@dou-ui/editor 0.1.0-alpha.12 → 0.1.0-alpha.13
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/cursors.js +42 -10
- package/dist/collaboration/cursors.js.map +1 -1
- package/dist/collaboration/index.js +30 -3
- package/dist/collaboration/index.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 +73 -15
- 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/commands.js +125 -13
- package/dist/core/commands.js.map +1 -1
- package/dist/core/extension.js +6 -2
- package/dist/core/extension.js.map +1 -1
- package/dist/core/model.js +8 -2
- package/dist/core/model.js.map +1 -1
- package/dist/core/schema.js.map +1 -1
- package/dist/core/transaction.js +12 -3
- package/dist/core/transaction.js.map +1 -1
- package/dist/document.js +40 -4
- package/dist/document.js.map +1 -1
- package/dist/dom.js +96 -13
- package/dist/dom.js.map +1 -1
- package/dist/editor.vue_vue_type_script_setup_true_lang.js +3 -3
- package/dist/editor.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/editor2.js.map +1 -1
- package/dist/extensions/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/table/plugin.js +33 -1
- package/dist/extensions/table/plugin.js.map +1 -1
- package/dist/extensions/table/table-controls.js.map +1 -1
- package/dist/extensions/table/table-controls.vue_vue_type_script_setup_true_lang.js +1 -1
- package/dist/extensions/table/table-controls.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/extensions/table/view.js +25 -1
- package/dist/extensions/table/view.js.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/locale.js +30 -0
- package/dist/locale.js.map +1 -1
- package/dist/style.css +1 -1
- package/dist/types/collaboration/cursors.d.ts +29 -1
- package/dist/types/collaboration/index.d.ts +17 -2
- package/dist/types/components/slash-choices.vue.d.ts +18 -0
- package/dist/types/core/blocks.d.ts +10 -0
- package/dist/types/core/commands.d.ts +17 -2
- package/dist/types/core/extension.d.ts +53 -2
- package/dist/types/core/model.d.ts +6 -1
- package/dist/types/core/schema.d.ts +1 -1
- package/dist/types/document.d.ts +4 -2
- package/dist/types/dom.d.ts +34 -4
- package/dist/types/editor.vue.d.ts +10 -0
- package/dist/types/extensions/columns/column-picker.vue.d.ts +10 -0
- package/dist/types/extensions/columns/columns-controls.vue.d.ts +3 -0
- package/dist/types/extensions/columns/html.d.ts +10 -0
- package/dist/types/extensions/columns/index.d.ts +9 -0
- package/dist/types/extensions/columns/keys.d.ts +6 -0
- package/dist/types/extensions/columns/plugin.d.ts +28 -0
- package/dist/types/extensions/columns/schema.d.ts +17 -0
- package/dist/types/extensions/columns/select-columns.vue.d.ts +13 -0
- package/dist/types/extensions/editor-kit.d.ts +4 -1
- package/dist/types/extensions/table/view.d.ts +8 -1
- package/dist/types/index.d.ts +12 -2
- package/dist/types/locale.d.ts +17 -0
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction.js","names":[],"sources":["../../src/core/transaction.ts"],"sourcesContent":["import type { Node as PMNode, Schema } from 'prosemirror-model'\nimport {\n NodeSelection,\n Selection,\n TextSelection,\n type EditorState,\n type Transaction,\n} from 'prosemirror-state'\nimport { blockAround, findBlockById, type BlockInfo } from './blocks'\nimport { blockSelectionRange } from './block-selection'\nimport {\n blockFromNode,\n contentAttrs,\n createContentNode,\n createId,\n nodeFromBlock,\n type Block,\n type BlockProps,\n type InlineContent,\n type PartialBlock,\n type PartialTableRow,\n} from './model'\nimport type { ContentType } from './schema'\nimport { closeHistory } from 'prosemirror-history'\nimport type { EditorView } from 'prosemirror-view'\nimport { originKey } from './editor'\n\n/**\n * Where blocks go: right before or after a block, or among a block's\n * children (`parent: null` is the top level). `index` counts from 0 and\n * defaults to the end.\n */\nexport type BlockPlacement =\n { before: string } | { after: string } | { parent: string | null; index?: number }\n\n/** The parts of a block to change. `props` are merged into the current ones. */\nexport interface BlockPatch {\n type?: ContentType\n props?: BlockProps\n /** Inline content, or plain text. */\n content?: InlineContent[] | string\n rows?: PartialTableRow[]\n /** Replaces all children; `[]` removes them. */\n children?: PartialBlock[]\n}\n\nexport interface EditorTransactionMeta {\n /** `false` keeps the change out of undo, e.g. a fix made by the program. */\n history?: boolean\n /** Who made the change; passed on to the `transaction` event. */\n origin?: string\n}\n\n/** Where a selection is put inside a block: at the start of its text or at the end. */\nexport type BlockEdge = 'start' | 'end'\n\n/**\n * Set on a transaction that is an undo step of its own, for history\n * providers other than the built-in one (collaboration reads it).\n */\nexport const ownStepKey = 'douOwnStep'\n\nconst warn = (message: string) => {\n if (process.env.NODE_ENV !== 'production') console.warn(`[@dou-ui/editor] ${message}`)\n}\n\n/**\n * Changes made by blocks and ids, applied together as one undo step. Ids\n * are looked up in the document as it is after the earlier calls.\n */\nexport class EditorTransaction {\n /** The ProseMirror transaction underneath, for anything the methods don't cover. */\n readonly tr: Transaction\n readonly meta: EditorTransactionMeta\n /** `focusBlock` was called: the editor takes focus once the changes are applied. */\n focused = false\n\n constructor(\n /** The state the changes start from. */\n readonly before: EditorState,\n meta: EditorTransactionMeta = {},\n /**\n * Whether the selection was placed by the user or the program. An editor\n * that never had focus has its selection at the start, which is no cursor.\n */\n private readonly hasCursor = true,\n ) {\n this.tr = before.tr\n this.meta = { ...meta }\n }\n\n get changed(): boolean {\n return this.tr.docChanged\n }\n\n setMeta(meta: EditorTransactionMeta): this {\n Object.assign(this.meta, meta)\n return this\n }\n\n /** A block as it is now, or `null`. */\n getBlock(id: string): Block | null {\n const info = findBlockById(this.tr.doc, id)\n return info ? blockFromNode(info.node) : null\n }\n\n /**\n * Insert blocks, by default after the block with the cursor (at the end\n * without one). Returns the new blocks' ids; an id already in the\n * document is replaced with a fresh one.\n */\n insertBlocks(blocks: PartialBlock[], placement?: BlockPlacement): string[] {\n if (!blocks.length) return []\n const tr = this.tr\n const schema = tr.doc.type.schema\n const taken = usedIds(tr.doc)\n const ids: string[] = []\n const nodes = blocks.map((block) => {\n const node = nodeFromBlock(schema, freshIds(block, taken))\n ids.push(node.attrs.id as string)\n return node\n })\n const target = placement ?? this.defaultPlacement()\n if (insertNodes(tr, target, nodes) === null) return []\n return ids\n }\n\n /** Change a block's type, props, content or children. Returns `false` when it isn't found. */\n updateBlock(id: string, patch: BlockPatch): boolean {\n const tr = this.tr\n const info = findBlockById(tr.doc, id)\n if (!info) {\n warn(`updateBlock: no block with the id \"${id}\"`)\n return false\n }\n const schema = tr.doc.type.schema\n // check everything before changing anything: a refused patch changes nothing\n const typeName = patch.type ?? info.content.type.name\n const nodeType = schema.nodes[typeName]\n if (!nodeType?.isInGroup('blockContent')) {\n warn(`updateBlock: unknown block type \"${typeName}\"`)\n return false\n }\n const rowsSpec = !!nodeType.spec.rows\n if (patch.rows !== undefined && !rowsSpec) {\n warn(`updateBlock: a \"${typeName}\" block has no rows`)\n return false\n }\n if (patch.content !== undefined && (rowsSpec || !nodeType.inlineContent)) {\n warn(`updateBlock: a \"${typeName}\" block has no text content`)\n return false\n }\n if (patch.children) replaceChildren(tr, info, patch.children)\n if (\n patch.type === undefined &&\n patch.props === undefined &&\n patch.content === undefined &&\n patch.rows === undefined\n )\n return true\n const current = findBlockById(tr.doc, id)!\n const content = current.content\n const props = { ...content.attrs, ...patch.props }\n const keepsContent = patch.content === undefined && patch.rows === undefined\n // keep the text node for node when it can stay: collaborators typing in it keep their place\n if (keepsContent && nodeType === content.type) {\n tr.setNodeMarkup(current.contentPos, undefined, contentAttrs(nodeType, props))\n return true\n }\n if (keepsContent && nodeType.isTextblock && content.isTextblock) {\n const from = current.contentPos\n tr.setBlockType(\n from + 1,\n from + content.nodeSize - 1,\n nodeType,\n contentAttrs(nodeType, props),\n )\n return true\n }\n const block = blockFromNode(current.node)\n const next = createContentNode(\n schema,\n typeName,\n props,\n patch.content ?? block.content,\n patch.rows ?? block.rows,\n )\n tr.replaceWith(current.contentPos, current.contentPos + content.nodeSize, next)\n return true\n }\n\n /** Remove blocks with their children. The document always keeps one block. */\n removeBlocks(ids: string[]): boolean {\n const infos = outermost(this.tr.doc, ids, 'removeBlocks')\n if (!infos.length) return false\n deleteInfos(this.tr, infos)\n const tr = this.tr\n if (tr.doc.content.size === 0) tr.insert(0, emptyBlock(tr.doc.type.schema))\n return true\n }\n\n /**\n * Move blocks, in the order given, to `placement`. Fails when it is\n * inside one of them.\n */\n moveBlocks(ids: string[], placement: BlockPlacement): boolean {\n const tr = this.tr\n const infos = outermost(tr.doc, ids, 'moveBlocks')\n if (!infos.length) return false\n const anchor =\n 'before' in placement\n ? placement.before\n : 'after' in placement\n ? placement.after\n : placement.parent\n if (\n anchor !== null &&\n infos.some((info) => info.node.attrs.id === anchor || contains(info, tr.doc, anchor))\n ) {\n warn('moveBlocks: blocks cannot be moved next to or into themselves')\n return false\n }\n // insert the moved blocks first, then delete the originals: the document never empties\n const nodes = infos.map((info) => info.node)\n // a selection inside a moved block goes along with it\n const { anchor: anchorPos, head } = tr.selection\n const nodeSelected = tr.selection instanceof NodeSelection\n const carried = infos.findIndex(\n (info) =>\n anchorPos > info.pos &&\n anchorPos < info.pos + info.node.nodeSize &&\n head > info.pos &&\n head < info.pos + info.node.nodeSize,\n )\n const base = tr.steps.length\n const at = insertNodes(tr, placement, nodes)\n if (at === null) return false\n const inserted = tr.steps.length\n deleteInfos(tr, infos, base)\n if (carried >= 0) {\n const info = infos[carried]!\n let start = at\n for (let i = 0; i < carried; i++) start += nodes[i]!.nodeSize\n const moved = tr.mapping.slice(inserted).map(start, 1)\n const shift = (pos: number) => moved + (pos - info.pos)\n tr.setSelection(\n nodeSelected\n ? NodeSelection.create(tr.doc, shift(anchorPos))\n : TextSelection.create(tr.doc, shift(anchorPos), shift(head)),\n )\n }\n return true\n }\n\n /** Put the cursor at the start or end of a block's text (or select a block without text). */\n focusBlock(id: string, edge: BlockEdge = 'end'): boolean {\n const tr = this.tr\n const info = findBlockById(tr.doc, id)\n if (!info) {\n warn(`focusBlock: no block with the id \"${id}\"`)\n return false\n }\n tr.setSelection(selectionIn(tr, info, edge)).scrollIntoView()\n this.focused = true\n return true\n }\n\n /** After the selection's block, or at the end. */\n private defaultPlacement(): BlockPlacement {\n if (!this.hasCursor && !this.tr.selectionSet) return { parent: null }\n // selected blocks are only known before the first change\n const range = this.tr.docChanged ? null : blockSelectionRange(this.before)\n const id = range\n ? (range.parent.child(range.to).attrs.id as string)\n : (blockAround(this.tr.selection.$to)?.node.attrs.id as string | undefined)\n return id ? { after: id } : { parent: null }\n }\n}\n\nfunction emptyBlock(schema: Schema): PMNode {\n return schema.nodes.block!.create({ id: createId() }, schema.nodes.paragraph!.create())\n}\n\nfunction usedIds(doc: PMNode): Set<string> {\n const ids = new Set<string>()\n doc.descendants((node) => {\n if (node.type.name === 'block') ids.add(node.attrs.id as string)\n return node.type.name === 'block' || node.type.name === 'blockGroup'\n })\n return ids\n}\n\n/** The block with ids that are free, recursively. */\nfunction freshIds(block: PartialBlock, taken: Set<string>): PartialBlock {\n let id = block.id\n if (!id || taken.has(id)) id = createId()\n taken.add(id)\n return {\n ...block,\n id,\n children: block.children?.map((child) => freshIds(child, taken)),\n }\n}\n\n/** Whether a block with `id` sits inside `info`. */\nfunction contains(info: BlockInfo, doc: PMNode, id: string): boolean {\n const found = findBlockById(doc, id)\n return !!found && found.pos > info.pos && found.pos < info.pos + info.node.nodeSize\n}\n\n/** The blocks with these ids, without those inside another one of them, in the order given. */\nfunction outermost(doc: PMNode, ids: string[], method: string): BlockInfo[] {\n const infos: BlockInfo[] = []\n const seen = new Set<string>()\n for (const id of ids) {\n if (seen.has(id)) continue\n seen.add(id)\n const info = findBlockById(doc, id)\n if (info) infos.push(info)\n else warn(`${method}: no block with the id \"${id}\"`)\n }\n return infos.filter(\n (info) =>\n !infos.some(\n (other) =>\n other !== info && info.pos > other.pos && info.pos < other.pos + other.node.nodeSize,\n ),\n )\n}\n\n/**\n * Delete blocks found in the document as it was after step `base`; a\n * group left without children goes too.\n */\nfunction deleteInfos(tr: Transaction, infos: BlockInfo[], base = tr.steps.length) {\n // last first, so the earlier positions stay valid\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a copy\n const sorted = [...infos].sort((a, b) => b.pos - a.pos)\n for (const info of sorted) {\n // a block moved right in front of this one pushes it on (`1`)\n const from = tr.mapping.slice(base).map(info.pos, 1)\n const to = from + info.node.nodeSize\n const $from = tr.doc.resolve(from)\n if ($from.parent.type.name === 'blockGroup' && $from.parent.childCount === 1)\n tr.delete($from.before(), $from.after())\n else tr.delete(from, to)\n }\n}\n\n/** Insert block nodes at a placement. Returns `false` when the placement can't be found. */\nfunction insertNodes(tr: Transaction, placement: BlockPlacement, nodes: PMNode[]): number | null {\n const schema = tr.doc.type.schema\n let at: number\n if ('before' in placement || 'after' in placement) {\n const id = 'before' in placement ? placement.before : placement.after\n const info = findBlockById(tr.doc, id)\n if (!info) {\n warn(`no block with the id \"${id}\" to insert next to`)\n return null\n }\n at = 'before' in placement ? info.pos : info.pos + info.node.nodeSize\n } else if (placement.parent === null) {\n at = childPos(0, tr.doc, placement.index)\n } else {\n const info = findBlockById(tr.doc, placement.parent)\n if (!info) {\n warn(`no block with the id \"${placement.parent}\" to insert into`)\n return null\n }\n if (!info.group) {\n at = info.contentPos + info.content.nodeSize\n tr.insert(at, schema.nodes.blockGroup!.create(null, nodes))\n return at + 1\n }\n at = childPos(info.contentPos + info.content.nodeSize + 1, info.group, placement.index)\n }\n tr.insert(at, nodes)\n return at\n}\n\n/** The position before the child at `index` of a container whose content starts at `start`. */\nfunction childPos(start: number, container: PMNode, index = container.childCount) {\n const at = Math.max(0, Math.min(index, container.childCount))\n let pos = start\n for (let i = 0; i < at; i++) pos += container.child(i).nodeSize\n return pos\n}\n\nfunction replaceChildren(tr: Transaction, info: BlockInfo, children: PartialBlock[]) {\n const schema = tr.doc.type.schema\n const groupPos = info.contentPos + info.content.nodeSize\n const taken = usedIds(tr.doc)\n // the old children's ids are free again\n info.group?.descendants((node) => {\n if (node.type.name === 'block') taken.delete(node.attrs.id as string)\n })\n const nodes = children.map((child) => nodeFromBlock(schema, freshIds(child, taken)))\n const group = nodes.length ? schema.nodes.blockGroup!.create(null, nodes) : null\n const end = info.group ? groupPos + info.group.nodeSize : groupPos\n if (group) tr.replaceWith(groupPos, end, group)\n else if (info.group) tr.delete(groupPos, end)\n}\n\n/** A cursor at the start or end of a block's text; a node selection for a block without text. */\nexport function selectionIn(tr: Transaction, info: BlockInfo, edge: BlockEdge): Selection {\n const content = info.content\n const doc = tr.doc\n if (content.isTextblock) {\n const pos = edge === 'start' ? info.contentPos + 1 : info.contentPos + content.nodeSize - 1\n return TextSelection.create(doc, pos)\n }\n if (content.isAtom) return NodeSelection.create(doc, info.contentPos)\n // a table: the first or last cell's text\n const inside = edge === 'start' ? info.contentPos + 1 : info.contentPos + content.nodeSize - 1\n return Selection.near(doc.resolve(inside), edge === 'start' ? 1 : -1)\n}\n\n/**\n * Apply a transaction made with `transact`: one undo step of its own,\n * unless `history` is `false`. Returns whether anything happened.\n */\nexport function applyEditorTransaction(view: EditorView, transaction: EditorTransaction): boolean {\n const { tr, meta } = transaction\n if (!tr.docChanged && !tr.selectionSet) return false\n if (meta.origin !== undefined) tr.setMeta(originKey, meta.origin)\n if (!tr.docChanged) {\n view.dispatch(tr)\n return true\n }\n if (meta.history === false) {\n tr.setMeta('addToHistory', false)\n view.dispatch(tr)\n return true\n }\n view.dispatch(closeHistory(tr).setMeta(ownStepKey, true))\n // and typing right after it starts another step\n view.dispatch(closeHistory(view.state.tr))\n return true\n}\n"],"mappings":";;;;;;;;;;;AA4DA,IAAa,aAAa;AAE1B,IAAM,QAAQ,YAAoB;CAChC,IAAA,QAAA,IAAA,aAA6B,cAAc,QAAQ,KAAK,oBAAoB,SAAS;AACvF;;;;;AAMA,IAAa,oBAAb,MAA+B;CASlB;CAMQ;;CAbnB;CACA;;CAEA,UAAU;CAEV,YAEE,QACA,OAA8B,CAAC,GAK/B,YAA6B,MAC7B;EAPS,KAAA,SAAA;EAMQ,KAAA,YAAA;EA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S,aAAa,EAAE,CAAC,CAAC,QAAQ,YAAY,IAAI,CAAC;CAExD,KAAK,SAAS,aAAa,KAAK,MAAM,EAAE,CAAC;CACzC,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"transaction.js","names":[],"sources":["../../src/core/transaction.ts"],"sourcesContent":["import type { Node as PMNode, Schema } from 'prosemirror-model'\nimport {\n NodeSelection,\n Selection,\n TextSelection,\n type EditorState,\n type Transaction,\n} from 'prosemirror-state'\nimport { blockAround, findBlockById, layoutOf, parentBlock, type BlockInfo } from './blocks'\nimport { blockSelectionRange } from './block-selection'\nimport {\n blockFromNode,\n contentAttrs,\n createContentNode,\n createId,\n nodeFromBlock,\n type Block,\n type BlockProps,\n type InlineContent,\n type PartialBlock,\n type PartialTableRow,\n} from './model'\nimport type { ContentType } from './schema'\nimport { closeHistory } from 'prosemirror-history'\nimport type { EditorView } from 'prosemirror-view'\nimport { originKey } from './editor'\n\n/**\n * Where blocks go: right before or after a block, or among a block's\n * children (`parent: null` is the top level). `index` counts from 0 and\n * defaults to the end.\n */\nexport type BlockPlacement =\n { before: string } | { after: string } | { parent: string | null; index?: number }\n\n/** The parts of a block to change. `props` are merged into the current ones. */\nexport interface BlockPatch {\n type?: ContentType\n props?: BlockProps\n /** Inline content, or plain text. */\n content?: InlineContent[] | string\n rows?: PartialTableRow[]\n /** Replaces all children; `[]` removes them. */\n children?: PartialBlock[]\n}\n\nexport interface EditorTransactionMeta {\n /** `false` keeps the change out of undo, e.g. a fix made by the program. */\n history?: boolean\n /** Who made the change; passed on to the `transaction` event. */\n origin?: string\n}\n\n/** Where a selection is put inside a block: at the start of its text or at the end. */\nexport type BlockEdge = 'start' | 'end'\n\n/**\n * Set on a transaction that is an undo step of its own, for history\n * providers other than the built-in one (collaboration reads it).\n */\nexport const ownStepKey = 'douOwnStep'\n\nconst warn = (message: string) => {\n if (process.env.NODE_ENV !== 'production') console.warn(`[@dou-ui/editor] ${message}`)\n}\n\n/**\n * Changes made by blocks and ids, applied together as one undo step. Ids\n * are looked up in the document as it is after the earlier calls.\n */\nexport class EditorTransaction {\n /** The ProseMirror transaction underneath, for anything the methods don't cover. */\n readonly tr: Transaction\n readonly meta: EditorTransactionMeta\n /** `focusBlock` was called: the editor takes focus once the changes are applied. */\n focused = false\n\n constructor(\n /** The state the changes start from. */\n readonly before: EditorState,\n meta: EditorTransactionMeta = {},\n /**\n * Whether the selection was placed by the user or the program. An editor\n * that never had focus has its selection at the start, which is no cursor.\n */\n private readonly hasCursor = true,\n ) {\n this.tr = before.tr\n this.meta = { ...meta }\n }\n\n get changed(): boolean {\n return this.tr.docChanged\n }\n\n setMeta(meta: EditorTransactionMeta): this {\n Object.assign(this.meta, meta)\n return this\n }\n\n /** A block as it is now, or `null`. */\n getBlock(id: string): Block | null {\n const info = findBlockById(this.tr.doc, id)\n return info ? blockFromNode(info.node) : null\n }\n\n /**\n * Insert blocks, by default after the block with the cursor (at the end\n * without one). Returns the new blocks' ids; an id already in the\n * document is replaced with a fresh one.\n */\n insertBlocks(blocks: PartialBlock[], placement?: BlockPlacement): string[] {\n if (!blocks.length) return []\n const tr = this.tr\n const schema = tr.doc.type.schema\n const taken = usedIds(tr.doc)\n const ids: string[] = []\n const nodes = blocks.map((block) => {\n const node = nodeFromBlock(schema, freshIds(block, taken), true)\n ids.push(node.attrs.id as string)\n return node\n })\n const target = placement ?? this.defaultPlacement()\n if (insertNodes(tr, target, nodes) === null) return []\n for (const id of ids) {\n const info = findBlockById(tr.doc, id)\n if (layoutOf(info?.node) === 'row' && info && inColumn(tr.doc, info))\n warn(\n `insertBlocks: columns don't go in a column; the block \"${id}\" is replaced by its columns' blocks`,\n )\n }\n return ids\n }\n\n /** Change a block's type, props, content or children. Returns `false` when it isn't found. */\n updateBlock(id: string, patch: BlockPatch): boolean {\n const tr = this.tr\n const info = findBlockById(tr.doc, id)\n if (!info) {\n warn(`updateBlock: no block with the id \"${id}\"`)\n return false\n }\n const schema = tr.doc.type.schema\n // check everything before changing anything: a refused patch changes nothing\n const typeName = patch.type ?? info.content.type.name\n const nodeType = schema.nodes[typeName]\n if (!nodeType?.isInGroup('blockContent')) {\n warn(`updateBlock: unknown block type \"${typeName}\"`)\n return false\n }\n const rowsSpec = !!nodeType.spec.rows\n if (patch.rows !== undefined && !rowsSpec) {\n warn(`updateBlock: a \"${typeName}\" block has no rows`)\n return false\n }\n if (patch.content !== undefined && (rowsSpec || !nodeType.inlineContent)) {\n warn(`updateBlock: a \"${typeName}\" block has no text content`)\n return false\n }\n if (patch.children) replaceChildren(tr, info, patch.children)\n if (\n patch.type === undefined &&\n patch.props === undefined &&\n patch.content === undefined &&\n patch.rows === undefined\n )\n return true\n const current = findBlockById(tr.doc, id)!\n const content = current.content\n const props = { ...content.attrs, ...patch.props }\n const keepsContent = patch.content === undefined && patch.rows === undefined\n // keep the text node for node when it can stay: collaborators typing in it keep their place\n if (keepsContent && nodeType === content.type) {\n tr.setNodeMarkup(current.contentPos, undefined, contentAttrs(nodeType, props))\n return true\n }\n if (keepsContent && nodeType.isTextblock && content.isTextblock) {\n const from = current.contentPos\n tr.setBlockType(\n from + 1,\n from + content.nodeSize - 1,\n nodeType,\n contentAttrs(nodeType, props),\n )\n return true\n }\n const block = blockFromNode(current.node)\n const next = createContentNode(\n schema,\n typeName,\n props,\n patch.content ?? block.content,\n patch.rows ?? block.rows,\n )\n tr.replaceWith(current.contentPos, current.contentPos + content.nodeSize, next)\n return true\n }\n\n /** Remove blocks with their children. The document always keeps one block. */\n removeBlocks(ids: string[]): boolean {\n const infos = outermost(this.tr.doc, ids, 'removeBlocks')\n if (!infos.length) return false\n deleteInfos(this.tr, infos)\n const tr = this.tr\n if (tr.doc.content.size === 0) tr.insert(0, emptyBlock(tr.doc.type.schema))\n return true\n }\n\n /**\n * Move blocks, in the order given, to `placement`. Fails when it is\n * inside one of them.\n */\n moveBlocks(ids: string[], placement: BlockPlacement): boolean {\n const tr = this.tr\n const infos = outermost(tr.doc, ids, 'moveBlocks')\n if (!infos.length) return false\n const anchor =\n 'before' in placement\n ? placement.before\n : 'after' in placement\n ? placement.after\n : placement.parent\n if (\n anchor !== null &&\n infos.some((info) => info.node.attrs.id === anchor || contains(info, tr.doc, anchor))\n ) {\n warn('moveBlocks: blocks cannot be moved next to or into themselves')\n return false\n }\n // insert the moved blocks first, then delete the originals: the document never empties\n const nodes = infos.map((info) => info.node)\n // a selection inside a moved block goes along with it\n const { anchor: anchorPos, head } = tr.selection\n const nodeSelected = tr.selection instanceof NodeSelection\n const carried = infos.findIndex(\n (info) =>\n anchorPos > info.pos &&\n anchorPos < info.pos + info.node.nodeSize &&\n head > info.pos &&\n head < info.pos + info.node.nodeSize,\n )\n const base = tr.steps.length\n const at = insertNodes(tr, placement, nodes)\n if (at === null) return false\n const inserted = tr.steps.length\n deleteInfos(tr, infos, base)\n if (carried >= 0) {\n const info = infos[carried]!\n let start = at\n for (let i = 0; i < carried; i++) start += nodes[i]!.nodeSize\n const moved = tr.mapping.slice(inserted).map(start, 1)\n const shift = (pos: number) => moved + (pos - info.pos)\n tr.setSelection(\n nodeSelected\n ? NodeSelection.create(tr.doc, shift(anchorPos))\n : TextSelection.create(tr.doc, shift(anchorPos), shift(head)),\n )\n }\n return true\n }\n\n /** Put the cursor at the start or end of a block's text (or select a block without text). */\n focusBlock(id: string, edge: BlockEdge = 'end'): boolean {\n const tr = this.tr\n const info = findBlockById(tr.doc, id)\n if (!info) {\n warn(`focusBlock: no block with the id \"${id}\"`)\n return false\n }\n tr.setSelection(selectionIn(tr, info, edge)).scrollIntoView()\n this.focused = true\n return true\n }\n\n /** After the selection's block, or at the end. */\n private defaultPlacement(): BlockPlacement {\n if (!this.hasCursor && !this.tr.selectionSet) return { parent: null }\n // selected blocks are only known before the first change\n const range = this.tr.docChanged ? null : blockSelectionRange(this.before)\n const id = range\n ? (range.parent.child(range.to).attrs.id as string)\n : (blockAround(this.tr.selection.$to)?.node.attrs.id as string | undefined)\n return id ? { after: id } : { parent: null }\n }\n}\n\nfunction emptyBlock(schema: Schema): PMNode {\n return schema.nodes.block!.create({ id: createId() }, schema.nodes.paragraph!.create())\n}\n\nfunction usedIds(doc: PMNode): Set<string> {\n const ids = new Set<string>()\n doc.descendants((node) => {\n if (node.type.name === 'block') ids.add(node.attrs.id as string)\n return node.type.name === 'block' || node.type.name === 'blockGroup'\n })\n return ids\n}\n\n/** The block with ids that are free, recursively. */\nfunction freshIds(block: PartialBlock, taken: Set<string>): PartialBlock {\n let id = block.id\n if (!id || taken.has(id)) id = createId()\n taken.add(id)\n return {\n ...block,\n id,\n children: block.children?.map((child) => freshIds(child, taken)),\n }\n}\n\n/** Whether a block with `id` sits inside `info`. */\nfunction contains(info: BlockInfo, doc: PMNode, id: string): boolean {\n const found = findBlockById(doc, id)\n return !!found && found.pos > info.pos && found.pos < info.pos + info.node.nodeSize\n}\n\n/** The blocks with these ids, without those inside another one of them, in the order given. */\nfunction outermost(doc: PMNode, ids: string[], method: string): BlockInfo[] {\n const infos: BlockInfo[] = []\n const seen = new Set<string>()\n for (const id of ids) {\n if (seen.has(id)) continue\n seen.add(id)\n const info = findBlockById(doc, id)\n if (info) infos.push(info)\n else warn(`${method}: no block with the id \"${id}\"`)\n }\n return infos.filter(\n (info) =>\n !infos.some(\n (other) =>\n other !== info && info.pos > other.pos && info.pos < other.pos + other.node.nodeSize,\n ),\n )\n}\n\n/**\n * Delete blocks found in the document as it was after step `base`; a\n * group left without children goes too.\n */\nfunction deleteInfos(tr: Transaction, infos: BlockInfo[], base = tr.steps.length) {\n // last first, so the earlier positions stay valid\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a copy\n const sorted = [...infos].sort((a, b) => b.pos - a.pos)\n for (const info of sorted) {\n // a block moved right in front of this one pushes it on (`1`)\n const from = tr.mapping.slice(base).map(info.pos, 1)\n const to = from + info.node.nodeSize\n const $from = tr.doc.resolve(from)\n if ($from.parent.type.name === 'blockGroup' && $from.parent.childCount === 1)\n tr.delete($from.before(), $from.after())\n else tr.delete(from, to)\n }\n}\n\n/** Insert block nodes at a placement. Returns `false` when the placement can't be found. */\nfunction insertNodes(tr: Transaction, placement: BlockPlacement, nodes: PMNode[]): number | null {\n const schema = tr.doc.type.schema\n let at: number\n if ('before' in placement || 'after' in placement) {\n const id = 'before' in placement ? placement.before : placement.after\n const info = findBlockById(tr.doc, id)\n if (!info) {\n warn(`no block with the id \"${id}\" to insert next to`)\n return null\n }\n at = 'before' in placement ? info.pos : info.pos + info.node.nodeSize\n } else if (placement.parent === null) {\n at = childPos(0, tr.doc, placement.index)\n } else {\n const info = findBlockById(tr.doc, placement.parent)\n if (!info) {\n warn(`no block with the id \"${placement.parent}\" to insert into`)\n return null\n }\n if (!info.group) {\n at = info.contentPos + info.content.nodeSize\n tr.insert(at, schema.nodes.blockGroup!.create(null, nodes))\n return at + 1\n }\n at = childPos(info.contentPos + info.content.nodeSize + 1, info.group, placement.index)\n }\n tr.insert(at, nodes)\n return at\n}\n\n/** The position before the child at `index` of a container whose content starts at `start`. */\nfunction childPos(start: number, container: PMNode, index = container.childCount) {\n const at = Math.max(0, Math.min(index, container.childCount))\n let pos = start\n for (let i = 0; i < at; i++) pos += container.child(i).nodeSize\n return pos\n}\n\n/** Whether a block sits in a column, at any depth. */\nfunction inColumn(doc: PMNode, info: BlockInfo): boolean {\n for (let parent = parentBlock(doc, info); parent; parent = parentBlock(doc, parent))\n if (layoutOf(parent.node) === 'column') return true\n return false\n}\n\nfunction replaceChildren(tr: Transaction, info: BlockInfo, children: PartialBlock[]) {\n const schema = tr.doc.type.schema\n const groupPos = info.contentPos + info.content.nodeSize\n const taken = usedIds(tr.doc)\n // the old children's ids are free again\n info.group?.descendants((node) => {\n if (node.type.name === 'block') taken.delete(node.attrs.id as string)\n })\n const nodes = children.map((child) => nodeFromBlock(schema, freshIds(child, taken), true))\n const group = nodes.length ? schema.nodes.blockGroup!.create(null, nodes) : null\n const end = info.group ? groupPos + info.group.nodeSize : groupPos\n if (group) tr.replaceWith(groupPos, end, group)\n else if (info.group) tr.delete(groupPos, end)\n}\n\n/** A cursor at the start or end of a block's text; a node selection for a block without text. */\nexport function selectionIn(tr: Transaction, info: BlockInfo, edge: BlockEdge): Selection {\n const content = info.content\n const doc = tr.doc\n if (content.isTextblock) {\n const pos = edge === 'start' ? info.contentPos + 1 : info.contentPos + content.nodeSize - 1\n return TextSelection.create(doc, pos)\n }\n if (content.isAtom) return NodeSelection.create(doc, info.contentPos)\n // a table: the first or last cell's text\n const inside = edge === 'start' ? info.contentPos + 1 : info.contentPos + content.nodeSize - 1\n return Selection.near(doc.resolve(inside), edge === 'start' ? 1 : -1)\n}\n\n/**\n * Apply a transaction made with `transact`: one undo step of its own,\n * unless `history` is `false`. Returns whether anything happened.\n */\nexport function applyEditorTransaction(view: EditorView, transaction: EditorTransaction): boolean {\n const { tr, meta } = transaction\n if (!tr.docChanged && !tr.selectionSet) return false\n if (meta.origin !== undefined) tr.setMeta(originKey, meta.origin)\n if (!tr.docChanged) {\n view.dispatch(tr)\n return true\n }\n if (meta.history === false) {\n tr.setMeta('addToHistory', false)\n view.dispatch(tr)\n return true\n }\n view.dispatch(closeHistory(tr).setMeta(ownStepKey, true))\n // and typing right after it starts another step\n view.dispatch(closeHistory(view.state.tr))\n return true\n}\n"],"mappings":";;;;;;;;;;;AA4DA,IAAa,aAAa;AAE1B,IAAM,QAAQ,YAAoB;CAChC,IAAA,QAAA,IAAA,aAA6B,cAAc,QAAQ,KAAK,oBAAoB,SAAS;AACvF;;;;;AAMA,IAAa,oBAAb,MAA+B;CASlB;CAMQ;;CAbnB;CACA;;CAEA,UAAU;CAEV,YAEE,QACA,OAA8B,CAAC,GAK/B,YAA6B,MAC7B;EAPS,KAAA,SAAA;EAMQ,KAAA,YAAA;EAEjB,KAAK,KAAK,OAAO;EACjB,KAAK,OAAO,EAAE,GAAG,KAAK;CACxB;CAEA,IAAI,UAAmB;EACrB,OAAO,KAAK,GAAG;CACjB;CAEA,QAAQ,MAAmC;EACzC,OAAO,OAAO,KAAK,MAAM,IAAI;EAC7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K,MAAM;CAChE,IAAI,CAAC,GAAG,YAAY;EAClB,KAAK,SAAS,EAAE;EAChB,OAAO;CACT;CACA,IAAI,KAAK,YAAY,OAAO;EAC1B,GAAG,QAAQ,gBAAgB,KAAK;EAChC,KAAK,SAAS,EAAE;EAChB,OAAO;CACT;CACA,KAAK,SAAS,aAAa,EAAE,CAAC,CAAC,QAAQ,YAAY,IAAI,CAAC;CAExD,KAAK,SAAS,aAAa,KAAK,MAAM,EAAE,CAAC;CACzC,OAAO;AACT"}
|
package/dist/document.js
CHANGED
|
@@ -29,7 +29,9 @@ function shapeProblems(value, lists) {
|
|
|
29
29
|
* The problems of an editor document, before it is saved or shown: an
|
|
30
30
|
* unknown version, blocks or table rows sharing an id, and block types,
|
|
31
31
|
* marks and inline nodes the extensions don't define, which the editor
|
|
32
|
-
* would show as a paragraph or leave out
|
|
32
|
+
* would show as a paragraph or leave out, and columns the editor would
|
|
33
|
+
* change on the next edit (a column outside a set of columns, a set with
|
|
34
|
+
* fewer than two, columns in a column…).
|
|
33
35
|
*/
|
|
34
36
|
function checkDocument(document, options = {}) {
|
|
35
37
|
const shape = shapeProblems(document, ["blocks"]);
|
|
@@ -43,14 +45,48 @@ function checkDocument(document, options = {}) {
|
|
|
43
45
|
});
|
|
44
46
|
const { schema } = kitOf(options.extensions ?? (defaultKit ??= [editorKit()]));
|
|
45
47
|
const ids = /* @__PURE__ */ new Set();
|
|
46
|
-
const walk = (blocks, at) => blocks.forEach((block, i) => {
|
|
48
|
+
const walk = (blocks, at, around) => blocks.forEach((block, i) => {
|
|
47
49
|
const path = `${at}[${i}]`;
|
|
48
50
|
checkBlock(block, path, schema, ids, problems);
|
|
49
|
-
|
|
51
|
+
const layout = layoutOfType(schema, block.type);
|
|
52
|
+
checkLayout(block, layout, path, around, schema, problems);
|
|
53
|
+
if (block.children) walk(block.children, `${path}.children`, {
|
|
54
|
+
layout,
|
|
55
|
+
inColumn: around.inColumn || layout === "column"
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
walk(document.blocks, "blocks", {
|
|
59
|
+
layout: void 0,
|
|
60
|
+
inColumn: false
|
|
50
61
|
});
|
|
51
|
-
walk(document.blocks, "blocks");
|
|
52
62
|
return problems;
|
|
53
63
|
}
|
|
64
|
+
var layoutOfType = (schema, type) => schema.nodes[type ?? "paragraph"]?.spec.layout;
|
|
65
|
+
/** Columns as the editor keeps them; anything else it changes on the next edit. */
|
|
66
|
+
function checkLayout(block, layout, path, around, schema, problems) {
|
|
67
|
+
const type = block.type ?? "paragraph";
|
|
68
|
+
const report = (message, at = path) => problems.push({
|
|
69
|
+
code: "invalid-columns",
|
|
70
|
+
blockId: block.id,
|
|
71
|
+
path: at,
|
|
72
|
+
text: type,
|
|
73
|
+
message
|
|
74
|
+
});
|
|
75
|
+
const children = block.children ?? [];
|
|
76
|
+
if (around.layout === "row" && layout !== "column") report(`A "${type}" block directly in a set of columns would move into the column before it`);
|
|
77
|
+
if (layout === "column") {
|
|
78
|
+
if (around.layout !== "row") report("A column outside a set of columns would be replaced by its blocks");
|
|
79
|
+
if (!children.length) report("An empty column would be removed");
|
|
80
|
+
const width = block.props?.width;
|
|
81
|
+
if (width != null && !(typeof width === "number" && width > 0)) report(`The column width ${JSON.stringify(width)} is not a positive number; it would be ignored`, `${path}.props.width`);
|
|
82
|
+
}
|
|
83
|
+
if (layout === "row") {
|
|
84
|
+
if (around.inColumn) report("Columns inside a column would be replaced by their blocks");
|
|
85
|
+
const columns = children.filter((child) => layoutOfType(schema, child.type) === "column");
|
|
86
|
+
if (columns.length < 2) report(`A set of ${columns.length} column(s) would be replaced by its blocks`);
|
|
87
|
+
}
|
|
88
|
+
if (layout && Array.isArray(block.content) && block.content.length) report(`A "${type}" block has no text of its own; its content would be left out`, `${path}.content`);
|
|
89
|
+
}
|
|
54
90
|
function checkBlock(block, path, schema, ids, problems) {
|
|
55
91
|
const blockId = block.id;
|
|
56
92
|
if (blockId !== void 0) {
|
package/dist/document.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"document.js","names":[],"sources":["../src/document.ts"],"sourcesContent":["import type { Schema } from 'prosemirror-model'\nimport { kitOf, type EditorExtensionList } from './core/convert'\nimport type { Block, EditorDocument, PartialBlock, PartialTableRow } from './core/model'\nimport { editorKit } from './extensions/editor-kit'\n\n/** A document with no blocks, to start from when nothing is saved yet. */\nexport const emptyDocument = (): EditorDocument<Block> => ({ version: 1, blocks: [] })\n\nexport interface DocumentProblem {\n code: 'version' | 'shape' | 'duplicate-id' | 'unknown-type' | 'unknown-mark' | 'unknown-inline'\n /** The block at fault, when it has an id. */\n blockId?: string\n /**\n * Where the problem is, as a path into the document, e.g.\n * `blocks[0].children[2]` or `blocks[1].content[0]`; `version` for the version.\n */\n path: string\n /** The id, type, mark or inline node at fault, for the editor's message. */\n text: string\n /** An English description, for logs. */\n message: string\n}\n\nexport interface CheckDocumentOptions {\n /** The editor's `extensions`, for the blocks, marks and inline nodes they add; `[editorKit()]` by default, as in the editor. */\n extensions?: EditorExtensionList\n}\n\nlet defaultKit: EditorExtensionList | undefined\n\n/**\n * What is wrong with the shape itself: the document is not an object, or a\n * list in it is not an array. Nothing else can be checked until it is fixed.\n */\nfunction shapeProblems(value: unknown, lists: string[]): DocumentProblem[] {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n return [{ code: 'shape', path: '', text: '', message: 'The document is not an object' }]\n return lists\n .filter((key) => !Array.isArray((value as Record<string, unknown>)[key]))\n .map((key) => ({ code: 'shape', path: key, text: '', message: `\"${key}\" is not a list` }))\n}\n\n/**\n * The problems of an editor document, before it is saved or shown: an\n * unknown version, blocks or table rows sharing an id, and block types,\n * marks and inline nodes the extensions don't define, which the editor\n * would show as a paragraph or leave out.\n */\nexport function checkDocument(\n document: EditorDocument<PartialBlock>,\n options: CheckDocumentOptions = {},\n): DocumentProblem[] {\n const shape = shapeProblems(document, ['blocks'])\n if (shape.length) return shape\n const problems: DocumentProblem[] = []\n if (document.version !== 1)\n problems.push({\n code: 'version',\n path: 'version',\n text: String(document.version),\n message: `Version ${String(document.version)} is not known`,\n })\n const { schema } = kitOf(options.extensions ?? (defaultKit ??= [editorKit()]))\n const ids = new Set<string>()\n const walk = (blocks: readonly PartialBlock[], at: string) =>\n blocks.forEach((block, i) => {\n const path = `${at}[${i}]`\n checkBlock(block, path, schema, ids, problems)\n if (block.children) walk(block.children, `${path}.children`)\n })\n walk(document.blocks, 'blocks')\n return problems\n}\n\nfunction checkBlock(\n block: PartialBlock,\n path: string,\n schema: Schema,\n ids: Set<string>,\n problems: DocumentProblem[],\n) {\n const blockId = block.id\n if (blockId !== undefined) {\n if (ids.has(blockId))\n problems.push({\n code: 'duplicate-id',\n blockId,\n path,\n text: blockId,\n message: `The block id \"${blockId}\" is used more than once`,\n })\n ids.add(blockId)\n }\n const type = block.type ?? 'paragraph'\n if (!schema.nodes[type]?.isInGroup('blockContent'))\n problems.push({\n code: 'unknown-type',\n blockId,\n path,\n text: type,\n message: `No block type \"${type}\" is defined; it would show as a paragraph`,\n })\n if (Array.isArray(block.content))\n block.content.forEach((item, i) => {\n const at = `${path}.content[${i}]`\n if (item.type === 'inline' && !schema.nodes[item.name]?.isInline)\n problems.push({\n code: 'unknown-inline',\n blockId,\n path: at,\n text: item.name,\n message: `No inline node \"${item.name}\" is defined; it would be left out`,\n })\n if (item.type === 'text')\n for (const mark of item.marks ?? [])\n if (!schema.marks[mark])\n problems.push({\n code: 'unknown-mark',\n blockId,\n path: at,\n text: mark,\n message: `No mark \"${mark}\" is defined; it would be left out`,\n })\n })\n if (block.rows) checkRows(block.rows, `${path}.rows`, blockId, problems)\n}\n\nfunction checkRows(\n rows: readonly PartialTableRow[],\n path: string,\n blockId: string | undefined,\n problems: DocumentProblem[],\n) {\n const ids = new Set<string>()\n rows.forEach((row, i) => {\n if (row.id === undefined) return\n if (ids.has(row.id))\n problems.push({\n code: 'duplicate-id',\n blockId,\n path: `${path}[${i}]`,\n text: row.id,\n message: `The row id \"${row.id}\" is used more than once in a table`,\n })\n ids.add(row.id)\n })\n}\n\nconst objects = <T>(value: unknown) =>\n (Array.isArray(value) ? value : []).filter(\n (item): item is T => !!item && typeof item === 'object',\n )\n\n/** The saved data as an object of version 1, or an error saying why it can't be. */\nfunction sourceOf(input: unknown): Record<string, unknown> {\n if (!input || typeof input !== 'object' || Array.isArray(input))\n throw new Error(\n `[@dou-ui/editor] an editor document must be an object, not ${Array.isArray(input) ? 'an array' : (JSON.stringify(input) ?? String(input))}`,\n )\n const source = input as Record<string, unknown>\n const version = source.version ?? 1\n if (version !== 1)\n throw new Error(\n `[@dou-ui/editor] unknown document version ${JSON.stringify(version) ?? String(version)} (expected 1); data saved by a newer @dou-ui/editor needs that version to open`,\n )\n return source\n}\n\n/**\n * Brings a saved document up to the current version, and fills what an\n * older or hand-written one may lack (`version`, `blocks`). Blocks that are\n * not objects are dropped; anything else is kept as it is, for the editor\n * to read as it reads partial blocks. Throws for data that is not an object (an array,\n * `null`, a string) and for a version it does not know.\n */\nexport function migrateDocument(input: unknown): EditorDocument<PartialBlock> {\n const source = sourceOf(input)\n return { ...source, version: 1, blocks: objects<PartialBlock>(source.blocks) }\n}\n\nconst warned = new Set<string>()\n\n/**\n * The blocks of the `v-model`, as the editor reads them. A document of the\n * wrong shape (not an object, a bare list of blocks, without `blocks` or a\n * known `version`) gets a warning in development and is read as well as it\n * can be: a list as the blocks, anything else missing as no blocks. What\n * the editor writes back always carries `version: 1`. `undefined`, no\n * `v-model` bound, is fine.\n */\nexport function readBlocks(value: unknown): PartialBlock[] | undefined {\n if (value === undefined) return undefined\n const plain = !!value && typeof value === 'object' && !Array.isArray(value)\n const source = (plain ? value : {}) as Partial<EditorDocument<PartialBlock>>\n const blocks = Array.isArray(source.blocks)\n const problem = Array.isArray(value)\n ? 'is a list of blocks'\n : !plain\n ? `is ${JSON.stringify(value) ?? String(value)}`\n : !blocks\n ? 'has no blocks array'\n : source.version === undefined\n ? 'has no version'\n : source.version !== 1\n ? `has version ${JSON.stringify(source.version)}`\n : ''\n if (problem && process.env.NODE_ENV !== 'production' && !warned.has(problem)) {\n warned.add(problem)\n console.warn(\n `[@dou-ui/editor] the v-model ${problem}; expected { version: 1, blocks: [...] }. It is read as well as it can be and the version as 1; read saved data with migrateDocument().`,\n )\n }\n if (Array.isArray(value)) return value as PartialBlock[]\n return blocks ? source.blocks : []\n}\n"],"mappings":";;;;AAMA,IAAa,uBAA8C;CAAE,SAAS;CAAG,QAAQ,CAAC;AAAE;AAsBpF,IAAI;;;;;AAMJ,SAAS,cAAc,OAAgB,OAAoC;CACzE,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D,OAAO,CAAC;EAAE,MAAM;EAAS,MAAM;EAAI,MAAM;EAAI,SAAS;CAAgC,CAAC;CACzF,OAAO,MACJ,QAAQ,QAAQ,CAAC,MAAM,QAAS,MAAkC,IAAI,CAAC,CAAC,CACxE,KAAK,SAAS;EAAE,MAAM;EAAS,MAAM;EAAK,MAAM;EAAI,SAAS,IAAI,IAAI;CAAiB,EAAE;AAC7F;;;;;;;AAQA,SAAgB,cACd,UACA,UAAgC,CAAC,GACd;CACnB,MAAM,QAAQ,cAAc,UAAU,CAAC,QAAQ,CAAC;CAChD,IAAI,MAAM,QAAQ,OAAO;CACzB,MAAM,WAA8B,CAAC;CACrC,IAAI,SAAS,YAAY,GACvB,SAAS,KAAK;EACZ,MAAM;EACN,MAAM;EACN,MAAM,OAAO,SAAS,OAAO;EAC7B,SAAS,WAAW,OAAO,SAAS,OAAO,EAAE;CAC/C,CAAC;CACH,MAAM,EAAE,WAAW,MAAM,QAAQ,eAAe,eAAe,CAAC,UAAU,CAAC,EAAE;CAC7E,MAAM,sBAAM,IAAI,IAAY;CAC5B,MAAM,QAAQ,QAAiC,OAC7C,OAAO,SAAS,OAAO,MAAM;EAC3B,MAAM,OAAO,GAAG,GAAG,GAAG,EAAE;EACxB,WAAW,OAAO,MAAM,QAAQ,KAAK,QAAQ;EAC7C,IAAI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CAAC,SACC,wBACA,OAAO,YAAY,KAAA,IACjB,mBACA,OAAO,YAAY,IACjB,eAAe,KAAK,UAAU,OAAO,OAAO,MAC5C;CACZ,IAAI,WAAA,QAAA,IAAA,aAAoC,gBAAgB,CAAC,OAAO,IAAI,OAAO,GAAG;EAC5E,OAAO,IAAI,OAAO;EAClB,QAAQ,KACN,gCAAgC,QAAQ,wIAC1C;CACF;CACA,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO;CACjC,OAAO,SAAS,OAAO,SAAS,CAAC;AACnC"}
|
|
1
|
+
{"version":3,"file":"document.js","names":[],"sources":["../src/document.ts"],"sourcesContent":["import type { Schema } from 'prosemirror-model'\nimport { kitOf, type EditorExtensionList } from './core/convert'\nimport type { Block, EditorDocument, PartialBlock, PartialTableRow } from './core/model'\nimport { editorKit } from './extensions/editor-kit'\n\n/** A document with no blocks, to start from when nothing is saved yet. */\nexport const emptyDocument = (): EditorDocument<Block> => ({ version: 1, blocks: [] })\n\nexport interface DocumentProblem {\n code:\n | 'version'\n | 'shape'\n | 'duplicate-id'\n | 'unknown-type'\n | 'unknown-mark'\n | 'unknown-inline'\n | 'invalid-columns'\n /** The block at fault, when it has an id. */\n blockId?: string\n /**\n * Where the problem is, as a path into the document, e.g.\n * `blocks[0].children[2]` or `blocks[1].content[0]`; `version` for the version.\n */\n path: string\n /** The id, type, mark or inline node at fault, for the editor's message. */\n text: string\n /** An English description, for logs. */\n message: string\n}\n\nexport interface CheckDocumentOptions {\n /** The editor's `extensions`, for the blocks, marks and inline nodes they add; `[editorKit()]` by default, as in the editor. */\n extensions?: EditorExtensionList\n}\n\nlet defaultKit: EditorExtensionList | undefined\n\n/**\n * What is wrong with the shape itself: the document is not an object, or a\n * list in it is not an array. Nothing else can be checked until it is fixed.\n */\nfunction shapeProblems(value: unknown, lists: string[]): DocumentProblem[] {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n return [{ code: 'shape', path: '', text: '', message: 'The document is not an object' }]\n return lists\n .filter((key) => !Array.isArray((value as Record<string, unknown>)[key]))\n .map((key) => ({ code: 'shape', path: key, text: '', message: `\"${key}\" is not a list` }))\n}\n\n/**\n * The problems of an editor document, before it is saved or shown: an\n * unknown version, blocks or table rows sharing an id, and block types,\n * marks and inline nodes the extensions don't define, which the editor\n * would show as a paragraph or leave out, and columns the editor would\n * change on the next edit (a column outside a set of columns, a set with\n * fewer than two, columns in a column…).\n */\nexport function checkDocument(\n document: EditorDocument<PartialBlock>,\n options: CheckDocumentOptions = {},\n): DocumentProblem[] {\n const shape = shapeProblems(document, ['blocks'])\n if (shape.length) return shape\n const problems: DocumentProblem[] = []\n if (document.version !== 1)\n problems.push({\n code: 'version',\n path: 'version',\n text: String(document.version),\n message: `Version ${String(document.version)} is not known`,\n })\n const { schema } = kitOf(options.extensions ?? (defaultKit ??= [editorKit()]))\n const ids = new Set<string>()\n const walk = (blocks: readonly PartialBlock[], at: string, around: Around) =>\n blocks.forEach((block, i) => {\n const path = `${at}[${i}]`\n checkBlock(block, path, schema, ids, problems)\n const layout = layoutOfType(schema, block.type)\n checkLayout(block, layout, path, around, schema, problems)\n if (block.children)\n walk(block.children, `${path}.children`, {\n layout,\n inColumn: around.inColumn || layout === 'column',\n })\n })\n walk(document.blocks, 'blocks', { layout: undefined, inColumn: false })\n return problems\n}\n\n/** What a block sits in: the layout of its parent, and whether that is inside a column. */\ninterface Around {\n layout: string | undefined\n inColumn: boolean\n}\n\nconst layoutOfType = (schema: Schema, type: string | undefined) =>\n schema.nodes[type ?? 'paragraph']?.spec.layout as string | undefined\n\n/** Columns as the editor keeps them; anything else it changes on the next edit. */\nfunction checkLayout(\n block: PartialBlock,\n layout: string | undefined,\n path: string,\n around: Around,\n schema: Schema,\n problems: DocumentProblem[],\n) {\n const type = block.type ?? 'paragraph'\n const report = (message: string, at = path) =>\n problems.push({ code: 'invalid-columns', blockId: block.id, path: at, text: type, message })\n const children = block.children ?? []\n if (around.layout === 'row' && layout !== 'column')\n report(`A \"${type}\" block directly in a set of columns would move into the column before it`)\n if (layout === 'column') {\n if (around.layout !== 'row')\n report('A column outside a set of columns would be replaced by its blocks')\n if (!children.length) report('An empty column would be removed')\n const width = block.props?.width\n if (width != null && !(typeof width === 'number' && width > 0))\n report(\n `The column width ${JSON.stringify(width)} is not a positive number; it would be ignored`,\n `${path}.props.width`,\n )\n }\n if (layout === 'row') {\n if (around.inColumn) report('Columns inside a column would be replaced by their blocks')\n const columns = children.filter((child) => layoutOfType(schema, child.type) === 'column')\n if (columns.length < 2)\n report(`A set of ${columns.length} column(s) would be replaced by its blocks`)\n }\n if (layout && Array.isArray(block.content) && block.content.length)\n report(\n `A \"${type}\" block has no text of its own; its content would be left out`,\n `${path}.content`,\n )\n}\n\nfunction checkBlock(\n block: PartialBlock,\n path: string,\n schema: Schema,\n ids: Set<string>,\n problems: DocumentProblem[],\n) {\n const blockId = block.id\n if (blockId !== undefined) {\n if (ids.has(blockId))\n problems.push({\n code: 'duplicate-id',\n blockId,\n path,\n text: blockId,\n message: `The block id \"${blockId}\" is used more than once`,\n })\n ids.add(blockId)\n }\n const type = block.type ?? 'paragraph'\n if (!schema.nodes[type]?.isInGroup('blockContent'))\n problems.push({\n code: 'unknown-type',\n blockId,\n path,\n text: type,\n message: `No block type \"${type}\" is defined; it would show as a paragraph`,\n })\n if (Array.isArray(block.content))\n block.content.forEach((item, i) => {\n const at = `${path}.content[${i}]`\n if (item.type === 'inline' && !schema.nodes[item.name]?.isInline)\n problems.push({\n code: 'unknown-inline',\n blockId,\n path: at,\n text: item.name,\n message: `No inline node \"${item.name}\" is defined; it would be left out`,\n })\n if (item.type === 'text')\n for (const mark of item.marks ?? [])\n if (!schema.marks[mark])\n problems.push({\n code: 'unknown-mark',\n blockId,\n path: at,\n text: mark,\n message: `No mark \"${mark}\" is defined; it would be left out`,\n })\n })\n if (block.rows) checkRows(block.rows, `${path}.rows`, blockId, problems)\n}\n\nfunction checkRows(\n rows: readonly PartialTableRow[],\n path: string,\n blockId: string | undefined,\n problems: DocumentProblem[],\n) {\n const ids = new Set<string>()\n rows.forEach((row, i) => {\n if (row.id === undefined) return\n if (ids.has(row.id))\n problems.push({\n code: 'duplicate-id',\n blockId,\n path: `${path}[${i}]`,\n text: row.id,\n message: `The row id \"${row.id}\" is used more than once in a table`,\n })\n ids.add(row.id)\n })\n}\n\nconst objects = <T>(value: unknown) =>\n (Array.isArray(value) ? value : []).filter(\n (item): item is T => !!item && typeof item === 'object',\n )\n\n/** The saved data as an object of version 1, or an error saying why it can't be. */\nfunction sourceOf(input: unknown): Record<string, unknown> {\n if (!input || typeof input !== 'object' || Array.isArray(input))\n throw new Error(\n `[@dou-ui/editor] an editor document must be an object, not ${Array.isArray(input) ? 'an array' : (JSON.stringify(input) ?? String(input))}`,\n )\n const source = input as Record<string, unknown>\n const version = source.version ?? 1\n if (version !== 1)\n throw new Error(\n `[@dou-ui/editor] unknown document version ${JSON.stringify(version) ?? String(version)} (expected 1); data saved by a newer @dou-ui/editor needs that version to open`,\n )\n return source\n}\n\n/**\n * Brings a saved document up to the current version, and fills what an\n * older or hand-written one may lack (`version`, `blocks`). Blocks that are\n * not objects are dropped; anything else is kept as it is, for the editor\n * to read as it reads partial blocks. Throws for data that is not an object (an array,\n * `null`, a string) and for a version it does not know.\n */\nexport function migrateDocument(input: unknown): EditorDocument<PartialBlock> {\n const source = sourceOf(input)\n return { ...source, version: 1, blocks: objects<PartialBlock>(source.blocks) }\n}\n\nconst warned = new Set<string>()\n\n/**\n * The blocks of the `v-model`, as the editor reads them. A document of the\n * wrong shape (not an object, a bare list of blocks, without `blocks` or a\n * known `version`) gets a warning in development and is read as well as it\n * can be: a list as the blocks, anything else missing as no blocks. What\n * the editor writes back always carries `version: 1`. `undefined`, no\n * `v-model` bound, is fine.\n */\nexport function readBlocks(value: unknown): PartialBlock[] | undefined {\n if (value === undefined) return undefined\n const plain = !!value && typeof value === 'object' && !Array.isArray(value)\n const source = (plain ? value : {}) as Partial<EditorDocument<PartialBlock>>\n const blocks = Array.isArray(source.blocks)\n const problem = Array.isArray(value)\n ? 'is a list of blocks'\n : !plain\n ? `is ${JSON.stringify(value) ?? String(value)}`\n : !blocks\n ? 'has no blocks array'\n : source.version === undefined\n ? 'has no version'\n : source.version !== 1\n ? `has version ${JSON.stringify(source.version)}`\n : ''\n if (problem && process.env.NODE_ENV !== 'production' && !warned.has(problem)) {\n warned.add(problem)\n console.warn(\n `[@dou-ui/editor] the v-model ${problem}; expected { version: 1, blocks: [...] }. It is read as well as it can be and the version as 1; read saved data with migrateDocument().`,\n )\n }\n if (Array.isArray(value)) return value as PartialBlock[]\n return blocks ? source.blocks : []\n}\n"],"mappings":";;;;AAMA,IAAa,uBAA8C;CAAE,SAAS;CAAG,QAAQ,CAAC;AAAE;AA6BpF,IAAI;;;;;AAMJ,SAAS,cAAc,OAAgB,OAAoC;CACzE,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D,OAAO,CAAC;EAAE,MAAM;EAAS,MAAM;EAAI,MAAM;EAAI,SAAS;CAAgC,CAAC;CACzF,OAAO,MACJ,QAAQ,QAAQ,CAAC,MAAM,QAAS,MAAkC,IAAI,CAAC,CAAC,CACxE,KAAK,SAAS;EAAE,MAAM;EAAS,MAAM;EAAK,MAAM;EAAI,SAAS,IAAI,IAAI;CAAiB,EAAE;AAC7F;;;;;;;;;AAUA,SAAgB,cACd,UACA,UAAgC,CAAC,GACd;CACnB,MAAM,QAAQ,cAAc,UAAU,CAAC,QAAQ,CAAC;CAChD,IAAI,MAAM,QAAQ,OAAO;CACzB,MAAM,WAA8B,CAAC;CACrC,IAAI,SAAS,YAAY,GACvB,SAAS,KAAK;EACZ,MAAM;EACN,MAAM;EACN,MAAM,OAAO,SAAS,OAAO;EAC7B,SAAS,WAAW,OAAO,SAAS,OAAO,EAAE;CAC/C,CAAC;CACH,MAAM,EAAE,WAAW,MAAM,QAAQ,eAAe,eAAe,CAAC,UAAU,CAAC,EAAE;CAC7E,MAAM,sBAAM,IAA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1C,MAAM,UAAU,MAAM,QAAQ,KAAK,IAC/B,wBACA,CAAC,QACC,MAAM,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK,MAC3C,CAAC,SACC,wBACA,OAAO,YAAY,KAAA,IACjB,mBACA,OAAO,YAAY,IACjB,eAAe,KAAK,UAAU,OAAO,OAAO,MAC5C;CACZ,IAAI,WAAA,QAAA,IAAA,aAAoC,gBAAgB,CAAC,OAAO,IAAI,OAAO,GAAG;EAC5E,OAAO,IAAI,OAAO;EAClB,QAAQ,KACN,gCAAgC,QAAQ,wIAC1C;CACF;CACA,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO;CACjC,OAAO,SAAS,OAAO,SAAS,CAAC;AACnC"}
|
package/dist/dom.js
CHANGED
|
@@ -1,23 +1,76 @@
|
|
|
1
1
|
// src/dom.ts
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
*/
|
|
8
|
-
function
|
|
9
|
-
const
|
|
2
|
+
var isBlock = (element) => element.classList.contains("dou-editor__block");
|
|
3
|
+
/** The blocks right inside a container element: the editing area or a group. */
|
|
4
|
+
var childBlocks = (container) => Array.from(container.children).filter(isBlock);
|
|
5
|
+
var contentOf = (block) => block.querySelector(":scope > .dou-editor__content");
|
|
6
|
+
var groupOf = (block) => block.querySelector(":scope > .dou-editor__group");
|
|
7
|
+
/** Where a block starts: its content's top, or its children's for a block without visible content (columns). */
|
|
8
|
+
function topOf(block) {
|
|
9
|
+
const content = contentOf(block);
|
|
10
|
+
return (content?.getClientRects().length ? content : groupOf(block) ?? block).getBoundingClientRect().top;
|
|
11
|
+
}
|
|
12
|
+
/** The last of `blocks` whose top is above `y` (the first when none is). */
|
|
13
|
+
function lastAbove(blocks, y) {
|
|
10
14
|
let low = 0;
|
|
11
|
-
let high =
|
|
12
|
-
let found =
|
|
15
|
+
let high = blocks.length - 1;
|
|
16
|
+
let found = 0;
|
|
13
17
|
while (low <= high) {
|
|
14
18
|
const middle = low + high >> 1;
|
|
15
|
-
if (
|
|
19
|
+
if (topOf(blocks[middle]) <= y) {
|
|
16
20
|
found = middle;
|
|
17
21
|
low = middle + 1;
|
|
18
22
|
} else high = middle - 1;
|
|
19
23
|
}
|
|
20
|
-
return
|
|
24
|
+
return blocks[found];
|
|
25
|
+
}
|
|
26
|
+
/** The group of a set of columns, around an element in one of them. */
|
|
27
|
+
var COLUMNS_GROUP = ".dou-editor__content--columns + .dou-editor__group";
|
|
28
|
+
/** The group of one column (its blocks). */
|
|
29
|
+
var COLUMN_GROUP = ".dou-editor__content--column + .dou-editor__group";
|
|
30
|
+
/** Whether columns sit side by side; a narrow editor stacks them. */
|
|
31
|
+
function sideBySide(columns) {
|
|
32
|
+
return columns.length > 1 && Math.abs(columns[0].getBoundingClientRect().top - columns[1].getBoundingClientRect().top) < 1;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The column at `x` among side-by-side ones: the gap before a column
|
|
36
|
+
* belongs to it (its handle sits there), what is left of the first to the
|
|
37
|
+
* first and right of the last to the last.
|
|
38
|
+
*/
|
|
39
|
+
function columnAtX(columns, x) {
|
|
40
|
+
let index = 0;
|
|
41
|
+
for (let next = 1; next < columns.length; next++) if (x >= columns[next - 1].getBoundingClientRect().right) index = next;
|
|
42
|
+
return index;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The content element (paragraph, heading, …) at height `y` in viewport
|
|
46
|
+
* coordinates: the last one whose top is above it, nested ones included.
|
|
47
|
+
* Blocks follow each other from top to bottom, so a binary search finds
|
|
48
|
+
* the block, then the same again among its children. In a set of
|
|
49
|
+
* columns, `x` picks the column (stacked columns go by `y` too).
|
|
50
|
+
*/
|
|
51
|
+
function contentAt(view, y, x) {
|
|
52
|
+
let container = view.dom;
|
|
53
|
+
for (;;) {
|
|
54
|
+
const blocks = childBlocks(container);
|
|
55
|
+
if (!blocks.length) return null;
|
|
56
|
+
const block = lastAbove(blocks, y);
|
|
57
|
+
const content = contentOf(block);
|
|
58
|
+
const group = groupOf(block);
|
|
59
|
+
if (group && content?.classList.contains("dou-editor__content--columns")) {
|
|
60
|
+
const columns = childBlocks(group);
|
|
61
|
+
if (!columns.length) return null;
|
|
62
|
+
const inner = groupOf(x !== void 0 && sideBySide(columns) ? columns[columnAtX(columns, x)] : lastAbove(columns, y));
|
|
63
|
+
if (!inner) return null;
|
|
64
|
+
container = inner;
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
const first = group?.getClientRects().length ? childBlocks(group)[0] : void 0;
|
|
68
|
+
if (group && first && topOf(first) <= y) {
|
|
69
|
+
container = group;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
return content;
|
|
73
|
+
}
|
|
21
74
|
}
|
|
22
75
|
/** The block element around a content element. */
|
|
23
76
|
function blockElementOf(content) {
|
|
@@ -43,11 +96,41 @@ function firstLine(content) {
|
|
|
43
96
|
height
|
|
44
97
|
};
|
|
45
98
|
}
|
|
99
|
+
/** A top-level table: only it reaches into the margins (a table in a column or a list doesn't). */
|
|
100
|
+
var isWideTable = (content) => content.classList.contains("dou-editor__content--table") && !!content.parentElement?.parentElement?.classList.contains("dou-editor__surface");
|
|
101
|
+
/**
|
|
102
|
+
* Where a block's content goes across: its box, less what a top-level
|
|
103
|
+
* table's frame reaches into the margins (its start padding and end margin),
|
|
104
|
+
* which keeps the table in line with the text. The editor lays out left to
|
|
105
|
+
* right, so the logical start and end are the left and right.
|
|
106
|
+
*/
|
|
107
|
+
function contentSpan(content) {
|
|
108
|
+
const rect = content.getBoundingClientRect();
|
|
109
|
+
if (!isWideTable(content)) return {
|
|
110
|
+
left: rect.left,
|
|
111
|
+
right: rect.right
|
|
112
|
+
};
|
|
113
|
+
const style = getComputedStyle(content);
|
|
114
|
+
return {
|
|
115
|
+
left: rect.left + (Number.parseFloat(style.paddingInlineStart) || 0),
|
|
116
|
+
right: rect.right + (Number.parseFloat(style.marginInlineEnd) || 0)
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Where the block handle goes: before the content, or before what shows of
|
|
121
|
+
* a table, whose left edge moves out into the margin as it scrolls.
|
|
122
|
+
*/
|
|
123
|
+
function handleLeft(content) {
|
|
124
|
+
const rect = content.getBoundingClientRect();
|
|
125
|
+
if (!isWideTable(content)) return rect.left;
|
|
126
|
+
const table = content.querySelector("table");
|
|
127
|
+
return table ? Math.max(rect.left, table.getBoundingClientRect().left) : contentSpan(content).left;
|
|
128
|
+
}
|
|
46
129
|
/** The right edge of the editor's text column: the surface less its padding (a reading width). */
|
|
47
130
|
function columnRight(surface) {
|
|
48
131
|
const padding = Number.parseFloat(getComputedStyle(surface).paddingRight) || 0;
|
|
49
132
|
return surface.getBoundingClientRect().right - padding;
|
|
50
133
|
}
|
|
51
|
-
export { blockElementOf, columnRight, contentAt, firstLine, scrollParent };
|
|
134
|
+
export { COLUMNS_GROUP, COLUMN_GROUP, blockElementOf, childBlocks, columnAtX, columnRight, contentAt, contentSpan, firstLine, handleLeft, scrollParent, sideBySide };
|
|
52
135
|
|
|
53
136
|
//# sourceMappingURL=dom.js.map
|
package/dist/dom.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dom.js","names":[],"sources":["../src/dom.ts"],"sourcesContent":["import type { EditorView } from 'prosemirror-view'\n\
|
|
1
|
+
{"version":3,"file":"dom.js","names":[],"sources":["../src/dom.ts"],"sourcesContent":["import type { EditorView } from 'prosemirror-view'\n\nconst isBlock = (element: Element): element is HTMLElement =>\n element.classList.contains('dou-editor__block')\n\n/** The blocks right inside a container element: the editing area or a group. */\nexport const childBlocks = (container: Element): HTMLElement[] =>\n Array.from(container.children).filter(isBlock)\n\nconst contentOf = (block: HTMLElement) =>\n block.querySelector<HTMLElement>(':scope > .dou-editor__content')\n\nconst groupOf = (block: HTMLElement) =>\n block.querySelector<HTMLElement>(':scope > .dou-editor__group')\n\n/** Where a block starts: its content's top, or its children's for a block without visible content (columns). */\nfunction topOf(block: HTMLElement): number {\n const content = contentOf(block)\n const shown = content?.getClientRects().length ? content : (groupOf(block) ?? block)\n return shown.getBoundingClientRect().top\n}\n\n/** The last of `blocks` whose top is above `y` (the first when none is). */\nfunction lastAbove(blocks: HTMLElement[], y: number): HTMLElement {\n let low = 0\n let high = blocks.length - 1\n let found = 0\n while (low <= high) {\n const middle = (low + high) >> 1\n if (topOf(blocks[middle]!) <= y) {\n found = middle\n low = middle + 1\n } else high = middle - 1\n }\n return blocks[found]!\n}\n\n/** The group of a set of columns, around an element in one of them. */\nexport const COLUMNS_GROUP = '.dou-editor__content--columns + .dou-editor__group'\n/** The group of one column (its blocks). */\nexport const COLUMN_GROUP = '.dou-editor__content--column + .dou-editor__group'\n\n/** Whether columns sit side by side; a narrow editor stacks them. */\nexport function sideBySide(columns: HTMLElement[]): boolean {\n return (\n columns.length > 1 &&\n Math.abs(columns[0]!.getBoundingClientRect().top - columns[1]!.getBoundingClientRect().top) < 1\n )\n}\n\n/**\n * The column at `x` among side-by-side ones: the gap before a column\n * belongs to it (its handle sits there), what is left of the first to the\n * first and right of the last to the last.\n */\nexport function columnAtX(columns: HTMLElement[], x: number): number {\n let index = 0\n for (let next = 1; next < columns.length; next++)\n if (x >= columns[next - 1]!.getBoundingClientRect().right) index = next\n return index\n}\n\n/**\n * The content element (paragraph, heading, …) at height `y` in viewport\n * coordinates: the last one whose top is above it, nested ones included.\n * Blocks follow each other from top to bottom, so a binary search finds\n * the block, then the same again among its children. In a set of\n * columns, `x` picks the column (stacked columns go by `y` too).\n */\nexport function contentAt(view: EditorView, y: number, x?: number): HTMLElement | null {\n let container: Element = view.dom\n for (;;) {\n const blocks = childBlocks(container)\n if (!blocks.length) return null\n const block = lastAbove(blocks, y)\n const content = contentOf(block)\n const group = groupOf(block)\n if (group && content?.classList.contains('dou-editor__content--columns')) {\n const columns = childBlocks(group)\n if (!columns.length) return null\n const column =\n x !== undefined && sideBySide(columns)\n ? columns[columnAtX(columns, x)]!\n : lastAbove(columns, y)\n const inner = groupOf(column)\n if (!inner) return null\n container = inner\n continue\n }\n // the children, when shown (a closed toggle hides them) and `y` reaches them\n const first = group?.getClientRects().length ? childBlocks(group)[0] : undefined\n if (group && first && topOf(first) <= y) {\n container = group\n continue\n }\n return content\n }\n}\n\n/** The block element around a content element. */\nexport function blockElementOf(content: HTMLElement): HTMLElement | null {\n return content.closest<HTMLElement>('.dou-editor__block')\n}\n\n/** The nearest ancestor that scrolls vertically, or `null` for the page. */\nexport function scrollParent(element: HTMLElement): HTMLElement | null {\n for (let node = element.parentElement; node; node = node.parentElement) {\n const { overflowY } = getComputedStyle(node)\n if ((overflowY === 'auto' || overflowY === 'scroll') && node.scrollHeight > node.clientHeight)\n return node\n }\n return null\n}\n\n/** Where the first line of a content element sits: its top and height. */\nexport function firstLine(content: HTMLElement): { top: number; height: number } {\n const rect = content.getBoundingClientRect()\n const style = getComputedStyle(content)\n const lineHeight = Number.parseFloat(style.lineHeight)\n const padding = Number.parseFloat(style.paddingTop) || 0\n const height = Number.isFinite(lineHeight) ? Math.min(lineHeight, rect.height) : rect.height\n return { top: rect.top + (height < rect.height ? padding : 0), height }\n}\n\n/** A top-level table: only it reaches into the margins (a table in a column or a list doesn't). */\nconst isWideTable = (content: HTMLElement) =>\n content.classList.contains('dou-editor__content--table') &&\n !!content.parentElement?.parentElement?.classList.contains('dou-editor__surface')\n\n/**\n * Where a block's content goes across: its box, less what a top-level\n * table's frame reaches into the margins (its start padding and end margin),\n * which keeps the table in line with the text. The editor lays out left to\n * right, so the logical start and end are the left and right.\n */\nexport function contentSpan(content: HTMLElement): { left: number; right: number } {\n const rect = content.getBoundingClientRect()\n if (!isWideTable(content)) return { left: rect.left, right: rect.right }\n const style = getComputedStyle(content)\n return {\n left: rect.left + (Number.parseFloat(style.paddingInlineStart) || 0),\n right: rect.right + (Number.parseFloat(style.marginInlineEnd) || 0),\n }\n}\n\n/**\n * Where the block handle goes: before the content, or before what shows of\n * a table, whose left edge moves out into the margin as it scrolls.\n */\nexport function handleLeft(content: HTMLElement): number {\n const rect = content.getBoundingClientRect()\n if (!isWideTable(content)) return rect.left\n const table = content.querySelector('table')\n return table ? Math.max(rect.left, table.getBoundingClientRect().left) : contentSpan(content).left\n}\n\n/** The right edge of the editor's text column: the surface less its padding (a reading width). */\nexport function columnRight(surface: HTMLElement): number {\n const padding = Number.parseFloat(getComputedStyle(surface).paddingRight) || 0\n return surface.getBoundingClientRect().right - padding\n}\n"],"mappings":";AAEA,IAAM,WAAW,YACf,QAAQ,UAAU,SAAS,mBAAmB;;AAGhD,IAAa,eAAe,cAC1B,MAAM,KAAK,UAAU,QAAQ,CAAC,CAAC,OAAO,OAAO;AAE/C,IAAM,aAAa,UACjB,MAAM,cAA2B,+BAA+B;AAElE,IAAM,WAAW,UACf,MAAM,cAA2B,6BAA6B;;AAGhE,SAAS,MAAM,OAA4B;CACzC,MAAM,UAAU,UAAU,KAAK;CAE/B,QADc,SAAS,eAAe,CAAC,CAAC,SAAS,UAAW,QAAQ,KAAK,KAAK,MAAA,CACjE,sBAAsB,CAAC,CAAC;AACvC;;AAGA,SAAS,UAAU,QAAuB,GAAwB;CAChE,IAAI,MAAM;CACV,IAAI,OAAO,OAAO,SAAS;CAC3B,IAAI,QAAQ;CACZ,OAAO,OAAO,MAAM;EAClB,MAAM,SAAU,MAAM,QAAS;EAC/B,IAAI,MAAM,OAAO,OAAQ,KAAK,GAAG;GAC/B,QAAQ;GACR,MAAM,SAAS;EACjB,OAAO,OAAO,SAAS;CACzB;CACA,OAAO,OAAO;AAChB;;AAGA,IAAa,gBAAgB;;AAE7B,IAAa,eAAe;;AAG5B,SAAgB,WAAW,SAAiC;CAC1D,OACE,QAAQ,SAAS,KACjB,KAAK,IAAI,QAAQ,EAAE,CAAE,sBAAsB,CAAC,CAAC,MAAM,QAAQ,EAAE,CAAE,sBAAsB,CAAC,CAAC,GAAG,IAAI;AAElG;;;;;;AAOA,SAAgB,UAAU,SAAwB,GAAmB;CACnE,IAAI,QA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js";
|
|
2
3
|
import { resolveEditorExtensions } from "./core/extension.js";
|
|
3
4
|
import { selectBlocks } from "./core/block-selection.js";
|
|
@@ -22,7 +23,6 @@ import { writeHTML } from "./core/output.js";
|
|
|
22
23
|
import { componentMounter, vueNodeView } from "./define-block.js";
|
|
23
24
|
import { editorKit } from "./extensions/editor-kit.js";
|
|
24
25
|
import { readBlocks } from "./document.js";
|
|
25
|
-
import { useEditorMessages } from "./locale.js";
|
|
26
26
|
import { useEditorComments } from "./use-comments.js";
|
|
27
27
|
import { isApplePlatform, useGlobalConfig, useNamespace } from "dou-ui";
|
|
28
28
|
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createVNode, defineComponent, getCurrentInstance, h, nextTick, normalizeClass, onBeforeUnmount, onMounted, openBlock, provide, ref, renderList, resolveDynamicComponent, shallowRef, toDisplayString, toRaw, unref, useId, useTemplateRef, watch } from "vue";
|
|
@@ -89,13 +89,13 @@ var editor_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defineCom
|
|
|
89
89
|
setup(__props, { expose: __expose, emit: __emit }) {
|
|
90
90
|
const props = __props;
|
|
91
91
|
const emit = __emit;
|
|
92
|
-
const
|
|
92
|
+
const messages = useEditorMessages(() => props.messages);
|
|
93
|
+
const kit = resolveEditorExtensions(props.extensions ?? [editorKit()], () => messages.value);
|
|
93
94
|
const stopWatchingExtensions = watch(() => props.extensions, () => {
|
|
94
95
|
console.warn("[@dou-ui/editor] `extensions` changed after mount and is ignored: it is read once. Create the list once outside the template, or give the editor a new `key` to rebuild it.");
|
|
95
96
|
stopWatchingExtensions();
|
|
96
97
|
});
|
|
97
98
|
const ns = useNamespace("editor");
|
|
98
|
-
const messages = useEditorMessages(() => props.messages);
|
|
99
99
|
const config = useGlobalConfig();
|
|
100
100
|
const root = useTemplateRef("root");
|
|
101
101
|
const mount = useTemplateRef("mount");
|