@dou-ui/editor 0.1.0-alpha.3 → 0.1.0-alpha.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/collaboration/binding.js +371 -57
- package/dist/collaboration/binding.js.map +1 -1
- package/dist/collaboration/cursors.js +42 -10
- package/dist/collaboration/cursors.js.map +1 -1
- package/dist/collaboration/index.js +61 -11
- package/dist/collaboration/index.js.map +1 -1
- package/dist/collaboration/inline-diff.js +138 -0
- package/dist/collaboration/inline-diff.js.map +1 -0
- package/dist/collaboration/merged-props.js +152 -0
- package/dist/collaboration/merged-props.js.map +1 -0
- package/dist/collaboration/order.js +41 -1
- package/dist/collaboration/order.js.map +1 -1
- package/dist/collaboration/table.js +64 -25
- package/dist/collaboration/table.js.map +1 -1
- package/dist/collaboration/text.js +213 -1
- package/dist/collaboration/text.js.map +1 -1
- package/dist/components/block-handle.js.map +1 -1
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js +127 -17
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/components/slash-choices.js +6 -0
- package/dist/components/slash-choices.js.map +1 -0
- package/dist/components/slash-choices.vue_vue_type_script_setup_true_lang.js +56 -0
- package/dist/components/slash-choices.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/components/slash-menu.js.map +1 -1
- package/dist/components/slash-menu.vue_vue_type_script_setup_true_lang.js +185 -20
- package/dist/components/slash-menu.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/core/block-selection.js +32 -4
- package/dist/core/block-selection.js.map +1 -1
- package/dist/core/blocks.js +21 -3
- package/dist/core/blocks.js.map +1 -1
- package/dist/core/cjk.js +54 -0
- package/dist/core/cjk.js.map +1 -0
- package/dist/core/commands.js +125 -13
- package/dist/core/commands.js.map +1 -1
- package/dist/core/comments.js +85 -3
- package/dist/core/comments.js.map +1 -1
- package/dist/core/convert.js +3 -3
- package/dist/core/convert.js.map +1 -1
- package/dist/core/extension.js +6 -2
- package/dist/core/extension.js.map +1 -1
- package/dist/core/model.js +10 -3
- package/dist/core/model.js.map +1 -1
- package/dist/core/output.js +26 -10
- package/dist/core/output.js.map +1 -1
- package/dist/core/prepare.js +12 -5
- package/dist/core/prepare.js.map +1 -1
- package/dist/core/schema.js.map +1 -1
- package/dist/core/transaction.js +19 -4
- package/dist/core/transaction.js.map +1 -1
- package/dist/define-block.js +8 -4
- package/dist/define-block.js.map +1 -1
- package/dist/document.js +59 -4
- package/dist/document.js.map +1 -1
- package/dist/dom.js +109 -13
- package/dist/dom.js.map +1 -1
- package/dist/editor.js.map +1 -1
- package/dist/editor.vue_vue_type_script_setup_true_lang.js +6 -5
- package/dist/editor.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/editor2.js.map +1 -1
- package/dist/extensions/callout/html.js +5 -4
- package/dist/extensions/callout/html.js.map +1 -1
- package/dist/extensions/columns/column-picker.js +6 -0
- package/dist/extensions/columns/column-picker.js.map +1 -0
- package/dist/extensions/columns/column-picker.vue_vue_type_script_setup_true_lang.js +57 -0
- package/dist/extensions/columns/column-picker.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/columns/columns-controls.js +6 -0
- package/dist/extensions/columns/columns-controls.js.map +1 -0
- package/dist/extensions/columns/columns-controls.vue_vue_type_script_setup_true_lang.js +341 -0
- package/dist/extensions/columns/columns-controls.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/columns/html.js +34 -0
- package/dist/extensions/columns/html.js.map +1 -0
- package/dist/extensions/columns/index.js +57 -0
- package/dist/extensions/columns/index.js.map +1 -0
- package/dist/extensions/columns/keys.js +53 -0
- package/dist/extensions/columns/keys.js.map +1 -0
- package/dist/extensions/columns/plugin.js +213 -0
- package/dist/extensions/columns/plugin.js.map +1 -0
- package/dist/extensions/columns/schema.js +58 -0
- package/dist/extensions/columns/schema.js.map +1 -0
- package/dist/extensions/columns/select-columns.js +6 -0
- package/dist/extensions/columns/select-columns.js.map +1 -0
- package/dist/extensions/columns/select-columns.vue_vue_type_script_setup_true_lang.js +71 -0
- package/dist/extensions/columns/select-columns.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/editor-kit.js +3 -1
- package/dist/extensions/editor-kit.js.map +1 -1
- package/dist/extensions/list-html.js +1 -1
- package/dist/extensions/list-html.js.map +1 -1
- package/dist/extensions/table/plugin.js +33 -1
- package/dist/extensions/table/plugin.js.map +1 -1
- package/dist/extensions/table/schema.js +5 -1
- package/dist/extensions/table/schema.js.map +1 -1
- package/dist/extensions/table/table-controls.js.map +1 -1
- package/dist/extensions/table/table-controls.vue_vue_type_script_setup_true_lang.js +80 -9
- package/dist/extensions/table/table-controls.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/extensions/table/view.js +181 -3
- package/dist/extensions/table/view.js.map +1 -1
- package/dist/flow/board-block.js +6 -0
- package/dist/flow/board-block.js.map +1 -0
- package/dist/flow/board-block.vue_vue_type_script_setup_true_lang.js +659 -0
- package/dist/flow/board-block.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/flow/board.js +221 -0
- package/dist/flow/board.js.map +1 -0
- package/dist/flow/index.js +173 -0
- package/dist/flow/index.js.map +1 -0
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/locale.js +78 -6
- package/dist/locale.js.map +1 -1
- package/dist/markdown/cjk-friendly.js +62 -0
- package/dist/markdown/cjk-friendly.js.map +1 -0
- package/dist/markdown/index.js +4 -3
- package/dist/markdown/index.js.map +1 -1
- package/dist/style.css +1 -1
- package/dist/style.js +2 -0
- package/dist/types/collaboration/binding.d.ts +12 -0
- package/dist/types/collaboration/cursors.d.ts +29 -1
- package/dist/types/collaboration/index.d.ts +53 -6
- package/dist/types/collaboration/inline-diff.d.ts +9 -0
- package/dist/types/collaboration/merged-props.d.ts +20 -0
- package/dist/types/collaboration/order.d.ts +5 -0
- package/dist/types/collaboration/table.d.ts +5 -1
- package/dist/types/collaboration/text.d.ts +20 -0
- package/dist/types/components/slash-choices.vue.d.ts +18 -0
- package/dist/types/core/blocks.d.ts +10 -0
- package/dist/types/core/cjk.d.ts +23 -0
- package/dist/types/core/commands.d.ts +17 -2
- package/dist/types/core/comments.d.ts +39 -3
- package/dist/types/core/convert.d.ts +10 -2
- package/dist/types/core/extension.d.ts +58 -4
- package/dist/types/core/model.d.ts +6 -1
- package/dist/types/core/prepare.d.ts +16 -2
- package/dist/types/core/schema.d.ts +1 -1
- package/dist/types/core/transaction.d.ts +6 -0
- package/dist/types/define-block.d.ts +16 -4
- package/dist/types/document.d.ts +5 -2
- package/dist/types/dom.d.ts +41 -4
- package/dist/types/editor.d.ts +15 -1
- package/dist/types/editor.vue.d.ts +24 -0
- package/dist/types/extensions/columns/column-picker.vue.d.ts +10 -0
- package/dist/types/extensions/columns/columns-controls.vue.d.ts +3 -0
- package/dist/types/extensions/columns/html.d.ts +10 -0
- package/dist/types/extensions/columns/index.d.ts +9 -0
- package/dist/types/extensions/columns/keys.d.ts +6 -0
- package/dist/types/extensions/columns/plugin.d.ts +28 -0
- package/dist/types/extensions/columns/schema.d.ts +17 -0
- package/dist/types/extensions/columns/select-columns.vue.d.ts +13 -0
- package/dist/types/extensions/editor-kit.d.ts +4 -1
- package/dist/types/extensions/table/view.d.ts +36 -2
- package/dist/types/flow/board-block.vue.d.ts +16 -0
- package/dist/types/flow/board.d.ts +53 -0
- package/dist/types/flow/index.d.ts +65 -0
- package/dist/types/index.d.ts +29 -4
- package/dist/types/locale.d.ts +34 -0
- package/dist/types/markdown/cjk-friendly.d.ts +6 -0
- package/dist/types/markdown/index.d.ts +11 -4
- package/dist/types/use-comments.d.ts +1 -0
- package/dist/use-comments.js +63 -9
- package/dist/use-comments.js.map +1 -1
- package/package.json +14 -5
|
@@ -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,QAAQ,GAAG;CAClC,MAAM,OAAO,KAAK,OAAO,WAAW,KAAK,YAAY,CAAC,CAAC;CACvD,IAAI,CAAC,MAAM,OAAO,CAAC;CACnB,MAAM,MAAM,KAAK,MACd,QAAQ,SAAS,KAAK,KAAK,SAAS,SAAS,CAAC,CAC9C,KAAK,SAAS,KAAK,MAAM,EAAY;CACxC,IAAI,IAAI,SAAS,GAAG,OAAO;CAC3B,MAAM,SAAS,IAAI,IAAI,IAAI,KAAK,OAAO,CAAC,IAAI,YAAY,MAAM,KAAK,IAAI,GAAG,CAAC,CAAC,CAAC;CAE7E,OAAO,IAAI,MAAM,GAAG,MAAM,OAAO,IAAI,CAAC,IAAK,OAAO,IAAI,CAAC,CAAE;AAC3D;;AAGA,SAAS,YAAY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,MAAM,WAAW,CAAC,GAAG,YAAY,OAAO;IACxD,OAAO;KAAE;KAAS,aAAa,mBAAmB,GAAG,KAAK,OAAO;IAAE;GACrE;EACF;EACA,YAAY;GACV,IAAI,OAA4B;GAChC,OAAO,EACL,OAAO,MAAM,UAAU;IACrB,MAAM,UAAU,WAAW,SAAS,KAAK,KAAK,CAAC,CAAE;IACjD,IAAI,YAAY,MAAM,QAAQ,UAAW,OAAO,OAAQ;IACxD,MAAM,EAAE,cAAc,KAAK;IAE3B,IACE,CAAC,UAAU,SACX,KAAK,MAAM,QAAQ,SAAS,OAC5B,CAAC,UAAU,GAAG,SAAS,SAAS,GAEhC,QAAQ,SAAS;GACrB,EACF;EACF;EACA,OAAO;GACL,cAAc,UAAU,WAAW,SAAS,KAAK,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"}
|
|
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,OAAO,MAAM,MAAM,MAAM,IAAI,EAAE,OAAO,8BAA8B,CAAC,CAClF,CAAC,IACD,cAAc;;AAGpB,SAAgB,WAAW,OAAoB,KAAuB;CACpE,MAAM,OAAO,MAAM,IAAI,QAAQ,GAAG;CAClC,MAAM,OAAO,KAAK,OAAO,WAAW,KAAK,YAAY,CAAC,CAAC;CACvD,IAAI,CAAC,MAAM,OAAO,CAAC;CACnB,MAAM,MAAM,KAAK,MACd,QAAQ,SAAS,KAAK,KAAK,SAAS,SAAS,CAAC,CAC9C,KAAK,SAAS,KAAK,MAAM,EAAY;CACxC,IAAI,IAAI,SAAS,GAAG,OAAO;CAC3B,MAAM,SAAS,IAAI,IAAI,IAAI,KAAK,OAAO,CAAC,IAAI,YAAY,MAAM,KA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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/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;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,CA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":[],"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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C,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"}
|
package/dist/core/model.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { isColor } from "./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,YA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AAM,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(`[@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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"}
|
package/dist/core/output.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { isColor } from "./colors.js";
|
|
2
2
|
import { isAlign } from "./align.js";
|
|
3
3
|
import { isSafeHref } from "./schema.js";
|
|
4
|
+
import { isCjkCodePoint, isNonEmojiGeneralUseVS, nextCodePoint, previousCodePoint } from "./cjk.js";
|
|
4
5
|
// src/core/output.ts
|
|
5
6
|
var tagsOf = (tags, value) => typeof tags === "function" ? tags(value) : tags;
|
|
6
7
|
function outputsOf(kit) {
|
|
@@ -117,16 +118,28 @@ function escapeLine(text) {
|
|
|
117
118
|
var escapeMarkdown = (text) => text.replace(SPECIAL, "\\$&");
|
|
118
119
|
var PUNCTUATION = /[\p{P}\p{S}]/u;
|
|
119
120
|
var SPACE = /\s/u;
|
|
121
|
+
/** Resolve the code point right before a delimiter, looking past a non-emoji general-use VS. */
|
|
122
|
+
function beforeCodePoint(text) {
|
|
123
|
+
const [last, lastPos] = previousCodePoint(text, text.length);
|
|
124
|
+
if (!isNonEmojiGeneralUseVS(last)) return last;
|
|
125
|
+
const [prevBase] = previousCodePoint(text, lastPos);
|
|
126
|
+
return SPACE.test(String.fromCodePoint(prevBase)) ? last : prevBase;
|
|
127
|
+
}
|
|
120
128
|
/**
|
|
121
129
|
* Whether a delimiter such as `**` can open (or close) emphasis here: the
|
|
122
130
|
* text inside must not start (end) with a space, and when it starts (ends)
|
|
123
|
-
* with punctuation, the outside must be a space, punctuation
|
|
131
|
+
* with punctuation, the outside must be a space, punctuation, the edge, or a
|
|
132
|
+
* CJK boundary (matching CommonMark CJK-friendly and `DouMarkdown`).
|
|
124
133
|
* Otherwise the HTML tag is written, which Markdown reads as well.
|
|
125
134
|
*/
|
|
126
135
|
function flanks(inner, outer) {
|
|
127
|
-
if (
|
|
128
|
-
|
|
129
|
-
|
|
136
|
+
if (inner === void 0) return false;
|
|
137
|
+
const innerChar = String.fromCodePoint(inner);
|
|
138
|
+
if (SPACE.test(innerChar)) return false;
|
|
139
|
+
if (!PUNCTUATION.test(innerChar)) return true;
|
|
140
|
+
if (outer === void 0) return true;
|
|
141
|
+
const outerChar = String.fromCodePoint(outer);
|
|
142
|
+
return SPACE.test(outerChar) || PUNCTUATION.test(outerChar) || isCjkCodePoint(inner) || isCjkCodePoint(outer);
|
|
130
143
|
}
|
|
131
144
|
function codeSpan(text) {
|
|
132
145
|
const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length));
|
|
@@ -154,17 +167,20 @@ var textOf = (item) => item?.type === "text" ? item.text : item?.type === "inlin
|
|
|
154
167
|
function inlineMarkdown(content, outputs) {
|
|
155
168
|
let result = "";
|
|
156
169
|
const stack = [];
|
|
157
|
-
/** The text a mark will cover from `start`, and the
|
|
170
|
+
/** The text a mark will cover from `start`, and the text immediately after it. */
|
|
158
171
|
function span(start, key) {
|
|
159
|
-
let
|
|
172
|
+
let raw = "";
|
|
160
173
|
let end = start;
|
|
161
174
|
while (end < content.length && keysOf(content[end], outputs).includes(key)) {
|
|
162
|
-
|
|
175
|
+
raw += textOf(content[end]);
|
|
163
176
|
end++;
|
|
164
177
|
}
|
|
178
|
+
let after = "";
|
|
179
|
+
if (end > start && /\S\s+$/.test(textOf(content[end - 1]))) after = " ";
|
|
180
|
+
else while (end < content.length && !after) after = textOf(content[end++]);
|
|
165
181
|
return {
|
|
166
|
-
text:
|
|
167
|
-
after
|
|
182
|
+
text: raw.trim(),
|
|
183
|
+
after
|
|
168
184
|
};
|
|
169
185
|
}
|
|
170
186
|
function open(key, start) {
|
|
@@ -183,7 +199,7 @@ function inlineMarkdown(content, outputs) {
|
|
|
183
199
|
};
|
|
184
200
|
const { text, after } = span(start, key);
|
|
185
201
|
const delimiter = tags.markdown;
|
|
186
|
-
const [opening, closing] = delimiter && flanks(text
|
|
202
|
+
const [opening, closing] = delimiter && text.length > 0 && flanks(nextCodePoint(text, 0), result ? beforeCodePoint(result) : void 0) && flanks(beforeCodePoint(text), after ? nextCodePoint(after, 0) : void 0) ? delimiter : tags.html ?? delimiter;
|
|
187
203
|
result += opening;
|
|
188
204
|
stack.push({
|
|
189
205
|
key,
|
package/dist/core/output.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"output.js","names":[],"sources":["../../src/core/output.ts"],"sourcesContent":["import type { ResolvedEditorExtensions } from './extension'\nimport type { Block, InlineContent, MarkField, PartialBlock } from './model'\nimport { isAlign } from './align'\nimport { isColor } from './colors'\nimport { isSafeHref } from './schema'\n\n/** What a block's writer gets besides the block. */\nexport interface BlockOutputContext {\n /** The block's text, already written in the output format. */\n content: string\n /** The block's text without formatting (e.g. for a code block). */\n text: string\n /** The child blocks, already written. */\n children: string\n /** The block's position, from 1, among the siblings of the same type right before it. */\n index: number\n /** Write other inline content (e.g. a table cell's) in the same format. */\n inline: (content: InlineContent[]) => string\n}\n\nexport interface MarkdownBlockContext extends BlockOutputContext {\n /** The block's text as HTML, for Markdown that holds HTML (e.g. `<summary>`). */\n html: string\n /** Write other inline content as HTML. */\n inlineHTML: (content: InlineContent[]) => string\n}\n\n/** How a block type is written as HTML and Markdown. */\nexport interface BlockOutput {\n html?: (block: Block, context: BlockOutputContext) => string\n /**\n * Consecutive blocks with the same `group` sit in one element, written\n * as its opening tag (e.g. `ul`, `ol`); in Markdown they are kept\n * together without blank lines.\n */\n group?: string\n markdown?: (block: Block, context: MarkdownBlockContext) => string\n}\n\n/** How an inline node (e.g. a mention) is written. */\nexport interface InlineOutput {\n html?: (props: Record<string, unknown>) => string\n markdown?: (props: Record<string, unknown>) => string\n}\n\n/**\n * How a mark is written: the text between an opening and a closing string.\n * A mark with a value (a color) gives a function of the value.\n */\nexport type MarkTags = [open: string, close: string]\n\nexport interface MarkOutput {\n html?: MarkTags | ((value: string) => MarkTags)\n markdown?: MarkTags | ((value: string) => MarkTags)\n}\n\n/** What an extension contributes to `blocksToHTML` and `blocksToMarkdown`. */\nexport interface EditorExtensionOutput {\n blocks?: Record<string, BlockOutput>\n inlines?: Record<string, InlineOutput>\n marks?: Record<string, MarkOutput>\n}\n\ninterface Outputs {\n blocks: Record<string, BlockOutput>\n inlines: Record<string, InlineOutput>\n marks: Record<string, MarkOutput>\n /** Marks stored as a field of the text run, by field: `color` → `textColor`. */\n fields: [field: MarkField, mark: string][]\n /** The block types that can be aligned. */\n aligned: Set<string>\n}\n\nconst tagsOf = (tags: MarkOutput['html'] | undefined, value: string): MarkTags | undefined =>\n typeof tags === 'function' ? tags(value) : tags\n\nfunction outputsOf(kit: ResolvedEditorExtensions): Outputs {\n const fields = Object.values(kit.schema.marks)\n .filter((type) => type.spec.field)\n .map((type) => [type.spec.field as MarkField, type.name] as [MarkField, string])\n const aligned = new Set(\n Object.values(kit.schema.nodes)\n .filter((type) => type.spec.attrs?.align)\n .map((type) => type.name),\n )\n const outputs: Outputs = { blocks: {}, inlines: {}, marks: {}, fields, aligned }\n // extensions that come first win, as with their keys\n for (let index = kit.extensions.length - 1; index >= 0; index--) {\n const extension = kit.extensions[index]!\n Object.assign(outputs.blocks, extension.output?.blocks)\n Object.assign(outputs.inlines, extension.output?.inlines)\n Object.assign(outputs.marks, extension.output?.marks)\n }\n return outputs\n}\n\n/** Fill in what a partial block leaves out, so writers always get a whole block. */\nconst toInline = (content: InlineContent[] | string): InlineContent[] =>\n typeof content === 'string' ? (content ? [{ type: 'text', text: content }] : []) : content\n\nfunction complete(block: PartialBlock): Block {\n const result: Block = {\n id: block.id ?? '',\n type: block.type ?? 'paragraph',\n props: block.props ?? {},\n content: toInline(block.content ?? []),\n children: (block.children ?? []).map(complete),\n }\n if (block.rows)\n result.rows = block.rows.map((row) => ({\n id: row.id ?? '',\n cells: row.cells.map((cell) =>\n typeof cell === 'string'\n ? { content: toInline(cell) }\n : { ...cell, content: toInline(cell.content ?? []) },\n ),\n }))\n return result\n}\n\n/* HTML */\n\nexport const escapeHTML = (text: string) =>\n text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"')\n\nconst plainText = (content: InlineContent[]) =>\n content\n .map((item) => (item.type === 'text' ? item.text : item.type === 'break' ? '\\n' : ''))\n .join('')\n\nfunction inlineHTML(content: InlineContent[], outputs: Outputs): string {\n let result = ''\n for (const item of content) {\n if (item.type === 'break') result += '<br>'\n else if (item.type === 'inline') result += outputs.inlines[item.name]?.html?.(item.props) ?? ''\n else {\n let text = escapeHTML(item.text)\n const marks = item.marks ?? []\n for (let index = marks.length - 1; index >= 0; index--) {\n const tags = tagsOf(outputs.marks[marks[index]!]?.html, '')\n if (tags) text = tags[0] + text + tags[1]\n }\n // highlight inside the color, both inside a link\n for (let index = outputs.fields.length - 1; index >= 0; index--) {\n const [field, mark] = outputs.fields[index]!\n const value = item[field]\n const tags = isColor(value) && tagsOf(outputs.marks[mark]?.html, value)\n if (tags) text = tags[0] + text + tags[1]\n }\n if (item.link && isSafeHref(item.link))\n text = `<a href=\"${escapeHTML(item.link)}\">${text}</a>`\n result += text\n }\n }\n return result\n}\n\nconst closingTag = (group: string) => `</${group.split(/\\s/)[0]}>`\n\n/** An aligned block's first element gets `style=\"text-align: …\"`. */\nfunction withAlign(html: string, align: unknown): string {\n if (!isAlign(align) || align === 'left') return html\n return html.replace(/^<([a-z][a-z0-9]*)/i, `<$1 style=\"text-align: ${align}\"`)\n}\n\n/** Top-level blocks go on lines of their own, so the HTML stays readable. */\nfunction blocksHTML(blocks: Block[], outputs: Outputs, top = false): string {\n const newline = top ? '\\n' : ''\n let result = ''\n let group: string | undefined\n let index = 0\n blocks.forEach((block, position) => {\n const output = outputs.blocks[block.type]\n index = position > 0 && blocks[position - 1]!.type === block.type ? index + 1 : 1\n if (output?.group !== group) {\n if (group) result += newline + closingTag(group)\n group = output?.group\n if (group) result += (result ? newline : '') + `<${group}>`\n }\n if (result) result += newline\n const context: BlockOutputContext = {\n content: inlineHTML(block.content, outputs),\n text: plainText(block.content),\n children: blocksHTML(block.children, outputs),\n index,\n inline: (content) => inlineHTML(content, outputs),\n }\n const html = output?.html\n ? output.html(block, context)\n : `<p>${context.content}</p>${context.children}`\n // only blocks that can be aligned, as the editor would keep them\n result += outputs.aligned.has(block.type) ? withAlign(html, block.props.align) : html\n })\n if (group) result += newline + closingTag(group)\n return result\n}\n\n/**\n * Write blocks as HTML, e.g. to show a document outside the editor or to\n * send it by email. Each extension decides how its blocks look; the\n * result has no editor classes.\n */\nexport function writeHTML(blocks: PartialBlock[], kit: ResolvedEditorExtensions): string {\n return blocksHTML(blocks.map(complete), outputsOf(kit), true)\n}\n\n/* Markdown */\n\n/** Characters that mean something anywhere in Markdown text. */\nconst SPECIAL = /[\\\\`*_[\\]<>~|]|&(?=#?\\w+;)/g\n\n/** What would start a block at the beginning of a line. */\nconst LINE_START = /^(\\s*)(#{1,6}(?=\\s|$)|[-+](?=\\s|$)|-+(?=\\s*$)|=+(?=\\s*$)|(\\d+)([.)])(?=\\s|$))/\n\nfunction escapeLine(text: string): string {\n return text.replace(\n LINE_START,\n (_all, space: string, mark: string, digits?: string, dot?: string) =>\n digits ? `${space}${digits}\\\\${dot}` : `${space}\\\\${mark}`,\n )\n}\n\nexport const escapeMarkdown = (text: string) => text.replace(SPECIAL, '\\\\$&')\n\nconst PUNCTUATION = /[\\p{P}\\p{S}]/u\nconst SPACE = /\\s/u\n\n/**\n * Whether a delimiter such as `**` can open (or close) emphasis here: the\n * text inside must not start (end) with a space, and when it starts (ends)\n * with punctuation, the outside must be a space, punctuation or the edge.\n * Otherwise the HTML tag is written, which Markdown reads as well.\n */\nfunction flanks(inner: string | undefined, outer: string | undefined) {\n if (!inner || SPACE.test(inner)) return false\n if (!PUNCTUATION.test(inner)) return true\n return !outer || SPACE.test(outer) || PUNCTUATION.test(outer)\n}\n\nfunction codeSpan(text: string): string {\n const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length))\n const fence = '`'.repeat(longest + 1)\n const pad =\n /^`|`$/.test(text) || (text.startsWith(' ') && text.endsWith(' ') && text.trim()) ? ' ' : ''\n return fence + pad + text + pad + fence\n}\n\n/** A key for each formatting a run has, outermost first: the link, then the marks. */\nfunction keysOf(item: InlineContent, outputs: Outputs): string[] {\n if (item.type !== 'text') return []\n const keys: string[] = []\n if (item.link && isSafeHref(item.link)) keys.push(`link:${item.link}`)\n for (const [field, mark] of outputs.fields) {\n const value = item[field]\n if (isColor(value) && hasOutput(mark, outputs)) keys.push(`${mark}=${value}`)\n }\n for (const mark of item.marks ?? [])\n if (mark !== 'code' && hasOutput(mark, outputs)) keys.push(mark)\n return keys\n}\n\nconst hasOutput = (mark: string, outputs: Outputs) =>\n !!(outputs.marks[mark]?.markdown ?? outputs.marks[mark]?.html)\n\nfunction linkDestination(href: string) {\n return /[\\s()<>]/.test(href) ? `<${href.replace(/[<>]/g, encodeURIComponent)}>` : href\n}\n\nconst textOf = (item: InlineContent | undefined) =>\n item?.type === 'text' ? item.text : item?.type === 'inline' ? '@' : item ? '\\n' : ''\n\nfunction inlineMarkdown(content: InlineContent[], outputs: Outputs): string {\n let result = ''\n const stack: { key: string; close: string }[] = []\n\n /** The text a mark will cover from `start`, and the character after it. */\n function span(start: number, key: string) {\n let text = ''\n let end = start\n while (end < content.length && keysOf(content[end]!, outputs).includes(key)) {\n text += textOf(content[end])\n end++\n }\n return { text: text.trim(), after: textOf(content[end])[0] }\n }\n\n function open(key: string, start: number) {\n if (key.startsWith('link:')) {\n stack.push({ key, close: `](${linkDestination(key.slice(5))})` })\n result += '['\n return\n }\n const [name, value = ''] = key.split('=') as [string, string?]\n const tags = {\n markdown: tagsOf(outputs.marks[name]!.markdown, value),\n html: tagsOf(outputs.marks[name]!.html, value),\n }\n const { text, after } = span(start, key)\n const delimiter = tags.markdown\n const usable =\n delimiter && flanks(text[0], result.at(-1)) && flanks(text.at(-1), after ?? undefined)\n const [opening, closing] = usable ? delimiter : (tags.html ?? delimiter!)\n result += opening\n stack.push({ key, close: closing })\n }\n\n content.forEach((item, index) => {\n const keys = keysOf(item, outputs)\n let keep = 0\n while (keep < stack.length && keys.includes(stack[keep]!.key)) keep++\n // spaces at the edges of formatted text go outside the delimiters\n let text = item.type === 'text' ? item.text : ''\n const lead = keys.length > keep ? (/^\\s+/.exec(text)?.[0] ?? '') : ''\n while (stack.length > keep) result += stack.pop()!.close\n result += lead\n text = text.slice(lead.length)\n for (const key of keys) if (!stack.some((entry) => entry.key === key)) open(key, index)\n\n if (item.type === 'break') {\n result += '\\\\\\n'\n return\n }\n if (item.type === 'inline') {\n result += outputs.inlines[item.name]?.markdown?.(item.props) ?? ''\n return\n }\n const nextKeys = keysOf(content[index + 1] ?? { type: 'break' }, outputs)\n const closes = stack.some((entry) => !nextKeys.includes(entry.key))\n const trail = closes ? (/\\s+$/.exec(text)?.[0] ?? '') : ''\n if (trail) text = text.slice(0, -trail.length)\n let written = item.marks?.includes('code') ? codeSpan(text) : escapeMarkdown(text)\n if (!item.marks?.includes('code')) written = written.split('\\n').map(escapeLine).join('\\n')\n result += written\n if (trail) {\n // close what ends here before the spaces; the next run closes nothing more\n const stay = stack.findIndex((entry) => !nextKeys.includes(entry.key))\n while (stack.length > stay) result += stack.pop()!.close\n result += trail\n }\n })\n while (stack.length) result += stack.pop()!.close\n return result\n}\n\n/** Put `prefix` before every line, and `rest` (default: as many spaces) before the ones after the first. */\nexport function indentLines(\n text: string,\n prefix: string,\n rest = ' '.repeat(prefix.length),\n): string {\n return text\n .split('\\n')\n .map((line, index) => (index === 0 ? prefix + line : line ? rest + line : rest.trimEnd()))\n .join('\\n')\n}\n\nfunction blocksMarkdown(blocks: Block[], outputs: Outputs): string {\n let result = ''\n let index = 0\n blocks.forEach((block, position) => {\n const output = outputs.blocks[block.type]\n const previous = blocks[position - 1]\n index = previous?.type === block.type ? index + 1 : 1\n const context: MarkdownBlockContext = {\n content: inlineMarkdown(block.content, outputs),\n html: inlineHTML(block.content, outputs),\n text: plainText(block.content),\n children: blocksMarkdown(block.children, outputs),\n index,\n inline: (content) => inlineMarkdown(content, outputs),\n inlineHTML: (content) => inlineHTML(content, outputs),\n }\n const written = output?.markdown\n ? output.markdown(block, context)\n : [context.content, context.children].filter(Boolean).join('\\n\\n')\n if (!written) return\n if (result) {\n const tight =\n previous && output?.group && outputs.blocks[previous.type]?.group === output.group\n result += tight ? '\\n' : '\\n\\n'\n }\n result += written\n })\n return result\n}\n\n/** Write blocks as Markdown (CommonMark with GitHub's extensions). */\nexport function writeMarkdown(blocks: PartialBlock[], kit: ResolvedEditorExtensions): string {\n const markdown = blocksMarkdown(blocks.map(complete), outputsOf(kit))\n return markdown ? `${markdown}\\n` : ''\n}\n"],"mappings":";;;;AAyEA,IAAM,UAAU,MAAsC,UACpD,OAAO,SAAS,aAAa,KAAK,KAAK,IAAI;AAE7C,SAAS,UAAU,KAAwC;CASzD,MAAM,UAAmB;EAAE,QAAQ,CAAC;EAAG,SAAS,CAAC;EAAG,OAAO,CAAC;EAAG,QARhD,OAAO,OAAO,IAAI,OAAO,KAAK,CAAC,CAC3C,QAAQ,SAAS,KAAK,KAAK,KAAK,CAAC,CACjC,KAAK,SAAS,CAAC,KAAK,KAAK,OAAoB,KAAK,IAAI,CAMM;EAAQ,SAAA,IALnD,IAClB,OAAO,OAAO,IAAI,OAAO,KAAK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orExtensions } from './extension'\nimport type { Block, InlineContent, MarkField, PartialBlock } from './model'\nimport { isAlign } from './align'\nimport { isCjkCodePoint, isNonEmojiGeneralUseVS, nextCodePoint, previousCodePoint } from './cjk'\nimport { isColor } from './colors'\nimport { isSafeHref } from './schema'\n\n/** What a block's writer gets besides the block. */\nexport interface BlockOutputContext {\n /** The block's text, already written in the output format. */\n content: string\n /** The block's text without formatting (e.g. for a code block). */\n text: string\n /** The child blocks, already written. */\n children: string\n /** The block's position, from 1, among the siblings of the same type right before it. */\n index: number\n /** Write other inline content (e.g. a table cell's) in the same format. */\n inline: (content: InlineContent[]) => string\n}\n\nexport interface MarkdownBlockContext extends BlockOutputContext {\n /** The block's text as HTML, for Markdown that holds HTML (e.g. `<summary>`). */\n html: string\n /** Write other inline content as HTML. */\n inlineHTML: (content: InlineContent[]) => string\n}\n\n/** How a block type is written as HTML and Markdown. */\nexport interface BlockOutput {\n html?: (block: Block, context: BlockOutputContext) => string\n /**\n * Consecutive blocks with the same `group` sit in one element, written\n * as its opening tag (e.g. `ul`, `ol`); in Markdown they are kept\n * together without blank lines.\n */\n group?: string\n markdown?: (block: Block, context: MarkdownBlockContext) => string\n}\n\n/** How an inline node (e.g. a mention) is written. */\nexport interface InlineOutput {\n html?: (props: Record<string, unknown>) => string\n markdown?: (props: Record<string, unknown>) => string\n}\n\n/**\n * How a mark is written: the text between an opening and a closing string.\n * A mark with a value (a color) gives a function of the value.\n */\nexport type MarkTags = [open: string, close: string]\n\nexport interface MarkOutput {\n html?: MarkTags | ((value: string) => MarkTags)\n markdown?: MarkTags | ((value: string) => MarkTags)\n}\n\n/** What an extension contributes to `blocksToHTML` and `blocksToMarkdown`. */\nexport interface EditorExtensionOutput {\n blocks?: Record<string, BlockOutput>\n inlines?: Record<string, InlineOutput>\n marks?: Record<string, MarkOutput>\n}\n\ninterface Outputs {\n blocks: Record<string, BlockOutput>\n inlines: Record<string, InlineOutput>\n marks: Record<string, MarkOutput>\n /** Marks stored as a field of the text run, by field: `color` → `textColor`. */\n fields: [field: MarkField, mark: string][]\n /** The block types that can be aligned. */\n aligned: Set<string>\n}\n\nconst tagsOf = (tags: MarkOutput['html'] | undefined, value: string): MarkTags | undefined =>\n typeof tags === 'function' ? tags(value) : tags\n\nfunction outputsOf(kit: ResolvedEditorExtensions): Outputs {\n const fields = Object.values(kit.schema.marks)\n .filter((type) => type.spec.field)\n .map((type) => [type.spec.field as MarkField, type.name] as [MarkField, string])\n const aligned = new Set(\n Object.values(kit.schema.nodes)\n .filter((type) => type.spec.attrs?.align)\n .map((type) => type.name),\n )\n const outputs: Outputs = { blocks: {}, inlines: {}, marks: {}, fields, aligned }\n // extensions that come first win, as with their keys\n for (let index = kit.extensions.length - 1; index >= 0; index--) {\n const extension = kit.extensions[index]!\n Object.assign(outputs.blocks, extension.output?.blocks)\n Object.assign(outputs.inlines, extension.output?.inlines)\n Object.assign(outputs.marks, extension.output?.marks)\n }\n return outputs\n}\n\n/** Fill in what a partial block leaves out, so writers always get a whole block. */\nconst toInline = (content: InlineContent[] | string): InlineContent[] =>\n typeof content === 'string' ? (content ? [{ type: 'text', text: content }] : []) : content\n\nfunction complete(block: PartialBlock): Block {\n const result: Block = {\n id: block.id ?? '',\n type: block.type ?? 'paragraph',\n props: block.props ?? {},\n content: toInline(block.content ?? []),\n children: (block.children ?? []).map(complete),\n }\n if (block.rows)\n result.rows = block.rows.map((row) => ({\n id: row.id ?? '',\n cells: row.cells.map((cell) =>\n typeof cell === 'string'\n ? { content: toInline(cell) }\n : { ...cell, content: toInline(cell.content ?? []) },\n ),\n }))\n return result\n}\n\n/* HTML */\n\nexport const escapeHTML = (text: string) =>\n text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"')\n\nconst plainText = (content: InlineContent[]) =>\n content\n .map((item) => (item.type === 'text' ? item.text : item.type === 'break' ? '\\n' : ''))\n .join('')\n\nfunction inlineHTML(content: InlineContent[], outputs: Outputs): string {\n let result = ''\n for (const item of content) {\n if (item.type === 'break') result += '<br>'\n else if (item.type === 'inline') result += outputs.inlines[item.name]?.html?.(item.props) ?? ''\n else {\n let text = escapeHTML(item.text)\n const marks = item.marks ?? []\n for (let index = marks.length - 1; index >= 0; index--) {\n const tags = tagsOf(outputs.marks[marks[index]!]?.html, '')\n if (tags) text = tags[0] + text + tags[1]\n }\n // highlight inside the color, both inside a link\n for (let index = outputs.fields.length - 1; index >= 0; index--) {\n const [field, mark] = outputs.fields[index]!\n const value = item[field]\n const tags = isColor(value) && tagsOf(outputs.marks[mark]?.html, value)\n if (tags) text = tags[0] + text + tags[1]\n }\n if (item.link && isSafeHref(item.link))\n text = `<a href=\"${escapeHTML(item.link)}\">${text}</a>`\n result += text\n }\n }\n return result\n}\n\nconst closingTag = (group: string) => `</${group.split(/\\s/)[0]}>`\n\n/** An aligned block's first element gets `style=\"text-align: …\"`. */\nfunction withAlign(html: string, align: unknown): string {\n if (!isAlign(align) || align === 'left') return html\n return html.replace(/^<([a-z][a-z0-9]*)/i, `<$1 style=\"text-align: ${align}\"`)\n}\n\n/** Top-level blocks go on lines of their own, so the HTML stays readable. */\nfunction blocksHTML(blocks: Block[], outputs: Outputs, top = false): string {\n const newline = top ? '\\n' : ''\n let result = ''\n let group: string | undefined\n let index = 0\n blocks.forEach((block, position) => {\n const output = outputs.blocks[block.type]\n index = position > 0 && blocks[position - 1]!.type === block.type ? index + 1 : 1\n if (output?.group !== group) {\n if (group) result += newline + closingTag(group)\n group = output?.group\n if (group) result += (result ? newline : '') + `<${group}>`\n }\n if (result) result += newline\n const context: BlockOutputContext = {\n content: inlineHTML(block.content, outputs),\n text: plainText(block.content),\n children: blocksHTML(block.children, outputs),\n index,\n inline: (content) => inlineHTML(content, outputs),\n }\n const html = output?.html\n ? output.html(block, context)\n : `<p>${context.content}</p>${context.children}`\n // only blocks that can be aligned, as the editor would keep them\n result += outputs.aligned.has(block.type) ? withAlign(html, block.props.align) : html\n })\n if (group) result += newline + closingTag(group)\n return result\n}\n\n/**\n * Write blocks as HTML, e.g. to show a document outside the editor or to\n * send it by email. Each extension decides how its blocks look; the\n * result has no editor classes.\n */\nexport function writeHTML(blocks: PartialBlock[], kit: ResolvedEditorExtensions): string {\n return blocksHTML(blocks.map(complete), outputsOf(kit), true)\n}\n\n/* Markdown */\n\n/** Characters that mean something anywhere in Markdown text. */\nconst SPECIAL = /[\\\\`*_[\\]<>~|]|&(?=#?\\w+;)/g\n\n/** What would start a block at the beginning of a line. */\nconst LINE_START = /^(\\s*)(#{1,6}(?=\\s|$)|[-+](?=\\s|$)|-+(?=\\s*$)|=+(?=\\s*$)|(\\d+)([.)])(?=\\s|$))/\n\nfunction escapeLine(text: string): string {\n return text.replace(\n LINE_START,\n (_all, space: string, mark: string, digits?: string, dot?: string) =>\n digits ? `${space}${digits}\\\\${dot}` : `${space}\\\\${mark}`,\n )\n}\n\nexport const escapeMarkdown = (text: string) => text.replace(SPECIAL, '\\\\$&')\n\nconst PUNCTUATION = /[\\p{P}\\p{S}]/u\nconst SPACE = /\\s/u\n\n/** Resolve the code point right before a delimiter, looking past a non-emoji general-use VS. */\nfunction beforeCodePoint(text: string): number {\n const [last, lastPos] = previousCodePoint(text, text.length)\n if (!isNonEmojiGeneralUseVS(last)) return last\n const [prevBase] = previousCodePoint(text, lastPos)\n return SPACE.test(String.fromCodePoint(prevBase)) ? last : prevBase\n}\n\n/**\n * Whether a delimiter such as `**` can open (or close) emphasis here: the\n * text inside must not start (end) with a space, and when it starts (ends)\n * with punctuation, the outside must be a space, punctuation, the edge, or a\n * CJK boundary (matching CommonMark CJK-friendly and `DouMarkdown`).\n * Otherwise the HTML tag is written, which Markdown reads as well.\n */\nfunction flanks(inner: number | undefined, outer: number | undefined): boolean {\n if (inner === undefined) return false\n const innerChar = String.fromCodePoint(inner)\n if (SPACE.test(innerChar)) return false\n if (!PUNCTUATION.test(innerChar)) return true\n if (outer === undefined) return true\n const outerChar = String.fromCodePoint(outer)\n return (\n SPACE.test(outerChar) ||\n PUNCTUATION.test(outerChar) ||\n isCjkCodePoint(inner) ||\n isCjkCodePoint(outer)\n )\n}\n\nfunction codeSpan(text: string): string {\n const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length))\n const fence = '`'.repeat(longest + 1)\n const pad =\n /^`|`$/.test(text) || (text.startsWith(' ') && text.endsWith(' ') && text.trim()) ? ' ' : ''\n return fence + pad + text + pad + fence\n}\n\n/** A key for each formatting a run has, outermost first: the link, then the marks. */\nfunction keysOf(item: InlineContent, outputs: Outputs): string[] {\n if (item.type !== 'text') return []\n const keys: string[] = []\n if (item.link && isSafeHref(item.link)) keys.push(`link:${item.link}`)\n for (const [field, mark] of outputs.fields) {\n const value = item[field]\n if (isColor(value) && hasOutput(mark, outputs)) keys.push(`${mark}=${value}`)\n }\n for (const mark of item.marks ?? [])\n if (mark !== 'code' && hasOutput(mark, outputs)) keys.push(mark)\n return keys\n}\n\nconst hasOutput = (mark: string, outputs: Outputs) =>\n !!(outputs.marks[mark]?.markdown ?? outputs.marks[mark]?.html)\n\nfunction linkDestination(href: string) {\n return /[\\s()<>]/.test(href) ? `<${href.replace(/[<>]/g, encodeURIComponent)}>` : href\n}\n\nconst textOf = (item: InlineContent | undefined) =>\n item?.type === 'text' ? item.text : item?.type === 'inline' ? '@' : item ? '\\n' : ''\n\nfunction inlineMarkdown(content: InlineContent[], outputs: Outputs): string {\n let result = ''\n const stack: { key: string; close: string }[] = []\n\n /** The text a mark will cover from `start`, and the text immediately after it. */\n function span(start: number, key: string) {\n let raw = ''\n let end = start\n while (end < content.length && keysOf(content[end]!, outputs).includes(key)) {\n raw += textOf(content[end])\n end++\n }\n let after = ''\n if (end > start && /\\S\\s+$/.test(textOf(content[end - 1]))) {\n after = ' '\n } else {\n while (end < content.length && !after) after = textOf(content[end++])\n }\n return { text: raw.trim(), after }\n }\n\n function open(key: string, start: number) {\n if (key.startsWith('link:')) {\n stack.push({ key, close: `](${linkDestination(key.slice(5))})` })\n result += '['\n return\n }\n const [name, value = ''] = key.split('=') as [string, string?]\n const tags = {\n markdown: tagsOf(outputs.marks[name]!.markdown, value),\n html: tagsOf(outputs.marks[name]!.html, value),\n }\n const { text, after } = span(start, key)\n const delimiter = tags.markdown\n const usable =\n delimiter &&\n text.length > 0 &&\n flanks(nextCodePoint(text, 0), result ? beforeCodePoint(result) : undefined) &&\n flanks(beforeCodePoint(text), after ? nextCodePoint(after, 0) : undefined)\n const [opening, closing] = usable ? delimiter : (tags.html ?? delimiter!)\n result += opening\n stack.push({ key, close: closing })\n }\n\n content.forEach((item, index) => {\n const keys = keysOf(item, outputs)\n let keep = 0\n while (keep < stack.length && keys.includes(stack[keep]!.key)) keep++\n // spaces at the edges of formatted text go outside the delimiters\n let text = item.type === 'text' ? item.text : ''\n const lead = keys.length > keep ? (/^\\s+/.exec(text)?.[0] ?? '') : ''\n while (stack.length > keep) result += stack.pop()!.close\n result += lead\n text = text.slice(lead.length)\n for (const key of keys) if (!stack.some((entry) => entry.key === key)) open(key, index)\n\n if (item.type === 'break') {\n result += '\\\\\\n'\n return\n }\n if (item.type === 'inline') {\n result += outputs.inlines[item.name]?.markdown?.(item.props) ?? ''\n return\n }\n const nextKeys = keysOf(content[index + 1] ?? { type: 'break' }, outputs)\n const closes = stack.some((entry) => !nextKeys.includes(entry.key))\n const trail = closes ? (/\\s+$/.exec(text)?.[0] ?? '') : ''\n if (trail) text = text.slice(0, -trail.length)\n let written = item.marks?.includes('code') ? codeSpan(text) : escapeMarkdown(text)\n if (!item.marks?.includes('code')) written = written.split('\\n').map(escapeLine).join('\\n')\n result += written\n if (trail) {\n // close what ends here before the spaces; the next run closes nothing more\n const stay = stack.findIndex((entry) => !nextKeys.includes(entry.key))\n while (stack.length > stay) result += stack.pop()!.close\n result += trail\n }\n })\n while (stack.length) result += stack.pop()!.close\n return result\n}\n\n/** Put `prefix` before every line, and `rest` (default: as many spaces) before the ones after the first. */\nexport function indentLines(\n text: string,\n prefix: string,\n rest = ' '.repeat(prefix.length),\n): string {\n return text\n .split('\\n')\n .map((line, index) => (index === 0 ? prefix + line : line ? rest + line : rest.trimEnd()))\n .join('\\n')\n}\n\nfunction blocksMarkdown(blocks: Block[], outputs: Outputs): string {\n let result = ''\n let index = 0\n blocks.forEach((block, position) => {\n const output = outputs.blocks[block.type]\n const previous = blocks[position - 1]\n index = previous?.type === block.type ? index + 1 : 1\n const context: MarkdownBlockContext = {\n content: inlineMarkdown(block.content, outputs),\n html: inlineHTML(block.content, outputs),\n text: plainText(block.content),\n children: blocksMarkdown(block.children, outputs),\n index,\n inline: (content) => inlineMarkdown(content, outputs),\n inlineHTML: (content) => inlineHTML(content, outputs),\n }\n const written = output?.markdown\n ? output.markdown(block, context)\n : [context.content, context.children].filter(Boolean).join('\\n\\n')\n if (!written) return\n if (result) {\n const tight =\n previous && output?.group && outputs.blocks[previous.type]?.group === output.group\n result += tight ? '\\n' : '\\n\\n'\n }\n result += written\n })\n return result\n}\n\n/** Write blocks as Markdown (CommonMark with GitHub's extensions). */\nexport function writeMarkdown(blocks: PartialBlock[], kit: ResolvedEditorExtensions): string {\n const markdown = blocksMarkdown(blocks.map(complete), outputsOf(kit))\n return markdown ? `${markdown}\\n` : ''\n}\n"],"mappings":";;;;;AA0EA,IAAM,UAAU,MAAsC,UACpD,OAAO,SAAS,aAAa,KAAK,KAAK,IAAI;AAE7C,SAAS,UAAU,KAAwC;CASzD,MAAM,UAAmB;EAAE,QAAQ,CAAC;EAAG,SAAS,CAAC;EAAG,OAAO,CAAC;EAAG,QARhD,OAAO,OAAO,IAAI,OAAO,KAAK,CAAC,CAC3C,QAAQ,SAAS,KAAK,KAAK,KAAK,CAAC,CACjC,KAAK,SAAS,CAAC,KAAK,KAAK,OAAoB,KAAK,IAAI,CAMM;EAAQ,SAAA,IALnD,IAClB,OAAO,OAAO,IAAI,OAAO,KAAK,CAAC,CAC5B,QAAQ,SAAS,KAAK,KAAK,OAAO,KAAK,CAAC,CACxC,KAAK,SAAS,KAAK,IAAI,CAE2C;CAAQ;CAE/E,KA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,SAAS,QAAQ,QAAQ,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,MAAM;EACnE,IAAI,CAAC,SAAS;EACd,IAAI,QAAQ;GACV,MAAM,QACJ,YAAY,QAAQ,SAAS,QAAQ,OAAO,SAAS,KAAK,EAAE,UAAU,OAAO;GAC/E,UAAU,QAAQ,OAAO;EAC3B;EACA,UAAU;CACZ,CAAC;CACD,OAAO;AACT;;AAGA,SAAgB,cAAc,QAAwB,KAAuC;CAC3F,MAAM,WAAW,eAAe,OAAO,IAAI,QAAQ,GAAG,UAAU,GAAG,CAAC;CACpE,OAAO,WAAW,GAAG,SAAS,MAAM;AACtC"}
|
package/dist/core/prepare.js
CHANGED
|
@@ -31,7 +31,7 @@ function splitContainer(element) {
|
|
|
31
31
|
const nodes = Array.from(element.childNodes);
|
|
32
32
|
while (nodes.length && isBlank(nodes[0])) nodes.shift();
|
|
33
33
|
const first = nodes[0];
|
|
34
|
-
if (first
|
|
34
|
+
if (first?.nodeType === 1 && first.tagName === "P") return {
|
|
35
35
|
content: Array.from(first.childNodes),
|
|
36
36
|
children: nodes.slice(1)
|
|
37
37
|
};
|
|
@@ -68,14 +68,21 @@ var BLOCK_TAGS = /* @__PURE__ */ new Set([
|
|
|
68
68
|
"UL"
|
|
69
69
|
]);
|
|
70
70
|
var isBlank = (node) => node.nodeType === 3 && !node.textContent?.trim();
|
|
71
|
-
var isBlockElement = (node) => node
|
|
71
|
+
var isBlockElement = (node) => node.nodeType === 1 && BLOCK_TAGS.has(node.tagName);
|
|
72
72
|
/** Run every extension's `prepareHTML` over the markup. */
|
|
73
73
|
function prepareElement(root, kit) {
|
|
74
74
|
for (const extension of kit.extensions) extension.prepareHTML?.(root);
|
|
75
75
|
}
|
|
76
|
-
/**
|
|
77
|
-
|
|
78
|
-
|
|
76
|
+
/**
|
|
77
|
+
* Read HTML as blocks, with the block types, inline nodes and marks of `kit`.
|
|
78
|
+
* Uses the global `DOMParser` unless given `domParser`; `name` is the
|
|
79
|
+
* function the error message tells to pass one to.
|
|
80
|
+
*/
|
|
81
|
+
function parseHTML(html, kit, domParser, name = "htmlToBlocks(html, extensions, { domParser })") {
|
|
82
|
+
const parser = domParser ?? (typeof DOMParser === "undefined" ? null : new DOMParser());
|
|
83
|
+
if (!parser) throw new Error(`[@dou-ui/editor] reading HTML needs a DOMParser, and there is none here: pass one from a DOM library such as happy-dom or linkedom, as ${name}`);
|
|
84
|
+
const whole = /^\s*<(!doctype|html)/i.test(html) ? html : `<!doctype html><html><head></head><body>${html}</body></html>`;
|
|
85
|
+
const doc = parser.parseFromString(whole, "text/html");
|
|
79
86
|
prepareElement(doc.body, kit);
|
|
80
87
|
const blocks = docToBlocks(DOMParser$1.fromSchema(kit.schema).parse(doc.body));
|
|
81
88
|
const fill = (list) => list.map((block) => ({
|