@dou-ui/editor 0.1.0-alpha.2 → 0.1.0-alpha.21
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/code/code-editor-block.js.map +1 -1
- package/dist/code/code-editor-block.vue_vue_type_script_setup_true_lang.js +1 -0
- package/dist/code/code-editor-block.vue_vue_type_script_setup_true_lang.js.map +1 -1
- 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 +125 -17
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/components/bubble-toolbar.js.map +1 -1
- package/dist/components/bubble-toolbar.vue_vue_type_script_setup_true_lang.js +2 -1
- package/dist/components/bubble-toolbar.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/components/comment-card.js.map +1 -1
- package/dist/components/comment-card.vue_vue_type_script_setup_true_lang.js +2 -1
- package/dist/components/comment-card.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/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/editor.js +2 -1
- package/dist/core/editor.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/plugins.js +108 -5
- package/dist/core/plugins.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 +112 -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 +3 -3
- package/dist/editor.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/editor2.js.map +1 -1
- package/dist/extensions/align/align-menu.js.map +1 -1
- package/dist/extensions/align/align-menu.vue_vue_type_script_setup_true_lang.js +4 -6
- package/dist/extensions/align/align-menu.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/extensions/callout/html.js +5 -4
- package/dist/extensions/callout/html.js.map +1 -1
- package/dist/extensions/colors/color-menu.js.map +1 -1
- package/dist/extensions/colors/color-menu.vue_vue_type_script_setup_true_lang.js +6 -8
- package/dist/extensions/colors/color-menu.vue_vue_type_script_setup_true_lang.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/table-controls.js.map +1 -1
- package/dist/extensions/table/table-controls.vue_vue_type_script_setup_true_lang.js +1 -1
- package/dist/extensions/table/table-controls.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/extensions/table/view.js +25 -1
- 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/index.js +2 -2
- package/dist/markdown/index.js.map +1 -1
- package/dist/style.css +1 -1
- package/dist/style.js +2 -1
- 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/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/plugins.d.ts +9 -0
- 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 +43 -4
- package/dist/types/editor.d.ts +9 -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 +8 -1
- 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/index.d.ts +8 -1
- package/dist/use-comments.js +2 -2
- package/dist/use-comments.js.map +1 -1
- package/package.json +14 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"comments.js","names":[],"sources":["../../src/core/comments.ts"],"sourcesContent":["import { Fragment, Slice, type Node as PMNode } from 'prosemirror-model'\nimport { Plugin, PluginKey, type EditorState, type Transaction } from 'prosemirror-state'\nimport { Decoration, DecorationSet, type EditorView } from 'prosemirror-view'\nimport { blockAround } from './blocks'\n\n/*\n * Comment threads are anchored by a `comment` mark carrying the thread's\n * id on the text they are about. The threads themselves (comments,\n * replies, resolved) are kept outside the document.\n */\n\n/** A range of the document, as positions. */\nexport interface CommentRange {\n from: number\n to: number\n}\n\n/** Where a thread is anchored: the block and the text it is about. */\nexport interface CommentAnchor {\n /** The id of the (first) block holding the text. */\n block: string\n /** The text the thread is about. */\n text: string\n from: number\n to: number\n}\n\nexport interface CommentPluginState {\n /** The text a thread is being started on, until its first comment is sent. */\n pending: CommentRange | null\n decorations: DecorationSet\n}\n\nexport const commentKey = new PluginKey<CommentPluginState>('dou-editor-comments')\n\ntype CommentMeta = { pending: CommentRange | null }\n\nexport interface CommentPluginOptions {\n /** The ids of the threads there are, or `null` when comments are off. */\n known: () => ReadonlySet<string> | null\n /** A click on text that is in threads, with their ids, innermost first; `[]` elsewhere. */\n onClick: (ids: string[]) => void\n onPending: (range: CommentRange | null) => void\n /** Text got selected (a range, not a cursor). */\n onSelect: () => void\n}\n\nconst pendingDecorations = (doc: PMNode, range: CommentRange | null) =>\n range && range.to > range.from\n ? DecorationSet.create(doc, [\n Decoration.inline(range.from, range.to, { class: 'dou-editor__comment-pending' }),\n ])\n : DecorationSet.empty\n\n/** The ids of the threads at `pos`, the shortest (innermost) first. */\nexport function commentsAt(state: EditorState, pos: number): string[] {\n const $pos = state.doc.resolve(pos)\n const node = $pos.parent.childAfter($pos.parentOffset).node\n if (!node) return []\n const ids = node.marks\n .filter((mark) => mark.type.name === 'comment')\n .map((mark) => mark.attrs.id as string)\n if (ids.length < 2) return ids\n const length = new Map(ids.map((id) => [id, rangeLength(state.doc, id, pos)]))\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts the fresh list\n return ids.sort((a, b) => length.get(a)! - length.get(b)!)\n}\n\n/** How long the run of `id`'s text around `pos` is, within its textblock. */\nfunction rangeLength(doc: PMNode, id: string, pos: number): number {\n const $pos = doc.resolve(pos)\n const start = $pos.start()\n let runStart = -1\n let around = false\n let length = Infinity\n $pos.parent.forEach((child, offset) => {\n const at = start + offset\n const end = at + child.nodeSize\n if (child.marks.some((mark) => mark.type.name === 'comment' && mark.attrs.id === id)) {\n if (runStart < 0) runStart = at\n if (at <= pos && pos <= end) around = true\n if (around) length = end - runStart\n } else {\n if (around) around = false\n runStart = -1\n }\n })\n return length\n}\n\n/** Every thread's anchor in the document, by id: the first and last positions of its text. */\nexport function commentAnchors(doc: PMNode): Map<string, CommentAnchor> {\n const anchors = new Map<string, CommentAnchor>()\n doc.descendants((node, pos) => {\n if (!node.isText) return true\n for (const mark of node.marks) {\n if (mark.type.name !== 'comment') continue\n const id = mark.attrs.id as string\n const end = pos + node.nodeSize\n const anchor = anchors.get(id)\n if (anchor) {\n anchor.to = end\n anchor.text += node.text\n } else {\n const block = blockAround(doc.resolve(pos))\n anchors.set(id, {\n block: (block?.node.attrs.id as string | undefined) ?? '',\n text: node.text ?? '',\n from: pos,\n to: end,\n })\n }\n }\n return false\n })\n return anchors\n}\n\n/** The text of `id`'s anchor that a thread card points at: its first and last positions. */\nexport function commentRange(doc: PMNode, id: string): CommentRange | null {\n let from = -1\n let to = -1\n doc.descendants((node, pos) => {\n if (!node.isText) return true\n if (node.marks.some((mark) => mark.type.name === 'comment' && mark.attrs.id === id)) {\n if (from < 0) from = pos\n to = pos + node.nodeSize\n }\n return false\n })\n return from < 0 ? null : { from, to }\n}\n\n/** Marks `range` as the text of a new thread. Not undone with the edits around it. */\nexport function anchorComment(view: EditorView, range: CommentRange, id: string) {\n const type = view.state.schema.marks.comment!\n const tr = view.state.tr.addMark(range.from, range.to, type.create({ id }))\n tr.setMeta(commentKey, { pending: null } satisfies CommentMeta)\n tr.setMeta('addToHistory', false)\n view.dispatch(tr)\n}\n\n/** Takes a removed thread's anchor off the text. */\nexport function unanchorComment(view: EditorView, id: string) {\n const type = view.state.schema.marks.comment!\n const tr = view.state.tr\n view.state.doc.descendants((node, pos) => {\n if (!node.isText) return true\n const mark = node.marks.find((m) => m.type === type && m.attrs.id === id)\n if (mark) tr.removeMark(pos, pos + node.nodeSize, mark)\n return false\n })\n if (!tr.docChanged) return\n tr.setMeta('addToHistory', false)\n view.dispatch(tr)\n}\n\nexport function setPendingComment(view: EditorView, range: CommentRange | null) {\n view.dispatch(view.state.tr.setMeta(commentKey, { pending: range } satisfies CommentMeta))\n}\n\n/**\n * A pasted copy of commented text doesn't take the thread along: the\n * thread keeps its one anchor. Text that was cut is no longer in the\n * document, so its threads come along with it.\n */\nfunction dropCopiedComments(slice: Slice, state: EditorState, known: ReadonlySet<string> | null) {\n const inDoc = new Set<string>()\n let any = false\n slice.content.descendants((node) => {\n if (node.marks.some((mark) => mark.type.name === 'comment')) any = true\n return !any\n })\n if (!any) return slice\n state.doc.descendants((node) => {\n for (const mark of node.marks) if (mark.type.name === 'comment') inDoc.add(mark.attrs.id)\n return true\n })\n const keep = (id: string) => !inDoc.has(id) && (!known || known.has(id))\n const strip = (fragment: Fragment): Fragment => {\n const nodes: PMNode[] = []\n fragment.forEach((node) => {\n if (node.isText) {\n nodes.push(\n node.mark(node.marks.filter((m) => m.type.name !== 'comment' || keep(m.attrs.id))),\n )\n } else nodes.push(node.copy(strip(node.content)))\n })\n return Fragment.from(nodes)\n }\n return new Slice(strip(slice.content), slice.openStart, slice.openEnd)\n}\n\nexport function commentPlugin(options: CommentPluginOptions): Plugin<CommentPluginState> {\n return new Plugin<CommentPluginState>({\n key: commentKey,\n state: {\n init: () => ({ pending: null, decorations: DecorationSet.empty }),\n apply(tr: Transaction, value: CommentPluginState): CommentPluginState {\n const meta = tr.getMeta(commentKey) as CommentMeta | undefined\n let pending = value.pending\n if (meta) pending = meta.pending\n else if (pending && tr.docChanged) {\n const from = tr.mapping.map(pending.from, 1)\n const to = tr.mapping.map(pending.to, -1)\n pending = to > from ? { from, to } : null\n }\n if (pending === value.pending && !tr.docChanged) return value\n return { pending, decorations: pendingDecorations(tr.doc, pending) }\n },\n },\n view: () => {\n let last: CommentRange | null = null\n return {\n update(view, previous) {\n const pending = commentKey.getState(view.state)!.pending\n if (pending !== last) options.onPending((last = pending))\n const { selection } = view.state\n // a selection made by the user, not one moved along by an edit\n if (\n !selection.empty &&\n view.state.doc === previous.doc &&\n !selection.eq(previous.selection)\n )\n options.onSelect()\n },\n }\n },\n props: {\n decorations: (state) => commentKey.getState(state)!.decorations,\n transformPasted: (slice, view) => dropCopiedComments(slice, view.state, options.known()),\n handleClick(view, pos, event) {\n if (event.button !== 0 || !options.known()) return false\n const known = options.known()!\n options.onClick(commentsAt(view.state, pos).filter((id) => known.has(id)))\n return false\n },\n },\n })\n}\n"],"mappings":";;;;;AAiCA,IAAa,aAAa,IAAI,UAA8B,qBAAqB;AAcjF,IAAM,sBAAsB,KAAa,UACvC,SAAS,MAAM,KAAK,MAAM,OACtB,cAAc,OAAO,KAAK,CACxB,WAAW,OAAO,MAAM,MAAM,MAAM,IAAI,EAAE,OAAO,8BAA8B,CAAC,CAClF,CAAC,IACD,cAAc;;AAGpB,SAAgB,WAAW,OAAoB,KAAuB;CACpE,MAAM,OAAO,MAAM,IAAI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,OAAO,MAAM,IAAI,EAAE,CAAC,CAAC;IACzE,OAAO;GACT;EACF;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"comments.js","names":[],"sources":["../../src/core/comments.ts"],"sourcesContent":["import { Fragment, Slice, type Node as PMNode } from 'prosemirror-model'\nimport { isHistoryTransaction } from 'prosemirror-history'\nimport { Plugin, PluginKey, type EditorState, type Transaction } from 'prosemirror-state'\nimport { Decoration, DecorationSet, type EditorView } from 'prosemirror-view'\nimport { blockAround } from './blocks'\nimport type { BlockProps } from './model'\n\n/*\n * Comment threads are anchored by a `comment` mark carrying the thread's\n * id on the text they are about, or inside a block that keeps them in its\n * props (its spec's `comments`, e.g. the nodes of a whiteboard). The\n * threads themselves (comments, replies, resolved) are kept outside the\n * document.\n */\n\n/** Where a thread is inside a block: what to show for it, and the block's own description of the spot. */\nexport interface BlockCommentAnchor<Target = unknown> {\n /** The text of what the thread is about, e.g. a node's label; `''` when it has none. */\n text: string\n /** Where in the block, as the block describes it, e.g. `{ node: 'n1' }`. */\n target: Target\n}\n\n/**\n * How a block type keeps comment threads on what is inside it, in its\n * props: the `comments` field of its spec. The block's component starts\n * and shows those threads itself (see `useEditor().comments`); the editor\n * lists them in `getCommentAnchors()`, leaves them out of pasted copies,\n * and puts them back after undo and redo, which restore older props.\n */\nexport interface BlockCommentsSpec<Target = unknown> {\n /** The threads in the block, by id. */\n anchors: (props: BlockProps) => Record<string, BlockCommentAnchor<Target>>\n /** The props with thread `id` on `target`; `null` when that isn't in the block any more. */\n place: (props: BlockProps, id: string, target: Target) => BlockProps | null\n /** The props with only the threads `keep` says yes to. */\n strip: (props: BlockProps, keep: (id: string) => boolean) => BlockProps\n}\n\ndeclare module 'prosemirror-model' {\n interface NodeSpec {\n /** Comment threads kept inside the block's props, see `BlockCommentsSpec`. */\n // oxlint-disable-next-line typescript/no-explicit-any -- each block type has its own target\n comments?: BlockCommentsSpec<any>\n }\n}\n\n/** The `comments` of a node's spec: a block type that keeps threads inside. */\nexport const blockCommentsOf = (node: PMNode) =>\n node.type.spec.comments as BlockCommentsSpec | undefined\n\n/** A range of the document, as positions. */\nexport interface CommentRange {\n from: number\n to: number\n}\n\n/** Where a thread is anchored: the block and the text it is about. */\nexport interface CommentAnchor {\n /** The id of the (first) block holding the text, or of the block the thread is inside. */\n block: string\n /** The text the thread is about; inside a block, what the block shows for it (e.g. a node's label). */\n text: string\n /** The text's first and last positions; inside a block, the block's. */\n from: number\n to: number\n /** Inside a block: the block's type. */\n type?: string\n /** Inside a block: where, as the block describes it (e.g. `{ node: 'n1' }` on a whiteboard). */\n target?: unknown\n}\n\nexport interface CommentPluginState {\n /** The text a thread is being started on, until its first comment is sent. */\n pending: CommentRange | null\n decorations: DecorationSet\n}\n\nexport const commentKey = new PluginKey<CommentPluginState>('dou-editor-comments')\n\ntype CommentMeta = { pending: CommentRange | null }\n\nexport interface CommentPluginOptions {\n /** The ids of the threads there are, or `null` when comments are off. */\n known: () => ReadonlySet<string> | null\n /** A click on text that is in threads, with their ids, innermost first; `[]` elsewhere. */\n onClick: (ids: string[]) => void\n onPending: (range: CommentRange | null) => void\n /** Text got selected (a range, not a cursor). */\n onSelect: () => void\n}\n\nconst pendingDecorations = (doc: PMNode, range: CommentRange | null) =>\n range && range.to > range.from\n ? DecorationSet.create(doc, [\n Decoration.inline(range.from, range.to, { class: 'dou-editor__comment-pending' }),\n ])\n : DecorationSet.empty\n\n/** The ids of the threads at `pos`, the shortest (innermost) first. */\nexport function commentsAt(state: EditorState, pos: number): string[] {\n const $pos = state.doc.resolve(pos)\n const node = $pos.parent.childAfter($pos.parentOffset).node\n if (!node) return []\n const ids = node.marks\n .filter((mark) => mark.type.name === 'comment')\n .map((mark) => mark.attrs.id as string)\n if (ids.length < 2) return ids\n const length = new Map(ids.map((id) => [id, rangeLength(state.doc, id, pos)]))\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts the fresh list\n return ids.sort((a, b) => length.get(a)! - length.get(b)!)\n}\n\n/** How long the run of `id`'s text around `pos` is, within its textblock. */\nfunction rangeLength(doc: PMNode, id: string, pos: number): number {\n const $pos = doc.resolve(pos)\n const start = $pos.start()\n let runStart = -1\n let around = false\n let length = Infinity\n $pos.parent.forEach((child, offset) => {\n const at = start + offset\n const end = at + child.nodeSize\n if (child.marks.some((mark) => mark.type.name === 'comment' && mark.attrs.id === id)) {\n if (runStart < 0) runStart = at\n if (at <= pos && pos <= end) around = true\n if (around) length = end - runStart\n } else {\n if (around) around = false\n runStart = -1\n }\n })\n return length\n}\n\n/** Every thread's anchor in the document, by id: the first and last positions of its text. */\nexport function commentAnchors(doc: PMNode): Map<string, CommentAnchor> {\n const anchors = new Map<string, CommentAnchor>()\n doc.descendants((node, pos) => {\n const inside = blockCommentsOf(node)\n if (inside) {\n const block = (doc.resolve(pos).parent.attrs.id as string | undefined) ?? ''\n for (const [id, at] of Object.entries(inside.anchors(node.attrs))) {\n if (anchors.has(id)) continue\n const to = pos + node.nodeSize\n anchors.set(id, {\n block,\n text: at.text,\n from: pos,\n to,\n type: node.type.name,\n target: at.target,\n })\n }\n return false\n }\n if (!node.isText) return true\n for (const mark of node.marks) {\n if (mark.type.name !== 'comment') continue\n const id = mark.attrs.id as string\n const end = pos + node.nodeSize\n const anchor = anchors.get(id)\n if (anchor) {\n anchor.to = end\n anchor.text += node.text\n } else {\n const block = blockAround(doc.resolve(pos))\n anchors.set(id, {\n block: (block?.node.attrs.id as string | undefined) ?? '',\n text: node.text ?? '',\n from: pos,\n to: end,\n })\n }\n }\n return false\n })\n return anchors\n}\n\n/** The text of `id`'s anchor that a thread card points at: its first and last positions. */\nexport function commentRange(doc: PMNode, id: string): CommentRange | null {\n let from = -1\n let to = -1\n doc.descendants((node, pos) => {\n if (!node.isText) return true\n if (node.marks.some((mark) => mark.type.name === 'comment' && mark.attrs.id === id)) {\n if (from < 0) from = pos\n to = pos + node.nodeSize\n }\n return false\n })\n return from < 0 ? null : { from, to }\n}\n\n/** Marks `range` as the text of a new thread. Not undone with the edits around it. */\nexport function anchorComment(view: EditorView, range: CommentRange, id: string) {\n const type = view.state.schema.marks.comment!\n const tr = view.state.tr.addMark(range.from, range.to, type.create({ id }))\n tr.setMeta(commentKey, { pending: null } satisfies CommentMeta)\n tr.setMeta('addToHistory', false)\n view.dispatch(tr)\n}\n\n/** Sets the props of the block content at `pos` that differ in `next`. */\nfunction setProps(tr: Transaction, pos: number, before: BlockProps, next: BlockProps) {\n for (const [name, value] of Object.entries(next))\n if (Object.hasOwn(before, name) && before[name] !== value) tr.setNodeAttribute(pos, name, value)\n}\n\n/** The id of the block around the content node at `pos`. */\nconst blockIdAt = (doc: PMNode, pos: number) =>\n (doc.resolve(pos).parent.attrs.id as string | undefined) ?? ''\n\n/** Takes a removed thread's anchor off the text, or out of the block it is inside. */\nexport function unanchorComment(view: EditorView, id: string) {\n const type = view.state.schema.marks.comment!\n const tr = view.state.tr\n view.state.doc.descendants((node, pos) => {\n const inside = blockCommentsOf(node)\n if (inside) {\n if (Object.hasOwn(inside.anchors(node.attrs), id))\n setProps(\n tr,\n pos,\n node.attrs,\n inside.strip(node.attrs, (other) => other !== id),\n )\n return false\n }\n if (!node.isText) return true\n const mark = node.marks.find((m) => m.type === type && m.attrs.id === id)\n if (mark) tr.removeMark(pos, pos + node.nodeSize, mark)\n return false\n })\n if (!tr.docChanged) return\n tr.setMeta('addToHistory', false)\n view.dispatch(tr)\n}\n\nexport function setPendingComment(view: EditorView, range: CommentRange | null) {\n view.dispatch(view.state.tr.setMeta(commentKey, { pending: range } satisfies CommentMeta))\n}\n\n/**\n * A pasted copy of commented text doesn't take the thread along: the\n * thread keeps its one anchor. Text that was cut is no longer in the\n * document, so its threads come along with it.\n */\nfunction dropCopiedComments(slice: Slice, state: EditorState, known: ReadonlySet<string> | null) {\n const inDoc = new Set<string>()\n let any = false\n slice.content.descendants((node) => {\n if (node.marks.some((mark) => mark.type.name === 'comment')) any = true\n const inside = blockCommentsOf(node)\n if (inside && Object.keys(inside.anchors(node.attrs)).length) any = true\n return !any\n })\n if (!any) return slice\n state.doc.descendants((node) => {\n for (const mark of node.marks) if (mark.type.name === 'comment') inDoc.add(mark.attrs.id)\n const inside = blockCommentsOf(node)\n if (inside) for (const id of Object.keys(inside.anchors(node.attrs))) inDoc.add(id)\n return true\n })\n const keep = (id: string) => !inDoc.has(id) && (!known || known.has(id))\n const strip = (fragment: Fragment): Fragment => {\n const nodes: PMNode[] = []\n fragment.forEach((node) => {\n const inside = blockCommentsOf(node)\n if (node.isText) {\n nodes.push(\n node.mark(node.marks.filter((m) => m.type.name !== 'comment' || keep(m.attrs.id))),\n )\n } else if (inside) {\n const attrs = { ...node.attrs, ...inside.strip(node.attrs, keep) }\n nodes.push(node.type.create(attrs, strip(node.content), node.marks))\n } else nodes.push(node.copy(strip(node.content)))\n })\n return Fragment.from(nodes)\n }\n return new Slice(strip(slice.content), slice.openStart, slice.openEnd)\n}\n\n/** The threads inside each block that keeps them, by block id. */\nfunction blockAnchors(doc: PMNode) {\n const found = new Map<string, Record<string, BlockCommentAnchor>>()\n doc.descendants((node, pos) => {\n const inside = blockCommentsOf(node)\n if (!inside) return true\n found.set(blockIdAt(doc, pos), inside.anchors(node.attrs))\n return false\n })\n return found\n}\n\n/**\n * Undo and redo bring back a block's props as they were, threads included,\n * but starting and deleting threads aren't steps of the history: each block\n * keeps the threads it had before, put back where they were if that is\n * still there, and those it comes back with that are still threads (on a\n * node brought back, say), not those deleted since. A block brought back by\n * the undo keeps what it comes with.\n */\nfunction keepBlockComments(\n before: PMNode,\n state: EditorState,\n known: ReadonlySet<string> | null,\n): Transaction | null {\n const had = blockAnchors(before)\n if (!had.size) return null\n const tr = state.tr\n state.doc.descendants((node, pos) => {\n const inside = blockCommentsOf(node)\n if (!inside) return true\n const anchors = had.get(blockIdAt(state.doc, pos))\n if (!anchors) return false\n let props = inside.strip(\n node.attrs,\n (id) => Object.hasOwn(anchors, id) || !known || known.has(id),\n )\n const now = inside.anchors(props)\n for (const [id, at] of Object.entries(anchors)) {\n if (Object.hasOwn(now, id)) continue\n props = inside.place(props, id, at.target) ?? props\n }\n if (props !== node.attrs) setProps(tr, pos, node.attrs, props)\n return false\n })\n return tr.docChanged ? tr.setMeta('addToHistory', false) : null\n}\n\nexport function commentPlugin(options: CommentPluginOptions): Plugin<CommentPluginState> {\n return new Plugin<CommentPluginState>({\n key: commentKey,\n appendTransaction: (trs, before, state) =>\n trs.some((tr) => tr.docChanged && isHistoryTransaction(tr))\n ? keepBlockComments(before.doc, state, options.known())\n : null,\n state: {\n init: () => ({ pending: null, decorations: DecorationSet.empty }),\n apply(tr: Transaction, value: CommentPluginState): CommentPluginState {\n const meta = tr.getMeta(commentKey) as CommentMeta | undefined\n let pending = value.pending\n if (meta) pending = meta.pending\n else if (pending && tr.docChanged) {\n const from = tr.mapping.map(pending.from, 1)\n const to = tr.mapping.map(pending.to, -1)\n pending = to > from ? { from, to } : null\n }\n if (pending === value.pending && !tr.docChanged) return value\n return { pending, decorations: pendingDecorations(tr.doc, pending) }\n },\n },\n view: () => {\n let last: CommentRange | null = null\n return {\n update(view, previous) {\n const pending = commentKey.getState(view.state)!.pending\n if (pending !== last) options.onPending((last = pending))\n const { selection } = view.state\n // a selection made by the user, not one moved along by an edit\n if (\n !selection.empty &&\n view.state.doc === previous.doc &&\n !selection.eq(previous.selection)\n )\n options.onSelect()\n },\n }\n },\n props: {\n decorations: (state) => commentKey.getState(state)!.decorations,\n transformPasted: (slice, view) => dropCopiedComments(slice, view.state, options.known()),\n handleClick(view, pos, event) {\n if (event.button !== 0 || !options.known()) return false\n const known = options.known()!\n options.onClick(commentsAt(view.state, pos).filter((id) => known.has(id)))\n return false\n },\n },\n })\n}\n"],"mappings":";;;;;;;AAgDA,IAAa,mBAAmB,SAC9B,KAAK,KAAK,KAAK;AA6BjB,IAAa,aAAa,IAAI,UAA8B,qBAAqB;AAcjF,IAAM,sBAAsB,KAAa,UACvC,SAAS,MAAM,KAAK,MAAM,OACtB,cAAc,OAAO,KAAK,CACxB,WAAW,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AK,CAAC,CAAE;GACpD,kBAAkB,OAAO,SAAS,mBAAmB,OAAO,KAAK,OAAO,QAAQ,MAAM,CAAC;GACvF,YAAY,MAAM,KAAK,OAAO;IAC5B,IAAI,MAAM,WAAW,KAAK,CAAC,QAAQ,MAAM,GAAG,OAAO;IACnD,MAAM,QAAQ,QAAQ,MAAM;IAC5B,QAAQ,QAAQ,WAAW,KAAK,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,MAAM,IAAI,EAAE,CAAC,CAAC;IACzE,OAAO;GACT;EACF;CACF,CAAC;AACH"}
|
package/dist/core/convert.js
CHANGED
|
@@ -19,9 +19,9 @@ function kitOf(extensions) {
|
|
|
19
19
|
function blocksToHTML(blocks, extensions) {
|
|
20
20
|
return writeHTML(blocks, kitOf(extensions));
|
|
21
21
|
}
|
|
22
|
-
/** Read HTML as blocks with the given extensions. Needs `DOMParser
|
|
23
|
-
function htmlToBlocks(html, extensions) {
|
|
24
|
-
return parseHTML(html, kitOf(extensions));
|
|
22
|
+
/** Read HTML as blocks with the given extensions. Needs a `DOMParser`: the browser's, or `options.domParser`. */
|
|
23
|
+
function htmlToBlocks(html, extensions, options = {}) {
|
|
24
|
+
return parseHTML(html, kitOf(extensions), options.domParser);
|
|
25
25
|
}
|
|
26
26
|
export { blocksToHTML, htmlToBlocks, kitOf };
|
|
27
27
|
|
package/dist/core/convert.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"convert.js","names":[],"sources":["../../src/core/convert.ts"],"sourcesContent":["import {\n resolveEditorExtensions,\n type EditorExtension,\n type ResolvedEditorExtensions,\n} from './extension'\nimport type { Block, PartialBlock } from './model'\nimport { writeHTML } from './output'\nimport { parseHTML } from './prepare'\n\nexport type EditorExtensionList = readonly (EditorExtension | EditorExtension[])[]\n\nconst resolved = new WeakMap<EditorExtensionList, ResolvedEditorExtensions>()\n\n/** Resolve a list of extensions once; the same array gives the same result. */\nexport function kitOf(extensions: EditorExtensionList): ResolvedEditorExtensions {\n let kit = resolved.get(extensions)\n if (!kit) {\n kit = resolveEditorExtensions(extensions)\n resolved.set(extensions, kit)\n }\n return kit\n}\n\n/**\n * Write blocks as HTML with the given extensions, e.g. to show a document\n * outside the editor. Works without a browser.\n */\nexport function blocksToHTML(blocks: PartialBlock[], extensions: EditorExtensionList): string {\n return writeHTML(blocks, kitOf(extensions))\n}\n\n/** Read HTML as blocks with the given extensions. Needs `DOMParser
|
|
1
|
+
{"version":3,"file":"convert.js","names":[],"sources":["../../src/core/convert.ts"],"sourcesContent":["import {\n resolveEditorExtensions,\n type EditorExtension,\n type ResolvedEditorExtensions,\n} from './extension'\nimport type { Block, PartialBlock } from './model'\nimport { writeHTML } from './output'\nimport { parseHTML, type DOMParserLike } from './prepare'\n\nexport type EditorExtensionList = readonly (EditorExtension | EditorExtension[])[]\n\nconst resolved = new WeakMap<EditorExtensionList, ResolvedEditorExtensions>()\n\n/** Resolve a list of extensions once; the same array gives the same result. */\nexport function kitOf(extensions: EditorExtensionList): ResolvedEditorExtensions {\n let kit = resolved.get(extensions)\n if (!kit) {\n kit = resolveEditorExtensions(extensions)\n resolved.set(extensions, kit)\n }\n return kit\n}\n\n/**\n * Write blocks as HTML with the given extensions, e.g. to show a document\n * outside the editor. Works without a browser.\n */\nexport function blocksToHTML(blocks: PartialBlock[], extensions: EditorExtensionList): string {\n return writeHTML(blocks, kitOf(extensions))\n}\n\nexport interface HTMLToBlocksOptions {\n /**\n * Reads the HTML. Defaults to the global `DOMParser`; where there is none\n * (Node, Bun), pass one from a DOM library such as happy-dom or linkedom.\n */\n domParser?: DOMParserLike\n}\n\n/** Read HTML as blocks with the given extensions. Needs a `DOMParser`: the browser's, or `options.domParser`. */\nexport function htmlToBlocks(\n html: string,\n extensions: EditorExtensionList,\n options: HTMLToBlocksOptions = {},\n): Block[] {\n return parseHTML(html, kitOf(extensions), options.domParser)\n}\n"],"mappings":";;;;AAWA,IAAM,2BAAW,IAAI,QAAuD;;AAG5E,SAAgB,MAAM,YAA2D;CAC/E,IAAI,MAAM,SAAS,IAAI,UAAU;CACjC,IAAI,CAAC,KAAK;EACR,MAAM,wBAAwB,UAAU;EACxC,SAAS,IAAI,YAAY,GAAG;CAC9B;CACA,OAAO;AACT;;;;;AAMA,SAAgB,aAAa,QAAwB,YAAyC;CAC5F,OAAO,UAAU,QAAQ,MAAM,UAAU,CAAC;AAC5C;;AAWA,SAAgB,aACd,MACA,YACA,UAA+B,CAAC,GACvB;CACT,OAAO,UAAU,MAAM,MAAM,UAAU,GAAG,QAAQ,SAAS;AAC7D"}
|
package/dist/core/editor.js
CHANGED
|
@@ -2,7 +2,7 @@ import { blocksToDoc, docToBlocks } from "./model.js";
|
|
|
2
2
|
import { blockSelectionPlugin } from "./block-selection.js";
|
|
3
3
|
import { editorInputRules } from "./input-rules.js";
|
|
4
4
|
import { editorKeymap } from "./keymap.js";
|
|
5
|
-
import { idPlugin, placeholderPlugin } from "./plugins.js";
|
|
5
|
+
import { idPlugin, listPlugin, placeholderPlugin } from "./plugins.js";
|
|
6
6
|
import { preparePastePlugin } from "./prepare.js";
|
|
7
7
|
import { keymap } from "prosemirror-keymap";
|
|
8
8
|
import { EditorState, Plugin, PluginKey } from "prosemirror-state";
|
|
@@ -52,6 +52,7 @@ function createPlugins(options) {
|
|
|
52
52
|
...builtInHistory ? [history()] : [],
|
|
53
53
|
preparePastePlugin(kit),
|
|
54
54
|
idPlugin(),
|
|
55
|
+
listPlugin(),
|
|
55
56
|
placeholderPlugin(options.placeholder)
|
|
56
57
|
];
|
|
57
58
|
}
|
package/dist/core/editor.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"editor.js","names":[],"sources":["../../src/core/editor.ts"],"sourcesContent":["import { baseKeymap } from 'prosemirror-commands'\nimport { history, redo, undo } from 'prosemirror-history'\nimport { keymap } from 'prosemirror-keymap'\nimport type { Node as PMNode } from 'prosemirror-model'\nimport { EditorState, Plugin, PluginKey, type Command, type Transaction } from 'prosemirror-state'\nimport { EditorView, type NodeViewConstructor } from 'prosemirror-view'\nimport { blockSelectionPlugin } from './block-selection'\nimport type { ResolvedEditorExtensions } from './extension'\nimport { editorInputRules } from './input-rules'\nimport { editorKeymap, type KeymapOptions } from './keymap'\nimport { blocksToDoc, docToBlocks, type Block, type PartialBlock } from './model'\nimport { idPlugin, placeholderPlugin, type PlaceholderOptions } from './plugins'\nimport { preparePastePlugin } from './prepare'\n\nexport interface CreateEditorOptions {\n /** Where the editor goes. */\n element: HTMLElement\n /** The resolved extensions: schema, plugins, node views. */\n kit: ResolvedEditorExtensions\n /** More node views, e.g. ones that render Vue components. */\n nodeViews?: Record<string, NodeViewConstructor>\n blocks?: PartialBlock[]\n editable?: boolean\n placeholder: PlaceholderOptions\n /** Called after each change to the document, with the transaction and the state before it. */\n onChange?: (view: EditorView, tr: Transaction, before: EditorState) => void\n /** Called after every state change, including the selection. */\n onUpdate?: (view: EditorView, before: EditorState) => void\n /**\n * Extra plugins, placed before the built-in ones so their keys win.\n * The collaboration extension adds its sync and cursor plugins here.\n */\n plugins?: Plugin[]\n /**\n * Key plugins placed after the extensions' keys, so an extension can\n * take one of their keys, and before the built-in ones.\n */\n keymaps?: Plugin[]\n /** Leave out the built-in undo history (collaboration brings its own). */\n history?: boolean\n undo?: KeymapOptions['undo']\n redo?: KeymapOptions['redo']\n /** Attributes for the editable element, e.g. an accessible name. */\n attributes?: () => Record<string, string>\n}\n\n/** The transaction meta that names who made a change, for the `transaction` event. */\nexport const originKey = 'douOrigin'\n\nconst historyKey = new PluginKey<{ undo: Command; redo: Command }>('douHistory')\n\n/**\n * The undo and redo the editor runs: the built-in history's, or those of\n * the extension or props that replace it. For node views that edit their\n * text themselves, so their undo is the document's.\n */\nexport function historyCommands(state: EditorState): {\n undo: Command\n redo: Command\n} {\n return historyKey.getState(state) ?? { undo, redo }\n}\n\nexport function createPlugins(options: Omit<CreateEditorOptions, 'element'>): Plugin[] {\n const { kit } = options\n const provider = kit.history\n const builtInHistory = options.history !== false && !provider\n const commands = {\n undo: options.undo ?? provider?.undo ?? undo,\n redo: options.redo ?? provider?.redo ?? redo,\n }\n return [\n new Plugin({\n key: historyKey,\n state: { init: () => commands, apply: (_tr, value) => value },\n }),\n ...(options.plugins ?? []),\n ...kit.plugins,\n editorInputRules(kit.inputRules),\n blockSelectionPlugin(),\n ...kit.keymaps.map((bindings) => keymap(bindings)),\n ...(options.keymaps ?? []),\n editorKeymap(commands),\n keymap(baseKeymap),\n ...(provider?.plugins ?? []),\n ...(builtInHistory ? [history()] : []),\n preparePastePlugin(kit),\n idPlugin(),\n placeholderPlugin(options.placeholder),\n ]\n}\n\nexport function createState(\n kit: ResolvedEditorExtensions,\n blocks: PartialBlock[] | undefined,\n plugins: Plugin[],\n): EditorState {\n return EditorState.create({\n schema: kit.schema,\n doc: blocksToDoc(kit.schema, blocks ?? []),\n plugins,\n })\n}\n\nconst viewNodeViews = new WeakMap<EditorView, Record<string, NodeViewConstructor>>()\n\n/** Fresh functions, so the view redraws every node view (e.g. after `editable` changes). */\nconst fresh = (nodeViews: Record<string, NodeViewConstructor>) =>\n Object.fromEntries(\n Object.entries(nodeViews).map(([name, create]) => [\n name,\n ((...args) => create(...args)) as NodeViewConstructor,\n ]),\n )\n\nexport function createEditorView(options: CreateEditorOptions): EditorView {\n const editable = options.editable ?? true\n const plugins = createPlugins(options)\n const nodeViews = { ...options.kit.nodeViews, ...options.nodeViews }\n const view: EditorView = new EditorView(options.element, {\n state: createState(options.kit, options.blocks, plugins),\n editable: () => editable,\n nodeViews: fresh(nodeViews),\n attributes: () => ({\n class: 'dou-editor__surface',\n role: 'textbox',\n 'aria-multiline': 'true',\n ...options.attributes?.(),\n }),\n // `this`, not `view`: plugins (e.g. collaboration) dispatch while the view is being created\n dispatchTransaction(this: EditorView, tr) {\n const before = this.state\n const next = before.apply(tr)\n this.updateState(next)\n if (next.doc !== before.doc) options.onChange?.(this, tr, before)\n options.onUpdate?.(this, before)\n },\n })\n viewNodeViews.set(view, nodeViews)\n return view\n}\n\nexport function setEditable(view: EditorView, value: boolean) {\n // node views draw controls (checkboxes…) that are disabled while read-only\n view.setProps({ editable: () => value, nodeViews: fresh(viewNodeViews.get(view) ?? {}) })\n}\n\n/** Replace the whole document, e.g. when `v-model` changes from outside. */\nexport function replaceBlocks(view: EditorView, blocks: PartialBlock[]) {\n const state = view.state\n const doc = blocksToDoc(state.schema, blocks)\n const tr = state.tr.replaceWith(0, state.doc.content.size, doc.content)\n tr.setMeta('addToHistory', false)\n tr.setMeta(originKey, 'external')\n view.dispatch(tr)\n}\n\n/**\n * Replace the document with `blocks` as one change undo takes back, e.g.\n * an older version. Only what differs is replaced, so the blocks that stay\n * keep their place, and with collaboration only they are written.\n */\nexport function restoreBlocks(view: EditorView, blocks: PartialBlock[]) {\n const state = view.state\n const next = blocksToDoc(state.schema, blocks)\n const start = state.doc.content.findDiffStart(next.content)\n if (start === null) return false\n const end = state.doc.content.findDiffEnd(next.content)!\n // the two ends can cross where the same text repeats: widen them to agree\n const overlap = start - Math.min(end.a, end.b)\n if (overlap > 0) {\n end.a += overlap\n end.b += overlap\n }\n view.dispatch(\n state.tr\n .replace(start, end.a, next.slice(start, end.b))\n .setMeta(originKey, 'restore')\n .scrollIntoView(),\n )\n return true\n}\n\nexport function getBlocks(view: EditorView): Block[] {\n return docToBlocks(view.state.doc)\n}\n\nexport function runCommand(view: EditorView, command: Command): boolean {\n return command(view.state, view.dispatch, view)\n}\n\nexport type { PMNode }\n"],"mappings":";;;;;;;;;;;;;AA+CA,IAAa,YAAY;AAEzB,IAAM,aAAa,IAAI,UAA4C,YAAY;;;;;;AAO/E,SAAgB,gBAAgB,OAG9B;CACA,OAAO,WAAW,SAAS,KAAK,KAAK;EAAE;EAAM;CAAK;AACpD;AAEA,SAAgB,cAAc,SAAyD;CACrF,MAAM,EAAE,QAAQ;CAChB,MAAM,WAAW,IAAI;CACrB,MAAM,iBAAiB,QAAQ,YAAY,SAAS,CAAC;CACrD,MAAM,WAAW;E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B,eAAe,CACpB;CACA,OAAO;AACT;AAEA,SAAgB,UAAU,MAA2B;CACnD,OAAO,YAAY,KAAK,MAAM,GAAG;AACnC;AAEA,SAAgB,WAAW,MAAkB,SAA2B;CACtE,OAAO,QAAQ,KAAK,OAAO,KAAK,UAAU,IAAI;AAChD"}
|
|
1
|
+
{"version":3,"file":"editor.js","names":[],"sources":["../../src/core/editor.ts"],"sourcesContent":["import { baseKeymap } from 'prosemirror-commands'\nimport { history, redo, undo } from 'prosemirror-history'\nimport { keymap } from 'prosemirror-keymap'\nimport type { Node as PMNode } from 'prosemirror-model'\nimport { EditorState, Plugin, PluginKey, type Command, type Transaction } from 'prosemirror-state'\nimport { EditorView, type NodeViewConstructor } from 'prosemirror-view'\nimport { blockSelectionPlugin } from './block-selection'\nimport type { ResolvedEditorExtensions } from './extension'\nimport { editorInputRules } from './input-rules'\nimport { editorKeymap, type KeymapOptions } from './keymap'\nimport { blocksToDoc, docToBlocks, type Block, type PartialBlock } from './model'\nimport { idPlugin, listPlugin, placeholderPlugin, type PlaceholderOptions } from './plugins'\nimport { preparePastePlugin } from './prepare'\n\nexport interface CreateEditorOptions {\n /** Where the editor goes. */\n element: HTMLElement\n /** The resolved extensions: schema, plugins, node views. */\n kit: ResolvedEditorExtensions\n /** More node views, e.g. ones that render Vue components. */\n nodeViews?: Record<string, NodeViewConstructor>\n blocks?: PartialBlock[]\n editable?: boolean\n placeholder: PlaceholderOptions\n /** Called after each change to the document, with the transaction and the state before it. */\n onChange?: (view: EditorView, tr: Transaction, before: EditorState) => void\n /** Called after every state change, including the selection. */\n onUpdate?: (view: EditorView, before: EditorState) => void\n /**\n * Extra plugins, placed before the built-in ones so their keys win.\n * The collaboration extension adds its sync and cursor plugins here.\n */\n plugins?: Plugin[]\n /**\n * Key plugins placed after the extensions' keys, so an extension can\n * take one of their keys, and before the built-in ones.\n */\n keymaps?: Plugin[]\n /** Leave out the built-in undo history (collaboration brings its own). */\n history?: boolean\n undo?: KeymapOptions['undo']\n redo?: KeymapOptions['redo']\n /** Attributes for the editable element, e.g. an accessible name. */\n attributes?: () => Record<string, string>\n}\n\n/** The transaction meta that names who made a change, for the `transaction` event. */\nexport const originKey = 'douOrigin'\n\nconst historyKey = new PluginKey<{ undo: Command; redo: Command }>('douHistory')\n\n/**\n * The undo and redo the editor runs: the built-in history's, or those of\n * the extension or props that replace it. For node views that edit their\n * text themselves, so their undo is the document's.\n */\nexport function historyCommands(state: EditorState): {\n undo: Command\n redo: Command\n} {\n return historyKey.getState(state) ?? { undo, redo }\n}\n\nexport function createPlugins(options: Omit<CreateEditorOptions, 'element'>): Plugin[] {\n const { kit } = options\n const provider = kit.history\n const builtInHistory = options.history !== false && !provider\n const commands = {\n undo: options.undo ?? provider?.undo ?? undo,\n redo: options.redo ?? provider?.redo ?? redo,\n }\n return [\n new Plugin({\n key: historyKey,\n state: { init: () => commands, apply: (_tr, value) => value },\n }),\n ...(options.plugins ?? []),\n ...kit.plugins,\n editorInputRules(kit.inputRules),\n blockSelectionPlugin(),\n ...kit.keymaps.map((bindings) => keymap(bindings)),\n ...(options.keymaps ?? []),\n editorKeymap(commands),\n keymap(baseKeymap),\n ...(provider?.plugins ?? []),\n ...(builtInHistory ? [history()] : []),\n preparePastePlugin(kit),\n idPlugin(),\n listPlugin(),\n placeholderPlugin(options.placeholder),\n ]\n}\n\nexport function createState(\n kit: ResolvedEditorExtensions,\n blocks: PartialBlock[] | undefined,\n plugins: Plugin[],\n): EditorState {\n return EditorState.create({\n schema: kit.schema,\n doc: blocksToDoc(kit.schema, blocks ?? []),\n plugins,\n })\n}\n\nconst viewNodeViews = new WeakMap<EditorView, Record<string, NodeViewConstructor>>()\n\n/** Fresh functions, so the view redraws every node view (e.g. after `editable` changes). */\nconst fresh = (nodeViews: Record<string, NodeViewConstructor>) =>\n Object.fromEntries(\n Object.entries(nodeViews).map(([name, create]) => [\n name,\n ((...args) => create(...args)) as NodeViewConstructor,\n ]),\n )\n\nexport function createEditorView(options: CreateEditorOptions): EditorView {\n const editable = options.editable ?? true\n const plugins = createPlugins(options)\n const nodeViews = { ...options.kit.nodeViews, ...options.nodeViews }\n const view: EditorView = new EditorView(options.element, {\n state: createState(options.kit, options.blocks, plugins),\n editable: () => editable,\n nodeViews: fresh(nodeViews),\n attributes: () => ({\n class: 'dou-editor__surface',\n role: 'textbox',\n 'aria-multiline': 'true',\n ...options.attributes?.(),\n }),\n // `this`, not `view`: plugins (e.g. collaboration) dispatch while the view is being created\n dispatchTransaction(this: EditorView, tr) {\n const before = this.state\n const next = before.apply(tr)\n this.updateState(next)\n if (next.doc !== before.doc) options.onChange?.(this, tr, before)\n options.onUpdate?.(this, before)\n },\n })\n viewNodeViews.set(view, nodeViews)\n return view\n}\n\nexport function setEditable(view: EditorView, value: boolean) {\n // node views draw controls (checkboxes…) that are disabled while read-only\n view.setProps({ editable: () => value, nodeViews: fresh(viewNodeViews.get(view) ?? {}) })\n}\n\n/** Replace the whole document, e.g. when `v-model` changes from outside. */\nexport function replaceBlocks(view: EditorView, blocks: PartialBlock[]) {\n const state = view.state\n const doc = blocksToDoc(state.schema, blocks)\n const tr = state.tr.replaceWith(0, state.doc.content.size, doc.content)\n tr.setMeta('addToHistory', false)\n tr.setMeta(originKey, 'external')\n view.dispatch(tr)\n}\n\n/**\n * Replace the document with `blocks` as one change undo takes back, e.g.\n * an older version. Only what differs is replaced, so the blocks that stay\n * keep their place, and with collaboration only they are written.\n */\nexport function restoreBlocks(view: EditorView, blocks: PartialBlock[]) {\n const state = view.state\n const next = blocksToDoc(state.schema, blocks)\n const start = state.doc.content.findDiffStart(next.content)\n if (start === null) return false\n const end = state.doc.content.findDiffEnd(next.content)!\n // the two ends can cross where the same text repeats: widen them to agree\n const overlap = start - Math.min(end.a, end.b)\n if (overlap > 0) {\n end.a += overlap\n end.b += overlap\n }\n view.dispatch(\n state.tr\n .replace(start, end.a, next.slice(start, end.b))\n .setMeta(originKey, 'restore')\n .scrollIntoView(),\n )\n return true\n}\n\nexport function getBlocks(view: EditorView): Block[] {\n return docToBlocks(view.state.doc)\n}\n\nexport function runCommand(view: EditorView, command: Command): boolean {\n return command(view.state, view.dispatch, view)\n}\n\nexport type { PMNode }\n"],"mappings":";;;;;;;;;;;;;AA+CA,IAAa,YAAY;AAEzB,IAAM,aAAa,IAAI,UAA4C,YAAY;;;;;;AAO/E,SAAgB,gBAAgB,OAG9B;CACA,OAAO,WAAW,SAAS,KAAK,KAAK;EAAE;EAAM;CAAK;AACpD;AAEA,SAAgB,cAAc,SAAyD;CACrF,MAAM,EAAE,QAAQ;CAChB,MAAM,WAAW,IAAI;CACrB,MAAM,iBAAiB,QAAQ,YAAY,SAAS,CAAC;CACrD,MAAM,WAAW;EACf,MAAM,QAAQ,QAAQ,UAAU,QAAQ;EACxC,MAAM,QAAQ,QAAQ,UAAU,QAAQ;CAC1C;CACA,OAAO;EACL,IAAI,OAAO;GACT,KAAK;GACL,OAAO;IAAE,YAAY;IAAU,QAAQ,KAAK,UAAU;GAAM;EAC9D,CAAC;EACD,GAAI,QAAQ,WAAW,CAAC;EACxB,GAAG,IAAI;EACP,iBAAiB,IAAI,UAAU;EAC/B,qBAAqB;EACrB,GAAG,IAAI,QAAQ,KAAK,aAAa,OAAO,QAAQ,CAAC;EACjD,GAAI,QAAQ,WAAW,CAAC;EACxB,aAAa,QAAQ;EACrB,OAAO,UAAU;EACjB,GAAI,UAAU,WAAW,CAAC;EAC1B,GAAI,iBAAiB,CAAC,QAAQ,CAAC,IAAI,CAAC;EACpC,mBAAmB,GAAG;EACtB,SAAS;EACT,WAAW;EACX,kBAAkB,QAAQ,WAAW;CACvC;AACF;AAEA,SAAgB,YACd,KACA,QACA,SACa;CACb,OAAO,YAAY,OAAO;EACxB,QAAQ,IAAI;EACZ,KAAK,YAAY,IAAI,QAAQ,UAAU,CAAC,CAAC;EACzC;CACF,CAAC;AACH;AAEA,IAAM,gCAAgB,IAAI,QAAyD;;AAGnF,IAAM,SAAS,cACb,OAAO,YACL,OAAO,QAAQ,SAA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B,MAAM,OAAO,YAAY,MAAM,QAAQ,MAAM;CAC7C,MAAM,QAAQ,MAAM,IAAI,QAAQ,cAAc,KAAK,OAAO;CAC1D,IAAI,UAAU,MAAM,OAAO;CAC3B,MAAM,MAAM,MAAM,IAAI,QAAQ,YAAY,KAAK,OAAO;CAEtD,MAAM,UAAU,QAAQ,KAAK,IAAI,IAAI,GAAG,IAAI,CAAC;CAC7C,IAAI,UAAU,GAAG;EACf,IAAI,KAAK;EACT,IAAI,KAAK;CACX;CACA,KAAK,SACH,MAAM,GACH,QAAQ,OAAO,IAAI,GAAG,KAAK,MAAM,OAAO,IAAI,CAAC,CAAC,CAAC,CAC/C,QAAQ,WAAW,SAAS,CAAC,CAC7B,eAAe,CACpB;CACA,OAAO;AACT;AAEA,SAAgB,UAAU,MAA2B;CACnD,OAAO,YAAY,KAAK,MAAM,GAAG;AACnC;AAEA,SAAgB,WAAW,MAAkB,SAA2B;CACtE,OAAO,QAAQ,KAAK,OAAO,KAAK,UAAU,IAAI;AAChD"}
|
package/dist/core/extension.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { editorLocales } from "../locale.js";
|
|
1
2
|
import { createSchema } from "./schema.js";
|
|
2
3
|
import { parseHotkey } from "dou-ui";
|
|
3
4
|
// src/core/extension.ts
|
|
@@ -46,7 +47,7 @@ function merge(target, source, what, owner) {
|
|
|
46
47
|
}
|
|
47
48
|
}
|
|
48
49
|
/** Sort the extensions by priority, build the schema and collect what they add. */
|
|
49
|
-
function resolveEditorExtensions(list) {
|
|
50
|
+
function resolveEditorExtensions(list, messages = () => editorLocales["zh-CN"]) {
|
|
50
51
|
const extensions = flatten(list).map((extension, index) => ({
|
|
51
52
|
extension,
|
|
52
53
|
index
|
|
@@ -70,7 +71,10 @@ function resolveEditorExtensions(list) {
|
|
|
70
71
|
inlines,
|
|
71
72
|
marks
|
|
72
73
|
});
|
|
73
|
-
const context = {
|
|
74
|
+
const context = {
|
|
75
|
+
schema,
|
|
76
|
+
messages
|
|
77
|
+
};
|
|
74
78
|
const providers = extensions.filter((extension) => extension.history);
|
|
75
79
|
if (providers.length > 1) throw new Error("[@dou-ui/editor] only one extension may replace the undo history");
|
|
76
80
|
const keepers = extensions.filter((extension) => extension.comments);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extension.js","names":[],"sources":["../../src/core/extension.ts"],"sourcesContent":["import type { InputRule } from 'prosemirror-inputrules'\nimport type { MarkSpec, NodeSpec, Schema } from 'prosemirror-model'\nimport type { Command, Plugin } from 'prosemirror-state'\nimport type { NodeViewConstructor } from 'prosemirror-view'\nimport { parseHotkey, type CommentAction, type CommentThread } from 'dou-ui'\nimport type { Component, Ref } from 'vue'\nimport type { EditorMessages } from '../locale'\nimport type { BlockProps } from './model'\nimport type { EditorExtensionOutput } from './output'\nimport { createSchema } from './schema'\n\n/** Text shown in a menu: fixed, or read from the editor's messages so it follows the locale. */\nexport type Label = string | ((messages: EditorMessages) => string)\n\nexport const labelOf = (label: Label | undefined, messages: EditorMessages) =>\n typeof label === 'function' ? label(messages) : (label ?? '')\n\n/** An entry of the slash menu and of the “turn into” menus. */\nexport interface BlockOption {\n /** Unique among the options. */\n key: string\n /** The block type it inserts or turns blocks into. */\n type: string\n props?: BlockProps\n label: Label\n /** A short description under the label in the slash menu. */\n hint?: Label\n icon: Component\n /** Extra words the slash menu matches, besides the label (pinyin works well). */\n keywords?: string[]\n /** The Markdown shortcut, shown as a hint. */\n shortcut?: string\n}\n\n/** A toggle in the formatting toolbar for a mark. */\nexport interface FormatOption {\n mark: string\n label: Label\n icon: Component\n /** The shortcut shown in its tooltip, written as in `useHotkey`, e.g. `mod+b`. */\n hotkey?: string\n}\n\n/** Where the comment threads live, when not in `v-model:comments`. */\nexport interface CommentsProvider {\n /** The threads, kept up to date. */\n threads: Readonly<Ref<readonly CommentThread[]>>\n /** Make a change this user asked for. */\n apply: (action: CommentAction) => void\n}\n\nexport interface EditorExtensionContext {\n schema: Schema\n}\n\n/** What the extension replacing the undo history provides (e.g. collaboration). */\nexport interface HistoryProvider {\n plugins: Plugin[]\n undo: Command\n redo: Command\n}\n\n/**\n * A piece of the editor: block types, marks, behaviour and menu entries.\n * The built-in blocks are extensions too (see `editorKit`).\n */\nexport interface EditorExtension {\n name: string\n /** Higher runs first: its keys, input rules and plugins win. Defaults to 100. */\n priority?: number\n /**\n * Content node specs for new block types, by type name. They join the\n * `blockContent` group. Extra spec fields the editor reads:\n * `continues` (Enter continues the same type, like a list) and\n * `component` (a Vue component that renders the block).\n */\n blocks?: Record<string, NodeSpec>\n /**\n * Nodes that only live inside the extension's blocks, e.g. a table's\n * rows and cells. They join no group.\n */\n nodes?: Record<string, NodeSpec>\n /** Inline nodes, e.g. a mention. */\n inlines?: Record<string, NodeSpec>\n marks?: Record<string, MarkSpec>\n nodeViews?: Record<string, NodeViewConstructor>\n /**\n * Node views that draw Vue components, by node type. Each is made with\n * `mount`, which renders a component into an element inside the editor's\n * app, so it can call `useEditor()` and follows the ConfigProvider.\n */\n componentViews?: Record<string, (mount: MountComponent) => NodeViewConstructor>\n inputRules?: (context: EditorExtensionContext) => InputRule[]\n /**\n * Keys, written as in `useHotkey` (e.g. `mod+shift+h`, `shift+tab`,\n * `enter`), while the editor has focus. A command returning `false` lets\n * the key through to the next extension.\n */\n keymap?: (context: EditorExtensionContext) => Record<string, Command>\n plugins?: (context: EditorExtensionContext) => Plugin[]\n /**\n * The document lives outside the editor (e.g. in a Yjs document): the\n * initial `modelValue` and later outside changes to it are ignored, and\n * `v-model` only mirrors the document.\n */\n externalDocument?: boolean\n /** Replace the built-in undo history. Only one extension may. */\n history?: (context: EditorExtensionContext) => HistoryProvider\n /**\n * Keep the comment threads somewhere else than `v-model:comments`, e.g.\n * in a shared document. `v-model:comments` then only mirrors them.\n * Only one extension may.\n */\n comments?: (context: EditorExtensionContext) => CommentsProvider\n /** Entries for the slash menu and the “turn into” menus. */\n blockOptions?: BlockOption[]\n /** Toggles for the formatting toolbar. */\n formats?: FormatOption[]\n /**\n * Components rendered next to the editing area while it is editable,\n * e.g. a popup of suggestions. They can call `useEditor()`.\n */\n overlays?: Component[]\n /**\n * Controls added to the formatting toolbar, after the marks (e.g. a\n * color menu). They can call `useEditor()`.\n */\n toolbar?: Component[]\n /**\n * Entries added to the block menu of the handle, usually a\n * `DouDropdownSub` or `DouDropdownItem`s. Each gets the block the menu is\n * for as the `block` prop (a `Block`) and can call `useEditor()`.\n */\n blockMenu?: Component[]\n /**\n * How the extension's blocks, inline nodes and marks are written as HTML\n * and Markdown (`blocksToHTML`, `blocksToMarkdown`).\n */\n output?: EditorExtensionOutput\n /**\n * Rewrite HTML before it is read as blocks (when pasting, and in\n * `htmlToBlocks` and `markdownToBlocks`), e.g. turn a `<details>`\n * element into a toggle with its children. `blockElement` and\n * `splitContainer` help build the editor's markup.\n */\n prepareHTML?: (root: HTMLElement) => void\n}\n\n/**\n * Renders `component` into `element` with `props` (a reactive object stays\n * live), inside the editor's app. Returns a function that removes it.\n */\nexport type MountComponent = (\n component: Component,\n props: Record<string, unknown>,\n element: HTMLElement,\n) => () => void\n\n/** Declare an extension; only gives it a type. */\nexport function defineEditorExtension(extension: EditorExtension): EditorExtension {\n return extension\n}\n\n/** Everything the extensions contribute, gathered once per list of extensions. */\nexport interface ResolvedEditorExtensions {\n extensions: EditorExtension[]\n schema: Schema\n context: EditorExtensionContext\n nodeViews: Record<string, NodeViewConstructor>\n componentViews: Record<string, (mount: MountComponent) => NodeViewConstructor>\n blockOptions: BlockOption[]\n formats: FormatOption[]\n overlays: Component[]\n toolbar: Component[]\n blockMenu: Component[]\n inputRules: InputRule[]\n keymaps: Record<string, Command>[]\n plugins: Plugin[]\n history: HistoryProvider | null\n comments: CommentsProvider | null\n externalDocument: boolean\n}\n\nconst PM_KEYS: Record<string, string> = {\n ' ': 'Space',\n arrowup: 'ArrowUp',\n arrowdown: 'ArrowDown',\n arrowleft: 'ArrowLeft',\n arrowright: 'ArrowRight',\n pageup: 'PageUp',\n pagedown: 'PageDown',\n}\nconst PM_MODIFIERS: Record<string, string> = {\n mod: 'Mod',\n ctrl: 'Ctrl',\n alt: 'Alt',\n meta: 'Meta',\n shift: 'Shift',\n}\n\n/** `mod+shift+h` → `Mod-Shift-h`, the way the ProseMirror keymap names keys. */\nexport function toEditorKey(hotkey: string): string {\n const steps = parseHotkey(hotkey)\n if (steps.length !== 1)\n throw new Error(`[@dou-ui/editor] key sequences aren't supported in a keymap: \"${hotkey}\"`)\n const keys = steps[0]!\n const modifiers = Object.keys(PM_MODIFIERS)\n .filter((name) => keys.includes(name))\n .map((name) => PM_MODIFIERS[name])\n const key = keys.find((name) => !(name in PM_MODIFIERS)) ?? ''\n const name = PM_KEYS[key] ?? (key.length > 1 ? key[0]!.toUpperCase() + key.slice(1) : key)\n return [...modifiers, name].join('-')\n}\n\nconst toEditorKeymap = (bindings: Record<string, Command>) =>\n Object.fromEntries(Object.entries(bindings).map(([key, command]) => [toEditorKey(key), command]))\n\nfunction flatten(list: readonly (EditorExtension | EditorExtension[])[]): EditorExtension[] {\n const result: EditorExtension[] = []\n for (const item of list) {\n if (Array.isArray(item)) result.push(...flatten(item))\n else result.push(item)\n }\n return result\n}\n\nfunction merge<T>(\n target: Record<string, T>,\n source: Record<string, T> | undefined,\n what: string,\n owner: string,\n) {\n for (const [name, value] of Object.entries(source ?? {})) {\n if (name in target)\n throw new Error(`[@dou-ui/editor] ${what} \"${name}\" from \"${owner}\" is already defined`)\n target[name] = value\n }\n}\n\n/** Sort the extensions by priority, build the schema and collect what they add. */\nexport function resolveEditorExtensions(\n list: readonly (EditorExtension | EditorExtension[])[],\n): ResolvedEditorExtensions {\n const extensions = flatten(list)\n .map((extension, index) => ({ extension, index }))\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n .sort(\n (a, b) => (b.extension.priority ?? 100) - (a.extension.priority ?? 100) || a.index - b.index,\n )\n .map((entry) => entry.extension)\n\n const names = new Set<string>()\n const blocks: Record<string, NodeSpec> = {}\n const nodes: Record<string, NodeSpec> = {}\n const inlines: Record<string, NodeSpec> = {}\n const marks: Record<string, MarkSpec> = {}\n for (const extension of extensions) {\n if (names.has(extension.name))\n throw new Error(`[@dou-ui/editor] the extension \"${extension.name}\" is added twice`)\n names.add(extension.name)\n merge(blocks, extension.blocks, 'block type', extension.name)\n merge(nodes, extension.nodes, 'node', extension.name)\n merge(inlines, extension.inlines, 'inline node', extension.name)\n merge(marks, extension.marks, 'mark', extension.name)\n }\n const schema = createSchema({ blocks, nodes, inlines, marks })\n const context: EditorExtensionContext = { schema }\n\n const providers = extensions.filter((extension) => extension.history)\n if (providers.length > 1)\n throw new Error('[@dou-ui/editor] only one extension may replace the undo history')\n\n const keepers = extensions.filter((extension) => extension.comments)\n if (keepers.length > 1)\n throw new Error('[@dou-ui/editor] only one extension may keep the comment threads')\n\n return {\n extensions,\n schema,\n context,\n nodeViews: Object.assign({}, ...extensions.map((extension) => extension.nodeViews ?? {})),\n componentViews: Object.assign(\n {},\n ...extensions.map((extension) => extension.componentViews ?? {}),\n ),\n blockOptions: extensions.flatMap((extension) => extension.blockOptions ?? []),\n formats: extensions.flatMap((extension) => extension.formats ?? []),\n overlays: extensions.flatMap((extension) => extension.overlays ?? []),\n toolbar: extensions.flatMap((extension) => extension.toolbar ?? []),\n blockMenu: extensions.flatMap((extension) => extension.blockMenu ?? []),\n inputRules: extensions.flatMap((extension) => extension.inputRules?.(context) ?? []),\n keymaps: extensions.flatMap((extension) =>\n extension.keymap ? [toEditorKeymap(extension.keymap(context))] : [],\n ),\n plugins: extensions.flatMap((extension) => extension.plugins?.(context) ?? []),\n history: providers[0]?.history?.(context) ?? null,\n comments: keepers[0]?.comments?.(context) ?? null,\n externalDocument: extensions.some((extension) => extension.externalDocument),\n }\n}\n"],"mappings":";;;AAcA,IAAa,WAAW,OAA0B,aAChD,OAAO,UAAU,aAAa,MAAM,QAAQ,IAAK,SAAS;;AAgJ5D,SAAgB,sBAAsB,WAA6C;CACjF,OAAO;AACT;AA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AAG,WAAW,KAAK,cAAc,UAAU,kBAAkB,CAAC,CAAC,CACjE;EACA,cAAc,WAAW,SAAS,cAAc,UAAU,gBAAgB,CAAC,CAAC;EAC5E,SAAS,WAAW,SAAS,cAAc,UAAU,WAAW,CAAC,CAAC;EAClE,UAAU,WAAW,SAAS,cAAc,UAAU,YAAY,CAAC,CAAC;EACpE,SAAS,WAAW,SAAS,cAAc,UAAU,WAAW,CAAC,CAAC;EAClE,WAAW,WAAW,SAAS,cAAc,UAAU,aAAa,CAAC,CAAC;EACtE,YAAY,WAAW,SAAS,cAAc,UAAU,aAAa,OAAO,KAAK,CAAC,CAAC;EACnF,SAAS,WAAW,SAAS,cAC3B,UAAU,SAAS,CAAC,eAAe,UAAU,OAAO,OAAO,CAAC,CAAC,IAAI,CAAC,CACpE;EACA,SAAS,WAAW,SAAS,cAAc,UAAU,UAAU,OAAO,KAAK,CAAC,CAAC;EAC7E,SAAS,UAAU,EAAE,EAAE,UAAU,OAAO,KAAK;EAC7C,UAAU,QAAQ,EAAE,EAAE,WAAW,OAAO,KAAK;EAC7C,kBAAkB,WAAW,MAAM,cAAc,UAAU,gBAAgB;CAC7E;AACF"}
|
|
1
|
+
{"version":3,"file":"extension.js","names":[],"sources":["../../src/core/extension.ts"],"sourcesContent":["import type { InputRule } from 'prosemirror-inputrules'\nimport type { MarkSpec, NodeSpec, Schema } from 'prosemirror-model'\nimport type { Command, Plugin } from 'prosemirror-state'\nimport type { NodeViewConstructor } from 'prosemirror-view'\nimport { parseHotkey, type CommentAction, type CommentThread } from 'dou-ui'\nimport type { Component, Ref } from 'vue'\nimport { editorLocales, type EditorMessages } from '../locale'\nimport type { BlockProps } from './model'\nimport type { EditorExtensionOutput } from './output'\nimport { createSchema } from './schema'\n\n/** Text shown in a menu: fixed, or read from the editor's messages so it follows the locale. */\nexport type Label = string | ((messages: EditorMessages) => string)\n\nexport const labelOf = (label: Label | undefined, messages: EditorMessages) =>\n typeof label === 'function' ? label(messages) : (label ?? '')\n\n/** An entry of the slash menu and of the “turn into” menus. */\nexport interface BlockOption {\n /** Unique among the options. */\n key: string\n /** The block type it inserts or turns blocks into. */\n type: string\n props?: BlockProps\n label: Label\n /** A short description under the label in the slash menu. */\n hint?: Label\n icon: Component\n /** Extra words the slash menu matches, besides the label (pinyin works well). */\n keywords?: string[]\n /** The Markdown shortcut, shown as a hint. */\n shortcut?: string\n /**\n * Variants to pick from in a panel beside the option in the slash menu,\n * e.g. how many columns. Choosing the option itself inserts the first.\n */\n choices?: BlockOptionChoices\n}\n\n/** One variant of a slash menu option. */\nexport interface BlockOptionChoice {\n /** The props it inserts with, over the option's own. */\n props: BlockProps\n /** Its name, also read out by screen readers. */\n label: Label\n}\n\n/** The variants of a slash menu option, picked in a panel beside it. */\nexport interface BlockOptionChoices {\n /** The panel's title, e.g. “Number of columns”; also the name screen readers give the panel. */\n title: Label\n items: BlockOptionChoice[]\n /**\n * Draws the variants (the panel around them and its title are drawn by\n * the menu). It gets the props in `BlockOptionChoicesProps` and emits\n * `hover` and `choose` with an index, as in `BlockOptionChoicesEmits`.\n * Without it, the panel lists their names.\n */\n component?: Component<BlockOptionChoicesProps>\n}\n\n/** What the `component` of `BlockOptionChoices` gets. */\nexport interface BlockOptionChoicesProps {\n items: BlockOptionChoice[]\n /** The index of the highlighted variant; -1 while the option itself is highlighted. */\n active: number\n messages: EditorMessages\n /**\n * For screen readers: give the element of variant `index` the id\n * `${idPrefix}-${index}` and `role=\"option\"` (with `aria-selected`), so\n * the editor can point at the highlighted one.\n */\n idPrefix: string\n}\n\n/** What the `component` of `BlockOptionChoices` emits. */\nexport interface BlockOptionChoicesEmits {\n /** The pointer is on variant `index`. */\n hover: [index: number]\n /** Variant `index` is picked: the menu inserts it. */\n choose: [index: number]\n}\n\n/** A toggle in the formatting toolbar for a mark. */\nexport interface FormatOption {\n mark: string\n label: Label\n icon: Component\n /** The shortcut shown in its tooltip, written as in `useHotkey`, e.g. `mod+b`. */\n hotkey?: string\n}\n\n/** Where the comment threads live, when not in `v-model:comments`. */\nexport interface CommentsProvider {\n /** The threads, kept up to date. */\n threads: Readonly<Ref<readonly CommentThread[]>>\n /** Make a change this user asked for. */\n apply: (action: CommentAction) => void\n}\n\nexport interface EditorExtensionContext {\n schema: Schema\n /**\n * The editor's messages, in its current locale, for text a plugin puts\n * in the document's markup (e.g. a name for screen readers). Outside an\n * editor (converting documents) the Chinese ones.\n */\n messages: () => EditorMessages\n}\n\n/** What the extension replacing the undo history provides (e.g. collaboration). */\nexport interface HistoryProvider {\n plugins: Plugin[]\n undo: Command\n redo: Command\n}\n\n/**\n * A piece of the editor: block types, marks, behaviour and menu entries.\n * The built-in blocks are extensions too (see `editorKit`).\n */\nexport interface EditorExtension {\n name: string\n /** Higher runs first: its keys, input rules and plugins win. Defaults to 100. */\n priority?: number\n /**\n * Content node specs for new block types, by type name. They join the\n * `blockContent` group. Extra spec fields the editor reads:\n * `continues` (Enter continues the same type, like a list),\n * `component` (a Vue component that renders the block) and\n * `mergeProps` (props holding lists of `{ id }` items that collaboration\n * merges item by item, by prop name: the fields that are such lists,\n * e.g. `{ board: ['nodes', 'edges'] }`).\n */\n blocks?: Record<string, NodeSpec>\n /**\n * Nodes that only live inside the extension's blocks, e.g. a table's\n * rows and cells. They join no group.\n */\n nodes?: Record<string, NodeSpec>\n /** Inline nodes, e.g. a mention. */\n inlines?: Record<string, NodeSpec>\n marks?: Record<string, MarkSpec>\n nodeViews?: Record<string, NodeViewConstructor>\n /**\n * Node views that draw Vue components, by node type. Each is made with\n * `mount`, which renders a component into an element inside the editor's\n * app, so it can call `useEditor()` and follows the ConfigProvider.\n */\n componentViews?: Record<string, (mount: MountComponent) => NodeViewConstructor>\n inputRules?: (context: EditorExtensionContext) => InputRule[]\n /**\n * Keys, written as in `useHotkey` (e.g. `mod+shift+h`, `shift+tab`,\n * `enter`), while the editor has focus. A command returning `false` lets\n * the key through to the next extension.\n */\n keymap?: (context: EditorExtensionContext) => Record<string, Command>\n plugins?: (context: EditorExtensionContext) => Plugin[]\n /**\n * The document lives outside the editor (e.g. in a Yjs document): the\n * initial `modelValue` and later outside changes to it are ignored, and\n * `v-model` only mirrors the document.\n */\n externalDocument?: boolean\n /** Replace the built-in undo history. Only one extension may. */\n history?: (context: EditorExtensionContext) => HistoryProvider\n /**\n * Keep the comment threads somewhere else than `v-model:comments`, e.g.\n * in a shared document. `v-model:comments` then only mirrors them.\n * Only one extension may.\n */\n comments?: (context: EditorExtensionContext) => CommentsProvider\n /** Entries for the slash menu and the “turn into” menus. */\n blockOptions?: BlockOption[]\n /** Toggles for the formatting toolbar. */\n formats?: FormatOption[]\n /**\n * Components rendered next to the editing area while it is editable,\n * e.g. a popup of suggestions. They can call `useEditor()`.\n */\n overlays?: Component[]\n /**\n * Controls added to the formatting toolbar, after the marks (e.g. a\n * color menu). They can call `useEditor()`.\n */\n toolbar?: Component[]\n /**\n * Entries added to the block menu of the handle, usually a\n * `DouDropdownSub` or `DouDropdownItem`s. Each gets the block the menu is\n * for as the `block` prop (a `Block`) and can call `useEditor()`.\n */\n blockMenu?: Component[]\n /**\n * How the extension's blocks, inline nodes and marks are written as HTML\n * and Markdown (`blocksToHTML`, `blocksToMarkdown`).\n */\n output?: EditorExtensionOutput\n /**\n * Rewrite HTML before it is read as blocks (when pasting, and in\n * `htmlToBlocks` and `markdownToBlocks`), e.g. turn a `<details>`\n * element into a toggle with its children. `blockElement` and\n * `splitContainer` help build the editor's markup.\n */\n prepareHTML?: (root: HTMLElement) => void\n}\n\n/**\n * Renders `component` into `element` with `props` (a reactive object stays\n * live), inside the editor's app. Returns a function that removes it.\n */\nexport type MountComponent = (\n component: Component,\n props: Record<string, unknown>,\n element: HTMLElement,\n) => () => void\n\n/** Declare an extension; only gives it a type. */\nexport function defineEditorExtension(extension: EditorExtension): EditorExtension {\n return extension\n}\n\n/** Everything the extensions contribute, gathered once per list of extensions. */\nexport interface ResolvedEditorExtensions {\n extensions: EditorExtension[]\n schema: Schema\n context: EditorExtensionContext\n nodeViews: Record<string, NodeViewConstructor>\n componentViews: Record<string, (mount: MountComponent) => NodeViewConstructor>\n blockOptions: BlockOption[]\n formats: FormatOption[]\n overlays: Component[]\n toolbar: Component[]\n blockMenu: Component[]\n inputRules: InputRule[]\n keymaps: Record<string, Command>[]\n plugins: Plugin[]\n history: HistoryProvider | null\n comments: CommentsProvider | null\n externalDocument: boolean\n}\n\nconst PM_KEYS: Record<string, string> = {\n ' ': 'Space',\n arrowup: 'ArrowUp',\n arrowdown: 'ArrowDown',\n arrowleft: 'ArrowLeft',\n arrowright: 'ArrowRight',\n pageup: 'PageUp',\n pagedown: 'PageDown',\n}\nconst PM_MODIFIERS: Record<string, string> = {\n mod: 'Mod',\n ctrl: 'Ctrl',\n alt: 'Alt',\n meta: 'Meta',\n shift: 'Shift',\n}\n\n/** `mod+shift+h` → `Mod-Shift-h`, the way the ProseMirror keymap names keys. */\nexport function toEditorKey(hotkey: string): string {\n const steps = parseHotkey(hotkey)\n if (steps.length !== 1)\n throw new Error(`[@dou-ui/editor] key sequences aren't supported in a keymap: \"${hotkey}\"`)\n const keys = steps[0]!\n const modifiers = Object.keys(PM_MODIFIERS)\n .filter((name) => keys.includes(name))\n .map((name) => PM_MODIFIERS[name])\n const key = keys.find((name) => !(name in PM_MODIFIERS)) ?? ''\n const name = PM_KEYS[key] ?? (key.length > 1 ? key[0]!.toUpperCase() + key.slice(1) : key)\n return [...modifiers, name].join('-')\n}\n\nconst toEditorKeymap = (bindings: Record<string, Command>) =>\n Object.fromEntries(Object.entries(bindings).map(([key, command]) => [toEditorKey(key), command]))\n\nfunction flatten(list: readonly (EditorExtension | EditorExtension[])[]): EditorExtension[] {\n const result: EditorExtension[] = []\n for (const item of list) {\n if (Array.isArray(item)) result.push(...flatten(item))\n else result.push(item)\n }\n return result\n}\n\nfunction merge<T>(\n target: Record<string, T>,\n source: Record<string, T> | undefined,\n what: string,\n owner: string,\n) {\n for (const [name, value] of Object.entries(source ?? {})) {\n if (name in target)\n throw new Error(`[@dou-ui/editor] ${what} \"${name}\" from \"${owner}\" is already defined`)\n target[name] = value\n }\n}\n\n/** Sort the extensions by priority, build the schema and collect what they add. */\nexport function resolveEditorExtensions(\n list: readonly (EditorExtension | EditorExtension[])[],\n messages: () => EditorMessages = () => editorLocales['zh-CN']!,\n): ResolvedEditorExtensions {\n const extensions = flatten(list)\n .map((extension, index) => ({ extension, index }))\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n .sort(\n (a, b) => (b.extension.priority ?? 100) - (a.extension.priority ?? 100) || a.index - b.index,\n )\n .map((entry) => entry.extension)\n\n const names = new Set<string>()\n const blocks: Record<string, NodeSpec> = {}\n const nodes: Record<string, NodeSpec> = {}\n const inlines: Record<string, NodeSpec> = {}\n const marks: Record<string, MarkSpec> = {}\n for (const extension of extensions) {\n if (names.has(extension.name))\n throw new Error(`[@dou-ui/editor] the extension \"${extension.name}\" is added twice`)\n names.add(extension.name)\n merge(blocks, extension.blocks, 'block type', extension.name)\n merge(nodes, extension.nodes, 'node', extension.name)\n merge(inlines, extension.inlines, 'inline node', extension.name)\n merge(marks, extension.marks, 'mark', extension.name)\n }\n const schema = createSchema({ blocks, nodes, inlines, marks })\n const context: EditorExtensionContext = { schema, messages }\n\n const providers = extensions.filter((extension) => extension.history)\n if (providers.length > 1)\n throw new Error('[@dou-ui/editor] only one extension may replace the undo history')\n\n const keepers = extensions.filter((extension) => extension.comments)\n if (keepers.length > 1)\n throw new Error('[@dou-ui/editor] only one extension may keep the comment threads')\n\n return {\n extensions,\n schema,\n context,\n nodeViews: Object.assign({}, ...extensions.map((extension) => extension.nodeViews ?? {})),\n componentViews: Object.assign(\n {},\n ...extensions.map((extension) => extension.componentViews ?? {}),\n ),\n blockOptions: extensions.flatMap((extension) => extension.blockOptions ?? []),\n formats: extensions.flatMap((extension) => extension.formats ?? []),\n overlays: extensions.flatMap((extension) => extension.overlays ?? []),\n toolbar: extensions.flatMap((extension) => extension.toolbar ?? []),\n blockMenu: extensions.flatMap((extension) => extension.blockMenu ?? []),\n inputRules: extensions.flatMap((extension) => extension.inputRules?.(context) ?? []),\n keymaps: extensions.flatMap((extension) =>\n extension.keymap ? [toEditorKeymap(extension.keymap(context))] : [],\n ),\n plugins: extensions.flatMap((extension) => extension.plugins?.(context) ?? []),\n history: providers[0]?.history?.(context) ?? null,\n comments: keepers[0]?.comments?.(context) ?? null,\n externalDocument: extensions.some((extension) => extension.externalDocument),\n }\n}\n"],"mappings":";;;;AAcA,IAAa,WAAW,OAA0B,aAChD,OAAO,UAAU,aAAa,MAAM,QAAQ,IAAK,SAAS;;AA0M5D,SAAgB,sBAAsB,WAA6C;CACjF,OAAO;AACT;AAsBA,IAAM,UAAkC;CACtC,KAAK;CACL,SAAS;CACT,WAAW;CACX,WAAW;CACX,YAAY;CACZ,QAAQ;CACR,UAAU;AACZ;AACA,IAAM,eAAuC;CAC3C,KAAK;CACL,MAAM;CACN,KAAK;CACL,MAAM;CACN,OAAO;AACT;;AAGA,SAAgB,YAAY,QAAwB;CAClD,MAAM,QAAQ,YAAY,MAAM;CAChC,IAAI,MAAM,WAAW,GACnB,MAAM,IAAI,MAAM,iEAAiE,OAAO,EAAE;CAC5F,MAAM,OAAO,MAAM;CACnB,MAAM,YAAY,OAAO,KAAK,YAAY,CAAC,CACxC,QAAQ,SAAS,KAAK,SAAS,IAAI,CAAC,CAAC,CACrC,KAAK,SAAS,aAAa,KAAK;CACnC,MAAM,MAAM,KAAK,MAAM,SAAS,EAAE,QAAQ,aAAa,KAAK;CAC5D,MAAM,OAAO,QAAQ,SAAS,IAAI,SAAS,IAAI,IAAI,EAAE,CAAE,YAAY,IAAI,IAAI,MAAM,CAAC,IAAI;CACtF,OAAO,CAAC,GAAG,WAAW,IAAI,CAAC,CAAC,KAAK,GAAG;AACtC;AAEA,IAAM,kBAAkB,aACtB,OAAO,YAAY,OAAO,QAAQ,QAAQ,CAAC,CAAC,KAAK,CAAC,KAAK,aAAa,CAAC,YAAY,GAAG,GAAG,OAAO,CAAC,C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colors.js";
|
|
2
|
+
import { toRaw } from "vue";
|
|
2
3
|
import { Mark } from "prosemirror-model";
|
|
3
4
|
// src/core/model.ts
|
|
4
5
|
var MARK_ORDER = [
|
|
@@ -162,7 +163,7 @@ function inlineNodes(schema, content, code) {
|
|
|
162
163
|
*/
|
|
163
164
|
function contentAttrs(type, props = {}) {
|
|
164
165
|
const attrs = {};
|
|
165
|
-
for (const name of Object.keys(type.spec.attrs ?? {})) if (props[name] !== void 0) attrs[name] = props[name];
|
|
166
|
+
for (const name of Object.keys(type.spec.attrs ?? {})) if (props[name] !== void 0) attrs[name] = toRaw(props[name]);
|
|
166
167
|
const normalize = type.spec.normalizeProps;
|
|
167
168
|
return normalize ? normalize(attrs) : attrs;
|
|
168
169
|
}
|
|
@@ -174,9 +175,15 @@ function createContentNode(schema, type, props, content, rows) {
|
|
|
174
175
|
if (nodeType.isAtom || !nodeType.inlineContent) return nodeType.create(attrs);
|
|
175
176
|
return nodeType.create(attrs, inlineNodes(schema, content, !!nodeType.spec.code));
|
|
176
177
|
}
|
|
177
|
-
|
|
178
|
+
/**
|
|
179
|
+
* The block node for `block`. With `fill`, a block that starts with
|
|
180
|
+
* children of its own (`template` in its spec, e.g. columns) and is given
|
|
181
|
+
* none gets them, as when it is picked from the slash menu.
|
|
182
|
+
*/
|
|
183
|
+
function nodeFromBlock(schema, block, fill = false) {
|
|
178
184
|
const content = createContentNode(schema, block.type ?? "paragraph", block.props, block.content, block.rows);
|
|
179
|
-
const
|
|
185
|
+
const template = fill ? content.type.spec.template : void 0;
|
|
186
|
+
const children = ((block.children?.length ? block.children : template?.(block.props ?? {})) ?? []).map((child) => nodeFromBlock(schema, child, fill));
|
|
180
187
|
const parts = children.length ? [content, schema.nodes.blockGroup.create(null, children)] : [content];
|
|
181
188
|
return schema.nodes.block.create({ id: block.id ?? createId() }, parts);
|
|
182
189
|
}
|
package/dist/core/model.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.js","names":[],"sources":["../../src/core/model.ts"],"sourcesContent":["import { Mark, type NodeType, type Node as PMNode, type Schema } from 'prosemirror-model'\nimport { isColor, type TextColor } from './colors'\nimport type { ContentType, MarkType } from './schema'\n\n/** A run of text with its formatting. */\nexport interface TextContent {\n type: 'text'\n text: string\n /** Formatting, in a fixed order: bold, italic, underline, strike, code. */\n marks?: MarkType[]\n /** The link target, when the text is a link. */\n link?: string\n /** The text color, by palette name (e.g. `red`), with the `colors` extension. */\n color?: TextColor\n /** The background color, by palette name (e.g. `yellow`), with the `colors` extension. */\n highlight?: TextColor\n /** The ids of the comment threads about this text. */\n comments?: string[]\n}\n\n/**\n * For the `colors` extension's marks (internal): a mark that carries one\n * color is stored on the text run under this name, e.g.\n * `{ text, color: 'red' }`, and keeps it in its `value` attribute.\n */\nexport type MarkField = 'color' | 'highlight'\n\n/** A line break inside a block (`Shift+Enter`). */\nexport interface BreakContent {\n type: 'break'\n}\n\n/** An inline node an extension adds, e.g. a mention. */\nexport interface InlineNodeContent {\n type: 'inline'\n /** The node's name, e.g. `mention`. */\n name: string\n props: Record<string, unknown>\n}\n\nexport type InlineContent = TextContent | BreakContent | InlineNodeContent\n\n/** A block's attributes: those of the built-in types, and any an extension declares. */\nexport interface BlockProps {\n /** Heading level, `1` to `3`. */\n level?: number\n /** Whether a to-do item is done. */\n checked?: boolean\n /** The language of a code block. */\n language?: string\n /** The tone of a callout: `info`, `tip`, `warning` or `danger`. */\n tone?: string\n /** How a paragraph, heading or quote lines up; left out when it follows the reading direction. */\n align?: 'left' | 'center' | 'right'\n [name: string]: unknown\n}\n\n/** A table cell: formatted text, and how far it reaches when merged. */\nexport interface TableCell {\n content: InlineContent[]\n /** Columns the cell spans, when more than one. */\n colspan?: number\n /** Rows the cell spans, when more than one. */\n rowspan?: number\n}\n\n/** A table row: one cell for every column, including those a merged cell covers. */\nexport interface TableRow {\n /** Stable across edits, like a block's id. */\n id: string\n cells: TableCell[]\n}\n\nexport interface PartialTableCell {\n content?: InlineContent[] | string\n colspan?: number\n rowspan?: number\n}\n\nexport interface PartialTableRow {\n id?: string\n cells: (PartialTableCell | string)[]\n}\n\n/** One block of the document, as `v-model` reads and writes it. */\nexport interface Block {\n /** Stable across edits; a random UUID unless you provide your own. */\n id: string\n type: ContentType\n props: BlockProps\n content: InlineContent[]\n /** The rows of a table; other blocks have none. */\n rows?: TableRow[]\n children: Block[]\n}\n\n/**\n * The document the editor edits, bound with `v-model`: plain JSON to store\n * and send as it is. The editor writes full blocks; it reads partial ones.\n */\nexport interface EditorDocument<B extends PartialBlock = Block> {\n /** The version of the format; see `migrateDocument`. */\n version: 1\n blocks: B[]\n}\n\n/** A block to insert: everything but the type is optional. */\nexport interface PartialBlock {\n id?: string\n type?: ContentType\n props?: BlockProps\n /** Inline content, or plain text. */\n content?: InlineContent[] | string\n rows?: PartialTableRow[]\n children?: PartialBlock[]\n}\n\n/**\n * A content node spec field for blocks whose content is rows rather than\n * text (a table): how to read them into a block and build them back.\n */\nexport interface RowsSpec {\n read: (node: PMNode) => { props: BlockProps; rows: TableRow[] }\n write: (type: NodeType, props: BlockProps, rows: PartialTableRow[]) => PMNode\n /** The node as a grid of ids and cell nodes, for collaboration. */\n grid: (node: PMNode) => TableGrid\n}\n\n/** A table node laid out by ids. */\nexport interface TableGrid {\n /** The props other than `columns`. */\n props: BlockProps\n /** Each column's id and its other fields (width, alignment). */\n columns: { id: string; width?: number; align?: string }[]\n /** Row ids, top to bottom. */\n rows: string[]\n /** The cells that are shown, merged ones by their top-left place. */\n cells: GridCell[]\n}\n\nexport interface GridCell {\n row: number\n col: number\n rowspan: number\n colspan: number\n /** The cell node; its content is inline. */\n node: PMNode\n /** Where the cell starts, counted from the start of the table's content. */\n offset: number\n}\n\nconst MARK_ORDER: string[] = ['bold', 'italic', 'underline', 'strike', 'code']\n\n/** Built-in marks in a fixed order, then the others by name. */\nconst markRank = (name: string) => {\n const index = MARK_ORDER.indexOf(name)\n return index < 0 ? MARK_ORDER.length : index\n}\n\n/** A random id; UUIDs keep blocks created at the same time on two devices apart. */\nexport function createId(): string {\n const crypto = globalThis.crypto\n if (crypto?.randomUUID) return crypto.randomUUID()\n // a v4 UUID from `getRandomValues`, or `Math.random` as a last resort\n const bytes = new Uint8Array(16)\n if (crypto?.getRandomValues) crypto.getRandomValues(bytes)\n else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256)\n bytes[6] = (bytes[6]! & 0x0f) | 0x40\n bytes[8] = (bytes[8]! & 0x3f) | 0x80\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n}\n\n/* document → blocks */\n\nexport function inlineOf(node: PMNode): InlineContent[] {\n const result: InlineContent[] = []\n node.forEach((child) => {\n if (child.type.name === 'hardBreak') {\n result.push({ type: 'break' })\n return\n }\n if (!child.isText) {\n result.push({ type: 'inline', name: child.type.name, props: { ...child.attrs } })\n return\n }\n const marks = child.marks\n .filter((mark) => !mark.type.spec.field)\n .map((mark) => mark.type.name)\n .filter((name): name is MarkType => name !== 'link' && name !== 'comment')\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts the filtered copy\n .sort((a, b) => markRank(a) - markRank(b) || a.localeCompare(b))\n const link = child.marks.find((mark) => mark.type.name === 'link')?.attrs.href as\n string | undefined\n const item: TextContent = { type: 'text', text: child.text ?? '' }\n if (marks.length) item.marks = marks\n if (link) item.link = link\n for (const mark of child.marks) {\n const field = mark.type.spec.field as MarkField | undefined\n if (field) item[field] = mark.attrs.value as TextColor\n }\n const comments = child.marks\n .filter((mark) => mark.type.name === 'comment')\n .map((mark) => mark.attrs.id as string)\n if (comments.length) item.comments = comments\n // merge with the previous run when the formatting is the same\n const previous = result.at(-1)\n if (\n previous?.type === 'text' &&\n previous.link === item.link &&\n previous.color === item.color &&\n previous.highlight === item.highlight &&\n String(previous.marks ?? '') === String(item.marks ?? '') &&\n String(previous.comments ?? '') === String(item.comments ?? '')\n )\n previous.text += item.text\n else result.push(item)\n })\n return result\n}\n\n/** A content node's attributes; those its spec lists as `optionalProps` only when set. */\nfunction propsOf(content: PMNode): BlockProps {\n const props: BlockProps = { ...content.attrs }\n for (const name of (content.type.spec.optionalProps as string[] | undefined) ?? [])\n if (props[name] === null || props[name] === undefined) delete props[name]\n return props\n}\n\n/**\n * Blocks already read, by node. Nodes never change, so a block that wasn't\n * edited is the same object as last time: reading a large document after\n * typing one key only builds the blocks on the path to that key.\n */\nconst blockCache = new WeakMap<PMNode, Block>()\n\nconst freeze = <T>(value: T): T => {\n if (value && typeof value === 'object' && !Object.isFrozen(value)) {\n Object.freeze(value)\n for (const item of Object.values(value)) freeze(item)\n }\n return value\n}\n\n/** A block of the document; shared between reads, so frozen. */\nexport function blockFromNode(node: PMNode): Block {\n let block = blockCache.get(node)\n if (!block) {\n block = readBlock(node)\n // a change to a shared block throws, instead of corrupting later reads\n freeze(block)\n blockCache.set(node, block)\n }\n return block\n}\n\nfunction readBlock(node: PMNode): Block {\n const content = node.firstChild!\n const group = node.childCount > 1 ? node.child(1) : null\n const children: Block[] = []\n group?.forEach((child) => children.push(blockFromNode(child)))\n const rows = content.type.spec.rows as RowsSpec | undefined\n if (rows) {\n const read = rows.read(content)\n return {\n id: node.attrs.id as string,\n type: content.type.name as ContentType,\n props: read.props,\n content: [],\n rows: read.rows,\n children,\n }\n }\n return {\n id: node.attrs.id as string,\n type: content.type.name as ContentType,\n props: propsOf(content),\n content: content.type.spec.code ? codeText(content) : inlineOf(content),\n children,\n }\n}\n\nfunction codeText(node: PMNode): InlineContent[] {\n return node.textContent ? [{ type: 'text', text: node.textContent }] : []\n}\n\nexport function docToBlocks(doc: PMNode): Block[] {\n const blocks: Block[] = []\n doc.forEach((node) => blocks.push(blockFromNode(node)))\n return blocks\n}\n\n/* blocks → document */\n\nfunction marksFor(schema: Schema, item: TextContent): Mark[] {\n const marks: Mark[] = []\n for (const name of item.marks ?? []) {\n const type = schema.marks[name]\n if (type) marks.push(type.create())\n }\n if (item.link && schema.marks.link) marks.push(schema.marks.link.create({ href: item.link }))\n for (const type of Object.values(schema.marks)) {\n const field = type.spec.field as MarkField | undefined\n const value = field && item[field]\n if (!value) continue\n // a color outside the palette is dropped\n if (!isColor(value)) warnOnce(`\"${value}\" is not a palette color; dropped`)\n else marks.push(type.create({ value }))\n }\n for (const id of item.comments ?? []) marks.push(schema.marks.comment!.create({ id }))\n return Mark.setFrom(marks) as Mark[]\n}\n\nexport function inlineNodes(\n schema: Schema,\n content: PartialBlock['content'],\n code: boolean,\n): PMNode[] {\n if (content === undefined) return []\n const items: InlineContent[] =\n typeof content === 'string' ? [{ type: 'text', text: content }] : content\n const nodes: PMNode[] = []\n for (const item of items) {\n if (item.type === 'break') {\n nodes.push(code ? schema.text('\\n') : schema.nodes.hardBreak!.create())\n } else if (item.type === 'inline') {\n // an inline node whose extension is missing is left out\n const type = schema.nodes[item.name]\n if (type?.isInline && !code) nodes.push(type.create(item.props))\n } else if (item.text) {\n nodes.push(schema.text(item.text, code ? [] : marksFor(schema, item)))\n }\n }\n return nodes\n}\n\n/**\n * The attributes a content type declares, taken from `props` where given.\n * A spec's `normalizeProps` can clamp them, e.g. a heading's level.\n */\nexport function contentAttrs(type: NodeType, props: BlockProps = {}) {\n const attrs: Record<string, unknown> = {}\n for (const name of Object.keys(type.spec.attrs ?? {})) {\n if (props[name] !== undefined) attrs[name] = props[name]\n }\n const normalize = type.spec.normalizeProps as\n ((attrs: Record<string, unknown>) => Record<string, unknown>) | undefined\n return normalize ? normalize(attrs) : attrs\n}\n\nexport function createContentNode(\n schema: Schema,\n type: ContentType,\n props?: BlockProps,\n content?: PartialBlock['content'],\n rows?: PartialTableRow[],\n): PMNode {\n const nodeType = schema.nodes[type]?.isInGroup('blockContent')\n ? schema.nodes[type]!\n : schema.nodes.paragraph!\n const rowsSpec = nodeType.spec.rows as RowsSpec | undefined\n if (rowsSpec) return rowsSpec.write(nodeType, props ?? {}, rows ?? [])\n const attrs = contentAttrs(nodeType, props)\n if (nodeType.isAtom || !nodeType.inlineContent) return nodeType.create(attrs)\n return nodeType.create(attrs, inlineNodes(schema, content, !!nodeType.spec.code))\n}\n\nexport function nodeFromBlock(schema: Schema, block: PartialBlock): PMNode {\n const content = createContentNode(\n schema,\n block.type ?? 'paragraph',\n block.props,\n block.content,\n block.rows,\n )\n const children = (block.children ?? []).map((child) => nodeFromBlock(schema, child))\n const parts = children.length\n ? [content, schema.nodes.blockGroup!.create(null, children)]\n : [content]\n return schema.nodes.block!.create({ id: block.id ?? createId() }, parts)\n}\n\nexport function blocksToDoc(schema: Schema, blocks: PartialBlock[]): PMNode {\n const list = blocks.length ? blocks : [{ type: 'paragraph' as const }]\n return schema.nodes.doc!.create(\n null,\n list.map((block) => nodeFromBlock(schema, block)),\n )\n}\n\nconst warned = new Set<string>()\n\n/** A development warning, once per message. */\nexport function warnOnce(message: string) {\n if (process.env.NODE_ENV === 'production' || warned.has(message)) return\n warned.add(message)\n console.warn(`[@dou-ui/editor] ${message}`)\n}\n"],"mappings":";;;AAuJA,IAAM,aAAuB;CAAC;CAAQ;CAAU;CAAa;CAAU;AAAM;;AAG7E,IAAM,YAAY,SAAiB;CACjC,MAAM,QAAQ,WAAW,QAAQ,IAAI;CACrC,OAAO,QAAQ,IAAI,WAAW,SAAS;AACzC;;AAGA,SAAgB,WAAmB;CACjC,MAAM,SAAS,WAAW;CAC1B,IAAI,QAAQ,YAAY,OAAO,OAAO,WAAW;CAEjD,MAAM,wBAAQ,IAAI,WAAW,EAAE;CAC/B,IAAI,QAAQ,iBAAiB,OAAO,gBAAgB,KAAK;MACpD,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK,MAAM,KAAK,KAAK,MAAM,KAAK,OAAO,IAAI,GAAG;CAC3E,MAAM,KAAM,MAAM,KAAM,KAAQ;CAChC,MAAM,KAAM,MAAM,KAAM,KAAQ;CAChC,MAAM,MAAM,MAAM,KAAK,Q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M,UAAU,SAAS,CAAC,GAAG,QAAQ,CAAC,CAAC;CACrE,MAAM,QAAQ,aAAa,UAAU,KAAK;CAC1C,IAAI,SAAS,UAAU,CAAC,SAAS,eAAe,OAAO,SAAS,OAAO,KAAK;CAC5E,OAAO,SAAS,OAAO,OAAO,YAAY,QAAQ,SAAS,CAAC,CAAC,SAAS,KAAK,IAAI,CAAC;AAClF;AAEA,SAAgB,cAAc,QAAgB,OAA6B;CACzE,MAAM,UAAU,kBACd,QACA,MAAM,QAAQ,aACd,MAAM,OACN,MAAM,SACN,MAAM,IACR;CACA,MAAM,YAAY,MAAM,YAAY,CAAC,EAAA,CAAG,KAAK,UAAU,cAAc,QAAQ,KAAK,CAAC;CACnF,MAAM,QAAQ,SAAS,SACnB,CAAC,SAAS,OAAO,MAAM,WAAY,OAAO,MAAM,QAAQ,CAAC,IACzD,CAAC,OAAO;CACZ,OAAO,OAAO,MAAM,MAAO,OAAO,EAAE,IAAI,MAAM,MAAM,SAAS,EAAE,GAAG,KAAK;AACzE;AAEA,SAAgB,YAAY,QAAgB,QAAgC;CAC1E,MAAM,OAAO,OAAO,SAAS,SAAS,CAAC,EAAE,MAAM,YAAqB,CAAC;CACrE,OAAO,OAAO,MAAM,IAAK,OACvB,MACA,KAAK,KAAK,UAAU,cAAc,QAAQ,KAAK,CAAC,CAClD;AACF;AAEA,IAAM,yBAAS,IAAI,IAAY;;AAG/B,SAAgB,SAAS,SAAiB;CACxC,IAAA,QAAA,IAAA,aAA6B,gBAAgB,OAAO,IAAI,OAAO,GAAG;CAClE,OAAO,IAAI,OAAO;CAClB,QAAQ,KAAK,oBAAoB,SAAS;AAC5C"}
|
|
1
|
+
{"version":3,"file":"model.js","names":[],"sources":["../../src/core/model.ts"],"sourcesContent":["import { Mark, type NodeType, type Node as PMNode, type Schema } from 'prosemirror-model'\nimport { toRaw } from 'vue'\nimport { isColor, type TextColor } from './colors'\nimport type { ContentType, MarkType } from './schema'\n\n/** A run of text with its formatting. */\nexport interface TextContent {\n type: 'text'\n text: string\n /** Formatting, in a fixed order: bold, italic, underline, strike, code. */\n marks?: MarkType[]\n /** The link target, when the text is a link. */\n link?: string\n /** The text color, by palette name (e.g. `red`), with the `colors` extension. */\n color?: TextColor\n /** The background color, by palette name (e.g. `yellow`), with the `colors` extension. */\n highlight?: TextColor\n /** The ids of the comment threads about this text. */\n comments?: string[]\n}\n\n/**\n * For the `colors` extension's marks (internal): a mark that carries one\n * color is stored on the text run under this name, e.g.\n * `{ text, color: 'red' }`, and keeps it in its `value` attribute.\n */\nexport type MarkField = 'color' | 'highlight'\n\n/** A line break inside a block (`Shift+Enter`). */\nexport interface BreakContent {\n type: 'break'\n}\n\n/** An inline node an extension adds, e.g. a mention. */\nexport interface InlineNodeContent {\n type: 'inline'\n /** The node's name, e.g. `mention`. */\n name: string\n props: Record<string, unknown>\n}\n\nexport type InlineContent = TextContent | BreakContent | InlineNodeContent\n\n/** A block's attributes: those of the built-in types, and any an extension declares. */\nexport interface BlockProps {\n /** Heading level, `1` to `3`. */\n level?: number\n /** Whether a to-do item is done. */\n checked?: boolean\n /** The language of a code block. */\n language?: string\n /** The tone of a callout: `info`, `tip`, `warning` or `danger`. */\n tone?: string\n /** How a paragraph, heading or quote lines up; left out when it follows the reading direction. */\n align?: 'left' | 'center' | 'right'\n [name: string]: unknown\n}\n\n/** A table cell: formatted text, and how far it reaches when merged. */\nexport interface TableCell {\n content: InlineContent[]\n /** Columns the cell spans, when more than one. */\n colspan?: number\n /** Rows the cell spans, when more than one. */\n rowspan?: number\n}\n\n/** A table row: one cell for every column, including those a merged cell covers. */\nexport interface TableRow {\n /** Stable across edits, like a block's id. */\n id: string\n cells: TableCell[]\n}\n\nexport interface PartialTableCell {\n content?: InlineContent[] | string\n colspan?: number\n rowspan?: number\n}\n\nexport interface PartialTableRow {\n id?: string\n cells: (PartialTableCell | string)[]\n}\n\n/** One block of the document, as `v-model` reads and writes it. */\nexport interface Block {\n /** Stable across edits; a random UUID unless you provide your own. */\n id: string\n type: ContentType\n props: BlockProps\n content: InlineContent[]\n /** The rows of a table; other blocks have none. */\n rows?: TableRow[]\n children: Block[]\n}\n\n/**\n * The document the editor edits, bound with `v-model`: plain JSON to store\n * and send as it is. The editor writes full blocks; it reads partial ones.\n */\nexport interface EditorDocument<B extends PartialBlock = Block> {\n /** The version of the format; see `migrateDocument`. */\n version: 1\n blocks: B[]\n}\n\n/** A block to insert: everything but the type is optional. */\nexport interface PartialBlock {\n id?: string\n type?: ContentType\n props?: BlockProps\n /** Inline content, or plain text. */\n content?: InlineContent[] | string\n rows?: PartialTableRow[]\n children?: PartialBlock[]\n}\n\n/**\n * A content node spec field for blocks whose content is rows rather than\n * text (a table): how to read them into a block and build them back.\n */\nexport interface RowsSpec {\n read: (node: PMNode) => { props: BlockProps; rows: TableRow[] }\n write: (type: NodeType, props: BlockProps, rows: PartialTableRow[]) => PMNode\n /** The node as a grid of ids and cell nodes, for collaboration. */\n grid: (node: PMNode) => TableGrid\n}\n\n/** A table node laid out by ids. */\nexport interface TableGrid {\n /** The props other than `columns`. */\n props: BlockProps\n /** Each column's id and its other fields (width, alignment). */\n columns: { id: string; width?: number; align?: string }[]\n /** Row ids, top to bottom. */\n rows: string[]\n /** The cells that are shown, merged ones by their top-left place. */\n cells: GridCell[]\n}\n\nexport interface GridCell {\n row: number\n col: number\n rowspan: number\n colspan: number\n /** The cell node; its content is inline. */\n node: PMNode\n /** Where the cell starts, counted from the start of the table's content. */\n offset: number\n}\n\nconst MARK_ORDER: string[] = ['bold', 'italic', 'underline', 'strike', 'code']\n\n/** Built-in marks in a fixed order, then the others by name. */\nconst markRank = (name: string) => {\n const index = MARK_ORDER.indexOf(name)\n return index < 0 ? MARK_ORDER.length : index\n}\n\n/** A random id; UUIDs keep blocks created at the same time on two devices apart. */\nexport function createId(): string {\n const crypto = globalThis.crypto\n if (crypto?.randomUUID) return crypto.randomUUID()\n // a v4 UUID from `getRandomValues`, or `Math.random` as a last resort\n const bytes = new Uint8Array(16)\n if (crypto?.getRandomValues) crypto.getRandomValues(bytes)\n else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256)\n bytes[6] = (bytes[6]! & 0x0f) | 0x40\n bytes[8] = (bytes[8]! & 0x3f) | 0x80\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n}\n\n/* document → blocks */\n\nexport function inlineOf(node: PMNode): InlineContent[] {\n const result: InlineContent[] = []\n node.forEach((child) => {\n if (child.type.name === 'hardBreak') {\n result.push({ type: 'break' })\n return\n }\n if (!child.isText) {\n result.push({ type: 'inline', name: child.type.name, props: { ...child.attrs } })\n return\n }\n const marks = child.marks\n .filter((mark) => !mark.type.spec.field)\n .map((mark) => mark.type.name)\n .filter((name): name is MarkType => name !== 'link' && name !== 'comment')\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts the filtered copy\n .sort((a, b) => markRank(a) - markRank(b) || a.localeCompare(b))\n const link = child.marks.find((mark) => mark.type.name === 'link')?.attrs.href as\n string | undefined\n const item: TextContent = { type: 'text', text: child.text ?? '' }\n if (marks.length) item.marks = marks\n if (link) item.link = link\n for (const mark of child.marks) {\n const field = mark.type.spec.field as MarkField | undefined\n if (field) item[field] = mark.attrs.value as TextColor\n }\n const comments = child.marks\n .filter((mark) => mark.type.name === 'comment')\n .map((mark) => mark.attrs.id as string)\n if (comments.length) item.comments = comments\n // merge with the previous run when the formatting is the same\n const previous = result.at(-1)\n if (\n previous?.type === 'text' &&\n previous.link === item.link &&\n previous.color === item.color &&\n previous.highlight === item.highlight &&\n String(previous.marks ?? '') === String(item.marks ?? '') &&\n String(previous.comments ?? '') === String(item.comments ?? '')\n )\n previous.text += item.text\n else result.push(item)\n })\n return result\n}\n\n/** A content node's attributes; those its spec lists as `optionalProps` only when set. */\nfunction propsOf(content: PMNode): BlockProps {\n const props: BlockProps = { ...content.attrs }\n for (const name of (content.type.spec.optionalProps as string[] | undefined) ?? [])\n if (props[name] === null || props[name] === undefined) delete props[name]\n return props\n}\n\n/**\n * Blocks already read, by node. Nodes never change, so a block that wasn't\n * edited is the same object as last time: reading a large document after\n * typing one key only builds the blocks on the path to that key.\n */\nconst blockCache = new WeakMap<PMNode, Block>()\n\nconst freeze = <T>(value: T): T => {\n if (value && typeof value === 'object' && !Object.isFrozen(value)) {\n Object.freeze(value)\n for (const item of Object.values(value)) freeze(item)\n }\n return value\n}\n\n/** A block of the document; shared between reads, so frozen. */\nexport function blockFromNode(node: PMNode): Block {\n let block = blockCache.get(node)\n if (!block) {\n block = readBlock(node)\n // a change to a shared block throws, instead of corrupting later reads\n freeze(block)\n blockCache.set(node, block)\n }\n return block\n}\n\nfunction readBlock(node: PMNode): Block {\n const content = node.firstChild!\n const group = node.childCount > 1 ? node.child(1) : null\n const children: Block[] = []\n group?.forEach((child) => children.push(blockFromNode(child)))\n const rows = content.type.spec.rows as RowsSpec | undefined\n if (rows) {\n const read = rows.read(content)\n return {\n id: node.attrs.id as string,\n type: content.type.name as ContentType,\n props: read.props,\n content: [],\n rows: read.rows,\n children,\n }\n }\n return {\n id: node.attrs.id as string,\n type: content.type.name as ContentType,\n props: propsOf(content),\n content: content.type.spec.code ? codeText(content) : inlineOf(content),\n children,\n }\n}\n\nfunction codeText(node: PMNode): InlineContent[] {\n return node.textContent ? [{ type: 'text', text: node.textContent }] : []\n}\n\nexport function docToBlocks(doc: PMNode): Block[] {\n const blocks: Block[] = []\n doc.forEach((node) => blocks.push(blockFromNode(node)))\n return blocks\n}\n\n/* blocks → document */\n\nfunction marksFor(schema: Schema, item: TextContent): Mark[] {\n const marks: Mark[] = []\n for (const name of item.marks ?? []) {\n const type = schema.marks[name]\n if (type) marks.push(type.create())\n }\n if (item.link && schema.marks.link) marks.push(schema.marks.link.create({ href: item.link }))\n for (const type of Object.values(schema.marks)) {\n const field = type.spec.field as MarkField | undefined\n const value = field && item[field]\n if (!value) continue\n // a color outside the palette is dropped\n if (!isColor(value)) warnOnce(`\"${value}\" is not a palette color; dropped`)\n else marks.push(type.create({ value }))\n }\n for (const id of item.comments ?? []) marks.push(schema.marks.comment!.create({ id }))\n return Mark.setFrom(marks) as Mark[]\n}\n\nexport function inlineNodes(\n schema: Schema,\n content: PartialBlock['content'],\n code: boolean,\n): PMNode[] {\n if (content === undefined) return []\n const items: InlineContent[] =\n typeof content === 'string' ? [{ type: 'text', text: content }] : content\n const nodes: PMNode[] = []\n for (const item of items) {\n if (item.type === 'break') {\n nodes.push(code ? schema.text('\\n') : schema.nodes.hardBreak!.create())\n } else if (item.type === 'inline') {\n // an inline node whose extension is missing is left out\n const type = schema.nodes[item.name]\n if (type?.isInline && !code) nodes.push(type.create(item.props))\n } else if (item.text) {\n nodes.push(schema.text(item.text, code ? [] : marksFor(schema, item)))\n }\n }\n return nodes\n}\n\n/**\n * The attributes a content type declares, taken from `props` where given.\n * A spec's `normalizeProps` can clamp them, e.g. a heading's level.\n */\nexport function contentAttrs(type: NodeType, props: BlockProps = {}) {\n const attrs: Record<string, unknown> = {}\n for (const name of Object.keys(type.spec.attrs ?? {})) {\n // a prop from a reactive document (an object one, e.g. a board) as its plain value:\n // blocks are frozen, and a frozen proxy breaks every read\n if (props[name] !== undefined) attrs[name] = toRaw(props[name])\n }\n const normalize = type.spec.normalizeProps as\n ((attrs: Record<string, unknown>) => Record<string, unknown>) | undefined\n return normalize ? normalize(attrs) : attrs\n}\n\nexport function createContentNode(\n schema: Schema,\n type: ContentType,\n props?: BlockProps,\n content?: PartialBlock['content'],\n rows?: PartialTableRow[],\n): PMNode {\n const nodeType = schema.nodes[type]?.isInGroup('blockContent')\n ? schema.nodes[type]!\n : schema.nodes.paragraph!\n const rowsSpec = nodeType.spec.rows as RowsSpec | undefined\n if (rowsSpec) return rowsSpec.write(nodeType, props ?? {}, rows ?? [])\n const attrs = contentAttrs(nodeType, props)\n if (nodeType.isAtom || !nodeType.inlineContent) return nodeType.create(attrs)\n return nodeType.create(attrs, inlineNodes(schema, content, !!nodeType.spec.code))\n}\n\n/**\n * The block node for `block`. With `fill`, a block that starts with\n * children of its own (`template` in its spec, e.g. columns) and is given\n * none gets them, as when it is picked from the slash menu.\n */\nexport function nodeFromBlock(schema: Schema, block: PartialBlock, fill = false): PMNode {\n const content = createContentNode(\n schema,\n block.type ?? 'paragraph',\n block.props,\n block.content,\n block.rows,\n )\n const template = fill\n ? (content.type.spec.template as ((props: BlockProps) => PartialBlock[]) | undefined)\n : undefined\n const given = block.children?.length ? block.children : template?.(block.props ?? {})\n const children = (given ?? []).map((child) => nodeFromBlock(schema, child, fill))\n const parts = children.length\n ? [content, schema.nodes.blockGroup!.create(null, children)]\n : [content]\n return schema.nodes.block!.create({ id: block.id ?? createId() }, parts)\n}\n\nexport function blocksToDoc(schema: Schema, blocks: PartialBlock[]): PMNode {\n const list = blocks.length ? blocks : [{ type: 'paragraph' as const }]\n return schema.nodes.doc!.create(\n null,\n list.map((block) => nodeFromBlock(schema, block)),\n )\n}\n\nconst warned = new Set<string>()\n\n/** A development warning, once per message. */\nexport function warnOnce(message: string) {\n if (process.env.NODE_ENV === 'production' || warned.has(message)) return\n warned.add(message)\n console.warn(`[@dou-ui/editor] ${message}`)\n}\n"],"mappings":";;;;AAwJA,IAAM,aAAuB;CAAC;CAAQ;CAAU;CAAa;CAAU;AAAM;;AAG7E,IAAM,YAAY,SAAiB;CACjC,MAAM,QAAQ,WAAW,QAAQ,IAAI;CACrC,OAAO,QAAQ,IAAI,WAAW,SAAS;AACzC;;AAGA,SAAgB,WAAmB;CACjC,MAAM,SAAS,WAAW;CAC1B,IAAI,QAAQ,YAAY,OAAO,OAAO,WAAW;CAEjD,MAAM,wBAAQ,IAAI,WAAW,EAAE;CAC/B,IAAI,QAAQ,iBAAiB,OAAO,gBAAgB,KAAK;MACpD,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK,MAAM,KAAK,KAAK,MAAM,KAAK,OAAO,IAAI,G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AI,OAAO;CAClB,QAAQ,KAAK,oBAAoB,SAAS;AAC5C"}
|
package/dist/core/plugins.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { createId } from "./model.js";
|
|
2
2
|
import { Plugin, PluginKey } from "prosemirror-state";
|
|
3
3
|
import { Decoration, DecorationSet } from "prosemirror-view";
|
|
4
|
+
import { ReplaceAroundStep, ReplaceStep } from "prosemirror-transform";
|
|
4
5
|
// src/core/plugins.ts
|
|
5
6
|
/**
|
|
6
7
|
* Whether a transaction came from another collaborator. Collaborative
|
|
@@ -38,6 +39,111 @@ function idPlugin() {
|
|
|
38
39
|
}
|
|
39
40
|
});
|
|
40
41
|
}
|
|
42
|
+
/**
|
|
43
|
+
* Whether a transaction may have changed which blocks there are, their
|
|
44
|
+
* types or their nesting. Typing and deleting inside one text block, marks
|
|
45
|
+
* and attributes don't; decorations that only follow the block structure
|
|
46
|
+
* then just map through the change instead of being rebuilt.
|
|
47
|
+
*/
|
|
48
|
+
function changesBlockStructure(tr) {
|
|
49
|
+
if (!tr.docChanged) return false;
|
|
50
|
+
return tr.steps.some((step, index) => {
|
|
51
|
+
if (step instanceof ReplaceAroundStep) return true;
|
|
52
|
+
if (!(step instanceof ReplaceStep)) return false;
|
|
53
|
+
const { from, to, slice } = step;
|
|
54
|
+
if (slice.openStart || slice.openEnd) return true;
|
|
55
|
+
let blocks = false;
|
|
56
|
+
slice.content.forEach((node) => {
|
|
57
|
+
if (!node.isInline) blocks = true;
|
|
58
|
+
});
|
|
59
|
+
if (blocks) return true;
|
|
60
|
+
const doc = tr.docs[index];
|
|
61
|
+
const $from = doc.resolve(from);
|
|
62
|
+
return !$from.parent.isTextblock || !$from.sameParent(doc.resolve(to));
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
/** Plugin state for decorations that only depend on the block structure. */
|
|
66
|
+
var structureDecorations = (build, update = (_set, tr) => build(tr.doc)) => ({
|
|
67
|
+
init: (_config, state) => build(state.doc),
|
|
68
|
+
apply: (tr, value) => !tr.docChanged ? value : changesBlockStructure(tr) ? update(value, tr) : value.map(tr.mapping, tr.doc)
|
|
69
|
+
});
|
|
70
|
+
var isList = (block) => !!block?.firstChild?.type.spec.continues;
|
|
71
|
+
/** Whether a sibling block is an item of the same list as `block`. */
|
|
72
|
+
var sameList = (sibling, block) => isList(sibling) && sibling.firstChild.type === block.firstChild.type;
|
|
73
|
+
/**
|
|
74
|
+
* The content of blocks that continue like a list (`continues` in their
|
|
75
|
+
* spec) gets `is-list`, so the stylesheet can space list items apart by the list gap
|
|
76
|
+
* instead of the block gap. The first and last block of a run of them also
|
|
77
|
+
* get `is-list-start` / `is-list-end`, where the block gap comes back. A run
|
|
78
|
+
* is one type: a to-do list right after a numbered one is a list of its
|
|
79
|
+
* own. Nested items under a list item, of any type, carry on its run.
|
|
80
|
+
*/
|
|
81
|
+
/** The list decorations of top-level blocks `first` to `final` (and their children). */
|
|
82
|
+
function listDecorationsOf(doc, first, final) {
|
|
83
|
+
const decorations = [];
|
|
84
|
+
const visit = (container, start, inList, from = 0, to = Infinity) => {
|
|
85
|
+
const last = container.childCount - 1;
|
|
86
|
+
container.forEach((block, offset, index) => {
|
|
87
|
+
if (index < from || index > to) return;
|
|
88
|
+
const pos = start + offset;
|
|
89
|
+
const content = block.firstChild;
|
|
90
|
+
const groupPos = pos + 1 + content.nodeSize;
|
|
91
|
+
const list = isList(block);
|
|
92
|
+
if (list) {
|
|
93
|
+
const classes = ["is-list"];
|
|
94
|
+
const previous = index > 0 ? container.child(index - 1) : null;
|
|
95
|
+
if (!(previous ? sameList(previous, block) : inList)) {
|
|
96
|
+
classes.push("is-list-start");
|
|
97
|
+
if (previous && isList(previous)) classes.push("is-list-after");
|
|
98
|
+
}
|
|
99
|
+
const end = !(index < last ? sameList(container.child(index + 1), block) : inList);
|
|
100
|
+
if (end && block.childCount < 2) classes.push("is-list-end");
|
|
101
|
+
decorations.push(Decoration.node(pos + 1, groupPos, { class: classes.join(" ") }));
|
|
102
|
+
if (end && block.childCount > 1) decorations.push(Decoration.node(groupPos, groupPos + block.child(1).nodeSize, { class: "is-list-end" }));
|
|
103
|
+
}
|
|
104
|
+
if (block.childCount > 1) visit(block.child(1), groupPos + 1, list);
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
visit(doc, 0, false, first, final);
|
|
108
|
+
return decorations;
|
|
109
|
+
}
|
|
110
|
+
var listDecorations = (doc) => DecorationSet.create(doc, listDecorationsOf(doc, 0, doc.childCount - 1));
|
|
111
|
+
/**
|
|
112
|
+
* After blocks were added, removed or changed type: only the top-level
|
|
113
|
+
* blocks the change touched, and one on either side (whose run may have
|
|
114
|
+
* started or ended there), are worked out again.
|
|
115
|
+
*/
|
|
116
|
+
function updateListDecorations(set, tr) {
|
|
117
|
+
const { doc, mapping } = tr;
|
|
118
|
+
let from = doc.content.size;
|
|
119
|
+
let to = 0;
|
|
120
|
+
mapping.maps.forEach((map, index) => {
|
|
121
|
+
const rest = mapping.slice(index + 1);
|
|
122
|
+
map.forEach((_oldStart, _oldEnd, start, end) => {
|
|
123
|
+
from = Math.min(from, rest.map(start, -1));
|
|
124
|
+
to = Math.max(to, rest.map(end, 1));
|
|
125
|
+
});
|
|
126
|
+
});
|
|
127
|
+
const mapped = set.map(mapping, doc);
|
|
128
|
+
if (from > to) return mapped;
|
|
129
|
+
const first = Math.max(0, doc.resolve(from).index(0) - 1);
|
|
130
|
+
const last = Math.min(doc.childCount - 1, doc.resolve(to).index(0) + 1);
|
|
131
|
+
let start = 0;
|
|
132
|
+
for (let index = 0; index < first; index++) start += doc.child(index).nodeSize;
|
|
133
|
+
let end = start;
|
|
134
|
+
for (let index = first; index <= last; index++) end += doc.child(index).nodeSize;
|
|
135
|
+
return mapped.remove(mapped.find(start, end)).add(doc, listDecorationsOf(doc, first, last));
|
|
136
|
+
}
|
|
137
|
+
/** Marks list-like blocks and the ends of their runs, for spacing. */
|
|
138
|
+
function listPlugin() {
|
|
139
|
+
return new Plugin({
|
|
140
|
+
key: new PluginKey("dou-editor-lists"),
|
|
141
|
+
state: structureDecorations(listDecorations, updateListDecorations),
|
|
142
|
+
props: { decorations(state) {
|
|
143
|
+
return this.getState(state);
|
|
144
|
+
} }
|
|
145
|
+
});
|
|
146
|
+
}
|
|
41
147
|
/** Numbered items count up within each run of consecutive numbered siblings. */
|
|
42
148
|
function numberDecorations(doc) {
|
|
43
149
|
const decorations = [];
|
|
@@ -59,10 +165,7 @@ function numberDecorations(doc) {
|
|
|
59
165
|
function numberingPlugin() {
|
|
60
166
|
return new Plugin({
|
|
61
167
|
key: new PluginKey("dou-editor-numbering"),
|
|
62
|
-
state:
|
|
63
|
-
init: (_config, state) => numberDecorations(state.doc),
|
|
64
|
-
apply: (tr, value) => tr.docChanged ? numberDecorations(tr.doc) : value
|
|
65
|
-
},
|
|
168
|
+
state: structureDecorations(numberDecorations),
|
|
66
169
|
props: { decorations(state) {
|
|
67
170
|
return this.getState(state);
|
|
68
171
|
} }
|
|
@@ -97,6 +200,6 @@ function placeholderPlugin(options) {
|
|
|
97
200
|
} }
|
|
98
201
|
});
|
|
99
202
|
}
|
|
100
|
-
export { idPlugin, isRemote, numberingPlugin, placeholderPlugin };
|
|
203
|
+
export { changesBlockStructure, idPlugin, isRemote, listPlugin, numberingPlugin, placeholderPlugin };
|
|
101
204
|
|
|
102
205
|
//# sourceMappingURL=plugins.js.map
|