@open-artifact/dc 0.0.0-stage → 0.2.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.
@@ -0,0 +1,1251 @@
1
+ import { TID_ATTRIBUTE } from "../render.js";
2
+ import { focusElement } from "./focus-guard.js";
3
+ /** Marks the element being edited (styled by {@link ensureStyle}). */
4
+ const EDITING_ATTRIBUTE = 'data-dc-editing';
5
+ /** Marks SVG text being edited. */
6
+ const SVG_EDITING_ATTRIBUTE = 'data-dc-editing-svg';
7
+ /** The selection color of the caret and marks drawn over SVG text. */
8
+ const MARK_COLOR = '#2a78d6';
9
+ /** Accessible name and role given to an element that has none while it is edited. */
10
+ const ARIA = [
11
+ ['role', 'textbox'],
12
+ ['aria-label', 'Edit text'],
13
+ ['aria-multiline', 'true'],
14
+ ];
15
+ /** A whole-hole seed: `{{ prop }}`. */
16
+ const WHOLE_PROP = /^\s*\{\{\s*([A-Za-z_$][\w$]*)\s*\}\}\s*$/;
17
+ /** Adds the editing style once. */
18
+ function ensureStyle() {
19
+ if (document.getElementById('dc-text-edit-style'))
20
+ return;
21
+ const style = document.createElement('style');
22
+ style.id = 'dc-text-edit-style';
23
+ style.textContent = `[${EDITING_ATTRIBUTE}]{outline:none!important;cursor:text!important;user-select:text!important;-webkit-user-select:text!important}[${SVG_EDITING_ATTRIBUTE}]{cursor:text!important}`;
24
+ document.head.appendChild(style);
25
+ }
26
+ /** The element a DOM node is or sits in. */
27
+ function elementOf(node) {
28
+ return node ? (node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement) : null;
29
+ }
30
+ function linkAt(range, root) {
31
+ const around = elementOf(range.commonAncestorContainer)?.closest('a');
32
+ if (around)
33
+ return around;
34
+ const words = String(range).trim();
35
+ const links = Array.from(root.querySelectorAll('a')).filter((link) => range.intersectsNode(link));
36
+ if (words === '' || links.length !== 1)
37
+ return null;
38
+ const link = links[0];
39
+ const inner = document.createRange();
40
+ inner.selectNodeContents(link);
41
+ const clipped = range.cloneRange();
42
+ if (clipped.compareBoundaryPoints(Range.START_TO_START, inner) < 0)
43
+ clipped.setStart(inner.startContainer, inner.startOffset);
44
+ if (clipped.compareBoundaryPoints(Range.END_TO_END, inner) > 0)
45
+ clipped.setEnd(inner.endContainer, inner.endOffset);
46
+ if (String(clipped).trim() !== words)
47
+ return null;
48
+ const media = Array.from(root.querySelectorAll('img, svg, picture, video')).some((node) => range.intersectsNode(node) && !link.contains(node));
49
+ return media ? null : link;
50
+ }
51
+ function unlinkPart(link, from, to) {
52
+ const parent = link.parentNode;
53
+ if (!parent)
54
+ return;
55
+ const copy = (fragment) => {
56
+ if (fragment.textContent === '' && !fragment.querySelector('*'))
57
+ return null;
58
+ const twin = link.cloneNode(false);
59
+ twin.removeAttribute(TID_ATTRIBUTE);
60
+ twin.appendChild(fragment);
61
+ for (const stamped of Array.from(twin.querySelectorAll(`[${TID_ATTRIBUTE}]`)))
62
+ stamped.removeAttribute(TID_ATTRIBUTE);
63
+ return twin;
64
+ };
65
+ let split = false;
66
+ if (from && link.contains(from)) {
67
+ const before = document.createRange();
68
+ before.setStart(link, 0);
69
+ before.setEndBefore(from);
70
+ if (!before.collapsed) {
71
+ const twin = copy(before.extractContents());
72
+ if (twin)
73
+ split = parent.insertBefore(twin, link) !== null;
74
+ }
75
+ }
76
+ if (to && link.contains(to)) {
77
+ const after = document.createRange();
78
+ after.setStartAfter(to);
79
+ after.setEnd(link, link.childNodes.length);
80
+ if (!after.collapsed) {
81
+ const twin = copy(after.extractContents());
82
+ if (twin)
83
+ split = parent.insertBefore(twin, link.nextSibling) !== null;
84
+ }
85
+ }
86
+ // Attributes that are more than "a link" (a class, a real style) stay on a span around the middle.
87
+ let holder = parent;
88
+ for (const attr of Array.from(link.attributes)) {
89
+ if (/^(href|target|rel|download|ping|hreflang|referrerpolicy|type)$|^data-dc-/.test(attr.name))
90
+ continue;
91
+ if (attr.name === 'id' && split)
92
+ continue;
93
+ if (attr.name === 'style' &&
94
+ /^\s*(((color|font[a-z-]*|line-height|letter-spacing|text-transform|text-decoration[a-z-]*|text-underline-offset):\s*inherit|text-decoration(-line)?:\s*(none|underline)|display:\s*block)[\s;]*)*$/.test(attr.value)) {
95
+ continue;
96
+ }
97
+ if (holder === parent)
98
+ holder = parent.insertBefore(document.createElement('span'), link);
99
+ holder.setAttribute(attr.name, attr.value);
100
+ }
101
+ while (link.firstChild)
102
+ holder.insertBefore(link.firstChild, holder === parent ? link : null);
103
+ parent.removeChild(link);
104
+ }
105
+ /** Text of an element as typed: text, `<br>` and block breaks as newlines. */
106
+ function typedText(root) {
107
+ const out = [];
108
+ const walk = (node) => {
109
+ for (let child = node.firstChild; child; child = child.nextSibling) {
110
+ if (child.nodeType === Node.TEXT_NODE)
111
+ out.push(child.nodeValue ?? '');
112
+ else if (child.nodeType === Node.ELEMENT_NODE) {
113
+ const tag = child.tagName;
114
+ if (tag === 'BR')
115
+ out.push(child.nextSibling || child.previousSibling ? '\n' : '');
116
+ else {
117
+ if (out.length && (tag === 'DIV' || tag === 'P'))
118
+ out.push('\n');
119
+ walk(child);
120
+ }
121
+ }
122
+ }
123
+ };
124
+ walk(root);
125
+ return out.join('');
126
+ }
127
+ /** The caret position under a point, if the browser can tell. */
128
+ function caretAt(x, y) {
129
+ const doc = document;
130
+ if (typeof doc.caretRangeFromPoint === 'function')
131
+ return doc.caretRangeFromPoint(x, y);
132
+ const position = doc.caretPositionFromPoint?.(x, y);
133
+ if (!position)
134
+ return null;
135
+ const range = document.createRange();
136
+ range.setStart(position.offsetNode, position.offset);
137
+ range.collapse(true);
138
+ return range;
139
+ }
140
+ function placeCaret(element, caret = 'all') {
141
+ const selection = getSelection();
142
+ if (!selection)
143
+ return;
144
+ if (caret && typeof caret === 'object') {
145
+ const range = caretAt(caret.x, caret.y);
146
+ if (range && element.contains(range.startContainer)) {
147
+ selection.removeAllRanges();
148
+ selection.addRange(range);
149
+ return;
150
+ }
151
+ caret = 'end';
152
+ }
153
+ selection.removeAllRanges();
154
+ const range = document.createRange();
155
+ if (caret === 'all') {
156
+ range.selectNodeContents(element);
157
+ selection.addRange(range);
158
+ return;
159
+ }
160
+ let node = element;
161
+ let pre = false;
162
+ for (let last = node.lastChild; last; last = node.lastChild) {
163
+ pre = /^pre|^break-spaces/.test(getComputedStyle(node).whiteSpace || '');
164
+ while (!pre && last.previousSibling && last.nodeType === Node.TEXT_NODE && /^\s*$/.test(last.nodeValue ?? ''))
165
+ last = last.previousSibling;
166
+ node = last;
167
+ if (last.nodeType !== Node.ELEMENT_NODE || last.nodeName === 'A')
168
+ break;
169
+ }
170
+ if (node.nodeType === Node.TEXT_NODE) {
171
+ const value = node.nodeValue ?? '';
172
+ range.setStart(node, pre ? value.length : value.replace(/\s+$/, '').length);
173
+ }
174
+ else if (node !== element)
175
+ range.setStartAfter(node);
176
+ else
177
+ range.setStart(element, 0);
178
+ range.collapse(true);
179
+ selection.addRange(range);
180
+ }
181
+ /* ------------------------------ SVG text ------------------------------ */
182
+ /** The words SVG text shows, its spaces collapsed as drawn. */
183
+ function drawnSvgText(element) {
184
+ const text = (element.textContent ?? '').replace(/[ \t\r\n\f]+/g, ' ');
185
+ let count = -1;
186
+ try {
187
+ count = element.getNumberOfChars();
188
+ }
189
+ catch {
190
+ /* Not laid out. */
191
+ }
192
+ if (text.length === count)
193
+ return text;
194
+ if (text.length > 1 && text.startsWith(' ') && text.endsWith(' ') && text.length - 1 === count) {
195
+ const outer = element.closest('text');
196
+ let before = '';
197
+ if (outer && outer !== element) {
198
+ const range = document.createRange();
199
+ range.setStart(outer, 0);
200
+ range.setEndBefore(element);
201
+ before = range.toString();
202
+ }
203
+ return /\S/.test(before) ? text.slice(0, -1) : text.slice(1);
204
+ }
205
+ return text.replace(/^ | $/g, '');
206
+ }
207
+ /** Screen pixels per user unit of SVG text. */
208
+ function svgScale(element) {
209
+ try {
210
+ const matrix = element.getScreenCTM();
211
+ const scale = (matrix && Math.sqrt(matrix.a * matrix.a + matrix.b * matrix.b)) || 1;
212
+ if (matrix && (matrix.b || matrix.c))
213
+ return scale;
214
+ const outer = element.closest('text') ?? element;
215
+ const box = outer.getBBox();
216
+ const rect = outer.getBoundingClientRect();
217
+ return box.width > 0 && rect.width > 0 ? rect.width / box.width : scale;
218
+ }
219
+ catch {
220
+ return 1;
221
+ }
222
+ }
223
+ /** A point of SVG text in screen pixels. */
224
+ function svgPoint(element, x, y) {
225
+ const matrix = element.getScreenCTM();
226
+ if (matrix && (matrix.b || matrix.c)) {
227
+ const point = new DOMPoint(x, y).matrixTransform(matrix);
228
+ return { x: point.x, y: point.y };
229
+ }
230
+ const outer = element.closest('text') ?? element;
231
+ const box = outer.getBBox();
232
+ const rect = outer.getBoundingClientRect();
233
+ const scale = box.width > 0 && rect.width > 0 ? rect.width / box.width : 1;
234
+ return { x: rect.left + (x - box.x) * scale, y: rect.top + (y - box.y) * scale };
235
+ }
236
+ /** One caret stop per character, plus one after the last. */
237
+ function svgStops(element) {
238
+ const glyphs = [];
239
+ let count = 0;
240
+ try {
241
+ count = element.getNumberOfChars();
242
+ }
243
+ catch {
244
+ /* Not laid out. */
245
+ }
246
+ let first = -1;
247
+ let last = -1;
248
+ for (let index = 0; index < count; index++) {
249
+ let stop = null;
250
+ try {
251
+ if (element.getExtentOfChar(index).width > 0) {
252
+ const from = svgPoint(element, element.getStartPositionOfChar(index).x, element.getStartPositionOfChar(index).y);
253
+ const to = svgPoint(element, element.getEndPositionOfChar(index).x, element.getEndPositionOfChar(index).y);
254
+ stop = { x: from.x, y: from.y, ang: Math.atan2(to.y - from.y, to.x - from.x), w: Math.hypot(to.x - from.x, to.y - from.y), drawn: true };
255
+ if (first < 0)
256
+ first = index;
257
+ last = index;
258
+ }
259
+ }
260
+ catch {
261
+ /* A glyph the browser does not place. */
262
+ }
263
+ glyphs.push(stop);
264
+ }
265
+ const stops = [];
266
+ if (first < 0)
267
+ return stops;
268
+ const end = glyphs[last];
269
+ const after = svgPoint(element, element.getEndPositionOfChar(last).x, element.getEndPositionOfChar(last).y);
270
+ const tail = { x: after.x, y: after.y, ang: end.ang, w: 0, drawn: true };
271
+ for (let index = 0; index <= count; index++) {
272
+ const glyph = glyphs[index];
273
+ if (index < count && glyph)
274
+ stops.push(glyph);
275
+ else if (index > last)
276
+ stops.push(index === last + 1 ? tail : { ...tail, w: 0, drawn: false });
277
+ else {
278
+ let next = index;
279
+ while (!glyphs[next])
280
+ next++;
281
+ const at = glyphs[next];
282
+ stops.push({ x: at.x, y: at.y, ang: at.ang, w: 0, drawn: false });
283
+ }
284
+ }
285
+ return stops;
286
+ }
287
+ /** The caret stop nearest a point. */
288
+ function nearestStop(element, x, y) {
289
+ const stops = svgStops(element);
290
+ let best = 0;
291
+ let distance = Infinity;
292
+ stops.forEach((stop, index) => {
293
+ if (!stop.drawn)
294
+ return;
295
+ const d = (stop.x - x) ** 2 + (stop.y - y) ** 2;
296
+ if (d < distance) {
297
+ distance = d;
298
+ best = index;
299
+ }
300
+ });
301
+ return best;
302
+ }
303
+ /** The selection in a field as character offsets [anchor, focus]. */
304
+ function fieldSelection(field) {
305
+ const selection = getSelection();
306
+ const length = (field.textContent ?? '').length;
307
+ const offset = (node, at) => {
308
+ if (!node || !field.contains(node))
309
+ return length;
310
+ if (node === field) {
311
+ let total = 0;
312
+ for (let index = 0; index < at && index < field.childNodes.length; index++)
313
+ total += (field.childNodes[index].textContent ?? '').length;
314
+ return total;
315
+ }
316
+ const walker = document.createTreeWalker(field, NodeFilter.SHOW_TEXT);
317
+ let total = 0;
318
+ for (let text = walker.nextNode(); text; text = walker.nextNode()) {
319
+ if (text === node)
320
+ return total + at;
321
+ total += (text.nodeValue ?? '').length;
322
+ }
323
+ return length;
324
+ };
325
+ if (!selection || !selection.rangeCount || !field.contains(selection.anchorNode))
326
+ return [length, length];
327
+ return [offset(selection.anchorNode, selection.anchorOffset), offset(selection.focusNode, selection.focusOffset)];
328
+ }
329
+ /** Selects characters `from`..`to` of a field. */
330
+ function selectInField(field, from, to) {
331
+ const locate = (at) => {
332
+ const walker = document.createTreeWalker(field, NodeFilter.SHOW_TEXT);
333
+ let last = null;
334
+ at = Math.max(0, at);
335
+ for (let text = walker.nextNode(); text; text = walker.nextNode()) {
336
+ if (at <= text.data.length)
337
+ return [text, at];
338
+ at -= text.data.length;
339
+ last = text;
340
+ }
341
+ return last ? [last, last.data.length] : [field, 0];
342
+ };
343
+ const [anchorNode, anchorOffset] = locate(from);
344
+ const [focusNode, focusOffset] = locate(to);
345
+ focusElement(field);
346
+ getSelection()?.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);
347
+ }
348
+ /* ------------------------- words of a component ------------------------- */
349
+ /** A text node's words, spaces collapsed. */
350
+ const nodeWords = (node) => (node.nodeValue ?? '').replace(/[ \t\n\r\f]+/g, ' ').replace(/^ | $/g, '');
351
+ /** The words a point falls on: a text node whose drawn box holds the point. */
352
+ function textNodeAt(x, y) {
353
+ const node = caretAt(x, y)?.startContainer ?? null;
354
+ if (!node || node.nodeType !== Node.TEXT_NODE || (node.nodeValue ?? '').trim() === '')
355
+ return null;
356
+ const range = document.createRange();
357
+ range.selectNodeContents(node);
358
+ for (const rect of Array.from(range.getClientRects())) {
359
+ if (x >= rect.left - 1 && x <= rect.right + 1 && y >= rect.top - 1 && y <= rect.bottom + 1)
360
+ return node;
361
+ }
362
+ return null;
363
+ }
364
+ function importTextNode(mount, targets, under) {
365
+ const own = (node) => {
366
+ const parent = node.parentElement;
367
+ return (node.nodeType === Node.TEXT_NODE &&
368
+ Boolean(parent) &&
369
+ mount.contains(node) &&
370
+ parent.closest(`[${TID_ATTRIBUTE}]`) === mount &&
371
+ parent.namespaceURI === 'http://www.w3.org/1999/xhtml' &&
372
+ !parent.closest('textarea, select, option, title, script, style, noscript'));
373
+ };
374
+ const each = (visit) => {
375
+ const walker = document.createTreeWalker(mount, NodeFilter.SHOW_TEXT);
376
+ for (let node = walker.nextNode(); node; node = walker.nextNode())
377
+ if (visit(node) === false)
378
+ return;
379
+ };
380
+ let found = null;
381
+ let unclear = false;
382
+ if (under) {
383
+ if (!own(under))
384
+ return null;
385
+ const words = nodeWords(under);
386
+ each((node) => {
387
+ if (node !== under && own(node) && nodeWords(node) === words)
388
+ return !(unclear = true);
389
+ });
390
+ found = under;
391
+ }
392
+ else {
393
+ each((node) => {
394
+ if (!own(node) || !/[\p{L}\p{N}]/u.test(node.nodeValue ?? ''))
395
+ return;
396
+ if (found)
397
+ return !(unclear = true);
398
+ found = node;
399
+ });
400
+ }
401
+ if (!found || unclear)
402
+ return null;
403
+ const node = found;
404
+ const words = nodeWords(node);
405
+ const target = targets.find((each) => each.words === words);
406
+ if (!target)
407
+ return null;
408
+ if (target.number) {
409
+ let digits = false;
410
+ each((other) => {
411
+ if (other !== node && own(other) && /\d/.test(other.nodeValue ?? ''))
412
+ return !(digits = true);
413
+ });
414
+ if (digits)
415
+ return null;
416
+ }
417
+ return { node, key: target.key, words };
418
+ }
419
+ /** True when the words are drawn where they can be seen and edited. */
420
+ function visibleWords(node, mount, underPoint) {
421
+ const parent = node.parentElement;
422
+ if (!parent)
423
+ return false;
424
+ const range = document.createRange();
425
+ range.selectNodeContents(node);
426
+ const rects = range.getClientRects();
427
+ if (!rects.length || rects[0].height < 2 || getComputedStyle(parent).visibility !== 'visible')
428
+ return false;
429
+ for (let element = parent; element; element = element.parentElement) {
430
+ const style = getComputedStyle(element);
431
+ const clips = style.overflowX !== 'visible' || style.overflowY !== 'visible';
432
+ if (parseFloat(style.opacity) === 0)
433
+ return false;
434
+ if (element !== mount && mount.contains(element) && clips && (element.offsetWidth < 2 || element.offsetHeight < 2))
435
+ return false;
436
+ }
437
+ if (underPoint)
438
+ return true;
439
+ const first = rects[0];
440
+ const top = document.elementFromPoint(first.left + first.width / 2, first.top + first.height / 2);
441
+ return Boolean(top && mount.contains(top));
442
+ }
443
+ /**
444
+ * Sets SVG text up for editing: the drawing shows one text
445
+ * node of its words, and a hidden field over it takes the keys.
446
+ */
447
+ function svgField(svg) {
448
+ const style = getComputedStyle(svg);
449
+ const pre = /^(pre|pre-wrap|break-spaces)$/.test(style.whiteSpace);
450
+ const startText = pre ? (svg.textContent ?? '') : drawnSvgText(svg);
451
+ const ws = svg.style.getPropertyValue('white-space');
452
+ svg.style.setProperty('white-space', 'pre');
453
+ svg.setAttribute(SVG_EDITING_ATTRIBUTE, '');
454
+ const field = document.createElement('div');
455
+ field.setAttribute('role', 'textbox');
456
+ field.setAttribute('aria-label', 'Edit text');
457
+ field.style.cssText = `position:fixed;left:0;top:0;z-index:2147483646;opacity:0;pointer-events:none;overflow:hidden;white-space:pre;outline:none;font-size:${style.fontSize};`;
458
+ const text = document.createTextNode(startText);
459
+ svg.replaceChildren(text);
460
+ field.textContent = startText;
461
+ document.body.appendChild(field);
462
+ return { edit: { svg, text, pre, ws, startText, lastStop: null, marks: [], anchor: null, down: null }, field };
463
+ }
464
+ /** Events that stay with a component's field while its words are edited. */
465
+ const FIELD_EVENTS = ['keydown', 'keyup', 'keypress', 'mousedown', 'mouseup', 'pointerdown', 'pointerup', 'dblclick'];
466
+ /**
467
+ * Also kept from a component around an import field: React hears focus
468
+ * through `focusin` / `focusout`, and a collection such as a menu would
469
+ * otherwise take focus back to its item and end the edit. The field's own
470
+ * `blur` listener still runs.
471
+ */
472
+ const IMPORT_FIELD_EVENTS = [...FIELD_EVENTS, 'focusin', 'focusout', 'click'];
473
+ /** Escapes text for HTML. */
474
+ const escapeHtml = (text) => text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
475
+ /** True for a pasted address that becomes a link. */
476
+ const URL_PASTE = /^https?:\/\/\S+$/i;
477
+ /** In-place text editing of one element at a time. */
478
+ export class TextEditor {
479
+ report;
480
+ session = null;
481
+ stateTimer = null;
482
+ constructor(report) {
483
+ this.report = report;
484
+ document.addEventListener('selectionchange', () => this.selectionChanged());
485
+ }
486
+ /** True while an element is being edited. */
487
+ get active() {
488
+ return this.session !== null;
489
+ }
490
+ /** The element being edited. */
491
+ get element() {
492
+ return this.session?.element ?? null;
493
+ }
494
+ /** Starts editing `host` (template node `tid`). */
495
+ start(host, tid, options = {}) {
496
+ this.end(true);
497
+ if (!host.isConnected)
498
+ return false;
499
+ const element = host;
500
+ ensureStyle();
501
+ const rendered = element.textContent ?? '';
502
+ let target = null;
503
+ let seeded = false;
504
+ if (options.seed != null) {
505
+ const whole = WHOLE_PROP.exec(options.seed);
506
+ const props = options.props ?? {};
507
+ if (whole && Object.hasOwn(props, whole[1]) && props[whole[1]] === rendered) {
508
+ target = { kind: 'prop', prop: whole[1], value: rendered };
509
+ }
510
+ else {
511
+ const matches = rendered.trim() === '' ? [] : (options.literals ?? []).filter((literal) => literal.value === rendered);
512
+ if (matches.length === 1)
513
+ target = { kind: 'script', ...matches[0] };
514
+ else
515
+ seeded = true;
516
+ }
517
+ }
518
+ const saved = Array.from(element.childNodes);
519
+ if (target)
520
+ element.textContent = rendered;
521
+ else if (seeded)
522
+ element.innerHTML = options.seed;
523
+ else {
524
+ const copies = saved.map((node) => node.cloneNode(true));
525
+ for (const copy of copies) {
526
+ if (copy.nodeType !== Node.ELEMENT_NODE)
527
+ continue;
528
+ copy.removeAttribute(TID_ATTRIBUTE);
529
+ for (const stamped of Array.from(copy.querySelectorAll(`[${TID_ATTRIBUTE}]`)))
530
+ stamped.removeAttribute(TID_ATTRIBUTE);
531
+ }
532
+ element.replaceChildren(...copies);
533
+ }
534
+ const session = {
535
+ element,
536
+ host,
537
+ tid,
538
+ saved,
539
+ startHtml: element.innerHTML,
540
+ target,
541
+ ownEditable: element.getAttribute('contenteditable'),
542
+ aria: [],
543
+ range: null,
544
+ linkRange: null,
545
+ newLink: null,
546
+ svg: null,
547
+ imported: null,
548
+ listeners: [],
549
+ };
550
+ this.session = session;
551
+ if (host instanceof SVGElement) {
552
+ // Drawn text takes no caret: a hidden field takes the keys and the drawing mirrors it.
553
+ const { edit, field } = svgField(host);
554
+ session.svg = edit;
555
+ session.element = field;
556
+ }
557
+ const field = session.element;
558
+ field.setAttribute('contenteditable', target || session.svg ? 'plaintext-only' : 'true');
559
+ if ((target || session.svg) && field.getAttribute('contenteditable') !== 'plaintext-only')
560
+ field.setAttribute('contenteditable', 'true');
561
+ field.setAttribute(EDITING_ATTRIBUTE, '');
562
+ if (!session.svg && !ARIA.some(([name]) => field.hasAttribute(name)) && !field.hasAttribute('aria-labelledby')) {
563
+ for (const [name, value] of ARIA)
564
+ field.setAttribute(name, value);
565
+ session.aria = ARIA.map(([name]) => name);
566
+ }
567
+ this.listenField(session);
568
+ focusElement(field);
569
+ placeCaret(field, session.svg ? 'all' : options.caret);
570
+ this.postState();
571
+ if (session.svg)
572
+ this.placeSvgField();
573
+ return true;
574
+ }
575
+ startImport(mount, tid, x, y, targets) {
576
+ this.end(true);
577
+ if (!mount.isConnected || !targets.length)
578
+ return false;
579
+ const under = textNodeAt(x, y);
580
+ const found = importTextNode(mount, targets, under);
581
+ if (!found || !visibleWords(found.node, mount, found.node === under))
582
+ return false;
583
+ ensureStyle();
584
+ const field = document.createElement('dc-edit-field');
585
+ field.textContent = (found.node.nodeValue ?? '').replace(/[ \t\n\r\f]+/g, ' ');
586
+ field.style.cssText = 'user-select:text!important;-webkit-user-select:text!important;';
587
+ const watch = new MutationObserver(() => {
588
+ if (this.session !== session)
589
+ watch.disconnect();
590
+ else if (!field.isConnected)
591
+ this.end(false);
592
+ });
593
+ const session = {
594
+ element: field,
595
+ host: mount,
596
+ tid,
597
+ saved: [],
598
+ startHtml: field.innerHTML,
599
+ target: { kind: 'import', key: found.key, words: found.words },
600
+ ownEditable: null,
601
+ aria: [],
602
+ range: null,
603
+ linkRange: null,
604
+ newLink: null,
605
+ svg: null,
606
+ imported: { mount, node: found.node, value: found.node.nodeValue ?? '', startText: field.textContent, key: found.key, words: found.words, watch },
607
+ listeners: [],
608
+ };
609
+ found.node.parentNode.insertBefore(field, found.node.nextSibling);
610
+ found.node.nodeValue = '';
611
+ this.session = session;
612
+ watch.observe(document.documentElement, { childList: true, subtree: true });
613
+ // The component's own handlers do not see keys and clicks meant for the field.
614
+ const keep = (event) => {
615
+ if (this.session === session && field.contains(event.target))
616
+ event.stopPropagation();
617
+ };
618
+ for (const type of IMPORT_FIELD_EVENTS) {
619
+ document.addEventListener(type, keep, true);
620
+ session.listeners.push([document, type, keep, true]);
621
+ }
622
+ field.setAttribute('contenteditable', 'plaintext-only');
623
+ if (field.getAttribute('contenteditable') !== 'plaintext-only')
624
+ field.setAttribute('contenteditable', 'true');
625
+ field.setAttribute(EDITING_ATTRIBUTE, 'import');
626
+ for (const [name, value] of ARIA)
627
+ field.setAttribute(name, name === 'aria-multiline' ? 'false' : value);
628
+ this.listenField(session);
629
+ focusElement(field);
630
+ placeCaret(field, 'all');
631
+ this.postState();
632
+ return true;
633
+ }
634
+ /** The field's own listeners: input, paste, and focus leaving. */
635
+ listenField(session) {
636
+ const field = session.element;
637
+ const listen = (on, type, listener, capture = false) => {
638
+ on.addEventListener(type, listener, capture);
639
+ session.listeners.push([on, type, listener, capture]);
640
+ };
641
+ listen(field, 'input', () => {
642
+ const svg = session.svg;
643
+ if (svg) {
644
+ if (!svg.svg.isConnected) {
645
+ this.end(false);
646
+ return;
647
+ }
648
+ if (svg.text.parentNode !== svg.svg)
649
+ svg.svg.replaceChildren(svg.text);
650
+ svg.text.nodeValue = field.textContent ?? '';
651
+ this.drawSvgMarks();
652
+ }
653
+ this.scheduleState();
654
+ });
655
+ listen(field, 'paste', (event) => this.paste(event));
656
+ listen(field, 'blur', () => {
657
+ if (this.session === session)
658
+ this.report({ type: 'text-blur' });
659
+ });
660
+ if (session.svg) {
661
+ const svg = session.svg;
662
+ listen(document, 'scroll', () => this.placeSvgField(), true);
663
+ listen(window, 'resize', () => this.placeSvgField());
664
+ listen(document, 'mousedown', (event) => this.svgPointerDown(event), true);
665
+ listen(document, 'mousemove', (event) => this.svgPointerMove(event), true);
666
+ listen(document, 'dblclick', (event) => {
667
+ if (!this.onSvgText(event))
668
+ return;
669
+ event.preventDefault();
670
+ event.stopPropagation();
671
+ this.svgSelectWord(event);
672
+ }, true);
673
+ }
674
+ }
675
+ /** Ends the edit, reporting the change (or none). */
676
+ end(commit) {
677
+ const session = this.session;
678
+ if (!session)
679
+ return;
680
+ this.session = null;
681
+ if (this.stateTimer !== null)
682
+ clearTimeout(this.stateTimer);
683
+ this.stateTimer = null;
684
+ const { element } = session;
685
+ for (const [on, type, listener, capture] of session.listeners)
686
+ on.removeEventListener(type, listener, capture);
687
+ element.removeAttribute(EDITING_ATTRIBUTE);
688
+ const finish = (live, changed, html, text, link) => {
689
+ this.report({ type: 'text-state', active: false });
690
+ if (!commit || !live || !changed)
691
+ this.report({ type: 'text-cancel', tid: session.tid });
692
+ else
693
+ this.report({ type: 'text-commit', tid: session.tid, html, text, ...(session.target ? { target: session.target } : {}), ...(link !== undefined && link >= 0 ? { link } : {}) });
694
+ };
695
+ if (session.imported) {
696
+ const imported = session.imported;
697
+ imported.watch.disconnect();
698
+ const text = element.textContent ?? '';
699
+ const live = imported.mount.isConnected && element.isConnected;
700
+ if (element.contains(document.activeElement))
701
+ element.blur();
702
+ element.remove();
703
+ if (imported.node.nodeValue === '')
704
+ imported.node.nodeValue = imported.value;
705
+ finish(live, text.trim() !== '' && text !== imported.startText, '', text);
706
+ return;
707
+ }
708
+ if (session.svg) {
709
+ const svg = session.svg;
710
+ const text = element.textContent ?? '';
711
+ if (element.contains(document.activeElement))
712
+ element.blur();
713
+ element.remove();
714
+ for (const mark of svg.marks)
715
+ mark.remove();
716
+ svg.svg.removeAttribute(SVG_EDITING_ATTRIBUTE);
717
+ if (svg.ws)
718
+ svg.svg.style.setProperty('white-space', svg.ws);
719
+ else
720
+ svg.svg.style.removeProperty('white-space');
721
+ if (!svg.svg.getAttribute('style'))
722
+ svg.svg.removeAttribute('style');
723
+ svg.svg.replaceChildren(...session.saved);
724
+ finish(svg.svg.isConnected, text.trim() !== '' && text !== svg.startText, escapeHtml(text), text);
725
+ return;
726
+ }
727
+ if (session.ownEditable !== null)
728
+ element.setAttribute('contenteditable', session.ownEditable);
729
+ else
730
+ element.removeAttribute('contenteditable');
731
+ for (const name of session.aria)
732
+ element.removeAttribute(name);
733
+ // Which link was just set: the editor selects it once the words are written.
734
+ const link = session.newLink && element.contains(session.newLink) ? Array.from(element.querySelectorAll('a')).indexOf(session.newLink) : undefined;
735
+ const html = element.innerHTML;
736
+ const text = session.target ? typedText(element) : (element.innerText ?? '').replace(/\n$/, '');
737
+ if (element.contains(document.activeElement))
738
+ document.activeElement?.blur?.();
739
+ // Hand React back the exact nodes it rendered; the source update re-renders the text.
740
+ element.replaceChildren(...session.saved);
741
+ finish(true, html !== session.startHtml, html, text, link);
742
+ }
743
+ /** Toggles a format on the selection. */
744
+ format(verb) {
745
+ const session = this.session;
746
+ if (!session || session.target || session.svg)
747
+ return;
748
+ this.refocus(session);
749
+ try {
750
+ FORMATS[verb](this, session);
751
+ }
752
+ catch {
753
+ /* A command the browser refuses changes nothing. */
754
+ }
755
+ this.postState();
756
+ }
757
+ applyLink(href) {
758
+ const session = this.session;
759
+ if (!session)
760
+ return;
761
+ const range = session.linkRange;
762
+ session.linkRange = null;
763
+ if (!range) {
764
+ this.cancelLinkEdit();
765
+ return;
766
+ }
767
+ const root = session.element;
768
+ try {
769
+ focusElement(root);
770
+ const selection = getSelection();
771
+ const found = linkAt(range, root);
772
+ const inner = found && found !== root && root.contains(found) ? found : null;
773
+ const outer = found && !inner ? found : null;
774
+ const address = (href ?? '').trim();
775
+ if (address === '') {
776
+ // Unlink what the selection covers.
777
+ let start = null;
778
+ let finish = null;
779
+ if (!range.collapsed) {
780
+ finish = document.createTextNode('');
781
+ const tail = range.cloneRange();
782
+ tail.collapse(false);
783
+ tail.insertNode(finish);
784
+ start = document.createTextNode('');
785
+ const head = range.cloneRange();
786
+ head.collapse(true);
787
+ head.insertNode(start);
788
+ }
789
+ const links = inner ? [inner] : [];
790
+ for (const link of Array.from(root.querySelectorAll('a')))
791
+ if (!links.includes(link) && range.intersectsNode(link))
792
+ links.push(link);
793
+ for (const link of links)
794
+ if (link !== root && root.contains(link))
795
+ unlinkPart(link, start, finish);
796
+ start?.remove();
797
+ finish?.remove();
798
+ }
799
+ else if (inner) {
800
+ if ((inner.getAttribute('href') ?? '').trim() === address) {
801
+ this.cancelLinkEdit();
802
+ return;
803
+ }
804
+ inner.setAttribute('href', address);
805
+ session.newLink = inner;
806
+ }
807
+ else if (!range.collapsed && !outer) {
808
+ const finish = document.createTextNode('');
809
+ const tail = range.cloneRange();
810
+ tail.collapse(false);
811
+ tail.insertNode(finish);
812
+ const start = document.createTextNode('');
813
+ const head = range.cloneRange();
814
+ head.collapse(true);
815
+ head.insertNode(start);
816
+ // Links the selection overlaps give up that part first: links never nest.
817
+ for (const link of Array.from(root.querySelectorAll('a'))) {
818
+ if (link !== root && root.contains(link) && range.intersectsNode(link))
819
+ unlinkPart(link, start, finish);
820
+ }
821
+ range.setStartAfter(start);
822
+ range.setEndBefore(finish);
823
+ const link = document.createElement('a');
824
+ link.setAttribute('href', address);
825
+ try {
826
+ range.surroundContents(link);
827
+ }
828
+ catch {
829
+ link.appendChild(range.extractContents());
830
+ range.insertNode(link);
831
+ }
832
+ try {
833
+ selection?.removeAllRanges();
834
+ const after = document.createRange();
835
+ after.setStartAfter(link);
836
+ after.collapse(true);
837
+ selection?.addRange(after);
838
+ }
839
+ catch {
840
+ /* The caret stays where it was. */
841
+ }
842
+ start.remove();
843
+ finish.remove();
844
+ session.newLink = link;
845
+ }
846
+ }
847
+ catch {
848
+ /* Leave the text as it is. */
849
+ }
850
+ // Setting a link ends the edit; the editor then selects the link.
851
+ if (session.newLink) {
852
+ this.end(true);
853
+ return;
854
+ }
855
+ this.postState();
856
+ }
857
+ /** Answers a `link-edit` without a change. */
858
+ cancelLinkEdit() {
859
+ const session = this.session;
860
+ if (!session)
861
+ return;
862
+ session.linkRange = null;
863
+ this.refocus(session);
864
+ this.postState();
865
+ }
866
+ /** Keys while editing; true when the key was handled here. */
867
+ keydown(event) {
868
+ const session = this.session;
869
+ if (!session)
870
+ return false;
871
+ const { element } = session;
872
+ const composing = event.isComposing || event.keyCode === 229;
873
+ if (event.key === ' ' && !composing && !event.ctrlKey && !event.metaKey && !event.altKey && element.closest('button, summary')) {
874
+ // A space must not press the button being retyped.
875
+ event.preventDefault();
876
+ document.execCommand('insertText', false, ' ');
877
+ return true;
878
+ }
879
+ if (document.activeElement !== element && !element.contains(document.activeElement))
880
+ focusElement(element);
881
+ if ((session.svg || session.imported) && event.key === 'Enter') {
882
+ // One line: Enter ends the edit.
883
+ if (composing)
884
+ return false;
885
+ event.preventDefault();
886
+ this.end(true);
887
+ return true;
888
+ }
889
+ if (event.key === 'Enter' && !event.shiftKey && !composing && !event.ctrlKey && !event.metaKey) {
890
+ const item = elementOf(getSelection()?.anchorNode ?? null)?.closest('li');
891
+ if (!(item && item !== element && element.contains(item))) {
892
+ event.preventDefault();
893
+ if (!document.execCommand('insertLineBreak'))
894
+ document.execCommand('insertHTML', false, '<br>');
895
+ return true;
896
+ }
897
+ return false;
898
+ }
899
+ if (event.key === 'Escape' || (event.key === 'Tab' && !event.ctrlKey && !event.metaKey && !composing)) {
900
+ event.preventDefault();
901
+ this.end(true);
902
+ return true;
903
+ }
904
+ if ((event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === 'k') {
905
+ event.preventDefault();
906
+ this.format('link');
907
+ return true;
908
+ }
909
+ if ((session.target || session.svg) && (event.metaKey || event.ctrlKey) && /^[biu]$/i.test(event.key)) {
910
+ // Plain text: no formatting.
911
+ event.preventDefault();
912
+ return true;
913
+ }
914
+ return false;
915
+ }
916
+ /* ----------------------------- internals ----------------------------- */
917
+ /** Focuses the element, putting back the selection it had when focus left. */
918
+ refocus(session) {
919
+ try {
920
+ focusElement(session.element);
921
+ const selection = getSelection();
922
+ const inside = selection && selection.rangeCount > 0 && session.element.contains(selection.getRangeAt(0).startContainer);
923
+ if (!inside && session.range && selection) {
924
+ selection.removeAllRanges();
925
+ selection.addRange(session.range);
926
+ }
927
+ else if (!inside)
928
+ placeCaret(session.element, 'end');
929
+ }
930
+ catch {
931
+ /* Focus is the browser's to give. */
932
+ }
933
+ }
934
+ selectionChanged() {
935
+ const session = this.session;
936
+ if (!session)
937
+ return;
938
+ const selection = getSelection();
939
+ if (selection && selection.rangeCount > 0) {
940
+ const range = selection.getRangeAt(0);
941
+ if (session.element.contains(range.startContainer) && session.element.contains(range.endContainer))
942
+ session.range = range.cloneRange();
943
+ }
944
+ this.drawSvgMarks();
945
+ this.scheduleState();
946
+ }
947
+ scheduleState() {
948
+ if (!this.session || this.stateTimer !== null)
949
+ return;
950
+ this.stateTimer = setTimeout(() => {
951
+ this.stateTimer = null;
952
+ if (this.session)
953
+ this.postState();
954
+ }, 120);
955
+ }
956
+ postState() {
957
+ const session = this.session;
958
+ if (this.stateTimer !== null)
959
+ clearTimeout(this.stateTimer);
960
+ this.stateTimer = null;
961
+ if (!session) {
962
+ this.report({ type: 'text-state', active: false });
963
+ return;
964
+ }
965
+ const formats = { bold: false, italic: false, underline: false, ul: false, ol: false, link: false };
966
+ const plain = session.target !== null || session.svg !== null;
967
+ if (!plain) {
968
+ const query = (command) => {
969
+ try {
970
+ return document.queryCommandState(command);
971
+ }
972
+ catch {
973
+ return false;
974
+ }
975
+ };
976
+ formats.bold = query('bold');
977
+ formats.italic = query('italic');
978
+ formats.ul = query('insertUnorderedList');
979
+ formats.ol = query('insertOrderedList');
980
+ const link = this.selectedLink(session);
981
+ formats.link = link !== null;
982
+ formats.underline = link ? (getComputedStyle(link).textDecorationLine || '').includes('underline') : query('underline');
983
+ }
984
+ this.report({ type: 'text-state', active: true, tid: session.tid, plain, formats });
985
+ }
986
+ /** The link at the selection inside the edited element. */
987
+ selectedLink(session) {
988
+ const selection = getSelection();
989
+ let link = elementOf(selection?.anchorNode ?? null)?.closest('a');
990
+ if (!link && selection && selection.rangeCount > 0)
991
+ link = linkAt(selection.getRangeAt(0), session.element);
992
+ return link && session.element.contains(link) ? link : null;
993
+ }
994
+ /** Rect of a range or element in board pixels. */
995
+ static rectOf(target) {
996
+ const rect = target.getBoundingClientRect();
997
+ return { x: rect.left, y: rect.top, width: rect.width, height: rect.height };
998
+ }
999
+ paste(event) {
1000
+ const session = this.session;
1001
+ if (!session)
1002
+ return;
1003
+ const text = event.clipboardData?.getData('text/plain') ?? '';
1004
+ const address = text.trim();
1005
+ if (session.svg || session.imported) {
1006
+ // One line of words.
1007
+ event.preventDefault();
1008
+ event.stopPropagation();
1009
+ document.execCommand('insertText', false, text.replace(/[ \t]*[\r\n]+[ \t]*/g, ' '));
1010
+ return;
1011
+ }
1012
+ // Anything else pastes as the browser does; the words are cleaned when written.
1013
+ if (session.target || !URL_PASTE.test(address))
1014
+ return;
1015
+ const selection = getSelection();
1016
+ if (selection && selection.rangeCount > 0 && !selection.isCollapsed) {
1017
+ const range = selection.getRangeAt(0);
1018
+ if (session.element.contains(range.commonAncestorContainer)) {
1019
+ event.preventDefault();
1020
+ const found = linkAt(range, session.element);
1021
+ const link = found && found !== session.element && session.element.contains(found) ? found : document.createElement('a');
1022
+ link.setAttribute('href', address);
1023
+ if (link !== found) {
1024
+ try {
1025
+ range.surroundContents(link);
1026
+ }
1027
+ catch {
1028
+ link.appendChild(range.extractContents());
1029
+ range.insertNode(link);
1030
+ }
1031
+ }
1032
+ selection.removeAllRanges();
1033
+ const after = document.createRange();
1034
+ after.setStartAfter(link);
1035
+ after.collapse(true);
1036
+ selection.addRange(after);
1037
+ this.scheduleState();
1038
+ }
1039
+ }
1040
+ }
1041
+ /* ------------------------------ SVG text ------------------------------ */
1042
+ /** Keeps the hidden field over the drawn text and redraws the marks. */
1043
+ placeSvgField() {
1044
+ const session = this.session;
1045
+ const svg = session?.svg;
1046
+ if (!svg)
1047
+ return;
1048
+ if (!svg.svg.isConnected) {
1049
+ this.end(false);
1050
+ return;
1051
+ }
1052
+ const rect = svg.svg.getBoundingClientRect();
1053
+ const field = session.element;
1054
+ if (rect.width > 0) {
1055
+ field.style.left = `${rect.left}px`;
1056
+ field.style.top = `${rect.top}px`;
1057
+ field.style.width = `${rect.width}px`;
1058
+ field.style.height = `${Math.max(rect.height, 1)}px`;
1059
+ }
1060
+ this.drawSvgMarks();
1061
+ }
1062
+ /** Draws the caret, or the selection, over the drawn text. */
1063
+ drawSvgMarks() {
1064
+ const session = this.session;
1065
+ const svg = session?.svg;
1066
+ if (!svg)
1067
+ return;
1068
+ let used = 0;
1069
+ const mark = (stop, width, height, caret) => {
1070
+ let element = svg.marks[used++];
1071
+ if (!element) {
1072
+ element = document.createElement('div');
1073
+ document.body.appendChild(element);
1074
+ svg.marks.push(element);
1075
+ }
1076
+ element.setAttribute('data-dc-svg-mark', caret ? 'caret' : 'sel');
1077
+ element.style.cssText = `position:fixed;left:0;top:0;pointer-events:none;z-index:2147483646;transform-origin:0 0;width:${caret ? 1.5 : width}px;height:${height * 1.05}px;background:${caret ? MARK_COLOR : `color-mix(in srgb,${MARK_COLOR} 32%,transparent)`};transform:translate(${stop.x}px,${stop.y}px) rotate(${stop.ang}rad) translate(0,${-height * 0.88}px);`;
1078
+ const animations = element.getAnimations?.() ?? [];
1079
+ if (caret && !animations.length) {
1080
+ element.animate?.([{ opacity: 1 }, { opacity: 1, offset: 0.5 }, { opacity: 0, offset: 0.5 }, { opacity: 0 }], { duration: 1000, iterations: Infinity });
1081
+ }
1082
+ for (const animation of animations) {
1083
+ if (caret)
1084
+ animation.currentTime = 0;
1085
+ else
1086
+ animation.cancel();
1087
+ }
1088
+ };
1089
+ if (svg.svg.isConnected) {
1090
+ const stops = svgStops(svg.svg);
1091
+ const height = (parseFloat(getComputedStyle(svg.svg).fontSize) || 16) * svgScale(svg.svg);
1092
+ const [anchor, focus] = fieldSelection(session.element);
1093
+ const from = Math.min(anchor, focus);
1094
+ const to = Math.max(anchor, focus);
1095
+ const last = stops.length - 1;
1096
+ if (last < 0) {
1097
+ if (svg.lastStop)
1098
+ mark(svg.lastStop, 0, height, true);
1099
+ }
1100
+ else if (from === to || to > last + 1) {
1101
+ svg.lastStop = stops[Math.min(from, last)];
1102
+ mark(svg.lastStop, 0, height, true);
1103
+ }
1104
+ else {
1105
+ for (let index = from; index < to && index < last; index++) {
1106
+ const stop = stops[index];
1107
+ const previous = stops[index - 1];
1108
+ if (stop.w > 0 && !(index > from && previous && stop.x === previous.x && stop.y === previous.y))
1109
+ mark(stop, stop.w, height, false);
1110
+ }
1111
+ svg.lastStop = stops[Math.min(to, last)];
1112
+ }
1113
+ }
1114
+ for (let index = used; index < svg.marks.length; index++)
1115
+ svg.marks[index].style.display = 'none';
1116
+ }
1117
+ onSvgText(event) {
1118
+ const svg = this.session?.svg;
1119
+ const target = event.target;
1120
+ if (!svg || !target)
1121
+ return false;
1122
+ if (svg.svg.contains(target))
1123
+ return true;
1124
+ if (!(target instanceof SVGElement) || (target.ownerSVGElement ?? target) !== svg.svg.ownerSVGElement)
1125
+ return false;
1126
+ const pad = (parseFloat(getComputedStyle(svg.svg).fontSize) || 16) * svgScale(svg.svg);
1127
+ const rect = svg.svg.getBoundingClientRect();
1128
+ return event.clientX >= rect.left - pad && event.clientX <= rect.right + pad && event.clientY >= rect.top - pad && event.clientY <= rect.bottom + pad;
1129
+ }
1130
+ /** A press on the drawn text places the caret there; three select it all. */
1131
+ svgPointerDown(event) {
1132
+ const session = this.session;
1133
+ const svg = session?.svg;
1134
+ if (!svg || !this.onSvgText(event))
1135
+ return;
1136
+ event.preventDefault();
1137
+ event.stopPropagation();
1138
+ if (event.button !== 0)
1139
+ return;
1140
+ const field = session.element;
1141
+ if (event.detail >= 3) {
1142
+ svg.anchor = null;
1143
+ selectInField(field, 0, (field.textContent ?? '').length);
1144
+ this.drawSvgMarks();
1145
+ return;
1146
+ }
1147
+ const at = nearestStop(svg.svg, event.clientX, event.clientY);
1148
+ const [anchor] = fieldSelection(field);
1149
+ svg.down = { x: event.clientX, y: event.clientY, moved: false };
1150
+ svg.anchor = event.shiftKey ? anchor : at;
1151
+ selectInField(field, svg.anchor, at);
1152
+ this.drawSvgMarks();
1153
+ }
1154
+ /** Dragging over the drawn text selects. */
1155
+ svgPointerMove(event) {
1156
+ const session = this.session;
1157
+ const svg = session?.svg;
1158
+ if (!svg || svg.anchor === null)
1159
+ return;
1160
+ if (!(event.buttons & 1)) {
1161
+ svg.anchor = null;
1162
+ return;
1163
+ }
1164
+ if (svg.down && Math.abs(event.clientX - svg.down.x) + Math.abs(event.clientY - svg.down.y) > 4)
1165
+ svg.down.moved = true;
1166
+ selectInField(session.element, svg.anchor, nearestStop(svg.svg, event.clientX, event.clientY));
1167
+ this.drawSvgMarks();
1168
+ }
1169
+ /** A double-click on the drawn text selects the word there. */
1170
+ svgSelectWord(event) {
1171
+ const session = this.session;
1172
+ const svg = session?.svg;
1173
+ if (!svg || svg.down?.moved)
1174
+ return;
1175
+ const text = session.element.textContent ?? '';
1176
+ const at = nearestStop(svg.svg, event.clientX, event.clientY);
1177
+ let from = at;
1178
+ let to = at;
1179
+ while (from > 0 && /\S/.test(text.charAt(from - 1)))
1180
+ from--;
1181
+ while (to < text.length && /\S/.test(text.charAt(to)))
1182
+ to++;
1183
+ selectInField(session.element, from, to);
1184
+ this.drawSvgMarks();
1185
+ }
1186
+ askLink(session) {
1187
+ const root = session.element;
1188
+ const selection = getSelection();
1189
+ let link = elementOf(selection?.anchorNode ?? null)?.closest('a');
1190
+ if (!link && selection && selection.rangeCount > 0)
1191
+ link = linkAt(selection.getRangeAt(0), root);
1192
+ if (link && !root.contains(link))
1193
+ link = null;
1194
+ let rect = null;
1195
+ let collapsed = true;
1196
+ if (selection && selection.rangeCount > 0) {
1197
+ const range = selection.getRangeAt(0);
1198
+ session.linkRange = range.cloneRange();
1199
+ collapsed = range.collapsed;
1200
+ rect = TextEditor.rectOf(range);
1201
+ }
1202
+ if ((!rect || (!rect.width && !rect.height)) && link)
1203
+ rect = TextEditor.rectOf(link);
1204
+ if (!rect || (!rect.width && !rect.height))
1205
+ rect = TextEditor.rectOf(root);
1206
+ // A caret in a link edits that link.
1207
+ if (link && session.linkRange?.collapsed)
1208
+ session.linkRange.selectNode(link);
1209
+ if (link === root) {
1210
+ // The edited element is the link: its own address (an attribute of the template element).
1211
+ session.linkRange = null;
1212
+ this.report({ type: 'link-edit', href: link.getAttribute('href') ?? '', collapsed: false, rect: TextEditor.rectOf(root), host: true });
1213
+ return;
1214
+ }
1215
+ this.report({ type: 'link-edit', href: link?.getAttribute('href') ?? '', collapsed: collapsed && !link, rect });
1216
+ }
1217
+ }
1218
+ const FORMATS = {
1219
+ bold: () => document.execCommand('bold'),
1220
+ italic: () => document.execCommand('italic'),
1221
+ underline: (editor, session) => {
1222
+ const selection = getSelection();
1223
+ const range = selection && selection.rangeCount > 0 ? selection.getRangeAt(0) : null;
1224
+ const links = [];
1225
+ if (range) {
1226
+ if (session.element.tagName === 'A')
1227
+ links.push(session.element);
1228
+ for (const link of Array.from(session.element.querySelectorAll('a')))
1229
+ if (range.intersectsNode(link))
1230
+ links.push(link);
1231
+ }
1232
+ const link = editor.selectedLink(session);
1233
+ const on = link ? !(getComputedStyle(link).textDecorationLine || '').includes('underline') : !document.queryCommandState('underline');
1234
+ document.execCommand('underline');
1235
+ if (document.queryCommandState('underline') !== on)
1236
+ document.execCommand('underline');
1237
+ // A link's own underline is its style, not a <u>.
1238
+ for (const each of links) {
1239
+ const lines = (getComputedStyle(each).textDecorationLine || '').split(/\s+/).filter((line) => line && line !== 'none');
1240
+ const has = lines.includes('underline');
1241
+ if (on && !has)
1242
+ lines.push('underline');
1243
+ if (!on && has)
1244
+ lines.splice(lines.indexOf('underline'), 1);
1245
+ each.style.textDecorationLine = lines.length ? lines.join(' ') : 'none';
1246
+ }
1247
+ },
1248
+ ul: () => document.execCommand('insertUnorderedList'),
1249
+ ol: () => document.execCommand('insertOrderedList'),
1250
+ link: (editor, session) => editor.askLink(session),
1251
+ };