@usememos/editor 26.10.15 → 26.10.16

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", "resolveUrl", "onLinkClick", "theme", "extensions"];
6
+ var LIVE = ["placeholder", "mode", "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);
@@ -81,7 +81,7 @@ function useLiveOptions(editorRef, props) {
81
81
  let any = false;
82
82
  for (const key of LIVE) {
83
83
  if (props[key] === applied.current.props[key]) continue;
84
- changed[key] = key === "editable" ? props.editable ?? true : key === "taskToggle" ? props.taskToggle ?? false : props[key];
84
+ changed[key] = key === "editable" ? props.editable ?? true : key === "mode" ? props.mode ?? "rich" : key === "taskToggle" ? props.taskToggle ?? false : props[key];
85
85
  any = true;
86
86
  }
87
87
  applied.current = { editor, props: { ...props } };
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 | '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', '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;AA0IjB;AA/FT,IAAM,OAAO,CAAC,eAAe,YAAY,cAAc,cAAc,cAAc,eAAe,SAAS,YAAY;AAGvH,IAAM,eAAe,CAAC,gBA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C1F,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;",
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 | '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;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Aa,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
@@ -296,6 +296,11 @@
296
296
  white-space: pre-wrap;
297
297
  tab-size: 2;
298
298
  }
299
+ .mbe-root > .mbe-source {
300
+ white-space: pre-wrap;
301
+ tab-size: 4;
302
+ overflow-wrap: anywhere;
303
+ }
299
304
  :is(.mbe-root, .mbe-flow) > .mbe-code pre {
300
305
  margin: 0;
301
306
  }
@@ -385,12 +390,14 @@
385
390
  .mbe-root > .mbe-paragraph.mbe-empty.mbe-show-hint::before,
386
391
  .mbe-root:not(.mbe-readonly) > .mbe-empty[data-hint]:is(h1, h2, h3, h4, h5, h6, blockquote:not(.mbe-list-item))::before,
387
392
  .mbe-root:not(.mbe-readonly) > .mbe-list-item.mbe-empty[data-hint] > .mbe-content::before,
388
- .mbe-root:not(.mbe-readonly) > .mbe-details.mbe-empty[data-hint] > .mbe-content::before {
393
+ .mbe-root:not(.mbe-readonly) > .mbe-details.mbe-empty[data-hint] > .mbe-content::before,
394
+ .mbe-root > .mbe-source.mbe-empty:only-child > .mbe-source-text::before {
389
395
  opacity: 0.5;
390
396
  pointer-events: none;
391
397
  position: absolute;
392
398
  }
393
- .mbe-root > .mbe-paragraph.mbe-empty:only-child::before {
399
+ .mbe-root > .mbe-paragraph.mbe-empty:only-child::before,
400
+ .mbe-root > .mbe-source.mbe-empty:only-child > .mbe-source-text::before {
394
401
  content: var(--mbe-placeholder, "");
395
402
  }
396
403
  .mbe-root > .mbe-paragraph.mbe-empty.mbe-show-hint::before {
@@ -1033,7 +1040,8 @@
1033
1040
  .mbe-root > .mbe-paragraph.mbe-empty.mbe-show-hint::before,
1034
1041
  .mbe-root:not(.mbe-readonly) > .mbe-empty[data-hint]:is(h1, h2, h3, h4, h5, h6, blockquote:not(.mbe-list-item))::before,
1035
1042
  .mbe-root:not(.mbe-readonly) > .mbe-list-item.mbe-empty[data-hint] > .mbe-content::before,
1036
- .mbe-root:not(.mbe-readonly) > .mbe-details.mbe-empty[data-hint] > .mbe-content::before {
1043
+ .mbe-root:not(.mbe-readonly) > .mbe-details.mbe-empty[data-hint] > .mbe-content::before,
1044
+ .mbe-root > .mbe-source.mbe-empty:only-child > .mbe-source-text::before {
1037
1045
  color: var(--mbe-muted);
1038
1046
  opacity: 0.7;
1039
1047
  }
package/dist/theme.css CHANGED
@@ -242,7 +242,8 @@
242
242
  .mbe-root > .mbe-paragraph.mbe-empty.mbe-show-hint::before,
243
243
  .mbe-root:not(.mbe-readonly) > .mbe-empty[data-hint]:is(h1, h2, h3, h4, h5, h6, blockquote:not(.mbe-list-item))::before,
244
244
  .mbe-root:not(.mbe-readonly) > .mbe-list-item.mbe-empty[data-hint] > .mbe-content::before,
245
- .mbe-root:not(.mbe-readonly) > .mbe-details.mbe-empty[data-hint] > .mbe-content::before {
245
+ .mbe-root:not(.mbe-readonly) > .mbe-details.mbe-empty[data-hint] > .mbe-content::before,
246
+ .mbe-root > .mbe-source.mbe-empty:only-child > .mbe-source-text::before {
246
247
  color: var(--mbe-muted);
247
248
  opacity: 0.7;
248
249
  }
@@ -1,2 +1,9 @@
1
1
  import { type Doc } from '../model.js';
2
2
  export declare function htmlToDoc(html: string, parser?: DOMParser): Doc;
3
+ /**
4
+ * Whether clipboard HTML only lays out and colors plain text, as code
5
+ * editors and terminals write it: lines as `<div>`s of colored `<span>`s,
6
+ * with no headings, lists, links or bold. Markdown copied from such an app
7
+ * arrives this way, so its plain text is read as Markdown instead.
8
+ */
9
+ export declare function isStyledText(html: string): boolean;
@@ -10,6 +10,7 @@ import { type Block, type CalloutType, type EditorState, type HeadingLevel, type
10
10
  import { type ToolbarItem } from './ui/toolbar.js';
11
11
  import { type ResolveUrl } from './view/dom.js';
12
12
  import { type Theme } from './theme.js';
13
+ import { type EditorMode } from './sourceMode.js';
13
14
  export interface EditorOptions {
14
15
  /** The element the editor renders into. */
15
16
  element: HTMLElement;
@@ -25,6 +26,8 @@ export interface EditorOptions {
25
26
  editable?: boolean;
26
27
  /** While `editable` is false, lets the user tick and untick task items. Default false. */
27
28
  taskToggle?: boolean;
29
+ /** `'source'` shows the whole document as its Markdown text. Default `'rich'`. */
30
+ mode?: EditorMode;
28
31
  /** Focus on creation: `true` or `'start'` puts the caret at the start, `'end'` at the end. */
29
32
  autofocus?: boolean | 'start' | 'end';
30
33
  /** Attributes for the editable root, such as `autocorrect` or `aria-label`. */
@@ -101,7 +104,7 @@ export interface EditorOptions {
101
104
  onBlur?: (editor: Editor) => void;
102
105
  }
103
106
  /** Options that `setOptions` can change while the editor runs. */
104
- export type RuntimeOptions = Pick<EditorOptions, 'placeholder' | 'editable' | 'taskToggle' | 'attributes' | 'resolveUrl' | 'onLinkClick' | 'theme' | 'extensions'>;
107
+ export type RuntimeOptions = Pick<EditorOptions, 'placeholder' | 'editable' | 'taskToggle' | 'mode' | 'attributes' | 'resolveUrl' | 'onLinkClick' | 'theme' | 'extensions'>;
105
108
  export interface EditorEvents {
106
109
  /** After document changes, at most once per animation frame. */
107
110
  change: {
@@ -250,6 +253,10 @@ export declare class Editor {
250
253
  /** The Markdown dialect: options plus the syntax of extensions. */
251
254
  private readonly markdown;
252
255
  private readonly history;
256
+ /** Rich blocks, or the whole document as text in one block (see sourceMode.ts). */
257
+ private modeValue;
258
+ /** A mode switch asked for during a composition, applied when it settles. */
259
+ private pendingMode;
253
260
  private readonly renderer;
254
261
  private composing;
255
262
  /**
@@ -345,6 +352,8 @@ export declare class Editor {
345
352
  get state(): EditorState;
346
353
  /** True while an input method (IME) is composing text. Replacing the document now would break the composition. */
347
354
  get isComposing(): boolean;
355
+ /** `'rich'` or `'source'`: the mode the editor shows now. */
356
+ get mode(): EditorMode;
348
357
  get isEditable(): boolean;
349
358
  /** True after `destroy()`. The editor then ignores every call that would change it; `getMarkdown()` still returns its last Markdown. */
350
359
  get isDestroyed(): boolean;
@@ -387,6 +396,20 @@ export declare class Editor {
387
396
  * by name; other changes to extensions need a new editor.
388
397
  */
389
398
  setOptions(options: RuntimeOptions): void;
399
+ /**
400
+ * Shows the document as blocks or as its Markdown text. The text does not
401
+ * change, so this emits no `change` and records no undo step. During a
402
+ * composition the switch waits for it to settle.
403
+ */
404
+ private setMode;
405
+ /** Rich blocks to text: the text is `getMarkdown()`; the selection and widgets keep their blocks. */
406
+ private enterSource;
407
+ /** Text to rich blocks, loaded as `setMarkdown` does, so the text saves byte for byte. */
408
+ private leaveSource;
409
+ /** Loads text as the document's blocks, with an empty paragraph for empty text, and makes its source current. */
410
+ private loadSource;
411
+ /** A history entry, in the current mode: an entry made in the other mode is serialized or loaded. */
412
+ private restore;
390
413
  /** Subscribes to an event. Returns a function that unsubscribes. */
391
414
  on<K extends keyof EditorEvents>(type: K, handler: (payload: EditorEvents[K]) => void): () => void;
392
415
  private emit;
@@ -397,6 +420,8 @@ export declare class Editor {
397
420
  run(command: (state: EditorState) => EditorState | null, kind?: ChangeKind): boolean;
398
421
  private createCommands;
399
422
  private toggleMark;
423
+ /** `insertMarkdown` in source mode: the Markdown is inserted as text. */
424
+ private insertSourceMarkdown;
400
425
  private undo;
401
426
  private redo;
402
427
  /** Scrolls the editor and the elements around it so the caret is visible. */
@@ -505,6 +530,8 @@ export declare class Editor {
505
530
  /** Events from the code-language input and other form controls inside the root are not editor input. */
506
531
  private fromControl;
507
532
  private onBeforeInput;
533
+ /** Input that works differently on text in source mode. Returns true when handled. */
534
+ private onSourceInput;
508
535
  private typeText;
509
536
  /**
510
537
  * True for input the `input` handler can read back from the DOM: text typed
@@ -15,19 +15,22 @@ export interface TagsOptions {
15
15
  readonly scan?: TagScanner;
16
16
  }
17
17
  /**
18
- * The default tag grammar. A tag is `#` and one or more segments separated
19
- * by `/`. A segment starts with a letter, number, `_` or emoji and goes on
20
- * with letters, combining marks, numbers, `_`, `-` and emoji. The `#` is not
21
- * preceded by a letter, mark, number, `_` or `#` (`C#`, `a#b` and `##x` are
22
- * not tags). A trailing `/` is not part of a tag, and a tag of only digits
23
- * (`#123`) is not a tag.
18
+ * The default tag grammar, memos': `#` and one or more segments separated
19
+ * by `/`. A segment is letters, digits and other Unicode identifier
20
+ * characters (XID_Continue), `-`, `+`, `&`, emoji, and an apostrophe between
21
+ * two letters (`#tag's`); it does not start with a combining mark. Anything
22
+ * may come before the `#` (`3pm#work`), and a `#` inside an emoji (the keycap `#`)
23
+ * starts no tag. `#2024` is a tag. A trailing `/` is not part of a tag.
24
24
  */
25
25
  export declare function scanTags(text: string, from?: number, to?: number): Generator<TextRange>;
26
26
  /**
27
- * The default mention grammar: `@` and a name of letters, combining marks,
28
- * numbers, `_`, `.` and `-` that starts with a letter, number or `_` and does
29
- * not end with `.` or `-`. The `@` is not preceded by a letter, mark, number,
30
- * `_`, `.`, `+`, `-` or `@`, so the middle of an e-mail address is no mention.
27
+ * The default mention grammar, memos' usernames: `@` and up to 36 ASCII
28
+ * letters, digits and `-`, starting and ending with a letter or digit. The
29
+ * character before the `@` is not a username character (`中文@dave` is a
30
+ * mention, `foo@bar` is not); formatting that starts right at the `@`
31
+ * counts as a boundary, as its delimiter does in the Markdown. A name that
32
+ * runs on into a character it cannot hold, such as `-` at the end or an
33
+ * accented letter (`@alicé`), is no mention.
31
34
  */
32
35
  export declare function scanMentions(text: string, from?: number, to?: number): Generator<TextRange>;
33
36
  /** `#tag` highlighting and `\#` escapes. */
@@ -1,17 +1,26 @@
1
+ import type { MarkdownSource } from './markdown/source.js';
1
2
  import type { EditorState } from './model.js';
2
3
  export type ChangeKind = 'typing' | 'other';
4
+ /** A restored entry: the state, and the source to save it with. */
5
+ export interface Restored {
6
+ state: EditorState;
7
+ source: MarkdownSource;
8
+ }
3
9
  export declare class History {
10
+ private readonly source;
4
11
  private undoStack;
5
12
  private redoStack;
6
13
  private lastKind;
7
14
  private lastTime;
15
+ /** `source` reads the source current when an entry is recorded. */
16
+ constructor(source: () => MarkdownSource);
8
17
  /** Call before applying a change, with the state the change starts from. */
9
18
  record(before: EditorState, kind: ChangeKind, now?: number): void;
10
19
  clear(): void;
11
20
  /** Ends the current typing group, e.g. when the caret moves. */
12
21
  breakGroup(): void;
13
- undo(current: EditorState): EditorState | null;
14
- redo(current: EditorState): EditorState | null;
22
+ undo(current: EditorState): Restored | null;
23
+ redo(current: EditorState): Restored | null;
15
24
  /** Moves the newest entry of `from` back into the document, and the current state onto `to`. */
16
25
  private step;
17
26
  }
@@ -8,6 +8,7 @@ export { parseMarkdown } from './markdown/parse.js';
8
8
  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
+ export type { EditorMode } from './sourceMode.js';
11
12
  export type { MarkdownOptions } from './markdown/options.js';
12
13
  export { docToHtml } from './clipboard/toHtml.js';
13
14
  export { htmlToDoc } from './clipboard/fromHtml.js';
@@ -1,18 +1,26 @@
1
1
  /**
2
- * Whether a URL literal may start after `prev`: at the
3
- * start of a line, after whitespace, or after `*`, `_`, `~` or `(`.
2
+ * Whether a URL literal may start after `prev`, as in cmark-gfm. A `www.`
3
+ * literal starts at the start of the text, after a space, tab or line break, or after `*`,
4
+ * `_`, `~` or `(`. A scheme starts after anything but an ASCII letter, which
5
+ * would be part of the scheme: `0http://a.b` holds a link, `xhttp://a.b` none.
4
6
  */
5
- export declare function isLiteralBoundary(prev: string | undefined): boolean;
7
+ export declare function isLiteralBoundary(prev: string | undefined, www: boolean): boolean;
6
8
  /**
7
9
  * A `www.`, `http(s)://` or `ftp://` literal starting at `pos`: its end
8
- * (exclusive) and link destination, or null. The caller checks the boundary
9
- * before `pos`.
10
+ * (exclusive) and link destination, or null. `www.` and the scheme may be in
11
+ * any case, as on github.com. The caller checks the boundary before `pos`.
10
12
  */
11
13
  export declare function urlLiteralAt(text: string, pos: number): {
12
14
  end: number;
13
15
  href: string;
14
16
  } | null;
15
- /** E-mail literals in plain text: `[from, to)` ranges. */
17
+ /**
18
+ * E-mail literals in plain text, as cmark-gfm finds them: `[from, to)`
19
+ * ranges. Before the "@", ASCII letters, digits, ".", "+", "-" and "_";
20
+ * after it, letters, digits, "-", "_" and periods followed by a letter or
21
+ * digit, with at least one period. The address ends with a letter, so
22
+ * `react@0.11.1` is not one.
23
+ */
16
24
  export declare function emailLiterals(text: string): {
17
25
  from: number;
18
26
  to: number;
@@ -3,11 +3,12 @@ import { type BlockNode, type InlineNode } from './ast.js';
3
3
  import { type MarkdownOptions } from './options.js';
4
4
  /**
5
5
  * Lowers one top-level block node. Structure the model cannot hold becomes
6
- * one raw Markdown block holding `source`, the node's Markdown.
6
+ * one raw Markdown block holding `source`, the node's Markdown. `before` is
7
+ * the last block lowered before it.
7
8
  */
8
- export declare function lowerTopLevel(node: BlockNode, options: MarkdownOptions, source: string): Block[];
9
+ export declare function lowerTopLevel(node: BlockNode, options: MarkdownOptions, source: string, before?: Block): Block[];
9
10
  /** Lowers one block node, or returns null when the model cannot hold its structure (see `fitsModel`). */
10
- export declare function lowerIfFits(node: BlockNode, options: MarkdownOptions): Block[] | null;
11
+ export declare function lowerIfFits(node: BlockNode, options: MarkdownOptions, before?: Block): Block[] | null;
11
12
  export declare function lowerInlines(nodes: readonly InlineNode[], options?: MarkdownOptions): Span[];
12
13
  /**
13
14
  * A GitHub alert: the first paragraph starts with a marker such as `[!NOTE]`
@@ -30,6 +30,8 @@ export interface Span {
30
30
  /** Sorted by MARK_ORDER, no duplicates. */
31
31
  readonly marks: readonly Mark[];
32
32
  readonly link?: string;
33
+ /** The link's title, shown as a tooltip and saved as `[text](url "title")`. Only with `link`. */
34
+ readonly linkTitle?: string;
33
35
  /** An image. Its `text` is a single ATOM_CHAR. */
34
36
  readonly image?: ImageAtom;
35
37
  /**
@@ -43,6 +45,7 @@ export type Inline = readonly Span[];
43
45
  export interface Format {
44
46
  readonly marks: readonly Mark[];
45
47
  readonly link?: string;
48
+ readonly linkTitle?: string;
46
49
  readonly token?: string;
47
50
  }
48
51
  export type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
@@ -74,6 +77,8 @@ export interface ListItemBlock {
74
77
  readonly quote?: true;
75
78
  /** Quoted items only: the item is inside a callout of this type. */
76
79
  readonly callout?: CalloutType;
80
+ /** Quoted items only: the item starts a new blockquote (see `QuoteBlock.quoteStart`). */
81
+ readonly quoteStart?: true;
77
82
  readonly content: Inline;
78
83
  }
79
84
  /** The kinds of callout, as in GitHub's alert syntax (`> [!NOTE]`). */
@@ -88,6 +93,11 @@ export interface QuoteBlock {
88
93
  readonly type: 'quote';
89
94
  /** Set on every paragraph of a callout, written as a GitHub alert (`> [!NOTE]`). */
90
95
  readonly callout?: CalloutType;
96
+ /**
97
+ * The block starts a new blockquote, though the block before it is in a
98
+ * blockquote of the same kind: in Markdown, a blank line between them.
99
+ */
100
+ readonly quoteStart?: true;
91
101
  readonly content: Inline;
92
102
  }
93
103
  /** Code block. Content is plain text (no marks); lines are separated by "\n". */
@@ -200,8 +210,10 @@ export declare function plain(text: string): Span[];
200
210
  export type QuoteKind = 'quote' | CalloutType;
201
211
  /** The blockquote a block is part of, or null for a block outside quotes. */
202
212
  export declare function quoteKind(block: Block | undefined): QuoteKind | null;
203
- /** True if `a` and `b` are parts of one blockquote when they are neighbours. */
213
+ /** True if `a` and `b` are parts of one blockquote when they are neighbours (`b` after `a`). */
204
214
  export declare function sameQuote(a: Block | undefined, b: Block | undefined): boolean;
215
+ /** `to` with the `quoteStart` of `from`, when both are quoted: a block that changes type keeps its quote boundary. */
216
+ export declare function keepQuoteStart<B extends Block>(from: Block, to: B): B;
205
217
  /** A list item moved into a blockquote of `kind`, or out of any with null. Keeps its ID. */
206
218
  export declare function withQuote(item: ListItemBlock, kind: QuoteKind | null): ListItemBlock;
207
219
  /** A block as it is inside its blockquote: a quote block is a paragraph there, and a quoted list item a plain one. */
@@ -232,6 +244,8 @@ export declare function withContent<B extends TextBlock>(block: B, content: Inli
232
244
  export declare function toPlain(inline: Inline): Span[];
233
245
  export declare function sortMarks(marks: Iterable<Mark>): Mark[];
234
246
  export declare function sameMarks(a: readonly Mark[], b: readonly Mark[]): boolean;
247
+ /** Whether two spans are in the same link, or both in none: the same destination and title. */
248
+ export declare function sameLink(a: Pick<Span, 'link' | 'linkTitle'>, b: Pick<Span, 'link' | 'linkTitle'> | undefined): boolean;
235
249
  export declare function inlineText(inline: Inline): string;
236
250
  export declare function inlineLength(inline: Inline): number;
237
251
  export declare function normalizeInline(inline: Inline): Span[];
@@ -251,7 +265,10 @@ export declare function rangeHasMark(inline: Inline, from: number, to: number, m
251
265
  export declare function setMarkInRange(inline: Inline, from: number, to: number, mark: Mark, on: boolean): Span[];
252
266
  /** Makes [from, to) one token of an inline syntax extension. */
253
267
  export declare function setTokenInRange(inline: Inline, from: number, to: number, token: string): Span[];
254
- /** Sets (or with `href` null, removes) a link on [from, to). */
268
+ /**
269
+ * Sets (or with `href` null, removes) a link on [from, to). A new link keeps
270
+ * the title of the first link in the range, so changing a link's URL keeps it.
271
+ */
255
272
  export declare function setLinkInRange(inline: Inline, from: number, to: number, href: string | null): Span[];
256
273
  /** Extension tokens that touch an offset, edges included, with their start offsets. At most two. */
257
274
  export declare function tokensAt(inline: Inline, offset: number): {
@@ -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' | 'resolveUrl' | 'referrerPolicy' | 'headingIds' | 'onLinkClick' | 'theme' | 'toolbar' | 'linkCard' | 'slashMenu' | 'slashHint' | 'labels' | 'icons'>;
5
+ type EditorProps = Pick<EditorOptions, 'markdown' | 'extensions' | 'placeholder' | 'mode' | 'editable' | 'taskToggle' | 'autofocus' | 'attributes' | 'resolveUrl' | 'referrerPolicy' | 'headingIds' | 'onLinkClick' | 'theme' | 'toolbar' | 'linkCard' | 'slashMenu' | 'slashHint' | '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`, `resolveUrl`, `onLinkClick` and `theme` update live.
23
+ * `placeholder`, `mode`, `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
@@ -0,0 +1,71 @@
1
+ import { type MarkdownSource } from './markdown/source.js';
2
+ import { type Doc, type EditorState, type Position, type Selection } from './model.js';
3
+ /** The ID of the one block that holds the text in source mode. */
4
+ export declare const SOURCE_ID = "mbe-source";
5
+ export type EditorMode = 'rich' | 'source';
6
+ export declare function sourceDoc(text: string): Doc;
7
+ export declare function isSourceDoc(doc: Doc): boolean;
8
+ /** The text of a source document. */
9
+ export declare function sourceText(doc: Doc): string;
10
+ export declare function sourcePosition(offset: number): Position;
11
+ export declare function sourceState(text: string, anchor: number, focus?: number): EditorState;
12
+ /** The selected range of a source state, in text order. */
13
+ export declare function sourceRange(state: EditorState): {
14
+ from: number;
15
+ to: number;
16
+ };
17
+ /** Inserts text at the selection, replacing it. */
18
+ export declare function insertSourceText(state: EditorState, insert: string): EditorState;
19
+ /**
20
+ * Inserts text at `offset` without replacing anything. With `block`, the
21
+ * text goes on lines of its own: a line break is added before it unless it
22
+ * starts a line, and after it unless a line break or the end follows.
23
+ */
24
+ export declare function insertSourceAt(state: EditorState, offset: number, insert: string, block: boolean, keepSelection: boolean): EditorState;
25
+ /** Backspace: deletes the selection or the character before the caret; nothing at the start. */
26
+ export declare function sourceDeleteBackward(state: EditorState, previous: (text: string, offset: number) => number): EditorState | null;
27
+ /** Delete: deletes the selection or the character after the caret; nothing at the end. */
28
+ export declare function sourceDeleteForward(state: EditorState, next: (text: string, offset: number) => number): EditorState | null;
29
+ /** Where an offset in `before` moves to in `after`, when the change between them is one replaced range. */
30
+ export declare function mapOffset(offset: number, before: string, after: string): number;
31
+ interface Placed {
32
+ /** Where the block's text starts in the source, or its source's start. */
33
+ readonly start: number;
34
+ /** Where the block's source ends. */
35
+ readonly end: number;
36
+ readonly text: string | null;
37
+ }
38
+ /**
39
+ * The offset in `loaded`'s text for a position in a rich document whose
40
+ * blocks match `loaded`'s by index. The caret keeps its column when the
41
+ * block's text before it appears verbatim in the source; otherwise it goes
42
+ * to the start of the block's text.
43
+ */
44
+ export declare function toSourceOffset(doc: Doc, pos: Position, loaded: {
45
+ doc: Doc;
46
+ source: MarkdownSource;
47
+ }, placed?: Placed[]): number;
48
+ /** The position in `loaded`'s document for an offset in its text: the block whose source holds it, at the same column when it can be. */
49
+ export declare function fromSourceOffset(offset: number, loaded: {
50
+ doc: Doc;
51
+ source: MarkdownSource;
52
+ }, placed?: Placed[]): Position;
53
+ /** Maps a selection of a rich document to offsets in `loaded`'s text. */
54
+ export declare function selectionToSource(doc: Doc, sel: Selection, loaded: {
55
+ doc: Doc;
56
+ source: MarkdownSource;
57
+ }): {
58
+ anchor: number;
59
+ focus: number;
60
+ };
61
+ /** Maps offsets in a text to a selection of `loaded`, the document loaded from it. */
62
+ export declare function selectionFromSource(anchor: number, focus: number, loaded: {
63
+ doc: Doc;
64
+ source: MarkdownSource;
65
+ }): Selection;
66
+ /** Where a block's source ends in `loaded`'s text, for a widget that follows the block. */
67
+ export declare function blockEndOffset(doc: Doc, blockId: string, loaded: {
68
+ doc: Doc;
69
+ source: MarkdownSource;
70
+ }): number;
71
+ export {};
@@ -42,6 +42,8 @@ export interface RenderContext {
42
42
  readonly icon?: (name: IconName) => Node | null;
43
43
  /** Code blocks get a copy button. */
44
44
  readonly codeCopy?: boolean;
45
+ /** The document is source mode's one code block: render it as plain text. */
46
+ readonly source?: boolean;
45
47
  /** An image failed to load and its element was replaced by the unavailable state. */
46
48
  readonly onImageError?: () => void;
47
49
  /** A loaded image element with this `src` from the elements being replaced, to show again instead of a new one. */
@@ -109,6 +111,8 @@ export declare class BlockRenderer {
109
111
  icon?: (name: IconName) => Node | null;
110
112
  /** Code blocks get a copy button. */
111
113
  codeCopy: boolean;
114
+ /** Source mode: the code block renders as plain text. Changing it needs a forced render. */
115
+ source: boolean;
112
116
  /** An image failed to load and now shows as unavailable. */
113
117
  onImageError?: () => void;
114
118
  /** Collapsible sections shown collapsed, by the ID of their title block. */
@@ -17,6 +17,8 @@ export declare class WidgetImpl implements Widget {
17
17
  private render;
18
18
  private readonly onRemove;
19
19
  blockId: string;
20
+ /** In source mode, the text offset the widget sits after. */
21
+ offset: number;
20
22
  isRemoved: boolean;
21
23
  private cleanup;
22
24
  constructor(element: HTMLElement, blockId: string, render: WidgetRender, onRemove: (widget: WidgetImpl) => void);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usememos/editor",
3
- "version": "26.10.15",
3
+ "version": "26.10.16",
4
4
  "description": "A block editor for Markdown. Zero runtime dependencies, with an optional React component.",
5
5
  "keywords": [
6
6
  "markdown",