@quickbuilder.io/rich-text 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -2
  3. package/adapters.d.ts +1 -0
  4. package/adapters.js +1 -0
  5. package/collaboration.d.ts +1 -0
  6. package/collaboration.js +1 -0
  7. package/commands.d.ts +1 -0
  8. package/commands.js +1 -0
  9. package/content.d.ts +1 -0
  10. package/content.js +1 -0
  11. package/contracts.d.ts +1 -0
  12. package/contracts.js +1 -0
  13. package/dist/adapters.d.mts +11 -0
  14. package/dist/adapters.d.ts +11 -0
  15. package/dist/adapters.js +564 -0
  16. package/dist/adapters.js.map +1 -0
  17. package/dist/adapters.mjs +557 -0
  18. package/dist/adapters.mjs.map +1 -0
  19. package/dist/collaboration.d.mts +29 -0
  20. package/dist/collaboration.d.ts +29 -0
  21. package/dist/collaboration.js +758 -0
  22. package/dist/collaboration.js.map +1 -0
  23. package/dist/collaboration.mjs +733 -0
  24. package/dist/collaboration.mjs.map +1 -0
  25. package/dist/commands.d.mts +8 -0
  26. package/dist/commands.d.ts +8 -0
  27. package/dist/commands.js +42 -0
  28. package/dist/commands.js.map +1 -0
  29. package/dist/commands.mjs +38 -0
  30. package/dist/commands.mjs.map +1 -0
  31. package/dist/content-types-CYHsrMrs.d.mts +27 -0
  32. package/dist/content-types-CYHsrMrs.d.ts +27 -0
  33. package/dist/content.d.mts +19 -0
  34. package/dist/content.d.ts +19 -0
  35. package/dist/content.js +785 -0
  36. package/dist/content.js.map +1 -0
  37. package/dist/content.mjs +775 -0
  38. package/dist/content.mjs.map +1 -0
  39. package/dist/contracts.d.mts +199 -0
  40. package/dist/contracts.d.ts +199 -0
  41. package/dist/contracts.js +4 -0
  42. package/dist/contracts.js.map +1 -0
  43. package/dist/contracts.mjs +3 -0
  44. package/dist/contracts.mjs.map +1 -0
  45. package/dist/extensions.d.mts +363 -0
  46. package/dist/extensions.d.ts +363 -0
  47. package/dist/extensions.js +153 -0
  48. package/dist/extensions.js.map +1 -0
  49. package/dist/extensions.mjs +142 -0
  50. package/dist/extensions.mjs.map +1 -0
  51. package/dist/history.d.mts +12 -0
  52. package/dist/history.d.ts +12 -0
  53. package/dist/history.js +464 -0
  54. package/dist/history.js.map +1 -0
  55. package/dist/history.mjs +459 -0
  56. package/dist/history.mjs.map +1 -0
  57. package/dist/index.d.mts +12 -0
  58. package/dist/index.d.ts +12 -0
  59. package/dist/index.js +1438 -0
  60. package/dist/index.js.map +1 -0
  61. package/dist/index.mjs +1372 -0
  62. package/dist/index.mjs.map +1 -0
  63. package/dist/markdown.d.mts +32 -0
  64. package/dist/markdown.d.ts +32 -0
  65. package/dist/markdown.js +739 -0
  66. package/dist/markdown.js.map +1 -0
  67. package/dist/markdown.mjs +735 -0
  68. package/dist/markdown.mjs.map +1 -0
  69. package/dist/runtime/dom.d.mts +148 -0
  70. package/dist/runtime/dom.d.ts +148 -0
  71. package/dist/runtime/dom.js +2145 -0
  72. package/dist/runtime/dom.js.map +1 -0
  73. package/dist/runtime/dom.mjs +2084 -0
  74. package/dist/runtime/dom.mjs.map +1 -0
  75. package/dist/schema.d.mts +23 -0
  76. package/dist/schema.d.ts +23 -0
  77. package/dist/schema.js +157 -0
  78. package/dist/schema.js.map +1 -0
  79. package/dist/schema.mjs +137 -0
  80. package/dist/schema.mjs.map +1 -0
  81. package/dist/serializer.d.mts +38 -0
  82. package/dist/serializer.d.ts +38 -0
  83. package/dist/serializer.js +504 -0
  84. package/dist/serializer.js.map +1 -0
  85. package/dist/serializer.mjs +491 -0
  86. package/dist/serializer.mjs.map +1 -0
  87. package/dist/svg-export-BtI8x_mG.d.mts +15 -0
  88. package/dist/svg-export-BtI8x_mG.d.ts +15 -0
  89. package/dist/transactions.d.mts +16 -0
  90. package/dist/transactions.d.ts +16 -0
  91. package/dist/transactions.js +637 -0
  92. package/dist/transactions.js.map +1 -0
  93. package/dist/transactions.mjs +631 -0
  94. package/dist/transactions.mjs.map +1 -0
  95. package/extensions.d.ts +1 -0
  96. package/extensions.js +1 -0
  97. package/history.d.ts +1 -0
  98. package/history.js +1 -0
  99. package/package.json +352 -4
  100. package/schema.d.ts +1 -0
  101. package/schema.js +1 -0
  102. package/serializer.d.ts +1 -0
  103. package/serializer.js +1 -0
  104. package/transactions.d.ts +1 -0
  105. package/transactions.js +1 -0
@@ -0,0 +1,2084 @@
1
+ // src/commands.ts
2
+ var richTextCommandRegistry = [
3
+ { command: "undo", group: "history" },
4
+ { command: "redo", group: "history" },
5
+ { command: "bold", group: "inline", inlineTagName: "strong" },
6
+ { command: "italic", group: "inline", inlineTagName: "em" },
7
+ { command: "underline", group: "inline", inlineTagName: "u" },
8
+ { command: "strike", group: "inline", inlineTagName: "s" },
9
+ { command: "inlineCode", group: "inline", inlineTagName: "code" },
10
+ { command: "highlight", group: "inline", inlineTagName: "mark" },
11
+ { command: "subscript", group: "inline", inlineTagName: "sub" },
12
+ { command: "superscript", group: "inline", inlineTagName: "sup" },
13
+ { command: "link", group: "inline" },
14
+ { command: "bulletedList", group: "structure", listTagName: "ul" },
15
+ { command: "numberedList", group: "structure", listTagName: "ol" },
16
+ { command: "taskList", group: "structure", taskList: true },
17
+ { command: "blockquote", group: "structure", blockTagName: "blockquote" },
18
+ { command: "horizontalRule", group: "structure" },
19
+ { command: "clearFormatting", group: "structure" },
20
+ { command: "alignLeft", group: "alignment", alignment: "left" },
21
+ { command: "alignCenter", group: "alignment", alignment: "center" },
22
+ { command: "alignRight", group: "alignment", alignment: "right" },
23
+ { command: "alignJustify", group: "alignment", alignment: "justify" },
24
+ { command: "findReplace", group: "tools" }
25
+ ];
26
+ var richTextAlignmentCommandByValue = {
27
+ left: "alignLeft",
28
+ center: "alignCenter",
29
+ right: "alignRight",
30
+ justify: "alignJustify"
31
+ };
32
+ function getRichTextCommandDefinition(command) {
33
+ return richTextCommandRegistry.find((definition) => definition.command === command);
34
+ }
35
+
36
+ // src/schema.ts
37
+ var QUICK_BUILDER_RICH_TEXT_SCHEMA_VERSION = 2;
38
+ var richTextAllowedTags = [
39
+ "a",
40
+ "b",
41
+ "blockquote",
42
+ "br",
43
+ "code",
44
+ "em",
45
+ "h1",
46
+ "h2",
47
+ "h3",
48
+ "h4",
49
+ "h5",
50
+ "h6",
51
+ "hr",
52
+ "i",
53
+ "img",
54
+ "input",
55
+ "label",
56
+ "li",
57
+ "mark",
58
+ "ol",
59
+ "p",
60
+ "pre",
61
+ "qb-video",
62
+ "s",
63
+ "span",
64
+ "sub",
65
+ "sup",
66
+ "strong",
67
+ "table",
68
+ "tbody",
69
+ "td",
70
+ "tfoot",
71
+ "th",
72
+ "thead",
73
+ "tr",
74
+ "u",
75
+ "ul"
76
+ ];
77
+ var richTextVoidTags = ["br", "hr", "img", "input"];
78
+ var richTextAllowedTargets = ["_blank", "_self", "_parent", "_top"];
79
+ var richTextAlignmentTags = [
80
+ "blockquote",
81
+ "h1",
82
+ "h2",
83
+ "h3",
84
+ "h4",
85
+ "h5",
86
+ "h6",
87
+ "li",
88
+ "ol",
89
+ "p",
90
+ "pre",
91
+ "td",
92
+ "th",
93
+ "ul"
94
+ ];
95
+ var richTextAllowedAlignments = ["left", "center", "right", "justify"];
96
+ var richTextAllowedFontFamilies = [
97
+ "default",
98
+ "carlito",
99
+ "source-sans-3",
100
+ "noto-sans",
101
+ "arimo",
102
+ "tinos",
103
+ "cousine"
104
+ ];
105
+ var richTextAllowedFontSizes = [
106
+ "default",
107
+ "8",
108
+ "9",
109
+ "10",
110
+ "11",
111
+ "12",
112
+ "14",
113
+ "16",
114
+ "18",
115
+ "24",
116
+ "30",
117
+ "36",
118
+ "48",
119
+ "60",
120
+ "72",
121
+ "96"
122
+ ];
123
+ var richTextAllowedLineHeights = ["1", "1.15", "1.5", "2"];
124
+ var richTextAllowedColors = [
125
+ "default",
126
+ "gray",
127
+ "brown",
128
+ "orange",
129
+ "yellow",
130
+ "green",
131
+ "blue",
132
+ "purple",
133
+ "pink",
134
+ "red"
135
+ ];
136
+ var richTextBlockSelector = "p,h1,h2,h3,pre,blockquote,li,ul,ol,td,th";
137
+ var richTextBlockFormatByTagName = {
138
+ p: "paragraph",
139
+ h1: "heading1",
140
+ h2: "heading2",
141
+ h3: "heading3",
142
+ pre: "codeBlock"
143
+ };
144
+ function isRichTextAlignment(value) {
145
+ return richTextAllowedAlignments.includes(value);
146
+ }
147
+ function isRichTextFontFamily(value) {
148
+ return richTextAllowedFontFamilies.includes(value);
149
+ }
150
+ function isRichTextFontSize(value) {
151
+ return richTextAllowedFontSizes.includes(value);
152
+ }
153
+ function isRichTextLineHeight(value) {
154
+ return richTextAllowedLineHeights.includes(value);
155
+ }
156
+ function isRichTextColor(value) {
157
+ return richTextAllowedColors.includes(value);
158
+ }
159
+
160
+ // src/entities.ts
161
+ var entities = {
162
+ amp: "&",
163
+ lt: "<",
164
+ gt: ">",
165
+ quot: '"',
166
+ apos: "'",
167
+ nbsp: "\xA0",
168
+ copy: "\xA9",
169
+ reg: "\xAE",
170
+ trade: "\u2122",
171
+ mdash: "\u2014",
172
+ ndash: "\u2013",
173
+ hellip: "\u2026",
174
+ lsquo: "\u2018",
175
+ rsquo: "\u2019",
176
+ ldquo: "\u201C",
177
+ rdquo: "\u201D",
178
+ bull: "\u2022",
179
+ middot: "\xB7"
180
+ };
181
+ function decodeRichTextEntities(value) {
182
+ return value.replace(
183
+ /&(#x[\da-f]+|#\d+|[a-z][a-z\d]+);/gi,
184
+ (original, entity) => {
185
+ if (!entity.startsWith("#")) {
186
+ const decoded = entities[entity];
187
+ if (decoded === void 0)
188
+ throw new Error(
189
+ `Unsupported named rich-text entity ${original}; use Unicode or a numeric entity`
190
+ );
191
+ return decoded;
192
+ }
193
+ const point = entity[1]?.toLowerCase() === "x" ? Number.parseInt(entity.slice(2), 16) : Number(entity.slice(1));
194
+ if (point < 1 || point > 1114111 || point >= 55296 && point <= 57343)
195
+ throw new Error("Invalid rich-text character entity");
196
+ return String.fromCodePoint(point);
197
+ }
198
+ );
199
+ }
200
+
201
+ // src/serializer.ts
202
+ var ACTIVE_CONTENT_TAG_PATTERN = /<\s*(script|style|iframe|object|embed|form)\b[^>]*>[\s\S]*?<\s*\/\s*\1\s*>/gi;
203
+ var ACTIVE_VOID_TAG_PATTERN = /<\s*(?:script|style|iframe|object|embed|link|meta|base)\b[^>]*\/?\s*>/gi;
204
+ var RICH_TEXT_VIDEO_PATTERN = /<qb-video\b((?:"[^"]*"|'[^']*'|[^'">])*)>[\s\S]*?<\/qb-video>/gi;
205
+ var RICH_TEXT_TAG_PATTERN = /<qb-video\b((?:"[^"]*"|'[^']*'|[^'">])*)>[\s\S]*?<\/qb-video>|<\/?([a-z][a-z0-9-]*)\b((?:"[^"]*"|'[^']*'|[^'">])*)>/gi;
206
+ var ATTRIBUTE_VALUE_PATTERN = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g;
207
+ var allowedTagSet = new Set(richTextAllowedTags);
208
+ var voidTagSet = new Set(richTextVoidTags);
209
+ var allowedTargetSet = new Set(richTextAllowedTargets);
210
+ var alignmentTagSet = new Set(richTextAlignmentTags);
211
+ var richTextMaximumUrlLength = 4096;
212
+ var richTextMaximumImageTextLength = 512;
213
+ function validateRichTextVideo(src, title) {
214
+ src = src.trim();
215
+ title = title.trim();
216
+ if (!src || src.length > 2048 || !title || title.length > 200 || /[\u0000-\u0020\u007f\\]/u.test(src)) return;
217
+ const relative = /^\/(?!\/)/u.test(src);
218
+ if (!relative && !src.startsWith("https://")) return;
219
+ try {
220
+ const url = new URL(src, "https://rich-text.invalid");
221
+ if (url.protocol !== "https:" || url.username || url.password) return;
222
+ return { src, title };
223
+ } catch {
224
+ return;
225
+ }
226
+ }
227
+ function readVideoAttributes(raw) {
228
+ const attributes = readHtmlAttributes(raw);
229
+ return validateRichTextVideo(attributes.get("data-src") ?? "", attributes.get("data-title") ?? "");
230
+ }
231
+ function sanitizeRichTextMarkup(value, options = {}) {
232
+ if (options.resolveImageSource !== void 0 && typeof options.resolveImageSource !== "function")
233
+ throw new TypeError("Invalid rich text image resolver.");
234
+ if (options.allowVideos !== void 0 && typeof options.allowVideos !== "boolean")
235
+ throw new TypeError("Invalid rich text video policy.");
236
+ if (options.videoPresentation !== void 0 && !["embed", "link"].includes(options.videoPresentation))
237
+ throw new TypeError("Invalid rich text video presentation.");
238
+ if (options.allowContentIdImages !== void 0 && typeof options.allowContentIdImages !== "boolean")
239
+ throw new TypeError("Invalid rich text Content-ID image policy.");
240
+ if (options.imageCrossOrigin !== void 0 && options.imageCrossOrigin !== "anonymous" && typeof options.imageCrossOrigin !== "function")
241
+ throw new TypeError("Invalid rich text image credentials policy.");
242
+ return sanitizeMarkup(value, options);
243
+ }
244
+ function sanitizeMarkup(value, options = {}) {
245
+ return value.replace(ACTIVE_CONTENT_TAG_PATTERN, "").replace(ACTIVE_VOID_TAG_PATTERN, "").replace(RICH_TEXT_TAG_PATTERN, (match, rawVideo, rawTagName, rawAttributes) => {
246
+ if (rawVideo !== void 0) {
247
+ if (options.allowVideos === false) return "";
248
+ const video = readVideoAttributes(rawVideo);
249
+ if (!video) return "";
250
+ if (options.videoPresentation === "link") {
251
+ return withBlockIdentity("<p>", rawVideo) + `<br><a href="${escapeHtmlAttribute(video.src)}">${escapeHtmlAttribute(video.title)}</a></p>`;
252
+ }
253
+ return withBlockIdentity(`<qb-video data-src="${escapeHtmlAttribute(video.src)}" data-title="${escapeHtmlAttribute(video.title)}" contenteditable="false">`, rawVideo) + "</qb-video>";
254
+ }
255
+ const tagName = rawTagName.toLowerCase();
256
+ if (tagName === "qb-video") return "";
257
+ if (!allowedTagSet.has(tagName)) {
258
+ return "";
259
+ }
260
+ if (match.startsWith("</")) {
261
+ return voidTagSet.has(tagName) ? "" : `</${tagName}>`;
262
+ }
263
+ if (voidTagSet.has(tagName)) {
264
+ if (tagName === "img") {
265
+ return withBlockIdentity(renderSafeImageTag(rawAttributes, options), rawAttributes);
266
+ }
267
+ if (tagName === "input") {
268
+ return withBlockIdentity(renderSafeTaskCheckbox(rawAttributes), rawAttributes);
269
+ }
270
+ return withBlockIdentity(`<${tagName}>`, rawAttributes);
271
+ }
272
+ if (tagName !== "a") {
273
+ return withBlockIdentity(renderSafeRichTextTag(tagName, rawAttributes), rawAttributes);
274
+ }
275
+ return renderSafeAnchorTag(rawAttributes);
276
+ });
277
+ }
278
+ function normalizeRichTextHtml(value) {
279
+ const sanitized = sanitizeRichTextMarkup(value);
280
+ return sanitized.trim() ? sanitized : "<p></p>";
281
+ }
282
+ function richTextHtmlToPlainText(html) {
283
+ if (html.length > 1e6) throw new RangeError("Rich text exceeds the serialization limit");
284
+ const text = sanitizeRichTextMarkup(html).replace(RICH_TEXT_VIDEO_PATTERN, (_element, raw) => `
285
+ ${escapeHtmlAttribute(readVideoAttributes(raw)?.title ?? "")}
286
+ `).replace(/<!--[\s\S]*?-->/g, "").replace(/<(?:br|hr)\b[^>]*>/gi, "\n").replace(/<\/(?:p|h[1-6]|li|blockquote|pre|tr|table)>/gi, "\n").replace(/<\/(?:td|th)>/gi, " ").replace(/<[^>]*>/g, "");
287
+ return decodeRichTextEntities(text).replace(/\t+\n/g, "\n").trim();
288
+ }
289
+ function withBlockIdentity(tag, rawAttributes) {
290
+ const id = readHtmlAttributes(rawAttributes).get("data-qb-block-id");
291
+ if (!tag || tag.startsWith("<span") || !id || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id)) return tag;
292
+ return tag.replace(/>$/, ` data-qb-block-id="${id}">`);
293
+ }
294
+ function renderSafeRichTextTag(tagName, rawAttributes) {
295
+ if (tagName === "span") {
296
+ return renderSafeSpanTag(rawAttributes);
297
+ }
298
+ if (tagName === "td" || tagName === "th") {
299
+ return renderSafeTableCellTag(tagName, rawAttributes);
300
+ }
301
+ if (tagName === "ul") {
302
+ const attributes2 = readHtmlAttributes(rawAttributes);
303
+ return attributes2.get("data-task-list") === "true" ? '<ul data-task-list="true">' : "<ul>";
304
+ }
305
+ if (tagName === "li") {
306
+ const attributes2 = readHtmlAttributes(rawAttributes);
307
+ const checked = attributes2.get("data-checked");
308
+ return checked === "true" || checked === "false" ? `<li data-checked="${checked}">` : "<li>";
309
+ }
310
+ if (!alignmentTagSet.has(tagName)) {
311
+ return `<${tagName}>`;
312
+ }
313
+ const attributes = readHtmlAttributes(rawAttributes);
314
+ const renderedAttributes = [];
315
+ const alignment = attributes.get("data-align");
316
+ const lineHeight = attributes.get("data-line-height");
317
+ if (isRichTextAlignment(alignment)) renderedAttributes.push(`data-align="${alignment}"`);
318
+ if (isRichTextLineHeight(lineHeight)) renderedAttributes.push(`data-line-height="${lineHeight}"`);
319
+ return renderedAttributes.length > 0 ? `<${tagName} ${renderedAttributes.join(" ")}>` : `<${tagName}>`;
320
+ }
321
+ function renderSafeSpanTag(rawAttributes) {
322
+ const attributes = readHtmlAttributes(rawAttributes);
323
+ const renderedAttributes = [];
324
+ const id = normalizeMentionAttribute(attributes.get("data-mention-id"), 128);
325
+ const label = normalizeMentionAttribute(attributes.get("data-mention-label"), 160);
326
+ const fontFamily = attributes.get("data-font-family");
327
+ const fontSize = attributes.get("data-font-size");
328
+ const textColor = attributes.get("data-text-color");
329
+ const highlightColor = attributes.get("data-highlight-color");
330
+ if (id && label) {
331
+ renderedAttributes.push(
332
+ `data-mention-id="${escapeHtmlAttribute(id)}"`,
333
+ `data-mention-label="${escapeHtmlAttribute(label)}"`
334
+ );
335
+ }
336
+ if (isRichTextFontFamily(fontFamily) && fontFamily !== "default") renderedAttributes.push(`data-font-family="${fontFamily}"`);
337
+ if (isRichTextFontSize(fontSize) && fontSize !== "default") renderedAttributes.push(`data-font-size="${fontSize}"`);
338
+ if (isRichTextColor(textColor) && textColor !== "default") renderedAttributes.push(`data-text-color="${textColor}"`);
339
+ if (isRichTextColor(highlightColor) && highlightColor !== "default") renderedAttributes.push(`data-highlight-color="${highlightColor}"`);
340
+ return renderedAttributes.length > 0 ? `<span ${renderedAttributes.join(" ")}>` : "<span>";
341
+ }
342
+ function renderSafeTableCellTag(tagName, rawAttributes) {
343
+ const attributes = readHtmlAttributes(rawAttributes);
344
+ const renderedAttributes = [];
345
+ const alignment = attributes.get("data-align");
346
+ const colSpan = normalizeTableSpan(attributes.get("colspan"));
347
+ const rowSpan = normalizeTableSpan(attributes.get("rowspan"));
348
+ const scope = attributes.get("scope");
349
+ if (isRichTextAlignment(alignment)) {
350
+ renderedAttributes.push(`data-align="${alignment}"`);
351
+ }
352
+ if (colSpan) {
353
+ renderedAttributes.push(`colspan="${colSpan}"`);
354
+ }
355
+ if (rowSpan) {
356
+ renderedAttributes.push(`rowspan="${rowSpan}"`);
357
+ }
358
+ if (tagName === "th" && scope && ["col", "row", "colgroup", "rowgroup"].includes(scope)) {
359
+ renderedAttributes.push(`scope="${scope}"`);
360
+ }
361
+ return renderedAttributes.length > 0 ? `<${tagName} ${renderedAttributes.join(" ")}>` : `<${tagName}>`;
362
+ }
363
+ function renderSafeAnchorTag(rawAttributes) {
364
+ const attributes = readHtmlAttributes(rawAttributes);
365
+ const renderedAttributes = [];
366
+ const href = attributes.get("href");
367
+ const target = attributes.get("target");
368
+ if (href && isSafeRichTextHref(href)) {
369
+ renderedAttributes.push(`href="${escapeHtmlAttribute(href)}"`);
370
+ }
371
+ if (target && allowedTargetSet.has(target)) {
372
+ renderedAttributes.push(`target="${target}"`);
373
+ if (target === "_blank") {
374
+ renderedAttributes.push('rel="noopener noreferrer"');
375
+ }
376
+ }
377
+ return renderedAttributes.length > 0 ? `<a ${renderedAttributes.join(" ")}>` : "<a>";
378
+ }
379
+ function renderSafeImageTag(rawAttributes, options) {
380
+ const attributes = readHtmlAttributes(rawAttributes);
381
+ const source = attributes.get("src");
382
+ const resolveSource = options.resolveImageSource;
383
+ if (!source || !resolveSource && !isAllowedImageSource(source, options)) return "";
384
+ const src = resolveSource ? resolveSource(source) : source;
385
+ if (src === null) return "";
386
+ if (!isAllowedImageSource(src, options)) throw new TypeError("Invalid replacement image URL.");
387
+ const renderedAttributes = [
388
+ `src="${escapeHtmlAttribute(src)}"`,
389
+ `alt="${escapeHtmlAttribute(normalizeTextAttribute(attributes.get("alt"), 512) ?? "")}"`
390
+ ];
391
+ const title = normalizeTextAttribute(attributes.get("title"), 512);
392
+ const width = normalizeImageDimension(attributes.get("width"));
393
+ const height = normalizeImageDimension(attributes.get("height"));
394
+ if (title) renderedAttributes.push(`title="${escapeHtmlAttribute(title)}"`);
395
+ if (width) renderedAttributes.push(`width="${width}"`);
396
+ if (height) renderedAttributes.push(`height="${height}"`);
397
+ const credentials = typeof options.imageCrossOrigin === "function" ? options.imageCrossOrigin(src) : options.imageCrossOrigin;
398
+ if (credentials !== void 0 && credentials !== "anonymous") throw new TypeError("Invalid resolved image credentials policy.");
399
+ if ((credentials ?? attributes.get("crossorigin")) === "anonymous") renderedAttributes.push('crossorigin="anonymous"');
400
+ renderedAttributes.push('loading="lazy"', 'decoding="async"');
401
+ return `<img ${renderedAttributes.join(" ")}>`;
402
+ }
403
+ function isAllowedImageSource(value, options) {
404
+ if (isSafeRichTextImageSrc(value)) return true;
405
+ if (!options.allowContentIdImages || value.length > richTextMaximumUrlLength || !/^cid:/iu.test(value)) return false;
406
+ try {
407
+ const identity = decodeURIComponent(value.slice(4));
408
+ return identity.length > 0 && identity.length <= 200 && !/[^\u0021-\u007e]|[<>"]/u.test(identity);
409
+ } catch {
410
+ return false;
411
+ }
412
+ }
413
+ function renderSafeTaskCheckbox(rawAttributes) {
414
+ const attributes = readHtmlAttributes(rawAttributes);
415
+ if (attributes.get("type")?.toLowerCase() !== "checkbox") return "";
416
+ const checked = attributes.get("checked") !== void 0 || /(?:^|\s)checked(?:\s|=|$)/i.test(rawAttributes);
417
+ return `<input type="checkbox"${checked ? ' checked=""' : ""} contenteditable="false">`;
418
+ }
419
+ function readHtmlAttributes(rawAttributes) {
420
+ const attributes = /* @__PURE__ */ new Map();
421
+ for (const match of rawAttributes.matchAll(ATTRIBUTE_VALUE_PATTERN)) {
422
+ const name = match[1]?.toLowerCase();
423
+ const value = match[2] ?? match[3] ?? match[4] ?? "";
424
+ if (name) {
425
+ attributes.set(name, decodeHtmlAttribute(value.trim()));
426
+ }
427
+ }
428
+ return attributes;
429
+ }
430
+ function isSafeRichTextHref(value) {
431
+ const trimmed = value.trim();
432
+ if (!trimmed || trimmed.length > richTextMaximumUrlLength || /[\u0000-\u001f\u007f]/.test(trimmed)) {
433
+ return false;
434
+ }
435
+ if (trimmed.startsWith("//")) {
436
+ return false;
437
+ }
438
+ if (/^(?:#|\/|\.\/|\.\.\/|\?)/.test(trimmed)) {
439
+ return true;
440
+ }
441
+ try {
442
+ const url = new URL(trimmed);
443
+ return ["http:", "https:", "mailto:", "tel:"].includes(url.protocol.toLowerCase());
444
+ } catch {
445
+ return false;
446
+ }
447
+ }
448
+ function isSafeRichTextImageSrc(value) {
449
+ const trimmed = value.trim();
450
+ if (!trimmed || trimmed.length > richTextMaximumUrlLength || /[\u0000-\u001f\u007f]/.test(trimmed) || trimmed.startsWith("//")) return false;
451
+ if (/^(?:\/|\.\/|\.\.\/)/.test(trimmed)) return true;
452
+ try {
453
+ const url = new URL(trimmed);
454
+ return url.protocol === "http:" || url.protocol === "https:";
455
+ } catch {
456
+ return false;
457
+ }
458
+ }
459
+ function normalizeTableSpan(value) {
460
+ if (!value || !/^\d{1,3}$/.test(value)) {
461
+ return null;
462
+ }
463
+ const numericValue = Number(value);
464
+ return numericValue >= 1 && numericValue <= 100 ? String(numericValue) : null;
465
+ }
466
+ function normalizeMentionAttribute(value, maxLength) {
467
+ const normalized = value?.trim();
468
+ if (!normalized || normalized.length > maxLength || /[<>"'`]/.test(normalized)) {
469
+ return null;
470
+ }
471
+ return normalized;
472
+ }
473
+ function normalizeTextAttribute(value, maxLength) {
474
+ const normalized = value?.trim();
475
+ if (!normalized || normalized.length > maxLength) return null;
476
+ return normalized;
477
+ }
478
+ function normalizeImageDimension(value) {
479
+ if (!value || !/^\d{1,5}$/.test(value)) return null;
480
+ const numericValue = Number(value);
481
+ return numericValue >= 1 && numericValue <= 1e4 ? String(numericValue) : null;
482
+ }
483
+ function escapeHtmlAttribute(value) {
484
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
485
+ }
486
+ function decodeHtmlAttribute(value) {
487
+ return value.replace(/&(?:#(\d+)|#x([0-9a-f]+)|(amp|quot|apos|lt|gt));/gi, (entity, decimal, hexadecimal, named) => {
488
+ if (decimal || hexadecimal) {
489
+ const codePoint = decimal ? Number(decimal) : Number.parseInt(hexadecimal, 16);
490
+ if (!Number.isSafeInteger(codePoint) || codePoint <= 0 || codePoint > 1114111 || codePoint >= 55296 && codePoint <= 57343) {
491
+ return "\uFFFD";
492
+ }
493
+ return String.fromCodePoint(codePoint);
494
+ }
495
+ const namedEntity = {
496
+ amp: "&",
497
+ apos: "'",
498
+ gt: ">",
499
+ lt: "<",
500
+ quot: '"'
501
+ };
502
+ return namedEntity[String(named).toLowerCase()] ?? entity;
503
+ });
504
+ }
505
+
506
+ // src/transactions.ts
507
+ function createRichTextDocumentSnapshot(html, schemaVersion = QUICK_BUILDER_RICH_TEXT_SCHEMA_VERSION) {
508
+ const safeHtml = normalizeRichTextHtml(html);
509
+ return {
510
+ html: safeHtml,
511
+ plainText: richTextHtmlToPlainText(safeHtml),
512
+ schemaVersion
513
+ };
514
+ }
515
+
516
+ // src/view-tree.ts
517
+ function richTextHtmlToViewTree(value) {
518
+ if (value.length > 1e6)
519
+ throw new RangeError("Rich text exceeds the rendering limit");
520
+ const html = normalizeRichTextHtml(value).replace(/<!--[\s\S]*?-->/g, "");
521
+ const root = [];
522
+ const stack = [
523
+ { tag: "", children: root }
524
+ ];
525
+ let count = 0;
526
+ const tokens = /<\/?([a-z][a-z\d-]*)\b((?:"[^"]*"|'[^']*'|[^'">])*)>|([^<]+)|</gi;
527
+ for (const match of html.matchAll(tokens)) {
528
+ if (++count > 2e4 || stack.length > 64)
529
+ throw new RangeError("Rich text exceeds the rendering complexity limit");
530
+ const current = stack[stack.length - 1];
531
+ if (!match[1]) {
532
+ current.children.push({ type: "text", value: decodeRichTextEntities(match[3] ?? "<") });
533
+ continue;
534
+ }
535
+ const tag = match[1].toLowerCase();
536
+ if (match[0].startsWith("</")) {
537
+ if (stack.length === 1 || current.tag !== tag)
538
+ throw new Error(`Unbalanced rich-text closing tag ${tag}`);
539
+ stack.pop();
540
+ continue;
541
+ }
542
+ const attributes = {};
543
+ for (const attribute of match[2].matchAll(/([\w-]+)="([^"]*)"/g))
544
+ attributes[attribute[1]] = decodeRichTextEntities(attribute[2]);
545
+ const node = {
546
+ type: "element",
547
+ tag,
548
+ attributes,
549
+ children: []
550
+ };
551
+ current.children.push(node);
552
+ if (!richTextVoidTags.some((voidTag) => voidTag === tag)) stack.push(node);
553
+ }
554
+ if (stack.length !== 1) throw new Error("Unclosed rich-text element");
555
+ return root;
556
+ }
557
+
558
+ // src/svg-export.ts
559
+ function richTextExportImageSources(html) {
560
+ const sources = /* @__PURE__ */ new Set();
561
+ function visit(nodes) {
562
+ for (const node of nodes) {
563
+ if (node.type !== "element") continue;
564
+ if (node.tag === "img") sources.add(node.attributes.src);
565
+ visit(node.children);
566
+ }
567
+ }
568
+ visit(richTextHtmlToViewTree(html));
569
+ return [...sources];
570
+ }
571
+
572
+ // src/runtime/export-images.ts
573
+ async function resolveImage(source, signal) {
574
+ const url = new URL(source, document.baseURI);
575
+ if (url.username || url.password || url.protocol !== "https:" && url.origin !== window.location.origin)
576
+ throw new Error("A document image has an unsupported export origin.");
577
+ const image = new Image();
578
+ image.crossOrigin = "anonymous";
579
+ signal.throwIfAborted();
580
+ await new Promise((resolve, reject) => {
581
+ const finish = (error) => {
582
+ image.onload = null;
583
+ image.onerror = null;
584
+ signal.removeEventListener("abort", abort);
585
+ if (error) reject(error);
586
+ else resolve();
587
+ };
588
+ const abort = () => {
589
+ finish(new Error("Document image export was interrupted."));
590
+ image.src = "";
591
+ };
592
+ signal.addEventListener("abort", abort, { once: true });
593
+ image.onload = () => finish();
594
+ image.onerror = () => finish(new Error("A document image could not be loaded for export. Its host must permit browser image access."));
595
+ image.src = url.href;
596
+ });
597
+ signal.throwIfAborted();
598
+ const { naturalWidth: width, naturalHeight: height } = image;
599
+ if (!width || !height || width * height > 16e6) throw new RangeError("A document image exceeds the export size limit.");
600
+ const scale = Math.min(1, 1600 / Math.max(width, height));
601
+ const canvas = document.createElement("canvas");
602
+ canvas.width = Math.max(1, Math.round(width * scale));
603
+ canvas.height = Math.max(1, Math.round(height * scale));
604
+ const context = canvas.getContext("2d");
605
+ if (!context) throw new Error("Canvas image export is unavailable.");
606
+ context.drawImage(image, 0, 0, canvas.width, canvas.height);
607
+ return { dataUrl: canvas.toDataURL("image/png"), width, height };
608
+ }
609
+ async function resolveRichTextExportImages(documents, signal = AbortSignal.timeout(15e3)) {
610
+ const sources = [...new Set(documents.flatMap(richTextExportImageSources))];
611
+ if (sources.length > 100) throw new RangeError("Too many document images to export at once.");
612
+ const result = /* @__PURE__ */ new Map();
613
+ let bytes = 0;
614
+ for (const source of sources) {
615
+ const image = await resolveImage(source, signal);
616
+ bytes += image.dataUrl.length;
617
+ if (bytes > 12e6) throw new RangeError("Document images exceed the export byte limit.");
618
+ result.set(source, image);
619
+ }
620
+ return result;
621
+ }
622
+
623
+ // src/runtime/dom.ts
624
+ var RICH_TEXT_COLLABORATION_COLOR_PATTERN = /^#[0-9a-fA-F]{6}$/;
625
+ var richTextSlashCommandDefinitions = [
626
+ {
627
+ command: "heading1",
628
+ group: "format",
629
+ keywords: ["h1", "heading", "heading 1", "title"],
630
+ label: "Heading 1"
631
+ },
632
+ {
633
+ command: "heading2",
634
+ group: "format",
635
+ keywords: ["h2", "heading", "heading 2", "section"],
636
+ label: "Heading 2"
637
+ },
638
+ {
639
+ command: "heading3",
640
+ group: "format",
641
+ keywords: ["h3", "heading", "heading 3", "subheading"],
642
+ label: "Heading 3"
643
+ },
644
+ {
645
+ command: "paragraph",
646
+ group: "format",
647
+ keywords: ["p", "paragraph", "text"],
648
+ label: "Paragraph"
649
+ },
650
+ {
651
+ command: "blockquote",
652
+ group: "format",
653
+ keywords: ["quote", "blockquote", "callout"],
654
+ label: "Quote"
655
+ },
656
+ {
657
+ command: "bulletedList",
658
+ group: "format",
659
+ keywords: ["bullet", "bulleted", "list", "unordered"],
660
+ label: "Bulleted list"
661
+ },
662
+ {
663
+ command: "numberedList",
664
+ group: "format",
665
+ keywords: ["number", "numbered", "ordered", "list"],
666
+ label: "Numbered list"
667
+ },
668
+ {
669
+ command: "taskList",
670
+ group: "format",
671
+ keywords: ["check", "checklist", "task", "todo"],
672
+ label: "Task list"
673
+ },
674
+ {
675
+ command: "codeBlock",
676
+ group: "format",
677
+ keywords: ["code", "pre", "snippet"],
678
+ label: "Code block"
679
+ },
680
+ {
681
+ command: "horizontalRule",
682
+ group: "insert",
683
+ keywords: ["divider", "horizontal rule", "separator"],
684
+ label: "Separator"
685
+ },
686
+ {
687
+ command: "table",
688
+ group: "insert",
689
+ keywords: ["table", "grid", "rows", "columns"],
690
+ label: "Table"
691
+ }
692
+ ];
693
+ function containsRichTextSelection(editor) {
694
+ const selection = window.getSelection();
695
+ if (!selection || selection.rangeCount === 0) {
696
+ return false;
697
+ }
698
+ const anchor = selection.anchorNode;
699
+ const focus = selection.focusNode;
700
+ return Boolean(anchor && focus && editor.contains(anchor) && editor.contains(focus));
701
+ }
702
+ function getRichTextEditorRange(editor) {
703
+ const selection = window.getSelection();
704
+ if (!selection || selection.rangeCount === 0 || !containsRichTextSelection(editor)) {
705
+ return null;
706
+ }
707
+ return selection.getRangeAt(0);
708
+ }
709
+ function cloneRichTextEditorRange(editor) {
710
+ return getRichTextEditorRange(editor)?.cloneRange() ?? null;
711
+ }
712
+ function restoreRichTextEditorRange(editor, range) {
713
+ const selection = window.getSelection();
714
+ if (!selection || !range || !editor.contains(range.startContainer) || !editor.contains(range.endContainer)) {
715
+ return false;
716
+ }
717
+ editor.focus({ preventScroll: true });
718
+ selection.removeAllRanges();
719
+ selection.addRange(range);
720
+ return true;
721
+ }
722
+ function restoreRichTextCaretAfter(node) {
723
+ const selection = window.getSelection();
724
+ if (!selection) {
725
+ return;
726
+ }
727
+ const range = document.createRange();
728
+ range.setStartAfter(node);
729
+ range.collapse(true);
730
+ selection.removeAllRanges();
731
+ selection.addRange(range);
732
+ }
733
+ function selectRichTextNodeContents(node) {
734
+ const selection = window.getSelection();
735
+ if (!selection) return;
736
+ const range = document.createRange();
737
+ range.selectNodeContents(node);
738
+ selection.removeAllRanges();
739
+ selection.addRange(range);
740
+ }
741
+ function restoreRichTextCaretAtEnd(node) {
742
+ const selection = window.getSelection();
743
+ if (!selection) return;
744
+ const range = document.createRange();
745
+ range.selectNodeContents(node);
746
+ range.collapse(false);
747
+ selection.removeAllRanges();
748
+ selection.addRange(range);
749
+ }
750
+ function focusRichTextEditorEnd(editor) {
751
+ editor.focus();
752
+ const selection = window.getSelection();
753
+ if (!selection) {
754
+ return;
755
+ }
756
+ const range = document.createRange();
757
+ range.selectNodeContents(editor);
758
+ range.collapse(false);
759
+ selection.removeAllRanges();
760
+ selection.addRange(range);
761
+ }
762
+ function insertRichTextParagraphAfter(editor, block) {
763
+ if (!isDirectRichTextEditorBlock(editor, block)) return null;
764
+ const paragraph = document.createElement("p");
765
+ paragraph.appendChild(document.createElement("br"));
766
+ block.after(paragraph);
767
+ editor.focus({ preventScroll: true });
768
+ restoreRichTextCaretAtEnd(paragraph);
769
+ return paragraph;
770
+ }
771
+ function duplicateRichTextBlock(editor, block) {
772
+ if (!isDirectRichTextEditorBlock(editor, block)) return null;
773
+ const duplicate = block.cloneNode(true);
774
+ block.after(duplicate);
775
+ editor.focus({ preventScroll: true });
776
+ restoreRichTextCaretAtEnd(duplicate);
777
+ return duplicate;
778
+ }
779
+ function moveRichTextBlock(editor, block, direction) {
780
+ if (!isDirectRichTextEditorBlock(editor, block)) return false;
781
+ const sibling = direction === "up" ? block.previousElementSibling : block.nextElementSibling;
782
+ if (!(sibling instanceof HTMLElement)) return false;
783
+ if (direction === "up") sibling.before(block);
784
+ else sibling.after(block);
785
+ editor.focus({ preventScroll: true });
786
+ restoreRichTextCaretAtEnd(block);
787
+ return true;
788
+ }
789
+ function reorderRichTextBlock(editor, block, target, placement) {
790
+ if (!isDirectRichTextEditorBlock(editor, block) || !isDirectRichTextEditorBlock(editor, target) || block === target) return false;
791
+ if (placement === "before") target.before(block);
792
+ else target.after(block);
793
+ editor.focus({ preventScroll: true });
794
+ restoreRichTextCaretAtEnd(block);
795
+ return true;
796
+ }
797
+ function deleteRichTextBlock(editor, block) {
798
+ if (!isDirectRichTextEditorBlock(editor, block)) return false;
799
+ const focusTarget = block.nextElementSibling ?? block.previousElementSibling;
800
+ block.remove();
801
+ const nextFocusTarget = focusTarget instanceof HTMLElement ? focusTarget : ensureEditableBlock(editor);
802
+ editor.focus({ preventScroll: true });
803
+ restoreRichTextCaretAtEnd(nextFocusTarget);
804
+ return true;
805
+ }
806
+ function getSelectedRichText(editor) {
807
+ const range = getRichTextEditorRange(editor);
808
+ return range?.toString().trim() ?? "";
809
+ }
810
+ function insertRichTextElementAtSelection(editor, element) {
811
+ const range = getRichTextEditorRange(editor);
812
+ if (!range) {
813
+ editor.appendChild(element);
814
+ restoreRichTextCaretAfter(element);
815
+ return;
816
+ }
817
+ if (!range.collapsed) range.deleteContents();
818
+ range.insertNode(element);
819
+ restoreRichTextCaretAfter(element);
820
+ }
821
+ function applyRichTextInlineTag(editor, tagName) {
822
+ const range = getRichTextEditorRange(editor);
823
+ if (!range) {
824
+ focusRichTextEditorEnd(editor);
825
+ return;
826
+ }
827
+ const activeWrapper = findSharedInlineWrapper(editor, range, tagName);
828
+ if (activeWrapper) {
829
+ removeInlineWrapperFromRange(activeWrapper, range);
830
+ return;
831
+ }
832
+ if (range.collapsed) return;
833
+ const wrapper = document.createElement(tagName);
834
+ wrapper.appendChild(range.extractContents());
835
+ range.insertNode(wrapper);
836
+ selectRichTextNodeContents(wrapper);
837
+ }
838
+ function applyRichTextInlineAttribute(editor, attribute, value) {
839
+ const range = getRichTextEditorRange(editor);
840
+ if (!range || range.collapsed) return;
841
+ const existingWrapper = getClosestRichTextAttributeWrapper(editor, range.commonAncestorContainer, attribute);
842
+ if (existingWrapper && rangeCoversElementContents(range, existingWrapper)) {
843
+ if (value) existingWrapper.setAttribute(attribute, value);
844
+ else existingWrapper.removeAttribute(attribute);
845
+ if (existingWrapper.attributes.length === 0) unwrapRichTextInlineElement(existingWrapper);
846
+ return;
847
+ }
848
+ if (!value) {
849
+ removeRichTextAttributeFromRange(editor, range, attribute);
850
+ return;
851
+ }
852
+ const wrapper = document.createElement("span");
853
+ wrapper.setAttribute(attribute, value);
854
+ wrapper.appendChild(range.extractContents());
855
+ range.insertNode(wrapper);
856
+ selectRichTextNodeContents(wrapper);
857
+ }
858
+ function applyRichTextLineHeight(editor, value) {
859
+ const blocks = getSelectedBlockElements(editor);
860
+ const targets = blocks.length > 0 ? blocks : [ensureEditableBlock(editor)];
861
+ for (const block of targets) {
862
+ if (value === "1") block.removeAttribute("data-line-height");
863
+ else block.setAttribute("data-line-height", value);
864
+ }
865
+ }
866
+ function readRichTextTypographyState(editor) {
867
+ const range = getRichTextEditorRange(editor);
868
+ const anchor = range?.commonAncestorContainer ?? null;
869
+ const block = getSelectedBlockElements(editor)[0] ?? null;
870
+ return {
871
+ fontFamily: readRichTextAttribute(editor, anchor, "data-font-family", "default"),
872
+ fontSize: readRichTextAttribute(editor, anchor, "data-font-size", "default"),
873
+ lineHeight: block?.getAttribute("data-line-height") ?? "1",
874
+ textColor: readRichTextAttribute(editor, anchor, "data-text-color", "default"),
875
+ highlightColor: readRichTextAttribute(editor, anchor, "data-highlight-color", "default")
876
+ };
877
+ }
878
+ function applyRichTextList(editor, listTagName) {
879
+ const range = getRichTextEditorRange(editor);
880
+ const blocks = getSelectedBlockElements(editor);
881
+ const selectedList = blocks.length > 0 && blocks.every((block) => block.tagName.toLowerCase() === "li" && block.parentElement === blocks[0]?.parentElement) ? blocks[0]?.parentElement : null;
882
+ if (selectedList?.matches("ul,ol")) {
883
+ const existingList = selectedList;
884
+ if (existingList.getAttribute("data-task-list") === "true") {
885
+ existingList.removeAttribute("data-task-list");
886
+ Array.from(existingList.children).forEach((item) => unwrapRichTextTaskItem(item));
887
+ const nextList2 = replaceElementTag(existingList, listTagName);
888
+ restoreRichTextCaretAtEnd(nextList2.lastElementChild ?? nextList2);
889
+ return;
890
+ }
891
+ if (existingList.tagName.toLowerCase() === listTagName) {
892
+ const paragraphs = document.createDocumentFragment();
893
+ let lastParagraph = null;
894
+ Array.from(existingList.children).forEach((item) => {
895
+ const paragraph = document.createElement("p");
896
+ while (item.firstChild) paragraph.appendChild(item.firstChild);
897
+ if (!paragraph.hasChildNodes()) paragraph.appendChild(document.createElement("br"));
898
+ paragraphs.appendChild(paragraph);
899
+ lastParagraph = paragraph;
900
+ });
901
+ existingList.replaceWith(paragraphs);
902
+ if (lastParagraph) restoreRichTextCaretAtEnd(lastParagraph);
903
+ return;
904
+ }
905
+ const nextList = replaceElementTag(existingList, listTagName);
906
+ restoreRichTextCaretAtEnd(nextList.lastElementChild ?? nextList);
907
+ return;
908
+ }
909
+ const list = document.createElement(listTagName);
910
+ const targetBlocks = blocks.length > 0 ? blocks : [ensureEditableBlock(editor)];
911
+ for (const block of targetBlocks) {
912
+ const item = document.createElement("li");
913
+ while (block.firstChild) item.appendChild(block.firstChild);
914
+ if (!item.hasChildNodes()) item.appendChild(document.createElement("br"));
915
+ list.appendChild(item);
916
+ }
917
+ const firstBlock = targetBlocks[0];
918
+ if (firstBlock?.parentNode) {
919
+ firstBlock.parentNode.insertBefore(list, firstBlock);
920
+ targetBlocks.forEach((block) => block.remove());
921
+ } else if (range) {
922
+ range.insertNode(list);
923
+ } else {
924
+ editor.appendChild(list);
925
+ }
926
+ restoreRichTextCaretAtEnd(list.lastElementChild ?? list);
927
+ }
928
+ function applyRichTextTaskList(editor) {
929
+ const range = getRichTextEditorRange(editor);
930
+ const blocks = getSelectedBlockElements(editor);
931
+ const selectedList = blocks.length > 0 && blocks.every((block) => block.tagName.toLowerCase() === "li" && block.parentElement === blocks[0]?.parentElement) ? blocks[0]?.parentElement : null;
932
+ if (selectedList?.matches("ul,ol")) {
933
+ if (selectedList.getAttribute("data-task-list") === "true") {
934
+ const paragraphs = document.createDocumentFragment();
935
+ let lastParagraph = null;
936
+ Array.from(selectedList.children).forEach((item) => {
937
+ unwrapRichTextTaskItem(item);
938
+ const paragraph = document.createElement("p");
939
+ while (item.firstChild) paragraph.appendChild(item.firstChild);
940
+ if (!paragraph.hasChildNodes()) paragraph.appendChild(document.createElement("br"));
941
+ paragraphs.appendChild(paragraph);
942
+ lastParagraph = paragraph;
943
+ });
944
+ selectedList.replaceWith(paragraphs);
945
+ if (lastParagraph) restoreRichTextCaretAtEnd(lastParagraph);
946
+ return;
947
+ }
948
+ const taskList2 = replaceElementTag(selectedList, "ul");
949
+ taskList2.setAttribute("data-task-list", "true");
950
+ Array.from(taskList2.children).forEach((item) => wrapRichTextTaskItem(item));
951
+ restoreRichTextCaretAtEnd(taskList2.lastElementChild ?? taskList2);
952
+ return;
953
+ }
954
+ const taskList = document.createElement("ul");
955
+ taskList.setAttribute("data-task-list", "true");
956
+ const targetBlocks = blocks.length > 0 ? blocks : [ensureEditableBlock(editor)];
957
+ for (const block of targetBlocks) {
958
+ const item = document.createElement("li");
959
+ while (block.firstChild) item.appendChild(block.firstChild);
960
+ wrapRichTextTaskItem(item);
961
+ taskList.appendChild(item);
962
+ }
963
+ const firstBlock = targetBlocks[0];
964
+ if (firstBlock?.parentNode) {
965
+ firstBlock.parentNode.insertBefore(taskList, firstBlock);
966
+ targetBlocks.forEach((block) => block.remove());
967
+ } else if (range) {
968
+ range.insertNode(taskList);
969
+ } else {
970
+ editor.appendChild(taskList);
971
+ }
972
+ restoreRichTextCaretAtEnd(taskList.lastElementChild ?? taskList);
973
+ }
974
+ function applyRichTextBlockTag(editor, tagName) {
975
+ const blocks = getSelectedBlockElements(editor);
976
+ const targetBlocks = blocks.length > 0 ? blocks : [ensureEditableBlock(editor)];
977
+ let lastBlock = null;
978
+ for (const currentBlock of targetBlocks) {
979
+ lastBlock = replaceRichTextBlock(currentBlock, tagName);
980
+ }
981
+ if (lastBlock) restoreRichTextCaretAtEnd(lastBlock);
982
+ }
983
+ function applyRichTextBlockFormat(editor, format) {
984
+ if (format === "paragraph") {
985
+ applyRichTextBlockTag(editor, "p");
986
+ } else if (format === "heading1") {
987
+ applyRichTextBlockTag(editor, "h1");
988
+ } else if (format === "heading2") {
989
+ applyRichTextBlockTag(editor, "h2");
990
+ } else if (format === "heading3") {
991
+ applyRichTextBlockTag(editor, "h3");
992
+ } else {
993
+ applyRichTextBlockTag(editor, "pre");
994
+ }
995
+ }
996
+ function clearRichTextFormatting(editor) {
997
+ const blocks = getSelectedBlockElements(editor);
998
+ const targetBlocks = blocks.length > 0 ? blocks : [ensureEditableBlock(editor)];
999
+ let lastParagraph = null;
1000
+ for (const block of targetBlocks) {
1001
+ const plainText = (block.textContent ?? "").trim();
1002
+ if (block.matches("li") && block.parentElement?.getAttribute("data-task-list") === "true") {
1003
+ const checked = Boolean(block.querySelector('input[type="checkbox"]:checked'));
1004
+ block.replaceChildren();
1005
+ wrapRichTextTaskItem(block, checked, plainText);
1006
+ restoreRichTextCaretAtEnd(block);
1007
+ continue;
1008
+ }
1009
+ if (block.matches("li,td,th")) {
1010
+ block.textContent = plainText;
1011
+ if (!block.hasChildNodes()) block.appendChild(document.createElement("br"));
1012
+ lastParagraph = null;
1013
+ restoreRichTextCaretAtEnd(block);
1014
+ continue;
1015
+ }
1016
+ const paragraph = document.createElement("p");
1017
+ paragraph.textContent = plainText;
1018
+ block.replaceWith(paragraph);
1019
+ lastParagraph = paragraph;
1020
+ }
1021
+ if (lastParagraph) restoreRichTextCaretAtEnd(lastParagraph);
1022
+ }
1023
+ function applyRichTextAlignment(editor, alignment) {
1024
+ const blocks = getSelectedBlockElements(editor);
1025
+ const targets = blocks.length > 0 ? blocks : [ensureEditableBlock(editor)];
1026
+ for (const block of targets) {
1027
+ block.setAttribute("data-align", alignment);
1028
+ }
1029
+ }
1030
+ function applyRichTextLink(editor, text, url) {
1031
+ const normalizedUrl = url.trim();
1032
+ if (!isSafeRichTextHref(normalizedUrl)) {
1033
+ return;
1034
+ }
1035
+ const link = document.createElement("a");
1036
+ link.textContent = text.trim() || normalizedUrl;
1037
+ link.setAttribute("href", normalizedUrl);
1038
+ if (/^https?:\/\//i.test(normalizedUrl)) {
1039
+ link.setAttribute("target", "_blank");
1040
+ }
1041
+ insertRichTextElementAtSelection(editor, link);
1042
+ }
1043
+ function insertRichTextHorizontalRule(editor) {
1044
+ const rule = document.createElement("hr");
1045
+ const paragraph = document.createElement("p");
1046
+ paragraph.appendChild(document.createElement("br"));
1047
+ const selectedBlock = getSelectedBlockElements(editor)[0] ?? null;
1048
+ const insertionAnchor = selectedBlock?.closest("li")?.parentElement ?? selectedBlock?.closest("table") ?? selectedBlock;
1049
+ if (insertionAnchor && insertionAnchor !== editor && editor.contains(insertionAnchor)) {
1050
+ insertionAnchor.after(rule, paragraph);
1051
+ } else {
1052
+ editor.append(rule, paragraph);
1053
+ }
1054
+ restoreRichTextCaretAtEnd(paragraph);
1055
+ }
1056
+ function createRichTextEditingHtml(html) {
1057
+ const template = document.createElement("template");
1058
+ template.innerHTML = normalizeRichTextHtml(html);
1059
+ for (const image of Array.from(template.content.querySelectorAll("img"))) image.setAttribute("loading", "eager");
1060
+ return template.innerHTML;
1061
+ }
1062
+ function insertRichTextImage(editor, image) {
1063
+ if (!isSafeRichTextImageSrc(image.src) || !isValidRichTextImageAlternative(image) || image.alt.trim().length > richTextMaximumImageTextLength || image.crossOrigin !== void 0 && image.crossOrigin !== "anonymous" || image.title !== void 0 && image.title.trim().length > richTextMaximumImageTextLength || !isValidRichTextImageDimension(image.width) || !isValidRichTextImageDimension(image.height)) return false;
1064
+ const element = document.createElement("img");
1065
+ if (image.crossOrigin === "anonymous") element.setAttribute("crossorigin", image.crossOrigin);
1066
+ element.setAttribute("src", image.src.trim());
1067
+ element.setAttribute("alt", image.alt.trim());
1068
+ element.setAttribute("loading", "eager");
1069
+ element.setAttribute("decoding", "async");
1070
+ if (image.title?.trim()) element.setAttribute("title", image.title.trim());
1071
+ if (image.width !== void 0) element.setAttribute("width", String(image.width));
1072
+ if (image.height !== void 0) element.setAttribute("height", String(image.height));
1073
+ insertRichTextMediaBlock(editor, element);
1074
+ return true;
1075
+ }
1076
+ function insertRichTextVideo(editor, input) {
1077
+ const video = validateRichTextVideo(input.src, input.title);
1078
+ if (!video || editor.querySelectorAll("qb-video").length >= 100) return false;
1079
+ const element = document.createElement("qb-video");
1080
+ element.setAttribute("data-src", video.src);
1081
+ element.setAttribute("data-title", video.title);
1082
+ element.setAttribute("contenteditable", "false");
1083
+ insertRichTextMediaBlock(editor, element);
1084
+ return true;
1085
+ }
1086
+ function insertRichTextMediaBlock(editor, element) {
1087
+ const paragraph = document.createElement("p");
1088
+ paragraph.appendChild(document.createElement("br"));
1089
+ const selectedBlock = getSelectedBlockElements(editor)[0] ?? null;
1090
+ const insertionAnchor = selectedBlock?.closest("li")?.parentElement ?? selectedBlock?.closest("table") ?? selectedBlock;
1091
+ if (insertionAnchor && insertionAnchor !== editor && editor.contains(insertionAnchor)) {
1092
+ insertionAnchor.after(element, paragraph);
1093
+ } else {
1094
+ editor.append(element, paragraph);
1095
+ }
1096
+ restoreRichTextCaretAtEnd(paragraph);
1097
+ }
1098
+ function isValidRichTextImageAlternative(image) {
1099
+ const alternative = image.alt.trim();
1100
+ return image.decorative === true ? alternative.length === 0 : alternative.length > 0;
1101
+ }
1102
+ function isValidRichTextImageDimension(value) {
1103
+ return value === void 0 || Number.isSafeInteger(value) && value >= 1 && value <= 1e4;
1104
+ }
1105
+ function selectRichTextSearchMatch(editor, query, requestedIndex = 0, options = {}) {
1106
+ const matches = findRichTextSearchRanges(editor, query, options);
1107
+ if (matches.length === 0) return { activeIndex: -1, count: 0 };
1108
+ const activeIndex = normalizeSearchIndex(requestedIndex, matches.length);
1109
+ const range = matches[activeIndex];
1110
+ const selection = window.getSelection();
1111
+ if (range && selection) {
1112
+ selection.removeAllRanges();
1113
+ selection.addRange(range);
1114
+ const element = range.commonAncestorContainer.nodeType === Node.ELEMENT_NODE ? range.commonAncestorContainer : range.commonAncestorContainer.parentElement;
1115
+ element?.scrollIntoView?.({ block: "nearest" });
1116
+ }
1117
+ return { activeIndex, count: matches.length };
1118
+ }
1119
+ function replaceRichTextSearchMatch(editor, query, replacement, requestedIndex = 0, options = {}) {
1120
+ const matches = findRichTextSearchRanges(editor, query, options);
1121
+ if (matches.length === 0) return { activeIndex: -1, count: 0, replaced: 0 };
1122
+ const activeIndex = normalizeSearchIndex(requestedIndex, matches.length);
1123
+ const range = matches[activeIndex];
1124
+ if (!range) return { activeIndex: -1, count: matches.length, replaced: 0 };
1125
+ range.deleteContents();
1126
+ range.insertNode(document.createTextNode(replacement));
1127
+ const next = selectRichTextSearchMatch(editor, query, activeIndex, options);
1128
+ return { ...next, replaced: 1 };
1129
+ }
1130
+ function replaceAllRichTextSearchMatches(editor, query, replacement, options = {}) {
1131
+ const matches = findRichTextSearchRanges(editor, query, options);
1132
+ for (const range of [...matches].reverse()) {
1133
+ range.deleteContents();
1134
+ range.insertNode(document.createTextNode(replacement));
1135
+ }
1136
+ return { activeIndex: -1, count: 0, replaced: matches.length };
1137
+ }
1138
+ function insertRichTextClipboardContent(editor, content) {
1139
+ const rawHtml = content.html?.trim();
1140
+ const safeHtml = rawHtml ? sanitizeRichTextMarkup(rawHtml) : "";
1141
+ const template = document.createElement("template");
1142
+ if (safeHtml.trim()) {
1143
+ template.innerHTML = safeHtml;
1144
+ } else if (content.plainText) {
1145
+ const lines = content.plainText.replace(/\r\n?/g, "\n").split("\n");
1146
+ lines.forEach((line, index) => {
1147
+ if (index > 0) template.content.appendChild(document.createElement("br"));
1148
+ template.content.appendChild(document.createTextNode(line));
1149
+ });
1150
+ }
1151
+ if (!template.content.hasChildNodes()) {
1152
+ return false;
1153
+ }
1154
+ let range = getRichTextEditorRange(editor);
1155
+ if (!range) {
1156
+ focusRichTextEditorEnd(editor);
1157
+ range = getRichTextEditorRange(editor);
1158
+ }
1159
+ if (!range) {
1160
+ return false;
1161
+ }
1162
+ const fragment = template.content.cloneNode(true);
1163
+ const lastNode = fragment.lastChild;
1164
+ range.deleteContents();
1165
+ range.insertNode(fragment);
1166
+ if (lastNode) restoreRichTextCaretAfter(lastNode);
1167
+ return true;
1168
+ }
1169
+ function createRichTextAiAssistantRequest({
1170
+ action,
1171
+ html,
1172
+ providerId,
1173
+ selectedText = ""
1174
+ }) {
1175
+ const normalizedProviderId = providerId?.trim();
1176
+ return {
1177
+ action,
1178
+ document: createRichTextDocumentSnapshot(html),
1179
+ providerId: normalizedProviderId || void 0,
1180
+ selectedText: selectedText.trim()
1181
+ };
1182
+ }
1183
+ function createRichTextAiAssistantSuggestion({
1184
+ action,
1185
+ html,
1186
+ id
1187
+ }) {
1188
+ const normalizedId = id.trim();
1189
+ if (!normalizedId) {
1190
+ throw new Error("Rich text AI assistant suggestion requires an id.");
1191
+ }
1192
+ return {
1193
+ action,
1194
+ document: createRichTextDocumentSnapshot(html),
1195
+ id: normalizedId
1196
+ };
1197
+ }
1198
+ function applyRichTextAiAssistantSuggestion(editor, suggestion, mode) {
1199
+ if (mode === "replace-document") {
1200
+ editor.innerHTML = suggestion.document.html;
1201
+ focusRichTextEditorEnd(editor);
1202
+ return true;
1203
+ }
1204
+ const range = getRichTextEditorRange(editor);
1205
+ if (!range) {
1206
+ return false;
1207
+ }
1208
+ const template = document.createElement("template");
1209
+ template.innerHTML = suggestion.document.html;
1210
+ const fragment = template.content.cloneNode(true);
1211
+ const lastNode = fragment.lastChild;
1212
+ const hasBlockContent = Array.from(template.content.children).some((element) => element.matches("p,h1,h2,h3,pre,blockquote,ul,ol,table"));
1213
+ if (hasBlockContent) {
1214
+ const startBlock = getTopLevelRichTextChild(editor, range.startContainer);
1215
+ const endBlock = getTopLevelRichTextChild(editor, range.endContainer);
1216
+ if (mode === "replace-selection" && startBlock && startBlock === endBlock && rangeCoversElementContents(range, startBlock)) {
1217
+ startBlock.replaceWith(fragment);
1218
+ } else {
1219
+ if (mode === "replace-selection") range.deleteContents();
1220
+ const insertionAnchor = endBlock ?? editor.lastElementChild;
1221
+ if (insertionAnchor) insertionAnchor.after(fragment);
1222
+ else editor.append(fragment);
1223
+ }
1224
+ editor.focus({ preventScroll: true });
1225
+ if (lastNode) restoreRichTextCaretAfter(lastNode);
1226
+ return true;
1227
+ }
1228
+ if (mode === "replace-selection") {
1229
+ range.deleteContents();
1230
+ range.insertNode(fragment);
1231
+ editor.focus({ preventScroll: true });
1232
+ if (lastNode) restoreRichTextCaretAfter(lastNode);
1233
+ return true;
1234
+ }
1235
+ range.collapse(false);
1236
+ range.insertNode(fragment);
1237
+ editor.focus({ preventScroll: true });
1238
+ if (lastNode) restoreRichTextCaretAfter(lastNode);
1239
+ return true;
1240
+ }
1241
+ function getTopLevelRichTextChild(editor, node) {
1242
+ let element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
1243
+ while (element?.parentElement && element.parentElement !== editor) element = element.parentElement;
1244
+ return element && element.parentElement === editor ? element : null;
1245
+ }
1246
+ function rangeCoversElementContents(range, element) {
1247
+ if (element === range.commonAncestorContainer) {
1248
+ return range.startOffset === 0 && range.endOffset === element.childNodes.length;
1249
+ }
1250
+ const contents = document.createRange();
1251
+ contents.selectNodeContents(element);
1252
+ return range.compareBoundaryPoints(Range.START_TO_START, contents) === 0 && range.compareBoundaryPoints(Range.END_TO_END, contents) === 0;
1253
+ }
1254
+ function createRichTextCollaborationPresence(presence) {
1255
+ const documentId = presence.documentId.trim();
1256
+ const userId = presence.userId.trim();
1257
+ const userName = presence.userName.trim();
1258
+ const color = presence.color.trim();
1259
+ if (!documentId) {
1260
+ throw new Error("Rich text collaboration presence requires a documentId.");
1261
+ }
1262
+ if (!userId) {
1263
+ throw new Error("Rich text collaboration presence requires a userId.");
1264
+ }
1265
+ if (!userName) {
1266
+ throw new Error("Rich text collaboration presence requires a userName.");
1267
+ }
1268
+ if (!RICH_TEXT_COLLABORATION_COLOR_PATTERN.test(color)) {
1269
+ throw new Error("Rich text collaboration presence color must be a six-digit hex color.");
1270
+ }
1271
+ return {
1272
+ color,
1273
+ documentId,
1274
+ selection: presence.selection,
1275
+ userId,
1276
+ userName
1277
+ };
1278
+ }
1279
+ function createRichTextCollaborationSnapshot({
1280
+ documentId,
1281
+ localUserId,
1282
+ presences
1283
+ }) {
1284
+ const normalizedDocumentId = documentId.trim();
1285
+ const normalizedLocalUserId = localUserId.trim();
1286
+ if (!normalizedDocumentId) {
1287
+ throw new Error("Rich text collaboration snapshot requires a documentId.");
1288
+ }
1289
+ if (!normalizedLocalUserId) {
1290
+ throw new Error("Rich text collaboration snapshot requires a localUserId.");
1291
+ }
1292
+ return {
1293
+ documentId: normalizedDocumentId,
1294
+ localUserId: normalizedLocalUserId,
1295
+ presences: presences.map(createRichTextCollaborationPresence)
1296
+ };
1297
+ }
1298
+ function resolveRichTextCollaborationPresences(snapshot) {
1299
+ return snapshot.presences.filter((presence) => presence.documentId === snapshot.documentId && presence.userId !== snapshot.localUserId).sort((first, second) => first.userName.localeCompare(second.userName) || first.userId.localeCompare(second.userId));
1300
+ }
1301
+ function readRichTextLocalCollaborationPresence({
1302
+ color,
1303
+ documentId,
1304
+ editor,
1305
+ userId,
1306
+ userName
1307
+ }) {
1308
+ return createRichTextCollaborationPresence({
1309
+ color,
1310
+ documentId,
1311
+ selection: readRichTextSelectionSnapshot(editor),
1312
+ userId,
1313
+ userName
1314
+ });
1315
+ }
1316
+ function getRichTextMentionQuery(editor) {
1317
+ const selection = window.getSelection();
1318
+ if (!selection || selection.rangeCount === 0 || !selection.isCollapsed || !containsRichTextSelection(editor)) {
1319
+ return { active: false, query: "", range: null };
1320
+ }
1321
+ const range = selection.getRangeAt(0);
1322
+ const textNode = range.startContainer.nodeType === Node.TEXT_NODE ? range.startContainer : range.startContainer.childNodes[Math.max(range.startOffset - 1, 0)];
1323
+ if (!textNode || textNode.nodeType !== Node.TEXT_NODE) {
1324
+ return { active: false, query: "", range: null };
1325
+ }
1326
+ const textBeforeCaret = textNode.textContent?.slice(0, range.startOffset) ?? "";
1327
+ const match = /(^|\s)@([\w.-]*)$/.exec(textBeforeCaret);
1328
+ if (!match) {
1329
+ return { active: false, query: "", range: null };
1330
+ }
1331
+ const mentionRange = document.createRange();
1332
+ const prefixLength = match[1]?.length ?? 0;
1333
+ const mentionOffset = match.index + prefixLength;
1334
+ mentionRange.setStart(textNode, mentionOffset);
1335
+ mentionRange.setEnd(textNode, range.startOffset);
1336
+ return {
1337
+ active: true,
1338
+ query: (match[2] ?? "").toLowerCase(),
1339
+ range: mentionRange
1340
+ };
1341
+ }
1342
+ function resolveRichTextMentions(query, mentions) {
1343
+ const normalizedQuery = query.trim().toLowerCase();
1344
+ if (!normalizedQuery) {
1345
+ return [...mentions];
1346
+ }
1347
+ return mentions.filter((mention) => {
1348
+ return mention.id.toLowerCase().includes(normalizedQuery) || mention.label.toLowerCase().includes(normalizedQuery) || Boolean(mention.description?.toLowerCase().includes(normalizedQuery));
1349
+ });
1350
+ }
1351
+ function insertRichTextMention(editor, mention, queryRange = getRichTextMentionQuery(editor).range) {
1352
+ const id = mention.id.trim();
1353
+ const label = mention.label.trim();
1354
+ if (!id || !label) {
1355
+ return false;
1356
+ }
1357
+ const mentionElement = document.createElement("span");
1358
+ mentionElement.setAttribute("data-mention-id", id);
1359
+ mentionElement.setAttribute("data-mention-label", label);
1360
+ mentionElement.textContent = `@${label}`;
1361
+ const trailingSpace = document.createTextNode(" ");
1362
+ const range = queryRange ?? getRichTextEditorRange(editor);
1363
+ if (range) {
1364
+ range.deleteContents();
1365
+ range.insertNode(trailingSpace);
1366
+ range.insertNode(mentionElement);
1367
+ restoreRichTextCaretAfter(trailingSpace);
1368
+ return true;
1369
+ }
1370
+ editor.appendChild(mentionElement);
1371
+ editor.appendChild(trailingSpace);
1372
+ restoreRichTextCaretAfter(trailingSpace);
1373
+ return true;
1374
+ }
1375
+ function getRichTextSlashCommandQuery(editor) {
1376
+ const selection = window.getSelection();
1377
+ if (!selection || selection.rangeCount === 0 || !selection.isCollapsed || !containsRichTextSelection(editor)) {
1378
+ return { active: false, query: "", range: null };
1379
+ }
1380
+ const range = selection.getRangeAt(0);
1381
+ const textNode = range.startContainer.nodeType === Node.TEXT_NODE ? range.startContainer : range.startContainer.childNodes[Math.max(range.startOffset - 1, 0)];
1382
+ if (!textNode || textNode.nodeType !== Node.TEXT_NODE) {
1383
+ return { active: false, query: "", range: null };
1384
+ }
1385
+ const textBeforeCaret = textNode.textContent?.slice(0, range.startOffset) ?? "";
1386
+ const match = /(^|\s)\/([\w-]*)$/.exec(textBeforeCaret);
1387
+ if (!match) {
1388
+ return { active: false, query: "", range: null };
1389
+ }
1390
+ const commandRange = document.createRange();
1391
+ const prefixLength = match[1]?.length ?? 0;
1392
+ const slashOffset = match.index + prefixLength;
1393
+ commandRange.setStart(textNode, slashOffset);
1394
+ commandRange.setEnd(textNode, range.startOffset);
1395
+ return {
1396
+ active: true,
1397
+ query: (match[2] ?? "").toLowerCase(),
1398
+ range: commandRange
1399
+ };
1400
+ }
1401
+ function resolveRichTextSlashCommands(query) {
1402
+ const normalizedQuery = query.trim().toLowerCase();
1403
+ if (!normalizedQuery) {
1404
+ return [...richTextSlashCommandDefinitions];
1405
+ }
1406
+ return richTextSlashCommandDefinitions.filter((definition) => {
1407
+ return definition.label.toLowerCase().includes(normalizedQuery) || definition.keywords.some((keyword) => keyword.includes(normalizedQuery));
1408
+ });
1409
+ }
1410
+ function executeRichTextSlashCommand(editor, command, queryRange = getRichTextSlashCommandQuery(editor).range) {
1411
+ if (queryRange) {
1412
+ queryRange.deleteContents();
1413
+ const selection = window.getSelection();
1414
+ selection?.removeAllRanges();
1415
+ selection?.addRange(queryRange);
1416
+ }
1417
+ if (command === "table") {
1418
+ insertRichTextTable(editor);
1419
+ return true;
1420
+ }
1421
+ if (command === "horizontalRule") {
1422
+ insertRichTextHorizontalRule(editor);
1423
+ return true;
1424
+ }
1425
+ if (command === "paragraph") {
1426
+ applyRichTextBlockFormat(editor, "paragraph");
1427
+ return true;
1428
+ }
1429
+ if (command === "heading1" || command === "heading2" || command === "heading3" || command === "codeBlock") {
1430
+ applyRichTextBlockFormat(editor, command);
1431
+ return true;
1432
+ }
1433
+ if (command === "blockquote") {
1434
+ applyRichTextBlockTag(editor, "blockquote");
1435
+ return true;
1436
+ }
1437
+ if (command === "taskList") {
1438
+ applyRichTextTaskList(editor);
1439
+ return true;
1440
+ }
1441
+ applyRichTextList(editor, command === "bulletedList" ? "ul" : "ol");
1442
+ return true;
1443
+ }
1444
+ function insertRichTextTable(editor, rows = 3, columns = 3) {
1445
+ const table = createRichTextTableElement(rows, columns);
1446
+ insertRichTextElementAtSelection(editor, table);
1447
+ focusRichTextTableCell(table.querySelector("td,th"));
1448
+ }
1449
+ function deleteRichTextTable(editor) {
1450
+ const table = getSelectedRichTextTable(editor);
1451
+ if (!table) {
1452
+ return false;
1453
+ }
1454
+ const paragraph = document.createElement("p");
1455
+ paragraph.appendChild(document.createElement("br"));
1456
+ table.replaceWith(paragraph);
1457
+ restoreRichTextCaretAfter(paragraph);
1458
+ return true;
1459
+ }
1460
+ function addRichTextTableRow(editor) {
1461
+ const context = getSelectedRichTextTableContext(editor);
1462
+ if (!context) {
1463
+ return false;
1464
+ }
1465
+ const nextRow = document.createElement("tr");
1466
+ for (let columnIndex = 0; columnIndex < context.columnCount; columnIndex += 1) {
1467
+ nextRow.appendChild(createRichTextTableCell());
1468
+ }
1469
+ context.row.after(nextRow);
1470
+ focusRichTextTableCell(getRichTextTableCells(nextRow)[context.columnIndex] ?? getRichTextTableCells(nextRow)[0]);
1471
+ return true;
1472
+ }
1473
+ function deleteRichTextTableRow(editor) {
1474
+ const context = getSelectedRichTextTableContext(editor);
1475
+ if (!context) {
1476
+ return false;
1477
+ }
1478
+ if (context.rows.length <= 1) {
1479
+ return deleteRichTextTable(editor);
1480
+ }
1481
+ const nextTarget = context.row.nextElementSibling ?? context.row.previousElementSibling;
1482
+ context.row.remove();
1483
+ focusRichTextTableCell(nextTarget ? getRichTextTableCells(nextTarget)[context.columnIndex] ?? getRichTextTableCells(nextTarget)[0] : null);
1484
+ return true;
1485
+ }
1486
+ function addRichTextTableColumn(editor) {
1487
+ const context = getSelectedRichTextTableContext(editor);
1488
+ if (!context) {
1489
+ return false;
1490
+ }
1491
+ for (const row of context.rows) {
1492
+ const cells = getRichTextTableCells(row);
1493
+ const newCell = createRichTextTableCell();
1494
+ const targetCell = cells[Math.min(context.columnIndex, cells.length - 1)];
1495
+ if (targetCell) {
1496
+ targetCell.after(newCell);
1497
+ } else {
1498
+ row.appendChild(newCell);
1499
+ }
1500
+ }
1501
+ focusRichTextTableCell(getRichTextTableCells(context.row)[context.columnIndex + 1]);
1502
+ return true;
1503
+ }
1504
+ function deleteRichTextTableColumn(editor) {
1505
+ const context = getSelectedRichTextTableContext(editor);
1506
+ if (!context) {
1507
+ return false;
1508
+ }
1509
+ if (context.columnCount <= 1) {
1510
+ return deleteRichTextTable(editor);
1511
+ }
1512
+ for (const row of context.rows) {
1513
+ getRichTextTableCells(row)[context.columnIndex]?.remove();
1514
+ }
1515
+ focusRichTextTableCell(getRichTextTableCells(context.row)[Math.min(context.columnIndex, context.columnCount - 2)]);
1516
+ return true;
1517
+ }
1518
+ function executeRichTextTableCommand(editor, command) {
1519
+ if (command === "insertTable") {
1520
+ insertRichTextTable(editor);
1521
+ return true;
1522
+ }
1523
+ if (command === "deleteTable") {
1524
+ return deleteRichTextTable(editor);
1525
+ }
1526
+ if (command === "addTableRow") {
1527
+ return addRichTextTableRow(editor);
1528
+ }
1529
+ if (command === "deleteTableRow") {
1530
+ return deleteRichTextTableRow(editor);
1531
+ }
1532
+ if (command === "addTableColumn") {
1533
+ return addRichTextTableColumn(editor);
1534
+ }
1535
+ return deleteRichTextTableColumn(editor);
1536
+ }
1537
+ function canExecuteRichTextTableCommand(editor, command) {
1538
+ return command === "insertTable" || getSelectedRichTextTableContext(editor) !== null;
1539
+ }
1540
+ function moveRichTextTableSelection(editor, direction) {
1541
+ const context = getSelectedRichTextTableContext(editor);
1542
+ if (!context) {
1543
+ return { changed: false, handled: false };
1544
+ }
1545
+ getRichTextTableCells(context.row);
1546
+ const flatCells = context.rows.flatMap((row) => getRichTextTableCells(row));
1547
+ let target = null;
1548
+ let changed = false;
1549
+ if (direction === "next-cell" || direction === "right") {
1550
+ target = flatCells[flatCells.indexOf(context.cell) + 1];
1551
+ if (!target && direction === "next-cell") {
1552
+ const newRow = document.createElement("tr");
1553
+ for (let columnIndex = 0; columnIndex < context.columnCount; columnIndex += 1) {
1554
+ newRow.appendChild(createRichTextTableCell());
1555
+ }
1556
+ context.rows[context.rows.length - 1]?.after(newRow);
1557
+ target = getRichTextTableCells(newRow)[0];
1558
+ changed = true;
1559
+ }
1560
+ } else if (direction === "previous-cell" || direction === "left") {
1561
+ target = flatCells[flatCells.indexOf(context.cell) - 1];
1562
+ } else if (direction === "up") {
1563
+ const previousRow = context.rows[context.rows.indexOf(context.row) - 1];
1564
+ target = previousRow ? getRichTextTableCells(previousRow)[context.columnIndex] : null;
1565
+ } else {
1566
+ const nextRow = context.rows[context.rows.indexOf(context.row) + 1];
1567
+ target = nextRow ? getRichTextTableCells(nextRow)[context.columnIndex] : null;
1568
+ }
1569
+ if (!target) {
1570
+ return { changed: false, handled: true };
1571
+ }
1572
+ focusRichTextTableCell(target);
1573
+ return { changed, handled: true };
1574
+ }
1575
+ function handleRichTextTableKeyboardNavigation(editor, event) {
1576
+ if (event.key === "Tab") {
1577
+ const result = moveRichTextTableSelection(editor, event.shiftKey ? "previous-cell" : "next-cell");
1578
+ if (result.handled) {
1579
+ event.preventDefault();
1580
+ }
1581
+ return result;
1582
+ }
1583
+ if (event.key === "ArrowUp" || event.key === "ArrowDown" || event.key === "ArrowLeft" || event.key === "ArrowRight") {
1584
+ const directionByKey = {
1585
+ ArrowDown: "down",
1586
+ ArrowLeft: "left",
1587
+ ArrowRight: "right",
1588
+ ArrowUp: "up"
1589
+ };
1590
+ const result = moveRichTextTableSelection(editor, directionByKey[event.key]);
1591
+ if (result.handled) {
1592
+ event.preventDefault();
1593
+ }
1594
+ return result;
1595
+ }
1596
+ return { changed: false, handled: false };
1597
+ }
1598
+ function executeRichTextDomCommand(editor, command) {
1599
+ const definition = getRichTextCommandDefinition(command);
1600
+ if (!definition) {
1601
+ return false;
1602
+ }
1603
+ if (definition.inlineTagName) {
1604
+ applyRichTextInlineTag(editor, definition.inlineTagName);
1605
+ return true;
1606
+ }
1607
+ if (definition.listTagName) {
1608
+ applyRichTextList(editor, definition.listTagName);
1609
+ return true;
1610
+ }
1611
+ if (definition.taskList) {
1612
+ applyRichTextTaskList(editor);
1613
+ return true;
1614
+ }
1615
+ if (definition.blockTagName) {
1616
+ applyRichTextBlockTag(editor, definition.blockTagName);
1617
+ return true;
1618
+ }
1619
+ if (definition.alignment) {
1620
+ applyRichTextAlignment(editor, definition.alignment);
1621
+ return true;
1622
+ }
1623
+ if (command === "clearFormatting") {
1624
+ clearRichTextFormatting(editor);
1625
+ return true;
1626
+ }
1627
+ if (command === "horizontalRule") {
1628
+ insertRichTextHorizontalRule(editor);
1629
+ return true;
1630
+ }
1631
+ return false;
1632
+ }
1633
+ function readRichTextEditorState(editor) {
1634
+ const activeCommands = /* @__PURE__ */ new Set();
1635
+ const selectedElement = getSelectionElement(editor);
1636
+ const block = selectedElement?.closest(richTextBlockSelector);
1637
+ const firstBlock = firstEditableBlock(editor);
1638
+ const blockTagName = block?.tagName.toLowerCase() ?? firstBlock?.tagName.toLowerCase() ?? "p";
1639
+ const alignment = readAlignment(findAlignedBlock(editor, selectedElement) ?? block ?? firstBlock);
1640
+ const blockFormat = richTextBlockFormatByTagName[blockTagName] ?? "paragraph";
1641
+ if (selectedElement?.closest("strong,b")) activeCommands.add("bold");
1642
+ if (selectedElement?.closest("em,i")) activeCommands.add("italic");
1643
+ if (selectedElement?.closest("u")) activeCommands.add("underline");
1644
+ if (selectedElement?.closest("s")) activeCommands.add("strike");
1645
+ if (selectedElement?.closest("code")) activeCommands.add("inlineCode");
1646
+ if (selectedElement?.closest("mark")) activeCommands.add("highlight");
1647
+ if (selectedElement?.closest("sub")) activeCommands.add("subscript");
1648
+ if (selectedElement?.closest("sup")) activeCommands.add("superscript");
1649
+ if (selectedElement?.closest("a")) activeCommands.add("link");
1650
+ const selectedUnorderedList = selectedElement?.closest("ul");
1651
+ if (selectedUnorderedList?.getAttribute("data-task-list") === "true") activeCommands.add("taskList");
1652
+ else if (selectedUnorderedList) activeCommands.add("bulletedList");
1653
+ if (selectedElement?.closest("ol")) activeCommands.add("numberedList");
1654
+ if (selectedElement?.closest("blockquote")) activeCommands.add("blockquote");
1655
+ activeCommands.add(richTextAlignmentCommandByValue[alignment]);
1656
+ return {
1657
+ activeCommands,
1658
+ alignment,
1659
+ blockFormat: selectedElement?.closest("blockquote") ? "paragraph" : blockFormat
1660
+ };
1661
+ }
1662
+ function getSelectionElement(editor) {
1663
+ const selection = window.getSelection();
1664
+ const node = selection?.anchorNode;
1665
+ if (!node || !editor.contains(node)) {
1666
+ return firstEditableBlock(editor);
1667
+ }
1668
+ return node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
1669
+ }
1670
+ function wrapRichTextTaskItem(item, checked = false, text) {
1671
+ const label = document.createElement("label");
1672
+ const checkbox = document.createElement("input");
1673
+ checkbox.setAttribute("type", "checkbox");
1674
+ checkbox.setAttribute("contenteditable", "false");
1675
+ checkbox.checked = checked;
1676
+ if (checked) checkbox.setAttribute("checked", "");
1677
+ if (text !== void 0) {
1678
+ label.append(checkbox, document.createTextNode(text));
1679
+ } else {
1680
+ const hasContent = item.hasChildNodes();
1681
+ const content = document.createDocumentFragment();
1682
+ while (item.firstChild) content.appendChild(item.firstChild);
1683
+ label.append(checkbox, content);
1684
+ if (!hasContent) label.appendChild(document.createElement("br"));
1685
+ }
1686
+ item.setAttribute("data-checked", checked ? "true" : "false");
1687
+ item.replaceChildren(label);
1688
+ }
1689
+ function unwrapRichTextTaskItem(item) {
1690
+ const label = Array.from(item.children).find((child) => child.tagName.toLowerCase() === "label");
1691
+ const checkbox = label?.querySelector(':scope > input[type="checkbox"]') ?? item.querySelector('input[type="checkbox"]');
1692
+ checkbox?.remove();
1693
+ if (label) {
1694
+ const content = document.createDocumentFragment();
1695
+ while (label.firstChild) content.appendChild(label.firstChild);
1696
+ item.replaceChildren(content);
1697
+ }
1698
+ item.removeAttribute("data-checked");
1699
+ }
1700
+ function findRichTextSearchRanges(editor, query, options) {
1701
+ const normalizedQuery = query.trim();
1702
+ if (!normalizedQuery || normalizedQuery.length > 256) return [];
1703
+ const needle = options.matchCase ? normalizedQuery : normalizedQuery.toLocaleLowerCase();
1704
+ const ranges = [];
1705
+ const walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT, {
1706
+ acceptNode: (node2) => node2.parentElement?.closest('[contenteditable="false"],script,style') ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT
1707
+ });
1708
+ let node = walker.nextNode();
1709
+ while (node && ranges.length < 1e4) {
1710
+ const rawValue = node.data;
1711
+ const haystack = options.matchCase ? rawValue : rawValue.toLocaleLowerCase();
1712
+ let offset = 0;
1713
+ while (offset <= haystack.length - needle.length && ranges.length < 1e4) {
1714
+ const matchIndex = haystack.indexOf(needle, offset);
1715
+ if (matchIndex < 0) break;
1716
+ const matchEnd = matchIndex + needle.length;
1717
+ if (!options.wholeWord || isWholeWordMatch(rawValue, matchIndex, matchEnd)) {
1718
+ const range = document.createRange();
1719
+ range.setStart(node, matchIndex);
1720
+ range.setEnd(node, matchEnd);
1721
+ ranges.push(range);
1722
+ }
1723
+ offset = matchEnd;
1724
+ }
1725
+ node = walker.nextNode();
1726
+ }
1727
+ return ranges;
1728
+ }
1729
+ function normalizeSearchIndex(index, matchCount) {
1730
+ return (Math.trunc(index) % matchCount + matchCount) % matchCount;
1731
+ }
1732
+ function isWholeWordMatch(value, start, end) {
1733
+ return !isRichTextWordCharacter(value[start - 1]) && !isRichTextWordCharacter(value[end]);
1734
+ }
1735
+ function isRichTextWordCharacter(value) {
1736
+ return Boolean(value && /[\p{L}\p{N}_]/u.test(value));
1737
+ }
1738
+ function createRichTextTableElement(rows, columns) {
1739
+ const table = document.createElement("table");
1740
+ const body = document.createElement("tbody");
1741
+ const rowCount = clampTableSize(rows);
1742
+ const columnCount = clampTableSize(columns);
1743
+ for (let rowIndex = 0; rowIndex < rowCount; rowIndex += 1) {
1744
+ const row = document.createElement("tr");
1745
+ for (let columnIndex = 0; columnIndex < columnCount; columnIndex += 1) {
1746
+ row.appendChild(createRichTextTableCell());
1747
+ }
1748
+ body.appendChild(row);
1749
+ }
1750
+ table.appendChild(body);
1751
+ return table;
1752
+ }
1753
+ function createRichTextTableCell() {
1754
+ const cell = document.createElement("td");
1755
+ cell.appendChild(document.createElement("br"));
1756
+ return cell;
1757
+ }
1758
+ function clampTableSize(value) {
1759
+ if (!Number.isFinite(value)) {
1760
+ return 3;
1761
+ }
1762
+ return Math.min(Math.max(Math.trunc(value), 1), 20);
1763
+ }
1764
+ function getSelectedRichTextTable(editor) {
1765
+ const selectedElement = getExplicitSelectionElement(editor);
1766
+ const table = selectedElement?.closest("table");
1767
+ return table && editor.contains(table) ? table : null;
1768
+ }
1769
+ function getSelectedRichTextTableContext(editor) {
1770
+ const selectedElement = getExplicitSelectionElement(editor);
1771
+ const selectedCell = selectedElement?.closest("td,th");
1772
+ const cell = selectedCell && editor.contains(selectedCell) ? selectedCell : null;
1773
+ const row = cell?.parentElement;
1774
+ const table = row?.closest("table");
1775
+ if (!cell || !row || !table || !editor.contains(table)) {
1776
+ return null;
1777
+ }
1778
+ const rows = Array.from(table.querySelectorAll("tr"));
1779
+ const cells = getRichTextTableCells(row);
1780
+ return {
1781
+ cell,
1782
+ columnCount: Math.max(...rows.map((candidate) => getRichTextTableCells(candidate).length)),
1783
+ columnIndex: Math.max(cells.indexOf(cell), 0),
1784
+ row,
1785
+ rows,
1786
+ table
1787
+ };
1788
+ }
1789
+ function getExplicitSelectionElement(editor) {
1790
+ const range = getRichTextEditorRange(editor);
1791
+ if (!range) return null;
1792
+ const node = range.startContainer;
1793
+ return node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
1794
+ }
1795
+ function getRichTextTableCells(row) {
1796
+ return Array.from(row.children).filter((child) => {
1797
+ const tagName = child.tagName.toLowerCase();
1798
+ return tagName === "td" || tagName === "th";
1799
+ });
1800
+ }
1801
+ function focusRichTextTableCell(cell) {
1802
+ if (!cell) {
1803
+ return;
1804
+ }
1805
+ const selection = window.getSelection();
1806
+ if (!selection) {
1807
+ return;
1808
+ }
1809
+ const range = document.createRange();
1810
+ range.selectNodeContents(cell);
1811
+ range.collapse(false);
1812
+ selection.removeAllRanges();
1813
+ selection.addRange(range);
1814
+ }
1815
+ function getSelectedBlockElements(editor) {
1816
+ const range = getRichTextEditorRange(editor);
1817
+ if (!range) {
1818
+ const block = firstEditableBlock(editor);
1819
+ return block ? [block] : [];
1820
+ }
1821
+ if (range.collapsed) {
1822
+ const selectedElement = range.startContainer.nodeType === Node.ELEMENT_NODE ? range.startContainer : range.startContainer.parentElement;
1823
+ const block = selectedElement?.closest(richTextBlockSelector);
1824
+ return block && editor.contains(block) ? [block] : [];
1825
+ }
1826
+ const intersectingBlocks = Array.from(editor.querySelectorAll(richTextBlockSelector)).filter((candidate) => {
1827
+ try {
1828
+ return range.intersectsNode(candidate);
1829
+ } catch {
1830
+ return false;
1831
+ }
1832
+ });
1833
+ return intersectingBlocks.filter((candidate) => !intersectingBlocks.some((other) => other !== candidate && candidate.contains(other)));
1834
+ }
1835
+ function getClosestRichTextAttributeWrapper(editor, node, attribute) {
1836
+ const element = node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement;
1837
+ const wrapper = element?.closest(`[${attribute}]`);
1838
+ return wrapper && editor.contains(wrapper) ? wrapper : null;
1839
+ }
1840
+ function readRichTextAttribute(editor, node, attribute, fallback) {
1841
+ if (!node) return fallback;
1842
+ return getClosestRichTextAttributeWrapper(editor, node, attribute)?.getAttribute(attribute) ?? fallback;
1843
+ }
1844
+ function unwrapRichTextInlineElement(element) {
1845
+ const fragment = document.createDocumentFragment();
1846
+ while (element.firstChild) fragment.appendChild(element.firstChild);
1847
+ element.replaceWith(fragment);
1848
+ }
1849
+ function removeRichTextAttributeFromRange(editor, range, attribute) {
1850
+ const startWrapper = getClosestRichTextAttributeWrapper(editor, range.startContainer, attribute);
1851
+ const endWrapper = getClosestRichTextAttributeWrapper(editor, range.endContainer, attribute);
1852
+ if (!startWrapper || startWrapper !== endWrapper) return;
1853
+ if (rangeCoversElementContents(range, startWrapper)) {
1854
+ startWrapper.removeAttribute(attribute);
1855
+ if (startWrapper.attributes.length === 0) unwrapRichTextInlineElement(startWrapper);
1856
+ return;
1857
+ }
1858
+ const beforeRange = document.createRange();
1859
+ beforeRange.selectNodeContents(startWrapper);
1860
+ beforeRange.setEnd(range.startContainer, range.startOffset);
1861
+ const afterRange = document.createRange();
1862
+ afterRange.selectNodeContents(startWrapper);
1863
+ afterRange.setStart(range.endContainer, range.endOffset);
1864
+ const beforeContent = beforeRange.cloneContents();
1865
+ const selectedContent = range.cloneContents();
1866
+ const afterContent = afterRange.cloneContents();
1867
+ const replacement = document.createDocumentFragment();
1868
+ if (fragmentHasContent(beforeContent)) {
1869
+ const beforeWrapper = startWrapper.cloneNode(false);
1870
+ beforeWrapper.appendChild(beforeContent);
1871
+ replacement.appendChild(beforeWrapper);
1872
+ }
1873
+ const selectedWrapper = startWrapper.cloneNode(false);
1874
+ selectedWrapper.removeAttribute(attribute);
1875
+ selectedWrapper.appendChild(selectedContent);
1876
+ const firstSelected = selectedWrapper.firstChild;
1877
+ const lastSelected = selectedWrapper.lastChild;
1878
+ if (selectedWrapper.attributes.length === 0) {
1879
+ while (selectedWrapper.firstChild) replacement.appendChild(selectedWrapper.firstChild);
1880
+ } else {
1881
+ replacement.appendChild(selectedWrapper);
1882
+ }
1883
+ if (fragmentHasContent(afterContent)) {
1884
+ const afterWrapper = startWrapper.cloneNode(false);
1885
+ afterWrapper.appendChild(afterContent);
1886
+ replacement.appendChild(afterWrapper);
1887
+ }
1888
+ startWrapper.replaceWith(replacement);
1889
+ const selection = window.getSelection();
1890
+ if (!selection || !firstSelected || !lastSelected) return;
1891
+ const nextRange = document.createRange();
1892
+ nextRange.setStartBefore(firstSelected);
1893
+ nextRange.setEndAfter(lastSelected);
1894
+ selection.removeAllRanges();
1895
+ selection.addRange(nextRange);
1896
+ }
1897
+ function findSharedInlineWrapper(editor, range, tagName) {
1898
+ const selector = tagName.toLowerCase();
1899
+ const startElement = range.startContainer.nodeType === Node.ELEMENT_NODE ? range.startContainer : range.startContainer.parentElement;
1900
+ const endElement = range.endContainer.nodeType === Node.ELEMENT_NODE ? range.endContainer : range.endContainer.parentElement;
1901
+ const startWrapper = startElement?.closest(selector);
1902
+ const endWrapper = endElement?.closest(selector);
1903
+ return startWrapper && startWrapper === endWrapper && editor.contains(startWrapper) ? startWrapper : null;
1904
+ }
1905
+ function removeInlineWrapperFromRange(wrapper, range) {
1906
+ const beforeRange = document.createRange();
1907
+ beforeRange.selectNodeContents(wrapper);
1908
+ beforeRange.setEnd(range.startContainer, range.startOffset);
1909
+ const afterRange = document.createRange();
1910
+ afterRange.selectNodeContents(wrapper);
1911
+ afterRange.setStart(range.endContainer, range.endOffset);
1912
+ const beforeContent = beforeRange.cloneContents();
1913
+ const selectedContent = range.cloneContents();
1914
+ const afterContent = afterRange.cloneContents();
1915
+ const replacement = document.createDocumentFragment();
1916
+ if (fragmentHasContent(beforeContent)) {
1917
+ const beforeWrapper = wrapper.cloneNode(false);
1918
+ beforeWrapper.appendChild(beforeContent);
1919
+ replacement.appendChild(beforeWrapper);
1920
+ }
1921
+ const selectedNodes = Array.from(selectedContent.childNodes);
1922
+ if (selectedNodes.length > 0) {
1923
+ replacement.appendChild(selectedContent);
1924
+ } else {
1925
+ selectedNodes.push(replacement.appendChild(document.createTextNode("")));
1926
+ }
1927
+ if (fragmentHasContent(afterContent)) {
1928
+ const afterWrapper = wrapper.cloneNode(false);
1929
+ afterWrapper.appendChild(afterContent);
1930
+ replacement.appendChild(afterWrapper);
1931
+ }
1932
+ wrapper.replaceWith(replacement);
1933
+ const firstSelected = selectedNodes[0];
1934
+ const lastSelected = selectedNodes[selectedNodes.length - 1];
1935
+ const selection = window.getSelection();
1936
+ if (!selection || !firstSelected || !lastSelected) return;
1937
+ const nextRange = document.createRange();
1938
+ if (range.collapsed && firstSelected.nodeType === Node.TEXT_NODE) {
1939
+ nextRange.setStart(firstSelected, 0);
1940
+ nextRange.collapse(true);
1941
+ } else {
1942
+ nextRange.setStartBefore(firstSelected);
1943
+ nextRange.setEndAfter(lastSelected);
1944
+ }
1945
+ selection.removeAllRanges();
1946
+ selection.addRange(nextRange);
1947
+ }
1948
+ function fragmentHasContent(fragment) {
1949
+ return fragment.childNodes.length > 0 && (fragment.textContent !== "" || Boolean(fragment.querySelector("br")));
1950
+ }
1951
+ function ensureEditableBlock(editor) {
1952
+ const existing = firstEditableBlock(editor);
1953
+ if (existing) {
1954
+ return existing;
1955
+ }
1956
+ const paragraph = document.createElement("p");
1957
+ paragraph.textContent = editor.textContent ?? "";
1958
+ editor.innerHTML = "";
1959
+ editor.appendChild(paragraph);
1960
+ return paragraph;
1961
+ }
1962
+ function isDirectRichTextEditorBlock(editor, block) {
1963
+ return block.parentElement === editor && block.matches(richTextBlockSelector);
1964
+ }
1965
+ function firstEditableBlock(editor) {
1966
+ return editor.querySelector(richTextBlockSelector);
1967
+ }
1968
+ function replaceRichTextBlock(block, tagName) {
1969
+ const nextBlock = document.createElement(tagName);
1970
+ if (tagName === "pre") {
1971
+ const code = document.createElement("code");
1972
+ code.textContent = block.textContent ?? "";
1973
+ nextBlock.appendChild(code);
1974
+ } else {
1975
+ while (block.firstChild) nextBlock.appendChild(block.firstChild);
1976
+ }
1977
+ if (block.matches("td,th,li")) {
1978
+ block.replaceChildren(nextBlock);
1979
+ return nextBlock;
1980
+ }
1981
+ block.replaceWith(nextBlock);
1982
+ return nextBlock;
1983
+ }
1984
+ function replaceElementTag(element, tagName) {
1985
+ if (element.tagName.toLowerCase() === tagName) return element;
1986
+ const replacement = document.createElement(tagName);
1987
+ for (const attribute of Array.from(element.attributes)) {
1988
+ replacement.setAttribute(attribute.name, attribute.value);
1989
+ }
1990
+ while (element.firstChild) replacement.appendChild(element.firstChild);
1991
+ element.replaceWith(replacement);
1992
+ return replacement;
1993
+ }
1994
+ function findAlignedBlock(editor, element) {
1995
+ let current = element;
1996
+ while (current && current !== editor) {
1997
+ if (current.matches(richTextBlockSelector) && current.hasAttribute("data-align")) {
1998
+ return current;
1999
+ }
2000
+ current = current.parentElement;
2001
+ }
2002
+ return null;
2003
+ }
2004
+ function readAlignment(block) {
2005
+ const value = block?.getAttribute("data-align");
2006
+ if (value === "center" || value === "right" || value === "justify") {
2007
+ return value;
2008
+ }
2009
+ return "left";
2010
+ }
2011
+ function readRichTextSelectionSnapshot(editor) {
2012
+ const selection = window.getSelection();
2013
+ if (!selection || selection.rangeCount === 0 || !containsRichTextSelection(editor)) {
2014
+ return null;
2015
+ }
2016
+ const anchorPath = readNodePath(editor, selection.anchorNode);
2017
+ const focusPath = readNodePath(editor, selection.focusNode);
2018
+ if (!anchorPath || !focusPath) {
2019
+ return null;
2020
+ }
2021
+ return {
2022
+ anchorOffset: selection.anchorOffset,
2023
+ anchorPath,
2024
+ collapsed: selection.isCollapsed,
2025
+ direction: "none",
2026
+ focusOffset: selection.focusOffset,
2027
+ focusPath
2028
+ };
2029
+ }
2030
+ function readNodePath(root, node) {
2031
+ if (!node || !root.contains(node)) {
2032
+ return null;
2033
+ }
2034
+ const path = [];
2035
+ let current = node;
2036
+ while (current && current !== root) {
2037
+ const parent = current.parentNode;
2038
+ if (!parent) {
2039
+ return null;
2040
+ }
2041
+ path.unshift(Array.prototype.indexOf.call(parent.childNodes, current));
2042
+ current = parent;
2043
+ }
2044
+ return path;
2045
+ }
2046
+ function replaceRichTextEditorHtml(editor, html) {
2047
+ const selection = editor.ownerDocument.getSelection();
2048
+ const inside = selection?.anchorNode && selection.focusNode && editor.contains(selection.anchorNode) && editor.contains(selection.focusNode);
2049
+ const before = editor.textContent ?? "";
2050
+ const offset = (node, point) => {
2051
+ const range = editor.ownerDocument.createRange();
2052
+ range.selectNodeContents(editor);
2053
+ range.setEnd(node, point);
2054
+ return range.toString().length;
2055
+ };
2056
+ const anchor = inside ? offset(selection.anchorNode, selection.anchorOffset) : null;
2057
+ const focus = inside ? offset(selection.focusNode, selection.focusOffset) : null;
2058
+ editor.innerHTML = createRichTextEditingHtml(html);
2059
+ if (anchor === null || focus === null || !selection) return null;
2060
+ const after = editor.textContent ?? "";
2061
+ let prefix = 0, suffix = 0;
2062
+ while (prefix < before.length && prefix < after.length && before[prefix] === after[prefix]) prefix++;
2063
+ while (suffix < before.length - prefix && suffix < after.length - prefix && before[before.length - 1 - suffix] === after[after.length - 1 - suffix]) suffix++;
2064
+ const translate = (point) => point <= prefix ? point : point >= before.length - suffix ? point + after.length - before.length : after.length - suffix;
2065
+ const resolve = (point) => {
2066
+ const walker = editor.ownerDocument.createTreeWalker(editor, 4);
2067
+ let node = walker.nextNode(), remaining = Math.max(0, point), last = editor;
2068
+ while (node) {
2069
+ last = node;
2070
+ const length = node.textContent?.length ?? 0;
2071
+ if (remaining <= length) return [node, remaining];
2072
+ remaining -= length;
2073
+ node = walker.nextNode();
2074
+ }
2075
+ return last === editor ? [editor, editor.childNodes.length] : [last, last.textContent?.length ?? 0];
2076
+ };
2077
+ const start = resolve(translate(anchor)), end = resolve(translate(focus));
2078
+ selection.setBaseAndExtent(start[0], start[1], end[0], end[1]);
2079
+ return selection.rangeCount ? selection.getRangeAt(0).cloneRange() : null;
2080
+ }
2081
+
2082
+ export { addRichTextTableColumn, addRichTextTableRow, applyRichTextAiAssistantSuggestion, applyRichTextAlignment, applyRichTextBlockFormat, applyRichTextBlockTag, applyRichTextInlineAttribute, applyRichTextInlineTag, applyRichTextLineHeight, applyRichTextLink, applyRichTextList, applyRichTextTaskList, canExecuteRichTextTableCommand, clearRichTextFormatting, cloneRichTextEditorRange, containsRichTextSelection, createRichTextAiAssistantRequest, createRichTextAiAssistantSuggestion, createRichTextCollaborationPresence, createRichTextCollaborationSnapshot, createRichTextEditingHtml, deleteRichTextBlock, deleteRichTextTable, deleteRichTextTableColumn, deleteRichTextTableRow, duplicateRichTextBlock, executeRichTextDomCommand, executeRichTextSlashCommand, executeRichTextTableCommand, focusRichTextEditorEnd, getRichTextEditorRange, getRichTextMentionQuery, getRichTextSlashCommandQuery, getSelectedRichText, handleRichTextTableKeyboardNavigation, insertRichTextClipboardContent, insertRichTextElementAtSelection, insertRichTextHorizontalRule, insertRichTextImage, insertRichTextMention, insertRichTextParagraphAfter, insertRichTextTable, insertRichTextVideo, moveRichTextBlock, moveRichTextTableSelection, readRichTextEditorState, readRichTextLocalCollaborationPresence, readRichTextTypographyState, reorderRichTextBlock, replaceAllRichTextSearchMatches, replaceRichTextEditorHtml, replaceRichTextSearchMatch, resolveRichTextCollaborationPresences, resolveRichTextExportImages, resolveRichTextMentions, resolveRichTextSlashCommands, restoreRichTextCaretAfter, restoreRichTextEditorRange, richTextSlashCommandDefinitions, selectRichTextSearchMatch };
2083
+ //# sourceMappingURL=dom.mjs.map
2084
+ //# sourceMappingURL=dom.mjs.map