@conloca/mdx 0.1.14 → 0.1.16

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.
Files changed (44) hide show
  1. package/README.md +31 -9
  2. package/dist/blocks.d.ts +37 -0
  3. package/dist/blocks.d.ts.map +1 -0
  4. package/dist/blocks.js +51 -0
  5. package/dist/code-block-frame.d.ts +41 -0
  6. package/dist/code-block-frame.d.ts.map +1 -0
  7. package/dist/code-block-frame.js +186 -0
  8. package/dist/editor-core.d.ts +58 -0
  9. package/dist/editor-core.d.ts.map +1 -0
  10. package/dist/editor-core.js +181 -0
  11. package/dist/hooks/useMDXEvaluation.d.ts +28 -0
  12. package/dist/hooks/useMDXEvaluation.d.ts.map +1 -0
  13. package/dist/hooks/useMDXEvaluation.js +117 -0
  14. package/dist/index.d.mts +104 -50
  15. package/dist/index.d.mts.map +1 -1
  16. package/dist/index.d.ts +8 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +4 -0
  19. package/dist/index.mjs +440 -369
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/markdown-options.d.ts +3 -0
  22. package/dist/markdown-options.d.ts.map +1 -0
  23. package/dist/markdown-options.js +19 -0
  24. package/dist/mdx/compile.d.ts +3 -0
  25. package/dist/mdx/compile.d.ts.map +1 -0
  26. package/dist/mdx/compile.js +27 -0
  27. package/dist/mdx/evaluate.d.ts +44 -0
  28. package/dist/mdx/evaluate.d.ts.map +1 -0
  29. package/dist/mdx/evaluate.js +57 -0
  30. package/dist/mdx-editor.d.ts +7 -0
  31. package/dist/mdx-editor.d.ts.map +1 -0
  32. package/dist/mdx-editor.js +7 -0
  33. package/dist/node.d.mts +46 -74
  34. package/dist/node.d.mts.map +1 -1
  35. package/dist/node.d.ts +17 -0
  36. package/dist/node.d.ts.map +1 -0
  37. package/dist/node.js +16 -0
  38. package/dist/node.mjs +35 -116
  39. package/dist/node.mjs.map +1 -1
  40. package/dist/style.css +88 -0
  41. package/dist/types.d.ts +16 -0
  42. package/dist/types.d.ts.map +1 -0
  43. package/dist/types.js +1 -0
  44. package/package.json +54 -15
package/dist/index.mjs CHANGED
@@ -1,39 +1,416 @@
1
- import { evaluate } from "@mdx-js/mdx";
2
- import React, { useEffect, useState } from "react";
3
- import * as devRuntime from "react/jsx-dev-runtime";
1
+ import './style.css';
2
+ import { BlockTypeSelect, BoldItalicUnderlineToggles, ButtonWithTooltip, Cell, ChangeCodeMirrorLanguage, CodeMirrorEditor, ConditionalContents, CreateLink, DiffSourceToggleWrapper, GenericJsxEditor, HighlightToggle, InsertCodeBlock, InsertImage, InsertTable, InsertThematicBreak, ListsToggle, MDXEditor as MDXEditor$1, Separator, StrikeThroughSupSubToggles, UndoRedo, codeBlockPlugin, codeMirrorPlugin, diffSourcePlugin, headingsPlugin, imagePlugin, jsxPlugin, linkDialogPlugin, linkPlugin, listsPlugin, markdownShortcutPlugin, quotePlugin, tablePlugin, thematicBreakPlugin, toolbarPlugin, useCellValue, useCodeBlockEditorContext } from "@mdxeditor/editor";
3
+ import { Check, Copy, Maximize2, Minimize2 } from "lucide-react";
4
+ import React, { createElement, useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
4
5
  import * as runtime from "react/jsx-runtime";
5
- import { jsx, jsxs } from "react/jsx-runtime";
6
- import remarkFrontmatter from "remark-frontmatter";
7
- import remarkGfm from "remark-gfm";
8
- import remarkMdxFrontmatter from "remark-mdx-frontmatter";
9
- import { BlockTypeSelect, BoldItalicUnderlineToggles, CreateLink, DiffSourceToggleWrapper, InsertCodeBlock, InsertImage, InsertTable, InsertThematicBreak, ListsToggle, MDXEditor as MDXEditor$1, Separator, UndoRedo, codeBlockPlugin, codeMirrorPlugin, diffSourcePlugin, frontmatterPlugin, headingsPlugin, imagePlugin, jsxPlugin, linkDialogPlugin, linkPlugin, listsPlugin, markdownShortcutPlugin, quotePlugin, tablePlugin, thematicBreakPlugin, toolbarPlugin } from "@mdxeditor/editor";
6
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
10
7
  import "@mdxeditor/editor/style.css";
11
-
12
- //#region src/hooks/useMDXEvaluation.ts
13
- const compiledCache = /* @__PURE__ */ new Map();
8
+ import * as devRuntime from "react/jsx-dev-runtime";
9
+ //#region src/code-block-frame.tsx
14
10
  /**
15
- * Standalone function that creates MDX evaluation options.
16
- * Checks for development mode only once at startup to avoid repeated
17
- * environment checks during runtime.
11
+ * Frame chrome around the editor's fenced code blocks — header bar with
12
+ * filename, language tag, and a copy button. The outer wrapper picks up
13
+ * the host's code-block classes (published via `codeBlockWrapperInfo$`
14
+ * by the host-wrapper plugin in cms-spa), so the host's actual code-
15
+ * block CSS (Starlight's expressive-code, Tailwind's pre styling, etc.)
16
+ * reaches the editor's frame through the cascade — no shipped mirror.
18
17
  *
19
- * @returns Configuration object for MDX evaluation with appropriate JSX runtime
18
+ * Host-agnostic: no Shiki / Starlight / ExpressiveCode imports. Class
19
+ * names are discovered at runtime from the host's live HTML.
20
20
  */
21
- function createMDXEvaluationOptions() {
22
- const isDevelopment = process.env.NODE_ENV === "development";
21
+ /**
22
+ * Realm-published cell carrying the host's code-block wrapper chain,
23
+ * outermost first. For Starlight's expressive-code:
24
+ *
25
+ * [
26
+ * { tagName: 'div', className: 'expressive-code' },
27
+ * { tagName: 'figure', className: 'frame has-title not-content' },
28
+ * ]
29
+ *
30
+ * The cms-spa `hostWrapperPlugin` writes to this whenever the fetched
31
+ * wrapper info changes; the code-block frame reads from it to render
32
+ * each chain link as a nested element with the host's expected tag
33
+ * name. Same publish-pattern as the content-wrapper plugin in cms-spa.
34
+ *
35
+ * Null when the host has no code-block chrome (or the fetch is in
36
+ * flight). The frame then falls back to its base `.conloca-code-block`
37
+ * wrapper with no host inheritance — "looks plain but not broken."
38
+ */
39
+ const codeBlockWrapperInfo$ = Cell(null);
40
+ const TITLE_META_RE = /\btitle=(?:"([^"]*)"|'([^']*)'|(\S+))/;
41
+ const FILENAME_COMMENT_RE = /^\s*(?:\/\/|#|;|--|<!--|\/\*)\s*([\w.\-/@]+\.[\w.-]+)\s*(?:-->|\*\/)?\s*$/;
42
+ function parseMeta(meta) {
43
+ const match = meta.match(TITLE_META_RE);
44
+ if (!match) return {
45
+ title: "",
46
+ rest: meta.trim()
47
+ };
23
48
  return {
24
- ...isDevelopment ? devRuntime : runtime,
25
- development: isDevelopment,
26
- remarkPlugins: [
27
- remarkFrontmatter,
28
- remarkMdxFrontmatter,
29
- remarkGfm
30
- ]
49
+ title: match[1] ?? match[2] ?? match[3] ?? "",
50
+ rest: (meta.slice(0, match.index) + meta.slice(match.index + match[0].length)).replace(/\s+/g, " ").trim()
51
+ };
52
+ }
53
+ /** Reassemble a meta string with `title` set (or stripped when empty). */
54
+ function buildMeta(title, rest) {
55
+ const trimmedTitle = title.trim();
56
+ const titleFragment = trimmedTitle ? `title="${trimmedTitle.replace(/"/g, "\\\"")}"` : "";
57
+ if (titleFragment && rest) return `${titleFragment} ${rest}`;
58
+ return titleFragment || rest;
59
+ }
60
+ /**
61
+ * Detect a leading filename comment, the convention EC's frames plugin
62
+ * uses on the published page when no explicit `title=` is set. Returns
63
+ * the filename when line 1 of the code is a single-line comment ending
64
+ * in a dot-extension; empty string otherwise.
65
+ *
66
+ * Used to pre-fill the editor's filename input on legacy fences so
67
+ * authors see the same value the reader sees in the rendered tab. Pure
68
+ * read — the underlying code/comment is never touched.
69
+ */
70
+ function detectFilenameComment(code) {
71
+ const match = (code.split("\n", 1)[0] ?? "").match(FILENAME_COMMENT_RE);
72
+ return match ? match[1] ?? "" : "";
73
+ }
74
+ function CopyButton({ code }) {
75
+ const [copied, setCopied] = useState(false);
76
+ return /* @__PURE__ */ jsx("button", {
77
+ type: "button",
78
+ onClick: useCallback(() => {
79
+ navigator.clipboard.writeText(code).then(() => {
80
+ setCopied(true);
81
+ window.setTimeout(() => setCopied(false), 1200);
82
+ });
83
+ }, [code]),
84
+ className: "conloca-code-copy",
85
+ "aria-label": copied ? "Copied" : "Copy code",
86
+ title: copied ? "Copied" : "Copy code",
87
+ children: copied ? /* @__PURE__ */ jsx(Check, {
88
+ size: 14,
89
+ "aria-hidden": "true"
90
+ }) : /* @__PURE__ */ jsx(Copy, {
91
+ size: 14,
92
+ "aria-hidden": "true"
93
+ })
94
+ });
95
+ }
96
+ /**
97
+ * Editable filename slot. Rewrites the code block's meta string via
98
+ * `setMeta` from `useCodeBlockEditorContext` so authors can author the
99
+ * frame title (`\`\`\`ts title="src/foo.ts"`) directly from the editor —
100
+ * the meta string round-trips through MDXEditor's markdown serializer
101
+ * and ExpressiveCode picks it up as the frame header on the published
102
+ * page. Other meta fragments (ins/del/mark/wrap) are preserved.
103
+ *
104
+ * Legacy fences with a filename comment on line 1 (`// foo.ts`) — EC's
105
+ * pre-meta convention for tab titles — are detected and pre-filled in
106
+ * the input as a read-only display. Opening such a fence does NOT
107
+ * mutate the source. Editing the field is an explicit author intent:
108
+ * the new value is written as `title=` meta AND the original comment
109
+ * line is stripped, so the editor's input becomes the single source of
110
+ * truth without breaking the published render.
111
+ */
112
+ function FilenameInput({ meta, code }) {
113
+ const { setMeta, setCode } = useCodeBlockEditorContext();
114
+ const parsed = useMemo(() => parseMeta(meta), [meta]);
115
+ const detectedFromComment = useMemo(() => parsed.title ? "" : detectFilenameComment(code), [parsed.title, code]);
116
+ const displayed = parsed.title || detectedFromComment;
117
+ const [title, setTitle] = useState(displayed);
118
+ const [interacted, setInteracted] = useState(false);
119
+ useEffect(() => {
120
+ setTitle(displayed);
121
+ setInteracted(false);
122
+ }, [displayed]);
123
+ const commit = useCallback((next) => {
124
+ if (!interacted) return;
125
+ if (next === parsed.title) return;
126
+ setMeta(buildMeta(next, parsed.rest));
127
+ if (detectedFromComment) {
128
+ const lines = code.split("\n");
129
+ if (lines[0] && FILENAME_COMMENT_RE.test(lines[0])) setCode(lines.slice(1).join("\n").replace(/^\n+/, ""));
130
+ }
131
+ }, [
132
+ interacted,
133
+ parsed.title,
134
+ parsed.rest,
135
+ detectedFromComment,
136
+ code,
137
+ setMeta,
138
+ setCode
139
+ ]);
140
+ const onChange = (e) => {
141
+ setInteracted(true);
142
+ setTitle(e.target.value);
31
143
  };
144
+ const onBlur = () => commit(title);
145
+ return /* @__PURE__ */ jsx("input", {
146
+ type: "text",
147
+ className: "conloca-code-block__filename",
148
+ value: title,
149
+ placeholder: "filename",
150
+ spellCheck: false,
151
+ onChange,
152
+ onBlur,
153
+ "aria-label": "Code block filename"
154
+ });
155
+ }
156
+ function ConlocaCodeBlockEditor(props) {
157
+ const chain = useCellValue(codeBlockWrapperInfo$) ?? [];
158
+ const frameLink = chain.length > 0 ? chain[chain.length - 1] : null;
159
+ const outerLinks = frameLink ? chain.slice(0, -1) : [];
160
+ const frameInner = /* @__PURE__ */ jsxs(Fragment, { children: [
161
+ /* @__PURE__ */ jsx("figcaption", {
162
+ className: "conloca-code-block__header header",
163
+ children: /* @__PURE__ */ jsx("span", {
164
+ className: "title",
165
+ children: /* @__PURE__ */ jsx(FilenameInput, {
166
+ meta: props.meta,
167
+ code: props.code
168
+ })
169
+ })
170
+ }),
171
+ /* @__PURE__ */ jsx("pre", {
172
+ className: "conloca-code-block__pre",
173
+ children: /* @__PURE__ */ jsx(CodeMirrorEditor, { ...props })
174
+ }),
175
+ /* @__PURE__ */ jsx("div", {
176
+ className: "conloca-code-block__copy copy",
177
+ children: /* @__PURE__ */ jsx(CopyButton, { code: props.code })
178
+ })
179
+ ] });
180
+ const frame = frameLink ? createElement(frameLink.tagName, { className: `conloca-code-block ${frameLink.className}` }, frameInner) : /* @__PURE__ */ jsx("div", {
181
+ className: "conloca-code-block",
182
+ children: frameInner
183
+ });
184
+ return outerLinks.reduceRight((kids, link) => createElement(link.tagName, { className: link.className }, kids), frame);
185
+ }
186
+ /**
187
+ * Catch-all descriptor — `priority: 100`, `match: () => true` — registered
188
+ * via `codeBlockPlugin({ codeBlockEditorDescriptors: [conlocaCodeBlockDescriptor] })`.
189
+ * Wraps the upstream `CodeMirrorEditor` with the host-themed frame.
190
+ */
191
+ const conlocaCodeBlockDescriptor = {
192
+ priority: 100,
193
+ match: () => true,
194
+ Editor: ConlocaCodeBlockEditor
195
+ };
196
+ //#endregion
197
+ //#region src/markdown-options.ts
198
+ const TO_MARKDOWN_OPTIONS = {
199
+ bullet: "-",
200
+ rule: "-",
201
+ emphasis: "_",
202
+ strong: "*",
203
+ fence: "`",
204
+ listItemIndent: "one",
205
+ tightDefinitions: true
206
+ };
207
+ //#endregion
208
+ //#region src/editor-core.tsx
209
+ const FOCUS_MODE_STORAGE_KEY = "conloca.mdxeditor.focusMode";
210
+ const FOCUS_MODE_BODY_CLASS = "mdxeditor-focus-mode";
211
+ /**
212
+ * Toggle focus-mode by writing the class on `document.body`. Direct DOM
213
+ * mutation (vs. piping a boolean through React state into the editor's
214
+ * `className` prop) avoids re-rendering Lexical on every toggle — the
215
+ * editor's prop is the only entry point and changing it forces a parse
216
+ * round-trip. Persisted in localStorage so the preference survives reloads.
217
+ */
218
+ function readFocusMode() {
219
+ if (typeof document === "undefined") return false;
220
+ return document.body.classList.contains(FOCUS_MODE_BODY_CLASS);
221
+ }
222
+ function subscribeFocusMode(callback) {
223
+ if (typeof window === "undefined") return () => {};
224
+ const handler = () => callback();
225
+ window.addEventListener("conloca:focusModeChange", handler);
226
+ return () => window.removeEventListener("conloca:focusModeChange", handler);
227
+ }
228
+ function setFocusMode(next) {
229
+ if (typeof document === "undefined") return;
230
+ document.body.classList.toggle(FOCUS_MODE_BODY_CLASS, next);
231
+ try {
232
+ if (next) window.localStorage.setItem(FOCUS_MODE_STORAGE_KEY, "1");
233
+ else window.localStorage.removeItem(FOCUS_MODE_STORAGE_KEY);
234
+ } catch {}
235
+ window.dispatchEvent(new Event("conloca:focusModeChange"));
236
+ }
237
+ function FocusModeToggle() {
238
+ const focusMode = useSyncExternalStore(subscribeFocusMode, readFocusMode, () => false);
239
+ const onClick = useCallback(() => setFocusMode(!focusMode), [focusMode]);
240
+ return /* @__PURE__ */ jsx(ButtonWithTooltip, {
241
+ title: focusMode ? "Exit focus mode (wider column)" : "Enter focus mode (narrow column)",
242
+ onClick,
243
+ children: /* @__PURE__ */ jsx(focusMode ? Minimize2 : Maximize2, {
244
+ size: 16,
245
+ "aria-hidden": true
246
+ })
247
+ });
248
+ }
249
+ const codeBlockLanguages = {
250
+ "": "Plain text",
251
+ text: "Plain Text",
252
+ js: "JavaScript",
253
+ jsx: "JavaScript (React)",
254
+ ts: "TypeScript",
255
+ tsx: "TypeScript (React)",
256
+ css: "CSS",
257
+ html: "HTML",
258
+ json: "JSON",
259
+ md: "Markdown",
260
+ mdx: "MDX",
261
+ bash: "Bash",
262
+ python: "Python"
263
+ };
264
+ /**
265
+ * Wildcard fallback so any unknown JSX tag round-trips through GenericJsxEditor
266
+ * instead of crashing the importer with "Parsing of the following markdown
267
+ * structure failed". Two entries because the upstream visitor dispatches by
268
+ * `kind` (block vs inline JSX) — without the inline one, an inline `<Badge>`
269
+ * mid-paragraph would be matched by the flow wildcard and lifted out of its
270
+ * paragraph in Lexical. Consumers passing typed descriptors win via the
271
+ * exact-name match in the visitor; the wildcard only handles the leftovers.
272
+ */
273
+ const wildcardJsxDescriptors = [{
274
+ name: "*",
275
+ kind: "flow",
276
+ props: [],
277
+ hasChildren: true,
278
+ Editor: GenericJsxEditor
279
+ }, {
280
+ name: "*",
281
+ kind: "text",
282
+ props: [],
283
+ hasChildren: true,
284
+ Editor: GenericJsxEditor
285
+ }];
286
+ function renderInsertImageButton(imageButtonRef) {
287
+ if (!imageButtonRef) return /* @__PURE__ */ jsx(InsertImage, {});
288
+ return React.createElement(InsertImage, { ref: imageButtonRef });
32
289
  }
33
- const mdxEvaluationOptions = createMDXEvaluationOptions();
290
+ /**
291
+ * Restore the persisted focus-mode preference on first import. Runs once at
292
+ * module load so the class is in place before any editor mounts — avoids a
293
+ * flash of wide column when the user previously selected focus mode.
294
+ */
295
+ if (typeof window !== "undefined") try {
296
+ if (window.localStorage.getItem(FOCUS_MODE_STORAGE_KEY) === "1") document.body.classList.add(FOCUS_MODE_BODY_CLASS);
297
+ } catch {}
298
+ const BaseMDXEditor = React.forwardRef(({ value, onChange, onSave, readOnly = false, imageDialog, disableImageSettingsButton = false, onImageShortcut, imageButtonRef, imageUploadHandler, jsxComponentDescriptors, extraPlugins, extraToolbarItems, className, placeholder, autoFocus }, ref) => {
299
+ useEffect(() => {
300
+ const handleKeyDown = (event) => {
301
+ if ((event.ctrlKey || event.metaKey) && event.key === "s") {
302
+ event.preventDefault();
303
+ onSave?.(value);
304
+ }
305
+ if ((event.ctrlKey || event.metaKey) && event.shiftKey && event.key.toLowerCase() === "i") {
306
+ if (!onImageShortcut) return;
307
+ event.preventDefault();
308
+ onImageShortcut();
309
+ }
310
+ };
311
+ document.addEventListener("keydown", handleKeyDown);
312
+ return () => document.removeEventListener("keydown", handleKeyDown);
313
+ }, [
314
+ onImageShortcut,
315
+ onSave,
316
+ value
317
+ ]);
318
+ return /* @__PURE__ */ jsx(MDXEditor$1, {
319
+ ref,
320
+ markdown: value,
321
+ toMarkdownOptions: TO_MARKDOWN_OPTIONS,
322
+ onChange,
323
+ onError: ({ error, source }) => {
324
+ console.error("[MDXEditor] parse error:", error, "\nsource:", source);
325
+ },
326
+ readOnly,
327
+ className,
328
+ placeholder,
329
+ autoFocus,
330
+ contentEditableClassName: "conloca-prose conloca-prose--editor",
331
+ plugins: [
332
+ headingsPlugin(),
333
+ listsPlugin(),
334
+ quotePlugin(),
335
+ linkPlugin(),
336
+ linkDialogPlugin(),
337
+ tablePlugin(),
338
+ thematicBreakPlugin(),
339
+ codeBlockPlugin({
340
+ defaultCodeBlockLanguage: "ts",
341
+ codeBlockEditorDescriptors: [conlocaCodeBlockDescriptor]
342
+ }),
343
+ codeMirrorPlugin({ codeBlockLanguages }),
344
+ diffSourcePlugin({ viewMode: "rich-text" }),
345
+ markdownShortcutPlugin(),
346
+ jsxPlugin({ jsxComponentDescriptors: [...jsxComponentDescriptors ?? [], ...wildcardJsxDescriptors] }),
347
+ imagePlugin({
348
+ ...imageDialog ? {
349
+ ImageDialog: imageDialog,
350
+ disableImageSettingsButton
351
+ } : {},
352
+ ...imageUploadHandler ? { imageUploadHandler } : {}
353
+ }),
354
+ ...extraPlugins ?? [],
355
+ toolbarPlugin({
356
+ toolbarClassName: "mdxeditor-toolbar-wrap",
357
+ toolbarContents: () => /* @__PURE__ */ jsx(DiffSourceToggleWrapper, { children: /* @__PURE__ */ jsx(ConditionalContents, { options: [{
358
+ when: (editor) => editor?.editorType === "codeblock",
359
+ contents: () => /* @__PURE__ */ jsx(ChangeCodeMirrorLanguage, {})
360
+ }, { fallback: () => /* @__PURE__ */ jsxs(Fragment, { children: [
361
+ /* @__PURE__ */ jsx(UndoRedo, {}),
362
+ /* @__PURE__ */ jsx(Separator, {}),
363
+ /* @__PURE__ */ jsx(BoldItalicUnderlineToggles, {}),
364
+ /* @__PURE__ */ jsx(StrikeThroughSupSubToggles, {}),
365
+ /* @__PURE__ */ jsx(HighlightToggle, {}),
366
+ /* @__PURE__ */ jsx(Separator, {}),
367
+ /* @__PURE__ */ jsx(ListsToggle, {}),
368
+ /* @__PURE__ */ jsx(Separator, {}),
369
+ /* @__PURE__ */ jsx(BlockTypeSelect, {}),
370
+ /* @__PURE__ */ jsx(Separator, {}),
371
+ /* @__PURE__ */ jsx(CreateLink, {}),
372
+ renderInsertImageButton(imageButtonRef),
373
+ /* @__PURE__ */ jsx(InsertTable, {}),
374
+ /* @__PURE__ */ jsx(InsertThematicBreak, {}),
375
+ /* @__PURE__ */ jsx(Separator, {}),
376
+ /* @__PURE__ */ jsx(InsertCodeBlock, {}),
377
+ extraToolbarItems,
378
+ /* @__PURE__ */ jsx(Separator, {}),
379
+ /* @__PURE__ */ jsx(FocusModeToggle, {})
380
+ ] }) }] }) })
381
+ })
382
+ ]
383
+ });
384
+ });
385
+ BaseMDXEditor.displayName = "BaseMDXEditor";
386
+ //#endregion
387
+ //#region src/hooks/useMDXEvaluation.ts
388
+ const compiledCache = /* @__PURE__ */ new Map();
389
+ /**
390
+ * Execute pre-compiled MDX code (compiled with outputFormat: 'function-body').
391
+ * This is the same as @mdx-js/mdx's run() — inlined here to avoid importing
392
+ * the full @mdx-js/mdx package (which pulls acorn + remark + unified into the browser).
393
+ *
394
+ * Note: Uses AsyncFunction constructor which requires CSP `unsafe-eval`.
395
+ * This is acceptable since the CMS admin UI runs in a trusted environment.
396
+ */
397
+ const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
398
+ async function runMDX(code, options) {
399
+ return new AsyncFunction(String(code))(options);
400
+ }
401
+ /**
402
+ * Create the JSX runtime options for runMDX().
403
+ * Checked once at module load to avoid repeated environment checks.
404
+ */
405
+ function createRunOptions() {
406
+ return process.env.NODE_ENV === "development" ? {
407
+ ...devRuntime,
408
+ development: true
409
+ } : { ...runtime };
410
+ }
411
+ const runOptions = createRunOptions();
34
412
  /**
35
413
  * Simple hash function for generating cache keys from MDX content.
36
- * Uses string hashing to avoid collisions when cacheKey isn't provided.
37
414
  */
38
415
  function hashString(str) {
39
416
  let hash = 0;
@@ -45,57 +422,44 @@ function hashString(str) {
45
422
  return hash.toString(36);
46
423
  }
47
424
  /**
48
- * Hook for evaluating MDX content into React components.
49
- *
50
- * Features:
51
- * - Evaluates MDX strings into renderable React components using @mdx-js/mdx
52
- * - Caches compiled components to avoid re-evaluation of unchanged content
53
- * - Handles both development (jsx-dev-runtime) and production (jsx-runtime) environments
54
- * - Provides retry mechanism to clear cache and re-evaluate failed compilations
55
- * - Returns loading and error states for UI feedback
425
+ * Hook for evaluating pre-compiled MDX code into React components.
56
426
  *
57
- * @param options - Configuration options
58
- * @param options.mdxContent - The MDX string to evaluate. If null, returns null component
59
- * @param options.cacheKey - Optional cache key. If not provided, uses first 100 chars of content
427
+ * Uses the browser-side half of a server-compile + browser-run pattern:
428
+ * 1. The server compiles MDX → JavaScript function body
429
+ * 2. The browser executes the pre-compiled code with run() (zero compiler dependencies)
60
430
  *
61
- * @returns Object containing:
62
- * - Component: The compiled React component (null if not yet compiled or error occurred)
63
- * - error: Error object if evaluation failed (null otherwise)
64
- * - isLoading: Boolean indicating if evaluation is in progress
65
- * - retry: Function to clear cache and retry evaluation
431
+ * This keeps the full MDX compilation pipeline on the server and only ships
432
+ * a tiny runtime helper to the browser.
66
433
  *
67
- * @example
68
- * ```tsx
69
- * const { Component, error, isLoading, retry } = useMDXEvaluation({
70
- * mdxContent: '# Hello\n\nThis is **MDX** content',
71
- * cacheKey: 'my-unique-key'
72
- * });
434
+ * @param options.compiledCode - The pre-compiled MDX function body. If null, returns null component
435
+ * @param options.cacheKey - Optional cache key. If not provided, uses hash of code
73
436
  *
74
- * if (isLoading) return <Spinner />;
75
- * if (error) return <Error message={error.message} onRetry={retry} />;
76
- * if (Component) return <Component />;
77
- * ```
437
+ * @returns Object containing Component, error, isLoading, retry
78
438
  */
79
- function useMDXEvaluation({ mdxContent, cacheKey }) {
439
+ function useMDXEvaluation({ compiledCode, cacheKey }) {
80
440
  const [Component, setComponent] = useState(null);
81
441
  const [error, setError] = useState(null);
82
- const [isLoading, setIsLoading] = useState(!!mdxContent);
442
+ const [isLoading, setIsLoading] = useState(() => {
443
+ if (!compiledCode) return false;
444
+ const key = cacheKey || `mdx-${hashString(compiledCode)}`;
445
+ return !compiledCache.has(key);
446
+ });
83
447
  const [retryCount, setRetryCount] = useState(0);
84
448
  const retry = () => {
85
- if (mdxContent) {
86
- const key = cacheKey || `mdx-${hashString(mdxContent)}`;
449
+ if (compiledCode) {
450
+ const key = cacheKey || `mdx-${hashString(compiledCode)}`;
87
451
  compiledCache.delete(key);
88
452
  }
89
453
  setRetryCount((prev) => prev + 1);
90
454
  };
91
455
  useEffect(() => {
92
- if (!mdxContent) {
456
+ if (!compiledCode) {
93
457
  setComponent(null);
94
458
  setError(null);
95
459
  setIsLoading(false);
96
460
  return;
97
461
  }
98
- const key = cacheKey || `mdx-${hashString(mdxContent)}`;
462
+ const key = cacheKey || `mdx-${hashString(compiledCode)}`;
99
463
  const cached = compiledCache.get(key);
100
464
  if (cached) {
101
465
  setComponent(() => cached);
@@ -103,23 +467,30 @@ function useMDXEvaluation({ mdxContent, cacheKey }) {
103
467
  setIsLoading(false);
104
468
  return;
105
469
  }
106
- const evaluateMDX = async () => {
470
+ let cancelled = false;
471
+ const compileAndRun = async () => {
107
472
  try {
108
473
  setError(null);
109
474
  setIsLoading(true);
110
- const { default: MDXComponent } = await evaluate(mdxContent, mdxEvaluationOptions);
475
+ const { default: MDXComponent } = await runMDX(compiledCode, runOptions);
476
+ if (cancelled) return;
111
477
  compiledCache.set(key, MDXComponent);
112
478
  setComponent(() => MDXComponent);
113
479
  } catch (err) {
114
- setError(err instanceof Error ? err : /* @__PURE__ */ new Error("MDX evaluation failed"));
480
+ if (cancelled) return;
481
+ const evaluationError = err instanceof Error ? err : /* @__PURE__ */ new Error("MDX evaluation failed");
482
+ setError(evaluationError);
115
483
  setComponent(null);
116
484
  } finally {
117
- setIsLoading(false);
485
+ if (!cancelled) setIsLoading(false);
118
486
  }
119
487
  };
120
- evaluateMDX();
488
+ compileAndRun();
489
+ return () => {
490
+ cancelled = true;
491
+ };
121
492
  }, [
122
- mdxContent,
493
+ compiledCode,
123
494
  cacheKey,
124
495
  retryCount
125
496
  ]);
@@ -130,316 +501,16 @@ function useMDXEvaluation({ mdxContent, cacheKey }) {
130
501
  retry
131
502
  };
132
503
  }
133
-
134
504
  //#endregion
135
505
  //#region src/mdx-editor.tsx
136
- /**
137
- * Error Boundary for catching React errors in MDXEditor.
138
- * Prevents editor crashes from breaking the entire CMS.
139
- */
140
- var MDXEditorErrorBoundary = class extends React.Component {
141
- constructor(props) {
142
- super(props);
143
- this.state = { hasError: false };
144
- }
145
- static getDerivedStateFromError(error) {
146
- return {
147
- hasError: true,
148
- error
149
- };
150
- }
151
- componentDidCatch(error, errorInfo) {
152
- console.error("[MDXEditor] Error boundary caught:", error, errorInfo);
153
- }
154
- render() {
155
- if (this.state.hasError) return /* @__PURE__ */ jsxs("div", {
156
- className: "p-4 bg-red-50 border border-red-200 rounded text-red-600",
157
- children: [
158
- /* @__PURE__ */ jsx("p", {
159
- className: "font-semibold mb-2",
160
- children: "MDXEditor Error"
161
- }),
162
- /* @__PURE__ */ jsx("p", {
163
- className: "text-sm mb-2",
164
- children: this.state.error?.message || "Unknown error occurred"
165
- }),
166
- /* @__PURE__ */ jsxs("details", {
167
- className: "text-xs",
168
- children: [/* @__PURE__ */ jsx("summary", {
169
- className: "cursor-pointer font-medium",
170
- children: "Stack Trace"
171
- }), /* @__PURE__ */ jsx("pre", {
172
- className: "mt-2 p-2 bg-red-100 rounded overflow-auto whitespace-pre-wrap",
173
- children: this.state.error?.stack
174
- })]
175
- })
176
- ]
177
- });
178
- return this.props.children;
179
- }
180
- };
181
- const MDXEditor = React.forwardRef(({ value, onChange, onSave, readOnly = false }, ref) => {
182
- useEffect(() => {
183
- const handleKeyDown = (e) => {
184
- if ((e.ctrlKey || e.metaKey) && e.key === "s") {
185
- e.preventDefault();
186
- if (onSave) onSave(value);
187
- }
188
- };
189
- document.addEventListener("keydown", handleKeyDown);
190
- return () => document.removeEventListener("keydown", handleKeyDown);
191
- }, [value, onSave]);
192
- return /* @__PURE__ */ jsx(MDXEditor$1, {
506
+ const MDXEditor = React.forwardRef((props, ref) => {
507
+ return /* @__PURE__ */ jsx(BaseMDXEditor, {
193
508
  ref,
194
- markdown: value,
195
- onChange,
196
- readOnly,
197
- contentEditableClassName: "prose max-w-none",
198
- plugins: [
199
- headingsPlugin(),
200
- listsPlugin(),
201
- quotePlugin(),
202
- linkPlugin(),
203
- linkDialogPlugin(),
204
- tablePlugin(),
205
- thematicBreakPlugin(),
206
- frontmatterPlugin(),
207
- codeBlockPlugin({ defaultCodeBlockLanguage: "ts" }),
208
- codeMirrorPlugin({ codeBlockLanguages: {
209
- text: "Plain Text",
210
- js: "JavaScript",
211
- jsx: "JavaScript (React)",
212
- ts: "TypeScript",
213
- tsx: "TypeScript (React)",
214
- css: "CSS",
215
- html: "HTML",
216
- json: "JSON",
217
- md: "Markdown",
218
- mdx: "MDX",
219
- bash: "Bash",
220
- python: "Python"
221
- } }),
222
- diffSourcePlugin({ viewMode: "rich-text" }),
223
- markdownShortcutPlugin(),
224
- jsxPlugin(),
225
- imagePlugin(),
226
- toolbarPlugin({ toolbarContents: () => /* @__PURE__ */ jsxs(DiffSourceToggleWrapper, { children: [
227
- /* @__PURE__ */ jsx(UndoRedo, {}),
228
- /* @__PURE__ */ jsx(Separator, {}),
229
- /* @__PURE__ */ jsx(BoldItalicUnderlineToggles, {}),
230
- /* @__PURE__ */ jsx(Separator, {}),
231
- /* @__PURE__ */ jsx(ListsToggle, {}),
232
- /* @__PURE__ */ jsx(Separator, {}),
233
- /* @__PURE__ */ jsx(BlockTypeSelect, {}),
234
- /* @__PURE__ */ jsx(Separator, {}),
235
- /* @__PURE__ */ jsx(CreateLink, {}),
236
- /* @__PURE__ */ jsx(InsertImage, {}),
237
- /* @__PURE__ */ jsx(InsertTable, {}),
238
- /* @__PURE__ */ jsx(InsertThematicBreak, {}),
239
- /* @__PURE__ */ jsx(Separator, {}),
240
- /* @__PURE__ */ jsx(InsertCodeBlock, {})
241
- ] }) })
242
- ]
509
+ ...props
243
510
  });
244
511
  });
245
512
  MDXEditor.displayName = "MDXEditor";
246
- /**
247
- * DeferredMDXEditor - A wrapper component that defers MDXEditor initialization to avoid React 19 render-phase state updates
248
- *
249
- * ## Why This Wrapper Exists
250
- *
251
- * MDXEditor (v3.38.0) uses Lexical under the hood, which performs synchronous state updates during its initial render
252
- * when provided with markdown content. This violates React 19's stricter rules about state updates during render.
253
- *
254
- * ## The Specific React 19 Issue
255
- *
256
- * In React 19, the framework is more strict about preventing state updates during the render phase. When MDXEditor
257
- * initializes with the `markdown` prop, Lexical immediately:
258
- * 1. Parses the markdown content
259
- * 2. Converts it to Lexical's internal state representation
260
- * 3. Attempts to commit these changes via `$commitPendingUpdates`
261
- *
262
- * This happens synchronously during render, causing the error:
263
- * "Can't perform a React state update on a component that hasn't mounted yet"
264
- *
265
- * ## How This Wrapper Solves It
266
- *
267
- * By deferring the actual MDXEditor component render by 10ms using setTimeout, we ensure:
268
- * 1. React completes the current render cycle
269
- * 2. The component tree is fully mounted
270
- * 3. Only then does MDXEditor initialize with its content
271
- *
272
- * This prevents Lexical from trying to update state during the render phase.
273
- *
274
- * ## When This Issue Occurs
275
- *
276
- * This issue is particularly prevalent when:
277
- * - Using MDXEditor in a modal that mounts/unmounts frequently
278
- * - Dynamically loading content into the editor
279
- * - Using React 19 with its stricter concurrent rendering rules
280
- *
281
- * ## Technical Details
282
- *
283
- * The error stack trace shows the issue originates from:
284
- * - triggerListeners @ Lexical.dev.mjs:8156
285
- * - $commitPendingUpdates @ Lexical.dev.mjs:8116
286
- *
287
- * These Lexical internal methods are called during the initial render when markdown content is provided.
288
- *
289
- * ## Future Considerations
290
- *
291
- * This wrapper is a workaround for what should ideally be fixed in the MDXEditor/Lexical library itself.
292
- * The library should defer its own state initialization to a useEffect or similar to be React 19 compliant.
293
- *
294
- * Related issues:
295
- * - https://github.com/mdx-editor/editor/issues/494 (React 19 compatibility)
296
- * - Various modal-related issues (#584, #581, #758, #276)
297
- */
298
- const DeferredMDXEditor = ({ value, onChange, onSave, readOnly }) => {
299
- const editorRef = React.useRef(null);
300
- const [isReady, setIsReady] = useState(false);
301
- useEffect(() => {
302
- const timer = setTimeout(() => {
303
- setIsReady(true);
304
- }, 10);
305
- return () => clearTimeout(timer);
306
- }, []);
307
- if (!isReady) return /* @__PURE__ */ jsx("div", {
308
- className: "flex items-center justify-center h-full text-gray-500",
309
- "data-testid": "deferred-editor-loading",
310
- children: "Initializing editor..."
311
- });
312
- return /* @__PURE__ */ jsx("div", {
313
- "data-testid": "deferred-editor-ready",
314
- children: /* @__PURE__ */ jsx(MDXEditor, {
315
- ref: editorRef,
316
- value,
317
- onChange,
318
- onSave,
319
- readOnly
320
- })
321
- });
322
- };
323
- const Dialog = ({ open, onOpenChange, children }) => {
324
- if (!open) return null;
325
- return /* @__PURE__ */ jsxs("div", {
326
- className: "fixed inset-0 z-50 flex items-center justify-center",
327
- children: [/* @__PURE__ */ jsx("div", {
328
- className: "fixed inset-0 bg-black/50",
329
- onClick: () => onOpenChange(false)
330
- }), /* @__PURE__ */ jsx("div", {
331
- className: "relative z-50 bg-white rounded-lg shadow-lg max-w-[90vw] max-h-[90vh] overflow-hidden",
332
- children
333
- })]
334
- });
335
- };
336
- const DialogContent = ({ children, className = "" }) => {
337
- return /* @__PURE__ */ jsx("div", {
338
- className: `p-6 ${className}`,
339
- children
340
- });
341
- };
342
- const DialogHeader = ({ children }) => {
343
- return /* @__PURE__ */ jsx("div", {
344
- className: "mb-4",
345
- children
346
- });
347
- };
348
- const DialogTitle = ({ children }) => {
349
- return /* @__PURE__ */ jsx("h2", {
350
- className: "text-xl font-semibold",
351
- children
352
- });
353
- };
354
- const MDXEditorModal = ({ isOpen, onClose, filePath, initialContent, onSave, headerExtra, onBeforeClose }) => {
355
- const [content, setContent] = useState(initialContent);
356
- const [isEditorReady, setIsEditorReady] = useState(false);
357
- const [isSaving, setIsSaving] = useState(false);
358
- useEffect(() => {
359
- setContent(initialContent);
360
- }, [initialContent]);
361
- const handleClose = () => {
362
- if (onBeforeClose && !onBeforeClose()) return;
363
- onClose();
364
- };
365
- useEffect(() => {
366
- if (isOpen) {
367
- const timer = setTimeout(() => {
368
- setIsEditorReady(true);
369
- }, 0);
370
- return () => clearTimeout(timer);
371
- }
372
- setIsEditorReady(false);
373
- }, [isOpen]);
374
- const handleSave = async () => {
375
- setIsSaving(true);
376
- try {
377
- await onSave(content);
378
- handleClose();
379
- } catch (error) {
380
- console.error("Save failed:", error);
381
- } finally {
382
- setIsSaving(false);
383
- }
384
- };
385
- if (!isOpen) return null;
386
- return /* @__PURE__ */ jsx(Dialog, {
387
- open: isOpen,
388
- onOpenChange: handleClose,
389
- children: /* @__PURE__ */ jsxs(DialogContent, {
390
- className: "w-[90vw] h-[90vh] flex flex-col",
391
- "data-testid": "mdx-editor-modal",
392
- children: [
393
- /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsxs("div", {
394
- className: "flex items-center justify-between gap-4",
395
- children: [
396
- /* @__PURE__ */ jsx(DialogTitle, { children: filePath ? `Edit: ${filePath}` : "New MDX File" }),
397
- headerExtra && /* @__PURE__ */ jsx("div", {
398
- className: "flex items-center gap-2",
399
- children: headerExtra
400
- }),
401
- /* @__PURE__ */ jsx("button", {
402
- onClick: handleClose,
403
- className: "p-2 hover:bg-gray-100 rounded",
404
- "aria-label": "Close",
405
- children: "✕"
406
- })
407
- ]
408
- }) }),
409
- /* @__PURE__ */ jsx("div", {
410
- className: "flex-1 overflow-hidden",
411
- children: isEditorReady ? /* @__PURE__ */ jsx(MDXEditorErrorBoundary, { children: /* @__PURE__ */ jsx(DeferredMDXEditor, {
412
- value: content,
413
- onChange: setContent,
414
- onSave: handleSave
415
- }) }) : /* @__PURE__ */ jsx("div", {
416
- className: "flex items-center justify-center h-full",
417
- children: /* @__PURE__ */ jsx("div", {
418
- className: "text-gray-500",
419
- "data-testid": "modal-editor-loading",
420
- children: "Loading editor..."
421
- })
422
- })
423
- }),
424
- /* @__PURE__ */ jsxs("div", {
425
- className: "flex justify-end gap-2 mt-4",
426
- children: [/* @__PURE__ */ jsx("button", {
427
- onClick: handleClose,
428
- className: "px-4 py-2 border border-gray-300 rounded hover:bg-gray-50",
429
- disabled: isSaving,
430
- children: "Cancel"
431
- }), /* @__PURE__ */ jsx("button", {
432
- onClick: handleSave,
433
- className: "px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed",
434
- disabled: isSaving,
435
- children: isSaving ? "Saving..." : "Save"
436
- })]
437
- })
438
- ]
439
- })
440
- });
441
- };
442
-
443
513
  //#endregion
444
- export { MDXEditor, MDXEditorModal, useMDXEvaluation };
514
+ export { BaseMDXEditor, MDXEditor, codeBlockWrapperInfo$, useMDXEvaluation };
515
+
445
516
  //# sourceMappingURL=index.mjs.map