@dou-ui/editor 0.1.0-alpha.3 → 0.1.0-alpha.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/collaboration/binding.js +371 -57
- package/dist/collaboration/binding.js.map +1 -1
- package/dist/collaboration/cursors.js +42 -10
- package/dist/collaboration/cursors.js.map +1 -1
- package/dist/collaboration/index.js +61 -11
- package/dist/collaboration/index.js.map +1 -1
- package/dist/collaboration/inline-diff.js +138 -0
- package/dist/collaboration/inline-diff.js.map +1 -0
- package/dist/collaboration/merged-props.js +152 -0
- package/dist/collaboration/merged-props.js.map +1 -0
- package/dist/collaboration/order.js +41 -1
- package/dist/collaboration/order.js.map +1 -1
- package/dist/collaboration/table.js +64 -25
- package/dist/collaboration/table.js.map +1 -1
- package/dist/collaboration/text.js +213 -1
- package/dist/collaboration/text.js.map +1 -1
- package/dist/components/block-handle.js.map +1 -1
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js +127 -17
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/components/slash-choices.js +6 -0
- package/dist/components/slash-choices.js.map +1 -0
- package/dist/components/slash-choices.vue_vue_type_script_setup_true_lang.js +56 -0
- package/dist/components/slash-choices.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/components/slash-menu.js.map +1 -1
- package/dist/components/slash-menu.vue_vue_type_script_setup_true_lang.js +185 -20
- package/dist/components/slash-menu.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/core/block-selection.js +32 -4
- package/dist/core/block-selection.js.map +1 -1
- package/dist/core/blocks.js +21 -3
- package/dist/core/blocks.js.map +1 -1
- package/dist/core/cjk.js +54 -0
- package/dist/core/cjk.js.map +1 -0
- package/dist/core/commands.js +125 -13
- package/dist/core/commands.js.map +1 -1
- package/dist/core/comments.js +85 -3
- package/dist/core/comments.js.map +1 -1
- package/dist/core/convert.js +3 -3
- package/dist/core/convert.js.map +1 -1
- package/dist/core/extension.js +6 -2
- package/dist/core/extension.js.map +1 -1
- package/dist/core/model.js +10 -3
- package/dist/core/model.js.map +1 -1
- package/dist/core/output.js +26 -10
- package/dist/core/output.js.map +1 -1
- package/dist/core/prepare.js +12 -5
- package/dist/core/prepare.js.map +1 -1
- package/dist/core/schema.js.map +1 -1
- package/dist/core/transaction.js +19 -4
- package/dist/core/transaction.js.map +1 -1
- package/dist/define-block.js +8 -4
- package/dist/define-block.js.map +1 -1
- package/dist/document.js +59 -4
- package/dist/document.js.map +1 -1
- package/dist/dom.js +109 -13
- package/dist/dom.js.map +1 -1
- package/dist/editor.js.map +1 -1
- package/dist/editor.vue_vue_type_script_setup_true_lang.js +6 -5
- package/dist/editor.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/editor2.js.map +1 -1
- package/dist/extensions/callout/html.js +5 -4
- package/dist/extensions/callout/html.js.map +1 -1
- package/dist/extensions/columns/column-picker.js +6 -0
- package/dist/extensions/columns/column-picker.js.map +1 -0
- package/dist/extensions/columns/column-picker.vue_vue_type_script_setup_true_lang.js +57 -0
- package/dist/extensions/columns/column-picker.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/columns/columns-controls.js +6 -0
- package/dist/extensions/columns/columns-controls.js.map +1 -0
- package/dist/extensions/columns/columns-controls.vue_vue_type_script_setup_true_lang.js +341 -0
- package/dist/extensions/columns/columns-controls.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/columns/html.js +34 -0
- package/dist/extensions/columns/html.js.map +1 -0
- package/dist/extensions/columns/index.js +57 -0
- package/dist/extensions/columns/index.js.map +1 -0
- package/dist/extensions/columns/keys.js +53 -0
- package/dist/extensions/columns/keys.js.map +1 -0
- package/dist/extensions/columns/plugin.js +213 -0
- package/dist/extensions/columns/plugin.js.map +1 -0
- package/dist/extensions/columns/schema.js +58 -0
- package/dist/extensions/columns/schema.js.map +1 -0
- package/dist/extensions/columns/select-columns.js +6 -0
- package/dist/extensions/columns/select-columns.js.map +1 -0
- package/dist/extensions/columns/select-columns.vue_vue_type_script_setup_true_lang.js +71 -0
- package/dist/extensions/columns/select-columns.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/editor-kit.js +3 -1
- package/dist/extensions/editor-kit.js.map +1 -1
- package/dist/extensions/list-html.js +1 -1
- package/dist/extensions/list-html.js.map +1 -1
- package/dist/extensions/table/plugin.js +33 -1
- package/dist/extensions/table/plugin.js.map +1 -1
- package/dist/extensions/table/schema.js +5 -1
- package/dist/extensions/table/schema.js.map +1 -1
- package/dist/extensions/table/table-controls.js.map +1 -1
- package/dist/extensions/table/table-controls.vue_vue_type_script_setup_true_lang.js +80 -9
- package/dist/extensions/table/table-controls.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/extensions/table/view.js +181 -3
- package/dist/extensions/table/view.js.map +1 -1
- package/dist/flow/board-block.js +6 -0
- package/dist/flow/board-block.js.map +1 -0
- package/dist/flow/board-block.vue_vue_type_script_setup_true_lang.js +659 -0
- package/dist/flow/board-block.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/flow/board.js +221 -0
- package/dist/flow/board.js.map +1 -0
- package/dist/flow/index.js +173 -0
- package/dist/flow/index.js.map +1 -0
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/locale.js +78 -6
- package/dist/locale.js.map +1 -1
- package/dist/markdown/cjk-friendly.js +62 -0
- package/dist/markdown/cjk-friendly.js.map +1 -0
- package/dist/markdown/index.js +4 -3
- package/dist/markdown/index.js.map +1 -1
- package/dist/style.css +1 -1
- package/dist/style.js +2 -0
- package/dist/types/collaboration/binding.d.ts +12 -0
- package/dist/types/collaboration/cursors.d.ts +29 -1
- package/dist/types/collaboration/index.d.ts +53 -6
- package/dist/types/collaboration/inline-diff.d.ts +9 -0
- package/dist/types/collaboration/merged-props.d.ts +20 -0
- package/dist/types/collaboration/order.d.ts +5 -0
- package/dist/types/collaboration/table.d.ts +5 -1
- package/dist/types/collaboration/text.d.ts +20 -0
- package/dist/types/components/slash-choices.vue.d.ts +18 -0
- package/dist/types/core/blocks.d.ts +10 -0
- package/dist/types/core/cjk.d.ts +23 -0
- package/dist/types/core/commands.d.ts +17 -2
- package/dist/types/core/comments.d.ts +39 -3
- package/dist/types/core/convert.d.ts +10 -2
- package/dist/types/core/extension.d.ts +58 -4
- package/dist/types/core/model.d.ts +6 -1
- package/dist/types/core/prepare.d.ts +16 -2
- package/dist/types/core/schema.d.ts +1 -1
- package/dist/types/core/transaction.d.ts +6 -0
- package/dist/types/define-block.d.ts +16 -4
- package/dist/types/document.d.ts +5 -2
- package/dist/types/dom.d.ts +41 -4
- package/dist/types/editor.d.ts +15 -1
- package/dist/types/editor.vue.d.ts +24 -0
- package/dist/types/extensions/columns/column-picker.vue.d.ts +10 -0
- package/dist/types/extensions/columns/columns-controls.vue.d.ts +3 -0
- package/dist/types/extensions/columns/html.d.ts +10 -0
- package/dist/types/extensions/columns/index.d.ts +9 -0
- package/dist/types/extensions/columns/keys.d.ts +6 -0
- package/dist/types/extensions/columns/plugin.d.ts +28 -0
- package/dist/types/extensions/columns/schema.d.ts +17 -0
- package/dist/types/extensions/columns/select-columns.vue.d.ts +13 -0
- package/dist/types/extensions/editor-kit.d.ts +4 -1
- package/dist/types/extensions/table/view.d.ts +36 -2
- package/dist/types/flow/board-block.vue.d.ts +16 -0
- package/dist/types/flow/board.d.ts +53 -0
- package/dist/types/flow/index.d.ts +65 -0
- package/dist/types/index.d.ts +29 -4
- package/dist/types/locale.d.ts +34 -0
- package/dist/types/markdown/cjk-friendly.d.ts +6 -0
- package/dist/types/markdown/index.d.ts +11 -4
- package/dist/types/use-comments.d.ts +1 -0
- package/dist/use-comments.js +63 -9
- package/dist/use-comments.js.map +1 -1
- package/package.json +14 -5
package/dist/dom.js
CHANGED
|
@@ -1,23 +1,76 @@
|
|
|
1
1
|
// src/dom.ts
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
*/
|
|
8
|
-
function
|
|
9
|
-
const
|
|
2
|
+
var isBlock = (element) => element.classList.contains("dou-editor__block");
|
|
3
|
+
/** The blocks right inside a container element: the editing area or a group. */
|
|
4
|
+
var childBlocks = (container) => Array.from(container.children).filter(isBlock);
|
|
5
|
+
var contentOf = (block) => block.querySelector(":scope > .dou-editor__content");
|
|
6
|
+
var groupOf = (block) => block.querySelector(":scope > .dou-editor__group");
|
|
7
|
+
/** Where a block starts: its content's top, or its children's for a block without visible content (columns). */
|
|
8
|
+
function topOf(block) {
|
|
9
|
+
const content = contentOf(block);
|
|
10
|
+
return (content?.getClientRects().length ? content : groupOf(block) ?? block).getBoundingClientRect().top;
|
|
11
|
+
}
|
|
12
|
+
/** The last of `blocks` whose top is above `y` (the first when none is). */
|
|
13
|
+
function lastAbove(blocks, y) {
|
|
10
14
|
let low = 0;
|
|
11
|
-
let high =
|
|
12
|
-
let found =
|
|
15
|
+
let high = blocks.length - 1;
|
|
16
|
+
let found = 0;
|
|
13
17
|
while (low <= high) {
|
|
14
18
|
const middle = low + high >> 1;
|
|
15
|
-
if (
|
|
19
|
+
if (topOf(blocks[middle]) <= y) {
|
|
16
20
|
found = middle;
|
|
17
21
|
low = middle + 1;
|
|
18
22
|
} else high = middle - 1;
|
|
19
23
|
}
|
|
20
|
-
return
|
|
24
|
+
return blocks[found];
|
|
25
|
+
}
|
|
26
|
+
/** The group of a set of columns, around an element in one of them. */
|
|
27
|
+
var COLUMNS_GROUP = ".dou-editor__content--columns + .dou-editor__group";
|
|
28
|
+
/** The group of one column (its blocks). */
|
|
29
|
+
var COLUMN_GROUP = ".dou-editor__content--column + .dou-editor__group";
|
|
30
|
+
/** Whether columns sit side by side; a narrow editor stacks them. */
|
|
31
|
+
function sideBySide(columns) {
|
|
32
|
+
return columns.length > 1 && Math.abs(columns[0].getBoundingClientRect().top - columns[1].getBoundingClientRect().top) < 1;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The column at `x` among side-by-side ones: the gap before a column
|
|
36
|
+
* belongs to it (its handle sits there), what is left of the first to the
|
|
37
|
+
* first and right of the last to the last.
|
|
38
|
+
*/
|
|
39
|
+
function columnAtX(columns, x) {
|
|
40
|
+
let index = 0;
|
|
41
|
+
for (let next = 1; next < columns.length; next++) if (x >= columns[next - 1].getBoundingClientRect().right) index = next;
|
|
42
|
+
return index;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* The content element (paragraph, heading, …) at height `y` in viewport
|
|
46
|
+
* coordinates: the last one whose top is above it, nested ones included.
|
|
47
|
+
* Blocks follow each other from top to bottom, so a binary search finds
|
|
48
|
+
* the block, then the same again among its children. In a set of
|
|
49
|
+
* columns, `x` picks the column (stacked columns go by `y` too).
|
|
50
|
+
*/
|
|
51
|
+
function contentAt(view, y, x) {
|
|
52
|
+
let container = view.dom;
|
|
53
|
+
for (;;) {
|
|
54
|
+
const blocks = childBlocks(container);
|
|
55
|
+
if (!blocks.length) return null;
|
|
56
|
+
const block = lastAbove(blocks, y);
|
|
57
|
+
const content = contentOf(block);
|
|
58
|
+
const group = groupOf(block);
|
|
59
|
+
if (group && content?.classList.contains("dou-editor__content--columns")) {
|
|
60
|
+
const columns = childBlocks(group);
|
|
61
|
+
if (!columns.length) return null;
|
|
62
|
+
const inner = groupOf(x !== void 0 && sideBySide(columns) ? columns[columnAtX(columns, x)] : lastAbove(columns, y));
|
|
63
|
+
if (!inner) return null;
|
|
64
|
+
container = inner;
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
const first = group?.getClientRects().length ? childBlocks(group)[0] : void 0;
|
|
68
|
+
if (group && first && topOf(first) <= y) {
|
|
69
|
+
container = group;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
return content;
|
|
73
|
+
}
|
|
21
74
|
}
|
|
22
75
|
/** The block element around a content element. */
|
|
23
76
|
function blockElementOf(content) {
|
|
@@ -43,11 +96,54 @@ function firstLine(content) {
|
|
|
43
96
|
height
|
|
44
97
|
};
|
|
45
98
|
}
|
|
99
|
+
/** A top-level table: only it reaches into the margins (a table in a column or a list doesn't). */
|
|
100
|
+
var isWideTable = (content) => content.classList.contains("dou-editor__content--table") && !!content.parentElement?.parentElement?.classList.contains("dou-editor__surface");
|
|
101
|
+
/**
|
|
102
|
+
* Where a block's content goes across: its box, less what a top-level
|
|
103
|
+
* table's frame reaches into the margins (its start padding and end margin),
|
|
104
|
+
* which keeps the table in line with the text. The editor lays out left to
|
|
105
|
+
* right, so the logical start and end are the left and right.
|
|
106
|
+
*/
|
|
107
|
+
function contentSpan(content) {
|
|
108
|
+
const rect = content.getBoundingClientRect();
|
|
109
|
+
if (!isWideTable(content)) return {
|
|
110
|
+
left: rect.left,
|
|
111
|
+
right: rect.right
|
|
112
|
+
};
|
|
113
|
+
const viewport = content.querySelector(":scope > .dou-editor-table__viewport");
|
|
114
|
+
const start = Number.parseFloat(getComputedStyle(viewport ?? content).paddingInlineStart) || 0;
|
|
115
|
+
const end = Number.parseFloat(getComputedStyle(content).marginInlineEnd) || 0;
|
|
116
|
+
return {
|
|
117
|
+
left: rect.left + start,
|
|
118
|
+
right: rect.right + end
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Where the block handle goes: before the content, or before what shows of
|
|
123
|
+
* a table, whose left edge moves out into the margin as it scrolls.
|
|
124
|
+
*/
|
|
125
|
+
function handleLeft(content) {
|
|
126
|
+
const rect = content.getBoundingClientRect();
|
|
127
|
+
if (!isWideTable(content)) return rect.left;
|
|
128
|
+
const table = content.querySelector("table");
|
|
129
|
+
return table ? Math.max(rect.left, table.getBoundingClientRect().left) : contentSpan(content).left;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* How far the block handle's bubble moves in over the text: by as much as
|
|
133
|
+
* its `start` (its left edge, "+" included when it can come out) lacks of
|
|
134
|
+
* `clip` plus 2px. Next to a table, a bubble that has to move in goes on
|
|
135
|
+
* past `clear`, right of the table's row handles, rather than onto them.
|
|
136
|
+
*/
|
|
137
|
+
function bubbleShift(start, clip, clear) {
|
|
138
|
+
const shift = Math.max(0, Math.ceil(clip + 2 - start));
|
|
139
|
+
if (!shift || clear === void 0) return shift;
|
|
140
|
+
return Math.max(shift, Math.ceil(clear - start));
|
|
141
|
+
}
|
|
46
142
|
/** The right edge of the editor's text column: the surface less its padding (a reading width). */
|
|
47
143
|
function columnRight(surface) {
|
|
48
144
|
const padding = Number.parseFloat(getComputedStyle(surface).paddingRight) || 0;
|
|
49
145
|
return surface.getBoundingClientRect().right - padding;
|
|
50
146
|
}
|
|
51
|
-
export { blockElementOf, columnRight, contentAt, firstLine, scrollParent };
|
|
147
|
+
export { COLUMNS_GROUP, COLUMN_GROUP, blockElementOf, bubbleShift, childBlocks, columnAtX, columnRight, contentAt, contentSpan, firstLine, handleLeft, scrollParent, sideBySide };
|
|
52
148
|
|
|
53
149
|
//# sourceMappingURL=dom.js.map
|
package/dist/dom.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dom.js","names":[],"sources":["../src/dom.ts"],"sourcesContent":["import type { EditorView } from 'prosemirror-view'\n\n/**\n * The content element (paragraph, heading, …) at height `y` in viewport\n * coordinates: the last one whose top is above it. Contents follow each\n * other from top to bottom in document order, nested ones included, so\n * a binary search does.\n */\nexport function contentAt(view: EditorView, y: number): HTMLElement | null {\n const list = view.dom.querySelectorAll<HTMLElement>('.dou-editor__content')\n let low = 0\n let high = list.length - 1\n let found = -1\n while (low <= high) {\n const middle = (low + high) >> 1\n if (list[middle]!.getBoundingClientRect().top <= y) {\n found = middle\n low = middle + 1\n } else high = middle - 1\n }\n return list[Math.max(found, 0)] ?? null\n}\n\n/** The block element around a content element. */\nexport function blockElementOf(content: HTMLElement): HTMLElement | null {\n return content.closest<HTMLElement>('.dou-editor__block')\n}\n\n/** The nearest ancestor that scrolls vertically, or `null` for the page. */\nexport function scrollParent(element: HTMLElement): HTMLElement | null {\n for (let node = element.parentElement; node; node = node.parentElement) {\n const { overflowY } = getComputedStyle(node)\n if ((overflowY === 'auto' || overflowY === 'scroll') && node.scrollHeight > node.clientHeight)\n return node\n }\n return null\n}\n\n/** Where the first line of a content element sits: its top and height. */\nexport function firstLine(content: HTMLElement): { top: number; height: number } {\n const rect = content.getBoundingClientRect()\n const style = getComputedStyle(content)\n const lineHeight = Number.parseFloat(style.lineHeight)\n const padding = Number.parseFloat(style.paddingTop) || 0\n const height = Number.isFinite(lineHeight) ? Math.min(lineHeight, rect.height) : rect.height\n return { top: rect.top + (height < rect.height ? padding : 0), height }\n}\n\n/** The right edge of the editor's text column: the surface less its padding (a reading width). */\nexport function columnRight(surface: HTMLElement): number {\n const padding = Number.parseFloat(getComputedStyle(surface).paddingRight) || 0\n return surface.getBoundingClientRect().right - padding\n}\n"],"mappings":";;;;;;;AAQA,SAAgB,UAAU,MAAkB,GAA+B;CACzE,MAAM,OAAO,KAAK,IAAI,iBAA8B,sBAAsB;CAC1E,IAAI,MAAM;CACV,IAAI,OAAO,KAAK,SAAS;CACzB,IAAI,QAAQ;CACZ,OAAO,OAAO,MAAM;EAClB,MAAM,SAAU,MAAM,QAAS;EAC/B,IAAI,KAAK,OAAO,CAAE,sBAAsB,CAAC,CAAC,OAAO,GAAG;GAClD,QAAQ;GACR,MAAM,SAAS;EACjB,OAAO,OAAO,SAAS;CACzB;CACA,OAAO,KAAK,KAAK,IAAI,OAAO,CAAC,MAAM;AACrC;;AAGA,SAAgB,eAAe,SAA0C;CACvE,OAAO,QAAQ,QAAqB,oBAAoB;AAC1D;;AAGA,SAAgB,aAAa,SAA0C;CACrE,KAAK,IAAI,OAAO,QAAQ,eAAe,MAAM,OAAO,KAAK,eAAe;EACtE,MAAM,EAAE,cAAc,iBAAiB,IAAI;EAC3C,KAAK,cAAc,UAAU,cAAc,aAAa,KAAK,eAAe,KAAK,cAC/E,OAAO;CACX;CACA,OAAO;AACT;;AAGA,SAAgB,UAAU,SAAuD;CAC/E,MAAM,OAAO,QAAQ,sBAAsB;CAC3C,MAAM,QAAQ,iBAAiB,OAAO;CACtC,MAAM,aAAa,OAAO,WAAW,MAAM,UAAU;CACrD,MAAM,UAAU,OAAO,WAAW,MAAM,UAAU,KAAK;CACvD,MAAM,SAAS,OAAO,SAAS,UAAU,IAAI,KAAK,IAAI,YAAY,KAAK,MAAM,IAAI,KAAK;CACtF,OAAO;EAAE,KAAK,KAAK,OAAO,SAAS,KAAK,SAAS,UAAU;EAAI;CAAO;AACxE;;AAGA,SAAgB,YAAY,SAA8B;CACxD,MAAM,UAAU,OAAO,WAAW,iBAAiB,OAAO,CAAC,CAAC,YAAY,KAAK;CAC7E,OAAO,QAAQ,sBAAsB,CAAC,CAAC,QAAQ;AACjD"}
|
|
1
|
+
{"version":3,"file":"dom.js","names":[],"sources":["../src/dom.ts"],"sourcesContent":["import type { EditorView } from 'prosemirror-view'\n\nconst isBlock = (element: Element): element is HTMLElement =>\n element.classList.contains('dou-editor__block')\n\n/** The blocks right inside a container element: the editing area or a group. */\nexport const childBlocks = (container: Element): HTMLElement[] =>\n Array.from(container.children).filter(isBlock)\n\nconst contentOf = (block: HTMLElement) =>\n block.querySelector<HTMLElement>(':scope > .dou-editor__content')\n\nconst groupOf = (block: HTMLElement) =>\n block.querySelector<HTMLElement>(':scope > .dou-editor__group')\n\n/** Where a block starts: its content's top, or its children's for a block without visible content (columns). */\nfunction topOf(block: HTMLElement): number {\n const content = contentOf(block)\n const shown = content?.getClientRects().length ? content : (groupOf(block) ?? block)\n return shown.getBoundingClientRect().top\n}\n\n/** The last of `blocks` whose top is above `y` (the first when none is). */\nfunction lastAbove(blocks: HTMLElement[], y: number): HTMLElement {\n let low = 0\n let high = blocks.length - 1\n let found = 0\n while (low <= high) {\n const middle = (low + high) >> 1\n if (topOf(blocks[middle]!) <= y) {\n found = middle\n low = middle + 1\n } else high = middle - 1\n }\n return blocks[found]!\n}\n\n/** The group of a set of columns, around an element in one of them. */\nexport const COLUMNS_GROUP = '.dou-editor__content--columns + .dou-editor__group'\n/** The group of one column (its blocks). */\nexport const COLUMN_GROUP = '.dou-editor__content--column + .dou-editor__group'\n\n/** Whether columns sit side by side; a narrow editor stacks them. */\nexport function sideBySide(columns: HTMLElement[]): boolean {\n return (\n columns.length > 1 &&\n Math.abs(columns[0]!.getBoundingClientRect().top - columns[1]!.getBoundingClientRect().top) < 1\n )\n}\n\n/**\n * The column at `x` among side-by-side ones: the gap before a column\n * belongs to it (its handle sits there), what is left of the first to the\n * first and right of the last to the last.\n */\nexport function columnAtX(columns: HTMLElement[], x: number): number {\n let index = 0\n for (let next = 1; next < columns.length; next++)\n if (x >= columns[next - 1]!.getBoundingClientRect().right) index = next\n return index\n}\n\n/**\n * The content element (paragraph, heading, …) at height `y` in viewport\n * coordinates: the last one whose top is above it, nested ones included.\n * Blocks follow each other from top to bottom, so a binary search finds\n * the block, then the same again among its children. In a set of\n * columns, `x` picks the column (stacked columns go by `y` too).\n */\nexport function contentAt(view: EditorView, y: number, x?: number): HTMLElement | null {\n let container: Element = view.dom\n for (;;) {\n const blocks = childBlocks(container)\n if (!blocks.length) return null\n const block = lastAbove(blocks, y)\n const content = contentOf(block)\n const group = groupOf(block)\n if (group && content?.classList.contains('dou-editor__content--columns')) {\n const columns = childBlocks(group)\n if (!columns.length) return null\n const column =\n x !== undefined && sideBySide(columns)\n ? columns[columnAtX(columns, x)]!\n : lastAbove(columns, y)\n const inner = groupOf(column)\n if (!inner) return null\n container = inner\n continue\n }\n // the children, when shown (a closed toggle hides them) and `y` reaches them\n const first = group?.getClientRects().length ? childBlocks(group)[0] : undefined\n if (group && first && topOf(first) <= y) {\n container = group\n continue\n }\n return content\n }\n}\n\n/** The block element around a content element. */\nexport function blockElementOf(content: HTMLElement): HTMLElement | null {\n return content.closest<HTMLElement>('.dou-editor__block')\n}\n\n/** The nearest ancestor that scrolls vertically, or `null` for the page. */\nexport function scrollParent(element: HTMLElement): HTMLElement | null {\n for (let node = element.parentElement; node; node = node.parentElement) {\n const { overflowY } = getComputedStyle(node)\n if ((overflowY === 'auto' || overflowY === 'scroll') && node.scrollHeight > node.clientHeight)\n return node\n }\n return null\n}\n\n/** Where the first line of a content element sits: its top and height. */\nexport function firstLine(content: HTMLElement): { top: number; height: number } {\n const rect = content.getBoundingClientRect()\n const style = getComputedStyle(content)\n const lineHeight = Number.parseFloat(style.lineHeight)\n const padding = Number.parseFloat(style.paddingTop) || 0\n const height = Number.isFinite(lineHeight) ? Math.min(lineHeight, rect.height) : rect.height\n return { top: rect.top + (height < rect.height ? padding : 0), height }\n}\n\n/** A top-level table: only it reaches into the margins (a table in a column or a list doesn't). */\nconst isWideTable = (content: HTMLElement) =>\n content.classList.contains('dou-editor__content--table') &&\n !!content.parentElement?.parentElement?.classList.contains('dou-editor__surface')\n\n/**\n * Where a block's content goes across: its box, less what a top-level\n * table's frame reaches into the margins (its start padding and end margin),\n * which keeps the table in line with the text. The editor lays out left to\n * right, so the logical start and end are the left and right.\n */\nexport function contentSpan(content: HTMLElement): { left: number; right: number } {\n const rect = content.getBoundingClientRect()\n if (!isWideTable(content)) return { left: rect.left, right: rect.right }\n const viewport = content.querySelector<HTMLElement>(':scope > .dou-editor-table__viewport')\n const start = Number.parseFloat(getComputedStyle(viewport ?? content).paddingInlineStart) || 0\n const end = Number.parseFloat(getComputedStyle(content).marginInlineEnd) || 0\n return {\n left: rect.left + start,\n right: rect.right + end,\n }\n}\n\n/**\n * Where the block handle goes: before the content, or before what shows of\n * a table, whose left edge moves out into the margin as it scrolls.\n */\nexport function handleLeft(content: HTMLElement): number {\n const rect = content.getBoundingClientRect()\n if (!isWideTable(content)) return rect.left\n const table = content.querySelector('table')\n return table ? Math.max(rect.left, table.getBoundingClientRect().left) : contentSpan(content).left\n}\n\n/**\n * How far the block handle's bubble moves in over the text: by as much as\n * its `start` (its left edge, \"+\" included when it can come out) lacks of\n * `clip` plus 2px. Next to a table, a bubble that has to move in goes on\n * past `clear`, right of the table's row handles, rather than onto them.\n */\nexport function bubbleShift(start: number, clip: number, clear?: number): number {\n const shift = Math.max(0, Math.ceil(clip + 2 - start))\n if (!shift || clear === undefined) return shift\n return Math.max(shift, Math.ceil(clear - start))\n}\n\n/** The right edge of the editor's text column: the surface less its padding (a reading width). */\nexport function columnRight(surface: HTMLElement): number {\n const padding = Number.parseFloat(getComputedStyle(surface).paddingRight) || 0\n return surface.getBoundingClientRect().right - padding\n}\n"],"mappings":";AAEA,IAAM,WAAW,YACf,QAAQ,UAAU,SAAS,mBAAmB;;AAGhD,IAAa,eAAe,cAC1B,MAAM,KAAK,UAAU,QAAQ,CAAC,CAAC,OAAO,OAAO;AAE/C,IAAM,aAAa,UACjB,MAAM,cAA2B,+BAA+B;AAElE,IAAM,WAAW,UACf,MAAM,cAA2B,6BAA6B;;AAGhE,SAAS,MAAM,OAA4B;CACzC,MAAM,UAAU,UAAU,KAAK;CAE/B,QADc,SAAS,eAAe,CAAC,CAAC,SAAS,UAAW,QAAQ,KAAK,KAAK,MAAA,CACjE,sBAAsB,CAAC,CAAC;AACvC;;AAGA,SAAS,UAAU,QAAuB,GAAwB;CAChE,IAAI,MAAM;CACV,IAAI,OAAO,OAAO,SAAS;CAC3B,IAAI,QAAQ;CACZ,OAAO,OAAO,MAAM;EAClB,MAAM,SAAU,MAAM,QAAS;EAC/B,IAAI,MAAM,OAAO,OAAQ,KAAK,GAAG;GAC/B,QAAQ;GACR,MAAM,SAAS;EACjB,OAAO,OAAO,SAAS;CACzB;CACA,OAAO,OAAO;AAChB;;AAGA,IAAa,gBAAgB;;AAE7B,IAAa,eAAe;;AAG5B,SAAgB,WAAW,SAAiC;CAC1D,OACE,QAAQ,SAAS,KACjB,KAAK,IAAI,QAAQ,EAAE,CAAE,sBAAsB,CAAC,CAAC,MAAM,QAAQ,EAAE,CAAE,sBAAsB,CAAC,CAAC,GAAG,IAAI;AAElG;;;;;;AAOA,SAAgB,UAAU,SAAwB,GAAmB;CACnE,IAAI,QAAQ;CACZ,KAAK,IAAI,OAAO,GAAG,OAAO,QAAQ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AAK,QAAQ,KAAK,CAAC;AACjD;;AAGA,SAAgB,YAAY,SAA8B;CACxD,MAAM,UAAU,OAAO,WAAW,iBAAiB,OAAO,CAAC,CAAC,YAAY,KAAK;CAC7E,OAAO,QAAQ,sBAAsB,CAAC,CAAC,QAAQ;AACjD"}
|
package/dist/editor.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"editor.js","names":[],"sources":["../src/editor.ts"],"sourcesContent":["import type { EditorState, Command, Plugin } from 'prosemirror-state'\nimport type { EditorView } from 'prosemirror-view'\nimport type { CommentAction, CommentAuthor, CommentThread } from 'dou-ui'\nimport {\n inject,\n onBeforeUnmount,\n provide,\n shallowReactive,\n shallowRef,\n type ComputedRef,\n type InjectionKey,\n type ShallowRef,\n} from 'vue'\nimport type { CommentAnchor, CommentRange } from './core/comments'\nimport type { EditorExtension, ResolvedEditorExtensions } from './core/extension'\nimport type { BlockChanges } from './core/changes'\nimport type { Block, EditorDocument, PartialBlock } from './core/model'\nimport type { EditorSearchQuery } from './core/search'\nimport type {\n BlockEdge,\n BlockPatch,\n BlockPlacement,\n EditorTransaction,\n EditorTransactionMeta,\n} from './core/transaction'\nimport type { EditorMessages, EditorMessagesOverride } from './locale'\n\nexport interface EditorProps {\n /**\n * The document, bound with `v-model`. With collaboration the shared\n * document is the source of truth: leave `v-model` out and read changes\n * from the `change` event.\n */\n modelValue?: EditorDocument<PartialBlock>\n /**\n * Blocks, marks, shortcuts and menu entries. Defaults to `[editorKit()]`;\n * read once, when the editor mounts.\n */\n extensions?: (EditorExtension | EditorExtension[])[]\n /** Show the document without editing it. Links stay clickable. */\n readonly?: boolean\n /** The built-in find panel (`Ctrl/⌘+F`). Off, the keys are left to the browser. On by default. */\n searchable?: boolean\n /** The hint in the empty block under the cursor. */\n placeholder?: string\n /** Replace any of the built-in texts. */\n messages?: EditorMessagesOverride\n /** The accessible name of the editing area. */\n ariaLabel?: string\n /** Focus the editor once it is mounted. */\n autofocus?: boolean\n /**\n * Extra ProseMirror plugins, e.g. for collaboration. They run before\n * the built-in ones, so their keys win.\n */\n plugins?: Plugin[]\n /** Leave out the built-in undo history (collaboration brings its own). */\n history?: boolean\n /** Undo and redo commands to replace the built-in ones. */\n undo?: Command\n redo?: Command\n /**\n * The comment threads, bound with `v-model:comments`. The text a thread\n * is about carries its id in the document; leave this out to turn\n * comments off.\n */\n comments?: CommentThread[]\n /** Who is commenting. Without it comments can be read but not written. */\n author?: CommentAuthor\n /** The id of the thread shown beside its text, bound with `v-model:activeComment`. */\n activeComment?: string | null\n /** Whether threads can be started and answered; also while `readonly`. Defaults to `true`. */\n commentable?: boolean\n /**\n * An older version of the document, e.g. one the app saved. The editor\n * then shows the document read-only, with what changed since marked:\n * blocks added and removed, and in each changed block the text added\n * and removed. Blocks are matched by `id`; a block without one shows as\n * removed.\n */\n compare?: EditorDocument<PartialBlock> | null\n /**\n * The block with the cursor and the selected blocks, bound with\n * `v-model:selection`. Setting it puts the cursor at the end of `block`,\n * or selects `blocks` when there are several siblings, without focusing.\n */\n selection?: EditorSelection\n}\n\n/**\n * Who made a change: `'external'` for a new `v-model` value or\n * `setBlocks`, `'remote'` for a collaborator's, `'restore'` for `restore`,\n * `'undo'` and `'redo'`, or\n * the `origin` given to `transact`. Typing and the editor's own commands\n * leave it out.\n */\nexport type EditorOrigin = 'external' | 'remote' | 'restore' | 'undo' | 'redo' | (string & {})\n\n/** What a change to the document did, as the `transaction` event hands it over. */\nexport interface EditorTransactionResult {\n /** The document after the change, as `update:modelValue` gets it next. */\n blocks: Block[]\n /** The blocks the change touched, by id. */\n changes: BlockChanges\n meta: {\n origin?: EditorOrigin\n /** Whether undo can take the change back: not for others' changes, nor for undo and redo themselves. */\n history: boolean\n }\n}\n\n/** Where the selection is, by block. */\nexport interface EditorSelection {\n /** The innermost block at the cursor (the moving end of a selection); `null` while none is. */\n block: string | null\n /**\n * The blocks the selection covers: the selected blocks, or the blocks a\n * text selection runs across, at the level they share.\n */\n blocks: string[]\n}\n\nexport interface EditorEmits {\n 'update:modelValue': [document: EditorDocument]\n /** The document changed: typing, formatting, moving blocks. */\n change: [document: EditorDocument]\n /** Every change to the document, with what it touched; `update:modelValue` follows. */\n transaction: [result: EditorTransactionResult]\n /** The cursor moved to another block, or other blocks were selected. */\n 'update:selection': [selection: EditorSelection]\n /** Before a link opens (Ctrl / ⌘ + click, or a click while read-only); `preventDefault()` keeps it from opening in a new tab. */\n linkOpen: [event: EditorLinkOpenEvent]\n focus: [event: FocusEvent]\n blur: [event: FocusEvent]\n 'update:comments': [threads: CommentThread[]]\n 'update:activeComment': [id: string | null]\n /** A change to the comments made here: to send to a server, notify people, keep a log. */\n commentAction: [action: CommentAction]\n}\n\n/**\n * Before a link is followed. `preventDefault()` stops the editor from\n * opening it in a new tab, e.g. to use the app's router or ask first.\n */\nexport interface EditorLinkOpenEvent {\n /** The address as the text's `link` holds it. */\n link: string\n /** The id of the block the link is in. */\n block: string\n defaultPrevented: boolean\n preventDefault: () => void\n}\n\nexport interface EditorExpose {\n /** The ProseMirror view, once mounted. */\n readonly view: EditorView | null\n focus: () => void\n blur: () => void\n /** The current document. */\n getBlocks: () => Block[]\n /** Replace the document. The change does not go into the undo history. */\n setBlocks: (blocks: PartialBlock[]) => void\n /** The current document as HTML, written by the extensions (see `blocksToHTML`). */\n getHTML: () => string\n /** Replace the document with HTML, read like pasted HTML. */\n setHTML: (html: string) => void\n /** Run a ProseMirror command, e.g. one of the exported ones. */\n run: (command: Command) => boolean\n /**\n * Opens the find panel (`Ctrl/⌘+F`), with a query put in; with `replace`\n * in it, the replace box opens too. `false` when `searchable` is off or\n * the editor is not mounted.\n */\n openSearch: (query?: Partial<EditorSearchQuery>) => boolean\n /** Closes the find panel; `false` when it was not open. */\n closeSearch: () => boolean\n /**\n * Make changes by blocks and ids, applied together as one undo step.\n * Returns what happened, or `null` when nothing changed. Works while\n * read-only too.\n */\n transact: (\n fn: (tr: EditorTransaction) => void,\n meta?: EditorTransactionMeta,\n ) => EditorTransactionResult | null\n /** One block, or `null` when there is none with that id. */\n getBlock: (id: string) => Block | null\n /**\n * Insert blocks, by default after the block with the cursor. Returns the\n * new blocks' ids (an id already in use is replaced). One undo step.\n */\n insertBlocks: (blocks: PartialBlock[], placement?: BlockPlacement) => string[]\n /** Change a block's type, props (merged), content or children. One undo step. */\n updateBlock: (id: string, patch: BlockPatch) => boolean\n /** Remove blocks with their children. One undo step. */\n removeBlocks: (ids: string[]) => boolean\n /** Move blocks, in the order given, before, after or into another block. One undo step. */\n moveBlocks: (ids: string[], placement: BlockPlacement) => boolean\n /** Focus the editor with the cursor at the start or end (the default) of a block, scrolled into view. */\n focusBlock: (id: string, edge?: BlockEdge) => boolean\n /** The selection by block, as `v-model:selection` has it. */\n getSelection: () => EditorSelection\n undo: () => boolean\n redo: () => boolean\n readonly canUndo: boolean\n readonly canRedo: boolean\n /**\n * Start a thread on the selected text and open the box for its first\n * comment; with the cursor on commented text, open that thread to reply.\n */\n comment: () => boolean\n /** Where each thread is anchored; `null` for a thread whose text was deleted. */\n getCommentAnchors: () => Record<string, CommentAnchor | null>\n /**\n * Replace the document with `doc`, e.g. an older version, as one\n * change undo takes back. With collaboration only the blocks that differ\n * are written, and everyone sees it. The `transaction` event has origin\n * `'restore'`. Like the other methods it works while `readonly`; it is\n * the one change allowed while comparing. Returns `false` when nothing\n * differs.\n */\n restore: (doc: EditorDocument<PartialBlock>) => boolean\n /** With `compare`: scroll to the next change after the one last shown; `false` when there is none. */\n nextChange: () => boolean\n /** With `compare`: scroll to the change before the one last shown. */\n previousChange: () => boolean\n}\n\n/** The comments, as the parts around the editing area see them. */\nexport interface EditorComments {\n /** Comments are on: there are threads to show. */\n enabled: ComputedRef<boolean>\n /** Threads can be started and answered. */\n writable: ComputedRef<boolean>\n threads: ComputedRef<readonly CommentThread[]>\n author: ComputedRef<CommentAuthor | undefined>\n /** The thread shown beside its text. */\n active: ComputedRef<string | null>\n /** The text a new thread is being started on. */\n pending: ShallowRef<CommentRange | null>\n /** Goes up when the open thread's reply box should take focus. */\n focusRequest: ShallowRef<number>\n /** The selected text, also in a read-only editor; `null` when there is none. */\n selection: () => CommentRange | null\n /** Start a thread on the selected text, or open the one the cursor is in. */\n start: () => boolean\n apply: (action: CommentAction) => void\n open: (id: string | null) => void\n /** Close the card, dropping a thread not yet started. */\n close: () => void\n}\n\n/** What the parts around the editing area (menus, handle, toolbar) share. */\nexport interface EditorContext {\n view: ShallowRef<EditorView | null>\n /** Updated on every transaction, so computeds follow the selection too. */\n state: ShallowRef<EditorState | null>\n focused: ShallowRef<boolean>\n /** Blocks are being dragged by the handle. */\n dragging: ShallowRef<boolean>\n editable: ComputedRef<boolean>\n messages: ComputedRef<EditorMessages>\n /** What the extensions contribute: schema, menu entries, toolbar toggles. */\n kit: ResolvedEditorExtensions\n /** The element the overlays are positioned against. */\n root: ShallowRef<HTMLElement | null>\n comments: EditorComments\n}\n\nexport const editorKey: InjectionKey<EditorContext> = Symbol('DouEditor')\n\nconst toolbarMenusKey: InjectionKey<Set<ShallowRef<boolean>>> = Symbol('DouEditorToolbarMenus')\n\n/** For the formatting toolbar: the open state of the menus in it. */\nexport function provideToolbarMenus(): Set<ShallowRef<boolean>> {\n const menus = shallowReactive(new Set<ShallowRef<boolean>>())\n provide(toolbarMenusKey, menus)\n return menus\n}\n\n/**\n * The open state for a menu in the formatting toolbar (an extension's\n * `toolbar` component), to bind with `v-model:open`: the toolbar stays\n * while the menu is open, though the focus has left the editor.\n */\nexport function useToolbarMenu(): ShallowRef<boolean> {\n const open = shallowRef(false)\n const menus = inject(toolbarMenusKey, null)\n if (menus) {\n menus.add(open)\n onBeforeUnmount(() => menus.delete(open))\n }\n return open\n}\n\n/** The editor around a block component, for its messages, state and view. */\nexport function useEditor(): EditorContext {\n const context = inject(editorKey, null)\n if (!context) throw new Error('[@dou-ui/editor] useEditor() must be called inside <DouEditor>')\n return context\n}\n"],"mappings":";;AA6QA,IAAa,YAAyC,OAAO,WAAW;AAExE,IAAM,kBAA0D,OAAO,uBAAuB;;AAG9F,SAAgB,sBAAgD;CAC9D,MAAM,QAAQ,gCAAgB,IAAI,IAAyB,CAAC;CAC5D,QAAQ,iBAAiB,KAAK;CAC9B,OAAO;AACT;;;;;;AAOA,SAAgB,iBAAsC;CACpD,MAAM,OAAO,WAAW,KAAK;CAC7B,MAAM,QAAQ,OAAO,iBAAiB,IAAI;CAC1C,IAAI,OAAO;EACT,MAAM,IAAI,IAAI;EACd,sBAAsB,MAAM,OAAO,IAAI,CAAC;CAC1C;CACA,OAAO;AACT;;AAGA,SAAgB,YAA2B;CACzC,MAAM,UAAU,OAAO,WAAW,IAAI;CACtC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,gEAAgE;CAC9F,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"editor.js","names":[],"sources":["../src/editor.ts"],"sourcesContent":["import type { EditorState, Command, Plugin } from 'prosemirror-state'\nimport type { EditorView } from 'prosemirror-view'\nimport type { CommentAction, CommentAuthor, CommentThread } from 'dou-ui'\nimport {\n inject,\n onBeforeUnmount,\n provide,\n shallowReactive,\n shallowRef,\n type ComputedRef,\n type InjectionKey,\n type ShallowRef,\n} from 'vue'\nimport type { CommentAnchor, CommentRange } from './core/comments'\nimport type { EditorExtension, ResolvedEditorExtensions } from './core/extension'\nimport type { BlockChanges } from './core/changes'\nimport type { Block, EditorDocument, PartialBlock } from './core/model'\nimport type { EditorSearchQuery } from './core/search'\nimport type {\n BlockEdge,\n BlockPatch,\n BlockPlacement,\n EditorTransaction,\n EditorTransactionMeta,\n} from './core/transaction'\nimport type { EditorMessages, EditorMessagesOverride } from './locale'\n\nexport interface EditorProps {\n /**\n * The document, bound with `v-model`. With collaboration the shared\n * document is the source of truth: leave `v-model` out and read changes\n * from the `change` event.\n */\n modelValue?: EditorDocument<PartialBlock>\n /**\n * Blocks, marks, shortcuts and menu entries. Defaults to `[editorKit()]`;\n * read once, when the editor mounts.\n */\n extensions?: (EditorExtension | EditorExtension[])[]\n /** Show the document without editing it. Links stay clickable. */\n readonly?: boolean\n /** The built-in find panel (`Ctrl/⌘+F`). Off, the keys are left to the browser. On by default. */\n searchable?: boolean\n /** The hint in the empty block under the cursor. */\n placeholder?: string\n /** Replace any of the built-in texts. */\n messages?: EditorMessagesOverride\n /** The accessible name of the editing area. */\n ariaLabel?: string\n /** Focus the editor once it is mounted. */\n autofocus?: boolean\n /**\n * Extra ProseMirror plugins, e.g. for collaboration. They run before\n * the built-in ones, so their keys win.\n */\n plugins?: Plugin[]\n /** Leave out the built-in undo history (collaboration brings its own). */\n history?: boolean\n /** Undo and redo commands to replace the built-in ones. */\n undo?: Command\n redo?: Command\n /**\n * The comment threads, bound with `v-model:comments`. The text a thread\n * is about carries its id in the document; leave this out to turn\n * comments off.\n */\n comments?: CommentThread[]\n /** Who is commenting. Without it comments can be read but not written. */\n author?: CommentAuthor\n /** The id of the thread shown beside its text, bound with `v-model:activeComment`. */\n activeComment?: string | null\n /** Whether threads can be started and answered; also while `readonly`. Defaults to `true`. */\n commentable?: boolean\n /**\n * An older version of the document, e.g. one the app saved. The editor\n * then shows the document read-only, with what changed since marked:\n * blocks added and removed, and in each changed block the text added\n * and removed. Blocks are matched by `id`; a block without one shows as\n * removed.\n */\n compare?: EditorDocument<PartialBlock> | null\n /**\n * The block with the cursor and the selected blocks, bound with\n * `v-model:selection`. Setting it puts the cursor at the end of `block`,\n * or selects `blocks` when there are several siblings, without focusing.\n */\n selection?: EditorSelection\n}\n\n/**\n * Who made a change: `'external'` for a new `v-model` value or\n * `setBlocks`, `'remote'` for a collaborator's, `'restore'` for `restore`,\n * `'undo'` and `'redo'`, or\n * the `origin` given to `transact`. Typing and the editor's own commands\n * leave it out.\n */\nexport type EditorOrigin = 'external' | 'remote' | 'restore' | 'undo' | 'redo' | (string & {})\n\n/** What a change to the document did, as the `transaction` event hands it over. */\nexport interface EditorTransactionResult {\n /** The document after the change, as `update:modelValue` gets it next. */\n blocks: Block[]\n /** The blocks the change touched, by id. */\n changes: BlockChanges\n meta: {\n origin?: EditorOrigin\n /** Whether undo can take the change back: not for others' changes, nor for undo and redo themselves. */\n history: boolean\n }\n}\n\n/** Where the selection is, by block. */\nexport interface EditorSelection {\n /** The innermost block at the cursor (the moving end of a selection); `null` while none is. */\n block: string | null\n /**\n * The blocks the selection covers: the selected blocks, or the blocks a\n * text selection runs across, at the level they share.\n */\n blocks: string[]\n}\n\nexport interface EditorEmits {\n 'update:modelValue': [document: EditorDocument]\n /** The document changed: typing, formatting, moving blocks. */\n change: [document: EditorDocument]\n /** Every change to the document, with what it touched; `update:modelValue` follows. */\n transaction: [result: EditorTransactionResult]\n /** The cursor moved to another block, or other blocks were selected. */\n 'update:selection': [selection: EditorSelection]\n /** Before a link opens (Ctrl / ⌘ + click, or a click while read-only); `preventDefault()` keeps it from opening in a new tab. */\n linkOpen: [event: EditorLinkOpenEvent]\n focus: [event: FocusEvent]\n blur: [event: FocusEvent]\n 'update:comments': [threads: CommentThread[]]\n 'update:activeComment': [id: string | null]\n /** A change to the comments made here: to send to a server, notify people, keep a log. */\n commentAction: [action: CommentAction]\n}\n\n/**\n * Before a link is followed. `preventDefault()` stops the editor from\n * opening it in a new tab, e.g. to use the app's router or ask first.\n */\nexport interface EditorLinkOpenEvent {\n /** The address as the text's `link` holds it. */\n link: string\n /** The id of the block the link is in. */\n block: string\n defaultPrevented: boolean\n preventDefault: () => void\n}\n\nexport interface EditorExpose {\n /** The ProseMirror view, once mounted. */\n readonly view: EditorView | null\n focus: () => void\n blur: () => void\n /** The current document. */\n getBlocks: () => Block[]\n /** Replace the document. The change does not go into the undo history. */\n setBlocks: (blocks: PartialBlock[]) => void\n /** The current document as HTML, written by the extensions (see `blocksToHTML`). */\n getHTML: () => string\n /** Replace the document with HTML, read like pasted HTML. */\n setHTML: (html: string) => void\n /** Run a ProseMirror command, e.g. one of the exported ones. */\n run: (command: Command) => boolean\n /**\n * Opens the find panel (`Ctrl/⌘+F`), with a query put in; with `replace`\n * in it, the replace box opens too. `false` when `searchable` is off or\n * the editor is not mounted.\n */\n openSearch: (query?: Partial<EditorSearchQuery>) => boolean\n /** Closes the find panel; `false` when it was not open. */\n closeSearch: () => boolean\n /**\n * Make changes by blocks and ids, applied together as one undo step.\n * Returns what happened, or `null` when nothing changed. Works while\n * read-only too.\n */\n transact: (\n fn: (tr: EditorTransaction) => void,\n meta?: EditorTransactionMeta,\n ) => EditorTransactionResult | null\n /** One block, or `null` when there is none with that id. */\n getBlock: (id: string) => Block | null\n /**\n * Insert blocks, by default after the block with the cursor. Returns the\n * new blocks' ids (an id already in use is replaced). One undo step.\n */\n insertBlocks: (blocks: PartialBlock[], placement?: BlockPlacement) => string[]\n /** Change a block's type, props (merged), content or children. One undo step. */\n updateBlock: (id: string, patch: BlockPatch) => boolean\n /** Remove blocks with their children. One undo step. */\n removeBlocks: (ids: string[]) => boolean\n /** Move blocks, in the order given, before, after or into another block. One undo step. */\n moveBlocks: (ids: string[], placement: BlockPlacement) => boolean\n /** Focus the editor with the cursor at the start or end (the default) of a block, scrolled into view. */\n focusBlock: (id: string, edge?: BlockEdge) => boolean\n /** The selection by block, as `v-model:selection` has it. */\n getSelection: () => EditorSelection\n undo: () => boolean\n redo: () => boolean\n readonly canUndo: boolean\n readonly canRedo: boolean\n /**\n * Start a thread on the selected text and open the box for its first\n * comment; with the cursor on commented text, open that thread to reply.\n */\n comment: () => boolean\n /** Where each thread is anchored; `null` for a thread whose text was deleted. */\n getCommentAnchors: () => Record<string, CommentAnchor | null>\n /**\n * Scroll the anchor of comment thread `id` into view (opening any collapsed\n * toggles around it). Returns `false` when comments are off or `id` has no\n * anchor in the document.\n */\n scrollToComment: (id: string, options?: ScrollIntoViewOptions) => boolean\n /**\n * Replace the document with `doc`, e.g. an older version, as one\n * change undo takes back. With collaboration only the blocks that differ\n * are written, and everyone sees it. The `transaction` event has origin\n * `'restore'`. Like the other methods it works while `readonly`; it is\n * the one change allowed while comparing. Returns `false` when nothing\n * differs.\n */\n restore: (doc: EditorDocument<PartialBlock>) => boolean\n /** With `compare`: scroll to the next change after the one last shown; `false` when there is none. */\n nextChange: () => boolean\n /** With `compare`: scroll to the change before the one last shown. */\n previousChange: () => boolean\n}\n\n/** The comments, as the parts around the editing area see them. */\nexport interface EditorComments {\n /** Comments are on: there are threads to show. */\n enabled: ComputedRef<boolean>\n /** Threads can be started and answered. */\n writable: ComputedRef<boolean>\n threads: ComputedRef<readonly CommentThread[]>\n author: ComputedRef<CommentAuthor | undefined>\n /** The thread shown beside its text. */\n active: ComputedRef<string | null>\n /** The text a new thread is being started on. */\n pending: ShallowRef<CommentRange | null>\n /** Goes up when the open thread's reply box should take focus. */\n focusRequest: ShallowRef<number>\n /** The selected text, also in a read-only editor; `null` when there is none. */\n selection: () => CommentRange | null\n /** Start a thread on the selected text, or open the one the cursor is in. */\n start: () => boolean\n /**\n * Make a change to the threads. A new thread goes on the text being\n * commented on; with `anchored`, its block already put it inside (see\n * `BlockCommentsSpec`). A removed thread is taken off its text or block.\n */\n apply: (action: CommentAction, options?: { anchored?: boolean }) => void\n /** Open a thread: beside its text, or inside its block, which watches `active`. */\n open: (id: string | null) => void\n /** Close the card, dropping a thread not yet started. */\n close: () => void\n}\n\n/** What the parts around the editing area (menus, handle, toolbar) share. */\nexport interface EditorContext {\n view: ShallowRef<EditorView | null>\n /** Updated on every transaction, so computeds follow the selection too. */\n state: ShallowRef<EditorState | null>\n focused: ShallowRef<boolean>\n /** Blocks are being dragged by the handle. */\n dragging: ShallowRef<boolean>\n editable: ComputedRef<boolean>\n messages: ComputedRef<EditorMessages>\n /** What the extensions contribute: schema, menu entries, toolbar toggles. */\n kit: ResolvedEditorExtensions\n /** The element the overlays are positioned against. */\n root: ShallowRef<HTMLElement | null>\n comments: EditorComments\n}\n\nexport const editorKey: InjectionKey<EditorContext> = Symbol('DouEditor')\n\nconst toolbarMenusKey: InjectionKey<Set<ShallowRef<boolean>>> = Symbol('DouEditorToolbarMenus')\n\n/** For the formatting toolbar: the open state of the menus in it. */\nexport function provideToolbarMenus(): Set<ShallowRef<boolean>> {\n const menus = shallowReactive(new Set<ShallowRef<boolean>>())\n provide(toolbarMenusKey, menus)\n return menus\n}\n\n/**\n * The open state for a menu in the formatting toolbar (an extension's\n * `toolbar` component), to bind with `v-model:open`: the toolbar stays\n * while the menu is open, though the focus has left the editor.\n */\nexport function useToolbarMenu(): ShallowRef<boolean> {\n const open = shallowRef(false)\n const menus = inject(toolbarMenusKey, null)\n if (menus) {\n menus.add(open)\n onBeforeUnmount(() => menus.delete(open))\n }\n return open\n}\n\n/** The editor around a block component, for its messages, state and view. */\nexport function useEditor(): EditorContext {\n const context = inject(editorKey, null)\n if (!context) throw new Error('[@dou-ui/editor] useEditor() must be called inside <DouEditor>')\n return context\n}\n"],"mappings":";;AAyRA,IAAa,YAAyC,OAAO,WAAW;AAExE,IAAM,kBAA0D,OAAO,uBAAuB;;AAG9F,SAAgB,sBAAgD;CAC9D,MAAM,QAAQ,gCAAgB,IAAI,IAAyB,CAAC;CAC5D,QAAQ,iBAAiB,KAAK;CAC9B,OAAO;AACT;;;;;;AAOA,SAAgB,iBAAsC;CACpD,MAAM,OAAO,WAAW,KAAK;CAC7B,MAAM,QAAQ,OAAO,iBAAiB,IAAI;CAC1C,IAAI,OAAO;EACT,MAAM,IAAI,IAAI;EACd,sBAAsB,MAAM,OAAO,IAAI,CAAC;CAC1C;CACA,OAAO;AACT;;AAGA,SAAgB,YAA2B;CACzC,MAAM,UAAU,OAAO,WAAW,IAAI;CACtC,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,gEAAgE;CAC9F,OAAO;AACT"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { useEditorMessages } from "./locale.js";
|
|
1
2
|
import { blocksToDoc, docToBlocks } from "./core/model.js";
|
|
2
3
|
import { resolveEditorExtensions } from "./core/extension.js";
|
|
3
4
|
import { selectBlocks } from "./core/block-selection.js";
|
|
@@ -22,7 +23,6 @@ import { writeHTML } from "./core/output.js";
|
|
|
22
23
|
import { componentMounter, vueNodeView } from "./define-block.js";
|
|
23
24
|
import { editorKit } from "./extensions/editor-kit.js";
|
|
24
25
|
import { readBlocks } from "./document.js";
|
|
25
|
-
import { useEditorMessages } from "./locale.js";
|
|
26
26
|
import { useEditorComments } from "./use-comments.js";
|
|
27
27
|
import { isApplePlatform, useGlobalConfig, useNamespace } from "dou-ui";
|
|
28
28
|
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createVNode, defineComponent, getCurrentInstance, h, nextTick, normalizeClass, onBeforeUnmount, onMounted, openBlock, provide, ref, renderList, resolveDynamicComponent, shallowRef, toDisplayString, toRaw, unref, useId, useTemplateRef, watch } from "vue";
|
|
@@ -89,13 +89,13 @@ var editor_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defineCom
|
|
|
89
89
|
setup(__props, { expose: __expose, emit: __emit }) {
|
|
90
90
|
const props = __props;
|
|
91
91
|
const emit = __emit;
|
|
92
|
-
const
|
|
92
|
+
const messages = useEditorMessages(() => props.messages);
|
|
93
|
+
const kit = resolveEditorExtensions(props.extensions ?? [editorKit()], () => messages.value);
|
|
93
94
|
const stopWatchingExtensions = watch(() => props.extensions, () => {
|
|
94
95
|
console.warn("[@dou-ui/editor] `extensions` changed after mount and is ignored: it is read once. Create the list once outside the template, or give the editor a new `key` to rebuild it.");
|
|
95
96
|
stopWatchingExtensions();
|
|
96
97
|
});
|
|
97
98
|
const ns = useNamespace("editor");
|
|
98
|
-
const messages = useEditorMessages(() => props.messages);
|
|
99
99
|
const config = useGlobalConfig();
|
|
100
100
|
const root = useTemplateRef("root");
|
|
101
101
|
const mount = useTemplateRef("mount");
|
|
@@ -114,7 +114,7 @@ var editor_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defineCom
|
|
|
114
114
|
return Array.isArray(blocks) ? docToBlocks(blocksToDoc(kit.schema, blocks)) : null;
|
|
115
115
|
});
|
|
116
116
|
const editable = computed(() => !props.readonly && !comparing.value);
|
|
117
|
-
const { comments, plugin: commentPlugin, anchors } = useEditorComments({
|
|
117
|
+
const { comments, plugin: commentPlugin, anchors, scrollToComment } = useEditorComments({
|
|
118
118
|
props,
|
|
119
119
|
emit,
|
|
120
120
|
view,
|
|
@@ -487,6 +487,7 @@ var editor_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defineCom
|
|
|
487
487
|
},
|
|
488
488
|
comment: () => comments.start(),
|
|
489
489
|
getCommentAnchors: anchors,
|
|
490
|
+
scrollToComment,
|
|
490
491
|
restore,
|
|
491
492
|
nextChange: () => goToChange(1),
|
|
492
493
|
previousChange: () => goToChange(-1)
|
|
@@ -499,7 +500,7 @@ var editor_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defineCom
|
|
|
499
500
|
if (!comments.enabled.value) return "";
|
|
500
501
|
const open = comments.threads.value.filter((thread) => !thread.resolved);
|
|
501
502
|
if (!open.length) return "";
|
|
502
|
-
let css = `${open.map((thread) => highlighted(thread.id)).join(",")}{background-color:var(--dou-editor-comment-bg);border-bottom-color:var(--dou-editor-comment-line)}`;
|
|
503
|
+
let css = `${open.map((thread) => highlighted(thread.id)).join(",")}{background-color:var(--dou-editor-comment-bg);border-bottom-color:var(--dou-editor-comment-line);--dou-editor-code-py:0;--dou-editor-code-bg:var(--dou-editor-comment-code-bg);--dou-editor-code-border:var(--dou-editor-comment-code-border)}`;
|
|
503
504
|
const active = comments.active.value;
|
|
504
505
|
if (active && open.some((thread) => thread.id === active)) css += `${highlighted(active)}{background-color:var(--dou-editor-comment-bg-active)}`;
|
|
505
506
|
return css;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"editor.vue_vue_type_script_setup_true_lang.js","names":["_openBlock","_createElementBlock","_normalizeClass","_unref","_createVNode","SearchBar","_createCommentVNode","_createElementVNode","_Fragment","BlockHandle","SlashMenu","BubbleToolbar","_renderList","_createBlock","_resolveDynamicComponent","_toDisplayString","CommentButton","CommentCard"],"sources":["../src/editor.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { isApplePlatform, useGlobalConfig, useNamespace } from 'dou-ui'\nimport { keymap } from 'prosemirror-keymap'\nimport { Plugin, type EditorState, type Transaction } from 'prosemirror-state'\nimport type { EditorView } from 'prosemirror-view'\nimport {\n computed,\n getCurrentInstance,\n nextTick,\n onBeforeUnmount,\n onMounted,\n provide,\n ref,\n shallowRef,\n toRaw,\n useTemplateRef,\n watch,\n h,\n useId,\n type Component,\n} from 'vue'\nimport BlockHandle from './components/block-handle.vue'\nimport BubbleToolbar from './components/bubble-toolbar.vue'\nimport SearchBar from './components/search-bar.vue'\nimport CommentButton from './components/comment-button.vue'\nimport CommentCard from './components/comment-card.vue'\nimport SlashMenu from './components/slash-menu.vue'\nimport { setFallbackHighlighter, type CodeHighlighter } from './core/highlight'\nimport { comparePlugin, compareKey } from './core/compare'\nimport {\n createEditorView,\n getBlocks,\n historyCommands,\n originKey,\n replaceBlocks,\n restoreBlocks,\n runCommand,\n setEditable,\n} from './core/editor'\nimport { diffBlocks } from './core/changes'\nimport { isRemote } from './core/plugins'\nimport { selectionOf, sameSelection } from './core/selection'\nimport { selectBlocks } from './core/block-selection'\nimport { applyEditorTransaction, EditorTransaction } from './core/transaction'\nimport {\n blocksToDoc,\n docToBlocks,\n type Block,\n type EditorDocument,\n type PartialBlock,\n} from './core/model'\nimport { resolveEditorExtensions } from './core/extension'\nimport {\n previewMatch,\n searchKey,\n searchPlugin,\n setSearch,\n type EditorSearchQuery,\n} from './core/search'\nimport { slashPlugin, type SlashState } from './core/slash'\nimport { writeHTML } from './core/output'\nimport { parseHTML } from './core/prepare'\nimport { componentMounter, vueNodeView } from './define-block'\nimport { editorKit } from './extensions/editor-kit'\nimport { readBlocks } from './document'\nimport {\n editorKey,\n type EditorEmits,\n type EditorExpose,\n type EditorProps,\n type EditorOrigin,\n type EditorLinkOpenEvent,\n type EditorSelection,\n type EditorTransactionResult,\n} from './editor'\nimport { useEditorMessages } from './locale'\nimport { useEditorComments } from './use-comments'\n\ndefineOptions({ name: 'DouEditor' })\n\nconst props = withDefaults(defineProps<EditorProps>(), {\n modelValue: undefined,\n extensions: undefined,\n readonly: false,\n searchable: true,\n placeholder: undefined,\n messages: undefined,\n ariaLabel: undefined,\n autofocus: false,\n plugins: undefined,\n history: true,\n undo: undefined,\n redo: undefined,\n selection: undefined,\n comments: undefined,\n author: undefined,\n activeComment: undefined,\n commentable: true,\n compare: undefined,\n})\nconst emit = defineEmits<EditorEmits>()\n\n// read once: changing the schema of a live editor would invalidate its document\nconst kit = resolveEditorExtensions(props.extensions ?? [editorKit()])\n// say so once, instead of silently keeping the old extensions\nconst stopWatchingExtensions = watch(\n () => props.extensions,\n () => {\n console.warn(\n '[@dou-ui/editor] `extensions` changed after mount and is ignored: it is read once. Create the list once outside the template, or give the editor a new `key` to rebuild it.',\n )\n stopWatchingExtensions()\n },\n)\n\nconst ns = useNamespace('editor')\nconst messages = useEditorMessages(() => props.messages)\nconst config = useGlobalConfig()\nconst root = useTemplateRef<HTMLElement>('root')\nconst mount = useTemplateRef<HTMLElement>('mount')\nconst view = shallowRef<EditorView | null>(null)\nconst state = shallowRef<EditorState | null>(null)\nconst focused = shallowRef(false)\nconst dragging = shallowRef(false)\n/** Showing what changed since an older version: read-only, without comments. */\nconst comparing = computed(() => !!props.compare)\n/**\n * The older version as whole blocks, matched to the current ones by id. A\n * block saved without an id gets a new one, so it shows as removed.\n */\nconst compareBlocks = computed(() => {\n const blocks = props.compare?.blocks\n return Array.isArray(blocks) ? docToBlocks(blocksToDoc(kit.schema, blocks)) : null\n})\nconst editable = computed(() => !props.readonly && !comparing.value)\n\nconst {\n comments,\n plugin: commentPlugin,\n anchors,\n} = useEditorComments({\n props,\n emit,\n view,\n provider: kit.comments,\n})\n\nconst context = { view, state, focused, dragging, editable, messages, root, kit, comments }\nprovide(editorKey, context)\n\n// block components render outside this component's tree: hand them the context\nconst appContext = getCurrentInstance()?.appContext ?? null\nconst mountComponent = componentMounter(appContext, [[editorKey, context]])\nconst componentViews = {\n ...Object.fromEntries(\n Object.entries(kit.schema.nodes)\n .filter(([, type]) => type.spec.component)\n .map(([name, type]) => [\n name,\n vueNodeView(type.spec.component as Component, appContext, [[editorKey, context]]),\n ]),\n ),\n ...Object.fromEntries(\n Object.entries(kit.componentViews).map(([name, create]) => [name, create(mountComponent)]),\n ),\n}\n\n// find and replace: the panel over the text, the matches marked in it\nconst searchOpen = ref(false)\nconst searchReplacing = ref(false)\nconst searchBar = useTemplateRef<InstanceType<typeof SearchBar>>('searchBar')\n/** Blocks that draw their own text, such as a code block in the code editor, are not searched. */\nconst searchSkip = (node: { type: { name: string } }) => node.type.name in kit.componentViews\n\n/** Opens the panel, with the replace box for `replace`. A selection on one line becomes the search. */\nfunction openSearch(replace = false, given?: Partial<EditorSearchQuery>) {\n const v = view.value\n if (!v || !props.searchable) return false\n const old = searchKey.getState(v.state)?.query ?? { search: '' }\n const query = { ...old, ...given }\n const { from, to, empty } = v.state.selection\n if (given?.search === undefined && !empty) {\n const text = v.state.doc.textBetween(from, to, '\\n')\n if (text && !text.includes('\\n')) query.search = text\n }\n if ((replace || given?.replace !== undefined) && editable.value) searchReplacing.value = true\n searchOpen.value = true\n v.dispatch(setSearch(v.state.tr, { query, active: true }))\n const preview = previewMatch(v.state)\n if (preview) v.dispatch(preview)\n void nextTick(() => searchBar.value?.focus(replace && editable.value ? 'replace' : 'find'))\n return true\n}\n\nfunction closeSearch() {\n const v = view.value\n if (!searchOpen.value || !v) return false\n searchOpen.value = false\n v.dispatch(setSearch(v.state.tr, { active: false }))\n v.focus()\n return true\n}\n\n/** Goes to the next (or previous) match; with the panel shut, opens it on the last search. */\nfunction findAgain(step: 1 | -1) {\n if (!searchOpen.value) {\n const v = view.value\n if (!v || !searchKey.getState(v.state)?.query.search || !openSearch()) return false\n }\n void nextTick(() => (step > 0 ? searchBar.value?.next() : searchBar.value?.previous()))\n return true\n}\n\nconst replaceKey = isApplePlatform() ? 'Mod-Alt-f' : 'Mod-h'\nconst searchKeys = keymap({\n 'Mod-f': () => openSearch(),\n [replaceKey]: () => openSearch(true),\n F3: () => findAgain(1),\n 'Mod-g': () => findAgain(1),\n 'Shift-F3': () => findAgain(-1),\n 'Mod-Shift-g': () => findAgain(-1),\n Escape: () => closeSearch(),\n})\n\nconst slash = shallowRef<SlashState | null>(null)\nconst slashMenu = useTemplateRef<InstanceType<typeof SlashMenu>>('slashMenu')\nconst bubble = useTemplateRef<InstanceType<typeof BubbleToolbar>>('bubble')\n\n// The document last sent through `v-model`: when the same object comes back,\n// it is not loaded again (that would move the cursor).\nlet emitted: EditorDocument | undefined\n\n// the result of the last change, for `transact` to hand back\nlet lastResult: EditorTransactionResult | null = null\n\nfunction onChange(current: EditorView, tr: Transaction, before: EditorState) {\n const blocks = getBlocks(current)\n const doc: EditorDocument = { version: 1, blocks }\n emitted = doc\n const history = tr.getMeta('history$') as { redo: boolean } | undefined\n const origin =\n (tr.getMeta(originKey) as EditorOrigin | undefined) ??\n (history ? (history.redo ? 'redo' : 'undo') : isRemote(tr) ? 'remote' : undefined)\n const meta: EditorTransactionResult['meta'] = {\n history:\n tr.getMeta('addToHistory') !== false &&\n origin !== 'remote' &&\n origin !== 'undo' &&\n origin !== 'redo',\n }\n if (origin !== undefined) meta.origin = origin\n lastResult = { blocks, changes: diffBlocks(before.doc, current.state.doc), meta }\n emit('transaction', lastResult)\n emit('update:modelValue', doc)\n emit('change', doc)\n}\n\nlet selection: EditorSelection = { block: null, blocks: [] }\n\nconst warn = (message: string) => {\n if (process.env.NODE_ENV !== 'production') console.warn(`[@dou-ui/editor] ${message}`)\n}\n\nconst lacksId = (blocks: PartialBlock[]): boolean =>\n blocks.some((block) => !block.id || lacksId(block.children ?? []))\n// until the editor is focused (or a block is, by the program) its selection is no cursor\nlet cursorKnown = false\n\nfunction onUpdate(current: EditorView) {\n state.value = current.state\n if (!cursorKnown) {\n if (!focused.value) return\n cursorKnown = true\n }\n const next = selectionOf(current.state)\n if (sameSelection(next, selection)) return\n selection = next\n emit('update:selection', next)\n}\n\n// a click on a link places the cursor; with Ctrl or ⌘ held, or while read-only, it opens the link\nconst openLinks = new Plugin({\n props: {\n handleDOMEvents: {\n click(clicked, event) {\n const link = (event.target as HTMLElement).closest<HTMLAnchorElement>('a.dou-editor__link')\n if (!link?.href || !(event.metaKey || event.ctrlKey || !clicked.editable)) return false\n event.preventDefault()\n const $pos = clicked.state.doc.resolve(clicked.posAtDOM(link, 0))\n let block = ''\n for (let depth = $pos.depth; depth > 0; depth--)\n if ($pos.node(depth).type.name === 'block') {\n block = $pos.node(depth).attrs.id as string\n break\n }\n const opening: EditorLinkOpenEvent = {\n link: link.getAttribute('href') ?? link.href,\n block,\n defaultPrevented: false,\n preventDefault() {\n this.defaultPrevented = true\n },\n }\n emit('linkOpen', opening)\n if (!opening.defaultPrevented) window.open(link.href, '_blank', 'noopener,noreferrer')\n return true\n },\n },\n },\n})\n\nonMounted(() => {\n const instance = createEditorView({\n element: mount.value!,\n kit,\n nodeViews: componentViews,\n // with collaboration the document comes from the shared document\n blocks: kit.externalDocument ? [] : readBlocks(props.modelValue),\n editable: editable.value,\n placeholder: {\n text: () => props.placeholder ?? messages.value.placeholder,\n heading: () => messages.value.headingPlaceholder,\n empty: () => props.placeholder ?? messages.value.emptyPlaceholder,\n },\n plugins: [\n ...(props.plugins ?? []),\n slashPlugin({\n onChange: (value) => (slash.value = value),\n onKey: (event) => slashMenu.value?.onKey(event) ?? false,\n }),\n keymap({\n 'Mod-k': () => bubble.value?.editLink() ?? false,\n 'Mod-Alt-m': () => comments.start(),\n // with the thread card open, Escape in the text closes it, and only that\n Escape: () => {\n if (!comments.pending.value && !comments.active.value) return false\n comments.close()\n return true\n },\n }),\n commentPlugin,\n comparePlugin({\n before: () => compareBlocks.value,\n label: () => messages.value.removedBlock,\n }),\n openLinks,\n searchPlugin({ skip: searchSkip }),\n ],\n keymaps: [searchKeys],\n history: props.history,\n undo: props.undo,\n redo: props.redo,\n attributes: () => {\n const attrs: Record<string, string> = {}\n if (props.ariaLabel) attrs['aria-label'] = props.ariaLabel\n if (!editable.value) attrs['aria-readonly'] = 'true'\n return attrs\n },\n onChange,\n onUpdate,\n })\n view.value = instance\n state.value = instance.state\n // code blocks without their own highlighter use the one DouCodeBlock uses\n watch(\n () =>\n (config.value.defaults as { DouCodeBlock?: { highlight?: CodeHighlighter } }).DouCodeBlock\n ?.highlight ?? null,\n (highlight) => setFallbackHighlighter(instance, highlight),\n { immediate: true },\n )\n instance.dom.addEventListener('focus', onFocus)\n instance.dom.addEventListener('blur', onBlur)\n if (props.autofocus) instance.focus()\n // blocks given without ids got them now: hand those back, so events' ids can be looked up\n const given = kit.externalDocument ? undefined : readBlocks(props.modelValue)\n if (given && lacksId(given)) {\n const doc: EditorDocument = { version: 1, blocks: getBlocks(instance) }\n emitted = doc\n emit('update:modelValue', doc)\n }\n})\n\nfunction onFocus(event: FocusEvent) {\n focused.value = true\n if (!cursorKnown && view.value) {\n cursorKnown = true\n const next = selectionOf(view.value.state)\n if (!sameSelection(next, selection)) {\n selection = next\n emit('update:selection', next)\n }\n }\n emit('focus', event)\n}\n\nfunction onBlur(event: FocusEvent) {\n focused.value = false\n emit('blur', event)\n}\n\nonBeforeUnmount(() => {\n view.value?.destroy()\n view.value = null\n})\n\nwatch(\n () => props.modelValue,\n (value) => {\n const current = view.value\n if (!current || value === undefined || kit.externalDocument || toRaw(value) === emitted) return\n replaceBlocks(current, readBlocks(value) ?? [])\n },\n)\n\nwatch(editable, (value) => view.value && setEditable(view.value, value))\nwatch(compareBlocks, () => view.value?.dispatch(view.value.state.tr.setMeta(compareKey, true)))\n\n/** The change last scrolled to, by its place among them. */\nlet changeIndex = -1\nwatch(\n () => props.compare,\n () => (changeIndex = -1),\n)\nfunction goToChange(step: 1 | -1) {\n const dom = view.value?.dom\n if (!dom || !props.compare) return false\n // a block's own mark, or the first piece of text changed in it\n const marks = [\n ...dom.querySelectorAll<HTMLElement>(\n '.dou-editor__diff-added, .dou-editor__diff-changed, .dou-editor__diff-removed-block, .dou-editor__diff-added-text, .dou-editor__diff-removed',\n ),\n ].filter((el, index, list) => {\n const block = el.closest('[data-block-id]')\n const previous = list[index - 1]\n return !previous || previous.closest('[data-block-id]') !== block || !block\n })\n const next = changeIndex + step\n const target = marks[next]\n if (!target) return false\n changeIndex = next\n target.scrollIntoView({ block: 'center' })\n const m = messages.value\n // a block added or removed, or one whose text or kind changed\n const kind = target.matches('.dou-editor__diff-added')\n ? m.changeAdded\n : target.matches('.dou-editor__diff-removed-block')\n ? m.changeRemoved\n : m.changeChanged\n announce(`${kind} ${changeText(target)}`)\n return true\n}\n\n/** The text of a change: what was removed, or its block as it is now. */\nfunction changeText(target: HTMLElement) {\n if (target.matches('.dou-editor__diff-removed-block')) return target.textContent ?? ''\n const block = (target.closest('[data-block-id]') ?? target).cloneNode(true) as HTMLElement\n for (const el of block.querySelectorAll('[data-diff=\"removed\"]')) el.remove()\n return block.textContent ?? ''\n}\n\n/** What the live region reads out: a version restored, the change gone to. */\nconst spoken = ref('')\nfunction announce(text: string) {\n // the same words twice still get read\n spoken.value = ''\n void nextTick(() => (spoken.value = text))\n}\n\nfunction restore(doc: EditorDocument<PartialBlock>) {\n // like the other methods it works while `readonly`, and it is the change comparing allows\n if (!view.value || !restoreBlocks(view.value, readBlocks(doc) ?? [])) return false\n announce(messages.value.restored)\n return true\n}\n\n// a selection from outside: the cursor goes to the block, or the blocks are selected\nwatch(\n () => props.selection,\n (value) => {\n const current = view.value\n if (!current || !value || sameSelection(value, selection)) return\n const known = cursorKnown\n cursorKnown = true\n let applied = false\n if (value.blocks.length > 1) {\n applied = selectBlocks(value.blocks[0]!, value.blocks.at(-1)!)(\n current.state,\n current.dispatch,\n )\n if (!applied) warn('`selection.blocks` must be sibling blocks that exist in the document')\n } else {\n const id = value.block ?? value.blocks[0]\n const transaction = new EditorTransaction(current.state)\n if (id && transaction.focusBlock(id)) {\n current.dispatch(transaction.tr)\n applied = true\n } else if (!id) warn('a selection without blocks cannot be set; the cursor stays where it is')\n }\n if (applied) return\n cursorKnown = known\n // hand back where the selection really is, so the binding doesn't keep a value that never applied\n emit('update:selection', { ...selection, blocks: [...selection.blocks] })\n },\n)\n\nfunction transact(\n fn: (tr: EditorTransaction) => void,\n meta?: EditorTransaction['meta'],\n): EditorTransactionResult | null {\n const current = view.value\n // comparing shows a version: nothing changes it but `restore`\n if (!current || props.compare) return null\n const transaction = new EditorTransaction(current.state, meta, cursorKnown)\n fn(transaction)\n lastResult = null\n // `focusBlock` places the cursor\n if (transaction.focused) cursorKnown = true\n applyEditorTransaction(current, transaction)\n if (transaction.focused) current.focus()\n const result = lastResult\n lastResult = null\n return result\n}\n\nconst history = (action: 'undo' | 'redo', dispatch: boolean) => {\n const current = view.value\n if (!current || props.compare) return false\n const command = historyCommands(current.state)[action]\n return dispatch ? runCommand(current, command) : command(current.state)\n}\n\ndefineExpose<EditorExpose>({\n get view() {\n return view.value\n },\n focus: () => view.value?.focus(),\n blur: () => (view.value?.dom as HTMLElement | undefined)?.blur(),\n getBlocks: () => (view.value ? getBlocks(view.value) : []),\n setBlocks: (blocks: PartialBlock[]) => view.value && replaceBlocks(view.value, blocks),\n getHTML: () => (view.value ? writeHTML(getBlocks(view.value), kit) : ''),\n setHTML: (html: string) => view.value && replaceBlocks(view.value, parseHTML(html, kit)),\n run: (command) => (view.value ? runCommand(view.value, command) : false),\n openSearch: (query) => openSearch(query?.replace !== undefined, query),\n closeSearch,\n transact,\n getBlock: (id) => (view.value ? new EditorTransaction(view.value.state).getBlock(id) : null),\n insertBlocks: (blocks, placement) => {\n let ids: string[] = []\n transact((tr) => (ids = tr.insertBlocks(blocks, placement)))\n return ids\n },\n updateBlock: (id, patch) => {\n let ok = false\n transact((tr) => (ok = tr.updateBlock(id, patch)))\n return ok\n },\n removeBlocks: (ids) => {\n let ok = false\n transact((tr) => (ok = tr.removeBlocks(ids)))\n return ok\n },\n moveBlocks: (ids, placement) => {\n let ok = false\n transact((tr) => (ok = tr.moveBlocks(ids, placement)))\n return ok\n },\n focusBlock: (id, edge) => {\n let ok = false\n transact((tr) => (ok = tr.focusBlock(id, edge)))\n return ok\n },\n getSelection: () => ({ ...selection, blocks: [...selection.blocks] }),\n undo: () => history('undo', true),\n redo: () => history('redo', true),\n get canUndo() {\n return !!state.value && history('undo', false)\n },\n get canRedo() {\n return !!state.value && history('redo', false)\n },\n comment: () => comments.start(),\n getCommentAnchors: anchors,\n restore,\n nextChange: () => goToChange(1),\n previousChange: () => goToChange(-1),\n})\n\n/*\n * Highlights for the threads that are open: by thread id, in one rule,\n * so a thread resolved or opened restyles its text without redrawing it.\n */\nconst scope = useId()\n/** An id as a CSS identifier: no quotes or `<`, which server rendering would escape. */\nconst ident = (id: string) =>\n id.replace(/[^a-zA-Z0-9_]|^[\\d-]/gu, (char) => `\\\\${char.codePointAt(0)!.toString(16)} `)\nconst highlighted = (id: string) => `[data-dou-editor=${ident(scope)}] [data-comment=${ident(id)}]`\nconst highlightCSS = computed(() => {\n if (!comments.enabled.value) return ''\n const open = comments.threads.value.filter((thread) => !thread.resolved)\n if (!open.length) return ''\n let css = `${open.map((thread) => highlighted(thread.id)).join(',')}{background-color:var(--dou-editor-comment-bg);border-bottom-color:var(--dou-editor-comment-line)}`\n const active = comments.active.value\n if (active && open.some((thread) => thread.id === active))\n css += `${highlighted(active)}{background-color:var(--dou-editor-comment-bg-active)}`\n return css\n})\nconst HighlightStyle = () => (highlightCSS.value ? h('style', highlightCSS.value) : null)\n</script>\n\n<template>\n <div\n ref=\"root\"\n :class=\"[\n ns.b(),\n {\n // comparing keeps the editor's own gutter, so the text doesn't move\n 'is-readonly': readonly,\n 'is-comparing': comparing,\n 'is-focused': focused,\n 'is-dragging': dragging,\n },\n ]\"\n :data-dou-editor=\"scope\"\n >\n <div v-if=\"searchOpen && view\" :class=\"ns.e('search')\">\n <SearchBar\n ref=\"searchBar\"\n v-model:replacing=\"searchReplacing\"\n :readonly=\"!editable\"\n :skip=\"searchSkip\"\n @close=\"closeSearch\"\n />\n </div>\n <HighlightStyle />\n <div ref=\"mount\" :class=\"ns.e('mount')\" />\n <template v-if=\"editable && view\">\n <BlockHandle />\n <SlashMenu ref=\"slashMenu\" :slash=\"slash\" />\n <BubbleToolbar ref=\"bubble\" />\n <component :is=\"overlay\" v-for=\"(overlay, index) in kit.overlays\" :key=\"index\" />\n </template>\n <div :class=\"ns.e('live')\" aria-live=\"polite\">{{ spoken }}</div>\n <template v-if=\"view && comments.enabled.value && !comparing\">\n <CommentButton v-if=\"readonly\" />\n <CommentCard />\n </template>\n </div>\n</template>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAgFA,MAAM,QAAQ;EAoBd,MAAM,OAAO;EAGb,MAAM,MAAM,wBAAwB,MAAM,cAAc,CAAC,UAAU,CAAC,CAAC;EAErE,MAAM,yBAAyB,YACvB,MAAM,kBACN;GACJ,QAAQ,KACN,6KACF;GACA,uBAAuB;EACzB,CACF;EAEA,MAAM,KAAK,aAAa,QAAQ;EAChC,MAAM,WAAW,wBAAwB,MAAM,QAAQ;EACvD,MAAM,SAAS,gBAAgB;EAC/B,MAAM,OAAO,eAA4B,MAAM;EAC/C,MAAM,QAAQ,eAA4B,OAAO;EACjD,MAAM,OAAO,WAA8B,IAAI;EAC/C,MAAM,QAAQ,WAA+B,IAAI;EACjD,MAAM,UAAU,WAAW,KAAK;EAChC,MAAM,WAAW,WAAW,KAAK;;EAEjC,MAAM,YAAY,eAAe,CAAC,CAAC,MAAM,OAAO;;;;;EAKhD,MAAM,gBAAgB,eAAe;GACnC,MAAM,SAAS,MAAM,SAAS;GAC9B,OAAO,MAAM,QAAQ,MAAM,IAAI,YAAY,YAAY,IAAI,QAAQ,MAAM,CAAC,IAAI;EAChF,CAAC;EACD,MAAM,WAAW,eAAe,CAAC,MAAM,YAAY,CAAC,UAAU,KAAK;EAEnE,MAAM,EACJ,UACA,QAAQ,eACR,YACE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AAA;;;IAE/EP,mBAAgE,OAAA;KAA1D,OAAKL,eAAEC,MAAA,EAAA,CAAE,CAAC,EAAC,MAAA,CAAA;KAAU,aAAU;IAAY,GAAAY,gBAAA,OAAA,KAAM,GAAA,CAAA;IACvC,KAAA,SAAQZ,MAAA,QAAA,CAAQ,CAAC,QAAQ,SAAK,CAAK,UAAA,SAAnDH,UAAA,GAAAC,mBAGWO,UAAA,EAAA,KAAA,EAAA,GAAA,CAFY,QAAA,YAArBR,UAAA,GAAAa,YAAiCG,wBAAA,EAAA,KAAA,EAAA,CAAA,K,8BACjCZ,YAAea,oBAAA,C"}
|
|
1
|
+
{"version":3,"file":"editor.vue_vue_type_script_setup_true_lang.js","names":["_openBlock","_createElementBlock","_normalizeClass","_unref","_createVNode","SearchBar","_createCommentVNode","_createElementVNode","_Fragment","BlockHandle","SlashMenu","BubbleToolbar","_renderList","_createBlock","_resolveDynamicComponent","_toDisplayString","CommentButton","CommentCard"],"sources":["../src/editor.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { isApplePlatform, useGlobalConfig, useNamespace } from 'dou-ui'\nimport { keymap } from 'prosemirror-keymap'\nimport { Plugin, type EditorState, type Transaction } from 'prosemirror-state'\nimport type { EditorView } from 'prosemirror-view'\nimport {\n computed,\n getCurrentInstance,\n nextTick,\n onBeforeUnmount,\n onMounted,\n provide,\n ref,\n shallowRef,\n toRaw,\n useTemplateRef,\n watch,\n h,\n useId,\n type Component,\n} from 'vue'\nimport BlockHandle from './components/block-handle.vue'\nimport BubbleToolbar from './components/bubble-toolbar.vue'\nimport SearchBar from './components/search-bar.vue'\nimport CommentButton from './components/comment-button.vue'\nimport CommentCard from './components/comment-card.vue'\nimport SlashMenu from './components/slash-menu.vue'\nimport { setFallbackHighlighter, type CodeHighlighter } from './core/highlight'\nimport { comparePlugin, compareKey } from './core/compare'\nimport {\n createEditorView,\n getBlocks,\n historyCommands,\n originKey,\n replaceBlocks,\n restoreBlocks,\n runCommand,\n setEditable,\n} from './core/editor'\nimport { diffBlocks } from './core/changes'\nimport { isRemote } from './core/plugins'\nimport { selectionOf, sameSelection } from './core/selection'\nimport { selectBlocks } from './core/block-selection'\nimport { applyEditorTransaction, EditorTransaction } from './core/transaction'\nimport {\n blocksToDoc,\n docToBlocks,\n type Block,\n type EditorDocument,\n type PartialBlock,\n} from './core/model'\nimport { resolveEditorExtensions } from './core/extension'\nimport {\n previewMatch,\n searchKey,\n searchPlugin,\n setSearch,\n type EditorSearchQuery,\n} from './core/search'\nimport { slashPlugin, type SlashState } from './core/slash'\nimport { writeHTML } from './core/output'\nimport { parseHTML } from './core/prepare'\nimport { componentMounter, vueNodeView } from './define-block'\nimport { editorKit } from './extensions/editor-kit'\nimport { readBlocks } from './document'\nimport {\n editorKey,\n type EditorEmits,\n type EditorExpose,\n type EditorProps,\n type EditorOrigin,\n type EditorLinkOpenEvent,\n type EditorSelection,\n type EditorTransactionResult,\n} from './editor'\nimport { useEditorMessages } from './locale'\nimport { useEditorComments } from './use-comments'\n\ndefineOptions({ name: 'DouEditor' })\n\nconst props = withDefaults(defineProps<EditorProps>(), {\n modelValue: undefined,\n extensions: undefined,\n readonly: false,\n searchable: true,\n placeholder: undefined,\n messages: undefined,\n ariaLabel: undefined,\n autofocus: false,\n plugins: undefined,\n history: true,\n undo: undefined,\n redo: undefined,\n selection: undefined,\n comments: undefined,\n author: undefined,\n activeComment: undefined,\n commentable: true,\n compare: undefined,\n})\nconst emit = defineEmits<EditorEmits>()\n\n// read once: changing the schema of a live editor would invalidate its document\nconst messages = useEditorMessages(() => props.messages)\nconst kit = resolveEditorExtensions(props.extensions ?? [editorKit()], () => messages.value)\n// say so once, instead of silently keeping the old extensions\nconst stopWatchingExtensions = watch(\n () => props.extensions,\n () => {\n console.warn(\n '[@dou-ui/editor] `extensions` changed after mount and is ignored: it is read once. Create the list once outside the template, or give the editor a new `key` to rebuild it.',\n )\n stopWatchingExtensions()\n },\n)\n\nconst ns = useNamespace('editor')\nconst config = useGlobalConfig()\nconst root = useTemplateRef<HTMLElement>('root')\nconst mount = useTemplateRef<HTMLElement>('mount')\nconst view = shallowRef<EditorView | null>(null)\nconst state = shallowRef<EditorState | null>(null)\nconst focused = shallowRef(false)\nconst dragging = shallowRef(false)\n/** Showing what changed since an older version: read-only, without comments. */\nconst comparing = computed(() => !!props.compare)\n/**\n * The older version as whole blocks, matched to the current ones by id. A\n * block saved without an id gets a new one, so it shows as removed.\n */\nconst compareBlocks = computed(() => {\n const blocks = props.compare?.blocks\n return Array.isArray(blocks) ? docToBlocks(blocksToDoc(kit.schema, blocks)) : null\n})\nconst editable = computed(() => !props.readonly && !comparing.value)\n\nconst {\n comments,\n plugin: commentPlugin,\n anchors,\n scrollToComment,\n} = useEditorComments({\n props,\n emit,\n view,\n provider: kit.comments,\n})\n\nconst context = { view, state, focused, dragging, editable, messages, root, kit, comments }\nprovide(editorKey, context)\n\n// block components render outside this component's tree: hand them the context\nconst appContext = getCurrentInstance()?.appContext ?? null\nconst mountComponent = componentMounter(appContext, [[editorKey, context]])\nconst componentViews = {\n ...Object.fromEntries(\n Object.entries(kit.schema.nodes)\n .filter(([, type]) => type.spec.component)\n .map(([name, type]) => [\n name,\n vueNodeView(type.spec.component as Component, appContext, [[editorKey, context]]),\n ]),\n ),\n ...Object.fromEntries(\n Object.entries(kit.componentViews).map(([name, create]) => [name, create(mountComponent)]),\n ),\n}\n\n// find and replace: the panel over the text, the matches marked in it\nconst searchOpen = ref(false)\nconst searchReplacing = ref(false)\nconst searchBar = useTemplateRef<InstanceType<typeof SearchBar>>('searchBar')\n/** Blocks that draw their own text, such as a code block in the code editor, are not searched. */\nconst searchSkip = (node: { type: { name: string } }) => node.type.name in kit.componentViews\n\n/** Opens the panel, with the replace box for `replace`. A selection on one line becomes the search. */\nfunction openSearch(replace = false, given?: Partial<EditorSearchQuery>) {\n const v = view.value\n if (!v || !props.searchable) return false\n const old = searchKey.getState(v.state)?.query ?? { search: '' }\n const query = { ...old, ...given }\n const { from, to, empty } = v.state.selection\n if (given?.search === undefined && !empty) {\n const text = v.state.doc.textBetween(from, to, '\\n')\n if (text && !text.includes('\\n')) query.search = text\n }\n if ((replace || given?.replace !== undefined) && editable.value) searchReplacing.value = true\n searchOpen.value = true\n v.dispatch(setSearch(v.state.tr, { query, active: true }))\n const preview = previewMatch(v.state)\n if (preview) v.dispatch(preview)\n void nextTick(() => searchBar.value?.focus(replace && editable.value ? 'replace' : 'find'))\n return true\n}\n\nfunction closeSearch() {\n const v = view.value\n if (!searchOpen.value || !v) return false\n searchOpen.value = false\n v.dispatch(setSearch(v.state.tr, { active: false }))\n v.focus()\n return true\n}\n\n/** Goes to the next (or previous) match; with the panel shut, opens it on the last search. */\nfunction findAgain(step: 1 | -1) {\n if (!searchOpen.value) {\n const v = view.value\n if (!v || !searchKey.getState(v.state)?.query.search || !openSearch()) return false\n }\n void nextTick(() => (step > 0 ? searchBar.value?.next() : searchBar.value?.previous()))\n return true\n}\n\nconst replaceKey = isApplePlatform() ? 'Mod-Alt-f' : 'Mod-h'\nconst searchKeys = keymap({\n 'Mod-f': () => openSearch(),\n [replaceKey]: () => openSearch(true),\n F3: () => findAgain(1),\n 'Mod-g': () => findAgain(1),\n 'Shift-F3': () => findAgain(-1),\n 'Mod-Shift-g': () => findAgain(-1),\n Escape: () => closeSearch(),\n})\n\nconst slash = shallowRef<SlashState | null>(null)\nconst slashMenu = useTemplateRef<InstanceType<typeof SlashMenu>>('slashMenu')\nconst bubble = useTemplateRef<InstanceType<typeof BubbleToolbar>>('bubble')\n\n// The document last sent through `v-model`: when the same object comes back,\n// it is not loaded again (that would move the cursor).\nlet emitted: EditorDocument | undefined\n\n// the result of the last change, for `transact` to hand back\nlet lastResult: EditorTransactionResult | null = null\n\nfunction onChange(current: EditorView, tr: Transaction, before: EditorState) {\n const blocks = getBlocks(current)\n const doc: EditorDocument = { version: 1, blocks }\n emitted = doc\n const history = tr.getMeta('history$') as { redo: boolean } | undefined\n const origin =\n (tr.getMeta(originKey) as EditorOrigin | undefined) ??\n (history ? (history.redo ? 'redo' : 'undo') : isRemote(tr) ? 'remote' : undefined)\n const meta: EditorTransactionResult['meta'] = {\n history:\n tr.getMeta('addToHistory') !== false &&\n origin !== 'remote' &&\n origin !== 'undo' &&\n origin !== 'redo',\n }\n if (origin !== undefined) meta.origin = origin\n lastResult = { blocks, changes: diffBlocks(before.doc, current.state.doc), meta }\n emit('transaction', lastResult)\n emit('update:modelValue', doc)\n emit('change', doc)\n}\n\nlet selection: EditorSelection = { block: null, blocks: [] }\n\nconst warn = (message: string) => {\n if (process.env.NODE_ENV !== 'production') console.warn(`[@dou-ui/editor] ${message}`)\n}\n\nconst lacksId = (blocks: PartialBlock[]): boolean =>\n blocks.some((block) => !block.id || lacksId(block.children ?? []))\n// until the editor is focused (or a block is, by the program) its selection is no cursor\nlet cursorKnown = false\n\nfunction onUpdate(current: EditorView) {\n state.value = current.state\n if (!cursorKnown) {\n if (!focused.value) return\n cursorKnown = true\n }\n const next = selectionOf(current.state)\n if (sameSelection(next, selection)) return\n selection = next\n emit('update:selection', next)\n}\n\n// a click on a link places the cursor; with Ctrl or ⌘ held, or while read-only, it opens the link\nconst openLinks = new Plugin({\n props: {\n handleDOMEvents: {\n click(clicked, event) {\n const link = (event.target as HTMLElement).closest<HTMLAnchorElement>('a.dou-editor__link')\n if (!link?.href || !(event.metaKey || event.ctrlKey || !clicked.editable)) return false\n event.preventDefault()\n const $pos = clicked.state.doc.resolve(clicked.posAtDOM(link, 0))\n let block = ''\n for (let depth = $pos.depth; depth > 0; depth--)\n if ($pos.node(depth).type.name === 'block') {\n block = $pos.node(depth).attrs.id as string\n break\n }\n const opening: EditorLinkOpenEvent = {\n link: link.getAttribute('href') ?? link.href,\n block,\n defaultPrevented: false,\n preventDefault() {\n this.defaultPrevented = true\n },\n }\n emit('linkOpen', opening)\n if (!opening.defaultPrevented) window.open(link.href, '_blank', 'noopener,noreferrer')\n return true\n },\n },\n },\n})\n\nonMounted(() => {\n const instance = createEditorView({\n element: mount.value!,\n kit,\n nodeViews: componentViews,\n // with collaboration the document comes from the shared document\n blocks: kit.externalDocument ? [] : readBlocks(props.modelValue),\n editable: editable.value,\n placeholder: {\n text: () => props.placeholder ?? messages.value.placeholder,\n heading: () => messages.value.headingPlaceholder,\n empty: () => props.placeholder ?? messages.value.emptyPlaceholder,\n },\n plugins: [\n ...(props.plugins ?? []),\n slashPlugin({\n onChange: (value) => (slash.value = value),\n onKey: (event) => slashMenu.value?.onKey(event) ?? false,\n }),\n keymap({\n 'Mod-k': () => bubble.value?.editLink() ?? false,\n 'Mod-Alt-m': () => comments.start(),\n // with the thread card open, Escape in the text closes it, and only that\n Escape: () => {\n if (!comments.pending.value && !comments.active.value) return false\n comments.close()\n return true\n },\n }),\n commentPlugin,\n comparePlugin({\n before: () => compareBlocks.value,\n label: () => messages.value.removedBlock,\n }),\n openLinks,\n searchPlugin({ skip: searchSkip }),\n ],\n keymaps: [searchKeys],\n history: props.history,\n undo: props.undo,\n redo: props.redo,\n attributes: () => {\n const attrs: Record<string, string> = {}\n if (props.ariaLabel) attrs['aria-label'] = props.ariaLabel\n if (!editable.value) attrs['aria-readonly'] = 'true'\n return attrs\n },\n onChange,\n onUpdate,\n })\n view.value = instance\n state.value = instance.state\n // code blocks without their own highlighter use the one DouCodeBlock uses\n watch(\n () =>\n (config.value.defaults as { DouCodeBlock?: { highlight?: CodeHighlighter } }).DouCodeBlock\n ?.highlight ?? null,\n (highlight) => setFallbackHighlighter(instance, highlight),\n { immediate: true },\n )\n instance.dom.addEventListener('focus', onFocus)\n instance.dom.addEventListener('blur', onBlur)\n if (props.autofocus) instance.focus()\n // blocks given without ids got them now: hand those back, so events' ids can be looked up\n const given = kit.externalDocument ? undefined : readBlocks(props.modelValue)\n if (given && lacksId(given)) {\n const doc: EditorDocument = { version: 1, blocks: getBlocks(instance) }\n emitted = doc\n emit('update:modelValue', doc)\n }\n})\n\nfunction onFocus(event: FocusEvent) {\n focused.value = true\n if (!cursorKnown && view.value) {\n cursorKnown = true\n const next = selectionOf(view.value.state)\n if (!sameSelection(next, selection)) {\n selection = next\n emit('update:selection', next)\n }\n }\n emit('focus', event)\n}\n\nfunction onBlur(event: FocusEvent) {\n focused.value = false\n emit('blur', event)\n}\n\nonBeforeUnmount(() => {\n view.value?.destroy()\n view.value = null\n})\n\nwatch(\n () => props.modelValue,\n (value) => {\n const current = view.value\n if (!current || value === undefined || kit.externalDocument || toRaw(value) === emitted) return\n replaceBlocks(current, readBlocks(value) ?? [])\n },\n)\n\nwatch(editable, (value) => view.value && setEditable(view.value, value))\nwatch(compareBlocks, () => view.value?.dispatch(view.value.state.tr.setMeta(compareKey, true)))\n\n/** The change last scrolled to, by its place among them. */\nlet changeIndex = -1\nwatch(\n () => props.compare,\n () => (changeIndex = -1),\n)\nfunction goToChange(step: 1 | -1) {\n const dom = view.value?.dom\n if (!dom || !props.compare) return false\n // a block's own mark, or the first piece of text changed in it\n const marks = [\n ...dom.querySelectorAll<HTMLElement>(\n '.dou-editor__diff-added, .dou-editor__diff-changed, .dou-editor__diff-removed-block, .dou-editor__diff-added-text, .dou-editor__diff-removed',\n ),\n ].filter((el, index, list) => {\n const block = el.closest('[data-block-id]')\n const previous = list[index - 1]\n return !previous || previous.closest('[data-block-id]') !== block || !block\n })\n const next = changeIndex + step\n const target = marks[next]\n if (!target) return false\n changeIndex = next\n target.scrollIntoView({ block: 'center' })\n const m = messages.value\n // a block added or removed, or one whose text or kind changed\n const kind = target.matches('.dou-editor__diff-added')\n ? m.changeAdded\n : target.matches('.dou-editor__diff-removed-block')\n ? m.changeRemoved\n : m.changeChanged\n announce(`${kind} ${changeText(target)}`)\n return true\n}\n\n/** The text of a change: what was removed, or its block as it is now. */\nfunction changeText(target: HTMLElement) {\n if (target.matches('.dou-editor__diff-removed-block')) return target.textContent ?? ''\n const block = (target.closest('[data-block-id]') ?? target).cloneNode(true) as HTMLElement\n for (const el of block.querySelectorAll('[data-diff=\"removed\"]')) el.remove()\n return block.textContent ?? ''\n}\n\n/** What the live region reads out: a version restored, the change gone to. */\nconst spoken = ref('')\nfunction announce(text: string) {\n // the same words twice still get read\n spoken.value = ''\n void nextTick(() => (spoken.value = text))\n}\n\nfunction restore(doc: EditorDocument<PartialBlock>) {\n // like the other methods it works while `readonly`, and it is the change comparing allows\n if (!view.value || !restoreBlocks(view.value, readBlocks(doc) ?? [])) return false\n announce(messages.value.restored)\n return true\n}\n\n// a selection from outside: the cursor goes to the block, or the blocks are selected\nwatch(\n () => props.selection,\n (value) => {\n const current = view.value\n if (!current || !value || sameSelection(value, selection)) return\n const known = cursorKnown\n cursorKnown = true\n let applied = false\n if (value.blocks.length > 1) {\n applied = selectBlocks(value.blocks[0]!, value.blocks.at(-1)!)(\n current.state,\n current.dispatch,\n )\n if (!applied) warn('`selection.blocks` must be sibling blocks that exist in the document')\n } else {\n const id = value.block ?? value.blocks[0]\n const transaction = new EditorTransaction(current.state)\n if (id && transaction.focusBlock(id)) {\n current.dispatch(transaction.tr)\n applied = true\n } else if (!id) warn('a selection without blocks cannot be set; the cursor stays where it is')\n }\n if (applied) return\n cursorKnown = known\n // hand back where the selection really is, so the binding doesn't keep a value that never applied\n emit('update:selection', { ...selection, blocks: [...selection.blocks] })\n },\n)\n\nfunction transact(\n fn: (tr: EditorTransaction) => void,\n meta?: EditorTransaction['meta'],\n): EditorTransactionResult | null {\n const current = view.value\n // comparing shows a version: nothing changes it but `restore`\n if (!current || props.compare) return null\n const transaction = new EditorTransaction(current.state, meta, cursorKnown)\n fn(transaction)\n lastResult = null\n // `focusBlock` places the cursor\n if (transaction.focused) cursorKnown = true\n applyEditorTransaction(current, transaction)\n if (transaction.focused) current.focus()\n const result = lastResult\n lastResult = null\n return result\n}\n\nconst history = (action: 'undo' | 'redo', dispatch: boolean) => {\n const current = view.value\n if (!current || props.compare) return false\n const command = historyCommands(current.state)[action]\n return dispatch ? runCommand(current, command) : command(current.state)\n}\n\ndefineExpose<EditorExpose>({\n get view() {\n return view.value\n },\n focus: () => view.value?.focus(),\n blur: () => (view.value?.dom as HTMLElement | undefined)?.blur(),\n getBlocks: () => (view.value ? getBlocks(view.value) : []),\n setBlocks: (blocks: PartialBlock[]) => view.value && replaceBlocks(view.value, blocks),\n getHTML: () => (view.value ? writeHTML(getBlocks(view.value), kit) : ''),\n setHTML: (html: string) => view.value && replaceBlocks(view.value, parseHTML(html, kit)),\n run: (command) => (view.value ? runCommand(view.value, command) : false),\n openSearch: (query) => openSearch(query?.replace !== undefined, query),\n closeSearch,\n transact,\n getBlock: (id) => (view.value ? new EditorTransaction(view.value.state).getBlock(id) : null),\n insertBlocks: (blocks, placement) => {\n let ids: string[] = []\n transact((tr) => (ids = tr.insertBlocks(blocks, placement)))\n return ids\n },\n updateBlock: (id, patch) => {\n let ok = false\n transact((tr) => (ok = tr.updateBlock(id, patch)))\n return ok\n },\n removeBlocks: (ids) => {\n let ok = false\n transact((tr) => (ok = tr.removeBlocks(ids)))\n return ok\n },\n moveBlocks: (ids, placement) => {\n let ok = false\n transact((tr) => (ok = tr.moveBlocks(ids, placement)))\n return ok\n },\n focusBlock: (id, edge) => {\n let ok = false\n transact((tr) => (ok = tr.focusBlock(id, edge)))\n return ok\n },\n getSelection: () => ({ ...selection, blocks: [...selection.blocks] }),\n undo: () => history('undo', true),\n redo: () => history('redo', true),\n get canUndo() {\n return !!state.value && history('undo', false)\n },\n get canRedo() {\n return !!state.value && history('redo', false)\n },\n comment: () => comments.start(),\n getCommentAnchors: anchors,\n scrollToComment,\n restore,\n nextChange: () => goToChange(1),\n previousChange: () => goToChange(-1),\n})\n\n/*\n * Highlights for the threads that are open: by thread id, in one rule,\n * so a thread resolved or opened restyles its text without redrawing it.\n */\nconst scope = useId()\n/** An id as a CSS identifier: no quotes or `<`, which server rendering would escape. */\nconst ident = (id: string) =>\n id.replace(/[^a-zA-Z0-9_]|^[\\d-]/gu, (char) => `\\\\${char.codePointAt(0)!.toString(16)} `)\nconst highlighted = (id: string) => `[data-dou-editor=${ident(scope)}] [data-comment=${ident(id)}]`\nconst highlightCSS = computed(() => {\n if (!comments.enabled.value) return ''\n const open = comments.threads.value.filter((thread) => !thread.resolved)\n if (!open.length) return ''\n let css = `${open.map((thread) => highlighted(thread.id)).join(',')}{background-color:var(--dou-editor-comment-bg);border-bottom-color:var(--dou-editor-comment-line);--dou-editor-code-py:0;--dou-editor-code-bg:var(--dou-editor-comment-code-bg);--dou-editor-code-border:var(--dou-editor-comment-code-border)}`\n const active = comments.active.value\n if (active && open.some((thread) => thread.id === active))\n css += `${highlighted(active)}{background-color:var(--dou-editor-comment-bg-active)}`\n return css\n})\nconst HighlightStyle = () => (highlightCSS.value ? h('style', highlightCSS.value) : null)\n</script>\n\n<template>\n <div\n ref=\"root\"\n :class=\"[\n ns.b(),\n {\n // comparing takes a narrow gutter for the bars beside changed blocks\n 'is-readonly': readonly,\n 'is-comparing': comparing,\n 'is-focused': focused,\n 'is-dragging': dragging,\n },\n ]\"\n :data-dou-editor=\"scope\"\n >\n <div v-if=\"searchOpen && view\" :class=\"ns.e('search')\">\n <SearchBar\n ref=\"searchBar\"\n v-model:replacing=\"searchReplacing\"\n :readonly=\"!editable\"\n :skip=\"searchSkip\"\n @close=\"closeSearch\"\n />\n </div>\n <HighlightStyle />\n <div ref=\"mount\" :class=\"ns.e('mount')\" />\n <template v-if=\"editable && view\">\n <BlockHandle />\n <SlashMenu ref=\"slashMenu\" :slash=\"slash\" />\n <BubbleToolbar ref=\"bubble\" />\n <component :is=\"overlay\" v-for=\"(overlay, index) in kit.overlays\" :key=\"index\" />\n </template>\n <div :class=\"ns.e('live')\" aria-live=\"polite\">{{ spoken }}</div>\n <template v-if=\"view && comments.enabled.value && !comparing\">\n <CommentButton v-if=\"readonly\" />\n <CommentCard />\n </template>\n </div>\n</template>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAgFA,MAAM,QAAQ;EAoBd,MAAM,O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names":["_sfc_main"],"sources":["../src/editor.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { isApplePlatform, useGlobalConfig, useNamespace } from 'dou-ui'\nimport { keymap } from 'prosemirror-keymap'\nimport { Plugin, type EditorState, type Transaction } from 'prosemirror-state'\nimport type { EditorView } from 'prosemirror-view'\nimport {\n computed,\n getCurrentInstance,\n nextTick,\n onBeforeUnmount,\n onMounted,\n provide,\n ref,\n shallowRef,\n toRaw,\n useTemplateRef,\n watch,\n h,\n useId,\n type Component,\n} from 'vue'\nimport BlockHandle from './components/block-handle.vue'\nimport BubbleToolbar from './components/bubble-toolbar.vue'\nimport SearchBar from './components/search-bar.vue'\nimport CommentButton from './components/comment-button.vue'\nimport CommentCard from './components/comment-card.vue'\nimport SlashMenu from './components/slash-menu.vue'\nimport { setFallbackHighlighter, type CodeHighlighter } from './core/highlight'\nimport { comparePlugin, compareKey } from './core/compare'\nimport {\n createEditorView,\n getBlocks,\n historyCommands,\n originKey,\n replaceBlocks,\n restoreBlocks,\n runCommand,\n setEditable,\n} from './core/editor'\nimport { diffBlocks } from './core/changes'\nimport { isRemote } from './core/plugins'\nimport { selectionOf, sameSelection } from './core/selection'\nimport { selectBlocks } from './core/block-selection'\nimport { applyEditorTransaction, EditorTransaction } from './core/transaction'\nimport {\n blocksToDoc,\n docToBlocks,\n type Block,\n type EditorDocument,\n type PartialBlock,\n} from './core/model'\nimport { resolveEditorExtensions } from './core/extension'\nimport {\n previewMatch,\n searchKey,\n searchPlugin,\n setSearch,\n type EditorSearchQuery,\n} from './core/search'\nimport { slashPlugin, type SlashState } from './core/slash'\nimport { writeHTML } from './core/output'\nimport { parseHTML } from './core/prepare'\nimport { componentMounter, vueNodeView } from './define-block'\nimport { editorKit } from './extensions/editor-kit'\nimport { readBlocks } from './document'\nimport {\n editorKey,\n type EditorEmits,\n type EditorExpose,\n type EditorProps,\n type EditorOrigin,\n type EditorLinkOpenEvent,\n type EditorSelection,\n type EditorTransactionResult,\n} from './editor'\nimport { useEditorMessages } from './locale'\nimport { useEditorComments } from './use-comments'\n\ndefineOptions({ name: 'DouEditor' })\n\nconst props = withDefaults(defineProps<EditorProps>(), {\n modelValue: undefined,\n extensions: undefined,\n readonly: false,\n searchable: true,\n placeholder: undefined,\n messages: undefined,\n ariaLabel: undefined,\n autofocus: false,\n plugins: undefined,\n history: true,\n undo: undefined,\n redo: undefined,\n selection: undefined,\n comments: undefined,\n author: undefined,\n activeComment: undefined,\n commentable: true,\n compare: undefined,\n})\nconst emit = defineEmits<EditorEmits>()\n\n// read once: changing the schema of a live editor would invalidate its document\nconst kit = resolveEditorExtensions(props.extensions ?? [editorKit()])\n// say so once, instead of silently keeping the old extensions\nconst stopWatchingExtensions = watch(\n () => props.extensions,\n () => {\n console.warn(\n '[@dou-ui/editor] `extensions` changed after mount and is ignored: it is read once. Create the list once outside the template, or give the editor a new `key` to rebuild it.',\n )\n stopWatchingExtensions()\n },\n)\n\nconst ns = useNamespace('editor')\nconst messages = useEditorMessages(() => props.messages)\nconst config = useGlobalConfig()\nconst root = useTemplateRef<HTMLElement>('root')\nconst mount = useTemplateRef<HTMLElement>('mount')\nconst view = shallowRef<EditorView | null>(null)\nconst state = shallowRef<EditorState | null>(null)\nconst focused = shallowRef(false)\nconst dragging = shallowRef(false)\n/** Showing what changed since an older version: read-only, without comments. */\nconst comparing = computed(() => !!props.compare)\n/**\n * The older version as whole blocks, matched to the current ones by id. A\n * block saved without an id gets a new one, so it shows as removed.\n */\nconst compareBlocks = computed(() => {\n const blocks = props.compare?.blocks\n return Array.isArray(blocks) ? docToBlocks(blocksToDoc(kit.schema, blocks)) : null\n})\nconst editable = computed(() => !props.readonly && !comparing.value)\n\nconst {\n comments,\n plugin: commentPlugin,\n anchors,\n} = useEditorComments({\n props,\n emit,\n view,\n provider: kit.comments,\n})\n\nconst context = { view, state, focused, dragging, editable, messages, root, kit, comments }\nprovide(editorKey, context)\n\n// block components render outside this component's tree: hand them the context\nconst appContext = getCurrentInstance()?.appContext ?? null\nconst mountComponent = componentMounter(appContext, [[editorKey, context]])\nconst componentViews = {\n ...Object.fromEntries(\n Object.entries(kit.schema.nodes)\n .filter(([, type]) => type.spec.component)\n .map(([name, type]) => [\n name,\n vueNodeView(type.spec.component as Component, appContext, [[editorKey, context]]),\n ]),\n ),\n ...Object.fromEntries(\n Object.entries(kit.componentViews).map(([name, create]) => [name, create(mountComponent)]),\n ),\n}\n\n// find and replace: the panel over the text, the matches marked in it\nconst searchOpen = ref(false)\nconst searchReplacing = ref(false)\nconst searchBar = useTemplateRef<InstanceType<typeof SearchBar>>('searchBar')\n/** Blocks that draw their own text, such as a code block in the code editor, are not searched. */\nconst searchSkip = (node: { type: { name: string } }) => node.type.name in kit.componentViews\n\n/** Opens the panel, with the replace box for `replace`. A selection on one line becomes the search. */\nfunction openSearch(replace = false, given?: Partial<EditorSearchQuery>) {\n const v = view.value\n if (!v || !props.searchable) return false\n const old = searchKey.getState(v.state)?.query ?? { search: '' }\n const query = { ...old, ...given }\n const { from, to, empty } = v.state.selection\n if (given?.search === undefined && !empty) {\n const text = v.state.doc.textBetween(from, to, '\\n')\n if (text && !text.includes('\\n')) query.search = text\n }\n if ((replace || given?.replace !== undefined) && editable.value) searchReplacing.value = true\n searchOpen.value = true\n v.dispatch(setSearch(v.state.tr, { query, active: true }))\n const preview = previewMatch(v.state)\n if (preview) v.dispatch(preview)\n void nextTick(() => searchBar.value?.focus(replace && editable.value ? 'replace' : 'find'))\n return true\n}\n\nfunction closeSearch() {\n const v = view.value\n if (!searchOpen.value || !v) return false\n searchOpen.value = false\n v.dispatch(setSearch(v.state.tr, { active: false }))\n v.focus()\n return true\n}\n\n/** Goes to the next (or previous) match; with the panel shut, opens it on the last search. */\nfunction findAgain(step: 1 | -1) {\n if (!searchOpen.value) {\n const v = view.value\n if (!v || !searchKey.getState(v.state)?.query.search || !openSearch()) return false\n }\n void nextTick(() => (step > 0 ? searchBar.value?.next() : searchBar.value?.previous()))\n return true\n}\n\nconst replaceKey = isApplePlatform() ? 'Mod-Alt-f' : 'Mod-h'\nconst searchKeys = keymap({\n 'Mod-f': () => openSearch(),\n [replaceKey]: () => openSearch(true),\n F3: () => findAgain(1),\n 'Mod-g': () => findAgain(1),\n 'Shift-F3': () => findAgain(-1),\n 'Mod-Shift-g': () => findAgain(-1),\n Escape: () => closeSearch(),\n})\n\nconst slash = shallowRef<SlashState | null>(null)\nconst slashMenu = useTemplateRef<InstanceType<typeof SlashMenu>>('slashMenu')\nconst bubble = useTemplateRef<InstanceType<typeof BubbleToolbar>>('bubble')\n\n// The document last sent through `v-model`: when the same object comes back,\n// it is not loaded again (that would move the cursor).\nlet emitted: EditorDocument | undefined\n\n// the result of the last change, for `transact` to hand back\nlet lastResult: EditorTransactionResult | null = null\n\nfunction onChange(current: EditorView, tr: Transaction, before: EditorState) {\n const blocks = getBlocks(current)\n const doc: EditorDocument = { version: 1, blocks }\n emitted = doc\n const history = tr.getMeta('history$') as { redo: boolean } | undefined\n const origin =\n (tr.getMeta(originKey) as EditorOrigin | undefined) ??\n (history ? (history.redo ? 'redo' : 'undo') : isRemote(tr) ? 'remote' : undefined)\n const meta: EditorTransactionResult['meta'] = {\n history:\n tr.getMeta('addToHistory') !== false &&\n origin !== 'remote' &&\n origin !== 'undo' &&\n origin !== 'redo',\n }\n if (origin !== undefined) meta.origin = origin\n lastResult = { blocks, changes: diffBlocks(before.doc, current.state.doc), meta }\n emit('transaction', lastResult)\n emit('update:modelValue', doc)\n emit('change', doc)\n}\n\nlet selection: EditorSelection = { block: null, blocks: [] }\n\nconst warn = (message: string) => {\n if (process.env.NODE_ENV !== 'production') console.warn(`[@dou-ui/editor] ${message}`)\n}\n\nconst lacksId = (blocks: PartialBlock[]): boolean =>\n blocks.some((block) => !block.id || lacksId(block.children ?? []))\n// until the editor is focused (or a block is, by the program) its selection is no cursor\nlet cursorKnown = false\n\nfunction onUpdate(current: EditorView) {\n state.value = current.state\n if (!cursorKnown) {\n if (!focused.value) return\n cursorKnown = true\n }\n const next = selectionOf(current.state)\n if (sameSelection(next, selection)) return\n selection = next\n emit('update:selection', next)\n}\n\n// a click on a link places the cursor; with Ctrl or ⌘ held, or while read-only, it opens the link\nconst openLinks = new Plugin({\n props: {\n handleDOMEvents: {\n click(clicked, event) {\n const link = (event.target as HTMLElement).closest<HTMLAnchorElement>('a.dou-editor__link')\n if (!link?.href || !(event.metaKey || event.ctrlKey || !clicked.editable)) return false\n event.preventDefault()\n const $pos = clicked.state.doc.resolve(clicked.posAtDOM(link, 0))\n let block = ''\n for (let depth = $pos.depth; depth > 0; depth--)\n if ($pos.node(depth).type.name === 'block') {\n block = $pos.node(depth).attrs.id as string\n break\n }\n const opening: EditorLinkOpenEvent = {\n link: link.getAttribute('href') ?? link.href,\n block,\n defaultPrevented: false,\n preventDefault() {\n this.defaultPrevented = true\n },\n }\n emit('linkOpen', opening)\n if (!opening.defaultPrevented) window.open(link.href, '_blank', 'noopener,noreferrer')\n return true\n },\n },\n },\n})\n\nonMounted(() => {\n const instance = createEditorView({\n element: mount.value!,\n kit,\n nodeViews: componentViews,\n // with collaboration the document comes from the shared document\n blocks: kit.externalDocument ? [] : readBlocks(props.modelValue),\n editable: editable.value,\n placeholder: {\n text: () => props.placeholder ?? messages.value.placeholder,\n heading: () => messages.value.headingPlaceholder,\n empty: () => props.placeholder ?? messages.value.emptyPlaceholder,\n },\n plugins: [\n ...(props.plugins ?? []),\n slashPlugin({\n onChange: (value) => (slash.value = value),\n onKey: (event) => slashMenu.value?.onKey(event) ?? false,\n }),\n keymap({\n 'Mod-k': () => bubble.value?.editLink() ?? false,\n 'Mod-Alt-m': () => comments.start(),\n // with the thread card open, Escape in the text closes it, and only that\n Escape: () => {\n if (!comments.pending.value && !comments.active.value) return false\n comments.close()\n return true\n },\n }),\n commentPlugin,\n comparePlugin({\n before: () => compareBlocks.value,\n label: () => messages.value.removedBlock,\n }),\n openLinks,\n searchPlugin({ skip: searchSkip }),\n ],\n keymaps: [searchKeys],\n history: props.history,\n undo: props.undo,\n redo: props.redo,\n attributes: () => {\n const attrs: Record<string, string> = {}\n if (props.ariaLabel) attrs['aria-label'] = props.ariaLabel\n if (!editable.value) attrs['aria-readonly'] = 'true'\n return attrs\n },\n onChange,\n onUpdate,\n })\n view.value = instance\n state.value = instance.state\n // code blocks without their own highlighter use the one DouCodeBlock uses\n watch(\n () =>\n (config.value.defaults as { DouCodeBlock?: { highlight?: CodeHighlighter } }).DouCodeBlock\n ?.highlight ?? null,\n (highlight) => setFallbackHighlighter(instance, highlight),\n { immediate: true },\n )\n instance.dom.addEventListener('focus', onFocus)\n instance.dom.addEventListener('blur', onBlur)\n if (props.autofocus) instance.focus()\n // blocks given without ids got them now: hand those back, so events' ids can be looked up\n const given = kit.externalDocument ? undefined : readBlocks(props.modelValue)\n if (given && lacksId(given)) {\n const doc: EditorDocument = { version: 1, blocks: getBlocks(instance) }\n emitted = doc\n emit('update:modelValue', doc)\n }\n})\n\nfunction onFocus(event: FocusEvent) {\n focused.value = true\n if (!cursorKnown && view.value) {\n cursorKnown = true\n const next = selectionOf(view.value.state)\n if (!sameSelection(next, selection)) {\n selection = next\n emit('update:selection', next)\n }\n }\n emit('focus', event)\n}\n\nfunction onBlur(event: FocusEvent) {\n focused.value = false\n emit('blur', event)\n}\n\nonBeforeUnmount(() => {\n view.value?.destroy()\n view.value = null\n})\n\nwatch(\n () => props.modelValue,\n (value) => {\n const current = view.value\n if (!current || value === undefined || kit.externalDocument || toRaw(value) === emitted) return\n replaceBlocks(current, readBlocks(value) ?? [])\n },\n)\n\nwatch(editable, (value) => view.value && setEditable(view.value, value))\nwatch(compareBlocks, () => view.value?.dispatch(view.value.state.tr.setMeta(compareKey, true)))\n\n/** The change last scrolled to, by its place among them. */\nlet changeIndex = -1\nwatch(\n () => props.compare,\n () => (changeIndex = -1),\n)\nfunction goToChange(step: 1 | -1) {\n const dom = view.value?.dom\n if (!dom || !props.compare) return false\n // a block's own mark, or the first piece of text changed in it\n const marks = [\n ...dom.querySelectorAll<HTMLElement>(\n '.dou-editor__diff-added, .dou-editor__diff-changed, .dou-editor__diff-removed-block, .dou-editor__diff-added-text, .dou-editor__diff-removed',\n ),\n ].filter((el, index, list) => {\n const block = el.closest('[data-block-id]')\n const previous = list[index - 1]\n return !previous || previous.closest('[data-block-id]') !== block || !block\n })\n const next = changeIndex + step\n const target = marks[next]\n if (!target) return false\n changeIndex = next\n target.scrollIntoView({ block: 'center' })\n const m = messages.value\n // a block added or removed, or one whose text or kind changed\n const kind = target.matches('.dou-editor__diff-added')\n ? m.changeAdded\n : target.matches('.dou-editor__diff-removed-block')\n ? m.changeRemoved\n : m.changeChanged\n announce(`${kind} ${changeText(target)}`)\n return true\n}\n\n/** The text of a change: what was removed, or its block as it is now. */\nfunction changeText(target: HTMLElement) {\n if (target.matches('.dou-editor__diff-removed-block')) return target.textContent ?? ''\n const block = (target.closest('[data-block-id]') ?? target).cloneNode(true) as HTMLElement\n for (const el of block.querySelectorAll('[data-diff=\"removed\"]')) el.remove()\n return block.textContent ?? ''\n}\n\n/** What the live region reads out: a version restored, the change gone to. */\nconst spoken = ref('')\nfunction announce(text: string) {\n // the same words twice still get read\n spoken.value = ''\n void nextTick(() => (spoken.value = text))\n}\n\nfunction restore(doc: EditorDocument<PartialBlock>) {\n // like the other methods it works while `readonly`, and it is the change comparing allows\n if (!view.value || !restoreBlocks(view.value, readBlocks(doc) ?? [])) return false\n announce(messages.value.restored)\n return true\n}\n\n// a selection from outside: the cursor goes to the block, or the blocks are selected\nwatch(\n () => props.selection,\n (value) => {\n const current = view.value\n if (!current || !value || sameSelection(value, selection)) return\n const known = cursorKnown\n cursorKnown = true\n let applied = false\n if (value.blocks.length > 1) {\n applied = selectBlocks(value.blocks[0]!, value.blocks.at(-1)!)(\n current.state,\n current.dispatch,\n )\n if (!applied) warn('`selection.blocks` must be sibling blocks that exist in the document')\n } else {\n const id = value.block ?? value.blocks[0]\n const transaction = new EditorTransaction(current.state)\n if (id && transaction.focusBlock(id)) {\n current.dispatch(transaction.tr)\n applied = true\n } else if (!id) warn('a selection without blocks cannot be set; the cursor stays where it is')\n }\n if (applied) return\n cursorKnown = known\n // hand back where the selection really is, so the binding doesn't keep a value that never applied\n emit('update:selection', { ...selection, blocks: [...selection.blocks] })\n },\n)\n\nfunction transact(\n fn: (tr: EditorTransaction) => void,\n meta?: EditorTransaction['meta'],\n): EditorTransactionResult | null {\n const current = view.value\n // comparing shows a version: nothing changes it but `restore`\n if (!current || props.compare) return null\n const transaction = new EditorTransaction(current.state, meta, cursorKnown)\n fn(transaction)\n lastResult = null\n // `focusBlock` places the cursor\n if (transaction.focused) cursorKnown = true\n applyEditorTransaction(current, transaction)\n if (transaction.focused) current.focus()\n const result = lastResult\n lastResult = null\n return result\n}\n\nconst history = (action: 'undo' | 'redo', dispatch: boolean) => {\n const current = view.value\n if (!current || props.compare) return false\n const command = historyCommands(current.state)[action]\n return dispatch ? runCommand(current, command) : command(current.state)\n}\n\ndefineExpose<EditorExpose>({\n get view() {\n return view.value\n },\n focus: () => view.value?.focus(),\n blur: () => (view.value?.dom as HTMLElement | undefined)?.blur(),\n getBlocks: () => (view.value ? getBlocks(view.value) : []),\n setBlocks: (blocks: PartialBlock[]) => view.value && replaceBlocks(view.value, blocks),\n getHTML: () => (view.value ? writeHTML(getBlocks(view.value), kit) : ''),\n setHTML: (html: string) => view.value && replaceBlocks(view.value, parseHTML(html, kit)),\n run: (command) => (view.value ? runCommand(view.value, command) : false),\n openSearch: (query) => openSearch(query?.replace !== undefined, query),\n closeSearch,\n transact,\n getBlock: (id) => (view.value ? new EditorTransaction(view.value.state).getBlock(id) : null),\n insertBlocks: (blocks, placement) => {\n let ids: string[] = []\n transact((tr) => (ids = tr.insertBlocks(blocks, placement)))\n return ids\n },\n updateBlock: (id, patch) => {\n let ok = false\n transact((tr) => (ok = tr.updateBlock(id, patch)))\n return ok\n },\n removeBlocks: (ids) => {\n let ok = false\n transact((tr) => (ok = tr.removeBlocks(ids)))\n return ok\n },\n moveBlocks: (ids, placement) => {\n let ok = false\n transact((tr) => (ok = tr.moveBlocks(ids, placement)))\n return ok\n },\n focusBlock: (id, edge) => {\n let ok = false\n transact((tr) => (ok = tr.focusBlock(id, edge)))\n return ok\n },\n getSelection: () => ({ ...selection, blocks: [...selection.blocks] }),\n undo: () => history('undo', true),\n redo: () => history('redo', true),\n get canUndo() {\n return !!state.value && history('undo', false)\n },\n get canRedo() {\n return !!state.value && history('redo', false)\n },\n comment: () => comments.start(),\n getCommentAnchors: anchors,\n restore,\n nextChange: () => goToChange(1),\n previousChange: () => goToChange(-1),\n})\n\n/*\n * Highlights for the threads that are open: by thread id, in one rule,\n * so a thread resolved or opened restyles its text without redrawing it.\n */\nconst scope = useId()\n/** An id as a CSS identifier: no quotes or `<`, which server rendering would escape. */\nconst ident = (id: string) =>\n id.replace(/[^a-zA-Z0-9_]|^[\\d-]/gu, (char) => `\\\\${char.codePointAt(0)!.toString(16)} `)\nconst highlighted = (id: string) => `[data-dou-editor=${ident(scope)}] [data-comment=${ident(id)}]`\nconst highlightCSS = computed(() => {\n if (!comments.enabled.value) return ''\n const open = comments.threads.value.filter((thread) => !thread.resolved)\n if (!open.length) return ''\n let css = `${open.map((thread) => highlighted(thread.id)).join(',')}{background-color:var(--dou-editor-comment-bg);border-bottom-color:var(--dou-editor-comment-line)}`\n const active = comments.active.value\n if (active && open.some((thread) => thread.id === active))\n css += `${highlighted(active)}{background-color:var(--dou-editor-comment-bg-active)}`\n return css\n})\nconst HighlightStyle = () => (highlightCSS.value ? h('style', highlightCSS.value) : null)\n</script>\n\n<template>\n <div\n ref=\"root\"\n :class=\"[\n ns.b(),\n {\n // comparing keeps the editor's own gutter, so the text doesn't move\n 'is-readonly': readonly,\n 'is-comparing': comparing,\n 'is-focused': focused,\n 'is-dragging': dragging,\n },\n ]\"\n :data-dou-editor=\"scope\"\n >\n <div v-if=\"searchOpen && view\" :class=\"ns.e('search')\">\n <SearchBar\n ref=\"searchBar\"\n v-model:replacing=\"searchReplacing\"\n :readonly=\"!editable\"\n :skip=\"searchSkip\"\n @close=\"closeSearch\"\n />\n </div>\n <HighlightStyle />\n <div ref=\"mount\" :class=\"ns.e('mount')\" />\n <template v-if=\"editable && view\">\n <BlockHandle />\n <SlashMenu ref=\"slashMenu\" :slash=\"slash\" />\n <BubbleToolbar ref=\"bubble\" />\n <component :is=\"overlay\" v-for=\"(overlay, index) in kit.overlays\" :key=\"index\" />\n </template>\n <div :class=\"ns.e('live')\" aria-live=\"polite\">{{ spoken }}</div>\n <template v-if=\"view && comments.enabled.value && !comparing\">\n <CommentButton v-if=\"readonly\" />\n <CommentCard />\n </template>\n </div>\n</template>\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"editor2.js","names":["_sfc_main"],"sources":["../src/editor.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport { isApplePlatform, useGlobalConfig, useNamespace } from 'dou-ui'\nimport { keymap } from 'prosemirror-keymap'\nimport { Plugin, type EditorState, type Transaction } from 'prosemirror-state'\nimport type { EditorView } from 'prosemirror-view'\nimport {\n computed,\n getCurrentInstance,\n nextTick,\n onBeforeUnmount,\n onMounted,\n provide,\n ref,\n shallowRef,\n toRaw,\n useTemplateRef,\n watch,\n h,\n useId,\n type Component,\n} from 'vue'\nimport BlockHandle from './components/block-handle.vue'\nimport BubbleToolbar from './components/bubble-toolbar.vue'\nimport SearchBar from './components/search-bar.vue'\nimport CommentButton from './components/comment-button.vue'\nimport CommentCard from './components/comment-card.vue'\nimport SlashMenu from './components/slash-menu.vue'\nimport { setFallbackHighlighter, type CodeHighlighter } from './core/highlight'\nimport { comparePlugin, compareKey } from './core/compare'\nimport {\n createEditorView,\n getBlocks,\n historyCommands,\n originKey,\n replaceBlocks,\n restoreBlocks,\n runCommand,\n setEditable,\n} from './core/editor'\nimport { diffBlocks } from './core/changes'\nimport { isRemote } from './core/plugins'\nimport { selectionOf, sameSelection } from './core/selection'\nimport { selectBlocks } from './core/block-selection'\nimport { applyEditorTransaction, EditorTransaction } from './core/transaction'\nimport {\n blocksToDoc,\n docToBlocks,\n type Block,\n type EditorDocument,\n type PartialBlock,\n} from './core/model'\nimport { resolveEditorExtensions } from './core/extension'\nimport {\n previewMatch,\n searchKey,\n searchPlugin,\n setSearch,\n type EditorSearchQuery,\n} from './core/search'\nimport { slashPlugin, type SlashState } from './core/slash'\nimport { writeHTML } from './core/output'\nimport { parseHTML } from './core/prepare'\nimport { componentMounter, vueNodeView } from './define-block'\nimport { editorKit } from './extensions/editor-kit'\nimport { readBlocks } from './document'\nimport {\n editorKey,\n type EditorEmits,\n type EditorExpose,\n type EditorProps,\n type EditorOrigin,\n type EditorLinkOpenEvent,\n type EditorSelection,\n type EditorTransactionResult,\n} from './editor'\nimport { useEditorMessages } from './locale'\nimport { useEditorComments } from './use-comments'\n\ndefineOptions({ name: 'DouEditor' })\n\nconst props = withDefaults(defineProps<EditorProps>(), {\n modelValue: undefined,\n extensions: undefined,\n readonly: false,\n searchable: true,\n placeholder: undefined,\n messages: undefined,\n ariaLabel: undefined,\n autofocus: false,\n plugins: undefined,\n history: true,\n undo: undefined,\n redo: undefined,\n selection: undefined,\n comments: undefined,\n author: undefined,\n activeComment: undefined,\n commentable: true,\n compare: undefined,\n})\nconst emit = defineEmits<EditorEmits>()\n\n// read once: changing the schema of a live editor would invalidate its document\nconst messages = useEditorMessages(() => props.messages)\nconst kit = resolveEditorExtensions(props.extensions ?? [editorKit()], () => messages.value)\n// say so once, instead of silently keeping the old extensions\nconst stopWatchingExtensions = watch(\n () => props.extensions,\n () => {\n console.warn(\n '[@dou-ui/editor] `extensions` changed after mount and is ignored: it is read once. Create the list once outside the template, or give the editor a new `key` to rebuild it.',\n )\n stopWatchingExtensions()\n },\n)\n\nconst ns = useNamespace('editor')\nconst config = useGlobalConfig()\nconst root = useTemplateRef<HTMLElement>('root')\nconst mount = useTemplateRef<HTMLElement>('mount')\nconst view = shallowRef<EditorView | null>(null)\nconst state = shallowRef<EditorState | null>(null)\nconst focused = shallowRef(false)\nconst dragging = shallowRef(false)\n/** Showing what changed since an older version: read-only, without comments. */\nconst comparing = computed(() => !!props.compare)\n/**\n * The older version as whole blocks, matched to the current ones by id. A\n * block saved without an id gets a new one, so it shows as removed.\n */\nconst compareBlocks = computed(() => {\n const blocks = props.compare?.blocks\n return Array.isArray(blocks) ? docToBlocks(blocksToDoc(kit.schema, blocks)) : null\n})\nconst editable = computed(() => !props.readonly && !comparing.value)\n\nconst {\n comments,\n plugin: commentPlugin,\n anchors,\n scrollToComment,\n} = useEditorComments({\n props,\n emit,\n view,\n provider: kit.comments,\n})\n\nconst context = { view, state, focused, dragging, editable, messages, root, kit, comments }\nprovide(editorKey, context)\n\n// block components render outside this component's tree: hand them the context\nconst appContext = getCurrentInstance()?.appContext ?? null\nconst mountComponent = componentMounter(appContext, [[editorKey, context]])\nconst componentViews = {\n ...Object.fromEntries(\n Object.entries(kit.schema.nodes)\n .filter(([, type]) => type.spec.component)\n .map(([name, type]) => [\n name,\n vueNodeView(type.spec.component as Component, appContext, [[editorKey, context]]),\n ]),\n ),\n ...Object.fromEntries(\n Object.entries(kit.componentViews).map(([name, create]) => [name, create(mountComponent)]),\n ),\n}\n\n// find and replace: the panel over the text, the matches marked in it\nconst searchOpen = ref(false)\nconst searchReplacing = ref(false)\nconst searchBar = useTemplateRef<InstanceType<typeof SearchBar>>('searchBar')\n/** Blocks that draw their own text, such as a code block in the code editor, are not searched. */\nconst searchSkip = (node: { type: { name: string } }) => node.type.name in kit.componentViews\n\n/** Opens the panel, with the replace box for `replace`. A selection on one line becomes the search. */\nfunction openSearch(replace = false, given?: Partial<EditorSearchQuery>) {\n const v = view.value\n if (!v || !props.searchable) return false\n const old = searchKey.getState(v.state)?.query ?? { search: '' }\n const query = { ...old, ...given }\n const { from, to, empty } = v.state.selection\n if (given?.search === undefined && !empty) {\n const text = v.state.doc.textBetween(from, to, '\\n')\n if (text && !text.includes('\\n')) query.search = text\n }\n if ((replace || given?.replace !== undefined) && editable.value) searchReplacing.value = true\n searchOpen.value = true\n v.dispatch(setSearch(v.state.tr, { query, active: true }))\n const preview = previewMatch(v.state)\n if (preview) v.dispatch(preview)\n void nextTick(() => searchBar.value?.focus(replace && editable.value ? 'replace' : 'find'))\n return true\n}\n\nfunction closeSearch() {\n const v = view.value\n if (!searchOpen.value || !v) return false\n searchOpen.value = false\n v.dispatch(setSearch(v.state.tr, { active: false }))\n v.focus()\n return true\n}\n\n/** Goes to the next (or previous) match; with the panel shut, opens it on the last search. */\nfunction findAgain(step: 1 | -1) {\n if (!searchOpen.value) {\n const v = view.value\n if (!v || !searchKey.getState(v.state)?.query.search || !openSearch()) return false\n }\n void nextTick(() => (step > 0 ? searchBar.value?.next() : searchBar.value?.previous()))\n return true\n}\n\nconst replaceKey = isApplePlatform() ? 'Mod-Alt-f' : 'Mod-h'\nconst searchKeys = keymap({\n 'Mod-f': () => openSearch(),\n [replaceKey]: () => openSearch(true),\n F3: () => findAgain(1),\n 'Mod-g': () => findAgain(1),\n 'Shift-F3': () => findAgain(-1),\n 'Mod-Shift-g': () => findAgain(-1),\n Escape: () => closeSearch(),\n})\n\nconst slash = shallowRef<SlashState | null>(null)\nconst slashMenu = useTemplateRef<InstanceType<typeof SlashMenu>>('slashMenu')\nconst bubble = useTemplateRef<InstanceType<typeof BubbleToolbar>>('bubble')\n\n// The document last sent through `v-model`: when the same object comes back,\n// it is not loaded again (that would move the cursor).\nlet emitted: EditorDocument | undefined\n\n// the result of the last change, for `transact` to hand back\nlet lastResult: EditorTransactionResult | null = null\n\nfunction onChange(current: EditorView, tr: Transaction, before: EditorState) {\n const blocks = getBlocks(current)\n const doc: EditorDocument = { version: 1, blocks }\n emitted = doc\n const history = tr.getMeta('history$') as { redo: boolean } | undefined\n const origin =\n (tr.getMeta(originKey) as EditorOrigin | undefined) ??\n (history ? (history.redo ? 'redo' : 'undo') : isRemote(tr) ? 'remote' : undefined)\n const meta: EditorTransactionResult['meta'] = {\n history:\n tr.getMeta('addToHistory') !== false &&\n origin !== 'remote' &&\n origin !== 'undo' &&\n origin !== 'redo',\n }\n if (origin !== undefined) meta.origin = origin\n lastResult = { blocks, changes: diffBlocks(before.doc, current.state.doc), meta }\n emit('transaction', lastResult)\n emit('update:modelValue', doc)\n emit('change', doc)\n}\n\nlet selection: EditorSelection = { block: null, blocks: [] }\n\nconst warn = (message: string) => {\n if (process.env.NODE_ENV !== 'production') console.warn(`[@dou-ui/editor] ${message}`)\n}\n\nconst lacksId = (blocks: PartialBlock[]): boolean =>\n blocks.some((block) => !block.id || lacksId(block.children ?? []))\n// until the editor is focused (or a block is, by the program) its selection is no cursor\nlet cursorKnown = false\n\nfunction onUpdate(current: EditorView) {\n state.value = current.state\n if (!cursorKnown) {\n if (!focused.value) return\n cursorKnown = true\n }\n const next = selectionOf(current.state)\n if (sameSelection(next, selection)) return\n selection = next\n emit('update:selection', next)\n}\n\n// a click on a link places the cursor; with Ctrl or ⌘ held, or while read-only, it opens the link\nconst openLinks = new Plugin({\n props: {\n handleDOMEvents: {\n click(clicked, event) {\n const link = (event.target as HTMLElement).closest<HTMLAnchorElement>('a.dou-editor__link')\n if (!link?.href || !(event.metaKey || event.ctrlKey || !clicked.editable)) return false\n event.preventDefault()\n const $pos = clicked.state.doc.resolve(clicked.posAtDOM(link, 0))\n let block = ''\n for (let depth = $pos.depth; depth > 0; depth--)\n if ($pos.node(depth).type.name === 'block') {\n block = $pos.node(depth).attrs.id as string\n break\n }\n const opening: EditorLinkOpenEvent = {\n link: link.getAttribute('href') ?? link.href,\n block,\n defaultPrevented: false,\n preventDefault() {\n this.defaultPrevented = true\n },\n }\n emit('linkOpen', opening)\n if (!opening.defaultPrevented) window.open(link.href, '_blank', 'noopener,noreferrer')\n return true\n },\n },\n },\n})\n\nonMounted(() => {\n const instance = createEditorView({\n element: mount.value!,\n kit,\n nodeViews: componentViews,\n // with collaboration the document comes from the shared document\n blocks: kit.externalDocument ? [] : readBlocks(props.modelValue),\n editable: editable.value,\n placeholder: {\n text: () => props.placeholder ?? messages.value.placeholder,\n heading: () => messages.value.headingPlaceholder,\n empty: () => props.placeholder ?? messages.value.emptyPlaceholder,\n },\n plugins: [\n ...(props.plugins ?? []),\n slashPlugin({\n onChange: (value) => (slash.value = value),\n onKey: (event) => slashMenu.value?.onKey(event) ?? false,\n }),\n keymap({\n 'Mod-k': () => bubble.value?.editLink() ?? false,\n 'Mod-Alt-m': () => comments.start(),\n // with the thread card open, Escape in the text closes it, and only that\n Escape: () => {\n if (!comments.pending.value && !comments.active.value) return false\n comments.close()\n return true\n },\n }),\n commentPlugin,\n comparePlugin({\n before: () => compareBlocks.value,\n label: () => messages.value.removedBlock,\n }),\n openLinks,\n searchPlugin({ skip: searchSkip }),\n ],\n keymaps: [searchKeys],\n history: props.history,\n undo: props.undo,\n redo: props.redo,\n attributes: () => {\n const attrs: Record<string, string> = {}\n if (props.ariaLabel) attrs['aria-label'] = props.ariaLabel\n if (!editable.value) attrs['aria-readonly'] = 'true'\n return attrs\n },\n onChange,\n onUpdate,\n })\n view.value = instance\n state.value = instance.state\n // code blocks without their own highlighter use the one DouCodeBlock uses\n watch(\n () =>\n (config.value.defaults as { DouCodeBlock?: { highlight?: CodeHighlighter } }).DouCodeBlock\n ?.highlight ?? null,\n (highlight) => setFallbackHighlighter(instance, highlight),\n { immediate: true },\n )\n instance.dom.addEventListener('focus', onFocus)\n instance.dom.addEventListener('blur', onBlur)\n if (props.autofocus) instance.focus()\n // blocks given without ids got them now: hand those back, so events' ids can be looked up\n const given = kit.externalDocument ? undefined : readBlocks(props.modelValue)\n if (given && lacksId(given)) {\n const doc: EditorDocument = { version: 1, blocks: getBlocks(instance) }\n emitted = doc\n emit('update:modelValue', doc)\n }\n})\n\nfunction onFocus(event: FocusEvent) {\n focused.value = true\n if (!cursorKnown && view.value) {\n cursorKnown = true\n const next = selectionOf(view.value.state)\n if (!sameSelection(next, selection)) {\n selection = next\n emit('update:selection', next)\n }\n }\n emit('focus', event)\n}\n\nfunction onBlur(event: FocusEvent) {\n focused.value = false\n emit('blur', event)\n}\n\nonBeforeUnmount(() => {\n view.value?.destroy()\n view.value = null\n})\n\nwatch(\n () => props.modelValue,\n (value) => {\n const current = view.value\n if (!current || value === undefined || kit.externalDocument || toRaw(value) === emitted) return\n replaceBlocks(current, readBlocks(value) ?? [])\n },\n)\n\nwatch(editable, (value) => view.value && setEditable(view.value, value))\nwatch(compareBlocks, () => view.value?.dispatch(view.value.state.tr.setMeta(compareKey, true)))\n\n/** The change last scrolled to, by its place among them. */\nlet changeIndex = -1\nwatch(\n () => props.compare,\n () => (changeIndex = -1),\n)\nfunction goToChange(step: 1 | -1) {\n const dom = view.value?.dom\n if (!dom || !props.compare) return false\n // a block's own mark, or the first piece of text changed in it\n const marks = [\n ...dom.querySelectorAll<HTMLElement>(\n '.dou-editor__diff-added, .dou-editor__diff-changed, .dou-editor__diff-removed-block, .dou-editor__diff-added-text, .dou-editor__diff-removed',\n ),\n ].filter((el, index, list) => {\n const block = el.closest('[data-block-id]')\n const previous = list[index - 1]\n return !previous || previous.closest('[data-block-id]') !== block || !block\n })\n const next = changeIndex + step\n const target = marks[next]\n if (!target) return false\n changeIndex = next\n target.scrollIntoView({ block: 'center' })\n const m = messages.value\n // a block added or removed, or one whose text or kind changed\n const kind = target.matches('.dou-editor__diff-added')\n ? m.changeAdded\n : target.matches('.dou-editor__diff-removed-block')\n ? m.changeRemoved\n : m.changeChanged\n announce(`${kind} ${changeText(target)}`)\n return true\n}\n\n/** The text of a change: what was removed, or its block as it is now. */\nfunction changeText(target: HTMLElement) {\n if (target.matches('.dou-editor__diff-removed-block')) return target.textContent ?? ''\n const block = (target.closest('[data-block-id]') ?? target).cloneNode(true) as HTMLElement\n for (const el of block.querySelectorAll('[data-diff=\"removed\"]')) el.remove()\n return block.textContent ?? ''\n}\n\n/** What the live region reads out: a version restored, the change gone to. */\nconst spoken = ref('')\nfunction announce(text: string) {\n // the same words twice still get read\n spoken.value = ''\n void nextTick(() => (spoken.value = text))\n}\n\nfunction restore(doc: EditorDocument<PartialBlock>) {\n // like the other methods it works while `readonly`, and it is the change comparing allows\n if (!view.value || !restoreBlocks(view.value, readBlocks(doc) ?? [])) return false\n announce(messages.value.restored)\n return true\n}\n\n// a selection from outside: the cursor goes to the block, or the blocks are selected\nwatch(\n () => props.selection,\n (value) => {\n const current = view.value\n if (!current || !value || sameSelection(value, selection)) return\n const known = cursorKnown\n cursorKnown = true\n let applied = false\n if (value.blocks.length > 1) {\n applied = selectBlocks(value.blocks[0]!, value.blocks.at(-1)!)(\n current.state,\n current.dispatch,\n )\n if (!applied) warn('`selection.blocks` must be sibling blocks that exist in the document')\n } else {\n const id = value.block ?? value.blocks[0]\n const transaction = new EditorTransaction(current.state)\n if (id && transaction.focusBlock(id)) {\n current.dispatch(transaction.tr)\n applied = true\n } else if (!id) warn('a selection without blocks cannot be set; the cursor stays where it is')\n }\n if (applied) return\n cursorKnown = known\n // hand back where the selection really is, so the binding doesn't keep a value that never applied\n emit('update:selection', { ...selection, blocks: [...selection.blocks] })\n },\n)\n\nfunction transact(\n fn: (tr: EditorTransaction) => void,\n meta?: EditorTransaction['meta'],\n): EditorTransactionResult | null {\n const current = view.value\n // comparing shows a version: nothing changes it but `restore`\n if (!current || props.compare) return null\n const transaction = new EditorTransaction(current.state, meta, cursorKnown)\n fn(transaction)\n lastResult = null\n // `focusBlock` places the cursor\n if (transaction.focused) cursorKnown = true\n applyEditorTransaction(current, transaction)\n if (transaction.focused) current.focus()\n const result = lastResult\n lastResult = null\n return result\n}\n\nconst history = (action: 'undo' | 'redo', dispatch: boolean) => {\n const current = view.value\n if (!current || props.compare) return false\n const command = historyCommands(current.state)[action]\n return dispatch ? runCommand(current, command) : command(current.state)\n}\n\ndefineExpose<EditorExpose>({\n get view() {\n return view.value\n },\n focus: () => view.value?.focus(),\n blur: () => (view.value?.dom as HTMLElement | undefined)?.blur(),\n getBlocks: () => (view.value ? getBlocks(view.value) : []),\n setBlocks: (blocks: PartialBlock[]) => view.value && replaceBlocks(view.value, blocks),\n getHTML: () => (view.value ? writeHTML(getBlocks(view.value), kit) : ''),\n setHTML: (html: string) => view.value && replaceBlocks(view.value, parseHTML(html, kit)),\n run: (command) => (view.value ? runCommand(view.value, command) : false),\n openSearch: (query) => openSearch(query?.replace !== undefined, query),\n closeSearch,\n transact,\n getBlock: (id) => (view.value ? new EditorTransaction(view.value.state).getBlock(id) : null),\n insertBlocks: (blocks, placement) => {\n let ids: string[] = []\n transact((tr) => (ids = tr.insertBlocks(blocks, placement)))\n return ids\n },\n updateBlock: (id, patch) => {\n let ok = false\n transact((tr) => (ok = tr.updateBlock(id, patch)))\n return ok\n },\n removeBlocks: (ids) => {\n let ok = false\n transact((tr) => (ok = tr.removeBlocks(ids)))\n return ok\n },\n moveBlocks: (ids, placement) => {\n let ok = false\n transact((tr) => (ok = tr.moveBlocks(ids, placement)))\n return ok\n },\n focusBlock: (id, edge) => {\n let ok = false\n transact((tr) => (ok = tr.focusBlock(id, edge)))\n return ok\n },\n getSelection: () => ({ ...selection, blocks: [...selection.blocks] }),\n undo: () => history('undo', true),\n redo: () => history('redo', true),\n get canUndo() {\n return !!state.value && history('undo', false)\n },\n get canRedo() {\n return !!state.value && history('redo', false)\n },\n comment: () => comments.start(),\n getCommentAnchors: anchors,\n scrollToComment,\n restore,\n nextChange: () => goToChange(1),\n previousChange: () => goToChange(-1),\n})\n\n/*\n * Highlights for the threads that are open: by thread id, in one rule,\n * so a thread resolved or opened restyles its text without redrawing it.\n */\nconst scope = useId()\n/** An id as a CSS identifier: no quotes or `<`, which server rendering would escape. */\nconst ident = (id: string) =>\n id.replace(/[^a-zA-Z0-9_]|^[\\d-]/gu, (char) => `\\\\${char.codePointAt(0)!.toString(16)} `)\nconst highlighted = (id: string) => `[data-dou-editor=${ident(scope)}] [data-comment=${ident(id)}]`\nconst highlightCSS = computed(() => {\n if (!comments.enabled.value) return ''\n const open = comments.threads.value.filter((thread) => !thread.resolved)\n if (!open.length) return ''\n let css = `${open.map((thread) => highlighted(thread.id)).join(',')}{background-color:var(--dou-editor-comment-bg);border-bottom-color:var(--dou-editor-comment-line);--dou-editor-code-py:0;--dou-editor-code-bg:var(--dou-editor-comment-code-bg);--dou-editor-code-border:var(--dou-editor-comment-code-border)}`\n const active = comments.active.value\n if (active && open.some((thread) => thread.id === active))\n css += `${highlighted(active)}{background-color:var(--dou-editor-comment-bg-active)}`\n return css\n})\nconst HighlightStyle = () => (highlightCSS.value ? h('style', highlightCSS.value) : null)\n</script>\n\n<template>\n <div\n ref=\"root\"\n :class=\"[\n ns.b(),\n {\n // comparing takes a narrow gutter for the bars beside changed blocks\n 'is-readonly': readonly,\n 'is-comparing': comparing,\n 'is-focused': focused,\n 'is-dragging': dragging,\n },\n ]\"\n :data-dou-editor=\"scope\"\n >\n <div v-if=\"searchOpen && view\" :class=\"ns.e('search')\">\n <SearchBar\n ref=\"searchBar\"\n v-model:replacing=\"searchReplacing\"\n :readonly=\"!editable\"\n :skip=\"searchSkip\"\n @close=\"closeSearch\"\n />\n </div>\n <HighlightStyle />\n <div ref=\"mount\" :class=\"ns.e('mount')\" />\n <template v-if=\"editable && view\">\n <BlockHandle />\n <SlashMenu ref=\"slashMenu\" :slash=\"slash\" />\n <BubbleToolbar ref=\"bubble\" />\n <component :is=\"overlay\" v-for=\"(overlay, index) in kit.overlays\" :key=\"index\" />\n </template>\n <div :class=\"ns.e('live')\" aria-live=\"polite\">{{ spoken }}</div>\n <template v-if=\"view && comments.enabled.value && !comparing\">\n <CommentButton v-if=\"readonly\" />\n <CommentCard />\n </template>\n </div>\n</template>\n"],"mappings":""}
|