@dou-ui/editor 0.1.0-alpha.2 → 0.1.0-alpha.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/code/code-editor-block.js.map +1 -1
- package/dist/code/code-editor-block.vue_vue_type_script_setup_true_lang.js +1 -0
- package/dist/code/code-editor-block.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/collaboration/binding.js +371 -57
- package/dist/collaboration/binding.js.map +1 -1
- package/dist/collaboration/cursors.js +42 -10
- package/dist/collaboration/cursors.js.map +1 -1
- package/dist/collaboration/index.js +61 -11
- package/dist/collaboration/index.js.map +1 -1
- package/dist/collaboration/inline-diff.js +138 -0
- package/dist/collaboration/inline-diff.js.map +1 -0
- package/dist/collaboration/merged-props.js +152 -0
- package/dist/collaboration/merged-props.js.map +1 -0
- package/dist/collaboration/order.js +41 -1
- package/dist/collaboration/order.js.map +1 -1
- package/dist/collaboration/table.js +64 -25
- package/dist/collaboration/table.js.map +1 -1
- package/dist/collaboration/text.js +213 -1
- package/dist/collaboration/text.js.map +1 -1
- package/dist/components/block-handle.js.map +1 -1
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js +125 -17
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/components/bubble-toolbar.js.map +1 -1
- package/dist/components/bubble-toolbar.vue_vue_type_script_setup_true_lang.js +2 -1
- package/dist/components/bubble-toolbar.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/components/comment-card.js.map +1 -1
- package/dist/components/comment-card.vue_vue_type_script_setup_true_lang.js +2 -1
- package/dist/components/comment-card.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/components/slash-choices.js +6 -0
- package/dist/components/slash-choices.js.map +1 -0
- package/dist/components/slash-choices.vue_vue_type_script_setup_true_lang.js +56 -0
- package/dist/components/slash-choices.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/components/slash-menu.js.map +1 -1
- package/dist/components/slash-menu.vue_vue_type_script_setup_true_lang.js +185 -20
- package/dist/components/slash-menu.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/core/block-selection.js +32 -4
- package/dist/core/block-selection.js.map +1 -1
- package/dist/core/blocks.js +21 -3
- package/dist/core/blocks.js.map +1 -1
- package/dist/core/commands.js +125 -13
- package/dist/core/commands.js.map +1 -1
- package/dist/core/comments.js +85 -3
- package/dist/core/comments.js.map +1 -1
- package/dist/core/convert.js +3 -3
- package/dist/core/convert.js.map +1 -1
- package/dist/core/editor.js +2 -1
- package/dist/core/editor.js.map +1 -1
- package/dist/core/extension.js +6 -2
- package/dist/core/extension.js.map +1 -1
- package/dist/core/model.js +10 -3
- package/dist/core/model.js.map +1 -1
- package/dist/core/plugins.js +108 -5
- package/dist/core/plugins.js.map +1 -1
- package/dist/core/prepare.js +12 -5
- package/dist/core/prepare.js.map +1 -1
- package/dist/core/schema.js.map +1 -1
- package/dist/core/transaction.js +19 -4
- package/dist/core/transaction.js.map +1 -1
- package/dist/define-block.js +8 -4
- package/dist/define-block.js.map +1 -1
- package/dist/document.js +59 -4
- package/dist/document.js.map +1 -1
- package/dist/dom.js +112 -13
- package/dist/dom.js.map +1 -1
- package/dist/editor.js.map +1 -1
- package/dist/editor.vue_vue_type_script_setup_true_lang.js +3 -3
- package/dist/editor.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/editor2.js.map +1 -1
- package/dist/extensions/align/align-menu.js.map +1 -1
- package/dist/extensions/align/align-menu.vue_vue_type_script_setup_true_lang.js +4 -6
- package/dist/extensions/align/align-menu.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/extensions/callout/html.js +5 -4
- package/dist/extensions/callout/html.js.map +1 -1
- package/dist/extensions/colors/color-menu.js.map +1 -1
- package/dist/extensions/colors/color-menu.vue_vue_type_script_setup_true_lang.js +6 -8
- package/dist/extensions/colors/color-menu.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/extensions/columns/column-picker.js +6 -0
- package/dist/extensions/columns/column-picker.js.map +1 -0
- package/dist/extensions/columns/column-picker.vue_vue_type_script_setup_true_lang.js +57 -0
- package/dist/extensions/columns/column-picker.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/columns/columns-controls.js +6 -0
- package/dist/extensions/columns/columns-controls.js.map +1 -0
- package/dist/extensions/columns/columns-controls.vue_vue_type_script_setup_true_lang.js +341 -0
- package/dist/extensions/columns/columns-controls.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/columns/html.js +34 -0
- package/dist/extensions/columns/html.js.map +1 -0
- package/dist/extensions/columns/index.js +57 -0
- package/dist/extensions/columns/index.js.map +1 -0
- package/dist/extensions/columns/keys.js +53 -0
- package/dist/extensions/columns/keys.js.map +1 -0
- package/dist/extensions/columns/plugin.js +213 -0
- package/dist/extensions/columns/plugin.js.map +1 -0
- package/dist/extensions/columns/schema.js +58 -0
- package/dist/extensions/columns/schema.js.map +1 -0
- package/dist/extensions/columns/select-columns.js +6 -0
- package/dist/extensions/columns/select-columns.js.map +1 -0
- package/dist/extensions/columns/select-columns.vue_vue_type_script_setup_true_lang.js +71 -0
- package/dist/extensions/columns/select-columns.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/editor-kit.js +3 -1
- package/dist/extensions/editor-kit.js.map +1 -1
- package/dist/extensions/list-html.js +1 -1
- package/dist/extensions/list-html.js.map +1 -1
- package/dist/extensions/table/plugin.js +33 -1
- package/dist/extensions/table/plugin.js.map +1 -1
- package/dist/extensions/table/table-controls.js.map +1 -1
- package/dist/extensions/table/table-controls.vue_vue_type_script_setup_true_lang.js +1 -1
- package/dist/extensions/table/table-controls.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/extensions/table/view.js +25 -1
- package/dist/extensions/table/view.js.map +1 -1
- package/dist/flow/board-block.js +6 -0
- package/dist/flow/board-block.js.map +1 -0
- package/dist/flow/board-block.vue_vue_type_script_setup_true_lang.js +659 -0
- package/dist/flow/board-block.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/flow/board.js +221 -0
- package/dist/flow/board.js.map +1 -0
- package/dist/flow/index.js +173 -0
- package/dist/flow/index.js.map +1 -0
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/locale.js +78 -6
- package/dist/locale.js.map +1 -1
- package/dist/markdown/index.js +2 -2
- package/dist/markdown/index.js.map +1 -1
- package/dist/style.css +1 -1
- package/dist/style.js +2 -1
- package/dist/types/collaboration/binding.d.ts +12 -0
- package/dist/types/collaboration/cursors.d.ts +29 -1
- package/dist/types/collaboration/index.d.ts +53 -6
- package/dist/types/collaboration/inline-diff.d.ts +9 -0
- package/dist/types/collaboration/merged-props.d.ts +20 -0
- package/dist/types/collaboration/order.d.ts +5 -0
- package/dist/types/collaboration/table.d.ts +5 -1
- package/dist/types/collaboration/text.d.ts +20 -0
- package/dist/types/components/slash-choices.vue.d.ts +18 -0
- package/dist/types/core/blocks.d.ts +10 -0
- package/dist/types/core/commands.d.ts +17 -2
- package/dist/types/core/comments.d.ts +39 -3
- package/dist/types/core/convert.d.ts +10 -2
- package/dist/types/core/extension.d.ts +58 -4
- package/dist/types/core/model.d.ts +6 -1
- package/dist/types/core/plugins.d.ts +9 -0
- package/dist/types/core/prepare.d.ts +16 -2
- package/dist/types/core/schema.d.ts +1 -1
- package/dist/types/core/transaction.d.ts +6 -0
- package/dist/types/define-block.d.ts +16 -4
- package/dist/types/document.d.ts +5 -2
- package/dist/types/dom.d.ts +43 -4
- package/dist/types/editor.d.ts +9 -1
- package/dist/types/editor.vue.d.ts +24 -0
- package/dist/types/extensions/columns/column-picker.vue.d.ts +10 -0
- package/dist/types/extensions/columns/columns-controls.vue.d.ts +3 -0
- package/dist/types/extensions/columns/html.d.ts +10 -0
- package/dist/types/extensions/columns/index.d.ts +9 -0
- package/dist/types/extensions/columns/keys.d.ts +6 -0
- package/dist/types/extensions/columns/plugin.d.ts +28 -0
- package/dist/types/extensions/columns/schema.d.ts +17 -0
- package/dist/types/extensions/columns/select-columns.vue.d.ts +13 -0
- package/dist/types/extensions/editor-kit.d.ts +4 -1
- package/dist/types/extensions/table/view.d.ts +8 -1
- package/dist/types/flow/board-block.vue.d.ts +16 -0
- package/dist/types/flow/board.d.ts +53 -0
- package/dist/types/flow/index.d.ts +65 -0
- package/dist/types/index.d.ts +29 -4
- package/dist/types/locale.d.ts +34 -0
- package/dist/types/markdown/index.d.ts +8 -1
- package/dist/use-comments.js +2 -2
- package/dist/use-comments.js.map +1 -1
- package/package.json +14 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"table.js","names":[],"sources":["../../src/collaboration/table.ts"],"sourcesContent":["import type { Node as PMNode, NodeType, Schema } from 'prosemirror-model'\nimport * as Y from 'yjs'\nimport {\n createId,\n inlineOf,\n type BlockProps,\n type PartialTableRow,\n type RowsSpec,\n type TableGrid,\n} from '../core/model'\nimport { orderKeys } from './order'\nimport { inlineFrom, insertInline, updateText } from './text'\n\n/*\n * How a table is stored: rows, columns, cells and merged cells apart, so\n * that edits made at the same time merge instead of overwriting each other.\n *\n * rows: Y.Map<row id, Y.Map { order }>\n * columns: Y.Map<column id, Y.Map { order, width?, align? }>\n * cells: Y.Map<\"row id:column id\", Y.Text>\n * merges: Y.Map<merge id, { rows: string[], columns: string[] }>\n *\n * Moving a row only changes its order key, so text typed into its cells\n * meanwhile stays with it. A merged cell lists the rows and columns it\n * covered when it was made, and spans from the first to the last of them\n * that still exist in the current order: a row inserted inside it falls\n * inside, and deleting its edge row shrinks it. Merged cells that overlap\n * are settled by id, the same way on every client.\n */\n\ntype YEntry = Y.Map<unknown>\n\nconst PARTS = ['rows', 'columns', 'cells', 'merges'] as const\n\nconst cellKey = (row: string, column: string) => `${row}:${column}`\n\ninterface StoredMerge {\n rows: string[]\n columns: string[]\n}\n\ninterface Rect {\n id: string\n top: number\n left: number\n bottom: number\n right: number\n}\n\nconst rectKey = (rect: Omit<Rect, 'id'>) => `${rect.top},${rect.left},${rect.bottom},${rect.right}`\n\nfunction part<T>(yblock: YEntry, name: (typeof PARTS)[number]): Y.Map<T> {\n let map = yblock.get(name) as Y.Map<T> | undefined\n if (!map) {\n map = new Y.Map<T>()\n yblock.set(name, map)\n }\n return map\n}\n\n/** Ids by their order key; ties by id. */\nfunction ordered(map: Y.Map<YEntry> | undefined): string[] {\n if (!map) return []\n const orderOf = (id: string) => (map.get(id)!.get('order') as string | undefined) ?? ''\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n return Array.from(map.keys()).sort((a, b) => {\n const x = orderOf(a)\n const y = orderOf(b)\n return x < y ? -1 : x > y ? 1 : a < b ? -1 : a > b ? 1 : 0\n })\n}\n\n/** The first and past-the-last index of the ids that still exist. */\nfunction span(ids: unknown, index: Map<string, number>): [number, number] | null {\n let low = Infinity\n let high = -1\n for (const id of Array.isArray(ids) ? ids : []) {\n const at = index.get(id as string)\n if (at === undefined) continue\n low = Math.min(low, at)\n high = Math.max(high, at)\n }\n return high < 0 ? null : [low, high + 1]\n}\n\n/** Where the merged cells are in the current order; overlapping ones lose by id. */\nfunction mergeRects(merges: Y.Map<StoredMerge> | undefined, rows: string[], columns: string[]) {\n const rects: Rect[] = []\n if (!merges) return rects\n const rowIndex = new Map(rows.map((id, index) => [id, index]))\n const colIndex = new Map(columns.map((id, index) => [id, index]))\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n for (const id of Array.from(merges.keys()).sort()) {\n const merge = merges.get(id)!\n const vertical = span(merge.rows, rowIndex)\n const horizontal = span(merge.columns, colIndex)\n if (!vertical || !horizontal) continue\n const rect = {\n id,\n top: vertical[0]!,\n bottom: vertical[1]!,\n left: horizontal[0]!,\n right: horizontal[1]!,\n }\n if ((rect.bottom - rect.top) * (rect.right - rect.left) < 2) continue\n const overlaps = rects.some(\n (other) =>\n rect.top < other.bottom &&\n other.top < rect.bottom &&\n rect.left < other.right &&\n other.left < rect.right,\n )\n if (!overlaps) rects.push(rect)\n }\n return rects\n}\n\nconst textToInline = (text: Y.Text | undefined, schema: Schema) =>\n text?.length\n ? inlineOf(schema.nodes.paragraph!.create(null, inlineFrom(text, schema, false)))\n : []\n\n/** The table node a stored table stands for. */\nexport function readTable(yblock: YEntry, type: NodeType, props: BlockProps): PMNode {\n const spec = type.spec.rows as RowsSpec\n const rowsMap = yblock.get('rows') as Y.Map<YEntry> | undefined\n const colsMap = yblock.get('columns') as Y.Map<YEntry> | undefined\n const cells = yblock.get('cells') as Y.Map<Y.Text> | undefined\n const rowIds = ordered(rowsMap)\n const colIds = ordered(colsMap)\n if (!rowIds.length || !colIds.length) return spec.write(type, props, [])\n const columns = colIds.map((id) => {\n const { order: _order, ...fields } = colsMap!.get(id)!.toJSON()\n return { ...fields, id }\n })\n const spans = new Map<string, Rect>()\n for (const rect of mergeRects(yblock.get('merges') as Y.Map<StoredMerge>, rowIds, colIds))\n spans.set(`${rect.top},${rect.left}`, rect)\n const rows: PartialTableRow[] = rowIds.map((row, r) => ({\n id: row,\n cells: colIds.map((col, c) => {\n const rect = spans.get(`${r},${c}`)\n return {\n content: textToInline(cells?.get(cellKey(row, col)), type.schema),\n colspan: rect ? rect.right - rect.left : 1,\n rowspan: rect ? rect.bottom - rect.top : 1,\n }\n }),\n }))\n return spec.write(type, { ...props, columns }, rows)\n}\n\n/** Bring a list of ids (rows or columns) in the map to `ids`, in that order. */\nfunction writeOrder(map: Y.Map<YEntry>, before: string[], ids: string[]) {\n const kept = new Set(ids)\n for (const id of before) if (!kept.has(id)) map.delete(id)\n const keys = ids.map((id) => (map.get(id)?.get('order') as string | undefined) ?? null)\n const next = orderKeys(keys)\n ids.forEach((id, index) => {\n let entry = map.get(id)\n if (!entry) {\n entry = new Y.Map<unknown>()\n map.set(id, entry)\n }\n if (keys[index] !== next[index]) entry.set('order', next[index])\n })\n}\n\n/**\n * Write the table `after` into a stored table that holds `before` (`null`\n * for a new one). Returns whether cells that became visible hold text the\n * editor doesn't show yet, typed by someone else while they were merged away.\n */\nexport function writeTable(yblock: YEntry, before: PMNode | null, after: PMNode): boolean {\n const spec = after.type.spec.rows as RowsSpec\n const grid = spec.grid(after)\n const old: TableGrid | null = before ? spec.grid(before) : null\n\n let props = yblock.get('props') as Y.Map<unknown> | undefined\n if (!props) {\n props = new Y.Map<unknown>()\n yblock.set('props', props)\n }\n for (const [name, value] of Object.entries(grid.props))\n if (JSON.stringify(props.get(name)) !== JSON.stringify(value)) props.set(name, value)\n for (const name of Array.from(props.keys())) if (!(name in grid.props)) props.delete(name)\n\n const rowsMap = part<YEntry>(yblock, 'rows')\n const colsMap = part<YEntry>(yblock, 'columns')\n const cells = part<Y.Text>(yblock, 'cells')\n const merges = part<StoredMerge>(yblock, 'merges')\n const colIds = grid.columns.map((column) => column.id)\n const oldCols = old ? old.columns.map((column) => column.id) : []\n const oldRows = old?.rows ?? []\n\n writeOrder(rowsMap, oldRows, grid.rows)\n writeOrder(colsMap, oldCols, colIds)\n for (const column of grid.columns) {\n const entry = colsMap.get(column.id)!\n for (const [name, value] of Object.entries(column) as [string, unknown][]) {\n if (name === 'id') continue\n if (JSON.stringify(entry.get(name)) !== JSON.stringify(value)) entry.set(name, value)\n }\n for (const name of Array.from(entry.keys()))\n if (name !== 'order' && !(name in column)) entry.delete(name)\n }\n\n // the cells of deleted rows and columns go with them\n const allRows = new Set([...oldRows, ...rowsMap.keys()])\n const allCols = new Set([...oldCols, ...colsMap.keys()])\n for (const row of oldRows)\n if (!rowsMap.has(row)) for (const col of allCols) cells.delete(cellKey(row, col))\n for (const col of oldCols)\n if (!colsMap.has(col)) for (const row of allRows) cells.delete(cellKey(row, col))\n\n // merged cells: keep the stored ones still shown, add the new ones\n const stored = mergeRects(merges, grid.rows, colIds)\n const shown = new Set(stored.map(rectKey))\n const wanted = new Set<string>()\n const created: string[] = []\n for (const cell of grid.cells) {\n if (cell.rowspan * cell.colspan < 2) continue\n const rect = {\n top: cell.row,\n left: cell.col,\n bottom: cell.row + cell.rowspan,\n right: cell.col + cell.colspan,\n }\n const key = rectKey(rect)\n wanted.add(key)\n if (shown.has(key)) continue\n const id = createId()\n created.push(id)\n merges.set(id, {\n rows: grid.rows.slice(rect.top, rect.bottom),\n columns: colIds.slice(rect.left, rect.right),\n })\n // merging moved the covered cells' text into this one\n for (let r = rect.top; r < rect.bottom; r++) {\n for (let c = rect.left; c < rect.right; c++) {\n if (r === rect.top && c === rect.left) continue\n const text = cells.get(cellKey(grid.rows[r]!, colIds[c]!))\n if (text?.length) text.delete(0, text.length)\n }\n }\n }\n const kept = new Set(created)\n for (const rect of stored) if (wanted.has(rectKey(rect))) kept.add(rect.id)\n for (const id of Array.from(merges.keys())) if (!kept.has(id)) merges.delete(id)\n\n // cell text\n const oldCells = new Map<string, PMNode>()\n for (const cell of old?.cells ?? [])\n oldCells.set(cellKey(old!.rows[cell.row]!, oldCols[cell.col]!), cell.node)\n let revealed = false\n for (const cell of grid.cells) {\n const key = cellKey(grid.rows[cell.row]!, colIds[cell.col]!)\n const node = cell.node\n let text = cells.get(key)\n if (!text) {\n text = new Y.Text()\n cells.set(key, text)\n insertInline(text, 0, node, 0, node.content.size)\n continue\n }\n const previous = oldCells.get(key)\n if (previous) {\n if (previous !== node && !previous.content.eq(node.content)) updateText(text, previous, node)\n } else if (node.content.size) {\n // shown again or reused: the editor's content wins\n text.delete(0, text.length)\n insertInline(text, 0, node, 0, node.content.size)\n } else if (text.length) {\n revealed = true\n }\n }\n return revealed\n}\n\n/** Forget a stored table's rows, e.g. when the block stops being a table. */\nexport function clearTable(yblock: YEntry) {\n for (const name of PARTS) if (yblock.has(name)) yblock.delete(name)\n}\n\n/** The cell a position in a table falls in, and the offset in its text. */\nexport function cellAt(table: PMNode, offset: number): { key: string; index: number } | null {\n const grid = (table.type.spec.rows as RowsSpec).grid(table)\n for (const cell of grid.cells) {\n if (offset > cell.offset && offset < cell.offset + cell.node.nodeSize) {\n const column = grid.columns[cell.col]!.id\n return { key: cellKey(grid.rows[cell.row]!, column), index: offset - cell.offset - 1 }\n }\n }\n return null\n}\n\n/** Where a cell's text starts in a table, by its key; `null` when it isn't shown. */\nexport function cellStart(table: PMNode, key: string): { offset: number; size: number } | null {\n const grid = (table.type.spec.rows as RowsSpec).grid(table)\n for (const cell of grid.cells) {\n if (cellKey(grid.rows[cell.row]!, grid.columns[cell.col]!.id) === key)\n return { offset: cell.offset + 1, size: cell.node.content.size }\n }\n return null\n}\n"],"mappings":";;;;;AAgCA,IAAM,QAAQ;CAAC;CAAQ;CAAW;CAAS;AAAQ;AAEnD,IAAM,WAAW,KAAa,WAAmB,GAAG,IAAI,GAAG;AAe3D,IAAM,WAAW,SAA2B,GAAG,KAAK,IAAI,GAAG,KAAK,KAAK,GAAG,KAAK,OAAO,GAAG,KAAK;AAE5F,SAAS,KAAQ,QAAgB,MAAwC;CACvE,IAAI,MAAM,OAAO,IAAI,IAAI;CACzB,IAAI,CAAC,KAAK;EACR,MAAM,IAAI,EAAE,IAAO;EACnB,OAAO,IAAI,MAAM,GAAG;CACtB;CACA,OAAO;AACT;;AAGA,SAAS,QAAQ,KAA0C;CACzD,IAAI,CAAC,KAAK,OAAO,CAAC;CAClB,MAAM,WAAW,OAAgB,IAAI,IAAI,EAAE,CAAC,CAAE,IAAI,OAAO,KAA4B;CAErF,OAAO,MAAM,KAAK,IAAI,KAAK,CAAC,CAAC,CAAC,MAAM,GAAG,MAAM;EAC3C,MAAM,IAAI,QAAQ,CAAC;EACnB,MAAM,IAAI,QAAQ,CAAC;EACnB,OAAO,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI;CAC3D,CAAC;AACH;;AAGA,SAAS,KAAK,KAAc,OAAqD;CAC/E,IAAI,MAAM;CACV,IAAI,OAAO;CACX,KAAK,MAAM,MAAM,MAAM,QAAQ,GAAG,IAAI,MAAM,CAAC,GAAG;EAC9C,MAAM,KAAK,MAAM,IAAI,EAAY;EACjC,IAAI,OAAO,KAAA,GAAW;EACtB,MAA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import type { Node as PMNode, NodeType, Schema } from 'prosemirror-model'\nimport * as Y from 'yjs'\nimport {\n createId,\n inlineOf,\n type BlockProps,\n type PartialTableRow,\n type RowsSpec,\n type TableGrid,\n} from '../core/model'\nimport { changedOrderKeys } from './order'\nimport type { DiffBudget } from './inline-diff'\nimport {\n inlineFrom,\n insertInline,\n prepareTextFromBase,\n updateText,\n type TextUpdatePlan,\n} from './text'\n\n/*\n * How a table is stored: rows, columns, cells and merged cells apart, so\n * that edits made at the same time merge instead of overwriting each other.\n *\n * rows: Y.Map<row id, Y.Map { order }>\n * columns: Y.Map<column id, Y.Map { order, width?, align? }>\n * cells: Y.Map<\"row id:column id\", Y.Text>\n * merges: Y.Map<merge id, { rows: string[], columns: string[] }>\n *\n * Moving a row only changes its order key, so text typed into its cells\n * meanwhile stays with it. A merged cell lists the rows and columns it\n * covered when it was made, and spans from the first to the last of them\n * that still exist in the current order: a row inserted inside it falls\n * inside, and deleting its edge row shrinks it. Merged cells that overlap\n * are settled by id, the same way on every client.\n */\n\ntype YEntry = Y.Map<unknown>\n\nconst PARTS = ['rows', 'columns', 'cells', 'merges'] as const\n\nconst cellKey = (row: string, column: string) => `${row}:${column}`\n\ninterface StoredMerge {\n rows: string[]\n columns: string[]\n}\n\nconst mergeKey = (merge: StoredMerge, rows?: Set<string>, columns?: Set<string>) =>\n JSON.stringify([\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh filtered list\n merge.rows.filter((id) => !rows || rows.has(id)).sort(),\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh filtered list\n merge.columns.filter((id) => !columns || columns.has(id)).sort(),\n ])\n\ninterface Rect {\n id: string\n top: number\n left: number\n bottom: number\n right: number\n}\n\nconst rectKey = (rect: Omit<Rect, 'id'>) => `${rect.top},${rect.left},${rect.bottom},${rect.right}`\n\nfunction part<T>(yblock: YEntry, name: (typeof PARTS)[number]): Y.Map<T> {\n let map = yblock.get(name) as Y.Map<T> | undefined\n if (!map) {\n map = new Y.Map<T>()\n yblock.set(name, map)\n }\n return map\n}\n\n/** Ids by their order key; ties by id. */\nfunction ordered(map: Y.Map<YEntry> | undefined): string[] {\n if (!map) return []\n const orderOf = (id: string) => (map.get(id)!.get('order') as string | undefined) ?? ''\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n return Array.from(map.keys()).sort((a, b) => {\n const x = orderOf(a)\n const y = orderOf(b)\n return x < y ? -1 : x > y ? 1 : a < b ? -1 : a > b ? 1 : 0\n })\n}\n\n/** The first and past-the-last index of the ids that still exist. */\nfunction span(ids: unknown, index: Map<string, number>): [number, number] | null {\n let low = Infinity\n let high = -1\n for (const id of Array.isArray(ids) ? ids : []) {\n const at = index.get(id as string)\n if (at === undefined) continue\n low = Math.min(low, at)\n high = Math.max(high, at)\n }\n return high < 0 ? null : [low, high + 1]\n}\n\n/** Where the merged cells are in the current order; overlapping ones lose by id. */\nfunction mergeRects(merges: Y.Map<StoredMerge> | undefined, rows: string[], columns: string[]) {\n const rects: Rect[] = []\n if (!merges) return rects\n const rowIndex = new Map(rows.map((id, index) => [id, index]))\n const colIndex = new Map(columns.map((id, index) => [id, index]))\n // oxlint-disable-next-line unicorn/no-array-sort -- sorts a fresh array\n for (const id of Array.from(merges.keys()).sort()) {\n const merge = merges.get(id)!\n const vertical = span(merge.rows, rowIndex)\n const horizontal = span(merge.columns, colIndex)\n if (!vertical || !horizontal) continue\n const rect = {\n id,\n top: vertical[0]!,\n bottom: vertical[1]!,\n left: horizontal[0]!,\n right: horizontal[1]!,\n }\n if ((rect.bottom - rect.top) * (rect.right - rect.left) < 2) continue\n const overlaps = rects.some(\n (other) =>\n rect.top < other.bottom &&\n other.top < rect.bottom &&\n rect.left < other.right &&\n other.left < rect.right,\n )\n if (!overlaps) rects.push(rect)\n }\n return rects\n}\n\nconst textToInline = (text: Y.Text | undefined, schema: Schema) =>\n text?.length\n ? inlineOf(schema.nodes.paragraph!.create(null, inlineFrom(text, schema, false)))\n : []\n\n/** The table node a stored table stands for. */\nexport function readTable(yblock: YEntry, type: NodeType, props: BlockProps): PMNode {\n const spec = type.spec.rows as RowsSpec\n const rowsMap = yblock.get('rows') as Y.Map<YEntry> | undefined\n const colsMap = yblock.get('columns') as Y.Map<YEntry> | undefined\n const cells = yblock.get('cells') as Y.Map<Y.Text> | undefined\n const rowIds = ordered(rowsMap)\n const colIds = ordered(colsMap)\n if (!rowIds.length || !colIds.length) return spec.write(type, props, [])\n const columns = colIds.map((id) => {\n const { order: _order, ...fields } = colsMap!.get(id)!.toJSON()\n return { ...fields, id }\n })\n const spans = new Map<string, Rect>()\n for (const rect of mergeRects(yblock.get('merges') as Y.Map<StoredMerge>, rowIds, colIds))\n spans.set(`${rect.top},${rect.left}`, rect)\n const rows: PartialTableRow[] = rowIds.map((row, r) => ({\n id: row,\n cells: colIds.map((col, c) => {\n const rect = spans.get(`${r},${c}`)\n return {\n content: textToInline(cells?.get(cellKey(row, col)), type.schema),\n colspan: rect ? rect.right - rect.left : 1,\n rowspan: rect ? rect.bottom - rect.top : 1,\n }\n }),\n }))\n return spec.write(type, { ...props, columns }, rows)\n}\n\n/** Bring a list of ids (rows or columns) in the map to `ids`, in that order. */\nfunction writeOrder(map: Y.Map<YEntry>, before: string[], ids: string[]) {\n const kept = new Set(ids)\n for (const id of before) if (!kept.has(id)) map.delete(id)\n const old = new Set(before)\n const live = ids.filter((id) => map.has(id) || !old.has(id))\n for (const id of live) if (!map.has(id)) map.set(id, new Y.Map<unknown>())\n const current = new Map(\n [...map].map(([id, fields]) => [id, (fields.get('order') as string | undefined) ?? null]),\n )\n const keys = changedOrderKeys(before, live, current)\n for (const [id, key] of keys) map.get(id)!.set('order', key)\n}\n\n/** Build all cell writes without changing the map, including any diff failures. */\nexport function prepareTableText(\n yblock: YEntry,\n before: PMNode | null,\n after: PMNode,\n plans: Map<Y.Text, TextUpdatePlan>,\n budget?: DiffBudget,\n) {\n if (!before) return\n const spec = after.type.spec.rows as RowsSpec\n const old = spec.grid(before)\n const grid = spec.grid(after)\n const previous = new Map(\n old.cells.map((cell) => [cellKey(old.rows[cell.row]!, old.columns[cell.col]!.id), cell.node]),\n )\n const cells = yblock.get('cells') as Y.Map<Y.Text> | undefined\n for (const cell of grid.cells) {\n const key = cellKey(grid.rows[cell.row]!, grid.columns[cell.col]!.id)\n const base = previous.get(key)\n const text = cells?.get(key)\n if (!base || !text || base.content.eq(cell.node.content)) continue\n const current = cell.node.type.create(null, inlineFrom(text, cell.node.type.schema, false))\n plans.set(text, prepareTextFromBase(base, cell.node, current, budget))\n }\n}\n\n/**\n * Write the table `after` into a stored table that holds `before` (`null`\n * for a new one). Returns whether cells that became visible hold text the\n * editor doesn't show yet, typed by someone else while they were merged away.\n */\nexport function writeTable(\n yblock: YEntry,\n before: PMNode | null,\n after: PMNode,\n plans?: Map<Y.Text, TextUpdatePlan>,\n): boolean {\n const spec = after.type.spec.rows as RowsSpec\n const grid = spec.grid(after)\n const old: TableGrid | null = before ? spec.grid(before) : null\n\n let props = yblock.get('props') as Y.Map<unknown> | undefined\n if (!props) {\n props = new Y.Map<unknown>()\n yblock.set('props', props)\n }\n for (const [name, value] of Object.entries(grid.props))\n if (!old || JSON.stringify(old.props[name]) !== JSON.stringify(value)) props.set(name, value)\n for (const name of Array.from(props.keys()))\n if (!(name in grid.props) && (!old || name in old.props)) props.delete(name)\n\n const rowsMap = part<YEntry>(yblock, 'rows')\n const colsMap = part<YEntry>(yblock, 'columns')\n const cells = part<Y.Text>(yblock, 'cells')\n const merges = part<StoredMerge>(yblock, 'merges')\n const colIds = grid.columns.map((column) => column.id)\n const oldCols = old ? old.columns.map((column) => column.id) : []\n const oldRows = old?.rows ?? []\n\n writeOrder(rowsMap, oldRows, grid.rows)\n writeOrder(colsMap, oldCols, colIds)\n const oldColumns = new Map(old?.columns.map((column) => [column.id, column]))\n for (const column of grid.columns) {\n const entry = colsMap.get(column.id)\n if (!entry) continue\n const previous = oldColumns.get(column.id)\n for (const [name, value] of Object.entries(column) as [string, unknown][]) {\n if (name === 'id') continue\n if (\n !previous ||\n JSON.stringify((previous as Record<string, unknown>)[name]) !== JSON.stringify(value)\n )\n entry.set(name, value)\n }\n for (const name of Array.from(entry.keys()))\n if (name !== 'order' && !(name in column) && (!previous || name in previous))\n entry.delete(name)\n }\n\n // the cells of deleted rows and columns go with them\n const allRows = new Set([...oldRows, ...rowsMap.keys()])\n const allCols = new Set([...oldCols, ...colsMap.keys()])\n for (const row of oldRows)\n if (!rowsMap.has(row)) for (const col of allCols) cells.delete(cellKey(row, col))\n for (const col of oldCols)\n if (!colsMap.has(col)) for (const row of allRows) cells.delete(cellKey(row, col))\n\n // merged cells: keep the stored ones still shown, add the new ones\n const stored = mergeRects(merges, grid.rows, colIds)\n const shown = new Set(stored.map(rectKey))\n const baseMerges = new Set<string>()\n for (const cell of old?.cells ?? []) {\n if (cell.rowspan * cell.colspan < 2) continue\n baseMerges.add(\n mergeKey({\n rows: old!.rows.slice(cell.row, cell.row + cell.rowspan),\n columns: oldCols.slice(cell.col, cell.col + cell.colspan),\n }),\n )\n }\n const wantedMerges = new Set<string>()\n const wanted = new Set<string>()\n const created: string[] = []\n for (const cell of grid.cells) {\n if (cell.rowspan * cell.colspan < 2) continue\n const rect = {\n top: cell.row,\n left: cell.col,\n bottom: cell.row + cell.rowspan,\n right: cell.col + cell.colspan,\n }\n const key = rectKey(rect)\n const value = {\n rows: grid.rows.slice(rect.top, rect.bottom),\n columns: colIds.slice(rect.left, rect.right),\n }\n const stable = mergeKey(value)\n wantedMerges.add(stable)\n wanted.add(key)\n if (baseMerges.has(stable) || shown.has(key)) continue\n const id = createId()\n created.push(id)\n merges.set(id, value)\n // merging moved the covered cells' text into this one\n for (let r = rect.top; r < rect.bottom; r++) {\n for (let c = rect.left; c < rect.right; c++) {\n if (r === rect.top && c === rect.left) continue\n const text = cells.get(cellKey(grid.rows[r]!, colIds[c]!))\n if (text?.length) text.delete(0, text.length)\n }\n }\n }\n const kept = new Set(created)\n for (const rect of stored) if (wanted.has(rectKey(rect))) kept.add(rect.id)\n const baseRows = new Set(old?.rows ?? [])\n const baseColumns = new Set(oldCols)\n for (const [id, merge] of merges) {\n const stable = mergeKey(merge, baseRows, baseColumns)\n if (!kept.has(id) && baseMerges.has(stable) && !wantedMerges.has(stable)) merges.delete(id)\n }\n\n // cell text\n const oldCells = new Map<string, PMNode>()\n for (const cell of old?.cells ?? [])\n oldCells.set(cellKey(old!.rows[cell.row]!, oldCols[cell.col]!), cell.node)\n let revealed = false\n for (const cell of grid.cells) {\n if (!rowsMap.has(grid.rows[cell.row]!) || !colsMap.has(colIds[cell.col]!)) continue\n const key = cellKey(grid.rows[cell.row]!, colIds[cell.col]!)\n const node = cell.node\n let text = cells.get(key)\n if (!text) {\n text = new Y.Text()\n cells.set(key, text)\n insertInline(text, 0, node, 0, node.content.size)\n continue\n }\n const previous = oldCells.get(key)\n if (previous) {\n if (previous !== node && !previous.content.eq(node.content)) {\n const plan = plans?.get(text)\n if (plan) plan(text)\n else updateText(text, previous, node)\n }\n } else if (node.content.size) {\n // shown again or reused: the editor's content wins\n text.delete(0, text.length)\n insertInline(text, 0, node, 0, node.content.size)\n } else if (text.length) {\n revealed = true\n }\n }\n return revealed\n}\n\n/** Forget a stored table's rows, e.g. when the block stops being a table. */\nexport function clearTable(yblock: YEntry) {\n for (const name of PARTS) if (yblock.has(name)) yblock.delete(name)\n}\n\n/** The cell a position in a table falls in, and the offset in its text. */\nexport function cellAt(table: PMNode, offset: number): { key: string; index: number } | null {\n const grid = (table.type.spec.rows as RowsSpec).grid(table)\n for (const cell of grid.cells) {\n if (offset > cell.offset && offset < cell.offset + cell.node.nodeSize) {\n const column = grid.columns[cell.col]!.id\n return { key: cellKey(grid.rows[cell.row]!, column), index: offset - cell.offset - 1 }\n }\n }\n return null\n}\n\n/** Where a cell's text starts in a table, by its key; `null` when it isn't shown. */\nexport function cellStart(table: PMNode, key: string): { offset: number; size: number } | null {\n const grid = (table.type.spec.rows as RowsSpec).grid(table)\n for (const cell of grid.c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AAGA,SAAgB,WAAW,QAAgB;CACzC,KAAK,MAAM,QAAQ,OAAO,IAAI,OAAO,IAAI,IAAI,GAAG,OAAO,OAAO,IAAI;AACpE;;AAGA,SAAgB,OAAO,OAAe,QAAuD;CAC3F,MAAM,OAAQ,MAAM,KAAK,KAAK,KAAkB,KAAK,KAAK;CAC1D,KAAK,MAAM,QAAQ,KAAK,OACtB,IAAI,SAAS,KAAK,UAAU,SAAS,KAAK,SAAS,KAAK,KAAK,UAAU;EACrE,MAAM,SAAS,KAAK,QAAQ,KAAK,IAAI,CAAE;EACvC,OAAO;GAAE,KAAK,QAAQ,KAAK,KAAK,KAAK,MAAO,MAAM;GAAG,OAAO,SAAS,KAAK,SAAS;EAAE;CACvF;CAEF,OAAO;AACT;;AAGA,SAAgB,UAAU,OAAe,KAAsD;CAC7F,MAAM,OAAQ,MAAM,KAAK,KAAK,KAAkB,KAAK,KAAK;CAC1D,KAAK,MAAM,QAAQ,KAAK,OACtB,IAAI,QAAQ,KAAK,KAAK,KAAK,MAAO,KAAK,QAAQ,KAAK,IAAI,CAAE,EAAE,MAAM,KAChE,OAAO;EAAE,QAAQ,KAAK,SAAS;EAAG,MAAM,KAAK,KAAK,QAAQ;CAAK;CAEnE,OAAO;AACT"}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { diffLists } from "./inline-diff.js";
|
|
1
2
|
import { Mark } from "prosemirror-model";
|
|
3
|
+
import { Mapping, StepMap, Transform } from "prosemirror-transform";
|
|
2
4
|
// src/collaboration/text.ts
|
|
3
5
|
var COMMENT = "comment";
|
|
4
6
|
var COMMENT_PREFIX = "comment:";
|
|
@@ -86,6 +88,216 @@ function updateText(text, before, after) {
|
|
|
86
88
|
if (end.a > start) text.delete(start, end.a - start);
|
|
87
89
|
if (end.b > start) insertInline(text, start, after, start, end.b);
|
|
88
90
|
}
|
|
89
|
-
|
|
91
|
+
/** Inline characters and embeds, with offsets matching ProseMirror and Y.Text. */
|
|
92
|
+
function units(node) {
|
|
93
|
+
const values = [];
|
|
94
|
+
const offsets = [];
|
|
95
|
+
node.forEach((child, at) => {
|
|
96
|
+
if (child.isText) {
|
|
97
|
+
let offset = at;
|
|
98
|
+
for (const character of child.text) {
|
|
99
|
+
offsets.push(offset);
|
|
100
|
+
values.push("t:" + character);
|
|
101
|
+
offset += character.length;
|
|
102
|
+
}
|
|
103
|
+
} else {
|
|
104
|
+
offsets.push(at);
|
|
105
|
+
values.push("n:" + JSON.stringify([child.type.name, child.attrs]));
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
offsets.push(node.content.size);
|
|
109
|
+
return {
|
|
110
|
+
values,
|
|
111
|
+
offsets
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** Exact content changes, at UTF-16 offsets, never inside a surrogate pair. */
|
|
115
|
+
function inlineChanges(before, after, budget) {
|
|
116
|
+
const a = units(before);
|
|
117
|
+
const b = units(after);
|
|
118
|
+
return diffLists(a.values, b.values, budget).map(([from, to, start, end]) => [
|
|
119
|
+
a.offsets[from],
|
|
120
|
+
a.offsets[to],
|
|
121
|
+
b.offsets[start],
|
|
122
|
+
b.offsets[end]
|
|
123
|
+
]);
|
|
124
|
+
}
|
|
125
|
+
var markKey = (mark) => mark.type.name === COMMENT ? COMMENT_PREFIX + mark.attrs.id : mark.type.name;
|
|
126
|
+
var markRuns = (node) => {
|
|
127
|
+
const result = [];
|
|
128
|
+
node.forEach((child, at) => result.push({
|
|
129
|
+
end: at + child.nodeSize,
|
|
130
|
+
marks: child.marks
|
|
131
|
+
}));
|
|
132
|
+
return result;
|
|
133
|
+
};
|
|
134
|
+
var mappingOf = (changes) => {
|
|
135
|
+
const mapping = new Mapping();
|
|
136
|
+
let shift = 0;
|
|
137
|
+
for (const [from, to, start, end] of changes) {
|
|
138
|
+
mapping.appendMap(new StepMap([
|
|
139
|
+
from + shift,
|
|
140
|
+
to - from,
|
|
141
|
+
end - start
|
|
142
|
+
]));
|
|
143
|
+
shift += end - start - (to - from);
|
|
144
|
+
}
|
|
145
|
+
return mapping;
|
|
146
|
+
};
|
|
147
|
+
/**
|
|
148
|
+
* Apply base → written edits to the current inline content. Offsets are
|
|
149
|
+
* mapped through the room's edits first; overlapping replacements use
|
|
150
|
+
* written content, while edits elsewhere and their marks remain intact.
|
|
151
|
+
*/
|
|
152
|
+
function prepareTextFromBase(base, written, current, budget) {
|
|
153
|
+
written = keepInlineComments(base, written, budget);
|
|
154
|
+
const writes = [];
|
|
155
|
+
if (base.content.eq(written.content)) return () => {};
|
|
156
|
+
const remote = base.content.eq(current.content) ? [] : inlineChanges(base, current, budget);
|
|
157
|
+
const own = inlineChanges(base, written, budget);
|
|
158
|
+
const roomMap = mappingOf(remote);
|
|
159
|
+
const writtenMap = mappingOf(own);
|
|
160
|
+
const ranges = [];
|
|
161
|
+
let remoteAt = 0;
|
|
162
|
+
for (const [start, end] of own) {
|
|
163
|
+
let from = start;
|
|
164
|
+
let to = end;
|
|
165
|
+
while (remoteAt < remote.length && remote[remoteAt][1] <= from) remoteAt++;
|
|
166
|
+
for (let i = remoteAt; i < remote.length; i++) {
|
|
167
|
+
const [left, right] = remote[i];
|
|
168
|
+
if (left >= to) break;
|
|
169
|
+
if (left < to && right > from) {
|
|
170
|
+
from = Math.min(from, left);
|
|
171
|
+
to = Math.max(to, right);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
const last = ranges[ranges.length - 1];
|
|
175
|
+
if (last && from <= last.to) last.to = Math.max(last.to, to);
|
|
176
|
+
else ranges.push({
|
|
177
|
+
from,
|
|
178
|
+
to
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
const tr = new Transform(current);
|
|
182
|
+
for (let i = ranges.length - 1; i >= 0; i--) {
|
|
183
|
+
const { from, to } = ranges[i];
|
|
184
|
+
const start = roomMap.map(from, 1);
|
|
185
|
+
const end = Math.max(start, roomMap.map(to, -1));
|
|
186
|
+
const writtenStart = writtenMap.map(from, -1);
|
|
187
|
+
const writtenEnd = writtenMap.map(to, 1);
|
|
188
|
+
tr.replaceWith(start, end, written.content.cut(writtenStart, writtenEnd));
|
|
189
|
+
writes.push((text) => {
|
|
190
|
+
if (end > start) text.delete(start, end - start);
|
|
191
|
+
if (writtenEnd > writtenStart) insertInline(text, start, written, writtenStart, writtenEnd);
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
let formatted = false;
|
|
195
|
+
base.forEach((node) => {
|
|
196
|
+
formatted ||= node.marks.length > 0;
|
|
197
|
+
});
|
|
198
|
+
written.forEach((node) => {
|
|
199
|
+
formatted ||= node.marks.length > 0;
|
|
200
|
+
});
|
|
201
|
+
if (!formatted) return (text) => {
|
|
202
|
+
for (const write of writes) write(text);
|
|
203
|
+
};
|
|
204
|
+
let run = null;
|
|
205
|
+
const flush = () => {
|
|
206
|
+
if (!run) return;
|
|
207
|
+
const attributes = {};
|
|
208
|
+
for (const mark of run.remove) attributes[markKey(mark)] = null;
|
|
209
|
+
for (const mark of run.add) attributes[markKey(mark)] = mark.type.name === COMMENT || !Object.keys(mark.attrs).length ? true : { ...mark.attrs };
|
|
210
|
+
const { from, to } = run;
|
|
211
|
+
writes.push((text) => text.format(from, to - from, attributes));
|
|
212
|
+
run = null;
|
|
213
|
+
};
|
|
214
|
+
const baseRuns = markRuns(base);
|
|
215
|
+
const writtenRuns = markRuns(written);
|
|
216
|
+
let baseRun = 0;
|
|
217
|
+
let writtenRun = 0;
|
|
218
|
+
let changed = 0;
|
|
219
|
+
for (let i = 0; i < base.content.size; i++) {
|
|
220
|
+
while (changed < own.length && own[changed][1] <= i) changed++;
|
|
221
|
+
if (changed < own.length && own[changed][0] <= i && i < own[changed][1]) continue;
|
|
222
|
+
const j = writtenMap.map(i, 1);
|
|
223
|
+
while (baseRuns[baseRun] && baseRuns[baseRun].end <= i) baseRun++;
|
|
224
|
+
while (writtenRuns[writtenRun] && writtenRuns[writtenRun].end <= j) writtenRun++;
|
|
225
|
+
const was = baseRuns[baseRun]?.marks ?? [];
|
|
226
|
+
const next = writtenRuns[writtenRun]?.marks ?? [];
|
|
227
|
+
const old = new Map(was.map((mark) => [markKey(mark), mark]));
|
|
228
|
+
const fresh = new Map(next.map((mark) => [markKey(mark), mark]));
|
|
229
|
+
const remove = was.filter((mark) => !fresh.get(markKey(mark))?.eq(mark));
|
|
230
|
+
const add = next.filter((mark) => !old.get(markKey(mark))?.eq(mark));
|
|
231
|
+
if (!remove.length && !add.length) continue;
|
|
232
|
+
const from = tr.mapping.map(roomMap.map(i, 1), 1);
|
|
233
|
+
const to = tr.mapping.map(roomMap.map(i + 1, -1), -1);
|
|
234
|
+
if (to <= from) continue;
|
|
235
|
+
const key = JSON.stringify([remove.map((mark) => mark.toJSON()), add.map((mark) => mark.toJSON())]);
|
|
236
|
+
if (run && run.to === from && run.key === key) run.to = to;
|
|
237
|
+
else {
|
|
238
|
+
flush();
|
|
239
|
+
run = {
|
|
240
|
+
from,
|
|
241
|
+
to,
|
|
242
|
+
remove,
|
|
243
|
+
add,
|
|
244
|
+
key
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
flush();
|
|
249
|
+
return (text) => {
|
|
250
|
+
for (const write of writes) write(text);
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* `after` with the comment marks of `before` on all unchanged inline
|
|
255
|
+
* fragments, when `after` has none: a version read from Markdown, which
|
|
256
|
+
* doesn't carry them, leaves the threads where the text stays the same.
|
|
257
|
+
*/
|
|
258
|
+
function keepInlineComments(before, after, budget) {
|
|
259
|
+
const type = after.type.schema.marks.comment;
|
|
260
|
+
if (!type || !after.inlineContent || !before.inlineContent || before.type !== after.type) return after;
|
|
261
|
+
let theirs = false;
|
|
262
|
+
after.descendants((node) => {
|
|
263
|
+
if (type.isInSet(node.marks)) theirs = true;
|
|
264
|
+
});
|
|
265
|
+
if (theirs) return after;
|
|
266
|
+
const ranges = [];
|
|
267
|
+
before.forEach((child, pos) => {
|
|
268
|
+
for (const mark of child.marks) if (mark.type === type) ranges.push({
|
|
269
|
+
from: pos,
|
|
270
|
+
to: pos + child.nodeSize,
|
|
271
|
+
mark
|
|
272
|
+
});
|
|
273
|
+
});
|
|
274
|
+
if (!ranges.length) return after;
|
|
275
|
+
const changes = inlineChanges(before, after, budget);
|
|
276
|
+
const same = [];
|
|
277
|
+
let left = 0;
|
|
278
|
+
let right = 0;
|
|
279
|
+
for (const [from, to, , end] of changes) {
|
|
280
|
+
if (from > left) same.push({
|
|
281
|
+
from: left,
|
|
282
|
+
to: from,
|
|
283
|
+
shift: right - left
|
|
284
|
+
});
|
|
285
|
+
left = to;
|
|
286
|
+
right = end;
|
|
287
|
+
}
|
|
288
|
+
if (left < before.content.size) same.push({
|
|
289
|
+
from: left,
|
|
290
|
+
to: before.content.size,
|
|
291
|
+
shift: right - left
|
|
292
|
+
});
|
|
293
|
+
const tr = new Transform(after);
|
|
294
|
+
for (const { from, to, mark } of ranges) for (const fragment of same) {
|
|
295
|
+
const start = Math.max(from, fragment.from);
|
|
296
|
+
const end = Math.min(to, fragment.to);
|
|
297
|
+
if (end > start) tr.addMark(start + fragment.shift, end + fragment.shift, mark);
|
|
298
|
+
}
|
|
299
|
+
return tr.doc;
|
|
300
|
+
}
|
|
301
|
+
export { inlineChanges, inlineFrom, insertInline, keepInlineComments, markAttributes, prepareTextFromBase, updateText };
|
|
90
302
|
|
|
91
303
|
//# sourceMappingURL=text.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"text.js","names":[],"sources":["../../src/collaboration/text.ts"],"sourcesContent":["import { Mark, type Node as PMNode, type Schema } from 'prosemirror-model'\nimport type * as Y from 'yjs'\n\n/* inline content ↔ Y.Text */\n\nexport type Attributes = Record<string, unknown>\n\n/*\n * A text can be in several comment threads at once, each added and\n * removed on its own, also by two people at the same time: every thread\n * is its own attribute, `comment:<thread id>`.\n */\nconst COMMENT = 'comment'\nconst COMMENT_PREFIX = 'comment:'\n\nexport function markAttributes(marks: readonly Mark[], schema: Schema): Attributes {\n // every mark is named, so `insert` doesn't inherit formatting from the left\n // (comment attributes the text doesn't have are cleared by `insert` itself)\n const attributes: Attributes = {}\n for (const name of Object.keys(schema.marks)) if (name !== COMMENT) attributes[name] = null\n for (const mark of marks) {\n if (mark.type.name === COMMENT) attributes[COMMENT_PREFIX + mark.attrs.id] = true\n else attributes[mark.type.name] = Object.keys(mark.attrs).length ? { ...mark.attrs } : true\n }\n return attributes\n}\n\n/** The comment attributes of the inline content from `from` to `to`. */\nfunction commentAttributes(node: PMNode, from: number, to: number): Set<string> {\n const keys = new Set<string>()\n node.nodesBetween(from, to, (child) => {\n for (const mark of child.marks)\n if (mark.type.name === COMMENT) keys.add(COMMENT_PREFIX + mark.attrs.id)\n })\n return keys\n}\n\ninterface Embed {\n node: string\n attrs?: Attributes\n}\n\n/** Write `content`'s inline nodes from `from` to `to` into `text` at `at`. */\nexport function insertInline(text: Y.Text, at: number, content: PMNode, from: number, to: number) {\n const schema = content.type.schema\n let offset = at\n content.forEach((child, pos) => {\n const start = Math.max(pos, from)\n const end = Math.min(pos + child.nodeSize, to)\n if (start >= end) return\n if (child.isText) {\n const piece = child.text!.slice(start - pos, end - pos)\n text.insert(offset, piece, markAttributes(child.marks, schema))\n offset += piece.length\n } else {\n const embed: Embed = { node: child.type.name }\n if (Object.keys(child.attrs).length) embed.attrs = { ...child.attrs }\n text.insertEmbed(offset, embed, markAttributes(child.marks, schema))\n offset += 1\n }\n })\n}\n\nfunction marksFrom(attributes: Attributes | undefined, schema: Schema): Mark[] {\n const marks: Mark[] = []\n for (const [name, value] of Object.entries(attributes ?? {})) {\n if (name.startsWith(COMMENT_PREFIX)) {\n if (value === true && schema.marks[COMMENT])\n marks.push(schema.marks[COMMENT].create({ id: name.slice(COMMENT_PREFIX.length) }))\n continue\n }\n const type = schema.marks[name]\n if (!type || value === null || value === undefined) continue\n marks.push(type.create(value === true ? null : (value as Attributes)))\n }\n return Mark.setFrom(marks) as Mark[]\n}\n\nexport function inlineFrom(text: Y.Text, schema: Schema, code: boolean): PMNode[] {\n const nodes: PMNode[] = []\n for (const op of text.toDelta() as { insert: string | Embed; attributes?: Attributes }[]) {\n if (typeof op.insert === 'string') {\n if (op.insert)\n nodes.push(schema.text(op.insert, code ? [] : marksFrom(op.attributes, schema)))\n } else {\n const type = schema.nodes[op.insert.node]\n if (type?.isInline)\n nodes.push(type.create(op.insert.attrs ?? null, null, marksFrom(op.attributes, schema)))\n }\n }\n return nodes\n}\n\n/** Bring `text` from `before`'s inline content to `after`'s, changing only what differs. */\nexport function updateText(text: Y.Text, before: PMNode, after: PMNode) {\n const start = before.content.findDiffStart(after.content)\n if (start === null) return\n const end = before.content.findDiffEnd(after.content)!\n // the ends can overlap the start when the change repeats nearby text\n const overlap = start - Math.min(end.a, end.b)\n if (overlap > 0) {\n end.a += overlap\n end.b += overlap\n }\n const sameText =\n end.a - start === end.b - start &&\n before.textBetween(start, end.a, '\\n', '') === after.textBetween(start, end.b, '\\n', '')\n if (sameText) {\n // only the formatting changed: keep the characters, so edits on them merge\n const schema = after.type.schema\n const comments = commentAttributes(before, start, end.a)\n after.content.forEach((child, pos) => {\n const from = Math.max(pos, start)\n const to = Math.min(pos + child.nodeSize, end.b)\n if (from >= to) return\n const attributes = markAttributes(child.marks, schema)\n // threads taken off this text\n for (const key of comments) if (!(key in attributes)) attributes[key] = null\n text.format(from, to - from, attributes)\n })\n return\n }\n if (end.a > start) text.delete(start, end.a - start)\n if (end.b > start) insertInline(text, start, after, start, end.b)\n}\n"],"mappings":";;AAYA,IAAM,UAAU;AAChB,IAAM,iBAAiB;AAEvB,SAAgB,eAAe,OAAwB,QAA4B;CAGjF,MAAM,aAAyB,CAAC;CAChC,KAAK,MAAM,QAAQ,OAAO,KAAK,OAAO,KAAK,GAAG,IAAI,SAAS,SAAS,WAAW,QAAQ;CACvF,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,KAAK,SAAS,SAAS,WAAW,iBAAiB,KAAK,MAAM,MAAM;MACxE,WA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AW,kBAAkB,QAAQ,OAAO,IAAI,CAAC;EACvD,MAAM,QAAQ,SAAS,OAAO,QAAQ;GACpC,MAAM,OAAO,KAAK,IAAI,KAAK,KAAK;GAChC,MAAM,KAAK,KAAK,IAAI,MAAM,MAAM,UAAU,IAAI,CAAC;GAC/C,IAAI,QAAQ,IAAI;GAChB,MAAM,aAAa,eAAe,MAAM,OAAO,MAAM;GAErD,KAAK,MAAM,OAAO,UAAU,IAAI,EAAE,OAAO,aAAa,WAAW,OAAO;GACxE,KAAK,OAAO,MAAM,KAAK,MAAM,UAAU;EACzC,CAAC;EACD;CACF;CACA,IAAI,IAAI,IAAI,OAAO,KAAK,OAAO,OAAO,IAAI,IAAI,KAAK;CACnD,IAAI,IAAI,IAAI,OAAO,aAAa,MAAM,OAAO,OAAO,OAAO,IAAI,CAAC;AAClE"}
|
|
1
|
+
{"version":3,"file":"text.js","names":[],"sources":["../../src/collaboration/text.ts"],"sourcesContent":["import { Mark, type Node as PMNode, type Schema } from 'prosemirror-model'\nimport type * as Y from 'yjs'\nimport { Mapping, StepMap, Transform } from 'prosemirror-transform'\nimport { diffLists, type DiffBudget } from './inline-diff'\n\n/* inline content ↔ Y.Text */\n\nexport type Attributes = Record<string, unknown>\n\n/*\n * A text can be in several comment threads at once, each added and\n * removed on its own, also by two people at the same time: every thread\n * is its own attribute, `comment:<thread id>`.\n */\nconst COMMENT = 'comment'\nconst COMMENT_PREFIX = 'comment:'\n\nexport function markAttributes(marks: readonly Mark[], schema: Schema): Attributes {\n // every mark is named, so `insert` doesn't inherit formatting from the left\n // (comment attributes the text doesn't have are cleared by `insert` itself)\n const attributes: Attributes = {}\n for (const name of Object.keys(schema.marks)) if (name !== COMMENT) attributes[name] = null\n for (const mark of marks) {\n if (mark.type.name === COMMENT) attributes[COMMENT_PREFIX + mark.attrs.id] = true\n else attributes[mark.type.name] = Object.keys(mark.attrs).length ? { ...mark.attrs } : true\n }\n return attributes\n}\n\n/** The comment attributes of the inline content from `from` to `to`. */\nfunction commentAttributes(node: PMNode, from: number, to: number): Set<string> {\n const keys = new Set<string>()\n node.nodesBetween(from, to, (child) => {\n for (const mark of child.marks)\n if (mark.type.name === COMMENT) keys.add(COMMENT_PREFIX + mark.attrs.id)\n })\n return keys\n}\n\ninterface Embed {\n node: string\n attrs?: Attributes\n}\n\n/** Write `content`'s inline nodes from `from` to `to` into `text` at `at`. */\nexport function insertInline(text: Y.Text, at: number, content: PMNode, from: number, to: number) {\n const schema = content.type.schema\n let offset = at\n content.forEach((child, pos) => {\n const start = Math.max(pos, from)\n const end = Math.min(pos + child.nodeSize, to)\n if (start >= end) return\n if (child.isText) {\n const piece = child.text!.slice(start - pos, end - pos)\n text.insert(offset, piece, markAttributes(child.marks, schema))\n offset += piece.length\n } else {\n const embed: Embed = { node: child.type.name }\n if (Object.keys(child.attrs).length) embed.attrs = { ...child.attrs }\n text.insertEmbed(offset, embed, markAttributes(child.marks, schema))\n offset += 1\n }\n })\n}\n\nfunction marksFrom(attributes: Attributes | undefined, schema: Schema): Mark[] {\n const marks: Mark[] = []\n for (const [name, value] of Object.entries(attributes ?? {})) {\n if (name.startsWith(COMMENT_PREFIX)) {\n if (value === true && schema.marks[COMMENT])\n marks.push(schema.marks[COMMENT].create({ id: name.slice(COMMENT_PREFIX.length) }))\n continue\n }\n const type = schema.marks[name]\n if (!type || value === null || value === undefined) continue\n marks.push(type.create(value === true ? null : (value as Attributes)))\n }\n return Mark.setFrom(marks) as Mark[]\n}\n\nexport function inlineFrom(text: Y.Text, schema: Schema, code: boolean): PMNode[] {\n const nodes: PMNode[] = []\n for (const op of text.toDelta() as { insert: string | Embed; attributes?: Attributes }[]) {\n if (typeof op.insert === 'string') {\n if (op.insert)\n nodes.push(schema.text(op.insert, code ? [] : marksFrom(op.attributes, schema)))\n } else {\n const type = schema.nodes[op.insert.node]\n if (type?.isInline)\n nodes.push(type.create(op.insert.attrs ?? null, null, marksFrom(op.attributes, schema)))\n }\n }\n return nodes\n}\n\n/** Bring `text` from `before`'s inline content to `after`'s, changing only what differs. */\nexport function updateText(text: Y.Text, before: PMNode, after: PMNode) {\n const start = before.content.findDiffStart(after.content)\n if (start === null) return\n const end = before.content.findDiffEnd(after.content)!\n // the ends can overlap the start when the change repeats nearby text\n const overlap = start - Math.min(end.a, end.b)\n if (overlap > 0) {\n end.a += overlap\n end.b += overlap\n }\n const sameText =\n end.a - start === end.b - start &&\n before.textBetween(start, end.a, '\\n', '') === after.textBetween(start, end.b, '\\n', '')\n if (sameText) {\n // only the formatting changed: keep the characters, so edits on them merge\n const schema = after.type.schema\n const comments = commentAttributes(before, start, end.a)\n after.content.forEach((child, pos) => {\n const from = Math.max(pos, start)\n const to = Math.min(pos + child.nodeSize, end.b)\n if (from >= to) return\n const attributes = markAttributes(child.marks, schema)\n // threads taken off this text\n for (const key of comments) if (!(key in attributes)) attributes[key] = null\n text.format(from, to - from, attributes)\n })\n return\n }\n if (end.a > start) text.delete(start, end.a - start)\n if (end.b > start) insertInline(text, start, after, start, end.b)\n}\n\n/** Inline characters and embeds, with offsets matching ProseMirror and Y.Text. */\nfunction units(node: PMNode) {\n const values: string[] = []\n const offsets: number[] = []\n node.forEach((child, at) => {\n if (child.isText) {\n let offset = at\n for (const character of child.text!) {\n offsets.push(offset)\n values.push('t:' + character)\n offset += character.length\n }\n } else {\n offsets.push(at)\n values.push('n:' + JSON.stringify([child.type.name, child.attrs]))\n }\n })\n offsets.push(node.content.size)\n return { values, offsets }\n}\n\n/** Exact content changes, at UTF-16 offsets, never inside a surrogate pair. */\nexport function inlineChanges(before: PMNode, after: PMNode, budget?: DiffBudget): InlineChange[] {\n const a = units(before)\n const b = units(after)\n return diffLists(a.values, b.values, budget).map(([from, to, start, end]) => [\n a.offsets[from]!,\n a.offsets[to]!,\n b.offsets[start]!,\n b.offsets[end]!,\n ])\n}\n\nexport type TextUpdatePlan = (text: Y.Text) => void\n\nconst markKey = (mark: Mark) =>\n mark.type.name === COMMENT ? COMMENT_PREFIX + mark.attrs.id : mark.type.name\n\nconst markRuns = (node: PMNode) => {\n const result: { end: number; marks: readonly Mark[] }[] = []\n node.forEach((child, at) => result.push({ end: at + child.nodeSize, marks: child.marks }))\n return result\n}\n\ntype InlineChange = [number, number, number, number]\nconst mappingOf = (changes: InlineChange[]) => {\n const mapping = new Mapping()\n let shift = 0\n for (const [from, to, start, end] of changes) {\n mapping.appendMap(new StepMap([from + shift, to - from, end - start]))\n shift += end - start - (to - from)\n }\n return mapping\n}\n\n/**\n * Apply base → written edits to the current inline content. Offsets are\n * mapped through the room's edits first; overlapping replacements use\n * written content, while edits elsewhere and their marks remain intact.\n */\nexport function prepareTextFromBase(\n base: PMNode,\n written: PMNode,\n current: PMNode,\n budget?: DiffBudget,\n): TextUpdatePlan {\n written = keepInlineComments(base, written, budget)\n const writes: TextUpdatePlan[] = []\n if (base.content.eq(written.content)) return () => {}\n const remote = base.content.eq(current.content) ? [] : inlineChanges(base, current, budget)\n const own = inlineChanges(base, written, budget)\n const roomMap = mappingOf(remote)\n const writtenMap = mappingOf(own)\n // An edit inside a replacement conflicts with that replacement as a\n // whole. Join such edits before mapping, so their ranges cannot cross.\n const ranges: { from: number; to: number }[] = []\n let remoteAt = 0\n for (const [start, end] of own) {\n let from = start\n let to = end\n while (remoteAt < remote.length && remote[remoteAt]![1] <= from) remoteAt++\n for (let i = remoteAt; i < remote.length; i++) {\n const [left, right] = remote[i]!\n if (left >= to) break\n if (left < to && right > from) {\n from = Math.min(from, left)\n to = Math.max(to, right)\n }\n }\n const last = ranges[ranges.length - 1]\n if (last && from <= last.to) last.to = Math.max(last.to, to)\n else ranges.push({ from, to })\n }\n const tr = new Transform(current)\n for (let i = ranges.length - 1; i >= 0; i--) {\n const { from, to } = ranges[i]!\n const start = roomMap.map(from, 1)\n const end = Math.max(start, roomMap.map(to, -1))\n const writtenStart = writtenMap.map(from, -1)\n const writtenEnd = writtenMap.map(to, 1)\n tr.replaceWith(start, end, written.content.cut(writtenStart, writtenEnd))\n writes.push((text) => {\n if (end > start) text.delete(start, end - start)\n if (writtenEnd > writtenStart) insertInline(text, start, written, writtenStart, writtenEnd)\n })\n }\n // Formatting is a field change, not a text replacement. Only marks\n // actually changed by the writer are applied to surviving characters.\n let formatted = false\n base.forEach((node) => {\n formatted ||= node.marks.length > 0\n })\n written.forEach((node) => {\n formatted ||= node.marks.length > 0\n })\n if (!formatted)\n return (text) => {\n for (const write of writes) write(text)\n }\n let run: { from: number; to: number; remove: Mark[]; add: Mark[]; key: string } | null = null\n const flush = () => {\n if (!run) return\n const attributes: Attributes = {}\n for (const mark of run.remove) attributes[markKey(mark)] = null\n for (const mark of run.add)\n attributes[markKey(mark)] =\n mark.type.name === COMMENT || !Object.keys(mark.attrs).length ? true : { ...mark.attrs }\n const { from, to } = run\n writes.push((text) => text.format(from, to - from, attributes))\n run = null\n }\n const baseRuns = markRuns(base)\n const writtenRuns = markRuns(written)\n let baseRun = 0\n let writtenRun = 0\n let changed = 0\n for (let i = 0; i < base.content.size; i++) {\n while (changed < own.length && own[changed]![1] <= i) changed++\n if (changed < own.length && own[changed]![0] <= i && i < own[changed]![1]) continue\n const j = writtenMap.map(i, 1)\n while (baseRuns[baseRun] && baseRuns[baseRun]!.end <= i) baseRun++\n while (writtenRuns[writtenRun] && writtenRuns[writtenRun]!.end <= j) writtenRun++\n const was = baseRuns[baseRun]?.marks ?? []\n const next = writtenRuns[writtenRun]?.marks ?? []\n const old = new Map(was.map((mark) => [markKey(mark), mark]))\n const fresh = new Map(next.map((mark) => [markKey(mark), mark]))\n const remove = was.filter((mark) => !fresh.get(markKey(mark))?.eq(mark))\n const add = next.filter((mark) => !old.get(markKey(mark))?.eq(mark))\n if (!remove.length && !add.length) continue\n const from = tr.mapping.map(roomMap.map(i, 1), 1)\n const to = tr.mapping.map(roomMap.map(i + 1, -1), -1)\n if (to <= from) continue\n const key = JSON.stringify([\n remove.map((mark) => mark.toJSON()),\n add.map((mark) => mark.toJSON()),\n ])\n if (run && run.to === from && run.key === key) run.to = to\n else {\n flush()\n run = { from, to, remove, add, key }\n }\n }\n flush()\n return (text) => {\n for (const write of writes) write(text)\n }\n}\n\n/** Used after a complete preflight, so no diff can fail after a map write. */\nexport function updateTextFromBase(text: Y.Text, base: PMNode, written: PMNode, current: PMNode) {\n prepareTextFromBase(base, written, current)(text)\n}\n\n/**\n * `after` with the comment marks of `before` on all unchanged inline\n * fragments, when `after` has none: a version read from Markdown, which\n * doesn't carry them, leaves the threads where the text stays the same.\n */\nexport function keepInlineComments(before: PMNode, after: PMNode, budget?: DiffBudget): PMNode {\n const type = after.type.schema.marks.comment\n if (!type || !after.inlineContent || !before.inlineContent || before.type !== after.type)\n return after\n let theirs = false\n after.descendants((node) => {\n if (type.isInSet(node.marks)) theirs = true\n })\n if (theirs) return after\n const ranges: { from: number; to: number; mark: Mark }[] = []\n before.forEach((child, pos) => {\n for (const mark of child.marks)\n if (mark.type === type) ranges.push({ from: pos, to: pos + child.nodeSize, mark })\n })\n if (!ranges.length) return after\n const changes = inlineChanges(before, after, budget)\n const same: { from: number; to: number; shift: number }[] = []\n let left = 0\n let right = 0\n for (const [from, to, , end] of changes) {\n if (from > left) same.push({ from: left, to: from, shift: right - left })\n left = to\n right = end\n }\n if (left < before.content.size)\n same.push({ from: left, to: before.content.size, shift: right - left })\n const tr = new Transform(after)\n for (const { from, to, mark } of ranges) {\n for (const fragment of same) {\n const start = Math.max(from, fragment.from)\n const end = Math.min(to, fragment.to)\n if (end > start) tr.addMark(start + fragment.shift, end + fragment.shift, mark)\n }\n }\n return tr.doc\n}\n"],"mappings":";;;;AAcA,IAAM,UAAU;AAChB,IAAM,iBAAiB;AAEvB,SAAgB,eAAe,OAAwB,QAA4B;CAGjF,MAAM,aAAyB,CAAC;CAChC,KAAK,MAAM,QAAQ,OAAO,KAAK,OAAO,KAAK,GAAG,IAAI,SAAS,SAAS,WAAW,QAAQ;CACvF,KAAK,MAAM,QAAQ,OACjB,IAAI,KAAK,KAAK,SAAS,SAAS,WAAW,iBAAiB,KAAK,MA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AAO,MAAM;CACnD,MAAM,OAAsD,CAAC;CAC7D,IAAI,OAAO;CACX,IAAI,QAAQ;CACZ,KAAK,MAAM,CAAC,MAAM,MAAM,QAAQ,SAAS;EACvC,IAAI,OAAO,MAAM,KAAK,KAAK;GAAE,MAAM;GAAM,IAAI;GAAM,OAAO,QAAQ;EAAK,CAAC;EACxE,OAAO;EACP,QAAQ;CACV;CACA,IAAI,OAAO,OAAO,QAAQ,MACxB,KAAK,KAAK;EAAE,MAAM;EAAM,IAAI,OAAO,QAAQ;EAAM,OAAO,QAAQ;CAAK,CAAC;CACxE,MAAM,KAAK,IAAI,UAAU,KAAK;CAC9B,KAAK,MAAM,EAAE,MAAM,IAAI,UAAU,QAC/B,KAAK,MAAM,YAAY,MAAM;EAC3B,MAAM,QAAQ,KAAK,IAAI,MAAM,SAAS,IAAI;EAC1C,MAAM,MAAM,KAAK,IAAI,IAAI,SAAS,EAAE;EACpC,IAAI,MAAM,OAAO,GAAG,QAAQ,QAAQ,SAAS,OAAO,MAAM,SAAS,OAAO,IAAI;CAChF;CAEF,OAAO,GAAG;AACZ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block-handle.js","names":["_sfc_main"],"sources":["../../src/components/block-handle.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ArrowDownIcon,\n ArrowUpIcon,\n CheckIcon,\n CopyIcon,\n GripVerticalIcon,\n PlusIcon,\n TrashIcon,\n} from '@dou-ui/icons'\nimport { DouDropdown, DouDropdownItem, DouDropdownSub } from 'dou-ui'\nimport { TextSelection } from 'prosemirror-state'\nimport { computed, inject, onBeforeUnmount, onMounted, shallowRef, watch } from 'vue'\nimport { isCurrent } from '../catalog'\nimport { labelOf, type BlockOption } from '../core/extension'\nimport {\n blockSelectionKey,\n blockSelectionRange,\n getBlockSelection,\n selectBlocks,\n} from '../core/block-selection'\nimport {\n blockAround,\n blocksIn,\n findBlockById,\n siblingRangeBetween,\n type SiblingRange,\n} from '../core/blocks'\nimport {\n duplicateBlocks,\n insertBlockAfter,\n swapBlocks,\n moveRangeTo,\n deleteBlocks,\n setBlockType,\n} from '../core/commands'\nimport { blockFromNode } from '../core/model'\nimport { slashKey } from '../core/slash'\nimport { blockElementOf, contentAt, firstLine, scrollParent } from '../dom'\nimport { editorKey } from '../editor'\nimport { useMenuEscape } from './menu-escape'\n\nconst { view, state, focused, messages, root, dragging, kit } = inject(editorKey)!\n\n/**\n * Touch screens have no hover: there the handle shows only the grip, next\n * to the block with the cursor (or the selected blocks) while the editor\n * has focus. A tap on it opens the menu, a press and drag moves the block.\n */\nconst touch = shallowRef(false)\nlet media: MediaQueryList | null = null\nconst onMedia = () => (touch.value = !!media?.matches)\n\n/** The block the handle is next to, by id. */\nconst hovered = shallowRef<string | null>(null)\nconst position = shallowRef<{ top: number; left: number; height: number } | null>(null)\nconst menuOpen = shallowRef(false)\nuseMenuEscape(menuOpen, () => (menuOpen.value = false))\n\nconst drop = shallowRef<{ pos: number; top: number; left: number; width: number } | null>(null)\n// typing hides the handle until the pointer moves again\nconst resting = shallowRef(false)\n\nconst visible = computed(() => {\n if (!position.value) return false\n if (menuOpen.value || dragging.value) return true\n if (touch.value) return focused.value || (!!state.value && !!getBlockSelection(state.value))\n return !resting.value\n})\n\nfunction place(content: HTMLElement) {\n const block = blockElementOf(content)\n const id = block?.dataset.blockId\n const host = root.value\n if (!id || !host) return\n const box = host.getBoundingClientRect()\n const line = firstLine(content)\n hovered.value = id\n position.value = {\n top: line.top - box.top,\n left: content.getBoundingClientRect().left - box.left,\n height: line.height,\n }\n}\n\nlet frame = 0\nlet lastY = 0\nlet lastX = 0\n\nfunction track(event: PointerEvent) {\n // a finger only moves the handle by moving the cursor; a drag reports itself\n if (event.pointerType === 'touch') return\n lastY = event.clientY\n lastX = event.clientX\n resting.value = false\n if (menuOpen.value || frame) return\n frame = requestAnimationFrame(() => {\n frame = 0\n if (dragging.value) return updateDrop()\n const current = view.value\n if (!current || menuOpen.value) return\n const content = contentAt(current, lastY)\n if (content) place(content)\n })\n}\n\nfunction leave(event: PointerEvent) {\n if (menuOpen.value || dragging.value || event.pointerType === 'touch') return\n position.value = null\n hovered.value = null\n}\n\n/** On touch screens: put the handle next to the block with the cursor. */\nfunction follow() {\n const current = view.value\n if (!current || dragging.value) return\n const selected = blockSelectionRange(current.state)\n const info = selected ? blocksIn(selected)[0] : blockAround(current.state.selection.$from)\n const element = info\n ? (current.nodeDOM(info.pos) as HTMLElement | null)?.querySelector<HTMLElement>(\n ':scope > .dou-editor__content',\n )\n : null\n if (element) place(element)\n else {\n position.value = null\n hovered.value = null\n }\n}\n\nlet followFrame = 0\nfunction scheduleFollow() {\n if (!touch.value || followFrame) return\n followFrame = requestAnimationFrame(() => {\n followFrame = 0\n if (touch.value && !menuOpen.value) follow()\n })\n}\n\nwatch([state, focused, touch], scheduleFollow)\n\nonMounted(() => {\n media = window.matchMedia('(pointer: coarse)')\n onMedia()\n media.addEventListener('change', onMedia)\n window.addEventListener('resize', scheduleFollow)\n root.value?.addEventListener('pointermove', track)\n root.value?.addEventListener('pointerleave', leave)\n})\nonBeforeUnmount(() => {\n media?.removeEventListener('change', onMedia)\n window.removeEventListener('resize', scheduleFollow)\n if (followFrame) cancelAnimationFrame(followFrame)\n root.value?.removeEventListener('pointermove', track)\n root.value?.removeEventListener('pointerleave', leave)\n if (frame) cancelAnimationFrame(frame)\n stopDrag()\n})\n\n// follow edits: keep the handle on its block, or hide it while typing\nwatch(state, (next, previous) => {\n if (touch.value || !next || !previous || next.doc === previous.doc || dragging.value) return\n if (!menuOpen.value) resting.value = true\n requestAnimationFrame(() => {\n const current = view.value\n if (!current || !hovered.value) return\n const element = current.dom.querySelector<HTMLElement>(\n `[data-block-id=\"${CSS.escape(hovered.value)}\"] > .dou-editor__content`,\n )\n if (element) place(element)\n else position.value = null\n })\n})\n\nconst target = computed(() => {\n const doc = state.value?.doc\n return doc && hovered.value ? findBlockById(doc, hovered.value) : null\n})\n\n/** The hovered block, or every selected block when it is one of them. */\nfunction rangeForHovered(): SiblingRange | null {\n const current = view.value\n const info = target.value\n if (!current || !info) return null\n const selected = blockSelectionRange(current.state)\n if (selected && info.pos >= selected.start && info.pos < selected.end) return selected\n return siblingRangeBetween(current.state.doc, info.pos + 1, info.pos + 1)\n}\n\n/** Select the blocks the menu or a drag acts on. */\nfunction selectTarget(): SiblingRange | null {\n const current = view.value\n const range = rangeForHovered()\n if (!current || !range) return null\n const blocks = blocksIn(range)\n selectBlocks(blocks[0]!.node.attrs.id, blocks.at(-1)!.node.attrs.id)(\n current.state,\n current.dispatch,\n )\n return blockSelectionRange(current.state)\n}\n\n/* the + button */\n\nfunction add(event: MouseEvent) {\n const current = view.value\n const info = target.value\n if (!current || !info) return\n const empty = info.content.isTextblock && info.content.content.size === 0\n if (!empty || info.content.type.name !== 'paragraph') {\n insertBlockAfter(info.pos)(current.state, current.dispatch)\n // Alt+click adds the block above instead\n if (event.altKey) swapBlocks(-1)(current.state, current.dispatch)\n } else {\n const tr = current.state.tr.setSelection(\n TextSelection.create(current.state.doc, info.contentPos + 1),\n )\n current.dispatch(tr)\n }\n const from = current.state.selection.from\n current.dispatch(current.state.tr.insertText('/').setMeta(slashKey, { from, query: '' }))\n current.focus()\n}\n\n/* the block menu */\n\nconst turnOptions = kit.blockOptions.filter(\n (option) => !!kit.schema.nodes[option.type]?.isTextblock,\n)\nconst current = computed(() => {\n const info = target.value\n return info ? blockFromNode(info.node) : null\n})\n\nfunction after(action: () => void) {\n action()\n // the menu gives focus back to the handle; the editor takes it after\n requestAnimationFrame(() => view.value?.focus())\n}\n\nfunction keep(run: (current: NonNullable<typeof view.value>) => void) {\n after(() => {\n const instance = view.value\n if (!instance) return\n const selection = getBlockSelection(instance.state)\n run(instance)\n if (selection) selectBlocks(selection.anchor, selection.head)(instance.state, instance.dispatch)\n })\n}\n\nconst turnInto = (option: BlockOption) =>\n keep((instance) => setBlockType(option.type, option.props)(instance.state, instance.dispatch))\nconst duplicate = () => keep((instance) => duplicateBlocks(instance.state, instance.dispatch))\nconst move = (direction: -1 | 1) =>\n keep((instance) => swapBlocks(direction)(instance.state, instance.dispatch))\n\nfunction remove() {\n after(() => {\n const instance = view.value\n const range = instance && blockSelectionRange(instance.state)\n if (!instance || !range) return\n const tr = deleteBlocks(instance.state.tr, blocksIn(range)).setMeta(blockSelectionKey, null)\n instance.dispatch(tr.scrollIntoView())\n position.value = null\n })\n}\n\nconst canMove = (direction: -1 | 1) => {\n const instance = view.value\n return !!instance && !!state.value && swapBlocks(direction)(instance.state)\n}\n\n/* dragging */\n\nlet start: { x: number; y: number; pointer: number; touch: boolean } | null = null\nlet range: SiblingRange | null = null\nlet scroller: HTMLElement | null = null\nlet scrollFrame = 0\n/** A copy of the dragged blocks that follows the pointer. */\nlet ghost: HTMLElement | null = null\n\nfunction showGhost(moving: SiblingRange) {\n const instance = view.value\n const host = root.value\n if (!instance || !host) return\n ghost = document.createElement('div')\n ghost.className = 'dou-editor__surface dou-editor__ghost'\n ghost.setAttribute('aria-hidden', 'true')\n let width = 0\n for (const block of blocksIn(moving)) {\n const element = instance.nodeDOM(block.pos) as HTMLElement | null\n if (!element) continue\n width = Math.max(width, element.getBoundingClientRect().width)\n const copy = element.cloneNode(true) as HTMLElement\n copy.classList.remove('is-selected')\n for (const node of [copy, ...copy.querySelectorAll('[id], .is-selected')]) {\n node.removeAttribute('id')\n node.classList.remove('is-selected')\n }\n ghost.append(copy)\n }\n ghost.style.width = `${Math.min(width, 360)}px`\n host.append(ghost)\n moveGhost()\n}\n\nfunction moveGhost() {\n if (!ghost) return\n // above a finger, which would hide it; below and right of a mouse pointer\n const y = start?.touch ? lastY - ghost.offsetHeight - 24 : lastY + 12\n ghost.style.transform = `translate(${lastX + 12}px, ${y}px)`\n}\n\nfunction onGripDown(event: PointerEvent) {\n if (event.button !== 0) return\n start = {\n x: event.clientX,\n y: event.clientY,\n pointer: event.pointerId,\n touch: event.pointerType === 'touch',\n }\n ;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)\n}\n\nfunction onGripMove(event: PointerEvent) {\n if (!start || event.pointerId !== start.pointer) return\n lastX = event.clientX\n lastY = event.clientY\n if (!dragging.value) {\n // a finger wobbles more than a mouse while tapping\n const slop = start.touch ? 8 : 4\n if (Math.hypot(event.clientX - start.x, event.clientY - start.y) < slop) return\n range = selectTarget()\n if (!range) return stopDrag()\n dragging.value = true\n scroller = root.value && scrollParent(root.value)\n window.addEventListener('keydown', onDragKey, true)\n showGhost(range)\n autoScroll()\n }\n moveGhost()\n updateDrop()\n}\n\nfunction onGripUp(event: PointerEvent) {\n if (!start || event.pointerId !== start.pointer) return\n if (dragging.value) finishDrag()\n else if (menuOpen.value) menuOpen.value = false\n else {\n selectTarget()\n menuOpen.value = true\n }\n start = null\n}\n\nfunction onDragKey(event: KeyboardEvent) {\n if (event.key !== 'Escape') return\n event.preventDefault()\n event.stopPropagation()\n stopDrag()\n}\n\nfunction updateDrop() {\n const instance = view.value\n const host = root.value\n if (!instance || !host || !range) return\n const content = contentAt(instance, lastY)\n const id = content && blockElementOf(content)?.dataset.blockId\n const info = id ? findBlockById(instance.state.doc, id) : null\n if (!content || !info) return (drop.value = null)\n const box = host.getBoundingClientRect()\n const rect = content.getBoundingClientRect()\n const below = lastY > rect.top + rect.height / 2\n let pos: number\n let y: number\n let left = rect.left\n if (!below) {\n pos = info.pos\n y = rect.top\n } else if (info.group) {\n // the lower half of a block with children: in front of its first child\n pos = info.contentPos + info.content.nodeSize + 1\n y = rect.bottom\n const child = blockElementOf(content)?.querySelector<HTMLElement>(\n ':scope > .dou-editor__group > .dou-editor__block > .dou-editor__content',\n )\n left = child?.getBoundingClientRect().left ?? rect.left\n } else {\n pos = info.pos + info.node.nodeSize\n y = blockElementOf(content)!.getBoundingClientRect().bottom\n }\n if (!moveRangeTo(range, pos)(instance.state)) return (drop.value = null)\n drop.value = { pos, top: y - box.top, left: left - box.left, width: box.right - left }\n}\n\nfunction autoScroll() {\n scrollFrame = requestAnimationFrame(() => {\n if (!dragging.value) return\n const edge = 48\n const top = scroller ? scroller.getBoundingClientRect().top : 0\n const bottom = scroller ? scroller.getBoundingClientRect().bottom : window.innerHeight\n let speed = 0\n if (lastY < top + edge) speed = -Math.ceil(((top + edge - lastY) / edge) * 16)\n else if (lastY > bottom - edge) speed = Math.ceil(((lastY - bottom + edge) / edge) * 16)\n if (speed) {\n if (scroller) scroller.scrollTop += speed\n else window.scrollBy(0, speed)\n updateDrop()\n }\n autoScroll()\n })\n}\n\nfunction finishDrag() {\n const instance = view.value\n const spot = drop.value\n const moving = range\n stopDrag()\n if (!instance || !spot || !moving) return\n const ids = blocksIn(moving).map((block) => block.node.attrs.id as string)\n if (!moveRangeTo(moving, spot.pos)(instance.state, instance.dispatch)) return\n selectBlocks(ids[0]!, ids.at(-1)!)(instance.state, instance.dispatch)\n instance.focus()\n}\n\nfunction stopDrag() {\n dragging.value = false\n drop.value = null\n range = null\n start = null\n ghost?.remove()\n ghost = null\n if (scrollFrame) cancelAnimationFrame(scrollFrame)\n scrollFrame = 0\n window.removeEventListener('keydown', onDragKey, true)\n}\n\nwatch(menuOpen, (value) => {\n if (value) return\n if (touch.value) scheduleFollow()\n else if (!root.value?.matches(':hover')) position.value = null\n})\n</script>\n\n<template>\n <div\n v-show=\"visible\"\n class=\"dou-editor__handle\"\n :style=\"\n position\n ? {\n top: `${position.top}px`,\n left: `${position.left}px`,\n '--dou-editor-line': `${position.height}px`,\n }\n : undefined\n \"\n @mousedown.prevent\n >\n <button\n type=\"button\"\n tabindex=\"-1\"\n class=\"dou-editor__handle-button dou-editor__add\"\n :aria-label=\"messages.addBlock\"\n :title=\"messages.addBlock\"\n @click=\"add\"\n >\n <PlusIcon />\n </button>\n <DouDropdown\n v-model:open=\"menuOpen\"\n trigger=\"manual\"\n placement=\"bottom-start\"\n class=\"dou-editor-menu\"\n >\n <button\n type=\"button\"\n tabindex=\"-1\"\n class=\"dou-editor__handle-button dou-editor__grip\"\n :aria-label=\"messages.dragHandle\"\n :title=\"messages.dragHandle\"\n @pointerdown=\"onGripDown\"\n @pointermove=\"onGripMove\"\n @pointerup=\"onGripUp\"\n @pointercancel=\"stopDrag\"\n >\n <GripVerticalIcon />\n </button>\n <template #menu>\n <DouDropdownSub :title=\"messages.turnInto\">\n <DouDropdownItem\n v-for=\"option in turnOptions\"\n :key=\"option.key\"\n @click=\"turnInto(option)\"\n >\n <template #prefix><component :is=\"option.icon\" /></template>\n {{ labelOf(option.label, messages) }}\n <template v-if=\"current && isCurrent(option, current.type, current.props)\" #suffix>\n <CheckIcon />\n </template>\n </DouDropdownItem>\n </DouDropdownSub>\n <template v-if=\"current\">\n <component\n :is=\"entry\"\n v-for=\"(entry, index) in kit.blockMenu\"\n :key=\"index\"\n :block=\"current\"\n />\n </template>\n <DouDropdownItem :shortcut=\"touch ? undefined : 'mod+d'\" @click=\"duplicate\">\n <template #prefix><CopyIcon /></template>\n {{ messages.duplicate }}\n </DouDropdownItem>\n <DouDropdownItem\n :disabled=\"!canMove(-1)\"\n :shortcut=\"touch ? undefined : 'mod+shift+up'\"\n @click=\"move(-1)\"\n >\n <template #prefix><ArrowUpIcon /></template>\n {{ messages.moveUp }}\n </DouDropdownItem>\n <DouDropdownItem\n :disabled=\"!canMove(1)\"\n :shortcut=\"touch ? undefined : 'mod+shift+down'\"\n @click=\"move(1)\"\n >\n <template #prefix><ArrowDownIcon /></template>\n {{ messages.moveDown }}\n </DouDropdownItem>\n <DouDropdownItem\n divided\n tone=\"danger\"\n :shortcut=\"touch ? undefined : 'delete'\"\n @click=\"remove\"\n >\n <template #prefix><TrashIcon /></template>\n {{ messages.delete }}\n </DouDropdownItem>\n </template>\n </DouDropdown>\n </div>\n <div\n v-if=\"drop\"\n class=\"dou-editor__drop\"\n :style=\"{ top: `${drop.top}px`, left: `${drop.left}px`, width: `${drop.width}px` }\"\n />\n</template>\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"block-handle.js","names":["_sfc_main"],"sources":["../../src/components/block-handle.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ArrowDownIcon,\n ArrowUpIcon,\n CheckIcon,\n CopyIcon,\n GripVerticalIcon,\n PlusIcon,\n TrashIcon,\n} from '@dou-ui/icons'\nimport { DouDropdown, DouDropdownItem, DouDropdownSub } from 'dou-ui'\nimport { TextSelection } from 'prosemirror-state'\nimport {\n computed,\n inject,\n onBeforeUnmount,\n onMounted,\n shallowRef,\n useTemplateRef,\n watch,\n} from 'vue'\nimport { isCurrent } from '../catalog'\nimport { labelOf, type BlockOption } from '../core/extension'\nimport {\n blockSelectionKey,\n blockSelectionRange,\n getBlockSelection,\n selectBlocks,\n} from '../core/block-selection'\nimport {\n blockAround,\n blocksIn,\n findBlockById,\n siblingRangeBetween,\n type SiblingRange,\n} from '../core/blocks'\nimport {\n duplicateBlocks,\n insertBlockAfter,\n swapBlocks,\n moveRangeTo,\n moveRangeToNewColumn,\n deleteBlocks,\n setBlockType,\n} from '../core/commands'\nimport { blockFromNode } from '../core/model'\nimport { slashKey } from '../core/slash'\nimport {\n blockElementOf,\n bubbleShift,\n childBlocks,\n COLUMN_GROUP,\n contentAt,\n contentSpan,\n firstLine,\n handleLeft,\n scrollParent,\n sideBySide,\n} from '../dom'\nimport { editorKey } from '../editor'\nimport { useMenuEscape } from './menu-escape'\n\nconst { view, state, focused, messages, root, dragging, kit } = inject(editorKey)!\n\n/**\n * Touch screens have no hover: there the handle shows only the grip, next\n * to the block with the cursor (or the selected blocks) while the editor\n * has focus. A tap on it opens the menu, a press and drag moves the block.\n */\nconst touch = shallowRef(false)\nlet media: MediaQueryList | null = null\n/** A mouse: \"+\" comes out of the bubble while the pointer is on it. */\nlet fine: MediaQueryList | null = null\nconst onMedia = () => (touch.value = !!media?.matches)\n\n/** The block the handle is next to, by id. */\nconst hovered = shallowRef<string | null>(null)\nconst position = shallowRef<{ top: number; left: number; height: number } | null>(null)\n/** In a column the handle is only the grip, in the gap before it, leaving room for the resize bar. */\nconst compact = shallowRef(false)\n/** Next to a table: further out, clear of its row handles. */\nconst table = shallowRef(false)\nconst menuOpen = shallowRef(false)\nuseMenuEscape(menuOpen, () => {\n menuOpen.value = false\n // the menu had the focus; the selected blocks still answer Delete and copy\n requestAnimationFrame(() => view.value?.focus())\n})\n\n/**\n * Where a drag would drop: before or after a block (a line across), or\n * beside a column, into a new column (a line down, `column` set).\n */\ninterface Drop {\n pos: number\n top: number\n left: number\n width: number\n height?: number\n column?: { row: string; index: number }\n}\nconst drop = shallowRef<Drop | null>(null)\n// typing hides the handle until the pointer moves again\nconst resting = shallowRef(false)\n\nconst visible = computed(() => {\n if (!position.value) return false\n if (menuOpen.value || dragging.value) return true\n if (touch.value) return focused.value || (!!state.value && !!getBlockSelection(state.value))\n return !resting.value\n})\n\nfunction place(content: HTMLElement) {\n const block = blockElementOf(content)\n const id = block?.dataset.blockId\n const host = root.value\n if (!id || !host) return\n const box = host.getBoundingClientRect()\n const line = firstLine(content)\n hovered.value = id\n compact.value = !!content.closest(COLUMN_GROUP)\n table.value = content.classList.contains('dou-editor__content--table')\n position.value = {\n top: line.top - box.top,\n left: handleLeft(content) - box.left,\n height: line.height,\n }\n}\n\nlet frame = 0\nlet lastY = 0\nlet lastX = 0\n\nfunction track(event: PointerEvent) {\n // a finger only moves the handle by moving the cursor; a drag reports itself\n if (event.pointerType === 'touch') return\n lastY = event.clientY\n lastX = event.clientX\n resting.value = false\n if (menuOpen.value || frame) return\n frame = requestAnimationFrame(() => {\n frame = 0\n if (dragging.value) return updateDrop()\n const current = view.value\n if (!current || menuOpen.value) return\n const content = contentAt(current, lastY, lastX)\n if (content) place(content)\n })\n}\n\n/** A wide table scrolled sideways: the handle next to it follows its left edge. */\nfunction onScroll(event: Event) {\n const content = event.target\n if (\n !(content instanceof HTMLElement) ||\n !content.classList.contains('dou-editor__content--table')\n )\n return\n if (position.value && hovered.value && blockElementOf(content)?.dataset.blockId === hovered.value)\n place(content)\n}\n\nfunction leave(event: PointerEvent) {\n if (menuOpen.value || dragging.value || event.pointerType === 'touch') return\n position.value = null\n hovered.value = null\n}\n\n/** On touch screens: put the handle next to the block with the cursor. */\nfunction follow() {\n const current = view.value\n if (!current || dragging.value) return\n const selected = blockSelectionRange(current.state)\n const info = selected ? blocksIn(selected)[0] : blockAround(current.state.selection.$from)\n const element = info\n ? (current.nodeDOM(info.pos) as HTMLElement | null)?.querySelector<HTMLElement>(\n ':scope > .dou-editor__content',\n )\n : null\n if (element) place(element)\n else {\n position.value = null\n hovered.value = null\n }\n}\n\nlet followFrame = 0\nfunction scheduleFollow() {\n if (!touch.value || followFrame) return\n followFrame = requestAnimationFrame(() => {\n followFrame = 0\n if (touch.value && !menuOpen.value) follow()\n })\n}\n\nwatch([state, focused, touch], scheduleFollow)\n\nonMounted(() => {\n media = window.matchMedia('(pointer: coarse)')\n fine = window.matchMedia('(hover: hover) and (pointer: fine)')\n onMedia()\n media.addEventListener('change', onMedia)\n window.addEventListener('resize', scheduleFollow)\n root.value?.addEventListener('pointermove', track)\n root.value?.addEventListener('pointerleave', leave)\n root.value?.addEventListener('scroll', onScroll, true)\n})\nonBeforeUnmount(() => {\n media?.removeEventListener('change', onMedia)\n window.removeEventListener('resize', scheduleFollow)\n if (followFrame) cancelAnimationFrame(followFrame)\n root.value?.removeEventListener('pointermove', track)\n root.value?.removeEventListener('pointerleave', leave)\n root.value?.removeEventListener('scroll', onScroll, true)\n if (frame) cancelAnimationFrame(frame)\n stopDrag()\n})\n\n// follow edits: keep the handle on its block, or hide it while typing\nwatch(state, (next, previous) => {\n if (touch.value || !next || !previous || next.doc === previous.doc || dragging.value) return\n if (!menuOpen.value) resting.value = true\n requestAnimationFrame(() => {\n const current = view.value\n if (!current || !hovered.value) return\n const element = current.dom.querySelector<HTMLElement>(\n `[data-block-id=\"${CSS.escape(hovered.value)}\"] > .dou-editor__content`,\n )\n if (element) place(element)\n else position.value = null\n })\n})\n\n/*\n * The bubble floats outside the text. When the editor's container cuts off\n * the room there (it clips, or the screen ends), the bubble moves in by as\n * much as it lacks, counting the \"+\" that comes out on hover, so the grip\n * stays under the pointer when it does, and a finger's reach on touch screens.\n */\nconst handle = useTemplateRef<HTMLElement>('handle')\n/** The width \"+\" adds to the bubble (its button, see the styles). */\nconst ADD_WIDTH = 20\n/** How far a finger's reach goes left of the bubble (the grip's ::before, past the bubble's border and padding). */\nconst TOUCH_REACH = 12\nconst shift = shallowRef(0)\n\nfunction clipLeft(from: HTMLElement): number {\n for (let node = from.parentElement; node; node = node.parentElement) {\n if (getComputedStyle(node).overflowX !== 'visible') return node.getBoundingClientRect().left\n }\n return 0\n}\n\nfunction fit() {\n const element = handle.value\n const host = root.value\n if (!element || !host || !visible.value) return\n let left = element.getBoundingClientRect().left - shift.value\n const plus = element.querySelector<HTMLElement>('.dou-editor__add')\n if (fine?.matches && !compact.value && plus && !plus.offsetWidth) left -= ADD_WIDTH\n const style = getComputedStyle(element)\n const clear =\n table.value && position.value\n ? host.getBoundingClientRect().left +\n position.value.left +\n Number.parseFloat(style.getPropertyValue('--dou-editor-handle-offset')) -\n 1\n : undefined\n const edge = clipLeft(host)\n /*\n * A finger's reach moves the bubble in too, but only as far as plain text\n * lets it: next to a table, a cut-off reach stays cut off rather than\n * pushing the bubble onto the row handles or past them.\n */\n const next = Math.max(\n bubbleShift(left, edge, clear),\n touch.value && !table.value ? bubbleShift(left - TOUCH_REACH, edge) : 0,\n )\n if (next !== shift.value) shift.value = next\n}\n\nwatch([position, visible, compact, table], fit, { flush: 'post' })\nlet sizes: ResizeObserver | null = null\nonMounted(() => {\n sizes = new ResizeObserver(fit)\n if (handle.value) sizes.observe(handle.value)\n})\nonBeforeUnmount(() => sizes?.disconnect())\n\nconst target = computed(() => {\n const doc = state.value?.doc\n return doc && hovered.value ? findBlockById(doc, hovered.value) : null\n})\n\n/** The hovered block, or every selected block when it is one of them. */\nfunction rangeForHovered(): SiblingRange | null {\n const current = view.value\n const info = target.value\n if (!current || !info) return null\n const selected = blockSelectionRange(current.state)\n if (selected && info.pos >= selected.start && info.pos < selected.end) return selected\n return siblingRangeBetween(current.state.doc, info.pos + 1, info.pos + 1)\n}\n\n/** Select the blocks the menu or a drag acts on. */\nfunction selectTarget(): SiblingRange | null {\n const current = view.value\n const range = rangeForHovered()\n if (!current || !range) return null\n const blocks = blocksIn(range)\n selectBlocks(blocks[0]!.node.attrs.id, blocks.at(-1)!.node.attrs.id)(\n current.state,\n current.dispatch,\n )\n return blockSelectionRange(current.state)\n}\n\n/* the + button */\n\nfunction add(event: MouseEvent) {\n const current = view.value\n const info = target.value\n if (!current || !info) return\n const empty = info.content.isTextblock && info.content.content.size === 0\n if (!empty || info.content.type.name !== 'paragraph') {\n insertBlockAfter(info.pos)(current.state, current.dispatch)\n // Alt+click adds the block above instead\n if (event.altKey) swapBlocks(-1)(current.state, current.dispatch)\n } else {\n const tr = current.state.tr.setSelection(\n TextSelection.create(current.state.doc, info.contentPos + 1),\n )\n current.dispatch(tr)\n }\n const from = current.state.selection.from\n current.dispatch(current.state.tr.insertText('/').setMeta(slashKey, { from, query: '' }))\n current.focus()\n}\n\n/* the block menu */\n\nconst turnOptions = kit.blockOptions.filter(\n (option) => !!kit.schema.nodes[option.type]?.isTextblock,\n)\nconst current = computed(() => {\n const info = target.value\n return info ? blockFromNode(info.node) : null\n})\n\nfunction after(action: () => void) {\n action()\n // the menu gives focus back to the handle; the editor takes it after\n requestAnimationFrame(() => view.value?.focus())\n}\n\nfunction keep(run: (current: NonNullable<typeof view.value>) => void) {\n after(() => {\n const instance = view.value\n if (!instance) return\n const selection = getBlockSelection(instance.state)\n run(instance)\n if (selection) selectBlocks(selection.anchor, selection.head)(instance.state, instance.dispatch)\n })\n}\n\nconst turnInto = (option: BlockOption) =>\n keep((instance) => setBlockType(option.type, option.props)(instance.state, instance.dispatch))\nconst duplicate = () => keep((instance) => duplicateBlocks(instance.state, instance.dispatch))\nconst move = (direction: -1 | 1) =>\n keep((instance) => swapBlocks(direction)(instance.state, instance.dispatch))\n\nfunction remove() {\n after(() => {\n const instance = view.value\n const range = instance && blockSelectionRange(instance.state)\n if (!instance || !range) return\n const tr = deleteBlocks(instance.state.tr, blocksIn(range)).setMeta(blockSelectionKey, null)\n instance.dispatch(tr.scrollIntoView())\n position.value = null\n })\n}\n\nconst canMove = (direction: -1 | 1) => {\n const instance = view.value\n return !!instance && !!state.value && swapBlocks(direction)(instance.state)\n}\n\n/* dragging */\n\nlet start: { x: number; y: number; pointer: number; touch: boolean } | null = null\nlet range: SiblingRange | null = null\nlet scroller: HTMLElement | null = null\nlet scrollFrame = 0\n/** A copy of the dragged blocks that follows the pointer. */\nlet ghost: HTMLElement | null = null\n\nfunction showGhost(moving: SiblingRange) {\n const instance = view.value\n const host = root.value\n if (!instance || !host) return\n ghost = document.createElement('div')\n ghost.className = 'dou-editor__surface dou-editor__ghost'\n ghost.setAttribute('aria-hidden', 'true')\n let width = 0\n for (const block of blocksIn(moving)) {\n const element = instance.nodeDOM(block.pos) as HTMLElement | null\n if (!element) continue\n width = Math.max(width, element.getBoundingClientRect().width)\n const copy = element.cloneNode(true) as HTMLElement\n copy.classList.remove('is-selected')\n for (const node of [copy, ...copy.querySelectorAll('[id], .is-selected')]) {\n node.removeAttribute('id')\n node.classList.remove('is-selected')\n }\n ghost.append(copy)\n }\n ghost.style.width = `${Math.min(width, 360)}px`\n host.append(ghost)\n moveGhost()\n}\n\nfunction moveGhost() {\n if (!ghost) return\n // above a finger, which would hide it; below and right of a mouse pointer\n const y = start?.touch ? lastY - ghost.offsetHeight - 24 : lastY + 12\n ghost.style.transform = `translate(${lastX + 12}px, ${y}px)`\n}\n\nfunction onGripDown(event: PointerEvent) {\n if (event.button !== 0) return\n start = {\n x: event.clientX,\n y: event.clientY,\n pointer: event.pointerId,\n touch: event.pointerType === 'touch',\n }\n ;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)\n}\n\nfunction onGripMove(event: PointerEvent) {\n if (!start || event.pointerId !== start.pointer) return\n lastX = event.clientX\n lastY = event.clientY\n if (!dragging.value) {\n // a finger wobbles more than a mouse while tapping\n const slop = start.touch ? 8 : 4\n if (Math.hypot(event.clientX - start.x, event.clientY - start.y) < slop) return\n range = selectTarget()\n if (!range) return stopDrag()\n dragging.value = true\n scroller = root.value && scrollParent(root.value)\n window.addEventListener('keydown', onDragKey, true)\n showGhost(range)\n autoScroll()\n }\n moveGhost()\n updateDrop()\n}\n\nfunction onGripUp(event: PointerEvent) {\n if (!start || event.pointerId !== start.pointer) return\n if (dragging.value) finishDrag()\n else if (menuOpen.value) menuOpen.value = false\n else {\n selectTarget()\n menuOpen.value = true\n }\n start = null\n}\n\nfunction onDragKey(event: KeyboardEvent) {\n if (event.key !== 'Escape') return\n event.preventDefault()\n event.stopPropagation()\n stopDrag()\n}\n\n/** Beside a column, past its edge: a new column there, when the set takes one more. */\n/** How far into the last column a drop still makes a new column after it. */\nconst LAST_COLUMN_EDGE = 16\n\nfunction columnDrop(content: HTMLElement, moving: SiblingRange, box: DOMRect): Drop | null {\n const instance = view.value\n const group = content.closest<HTMLElement>(COLUMN_GROUP)\n const column = group?.parentElement\n const rowGroup = column?.parentElement\n const rowId = rowGroup?.parentElement?.dataset.blockId\n if (!instance || !column || !rowGroup || !rowId) return null\n const columns = childBlocks(rowGroup)\n const index = columns.indexOf(column)\n if (index < 0 || !sideBySide(columns)) return null\n const rect = column.getBoundingClientRect()\n // right of the last column there may be no room (the editor's edge): its last strip counts\n const right = index === columns.length - 1 ? rect.right - LAST_COLUMN_EDGE : rect.right\n const at = lastX < rect.left ? index : lastX > right ? index + 1 : -1\n if (at < 0) return null\n const row = findBlockById(instance.state.doc, rowId)\n if (!row || !moveRangeToNewColumn(moving, row.pos, at)(instance.state)) return null\n const gap =\n columns.length > 1\n ? columns[1]!.getBoundingClientRect().left - columns[0]!.getBoundingClientRect().right\n : 0\n const x =\n at === 0\n ? columns[0]!.getBoundingClientRect().left - gap / 2\n : at === columns.length\n ? columns.at(-1)!.getBoundingClientRect().right - 1\n : (columns[at - 1]!.getBoundingClientRect().right +\n columns[at]!.getBoundingClientRect().left) /\n 2\n const rowRect = rowGroup.getBoundingClientRect()\n return {\n pos: row.pos,\n top: rowRect.top - box.top,\n left: x - box.left,\n width: 0,\n height: rowRect.height,\n column: { row: rowId, index: at },\n }\n}\n\nfunction updateDrop() {\n const instance = view.value\n const host = root.value\n if (!instance || !host || !range) return\n const content = contentAt(instance, lastY, lastX)\n const id = content && blockElementOf(content)?.dataset.blockId\n const info = id ? findBlockById(instance.state.doc, id) : null\n if (!content || !info) return (drop.value = null)\n const box = host.getBoundingClientRect()\n const beside = columnDrop(content, range, box)\n if (beside) return (drop.value = beside)\n const rect = content.getBoundingClientRect()\n const span = contentSpan(content)\n const below = lastY > rect.top + rect.height / 2\n let pos: number\n let y: number\n let left = span.left\n if (!below) {\n pos = info.pos\n y = rect.top\n } else if (info.group) {\n // the lower half of a block with children: in front of its first child\n pos = info.contentPos + info.content.nodeSize + 1\n y = rect.bottom\n const child = blockElementOf(content)?.querySelector<HTMLElement>(\n ':scope > .dou-editor__group > .dou-editor__block > .dou-editor__content',\n )\n left = child ? contentSpan(child).left : span.left\n } else {\n pos = info.pos + info.node.nodeSize\n y = blockElementOf(content)!.getBoundingClientRect().bottom\n }\n if (!moveRangeTo(range, pos)(instance.state)) return (drop.value = null)\n // to the end of the text column, which a reading width can end before the editor\n drop.value = { pos, top: y - box.top, left: left - box.left, width: span.right - left }\n}\n\nfunction autoScroll() {\n scrollFrame = requestAnimationFrame(() => {\n if (!dragging.value) return\n const edge = 48\n const top = scroller ? scroller.getBoundingClientRect().top : 0\n const bottom = scroller ? scroller.getBoundingClientRect().bottom : window.innerHeight\n let speed = 0\n if (lastY < top + edge) speed = -Math.ceil(((top + edge - lastY) / edge) * 16)\n else if (lastY > bottom - edge) speed = Math.ceil(((lastY - bottom + edge) / edge) * 16)\n if (speed) {\n if (scroller) scroller.scrollTop += speed\n else window.scrollBy(0, speed)\n updateDrop()\n }\n autoScroll()\n })\n}\n\nfunction finishDrag() {\n const instance = view.value\n const spot = drop.value\n const moving = range\n stopDrag()\n if (!instance || !spot || !moving) return\n const ids = blocksIn(moving).map((block) => block.node.attrs.id as string)\n const row = spot.column && findBlockById(instance.state.doc, spot.column.row)\n const command = spot.column\n ? row && moveRangeToNewColumn(moving, row.pos, spot.column.index)\n : moveRangeTo(moving, spot.pos)\n if (!command || !command(instance.state, instance.dispatch)) return\n selectBlocks(ids[0]!, ids.at(-1)!)(instance.state, instance.dispatch)\n instance.focus()\n}\n\nfunction stopDrag() {\n dragging.value = false\n drop.value = null\n range = null\n start = null\n ghost?.remove()\n ghost = null\n if (scrollFrame) cancelAnimationFrame(scrollFrame)\n scrollFrame = 0\n window.removeEventListener('keydown', onDragKey, true)\n}\n\nwatch(menuOpen, (value) => {\n if (value) return\n if (touch.value) scheduleFollow()\n else if (!root.value?.matches(':hover')) position.value = null\n})\n</script>\n\n<template>\n <div\n v-show=\"visible\"\n ref=\"handle\"\n :class=\"['dou-editor__handle', { 'is-compact': compact, 'is-table': table }]\"\n :style=\"\n position\n ? {\n top: `${position.top}px`,\n left: `${position.left}px`,\n '--dou-editor-line': `${position.height}px`,\n '--dou-editor-handle-shift': `${shift}px`,\n }\n : undefined\n \"\n @mousedown.prevent\n >\n <button\n type=\"button\"\n tabindex=\"-1\"\n class=\"dou-editor__handle-button dou-editor__add\"\n :aria-label=\"messages.addBlock\"\n :title=\"messages.addBlock\"\n @click=\"add\"\n >\n <PlusIcon />\n </button>\n <DouDropdown\n v-model:open=\"menuOpen\"\n trigger=\"manual\"\n placement=\"bottom-start\"\n class=\"dou-editor-menu\"\n >\n <button\n type=\"button\"\n tabindex=\"-1\"\n class=\"dou-editor__handle-button dou-editor__grip\"\n :aria-label=\"messages.dragHandle\"\n :title=\"messages.dragHandle\"\n @pointerdown=\"onGripDown\"\n @pointermove=\"onGripMove\"\n @pointerup=\"onGripUp\"\n @pointercancel=\"stopDrag\"\n >\n <GripVerticalIcon />\n </button>\n <template #menu>\n <DouDropdownSub :title=\"messages.turnInto\">\n <DouDropdownItem\n v-for=\"option in turnOptions\"\n :key=\"option.key\"\n @click=\"turnInto(option)\"\n >\n <template #prefix><component :is=\"option.icon\" /></template>\n {{ labelOf(option.label, messages) }}\n <template v-if=\"current && isCurrent(option, current.type, current.props)\" #suffix>\n <CheckIcon />\n </template>\n </DouDropdownItem>\n </DouDropdownSub>\n <template v-if=\"current\">\n <component\n :is=\"entry\"\n v-for=\"(entry, index) in kit.blockMenu\"\n :key=\"index\"\n :block=\"current\"\n />\n </template>\n <DouDropdownItem :shortcut=\"touch ? undefined : 'mod+d'\" @click=\"duplicate\">\n <template #prefix><CopyIcon /></template>\n {{ messages.duplicate }}\n </DouDropdownItem>\n <DouDropdownItem\n :disabled=\"!canMove(-1)\"\n :shortcut=\"touch ? undefined : 'mod+shift+up'\"\n @click=\"move(-1)\"\n >\n <template #prefix><ArrowUpIcon /></template>\n {{ messages.moveUp }}\n </DouDropdownItem>\n <DouDropdownItem\n :disabled=\"!canMove(1)\"\n :shortcut=\"touch ? undefined : 'mod+shift+down'\"\n @click=\"move(1)\"\n >\n <template #prefix><ArrowDownIcon /></template>\n {{ messages.moveDown }}\n </DouDropdownItem>\n <DouDropdownItem\n divided\n tone=\"danger\"\n :shortcut=\"touch ? undefined : 'delete'\"\n @click=\"remove\"\n >\n <template #prefix><TrashIcon /></template>\n {{ messages.delete }}\n </DouDropdownItem>\n </template>\n </DouDropdown>\n </div>\n <div\n v-if=\"drop\"\n :class=\"['dou-editor__drop', { 'is-vertical': drop.column }]\"\n :style=\"\n drop.column\n ? { top: `${drop.top}px`, left: `${drop.left}px`, height: `${drop.height}px` }\n : { top: `${drop.top}px`, left: `${drop.left}px`, width: `${drop.width}px` }\n \"\n />\n</template>\n"],"mappings":""}
|