@dou-ui/editor 0.1.0-alpha.3 → 0.1.0-alpha.30
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/collaboration/binding.js +371 -57
- package/dist/collaboration/binding.js.map +1 -1
- package/dist/collaboration/cursors.js +42 -10
- package/dist/collaboration/cursors.js.map +1 -1
- package/dist/collaboration/index.js +61 -11
- package/dist/collaboration/index.js.map +1 -1
- package/dist/collaboration/inline-diff.js +138 -0
- package/dist/collaboration/inline-diff.js.map +1 -0
- package/dist/collaboration/merged-props.js +152 -0
- package/dist/collaboration/merged-props.js.map +1 -0
- package/dist/collaboration/order.js +41 -1
- package/dist/collaboration/order.js.map +1 -1
- package/dist/collaboration/table.js +64 -25
- package/dist/collaboration/table.js.map +1 -1
- package/dist/collaboration/text.js +213 -1
- package/dist/collaboration/text.js.map +1 -1
- package/dist/components/block-handle.js.map +1 -1
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js +127 -17
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/components/slash-choices.js +6 -0
- package/dist/components/slash-choices.js.map +1 -0
- package/dist/components/slash-choices.vue_vue_type_script_setup_true_lang.js +56 -0
- package/dist/components/slash-choices.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/components/slash-menu.js.map +1 -1
- package/dist/components/slash-menu.vue_vue_type_script_setup_true_lang.js +185 -20
- package/dist/components/slash-menu.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/core/block-selection.js +32 -4
- package/dist/core/block-selection.js.map +1 -1
- package/dist/core/blocks.js +21 -3
- package/dist/core/blocks.js.map +1 -1
- package/dist/core/cjk.js +54 -0
- package/dist/core/cjk.js.map +1 -0
- package/dist/core/commands.js +125 -13
- package/dist/core/commands.js.map +1 -1
- package/dist/core/comments.js +85 -3
- package/dist/core/comments.js.map +1 -1
- package/dist/core/convert.js +3 -3
- package/dist/core/convert.js.map +1 -1
- package/dist/core/extension.js +6 -2
- package/dist/core/extension.js.map +1 -1
- package/dist/core/model.js +10 -3
- package/dist/core/model.js.map +1 -1
- package/dist/core/output.js +26 -10
- package/dist/core/output.js.map +1 -1
- package/dist/core/prepare.js +12 -5
- package/dist/core/prepare.js.map +1 -1
- package/dist/core/schema.js.map +1 -1
- package/dist/core/transaction.js +19 -4
- package/dist/core/transaction.js.map +1 -1
- package/dist/define-block.js +8 -4
- package/dist/define-block.js.map +1 -1
- package/dist/document.js +59 -4
- package/dist/document.js.map +1 -1
- package/dist/dom.js +109 -13
- package/dist/dom.js.map +1 -1
- package/dist/editor.js.map +1 -1
- package/dist/editor.vue_vue_type_script_setup_true_lang.js +6 -5
- package/dist/editor.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/editor2.js.map +1 -1
- package/dist/extensions/callout/html.js +5 -4
- package/dist/extensions/callout/html.js.map +1 -1
- package/dist/extensions/columns/column-picker.js +6 -0
- package/dist/extensions/columns/column-picker.js.map +1 -0
- package/dist/extensions/columns/column-picker.vue_vue_type_script_setup_true_lang.js +57 -0
- package/dist/extensions/columns/column-picker.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/columns/columns-controls.js +6 -0
- package/dist/extensions/columns/columns-controls.js.map +1 -0
- package/dist/extensions/columns/columns-controls.vue_vue_type_script_setup_true_lang.js +341 -0
- package/dist/extensions/columns/columns-controls.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/columns/html.js +34 -0
- package/dist/extensions/columns/html.js.map +1 -0
- package/dist/extensions/columns/index.js +57 -0
- package/dist/extensions/columns/index.js.map +1 -0
- package/dist/extensions/columns/keys.js +53 -0
- package/dist/extensions/columns/keys.js.map +1 -0
- package/dist/extensions/columns/plugin.js +213 -0
- package/dist/extensions/columns/plugin.js.map +1 -0
- package/dist/extensions/columns/schema.js +58 -0
- package/dist/extensions/columns/schema.js.map +1 -0
- package/dist/extensions/columns/select-columns.js +6 -0
- package/dist/extensions/columns/select-columns.js.map +1 -0
- package/dist/extensions/columns/select-columns.vue_vue_type_script_setup_true_lang.js +71 -0
- package/dist/extensions/columns/select-columns.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/editor-kit.js +3 -1
- package/dist/extensions/editor-kit.js.map +1 -1
- package/dist/extensions/list-html.js +1 -1
- package/dist/extensions/list-html.js.map +1 -1
- package/dist/extensions/table/plugin.js +33 -1
- package/dist/extensions/table/plugin.js.map +1 -1
- package/dist/extensions/table/schema.js +5 -1
- package/dist/extensions/table/schema.js.map +1 -1
- package/dist/extensions/table/table-controls.js.map +1 -1
- package/dist/extensions/table/table-controls.vue_vue_type_script_setup_true_lang.js +80 -9
- package/dist/extensions/table/table-controls.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/extensions/table/view.js +181 -3
- package/dist/extensions/table/view.js.map +1 -1
- package/dist/flow/board-block.js +6 -0
- package/dist/flow/board-block.js.map +1 -0
- package/dist/flow/board-block.vue_vue_type_script_setup_true_lang.js +659 -0
- package/dist/flow/board-block.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/flow/board.js +221 -0
- package/dist/flow/board.js.map +1 -0
- package/dist/flow/index.js +173 -0
- package/dist/flow/index.js.map +1 -0
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/locale.js +78 -6
- package/dist/locale.js.map +1 -1
- package/dist/markdown/cjk-friendly.js +62 -0
- package/dist/markdown/cjk-friendly.js.map +1 -0
- package/dist/markdown/index.js +4 -3
- package/dist/markdown/index.js.map +1 -1
- package/dist/style.css +1 -1
- package/dist/style.js +2 -0
- package/dist/types/collaboration/binding.d.ts +12 -0
- package/dist/types/collaboration/cursors.d.ts +29 -1
- package/dist/types/collaboration/index.d.ts +53 -6
- package/dist/types/collaboration/inline-diff.d.ts +9 -0
- package/dist/types/collaboration/merged-props.d.ts +20 -0
- package/dist/types/collaboration/order.d.ts +5 -0
- package/dist/types/collaboration/table.d.ts +5 -1
- package/dist/types/collaboration/text.d.ts +20 -0
- package/dist/types/components/slash-choices.vue.d.ts +18 -0
- package/dist/types/core/blocks.d.ts +10 -0
- package/dist/types/core/cjk.d.ts +23 -0
- package/dist/types/core/commands.d.ts +17 -2
- package/dist/types/core/comments.d.ts +39 -3
- package/dist/types/core/convert.d.ts +10 -2
- package/dist/types/core/extension.d.ts +58 -4
- package/dist/types/core/model.d.ts +6 -1
- package/dist/types/core/prepare.d.ts +16 -2
- package/dist/types/core/schema.d.ts +1 -1
- package/dist/types/core/transaction.d.ts +6 -0
- package/dist/types/define-block.d.ts +16 -4
- package/dist/types/document.d.ts +5 -2
- package/dist/types/dom.d.ts +41 -4
- package/dist/types/editor.d.ts +15 -1
- package/dist/types/editor.vue.d.ts +24 -0
- package/dist/types/extensions/columns/column-picker.vue.d.ts +10 -0
- package/dist/types/extensions/columns/columns-controls.vue.d.ts +3 -0
- package/dist/types/extensions/columns/html.d.ts +10 -0
- package/dist/types/extensions/columns/index.d.ts +9 -0
- package/dist/types/extensions/columns/keys.d.ts +6 -0
- package/dist/types/extensions/columns/plugin.d.ts +28 -0
- package/dist/types/extensions/columns/schema.d.ts +17 -0
- package/dist/types/extensions/columns/select-columns.vue.d.ts +13 -0
- package/dist/types/extensions/editor-kit.d.ts +4 -1
- package/dist/types/extensions/table/view.d.ts +36 -2
- package/dist/types/flow/board-block.vue.d.ts +16 -0
- package/dist/types/flow/board.d.ts +53 -0
- package/dist/types/flow/index.d.ts +65 -0
- package/dist/types/index.d.ts +29 -4
- package/dist/types/locale.d.ts +34 -0
- package/dist/types/markdown/cjk-friendly.d.ts +6 -0
- package/dist/types/markdown/index.d.ts +11 -4
- package/dist/types/use-comments.d.ts +1 -0
- package/dist/use-comments.js +63 -9
- package/dist/use-comments.js.map +1 -1
- package/package.json +14 -5
package/dist/core/prepare.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepare.js","names":["PMDOMParser"],"sources":["../../src/core/prepare.ts"],"sourcesContent":["import { DOMParser as PMDOMParser } from 'prosemirror-model'\nimport { Plugin, PluginKey } from 'prosemirror-state'\nimport type { ResolvedEditorExtensions } from './extension'\nimport { createId, docToBlocks, type Block } from './model'\n\n/**\n * The editor's own markup for a block: a content element of `type` holding\n * `content`, followed by a group holding `children`. Extensions use it in\n * `prepareHTML` to turn containers such as `<details>` into blocks.\n */\nexport function blockElement(\n doc: Document,\n type: string,\n content: Node[],\n children: Node[] = [],\n data: Record<string, string> = {},\n): HTMLElement {\n const block = doc.createElement('div')\n block.dataset.blockId = ''\n const element = doc.createElement('div')\n element.dataset.contentType = type\n Object.assign(element.dataset, data)\n element.append(...content)\n block.append(element)\n if (children.some((node) => node.nodeType === 1 || node.textContent?.trim())) {\n const group = doc.createElement('div')\n group.className = 'dou-editor__group'\n group.append(...children)\n block.append(group)\n }\n return block\n}\n\n/**\n * Split a container's children into its own text (the first paragraph, or\n * the inline nodes before the first block element) and the blocks after it.\n */\nexport function splitContainer(element: Element): { content: Node[]; children: Node[] } {\n const nodes = Array.from(element.childNodes)\n while (nodes.length && isBlank(nodes[0]!)) nodes.shift()\n const first = nodes[0]\n if (first
|
|
1
|
+
{"version":3,"file":"prepare.js","names":["PMDOMParser"],"sources":["../../src/core/prepare.ts"],"sourcesContent":["import { DOMParser as PMDOMParser } from 'prosemirror-model'\nimport { Plugin, PluginKey } from 'prosemirror-state'\nimport type { ResolvedEditorExtensions } from './extension'\nimport { createId, docToBlocks, type Block } from './model'\n\n/**\n * The editor's own markup for a block: a content element of `type` holding\n * `content`, followed by a group holding `children`. Extensions use it in\n * `prepareHTML` to turn containers such as `<details>` into blocks.\n */\nexport function blockElement(\n doc: Document,\n type: string,\n content: Node[],\n children: Node[] = [],\n data: Record<string, string> = {},\n): HTMLElement {\n const block = doc.createElement('div')\n block.dataset.blockId = ''\n const element = doc.createElement('div')\n element.dataset.contentType = type\n Object.assign(element.dataset, data)\n element.append(...content)\n block.append(element)\n if (children.some((node) => node.nodeType === 1 || node.textContent?.trim())) {\n const group = doc.createElement('div')\n group.className = 'dou-editor__group'\n group.append(...children)\n block.append(group)\n }\n return block\n}\n\n/**\n * Split a container's children into its own text (the first paragraph, or\n * the inline nodes before the first block element) and the blocks after it.\n */\nexport function splitContainer(element: Element): { content: Node[]; children: Node[] } {\n const nodes = Array.from(element.childNodes)\n while (nodes.length && isBlank(nodes[0]!)) nodes.shift()\n const first = nodes[0]\n if (first?.nodeType === 1 && (first as Element).tagName === 'P')\n return { content: Array.from(first.childNodes), children: nodes.slice(1) }\n const content: Node[] = []\n while (nodes.length && !isBlockElement(nodes[0]!)) content.push(nodes.shift()!)\n return { content, children: nodes }\n}\n\nconst BLOCK_TAGS = new Set([\n 'ADDRESS',\n 'ARTICLE',\n 'ASIDE',\n 'BLOCKQUOTE',\n 'DETAILS',\n 'DIV',\n 'DL',\n 'FIGURE',\n 'FOOTER',\n 'H1',\n 'H2',\n 'H3',\n 'H4',\n 'H5',\n 'H6',\n 'HEADER',\n 'HR',\n 'OL',\n 'P',\n 'PRE',\n 'SECTION',\n 'TABLE',\n 'UL',\n])\n\nconst isBlank = (node: Node) => node.nodeType === 3 && !node.textContent?.trim()\n\nconst isBlockElement = (node: Node) =>\n node.nodeType === 1 && BLOCK_TAGS.has((node as Element).tagName)\n\n/** Run every extension's `prepareHTML` over the markup. */\nexport function prepareElement(root: HTMLElement, kit: ResolvedEditorExtensions) {\n for (const extension of kit.extensions) extension.prepareHTML?.(root)\n}\n\n/**\n * Something that reads HTML like the browser's `DOMParser`, e.g. one from a\n * DOM library such as happy-dom or linkedom. Only `parseFromString` is used,\n * and only the `body` of what it returns.\n */\nexport interface DOMParserLike {\n parseFromString(html: string, type: 'text/html'): { body: unknown }\n}\n\n/**\n * Read HTML as blocks, with the block types, inline nodes and marks of `kit`.\n * Uses the global `DOMParser` unless given `domParser`; `name` is the\n * function the error message tells to pass one to.\n */\nexport function parseHTML(\n html: string,\n kit: ResolvedEditorExtensions,\n domParser?: DOMParserLike,\n name = 'htmlToBlocks(html, extensions, { domParser })',\n): Block[] {\n const parser = domParser ?? (typeof DOMParser === 'undefined' ? null : new DOMParser())\n if (!parser)\n throw new Error(\n `[@dou-ui/editor] reading HTML needs a DOMParser, and there is none here: pass one from a DOM library such as happy-dom or linkedom, as ${name}`,\n )\n // a whole document: some libraries leave the body empty for a bare fragment\n const whole = /^\\s*<(!doctype|html)/i.test(html)\n ? html\n : `<!doctype html><html><head></head><body>${html}</body></html>`\n const doc = parser.parseFromString(whole, 'text/html') as unknown as Document\n prepareElement(doc.body, kit)\n const blocks = docToBlocks(PMDOMParser.fromSchema(kit.schema).parse(doc.body as unknown as Node))\n // read blocks are shared and read-only: copy the ones without an id\n const fill = (list: Block[]): Block[] =>\n list.map((block) => ({ ...block, id: block.id || createId(), children: fill(block.children) }))\n return fill(blocks)\n}\n\n/** Pasted HTML goes through the extensions' `prepareHTML` too. */\nexport function preparePastePlugin(kit: ResolvedEditorExtensions): Plugin {\n return new Plugin({\n key: new PluginKey('dou-editor-paste'),\n props: {\n transformPastedHTML(html) {\n if (!kit.extensions.some((extension) => extension.prepareHTML)) return html\n const doc = new DOMParser().parseFromString(html, 'text/html')\n prepareElement(doc.body, kit)\n return doc.body.innerHTML\n },\n },\n })\n}\n"],"mappings":";;;;;;;;;AAUA,SAAgB,aACd,KACA,MACA,SACA,WAAmB,CAAC,GACpB,OAA+B,CAAC,GACnB;CACb,MAAM,QAAQ,IAAI,cAAc,KAAK;CACrC,MAAM,QAAQ,UAAU;CACxB,MAAM,UAAU,IAAI,cAAc,KAAK;CACvC,QAAQ,QAAQ,cAAc;CAC9B,OAAO,OAAO,QAAQ,SAAS,IAAI;CACnC,QAAQ,OAAO,GAAG,OAAO;CACzB,MAAM,OAAO,OAAO;CACpB,IAAI,SAAS,MAAM,SAAS,KAAK,aAAa,KAAK,KAAK,aAAa,KAAK,CAAC,GAAG;EAC5E,MAAM,QAAQ,IAAI,cAAc,KAAK;EACrC,MAAM,YAAY;EAClB,MAAM,OAAO,GAAG,QAA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AI,MAAM,CAAC,CAAC,MAAM,IAAI,IAAuB,CAAC;CAEhG,MAAM,QAAQ,SACZ,KAAK,KAAK,WAAW;EAAE,GAAG;EAAO,IAAI,MAAM,MAAM,SAAS;EAAG,UAAU,KAAK,MAAM,QAAQ;CAAE,EAAE;CAChG,OAAO,KAAK,MAAM;AACpB;;AAGA,SAAgB,mBAAmB,KAAuC;CACxE,OAAO,IAAI,OAAO;EAChB,KAAK,IAAI,UAAU,kBAAkB;EACrC,OAAO,EACL,oBAAoB,MAAM;GACxB,IAAI,CAAC,IAAI,WAAW,MAAM,cAAc,UAAU,WAAW,GAAG,OAAO;GACvE,MAAM,MAAM,IAAI,UAAU,CAAC,CAAC,gBAAgB,MAAM,WAAW;GAC7D,eAAe,IAAI,MAAM,GAAG;GAC5B,OAAO,IAAI,KAAK;EAClB,EACF;CACF,CAAC;AACH"}
|
package/dist/core/schema.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.js","names":[],"sources":["../../src/core/schema.ts"],"sourcesContent":["import { alignable } from './align'\nimport { Schema, type DOMOutputSpec, type MarkSpec, type NodeSpec } from 'prosemirror-model'\n\n/**\n * The document is a list of blocks. Each block is a `block` node holding\n * one piece of content (a paragraph, a heading, a list item…) and,\n * optionally, a `blockGroup` of child blocks:\n *\n * doc\n * └─ block#id\n * ├─ paragraph \"Hello\"\n * └─ blockGroup\n * └─ block#id\n * └─ checkItem \"Nested\"\n *\n * The frame (doc, block, group, paragraph, text, line break) is fixed;\n * every other content type and mark comes from an extension. Every piece\n * of state lives in node attributes (never in a node view), so a\n * collaborative binding can sync it like any other change.\n */\n\n/** The DOM of a content node: `div.dou-editor__content--<type>[data-content-type]`. */\nexport const contentDOM = (type: string, extra: Record<string, string> = {}): DOMOutputSpec => [\n 'div',\n {\n class: `dou-editor__content dou-editor__content--${type}`,\n 'data-content-type': type,\n ...extra,\n },\n 0,\n]\n\n/** A content type holding formatted text, parsed back from its own DOM. */\nexport const textBlock = (type: string, spec: Partial<NodeSpec> = {}): NodeSpec => ({\n content: 'inline*',\n defining: true,\n parseDOM: [{ tag: `div[data-content-type=\"${type}\"]` }],\n toDOM: () => contentDOM(type),\n ...spec,\n})\n\nconst frame: Record<string, NodeSpec> = {\n doc: { content: 'block+' },\n\n block: {\n attrs: { id: { default: null } },\n content: 'blockContent blockGroup?',\n defining: true,\n parseDOM: [\n {\n tag: 'div[data-block-id]',\n getAttrs: (dom) => ({ id: (dom as HTMLElement).dataset.blockId ?? null }),\n },\n ],\n toDOM: (node) => ['div', { class: 'dou-editor__block', 'data-block-id': node.attrs.id }, 0],\n },\n\n blockGroup: {\n content: 'block+',\n parseDOM: [{ tag: 'div.dou-editor__group' }],\n toDOM: () => ['div', { class: 'dou-editor__group', role: 'group' }, 0],\n },\n\n paragraph: alignable(\n textBlock('paragraph', {\n group: 'blockContent',\n parseDOM: [{ tag: 'div[data-content-type=\"paragraph\"]' }, { tag: 'p' }],\n }),\n ),\n}\n\nconst inlineFrame: Record<string, NodeSpec> = {\n text: { group: 'inline' },\n\n hardBreak: {\n inline: true,\n // newlines from a code block become line breaks when it turns into text, and back\n linebreakReplacement: true,\n group: 'inline',\n selectable: false,\n parseDOM: [{ tag: 'br' }],\n toDOM: () => ['br'],\n },\n}\n\n/**\n * Where a comment thread is anchored: the text it is about carries the\n * thread's id. A text can be in several threads, so the mark excludes\n * nothing, not even itself; typing at its edge doesn't extend it.\n */\nconst commentMark: MarkSpec = {\n attrs: { id: {} },\n excludes: '',\n inclusive: false,\n parseDOM: [\n {\n tag: 'span[data-comment]',\n getAttrs: (dom) => ({ id: (dom as HTMLElement).dataset.comment }),\n },\n ],\n toDOM: (mark) => ['span', { class: 'dou-editor__comment', 'data-comment': mark.attrs.id }, 0],\n}\n\nexport interface SchemaParts {\n blocks: Record<string, NodeSpec>\n /** Nodes inside blocks, e.g. table rows and cells. */\n nodes?: Record<string, NodeSpec>\n inlines: Record<string, NodeSpec>\n marks: Record<string, MarkSpec>\n}\n\n/** The schema for a set of extensions' blocks, inline nodes and marks. */\nexport function createSchema({ blocks, nodes: inner = {}, inlines, marks }: SchemaParts): Schema {\n const nodes: Record<string, NodeSpec> = { ...frame }\n for (const [name, spec] of Object.entries(blocks)) {\n if (name in nodes) throw new Error(`[@dou-ui/editor] \"${name}\" is a built-in node`)\n nodes[name] = { ...spec, group: spec.group ? `blockContent ${spec.group}` : 'blockContent' }\n }\n for (const [name, spec] of Object.entries(inner)) {\n if (name in nodes) throw new Error(`[@dou-ui/editor] \"${name}\" is a built-in node`)\n nodes[name] = spec\n }\n Object.assign(nodes, inlineFrame)\n for (const [name, spec] of Object.entries(inlines)) {\n if (name in nodes) throw new Error(`[@dou-ui/editor] \"${name}\" is a built-in node`)\n nodes[name] = { inline: true, ...spec, group: spec.group ? `inline ${spec.group}` : 'inline' }\n }\n if ('comment' in marks) throw new Error('[@dou-ui/editor] \"comment\" is a built-in mark')\n // any text can be commented on, also text whose mark excludes all others (inline code)\n const others = Object.keys(marks).join(' ')\n const specs = Object.fromEntries(\n Object.entries(marks).map(([name, spec]) => [\n name,\n spec.excludes === '_' ? { ...spec, excludes: others } : spec,\n ]),\n )\n // first, so a comment wraps the formatting of the text it is about\n return new Schema({ nodes, marks: { comment: commentMark, ...specs } })\n}\n\n/** Links may only point to web pages, mail, phone numbers or relative paths. */\nexport function isSafeHref(href: string): boolean {\n // browsers ignore whitespace and control characters inside the scheme\n // eslint-disable-next-line no-control-regex\n const value = href.replace(/[\\u0000- ]/g, '')\n const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(value)?.[1]?.toLowerCase()\n return !scheme || ['http', 'https', 'mailto', 'tel'].includes(scheme)\n}\n\n/** The content types that come with `editorKit`; extensions add more. */\nexport type BuiltinContentType =\n | 'paragraph'\n | 'heading'\n | 'bulletItem'\n | 'numberedItem'\n | 'checkItem'\n | 'quote'\n | 'codeBlock'\n | 'divider'\n | 'toggle'\n | 'callout'\n | 'table'\n\nexport type ContentType = BuiltinContentType | (string & {})\n\nexport type BuiltinMarkType = 'bold' | 'italic' | 'underline' | 'strike' | 'code'\n\nexport type MarkType = BuiltinMarkType | (string & {})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsBA,IAAa,cAAc,MAAc,QAAgC,CAAC,MAAqB;CAC7F;CACA;EACE,OAAO,4CAA4C;EACnD,qBAAqB;EACrB,GAAG;CACL;CACA;AACF;;AAGA,IAAa,aAAa,MAAc,OAA0B,CAAC,OAAiB;CAClF,SAAS;CACT,UAAU;CACV,UAAU,CAAC,EAAE,KAAK,0BAA0B,KAAK,IAAI,CAAC;CACtD,aAAa,WAAW,IAAI;CAC5B,GAAG;AACL;AAEA,IAAM,QAAkC;CACtC,KAAK,EAAE,SAAS,SAAS;CAEzB,OAAO;EACL,OAAO,EAAE,IAAI,EAAE,SAAS,KAAK,EAAE;EAC/B,SAAS;EACT,UAAU;EACV,UAAU,CACR;GACE,KAAK;GACL,WAAW,SAAS,EAAE,IAAK,IAAoB,QAAQ,WAAW,KAAK;EACzE,CACF;EACA,QAAQ,SAAS;GAAC;GAAO;IAAE,OAAO;IAAqB,iBAAiB,KAAK,MAAM;GAAG;GAAG;EAAC;CAC5F;CAEA,YAAY;EACV,SAAS;EACT,UAAU,CAAC,EAAE,KAAK,wBAAwB,CAAC;EAC3C,aAAa;GAAC;GAAO;IAAE,OAAO;IAAqB,MAAM;GAAQ;GAAG;EAAC;CACvE;CAEA,WAAW,UACT,UAAU,aAAa;EACrB,OAAO;EACP,UAAU,CAAC,EAAE,KAAK,uCAAqC,GAAG,EAAE,KAAK,IAAI,CAAC;CACxE,CAAC,CACH;AACF;AAEA,IAAM,cAAwC;CAC5C,MAAM,EAAE,OAAO,SAAS;CAExB,WAAW;EACT,QAAQ;EAER,sBAAsB;EACtB,OAAO;EACP,YAAY;EACZ,UAAU,CAAC,EAAE,KAAK,KAAK,CAAC;EACxB,aAAa,CAAC,IAAI;CACpB;AACF;;;;;;AAOA,IAAM,cAAwB;CAC5B,OAAO,EAA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C1D,CAAC,CACH;CAEA,OAAO,IAAI,OAAO;EAAE;EAAO,OAAO;GAAE,SAAS;GAAa,GAAG;EAAM;CAAE,CAAC;AACxE;;AAGA,SAAgB,WAAW,MAAuB;CAGhD,MAAM,QAAQ,KAAK,QAAQ,eAAe,EAAE;CAC5C,MAAM,SAAS,yBAAyB,KAAK,KAAK,CAAC,GAAG,EAAE,EAAE,YAAY;CACtE,OAAO,CAAC,UAAU;EAAC;EAAQ;EAAS;EAAU;CAAK,CAAC,CAAC,SAAS,MAAM;AACtE"}
|
|
1
|
+
{"version":3,"file":"schema.js","names":[],"sources":["../../src/core/schema.ts"],"sourcesContent":["import { alignable } from './align'\nimport { Schema, type DOMOutputSpec, type MarkSpec, type NodeSpec } from 'prosemirror-model'\n\n/**\n * The document is a list of blocks. Each block is a `block` node holding\n * one piece of content (a paragraph, a heading, a list item…) and,\n * optionally, a `blockGroup` of child blocks:\n *\n * doc\n * └─ block#id\n * ├─ paragraph \"Hello\"\n * └─ blockGroup\n * └─ block#id\n * └─ checkItem \"Nested\"\n *\n * The frame (doc, block, group, paragraph, text, line break) is fixed;\n * every other content type and mark comes from an extension. Every piece\n * of state lives in node attributes (never in a node view), so a\n * collaborative binding can sync it like any other change.\n */\n\n/** The DOM of a content node: `div.dou-editor__content--<type>[data-content-type]`. */\nexport const contentDOM = (type: string, extra: Record<string, string> = {}): DOMOutputSpec => [\n 'div',\n {\n class: `dou-editor__content dou-editor__content--${type}`,\n 'data-content-type': type,\n ...extra,\n },\n 0,\n]\n\n/** A content type holding formatted text, parsed back from its own DOM. */\nexport const textBlock = (type: string, spec: Partial<NodeSpec> = {}): NodeSpec => ({\n content: 'inline*',\n defining: true,\n parseDOM: [{ tag: `div[data-content-type=\"${type}\"]` }],\n toDOM: () => contentDOM(type),\n ...spec,\n})\n\nconst frame: Record<string, NodeSpec> = {\n doc: { content: 'block+' },\n\n block: {\n attrs: { id: { default: null } },\n content: 'blockContent blockGroup?',\n defining: true,\n parseDOM: [\n {\n tag: 'div[data-block-id]',\n getAttrs: (dom) => ({ id: (dom as HTMLElement).dataset.blockId ?? null }),\n },\n ],\n toDOM: (node) => ['div', { class: 'dou-editor__block', 'data-block-id': node.attrs.id }, 0],\n },\n\n blockGroup: {\n content: 'block+',\n parseDOM: [{ tag: 'div.dou-editor__group' }],\n toDOM: () => ['div', { class: 'dou-editor__group', role: 'group' }, 0],\n },\n\n paragraph: alignable(\n textBlock('paragraph', {\n group: 'blockContent',\n parseDOM: [{ tag: 'div[data-content-type=\"paragraph\"]' }, { tag: 'p' }],\n }),\n ),\n}\n\nconst inlineFrame: Record<string, NodeSpec> = {\n text: { group: 'inline' },\n\n hardBreak: {\n inline: true,\n // newlines from a code block become line breaks when it turns into text, and back\n linebreakReplacement: true,\n group: 'inline',\n selectable: false,\n parseDOM: [{ tag: 'br' }],\n toDOM: () => ['br'],\n },\n}\n\n/**\n * Where a comment thread is anchored: the text it is about carries the\n * thread's id. A text can be in several threads, so the mark excludes\n * nothing, not even itself; typing at its edge doesn't extend it.\n */\nconst commentMark: MarkSpec = {\n attrs: { id: {} },\n excludes: '',\n inclusive: false,\n parseDOM: [\n {\n tag: 'span[data-comment]',\n getAttrs: (dom) => ({ id: (dom as HTMLElement).dataset.comment }),\n },\n ],\n toDOM: (mark) => ['span', { class: 'dou-editor__comment', 'data-comment': mark.attrs.id }, 0],\n}\n\nexport interface SchemaParts {\n blocks: Record<string, NodeSpec>\n /** Nodes inside blocks, e.g. table rows and cells. */\n nodes?: Record<string, NodeSpec>\n inlines: Record<string, NodeSpec>\n marks: Record<string, MarkSpec>\n}\n\n/** The schema for a set of extensions' blocks, inline nodes and marks. */\nexport function createSchema({ blocks, nodes: inner = {}, inlines, marks }: SchemaParts): Schema {\n const nodes: Record<string, NodeSpec> = { ...frame }\n for (const [name, spec] of Object.entries(blocks)) {\n if (name in nodes) throw new Error(`[@dou-ui/editor] \"${name}\" is a built-in node`)\n nodes[name] = { ...spec, group: spec.group ? `blockContent ${spec.group}` : 'blockContent' }\n }\n for (const [name, spec] of Object.entries(inner)) {\n if (name in nodes) throw new Error(`[@dou-ui/editor] \"${name}\" is a built-in node`)\n nodes[name] = spec\n }\n Object.assign(nodes, inlineFrame)\n for (const [name, spec] of Object.entries(inlines)) {\n if (name in nodes) throw new Error(`[@dou-ui/editor] \"${name}\" is a built-in node`)\n nodes[name] = { inline: true, ...spec, group: spec.group ? `inline ${spec.group}` : 'inline' }\n }\n if ('comment' in marks) throw new Error('[@dou-ui/editor] \"comment\" is a built-in mark')\n // any text can be commented on, also text whose mark excludes all others (inline code)\n const others = Object.keys(marks).join(' ')\n const specs = Object.fromEntries(\n Object.entries(marks).map(([name, spec]) => [\n name,\n spec.excludes === '_' ? { ...spec, excludes: others } : spec,\n ]),\n )\n // first, so a comment wraps the formatting of the text it is about\n return new Schema({ nodes, marks: { comment: commentMark, ...specs } })\n}\n\n/** Links may only point to web pages, mail, phone numbers or relative paths. */\nexport function isSafeHref(href: string): boolean {\n // browsers ignore whitespace and control characters inside the scheme\n // eslint-disable-next-line no-control-regex\n const value = href.replace(/[\\u0000- ]/g, '')\n const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(value)?.[1]?.toLowerCase()\n return !scheme || ['http', 'https', 'mailto', 'tel'].includes(scheme)\n}\n\n/** The content types that come with `editorKit`; extensions add more. */\nexport type BuiltinContentType =\n | 'paragraph'\n | 'heading'\n | 'bulletItem'\n | 'numberedItem'\n | 'checkItem'\n | 'quote'\n | 'codeBlock'\n | 'divider'\n | 'toggle'\n | 'callout'\n | 'table'\n | 'columns'\n | 'column'\n\nexport type ContentType = BuiltinContentType | (string & {})\n\nexport type BuiltinMarkType = 'bold' | 'italic' | 'underline' | 'strike' | 'code'\n\nexport type MarkType = BuiltinMarkType | (string & {})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsBA,IAAa,cAAc,MAAc,QAAgC,CAAC,MAAqB;CAC7F;CACA;EACE,OAAO,4CAA4C;EACnD,qBAAqB;EACrB,GAAG;C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,EAAE,EAAE,YAAY;CACtE,OAAO,CAAC,UAAU;EAAC;EAAQ;EAAS;EAAU;CAAK,CAAC,CAAC,SAAS,MAAM;AACtE"}
|
package/dist/core/transaction.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { blockFromNode, contentAttrs, createContentNode, createId, nodeFromBlock } from "./model.js";
|
|
2
|
-
import { blockAround, findBlockById } from "./blocks.js";
|
|
2
|
+
import { blockAround, findBlockById, layoutOf, parentBlock } from "./blocks.js";
|
|
3
3
|
import { blockSelectionRange } from "./block-selection.js";
|
|
4
4
|
import { originKey } from "./editor.js";
|
|
5
5
|
import { NodeSelection, Selection, TextSelection } from "prosemirror-state";
|
|
@@ -10,6 +10,12 @@ import { closeHistory } from "prosemirror-history";
|
|
|
10
10
|
* providers other than the built-in one (collaboration reads it).
|
|
11
11
|
*/
|
|
12
12
|
var ownStepKey = "douOwnStep";
|
|
13
|
+
/**
|
|
14
|
+
* Set on a transaction that joins the undo step before it however long
|
|
15
|
+
* after it comes, e.g. the frames of a drag on a whiteboard (with
|
|
16
|
+
* `appendedTransaction` for the built-in history).
|
|
17
|
+
*/
|
|
18
|
+
var joinStepKey = "douJoinStep";
|
|
13
19
|
var warn = (message) => {
|
|
14
20
|
if (process.env.NODE_ENV !== "production") console.warn(`[@dou-ui/editor] ${message}`);
|
|
15
21
|
};
|
|
@@ -55,11 +61,15 @@ var EditorTransaction = class {
|
|
|
55
61
|
const taken = usedIds(tr.doc);
|
|
56
62
|
const ids = [];
|
|
57
63
|
const nodes = blocks.map((block) => {
|
|
58
|
-
const node = nodeFromBlock(schema, freshIds(block, taken));
|
|
64
|
+
const node = nodeFromBlock(schema, freshIds(block, taken), true);
|
|
59
65
|
ids.push(node.attrs.id);
|
|
60
66
|
return node;
|
|
61
67
|
});
|
|
62
68
|
if (insertNodes(tr, placement ?? this.defaultPlacement(), nodes) === null) return [];
|
|
69
|
+
for (const id of ids) {
|
|
70
|
+
const info = findBlockById(tr.doc, id);
|
|
71
|
+
if (layoutOf(info?.node) === "row" && info && inColumn(tr.doc, info)) warn(`insertBlocks: columns don't go in a column; the block "${id}" is replaced by its columns' blocks`);
|
|
72
|
+
}
|
|
63
73
|
return ids;
|
|
64
74
|
}
|
|
65
75
|
/** Change a block's type, props, content or children. Returns `false` when it isn't found. */
|
|
@@ -260,6 +270,11 @@ function childPos(start, container, index = container.childCount) {
|
|
|
260
270
|
for (let i = 0; i < at; i++) pos += container.child(i).nodeSize;
|
|
261
271
|
return pos;
|
|
262
272
|
}
|
|
273
|
+
/** Whether a block sits in a column, at any depth. */
|
|
274
|
+
function inColumn(doc, info) {
|
|
275
|
+
for (let parent = parentBlock(doc, info); parent; parent = parentBlock(doc, parent)) if (layoutOf(parent.node) === "column") return true;
|
|
276
|
+
return false;
|
|
277
|
+
}
|
|
263
278
|
function replaceChildren(tr, info, children) {
|
|
264
279
|
const schema = tr.doc.type.schema;
|
|
265
280
|
const groupPos = info.contentPos + info.content.nodeSize;
|
|
@@ -267,7 +282,7 @@ function replaceChildren(tr, info, children) {
|
|
|
267
282
|
info.group?.descendants((node) => {
|
|
268
283
|
if (node.type.name === "block") taken.delete(node.attrs.id);
|
|
269
284
|
});
|
|
270
|
-
const nodes = children.map((child) => nodeFromBlock(schema, freshIds(child, taken)));
|
|
285
|
+
const nodes = children.map((child) => nodeFromBlock(schema, freshIds(child, taken), true));
|
|
271
286
|
const group = nodes.length ? schema.nodes.blockGroup.create(null, nodes) : null;
|
|
272
287
|
const end = info.group ? groupPos + info.group.nodeSize : groupPos;
|
|
273
288
|
if (group) tr.replaceWith(groupPos, end, group);
|
|
@@ -306,6 +321,6 @@ function applyEditorTransaction(view, transaction) {
|
|
|
306
321
|
view.dispatch(closeHistory(view.state.tr));
|
|
307
322
|
return true;
|
|
308
323
|
}
|
|
309
|
-
export { EditorTransaction, applyEditorTransaction, ownStepKey, selectionIn };
|
|
324
|
+
export { EditorTransaction, applyEditorTransaction, joinStepKey, ownStepKey, selectionIn };
|
|
310
325
|
|
|
311
326
|
//# sourceMappingURL=transaction.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction.js","names":[],"sources":["../../src/core/transaction.ts"],"sourcesContent":["import type { Node as PMNode, Schema } from 'prosemirror-model'\nimport {\n NodeSelection,\n Selection,\n TextSelection,\n type EditorState,\n type Transaction,\n} from 'prosemirror-state'\nimport { blockAround, findBlockById, type BlockInfo } from './blocks'\nimport { blockSelectionRange } from './block-selection'\nimport {\n blockFromNode,\n contentAttrs,\n createContentNode,\n createId,\n nodeFromBlock,\n type Block,\n type BlockProps,\n type InlineContent,\n type PartialBlock,\n type PartialTableRow,\n} from './model'\nimport type { ContentType } from './schema'\nimport { closeHistory } from 'prosemirror-history'\nimport type { EditorView } from 'prosemirror-view'\nimport { originKey } from './editor'\n\n/**\n * Where blocks go: right before or after a block, or among a block's\n * children (`parent: null` is the top level). `index` counts from 0 and\n * defaults to the end.\n */\nexport type BlockPlacement =\n { before: string } | { after: string } | { parent: string | null; index?: number }\n\n/** The parts of a block to change. `props` are merged into the current ones. */\nexport interface BlockPatch {\n type?: ContentType\n props?: BlockProps\n /** Inline content, or plain text. */\n content?: InlineContent[] | string\n rows?: PartialTableRow[]\n /** Replaces all children; `[]` removes them. */\n children?: PartialBlock[]\n}\n\nexport interface EditorTransactionMeta {\n /** `false` keeps the change out of undo, e.g. a fix made by the program. */\n history?: boolean\n /** Who made the change; passed on to the `transaction` event. */\n origin?: string\n}\n\n/** Where a selection is put inside a block: at the start of its text or at the end. */\nexport type BlockEdge = 'start' | 'end'\n\n/**\n * Set on a transaction that is an undo step of its own, for history\n * providers other than the built-in one (collaboration reads it).\n */\nexport const ownStepKey = 'douOwnStep'\n\nconst warn = (message: string) => {\n if (process.env.NODE_ENV !== 'production') console.warn(`[@dou-ui/editor] ${message}`)\n}\n\n/**\n * Changes made by blocks and ids, applied together as one undo step. Ids\n * are looked up in the document as it is after the earlier calls.\n */\nexport class EditorTransaction {\n /** The ProseMirror transaction underneath, for anything the methods don't cover. */\n readonly tr: Transaction\n readonly meta: EditorTransactionMeta\n /** `focusBlock` was called: the editor takes focus once the changes are applied. */\n focused = false\n\n constructor(\n /** The state the changes start from. */\n readonly before: EditorState,\n meta: EditorTransactionMeta = {},\n /**\n * Whether the selection was placed by the user or the program. An editor\n * that never had focus has its selection at the start, which is no cursor.\n */\n private readonly hasCursor = true,\n ) {\n this.tr = before.tr\n this.meta = { ...meta }\n }\n\n get changed(): boolean {\n return this.tr.docChanged\n }\n\n setMeta(meta: EditorTransactionMeta): this {\n Object.assign(this.meta, meta)\n return this\n }\n\n /** A block as it is now, or `null`. */\n getBlock(id: string): Block | null {\n const info = findBlockById(this.tr.doc, id)\n return info ? blockFromNode(info.node) : null\n }\n\n /**\n * Insert blocks, by default after the block with the cursor (at the end\n * without one). Returns the new blocks' ids; an id already in the\n * document is replaced with a fresh one.\n */\n insertBlocks(blocks: PartialBlock[], placement?: BlockPlacement): string[] {\n if (!blocks.length) return []\n const tr = this.tr\n const schema = tr.doc.type.schema\n const taken = usedIds(tr.doc)\n const ids: string[] = []\n const nodes = blocks.map((block) => {\n const node = nodeFromBlock(schema, freshIds(block, taken))\n ids.push(node.attrs.id as string)\n return node\n })\n const target = placement ?? this.defaultPlacement()\n if (insertNodes(tr, target, nodes) === null) return []\n return ids\n }\n\n /** Change a block's type, props, content or children. Returns `false` when it isn't found. */\n updateBlock(id: string, patch: BlockPatch): boolean {\n const tr = this.tr\n const info = findBlockById(tr.doc, id)\n if (!info) {\n warn(`updateBlock: no block with the id \"${id}\"`)\n return false\n }\n const schema = tr.doc.type.schema\n // check everything before changing anything: a refused patch changes nothing\n const typeName = patch.type ?? info.content.type.name\n const nodeType = schema.nodes[typeName]\n if (!nodeType?.isInGroup('blockContent')) {\n warn(`updateBlock: unknown block type \"${typeName}\"`)\n return false\n }\n const rowsSpec = !!nodeType.spec.rows\n if (patch.rows !== undefined && !rowsSpec) {\n warn(`updateBlock: a \"${typeName}\" block has no rows`)\n return false\n }\n if (patch.content !== undefined && (rowsSpec || !nodeType.inlineContent)) {\n warn(`updateBlock: a \"${typeName}\" block has no text content`)\n return false\n }\n if (patch.children) replaceChildren(tr, info, patch.children)\n if (\n patch.type === undefined &&\n patch.props === undefined &&\n patch.content === undefined &&\n patch.rows === undefined\n )\n return true\n const current = findBlockById(tr.doc, id)!\n const content = current.content\n const props = { ...content.attrs, ...patch.props }\n const keepsContent = patch.content === undefined && patch.rows === undefined\n // keep the text node for node when it can stay: collaborators typing in it keep their place\n if (keepsContent && nodeType === content.type) {\n tr.setNodeMarkup(current.contentPos, undefined, contentAttrs(nodeType, props))\n return true\n }\n if (keepsContent && nodeType.isTextblock && content.isTextblock) {\n const from = current.contentPos\n tr.setBlockType(\n from + 1,\n from + content.nodeSize - 1,\n nodeType,\n contentAttrs(nodeType, props),\n )\n return true\n }\n const block = blockFromNode(current.node)\n const next = createContentNode(\n schema,\n typeName,\n props,\n patch.content ?? block.content,\n patch.rows ?? block.rows,\n )\n tr.replaceWith(current.contentPos, current.contentPos + content.nodeSize, next)\n return true\n }\n\n /** Remove blocks with their children. The document always keeps one block. */\n removeBlocks(ids: string[]): boolean {\n const infos = outermost(this.tr.doc, ids, 'removeBlocks')\n if (!infos.length) return false\n deleteInfos(this.tr, infos)\n const tr = this.tr\n if (tr.doc.content.size === 0) tr.insert(0, emptyBlock(tr.doc.type.schema))\n return true\n }\n\n /**\n * Move blocks, in the order given, to `placement`. Fails when it is\n * inside one of them.\n */\n moveBlocks(ids: string[], placement: BlockPlacement): boolean {\n const tr = this.tr\n const infos = outermost(tr.doc, ids, 'moveBlocks')\n if (!infos.length) return false\n const anchor =\n 'before' in placement\n ? placement.before\n : 'after' in placement\n ? placement.after\n : placement.parent\n if (\n anchor !== null &&\n infos.some((info) => info.node.attrs.id === anchor || contains(info, tr.doc, anchor))\n ) {\n warn('moveBlocks: blocks cannot be moved next to or into themselves')\n return false\n }\n // insert the moved blocks first, then delete the originals: the document never empties\n const nodes = infos.map((info) => info.node)\n // a selection inside a moved block goes along with it\n const { anchor: anchorPos, head } = tr.selection\n const nodeSelected = tr.selection instanceof NodeSelection\n const carried = infos.findIndex(\n (info) =>\n anchorPos > info.pos &&\n anchorPos < info.pos + info.node.nodeSize &&\n head > info.pos &&\n head < info.pos + info.node.nodeSize,\n )\n const base = tr.steps.length\n const at = insertNodes(tr, placement, nodes)\n if (at === null) return false\n const inserted = tr.steps.length\n deleteInfos(tr, infos, base)\n if (carried >= 0) {\n const info = infos[carried]!\n let start = at\n for (let i = 0; i < carried; i++) start += nodes[i]!.nodeSize\n const moved = tr.mapping.slice(inserted).map(start, 1)\n const shift = (pos: number) => moved + (pos - info.pos)\n tr.setSelection(\n nodeSelected\n ? NodeSelection.create(tr.doc, shift(anchorPos))\n : TextSelection.create(tr.doc, shift(anchorPos), shift(head)),\n )\n }\n return true\n }\n\n /** Put the cursor at the start or end of a block's text (or select a block without text). */\n focusBlock(id: string, edge: BlockEdge = 'end'): boolean {\n const tr = this.tr\n const info = findBlockById(tr.doc, id)\n if (!info) {\n warn(`focusBlock: no block with the id \"${id}\"`)\n return false\n }\n tr.setSelection(selectionIn(tr, info, edge)).scrollIntoView()\n this.focused = true\n return true\n }\n\n /** After the selection's block, or at the end. */\n private defaultPlacement(): BlockPlacement {\n if (!this.hasCursor && !this.tr.selectionSet) return { parent: null }\n // selected blocks are only known before the first change\n const range = this.tr.docChanged ? null : blockSelectionRange(this.before)\n const id = range\n ? (range.parent.child(range.to).attrs.id as string)\n : (blockAround(this.tr.selection.$to)?.node.attrs.id as string | undefined)\n return id ? { after: id } : { parent: null }\n }\n}\n\nfunction emptyBlock(schema: Schema): PMNode {\n return schema.nodes.block!.create({ id: createId() }, schema.nodes.paragraph!.create())\n}\n\nfunction usedIds(doc: PMNode): Set<string> {\n const ids = new Set<string>()\n doc.descendants((node) => {\n if (node.type.name === 'block') ids.add(node.attrs.id as string)\n return node.type.name === 'block' || node.type.name === 'blockGroup'\n })\n return ids\n}\n\n/** The block with ids that are free, recursively. */\nfunction freshIds(block: PartialBlock, taken: Set<string>): PartialBlock {\n let id = block.id\n if (!id || taken.has(id)) id = createId()\n taken.add(id)\n return {\n ...block,\n id,\n children: block.children?.map((child) => freshIds(child, taken)),\n }\n}\n\n/** Whether a block with `id` sits inside `info`. */\nfunction contains(info: BlockInfo, doc: PMNode, id: string): boolean {\n const found = findBlockById(doc, id)\n return !!found && found.pos > info.pos && found.pos < info.pos + info.node.nodeSize\n}\n\n/** The blocks with these ids, without those inside another one of them, in the order given. */\nfunction outermost(doc: PMNode, ids: string[], method: string): BlockInfo[] {\n const infos: BlockInfo[] = []\n const seen = new Set<string>()\n for (const id of ids) {\n if (seen.has(id)) continue\n seen.add(id)\n const info = findBlockById(doc, id)\n if (info) infos.push(info)\n else warn(`${method}: no block with the id \"${id}\"`)\n }\n return infos.filter(\n (info) =>\n !infos.some(\n (other) =>\n other !== info && info.pos > other.pos && info.pos < other.pos + other.node.nodeSize,\n ),\n )\n}\n\n/**\n * Delete blocks found in the document as it was after step `base`; a\n * group left without children goes too.\n */\nfunction deleteInfos(tr: Transaction, infos: BlockInfo[], base = tr.steps.length) {\n // last first, so the earlier positions stay valid\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a copy\n const sorted = [...infos].sort((a, b) => b.pos - a.pos)\n for (const info of sorted) {\n // a block moved right in front of this one pushes it on (`1`)\n const from = tr.mapping.slice(base).map(info.pos, 1)\n const to = from + info.node.nodeSize\n const $from = tr.doc.resolve(from)\n if ($from.parent.type.name === 'blockGroup' && $from.parent.childCount === 1)\n tr.delete($from.before(), $from.after())\n else tr.delete(from, to)\n }\n}\n\n/** Insert block nodes at a placement. Returns `false` when the placement can't be found. */\nfunction insertNodes(tr: Transaction, placement: BlockPlacement, nodes: PMNode[]): number | null {\n const schema = tr.doc.type.schema\n let at: number\n if ('before' in placement || 'after' in placement) {\n const id = 'before' in placement ? placement.before : placement.after\n const info = findBlockById(tr.doc, id)\n if (!info) {\n warn(`no block with the id \"${id}\" to insert next to`)\n return null\n }\n at = 'before' in placement ? info.pos : info.pos + info.node.nodeSize\n } else if (placement.parent === null) {\n at = childPos(0, tr.doc, placement.index)\n } else {\n const info = findBlockById(tr.doc, placement.parent)\n if (!info) {\n warn(`no block with the id \"${placement.parent}\" to insert into`)\n return null\n }\n if (!info.group) {\n at = info.contentPos + info.content.nodeSize\n tr.insert(at, schema.nodes.blockGroup!.create(null, nodes))\n return at + 1\n }\n at = childPos(info.contentPos + info.content.nodeSize + 1, info.group, placement.index)\n }\n tr.insert(at, nodes)\n return at\n}\n\n/** The position before the child at `index` of a container whose content starts at `start`. */\nfunction childPos(start: number, container: PMNode, index = container.childCount) {\n const at = Math.max(0, Math.min(index, container.childCount))\n let pos = start\n for (let i = 0; i < at; i++) pos += container.child(i).nodeSize\n return pos\n}\n\nfunction replaceChildren(tr: Transaction, info: BlockInfo, children: PartialBlock[]) {\n const schema = tr.doc.type.schema\n const groupPos = info.contentPos + info.content.nodeSize\n const taken = usedIds(tr.doc)\n // the old children's ids are free again\n info.group?.descendants((node) => {\n if (node.type.name === 'block') taken.delete(node.attrs.id as string)\n })\n const nodes = children.map((child) => nodeFromBlock(schema, freshIds(child, taken)))\n const group = nodes.length ? schema.nodes.blockGroup!.create(null, nodes) : null\n const end = info.group ? groupPos + info.group.nodeSize : groupPos\n if (group) tr.replaceWith(groupPos, end, group)\n else if (info.group) tr.delete(groupPos, end)\n}\n\n/** A cursor at the start or end of a block's text; a node selection for a block without text. */\nexport function selectionIn(tr: Transaction, info: BlockInfo, edge: BlockEdge): Selection {\n const content = info.content\n const doc = tr.doc\n if (content.isTextblock) {\n const pos = edge === 'start' ? info.contentPos + 1 : info.contentPos + content.nodeSize - 1\n return TextSelection.create(doc, pos)\n }\n if (content.isAtom) return NodeSelection.create(doc, info.contentPos)\n // a table: the first or last cell's text\n const inside = edge === 'start' ? info.contentPos + 1 : info.contentPos + content.nodeSize - 1\n return Selection.near(doc.resolve(inside), edge === 'start' ? 1 : -1)\n}\n\n/**\n * Apply a transaction made with `transact`: one undo step of its own,\n * unless `history` is `false`. Returns whether anything happened.\n */\nexport function applyEditorTransaction(view: EditorView, transaction: EditorTransaction): boolean {\n const { tr, meta } = transaction\n if (!tr.docChanged && !tr.selectionSet) return false\n if (meta.origin !== undefined) tr.setMeta(originKey, meta.origin)\n if (!tr.docChanged) {\n view.dispatch(tr)\n return true\n }\n if (meta.history === false) {\n tr.setMeta('addToHistory', false)\n view.dispatch(tr)\n return true\n }\n view.dispatch(closeHistory(tr).setMeta(ownStepKey, true))\n // and typing right after it starts another step\n view.dispatch(closeHistory(view.state.tr))\n return true\n}\n"],"mappings":";;;;;;;;;;;AA4DA,IAAa,aAAa;AAE1B,IAAM,QAAQ,YAAoB;CAChC,IAAA,QAAA,IAAA,aAA6B,cAAc,QAAQ,KAAK,oBAAoB,SAAS;AACvF;;;;;AAMA,IAAa,oBAAb,MAA+B;CASlB;CAMQ;;CAbnB;CACA;;CAEA,UAAU;CAEV,YAEE,QACA,OAA8B,CAAC,GAK/B,YAA6B,MAC7B;EAPS,KAAA,SAAA;EAMQ,KAAA,YAAA;EAEjB,KAAK,KAAK,OAAO;EACjB,KAAK,OAAO,EAAE,GAAG,KAAK;CACxB;CAEA,IAAI,UAAmB;EACrB,OAAO,KAAK,GAAG;CACjB;CAEA,QAAQ,MAAmC;EACzC,OAAO,OAAO,KAAK,MAAM,IAAI;EAC7B,OAAO;CACT;;CAGA,SAAS,IAA0B;EACjC,MAAM,OAAO,cAAc,KAAK,GAAG,KAAK,EAAE;EAC1C,OAAO,OAAO,cAAc,KAAK,IAAI,IAAI;CAC3C;;;;;;CAOA,aAAa,QAAwB,WAAsC;EACzE,IAAI,CAAC,OAAO,QAAQ,OAAO,CAAC;EAC5B,MAAM,KAAK,KAAK;EAChB,MAAM,SAAS,GAAG,IAAI,KAAK;EAC3B,MAAM,QAAQ,QAAQ,GAAG,GAAG;EAC5B,MAAM,MAAgB,CAAC;EACvB,MAAM,QAAQ,OAAO,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S,UAAU,KAAK,aAAa,IAAI,KAAK,aAAa,QAAQ,WAAW;EAC1F,OAAO,cAAc,OAAO,KAAK,GAAG;CACtC;CACA,IAAI,QAAQ,QAAQ,OAAO,cAAc,OAAO,KAAK,KAAK,UAAU;CAEpE,MAAM,SAAS,SAAS,UAAU,KAAK,aAAa,IAAI,KAAK,aAAa,QAAQ,WAAW;CAC7F,OAAO,UAAU,KAAK,IAAI,QAAQ,MAAM,GAAG,SAAS,UAAU,IAAI,EAAE;AACtE;;;;;AAMA,SAAgB,uBAAuB,MAAkB,aAAyC;CAChG,MAAM,EAAE,IAAI,SAAS;CACrB,IAAI,CAAC,GAAG,cAAc,CAAC,GAAG,cAAc,OAAO;CAC/C,IAAI,KAAK,WAAW,KAAA,GAAW,GAAG,QAAQ,WAAW,KAAK,MAAM;CAChE,IAAI,CAAC,GAAG,YAAY;EAClB,KAAK,SAAS,EAAE;EAChB,OAAO;CACT;CACA,IAAI,KAAK,YAAY,OAAO;EAC1B,GAAG,QAAQ,gBAAgB,KAAK;EAChC,KAAK,SAAS,EAAE;EAChB,OAAO;CACT;CACA,KAAK,SAAS,aAAa,EAAE,CAAC,CAAC,QAAQ,YAAY,IAAI,CAAC;CAExD,KAAK,SAAS,aAAa,KAAK,MAAM,EAAE,CAAC;CACzC,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"transaction.js","names":[],"sources":["../../src/core/transaction.ts"],"sourcesContent":["import type { Node as PMNode, Schema } from 'prosemirror-model'\nimport {\n NodeSelection,\n Selection,\n TextSelection,\n type EditorState,\n type Transaction,\n} from 'prosemirror-state'\nimport { blockAround, findBlockById, layoutOf, parentBlock, type BlockInfo } from './blocks'\nimport { blockSelectionRange } from './block-selection'\nimport {\n blockFromNode,\n contentAttrs,\n createContentNode,\n createId,\n nodeFromBlock,\n type Block,\n type BlockProps,\n type InlineContent,\n type PartialBlock,\n type PartialTableRow,\n} from './model'\nimport type { ContentType } from './schema'\nimport { closeHistory } from 'prosemirror-history'\nimport type { EditorView } from 'prosemirror-view'\nimport { originKey } from './editor'\n\n/**\n * Where blocks go: right before or after a block, or among a block's\n * children (`parent: null` is the top level). `index` counts from 0 and\n * defaults to the end.\n */\nexport type BlockPlacement =\n { before: string } | { after: string } | { parent: string | null; index?: number }\n\n/** The parts of a block to change. `props` are merged into the current ones. */\nexport interface BlockPatch {\n type?: ContentType\n props?: BlockProps\n /** Inline content, or plain text. */\n content?: InlineContent[] | string\n rows?: PartialTableRow[]\n /** Replaces all children; `[]` removes them. */\n children?: PartialBlock[]\n}\n\nexport interface EditorTransactionMeta {\n /** `false` keeps the change out of undo, e.g. a fix made by the program. */\n history?: boolean\n /** Who made the change; passed on to the `transaction` event. */\n origin?: string\n}\n\n/** Where a selection is put inside a block: at the start of its text or at the end. */\nexport type BlockEdge = 'start' | 'end'\n\n/**\n * Set on a transaction that is an undo step of its own, for history\n * providers other than the built-in one (collaboration reads it).\n */\nexport const ownStepKey = 'douOwnStep'\n\n/**\n * Set on a transaction that joins the undo step before it however long\n * after it comes, e.g. the frames of a drag on a whiteboard (with\n * `appendedTransaction` for the built-in history).\n */\nexport const joinStepKey = 'douJoinStep'\n\nconst warn = (message: string) => {\n if (process.env.NODE_ENV !== 'production') console.warn(`[@dou-ui/editor] ${message}`)\n}\n\n/**\n * Changes made by blocks and ids, applied together as one undo step. Ids\n * are looked up in the document as it is after the earlier calls.\n */\nexport class EditorTransaction {\n /** The ProseMirror transaction underneath, for anything the methods don't cover. */\n readonly tr: Transaction\n readonly meta: EditorTransactionMeta\n /** `focusBlock` was called: the editor takes focus once the changes are applied. */\n focused = false\n\n constructor(\n /** The state the changes start from. */\n readonly before: EditorState,\n meta: EditorTransactionMeta = {},\n /**\n * Whether the selection was placed by the user or the program. An editor\n * that never had focus has its selection at the start, which is no cursor.\n */\n private readonly hasCursor = true,\n ) {\n this.tr = before.tr\n this.meta = { ...meta }\n }\n\n get changed(): boolean {\n return this.tr.docChanged\n }\n\n setMeta(meta: EditorTransactionMeta): this {\n Object.assign(this.meta, meta)\n return this\n }\n\n /** A block as it is now, or `null`. */\n getBlock(id: string): Block | null {\n const info = findBlockById(this.tr.doc, id)\n return info ? blockFromNode(info.node) : null\n }\n\n /**\n * Insert blocks, by default after the block with the cursor (at the end\n * without one). Returns the new blocks' ids; an id already in the\n * document is replaced with a fresh one.\n */\n insertBlocks(blocks: PartialBlock[], placement?: BlockPlacement): string[] {\n if (!blocks.length) return []\n const tr = this.tr\n const schema = tr.doc.type.schema\n const taken = usedIds(tr.doc)\n const ids: string[] = []\n const nodes = blocks.map((block) => {\n const node = nodeFromBlock(schema, freshIds(block, taken), true)\n ids.push(node.attrs.id as string)\n return node\n })\n const target = placement ?? this.defaultPlacement()\n if (insertNodes(tr, target, nodes) === null) return []\n for (const id of ids) {\n const info = findBlockById(tr.doc, id)\n if (layoutOf(info?.node) === 'row' && info && inColumn(tr.doc, info))\n warn(\n `insertBlocks: columns don't go in a column; the block \"${id}\" is replaced by its columns' blocks`,\n )\n }\n return ids\n }\n\n /** Change a block's type, props, content or children. Returns `false` when it isn't found. */\n updateBlock(id: string, patch: BlockPatch): boolean {\n const tr = this.tr\n const info = findBlockById(tr.doc, id)\n if (!info) {\n warn(`updateBlock: no block with the id \"${id}\"`)\n return false\n }\n const schema = tr.doc.type.schema\n // check everything before changing anything: a refused patch changes nothing\n const typeName = patch.type ?? info.content.type.name\n const nodeType = schema.nodes[typeName]\n if (!nodeType?.isInGroup('blockContent')) {\n warn(`updateBlock: unknown block type \"${typeName}\"`)\n return false\n }\n const rowsSpec = !!nodeType.spec.rows\n if (patch.rows !== undefined && !rowsSpec) {\n warn(`updateBlock: a \"${typeName}\" block has no rows`)\n return false\n }\n if (patch.content !== undefined && (rowsSpec || !nodeType.inlineContent)) {\n warn(`updateBlock: a \"${typeName}\" block has no text content`)\n return false\n }\n if (patch.children) replaceChildren(tr, info, patch.children)\n if (\n patch.type === undefined &&\n patch.props === undefined &&\n patch.content === undefined &&\n patch.rows === undefined\n )\n return true\n const current = findBlockById(tr.doc, id)!\n const content = current.content\n const props = { ...content.attrs, ...patch.props }\n const keepsContent = patch.content === undefined && patch.rows === undefined\n // keep the text node for node when it can stay: collaborators typing in it keep their place\n if (keepsContent && nodeType === content.type) {\n tr.setNodeMarkup(current.contentPos, undefined, contentAttrs(nodeType, props))\n return true\n }\n if (keepsContent && nodeType.isTextblock && content.isTextblock) {\n const from = current.contentPos\n tr.setBlockType(\n from + 1,\n from + content.nodeSize - 1,\n nodeType,\n contentAttrs(nodeType, props),\n )\n return true\n }\n const block = blockFromNode(current.node)\n const next = createContentNode(\n schema,\n typeName,\n props,\n patch.content ?? block.content,\n patch.rows ?? block.rows,\n )\n tr.replaceWith(current.contentPos, current.contentPos + content.nodeSize, next)\n return true\n }\n\n /** Remove blocks with their children. The document always keeps one block. */\n removeBlocks(ids: string[]): boolean {\n const infos = outermost(this.tr.doc, ids, 'removeBlocks')\n if (!infos.length) return false\n deleteInfos(this.tr, infos)\n const tr = this.tr\n if (tr.doc.content.size === 0) tr.insert(0, emptyBlock(tr.doc.type.schema))\n return true\n }\n\n /**\n * Move blocks, in the order given, to `placement`. Fails when it is\n * inside one of them.\n */\n moveBlocks(ids: string[], placement: BlockPlacement): boolean {\n const tr = this.tr\n const infos = outermost(tr.doc, ids, 'moveBlocks')\n if (!infos.length) return false\n const anchor =\n 'before' in placement\n ? placement.before\n : 'after' in placement\n ? placement.after\n : placement.parent\n if (\n anchor !== null &&\n infos.some((info) => info.node.attrs.id === anchor || contains(info, tr.doc, anchor))\n ) {\n warn('moveBlocks: blocks cannot be moved next to or into themselves')\n return false\n }\n // insert the moved blocks first, then delete the originals: the document never empties\n const nodes = infos.map((info) => info.node)\n // a selection inside a moved block goes along with it\n const { anchor: anchorPos, head } = tr.selection\n const nodeSelected = tr.selection instanceof NodeSelection\n const carried = infos.findIndex(\n (info) =>\n anchorPos > info.pos &&\n anchorPos < info.pos + info.node.nodeSize &&\n head > info.pos &&\n head < info.pos + info.node.nodeSize,\n )\n const base = tr.steps.length\n const at = insertNodes(tr, placement, nodes)\n if (at === null) return false\n const inserted = tr.steps.length\n deleteInfos(tr, infos, base)\n if (carried >= 0) {\n const info = infos[carried]!\n let start = at\n for (let i = 0; i < carried; i++) start += nodes[i]!.nodeSize\n const moved = tr.mapping.slice(inserted).map(start, 1)\n const shift = (pos: number) => moved + (pos - info.pos)\n tr.setSelection(\n nodeSelected\n ? NodeSelection.create(tr.doc, shift(anchorPos))\n : TextSelection.create(tr.doc, shift(anchorPos), shift(head)),\n )\n }\n return true\n }\n\n /** Put the cursor at the start or end of a block's text (or select a block without text). */\n focusBlock(id: string, edge: BlockEdge = 'end'): boolean {\n const tr = this.tr\n const info = findBlockById(tr.doc, id)\n if (!info) {\n warn(`focusBlock: no block with the id \"${id}\"`)\n return false\n }\n tr.setSelection(selectionIn(tr, info, edge)).scrollIntoView()\n this.focused = true\n return true\n }\n\n /** After the selection's block, or at the end. */\n private defaultPlacement(): BlockPlacement {\n if (!this.hasCursor && !this.tr.selectionSet) return { parent: null }\n // selected blocks are only known before the first change\n const range = this.tr.docChanged ? null : blockSelectionRange(this.before)\n const id = range\n ? (range.parent.child(range.to).attrs.id as string)\n : (blockAround(this.tr.selection.$to)?.node.attrs.id as string | undefined)\n return id ? { after: id } : { parent: null }\n }\n}\n\nfunction emptyBlock(schema: Schema): PMNode {\n return schema.nodes.block!.create({ id: createId() }, schema.nodes.paragraph!.create())\n}\n\nfunction usedIds(doc: PMNode): Set<string> {\n const ids = new Set<string>()\n doc.descendants((node) => {\n if (node.type.name === 'block') ids.add(node.attrs.id as string)\n return node.type.name === 'block' || node.type.name === 'blockGroup'\n })\n return ids\n}\n\n/** The block with ids that are free, recursively. */\nfunction freshIds(block: PartialBlock, taken: Set<string>): PartialBlock {\n let id = block.id\n if (!id || taken.has(id)) id = createId()\n taken.add(id)\n return {\n ...block,\n id,\n children: block.children?.map((child) => freshIds(child, taken)),\n }\n}\n\n/** Whether a block with `id` sits inside `info`. */\nfunction contains(info: BlockInfo, doc: PMNode, id: string): boolean {\n const found = findBlockById(doc, id)\n return !!found && found.pos > info.pos && found.pos < info.pos + info.node.nodeSize\n}\n\n/** The blocks with these ids, without those inside another one of them, in the order given. */\nfunction outermost(doc: PMNode, ids: string[], method: string): BlockInfo[] {\n const infos: BlockInfo[] = []\n const seen = new Set<string>()\n for (const id of ids) {\n if (seen.has(id)) continue\n seen.add(id)\n const info = findBlockById(doc, id)\n if (info) infos.push(info)\n else warn(`${method}: no block with the id \"${id}\"`)\n }\n return infos.filter(\n (info) =>\n !infos.some(\n (other) =>\n other !== info && info.pos > other.pos && info.pos < other.pos + other.node.nodeSize,\n ),\n )\n}\n\n/**\n * Delete blocks found in the document as it was after step `base`; a\n * group left without children goes too.\n */\nfunction deleteInfos(tr: Transaction, infos: BlockInfo[], base = tr.steps.length) {\n // last first, so the earlier positions stay valid\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a copy\n const sorted = [...infos].sort((a, b) => b.pos - a.pos)\n for (const info of sorted) {\n // a block moved right in front of this one pushes it on (`1`)\n const from = tr.mapping.slice(base).map(info.pos, 1)\n const to = from + info.node.nodeSize\n const $from = tr.doc.resolve(from)\n if ($from.parent.type.name === 'blockGroup' && $from.parent.childCount === 1)\n tr.delete($from.before(), $from.after())\n else tr.delete(from, to)\n }\n}\n\n/** Insert block nodes at a placement. Returns `false` when the placement can't be found. */\nfunction insertNodes(tr: Transaction, placement: BlockPlacement, nodes: PMNode[]): number | null {\n const schema = tr.doc.type.schema\n let at: number\n if ('before' in placement || 'after' in placement) {\n const id = 'before' in placement ? placement.before : placement.after\n const info = findBlockById(tr.doc, id)\n if (!info) {\n warn(`no block with the id \"${id}\" to insert next to`)\n return null\n }\n at = 'before' in placement ? info.pos : info.pos + info.node.nodeSize\n } else if (placement.parent === null) {\n at = childPos(0, tr.doc, placement.index)\n } else {\n const info = findBlockById(tr.doc, placement.parent)\n if (!info) {\n warn(`no block with the id \"${placement.parent}\" to insert into`)\n return null\n }\n if (!info.group) {\n at = info.contentPos + info.content.nodeSize\n tr.insert(at, schema.nodes.blockGroup!.create(null, nodes))\n return at + 1\n }\n at = childPos(info.contentPos + info.content.nodeSize + 1, info.group, placement.index)\n }\n tr.insert(at, nodes)\n return at\n}\n\n/** The position before the child at `index` of a container whose content starts at `start`. */\nfunction childPos(start: number, container: PMNode, index = container.childCount) {\n const at = Math.max(0, Math.min(index, container.childCount))\n let pos = start\n for (let i = 0; i < at; i++) pos += container.child(i).nodeSize\n return pos\n}\n\n/** Whether a block sits in a column, at any depth. */\nfunction inColumn(doc: PMNode, info: BlockInfo): boolean {\n for (let parent = parentBlock(doc, info); parent; parent = parentBlock(doc, parent))\n if (layoutOf(parent.node) === 'column') return true\n return false\n}\n\nfunction replaceChildren(tr: Transaction, info: BlockInfo, children: PartialBlock[]) {\n const schema = tr.doc.type.schema\n const groupPos = info.contentPos + info.content.nodeSize\n const taken = usedIds(tr.doc)\n // the old children's ids are free again\n info.group?.descendants((node) => {\n if (node.type.name === 'block') taken.delete(node.attrs.id as string)\n })\n const nodes = children.map((child) => nodeFromBlock(schema, freshIds(child, taken), true))\n const group = nodes.length ? schema.nodes.blockGroup!.create(null, nodes) : null\n const end = info.group ? groupPos + info.group.nodeSize : groupPos\n if (group) tr.replaceWith(groupPos, end, group)\n else if (info.group) tr.delete(groupPos, end)\n}\n\n/** A cursor at the start or end of a block's text; a node selection for a block without text. */\nexport function selectionIn(tr: Transaction, info: BlockInfo, edge: BlockEdge): Selection {\n const content = info.content\n const doc = tr.doc\n if (content.isTextblock) {\n const pos = edge === 'start' ? info.contentPos + 1 : info.contentPos + content.nodeSize - 1\n return TextSelection.create(doc, pos)\n }\n if (content.isAtom) return NodeSelection.create(doc, info.contentPos)\n // a table: the first or last cell's text\n const inside = edge === 'start' ? info.contentPos + 1 : info.contentPos + content.nodeSize - 1\n return Selection.near(doc.resolve(inside), edge === 'start' ? 1 : -1)\n}\n\n/**\n * Apply a transaction made with `transact`: one undo step of its own,\n * unless `history` is `false`. Returns whether anything happened.\n */\nexport function applyEditorTransaction(view: EditorView, transaction: EditorTransaction): boolean {\n const { tr, meta } = transaction\n if (!tr.docChanged && !tr.selectionSet) return false\n if (meta.origin !== undefined) tr.setMeta(originKey, meta.origin)\n if (!tr.docChanged) {\n view.dispatch(tr)\n return true\n }\n if (meta.history === false) {\n tr.setMeta('addToHistory', false)\n view.dispatch(tr)\n return true\n }\n view.dispatch(closeHistory(tr).setMeta(ownStepKey, true))\n // and typing right after it starts another step\n view.dispatch(closeHistory(view.state.tr))\n return true\n}\n"],"mappings":";;;;;;;;;;;AA4DA,IAAa,aAAa;;;;;;AAO1B,IAAa,cAAc;AAE3B,IAAM,QAAQ,YAAoB;CAChC,IAAA,QAAA,IAAA,aAA6B,cAAc,QAAQ,KAAK,oBAAoB,SAAS;AACvF;;;;;AAMA,IAAa,oBAAb,MAA+B;CASlB;CAMQ;;CAbnB;CACA;;CAEA,UAAU;CAEV,YAEE,QACA,OAA8B,CAAC,GAK/B,YAA6B,MAC7B;EAPS,KAAA,SAAA;EAMQ,KAAA,YAAA;EAEjB,KAAK,KAAK,OAAO;EACjB,KAAK,OAAO,EAAE,GAAG,KAAK;CACxB;CAEA,IAAI,UAAmB;EACrB,OAAO,KAAK,GAAG;CACjB;CAEA,QAAQ,MAAmC;EACzC,OAAO,OAAO,KAAK,MAAM,IAAI;EAC7B,OAAO;CACT;;CAGA,SAAS,IAA0B;EACjC,MAAM,OAAO,cAAc,KAAK,GAAG,KAAK,EAAE;EAC1C,OAAO,OAAO,cAAc,KAAK,IAAI,IAAI;CAC3C;;;;;;CAOA,aAAa,QAAwB,WAAsC;EACzE,IAAI,CAAC,OAAO,QAAQ,OAAO,CAAC;EAC5B,MAAM,KAAK,KAAK;EAChB,MAAM,SAAS,GAAG,IAAI,KAAK;EAC3B,MAAM,QAAQ,QAAQ,GAAG,GAAG;EAC5B,MAAM,MAAgB,CAAC;EACvB,MAAM,QAAQ,OAAO,KAAK,UAAU;GAClC,MAAM,OAAO,cA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
71
71
|
},
|
|
72
72
|
selected: false,
|
|
73
73
|
editable: view.editable,
|
|
74
|
-
updateProps(props) {
|
|
74
|
+
updateProps(props, options) {
|
|
75
75
|
const pos = getPos();
|
|
76
76
|
if (pos === void 0) return;
|
|
77
77
|
const current = view.state.doc.nodeAt(pos);
|
|
78
78
|
if (!current) return;
|
|
79
|
-
view.
|
|
79
|
+
const tr = view.state.tr.setNodeMarkup(pos, void 0, {
|
|
80
80
|
...current.attrs,
|
|
81
81
|
...props
|
|
82
|
-
})
|
|
82
|
+
});
|
|
83
|
+
if (options?.history === false) tr.setMeta("addToHistory", false);
|
|
84
|
+
view.dispatch(tr);
|
|
83
85
|
}
|
|
84
86
|
});
|
|
85
87
|
const Root = defineComponent({ setup() {
|
|
@@ -114,7 +116,8 @@ function vueNodeView(component, appContext, provides = []) {
|
|
|
114
116
|
stopEvent: (event) => {
|
|
115
117
|
const target = event.target;
|
|
116
118
|
if (contentElement?.contains(target)) return false;
|
|
117
|
-
|
|
119
|
+
const control = target.closest?.("input, textarea, select, button, a, [contenteditable=\"true\"], [data-editor-control]");
|
|
120
|
+
return !!control && control !== dom && dom.contains(control);
|
|
118
121
|
},
|
|
119
122
|
ignoreMutation: (mutation) => !contentElement || !contentElement.contains(mutation.target),
|
|
120
123
|
destroy() {
|
|
@@ -143,6 +146,7 @@ function defineBlock(options) {
|
|
|
143
146
|
},
|
|
144
147
|
continues: options.continues,
|
|
145
148
|
component: options.component,
|
|
149
|
+
comments: options.comments,
|
|
146
150
|
parseDOM: [{
|
|
147
151
|
tag: `div[data-content-type="${type}"]`,
|
|
148
152
|
getAttrs: (dom) => readDataAttrs(dom, names)
|
package/dist/define-block.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define-block.js","names":[],"sources":["../src/define-block.ts"],"sourcesContent":["import type { NodeSpec } from 'prosemirror-model'\nimport type { NodeView, NodeViewConstructor } from 'prosemirror-view'\nimport {\n defineComponent,\n h,\n inject,\n onMounted,\n provide,\n render,\n shallowReactive,\n shallowRef,\n type AppContext,\n type Component,\n type InjectionKey,\n type PropType,\n} from 'vue'\nimport type { BlockOption, EditorExtension, Label, MountComponent } from './core/extension'\nimport type { BlockProps } from './core/model'\n\n/** What a block's Vue component receives. */\nexport interface BlockViewProps {\n /** The block's id, type and current props. */\n block: { id: string; type: string; props: BlockProps }\n /** Change props; the change goes into the document, the undo history and collaboration. */\n updateProps: (props: BlockProps) => void\n /** The block is selected as a whole (a block without text was clicked). */\n selected: boolean\n editable: boolean\n}\n\nexport interface DefineBlockOptions {\n type: string\n /** The props and their defaults. They are stored in the document, as `Block.props`. */\n props?: Record<string, unknown>\n /** `inline` holds formatted text; `none` has no text (an image, an embed). Defaults to `inline`. */\n content?: 'inline' | 'none'\n /** Renders the block. Put `<EditorContent />` where the text goes. */\n component?: Component\n /** `Enter` at the end continues with the same type, like a list. */\n continues?: boolean\n /** Entries for the slash menu and the “turn into” menus; one is made from `menu` when given. */\n menu?: Omit<BlockOption, 'key' | 'type'> & { key?: string }\n /** Override the ProseMirror spec, e.g. `parseDOM` for pasting HTML from elsewhere. */\n spec?: Partial<NodeSpec>\n}\n\nconst contentKey: InjectionKey<HTMLElement | null> = Symbol('DouEditorContent')\n\n/** Where a block component's text goes. */\nexport const EditorContent = defineComponent({\n name: 'DouEditorContent',\n props: { as: { type: String as PropType<string>, default: 'div' } },\n setup(props) {\n const content = inject(contentKey, null)\n const host = shallowRef<HTMLElement | null>(null)\n onMounted(() => {\n if (content && host.value) host.value.append(content)\n })\n return () => h(props.as, { ref: host, class: 'dou-editor__text' })\n },\n})\n\n/** Store props as `data-prop-*` attributes, so copy and paste keep them. */\nconst dataAttrs = (props: Record<string, unknown>) =>\n Object.fromEntries(\n Object.entries(props).map(([name, value]) => [`data-prop-${name}`, JSON.stringify(value)]),\n )\n\nfunction readDataAttrs(dom: HTMLElement, names: string[]) {\n const attrs: Record<string, unknown> = {}\n for (const name of names) {\n const raw = dom.getAttribute(`data-prop-${name}`)\n if (raw === null) continue\n try {\n attrs[name] = JSON.parse(raw)\n } catch {\n // ignore attributes that are not ours\n }\n }\n return attrs\n}\n\n/** Renders components inside an app, with values provided to them. */\nexport function componentMounter(\n appContext: AppContext | null,\n provides: [InjectionKey<unknown>, unknown][] = [],\n): MountComponent {\n return (component, props, element) => {\n const Root = defineComponent({\n setup() {\n for (const [key, value] of provides) provide(key, value)\n return () => h(component, { ...props })\n },\n })\n const vnode = h(Root)\n vnode.appContext = appContext\n render(vnode, element)\n return () => render(null, element)\n }\n}\n\n/**\n * A node view that renders a Vue component. Everything the component shows\n * besides the text is outside the editable content, so its buttons and\n * inputs work as usual.\n */\nexport function vueNodeView(\n component: Component,\n appContext: AppContext | null,\n provides: [InjectionKey<unknown>, unknown][] = [],\n): NodeViewConstructor {\n return (node, view, getPos) => {\n // the id lives on the block around the content node\n const idOf = () => {\n const pos = getPos()\n if (pos === undefined) return ''\n return (view.state.doc.resolve(pos).parent.attrs.id as string | null) ?? ''\n }\n const type = node.type.name\n const dom = document.createElement('div')\n dom.className = `dou-editor__content dou-editor__content--${type} dou-editor__content--custom`\n dom.dataset.contentType = type\n const contentElement = node.isTextblock ? document.createElement('div') : null\n const state = shallowReactive<BlockViewProps>({\n block: { id: idOf(), type, props: { ...node.attrs } },\n selected: false,\n editable: view.editable,\n updateProps(props) {\n const pos = getPos()\n if (pos === undefined) return\n const current = view.state.doc.nodeAt(pos)\n if (!current) return\n view.dispatch(view.state.tr.setNodeMarkup(pos, undefined, { ...current.attrs, ...props }))\n },\n })\n const Root = defineComponent({\n setup() {\n provide(contentKey, contentElement)\n for (const [key, value] of provides) provide(key, value)\n return () => h(component, { ...state })\n },\n })\n const vnode = h(Root)\n vnode.appContext = appContext\n render(vnode, dom)\n let current = node\n const nodeView: NodeView = {\n dom,\n contentDOM: contentElement,\n update(next) {\n if (next.type !== current.type) return false\n current = next\n state.block = { id: idOf(), type, props: { ...next.attrs } }\n state.editable = view.editable\n return true\n },\n selectNode() {\n state.selected = true\n },\n deselectNode() {\n state.selected = false\n },\n // the component's own controls (and anything marked `data-editor-control`)\n // handle their events; the editor gets the rest, so a click on a block\n // without text still selects it\n stopEvent: (event) => {\n const target = event.target as HTMLElement\n if (contentElement?.contains(target)) return false\n return !!target.closest?.(\n 'input, textarea, select, button, a, [contenteditable=\"true\"], [data-editor-control]',\n )\n },\n ignoreMutation: (mutation) => !contentElement || !contentElement.contains(mutation.target),\n destroy() {\n render(null, dom)\n },\n }\n return nodeView\n }\n}\n\n/**\n * Declare a block type rendered by a Vue component (or by plain DOM), with\n * its props stored in the document. Returns an extension for `extensions`.\n */\nexport function defineBlock(options: DefineBlockOptions): EditorExtension {\n const { type } = options\n const props = options.props ?? {}\n const names = Object.keys(props)\n const inline = (options.content ?? 'inline') === 'inline'\n const spec: NodeSpec = {\n attrs: Object.fromEntries(names.map((name) => [name, { default: props[name] }])),\n ...(inline ? { content: 'inline*', defining: true } : { atom: true, selectable: true }),\n continues: options.continues,\n component: options.component,\n parseDOM: [\n {\n tag: `div[data-content-type=\"${type}\"]`,\n getAttrs: (dom) => readDataAttrs(dom as HTMLElement, names),\n },\n ],\n toDOM: (node) => {\n const attrs = {\n class: `dou-editor__content dou-editor__content--${type}`,\n 'data-content-type': type,\n ...dataAttrs(node.attrs),\n }\n return inline ? ['div', attrs, 0] : ['div', attrs]\n },\n ...options.spec,\n }\n const menu = options.menu\n return {\n name: `block:${type}`,\n blocks: { [type]: spec },\n blockOptions: menu ? [{ ...menu, key: menu.key ?? type, type }] : [],\n }\n}\n\nexport type { Label }\n"],"mappings":";;AA8CA,IAAM,aAA+C,OAAO,kBAAkB;;AAG9E,IAAa,gBAAgB,gBAAgB;CAC3C,MAAM;CACN,OAAO,EAAE,IAAI;EAAE,MAAM;EAA4B,SAAS;CAAM,EAAE;CAClE,MAAM,OAAO;EACX,MAAM,UAAU,OAAO,YAAY,IAAI;EACvC,MAAM,OAAO,WAA+B,IAAI;EAChD,gBAAgB;GACd,IAAI,WAAW,KA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,eAAe,SAAS,SAAS,MAAM;GACzF,UAAU;IACR,OAAO,MAAM,GAAG;GAClB;EAEK;CACT;AACF;;;;;AAMA,SAAgB,YAAY,SAA8C;CACxE,MAAM,EAAE,SAAS;CACjB,MAAM,QAAQ,QAAQ,SAAS,CAAC;CAChC,MAAM,QAAQ,OAAO,KAAK,KAAK;CAC/B,MAAM,UAAU,QAAQ,WAAW,cAAc;CACjD,MAAM,OAAiB;EACrB,OAAO,OAAO,YAAY,MAAM,KAAK,SAAS,CAAC,MAAM,EAAE,SAAS,MAAM,MAAM,CAAC,CAAC,CAAC;EAC/E,GAAI,SAAS;GAAE,SAAS;GAAW,UAAU;EAAK,IAAI;GAAE,MAAM;GAAM,YAAY;EAAK;EACrF,WAAW,QAAQ;EACnB,WAAW,QAAQ;EACnB,UAAU,CACR;GACE,KAAK,0BAA0B,KAAK;GACpC,WAAW,QAAQ,cAAc,KAAoB,KAAK;EAC5D,CACF;EACA,QAAQ,SAAS;GACf,MAAM,QAAQ;IACZ,OAAO,4CAA4C;IACnD,qBAAqB;IACrB,GAAG,UAAU,KAAK,KAAK;GACzB;GACA,OAAO,SAAS;IAAC;IAAO;IAAO;GAAC,IAAI,CAAC,OAAO,KAAK;EACnD;EACA,GAAG,QAAQ;CACb;CACA,MAAM,OAAO,QAAQ;CACrB,OAAO;EACL,MAAM,SAAS;EACf,QAAQ,GAAG,OAAO,KAAK;EACvB,cAAc,OAAO,CAAC;GAAE,GAAG;GAAM,KAAK,KAAK,OAAO;GAAM;EAAK,CAAC,IAAI,CAAC;CACrE;AACF"}
|
|
1
|
+
{"version":3,"file":"define-block.js","names":[],"sources":["../src/define-block.ts"],"sourcesContent":["import type { NodeSpec } from 'prosemirror-model'\nimport type { NodeView, NodeViewConstructor } from 'prosemirror-view'\nimport {\n defineComponent,\n h,\n inject,\n onMounted,\n provide,\n render,\n shallowReactive,\n shallowRef,\n type AppContext,\n type Component,\n type InjectionKey,\n type PropType,\n} from 'vue'\nimport type { BlockCommentsSpec } from './core/comments'\nimport type { BlockOption, EditorExtension, Label, MountComponent } from './core/extension'\nimport type { BlockProps } from './core/model'\n\n/** What a block's Vue component receives. */\nexport interface BlockViewProps {\n /** The block's id, type and current props. */\n block: { id: string; type: string; props: BlockProps }\n /**\n * Change props; the change goes into the document, the undo history and\n * collaboration. `history: false` keeps it out of the undo history, e.g.\n * for the id of a comment thread put inside the block.\n */\n updateProps: (props: BlockProps, options?: { history?: boolean }) => void\n /** The block is selected as a whole (a block without text was clicked). */\n selected: boolean\n editable: boolean\n}\n\nexport interface DefineBlockOptions<Target = unknown> {\n type: string\n /** The props and their defaults. They are stored in the document, as `Block.props`. */\n props?: Record<string, unknown>\n /** `inline` holds formatted text; `none` has no text (an image, an embed). Defaults to `inline`. */\n content?: 'inline' | 'none'\n /** Renders the block. Put `<EditorContent />` where the text goes. */\n component?: Component\n /** `Enter` at the end continues with the same type, like a list. */\n continues?: boolean\n /**\n * Comment threads on what is inside the block, kept in its props: how\n * to find, put back and strip them. See `BlockCommentsSpec`.\n */\n comments?: BlockCommentsSpec<Target>\n /** Entries for the slash menu and the “turn into” menus; one is made from `menu` when given. */\n menu?: Omit<BlockOption, 'key' | 'type'> & { key?: string }\n /** Override the ProseMirror spec, e.g. `parseDOM` for pasting HTML from elsewhere. */\n spec?: Partial<NodeSpec>\n}\n\nconst contentKey: InjectionKey<HTMLElement | null> = Symbol('DouEditorContent')\n\n/** Where a block component's text goes. */\nexport const EditorContent = defineComponent({\n name: 'DouEditorContent',\n props: { as: { type: String as PropType<string>, default: 'div' } },\n setup(props) {\n const content = inject(contentKey, null)\n const host = shallowRef<HTMLElement | null>(null)\n onMounted(() => {\n if (content && host.value) host.value.append(content)\n })\n return () => h(props.as, { ref: host, class: 'dou-editor__text' })\n },\n})\n\n/** Store props as `data-prop-*` attributes, so copy and paste keep them. */\nconst dataAttrs = (props: Record<string, unknown>) =>\n Object.fromEntries(\n Object.entries(props).map(([name, value]) => [`data-prop-${name}`, JSON.stringify(value)]),\n )\n\nfunction readDataAttrs(dom: HTMLElement, names: string[]) {\n const attrs: Record<string, unknown> = {}\n for (const name of names) {\n const raw = dom.getAttribute(`data-prop-${name}`)\n if (raw === null) continue\n try {\n attrs[name] = JSON.parse(raw)\n } catch {\n // ignore attributes that are not ours\n }\n }\n return attrs\n}\n\n/** Renders components inside an app, with values provided to them. */\nexport function componentMounter(\n appContext: AppContext | null,\n provides: [InjectionKey<unknown>, unknown][] = [],\n): MountComponent {\n return (component, props, element) => {\n const Root = defineComponent({\n setup() {\n for (const [key, value] of provides) provide(key, value)\n return () => h(component, { ...props })\n },\n })\n const vnode = h(Root)\n vnode.appContext = appContext\n render(vnode, element)\n return () => render(null, element)\n }\n}\n\n/**\n * A node view that renders a Vue component. Everything the component shows\n * besides the text is outside the editable content, so its buttons and\n * inputs work as usual.\n */\nexport function vueNodeView(\n component: Component,\n appContext: AppContext | null,\n provides: [InjectionKey<unknown>, unknown][] = [],\n): NodeViewConstructor {\n return (node, view, getPos) => {\n // the id lives on the block around the content node\n const idOf = () => {\n const pos = getPos()\n if (pos === undefined) return ''\n return (view.state.doc.resolve(pos).parent.attrs.id as string | null) ?? ''\n }\n const type = node.type.name\n const dom = document.createElement('div')\n dom.className = `dou-editor__content dou-editor__content--${type} dou-editor__content--custom`\n dom.dataset.contentType = type\n const contentElement = node.isTextblock ? document.createElement('div') : null\n const state = shallowReactive<BlockViewProps>({\n block: { id: idOf(), type, props: { ...node.attrs } },\n selected: false,\n editable: view.editable,\n updateProps(props, options) {\n const pos = getPos()\n if (pos === undefined) return\n const current = view.state.doc.nodeAt(pos)\n if (!current) return\n const tr = view.state.tr.setNodeMarkup(pos, undefined, { ...current.attrs, ...props })\n if (options?.history === false) tr.setMeta('addToHistory', false)\n view.dispatch(tr)\n },\n })\n const Root = defineComponent({\n setup() {\n provide(contentKey, contentElement)\n for (const [key, value] of provides) provide(key, value)\n return () => h(component, { ...state })\n },\n })\n const vnode = h(Root)\n vnode.appContext = appContext\n render(vnode, dom)\n let current = node\n const nodeView: NodeView = {\n dom,\n contentDOM: contentElement,\n update(next) {\n if (next.type !== current.type) return false\n current = next\n state.block = { id: idOf(), type, props: { ...next.attrs } }\n state.editable = view.editable\n return true\n },\n selectNode() {\n state.selected = true\n },\n deselectNode() {\n state.selected = false\n },\n // the component's own controls (and anything marked `data-editor-control`)\n // handle their events; the editor gets the rest, so a click on a block\n // without text still selects it\n stopEvent: (event) => {\n const target = event.target as HTMLElement\n if (contentElement?.contains(target)) return false\n const control = target.closest?.(\n 'input, textarea, select, button, a, [contenteditable=\"true\"], [data-editor-control]',\n )\n // only inside the block: the editor around it is contenteditable too\n return !!control && control !== dom && dom.contains(control)\n },\n ignoreMutation: (mutation) => !contentElement || !contentElement.contains(mutation.target),\n destroy() {\n render(null, dom)\n },\n }\n return nodeView\n }\n}\n\n/**\n * Declare a block type rendered by a Vue component (or by plain DOM), with\n * its props stored in the document. Returns an extension for `extensions`.\n */\nexport function defineBlock<Target = unknown>(\n options: DefineBlockOptions<Target>,\n): EditorExtension {\n const { type } = options\n const props = options.props ?? {}\n const names = Object.keys(props)\n const inline = (options.content ?? 'inline') === 'inline'\n const spec: NodeSpec = {\n attrs: Object.fromEntries(names.map((name) => [name, { default: props[name] }])),\n ...(inline ? { content: 'inline*', defining: true } : { atom: true, selectable: true }),\n continues: options.continues,\n component: options.component,\n comments: options.comments,\n parseDOM: [\n {\n tag: `div[data-content-type=\"${type}\"]`,\n getAttrs: (dom) => readDataAttrs(dom as HTMLElement, names),\n },\n ],\n toDOM: (node) => {\n const attrs = {\n class: `dou-editor__content dou-editor__content--${type}`,\n 'data-content-type': type,\n ...dataAttrs(node.attrs),\n }\n return inline ? ['div', attrs, 0] : ['div', attrs]\n },\n ...options.spec,\n }\n const menu = options.menu\n return {\n name: `block:${type}`,\n blocks: { [type]: spec },\n blockOptions: menu ? [{ ...menu, key: menu.key ?? type, type }] : [],\n }\n}\n\nexport type { Label }\n"],"mappings":";;AAwDA,IAAM,aAA+C,OAAO,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AQ,GAAG,OAAO,KAAK;EACvB,cAAc,OAAO,CAAC;GAAE,GAAG;GAAM,KAAK,KAAK,OAAO;GAAM;EAAK,CAAC,IAAI,CAAC;CACrE;AACF"}
|
package/dist/document.js
CHANGED
|
@@ -29,7 +29,10 @@ function shapeProblems(value, lists) {
|
|
|
29
29
|
* The problems of an editor document, before it is saved or shown: an
|
|
30
30
|
* unknown version, blocks or table rows sharing an id, and block types,
|
|
31
31
|
* marks and inline nodes the extensions don't define, which the editor
|
|
32
|
-
* would show as a paragraph or leave out
|
|
32
|
+
* would show as a paragraph or leave out, and columns the editor would
|
|
33
|
+
* change on the next edit (a column outside a set of columns, a set with
|
|
34
|
+
* fewer than two, columns in a column…), and props a block type says it can't use
|
|
35
|
+
* (its spec's `checkProps`, e.g. a whiteboard's board that isn't a flow).
|
|
33
36
|
*/
|
|
34
37
|
function checkDocument(document, options = {}) {
|
|
35
38
|
const shape = shapeProblems(document, ["blocks"]);
|
|
@@ -43,14 +46,66 @@ function checkDocument(document, options = {}) {
|
|
|
43
46
|
});
|
|
44
47
|
const { schema } = kitOf(options.extensions ?? (defaultKit ??= [editorKit()]));
|
|
45
48
|
const ids = /* @__PURE__ */ new Set();
|
|
46
|
-
const walk = (blocks, at) => blocks.forEach((block, i) => {
|
|
49
|
+
const walk = (blocks, at, around) => blocks.forEach((block, i) => {
|
|
47
50
|
const path = `${at}[${i}]`;
|
|
48
51
|
checkBlock(block, path, schema, ids, problems);
|
|
49
|
-
|
|
52
|
+
const layout = layoutOfType(schema, block.type);
|
|
53
|
+
checkLayout(block, layout, path, around, schema, problems);
|
|
54
|
+
checkProps(block, path, schema, problems);
|
|
55
|
+
if (block.children) walk(block.children, `${path}.children`, {
|
|
56
|
+
layout,
|
|
57
|
+
inColumn: around.inColumn || layout === "column"
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
walk(document.blocks, "blocks", {
|
|
61
|
+
layout: void 0,
|
|
62
|
+
inColumn: false
|
|
50
63
|
});
|
|
51
|
-
walk(document.blocks, "blocks");
|
|
52
64
|
return problems;
|
|
53
65
|
}
|
|
66
|
+
/**
|
|
67
|
+
* Props a block type can't use, as its spec's `checkProps` tells: a
|
|
68
|
+
* whiteboard whose `board` isn't a flow document, a height that isn't a
|
|
69
|
+
* number… Each is `{ prop, message }`.
|
|
70
|
+
*/
|
|
71
|
+
function checkProps(block, path, schema, problems) {
|
|
72
|
+
const type = block.type ?? "paragraph";
|
|
73
|
+
const check = schema.nodes[type]?.spec.checkProps;
|
|
74
|
+
if (!check || !block.props) return;
|
|
75
|
+
for (const { prop, message } of check(block.props)) problems.push({
|
|
76
|
+
code: "invalid-props",
|
|
77
|
+
blockId: block.id,
|
|
78
|
+
path: `${path}.props.${prop}`,
|
|
79
|
+
text: type,
|
|
80
|
+
message
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
var layoutOfType = (schema, type) => schema.nodes[type ?? "paragraph"]?.spec.layout;
|
|
84
|
+
/** Columns as the editor keeps them; anything else it changes on the next edit. */
|
|
85
|
+
function checkLayout(block, layout, path, around, schema, problems) {
|
|
86
|
+
const type = block.type ?? "paragraph";
|
|
87
|
+
const report = (message, at = path) => problems.push({
|
|
88
|
+
code: "invalid-columns",
|
|
89
|
+
blockId: block.id,
|
|
90
|
+
path: at,
|
|
91
|
+
text: type,
|
|
92
|
+
message
|
|
93
|
+
});
|
|
94
|
+
const children = block.children ?? [];
|
|
95
|
+
if (around.layout === "row" && layout !== "column") report(`A "${type}" block directly in a set of columns would move into the column before it`);
|
|
96
|
+
if (layout === "column") {
|
|
97
|
+
if (around.layout !== "row") report("A column outside a set of columns would be replaced by its blocks");
|
|
98
|
+
if (!children.length) report("An empty column would be removed");
|
|
99
|
+
const width = block.props?.width;
|
|
100
|
+
if (width != null && !(typeof width === "number" && width > 0)) report(`The column width ${JSON.stringify(width)} is not a positive number; it would be ignored`, `${path}.props.width`);
|
|
101
|
+
}
|
|
102
|
+
if (layout === "row") {
|
|
103
|
+
if (around.inColumn) report("Columns inside a column would be replaced by their blocks");
|
|
104
|
+
const columns = children.filter((child) => layoutOfType(schema, child.type) === "column");
|
|
105
|
+
if (columns.length < 2) report(`A set of ${columns.length} column(s) would be replaced by its blocks`);
|
|
106
|
+
}
|
|
107
|
+
if (layout && Array.isArray(block.content) && block.content.length) report(`A "${type}" block has no text of its own; its content would be left out`, `${path}.content`);
|
|
108
|
+
}
|
|
54
109
|
function checkBlock(block, path, schema, ids, problems) {
|
|
55
110
|
const blockId = block.id;
|
|
56
111
|
if (blockId !== void 0) {
|
package/dist/document.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"document.js","names":[],"sources":["../src/document.ts"],"sourcesContent":["import type { Schema } from 'prosemirror-model'\nimport { kitOf, type EditorExtensionList } from './core/convert'\nimport type { Block, EditorDocument, PartialBlock, PartialTableRow } from './core/model'\nimport { editorKit } from './extensions/editor-kit'\n\n/** A document with no blocks, to start from when nothing is saved yet. */\nexport const emptyDocument = (): EditorDocument<Block> => ({ version: 1, blocks: [] })\n\nexport interface DocumentProblem {\n code: 'version' | 'shape' | 'duplicate-id' | 'unknown-type' | 'unknown-mark' | 'unknown-inline'\n /** The block at fault, when it has an id. */\n blockId?: string\n /**\n * Where the problem is, as a path into the document, e.g.\n * `blocks[0].children[2]` or `blocks[1].content[0]`; `version` for the version.\n */\n path: string\n /** The id, type, mark or inline node at fault, for the editor's message. */\n text: string\n /** An English description, for logs. */\n message: string\n}\n\nexport interface CheckDocumentOptions {\n /** The editor's `extensions`, for the blocks, marks and inline nodes they add; `[editorKit()]` by default, as in the editor. */\n extensions?: EditorExtensionList\n}\n\nlet defaultKit: EditorExtensionList | undefined\n\n/**\n * What is wrong with the shape itself: the document is not an object, or a\n * list in it is not an array. Nothing else can be checked until it is fixed.\n */\nfunction shapeProblems(value: unknown, lists: string[]): DocumentProblem[] {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n return [{ code: 'shape', path: '', text: '', message: 'The document is not an object' }]\n return lists\n .filter((key) => !Array.isArray((value as Record<string, unknown>)[key]))\n .map((key) => ({ code: 'shape', path: key, text: '', message: `\"${key}\" is not a list` }))\n}\n\n/**\n * The problems of an editor document, before it is saved or shown: an\n * unknown version, blocks or table rows sharing an id, and block types,\n * marks and inline nodes the extensions don't define, which the editor\n * would show as a paragraph or leave out.\n */\nexport function checkDocument(\n document: EditorDocument<PartialBlock>,\n options: CheckDocumentOptions = {},\n): DocumentProblem[] {\n const shape = shapeProblems(document, ['blocks'])\n if (shape.length) return shape\n const problems: DocumentProblem[] = []\n if (document.version !== 1)\n problems.push({\n code: 'version',\n path: 'version',\n text: String(document.version),\n message: `Version ${String(document.version)} is not known`,\n })\n const { schema } = kitOf(options.extensions ?? (defaultKit ??= [editorKit()]))\n const ids = new Set<string>()\n const walk = (blocks: readonly PartialBlock[], at: string) =>\n blocks.forEach((block, i) => {\n const path = `${at}[${i}]`\n checkBlock(block, path, schema, ids, problems)\n if (block.children) walk(block.children, `${path}.children`)\n })\n walk(document.blocks, 'blocks')\n return problems\n}\n\nfunction checkBlock(\n block: PartialBlock,\n path: string,\n schema: Schema,\n ids: Set<string>,\n problems: DocumentProblem[],\n) {\n const blockId = block.id\n if (blockId !== undefined) {\n if (ids.has(blockId))\n problems.push({\n code: 'duplicate-id',\n blockId,\n path,\n text: blockId,\n message: `The block id \"${blockId}\" is used more than once`,\n })\n ids.add(blockId)\n }\n const type = block.type ?? 'paragraph'\n if (!schema.nodes[type]?.isInGroup('blockContent'))\n problems.push({\n code: 'unknown-type',\n blockId,\n path,\n text: type,\n message: `No block type \"${type}\" is defined; it would show as a paragraph`,\n })\n if (Array.isArray(block.content))\n block.content.forEach((item, i) => {\n const at = `${path}.content[${i}]`\n if (item.type === 'inline' && !schema.nodes[item.name]?.isInline)\n problems.push({\n code: 'unknown-inline',\n blockId,\n path: at,\n text: item.name,\n message: `No inline node \"${item.name}\" is defined; it would be left out`,\n })\n if (item.type === 'text')\n for (const mark of item.marks ?? [])\n if (!schema.marks[mark])\n problems.push({\n code: 'unknown-mark',\n blockId,\n path: at,\n text: mark,\n message: `No mark \"${mark}\" is defined; it would be left out`,\n })\n })\n if (block.rows) checkRows(block.rows, `${path}.rows`, blockId, problems)\n}\n\nfunction checkRows(\n rows: readonly PartialTableRow[],\n path: string,\n blockId: string | undefined,\n problems: DocumentProblem[],\n) {\n const ids = new Set<string>()\n rows.forEach((row, i) => {\n if (row.id === undefined) return\n if (ids.has(row.id))\n problems.push({\n code: 'duplicate-id',\n blockId,\n path: `${path}[${i}]`,\n text: row.id,\n message: `The row id \"${row.id}\" is used more than once in a table`,\n })\n ids.add(row.id)\n })\n}\n\nconst objects = <T>(value: unknown) =>\n (Array.isArray(value) ? value : []).filter(\n (item): item is T => !!item && typeof item === 'object',\n )\n\n/** The saved data as an object of version 1, or an error saying why it can't be. */\nfunction sourceOf(input: unknown): Record<string, unknown> {\n if (!input || typeof input !== 'object' || Array.isArray(input))\n throw new Error(\n `[@dou-ui/editor] an editor document must be an object, not ${Array.isArray(input) ? 'an array' : (JSON.stringify(input) ?? String(input))}`,\n )\n const source = input as Record<string, unknown>\n const version = source.version ?? 1\n if (version !== 1)\n throw new Error(\n `[@dou-ui/editor] unknown document version ${JSON.stringify(version) ?? String(version)} (expected 1); data saved by a newer @dou-ui/editor needs that version to open`,\n )\n return source\n}\n\n/**\n * Brings a saved document up to the current version, and fills what an\n * older or hand-written one may lack (`version`, `blocks`). Blocks that are\n * not objects are dropped; anything else is kept as it is, for the editor\n * to read as it reads partial blocks. Throws for data that is not an object (an array,\n * `null`, a string) and for a version it does not know.\n */\nexport function migrateDocument(input: unknown): EditorDocument<PartialBlock> {\n const source = sourceOf(input)\n return { ...source, version: 1, blocks: objects<PartialBlock>(source.blocks) }\n}\n\nconst warned = new Set<string>()\n\n/**\n * The blocks of the `v-model`, as the editor reads them. A document of the\n * wrong shape (not an object, a bare list of blocks, without `blocks` or a\n * known `version`) gets a warning in development and is read as well as it\n * can be: a list as the blocks, anything else missing as no blocks. What\n * the editor writes back always carries `version: 1`. `undefined`, no\n * `v-model` bound, is fine.\n */\nexport function readBlocks(value: unknown): PartialBlock[] | undefined {\n if (value === undefined) return undefined\n const plain = !!value && typeof value === 'object' && !Array.isArray(value)\n const source = (plain ? value : {}) as Partial<EditorDocument<PartialBlock>>\n const blocks = Array.isArray(source.blocks)\n const problem = Array.isArray(value)\n ? 'is a list of blocks'\n : !plain\n ? `is ${JSON.stringify(value) ?? String(value)}`\n : !blocks\n ? 'has no blocks array'\n : source.version === undefined\n ? 'has no version'\n : source.version !== 1\n ? `has version ${JSON.stringify(source.version)}`\n : ''\n if (problem && process.env.NODE_ENV !== 'production' && !warned.has(problem)) {\n warned.add(problem)\n console.warn(\n `[@dou-ui/editor] the v-model ${problem}; expected { version: 1, blocks: [...] }. It is read as well as it can be and the version as 1; read saved data with migrateDocument().`,\n )\n }\n if (Array.isArray(value)) return value as PartialBlock[]\n return blocks ? source.blocks : []\n}\n"],"mappings":";;;;AAMA,IAAa,uBAA8C;CAAE,SAAS;CAAG,QAAQ,CAAC;AAAE;AAsBpF,IAAI;;;;;AAMJ,SAAS,cAAc,OAAgB,OAAoC;CACzE,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D,OAAO,CAAC;EAAE,MAAM;EAAS,MAAM;EAAI,MAAM;EAAI,SAAS;CAAgC,CAAC;CACzF,OAAO,MACJ,QAAQ,QAAQ,CAAC,MAAM,QAAS,MAAkC,IAAI,CAAC,CAAC,CACxE,KAAK,SAAS;EAAE,MAAM;EAAS,MAAM;EAAK,MAAM;EAAI,SAAS,IAAI,IAAI;CAAiB,EAAE;AAC7F;;;;;;;AAQA,SAAgB,cACd,UACA,UAAgC,CAAC,GACd;CACnB,MAAM,QAAQ,cAAc,UAAU,CAAC,QAAQ,CAAC;CAChD,IAAI,MAAM,QAAQ,OAAO;CACzB,MAAM,WAA8B,CAAC;CACrC,IAAI,SAAS,YAAY,GACvB,SAAS,KAAK;EACZ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,IAAI,IAAY;;;;;;;;;AAU/B,SAAgB,WAAW,OAA4C;CACrE,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,MAAM,QAAQ,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;CAC1E,MAAM,SAAU,QAAQ,QAAQ,CAAC;CACjC,MAAM,SAAS,MAAM,QAAQ,OAAO,MAAM;CAC1C,MAAM,UAAU,MAAM,QAAQ,KAAK,IAC/B,wBACA,CAAC,QACC,MAAM,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK,MAC3C,CAAC,SACC,wBACA,OAAO,YAAY,KAAA,IACjB,mBACA,OAAO,YAAY,IACjB,eAAe,KAAK,UAAU,OAAO,OAAO,MAC5C;CACZ,IAAI,WAAA,QAAA,IAAA,aAAoC,gBAAgB,CAAC,OAAO,IAAI,OAAO,GAAG;EAC5E,OAAO,IAAI,OAAO;EAClB,QAAQ,KACN,gCAAgC,QAAQ,wIAC1C;CACF;CACA,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO;CACjC,OAAO,SAAS,OAAO,SAAS,CAAC;AACnC"}
|
|
1
|
+
{"version":3,"file":"document.js","names":[],"sources":["../src/document.ts"],"sourcesContent":["import type { Schema } from 'prosemirror-model'\nimport { kitOf, type EditorExtensionList } from './core/convert'\nimport type { Block, EditorDocument, PartialBlock, PartialTableRow } from './core/model'\nimport { editorKit } from './extensions/editor-kit'\n\n/** A document with no blocks, to start from when nothing is saved yet. */\nexport const emptyDocument = (): EditorDocument<Block> => ({ version: 1, blocks: [] })\n\nexport interface DocumentProblem {\n code:\n | 'version'\n | 'shape'\n | 'duplicate-id'\n | 'unknown-type'\n | 'unknown-mark'\n | 'unknown-inline'\n | 'invalid-columns'\n | 'invalid-props'\n /** The block at fault, when it has an id. */\n blockId?: string\n /**\n * Where the problem is, as a path into the document, e.g.\n * `blocks[0].children[2]` or `blocks[1].content[0]`; `version` for the version.\n */\n path: string\n /** The id, type, mark or inline node at fault, for the editor's message. */\n text: string\n /** An English description, for logs. */\n message: string\n}\n\nexport interface CheckDocumentOptions {\n /** The editor's `extensions`, for the blocks, marks and inline nodes they add; `[editorKit()]` by default, as in the editor. */\n extensions?: EditorExtensionList\n}\n\nlet defaultKit: EditorExtensionList | undefined\n\n/**\n * What is wrong with the shape itself: the document is not an object, or a\n * list in it is not an array. Nothing else can be checked until it is fixed.\n */\nfunction shapeProblems(value: unknown, lists: string[]): DocumentProblem[] {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n return [{ code: 'shape', path: '', text: '', message: 'The document is not an object' }]\n return lists\n .filter((key) => !Array.isArray((value as Record<string, unknown>)[key]))\n .map((key) => ({ code: 'shape', path: key, text: '', message: `\"${key}\" is not a list` }))\n}\n\n/**\n * The problems of an editor document, before it is saved or shown: an\n * unknown version, blocks or table rows sharing an id, and block types,\n * marks and inline nodes the extensions don't define, which the editor\n * would show as a paragraph or leave out, and columns the editor would\n * change on the next edit (a column outside a set of columns, a set with\n * fewer than two, columns in a column…), and props a block type says it can't use\n * (its spec's `checkProps`, e.g. a whiteboard's board that isn't a flow).\n */\nexport function checkDocument(\n document: EditorDocument<PartialBlock>,\n options: CheckDocumentOptions = {},\n): DocumentProblem[] {\n const shape = shapeProblems(document, ['blocks'])\n if (shape.length) return shape\n const problems: DocumentProblem[] = []\n if (document.version !== 1)\n problems.push({\n code: 'version',\n path: 'version',\n text: String(document.version),\n message: `Version ${String(document.version)} is not known`,\n })\n const { schema } = kitOf(options.extensions ?? (defaultKit ??= [editorKit()]))\n const ids = new Set<string>()\n const walk = (blocks: readonly PartialBlock[], at: string, around: Around) =>\n blocks.forEach((block, i) => {\n const path = `${at}[${i}]`\n checkBlock(block, path, schema, ids, problems)\n const layout = layoutOfType(schema, block.type)\n checkLayout(block, layout, path, around, schema, problems)\n checkProps(block, path, schema, problems)\n if (block.children)\n walk(block.children, `${path}.children`, {\n layout,\n inColumn: around.inColumn || layout === 'column',\n })\n })\n walk(document.blocks, 'blocks', { layout: undefined, inColumn: false })\n return problems\n}\n\n/**\n * Props a block type can't use, as its spec's `checkProps` tells: a\n * whiteboard whose `board` isn't a flow document, a height that isn't a\n * number… Each is `{ prop, message }`.\n */\nfunction checkProps(\n block: PartialBlock,\n path: string,\n schema: Schema,\n problems: DocumentProblem[],\n) {\n const type = block.type ?? 'paragraph'\n const check = schema.nodes[type]?.spec.checkProps as\n ((props: Record<string, unknown>) => { prop: string; message: string }[]) | undefined\n if (!check || !block.props) return\n for (const { prop, message } of check(block.props as Record<string, unknown>))\n problems.push({\n code: 'invalid-props',\n blockId: block.id,\n path: `${path}.props.${prop}`,\n text: type,\n message,\n })\n}\n\n/** What a block sits in: the layout of its parent, and whether that is inside a column. */\ninterface Around {\n layout: string | undefined\n inColumn: boolean\n}\n\nconst layoutOfType = (schema: Schema, type: string | undefined) =>\n schema.nodes[type ?? 'paragraph']?.spec.layout as string | undefined\n\n/** Columns as the editor keeps them; anything else it changes on the next edit. */\nfunction checkLayout(\n block: PartialBlock,\n layout: string | undefined,\n path: string,\n around: Around,\n schema: Schema,\n problems: DocumentProblem[],\n) {\n const type = block.type ?? 'paragraph'\n const report = (message: string, at = path) =>\n problems.push({ code: 'invalid-columns', blockId: block.id, path: at, text: type, message })\n const children = block.children ?? []\n if (around.layout === 'row' && layout !== 'column')\n report(`A \"${type}\" block directly in a set of columns would move into the column before it`)\n if (layout === 'column') {\n if (around.layout !== 'row')\n report('A column outside a set of columns would be replaced by its blocks')\n if (!children.length) report('An empty column would be removed')\n const width = block.props?.width\n if (width != null && !(typeof width === 'number' && width > 0))\n report(\n `The column width ${JSON.stringify(width)} is not a positive number; it would be ignored`,\n `${path}.props.width`,\n )\n }\n if (layout === 'row') {\n if (around.inColumn) report('Columns inside a column would be replaced by their blocks')\n const columns = children.filter((child) => layoutOfType(schema, child.type) === 'column')\n if (columns.length < 2)\n report(`A set of ${columns.length} column(s) would be replaced by its blocks`)\n }\n if (layout && Array.isArray(block.content) && block.content.length)\n report(\n `A \"${type}\" block has no text of its own; its content would be left out`,\n `${path}.content`,\n )\n}\n\nfunction checkBlock(\n block: PartialBlock,\n path: string,\n schema: Schema,\n ids: Set<string>,\n problems: DocumentProblem[],\n) {\n const blockId = block.id\n if (blockId !== undefined) {\n if (ids.has(blockId))\n problems.push({\n code: 'duplicate-id',\n blockId,\n path,\n text: blockId,\n message: `The block id \"${blockId}\" is used more than once`,\n })\n ids.add(blockId)\n }\n const type = block.type ?? 'paragraph'\n if (!schema.nodes[type]?.isInGroup('blockContent'))\n problems.push({\n code: 'unknown-type',\n blockId,\n path,\n text: type,\n message: `No block type \"${type}\" is defined; it would show as a paragraph`,\n })\n if (Array.isArray(block.content))\n block.content.forEach((item, i) => {\n const at = `${path}.content[${i}]`\n if (item.type === 'inline' && !schema.nodes[item.name]?.isInline)\n problems.push({\n code: 'unknown-inline',\n blockId,\n path: at,\n text: item.name,\n message: `No inline node \"${item.name}\" is defined; it would be left out`,\n })\n if (item.type === 'text')\n for (const mark of item.marks ?? [])\n if (!schema.marks[mark])\n problems.push({\n code: 'unknown-mark',\n blockId,\n path: at,\n text: mark,\n message: `No mark \"${mark}\" is defined; it would be left out`,\n })\n })\n if (block.rows) checkRows(block.rows, `${path}.rows`, blockId, problems)\n}\n\nfunction checkRows(\n rows: readonly PartialTableRow[],\n path: string,\n blockId: string | undefined,\n problems: DocumentProblem[],\n) {\n const ids = new Set<string>()\n rows.forEach((row, i) => {\n if (row.id === undefined) return\n if (ids.has(row.id))\n problems.push({\n code: 'duplicate-id',\n blockId,\n path: `${path}[${i}]`,\n text: row.id,\n message: `The row id \"${row.id}\" is used more than once in a table`,\n })\n ids.add(row.id)\n })\n}\n\nconst objects = <T>(value: unknown) =>\n (Array.isArray(value) ? value : []).filter(\n (item): item is T => !!item && typeof item === 'object',\n )\n\n/** The saved data as an object of version 1, or an error saying why it can't be. */\nfunction sourceOf(input: unknown): Record<string, unknown> {\n if (!input || typeof input !== 'object' || Array.isArray(input))\n throw new Error(\n `[@dou-ui/editor] an editor document must be an object, not ${Array.isArray(input) ? 'an array' : (JSON.stringify(input) ?? String(input))}`,\n )\n const source = input as Record<string, unknown>\n const version = source.version ?? 1\n if (version !== 1)\n throw new Error(\n `[@dou-ui/editor] unknown document version ${JSON.stringify(version) ?? String(version)} (expected 1); data saved by a newer @dou-ui/editor needs that version to open`,\n )\n return source\n}\n\n/**\n * Brings a saved document up to the current version, and fills what an\n * older or hand-written one may lack (`version`, `blocks`). Blocks that are\n * not objects are dropped; anything else is kept as it is, for the editor\n * to read as it reads partial blocks. Throws for data that is not an object (an array,\n * `null`, a string) and for a version it does not know.\n */\nexport function migrateDocument(input: unknown): EditorDocument<PartialBlock> {\n const source = sourceOf(input)\n return { ...source, version: 1, blocks: objects<PartialBlock>(source.blocks) }\n}\n\nconst warned = new Set<string>()\n\n/**\n * The blocks of the `v-model`, as the editor reads them. A document of the\n * wrong shape (not an object, a bare list of blocks, without `blocks` or a\n * known `version`) gets a warning in development and is read as well as it\n * can be: a list as the blocks, anything else missing as no blocks. What\n * the editor writes back always carries `version: 1`. `undefined`, no\n * `v-model` bound, is fine.\n */\nexport function readBlocks(value: unknown): PartialBlock[] | undefined {\n if (value === undefined) return undefined\n const plain = !!value && typeof value === 'object' && !Array.isArray(value)\n const source = (plain ? value : {}) as Partial<EditorDocument<PartialBlock>>\n const blocks = Array.isArray(source.blocks)\n const problem = Array.isArray(value)\n ? 'is a list of blocks'\n : !plain\n ? `is ${JSON.stringify(value) ?? String(value)}`\n : !blocks\n ? 'has no blocks array'\n : source.version === undefined\n ? 'has no version'\n : source.version !== 1\n ? `has version ${JSON.stringify(source.version)}`\n : ''\n if (problem && process.env.NODE_ENV !== 'production' && !warned.has(problem)) {\n warned.add(problem)\n console.warn(\n `[@dou-ui/editor] the v-model ${problem}; expected { version: 1, blocks: [...] }. It is read as well as it can be and the version as 1; read saved data with migrateDocument().`,\n )\n }\n if (Array.isArray(value)) return value as PartialBlock[]\n return blocks ? source.blocks : []\n}\n"],"mappings":";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