react-smart-copy 1.18.0 → 1.19.1

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