@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.
package/README.md CHANGED
@@ -149,6 +149,31 @@ flowchart LR
149
149
 
150
150
  ![Mermaid diagrams rendered in the dark theme](docs/screenshots/diagrams-dark.jpg)
151
151
 
152
+ ### Page metadata
153
+
154
+ Add YAML frontmatter to set a page title, description, canonical URL, and Open Graph sharing tags. Metadata appears in the initial HTML response and in HTML exports, and updates as you navigate between documents. `.md` and `.mdx` use the same fields.
155
+
156
+ ```yaml
157
+ ---
158
+ title: My guide
159
+ description: How to get started.
160
+ canonical: https://docs.example.com/guide
161
+ openGraph:
162
+ - property: og:title
163
+ content: My guide
164
+ - property: og:type
165
+ content: article
166
+ - property: og:url
167
+ content: https://docs.example.com/guide
168
+ - property: og:image
169
+ content: https://docs.example.com/guide.png
170
+ - property: og:image:alt
171
+ content: A diagram from the guide
172
+ ---
173
+ ```
174
+
175
+ Use absolute public URLs for canonical links and sharing images. Open Graph values are explicit, so the sharing title can differ from the browser title. The list preserves repeated images and their attributes. See [metadata rules and validation](docs/advanced.md#page-metadata).
176
+
152
177
  ### Builtin components
153
178
 
154
179
  A small set of components is available in every file, `.md` included, with no import:
package/client/App.tsx CHANGED
@@ -1,7 +1,21 @@
1
+ import { useLayoutEffect } from "react";
2
+ import { docModuleCache } from "./doc-module-cache";
3
+ import { applyHeadMetadata } from "./head-metadata";
1
4
  import { AppShell } from "./shell/AppShell";
2
- import { useRouter, type Route } from "./router";
5
+ import { titleFor, useRouter, type Route } from "./router";
3
6
 
4
7
  export function App({ initialRoute }: { initialRoute: Route }) {
5
8
  const { route, navigate } = useRouter(initialRoute);
9
+ useLayoutEffect(() => {
10
+ const cached = route.kind === "doc" ? docModuleCache.get(route.path) : undefined;
11
+ applyHeadMetadata(
12
+ titleFor(route),
13
+ route.kind === "doc"
14
+ ? cached?.status === "ok"
15
+ ? cached.metadata
16
+ : route.metadata
17
+ : undefined,
18
+ );
19
+ }, [route]);
6
20
  return <AppShell route={route} navigate={navigate} />;
7
21
  }
@@ -46,13 +46,15 @@ export interface MdSectionProps {
46
46
  /** 1-based, inclusive source line numbers, as strings. */
47
47
  startLine: string;
48
48
  endLine: string;
49
+ /** Raw JSX renders nested diagrams whose source cannot be edited as a Markdown fence. */
50
+ rawJsx?: string;
49
51
  children: ReactNode;
50
52
  }
51
53
 
52
54
  /**
53
55
  * MDXProvider registration (see client/mdx-components.ts) for the synthetic
54
56
  * `<MdSection>` element the server's remark-sections compiler plugin wraps
55
- * around every maximal run of pure-markdown top-level nodes. In read mode
57
+ * around editable top-level Markdown and JSX blocks. In read mode
56
58
  * it's invisible — same children, same DOM — until hovered, when a pencil
57
59
  * appears to swap it into an inline Tiptap editor seeded from the raw file.
58
60
  *
@@ -65,7 +67,7 @@ export interface MdSectionProps {
65
67
  * now-stale line numbers; keying on the range forces a clean remount back to
66
68
  * read mode instead.
67
69
  */
68
- export function MdSection({ index, startLine, endLine, children }: MdSectionProps) {
70
+ export function MdSection({ index, startLine, endLine, rawJsx, children }: MdSectionProps) {
69
71
  const ctxPath = useContext(DocContext)?.path;
70
72
  // MdSection also renders inside the SSR worker (client/ssr-entry.tsx, used
71
73
  // by the `mdxserve validate` render check via renderToString), which has no
@@ -81,6 +83,7 @@ export function MdSection({ index, startLine, endLine, children }: MdSectionProp
81
83
  index={index}
82
84
  startLine={Number(startLine)}
83
85
  endLine={Number(endLine)}
86
+ rawJsx={rawJsx === "true"}
84
87
  >
85
88
  {children}
86
89
  </Section>
@@ -92,12 +95,14 @@ function Section({
92
95
  index,
93
96
  startLine,
94
97
  endLine,
98
+ rawJsx,
95
99
  children,
96
100
  }: {
97
101
  path: string;
98
102
  index: string;
99
103
  startLine: number;
100
104
  endLine: number;
105
+ rawJsx: boolean;
101
106
  children: ReactNode;
102
107
  }) {
103
108
  const [mode, setMode] = useState<"read" | "loading" | "edit" | "diagram">("read");
@@ -221,7 +226,7 @@ function Section({
221
226
  return (
222
227
  <DiagramEditContext.Provider
223
228
  value={
224
- shellInfo.permissions !== "restricted" && mode === "read"
229
+ shellInfo.permissions !== "restricted" && mode === "read" && !rawJsx
225
230
  ? (target) => void startEdit(target)
226
231
  : null
227
232
  }
@@ -5,7 +5,10 @@ import {
5
5
  type DiagramEditTarget,
6
6
  } from "./diagrams/edit-block";
7
7
  import type { ExistingDiagram } from "./diagrams/edit-context";
8
- import { mermaidSlash } from "./diagrams/slash";
8
+ import { blockSlash } from "./editor/slash";
9
+ import { MdxBlock } from "./editor/mdx-block";
10
+ import { ImageDialog } from "./editor/ImageDialog";
11
+ import { LinkDialog } from "./editor/LinkDialog";
9
12
  import { MermaidDialog } from "./diagrams/Dialog";
10
13
  import type { Range } from "@tiptap/core";
11
14
  import {
@@ -113,6 +116,8 @@ export default function MdSectionEditor({
113
116
  const [editTarget, setEditTarget] = useState<DiagramEditTarget | null>(null);
114
117
  const openedDiagram = useRef(false);
115
118
  const [diagramRange, setDiagramRange] = useState<Range | null>(null);
119
+ const [imageRange, setImageRange] = useState<Range | null>(null);
120
+ const [linkRange, setLinkRange] = useState<Range | null>(null);
116
121
  const openDiagram = useRef<(range: Range) => void>(() => {});
117
122
  openDiagram.current = setDiagramRange;
118
123
  useEffect(() => {
@@ -152,10 +157,13 @@ export default function MdSectionEditor({
152
157
  const editor = useEditor({
153
158
  extensions: [
154
159
  mermaidEditButtons(() => diagramEnabled.current, setEditTarget),
155
- mermaidSlash(
160
+ blockSlash(
156
161
  () => diagramEnabled.current,
157
162
  (range) => openDiagram.current(range),
163
+ setImageRange,
164
+ setLinkRange,
158
165
  ),
166
+ MdxBlock,
159
167
  StarterKit.configure({
160
168
  heading: { levels: [1, 2, 3, 4, 5, 6] },
161
169
  link: { openOnClick: false },
@@ -282,7 +290,7 @@ export default function MdSectionEditor({
282
290
  }
283
291
 
284
292
  function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
285
- if (diagramRange || editTarget) return;
293
+ if (diagramRange || editTarget || imageRange || linkRange) return;
286
294
  if ((event.metaKey || event.ctrlKey) && event.key === "s") {
287
295
  event.preventDefault();
288
296
  void save();
@@ -303,6 +311,54 @@ export default function MdSectionEditor({
303
311
  return (
304
312
  <div className="mdx-section" data-editing onClick={onClick} onKeyDown={onKeyDown}>
305
313
  <EditorContent editor={editor} />
314
+ {linkRange && (
315
+ <LinkDialog
316
+ onClose={() => {
317
+ setLinkRange(null);
318
+ editor.commands.focus();
319
+ }}
320
+ onInsert={({ href, text }) => {
321
+ if (linkRange.to > editor.state.doc.content.size) return;
322
+ editor
323
+ .chain()
324
+ .focus()
325
+ .insertContentAt(linkRange, {
326
+ type: "text",
327
+ text,
328
+ marks: [{ type: "link", attrs: { href } }],
329
+ })
330
+ .run();
331
+ setLinkRange(null);
332
+ }}
333
+ />
334
+ )}
335
+ {imageRange && (
336
+ <ImageDialog
337
+ onClose={() => {
338
+ setImageRange(null);
339
+ editor.commands.focus();
340
+ }}
341
+ onInsert={(attrs) => {
342
+ if (imageRange.to > editor.state.doc.content.size) return;
343
+ const position = editor.state.doc.resolve(imageRange.from);
344
+ if (
345
+ position.parent.type.name !== "paragraph" ||
346
+ position.parent.textContent !==
347
+ editor.state.doc.textBetween(imageRange.from, imageRange.to)
348
+ )
349
+ return;
350
+ editor
351
+ .chain()
352
+ .focus()
353
+ .insertContentAt({ from: position.before(), to: position.after() }, [
354
+ { type: "image", attrs },
355
+ { type: "paragraph" },
356
+ ])
357
+ .run();
358
+ setImageRange(null);
359
+ }}
360
+ />
361
+ )}
306
362
  <AnimatePresence>
307
363
  {(diagramRange || editTarget) && (
308
364
  <MermaidDialog
@@ -365,6 +421,9 @@ export default function MdSectionEditor({
365
421
  initial="initial"
366
422
  animate={entered ? "animate" : "initial"}
367
423
  >
424
+ <motion.span variants={hint} className="flex items-center gap-1.5">
425
+ <Kbd>/</Kbd> to add a block
426
+ </motion.span>
368
427
  <motion.span variants={hint} className="flex items-center gap-1.5">
369
428
  <Kbd>{isApplePlatform() ? "⌘S" : "Ctrl S"}</Kbd> to save
370
429
  </motion.span>
package/client/app.css CHANGED
@@ -35,6 +35,8 @@
35
35
  @import "./design/base/editor.css";
36
36
  @import "./ui/modal.css";
37
37
  @import "./Settings.css";
38
+ @import "./editor/image-dialog.css";
39
+ @import "./editor/component-fields.css";
38
40
  @import "./diagrams/style.css";
39
41
 
40
42
  /* `:root[...]` (not bare `[data-theme]`) because rehype-pretty-code stamps
@@ -149,3 +149,62 @@
149
149
  flex: 1 1 auto;
150
150
  min-width: 0;
151
151
  }
152
+
153
+ /* The slash picker stays outside the section frame so it can cross section
154
+ and scroll boundaries without being clipped. Focus remains in the editor. */
155
+ .block-slash-menu {
156
+ position: fixed;
157
+ z-index: 100;
158
+ width: min(320px, calc(100vw - 16px));
159
+ max-height: min(420px, calc(100dvh - 16px));
160
+ overflow-y: auto;
161
+ padding: 6px;
162
+ border: 1px solid var(--border-default);
163
+ border-radius: var(--radius-md);
164
+ background: var(--surface-raised);
165
+ box-shadow: 0 12px 32px #0003;
166
+ }
167
+
168
+ .block-slash-menu[hidden] {
169
+ display: none;
170
+ }
171
+
172
+ .block-slash-group {
173
+ padding: 8px 10px 4px;
174
+ color: var(--text-subtle);
175
+ font-size: var(--size-xs);
176
+ font-weight: 700;
177
+ letter-spacing: 0.04em;
178
+ text-transform: uppercase;
179
+ }
180
+
181
+ .block-slash-option {
182
+ display: flex;
183
+ width: 100%;
184
+ flex-direction: column;
185
+ gap: 2px;
186
+ padding: 8px 10px;
187
+ border-radius: var(--radius-sm);
188
+ background: transparent;
189
+ color: var(--text-body);
190
+ text-align: left;
191
+ cursor: pointer;
192
+ }
193
+
194
+ .block-slash-option strong {
195
+ font-size: var(--size-sm);
196
+ font-weight: 600;
197
+ }
198
+ .block-slash-option small {
199
+ color: var(--text-subtle);
200
+ font-size: var(--size-xs);
201
+ }
202
+ .block-slash-option[aria-selected="true"],
203
+ .block-slash-option:hover {
204
+ background: var(--surface-accent-soft);
205
+ color: var(--text-accent);
206
+ }
207
+ .block-slash-option[aria-selected="true"] small,
208
+ .block-slash-option:hover small {
209
+ color: var(--text-accent);
210
+ }
@@ -476,25 +476,6 @@
476
476
  flex-wrap: wrap;
477
477
  }
478
478
  }
479
- .diagram-slash-menu {
480
- position: fixed;
481
- z-index: 100;
482
- background: var(--surface-raised);
483
- border: 1px solid var(--border-default);
484
- padding: 6px;
485
- box-shadow: 0 6px 20px #0002;
486
- border-radius: 8px;
487
- width: 250px;
488
- }
489
- .diagram-slash-menu button {
490
- padding: 12px;
491
- text-align: left;
492
- width: 100%;
493
- background: var(--surface-accent-soft);
494
- color: var(--text-accent);
495
- border-radius: 5px;
496
- }
497
-
498
479
  .diagram-statusbar[data-error="true"] > :first-child {
499
480
  color: var(--status-danger-fg);
500
481
  }
@@ -1,7 +1,9 @@
1
1
  import type { ComponentType } from "react";
2
+ import type { DocumentMetadata } from "../src/docs/metadata";
2
3
 
3
4
  export type DocModuleState =
4
- { status: "ok"; Component: ComponentType } | { status: "error"; message: string };
5
+ | { status: "ok"; Component: ComponentType; metadata: DocumentMetadata }
6
+ | { status: "error"; message: string };
5
7
 
6
8
  /**
7
9
  * Modules imported for doc routes, keyed by the doc's path (its absolute path
@@ -15,3 +17,9 @@ export type DocModuleState =
15
17
  * router's tRPC/react-query graph into an exported file.
16
18
  */
17
19
  export const docModuleCache = new Map<string, DocModuleState>();
20
+
21
+ /** A Vite /@fs URL whose path remains intact even for URL punctuation in filenames. */
22
+ export function docModuleUrl(path: string, refreshToken?: string): string {
23
+ const encodedPath = path.split("/").map(encodeURIComponent).join("/");
24
+ return `/@fs${encodedPath}${refreshToken === undefined ? "" : `?mdxserve_refresh=${refreshToken}`}`;
25
+ }
@@ -0,0 +1,69 @@
1
+ import { useEffect, useRef, useState } from "react";
2
+
3
+ export function ImageDialog({
4
+ onClose,
5
+ onInsert,
6
+ }: {
7
+ onClose: () => void;
8
+ onInsert: (image: { src: string; alt: string; title: string }) => void;
9
+ }) {
10
+ const dialog = useRef<HTMLDialogElement>(null);
11
+ const [src, setSrc] = useState("");
12
+ const [alt, setAlt] = useState("");
13
+ const [title, setTitle] = useState("");
14
+ useEffect(() => {
15
+ dialog.current?.showModal();
16
+ }, []);
17
+ return (
18
+ <dialog
19
+ ref={dialog}
20
+ className="editor-image-dialog"
21
+ aria-labelledby="editor-image-title"
22
+ onCancel={(event) => {
23
+ event.preventDefault();
24
+ event.stopPropagation();
25
+ onClose();
26
+ }}
27
+ onKeyDown={(event) => event.stopPropagation()}
28
+ >
29
+ <form
30
+ onSubmit={(event) => {
31
+ event.preventDefault();
32
+ if (src.trim()) onInsert({ src: src.trim(), alt, title });
33
+ }}
34
+ >
35
+ <h2 id="editor-image-title">Insert image</h2>
36
+ <label>
37
+ Image URL or path
38
+ <input
39
+ autoFocus
40
+ required
41
+ value={src}
42
+ onChange={(event) => setSrc(event.target.value)}
43
+ placeholder="https://… or ./assets/image.png"
44
+ />
45
+ </label>
46
+ <label>
47
+ Alternative text
48
+ <input
49
+ value={alt}
50
+ onChange={(event) => setAlt(event.target.value)}
51
+ placeholder="Describe the image"
52
+ />
53
+ </label>
54
+ <label>
55
+ Title (optional)
56
+ <input value={title} onChange={(event) => setTitle(event.target.value)} />
57
+ </label>
58
+ <footer>
59
+ <button type="button" onClick={onClose}>
60
+ Cancel
61
+ </button>
62
+ <button type="submit" disabled={!src.trim()}>
63
+ Insert image
64
+ </button>
65
+ </footer>
66
+ </form>
67
+ </dialog>
68
+ );
69
+ }
@@ -0,0 +1,60 @@
1
+ import { useEffect, useRef, useState } from "react";
2
+
3
+ export function LinkDialog({
4
+ onClose,
5
+ onInsert,
6
+ }: {
7
+ onClose: () => void;
8
+ onInsert: (link: { href: string; text: string }) => void;
9
+ }) {
10
+ const dialog = useRef<HTMLDialogElement>(null);
11
+ const [href, setHref] = useState("");
12
+ const [text, setText] = useState("");
13
+ useEffect(() => {
14
+ dialog.current?.showModal();
15
+ }, []);
16
+ return (
17
+ <dialog
18
+ ref={dialog}
19
+ className="editor-image-dialog"
20
+ aria-labelledby="editor-link-title"
21
+ onCancel={(event) => {
22
+ event.preventDefault();
23
+ event.stopPropagation();
24
+ onClose();
25
+ }}
26
+ onKeyDown={(event) => event.stopPropagation()}
27
+ >
28
+ <form
29
+ onSubmit={(event) => {
30
+ event.preventDefault();
31
+ if (href.trim()) onInsert({ href: href.trim(), text: text.trim() || href.trim() });
32
+ }}
33
+ >
34
+ <h2 id="editor-link-title">Insert link</h2>
35
+ <label>
36
+ URL or path
37
+ <input
38
+ autoFocus
39
+ required
40
+ value={href}
41
+ onChange={(event) => setHref(event.target.value)}
42
+ placeholder="https://… or ./page.md"
43
+ />
44
+ </label>
45
+ <label>
46
+ Link text
47
+ <input value={text} onChange={(event) => setText(event.target.value)} />
48
+ </label>
49
+ <footer>
50
+ <button type="button" onClick={onClose}>
51
+ Cancel
52
+ </button>
53
+ <button type="submit" disabled={!href.trim()}>
54
+ Insert link
55
+ </button>
56
+ </footer>
57
+ </form>
58
+ </dialog>
59
+ );
60
+ }