@pairdraw/web-capture 0.0.0-stage → 0.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +20 -2
- package/dist/capturer.d.ts +56 -0
- package/dist/capturer.d.ts.map +1 -0
- package/dist/capturer.js +3 -0
- package/dist/chunks/capturer/clipboard.js +575 -0
- package/dist/chunks/capturer/clipboard.js.map +1 -0
- package/dist/chunks/capturer/fonts.js +25 -0
- package/dist/chunks/capturer/fonts.js.map +1 -0
- package/dist/chunks/capturer/images.js +113 -0
- package/dist/chunks/capturer/images.js.map +1 -0
- package/dist/chunks/capturer/index.js +445 -0
- package/dist/chunks/capturer/index.js.map +1 -0
- package/dist/chunks/design-document.js +251 -0
- package/dist/chunks/design-document.js.map +1 -0
- package/dist/chunks/index.js +125 -0
- package/dist/chunks/index.js.map +1 -0
- package/dist/clipboard.d.ts +106 -0
- package/dist/clipboard.d.ts.map +1 -0
- package/dist/index.d.ts +110 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/package.json +55 -4
- package/src/capturer/clipboard.ts +59 -0
- package/src/capturer/fonts.ts +30 -0
- package/src/capturer/images.ts +153 -0
- package/src/capturer/index.ts +170 -0
- package/src/capturer/page.ts +51 -0
- package/src/capturer/svg.ts +79 -0
- package/src/capturer/walk.ts +283 -0
- package/src/clipboard.ts +85 -0
- package/src/design-document.ts +267 -0
- package/src/format.ts +17 -0
- package/src/html.ts +44 -0
- package/src/index.ts +41 -0
- package/src/limits.ts +23 -0
- package/src/parse.ts +165 -0
- package/src/record.ts +10 -0
- package/src/sanitize.ts +134 -0
- package/src/schema.ts +75 -0
- package/src/styles.ts +163 -0
- package/src/types.ts +28 -0
- package/src/urls.ts +27 -0
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { MAX_CAPTURE_DEPTH } from '#web-capture/limits'
|
|
2
|
+
import { CAPTURED_STYLE_PROPERTIES, withoutImpliedValues } from '#web-capture/styles'
|
|
3
|
+
import type { WebCaptureBox, WebCaptureElement, WebCaptureNode } from '#web-capture/types'
|
|
4
|
+
|
|
5
|
+
import type { FontCollector } from './fonts'
|
|
6
|
+
import type { CaptureWindow, ImageInliner } from './images'
|
|
7
|
+
import { standaloneSVGMarkup } from './svg'
|
|
8
|
+
|
|
9
|
+
/** What a walk shares: the page, where the root sits, its budget, and work left to finish. */
|
|
10
|
+
export interface WalkContext {
|
|
11
|
+
view: CaptureWindow
|
|
12
|
+
origin: Pick<WebCaptureBox, 'x' | 'y'>
|
|
13
|
+
maxElements: number
|
|
14
|
+
elements: number
|
|
15
|
+
truncated: boolean
|
|
16
|
+
images: ImageInliner
|
|
17
|
+
fonts: FontCollector
|
|
18
|
+
/** Images still being read, each writing its element's source when done. */
|
|
19
|
+
pending: Promise<void>[]
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Elements that never draw, or draw another document a page cannot read. */
|
|
23
|
+
const SKIPPED_TAGS = new Set([
|
|
24
|
+
'script',
|
|
25
|
+
'style',
|
|
26
|
+
'link',
|
|
27
|
+
'meta',
|
|
28
|
+
'head',
|
|
29
|
+
'title',
|
|
30
|
+
'template',
|
|
31
|
+
'noscript',
|
|
32
|
+
'base',
|
|
33
|
+
'iframe',
|
|
34
|
+
'frame',
|
|
35
|
+
'object',
|
|
36
|
+
'embed',
|
|
37
|
+
'source',
|
|
38
|
+
'track',
|
|
39
|
+
'param'
|
|
40
|
+
])
|
|
41
|
+
|
|
42
|
+
const KEPT_ATTRIBUTES = ['id', 'class', 'alt', 'title', 'role', 'aria-label', 'lang', 'dir']
|
|
43
|
+
|
|
44
|
+
/** Input types whose value is text a person reads in the field. */
|
|
45
|
+
const TEXT_INPUT_TYPES = new Set([
|
|
46
|
+
'',
|
|
47
|
+
'text',
|
|
48
|
+
'email',
|
|
49
|
+
'search',
|
|
50
|
+
'url',
|
|
51
|
+
'tel',
|
|
52
|
+
'number',
|
|
53
|
+
'password'
|
|
54
|
+
])
|
|
55
|
+
|
|
56
|
+
const BACKGROUND_URL = /url\(\s*(['"]?)(.*?)\1\s*\)/
|
|
57
|
+
|
|
58
|
+
function boxOf(element: Element, origin: WalkContext['origin']): WebCaptureBox {
|
|
59
|
+
const rect = element.getBoundingClientRect()
|
|
60
|
+
return {
|
|
61
|
+
x: rect.left - origin.x,
|
|
62
|
+
y: rect.top - origin.y,
|
|
63
|
+
width: rect.width,
|
|
64
|
+
height: rect.height
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function attributesOf(element: Element, view: CaptureWindow): Record<string, string> {
|
|
69
|
+
const attrs: Record<string, string> = {}
|
|
70
|
+
for (const name of KEPT_ATTRIBUTES) {
|
|
71
|
+
const value = element.getAttribute(name)
|
|
72
|
+
if (value !== null && value !== '') attrs[name] = value
|
|
73
|
+
}
|
|
74
|
+
// The resolved address, not the attribute as written, which may be relative.
|
|
75
|
+
if (element instanceof view.HTMLAnchorElement && element.hasAttribute('href') && element.href) {
|
|
76
|
+
attrs.href = element.href
|
|
77
|
+
}
|
|
78
|
+
return attrs
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function readStyle(style: CSSStyleDeclaration): Record<string, string> {
|
|
82
|
+
const computed: Record<string, string> = {}
|
|
83
|
+
for (const property of CAPTURED_STYLE_PROPERTIES) {
|
|
84
|
+
const value = style.getPropertyValue(property)
|
|
85
|
+
if (value) computed[property] = value
|
|
86
|
+
}
|
|
87
|
+
// A hidden box keeps its room but draws nothing, as a transparent layer does.
|
|
88
|
+
const visibility = style.getPropertyValue('visibility')
|
|
89
|
+
if (visibility === 'hidden' || visibility === 'collapse') computed.opacity = '0'
|
|
90
|
+
return withoutImpliedValues(computed)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function hasDirectText(element: Element): boolean {
|
|
94
|
+
return [...element.childNodes].some(
|
|
95
|
+
(child) => child.nodeType === 3 && (child.textContent ?? '').trim().length > 0
|
|
96
|
+
)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The nodes an element draws: its shadow tree with slots filled when it has an open one. */
|
|
100
|
+
function renderedChildren(element: Element, view: CaptureWindow): Node[] {
|
|
101
|
+
const source = element.shadowRoot ? element.shadowRoot.childNodes : element.childNodes
|
|
102
|
+
return [...source].flatMap((child) => {
|
|
103
|
+
if (child instanceof view.HTMLSlotElement) {
|
|
104
|
+
const assigned = child.assignedNodes({ flatten: true })
|
|
105
|
+
return assigned.length > 0 ? assigned : [...child.childNodes]
|
|
106
|
+
}
|
|
107
|
+
return [child]
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function controlText(element: Element, view: CaptureWindow): string | null {
|
|
112
|
+
if (element instanceof view.HTMLTextAreaElement) {
|
|
113
|
+
return element.value || element.placeholder || null
|
|
114
|
+
}
|
|
115
|
+
if (element instanceof view.HTMLSelectElement) {
|
|
116
|
+
return element.selectedOptions.item(0)?.text ?? null
|
|
117
|
+
}
|
|
118
|
+
if (element instanceof view.HTMLInputElement) {
|
|
119
|
+
if (!TEXT_INPUT_TYPES.has(element.type)) {
|
|
120
|
+
return element.type === 'button' || element.type === 'submit' ? element.value : null
|
|
121
|
+
}
|
|
122
|
+
if (element.type === 'password' && element.value) return '•'.repeat(element.value.length)
|
|
123
|
+
return element.value || element.placeholder || null
|
|
124
|
+
}
|
|
125
|
+
return null
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Reads an image in the background and writes it as the element's source. */
|
|
129
|
+
function inlineSource(
|
|
130
|
+
context: WalkContext,
|
|
131
|
+
node: WebCaptureElement,
|
|
132
|
+
read: () => Promise<string | null>
|
|
133
|
+
): void {
|
|
134
|
+
context.pending.push(
|
|
135
|
+
read().then((source) => {
|
|
136
|
+
if (source) node.attrs.src = source
|
|
137
|
+
return undefined
|
|
138
|
+
})
|
|
139
|
+
)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function imageSize(box: WebCaptureBox) {
|
|
143
|
+
return { width: Math.round(box.width), height: Math.round(box.height) }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** What a canvas shows, or null when it drew another site's image, which taints it. */
|
|
147
|
+
function canvasDataURL(canvas: HTMLCanvasElement): string | null {
|
|
148
|
+
try {
|
|
149
|
+
return canvas.toDataURL('image/png')
|
|
150
|
+
} catch {
|
|
151
|
+
return null
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function captureReplaced(element: Element, node: WebCaptureElement, context: WalkContext): boolean {
|
|
156
|
+
const { view } = context
|
|
157
|
+
const box = node.box ?? { x: 0, y: 0, width: 0, height: 0 }
|
|
158
|
+
if (element instanceof view.SVGSVGElement) {
|
|
159
|
+
node.tagName = 'img'
|
|
160
|
+
if (box.width > 0 && box.height > 0) {
|
|
161
|
+
const markup = standaloneSVGMarkup(view, element, imageSize(box))
|
|
162
|
+
inlineSource(context, node, () => context.images.rasterizeSVG(markup, imageSize(box)))
|
|
163
|
+
}
|
|
164
|
+
return true
|
|
165
|
+
}
|
|
166
|
+
if (element instanceof view.HTMLImageElement) {
|
|
167
|
+
const source = element.currentSrc || element.src
|
|
168
|
+
if (source) {
|
|
169
|
+
// The address stays when the image cannot be inlined; the importer records it.
|
|
170
|
+
node.attrs.src = source
|
|
171
|
+
inlineSource(context, node, () => context.images.inline(source, imageSize(box)))
|
|
172
|
+
}
|
|
173
|
+
return true
|
|
174
|
+
}
|
|
175
|
+
if (element instanceof view.HTMLCanvasElement) {
|
|
176
|
+
node.tagName = 'img'
|
|
177
|
+
const drawn = canvasDataURL(element)
|
|
178
|
+
const source = drawn && context.images.accept(drawn)
|
|
179
|
+
if (source) node.attrs.src = source
|
|
180
|
+
return true
|
|
181
|
+
}
|
|
182
|
+
if (element instanceof view.HTMLVideoElement) {
|
|
183
|
+
node.tagName = 'img'
|
|
184
|
+
const poster = element.poster
|
|
185
|
+
if (poster) inlineSource(context, node, () => context.images.inline(poster, imageSize(box)))
|
|
186
|
+
return true
|
|
187
|
+
}
|
|
188
|
+
const text = controlText(element, view)
|
|
189
|
+
if (text !== null) {
|
|
190
|
+
node.children = [{ type: 'text', text }]
|
|
191
|
+
return true
|
|
192
|
+
}
|
|
193
|
+
return false
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* A background image becomes an image: the element itself when it holds nothing else, or an
|
|
198
|
+
* image layer behind its content otherwise, since layers have no background images.
|
|
199
|
+
*/
|
|
200
|
+
function captureBackground(
|
|
201
|
+
style: CSSStyleDeclaration,
|
|
202
|
+
node: WebCaptureElement,
|
|
203
|
+
context: WalkContext
|
|
204
|
+
) {
|
|
205
|
+
const match = BACKGROUND_URL.exec(style.getPropertyValue('background-image'))
|
|
206
|
+
const url = match?.[2]
|
|
207
|
+
const box = node.box
|
|
208
|
+
if (!url || !box || box.width <= 0 || box.height <= 0) return
|
|
209
|
+
const fit = style.getPropertyValue('background-size') === 'contain' ? 'contain' : 'cover'
|
|
210
|
+
if (node.tagName !== 'img' && node.children.length === 0) {
|
|
211
|
+
node.tagName = 'img'
|
|
212
|
+
node.computedStyle['object-fit'] = fit
|
|
213
|
+
inlineSource(context, node, () => context.images.inline(url))
|
|
214
|
+
return
|
|
215
|
+
}
|
|
216
|
+
if (node.tagName === 'img') return
|
|
217
|
+
const radii = Object.fromEntries(
|
|
218
|
+
Object.entries(node.computedStyle).filter(([property]) => property.endsWith('-radius'))
|
|
219
|
+
)
|
|
220
|
+
const image: WebCaptureElement = {
|
|
221
|
+
type: 'element',
|
|
222
|
+
tagName: 'img',
|
|
223
|
+
attrs: {},
|
|
224
|
+
computedStyle: {
|
|
225
|
+
...radii,
|
|
226
|
+
display: 'block',
|
|
227
|
+
position: 'absolute',
|
|
228
|
+
left: '0px',
|
|
229
|
+
top: '0px',
|
|
230
|
+
width: `${box.width}px`,
|
|
231
|
+
height: `${box.height}px`,
|
|
232
|
+
'object-fit': fit
|
|
233
|
+
},
|
|
234
|
+
box,
|
|
235
|
+
children: []
|
|
236
|
+
}
|
|
237
|
+
inlineSource(context, image, () => context.images.inline(url))
|
|
238
|
+
node.children.unshift(image)
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function captureChildren(element: Element, context: WalkContext, depth: number): WebCaptureNode[] {
|
|
242
|
+
return renderedChildren(element, context.view).flatMap((child) => {
|
|
243
|
+
if (child.nodeType === 3) {
|
|
244
|
+
const text = child.textContent ?? ''
|
|
245
|
+
return text.length > 0 ? [{ type: 'text' as const, text }] : []
|
|
246
|
+
}
|
|
247
|
+
return child instanceof context.view.Element ? walkElement(child, context, depth + 1) : []
|
|
248
|
+
})
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* The element as a capture holds it, with its descendants; several nodes when it has no box
|
|
253
|
+
* of its own (`display: contents`) and none when it is not displayed.
|
|
254
|
+
*/
|
|
255
|
+
export function walkElement(element: Element, context: WalkContext, depth = 0): WebCaptureNode[] {
|
|
256
|
+
const tagName = element.localName.toLowerCase()
|
|
257
|
+
if (SKIPPED_TAGS.has(tagName)) return []
|
|
258
|
+
const style = context.view.getComputedStyle(element)
|
|
259
|
+
const display = style.getPropertyValue('display')
|
|
260
|
+
if (display === 'none') return []
|
|
261
|
+
if (display === 'contents') return captureChildren(element, context, depth)
|
|
262
|
+
if (depth > MAX_CAPTURE_DEPTH || context.elements >= context.maxElements) {
|
|
263
|
+
context.truncated = true
|
|
264
|
+
return []
|
|
265
|
+
}
|
|
266
|
+
context.elements++
|
|
267
|
+
const node: WebCaptureElement = {
|
|
268
|
+
type: 'element',
|
|
269
|
+
tagName,
|
|
270
|
+
attrs: attributesOf(element, context.view),
|
|
271
|
+
computedStyle: readStyle(style),
|
|
272
|
+
box: boxOf(element, context.origin),
|
|
273
|
+
children: []
|
|
274
|
+
}
|
|
275
|
+
if (!captureReplaced(element, node, context)) {
|
|
276
|
+
node.children = captureChildren(element, context, depth)
|
|
277
|
+
}
|
|
278
|
+
if (hasDirectText(element) || node.children.some((child) => child.type === 'text')) {
|
|
279
|
+
context.fonts.add(style)
|
|
280
|
+
}
|
|
281
|
+
captureBackground(style, node, context)
|
|
282
|
+
return [node]
|
|
283
|
+
}
|
package/src/clipboard.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { compact } from 'es-toolkit'
|
|
2
|
+
import { Inflate, deflateSync, strToU8 } from 'fflate'
|
|
3
|
+
import { fromUint8Array, isValid, toUint8Array } from 'js-base64'
|
|
4
|
+
|
|
5
|
+
import type { WebCapture, WebCaptureReadResult } from './format'
|
|
6
|
+
import { webCaptureToHTML } from './html'
|
|
7
|
+
import { MAX_CAPTURE_JSON_LENGTH } from './limits'
|
|
8
|
+
import { normalizeWebCapture, parseWebCapture } from './parse'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Clipboard HTML carries a capture between these markers, as Base64 of the DEFLATE-compressed
|
|
12
|
+
* JSON, the way Figma and Pairdraw carry their layers in an HTML comment.
|
|
13
|
+
*/
|
|
14
|
+
export const WEB_CAPTURE_CLIPBOARD_START = '<!--(pairdraw-web-capture)'
|
|
15
|
+
export const WEB_CAPTURE_CLIPBOARD_END = '(/pairdraw-web-capture)-->'
|
|
16
|
+
|
|
17
|
+
/** Compressed bytes inflated per step, so an oversized payload stops early. */
|
|
18
|
+
const INFLATE_STEP = 16 * 1024
|
|
19
|
+
|
|
20
|
+
export interface WebCaptureClipboardPayload {
|
|
21
|
+
/** The capture in markers, followed by its content as styled HTML for other applications. */
|
|
22
|
+
html: string
|
|
23
|
+
/** The page's title and address, for applications that only read text. */
|
|
24
|
+
text: string
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** What the clipboard holds after copying a capture: the capture itself and a readable copy. */
|
|
28
|
+
export function encodeWebCaptureClipboard(captured: WebCapture): WebCaptureClipboardPayload {
|
|
29
|
+
const capture = normalizeWebCapture(captured)
|
|
30
|
+
const compressed = deflateSync(strToU8(JSON.stringify(capture)), { level: 6 })
|
|
31
|
+
const marker = `${WEB_CAPTURE_CLIPBOARD_START}${fromUint8Array(compressed)}${WEB_CAPTURE_CLIPBOARD_END}`
|
|
32
|
+
const html = `<meta charset="utf-8">${marker}${webCaptureToHTML(capture, { images: false })}`
|
|
33
|
+
const text = compact([capture.source.title, capture.source.url]).join('\n')
|
|
34
|
+
return { html, text }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function markedPayload(html: string): string | null {
|
|
38
|
+
const start = html.indexOf(WEB_CAPTURE_CLIPBOARD_START)
|
|
39
|
+
if (start === -1) return null
|
|
40
|
+
const from = start + WEB_CAPTURE_CLIPBOARD_START.length
|
|
41
|
+
const end = html.indexOf(WEB_CAPTURE_CLIPBOARD_END, from)
|
|
42
|
+
return end === -1 ? null : html.slice(from, end)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Whether clipboard HTML holds a complete capture marker. */
|
|
46
|
+
export function hasWebCaptureClipboardMarker(html: string): boolean {
|
|
47
|
+
return markedPayload(html) !== null
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Inflates at most `MAX_CAPTURE_JSON_LENGTH` bytes of text. */
|
|
51
|
+
function inflateText(bytes: Uint8Array): { text: string } | 'invalid' | 'too-large' {
|
|
52
|
+
const decoder = new TextDecoder()
|
|
53
|
+
// An object, since the inflate callback changes it where control flow analysis cannot see.
|
|
54
|
+
const state = { text: '', length: 0, overflow: false }
|
|
55
|
+
const inflate = new Inflate((chunk) => {
|
|
56
|
+
state.length += chunk.length
|
|
57
|
+
if (state.length > MAX_CAPTURE_JSON_LENGTH) state.overflow = true
|
|
58
|
+
else state.text += decoder.decode(chunk, { stream: true })
|
|
59
|
+
})
|
|
60
|
+
try {
|
|
61
|
+
for (let offset = 0; offset < bytes.length; offset += INFLATE_STEP) {
|
|
62
|
+
if (state.overflow) break
|
|
63
|
+
const end = offset + INFLATE_STEP
|
|
64
|
+
inflate.push(bytes.subarray(offset, end), end >= bytes.length)
|
|
65
|
+
}
|
|
66
|
+
} catch {
|
|
67
|
+
return 'invalid'
|
|
68
|
+
}
|
|
69
|
+
return state.overflow ? 'too-large' : { text: state.text + decoder.decode() }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The capture clipboard HTML holds, or null when it holds none. Clipboard HTML is writable by
|
|
74
|
+
* any page, so the payload is size-limited, validated, and normalized before it is returned.
|
|
75
|
+
*/
|
|
76
|
+
export function readWebCaptureClipboard(html: string): WebCaptureReadResult | null {
|
|
77
|
+
const payload = markedPayload(html)
|
|
78
|
+
if (payload === null) return null
|
|
79
|
+
const encoded = payload.trim()
|
|
80
|
+
if (encoded.length > MAX_CAPTURE_JSON_LENGTH) return { ok: false, error: 'too-large' }
|
|
81
|
+
if (!isValid(encoded)) return { ok: false, error: 'invalid' }
|
|
82
|
+
const inflated = inflateText(toUint8Array(encoded))
|
|
83
|
+
if (typeof inflated === 'string') return { ok: false, error: inflated }
|
|
84
|
+
return parseWebCapture(inflated.text)
|
|
85
|
+
}
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
import { omit } from 'es-toolkit'
|
|
2
|
+
|
|
3
|
+
import type { WebCapture } from './format'
|
|
4
|
+
import { ownValue } from './record'
|
|
5
|
+
import type { WebCaptureBox, WebCaptureElement, WebCaptureNode, WebCaptureText } from './types'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* An element of the styled DOM `@pairdraw/dom-css` builds layers from. The shape matches its
|
|
9
|
+
* `DesignElement`, so a capture imports through `sceneGraphFromStyledHTML` without a CSS runtime.
|
|
10
|
+
*/
|
|
11
|
+
export interface WebCaptureDesignElement {
|
|
12
|
+
type: 'element'
|
|
13
|
+
tagName: string
|
|
14
|
+
attrs: Record<string, string>
|
|
15
|
+
computedStyle: Record<string, string>
|
|
16
|
+
children: WebCaptureDesignNode[]
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type WebCaptureDesignNode = WebCaptureDesignElement | WebCaptureText
|
|
20
|
+
|
|
21
|
+
/** The styled DOM of a capture, matching `@pairdraw/dom-css`'s `DesignDocument`. */
|
|
22
|
+
export interface WebCaptureDesignDocument {
|
|
23
|
+
type: 'document'
|
|
24
|
+
children: WebCaptureDesignNode[]
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const SIDES = ['top', 'right', 'bottom', 'left'] as const
|
|
28
|
+
type Side = (typeof SIDES)[number]
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Displays the importer has no layout for, mapped to the closest one it has. A grid of
|
|
32
|
+
* fixed-size cells wraps as a row of them does, and a table row is a row of its cells.
|
|
33
|
+
*/
|
|
34
|
+
const DISPLAY_FALLBACKS: Record<string, Record<string, string>> = {
|
|
35
|
+
grid: { display: 'flex', 'flex-direction': 'row', 'flex-wrap': 'wrap' },
|
|
36
|
+
'inline-grid': { display: 'inline-flex', 'flex-direction': 'row', 'flex-wrap': 'wrap' },
|
|
37
|
+
'table-row': { display: 'flex', 'flex-direction': 'row', 'flex-wrap': 'nowrap' },
|
|
38
|
+
table: { display: 'block' },
|
|
39
|
+
'inline-table': { display: 'inline-block' },
|
|
40
|
+
'table-row-group': { display: 'block' },
|
|
41
|
+
'table-header-group': { display: 'block' },
|
|
42
|
+
'table-footer-group': { display: 'block' },
|
|
43
|
+
'table-cell': { display: 'block' },
|
|
44
|
+
'table-caption': { display: 'block' },
|
|
45
|
+
'list-item': { display: 'block' },
|
|
46
|
+
'flow-root': { display: 'block' }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Inline text tags the importer lays out inline when they say nothing of their display. Left
|
|
51
|
+
* without one, a run such as a link or a bold word stays text instead of a box around text.
|
|
52
|
+
*/
|
|
53
|
+
const INLINE_TEXT_TAGS = new Set(['a', 'b', 'code', 'em', 'i', 'small', 'span', 'strong', 'u'])
|
|
54
|
+
|
|
55
|
+
function pixels(value: string | undefined): number {
|
|
56
|
+
if (!value?.endsWith('px')) return 0
|
|
57
|
+
const parsed = Number.parseFloat(value)
|
|
58
|
+
return Number.isFinite(parsed) ? parsed : 0
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function px(value: number): string {
|
|
62
|
+
return `${Math.round(value * 100) / 100}px`
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const MARGINS = SIDES.map((side) => `margin-${side}` as const)
|
|
66
|
+
|
|
67
|
+
/** The element's margins in pixels, and its style without them. */
|
|
68
|
+
function splitMargins(style: Record<string, string>) {
|
|
69
|
+
const margins = { top: 0, right: 0, bottom: 0, left: 0 }
|
|
70
|
+
for (const side of SIDES) margins[side] = pixels(style[`margin-${side}`])
|
|
71
|
+
return { margins, style: omit(style, MARGINS) }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function isAbsolute(style: Record<string, string>): boolean {
|
|
75
|
+
return style.position === 'absolute' || style.position === 'fixed'
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function isInline(style: Record<string, string>): boolean {
|
|
79
|
+
return (ownValue(style, 'display') ?? '').startsWith('inline')
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Places an absolute box in its parent layer. CSS measures `left` and `top` from the containing
|
|
84
|
+
* block, which may be a further ancestor or the viewport, so the recorded boxes place it where
|
|
85
|
+
* the page drew it. Without them, it sits at its offset plus its margin, as CSS places it.
|
|
86
|
+
*/
|
|
87
|
+
function placeAbsolute(
|
|
88
|
+
style: Record<string, string>,
|
|
89
|
+
margins: Record<Side, number>,
|
|
90
|
+
box: WebCaptureBox | undefined,
|
|
91
|
+
parentBox: WebCaptureBox | undefined
|
|
92
|
+
): void {
|
|
93
|
+
if (box && parentBox) {
|
|
94
|
+
style.left = px(box.x - parentBox.x)
|
|
95
|
+
style.top = px(box.y - parentBox.y)
|
|
96
|
+
return
|
|
97
|
+
}
|
|
98
|
+
if (ownValue(style, 'left') !== undefined) style.left = px(pixels(style.left) + margins.left)
|
|
99
|
+
if (ownValue(style, 'top') !== undefined) style.top = px(pixels(style.top) + margins.top)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* A box in normal flow keeps the room its margins took inside a transparent box padded by them.
|
|
104
|
+
* Negative margins, which pull neighbours over each other, are dropped.
|
|
105
|
+
*/
|
|
106
|
+
function marginBox(
|
|
107
|
+
element: WebCaptureDesignElement,
|
|
108
|
+
margins: Record<Side, number>
|
|
109
|
+
): WebCaptureDesignElement {
|
|
110
|
+
const style: Record<string, string> = { display: 'block' }
|
|
111
|
+
for (const side of SIDES) {
|
|
112
|
+
if (margins[side] > 0) style[`padding-${side}`] = px(margins[side])
|
|
113
|
+
}
|
|
114
|
+
const alignSelf = ownValue(element.computedStyle, 'align-self')
|
|
115
|
+
if (alignSelf === undefined) {
|
|
116
|
+
return { type: 'element', tagName: 'div', attrs: {}, computedStyle: style, children: [element] }
|
|
117
|
+
}
|
|
118
|
+
// The box is the flex item now, so it aligns itself as the element did.
|
|
119
|
+
style['align-self'] = alignSelf
|
|
120
|
+
const child = { ...element, computedStyle: omit(element.computedStyle, ['align-self']) }
|
|
121
|
+
return { type: 'element', tagName: 'div', attrs: {}, computedStyle: style, children: [child] }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function convertChildren(
|
|
125
|
+
children: readonly WebCaptureNode[],
|
|
126
|
+
parentBox: WebCaptureBox | undefined
|
|
127
|
+
): WebCaptureDesignNode[] {
|
|
128
|
+
return children.map((child): WebCaptureDesignNode =>
|
|
129
|
+
child.type === 'text' ? child : convertElement(child, parentBox)
|
|
130
|
+
)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const GRID_DISPLAYS = new Set(['grid', 'inline-grid'])
|
|
134
|
+
|
|
135
|
+
type BoxedElement = WebCaptureElement & { box: WebCaptureBox }
|
|
136
|
+
|
|
137
|
+
function hasBox(element: WebCaptureElement): element is BoxedElement {
|
|
138
|
+
return element.box !== undefined
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* A grid whose items can stay where the page drew them: the capture recorded the grid's box and
|
|
143
|
+
* every item's, and the grid holds no loose text. Null otherwise, and for anything but a grid.
|
|
144
|
+
*/
|
|
145
|
+
function placeableGrid(
|
|
146
|
+
element: WebCaptureElement
|
|
147
|
+
): { box: WebCaptureBox; items: BoxedElement[] } | null {
|
|
148
|
+
if (!GRID_DISPLAYS.has(ownValue(element.computedStyle, 'display') ?? '') || !hasBox(element)) {
|
|
149
|
+
return null
|
|
150
|
+
}
|
|
151
|
+
const items: BoxedElement[] = []
|
|
152
|
+
for (const child of element.children) {
|
|
153
|
+
if (child.type === 'text') {
|
|
154
|
+
if (child.text.trim().length > 0) return null
|
|
155
|
+
} else if (hasBox(child)) {
|
|
156
|
+
items.push(child)
|
|
157
|
+
} else {
|
|
158
|
+
return null
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return { box: element.box, items }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Auto layout has no grid tracks, so a grid keeps its drawn size and its items become absolute
|
|
166
|
+
* boxes where the page drew them. Their margins already moved their boxes.
|
|
167
|
+
*/
|
|
168
|
+
function gridStyle(style: Record<string, string>, box: WebCaptureBox): Record<string, string> {
|
|
169
|
+
return {
|
|
170
|
+
...omit(style, ['gap', 'row-gap', 'column-gap']),
|
|
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
|
+
|
|
178
|
+
const PLACEMENT = [...MARGINS, 'position', ...SIDES]
|
|
179
|
+
|
|
180
|
+
function placeGridItem(item: BoxedElement, grid: WebCaptureBox): WebCaptureDesignElement {
|
|
181
|
+
// Without margins or a position of its own, the item converts to itself, not a margin box.
|
|
182
|
+
const converted = convertElement({ ...item, computedStyle: omit(item.computedStyle, PLACEMENT) })
|
|
183
|
+
converted.computedStyle = {
|
|
184
|
+
...converted.computedStyle,
|
|
185
|
+
position: 'absolute',
|
|
186
|
+
left: px(item.box.x - grid.x),
|
|
187
|
+
top: px(item.box.y - grid.y),
|
|
188
|
+
width: px(item.box.width),
|
|
189
|
+
height: px(item.box.height),
|
|
190
|
+
'box-sizing': 'border-box'
|
|
191
|
+
}
|
|
192
|
+
return converted
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* The style an element is laid out with, the closest display the importer has standing in for
|
|
197
|
+
* one it lacks, and its converted children.
|
|
198
|
+
*/
|
|
199
|
+
function layoutOf(element: WebCaptureElement) {
|
|
200
|
+
const grid = placeableGrid(element)
|
|
201
|
+
if (grid) {
|
|
202
|
+
return {
|
|
203
|
+
displayed: gridStyle(element.computedStyle, grid.box),
|
|
204
|
+
children: grid.items.map((item) => placeGridItem(item, grid.box))
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const display = ownValue(element.computedStyle, 'display') ?? ''
|
|
208
|
+
return {
|
|
209
|
+
displayed: { ...element.computedStyle, ...DISPLAY_FALLBACKS[display] },
|
|
210
|
+
children: convertChildren(element.children, element.box)
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function convertElement(
|
|
215
|
+
element: WebCaptureElement,
|
|
216
|
+
parentBox?: WebCaptureBox
|
|
217
|
+
): WebCaptureDesignElement {
|
|
218
|
+
const { displayed, children } = layoutOf(element)
|
|
219
|
+
const inline = isInline(displayed)
|
|
220
|
+
const split = splitMargins(displayed)
|
|
221
|
+
const { margins } = split
|
|
222
|
+
const style =
|
|
223
|
+
displayed.display === 'inline' && INLINE_TEXT_TAGS.has(element.tagName)
|
|
224
|
+
? omit(split.style, ['display'])
|
|
225
|
+
: split.style
|
|
226
|
+
const converted: WebCaptureDesignElement = {
|
|
227
|
+
type: 'element',
|
|
228
|
+
tagName: element.tagName,
|
|
229
|
+
attrs: { ...element.attrs },
|
|
230
|
+
computedStyle: style,
|
|
231
|
+
children
|
|
232
|
+
}
|
|
233
|
+
if (isAbsolute(style)) {
|
|
234
|
+
placeAbsolute(style, margins, element.box, parentBox)
|
|
235
|
+
return converted
|
|
236
|
+
}
|
|
237
|
+
const spaced = SIDES.some((side) => margins[side] > 0)
|
|
238
|
+
return spaced && !inline ? marginBox(converted, margins) : converted
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* The capture as the styled DOM layers are built from. The root keeps the size it had on the
|
|
243
|
+
* page and drops its own position and margins, so it lands where a paste puts it.
|
|
244
|
+
*/
|
|
245
|
+
export function webCaptureDesignDocument(capture: WebCapture): WebCaptureDesignDocument {
|
|
246
|
+
const { root } = capture
|
|
247
|
+
const { displayed, children } = layoutOf(root)
|
|
248
|
+
const style = omit(splitMargins(displayed).style, ['position', ...SIDES])
|
|
249
|
+
// The box a capture records is the border box, padding and borders included.
|
|
250
|
+
if (root.box) {
|
|
251
|
+
style.width = px(root.box.width)
|
|
252
|
+
style.height = px(root.box.height)
|
|
253
|
+
style['box-sizing'] = 'border-box'
|
|
254
|
+
}
|
|
255
|
+
return {
|
|
256
|
+
type: 'document',
|
|
257
|
+
children: [
|
|
258
|
+
{
|
|
259
|
+
type: 'element',
|
|
260
|
+
tagName: root.tagName,
|
|
261
|
+
attrs: { ...root.attrs },
|
|
262
|
+
computedStyle: style,
|
|
263
|
+
children
|
|
264
|
+
}
|
|
265
|
+
]
|
|
266
|
+
}
|
|
267
|
+
}
|
package/src/format.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type * as v from 'valibot'
|
|
2
|
+
|
|
3
|
+
import type { webCaptureFontSchema, webCaptureSchema, webCaptureViewportSchema } from './schema'
|
|
4
|
+
|
|
5
|
+
/** A page or element captured with the styles the browser computed for it. */
|
|
6
|
+
export type WebCapture = v.InferOutput<typeof webCaptureSchema>
|
|
7
|
+
|
|
8
|
+
export type WebCaptureFont = v.InferOutput<typeof webCaptureFontSchema>
|
|
9
|
+
|
|
10
|
+
export type WebCaptureViewport = v.InferOutput<typeof webCaptureViewportSchema>
|
|
11
|
+
|
|
12
|
+
/** Why a capture could not be read. */
|
|
13
|
+
export type WebCaptureReadError = 'invalid' | 'too-large' | 'unsupported-version'
|
|
14
|
+
|
|
15
|
+
export type WebCaptureReadResult =
|
|
16
|
+
| { ok: true; capture: WebCapture }
|
|
17
|
+
| { ok: false; error: WebCaptureReadError }
|
package/src/html.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { escapeAttribute, escapeText } from 'entities'
|
|
2
|
+
|
|
3
|
+
import type { WebCapture } from './format'
|
|
4
|
+
import { ownValue } from './record'
|
|
5
|
+
import type { WebCaptureElement, WebCaptureNode } from './types'
|
|
6
|
+
|
|
7
|
+
const VOID_TAGS = new Set(['area', 'br', 'col', 'hr', 'img', 'input', 'source', 'wbr'])
|
|
8
|
+
|
|
9
|
+
export interface WebCaptureHTMLOptions {
|
|
10
|
+
/** Keep inlined images; without them an image keeps only its size and description. */
|
|
11
|
+
images?: boolean
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function styleAttribute(style: Record<string, string>): string {
|
|
15
|
+
return Object.entries(style)
|
|
16
|
+
.map(([property, value]) => `${property}: ${value}`)
|
|
17
|
+
.join('; ')
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function attributes(element: WebCaptureElement, options: WebCaptureHTMLOptions): string {
|
|
21
|
+
const attrs: Record<string, string> = { ...element.attrs }
|
|
22
|
+
if (options.images === false && ownValue(attrs, 'src')?.startsWith('data:')) delete attrs.src
|
|
23
|
+
const style = styleAttribute(element.computedStyle)
|
|
24
|
+
if (style) attrs.style = style
|
|
25
|
+
return Object.entries(attrs)
|
|
26
|
+
.map(([name, value]) => ` ${name}="${escapeAttribute(value)}"`)
|
|
27
|
+
.join('')
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function serialize(node: WebCaptureNode, options: WebCaptureHTMLOptions): string {
|
|
31
|
+
if (node.type === 'text') return escapeText(node.text)
|
|
32
|
+
const open = `<${node.tagName}${attributes(node, options)}>`
|
|
33
|
+
if (VOID_TAGS.has(node.tagName)) return open
|
|
34
|
+
const children = node.children.map((child) => serialize(child, options)).join('')
|
|
35
|
+
return `${open}${children}</${node.tagName}>`
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The capture as static HTML whose elements carry their computed styles inline, for
|
|
40
|
+
* applications that read clipboard HTML but not the capture itself.
|
|
41
|
+
*/
|
|
42
|
+
export function webCaptureToHTML(capture: WebCapture, options: WebCaptureHTMLOptions = {}): string {
|
|
43
|
+
return serialize(capture.root, options)
|
|
44
|
+
}
|