react-smart-copy 1.17.2 → 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.
Files changed (154) hide show
  1. package/README.md +86 -5
  2. package/dist/capture.cjs +30 -153
  3. package/dist/capture.cjs.map +1 -1
  4. package/dist/capture.d.cts +2 -25
  5. package/dist/capture.d.ts +2 -25
  6. package/dist/capture.js +5 -128
  7. package/dist/capture.js.map +1 -1
  8. package/dist/chunks/clipboard-adapter-Cfz-rzw3.cjs +102 -0
  9. package/dist/chunks/clipboard-adapter-Cfz-rzw3.cjs.map +1 -0
  10. package/dist/chunks/clipboard-adapter-CtH4VELE.d.cts +43 -0
  11. package/dist/chunks/clipboard-adapter-DEXkXxwV.js +97 -0
  12. package/dist/chunks/clipboard-adapter-DEXkXxwV.js.map +1 -0
  13. package/dist/chunks/clipboard-adapter-Ds0irroN.d.ts +43 -0
  14. package/dist/chunks/contrast-C6CVklEI.cjs +842 -0
  15. package/dist/chunks/contrast-C6CVklEI.cjs.map +1 -0
  16. package/dist/chunks/contrast-DpK2JIVu.js +789 -0
  17. package/dist/chunks/contrast-DpK2JIVu.js.map +1 -0
  18. package/dist/chunks/copy-interceptor-C6NABy1l.d.ts +141 -0
  19. package/dist/chunks/copy-interceptor-CZWzGOkL.d.cts +141 -0
  20. package/dist/chunks/core-Cp2HSpaz.js +1035 -0
  21. package/dist/chunks/core-Cp2HSpaz.js.map +1 -0
  22. package/dist/chunks/core-DYf_Lhbe.cjs +1142 -0
  23. package/dist/chunks/core-DYf_Lhbe.cjs.map +1 -0
  24. package/dist/chunks/deadline-C29AlS_Q.js +46 -0
  25. package/dist/chunks/deadline-C29AlS_Q.js.map +1 -0
  26. package/dist/chunks/deadline-DkiB8ZHE.cjs +51 -0
  27. package/dist/chunks/deadline-DkiB8ZHE.cjs.map +1 -0
  28. package/dist/chunks/errors-9h8sdFFX.js +120 -0
  29. package/dist/chunks/errors-9h8sdFFX.js.map +1 -0
  30. package/dist/chunks/errors-BwOF6T_M.cjs +167 -0
  31. package/dist/chunks/errors-BwOF6T_M.cjs.map +1 -0
  32. package/dist/chunks/index-mr7sSAgP.d.ts +426 -0
  33. package/dist/chunks/index-vz0iW5V2.d.cts +426 -0
  34. package/dist/chunks/inert-html-D75NyVvT.js +34 -0
  35. package/dist/chunks/inert-html-D75NyVvT.js.map +1 -0
  36. package/dist/chunks/inert-html-DyxjWDok.cjs +39 -0
  37. package/dist/chunks/inert-html-DyxjWDok.cjs.map +1 -0
  38. package/dist/chunks/mime--LB7kdqG.cjs +153 -0
  39. package/dist/chunks/mime--LB7kdqG.cjs.map +1 -0
  40. package/dist/chunks/mime-aa-HA2dm.js +100 -0
  41. package/dist/chunks/mime-aa-HA2dm.js.map +1 -0
  42. package/dist/chunks/paste-adapter--SPL4PRE.d.cts +35 -0
  43. package/dist/chunks/paste-adapter-uahXnTYk.d.ts +35 -0
  44. package/dist/chunks/paste-reader-Bo01IMC_.cjs +289 -0
  45. package/dist/chunks/paste-reader-Bo01IMC_.cjs.map +1 -0
  46. package/dist/chunks/paste-reader-D9i7yMXF.js +224 -0
  47. package/dist/chunks/paste-reader-D9i7yMXF.js.map +1 -0
  48. package/dist/chunks/paste-reader-DcXnRWQr.d.cts +96 -0
  49. package/dist/chunks/paste-reader-DcXnRWQr.d.ts +96 -0
  50. package/dist/chunks/payload-CUymxwim.cjs +100 -0
  51. package/dist/chunks/payload-CUymxwim.cjs.map +1 -0
  52. package/dist/chunks/payload-CcwKJ_bU.d.cts +162 -0
  53. package/dist/chunks/payload-Cl_8hCI5.d.ts +162 -0
  54. package/dist/chunks/payload-DGw-JOo7.js +71 -0
  55. package/dist/chunks/payload-DGw-JOo7.js.map +1 -0
  56. package/dist/chunks/payload-DI5AorDz.js +103 -0
  57. package/dist/chunks/payload-DI5AorDz.js.map +1 -0
  58. package/dist/chunks/payload-J6GjHuh3.cjs +132 -0
  59. package/dist/chunks/payload-J6GjHuh3.cjs.map +1 -0
  60. package/dist/chunks/share-Bop47Znn.js +208 -0
  61. package/dist/chunks/share-Bop47Znn.js.map +1 -0
  62. package/dist/chunks/share-C0esXvRK.d.cts +115 -0
  63. package/dist/chunks/share-ayDz974N.cjs +231 -0
  64. package/dist/chunks/share-ayDz974N.cjs.map +1 -0
  65. package/dist/chunks/share-e7FenIr2.d.ts +115 -0
  66. package/dist/chunks/text-field-Ba8W3v4R.cjs +77 -0
  67. package/dist/chunks/text-field-Ba8W3v4R.cjs.map +1 -0
  68. package/dist/chunks/text-field-C0SGmvvR.d.cts +18 -0
  69. package/dist/chunks/text-field-C0SGmvvR.d.ts +18 -0
  70. package/dist/chunks/text-field-DUvrMMaK.js +66 -0
  71. package/dist/chunks/text-field-DUvrMMaK.js.map +1 -0
  72. package/dist/chunks/url-B9jdFGQy.cjs +86 -0
  73. package/dist/chunks/url-B9jdFGQy.cjs.map +1 -0
  74. package/dist/chunks/url-BcMYVCXQ.js +135 -0
  75. package/dist/chunks/url-BcMYVCXQ.js.map +1 -0
  76. package/dist/chunks/url-D4PGsRm8.cjs +164 -0
  77. package/dist/chunks/url-D4PGsRm8.cjs.map +1 -0
  78. package/dist/chunks/url-DWdElCT3.d.cts +43 -0
  79. package/dist/chunks/url-DWdElCT3.d.ts +43 -0
  80. package/dist/chunks/url-vJaFPbNL.js +57 -0
  81. package/dist/chunks/url-vJaFPbNL.js.map +1 -0
  82. package/dist/code.cjs +22 -113
  83. package/dist/code.cjs.map +1 -1
  84. package/dist/code.d.cts +4 -28
  85. package/dist/code.d.ts +4 -28
  86. package/dist/code.js +5 -96
  87. package/dist/code.js.map +1 -1
  88. package/dist/color.cjs +21 -893
  89. package/dist/color.cjs.map +1 -1
  90. package/dist/color.d.cts +4 -28
  91. package/dist/color.d.ts +4 -28
  92. package/dist/color.js +4 -876
  93. package/dist/color.js.map +1 -1
  94. package/dist/core.cjs +52 -1659
  95. package/dist/core.d.cts +8 -878
  96. package/dist/core.d.ts +8 -878
  97. package/dist/core.js +7 -1614
  98. package/dist/image.cjs +23 -94
  99. package/dist/image.cjs.map +1 -1
  100. package/dist/image.d.cts +1 -0
  101. package/dist/image.d.ts +1 -0
  102. package/dist/image.js +3 -74
  103. package/dist/image.js.map +1 -1
  104. package/dist/index.cjs +74 -2072
  105. package/dist/index.cjs.map +1 -1
  106. package/dist/index.d.cts +8 -978
  107. package/dist/index.d.ts +8 -978
  108. package/dist/index.js +7 -2005
  109. package/dist/index.js.map +1 -1
  110. package/dist/link.cjs +26 -339
  111. package/dist/link.cjs.map +1 -1
  112. package/dist/link.d.cts +5 -83
  113. package/dist/link.d.ts +5 -83
  114. package/dist/link.js +7 -320
  115. package/dist/link.js.map +1 -1
  116. package/dist/markdown.cjs +19 -159
  117. package/dist/markdown.cjs.map +1 -1
  118. package/dist/markdown.d.cts +3 -16
  119. package/dist/markdown.d.ts +3 -16
  120. package/dist/markdown.js +6 -146
  121. package/dist/markdown.js.map +1 -1
  122. package/dist/rich.cjs +1123 -940
  123. package/dist/rich.cjs.map +1 -1
  124. package/dist/rich.d.cts +101 -91
  125. package/dist/rich.d.ts +101 -91
  126. package/dist/rich.js +1099 -919
  127. package/dist/rich.js.map +1 -1
  128. package/dist/share.cjs +5 -640
  129. package/dist/share.d.cts +3 -248
  130. package/dist/share.d.ts +3 -248
  131. package/dist/share.js +1 -637
  132. package/dist/structured.cjs +13 -95
  133. package/dist/structured.cjs.map +1 -1
  134. package/dist/structured.d.cts +2 -11
  135. package/dist/structured.d.ts +2 -11
  136. package/dist/structured.js +4 -86
  137. package/dist/structured.js.map +1 -1
  138. package/dist/table.cjs +13 -40
  139. package/dist/table.cjs.map +1 -1
  140. package/dist/table.d.cts +2 -12
  141. package/dist/table.d.ts +2 -12
  142. package/dist/table.js +4 -31
  143. package/dist/table.js.map +1 -1
  144. package/dist/testing.cjs +10 -43
  145. package/dist/testing.cjs.map +1 -1
  146. package/dist/testing.d.cts +6 -181
  147. package/dist/testing.d.ts +6 -181
  148. package/dist/testing.js +3 -36
  149. package/dist/testing.js.map +1 -1
  150. package/package.json +37 -5
  151. package/dist/core.cjs.map +0 -1
  152. package/dist/core.js.map +0 -1
  153. package/dist/share.cjs.map +0 -1
  154. package/dist/share.js.map +0 -1
package/dist/rich.js CHANGED
@@ -1,138 +1,9 @@
1
- //#region src/core/errors.ts
2
- function createCopyError(type, message, cause) {
3
- return cause === void 0 ? {
4
- type,
5
- message
6
- } : {
7
- type,
8
- message,
9
- cause
10
- };
11
- }
12
- /**
13
- * Branded (not `instanceof`) so failures stay recognisable even when the core
14
- * is bundled twice, e.g. `react-smart-copy` and `react-smart-copy/core` together.
15
- */
16
- const COPY_FAILURE_BRAND = Symbol.for("react-smart-copy.CopyFailure");
17
- /** Error thrown by adapters to carry a fully classified {@link CopyError}. */
18
- var CopyFailure = class extends Error {
19
- constructor(copyError) {
20
- super(copyError.message);
21
- this[COPY_FAILURE_BRAND] = true;
22
- this.name = "CopyFailure";
23
- this.copyError = copyError;
24
- }
25
- };
26
- /** Shorthand for throwing a classified failure. */
27
- function copyFailure(type, message, cause) {
28
- return new CopyFailure(createCopyError(type, message, cause));
29
- }
30
- //#endregion
31
- //#region src/link/url.ts
32
- /** Schemes a copied or pasted link may use by default. Never `javascript:`, `data:`, `vbscript:` or `file:`. */
33
- const DEFAULT_LINK_PROTOCOLS = /* @__PURE__ */ Object.freeze([
34
- "https:",
35
- "http:",
36
- "mailto:",
37
- "tel:"
38
- ]);
39
- /**
40
- * Query parameters that only track where a click came from: the defaults of
41
- * {@link cleanLinkUrl}. `utm_` matches every parameter starting with it.
42
- */
43
- const TRACKING_PARAMETERS = /* @__PURE__ */ Object.freeze([
44
- "utm_",
45
- "fbclid",
46
- "gclid",
47
- "gclsrc",
48
- "dclid",
49
- "gbraid",
50
- "wbraid",
51
- "msclkid",
52
- "yclid",
53
- "twclid",
54
- "ttclid",
55
- "li_fat_id",
56
- "igshid",
57
- "igsh",
58
- "mc_cid",
59
- "mc_eid",
60
- "_hsenc",
61
- "_hsmi",
62
- "mkt_tok",
63
- "oly_anon_id",
64
- "oly_enc_id",
65
- "vero_id",
66
- "wickedid",
67
- "_gl"
68
- ]);
69
- const invalid = (message) => copyFailure("invalid-payload", message);
70
- function baseUrl(base) {
71
- if (base !== void 0) {
72
- if (typeof base === "string" || base instanceof URL) return String(base);
73
- throw invalid("`base` must be a string or a URL.");
74
- }
75
- return typeof location === "undefined" ? void 0 : location.href;
76
- }
77
- function protocolSet(protocols) {
78
- const list = protocols ?? DEFAULT_LINK_PROTOCOLS;
79
- const valid = (protocol) => typeof protocol === "string" && /^[a-z][a-z\d+.-]*:$/i.test(protocol);
80
- if (!Array.isArray(list) || list.length === 0 || !list.every(valid)) throw invalid("`protocols` must be a non-empty list of schemes with their colon, like \"https:\".");
81
- return new Set(list.map((protocol) => protocol.toLowerCase()));
82
- }
83
- function matcher(params) {
84
- const list = params ?? TRACKING_PARAMETERS;
85
- if (!Array.isArray(list) || !list.every((param) => typeof param === "string" || param instanceof RegExp)) throw invalid("`clean.params` must be a list of strings and regular expressions.");
86
- return (name) => {
87
- const lower = name.toLowerCase();
88
- return list.some((param) => {
89
- if (typeof param !== "string") return new RegExp(param.source, param.flags.replace(/[gy]/g, "")).test(name);
90
- const wanted = param.toLowerCase();
91
- return wanted.endsWith("_") ? lower.startsWith(wanted) : lower === wanted;
92
- });
93
- };
94
- }
95
- /** The cleaning step `clean` asks for, or `null`. Throws for an invalid option. */
96
- function cleaner(option) {
97
- const cleaning = option ?? false;
98
- if (cleaning === false) return null;
99
- if (cleaning !== true && (typeof cleaning !== "object" || cleaning === null)) throw invalid("`clean` must be a boolean or an options object.");
100
- const settings = cleaning === true ? {} : cleaning;
101
- const tracking = matcher(settings.params);
102
- const keep = settings.keep ?? [];
103
- if (!Array.isArray(keep) || !keep.every((name) => typeof name === "string")) throw invalid("`clean.keep` must be a list of strings.");
104
- const kept = new Set(keep.map((name) => name.toLowerCase()));
105
- return (url) => {
106
- for (const name of [...new Set(url.searchParams.keys())]) if (tracking(name) && !kept.has(name.toLowerCase())) url.searchParams.delete(name);
107
- };
108
- }
109
- /**
110
- * Validates `options` once (throwing a typed `invalid-payload` error for invalid
111
- * ones) and returns a resolver that throws only for invalid links.
112
- * @internal
113
- */
114
- function linkUrlResolver(options = {}) {
115
- const protocols = protocolSet(options.protocols);
116
- const base = baseUrl(options.base);
117
- const clean = cleaner(options.clean);
118
- return (input) => {
119
- if (typeof input !== "string" && !(input instanceof URL)) throw invalid("A link must be a string or a URL.");
120
- const raw = String(input).trim();
121
- if (raw === "") throw invalid("A link must not be empty.");
122
- let url;
123
- try {
124
- url = new URL(raw, base);
125
- } catch (cause) {
126
- throw copyFailure("invalid-payload", `Not a valid link: ${JSON.stringify(raw.slice(0, 200))}.`, cause);
127
- }
128
- if (!protocols.has(url.protocol)) throw invalid(`Links with the scheme "${url.protocol}" are not allowed (allowed: ${[...protocols].join(", ")}).`);
129
- url.username = "";
130
- url.password = "";
131
- clean?.(url);
132
- return url.href;
133
- };
134
- }
135
- //#endregion
1
+
2
+ import { n as copyFailure } from "./chunks/errors-9h8sdFFX.js";
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";
6
+ import { i as formatColor, l as toGamut, n as contrastRatio, o as parseColor, s as color } from "./chunks/contrast-DpK2JIVu.js";
136
7
  //#region src/rich/policy.ts
137
8
  /**
138
9
  * What portable rich text may contain: the elements, attributes and CSS that Gmail,
@@ -356,7 +227,7 @@ const TABLE_PARTS = /* @__PURE__ */ new Set([
356
227
  "thead",
357
228
  "tr"
358
229
  ]);
359
- const HEADINGS = /* @__PURE__ */ new Set([
230
+ const HEADINGS$1 = /* @__PURE__ */ new Set([
360
231
  "h1",
361
232
  "h2",
362
233
  "h3",
@@ -452,783 +323,6 @@ function attributeAllowed(tag, name, value) {
452
323
  }
453
324
  }
454
325
  //#endregion
455
- //#region src/color/convert.ts
456
- const color = (r, g, b, alpha = 1) => Object.freeze({
457
- r,
458
- g,
459
- b,
460
- alpha
461
- });
462
- const mul = (m, [x, y, z]) => [
463
- m[0][0] * x + m[0][1] * y + m[0][2] * z,
464
- m[1][0] * x + m[1][1] * y + m[1][2] * z,
465
- m[2][0] * x + m[2][1] * y + m[2][2] * z
466
- ];
467
- /** The sRGB (and Display P3) transfer function, extended to negative values by symmetry. */
468
- const toLinear = (c) => {
469
- const abs = Math.abs(c);
470
- return abs <= .04045 ? c / 12.92 : Math.sign(c) * ((abs + .055) / 1.055) ** 2.4;
471
- };
472
- const fromLinear = (c) => {
473
- const abs = Math.abs(c);
474
- return abs > .0031308 ? Math.sign(c) * (1.055 * abs ** (1 / 2.4) - .055) : 12.92 * c;
475
- };
476
- /** Applies `f` to each component; the result stays a three-component vector. */
477
- const map3 = ([x, y, z], f) => [
478
- f(x, 0),
479
- f(y, 1),
480
- f(z, 2)
481
- ];
482
- /** Three numbers as a vector, or null when one is missing. */
483
- const vec3 = ([x, y, z]) => typeof x === "number" && typeof y === "number" && typeof z === "number" ? [
484
- x,
485
- y,
486
- z
487
- ] : null;
488
- const linearRgb = (c) => [
489
- toLinear(c.r),
490
- toLinear(c.g),
491
- toLinear(c.b)
492
- ];
493
- const fromLinearRgb = ([r, g, b], alpha) => color(fromLinear(r), fromLinear(g), fromLinear(b), alpha);
494
- const SRGB_TO_XYZ = [
495
- [
496
- .41239079926595934,
497
- .357584339383878,
498
- .1804807884018343
499
- ],
500
- [
501
- .21263900587151027,
502
- .715168678767756,
503
- .07219231536073371
504
- ],
505
- [
506
- .01933081871559182,
507
- .11919477979462598,
508
- .9505321522496607
509
- ]
510
- ];
511
- const XYZ_TO_SRGB = [
512
- [
513
- 3.2409699419045226,
514
- -1.537383177570094,
515
- -.4986107602930034
516
- ],
517
- [
518
- -.9692436362808796,
519
- 1.8759675015077202,
520
- .04155505740717559
521
- ],
522
- [
523
- .05563007969699366,
524
- -.20397695888897652,
525
- 1.0569715142428786
526
- ]
527
- ];
528
- const P3_TO_XYZ = [
529
- [
530
- .4865709486482162,
531
- .26566769316909306,
532
- .1982172852343625
533
- ],
534
- [
535
- .2289745640697488,
536
- .6917385218365064,
537
- .079286914093745
538
- ],
539
- [
540
- 0,
541
- .04511338185890264,
542
- 1.043944368900976
543
- ]
544
- ];
545
- const XYZ_TO_P3 = [
546
- [
547
- 2.493496911941425,
548
- -.9313836179191239,
549
- -.40271078445071684
550
- ],
551
- [
552
- -.8294889695615747,
553
- 1.7626640603183463,
554
- .023624685841943577
555
- ],
556
- [
557
- .03584583024378447,
558
- -.07617238926804182,
559
- .9568845240076872
560
- ]
561
- ];
562
- /** Bradford chromatic adaptation between the D65 and D50 white points (Lab and LCH use D50). */
563
- const D65_TO_D50 = [
564
- [
565
- 1.0479297925449969,
566
- .022946870601609652,
567
- -.05019226628920524
568
- ],
569
- [
570
- .02962780877005599,
571
- .9904344267538799,
572
- -.017073799063418826
573
- ],
574
- [
575
- -.009243040646204504,
576
- .015055191490298152,
577
- .7518742814281371
578
- ]
579
- ];
580
- const D50_TO_D65 = [
581
- [
582
- .955473421488075,
583
- -.02309845494876471,
584
- .06325924320057072
585
- ],
586
- [
587
- -.0283697093338637,
588
- 1.0099953980813041,
589
- .021041441191917323
590
- ],
591
- [
592
- .012314014864481998,
593
- -.020507649298898964,
594
- 1.330365926242124
595
- ]
596
- ];
597
- /** Linear sRGB to OKLab's cone responses, and back. */
598
- const LRGB_TO_LMS = [
599
- [
600
- .412221469470763,
601
- .5363325372617348,
602
- .0514459932675022
603
- ],
604
- [
605
- .2119034958178252,
606
- .6806995506452344,
607
- .1073969535369406
608
- ],
609
- [
610
- .0883024591900564,
611
- .2817188391361215,
612
- .6299787016738222
613
- ]
614
- ];
615
- const LMS_TO_LRGB = [
616
- [
617
- 4.076741636075957,
618
- -3.3077115392580616,
619
- .2309699031821044
620
- ],
621
- [
622
- -1.2684379732850317,
623
- 2.6097573492876887,
624
- -.3413193760026573
625
- ],
626
- [
627
- -.0041960761386756,
628
- -.7034186179359362,
629
- 1.7076146940746117
630
- ]
631
- ];
632
- const LMS_TO_OKLAB = [
633
- [
634
- .210454268309314,
635
- .7936177747023054,
636
- -.0040720430116193
637
- ],
638
- [
639
- 1.9779985324311684,
640
- -2.42859224204858,
641
- .450593709617411
642
- ],
643
- [
644
- .0259040424655478,
645
- .7827717124575296,
646
- -.8086757549230774
647
- ]
648
- ];
649
- const OKLAB_TO_LMS = [
650
- [
651
- 1,
652
- .3963377773761749,
653
- .2158037573099136
654
- ],
655
- [
656
- 1,
657
- -.1055613458156586,
658
- -.0638541728258133
659
- ],
660
- [
661
- 1,
662
- -.0894841775298119,
663
- -1.2914855480194092
664
- ]
665
- ];
666
- const toXyz = (c) => mul(SRGB_TO_XYZ, linearRgb(c));
667
- const fromXyz = (xyz, alpha) => fromLinearRgb(mul(XYZ_TO_SRGB, xyz), alpha);
668
- /** Display P3 channels (gamma-encoded, 0 to 1 inside P3). */
669
- const toP3 = (c) => map3(mul(XYZ_TO_P3, toXyz(c)), fromLinear);
670
- const fromP3 = (p3, alpha) => fromXyz(mul(P3_TO_XYZ, map3(p3, toLinear)), alpha);
671
- const fromXyzD50 = (xyz, alpha) => fromXyz(mul(D50_TO_D65, xyz), alpha);
672
- /** OKLab: L in [0, 1], a and b around ±0.4. */
673
- const toOklab = (c) => mul(LMS_TO_OKLAB, map3(mul(LRGB_TO_LMS, linearRgb(c)), Math.cbrt));
674
- const fromOklab = (lab, alpha) => fromLinearRgb(mul(LMS_TO_LRGB, map3(mul(OKLAB_TO_LMS, lab), (v) => v ** 3)), alpha);
675
- const D50_WHITE = [
676
- .3457 / .3585,
677
- 1,
678
- .2958 / .3585
679
- ];
680
- const KAPPA = 24389 / 27;
681
- const EPSILON = 216 / 24389;
682
- /** CIE Lab (D50): L in [0, 100], a and b around ±125. */
683
- const toLab = (c) => {
684
- const [x, y, z] = map3(mul(D65_TO_D50, toXyz(c)), (v, i) => v / D50_WHITE[i]);
685
- const f = (v) => v > EPSILON ? Math.cbrt(v) : (KAPPA * v + 16) / 116;
686
- const [fx, fy, fz] = [
687
- f(x),
688
- f(y),
689
- f(z)
690
- ];
691
- return [
692
- 116 * fy - 16,
693
- 500 * (fx - fy),
694
- 200 * (fy - fz)
695
- ];
696
- };
697
- const fromLab = ([l, a, b], alpha) => {
698
- const fy = (l + 16) / 116;
699
- const fx = a / 500 + fy;
700
- const fz = fy - b / 200;
701
- const xyz = [
702
- fx ** 3 > EPSILON ? fx ** 3 : (116 * fx - 16) / KAPPA,
703
- l > KAPPA * EPSILON ? fy ** 3 : l / KAPPA,
704
- fz ** 3 > EPSILON ? fz ** 3 : (116 * fz - 16) / KAPPA
705
- ];
706
- return fromXyzD50(map3(xyz, (v, i) => v * D50_WHITE[i]), alpha);
707
- };
708
- /** Lab-like to its polar form: lightness, chroma, and hue in degrees from 0 to 360. */
709
- const toPolar = ([l, a, b]) => [
710
- l,
711
- Math.hypot(a, b),
712
- (Math.atan2(b, a) * 180 / Math.PI + 360) % 360
713
- ];
714
- const fromPolar = ([l, c, h]) => [
715
- l,
716
- c * Math.cos(h * Math.PI / 180),
717
- c * Math.sin(h * Math.PI / 180)
718
- ];
719
- const clip01 = (v) => Math.min(1, Math.max(0, v));
720
- /**
721
- * Below this spread between channels a colour is grey: what is left is rounding error from
722
- * converting it (from Lab, OKLCH, P3...), and its hue and saturation would be noise. The
723
- * faintest real tint in 8-bit sRGB, such as #fffffe, has a spread of about 0.004.
724
- */
725
- const GREY = 1e-9;
726
- /**
727
- * Hue, saturation and lightness of a colour inside sRGB (hue 0 for greys), with s and l in [0, 1].
728
- * Channels are clipped first: colours count as inside sRGB within rounding error, a little past 0 or 1.
729
- */
730
- function toHsl(c) {
731
- const [r, g, b] = map3([
732
- c.r,
733
- c.g,
734
- c.b
735
- ], clip01);
736
- const max = Math.max(r, g, b);
737
- const min = Math.min(r, g, b);
738
- const l = (max + min) / 2;
739
- const d = max - min;
740
- if (d < GREY) return [
741
- 0,
742
- 0,
743
- l
744
- ];
745
- const s = (max - l) / Math.min(l, 1 - l);
746
- let h;
747
- if (max === r) h = (g - b) / d + (g < b ? 6 : 0);
748
- else if (max === g) h = (b - r) / d + 2;
749
- else h = (r - g) / d + 4;
750
- return [
751
- h * 60,
752
- s,
753
- l
754
- ];
755
- }
756
- function fromHsl(h, s, l, alpha) {
757
- const hue = (h % 360 + 360) % 360;
758
- const f = (n) => {
759
- const k = (n + hue / 30) % 12;
760
- return l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k - 3, 9 - k, 1));
761
- };
762
- return color(f(0), f(8), f(4), alpha);
763
- }
764
- function fromHwb(h, w, b, alpha) {
765
- if (w + b >= 1) {
766
- const grey = w / (w + b);
767
- return color(grey, grey, grey, alpha);
768
- }
769
- const pure = fromHsl(h, 1, .5, 1);
770
- const scale = (v) => v * (1 - w - b) + w;
771
- return color(scale(pure.r), scale(pure.g), scale(pure.b), alpha);
772
- }
773
- /** Hue, whiteness and blackness of an sRGB colour, with w and b in [0, 1] (channels clipped, as in `toHsl`). */
774
- function toHwb(c) {
775
- const [h] = toHsl(c);
776
- const [r, g, b] = map3([
777
- c.r,
778
- c.g,
779
- c.b
780
- ], clip01);
781
- return [
782
- h,
783
- Math.min(r, g, b),
784
- 1 - Math.max(r, g, b)
785
- ];
786
- }
787
- /** Distance in OKLab: about 0.02 is the smallest difference people notice. */
788
- const deltaEOK = (a, b) => {
789
- const [l1, a1, b1] = toOklab(a);
790
- const [l2, a2, b2] = toOklab(b);
791
- return Math.hypot(l1 - l2, a1 - a2, b1 - b2);
792
- };
793
- const channels = (c, gamut) => gamut === "srgb" ? [
794
- c.r,
795
- c.g,
796
- c.b
797
- ] : toP3(c);
798
- const clipTo = (c, gamut) => {
799
- const [x, y, z] = map3(channels(c, gamut), clip01);
800
- return gamut === "srgb" ? color(x, y, z, c.alpha) : fromP3([
801
- x,
802
- y,
803
- z
804
- ], c.alpha);
805
- };
806
- /** Whether a colour is inside a gamut, within rounding error. */
807
- function inGamut(c, gamut = "srgb") {
808
- return channels(c, gamut).every((v) => v >= -1e-6 && v <= 1 + 1e-6);
809
- }
810
- /**
811
- * The colour inside `gamut` that looks closest: the CSS Color 4 gamut mapping
812
- * algorithm, which keeps lightness and hue and reduces chroma in OKLCH until
813
- * clipping is no longer visible (`"map"`), or plain clipping of each channel (`"clip"`).
814
- */
815
- function toGamut(c, gamut = "srgb", method = "map") {
816
- if (inGamut(c, gamut)) return clipTo(c, gamut);
817
- if (method === "clip") return clipTo(c, gamut);
818
- const [l, chroma, hue] = toPolar(toOklab(c));
819
- if (l >= 1 - 1e-7) return clipTo(color(1, 1, 1, c.alpha), gamut);
820
- if (l <= 1e-7) return clipTo(color(0, 0, 0, c.alpha), gamut);
821
- const JND = .02;
822
- let low = 0;
823
- let high = chroma;
824
- let lowInGamut = true;
825
- let current = c;
826
- let clipped = clipTo(current, gamut);
827
- if (deltaEOK(clipped, current) < JND) return clipped;
828
- while (high - low > 1e-4) {
829
- const mid = (low + high) / 2;
830
- current = fromOklab(fromPolar([
831
- l,
832
- mid,
833
- hue
834
- ]), c.alpha);
835
- if (lowInGamut && inGamut(current, gamut)) {
836
- low = mid;
837
- continue;
838
- }
839
- clipped = clipTo(current, gamut);
840
- const e = deltaEOK(clipped, current);
841
- if (e < JND) {
842
- if (JND - e < 1e-4) return clipped;
843
- lowInGamut = false;
844
- low = mid;
845
- } else high = mid;
846
- }
847
- return clipped;
848
- }
849
- //#endregion
850
- //#region src/color/names.ts
851
- /**
852
- * The 148 named colours of CSS Color 4, as "name rrggbb" pairs. Parsed into a map
853
- * the first time a name is looked up, so the table costs nothing until then.
854
- */
855
- const NAMED = [
856
- "aliceblue f0f8ff antiquewhite faebd7 aqua 00ffff aquamarine 7fffd4 azure f0ffff beige f5f5dc bisque ffe4c4",
857
- "black 000000 blanchedalmond ffebcd blue 0000ff blueviolet 8a2be2 brown a52a2a burlywood deb887",
858
- "cadetblue 5f9ea0 chartreuse 7fff00 chocolate d2691e coral ff7f50 cornflowerblue 6495ed cornsilk fff8dc",
859
- "crimson dc143c cyan 00ffff darkblue 00008b darkcyan 008b8b darkgoldenrod b8860b darkgray a9a9a9",
860
- "darkgreen 006400 darkgrey a9a9a9 darkkhaki bdb76b darkmagenta 8b008b darkolivegreen 556b2f darkorange ff8c00",
861
- "darkorchid 9932cc darkred 8b0000 darksalmon e9967a darkseagreen 8fbc8f darkslateblue 483d8b",
862
- "darkslategray 2f4f4f darkslategrey 2f4f4f darkturquoise 00ced1 darkviolet 9400d3 deeppink ff1493",
863
- "deepskyblue 00bfff dimgray 696969 dimgrey 696969 dodgerblue 1e90ff firebrick b22222 floralwhite fffaf0",
864
- "forestgreen 228b22 fuchsia ff00ff gainsboro dcdcdc ghostwhite f8f8ff gold ffd700 goldenrod daa520 gray 808080",
865
- "green 008000 greenyellow adff2f grey 808080 honeydew f0fff0 hotpink ff69b4 indianred cd5c5c indigo 4b0082",
866
- "ivory fffff0 khaki f0e68c lavender e6e6fa lavenderblush fff0f5 lawngreen 7cfc00 lemonchiffon fffacd",
867
- "lightblue add8e6 lightcoral f08080 lightcyan e0ffff lightgoldenrodyellow fafad2 lightgray d3d3d3",
868
- "lightgreen 90ee90 lightgrey d3d3d3 lightpink ffb6c1 lightsalmon ffa07a lightseagreen 20b2aa",
869
- "lightskyblue 87cefa lightslategray 778899 lightslategrey 778899 lightsteelblue b0c4de lightyellow ffffe0",
870
- "lime 00ff00 limegreen 32cd32 linen faf0e6 magenta ff00ff maroon 800000 mediumaquamarine 66cdaa",
871
- "mediumblue 0000cd mediumorchid ba55d3 mediumpurple 9370db mediumseagreen 3cb371 mediumslateblue 7b68ee",
872
- "mediumspringgreen 00fa9a mediumturquoise 48d1cc mediumvioletred c71585 midnightblue 191970 mintcream f5fffa",
873
- "mistyrose ffe4e1 moccasin ffe4b5 navajowhite ffdead navy 000080 oldlace fdf5e6 olive 808000 olivedrab 6b8e23",
874
- "orange ffa500 orangered ff4500 orchid da70d6 palegoldenrod eee8aa palegreen 98fb98 paleturquoise afeeee",
875
- "palevioletred db7093 papayawhip ffefd5 peachpuff ffdab9 peru cd853f pink ffc0cb plum dda0dd powderblue b0e0e6",
876
- "purple 800080 rebeccapurple 663399 red ff0000 rosybrown bc8f8f royalblue 4169e1 saddlebrown 8b4513",
877
- "salmon fa8072 sandybrown f4a460 seagreen 2e8b57 seashell fff5ee sienna a0522d silver c0c0c0 skyblue 87ceeb",
878
- "slateblue 6a5acd slategray 708090 slategrey 708090 snow fffafa springgreen 00ff7f steelblue 4682b4 tan d2b48c",
879
- "teal 008080 thistle d8bfd8 tomato ff6347 turquoise 40e0d0 violet ee82ee wheat f5deb3 white ffffff",
880
- "whitesmoke f5f5f5 yellow ffff00 yellowgreen 9acd32"
881
- ].join(" ");
882
- let table;
883
- /** The colour for a CSS colour name (lowercase), as 0xrrggbb, or `undefined`. */
884
- function namedColor(name) {
885
- if (table === void 0) {
886
- table = /* @__PURE__ */ new Map();
887
- const parts = NAMED.split(" ");
888
- for (let i = 0; i < parts.length; i += 2) table.set(parts[i], parseInt(parts[i + 1], 16));
889
- }
890
- return table.get(name);
891
- }
892
- //#endregion
893
- //#region src/color/parse.ts
894
- /** Longer input is not a colour: parsing stays cheap whatever is pasted. */
895
- const MAX_LENGTH = 256;
896
- const NUMBER = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/;
897
- const HEX = /^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/;
898
- const FUNCTION = /^([a-z][a-z\d-]*)\(([^()]*)\)$/;
899
- const ANGLE_UNITS = {
900
- deg: 1,
901
- grad: .9,
902
- rad: 180 / Math.PI,
903
- turn: 360
904
- };
905
- /** One component: a number, a percentage, an angle (in degrees) or `none`. */
906
- function token(text) {
907
- if (text === "none") return {
908
- kind: "none",
909
- value: 0
910
- };
911
- if (text.endsWith("%")) {
912
- const body = text.slice(0, -1);
913
- return NUMBER.test(body) ? {
914
- kind: "percent",
915
- value: Number(body)
916
- } : null;
917
- }
918
- const unit = /[a-z]+$/.exec(text)?.[0];
919
- if (unit !== void 0) {
920
- const factor = ANGLE_UNITS[unit];
921
- const body = text.slice(0, -unit.length);
922
- return factor === void 0 || !NUMBER.test(body) ? null : {
923
- kind: "angle",
924
- value: Number(body) * factor
925
- };
926
- }
927
- return NUMBER.test(text) ? {
928
- kind: "number",
929
- value: Number(text)
930
- } : null;
931
- }
932
- const clamp = (v, min, max) => Math.min(max, Math.max(min, v));
933
- /** A component's value: numbers as they are, percentages scaled so 100% is `full`. */
934
- function amount(t, full, allowed) {
935
- if (t.kind === "none") return 0;
936
- if (!allowed.includes(t.kind)) return null;
937
- return t.kind === "percent" ? t.value / 100 * full : t.value;
938
- }
939
- const hueOf = (t) => amount(t, 0, ["number", "angle"]);
940
- const alphaOf = (t) => {
941
- if (t === void 0) return 1;
942
- const value = amount(t, 1, ["number", "percent"]);
943
- return value === null ? null : clamp(value, 0, 1);
944
- };
945
- /** Splits arguments into three components and an optional alpha; `legacy` for the comma syntax. */
946
- function split(args) {
947
- const legacy = args.includes(",");
948
- let main;
949
- let alphaText;
950
- if (legacy) {
951
- const list = args.split(",").map((part) => part.trim());
952
- if (list.length < 3 || list.length > 4) return null;
953
- main = list.slice(0, 3);
954
- alphaText = list[3];
955
- } else {
956
- const [body, rest, extra] = args.split("/");
957
- if (extra !== void 0) return null;
958
- main = body.trim().split(/\s+/);
959
- alphaText = rest?.trim();
960
- if (main.length !== 3 || alphaText === "") return null;
961
- }
962
- const parts = main.map(token);
963
- if (parts.some((part) => part === null)) return null;
964
- const alpha = alphaText === void 0 ? void 0 : token(alphaText);
965
- if (alpha === null) return null;
966
- if (legacy && [...parts, alpha].some((part) => part?.kind === "none")) return null;
967
- return {
968
- parts,
969
- alpha,
970
- legacy
971
- };
972
- }
973
- function rgb(parts, legacy) {
974
- if (legacy && new Set(parts.map((part) => part.kind)).size !== 1) return null;
975
- const values = parts.map((part) => amount(part, 255, ["number", "percent"]));
976
- const vector = vec3(values);
977
- return vector === null ? null : map3(vector, (v) => clamp(v, 0, 255) / 255);
978
- }
979
- const PREDEFINED = {
980
- srgb: ([r, g, b], alpha) => color(r, g, b, alpha),
981
- "srgb-linear": fromLinearRgb,
982
- "display-p3": fromP3,
983
- xyz: fromXyz,
984
- "xyz-d65": fromXyz,
985
- "xyz-d50": fromXyzD50
986
- };
987
- /** `color(space c1 c2 c3 / alpha)`. */
988
- function predefined(args) {
989
- const match = /^([a-z\d-]+)\s+(.*)$/.exec(args.trim());
990
- if (match === null) return null;
991
- const convert = PREDEFINED[match[1]];
992
- const parsed = split(match[2]);
993
- if (convert === void 0 || parsed === null || parsed.legacy) return null;
994
- const values = parsed.parts.map((part) => amount(part, 1, ["number", "percent"]));
995
- const alpha = alphaOf(parsed.alpha);
996
- const vector = vec3(values);
997
- return vector === null || alpha === null ? null : convert(vector, alpha);
998
- }
999
- function functional(name, args) {
1000
- if (name === "color") return predefined(args);
1001
- const parsed = split(args);
1002
- if (parsed === null) return null;
1003
- const { parts, legacy } = parsed;
1004
- const [a, b, c] = parts;
1005
- const alpha = alphaOf(parsed.alpha);
1006
- if (alpha === null) return null;
1007
- switch (name) {
1008
- case "rgb":
1009
- case "rgba": {
1010
- const values = rgb(parts, legacy);
1011
- return values === null ? null : color(values[0], values[1], values[2], alpha);
1012
- }
1013
- case "hsl":
1014
- case "hsla": {
1015
- const hue = hueOf(a);
1016
- const kinds = legacy ? ["percent"] : ["number", "percent"];
1017
- const s = amount(b, 100, kinds);
1018
- const l = amount(c, 100, kinds);
1019
- if (hue === null || s === null || l === null) return null;
1020
- return fromHsl(hue, clamp(s, 0, 100) / 100, clamp(l, 0, 100) / 100, alpha);
1021
- }
1022
- case "hwb": {
1023
- const hue = hueOf(a);
1024
- const w = amount(b, 100, ["number", "percent"]);
1025
- const k = amount(c, 100, ["number", "percent"]);
1026
- if (legacy || hue === null || w === null || k === null) return null;
1027
- return fromHwb(hue, clamp(w, 0, 100) / 100, clamp(k, 0, 100) / 100, alpha);
1028
- }
1029
- default: return legacy ? null : lab(name, a, b, c, alpha);
1030
- }
1031
- }
1032
- /** lab(), lch(), oklab() and oklch(). */
1033
- function lab(name, a, b, c, alpha) {
1034
- const ok = name.startsWith("ok");
1035
- const polar = name.endsWith("ch");
1036
- if (![
1037
- "lab",
1038
- "lch",
1039
- "oklab",
1040
- "oklch"
1041
- ].includes(name)) return null;
1042
- const lightMax = ok ? 1 : 100;
1043
- const l = amount(a, lightMax, ["number", "percent"]);
1044
- const second = amount(b, ok ? .4 : polar ? 150 : 125, ["number", "percent"]);
1045
- const third = polar ? hueOf(c) : amount(c, ok ? .4 : 125, ["number", "percent"]);
1046
- if (l === null || second === null || third === null) return null;
1047
- const lightness = clamp(l, 0, lightMax);
1048
- const values = polar ? fromPolar([
1049
- lightness,
1050
- Math.max(0, second),
1051
- third
1052
- ]) : [
1053
- lightness,
1054
- second,
1055
- third
1056
- ];
1057
- return ok ? fromOklab(values, alpha) : fromLab(values, alpha);
1058
- }
1059
- /**
1060
- * Parses a CSS colour, or returns `null`: hex (`#rgb`, `#rgba`, `#rrggbb`,
1061
- * `#rrggbbaa`), the 148 named colours and `transparent`, `rgb()` and `hsl()` in
1062
- * both syntaxes, `hwb()`, `lab()`, `lch()`, `oklab()`, `oklch()`, and `color()`
1063
- * in `srgb`, `srgb-linear`, `display-p3`, `xyz`, `xyz-d65` and `xyz-d50`.
1064
- * Never throws. Colours outside sRGB keep their exact value.
1065
- *
1066
- * Not colours on their own: `currentcolor`, system colours, `var()`, `calc()`,
1067
- * `color-mix()` and relative colours.
1068
- *
1069
- * @example
1070
- * parseColor('oklch(62.8% 0.258 29.23)'); // { r: 1, g: 0, b: 0, alpha: 1 } (rounded)
1071
- */
1072
- function parseColor(input) {
1073
- if (typeof input !== "string" || input.length > MAX_LENGTH) return null;
1074
- const text = input.trim().toLowerCase();
1075
- const hex = HEX.exec(text)?.[1];
1076
- if (hex !== void 0) {
1077
- const full = hex.length <= 4 ? hex.replace(/./g, (digit) => digit + digit) : hex;
1078
- const byte = (i) => parseInt(full.slice(i, i + 2), 16) / 255;
1079
- return color(byte(0), byte(2), byte(4), full.length === 8 ? byte(6) : 1);
1080
- }
1081
- if (text === "transparent") return color(0, 0, 0, 0);
1082
- const named = namedColor(text);
1083
- if (named !== void 0) return color((named >> 16 & 255) / 255, (named >> 8 & 255) / 255, (named & 255) / 255);
1084
- const match = FUNCTION.exec(text);
1085
- return match === null ? null : functional(match[1], match[2].trim());
1086
- }
1087
- //#endregion
1088
- //#region src/color/format.ts
1089
- const COLOR_FORMATS = /* @__PURE__ */ Object.freeze([
1090
- "hex",
1091
- "rgb",
1092
- "hsl",
1093
- "hwb",
1094
- "oklch",
1095
- "oklab",
1096
- "lab",
1097
- "lch",
1098
- "p3"
1099
- ]);
1100
- const isColor = (value) => typeof value === "object" && value !== null && [
1101
- "r",
1102
- "g",
1103
- "b",
1104
- "alpha"
1105
- ].every((key) => Number.isFinite(value[key]));
1106
- /** Resolves a colour input, throwing a typed error for anything that is not one. */
1107
- function toColor(input) {
1108
- if (typeof input === "string") {
1109
- const parsed = parseColor(input);
1110
- if (parsed === null) throw copyFailure("invalid-payload", `Not a colour: ${JSON.stringify(input.slice(0, 100))}.`);
1111
- return parsed;
1112
- }
1113
- if (!isColor(input)) throw copyFailure("invalid-payload", "A colour must be a CSS colour string or an { r, g, b, alpha } object with finite numbers.");
1114
- return input;
1115
- }
1116
- /** Rounds to `places` decimals, without trailing zeros or `-0`. */
1117
- function num(value, places) {
1118
- const factor = 10 ** places;
1119
- const rounded = Math.round(value * factor) / factor;
1120
- return String(Object.is(rounded, -0) ? 0 : rounded);
1121
- }
1122
- /** A hue in degrees, with 360 written as 0. */
1123
- const hue = (value, places) => {
1124
- const text = num(value, places);
1125
- return text === "360" ? "0" : text;
1126
- };
1127
- const byte = (v) => Math.round(Math.min(1, Math.max(0, v)) * 255);
1128
- /** The alpha suffix of a functional notation: nothing when opaque. */
1129
- const alphaPart = (alpha, legacy, places) => alpha >= 1 ? "" : legacy ? `, ${num(alpha, places)}` : ` / ${num(alpha, places)}`;
1130
- /**
1131
- * Writes a colour in a CSS format. Text is parsed first, so this also converts
1132
- * between formats.
1133
- *
1134
- * @example
1135
- * formatColor('rgb(255 0 0)', 'oklch'); // 'oklch(62.8% 0.2577 29.23)'
1136
- * formatColor('color(display-p3 1 0 0)', 'hex'); // '#ff0000' after gamut mapping, never a wrong hue
1137
- */
1138
- function formatColor(input, format = "hex", options = {}) {
1139
- const c = toColor(input);
1140
- const { gamut = "map", legacy = false, uppercase = false, precision } = options;
1141
- const method = gamut;
1142
- if (method !== "map" && method !== "clip") throw copyFailure("invalid-payload", "`gamut` must be \"map\" or \"clip\".");
1143
- if (precision !== void 0 && !(Number.isInteger(precision) && precision >= 0 && precision <= 10)) throw copyFailure("invalid-payload", "`precision` must be an integer from 0 to 10.");
1144
- const dp = (fallback) => precision ?? fallback;
1145
- const a = c.alpha;
1146
- switch (format) {
1147
- case "hex": {
1148
- const s = toGamut(c, "srgb", gamut);
1149
- const digits = [
1150
- s.r,
1151
- s.g,
1152
- s.b,
1153
- ...a < 1 ? [a] : []
1154
- ].map((v) => byte(v).toString(16).padStart(2, "0")).join("");
1155
- return `#${uppercase ? digits.toUpperCase() : digits}`;
1156
- }
1157
- case "rgb": {
1158
- const s = toGamut(c, "srgb", gamut);
1159
- const [r, g, b] = [
1160
- s.r,
1161
- s.g,
1162
- s.b
1163
- ].map(byte);
1164
- return legacy ? `${a < 1 ? "rgba" : "rgb"}(${String(r)}, ${String(g)}, ${String(b)}${alphaPart(a, true, dp(3))})` : `rgb(${String(r)} ${String(g)} ${String(b)}${alphaPart(a, false, dp(3))})`;
1165
- }
1166
- case "hsl": {
1167
- const [h, s, l] = toHsl(toGamut(c, "srgb", gamut));
1168
- const [hh, ss, ll] = [
1169
- hue(h, dp(2)),
1170
- `${num(s * 100, dp(2))}%`,
1171
- `${num(l * 100, dp(2))}%`
1172
- ];
1173
- return legacy ? `${a < 1 ? "hsla" : "hsl"}(${hh}, ${ss}, ${ll}${alphaPart(a, true, dp(3))})` : `hsl(${hh} ${ss} ${ll}${alphaPart(a, false, dp(3))})`;
1174
- }
1175
- case "hwb": {
1176
- const [h, w, b] = toHwb(toGamut(c, "srgb", gamut));
1177
- return `hwb(${hue(h, dp(2))} ${num(w * 100, dp(2))}% ${num(b * 100, dp(2))}%${alphaPart(a, false, dp(3))})`;
1178
- }
1179
- case "oklab": {
1180
- const [l, x, y] = toOklab(c);
1181
- return `oklab(${num(l * 100, dp(2))}% ${num(x, dp(5))} ${num(y, dp(5))}${alphaPart(a, false, dp(3))})`;
1182
- }
1183
- case "oklch": {
1184
- const [l, ch, h] = toPolar(toOklab(c));
1185
- const chroma = num(ch, dp(5));
1186
- return `oklch(${num(l * 100, dp(2))}% ${chroma} ${chroma === "0" ? "0" : hue(h, dp(2))}${alphaPart(a, false, dp(3))})`;
1187
- }
1188
- case "lab": {
1189
- const [l, x, y] = toLab(c);
1190
- return `lab(${num(l, dp(2))} ${num(x, dp(2))} ${num(y, dp(2))}${alphaPart(a, false, dp(3))})`;
1191
- }
1192
- case "lch": {
1193
- const [l, ch, h] = toPolar(toLab(c));
1194
- const chroma = num(ch, dp(2));
1195
- return `lch(${num(l, dp(2))} ${chroma} ${chroma === "0" ? "0" : hue(h, dp(2))}${alphaPart(a, false, dp(3))})`;
1196
- }
1197
- case "p3": {
1198
- const [r, g, b] = toP3(toGamut(c, "p3", gamut));
1199
- return `color(display-p3 ${num(r, dp(4))} ${num(g, dp(4))} ${num(b, dp(4))}${alphaPart(a, false, dp(3))})`;
1200
- }
1201
- default: throw copyFailure("invalid-payload", `Unknown colour format ${JSON.stringify(String(format))}: use one of ${COLOR_FORMATS.join(", ")}.`);
1202
- }
1203
- }
1204
- //#endregion
1205
- //#region src/color/contrast.ts
1206
- const WHITE$1 = /* @__PURE__ */ color(1, 1, 1);
1207
- /** `top` drawn over `bottom`, both made opaque first. */
1208
- function over(top, bottom) {
1209
- const mix = (a, b) => a * top.alpha + b * (1 - top.alpha);
1210
- return color(mix(top.r, bottom.r), mix(top.g, bottom.g), mix(top.b, bottom.b));
1211
- }
1212
- /** WCAG 2 relative luminance of an opaque sRGB colour. */
1213
- function luminance(c) {
1214
- const lin = (v) => v <= .04045 ? v / 12.92 : ((v + .055) / 1.055) ** 2.4;
1215
- return .2126 * lin(c.r) + .7152 * lin(c.g) + .0722 * lin(c.b);
1216
- }
1217
- /**
1218
- * The WCAG 2 contrast ratio of text over a background, from 1 to 21. Colours are
1219
- * mapped into sRGB, a translucent background is drawn over white, and translucent
1220
- * text over the background, as a browser would show them. Never rounded: 4.499 is
1221
- * not 4.5.
1222
- *
1223
- * @example
1224
- * contrastRatio('#767676', '#fff'); // 4.54
1225
- */
1226
- function contrastRatio(text, background) {
1227
- const bg = over(toGamut(toColor(background)), WHITE$1);
1228
- const [light, dark] = [luminance(over(toGamut(toColor(text)), bg)), luminance(bg)].sort((a, b) => b - a);
1229
- return (light + .05) / (dark + .05);
1230
- }
1231
- //#endregion
1232
326
  //#region src/rich/style.ts
1233
327
  const INHERITED = [
1234
328
  "color",
@@ -1537,7 +631,7 @@ const VOID = /* @__PURE__ */ new Set([
1537
631
  ]);
1538
632
  const BLOCK_DISPLAY = /^(?:block|flex|grid|flow-root|list-item|table)$/;
1539
633
  const DATA_IMAGE = /^data:image\/(?:png|jpeg|gif|webp);base64,[a-z\d+/]+=*$/i;
1540
- function positive(value, fallback, name) {
634
+ function positive$1(value, fallback, name) {
1541
635
  if (value === void 0) return fallback;
1542
636
  if (Number.isInteger(value) && value > 0) return value;
1543
637
  throw copyFailure("invalid-payload", `\`${name}\` must be a positive integer.`);
@@ -1568,7 +662,7 @@ var Builder = class {
1568
662
  this.elements = 0;
1569
663
  this.size = 0;
1570
664
  this.implied = /* @__PURE__ */ new WeakSet();
1571
- 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";
1572
666
  const baseOption = base === void 0 ? {} : { base };
1573
667
  this.resolveLink = linkUrlResolver({
1574
668
  ...baseOption,
@@ -1713,7 +807,7 @@ var Builder = class {
1713
807
  return;
1714
808
  }
1715
809
  if (name === "p" && holdsBlocks(source)) name = "div";
1716
- if (HEADINGS.has(name) && HEADINGS.has(parentTag)) name = "span";
810
+ if (HEADINGS$1.has(name) && HEADINGS$1.has(parentTag)) name = "span";
1717
811
  if ((name === "li" || name === "dd" || name === "dt") && closesItem(name, parent)) name = "div";
1718
812
  if (name === "div" && PHRASING.has(parentTag)) name = "span";
1719
813
  if (name === "a" && insideLink(parent)) name = "span";
@@ -1770,7 +864,7 @@ var Builder = class {
1770
864
  function domFor(source) {
1771
865
  if (typeof source === "string") {
1772
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.");
1773
- const doc = new DOMParser().parseFromString(`<!doctype html><body>${source}`, "text/html");
867
+ const doc = parseInertHtml(`<!doctype html><body>${source}`);
1774
868
  return {
1775
869
  doc,
1776
870
  root: doc.body,
@@ -1836,7 +930,7 @@ function prepareRich(source, options = {}) {
1836
930
  throw copyFailure("invalid-payload", `\`ignore\` is not a valid CSS selector: ${options.ignore}`, cause);
1837
931
  }
1838
932
  const out = doc.implementation.createHTMLDocument("");
1839
- 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));
1840
934
  const container = out.createElement("div");
1841
935
  if (typeof source === "string") builder.children(root, container, ROOT_PARENT, page, null);
1842
936
  else builder.node(root, container, ROOT_PARENT, page, range, true);
@@ -1907,6 +1001,1092 @@ function richTransform(options = {}) {
1907
1001
  };
1908
1002
  }
1909
1003
  //#endregion
1910
- 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 };
1911
2091
 
1912
2092
  //# sourceMappingURL=rich.js.map