@daasboard/editor 0.0.0-stage → 0.1.0

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.
Files changed (83) hide show
  1. package/LICENSE +5 -0
  2. package/README.md +6 -2
  3. package/dist/camera/CameraInput.d.ts +106 -0
  4. package/dist/camera/CameraInput.js +398 -0
  5. package/dist/clipboard/ObjectClipboard.d.ts +40 -0
  6. package/dist/clipboard/ObjectClipboard.js +243 -0
  7. package/dist/clipboard/PasteCommitError.d.ts +4 -0
  8. package/dist/clipboard/PasteCommitError.js +7 -0
  9. package/dist/clipboard/carrier.d.ts +5 -0
  10. package/dist/clipboard/carrier.js +59 -0
  11. package/dist/clipboard/objects.d.ts +21 -0
  12. package/dist/clipboard/objects.js +362 -0
  13. package/dist/clipboard/placement.d.ts +11 -0
  14. package/dist/clipboard/placement.js +21 -0
  15. package/dist/clipboard/systemImages.d.ts +1 -0
  16. package/dist/clipboard/systemImages.js +24 -0
  17. package/dist/index.d.ts +23 -0
  18. package/dist/index.js +22 -0
  19. package/dist/input/TouchInput.d.ts +159 -0
  20. package/dist/input/TouchInput.js +656 -0
  21. package/dist/input/visiblePart.d.ts +8 -0
  22. package/dist/input/visiblePart.js +15 -0
  23. package/dist/interaction/InteractionLayer.d.ts +83 -0
  24. package/dist/interaction/InteractionLayer.js +520 -0
  25. package/dist/props/PropertyController.d.ts +130 -0
  26. package/dist/props/PropertyController.js +1448 -0
  27. package/dist/props/PropertyRegistry.d.ts +38 -0
  28. package/dist/props/PropertyRegistry.js +21 -0
  29. package/dist/props/builtinProperties.d.ts +23 -0
  30. package/dist/props/builtinProperties.js +350 -0
  31. package/dist/props/defaults.d.ts +6 -0
  32. package/dist/props/defaults.js +29 -0
  33. package/dist/selection/SelectionModel.d.ts +25 -0
  34. package/dist/selection/SelectionModel.js +79 -0
  35. package/dist/text/CanvasEditorView.d.ts +99 -0
  36. package/dist/text/CanvasEditorView.js +308 -0
  37. package/dist/text/InputSink.d.ts +157 -0
  38. package/dist/text/InputSink.js +841 -0
  39. package/dist/text/TextEditSession.d.ts +173 -0
  40. package/dist/text/TextEditSession.js +1328 -0
  41. package/dist/text/clipboard.d.ts +11 -0
  42. package/dist/text/clipboard.js +489 -0
  43. package/dist/text/commands.d.ts +48 -0
  44. package/dist/text/commands.js +329 -0
  45. package/dist/text/contextMirror.d.ts +51 -0
  46. package/dist/text/contextMirror.js +292 -0
  47. package/dist/text/flat.d.ts +35 -0
  48. package/dist/text/flat.js +556 -0
  49. package/dist/text/graphemes.d.ts +16 -0
  50. package/dist/text/graphemes.js +219 -0
  51. package/dist/text/index.d.ts +13 -0
  52. package/dist/text/index.js +13 -0
  53. package/dist/text/inputReducer.d.ts +24 -0
  54. package/dist/text/inputReducer.js +44 -0
  55. package/dist/text/keymap.d.ts +17 -0
  56. package/dist/text/keymap.js +148 -0
  57. package/dist/text/schema.d.ts +12 -0
  58. package/dist/text/schema.js +44 -0
  59. package/dist/text/sessionFocus.d.ts +20 -0
  60. package/dist/text/sessionFocus.js +51 -0
  61. package/dist/text/types.d.ts +114 -0
  62. package/dist/text/types.js +1 -0
  63. package/dist/tools/CreateTool.d.ts +78 -0
  64. package/dist/tools/CreateTool.js +258 -0
  65. package/dist/tools/SelectTool.d.ts +155 -0
  66. package/dist/tools/SelectTool.js +808 -0
  67. package/dist/tools/ToolManager.d.ts +63 -0
  68. package/dist/tools/ToolManager.js +146 -0
  69. package/dist/tools/connectorEndpoints.d.ts +17 -0
  70. package/dist/tools/connectorEndpoints.js +53 -0
  71. package/dist/tools/frameRotation.d.ts +8 -0
  72. package/dist/tools/frameRotation.js +66 -0
  73. package/dist/tools/gradientHandles.d.ts +67 -0
  74. package/dist/tools/gradientHandles.js +110 -0
  75. package/dist/tools/presetPaths.d.ts +5 -0
  76. package/dist/tools/presetPaths.js +49 -0
  77. package/dist/tools/snapResize.d.ts +7 -0
  78. package/dist/tools/snapResize.js +65 -0
  79. package/dist/tools/snapping.d.ts +30 -0
  80. package/dist/tools/snapping.js +280 -0
  81. package/dist/tools/transform.d.ts +52 -0
  82. package/dist/tools/transform.js +277 -0
  83. package/package.json +36 -3
@@ -0,0 +1,1328 @@
1
+ import { TextLayoutCache, textOrigin } from "@daasboard/render-core";
2
+ import { applyDeltaToString, emptyTextContent, flatToContent, isEmptyTextContent, TEXT_CASES } from "@daasboard/doc";
3
+ import { EditorState, TextSelection } from "prosemirror-state";
4
+ import { CARET_AFFINITY, CanvasEditorView, graphemeCaretEdge, selectionRects } from "./CanvasEditorView.js";
5
+ import { applyMark, backspace, del, enter, insertHardBreak, lineBackspace, lineDelete, MAX_INDENT, setParagraphAttr, windowsWordDelete, wordBackspace, wordDelete } from "./commands.js";
6
+ import { clipboardTransaction, serializeClipboard } from "./clipboard.js";
7
+ import { prevGraphemeStart, wordRanges } from "./graphemes.js";
8
+ import { changedParagraphs, contentToPm, offsetToPmPos, paragraphIndexAtOffset, paragraphIndexAtPos, paragraphStarts, pmDiffToDelta, pmPosToOffset, pmToContent, pmToFlat, pmToText, snapDown, snapUp, EMPTY_ATTRS } from "./flat.js";
9
+ import { buildKeymap, handleKey, keyCodeFromCode, resolveTextPlatform } from "./keymap.js";
10
+ import { INLINE_MARK_KEYS, PARAGRAPH_ATTR_KEYS, markType, paragraphType } from "./schema.js";
11
+ export const FROM_DOC = "textEditSession/fromDoc";
12
+ export const LABEL = "textEditSession/label";
13
+ const ALSO = "textEditSession/also";
14
+ const MOVED = "textEditSession/moved";
15
+ const BY_UNIT = "textEditSession/byUnit";
16
+ export const BLINK_MS = 500;
17
+ const INLINE_KEY_SET = new Set(INLINE_MARK_KEYS);
18
+ const PARAGRAPH_KEY_SET = new Set(PARAGRAPH_ATTR_KEYS);
19
+ const isInlineKey = (k) => INLINE_KEY_SET.has(k);
20
+ const isParagraphKey = (k) => PARAGRAPH_KEY_SET.has(k);
21
+ const isClear = (v) => v === undefined || v === null;
22
+ const defaultNow = () => (typeof performance !== "undefined" ? performance.now() : Date.now());
23
+ export class TextEditSession {
24
+ objectId;
25
+ view;
26
+ texts;
27
+ doc;
28
+ renderer;
29
+ selection;
30
+ toClient;
31
+ onChange;
32
+ onEnd;
33
+ onPresenceCaret;
34
+ now;
35
+ keymap;
36
+ windows;
37
+ ownsTexts;
38
+ unsubscribeDoc;
39
+ unsubscribeSelection;
40
+ ended = false;
41
+ writing = false;
42
+ lastActivity;
43
+ localVersion = 0;
44
+ live = null;
45
+ liveContent = null;
46
+ liveBase = null;
47
+ liveBaseVersion = -1;
48
+ liveBaseTextVersion = -1;
49
+ liveDoc = null;
50
+ livePreedit = null;
51
+ liveFitted;
52
+ previewing = null;
53
+ previewed = null;
54
+ drawn = null;
55
+ lastBase;
56
+ matchedText;
57
+ preeditText = null;
58
+ preeditFrom = 0;
59
+ preeditReplaceTo = 0;
60
+ dragAnchor = null;
61
+ pressed = false;
62
+ words = null;
63
+ settledAffinity = "downstream";
64
+ deferRebuild = false;
65
+ deferredDeltas = null;
66
+ fresh;
67
+ mirror;
68
+ mirrorHooks = null;
69
+ constructor(opts) {
70
+ this.objectId = opts.objectId;
71
+ this.doc = opts.doc;
72
+ this.renderer = opts.renderer;
73
+ this.selection = opts.selection;
74
+ this.toClient = opts.toClient ?? ((p) => p);
75
+ this.onChange = opts.onChange;
76
+ this.onEnd = opts.onEnd;
77
+ this.onPresenceCaret = opts.onPresenceCaret;
78
+ this.now = opts.now ?? defaultNow;
79
+ const platform = resolveTextPlatform(opts);
80
+ this.keymap = buildKeymap(platform);
81
+ this.windows = platform.windows;
82
+ this.ownsTexts = !opts.texts;
83
+ this.texts = opts.texts ?? new TextLayoutCache(opts.renderer, opts.fallbacks ?? (() => []));
84
+ const base = this.doc.get(this.objectId);
85
+ if (!base)
86
+ throw new Error(`TextEditSession: no object ${this.objectId}`);
87
+ this.doc.endTyping();
88
+ this.lastBase = base;
89
+ this.matchedText = base.text;
90
+ this.lastActivity = this.now();
91
+ this.fresh = !!opts.discardIfUntouched;
92
+ const pmDoc = contentToPm(base.text ?? emptyTextContent());
93
+ const state = EditorState.create({ doc: pmDoc, selection: TextSelection.create(pmDoc, pmDoc.content.size - 1) });
94
+ const provider = {
95
+ renderer: this.renderer,
96
+ layout: () => (this.ended ? null : this.texts.get(this.drawnObject())),
97
+ origin: () => {
98
+ if (this.ended)
99
+ return textOrigin(this.lastBase, 0);
100
+ const o = this.drawnObject();
101
+ return textOrigin(o, this.texts.get(o)?.height ?? 0);
102
+ },
103
+ };
104
+ this.view = new CanvasEditorView({ state, layout: provider, dispatchTransaction: (tr) => this.onTransaction(tr), props: { markDefault: (name) => this.objectDefault(name) } });
105
+ this.mirror = {
106
+ length: () => {
107
+ const doc = this.view.state.doc;
108
+ return paragraphStarts(doc)[doc.childCount];
109
+ },
110
+ text: (from, to) => flatSlice(this.view.state.doc, from, to),
111
+ selection: () => {
112
+ const { doc, selection } = this.view.state;
113
+ return { anchor: pmPosToOffset(doc, selection.anchor), head: pmPosToOffset(doc, selection.head) };
114
+ },
115
+ textVersion: () => this.view.state.doc,
116
+ replace: (from, to, text, anchor, head) => this.replaceFlat(from, to, text, anchor, head),
117
+ select: (anchor, head) => {
118
+ if (!this.ended)
119
+ this.selectRange(anchor, head);
120
+ },
121
+ compose: (from, to, text) => this.compose(from, to, text),
122
+ composition: () => (this.preeditText !== null ? { from: this.preeditFrom, to: this.preeditReplaceTo } : null),
123
+ connect: (hooks) => {
124
+ this.mirrorHooks = hooks;
125
+ return () => {
126
+ if (this.mirrorHooks === hooks)
127
+ this.mirrorHooks = null;
128
+ };
129
+ },
130
+ };
131
+ if (base.kind === "text")
132
+ this.liveObject();
133
+ this.view.focus();
134
+ this.syncSelection();
135
+ this.unsubscribeDoc = this.doc.subscribe((cs, meta) => this.onDocChange(cs, meta));
136
+ this.unsubscribeSelection = this.selection.onChange(() => {
137
+ if (!this.ended && !this.selection.has(this.objectId))
138
+ this.end();
139
+ });
140
+ }
141
+ get state() {
142
+ return this.view.state;
143
+ }
144
+ get active() {
145
+ return !this.ended;
146
+ }
147
+ get composing() {
148
+ return this.preeditText !== null;
149
+ }
150
+ onTransaction(tr) {
151
+ const before = this.view.state;
152
+ const snapshot = { state: before, affinity: this.settledAffinity, preeditFrom: this.preeditFrom, preeditReplaceTo: this.preeditReplaceTo, dragAnchor: this.dragAnchor };
153
+ const next = before.apply(tr);
154
+ this.view.updateState(next);
155
+ this.settledAffinity = this.view.affinity;
156
+ const moved = tr.getMeta(MOVED);
157
+ if (moved?.preedit) {
158
+ this.preeditFrom = moved.preedit.from;
159
+ this.preeditReplaceTo = moved.preedit.to;
160
+ }
161
+ if (moved?.dragAnchor !== undefined)
162
+ this.dragAnchor = moved.dragAnchor;
163
+ const unit = this.dragAnchor;
164
+ if (unit && unit.unit !== "char" && !tr.getMeta(BY_UNIT) && !tr.getMeta(FROM_DOC) && !moved && (tr.docChanged || tr.selectionSet || tr.storedMarksSet))
165
+ this.dragAnchor = null;
166
+ if (this.ended)
167
+ return;
168
+ if (!tr.docChanged && (tr.selectionSet || tr.getMeta(CARET_AFFINITY) !== undefined))
169
+ this.doc.endTyping();
170
+ const also = tr.getMeta(ALSO);
171
+ if ((tr.docChanged || also) && !tr.getMeta(FROM_DOC)) {
172
+ const delta = tr.docChanged ? pmDiffToDelta(before.doc, next.doc) : [];
173
+ if (delta.length || also) {
174
+ const label = tr.getMeta(LABEL) ?? "Typing";
175
+ if (label !== "Typing")
176
+ this.doc.endTyping();
177
+ try {
178
+ this.write(label, delta, also, snapshot);
179
+ }
180
+ finally {
181
+ if (label !== "Typing")
182
+ this.doc.endTyping();
183
+ }
184
+ }
185
+ }
186
+ this.afterChange();
187
+ }
188
+ write(label, delta, also, snapshot) {
189
+ const base = this.doc.get(this.objectId);
190
+ const preedit = this.preeditText;
191
+ const previewing = this.previewing;
192
+ let live;
193
+ try {
194
+ this.preeditText = null;
195
+ this.previewing = null;
196
+ live = this.liveObject();
197
+ }
198
+ finally {
199
+ this.preeditText = preedit;
200
+ this.previewing = previewing;
201
+ }
202
+ const fitted = this.liveFitted ?? live.h;
203
+ const h = delta.length && base && base.kind === "text" && fitted !== base.h ? fitted : null;
204
+ this.writing = !also;
205
+ try {
206
+ this.doc.transact(label, (tx) => {
207
+ if (delta.length)
208
+ tx.editText(this.objectId, delta);
209
+ if (h !== null)
210
+ tx.set(this.objectId, "h", h);
211
+ also?.(tx);
212
+ });
213
+ if (!also) {
214
+ const written = this.doc.get(this.objectId);
215
+ this.matchedText = written?.text;
216
+ if (this.live && this.liveDoc === this.view.state.doc && this.livePreedit === null)
217
+ this.liveBaseTextVersion = written?.textVersion ?? 0;
218
+ }
219
+ }
220
+ catch (err) {
221
+ const held = this.doc.get(this.objectId);
222
+ this.rebuildFromDoc(held, undefined, undefined, contentToPm(held?.text ?? emptyTextContent(), snapshot.state.doc), snapshot);
223
+ throw err;
224
+ }
225
+ finally {
226
+ this.writing = false;
227
+ }
228
+ }
229
+ afterChange() {
230
+ if (this.ended)
231
+ return;
232
+ this.syncSelection();
233
+ this.lastActivity = this.now();
234
+ this.onChange();
235
+ this.mirrorHooks?.changed();
236
+ }
237
+ syncMirror(commit = false) {
238
+ if (!this.ended)
239
+ this.mirrorHooks?.sync(commit);
240
+ }
241
+ syncSelection() {
242
+ const { doc, selection } = this.view.state;
243
+ this.selection.setTextRange({ objectId: this.objectId, from: pmPosToOffset(doc, selection.from), to: pmPosToOffset(doc, selection.to) });
244
+ this.onPresenceCaret?.({ objectId: this.objectId, anchor: pmPosToOffset(doc, selection.anchor), head: pmPosToOffset(doc, selection.head) });
245
+ }
246
+ onDocChange(cs, meta) {
247
+ if (this.ended)
248
+ return;
249
+ if (this.fresh && (meta.origin !== "remote" || cs.updated.some((o) => o.id === this.objectId) || cs.removed.includes(this.objectId)))
250
+ this.fresh = false;
251
+ if (cs.removed.includes(this.objectId)) {
252
+ this.end();
253
+ return;
254
+ }
255
+ if (!cs.updated.some((o) => o.id === this.objectId))
256
+ return;
257
+ if (this.writing)
258
+ return;
259
+ if (this.deferRebuild) {
260
+ const d = meta.textDeltas?.get(this.objectId);
261
+ if (d && d.length) {
262
+ const acc = this.deferredDeltas ?? (this.deferredDeltas = []);
263
+ acc.push(...d);
264
+ }
265
+ return;
266
+ }
267
+ const base = this.doc.get(this.objectId);
268
+ if (!base) {
269
+ this.end();
270
+ return;
271
+ }
272
+ this.lastBase = base;
273
+ const next = this.docView(base);
274
+ if (next === this.view.state.doc) {
275
+ this.matchedText = base.text;
276
+ this.onChange();
277
+ return;
278
+ }
279
+ this.syncMirror();
280
+ if (this.ended)
281
+ return;
282
+ this.rebuildFromDoc(base, meta.origin, meta.textDeltas?.get(this.objectId), next);
283
+ }
284
+ docView(base) {
285
+ const doc = this.view.state.doc;
286
+ if (base && base.text === this.matchedText)
287
+ return doc;
288
+ return contentToPm(base?.text ?? emptyTextContent(), doc);
289
+ }
290
+ rebuildFromDoc(base = this.doc.get(this.objectId), origin = "remote", deltas, next, from) {
291
+ const state = from?.state ?? this.view.state;
292
+ const oldDoc = state.doc;
293
+ const newDoc = next ?? this.docView(base);
294
+ const range = changedParagraphs(oldDoc, newDoc);
295
+ const oldStarts = paragraphStarts(oldDoc);
296
+ const mapOff = offsetMap(oldDoc, newDoc, range, origin === "undo" || origin === "redo", deltas);
297
+ const map = (pmPos) => offsetToPmPos(newDoc, mapOff(pmPosToOffset(oldDoc, pmPos)));
298
+ const anchor = map(state.selection.anchor);
299
+ const head = map(state.selection.head);
300
+ if (this.preeditText !== null) {
301
+ this.preeditFrom = mapOff(from ? from.preeditFrom : this.preeditFrom);
302
+ this.preeditReplaceTo = Math.max(this.preeditFrom, mapOff(from ? from.preeditReplaceTo : this.preeditReplaceTo));
303
+ }
304
+ const dragAnchor = from ? from.dragAnchor : this.dragAnchor;
305
+ this.dragAnchor = dragAnchor === null ? null : { ...dragAnchor, from: map(dragAnchor.from), to: map(dragAnchor.to) };
306
+ const stored = state.storedMarks;
307
+ const tr = this.view.state.tr;
308
+ if (tr.doc !== oldDoc)
309
+ tr.replaceWith(0, tr.doc.content.size, oldDoc.content);
310
+ if (range) {
311
+ const changed = [];
312
+ for (let i = range.start; i < range.endAfter; i++)
313
+ changed.push(newDoc.child(i));
314
+ tr.replaceWith(oldStarts[range.start] + range.start, oldStarts[range.endBefore] + range.endBefore, changed);
315
+ }
316
+ tr.setSelection(TextSelection.create(tr.doc, anchor, head)).setMeta(FROM_DOC, true);
317
+ tr.setMeta(CARET_AFFINITY, from ? from.affinity : this.view.affinity);
318
+ if (stored)
319
+ tr.setStoredMarks(stored);
320
+ this.view.dispatch(tr);
321
+ this.matchedText = base?.text;
322
+ }
323
+ run(cmd) {
324
+ return cmd(this.view.state, this.view.dispatch, this.view);
325
+ }
326
+ select(anchor, head, affinity = "downstream", byUnit = false) {
327
+ const state = this.view.state;
328
+ const max = state.doc.content.size - 1;
329
+ const snap = (pos, up) => {
330
+ const clamped = Math.max(1, Math.min(max, pos));
331
+ const $pos = state.doc.resolve(clamped);
332
+ const offset = $pos.parentOffset;
333
+ const text = $pos.parent.textContent;
334
+ return clamped + (up ? snapUp(text, offset) : snapDown(text, offset)) - offset;
335
+ };
336
+ const a = snap(anchor, anchor > head);
337
+ const h = snap(head, head > anchor);
338
+ const tr = state.tr.setSelection(TextSelection.create(state.doc, a, h)).setMeta(CARET_AFFINITY, affinity);
339
+ if (byUnit)
340
+ tr.setMeta(BY_UNIT, true);
341
+ this.view.dispatch(tr);
342
+ }
343
+ liveObject() {
344
+ const base = (this.ended ? undefined : this.doc.get(this.objectId)) ?? this.lastBase;
345
+ this.lastBase = base;
346
+ const pmDoc = this.shown().doc;
347
+ const baseTextVersion = base.textVersion ?? 0;
348
+ if (this.live && this.liveBase === base && this.liveBaseVersion === base.version && this.liveDoc === pmDoc && this.livePreedit === this.preeditText)
349
+ return this.live;
350
+ const textChanged = !this.live || this.liveDoc !== pmDoc || this.livePreedit !== this.preeditText || this.liveBaseTextVersion !== baseTextVersion;
351
+ if (textChanged)
352
+ this.localVersion++;
353
+ const content = textChanged ? (this.preeditText !== null ? withPreedit(pmDoc, this.preeditFrom, this.preeditReplaceTo, this.preeditText) : pmToContent(pmDoc)) : this.liveContent;
354
+ const lastKey = this.live?.textVersion ?? -1;
355
+ const { style, text } = uncased(base.style, content, textChanged ? null : this.live.text);
356
+ const live = { ...base, style, text, textVersion: textChanged ? Math.max(lastKey + 1, baseTextVersion + this.localVersion) : lastKey };
357
+ if (base.kind === "text" && !this.ended) {
358
+ const fitted = this.fittedHeight(live, content, base.style);
359
+ this.liveFitted = fitted;
360
+ live.h = isCased(base.style, content) ? Math.max(fitted, this.boxFor(live, this.texts.get(live)?.height ?? 0)) : fitted;
361
+ }
362
+ this.liveContent = content;
363
+ this.live = live;
364
+ this.liveBase = base;
365
+ this.liveBaseVersion = base.version;
366
+ this.liveBaseTextVersion = baseTextVersion;
367
+ this.liveDoc = pmDoc;
368
+ this.livePreedit = this.preeditText;
369
+ return live;
370
+ }
371
+ drawnAs(drawn) {
372
+ this.drawn = drawn;
373
+ }
374
+ drawnObject() {
375
+ const live = this.liveObject();
376
+ return this.drawn ? this.drawn(live) : live;
377
+ }
378
+ shown() {
379
+ const state = this.view.state;
380
+ if (!this.previewing)
381
+ return state;
382
+ const defaults = Object.keys(this.previewing).map((name) => this.objectDefault(name));
383
+ const memo = this.previewed;
384
+ if (memo?.from !== state || memo.defaults.some((v, i) => !Object.is(v, defaults[i]))) {
385
+ const tr = this.formatting(state, this.previewing);
386
+ this.previewed = { from: state, defaults, state: tr.docChanged || tr.storedMarksSet ? state.apply(tr) : state };
387
+ }
388
+ return this.previewed.state;
389
+ }
390
+ fittedHeight(live, content, style) {
391
+ if (isCased(style, content))
392
+ return this.boxFor(live, this.texts.measureHeight({ ...live, style, text: content }));
393
+ if (this.texts.get(live)?.pending)
394
+ this.texts.settle(live.id);
395
+ return this.boxFor(live, this.texts.get(live)?.height ?? 0);
396
+ }
397
+ boxFor(live, laid) {
398
+ const oneLine = (live.style.fontSize ?? 14) * (live.style.lineHeight ?? 1.4);
399
+ return Math.max(live.h, Math.ceil(Math.max(oneLine, laid) + (live.style.paddingTop ?? 8) + (live.style.paddingBottom ?? 8)));
400
+ }
401
+ preedit() {
402
+ return this.preeditText !== null ? { from: this.preeditFrom, to: this.preeditFrom + this.preeditText.length } : null;
403
+ }
404
+ reveal(offset) {
405
+ const handle = this.ended ? null : this.view.provider.layout();
406
+ if (!handle?.pending)
407
+ return;
408
+ const lines = this.renderer.lineMetrics(handle);
409
+ let lo = 0;
410
+ let hi = lines.length - 1;
411
+ while (lo < hi) {
412
+ const mid = (lo + hi + 1) >> 1;
413
+ if (lines[mid].startIndex <= offset)
414
+ lo = mid;
415
+ else
416
+ hi = mid - 1;
417
+ }
418
+ const line = lines[lo];
419
+ if (line && line.startIndex <= offset && offset <= line.endIndex)
420
+ return;
421
+ this.texts.settle(this.objectId);
422
+ }
423
+ preeditRects() {
424
+ const range = this.preedit();
425
+ if (!range || range.to <= range.from)
426
+ return [];
427
+ this.reveal(range.to);
428
+ const handle = this.view.provider.layout();
429
+ if (!handle)
430
+ return [];
431
+ const o = this.view.provider.origin();
432
+ return this.renderer.rectsForRange(handle, range.from, range.to).map((r) => ({ x: o.x + r.x, y: o.y + r.y, w: r.w, h: r.h }));
433
+ }
434
+ caretRect() {
435
+ if (this.preeditText !== null)
436
+ return this.preeditCaret();
437
+ const sel = this.view.state.selection;
438
+ if (!sel.empty)
439
+ return null;
440
+ this.reveal(pmPosToOffset(this.view.state.doc, sel.head));
441
+ return this.view.coordsAtPos(sel.head);
442
+ }
443
+ preeditCaret() {
444
+ const range = this.preedit();
445
+ this.reveal(range.to);
446
+ const handle = this.view.provider.layout();
447
+ if (handle && range.to > range.from) {
448
+ const preedit = this.preeditText;
449
+ const start = range.from + prevGraphemeStart(preedit, preedit.length);
450
+ const edge = graphemeCaretEdge(this.renderer, handle, start, range.to, true);
451
+ if (edge) {
452
+ const o = this.view.provider.origin();
453
+ return { x: o.x + edge.x, y: o.y + edge.y, w: 0, h: edge.h };
454
+ }
455
+ const rects = this.renderer.rectsForRange(handle, range.from, range.to);
456
+ const last = rects[rects.length - 1];
457
+ if (last) {
458
+ const o = this.view.provider.origin();
459
+ return { x: o.x + last.x + last.w, y: o.y + last.y, w: 0, h: last.h };
460
+ }
461
+ }
462
+ return this.view.coordsAtPos(this.view.state.selection.head);
463
+ }
464
+ selectionRects() {
465
+ const sel = this.view.state.selection;
466
+ if (sel.empty)
467
+ return [];
468
+ this.reveal(pmPosToOffset(this.view.state.doc, sel.head));
469
+ return selectionRects(this.view, sel.from, sel.to);
470
+ }
471
+ caretVisible(now) {
472
+ return Math.floor(Math.max(0, now - this.lastActivity) / BLINK_MS) % 2 === 0;
473
+ }
474
+ insertText(text) {
475
+ const state = this.view.state;
476
+ const parts = text.replace(/\r\n?/g, "\n").split("\n");
477
+ const { from, to, empty, $from } = state.selection;
478
+ if (parts.length === 1) {
479
+ const part = parts[0];
480
+ if (!part)
481
+ return;
482
+ const tr = state.tr;
483
+ tr.insertText(part, from, to);
484
+ if (!tr.docChanged)
485
+ return;
486
+ tr.setMeta(LABEL, "Typing").setMeta(CARET_AFFINITY, "upstream");
487
+ this.view.dispatch(tr);
488
+ return;
489
+ }
490
+ const marks = state.storedMarks ?? $from.marks();
491
+ const firstAttrs = $from.parent.attrs;
492
+ const tr = state.tr;
493
+ if (!empty)
494
+ tr.deleteSelection();
495
+ parts.forEach((part, i) => {
496
+ if (i > 0) {
497
+ const $pos = tr.doc.resolve(tr.selection.from);
498
+ tr.split($pos.pos, 1, [{ type: paragraphType, attrs: firstAttrs }]);
499
+ }
500
+ if (part) {
501
+ tr.setStoredMarks(marks);
502
+ tr.insertText(part);
503
+ }
504
+ });
505
+ if (!tr.docChanged)
506
+ return;
507
+ tr.setMeta(LABEL, "Paste").setMeta(CARET_AFFINITY, "upstream");
508
+ this.view.dispatch(tr);
509
+ }
510
+ replaceFlat(from, to, text, anchor, head) {
511
+ if (this.ended)
512
+ return;
513
+ const state = this.view.state;
514
+ const doc = state.doc;
515
+ const a = offsetToPmPos(doc, Math.min(from, to));
516
+ const b = offsetToPmPos(doc, Math.max(from, to));
517
+ const parts = text.replace(/\r\n?/g, "\n").split("\n");
518
+ const tr = state.tr;
519
+ if (parts.length === 1) {
520
+ if (parts[0])
521
+ tr.insertText(parts[0], a, b);
522
+ else if (b > a)
523
+ tr.delete(a, b);
524
+ }
525
+ else {
526
+ const $a = doc.resolve(a);
527
+ const marks = state.storedMarks ?? (a === b ? $a.marks() : ($a.marksAcross(doc.resolve(b)) ?? $a.marks()));
528
+ const attrs = $a.parent.attrs;
529
+ if (b > a)
530
+ tr.delete(a, b);
531
+ tr.setSelection(TextSelection.create(tr.doc, a));
532
+ parts.forEach((part, i) => {
533
+ if (i > 0)
534
+ tr.split(tr.selection.from, 1, [{ type: paragraphType, attrs }]);
535
+ if (part)
536
+ tr.setStoredMarks(marks).insertText(part);
537
+ });
538
+ }
539
+ if (!tr.docChanged) {
540
+ const sel = this.mirror.selection();
541
+ if (sel.anchor !== anchor || sel.head !== head)
542
+ this.selectRange(anchor, head);
543
+ return;
544
+ }
545
+ const max = tr.doc.content.size - 1;
546
+ const snap = (offset) => {
547
+ const pos = Math.max(1, Math.min(max, offsetToPmPos(tr.doc, offset)));
548
+ const $pos = tr.doc.resolve(pos);
549
+ return pos + snapDown($pos.parent.textContent, $pos.parentOffset) - $pos.parentOffset;
550
+ };
551
+ tr.setSelection(TextSelection.create(tr.doc, snap(anchor), snap(head)));
552
+ this.view.dispatch(tr.setMeta(LABEL, "Typing").setMeta(CARET_AFFINITY, "upstream"));
553
+ }
554
+ deleteBackward(unit) {
555
+ this.run(unit === "char" ? backspace : unit === "word" ? wordBackspace : lineBackspace);
556
+ }
557
+ deleteForward(unit) {
558
+ this.run(unit === "char" ? del : unit === "word" ? (this.windows ? windowsWordDelete : wordDelete) : lineDelete);
559
+ }
560
+ splitBlock() {
561
+ this.run(enter);
562
+ }
563
+ insertLineBreak() {
564
+ this.run(insertHardBreak);
565
+ }
566
+ keydown(e) {
567
+ if (this.ended || this.preeditText !== null)
568
+ return false;
569
+ if (e.key === "Escape") {
570
+ this.end();
571
+ return true;
572
+ }
573
+ if ((e.ctrlKey || e.metaKey) && !e.altKey) {
574
+ const k = e.key.toLowerCase();
575
+ const fromCode = keyCodeFromCode(e.code, e.key);
576
+ const isZ = k === "z" || fromCode === 90;
577
+ const isY = k === "y" || fromCode === 89;
578
+ if (isZ && !e.shiftKey) {
579
+ this.undo();
580
+ return true;
581
+ }
582
+ if ((isZ && e.shiftKey) || isY) {
583
+ this.redo();
584
+ return true;
585
+ }
586
+ }
587
+ return handleKey(this.view, e, this.keymap);
588
+ }
589
+ compositionStart() {
590
+ if (this.ended || this.preeditText !== null)
591
+ return;
592
+ const { doc, selection } = this.view.state;
593
+ this.preeditFrom = pmPosToOffset(doc, selection.from);
594
+ this.preeditReplaceTo = pmPosToOffset(doc, selection.to);
595
+ this.preeditText = "";
596
+ this.view.composing = true;
597
+ if (!selection.empty)
598
+ this.select(offsetToPmPos(doc, this.preeditFrom), offsetToPmPos(doc, this.preeditFrom));
599
+ else
600
+ this.afterChange();
601
+ }
602
+ compositionUpdate(data) {
603
+ if (this.ended)
604
+ return;
605
+ if (this.preeditText === null)
606
+ this.compositionStart();
607
+ this.preeditText = data;
608
+ this.afterChange();
609
+ }
610
+ compositionEnd(data) {
611
+ if (this.ended)
612
+ return;
613
+ const wasComposing = this.preeditText !== null;
614
+ const from = this.preeditFrom;
615
+ const to = this.preeditReplaceTo;
616
+ this.preeditText = null;
617
+ this.view.composing = false;
618
+ if (!wasComposing)
619
+ return;
620
+ if (data) {
621
+ const state = this.view.state;
622
+ const start = offsetToPmPos(state.doc, from);
623
+ const end = offsetToPmPos(state.doc, to);
624
+ const tr = state.tr.setSelection(TextSelection.create(state.doc, start, end));
625
+ const parts = data.replace(/\r\n?/g, "\n").split("\n");
626
+ if (parts.length === 1) {
627
+ if (state.storedMarks)
628
+ tr.setStoredMarks(state.storedMarks);
629
+ tr.insertText(parts[0], start, end);
630
+ }
631
+ else {
632
+ const $from = state.doc.resolve(start);
633
+ const marks = state.storedMarks ?? $from.marks();
634
+ if (start !== end)
635
+ tr.deleteSelection();
636
+ parts.forEach((part, i) => {
637
+ if (i > 0)
638
+ tr.split(tr.selection.from, 1, [{ type: paragraphType, attrs: $from.parent.attrs }]);
639
+ if (part)
640
+ tr.setStoredMarks(marks).insertText(part);
641
+ });
642
+ }
643
+ if (tr.docChanged)
644
+ this.view.dispatch(tr.setMeta(LABEL, "Typing").setMeta(CARET_AFFINITY, "upstream"));
645
+ else
646
+ this.afterChange();
647
+ }
648
+ else {
649
+ this.selectRange(from, to);
650
+ }
651
+ }
652
+ compose(from, to, text) {
653
+ if (this.ended || this.preeditText === null)
654
+ return;
655
+ const doc = this.view.state.doc;
656
+ const last = paragraphStarts(doc)[doc.childCount] - 1;
657
+ const snap = (offset) => {
658
+ const clamped = Math.max(0, Math.min(last, offset));
659
+ const $pos = doc.resolve(offsetToPmPos(doc, clamped));
660
+ return clamped - $pos.parentOffset + snapDown($pos.parent.textContent, $pos.parentOffset);
661
+ };
662
+ const a = snap(Math.min(from, to));
663
+ const b = Math.max(a, snap(Math.max(from, to)));
664
+ if (a === this.preeditFrom && b === this.preeditReplaceTo && text === this.preeditText)
665
+ return;
666
+ this.preeditFrom = a;
667
+ this.preeditReplaceTo = b;
668
+ this.preeditText = text;
669
+ this.afterChange();
670
+ }
671
+ copyText() {
672
+ const { from, to, empty } = this.view.state.selection;
673
+ return empty ? "" : this.view.state.doc.textBetween(from, to, "\n", "\n").replace(/\u2028/g, "\n");
674
+ }
675
+ copyClipboard() {
676
+ const selection = this.view.state.selection;
677
+ return selection.empty ? null : serializeClipboard(selection.content(), selection.$from.parentOffset === 0);
678
+ }
679
+ pasteClipboard(content) {
680
+ this.syncMirror();
681
+ const tr = clipboardTransaction(this.view.state, content);
682
+ if (tr)
683
+ this.view.dispatch(tr.setMeta(LABEL, "Paste").setMeta(CARET_AFFINITY, "upstream"));
684
+ return true;
685
+ }
686
+ cut() {
687
+ const text = this.copyText();
688
+ if (text)
689
+ this.view.dispatch(this.view.state.tr.deleteSelection().setMeta(LABEL, "Cut"));
690
+ return text;
691
+ }
692
+ undo() {
693
+ this.walkDoc("undo");
694
+ }
695
+ redo() {
696
+ this.walkDoc("redo");
697
+ }
698
+ walkDoc(dir) {
699
+ if (this.ended)
700
+ return;
701
+ this.syncMirror();
702
+ if (this.ended)
703
+ return;
704
+ this.deferRebuild = true;
705
+ this.deferredDeltas = [];
706
+ try {
707
+ if (dir === "undo")
708
+ this.doc.undo();
709
+ else
710
+ this.doc.redo();
711
+ }
712
+ finally {
713
+ this.deferRebuild = false;
714
+ }
715
+ if (this.ended)
716
+ return;
717
+ const base = this.doc.get(this.objectId);
718
+ if (!base) {
719
+ this.end();
720
+ return;
721
+ }
722
+ this.lastBase = base;
723
+ const deltas = this.deferredDeltas;
724
+ this.deferredDeltas = null;
725
+ const next = this.docView(base);
726
+ if (next === this.view.state.doc) {
727
+ this.matchedText = base.text;
728
+ this.onChange();
729
+ }
730
+ else
731
+ this.rebuildFromDoc(base, dir, deltas && deltas.length > 0 ? deltas : undefined, next);
732
+ }
733
+ blur() {
734
+ this.end();
735
+ }
736
+ caretClientRect() {
737
+ if (this.ended)
738
+ return null;
739
+ if (this.preeditText === null)
740
+ this.reveal(pmPosToOffset(this.view.state.doc, this.view.state.selection.head));
741
+ const r = this.preeditText !== null ? this.preeditCaret() : this.view.coordsAtPos(this.view.state.selection.head);
742
+ const top = this.toClient(this.rotatePoint({ x: r.x, y: r.y }));
743
+ const bottom = this.toClient(this.rotatePoint({ x: r.x, y: r.y + r.h }));
744
+ return { left: top.x, top: top.y, height: Math.max(1, Math.hypot(bottom.x - top.x, bottom.y - top.y)) };
745
+ }
746
+ objFrame() {
747
+ const o = this.drawnObject();
748
+ return { cx: o.x + o.w / 2, cy: o.y + o.h / 2, rot: o.rot };
749
+ }
750
+ unrotate(p) {
751
+ const { cx, cy, rot } = this.objFrame();
752
+ if (!rot)
753
+ return p;
754
+ const c = Math.cos(-rot);
755
+ const s = Math.sin(-rot);
756
+ const dx = p.x - cx;
757
+ const dy = p.y - cy;
758
+ return { x: cx + dx * c - dy * s, y: cy + dx * s + dy * c };
759
+ }
760
+ rotatePoint(p) {
761
+ const { cx, cy, rot } = this.objFrame();
762
+ if (!rot)
763
+ return p;
764
+ const c = Math.cos(rot);
765
+ const s = Math.sin(rot);
766
+ const dx = p.x - cx;
767
+ const dy = p.y - cy;
768
+ return { x: cx + dx * c - dy * s, y: cy + dx * s + dy * c };
769
+ }
770
+ readMark(name) {
771
+ const state = this.shown();
772
+ const over = (values) => (values.length > 1 ? { value: values[0], mixed: true, values } : { value: values[0], mixed: false });
773
+ const distinct = [];
774
+ const seen = (v) => {
775
+ if (!distinct.includes(v))
776
+ distinct.push(v);
777
+ };
778
+ if (isParagraphKey(name)) {
779
+ const doc = state.doc;
780
+ const first = paragraphIndexAtPos(doc, state.selection.from);
781
+ const last = paragraphIndexAtPos(doc, state.selection.to);
782
+ for (let i = first; i <= last; i++)
783
+ seen(paragraphValue(name, doc.child(i).attrs));
784
+ return over(distinct);
785
+ }
786
+ if (!isInlineKey(name))
787
+ return { value: undefined, mixed: false };
788
+ const type = markType(name);
789
+ const { from, to, empty, $from } = state.selection;
790
+ const def = this.objectDefault(name);
791
+ const eff = (m) => markValue(name, m) ?? def;
792
+ if (empty)
793
+ return { value: eff(type.isInSet(state.storedMarks ?? $from.marks())), mixed: false };
794
+ state.doc.nodesBetween(from, to, (node) => {
795
+ if (node.isInline)
796
+ seen(eff(type.isInSet(node.marks)));
797
+ });
798
+ if (!distinct.length)
799
+ return { value: eff(type.isInSet($from.marks())), mixed: false };
800
+ return over(distinct);
801
+ }
802
+ objectDefault(name) {
803
+ const s = this.lastBase.style;
804
+ switch (name) {
805
+ case "weight":
806
+ return s.fontWeight ?? 400;
807
+ case "italic":
808
+ return s.italic ?? false;
809
+ case "underline":
810
+ return s.underline ?? false;
811
+ case "strike":
812
+ return s.strike ?? false;
813
+ case "size":
814
+ return s.fontSize ?? 14;
815
+ case "family":
816
+ return s.fontFamily ?? "Inter";
817
+ case "color":
818
+ return s.color ?? "#1a1a1a";
819
+ case "letterSpacing":
820
+ return s.letterSpacing ?? 0;
821
+ case "textCase":
822
+ return s.textCase ?? "none";
823
+ default:
824
+ return undefined;
825
+ }
826
+ }
827
+ writeMark(name, value) {
828
+ if (this.ended)
829
+ return;
830
+ this.syncMirror();
831
+ if (this.ended)
832
+ return;
833
+ this.markCommand(name, value)?.(this.view.state, (tr) => this.view.dispatch(tr.setMeta(LABEL, "Format text")), this.view);
834
+ }
835
+ markCommand(name, value) {
836
+ if (isParagraphKey(name)) {
837
+ const v = paragraphAttrValue(name, value);
838
+ return v === INVALID ? null : setParagraphAttr(name, v);
839
+ }
840
+ if (!isInlineKey(name))
841
+ return null;
842
+ const type = markType(name);
843
+ const v = inlineMarkValue(name, value);
844
+ if (v === INVALID)
845
+ return null;
846
+ const mark = v === undefined || v === this.objectDefault(name) ? null : name === "link" ? type.create({ href: v }) : type.create({ value: v });
847
+ return (state, dispatch) => applyMark(state, dispatch, type, mark);
848
+ }
849
+ formatting(state, marks) {
850
+ const tr = state.tr;
851
+ let cur = state;
852
+ const entries = Object.entries(marks).sort(([a], [b]) => Number(isInlineKey(a)) - Number(isInlineKey(b)));
853
+ for (const [name, value] of entries) {
854
+ this.markCommand(name, value)?.(cur, (t) => {
855
+ for (const step of t.steps)
856
+ tr.step(step);
857
+ if (t.storedMarksSet)
858
+ tr.setStoredMarks(t.storedMarks);
859
+ cur = cur.apply(t);
860
+ }, this.view);
861
+ }
862
+ return tr;
863
+ }
864
+ previewMarks(marks) {
865
+ if (marks)
866
+ this.syncMirror();
867
+ const next = this.ended || !marks || Object.keys(marks).length === 0 ? null : { ...marks };
868
+ const prev = this.previewing;
869
+ if (next === prev || (next && prev && Object.keys(next).length === Object.keys(prev).length && Object.keys(next).every((k) => Object.is(next[k], prev[k]))))
870
+ return;
871
+ this.previewing = next;
872
+ this.previewed = null;
873
+ if (!this.ended)
874
+ this.onChange();
875
+ }
876
+ commitMarks(marks, label, also, text) {
877
+ this.syncMirror();
878
+ this.previewing = null;
879
+ this.previewed = null;
880
+ if (this.ended) {
881
+ if (also || text) {
882
+ this.doc.transact(label, (tx) => {
883
+ if (text)
884
+ tx.set(this.objectId, "text", text);
885
+ also?.(tx);
886
+ });
887
+ }
888
+ return;
889
+ }
890
+ const tr = text ? this.replacing(text, marks) : this.formatting(this.view.state, marks);
891
+ if (!tr.docChanged && !tr.storedMarksSet && !also) {
892
+ this.onChange();
893
+ return;
894
+ }
895
+ this.view.dispatch(tr.setMeta(LABEL, label).setMeta(ALSO, also));
896
+ }
897
+ replacing(text, marks) {
898
+ const state = this.view.state;
899
+ const doc = contentToPm(text, state.doc);
900
+ const map = offsetMap(state.doc, doc, changedParagraphs(state.doc, doc), false);
901
+ const pos = (pmPos) => offsetToPmPos(doc, map(pmPosToOffset(state.doc, pmPos)));
902
+ const tr = state.tr.replaceWith(0, state.doc.content.size, doc.content);
903
+ tr.setSelection(TextSelection.create(tr.doc, pos(state.selection.anchor), pos(state.selection.head)));
904
+ const moved = {};
905
+ if (this.preeditText !== null) {
906
+ const from = map(this.preeditFrom);
907
+ moved.preedit = { from, to: Math.max(from, map(this.preeditReplaceTo)) };
908
+ }
909
+ const anchor = this.dragAnchor;
910
+ if (anchor !== null)
911
+ moved.dragAnchor = { ...anchor, from: pos(anchor.from), to: pos(anchor.to) };
912
+ tr.setMeta(MOVED, moved);
913
+ if (state.storedMarks)
914
+ tr.setStoredMarks(state.storedMarks);
915
+ const format = this.formatting(state.apply(tr), marks);
916
+ for (const step of format.steps)
917
+ tr.step(step);
918
+ tr.setStoredMarks(format.storedMarks);
919
+ return tr;
920
+ }
921
+ pointer(worldRaw, phase, shift = false, clicks = 1) {
922
+ if (this.ended)
923
+ return false;
924
+ if (phase === "down")
925
+ this.syncMirror(true);
926
+ if (this.ended)
927
+ return false;
928
+ if (this.preeditText !== null)
929
+ return true;
930
+ if (phase === "up") {
931
+ const dragging = this.pressed;
932
+ this.pressed = false;
933
+ if (this.dragAnchor?.unit === "char")
934
+ this.dragAnchor = null;
935
+ return dragging;
936
+ }
937
+ const world = this.unrotate(worldRaw);
938
+ const handle = this.view.provider.layout();
939
+ if (handle?.pending && world.y > this.view.provider.origin().y + handle.height)
940
+ this.texts.settle(this.objectId);
941
+ if (phase === "move") {
942
+ const anchor = this.dragAnchor;
943
+ if (!this.pressed || anchor === null)
944
+ return false;
945
+ const hit = this.view.posAtCoords({ left: world.x, top: world.y });
946
+ if (anchor.unit !== "char") {
947
+ this.extend(anchor, hit ?? this.nearestHit(world));
948
+ return true;
949
+ }
950
+ const pos = hit?.pos ?? this.nearestPos(world);
951
+ if (pos !== this.view.state.selection.head || (hit && hit.affinity !== this.view.affinity))
952
+ this.select(anchor.from, pos, hit?.affinity);
953
+ return true;
954
+ }
955
+ const hit = this.view.posAtCoords({ left: world.x, top: world.y });
956
+ const o = this.drawnObject();
957
+ const inBox = world.x >= o.x && world.x <= o.x + o.w && world.y >= o.y && world.y <= o.y + o.h;
958
+ if (!hit && !inBox)
959
+ return false;
960
+ const pos = hit?.pos ?? this.nearestPos(world);
961
+ const prior = this.dragAnchor;
962
+ this.pressed = true;
963
+ if (clicks >= 2) {
964
+ const unit = clicks >= 3 ? "paragraph" : "word";
965
+ const { from, to } = unit === "word" ? this.wordRange(pos, hit?.affinity) : this.paragraphRange(pos);
966
+ this.dragAnchor = { unit, from, to };
967
+ this.select(from, to, "downstream", true);
968
+ }
969
+ else if (shift && prior && prior.unit !== "char") {
970
+ this.extend(prior, hit ?? this.nearestHit(world));
971
+ }
972
+ else {
973
+ const anchor = shift ? this.view.state.selection.anchor : pos;
974
+ this.select(anchor, pos, hit?.affinity);
975
+ this.dragAnchor = { unit: "char", from: anchor, to: anchor };
976
+ }
977
+ return true;
978
+ }
979
+ extend(anchor, hit) {
980
+ const unit = anchor.unit === "word" ? this.wordRange(hit.pos, hit.affinity) : this.paragraphRange(hit.pos);
981
+ const from = Math.min(anchor.from, unit.from);
982
+ const to = Math.max(anchor.to, unit.to);
983
+ const [a, h] = unit.from < anchor.from ? [to, from] : [from, to];
984
+ const { selection } = this.view.state;
985
+ if (selection.anchor === a && selection.head === h)
986
+ return;
987
+ this.select(a, h, "downstream", true);
988
+ }
989
+ nearestPos(world) {
990
+ return this.nearestHit(world).pos;
991
+ }
992
+ nearestHit(world) {
993
+ const handle = this.view.provider.layout();
994
+ const o = this.view.provider.origin();
995
+ if (handle) {
996
+ const x = Math.max(o.x, Math.min(o.x + handle.width, world.x));
997
+ const y = Math.max(o.y, Math.min(o.y + handle.height, world.y));
998
+ const hit = this.view.posAtCoords({ left: x, top: y });
999
+ if (hit)
1000
+ return hit;
1001
+ }
1002
+ return { pos: world.y < o.y ? 1 : this.view.state.doc.content.size - 1, affinity: "downstream" };
1003
+ }
1004
+ wordRange(pos, affinity = "downstream") {
1005
+ const $pos = this.view.state.doc.resolve(pos);
1006
+ const node = $pos.parent;
1007
+ if (this.words?.node !== node)
1008
+ this.words = { node, ranges: wordRanges(node.textContent) };
1009
+ const { start, end } = this.words.ranges($pos.parentOffset, affinity, this.windows);
1010
+ return { from: $pos.start() + start, to: $pos.start() + end };
1011
+ }
1012
+ paragraphRange(pos) {
1013
+ const $pos = this.view.state.doc.resolve(pos);
1014
+ return { from: $pos.start(), to: $pos.end() };
1015
+ }
1016
+ selectWordAt(pos, affinity = "downstream") {
1017
+ const { from, to } = this.wordRange(pos, affinity);
1018
+ this.select(from, to);
1019
+ }
1020
+ moveSelectionEnd(end, worldRaw) {
1021
+ if (this.ended)
1022
+ return;
1023
+ this.syncMirror(true);
1024
+ if (this.ended || this.preeditText !== null)
1025
+ return;
1026
+ const world = this.unrotate(worldRaw);
1027
+ const handle = this.view.provider.layout();
1028
+ if (handle?.pending && world.y > this.view.provider.origin().y + handle.height)
1029
+ this.texts.settle(this.objectId);
1030
+ const hit = this.view.posAtCoords({ left: world.x, top: world.y }) ?? this.nearestHit(world);
1031
+ const { anchor, head } = this.view.state.selection;
1032
+ const a = end === "head" ? anchor : hit.pos;
1033
+ const h = end === "anchor" ? head : hit.pos;
1034
+ const affinity = end === "anchor" ? this.view.affinity : hit.affinity;
1035
+ if (a !== anchor || h !== head || affinity !== this.view.affinity)
1036
+ this.select(a, h, affinity);
1037
+ }
1038
+ selectionEnds() {
1039
+ if (this.ended)
1040
+ return [];
1041
+ const caret = this.caretRect();
1042
+ if (caret)
1043
+ return [{ end: "caret", rect: caret }];
1044
+ const { doc, selection } = this.view.state;
1045
+ const at = (pos, affinity) => {
1046
+ this.reveal(pmPosToOffset(doc, pos));
1047
+ const o = this.view.provider.origin();
1048
+ const c = this.view.caretLocal(pos, affinity);
1049
+ return { x: o.x + c.x, y: o.y + c.y, w: 0, h: c.h };
1050
+ };
1051
+ const forward = selection.anchor < selection.head;
1052
+ return [
1053
+ { end: forward ? "anchor" : "head", rect: at(selection.from, "downstream") },
1054
+ { end: forward ? "head" : "anchor", rect: at(selection.to, "upstream") },
1055
+ ];
1056
+ }
1057
+ selectParagraphAt(pos) {
1058
+ const { from, to } = this.paragraphRange(pos);
1059
+ this.select(from, to);
1060
+ }
1061
+ selectRange(from, to = from) {
1062
+ const doc = this.view.state.doc;
1063
+ this.select(offsetToPmPos(doc, from), offsetToPmPos(doc, to));
1064
+ }
1065
+ selectAll() {
1066
+ const doc = this.view.state.doc;
1067
+ this.select(1, doc.content.size - 1);
1068
+ }
1069
+ focus() {
1070
+ this.view.focus();
1071
+ this.lastActivity = this.now();
1072
+ if (!this.ended)
1073
+ this.mirrorHooks?.focused();
1074
+ }
1075
+ end() {
1076
+ if (this.ended)
1077
+ return;
1078
+ this.doc.endTyping();
1079
+ this.ended = true;
1080
+ this.unsubscribeDoc();
1081
+ this.unsubscribeSelection();
1082
+ this.preeditText = null;
1083
+ this.previewing = null;
1084
+ this.previewed = null;
1085
+ this.view.composing = false;
1086
+ this.view.blur();
1087
+ this.dragAnchor = null;
1088
+ this.pressed = false;
1089
+ this.words = null;
1090
+ if (this.ownsTexts)
1091
+ this.texts.clear();
1092
+ else
1093
+ this.texts.invalidate(this.objectId);
1094
+ if (this.selection.textRange?.objectId === this.objectId)
1095
+ this.selection.setTextRange(null);
1096
+ this.onPresenceCaret?.(null);
1097
+ if (this.fresh && isEmptyTextContent(this.doc.get(this.objectId)?.text) && this.doc.canUndo())
1098
+ this.doc.undo();
1099
+ this.onEnd();
1100
+ }
1101
+ }
1102
+ function flatSlice(doc, from, to) {
1103
+ const starts = paragraphStarts(doc);
1104
+ const total = starts[doc.childCount];
1105
+ const a = Math.max(0, Math.min(total, from));
1106
+ const b = Math.max(a, Math.min(total, to));
1107
+ if (a === b)
1108
+ return "";
1109
+ let out = "";
1110
+ for (let i = paragraphIndexAtOffset(doc, a); i < doc.childCount && starts[i] < b; i++) {
1111
+ const paragraph = doc.child(i);
1112
+ const size = paragraph.content.size;
1113
+ const lo = Math.max(0, a - starts[i]);
1114
+ const hi = Math.min(size + 1, b - starts[i]);
1115
+ const end = Math.min(hi, size);
1116
+ if (end > lo)
1117
+ out += paragraph.textBetween(lo, end);
1118
+ if (hi > size)
1119
+ out += "\n";
1120
+ }
1121
+ return out;
1122
+ }
1123
+ export function mapOffsetThroughDelta(off, delta, bias) {
1124
+ let oldPos = 0;
1125
+ let newPos = 0;
1126
+ let i = 0;
1127
+ while (i < delta.length) {
1128
+ const op = delta[i];
1129
+ if ("retain" in op) {
1130
+ if (off < oldPos + op.retain)
1131
+ return newPos + (off - oldPos);
1132
+ oldPos += op.retain;
1133
+ newPos += op.retain;
1134
+ i++;
1135
+ continue;
1136
+ }
1137
+ let del = 0;
1138
+ let ins = 0;
1139
+ while (i < delta.length) {
1140
+ const o = delta[i];
1141
+ if ("retain" in o)
1142
+ break;
1143
+ if ("delete" in o)
1144
+ del += o.delete;
1145
+ else
1146
+ ins += o.insert.length;
1147
+ i++;
1148
+ }
1149
+ const groupOldEnd = oldPos + del;
1150
+ if (off === oldPos) {
1151
+ return bias === "after" ? newPos + ins : newPos;
1152
+ }
1153
+ if (off < groupOldEnd) {
1154
+ return bias === "after" ? newPos + ins : newPos;
1155
+ }
1156
+ oldPos = groupOldEnd;
1157
+ newPos += ins;
1158
+ }
1159
+ return newPos + (off - oldPos);
1160
+ }
1161
+ function offsetMap(oldDoc, newDoc, range, toWindowEnd, deltas) {
1162
+ const oldText = pmToText(oldDoc);
1163
+ const newText = pmToText(newDoc);
1164
+ const oldStarts = paragraphStarts(oldDoc);
1165
+ const clamp = (off) => snapDown(newText, Math.max(0, Math.min(newText.length - 1, off)));
1166
+ if (deltas && deltas.length) {
1167
+ const bias = toWindowEnd ? "after" : "before";
1168
+ const effective = [];
1169
+ let cur = oldText;
1170
+ for (const d of deltas) {
1171
+ let next;
1172
+ try {
1173
+ next = applyDeltaToString(cur, d);
1174
+ }
1175
+ catch {
1176
+ break;
1177
+ }
1178
+ if (!next.endsWith("\n"))
1179
+ next += "\n";
1180
+ if (next !== cur)
1181
+ effective.push(d);
1182
+ cur = next;
1183
+ }
1184
+ if (cur === newText)
1185
+ return (off) => clamp(effective.reduce((o, d) => mapOffsetThroughDelta(o, d, bias), off));
1186
+ }
1187
+ const max = Math.min(oldText.length, newText.length);
1188
+ let p = range ? oldStarts[range.start] : max;
1189
+ while (p < max && oldText.charCodeAt(p) === newText.charCodeAt(p))
1190
+ p++;
1191
+ p = snapDown(oldText, p);
1192
+ let s = range ? Math.min(max - p, oldText.length - oldStarts[range.endBefore]) : 0;
1193
+ while (s < max - p && oldText.charCodeAt(oldText.length - 1 - s) === newText.charCodeAt(newText.length - 1 - s))
1194
+ s++;
1195
+ const aEnd = oldText.length - s;
1196
+ const bEnd = newText.length - s;
1197
+ return (off) => {
1198
+ if (off < p)
1199
+ return clamp(off);
1200
+ if (off === p)
1201
+ return clamp(toWindowEnd ? bEnd : p);
1202
+ if (off >= aEnd)
1203
+ return clamp(off + (bEnd - aEnd));
1204
+ return clamp(toWindowEnd ? bEnd : p);
1205
+ };
1206
+ }
1207
+ function markValue(name, mark) {
1208
+ if (!mark)
1209
+ return undefined;
1210
+ return name === "link" ? mark.attrs.href : mark.attrs.value;
1211
+ }
1212
+ function paragraphValue(name, attrs) {
1213
+ const v = attrs[name];
1214
+ if (name === "list")
1215
+ return v ?? "none";
1216
+ if (name === "indent")
1217
+ return typeof v === "number" ? v : 0;
1218
+ if (name === "checked")
1219
+ return v === true;
1220
+ return v ?? undefined;
1221
+ }
1222
+ const INVALID = Symbol("invalid mark value");
1223
+ function isCased(style, content) {
1224
+ if (style.textCase && style.textCase !== "none")
1225
+ return true;
1226
+ return content.paragraphs.some((p) => p.runs.some((r) => r.textCase !== undefined && r.textCase !== "none"));
1227
+ }
1228
+ function uncased(style, content, previous) {
1229
+ let s = style;
1230
+ if (s.textCase !== undefined) {
1231
+ s = { ...s };
1232
+ delete s.textCase;
1233
+ }
1234
+ if (previous)
1235
+ return { style: s, text: previous };
1236
+ if (!content.paragraphs.some((p) => p.runs.some((r) => r.textCase !== undefined)))
1237
+ return { style: s, text: content };
1238
+ const text = {
1239
+ paragraphs: content.paragraphs.map((p) => {
1240
+ if (!p.runs.some((r) => r.textCase !== undefined))
1241
+ return p;
1242
+ return {
1243
+ ...p,
1244
+ runs: p.runs.map((r) => {
1245
+ if (r.textCase === undefined)
1246
+ return r;
1247
+ const run = { ...r };
1248
+ delete run.textCase;
1249
+ return run;
1250
+ }),
1251
+ };
1252
+ }),
1253
+ };
1254
+ return { style: s, text };
1255
+ }
1256
+ function inlineMarkValue(name, value) {
1257
+ if (isClear(value))
1258
+ return undefined;
1259
+ switch (name) {
1260
+ case "link":
1261
+ case "color":
1262
+ case "family":
1263
+ return typeof value === "string" && value.length > 0 ? value : INVALID;
1264
+ case "size":
1265
+ return Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : INVALID;
1266
+ case "weight":
1267
+ return Number.isFinite(Number(value)) && Number(value) >= 100 && Number(value) <= 900 ? Number(value) : INVALID;
1268
+ case "letterSpacing":
1269
+ return Number.isFinite(Number(value)) ? Number(value) : INVALID;
1270
+ case "textCase":
1271
+ return TEXT_CASES.has(value) ? value : INVALID;
1272
+ default:
1273
+ return typeof value === "boolean" ? value : INVALID;
1274
+ }
1275
+ }
1276
+ function paragraphAttrValue(name, value) {
1277
+ if (name === "indent") {
1278
+ if (isClear(value))
1279
+ return 0;
1280
+ const n = Number(value);
1281
+ return Number.isFinite(n) ? Math.max(0, Math.min(MAX_INDENT, Math.round(n))) : INVALID;
1282
+ }
1283
+ if (name === "checked")
1284
+ return value === true ? true : isClear(value) || value === false ? null : INVALID;
1285
+ if (isClear(value) || (name === "list" && value === "none"))
1286
+ return null;
1287
+ if (name === "list")
1288
+ return value === "bullet" || value === "number" || value === "task" ? value : INVALID;
1289
+ if (name === "lineHeight")
1290
+ return Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : INVALID;
1291
+ if (name === "start")
1292
+ return Number.isFinite(Number(value)) && Number(value) >= 0 ? Math.round(Number(value)) : INVALID;
1293
+ return value === "left" || value === "center" || value === "right" || value === "justify" ? value : INVALID;
1294
+ }
1295
+ function withPreedit(pmDoc, from, to, preedit) {
1296
+ const starts = paragraphStarts(pmDoc);
1297
+ const total = starts[pmDoc.childCount];
1298
+ const at = Math.max(0, Math.min(total - 1, from));
1299
+ const end = Math.max(at, Math.min(total - 1, to));
1300
+ const whole = pmToContent(pmDoc);
1301
+ if (!preedit && at === end)
1302
+ return whole;
1303
+ const first = paragraphIndexAtOffset(pmDoc, at);
1304
+ const last = paragraphIndexAtOffset(pmDoc, end);
1305
+ const flat = pmToFlat(pmDoc, first, last + 1);
1306
+ const a = at - starts[first];
1307
+ const e = end - starts[first];
1308
+ let spliced;
1309
+ if (!preedit)
1310
+ spliced = { text: flat.text.slice(0, a) + flat.text.slice(e), attrs: flat.attrs.slice(0, a).concat(flat.attrs.slice(e)) };
1311
+ else {
1312
+ const source = a > 0 && flat.text.charCodeAt(a - 1) !== 10 ? flat.attrs[a - 1] : e < flat.text.length && flat.text.charCodeAt(e) !== 10 ? flat.attrs[e] : EMPTY_ATTRS;
1313
+ const attrs = {};
1314
+ for (const k of INLINE_MARK_KEYS)
1315
+ if (!isClear(source[k]))
1316
+ attrs[k] = source[k];
1317
+ attrs.underline = true;
1318
+ const filled = new Array(preedit.length).fill(attrs);
1319
+ spliced = { text: flat.text.slice(0, a) + preedit + flat.text.slice(e), attrs: flat.attrs.slice(0, a).concat(filled, flat.attrs.slice(e)) };
1320
+ }
1321
+ if (first !== last) {
1322
+ const firstTerminator = starts[first + 1] - 1 - starts[first];
1323
+ const terminator = spliced.text.indexOf("\n", a + preedit.length);
1324
+ if (terminator >= 0)
1325
+ spliced.attrs[terminator] = flat.attrs[firstTerminator];
1326
+ }
1327
+ return { paragraphs: whole.paragraphs.slice(0, first).concat(flatToContent(spliced).paragraphs, whole.paragraphs.slice(last + 1)) };
1328
+ }