@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
@@ -0,0 +1,262 @@
1
+ import {
2
+ Cell,
3
+ type CodeBlockEditorDescriptor,
4
+ type CodeBlockEditorProps,
5
+ CodeMirrorEditor,
6
+ useCellValue,
7
+ useCodeBlockEditorContext,
8
+ } from '@mdxeditor/editor';
9
+ import { Check, Copy } from 'lucide-react';
10
+ import { type ChangeEvent, createElement, type ReactElement, useCallback, useEffect, useMemo, useState } from 'react';
11
+
12
+ /**
13
+ * Frame chrome around the editor's fenced code blocks — header bar with
14
+ * filename, language tag, and a copy button. The outer wrapper picks up
15
+ * the host's code-block classes (published via `codeBlockWrapperInfo$`
16
+ * by the host-wrapper plugin in cms-spa), so the host's actual code-
17
+ * block CSS (Starlight's expressive-code, Tailwind's pre styling, etc.)
18
+ * reaches the editor's frame through the cascade — no shipped mirror.
19
+ *
20
+ * Host-agnostic: no Shiki / Starlight / ExpressiveCode imports. Class
21
+ * names are discovered at runtime from the host's live HTML.
22
+ */
23
+
24
+ /**
25
+ * Realm-published cell carrying the host's code-block wrapper chain,
26
+ * outermost first. For Starlight's expressive-code:
27
+ *
28
+ * [
29
+ * { tagName: 'div', className: 'expressive-code' },
30
+ * { tagName: 'figure', className: 'frame has-title not-content' },
31
+ * ]
32
+ *
33
+ * The cms-spa `hostWrapperPlugin` writes to this whenever the fetched
34
+ * wrapper info changes; the code-block frame reads from it to render
35
+ * each chain link as a nested element with the host's expected tag
36
+ * name. Same publish-pattern as the content-wrapper plugin in cms-spa.
37
+ *
38
+ * Null when the host has no code-block chrome (or the fetch is in
39
+ * flight). The frame then falls back to its base `.conloca-code-block`
40
+ * wrapper with no host inheritance — "looks plain but not broken."
41
+ */
42
+ export const codeBlockWrapperInfo$ = Cell<{ tagName: string; className: string }[] | null>(null);
43
+
44
+ const TITLE_META_RE = /\btitle=(?:"([^"]*)"|'([^']*)'|(\S+))/;
45
+ // First-line filename comment, the convention ExpressiveCode's frames
46
+ // plugin recognizes when no explicit `title=` is set on the fence —
47
+ // `// foo.ts`, `# foo.py`, `<!-- foo.html -->`, `/* foo.css */`,
48
+ // `; foo.ini`, `-- foo.sql`. Requires a dot-extension so plain prose
49
+ // comments don't get mistaken for filenames.
50
+ const FILENAME_COMMENT_RE = /^\s*(?:\/\/|#|;|--|<!--|\/\*)\s*([\w.\-/@]+\.[\w.-]+)\s*(?:-->|\*\/)?\s*$/;
51
+
52
+ interface MetaParts {
53
+ /** The current title value (empty string when no title meta is set). */
54
+ title: string;
55
+ /** Everything else in the meta string, with the title slice removed. */
56
+ rest: string;
57
+ }
58
+
59
+ function parseMeta(meta: string): MetaParts {
60
+ const match = meta.match(TITLE_META_RE);
61
+ if (!match) return { title: '', rest: meta.trim() };
62
+ const value = match[1] ?? match[2] ?? match[3] ?? '';
63
+ const rest = (meta.slice(0, match.index) + meta.slice(match.index! + match[0].length)).replace(/\s+/g, ' ').trim();
64
+ return { title: value, rest };
65
+ }
66
+
67
+ /** Reassemble a meta string with `title` set (or stripped when empty). */
68
+ function buildMeta(title: string, rest: string): string {
69
+ const trimmedTitle = title.trim();
70
+ const titleFragment = trimmedTitle ? `title="${trimmedTitle.replace(/"/g, '\\"')}"` : '';
71
+ if (titleFragment && rest) return `${titleFragment} ${rest}`;
72
+ return titleFragment || rest;
73
+ }
74
+
75
+ /**
76
+ * Detect a leading filename comment, the convention EC's frames plugin
77
+ * uses on the published page when no explicit `title=` is set. Returns
78
+ * the filename when line 1 of the code is a single-line comment ending
79
+ * in a dot-extension; empty string otherwise.
80
+ *
81
+ * Used to pre-fill the editor's filename input on legacy fences so
82
+ * authors see the same value the reader sees in the rendered tab. Pure
83
+ * read — the underlying code/comment is never touched.
84
+ */
85
+ function detectFilenameComment(code: string): string {
86
+ const firstLine = code.split('\n', 1)[0] ?? '';
87
+ const match = firstLine.match(FILENAME_COMMENT_RE);
88
+ return match ? (match[1] ?? '') : '';
89
+ }
90
+
91
+ function CopyButton({ code }: { code: string }) {
92
+ const [copied, setCopied] = useState(false);
93
+ const onClick = useCallback(() => {
94
+ void navigator.clipboard.writeText(code).then(() => {
95
+ setCopied(true);
96
+ window.setTimeout(() => setCopied(false), 1200);
97
+ });
98
+ }, [code]);
99
+ return (
100
+ <button
101
+ type="button"
102
+ onClick={onClick}
103
+ className="conloca-code-copy"
104
+ aria-label={copied ? 'Copied' : 'Copy code'}
105
+ title={copied ? 'Copied' : 'Copy code'}
106
+ >
107
+ {copied ? <Check size={14} aria-hidden="true" /> : <Copy size={14} aria-hidden="true" />}
108
+ </button>
109
+ );
110
+ }
111
+
112
+ /**
113
+ * Editable filename slot. Rewrites the code block's meta string via
114
+ * `setMeta` from `useCodeBlockEditorContext` so authors can author the
115
+ * frame title (`\`\`\`ts title="src/foo.ts"`) directly from the editor —
116
+ * the meta string round-trips through MDXEditor's markdown serializer
117
+ * and ExpressiveCode picks it up as the frame header on the published
118
+ * page. Other meta fragments (ins/del/mark/wrap) are preserved.
119
+ *
120
+ * Legacy fences with a filename comment on line 1 (`// foo.ts`) — EC's
121
+ * pre-meta convention for tab titles — are detected and pre-filled in
122
+ * the input as a read-only display. Opening such a fence does NOT
123
+ * mutate the source. Editing the field is an explicit author intent:
124
+ * the new value is written as `title=` meta AND the original comment
125
+ * line is stripped, so the editor's input becomes the single source of
126
+ * truth without breaking the published render.
127
+ */
128
+ function FilenameInput({ meta, code }: { meta: string; code: string }) {
129
+ const { setMeta, setCode } = useCodeBlockEditorContext();
130
+ const parsed = useMemo(() => parseMeta(meta), [meta]);
131
+ const detectedFromComment = useMemo(() => (parsed.title ? '' : detectFilenameComment(code)), [parsed.title, code]);
132
+ const displayed = parsed.title || detectedFromComment;
133
+ const [title, setTitle] = useState(displayed);
134
+ const [interacted, setInteracted] = useState(false);
135
+
136
+ // External updates (HMR, language change, sibling code edits) reset
137
+ // the local view to the canonical value and clear the "user edited"
138
+ // flag — so the next blur after an external update doesn't write
139
+ // anything until the author actively types again.
140
+ useEffect(() => {
141
+ setTitle(displayed);
142
+ setInteracted(false);
143
+ }, [displayed]);
144
+
145
+ const commit = useCallback(
146
+ (next: string) => {
147
+ if (!interacted) return;
148
+ if (next === parsed.title) return;
149
+ setMeta(buildMeta(next, parsed.rest));
150
+ // If the pre-fill came from a leading filename comment and the
151
+ // author has now committed an explicit title, strip the comment
152
+ // so EC doesn't render the title twice (once as the tab, once as
153
+ // a stray code comment) on the published page.
154
+ if (detectedFromComment) {
155
+ const lines = code.split('\n');
156
+ if (lines[0] && FILENAME_COMMENT_RE.test(lines[0])) {
157
+ setCode(lines.slice(1).join('\n').replace(/^\n+/, ''));
158
+ }
159
+ }
160
+ },
161
+ [interacted, parsed.title, parsed.rest, detectedFromComment, code, setMeta, setCode],
162
+ );
163
+
164
+ const onChange = (e: ChangeEvent<HTMLInputElement>) => {
165
+ setInteracted(true);
166
+ setTitle(e.target.value);
167
+ };
168
+ const onBlur = () => commit(title);
169
+
170
+ return (
171
+ <input
172
+ type="text"
173
+ className="conloca-code-block__filename"
174
+ value={title}
175
+ placeholder="filename"
176
+ spellCheck={false}
177
+ onChange={onChange}
178
+ onBlur={onBlur}
179
+ aria-label="Code block filename"
180
+ />
181
+ );
182
+ }
183
+
184
+ function ConlocaCodeBlockEditor(props: CodeBlockEditorProps) {
185
+ // Materialise the host's discovered code-block chain as nested
186
+ // elements. The INNERMOST link in the chain becomes the "frame"
187
+ // element that directly holds the filename header, the code body,
188
+ // and the copy slot — matching ExpressiveCode's authoring shape:
189
+ //
190
+ // <div class="expressive-code"> ← outer link
191
+ // <figure class="frame has-title …"> ← inner link (frame)
192
+ // <figcaption class="header">
193
+ // <span class="title"><FilenameInput /></span>
194
+ // </figcaption>
195
+ // <pre><CodeMirror /></pre>
196
+ // <div class="copy"><CopyButton /></div>
197
+ // </figure>
198
+ // </div>
199
+ //
200
+ // Rendering with the host's expected tags (figure / figcaption / pre)
201
+ // and nesting depth lets descendant CSS selectors land — both single-
202
+ // class (`.frame { ... }`) and descendant (`.expressive-code .frame
203
+ // .header > .title { ... }`) rules paint without us shipping a
204
+ // parallel copy.
205
+ //
206
+ // When chain is null/empty (host has no code-block chrome, or the
207
+ // wrapper fetch hasn't resolved yet) we fall back to a bare
208
+ // `<div class="conloca-code-block">` containing the same inner
209
+ // shape — "looks plain but not broken."
210
+ const chain = useCellValue(codeBlockWrapperInfo$) ?? [];
211
+ const frameLink = chain.length > 0 ? chain[chain.length - 1] : null;
212
+ const outerLinks = frameLink ? chain.slice(0, -1) : [];
213
+
214
+ const frameInner = (
215
+ <>
216
+ <figcaption className="conloca-code-block__header header">
217
+ <span className="title">
218
+ <FilenameInput meta={props.meta} code={props.code} />
219
+ </span>
220
+ </figcaption>
221
+ <pre className="conloca-code-block__pre">
222
+ <CodeMirrorEditor {...props} />
223
+ </pre>
224
+ {/* `.copy` matches expressive-code's expected slot name so any
225
+ `.frame .copy` styling from the host paints. We host only the
226
+ copy button here — language selection lives in MDXEditor's
227
+ own `_codeMirrorToolbar_*` (combobox), positioned via
228
+ editor-styles.css so it doesn't overlap the code. */}
229
+ <div className="conloca-code-block__copy copy">
230
+ <CopyButton code={props.code} />
231
+ </div>
232
+ </>
233
+ );
234
+
235
+ // The frame element carries `conloca-code-block` (our own targeting
236
+ // hook) alongside the host's discovered classes. When the host has
237
+ // no chain, we still wrap in a plain `<div>` so the inner shape is
238
+ // consistent for our utility selectors.
239
+ const frame = frameLink ? (
240
+ createElement(frameLink.tagName, { className: `conloca-code-block ${frameLink.className}` }, frameInner)
241
+ ) : (
242
+ <div className="conloca-code-block">{frameInner}</div>
243
+ );
244
+
245
+ // Wrap outer links from inside out. `reduceRight` so the first
246
+ // chain link ends up as the outermost rendered element.
247
+ return outerLinks.reduceRight<ReactElement>(
248
+ (kids, link) => createElement(link.tagName, { className: link.className }, kids),
249
+ frame,
250
+ );
251
+ }
252
+
253
+ /**
254
+ * Catch-all descriptor — `priority: 100`, `match: () => true` — registered
255
+ * via `codeBlockPlugin({ codeBlockEditorDescriptors: [conlocaCodeBlockDescriptor] })`.
256
+ * Wraps the upstream `CodeMirrorEditor` with the host-themed frame.
257
+ */
258
+ export const conlocaCodeBlockDescriptor: CodeBlockEditorDescriptor = {
259
+ priority: 100,
260
+ match: () => true,
261
+ Editor: ConlocaCodeBlockEditor,
262
+ };
@@ -0,0 +1,403 @@
1
+ import {
2
+ BlockTypeSelect,
3
+ BoldItalicUnderlineToggles,
4
+ ButtonWithTooltip,
5
+ ChangeCodeMirrorLanguage,
6
+ ConditionalContents,
7
+ CreateLink,
8
+ codeBlockPlugin,
9
+ codeMirrorPlugin,
10
+ DiffSourceToggleWrapper,
11
+ diffSourcePlugin,
12
+ GenericJsxEditor,
13
+ HighlightToggle,
14
+ headingsPlugin,
15
+ InsertCodeBlock,
16
+ InsertImage,
17
+ InsertTable,
18
+ InsertThematicBreak,
19
+ imagePlugin,
20
+ type JsxComponentDescriptor,
21
+ jsxPlugin,
22
+ ListsToggle,
23
+ linkDialogPlugin,
24
+ linkPlugin,
25
+ listsPlugin,
26
+ MDXEditor as MDXEditorLib,
27
+ type MDXEditorMethods,
28
+ markdownShortcutPlugin,
29
+ quotePlugin,
30
+ type RealmPlugin,
31
+ Separator,
32
+ StrikeThroughSupSubToggles,
33
+ tablePlugin,
34
+ thematicBreakPlugin,
35
+ toolbarPlugin,
36
+ UndoRedo,
37
+ } from '@mdxeditor/editor';
38
+ import { Maximize2, Minimize2 } from 'lucide-react';
39
+ import React, { useCallback, useEffect, useImperativeHandle, useRef, useSyncExternalStore } from 'react';
40
+ import { conlocaCodeBlockDescriptor } from './code-block-frame.js';
41
+ import { joinEsm, type PreservedEsm, splitEsm } from './esm-passthrough.js';
42
+ import { TO_MARKDOWN_OPTIONS } from './markdown-options.js';
43
+
44
+ const FOCUS_MODE_STORAGE_KEY = 'conloca.mdxeditor.focusMode';
45
+ const FOCUS_MODE_BODY_CLASS = 'mdxeditor-focus-mode';
46
+
47
+ /**
48
+ * Toggle focus-mode by writing the class on `document.body`. Direct DOM
49
+ * mutation (vs. piping a boolean through React state into the editor's
50
+ * `className` prop) avoids re-rendering Lexical on every toggle — the
51
+ * editor's prop is the only entry point and changing it forces a parse
52
+ * round-trip. Persisted in localStorage so the preference survives reloads.
53
+ */
54
+ function readFocusMode(): boolean {
55
+ if (typeof document === 'undefined') return false;
56
+ return document.body.classList.contains(FOCUS_MODE_BODY_CLASS);
57
+ }
58
+
59
+ function subscribeFocusMode(callback: () => void): () => void {
60
+ if (typeof window === 'undefined') return () => {};
61
+ const handler = () => callback();
62
+ window.addEventListener('conloca:focusModeChange', handler);
63
+ return () => window.removeEventListener('conloca:focusModeChange', handler);
64
+ }
65
+
66
+ function setFocusMode(next: boolean): void {
67
+ if (typeof document === 'undefined') return;
68
+ document.body.classList.toggle(FOCUS_MODE_BODY_CLASS, next);
69
+ try {
70
+ if (next) {
71
+ window.localStorage.setItem(FOCUS_MODE_STORAGE_KEY, '1');
72
+ } else {
73
+ window.localStorage.removeItem(FOCUS_MODE_STORAGE_KEY);
74
+ }
75
+ } catch {
76
+ // localStorage may be unavailable (private mode, SSR) — ignore.
77
+ }
78
+ window.dispatchEvent(new Event('conloca:focusModeChange'));
79
+ }
80
+
81
+ function FocusModeToggle() {
82
+ const focusMode = useSyncExternalStore(subscribeFocusMode, readFocusMode, () => false);
83
+ const onClick = useCallback(() => setFocusMode(!focusMode), [focusMode]);
84
+ const Icon = focusMode ? Minimize2 : Maximize2;
85
+ return (
86
+ <ButtonWithTooltip
87
+ title={focusMode ? 'Exit focus mode (wider column)' : 'Enter focus mode (narrow column)'}
88
+ onClick={onClick}
89
+ >
90
+ <Icon size={16} aria-hidden />
91
+ </ButtonWithTooltip>
92
+ );
93
+ }
94
+
95
+ export interface BaseMDXEditorProps {
96
+ value: string;
97
+ /**
98
+ * Called whenever the editor content changes. The second argument is `true`
99
+ * the first time the library normalizes the parsed markdown back to its
100
+ * canonical form (bullet style, trailing newline, etc.) — consumers tracking
101
+ * dirty state should treat that call as a re-baseline rather than a user
102
+ * edit, otherwise the editor looks dirty the moment the page loads.
103
+ */
104
+ onChange: (value: string, initialMarkdownNormalize?: boolean) => void;
105
+ onSave?: (value: string) => void;
106
+ readOnly?: boolean;
107
+ imageDialog?: React.FC | null;
108
+ disableImageSettingsButton?: boolean;
109
+ onImageShortcut?: () => void;
110
+ imageButtonRef?: React.Ref<HTMLButtonElement>;
111
+ /**
112
+ * Upload handler for images pasted or dropped directly into the editor. When
113
+ * provided, the underlying imagePlugin will route those events through this
114
+ * function and insert the returned URL as the image src. Independent of the
115
+ * library/picker `imageDialog` flow — both can be active simultaneously.
116
+ */
117
+ imageUploadHandler?: (file: File) => Promise<string>;
118
+ jsxComponentDescriptors?: JsxComponentDescriptor[];
119
+ /**
120
+ * Additional @mdxeditor/editor RealmPlugins appended to the built-in
121
+ * plugin list. Used by the SPA shell to register the MDX components
122
+ * registry-driven slash menu without coupling @conloca/mdx to
123
+ * @conloca/cms-spa.
124
+ */
125
+ extraPlugins?: RealmPlugin[];
126
+ /**
127
+ * Extra toolbar buttons inserted between `<InsertAdmonition />` and the
128
+ * separator preceding focus mode. Pass `null` (default) to keep the
129
+ * stock toolbar.
130
+ */
131
+ extraToolbarItems?: React.ReactNode;
132
+ /**
133
+ * Class applied to the MDXEditor root element (library forwards it to the
134
+ * toolbar and portaled popups too). Pass `"dark-theme"` to activate the
135
+ * library's built-in Radix dark palette.
136
+ * See https://mdxeditor.dev/editor/docs/theming
137
+ */
138
+ className?: string;
139
+ /** Placeholder shown when the editor is empty. Forwarded to MDXEditorLib. */
140
+ placeholder?: React.ReactNode;
141
+ /** Auto-focus the editor on mount. Forwarded to MDXEditorLib. */
142
+ autoFocus?: boolean | { defaultSelection?: 'rootStart' | 'rootEnd'; preventScroll?: boolean };
143
+ }
144
+
145
+ // The empty-string entry is the documented escape hatch for code blocks
146
+ // authored without a language hint. Without it, fences like ```\nfoo\n``` (which
147
+ // the parser tags as language `null` / meta `'N/A'`) trip a hard error in
148
+ // older versions and emit a noisy warning even on v3.55+. See mdx-editor/editor
149
+ // issues #370, #423, #463, #885, #886, #901.
150
+ const codeBlockLanguages: Record<string, string> = {
151
+ '': 'Plain text',
152
+ text: 'Plain Text',
153
+ js: 'JavaScript',
154
+ jsx: 'JavaScript (React)',
155
+ ts: 'TypeScript',
156
+ tsx: 'TypeScript (React)',
157
+ css: 'CSS',
158
+ html: 'HTML',
159
+ json: 'JSON',
160
+ md: 'Markdown',
161
+ mdx: 'MDX',
162
+ bash: 'Bash',
163
+ python: 'Python',
164
+ };
165
+
166
+ /**
167
+ * Wildcard fallback so any unknown JSX tag round-trips through GenericJsxEditor
168
+ * instead of crashing the importer with "Parsing of the following markdown
169
+ * structure failed". Two entries because the upstream visitor dispatches by
170
+ * `kind` (block vs inline JSX) — without the inline one, an inline `<Badge>`
171
+ * mid-paragraph would be matched by the flow wildcard and lifted out of its
172
+ * paragraph in Lexical. Consumers passing typed descriptors win via the
173
+ * exact-name match in the visitor; the wildcard only handles the leftovers.
174
+ */
175
+ const wildcardJsxDescriptors: JsxComponentDescriptor[] = [
176
+ { name: '*', kind: 'flow', props: [], hasChildren: true, Editor: GenericJsxEditor },
177
+ { name: '*', kind: 'text', props: [], hasChildren: true, Editor: GenericJsxEditor },
178
+ ];
179
+
180
+ function renderInsertImageButton(imageButtonRef?: React.Ref<HTMLButtonElement>) {
181
+ if (!imageButtonRef) {
182
+ return <InsertImage />;
183
+ }
184
+
185
+ return React.createElement(InsertImage as unknown as React.FC<{ ref: React.Ref<HTMLButtonElement> }>, {
186
+ ref: imageButtonRef,
187
+ });
188
+ }
189
+
190
+ /**
191
+ * Restore the persisted focus-mode preference on first import. Runs once at
192
+ * module load so the class is in place before any editor mounts — avoids a
193
+ * flash of wide column when the user previously selected focus mode.
194
+ */
195
+ if (typeof window !== 'undefined') {
196
+ try {
197
+ if (window.localStorage.getItem(FOCUS_MODE_STORAGE_KEY) === '1') {
198
+ document.body.classList.add(FOCUS_MODE_BODY_CLASS);
199
+ }
200
+ } catch {
201
+ // ignore
202
+ }
203
+ }
204
+
205
+ export const BaseMDXEditor = React.forwardRef<MDXEditorMethods, BaseMDXEditorProps>(
206
+ (
207
+ {
208
+ value,
209
+ onChange,
210
+ onSave,
211
+ readOnly = false,
212
+ imageDialog,
213
+ disableImageSettingsButton = false,
214
+ onImageShortcut,
215
+ imageButtonRef,
216
+ imageUploadHandler,
217
+ jsxComponentDescriptors,
218
+ extraPlugins,
219
+ extraToolbarItems,
220
+ className,
221
+ placeholder,
222
+ autoFocus,
223
+ },
224
+ ref,
225
+ ) => {
226
+ // The library reads `markdown` once, as `initialMarkdown`, and consumers
227
+ // swap documents by remounting (see the `key=` on MdxPageEditor's and
228
+ // FragmentEditor's editors). So the ESM lifted off the document belongs to
229
+ // whatever the editor was *seeded* with — re-deriving it from `value` would
230
+ // parse the whole document on every keystroke and would be wrong if the
231
+ // prop ever changed without a remount.
232
+ const seededRef = useRef<PreservedEsm | null>(null);
233
+ seededRef.current ??= splitEsm(value);
234
+ // Known consequence: the editor is seeded with the stripped body, so the
235
+ // Source and Diff views (diffSourcePlugin, below) show a document without
236
+ // the import block even though the committed file has it. Data is safe —
237
+ // retyping an import there is reconciled by `joinEsm` against the preserved
238
+ // bindings rather than declared twice — but the raw view is not a faithful
239
+ // picture of the file on disk. Fixing that needs the library to render ESM
240
+ // it cannot represent in rich-text mode.
241
+
242
+ const innerRef = useRef<MDXEditorMethods>(null);
243
+
244
+ // Everything leaving the editor gets the author's import/export block put
245
+ // back verbatim. `onChange` is the save path; the imperative handle is
246
+ // intercepted too so `getMarkdown()` never reports a document that is
247
+ // missing statements the file on disk has.
248
+ const handleChange = useCallback(
249
+ (markdown: string, initialMarkdownNormalize?: boolean) => {
250
+ const preserved = seededRef.current;
251
+ onChange(preserved === null ? markdown : joinEsm(preserved, markdown), initialMarkdownNormalize);
252
+ },
253
+ [onChange],
254
+ );
255
+
256
+ useImperativeHandle(
257
+ ref,
258
+ () => ({
259
+ getMarkdown: () => {
260
+ const markdown = innerRef.current?.getMarkdown() ?? '';
261
+ const preserved = seededRef.current;
262
+ return preserved === null ? markdown : joinEsm(preserved, markdown);
263
+ },
264
+ // Replaces the whole document, so its ESM becomes the preserved block.
265
+ setMarkdown: (markdown: string) => {
266
+ const split = splitEsm(markdown);
267
+ seededRef.current = split;
268
+ innerRef.current?.setMarkdown(split.body);
269
+ },
270
+ // Inserts at the cursor rather than reseeding, so the preserved block is
271
+ // unaffected. ESM in inserted markdown is dropped by the library, as
272
+ // before — the editor has never been able to author new imports.
273
+ insertMarkdown: (markdown: string) => innerRef.current?.insertMarkdown(markdown),
274
+ focus: (
275
+ callbackFn?: () => void,
276
+ opts?: { defaultSelection?: 'rootStart' | 'rootEnd'; preventScroll?: boolean },
277
+ ) => innerRef.current?.focus(callbackFn, opts),
278
+ getContentEditableHTML: () => innerRef.current?.getContentEditableHTML() ?? '',
279
+ getSelectionMarkdown: () => innerRef.current?.getSelectionMarkdown() ?? '',
280
+ }),
281
+ [],
282
+ );
283
+
284
+ useEffect(() => {
285
+ const handleKeyDown = (event: KeyboardEvent) => {
286
+ if ((event.ctrlKey || event.metaKey) && event.key === 's') {
287
+ event.preventDefault();
288
+ onSave?.(value);
289
+ }
290
+
291
+ if ((event.ctrlKey || event.metaKey) && event.shiftKey && event.key.toLowerCase() === 'i') {
292
+ if (!onImageShortcut) {
293
+ return;
294
+ }
295
+
296
+ event.preventDefault();
297
+ onImageShortcut();
298
+ }
299
+ };
300
+
301
+ document.addEventListener('keydown', handleKeyDown);
302
+ return () => document.removeEventListener('keydown', handleKeyDown);
303
+ }, [onImageShortcut, onSave, value]);
304
+
305
+ return (
306
+ <MDXEditorLib
307
+ ref={innerRef}
308
+ markdown={seededRef.current.body}
309
+ toMarkdownOptions={TO_MARKDOWN_OPTIONS}
310
+ onChange={handleChange}
311
+ onError={({ error, source }) => {
312
+ // Library invokes this synchronously inside a gurx signal, so don't
313
+ // setState here — that triggers a render-phase warning (#872).
314
+ // Logging only is enough; the React error boundary still catches
315
+ // anything that escapes from rendering.
316
+ console.error('[MDXEditor] parse error:', error, '\nsource:', source);
317
+ }}
318
+ readOnly={readOnly}
319
+ className={className}
320
+ placeholder={placeholder}
321
+ autoFocus={autoFocus}
322
+ contentEditableClassName="conloca-prose conloca-prose--editor"
323
+ plugins={[
324
+ headingsPlugin(),
325
+ listsPlugin(),
326
+ quotePlugin(),
327
+ linkPlugin(),
328
+ linkDialogPlugin(),
329
+ tablePlugin(),
330
+ thematicBreakPlugin(),
331
+ // frontmatterPlugin intentionally omitted: metadata (title,
332
+ // description, id, created, modified) is server-owned and stripped
333
+ // from `content.mdx` on load. Re-introducing the plugin would let
334
+ // the editor round-trip a YAML block as body text, corrupting the
335
+ // file when content is inserted above it.
336
+ codeBlockPlugin({
337
+ defaultCodeBlockLanguage: 'ts',
338
+ codeBlockEditorDescriptors: [conlocaCodeBlockDescriptor],
339
+ }),
340
+ codeMirrorPlugin({ codeBlockLanguages }),
341
+ diffSourcePlugin({ viewMode: 'rich-text' }),
342
+ markdownShortcutPlugin(),
343
+ jsxPlugin({
344
+ jsxComponentDescriptors: [...(jsxComponentDescriptors ?? []), ...wildcardJsxDescriptors],
345
+ }),
346
+ imagePlugin({
347
+ ...(imageDialog ? { ImageDialog: imageDialog, disableImageSettingsButton } : {}),
348
+ ...(imageUploadHandler ? { imageUploadHandler } : {}),
349
+ }),
350
+ ...(extraPlugins ?? []),
351
+ toolbarPlugin({
352
+ // flex-wrap so the toolbar reflows on narrow viewports instead of
353
+ // overflowing horizontally — workaround documented in
354
+ // mdx-editor/editor#908.
355
+ toolbarClassName: 'mdxeditor-toolbar-wrap',
356
+ toolbarContents: () => (
357
+ <DiffSourceToggleWrapper>
358
+ <ConditionalContents
359
+ options={[
360
+ {
361
+ // When the user clicks into a code block, swap most of
362
+ // the rich-text toolbar for the language picker — those
363
+ // controls are no-ops inside CodeMirror anyway.
364
+ when: (editor) => editor?.editorType === 'codeblock',
365
+ contents: () => <ChangeCodeMirrorLanguage />,
366
+ },
367
+ {
368
+ fallback: () => (
369
+ <>
370
+ <UndoRedo />
371
+ <Separator />
372
+ <BoldItalicUnderlineToggles />
373
+ <StrikeThroughSupSubToggles />
374
+ <HighlightToggle />
375
+ <Separator />
376
+ <ListsToggle />
377
+ <Separator />
378
+ <BlockTypeSelect />
379
+ <Separator />
380
+ <CreateLink />
381
+ {renderInsertImageButton(imageButtonRef)}
382
+ <InsertTable />
383
+ <InsertThematicBreak />
384
+ <Separator />
385
+ <InsertCodeBlock />
386
+ {extraToolbarItems}
387
+ <Separator />
388
+ <FocusModeToggle />
389
+ </>
390
+ ),
391
+ },
392
+ ]}
393
+ />
394
+ </DiffSourceToggleWrapper>
395
+ ),
396
+ }),
397
+ ]}
398
+ />
399
+ );
400
+ },
401
+ );
402
+
403
+ BaseMDXEditor.displayName = 'BaseMDXEditor';