@usememos/editor 26.10.25 → 26.10.27

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.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 | 'mode'\n | 'smartLists'\n | 'editable'\n | 'taskToggle'\n | 'autofocus'\n | 'attributes'\n | 'resolveUrl'\n | 'referrerPolicy'\n | 'headingIds'\n | 'onLinkClick'\n | 'theme'\n | 'toolbar'\n | 'linkCard'\n | 'slashMenu'\n | 'slashHint'\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', 'mode', '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`, `mode`, `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 === 'mode' ? (props.mode ?? 'rich') : 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;AA4IjB;AA/FT,IAAM,OAAO,CAAC,eAAe,QAAQ,YAAY,cAAc,cAAc,cAAc,eAAe,SAAS,YAAY;AAG/H,IAAM,eAAe,CAAC,gBAA6C,cAAc,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,IAAI;AAc1G,IAAM,iBAAiB,WAAW,SAASA,gBAAe,OAA4B,KAAkC;AAC7H,QAAM,YAAY,OAAuB,IAAI;AAC7C,QAAM,YAAY,OAAsB,IAAI;AAI5C,QAAM,UAAU,OAAiB,CAAC,CAAC;AAEnC,QAAM,WAAW,OAAsB,IAAI;AAE3C,QAAM,SAAS,OAAO,KAAK;AAC3B,SAAO,UAAU;AACjB,QAAM,aAAa,aAAa,MAAM,UAAU;AAEhD,YAAU,MAAM;AACd,UAAM,EAAE,OAAO,cAAc,UAAU,UAAU,SAAS,QAAQ,WAAW,OAAO,GAAG,QAAQ,IAAI,OAAO;AAC1G,UAAM,WAAW,UAAU;AAC3B,UAAM,SAAS,IAAI,OAAO;AAAA,MACxB,GAAG;AAAA,MACH,SAAS,UAAU;AAAA,MACnB,SAAS,UAAU,YAAY,KAAK,SAAS,gBAAgB;AAAA,MAC7D,UAAU,CAAC,aAAa;AACtB,gBAA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AI;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 | 'mode'\n | 'smartLists'\n | 'sourceHighlighting'\n | 'editable'\n | 'taskToggle'\n | 'autofocus'\n | 'attributes'\n | 'resolveUrl'\n | 'referrerPolicy'\n | 'headingIds'\n | 'onLinkClick'\n | 'theme'\n | 'toolbar'\n | 'linkCard'\n | 'slashMenu'\n | 'slashHint'\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', 'mode', '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`, `mode`, `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 === 'mode' ? (props.mode ?? 'rich') : 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;AA6IjB;AA/FT,IAAM,OAAO,CAAC,eAAe,QAAQ,YAAY,cAAc,cAAc,cAAc,eAAe,SAAS,YAAY;AAG/H,IAAM,eAAe,CAAC,gBAA6C,cAAc,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,IAAI;AAc1G,IAAM,iBAAiB,WAAW,SAASA,gBAAe,OAA4B,KAAkC;AAC7H,QAAM,YAAY,OAAuB,IAAI;AAC7C,QAAM,YAAY,OAAsB,IAAI;AAI5C,QAAM,UAAU,OAAiB,CAAC,CAAC;AAEnC,QAAM,WAAW,OAAsB,IAAI;AAE3C,QAAM,SAAS,OAAO,KAAK;AAC3B,SAAO,UAAU;AACjB,QAAM,aAAa,aAAa,MAAM,UAAU;AAEhD,YAAU,MAAM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AM,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
@@ -312,6 +312,9 @@
312
312
  tab-size: 4;
313
313
  overflow-wrap: anywhere;
314
314
  }
315
+ .mbe-root > .mbe-source .mbe-source-line {
316
+ display: block;
317
+ }
315
318
  :is(.mbe-root, .mbe-flow) > .mbe-code pre {
316
319
  margin: 0;
317
320
  }
@@ -332,6 +335,15 @@
332
335
  cursor: default;
333
336
  white-space: normal;
334
337
  }
338
+ :is(.mbe-root, .mbe-flow, .mbe-footnotes) > .mbe-footnote {
339
+ display: grid;
340
+ grid-template-columns: auto 1fr;
341
+ column-gap: 0.375em;
342
+ align-items: baseline;
343
+ }
344
+ :is(.mbe-root, .mbe-flow, .mbe-footnotes) > .mbe-footnote > :last-child {
345
+ min-width: 0;
346
+ }
335
347
  .mbe-root > .mbe-footnote-collected {
336
348
  display: none;
337
349
  }
@@ -746,6 +758,7 @@
746
758
  "Liberation Mono",
747
759
  "Courier New",
748
760
  monospace;
761
+ --mbe-source-font: var(--mbe-font);
749
762
  --mbe-font-size: 16px;
750
763
  --mbe-line-height: 24px;
751
764
  --mbe-leading: calc(var(--mbe-line-height) - var(--mbe-font-size));
@@ -864,7 +877,7 @@
864
877
  color: var(--mbe-muted);
865
878
  }
866
879
  .mbe-root .mbe-footnote-label {
867
- margin-inline-end: 0.375em;
880
+ font-size: 0.75em;
868
881
  color: var(--mbe-link);
869
882
  }
870
883
  .mbe-root > .mbe-footnotes {
@@ -1001,8 +1014,26 @@
1001
1014
  font: inherit;
1002
1015
  }
1003
1016
  .mbe-root > .mbe-source {
1017
+ font-family: var(--mbe-source-font);
1018
+ }
1019
+ .mbe-root > .mbe-source :is(.mbe-src-marker, .mbe-src-html, .mbe-src-token, .mbe-src-escape, .mbe-src-lang) {
1020
+ color: var(--mbe-muted);
1021
+ }
1022
+ .mbe-root > .mbe-source :is(.mbe-src-heading, .mbe-src-strong) {
1023
+ font-weight: 600;
1024
+ }
1025
+ .mbe-root > .mbe-source .mbe-src-em {
1026
+ font-style: italic;
1027
+ }
1028
+ .mbe-root > .mbe-source .mbe-src-strike {
1029
+ text-decoration: line-through;
1030
+ }
1031
+ .mbe-root > .mbe-source :is(.mbe-src-code, .mbe-src-lang) {
1004
1032
  font-family: var(--mbe-mono);
1005
1033
  }
1034
+ .mbe-root > .mbe-source .mbe-src-url {
1035
+ color: var(--mbe-link);
1036
+ }
1006
1037
  :is(.mbe-root, .mbe-flow) > pre.mbe-raw {
1007
1038
  color: var(--mbe-muted);
1008
1039
  }
package/dist/theme.css CHANGED
@@ -17,6 +17,8 @@
17
17
  --mbe-font: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans',
18
18
  sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
19
19
  --mbe-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;
20
+ /* Source mode's text: the body font, as Obsidian shows source; var(--mbe-mono) for an all-monospace view. */
21
+ --mbe-source-font: var(--mbe-font);
20
22
  --mbe-font-size: 16px;
21
23
  --mbe-line-height: 24px;
22
24
  /* The room a line has around its text. Headings, code and tables size
@@ -122,7 +124,7 @@
122
124
  /* A mention with an onClick (tags.ts), read-only: underlined on hover, as a name that leads somewhere. */
123
125
  .mbe-root.mbe-readonly [data-mbe-mention]:hover { text-decoration: underline; }
124
126
  :is(.mbe-root, .mbe-flow, .mbe-footnotes) > .mbe-footnote { font-size: 0.875em; color: var(--mbe-muted); }
125
- .mbe-root .mbe-footnote-label { margin-inline-end: 0.375em; color: var(--mbe-link); }
127
+ .mbe-root .mbe-footnote-label { font-size: 0.75em; color: var(--mbe-link); }
126
128
  /* The footnotes collected at the end, read-only: under a thin rule, in small
127
129
  muted text. A backlink to each reference is a quiet arrow that takes the
128
130
  link color on hover, not a boxed glyph. */
@@ -213,10 +215,17 @@
213
215
  }
214
216
  :is(.mbe-root, .mbe-flow) > .mbe-code pre { padding: 2px 12px 10px; }
215
217
  :is(.mbe-root, .mbe-flow) > .mbe-code pre code { background: none; padding: 0; border-radius: 0; font: inherit; }
216
- /* Source mode: the whole document as Markdown text, in the mono font at the
217
- body's size and line height, so markers and indentation line up and a
218
- switch keeps the text's rhythm. */
219
- .mbe-root > .mbe-source { font-family: var(--mbe-mono); }
218
+ /* Source mode: the whole document as Markdown text, at the body's size and
219
+ line height, so a switch keeps the text's rhythm. Its highlighting changes
220
+ weight, slant and color, never size: markers dim, strong text is bold,
221
+ emphasis italic, headings heavier, code is mono, URLs take the link color. */
222
+ .mbe-root > .mbe-source { font-family: var(--mbe-source-font); }
223
+ .mbe-root > .mbe-source :is(.mbe-src-marker, .mbe-src-html, .mbe-src-token, .mbe-src-escape, .mbe-src-lang) { color: var(--mbe-muted); }
224
+ .mbe-root > .mbe-source :is(.mbe-src-heading, .mbe-src-strong) { font-weight: 600; }
225
+ .mbe-root > .mbe-source .mbe-src-em { font-style: italic; }
226
+ .mbe-root > .mbe-source .mbe-src-strike { text-decoration: line-through; }
227
+ .mbe-root > .mbe-source :is(.mbe-src-code, .mbe-src-lang) { font-family: var(--mbe-mono); }
228
+ .mbe-root > .mbe-source .mbe-src-url { color: var(--mbe-link); }
220
229
 
221
230
  /* Raw blocks: Markdown kept as source (HTML, structure the editor cannot hold, extension syntax) */
222
231
  :is(.mbe-root, .mbe-flow) > pre.mbe-raw { color: var(--mbe-muted); }
@@ -26,7 +26,12 @@ export type Decorator = (ctx: DecorationContext) => readonly Decoration[];
26
26
  /** Whether a span is code, a link, an image, raw HTML or a token: text that is not plain prose. */
27
27
  export declare function isExcluded(span: Span): boolean;
28
28
  export declare function decorationContext(block: Block, content: Inline, cell?: Cell): DecorationContext;
29
+ /** Whether `[from, to)` overlaps any of `ranges`, which are sorted and do not overlap each other (as `excluded` is). */
29
30
  export declare function overlapsAny(from: number, to: number, ranges: readonly TextRange[]): boolean;
31
+ /** Whether two decorations are the same: range, class and attributes. */
32
+ export declare function sameDecoration(a: Decoration, b: Decoration): boolean;
33
+ /** Whether two lists hold the same decorations in the same order. */
34
+ export declare function sameDecorations(a: readonly Decoration[], b: readonly Decoration[]): boolean;
30
35
  /**
31
36
  * Splits content at decoration edges. Each piece is a span with the
32
37
  * decorations that cover it, in the order given. Spans for which `atomic`
@@ -34,6 +34,14 @@ export interface EditorOptions {
34
34
  * Tab indent as in a code block. Default true. Fixed for the editor's lifetime.
35
35
  */
36
36
  smartLists?: boolean;
37
+ /**
38
+ * In source mode, the Markdown syntax is highlighted: markers dimmed,
39
+ * strong text bold, emphasis italic, headings heavier, code and URLs
40
+ * tinted (classes `mbe-src-*`). `false` leaves the text plain; the
41
+ * extensions' decorations show either way. Default true. Fixed for the
42
+ * editor's lifetime.
43
+ */
44
+ sourceHighlighting?: boolean;
37
45
  /** Focus on creation: `true` or `'start'` puts the caret at the start, `'end'` at the end. */
38
46
  autofocus?: boolean | 'start' | 'end';
39
47
  /** Attributes for the editable root, such as `autocorrect` or `aria-label`. */
@@ -295,6 +303,9 @@ export declare class Editor {
295
303
  /** Task checkboxes stay usable while read-only. */
296
304
  private taskToggle;
297
305
  private readonly smartLists;
306
+ private readonly sourceHighlighting;
307
+ /** Source mode's decorations, computed once per text; a long text gets them a moment after the keystroke (see `SourceHighlighter`). */
308
+ private readonly sourceHighlighter;
298
309
  private readonly options;
299
310
  /** The extensions in priority order, ending with the default keymap unless one was given. */
300
311
  private readonly extensions;
@@ -436,7 +447,6 @@ export declare class Editor {
436
447
  /** Applies a command (a pure function of the state), records history, re-renders, and emits events. */
437
448
  run(command: (state: EditorState) => EditorState | null, kind?: ChangeKind): boolean;
438
449
  private createCommands;
439
- private toggleMark;
440
450
  /** `insertMarkdown` in source mode: the Markdown is inserted as text. */
441
451
  private insertSourceMarkdown;
442
452
  private undo;
@@ -490,6 +500,8 @@ export declare class Editor {
490
500
  * a table replaces the focused cell).
491
501
  */
492
502
  private paint;
503
+ /** Source mode's block with the exact markup, once it is read: only the lines whose highlighting changed are rendered again. */
504
+ private refreshSource;
493
505
  /** Heading ids from the `headingIds` option, computed again only when the document changes. */
494
506
  private applyHeadingIds;
495
507
  /**
@@ -636,6 +648,10 @@ export declare class Editor {
636
648
  private onScroll;
637
649
  private onCopy;
638
650
  private onPaste;
651
+ /** What a paste writes in source mode: the editor's own Markdown, other HTML as Markdown, else the text; inside a fence, the text as written. */
652
+ private pastedMarkdown;
653
+ /** The URL a paste makes a link of: the text, when it is one URL and the paste is not plain. */
654
+ private pastedUrl;
639
655
  /** Clipboard content as blocks: the editor's own Markdown, other HTML, or text as Markdown. */
640
656
  private pastedBlocks;
641
657
  private onDrop;
@@ -2,6 +2,7 @@ import type { Editor } from '../editor.js';
2
2
  import type { Extension } from '../extension.js';
3
3
  import type { Icon } from '../icons.js';
4
4
  import type { Block, Cell, Inline, Position } from '../model.js';
5
+ import type { EditorMode } from '../sourceMode.js';
5
6
  export interface SuggestionItem {
6
7
  /** Stable ID, for tests and keys. Defaults to the label. */
7
8
  readonly id?: string;
@@ -56,6 +57,8 @@ export interface SuggestionAllowContext {
56
57
  readonly excluded: boolean;
57
58
  /** True when the user asked for the popup (Ctrl+Space), rather than typing. */
58
59
  readonly explicit: boolean;
60
+ /** The editor's mode. In source mode `block` is the one block holding the Markdown text, and `excluded` covers its syntax, code and URLs too. */
61
+ readonly mode: EditorMode;
59
62
  }
60
63
  export interface SuggestionItemsContext {
61
64
  /** What the matcher returned; for the built-in matchers, the text between the trigger and the caret, unchanged. */
@@ -117,6 +120,8 @@ export interface SuggestionConfig<T extends SuggestionItem = SuggestionItem> {
117
120
  readonly allowSpaces?: boolean;
118
121
  /** Default matcher only: the trigger may follow any character. Default false: only the start of a line or whitespace. */
119
122
  readonly allowAnywhere?: boolean;
123
+ /** Never opens in source mode: for a suggestion whose items create blocks, such as the slash menu. */
124
+ readonly richOnly?: boolean;
120
125
  /** Waits until the query has not changed for this many ms before calling `items`. Default 0. */
121
126
  readonly debounce?: number;
122
127
  /** Most items shown. Default 50. */
@@ -9,6 +9,7 @@ export { parseInline } from './markdown/inline.js';
9
9
  export { serializeMarkdown, serializeInline, type SerializeOptions } from './markdown/serialize.js';
10
10
  export { loadMarkdown, type MarkdownSource } from './markdown/source.js';
11
11
  export type { EditorMode } from './sourceMode.js';
12
+ export type { MarkupKind } from './markdown/markup.js';
12
13
  export type { MarkdownOptions } from './markdown/options.js';
13
14
  export { docToHtml } from './clipboard/toHtml.js';
14
15
  export { htmlToDoc } from './clipboard/fromHtml.js';
@@ -1,46 +1,87 @@
1
1
  import type { Align } from '../model.js';
2
- export type InlineNode = TextNode | {
2
+ /** A range of the parsed text: `from` inclusive, `to` exclusive. */
3
+ export interface Range {
4
+ readonly from: number;
5
+ readonly to: number;
6
+ }
7
+ /**
8
+ * A piece of markup of an inline node, in the coordinates of its `pos`:
9
+ * `open` and `close` are delimiter runs, brackets, backticks or the `<` and
10
+ * `>` of an autolink; `tail` is a link's `(destination "title")` or
11
+ * `[label]`, with `dest` and `title` the destination and title text in it,
12
+ * or a bare URL's text.
13
+ */
14
+ export interface SyntaxRange extends Range {
15
+ readonly kind: 'open' | 'close' | 'tail' | 'dest' | 'title';
16
+ }
17
+ /** A run of a text node's value that is a verbatim slice of the parsed text: `value.slice(at, pieceEnd(piece))`. */
18
+ export interface TextPiece extends Range {
19
+ readonly at: number;
20
+ }
21
+ /** Where a piece ends in its text node's value. */
22
+ export declare function pieceEnd(p: TextPiece): number;
23
+ /**
24
+ * Where an inline node sits in the text it was parsed from (a paragraph's
25
+ * content as the block parser built it; see `ContentSource`). Nodes made
26
+ * elsewhere than by the parser have no `pos`.
27
+ */
28
+ export interface Positioned {
29
+ readonly pos?: Range;
30
+ readonly syntax?: readonly SyntaxRange[];
31
+ }
32
+ export type InlineNode = TextNode | ({
3
33
  readonly type: 'softBreak';
4
- } | {
34
+ } & Positioned) | ({
5
35
  readonly type: 'hardBreak';
6
- } | {
7
- readonly type: 'code';
8
- readonly value: string;
9
- }
36
+ } & Positioned) | CodeNode
10
37
  /** Raw inline HTML, verbatim. */
11
- | {
38
+ | ({
12
39
  readonly type: 'html';
13
40
  readonly value: string;
14
- }
41
+ } & Positioned)
15
42
  /** A token of an inline syntax extension (`name`), verbatim source. */
16
- | {
43
+ | ({
17
44
  readonly type: 'token';
18
45
  readonly name: string;
19
46
  readonly value: string;
20
- } | {
47
+ } & Positioned) | ({
21
48
  readonly type: 'emphasis';
22
49
  readonly children: InlineNode[];
23
- } | {
50
+ } & Positioned) | ({
24
51
  readonly type: 'strong';
25
52
  readonly children: InlineNode[];
26
- }
53
+ } & Positioned)
27
54
  /** GFM strikethrough (`~text~` or `~~text~~`). */
28
- | {
55
+ | ({
29
56
  readonly type: 'strike';
30
57
  readonly children: InlineNode[];
31
- } | LinkNode | ImageNode;
58
+ } & Positioned) | LinkNode | ImageNode;
32
59
  export interface TextNode {
33
60
  readonly type: 'text';
34
61
  readonly value: string;
62
+ readonly pos?: Range;
63
+ /**
64
+ * The verbatim runs of `value` when it is not one verbatim slice of `pos`:
65
+ * an escape or entity stands for text that is not written as such, and the
66
+ * gaps between the pieces are those. Empty when nothing in it is verbatim.
67
+ * Absent when all of it is.
68
+ */
69
+ readonly pieces?: readonly TextPiece[];
70
+ }
71
+ export interface CodeNode extends Positioned {
72
+ readonly type: 'code';
73
+ readonly value: string;
74
+ /** Where `value` is in the text: between the backtick runs, less a stripped space on each side. */
75
+ readonly content?: Range;
35
76
  }
36
- export interface LinkNode {
77
+ export interface LinkNode extends Positioned {
37
78
  readonly type: 'link';
38
79
  /** Decoded destination, not yet percent-encoded. */
39
80
  readonly destination: string;
40
81
  readonly title: string;
41
82
  readonly children: InlineNode[];
42
83
  }
43
- export interface ImageNode {
84
+ export interface ImageNode extends Positioned {
44
85
  readonly type: 'image';
45
86
  readonly destination: string;
46
87
  readonly title: string;
@@ -81,10 +122,37 @@ export declare function imageSuffixText(s: {
81
122
  }): string;
82
123
  export type BlockNode = ParagraphNode | HeadingNode | {
83
124
  readonly type: 'thematicBreak';
125
+ readonly lines?: SourceLines;
84
126
  } | BlockQuoteNode | ListNode | CodeBlockNode | HtmlBlockNode | RawNode | TableNode;
127
+ /**
128
+ * One line of a leaf block's content as the block parser built it: the line's
129
+ * text after the block's prefixes (quote markers, list indentation), followed
130
+ * by "\n". `at` is where it starts in that content, `line` its 1-based source
131
+ * line, `offset` where its text starts on that line, and `pad` the spaces that
132
+ * stand in for the rest of a tab the prefix consumed only partly. A table
133
+ * cell's content is pieces of one line instead: one entry per run of its text
134
+ * written as such, an escaped pipe (`\|`, read as `|`) starting a new one.
135
+ */
136
+ export interface ContentLine {
137
+ readonly at: number;
138
+ readonly line: number;
139
+ readonly offset: number;
140
+ readonly pad: number;
141
+ }
142
+ /**
143
+ * Where a leaf block's content came from, so its text maps back to the
144
+ * source. The inline nodes' `pos` and a code block's text count from `start`
145
+ * in the built content: link reference definitions, a task marker, a fence's
146
+ * info line or trimmed whitespace come before it.
147
+ */
148
+ export interface ContentSource {
149
+ readonly lines: readonly ContentLine[];
150
+ readonly start: number;
151
+ }
85
152
  export interface ParagraphNode {
86
153
  readonly type: 'paragraph';
87
154
  readonly children: InlineNode[];
155
+ readonly source?: ContentSource;
88
156
  }
89
157
  export interface HeadingNode {
90
158
  readonly type: 'heading';
@@ -92,6 +160,7 @@ export interface HeadingNode {
92
160
  /** True for a setext heading (underlined with `=` or `-`). */
93
161
  readonly setext: boolean;
94
162
  readonly children: InlineNode[];
163
+ readonly source?: ContentSource;
95
164
  }
96
165
  export interface BlockQuoteNode {
97
166
  readonly type: 'blockQuote';
@@ -114,6 +183,8 @@ export interface ListItemNode {
114
183
  readonly task: boolean;
115
184
  readonly checked: boolean;
116
185
  readonly children: BlockNode[];
186
+ /** The item's source lines, the first holding its marker. */
187
+ readonly lines?: SourceLines;
117
188
  }
118
189
  export interface CodeBlockNode {
119
190
  readonly type: 'codeBlock';
@@ -122,17 +193,22 @@ export interface CodeBlockNode {
122
193
  readonly info: string;
123
194
  /** Code text. Ends with "\n" unless empty. */
124
195
  readonly value: string;
196
+ readonly source?: ContentSource;
197
+ /** The block's source lines: for a fenced block, from the opening fence to the closing one, or to the last line it has. */
198
+ readonly lines?: SourceLines;
125
199
  }
126
200
  export interface HtmlBlockNode {
127
201
  readonly type: 'htmlBlock';
128
202
  /** Raw HTML, verbatim, without the final line ending. */
129
203
  readonly value: string;
204
+ readonly source?: ContentSource;
130
205
  }
131
206
  /** A block of a block syntax extension (`name`): its source lines, verbatim, without the final line ending. */
132
207
  export interface RawNode {
133
208
  readonly type: 'raw';
134
209
  readonly name: string;
135
210
  readonly value: string;
211
+ readonly source?: ContentSource;
136
212
  }
137
213
  export type TableAlign = Align;
138
214
  export interface TableNode {
@@ -140,6 +216,10 @@ export interface TableNode {
140
216
  readonly align: TableAlign[];
141
217
  /** `rows[0]` is the header row. Every row has `align.length` cells. */
142
218
  readonly rows: InlineNode[][][];
219
+ /** Where each cell's content was written, by row and cell, for a table from the parser: the cell's inline nodes' `pos` count from its content's start. */
220
+ readonly sources?: readonly (readonly ContentSource[])[];
221
+ /** The table's source lines: the header row, the delimiter row and the body rows. */
222
+ readonly lines?: SourceLines;
143
223
  }
144
224
  /** Source lines of a top-level block, 1-based and inclusive. */
145
225
  export interface SourceLines {
@@ -1,15 +1,23 @@
1
1
  import { type Block, type CalloutType, type Span } from '../model.js';
2
2
  import { type BlockNode, type InlineNode } from './ast.js';
3
3
  import { type MarkdownOptions } from './options.js';
4
+ import { type LowerContext, SegmentBuilder } from './sourceMap.js';
4
5
  /**
5
6
  * Lowers one top-level block node. Structure the model cannot hold becomes
6
7
  * one raw Markdown block holding `source`, the node's Markdown. `before` is
7
8
  * the last block lowered before it.
8
9
  */
9
10
  export declare function lowerTopLevel(node: BlockNode, options: MarkdownOptions, source: string, before?: Block): Block[];
10
- /** Lowers one block node, or returns null when the model cannot hold its structure (see `fitsModel`). */
11
- export declare function lowerIfFits(node: BlockNode, options: MarkdownOptions, before?: Block): Block[] | null;
12
- export declare function lowerInlines(nodes: readonly InlineNode[], options?: MarkdownOptions): Span[];
11
+ /**
12
+ * Lowers one block node, or returns null when the model cannot hold its
13
+ * structure (see `fitsModel`). With `ctx`, each block that holds text gets a
14
+ * source map (see `sourceMap.ts`).
15
+ */
16
+ export declare function lowerIfFits(node: BlockNode, options: MarkdownOptions, before?: Block, ctx?: LowerContext): Block[] | null;
17
+ /** With `map`, where each span's text was written is recorded as it is lowered. */
18
+ export declare function lowerInlines(nodes: readonly InlineNode[], options?: MarkdownOptions, map?: SegmentBuilder): Span[];
19
+ /** The language of a fence: the first word of its info string. */
20
+ export declare function firstWord(info: string): string;
13
21
  /**
14
22
  * A GitHub alert: the first paragraph starts with a marker such as `[!NOTE]`
15
23
  * alone on its line. Returns its type and the paragraph's content after the marker line.
@@ -0,0 +1,24 @@
1
+ import type { Range } from './ast.js';
2
+ import type { MarkdownOptions } from './options.js';
3
+ /**
4
+ * What a range of the text is: `marker` is syntax (delimiters, brackets,
5
+ * list and quote markers, `#`, fences, pipes, a hard break's backslash);
6
+ * the others are the text the markup marks, and `lang` a fence's info
7
+ * string, `escape` an escape or entity, `url` a destination or bare URL,
8
+ * `html` raw HTML and `token` an extension's syntax.
9
+ */
10
+ export type MarkupKind = 'marker' | 'heading' | 'em' | 'strong' | 'strike' | 'code' | 'link' | 'url' | 'html' | 'token' | 'escape' | 'lang';
11
+ export interface MarkupRange extends Range {
12
+ readonly kind: MarkupKind;
13
+ }
14
+ /** The content of a fenced or indented code block, for a code highlighter. */
15
+ export interface CodeRange extends Range {
16
+ readonly language: string;
17
+ }
18
+ export interface Markup {
19
+ /** In order of `from`; ranges of different kinds may nest (emphasis in a link). */
20
+ readonly ranges: readonly MarkupRange[];
21
+ readonly code: readonly CodeRange[];
22
+ }
23
+ /** The Markdown syntax in `text`, as the parser reads it with `options`. */
24
+ export declare function markdownMarkup(text: string, options?: MarkdownOptions): Markup;
@@ -70,7 +70,9 @@ export interface BlockSyntax {
70
70
  export interface BlockSyntaxMatcher {
71
71
  /**
72
72
  * For each following line: `continue` adds it, `close` adds it and ends
73
- * the block, `end` ends the block before it.
73
+ * the block, `end` ends the block before it. Blank lines at the end of the
74
+ * block are dropped from it, so a matcher may continue through a blank
75
+ * line to see whether the block goes on after it.
74
76
  */
75
77
  next(line: string): 'continue' | 'close' | 'end';
76
78
  }
@@ -1,4 +1,5 @@
1
1
  import { type Block, type Doc } from '../model.js';
2
+ import { type Segment } from './sourceMap.js';
2
3
  import { type MarkdownOptions } from './options.js';
3
4
  export interface SourceGroup {
4
5
  /** Position among the groups of the source. */
@@ -21,9 +22,14 @@ export interface MarkdownSource {
21
22
  readonly groupOf: WeakMap<Block, SourceGroup>;
22
23
  /** Source of every link reference definition, so a kept block's reference links keep working. */
23
24
  readonly definitions: readonly string[];
25
+ /** Where each loaded block's text is in `text` (see `sourceMap.ts`). Tables and blocks with no text have none. */
26
+ readonly mapOf: WeakMap<Block, readonly Segment[]>;
24
27
  }
25
- /** Parses Markdown and remembers its source, for `serializeMarkdown(doc, { source })`. */
26
- export declare function loadMarkdown(text: string, options?: MarkdownOptions): {
28
+ /**
29
+ * Parses Markdown and remembers its source, for `serializeMarkdown(doc, { source })`.
30
+ * `maps` false skips the source maps, for a caller that keeps only the document.
31
+ */
32
+ export declare function loadMarkdown(text: string, options?: MarkdownOptions, maps?: boolean): {
27
33
  doc: Doc;
28
34
  source: MarkdownSource;
29
35
  };
@@ -0,0 +1,66 @@
1
+ import type { Block } from '../model.js';
2
+ import { type ContentSource, type InlineNode, type Range } from './ast.js';
3
+ export interface Segment {
4
+ /** Range in the block's text. */
5
+ readonly from: number;
6
+ readonly to: number;
7
+ /** Range in the source text. */
8
+ readonly srcFrom: number;
9
+ readonly srcTo: number;
10
+ /** True when the text was written as such, offset for offset. */
11
+ readonly linear: boolean;
12
+ /** For a line break: where its next line starts in the source. An offset from there maps after the break, not before it. */
13
+ readonly nextLine?: number;
14
+ }
15
+ /** Where each 1-based line of a text starts, and where it ends before its line ending. A byte order mark is not on line 1. */
16
+ export interface LineTable {
17
+ readonly starts: readonly number[];
18
+ readonly ends: readonly number[];
19
+ }
20
+ export declare function lineTable(text: string): LineTable;
21
+ /** What lowering needs to record source maps: the line table and, per block, the map. */
22
+ export interface LowerContext {
23
+ readonly lines: LineTable;
24
+ readonly maps: WeakMap<Block, readonly Segment[]>;
25
+ }
26
+ /** One segment: the text `[from, to)` is the source `[srcFrom, srcTo)`, written as such. */
27
+ export declare function identitySegment(from: number, to: number, srcFrom: number): Segment;
28
+ /**
29
+ * Builds the segments of one leaf block from the ranges of its inline nodes,
30
+ * which count from the leaf content's start (see `ContentSource`).
31
+ */
32
+ export declare class SegmentBuilder {
33
+ private readonly content;
34
+ private readonly table;
35
+ readonly segments: Segment[];
36
+ /** How much of the block's text is recorded so far. */
37
+ private at;
38
+ constructor(content: ContentSource, table: LineTable);
39
+ /** Records where the next `length` characters of the block's text, lowered from `node`, were written. A node without a position (not from the parser) is syntax to the map. */
40
+ record(node: InlineNode, length: number): void;
41
+ /** The text from `modelFrom` was written as the content's `[from, to)`: one segment per source line, the line endings and tab padding atomic. */
42
+ linear(modelFrom: number, from: number, to: number): void;
43
+ /** The text `[modelFrom, modelTo)` stands for the content's `[from, to)` as a whole. */
44
+ atomic(modelFrom: number, modelTo: number, from: number, to: number): void;
45
+ /** The source offset of a content offset: a line ending maps to the end of its line. */
46
+ source(offset: number): number;
47
+ /** The index of the content line holding content offset `o`: the last one starting at or before it. */
48
+ private lineIndex;
49
+ private push;
50
+ }
51
+ /** The source ranges of the content's `[from, to)`, one per line it spans, without line endings or the lines' prefixes. */
52
+ export declare function sourcePieces(content: ContentSource, table: LineTable, from: number, to: number): Range[];
53
+ /**
54
+ * The source offset for an offset in the block's text. Between two segments
55
+ * (text whose nodes were made elsewhere than by the parser) the offset goes
56
+ * to the next segment's source; at the end of a segment it stays before any
57
+ * syntax that follows.
58
+ */
59
+ export declare function toSource(segments: readonly Segment[], offset: number): number;
60
+ /**
61
+ * The offset in the block's text for a source offset. On syntax, the offset
62
+ * goes to the text after it; inside something atomic, before it.
63
+ */
64
+ export declare function fromSource(segments: readonly Segment[], offset: number): number;
65
+ /** The source range the block's text covers, from its first segment to its last; null for a block with no map. */
66
+ export declare function sourceSpan(segments: readonly Segment[] | null | undefined): Range | null;