@mieweb/ui 0.10.0-dev.4 → 0.10.0-dev.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/kerebron.cjs CHANGED
@@ -25,18 +25,32 @@ var SafeAdvancedEditorKit = class {
25
25
  }
26
26
  };
27
27
  async function createEditorKits(config) {
28
- if (!config) return [new SafeAdvancedEditorKit(false)];
29
- const { HuddleYjsKit, defaultWsUrl } = await import('./collabKit-GCRHP25F.cjs');
30
- const url = config.wsUrl ?? defaultWsUrl();
31
- return [
32
- new SafeAdvancedEditorKit(true),
33
- new HuddleYjsKit(
34
- url,
35
- config.params ?? {},
36
- config.WebSocketPolyfill,
37
- config.user
38
- )
39
- ];
28
+ if (!config) {
29
+ return { kits: [new SafeAdvancedEditorKit(false)], collaborative: false };
30
+ }
31
+ try {
32
+ const { HuddleYjsKit, defaultWsUrl } = await import('./collabKit-GCRHP25F.cjs');
33
+ const url = config.wsUrl ?? defaultWsUrl();
34
+ return {
35
+ kits: [
36
+ new SafeAdvancedEditorKit(true),
37
+ new HuddleYjsKit(
38
+ url,
39
+ config.params ?? {},
40
+ config.WebSocketPolyfill,
41
+ config.user
42
+ )
43
+ ],
44
+ collaborative: true
45
+ };
46
+ } catch (error) {
47
+ console.warn(
48
+ "[RichEditor] Collaborative editing unavailable \u2014 the Yjs kit failed to load. Continuing as a local editor.",
49
+ error
50
+ );
51
+ config.onUnavailable?.(error);
52
+ return { kits: [new SafeAdvancedEditorKit(false)], collaborative: false };
53
+ }
40
54
  }
41
55
  var MARKDOWN_TYPE = "text/x-markdown";
42
56
  var initialLoadQueue = Promise.resolve();
@@ -105,7 +119,7 @@ var RichEditor = react.forwardRef(
105
119
  }
106
120
  };
107
121
  const setup = async () => {
108
- const editorKits = await createEditorKits(collab);
122
+ const { kits: editorKits, collaborative } = await createEditorKits(collab);
109
123
  if (disposed) return;
110
124
  editor$1 = editor.CoreEditor.create({
111
125
  element: mount,
@@ -127,7 +141,7 @@ var RichEditor = react.forwardRef(
127
141
  });
128
142
  editor$1.addEventListener("transaction", onTransaction);
129
143
  const joinRoom = () => {
130
- if (collab && editor$1 && !disposed) {
144
+ if (collaborative && collab && editor$1 && !disposed) {
131
145
  editor$1.run.changeRoom?.(collab.room);
132
146
  reseedWhenRoomStaysEmpty();
133
147
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/components/RichEditor/editorKits.ts","../src/components/RichEditor/RichEditor.tsx","../src/components/RichEditor/CodeEditor.tsx"],"names":["AdvancedEditorKit","forwardRef","RichEditor","useIsDarkMode","useRef","useState","useEffect","editor","CoreEditor","createAssetLoad","useImperativeHandle","jsx","jsxs","CodeEditorKit"],"mappings":";;;;;;;;;;;AA4DA,IAAM,gBAAA,GAAmB,CAAC,cAAA,EAAgB,OAAO,CAAA;AAIjD,IAAM,wBAAN,MAAiD;AAAA,EAE/C,YAA6B,SAAA,EAAoB;AAApB,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AAAA,EAAqB;AAAA,EAArB,SAAA;AAAA,EAD7B,IAAA,GAAO,iBAAA;AAAA,EAGP,aAAA,GAAgB;AACd,IAAA,MAAM,OAAA,GAAoB,CAAC,GAAG,gBAAgB,CAAA;AAC9C,IAAA,IAAI,IAAA,CAAK,SAAA,EAAW,OAAA,CAAQ,IAAA,CAAK,SAAS,CAAA;AAE1C,IAAA,OAAO,IAAIA,mCAAA,EAAkB,CAC1B,aAAA,EAAc,CACd,MAAA;AAAA,MACC,CAAC,cACC,EAAE,MAAA,IAAU,aAAa,OAAA,CAAQ,QAAA,CAAS,UAAU,IAAI,CAAA;AAAA,KAC5D;AAAA,EACJ;AACF,CAAA;AAWA,eAAsB,iBACpB,MAAA,EACsB;AACtB,EAAA,IAAI,CAAC,MAAA,EAAQ,OAAO,CAAC,IAAI,qBAAA,CAAsB,KAAK,CAAC,CAAA;AAErD,EAAA,MAAM,EAAE,YAAA,EAAc,YAAA,EAAa,GAAI,MAAM,OAAO,0BAAa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EAAE,CAAA;AAEL,EAAA,uBACEI,cAAAA,CAAC,KAAA,EAAA,EACC,QAAA,kBAAAA,eAAC,KAAA,EAAA,EACC,QAAA,kBAAAA,cAAAA,CAAC,KAAA,EAAA,EAAI,GAAA,EAAK,SAAA,EAAW,SAAA,EAAU,cAAA,EAAe,GAChD,CAAA,EACF,CAAA;AAEJ;AAEA,UAAA,CAAW,WAAA,GAAc,YAAA","file":"kerebron.cjs","sourcesContent":["/**\n * Editor kit assembly for {@link RichEditor}, for both plain and collaborative\n * (Yjs) mode.\n *\n * Both modes start from {@link AdvancedEditorKit} and drop the extensions that\n * are unsafe for our usage — see {@link unsafeExtensions} — then collaborative\n * mode adds the Yjs pieces on top.\n *\n * The Yjs pieces live in `collabKit.ts` behind a dynamic `import()`, so\n * `@kerebron/extension-yjs`, `yjs` and `y-protocols` remain truly optional\n * peers — plain-mode consumers never load them.\n */\nimport type { EditorKit } from '@kerebron/editor';\nimport { AdvancedEditorKit } from '@kerebron/editor-kits/AdvancedEditorKit';\n\nexport interface CollabConfig {\n /** Room id — one shared document per room (e.g. a post id). */\n room: string;\n /**\n * WebSocket base URL for the Yjs relay. Defaults to\n * `<ws|wss>://<location.host>/yjs`. The room id is appended by the provider.\n */\n wsUrl?: string;\n /** Extra query params for the socket (e.g. `{ token }` for auth). */\n params?: Record<string, string>;\n /**\n * Who this editor is, published on awareness (`kerebron:user`) so peers see\n * a named, coloured cursor. Without it remote cursors do not render — the\n * position plugin skips awareness states that carry no user — and the\n * `id` is what the cursor colour is derived from (kerebron's `User` shape).\n */\n user?: { id: string; name: string; color?: string };\n /**\n * Custom WebSocket implementation handed to the Yjs provider — e.g. a\n * loopback socket for demos/tests, or a polyfill outside the browser.\n * Defaults to `globalThis.WebSocket`.\n */\n WebSocketPolyfill?: typeof globalThis.WebSocket;\n}\n\n/**\n * Extensions dropped from {@link AdvancedEditorKit}, and why.\n *\n * `autocomplete` and `hover` debounce their DOM handlers (200ms) and then call\n * `dispatchMeta`, which reads `this.editor.state` with no guard that the editor\n * is still alive. Any teardown or document swap inside that debounce window\n * lands the deferred call on a dead view and throws\n * `null.matchesNode()` inside ProseMirror's `EditorView.updateStateInner`,\n * leaving the view permanently broken. Two ways to hit it:\n * - remount (e.g. a `key` change) while the pointer is over the editor, which\n * fires the debounced `onMouseLeave` after the view is destroyed;\n * - a Yjs remote update replacing the document tree under a pending callback.\n * The first applies to *every* editor, so both extensions come out in both\n * modes. No functional cost — autocomplete popups and node-hover tooltips are\n * compositor conveniences, not required for editing.\n *\n * `history` is collab-only: ExtensionYjs supplies its own CRDT-aware undo/redo\n * and the editor throws `Extension conflict: yjs vs history` if both are\n * present. Plain mode keeps it, so undo/redo still works there.\n */\nconst unsafeExtensions = ['autocomplete', 'hover'] as const;\n\n/** {@link AdvancedEditorKit} minus {@link unsafeExtensions} (and, for collab\n * mode, minus `history`). */\nclass SafeAdvancedEditorKit implements EditorKit {\n name = 'advanced-editor';\n constructor(private readonly forCollab: boolean) {}\n\n getExtensions() {\n const dropped: string[] = [...unsafeExtensions];\n if (this.forCollab) dropped.push('history');\n\n return new AdvancedEditorKit()\n .getExtensions()\n .filter(\n (extension) =>\n !('name' in extension && dropped.includes(extension.name))\n );\n }\n}\n\n/** MarkYChange + ExtensionYjs live in `collabKit.ts` (lazy-loaded). */\n\n/**\n * Build the editor kits for a session. Pass `config` to join a collaborative\n * room; omit it for a plain local editor.\n *\n * Async because collaborative mode lazy-loads the Yjs kit (and its optional\n * peer deps) on first use; plain mode resolves immediately.\n */\nexport async function createEditorKits(\n config?: CollabConfig\n): Promise<EditorKit[]> {\n if (!config) return [new SafeAdvancedEditorKit(false)];\n\n const { HuddleYjsKit, defaultWsUrl } = await import('./collabKit');\n const url = config.wsUrl ?? defaultWsUrl();\n return [\n new SafeAdvancedEditorKit(true),\n new HuddleYjsKit(\n url,\n config.params ?? {},\n config.WebSocketPolyfill,\n config.user\n ),\n ];\n}\n","'use client';\n\nimport {\n forwardRef,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from 'react';\n\nimport { CoreEditor, type AssetLoad } from '@kerebron/editor';\nimport { createAssetLoad } from '@kerebron/wasm/web';\n\nimport { useIsDarkMode } from '../../hooks/useIsDarkMode';\nimport { createEditorKits, type CollabConfig } from './editorKits';\n\nexport type { CollabConfig } from './editorKits';\n\nconst MARKDOWN_TYPE = 'text/x-markdown';\n\n/**\n * The markdown converter's tree-sitter WASM init is not concurrency-safe, so\n * every editor's *first* load queues behind the previous one. Later loads (a\n * `value` change) are free — by then the grammars are warm.\n */\nlet initialLoadQueue: Promise<unknown> = Promise.resolve();\n\nfunction queueInitialLoad(load: () => Promise<void>): Promise<void> {\n const queued = initialLoadQueue.catch(() => undefined).then(load);\n initialLoadQueue = queued.catch(() => undefined);\n return queued;\n}\n\nexport interface RichEditorProps {\n /** Markdown to load. Changing it reloads the editor unless `collab` is set. */\n value?: string;\n /** Called with the editor's markdown content whenever it changes. */\n onChange?: (value: string) => void;\n /** Whether to render the live markdown output preview. Defaults to `false`. */\n showPreview?: boolean;\n /**\n * Enable live collaborative editing (Yjs) for the given room. When set, the\n * editor connects to the `/yjs` websocket relay and every peer in the same\n * `room` co-edits one shared document. Uncontrolled like `value` — remount via\n * `key` to switch rooms.\n */\n collab?: CollabConfig;\n /** Read-only surface: no typing, and the content dims. */\n disabled?: boolean;\n /**\n * Id for the editor host element — an `aria-labelledby`/`aria-describedby`\n * anchor. The host is a `div`, not a labelable control, so a\n * `<label htmlFor>` will not associate; name the editor with `aria-label`\n * or `aria-labelledby` instead.\n */\n id?: string;\n /** Extra classes on the editor surface, beside `kb-component`. */\n className?: string;\n 'aria-label'?: string;\n 'aria-labelledby'?: string;\n /**\n * Where the tree-sitter WASM grammars load from. Defaults to\n * `createAssetLoad('/kerebron-wasm')`; supply your own when the host serves\n * `@kerebron/wasm`'s `assets/` somewhere else.\n */\n assetLoad?: AssetLoad;\n}\n\nexport interface RichEditorHandle {\n /**\n * The editor's markdown, awaiting the initial load. `onChange` can lag the\n * last keystroke, so read this on submit rather than trusting mirrored state.\n */\n getContent: () => Promise<string>;\n /** Focus the editor, restoring the caret where the writer left it. */\n focus: () => void;\n}\n\n/**\n * Markdown editor over Kerebron's `CoreEditor`.\n *\n * The editor mounts into a **disposable child div**: `CoreEditor.destroy()`\n * replaces its host element with a clone, which would strand React's ref (and,\n * under StrictMode's double-mount, leave the live editor detached behind a\n * dead clone).\n */\nconst RichEditor = forwardRef<RichEditorHandle, RichEditorProps>(\n function RichEditor(\n {\n value = '',\n onChange,\n showPreview = false,\n collab,\n disabled = false,\n id,\n className,\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledBy,\n assetLoad,\n },\n ref\n ) {\n const isDark = useIsDarkMode();\n const hostRef = useRef<HTMLDivElement>(null);\n const editorInstance = useRef<CoreEditor | null>(null);\n const onChangeRef = useRef(onChange);\n onChangeRef.current = onChange;\n // Mirrors what the editor last held, so an echo of our own `onChange`\n // doesn't reload the document out from under the caret.\n const valueRef = useRef(value);\n const readyRef = useRef<Promise<void> | null>(null);\n const loadingRef = useRef(false);\n const disabledRef = useRef(disabled);\n\n const [md, setMd] = useState<string>('');\n\n useEffect(() => {\n disabledRef.current = disabled;\n editorInstance.current?.view.setProps({\n editable: () => !disabledRef.current,\n });\n }, [disabled]);\n\n useEffect(() => {\n // In collab mode the CRDT owns the content; reloading would fight it.\n if (collab || value === valueRef.current) return;\n valueRef.current = value;\n const editor = editorInstance.current;\n if (!editor) return;\n\n loadingRef.current = true;\n void editor\n .loadDocumentText(MARKDOWN_TYPE, value)\n .catch(() => undefined)\n .finally(() => {\n if (editorInstance.current === editor) loadingRef.current = false;\n });\n // `collab` is fixed for the lifetime of the instance.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [value]);\n\n useEffect(() => {\n if (!hostRef.current) return;\n const host = hostRef.current;\n\n // Set on cleanup so async continuations (kit loading and the\n // `loadDocumentText` chain) don't touch the editor after `destroy()`.\n let disposed = false;\n let editor: CoreEditor | null = null;\n\n const mount = document.createElement('div');\n host.appendChild(mount);\n\n // Listen to transactions and update markdown preview\n const onTransaction = async () => {\n // Programmatic loads are not edits — reporting them would echo the\n // caller's own `value` back through `onChange`.\n if (loadingRef.current || !editorInstance.current) return;\n\n try {\n const buffer =\n await editorInstance.current.saveDocument(MARKDOWN_TYPE);\n const markdown = new globalThis.TextDecoder().decode(buffer);\n if (disposed) return;\n valueRef.current = markdown;\n setMd(markdown);\n onChangeRef.current?.(markdown);\n } catch (err) {\n console.error('Failed to save markdown:', err);\n }\n };\n\n // Initialize the editor. Both modes drop the teardown-unsafe extensions;\n // collaborative mode additionally swaps `history` for the Yjs CRDT sync\n // and lazy-loads the Yjs kit (see `editorKits.ts` for why).\n const setup = async () => {\n const editorKits = await createEditorKits(collab);\n if (disposed) return;\n\n editor = CoreEditor.create({\n element: mount,\n uri: 'file:///untitled.md',\n assetLoad: assetLoad ?? createAssetLoad('/kerebron-wasm'),\n editorKits,\n readOnly: disabledRef.current,\n });\n\n editorInstance.current = editor;\n // The contenteditable surface has no implicit ARIA role, so labeling\n // attributes are only permitted alongside an explicit textbox role.\n const surfaceAttributes =\n ariaLabel || ariaLabelledBy\n ? {\n role: 'textbox',\n 'aria-multiline': 'true',\n ...(ariaLabel ? { 'aria-label': ariaLabel } : {}),\n ...(ariaLabelledBy\n ? { 'aria-labelledby': ariaLabelledBy }\n : {}),\n }\n : null;\n editor.view.setProps({\n editable: () => !disabledRef.current,\n ...(surfaceAttributes ? { attributes: surfaceAttributes } : {}),\n });\n editor.addEventListener('transaction', onTransaction);\n\n // Seed initial content, then populate the preview once on mount.\n //\n // In collaborative mode we still load the local markdown first, then\n // join the room: the Yjs binding seeds an *empty* shared document from\n // this content on the first join, and overwrites the editor with the\n // shared content when the room already has edits — so the stored\n // markdown is the starting point without ever double-inserting.\n const joinRoom = () => {\n if (collab && editor && !disposed) {\n (\n editor.run as Record<string, (...args: unknown[]) => boolean>\n ).changeRoom?.(collab.room);\n reseedWhenRoomStaysEmpty();\n }\n };\n\n // The Yjs binding is supposed to seed an empty room from the local\n // content, but the sync import can land as an overwrite that blanks\n // the just-loaded seed (observed with extension-yjs 0.8.x). Heal it:\n // once the join settles, an empty document with a non-empty seed\n // means nobody's content won — reload the seed, which the binding\n // then pushes into the room. Joiners pass no value, so exactly one\n // participant ever does this.\n const seed = valueRef.current;\n const reseedWhenRoomStaysEmpty = () => {\n if (!seed) return;\n const check = async (attempt: number) => {\n if (disposed || !editorInstance.current) return;\n try {\n const buffer =\n await editorInstance.current.saveDocument(MARKDOWN_TYPE);\n const current = new globalThis.TextDecoder()\n .decode(buffer)\n .trim();\n if (disposed || !editorInstance.current) return;\n if (current) return; // somebody's content arrived — done\n if (attempt >= 2) {\n await editorInstance.current.loadDocumentText(\n MARKDOWN_TYPE,\n seed\n );\n return;\n }\n setTimeout(() => void check(attempt + 1), 300);\n } catch {\n // A failed probe must not break the editor; the room stays as-is.\n }\n };\n setTimeout(() => void check(0), 300);\n };\n\n if (valueRef.current) {\n await queueInitialLoad(() =>\n editor!.loadDocumentText(MARKDOWN_TYPE, valueRef.current)\n );\n await onTransaction();\n joinRoom();\n } else {\n void onTransaction();\n joinRoom();\n }\n };\n\n readyRef.current = setup().catch((err) =>\n console.error('Failed to set up editor:', err)\n );\n\n // Cleanup on unmount\n return () => {\n disposed = true;\n editorInstance.current = null; // makes onTransaction's guard effective\n editor?.removeEventListener('transaction', onTransaction);\n editor?.destroy();\n readyRef.current = null;\n host.replaceChildren();\n };\n // Initial `value`/`collab` are intentionally only applied on mount\n // (uncontrolled). Remount via `key` to switch rooms.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useImperativeHandle(\n ref,\n () => ({\n getContent: async (): Promise<string> => {\n await readyRef.current;\n const editor = editorInstance.current;\n if (!editor) return valueRef.current;\n const buffer = await editor.saveDocument(MARKDOWN_TYPE);\n const markdown = new globalThis.TextDecoder().decode(buffer);\n valueRef.current = markdown;\n return markdown;\n },\n focus: (): void => {\n const apply = (): void => {\n const view = editorInstance.current?.view as\n | { focus?: () => void }\n | undefined;\n if (view?.focus) {\n view.focus();\n return;\n }\n hostRef.current\n ?.querySelector<HTMLElement>('[contenteditable=\"true\"], textarea')\n ?.focus();\n };\n // Callers focus on mount; the editor may still be loading its kits.\n if (editorInstance.current) apply();\n else void readyRef.current?.then(apply);\n },\n }),\n []\n );\n\n return (\n <div>\n <div>\n <div\n ref={hostRef}\n id={id}\n className={[\n 'kb-component',\n isDark ? 'kb-component--dark' : '',\n className ?? '',\n ]\n .filter(Boolean)\n .join(' ')}\n aria-label={ariaLabel}\n aria-labelledby={ariaLabelledBy}\n aria-disabled={disabled || undefined}\n style={{\n isolation: 'isolate',\n opacity: disabled ? 0.65 : undefined,\n pointerEvents: disabled ? 'none' : undefined,\n }}\n />\n </div>\n\n {showPreview && (\n <div>\n <div>\n <h5>Markdown Output</h5>\n <pre>{md}</pre>\n </div>\n </div>\n )}\n </div>\n );\n }\n);\n\nRichEditor.displayName = 'RichEditor';\n\nexport { RichEditor };\n","import React, { useEffect, useRef } from 'react';\n\nimport { CoreEditor } from '@kerebron/editor';\nimport { CodeEditorKit } from '@kerebron/editor-kits/CodeEditorKit';\nimport { createAssetLoad } from '@kerebron/wasm/web';\n\nexport interface CodeEditorProps {\n /** Initial source code to load into the editor. */\n value?: string;\n /** Called with the editor's contents whenever they change. */\n onChange?: (value: string) => void;\n /** Language/grammar to use for syntax highlighting. Defaults to `typescript`. */\n lang?: string;\n}\n\nconst CodeEditor: React.FC<CodeEditorProps> = ({\n value = '',\n onChange,\n lang = 'typescript',\n}) => {\n const editorRef = useRef<HTMLDivElement>(null);\n const editorInstance = useRef<CoreEditor | null>(null);\n const onChangeRef = useRef(onChange);\n onChangeRef.current = onChange;\n\n useEffect(() => {\n const root = editorRef.current;\n if (!root) return;\n\n const applySelectLabel = () => {\n root.querySelectorAll('select.codejar-select').forEach((element) => {\n if (!element.getAttribute('aria-label')) {\n element.setAttribute('aria-label', 'Code editor language');\n }\n });\n };\n\n applySelectLabel();\n const observer = new MutationObserver(() => applySelectLabel());\n observer.observe(root, { childList: true, subtree: true });\n return () => observer.disconnect();\n }, []);\n\n useEffect(() => {\n if (!editorRef.current) return;\n\n // Initialize the editor\n const editor = CoreEditor.create({\n element: editorRef.current,\n uri: 'file:///untitled.ts',\n assetLoad: createAssetLoad('/kerebron-wasm'),\n editorKits: [new CodeEditorKit(lang)],\n });\n\n editorInstance.current = editor;\n\n // Surface edits to callers.\n const onTransaction = async () => {\n if (!editorInstance.current) return;\n\n try {\n const buffer = await editorInstance.current.saveDocument('text/plain');\n onChangeRef.current?.(new globalThis.TextDecoder().decode(buffer));\n } catch (err) {\n console.error('Failed to read code:', err);\n }\n };\n\n editor.addEventListener('transaction', onTransaction);\n\n // Seed initial content on mount.\n if (value) {\n editor\n .loadDocumentText('text/plain', value)\n .catch((err) => console.error('Failed to load code:', err));\n }\n\n // Cleanup on unmount\n return () => {\n editor.removeEventListener('transaction', onTransaction);\n editor.destroy();\n };\n // Initial `value`/`lang` are intentionally only applied on mount.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n <div>\n <div>\n <div ref={editorRef} className=\"kb-component\" />\n </div>\n </div>\n );\n};\n\nCodeEditor.displayName = 'CodeEditor';\n\nexport { CodeEditor };\n"]}
1
+ {"version":3,"sources":["../src/components/RichEditor/editorKits.ts","../src/components/RichEditor/RichEditor.tsx","../src/components/RichEditor/CodeEditor.tsx"],"names":["AdvancedEditorKit","forwardRef","RichEditor","useIsDarkMode","useRef","useState","useEffect","editor","CoreEditor","createAssetLoad","useImperativeHandle","jsx","jsxs","CodeEditorKit"],"mappings":";;;;;;;;;;;AAmFA,IAAM,gBAAA,GAAmB,CAAC,cAAA,EAAgB,OAAO,CAAA;AAIjD,IAAM,wBAAN,MAAiD;AAAA,EAE/C,YAA6B,SAAA,EAAoB;AAApB,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AAAA,EAAqB;AAAA,EAArB,SAAA;AAAA,EAD7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,UAAA,CAAW,WAAA,GAAc,YAAA","file":"kerebron.cjs","sourcesContent":["/**\n * Editor kit assembly for {@link RichEditor}, for both plain and collaborative\n * (Yjs) mode.\n *\n * Both modes start from {@link AdvancedEditorKit} and drop the extensions that\n * are unsafe for our usage — see {@link unsafeExtensions} — then collaborative\n * mode adds the Yjs pieces on top.\n *\n * The Yjs pieces live in `collabKit.ts` behind a dynamic `import()`, so\n * `@kerebron/extension-yjs`, `yjs` and `y-protocols` remain truly optional\n * peers — plain-mode consumers never load them.\n */\nimport type { EditorKit } from '@kerebron/editor';\nimport { AdvancedEditorKit } from '@kerebron/editor-kits/AdvancedEditorKit';\n\nexport interface CollabConfig {\n /** Room id — one shared document per room (e.g. a post id). */\n room: string;\n /**\n * WebSocket base URL for the Yjs relay. Defaults to\n * `<ws|wss>://<location.host>/yjs`. The room id is appended by the provider.\n */\n wsUrl?: string;\n /** Extra query params for the socket (e.g. `{ token }` for auth). */\n params?: Record<string, string>;\n /**\n * Who this editor is, published on awareness (`kerebron:user`) so peers see\n * a named, coloured cursor. Without it remote cursors do not render — the\n * position plugin skips awareness states that carry no user — and the\n * `id` is what the cursor colour is derived from (kerebron's `User` shape).\n */\n user?: { id: string; name: string; color?: string };\n /**\n * Custom WebSocket implementation handed to the Yjs provider — e.g. a\n * loopback socket for demos/tests, or a polyfill outside the browser.\n * Defaults to `globalThis.WebSocket`.\n */\n WebSocketPolyfill?: typeof globalThis.WebSocket;\n /**\n * Called when collaborative editing could not be started at all — the Yjs\n * kit failed to load (see {@link createEditorKits}). The editor mounts\n * anyway, as a local one; this is how the host finds out that edits are no\n * longer shared, so it can say so, or tear its own editor down if unshared\n * editing would be unsafe.\n *\n * Not for connection trouble: a room that is reachable but currently\n * disconnected still has the Yjs kit loaded, and the provider retries on its\n * own. This fires once, before the editor is created.\n */\n onUnavailable?: (error: unknown) => void;\n}\n\n/** What {@link createEditorKits} resolves to. */\nexport interface EditorKits {\n kits: EditorKit[];\n /**\n * Whether the returned kits can actually collaborate. False when `config`\n * asked for a room but the Yjs kit could not be loaded, so callers know not\n * to join one.\n */\n collaborative: boolean;\n}\n\n/**\n * Extensions dropped from {@link AdvancedEditorKit}, and why.\n *\n * `autocomplete` and `hover` debounce their DOM handlers (200ms) and then call\n * `dispatchMeta`, which reads `this.editor.state` with no guard that the editor\n * is still alive. Any teardown or document swap inside that debounce window\n * lands the deferred call on a dead view and throws\n * `null.matchesNode()` inside ProseMirror's `EditorView.updateStateInner`,\n * leaving the view permanently broken. Two ways to hit it:\n * - remount (e.g. a `key` change) while the pointer is over the editor, which\n * fires the debounced `onMouseLeave` after the view is destroyed;\n * - a Yjs remote update replacing the document tree under a pending callback.\n * The first applies to *every* editor, so both extensions come out in both\n * modes. No functional cost — autocomplete popups and node-hover tooltips are\n * compositor conveniences, not required for editing.\n *\n * `history` is collab-only: ExtensionYjs supplies its own CRDT-aware undo/redo\n * and the editor throws `Extension conflict: yjs vs history` if both are\n * present. Plain mode keeps it, so undo/redo still works there.\n */\nconst unsafeExtensions = ['autocomplete', 'hover'] as const;\n\n/** {@link AdvancedEditorKit} minus {@link unsafeExtensions} (and, for collab\n * mode, minus `history`). */\nclass SafeAdvancedEditorKit implements EditorKit {\n name = 'advanced-editor';\n constructor(private readonly forCollab: boolean) {}\n\n getExtensions() {\n const dropped: string[] = [...unsafeExtensions];\n if (this.forCollab) dropped.push('history');\n\n return new AdvancedEditorKit()\n .getExtensions()\n .filter(\n (extension) =>\n !('name' in extension && dropped.includes(extension.name))\n );\n }\n}\n\n/** MarkYChange + ExtensionYjs live in `collabKit.ts` (lazy-loaded). */\n\n/**\n * Build the editor kits for a session. Pass `config` to join a collaborative\n * room; omit it for a plain local editor.\n *\n * Async because collaborative mode lazy-loads the Yjs kit (and its optional\n * peer deps) on first use; plain mode resolves immediately.\n *\n * That lazy load is allowed to fail. `@kerebron/extension-yjs`, `yjs` and\n * `y-protocols` are optional peers, so the chunk can be absent (peers never\n * installed), stale (a dev server's dependency hash moved under a running\n * page) or simply unreachable (a partial deploy, an offline client). None of\n * that is a reason to leave the caller without an editor: collaboration is an\n * enhancement, editing is the feature. So a failed load degrades to the local\n * kit and reports itself through {@link CollabConfig.onUnavailable} rather\n * than rejecting.\n */\nexport async function createEditorKits(\n config?: CollabConfig\n): Promise<EditorKits> {\n if (!config) {\n return { kits: [new SafeAdvancedEditorKit(false)], collaborative: false };\n }\n\n try {\n const { HuddleYjsKit, defaultWsUrl } = await import('./collabKit');\n const url = config.wsUrl ?? defaultWsUrl();\n return {\n kits: [\n new SafeAdvancedEditorKit(true),\n new HuddleYjsKit(\n url,\n config.params ?? {},\n config.WebSocketPolyfill,\n config.user\n ),\n ],\n collaborative: true,\n };\n } catch (error) {\n console.warn(\n '[RichEditor] Collaborative editing unavailable — the Yjs kit failed to load. Continuing as a local editor.',\n error\n );\n config.onUnavailable?.(error);\n return { kits: [new SafeAdvancedEditorKit(false)], collaborative: false };\n }\n}\n","'use client';\n\nimport {\n forwardRef,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from 'react';\n\nimport { CoreEditor, type AssetLoad } from '@kerebron/editor';\nimport { createAssetLoad } from '@kerebron/wasm/web';\n\nimport { useIsDarkMode } from '../../hooks/useIsDarkMode';\nimport { createEditorKits, type CollabConfig } from './editorKits';\n\nexport type { CollabConfig } from './editorKits';\n\nconst MARKDOWN_TYPE = 'text/x-markdown';\n\n/**\n * The markdown converter's tree-sitter WASM init is not concurrency-safe, so\n * every editor's *first* load queues behind the previous one. Later loads (a\n * `value` change) are free — by then the grammars are warm.\n */\nlet initialLoadQueue: Promise<unknown> = Promise.resolve();\n\nfunction queueInitialLoad(load: () => Promise<void>): Promise<void> {\n const queued = initialLoadQueue.catch(() => undefined).then(load);\n initialLoadQueue = queued.catch(() => undefined);\n return queued;\n}\n\nexport interface RichEditorProps {\n /** Markdown to load. Changing it reloads the editor unless `collab` is set. */\n value?: string;\n /** Called with the editor's markdown content whenever it changes. */\n onChange?: (value: string) => void;\n /** Whether to render the live markdown output preview. Defaults to `false`. */\n showPreview?: boolean;\n /**\n * Enable live collaborative editing (Yjs) for the given room. When set, the\n * editor connects to the `/yjs` websocket relay and every peer in the same\n * `room` co-edits one shared document. Uncontrolled like `value` — remount via\n * `key` to switch rooms.\n *\n * Best-effort: if the Yjs kit cannot be loaded the editor still mounts, as a\n * local one, and `collab.onUnavailable` is called. Pass that callback if\n * unshared editing is something your users need to be told about.\n */\n collab?: CollabConfig;\n /** Read-only surface: no typing, and the content dims. */\n disabled?: boolean;\n /**\n * Id for the editor host element — an `aria-labelledby`/`aria-describedby`\n * anchor. The host is a `div`, not a labelable control, so a\n * `<label htmlFor>` will not associate; name the editor with `aria-label`\n * or `aria-labelledby` instead.\n */\n id?: string;\n /** Extra classes on the editor surface, beside `kb-component`. */\n className?: string;\n 'aria-label'?: string;\n 'aria-labelledby'?: string;\n /**\n * Where the tree-sitter WASM grammars load from. Defaults to\n * `createAssetLoad('/kerebron-wasm')`; supply your own when the host serves\n * `@kerebron/wasm`'s `assets/` somewhere else.\n */\n assetLoad?: AssetLoad;\n}\n\nexport interface RichEditorHandle {\n /**\n * The editor's markdown, awaiting the initial load. `onChange` can lag the\n * last keystroke, so read this on submit rather than trusting mirrored state.\n */\n getContent: () => Promise<string>;\n /** Focus the editor, restoring the caret where the writer left it. */\n focus: () => void;\n}\n\n/**\n * Markdown editor over Kerebron's `CoreEditor`.\n *\n * The editor mounts into a **disposable child div**: `CoreEditor.destroy()`\n * replaces its host element with a clone, which would strand React's ref (and,\n * under StrictMode's double-mount, leave the live editor detached behind a\n * dead clone).\n */\nconst RichEditor = forwardRef<RichEditorHandle, RichEditorProps>(\n function RichEditor(\n {\n value = '',\n onChange,\n showPreview = false,\n collab,\n disabled = false,\n id,\n className,\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledBy,\n assetLoad,\n },\n ref\n ) {\n const isDark = useIsDarkMode();\n const hostRef = useRef<HTMLDivElement>(null);\n const editorInstance = useRef<CoreEditor | null>(null);\n const onChangeRef = useRef(onChange);\n onChangeRef.current = onChange;\n // Mirrors what the editor last held, so an echo of our own `onChange`\n // doesn't reload the document out from under the caret.\n const valueRef = useRef(value);\n const readyRef = useRef<Promise<void> | null>(null);\n const loadingRef = useRef(false);\n const disabledRef = useRef(disabled);\n\n const [md, setMd] = useState<string>('');\n\n useEffect(() => {\n disabledRef.current = disabled;\n editorInstance.current?.view.setProps({\n editable: () => !disabledRef.current,\n });\n }, [disabled]);\n\n useEffect(() => {\n // In collab mode the CRDT owns the content; reloading would fight it.\n if (collab || value === valueRef.current) return;\n valueRef.current = value;\n const editor = editorInstance.current;\n if (!editor) return;\n\n loadingRef.current = true;\n void editor\n .loadDocumentText(MARKDOWN_TYPE, value)\n .catch(() => undefined)\n .finally(() => {\n if (editorInstance.current === editor) loadingRef.current = false;\n });\n // `collab` is fixed for the lifetime of the instance.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [value]);\n\n useEffect(() => {\n if (!hostRef.current) return;\n const host = hostRef.current;\n\n // Set on cleanup so async continuations (kit loading and the\n // `loadDocumentText` chain) don't touch the editor after `destroy()`.\n let disposed = false;\n let editor: CoreEditor | null = null;\n\n const mount = document.createElement('div');\n host.appendChild(mount);\n\n // Listen to transactions and update markdown preview\n const onTransaction = async () => {\n // Programmatic loads are not edits — reporting them would echo the\n // caller's own `value` back through `onChange`.\n if (loadingRef.current || !editorInstance.current) return;\n\n try {\n const buffer =\n await editorInstance.current.saveDocument(MARKDOWN_TYPE);\n const markdown = new globalThis.TextDecoder().decode(buffer);\n if (disposed) return;\n valueRef.current = markdown;\n setMd(markdown);\n onChangeRef.current?.(markdown);\n } catch (err) {\n console.error('Failed to save markdown:', err);\n }\n };\n\n // Initialize the editor. Both modes drop the teardown-unsafe extensions;\n // collaborative mode additionally swaps `history` for the Yjs CRDT sync\n // and lazy-loads the Yjs kit (see `editorKits.ts` for why).\n const setup = async () => {\n // `collaborative` is false when a room was asked for but the Yjs kit\n // could not be loaded — the editor is still created, just a local one,\n // so there is no room to join below.\n const { kits: editorKits, collaborative } =\n await createEditorKits(collab);\n if (disposed) return;\n\n editor = CoreEditor.create({\n element: mount,\n uri: 'file:///untitled.md',\n assetLoad: assetLoad ?? createAssetLoad('/kerebron-wasm'),\n editorKits,\n readOnly: disabledRef.current,\n });\n\n editorInstance.current = editor;\n // The contenteditable surface has no implicit ARIA role, so labeling\n // attributes are only permitted alongside an explicit textbox role.\n const surfaceAttributes =\n ariaLabel || ariaLabelledBy\n ? {\n role: 'textbox',\n 'aria-multiline': 'true',\n ...(ariaLabel ? { 'aria-label': ariaLabel } : {}),\n ...(ariaLabelledBy\n ? { 'aria-labelledby': ariaLabelledBy }\n : {}),\n }\n : null;\n editor.view.setProps({\n editable: () => !disabledRef.current,\n ...(surfaceAttributes ? { attributes: surfaceAttributes } : {}),\n });\n editor.addEventListener('transaction', onTransaction);\n\n // Seed initial content, then populate the preview once on mount.\n //\n // In collaborative mode we still load the local markdown first, then\n // join the room: the Yjs binding seeds an *empty* shared document from\n // this content on the first join, and overwrites the editor with the\n // shared content when the room already has edits — so the stored\n // markdown is the starting point without ever double-inserting.\n const joinRoom = () => {\n if (collaborative && collab && editor && !disposed) {\n (\n editor.run as Record<string, (...args: unknown[]) => boolean>\n ).changeRoom?.(collab.room);\n reseedWhenRoomStaysEmpty();\n }\n };\n\n // The Yjs binding is supposed to seed an empty room from the local\n // content, but the sync import can land as an overwrite that blanks\n // the just-loaded seed (observed with extension-yjs 0.8.x). Heal it:\n // once the join settles, an empty document with a non-empty seed\n // means nobody's content won — reload the seed, which the binding\n // then pushes into the room. Joiners pass no value, so exactly one\n // participant ever does this.\n const seed = valueRef.current;\n const reseedWhenRoomStaysEmpty = () => {\n if (!seed) return;\n const check = async (attempt: number) => {\n if (disposed || !editorInstance.current) return;\n try {\n const buffer =\n await editorInstance.current.saveDocument(MARKDOWN_TYPE);\n const current = new globalThis.TextDecoder()\n .decode(buffer)\n .trim();\n if (disposed || !editorInstance.current) return;\n if (current) return; // somebody's content arrived — done\n if (attempt >= 2) {\n await editorInstance.current.loadDocumentText(\n MARKDOWN_TYPE,\n seed\n );\n return;\n }\n setTimeout(() => void check(attempt + 1), 300);\n } catch {\n // A failed probe must not break the editor; the room stays as-is.\n }\n };\n setTimeout(() => void check(0), 300);\n };\n\n if (valueRef.current) {\n await queueInitialLoad(() =>\n editor!.loadDocumentText(MARKDOWN_TYPE, valueRef.current)\n );\n await onTransaction();\n joinRoom();\n } else {\n void onTransaction();\n joinRoom();\n }\n };\n\n readyRef.current = setup().catch((err) =>\n console.error('Failed to set up editor:', err)\n );\n\n // Cleanup on unmount\n return () => {\n disposed = true;\n editorInstance.current = null; // makes onTransaction's guard effective\n editor?.removeEventListener('transaction', onTransaction);\n editor?.destroy();\n readyRef.current = null;\n host.replaceChildren();\n };\n // Initial `value`/`collab` are intentionally only applied on mount\n // (uncontrolled). Remount via `key` to switch rooms.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useImperativeHandle(\n ref,\n () => ({\n getContent: async (): Promise<string> => {\n await readyRef.current;\n const editor = editorInstance.current;\n if (!editor) return valueRef.current;\n const buffer = await editor.saveDocument(MARKDOWN_TYPE);\n const markdown = new globalThis.TextDecoder().decode(buffer);\n valueRef.current = markdown;\n return markdown;\n },\n focus: (): void => {\n const apply = (): void => {\n const view = editorInstance.current?.view as\n | { focus?: () => void }\n | undefined;\n if (view?.focus) {\n view.focus();\n return;\n }\n hostRef.current\n ?.querySelector<HTMLElement>('[contenteditable=\"true\"], textarea')\n ?.focus();\n };\n // Callers focus on mount; the editor may still be loading its kits.\n if (editorInstance.current) apply();\n else void readyRef.current?.then(apply);\n },\n }),\n []\n );\n\n return (\n <div>\n <div>\n <div\n ref={hostRef}\n id={id}\n className={[\n 'kb-component',\n isDark ? 'kb-component--dark' : '',\n className ?? '',\n ]\n .filter(Boolean)\n .join(' ')}\n aria-label={ariaLabel}\n aria-labelledby={ariaLabelledBy}\n aria-disabled={disabled || undefined}\n style={{\n isolation: 'isolate',\n opacity: disabled ? 0.65 : undefined,\n pointerEvents: disabled ? 'none' : undefined,\n }}\n />\n </div>\n\n {showPreview && (\n <div>\n <div>\n <h5>Markdown Output</h5>\n <pre>{md}</pre>\n </div>\n </div>\n )}\n </div>\n );\n }\n);\n\nRichEditor.displayName = 'RichEditor';\n\nexport { RichEditor };\n","import React, { useEffect, useRef } from 'react';\n\nimport { CoreEditor } from '@kerebron/editor';\nimport { CodeEditorKit } from '@kerebron/editor-kits/CodeEditorKit';\nimport { createAssetLoad } from '@kerebron/wasm/web';\n\nexport interface CodeEditorProps {\n /** Initial source code to load into the editor. */\n value?: string;\n /** Called with the editor's contents whenever they change. */\n onChange?: (value: string) => void;\n /** Language/grammar to use for syntax highlighting. Defaults to `typescript`. */\n lang?: string;\n}\n\nconst CodeEditor: React.FC<CodeEditorProps> = ({\n value = '',\n onChange,\n lang = 'typescript',\n}) => {\n const editorRef = useRef<HTMLDivElement>(null);\n const editorInstance = useRef<CoreEditor | null>(null);\n const onChangeRef = useRef(onChange);\n onChangeRef.current = onChange;\n\n useEffect(() => {\n const root = editorRef.current;\n if (!root) return;\n\n const applySelectLabel = () => {\n root.querySelectorAll('select.codejar-select').forEach((element) => {\n if (!element.getAttribute('aria-label')) {\n element.setAttribute('aria-label', 'Code editor language');\n }\n });\n };\n\n applySelectLabel();\n const observer = new MutationObserver(() => applySelectLabel());\n observer.observe(root, { childList: true, subtree: true });\n return () => observer.disconnect();\n }, []);\n\n useEffect(() => {\n if (!editorRef.current) return;\n\n // Initialize the editor\n const editor = CoreEditor.create({\n element: editorRef.current,\n uri: 'file:///untitled.ts',\n assetLoad: createAssetLoad('/kerebron-wasm'),\n editorKits: [new CodeEditorKit(lang)],\n });\n\n editorInstance.current = editor;\n\n // Surface edits to callers.\n const onTransaction = async () => {\n if (!editorInstance.current) return;\n\n try {\n const buffer = await editorInstance.current.saveDocument('text/plain');\n onChangeRef.current?.(new globalThis.TextDecoder().decode(buffer));\n } catch (err) {\n console.error('Failed to read code:', err);\n }\n };\n\n editor.addEventListener('transaction', onTransaction);\n\n // Seed initial content on mount.\n if (value) {\n editor\n .loadDocumentText('text/plain', value)\n .catch((err) => console.error('Failed to load code:', err));\n }\n\n // Cleanup on unmount\n return () => {\n editor.removeEventListener('transaction', onTransaction);\n editor.destroy();\n };\n // Initial `value`/`lang` are intentionally only applied on mount.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n <div>\n <div>\n <div ref={editorRef} className=\"kb-component\" />\n </div>\n </div>\n );\n};\n\nCodeEditor.displayName = 'CodeEditor';\n\nexport { CodeEditor };\n"]}
@@ -42,6 +42,18 @@ interface CollabConfig {
42
42
  * Defaults to `globalThis.WebSocket`.
43
43
  */
44
44
  WebSocketPolyfill?: typeof globalThis.WebSocket;
45
+ /**
46
+ * Called when collaborative editing could not be started at all — the Yjs
47
+ * kit failed to load (see {@link createEditorKits}). The editor mounts
48
+ * anyway, as a local one; this is how the host finds out that edits are no
49
+ * longer shared, so it can say so, or tear its own editor down if unshared
50
+ * editing would be unsafe.
51
+ *
52
+ * Not for connection trouble: a room that is reachable but currently
53
+ * disconnected still has the Yjs kit loaded, and the provider retries on its
54
+ * own. This fires once, before the editor is created.
55
+ */
56
+ onUnavailable?: (error: unknown) => void;
45
57
  }
46
58
 
47
59
  interface RichEditorProps {
@@ -56,6 +68,10 @@ interface RichEditorProps {
56
68
  * editor connects to the `/yjs` websocket relay and every peer in the same
57
69
  * `room` co-edits one shared document. Uncontrolled like `value` — remount via
58
70
  * `key` to switch rooms.
71
+ *
72
+ * Best-effort: if the Yjs kit cannot be loaded the editor still mounts, as a
73
+ * local one, and `collab.onUnavailable` is called. Pass that callback if
74
+ * unshared editing is something your users need to be told about.
59
75
  */
60
76
  collab?: CollabConfig;
61
77
  /** Read-only surface: no typing, and the content dims. */
@@ -42,6 +42,18 @@ interface CollabConfig {
42
42
  * Defaults to `globalThis.WebSocket`.
43
43
  */
44
44
  WebSocketPolyfill?: typeof globalThis.WebSocket;
45
+ /**
46
+ * Called when collaborative editing could not be started at all — the Yjs
47
+ * kit failed to load (see {@link createEditorKits}). The editor mounts
48
+ * anyway, as a local one; this is how the host finds out that edits are no
49
+ * longer shared, so it can say so, or tear its own editor down if unshared
50
+ * editing would be unsafe.
51
+ *
52
+ * Not for connection trouble: a room that is reachable but currently
53
+ * disconnected still has the Yjs kit loaded, and the provider retries on its
54
+ * own. This fires once, before the editor is created.
55
+ */
56
+ onUnavailable?: (error: unknown) => void;
45
57
  }
46
58
 
47
59
  interface RichEditorProps {
@@ -56,6 +68,10 @@ interface RichEditorProps {
56
68
  * editor connects to the `/yjs` websocket relay and every peer in the same
57
69
  * `room` co-edits one shared document. Uncontrolled like `value` — remount via
58
70
  * `key` to switch rooms.
71
+ *
72
+ * Best-effort: if the Yjs kit cannot be loaded the editor still mounts, as a
73
+ * local one, and `collab.onUnavailable` is called. Pass that callback if
74
+ * unshared editing is something your users need to be told about.
59
75
  */
60
76
  collab?: CollabConfig;
61
77
  /** Read-only surface: no typing, and the content dims. */
package/dist/kerebron.js CHANGED
@@ -23,18 +23,32 @@ var SafeAdvancedEditorKit = class {
23
23
  }
24
24
  };
25
25
  async function createEditorKits(config) {
26
- if (!config) return [new SafeAdvancedEditorKit(false)];
27
- const { HuddleYjsKit, defaultWsUrl } = await import('./collabKit-SJPDPXU4.js');
28
- const url = config.wsUrl ?? defaultWsUrl();
29
- return [
30
- new SafeAdvancedEditorKit(true),
31
- new HuddleYjsKit(
32
- url,
33
- config.params ?? {},
34
- config.WebSocketPolyfill,
35
- config.user
36
- )
37
- ];
26
+ if (!config) {
27
+ return { kits: [new SafeAdvancedEditorKit(false)], collaborative: false };
28
+ }
29
+ try {
30
+ const { HuddleYjsKit, defaultWsUrl } = await import('./collabKit-SJPDPXU4.js');
31
+ const url = config.wsUrl ?? defaultWsUrl();
32
+ return {
33
+ kits: [
34
+ new SafeAdvancedEditorKit(true),
35
+ new HuddleYjsKit(
36
+ url,
37
+ config.params ?? {},
38
+ config.WebSocketPolyfill,
39
+ config.user
40
+ )
41
+ ],
42
+ collaborative: true
43
+ };
44
+ } catch (error) {
45
+ console.warn(
46
+ "[RichEditor] Collaborative editing unavailable \u2014 the Yjs kit failed to load. Continuing as a local editor.",
47
+ error
48
+ );
49
+ config.onUnavailable?.(error);
50
+ return { kits: [new SafeAdvancedEditorKit(false)], collaborative: false };
51
+ }
38
52
  }
39
53
  var MARKDOWN_TYPE = "text/x-markdown";
40
54
  var initialLoadQueue = Promise.resolve();
@@ -103,7 +117,7 @@ var RichEditor = forwardRef(
103
117
  }
104
118
  };
105
119
  const setup = async () => {
106
- const editorKits = await createEditorKits(collab);
120
+ const { kits: editorKits, collaborative } = await createEditorKits(collab);
107
121
  if (disposed) return;
108
122
  editor = CoreEditor.create({
109
123
  element: mount,
@@ -125,7 +139,7 @@ var RichEditor = forwardRef(
125
139
  });
126
140
  editor.addEventListener("transaction", onTransaction);
127
141
  const joinRoom = () => {
128
- if (collab && editor && !disposed) {
142
+ if (collaborative && collab && editor && !disposed) {
129
143
  editor.run.changeRoom?.(collab.room);
130
144
  reseedWhenRoomStaysEmpty();
131
145
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/components/RichEditor/editorKits.ts","../src/components/RichEditor/RichEditor.tsx","../src/components/RichEditor/CodeEditor.tsx"],"names":["RichEditor","useRef","useEffect","CoreEditor","createAssetLoad","jsx"],"mappings":";;;;;;;;;AA4DA,IAAM,gBAAA,GAAmB,CAAC,cAAA,EAAgB,OAAO,CAAA;AAIjD,IAAM,wBAAN,MAAiD;AAAA,EAE/C,YAA6B,SAAA,EAAoB;AAApB,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AAAA,EAAqB;AAAA,EAArB,SAAA;AAAA,EAD7B,IAAA,GAAO,iBAAA;AAAA,EAGP,aAAA,GAAgB;AACd,IAAA,MAAM,OAAA,GAAoB,CAAC,GAAG,gBAAgB,CAAA;AAC9C,IAAA,IAAI,IAAA,CAAK,SAAA,EAAW,OA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AAa,CAAA;AAGpD,IAAA,IAAI,KAAA,EAAO;AACT,MAAA,MAAA,CACG,gBAAA,CAAiB,YAAA,EAAc,KAAK,CAAA,CACpC,KAAA,CAAM,CAAC,GAAA,KAAQ,OAAA,CAAQ,KAAA,CAAM,sBAAA,EAAwB,GAAG,CAAC,CAAA;AAAA,IAC9D;AAGA,IAAA,OAAO,MAAM;AACX,MAAA,MAAA,CAAO,mBAAA,CAAoB,eAAe,aAAa,CAAA;AACvD,MAAA,MAAA,CAAO,OAAA,EAAQ;AAAA,IACjB,CAAA;AAAA,EAGF,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,uBACEC,GAAAA,CAAC,KAAA,EAAA,EACC,QAAA,kBAAAA,IAAC,KAAA,EAAA,EACC,QAAA,kBAAAA,GAAAA,CAAC,KAAA,EAAA,EAAI,GAAA,EAAK,SAAA,EAAW,SAAA,EAAU,cAAA,EAAe,GAChD,CAAA,EACF,CAAA;AAEJ;AAEA,UAAA,CAAW,WAAA,GAAc,YAAA","file":"kerebron.js","sourcesContent":["/**\n * Editor kit assembly for {@link RichEditor}, for both plain and collaborative\n * (Yjs) mode.\n *\n * Both modes start from {@link AdvancedEditorKit} and drop the extensions that\n * are unsafe for our usage — see {@link unsafeExtensions} — then collaborative\n * mode adds the Yjs pieces on top.\n *\n * The Yjs pieces live in `collabKit.ts` behind a dynamic `import()`, so\n * `@kerebron/extension-yjs`, `yjs` and `y-protocols` remain truly optional\n * peers — plain-mode consumers never load them.\n */\nimport type { EditorKit } from '@kerebron/editor';\nimport { AdvancedEditorKit } from '@kerebron/editor-kits/AdvancedEditorKit';\n\nexport interface CollabConfig {\n /** Room id — one shared document per room (e.g. a post id). */\n room: string;\n /**\n * WebSocket base URL for the Yjs relay. Defaults to\n * `<ws|wss>://<location.host>/yjs`. The room id is appended by the provider.\n */\n wsUrl?: string;\n /** Extra query params for the socket (e.g. `{ token }` for auth). */\n params?: Record<string, string>;\n /**\n * Who this editor is, published on awareness (`kerebron:user`) so peers see\n * a named, coloured cursor. Without it remote cursors do not render — the\n * position plugin skips awareness states that carry no user — and the\n * `id` is what the cursor colour is derived from (kerebron's `User` shape).\n */\n user?: { id: string; name: string; color?: string };\n /**\n * Custom WebSocket implementation handed to the Yjs provider — e.g. a\n * loopback socket for demos/tests, or a polyfill outside the browser.\n * Defaults to `globalThis.WebSocket`.\n */\n WebSocketPolyfill?: typeof globalThis.WebSocket;\n}\n\n/**\n * Extensions dropped from {@link AdvancedEditorKit}, and why.\n *\n * `autocomplete` and `hover` debounce their DOM handlers (200ms) and then call\n * `dispatchMeta`, which reads `this.editor.state` with no guard that the editor\n * is still alive. Any teardown or document swap inside that debounce window\n * lands the deferred call on a dead view and throws\n * `null.matchesNode()` inside ProseMirror's `EditorView.updateStateInner`,\n * leaving the view permanently broken. Two ways to hit it:\n * - remount (e.g. a `key` change) while the pointer is over the editor, which\n * fires the debounced `onMouseLeave` after the view is destroyed;\n * - a Yjs remote update replacing the document tree under a pending callback.\n * The first applies to *every* editor, so both extensions come out in both\n * modes. No functional cost — autocomplete popups and node-hover tooltips are\n * compositor conveniences, not required for editing.\n *\n * `history` is collab-only: ExtensionYjs supplies its own CRDT-aware undo/redo\n * and the editor throws `Extension conflict: yjs vs history` if both are\n * present. Plain mode keeps it, so undo/redo still works there.\n */\nconst unsafeExtensions = ['autocomplete', 'hover'] as const;\n\n/** {@link AdvancedEditorKit} minus {@link unsafeExtensions} (and, for collab\n * mode, minus `history`). */\nclass SafeAdvancedEditorKit implements EditorKit {\n name = 'advanced-editor';\n constructor(private readonly forCollab: boolean) {}\n\n getExtensions() {\n const dropped: string[] = [...unsafeExtensions];\n if (this.forCollab) dropped.push('history');\n\n return new AdvancedEditorKit()\n .getExtensions()\n .filter(\n (extension) =>\n !('name' in extension && dropped.includes(extension.name))\n );\n }\n}\n\n/** MarkYChange + ExtensionYjs live in `collabKit.ts` (lazy-loaded). */\n\n/**\n * Build the editor kits for a session. Pass `config` to join a collaborative\n * room; omit it for a plain local editor.\n *\n * Async because collaborative mode lazy-loads the Yjs kit (and its optional\n * peer deps) on first use; plain mode resolves immediately.\n */\nexport async function createEditorKits(\n config?: CollabConfig\n): Promise<EditorKit[]> {\n if (!config) return [new SafeAdvancedEditorKit(false)];\n\n const { HuddleYjsKit, defaultWsUrl } = await import('./collabKit');\n const url = config.wsUrl ?? defaultWsUrl();\n return [\n new SafeAdvancedEditorKit(true),\n new HuddleYjsKit(\n url,\n config.params ?? {},\n config.WebSocketPolyfill,\n config.user\n ),\n ];\n}\n","'use client';\n\nimport {\n forwardRef,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from 'react';\n\nimport { CoreEditor, type AssetLoad } from '@kerebron/editor';\nimport { createAssetLoad } from '@kerebron/wasm/web';\n\nimport { useIsDarkMode } from '../../hooks/useIsDarkMode';\nimport { createEditorKits, type CollabConfig } from './editorKits';\n\nexport type { CollabConfig } from './editorKits';\n\nconst MARKDOWN_TYPE = 'text/x-markdown';\n\n/**\n * The markdown converter's tree-sitter WASM init is not concurrency-safe, so\n * every editor's *first* load queues behind the previous one. Later loads (a\n * `value` change) are free — by then the grammars are warm.\n */\nlet initialLoadQueue: Promise<unknown> = Promise.resolve();\n\nfunction queueInitialLoad(load: () => Promise<void>): Promise<void> {\n const queued = initialLoadQueue.catch(() => undefined).then(load);\n initialLoadQueue = queued.catch(() => undefined);\n return queued;\n}\n\nexport interface RichEditorProps {\n /** Markdown to load. Changing it reloads the editor unless `collab` is set. */\n value?: string;\n /** Called with the editor's markdown content whenever it changes. */\n onChange?: (value: string) => void;\n /** Whether to render the live markdown output preview. Defaults to `false`. */\n showPreview?: boolean;\n /**\n * Enable live collaborative editing (Yjs) for the given room. When set, the\n * editor connects to the `/yjs` websocket relay and every peer in the same\n * `room` co-edits one shared document. Uncontrolled like `value` — remount via\n * `key` to switch rooms.\n */\n collab?: CollabConfig;\n /** Read-only surface: no typing, and the content dims. */\n disabled?: boolean;\n /**\n * Id for the editor host element — an `aria-labelledby`/`aria-describedby`\n * anchor. The host is a `div`, not a labelable control, so a\n * `<label htmlFor>` will not associate; name the editor with `aria-label`\n * or `aria-labelledby` instead.\n */\n id?: string;\n /** Extra classes on the editor surface, beside `kb-component`. */\n className?: string;\n 'aria-label'?: string;\n 'aria-labelledby'?: string;\n /**\n * Where the tree-sitter WASM grammars load from. Defaults to\n * `createAssetLoad('/kerebron-wasm')`; supply your own when the host serves\n * `@kerebron/wasm`'s `assets/` somewhere else.\n */\n assetLoad?: AssetLoad;\n}\n\nexport interface RichEditorHandle {\n /**\n * The editor's markdown, awaiting the initial load. `onChange` can lag the\n * last keystroke, so read this on submit rather than trusting mirrored state.\n */\n getContent: () => Promise<string>;\n /** Focus the editor, restoring the caret where the writer left it. */\n focus: () => void;\n}\n\n/**\n * Markdown editor over Kerebron's `CoreEditor`.\n *\n * The editor mounts into a **disposable child div**: `CoreEditor.destroy()`\n * replaces its host element with a clone, which would strand React's ref (and,\n * under StrictMode's double-mount, leave the live editor detached behind a\n * dead clone).\n */\nconst RichEditor = forwardRef<RichEditorHandle, RichEditorProps>(\n function RichEditor(\n {\n value = '',\n onChange,\n showPreview = false,\n collab,\n disabled = false,\n id,\n className,\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledBy,\n assetLoad,\n },\n ref\n ) {\n const isDark = useIsDarkMode();\n const hostRef = useRef<HTMLDivElement>(null);\n const editorInstance = useRef<CoreEditor | null>(null);\n const onChangeRef = useRef(onChange);\n onChangeRef.current = onChange;\n // Mirrors what the editor last held, so an echo of our own `onChange`\n // doesn't reload the document out from under the caret.\n const valueRef = useRef(value);\n const readyRef = useRef<Promise<void> | null>(null);\n const loadingRef = useRef(false);\n const disabledRef = useRef(disabled);\n\n const [md, setMd] = useState<string>('');\n\n useEffect(() => {\n disabledRef.current = disabled;\n editorInstance.current?.view.setProps({\n editable: () => !disabledRef.current,\n });\n }, [disabled]);\n\n useEffect(() => {\n // In collab mode the CRDT owns the content; reloading would fight it.\n if (collab || value === valueRef.current) return;\n valueRef.current = value;\n const editor = editorInstance.current;\n if (!editor) return;\n\n loadingRef.current = true;\n void editor\n .loadDocumentText(MARKDOWN_TYPE, value)\n .catch(() => undefined)\n .finally(() => {\n if (editorInstance.current === editor) loadingRef.current = false;\n });\n // `collab` is fixed for the lifetime of the instance.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [value]);\n\n useEffect(() => {\n if (!hostRef.current) return;\n const host = hostRef.current;\n\n // Set on cleanup so async continuations (kit loading and the\n // `loadDocumentText` chain) don't touch the editor after `destroy()`.\n let disposed = false;\n let editor: CoreEditor | null = null;\n\n const mount = document.createElement('div');\n host.appendChild(mount);\n\n // Listen to transactions and update markdown preview\n const onTransaction = async () => {\n // Programmatic loads are not edits — reporting them would echo the\n // caller's own `value` back through `onChange`.\n if (loadingRef.current || !editorInstance.current) return;\n\n try {\n const buffer =\n await editorInstance.current.saveDocument(MARKDOWN_TYPE);\n const markdown = new globalThis.TextDecoder().decode(buffer);\n if (disposed) return;\n valueRef.current = markdown;\n setMd(markdown);\n onChangeRef.current?.(markdown);\n } catch (err) {\n console.error('Failed to save markdown:', err);\n }\n };\n\n // Initialize the editor. Both modes drop the teardown-unsafe extensions;\n // collaborative mode additionally swaps `history` for the Yjs CRDT sync\n // and lazy-loads the Yjs kit (see `editorKits.ts` for why).\n const setup = async () => {\n const editorKits = await createEditorKits(collab);\n if (disposed) return;\n\n editor = CoreEditor.create({\n element: mount,\n uri: 'file:///untitled.md',\n assetLoad: assetLoad ?? createAssetLoad('/kerebron-wasm'),\n editorKits,\n readOnly: disabledRef.current,\n });\n\n editorInstance.current = editor;\n // The contenteditable surface has no implicit ARIA role, so labeling\n // attributes are only permitted alongside an explicit textbox role.\n const surfaceAttributes =\n ariaLabel || ariaLabelledBy\n ? {\n role: 'textbox',\n 'aria-multiline': 'true',\n ...(ariaLabel ? { 'aria-label': ariaLabel } : {}),\n ...(ariaLabelledBy\n ? { 'aria-labelledby': ariaLabelledBy }\n : {}),\n }\n : null;\n editor.view.setProps({\n editable: () => !disabledRef.current,\n ...(surfaceAttributes ? { attributes: surfaceAttributes } : {}),\n });\n editor.addEventListener('transaction', onTransaction);\n\n // Seed initial content, then populate the preview once on mount.\n //\n // In collaborative mode we still load the local markdown first, then\n // join the room: the Yjs binding seeds an *empty* shared document from\n // this content on the first join, and overwrites the editor with the\n // shared content when the room already has edits — so the stored\n // markdown is the starting point without ever double-inserting.\n const joinRoom = () => {\n if (collab && editor && !disposed) {\n (\n editor.run as Record<string, (...args: unknown[]) => boolean>\n ).changeRoom?.(collab.room);\n reseedWhenRoomStaysEmpty();\n }\n };\n\n // The Yjs binding is supposed to seed an empty room from the local\n // content, but the sync import can land as an overwrite that blanks\n // the just-loaded seed (observed with extension-yjs 0.8.x). Heal it:\n // once the join settles, an empty document with a non-empty seed\n // means nobody's content won — reload the seed, which the binding\n // then pushes into the room. Joiners pass no value, so exactly one\n // participant ever does this.\n const seed = valueRef.current;\n const reseedWhenRoomStaysEmpty = () => {\n if (!seed) return;\n const check = async (attempt: number) => {\n if (disposed || !editorInstance.current) return;\n try {\n const buffer =\n await editorInstance.current.saveDocument(MARKDOWN_TYPE);\n const current = new globalThis.TextDecoder()\n .decode(buffer)\n .trim();\n if (disposed || !editorInstance.current) return;\n if (current) return; // somebody's content arrived — done\n if (attempt >= 2) {\n await editorInstance.current.loadDocumentText(\n MARKDOWN_TYPE,\n seed\n );\n return;\n }\n setTimeout(() => void check(attempt + 1), 300);\n } catch {\n // A failed probe must not break the editor; the room stays as-is.\n }\n };\n setTimeout(() => void check(0), 300);\n };\n\n if (valueRef.current) {\n await queueInitialLoad(() =>\n editor!.loadDocumentText(MARKDOWN_TYPE, valueRef.current)\n );\n await onTransaction();\n joinRoom();\n } else {\n void onTransaction();\n joinRoom();\n }\n };\n\n readyRef.current = setup().catch((err) =>\n console.error('Failed to set up editor:', err)\n );\n\n // Cleanup on unmount\n return () => {\n disposed = true;\n editorInstance.current = null; // makes onTransaction's guard effective\n editor?.removeEventListener('transaction', onTransaction);\n editor?.destroy();\n readyRef.current = null;\n host.replaceChildren();\n };\n // Initial `value`/`collab` are intentionally only applied on mount\n // (uncontrolled). Remount via `key` to switch rooms.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useImperativeHandle(\n ref,\n () => ({\n getContent: async (): Promise<string> => {\n await readyRef.current;\n const editor = editorInstance.current;\n if (!editor) return valueRef.current;\n const buffer = await editor.saveDocument(MARKDOWN_TYPE);\n const markdown = new globalThis.TextDecoder().decode(buffer);\n valueRef.current = markdown;\n return markdown;\n },\n focus: (): void => {\n const apply = (): void => {\n const view = editorInstance.current?.view as\n | { focus?: () => void }\n | undefined;\n if (view?.focus) {\n view.focus();\n return;\n }\n hostRef.current\n ?.querySelector<HTMLElement>('[contenteditable=\"true\"], textarea')\n ?.focus();\n };\n // Callers focus on mount; the editor may still be loading its kits.\n if (editorInstance.current) apply();\n else void readyRef.current?.then(apply);\n },\n }),\n []\n );\n\n return (\n <div>\n <div>\n <div\n ref={hostRef}\n id={id}\n className={[\n 'kb-component',\n isDark ? 'kb-component--dark' : '',\n className ?? '',\n ]\n .filter(Boolean)\n .join(' ')}\n aria-label={ariaLabel}\n aria-labelledby={ariaLabelledBy}\n aria-disabled={disabled || undefined}\n style={{\n isolation: 'isolate',\n opacity: disabled ? 0.65 : undefined,\n pointerEvents: disabled ? 'none' : undefined,\n }}\n />\n </div>\n\n {showPreview && (\n <div>\n <div>\n <h5>Markdown Output</h5>\n <pre>{md}</pre>\n </div>\n </div>\n )}\n </div>\n );\n }\n);\n\nRichEditor.displayName = 'RichEditor';\n\nexport { RichEditor };\n","import React, { useEffect, useRef } from 'react';\n\nimport { CoreEditor } from '@kerebron/editor';\nimport { CodeEditorKit } from '@kerebron/editor-kits/CodeEditorKit';\nimport { createAssetLoad } from '@kerebron/wasm/web';\n\nexport interface CodeEditorProps {\n /** Initial source code to load into the editor. */\n value?: string;\n /** Called with the editor's contents whenever they change. */\n onChange?: (value: string) => void;\n /** Language/grammar to use for syntax highlighting. Defaults to `typescript`. */\n lang?: string;\n}\n\nconst CodeEditor: React.FC<CodeEditorProps> = ({\n value = '',\n onChange,\n lang = 'typescript',\n}) => {\n const editorRef = useRef<HTMLDivElement>(null);\n const editorInstance = useRef<CoreEditor | null>(null);\n const onChangeRef = useRef(onChange);\n onChangeRef.current = onChange;\n\n useEffect(() => {\n const root = editorRef.current;\n if (!root) return;\n\n const applySelectLabel = () => {\n root.querySelectorAll('select.codejar-select').forEach((element) => {\n if (!element.getAttribute('aria-label')) {\n element.setAttribute('aria-label', 'Code editor language');\n }\n });\n };\n\n applySelectLabel();\n const observer = new MutationObserver(() => applySelectLabel());\n observer.observe(root, { childList: true, subtree: true });\n return () => observer.disconnect();\n }, []);\n\n useEffect(() => {\n if (!editorRef.current) return;\n\n // Initialize the editor\n const editor = CoreEditor.create({\n element: editorRef.current,\n uri: 'file:///untitled.ts',\n assetLoad: createAssetLoad('/kerebron-wasm'),\n editorKits: [new CodeEditorKit(lang)],\n });\n\n editorInstance.current = editor;\n\n // Surface edits to callers.\n const onTransaction = async () => {\n if (!editorInstance.current) return;\n\n try {\n const buffer = await editorInstance.current.saveDocument('text/plain');\n onChangeRef.current?.(new globalThis.TextDecoder().decode(buffer));\n } catch (err) {\n console.error('Failed to read code:', err);\n }\n };\n\n editor.addEventListener('transaction', onTransaction);\n\n // Seed initial content on mount.\n if (value) {\n editor\n .loadDocumentText('text/plain', value)\n .catch((err) => console.error('Failed to load code:', err));\n }\n\n // Cleanup on unmount\n return () => {\n editor.removeEventListener('transaction', onTransaction);\n editor.destroy();\n };\n // Initial `value`/`lang` are intentionally only applied on mount.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n <div>\n <div>\n <div ref={editorRef} className=\"kb-component\" />\n </div>\n </div>\n );\n};\n\nCodeEditor.displayName = 'CodeEditor';\n\nexport { CodeEditor };\n"]}
1
+ {"version":3,"sources":["../src/components/RichEditor/editorKits.ts","../src/components/RichEditor/RichEditor.ts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AGF,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,uBACEC,GAAAA,CAAC,KAAA,EAAA,EACC,QAAA,kBAAAA,IAAC,KAAA,EAAA,EACC,QAAA,kBAAAA,GAAAA,CAAC,KAAA,EAAA,EAAI,GAAA,EAAK,SAAA,EAAW,SAAA,EAAU,cAAA,EAAe,GAChD,CAAA,EACF,CAAA;AAEJ;AAEA,UAAA,CAAW,WAAA,GAAc,YAAA","file":"kerebron.js","sourcesContent":["/**\n * Editor kit assembly for {@link RichEditor}, for both plain and collaborative\n * (Yjs) mode.\n *\n * Both modes start from {@link AdvancedEditorKit} and drop the extensions that\n * are unsafe for our usage — see {@link unsafeExtensions} — then collaborative\n * mode adds the Yjs pieces on top.\n *\n * The Yjs pieces live in `collabKit.ts` behind a dynamic `import()`, so\n * `@kerebron/extension-yjs`, `yjs` and `y-protocols` remain truly optional\n * peers — plain-mode consumers never load them.\n */\nimport type { EditorKit } from '@kerebron/editor';\nimport { AdvancedEditorKit } from '@kerebron/editor-kits/AdvancedEditorKit';\n\nexport interface CollabConfig {\n /** Room id — one shared document per room (e.g. a post id). */\n room: string;\n /**\n * WebSocket base URL for the Yjs relay. Defaults to\n * `<ws|wss>://<location.host>/yjs`. The room id is appended by the provider.\n */\n wsUrl?: string;\n /** Extra query params for the socket (e.g. `{ token }` for auth). */\n params?: Record<string, string>;\n /**\n * Who this editor is, published on awareness (`kerebron:user`) so peers see\n * a named, coloured cursor. Without it remote cursors do not render — the\n * position plugin skips awareness states that carry no user — and the\n * `id` is what the cursor colour is derived from (kerebron's `User` shape).\n */\n user?: { id: string; name: string; color?: string };\n /**\n * Custom WebSocket implementation handed to the Yjs provider — e.g. a\n * loopback socket for demos/tests, or a polyfill outside the browser.\n * Defaults to `globalThis.WebSocket`.\n */\n WebSocketPolyfill?: typeof globalThis.WebSocket;\n /**\n * Called when collaborative editing could not be started at all — the Yjs\n * kit failed to load (see {@link createEditorKits}). The editor mounts\n * anyway, as a local one; this is how the host finds out that edits are no\n * longer shared, so it can say so, or tear its own editor down if unshared\n * editing would be unsafe.\n *\n * Not for connection trouble: a room that is reachable but currently\n * disconnected still has the Yjs kit loaded, and the provider retries on its\n * own. This fires once, before the editor is created.\n */\n onUnavailable?: (error: unknown) => void;\n}\n\n/** What {@link createEditorKits} resolves to. */\nexport interface EditorKits {\n kits: EditorKit[];\n /**\n * Whether the returned kits can actually collaborate. False when `config`\n * asked for a room but the Yjs kit could not be loaded, so callers know not\n * to join one.\n */\n collaborative: boolean;\n}\n\n/**\n * Extensions dropped from {@link AdvancedEditorKit}, and why.\n *\n * `autocomplete` and `hover` debounce their DOM handlers (200ms) and then call\n * `dispatchMeta`, which reads `this.editor.state` with no guard that the editor\n * is still alive. Any teardown or document swap inside that debounce window\n * lands the deferred call on a dead view and throws\n * `null.matchesNode()` inside ProseMirror's `EditorView.updateStateInner`,\n * leaving the view permanently broken. Two ways to hit it:\n * - remount (e.g. a `key` change) while the pointer is over the editor, which\n * fires the debounced `onMouseLeave` after the view is destroyed;\n * - a Yjs remote update replacing the document tree under a pending callback.\n * The first applies to *every* editor, so both extensions come out in both\n * modes. No functional cost — autocomplete popups and node-hover tooltips are\n * compositor conveniences, not required for editing.\n *\n * `history` is collab-only: ExtensionYjs supplies its own CRDT-aware undo/redo\n * and the editor throws `Extension conflict: yjs vs history` if both are\n * present. Plain mode keeps it, so undo/redo still works there.\n */\nconst unsafeExtensions = ['autocomplete', 'hover'] as const;\n\n/** {@link AdvancedEditorKit} minus {@link unsafeExtensions} (and, for collab\n * mode, minus `history`). */\nclass SafeAdvancedEditorKit implements EditorKit {\n name = 'advanced-editor';\n constructor(private readonly forCollab: boolean) {}\n\n getExtensions() {\n const dropped: string[] = [...unsafeExtensions];\n if (this.forCollab) dropped.push('history');\n\n return new AdvancedEditorKit()\n .getExtensions()\n .filter(\n (extension) =>\n !('name' in extension && dropped.includes(extension.name))\n );\n }\n}\n\n/** MarkYChange + ExtensionYjs live in `collabKit.ts` (lazy-loaded). */\n\n/**\n * Build the editor kits for a session. Pass `config` to join a collaborative\n * room; omit it for a plain local editor.\n *\n * Async because collaborative mode lazy-loads the Yjs kit (and its optional\n * peer deps) on first use; plain mode resolves immediately.\n *\n * That lazy load is allowed to fail. `@kerebron/extension-yjs`, `yjs` and\n * `y-protocols` are optional peers, so the chunk can be absent (peers never\n * installed), stale (a dev server's dependency hash moved under a running\n * page) or simply unreachable (a partial deploy, an offline client). None of\n * that is a reason to leave the caller without an editor: collaboration is an\n * enhancement, editing is the feature. So a failed load degrades to the local\n * kit and reports itself through {@link CollabConfig.onUnavailable} rather\n * than rejecting.\n */\nexport async function createEditorKits(\n config?: CollabConfig\n): Promise<EditorKits> {\n if (!config) {\n return { kits: [new SafeAdvancedEditorKit(false)], collaborative: false };\n }\n\n try {\n const { HuddleYjsKit, defaultWsUrl } = await import('./collabKit');\n const url = config.wsUrl ?? defaultWsUrl();\n return {\n kits: [\n new SafeAdvancedEditorKit(true),\n new HuddleYjsKit(\n url,\n config.params ?? {},\n config.WebSocketPolyfill,\n config.user\n ),\n ],\n collaborative: true,\n };\n } catch (error) {\n console.warn(\n '[RichEditor] Collaborative editing unavailable — the Yjs kit failed to load. Continuing as a local editor.',\n error\n );\n config.onUnavailable?.(error);\n return { kits: [new SafeAdvancedEditorKit(false)], collaborative: false };\n }\n}\n","'use client';\n\nimport {\n forwardRef,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n} from 'react';\n\nimport { CoreEditor, type AssetLoad } from '@kerebron/editor';\nimport { createAssetLoad } from '@kerebron/wasm/web';\n\nimport { useIsDarkMode } from '../../hooks/useIsDarkMode';\nimport { createEditorKits, type CollabConfig } from './editorKits';\n\nexport type { CollabConfig } from './editorKits';\n\nconst MARKDOWN_TYPE = 'text/x-markdown';\n\n/**\n * The markdown converter's tree-sitter WASM init is not concurrency-safe, so\n * every editor's *first* load queues behind the previous one. Later loads (a\n * `value` change) are free — by then the grammars are warm.\n */\nlet initialLoadQueue: Promise<unknown> = Promise.resolve();\n\nfunction queueInitialLoad(load: () => Promise<void>): Promise<void> {\n const queued = initialLoadQueue.catch(() => undefined).then(load);\n initialLoadQueue = queued.catch(() => undefined);\n return queued;\n}\n\nexport interface RichEditorProps {\n /** Markdown to load. Changing it reloads the editor unless `collab` is set. */\n value?: string;\n /** Called with the editor's markdown content whenever it changes. */\n onChange?: (value: string) => void;\n /** Whether to render the live markdown output preview. Defaults to `false`. */\n showPreview?: boolean;\n /**\n * Enable live collaborative editing (Yjs) for the given room. When set, the\n * editor connects to the `/yjs` websocket relay and every peer in the same\n * `room` co-edits one shared document. Uncontrolled like `value` — remount via\n * `key` to switch rooms.\n *\n * Best-effort: if the Yjs kit cannot be loaded the editor still mounts, as a\n * local one, and `collab.onUnavailable` is called. Pass that callback if\n * unshared editing is something your users need to be told about.\n */\n collab?: CollabConfig;\n /** Read-only surface: no typing, and the content dims. */\n disabled?: boolean;\n /**\n * Id for the editor host element — an `aria-labelledby`/`aria-describedby`\n * anchor. The host is a `div`, not a labelable control, so a\n * `<label htmlFor>` will not associate; name the editor with `aria-label`\n * or `aria-labelledby` instead.\n */\n id?: string;\n /** Extra classes on the editor surface, beside `kb-component`. */\n className?: string;\n 'aria-label'?: string;\n 'aria-labelledby'?: string;\n /**\n * Where the tree-sitter WASM grammars load from. Defaults to\n * `createAssetLoad('/kerebron-wasm')`; supply your own when the host serves\n * `@kerebron/wasm`'s `assets/` somewhere else.\n */\n assetLoad?: AssetLoad;\n}\n\nexport interface RichEditorHandle {\n /**\n * The editor's markdown, awaiting the initial load. `onChange` can lag the\n * last keystroke, so read this on submit rather than trusting mirrored state.\n */\n getContent: () => Promise<string>;\n /** Focus the editor, restoring the caret where the writer left it. */\n focus: () => void;\n}\n\n/**\n * Markdown editor over Kerebron's `CoreEditor`.\n *\n * The editor mounts into a **disposable child div**: `CoreEditor.destroy()`\n * replaces its host element with a clone, which would strand React's ref (and,\n * under StrictMode's double-mount, leave the live editor detached behind a\n * dead clone).\n */\nconst RichEditor = forwardRef<RichEditorHandle, RichEditorProps>(\n function RichEditor(\n {\n value = '',\n onChange,\n showPreview = false,\n collab,\n disabled = false,\n id,\n className,\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledBy,\n assetLoad,\n },\n ref\n ) {\n const isDark = useIsDarkMode();\n const hostRef = useRef<HTMLDivElement>(null);\n const editorInstance = useRef<CoreEditor | null>(null);\n const onChangeRef = useRef(onChange);\n onChangeRef.current = onChange;\n // Mirrors what the editor last held, so an echo of our own `onChange`\n // doesn't reload the document out from under the caret.\n const valueRef = useRef(value);\n const readyRef = useRef<Promise<void> | null>(null);\n const loadingRef = useRef(false);\n const disabledRef = useRef(disabled);\n\n const [md, setMd] = useState<string>('');\n\n useEffect(() => {\n disabledRef.current = disabled;\n editorInstance.current?.view.setProps({\n editable: () => !disabledRef.current,\n });\n }, [disabled]);\n\n useEffect(() => {\n // In collab mode the CRDT owns the content; reloading would fight it.\n if (collab || value === valueRef.current) return;\n valueRef.current = value;\n const editor = editorInstance.current;\n if (!editor) return;\n\n loadingRef.current = true;\n void editor\n .loadDocumentText(MARKDOWN_TYPE, value)\n .catch(() => undefined)\n .finally(() => {\n if (editorInstance.current === editor) loadingRef.current = false;\n });\n // `collab` is fixed for the lifetime of the instance.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [value]);\n\n useEffect(() => {\n if (!hostRef.current) return;\n const host = hostRef.current;\n\n // Set on cleanup so async continuations (kit loading and the\n // `loadDocumentText` chain) don't touch the editor after `destroy()`.\n let disposed = false;\n let editor: CoreEditor | null = null;\n\n const mount = document.createElement('div');\n host.appendChild(mount);\n\n // Listen to transactions and update markdown preview\n const onTransaction = async () => {\n // Programmatic loads are not edits — reporting them would echo the\n // caller's own `value` back through `onChange`.\n if (loadingRef.current || !editorInstance.current) return;\n\n try {\n const buffer =\n await editorInstance.current.saveDocument(MARKDOWN_TYPE);\n const markdown = new globalThis.TextDecoder().decode(buffer);\n if (disposed) return;\n valueRef.current = markdown;\n setMd(markdown);\n onChangeRef.current?.(markdown);\n } catch (err) {\n console.error('Failed to save markdown:', err);\n }\n };\n\n // Initialize the editor. Both modes drop the teardown-unsafe extensions;\n // collaborative mode additionally swaps `history` for the Yjs CRDT sync\n // and lazy-loads the Yjs kit (see `editorKits.ts` for why).\n const setup = async () => {\n // `collaborative` is false when a room was asked for but the Yjs kit\n // could not be loaded — the editor is still created, just a local one,\n // so there is no room to join below.\n const { kits: editorKits, collaborative } =\n await createEditorKits(collab);\n if (disposed) return;\n\n editor = CoreEditor.create({\n element: mount,\n uri: 'file:///untitled.md',\n assetLoad: assetLoad ?? createAssetLoad('/kerebron-wasm'),\n editorKits,\n readOnly: disabledRef.current,\n });\n\n editorInstance.current = editor;\n // The contenteditable surface has no implicit ARIA role, so labeling\n // attributes are only permitted alongside an explicit textbox role.\n const surfaceAttributes =\n ariaLabel || ariaLabelledBy\n ? {\n role: 'textbox',\n 'aria-multiline': 'true',\n ...(ariaLabel ? { 'aria-label': ariaLabel } : {}),\n ...(ariaLabelledBy\n ? { 'aria-labelledby': ariaLabelledBy }\n : {}),\n }\n : null;\n editor.view.setProps({\n editable: () => !disabledRef.current,\n ...(surfaceAttributes ? { attributes: surfaceAttributes } : {}),\n });\n editor.addEventListener('transaction', onTransaction);\n\n // Seed initial content, then populate the preview once on mount.\n //\n // In collaborative mode we still load the local markdown first, then\n // join the room: the Yjs binding seeds an *empty* shared document from\n // this content on the first join, and overwrites the editor with the\n // shared content when the room already has edits — so the stored\n // markdown is the starting point without ever double-inserting.\n const joinRoom = () => {\n if (collaborative && collab && editor && !disposed) {\n (\n editor.run as Record<string, (...args: unknown[]) => boolean>\n ).changeRoom?.(collab.room);\n reseedWhenRoomStaysEmpty();\n }\n };\n\n // The Yjs binding is supposed to seed an empty room from the local\n // content, but the sync import can land as an overwrite that blanks\n // the just-loaded seed (observed with extension-yjs 0.8.x). Heal it:\n // once the join settles, an empty document with a non-empty seed\n // means nobody's content won — reload the seed, which the binding\n // then pushes into the room. Joiners pass no value, so exactly one\n // participant ever does this.\n const seed = valueRef.current;\n const reseedWhenRoomStaysEmpty = () => {\n if (!seed) return;\n const check = async (attempt: number) => {\n if (disposed || !editorInstance.current) return;\n try {\n const buffer =\n await editorInstance.current.saveDocument(MARKDOWN_TYPE);\n const current = new globalThis.TextDecoder()\n .decode(buffer)\n .trim();\n if (disposed || !editorInstance.current) return;\n if (current) return; // somebody's content arrived — done\n if (attempt >= 2) {\n await editorInstance.current.loadDocumentText(\n MARKDOWN_TYPE,\n seed\n );\n return;\n }\n setTimeout(() => void check(attempt + 1), 300);\n } catch {\n // A failed probe must not break the editor; the room stays as-is.\n }\n };\n setTimeout(() => void check(0), 300);\n };\n\n if (valueRef.current) {\n await queueInitialLoad(() =>\n editor!.loadDocumentText(MARKDOWN_TYPE, valueRef.current)\n );\n await onTransaction();\n joinRoom();\n } else {\n void onTransaction();\n joinRoom();\n }\n };\n\n readyRef.current = setup().catch((err) =>\n console.error('Failed to set up editor:', err)\n );\n\n // Cleanup on unmount\n return () => {\n disposed = true;\n editorInstance.current = null; // makes onTransaction's guard effective\n editor?.removeEventListener('transaction', onTransaction);\n editor?.destroy();\n readyRef.current = null;\n host.replaceChildren();\n };\n // Initial `value`/`collab` are intentionally only applied on mount\n // (uncontrolled). Remount via `key` to switch rooms.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useImperativeHandle(\n ref,\n () => ({\n getContent: async (): Promise<string> => {\n await readyRef.current;\n const editor = editorInstance.current;\n if (!editor) return valueRef.current;\n const buffer = await editor.saveDocument(MARKDOWN_TYPE);\n const markdown = new globalThis.TextDecoder().decode(buffer);\n valueRef.current = markdown;\n return markdown;\n },\n focus: (): void => {\n const apply = (): void => {\n const view = editorInstance.current?.view as\n | { focus?: () => void }\n | undefined;\n if (view?.focus) {\n view.focus();\n return;\n }\n hostRef.current\n ?.querySelector<HTMLElement>('[contenteditable=\"true\"], textarea')\n ?.focus();\n };\n // Callers focus on mount; the editor may still be loading its kits.\n if (editorInstance.current) apply();\n else void readyRef.current?.then(apply);\n },\n }),\n []\n );\n\n return (\n <div>\n <div>\n <div\n ref={hostRef}\n id={id}\n className={[\n 'kb-component',\n isDark ? 'kb-component--dark' : '',\n className ?? '',\n ]\n .filter(Boolean)\n .join(' ')}\n aria-label={ariaLabel}\n aria-labelledby={ariaLabelledBy}\n aria-disabled={disabled || undefined}\n style={{\n isolation: 'isolate',\n opacity: disabled ? 0.65 : undefined,\n pointerEvents: disabled ? 'none' : undefined,\n }}\n />\n </div>\n\n {showPreview && (\n <div>\n <div>\n <h5>Markdown Output</h5>\n <pre>{md}</pre>\n </div>\n </div>\n )}\n </div>\n );\n }\n);\n\nRichEditor.displayName = 'RichEditor';\n\nexport { RichEditor };\n","import React, { useEffect, useRef } from 'react';\n\nimport { CoreEditor } from '@kerebron/editor';\nimport { CodeEditorKit } from '@kerebron/editor-kits/CodeEditorKit';\nimport { createAssetLoad } from '@kerebron/wasm/web';\n\nexport interface CodeEditorProps {\n /** Initial source code to load into the editor. */\n value?: string;\n /** Called with the editor's contents whenever they change. */\n onChange?: (value: string) => void;\n /** Language/grammar to use for syntax highlighting. Defaults to `typescript`. */\n lang?: string;\n}\n\nconst CodeEditor: React.FC<CodeEditorProps> = ({\n value = '',\n onChange,\n lang = 'typescript',\n}) => {\n const editorRef = useRef<HTMLDivElement>(null);\n const editorInstance = useRef<CoreEditor | null>(null);\n const onChangeRef = useRef(onChange);\n onChangeRef.current = onChange;\n\n useEffect(() => {\n const root = editorRef.current;\n if (!root) return;\n\n const applySelectLabel = () => {\n root.querySelectorAll('select.codejar-select').forEach((element) => {\n if (!element.getAttribute('aria-label')) {\n element.setAttribute('aria-label', 'Code editor language');\n }\n });\n };\n\n applySelectLabel();\n const observer = new MutationObserver(() => applySelectLabel());\n observer.observe(root, { childList: true, subtree: true });\n return () => observer.disconnect();\n }, []);\n\n useEffect(() => {\n if (!editorRef.current) return;\n\n // Initialize the editor\n const editor = CoreEditor.create({\n element: editorRef.current,\n uri: 'file:///untitled.ts',\n assetLoad: createAssetLoad('/kerebron-wasm'),\n editorKits: [new CodeEditorKit(lang)],\n });\n\n editorInstance.current = editor;\n\n // Surface edits to callers.\n const onTransaction = async () => {\n if (!editorInstance.current) return;\n\n try {\n const buffer = await editorInstance.current.saveDocument('text/plain');\n onChangeRef.current?.(new globalThis.TextDecoder().decode(buffer));\n } catch (err) {\n console.error('Failed to read code:', err);\n }\n };\n\n editor.addEventListener('transaction', onTransaction);\n\n // Seed initial content on mount.\n if (value) {\n editor\n .loadDocumentText('text/plain', value)\n .catch((err) => console.error('Failed to load code:', err));\n }\n\n // Cleanup on unmount\n return () => {\n editor.removeEventListener('transaction', onTransaction);\n editor.destroy();\n };\n // Initial `value`/`lang` are intentionally only applied on mount.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n <div>\n <div>\n <div ref={editorRef} className=\"kb-component\" />\n </div>\n </div>\n );\n};\n\nCodeEditor.displayName = 'CodeEditor';\n\nexport { CodeEditor };\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mieweb/ui",
3
- "version": "0.10.0-dev.4",
3
+ "version": "0.10.0-dev.5",
4
4
  "description": "A themeable, accessible React component library built with Tailwind CSS",
5
5
  "author": "Medical Informatics Engineering, Inc.",
6
6
  "license": "SEE LICENSE IN LICENSE",