@und-ui/richtext 0.0.0-stage → 0.3.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,1124 @@
1
+ /* Visual design ported from Astryx (MIT, (c) Meta Platforms, Inc.); see THIRD_PARTY_NOTICES.md */
2
+ import { html, nothing, svg, type PropertyValues, type TemplateResult } from 'lit';
3
+ import { UndElement } from '@und-ui/core/base/UndElement';
4
+ import { LocaleDirController } from '@und-ui/core/controllers/locale-dir';
5
+ import { isServer } from '@und-ui/core/utils/ssr-safe';
6
+ import {
7
+ cleanHref,
8
+ sanitizeHtml,
9
+ sanitizeNode,
10
+ textToFragment,
11
+ toHtml,
12
+ toMarkdown,
13
+ } from '../../sanitize.js';
14
+ import { contentStyles, editorStyles } from './rich-text-editor.styles.js';
15
+
16
+ export interface RichTextStrings {
17
+ toolbar: string;
18
+ bold: string;
19
+ italic: string;
20
+ underline: string;
21
+ strike: string;
22
+ code: string;
23
+ link: string;
24
+ heading2: string;
25
+ heading3: string;
26
+ bulletList: string;
27
+ numberedList: string;
28
+ quote: string;
29
+ linkUrl: string;
30
+ apply: string;
31
+ removeLink: string;
32
+ cancel: string;
33
+ invalidUrl: string;
34
+ required: string;
35
+ }
36
+
37
+ const strings: RichTextStrings = {
38
+ toolbar: 'Formatting',
39
+ bold: 'Bold',
40
+ italic: 'Italic',
41
+ underline: 'Underline',
42
+ strike: 'Strikethrough',
43
+ code: 'Code',
44
+ link: 'Link',
45
+ heading2: 'Heading',
46
+ heading3: 'Subheading',
47
+ bulletList: 'Bulleted list',
48
+ numberedList: 'Numbered list',
49
+ quote: 'Quote',
50
+ linkUrl: 'Link address',
51
+ apply: 'Apply',
52
+ removeLink: 'Remove link',
53
+ cancel: 'Cancel',
54
+ invalidUrl: 'Enter a web address such as https://example.com',
55
+ required: 'Enter some text.',
56
+ };
57
+
58
+ /** Replaces some built-in English strings of `und-rich-text-editor`. Unknown keys and non-strings are ignored. */
59
+ export function setRichTextStrings(next: Partial<RichTextStrings>): void {
60
+ for (const key of Object.keys(strings) as (keyof RichTextStrings)[]) {
61
+ const value: unknown = Object.hasOwn(next, key) ? next[key] : undefined;
62
+ if (typeof value === 'string') strings[key] = value;
63
+ }
64
+ }
65
+
66
+ type Tool =
67
+ | 'bold'
68
+ | 'italic'
69
+ | 'underline'
70
+ | 'strike'
71
+ | 'code'
72
+ | 'link'
73
+ | 'h2'
74
+ | 'h3'
75
+ | 'ul'
76
+ | 'ol'
77
+ | 'quote';
78
+
79
+ // Icon paths from Lucide (ISC licence), 24px grid, 2px stroke.
80
+ const ICONS: Record<Tool, string> = {
81
+ bold: 'M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8',
82
+ italic: 'M19 4h-9M14 20H5M15 4 9 20',
83
+ underline: 'M6 4v6a6 6 0 0 0 12 0V4M4 20h16',
84
+ strike: 'M16 4H9a3 3 0 0 0-2.83 4M14 12a4 4 0 0 1 0 8H6M4 12h16',
85
+ code: 'm16 18 6-6-6-6M8 6l-6 6 6 6',
86
+ link: 'M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71',
87
+ h2: 'M4 12h8M4 18V6M12 18V6M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1',
88
+ h3: 'M4 12h8M4 18V6M12 18V6M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2',
89
+ ul: 'M3 12h.01M3 18h.01M3 6h.01M8 12h13M8 18h13M8 6h13',
90
+ ol: 'M10 12h11M10 18h11M10 6h11M4 10h2M4 6h1v4M6 18H4c0-1 2-2 2-3s-1-1.5-2-1',
91
+ quote:
92
+ 'M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2zM5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z',
93
+ };
94
+
95
+ /** Toolbar groups, separated visually. */
96
+ const GROUPS: Tool[][] = [
97
+ ['bold', 'italic', 'underline', 'strike', 'code'],
98
+ ['link'],
99
+ ['h2', 'h3', 'quote'],
100
+ ['ul', 'ol'],
101
+ ];
102
+
103
+ const LABEL: Record<Tool, keyof RichTextStrings> = {
104
+ bold: 'bold',
105
+ italic: 'italic',
106
+ underline: 'underline',
107
+ strike: 'strike',
108
+ code: 'code',
109
+ link: 'link',
110
+ h2: 'heading2',
111
+ h3: 'heading3',
112
+ ul: 'bulletList',
113
+ ol: 'numberedList',
114
+ quote: 'quote',
115
+ };
116
+
117
+ const SHORTCUT: Partial<Record<Tool, string>> = {
118
+ bold: 'Control+B',
119
+ italic: 'Control+I',
120
+ underline: 'Control+U',
121
+ strike: 'Control+Shift+X',
122
+ code: 'Control+E',
123
+ link: 'Control+K',
124
+ };
125
+
126
+ const INLINE_TAG: Partial<Record<Tool, string>> = {
127
+ bold: 'strong,b',
128
+ italic: 'em,i',
129
+ underline: 'u',
130
+ strike: 's,strike,del',
131
+ code: 'code',
132
+ link: 'a',
133
+ };
134
+
135
+ /** Block shortcuts typed at the start of a paragraph, then a space. */
136
+ const BLOCK_SHORTCUTS: [RegExp, Tool | 'pre'][] = [
137
+ [/^#{1,2}$/, 'h2'],
138
+ [/^#{3,6}$/, 'h3'],
139
+ [/^[-*+]$/, 'ul'],
140
+ [/^1[.)]$/, 'ol'],
141
+ [/^>$/, 'quote'],
142
+ [/^```$/, 'pre'],
143
+ ];
144
+
145
+ /** Inline shortcuts completed by their closing mark. */
146
+ const INLINE_SHORTCUTS: [RegExp, string][] = [
147
+ [/\*\*([^*\s](?:[^*]*[^*\s])?)\*\*$/, 'strong'],
148
+ [/~~([^~\s](?:[^~]*[^~\s])?)~~$/, 's'],
149
+ [/`([^`]+)`$/, 'code'],
150
+ [/(?:^|[^*\w])\*([^*\s](?:[^*]*[^*\s])?)\*$/, 'em'],
151
+ [/(?:^|\W)_([^_\s](?:[^_]*[^_\s])?)_$/, 'em'],
152
+ ];
153
+
154
+ const URL_AT_END = /(?:https?:\/\/|www\.)[^\s<>"]+$/i;
155
+
156
+ let counter = 0;
157
+
158
+ /**
159
+ * A small rich text editor: a formatting toolbar (bold, italic, underline,
160
+ * strikethrough, inline code, link, headings, quote, lists), Markdown
161
+ * shortcuts as you type (`## `, `- `, `1. `, `> `, `**bold**`, `` `code` ``),
162
+ * autolinked URLs and native undo.
163
+ *
164
+ * Security first: pasted, dropped and assigned HTML goes through an
165
+ * allowlist sanitizer that rebuilds clean nodes (no HTML-string sinks, safe
166
+ * link URLs only, Trusted Types friendly), and `value` is always sanitized
167
+ * HTML. The editable area is light DOM (ADR 0002), so selection, spell
168
+ * checking and assistive technology work as in a plain contenteditable.
169
+ *
170
+ * Form-associated: submits the sanitized HTML under `name`, and the Markdown
171
+ * under `markdown-name` when set.
172
+ *
173
+ * @summary A small, security-first rich text editor with Markdown shortcuts.
174
+ * @tag und-rich-text-editor
175
+ *
176
+ * @csspart toolbar - The formatting toolbar.
177
+ * @csspart button - Each toolbar button.
178
+ * @csspart link-form - The link address form.
179
+ *
180
+ * @cssprop [--und-rich-text-min-height] - Minimum block size of the editing area (default 8rem).
181
+ * @cssprop [--und-rich-text-max-height] - Maximum block size before the editing area scrolls.
182
+ *
183
+ * @fires input - The content changed.
184
+ * @fires change - The content changed and the editor lost focus.
185
+ */
186
+ export class UndRichTextEditor extends UndElement {
187
+ static override tagName = 'und-rich-text-editor';
188
+ static formAssociated = true;
189
+ static override styles = editorStyles;
190
+
191
+ static override properties = {
192
+ label: {},
193
+ placeholder: {},
194
+ name: { reflect: true },
195
+ markdownName: { attribute: 'markdown-name' },
196
+ value: { noAccessor: true },
197
+ disabled: { type: Boolean, reflect: true },
198
+ readOnly: { type: Boolean, attribute: 'readonly', reflect: true },
199
+ required: { type: Boolean, reflect: true },
200
+ noToolbar: { type: Boolean, attribute: 'no-toolbar' },
201
+ };
202
+
203
+ /**
204
+ * Accessible name (and visible label) of the editing area.
205
+ * @attr label
206
+ */
207
+ declare label: string | undefined;
208
+
209
+ /**
210
+ * Text shown while the editor is empty.
211
+ * @attr placeholder
212
+ */
213
+ declare placeholder: string | undefined;
214
+
215
+ /**
216
+ * Form field name for the sanitized HTML.
217
+ * @attr name
218
+ */
219
+ declare name: string | undefined;
220
+
221
+ /**
222
+ * Form field name for the Markdown version (optional).
223
+ * @attr markdown-name
224
+ */
225
+ declare markdownName: string | undefined;
226
+
227
+ /**
228
+ * Disables editing and the toolbar. A disabled ancestor fieldset also disables it.
229
+ * @attr disabled
230
+ */
231
+ declare disabled: boolean;
232
+
233
+ /**
234
+ * Shows the content without allowing edits.
235
+ * @attr readonly
236
+ */
237
+ declare readOnly: boolean;
238
+
239
+ /**
240
+ * Requires some text before the form submits.
241
+ * @attr required
242
+ */
243
+ declare required: boolean;
244
+
245
+ /**
246
+ * Hides the toolbar (keyboard shortcuts and Markdown shortcuts still work).
247
+ * @attr no-toolbar
248
+ */
249
+ declare noToolbar: boolean;
250
+
251
+ #editor: HTMLElement | undefined;
252
+ #labelEl: HTMLElement | undefined;
253
+ #value = '';
254
+ #default: string | undefined;
255
+ #range: Range | undefined;
256
+ #escape: Node | undefined;
257
+ #active = new Set<Tool>();
258
+ #linkOpen = false;
259
+ #linkError = false;
260
+ #focusIndex = 0;
261
+ #changedSinceFocus = false;
262
+ #fieldsetDisabled = false;
263
+ readonly #id = `und-rte-${++counter}`;
264
+ readonly #locale = new LocaleDirController(this);
265
+
266
+ constructor() {
267
+ super();
268
+ this.disabled = false;
269
+ this.readOnly = false;
270
+ this.required = false;
271
+ this.noToolbar = false;
272
+ }
273
+
274
+ /**
275
+ * The content as sanitized HTML. Setting it sanitizes the input (never
276
+ * trust it), so assigning user or server HTML is safe.
277
+ * @attr value
278
+ */
279
+ get value(): string {
280
+ return this.#editor ? this.#serialize().html : this.#value;
281
+ }
282
+
283
+ set value(next: string | null | undefined) {
284
+ const value = next ?? '';
285
+ // The first value (attribute or property) is what form reset restores.
286
+ this.#default ??= value;
287
+ this.#value = value;
288
+ // A framework writing back the value it just read (v-model, controlled React)
289
+ // must not reload the content, or the caret jumps to the start.
290
+ if (this.#editor && value !== this.#serialize().html) this.#load(value);
291
+ }
292
+
293
+ /** The content as Markdown (CommonMark plus `~~strikethrough~~`). */
294
+ get markdown(): string {
295
+ return this.#serialize().markdown;
296
+ }
297
+
298
+ /** The form the editor belongs to. */
299
+ get form(): HTMLFormElement | null {
300
+ return isServer ? null : this.internals.form;
301
+ }
302
+
303
+ /** The editable element (light DOM). */
304
+ get editor(): HTMLElement | undefined {
305
+ return this.#editor;
306
+ }
307
+
308
+ override focus(options?: FocusOptions): void {
309
+ this.#editor?.focus(options);
310
+ }
311
+
312
+ override connectedCallback(): void {
313
+ super.connectedCallback();
314
+ if (isServer) return;
315
+ adoptContentStyles(this);
316
+ if (!this.#editor) this.#build();
317
+ document.addEventListener('selectionchange', this.#onSelectionChange);
318
+ }
319
+
320
+ override disconnectedCallback(): void {
321
+ super.disconnectedCallback();
322
+ document.removeEventListener('selectionchange', this.#onSelectionChange);
323
+ }
324
+
325
+ #build(): void {
326
+ const label = document.createElement('div');
327
+ label.className = 'und-rte__label';
328
+ label.id = `${this.#id}-label`;
329
+ label.slot = 'label';
330
+ label.addEventListener('click', () => this.focus());
331
+ const editor = document.createElement('div');
332
+ editor.className = 'und-rte__content';
333
+ editor.id = `${this.#id}-content`;
334
+ editor.setAttribute('role', 'textbox');
335
+ editor.setAttribute('aria-multiline', 'true');
336
+ editor.setAttribute('aria-labelledby', label.id);
337
+ editor.addEventListener('beforeinput', this.#onBeforeInput);
338
+ editor.addEventListener('input', this.#onInput);
339
+ editor.addEventListener('keydown', this.#onEditorKeydown);
340
+ editor.addEventListener('paste', this.#onPaste);
341
+ editor.addEventListener('drop', this.#onDrop);
342
+ editor.addEventListener('focus', this.#onFocus);
343
+ editor.addEventListener('blur', this.#onBlur);
344
+ // Existing children are author content: keep their safe parts as the initial value.
345
+ const initial = this.hasChildNodes() && !this.#value ? sanitizeNode(this) : undefined;
346
+ this.replaceChildren(label, editor);
347
+ this.#labelEl = label;
348
+ this.#editor = editor;
349
+ if (initial) {
350
+ editor.append(initial);
351
+ this.#default ??= this.#serialize().html;
352
+ this.#afterChange(false);
353
+ } else this.#load(this.#value);
354
+ }
355
+
356
+ #load(value: string): void {
357
+ const editor = this.#editor;
358
+ if (!editor) return;
359
+ editor.replaceChildren(sanitizeHtml(value));
360
+ this.#afterChange(false);
361
+ }
362
+
363
+ #serialize(): { html: string; markdown: string } {
364
+ if (!this.#editor) {
365
+ const clean = sanitizeHtml(this.#value);
366
+ return { html: toHtml(clean), markdown: toMarkdown(clean) };
367
+ }
368
+ const clean = sanitizeNode(this.#editor);
369
+ if ((this.#editor.textContent ?? '').trim() === '') return { html: '', markdown: '' };
370
+ return { html: toHtml(clean), markdown: toMarkdown(clean) };
371
+ }
372
+
373
+ protected override updated(changed: PropertyValues<this>): void {
374
+ const editor = this.#editor;
375
+ if (!editor || !this.#labelEl) return;
376
+ const off = this.disabled || this.#fieldsetDisabled;
377
+ editor.contentEditable = off || this.readOnly ? 'false' : 'true';
378
+ editor.tabIndex = off ? -1 : 0;
379
+ editor.toggleAttribute('aria-disabled', off);
380
+ if (off) editor.setAttribute('aria-disabled', 'true');
381
+ editor.toggleAttribute('aria-readonly', this.readOnly);
382
+ if (this.readOnly) editor.setAttribute('aria-readonly', 'true');
383
+ editor.toggleAttribute('aria-required', this.required);
384
+ if (this.required) editor.setAttribute('aria-required', 'true');
385
+ if (this.placeholder) {
386
+ editor.setAttribute('aria-placeholder', this.placeholder);
387
+ editor.dataset.placeholder = this.placeholder;
388
+ } else {
389
+ editor.removeAttribute('aria-placeholder');
390
+ delete editor.dataset.placeholder;
391
+ }
392
+ this.#labelEl.textContent = this.label ?? '';
393
+ this.#labelEl.hidden = !this.label;
394
+ if (!this.label) editor.removeAttribute('aria-labelledby');
395
+ else editor.setAttribute('aria-labelledby', this.#labelEl.id);
396
+ if (
397
+ changed.has('required') ||
398
+ changed.has('name') ||
399
+ changed.has('markdownName') ||
400
+ !this.hasUpdated
401
+ ) {
402
+ this.#syncForm();
403
+ }
404
+ const buttons = this.#buttons();
405
+ buttons.forEach((b, i) => (b.tabIndex = i === this.#focusIndex ? 0 : -1));
406
+ }
407
+
408
+ // ------------------------------------------------------------ form
409
+
410
+ #syncForm(): void {
411
+ if (isServer) return;
412
+ const { html: value, markdown } = this.#serialize();
413
+ if (this.markdownName && this.name) {
414
+ const data = new FormData();
415
+ data.append(this.name, value);
416
+ data.append(this.markdownName, markdown);
417
+ this.internals.setFormValue(data, value);
418
+ } else this.internals.setFormValue(value);
419
+ if (this.required && value === '') {
420
+ this.internals.setValidity({ valueMissing: true }, strings.required, this.#editor);
421
+ } else this.internals.setValidity({});
422
+ }
423
+
424
+ formResetCallback(): void {
425
+ this.value = this.#default ?? '';
426
+ }
427
+
428
+ formDisabledCallback(disabled: boolean): void {
429
+ this.#fieldsetDisabled = disabled;
430
+ this.requestUpdate();
431
+ }
432
+
433
+ formStateRestoreCallback(state: string | FormData | null): void {
434
+ if (typeof state === 'string') this.value = state;
435
+ else if (state && this.name) {
436
+ const html = state.get(this.name);
437
+ if (typeof html === 'string') this.value = html;
438
+ }
439
+ }
440
+
441
+ /** Whether the editor's value satisfies its constraints. */
442
+ checkValidity(): boolean {
443
+ return this.internals.checkValidity();
444
+ }
445
+
446
+ /** Like `checkValidity()`, and shows the browser's message when invalid. */
447
+ reportValidity(): boolean {
448
+ return this.internals.reportValidity();
449
+ }
450
+
451
+ // --------------------------------------------------------- editing
452
+
453
+ #afterChange(user: boolean): void {
454
+ const editor = this.#editor;
455
+ if (!editor) return;
456
+ this.#unnest(editor);
457
+ // Typing needs a paragraph to type into (not the bare editing host).
458
+ if (!editor.firstElementChild && editor.textContent === '') {
459
+ const p = document.createElement('p');
460
+ p.appendChild(document.createElement('br'));
461
+ editor.appendChild(p);
462
+ }
463
+ editor.toggleAttribute('data-empty', this.#isEmpty());
464
+ this.#syncForm();
465
+ if (user) {
466
+ this.#changedSinceFocus = true;
467
+ this.dispatchEvent(new Event('input', { bubbles: true, composed: true }));
468
+ }
469
+ }
470
+
471
+ /** Lifts lists, quotes and code blocks that an engine nested inside a paragraph or heading. */
472
+ #unnest(editor: HTMLElement): void {
473
+ const nested = editor.querySelectorAll(
474
+ ':scope > :is(p,h2,h3):has(> :is(ul,ol,blockquote,pre,p))',
475
+ );
476
+ if (nested.length === 0) return;
477
+ const range = this.#selectionRange();
478
+ const at = range && ([range.startContainer, range.startOffset] as const);
479
+ for (const block of nested) {
480
+ for (const child of [...block.childNodes]) {
481
+ const tag = child.nodeName;
482
+ const empty =
483
+ tag === 'BR' || (child.nodeType === 3 && (child.textContent ?? '').trim() === '');
484
+ if (empty) child.remove();
485
+ }
486
+ block.replaceWith(...block.childNodes);
487
+ }
488
+ if (at && at[0].isConnected) {
489
+ const r = document.createRange();
490
+ r.setStart(
491
+ at[0],
492
+ Math.min(at[1], at[0].nodeType === 3 ? (at[0] as Text).length : at[0].childNodes.length),
493
+ );
494
+ sel(r);
495
+ }
496
+ }
497
+
498
+ #isEmpty(): boolean {
499
+ const editor = this.#editor;
500
+ if (!editor || (editor.textContent ?? '') !== '') return false;
501
+ return !editor.querySelector('li,blockquote,pre,h2,h3');
502
+ }
503
+
504
+ #selectionRange(): Range | undefined {
505
+ const sel = document.getSelection();
506
+ if (!sel || sel.rangeCount === 0 || !this.#editor) return undefined;
507
+ const range = sel.getRangeAt(0);
508
+ return this.#editor.contains(range.commonAncestorContainer) ? range : undefined;
509
+ }
510
+
511
+ #onSelectionChange = (): void => {
512
+ const range = this.#selectionRange();
513
+ if (!range) return;
514
+ this.#range = range.cloneRange();
515
+ const active = this.#activeTools(range);
516
+ const same = active.size === this.#active.size && [...active].every((t) => this.#active.has(t));
517
+ if (!same) {
518
+ this.#active = active;
519
+ this.requestUpdate();
520
+ }
521
+ };
522
+
523
+ #activeTools(range: Range): Set<Tool> {
524
+ const active = new Set<Tool>();
525
+ const start =
526
+ range.startContainer.nodeType === 1
527
+ ? (range.startContainer as Element)
528
+ : range.startContainer.parentElement;
529
+ if (!start || !this.#editor) return active;
530
+ for (const [tool, selector] of Object.entries(INLINE_TAG) as [Tool, string][]) {
531
+ const hit = start.closest(selector);
532
+ if (hit && this.#editor.contains(hit)) active.add(tool);
533
+ }
534
+ const block = this.#blockOf(start);
535
+ const tag = block?.localName;
536
+ if (tag === 'h2' || tag === 'h3') active.add(tag);
537
+ const list = start.closest('ul,ol');
538
+ if (list && this.#editor.contains(list)) active.add(list.localName as Tool);
539
+ const quote = start.closest('blockquote');
540
+ if (quote && this.#editor.contains(quote)) active.add('quote');
541
+ return active;
542
+ }
543
+
544
+ /** The editor's direct child that contains `node`. */
545
+ #blockOf(node: Node | null): HTMLElement | undefined {
546
+ let n = node;
547
+ while (n && n.parentNode !== this.#editor) n = n.parentNode;
548
+ return (n ?? undefined) as HTMLElement | undefined;
549
+ }
550
+
551
+ #restore(): Range | undefined {
552
+ const editor = this.#editor;
553
+ if (!editor) return undefined;
554
+ editor.focus({ preventScroll: true });
555
+ const sel = document.getSelection();
556
+ if (this.#range && editor.contains(this.#range.commonAncestorContainer) && sel) {
557
+ sel.removeAllRanges();
558
+ sel.addRange(this.#range);
559
+ }
560
+ return this.#selectionRange();
561
+ }
562
+
563
+ // execCommand is deprecated but is the only way to keep the native undo stack.
564
+ #exec(command: string, value?: string): void {
565
+ document.execCommand(command, false, value);
566
+ }
567
+
568
+ /** Runs a toolbar action. */
569
+ #apply(tool: Tool): void {
570
+ if (this.disabled || this.readOnly || this.#fieldsetDisabled) return;
571
+ if (tool === 'link') {
572
+ this.#openLink();
573
+ return;
574
+ }
575
+ const range = this.#restore();
576
+ if (!range) return;
577
+ document.execCommand('defaultParagraphSeparator', false, 'p');
578
+ const active = this.#activeTools(range);
579
+ switch (tool) {
580
+ case 'bold':
581
+ case 'italic':
582
+ case 'underline':
583
+ this.#exec(tool);
584
+ break;
585
+ case 'strike':
586
+ this.#exec('strikeThrough');
587
+ break;
588
+ case 'code':
589
+ this.#toggleCode(range);
590
+ break;
591
+ case 'h2':
592
+ case 'h3':
593
+ case 'quote': {
594
+ const tag = tool === 'quote' ? 'blockquote' : tool;
595
+ if (tool === 'quote' && active.has('quote')) this.#exec('outdent');
596
+ this.#exec('formatBlock', active.has(tool) ? '<p>' : `<${tag}>`);
597
+ break;
598
+ }
599
+ case 'ul':
600
+ this.#exec('insertUnorderedList');
601
+ break;
602
+ case 'ol':
603
+ this.#exec('insertOrderedList');
604
+ break;
605
+ }
606
+ this.#afterChange(true);
607
+ this.#onSelectionChange();
608
+ }
609
+
610
+ #toggleCode(range: Range): void {
611
+ const start =
612
+ range.startContainer.nodeType === 1
613
+ ? (range.startContainer as Element)
614
+ : range.startContainer.parentElement;
615
+ const code = start?.closest('code');
616
+ if (code && this.#editor?.contains(code)) {
617
+ code.replaceWith(...code.childNodes);
618
+ return;
619
+ }
620
+ if (range.collapsed) return;
621
+ const el = document.createElement('code');
622
+ el.textContent = range.toString();
623
+ range.deleteContents();
624
+ range.insertNode(el);
625
+ this.#select(el);
626
+ }
627
+
628
+ #select(node: Node, collapseToEnd = false): void {
629
+ const sel = document.getSelection();
630
+ if (!sel) return;
631
+ const r = document.createRange();
632
+ r.selectNodeContents(node);
633
+ if (collapseToEnd) r.collapse(false);
634
+ sel.removeAllRanges();
635
+ sel.addRange(r);
636
+ this.#range = r.cloneRange();
637
+ }
638
+
639
+ // ----------------------------------------------------------- links
640
+
641
+ #openLink(): void {
642
+ const range = this.#selectionRange() ?? this.#range;
643
+ if (range) this.#range = range.cloneRange();
644
+ this.#linkOpen = true;
645
+ this.#linkError = false;
646
+ this.requestUpdate();
647
+ void this.updateComplete.then(() => {
648
+ const input = this.renderRoot.querySelector<HTMLInputElement>('.link-input');
649
+ if (!input) return;
650
+ const start = range?.startContainer;
651
+ const a = (start?.nodeType === 1 ? (start as Element) : start?.parentElement)?.closest('a');
652
+ input.value = a && this.#editor?.contains(a) ? (a.getAttribute('href') ?? '') : '';
653
+ input.focus();
654
+ input.select();
655
+ });
656
+ }
657
+
658
+ #closeLink(refocus = true): void {
659
+ this.#linkOpen = false;
660
+ this.#linkError = false;
661
+ this.requestUpdate();
662
+ if (refocus) this.#restore();
663
+ }
664
+
665
+ #applyLink(raw: string): void {
666
+ const href = cleanHref(raw);
667
+ if (!href) {
668
+ this.#linkError = true;
669
+ this.requestUpdate();
670
+ return;
671
+ }
672
+ this.#closeLink();
673
+ const range = this.#selectionRange();
674
+ if (!range) return;
675
+ const existing = this.#linkAt(range);
676
+ if (existing) existing.setAttribute('href', href);
677
+ else if (range.collapsed) {
678
+ const a = document.createElement('a');
679
+ a.href = href;
680
+ a.textContent = raw.trim();
681
+ range.insertNode(a);
682
+ this.#caretAfter(a);
683
+ } else this.#exec('createLink', href);
684
+ this.#afterChange(true);
685
+ }
686
+
687
+ #removeLink(): void {
688
+ this.#closeLink();
689
+ const range = this.#selectionRange();
690
+ const a = range && this.#linkAt(range);
691
+ if (a) {
692
+ a.replaceWith(...a.childNodes);
693
+ this.#afterChange(true);
694
+ }
695
+ }
696
+
697
+ #linkAt(range: Range): HTMLAnchorElement | undefined {
698
+ const start = range.startContainer;
699
+ const a = (start.nodeType === 1 ? (start as Element) : start.parentElement)?.closest('a');
700
+ return a && this.#editor?.contains(a) ? a : undefined;
701
+ }
702
+
703
+ /** Puts the caret after an inline element; the next typed text goes outside it. */
704
+ #caretAfter(node: Node): void {
705
+ this.#placeAfter(node);
706
+ this.#escape = node;
707
+ }
708
+
709
+ /** Whether the caret sits right after `node` (or at its very end), with nothing in between. */
710
+ #atBoundary(node: Node, range: Range): boolean {
711
+ if (!range.collapsed || !node.parentNode) return false;
712
+ const probe = document.createRange();
713
+ try {
714
+ if (node.contains(range.startContainer)) {
715
+ probe.setStart(range.startContainer, range.startOffset);
716
+ probe.setEndAfter(node);
717
+ } else {
718
+ probe.setStartAfter(node);
719
+ probe.setEnd(range.startContainer, range.startOffset);
720
+ if (probe.collapsed && range.compareBoundaryPoints(Range.START_TO_START, probe) !== 0)
721
+ return false;
722
+ }
723
+ } catch {
724
+ return false;
725
+ }
726
+ return probe.toString() === '';
727
+ }
728
+
729
+ // ---------------------------------------------------------- events
730
+
731
+ #onFocus = (): void => {
732
+ this.#changedSinceFocus = false;
733
+ document.execCommand('defaultParagraphSeparator', false, 'p');
734
+ };
735
+
736
+ #onBlur = (): void => {
737
+ if (!this.#changedSinceFocus) return;
738
+ // Focus moving into the toolbar or link form is still "in" the editor.
739
+ queueMicrotask(() => {
740
+ if (this.matches(':focus-within')) return;
741
+ this.#changedSinceFocus = false;
742
+ this.dispatchEvent(new Event('change', { bubbles: true }));
743
+ });
744
+ };
745
+
746
+ #onBeforeInput = (event: InputEvent): void => {
747
+ const escape = this.#escape;
748
+ this.#escape = undefined;
749
+ const range = this.#selectionRange();
750
+ if (escape && event.inputType === 'insertText' && event.data && range) {
751
+ if (this.#atBoundary(escape, range)) {
752
+ // Engines put the caret back inside the element; type after it instead.
753
+ event.preventDefault();
754
+ const text = document.createTextNode(event.data);
755
+ (escape as ChildNode).after(text);
756
+ const r = document.createRange();
757
+ r.setStart(text, text.length);
758
+ sel(r);
759
+ this.#afterChange(true);
760
+ return;
761
+ }
762
+ }
763
+ // Rich content from outside comes only through paste and drop (sanitized
764
+ // there); other ways in (drag of HTML, autocomplete with markup) are
765
+ // limited to plain text.
766
+ if (event.inputType === 'insertFromDrop' || event.inputType === 'insertReplacementText') {
767
+ const text = event.dataTransfer?.getData('text/plain');
768
+ if (text != null && event.dataTransfer?.types.includes('text/html')) {
769
+ event.preventDefault();
770
+ this.#insert(textToFragment(text));
771
+ }
772
+ }
773
+ };
774
+
775
+ #onInput = (event: Event): void => {
776
+ const e = event as InputEvent;
777
+ if (e.inputType === 'insertText' && e.data) {
778
+ if (e.data === ' ') {
779
+ if (this.#blockShortcut()) return;
780
+ this.#autolink(1);
781
+ } else if (/[*_`~]$/.test(e.data)) this.#inlineShortcut();
782
+ }
783
+ this.#afterChange(true);
784
+ };
785
+
786
+ #onEditorKeydown = (event: KeyboardEvent): void => {
787
+ const mod = event.ctrlKey || event.metaKey;
788
+ if (event.key === 'Enter' && !mod) this.#autolink(0);
789
+ if (!mod || event.altKey) return;
790
+ const key = event.key.toLowerCase();
791
+ const tool: Tool | undefined = event.shiftKey
792
+ ? key === 'x'
793
+ ? 'strike'
794
+ : undefined
795
+ : ({ b: 'bold', i: 'italic', u: 'underline', e: 'code', k: 'link' } as Record<string, Tool>)[
796
+ key
797
+ ];
798
+ if (!tool) return;
799
+ event.preventDefault();
800
+ this.#apply(tool);
801
+ };
802
+
803
+ #onPaste = (event: ClipboardEvent): void => {
804
+ const data = event.clipboardData;
805
+ if (!data) return;
806
+ event.preventDefault();
807
+ const markup = data.getData('text/html');
808
+ this.#insert(markup ? sanitizeHtml(markup) : textToFragment(data.getData('text/plain')));
809
+ };
810
+
811
+ #onDrop = (event: DragEvent): void => {
812
+ const data = event.dataTransfer;
813
+ if (!data || (!data.types.includes('text/html') && !data.types.includes('text/plain'))) return;
814
+ event.preventDefault();
815
+ // Move the caret to the drop point first, where the engine supports it.
816
+ const doc = document as Document & {
817
+ caretRangeFromPoint?: (x: number, y: number) => Range | null;
818
+ };
819
+ const at = doc.caretRangeFromPoint?.(event.clientX, event.clientY);
820
+ if (at && this.#editor?.contains(at.startContainer)) {
821
+ const sel = document.getSelection();
822
+ sel?.removeAllRanges();
823
+ sel?.addRange(at);
824
+ }
825
+ const markup = data.getData('text/html');
826
+ this.#insert(markup ? sanitizeHtml(markup) : textToFragment(data.getData('text/plain')));
827
+ };
828
+
829
+ /** Inserts clean content at the caret, splitting the current block when the content has blocks. */
830
+ #insert(fragment: DocumentFragment): void {
831
+ if (this.disabled || this.readOnly) return;
832
+ const range = this.#selectionRange() ?? this.#restore();
833
+ const editor = this.#editor;
834
+ if (!range || !editor) return;
835
+ range.deleteContents();
836
+ const nodes = [...fragment.childNodes];
837
+ const last = nodes.at(-1);
838
+ if (!last) return;
839
+ const single = nodes.length === 1 && nodes[0]?.nodeName === 'P';
840
+ const block = this.#blockOf(range.startContainer);
841
+ if (single || !block || block.localName === 'pre') {
842
+ const inline = document.createDocumentFragment();
843
+ const first = nodes[0];
844
+ const lastInline = single && first ? first.lastChild : last;
845
+ if (single && first) inline.append(...first.childNodes);
846
+ else inline.append(...nodes);
847
+ range.insertNode(inline);
848
+ if (lastInline) this.#placeAfter(lastInline);
849
+ } else {
850
+ // Split the block at the caret and put the new blocks in between.
851
+ const tail = document.createRange();
852
+ tail.setStart(range.startContainer, range.startOffset);
853
+ tail.setEndAfter(block.lastChild ?? block);
854
+ const rest = tail.extractContents();
855
+ const after = document.createElement(block.localName);
856
+ after.append(rest);
857
+ block.after(...nodes);
858
+ if ((after.textContent ?? '') !== '') last.parentNode?.insertBefore(after, last.nextSibling);
859
+ if ((block.textContent ?? '') === '' && !block.querySelector('li')) block.remove();
860
+ this.#select(last, true);
861
+ }
862
+ this.#afterChange(true);
863
+ }
864
+
865
+ #placeAfter(node: Node): void {
866
+ const sel = document.getSelection();
867
+ if (!sel || !node.parentNode) return;
868
+ const r = document.createRange();
869
+ r.setStartAfter(node);
870
+ r.collapse(true);
871
+ sel.removeAllRanges();
872
+ sel.addRange(r);
873
+ }
874
+
875
+ /** `## `, `- `, `1. `, `> ` and ``` at the start of a paragraph. */
876
+ #blockShortcut(): boolean {
877
+ const range = this.#selectionRange();
878
+ if (!range?.collapsed) return false;
879
+ const node = range.startContainer;
880
+ const block = this.#blockOf(node);
881
+ if (node.nodeType !== 3 || !block || block.localName !== 'p') return false;
882
+ if (block.firstChild !== node) return false;
883
+ const typed = (node as Text).data.slice(0, range.startOffset);
884
+ const match = /^(\S+)\s$/.exec(typed);
885
+ const marker = match?.[1];
886
+ const found = marker ? BLOCK_SHORTCUTS.find(([re]) => re.test(marker)) : undefined;
887
+ if (!found) return false;
888
+ const r = document.createRange();
889
+ r.setStart(node, 0);
890
+ r.setEnd(node, range.startOffset);
891
+ const sel = document.getSelection();
892
+ sel?.removeAllRanges();
893
+ sel?.addRange(r);
894
+ this.#exec('delete');
895
+ const tool = found[1];
896
+ if (tool === 'pre') this.#exec('formatBlock', '<pre>');
897
+ else if (tool === 'ul') this.#exec('insertUnorderedList');
898
+ else if (tool === 'ol') this.#exec('insertOrderedList');
899
+ else this.#exec('formatBlock', `<${tool === 'quote' ? 'blockquote' : tool}>`);
900
+ this.#afterChange(true);
901
+ return true;
902
+ }
903
+
904
+ /** `**bold**`, `_italic_`, `~~strike~~` and `` `code` `` when the closing mark is typed. */
905
+ #inlineShortcut(): void {
906
+ const range = this.#selectionRange();
907
+ const node = range?.startContainer;
908
+ if (!range?.collapsed || node?.nodeType !== 3) return;
909
+ const parent = node.parentElement;
910
+ if (parent?.closest('code,pre')) return;
911
+ const before = (node as Text).data.slice(0, range.startOffset);
912
+ for (const [re, tag] of INLINE_SHORTCUTS) {
913
+ const match = re.exec(before);
914
+ const inner = match?.[1];
915
+ if (!match || !inner) continue;
916
+ const full = match[0];
917
+ // Leading context characters of the pattern stay as text.
918
+ const markLen = (full.length - inner.length) / 2;
919
+ const lead = full.length - inner.length - markLen * 2;
920
+ const start = range.startOffset - full.length + Math.max(0, lead);
921
+ const r = document.createRange();
922
+ r.setStart(node, start);
923
+ r.setEnd(node, range.startOffset);
924
+ r.deleteContents();
925
+ const el = document.createElement(tag);
926
+ el.textContent = inner;
927
+ r.insertNode(el);
928
+ this.#caretAfter(el);
929
+ return;
930
+ }
931
+ }
932
+
933
+ /** Links a URL just typed before the caret (`offset` skips the space that triggered it). */
934
+ #autolink(offset: number): void {
935
+ const range = this.#selectionRange();
936
+ const node = range?.startContainer;
937
+ if (!range?.collapsed || node?.nodeType !== 3) return;
938
+ if (node.parentElement?.closest('a,code,pre')) return;
939
+ const end = range.startOffset - offset;
940
+ if (end < 0) return;
941
+ const before = (node as Text).data.slice(0, end);
942
+ const match = URL_AT_END.exec(before);
943
+ if (!match) return;
944
+ const url = match[0].replace(/[.,;:!?)\]'"]+$/, '');
945
+ const href = cleanHref(url);
946
+ if (!href || url.length < 5) return;
947
+ const caret = range.startOffset;
948
+ const r = document.createRange();
949
+ r.setStart(node, match.index);
950
+ r.setEnd(node, match.index + url.length);
951
+ const a = document.createElement('a');
952
+ a.href = href;
953
+ r.surroundContents(a);
954
+ // Put the caret back where it was, after the link.
955
+ const rest = a.nextSibling;
956
+ const sel = document.getSelection();
957
+ if (rest && rest.nodeType === 3 && sel) {
958
+ const c = document.createRange();
959
+ c.setStart(rest, Math.min(caret - match.index - url.length, (rest as Text).length));
960
+ c.collapse(true);
961
+ sel.removeAllRanges();
962
+ sel.addRange(c);
963
+ } else this.#placeAfter(a);
964
+ }
965
+
966
+ // --------------------------------------------------------- toolbar
967
+
968
+ #buttons(): HTMLButtonElement[] {
969
+ return [...this.renderRoot.querySelectorAll<HTMLButtonElement>('.tool')];
970
+ }
971
+
972
+ #onToolbarKeydown = (event: KeyboardEvent): void => {
973
+ const buttons = this.#buttons();
974
+ const index = buttons.indexOf(event.composedPath()[0] as HTMLButtonElement);
975
+ if (index === -1) return;
976
+ const rtl = this.#locale.isRtl;
977
+ let next = -1;
978
+ if (event.key === (rtl ? 'ArrowLeft' : 'ArrowRight')) next = (index + 1) % buttons.length;
979
+ else if (event.key === (rtl ? 'ArrowRight' : 'ArrowLeft'))
980
+ next = (index - 1 + buttons.length) % buttons.length;
981
+ else if (event.key === 'Home') next = 0;
982
+ else if (event.key === 'End') next = buttons.length - 1;
983
+ else if (event.key === 'Escape') {
984
+ event.preventDefault();
985
+ this.#restore();
986
+ return;
987
+ }
988
+ if (next === -1) return;
989
+ event.preventDefault();
990
+ this.#focusIndex = next;
991
+ buttons.forEach((b, i) => (b.tabIndex = i === next ? 0 : -1));
992
+ buttons[next]?.focus();
993
+ };
994
+
995
+ #onLinkKeydown = (event: KeyboardEvent): void => {
996
+ if (event.key === 'Escape') {
997
+ event.preventDefault();
998
+ event.stopPropagation();
999
+ this.#closeLink();
1000
+ } else if (event.key === 'Enter') {
1001
+ event.preventDefault();
1002
+ this.#applyLink((event.target as HTMLInputElement).value);
1003
+ }
1004
+ };
1005
+
1006
+ #renderTool(tool: Tool, index: number): TemplateResult {
1007
+ const name = strings[LABEL[tool]];
1008
+ const pressed = tool === 'link' ? this.#linkOpen : this.#active.has(tool);
1009
+ const off = this.disabled || this.readOnly || this.#fieldsetDisabled;
1010
+ return html`<button
1011
+ type="button"
1012
+ class="tool"
1013
+ part="button"
1014
+ data-tool=${tool}
1015
+ aria-label=${name}
1016
+ aria-pressed=${tool === 'link' ? nothing : String(pressed)}
1017
+ aria-expanded=${tool === 'link' ? String(this.#linkOpen) : nothing}
1018
+ aria-keyshortcuts=${SHORTCUT[tool] ?? nothing}
1019
+ title=${name}
1020
+ ?disabled=${off}
1021
+ ?data-on=${pressed}
1022
+ @mousedown=${(e: MouseEvent) => e.preventDefault()}
1023
+ @click=${() => {
1024
+ this.#focusIndex = index;
1025
+ this.#apply(tool);
1026
+ }}
1027
+ >
1028
+ <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1029
+ ${svg`<path d=${ICONS[tool]}></path>`}
1030
+ </svg>
1031
+ </button>`;
1032
+ }
1033
+
1034
+ #renderLinkForm(): TemplateResult | typeof nothing {
1035
+ if (!this.#linkOpen) return nothing;
1036
+ const errId = `${this.#id}-link-error`;
1037
+ return html`<div class="link-form" part="link-form" role="group" aria-label=${strings.link}>
1038
+ <input
1039
+ class="link-input"
1040
+ type="url"
1041
+ inputmode="url"
1042
+ autocomplete="url"
1043
+ spellcheck="false"
1044
+ placeholder="https://"
1045
+ aria-label=${strings.linkUrl}
1046
+ aria-invalid=${this.#linkError ? 'true' : 'false'}
1047
+ aria-describedby=${this.#linkError ? errId : nothing}
1048
+ @keydown=${this.#onLinkKeydown}
1049
+ />
1050
+ <button
1051
+ type="button"
1052
+ class="text-button primary"
1053
+ @click=${() =>
1054
+ this.#applyLink(
1055
+ this.renderRoot.querySelector<HTMLInputElement>('.link-input')?.value ?? '',
1056
+ )}
1057
+ >
1058
+ ${strings.apply}
1059
+ </button>
1060
+ <button type="button" class="text-button" @click=${() => this.#removeLink()}>
1061
+ ${strings.removeLink}
1062
+ </button>
1063
+ <button type="button" class="text-button" @click=${() => this.#closeLink()}>
1064
+ ${strings.cancel}
1065
+ </button>
1066
+ ${
1067
+ this.#linkError
1068
+ ? html`<p id=${errId} class="link-error" role="alert">${strings.invalidUrl}</p>`
1069
+ : nothing
1070
+ }
1071
+ </div>`;
1072
+ }
1073
+
1074
+ protected override render(): TemplateResult {
1075
+ let index = 0;
1076
+ return html`<slot name="label"></slot>
1077
+ <div class="frame">
1078
+ ${
1079
+ this.noToolbar
1080
+ ? nothing
1081
+ : html`<div
1082
+ class="toolbar"
1083
+ part="toolbar"
1084
+ role="toolbar"
1085
+ aria-label=${strings.toolbar}
1086
+ @keydown=${this.#onToolbarKeydown}
1087
+ >
1088
+ ${GROUPS.map(
1089
+ (group, g) =>
1090
+ html`${g > 0 ? html`<span class="sep" aria-hidden="true"></span>` : nothing}
1091
+ ${group.map((tool) => this.#renderTool(tool, index++))}`,
1092
+ )}
1093
+ </div>`
1094
+ }
1095
+ ${this.#renderLinkForm()}
1096
+ <slot></slot>
1097
+ </div>`;
1098
+ }
1099
+ }
1100
+
1101
+ function sel(range: Range): void {
1102
+ const selection = document.getSelection();
1103
+ selection?.removeAllRanges();
1104
+ selection?.addRange(range);
1105
+ }
1106
+
1107
+ /** Adopts the light-DOM content styles once per tree (document or shadow root). */
1108
+ function adoptContentStyles(host: Element): void {
1109
+ const root = host.getRootNode();
1110
+ const sheet = contentStyles.styleSheet;
1111
+ if (!sheet || !(root instanceof Document || root instanceof ShadowRoot)) return;
1112
+ if (root.adoptedStyleSheets.includes(sheet)) return;
1113
+ try {
1114
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
1115
+ } catch {
1116
+ // A sheet from another document (iframes) cannot be adopted here.
1117
+ }
1118
+ }
1119
+
1120
+ declare global {
1121
+ interface HTMLElementTagNameMap {
1122
+ 'und-rich-text-editor': UndRichTextEditor;
1123
+ }
1124
+ }