react-smart-copy 1.18.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/rich.cjs CHANGED
@@ -2,6 +2,8 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const require_errors = require("./chunks/errors-BwOF6T_M.cjs");
4
4
  const require_url = require("./chunks/url-D4PGsRm8.cjs");
5
+ const require_inert_html = require("./chunks/inert-html-DyxjWDok.cjs");
6
+ const require_url$1 = require("./chunks/url-B9jdFGQy.cjs");
5
7
  const require_contrast = require("./chunks/contrast-C6CVklEI.cjs");
6
8
  //#region src/rich/policy.ts
7
9
  /**
@@ -226,7 +228,7 @@ const TABLE_PARTS = /* @__PURE__ */ new Set([
226
228
  "thead",
227
229
  "tr"
228
230
  ]);
229
- const HEADINGS = /* @__PURE__ */ new Set([
231
+ const HEADINGS$1 = /* @__PURE__ */ new Set([
230
232
  "h1",
231
233
  "h2",
232
234
  "h3",
@@ -630,7 +632,7 @@ const VOID = /* @__PURE__ */ new Set([
630
632
  ]);
631
633
  const BLOCK_DISPLAY = /^(?:block|flex|grid|flow-root|list-item|table)$/;
632
634
  const DATA_IMAGE = /^data:image\/(?:png|jpeg|gif|webp);base64,[a-z\d+/]+=*$/i;
633
- function positive(value, fallback, name) {
635
+ function positive$1(value, fallback, name) {
634
636
  if (value === void 0) return fallback;
635
637
  if (Number.isInteger(value) && value > 0) return value;
636
638
  throw require_errors.copyFailure("invalid-payload", `\`${name}\` must be a positive integer.`);
@@ -661,7 +663,7 @@ var Builder = class {
661
663
  this.elements = 0;
662
664
  this.size = 0;
663
665
  this.implied = /* @__PURE__ */ new WeakSet();
664
- this.scheme = (raw) => /^\s*([a-z][a-z\d+.-]*):/i.exec(raw ?? "")?.[1]?.toLowerCase() ?? "relative";
666
+ this.scheme = (raw) => /^\s*([a-z][a-z\d+.-]*):/i.exec((raw ?? "").replace(/[\t\n\r]/g, ""))?.[1]?.toLowerCase() ?? "relative";
665
667
  const baseOption = base === void 0 ? {} : { base };
666
668
  this.resolveLink = require_url.linkUrlResolver({
667
669
  ...baseOption,
@@ -806,7 +808,7 @@ var Builder = class {
806
808
  return;
807
809
  }
808
810
  if (name === "p" && holdsBlocks(source)) name = "div";
809
- if (HEADINGS.has(name) && HEADINGS.has(parentTag)) name = "span";
811
+ if (HEADINGS$1.has(name) && HEADINGS$1.has(parentTag)) name = "span";
810
812
  if ((name === "li" || name === "dd" || name === "dt") && closesItem(name, parent)) name = "div";
811
813
  if (name === "div" && PHRASING.has(parentTag)) name = "span";
812
814
  if (name === "a" && insideLink(parent)) name = "span";
@@ -863,7 +865,7 @@ var Builder = class {
863
865
  function domFor(source) {
864
866
  if (typeof source === "string") {
865
867
  if (typeof DOMParser === "undefined") throw require_errors.copyFailure("unsupported", "Reading HTML text needs a DOM (DOMParser); pass a DOM node, or use a browser or jsdom.");
866
- const doc = new DOMParser().parseFromString(`<!doctype html><body>${source}`, "text/html");
868
+ const doc = require_inert_html.parseInertHtml(`<!doctype html><body>${source}`);
867
869
  return {
868
870
  doc,
869
871
  root: doc.body,
@@ -929,7 +931,7 @@ function prepareRich(source, options = {}) {
929
931
  throw require_errors.copyFailure("invalid-payload", `\`ignore\` is not a valid CSS selector: ${options.ignore}`, cause);
930
932
  }
931
933
  const out = doc.implementation.createHTMLDocument("");
932
- const builder = new Builder(out, options, mode, computed, colors, options.ignore ?? null, positive(options.maxElements, 1e4, "maxElements"), positive(options.maxLength, 1e6, "maxLength"), options.base ?? (doc.baseURI === "about:blank" ? void 0 : doc.baseURI));
934
+ const builder = new Builder(out, options, mode, computed, colors, options.ignore ?? null, positive$1(options.maxElements, 1e4, "maxElements"), positive$1(options.maxLength, 1e6, "maxLength"), options.base ?? (doc.baseURI === "about:blank" ? void 0 : doc.baseURI));
933
935
  const container = out.createElement("div");
934
936
  if (typeof source === "string") builder.children(root, container, ROOT_PARENT, page, null);
935
937
  else builder.node(root, container, ROOT_PARENT, page, range, true);
@@ -1000,6 +1002,1095 @@ function richTransform(options = {}) {
1000
1002
  };
1001
1003
  }
1002
1004
  //#endregion
1005
+ //#region src/rich/paste.ts
1006
+ /** Every format, in the order the docs list them. */
1007
+ const RICH_PASTE_FORMATS = [
1008
+ "bold",
1009
+ "italic",
1010
+ "underline",
1011
+ "strike",
1012
+ "code",
1013
+ "superscript",
1014
+ "subscript",
1015
+ "link",
1016
+ "image",
1017
+ "heading",
1018
+ "list",
1019
+ "quote",
1020
+ "codeBlock",
1021
+ "table",
1022
+ "rule"
1023
+ ];
1024
+ const STRONG = 1;
1025
+ const EM = 2;
1026
+ const UNDERLINE = 4;
1027
+ const STRIKE = 8;
1028
+ const CODE = 16;
1029
+ const SUP = 32;
1030
+ const SUB = 64;
1031
+ /** Inline formats, outermost first: the fixed order makes the output canonical. */
1032
+ const INLINE = [
1033
+ [
1034
+ STRONG,
1035
+ "strong",
1036
+ "bold"
1037
+ ],
1038
+ [
1039
+ EM,
1040
+ "em",
1041
+ "italic"
1042
+ ],
1043
+ [
1044
+ UNDERLINE,
1045
+ "u",
1046
+ "underline"
1047
+ ],
1048
+ [
1049
+ STRIKE,
1050
+ "s",
1051
+ "strike"
1052
+ ],
1053
+ [
1054
+ CODE,
1055
+ "code",
1056
+ "code"
1057
+ ],
1058
+ [
1059
+ SUP,
1060
+ "sup",
1061
+ "superscript"
1062
+ ],
1063
+ [
1064
+ SUB,
1065
+ "sub",
1066
+ "subscript"
1067
+ ]
1068
+ ];
1069
+ const TAG_BITS = {
1070
+ b: STRONG,
1071
+ strong: STRONG,
1072
+ i: EM,
1073
+ em: EM,
1074
+ cite: EM,
1075
+ dfn: EM,
1076
+ var: EM,
1077
+ u: UNDERLINE,
1078
+ ins: UNDERLINE,
1079
+ s: STRIKE,
1080
+ strike: STRIKE,
1081
+ del: STRIKE,
1082
+ code: CODE,
1083
+ kbd: CODE,
1084
+ samp: CODE,
1085
+ tt: CODE,
1086
+ sup: SUP,
1087
+ sub: SUB
1088
+ };
1089
+ const MONOSPACE = /\b(monospace|courier|consolas|menlo|monaco|source code pro|roboto mono|fira (code|mono)|jetbrains mono|sf mono|cascadia|ubuntu mono|lucida console|inconsolata)\b/;
1090
+ /** Inline CSS, lower-cased. */
1091
+ function styleOf(element) {
1092
+ const map = /* @__PURE__ */ new Map();
1093
+ for (const declaration of (element.getAttribute("style") ?? "").split(";")) {
1094
+ const colon = declaration.indexOf(":");
1095
+ if (colon > 0) map.set(declaration.slice(0, colon).trim().toLowerCase(), declaration.slice(colon + 1).trim().toLowerCase());
1096
+ }
1097
+ return map;
1098
+ }
1099
+ /** Formats after this element: its tag first, then its inline CSS, which wins (Google Docs, Word). */
1100
+ function bitsOf(bits, tag, style) {
1101
+ let next = bits | (TAG_BITS[tag] ?? 0);
1102
+ const weight = style.get("font-weight");
1103
+ if (weight !== void 0) {
1104
+ const numeric = Number.parseInt(weight, 10);
1105
+ if (weight === "bold" || weight === "bolder" || numeric >= 600) next |= STRONG;
1106
+ else if (weight === "normal" || weight === "lighter" || numeric > 0) next &= -2;
1107
+ }
1108
+ const fontStyle = style.get("font-style");
1109
+ if (fontStyle === "italic" || fontStyle === "oblique") next |= EM;
1110
+ else if (fontStyle === "normal") next &= -3;
1111
+ const decoration = style.get("text-decoration-line") ?? style.get("text-decoration");
1112
+ if (decoration !== void 0) {
1113
+ if (decoration.includes("underline")) next |= UNDERLINE;
1114
+ if (decoration.includes("line-through")) next |= STRIKE;
1115
+ if (decoration === "none") next &= -13;
1116
+ }
1117
+ const vertical = style.get("vertical-align");
1118
+ if (vertical === "super") next = (next | SUP) & -65;
1119
+ else if (vertical === "sub") next = (next | SUB) & -33;
1120
+ else if (vertical === "baseline") next &= -97;
1121
+ const family = style.get("font-family");
1122
+ if (family !== void 0 && MONOSPACE.test(family)) next |= CODE;
1123
+ return next;
1124
+ }
1125
+ /** Never content: scripts, metadata, embeds, media, controls, and Word's `<o:p>` spacers. */
1126
+ const SKIP = /* @__PURE__ */ new Set([
1127
+ ...DROP,
1128
+ "xml",
1129
+ "o:p",
1130
+ "area",
1131
+ "menuitem"
1132
+ ]);
1133
+ /** Left out without a report: what every clipboard document carries (its head, Office markup), not content. */
1134
+ const QUIET = /* @__PURE__ */ new Set([
1135
+ "head",
1136
+ "meta",
1137
+ "title",
1138
+ "link",
1139
+ "base",
1140
+ "style",
1141
+ "xml",
1142
+ "o:p"
1143
+ ]);
1144
+ const HEADINGS = /* @__PURE__ */ new Set([
1145
+ "h1",
1146
+ "h2",
1147
+ "h3",
1148
+ "h4",
1149
+ "h5",
1150
+ "h6"
1151
+ ]);
1152
+ /** Elements that start a new block. Anything else is inline: its content joins the current line. */
1153
+ const BLOCKS = /* @__PURE__ */ new Set([
1154
+ "address",
1155
+ "article",
1156
+ "aside",
1157
+ "blockquote",
1158
+ "body",
1159
+ "caption",
1160
+ "center",
1161
+ "dd",
1162
+ "details",
1163
+ "dialog",
1164
+ "dir",
1165
+ "div",
1166
+ "dl",
1167
+ "dt",
1168
+ "fieldset",
1169
+ "figcaption",
1170
+ "figure",
1171
+ "footer",
1172
+ "form",
1173
+ "h1",
1174
+ "h2",
1175
+ "h3",
1176
+ "h4",
1177
+ "h5",
1178
+ "h6",
1179
+ "header",
1180
+ "hgroup",
1181
+ "hr",
1182
+ "legend",
1183
+ "li",
1184
+ "listing",
1185
+ "main",
1186
+ "menu",
1187
+ "nav",
1188
+ "ol",
1189
+ "p",
1190
+ "pre",
1191
+ "search",
1192
+ "section",
1193
+ "summary",
1194
+ "table",
1195
+ "tbody",
1196
+ "td",
1197
+ "tfoot",
1198
+ "th",
1199
+ "thead",
1200
+ "tr",
1201
+ "ul",
1202
+ "xmp"
1203
+ ]);
1204
+ /** What ends a line in an item already: a line break, or a block written into it. */
1205
+ const LINE_ENDS = /* @__PURE__ */ new Set([
1206
+ "br",
1207
+ "ul",
1208
+ "ol",
1209
+ "table",
1210
+ "pre",
1211
+ "blockquote",
1212
+ "hr",
1213
+ "p",
1214
+ "h1",
1215
+ "h2",
1216
+ "h3",
1217
+ "h4",
1218
+ "h5",
1219
+ "h6"
1220
+ ]);
1221
+ /** Containers that hold their own lines: inline content goes straight into them, not into a paragraph. */
1222
+ const ITEMS = /* @__PURE__ */ new Set([
1223
+ "li",
1224
+ "td",
1225
+ "th",
1226
+ "dt",
1227
+ "dd",
1228
+ "caption"
1229
+ ]);
1230
+ const BLOCK_SELECTOR = /* @__PURE__ */ [...BLOCKS].join(",");
1231
+ const WORD_LIST = /mso-list\s*:\s*l\d+\s+level(\d+)/i;
1232
+ const ORDERED_MARKER = /^\(?(\d+|[a-z]|[ivxlcdm]+)[.)]/i;
1233
+ /** Deeper than this, content is kept as plain text: nothing is lost, and nothing overflows the stack. */
1234
+ const MAX_DEPTH = 200;
1235
+ /** Most characters of pasted HTML read. */
1236
+ const MAX_INPUT = 16777216;
1237
+ function isHidden(element, style) {
1238
+ return element.hasAttribute("hidden") || element.getAttribute("aria-hidden") === "true" || style.get("display") === "none" || style.get("visibility") === "hidden" || style.get("mso-list") === "ignore";
1239
+ }
1240
+ const isWordListParagraph = (node) => node.nodeType === 1 && WORD_LIST.test(node.getAttribute("style") ?? "");
1241
+ /**
1242
+ * The text of a code block, with its lines: line breaks, and one per block (as code editors put each
1243
+ * line in a `<div>`). `skipped` hears of each element left out.
1244
+ */
1245
+ function codeText(element, skipped) {
1246
+ let text = "";
1247
+ const walk = (node) => {
1248
+ if (node.nodeType === 3) {
1249
+ text += node.data.replace(/\u00A0/g, " ");
1250
+ return;
1251
+ }
1252
+ if (node.nodeType !== 1) return;
1253
+ const child = node;
1254
+ const tag = child.localName;
1255
+ if (SKIP.has(tag)) {
1256
+ skipped(tag);
1257
+ return;
1258
+ }
1259
+ if (isHidden(child, styleOf(child))) return;
1260
+ if (tag === "br") {
1261
+ text += "\n";
1262
+ return;
1263
+ }
1264
+ const block = BLOCKS.has(tag);
1265
+ if (block && text !== "" && !text.endsWith("\n")) text += "\n";
1266
+ child.childNodes.forEach(walk);
1267
+ if (block && text !== "" && !text.endsWith("\n")) text += "\n";
1268
+ };
1269
+ element.childNodes.forEach(walk);
1270
+ return text.replace(/\r\n?/g, "\n").replace(/\n$/, "");
1271
+ }
1272
+ /** A `<div style="white-space: pre; font-family: monospace">`, as code editors (VS Code) write. */
1273
+ function isCodeContainer(tag, style) {
1274
+ const whiteSpace = style.get("white-space");
1275
+ const family = style.get("font-family");
1276
+ return tag === "div" && whiteSpace !== void 0 && whiteSpace.startsWith("pre") && family !== void 0 && MONOSPACE.test(family);
1277
+ }
1278
+ /** A table used for layout (mail, old pages): its cells are just content, in reading order. */
1279
+ function isLayoutTable(table) {
1280
+ const role = table.getAttribute("role");
1281
+ if (role === "presentation" || role === "none") return true;
1282
+ return table.querySelectorAll("td, th").length === 1 || table.querySelector("td table, th table") !== null;
1283
+ }
1284
+ /** A URL's scheme for reports, read as the URL parser reads it: tabs and line breaks inside it don't count. */
1285
+ function positive(value, fallback, name) {
1286
+ if (value === void 0) return fallback;
1287
+ if (Number.isInteger(value) && value > 0) return value;
1288
+ throw require_errors.copyFailure("invalid-payload", `\`${name}\` must be a positive integer.`);
1289
+ }
1290
+ const scheme = (raw) => /^\s*([a-z][a-z\d+.-]*):/i.exec(raw.replace(/[\t\n\r]/g, ""))?.[1]?.toLowerCase() ?? "relative";
1291
+ var Cleaner = class {
1292
+ constructor(out, formats, options) {
1293
+ this.out = out;
1294
+ this.formats = formats;
1295
+ this.nodes = 0;
1296
+ this.truncated = false;
1297
+ this.removals = /* @__PURE__ */ new Map();
1298
+ this.allowedBits = INLINE.reduce((bits, [bit, , format]) => formats.has(format) ? bits | bit : bits, 0);
1299
+ const base = options.base === void 0 ? {} : { base: options.base };
1300
+ this.resolveLink = require_url.linkUrlResolver({
1301
+ ...base,
1302
+ ...options.protocols === void 0 ? {} : { protocols: options.protocols }
1303
+ });
1304
+ this.resolveImage = require_url.linkUrlResolver({
1305
+ ...base,
1306
+ protocols: options.dataImages === true ? [
1307
+ "https:",
1308
+ "http:",
1309
+ "data:"
1310
+ ] : ["https:", "http:"]
1311
+ });
1312
+ this.absolute = options.base === void 0 ? (raw) => new URL(raw.trim()).href : (raw) => raw;
1313
+ this.maxNodes = positive(options.maxNodes, 2e5, "maxNodes");
1314
+ }
1315
+ remove(reason, name) {
1316
+ const key = `${reason} ${name}`;
1317
+ this.removals.set(key, {
1318
+ reason,
1319
+ name,
1320
+ count: (this.removals.get(key)?.count ?? 0) + 1
1321
+ });
1322
+ }
1323
+ /** A link's address, absolute and scheme-checked, with click-tracking redirects (Google, Outlook Safe Links) unwrapped; `null` when unsafe. */
1324
+ link(element) {
1325
+ const raw = (element.getAttribute("href") ?? "").trim();
1326
+ if (raw === "") return null;
1327
+ try {
1328
+ return require_url$1.unwrapRedirect(new URL(this.resolveLink(this.absolute(raw)))).href;
1329
+ } catch {
1330
+ this.remove("unsafe-link", scheme(raw));
1331
+ return null;
1332
+ }
1333
+ }
1334
+ /** Whether an image may be kept: an absolute, scheme-checked address. */
1335
+ safeImage(image) {
1336
+ const raw = image.getAttribute("src") ?? "";
1337
+ try {
1338
+ this.resolveImage(this.absolute(raw));
1339
+ return true;
1340
+ } catch {
1341
+ this.remove("unsafe-image", scheme(raw));
1342
+ return false;
1343
+ }
1344
+ }
1345
+ el(tag, ...children) {
1346
+ const element = this.out.createElement(tag);
1347
+ element.append(...children);
1348
+ return element;
1349
+ }
1350
+ /** Whether reading may go on: a budget on source nodes, so huge or hostile input stays bounded. */
1351
+ count() {
1352
+ if (this.nodes >= this.maxNodes) {
1353
+ this.truncated = true;
1354
+ return false;
1355
+ }
1356
+ this.nodes += 1;
1357
+ return true;
1358
+ }
1359
+ /**
1360
+ * Converts `nodes` into blocks inside `parent`. Inline content goes straight into `parent` when it is an
1361
+ * item (a list item, a table cell), or into paragraphs otherwise.
1362
+ */
1363
+ blocks(nodes, parent, ctx) {
1364
+ const item = parent.nodeType === 1 && ITEMS.has(parent.localName);
1365
+ let runs = [];
1366
+ const flush = () => {
1367
+ if (item) this.line(runs, parent);
1368
+ else {
1369
+ const paragraph = this.out.createElement("p");
1370
+ if (this.emit(runs, paragraph)) parent.append(paragraph);
1371
+ }
1372
+ runs = [];
1373
+ };
1374
+ for (let index = 0; index < nodes.length; index += 1) {
1375
+ const node = nodes[index];
1376
+ if (isWordListParagraph(node)) {
1377
+ flush();
1378
+ index += this.wordList(nodes, index, parent, ctx) - 1;
1379
+ continue;
1380
+ }
1381
+ if (node.nodeType !== 1 || !BLOCKS.has(node.localName)) {
1382
+ const wrapper = node.nodeType === 1 ? this.wrapper(node, ctx) : null;
1383
+ if (wrapper === null) this.inline(node, ctx, runs);
1384
+ else {
1385
+ flush();
1386
+ this.blocks(Array.from(node.childNodes), parent, wrapper);
1387
+ }
1388
+ continue;
1389
+ }
1390
+ const element = node;
1391
+ const tag = element.localName;
1392
+ const style = styleOf(element);
1393
+ if (isHidden(element, style) || !this.count()) continue;
1394
+ if (item && (tag === "p" || tag === "div" && !isCodeContainer(tag, style))) {
1395
+ flush();
1396
+ runs = this.runsOf(element, ctx);
1397
+ flush();
1398
+ continue;
1399
+ }
1400
+ flush();
1401
+ this.block(element, tag, style, parent, ctx);
1402
+ }
1403
+ flush();
1404
+ }
1405
+ /** The context inside an inline element that holds blocks, or `null` for one that holds only inline content. */
1406
+ wrapper(element, ctx) {
1407
+ if (ctx.depth >= MAX_DEPTH || element.querySelector(BLOCK_SELECTOR) === null) return null;
1408
+ const tag = element.localName;
1409
+ const style = styleOf(element);
1410
+ if (SKIP.has(tag) || element.namespaceURI !== "http://www.w3.org/1999/xhtml" || isHidden(element, style)) return null;
1411
+ return this.inner(element, tag, style, ctx);
1412
+ }
1413
+ /** The formats and link inside an inline element. */
1414
+ inner(element, tag, style, ctx) {
1415
+ const href = tag === "a" && ctx.href === null && this.formats.has("link") ? this.link(element) : ctx.href;
1416
+ return {
1417
+ bits: bitsOf(ctx.bits, tag, style),
1418
+ href,
1419
+ depth: ctx.depth + 1
1420
+ };
1421
+ }
1422
+ block(element, tag, style, parent, ctx) {
1423
+ const deeper = {
1424
+ ...ctx,
1425
+ depth: ctx.depth + 1
1426
+ };
1427
+ if (ctx.depth >= MAX_DEPTH) {
1428
+ this.paragraph([{
1429
+ kind: "text",
1430
+ text: element.textContent,
1431
+ bits: 0,
1432
+ href: null
1433
+ }], parent);
1434
+ return;
1435
+ }
1436
+ if (tag === "pre" || tag === "listing" || tag === "xmp" || isCodeContainer(tag, style)) {
1437
+ this.codeBlock(codeText(element, (skipped) => {
1438
+ if (!QUIET.has(skipped)) this.remove("unsafe-element", skipped);
1439
+ }), parent);
1440
+ return;
1441
+ }
1442
+ if (HEADINGS.has(tag)) {
1443
+ const runs = this.runsOf(element, deeper).map((run) => ({
1444
+ ...run,
1445
+ bits: run.bits & -2
1446
+ }));
1447
+ if (this.formats.has("heading")) {
1448
+ const heading = this.out.createElement(tag);
1449
+ if (this.emit(runs, heading)) parent.append(heading);
1450
+ } else this.paragraph(runs.map((run) => ({
1451
+ ...run,
1452
+ bits: run.bits | STRONG
1453
+ })), parent);
1454
+ return;
1455
+ }
1456
+ if (tag === "ul" || tag === "ol" || tag === "menu" || tag === "dir") {
1457
+ this.list(element, tag === "ol", parent, deeper);
1458
+ return;
1459
+ }
1460
+ if (tag === "li") {
1461
+ this.list(element, false, parent, deeper, [element]);
1462
+ return;
1463
+ }
1464
+ if (tag === "blockquote") {
1465
+ if (!this.formats.has("quote")) {
1466
+ this.blocks(Array.from(element.childNodes), parent, deeper);
1467
+ return;
1468
+ }
1469
+ const quote = this.out.createElement("blockquote");
1470
+ this.blocks(Array.from(element.childNodes), quote, deeper);
1471
+ if (quote.firstChild !== null) parent.append(quote);
1472
+ return;
1473
+ }
1474
+ if (tag === "table") {
1475
+ this.table(element, parent, deeper);
1476
+ return;
1477
+ }
1478
+ if (tag === "hr") {
1479
+ if (this.formats.has("rule")) parent.append(this.out.createElement("hr"));
1480
+ return;
1481
+ }
1482
+ if (tag === "dl") {
1483
+ this.blocks(Array.from(element.childNodes), parent, deeper);
1484
+ return;
1485
+ }
1486
+ this.blocks(Array.from(element.childNodes), parent, deeper);
1487
+ }
1488
+ /** A new line of an item: after a line break when the item already ends in text. */
1489
+ line(runs, item) {
1490
+ const last = item.lastChild;
1491
+ if (last !== null && hasContent(runs) && (last.nodeType !== 1 || !LINE_ENDS.has(last.localName))) item.append(this.out.createElement("br"));
1492
+ this.emit(runs, item);
1493
+ }
1494
+ /** A paragraph for `runs` (or the item's own line), when they hold anything. */
1495
+ paragraph(runs, parent) {
1496
+ if (parent.nodeType === 1 && ITEMS.has(parent.localName)) {
1497
+ this.line(runs, parent);
1498
+ return;
1499
+ }
1500
+ const paragraph = this.out.createElement("p");
1501
+ if (this.emit(runs, paragraph)) parent.append(paragraph);
1502
+ }
1503
+ codeBlock(text, parent) {
1504
+ if (text.trim() === "") return;
1505
+ if (this.formats.has("codeBlock")) {
1506
+ parent.append(this.el("pre", this.el("code", this.out.createTextNode(text))));
1507
+ return;
1508
+ }
1509
+ for (const line of text.split("\n")) this.paragraph([{
1510
+ kind: "text",
1511
+ text: line.replace(/ /g, "\xA0"),
1512
+ bits: CODE,
1513
+ href: null
1514
+ }], parent);
1515
+ }
1516
+ list(element, ordered, parent, ctx, items) {
1517
+ const start = ordered ? Number.parseInt(element.getAttribute("start") ?? "1", 10) : 1;
1518
+ const first = Number.isFinite(start) ? start : 1;
1519
+ if (!this.formats.has("list")) {
1520
+ let number = first;
1521
+ for (const child of items ?? Array.from(element.childNodes)) {
1522
+ if (child.nodeType !== 1 || child.localName !== "li") {
1523
+ this.blocks([child], parent, ctx);
1524
+ continue;
1525
+ }
1526
+ const marker = {
1527
+ kind: "text",
1528
+ text: ordered ? `${String(number)}. ` : "• ",
1529
+ bits: 0,
1530
+ href: null
1531
+ };
1532
+ number += 1;
1533
+ const runs = Array.from(child.childNodes).filter((node) => !(node.nodeType === 1 && /^(?:ul|ol|menu|dir)$/.test(node.localName))).flatMap((node) => node.nodeType === 1 && BLOCKS.has(node.localName) ? [...this.runsOf(node, ctx), BREAK] : this.inlineRuns(node, ctx));
1534
+ this.paragraph([marker, ...trimBreaks(runs)], parent);
1535
+ for (const nested of Array.from(child.children)) if (/^(?:ul|ol|menu|dir)$/.test(nested.localName)) this.list(nested, nested.localName === "ol", parent, ctx);
1536
+ }
1537
+ return;
1538
+ }
1539
+ const list = this.out.createElement(ordered ? "ol" : "ul");
1540
+ if (ordered && first !== 1) list.setAttribute("start", String(first));
1541
+ for (const child of items ?? Array.from(element.childNodes)) {
1542
+ if (child.nodeType === 1 && child.localName === "li") {
1543
+ const li = this.out.createElement("li");
1544
+ this.blocks(Array.from(child.childNodes), li, ctx);
1545
+ list.append(li);
1546
+ continue;
1547
+ }
1548
+ const host = list.lastElementChild ?? list.appendChild(this.out.createElement("li"));
1549
+ this.blocks([child], host, ctx);
1550
+ }
1551
+ for (const li of Array.from(list.children)) if (li.firstChild === null) li.remove();
1552
+ if (list.firstChild !== null) parent.append(list);
1553
+ }
1554
+ /**
1555
+ * Word writes lists as paragraphs with `mso-list: l0 level2`, and each marker (`1.`, `·`) as
1556
+ * text in a span hidden with `mso-list: Ignore`. Rebuilds the consecutive list paragraphs
1557
+ * from `nodes[start]` as nested lists. Returns how many nodes they took.
1558
+ */
1559
+ wordList(nodes, start, parent, ctx) {
1560
+ const roots = [];
1561
+ const stack = [];
1562
+ let consumed = 0;
1563
+ const flat = !this.formats.has("list");
1564
+ for (let index = start; index < nodes.length; index += 1) {
1565
+ const node = nodes[index];
1566
+ if (node.nodeType === 8 || node.nodeType === 3 && node.data.trim() === "") continue;
1567
+ if (!isWordListParagraph(node)) break;
1568
+ consumed = index - start + 1;
1569
+ if (!this.count()) break;
1570
+ const level = Number(WORD_LIST.exec(node.getAttribute("style"))?.[1]);
1571
+ const marker = (node.querySelector("[style*=\"mso-list\"][style*=\"gnore\"]")?.textContent ?? "").replace(/\s+/g, "");
1572
+ const ordered = ORDERED_MARKER.exec(marker);
1573
+ const runs = this.runsOf(node, ctx);
1574
+ if (flat) {
1575
+ const shown = ordered !== null ? `${marker} ` : "• ";
1576
+ this.paragraph([{
1577
+ kind: "text",
1578
+ text: shown,
1579
+ bits: 0,
1580
+ href: null
1581
+ }, ...runs], parent);
1582
+ continue;
1583
+ }
1584
+ while (stack.length > 0 && stack[stack.length - 1].level > level) stack.pop();
1585
+ let top = stack[stack.length - 1];
1586
+ if (top !== void 0 && top.level === level && top.list.ordered !== (ordered !== null)) {
1587
+ stack.pop();
1588
+ top = stack[stack.length - 1];
1589
+ }
1590
+ if (top === void 0 || top.level < level) {
1591
+ const number = ordered !== null && /^\d+$/.test(ordered[1]) ? Number(ordered[1]) : 1;
1592
+ const list = {
1593
+ ordered: ordered !== null,
1594
+ start: number,
1595
+ items: []
1596
+ };
1597
+ const host = top?.list.items[top.list.items.length - 1];
1598
+ if (host === void 0) roots.push(list);
1599
+ else host.nested.push(list);
1600
+ top = {
1601
+ level,
1602
+ list
1603
+ };
1604
+ stack.push(top);
1605
+ }
1606
+ top.list.items.push({
1607
+ runs,
1608
+ nested: []
1609
+ });
1610
+ }
1611
+ for (const list of roots) this.writeWordList(list, parent);
1612
+ return consumed;
1613
+ }
1614
+ /** Writes a rebuilt Word list. An item with nothing in it is left out, unless it holds a nested list. */
1615
+ writeWordList(list, parent) {
1616
+ const element = this.out.createElement(list.ordered ? "ol" : "ul");
1617
+ if (list.ordered && list.start !== 1) element.setAttribute("start", String(list.start));
1618
+ for (const item of list.items) {
1619
+ const li = this.out.createElement("li");
1620
+ this.emit(item.runs, li);
1621
+ for (const nested of item.nested) this.writeWordList(nested, li);
1622
+ if (li.firstChild !== null) element.append(li);
1623
+ }
1624
+ if (element.firstChild !== null) parent.appendChild(element);
1625
+ }
1626
+ table(table, parent, ctx) {
1627
+ const rows = Array.from(table.querySelectorAll("tr")).filter((row) => row.closest("table") === table);
1628
+ const caption = Array.from(table.children).find((child) => child.localName === "caption");
1629
+ if (!this.formats.has("table") || isLayoutTable(table)) {
1630
+ if (caption !== void 0) this.blocks(Array.from(caption.childNodes), parent, ctx);
1631
+ for (const row of rows) for (const cell of Array.from(row.children)) if (cell.localName === "td" || cell.localName === "th") this.blocks(Array.from(cell.childNodes), parent, ctx);
1632
+ return;
1633
+ }
1634
+ const out = this.out.createElement("table");
1635
+ if (caption !== void 0) {
1636
+ const element = this.out.createElement("caption");
1637
+ this.blocks(Array.from(caption.childNodes), element, ctx);
1638
+ if (element.firstChild !== null) out.append(element);
1639
+ }
1640
+ const sections = /* @__PURE__ */ new Map();
1641
+ for (const row of rows) {
1642
+ if (!this.count()) break;
1643
+ const group = row.parentElement;
1644
+ let section = sections.get(group);
1645
+ if (section === void 0) {
1646
+ section = this.out.createElement(group.localName === "thead" || group.localName === "tfoot" ? group.localName : "tbody");
1647
+ sections.set(group, section);
1648
+ out.append(section);
1649
+ }
1650
+ const tr = this.out.createElement("tr");
1651
+ for (const cell of Array.from(row.children)) {
1652
+ if (cell.localName !== "td" && cell.localName !== "th") continue;
1653
+ const element = this.out.createElement(cell.localName);
1654
+ for (const attribute of [
1655
+ "colspan",
1656
+ "rowspan",
1657
+ "scope"
1658
+ ]) {
1659
+ const value = cell.getAttribute(attribute);
1660
+ if (value !== null) element.setAttribute(attribute, value);
1661
+ }
1662
+ this.blocks(Array.from(cell.childNodes), element, cell.localName === "th" ? {
1663
+ ...ctx,
1664
+ bits: ctx.bits & -2
1665
+ } : ctx);
1666
+ if (cell.localName === "th") stripBold(element);
1667
+ tr.append(element);
1668
+ }
1669
+ section.append(tr);
1670
+ }
1671
+ if (rows.length > 0) parent.append(out);
1672
+ }
1673
+ /** The inline content of `element` as runs: its blocks become lines, separated by line breaks. */
1674
+ runsOf(element, ctx) {
1675
+ const runs = [];
1676
+ const inner = {
1677
+ ...ctx,
1678
+ bits: bitsOf(ctx.bits, element.localName, styleOf(element))
1679
+ };
1680
+ for (const child of Array.from(element.childNodes)) {
1681
+ if (child.nodeType === 1 && BLOCKS.has(child.localName) && child.localName !== "br") {
1682
+ const element = child;
1683
+ if (isHidden(element, styleOf(element))) continue;
1684
+ if (runs.length > 0) runs.push(BREAK);
1685
+ runs.push(...this.runsOf(element, {
1686
+ ...inner,
1687
+ depth: inner.depth + 1
1688
+ }));
1689
+ runs.push(BREAK);
1690
+ continue;
1691
+ }
1692
+ this.inline(child, inner, runs);
1693
+ }
1694
+ return trimBreaks(runs);
1695
+ }
1696
+ inlineRuns(node, ctx) {
1697
+ const runs = [];
1698
+ this.inline(node, ctx, runs);
1699
+ return runs;
1700
+ }
1701
+ /** Inline content into runs: text with its formats and link, line breaks and images. */
1702
+ inline(node, ctx, runs) {
1703
+ if (!this.count()) return;
1704
+ if (node.nodeType === 3) {
1705
+ runs.push({
1706
+ kind: "text",
1707
+ text: node.data,
1708
+ bits: ctx.bits,
1709
+ href: ctx.href
1710
+ });
1711
+ return;
1712
+ }
1713
+ if (node.nodeType !== 1) return;
1714
+ const element = node;
1715
+ const tag = element.localName;
1716
+ const style = styleOf(element);
1717
+ if (SKIP.has(tag) || element.namespaceURI !== "http://www.w3.org/1999/xhtml") {
1718
+ if (!QUIET.has(tag)) this.remove("unsafe-element", tag);
1719
+ return;
1720
+ }
1721
+ if (isHidden(element, style)) return;
1722
+ if (tag === "br") {
1723
+ runs.push({
1724
+ kind: "break",
1725
+ bits: ctx.bits,
1726
+ href: ctx.href
1727
+ });
1728
+ return;
1729
+ }
1730
+ if (tag === "img") {
1731
+ if (!this.formats.has("image") || this.safeImage(element)) runs.push({
1732
+ kind: "image",
1733
+ image: element,
1734
+ bits: ctx.bits,
1735
+ href: ctx.href
1736
+ });
1737
+ else runs.push({
1738
+ kind: "text",
1739
+ text: element.getAttribute("alt") ?? "",
1740
+ bits: ctx.bits,
1741
+ href: ctx.href
1742
+ });
1743
+ return;
1744
+ }
1745
+ if (ctx.depth >= MAX_DEPTH) {
1746
+ runs.push({
1747
+ kind: "text",
1748
+ text: element.textContent,
1749
+ bits: ctx.bits,
1750
+ href: ctx.href
1751
+ });
1752
+ return;
1753
+ }
1754
+ const inner = this.inner(element, tag, style, ctx);
1755
+ if (BLOCKS.has(tag)) {
1756
+ runs.push(BREAK, ...this.runsOf(element, inner), BREAK);
1757
+ return;
1758
+ }
1759
+ for (const child of Array.from(element.childNodes)) this.inline(child, inner, runs);
1760
+ }
1761
+ /**
1762
+ * Writes `runs` into `target` as minimal, canonical markup: links outermost, then the formats in a
1763
+ * fixed order, each over the longest stretch it covers. Whitespace collapses as the browser shows it.
1764
+ * Returns whether anything was written.
1765
+ */
1766
+ emit(runs, target) {
1767
+ const cleaned = collapse(runs.map((run) => {
1768
+ const bits = run.bits & this.allowedBits;
1769
+ const href = this.formats.has("link") ? run.href : null;
1770
+ return run.kind === "image" && !this.formats.has("image") ? {
1771
+ kind: "text",
1772
+ text: run.image.getAttribute("alt") ?? "",
1773
+ bits,
1774
+ href
1775
+ } : {
1776
+ ...run,
1777
+ bits,
1778
+ href
1779
+ };
1780
+ }));
1781
+ if (cleaned.length === 0) return false;
1782
+ this.write(cleaned, target, 0);
1783
+ return true;
1784
+ }
1785
+ write(runs, target, level) {
1786
+ if (level === 0) {
1787
+ for (const group of groups(runs, (run) => run.href)) {
1788
+ const href = group[0].href;
1789
+ if (href === null) this.write(group, target, 1);
1790
+ else {
1791
+ const link = this.out.createElement("a");
1792
+ link.setAttribute("href", href);
1793
+ this.write(group, link, 1);
1794
+ target.appendChild(link);
1795
+ }
1796
+ }
1797
+ return;
1798
+ }
1799
+ const format = INLINE[level - 1];
1800
+ if (format === void 0) {
1801
+ for (const run of runs) if (run.kind === "text") target.appendChild(this.out.createTextNode(run.text));
1802
+ else if (run.kind === "break") target.appendChild(this.out.createElement("br"));
1803
+ else target.appendChild(copyImage(this.out, run.image));
1804
+ return;
1805
+ }
1806
+ const [bit, tag] = format;
1807
+ for (const group of groups(runs, (run) => (run.bits & bit) !== 0)) if ((group[0].bits & bit) === 0) this.write(group, target, level + 1);
1808
+ else {
1809
+ const element = this.out.createElement(tag);
1810
+ this.write(group, element, level + 1);
1811
+ target.appendChild(element);
1812
+ }
1813
+ }
1814
+ };
1815
+ const BREAK = {
1816
+ kind: "break",
1817
+ bits: 0,
1818
+ href: null
1819
+ };
1820
+ const hasContent = (runs) => runs.some((run) => run.kind === "image" || run.kind === "text" && /[^\s]/.test(run.text));
1821
+ function trimBreaks(runs) {
1822
+ let start = 0;
1823
+ let end = runs.length;
1824
+ while (start < end && runs[start].kind === "break") start += 1;
1825
+ while (end > start && runs[end - 1].kind === "break") end -= 1;
1826
+ return runs.slice(start, end);
1827
+ }
1828
+ /** Maximal stretches of runs with the same key. */
1829
+ function groups(runs, key) {
1830
+ const out = [];
1831
+ let last;
1832
+ for (const run of runs) {
1833
+ const value = key(run);
1834
+ const current = out[out.length - 1];
1835
+ if (current !== void 0 && value === last) current.push(run);
1836
+ else out.push([run]);
1837
+ last = value;
1838
+ }
1839
+ return out;
1840
+ }
1841
+ /**
1842
+ * Whitespace as the browser shows it: runs of it are one space, none at the start or end of a line,
1843
+ * and line breaks without text after them (or several in a row at the edges) are left out.
1844
+ * Spaces take no formats, so formatting never starts or ends with one.
1845
+ */
1846
+ function collapse(runs) {
1847
+ const out = [];
1848
+ let lineStart = true;
1849
+ let pendingSpace = false;
1850
+ for (const run of runs) {
1851
+ if (run.kind === "break") {
1852
+ pendingSpace = false;
1853
+ out.push(run);
1854
+ lineStart = true;
1855
+ continue;
1856
+ }
1857
+ if (run.kind === "image") {
1858
+ if (pendingSpace) out.push({
1859
+ kind: "text",
1860
+ text: " ",
1861
+ bits: 0,
1862
+ href: null
1863
+ });
1864
+ pendingSpace = false;
1865
+ out.push(run);
1866
+ lineStart = false;
1867
+ continue;
1868
+ }
1869
+ const parts = run.text.split(/[ \t\n\r\f]+/);
1870
+ for (let index = 0; index < parts.length; index += 1) {
1871
+ const part = parts[index];
1872
+ if (index > 0 && !lineStart) pendingSpace = true;
1873
+ if (part === "") continue;
1874
+ if (pendingSpace) {
1875
+ const last = out[out.length - 1];
1876
+ out.push({
1877
+ kind: "text",
1878
+ text: " ",
1879
+ bits: last.bits & run.bits,
1880
+ href: last.href === run.href ? run.href : null
1881
+ });
1882
+ }
1883
+ pendingSpace = false;
1884
+ out.push({
1885
+ kind: "text",
1886
+ text: part,
1887
+ bits: run.bits,
1888
+ href: run.href
1889
+ });
1890
+ lineStart = false;
1891
+ }
1892
+ }
1893
+ const merged = [];
1894
+ for (const run of trimBreaks(out)) {
1895
+ const last = merged[merged.length - 1];
1896
+ if (run.kind === "text" && last?.kind === "text" && last.bits === run.bits && last.href === run.href) merged[merged.length - 1] = {
1897
+ ...last,
1898
+ text: last.text + run.text
1899
+ };
1900
+ else merged.push(run);
1901
+ }
1902
+ return hasContent(merged) ? merged : [];
1903
+ }
1904
+ /** An image with what describes it, never its styles or event handlers. */
1905
+ function copyImage(doc, image) {
1906
+ const out = doc.createElement("img");
1907
+ for (const name of [
1908
+ "src",
1909
+ "alt",
1910
+ "title",
1911
+ "width",
1912
+ "height"
1913
+ ]) {
1914
+ const value = image.getAttribute(name);
1915
+ if (value !== null) out.setAttribute(name, value);
1916
+ }
1917
+ return out;
1918
+ }
1919
+ /** Bold inside a header cell is noise: the cell is bold already. */
1920
+ function stripBold(cell) {
1921
+ for (const strong of Array.from(cell.querySelectorAll("strong"))) strong.replaceWith(...Array.from(strong.childNodes));
1922
+ cell.normalize();
1923
+ }
1924
+ function resolveFormats(formats) {
1925
+ if (formats === void 0) return new Set(RICH_PASTE_FORMATS);
1926
+ const value = formats;
1927
+ if (!Array.isArray(value) || !value.every((format) => RICH_PASTE_FORMATS.includes(format))) throw require_errors.copyFailure("invalid-payload", `\`formats\` must be an array of: ${RICH_PASTE_FORMATS.join(", ")}.`);
1928
+ return new Set(formats);
1929
+ }
1930
+ const escapeHtml = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1931
+ /** Plain text as rich content: a paragraph per block of lines, a line break per line. Needs no DOM. */
1932
+ function fromText(text, maxLength) {
1933
+ const normalized = text.replace(/\r\n?/g, "\n");
1934
+ const paragraphs = normalized.split(/\n[ \t]*\n+/).map((block) => block.split("\n").map((line) => escapeHtml(line.trim())).filter((line) => line !== "")).filter((lines) => lines.length > 0);
1935
+ let html = "";
1936
+ let truncated = false;
1937
+ for (const lines of paragraphs) {
1938
+ const paragraph = `<p>${lines.join("<br>")}</p>`;
1939
+ if (html.length + paragraph.length > maxLength) {
1940
+ truncated = true;
1941
+ break;
1942
+ }
1943
+ html += paragraph;
1944
+ }
1945
+ return {
1946
+ html,
1947
+ text: normalized.trim(),
1948
+ removed: [],
1949
+ truncated,
1950
+ source: "text"
1951
+ };
1952
+ }
1953
+ /**
1954
+ * Cleans what was pasted into semantic, safe HTML for a rich-text editor: the HTML Google Docs,
1955
+ * Word, Outlook, Gmail, Notion and web pages put on the clipboard becomes paragraphs, headings,
1956
+ * lists, quotes, code blocks, tables, links and images, with bold, italic, underline,
1957
+ * strikethrough, code, superscript and subscript as tags (`<strong>`, `<em>`, ...).
1958
+ *
1959
+ * - Formatting set by CSS (`font-weight: 700`, `font-style: italic`) becomes tags, and every
1960
+ * style, class and id is left out: pasted content takes the editor's look, not the source's.
1961
+ * - Word's paragraph lists become real lists; Google Docs' wrappers, empty spacers and hidden
1962
+ * markers go. Layout tables (mail) become their content.
1963
+ * - The output is canonical (the same content always gives the same HTML) and goes through the
1964
+ * same sanitizer as {@link prepareRich}: only allowlisted elements and attributes, links and
1965
+ * images with absolute, scheme-checked URLs. `removed` says what was left out.
1966
+ * - `formats` limits the output to what your editor holds, keeping all of the text.
1967
+ *
1968
+ * Plain text (no HTML on the clipboard) becomes paragraphs and line breaks. Returns `null` when
1969
+ * there is nothing to paste. HTML needs `DOMParser` (any browser, or jsdom); without one, the
1970
+ * plain text is used.
1971
+ *
1972
+ * @example
1973
+ * // TipTap / ProseMirror
1974
+ * editorProps: { transformPastedHTML: (html) => pasteToRich({ html })?.html ?? '' }
1975
+ */
1976
+ function pasteToRich(source, options = {}) {
1977
+ const formats = resolveFormats(options.formats);
1978
+ const maxLength = options.maxLength ?? 1e6;
1979
+ const html = source.html ?? null;
1980
+ const text = source.text ?? null;
1981
+ if (html !== null && html.trim() !== "" && typeof DOMParser !== "undefined") {
1982
+ const parsed = require_inert_html.parseInertHtml(`<!doctype html><body>${html.slice(0, MAX_INPUT)}`);
1983
+ const out = parsed.implementation.createHTMLDocument("");
1984
+ const cleaner = new Cleaner(out, formats, options);
1985
+ const fragment = out.createDocumentFragment();
1986
+ cleaner.blocks(Array.from(parsed.body.childNodes), fragment, {
1987
+ bits: 0,
1988
+ href: null,
1989
+ depth: 0
1990
+ });
1991
+ const result = prepareRich(fragment, {
1992
+ styles: "none",
1993
+ images: formats.has("image") ? "keep" : "alt",
1994
+ ...options.base === void 0 ? {} : { base: options.base },
1995
+ ...options.protocols === void 0 ? {} : { protocols: options.protocols },
1996
+ ...options.dataImages === void 0 ? {} : { dataImages: options.dataImages },
1997
+ ...options.maxElements === void 0 ? {} : { maxElements: options.maxElements },
1998
+ maxLength,
1999
+ ...options.text === void 0 ? {} : { text: options.text }
2000
+ });
2001
+ if (result.html !== "") {
2002
+ const removed = [...cleaner.removals.values(), ...result.removed];
2003
+ return {
2004
+ ...result,
2005
+ removed,
2006
+ truncated: result.truncated || cleaner.truncated || html.length > MAX_INPUT,
2007
+ source: "html"
2008
+ };
2009
+ }
2010
+ }
2011
+ if (text === null || text.trim() === "") return null;
2012
+ const value = maxLength;
2013
+ if (!(Number.isInteger(value) && maxLength > 0)) throw require_errors.copyFailure("invalid-payload", "`maxLength` must be a positive integer.");
2014
+ return fromText(text, maxLength);
2015
+ }
2016
+ /** The editable element a paste lands in: the handler's element when it is `contenteditable`. */
2017
+ function editableHost(event) {
2018
+ const target = event.currentTarget ?? event.target;
2019
+ if (typeof target !== "object" || target === null || target.nodeType !== 1) return null;
2020
+ const element = target;
2021
+ return element.isContentEditable ? element : null;
2022
+ }
2023
+ /**
2024
+ * Inserts HTML at the selection in an editable element, as a paste would: the browser's undo
2025
+ * (Ctrl/Cmd+Z) still works and `input` events fire. Without a selection inside the element,
2026
+ * the HTML goes at its end.
2027
+ */
2028
+ function insertHtml(host, html) {
2029
+ const doc = host.ownerDocument;
2030
+ const selection = doc.getSelection();
2031
+ const current = selection !== null && selection.rangeCount > 0 ? selection.getRangeAt(0) : null;
2032
+ let range;
2033
+ if (current !== null && host.contains(current.commonAncestorContainer)) range = current.cloneRange();
2034
+ else {
2035
+ range = doc.createRange();
2036
+ range.selectNodeContents(host);
2037
+ range.collapse(false);
2038
+ }
2039
+ if (doc.activeElement !== host) host.focus();
2040
+ selection?.removeAllRanges();
2041
+ selection?.addRange(range);
2042
+ try {
2043
+ if (doc.activeElement === host && doc.execCommand("insertHTML", false, html)) return;
2044
+ } catch {}
2045
+ range.deleteContents();
2046
+ const fragment = range.createContextualFragment(html);
2047
+ const last = fragment.lastChild;
2048
+ range.insertNode(fragment);
2049
+ range.setStartAfter(last);
2050
+ range.collapse(true);
2051
+ const view = doc.defaultView;
2052
+ host.dispatchEvent(view !== null && typeof view.InputEvent === "function" ? new view.InputEvent("input", {
2053
+ bubbles: true,
2054
+ inputType: "insertFromPaste"
2055
+ }) : new Event("input", { bubbles: true }));
2056
+ }
2057
+ /**
2058
+ * A paste handler for `contenteditable` elements: what is pasted from Google Docs, Word, mail or
2059
+ * a web page goes in as clean, semantic HTML (see {@link pasteToRich}), with undo intact. Plain-text
2060
+ * pastes are left to the browser. Returns whether it handled the paste.
2061
+ *
2062
+ * Rich-text editors (TipTap, ProseMirror, Lexical, Quill) have their own paste pipelines: use
2063
+ * {@link pasteToRich} in their hook instead, so the editor keeps its document model.
2064
+ *
2065
+ * @example
2066
+ * <div contentEditable onPaste={pasteAsRich} />
2067
+ * <div contentEditable onPaste={(event) => pasteAsRich(event, { formats: ['bold', 'italic', 'link', 'list'] })} />
2068
+ */
2069
+ function pasteAsRich(event, options) {
2070
+ if (event.defaultPrevented || event.clipboardData === null) return false;
2071
+ const host = editableHost(event);
2072
+ if (host === null) return false;
2073
+ const html = event.clipboardData.getData("text/html");
2074
+ if (html === "") return false;
2075
+ let pasted;
2076
+ try {
2077
+ pasted = pasteToRich({
2078
+ html,
2079
+ text: event.clipboardData.getData("text/plain")
2080
+ }, options);
2081
+ } catch {
2082
+ return false;
2083
+ }
2084
+ if (pasted?.source !== "html") return false;
2085
+ event.preventDefault();
2086
+ if (options?.onPaste?.(pasted) === false) return true;
2087
+ insertHtml(host, pasted.html);
2088
+ return true;
2089
+ }
2090
+ //#endregion
2091
+ exports.RICH_PASTE_FORMATS = RICH_PASTE_FORMATS;
2092
+ exports.pasteAsRich = pasteAsRich;
2093
+ exports.pasteToRich = pasteToRich;
1003
2094
  exports.plainText = plainText;
1004
2095
  exports.prepareRich = prepareRich;
1005
2096
  exports.richPayload = richPayload;