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