@zumer/snapdom-plugins 4.4.0 → 4.4.1-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,8 @@
1
1
  # @zumer/snapdom-plugins
2
2
 
3
+ [![NPM version](https://img.shields.io/npm/v/@zumer/snapdom-plugins?style=flat-square&label=Plugins)](https://www.npmjs.com/package/@zumer/snapdom-plugins)
4
+ [![Core version](https://img.shields.io/npm/v/@zumer/snapdom?style=flat-square&label=SnapDOM)](https://www.npmjs.com/package/@zumer/snapdom)
5
+
3
6
  Official plugins for [SnapDOM](https://github.com/zumerlab/snapdom), a high-performance DOM engine
4
7
  that exports a rendered element as PNG, SVG or canvas in the browser. Core exports images and
5
8
  canvases; this package adds HTML, structured context, element maps, PDF, editable vectors, ASCII,
@@ -178,9 +181,9 @@ The built-in mask without custom selectors permits reuse of unchanged captures.
178
181
  masks and nonempty `selector`, `blocks` or `attributes` rules run on every capture. Changed
179
182
  content runs the full pipeline so no field skips redaction.
180
183
 
181
- Nonempty `blocks` or `attributes` rules add a final `beforeRender` pass. In builds with the
182
- experimental `engine: 'html-in-canvas'` enabled, that pass makes the capture use the SVG
183
- renderer. Field-only redaction does not add this pass.
184
+ Nonempty `blocks` or `attributes` rules add a final `beforeRender` pass, which makes a capture
185
+ requested with `engine: 'html-in-canvas'` use the SVG renderer. Field-only redaction does not
186
+ add this pass.
184
187
 
185
188
  `agent-map` and `context-export` omit sensitive values and mask other typed values in their
186
189
  structured state fields. Ordinary page text and labels remain. An attached image still
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zumer/snapdom-plugins",
3
- "version": "4.4.0",
3
+ "version": "4.4.1-dev.0",
4
4
  "description": "Official plugins for SnapDOM",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -38,6 +38,6 @@ export interface RedactInputsOptions {
38
38
  * Optional blocks exclude whole subtrees; attribute rules remove named attributes. The live DOM is unchanged.
39
39
  * These rules do not search captured text or images for sensitive content.
40
40
  * The default mask without selectors permits unchanged-repeat memoization; custom masks and selectors run every capture.
41
- * Nonempty blocks/attribute rules add a beforeRender pass, so experimental html-in-canvas captures use SVG.
41
+ * Nonempty blocks/attribute rules add a beforeRender pass, so html-in-canvas captures use SVG.
42
42
  */
43
43
  export declare function redactInputs(options?: RedactInputsOptions): SnapdomPlugin;
package/stream/README.md CHANGED
@@ -21,8 +21,11 @@ live.stop();
21
21
 
22
22
  The first frame is a full capture. After that, every change (mutations, typing, focus, hover,
23
23
  running animations) is traced to the nearest box that can be repainted on its own, and only
24
- that subtree is captured and drawn into its rect. A frame that cannot be patched exactly is a
25
- full frame, and `frame.reason` says why (`'root resized'`, `'no host for <div.x>'`, ...).
24
+ that subtree is captured and drawn into its rect. A change in a box that cannot (a value on a
25
+ translucent card, a row under a badge) repaints a window of the element instead: a `clip`
26
+ capture of that box, with everything that paints there. The pointer repaints only what a
27
+ `:hover` rule restyles. A frame that cannot be patched exactly is a full frame, and
28
+ `frame.reason` says why (`'root resized'`, `'no host for <div.x>'`, ...).
26
29
  A keyframe in idle time heals anything the change tracking could not see, at most every 2 s
27
30
  and never more than 2% of the main thread.
28
31
 
@@ -10,8 +10,11 @@
10
10
  * was restyled hands the change to the enclosing box that did not; an absolutely positioned
11
11
  * box over a solid or clear backdrop may move and resize itself, since it pushes nothing.
12
12
  * Only that subtree is captured, laid out at its subpixel phase, and drawn over its backdrop
13
- * or where it is fully opaque. Anything this cannot prove is a full frame, with the reason
14
- * on the frame.
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.
15
18
  *
16
19
  * Measured 2026-10-23, 1000px grid, one card's text changed per frame, median ms per frame
17
20
  * (full / patch): 400 cards Chromium 11.7 / 4.2, Firefox 28 / 4, WebKit 20 / 4; 2000 cards
@@ -34,6 +37,13 @@ const WEBKIT = typeof navigator !== 'undefined' && (/ipad|iphone|ipod/i.test(nav
34
37
  (/applewebkit/i.test(navigator.userAgent) && !/chrome|chromium|crios|edg|opr|android/i.test(navigator.userAgent)))
35
38
 
36
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
37
47
  /** A patch larger than this share of the frame costs about what a full frame does. */
38
48
  const MAX_PATCH_AREA = 0.5
39
49
  /** Self-healing keyframe: anything the heuristics missed lasts at most this long, or 50
@@ -57,10 +67,48 @@ function hasEffect(cs) {
57
67
  cs.clipPath !== 'none' || (cs.backdropFilter && cs.backdropFilter !== 'none')
58
68
  }
59
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
+
60
75
  function clips(cs) {
61
76
  return cs.overflowX !== 'visible' || cs.overflowY !== 'visible'
62
77
  }
63
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
+
64
112
  function inside(a, b) {
65
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
66
114
  }
@@ -139,8 +187,9 @@ async function decode(url) {
139
187
  * @param {boolean} [options.patches=true] - false repaints full frames only (the baseline).
140
188
  * @param {boolean} [options.animations=true] - false stops following running animations and
141
189
  * transitions: an animated box keeps its last drawn pixels until a patch, a full frame or the
142
- * keyframe repaints it. A transparent spinner has no host, so by default every tick is a full
143
- * frame (Zumly views at dpr 2, fps 5: 109 ms a frame, against 9-13 ms patches without it).
190
+ * keyframe repaints it. A transparent spinner has no host and turns its own box, so by default
191
+ * nearly every tick is a full frame (Zumly views at dpr 2, fps 5: 109 ms a frame, against
192
+ * 9-13 ms patches without it).
144
193
  * @returns {{canvas: HTMLCanvasElement, stop: () => void, ready: Promise<void>, stats: object}}
145
194
  */
146
195
  export function stream(element, options = {}) {
@@ -154,8 +203,14 @@ export function stream(element, options = {}) {
154
203
  const rects = new WeakMap() // element -> rect at the last paint that covered it
155
204
  const backdrops = new Map() // this frame's hosts that draw over a solid colour
156
205
  const movedFrom = new Map() // this frame's out-of-flow hosts that moved -> their old rect
206
+ const regions = new Set() // this frame's hosts repainted as a window of the root
157
207
  const stats = { full: 0, patch: 0, skipped: 0, lastMs: 0 }
158
208
  let floaters = []
209
+ let glass = [] // backdrop-filter boxes: a change under one shows through its blur
210
+ let hoverList = null // the :hover selectors at the last full frame, null if unreadable
211
+ let hovered = new Set() // what they matched at the last look
212
+ let hoverMoved = false
213
+ let nodes = 0 // in the root at the last full frame, the root included
159
214
  let forceFull = true
160
215
  let lastKeyframe = 0
161
216
  let keyframeDue = false // set from idle time once the keyframe interval has passed
@@ -171,6 +226,13 @@ export function stream(element, options = {}) {
171
226
  const observer = new MutationObserver(records => netTargets(records, dirty, restyled))
172
227
  observer.observe(element, { subtree: true, childList: true, attributes: true, characterData: true, attributeOldValue: true, characterDataOldValue: true })
173
228
  const onEvent = (e) => {
229
+ // A pointer that crosses boxes no :hover rule matches changes no pixel. Moving over the
230
+ // gaps of a 48-tile board made its root dirty, and every move a 300 ms full frame (Zumly,
231
+ // dpr 2). A shadow tree's event arrives at its host, and its sheets were not read.
232
+ if (hoverList !== null && HOVER_EVENTS.has(e.type) && e.composedPath()[0] === e.target) {
233
+ hoverMoved = true
234
+ return
235
+ }
174
236
  dirty.add(e.target)
175
237
  if (e.relatedTarget && element.contains(e.relatedTarget)) dirty.add(e.relatedTarget)
176
238
  }
@@ -207,14 +269,26 @@ export function stream(element, options = {}) {
207
269
  function snapshotLayout() {
208
270
  rootRect = element.getBoundingClientRect()
209
271
  floaters = []
210
- for (const el of element.querySelectorAll('*')) {
272
+ glass = []
273
+ const all = element.querySelectorAll('*')
274
+ nodes = all.length + 1
275
+ for (const el of all) {
211
276
  rects.set(el, rectOf(el))
212
277
  const cs = getComputedStyle(el)
213
278
  if (cs.position === 'absolute' || cs.position === 'fixed' || cs.position === 'sticky' ||
214
279
  (cs.position === 'relative' && cs.zIndex !== 'auto') || cs.transform !== 'none') floaters.push(el)
280
+ if (cs.backdropFilter && cs.backdropFilter !== 'none') glass.push(el)
215
281
  }
216
282
  }
217
283
 
284
+ /** The elements the :hover rules match now, the root included. */
285
+ function hoverMatches() {
286
+ if (!hoverList) return new Set()
287
+ const out = new Set(element.querySelectorAll(hoverList))
288
+ if (element.matches(hoverList)) out.add(element)
289
+ return out
290
+ }
291
+
218
292
  /** The box a change to `node` can be repainted through, or null for a full frame. */
219
293
  function hostFor(node) {
220
294
  let el = node?.nodeType === 1 ? node : node?.parentElement
@@ -227,8 +301,8 @@ export function stream(element, options = {}) {
227
301
  for (let i = start; i < chain.length; i++) {
228
302
  const cs = styles[i]
229
303
  if (!opaqueColor(cs.backgroundColor)) continue
230
- // Visible overflow paints outside the box, over pixels the patch does not repaint.
231
- if (!clips(cs) && (chain[i].scrollWidth > chain[i].clientWidth + 1 || chain[i].scrollHeight > chain[i].clientHeight + 1)) continue
304
+ // Over pixels the patch does not repaint.
305
+ if (overflows(chain[i], cs)) continue
232
306
  // A box a clipping ancestor cuts, past its edges or into a rounded corner, would be
233
307
  // drawn whole: a row half out of a 40px scroller painted its hidden half (19200 px
234
308
  // off). The host is the box itself, so the test is on its rect, not on the changed
@@ -242,6 +316,24 @@ export function stream(element, options = {}) {
242
316
  return null
243
317
  }
244
318
 
319
+ /** The box a change to `node` stayed inside, to repaint as a window of the root, or null.
320
+ * The window has everything that paints in it, so the box needs no backdrop and may sit
321
+ * under positioned boxes; it must keep its rect, paint nothing new outside itself, and
322
+ * have no blur spread the change past it: a blurring ancestor, or a glass box over it. */
323
+ function regionFor(node) {
324
+ let el = node?.nodeType === 1 ? node : node?.parentElement
325
+ for (let a = el; a; a = a === element ? null : a.parentElement) if (spreads(getComputedStyle(a))) return null
326
+ for (; el && el !== element; el = el.parentElement) {
327
+ const r = rectOf(el)
328
+ const cs = getComputedStyle(el)
329
+ if (!r.width || !r.height || !sameRect(rects.get(el) || {}, r) || overflows(el, cs)) continue
330
+ if (restyled.has(el) && outerInk(cs)) continue
331
+ for (const g of glass) if (!g.contains(el) && !el.contains(g) && intersects(rectOf(g), r)) return null
332
+ return el
333
+ }
334
+ return null
335
+ }
336
+
245
337
  async function full() {
246
338
  const t0 = performance.now()
247
339
  // A full frame is the one long task of a stream; 'auto' lets a long clone yield (#503).
@@ -257,6 +349,10 @@ export function stream(element, options = {}) {
257
349
  ox = contentX * k
258
350
  oy = contentY * k
259
351
  snapshotLayout()
352
+ // Read again at every full frame, so a sheet added later counts from the next keyframe.
353
+ const sels = hoverSelectors(element)
354
+ hoverList = sels && sels.length * nodes <= HOVER_BUDGET ? sels.join(',') : null
355
+ try { hovered = hoverMatches() } catch { hoverList = null }
260
356
  lastKeyframe = performance.now()
261
357
  keyframeDue = false
262
358
  fullMs = lastKeyframe - t0
@@ -271,8 +367,7 @@ export function stream(element, options = {}) {
271
367
  * other box on the whole-pixel rect around the host, or around `old`, where a moved host
272
368
  * was. */
273
369
  function backdropOf(host, old) {
274
- const cs = getComputedStyle(host)
275
- if (cs.boxShadow !== 'none' || (cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0)) return null
370
+ if (outerInk(getComputedStyle(host))) return null
276
371
  let color = null
277
372
  for (let a = host.parentElement; a && !color; a = a === element ? null : a.parentElement) {
278
373
  const s = getComputedStyle(a)
@@ -325,7 +420,7 @@ export function stream(element, options = {}) {
325
420
  lctx.fillRect(0, 0, w, h)
326
421
  }
327
422
  lctx.drawImage(src, 0, 0, w, h)
328
- return { layer, x, y, w, h, backdrop, host, drawnAt: r }
423
+ return { layer, x, y, w, h, replace: true, host, drawnAt: r }
329
424
  }
330
425
  // Otherwise keep only the pixels the box covers fully. Inside an opaque box that is
331
426
  // everything; what is left are its antialiased edges and rounded corners, which did not
@@ -340,11 +435,33 @@ export function stream(element, options = {}) {
340
435
  return { layer, x, y, w, h, host, drawnAt: r }
341
436
  }
342
437
 
438
+ /** Capture the root clipped to `host`'s box on whole canvas pixels: the full frame's
439
+ * pixels for that window. A value on a glass tile of the Zumly board (48 tiles, dpr 2):
440
+ * 9 ms against 323 for the full frame, identical to it. A window over the tile's rounded
441
+ * corners differed on the antialiased arc, by up to 28 levels on 45 pixels (cause not
442
+ * found). Sixteen windows at once cost 101 ms; one window per row of them cost 149, since a
443
+ * row keeps every tile in it. */
444
+ async function renderRegion(host) {
445
+ const drawnAt = rectOf(host)
446
+ const r = pixelRect(drawnAt)
447
+ const res = await 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 } })
448
+ const { vbW, vbH, contentX = 0, contentY = 0, clip } = res.meta
449
+ const src = WEBKIT ? await res.toCanvas() : await decode(res.url)
450
+ const x = Math.round(ox + r.left * k), y = Math.round(oy + r.top * k)
451
+ const w = Math.round(ox + r.right * k) - x, h = Math.round(oy + r.bottom * k) - y
452
+ // The image starts contentX before the window, over pixels the clip culled: keep the window.
453
+ const layer = document.createElement('canvas')
454
+ layer.width = w
455
+ layer.height = h
456
+ 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))
457
+ return { layer, x, y, w, h, replace: true, host, drawnAt }
458
+ }
459
+
343
460
  async function patch(hosts) {
344
461
  // Captures and decodes overlap; the draws then land in one synchronous pass, so the
345
462
  // canvas never shows half a frame. Three hosts a frame (clock, KPI, list row) in
346
463
  // demos/stream-webgl.html: 11.9 ms one after another.
347
- const layers = await Promise.all(hosts.map(renderPatch))
464
+ const layers = await Promise.all(hosts.map((h) => regions.has(h) ? renderRegion(h) : renderPatch(h)))
348
465
  const out = []
349
466
  // The canvas clips draws past its edge; a reported rect must be clipped too, or a box
350
467
  // sliding off the stage (the lower third hides to left:-720px) hands texSubImage2D a
@@ -361,9 +478,9 @@ export function stream(element, options = {}) {
361
478
  paintBackdrop(backdrops.get(host), x, y, w, h)
362
479
  report(x, y, w, h)
363
480
  }
364
- for (const { layer, x, y, w, h, backdrop } of layers) {
365
- // A backdrop layer is the full frame's pixels for its whole rect: replace, not blend.
366
- if (backdrop) ctx.clearRect(x, y, w, h)
481
+ for (const { layer, x, y, w, h, replace } of layers) {
482
+ // A backdrop or window layer is the full frame's pixels for its whole rect: replace, not blend.
483
+ if (replace) ctx.clearRect(x, y, w, h)
367
484
  ctx.drawImage(layer, x, y)
368
485
  report(x, y, w, h)
369
486
  }
@@ -387,6 +504,7 @@ export function stream(element, options = {}) {
387
504
  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'
388
505
  rootRect = now
389
506
  const hosts = new Set()
507
+ regions.clear()
390
508
  for (const node of dirty) {
391
509
  if (!node?.isConnected) return 'node removed'
392
510
  let host = hostFor(node)
@@ -406,6 +524,7 @@ export function stream(element, options = {}) {
406
524
  movedFrom.set(p, old)
407
525
  }
408
526
  }
527
+ if (!host && (host = regionFor(node))) regions.add(host)
409
528
  if (!host) return `no host for ${describe(node)}`
410
529
  hosts.add(host)
411
530
  }
@@ -417,14 +536,18 @@ export function stream(element, options = {}) {
417
536
  backdrops.clear()
418
537
  for (const h of movedFrom.keys()) if (!hosts.has(h)) movedFrom.delete(h)
419
538
  for (const h of hosts) {
420
- const backdrop = backdropOf(h)
421
- if (backdrop) backdrops.set(h, backdrop)
422
539
  const after = rectOf(h)
423
540
  area += after.width * after.height
424
- for (const f of floaters) {
425
- if (f === h || h.contains(f) || f.contains(h)) continue
426
- if (intersects(rectOf(f), after)) return `${describe(f)} overlaps ${describe(h)}`
541
+ if (regions.has(h)) continue
542
+ const over = floaters.find((f) => f !== h && !h.contains(f) && !f.contains(h) && intersects(rectOf(f), after))
543
+ if (over) {
544
+ // The window has the positioned box in it too.
545
+ if (movedFrom.has(h) || regionFor(h) !== h) return `${describe(over)} overlaps ${describe(h)}`
546
+ regions.add(h)
547
+ continue
427
548
  }
549
+ const backdrop = backdropOf(h)
550
+ if (backdrop) backdrops.set(h, backdrop)
428
551
  }
429
552
  if (area > MAX_PATCH_AREA * rootRect.width * rootRect.height) return 'patch area too large'
430
553
  return [...hosts]
@@ -446,6 +569,13 @@ export function stream(element, options = {}) {
446
569
  for (const target of animating) if (!running.has(target)) dirty.add(target)
447
570
  animating = running
448
571
  }
572
+ if (hoverMoved) {
573
+ hoverMoved = false
574
+ const now = hoverMatches()
575
+ for (const el of now) if (!hovered.has(el)) dirty.add(el)
576
+ for (const el of hovered) if (!now.has(el) && el.isConnected) dirty.add(el)
577
+ hovered = now
578
+ }
449
579
  netTargets(observer.takeRecords(), dirty, restyled)
450
580
  // The keyframe waits for idle time, so it never lands on top of a burst of edits.
451
581
  if (!keyframeDue && !idleAsked && now - lastKeyframe > Math.max(KEYFRAME_MS, fullMs * KEYFRAME_COST)) {