@dou-ui/editor 0.1.0-alpha.14 → 0.1.0-alpha.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/collaboration/binding.js +32 -10
- package/dist/collaboration/binding.js.map +1 -1
- package/dist/collaboration/index.js +3 -0
- package/dist/collaboration/index.js.map +1 -1
- package/dist/collaboration/merged-props.js +152 -0
- package/dist/collaboration/merged-props.js.map +1 -0
- package/dist/components/block-handle.js.map +1 -1
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js +55 -5
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/core/extension.js.map +1 -1
- package/dist/core/model.js +2 -1
- package/dist/core/model.js.map +1 -1
- package/dist/core/transaction.js +7 -1
- package/dist/core/transaction.js.map +1 -1
- package/dist/define-block.js +2 -1
- package/dist/define-block.js.map +1 -1
- package/dist/document.js +20 -1
- package/dist/document.js.map +1 -1
- package/dist/dom.js +12 -1
- package/dist/dom.js.map +1 -1
- package/dist/editor.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/editor2.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 +598 -0
- package/dist/flow/board-block.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/flow/board.js +102 -0
- package/dist/flow/board.js.map +1 -0
- package/dist/flow/index.js +170 -0
- package/dist/flow/index.js.map +1 -0
- package/dist/locale.js +48 -6
- package/dist/locale.js.map +1 -1
- package/dist/style.css +1 -1
- package/dist/style.js +2 -0
- package/dist/types/collaboration/binding.d.ts +4 -0
- package/dist/types/collaboration/merged-props.d.ts +20 -0
- package/dist/types/core/extension.d.ts +5 -2
- package/dist/types/core/transaction.d.ts +6 -0
- package/dist/types/document.d.ts +3 -2
- package/dist/types/dom.d.ts +7 -0
- package/dist/types/editor.vue.d.ts +14 -0
- package/dist/types/flow/board-block.vue.d.ts +16 -0
- package/dist/types/flow/board.d.ts +40 -0
- package/dist/types/flow/index.d.ts +59 -0
- package/dist/types/index.d.ts +14 -0
- package/dist/types/locale.d.ts +17 -0
- package/package.json +14 -5
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\n/**\n * The block node for `block`. With `fill`, a block that starts with\n * children of its own (`template` in its spec, e.g. columns) and is given\n * none gets them, as when it is picked from the slash menu.\n */\nexport function nodeFromBlock(schema: Schema, block: PartialBlock, fill = false): PMNode {\n const content = createContentNode(\n schema,\n block.type ?? 'paragraph',\n block.props,\n block.content,\n block.rows,\n )\n const template = fill\n ? (content.type.spec.template as ((props: BlockProps) => PartialBlock[]) | undefined)\n : undefined\n const given = block.children?.length ? block.children : template?.(block.props ?? {})\n const children = (given ?? []).map((child) => nodeFromBlock(schema, child, fill))\n const parts = children.length\n ? [content, schema.nodes.blockGroup!.create(null, children)]\n : [content]\n return schema.nodes.block!.create({ id: block.id ?? createId() }, parts)\n}\n\nexport function blocksToDoc(schema: Schema, blocks: PartialBlock[]): PMNode {\n const list = blocks.length ? blocks : [{ type: 'paragraph' as const }]\n return schema.nodes.doc!.create(\n null,\n list.map((block) => nodeFromBlock(schema, block)),\n )\n}\n\nconst warned = new Set<string>()\n\n/** A development warning, once per message. */\nexport function warnOnce(message: string) {\n if (process.env.NODE_ENV === 'production' || warned.has(message)) return\n warned.add(message)\n console.warn(`[@dou-ui/editor] ${message}`)\n}\n"],"mappings":";;;AAuJA,IAAM,aAAuB;CAAC;CAAQ;CAAU;CAAa;CAAU;AAAM;;AAG7E,IAAM,YAAY,SAAiB;CACjC,MAAM,QAAQ,WAAW,QAAQ,IAAI;CACrC,OAA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,OAAO,OAAO,SAAS,SAAS,CAAC,EAAE,MAAM,YAAqB,CAAC;CACrE,OAAO,OAAO,MAAM,IAAK,OACvB,MACA,KAAK,KAAK,UAAU,cAAc,QAAQ,KAAK,CAAC,CAClD;AACF;AAEA,IAAM,yBAAS,IAAI,IAAY;;AAG/B,SAAgB,SAAS,SAAiB;CACxC,IAAA,QAAA,IAAA,aAA6B,gBAAgB,OAAO,IAAI,OAAO,GAAG;CAClE,OAAO,IAAI,OAAO;CAClB,QAAQ,KAAK,oBAAoB,SAAS;AAC5C"}
|
|
1
|
+
{"version":3,"file":"model.js","names":[],"sources":["../../src/core/model.ts"],"sourcesContent":["import { Mark, type NodeType, type Node as PMNode, type Schema } from 'prosemirror-model'\nimport { toRaw } from 'vue'\nimport { isColor, type TextColor } from './colors'\nimport type { ContentType, MarkType } from './schema'\n\n/** A run of text with its formatting. */\nexport interface TextContent {\n type: 'text'\n text: string\n /** Formatting, in a fixed order: bold, italic, underline, strike, code. */\n marks?: MarkType[]\n /** The link target, when the text is a link. */\n link?: string\n /** The text color, by palette name (e.g. `red`), with the `colors` extension. */\n color?: TextColor\n /** The background color, by palette name (e.g. `yellow`), with the `colors` extension. */\n highlight?: TextColor\n /** The ids of the comment threads about this text. */\n comments?: string[]\n}\n\n/**\n * For the `colors` extension's marks (internal): a mark that carries one\n * color is stored on the text run under this name, e.g.\n * `{ text, color: 'red' }`, and keeps it in its `value` attribute.\n */\nexport type MarkField = 'color' | 'highlight'\n\n/** A line break inside a block (`Shift+Enter`). */\nexport interface BreakContent {\n type: 'break'\n}\n\n/** An inline node an extension adds, e.g. a mention. */\nexport interface InlineNodeContent {\n type: 'inline'\n /** The node's name, e.g. `mention`. */\n name: string\n props: Record<string, unknown>\n}\n\nexport type InlineContent = TextContent | BreakContent | InlineNodeContent\n\n/** A block's attributes: those of the built-in types, and any an extension declares. */\nexport interface BlockProps {\n /** Heading level, `1` to `3`. */\n level?: number\n /** Whether a to-do item is done. */\n checked?: boolean\n /** The language of a code block. */\n language?: string\n /** The tone of a callout: `info`, `tip`, `warning` or `danger`. */\n tone?: string\n /** How a paragraph, heading or quote lines up; left out when it follows the reading direction. */\n align?: 'left' | 'center' | 'right'\n [name: string]: unknown\n}\n\n/** A table cell: formatted text, and how far it reaches when merged. */\nexport interface TableCell {\n content: InlineContent[]\n /** Columns the cell spans, when more than one. */\n colspan?: number\n /** Rows the cell spans, when more than one. */\n rowspan?: number\n}\n\n/** A table row: one cell for every column, including those a merged cell covers. */\nexport interface TableRow {\n /** Stable across edits, like a block's id. */\n id: string\n cells: TableCell[]\n}\n\nexport interface PartialTableCell {\n content?: InlineContent[] | string\n colspan?: number\n rowspan?: number\n}\n\nexport interface PartialTableRow {\n id?: string\n cells: (PartialTableCell | string)[]\n}\n\n/** One block of the document, as `v-model` reads and writes it. */\nexport interface Block {\n /** Stable across edits; a random UUID unless you provide your own. */\n id: string\n type: ContentType\n props: BlockProps\n content: InlineContent[]\n /** The rows of a table; other blocks have none. */\n rows?: TableRow[]\n children: Block[]\n}\n\n/**\n * The document the editor edits, bound with `v-model`: plain JSON to store\n * and send as it is. The editor writes full blocks; it reads partial ones.\n */\nexport interface EditorDocument<B extends PartialBlock = Block> {\n /** The version of the format; see `migrateDocument`. */\n version: 1\n blocks: B[]\n}\n\n/** A block to insert: everything but the type is optional. */\nexport interface PartialBlock {\n id?: string\n type?: ContentType\n props?: BlockProps\n /** Inline content, or plain text. */\n content?: InlineContent[] | string\n rows?: PartialTableRow[]\n children?: PartialBlock[]\n}\n\n/**\n * A content node spec field for blocks whose content is rows rather than\n * text (a table): how to read them into a block and build them back.\n */\nexport interface RowsSpec {\n read: (node: PMNode) => { props: BlockProps; rows: TableRow[] }\n write: (type: NodeType, props: BlockProps, rows: PartialTableRow[]) => PMNode\n /** The node as a grid of ids and cell nodes, for collaboration. */\n grid: (node: PMNode) => TableGrid\n}\n\n/** A table node laid out by ids. */\nexport interface TableGrid {\n /** The props other than `columns`. */\n props: BlockProps\n /** Each column's id and its other fields (width, alignment). */\n columns: { id: string; width?: number; align?: string }[]\n /** Row ids, top to bottom. */\n rows: string[]\n /** The cells that are shown, merged ones by their top-left place. */\n cells: GridCell[]\n}\n\nexport interface GridCell {\n row: number\n col: number\n rowspan: number\n colspan: number\n /** The cell node; its content is inline. */\n node: PMNode\n /** Where the cell starts, counted from the start of the table's content. */\n offset: number\n}\n\nconst MARK_ORDER: string[] = ['bold', 'italic', 'underline', 'strike', 'code']\n\n/** Built-in marks in a fixed order, then the others by name. */\nconst markRank = (name: string) => {\n const index = MARK_ORDER.indexOf(name)\n return index < 0 ? MARK_ORDER.length : index\n}\n\n/** A random id; UUIDs keep blocks created at the same time on two devices apart. */\nexport function createId(): string {\n const crypto = globalThis.crypto\n if (crypto?.randomUUID) return crypto.randomUUID()\n // a v4 UUID from `getRandomValues`, or `Math.random` as a last resort\n const bytes = new Uint8Array(16)\n if (crypto?.getRandomValues) crypto.getRandomValues(bytes)\n else for (let i = 0; i < 16; i++) bytes[i] = Math.floor(Math.random() * 256)\n bytes[6] = (bytes[6]! & 0x0f) | 0x40\n bytes[8] = (bytes[8]! & 0x3f) | 0x80\n const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n}\n\n/* document → blocks */\n\nexport function inlineOf(node: PMNode): InlineContent[] {\n const result: InlineContent[] = []\n node.forEach((child) => {\n if (child.type.name === 'hardBreak') {\n result.push({ type: 'break' })\n return\n }\n if (!child.isText) {\n result.push({ type: 'inline', name: child.type.name, props: { ...child.attrs } })\n return\n }\n const marks = child.marks\n .filter((mark) => !mark.type.spec.field)\n .map((mark) => mark.type.name)\n .filter((name): name is MarkType => name !== 'link' && name !== 'comment')\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts the filtered copy\n .sort((a, b) => markRank(a) - markRank(b) || a.localeCompare(b))\n const link = child.marks.find((mark) => mark.type.name === 'link')?.attrs.href as\n string | undefined\n const item: TextContent = { type: 'text', text: child.text ?? '' }\n if (marks.length) item.marks = marks\n if (link) item.link = link\n for (const mark of child.marks) {\n const field = mark.type.spec.field as MarkField | undefined\n if (field) item[field] = mark.attrs.value as TextColor\n }\n const comments = child.marks\n .filter((mark) => mark.type.name === 'comment')\n .map((mark) => mark.attrs.id as string)\n if (comments.length) item.comments = comments\n // merge with the previous run when the formatting is the same\n const previous = result.at(-1)\n if (\n previous?.type === 'text' &&\n previous.link === item.link &&\n previous.color === item.color &&\n previous.highlight === item.highlight &&\n String(previous.marks ?? '') === String(item.marks ?? '') &&\n String(previous.comments ?? '') === String(item.comments ?? '')\n )\n previous.text += item.text\n else result.push(item)\n })\n return result\n}\n\n/** A content node's attributes; those its spec lists as `optionalProps` only when set. */\nfunction propsOf(content: PMNode): BlockProps {\n const props: BlockProps = { ...content.attrs }\n for (const name of (content.type.spec.optionalProps as string[] | undefined) ?? [])\n if (props[name] === null || props[name] === undefined) delete props[name]\n return props\n}\n\n/**\n * Blocks already read, by node. Nodes never change, so a block that wasn't\n * edited is the same object as last time: reading a large document after\n * typing one key only builds the blocks on the path to that key.\n */\nconst blockCache = new WeakMap<PMNode, Block>()\n\nconst freeze = <T>(value: T): T => {\n if (value && typeof value === 'object' && !Object.isFrozen(value)) {\n Object.freeze(value)\n for (const item of Object.values(value)) freeze(item)\n }\n return value\n}\n\n/** A block of the document; shared between reads, so frozen. */\nexport function blockFromNode(node: PMNode): Block {\n let block = blockCache.get(node)\n if (!block) {\n block = readBlock(node)\n // a change to a shared block throws, instead of corrupting later reads\n freeze(block)\n blockCache.set(node, block)\n }\n return block\n}\n\nfunction readBlock(node: PMNode): Block {\n const content = node.firstChild!\n const group = node.childCount > 1 ? node.child(1) : null\n const children: Block[] = []\n group?.forEach((child) => children.push(blockFromNode(child)))\n const rows = content.type.spec.rows as RowsSpec | undefined\n if (rows) {\n const read = rows.read(content)\n return {\n id: node.attrs.id as string,\n type: content.type.name as ContentType,\n props: read.props,\n content: [],\n rows: read.rows,\n children,\n }\n }\n return {\n id: node.attrs.id as string,\n type: content.type.name as ContentType,\n props: propsOf(content),\n content: content.type.spec.code ? codeText(content) : inlineOf(content),\n children,\n }\n}\n\nfunction codeText(node: PMNode): InlineContent[] {\n return node.textContent ? [{ type: 'text', text: node.textContent }] : []\n}\n\nexport function docToBlocks(doc: PMNode): Block[] {\n const blocks: Block[] = []\n doc.forEach((node) => blocks.push(blockFromNode(node)))\n return blocks\n}\n\n/* blocks → document */\n\nfunction marksFor(schema: Schema, item: TextContent): Mark[] {\n const marks: Mark[] = []\n for (const name of item.marks ?? []) {\n const type = schema.marks[name]\n if (type) marks.push(type.create())\n }\n if (item.link && schema.marks.link) marks.push(schema.marks.link.create({ href: item.link }))\n for (const type of Object.values(schema.marks)) {\n const field = type.spec.field as MarkField | undefined\n const value = field && item[field]\n if (!value) continue\n // a color outside the palette is dropped\n if (!isColor(value)) warnOnce(`\"${value}\" is not a palette color; dropped`)\n else marks.push(type.create({ value }))\n }\n for (const id of item.comments ?? []) marks.push(schema.marks.comment!.create({ id }))\n return Mark.setFrom(marks) as Mark[]\n}\n\nexport function inlineNodes(\n schema: Schema,\n content: PartialBlock['content'],\n code: boolean,\n): PMNode[] {\n if (content === undefined) return []\n const items: InlineContent[] =\n typeof content === 'string' ? [{ type: 'text', text: content }] : content\n const nodes: PMNode[] = []\n for (const item of items) {\n if (item.type === 'break') {\n nodes.push(code ? schema.text('\\n') : schema.nodes.hardBreak!.create())\n } else if (item.type === 'inline') {\n // an inline node whose extension is missing is left out\n const type = schema.nodes[item.name]\n if (type?.isInline && !code) nodes.push(type.create(item.props))\n } else if (item.text) {\n nodes.push(schema.text(item.text, code ? [] : marksFor(schema, item)))\n }\n }\n return nodes\n}\n\n/**\n * The attributes a content type declares, taken from `props` where given.\n * A spec's `normalizeProps` can clamp them, e.g. a heading's level.\n */\nexport function contentAttrs(type: NodeType, props: BlockProps = {}) {\n const attrs: Record<string, unknown> = {}\n for (const name of Object.keys(type.spec.attrs ?? {})) {\n // a prop from a reactive document (an object one, e.g. a board) as its plain value:\n // blocks are frozen, and a frozen proxy breaks every read\n if (props[name] !== undefined) attrs[name] = toRaw(props[name])\n }\n const normalize = type.spec.normalizeProps as\n ((attrs: Record<string, unknown>) => Record<string, unknown>) | undefined\n return normalize ? normalize(attrs) : attrs\n}\n\nexport function createContentNode(\n schema: Schema,\n type: ContentType,\n props?: BlockProps,\n content?: PartialBlock['content'],\n rows?: PartialTableRow[],\n): PMNode {\n const nodeType = schema.nodes[type]?.isInGroup('blockContent')\n ? schema.nodes[type]!\n : schema.nodes.paragraph!\n const rowsSpec = nodeType.spec.rows as RowsSpec | undefined\n if (rowsSpec) return rowsSpec.write(nodeType, props ?? {}, rows ?? [])\n const attrs = contentAttrs(nodeType, props)\n if (nodeType.isAtom || !nodeType.inlineContent) return nodeType.create(attrs)\n return nodeType.create(attrs, inlineNodes(schema, content, !!nodeType.spec.code))\n}\n\n/**\n * The block node for `block`. With `fill`, a block that starts with\n * children of its own (`template` in its spec, e.g. columns) and is given\n * none gets them, as when it is picked from the slash menu.\n */\nexport function nodeFromBlock(schema: Schema, block: PartialBlock, fill = false): PMNode {\n const content = createContentNode(\n schema,\n block.type ?? 'paragraph',\n block.props,\n block.content,\n block.rows,\n )\n const template = fill\n ? (content.type.spec.template as ((props: BlockProps) => PartialBlock[]) | undefined)\n : undefined\n const given = block.children?.length ? block.children : template?.(block.props ?? {})\n const children = (given ?? []).map((child) => nodeFromBlock(schema, child, fill))\n const parts = children.length\n ? [content, schema.nodes.blockGroup!.create(null, children)]\n : [content]\n return schema.nodes.block!.create({ id: block.id ?? createId() }, parts)\n}\n\nexport function blocksToDoc(schema: Schema, blocks: PartialBlock[]): PMNode {\n const list = blocks.length ? blocks : [{ type: 'paragraph' as const }]\n return schema.nodes.doc!.create(\n null,\n list.map((block) => nodeFromBlock(schema, block)),\n )\n}\n\nconst warned = new Set<string>()\n\n/** A development warning, once per message. */\nexport function warnOnce(message: string) {\n if (process.env.NODE_ENV === 'production' || warned.has(message)) return\n warned.add(message)\n console.warn(`[@dou-ui/editor] ${message}`)\n}\n"],"mappings":";;;;AAwJA,IAAM,aAAuB;CAAC;CAAQ;CAAU;CAAa;CAAU;AAAM;;AAG7E,IAAM,YAAY,SAAiB;CACjC,MAAM,QAAQ,WAAW,QAAQ,IAAI;CACrC,OAAO,QAAQ,IAAI,WAAW,SAAS;AACzC;;AAGA,SAAgB,WAAmB;CACjC,MAAM,SAAS,WAAW;CAC1B,IAAI,QAAQ,YAAY,OAAO,OAAO,WAAW;CAEjD,MAAM,wBAAQ,IAAI,WAAW,EAAE;CAC/B,IAAI,QAAQ,iBAAiB,OAAO,gBAAgB,KAAK;MACpD,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK,MAAM,KAAK,KAAK,MAAM,KAAK,OAAO,IAAI,GAAG;CAC3E,MAAM,KAAM,MAAM,KAAM,KAAQ;CAChC,MAAM,KAAM,MAAM,KAAM,KAAQ;CAChC,MAAM,MAAM,MAAM,KAAK,QAAQ,SAAS,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;CACnF,OAAO,GAAG,IAAI,MAAM,GAAG,CAAC,EAAE,GAAG,IAAI,MAAM,GAAG,EAAE,EAAE,GAAG,IAAI,MAAM,IAAI,EAAE,EAAE,GAAG,IAAI,MAAM,IAAI,EAAE,EAAE,GAAG,IAAI,MAAM,EAAE;AACzG;AAIA,SAAgB,SAAS,MAA+B;CACtD,MAAM,SAA0B,CAAC;CACjC,KAAK,SAAS,UAAU;EACtB,IAAI,MAAM,KAAK,SAAS,aAAa;GACnC,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;GAC7B;EACF;EACA,IAAI,CAAC,MAAM,QAAQ;GACjB,OAAO,KAAK;IAAE,MAAM;IAAU,MAAM,MAAM,KAAK;IAAM,OAAO,EAAE,GAAG,MAAM,MAAM;GAAE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,OAAO,IAAI,CAAC;CAChF,MAAM,QAAQ,SAAS,SACnB,CAAC,SAAS,OAAO,MAAM,WAAY,OAAO,MAAM,QAAQ,CAAC,IACzD,CAAC,OAAO;CACZ,OAAO,OAAO,MAAM,MAAO,OAAO,EAAE,IAAI,MAAM,MAAM,SAAS,EAAE,GAAG,KAAK;AACzE;AAEA,SAAgB,YAAY,QAAgB,QAAgC;CAC1E,MAAM,OAAO,OAAO,SAAS,SAAS,CAAC,EAAE,MAAM,YAAqB,CAAC;CACrE,OAAO,OAAO,MAAM,IAAK,OACvB,MACA,KAAK,KAAK,UAAU,cAAc,QAAQ,KAAK,CAAC,CAClD;AACF;AAEA,IAAM,yBAAS,IAAI,IAAY;;AAG/B,SAAgB,SAAS,SAAiB;CACxC,IAAA,QAAA,IAAA,aAA6B,gBAAgB,OAAO,IAAI,OAAO,GAAG;CAClE,OAAO,IAAI,OAAO;CAClB,QAAQ,KAAK,oBAAoB,SAAS;AAC5C"}
|
package/dist/core/transaction.js
CHANGED
|
@@ -10,6 +10,12 @@ import { closeHistory } from "prosemirror-history";
|
|
|
10
10
|
* providers other than the built-in one (collaboration reads it).
|
|
11
11
|
*/
|
|
12
12
|
var ownStepKey = "douOwnStep";
|
|
13
|
+
/**
|
|
14
|
+
* Set on a transaction that joins the undo step before it however long
|
|
15
|
+
* after it comes, e.g. the frames of a drag on a whiteboard (with
|
|
16
|
+
* `appendedTransaction` for the built-in history).
|
|
17
|
+
*/
|
|
18
|
+
var joinStepKey = "douJoinStep";
|
|
13
19
|
var warn = (message) => {
|
|
14
20
|
if (process.env.NODE_ENV !== "production") console.warn(`[@dou-ui/editor] ${message}`);
|
|
15
21
|
};
|
|
@@ -315,6 +321,6 @@ function applyEditorTransaction(view, transaction) {
|
|
|
315
321
|
view.dispatch(closeHistory(view.state.tr));
|
|
316
322
|
return true;
|
|
317
323
|
}
|
|
318
|
-
export { EditorTransaction, applyEditorTransaction, ownStepKey, selectionIn };
|
|
324
|
+
export { EditorTransaction, applyEditorTransaction, joinStepKey, ownStepKey, selectionIn };
|
|
319
325
|
|
|
320
326
|
//# sourceMappingURL=transaction.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction.js","names":[],"sources":["../../src/core/transaction.ts"],"sourcesContent":["import type { Node as PMNode, Schema } from 'prosemirror-model'\nimport {\n NodeSelection,\n Selection,\n TextSelection,\n type EditorState,\n type Transaction,\n} from 'prosemirror-state'\nimport { blockAround, findBlockById, 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;EAC7B,OAAO;CAC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ChE,IAAI,CAAC,GAAG,YAAY;EAClB,KAAK,SAAS,EAAE;EAChB,OAAO;CACT;CACA,IAAI,KAAK,YAAY,OAAO;EAC1B,GAAG,QAAQ,gBAAgB,KAAK;EAChC,KAAK,SAAS,EAAE;EAChB,OAAO;CACT;CACA,KAAK,SAAS,aAAa,EAAE,CAAC,CAAC,QAAQ,YAAY,IAAI,CAAC;CAExD,KAAK,SAAS,aAAa,KAAK,MAAM,EAAE,CAAC;CACzC,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"transaction.js","names":[],"sources":["../../src/core/transaction.ts"],"sourcesContent":["import type { Node as PMNode, Schema } from 'prosemirror-model'\nimport {\n NodeSelection,\n Selection,\n TextSelection,\n type EditorState,\n type Transaction,\n} from 'prosemirror-state'\nimport { blockAround, findBlockById, layoutOf, parentBlock, type BlockInfo } from './blocks'\nimport { blockSelectionRange } from './block-selection'\nimport {\n blockFromNode,\n contentAttrs,\n createContentNode,\n createId,\n nodeFromBlock,\n type Block,\n type BlockProps,\n type InlineContent,\n type PartialBlock,\n type PartialTableRow,\n} from './model'\nimport type { ContentType } from './schema'\nimport { closeHistory } from 'prosemirror-history'\nimport type { EditorView } from 'prosemirror-view'\nimport { originKey } from './editor'\n\n/**\n * Where blocks go: right before or after a block, or among a block's\n * children (`parent: null` is the top level). `index` counts from 0 and\n * defaults to the end.\n */\nexport type BlockPlacement =\n { before: string } | { after: string } | { parent: string | null; index?: number }\n\n/** The parts of a block to change. `props` are merged into the current ones. */\nexport interface BlockPatch {\n type?: ContentType\n props?: BlockProps\n /** Inline content, or plain text. */\n content?: InlineContent[] | string\n rows?: PartialTableRow[]\n /** Replaces all children; `[]` removes them. */\n children?: PartialBlock[]\n}\n\nexport interface EditorTransactionMeta {\n /** `false` keeps the change out of undo, e.g. a fix made by the program. */\n history?: boolean\n /** Who made the change; passed on to the `transaction` event. */\n origin?: string\n}\n\n/** Where a selection is put inside a block: at the start of its text or at the end. */\nexport type BlockEdge = 'start' | 'end'\n\n/**\n * Set on a transaction that is an undo step of its own, for history\n * providers other than the built-in one (collaboration reads it).\n */\nexport const ownStepKey = 'douOwnStep'\n\n/**\n * Set on a transaction that joins the undo step before it however long\n * after it comes, e.g. the frames of a drag on a whiteboard (with\n * `appendedTransaction` for the built-in history).\n */\nexport const joinStepKey = 'douJoinStep'\n\nconst warn = (message: string) => {\n if (process.env.NODE_ENV !== 'production') console.warn(`[@dou-ui/editor] ${message}`)\n}\n\n/**\n * Changes made by blocks and ids, applied together as one undo step. Ids\n * are looked up in the document as it is after the earlier calls.\n */\nexport class EditorTransaction {\n /** The ProseMirror transaction underneath, for anything the methods don't cover. */\n readonly tr: Transaction\n readonly meta: EditorTransactionMeta\n /** `focusBlock` was called: the editor takes focus once the changes are applied. */\n focused = false\n\n constructor(\n /** The state the changes start from. */\n readonly before: EditorState,\n meta: EditorTransactionMeta = {},\n /**\n * Whether the selection was placed by the user or the program. An editor\n * that never had focus has its selection at the start, which is no cursor.\n */\n private readonly hasCursor = true,\n ) {\n this.tr = before.tr\n this.meta = { ...meta }\n }\n\n get changed(): boolean {\n return this.tr.docChanged\n }\n\n setMeta(meta: EditorTransactionMeta): this {\n Object.assign(this.meta, meta)\n return this\n }\n\n /** A block as it is now, or `null`. */\n getBlock(id: string): Block | null {\n const info = findBlockById(this.tr.doc, id)\n return info ? blockFromNode(info.node) : null\n }\n\n /**\n * Insert blocks, by default after the block with the cursor (at the end\n * without one). Returns the new blocks' ids; an id already in the\n * document is replaced with a fresh one.\n */\n insertBlocks(blocks: PartialBlock[], placement?: BlockPlacement): string[] {\n if (!blocks.length) return []\n const tr = this.tr\n const schema = tr.doc.type.schema\n const taken = usedIds(tr.doc)\n const ids: string[] = []\n const nodes = blocks.map((block) => {\n const node = nodeFromBlock(schema, freshIds(block, taken), true)\n ids.push(node.attrs.id as string)\n return node\n })\n const target = placement ?? this.defaultPlacement()\n if (insertNodes(tr, target, nodes) === null) return []\n for (const id of ids) {\n const info = findBlockById(tr.doc, id)\n if (layoutOf(info?.node) === 'row' && info && inColumn(tr.doc, info))\n warn(\n `insertBlocks: columns don't go in a column; the block \"${id}\" is replaced by its columns' blocks`,\n )\n }\n return ids\n }\n\n /** Change a block's type, props, content or children. Returns `false` when it isn't found. */\n updateBlock(id: string, patch: BlockPatch): boolean {\n const tr = this.tr\n const info = findBlockById(tr.doc, id)\n if (!info) {\n warn(`updateBlock: no block with the id \"${id}\"`)\n return false\n }\n const schema = tr.doc.type.schema\n // check everything before changing anything: a refused patch changes nothing\n const typeName = patch.type ?? info.content.type.name\n const nodeType = schema.nodes[typeName]\n if (!nodeType?.isInGroup('blockContent')) {\n warn(`updateBlock: unknown block type \"${typeName}\"`)\n return false\n }\n const rowsSpec = !!nodeType.spec.rows\n if (patch.rows !== undefined && !rowsSpec) {\n warn(`updateBlock: a \"${typeName}\" block has no rows`)\n return false\n }\n if (patch.content !== undefined && (rowsSpec || !nodeType.inlineContent)) {\n warn(`updateBlock: a \"${typeName}\" block has no text content`)\n return false\n }\n if (patch.children) replaceChildren(tr, info, patch.children)\n if (\n patch.type === undefined &&\n patch.props === undefined &&\n patch.content === undefined &&\n patch.rows === undefined\n )\n return true\n const current = findBlockById(tr.doc, id)!\n const content = current.content\n const props = { ...content.attrs, ...patch.props }\n const keepsContent = patch.content === undefined && patch.rows === undefined\n // keep the text node for node when it can stay: collaborators typing in it keep their place\n if (keepsContent && nodeType === content.type) {\n tr.setNodeMarkup(current.contentPos, undefined, contentAttrs(nodeType, props))\n return true\n }\n if (keepsContent && nodeType.isTextblock && content.isTextblock) {\n const from = current.contentPos\n tr.setBlockType(\n from + 1,\n from + content.nodeSize - 1,\n nodeType,\n contentAttrs(nodeType, props),\n )\n return true\n }\n const block = blockFromNode(current.node)\n const next = createContentNode(\n schema,\n typeName,\n props,\n patch.content ?? block.content,\n patch.rows ?? block.rows,\n )\n tr.replaceWith(current.contentPos, current.contentPos + content.nodeSize, next)\n return true\n }\n\n /** Remove blocks with their children. The document always keeps one block. */\n removeBlocks(ids: string[]): boolean {\n const infos = outermost(this.tr.doc, ids, 'removeBlocks')\n if (!infos.length) return false\n deleteInfos(this.tr, infos)\n const tr = this.tr\n if (tr.doc.content.size === 0) tr.insert(0, emptyBlock(tr.doc.type.schema))\n return true\n }\n\n /**\n * Move blocks, in the order given, to `placement`. Fails when it is\n * inside one of them.\n */\n moveBlocks(ids: string[], placement: BlockPlacement): boolean {\n const tr = this.tr\n const infos = outermost(tr.doc, ids, 'moveBlocks')\n if (!infos.length) return false\n const anchor =\n 'before' in placement\n ? placement.before\n : 'after' in placement\n ? placement.after\n : placement.parent\n if (\n anchor !== null &&\n infos.some((info) => info.node.attrs.id === anchor || contains(info, tr.doc, anchor))\n ) {\n warn('moveBlocks: blocks cannot be moved next to or into themselves')\n return false\n }\n // insert the moved blocks first, then delete the originals: the document never empties\n const nodes = infos.map((info) => info.node)\n // a selection inside a moved block goes along with it\n const { anchor: anchorPos, head } = tr.selection\n const nodeSelected = tr.selection instanceof NodeSelection\n const carried = infos.findIndex(\n (info) =>\n anchorPos > info.pos &&\n anchorPos < info.pos + info.node.nodeSize &&\n head > info.pos &&\n head < info.pos + info.node.nodeSize,\n )\n const base = tr.steps.length\n const at = insertNodes(tr, placement, nodes)\n if (at === null) return false\n const inserted = tr.steps.length\n deleteInfos(tr, infos, base)\n if (carried >= 0) {\n const info = infos[carried]!\n let start = at\n for (let i = 0; i < carried; i++) start += nodes[i]!.nodeSize\n const moved = tr.mapping.slice(inserted).map(start, 1)\n const shift = (pos: number) => moved + (pos - info.pos)\n tr.setSelection(\n nodeSelected\n ? NodeSelection.create(tr.doc, shift(anchorPos))\n : TextSelection.create(tr.doc, shift(anchorPos), shift(head)),\n )\n }\n return true\n }\n\n /** Put the cursor at the start or end of a block's text (or select a block without text). */\n focusBlock(id: string, edge: BlockEdge = 'end'): boolean {\n const tr = this.tr\n const info = findBlockById(tr.doc, id)\n if (!info) {\n warn(`focusBlock: no block with the id \"${id}\"`)\n return false\n }\n tr.setSelection(selectionIn(tr, info, edge)).scrollIntoView()\n this.focused = true\n return true\n }\n\n /** After the selection's block, or at the end. */\n private defaultPlacement(): BlockPlacement {\n if (!this.hasCursor && !this.tr.selectionSet) return { parent: null }\n // selected blocks are only known before the first change\n const range = this.tr.docChanged ? null : blockSelectionRange(this.before)\n const id = range\n ? (range.parent.child(range.to).attrs.id as string)\n : (blockAround(this.tr.selection.$to)?.node.attrs.id as string | undefined)\n return id ? { after: id } : { parent: null }\n }\n}\n\nfunction emptyBlock(schema: Schema): PMNode {\n return schema.nodes.block!.create({ id: createId() }, schema.nodes.paragraph!.create())\n}\n\nfunction usedIds(doc: PMNode): Set<string> {\n const ids = new Set<string>()\n doc.descendants((node) => {\n if (node.type.name === 'block') ids.add(node.attrs.id as string)\n return node.type.name === 'block' || node.type.name === 'blockGroup'\n })\n return ids\n}\n\n/** The block with ids that are free, recursively. */\nfunction freshIds(block: PartialBlock, taken: Set<string>): PartialBlock {\n let id = block.id\n if (!id || taken.has(id)) id = createId()\n taken.add(id)\n return {\n ...block,\n id,\n children: block.children?.map((child) => freshIds(child, taken)),\n }\n}\n\n/** Whether a block with `id` sits inside `info`. */\nfunction contains(info: BlockInfo, doc: PMNode, id: string): boolean {\n const found = findBlockById(doc, id)\n return !!found && found.pos > info.pos && found.pos < info.pos + info.node.nodeSize\n}\n\n/** The blocks with these ids, without those inside another one of them, in the order given. */\nfunction outermost(doc: PMNode, ids: string[], method: string): BlockInfo[] {\n const infos: BlockInfo[] = []\n const seen = new Set<string>()\n for (const id of ids) {\n if (seen.has(id)) continue\n seen.add(id)\n const info = findBlockById(doc, id)\n if (info) infos.push(info)\n else warn(`${method}: no block with the id \"${id}\"`)\n }\n return infos.filter(\n (info) =>\n !infos.some(\n (other) =>\n other !== info && info.pos > other.pos && info.pos < other.pos + other.node.nodeSize,\n ),\n )\n}\n\n/**\n * Delete blocks found in the document as it was after step `base`; a\n * group left without children goes too.\n */\nfunction deleteInfos(tr: Transaction, infos: BlockInfo[], base = tr.steps.length) {\n // last first, so the earlier positions stay valid\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a copy\n const sorted = [...infos].sort((a, b) => b.pos - a.pos)\n for (const info of sorted) {\n // a block moved right in front of this one pushes it on (`1`)\n const from = tr.mapping.slice(base).map(info.pos, 1)\n const to = from + info.node.nodeSize\n const $from = tr.doc.resolve(from)\n if ($from.parent.type.name === 'blockGroup' && $from.parent.childCount === 1)\n tr.delete($from.before(), $from.after())\n else tr.delete(from, to)\n }\n}\n\n/** Insert block nodes at a placement. Returns `false` when the placement can't be found. */\nfunction insertNodes(tr: Transaction, placement: BlockPlacement, nodes: PMNode[]): number | null {\n const schema = tr.doc.type.schema\n let at: number\n if ('before' in placement || 'after' in placement) {\n const id = 'before' in placement ? placement.before : placement.after\n const info = findBlockById(tr.doc, id)\n if (!info) {\n warn(`no block with the id \"${id}\" to insert next to`)\n return null\n }\n at = 'before' in placement ? info.pos : info.pos + info.node.nodeSize\n } else if (placement.parent === null) {\n at = childPos(0, tr.doc, placement.index)\n } else {\n const info = findBlockById(tr.doc, placement.parent)\n if (!info) {\n warn(`no block with the id \"${placement.parent}\" to insert into`)\n return null\n }\n if (!info.group) {\n at = info.contentPos + info.content.nodeSize\n tr.insert(at, schema.nodes.blockGroup!.create(null, nodes))\n return at + 1\n }\n at = childPos(info.contentPos + info.content.nodeSize + 1, info.group, placement.index)\n }\n tr.insert(at, nodes)\n return at\n}\n\n/** The position before the child at `index` of a container whose content starts at `start`. */\nfunction childPos(start: number, container: PMNode, index = container.childCount) {\n const at = Math.max(0, Math.min(index, container.childCount))\n let pos = start\n for (let i = 0; i < at; i++) pos += container.child(i).nodeSize\n return pos\n}\n\n/** Whether a block sits in a column, at any depth. */\nfunction inColumn(doc: PMNode, info: BlockInfo): boolean {\n for (let parent = parentBlock(doc, info); parent; parent = parentBlock(doc, parent))\n if (layoutOf(parent.node) === 'column') return true\n return false\n}\n\nfunction replaceChildren(tr: Transaction, info: BlockInfo, children: PartialBlock[]) {\n const schema = tr.doc.type.schema\n const groupPos = info.contentPos + info.content.nodeSize\n const taken = usedIds(tr.doc)\n // the old children's ids are free again\n info.group?.descendants((node) => {\n if (node.type.name === 'block') taken.delete(node.attrs.id as string)\n })\n const nodes = children.map((child) => nodeFromBlock(schema, freshIds(child, taken), true))\n const group = nodes.length ? schema.nodes.blockGroup!.create(null, nodes) : null\n const end = info.group ? groupPos + info.group.nodeSize : groupPos\n if (group) tr.replaceWith(groupPos, end, group)\n else if (info.group) tr.delete(groupPos, end)\n}\n\n/** A cursor at the start or end of a block's text; a node selection for a block without text. */\nexport function selectionIn(tr: Transaction, info: BlockInfo, edge: BlockEdge): Selection {\n const content = info.content\n const doc = tr.doc\n if (content.isTextblock) {\n const pos = edge === 'start' ? info.contentPos + 1 : info.contentPos + content.nodeSize - 1\n return TextSelection.create(doc, pos)\n }\n if (content.isAtom) return NodeSelection.create(doc, info.contentPos)\n // a table: the first or last cell's text\n const inside = edge === 'start' ? info.contentPos + 1 : info.contentPos + content.nodeSize - 1\n return Selection.near(doc.resolve(inside), edge === 'start' ? 1 : -1)\n}\n\n/**\n * Apply a transaction made with `transact`: one undo step of its own,\n * unless `history` is `false`. Returns whether anything happened.\n */\nexport function applyEditorTransaction(view: EditorView, transaction: EditorTransaction): boolean {\n const { tr, meta } = transaction\n if (!tr.docChanged && !tr.selectionSet) return false\n if (meta.origin !== undefined) tr.setMeta(originKey, meta.origin)\n if (!tr.docChanged) {\n view.dispatch(tr)\n return true\n }\n if (meta.history === false) {\n tr.setMeta('addToHistory', false)\n view.dispatch(tr)\n return true\n }\n view.dispatch(closeHistory(tr).setMeta(ownStepKey, true))\n // and typing right after it starts another step\n view.dispatch(closeHistory(view.state.tr))\n return true\n}\n"],"mappings":";;;;;;;;;;;AA4DA,IAAa,aAAa;;;;;;AAO1B,IAAa,cAAc;AAE3B,IAAM,QAAQ,YAAoB;CAChC,IAAA,QAAA,IAAA,aAA6B,cAAc,QAAQ,KAAK,oBAAoB,SAAS;AACvF;;;;;AA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AM,SAAS,SAAS,UAAU,KAAK,aAAa,IAAI,KAAK,aAAa,QAAQ,WAAW;CAC7F,OAAO,UAAU,KAAK,IAAI,QAAQ,MAAM,GAAG,SAAS,UAAU,IAAI,EAAE;AACtE;;;;;AAMA,SAAgB,uBAAuB,MAAkB,aAAyC;CAChG,MAAM,EAAE,IAAI,SAAS;CACrB,IAAI,CAAC,GAAG,cAAc,CAAC,GAAG,cAAc,OAAO;CAC/C,IAAI,KAAK,WAAW,KAAA,GAAW,GAAG,QAAQ,WAAW,KAAK,MAAM;CAChE,IAAI,CAAC,GAAG,YAAY;EAClB,KAAK,SAAS,EAAE;EAChB,OAAO;CACT;CACA,IAAI,KAAK,YAAY,OAAO;EAC1B,GAAG,QAAQ,gBAAgB,KAAK;EAChC,KAAK,SAAS,EAAE;EAChB,OAAO;CACT;CACA,KAAK,SAAS,aAAa,EAAE,CAAC,CAAC,QAAQ,YAAY,IAAI,CAAC;CAExD,KAAK,SAAS,aAAa,KAAK,MAAM,EAAE,CAAC;CACzC,OAAO;AACT"}
|
package/dist/define-block.js
CHANGED
|
@@ -114,7 +114,8 @@ function vueNodeView(component, appContext, provides = []) {
|
|
|
114
114
|
stopEvent: (event) => {
|
|
115
115
|
const target = event.target;
|
|
116
116
|
if (contentElement?.contains(target)) return false;
|
|
117
|
-
|
|
117
|
+
const control = target.closest?.("input, textarea, select, button, a, [contenteditable=\"true\"], [data-editor-control]");
|
|
118
|
+
return !!control && control !== dom && dom.contains(control);
|
|
118
119
|
},
|
|
119
120
|
ignoreMutation: (mutation) => !contentElement || !contentElement.contains(mutation.target),
|
|
120
121
|
destroy() {
|
package/dist/define-block.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define-block.js","names":[],"sources":["../src/define-block.ts"],"sourcesContent":["import type { NodeSpec } from 'prosemirror-model'\nimport type { NodeView, NodeViewConstructor } from 'prosemirror-view'\nimport {\n defineComponent,\n h,\n inject,\n onMounted,\n provide,\n render,\n shallowReactive,\n shallowRef,\n type AppContext,\n type Component,\n type InjectionKey,\n type PropType,\n} from 'vue'\nimport type { BlockOption, EditorExtension, Label, MountComponent } from './core/extension'\nimport type { BlockProps } from './core/model'\n\n/** What a block's Vue component receives. */\nexport interface BlockViewProps {\n /** The block's id, type and current props. */\n block: { id: string; type: string; props: BlockProps }\n /** Change props; the change goes into the document, the undo history and collaboration. */\n updateProps: (props: BlockProps) => void\n /** The block is selected as a whole (a block without text was clicked). */\n selected: boolean\n editable: boolean\n}\n\nexport interface DefineBlockOptions {\n type: string\n /** The props and their defaults. They are stored in the document, as `Block.props`. */\n props?: Record<string, unknown>\n /** `inline` holds formatted text; `none` has no text (an image, an embed). Defaults to `inline`. */\n content?: 'inline' | 'none'\n /** Renders the block. Put `<EditorContent />` where the text goes. */\n component?: Component\n /** `Enter` at the end continues with the same type, like a list. */\n continues?: boolean\n /** Entries for the slash menu and the “turn into” menus; one is made from `menu` when given. */\n menu?: Omit<BlockOption, 'key' | 'type'> & { key?: string }\n /** Override the ProseMirror spec, e.g. `parseDOM` for pasting HTML from elsewhere. */\n spec?: Partial<NodeSpec>\n}\n\nconst contentKey: InjectionKey<HTMLElement | null> = Symbol('DouEditorContent')\n\n/** Where a block component's text goes. */\nexport const EditorContent = defineComponent({\n name: 'DouEditorContent',\n props: { as: { type: String as PropType<string>, default: 'div' } },\n setup(props) {\n const content = inject(contentKey, null)\n const host = shallowRef<HTMLElement | null>(null)\n onMounted(() => {\n if (content && host.value) host.value.append(content)\n })\n return () => h(props.as, { ref: host, class: 'dou-editor__text' })\n },\n})\n\n/** Store props as `data-prop-*` attributes, so copy and paste keep them. */\nconst dataAttrs = (props: Record<string, unknown>) =>\n Object.fromEntries(\n Object.entries(props).map(([name, value]) => [`data-prop-${name}`, JSON.stringify(value)]),\n )\n\nfunction readDataAttrs(dom: HTMLElement, names: string[]) {\n const attrs: Record<string, unknown> = {}\n for (const name of names) {\n const raw = dom.getAttribute(`data-prop-${name}`)\n if (raw === null) continue\n try {\n attrs[name] = JSON.parse(raw)\n } catch {\n // ignore attributes that are not ours\n }\n }\n return attrs\n}\n\n/** Renders components inside an app, with values provided to them. */\nexport function componentMounter(\n appContext: AppContext | null,\n provides: [InjectionKey<unknown>, unknown][] = [],\n): MountComponent {\n return (component, props, element) => {\n const Root = defineComponent({\n setup() {\n for (const [key, value] of provides) provide(key, value)\n return () => h(component, { ...props })\n },\n })\n const vnode = h(Root)\n vnode.appContext = appContext\n render(vnode, element)\n return () => render(null, element)\n }\n}\n\n/**\n * A node view that renders a Vue component. Everything the component shows\n * besides the text is outside the editable content, so its buttons and\n * inputs work as usual.\n */\nexport function vueNodeView(\n component: Component,\n appContext: AppContext | null,\n provides: [InjectionKey<unknown>, unknown][] = [],\n): NodeViewConstructor {\n return (node, view, getPos) => {\n // the id lives on the block around the content node\n const idOf = () => {\n const pos = getPos()\n if (pos === undefined) return ''\n return (view.state.doc.resolve(pos).parent.attrs.id as string | null) ?? ''\n }\n const type = node.type.name\n const dom = document.createElement('div')\n dom.className = `dou-editor__content dou-editor__content--${type} dou-editor__content--custom`\n dom.dataset.contentType = type\n const contentElement = node.isTextblock ? document.createElement('div') : null\n const state = shallowReactive<BlockViewProps>({\n block: { id: idOf(), type, props: { ...node.attrs } },\n selected: false,\n editable: view.editable,\n updateProps(props) {\n const pos = getPos()\n if (pos === undefined) return\n const current = view.state.doc.nodeAt(pos)\n if (!current) return\n view.dispatch(view.state.tr.setNodeMarkup(pos, undefined, { ...current.attrs, ...props }))\n },\n })\n const Root = defineComponent({\n setup() {\n provide(contentKey, contentElement)\n for (const [key, value] of provides) provide(key, value)\n return () => h(component, { ...state })\n },\n })\n const vnode = h(Root)\n vnode.appContext = appContext\n render(vnode, dom)\n let current = node\n const nodeView: NodeView = {\n dom,\n contentDOM: contentElement,\n update(next) {\n if (next.type !== current.type) return false\n current = next\n state.block = { id: idOf(), type, props: { ...next.attrs } }\n state.editable = view.editable\n return true\n },\n selectNode() {\n state.selected = true\n },\n deselectNode() {\n state.selected = false\n },\n // the component's own controls (and anything marked `data-editor-control`)\n // handle their events; the editor gets the rest, so a click on a block\n // without text still selects it\n stopEvent: (event) => {\n const target = event.target as HTMLElement\n if (contentElement?.contains(target)) return false\n return !!target.closest?.(\n 'input, textarea, select, button, a, [contenteditable=\"true\"], [data-editor-control]',\n )\n },\n ignoreMutation: (mutation) => !contentElement || !contentElement.contains(mutation.target),\n destroy() {\n render(null, dom)\n },\n }\n return nodeView\n }\n}\n\n/**\n * Declare a block type rendered by a Vue component (or by plain DOM), with\n * its props stored in the document. Returns an extension for `extensions`.\n */\nexport function defineBlock(options: DefineBlockOptions): EditorExtension {\n const { type } = options\n const props = options.props ?? {}\n const names = Object.keys(props)\n const inline = (options.content ?? 'inline') === 'inline'\n const spec: NodeSpec = {\n attrs: Object.fromEntries(names.map((name) => [name, { default: props[name] }])),\n ...(inline ? { content: 'inline*', defining: true } : { atom: true, selectable: true }),\n continues: options.continues,\n component: options.component,\n parseDOM: [\n {\n tag: `div[data-content-type=\"${type}\"]`,\n getAttrs: (dom) => readDataAttrs(dom as HTMLElement, names),\n },\n ],\n toDOM: (node) => {\n const attrs = {\n class: `dou-editor__content dou-editor__content--${type}`,\n 'data-content-type': type,\n ...dataAttrs(node.attrs),\n }\n return inline ? ['div', attrs, 0] : ['div', attrs]\n },\n ...options.spec,\n }\n const menu = options.menu\n return {\n name: `block:${type}`,\n blocks: { [type]: spec },\n blockOptions: menu ? [{ ...menu, key: menu.key ?? type, type }] : [],\n }\n}\n\nexport type { Label }\n"],"mappings":";;AA8CA,IAAM,aAA+C,OAAO,kBAAkB;;AAG9E,IAAa,gBAAgB,gBAAgB;CAC3C,MAAM;CACN,OAAO,EAAE,IAAI;EAAE,MAAM;EAA4B,SAAS;CAAM,EAAE;CAClE,MAAM,OAAO;EACX,MAAM,UAAU,OAAO,YAAY,IAAI;EACvC,MAAM,OAAO,WAA+B,IAAI;EAChD,gBAAgB;GACd,IAAI,WAAW,KAAK,OAAO,KAAK,MA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,MAAM;GACzF,UAAU;IACR,OAAO,MAAM,GAAG;GAClB;EAEK;CACT;AACF;;;;;AAMA,SAAgB,YAAY,SAA8C;CACxE,MAAM,EAAE,SAAS;CACjB,MAAM,QAAQ,QAAQ,SAAS,CAAC;CAChC,MAAM,QAAQ,OAAO,KAAK,KAAK;CAC/B,MAAM,UAAU,QAAQ,WAAW,cAAc;CACjD,MAAM,OAAiB;EACrB,OAAO,OAAO,YAAY,MAAM,KAAK,SAAS,CAAC,MAAM,EAAE,SAAS,MAAM,MAAM,CAAC,CAAC,CAAC;EAC/E,GAAI,SAAS;GAAE,SAAS;GAAW,UAAU;EAAK,IAAI;GAAE,MAAM;GAAM,YAAY;EAAK;EACrF,WAAW,QAAQ;EACnB,WAAW,QAAQ;EACnB,UAAU,CACR;GACE,KAAK,0BAA0B,KAAK;GACpC,WAAW,QAAQ,cAAc,KAAoB,KAAK;EAC5D,CACF;EACA,QAAQ,SAAS;GACf,MAAM,QAAQ;IACZ,OAAO,4CAA4C;IACnD,qBAAqB;IACrB,GAAG,UAAU,KAAK,KAAK;GACzB;GACA,OAAO,SAAS;IAAC;IAAO;IAAO;GAAC,IAAI,CAAC,OAAO,KAAK;EACnD;EACA,GAAG,QAAQ;CACb;CACA,MAAM,OAAO,QAAQ;CACrB,OAAO;EACL,MAAM,SAAS;EACf,QAAQ,GAAG,OAAO,KAAK;EACvB,cAAc,OAAO,CAAC;GAAE,GAAG;GAAM,KAAK,KAAK,OAAO;GAAM;EAAK,CAAC,IAAI,CAAC;CACrE;AACF"}
|
|
1
|
+
{"version":3,"file":"define-block.js","names":[],"sources":["../src/define-block.ts"],"sourcesContent":["import type { NodeSpec } from 'prosemirror-model'\nimport type { NodeView, NodeViewConstructor } from 'prosemirror-view'\nimport {\n defineComponent,\n h,\n inject,\n onMounted,\n provide,\n render,\n shallowReactive,\n shallowRef,\n type AppContext,\n type Component,\n type InjectionKey,\n type PropType,\n} from 'vue'\nimport type { BlockOption, EditorExtension, Label, MountComponent } from './core/extension'\nimport type { BlockProps } from './core/model'\n\n/** What a block's Vue component receives. */\nexport interface BlockViewProps {\n /** The block's id, type and current props. */\n block: { id: string; type: string; props: BlockProps }\n /** Change props; the change goes into the document, the undo history and collaboration. */\n updateProps: (props: BlockProps) => void\n /** The block is selected as a whole (a block without text was clicked). */\n selected: boolean\n editable: boolean\n}\n\nexport interface DefineBlockOptions {\n type: string\n /** The props and their defaults. They are stored in the document, as `Block.props`. */\n props?: Record<string, unknown>\n /** `inline` holds formatted text; `none` has no text (an image, an embed). Defaults to `inline`. */\n content?: 'inline' | 'none'\n /** Renders the block. Put `<EditorContent />` where the text goes. */\n component?: Component\n /** `Enter` at the end continues with the same type, like a list. */\n continues?: boolean\n /** Entries for the slash menu and the “turn into” menus; one is made from `menu` when given. */\n menu?: Omit<BlockOption, 'key' | 'type'> & { key?: string }\n /** Override the ProseMirror spec, e.g. `parseDOM` for pasting HTML from elsewhere. */\n spec?: Partial<NodeSpec>\n}\n\nconst contentKey: InjectionKey<HTMLElement | null> = Symbol('DouEditorContent')\n\n/** Where a block component's text goes. */\nexport const EditorContent = defineComponent({\n name: 'DouEditorContent',\n props: { as: { type: String as PropType<string>, default: 'div' } },\n setup(props) {\n const content = inject(contentKey, null)\n const host = shallowRef<HTMLElement | null>(null)\n onMounted(() => {\n if (content && host.value) host.value.append(content)\n })\n return () => h(props.as, { ref: host, class: 'dou-editor__text' })\n },\n})\n\n/** Store props as `data-prop-*` attributes, so copy and paste keep them. */\nconst dataAttrs = (props: Record<string, unknown>) =>\n Object.fromEntries(\n Object.entries(props).map(([name, value]) => [`data-prop-${name}`, JSON.stringify(value)]),\n )\n\nfunction readDataAttrs(dom: HTMLElement, names: string[]) {\n const attrs: Record<string, unknown> = {}\n for (const name of names) {\n const raw = dom.getAttribute(`data-prop-${name}`)\n if (raw === null) continue\n try {\n attrs[name] = JSON.parse(raw)\n } catch {\n // ignore attributes that are not ours\n }\n }\n return attrs\n}\n\n/** Renders components inside an app, with values provided to them. */\nexport function componentMounter(\n appContext: AppContext | null,\n provides: [InjectionKey<unknown>, unknown][] = [],\n): MountComponent {\n return (component, props, element) => {\n const Root = defineComponent({\n setup() {\n for (const [key, value] of provides) provide(key, value)\n return () => h(component, { ...props })\n },\n })\n const vnode = h(Root)\n vnode.appContext = appContext\n render(vnode, element)\n return () => render(null, element)\n }\n}\n\n/**\n * A node view that renders a Vue component. Everything the component shows\n * besides the text is outside the editable content, so its buttons and\n * inputs work as usual.\n */\nexport function vueNodeView(\n component: Component,\n appContext: AppContext | null,\n provides: [InjectionKey<unknown>, unknown][] = [],\n): NodeViewConstructor {\n return (node, view, getPos) => {\n // the id lives on the block around the content node\n const idOf = () => {\n const pos = getPos()\n if (pos === undefined) return ''\n return (view.state.doc.resolve(pos).parent.attrs.id as string | null) ?? ''\n }\n const type = node.type.name\n const dom = document.createElement('div')\n dom.className = `dou-editor__content dou-editor__content--${type} dou-editor__content--custom`\n dom.dataset.contentType = type\n const contentElement = node.isTextblock ? document.createElement('div') : null\n const state = shallowReactive<BlockViewProps>({\n block: { id: idOf(), type, props: { ...node.attrs } },\n selected: false,\n editable: view.editable,\n updateProps(props) {\n const pos = getPos()\n if (pos === undefined) return\n const current = view.state.doc.nodeAt(pos)\n if (!current) return\n view.dispatch(view.state.tr.setNodeMarkup(pos, undefined, { ...current.attrs, ...props }))\n },\n })\n const Root = defineComponent({\n setup() {\n provide(contentKey, contentElement)\n for (const [key, value] of provides) provide(key, value)\n return () => h(component, { ...state })\n },\n })\n const vnode = h(Root)\n vnode.appContext = appContext\n render(vnode, dom)\n let current = node\n const nodeView: NodeView = {\n dom,\n contentDOM: contentElement,\n update(next) {\n if (next.type !== current.type) return false\n current = next\n state.block = { id: idOf(), type, props: { ...next.attrs } }\n state.editable = view.editable\n return true\n },\n selectNode() {\n state.selected = true\n },\n deselectNode() {\n state.selected = false\n },\n // the component's own controls (and anything marked `data-editor-control`)\n // handle their events; the editor gets the rest, so a click on a block\n // without text still selects it\n stopEvent: (event) => {\n const target = event.target as HTMLElement\n if (contentElement?.contains(target)) return false\n const control = target.closest?.(\n 'input, textarea, select, button, a, [contenteditable=\"true\"], [data-editor-control]',\n )\n // only inside the block: the editor around it is contenteditable too\n return !!control && control !== dom && dom.contains(control)\n },\n ignoreMutation: (mutation) => !contentElement || !contentElement.contains(mutation.target),\n destroy() {\n render(null, dom)\n },\n }\n return nodeView\n }\n}\n\n/**\n * Declare a block type rendered by a Vue component (or by plain DOM), with\n * its props stored in the document. Returns an extension for `extensions`.\n */\nexport function defineBlock(options: DefineBlockOptions): EditorExtension {\n const { type } = options\n const props = options.props ?? {}\n const names = Object.keys(props)\n const inline = (options.content ?? 'inline') === 'inline'\n const spec: NodeSpec = {\n attrs: Object.fromEntries(names.map((name) => [name, { default: props[name] }])),\n ...(inline ? { content: 'inline*', defining: true } : { atom: true, selectable: true }),\n continues: options.continues,\n component: options.component,\n parseDOM: [\n {\n tag: `div[data-content-type=\"${type}\"]`,\n getAttrs: (dom) => readDataAttrs(dom as HTMLElement, names),\n },\n ],\n toDOM: (node) => {\n const attrs = {\n class: `dou-editor__content dou-editor__content--${type}`,\n 'data-content-type': type,\n ...dataAttrs(node.attrs),\n }\n return inline ? ['div', attrs, 0] : ['div', attrs]\n },\n ...options.spec,\n }\n const menu = options.menu\n return {\n name: `block:${type}`,\n blocks: { [type]: spec },\n blockOptions: menu ? [{ ...menu, key: menu.key ?? type, type }] : [],\n }\n}\n\nexport type { Label }\n"],"mappings":";;AA8CA,IAAM,aAA+C,OAAO,kBAAkB;;AAG9E,IAAa,gBAAgB,gBAAgB;CAC3C,MAAM;CACN,OAAO,EAAE,IAAI;EAAE,MAAM;EAA4B,SAAS;CAAM,EAAE;CAClE,MAAM,OAAO;EACX,MAAM,UAAU,OAAO,YAAY,IAAI;EACvC,MAAM,OAAO,WAA+B,IAAI;EAChD,gBAAgB;GACd,IAAI,WAAW,KAAK,OAAO,KAAK,MAAM,OAAO,OAAO;EACtD,CAAC;EACD,aAAa,EAAE,MA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SAAS,SAAS,MAAM;GACzF,UAAU;IACR,OAAO,MAAM,GAAG;GAClB;EAEK;CACT;AACF;;;;;AAMA,SAAgB,YAAY,SAA8C;CACxE,MAAM,EAAE,SAAS;CACjB,MAAM,QAAQ,QAAQ,SAAS,CAAC;CAChC,MAAM,QAAQ,OAAO,KAAK,KAAK;CAC/B,MAAM,UAAU,QAAQ,WAAW,cAAc;CACjD,MAAM,OAAiB;EACrB,OAAO,OAAO,YAAY,MAAM,KAAK,SAAS,CAAC,MAAM,EAAE,SAAS,MAAM,MAAM,CAAC,CAAC,CAAC;EAC/E,GAAI,SAAS;GAAE,SAAS;GAAW,UAAU;EAAK,IAAI;GAAE,MAAM;GAAM,YAAY;EAAK;EACrF,WAAW,QAAQ;EACnB,WAAW,QAAQ;EACnB,UAAU,CACR;GACE,KAAK,0BAA0B,KAAK;GACpC,WAAW,QAAQ,cAAc,KAAoB,KAAK;EAC5D,CACF;EACA,QAAQ,SAAS;GACf,MAAM,QAAQ;IACZ,OAAO,4CAA4C;IACnD,qBAAqB;IACrB,GAAG,UAAU,KAAK,KAAK;GACzB;GACA,OAAO,SAAS;IAAC;IAAO;IAAO;GAAC,IAAI,CAAC,OAAO,KAAK;EACnD;EACA,GAAG,QAAQ;CACb;CACA,MAAM,OAAO,QAAQ;CACrB,OAAO;EACL,MAAM,SAAS;EACf,QAAQ,GAAG,OAAO,KAAK;EACvB,cAAc,OAAO,CAAC;GAAE,GAAG;GAAM,KAAK,KAAK,OAAO;GAAM;EAAK,CAAC,IAAI,CAAC;CACrE;AACF"}
|
package/dist/document.js
CHANGED
|
@@ -31,7 +31,8 @@ function shapeProblems(value, lists) {
|
|
|
31
31
|
* marks and inline nodes the extensions don't define, which the editor
|
|
32
32
|
* would show as a paragraph or leave out, and columns the editor would
|
|
33
33
|
* change on the next edit (a column outside a set of columns, a set with
|
|
34
|
-
* fewer than two, columns in a column…)
|
|
34
|
+
* fewer than two, columns in a column…), and props a block type says it can't use
|
|
35
|
+
* (its spec's `checkProps`, e.g. a whiteboard's board that isn't a flow).
|
|
35
36
|
*/
|
|
36
37
|
function checkDocument(document, options = {}) {
|
|
37
38
|
const shape = shapeProblems(document, ["blocks"]);
|
|
@@ -50,6 +51,7 @@ function checkDocument(document, options = {}) {
|
|
|
50
51
|
checkBlock(block, path, schema, ids, problems);
|
|
51
52
|
const layout = layoutOfType(schema, block.type);
|
|
52
53
|
checkLayout(block, layout, path, around, schema, problems);
|
|
54
|
+
checkProps(block, path, schema, problems);
|
|
53
55
|
if (block.children) walk(block.children, `${path}.children`, {
|
|
54
56
|
layout,
|
|
55
57
|
inColumn: around.inColumn || layout === "column"
|
|
@@ -61,6 +63,23 @@ function checkDocument(document, options = {}) {
|
|
|
61
63
|
});
|
|
62
64
|
return problems;
|
|
63
65
|
}
|
|
66
|
+
/**
|
|
67
|
+
* Props a block type can't use, as its spec's `checkProps` tells: a
|
|
68
|
+
* whiteboard whose `board` isn't a flow document, a height that isn't a
|
|
69
|
+
* number… Each is `{ prop, message }`.
|
|
70
|
+
*/
|
|
71
|
+
function checkProps(block, path, schema, problems) {
|
|
72
|
+
const type = block.type ?? "paragraph";
|
|
73
|
+
const check = schema.nodes[type]?.spec.checkProps;
|
|
74
|
+
if (!check || !block.props) return;
|
|
75
|
+
for (const { prop, message } of check(block.props)) problems.push({
|
|
76
|
+
code: "invalid-props",
|
|
77
|
+
blockId: block.id,
|
|
78
|
+
path: `${path}.props.${prop}`,
|
|
79
|
+
text: type,
|
|
80
|
+
message
|
|
81
|
+
});
|
|
82
|
+
}
|
|
64
83
|
var layoutOfType = (schema, type) => schema.nodes[type ?? "paragraph"]?.spec.layout;
|
|
65
84
|
/** Columns as the editor keeps them; anything else it changes on the next edit. */
|
|
66
85
|
function checkLayout(block, layout, path, around, schema, problems) {
|
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:\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;CA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,SAAS,CAAC;AACnC"}
|
|
1
|
+
{"version":3,"file":"document.js","names":[],"sources":["../src/document.ts"],"sourcesContent":["import type { Schema } from 'prosemirror-model'\nimport { kitOf, type EditorExtensionList } from './core/convert'\nimport type { Block, EditorDocument, PartialBlock, PartialTableRow } from './core/model'\nimport { editorKit } from './extensions/editor-kit'\n\n/** A document with no blocks, to start from when nothing is saved yet. */\nexport const emptyDocument = (): EditorDocument<Block> => ({ version: 1, blocks: [] })\n\nexport interface DocumentProblem {\n code:\n | 'version'\n | 'shape'\n | 'duplicate-id'\n | 'unknown-type'\n | 'unknown-mark'\n | 'unknown-inline'\n | 'invalid-columns'\n | 'invalid-props'\n /** The block at fault, when it has an id. */\n blockId?: string\n /**\n * Where the problem is, as a path into the document, e.g.\n * `blocks[0].children[2]` or `blocks[1].content[0]`; `version` for the version.\n */\n path: string\n /** The id, type, mark or inline node at fault, for the editor's message. */\n text: string\n /** An English description, for logs. */\n message: string\n}\n\nexport interface CheckDocumentOptions {\n /** The editor's `extensions`, for the blocks, marks and inline nodes they add; `[editorKit()]` by default, as in the editor. */\n extensions?: EditorExtensionList\n}\n\nlet defaultKit: EditorExtensionList | undefined\n\n/**\n * What is wrong with the shape itself: the document is not an object, or a\n * list in it is not an array. Nothing else can be checked until it is fixed.\n */\nfunction shapeProblems(value: unknown, lists: string[]): DocumentProblem[] {\n if (!value || typeof value !== 'object' || Array.isArray(value))\n return [{ code: 'shape', path: '', text: '', message: 'The document is not an object' }]\n return lists\n .filter((key) => !Array.isArray((value as Record<string, unknown>)[key]))\n .map((key) => ({ code: 'shape', path: key, text: '', message: `\"${key}\" is not a list` }))\n}\n\n/**\n * The problems of an editor document, before it is saved or shown: an\n * unknown version, blocks or table rows sharing an id, and block types,\n * marks and inline nodes the extensions don't define, which the editor\n * would show as a paragraph or leave out, and columns the editor would\n * change on the next edit (a column outside a set of columns, a set with\n * fewer than two, columns in a column…), and props a block type says it can't use\n * (its spec's `checkProps`, e.g. a whiteboard's board that isn't a flow).\n */\nexport function checkDocument(\n document: EditorDocument<PartialBlock>,\n options: CheckDocumentOptions = {},\n): DocumentProblem[] {\n const shape = shapeProblems(document, ['blocks'])\n if (shape.length) return shape\n const problems: DocumentProblem[] = []\n if (document.version !== 1)\n problems.push({\n code: 'version',\n path: 'version',\n text: String(document.version),\n message: `Version ${String(document.version)} is not known`,\n })\n const { schema } = kitOf(options.extensions ?? (defaultKit ??= [editorKit()]))\n const ids = new Set<string>()\n const walk = (blocks: readonly PartialBlock[], at: string, around: Around) =>\n blocks.forEach((block, i) => {\n const path = `${at}[${i}]`\n checkBlock(block, path, schema, ids, problems)\n const layout = layoutOfType(schema, block.type)\n checkLayout(block, layout, path, around, schema, problems)\n checkProps(block, path, schema, problems)\n if (block.children)\n walk(block.children, `${path}.children`, {\n layout,\n inColumn: around.inColumn || layout === 'column',\n })\n })\n walk(document.blocks, 'blocks', { layout: undefined, inColumn: false })\n return problems\n}\n\n/**\n * Props a block type can't use, as its spec's `checkProps` tells: a\n * whiteboard whose `board` isn't a flow document, a height that isn't a\n * number… Each is `{ prop, message }`.\n */\nfunction checkProps(\n block: PartialBlock,\n path: string,\n schema: Schema,\n problems: DocumentProblem[],\n) {\n const type = block.type ?? 'paragraph'\n const check = schema.nodes[type]?.spec.checkProps as\n ((props: Record<string, unknown>) => { prop: string; message: string }[]) | undefined\n if (!check || !block.props) return\n for (const { prop, message } of check(block.props as Record<string, unknown>))\n problems.push({\n code: 'invalid-props',\n blockId: block.id,\n path: `${path}.props.${prop}`,\n text: type,\n message,\n })\n}\n\n/** What a block sits in: the layout of its parent, and whether that is inside a column. */\ninterface Around {\n layout: string | undefined\n inColumn: boolean\n}\n\nconst layoutOfType = (schema: Schema, type: string | undefined) =>\n schema.nodes[type ?? 'paragraph']?.spec.layout as string | undefined\n\n/** Columns as the editor keeps them; anything else it changes on the next edit. */\nfunction checkLayout(\n block: PartialBlock,\n layout: string | undefined,\n path: string,\n around: Around,\n schema: Schema,\n problems: DocumentProblem[],\n) {\n const type = block.type ?? 'paragraph'\n const report = (message: string, at = path) =>\n problems.push({ code: 'invalid-columns', blockId: block.id, path: at, text: type, message })\n const children = block.children ?? []\n if (around.layout === 'row' && layout !== 'column')\n report(`A \"${type}\" block directly in a set of columns would move into the column before it`)\n if (layout === 'column') {\n if (around.layout !== 'row')\n report('A column outside a set of columns would be replaced by its blocks')\n if (!children.length) report('An empty column would be removed')\n const width = block.props?.width\n if (width != null && !(typeof width === 'number' && width > 0))\n report(\n `The column width ${JSON.stringify(width)} is not a positive number; it would be ignored`,\n `${path}.props.width`,\n )\n }\n if (layout === 'row') {\n if (around.inColumn) report('Columns inside a column would be replaced by their blocks')\n const columns = children.filter((child) => layoutOfType(schema, child.type) === 'column')\n if (columns.length < 2)\n report(`A set of ${columns.length} column(s) would be replaced by its blocks`)\n }\n if (layout && Array.isArray(block.content) && block.content.length)\n report(\n `A \"${type}\" block has no text of its own; its content would be left out`,\n `${path}.content`,\n )\n}\n\nfunction checkBlock(\n block: PartialBlock,\n path: string,\n schema: Schema,\n ids: Set<string>,\n problems: DocumentProblem[],\n) {\n const blockId = block.id\n if (blockId !== undefined) {\n if (ids.has(blockId))\n problems.push({\n code: 'duplicate-id',\n blockId,\n path,\n text: blockId,\n message: `The block id \"${blockId}\" is used more than once`,\n })\n ids.add(blockId)\n }\n const type = block.type ?? 'paragraph'\n if (!schema.nodes[type]?.isInGroup('blockContent'))\n problems.push({\n code: 'unknown-type',\n blockId,\n path,\n text: type,\n message: `No block type \"${type}\" is defined; it would show as a paragraph`,\n })\n if (Array.isArray(block.content))\n block.content.forEach((item, i) => {\n const at = `${path}.content[${i}]`\n if (item.type === 'inline' && !schema.nodes[item.name]?.isInline)\n problems.push({\n code: 'unknown-inline',\n blockId,\n path: at,\n text: item.name,\n message: `No inline node \"${item.name}\" is defined; it would be left out`,\n })\n if (item.type === 'text')\n for (const mark of item.marks ?? [])\n if (!schema.marks[mark])\n problems.push({\n code: 'unknown-mark',\n blockId,\n path: at,\n text: mark,\n message: `No mark \"${mark}\" is defined; it would be left out`,\n })\n })\n if (block.rows) checkRows(block.rows, `${path}.rows`, blockId, problems)\n}\n\nfunction checkRows(\n rows: readonly PartialTableRow[],\n path: string,\n blockId: string | undefined,\n problems: DocumentProblem[],\n) {\n const ids = new Set<string>()\n rows.forEach((row, i) => {\n if (row.id === undefined) return\n if (ids.has(row.id))\n problems.push({\n code: 'duplicate-id',\n blockId,\n path: `${path}[${i}]`,\n text: row.id,\n message: `The row id \"${row.id}\" is used more than once in a table`,\n })\n ids.add(row.id)\n })\n}\n\nconst objects = <T>(value: unknown) =>\n (Array.isArray(value) ? value : []).filter(\n (item): item is T => !!item && typeof item === 'object',\n )\n\n/** The saved data as an object of version 1, or an error saying why it can't be. */\nfunction sourceOf(input: unknown): Record<string, unknown> {\n if (!input || typeof input !== 'object' || Array.isArray(input))\n throw new Error(\n `[@dou-ui/editor] an editor document must be an object, not ${Array.isArray(input) ? 'an array' : (JSON.stringify(input) ?? String(input))}`,\n )\n const source = input as Record<string, unknown>\n const version = source.version ?? 1\n if (version !== 1)\n throw new Error(\n `[@dou-ui/editor] unknown document version ${JSON.stringify(version) ?? String(version)} (expected 1); data saved by a newer @dou-ui/editor needs that version to open`,\n )\n return source\n}\n\n/**\n * Brings a saved document up to the current version, and fills what an\n * older or hand-written one may lack (`version`, `blocks`). Blocks that are\n * not objects are dropped; anything else is kept as it is, for the editor\n * to read as it reads partial blocks. Throws for data that is not an object (an array,\n * `null`, a string) and for a version it does not know.\n */\nexport function migrateDocument(input: unknown): EditorDocument<PartialBlock> {\n const source = sourceOf(input)\n return { ...source, version: 1, blocks: objects<PartialBlock>(source.blocks) }\n}\n\nconst warned = new Set<string>()\n\n/**\n * The blocks of the `v-model`, as the editor reads them. A document of the\n * wrong shape (not an object, a bare list of blocks, without `blocks` or a\n * known `version`) gets a warning in development and is read as well as it\n * can be: a list as the blocks, anything else missing as no blocks. What\n * the editor writes back always carries `version: 1`. `undefined`, no\n * `v-model` bound, is fine.\n */\nexport function readBlocks(value: unknown): PartialBlock[] | undefined {\n if (value === undefined) return undefined\n const plain = !!value && typeof value === 'object' && !Array.isArray(value)\n const source = (plain ? value : {}) as Partial<EditorDocument<PartialBlock>>\n const blocks = Array.isArray(source.blocks)\n const problem = Array.isArray(value)\n ? 'is a list of blocks'\n : !plain\n ? `is ${JSON.stringify(value) ?? String(value)}`\n : !blocks\n ? 'has no blocks array'\n : source.version === undefined\n ? 'has no version'\n : source.version !== 1\n ? `has version ${JSON.stringify(source.version)}`\n : ''\n if (problem && process.env.NODE_ENV !== 'production' && !warned.has(problem)) {\n warned.add(problem)\n console.warn(\n `[@dou-ui/editor] the v-model ${problem}; expected { version: 1, blocks: [...] }. It is read as well as it can be and the version as 1; read saved data with migrateDocument().`,\n )\n }\n if (Array.isArray(value)) return value as PartialBlock[]\n return blocks ? source.blocks : []\n}\n"],"mappings":";;;;AAMA,IAAa,uBAA8C;CAAE,SAAS;CAAG,QAAQ,CAAC;AAAE;AA8BpF,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;;;;;;;;;;AAWA,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;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d,MAAM,IAAI,MACR,6CAA6C,KAAK,UAAU,OAAO,KAAK,OAAO,OAAO,EAAE,+EAC1F;CACF,OAAO;AACT;;;;;;;;AASA,SAAgB,gBAAgB,OAA8C;CAC5E,MAAM,SAAS,SAAS,KAAK;CAC7B,OAAO;EAAE,GAAG;EAAQ,SAAS;EAAG,QAAQ,QAAsB,OAAO,MAAM;CAAE;AAC/E;AAEA,IAAM,yBAAS,IAAI,IAAY;;;;;;;;;AAU/B,SAAgB,WAAW,OAA4C;CACrE,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,MAAM,QAAQ,CAAC,CAAC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;CAC1E,MAAM,SAAU,QAAQ,QAAQ,CAAC;CACjC,MAAM,SAAS,MAAM,QAAQ,OAAO,MAAM;CAC1C,MAAM,UAAU,MAAM,QAAQ,KAAK,IAC/B,wBACA,CAAC,QACC,MAAM,KAAK,UAAU,KAAK,KAAK,OAAO,KAAK,MAC3C,CAAC,SACC,wBACA,OAAO,YAAY,KAAA,IACjB,mBACA,OAAO,YAAY,IACjB,eAAe,KAAK,UAAU,OAAO,OAAO,MAC5C;CACZ,IAAI,WAAA,QAAA,IAAA,aAAoC,gBAAgB,CAAC,OAAO,IAAI,OAAO,GAAG;EAC5E,OAAO,IAAI,OAAO;EAClB,QAAQ,KACN,gCAAgC,QAAQ,wIAC1C;CACF;CACA,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO;CACjC,OAAO,SAAS,OAAO,SAAS,CAAC;AACnC"}
|
package/dist/dom.js
CHANGED
|
@@ -126,11 +126,22 @@ function handleLeft(content) {
|
|
|
126
126
|
const table = content.querySelector("table");
|
|
127
127
|
return table ? Math.max(rect.left, table.getBoundingClientRect().left) : contentSpan(content).left;
|
|
128
128
|
}
|
|
129
|
+
/**
|
|
130
|
+
* How far the block handle's bubble moves in over the text: by as much as
|
|
131
|
+
* its `start` (its left edge, "+" included when it can come out) lacks of
|
|
132
|
+
* `clip` plus 2px. Next to a table, a bubble that has to move in goes on
|
|
133
|
+
* past `clear`, right of the table's row handles, rather than onto them.
|
|
134
|
+
*/
|
|
135
|
+
function bubbleShift(start, clip, clear) {
|
|
136
|
+
const shift = Math.max(0, Math.ceil(clip + 2 - start));
|
|
137
|
+
if (!shift || clear === void 0) return shift;
|
|
138
|
+
return Math.max(shift, Math.ceil(clear - start));
|
|
139
|
+
}
|
|
129
140
|
/** The right edge of the editor's text column: the surface less its padding (a reading width). */
|
|
130
141
|
function columnRight(surface) {
|
|
131
142
|
const padding = Number.parseFloat(getComputedStyle(surface).paddingRight) || 0;
|
|
132
143
|
return surface.getBoundingClientRect().right - padding;
|
|
133
144
|
}
|
|
134
|
-
export { COLUMNS_GROUP, COLUMN_GROUP, blockElementOf, childBlocks, columnAtX, columnRight, contentAt, contentSpan, firstLine, handleLeft, scrollParent, sideBySide };
|
|
145
|
+
export { COLUMNS_GROUP, COLUMN_GROUP, blockElementOf, bubbleShift, childBlocks, columnAtX, columnRight, contentAt, contentSpan, firstLine, handleLeft, scrollParent, sideBySide };
|
|
135
146
|
|
|
136
147
|
//# 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\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,QAAQ;CACZ,KAAK,IAAI,OAAO,GAAG,OAAO,QAAQ,QAAQ,QACxC,IA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AAU;CACrD,MAAM,UAAU,OAAO,WAAW,MAAM,UAAU,KAAK;CACvD,MAAM,SAAS,OAAO,SAAS,UAAU,IAAI,KAAK,IAAI,YAAY,KAAK,MAAM,IAAI,KAAK;CACtF,OAAO;EAAE,KAAK,KAAK,OAAO,SAAS,KAAK,SAAS,UAAU;EAAI;CAAO;AACxE;;AAGA,IAAM,eAAe,YACnB,QAAQ,UAAU,SAAS,4BAA4B,KACvD,CAAC,CAAC,QAAQ,eAAe,eAAe,UAAU,SAAS,qBAAqB;;;;;;;AAQlF,SAAgB,YAAY,SAAuD;CACjF,MAAM,OAAO,QAAQ,sBAAsB;CAC3C,IAAI,CAAC,YAAY,OAAO,GAAG,OAAO;EAAE,MAAM,KAAK;EAAM,OAAO,KAAK;CAAM;CACvE,MAAM,QAAQ,iBAAiB,OAAO;CACtC,OAAO;EACL,MAAM,KAAK,QAAQ,OAAO,WAAW,MAAM,kBAAkB,KAAK;EAClE,OAAO,KAAK,SAAS,OAAO,WAAW,MAAM,eAAe,KAAK;CACnE;AACF;;;;;AAMA,SAAgB,WAAW,SAA8B;CACvD,MAAM,OAAO,QAAQ,sBAAsB;CAC3C,IAAI,CAAC,YAAY,OAAO,GAAG,OAAO,KAAK;CACvC,MAAM,QAAQ,QAAQ,cAAc,OAAO;CAC3C,OAAO,QAAQ,KAAK,IAAI,KAAK,MAAM,MAAM,sBAAsB,CAAC,CAAC,IAAI,IAAI,YAAY,OAAO,CAAC,CAAC;AAChG;;AAGA,SAAgB,YAAY,SAA8B;CACxD,MAAM,UAAU,OAAO,WAAW,iBAAiB,OAAO,CAAC,CAAC,YAAY,KAAK;CAC7E,OAAO,QAAQ,sBAAsB,CAAC,CAAC,QAAQ;AACjD"}
|
|
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/**\n * How far the block handle's bubble moves in over the text: by as much as\n * its `start` (its left edge, \"+\" included when it can come out) lacks of\n * `clip` plus 2px. Next to a table, a bubble that has to move in goes on\n * past `clear`, right of the table's row handles, rather than onto them.\n */\nexport function bubbleShift(start: number, clip: number, clear?: number): number {\n const shift = Math.max(0, Math.ceil(clip + 2 - start))\n if (!shift || clear === undefined) return shift\n return Math.max(shift, Math.ceil(clear - start))\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,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