@pairdraw/web-capture 0.0.0-stage → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/dist/capturer.d.ts +56 -0
  4. package/dist/capturer.d.ts.map +1 -0
  5. package/dist/capturer.js +3 -0
  6. package/dist/chunks/capturer/clipboard.js +575 -0
  7. package/dist/chunks/capturer/clipboard.js.map +1 -0
  8. package/dist/chunks/capturer/fonts.js +25 -0
  9. package/dist/chunks/capturer/fonts.js.map +1 -0
  10. package/dist/chunks/capturer/images.js +113 -0
  11. package/dist/chunks/capturer/images.js.map +1 -0
  12. package/dist/chunks/capturer/index.js +445 -0
  13. package/dist/chunks/capturer/index.js.map +1 -0
  14. package/dist/chunks/design-document.js +251 -0
  15. package/dist/chunks/design-document.js.map +1 -0
  16. package/dist/chunks/index.js +125 -0
  17. package/dist/chunks/index.js.map +1 -0
  18. package/dist/clipboard.d.ts +106 -0
  19. package/dist/clipboard.d.ts.map +1 -0
  20. package/dist/index.d.ts +110 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +4 -0
  23. package/package.json +43 -4
  24. package/src/capturer/clipboard.ts +59 -0
  25. package/src/capturer/fonts.ts +30 -0
  26. package/src/capturer/images.ts +153 -0
  27. package/src/capturer/index.ts +170 -0
  28. package/src/capturer/page.ts +51 -0
  29. package/src/capturer/svg.ts +79 -0
  30. package/src/capturer/walk.ts +283 -0
  31. package/src/clipboard.ts +85 -0
  32. package/src/design-document.ts +267 -0
  33. package/src/format.ts +17 -0
  34. package/src/html.ts +44 -0
  35. package/src/index.ts +41 -0
  36. package/src/limits.ts +23 -0
  37. package/src/parse.ts +165 -0
  38. package/src/record.ts +10 -0
  39. package/src/sanitize.ts +134 -0
  40. package/src/schema.ts +75 -0
  41. package/src/styles.ts +163 -0
  42. package/src/types.ts +28 -0
  43. package/src/urls.ts +27 -0
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ import { CAPTURED_STYLE_PROPERTIES, 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, webCaptureSchema, webCaptureToHTML, withoutImpliedValues } from "./chunks/capturer/clipboard.js";
2
+ import { webCaptureDesignDocument } from "./chunks/design-document.js";
3
+ import { hasWebContent, sanitizeWebHTML } from "./chunks/index.js";
4
+ export { CAPTURED_STYLE_PROPERTIES, 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, hasWebContent, isCapturedStyleProperty, normalizeWebCapture, parseWebCapture, readWebCapture, readWebCaptureClipboard, safeImageSource, safeLinkURL, sanitizeWebHTML, webCaptureDesignDocument, webCaptureSchema, webCaptureToHTML, withoutImpliedValues };
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@pairdraw/web-capture",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.16.0",
4
+ "license": "MIT",
5
+ "files": [
6
+ "dist",
7
+ "src",
8
+ "README.md"
9
+ ],
10
+ "main": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "dependencies": {
13
+ "entities": "^8.0.0",
14
+ "es-toolkit": "^1.52.0",
15
+ "fflate": "^0.8.3",
16
+ "js-base64": "^3.9.3",
17
+ "valibot": "^1.5.0"
18
+ },
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js",
23
+ "default": "./dist/index.js"
24
+ },
25
+ "./capturer": {
26
+ "types": "./dist/capturer.d.ts",
27
+ "import": "./dist/capturer.js",
28
+ "default": "./dist/capturer.js"
29
+ }
30
+ },
31
+ "imports": {
32
+ "#web-capture/*": {
33
+ "types": "./src/*.ts",
34
+ "default": "./dist/*.js"
35
+ },
36
+ "#web-capture-tests/*": "./tests/*.ts"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/BadryansahBangsawan/pairdraw.git",
41
+ "directory": "packages/web-capture"
42
+ },
43
+ "type": "module",
44
+ "sideEffects": false
45
+ }
@@ -0,0 +1,59 @@
1
+ import { encodeWebCaptureClipboard, type WebCaptureClipboardPayload } from '#web-capture/clipboard'
2
+ import type { WebCapture } from '#web-capture/format'
3
+
4
+ /** The part of the asynchronous clipboard a capture write uses. */
5
+ export type CaptureClipboard = Pick<Clipboard, 'write'>
6
+
7
+ export interface WriteCaptureClipboardOptions {
8
+ /** The clipboard to write; the page's own by default. */
9
+ clipboard?: CaptureClipboard
10
+ /** Builds a clipboard item; the page's `ClipboardItem` by default. */
11
+ createItem?: (items: Record<string, Promise<Blob>>) => ClipboardItem
12
+ }
13
+
14
+ /** Thrown when the page has no asynchronous clipboard, which only secure pages offer. */
15
+ export class CaptureClipboardUnavailableError extends Error {
16
+ constructor() {
17
+ super('Copying a capture needs a page served over HTTPS')
18
+ this.name = 'CaptureClipboardUnavailableError'
19
+ }
20
+ }
21
+
22
+ function isPayload(
23
+ value: WebCapture | WebCaptureClipboardPayload
24
+ ): value is WebCaptureClipboardPayload {
25
+ return 'html' in value && 'text' in value
26
+ }
27
+
28
+ /**
29
+ * Copies a capture so it pastes into a Pairdraw canvas, as HTML for Pairdraw and other
30
+ * applications and as the page's title and address for plain text. Pass the capture's promise
31
+ * straight from the click that asked for it: the write starts inside that click and resolves
32
+ * its data later, so a capture that takes a while still counts as the click's own.
33
+ */
34
+ export async function writeWebCaptureClipboard(
35
+ capture:
36
+ | WebCapture
37
+ | WebCaptureClipboardPayload
38
+ | Promise<WebCapture | WebCaptureClipboardPayload>,
39
+ options: WriteCaptureClipboardOptions = {}
40
+ ): Promise<void> {
41
+ const clipboard =
42
+ options.clipboard ?? (typeof navigator === 'undefined' ? undefined : navigator.clipboard)
43
+ const createItem =
44
+ options.createItem ??
45
+ (typeof ClipboardItem === 'undefined'
46
+ ? undefined
47
+ : (items: Record<string, Promise<Blob>>) => new ClipboardItem(items))
48
+ // `navigator.clipboard` is missing outside secure contexts.
49
+ if (!clipboard || !createItem) throw new CaptureClipboardUnavailableError()
50
+ const payload = Promise.resolve(capture).then((value) =>
51
+ isPayload(value) ? value : encodeWebCaptureClipboard(value)
52
+ )
53
+ await clipboard.write([
54
+ createItem({
55
+ 'text/html': payload.then((value) => new Blob([value.html], { type: 'text/html' })),
56
+ 'text/plain': payload.then((value) => new Blob([value.text], { type: 'text/plain' }))
57
+ })
58
+ ])
59
+ }
@@ -0,0 +1,30 @@
1
+ import type { WebCaptureFont } from '#web-capture/format'
2
+
3
+ /** The fonts a capture's text uses, so an importer knows which families to load. */
4
+ export interface FontCollector {
5
+ add(style: CSSStyleDeclaration): void
6
+ list(): WebCaptureFont[]
7
+ }
8
+
9
+ /** The family a browser tries first, without the quotes CSS may put around it. */
10
+ function primaryFontFamily(fontFamily: string): string {
11
+ const first = fontFamily.split(',')[0] ?? ''
12
+ return first.trim().replace(/^(['"])(.*)\1$/, '$2')
13
+ }
14
+
15
+ export function createFontCollector(): FontCollector {
16
+ const fonts = new Map<string, WebCaptureFont>()
17
+ return {
18
+ add(style) {
19
+ const family = primaryFontFamily(style.getPropertyValue('font-family'))
20
+ if (!family) return
21
+ const font = {
22
+ family,
23
+ weight: style.getPropertyValue('font-weight') || '400',
24
+ style: style.getPropertyValue('font-style') || 'normal'
25
+ }
26
+ fonts.set(`${font.family}|${font.weight}|${font.style}`, font)
27
+ },
28
+ list: () => [...fonts.values()]
29
+ }
30
+ }
@@ -0,0 +1,153 @@
1
+ import { MAX_CAPTURE_IMAGE_BYTES, MAX_CAPTURE_IMAGES_BYTES } from '#web-capture/limits'
2
+ import { fromUint8Array } from 'js-base64'
3
+
4
+ /**
5
+ * Fetches an image the page itself may not read, such as one from another site without CORS
6
+ * headers. An extension passes one that fetches with its own host permission.
7
+ */
8
+ export type CaptureImageFetcher = (url: string) => Promise<Blob | null>
9
+
10
+ /** The page's window, whose constructors and network the capturer uses. */
11
+ export type CaptureWindow = Window & typeof globalThis
12
+
13
+ export interface ImageInlinerOptions {
14
+ fetchImage?: CaptureImageFetcher
15
+ maxImageBytes?: number
16
+ maxTotalBytes?: number
17
+ signal?: AbortSignal
18
+ }
19
+
20
+ export interface ImageSize {
21
+ width: number
22
+ height: number
23
+ }
24
+
25
+ /** Turns page images into raster data URLs, the only images a capture carries inside it. */
26
+ export interface ImageInliner {
27
+ /** The image at `url` as a raster data URL, or null when it cannot be read or is too large. */
28
+ inline(url: string, size?: ImageSize): Promise<string | null>
29
+ /** SVG markup drawn at `size`, as a PNG data URL. */
30
+ rasterizeSVG(markup: string, size: ImageSize): Promise<string | null>
31
+ /** A data URL a page already produced, such as a canvas's, if the budget still allows it. */
32
+ accept(dataURL: string): string | null
33
+ }
34
+
35
+ const RASTER_TYPES = new Set([
36
+ 'image/png',
37
+ 'image/jpeg',
38
+ 'image/gif',
39
+ 'image/webp',
40
+ 'image/avif',
41
+ 'image/bmp',
42
+ 'image/x-icon',
43
+ 'image/vnd.microsoft.icon'
44
+ ])
45
+
46
+ /** Larger scales add bytes but no detail a design layer can use. */
47
+ const MAX_RASTER_SCALE = 2
48
+ /** Images fetched at once, so a long page does not flood the network. */
49
+ const CONCURRENT_FETCHES = 6
50
+
51
+ function createLimiter(limit: number) {
52
+ let active = 0
53
+ const waiting: Array<() => void> = []
54
+ return async <T>(task: () => Promise<T>): Promise<T> => {
55
+ if (active >= limit) {
56
+ await new Promise<void>((resolve) => {
57
+ waiting.push(resolve)
58
+ })
59
+ }
60
+ active++
61
+ try {
62
+ return await task()
63
+ } finally {
64
+ active--
65
+ waiting.shift()?.()
66
+ }
67
+ }
68
+ }
69
+
70
+ export function createImageInliner(
71
+ view: CaptureWindow,
72
+ options: ImageInlinerOptions = {}
73
+ ): ImageInliner {
74
+ const maxImageBytes = options.maxImageBytes ?? MAX_CAPTURE_IMAGE_BYTES
75
+ const maxTotalBytes = options.maxTotalBytes ?? MAX_CAPTURE_IMAGES_BYTES
76
+ const cache = new Map<string, Promise<string | null>>()
77
+ const limit = createLimiter(CONCURRENT_FETCHES)
78
+ let totalBytes = 0
79
+
80
+ /** Counts an image against the capture's budget; false when it does not fit. */
81
+ function reserve(bytes: number): boolean {
82
+ if (bytes > maxImageBytes || totalBytes + bytes > maxTotalBytes) return false
83
+ totalBytes += bytes
84
+ return true
85
+ }
86
+
87
+ function accept(dataURL: string): string | null {
88
+ // Base64 holds three bytes in four characters.
89
+ return reserve(Math.ceil((dataURL.length * 3) / 4)) ? dataURL : null
90
+ }
91
+
92
+ async function rasterize(blob: Blob, size?: ImageSize): Promise<string | null> {
93
+ const url = view.URL.createObjectURL(blob)
94
+ try {
95
+ const image = new view.Image()
96
+ image.src = url
97
+ await image.decode()
98
+ const width = size?.width || image.naturalWidth
99
+ const height = size?.height || image.naturalHeight
100
+ if (!width || !height) return null
101
+ const scale = Math.min(view.devicePixelRatio || 1, MAX_RASTER_SCALE)
102
+ const canvas = view.document.createElement('canvas')
103
+ canvas.width = Math.max(1, Math.round(width * scale))
104
+ canvas.height = Math.max(1, Math.round(height * scale))
105
+ const context = canvas.getContext('2d')
106
+ if (!context) return null
107
+ context.drawImage(image, 0, 0, canvas.width, canvas.height)
108
+ return accept(canvas.toDataURL('image/png'))
109
+ } catch {
110
+ return null
111
+ } finally {
112
+ view.URL.revokeObjectURL(url)
113
+ }
114
+ }
115
+
116
+ async function fromBlob(blob: Blob, size?: ImageSize): Promise<string | null> {
117
+ if (blob.size > maxImageBytes) return null
118
+ const type = blob.type.toLowerCase()
119
+ if (!RASTER_TYPES.has(type)) return rasterize(blob, size)
120
+ const bytes = new Uint8Array(await blob.arrayBuffer())
121
+ if (!reserve(bytes.length)) return null
122
+ return `data:${type};base64,${fromUint8Array(bytes)}`
123
+ }
124
+
125
+ async function fetchBlob(url: string): Promise<Blob | null> {
126
+ // Another site's image without CORS headers fails here; the injected fetcher may read it.
127
+ const response = await view
128
+ .fetch(url, { credentials: 'same-origin', signal: options.signal })
129
+ .catch(() => null)
130
+ if (response?.ok) return response.blob()
131
+ if (!options.fetchImage || url.startsWith('data:')) return null
132
+ return options.fetchImage(url).catch(() => null)
133
+ }
134
+
135
+ function inline(url: string, size?: ImageSize): Promise<string | null> {
136
+ const key = size ? `${url}#${size.width}x${size.height}` : url
137
+ const cached = cache.get(key)
138
+ if (cached) return cached
139
+ const task = limit(async () => {
140
+ options.signal?.throwIfAborted()
141
+ const blob = await fetchBlob(url)
142
+ return blob ? fromBlob(blob, size) : null
143
+ }).catch(() => null)
144
+ cache.set(key, task)
145
+ return task
146
+ }
147
+
148
+ function rasterizeSVG(markup: string, size: ImageSize): Promise<string | null> {
149
+ return rasterize(new view.Blob([markup], { type: 'image/svg+xml' }), size)
150
+ }
151
+
152
+ return { inline, rasterizeSVG, accept }
153
+ }
@@ -0,0 +1,170 @@
1
+ import type { WebCapture } from '#web-capture/format'
2
+ import { MAX_CAPTURE_ELEMENTS, WEB_CAPTURE_FORMAT, WEB_CAPTURE_VERSION } from '#web-capture/limits'
3
+ import { normalizeWebCapture } from '#web-capture/parse'
4
+ import type { WebCaptureElement } from '#web-capture/types'
5
+
6
+ import { createFontCollector } from './fonts'
7
+ import {
8
+ createImageInliner,
9
+ type CaptureImageFetcher,
10
+ type CaptureWindow,
11
+ type ImageInliner
12
+ } from './images'
13
+ import { walkElement, type WalkContext } from './walk'
14
+
15
+ export {
16
+ CaptureClipboardUnavailableError,
17
+ writeWebCaptureClipboard,
18
+ type CaptureClipboard,
19
+ type WriteCaptureClipboardOptions
20
+ } from './clipboard'
21
+ export type { CaptureImageFetcher } from './images'
22
+
23
+ export interface CaptureOptions {
24
+ /** Elements to capture at most; the capture is marked truncated when the page has more. */
25
+ maxElements?: number
26
+ /** Carry images inside the capture as data URLs (the default), or keep only their addresses. */
27
+ inlineImages?: boolean
28
+ /** Reads images the page cannot, such as another site's without CORS headers. */
29
+ fetchImage?: CaptureImageFetcher
30
+ /** Bytes one inlined image may take. */
31
+ maxImageBytes?: number
32
+ /** Bytes all inlined images may take together. */
33
+ maxTotalImageBytes?: number
34
+ signal?: AbortSignal
35
+ }
36
+
37
+ const NO_IMAGES: ImageInliner = {
38
+ inline: async () => null,
39
+ rasterizeSVG: async () => null,
40
+ accept: () => null
41
+ }
42
+
43
+ function windowOf(document: Document): CaptureWindow {
44
+ const view = document.defaultView
45
+ if (!view) throw new TypeError('Capturing needs a document shown in a window')
46
+ return view
47
+ }
48
+
49
+ function createContext(
50
+ view: CaptureWindow,
51
+ origin: WalkContext['origin'],
52
+ options: CaptureOptions
53
+ ): WalkContext {
54
+ return {
55
+ view,
56
+ origin,
57
+ maxElements: options.maxElements ?? MAX_CAPTURE_ELEMENTS,
58
+ elements: 0,
59
+ truncated: false,
60
+ images:
61
+ options.inlineImages === false
62
+ ? NO_IMAGES
63
+ : createImageInliner(view, {
64
+ fetchImage: options.fetchImage,
65
+ maxImageBytes: options.maxImageBytes,
66
+ maxTotalBytes: options.maxTotalImageBytes,
67
+ signal: options.signal
68
+ }),
69
+ fonts: createFontCollector(),
70
+ pending: []
71
+ }
72
+ }
73
+
74
+ async function finish(
75
+ context: WalkContext,
76
+ root: WebCaptureElement,
77
+ scope: WebCapture['scope'],
78
+ options: CaptureOptions
79
+ ): Promise<WebCapture> {
80
+ await Promise.all(context.pending)
81
+ options.signal?.throwIfAborted()
82
+ const { view } = context
83
+ return normalizeWebCapture({
84
+ format: WEB_CAPTURE_FORMAT,
85
+ version: WEB_CAPTURE_VERSION,
86
+ scope,
87
+ source: { url: view.location.href || undefined, title: view.document.title || undefined },
88
+ capturedAt: new Date().toISOString(),
89
+ viewport: {
90
+ width: view.innerWidth,
91
+ height: view.innerHeight,
92
+ devicePixelRatio: view.devicePixelRatio || 1
93
+ },
94
+ root,
95
+ fonts: context.fonts.list(),
96
+ truncated: context.truncated
97
+ })
98
+ }
99
+
100
+ /** The single root a walk returns; an element without a box of its own gets one around it. */
101
+ function rootElement(element: Element, context: WalkContext): WebCaptureElement {
102
+ const nodes = walkElement(element, context)
103
+ const first = nodes.at(0)
104
+ if (nodes.length === 1 && first?.type === 'element') return first
105
+ if (nodes.length === 0) throw new Error('The element is not displayed')
106
+ const rect = element.getBoundingClientRect()
107
+ return {
108
+ type: 'element',
109
+ tagName: 'div',
110
+ attrs: {},
111
+ computedStyle: { display: 'block' },
112
+ box: { x: 0, y: 0, width: rect.width, height: rect.height },
113
+ children: nodes
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Captures one element of a live page with the styles the browser computed for it, its
119
+ * images inlined as data URLs. Runs in the page, as a content script or a capturer SDK does.
120
+ */
121
+ export async function captureElement(
122
+ element: Element,
123
+ options: CaptureOptions = {}
124
+ ): Promise<WebCapture> {
125
+ options.signal?.throwIfAborted()
126
+ const view = windowOf(element.ownerDocument)
127
+ const rect = element.getBoundingClientRect()
128
+ const context = createContext(view, { x: rect.left, y: rect.top }, options)
129
+ return finish(context, rootElement(element, context), 'element', options)
130
+ }
131
+
132
+ function isTransparent(color: string): boolean {
133
+ return color === '' || color === 'transparent' || color === 'rgba(0, 0, 0, 0)'
134
+ }
135
+
136
+ /**
137
+ * Captures a whole page: the body at the page's full scroll size, on the background the page
138
+ * shows, with the body's margins kept as space around its content.
139
+ */
140
+ export async function capturePage(
141
+ document: Document = globalThis.document,
142
+ options: CaptureOptions = {}
143
+ ): Promise<WebCapture> {
144
+ options.signal?.throwIfAborted()
145
+ const view = windowOf(document)
146
+ const { body, documentElement } = document
147
+ const pageRect = documentElement.getBoundingClientRect()
148
+ const context = createContext(view, { x: pageRect.left, y: pageRect.top }, options)
149
+ const root = rootElement(body, context)
150
+ const bodyStyle = view.getComputedStyle(body)
151
+ const style = root.computedStyle
152
+ for (const side of ['top', 'right', 'bottom', 'left'] as const) {
153
+ const margin = Number.parseFloat(bodyStyle.getPropertyValue(`margin-${side}`)) || 0
154
+ const padding = Number.parseFloat(bodyStyle.getPropertyValue(`padding-${side}`)) || 0
155
+ if (margin + padding > 0) style[`padding-${side}`] = `${margin + padding}px`
156
+ delete style[`margin-${side}`]
157
+ }
158
+ const background = [bodyStyle, view.getComputedStyle(documentElement)]
159
+ .map((computed) => computed.getPropertyValue('background-color'))
160
+ .find((color) => !isTransparent(color))
161
+ style['background-color'] = background ?? 'rgb(255, 255, 255)'
162
+ // The page's size, not the body's, which may be shorter than the window.
163
+ const width = documentElement.clientWidth || pageRect.width
164
+ const height = Math.max(documentElement.scrollHeight, view.innerHeight)
165
+ style.width = `${width}px`
166
+ style.height = `${height}px`
167
+ style['box-sizing'] = 'border-box'
168
+ root.box = { x: 0, y: 0, width, height }
169
+ return finish(context, root, 'page', options)
170
+ }
@@ -0,0 +1,51 @@
1
+ import { encodeWebCaptureClipboard } from '#web-capture/clipboard'
2
+
3
+ import { captureElement, capturePage } from './index'
4
+
5
+ /**
6
+ * The page script the desktop browser evals. It only reads the DOM and returns the clipboard HTML
7
+ * the editor already imports. Images stay as addresses: inlining them makes the reply too large
8
+ * for one evaluation, and a page that blocks them still imports.
9
+ */
10
+ const CAPTURE_OPTIONS = { inlineImages: false } as const
11
+
12
+ /** Clipboard HTML of the whole page, the same envelope a copied capture uses. */
13
+ export async function capturePageHTML(document: Document = globalThis.document): Promise<string> {
14
+ return encodeWebCaptureClipboard(await capturePage(document, CAPTURE_OPTIONS)).html
15
+ }
16
+
17
+ /** Clipboard HTML of one element. An unknown element is an empty string, which imports nothing. */
18
+ export async function captureElementHTML(
19
+ element: Element | null,
20
+ document: Document = globalThis.document
21
+ ): Promise<string> {
22
+ if (!element || element.ownerDocument !== document) return ''
23
+ return encodeWebCaptureClipboard(await captureElement(element, CAPTURE_OPTIONS)).html
24
+ }
25
+
26
+ /** A failed read comes back as text. The window command turns the prefix into its error. */
27
+ function captureFailure(error: unknown): string {
28
+ const message = error instanceof Error ? error.message : String(error)
29
+ return `pairdraw-capture-error:${message}`
30
+ }
31
+
32
+ const pageWindow = globalThis as typeof globalThis & {
33
+ __pairdrawCapturePage?: () => Promise<string>
34
+ __pairdrawCaptureElement?: (selector: string) => Promise<string>
35
+ }
36
+
37
+ pageWindow.__pairdrawCapturePage = async () => {
38
+ try {
39
+ return await capturePageHTML(document)
40
+ } catch (error) {
41
+ return captureFailure(error)
42
+ }
43
+ }
44
+
45
+ pageWindow.__pairdrawCaptureElement = async (selector: string) => {
46
+ try {
47
+ return await captureElementHTML(document.querySelector(selector), document)
48
+ } catch (error) {
49
+ return captureFailure(error)
50
+ }
51
+ }
@@ -0,0 +1,79 @@
1
+ import type { CaptureWindow, ImageSize } from './images'
2
+
3
+ /**
4
+ * Presentation properties an icon usually takes from the page's stylesheets or `currentColor`,
5
+ * which a standalone SVG loses. They are written onto the copy as inline styles.
6
+ */
7
+ const PRESENTATION_PROPERTIES = [
8
+ 'fill',
9
+ 'fill-opacity',
10
+ 'fill-rule',
11
+ 'stroke',
12
+ 'stroke-width',
13
+ 'stroke-opacity',
14
+ 'stroke-linecap',
15
+ 'stroke-linejoin',
16
+ 'stroke-dasharray',
17
+ 'opacity',
18
+ 'color',
19
+ 'font-family',
20
+ 'font-size',
21
+ 'font-weight',
22
+ 'display',
23
+ 'visibility'
24
+ ]
25
+
26
+ /** Elements whose styles are copied; very large drawings keep the rest as they are. */
27
+ const MAX_STYLED_ELEMENTS = 4000
28
+
29
+ const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'
30
+
31
+ function inlineStyles(view: CaptureWindow, original: Element, copy: Element): void {
32
+ const style = view.getComputedStyle(original)
33
+ const declarations = PRESENTATION_PROPERTIES.flatMap((property) => {
34
+ const value = style.getPropertyValue(property)
35
+ return value ? [`${property}:${value}`] : []
36
+ })
37
+ if (declarations.length > 0) copy.setAttribute('style', declarations.join(';'))
38
+ }
39
+
40
+ /** A `<use>` pointing at an icon sprite elsewhere in the page needs that sprite in the copy. */
41
+ function referencedSymbols(svg: SVGSVGElement, document: Document): Element[] {
42
+ const symbols = new Set<Element>()
43
+ for (const use of svg.querySelectorAll('use')) {
44
+ const reference = use.getAttribute('href') ?? use.getAttribute('xlink:href') ?? ''
45
+ if (!reference.startsWith('#')) continue
46
+ const target = document.getElementById(reference.slice(1))
47
+ if (target && !svg.contains(target)) symbols.add(target)
48
+ }
49
+ return [...symbols]
50
+ }
51
+
52
+ /**
53
+ * The SVG as standalone markup that draws as it did on the page: its computed presentation
54
+ * styles inlined, sprites it references copied in, and its drawn size set.
55
+ */
56
+ export function standaloneSVGMarkup(
57
+ view: CaptureWindow,
58
+ svg: SVGSVGElement,
59
+ size: ImageSize
60
+ ): string {
61
+ const copy = svg.cloneNode(true)
62
+ if (!(copy instanceof view.SVGSVGElement)) return ''
63
+ const originals = [svg, ...svg.querySelectorAll('*')]
64
+ const copies = [copy, ...copy.querySelectorAll('*')]
65
+ for (const [index, original] of originals.slice(0, MAX_STYLED_ELEMENTS).entries()) {
66
+ const target = copies.at(index)
67
+ if (target) inlineStyles(view, original, target)
68
+ }
69
+ const symbols = referencedSymbols(svg, svg.ownerDocument)
70
+ if (symbols.length > 0) {
71
+ const defs = svg.ownerDocument.createElementNS(SVG_NAMESPACE, 'defs')
72
+ for (const symbol of symbols) defs.append(symbol.cloneNode(true))
73
+ copy.prepend(defs)
74
+ }
75
+ copy.setAttribute('xmlns', SVG_NAMESPACE)
76
+ copy.setAttribute('width', String(size.width))
77
+ copy.setAttribute('height', String(size.height))
78
+ return new view.XMLSerializer().serializeToString(copy)
79
+ }