@usememos/editor 26.10.2 → 26.10.4

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/react.js CHANGED
@@ -3,7 +3,7 @@ import { Editor } from "@usememos/editor";
3
3
  import { forwardRef, useEffect, useRef, useState } from "react";
4
4
  import { flushSync } from "react-dom";
5
5
  import { jsx } from "react/jsx-runtime";
6
- var LIVE = ["placeholder", "editable", "taskToggle", "attributes", "resolveImageSrc", "theme", "extensions"];
6
+ var LIVE = ["placeholder", "editable", "taskToggle", "attributes", "resolveUrl", "onLinkClick", "theme", "extensions"];
7
7
  var extensionKey = (extensions) => (extensions ?? []).map((e) => e.name).join("\n");
8
8
  var MarkdownEditor = forwardRef(function MarkdownEditor2(props, ref) {
9
9
  const container = useRef(null);
@@ -106,7 +106,8 @@ function useEditor(options, deps = []) {
106
106
  onChange: (markdown, e) => latest.current.onChange?.(markdown, e),
107
107
  onSubmit: (markdown, e) => latest.current.onSubmit?.(markdown, e),
108
108
  onFocus: (e) => latest.current.onFocus?.(e),
109
- onBlur: (e) => latest.current.onBlur?.(e)
109
+ onBlur: (e) => latest.current.onBlur?.(e),
110
+ onLinkClick: (ctx) => latest.current.onLinkClick?.(ctx)
110
111
  });
111
112
  if (o.autofocus) pendingAutofocus.set(instance, o.autofocus === "end" ? "end" : "start");
112
113
  setEditor(instance);
package/dist/react.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/react/index.tsx"],
4
- "sourcesContent": ["import { Editor, type EditorOptions, type SuggestionState } from '@usememos/editor';\nimport { type CSSProperties, type ForwardedRef, forwardRef, useEffect, useRef, useState } from 'react';\nimport { flushSync } from 'react-dom';\n\nexport type { Editor, SuggestionState } from '@usememos/editor';\n\n/** Constructor options that the React components take as props. */\ntype EditorProps = Pick<\n EditorOptions,\n | 'markdown'\n | 'extensions'\n | 'placeholder'\n | 'editable'\n | 'taskToggle'\n | 'autofocus'\n | 'attributes'\n | 'resolveImageSrc'\n | 'theme'\n | 'toolbar'\n | 'slashMenu'\n | 'labels'\n | 'icons'\n>;\n\nexport interface MarkdownEditorProps extends EditorProps {\n /** Markdown. The editor updates only when this is not a value it emitted itself. */\n value?: string;\n /** Initial Markdown for uncontrolled use. */\n defaultValue?: string;\n /** Called after document changes, at most once per animation frame. */\n onChange?: (markdown: string) => void;\n /** Called on Mod+Enter or Ctrl+Enter with the current Markdown. */\n onSubmit?: (markdown: string) => void;\n onFocus?: () => void;\n onBlur?: () => void;\n className?: string;\n style?: CSSProperties;\n}\n\n/** Options that `setOptions` applies without recreating the editor. `extensions` updates suggestion callbacks only. */\nconst LIVE = ['placeholder', 'editable', 'taskToggle', 'attributes', 'resolveImageSrc', 'theme', 'extensions'] as const;\n\n/** The extension list's identity for recreating the editor: names, so an inline array does not recreate it on every render. */\nconst extensionKey = (extensions: EditorOptions['extensions']) => (extensions ?? []).map((e) => e.name).join('\\n');\n\n/**\n * The editor as a controlled React component. A `ref` gives the core `Editor`.\n *\n * `placeholder`, `editable`, `taskToggle`, `attributes`, `resolveImageSrc` and `theme` update live.\n * A change to the names in `extensions` recreates the editor, keeping its\n * Markdown; with the same names, the callbacks of `suggestion()` extensions\n * (`items`, `command`, `match`, `allow`) update live. Other props are read\n * when the editor is created; change the component's `key` to apply new values.\n *\n * A `value` that arrives while an input method is composing text is applied\n * when the composition ends, so it does not break the composition.\n */\nexport const MarkdownEditor = forwardRef(function MarkdownEditor(props: MarkdownEditorProps, ref: ForwardedRef<Editor | null>) {\n const container = useRef<HTMLDivElement>(null);\n const editorRef = useRef<Editor | null>(null);\n // Values the editor emitted that the parent has not passed back yet, oldest\n // first. While the user keeps typing, React may hand back an older one;\n // those echoes must not reset the document.\n const pending = useRef<string[]>([]);\n // An outside value that arrived during IME composition.\n const deferred = useRef<string | null>(null);\n // Callbacks are read through a ref so changing them does not recreate the editor.\n const latest = useRef(props);\n latest.current = props;\n const extensions = extensionKey(props.extensions);\n\n useEffect(() => {\n const { value, defaultValue, onChange, onSubmit, onFocus, onBlur, className, style, ...options } = latest.current;\n const previous = editorRef.current;\n const editor = new Editor({\n ...options,\n element: container.current!,\n content: previous?.getMarkdown() ?? value ?? defaultValue ?? '',\n onChange: (markdown) => {\n pending.current.push(markdown);\n if (pending.current.length > 100) pending.current.shift();\n // Render the parent's update now, as React does for a native input's\n // onChange. Left to React's scheduler, it can still be waiting when\n // the parent sets a new value (clearing the box on submit) that equals\n // the value it last rendered; the value effect would then not run.\n flushSync(() => latest.current.onChange?.(markdown));\n },\n onSubmit: (markdown) => latest.current.onSubmit?.(markdown),\n onFocus: () => latest.current.onFocus?.(),\n onBlur: () => latest.current.onBlur?.(),\n });\n editorRef.current = editor;\n pending.current = [];\n assignRef(ref, editor);\n const root = container.current!;\n const onCompositionEnd = () => {\n // Runs after the editor's own compositionend handler, which was added first.\n const value = deferred.current;\n deferred.current = null;\n if (value !== null && value !== editor.getMarkdown()) {\n pending.current = [];\n editor.setMarkdown(value);\n }\n };\n root.addEventListener('compositionend', onCompositionEnd);\n return () => {\n root.removeEventListener('compositionend', onCompositionEnd);\n editor.destroy();\n if (editorRef.current === editor) editorRef.current = null;\n assignRef(ref, null);\n };\n // Recreate only when the extension names change; see the note on the component.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [extensions]);\n\n useEffect(() => {\n const editor = editorRef.current;\n if (!editor || props.value === undefined) return;\n const echo = pending.current.indexOf(props.value);\n if (echo >= 0) {\n // The parent caught up to a value the editor emitted.\n pending.current.splice(0, echo + 1);\n return;\n }\n if (props.value === editor.getMarkdown()) return;\n if (editor.isComposing) {\n deferred.current = props.value;\n return;\n }\n pending.current = [];\n editor.setMarkdown(props.value);\n }, [props.value]);\n\n useLiveOptions(editorRef, props);\n\n return <div ref={container} className={props.className} style={props.style} />;\n});\n\n/** Applies the live options when they change. */\nfunction useLiveOptions(editorRef: { current: Editor | null }, props: EditorProps): void {\n const applied = useRef<{ editor: Editor | null; props: Partial<EditorProps> }>({ editor: null, props: {} });\n useEffect(() => {\n const editor = editorRef.current;\n if (!editor) return;\n if (applied.current.editor !== editor) {\n // A new editor was created with these props.\n applied.current = { editor, props: { ...props } };\n return;\n }\n const changed: Partial<Pick<EditorOptions, (typeof LIVE)[number]>> = {};\n let any = false;\n for (const key of LIVE) {\n if (props[key] === applied.current.props[key]) continue;\n (changed as Record<string, unknown>)[key] = key === 'editable' ? (props.editable ?? true) : key === 'taskToggle' ? (props.taskToggle ?? false) : props[key];\n any = true;\n }\n applied.current = { editor, props: { ...props } };\n if (any) editor.setOptions(changed);\n });\n}\n\n/**\n * Creates an editor for the lifetime of the component, or until a value in\n * `deps` changes. Returns null until the editor exists. Pair it with\n * `<EditorContent editor={editor} />`, which shows it.\n *\n * Callbacks in `options` are read when called, so they may change between\n * renders without recreating the editor. So do the callbacks of\n * `suggestion()` extensions, matched by name.\n */\nexport function useEditor(options: Omit<EditorOptions, 'element'>, deps: readonly unknown[] = []): Editor | null {\n const [editor, setEditor] = useState<Editor | null>(null);\n const latest = useRef(options);\n latest.current = options;\n\n useEffect(() => {\n if (editor && options.extensions) editor.setOptions({ extensions: options.extensions });\n }, [editor, options.extensions]);\n\n useEffect(() => {\n const o = latest.current;\n const element = document.createElement('div');\n const instance = new Editor({\n ...o,\n element,\n // A detached element cannot take focus; EditorContent focuses once mounted.\n autofocus: false,\n onChange: (markdown, e) => latest.current.onChange?.(markdown, e),\n onSubmit: (markdown, e) => latest.current.onSubmit?.(markdown, e),\n onFocus: (e) => latest.current.onFocus?.(e),\n onBlur: (e) => latest.current.onBlur?.(e),\n });\n if (o.autofocus) pendingAutofocus.set(instance, o.autofocus === 'end' ? 'end' : 'start');\n setEditor(instance);\n return () => {\n instance.destroy();\n setEditor(null);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n\n return editor;\n}\n\n/**\n * The open autocomplete popup of `editor`, or of its suggestion `name`, and\n * a re-render on each change. With `render: false` on a suggestion, draw your\n * own popup from it: put it at `state.anchorRect()`, give the listbox\n * `id={state.listboxId}` and each option `id={state.optionId(i)}`, highlight\n * `state.active`, and call `editor.suggestion.accept(i)` on click.\n */\nexport function useSuggestion(editor: Editor | null, name?: string): SuggestionState | null {\n const select = (state: SuggestionState | null | undefined) => (state && (name === undefined || state.name === name) ? state : null);\n const [state, setState] = useState<SuggestionState | null>(() => select(editor?.suggestion.state));\n useEffect(() => {\n if (!editor) {\n setState(null);\n return;\n }\n setState(select(editor.suggestion.state));\n return editor.on('suggestionChange', ({ state }) => setState(select(state)));\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [editor, name]);\n return state;\n}\n\nexport interface EditorContentProps {\n editor: Editor | null;\n className?: string;\n style?: CSSProperties;\n}\n\n/** Shows an editor created with `useEditor`. */\nexport function EditorContent({ editor, className, style }: EditorContentProps) {\n const container = useRef<HTMLDivElement>(null);\n useEffect(() => {\n const host = container.current;\n if (!editor || !host) return;\n host.appendChild(editor.root);\n const autofocus = pendingAutofocus.get(editor);\n if (autofocus) {\n pendingAutofocus.delete(editor);\n editor.commands.focus(autofocus);\n }\n return () => {\n if (editor.root.parentNode === host) host.removeChild(editor.root);\n };\n }, [editor]);\n return <div ref={container} className={className} style={style} />;\n}\n\n/** Where to focus an editor from `useEditor` once `EditorContent` mounts it. */\nconst pendingAutofocus = new WeakMap<Editor, 'start' | 'end'>();\n\nfunction assignRef<T>(ref: ForwardedRef<T>, value: T): void {\n if (typeof ref === 'function') ref(value);\n else if (ref) ref.current = value;\n}\n"],
5
- "mappings": ";AAAA,SAAS,cAAwD;AACjE,SAAgD,YAAY,WAAW,QAAQ,gBAAgB;AAC/F,SAAS,iBAAiB;AAqIjB;AA/FT,IAAM,OAAO,CAAC,eAAe,YAAY,cAAc,cAAc,mBAAmB,SAAS,YAAY;AAG7G,IAAM,eAAe,CAAC,gBAA6C,cAAc,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,IAAI;AAc1G,IAAM,iBAAiB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,KAAK,CAAC;AACjG,YAAU,MAAM;AACd,QAAI,CAAC,QAAQ;AACX,eAAS,IAAI;AACb;AAAA,IACF;AACA,aAAS,OAAO,OAAO,WAAW,KAAK,CAAC;AACxC,WAAO,OAAO,GAAG,oBAAoB,CAAC,EAAE,OAAAA,OAAM,MAAM,SAAS,OAAOA,MAAK,CAAC,CAAC;AAAA,EAE7E,GAAG,CAAC,QAAQ,IAAI,CAAC;AACjB,SAAO;AACT;AASO,SAAS,cAAc,EAAE,QAAQ,WAAW,MAAM,GAAuB;AAC9E,QAAM,YAAY,OAAuB,IAAI;AAC7C,YAAU,MAAM;AACd,UAAM,OAAO,UAAU;AACvB,QAAI,CAAC,UAAU,CAAC,KAAM;AACtB,SAAK,YAAY,OAAO,IAAI;AAC5B,UAAM,YAAY,iBAAiB,IAAI,MAAM;AAC7C,QAAI,WAAW;AACb,uBAAiB,OAAO,MAAM;AAC9B,aAAO,SAAS,MAAM,SAAS;AAAA,IACjC;AACA,WAAO,MAAM;AACX,UAAI,OAAO,KAAK,eAAe,KAAM,MAAK,YAAY,OAAO,IAAI;AAAA,IACnE;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AACX,SAAO,oBAAC,SAAI,KAAK,WAAW,WAAsB,OAAc;AAClE;AAGA,IAAM,mBAAmB,oBAAI,QAAiC;AAE9D,SAAS,UAAa,KAAsB,OAAgB;AAC1D,MAAI,OAAO,QAAQ,WAAY,KAAI,KAAK;AAAA,WAC/B,IAAK,KAAI,UAAU;AAC9B;",
4
+ "sourcesContent": ["import { Editor, type EditorOptions, type SuggestionState } from '@usememos/editor';\nimport { type CSSProperties, type ForwardedRef, forwardRef, useEffect, useRef, useState } from 'react';\nimport { flushSync } from 'react-dom';\n\nexport type { Editor, SuggestionState } from '@usememos/editor';\n\n/** Constructor options that the React components take as props. */\ntype EditorProps = Pick<\n EditorOptions,\n | 'markdown'\n | 'extensions'\n | 'placeholder'\n | 'editable'\n | 'taskToggle'\n | 'autofocus'\n | 'attributes'\n | 'resolveUrl'\n | 'referrerPolicy'\n | 'headingIds'\n | 'onLinkClick'\n | 'theme'\n | 'toolbar'\n | 'slashMenu'\n | 'labels'\n | 'icons'\n>;\n\nexport interface MarkdownEditorProps extends EditorProps {\n /** Markdown. The editor updates only when this is not a value it emitted itself. */\n value?: string;\n /** Initial Markdown for uncontrolled use. */\n defaultValue?: string;\n /** Called after document changes, at most once per animation frame. */\n onChange?: (markdown: string) => void;\n /** Called on Mod+Enter or Ctrl+Enter with the current Markdown. */\n onSubmit?: (markdown: string) => void;\n onFocus?: () => void;\n onBlur?: () => void;\n className?: string;\n style?: CSSProperties;\n}\n\n/** Options that `setOptions` applies without recreating the editor. `extensions` updates suggestion callbacks only. */\nconst LIVE = ['placeholder', 'editable', 'taskToggle', 'attributes', 'resolveUrl', 'onLinkClick', 'theme', 'extensions'] as const;\n\n/** The extension list's identity for recreating the editor: names, so an inline array does not recreate it on every render. */\nconst extensionKey = (extensions: EditorOptions['extensions']) => (extensions ?? []).map((e) => e.name).join('\\n');\n\n/**\n * The editor as a controlled React component. A `ref` gives the core `Editor`.\n *\n * `placeholder`, `editable`, `taskToggle`, `attributes`, `resolveUrl`, `onLinkClick` and `theme` update live.\n * A change to the names in `extensions` recreates the editor, keeping its\n * Markdown; with the same names, the callbacks of `suggestion()` extensions\n * (`items`, `command`, `match`, `allow`) update live. Other props are read\n * when the editor is created; change the component's `key` to apply new values.\n *\n * A `value` that arrives while an input method is composing text is applied\n * when the composition ends, so it does not break the composition.\n */\nexport const MarkdownEditor = forwardRef(function MarkdownEditor(props: MarkdownEditorProps, ref: ForwardedRef<Editor | null>) {\n const container = useRef<HTMLDivElement>(null);\n const editorRef = useRef<Editor | null>(null);\n // Values the editor emitted that the parent has not passed back yet, oldest\n // first. While the user keeps typing, React may hand back an older one;\n // those echoes must not reset the document.\n const pending = useRef<string[]>([]);\n // An outside value that arrived during IME composition.\n const deferred = useRef<string | null>(null);\n // Callbacks are read through a ref so changing them does not recreate the editor.\n const latest = useRef(props);\n latest.current = props;\n const extensions = extensionKey(props.extensions);\n\n useEffect(() => {\n const { value, defaultValue, onChange, onSubmit, onFocus, onBlur, className, style, ...options } = latest.current;\n const previous = editorRef.current;\n const editor = new Editor({\n ...options,\n element: container.current!,\n content: previous?.getMarkdown() ?? value ?? defaultValue ?? '',\n onChange: (markdown) => {\n pending.current.push(markdown);\n if (pending.current.length > 100) pending.current.shift();\n // Render the parent's update now, as React does for a native input's\n // onChange. Left to React's scheduler, it can still be waiting when\n // the parent sets a new value (clearing the box on submit) that equals\n // the value it last rendered; the value effect would then not run.\n flushSync(() => latest.current.onChange?.(markdown));\n },\n onSubmit: (markdown) => latest.current.onSubmit?.(markdown),\n onFocus: () => latest.current.onFocus?.(),\n onBlur: () => latest.current.onBlur?.(),\n });\n editorRef.current = editor;\n pending.current = [];\n assignRef(ref, editor);\n const root = container.current!;\n const onCompositionEnd = () => {\n // Runs after the editor's own compositionend handler, which was added first.\n const value = deferred.current;\n deferred.current = null;\n if (value !== null && value !== editor.getMarkdown()) {\n pending.current = [];\n editor.setMarkdown(value);\n }\n };\n root.addEventListener('compositionend', onCompositionEnd);\n return () => {\n root.removeEventListener('compositionend', onCompositionEnd);\n editor.destroy();\n if (editorRef.current === editor) editorRef.current = null;\n assignRef(ref, null);\n };\n // Recreate only when the extension names change; see the note on the component.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [extensions]);\n\n useEffect(() => {\n const editor = editorRef.current;\n if (!editor || props.value === undefined) return;\n const echo = pending.current.indexOf(props.value);\n if (echo >= 0) {\n // The parent caught up to a value the editor emitted.\n pending.current.splice(0, echo + 1);\n return;\n }\n if (props.value === editor.getMarkdown()) return;\n if (editor.isComposing) {\n deferred.current = props.value;\n return;\n }\n pending.current = [];\n editor.setMarkdown(props.value);\n }, [props.value]);\n\n useLiveOptions(editorRef, props);\n\n return <div ref={container} className={props.className} style={props.style} />;\n});\n\n/** Applies the live options when they change. */\nfunction useLiveOptions(editorRef: { current: Editor | null }, props: EditorProps): void {\n const applied = useRef<{ editor: Editor | null; props: Partial<EditorProps> }>({ editor: null, props: {} });\n useEffect(() => {\n const editor = editorRef.current;\n if (!editor) return;\n if (applied.current.editor !== editor) {\n // A new editor was created with these props.\n applied.current = { editor, props: { ...props } };\n return;\n }\n const changed: Partial<Pick<EditorOptions, (typeof LIVE)[number]>> = {};\n let any = false;\n for (const key of LIVE) {\n if (props[key] === applied.current.props[key]) continue;\n (changed as Record<string, unknown>)[key] = key === 'editable' ? (props.editable ?? true) : key === 'taskToggle' ? (props.taskToggle ?? false) : props[key];\n any = true;\n }\n applied.current = { editor, props: { ...props } };\n if (any) editor.setOptions(changed);\n });\n}\n\n/**\n * Creates an editor for the lifetime of the component, or until a value in\n * `deps` changes. Returns null until the editor exists. Pair it with\n * `<EditorContent editor={editor} />`, which shows it.\n *\n * Callbacks in `options` are read when called, so they may change between\n * renders without recreating the editor. So do the callbacks of\n * `suggestion()` extensions, matched by name.\n */\nexport function useEditor(options: Omit<EditorOptions, 'element'>, deps: readonly unknown[] = []): Editor | null {\n const [editor, setEditor] = useState<Editor | null>(null);\n const latest = useRef(options);\n latest.current = options;\n\n useEffect(() => {\n if (editor && options.extensions) editor.setOptions({ extensions: options.extensions });\n }, [editor, options.extensions]);\n\n useEffect(() => {\n const o = latest.current;\n const element = document.createElement('div');\n const instance = new Editor({\n ...o,\n element,\n // A detached element cannot take focus; EditorContent focuses once mounted.\n autofocus: false,\n onChange: (markdown, e) => latest.current.onChange?.(markdown, e),\n onSubmit: (markdown, e) => latest.current.onSubmit?.(markdown, e),\n onFocus: (e) => latest.current.onFocus?.(e),\n onBlur: (e) => latest.current.onBlur?.(e),\n onLinkClick: (ctx) => latest.current.onLinkClick?.(ctx),\n });\n if (o.autofocus) pendingAutofocus.set(instance, o.autofocus === 'end' ? 'end' : 'start');\n setEditor(instance);\n return () => {\n instance.destroy();\n setEditor(null);\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps);\n\n return editor;\n}\n\n/**\n * The open autocomplete popup of `editor`, or of its suggestion `name`, and\n * a re-render on each change. With `render: false` on a suggestion, draw your\n * own popup from it: put it at `state.anchorRect()`, give the listbox\n * `id={state.listboxId}` and each option `id={state.optionId(i)}`, highlight\n * `state.active`, and call `editor.suggestion.accept(i)` on click.\n */\nexport function useSuggestion(editor: Editor | null, name?: string): SuggestionState | null {\n const select = (state: SuggestionState | null | undefined) => (state && (name === undefined || state.name === name) ? state : null);\n const [state, setState] = useState<SuggestionState | null>(() => select(editor?.suggestion.state));\n useEffect(() => {\n if (!editor) {\n setState(null);\n return;\n }\n setState(select(editor.suggestion.state));\n return editor.on('suggestionChange', ({ state }) => setState(select(state)));\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [editor, name]);\n return state;\n}\n\nexport interface EditorContentProps {\n editor: Editor | null;\n className?: string;\n style?: CSSProperties;\n}\n\n/** Shows an editor created with `useEditor`. */\nexport function EditorContent({ editor, className, style }: EditorContentProps) {\n const container = useRef<HTMLDivElement>(null);\n useEffect(() => {\n const host = container.current;\n if (!editor || !host) return;\n host.appendChild(editor.root);\n const autofocus = pendingAutofocus.get(editor);\n if (autofocus) {\n pendingAutofocus.delete(editor);\n editor.commands.focus(autofocus);\n }\n return () => {\n if (editor.root.parentNode === host) host.removeChild(editor.root);\n };\n }, [editor]);\n return <div ref={container} className={className} style={style} />;\n}\n\n/** Where to focus an editor from `useEditor` once `EditorContent` mounts it. */\nconst pendingAutofocus = new WeakMap<Editor, 'start' | 'end'>();\n\nfunction assignRef<T>(ref: ForwardedRef<T>, value: T): void {\n if (typeof ref === 'function') ref(value);\n else if (ref) ref.current = value;\n}\n"],
5
+ "mappings": ";AAAA,SAAS,cAAwD;AACjE,SAAgD,YAAY,WAAW,QAAQ,gBAAgB;AAC/F,SAAS,iBAAiB;AAwIjB;AA/FT,IAAM,OAAO,CAAC,eAAe,YAAY,cAAc,cAAc,cAAc,eAAe,SAAS,YAAY;AAGvH,IAAM,eAAe,CAAC,gBAA6C,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QAAM,SAAS,CAACC,WAA+CA,WAAU,SAAS,UAAaA,OAAM,SAAS,QAAQA,SAAQ;AAC9H,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAiC,MAAM,OAAO,QAAQ,WAAW,KAAK,CAAC;AACjG,YAAU,MAAM;AACd,QAAI,CAAC,QAAQ;AACX,eAAS,IAAI;AACb;AAAA,IACF;AACA,aAAS,OAAO,OAAO,WAAW,KAAK,CAAC;AACxC,WAAO,OAAO,GAAG,oBAAoB,CAAC,EAAE,OAAAA,OAAM,MAAM,SAAS,OAAOA,MAAK,CAAC,CAAC;AAAA,EAE7E,GAAG,CAAC,QAAQ,IAAI,CAAC;AACjB,SAAO;AACT;AASO,SAAS,cAAc,EAAE,QAAQ,WAAW,MAAM,GAAuB;AAC9E,QAAM,YAAY,OAAuB,IAAI;AAC7C,YAAU,MAAM;AACd,UAAM,OAAO,UAAU;AACvB,QAAI,CAAC,UAAU,CAAC,KAAM;AACtB,SAAK,YAAY,OAAO,IAAI;AAC5B,UAAM,YAAY,iBAAiB,IAAI,MAAM;AAC7C,QAAI,WAAW;AACb,uBAAiB,OAAO,MAAM;AAC9B,aAAO,SAAS,MAAM,SAAS;AAAA,IACjC;AACA,WAAO,MAAM;AACX,UAAI,OAAO,KAAK,eAAe,KAAM,MAAK,YAAY,OAAO,IAAI;AAAA,IACnE;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AACX,SAAO,oBAAC,SAAI,KAAK,WAAW,WAAsB,OAAc;AAClE;AAGA,IAAM,mBAAmB,oBAAI,QAAiC;AAE9D,SAAS,UAAa,KAAsB,OAAgB;AAC1D,MAAI,OAAO,QAAQ,WAAY,KAAI,KAAK;AAAA,WAC/B,IAAK,KAAI,UAAU;AAC9B;",
6
6
  "names": ["MarkdownEditor", "value", "state"]
7
7
  }
package/dist/style.css CHANGED
@@ -115,6 +115,29 @@
115
115
  display: flex;
116
116
  align-items: center;
117
117
  }
118
+ .mbe-root .mbe-code-copy {
119
+ margin-inline-start: auto;
120
+ display: inline-flex;
121
+ align-items: center;
122
+ justify-content: center;
123
+ border: 0;
124
+ background: none;
125
+ padding: 2px;
126
+ font: inherit;
127
+ color: inherit;
128
+ cursor: pointer;
129
+ opacity: 0;
130
+ }
131
+ .mbe-root .mbe-code:hover .mbe-code-copy,
132
+ .mbe-root .mbe-code-copy:focus-visible,
133
+ .mbe-root .mbe-code-copy.mbe-copied {
134
+ opacity: 1;
135
+ }
136
+ @media (hover: none) {
137
+ .mbe-root .mbe-code-copy {
138
+ opacity: 1;
139
+ }
140
+ }
118
141
  .mbe-root .mbe-code-lang {
119
142
  font: inherit;
120
143
  color: inherit;
@@ -446,6 +469,22 @@
446
469
  .mbe-root .mbe-image {
447
470
  border-radius: 8px;
448
471
  }
472
+ .mbe-root .mbe-footnote-ref {
473
+ font-size: 0.75em;
474
+ line-height: 0;
475
+ color: var(--mbe-link);
476
+ }
477
+ .mbe-root.mbe-readonly .mbe-footnote-ref {
478
+ cursor: pointer;
479
+ }
480
+ .mbe-root > .mbe-footnote {
481
+ font-size: 0.875em;
482
+ color: var(--mbe-muted);
483
+ }
484
+ .mbe-root .mbe-footnote-label {
485
+ margin-inline-end: 0.375em;
486
+ color: var(--mbe-link);
487
+ }
449
488
  .mbe-root > blockquote {
450
489
  border-inline-start: 3px solid var(--mbe-quote-border);
451
490
  padding-inline-start: 12px;
@@ -466,7 +505,7 @@
466
505
  border-color: var(--mbe-accent);
467
506
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='3' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M20 6 9 17l-5-5'/%3E%3C/svg%3E");
468
507
  }
469
- .mbe-root > .mbe-code {
508
+ .mbe-root > .mbe-code:not(.mbe-view-block) {
470
509
  background: var(--mbe-block-code-bg);
471
510
  border-radius: var(--mbe-radius);
472
511
  overflow: hidden;
@@ -482,6 +521,17 @@
482
521
  color: var(--mbe-muted);
483
522
  opacity: 1;
484
523
  }
524
+ .mbe-root .mbe-code-copy {
525
+ color: var(--mbe-muted);
526
+ border-radius: 4px;
527
+ }
528
+ .mbe-root .mbe-code-copy:hover {
529
+ color: var(--mbe-text);
530
+ background: var(--mbe-hover);
531
+ }
532
+ .mbe-root .mbe-code-copy.mbe-copied {
533
+ color: var(--mbe-accent);
534
+ }
485
535
  .mbe-root > .mbe-code pre,
486
536
  .mbe-root > pre.mbe-raw {
487
537
  font: 14px/22px var(--mbe-mono);
package/dist/theme.css CHANGED
@@ -93,6 +93,11 @@
93
93
  .mbe-root :is(.mbe-raw-html, .mbe-token) { color: var(--mbe-muted); }
94
94
  .mbe-root code { background: var(--mbe-code-bg); border-radius: 4px; padding: 2px 4px; }
95
95
  .mbe-root .mbe-image { border-radius: 8px; }
96
+ /* Footnotes, rendered: a reference is a small raised label, a definition a small muted note. */
97
+ .mbe-root .mbe-footnote-ref { font-size: 0.75em; line-height: 0; color: var(--mbe-link); }
98
+ .mbe-root.mbe-readonly .mbe-footnote-ref { cursor: pointer; }
99
+ .mbe-root > .mbe-footnote { font-size: 0.875em; color: var(--mbe-muted); }
100
+ .mbe-root .mbe-footnote-label { margin-inline-end: 0.375em; color: var(--mbe-link); }
96
101
 
97
102
  /* Quote */
98
103
  .mbe-root > blockquote {
@@ -118,7 +123,7 @@
118
123
  }
119
124
 
120
125
  /* Code: a quiet panel, with the language as a small label above the code. */
121
- .mbe-root > .mbe-code {
126
+ .mbe-root > .mbe-code:not(.mbe-view-block) {
122
127
  background: var(--mbe-block-code-bg);
123
128
  border-radius: var(--mbe-radius);
124
129
  overflow: hidden;
@@ -126,6 +131,9 @@
126
131
  .mbe-root .mbe-code-bar { padding: 6px 12px 0; }
127
132
  .mbe-root .mbe-code-lang { font: 12px/16px var(--mbe-font); color: var(--mbe-muted); }
128
133
  .mbe-root .mbe-code-lang::placeholder { color: var(--mbe-muted); opacity: 1; }
134
+ .mbe-root .mbe-code-copy { color: var(--mbe-muted); border-radius: 4px; }
135
+ .mbe-root .mbe-code-copy:hover { color: var(--mbe-text); background: var(--mbe-hover); }
136
+ .mbe-root .mbe-code-copy.mbe-copied { color: var(--mbe-accent); }
129
137
  /* Block source text: code blocks and raw blocks. */
130
138
  .mbe-root > .mbe-code pre,
131
139
  .mbe-root > pre.mbe-raw { font: 14px/22px var(--mbe-mono); }
@@ -6,6 +6,7 @@ import type { Extension } from './extension.js';
6
6
  import { type SuggestionState } from './suggest/controller.js';
7
7
  import { type Widget, type WidgetRender } from './widgets.js';
8
8
  import { type Block, type EditorState, type HeadingLevel, type Position, type Selection } from './model.js';
9
+ import { type ResolveUrl } from './view/dom.js';
9
10
  import { type Theme } from './theme.js';
10
11
  export interface EditorOptions {
11
12
  /** The element the editor renders into. */
@@ -26,8 +27,37 @@ export interface EditorOptions {
26
27
  autofocus?: boolean | 'start' | 'end';
27
28
  /** Attributes for the editable root, such as `autocorrect` or `aria-label`. */
28
29
  attributes?: Readonly<Record<string, string>>;
29
- /** Maps an image `src` to the URL to display. The saved Markdown keeps the original `src`. */
30
- resolveImageSrc?: (src: string) => string;
30
+ /**
31
+ * Maps a link's or image's URL to the URL to use, or null to drop it: the
32
+ * link is not clickable, the image has no `src`. The saved Markdown keeps
33
+ * the original. Default `defaultResolveUrl`: relative URLs, `http`, `https`,
34
+ * `mailto` and `tel`.
35
+ */
36
+ resolveUrl?: ResolveUrl;
37
+ /** `referrerpolicy` for images, such as `no-referrer`. Fixed for the editor's lifetime. */
38
+ referrerPolicy?: ReferrerPolicy;
39
+ /** A copy button on code blocks, which copies the code. Default true. Fixed for the editor's lifetime. */
40
+ codeCopy?: boolean;
41
+ /**
42
+ * Element ids for the document's headings, for in-page links and an
43
+ * outline: called with every heading in order, returns an id (or
44
+ * undefined) for each. Called again when the document changes. Fixed for
45
+ * the editor's lifetime.
46
+ */
47
+ headingIds?: (headings: readonly {
48
+ readonly text: string;
49
+ readonly level: HeadingLevel;
50
+ }[]) => readonly (string | undefined)[];
51
+ /**
52
+ * Called when a link is clicked to be opened: a plain click while read-only,
53
+ * Mod+click while editing. Return true to handle it, for example to route an
54
+ * in-app link; otherwise the editor opens `href` in a new tab.
55
+ */
56
+ onLinkClick?: (ctx: {
57
+ readonly editor: Editor;
58
+ readonly href: string;
59
+ readonly event: MouseEvent;
60
+ }) => boolean | void;
31
61
  /** Classes for rendered elements, colors and fonts, and the color scheme. See `Theme`. */
32
62
  theme?: Theme;
33
63
  /** Overrides UI strings. */
@@ -52,7 +82,7 @@ export interface EditorOptions {
52
82
  onBlur?: (editor: Editor) => void;
53
83
  }
54
84
  /** Options that `setOptions` can change while the editor runs. */
55
- export type RuntimeOptions = Pick<EditorOptions, 'placeholder' | 'editable' | 'taskToggle' | 'attributes' | 'resolveImageSrc' | 'theme' | 'extensions'>;
85
+ export type RuntimeOptions = Pick<EditorOptions, 'placeholder' | 'editable' | 'taskToggle' | 'attributes' | 'resolveUrl' | 'onLinkClick' | 'theme' | 'extensions'>;
56
86
  export interface EditorEvents {
57
87
  /** After document changes, at most once per animation frame. */
58
88
  change: {
@@ -241,6 +271,12 @@ export declare class Editor {
241
271
  private blockSel;
242
272
  /** Block elements that carry the selected class. */
243
273
  private selectedEls;
274
+ /** The ids `headingIds` gave the headings of `doc`, by block ID. */
275
+ private headingIdsFor;
276
+ /** `redecorate()` was called during a composition; it runs when the composition settles. */
277
+ private redecoratePending;
278
+ /** The frame that renders blocks again after their views settled. */
279
+ private viewFrame;
244
280
  constructor(options: EditorOptions);
245
281
  /** The document as Markdown. Blocks that were not edited are written exactly as they were loaded. */
246
282
  getMarkdown(): string;
@@ -294,7 +330,7 @@ export declare class Editor {
294
330
  blur(): void;
295
331
  /**
296
332
  * Changes `placeholder`, `editable`, `taskToggle`, `attributes`,
297
- * `resolveImageSrc` or `theme`. `extensions` only updates the callbacks of
333
+ * `resolveUrl`, `onLinkClick` or `theme`. `extensions` only updates the callbacks of
298
334
  * `suggestion()` extensions (`items`, `command`, `match`, `allow`), matched
299
335
  * by name; other changes to extensions need a new editor.
300
336
  */
@@ -358,6 +394,22 @@ export declare class Editor {
358
394
  * a table replaces the focused cell).
359
395
  */
360
396
  private paint;
397
+ /** Heading ids from the `headingIds` option, computed again only when the document changes. */
398
+ private applyHeadingIds;
399
+ /**
400
+ * Computes decorations again for every block and renders the blocks whose
401
+ * decorations depend on something outside the document changed, such as
402
+ * which mentioned people exist or a highlighter's language that finished
403
+ * loading. Waits for an input method to finish composing.
404
+ */
405
+ redecorate(): void;
406
+ /**
407
+ * Views that returned a promise settled: their blocks render again on the
408
+ * next frame, or when a composition settles, since rendering would end it.
409
+ */
410
+ private viewsSettled;
411
+ /** A block rendered by a view (a formula block, a diagram), or null. */
412
+ private viewBlock;
361
413
  /** Re-renders if the views that show their source changed: after the selection, focus or editability changes. */
362
414
  private refreshRevealed;
363
415
  private onMouseUp;
@@ -430,6 +482,13 @@ export declare class Editor {
430
482
  */
431
483
  private readDom;
432
484
  private onKeyDown;
485
+ /**
486
+ * WebKit skips code blocks and tables with ArrowDown and ArrowUp. When no
487
+ * editable text follows them (a rendered footnote or formula is not), it
488
+ * does not move the caret at all. If the browser left the caret on the edge
489
+ * line of its block, move it into the next block that holds a caret.
490
+ */
491
+ private unlessCaretMoves;
433
492
  /** Selects all the text of the block (or table cell) holding `target`. False if it holds none. */
434
493
  private selectBlockText;
435
494
  private moveMenu;
@@ -441,6 +500,8 @@ export declare class Editor {
441
500
  */
442
501
  private clickBelowLastBlock;
443
502
  private onClick;
503
+ /** Copies the code of the code block holding `button`, and shows that it did for a moment. */
504
+ private copyCode;
444
505
  /** The code block language input. */
445
506
  private onControlChange;
446
507
  private onFocusIn;
@@ -1,8 +1,8 @@
1
- import type { Decorator } from './decorations.js';
1
+ import type { Decoration, Decorator } from './decorations.js';
2
2
  import type { Editor } from './editor.js';
3
3
  import type { SuggestionConfig } from './extensions/suggestion.js';
4
4
  import type { MarkdownSyntax } from './markdown/options.js';
5
- import type { Position } from './model.js';
5
+ import type { CodeBlock, Position } from './model.js';
6
6
  import type { ThemeClasses } from './theme.js';
7
7
  export interface ExtensionContext {
8
8
  readonly editor: Editor;
@@ -14,11 +14,24 @@ export interface ExtensionContext {
14
14
  export type KeyHandler = (ctx: ExtensionContext) => boolean;
15
15
  /**
16
16
  * Renders the Markdown source of a token (`kind` is `inline`, `element` a
17
- * span) or of a raw block (`block`, a div) into `element`. Returns false, or
18
- * throws, to show the source instead. Results are cached by source, so the
19
- * output must depend on nothing else.
17
+ * span), a raw block, or the code of a code block (`block`, a div) into
18
+ * `element`. Returns false, or throws, to show the source instead. Results
19
+ * are cached by source, so the output must depend on nothing else.
20
+ *
21
+ * A view that finishes later (a diagram, a renderer that loads on demand)
22
+ * fills in what it can at once and returns a promise: the editor shows that
23
+ * meanwhile, and the finished element when the promise resolves. A promise
24
+ * that rejects or resolves to false shows the source.
20
25
  */
21
- export type SyntaxView = (source: string, element: HTMLElement, kind: 'inline' | 'block') => void | false;
26
+ export type SyntaxView = (source: string, element: HTMLElement, kind: 'inline' | 'block') => void | false | PromiseLike<void | false>;
27
+ /** A code block's code, for decorations such as syntax highlighting. */
28
+ export interface CodeDecorationContext {
29
+ readonly block: CodeBlock;
30
+ /** The code. */
31
+ readonly text: string;
32
+ /** The info string's language, as written; empty for none. */
33
+ readonly language: string;
34
+ }
22
35
  export interface Extension {
23
36
  /** Unique name, for debugging and for replacing a built-in extension. */
24
37
  readonly name: string;
@@ -49,12 +62,20 @@ export interface Extension {
49
62
  readonly event: DragEvent;
50
63
  readonly position: Position | null;
51
64
  }) => boolean;
65
+ /**
66
+ * Classes on ranges of a code block's code, for syntax highlighting, in
67
+ * editing and read-only alike. Recomputed only for code blocks that
68
+ * changed; call `editor.redecorate()` when a language finishes loading.
69
+ * Never saved.
70
+ */
71
+ readonly codeDecorations?: (ctx: CodeDecorationContext) => readonly Decoration[];
52
72
  /**
53
73
  * Shows tokens and raw blocks of a syntax rendered instead of as source,
54
- * keyed by syntax name; `math()` uses this to show formulas. While editing,
55
- * a token shows its source when the caret touches it, and a raw block when
56
- * the selection is in it; clicking either does the same. Read-only always
57
- * shows the rendered view.
74
+ * keyed by syntax name; `math()` uses this to show formulas. `code:` and a
75
+ * language (`code:mermaid`) renders code blocks of that language, such as
76
+ * diagrams. While editing, a token shows its source when the caret touches
77
+ * it, and a block when the selection is in it; clicking either does the
78
+ * same. Read-only always shows the rendered view.
58
79
  */
59
80
  readonly views?: Readonly<Record<string, SyntaxView>>;
60
81
  /**
@@ -1,2 +1,6 @@
1
1
  import type { Extension } from '../extension.js';
2
- export declare function footnotes(): Extension;
2
+ export interface FootnotesOptions {
3
+ /** Render references and definitions instead of showing their source. Default true. */
4
+ readonly render?: boolean;
5
+ }
6
+ export declare function footnotes(options?: FootnotesOptions): Extension;
@@ -4,11 +4,12 @@ export interface MathOptions {
4
4
  * Renders TeX into `element`. `displayMode` is true for a `$$` block.
5
5
  * KaTeX's `render` has this shape:
6
6
  * `render: (tex, el, options) => katex.render(tex, el, { ...options, throwOnError: false })`.
7
- * Throwing shows the source instead.
7
+ * Throwing shows the source instead. A renderer that loads on demand can
8
+ * return a promise; the source shows until it resolves (see `views`).
8
9
  */
9
10
  readonly render?: (tex: string, element: HTMLElement, options: {
10
11
  readonly displayMode: boolean;
11
- }) => void;
12
+ }) => void | PromiseLike<void>;
12
13
  }
13
14
  /** The TeX inside a token (`$x$`, `$$x$$`) or a fenced block (`$$` lines around it). */
14
15
  export declare function mathSource(source: string, kind: 'inline' | 'block'): string;
@@ -3,9 +3,14 @@ import type { Extension } from '../extension.js';
3
3
  /** Finds tags or mentions in `text[from, to)`. `text` is the whole container, so a scanner can look before `from`. */
4
4
  export type TagScanner = (text: string, from: number, to: number) => Iterable<TextRange>;
5
5
  export interface TagsOptions {
6
- /** Class on each match. Default `mbe-tag` for tags and `mbe-mention` for mentions. */
7
- readonly class?: string;
8
- readonly attributes?: Readonly<Record<string, string>>;
6
+ /**
7
+ * Class on each match. Default `mbe-tag` for tags and `mbe-mention` for
8
+ * mentions. A function gets the match as written (`#work/planning`), for a
9
+ * class per tag or per person.
10
+ */
11
+ readonly class?: string | ((match: string) => string);
12
+ /** Attributes on each match, or a function of the match, such as `data-tag` or a custom color. */
13
+ readonly attributes?: Readonly<Record<string, string>> | ((match: string) => Readonly<Record<string, string>> | undefined);
9
14
  /** Finds matches in a run of text. Default `scanTags` or `scanMentions`. */
10
15
  readonly scan?: TagScanner;
11
16
  }
@@ -66,6 +66,17 @@ declare const ICONS: {
66
66
  rx: string;
67
67
  ry: string;
68
68
  }])[];
69
+ /** `copy` */
70
+ copyCode: (string | [string, {
71
+ width: string;
72
+ height: string;
73
+ x: string;
74
+ y: string;
75
+ rx: string;
76
+ ry: string;
77
+ }])[];
78
+ /** `check` */
79
+ copied: string[];
69
80
  /** `trash` */
70
81
  delete: readonly IconChild[];
71
82
  /** `arrow-up` */
@@ -10,11 +10,11 @@ export { loadMarkdown, type MarkdownSource } from './markdown/source.js';
10
10
  export type { MarkdownOptions } from './markdown/options.js';
11
11
  export { docToHtml } from './clipboard/toHtml.js';
12
12
  export { htmlToDoc } from './clipboard/fromHtml.js';
13
- export type { Extension, ExtensionContext, KeyHandler, SyntaxView } from './extension.js';
13
+ export type { CodeDecorationContext, Extension, ExtensionContext, KeyHandler, SyntaxView } from './extension.js';
14
14
  export type { ColorScheme, Theme, ThemeClasses, ThemeColors, ThemeTokens } from './theme.js';
15
15
  export { defaultKeymap } from './extensions/keymap.js';
16
16
  export { math, type MathOptions } from './extensions/math.js';
17
- export { footnotes } from './extensions/footnotes.js';
17
+ export { footnotes, type FootnotesOptions } from './extensions/footnotes.js';
18
18
  export type { BlockSyntax, BlockSyntaxMatcher, InlineSyntax, MarkdownSyntax } from './markdown/options.js';
19
19
  export { textDecorator, type TextDecoratorOptions } from './extensions/textDecorator.js';
20
20
  export { mentions, scanMentions, scanTags, tags, type TagScanner, type TagsOptions } from './extensions/tags.js';
@@ -24,3 +24,4 @@ export { matchToken, type MatchTokenOptions } from './suggest/match.js';
24
24
  export type { SuggestionState } from './suggest/controller.js';
25
25
  export type { Widget, WidgetRender } from './widgets.js';
26
26
  export { fileHandler, type FileHandlerOptions } from './extensions/fileHandler.js';
27
+ export { defaultResolveUrl, type ResolveUrl, type UrlKind } from './view/dom.js';
@@ -35,6 +35,10 @@ export declare const DEFAULT_LABELS: {
35
35
  language: string;
36
36
  /** Shown in a code block's language field when it has none. */
37
37
  plainText: string;
38
+ /** The copy button of a code block. */
39
+ copyCode: string;
40
+ /** The copy button of a code block, just after copying. */
41
+ copied: string;
38
42
  addRowAbove: string;
39
43
  addRowBelow: string;
40
44
  addColumnLeft: string;
@@ -20,5 +20,9 @@ export declare function serializeInline(inline: Inline, options?: MarkdownOption
20
20
  * - Whitespace at the edges of a bold, italic or strike run moves outside it,
21
21
  * because `**foo **` is not valid emphasis.
22
22
  * - A "\n" in a code span is a hard break outside the code span.
23
+ * - Spaces and tabs that end a line of text are dropped, because Markdown
24
+ * strips them. Writing them as character references instead would leave
25
+ * "&#32;" behind wherever someone typed a space last. A line of only
26
+ * whitespace keeps it, so the line is not lost.
23
27
  */
24
28
  export declare function representableInline(inline: Inline): Span[];
@@ -2,7 +2,7 @@ import { Editor, type EditorOptions, type SuggestionState } from '@usememos/edit
2
2
  import { type CSSProperties } from 'react';
3
3
  export type { Editor, SuggestionState } from '@usememos/editor';
4
4
  /** Constructor options that the React components take as props. */
5
- type EditorProps = Pick<EditorOptions, 'markdown' | 'extensions' | 'placeholder' | 'editable' | 'taskToggle' | 'autofocus' | 'attributes' | 'resolveImageSrc' | 'theme' | 'toolbar' | 'slashMenu' | 'labels' | 'icons'>;
5
+ type EditorProps = Pick<EditorOptions, 'markdown' | 'extensions' | 'placeholder' | 'editable' | 'taskToggle' | 'autofocus' | 'attributes' | 'resolveUrl' | 'referrerPolicy' | 'headingIds' | 'onLinkClick' | 'theme' | 'toolbar' | 'slashMenu' | 'labels' | 'icons'>;
6
6
  export interface MarkdownEditorProps extends EditorProps {
7
7
  /** Markdown. The editor updates only when this is not a value it emitted itself. */
8
8
  value?: string;
@@ -20,7 +20,7 @@ export interface MarkdownEditorProps extends EditorProps {
20
20
  /**
21
21
  * The editor as a controlled React component. A `ref` gives the core `Editor`.
22
22
  *
23
- * `placeholder`, `editable`, `taskToggle`, `attributes`, `resolveImageSrc` and `theme` update live.
23
+ * `placeholder`, `editable`, `taskToggle`, `attributes`, `resolveUrl`, `onLinkClick` and `theme` update live.
24
24
  * A change to the names in `extensions` recreates the editor, keeping its
25
25
  * Markdown; with the same names, the callbacks of `suggestion()` extensions
26
26
  * (`items`, `command`, `match`, `allow`) update live. Other props are read
@@ -1,24 +1,44 @@
1
- import { type Block, type Cell, type Doc, type Inline, type Position } from '../model.js';
1
+ import { type Block, type Cell, type CodeBlock, type Doc, type Inline, type Position } from '../model.js';
2
2
  import type { SyntaxView } from '../extension.js';
3
3
  import type { Labels } from '../labels.js';
4
+ import type { IconName } from '../icons.js';
4
5
  import type { ThemeClasses } from '../theme.js';
5
6
  import { type Decoration } from '../decorations.js';
6
7
  export declare const BLOCK_ATTR = "data-block-id";
7
- /** Only these URL schemes become clickable `href`s. Others are kept in the model but not linked. */
8
- export declare function safeHref(href: string): string | null;
8
+ /** The view name for code blocks of a language: `code:mermaid`. */
9
+ export declare function codeViewName(language: string): string;
10
+ /** What a URL in the document is used for. */
11
+ export type UrlKind = 'link' | 'image';
12
+ /** Maps a link or image URL from the document to the URL to use, or null to drop it. The saved Markdown keeps the original. */
13
+ export type ResolveUrl = (url: string, kind: UrlKind) => string | null;
14
+ /**
15
+ * The default URL policy: relative URLs and fragments, and the schemes
16
+ * `http`, `https`, `mailto` and `tel`. Other URLs (`javascript:`, `data:`)
17
+ * are kept in the model but not used. Apps that allow more can call this
18
+ * for everything else.
19
+ */
20
+ export declare const defaultResolveUrl: ResolveUrl;
9
21
  /** What rendering needs besides the block. */
10
22
  export interface RenderContext {
11
23
  readonly doc: Document;
12
24
  readonly labels: Labels;
13
- readonly resolveImageSrc?: (src: string) => string;
25
+ readonly resolveUrl: ResolveUrl;
26
+ /** `referrerpolicy` for images. */
27
+ readonly referrerPolicy?: ReferrerPolicy;
14
28
  /** Decorations for a text container. */
15
29
  readonly decorate?: (block: Block, content: Inline, cell?: Cell) => readonly Decoration[];
30
+ /** Decorations for a code block's code, such as syntax highlighting. */
31
+ readonly decorateCode?: (block: CodeBlock) => readonly Decoration[];
16
32
  /** Syntaxes that have a view. */
17
33
  readonly views?: ReadonlyMap<string, SyntaxView>;
18
34
  /** A token or raw block of an extension syntax, rendered; null shows its source. */
19
35
  readonly view?: (syntax: string, source: string, kind: 'inline' | 'block') => HTMLElement | null;
20
36
  /** Theme classes for rendered elements. */
21
37
  readonly classes: ThemeClasses;
38
+ /** The icon of a UI control, or null for none. */
39
+ readonly icon?: (name: IconName) => Node | null;
40
+ /** Code blocks get a copy button. */
41
+ readonly codeCopy?: boolean;
22
42
  }
23
43
  /**
24
44
  * Which views of one block show their source: `REVEAL_BLOCK` for a whole raw
@@ -28,6 +48,16 @@ export type BlockReveal = ReadonlySet<string>;
28
48
  export declare const REVEAL_BLOCK = "block";
29
49
  export declare function tokenKey(cell: Cell | undefined, from: number): string;
30
50
  export declare function sameReveal(a: BlockReveal | undefined, b: BlockReveal | undefined): boolean;
51
+ /**
52
+ * Runs of inline raw HTML that render as one piece: an opening tag through
53
+ * its closing tag, with the text between (`<kbd>Ctrl</kbd>`), or a single tag
54
+ * (`<br>`, an unmatched tag, a comment). Runs that would cross a link are
55
+ * left out. Offsets are into the container's text.
56
+ */
57
+ export declare function htmlRuns(inline: Inline): {
58
+ from: number;
59
+ to: number;
60
+ }[];
31
61
  /**
32
62
  * Keyed reconciliation. Blocks are immutable, so a block whose object is the
33
63
  * same as last render keeps its DOM element untouched.
@@ -38,16 +68,30 @@ export declare class BlockRenderer {
38
68
  private rendered;
39
69
  /** Last number written into each ordered item's marker, keyed by element. */
40
70
  private readonly numbers;
41
- /** Maps an image `src` to the URL to display. Set before a full render. */
42
- resolveImageSrc?: (src: string) => string;
71
+ /** The URL policy for links and images. Set before a full render. */
72
+ resolveUrl: ResolveUrl;
73
+ /** `referrerpolicy` for images. */
74
+ referrerPolicy?: ReferrerPolicy;
43
75
  /** Decorations for a text container. */
44
76
  decorate?: RenderContext['decorate'];
77
+ /** Decorations for a code block's code. */
78
+ decorateCode?: RenderContext['decorateCode'];
79
+ /**
80
+ * Called when views that returned a promise settle, with the blocks that
81
+ * showed them. Those blocks must render again to show the finished view,
82
+ * or their source if it failed.
83
+ */
84
+ onViewSettled?: (blockIds: readonly string[]) => void;
45
85
  /** Widget elements to place after a block. */
46
86
  widgetsAfter?: (blockId: string) => readonly HTMLElement[] | undefined;
47
87
  /** Views of extension syntaxes, by syntax name. */
48
88
  views?: ReadonlyMap<string, SyntaxView>;
49
89
  /** Theme classes for rendered elements. Set before a full render. */
50
90
  classes: ThemeClasses;
91
+ /** The icon of a UI control. */
92
+ icon?: (name: IconName) => Node | null;
93
+ /** Code blocks get a copy button. */
94
+ codeCopy: boolean;
51
95
  /** Per block, the views that show their source. A block re-renders when its entry changes. */
52
96
  revealed: ReadonlyMap<string, BlockReveal>;
53
97
  /**
@@ -55,9 +99,20 @@ export declare class BlockRenderer {
55
99
  * Cloned on reuse: typing re-renders a block and every formula in it.
56
100
  */
57
101
  private readonly viewCache;
102
+ /** Views whose promise has not settled, by cache key, with the blocks showing them. */
103
+ private readonly pendingViews;
104
+ /** Views whose promise rejected or resolved to false: their source shows. */
105
+ private readonly failedViews;
106
+ /** The block being rendered, so a pending view knows which blocks to render again. */
107
+ private renderingBlock;
58
108
  constructor(root: HTMLElement, labels: Labels);
59
109
  private context;
60
110
  private renderView;
111
+ /**
112
+ * A view that renders later (a diagram, a lazily loaded renderer) shows what
113
+ * it filled in at once, and its blocks render again when it settles.
114
+ */
115
+ private awaitView;
61
116
  /**
62
117
  * `force` re-renders every block. `lazy` (with a full render) lets blocks
63
118
  * skip layout while off screen; use it only when loading a document.