@conloca/mdx 0.1.16 → 0.2.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.
Files changed (91) hide show
  1. package/README.md +50 -16
  2. package/dist/code-block-frame.js +1 -0
  3. package/dist/code-block-frame.js.map +1 -0
  4. package/dist/editor-core.d.ts +0 -2
  5. package/dist/editor-core.d.ts.map +1 -1
  6. package/dist/editor-core.js +50 -6
  7. package/dist/editor-core.js.map +1 -0
  8. package/dist/esm-passthrough.d.ts +36 -0
  9. package/dist/esm-passthrough.d.ts.map +1 -0
  10. package/dist/esm-passthrough.js +237 -0
  11. package/dist/esm-passthrough.js.map +1 -0
  12. package/dist/fragments.d.ts +37 -0
  13. package/dist/fragments.d.ts.map +1 -0
  14. package/dist/fragments.js +53 -0
  15. package/dist/fragments.js.map +1 -0
  16. package/dist/index.d.ts +0 -2
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +1 -1
  19. package/dist/index.js.map +1 -0
  20. package/dist/markdown-options.js +1 -0
  21. package/dist/markdown-options.js.map +1 -0
  22. package/dist/mdx/compile-request.d.ts +5 -0
  23. package/dist/mdx/compile-request.d.ts.map +1 -0
  24. package/dist/mdx/compile-request.js +40 -0
  25. package/dist/mdx/compile-request.js.map +1 -0
  26. package/dist/mdx/compile.d.ts.map +1 -1
  27. package/dist/mdx/compile.js +30 -1
  28. package/dist/mdx/compile.js.map +1 -0
  29. package/dist/mdx/evaluate.d.ts +18 -23
  30. package/dist/mdx/evaluate.d.ts.map +1 -1
  31. package/dist/mdx/evaluate.js +123 -29
  32. package/dist/mdx/evaluate.js.map +1 -0
  33. package/dist/mdx/heading-outline.d.ts +46 -0
  34. package/dist/mdx/heading-outline.d.ts.map +1 -0
  35. package/dist/mdx/heading-outline.js +114 -0
  36. package/dist/mdx/heading-outline.js.map +1 -0
  37. package/dist/mdx/literal-attributes.d.ts +26 -0
  38. package/dist/mdx/literal-attributes.d.ts.map +1 -0
  39. package/dist/mdx/literal-attributes.js +40 -0
  40. package/dist/mdx/literal-attributes.js.map +1 -0
  41. package/dist/mdx/restrict-expressions.d.ts +45 -0
  42. package/dist/mdx/restrict-expressions.d.ts.map +1 -0
  43. package/dist/mdx/restrict-expressions.js +171 -0
  44. package/dist/mdx/restrict-expressions.js.map +1 -0
  45. package/dist/mdx-editor.js +1 -0
  46. package/dist/mdx-editor.js.map +1 -0
  47. package/dist/node.d.ts +3 -2
  48. package/dist/node.d.ts.map +1 -1
  49. package/dist/node.js +3 -1
  50. package/dist/node.js.map +1 -0
  51. package/dist/sandbox-frame.d.ts +114 -0
  52. package/dist/sandbox-frame.d.ts.map +1 -0
  53. package/dist/sandbox-frame.js +253 -0
  54. package/dist/sandbox-frame.js.map +1 -0
  55. package/dist/types.d.ts +7 -4
  56. package/dist/types.d.ts.map +1 -1
  57. package/dist/types.js +1 -0
  58. package/dist/types.js.map +1 -0
  59. package/package.json +58 -41
  60. package/src/code-block-frame.tsx +262 -0
  61. package/src/editor-core.tsx +403 -0
  62. package/src/editor-styles.css +282 -0
  63. package/src/esm-passthrough.ts +269 -0
  64. package/src/fragments.ts +91 -0
  65. package/src/index.ts +5 -0
  66. package/src/markdown-options.ts +21 -0
  67. package/src/mdx/compile-request.ts +53 -0
  68. package/src/mdx/compile.ts +60 -0
  69. package/src/mdx/evaluate.ts +174 -0
  70. package/src/mdx/heading-outline.ts +153 -0
  71. package/src/mdx/literal-attributes.ts +50 -0
  72. package/src/mdx/restrict-expressions.ts +184 -0
  73. package/src/mdx-editor.tsx +15 -0
  74. package/src/node.ts +25 -0
  75. package/src/sandbox-frame.ts +294 -0
  76. package/src/types.ts +23 -0
  77. package/dist/blocks.d.ts +0 -37
  78. package/dist/blocks.d.ts.map +0 -1
  79. package/dist/blocks.js +0 -51
  80. package/dist/hooks/useMDXEvaluation.d.ts +0 -28
  81. package/dist/hooks/useMDXEvaluation.d.ts.map +0 -1
  82. package/dist/hooks/useMDXEvaluation.js +0 -117
  83. package/dist/index.d.mts +0 -127
  84. package/dist/index.d.mts.map +0 -1
  85. package/dist/index.mjs +0 -516
  86. package/dist/index.mjs.map +0 -1
  87. package/dist/node.d.mts +0 -102
  88. package/dist/node.d.mts.map +0 -1
  89. package/dist/node.mjs +0 -140
  90. package/dist/node.mjs.map +0 -1
  91. package/dist/style.css +0 -88
package/dist/index.d.mts DELETED
@@ -1,127 +0,0 @@
1
- import { JsxComponentDescriptor, MDXEditorMethods, MDXEditorMethods as MDXEditorMethods$1, RealmPlugin } from "@mdxeditor/editor";
2
- import React from "react";
3
- import "@mdxeditor/editor/style.css";
4
- //#region src/code-block-frame.d.ts
5
- /**
6
- * Frame chrome around the editor's fenced code blocks — header bar with
7
- * filename, language tag, and a copy button. The outer wrapper picks up
8
- * the host's code-block classes (published via `codeBlockWrapperInfo$`
9
- * by the host-wrapper plugin in cms-spa), so the host's actual code-
10
- * block CSS (Starlight's expressive-code, Tailwind's pre styling, etc.)
11
- * reaches the editor's frame through the cascade — no shipped mirror.
12
- *
13
- * Host-agnostic: no Shiki / Starlight / ExpressiveCode imports. Class
14
- * names are discovered at runtime from the host's live HTML.
15
- */
16
- /**
17
- * Realm-published cell carrying the host's code-block wrapper chain,
18
- * outermost first. For Starlight's expressive-code:
19
- *
20
- * [
21
- * { tagName: 'div', className: 'expressive-code' },
22
- * { tagName: 'figure', className: 'frame has-title not-content' },
23
- * ]
24
- *
25
- * The cms-spa `hostWrapperPlugin` writes to this whenever the fetched
26
- * wrapper info changes; the code-block frame reads from it to render
27
- * each chain link as a nested element with the host's expected tag
28
- * name. Same publish-pattern as the content-wrapper plugin in cms-spa.
29
- *
30
- * Null when the host has no code-block chrome (or the fetch is in
31
- * flight). The frame then falls back to its base `.conloca-code-block`
32
- * wrapper with no host inheritance — "looks plain but not broken."
33
- */
34
- declare const codeBlockWrapperInfo$: import("@mdxeditor/editor").NodeRef<{
35
- tagName: string;
36
- className: string;
37
- }[] | null>;
38
- //#endregion
39
- //#region src/editor-core.d.ts
40
- interface BaseMDXEditorProps {
41
- value: string;
42
- /**
43
- * Called whenever the editor content changes. The second argument is `true`
44
- * the first time the library normalizes the parsed markdown back to its
45
- * canonical form (bullet style, trailing newline, etc.) — consumers tracking
46
- * dirty state should treat that call as a re-baseline rather than a user
47
- * edit, otherwise the editor looks dirty the moment the page loads.
48
- */
49
- onChange: (value: string, initialMarkdownNormalize?: boolean) => void;
50
- onSave?: (value: string) => void;
51
- readOnly?: boolean;
52
- imageDialog?: React.FC | null;
53
- disableImageSettingsButton?: boolean;
54
- onImageShortcut?: () => void;
55
- imageButtonRef?: React.Ref<HTMLButtonElement>;
56
- /**
57
- * Upload handler for images pasted or dropped directly into the editor. When
58
- * provided, the underlying imagePlugin will route those events through this
59
- * function and insert the returned URL as the image src. Independent of the
60
- * library/picker `imageDialog` flow — both can be active simultaneously.
61
- */
62
- imageUploadHandler?: (file: File) => Promise<string>;
63
- jsxComponentDescriptors?: JsxComponentDescriptor[];
64
- /**
65
- * Additional @mdxeditor/editor RealmPlugins appended to the built-in
66
- * plugin list. Used by the SPA shell to register the MDX components
67
- * registry-driven slash menu without coupling @conloca/mdx to
68
- * @conloca/cms-spa.
69
- */
70
- extraPlugins?: RealmPlugin[];
71
- /**
72
- * Extra toolbar buttons inserted between `<InsertAdmonition />` and the
73
- * separator preceding focus mode. Pass `null` (default) to keep the
74
- * stock toolbar.
75
- */
76
- extraToolbarItems?: React.ReactNode;
77
- /**
78
- * Class applied to the MDXEditor root element (library forwards it to the
79
- * toolbar and portaled popups too). Pass `"dark-theme"` to activate the
80
- * library's built-in Radix dark palette.
81
- * See https://mdxeditor.dev/editor/docs/theming
82
- */
83
- className?: string;
84
- /** Placeholder shown when the editor is empty. Forwarded to MDXEditorLib. */
85
- placeholder?: React.ReactNode;
86
- /** Auto-focus the editor on mount. Forwarded to MDXEditorLib. */
87
- autoFocus?: boolean | {
88
- defaultSelection?: 'rootStart' | 'rootEnd';
89
- preventScroll?: boolean;
90
- };
91
- }
92
- declare const BaseMDXEditor: React.ForwardRefExoticComponent<BaseMDXEditorProps & React.RefAttributes<MDXEditorMethods$1>>;
93
- //#endregion
94
- //#region src/hooks/useMDXEvaluation.d.ts
95
- interface UseMDXEvaluationOptions {
96
- compiledCode: string | null;
97
- cacheKey?: string;
98
- }
99
- interface UseMDXEvaluationResult {
100
- Component: React.ComponentType | null;
101
- error: Error | null;
102
- isLoading: boolean;
103
- retry: () => void;
104
- }
105
- /**
106
- * Hook for evaluating pre-compiled MDX code into React components.
107
- *
108
- * Uses the browser-side half of a server-compile + browser-run pattern:
109
- * 1. The server compiles MDX → JavaScript function body
110
- * 2. The browser executes the pre-compiled code with run() (zero compiler dependencies)
111
- *
112
- * This keeps the full MDX compilation pipeline on the server and only ships
113
- * a tiny runtime helper to the browser.
114
- *
115
- * @param options.compiledCode - The pre-compiled MDX function body. If null, returns null component
116
- * @param options.cacheKey - Optional cache key. If not provided, uses hash of code
117
- *
118
- * @returns Object containing Component, error, isLoading, retry
119
- */
120
- declare function useMDXEvaluation({ compiledCode, cacheKey }: UseMDXEvaluationOptions): UseMDXEvaluationResult;
121
- //#endregion
122
- //#region src/mdx-editor.d.ts
123
- interface MDXEditorProps extends Omit<BaseMDXEditorProps, 'disableImageSettingsButton' | 'imageButtonRef' | 'imageDialog' | 'onImageShortcut'> {}
124
- declare const MDXEditor: React.ForwardRefExoticComponent<MDXEditorProps & React.RefAttributes<MDXEditorMethods$1>>;
125
- //#endregion
126
- export { BaseMDXEditor, type BaseMDXEditorProps, MDXEditor, type MDXEditorMethods, MDXEditorProps, type UseMDXEvaluationOptions, type UseMDXEvaluationResult, codeBlockWrapperInfo$, useMDXEvaluation };
127
- //# sourceMappingURL=index.d.mts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/code-block-frame.tsx","../src/editor-core.tsx","../src/hooks/useMDXEvaluation.ts","../src/mdx-editor.tsx"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAyCa,mDAAqB;EAAmB;EAAmB;;;;UCsDvD;EACf;;;;;;;;EAQA,WAAW,eAAe;EAC1B,UAAU;EACV;EACA,cAAc,MAAM;EACpB;EACA;EACA,iBAAiB,MAAM,IAAI;;;;;;;EAO3B,sBAAsB,MAAM,SAAS;EACrC,0BAA0B;;;;;;;EAO1B,eAAe;;;;;;EAMf,oBAAoB,MAAM;;;;;;;EAO1B;;EAEA,cAAc,MAAM;;EAEpB;IAAwB;IAA4C;;;cA+DzD,eAAa,MAAA,0BAAA,qBAAA,MAAA,cAAA;;;UChKT;EACf;EACA;;UAGe;EACf,WAAW,MAAM;EACjB,OAAO;EACP;EACA;;;;;;;;;;;;;;;;;iBAkBc,mBAAmB,cAAc,YAAY,0BAA0B;;;UCpEtE,uBACP,KACN;cAIS,WAAS,MAAA,0BAAA,iBAAA,MAAA,cAAA"}
package/dist/index.mjs DELETED
@@ -1,516 +0,0 @@
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";
5
- import * as runtime from "react/jsx-runtime";
6
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
7
- import "@mdxeditor/editor/style.css";
8
- import * as devRuntime from "react/jsx-dev-runtime";
9
- //#region src/code-block-frame.tsx
10
- /**
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.
17
- *
18
- * Host-agnostic: no Shiki / Starlight / ExpressiveCode imports. Class
19
- * names are discovered at runtime from the host's live HTML.
20
- */
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
- };
48
- return {
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);
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 });
289
- }
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();
412
- /**
413
- * Simple hash function for generating cache keys from MDX content.
414
- */
415
- function hashString(str) {
416
- let hash = 0;
417
- for (let i = 0; i < str.length; i++) {
418
- const char = str.charCodeAt(i);
419
- hash = (hash << 5) - hash + char;
420
- hash = hash & hash;
421
- }
422
- return hash.toString(36);
423
- }
424
- /**
425
- * Hook for evaluating pre-compiled MDX code into React components.
426
- *
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)
430
- *
431
- * This keeps the full MDX compilation pipeline on the server and only ships
432
- * a tiny runtime helper to the browser.
433
- *
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
436
- *
437
- * @returns Object containing Component, error, isLoading, retry
438
- */
439
- function useMDXEvaluation({ compiledCode, cacheKey }) {
440
- const [Component, setComponent] = useState(null);
441
- const [error, setError] = useState(null);
442
- const [isLoading, setIsLoading] = useState(() => {
443
- if (!compiledCode) return false;
444
- const key = cacheKey || `mdx-${hashString(compiledCode)}`;
445
- return !compiledCache.has(key);
446
- });
447
- const [retryCount, setRetryCount] = useState(0);
448
- const retry = () => {
449
- if (compiledCode) {
450
- const key = cacheKey || `mdx-${hashString(compiledCode)}`;
451
- compiledCache.delete(key);
452
- }
453
- setRetryCount((prev) => prev + 1);
454
- };
455
- useEffect(() => {
456
- if (!compiledCode) {
457
- setComponent(null);
458
- setError(null);
459
- setIsLoading(false);
460
- return;
461
- }
462
- const key = cacheKey || `mdx-${hashString(compiledCode)}`;
463
- const cached = compiledCache.get(key);
464
- if (cached) {
465
- setComponent(() => cached);
466
- setError(null);
467
- setIsLoading(false);
468
- return;
469
- }
470
- let cancelled = false;
471
- const compileAndRun = async () => {
472
- try {
473
- setError(null);
474
- setIsLoading(true);
475
- const { default: MDXComponent } = await runMDX(compiledCode, runOptions);
476
- if (cancelled) return;
477
- compiledCache.set(key, MDXComponent);
478
- setComponent(() => MDXComponent);
479
- } catch (err) {
480
- if (cancelled) return;
481
- const evaluationError = err instanceof Error ? err : /* @__PURE__ */ new Error("MDX evaluation failed");
482
- setError(evaluationError);
483
- setComponent(null);
484
- } finally {
485
- if (!cancelled) setIsLoading(false);
486
- }
487
- };
488
- compileAndRun();
489
- return () => {
490
- cancelled = true;
491
- };
492
- }, [
493
- compiledCode,
494
- cacheKey,
495
- retryCount
496
- ]);
497
- return {
498
- Component,
499
- error,
500
- isLoading,
501
- retry
502
- };
503
- }
504
- //#endregion
505
- //#region src/mdx-editor.tsx
506
- const MDXEditor = React.forwardRef((props, ref) => {
507
- return /* @__PURE__ */ jsx(BaseMDXEditor, {
508
- ref,
509
- ...props
510
- });
511
- });
512
- MDXEditor.displayName = "MDXEditor";
513
- //#endregion
514
- export { BaseMDXEditor, MDXEditor, codeBlockWrapperInfo$, useMDXEvaluation };
515
-
516
- //# sourceMappingURL=index.mjs.map