@karimsa/mdxserve 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,166 @@
1
+ import { Extension, type Range } from "@tiptap/core";
2
+ import { Suggestion, type SuggestionProps } from "@tiptap/suggestion";
3
+ import { PluginKey } from "@tiptap/pm/state";
4
+ import { insertSlashBlock, matchingBlocks, type SlashBlock } from "./blocks";
5
+
6
+ export function blockSlash(
7
+ enabledDiagram: () => boolean,
8
+ onOpenDiagram: (range: Range) => void,
9
+ onOpenImage: (range: Range) => void,
10
+ onOpenLink?: (range: Range) => void,
11
+ ) {
12
+ return Extension.create({
13
+ name: "blockSlash",
14
+ addProseMirrorPlugins() {
15
+ const editor = this.editor;
16
+ return [
17
+ Suggestion<SlashBlock>({
18
+ editor,
19
+ pluginKey: new PluginKey("blockSlash"),
20
+ char: "/",
21
+ allowSpaces: true,
22
+ startOfLine: true,
23
+ allow: ({ editor: activeEditor, state, range }) =>
24
+ activeEditor.isEditable &&
25
+ state.selection.empty &&
26
+ !state.selection.$from.marks().some((mark) => mark.type.name === "code") &&
27
+ state.doc.resolve(range.from).parent.type.name === "paragraph" &&
28
+ state.doc.resolve(range.from).parent.textContent ===
29
+ state.doc.textBetween(range.from, range.to),
30
+ items: ({ query }) => matchingBlocks(query),
31
+ command: ({ range, props: block }) => {
32
+ if (block.kind === "image") onOpenImage(range);
33
+ else if (block.id === "link" && onOpenLink) onOpenLink(range);
34
+ else if (block.kind === "diagram" && enabledDiagram()) onOpenDiagram(range);
35
+ else insertSlashBlock(editor, range, block);
36
+ },
37
+ render: () => {
38
+ let menu: HTMLDivElement | undefined;
39
+ let activeProps: SuggestionProps<SlashBlock> | undefined;
40
+ let selected = 0;
41
+ let scrollTarget: Element | null = null;
42
+ const position = () => {
43
+ if (!menu || !activeProps) return;
44
+ const rect = activeProps.clientRect?.();
45
+ if (!rect) return;
46
+ const margin = 8;
47
+ const width = menu.getBoundingClientRect().width || 320;
48
+ const height = menu.getBoundingClientRect().height;
49
+ menu.style.left = `${Math.max(margin, Math.min(rect.left, window.innerWidth - width - margin))}px`;
50
+ const below = window.innerHeight - rect.bottom - margin;
51
+ const above = rect.top - margin;
52
+ menu.style.top = `${below >= height || below >= above ? Math.min(rect.bottom + 6, window.innerHeight - height - margin) : Math.max(margin, rect.top - height - 6)}px`;
53
+ };
54
+ const destroy = () => {
55
+ window.removeEventListener("resize", position);
56
+ window.removeEventListener("scroll", position, true);
57
+ scrollTarget?.removeEventListener("scroll", position);
58
+ scrollTarget = null;
59
+ menu?.remove();
60
+ menu = undefined;
61
+ activeProps = undefined;
62
+ };
63
+ const choose = (index: number) => {
64
+ const block = activeProps?.items[index];
65
+ if (!block || !activeProps) return;
66
+ activeProps.command(block);
67
+ destroy();
68
+ };
69
+ const draw = () => {
70
+ if (!menu || !activeProps) return;
71
+ menu.replaceChildren();
72
+ const blocks = activeProps.items;
73
+ if (selected >= blocks.length) selected = 0;
74
+ menu.hidden = blocks.length === 0;
75
+ if (blocks.length === 0) return;
76
+ let group = "";
77
+ blocks.forEach((block, index) => {
78
+ if (group !== block.group) {
79
+ group = block.group;
80
+ const heading = document.createElement("div");
81
+ heading.className = "block-slash-group";
82
+ heading.textContent = group;
83
+ menu?.append(heading);
84
+ }
85
+ const option = document.createElement("button");
86
+ option.type = "button";
87
+ option.className = "block-slash-option";
88
+ option.id = `block-slash-${block.id}`;
89
+ option.setAttribute("role", "option");
90
+ option.setAttribute("aria-selected", String(index === selected));
91
+ const title = document.createElement("strong");
92
+ title.textContent = block.label;
93
+ const description = document.createElement("small");
94
+ description.textContent = block.description;
95
+ option.append(title, description);
96
+ option.onmouseenter = () => {
97
+ selected = index;
98
+ updateSelection();
99
+ };
100
+ option.onmousedown = (event) => {
101
+ event.preventDefault();
102
+ choose(index);
103
+ };
104
+ menu?.append(option);
105
+ });
106
+ position();
107
+ };
108
+ const updateSelection = () => {
109
+ menu
110
+ ?.querySelectorAll<HTMLButtonElement>('[role="option"]')
111
+ .forEach((option, index) => {
112
+ option.setAttribute("aria-selected", String(index === selected));
113
+ if (index === selected) option.scrollIntoView?.({ block: "nearest" });
114
+ });
115
+ };
116
+ return {
117
+ onStart(props) {
118
+ activeProps = props;
119
+ selected = 0;
120
+ menu = document.createElement("div");
121
+ menu.className = "block-slash-menu";
122
+ menu.setAttribute("role", "listbox");
123
+ menu.setAttribute("aria-label", "Insert block");
124
+ document.body.append(menu);
125
+ window.addEventListener("resize", position);
126
+ window.addEventListener("scroll", position, true);
127
+ scrollTarget = editor.view.dom.closest("[data-editing]");
128
+ scrollTarget?.addEventListener("scroll", position);
129
+ draw();
130
+ },
131
+ onUpdate(props) {
132
+ activeProps = props;
133
+ selected = 0;
134
+ draw();
135
+ },
136
+ onKeyDown({ event }) {
137
+ if (event.key === "Escape") {
138
+ event.preventDefault();
139
+ event.stopPropagation();
140
+ destroy();
141
+ return true;
142
+ }
143
+ if (
144
+ !activeProps?.items.length ||
145
+ !["ArrowDown", "ArrowUp", "Enter"].includes(event.key)
146
+ )
147
+ return false;
148
+ event.preventDefault();
149
+ event.stopPropagation();
150
+ if (event.key === "Enter") choose(selected);
151
+ else {
152
+ selected =
153
+ (selected + (event.key === "ArrowDown" ? 1 : -1) + activeProps.items.length) %
154
+ activeProps.items.length;
155
+ updateSelection();
156
+ }
157
+ return true;
158
+ },
159
+ onExit: destroy,
160
+ };
161
+ },
162
+ }),
163
+ ];
164
+ },
165
+ });
166
+ }
@@ -0,0 +1,32 @@
1
+ import type { DocumentMetadata } from "../src/docs/metadata";
2
+
3
+ const marker = "data-mdxserve-metadata";
4
+
5
+ /** Replace only metadata owned by mdxserve; keep the shell's single title element. */
6
+ export function applyHeadMetadata(title: string, metadata?: DocumentMetadata): void {
7
+ document.title = metadata?.title ?? title;
8
+ for (const element of document.head.querySelectorAll(`[${marker}]`)) element.remove();
9
+ if (!metadata) return;
10
+
11
+ if (metadata.description !== undefined) {
12
+ const description = document.createElement("meta");
13
+ description.name = "description";
14
+ description.content = metadata.description;
15
+ description.setAttribute(marker, "");
16
+ document.head.append(description);
17
+ }
18
+ if (metadata.canonical !== undefined) {
19
+ const canonical = document.createElement("link");
20
+ canonical.rel = "canonical";
21
+ canonical.href = metadata.canonical;
22
+ canonical.setAttribute(marker, "");
23
+ document.head.append(canonical);
24
+ }
25
+ for (const item of metadata.openGraph) {
26
+ const graph = document.createElement("meta");
27
+ graph.setAttribute("property", item.property);
28
+ graph.content = item.content;
29
+ graph.setAttribute(marker, "");
30
+ document.head.append(graph);
31
+ }
32
+ }
package/client/router.ts CHANGED
@@ -5,6 +5,7 @@ import type { inferRouterOutputs } from "@trpc/server";
5
5
  import { queryClient, trpc } from "./api";
6
6
  // Type-only: see the comment in client/api.ts — src/ is not served by Vite.
7
7
  import type { AppRouter } from "../src/api/router";
8
+ import type { DocumentMetadata } from "../src/docs/metadata";
8
9
 
9
10
  type RouterOutputs = inferRouterOutputs<AppRouter>;
10
11
  type DocTreeOutput = RouterOutputs["getDocTree"];
@@ -23,7 +24,14 @@ export interface RootInfo {
23
24
  export type Route =
24
25
  | { kind: "home"; roots: RootInfo[] }
25
26
  | { kind: "listing"; path: string; rootName: string; rootDir: string; entries: ListingEntry[] }
26
- | { kind: "doc"; path: string; rootName: string; rootDir: string; mtime?: number }
27
+ | {
28
+ kind: "doc";
29
+ path: string;
30
+ rootName: string;
31
+ rootDir: string;
32
+ mtime?: number;
33
+ metadata?: DocumentMetadata;
34
+ }
27
35
  | { kind: "notfound"; path: string; rootName?: string; rootDir?: string };
28
36
 
29
37
  // Derived from the router's own output schema (src/listing/controller.ts's
@@ -39,31 +47,40 @@ export interface RootTree extends RootInfo {
39
47
  // The doc-module cache lives in client/doc-module-cache.ts (so an exported
40
48
  // file can use it without this module's tRPC graph); re-exported here for the
41
49
  // live viewer's callers.
42
- import { docModuleCache, type DocModuleState } from "./doc-module-cache";
50
+ import { docModuleCache, docModuleUrl, type DocModuleState } from "./doc-module-cache";
43
51
  import { decodeRoutePath } from "./route-path";
44
52
  export { docModuleCache, type DocModuleState };
45
53
  const docModulePromises = new Map<string, Promise<void>>();
54
+ const docModuleGenerations = new Map<string, number>();
46
55
 
47
- function ensureDocModule(path: string): Promise<void> {
48
- if (docModuleCache.has(path)) return Promise.resolve();
56
+ function ensureDocModule(path: string, refresh = false): Promise<void> {
57
+ if (!refresh && docModuleCache.has(path)) return Promise.resolve();
49
58
  const pending = docModulePromises.get(path);
50
- if (pending) return pending;
51
-
52
- // Vite serves absolute filesystem paths through its /@fs/ scheme.
53
- const promise = import(/* @vite-ignore */ "/@fs" + path)
54
- .then((mod: { default?: ComponentType }) => {
59
+ if (pending && !refresh) return pending;
60
+ const generation = (docModuleGenerations.get(path) ?? 0) + 1;
61
+ docModuleGenerations.set(path, generation);
62
+
63
+ const moduleUrl = docModuleUrl(path, refresh ? `${Date.now()}-${generation}` : undefined);
64
+ const promise = import(/* @vite-ignore */ moduleUrl)
65
+ .then((mod: { default?: ComponentType; __mdxserveMetadata?: DocumentMetadata }) => {
66
+ if (docModuleGenerations.get(path) !== generation) return;
55
67
  if (!mod.default) {
56
68
  docModuleCache.set(path, { status: "error", message: `${path} has no default export.` });
57
69
  } else {
58
- docModuleCache.set(path, { status: "ok", Component: mod.default });
70
+ docModuleCache.set(path, {
71
+ status: "ok",
72
+ Component: mod.default,
73
+ metadata: mod.__mdxserveMetadata ?? { openGraph: [] },
74
+ });
59
75
  }
60
76
  })
61
77
  .catch((error: unknown) => {
78
+ if (docModuleGenerations.get(path) !== generation) return;
62
79
  const message = error instanceof Error ? (error.stack ?? error.message) : String(error);
63
80
  docModuleCache.set(path, { status: "error", message });
64
81
  })
65
82
  .finally(() => {
66
- docModulePromises.delete(path);
83
+ if (docModulePromises.get(path) === promise) docModulePromises.delete(path);
67
84
  });
68
85
 
69
86
  docModulePromises.set(path, promise);
@@ -222,7 +239,7 @@ export function useFolderListing(folder: string): FolderListing {
222
239
  return { entries: data?.entries ?? null, error: isError && !data, notFound };
223
240
  }
224
241
 
225
- function titleFor(route: Route): string {
242
+ export function titleFor(route: Route): string {
226
243
  if (route.kind === "home") return "mdxserve";
227
244
  if (route.kind === "listing") return `${route.rootName}${route.path.slice(route.rootDir.length)}`;
228
245
  if (route.kind === "doc") {
@@ -306,7 +323,6 @@ export function useRouter(initialRoute: Route) {
306
323
  // "/" resolves to that root's listing (mirroring the server's 302),
307
324
  // and the address bar should say so.
308
325
  history.pushState({}, "", next.kind === "home" ? "/" : next.path);
309
- document.title = titleFor(next);
310
326
  setRoute(next);
311
327
  });
312
328
  },
@@ -333,7 +349,6 @@ export function useRouter(initialRoute: Route) {
333
349
  }, []);
334
350
 
335
351
  useEffect(() => {
336
- document.title = titleFor(initialRoute);
337
352
  // The server embeds the initial listing's entries straight into the page,
338
353
  // but useFolderListing consumers still need them in the shared cache.
339
354
  if (initialRoute.kind === "listing") {
@@ -351,7 +366,6 @@ export function useRouter(initialRoute: Route) {
351
366
  function onPopState() {
352
367
  loadRoute(location.pathname).then((next) => {
353
368
  if (!next) return;
354
- document.title = titleFor(next);
355
369
  setRoute(next);
356
370
  });
357
371
  }
@@ -362,6 +376,25 @@ export function useRouter(initialRoute: Route) {
362
376
  return () => window.removeEventListener("popstate", onPopState);
363
377
  }, [loadRoute]);
364
378
 
379
+ // The file watcher names the changed source even when Vite attributes its
380
+ // HMR update to an importer. Re-import with a new URL so metadata removals
381
+ // replace the cached module as well as changes to the visible document.
382
+ useEffect(() => {
383
+ if (!import.meta.hot) return;
384
+ const handleDocChanged = (data: { files?: Array<{ path: string }> }) => {
385
+ for (const file of data?.files ?? []) {
386
+ if (!docModuleCache.has(file.path)) continue;
387
+ void ensureDocModule(file.path, true).then(() => {
388
+ setRoute((current) =>
389
+ current.kind === "doc" && current.path === file.path ? { ...current } : current,
390
+ );
391
+ });
392
+ }
393
+ };
394
+ import.meta.hot.on("mdxserve:doc-changed", handleDocChanged);
395
+ return () => import.meta.hot?.off?.("mdxserve:doc-changed", handleDocChanged);
396
+ }, []);
397
+
365
398
  useEffect(() => {
366
399
  function onClick(event: MouseEvent) {
367
400
  if (event.defaultPrevented || event.button !== 0) return;
@@ -448,7 +481,6 @@ export function useRouter(initialRoute: Route) {
448
481
  roots: remaining.map((info) => ({ name: info.name, dir: info.dir })),
449
482
  };
450
483
  history.pushState({}, "", "/");
451
- document.title = titleFor(homeRoute);
452
484
  setRoute(homeRoute);
453
485
  }
454
486
  window.addEventListener("mdxserve:roots-changed", onRootsChanged);
@@ -5,6 +5,8 @@ import type { ComponentType } from "react";
5
5
  import { mdxComponentsBase } from "./mdx-components-base";
6
6
  import { docModuleCache } from "./doc-module-cache";
7
7
  import { StandaloneShell } from "./shell/StandaloneShell";
8
+ import { applyHeadMetadata } from "./head-metadata";
9
+ import type { DocumentMetadata } from "../src/docs/metadata";
8
10
 
9
11
  /**
10
12
  * What `mdxserve export` embeds as `#__mdxserve_route` JSON, read back by
@@ -16,6 +18,7 @@ export interface StandaloneMeta {
16
18
  path: string;
17
19
  label: string;
18
20
  mtime?: number;
21
+ metadata?: DocumentMetadata;
19
22
  }
20
23
 
21
24
  /** Parses the `#__mdxserve_route` script tag the same way entry.tsx does. */
@@ -35,12 +38,18 @@ export function readMeta(): StandaloneMeta {
35
38
  * export names and this signature stable, since that generated import is not
36
39
  * type-checked against this file.
37
40
  */
38
- export function mount(Doc: ComponentType, meta: StandaloneMeta): void {
41
+ export function mount(
42
+ Doc: ComponentType,
43
+ meta: StandaloneMeta,
44
+ moduleMetadata?: DocumentMetadata,
45
+ ): void {
39
46
  const rootEl = document.getElementById("root");
40
47
  if (!rootEl) return;
41
48
  // DocView reads the module from the router's cache; seed it with the doc
42
49
  // that was compiled into this file so it renders synchronously.
43
- docModuleCache.set(meta.path, { status: "ok", Component: Doc });
50
+ const metadata = moduleMetadata ?? meta.metadata ?? { openGraph: [] };
51
+ docModuleCache.set(meta.path, { status: "ok", Component: Doc, metadata });
52
+ applyHeadMetadata(meta.label, metadata);
44
53
  createRoot(rootEl).render(
45
54
  <MotionConfig reducedMotion="user">
46
55
  <MDXProvider components={mdxComponentsBase}>