@dou-ui/editor 0.1.0-alpha.12 → 0.1.0-alpha.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/collaboration/cursors.js +42 -10
- package/dist/collaboration/cursors.js.map +1 -1
- package/dist/collaboration/index.js +30 -3
- package/dist/collaboration/index.js.map +1 -1
- package/dist/components/block-handle.js.map +1 -1
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js +73 -15
- package/dist/components/block-handle.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/components/slash-choices.js +6 -0
- package/dist/components/slash-choices.js.map +1 -0
- package/dist/components/slash-choices.vue_vue_type_script_setup_true_lang.js +56 -0
- package/dist/components/slash-choices.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/components/slash-menu.js.map +1 -1
- package/dist/components/slash-menu.vue_vue_type_script_setup_true_lang.js +185 -20
- package/dist/components/slash-menu.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/core/block-selection.js +32 -4
- package/dist/core/block-selection.js.map +1 -1
- package/dist/core/blocks.js +21 -3
- package/dist/core/blocks.js.map +1 -1
- package/dist/core/commands.js +125 -13
- package/dist/core/commands.js.map +1 -1
- package/dist/core/extension.js +6 -2
- package/dist/core/extension.js.map +1 -1
- package/dist/core/model.js +8 -2
- package/dist/core/model.js.map +1 -1
- package/dist/core/schema.js.map +1 -1
- package/dist/core/transaction.js +12 -3
- package/dist/core/transaction.js.map +1 -1
- package/dist/document.js +40 -4
- package/dist/document.js.map +1 -1
- package/dist/dom.js +96 -13
- package/dist/dom.js.map +1 -1
- package/dist/editor.vue_vue_type_script_setup_true_lang.js +3 -3
- package/dist/editor.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/editor2.js.map +1 -1
- package/dist/extensions/columns/column-picker.js +6 -0
- package/dist/extensions/columns/column-picker.js.map +1 -0
- package/dist/extensions/columns/column-picker.vue_vue_type_script_setup_true_lang.js +57 -0
- package/dist/extensions/columns/column-picker.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/columns/columns-controls.js +6 -0
- package/dist/extensions/columns/columns-controls.js.map +1 -0
- package/dist/extensions/columns/columns-controls.vue_vue_type_script_setup_true_lang.js +341 -0
- package/dist/extensions/columns/columns-controls.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/columns/html.js +34 -0
- package/dist/extensions/columns/html.js.map +1 -0
- package/dist/extensions/columns/index.js +57 -0
- package/dist/extensions/columns/index.js.map +1 -0
- package/dist/extensions/columns/keys.js +53 -0
- package/dist/extensions/columns/keys.js.map +1 -0
- package/dist/extensions/columns/plugin.js +213 -0
- package/dist/extensions/columns/plugin.js.map +1 -0
- package/dist/extensions/columns/schema.js +58 -0
- package/dist/extensions/columns/schema.js.map +1 -0
- package/dist/extensions/columns/select-columns.js +6 -0
- package/dist/extensions/columns/select-columns.js.map +1 -0
- package/dist/extensions/columns/select-columns.vue_vue_type_script_setup_true_lang.js +71 -0
- package/dist/extensions/columns/select-columns.vue_vue_type_script_setup_true_lang.js.map +1 -0
- package/dist/extensions/editor-kit.js +3 -1
- package/dist/extensions/editor-kit.js.map +1 -1
- package/dist/extensions/table/plugin.js +33 -1
- package/dist/extensions/table/plugin.js.map +1 -1
- package/dist/extensions/table/table-controls.js.map +1 -1
- package/dist/extensions/table/table-controls.vue_vue_type_script_setup_true_lang.js +1 -1
- package/dist/extensions/table/table-controls.vue_vue_type_script_setup_true_lang.js.map +1 -1
- package/dist/extensions/table/view.js +25 -1
- package/dist/extensions/table/view.js.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/locale.js +30 -0
- package/dist/locale.js.map +1 -1
- package/dist/style.css +1 -1
- package/dist/types/collaboration/cursors.d.ts +29 -1
- package/dist/types/collaboration/index.d.ts +17 -2
- package/dist/types/components/slash-choices.vue.d.ts +18 -0
- package/dist/types/core/blocks.d.ts +10 -0
- package/dist/types/core/commands.d.ts +17 -2
- package/dist/types/core/extension.d.ts +53 -2
- package/dist/types/core/model.d.ts +6 -1
- package/dist/types/core/schema.d.ts +1 -1
- package/dist/types/document.d.ts +4 -2
- package/dist/types/dom.d.ts +34 -4
- package/dist/types/editor.vue.d.ts +10 -0
- package/dist/types/extensions/columns/column-picker.vue.d.ts +10 -0
- package/dist/types/extensions/columns/columns-controls.vue.d.ts +3 -0
- package/dist/types/extensions/columns/html.d.ts +10 -0
- package/dist/types/extensions/columns/index.d.ts +9 -0
- package/dist/types/extensions/columns/keys.d.ts +6 -0
- package/dist/types/extensions/columns/plugin.d.ts +28 -0
- package/dist/types/extensions/columns/schema.d.ts +17 -0
- package/dist/types/extensions/columns/select-columns.vue.d.ts +13 -0
- package/dist/types/extensions/editor-kit.d.ts +4 -1
- package/dist/types/extensions/table/view.d.ts +8 -1
- package/dist/types/index.d.ts +12 -2
- package/dist/types/locale.d.ts +17 -0
- package/package.json +5 -5
|
@@ -5,10 +5,42 @@ import { Decoration, DecorationSet } from "prosemirror-view";
|
|
|
5
5
|
import * as Y from "yjs";
|
|
6
6
|
// src/collaboration/cursors.ts
|
|
7
7
|
/** The text a place points into: the block's own, or one of its table cells. */
|
|
8
|
-
function textOf(
|
|
9
|
-
const yblock =
|
|
10
|
-
if (!
|
|
11
|
-
|
|
8
|
+
function textOf(map, block, cell) {
|
|
9
|
+
const yblock = map.get(block);
|
|
10
|
+
if (!(yblock instanceof Y.Map)) return void 0;
|
|
11
|
+
if (!cell) {
|
|
12
|
+
if (yblock.has("cells")) return void 0;
|
|
13
|
+
const text = yblock.get("text");
|
|
14
|
+
return text instanceof Y.Text ? text : void 0;
|
|
15
|
+
}
|
|
16
|
+
const cells = yblock.get("cells");
|
|
17
|
+
const text = cells instanceof Y.Map ? cells.get(cell) : void 0;
|
|
18
|
+
return text instanceof Y.Text ? text : void 0;
|
|
19
|
+
}
|
|
20
|
+
function placeAt(map, target, holdsText) {
|
|
21
|
+
const yblock = map.get(target.block);
|
|
22
|
+
if (!target.cell && yblock instanceof Y.Map && !holdsText(String(yblock.get("type")))) return null;
|
|
23
|
+
const text = textOf(map, target.block, target.cell);
|
|
24
|
+
if (!text) return null;
|
|
25
|
+
const offset = Math.max(0, Math.min(Math.floor(target.offset ?? text.length), text.length));
|
|
26
|
+
const position = Y.relativePositionToJSON(Y.createRelativePositionFromTypeIndex(text, offset));
|
|
27
|
+
return target.cell ? {
|
|
28
|
+
block: target.block,
|
|
29
|
+
cell: target.cell,
|
|
30
|
+
position
|
|
31
|
+
} : {
|
|
32
|
+
block: target.block,
|
|
33
|
+
position
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** A cursor at `head`, selecting from `anchor`; `null` when either has no text to be in. */
|
|
37
|
+
function cursorIn(map, head, anchor, holdsText) {
|
|
38
|
+
const to = placeAt(map, head, holdsText);
|
|
39
|
+
const from = anchor === head ? to : placeAt(map, anchor, holdsText);
|
|
40
|
+
return to && from ? {
|
|
41
|
+
anchor: from,
|
|
42
|
+
head: to
|
|
43
|
+
} : null;
|
|
12
44
|
}
|
|
13
45
|
/** A document position as a place that survives other people's edits. */
|
|
14
46
|
function placeOf(binding, doc, pos) {
|
|
@@ -23,7 +55,7 @@ function placeOf(binding, doc, pos) {
|
|
|
23
55
|
cell = found.key;
|
|
24
56
|
index = found.index;
|
|
25
57
|
}
|
|
26
|
-
const text = textOf(binding, id, cell);
|
|
58
|
+
const text = textOf(binding.map, id, cell);
|
|
27
59
|
if (!text) return null;
|
|
28
60
|
const offset = Math.max(0, Math.min(index, text.length));
|
|
29
61
|
const position = Y.relativePositionToJSON(Y.createRelativePositionFromTypeIndex(text, offset));
|
|
@@ -49,7 +81,7 @@ function positionOf(binding, doc, place) {
|
|
|
49
81
|
start += cell.offset;
|
|
50
82
|
size = cell.size;
|
|
51
83
|
}
|
|
52
|
-
const offset = absolute && textOf(binding, place.block, place.cell) === absolute.type ? Math.min(absolute.index, size) : 0;
|
|
84
|
+
const offset = absolute && textOf(binding.map, place.block, place.cell) === absolute.type ? Math.min(absolute.index, size) : 0;
|
|
53
85
|
return start + offset;
|
|
54
86
|
}
|
|
55
87
|
function cursorElement(user) {
|
|
@@ -67,7 +99,7 @@ function decorations(binding, awareness, state) {
|
|
|
67
99
|
const found = [];
|
|
68
100
|
awareness.getStates().forEach((value, client) => {
|
|
69
101
|
if (client === awareness.clientID) return;
|
|
70
|
-
const cursor = value.
|
|
102
|
+
const cursor = value.editor;
|
|
71
103
|
const user = value.user;
|
|
72
104
|
if (!cursor) return;
|
|
73
105
|
const anchor = positionOf(binding, state.doc, cursor.anchor);
|
|
@@ -128,7 +160,7 @@ function cursorsPlugin(binding, awareness) {
|
|
|
128
160
|
const json = JSON.stringify(cursor);
|
|
129
161
|
if (json === last) return;
|
|
130
162
|
last = json;
|
|
131
|
-
awareness.setLocalStateField("
|
|
163
|
+
awareness.setLocalStateField("editor", cursor);
|
|
132
164
|
};
|
|
133
165
|
const onFocus = () => share();
|
|
134
166
|
view.dom.addEventListener("focus", onFocus);
|
|
@@ -139,12 +171,12 @@ function cursorsPlugin(binding, awareness) {
|
|
|
139
171
|
awareness.off("change", onChange);
|
|
140
172
|
view.dom.removeEventListener("focus", onFocus);
|
|
141
173
|
view.dom.removeEventListener("blur", onFocus);
|
|
142
|
-
awareness.setLocalStateField("
|
|
174
|
+
awareness.setLocalStateField("editor", null);
|
|
143
175
|
}
|
|
144
176
|
};
|
|
145
177
|
}
|
|
146
178
|
});
|
|
147
179
|
}
|
|
148
|
-
export { cursorsPlugin, placeOf, positionOf };
|
|
180
|
+
export { cursorIn, cursorsPlugin, placeOf, positionOf };
|
|
149
181
|
|
|
150
182
|
//# sourceMappingURL=cursors.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cursors.js","names":[],"sources":["../../src/collaboration/cursors.ts"],"sourcesContent":["import type { Node as PMNode } from 'prosemirror-model'\nimport { Plugin, PluginKey, type EditorState } from 'prosemirror-state'\nimport { Decoration, DecorationSet } from 'prosemirror-view'\nimport * as Y from 'yjs'\nimport { blockAround, findBlockById } from '../core/blocks'\nimport type { Binding, YBlock } from './binding'\nimport { cellAt, cellStart } from './table'\n\n/** What the editor needs of a Yjs awareness instance (`y-protocols/awareness`). */\nexport interface AwarenessLike {\n clientID: number\n getLocalState(): Record<string, unknown> | null\n setLocalStateField(field: string, value: unknown): void\n getStates(): Map<number, Record<string, unknown>>\n on(event: 'change', listener: (...args: unknown[]) => void): void\n off(event: 'change', listener: (...args: unknown[]) => void): void\n}\n\n/** A place in the text: the block and a position in its text that follows edits. */\ninterface Place {\n block: string\n /** In a table: the cell, `row id:column id`. */\n cell?: string\n position: unknown\n}\n\n/** The text a place points into: the block's own, or one of its table cells. */\nfunction textOf(binding: Binding, block: string, cell?: string): Y.Text | undefined {\n const yblock = binding.map.get(block) as YBlock | undefined\n if (!cell) return yblock?.get('text') as Y.Text | undefined\n return (yblock?.get('cells') as Y.Map<Y.Text> | undefined)?.get(cell)\n}\n\ninterface Cursor {\n anchor: Place\n head: Place\n}\n\n/** A document position as a place that survives other people's edits. */\nexport function placeOf(binding: Binding, doc: PMNode, pos: number): Place | null {\n const info = blockAround(doc.resolve(pos))\n if (!info) return null\n const id = info.node.attrs.id as string\n let index = pos - info.contentPos - 1\n let cell: string | undefined\n if (info.content.type.spec.rows) {\n const found = cellAt(info.content, index)\n if (!found) return null\n cell = found.key\n index = found.index\n }\n const text = textOf(binding, id, cell)\n if (!text) return null\n const offset = Math.max(0, Math.min(index, text.length))\n const position = Y.relativePositionToJSON(Y.createRelativePositionFromTypeIndex(text, offset))\n return cell ? { block: id, cell, position } : { block: id, position }\n}\n\n/** Back from a place to a document position, or `null` if its block is gone. */\nexport function positionOf(binding: Binding, doc: PMNode, place: Place): number | null {\n const info = findBlockById(doc, place.block)\n if (!info) return null\n const absolute = Y.createAbsolutePositionFromRelativePosition(\n Y.createRelativePositionFromJSON(place.position),\n binding.map.doc!,\n )\n let start = info.contentPos + 1\n let size = info.content.content.size\n if (place.cell) {\n const cell = info.content.type.spec.rows ? cellStart(info.content, place.cell) : null\n if (!cell) return null\n start += cell.offset\n size = cell.size\n }\n const offset =\n absolute && textOf(binding, place.block, place.cell) === absolute.type\n ? Math.min(absolute.index, size)\n : 0\n return start + offset\n}\n\nfunction cursorElement(user: { name: string; color: string }) {\n const cursor = document.createElement('span')\n cursor.className = 'dou-editor__cursor'\n cursor.style.setProperty('--dou-editor-cursor-color', user.color)\n const label = document.createElement('span')\n label.className = 'dou-editor__cursor-label'\n label.textContent = user.name\n // word joiners keep the caret from breaking the line around it\n cursor.append('', label, '')\n return cursor\n}\n\nconst cursorsKey = new PluginKey<DecorationSet>('dou-editor-cursors')\n\nfunction decorations(binding: Binding, awareness: AwarenessLike, state: EditorState) {\n const found: Decoration[] = []\n awareness.getStates().forEach((value, client) => {\n if (client === awareness.clientID) return\n const cursor = value.cursor as Cursor | null | undefined\n const user = value.user as { name?: string; color?: string } | undefined\n if (!cursor) return\n const anchor = positionOf(binding, state.doc, cursor.anchor)\n const head = positionOf(binding, state.doc, cursor.head)\n if (anchor === null || head === null) return\n const shown = { name: user?.name ?? '', color: user?.color ?? '#6b7280' }\n found.push(\n Decoration.widget(head, () => cursorElement(shown), {\n key: `cursor-${client}-${shown.name}-${shown.color}`,\n side: 10,\n }),\n )\n if (anchor !== head) {\n found.push(\n Decoration.inline(Math.min(anchor, head), Math.max(anchor, head), {\n class: 'dou-editor__remote-selection',\n style: `--dou-editor-cursor-color: ${shown.color}`,\n }),\n )\n }\n })\n return DecorationSet.create(state.doc, found)\n}\n\n/** Shares this user's cursor and shows everyone else's. */\nexport function cursorsPlugin(binding: Binding, awareness: AwarenessLike): Plugin {\n return new Plugin<DecorationSet>({\n key: cursorsKey,\n state: {\n init: (_config, state) => decorations(binding, awareness, state),\n apply(tr, value, _old, state) {\n if (tr.docChanged || tr.getMeta(cursorsKey)) return decorations(binding, awareness, state)\n return value\n },\n },\n props: {\n decorations(state) {\n return cursorsKey.getState(state)\n },\n },\n view(view) {\n let scheduled = false\n // others' cursors changed: redraw on the next frame, never inside a dispatch\n const onChange = () => {\n if (scheduled) return\n scheduled = true\n queueMicrotask(() => {\n scheduled = false\n if (binding.view === view) view.dispatch(view.state.tr.setMeta(cursorsKey, true))\n })\n }\n awareness.on('change', onChange)\n let last = ''\n const share = () => {\n let cursor: Cursor | null = null\n if (view.hasFocus()) {\n const { anchor, head } = view.state.selection\n const a = placeOf(binding, view.state.doc, anchor)\n const h = placeOf(binding, view.state.doc, head)\n if (a && h) cursor = { anchor: a, head: h }\n }\n const json = JSON.stringify(cursor)\n if (json === last) return\n last = json\n awareness.setLocalStateField('cursor', cursor)\n }\n const onFocus = () => share()\n view.dom.addEventListener('focus', onFocus)\n view.dom.addEventListener('blur', onFocus)\n return {\n update: share,\n destroy() {\n awareness.off('change', onChange)\n view.dom.removeEventListener('focus', onFocus)\n view.dom.removeEventListener('blur', onFocus)\n awareness.setLocalStateField('cursor', null)\n },\n }\n },\n })\n}\n"],"mappings":";;;;;;;AA2BA,SAAS,OAAO,SAAkB,OAAe,MAAmC;CAClF,MAAM,SAAS,QAAQ,IAAI,IAAI,KAAK;CACpC,IAAI,CAAC,MAAM,OAAO,QAAQ,IAAI,MAAM;CACpC,QAAQ,QAAQ,IAAI,OAAO,EAAA,EAAiC,IAAI,IAAI;AACtE;;AAQA,SAAgB,QAAQ,SAAkB,KAAa,KAA2B;CAChF,MAAM,OAAO,YAAY,IAAI,QAAQ,GAAG,CAAC;CACzC,IAAI,CAAC,MAAM,OAAO;CAClB,MAAM,KAAK,KAAK,KAAK,MAAM;CAC3B,IAAI,QAAQ,MAAM,KAAK,aAAa;CACpC,IAAI;CACJ,IAAI,KAAK,QAAQ,KAAK,KAAK,MAAM;EAC/B,MAAM,QAAQ,OAAO,KAAK,SAAS,KAAK;EACxC,IAAI,CAAC,OAAO,OAAO;EACnB,OAAO,MAAM;EACb,QAAQ,MAAM;CAChB;CACA,MAAM,OAAO,OAAO,SAAS,IAAI,IAAI;CACrC,IAAI,C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C;IAClF,CAAC;GACH;GACA,UAAU,GAAG,UAAU,QAAQ;GAC/B,IAAI,OAAO;GACX,MAAM,cAAc;IAClB,IAAI,SAAwB;IAC5B,IAAI,KAAK,SAAS,GAAG;KACnB,MAAM,EAAE,QAAQ,SAAS,KAAK,MAAM;KACpC,MAAM,IAAI,QAAQ,SAAS,KAAK,MAAM,KAAK,MAAM;KACjD,MAAM,IAAI,QAAQ,SAAS,KAAK,MAAM,KAAK,IAAI;KAC/C,IAAI,KAAK,GAAG,SAAS;MAAE,QAAQ;MAAG,MAAM;KAAE;IAC5C;IACA,MAAM,OAAO,KAAK,UAAU,MAAM;IAClC,IAAI,SAAS,MAAM;IACnB,OAAO;IACP,UAAU,mBAAmB,UAAU,MAAM;GAC/C;GACA,MAAM,gBAAgB,MAAM;GAC5B,KAAK,IAAI,iBAAiB,SAAS,OAAO;GAC1C,KAAK,IAAI,iBAAiB,QAAQ,OAAO;GACzC,OAAO;IACL,QAAQ;IACR,UAAU;KACR,UAAU,IAAI,UAAU,QAAQ;KAChC,KAAK,IAAI,oBAAoB,SAAS,OAAO;KAC7C,KAAK,IAAI,oBAAoB,QAAQ,OAAO;KAC5C,UAAU,mBAAmB,UAAU,IAAI;IAC7C;GACF;EACF;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"cursors.js","names":[],"sources":["../../src/collaboration/cursors.ts"],"sourcesContent":["import type { Node as PMNode } from 'prosemirror-model'\nimport { Plugin, PluginKey, type EditorState } from 'prosemirror-state'\nimport { Decoration, DecorationSet } from 'prosemirror-view'\nimport * as Y from 'yjs'\nimport { blockAround, findBlockById } from '../core/blocks'\nimport type { Binding, YBlock } from './binding'\nimport { cellAt, cellStart } from './table'\n\n/** What the editor needs of a Yjs awareness instance (`y-protocols/awareness`). */\nexport interface AwarenessLike {\n clientID: number\n getLocalState(): Record<string, unknown> | null\n setLocalStateField(field: string, value: unknown): void\n getStates(): Map<number, Record<string, unknown>>\n on(event: 'change', listener: (...args: unknown[]) => void): void\n off(event: 'change', listener: (...args: unknown[]) => void): void\n}\n\n/** A place in the text: the block and a position in its text that follows edits. */\nexport interface EditorPresencePlace {\n block: string\n /** In a table: the cell, `row id:column id`. */\n cell?: string\n /** A Yjs relative position as JSON (`Y.relativePositionToJSON`). */\n position: unknown\n}\ntype Place = EditorPresencePlace\n\n/**\n * Where a person's cursor is, shared in the awareness field `editor`\n * (`null` when they have none). The selection runs from `anchor` to\n * `head`; the cursor with the name is drawn at `head`.\n */\nexport interface EditorPresence {\n anchor: EditorPresencePlace\n head: EditorPresencePlace\n}\ntype Cursor = EditorPresence\n\n/** The text a place points into: the block's own, or one of its table cells. */\nfunction textOf(map: Y.Map<unknown>, block: string, cell?: string): Y.Text | undefined {\n const yblock = map.get(block)\n if (!(yblock instanceof Y.Map)) return undefined\n if (!cell) {\n // a table's text is in its cells\n if ((yblock as YBlock).has('cells')) return undefined\n const text = (yblock as YBlock).get('text')\n return text instanceof Y.Text ? text : undefined\n }\n const cells = (yblock as YBlock).get('cells')\n const text = cells instanceof Y.Map ? cells.get(cell) : undefined\n return text instanceof Y.Text ? text : undefined\n}\n\n/** A place in a block's text, given without an editor. */\nexport interface EditorCursorTarget {\n block: string\n /** In a table: the cell, `row id:column id`. */\n cell?: string\n /**\n * Where in the text: the number of characters before it (UTF-16 code\n * units, as `string.length` counts them; an inline node such as a mention\n * counts as one). Kept within the text; left out, its end.\n */\n offset?: number\n}\n\n/** Whether blocks of a stored type hold text of their own, e.g. not an image or a divider. */\nexport type HoldsText = (type: string) => boolean\n\nfunction placeAt(\n map: Y.Map<unknown>,\n target: EditorCursorTarget,\n holdsText: HoldsText,\n): Place | null {\n const yblock = map.get(target.block)\n if (!target.cell && yblock instanceof Y.Map && !holdsText(String(yblock.get('type')))) return null\n const text = textOf(map, target.block, target.cell)\n if (!text) return null\n const offset = Math.max(0, Math.min(Math.floor(target.offset ?? text.length), text.length))\n const position = Y.relativePositionToJSON(Y.createRelativePositionFromTypeIndex(text, offset))\n return target.cell\n ? { block: target.block, cell: target.cell, position }\n : { block: target.block, position }\n}\n\n/** A cursor at `head`, selecting from `anchor`; `null` when either has no text to be in. */\nexport function cursorIn(\n map: Y.Map<unknown>,\n head: EditorCursorTarget,\n anchor: EditorCursorTarget,\n holdsText: HoldsText,\n): EditorPresence | null {\n const to = placeAt(map, head, holdsText)\n const from = anchor === head ? to : placeAt(map, anchor, holdsText)\n return to && from ? { anchor: from, head: to } : null\n}\n\n/** A document position as a place that survives other people's edits. */\nexport function placeOf(binding: Binding, doc: PMNode, pos: number): Place | null {\n const info = blockAround(doc.resolve(pos))\n if (!info) return null\n const id = info.node.attrs.id as string\n let index = pos - info.contentPos - 1\n let cell: string | undefined\n if (info.content.type.spec.rows) {\n const found = cellAt(info.content, index)\n if (!found) return null\n cell = found.key\n index = found.index\n }\n const text = textOf(binding.map as Y.Map<unknown>, id, cell)\n if (!text) return null\n const offset = Math.max(0, Math.min(index, text.length))\n const position = Y.relativePositionToJSON(Y.createRelativePositionFromTypeIndex(text, offset))\n return cell ? { block: id, cell, position } : { block: id, position }\n}\n\n/** Back from a place to a document position, or `null` if its block is gone. */\nexport function positionOf(binding: Binding, doc: PMNode, place: Place): number | null {\n const info = findBlockById(doc, place.block)\n if (!info) return null\n const absolute = Y.createAbsolutePositionFromRelativePosition(\n Y.createRelativePositionFromJSON(place.position),\n binding.map.doc!,\n )\n let start = info.contentPos + 1\n let size = info.content.content.size\n if (place.cell) {\n const cell = info.content.type.spec.rows ? cellStart(info.content, place.cell) : null\n if (!cell) return null\n start += cell.offset\n size = cell.size\n }\n const offset =\n absolute && textOf(binding.map as Y.Map<unknown>, place.block, place.cell) === absolute.type\n ? Math.min(absolute.index, size)\n : 0\n return start + offset\n}\n\nfunction cursorElement(user: { name: string; color: string }) {\n const cursor = document.createElement('span')\n cursor.className = 'dou-editor__cursor'\n cursor.style.setProperty('--dou-editor-cursor-color', user.color)\n const label = document.createElement('span')\n label.className = 'dou-editor__cursor-label'\n label.textContent = user.name\n // word joiners keep the caret from breaking the line around it\n cursor.append('', label, '')\n return cursor\n}\n\nconst cursorsKey = new PluginKey<DecorationSet>('dou-editor-cursors')\n\nfunction decorations(binding: Binding, awareness: AwarenessLike, state: EditorState) {\n const found: Decoration[] = []\n awareness.getStates().forEach((value, client) => {\n if (client === awareness.clientID) return\n const cursor = value.editor as Cursor | null | undefined\n const user = value.user as { name?: string; color?: string } | undefined\n if (!cursor) return\n const anchor = positionOf(binding, state.doc, cursor.anchor)\n const head = positionOf(binding, state.doc, cursor.head)\n if (anchor === null || head === null) return\n const shown = { name: user?.name ?? '', color: user?.color ?? '#6b7280' }\n found.push(\n Decoration.widget(head, () => cursorElement(shown), {\n key: `cursor-${client}-${shown.name}-${shown.color}`,\n side: 10,\n }),\n )\n if (anchor !== head) {\n found.push(\n Decoration.inline(Math.min(anchor, head), Math.max(anchor, head), {\n class: 'dou-editor__remote-selection',\n style: `--dou-editor-cursor-color: ${shown.color}`,\n }),\n )\n }\n })\n return DecorationSet.create(state.doc, found)\n}\n\n/** Shares this user's cursor and shows everyone else's. */\nexport function cursorsPlugin(binding: Binding, awareness: AwarenessLike): Plugin {\n return new Plugin<DecorationSet>({\n key: cursorsKey,\n state: {\n init: (_config, state) => decorations(binding, awareness, state),\n apply(tr, value, _old, state) {\n if (tr.docChanged || tr.getMeta(cursorsKey)) return decorations(binding, awareness, state)\n return value\n },\n },\n props: {\n decorations(state) {\n return cursorsKey.getState(state)\n },\n },\n view(view) {\n let scheduled = false\n // others' cursors changed: redraw on the next frame, never inside a dispatch\n const onChange = () => {\n if (scheduled) return\n scheduled = true\n queueMicrotask(() => {\n scheduled = false\n if (binding.view === view) view.dispatch(view.state.tr.setMeta(cursorsKey, true))\n })\n }\n awareness.on('change', onChange)\n let last = ''\n const share = () => {\n let cursor: Cursor | null = null\n if (view.hasFocus()) {\n const { anchor, head } = view.state.selection\n const a = placeOf(binding, view.state.doc, anchor)\n const h = placeOf(binding, view.state.doc, head)\n if (a && h) cursor = { anchor: a, head: h }\n }\n const json = JSON.stringify(cursor)\n if (json === last) return\n last = json\n awareness.setLocalStateField('editor', cursor)\n }\n const onFocus = () => share()\n view.dom.addEventListener('focus', onFocus)\n view.dom.addEventListener('blur', onFocus)\n return {\n update: share,\n destroy() {\n awareness.off('change', onChange)\n view.dom.removeEventListener('focus', onFocus)\n view.dom.removeEventListener('blur', onFocus)\n awareness.setLocalStateField('editor', null)\n },\n }\n },\n })\n}\n"],"mappings":";;;;;;;AAwCA,SAAS,OAAO,KAAqB,OAAe,MAAmC;CACrF,MAAM,SAAS,IAAI,IAAI,KAAK;CAC5B,IAAI,EAAE,kBAAkB,EAAE,MAAM,OAAO,KAAA;CACvC,IAAI,CAAC,MAAM;EAET,IAAK,OAAkB,IAAI,OAAO,GAAG,OAAO,KAAA;EAC5C,MAAM,OAAQ,OAAkB,IAAI,MAAM;EAC1C,OAAO,gBAAgB,EAAE,OAAO,OAAO,KAAA;CACzC;CACA,MAAM,QAAS,OAAkB,IAAI,OAAO;CAC5C,MAAM,OAAO,iBAAiB,EAAE,MAAM,MAAM,IAAI,IAAI,IAAI,KAAA;CACxD,OAAO,gBAAgB,EAAE,OAAO,OAAO,KAAA;AACzC;AAkBA,SAAS,QACP,KACA,QACA,WACc;CACd,MAAM,SAAS,IAAI,IAAI,OAAO,KAAK;CACnC,IAAI,CAAC,OAAO,QAAQ,kBAAkB,EAAE,OAAO,CAAC,UAAU,OAAO,OAAO,IAAI,MAAM,CAAC,CAAC,GAAG,OAAO;CAC9F,MAAM,OAAO,OAAO,KAAK,OAAO,OAAO,OAAO,IAAI;CAClD,IAAI,CAAC,MAAM,OAAO;CAClB,MAAM,SAAS,KAAK,IAAI,GAAG,KAAK,IAAI,KAAK,MAAM,OAAO,UAAU,KAAK,MAAM,GAAG,KAAK,MAAM,CAAC;CAC1F,MAAM,WAAW,EAAE,uBAAuB,EAAE,oCAAoC,MAAM,MAAM,CAAC;CAC7F,OAAO,OAAO,OACV;EAAE,OAAO,OAAO;EAAO,MA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AAiB,SAAS,OAAO;GAC1C,KAAK,IAAI,iBAAiB,QAAQ,OAAO;GACzC,OAAO;IACL,QAAQ;IACR,UAAU;KACR,UAAU,IAAI,UAAU,QAAQ;KAChC,KAAK,IAAI,oBAAoB,SAAS,OAAO;KAC7C,KAAK,IAAI,oBAAoB,QAAQ,OAAO;KAC5C,UAAU,mBAAmB,UAAU,IAAI;IAC7C;GACF;EACF;CACF,CAAC;AACH"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { blocksToDoc, docToBlocks } from "../core/model.js";
|
|
2
2
|
import { defineEditorExtension, resolveEditorExtensions } from "../core/extension.js";
|
|
3
3
|
import { editorKit } from "../extensions/editor-kit.js";
|
|
4
|
-
import { cursorsPlugin, positionOf } from "./cursors.js";
|
|
4
|
+
import { cursorIn, cursorsPlugin, positionOf } from "./cursors.js";
|
|
5
5
|
import { createBinding, readDoc, syncPlugin, updateDoc, writeDoc } from "./binding.js";
|
|
6
6
|
import { applySharedCommentAction, collaborationColors, readSharedComments } from "dou-ui";
|
|
7
7
|
import { shallowRef } from "vue";
|
|
@@ -81,7 +81,34 @@ function collaboration(options) {
|
|
|
81
81
|
});
|
|
82
82
|
}
|
|
83
83
|
/** The extensions the editors of the shared document use; `[editorKit()]` when left out. */
|
|
84
|
-
var
|
|
84
|
+
var schemas = /* @__PURE__ */ new WeakMap();
|
|
85
|
+
var defaultSchema;
|
|
86
|
+
/** The schema of a list of extensions, resolved once per list; without one, of `[editorKit()]`. */
|
|
87
|
+
function schemaOf(extensions) {
|
|
88
|
+
if (!extensions) return defaultSchema ??= resolveEditorExtensions([editorKit()]).schema;
|
|
89
|
+
let schema = schemas.get(extensions);
|
|
90
|
+
if (!schema) {
|
|
91
|
+
schema = resolveEditorExtensions(extensions).schema;
|
|
92
|
+
schemas.set(extensions, schema);
|
|
93
|
+
}
|
|
94
|
+
return schema;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The value for the awareness field `editor` that puts a cursor at `head`,
|
|
98
|
+
* selecting from `options.anchor` when given, without an editor: e.g. on
|
|
99
|
+
* the server, for a program writing into the document with `updateMap`, so
|
|
100
|
+
* the people in the editor see where it writes. `null` when the block isn't
|
|
101
|
+
* in the map or has no text, e.g. an image, a divider, or a table without
|
|
102
|
+
* `cell`.
|
|
103
|
+
*/
|
|
104
|
+
function cursorAt(map, head, options = {}) {
|
|
105
|
+
const schema = schemaOf(options.extensions);
|
|
106
|
+
const holdsText = (name) => {
|
|
107
|
+
const known = schema.nodes[name];
|
|
108
|
+
return (known?.isInGroup("blockContent") ? known : schema.nodes.paragraph).inlineContent;
|
|
109
|
+
};
|
|
110
|
+
return cursorIn(map, head, options.anchor ?? head, holdsText);
|
|
111
|
+
}
|
|
85
112
|
/** Runs `write` as one transaction of the map's document, from `origin`. */
|
|
86
113
|
function transact(map, write, origin) {
|
|
87
114
|
if (map.doc) map.doc.transact(write, origin ?? null);
|
|
@@ -123,6 +150,6 @@ function readMap(map, options = {}) {
|
|
|
123
150
|
blocks: doc ? docToBlocks(doc) : []
|
|
124
151
|
};
|
|
125
152
|
}
|
|
126
|
-
export { collaboration, collaborationColors, fillMap, readMap, updateMap };
|
|
153
|
+
export { collaboration, collaborationColors, cursorAt, fillMap, readMap, updateMap };
|
|
127
154
|
|
|
128
155
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/collaboration/index.ts"],"sourcesContent":["import {\n applySharedCommentAction,\n collaborationColors,\n readSharedComments,\n type CommentThread,\n type SharedCommentMap,\n} from 'dou-ui'\nimport { shallowRef } from 'vue'\nimport { Plugin, TextSelection, type Command } from 'prosemirror-state'\nimport * as Y from 'yjs'\nimport {\n defineEditorExtension,\n resolveEditorExtensions,\n type EditorExtension,\n} from '../core/extension'\nimport { blocksToDoc, docToBlocks, type EditorDocument, type PartialBlock } from '../core/model'\nimport { editorKit } from '../extensions/editor-kit'\nimport { createBinding, readDoc, syncPlugin, updateDoc, writeDoc, type YBlock } from './binding'\nimport { cursorsPlugin, positionOf, type AwarenessLike } from './cursors'\n\n/** How the people editing together see each other. */\nexport interface CollaborationUser {\n name: string\n /** The cursor color, any CSS color. Picked from the client id when left out. */\n color?: string\n}\n\nexport interface CollaborationOptions {\n /** Where the document lives, e.g. `ydoc.getMap('document')`. */\n map: Y.Map<unknown>\n /** Shares cursors and selections (`y-protocols/awareness`). Without it, others' cursors are not shown. */\n awareness?: AwarenessLike\n /** This user, shown at their cursor to the others. Needs `awareness`. */\n user?: CollaborationUser\n /**\n * Where the comment threads live, e.g. `ydoc.getMap('comments')`, so\n * they reach everyone with the document. `v-model:comments` then only\n * mirrors them. Without it, the text's anchors still travel with the\n * document and the threads are the app's to share.\n */\n comments?: Y.Map<unknown>\n}\n\nexport { collaborationColors }\n\n/**\n * Edit together through a Yjs document. The document lives in `map`: the\n * editor's `v-model` only mirrors it and changes to `v-model` are not\n * written back. Undo only takes back this user's own changes.\n */\nexport function collaboration(options: CollaborationOptions): EditorExtension {\n const map = options.map as Y.Map<YBlock>\n const { awareness, user } = options\n if (awareness && user) {\n const color = user.color ?? collaborationColors[map.doc!.clientID % collaborationColors.length]\n awareness.setLocalStateField('user', { name: user.name, color })\n }\n const binding = createBinding(map)\n const undoManager = new Y.UndoManager(map, {\n trackedOrigins: new Set([binding.origin]),\n captureTimeout: 500,\n })\n binding.stopCapturing = () => undoManager.stopCapturing()\n // put the cursor back where it was when the change was made\n undoManager.on('stack-item-added', (event: { stackItem: { meta: Map<string, unknown> } }) => {\n if (!event.stackItem.meta.has('selection'))\n event.stackItem.meta.set('selection', binding.selectionBefore ?? null)\n })\n undoManager.on('stack-item-popped', (event: { stackItem: { meta: Map<string, unknown> } }) => {\n const view = binding.view\n const place = event.stackItem.meta.get('selection') as Parameters<typeof positionOf>[2] | null\n if (!view || !place) return\n const pos = positionOf(binding, view.state.doc, place)\n if (pos === null) return\n view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(pos))))\n })\n const run =\n (action: 'undo' | 'redo'): Command =>\n (_state, dispatch) => {\n const stack = action === 'undo' ? undoManager.undoStack : undoManager.redoStack\n if (!stack.length) return false\n if (dispatch) {\n binding.undoing = action\n try {\n undoManager[action]()\n } finally {\n binding.undoing = undefined\n }\n }\n return true\n }\n\n const shared = options.comments\n const threads = shallowRef<readonly CommentThread[]>([])\n const readThreads = () => (threads.value = readSharedComments(shared as SharedCommentMap))\n if (shared) readThreads()\n // follows the shared threads while the editor is there\n const commentsPlugin = new Plugin({\n view: () => {\n shared!.observe(readThreads)\n readThreads()\n return { destroy: () => shared!.unobserve(readThreads) }\n },\n })\n\n return defineEditorExtension({\n name: 'collaboration',\n externalDocument: true,\n comments: shared\n ? () => ({\n threads,\n apply: (action) =>\n applySharedCommentAction(shared as SharedCommentMap, action, binding.untracked),\n })\n : undefined,\n plugins: () => [\n syncPlugin(binding),\n ...(awareness ? [cursorsPlugin(binding, awareness)] : []),\n ...(shared ? [commentsPlugin] : []),\n ],\n history: () => ({ plugins: [], undo: run('undo'), redo: run('redo') }),\n })\n}\n\ntype ExtensionList = (EditorExtension | EditorExtension[])[]\n\n/** The extensions the editors of the shared document use; `[editorKit()]` when left out. */\nconst schemaOf = (extensions: ExtensionList = [editorKit()]) =>\n resolveEditorExtensions(extensions).schema\n\n/** Runs `write` as one transaction of the map's document, from `origin`. */\nfunction transact(map: Y.Map<unknown>, write: () => void, origin: unknown) {\n if (map.doc) map.doc.transact(write, origin ?? null)\n else write()\n}\n\nexport interface FillMapOptions {\n /** The extensions the editors use, for custom blocks. Defaults to `[editorKit()]`. */\n extensions?: ExtensionList\n /** The origin of the Yjs transaction, so the others can tell who wrote it. */\n origin?: unknown\n}\n\n/**\n * Write a document into an empty map, e.g. when a document that so far was\n * saved as JSON starts being edited together. Do it once, where the\n * document is created (often on the server): two clients filling the same\n * empty map at the same time would both add their copy.\n */\nexport function fillMap(\n map: Y.Map<unknown>,\n doc: EditorDocument<PartialBlock>,\n options: FillMapOptions = {},\n) {\n const schema = schemaOf(options.extensions)\n transact(\n map,\n () => writeDoc(map as Y.Map<YBlock>, blocksToDoc(schema, doc.blocks)),\n options.origin,\n )\n}\n\nexport interface UpdateMapOptions extends FillMapOptions {\n /**\n * The version `doc` was made from, e.g. the one read with `readMap` and\n * given to a program that took a while to write `doc`. Only what differs\n * between `base` and `doc` is written, so what others changed in the map\n * meanwhile stays. Get it the same way as `doc`: when `doc` is read from\n * Markdown, read `base` from the Markdown the program was given. Left\n * out, the map as it is now.\n */\n base?: EditorDocument<PartialBlock>\n}\n\n/**\n * Change a shared map from `options.base` to `doc`, without an editor, e.g.\n * on the server when a program wrote a new version while people edit the\n * document. Only what differs is written: blocks keep their id and their\n * text is changed character by character, so the cursors, undo and comment\n * threads of the others stay. Blocks with new ids (e.g. read from Markdown)\n * are matched to the stored ones by content and place; one that matches\n * none is written as a new block, and one left over is removed. An empty\n * map is filled.\n */\nexport function updateMap(\n map: Y.Map<unknown>,\n doc: EditorDocument<PartialBlock>,\n options: UpdateMapOptions = {},\n) {\n const schema = schemaOf(options.extensions)\n const { base } = options\n transact(\n map,\n () =>\n updateDoc(\n map as Y.Map<YBlock>,\n blocksToDoc(schema, doc.blocks),\n schema,\n base && blocksToDoc(schema, base.blocks),\n ),\n options.origin,\n )\n}\n\nexport interface ReadMapOptions {\n /** The extensions the editors use, for custom blocks. Defaults to `[editorKit()]`. */\n extensions?: ExtensionList\n}\n\n/**\n * The document a shared map holds, read without an editor, e.g. to save a\n * version on the server. An empty map reads as no blocks.\n */\nexport function readMap(map: Y.Map<unknown>, options: ReadMapOptions = {}): EditorDocument {\n const doc = readDoc(map as Y.Map<YBlock>, schemaOf(options.extensions))\n return { version: 1, blocks: doc ? docToBlocks(doc) : [] }\n}\n\nexport type { AwarenessLike }\n"],"mappings":";;;;;;;;;;;;;;;AAkDA,SAAgB,cAAc,SAAgD;CAC5E,MAAM,MAAM,QAAQ;CACpB,MAAM,EAAE,WAAW,SAAS;CAC5B,I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AAC;CACtE,OAAO;EAAE,SAAS;EAAG,QAAQ,MAAM,YAAY,GAAG,IAAI,CAAC;CAAE;AAC3D"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/collaboration/index.ts"],"sourcesContent":["import {\n applySharedCommentAction,\n collaborationColors,\n readSharedComments,\n type CommentThread,\n type SharedCommentMap,\n} from 'dou-ui'\nimport type { Schema } from 'prosemirror-model'\nimport { shallowRef } from 'vue'\nimport { Plugin, TextSelection, type Command } from 'prosemirror-state'\nimport * as Y from 'yjs'\nimport {\n defineEditorExtension,\n resolveEditorExtensions,\n type EditorExtension,\n} from '../core/extension'\nimport { blocksToDoc, docToBlocks, type EditorDocument, type PartialBlock } from '../core/model'\nimport { editorKit } from '../extensions/editor-kit'\nimport { createBinding, readDoc, syncPlugin, updateDoc, writeDoc, type YBlock } from './binding'\nimport {\n cursorIn,\n cursorsPlugin,\n positionOf,\n type AwarenessLike,\n type EditorCursorTarget,\n type EditorPresence,\n type EditorPresencePlace,\n} from './cursors'\n\n/** How the people editing together see each other. */\nexport interface CollaborationUser {\n name: string\n /** The cursor color, any CSS color. Picked from the client id when left out. */\n color?: string\n}\n\nexport interface CollaborationOptions {\n /** Where the document lives, e.g. `ydoc.getMap('document')`. */\n map: Y.Map<unknown>\n /** Shares cursors and selections (`y-protocols/awareness`). Without it, others' cursors are not shown. */\n awareness?: AwarenessLike\n /** This user, shown at their cursor to the others. Needs `awareness`. */\n user?: CollaborationUser\n /**\n * Where the comment threads live, e.g. `ydoc.getMap('comments')`, so\n * they reach everyone with the document. `v-model:comments` then only\n * mirrors them. Without it, the text's anchors still travel with the\n * document and the threads are the app's to share.\n */\n comments?: Y.Map<unknown>\n}\n\nexport { collaborationColors }\n\n/**\n * Edit together through a Yjs document. The document lives in `map`: the\n * editor's `v-model` only mirrors it and changes to `v-model` are not\n * written back. Undo only takes back this user's own changes.\n */\nexport function collaboration(options: CollaborationOptions): EditorExtension {\n const map = options.map as Y.Map<YBlock>\n const { awareness, user } = options\n if (awareness && user) {\n const color = user.color ?? collaborationColors[map.doc!.clientID % collaborationColors.length]\n awareness.setLocalStateField('user', { name: user.name, color })\n }\n const binding = createBinding(map)\n const undoManager = new Y.UndoManager(map, {\n trackedOrigins: new Set([binding.origin]),\n captureTimeout: 500,\n })\n binding.stopCapturing = () => undoManager.stopCapturing()\n // put the cursor back where it was when the change was made\n undoManager.on('stack-item-added', (event: { stackItem: { meta: Map<string, unknown> } }) => {\n if (!event.stackItem.meta.has('selection'))\n event.stackItem.meta.set('selection', binding.selectionBefore ?? null)\n })\n undoManager.on('stack-item-popped', (event: { stackItem: { meta: Map<string, unknown> } }) => {\n const view = binding.view\n const place = event.stackItem.meta.get('selection') as Parameters<typeof positionOf>[2] | null\n if (!view || !place) return\n const pos = positionOf(binding, view.state.doc, place)\n if (pos === null) return\n view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(pos))))\n })\n const run =\n (action: 'undo' | 'redo'): Command =>\n (_state, dispatch) => {\n const stack = action === 'undo' ? undoManager.undoStack : undoManager.redoStack\n if (!stack.length) return false\n if (dispatch) {\n binding.undoing = action\n try {\n undoManager[action]()\n } finally {\n binding.undoing = undefined\n }\n }\n return true\n }\n\n const shared = options.comments\n const threads = shallowRef<readonly CommentThread[]>([])\n const readThreads = () => (threads.value = readSharedComments(shared as SharedCommentMap))\n if (shared) readThreads()\n // follows the shared threads while the editor is there\n const commentsPlugin = new Plugin({\n view: () => {\n shared!.observe(readThreads)\n readThreads()\n return { destroy: () => shared!.unobserve(readThreads) }\n },\n })\n\n return defineEditorExtension({\n name: 'collaboration',\n externalDocument: true,\n comments: shared\n ? () => ({\n threads,\n apply: (action) =>\n applySharedCommentAction(shared as SharedCommentMap, action, binding.untracked),\n })\n : undefined,\n plugins: () => [\n syncPlugin(binding),\n ...(awareness ? [cursorsPlugin(binding, awareness)] : []),\n ...(shared ? [commentsPlugin] : []),\n ],\n history: () => ({ plugins: [], undo: run('undo'), redo: run('redo') }),\n })\n}\n\ntype ExtensionList = (EditorExtension | EditorExtension[])[]\n\n/** The extensions the editors of the shared document use; `[editorKit()]` when left out. */\nconst schemas = new WeakMap<ExtensionList, Schema>()\nlet defaultSchema: Schema | undefined\n\n/** The schema of a list of extensions, resolved once per list; without one, of `[editorKit()]`. */\nfunction schemaOf(extensions?: ExtensionList): Schema {\n if (!extensions) return (defaultSchema ??= resolveEditorExtensions([editorKit()]).schema)\n let schema = schemas.get(extensions)\n if (!schema) {\n schema = resolveEditorExtensions(extensions).schema\n schemas.set(extensions, schema)\n }\n return schema\n}\n\nexport interface CursorAtOptions {\n /** Where a selection starts; left out, only a cursor at `head`. */\n anchor?: EditorCursorTarget\n /** The extensions the editors use, for custom blocks. Defaults to `[editorKit()]`. */\n extensions?: ExtensionList\n}\n\n/**\n * The value for the awareness field `editor` that puts a cursor at `head`,\n * selecting from `options.anchor` when given, without an editor: e.g. on\n * the server, for a program writing into the document with `updateMap`, so\n * the people in the editor see where it writes. `null` when the block isn't\n * in the map or has no text, e.g. an image, a divider, or a table without\n * `cell`.\n */\nexport function cursorAt(\n map: Y.Map<unknown>,\n head: EditorCursorTarget,\n options: CursorAtOptions = {},\n): EditorPresence | null {\n const schema = schemaOf(options.extensions)\n const holdsText = (name: string) => {\n const known = schema.nodes[name]\n // unknown types are read as paragraphs\n const type = known?.isInGroup('blockContent') ? known : schema.nodes.paragraph!\n return type.inlineContent\n }\n return cursorIn(map, head, options.anchor ?? head, holdsText)\n}\n\n/** Runs `write` as one transaction of the map's document, from `origin`. */\nfunction transact(map: Y.Map<unknown>, write: () => void, origin: unknown) {\n if (map.doc) map.doc.transact(write, origin ?? null)\n else write()\n}\n\nexport interface FillMapOptions {\n /** The extensions the editors use, for custom blocks. Defaults to `[editorKit()]`. */\n extensions?: ExtensionList\n /** The origin of the Yjs transaction, so the others can tell who wrote it. */\n origin?: unknown\n}\n\n/**\n * Write a document into an empty map, e.g. when a document that so far was\n * saved as JSON starts being edited together. Do it once, where the\n * document is created (often on the server): two clients filling the same\n * empty map at the same time would both add their copy.\n */\nexport function fillMap(\n map: Y.Map<unknown>,\n doc: EditorDocument<PartialBlock>,\n options: FillMapOptions = {},\n) {\n const schema = schemaOf(options.extensions)\n transact(\n map,\n () => writeDoc(map as Y.Map<YBlock>, blocksToDoc(schema, doc.blocks)),\n options.origin,\n )\n}\n\nexport interface UpdateMapOptions extends FillMapOptions {\n /**\n * The version `doc` was made from, e.g. the one read with `readMap` and\n * given to a program that took a while to write `doc`. Only what differs\n * between `base` and `doc` is written, so what others changed in the map\n * meanwhile stays. Get it the same way as `doc`: when `doc` is read from\n * Markdown, read `base` from the Markdown the program was given. Left\n * out, the map as it is now.\n */\n base?: EditorDocument<PartialBlock>\n}\n\n/**\n * Change a shared map from `options.base` to `doc`, without an editor, e.g.\n * on the server when a program wrote a new version while people edit the\n * document. Only what differs is written: blocks keep their id and their\n * text is changed character by character, so the cursors, undo and comment\n * threads of the others stay. Blocks with new ids (e.g. read from Markdown)\n * are matched to the stored ones by content and place; one that matches\n * none is written as a new block, and one left over is removed. An empty\n * map is filled.\n */\nexport function updateMap(\n map: Y.Map<unknown>,\n doc: EditorDocument<PartialBlock>,\n options: UpdateMapOptions = {},\n) {\n const schema = schemaOf(options.extensions)\n const { base } = options\n transact(\n map,\n () =>\n updateDoc(\n map as Y.Map<YBlock>,\n blocksToDoc(schema, doc.blocks),\n schema,\n base && blocksToDoc(schema, base.blocks),\n ),\n options.origin,\n )\n}\n\nexport interface ReadMapOptions {\n /** The extensions the editors use, for custom blocks. Defaults to `[editorKit()]`. */\n extensions?: ExtensionList\n}\n\n/**\n * The document a shared map holds, read without an editor, e.g. to save a\n * version on the server. An empty map reads as no blocks.\n */\nexport function readMap(map: Y.Map<unknown>, options: ReadMapOptions = {}): EditorDocument {\n const doc = readDoc(map as Y.Map<YBlock>, schemaOf(options.extensions))\n return { version: 1, blocks: doc ? docToBlocks(doc) : [] }\n}\n\nexport type { AwarenessLike, EditorCursorTarget, EditorPresence, Edit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D;;AAGA,SAAS,SAAS,KAAqB,OAAmB,QAAiB;CACzE,IAAI,IAAI,KAAK,IAAI,IAAI,SAAS,OAAO,UAAU,IAAI;MAC9C,MAAM;AACb;;;;;;;AAeA,SAAgB,QACd,KACA,KACA,UAA0B,CAAC,GAC3B;CACA,MAAM,SAAS,SAAS,QAAQ,UAAU;CAC1C,SACE,WACM,SAAS,KAAsB,YAAY,QAAQ,IAAI,MAAM,CAAC,GACpE,QAAQ,MACV;AACF;;;;;;;;;;;AAwBA,SAAgB,UACd,KACA,KACA,UAA4B,CAAC,GAC7B;CACA,MAAM,SAAS,SAAS,QAAQ,UAAU;CAC1C,MAAM,EAAE,SAAS;CACjB,SACE,WAEE,UACE,KACA,YAAY,QAAQ,IAAI,MAAM,GAC9B,QACA,QAAQ,YAAY,QAAQ,KAAK,MAAM,CACzC,GACF,QAAQ,MACV;AACF;;;;;AAWA,SAAgB,QAAQ,KAAqB,UAA0B,CAAC,GAAmB;CACzF,MAAM,MAAM,QAAQ,KAAsB,SAAS,QAAQ,UAAU,CAAC;CACtE,OAAO;EAAE,SAAS;EAAG,QAAQ,MAAM,YAAY,GAAG,IAAI,CAAC;CAAE;AAC3D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block-handle.js","names":["_sfc_main"],"sources":["../../src/components/block-handle.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ArrowDownIcon,\n ArrowUpIcon,\n CheckIcon,\n CopyIcon,\n GripVerticalIcon,\n PlusIcon,\n TrashIcon,\n} from '@dou-ui/icons'\nimport { DouDropdown, DouDropdownItem, DouDropdownSub } from 'dou-ui'\nimport { TextSelection } from 'prosemirror-state'\nimport { computed, inject, onBeforeUnmount, onMounted, shallowRef, watch } from 'vue'\nimport { isCurrent } from '../catalog'\nimport { labelOf, type BlockOption } from '../core/extension'\nimport {\n blockSelectionKey,\n blockSelectionRange,\n getBlockSelection,\n selectBlocks,\n} from '../core/block-selection'\nimport {\n blockAround,\n blocksIn,\n findBlockById,\n siblingRangeBetween,\n type SiblingRange,\n} from '../core/blocks'\nimport {\n duplicateBlocks,\n insertBlockAfter,\n swapBlocks,\n moveRangeTo,\n deleteBlocks,\n setBlockType,\n} from '../core/commands'\nimport { blockFromNode } from '../core/model'\nimport { slashKey } from '../core/slash'\nimport { blockElementOf, contentAt, firstLine, scrollParent } from '../dom'\nimport { editorKey } from '../editor'\nimport { useMenuEscape } from './menu-escape'\n\nconst { view, state, focused, messages, root, dragging, kit } = inject(editorKey)!\n\n/**\n * Touch screens have no hover: there the handle shows only the grip, next\n * to the block with the cursor (or the selected blocks) while the editor\n * has focus. A tap on it opens the menu, a press and drag moves the block.\n */\nconst touch = shallowRef(false)\nlet media: MediaQueryList | null = null\nconst onMedia = () => (touch.value = !!media?.matches)\n\n/** The block the handle is next to, by id. */\nconst hovered = shallowRef<string | null>(null)\nconst position = shallowRef<{ top: number; left: number; height: number } | null>(null)\nconst menuOpen = shallowRef(false)\nuseMenuEscape(menuOpen, () => (menuOpen.value = false))\n\nconst drop = shallowRef<{ pos: number; top: number; left: number; width: number } | null>(null)\n// typing hides the handle until the pointer moves again\nconst resting = shallowRef(false)\n\nconst visible = computed(() => {\n if (!position.value) return false\n if (menuOpen.value || dragging.value) return true\n if (touch.value) return focused.value || (!!state.value && !!getBlockSelection(state.value))\n return !resting.value\n})\n\nfunction place(content: HTMLElement) {\n const block = blockElementOf(content)\n const id = block?.dataset.blockId\n const host = root.value\n if (!id || !host) return\n const box = host.getBoundingClientRect()\n const line = firstLine(content)\n hovered.value = id\n position.value = {\n top: line.top - box.top,\n left: content.getBoundingClientRect().left - box.left,\n height: line.height,\n }\n}\n\nlet frame = 0\nlet lastY = 0\nlet lastX = 0\n\nfunction track(event: PointerEvent) {\n // a finger only moves the handle by moving the cursor; a drag reports itself\n if (event.pointerType === 'touch') return\n lastY = event.clientY\n lastX = event.clientX\n resting.value = false\n if (menuOpen.value || frame) return\n frame = requestAnimationFrame(() => {\n frame = 0\n if (dragging.value) return updateDrop()\n const current = view.value\n if (!current || menuOpen.value) return\n const content = contentAt(current, lastY)\n if (content) place(content)\n })\n}\n\nfunction leave(event: PointerEvent) {\n if (menuOpen.value || dragging.value || event.pointerType === 'touch') return\n position.value = null\n hovered.value = null\n}\n\n/** On touch screens: put the handle next to the block with the cursor. */\nfunction follow() {\n const current = view.value\n if (!current || dragging.value) return\n const selected = blockSelectionRange(current.state)\n const info = selected ? blocksIn(selected)[0] : blockAround(current.state.selection.$from)\n const element = info\n ? (current.nodeDOM(info.pos) as HTMLElement | null)?.querySelector<HTMLElement>(\n ':scope > .dou-editor__content',\n )\n : null\n if (element) place(element)\n else {\n position.value = null\n hovered.value = null\n }\n}\n\nlet followFrame = 0\nfunction scheduleFollow() {\n if (!touch.value || followFrame) return\n followFrame = requestAnimationFrame(() => {\n followFrame = 0\n if (touch.value && !menuOpen.value) follow()\n })\n}\n\nwatch([state, focused, touch], scheduleFollow)\n\nonMounted(() => {\n media = window.matchMedia('(pointer: coarse)')\n onMedia()\n media.addEventListener('change', onMedia)\n window.addEventListener('resize', scheduleFollow)\n root.value?.addEventListener('pointermove', track)\n root.value?.addEventListener('pointerleave', leave)\n})\nonBeforeUnmount(() => {\n media?.removeEventListener('change', onMedia)\n window.removeEventListener('resize', scheduleFollow)\n if (followFrame) cancelAnimationFrame(followFrame)\n root.value?.removeEventListener('pointermove', track)\n root.value?.removeEventListener('pointerleave', leave)\n if (frame) cancelAnimationFrame(frame)\n stopDrag()\n})\n\n// follow edits: keep the handle on its block, or hide it while typing\nwatch(state, (next, previous) => {\n if (touch.value || !next || !previous || next.doc === previous.doc || dragging.value) return\n if (!menuOpen.value) resting.value = true\n requestAnimationFrame(() => {\n const current = view.value\n if (!current || !hovered.value) return\n const element = current.dom.querySelector<HTMLElement>(\n `[data-block-id=\"${CSS.escape(hovered.value)}\"] > .dou-editor__content`,\n )\n if (element) place(element)\n else position.value = null\n })\n})\n\nconst target = computed(() => {\n const doc = state.value?.doc\n return doc && hovered.value ? findBlockById(doc, hovered.value) : null\n})\n\n/** The hovered block, or every selected block when it is one of them. */\nfunction rangeForHovered(): SiblingRange | null {\n const current = view.value\n const info = target.value\n if (!current || !info) return null\n const selected = blockSelectionRange(current.state)\n if (selected && info.pos >= selected.start && info.pos < selected.end) return selected\n return siblingRangeBetween(current.state.doc, info.pos + 1, info.pos + 1)\n}\n\n/** Select the blocks the menu or a drag acts on. */\nfunction selectTarget(): SiblingRange | null {\n const current = view.value\n const range = rangeForHovered()\n if (!current || !range) return null\n const blocks = blocksIn(range)\n selectBlocks(blocks[0]!.node.attrs.id, blocks.at(-1)!.node.attrs.id)(\n current.state,\n current.dispatch,\n )\n return blockSelectionRange(current.state)\n}\n\n/* the + button */\n\nfunction add(event: MouseEvent) {\n const current = view.value\n const info = target.value\n if (!current || !info) return\n const empty = info.content.isTextblock && info.content.content.size === 0\n if (!empty || info.content.type.name !== 'paragraph') {\n insertBlockAfter(info.pos)(current.state, current.dispatch)\n // Alt+click adds the block above instead\n if (event.altKey) swapBlocks(-1)(current.state, current.dispatch)\n } else {\n const tr = current.state.tr.setSelection(\n TextSelection.create(current.state.doc, info.contentPos + 1),\n )\n current.dispatch(tr)\n }\n const from = current.state.selection.from\n current.dispatch(current.state.tr.insertText('/').setMeta(slashKey, { from, query: '' }))\n current.focus()\n}\n\n/* the block menu */\n\nconst turnOptions = kit.blockOptions.filter(\n (option) => !!kit.schema.nodes[option.type]?.isTextblock,\n)\nconst current = computed(() => {\n const info = target.value\n return info ? blockFromNode(info.node) : null\n})\n\nfunction after(action: () => void) {\n action()\n // the menu gives focus back to the handle; the editor takes it after\n requestAnimationFrame(() => view.value?.focus())\n}\n\nfunction keep(run: (current: NonNullable<typeof view.value>) => void) {\n after(() => {\n const instance = view.value\n if (!instance) return\n const selection = getBlockSelection(instance.state)\n run(instance)\n if (selection) selectBlocks(selection.anchor, selection.head)(instance.state, instance.dispatch)\n })\n}\n\nconst turnInto = (option: BlockOption) =>\n keep((instance) => setBlockType(option.type, option.props)(instance.state, instance.dispatch))\nconst duplicate = () => keep((instance) => duplicateBlocks(instance.state, instance.dispatch))\nconst move = (direction: -1 | 1) =>\n keep((instance) => swapBlocks(direction)(instance.state, instance.dispatch))\n\nfunction remove() {\n after(() => {\n const instance = view.value\n const range = instance && blockSelectionRange(instance.state)\n if (!instance || !range) return\n const tr = deleteBlocks(instance.state.tr, blocksIn(range)).setMeta(blockSelectionKey, null)\n instance.dispatch(tr.scrollIntoView())\n position.value = null\n })\n}\n\nconst canMove = (direction: -1 | 1) => {\n const instance = view.value\n return !!instance && !!state.value && swapBlocks(direction)(instance.state)\n}\n\n/* dragging */\n\nlet start: { x: number; y: number; pointer: number; touch: boolean } | null = null\nlet range: SiblingRange | null = null\nlet scroller: HTMLElement | null = null\nlet scrollFrame = 0\n/** A copy of the dragged blocks that follows the pointer. */\nlet ghost: HTMLElement | null = null\n\nfunction showGhost(moving: SiblingRange) {\n const instance = view.value\n const host = root.value\n if (!instance || !host) return\n ghost = document.createElement('div')\n ghost.className = 'dou-editor__surface dou-editor__ghost'\n ghost.setAttribute('aria-hidden', 'true')\n let width = 0\n for (const block of blocksIn(moving)) {\n const element = instance.nodeDOM(block.pos) as HTMLElement | null\n if (!element) continue\n width = Math.max(width, element.getBoundingClientRect().width)\n const copy = element.cloneNode(true) as HTMLElement\n copy.classList.remove('is-selected')\n for (const node of [copy, ...copy.querySelectorAll('[id], .is-selected')]) {\n node.removeAttribute('id')\n node.classList.remove('is-selected')\n }\n ghost.append(copy)\n }\n ghost.style.width = `${Math.min(width, 360)}px`\n host.append(ghost)\n moveGhost()\n}\n\nfunction moveGhost() {\n if (!ghost) return\n // above a finger, which would hide it; below and right of a mouse pointer\n const y = start?.touch ? lastY - ghost.offsetHeight - 24 : lastY + 12\n ghost.style.transform = `translate(${lastX + 12}px, ${y}px)`\n}\n\nfunction onGripDown(event: PointerEvent) {\n if (event.button !== 0) return\n start = {\n x: event.clientX,\n y: event.clientY,\n pointer: event.pointerId,\n touch: event.pointerType === 'touch',\n }\n ;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)\n}\n\nfunction onGripMove(event: PointerEvent) {\n if (!start || event.pointerId !== start.pointer) return\n lastX = event.clientX\n lastY = event.clientY\n if (!dragging.value) {\n // a finger wobbles more than a mouse while tapping\n const slop = start.touch ? 8 : 4\n if (Math.hypot(event.clientX - start.x, event.clientY - start.y) < slop) return\n range = selectTarget()\n if (!range) return stopDrag()\n dragging.value = true\n scroller = root.value && scrollParent(root.value)\n window.addEventListener('keydown', onDragKey, true)\n showGhost(range)\n autoScroll()\n }\n moveGhost()\n updateDrop()\n}\n\nfunction onGripUp(event: PointerEvent) {\n if (!start || event.pointerId !== start.pointer) return\n if (dragging.value) finishDrag()\n else if (menuOpen.value) menuOpen.value = false\n else {\n selectTarget()\n menuOpen.value = true\n }\n start = null\n}\n\nfunction onDragKey(event: KeyboardEvent) {\n if (event.key !== 'Escape') return\n event.preventDefault()\n event.stopPropagation()\n stopDrag()\n}\n\nfunction updateDrop() {\n const instance = view.value\n const host = root.value\n if (!instance || !host || !range) return\n const content = contentAt(instance, lastY)\n const id = content && blockElementOf(content)?.dataset.blockId\n const info = id ? findBlockById(instance.state.doc, id) : null\n if (!content || !info) return (drop.value = null)\n const box = host.getBoundingClientRect()\n const rect = content.getBoundingClientRect()\n const below = lastY > rect.top + rect.height / 2\n let pos: number\n let y: number\n let left = rect.left\n if (!below) {\n pos = info.pos\n y = rect.top\n } else if (info.group) {\n // the lower half of a block with children: in front of its first child\n pos = info.contentPos + info.content.nodeSize + 1\n y = rect.bottom\n const child = blockElementOf(content)?.querySelector<HTMLElement>(\n ':scope > .dou-editor__group > .dou-editor__block > .dou-editor__content',\n )\n left = child?.getBoundingClientRect().left ?? rect.left\n } else {\n pos = info.pos + info.node.nodeSize\n y = blockElementOf(content)!.getBoundingClientRect().bottom\n }\n if (!moveRangeTo(range, pos)(instance.state)) return (drop.value = null)\n // to the end of the text column, which a reading width can end before the editor\n drop.value = { pos, top: y - box.top, left: left - box.left, width: rect.right - left }\n}\n\nfunction autoScroll() {\n scrollFrame = requestAnimationFrame(() => {\n if (!dragging.value) return\n const edge = 48\n const top = scroller ? scroller.getBoundingClientRect().top : 0\n const bottom = scroller ? scroller.getBoundingClientRect().bottom : window.innerHeight\n let speed = 0\n if (lastY < top + edge) speed = -Math.ceil(((top + edge - lastY) / edge) * 16)\n else if (lastY > bottom - edge) speed = Math.ceil(((lastY - bottom + edge) / edge) * 16)\n if (speed) {\n if (scroller) scroller.scrollTop += speed\n else window.scrollBy(0, speed)\n updateDrop()\n }\n autoScroll()\n })\n}\n\nfunction finishDrag() {\n const instance = view.value\n const spot = drop.value\n const moving = range\n stopDrag()\n if (!instance || !spot || !moving) return\n const ids = blocksIn(moving).map((block) => block.node.attrs.id as string)\n if (!moveRangeTo(moving, spot.pos)(instance.state, instance.dispatch)) return\n selectBlocks(ids[0]!, ids.at(-1)!)(instance.state, instance.dispatch)\n instance.focus()\n}\n\nfunction stopDrag() {\n dragging.value = false\n drop.value = null\n range = null\n start = null\n ghost?.remove()\n ghost = null\n if (scrollFrame) cancelAnimationFrame(scrollFrame)\n scrollFrame = 0\n window.removeEventListener('keydown', onDragKey, true)\n}\n\nwatch(menuOpen, (value) => {\n if (value) return\n if (touch.value) scheduleFollow()\n else if (!root.value?.matches(':hover')) position.value = null\n})\n</script>\n\n<template>\n <div\n v-show=\"visible\"\n class=\"dou-editor__handle\"\n :style=\"\n position\n ? {\n top: `${position.top}px`,\n left: `${position.left}px`,\n '--dou-editor-line': `${position.height}px`,\n }\n : undefined\n \"\n @mousedown.prevent\n >\n <button\n type=\"button\"\n tabindex=\"-1\"\n class=\"dou-editor__handle-button dou-editor__add\"\n :aria-label=\"messages.addBlock\"\n :title=\"messages.addBlock\"\n @click=\"add\"\n >\n <PlusIcon />\n </button>\n <DouDropdown\n v-model:open=\"menuOpen\"\n trigger=\"manual\"\n placement=\"bottom-start\"\n class=\"dou-editor-menu\"\n >\n <button\n type=\"button\"\n tabindex=\"-1\"\n class=\"dou-editor__handle-button dou-editor__grip\"\n :aria-label=\"messages.dragHandle\"\n :title=\"messages.dragHandle\"\n @pointerdown=\"onGripDown\"\n @pointermove=\"onGripMove\"\n @pointerup=\"onGripUp\"\n @pointercancel=\"stopDrag\"\n >\n <GripVerticalIcon />\n </button>\n <template #menu>\n <DouDropdownSub :title=\"messages.turnInto\">\n <DouDropdownItem\n v-for=\"option in turnOptions\"\n :key=\"option.key\"\n @click=\"turnInto(option)\"\n >\n <template #prefix><component :is=\"option.icon\" /></template>\n {{ labelOf(option.label, messages) }}\n <template v-if=\"current && isCurrent(option, current.type, current.props)\" #suffix>\n <CheckIcon />\n </template>\n </DouDropdownItem>\n </DouDropdownSub>\n <template v-if=\"current\">\n <component\n :is=\"entry\"\n v-for=\"(entry, index) in kit.blockMenu\"\n :key=\"index\"\n :block=\"current\"\n />\n </template>\n <DouDropdownItem :shortcut=\"touch ? undefined : 'mod+d'\" @click=\"duplicate\">\n <template #prefix><CopyIcon /></template>\n {{ messages.duplicate }}\n </DouDropdownItem>\n <DouDropdownItem\n :disabled=\"!canMove(-1)\"\n :shortcut=\"touch ? undefined : 'mod+shift+up'\"\n @click=\"move(-1)\"\n >\n <template #prefix><ArrowUpIcon /></template>\n {{ messages.moveUp }}\n </DouDropdownItem>\n <DouDropdownItem\n :disabled=\"!canMove(1)\"\n :shortcut=\"touch ? undefined : 'mod+shift+down'\"\n @click=\"move(1)\"\n >\n <template #prefix><ArrowDownIcon /></template>\n {{ messages.moveDown }}\n </DouDropdownItem>\n <DouDropdownItem\n divided\n tone=\"danger\"\n :shortcut=\"touch ? undefined : 'delete'\"\n @click=\"remove\"\n >\n <template #prefix><TrashIcon /></template>\n {{ messages.delete }}\n </DouDropdownItem>\n </template>\n </DouDropdown>\n </div>\n <div\n v-if=\"drop\"\n class=\"dou-editor__drop\"\n :style=\"{ top: `${drop.top}px`, left: `${drop.left}px`, width: `${drop.width}px` }\"\n />\n</template>\n"],"mappings":""}
|
|
1
|
+
{"version":3,"file":"block-handle.js","names":["_sfc_main"],"sources":["../../src/components/block-handle.vue"],"sourcesContent":["<script setup lang=\"ts\">\nimport {\n ArrowDownIcon,\n ArrowUpIcon,\n CheckIcon,\n CopyIcon,\n GripVerticalIcon,\n PlusIcon,\n TrashIcon,\n} from '@dou-ui/icons'\nimport { DouDropdown, DouDropdownItem, DouDropdownSub } from 'dou-ui'\nimport { TextSelection } from 'prosemirror-state'\nimport { computed, inject, onBeforeUnmount, onMounted, shallowRef, watch } from 'vue'\nimport { isCurrent } from '../catalog'\nimport { labelOf, type BlockOption } from '../core/extension'\nimport {\n blockSelectionKey,\n blockSelectionRange,\n getBlockSelection,\n selectBlocks,\n} from '../core/block-selection'\nimport {\n blockAround,\n blocksIn,\n findBlockById,\n siblingRangeBetween,\n type SiblingRange,\n} from '../core/blocks'\nimport {\n duplicateBlocks,\n insertBlockAfter,\n swapBlocks,\n moveRangeTo,\n moveRangeToNewColumn,\n deleteBlocks,\n setBlockType,\n} from '../core/commands'\nimport { blockFromNode } from '../core/model'\nimport { slashKey } from '../core/slash'\nimport {\n blockElementOf,\n childBlocks,\n COLUMN_GROUP,\n contentAt,\n contentSpan,\n firstLine,\n handleLeft,\n scrollParent,\n sideBySide,\n} from '../dom'\nimport { editorKey } from '../editor'\nimport { useMenuEscape } from './menu-escape'\n\nconst { view, state, focused, messages, root, dragging, kit } = inject(editorKey)!\n\n/**\n * Touch screens have no hover: there the handle shows only the grip, next\n * to the block with the cursor (or the selected blocks) while the editor\n * has focus. A tap on it opens the menu, a press and drag moves the block.\n */\nconst touch = shallowRef(false)\nlet media: MediaQueryList | null = null\nconst onMedia = () => (touch.value = !!media?.matches)\n\n/** The block the handle is next to, by id. */\nconst hovered = shallowRef<string | null>(null)\nconst position = shallowRef<{ top: number; left: number; height: number } | null>(null)\n/** In a column the handle is only the grip, in the gap before it, leaving room for the resize bar. */\nconst compact = shallowRef(false)\nconst menuOpen = shallowRef(false)\nuseMenuEscape(menuOpen, () => (menuOpen.value = false))\n\n/**\n * Where a drag would drop: before or after a block (a line across), or\n * beside a column, into a new column (a line down, `column` set).\n */\ninterface Drop {\n pos: number\n top: number\n left: number\n width: number\n height?: number\n column?: { row: string; index: number }\n}\nconst drop = shallowRef<Drop | null>(null)\n// typing hides the handle until the pointer moves again\nconst resting = shallowRef(false)\n\nconst visible = computed(() => {\n if (!position.value) return false\n if (menuOpen.value || dragging.value) return true\n if (touch.value) return focused.value || (!!state.value && !!getBlockSelection(state.value))\n return !resting.value\n})\n\nfunction place(content: HTMLElement) {\n const block = blockElementOf(content)\n const id = block?.dataset.blockId\n const host = root.value\n if (!id || !host) return\n const box = host.getBoundingClientRect()\n const line = firstLine(content)\n hovered.value = id\n compact.value = !!content.closest(COLUMN_GROUP)\n position.value = {\n top: line.top - box.top,\n left: handleLeft(content) - box.left,\n height: line.height,\n }\n}\n\nlet frame = 0\nlet lastY = 0\nlet lastX = 0\n\nfunction track(event: PointerEvent) {\n // a finger only moves the handle by moving the cursor; a drag reports itself\n if (event.pointerType === 'touch') return\n lastY = event.clientY\n lastX = event.clientX\n resting.value = false\n if (menuOpen.value || frame) return\n frame = requestAnimationFrame(() => {\n frame = 0\n if (dragging.value) return updateDrop()\n const current = view.value\n if (!current || menuOpen.value) return\n const content = contentAt(current, lastY, lastX)\n if (content) place(content)\n })\n}\n\n/** A wide table scrolled sideways: the handle next to it follows its left edge. */\nfunction onScroll(event: Event) {\n const content = event.target\n if (\n !(content instanceof HTMLElement) ||\n !content.classList.contains('dou-editor__content--table')\n )\n return\n if (position.value && hovered.value && blockElementOf(content)?.dataset.blockId === hovered.value)\n place(content)\n}\n\nfunction leave(event: PointerEvent) {\n if (menuOpen.value || dragging.value || event.pointerType === 'touch') return\n position.value = null\n hovered.value = null\n}\n\n/** On touch screens: put the handle next to the block with the cursor. */\nfunction follow() {\n const current = view.value\n if (!current || dragging.value) return\n const selected = blockSelectionRange(current.state)\n const info = selected ? blocksIn(selected)[0] : blockAround(current.state.selection.$from)\n const element = info\n ? (current.nodeDOM(info.pos) as HTMLElement | null)?.querySelector<HTMLElement>(\n ':scope > .dou-editor__content',\n )\n : null\n if (element) place(element)\n else {\n position.value = null\n hovered.value = null\n }\n}\n\nlet followFrame = 0\nfunction scheduleFollow() {\n if (!touch.value || followFrame) return\n followFrame = requestAnimationFrame(() => {\n followFrame = 0\n if (touch.value && !menuOpen.value) follow()\n })\n}\n\nwatch([state, focused, touch], scheduleFollow)\n\nonMounted(() => {\n media = window.matchMedia('(pointer: coarse)')\n onMedia()\n media.addEventListener('change', onMedia)\n window.addEventListener('resize', scheduleFollow)\n root.value?.addEventListener('pointermove', track)\n root.value?.addEventListener('pointerleave', leave)\n root.value?.addEventListener('scroll', onScroll, true)\n})\nonBeforeUnmount(() => {\n media?.removeEventListener('change', onMedia)\n window.removeEventListener('resize', scheduleFollow)\n if (followFrame) cancelAnimationFrame(followFrame)\n root.value?.removeEventListener('pointermove', track)\n root.value?.removeEventListener('pointerleave', leave)\n root.value?.removeEventListener('scroll', onScroll, true)\n if (frame) cancelAnimationFrame(frame)\n stopDrag()\n})\n\n// follow edits: keep the handle on its block, or hide it while typing\nwatch(state, (next, previous) => {\n if (touch.value || !next || !previous || next.doc === previous.doc || dragging.value) return\n if (!menuOpen.value) resting.value = true\n requestAnimationFrame(() => {\n const current = view.value\n if (!current || !hovered.value) return\n const element = current.dom.querySelector<HTMLElement>(\n `[data-block-id=\"${CSS.escape(hovered.value)}\"] > .dou-editor__content`,\n )\n if (element) place(element)\n else position.value = null\n })\n})\n\nconst target = computed(() => {\n const doc = state.value?.doc\n return doc && hovered.value ? findBlockById(doc, hovered.value) : null\n})\n\n/** The hovered block, or every selected block when it is one of them. */\nfunction rangeForHovered(): SiblingRange | null {\n const current = view.value\n const info = target.value\n if (!current || !info) return null\n const selected = blockSelectionRange(current.state)\n if (selected && info.pos >= selected.start && info.pos < selected.end) return selected\n return siblingRangeBetween(current.state.doc, info.pos + 1, info.pos + 1)\n}\n\n/** Select the blocks the menu or a drag acts on. */\nfunction selectTarget(): SiblingRange | null {\n const current = view.value\n const range = rangeForHovered()\n if (!current || !range) return null\n const blocks = blocksIn(range)\n selectBlocks(blocks[0]!.node.attrs.id, blocks.at(-1)!.node.attrs.id)(\n current.state,\n current.dispatch,\n )\n return blockSelectionRange(current.state)\n}\n\n/* the + button */\n\nfunction add(event: MouseEvent) {\n const current = view.value\n const info = target.value\n if (!current || !info) return\n const empty = info.content.isTextblock && info.content.content.size === 0\n if (!empty || info.content.type.name !== 'paragraph') {\n insertBlockAfter(info.pos)(current.state, current.dispatch)\n // Alt+click adds the block above instead\n if (event.altKey) swapBlocks(-1)(current.state, current.dispatch)\n } else {\n const tr = current.state.tr.setSelection(\n TextSelection.create(current.state.doc, info.contentPos + 1),\n )\n current.dispatch(tr)\n }\n const from = current.state.selection.from\n current.dispatch(current.state.tr.insertText('/').setMeta(slashKey, { from, query: '' }))\n current.focus()\n}\n\n/* the block menu */\n\nconst turnOptions = kit.blockOptions.filter(\n (option) => !!kit.schema.nodes[option.type]?.isTextblock,\n)\nconst current = computed(() => {\n const info = target.value\n return info ? blockFromNode(info.node) : null\n})\n\nfunction after(action: () => void) {\n action()\n // the menu gives focus back to the handle; the editor takes it after\n requestAnimationFrame(() => view.value?.focus())\n}\n\nfunction keep(run: (current: NonNullable<typeof view.value>) => void) {\n after(() => {\n const instance = view.value\n if (!instance) return\n const selection = getBlockSelection(instance.state)\n run(instance)\n if (selection) selectBlocks(selection.anchor, selection.head)(instance.state, instance.dispatch)\n })\n}\n\nconst turnInto = (option: BlockOption) =>\n keep((instance) => setBlockType(option.type, option.props)(instance.state, instance.dispatch))\nconst duplicate = () => keep((instance) => duplicateBlocks(instance.state, instance.dispatch))\nconst move = (direction: -1 | 1) =>\n keep((instance) => swapBlocks(direction)(instance.state, instance.dispatch))\n\nfunction remove() {\n after(() => {\n const instance = view.value\n const range = instance && blockSelectionRange(instance.state)\n if (!instance || !range) return\n const tr = deleteBlocks(instance.state.tr, blocksIn(range)).setMeta(blockSelectionKey, null)\n instance.dispatch(tr.scrollIntoView())\n position.value = null\n })\n}\n\nconst canMove = (direction: -1 | 1) => {\n const instance = view.value\n return !!instance && !!state.value && swapBlocks(direction)(instance.state)\n}\n\n/* dragging */\n\nlet start: { x: number; y: number; pointer: number; touch: boolean } | null = null\nlet range: SiblingRange | null = null\nlet scroller: HTMLElement | null = null\nlet scrollFrame = 0\n/** A copy of the dragged blocks that follows the pointer. */\nlet ghost: HTMLElement | null = null\n\nfunction showGhost(moving: SiblingRange) {\n const instance = view.value\n const host = root.value\n if (!instance || !host) return\n ghost = document.createElement('div')\n ghost.className = 'dou-editor__surface dou-editor__ghost'\n ghost.setAttribute('aria-hidden', 'true')\n let width = 0\n for (const block of blocksIn(moving)) {\n const element = instance.nodeDOM(block.pos) as HTMLElement | null\n if (!element) continue\n width = Math.max(width, element.getBoundingClientRect().width)\n const copy = element.cloneNode(true) as HTMLElement\n copy.classList.remove('is-selected')\n for (const node of [copy, ...copy.querySelectorAll('[id], .is-selected')]) {\n node.removeAttribute('id')\n node.classList.remove('is-selected')\n }\n ghost.append(copy)\n }\n ghost.style.width = `${Math.min(width, 360)}px`\n host.append(ghost)\n moveGhost()\n}\n\nfunction moveGhost() {\n if (!ghost) return\n // above a finger, which would hide it; below and right of a mouse pointer\n const y = start?.touch ? lastY - ghost.offsetHeight - 24 : lastY + 12\n ghost.style.transform = `translate(${lastX + 12}px, ${y}px)`\n}\n\nfunction onGripDown(event: PointerEvent) {\n if (event.button !== 0) return\n start = {\n x: event.clientX,\n y: event.clientY,\n pointer: event.pointerId,\n touch: event.pointerType === 'touch',\n }\n ;(event.currentTarget as HTMLElement).setPointerCapture(event.pointerId)\n}\n\nfunction onGripMove(event: PointerEvent) {\n if (!start || event.pointerId !== start.pointer) return\n lastX = event.clientX\n lastY = event.clientY\n if (!dragging.value) {\n // a finger wobbles more than a mouse while tapping\n const slop = start.touch ? 8 : 4\n if (Math.hypot(event.clientX - start.x, event.clientY - start.y) < slop) return\n range = selectTarget()\n if (!range) return stopDrag()\n dragging.value = true\n scroller = root.value && scrollParent(root.value)\n window.addEventListener('keydown', onDragKey, true)\n showGhost(range)\n autoScroll()\n }\n moveGhost()\n updateDrop()\n}\n\nfunction onGripUp(event: PointerEvent) {\n if (!start || event.pointerId !== start.pointer) return\n if (dragging.value) finishDrag()\n else if (menuOpen.value) menuOpen.value = false\n else {\n selectTarget()\n menuOpen.value = true\n }\n start = null\n}\n\nfunction onDragKey(event: KeyboardEvent) {\n if (event.key !== 'Escape') return\n event.preventDefault()\n event.stopPropagation()\n stopDrag()\n}\n\n/** Beside a column, past its edge: a new column there, when the set takes one more. */\n/** How far into the last column a drop still makes a new column after it. */\nconst LAST_COLUMN_EDGE = 16\n\nfunction columnDrop(content: HTMLElement, moving: SiblingRange, box: DOMRect): Drop | null {\n const instance = view.value\n const group = content.closest<HTMLElement>(COLUMN_GROUP)\n const column = group?.parentElement\n const rowGroup = column?.parentElement\n const rowId = rowGroup?.parentElement?.dataset.blockId\n if (!instance || !column || !rowGroup || !rowId) return null\n const columns = childBlocks(rowGroup)\n const index = columns.indexOf(column)\n if (index < 0 || !sideBySide(columns)) return null\n const rect = column.getBoundingClientRect()\n // right of the last column there may be no room (the editor's edge): its last strip counts\n const right = index === columns.length - 1 ? rect.right - LAST_COLUMN_EDGE : rect.right\n const at = lastX < rect.left ? index : lastX > right ? index + 1 : -1\n if (at < 0) return null\n const row = findBlockById(instance.state.doc, rowId)\n if (!row || !moveRangeToNewColumn(moving, row.pos, at)(instance.state)) return null\n const gap =\n columns.length > 1\n ? columns[1]!.getBoundingClientRect().left - columns[0]!.getBoundingClientRect().right\n : 0\n const x =\n at === 0\n ? columns[0]!.getBoundingClientRect().left - gap / 2\n : at === columns.length\n ? columns.at(-1)!.getBoundingClientRect().right - 1\n : (columns[at - 1]!.getBoundingClientRect().right +\n columns[at]!.getBoundingClientRect().left) /\n 2\n const rowRect = rowGroup.getBoundingClientRect()\n return {\n pos: row.pos,\n top: rowRect.top - box.top,\n left: x - box.left,\n width: 0,\n height: rowRect.height,\n column: { row: rowId, index: at },\n }\n}\n\nfunction updateDrop() {\n const instance = view.value\n const host = root.value\n if (!instance || !host || !range) return\n const content = contentAt(instance, lastY, lastX)\n const id = content && blockElementOf(content)?.dataset.blockId\n const info = id ? findBlockById(instance.state.doc, id) : null\n if (!content || !info) return (drop.value = null)\n const box = host.getBoundingClientRect()\n const beside = columnDrop(content, range, box)\n if (beside) return (drop.value = beside)\n const rect = content.getBoundingClientRect()\n const span = contentSpan(content)\n const below = lastY > rect.top + rect.height / 2\n let pos: number\n let y: number\n let left = span.left\n if (!below) {\n pos = info.pos\n y = rect.top\n } else if (info.group) {\n // the lower half of a block with children: in front of its first child\n pos = info.contentPos + info.content.nodeSize + 1\n y = rect.bottom\n const child = blockElementOf(content)?.querySelector<HTMLElement>(\n ':scope > .dou-editor__group > .dou-editor__block > .dou-editor__content',\n )\n left = child ? contentSpan(child).left : span.left\n } else {\n pos = info.pos + info.node.nodeSize\n y = blockElementOf(content)!.getBoundingClientRect().bottom\n }\n if (!moveRangeTo(range, pos)(instance.state)) return (drop.value = null)\n // to the end of the text column, which a reading width can end before the editor\n drop.value = { pos, top: y - box.top, left: left - box.left, width: span.right - left }\n}\n\nfunction autoScroll() {\n scrollFrame = requestAnimationFrame(() => {\n if (!dragging.value) return\n const edge = 48\n const top = scroller ? scroller.getBoundingClientRect().top : 0\n const bottom = scroller ? scroller.getBoundingClientRect().bottom : window.innerHeight\n let speed = 0\n if (lastY < top + edge) speed = -Math.ceil(((top + edge - lastY) / edge) * 16)\n else if (lastY > bottom - edge) speed = Math.ceil(((lastY - bottom + edge) / edge) * 16)\n if (speed) {\n if (scroller) scroller.scrollTop += speed\n else window.scrollBy(0, speed)\n updateDrop()\n }\n autoScroll()\n })\n}\n\nfunction finishDrag() {\n const instance = view.value\n const spot = drop.value\n const moving = range\n stopDrag()\n if (!instance || !spot || !moving) return\n const ids = blocksIn(moving).map((block) => block.node.attrs.id as string)\n const row = spot.column && findBlockById(instance.state.doc, spot.column.row)\n const command = spot.column\n ? row && moveRangeToNewColumn(moving, row.pos, spot.column.index)\n : moveRangeTo(moving, spot.pos)\n if (!command || !command(instance.state, instance.dispatch)) return\n selectBlocks(ids[0]!, ids.at(-1)!)(instance.state, instance.dispatch)\n instance.focus()\n}\n\nfunction stopDrag() {\n dragging.value = false\n drop.value = null\n range = null\n start = null\n ghost?.remove()\n ghost = null\n if (scrollFrame) cancelAnimationFrame(scrollFrame)\n scrollFrame = 0\n window.removeEventListener('keydown', onDragKey, true)\n}\n\nwatch(menuOpen, (value) => {\n if (value) return\n if (touch.value) scheduleFollow()\n else if (!root.value?.matches(':hover')) position.value = null\n})\n</script>\n\n<template>\n <div\n v-show=\"visible\"\n :class=\"['dou-editor__handle', { 'is-compact': compact }]\"\n :style=\"\n position\n ? {\n top: `${position.top}px`,\n left: `${position.left}px`,\n '--dou-editor-line': `${position.height}px`,\n }\n : undefined\n \"\n @mousedown.prevent\n >\n <button\n type=\"button\"\n tabindex=\"-1\"\n class=\"dou-editor__handle-button dou-editor__add\"\n :aria-label=\"messages.addBlock\"\n :title=\"messages.addBlock\"\n @click=\"add\"\n >\n <PlusIcon />\n </button>\n <DouDropdown\n v-model:open=\"menuOpen\"\n trigger=\"manual\"\n placement=\"bottom-start\"\n class=\"dou-editor-menu\"\n >\n <button\n type=\"button\"\n tabindex=\"-1\"\n class=\"dou-editor__handle-button dou-editor__grip\"\n :aria-label=\"messages.dragHandle\"\n :title=\"messages.dragHandle\"\n @pointerdown=\"onGripDown\"\n @pointermove=\"onGripMove\"\n @pointerup=\"onGripUp\"\n @pointercancel=\"stopDrag\"\n >\n <GripVerticalIcon />\n </button>\n <template #menu>\n <DouDropdownSub :title=\"messages.turnInto\">\n <DouDropdownItem\n v-for=\"option in turnOptions\"\n :key=\"option.key\"\n @click=\"turnInto(option)\"\n >\n <template #prefix><component :is=\"option.icon\" /></template>\n {{ labelOf(option.label, messages) }}\n <template v-if=\"current && isCurrent(option, current.type, current.props)\" #suffix>\n <CheckIcon />\n </template>\n </DouDropdownItem>\n </DouDropdownSub>\n <template v-if=\"current\">\n <component\n :is=\"entry\"\n v-for=\"(entry, index) in kit.blockMenu\"\n :key=\"index\"\n :block=\"current\"\n />\n </template>\n <DouDropdownItem :shortcut=\"touch ? undefined : 'mod+d'\" @click=\"duplicate\">\n <template #prefix><CopyIcon /></template>\n {{ messages.duplicate }}\n </DouDropdownItem>\n <DouDropdownItem\n :disabled=\"!canMove(-1)\"\n :shortcut=\"touch ? undefined : 'mod+shift+up'\"\n @click=\"move(-1)\"\n >\n <template #prefix><ArrowUpIcon /></template>\n {{ messages.moveUp }}\n </DouDropdownItem>\n <DouDropdownItem\n :disabled=\"!canMove(1)\"\n :shortcut=\"touch ? undefined : 'mod+shift+down'\"\n @click=\"move(1)\"\n >\n <template #prefix><ArrowDownIcon /></template>\n {{ messages.moveDown }}\n </DouDropdownItem>\n <DouDropdownItem\n divided\n tone=\"danger\"\n :shortcut=\"touch ? undefined : 'delete'\"\n @click=\"remove\"\n >\n <template #prefix><TrashIcon /></template>\n {{ messages.delete }}\n </DouDropdownItem>\n </template>\n </DouDropdown>\n </div>\n <div\n v-if=\"drop\"\n :class=\"['dou-editor__drop', { 'is-vertical': drop.column }]\"\n :style=\"\n drop.column\n ? { top: `${drop.top}px`, left: `${drop.left}px`, height: `${drop.height}px` }\n : { top: `${drop.top}px`, left: `${drop.left}px`, width: `${drop.width}px` }\n \"\n />\n</template>\n"],"mappings":""}
|
|
@@ -2,19 +2,20 @@ import { blockFromNode } from "../core/model.js";
|
|
|
2
2
|
import { labelOf } from "../core/extension.js";
|
|
3
3
|
import { isCurrent } from "../catalog.js";
|
|
4
4
|
import { blockAround, blocksIn, findBlockById, siblingRangeBetween } from "../core/blocks.js";
|
|
5
|
-
import { deleteBlocks, duplicateBlocks, insertBlockAfter, moveRangeTo, setBlockType, swapBlocks } from "../core/commands.js";
|
|
5
|
+
import { deleteBlocks, duplicateBlocks, insertBlockAfter, moveRangeTo, moveRangeToNewColumn, setBlockType, swapBlocks } from "../core/commands.js";
|
|
6
6
|
import { blockSelectionKey, blockSelectionRange, getBlockSelection, selectBlocks } from "../core/block-selection.js";
|
|
7
7
|
import { slashKey } from "../core/slash.js";
|
|
8
|
-
import { blockElementOf, contentAt, firstLine, scrollParent } from "../dom.js";
|
|
8
|
+
import { COLUMN_GROUP, blockElementOf, childBlocks, contentAt, contentSpan, firstLine, handleLeft, scrollParent, sideBySide } from "../dom.js";
|
|
9
9
|
import { editorKey } from "../editor.js";
|
|
10
10
|
import { useMenuEscape } from "./menu-escape.js";
|
|
11
11
|
import { DouDropdown, DouDropdownItem, DouDropdownSub } from "dou-ui";
|
|
12
|
-
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createSlots, createTextVNode, createVNode, defineComponent, inject, normalizeStyle, onBeforeUnmount, onMounted, openBlock, renderList, resolveDynamicComponent, shallowRef, toDisplayString, unref, vShow, watch, withCtx, withDirectives, withModifiers } from "vue";
|
|
12
|
+
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createSlots, createTextVNode, createVNode, defineComponent, inject, normalizeClass, normalizeStyle, onBeforeUnmount, onMounted, openBlock, renderList, resolveDynamicComponent, shallowRef, toDisplayString, unref, vShow, watch, withCtx, withDirectives, withModifiers } from "vue";
|
|
13
13
|
import { TextSelection } from "prosemirror-state";
|
|
14
14
|
import { ArrowDownIcon, ArrowUpIcon, CheckIcon, CopyIcon, GripVerticalIcon, PlusIcon, TrashIcon } from "@dou-ui/icons";
|
|
15
15
|
// src/components/block-handle.vue?vue&type=script&setup=true&lang.ts
|
|
16
16
|
var _hoisted_1 = ["aria-label", "title"];
|
|
17
17
|
var _hoisted_2 = ["aria-label", "title"];
|
|
18
|
+
var LAST_COLUMN_EDGE = 16;
|
|
18
19
|
var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ defineComponent({
|
|
19
20
|
__name: "block-handle",
|
|
20
21
|
setup(__props) {
|
|
@@ -30,8 +31,14 @@ var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
|
|
|
30
31
|
/** The block the handle is next to, by id. */
|
|
31
32
|
const hovered = shallowRef(null);
|
|
32
33
|
const position = shallowRef(null);
|
|
34
|
+
/** In a column the handle is only the grip, in the gap before it, leaving room for the resize bar. */
|
|
35
|
+
const compact = shallowRef(false);
|
|
33
36
|
const menuOpen = shallowRef(false);
|
|
34
37
|
useMenuEscape(menuOpen, () => menuOpen.value = false);
|
|
38
|
+
/**
|
|
39
|
+
* Where a drag would drop: before or after a block (a line across), or
|
|
40
|
+
* beside a column, into a new column (a line down, `column` set).
|
|
41
|
+
*/
|
|
35
42
|
const drop = shallowRef(null);
|
|
36
43
|
const resting = shallowRef(false);
|
|
37
44
|
const visible = computed(() => {
|
|
@@ -47,9 +54,10 @@ var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
|
|
|
47
54
|
const box = host.getBoundingClientRect();
|
|
48
55
|
const line = firstLine(content);
|
|
49
56
|
hovered.value = id;
|
|
57
|
+
compact.value = !!content.closest(COLUMN_GROUP);
|
|
50
58
|
position.value = {
|
|
51
59
|
top: line.top - box.top,
|
|
52
|
-
left: content
|
|
60
|
+
left: handleLeft(content) - box.left,
|
|
53
61
|
height: line.height
|
|
54
62
|
};
|
|
55
63
|
}
|
|
@@ -67,10 +75,16 @@ var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
|
|
|
67
75
|
if (dragging.value) return updateDrop();
|
|
68
76
|
const current = view.value;
|
|
69
77
|
if (!current || menuOpen.value) return;
|
|
70
|
-
const content = contentAt(current, lastY);
|
|
78
|
+
const content = contentAt(current, lastY, lastX);
|
|
71
79
|
if (content) place(content);
|
|
72
80
|
});
|
|
73
81
|
}
|
|
82
|
+
/** A wide table scrolled sideways: the handle next to it follows its left edge. */
|
|
83
|
+
function onScroll(event) {
|
|
84
|
+
const content = event.target;
|
|
85
|
+
if (!(content instanceof HTMLElement) || !content.classList.contains("dou-editor__content--table")) return;
|
|
86
|
+
if (position.value && hovered.value && blockElementOf(content)?.dataset.blockId === hovered.value) place(content);
|
|
87
|
+
}
|
|
74
88
|
function leave(event) {
|
|
75
89
|
if (menuOpen.value || dragging.value || event.pointerType === "touch") return;
|
|
76
90
|
position.value = null;
|
|
@@ -109,6 +123,7 @@ var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
|
|
|
109
123
|
window.addEventListener("resize", scheduleFollow);
|
|
110
124
|
root.value?.addEventListener("pointermove", track);
|
|
111
125
|
root.value?.addEventListener("pointerleave", leave);
|
|
126
|
+
root.value?.addEventListener("scroll", onScroll, true);
|
|
112
127
|
});
|
|
113
128
|
onBeforeUnmount(() => {
|
|
114
129
|
media?.removeEventListener("change", onMedia);
|
|
@@ -116,6 +131,7 @@ var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
|
|
|
116
131
|
if (followFrame) cancelAnimationFrame(followFrame);
|
|
117
132
|
root.value?.removeEventListener("pointermove", track);
|
|
118
133
|
root.value?.removeEventListener("pointerleave", leave);
|
|
134
|
+
root.value?.removeEventListener("scroll", onScroll, true);
|
|
119
135
|
if (frame) cancelAnimationFrame(frame);
|
|
120
136
|
stopDrag();
|
|
121
137
|
});
|
|
@@ -284,27 +300,63 @@ var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
|
|
|
284
300
|
event.stopPropagation();
|
|
285
301
|
stopDrag();
|
|
286
302
|
}
|
|
303
|
+
/** Beside a column, past its edge: a new column there, when the set takes one more. */
|
|
304
|
+
/** How far into the last column a drop still makes a new column after it. */
|
|
305
|
+
function columnDrop(content, moving, box) {
|
|
306
|
+
const instance = view.value;
|
|
307
|
+
const column = content.closest(COLUMN_GROUP)?.parentElement;
|
|
308
|
+
const rowGroup = column?.parentElement;
|
|
309
|
+
const rowId = rowGroup?.parentElement?.dataset.blockId;
|
|
310
|
+
if (!instance || !column || !rowGroup || !rowId) return null;
|
|
311
|
+
const columns = childBlocks(rowGroup);
|
|
312
|
+
const index = columns.indexOf(column);
|
|
313
|
+
if (index < 0 || !sideBySide(columns)) return null;
|
|
314
|
+
const rect = column.getBoundingClientRect();
|
|
315
|
+
const right = index === columns.length - 1 ? rect.right - LAST_COLUMN_EDGE : rect.right;
|
|
316
|
+
const at = lastX < rect.left ? index : lastX > right ? index + 1 : -1;
|
|
317
|
+
if (at < 0) return null;
|
|
318
|
+
const row = findBlockById(instance.state.doc, rowId);
|
|
319
|
+
if (!row || !moveRangeToNewColumn(moving, row.pos, at)(instance.state)) return null;
|
|
320
|
+
const gap = columns.length > 1 ? columns[1].getBoundingClientRect().left - columns[0].getBoundingClientRect().right : 0;
|
|
321
|
+
const x = at === 0 ? columns[0].getBoundingClientRect().left - gap / 2 : at === columns.length ? columns.at(-1).getBoundingClientRect().right - 1 : (columns[at - 1].getBoundingClientRect().right + columns[at].getBoundingClientRect().left) / 2;
|
|
322
|
+
const rowRect = rowGroup.getBoundingClientRect();
|
|
323
|
+
return {
|
|
324
|
+
pos: row.pos,
|
|
325
|
+
top: rowRect.top - box.top,
|
|
326
|
+
left: x - box.left,
|
|
327
|
+
width: 0,
|
|
328
|
+
height: rowRect.height,
|
|
329
|
+
column: {
|
|
330
|
+
row: rowId,
|
|
331
|
+
index: at
|
|
332
|
+
}
|
|
333
|
+
};
|
|
334
|
+
}
|
|
287
335
|
function updateDrop() {
|
|
288
336
|
const instance = view.value;
|
|
289
337
|
const host = root.value;
|
|
290
338
|
if (!instance || !host || !range) return;
|
|
291
|
-
const content = contentAt(instance, lastY);
|
|
339
|
+
const content = contentAt(instance, lastY, lastX);
|
|
292
340
|
const id = content && blockElementOf(content)?.dataset.blockId;
|
|
293
341
|
const info = id ? findBlockById(instance.state.doc, id) : null;
|
|
294
342
|
if (!content || !info) return drop.value = null;
|
|
295
343
|
const box = host.getBoundingClientRect();
|
|
344
|
+
const beside = columnDrop(content, range, box);
|
|
345
|
+
if (beside) return drop.value = beside;
|
|
296
346
|
const rect = content.getBoundingClientRect();
|
|
347
|
+
const span = contentSpan(content);
|
|
297
348
|
const below = lastY > rect.top + rect.height / 2;
|
|
298
349
|
let pos;
|
|
299
350
|
let y;
|
|
300
|
-
let left =
|
|
351
|
+
let left = span.left;
|
|
301
352
|
if (!below) {
|
|
302
353
|
pos = info.pos;
|
|
303
354
|
y = rect.top;
|
|
304
355
|
} else if (info.group) {
|
|
305
356
|
pos = info.contentPos + info.content.nodeSize + 1;
|
|
306
357
|
y = rect.bottom;
|
|
307
|
-
|
|
358
|
+
const child = blockElementOf(content)?.querySelector(":scope > .dou-editor__group > .dou-editor__block > .dou-editor__content");
|
|
359
|
+
left = child ? contentSpan(child).left : span.left;
|
|
308
360
|
} else {
|
|
309
361
|
pos = info.pos + info.node.nodeSize;
|
|
310
362
|
y = blockElementOf(content).getBoundingClientRect().bottom;
|
|
@@ -314,7 +366,7 @@ var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
|
|
|
314
366
|
pos,
|
|
315
367
|
top: y - box.top,
|
|
316
368
|
left: left - box.left,
|
|
317
|
-
width:
|
|
369
|
+
width: span.right - left
|
|
318
370
|
};
|
|
319
371
|
}
|
|
320
372
|
function autoScroll() {
|
|
@@ -341,7 +393,9 @@ var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
|
|
|
341
393
|
stopDrag();
|
|
342
394
|
if (!instance || !spot || !moving) return;
|
|
343
395
|
const ids = blocksIn(moving).map((block) => block.node.attrs.id);
|
|
344
|
-
|
|
396
|
+
const row = spot.column && findBlockById(instance.state.doc, spot.column.row);
|
|
397
|
+
const command = spot.column ? row && moveRangeToNewColumn(moving, row.pos, spot.column.index) : moveRangeTo(moving, spot.pos);
|
|
398
|
+
if (!command || !command(instance.state, instance.dispatch)) return;
|
|
345
399
|
selectBlocks(ids[0], ids.at(-1))(instance.state, instance.dispatch);
|
|
346
400
|
instance.focus();
|
|
347
401
|
}
|
|
@@ -363,7 +417,7 @@ var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
|
|
|
363
417
|
});
|
|
364
418
|
return (_ctx, _cache) => {
|
|
365
419
|
return openBlock(), createElementBlock(Fragment, null, [withDirectives(createElementVNode("div", {
|
|
366
|
-
class: "dou-editor__handle",
|
|
420
|
+
class: normalizeClass(["dou-editor__handle", { "is-compact": compact.value }]),
|
|
367
421
|
style: normalizeStyle(position.value ? {
|
|
368
422
|
top: `${position.value.top}px`,
|
|
369
423
|
left: `${position.value.left}px`,
|
|
@@ -457,15 +511,19 @@ var block_handle_vue_vue_type_script_setup_true_lang_default = /*@__PURE__*/ def
|
|
|
457
511
|
onPointercancel: stopDrag
|
|
458
512
|
}, [createVNode(unref(GripVerticalIcon))], 40, _hoisted_2)]),
|
|
459
513
|
_: 1
|
|
460
|
-
}, 8, ["open"])],
|
|
514
|
+
}, 8, ["open"])], 38), [[vShow, visible.value]]), drop.value ? (openBlock(), createElementBlock("div", {
|
|
461
515
|
key: 0,
|
|
462
|
-
class: "dou-editor__drop",
|
|
463
|
-
style: normalizeStyle({
|
|
516
|
+
class: normalizeClass(["dou-editor__drop", { "is-vertical": drop.value.column }]),
|
|
517
|
+
style: normalizeStyle(drop.value.column ? {
|
|
518
|
+
top: `${drop.value.top}px`,
|
|
519
|
+
left: `${drop.value.left}px`,
|
|
520
|
+
height: `${drop.value.height}px`
|
|
521
|
+
} : {
|
|
464
522
|
top: `${drop.value.top}px`,
|
|
465
523
|
left: `${drop.value.left}px`,
|
|
466
524
|
width: `${drop.value.width}px`
|
|
467
525
|
})
|
|
468
|
-
}, null,
|
|
526
|
+
}, null, 6)) : createCommentVNode("", true)], 64);
|
|
469
527
|
};
|
|
470
528
|
}
|
|
471
529
|
});
|