@pairdraw/web-capture 0.19.0 → 0.19.2

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.
@@ -1,4 +1,4 @@
1
- import { compact } from "es-toolkit";
1
+ import { compact, omit } from "es-toolkit";
2
2
  import { Inflate, deflateSync, strToU8 } from "fflate";
3
3
  import { fromUint8Array, isValid, toUint8Array } from "js-base64";
4
4
  import { escapeAttribute, escapeText } from "entities";
@@ -12,6 +12,357 @@ function ownValue(record, key) {
12
12
  return Object.hasOwn(record, key) ? record[key] : void 0;
13
13
  }
14
14
  //#endregion
15
+ //#region src/design-document.ts
16
+ const SIDES$1 = [
17
+ "top",
18
+ "right",
19
+ "bottom",
20
+ "left"
21
+ ];
22
+ /**
23
+ * Displays the importer has no layout for, mapped to the closest one it has. A grid of
24
+ * fixed-size cells wraps as a row of them does, and a table row is a row of its cells.
25
+ */
26
+ const DISPLAY_FALLBACKS = {
27
+ grid: {
28
+ display: "flex",
29
+ "flex-direction": "row",
30
+ "flex-wrap": "wrap"
31
+ },
32
+ "inline-grid": {
33
+ display: "inline-flex",
34
+ "flex-direction": "row",
35
+ "flex-wrap": "wrap"
36
+ },
37
+ "table-row": {
38
+ display: "flex",
39
+ "flex-direction": "row",
40
+ "flex-wrap": "nowrap"
41
+ },
42
+ table: { display: "block" },
43
+ "inline-table": { display: "inline-block" },
44
+ "table-row-group": { display: "block" },
45
+ "table-header-group": { display: "block" },
46
+ "table-footer-group": { display: "block" },
47
+ "table-cell": { display: "block" },
48
+ "table-caption": { display: "block" },
49
+ "list-item": { display: "block" },
50
+ "flow-root": { display: "block" }
51
+ };
52
+ /**
53
+ * Inline text tags the importer lays out inline when they say nothing of their display. Left
54
+ * without one, a run such as a link or a bold word stays text instead of a box around text.
55
+ */
56
+ const INLINE_TEXT_TAGS = /* @__PURE__ */ new Set([
57
+ "a",
58
+ "b",
59
+ "code",
60
+ "em",
61
+ "i",
62
+ "small",
63
+ "span",
64
+ "strong",
65
+ "u"
66
+ ]);
67
+ function pixels(value) {
68
+ if (!value?.endsWith("px")) return 0;
69
+ const parsed = Number.parseFloat(value);
70
+ return Number.isFinite(parsed) ? parsed : 0;
71
+ }
72
+ function px(value) {
73
+ return `${Math.round(value * 100) / 100}px`;
74
+ }
75
+ const MARGINS = SIDES$1.map((side) => `margin-${side}`);
76
+ /** The element's margins in pixels, and its style without them. */
77
+ function splitMargins(style) {
78
+ const margins = {
79
+ top: 0,
80
+ right: 0,
81
+ bottom: 0,
82
+ left: 0
83
+ };
84
+ for (const side of SIDES$1) margins[side] = pixels(style[`margin-${side}`]);
85
+ return {
86
+ margins,
87
+ style: omit(style, MARGINS)
88
+ };
89
+ }
90
+ function isAbsolute(style) {
91
+ return style.position === "absolute" || style.position === "fixed";
92
+ }
93
+ function isInline(style) {
94
+ return (ownValue(style, "display") ?? "").startsWith("inline");
95
+ }
96
+ /**
97
+ * Places an absolute box in its parent layer. CSS measures `left` and `top` from the containing
98
+ * block, which may be a further ancestor or the viewport, so the recorded boxes place it where
99
+ * the page drew it. Without them, it sits at its offset plus its margin, as CSS places it.
100
+ */
101
+ function placeAbsolute(style, margins, box, parentBox) {
102
+ if (box && parentBox) {
103
+ style.left = px(box.x - parentBox.x);
104
+ style.top = px(box.y - parentBox.y);
105
+ return;
106
+ }
107
+ if (ownValue(style, "left") !== void 0) style.left = px(pixels(style.left) + margins.left);
108
+ if (ownValue(style, "top") !== void 0) style.top = px(pixels(style.top) + margins.top);
109
+ }
110
+ /**
111
+ * A box in normal flow keeps the room its margins took inside a transparent box padded by them.
112
+ * Negative margins, which pull neighbours over each other, are dropped.
113
+ */
114
+ function marginBox(element, margins) {
115
+ const style = { display: "block" };
116
+ for (const side of SIDES$1) if (margins[side] > 0) style[`padding-${side}`] = px(margins[side]);
117
+ const alignSelf = ownValue(element.computedStyle, "align-self");
118
+ if (alignSelf === void 0) return {
119
+ type: "element",
120
+ tagName: "div",
121
+ attrs: {},
122
+ computedStyle: style,
123
+ children: [element]
124
+ };
125
+ style["align-self"] = alignSelf;
126
+ return {
127
+ type: "element",
128
+ tagName: "div",
129
+ attrs: {},
130
+ computedStyle: style,
131
+ children: [{
132
+ ...element,
133
+ computedStyle: omit(element.computedStyle, ["align-self"])
134
+ }]
135
+ };
136
+ }
137
+ function convertChildren(children, parentBox) {
138
+ return children.map((child) => child.type === "text" ? child : convertElement(child, parentBox));
139
+ }
140
+ const GRID_DISPLAYS = /* @__PURE__ */ new Set(["grid", "inline-grid"]);
141
+ function hasBox(element) {
142
+ return element.box !== void 0;
143
+ }
144
+ /**
145
+ * A grid whose items can stay where the page drew them: the capture recorded the grid's box and
146
+ * every item's, and the grid holds no loose text. Null otherwise, and for anything but a grid.
147
+ */
148
+ function placeableGrid(element) {
149
+ if (!GRID_DISPLAYS.has(ownValue(element.computedStyle, "display") ?? "") || !hasBox(element)) return null;
150
+ const items = [];
151
+ for (const child of element.children) if (child.type === "text") {
152
+ if (child.text.trim().length > 0) return null;
153
+ } else if (hasBox(child)) items.push(child);
154
+ else return null;
155
+ return {
156
+ box: element.box,
157
+ items
158
+ };
159
+ }
160
+ /**
161
+ * Auto layout has no grid tracks, so a grid keeps its drawn size and its items become absolute
162
+ * boxes where the page drew them. Their margins already moved their boxes.
163
+ */
164
+ function gridStyle(style, box) {
165
+ return {
166
+ ...omit(style, [
167
+ "gap",
168
+ "row-gap",
169
+ "column-gap"
170
+ ]),
171
+ display: style.display === "inline-grid" ? "inline-block" : "block",
172
+ width: px(box.width),
173
+ height: px(box.height),
174
+ "box-sizing": "border-box"
175
+ };
176
+ }
177
+ const PLACEMENT = [
178
+ ...MARGINS,
179
+ "position",
180
+ ...SIDES$1
181
+ ];
182
+ function placeGridItem(item, grid) {
183
+ const converted = convertElement({
184
+ ...item,
185
+ computedStyle: omit(item.computedStyle, PLACEMENT)
186
+ });
187
+ converted.computedStyle = {
188
+ ...converted.computedStyle,
189
+ position: "absolute",
190
+ left: px(item.box.x - grid.x),
191
+ top: px(item.box.y - grid.y),
192
+ width: px(item.box.width),
193
+ height: px(item.box.height),
194
+ "box-sizing": "border-box"
195
+ };
196
+ return converted;
197
+ }
198
+ /**
199
+ * The style an element is laid out with, the closest display the importer has standing in for
200
+ * one it lacks, and its converted children.
201
+ */
202
+ function layoutOf(element) {
203
+ const grid = placeableGrid(element);
204
+ if (grid) return {
205
+ displayed: gridStyle(element.computedStyle, grid.box),
206
+ children: grid.items.map((item) => placeGridItem(item, grid.box))
207
+ };
208
+ const display = ownValue(element.computedStyle, "display") ?? "";
209
+ return {
210
+ displayed: {
211
+ ...element.computedStyle,
212
+ ...DISPLAY_FALLBACKS[display]
213
+ },
214
+ children: convertChildren(element.children, element.box)
215
+ };
216
+ }
217
+ /** Input types Chrome paints as a small intrinsic glyph, whatever box `width` gives them. */
218
+ const GLYPH_INPUT_TYPES = {
219
+ checkbox: true,
220
+ radio: true
221
+ };
222
+ /**
223
+ * A checkbox or radio wider than its glyph: Chrome honors the width for layout but paints only
224
+ * a small square centered in the box (`input { width: 100% }` in a flex label). Import the
225
+ * square at the glyph's size, centered in a box that keeps the room the wide element took, so
226
+ * following content stays where the page put it. Null when the box already fits the glyph.
227
+ */
228
+ function glyphBox(element, converted, margins, parentBox) {
229
+ const box = element.box;
230
+ if (element.tagName !== "input" || !Object.hasOwn(GLYPH_INPUT_TYPES, element.attrs.type) || !box || box.width <= 0 || box.height <= 0) return null;
231
+ const side = Math.min(box.width, box.height);
232
+ if (box.width - side < 1) return null;
233
+ const style = converted.computedStyle;
234
+ const absolute = isAbsolute(style);
235
+ style.width = px(side);
236
+ style.height = px(side);
237
+ style["box-sizing"] = "border-box";
238
+ delete style.position;
239
+ delete style.left;
240
+ delete style.top;
241
+ delete style.right;
242
+ delete style.bottom;
243
+ const wrapper = {
244
+ display: "flex",
245
+ "justify-content": "center",
246
+ "align-items": "center",
247
+ width: px(box.width),
248
+ height: px(box.height),
249
+ "box-sizing": "border-box"
250
+ };
251
+ const alignSelf = ownValue(style, "align-self");
252
+ if (alignSelf !== void 0) {
253
+ wrapper["align-self"] = alignSelf;
254
+ delete style["align-self"];
255
+ }
256
+ const wrapped = {
257
+ type: "element",
258
+ tagName: "div",
259
+ attrs: {},
260
+ computedStyle: wrapper,
261
+ children: [converted]
262
+ };
263
+ if (absolute) {
264
+ wrapper.position = element.computedStyle.position === "fixed" ? "fixed" : "absolute";
265
+ for (const key of ["left", "top"]) {
266
+ const value = ownValue(element.computedStyle, key);
267
+ if (value !== void 0) wrapper[key] = value;
268
+ }
269
+ placeAbsolute(wrapper, margins, box, parentBox);
270
+ return wrapped;
271
+ }
272
+ return SIDES$1.some((side) => margins[side] > 0) ? marginBox(wrapped, margins) : wrapped;
273
+ }
274
+ /** What a box records of its size and border, which a word box drawn as a run of text drops. */
275
+ const WORD_BOX_PROPERTIES = [
276
+ "display",
277
+ "width",
278
+ "height",
279
+ "min-width",
280
+ "max-width",
281
+ "min-height",
282
+ "max-height",
283
+ "box-sizing",
284
+ ...SIDES$1.flatMap((side) => [
285
+ "style",
286
+ "width",
287
+ "color"
288
+ ].map((part) => `border-${side}-${part}`))
289
+ ];
290
+ /** Properties that make a box draw something besides its text, or change where its text sits. */
291
+ const DRAWN_BOX_PROPERTIES = [
292
+ "background-color",
293
+ "background-image",
294
+ "box-shadow",
295
+ "opacity",
296
+ "overflow",
297
+ ...SIDES$1.map((side) => `padding-${side}`)
298
+ ];
299
+ /**
300
+ * An inline-block that holds one line of text and draws nothing else, as pages that fade words
301
+ * in box each word. It reads as a run of the text around it, not a box: kept as a box, every word
302
+ * becomes a layer of its own and wraps at its own width.
303
+ */
304
+ function isWordBox(element, style) {
305
+ if (style.display !== "inline-block" || !INLINE_TEXT_TAGS.has(element.tagName)) return false;
306
+ if (!element.children.every((child) => child.type === "text")) return false;
307
+ if (DRAWN_BOX_PROPERTIES.some((property) => ownValue(style, property) !== void 0)) return false;
308
+ if (SIDES$1.some((side) => pixels(style[`margin-${side}`]) !== 0)) return false;
309
+ if (SIDES$1.some((side) => pixels(style[`border-${side}-width`]) > 0)) return false;
310
+ const lineHeight = pixels(style["line-height"]) || pixels(style["font-size"]) * 1.5;
311
+ return element.box !== void 0 && element.box.height < lineHeight * 1.5;
312
+ }
313
+ function convertElement(element, parentBox) {
314
+ const { displayed, children } = layoutOf(element);
315
+ if (isWordBox(element, displayed)) return {
316
+ type: "element",
317
+ tagName: element.tagName,
318
+ attrs: { ...element.attrs },
319
+ computedStyle: omit(displayed, [...WORD_BOX_PROPERTIES, ...MARGINS]),
320
+ children
321
+ };
322
+ const inline = isInline(displayed);
323
+ const split = splitMargins(displayed);
324
+ const { margins } = split;
325
+ const style = displayed.display === "inline" && INLINE_TEXT_TAGS.has(element.tagName) ? omit(split.style, ["display"]) : split.style;
326
+ const converted = {
327
+ type: "element",
328
+ tagName: element.tagName,
329
+ attrs: { ...element.attrs },
330
+ computedStyle: style,
331
+ children
332
+ };
333
+ const glyph = glyphBox(element, converted, margins, parentBox);
334
+ if (glyph) return glyph;
335
+ if (isAbsolute(style)) {
336
+ placeAbsolute(style, margins, element.box, parentBox);
337
+ return converted;
338
+ }
339
+ return SIDES$1.some((side) => margins[side] > 0) && !inline ? marginBox(converted, margins) : converted;
340
+ }
341
+ /**
342
+ * The capture as the styled DOM layers are built from. The root keeps the size it had on the
343
+ * page and drops its own position and margins, so it lands where a paste puts it.
344
+ */
345
+ function webCaptureDesignDocument(capture) {
346
+ const { root } = capture;
347
+ const { displayed, children } = layoutOf(root);
348
+ const style = omit(splitMargins(displayed).style, ["position", ...SIDES$1]);
349
+ if (root.box) {
350
+ style.width = px(root.box.width);
351
+ style.height = px(root.box.height);
352
+ style["box-sizing"] = "border-box";
353
+ }
354
+ return {
355
+ type: "document",
356
+ children: [{
357
+ type: "element",
358
+ tagName: root.tagName,
359
+ attrs: { ...root.attrs },
360
+ computedStyle: style,
361
+ children
362
+ }]
363
+ };
364
+ }
365
+ //#endregion
15
366
  //#region src/html.ts
16
367
  const VOID_TAGS = /* @__PURE__ */ new Set([
17
368
  "area",
@@ -23,28 +374,76 @@ const VOID_TAGS = /* @__PURE__ */ new Set([
23
374
  "source",
24
375
  "wbr"
25
376
  ]);
377
+ /** Tags whose start ends an open `<p>` when HTML is parsed, which would lift them out of it. */
378
+ const CLOSES_PARAGRAPH = /* @__PURE__ */ new Set([
379
+ "address",
380
+ "article",
381
+ "aside",
382
+ "blockquote",
383
+ "details",
384
+ "div",
385
+ "dl",
386
+ "fieldset",
387
+ "figcaption",
388
+ "figure",
389
+ "footer",
390
+ "form",
391
+ "h1",
392
+ "h2",
393
+ "h3",
394
+ "h4",
395
+ "h5",
396
+ "h6",
397
+ "header",
398
+ "hgroup",
399
+ "hr",
400
+ "main",
401
+ "menu",
402
+ "nav",
403
+ "ol",
404
+ "p",
405
+ "pre",
406
+ "section",
407
+ "table",
408
+ "ul"
409
+ ]);
410
+ /**
411
+ * The tag an element is written with. A script can put a block inside a `<p>`, as the capture's
412
+ * own spacers around a margined box do, but parsing would end the paragraph there; a `<div>`
413
+ * holds it in place, and the element's styles say how it lays out either way.
414
+ */
415
+ function writtenTag(element) {
416
+ const holdsBlock = element.children.some((child) => child.type === "element" && CLOSES_PARAGRAPH.has(child.tagName));
417
+ return element.tagName === "p" && holdsBlock ? "div" : element.tagName;
418
+ }
26
419
  function styleAttribute(style) {
27
420
  return Object.entries(style).map(([property, value]) => `${property}: ${value}`).join("; ");
28
421
  }
29
422
  function attributes(element, options) {
30
423
  const attrs = { ...element.attrs };
31
424
  if (options.images === false && ownValue(attrs, "src")?.startsWith("data:")) delete attrs.src;
425
+ if (element.tagName === "input") {
426
+ const text = element.children.map((child) => child.type === "text" ? child.text : "").join("");
427
+ if (text) attrs.value = text;
428
+ }
32
429
  const style = styleAttribute(element.computedStyle);
33
430
  if (style) attrs.style = style;
34
431
  return Object.entries(attrs).map(([name, value]) => ` ${name}="${escapeAttribute(value)}"`).join("");
35
432
  }
36
433
  function serialize(node, options) {
37
434
  if (node.type === "text") return escapeText(node.text);
38
- const open = `<${node.tagName}${attributes(node, options)}>`;
39
- if (VOID_TAGS.has(node.tagName)) return open;
40
- return `${open}${node.children.map((child) => serialize(child, options)).join("")}</${node.tagName}>`;
435
+ const tag = writtenTag(node);
436
+ const open = `<${tag}${attributes(node, options)}>`;
437
+ if (VOID_TAGS.has(tag)) return open;
438
+ return `${open}${node.children.map((child) => serialize(child, options)).join("")}</${tag}>`;
41
439
  }
42
440
  /**
43
- * The capture as static HTML whose elements carry their computed styles inline, for
44
- * applications that read clipboard HTML but not the capture itself.
441
+ * The capture as static HTML whose elements carry their styles inline, for applications that
442
+ * read clipboard HTML but not the capture itself, and for importing it as HTML. It is the styled
443
+ * DOM a paste builds layers from, so the HTML importer reads the capture as the paste does.
45
444
  */
46
445
  function webCaptureToHTML(capture, options = {}) {
47
- return serialize(capture.root, options);
446
+ return webCaptureDesignDocument(capture).children.map((node) => serialize(node, options)).join("");
48
447
  }
49
448
  //#endregion
50
449
  //#region src/limits.ts
@@ -183,6 +582,7 @@ const CAPTURED_STYLE_PROPERTIES = [
183
582
  "min-width",
184
583
  "object-fit",
185
584
  "opacity",
585
+ "order",
186
586
  "overflow",
187
587
  "padding-bottom",
188
588
  "padding-left",
@@ -242,6 +642,7 @@ const IMPLIED_VALUES = {
242
642
  "min-width": ["auto", "0px"],
243
643
  "object-fit": ["fill"],
244
644
  opacity: ["1"],
645
+ order: ["0"],
245
646
  overflow: ["visible"],
246
647
  "row-gap": ["normal"],
247
648
  "text-indent": ["0px"],
@@ -625,6 +1026,6 @@ async function writeWebCaptureClipboard(capture, options = {}) {
625
1026
  })]);
626
1027
  }
627
1028
  //#endregion
628
- export { CAPTURED_STYLE_PROPERTIES, CaptureClipboardUnavailableError, MAX_CAPTURE_DEPTH, MAX_CAPTURE_ELEMENTS, MAX_CAPTURE_IMAGES_BYTES, MAX_CAPTURE_IMAGE_BYTES, MAX_CAPTURE_JSON_LENGTH, MAX_WEB_HTML_LENGTH, WEB_CAPTURE_CLIPBOARD_END, WEB_CAPTURE_CLIPBOARD_START, WEB_CAPTURE_FORMAT, WEB_CAPTURE_VERSION, encodeWebCaptureClipboard, hasWebCaptureClipboardMarker, isCapturedStyleProperty, normalizeWebCapture, ownValue, parseWebCapture, readWebCapture, readWebCaptureClipboard, safeImageSource, safeLinkURL, webCaptureSchema, webCaptureToHTML, withoutImpliedValues, writeWebCaptureClipboard };
1029
+ export { CAPTURED_STYLE_PROPERTIES, CaptureClipboardUnavailableError, MAX_CAPTURE_DEPTH, MAX_CAPTURE_ELEMENTS, MAX_CAPTURE_IMAGES_BYTES, MAX_CAPTURE_IMAGE_BYTES, MAX_CAPTURE_JSON_LENGTH, MAX_WEB_HTML_LENGTH, WEB_CAPTURE_CLIPBOARD_END, WEB_CAPTURE_CLIPBOARD_START, WEB_CAPTURE_FORMAT, WEB_CAPTURE_VERSION, encodeWebCaptureClipboard, hasWebCaptureClipboardMarker, isCapturedStyleProperty, normalizeWebCapture, parseWebCapture, readWebCapture, readWebCaptureClipboard, safeImageSource, safeLinkURL, webCaptureDesignDocument, webCaptureSchema, webCaptureToHTML, withoutImpliedValues, writeWebCaptureClipboard };
629
1030
 
630
1031
  //# sourceMappingURL=clipboard.js.map