dsh-ui-smooth 0.1.0 → 0.1.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/src/recycle.js CHANGED
@@ -1,262 +1,334 @@
1
- /**
2
- * Transcript recycling: keep old turns out of the render path.
3
- *
4
- * Two tiers, both gated on "old enough and cold enough". `skip` asks the browser
5
- * to stop rendering the subtree (`content-visibility: hidden`); `unmount` moves
6
- * the row's nodes into a detached fragment and holds its measured height, so the
7
- * transcript does not jump, and puts them back before the row can scroll into
8
- * view. Neither frees memory: React still owns every node.
9
- */
10
-
11
- const { debugEnabled, getConfig, loadConfig } = require('./config.js')
12
- const { releaseHistory } = require('./release.js')
13
-
14
- /* ------------------------------------------------------------------ *
15
- * Transcript recycling
16
- * ------------------------------------------------------------------ */
17
-
18
- const ROW_ATTRIBUTE = 'data-ui-smooth'
19
- const HEIGHT_PROPERTY = '--ui-smooth-height'
20
-
21
- const CONTAINMENT_CSS = `
22
- [data-conversation-content] [${ROW_ATTRIBUTE}="skip"] {
23
- content-visibility: hidden;
24
- contain-intrinsic-size: auto 320px;
25
- }
26
- [data-conversation-content] [${ROW_ATTRIBUTE}="parked"] {
27
- display: block;
28
- min-height: var(${HEIGHT_PROPERTY}, 40px);
29
- }
30
- `
31
-
32
- /**
33
- * Two tiers, both gated on "old enough and cold enough" — a turn has to
34
- * be more than N turns behind the newest one *and* have been out of the
35
- * viewport for M minutes:
36
- *
37
- * skip the browser stops rendering the subtree (`content-visibility:
38
- * hidden`), which drops its layout, style and paint work while
39
- * the DOM stays where React put it.
40
- * unmount the subtree's nodes are moved out of the document into a
41
- * detached fragment, and the row keeps its measured height, so
42
- * the transcript does not jump. Scrolling anywhere near the
43
- * row puts the nodes back before it can be seen.
44
- *
45
- * Nothing is destroyed: React still owns the nodes, and a plugin that
46
- * deleted them would fail the next time React reconciles that subtree.
47
- * Detaching is the furthest a plugin can go, and it does drop the
48
- * browser's per-node layout and style bookkeeping along with the paint.
49
- */
50
- function createRecycler(ctx) {
51
- const seenAt = new WeakMap()
52
- /** When each turn was last mounted or looked at; outlives the row itself. */
53
- const warmth = new Map()
54
- const parked = new WeakMap()
55
- let root = null
56
- let nearObserver = null
57
- let timer = 0
58
- let idleHandle = 0
59
- let releases = 0
60
-
61
- /** The top-level flow and the turn rows directly inside it. */
62
- function inspect() {
63
- const flow = document.querySelector('[data-conversation-content] [data-chat-flow]')
64
- if (flow === null) return null
65
- const rows = []
66
- const candidates = flow.querySelectorAll('[data-chat-turn]')
67
- for (const row of candidates) {
68
- if (row.closest('[data-chat-flow]') !== flow) continue
69
- const turn = Number(row.getAttribute('data-chat-turn'))
70
- if (!Number.isSafeInteger(turn)) continue
71
- rows.push({ row, turn })
72
- }
73
- return rows.length === 0 ? null : { flow, rows }
74
- }
75
-
76
- function watchNear(flow, rows) {
77
- const scroller = flow.closest('[data-conversation-scroll]')
78
- if (nearObserver === null || root !== scroller) {
79
- if (nearObserver !== null) nearObserver.disconnect()
80
- nearObserver = new IntersectionObserver((records) => {
81
- for (const record of records) {
82
- if (!record.isIntersecting) continue
83
- const seen = Date.now()
84
- seenAt.set(record.target, seen)
85
- const turn = Number(record.target.getAttribute('data-chat-turn'))
86
- if (Number.isSafeInteger(turn)) warmth.set(turn, seen)
87
- unpark(record.target)
88
- record.target.removeAttribute(ROW_ATTRIBUTE)
89
- }
90
- }, { root: scroller ?? null, rootMargin: '600px 0px 600px 0px' })
91
- root = scroller ?? null
92
- }
93
- // History arrives in chunks, so rows appear long after the observer was
94
- // built: observe on every pass or the late ones are never watched and
95
- // their parked content is never released.
96
- for (const entry of rows) nearObserver.observe(entry.row)
97
- }
98
-
99
- /**
100
- * Move a turn's content out of the document, keeping its height so the
101
- * scroll position and every measurement around it stay stable.
102
- */
103
- function park(row, measuredHeight) {
104
- if (parked.has(row)) return false
105
- if (row.contains(document.activeElement)) return false
106
- const selection = window.getSelection()
107
- const anchor = selection === null || selection === undefined ? null : selection.anchorNode
108
- if (anchor !== null && row.contains(anchor)) return false
109
-
110
- const height = Math.round(measuredHeight)
111
- const fragment = document.createDocumentFragment()
112
- while (row.firstChild !== null) fragment.appendChild(row.firstChild)
113
- row.style.setProperty(HEIGHT_PROPERTY, `${Math.max(1, height)}px`)
114
- row.setAttribute(ROW_ATTRIBUTE, 'parked')
115
- parked.set(row, fragment)
116
- return true
117
- }
118
-
119
- /** Put a parked turn's content back where it was. */
120
- function unpark(row) {
121
- const fragment = parked.get(row)
122
- if (fragment === undefined) return false
123
- while (fragment.firstChild !== null) row.appendChild(fragment.firstChild)
124
- row.style.removeProperty(HEIGHT_PROPERTY)
125
- if (row.getAttribute(ROW_ATTRIBUTE) === 'parked') row.removeAttribute(ROW_ATTRIBUTE)
126
- parked.delete(row)
127
- return true
128
- }
129
-
130
- /** Put everything back: the cheapest safe answer to any doubt. */
131
- function restoreAll() {
132
- for (const row of document.querySelectorAll(`[${ROW_ATTRIBUTE}="parked"]`)) unpark(row)
133
- for (const row of document.querySelectorAll(`[${ROW_ATTRIBUTE}="skip"]`)) row.removeAttribute(ROW_ATTRIBUTE)
134
- }
135
-
136
- function pass() {
137
- const found = inspect()
138
- if (found === null) return
139
- watchNear(found.flow, found.rows)
140
-
141
- const config = getConfig()
142
-
143
- // Streaming is the one moment the app re-renders on its own, so the pass
144
- // stays away from the transcript unless the reader asked it not to.
145
- if (!config.duringStream && document.querySelector('[data-streaming]') !== null) return
146
-
147
- let newest = 0
148
- for (const entry of found.rows) newest = Math.max(newest, entry.turn)
149
- const now = Date.now()
150
- const skipMinutes = config.skip.minutes * 60000
151
- const unmountMinutes = config.unmount.minutes * 60000
152
- const scroller = found.flow.closest('[data-conversation-scroll]')
153
- const viewport = scroller === null ? null : scroller.getBoundingClientRect()
154
- let skipped = 0
155
- let unmounted = 0
156
-
157
- if (warmth.size > 5000) warmth.clear()
158
- for (const entry of found.rows) {
159
- if (!seenAt.has(entry.row)) {
160
- seenAt.set(entry.row, now)
161
- warmth.set(entry.turn, now)
162
- }
163
- const age = newest - entry.turn
164
- const cold = now - (seenAt.get(entry.row) ?? 0)
165
- const unmount = config.unmount.enabled
166
- && age > config.unmount.turns
167
- && age > config.skip.turns
168
- && cold > unmountMinutes
169
- const skip = config.skip.enabled
170
- && age > config.skip.turns
171
- && cold > skipMinutes
172
-
173
- if (unmount) {
174
- if (entry.row.getAttribute(ROW_ATTRIBUTE) === 'parked') {
175
- unmounted += 1
176
- continue
177
- }
178
- // One read answers both questions: how tall is it, and is it far
179
- // enough from the viewport that nothing on screen moves.
180
- const box = entry.row.getBoundingClientRect()
181
- const near = viewport !== null && box.bottom > viewport.top - 800 && box.top < viewport.bottom + 800
182
- if (!near && park(entry.row, box.height)) unmounted += 1
183
- continue
184
- }
185
-
186
- unpark(entry.row)
187
- if (skip) {
188
- if (entry.row.getAttribute(ROW_ATTRIBUTE) !== 'skip') entry.row.setAttribute(ROW_ATTRIBUTE, 'skip')
189
- skipped += 1
190
- } else if (entry.row.hasAttribute(ROW_ATTRIBUTE)) {
191
- entry.row.removeAttribute(ROW_ATTRIBUTE)
192
- }
193
- }
194
-
195
- if (config.release.enabled) {
196
- const quietMs = config.release.minutes * 60000
197
- releases += releaseHistory(ctx?.sessions, config.release, (turn) => now - (warmth.get(turn) ?? 0) > quietMs)
198
- }
199
-
200
- if (debugEnabled()) {
201
- console.info(`[dsh-ui-smooth] ${skipped} turn(s) not rendered, ${unmounted} turn(s) parked outside the document, ${releases} window trim(s) total`, config)
202
- }
203
- }
204
-
205
- function schedule(delayMs) {
206
- if (idleHandle !== 0 || timer !== 0) return
207
- const run = () => {
208
- idleHandle = 0
209
- timer = 0
210
- pass()
211
- }
212
- if (typeof requestIdleCallback === 'function') {
213
- idleHandle = requestIdleCallback(run, { timeout: Math.max(500, delayMs) })
214
- } else {
215
- timer = setTimeout(run, delayMs)
216
- }
217
- }
218
-
219
- const onScroll = () => schedule(150)
220
- const onVisibility = () => {
221
- if (document.visibilityState !== 'visible') return
222
- restoreAll()
223
- schedule(0)
224
- }
225
- const onResize = () => {
226
- restoreAll()
227
- schedule(200)
228
- }
229
- const mutations = new MutationObserver(() => schedule(400))
230
- const ticker = setInterval(() => {
231
- loadConfig().then(() => schedule(0))
232
- }, 30000)
233
-
234
- document.addEventListener('scroll', onScroll, { capture: true, passive: true })
235
- document.addEventListener('visibilitychange', onVisibility)
236
- window.addEventListener('resize', onResize)
237
- mutations.observe(document.body, { childList: true, subtree: true })
238
- schedule(0)
239
-
240
- return {
241
- pass: () => pass(),
242
- restoreAll: () => restoreAll(),
243
- stats: () => ({
244
- skipped: document.querySelectorAll(`[${ROW_ATTRIBUTE}="skip"]`).length,
245
- parked: document.querySelectorAll(`[${ROW_ATTRIBUTE}="parked"]`).length,
246
- released: releases
247
- }),
248
- dispose: () => {
249
- restoreAll()
250
- if (nearObserver !== null) nearObserver.disconnect()
251
- mutations.disconnect()
252
- clearInterval(ticker)
253
- if (timer !== 0) clearTimeout(timer)
254
- if (idleHandle !== 0 && typeof cancelIdleCallback === 'function') cancelIdleCallback(idleHandle)
255
- document.removeEventListener('scroll', onScroll, { capture: true })
256
- document.removeEventListener('visibilitychange', onVisibility)
257
- window.removeEventListener('resize', onResize)
258
- }
259
- }
260
- }
261
-
262
- module.exports = { CONTAINMENT_CSS, createRecycler }
1
+ /**
2
+ * Transcript recycling: keep old turns out of the render path.
3
+ *
4
+ * Two tiers, both gated on "old enough and cold enough". `skip` asks the browser
5
+ * to stop rendering the subtree (`content-visibility: hidden`); `unmount` moves
6
+ * the row's nodes into a detached fragment and holds its measured height, so the
7
+ * transcript does not jump, and puts them back before the row can scroll into
8
+ * view. Neither frees memory: React still owns every node.
9
+ */
10
+
11
+ const { debugEnabled, getConfig, loadConfig } = require('./config.js')
12
+ const { releaseHistory } = require('./release.js')
13
+
14
+ /* ------------------------------------------------------------------ *
15
+ * Transcript recycling
16
+ * ------------------------------------------------------------------ */
17
+
18
+ const ROW_ATTRIBUTE = 'data-ui-smooth'
19
+ const HEIGHT_PROPERTY = '--ui-smooth-height'
20
+
21
+ /** How far outside the viewport a row still counts as being looked at. */
22
+ const NEAR_BAND = 800
23
+
24
+ /**
25
+ * Frames kept free of recycling work after the window comes back: the renderer
26
+ * owes that moment to everything it skipped while hidden, and the transcript is
27
+ * the heaviest thing to lay out.
28
+ */
29
+ const RESUME_GRACE_MS = 900
30
+
31
+ const CONTAINMENT_CSS = `
32
+ [data-conversation-content] [${ROW_ATTRIBUTE}] {
33
+ box-sizing: border-box;
34
+ }
35
+ [data-conversation-content] [${ROW_ATTRIBUTE}="skip"] {
36
+ content-visibility: hidden;
37
+ contain-intrinsic-size: auto var(${HEIGHT_PROPERTY}, 320px);
38
+ min-height: var(${HEIGHT_PROPERTY}, 0);
39
+ }
40
+ [data-conversation-content] [${ROW_ATTRIBUTE}="parked"] {
41
+ display: block;
42
+ min-height: var(${HEIGHT_PROPERTY}, 40px);
43
+ }
44
+ `
45
+
46
+ /**
47
+ * Two tiers, both gated on "old enough and cold enough" — a turn has to
48
+ * be more than N turns behind the newest one *and* have been out of the
49
+ * viewport for M minutes:
50
+ *
51
+ * skip the browser stops rendering the subtree (`content-visibility:
52
+ * hidden`), which drops its layout, style and paint work while
53
+ * the DOM stays where React put it.
54
+ * unmount the subtree's nodes are moved out of the document into a
55
+ * detached fragment, and the row keeps its measured height, so
56
+ * the transcript does not jump. Scrolling anywhere near the
57
+ * row puts the nodes back before it can be seen.
58
+ *
59
+ * Nothing is destroyed: React still owns the nodes, and a plugin that
60
+ * deleted them would fail the next time React reconciles that subtree.
61
+ * Detaching is the furthest a plugin can go, and it does drop the
62
+ * browser's per-node layout and style bookkeeping along with the paint.
63
+ */
64
+ function createRecycler(ctx) {
65
+ const seenAt = new WeakMap()
66
+ /** When each turn was last mounted or looked at; outlives the row itself. */
67
+ const warmth = new Map()
68
+ const parked = new WeakMap()
69
+ let root = null
70
+ let nearObserver = null
71
+ let timer = 0
72
+ let idleHandle = 0
73
+ let resumedAt = 0
74
+ let releases = 0
75
+
76
+ /** The top-level flow and the turn rows directly inside it. */
77
+ function inspect() {
78
+ const flow = document.querySelector('[data-conversation-content] [data-chat-flow]')
79
+ if (flow === null) return null
80
+ const rows = []
81
+ const candidates = flow.querySelectorAll('[data-chat-turn]')
82
+ for (const row of candidates) {
83
+ if (row.closest('[data-chat-flow]') !== flow) continue
84
+ const turn = Number(row.getAttribute('data-chat-turn'))
85
+ if (!Number.isSafeInteger(turn)) continue
86
+ rows.push({ row, turn })
87
+ }
88
+ return rows.length === 0 ? null : { flow, rows }
89
+ }
90
+
91
+ function watchNear(flow, rows) {
92
+ const scroller = flow.closest('[data-conversation-scroll]')
93
+ if (nearObserver === null || root !== scroller) {
94
+ if (nearObserver !== null) nearObserver.disconnect()
95
+ nearObserver = new IntersectionObserver((records) => {
96
+ for (const record of records) {
97
+ if (!record.isIntersecting) continue
98
+ const seen = Date.now()
99
+ seenAt.set(record.target, seen)
100
+ const turn = Number(record.target.getAttribute('data-chat-turn'))
101
+ if (Number.isSafeInteger(turn)) warmth.set(turn, seen)
102
+ unpark(record.target)
103
+ record.target.removeAttribute(ROW_ATTRIBUTE)
104
+ }
105
+ }, { root: scroller ?? null, rootMargin: '600px 0px 600px 0px' })
106
+ root = scroller ?? null
107
+ }
108
+ // History arrives in chunks, so rows appear long after the observer was
109
+ // built: observe on every pass or the late ones are never watched and
110
+ // their parked content is never released.
111
+ for (const entry of rows) nearObserver.observe(entry.row)
112
+ }
113
+
114
+ /**
115
+ * Move a turn's content out of the document, keeping its height so the
116
+ * scroll position and every measurement around it stay stable.
117
+ */
118
+ function park(row, measuredHeight) {
119
+ if (parked.has(row)) return false
120
+ if (row.contains(document.activeElement)) return false
121
+ const selection = window.getSelection()
122
+ const anchor = selection === null || selection === undefined ? null : selection.anchorNode
123
+ if (anchor !== null && row.contains(anchor)) return false
124
+
125
+ const fragment = document.createDocumentFragment()
126
+ while (row.firstChild !== null) fragment.appendChild(row.firstChild)
127
+ row.style.setProperty(HEIGHT_PROPERTY, `${Math.max(1, measuredHeight).toFixed(2)}px`)
128
+ row.setAttribute(ROW_ATTRIBUTE, 'parked')
129
+ parked.set(row, fragment)
130
+ return true
131
+ }
132
+
133
+ function keepHeight(row, measured) {
134
+ if (!(measured >= 1)) return
135
+ row.style.setProperty(HEIGHT_PROPERTY, `${measured.toFixed(2)}px`)
136
+ }
137
+
138
+ /** Put a parked turn's content back where it was. */
139
+ function unpark(row) {
140
+ const fragment = parked.get(row)
141
+ if (fragment === undefined) return false
142
+ while (fragment.firstChild !== null) row.appendChild(fragment.firstChild)
143
+ row.style.removeProperty(HEIGHT_PROPERTY)
144
+ if (row.getAttribute(ROW_ATTRIBUTE) === 'parked') row.removeAttribute(ROW_ATTRIBUTE)
145
+ parked.delete(row)
146
+ return true
147
+ }
148
+
149
+ /** Put everything back: the cheapest safe answer to any doubt. */
150
+ function restoreAll() {
151
+ for (const row of document.querySelectorAll(`[${ROW_ATTRIBUTE}="parked"]`)) unpark(row)
152
+ for (const row of document.querySelectorAll(`[${ROW_ATTRIBUTE}="skip"]`)) {
153
+ row.removeAttribute(ROW_ATTRIBUTE)
154
+ row.style.removeProperty(HEIGHT_PROPERTY)
155
+ }
156
+ }
157
+
158
+ function pass() {
159
+ const found = inspect()
160
+ if (found === null) return
161
+ watchNear(found.flow, found.rows)
162
+
163
+ const config = getConfig()
164
+
165
+ // Streaming is the one moment the app re-renders on its own, so the pass
166
+ // stays away from the transcript unless the reader asked it not to.
167
+ if (!config.duringStream && document.querySelector('[data-streaming]') !== null) return
168
+
169
+ // A hidden window paints nothing, so every measurement here would only
170
+ // cost layout for a frame nobody sees — and parking by a box measured
171
+ // while hidden risks a wrong height. The next visible frame re-measures.
172
+ if (document.visibilityState !== 'visible') return
173
+
174
+ let newest = 0
175
+ for (const entry of found.rows) newest = Math.max(newest, entry.turn)
176
+ const now = Date.now()
177
+ // The app is still catching up on the frames the hidden window skipped;
178
+ // measuring the transcript in the same window would queue behind it.
179
+ if (now - resumedAt < RESUME_GRACE_MS) {
180
+ schedule(RESUME_GRACE_MS - (now - resumedAt) + 50)
181
+ return
182
+ }
183
+ const skipMinutes = config.skip.minutes * 60000
184
+ const unmountMinutes = config.unmount.minutes * 60000
185
+ const scroller = found.flow.closest('[data-conversation-scroll]')
186
+ const viewport = scroller === null
187
+ ? { top: 0, bottom: window.innerHeight }
188
+ : scroller.getBoundingClientRect()
189
+
190
+ // Read every box before the first mutation: interleaving the two forces a
191
+ // fresh layout per row, which is the whole transcript's height at once.
192
+ const boxes = new Map()
193
+ const slots = new Map()
194
+ const gap = parseFloat(getComputedStyle(found.flow).rowGap)
195
+ const flowBottom = found.flow.getBoundingClientRect().bottom
196
+ let previous = null
197
+ for (const entry of found.rows) {
198
+ const box = entry.row.getBoundingClientRect()
199
+ boxes.set(entry.row, box)
200
+ // The space a row takes in the flow is not its border box: a turn's
201
+ // children carry margins that collapse through the row and count in the
202
+ // layout without ever landing inside its measured height. Taking the gap
203
+ // to the next row keeps that space, so parking one row moves nothing
204
+ // below it.
205
+ if (previous !== null) slots.set(previous.row, previous.top === null ? box.height : box.top - previous.top - (Number.isFinite(gap) ? gap : 0))
206
+ previous = { row: entry.row, top: box.top }
207
+ }
208
+ if (previous !== null) slots.set(previous.row, flowBottom - previous.top - (Number.isFinite(gap) ? gap : 0))
209
+
210
+ let skipped = 0
211
+ let unmounted = 0
212
+
213
+ if (warmth.size > 5000) warmth.clear()
214
+ for (const entry of found.rows) {
215
+ const box = boxes.get(entry.row)
216
+ // A row in or near the viewport was just looked at, whatever the
217
+ // observer has had time to report: keep it warm and leave it alone.
218
+ const near = box.bottom > viewport.top - NEAR_BAND && box.top < viewport.bottom + NEAR_BAND
219
+ if (near || !seenAt.has(entry.row)) {
220
+ seenAt.set(entry.row, now)
221
+ warmth.set(entry.turn, now)
222
+ }
223
+ const age = newest - entry.turn
224
+ const cold = now - (seenAt.get(entry.row) ?? 0)
225
+ const unmount = config.unmount.enabled
226
+ && age > config.unmount.turns
227
+ && age > config.skip.turns
228
+ && cold > unmountMinutes
229
+ const skip = config.skip.enabled
230
+ && age > config.skip.turns
231
+ && cold > skipMinutes
232
+
233
+ if (unmount) {
234
+ if (entry.row.getAttribute(ROW_ATTRIBUTE) === 'parked') {
235
+ unmounted += 1
236
+ continue
237
+ }
238
+ if (!near && box.height >= 1 && park(entry.row, slots.get(entry.row) ?? box.height)) unmounted += 1
239
+ continue
240
+ }
241
+
242
+ unpark(entry.row)
243
+ // A row with nothing to measure has nothing to hold open either: skipping
244
+ // it would leave the transcript a 320px placeholder it never had.
245
+ if (skip && box.height >= 1) {
246
+ if (entry.row.getAttribute(ROW_ATTRIBUTE) !== 'skip') {
247
+ keepHeight(entry.row, box.height)
248
+ entry.row.setAttribute(ROW_ATTRIBUTE, 'skip')
249
+ }
250
+ skipped += 1
251
+ } else if (entry.row.hasAttribute(ROW_ATTRIBUTE)) {
252
+ entry.row.removeAttribute(ROW_ATTRIBUTE)
253
+ entry.row.style.removeProperty(HEIGHT_PROPERTY)
254
+ }
255
+ }
256
+
257
+ if (config.release.enabled) {
258
+ const quietMs = config.release.minutes * 60000
259
+ releases += releaseHistory(ctx?.sessions, config.release, (turn) => now - (warmth.get(turn) ?? 0) > quietMs)
260
+ }
261
+
262
+ if (debugEnabled()) {
263
+ console.info(`[dsh-ui-smooth] ${skipped} turn(s) not rendered, ${unmounted} turn(s) parked outside the document, ${releases} window trim(s) total`, config)
264
+ }
265
+ }
266
+
267
+ function schedule(delayMs) {
268
+ if (idleHandle !== 0 || timer !== 0) return
269
+ const run = () => {
270
+ idleHandle = 0
271
+ timer = 0
272
+ pass()
273
+ }
274
+ if (typeof requestIdleCallback === 'function') {
275
+ idleHandle = requestIdleCallback(run, { timeout: Math.max(500, delayMs) })
276
+ } else {
277
+ timer = setTimeout(run, delayMs)
278
+ }
279
+ }
280
+
281
+ const onScroll = () => schedule(150)
282
+ const onVisibility = () => {
283
+ // Coming back must not put every parked row back into the document at
284
+ // once: that lays the whole transcript out in one frame, on top of the
285
+ // app's own catch-up. The observer returns only the rows near the
286
+ // viewport, and this pass waits out the grace period first.
287
+ if (document.visibilityState !== 'visible') return
288
+ resumedAt = Date.now()
289
+ schedule(RESUME_GRACE_MS + 200)
290
+ }
291
+ const onResize = () => {
292
+ // Restoring a minimized window fires this, and putting every parked row
293
+ // back here is the same whole-transcript burst the visibility handler
294
+ // used to cause. The heights held for distant rows are stale, but only
295
+ // the ones on screen need a real number now: the near band returns
296
+ // those, and the rest re-measure when they are next looked at.
297
+ resumedAt = Date.now()
298
+ schedule(RESUME_GRACE_MS + 200)
299
+ }
300
+ const mutations = new MutationObserver(() => schedule(400))
301
+ const ticker = setInterval(() => {
302
+ if (document.visibilityState !== 'visible') return
303
+ loadConfig().then(() => schedule(0))
304
+ }, 30000)
305
+
306
+ document.addEventListener('scroll', onScroll, { capture: true, passive: true })
307
+ document.addEventListener('visibilitychange', onVisibility)
308
+ window.addEventListener('resize', onResize)
309
+ mutations.observe(document.body, { childList: true, subtree: true })
310
+ schedule(0)
311
+
312
+ return {
313
+ pass: () => pass(),
314
+ restoreAll: () => restoreAll(),
315
+ stats: () => ({
316
+ skipped: document.querySelectorAll(`[${ROW_ATTRIBUTE}="skip"]`).length,
317
+ parked: document.querySelectorAll(`[${ROW_ATTRIBUTE}="parked"]`).length,
318
+ released: releases
319
+ }),
320
+ dispose: () => {
321
+ restoreAll()
322
+ if (nearObserver !== null) nearObserver.disconnect()
323
+ mutations.disconnect()
324
+ clearInterval(ticker)
325
+ if (timer !== 0) clearTimeout(timer)
326
+ if (idleHandle !== 0 && typeof cancelIdleCallback === 'function') cancelIdleCallback(idleHandle)
327
+ document.removeEventListener('scroll', onScroll, { capture: true })
328
+ document.removeEventListener('visibilitychange', onVisibility)
329
+ window.removeEventListener('resize', onResize)
330
+ }
331
+ }
332
+ }
333
+
334
+ module.exports = { CONTAINMENT_CSS, createRecycler }