@zumer/snapdom-plugins 4.4.1-dev.1 → 5.0.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 (70) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +30 -83
  3. package/ascii-export.d.ts +0 -7
  4. package/ascii-export.js +0 -21
  5. package/index.d.ts +0 -3
  6. package/index.js +1 -4
  7. package/package.json +4 -19
  8. package/pdf/LICENSE +0 -21
  9. package/pdf/README.md +0 -22
  10. package/pdf/REFERENCE.md +0 -520
  11. package/pdf/src/frontmatter.js +0 -200
  12. package/pdf/src/furniture.js +0 -398
  13. package/pdf/src/index.js +0 -2415
  14. package/pdf/src/mega/README.md +0 -47
  15. package/pdf/src/mega/diag.js +0 -148
  16. package/pdf/src/mega/flow.js +0 -56
  17. package/pdf/src/mega/fonts.js +0 -287
  18. package/pdf/src/mega/forms.js +0 -479
  19. package/pdf/src/mega/labels.js +0 -43
  20. package/pdf/src/mega/meta.js +0 -145
  21. package/pdf/src/nav.js +0 -357
  22. package/pdf/src/paginate.js +0 -583
  23. package/pdf/src/tagged.js +0 -355
  24. package/pdf/src/text-layer.js +0 -1771
  25. package/pdf/src/writer/encrypt.js +0 -218
  26. package/pdf/src/writer/font.js +0 -507
  27. package/pdf/src/writer/index.js +0 -1135
  28. package/pdf/src/writer/subset.js +0 -387
  29. package/pdf.d.ts +0 -294
  30. package/pdf.js +0 -1
  31. package/stream/LICENSE +0 -21
  32. package/stream/README.md +0 -142
  33. package/stream/src/index.js +0 -41
  34. package/stream/src/overlays.js +0 -153
  35. package/stream/src/recorder.js +0 -41
  36. package/stream/src/stream.js +0 -686
  37. package/stream/src/webgl.js +0 -58
  38. package/stream.d.ts +0 -86
  39. package/stream.js +0 -1
  40. package/vector/CONTRACT.md +0 -903
  41. package/vector/LICENSE +0 -21
  42. package/vector/README.md +0 -35
  43. package/vector/src/adapters/snapdom.js +0 -795
  44. package/vector/src/collect/box.js +0 -1676
  45. package/vector/src/collect/font.js +0 -487
  46. package/vector/src/collect/image.js +0 -1458
  47. package/vector/src/collect/mathml.js +0 -272
  48. package/vector/src/collect/text.js +0 -3027
  49. package/vector/src/css/color.js +0 -823
  50. package/vector/src/css/gradient.js +0 -1126
  51. package/vector/src/css/matrix.js +0 -398
  52. package/vector/src/css/radius.js +0 -124
  53. package/vector/src/css/shadow.js +0 -201
  54. package/vector/src/emit/figma-json.js +0 -1995
  55. package/vector/src/emit/h2d-vector.js +0 -215
  56. package/vector/src/emit/h2d.js +0 -1147
  57. package/vector/src/emit/pdf.js +0 -2571
  58. package/vector/src/emit/svg-flat.js +0 -4842
  59. package/vector/src/exclusion.js +0 -13
  60. package/vector/src/index.js +0 -2910
  61. package/vector/src/paint.js +0 -2908
  62. package/vector/src/public.js +0 -57
  63. package/vector/src/writer/encrypt.js +0 -227
  64. package/vector/src/writer/font.js +0 -507
  65. package/vector/src/writer/index.js +0 -1148
  66. package/vector/src/writer/subset.js +0 -387
  67. package/vector/svd/index.js +0 -72
  68. package/vector/svd/schema.js +0 -985
  69. package/vector.d.ts +0 -28
  70. package/vector.js +0 -1
@@ -1,686 +0,0 @@
1
- /**
2
- * `snapdom.stream(el)`: a live element as a canvas that repaints only what changed.
3
- *
4
- * A browser compositor does not repaint the page when one button changes; it repaints that
5
- * layer. This does the same over captures. The first frame is a full capture. After that,
6
- * every change (mutation records, typing, focus, hover, running animations) is attributed to
7
- * the nearest ancestor that can be painted standalone over the previous pixels: an opaque
8
- * box, with no ancestor effect (opacity, filter, transform, blend, mask) between it and the
9
- * root, inside every clipping ancestor and under no positioned element. A box that moved or
10
- * was restyled hands the change to the enclosing box that did not; an absolutely positioned
11
- * box over a solid or clear backdrop may move and resize itself, since it pushes nothing.
12
- * Only that subtree is captured, laid out at its subpixel phase, and drawn over its backdrop
13
- * or where it is fully opaque. A change with no such box (a value on a glass card, a row
14
- * under a badge) repaints a window of the root: a `clip` capture of the box the change stayed
15
- * inside, which has everything that paints there. Anything this cannot prove is a full
16
- * frame, with the reason on the frame. The pointer counts only through `:hover` rules: a move
17
- * repaints the elements whose match it changed.
18
- *
19
- * Measured 2026-10-23, 1000px grid, one card's text changed per frame, median ms per frame
20
- * (full / patch): 400 cards Chromium 11.7 / 4.2, Firefox 28 / 4, WebKit 20 / 4; 2000 cards
21
- * 52.9 / 4.9, 119 / 5, 90 / 4. The patch cost tracks the changed box, not the page.
22
- *
23
- * Output: `stream.canvas` is updated in place; `onFrame` receives the dirty rects in canvas
24
- * pixels, so a WebGL consumer can `texSubImage2D` just those and a video consumer can use
25
- * `canvas.captureStream()`. Pinned by __tests__/plugin.stream.test.js, which compares every
26
- * patched frame against a full capture of the same DOM state.
27
- *
28
- * Built on the public capture API plus one engine contract, the internal `__subpixel` option
29
- * (src/engines/svg.js), which lays a patch out at the page's subpixel offset.
30
- * @module plugins/stream
31
- */
32
- import { snapdom as capture } from '@zumer/snapdom'
33
-
34
- // WebKit keeps toCanvas, whose draw workarounds a raw decode would skip. Every iOS browser is
35
- // WebKit; elsewhere WebKit is AppleWebKit without a Chromium token.
36
- const WEBKIT = typeof navigator !== 'undefined' && (/ipad|iphone|ipod/i.test(navigator.userAgent) ||
37
- (/applewebkit/i.test(navigator.userAgent) && !/chrome|chromium|crios|edg|opr|android/i.test(navigator.userAgent)))
38
-
39
- const EVENTS = ['input', 'change', 'focusin', 'focusout', 'pointerover', 'pointerout', 'scroll', 'toggle']
40
- const HOVER_EVENTS = new Set(['pointerover', 'pointerout'])
41
- /** :hover selectors x nodes one hover query may cost. A query is linear in both: 200 x 1400
42
- * took 1.5 to 1.75 ms on all three engines, 2000 x 1400 took 13 to 30. Past it the pointer
43
- * repaints whatever it crosses, as it did before the query. */
44
- const HOVER_BUDGET = 300_000
45
- /** Cut from a :hover selector, so it matches the box the pseudo-element hangs from. */
46
- const PSEUDO_ELEMENT = /::?(?:before|after|first-line|first-letter)\b|::[\w-]+(?:\([^)]*\))?/g
47
- /** A patch larger than this share of the frame costs about what a full frame does. */
48
- const MAX_PATCH_AREA = 0.5
49
- /** Self-healing keyframe: anything the heuristics missed lasts at most this long, or 50
50
- * full frames' worth of time, so the safety net costs under 2% of the main thread (a
51
- * 3000-card lab frame took 235 ms: every 2 s it froze the page 7 times in 8 s). */
52
- const KEYFRAME_MS = 2000
53
- const KEYFRAME_COST = 50
54
-
55
- function opaqueColor(value) {
56
- if (!value || value === 'transparent') return false
57
- const m = value.match(/rgba?\(([^)]+)\)/)
58
- if (!m) return false
59
- const parts = m[1].split(/[\s,/]+/).filter(Boolean)
60
- return parts.length < 4 || parseFloat(parts[3]) >= 1
61
- }
62
-
63
- /** An ancestor effect the standalone subtree capture would not reproduce. */
64
- function hasEffect(cs) {
65
- return parseFloat(cs.opacity) < 1 || cs.filter !== 'none' || cs.transform !== 'none' ||
66
- cs.mixBlendMode !== 'normal' || (cs.maskImage && cs.maskImage !== 'none') ||
67
- cs.clipPath !== 'none' || (cs.backdropFilter && cs.backdropFilter !== 'none')
68
- }
69
-
70
- /** A filter that carries a change past the box it happened in. */
71
- function spreads(cs) {
72
- return /blur|drop-shadow|url\(/.test(cs.filter)
73
- }
74
-
75
- function clips(cs) {
76
- return cs.overflowX !== 'visible' || cs.overflowY !== 'visible'
77
- }
78
-
79
- /** Visible overflow paints outside the box. */
80
- function overflows(el, cs) {
81
- return !clips(cs) && (el.scrollWidth > el.clientWidth + 1 || el.scrollHeight > el.clientHeight + 1)
82
- }
83
-
84
- /** A shadow or outline paints outside the box. */
85
- function outerInk(cs) {
86
- return cs.boxShadow !== 'none' || (cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0)
87
- }
88
-
89
- /** Every selector that names :hover; null when a sheet cannot be read (cross origin) or a
90
- * nested `&` rule cannot be queried, and then any hover may restyle. Pseudo-elements are
91
- * cut: `.dot:hover::after` repaints with `.dot`. */
92
- function hoverSelectors(root) {
93
- const list = []
94
- const walk = (rules) => {
95
- for (const rule of rules) {
96
- const sel = rule.selectorText
97
- if (sel?.includes(':hover')) {
98
- if (sel.includes('&')) throw new Error('nested')
99
- list.push(sel.replace(PSEUDO_ELEMENT, ''))
100
- }
101
- if (rule.cssRules) walk(rule.cssRules)
102
- if (rule.styleSheet) walk(rule.styleSheet.cssRules)
103
- }
104
- }
105
- const scope = root.getRootNode()
106
- try {
107
- for (const sheet of [...scope.styleSheets, ...(scope.adoptedStyleSheets || [])]) walk(sheet.cssRules)
108
- } catch { return null }
109
- return list
110
- }
111
-
112
- function inside(a, b) {
113
- return a.left >= b.left - 0.5 && a.top >= b.top - 0.5 && a.right <= b.right + 0.5 && a.bottom <= b.bottom + 0.5
114
- }
115
-
116
- /** Whether a clipping ancestor cuts into `r`: past its edges, or into a rounded corner. A
117
- * clock flush with the end of a rounded scoreboard drew square corners where the page
118
- * clipped them round. */
119
- function escapesClip(r, clip, cs) {
120
- if (!inside(r, clip)) return true
121
- const radius = Math.max(...['borderTopLeftRadius', 'borderTopRightRadius', 'borderBottomRightRadius', 'borderBottomLeftRadius']
122
- .map((p) => parseFloat(cs[p]) || 0))
123
- if (!radius) return false
124
- return [[clip.left, clip.top], [clip.right - radius, clip.top], [clip.left, clip.bottom - radius], [clip.right - radius, clip.bottom - radius]]
125
- .some(([x, y]) => intersects(r, { left: x, top: y, right: x + radius, bottom: y + radius }))
126
- }
127
-
128
- function intersects(a, b) {
129
- return a.left < b.right && b.left < a.right && a.top < b.bottom && b.top < a.bottom
130
- }
131
-
132
- function sameRect(a, b) {
133
- return Math.abs(a.left - b.left) < 0.5 && Math.abs(a.top - b.top) < 0.5 &&
134
- Math.abs(a.width - b.width) < 0.5 && Math.abs(a.height - b.height) < 0.5
135
- }
136
-
137
- /** Targets whose records have a net effect. The capture pipeline writes to live nodes and
138
- * undoes the write (text-overflow, line-clamp, content-visibility); those records cancel. */
139
- function netTargets(records, out, restyled) {
140
- const attrs = new Map(), chars = new Map()
141
- for (const rec of records) {
142
- if (rec.type === 'attributes') {
143
- const key = rec.target
144
- let byName = attrs.get(key)
145
- if (!byName) attrs.set(key, byName = new Map())
146
- if (!byName.has(rec.attributeName)) byName.set(rec.attributeName, rec.oldValue)
147
- } else if (rec.type === 'characterData') {
148
- if (!chars.has(rec.target)) chars.set(rec.target, rec.oldValue)
149
- } else {
150
- let added = 0
151
- for (const n of rec.addedNodes) added += n.nodeType === 3 ? n.data.length : 1e6
152
- for (const n of rec.removedNodes) added -= n.nodeType === 3 ? n.data.length : 1e6
153
- if (added || rec.addedNodes.length !== rec.removedNodes.length) out.add(rec.target)
154
- else {
155
- const before = [...rec.removedNodes].map(n => n.data).join('')
156
- const after = [...rec.addedNodes].map(n => n.data).join('')
157
- if (before !== after) out.add(rec.target)
158
- }
159
- }
160
- }
161
- for (const [el, byName] of attrs) {
162
- for (const [name, old] of byName) if (el.getAttribute(name) !== old) { out.add(el); restyled?.add(el); break }
163
- }
164
- for (const [node, old] of chars) if (node.data !== old) out.add(node.parentElement)
165
- }
166
-
167
- function describe(node) {
168
- const el = node?.nodeType === 1 ? node : node?.parentElement
169
- if (!el) return 'a detached node'
170
- return `<${el.tagName.toLowerCase()}${el.id ? '#' + el.id : ''}${el.classList?.length ? '.' + [...el.classList].join('.') : ''}>`
171
- }
172
-
173
- /** A task of its own, with rendering's turn before it: a message, as the core's time slicing
174
- * yields (scheduler.yield() resumes ahead of rendering, a nested setTimeout clamps to 4 ms). */
175
- function nextTask() {
176
- return new Promise((resolve) => {
177
- const channel = new MessageChannel()
178
- channel.port1.onmessage = () => resolve()
179
- channel.port2.postMessage(0)
180
- })
181
- }
182
-
183
- /** How long the [start, end] spans cover, overlaps counted once. */
184
- function covered(spans) {
185
- let sum = 0
186
- let end = -Infinity
187
- for (const [s, e] of spans.sort((a, b) => a[0] - b[0])) {
188
- if (e > end) { sum += e - Math.max(s, end); end = e }
189
- }
190
- return sum
191
- }
192
-
193
- async function decode(url) {
194
- const img = new Image()
195
- img.decoding = 'sync'
196
- img.src = url
197
- await img.decode()
198
- return img
199
- }
200
-
201
- /**
202
- * Stream an element into a canvas, repainting only the boxes that changed.
203
- * @param {Element} element
204
- * @param {object} [options] - capture options (scale, dpr, embedFonts, ...), plus:
205
- * @param {(frame: {full: boolean, reason: string|null, rects: {x:number,y:number,width:number,height:number}[], ms: number, busyMs: number, canvas: HTMLCanvasElement}) => void} [options.onFrame]
206
- * `ms` is the frame's wall time; `busyMs` the part its own work held the main thread, without
207
- * the turns between windows or the decodes (a full frame's capture counts whole, its sliced
208
- * pauses included). Zumly's board, 17 windows a second at 4x CPU: 584 to 778 ms of wall
209
- * time, which turned its stream off on a budget of blocked time.
210
- * @param {number} [options.fps] - cap on frames per second; default every animation frame.
211
- * @param {boolean} [options.patches=true] - false repaints full frames only (the baseline).
212
- * @param {boolean} [options.animations=true] - false stops following running animations and
213
- * transitions: an animated box keeps its last drawn pixels until a patch, a full frame or the
214
- * keyframe repaints it. A transparent spinner has no host and turns its own box, so by default
215
- * nearly every tick is a full frame (Zumly views at dpr 2, fps 5: 109 ms a frame, against
216
- * 9-13 ms patches without it).
217
- * @returns {{canvas: HTMLCanvasElement, stop: () => void, ready: Promise<void>, stats: object}}
218
- */
219
- export function stream(element, options = {}) {
220
- const { onFrame, fps, patches = true, animations = true, ...rest } = options
221
- const opts = { ...rest, outerShadows: false, dpr: rest.dpr ?? (globalThis.devicePixelRatio || 1) }
222
- const k = (opts.scale ?? 1) * opts.dpr
223
- const canvas = document.createElement('canvas')
224
- const ctx = canvas.getContext('2d')
225
- const dirty = new Set()
226
- const restyled = new Set() // elements whose own attributes changed: their box may have too
227
- const rects = new WeakMap() // element -> rect at the last paint that covered it
228
- const backdrops = new Map() // this frame's hosts that draw over a solid colour
229
- const movedFrom = new Map() // this frame's out-of-flow hosts that moved -> their old rect
230
- const regions = new Set() // this frame's hosts repainted as a window of the root
231
- let windows = Promise.resolve() // the turn of the next window capture
232
- let spans = [] // this frame's own work on the main thread, [start, end]
233
- const stats = { full: 0, patch: 0, skipped: 0, lastMs: 0 }
234
- let floaters = []
235
- let glass = [] // backdrop-filter boxes: a change under one shows through its blur
236
- let hoverList = null // the :hover selectors at the last full frame, null if unreadable
237
- let hovered = new Set() // what they matched at the last look
238
- let hoverMoved = false
239
- let forceFull = true
240
- let lastKeyframe = 0
241
- let keyframeDue = false // set from idle time once the keyframe interval has passed
242
- let fullMs = 0
243
- let idleAsked = false
244
- let stopped = false
245
- let busy = false
246
- let lastTick = 0
247
- let rootRect = null
248
- let animating = new Set() // targets of the animations running at the last tick
249
- let ox = 0, oy = 0 // canvas pixels from the canvas origin to the root's border box
250
-
251
- const observer = new MutationObserver(records => netTargets(records, dirty, restyled))
252
- observer.observe(element, { subtree: true, childList: true, attributes: true, characterData: true, attributeOldValue: true, characterDataOldValue: true })
253
- const onEvent = (e) => {
254
- // A pointer that crosses boxes no :hover rule matches changes no pixel. Moving over the
255
- // gaps of a 48-tile board made its root dirty, and every move a 300 ms full frame (Zumly,
256
- // dpr 2). A shadow tree's event arrives at its host, and its sheets were not read.
257
- if (hoverList !== null && HOVER_EVENTS.has(e.type) && e.composedPath()[0] === e.target) {
258
- hoverMoved = true
259
- return
260
- }
261
- dirty.add(e.target)
262
- if (e.relatedTarget && element.contains(e.relatedTarget)) dirty.add(e.relatedTarget)
263
- }
264
- for (const type of EVENTS) element.addEventListener(type, onEvent, true)
265
- const onResize = () => { forceFull = true }
266
- addEventListener('resize', onResize)
267
-
268
- function rectOf(el) {
269
- const r = el.getBoundingClientRect()
270
- return { left: r.left - rootRect.left, top: r.top - rootRect.top, right: r.right - rootRect.left, bottom: r.bottom - rootRect.top, width: r.width, height: r.height }
271
- }
272
-
273
- /** `r` grown to whole canvas pixels, in the same root-relative CSS px. */
274
- function pixelRect(r) {
275
- return { left: (Math.floor(ox + r.left * k) - ox) / k, top: (Math.floor(oy + r.top * k) - oy) / k, right: (Math.ceil(ox + r.right * k) - ox) / k, bottom: (Math.ceil(oy + r.bottom * k) - oy) / k }
276
- }
277
-
278
- /** The nearest absolutely or fixed positioned ancestor: it leaves the flow, so its own
279
- * changes of size or place move nothing else. Drawn only over a backdrop. */
280
- function positionedHost(node) {
281
- for (let el = node?.nodeType === 1 ? node : node?.parentElement; el && el !== element; el = el.parentElement) {
282
- const cs = getComputedStyle(el)
283
- if (cs.position !== 'absolute' && cs.position !== 'fixed') continue
284
- for (let a = el; a !== element; a = a.parentElement) {
285
- const as = getComputedStyle(a)
286
- if (hasEffect(as) || (a !== el && clips(as))) return null
287
- }
288
- return el
289
- }
290
- return null
291
- }
292
-
293
- /** Remember every box's rect and the positioned elements that can paint over others. */
294
- function snapshotLayout() {
295
- rootRect = element.getBoundingClientRect()
296
- floaters = []
297
- glass = []
298
- for (const el of element.querySelectorAll('*')) {
299
- rects.set(el, rectOf(el))
300
- const cs = getComputedStyle(el)
301
- if (cs.position === 'absolute' || cs.position === 'fixed' || cs.position === 'sticky' ||
302
- (cs.position === 'relative' && cs.zIndex !== 'auto') || cs.transform !== 'none') floaters.push(el)
303
- if (cs.backdropFilter && cs.backdropFilter !== 'none') glass.push(el)
304
- }
305
- }
306
-
307
- /** The elements the :hover rules match now, the root included. */
308
- function hoverMatches() {
309
- if (!hoverList) return new Set()
310
- const out = new Set(element.querySelectorAll(hoverList))
311
- if (element.matches(hoverList)) out.add(element)
312
- return out
313
- }
314
-
315
- /** The box a change to `node` can be repainted through, or null for a full frame. */
316
- function hostFor(node) {
317
- let el = node?.nodeType === 1 ? node : node?.parentElement
318
- if (!el || el === element || !element.contains(el)) return null
319
- const chain = [], styles = []
320
- for (let a = el; a && a !== element; a = a.parentElement) { chain.push(a); styles.push(getComputedStyle(a)) }
321
- // Search above the highest ancestor with an effect.
322
- let start = 0
323
- for (let i = 0; i < chain.length; i++) if (hasEffect(styles[i])) start = i + 1
324
- for (let i = start; i < chain.length; i++) {
325
- const cs = styles[i]
326
- if (!opaqueColor(cs.backgroundColor)) continue
327
- // Over pixels the patch does not repaint.
328
- if (overflows(chain[i], cs)) continue
329
- // A box a clipping ancestor cuts, past its edges or into a rounded corner, would be
330
- // drawn whole: a row half out of a 40px scroller painted its hidden half (19200 px
331
- // off). The host is the box itself, so the test is on its rect, not on the changed
332
- // node's. Resume at the outermost ancestor that cuts it.
333
- const r = rectOf(chain[i])
334
- let cut = -1
335
- for (let m = i + 1; m < chain.length; m++) if (clips(styles[m]) && escapesClip(r, rectOf(chain[m]), styles[m])) cut = m
336
- if (cut < 0) return chain[i]
337
- i = cut - 1
338
- }
339
- return null
340
- }
341
-
342
- /** The box a change to `node` stayed inside, to repaint as a window of the root, or null.
343
- * The window has everything that paints in it, so the box needs no backdrop and may sit
344
- * under positioned boxes; it must keep its rect, paint nothing new outside itself, and
345
- * have no blur spread the change past it: a blurring ancestor, or a glass box over it. */
346
- function regionFor(node) {
347
- let el = node?.nodeType === 1 ? node : node?.parentElement
348
- for (let a = el; a; a = a === element ? null : a.parentElement) if (spreads(getComputedStyle(a))) return null
349
- for (; el && el !== element; el = el.parentElement) {
350
- const r = rectOf(el)
351
- const cs = getComputedStyle(el)
352
- if (!r.width || !r.height || !sameRect(rects.get(el) || {}, r) || overflows(el, cs)) continue
353
- if (restyled.has(el) && outerInk(cs)) continue
354
- for (const g of glass) if (!g.contains(el) && !el.contains(g) && intersects(rectOf(g), r)) return null
355
- return el
356
- }
357
- return null
358
- }
359
-
360
- async function full() {
361
- const t0 = performance.now()
362
- // Read before the capture, at every full frame. A pointer that moves while it runs is then
363
- // diffed next tick; read after it, the first capture left the events nothing to go by, and
364
- // a pointer over the Zumly board's gaps made the root dirty (a 400 ms full frame, 4 of 4).
365
- // A sheet added later counts from the next keyframe.
366
- const sels = hoverSelectors(element)
367
- hoverList = sels && sels.length * (element.getElementsByTagName('*').length + 1) <= HOVER_BUDGET ? sels.join(',') : null
368
- try { hovered = hoverMatches() } catch { hoverList = null }
369
- // A full frame is the one long task of a stream; 'auto' lets a long clone yield (#503).
370
- // Lab, 1000 cards under constant edits: worst frame gap 67 -> 33 ms. Under edits on
371
- // every frame a big tree tears and redoes in one task, which only the interval helps.
372
- const res = await held(() => capture(element, { fast: 'auto', ...opts }), t0)
373
- const { vbW, vbH, contentX = 0, contentY = 0 } = res.meta
374
- const src = WEBKIT ? await res.toCanvas() : await decode(res.url)
375
- const drawn = performance.now()
376
- const w = Math.round(vbW * k), h = Math.round(vbH * k)
377
- if (canvas.width !== w || canvas.height !== h) { canvas.width = w; canvas.height = h }
378
- ctx.clearRect(0, 0, w, h)
379
- ctx.drawImage(src, 0, 0, w, h)
380
- ox = contentX * k
381
- oy = contentY * k
382
- snapshotLayout()
383
- lastKeyframe = performance.now()
384
- keyframeDue = false
385
- fullMs = lastKeyframe - t0
386
- spans.push([drawn, lastKeyframe])
387
- stats.full++
388
- return [{ x: 0, y: 0, width: w, height: h }]
389
- }
390
-
391
- /** The solid colour behind `host` ('transparent' over a clear root) when the patch can be
392
- * drawn over it and come out exact, edges and corners included; null otherwise. Needs no
393
- * shadow or outline of its own (they paint outside the box, where the fill would erase
394
- * them), only opaque or clear ancestor backgrounds up to the first opaque one, and no
395
- * other box on the whole-pixel rect around the host, or around `old`, where a moved host
396
- * was. */
397
- function backdropOf(host, old) {
398
- if (outerInk(getComputedStyle(host))) return null
399
- let color = null
400
- for (let a = host.parentElement; a && !color; a = a === element ? null : a.parentElement) {
401
- const s = getComputedStyle(a)
402
- if (s.backgroundImage !== 'none') return null
403
- if (opaqueColor(s.backgroundColor)) color = s.backgroundColor
404
- else if (s.backgroundColor !== 'rgba(0, 0, 0, 0)' && s.backgroundColor !== 'transparent') return null
405
- }
406
- const areas = [pixelRect(rectOf(host)), ...(old ? [pixelRect(old)] : [])]
407
- const others = [...host.parentElement.children, ...floaters]
408
- for (const other of others) {
409
- if (other === host || host.contains(other) || other.contains(host)) continue
410
- const or = rects.get(other)
411
- if (or && areas.some((a) => intersects(or, a))) return null
412
- }
413
- return color || 'transparent'
414
- }
415
-
416
- function paintBackdrop(backdrop, x, y, w, h) {
417
- ctx.clearRect(x, y, w, h)
418
- if (backdrop !== 'transparent') {
419
- ctx.fillStyle = backdrop
420
- ctx.fillRect(x, y, w, h)
421
- }
422
- }
423
-
424
- /** Capture one host at its subpixel phase and return its pixels, placed. */
425
- async function renderPatch(host) {
426
- const r = rectOf(host)
427
- // Lay the patch out at the page's subpixel phase (svg engine, options.__subpixel), so
428
- // its glyphs and snapped box edges land on the same pixels as in the full frame:
429
- // white cards on black at 1fr offsets differed on 596 pixels at phase zero.
430
- const left = ox + r.left * k, top = oy + r.top * k
431
- const x0 = Math.floor(left + 0.001), y0 = Math.floor(top + 0.001)
432
- const phase = { x: (left - x0) / k, y: (top - y0) / k }
433
- // Always passed, even at phase zero: it also lays the root out at its exact width.
434
- const res = await held(() => capture(host, { ...opts, __subpixel: phase }))
435
- const { vbW, vbH, contentX = 0, contentY = 0 } = res.meta
436
- const x = Math.round(x0 - contentX * k), y = Math.round(y0 - contentY * k)
437
- const w = Math.round(vbW * k), h = Math.round(vbH * k)
438
- const src = WEBKIT ? await res.toCanvas() : await decode(res.url)
439
- const drawn = performance.now()
440
- const layer = document.createElement('canvas')
441
- layer.width = w
442
- layer.height = h
443
- const backdrop = backdrops.get(host)
444
- if (backdrop) {
445
- // Over its solid backdrop the patch is the full frame's pixels, edges included.
446
- const lctx = layer.getContext('2d')
447
- if (backdrop !== 'transparent') {
448
- lctx.fillStyle = backdrop
449
- lctx.fillRect(0, 0, w, h)
450
- }
451
- lctx.drawImage(src, 0, 0, w, h)
452
- spans.push([drawn, performance.now()])
453
- return { layer, x, y, w, h, replace: true, host, drawnAt: r }
454
- }
455
- // Otherwise keep only the pixels the box covers fully. Inside an opaque box that is
456
- // everything; what is left are its antialiased edges and rounded corners, which did not
457
- // change (restyled hosts without a backdrop climb in plan) and which drawing again would
458
- // blend over themselves. Same scene: 36 pixels off without this, 0 with it.
459
- const lctx = layer.getContext('2d', { willReadFrequently: true })
460
- lctx.drawImage(src, 0, 0, w, h)
461
- const img = lctx.getImageData(0, 0, w, h)
462
- const px = img.data
463
- for (let i = 3; i < px.length; i += 4) if (px[i] < 255) px[i] = 0
464
- lctx.putImageData(img, 0, 0)
465
- spans.push([drawn, performance.now()])
466
- return { layer, x, y, w, h, host, drawnAt: r }
467
- }
468
-
469
- /** Capture the root clipped to `host`'s box on whole canvas pixels: the full frame's
470
- * pixels for that window. A value on a glass tile of the Zumly board (48 tiles, dpr 2):
471
- * 9 ms against 323 for the full frame, identical to it. A window over the tile's rounded
472
- * corners differed on the antialiased arc, by up to 28 levels on 45 pixels (cause not
473
- * found). Sixteen windows at once cost 101 ms; one window per row of them cost 149, since a
474
- * row keeps every tile in it. */
475
- async function renderRegion(host) {
476
- // One window per task. Captures of one element run one after another in the core, and
477
- // each began in the task the last one ended in: the board's 17 windows a second were one
478
- // task of up to 95 ms, and 9.5% of the frames at rest were dropped.
479
- const turn = windows.then(async () => {
480
- // stop() between turns drops the rest: Zumly stops the stream as a zoom starts, and the
481
- // queued windows went on capturing through the motion (2.7 to 5.3% frames dropped).
482
- if (stopped) return null
483
- const drawnAt = rectOf(host)
484
- const r = pixelRect(drawnAt)
485
- return { drawnAt, r, res: await held(() => capture(element, { ...opts, clip: { x: rootRect.left + scrollX + r.left, y: rootRect.top + scrollY + r.top, width: r.right - r.left, height: r.bottom - r.top } })) }
486
- })
487
- windows = turn.then(nextTask, nextTask)
488
- const shot = await turn
489
- if (!shot) return null
490
- const { drawnAt, r, res } = shot
491
- const { vbW, vbH, contentX = 0, contentY = 0, clip } = res.meta
492
- const src = WEBKIT ? await res.toCanvas() : await decode(res.url)
493
- const drawn = performance.now()
494
- const x = Math.round(ox + r.left * k), y = Math.round(oy + r.top * k)
495
- const w = Math.round(ox + r.right * k) - x, h = Math.round(oy + r.bottom * k) - y
496
- // The image starts contentX before the window, over pixels the clip culled: keep the window.
497
- const layer = document.createElement('canvas')
498
- layer.width = w
499
- layer.height = h
500
- layer.getContext('2d').drawImage(src, Math.round(ox + (clip.x - contentX) * k) - x, Math.round(oy + (clip.y - contentY) * k) - y, Math.round(vbW * k), Math.round(vbH * k))
501
- spans.push([drawn, performance.now()])
502
- return { layer, x, y, w, h, replace: true, host, drawnAt }
503
- }
504
-
505
- /** `run()`'s result, the time from `t` to it counted as the frame's own. */
506
- async function held(run, t = performance.now()) {
507
- try { return await run() } finally { spans.push([t, performance.now()]) }
508
- }
509
-
510
- async function patch(hosts) {
511
- // Captures and decodes overlap; the draws then land in one synchronous pass, so the
512
- // canvas never shows half a frame. Three hosts a frame (clock, KPI, list row) in
513
- // demos/stream-webgl.html: 11.9 ms one after another.
514
- const layers = await Promise.all(hosts.map((h) => regions.has(h) ? renderRegion(h) : renderPatch(h)))
515
- if (stopped) return []
516
- const drawn = performance.now()
517
- const out = []
518
- // The canvas clips draws past its edge; a reported rect must be clipped too, or a box
519
- // sliding off the stage (the lower third hides to left:-720px) hands texSubImage2D a
520
- // negative offset and the upload is rejected. Pinned by __tests__/plugin.stream.test.js.
521
- const report = (x, y, w, h) => {
522
- const x0 = Math.max(0, x), y0 = Math.max(0, y)
523
- const x1 = Math.min(canvas.width, x + w), y1 = Math.min(canvas.height, y + h)
524
- if (x1 > x0 && y1 > y0) out.push({ x: x0, y: y0, width: x1 - x0, height: y1 - y0 })
525
- }
526
- for (const [host, old] of movedFrom) {
527
- const r = pixelRect(old)
528
- const x = Math.round(ox + r.left * k), y = Math.round(oy + r.top * k)
529
- const w = Math.round(ox + r.right * k) - x, h = Math.round(oy + r.bottom * k) - y
530
- paintBackdrop(backdrops.get(host), x, y, w, h)
531
- report(x, y, w, h)
532
- }
533
- for (const { layer, x, y, w, h, replace } of layers) {
534
- // A backdrop or window layer is the full frame's pixels for its whole rect: replace, not blend.
535
- if (replace) ctx.clearRect(x, y, w, h)
536
- ctx.drawImage(layer, x, y)
537
- report(x, y, w, h)
538
- }
539
- movedFrom.clear()
540
- // Remember where each host was drawn, not where it is now: a sliding box kept moving
541
- // while it was captured, and clearing its current rect next frame left a trail behind.
542
- for (const { host, drawnAt } of layers) {
543
- rects.set(host, drawnAt)
544
- for (const el of host.querySelectorAll('*')) rects.set(el, rectOf(el))
545
- }
546
- spans.push([drawn, performance.now()])
547
- stats.patch++
548
- return out
549
- }
550
-
551
- /** Hosts for this frame, or the reason only a full frame is safe. */
552
- function plan() {
553
- if (!patches) return 'patches off'
554
- if (forceFull) return 'resize'
555
- if (keyframeDue) return 'keyframe'
556
- const now = element.getBoundingClientRect()
557
- if (!sameRect({ left: 0, top: 0, width: now.width, height: now.height }, { left: 0, top: 0, width: rootRect.width, height: rootRect.height })) return 'root resized'
558
- rootRect = now
559
- const hosts = new Set()
560
- regions.clear()
561
- for (const node of dirty) {
562
- if (!node?.isConnected) return 'node removed'
563
- let host = hostFor(node)
564
- // A box that moved or resized may have moved its siblings, and a restyled box may have
565
- // changed its own edges, which only a solid backdrop lets the patch redraw. If an
566
- // enclosing host kept its rect, the change stayed inside it: repaint that box instead.
567
- while (host && (!sameRect(rects.get(host) || {}, rectOf(host)) || (restyled.has(host) && !backdropOf(host)))) host = hostFor(host.parentElement)
568
- if (!host) {
569
- // Out of the flow, a box can move or resize freely: clear where it was, draw it
570
- // where it is. A lower third whose name got longer.
571
- const p = positionedHost(node)
572
- const old = p && rects.get(p)
573
- if (old && backdropOf(p, old)) {
574
- host = p
575
- // Always clear where it was last drawn: a slide's last step can be under the
576
- // half-pixel sameRect allows, and the column it left kept the old edge.
577
- movedFrom.set(p, old)
578
- }
579
- }
580
- if (!host && (host = regionFor(node))) regions.add(host)
581
- if (!host) return `no host for ${describe(node)}`
582
- hosts.add(host)
583
- }
584
- // Outermost hosts only: a box inside another dirty box is repainted by it.
585
- for (const h of [...hosts]) {
586
- for (let a = h.parentElement; a && a !== element; a = a.parentElement) if (hosts.has(a)) { hosts.delete(h); break }
587
- }
588
- let area = 0
589
- backdrops.clear()
590
- for (const h of movedFrom.keys()) if (!hosts.has(h)) movedFrom.delete(h)
591
- for (const h of hosts) {
592
- const after = rectOf(h)
593
- area += after.width * after.height
594
- if (regions.has(h)) continue
595
- const over = floaters.find((f) => f !== h && !h.contains(f) && !f.contains(h) && intersects(rectOf(f), after))
596
- if (over) {
597
- // The window has the positioned box in it too.
598
- if (movedFrom.has(h) || regionFor(h) !== h) return `${describe(over)} overlaps ${describe(h)}`
599
- regions.add(h)
600
- continue
601
- }
602
- const backdrop = backdropOf(h)
603
- if (backdrop) backdrops.set(h, backdrop)
604
- }
605
- if (area > MAX_PATCH_AREA * rootRect.width * rootRect.height) return 'patch area too large'
606
- return [...hosts]
607
- }
608
-
609
- async function tick() {
610
- if (stopped) return
611
- requestAnimationFrame(tick)
612
- const now = performance.now()
613
- if (busy || (fps && now - lastTick < 1000 / fps)) return
614
- // A running animation repaints its target every frame, and once more when it stops: the
615
- // frame before a pause or the end of a transition is not where it came to rest.
616
- if (animations) {
617
- const running = new Set()
618
- for (const a of element.getAnimations?.({ subtree: true }) || []) {
619
- if (a.playState === 'running') running.add(a.effect?.target || element)
620
- }
621
- for (const target of running) dirty.add(target)
622
- for (const target of animating) if (!running.has(target)) dirty.add(target)
623
- animating = running
624
- }
625
- if (hoverMoved) {
626
- hoverMoved = false
627
- const now = hoverMatches()
628
- for (const el of now) if (!hovered.has(el)) dirty.add(el)
629
- for (const el of hovered) if (!now.has(el) && el.isConnected) dirty.add(el)
630
- hovered = now
631
- }
632
- netTargets(observer.takeRecords(), dirty, restyled)
633
- // The keyframe waits for idle time, so it never lands on top of a burst of edits.
634
- if (!keyframeDue && !idleAsked && now - lastKeyframe > Math.max(KEYFRAME_MS, fullMs * KEYFRAME_COST)) {
635
- idleAsked = true
636
- const due = () => { keyframeDue = true; idleAsked = false }
637
- if (typeof requestIdleCallback === 'function') requestIdleCallback(due, { timeout: KEYFRAME_MS })
638
- else due()
639
- }
640
- if (!dirty.size && !forceFull && !keyframeDue) { stats.skipped++; return }
641
- busy = true
642
- lastTick = now
643
- spans = []
644
- try {
645
- const hosts = plan()
646
- spans.push([now, performance.now()])
647
- dirty.clear()
648
- restyled.clear()
649
- const reason = typeof hosts === 'string' ? hosts : null
650
- forceFull = false
651
- const out = reason ? await full() : hosts.length ? await patch(hosts) : []
652
- // Records produced by our own capture are net-zero; anything else lands next frame.
653
- netTargets(observer.takeRecords(), dirty, restyled)
654
- stats.lastMs = performance.now() - now
655
- if (out.length) onFrame?.({ full: !!reason, reason, rects: out, ms: stats.lastMs, busyMs: covered(spans), canvas })
656
- } finally {
657
- busy = false
658
- }
659
- }
660
-
661
- const ready = (async () => {
662
- busy = true
663
- try {
664
- forceFull = false
665
- // Edits from before the capture are in it. Edits landing while it runs may come after
666
- // it read the DOM: they stay dirty for the first tick. Dropping them here lost them
667
- // until a keyframe (a 1000-card lab under edits kept stale cards for seconds).
668
- await full()
669
- netTargets(observer.takeRecords(), dirty, restyled)
670
- onFrame?.({ full: true, reason: 'start', rects: [{ x: 0, y: 0, width: canvas.width, height: canvas.height }], ms: 0, busyMs: 0, canvas })
671
- } finally { busy = false }
672
- requestAnimationFrame(tick)
673
- })()
674
-
675
- return {
676
- canvas,
677
- ready,
678
- stats,
679
- stop() {
680
- stopped = true
681
- observer.disconnect()
682
- for (const type of EVENTS) element.removeEventListener(type, onEvent, true)
683
- removeEventListener('resize', onResize)
684
- },
685
- }
686
- }