react-smart-copy 1.16.0 → 1.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +73 -1
- package/dist/rich.cjs +1883 -0
- package/dist/rich.cjs.map +1 -0
- package/dist/rich.d.cts +212 -0
- package/dist/rich.d.ts +212 -0
- package/dist/rich.js +1879 -0
- package/dist/rich.js.map +1 -0
- package/package.json +35 -4
package/dist/rich.js
ADDED
|
@@ -0,0 +1,1879 @@
|
|
|
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
|
|
136
|
+
//#region src/rich/policy.ts
|
|
137
|
+
/**
|
|
138
|
+
* What portable rich text may contain: the elements, attributes and CSS that Gmail,
|
|
139
|
+
* Outlook, Apple Mail, Google Docs, Word, Notion and Slack keep, and nothing that
|
|
140
|
+
* can run, load or track. Everything not listed here is left out.
|
|
141
|
+
*/
|
|
142
|
+
/** Elements written as they are. */
|
|
143
|
+
const KEEP = /* @__PURE__ */ new Set([
|
|
144
|
+
"a",
|
|
145
|
+
"abbr",
|
|
146
|
+
"b",
|
|
147
|
+
"bdi",
|
|
148
|
+
"bdo",
|
|
149
|
+
"blockquote",
|
|
150
|
+
"br",
|
|
151
|
+
"caption",
|
|
152
|
+
"cite",
|
|
153
|
+
"code",
|
|
154
|
+
"col",
|
|
155
|
+
"colgroup",
|
|
156
|
+
"dd",
|
|
157
|
+
"del",
|
|
158
|
+
"dfn",
|
|
159
|
+
"div",
|
|
160
|
+
"dl",
|
|
161
|
+
"dt",
|
|
162
|
+
"em",
|
|
163
|
+
"figcaption",
|
|
164
|
+
"figure",
|
|
165
|
+
"h1",
|
|
166
|
+
"h2",
|
|
167
|
+
"h3",
|
|
168
|
+
"h4",
|
|
169
|
+
"h5",
|
|
170
|
+
"h6",
|
|
171
|
+
"hr",
|
|
172
|
+
"i",
|
|
173
|
+
"img",
|
|
174
|
+
"ins",
|
|
175
|
+
"kbd",
|
|
176
|
+
"li",
|
|
177
|
+
"mark",
|
|
178
|
+
"ol",
|
|
179
|
+
"p",
|
|
180
|
+
"pre",
|
|
181
|
+
"q",
|
|
182
|
+
"s",
|
|
183
|
+
"samp",
|
|
184
|
+
"small",
|
|
185
|
+
"span",
|
|
186
|
+
"strong",
|
|
187
|
+
"sub",
|
|
188
|
+
"sup",
|
|
189
|
+
"table",
|
|
190
|
+
"tbody",
|
|
191
|
+
"td",
|
|
192
|
+
"tfoot",
|
|
193
|
+
"th",
|
|
194
|
+
"thead",
|
|
195
|
+
"time",
|
|
196
|
+
"tr",
|
|
197
|
+
"u",
|
|
198
|
+
"ul",
|
|
199
|
+
"var"
|
|
200
|
+
]);
|
|
201
|
+
/** Elements left out with everything inside them: they run, load, embed, or are page chrome. */
|
|
202
|
+
const DROP = /* @__PURE__ */ new Set([
|
|
203
|
+
"applet",
|
|
204
|
+
"audio",
|
|
205
|
+
"base",
|
|
206
|
+
"button",
|
|
207
|
+
"canvas",
|
|
208
|
+
"datalist",
|
|
209
|
+
"dialog",
|
|
210
|
+
"embed",
|
|
211
|
+
"frame",
|
|
212
|
+
"frameset",
|
|
213
|
+
"head",
|
|
214
|
+
"iframe",
|
|
215
|
+
"input",
|
|
216
|
+
"link",
|
|
217
|
+
"map",
|
|
218
|
+
"math",
|
|
219
|
+
"meta",
|
|
220
|
+
"meter",
|
|
221
|
+
"noembed",
|
|
222
|
+
"noframes",
|
|
223
|
+
"noscript",
|
|
224
|
+
"object",
|
|
225
|
+
"option",
|
|
226
|
+
"optgroup",
|
|
227
|
+
"output",
|
|
228
|
+
"param",
|
|
229
|
+
"portal",
|
|
230
|
+
"progress",
|
|
231
|
+
"script",
|
|
232
|
+
"select",
|
|
233
|
+
"slot",
|
|
234
|
+
"source",
|
|
235
|
+
"style",
|
|
236
|
+
"svg",
|
|
237
|
+
"template",
|
|
238
|
+
"textarea",
|
|
239
|
+
"title",
|
|
240
|
+
"track",
|
|
241
|
+
"video"
|
|
242
|
+
]);
|
|
243
|
+
/** Elements that become a `<div>`: blocks without an email-safe equivalent. */
|
|
244
|
+
const AS_BLOCK = /* @__PURE__ */ new Set([
|
|
245
|
+
"address",
|
|
246
|
+
"article",
|
|
247
|
+
"aside",
|
|
248
|
+
"body",
|
|
249
|
+
"center",
|
|
250
|
+
"details",
|
|
251
|
+
"fieldset",
|
|
252
|
+
"footer",
|
|
253
|
+
"form",
|
|
254
|
+
"header",
|
|
255
|
+
"hgroup",
|
|
256
|
+
"html",
|
|
257
|
+
"legend",
|
|
258
|
+
"listing",
|
|
259
|
+
"main",
|
|
260
|
+
"menu",
|
|
261
|
+
"nav",
|
|
262
|
+
"plaintext",
|
|
263
|
+
"search",
|
|
264
|
+
"section",
|
|
265
|
+
"summary",
|
|
266
|
+
"xmp"
|
|
267
|
+
]);
|
|
268
|
+
/** Elements whose children are block-level text in the plain-text version. */
|
|
269
|
+
const TEXT_BLOCKS = /* @__PURE__ */ new Set([
|
|
270
|
+
"blockquote",
|
|
271
|
+
"caption",
|
|
272
|
+
"dd",
|
|
273
|
+
"div",
|
|
274
|
+
"dl",
|
|
275
|
+
"dt",
|
|
276
|
+
"figcaption",
|
|
277
|
+
"figure",
|
|
278
|
+
"h1",
|
|
279
|
+
"h2",
|
|
280
|
+
"h3",
|
|
281
|
+
"h4",
|
|
282
|
+
"h5",
|
|
283
|
+
"h6",
|
|
284
|
+
"hr",
|
|
285
|
+
"li",
|
|
286
|
+
"ol",
|
|
287
|
+
"p",
|
|
288
|
+
"pre",
|
|
289
|
+
"table",
|
|
290
|
+
"tbody",
|
|
291
|
+
"tfoot",
|
|
292
|
+
"thead",
|
|
293
|
+
"tr",
|
|
294
|
+
"ul"
|
|
295
|
+
]);
|
|
296
|
+
/** What table parts may contain: anything else is moved out of the table by every HTML parser. */
|
|
297
|
+
const TABLE_CHILDREN = {
|
|
298
|
+
table: /* @__PURE__ */ new Set([
|
|
299
|
+
"caption",
|
|
300
|
+
"colgroup",
|
|
301
|
+
"thead",
|
|
302
|
+
"tbody",
|
|
303
|
+
"tfoot",
|
|
304
|
+
"tr"
|
|
305
|
+
]),
|
|
306
|
+
thead: /* @__PURE__ */ new Set(["tr"]),
|
|
307
|
+
tbody: /* @__PURE__ */ new Set(["tr"]),
|
|
308
|
+
tfoot: /* @__PURE__ */ new Set(["tr"]),
|
|
309
|
+
tr: /* @__PURE__ */ new Set(["td", "th"]),
|
|
310
|
+
colgroup: /* @__PURE__ */ new Set(["col"])
|
|
311
|
+
};
|
|
312
|
+
/** Elements that hold only text-level content: a block inside one would be split out by HTML parsers. */
|
|
313
|
+
const PHRASING = /* @__PURE__ */ new Set([
|
|
314
|
+
"a",
|
|
315
|
+
"abbr",
|
|
316
|
+
"b",
|
|
317
|
+
"bdi",
|
|
318
|
+
"bdo",
|
|
319
|
+
"cite",
|
|
320
|
+
"code",
|
|
321
|
+
"del",
|
|
322
|
+
"dfn",
|
|
323
|
+
"em",
|
|
324
|
+
"h1",
|
|
325
|
+
"h2",
|
|
326
|
+
"h3",
|
|
327
|
+
"h4",
|
|
328
|
+
"h5",
|
|
329
|
+
"h6",
|
|
330
|
+
"i",
|
|
331
|
+
"ins",
|
|
332
|
+
"kbd",
|
|
333
|
+
"mark",
|
|
334
|
+
"p",
|
|
335
|
+
"q",
|
|
336
|
+
"s",
|
|
337
|
+
"samp",
|
|
338
|
+
"small",
|
|
339
|
+
"span",
|
|
340
|
+
"strong",
|
|
341
|
+
"sub",
|
|
342
|
+
"sup",
|
|
343
|
+
"time",
|
|
344
|
+
"u",
|
|
345
|
+
"var"
|
|
346
|
+
]);
|
|
347
|
+
/** Table parts: outside their own parent, HTML parsers ignore their tags. */
|
|
348
|
+
const TABLE_PARTS = /* @__PURE__ */ new Set([
|
|
349
|
+
"caption",
|
|
350
|
+
"col",
|
|
351
|
+
"colgroup",
|
|
352
|
+
"tbody",
|
|
353
|
+
"td",
|
|
354
|
+
"tfoot",
|
|
355
|
+
"th",
|
|
356
|
+
"thead",
|
|
357
|
+
"tr"
|
|
358
|
+
]);
|
|
359
|
+
const HEADINGS = /* @__PURE__ */ new Set([
|
|
360
|
+
"h1",
|
|
361
|
+
"h2",
|
|
362
|
+
"h3",
|
|
363
|
+
"h4",
|
|
364
|
+
"h5",
|
|
365
|
+
"h6"
|
|
366
|
+
]);
|
|
367
|
+
/** Elements whose start tag closes an open `<p>`: a paragraph holding one is split in two by HTML parsers. */
|
|
368
|
+
const CLOSES_P = /* @__PURE__ */ new Set([
|
|
369
|
+
"blockquote",
|
|
370
|
+
"dd",
|
|
371
|
+
"dl",
|
|
372
|
+
"dt",
|
|
373
|
+
"figcaption",
|
|
374
|
+
"figure",
|
|
375
|
+
"h1",
|
|
376
|
+
"h2",
|
|
377
|
+
"h3",
|
|
378
|
+
"h4",
|
|
379
|
+
"h5",
|
|
380
|
+
"h6",
|
|
381
|
+
"hr",
|
|
382
|
+
"li",
|
|
383
|
+
"ol",
|
|
384
|
+
"p",
|
|
385
|
+
"pre",
|
|
386
|
+
"table",
|
|
387
|
+
"ul"
|
|
388
|
+
]);
|
|
389
|
+
/** Where HTML parsers stop looking for an open list item to close: their "special" elements, less address, div and p. */
|
|
390
|
+
const ITEM_SCOPE = /* @__PURE__ */ new Set([
|
|
391
|
+
"blockquote",
|
|
392
|
+
"br",
|
|
393
|
+
"caption",
|
|
394
|
+
"col",
|
|
395
|
+
"colgroup",
|
|
396
|
+
"dd",
|
|
397
|
+
"dl",
|
|
398
|
+
"dt",
|
|
399
|
+
"figcaption",
|
|
400
|
+
"figure",
|
|
401
|
+
"h1",
|
|
402
|
+
"h2",
|
|
403
|
+
"h3",
|
|
404
|
+
"h4",
|
|
405
|
+
"h5",
|
|
406
|
+
"h6",
|
|
407
|
+
"hr",
|
|
408
|
+
"img",
|
|
409
|
+
"li",
|
|
410
|
+
"ol",
|
|
411
|
+
"pre",
|
|
412
|
+
"table",
|
|
413
|
+
"tbody",
|
|
414
|
+
"td",
|
|
415
|
+
"tfoot",
|
|
416
|
+
"th",
|
|
417
|
+
"thead",
|
|
418
|
+
"tr",
|
|
419
|
+
"ul"
|
|
420
|
+
]);
|
|
421
|
+
/** Whether a new `li` (or `dd`, `dt`) under `parent` would close an open one, as HTML parsers do with `<li>` in `<li>`. */
|
|
422
|
+
function closesItem(name, parent) {
|
|
423
|
+
const group = name === "li" ? ["li"] : ["dd", "dt"];
|
|
424
|
+
for (let node = parent; node !== null && node.nodeType === 1; node = node.parentNode) {
|
|
425
|
+
const tag = node.localName;
|
|
426
|
+
if (group.includes(tag)) return true;
|
|
427
|
+
if (ITEM_SCOPE.has(tag)) return false;
|
|
428
|
+
}
|
|
429
|
+
return false;
|
|
430
|
+
}
|
|
431
|
+
const INTEGER = /^\d{1,4}$/;
|
|
432
|
+
/** Attributes kept per element (after `href` and `src`, which are checked as URLs). */
|
|
433
|
+
function attributeAllowed(tag, name, value) {
|
|
434
|
+
switch (name) {
|
|
435
|
+
case "dir": return /^(?:ltr|rtl|auto)$/i.test(value);
|
|
436
|
+
case "lang": return /^[a-z]{2,3}(?:-[a-z\d]{1,8})*$/i.test(value);
|
|
437
|
+
case "title": return [
|
|
438
|
+
"a",
|
|
439
|
+
"abbr",
|
|
440
|
+
"dfn"
|
|
441
|
+
].includes(tag);
|
|
442
|
+
case "colspan":
|
|
443
|
+
case "rowspan": return (tag === "td" || tag === "th") && INTEGER.test(value) && Number(value) >= 1 && Number(value) <= 1e3;
|
|
444
|
+
case "scope": return tag === "th" && /^(?:row|col|rowgroup|colgroup)$/i.test(value);
|
|
445
|
+
case "span": return (tag === "col" || tag === "colgroup") && INTEGER.test(value);
|
|
446
|
+
case "start": return tag === "ol" && /^-?\d{1,9}$/.test(value);
|
|
447
|
+
case "reversed": return tag === "ol";
|
|
448
|
+
case "type": return tag === "ol" && /^[1aAiI]$/.test(value);
|
|
449
|
+
case "value": return tag === "li" && /^-?\d{1,9}$/.test(value);
|
|
450
|
+
case "datetime": return tag === "time" && /^[\d\-:T.+ Z]{1,40}$/.test(value);
|
|
451
|
+
default: return false;
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
//#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
|
+
const linearRgb = (c) => [
|
|
477
|
+
toLinear(c.r),
|
|
478
|
+
toLinear(c.g),
|
|
479
|
+
toLinear(c.b)
|
|
480
|
+
];
|
|
481
|
+
const fromLinearRgb = ([r, g, b], alpha) => color(fromLinear(r), fromLinear(g), fromLinear(b), alpha);
|
|
482
|
+
const SRGB_TO_XYZ = [
|
|
483
|
+
[
|
|
484
|
+
.41239079926595934,
|
|
485
|
+
.357584339383878,
|
|
486
|
+
.1804807884018343
|
|
487
|
+
],
|
|
488
|
+
[
|
|
489
|
+
.21263900587151027,
|
|
490
|
+
.715168678767756,
|
|
491
|
+
.07219231536073371
|
|
492
|
+
],
|
|
493
|
+
[
|
|
494
|
+
.01933081871559182,
|
|
495
|
+
.11919477979462598,
|
|
496
|
+
.9505321522496607
|
|
497
|
+
]
|
|
498
|
+
];
|
|
499
|
+
const XYZ_TO_SRGB = [
|
|
500
|
+
[
|
|
501
|
+
3.2409699419045226,
|
|
502
|
+
-1.537383177570094,
|
|
503
|
+
-.4986107602930034
|
|
504
|
+
],
|
|
505
|
+
[
|
|
506
|
+
-.9692436362808796,
|
|
507
|
+
1.8759675015077202,
|
|
508
|
+
.04155505740717559
|
|
509
|
+
],
|
|
510
|
+
[
|
|
511
|
+
.05563007969699366,
|
|
512
|
+
-.20397695888897652,
|
|
513
|
+
1.0569715142428786
|
|
514
|
+
]
|
|
515
|
+
];
|
|
516
|
+
const P3_TO_XYZ = [
|
|
517
|
+
[
|
|
518
|
+
.4865709486482162,
|
|
519
|
+
.26566769316909306,
|
|
520
|
+
.1982172852343625
|
|
521
|
+
],
|
|
522
|
+
[
|
|
523
|
+
.2289745640697488,
|
|
524
|
+
.6917385218365064,
|
|
525
|
+
.079286914093745
|
|
526
|
+
],
|
|
527
|
+
[
|
|
528
|
+
0,
|
|
529
|
+
.04511338185890264,
|
|
530
|
+
1.043944368900976
|
|
531
|
+
]
|
|
532
|
+
];
|
|
533
|
+
const XYZ_TO_P3 = [
|
|
534
|
+
[
|
|
535
|
+
2.493496911941425,
|
|
536
|
+
-.9313836179191239,
|
|
537
|
+
-.40271078445071684
|
|
538
|
+
],
|
|
539
|
+
[
|
|
540
|
+
-.8294889695615747,
|
|
541
|
+
1.7626640603183463,
|
|
542
|
+
.023624685841943577
|
|
543
|
+
],
|
|
544
|
+
[
|
|
545
|
+
.03584583024378447,
|
|
546
|
+
-.07617238926804182,
|
|
547
|
+
.9568845240076872
|
|
548
|
+
]
|
|
549
|
+
];
|
|
550
|
+
/** Bradford chromatic adaptation between the D65 and D50 white points (Lab and LCH use D50). */
|
|
551
|
+
const D65_TO_D50 = [
|
|
552
|
+
[
|
|
553
|
+
1.0479297925449969,
|
|
554
|
+
.022946870601609652,
|
|
555
|
+
-.05019226628920524
|
|
556
|
+
],
|
|
557
|
+
[
|
|
558
|
+
.02962780877005599,
|
|
559
|
+
.9904344267538799,
|
|
560
|
+
-.017073799063418826
|
|
561
|
+
],
|
|
562
|
+
[
|
|
563
|
+
-.009243040646204504,
|
|
564
|
+
.015055191490298152,
|
|
565
|
+
.7518742814281371
|
|
566
|
+
]
|
|
567
|
+
];
|
|
568
|
+
const D50_TO_D65 = [
|
|
569
|
+
[
|
|
570
|
+
.955473421488075,
|
|
571
|
+
-.02309845494876471,
|
|
572
|
+
.06325924320057072
|
|
573
|
+
],
|
|
574
|
+
[
|
|
575
|
+
-.0283697093338637,
|
|
576
|
+
1.0099953980813041,
|
|
577
|
+
.021041441191917323
|
|
578
|
+
],
|
|
579
|
+
[
|
|
580
|
+
.012314014864481998,
|
|
581
|
+
-.020507649298898964,
|
|
582
|
+
1.330365926242124
|
|
583
|
+
]
|
|
584
|
+
];
|
|
585
|
+
/** Linear sRGB to OKLab's cone responses, and back. */
|
|
586
|
+
const LRGB_TO_LMS = [
|
|
587
|
+
[
|
|
588
|
+
.412221469470763,
|
|
589
|
+
.5363325372617348,
|
|
590
|
+
.0514459932675022
|
|
591
|
+
],
|
|
592
|
+
[
|
|
593
|
+
.2119034958178252,
|
|
594
|
+
.6806995506452344,
|
|
595
|
+
.1073969535369406
|
|
596
|
+
],
|
|
597
|
+
[
|
|
598
|
+
.0883024591900564,
|
|
599
|
+
.2817188391361215,
|
|
600
|
+
.6299787016738222
|
|
601
|
+
]
|
|
602
|
+
];
|
|
603
|
+
const LMS_TO_LRGB = [
|
|
604
|
+
[
|
|
605
|
+
4.076741636075957,
|
|
606
|
+
-3.3077115392580616,
|
|
607
|
+
.2309699031821044
|
|
608
|
+
],
|
|
609
|
+
[
|
|
610
|
+
-1.2684379732850317,
|
|
611
|
+
2.6097573492876887,
|
|
612
|
+
-.3413193760026573
|
|
613
|
+
],
|
|
614
|
+
[
|
|
615
|
+
-.0041960761386756,
|
|
616
|
+
-.7034186179359362,
|
|
617
|
+
1.7076146940746117
|
|
618
|
+
]
|
|
619
|
+
];
|
|
620
|
+
const LMS_TO_OKLAB = [
|
|
621
|
+
[
|
|
622
|
+
.210454268309314,
|
|
623
|
+
.7936177747023054,
|
|
624
|
+
-.0040720430116193
|
|
625
|
+
],
|
|
626
|
+
[
|
|
627
|
+
1.9779985324311684,
|
|
628
|
+
-2.42859224204858,
|
|
629
|
+
.450593709617411
|
|
630
|
+
],
|
|
631
|
+
[
|
|
632
|
+
.0259040424655478,
|
|
633
|
+
.7827717124575296,
|
|
634
|
+
-.8086757549230774
|
|
635
|
+
]
|
|
636
|
+
];
|
|
637
|
+
const OKLAB_TO_LMS = [
|
|
638
|
+
[
|
|
639
|
+
1,
|
|
640
|
+
.3963377773761749,
|
|
641
|
+
.2158037573099136
|
|
642
|
+
],
|
|
643
|
+
[
|
|
644
|
+
1,
|
|
645
|
+
-.1055613458156586,
|
|
646
|
+
-.0638541728258133
|
|
647
|
+
],
|
|
648
|
+
[
|
|
649
|
+
1,
|
|
650
|
+
-.0894841775298119,
|
|
651
|
+
-1.2914855480194092
|
|
652
|
+
]
|
|
653
|
+
];
|
|
654
|
+
const toXyz = (c) => mul(SRGB_TO_XYZ, linearRgb(c));
|
|
655
|
+
const fromXyz = (xyz, alpha) => fromLinearRgb(mul(XYZ_TO_SRGB, xyz), alpha);
|
|
656
|
+
/** Display P3 channels (gamma-encoded, 0 to 1 inside P3). */
|
|
657
|
+
const toP3 = (c) => mul(XYZ_TO_P3, toXyz(c)).map(fromLinear);
|
|
658
|
+
const fromP3 = (p3, alpha) => fromXyz(mul(P3_TO_XYZ, p3.map(toLinear)), alpha);
|
|
659
|
+
const fromXyzD50 = (xyz, alpha) => fromXyz(mul(D50_TO_D65, xyz), alpha);
|
|
660
|
+
/** OKLab: L in [0, 1], a and b around ±0.4. */
|
|
661
|
+
const toOklab = (c) => mul(LMS_TO_OKLAB, mul(LRGB_TO_LMS, linearRgb(c)).map(Math.cbrt));
|
|
662
|
+
const fromOklab = (lab, alpha) => fromLinearRgb(mul(LMS_TO_LRGB, mul(OKLAB_TO_LMS, lab).map((v) => v ** 3)), alpha);
|
|
663
|
+
const D50_WHITE = [
|
|
664
|
+
.3457 / .3585,
|
|
665
|
+
1,
|
|
666
|
+
.2958 / .3585
|
|
667
|
+
];
|
|
668
|
+
const KAPPA = 24389 / 27;
|
|
669
|
+
const EPSILON = 216 / 24389;
|
|
670
|
+
/** CIE Lab (D50): L in [0, 100], a and b around ±125. */
|
|
671
|
+
const toLab = (c) => {
|
|
672
|
+
const [x, y, z] = mul(D65_TO_D50, toXyz(c)).map((v, i) => v / D50_WHITE[i]);
|
|
673
|
+
const f = (v) => v > EPSILON ? Math.cbrt(v) : (KAPPA * v + 16) / 116;
|
|
674
|
+
const [fx, fy, fz] = [
|
|
675
|
+
f(x),
|
|
676
|
+
f(y),
|
|
677
|
+
f(z)
|
|
678
|
+
];
|
|
679
|
+
return [
|
|
680
|
+
116 * fy - 16,
|
|
681
|
+
500 * (fx - fy),
|
|
682
|
+
200 * (fy - fz)
|
|
683
|
+
];
|
|
684
|
+
};
|
|
685
|
+
const fromLab = ([l, a, b], alpha) => {
|
|
686
|
+
const fy = (l + 16) / 116;
|
|
687
|
+
const fx = a / 500 + fy;
|
|
688
|
+
const fz = fy - b / 200;
|
|
689
|
+
const xyz = [
|
|
690
|
+
fx ** 3 > EPSILON ? fx ** 3 : (116 * fx - 16) / KAPPA,
|
|
691
|
+
l > KAPPA * EPSILON ? fy ** 3 : l / KAPPA,
|
|
692
|
+
fz ** 3 > EPSILON ? fz ** 3 : (116 * fz - 16) / KAPPA
|
|
693
|
+
];
|
|
694
|
+
return fromXyzD50(xyz.map((v, i) => v * D50_WHITE[i]), alpha);
|
|
695
|
+
};
|
|
696
|
+
/** Lab-like to its polar form: lightness, chroma, and hue in degrees from 0 to 360. */
|
|
697
|
+
const toPolar = ([l, a, b]) => [
|
|
698
|
+
l,
|
|
699
|
+
Math.hypot(a, b),
|
|
700
|
+
(Math.atan2(b, a) * 180 / Math.PI + 360) % 360
|
|
701
|
+
];
|
|
702
|
+
const fromPolar = ([l, c, h]) => [
|
|
703
|
+
l,
|
|
704
|
+
c * Math.cos(h * Math.PI / 180),
|
|
705
|
+
c * Math.sin(h * Math.PI / 180)
|
|
706
|
+
];
|
|
707
|
+
/** Hue, saturation and lightness of a colour inside sRGB (hue 0 for greys), with s and l in [0, 1]. */
|
|
708
|
+
function toHsl(c) {
|
|
709
|
+
const max = Math.max(c.r, c.g, c.b);
|
|
710
|
+
const min = Math.min(c.r, c.g, c.b);
|
|
711
|
+
const l = (max + min) / 2;
|
|
712
|
+
const d = max - min;
|
|
713
|
+
if (d === 0) return [
|
|
714
|
+
0,
|
|
715
|
+
0,
|
|
716
|
+
l
|
|
717
|
+
];
|
|
718
|
+
const s = (max - l) / Math.min(l, 1 - l);
|
|
719
|
+
let h;
|
|
720
|
+
if (max === c.r) h = (c.g - c.b) / d + (c.g < c.b ? 6 : 0);
|
|
721
|
+
else if (max === c.g) h = (c.b - c.r) / d + 2;
|
|
722
|
+
else h = (c.r - c.g) / d + 4;
|
|
723
|
+
return [
|
|
724
|
+
h * 60,
|
|
725
|
+
s,
|
|
726
|
+
l
|
|
727
|
+
];
|
|
728
|
+
}
|
|
729
|
+
function fromHsl(h, s, l, alpha) {
|
|
730
|
+
const hue = (h % 360 + 360) % 360;
|
|
731
|
+
const f = (n) => {
|
|
732
|
+
const k = (n + hue / 30) % 12;
|
|
733
|
+
return l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k - 3, 9 - k, 1));
|
|
734
|
+
};
|
|
735
|
+
return color(f(0), f(8), f(4), alpha);
|
|
736
|
+
}
|
|
737
|
+
function fromHwb(h, w, b, alpha) {
|
|
738
|
+
if (w + b >= 1) {
|
|
739
|
+
const grey = w / (w + b);
|
|
740
|
+
return color(grey, grey, grey, alpha);
|
|
741
|
+
}
|
|
742
|
+
const pure = fromHsl(h, 1, .5, 1);
|
|
743
|
+
const scale = (v) => v * (1 - w - b) + w;
|
|
744
|
+
return color(scale(pure.r), scale(pure.g), scale(pure.b), alpha);
|
|
745
|
+
}
|
|
746
|
+
/** Hue, whiteness and blackness of an sRGB colour, with w and b in [0, 1]. */
|
|
747
|
+
function toHwb(c) {
|
|
748
|
+
const [h] = toHsl(c);
|
|
749
|
+
return [
|
|
750
|
+
h,
|
|
751
|
+
Math.min(c.r, c.g, c.b),
|
|
752
|
+
1 - Math.max(c.r, c.g, c.b)
|
|
753
|
+
];
|
|
754
|
+
}
|
|
755
|
+
/** Distance in OKLab: about 0.02 is the smallest difference people notice. */
|
|
756
|
+
const deltaEOK = (a, b) => {
|
|
757
|
+
const [l1, a1, b1] = toOklab(a);
|
|
758
|
+
const [l2, a2, b2] = toOklab(b);
|
|
759
|
+
return Math.hypot(l1 - l2, a1 - a2, b1 - b2);
|
|
760
|
+
};
|
|
761
|
+
const channels = (c, gamut) => gamut === "srgb" ? [
|
|
762
|
+
c.r,
|
|
763
|
+
c.g,
|
|
764
|
+
c.b
|
|
765
|
+
] : toP3(c);
|
|
766
|
+
const clip01 = (v) => Math.min(1, Math.max(0, v));
|
|
767
|
+
const clipTo = (c, gamut) => {
|
|
768
|
+
const [x, y, z] = channels(c, gamut).map(clip01);
|
|
769
|
+
return gamut === "srgb" ? color(x, y, z, c.alpha) : fromP3([
|
|
770
|
+
x,
|
|
771
|
+
y,
|
|
772
|
+
z
|
|
773
|
+
], c.alpha);
|
|
774
|
+
};
|
|
775
|
+
/** Whether a colour is inside a gamut, within rounding error. */
|
|
776
|
+
function inGamut(c, gamut = "srgb") {
|
|
777
|
+
return channels(c, gamut).every((v) => v >= -1e-6 && v <= 1 + 1e-6);
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* The colour inside `gamut` that looks closest: the CSS Color 4 gamut mapping
|
|
781
|
+
* algorithm, which keeps lightness and hue and reduces chroma in OKLCH until
|
|
782
|
+
* clipping is no longer visible (`"map"`), or plain clipping of each channel (`"clip"`).
|
|
783
|
+
*/
|
|
784
|
+
function toGamut(c, gamut = "srgb", method = "map") {
|
|
785
|
+
if (inGamut(c, gamut)) return clipTo(c, gamut);
|
|
786
|
+
if (method === "clip") return clipTo(c, gamut);
|
|
787
|
+
const [l, chroma, hue] = toPolar(toOklab(c));
|
|
788
|
+
if (l >= 1 - 1e-7) return clipTo(color(1, 1, 1, c.alpha), gamut);
|
|
789
|
+
if (l <= 1e-7) return clipTo(color(0, 0, 0, c.alpha), gamut);
|
|
790
|
+
const JND = .02;
|
|
791
|
+
let low = 0;
|
|
792
|
+
let high = chroma;
|
|
793
|
+
let lowInGamut = true;
|
|
794
|
+
let current = c;
|
|
795
|
+
let clipped = clipTo(current, gamut);
|
|
796
|
+
if (deltaEOK(clipped, current) < JND) return clipped;
|
|
797
|
+
while (high - low > 1e-4) {
|
|
798
|
+
const mid = (low + high) / 2;
|
|
799
|
+
current = fromOklab(fromPolar([
|
|
800
|
+
l,
|
|
801
|
+
mid,
|
|
802
|
+
hue
|
|
803
|
+
]), c.alpha);
|
|
804
|
+
if (lowInGamut && inGamut(current, gamut)) {
|
|
805
|
+
low = mid;
|
|
806
|
+
continue;
|
|
807
|
+
}
|
|
808
|
+
clipped = clipTo(current, gamut);
|
|
809
|
+
const e = deltaEOK(clipped, current);
|
|
810
|
+
if (e < JND) {
|
|
811
|
+
if (JND - e < 1e-4) return clipped;
|
|
812
|
+
lowInGamut = false;
|
|
813
|
+
low = mid;
|
|
814
|
+
} else high = mid;
|
|
815
|
+
}
|
|
816
|
+
return clipped;
|
|
817
|
+
}
|
|
818
|
+
//#endregion
|
|
819
|
+
//#region src/color/names.ts
|
|
820
|
+
/**
|
|
821
|
+
* The 148 named colours of CSS Color 4, as "name rrggbb" pairs. Parsed into a map
|
|
822
|
+
* the first time a name is looked up, so the table costs nothing until then.
|
|
823
|
+
*/
|
|
824
|
+
const NAMED = [
|
|
825
|
+
"aliceblue f0f8ff antiquewhite faebd7 aqua 00ffff aquamarine 7fffd4 azure f0ffff beige f5f5dc bisque ffe4c4",
|
|
826
|
+
"black 000000 blanchedalmond ffebcd blue 0000ff blueviolet 8a2be2 brown a52a2a burlywood deb887",
|
|
827
|
+
"cadetblue 5f9ea0 chartreuse 7fff00 chocolate d2691e coral ff7f50 cornflowerblue 6495ed cornsilk fff8dc",
|
|
828
|
+
"crimson dc143c cyan 00ffff darkblue 00008b darkcyan 008b8b darkgoldenrod b8860b darkgray a9a9a9",
|
|
829
|
+
"darkgreen 006400 darkgrey a9a9a9 darkkhaki bdb76b darkmagenta 8b008b darkolivegreen 556b2f darkorange ff8c00",
|
|
830
|
+
"darkorchid 9932cc darkred 8b0000 darksalmon e9967a darkseagreen 8fbc8f darkslateblue 483d8b",
|
|
831
|
+
"darkslategray 2f4f4f darkslategrey 2f4f4f darkturquoise 00ced1 darkviolet 9400d3 deeppink ff1493",
|
|
832
|
+
"deepskyblue 00bfff dimgray 696969 dimgrey 696969 dodgerblue 1e90ff firebrick b22222 floralwhite fffaf0",
|
|
833
|
+
"forestgreen 228b22 fuchsia ff00ff gainsboro dcdcdc ghostwhite f8f8ff gold ffd700 goldenrod daa520 gray 808080",
|
|
834
|
+
"green 008000 greenyellow adff2f grey 808080 honeydew f0fff0 hotpink ff69b4 indianred cd5c5c indigo 4b0082",
|
|
835
|
+
"ivory fffff0 khaki f0e68c lavender e6e6fa lavenderblush fff0f5 lawngreen 7cfc00 lemonchiffon fffacd",
|
|
836
|
+
"lightblue add8e6 lightcoral f08080 lightcyan e0ffff lightgoldenrodyellow fafad2 lightgray d3d3d3",
|
|
837
|
+
"lightgreen 90ee90 lightgrey d3d3d3 lightpink ffb6c1 lightsalmon ffa07a lightseagreen 20b2aa",
|
|
838
|
+
"lightskyblue 87cefa lightslategray 778899 lightslategrey 778899 lightsteelblue b0c4de lightyellow ffffe0",
|
|
839
|
+
"lime 00ff00 limegreen 32cd32 linen faf0e6 magenta ff00ff maroon 800000 mediumaquamarine 66cdaa",
|
|
840
|
+
"mediumblue 0000cd mediumorchid ba55d3 mediumpurple 9370db mediumseagreen 3cb371 mediumslateblue 7b68ee",
|
|
841
|
+
"mediumspringgreen 00fa9a mediumturquoise 48d1cc mediumvioletred c71585 midnightblue 191970 mintcream f5fffa",
|
|
842
|
+
"mistyrose ffe4e1 moccasin ffe4b5 navajowhite ffdead navy 000080 oldlace fdf5e6 olive 808000 olivedrab 6b8e23",
|
|
843
|
+
"orange ffa500 orangered ff4500 orchid da70d6 palegoldenrod eee8aa palegreen 98fb98 paleturquoise afeeee",
|
|
844
|
+
"palevioletred db7093 papayawhip ffefd5 peachpuff ffdab9 peru cd853f pink ffc0cb plum dda0dd powderblue b0e0e6",
|
|
845
|
+
"purple 800080 rebeccapurple 663399 red ff0000 rosybrown bc8f8f royalblue 4169e1 saddlebrown 8b4513",
|
|
846
|
+
"salmon fa8072 sandybrown f4a460 seagreen 2e8b57 seashell fff5ee sienna a0522d silver c0c0c0 skyblue 87ceeb",
|
|
847
|
+
"slateblue 6a5acd slategray 708090 slategrey 708090 snow fffafa springgreen 00ff7f steelblue 4682b4 tan d2b48c",
|
|
848
|
+
"teal 008080 thistle d8bfd8 tomato ff6347 turquoise 40e0d0 violet ee82ee wheat f5deb3 white ffffff",
|
|
849
|
+
"whitesmoke f5f5f5 yellow ffff00 yellowgreen 9acd32"
|
|
850
|
+
].join(" ");
|
|
851
|
+
let table;
|
|
852
|
+
/** The colour for a CSS colour name (lowercase), as 0xrrggbb, or `undefined`. */
|
|
853
|
+
function namedColor(name) {
|
|
854
|
+
if (table === void 0) {
|
|
855
|
+
table = /* @__PURE__ */ new Map();
|
|
856
|
+
const parts = NAMED.split(" ");
|
|
857
|
+
for (let i = 0; i < parts.length; i += 2) table.set(parts[i], parseInt(parts[i + 1], 16));
|
|
858
|
+
}
|
|
859
|
+
return table.get(name);
|
|
860
|
+
}
|
|
861
|
+
//#endregion
|
|
862
|
+
//#region src/color/parse.ts
|
|
863
|
+
/** Longer input is not a colour: parsing stays cheap whatever is pasted. */
|
|
864
|
+
const MAX_LENGTH = 256;
|
|
865
|
+
const NUMBER = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/;
|
|
866
|
+
const HEX = /^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/;
|
|
867
|
+
const FUNCTION = /^([a-z][a-z\d-]*)\(([^()]*)\)$/;
|
|
868
|
+
const ANGLE_UNITS = {
|
|
869
|
+
deg: 1,
|
|
870
|
+
grad: .9,
|
|
871
|
+
rad: 180 / Math.PI,
|
|
872
|
+
turn: 360
|
|
873
|
+
};
|
|
874
|
+
/** One component: a number, a percentage, an angle (in degrees) or `none`. */
|
|
875
|
+
function token(text) {
|
|
876
|
+
if (text === "none") return {
|
|
877
|
+
kind: "none",
|
|
878
|
+
value: 0
|
|
879
|
+
};
|
|
880
|
+
if (text.endsWith("%")) {
|
|
881
|
+
const body = text.slice(0, -1);
|
|
882
|
+
return NUMBER.test(body) ? {
|
|
883
|
+
kind: "percent",
|
|
884
|
+
value: Number(body)
|
|
885
|
+
} : null;
|
|
886
|
+
}
|
|
887
|
+
const unit = /[a-z]+$/.exec(text)?.[0];
|
|
888
|
+
if (unit !== void 0) {
|
|
889
|
+
const factor = ANGLE_UNITS[unit];
|
|
890
|
+
const body = text.slice(0, -unit.length);
|
|
891
|
+
return factor === void 0 || !NUMBER.test(body) ? null : {
|
|
892
|
+
kind: "angle",
|
|
893
|
+
value: Number(body) * factor
|
|
894
|
+
};
|
|
895
|
+
}
|
|
896
|
+
return NUMBER.test(text) ? {
|
|
897
|
+
kind: "number",
|
|
898
|
+
value: Number(text)
|
|
899
|
+
} : null;
|
|
900
|
+
}
|
|
901
|
+
const clamp = (v, min, max) => Math.min(max, Math.max(min, v));
|
|
902
|
+
/** A component's value: numbers as they are, percentages scaled so 100% is `full`. */
|
|
903
|
+
function amount(t, full, allowed) {
|
|
904
|
+
if (t.kind === "none") return 0;
|
|
905
|
+
if (!allowed.includes(t.kind)) return null;
|
|
906
|
+
return t.kind === "percent" ? t.value / 100 * full : t.value;
|
|
907
|
+
}
|
|
908
|
+
const hueOf = (t) => amount(t, 0, ["number", "angle"]);
|
|
909
|
+
const alphaOf = (t) => {
|
|
910
|
+
if (t === void 0) return 1;
|
|
911
|
+
const value = amount(t, 1, ["number", "percent"]);
|
|
912
|
+
return value === null ? null : clamp(value, 0, 1);
|
|
913
|
+
};
|
|
914
|
+
/** Splits arguments into three components and an optional alpha; `legacy` for the comma syntax. */
|
|
915
|
+
function split(args) {
|
|
916
|
+
const legacy = args.includes(",");
|
|
917
|
+
let main;
|
|
918
|
+
let alphaText;
|
|
919
|
+
if (legacy) {
|
|
920
|
+
const list = args.split(",").map((part) => part.trim());
|
|
921
|
+
if (list.length < 3 || list.length > 4) return null;
|
|
922
|
+
main = list.slice(0, 3);
|
|
923
|
+
alphaText = list[3];
|
|
924
|
+
} else {
|
|
925
|
+
const [body, rest, extra] = args.split("/");
|
|
926
|
+
if (extra !== void 0) return null;
|
|
927
|
+
main = body.trim().split(/\s+/);
|
|
928
|
+
alphaText = rest?.trim();
|
|
929
|
+
if (main.length !== 3 || alphaText === "") return null;
|
|
930
|
+
}
|
|
931
|
+
const parts = main.map(token);
|
|
932
|
+
if (parts.some((part) => part === null)) return null;
|
|
933
|
+
const alpha = alphaText === void 0 ? void 0 : token(alphaText);
|
|
934
|
+
if (alpha === null) return null;
|
|
935
|
+
if (legacy && [...parts, alpha].some((part) => part?.kind === "none")) return null;
|
|
936
|
+
return {
|
|
937
|
+
parts,
|
|
938
|
+
alpha,
|
|
939
|
+
legacy
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
function rgb(parts, legacy) {
|
|
943
|
+
if (legacy && new Set(parts.map((part) => part.kind)).size !== 1) return null;
|
|
944
|
+
const values = parts.map((part) => amount(part, 255, ["number", "percent"]));
|
|
945
|
+
return values.some((v) => v === null) ? null : values.map((v) => clamp(v, 0, 255) / 255);
|
|
946
|
+
}
|
|
947
|
+
const PREDEFINED = {
|
|
948
|
+
srgb: ([r, g, b], alpha) => color(r, g, b, alpha),
|
|
949
|
+
"srgb-linear": fromLinearRgb,
|
|
950
|
+
"display-p3": fromP3,
|
|
951
|
+
xyz: fromXyz,
|
|
952
|
+
"xyz-d65": fromXyz,
|
|
953
|
+
"xyz-d50": fromXyzD50
|
|
954
|
+
};
|
|
955
|
+
/** `color(space c1 c2 c3 / alpha)`. */
|
|
956
|
+
function predefined(args) {
|
|
957
|
+
const match = /^([a-z\d-]+)\s+(.*)$/.exec(args.trim());
|
|
958
|
+
if (match === null) return null;
|
|
959
|
+
const convert = PREDEFINED[match[1]];
|
|
960
|
+
const parsed = split(match[2]);
|
|
961
|
+
if (convert === void 0 || parsed === null || parsed.legacy) return null;
|
|
962
|
+
const values = parsed.parts.map((part) => amount(part, 1, ["number", "percent"]));
|
|
963
|
+
const alpha = alphaOf(parsed.alpha);
|
|
964
|
+
return values.some((v) => v === null) || alpha === null ? null : convert(values, alpha);
|
|
965
|
+
}
|
|
966
|
+
function functional(name, args) {
|
|
967
|
+
if (name === "color") return predefined(args);
|
|
968
|
+
const parsed = split(args);
|
|
969
|
+
if (parsed === null) return null;
|
|
970
|
+
const { parts, legacy } = parsed;
|
|
971
|
+
const [a, b, c] = parts;
|
|
972
|
+
const alpha = alphaOf(parsed.alpha);
|
|
973
|
+
if (alpha === null) return null;
|
|
974
|
+
switch (name) {
|
|
975
|
+
case "rgb":
|
|
976
|
+
case "rgba": {
|
|
977
|
+
const values = rgb(parts, legacy);
|
|
978
|
+
return values === null ? null : color(values[0], values[1], values[2], alpha);
|
|
979
|
+
}
|
|
980
|
+
case "hsl":
|
|
981
|
+
case "hsla": {
|
|
982
|
+
const hue = hueOf(a);
|
|
983
|
+
const kinds = legacy ? ["percent"] : ["number", "percent"];
|
|
984
|
+
const s = amount(b, 100, kinds);
|
|
985
|
+
const l = amount(c, 100, kinds);
|
|
986
|
+
if (hue === null || s === null || l === null) return null;
|
|
987
|
+
return fromHsl(hue, clamp(s, 0, 100) / 100, clamp(l, 0, 100) / 100, alpha);
|
|
988
|
+
}
|
|
989
|
+
case "hwb": {
|
|
990
|
+
const hue = hueOf(a);
|
|
991
|
+
const w = amount(b, 100, ["number", "percent"]);
|
|
992
|
+
const k = amount(c, 100, ["number", "percent"]);
|
|
993
|
+
if (legacy || hue === null || w === null || k === null) return null;
|
|
994
|
+
return fromHwb(hue, clamp(w, 0, 100) / 100, clamp(k, 0, 100) / 100, alpha);
|
|
995
|
+
}
|
|
996
|
+
default: return legacy ? null : lab(name, a, b, c, alpha);
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
/** lab(), lch(), oklab() and oklch(). */
|
|
1000
|
+
function lab(name, a, b, c, alpha) {
|
|
1001
|
+
const ok = name.startsWith("ok");
|
|
1002
|
+
const polar = name.endsWith("ch");
|
|
1003
|
+
if (![
|
|
1004
|
+
"lab",
|
|
1005
|
+
"lch",
|
|
1006
|
+
"oklab",
|
|
1007
|
+
"oklch"
|
|
1008
|
+
].includes(name)) return null;
|
|
1009
|
+
const lightMax = ok ? 1 : 100;
|
|
1010
|
+
const l = amount(a, lightMax, ["number", "percent"]);
|
|
1011
|
+
const second = amount(b, ok ? .4 : polar ? 150 : 125, ["number", "percent"]);
|
|
1012
|
+
const third = polar ? hueOf(c) : amount(c, ok ? .4 : 125, ["number", "percent"]);
|
|
1013
|
+
if (l === null || second === null || third === null) return null;
|
|
1014
|
+
const lightness = clamp(l, 0, lightMax);
|
|
1015
|
+
const values = polar ? fromPolar([
|
|
1016
|
+
lightness,
|
|
1017
|
+
Math.max(0, second),
|
|
1018
|
+
third
|
|
1019
|
+
]) : [
|
|
1020
|
+
lightness,
|
|
1021
|
+
second,
|
|
1022
|
+
third
|
|
1023
|
+
];
|
|
1024
|
+
return ok ? fromOklab(values, alpha) : fromLab(values, alpha);
|
|
1025
|
+
}
|
|
1026
|
+
/**
|
|
1027
|
+
* Parses a CSS colour, or returns `null`: hex (`#rgb`, `#rgba`, `#rrggbb`,
|
|
1028
|
+
* `#rrggbbaa`), the 148 named colours and `transparent`, `rgb()` and `hsl()` in
|
|
1029
|
+
* both syntaxes, `hwb()`, `lab()`, `lch()`, `oklab()`, `oklch()`, and `color()`
|
|
1030
|
+
* in `srgb`, `srgb-linear`, `display-p3`, `xyz`, `xyz-d65` and `xyz-d50`.
|
|
1031
|
+
* Never throws. Colours outside sRGB keep their exact value.
|
|
1032
|
+
*
|
|
1033
|
+
* Not colours on their own: `currentcolor`, system colours, `var()`, `calc()`,
|
|
1034
|
+
* `color-mix()` and relative colours.
|
|
1035
|
+
*
|
|
1036
|
+
* @example
|
|
1037
|
+
* parseColor('oklch(62.8% 0.258 29.23)'); // { r: 1, g: 0, b: 0, alpha: 1 } (rounded)
|
|
1038
|
+
*/
|
|
1039
|
+
function parseColor(input) {
|
|
1040
|
+
if (typeof input !== "string" || input.length > MAX_LENGTH) return null;
|
|
1041
|
+
const text = input.trim().toLowerCase();
|
|
1042
|
+
const hex = HEX.exec(text)?.[1];
|
|
1043
|
+
if (hex !== void 0) {
|
|
1044
|
+
const full = hex.length <= 4 ? hex.replace(/./g, (digit) => digit + digit) : hex;
|
|
1045
|
+
const byte = (i) => parseInt(full.slice(i, i + 2), 16) / 255;
|
|
1046
|
+
return color(byte(0), byte(2), byte(4), full.length === 8 ? byte(6) : 1);
|
|
1047
|
+
}
|
|
1048
|
+
if (text === "transparent") return color(0, 0, 0, 0);
|
|
1049
|
+
const named = namedColor(text);
|
|
1050
|
+
if (named !== void 0) return color((named >> 16 & 255) / 255, (named >> 8 & 255) / 255, (named & 255) / 255);
|
|
1051
|
+
const match = FUNCTION.exec(text);
|
|
1052
|
+
return match === null ? null : functional(match[1], match[2].trim());
|
|
1053
|
+
}
|
|
1054
|
+
//#endregion
|
|
1055
|
+
//#region src/color/format.ts
|
|
1056
|
+
const COLOR_FORMATS = /* @__PURE__ */ Object.freeze([
|
|
1057
|
+
"hex",
|
|
1058
|
+
"rgb",
|
|
1059
|
+
"hsl",
|
|
1060
|
+
"hwb",
|
|
1061
|
+
"oklch",
|
|
1062
|
+
"oklab",
|
|
1063
|
+
"lab",
|
|
1064
|
+
"lch",
|
|
1065
|
+
"p3"
|
|
1066
|
+
]);
|
|
1067
|
+
const isColor = (value) => typeof value === "object" && value !== null && [
|
|
1068
|
+
"r",
|
|
1069
|
+
"g",
|
|
1070
|
+
"b",
|
|
1071
|
+
"alpha"
|
|
1072
|
+
].every((key) => Number.isFinite(value[key]));
|
|
1073
|
+
/** Resolves a colour input, throwing a typed error for anything that is not one. */
|
|
1074
|
+
function toColor(input) {
|
|
1075
|
+
if (typeof input === "string") {
|
|
1076
|
+
const parsed = parseColor(input);
|
|
1077
|
+
if (parsed === null) throw copyFailure("invalid-payload", `Not a colour: ${JSON.stringify(input.slice(0, 100))}.`);
|
|
1078
|
+
return parsed;
|
|
1079
|
+
}
|
|
1080
|
+
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.");
|
|
1081
|
+
return input;
|
|
1082
|
+
}
|
|
1083
|
+
/** Rounds to `places` decimals, without trailing zeros or `-0`. */
|
|
1084
|
+
function num(value, places) {
|
|
1085
|
+
const factor = 10 ** places;
|
|
1086
|
+
const rounded = Math.round(value * factor) / factor;
|
|
1087
|
+
return String(Object.is(rounded, -0) ? 0 : rounded);
|
|
1088
|
+
}
|
|
1089
|
+
/** A hue in degrees, with 360 written as 0. */
|
|
1090
|
+
const hue = (value, places) => {
|
|
1091
|
+
const text = num(value, places);
|
|
1092
|
+
return text === "360" ? "0" : text;
|
|
1093
|
+
};
|
|
1094
|
+
const byte = (v) => Math.round(Math.min(1, Math.max(0, v)) * 255);
|
|
1095
|
+
/** The alpha suffix of a functional notation: nothing when opaque. */
|
|
1096
|
+
const alphaPart = (alpha, legacy, places) => alpha >= 1 ? "" : legacy ? `, ${num(alpha, places)}` : ` / ${num(alpha, places)}`;
|
|
1097
|
+
/**
|
|
1098
|
+
* Writes a colour in a CSS format. Text is parsed first, so this also converts
|
|
1099
|
+
* between formats.
|
|
1100
|
+
*
|
|
1101
|
+
* @example
|
|
1102
|
+
* formatColor('rgb(255 0 0)', 'oklch'); // 'oklch(62.8% 0.2577 29.23)'
|
|
1103
|
+
* formatColor('color(display-p3 1 0 0)', 'hex'); // '#ff0000' after gamut mapping, never a wrong hue
|
|
1104
|
+
*/
|
|
1105
|
+
function formatColor(input, format = "hex", options = {}) {
|
|
1106
|
+
const c = toColor(input);
|
|
1107
|
+
const { gamut = "map", legacy = false, uppercase = false, precision } = options;
|
|
1108
|
+
const method = gamut;
|
|
1109
|
+
if (method !== "map" && method !== "clip") throw copyFailure("invalid-payload", "`gamut` must be \"map\" or \"clip\".");
|
|
1110
|
+
if (precision !== void 0 && !(Number.isInteger(precision) && precision >= 0 && precision <= 10)) throw copyFailure("invalid-payload", "`precision` must be an integer from 0 to 10.");
|
|
1111
|
+
const dp = (fallback) => precision ?? fallback;
|
|
1112
|
+
const a = c.alpha;
|
|
1113
|
+
switch (format) {
|
|
1114
|
+
case "hex": {
|
|
1115
|
+
const s = toGamut(c, "srgb", gamut);
|
|
1116
|
+
const digits = [
|
|
1117
|
+
s.r,
|
|
1118
|
+
s.g,
|
|
1119
|
+
s.b,
|
|
1120
|
+
...a < 1 ? [a] : []
|
|
1121
|
+
].map((v) => byte(v).toString(16).padStart(2, "0")).join("");
|
|
1122
|
+
return `#${uppercase ? digits.toUpperCase() : digits}`;
|
|
1123
|
+
}
|
|
1124
|
+
case "rgb": {
|
|
1125
|
+
const s = toGamut(c, "srgb", gamut);
|
|
1126
|
+
const [r, g, b] = [
|
|
1127
|
+
s.r,
|
|
1128
|
+
s.g,
|
|
1129
|
+
s.b
|
|
1130
|
+
].map(byte);
|
|
1131
|
+
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))})`;
|
|
1132
|
+
}
|
|
1133
|
+
case "hsl": {
|
|
1134
|
+
const [h, s, l] = toHsl(toGamut(c, "srgb", gamut));
|
|
1135
|
+
const [hh, ss, ll] = [
|
|
1136
|
+
hue(h, dp(2)),
|
|
1137
|
+
`${num(s * 100, dp(2))}%`,
|
|
1138
|
+
`${num(l * 100, dp(2))}%`
|
|
1139
|
+
];
|
|
1140
|
+
return legacy ? `${a < 1 ? "hsla" : "hsl"}(${hh}, ${ss}, ${ll}${alphaPart(a, true, dp(3))})` : `hsl(${hh} ${ss} ${ll}${alphaPart(a, false, dp(3))})`;
|
|
1141
|
+
}
|
|
1142
|
+
case "hwb": {
|
|
1143
|
+
const [h, w, b] = toHwb(toGamut(c, "srgb", gamut));
|
|
1144
|
+
return `hwb(${hue(h, dp(2))} ${num(w * 100, dp(2))}% ${num(b * 100, dp(2))}%${alphaPart(a, false, dp(3))})`;
|
|
1145
|
+
}
|
|
1146
|
+
case "oklab": {
|
|
1147
|
+
const [l, x, y] = toOklab(c);
|
|
1148
|
+
return `oklab(${num(l * 100, dp(2))}% ${num(x, dp(5))} ${num(y, dp(5))}${alphaPart(a, false, dp(3))})`;
|
|
1149
|
+
}
|
|
1150
|
+
case "oklch": {
|
|
1151
|
+
const [l, ch, h] = toPolar(toOklab(c));
|
|
1152
|
+
const chroma = num(ch, dp(5));
|
|
1153
|
+
return `oklch(${num(l * 100, dp(2))}% ${chroma} ${chroma === "0" ? "0" : hue(h, dp(2))}${alphaPart(a, false, dp(3))})`;
|
|
1154
|
+
}
|
|
1155
|
+
case "lab": {
|
|
1156
|
+
const [l, x, y] = toLab(c);
|
|
1157
|
+
return `lab(${num(l, dp(2))} ${num(x, dp(2))} ${num(y, dp(2))}${alphaPart(a, false, dp(3))})`;
|
|
1158
|
+
}
|
|
1159
|
+
case "lch": {
|
|
1160
|
+
const [l, ch, h] = toPolar(toLab(c));
|
|
1161
|
+
const chroma = num(ch, dp(2));
|
|
1162
|
+
return `lch(${num(l, dp(2))} ${chroma} ${chroma === "0" ? "0" : hue(h, dp(2))}${alphaPart(a, false, dp(3))})`;
|
|
1163
|
+
}
|
|
1164
|
+
case "p3": {
|
|
1165
|
+
const [r, g, b] = toP3(toGamut(c, "p3", gamut));
|
|
1166
|
+
return `color(display-p3 ${num(r, dp(4))} ${num(g, dp(4))} ${num(b, dp(4))}${alphaPart(a, false, dp(3))})`;
|
|
1167
|
+
}
|
|
1168
|
+
default: throw copyFailure("invalid-payload", `Unknown colour format ${JSON.stringify(String(format))}: use one of ${COLOR_FORMATS.join(", ")}.`);
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
//#endregion
|
|
1172
|
+
//#region src/color/contrast.ts
|
|
1173
|
+
const WHITE$1 = /* @__PURE__ */ color(1, 1, 1);
|
|
1174
|
+
/** `top` drawn over `bottom`, both made opaque first. */
|
|
1175
|
+
function over(top, bottom) {
|
|
1176
|
+
const mix = (a, b) => a * top.alpha + b * (1 - top.alpha);
|
|
1177
|
+
return color(mix(top.r, bottom.r), mix(top.g, bottom.g), mix(top.b, bottom.b));
|
|
1178
|
+
}
|
|
1179
|
+
/** WCAG 2 relative luminance of an opaque sRGB colour. */
|
|
1180
|
+
function luminance(c) {
|
|
1181
|
+
const lin = (v) => v <= .04045 ? v / 12.92 : ((v + .055) / 1.055) ** 2.4;
|
|
1182
|
+
return .2126 * lin(c.r) + .7152 * lin(c.g) + .0722 * lin(c.b);
|
|
1183
|
+
}
|
|
1184
|
+
/**
|
|
1185
|
+
* The WCAG 2 contrast ratio of text over a background, from 1 to 21. Colours are
|
|
1186
|
+
* mapped into sRGB, a translucent background is drawn over white, and translucent
|
|
1187
|
+
* text over the background, as a browser would show them. Never rounded: 4.499 is
|
|
1188
|
+
* not 4.5.
|
|
1189
|
+
*
|
|
1190
|
+
* @example
|
|
1191
|
+
* contrastRatio('#767676', '#fff'); // 4.54
|
|
1192
|
+
*/
|
|
1193
|
+
function contrastRatio(text, background) {
|
|
1194
|
+
const bg = over(toGamut(toColor(background)), WHITE$1);
|
|
1195
|
+
const [light, dark] = [luminance(over(toGamut(toColor(text)), bg)), luminance(bg)].sort((a, b) => b - a);
|
|
1196
|
+
return (light + .05) / (dark + .05);
|
|
1197
|
+
}
|
|
1198
|
+
//#endregion
|
|
1199
|
+
//#region src/rich/style.ts
|
|
1200
|
+
const INHERITED = [
|
|
1201
|
+
"color",
|
|
1202
|
+
"font-family",
|
|
1203
|
+
"font-size",
|
|
1204
|
+
"font-style",
|
|
1205
|
+
"font-weight",
|
|
1206
|
+
"text-align",
|
|
1207
|
+
"white-space",
|
|
1208
|
+
"text-transform",
|
|
1209
|
+
"list-style-type",
|
|
1210
|
+
"border-collapse"
|
|
1211
|
+
];
|
|
1212
|
+
const SIDES = [
|
|
1213
|
+
"top",
|
|
1214
|
+
"right",
|
|
1215
|
+
"bottom",
|
|
1216
|
+
"left"
|
|
1217
|
+
];
|
|
1218
|
+
const OWN = [
|
|
1219
|
+
"background-color",
|
|
1220
|
+
"text-decoration-line",
|
|
1221
|
+
"vertical-align",
|
|
1222
|
+
"border-top-width",
|
|
1223
|
+
"border-top-style",
|
|
1224
|
+
"border-top-color",
|
|
1225
|
+
"padding-top",
|
|
1226
|
+
"border-right-width",
|
|
1227
|
+
"border-right-style",
|
|
1228
|
+
"border-right-color",
|
|
1229
|
+
"padding-right",
|
|
1230
|
+
"border-bottom-width",
|
|
1231
|
+
"border-bottom-style",
|
|
1232
|
+
"border-bottom-color",
|
|
1233
|
+
"padding-bottom",
|
|
1234
|
+
"border-left-width",
|
|
1235
|
+
"border-left-style",
|
|
1236
|
+
"border-left-color",
|
|
1237
|
+
"padding-left"
|
|
1238
|
+
];
|
|
1239
|
+
const PROPERTIES = [...INHERITED, ...OWN];
|
|
1240
|
+
const INHERITED_SET = /* @__PURE__ */ new Set(INHERITED);
|
|
1241
|
+
/**
|
|
1242
|
+
* What an element gets from its parent: the inherited values, with its own declared
|
|
1243
|
+
* ones on top. Lists set their own marker, as browsers' default styles do, so a list
|
|
1244
|
+
* doesn't inherit its parent list's marker.
|
|
1245
|
+
*/
|
|
1246
|
+
function inherit(parent, own, tag = "") {
|
|
1247
|
+
const merged = {};
|
|
1248
|
+
for (const name of PROPERTIES) {
|
|
1249
|
+
const value = own === void 0 ? "" : own[name];
|
|
1250
|
+
const inherits = INHERITED_SET.has(name) && !(name === "list-style-type" && (tag === "ul" || tag === "ol"));
|
|
1251
|
+
merged[name] = value !== "" ? value : inherits ? parent[name] : "";
|
|
1252
|
+
}
|
|
1253
|
+
return merged;
|
|
1254
|
+
}
|
|
1255
|
+
function readValues(source) {
|
|
1256
|
+
const values = {};
|
|
1257
|
+
for (const name of PROPERTIES) values[name] = source.getPropertyValue(name).trim().toLowerCase();
|
|
1258
|
+
return values;
|
|
1259
|
+
}
|
|
1260
|
+
/** Inherited values every rendering starts from: an empty parent for the root. */
|
|
1261
|
+
const ROOT_PARENT = /* @__PURE__ */ Object.freeze({
|
|
1262
|
+
...Object.fromEntries(PROPERTIES.map((name) => [name, ""])),
|
|
1263
|
+
"font-style": "normal",
|
|
1264
|
+
"font-weight": "400",
|
|
1265
|
+
"text-align": "start",
|
|
1266
|
+
"white-space": "normal",
|
|
1267
|
+
"text-transform": "none",
|
|
1268
|
+
"border-collapse": "separate"
|
|
1269
|
+
});
|
|
1270
|
+
const KEYWORDS = {
|
|
1271
|
+
"font-style": /^(?:normal|italic|oblique)$/,
|
|
1272
|
+
"text-align": /^(?:left|right|center|justify)$/,
|
|
1273
|
+
"white-space": /^(?:normal|pre|pre-wrap|pre-line|nowrap|break-spaces)$/,
|
|
1274
|
+
"text-transform": /^(?:none|uppercase|lowercase|capitalize)$/,
|
|
1275
|
+
"list-style-type": /^(?:none|disc|circle|square|decimal|decimal-leading-zero|lower-alpha|upper-alpha|lower-latin|upper-latin|lower-roman|upper-roman|lower-greek)$/,
|
|
1276
|
+
"border-collapse": /^(?:collapse|separate)$/,
|
|
1277
|
+
"vertical-align": /^(?:top|bottom)$/
|
|
1278
|
+
};
|
|
1279
|
+
const LENGTH = /^(?:0|\d{1,4}(?:\.\d+)?(?:px|pt|em|%))$/;
|
|
1280
|
+
const FONT_FAMILY = /^[\w\s,'"-]{1,200}$/;
|
|
1281
|
+
/** Elements whose default style already shows a value: writing it again adds nothing. */
|
|
1282
|
+
const TAG_DEFAULTS = {
|
|
1283
|
+
b: { "font-weight": "700" },
|
|
1284
|
+
strong: { "font-weight": "700" },
|
|
1285
|
+
th: {
|
|
1286
|
+
"font-weight": "700",
|
|
1287
|
+
"text-align": "center"
|
|
1288
|
+
},
|
|
1289
|
+
h1: { "font-weight": "700" },
|
|
1290
|
+
h2: { "font-weight": "700" },
|
|
1291
|
+
h3: { "font-weight": "700" },
|
|
1292
|
+
h4: { "font-weight": "700" },
|
|
1293
|
+
h5: { "font-weight": "700" },
|
|
1294
|
+
h6: { "font-weight": "700" },
|
|
1295
|
+
em: { "font-style": "italic" },
|
|
1296
|
+
i: { "font-style": "italic" },
|
|
1297
|
+
cite: { "font-style": "italic" },
|
|
1298
|
+
dfn: { "font-style": "italic" },
|
|
1299
|
+
var: { "font-style": "italic" },
|
|
1300
|
+
pre: { "white-space": "pre" },
|
|
1301
|
+
ol: { "list-style-type": "decimal" },
|
|
1302
|
+
ul: { "list-style-type": "disc" },
|
|
1303
|
+
li: { "list-style-type": "" },
|
|
1304
|
+
a: { "text-decoration-line": "underline" },
|
|
1305
|
+
u: { "text-decoration-line": "underline" },
|
|
1306
|
+
ins: { "text-decoration-line": "underline" },
|
|
1307
|
+
s: { "text-decoration-line": "line-through" },
|
|
1308
|
+
del: { "text-decoration-line": "line-through" }
|
|
1309
|
+
};
|
|
1310
|
+
const weight = (value) => value === "bold" ? "700" : value === "normal" ? "400" : /^[1-9]00$/.test(value) ? value : "";
|
|
1311
|
+
/** `start` and `end` as the left and right they mean in left-to-right text. */
|
|
1312
|
+
const align = (value) => {
|
|
1313
|
+
if (value === "start") return "left";
|
|
1314
|
+
if (value === "end") return "right";
|
|
1315
|
+
return value === "-webkit-center" || value === "-internal-center" || value === "-moz-center" ? "center" : value;
|
|
1316
|
+
};
|
|
1317
|
+
/** A colour as an opaque hex value, drawn over `under`; `null` for none or invisible. */
|
|
1318
|
+
function opaque(value, under) {
|
|
1319
|
+
const c = parseColor(value);
|
|
1320
|
+
if (c === null || c.alpha === 0) return null;
|
|
1321
|
+
const mapped = toGamut(c);
|
|
1322
|
+
const mix = (top, bottom) => top * c.alpha + bottom * (1 - c.alpha);
|
|
1323
|
+
return color(mix(mapped.r, under.r), mix(mapped.g, under.g), mix(mapped.b, under.b));
|
|
1324
|
+
}
|
|
1325
|
+
const WHITE = /* @__PURE__ */ color(1, 1, 1);
|
|
1326
|
+
/** Pixel lengths rounded to 2 decimals; other units kept as written. */
|
|
1327
|
+
function length(value) {
|
|
1328
|
+
if (!LENGTH.test(value)) return null;
|
|
1329
|
+
return value.endsWith("px") ? `${String(Math.round(parseFloat(value) * 100) / 100)}px` : value;
|
|
1330
|
+
}
|
|
1331
|
+
/**
|
|
1332
|
+
* The declarations to write for an element: inherited properties where they differ
|
|
1333
|
+
* from the parent (all of them at the root), and the element's own box and decoration.
|
|
1334
|
+
*/
|
|
1335
|
+
function declarations(tag, values, parent, background, colors) {
|
|
1336
|
+
const out = [];
|
|
1337
|
+
const defaults = TAG_DEFAULTS[tag] ?? {};
|
|
1338
|
+
const changed = (name, value) => value !== "" && value !== parent[name] && value !== defaults[name];
|
|
1339
|
+
let droppedColor = false;
|
|
1340
|
+
let own = background;
|
|
1341
|
+
if (colors !== "none") {
|
|
1342
|
+
const bg = opaque(values["background-color"], background);
|
|
1343
|
+
if (bg !== null) {
|
|
1344
|
+
own = bg;
|
|
1345
|
+
out.push(`background-color:${formatColor(bg)}`);
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
const family = values["font-family"];
|
|
1349
|
+
if (changed("font-family", family) && FONT_FAMILY.test(family)) out.push(`font-family:${family}`);
|
|
1350
|
+
const size = length(values["font-size"]);
|
|
1351
|
+
if (size !== null && changed("font-size", values["font-size"])) out.push(`font-size:${size}`);
|
|
1352
|
+
const fontWeight = weight(values["font-weight"]);
|
|
1353
|
+
if (fontWeight !== weight(parent["font-weight"]) && changed("font-weight", fontWeight)) out.push(`font-weight:${fontWeight}`);
|
|
1354
|
+
for (const name of [
|
|
1355
|
+
"font-style",
|
|
1356
|
+
"white-space",
|
|
1357
|
+
"text-transform",
|
|
1358
|
+
"border-collapse"
|
|
1359
|
+
]) {
|
|
1360
|
+
const value = values[name];
|
|
1361
|
+
if (changed(name, value) && KEYWORDS[name].test(value)) out.push(`${name}:${value}`);
|
|
1362
|
+
}
|
|
1363
|
+
const textAlign = align(values["text-align"]);
|
|
1364
|
+
if (textAlign !== align(parent["text-align"]) && textAlign !== defaults["text-align"] && KEYWORDS["text-align"].test(textAlign)) out.push(`text-align:${textAlign}`);
|
|
1365
|
+
if (tag === "ul" || tag === "ol") {
|
|
1366
|
+
const list = values["list-style-type"];
|
|
1367
|
+
if (list !== defaults["list-style-type"] && list !== "circle" && list !== "square" && KEYWORDS["list-style-type"].test(list)) out.push(`list-style-type:${list}`);
|
|
1368
|
+
}
|
|
1369
|
+
if (colors !== "none" && changed("color", values["color"])) {
|
|
1370
|
+
const text = opaque(values["color"], own);
|
|
1371
|
+
if (text !== null) {
|
|
1372
|
+
if (colors === "readable" && contrastRatio(text, own) < 3) droppedColor = true;
|
|
1373
|
+
else out.push(`color:${formatColor(text)}`);
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
const decoration = values["text-decoration-line"];
|
|
1377
|
+
if (decoration !== "" && decoration !== defaults["text-decoration-line"] && /^(?:none|(?:underline|overline|line-through)(?: (?:underline|overline|line-through))*)$/.test(decoration)) {
|
|
1378
|
+
if (decoration !== "none" || tag === "a") out.push(`text-decoration:${decoration}`);
|
|
1379
|
+
}
|
|
1380
|
+
const vertical = values["vertical-align"];
|
|
1381
|
+
if ((tag === "td" || tag === "th") && KEYWORDS["vertical-align"].test(vertical)) out.push(`vertical-align:${vertical}`);
|
|
1382
|
+
out.push(...box(values, own, colors));
|
|
1383
|
+
return {
|
|
1384
|
+
css: out.join(";"),
|
|
1385
|
+
background: own,
|
|
1386
|
+
droppedColor
|
|
1387
|
+
};
|
|
1388
|
+
}
|
|
1389
|
+
/** Borders and padding, as shorthands where every side is the same. */
|
|
1390
|
+
function box(values, background, colors) {
|
|
1391
|
+
const borders = SIDES.map((side) => {
|
|
1392
|
+
const width = length(values[`border-${side}-width`]);
|
|
1393
|
+
const style = values[`border-${side}-style`];
|
|
1394
|
+
if (width === null || width === "0" || width === "0px" || !/^(?:solid|dashed|dotted|double)$/.test(style)) return null;
|
|
1395
|
+
const lineColor = colors === "none" ? null : opaque(values[`border-${side}-color`], background);
|
|
1396
|
+
return `${width} ${style}${lineColor === null ? "" : ` ${formatColor(lineColor)}`}`;
|
|
1397
|
+
});
|
|
1398
|
+
const out = [];
|
|
1399
|
+
if (borders.every((border) => border !== null && border === borders[0])) out.push(`border:${borders[0]}`);
|
|
1400
|
+
else borders.forEach((border, index) => {
|
|
1401
|
+
if (border !== null) out.push(`border-${SIDES[index]}:${border}`);
|
|
1402
|
+
});
|
|
1403
|
+
const padding = SIDES.map((side) => length(values[`padding-${side}`]) ?? "0");
|
|
1404
|
+
if (padding.some((value) => value !== "0" && value !== "0px")) out.push(`padding:${padding.map((value) => value === "0px" ? "0" : value).join(" ")}`);
|
|
1405
|
+
return out;
|
|
1406
|
+
}
|
|
1407
|
+
//#endregion
|
|
1408
|
+
//#region src/rich/text.ts
|
|
1409
|
+
/**
|
|
1410
|
+
* Readable plain text for sanitized rich content: blocks on their own lines, list
|
|
1411
|
+
* items with bullets or numbers (indented when nested), table cells separated by tabs,
|
|
1412
|
+
* images by their alt text, and preformatted text as it is.
|
|
1413
|
+
*/
|
|
1414
|
+
function plainText(root) {
|
|
1415
|
+
const lines = [];
|
|
1416
|
+
let line = "";
|
|
1417
|
+
const flush = () => {
|
|
1418
|
+
const trimmed = line.replace(/[ \t\u00A0]+$/, "");
|
|
1419
|
+
if (trimmed !== "" || lines.length > 0 && lines[lines.length - 1] !== "") lines.push(trimmed);
|
|
1420
|
+
line = "";
|
|
1421
|
+
};
|
|
1422
|
+
const breakBlock = () => {
|
|
1423
|
+
if (line.trim() !== "") flush();
|
|
1424
|
+
else line = "";
|
|
1425
|
+
};
|
|
1426
|
+
const walk = (node, pre, depth) => {
|
|
1427
|
+
if (node.nodeType === 3) {
|
|
1428
|
+
const data = node.data;
|
|
1429
|
+
if (pre) line += data.replace(/\r\n?/g, "\n");
|
|
1430
|
+
else {
|
|
1431
|
+
const collapsed = data.replace(/\s+/g, " ");
|
|
1432
|
+
line += /(?:^|[ \t])$/.test(line) && collapsed.startsWith(" ") ? collapsed.slice(1) : collapsed;
|
|
1433
|
+
}
|
|
1434
|
+
if (pre && line.includes("\n")) {
|
|
1435
|
+
const parts = line.split("\n");
|
|
1436
|
+
line = parts.pop();
|
|
1437
|
+
for (const part of parts) lines.push(part);
|
|
1438
|
+
}
|
|
1439
|
+
if (!pre && line.trimStart() === "") line = "";
|
|
1440
|
+
return;
|
|
1441
|
+
}
|
|
1442
|
+
if (node.nodeType !== 1) return;
|
|
1443
|
+
const element = node;
|
|
1444
|
+
const tag = element.localName;
|
|
1445
|
+
switch (tag) {
|
|
1446
|
+
case "br":
|
|
1447
|
+
flush();
|
|
1448
|
+
return;
|
|
1449
|
+
case "img":
|
|
1450
|
+
line += element.getAttribute("alt") ?? "";
|
|
1451
|
+
return;
|
|
1452
|
+
case "hr":
|
|
1453
|
+
breakBlock();
|
|
1454
|
+
lines.push("—".repeat(3));
|
|
1455
|
+
return;
|
|
1456
|
+
case "td":
|
|
1457
|
+
case "th":
|
|
1458
|
+
if (element.previousElementSibling !== null) line += " ";
|
|
1459
|
+
element.childNodes.forEach((child) => {
|
|
1460
|
+
walk(child, pre, depth);
|
|
1461
|
+
});
|
|
1462
|
+
return;
|
|
1463
|
+
case "li": {
|
|
1464
|
+
breakBlock();
|
|
1465
|
+
const list = element.parentElement;
|
|
1466
|
+
const ordered = list?.localName === "ol";
|
|
1467
|
+
let marker = "•";
|
|
1468
|
+
if (ordered) {
|
|
1469
|
+
const items = Array.from(list.children).filter((child) => child.localName === "li");
|
|
1470
|
+
const start = Number(list.getAttribute("start") ?? "1");
|
|
1471
|
+
const own = element.getAttribute("value");
|
|
1472
|
+
marker = `${String(own === null ? start + items.indexOf(element) : Number(own))}.`;
|
|
1473
|
+
}
|
|
1474
|
+
line = `${" ".repeat(Math.max(0, depth - 1))}${marker} `;
|
|
1475
|
+
element.childNodes.forEach((child) => {
|
|
1476
|
+
walk(child, pre, depth);
|
|
1477
|
+
});
|
|
1478
|
+
breakBlock();
|
|
1479
|
+
return;
|
|
1480
|
+
}
|
|
1481
|
+
default: {
|
|
1482
|
+
const block = TEXT_BLOCKS.has(tag);
|
|
1483
|
+
const list = tag === "ul" || tag === "ol";
|
|
1484
|
+
if (block) breakBlock();
|
|
1485
|
+
const keep = pre || tag === "pre" || /white-space:\s*pre/.test(element.getAttribute("style") ?? "");
|
|
1486
|
+
element.childNodes.forEach((child) => {
|
|
1487
|
+
walk(child, keep, list ? depth + 1 : depth);
|
|
1488
|
+
});
|
|
1489
|
+
if (block) breakBlock();
|
|
1490
|
+
}
|
|
1491
|
+
}
|
|
1492
|
+
};
|
|
1493
|
+
walk(root, false, 0);
|
|
1494
|
+
flush();
|
|
1495
|
+
return lines.join("\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
1496
|
+
}
|
|
1497
|
+
//#endregion
|
|
1498
|
+
//#region src/rich/walk.ts
|
|
1499
|
+
const VOID = /* @__PURE__ */ new Set([
|
|
1500
|
+
"br",
|
|
1501
|
+
"hr",
|
|
1502
|
+
"img",
|
|
1503
|
+
"col"
|
|
1504
|
+
]);
|
|
1505
|
+
const BLOCK_DISPLAY = /^(?:block|flex|grid|flow-root|list-item|table)$/;
|
|
1506
|
+
const DATA_IMAGE = /^data:image\/(?:png|jpeg|gif|webp);base64,[a-z\d+/]+=*$/i;
|
|
1507
|
+
function positive(value, fallback, name) {
|
|
1508
|
+
if (value === void 0) return fallback;
|
|
1509
|
+
if (Number.isInteger(value) && value > 0) return value;
|
|
1510
|
+
throw copyFailure("invalid-payload", `\`${name}\` must be a positive integer.`);
|
|
1511
|
+
}
|
|
1512
|
+
/** Whether `source` holds an element that would close a paragraph around it. */
|
|
1513
|
+
function holdsBlocks(source) {
|
|
1514
|
+
for (let child = source.firstElementChild; child !== null; child = child.nextElementSibling) if (CLOSES_P.has(child.localName) || holdsBlocks(child)) return true;
|
|
1515
|
+
return false;
|
|
1516
|
+
}
|
|
1517
|
+
/** Whether `node` is (inside) a link in the output. */
|
|
1518
|
+
function insideLink(node) {
|
|
1519
|
+
for (let current = node; current !== null; current = current.parentNode) if (current.localName === "a") return true;
|
|
1520
|
+
return false;
|
|
1521
|
+
}
|
|
1522
|
+
const isRange = (value) => typeof value === "object" && value !== null && "commonAncestorContainer" in value && typeof value.intersectsNode === "function";
|
|
1523
|
+
var Builder = class {
|
|
1524
|
+
constructor(out, options, mode, computed, colors, ignore, maxElements, maxLength, base) {
|
|
1525
|
+
this.out = out;
|
|
1526
|
+
this.options = options;
|
|
1527
|
+
this.mode = mode;
|
|
1528
|
+
this.computed = computed;
|
|
1529
|
+
this.colors = colors;
|
|
1530
|
+
this.ignore = ignore;
|
|
1531
|
+
this.maxElements = maxElements;
|
|
1532
|
+
this.maxLength = maxLength;
|
|
1533
|
+
this.removals = /* @__PURE__ */ new Map();
|
|
1534
|
+
this.truncated = false;
|
|
1535
|
+
this.elements = 0;
|
|
1536
|
+
this.size = 0;
|
|
1537
|
+
this.implied = /* @__PURE__ */ new WeakSet();
|
|
1538
|
+
this.scheme = (raw) => /^\s*([a-z][a-z\d+.-]*):/i.exec(raw ?? "")?.[1]?.toLowerCase() ?? "relative";
|
|
1539
|
+
const baseOption = base === void 0 ? {} : { base };
|
|
1540
|
+
this.resolveLink = linkUrlResolver({
|
|
1541
|
+
...baseOption,
|
|
1542
|
+
...options.protocols === void 0 ? {} : { protocols: options.protocols }
|
|
1543
|
+
});
|
|
1544
|
+
this.resolveImage = linkUrlResolver({
|
|
1545
|
+
...baseOption,
|
|
1546
|
+
protocols: options.dataImages === true ? [
|
|
1547
|
+
"https:",
|
|
1548
|
+
"http:",
|
|
1549
|
+
"data:"
|
|
1550
|
+
] : ["https:", "http:"]
|
|
1551
|
+
});
|
|
1552
|
+
}
|
|
1553
|
+
remove(reason, name) {
|
|
1554
|
+
const key = `${reason} ${name}`;
|
|
1555
|
+
const known = this.removals.get(key);
|
|
1556
|
+
this.removals.set(key, {
|
|
1557
|
+
reason,
|
|
1558
|
+
name,
|
|
1559
|
+
count: (known?.count ?? 0) + 1
|
|
1560
|
+
});
|
|
1561
|
+
}
|
|
1562
|
+
/** The style values to use for an element, or `null` when it is hidden. */
|
|
1563
|
+
values(element, parent) {
|
|
1564
|
+
if (this.mode === "computed") {
|
|
1565
|
+
const style = this.computed(element);
|
|
1566
|
+
if (style === null) return inherit(parent, void 0, element.localName);
|
|
1567
|
+
const display = style.getPropertyValue("display").trim();
|
|
1568
|
+
const visibility = style.getPropertyValue("visibility").trim();
|
|
1569
|
+
if (display === "none" || visibility === "hidden" || visibility === "collapse") return null;
|
|
1570
|
+
return {
|
|
1571
|
+
...readValues(style),
|
|
1572
|
+
display
|
|
1573
|
+
};
|
|
1574
|
+
}
|
|
1575
|
+
const declared = element.style;
|
|
1576
|
+
if (declared?.getPropertyValue("display").trim() === "none") return null;
|
|
1577
|
+
const tag = element.localName;
|
|
1578
|
+
return this.mode === "none" || declared === void 0 ? inherit(parent, void 0, tag) : inherit(parent, readValues(declared), tag);
|
|
1579
|
+
}
|
|
1580
|
+
url(raw, resolve) {
|
|
1581
|
+
if (raw === null || raw.trim() === "") return null;
|
|
1582
|
+
try {
|
|
1583
|
+
return resolve(raw);
|
|
1584
|
+
} catch {
|
|
1585
|
+
return null;
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
budget(cost) {
|
|
1589
|
+
if (this.elements >= this.maxElements || this.size + cost > this.maxLength) {
|
|
1590
|
+
this.truncated = true;
|
|
1591
|
+
return false;
|
|
1592
|
+
}
|
|
1593
|
+
this.size += cost;
|
|
1594
|
+
return true;
|
|
1595
|
+
}
|
|
1596
|
+
/** Converts `source` into `parent`, keeping only what lies inside `range` when given. */
|
|
1597
|
+
node(source, parent, inherited, background, range, root = false) {
|
|
1598
|
+
if (source.nodeType === 3) {
|
|
1599
|
+
let text = source.data;
|
|
1600
|
+
if (range !== null) {
|
|
1601
|
+
const end = source === range.endContainer ? range.endOffset : text.length;
|
|
1602
|
+
text = text.slice(source === range.startContainer ? range.startOffset : 0, end);
|
|
1603
|
+
}
|
|
1604
|
+
if (TABLE_CHILDREN[parent.localName] !== void 0 && text.trim() !== "") {
|
|
1605
|
+
this.remove("misplaced", "#text");
|
|
1606
|
+
return;
|
|
1607
|
+
}
|
|
1608
|
+
if (text !== "" && this.budget(text.length)) parent.appendChild(this.out.createTextNode(text));
|
|
1609
|
+
return;
|
|
1610
|
+
}
|
|
1611
|
+
if (source.nodeType === 11 || source.nodeType === 9) {
|
|
1612
|
+
this.children(source, parent, inherited, background, range);
|
|
1613
|
+
return;
|
|
1614
|
+
}
|
|
1615
|
+
if (source.nodeType !== 1) return;
|
|
1616
|
+
this.element(source, parent, inherited, background, range, root);
|
|
1617
|
+
}
|
|
1618
|
+
children(source, parent, inherited, background, range) {
|
|
1619
|
+
for (let child = source.firstChild; child !== null && !this.truncated; child = child.nextSibling) if (range === null || range.intersectsNode(child)) this.node(child, parent, inherited, background, range);
|
|
1620
|
+
}
|
|
1621
|
+
element(source, parent, inherited, background, range, root) {
|
|
1622
|
+
const tag = source.localName.toLowerCase();
|
|
1623
|
+
if (DROP.has(tag) || source.namespaceURI !== "http://www.w3.org/1999/xhtml") {
|
|
1624
|
+
this.remove("unsafe-element", tag);
|
|
1625
|
+
return;
|
|
1626
|
+
}
|
|
1627
|
+
if (source.hasAttribute("data-copy-ignore") || source.hasAttribute("hidden") || source.getAttribute("aria-hidden") === "true" || this.ignore !== null && source.matches(this.ignore)) {
|
|
1628
|
+
this.remove("ignored", tag);
|
|
1629
|
+
return;
|
|
1630
|
+
}
|
|
1631
|
+
let values = this.values(source, inherited);
|
|
1632
|
+
if (values === null) {
|
|
1633
|
+
this.remove("hidden", tag);
|
|
1634
|
+
return;
|
|
1635
|
+
}
|
|
1636
|
+
if (root && range !== null) values = {
|
|
1637
|
+
...values,
|
|
1638
|
+
"background-color": "",
|
|
1639
|
+
"border-top-style": "",
|
|
1640
|
+
"border-right-style": "",
|
|
1641
|
+
"border-bottom-style": "",
|
|
1642
|
+
"border-left-style": "",
|
|
1643
|
+
"padding-top": "",
|
|
1644
|
+
"padding-right": "",
|
|
1645
|
+
"padding-bottom": "",
|
|
1646
|
+
"padding-left": ""
|
|
1647
|
+
};
|
|
1648
|
+
if (tag === "img") {
|
|
1649
|
+
this.image(source, parent);
|
|
1650
|
+
return;
|
|
1651
|
+
}
|
|
1652
|
+
let name = KEEP.has(tag) ? tag : AS_BLOCK.has(tag) || BLOCK_DISPLAY.test(values.display ?? "") ? "div" : "span";
|
|
1653
|
+
let href = null;
|
|
1654
|
+
if (tag === "a") {
|
|
1655
|
+
const raw = source.getAttribute("href");
|
|
1656
|
+
href = this.url(raw, this.resolveLink);
|
|
1657
|
+
if (href === null) {
|
|
1658
|
+
if (raw !== null && raw.trim() !== "") this.remove("unsafe-link", this.scheme(raw));
|
|
1659
|
+
name = "span";
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
let target = parent;
|
|
1663
|
+
let parentTag = parent.localName;
|
|
1664
|
+
if (TABLE_PARTS.has(name) && TABLE_CHILDREN[parentTag] === void 0) {
|
|
1665
|
+
if (root) {
|
|
1666
|
+
target = parent.appendChild(this.out.createElement("table"));
|
|
1667
|
+
parentTag = "table";
|
|
1668
|
+
} else if (name === "col") {
|
|
1669
|
+
this.remove("misplaced", tag);
|
|
1670
|
+
return;
|
|
1671
|
+
} else name = "div";
|
|
1672
|
+
}
|
|
1673
|
+
const implied = [];
|
|
1674
|
+
if (parentTag === "table" && (name === "tr" || name === "td" || name === "th")) implied.push("tbody");
|
|
1675
|
+
if ((name === "td" || name === "th") && (implied.length > 0 || parentTag === "tbody" || parentTag === "thead" || parentTag === "tfoot")) implied.push("tr");
|
|
1676
|
+
if (parentTag === "table" && name === "col") implied.push("colgroup");
|
|
1677
|
+
const allowed = TABLE_CHILDREN[implied.at(-1) ?? parentTag];
|
|
1678
|
+
if (allowed !== void 0 && !allowed.has(name)) {
|
|
1679
|
+
this.remove("misplaced", tag);
|
|
1680
|
+
return;
|
|
1681
|
+
}
|
|
1682
|
+
if (name === "p" && holdsBlocks(source)) name = "div";
|
|
1683
|
+
if (HEADINGS.has(name) && HEADINGS.has(parentTag)) name = "span";
|
|
1684
|
+
if ((name === "li" || name === "dd" || name === "dt") && closesItem(name, parent)) name = "div";
|
|
1685
|
+
if (name === "div" && PHRASING.has(parentTag)) name = "span";
|
|
1686
|
+
if (name === "a" && insideLink(parent)) name = "span";
|
|
1687
|
+
if (!this.budget(name.length * 2 + 5)) return;
|
|
1688
|
+
for (const wrapper of implied) {
|
|
1689
|
+
const last = target.lastElementChild;
|
|
1690
|
+
target = last !== null && this.implied.has(last) && last.localName === wrapper ? last : target.appendChild(this.out.createElement(wrapper));
|
|
1691
|
+
this.implied.add(target);
|
|
1692
|
+
}
|
|
1693
|
+
this.elements += 1;
|
|
1694
|
+
const out = this.out.createElement(name);
|
|
1695
|
+
if (href !== null && name === "a") out.setAttribute("href", href);
|
|
1696
|
+
for (const attribute of Array.from(source.attributes)) {
|
|
1697
|
+
const key = attribute.name.toLowerCase();
|
|
1698
|
+
if (name === tag && attributeAllowed(tag, key, attribute.value)) out.setAttribute(key, attribute.value);
|
|
1699
|
+
}
|
|
1700
|
+
const style = declarations(name, values, root ? ROOT_PARENT : inherited, background, this.colors);
|
|
1701
|
+
if (style.droppedColor) this.remove("unreadable-color", tag);
|
|
1702
|
+
if (style.css !== "" && this.budget(style.css.length)) out.setAttribute("style", style.css);
|
|
1703
|
+
target.appendChild(out);
|
|
1704
|
+
if (!VOID.has(name)) this.children(source, out, values, style.background, range);
|
|
1705
|
+
}
|
|
1706
|
+
image(source, parent) {
|
|
1707
|
+
const alt = source.getAttribute("alt") ?? "";
|
|
1708
|
+
const policy = this.options.images ?? "keep";
|
|
1709
|
+
if (policy === "drop") {
|
|
1710
|
+
this.remove("image", "img");
|
|
1711
|
+
return;
|
|
1712
|
+
}
|
|
1713
|
+
const raw = this.mode === "computed" && source.currentSrc !== "" ? source.currentSrc : source.getAttribute("src");
|
|
1714
|
+
const src = policy === "keep" ? this.url(raw, this.resolveImage) : null;
|
|
1715
|
+
if (!(src !== null && (!src.startsWith("data:") || DATA_IMAGE.test(src) && src.length <= 2e6))) {
|
|
1716
|
+
this.remove(policy === "keep" ? "unsafe-image" : "image", policy === "keep" ? this.scheme(raw) : "img");
|
|
1717
|
+
if (alt !== "" && this.budget(alt.length)) parent.appendChild(this.out.createTextNode(alt));
|
|
1718
|
+
return;
|
|
1719
|
+
}
|
|
1720
|
+
if (!this.budget(src.length + alt.length + 40)) return;
|
|
1721
|
+
this.elements += 1;
|
|
1722
|
+
const out = this.out.createElement("img");
|
|
1723
|
+
out.setAttribute("src", src);
|
|
1724
|
+
if (alt !== "") out.setAttribute("alt", alt);
|
|
1725
|
+
for (const side of ["width", "height"]) {
|
|
1726
|
+
const shown = this.mode === "computed" ? Math.round(source[side]) : NaN;
|
|
1727
|
+
const declared = source.getAttribute(side) ?? "";
|
|
1728
|
+
const value = shown > 0 ? String(shown) : /^\d{1,5}$/.test(declared) ? declared : "";
|
|
1729
|
+
if (value !== "") out.setAttribute(side, value);
|
|
1730
|
+
}
|
|
1731
|
+
const title = source.getAttribute("title");
|
|
1732
|
+
if (title !== null) out.setAttribute("title", title);
|
|
1733
|
+
parent.appendChild(out);
|
|
1734
|
+
}
|
|
1735
|
+
};
|
|
1736
|
+
/** The DOM document to read and write with, or a typed error outside a browser. */
|
|
1737
|
+
function domFor(source) {
|
|
1738
|
+
if (typeof source === "string") {
|
|
1739
|
+
if (typeof DOMParser === "undefined") throw copyFailure("unsupported", "Reading HTML text needs a DOM (DOMParser); pass a DOM node, or use a browser or jsdom.");
|
|
1740
|
+
const doc = new DOMParser().parseFromString(`<!doctype html><body>${source}`, "text/html");
|
|
1741
|
+
return {
|
|
1742
|
+
doc,
|
|
1743
|
+
root: doc.body,
|
|
1744
|
+
range: null,
|
|
1745
|
+
live: false
|
|
1746
|
+
};
|
|
1747
|
+
}
|
|
1748
|
+
if (isRange(source)) {
|
|
1749
|
+
const container = source.commonAncestorContainer;
|
|
1750
|
+
const element = container.nodeType === 1 ? container : container.parentNode;
|
|
1751
|
+
if (element === null || container.ownerDocument === null) throw copyFailure("invalid-payload", "The range is not in a document.");
|
|
1752
|
+
return {
|
|
1753
|
+
doc: container.ownerDocument,
|
|
1754
|
+
root: element,
|
|
1755
|
+
range: source,
|
|
1756
|
+
live: container.isConnected
|
|
1757
|
+
};
|
|
1758
|
+
}
|
|
1759
|
+
const value = source;
|
|
1760
|
+
if (typeof value !== "object" || value === null || !("nodeType" in value) || value.nodeType !== 1 && value.nodeType !== 11) throw copyFailure("invalid-payload", "Rich content must be an element, a fragment, a range or HTML text.");
|
|
1761
|
+
const node = value;
|
|
1762
|
+
return {
|
|
1763
|
+
doc: node.ownerDocument,
|
|
1764
|
+
root: node,
|
|
1765
|
+
range: null,
|
|
1766
|
+
live: node.isConnected
|
|
1767
|
+
};
|
|
1768
|
+
}
|
|
1769
|
+
/**
|
|
1770
|
+
* Converts content into portable rich text: the HTML that mail clients, Google Docs,
|
|
1771
|
+
* Word, Notion and Slack paste as it looks, plus a plain-text version.
|
|
1772
|
+
*
|
|
1773
|
+
* - Only safe, widely supported elements and attributes are kept: never scripts,
|
|
1774
|
+
* event handlers, embeds, forms or tracking pixels from `data:` or `blob:` URLs.
|
|
1775
|
+
* - Styles are inline, from what the reader sees (computed styles) for content on
|
|
1776
|
+
* the page. Classes, stylesheets and CSS variables can't travel; their result can.
|
|
1777
|
+
* - Every colour becomes an opaque hex value, which every mail client understands
|
|
1778
|
+
* (not `oklch()` or `rgb(r g b / 50%)`). Text that would be unreadable on a white
|
|
1779
|
+
* page, such as light text from a dark theme, keeps the destination's colour.
|
|
1780
|
+
* - Links and images get absolute, scheme-checked URLs; images get their displayed size.
|
|
1781
|
+
*
|
|
1782
|
+
* Never inserts anything into the page: the output is built in a separate, inert document.
|
|
1783
|
+
*
|
|
1784
|
+
* @example
|
|
1785
|
+
* const { html, text, removed } = prepareRich(articleRef.current);
|
|
1786
|
+
*/
|
|
1787
|
+
function prepareRich(source, options = {}) {
|
|
1788
|
+
const { doc, root, range, live } = domFor(source);
|
|
1789
|
+
const mode = options.styles ?? (live && doc.defaultView !== null ? "computed" : "inline");
|
|
1790
|
+
const modeValue = mode;
|
|
1791
|
+
if (modeValue !== "computed" && modeValue !== "inline" && modeValue !== "none") throw copyFailure("invalid-payload", "`styles` must be \"computed\", \"inline\" or \"none\".");
|
|
1792
|
+
const colors = options.colors ?? "readable";
|
|
1793
|
+
const colorsValue = colors;
|
|
1794
|
+
if (colorsValue !== "readable" && colorsValue !== "keep" && colorsValue !== "none") throw copyFailure("invalid-payload", "`colors` must be \"readable\", \"keep\" or \"none\".");
|
|
1795
|
+
const images = options.images ?? "keep";
|
|
1796
|
+
if (images !== "keep" && images !== "alt" && images !== "drop") throw copyFailure("invalid-payload", "`images` must be \"keep\", \"alt\" or \"drop\".");
|
|
1797
|
+
const view = doc.defaultView;
|
|
1798
|
+
const computed = options.computedStyle ?? ((element) => view === null ? null : view.getComputedStyle(element));
|
|
1799
|
+
const page = options.background === void 0 ? WHITE : declarationsBackground(options.background);
|
|
1800
|
+
if (options.ignore !== void 0) try {
|
|
1801
|
+
doc.createElement("div").matches(options.ignore);
|
|
1802
|
+
} catch (cause) {
|
|
1803
|
+
throw copyFailure("invalid-payload", `\`ignore\` is not a valid CSS selector: ${options.ignore}`, cause);
|
|
1804
|
+
}
|
|
1805
|
+
const out = doc.implementation.createHTMLDocument("");
|
|
1806
|
+
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));
|
|
1807
|
+
const container = out.createElement("div");
|
|
1808
|
+
if (typeof source === "string") builder.children(root, container, ROOT_PARENT, page, null);
|
|
1809
|
+
else builder.node(root, container, ROOT_PARENT, page, range, true);
|
|
1810
|
+
container.normalize();
|
|
1811
|
+
const text = (options.text ?? plainText)(container);
|
|
1812
|
+
if (typeof text !== "string") throw copyFailure("invalid-payload", "`text` must return a string.");
|
|
1813
|
+
const first = container.firstChild;
|
|
1814
|
+
if (first?.nodeType === 3) first.data = first.data.replace(/^\s+/, "");
|
|
1815
|
+
const last = container.lastChild;
|
|
1816
|
+
if (last?.nodeType === 3) last.data = last.data.replace(/\s+$/, "");
|
|
1817
|
+
const empty = container.textContent.trim() === "" && container.querySelector("img, br, hr") === null;
|
|
1818
|
+
return {
|
|
1819
|
+
html: empty ? "" : container.innerHTML,
|
|
1820
|
+
text: empty ? "" : text,
|
|
1821
|
+
removed: [...builder.removals.values()],
|
|
1822
|
+
truncated: builder.truncated
|
|
1823
|
+
};
|
|
1824
|
+
}
|
|
1825
|
+
/** The destination background as an opaque colour; a typed error for anything else. */
|
|
1826
|
+
function declarationsBackground(value) {
|
|
1827
|
+
const parsed = typeof value === "string" ? parseColor(value) : null;
|
|
1828
|
+
if (parsed === null || parsed.alpha !== 1) throw copyFailure("invalid-payload", "`background` must be an opaque CSS colour.");
|
|
1829
|
+
return parsed;
|
|
1830
|
+
}
|
|
1831
|
+
//#endregion
|
|
1832
|
+
//#region src/rich/payload.ts
|
|
1833
|
+
/**
|
|
1834
|
+
* Content to copy as portable rich text: the sanitized HTML, and its plain text for
|
|
1835
|
+
* editors and plain fields. A typed `invalid-payload` error when nothing is left to copy.
|
|
1836
|
+
*
|
|
1837
|
+
* @example
|
|
1838
|
+
* const { copy } = useCopy();
|
|
1839
|
+
* <button onClick={() => copy(() => richPayload(noteRef.current))}>Copy note</button>
|
|
1840
|
+
*/
|
|
1841
|
+
function richPayload(source, options = {}) {
|
|
1842
|
+
const { html, text } = prepareRich(source, options);
|
|
1843
|
+
if (html === "" || text === "") throw copyFailure("invalid-payload", "There is nothing to copy: the content is empty, hidden or entirely left out.");
|
|
1844
|
+
return {
|
|
1845
|
+
kind: "html",
|
|
1846
|
+
html,
|
|
1847
|
+
text
|
|
1848
|
+
};
|
|
1849
|
+
}
|
|
1850
|
+
/**
|
|
1851
|
+
* A copy interceptor transform that makes Ctrl/Cmd+C (and cut) of a selection in your
|
|
1852
|
+
* page portable: what the reader selected, with the styles they see, sanitized. The
|
|
1853
|
+
* plain text stays the browser's own. Selections in text fields are left alone.
|
|
1854
|
+
*
|
|
1855
|
+
* @example
|
|
1856
|
+
* useCopyInterceptor(articleRef, { transform: richTransform() });
|
|
1857
|
+
*/
|
|
1858
|
+
function richTransform(options = {}) {
|
|
1859
|
+
return (selection) => {
|
|
1860
|
+
if (selection.field !== null || typeof document === "undefined") return void 0;
|
|
1861
|
+
const live = document.getSelection();
|
|
1862
|
+
if (live === null || live.rangeCount === 0) return void 0;
|
|
1863
|
+
const parts = [];
|
|
1864
|
+
for (let index = 0; index < live.rangeCount; index += 1) {
|
|
1865
|
+
const { html, text } = prepareRich(live.getRangeAt(index), options);
|
|
1866
|
+
if (text !== "" || html.includes("<img")) parts.push(html);
|
|
1867
|
+
}
|
|
1868
|
+
const html = parts.join("");
|
|
1869
|
+
return html === "" ? void 0 : {
|
|
1870
|
+
kind: "html",
|
|
1871
|
+
html,
|
|
1872
|
+
text: selection.text
|
|
1873
|
+
};
|
|
1874
|
+
};
|
|
1875
|
+
}
|
|
1876
|
+
//#endregion
|
|
1877
|
+
export { plainText, prepareRich, richPayload, richTransform };
|
|
1878
|
+
|
|
1879
|
+
//# sourceMappingURL=rich.js.map
|