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/lib/client.js CHANGED
@@ -1,1483 +1,1665 @@
1
- /**
2
- * GENERATED FILE — do not edit. Sources live in src/, built by scripts/build.mjs.
3
- *
4
- * dsh-ui-smooth — client half.
5
- *
6
- * Four jobs, all of them about keeping the Web UI's main thread and heap free:
7
- *
8
- * 1. Animation budget. Idle CPU comes from decorative animations that run
9
- * forever on properties the renderer cannot composite: `infinite` on `left`
10
- * relayouts its subtree every frame, and `background-position` behind
11
- * `background-clip: text` re-rasterizes glyphs. Those are rewritten onto
12
- * `transform` (same trajectory) or stepped with `steps()`. Finite
13
- * animations, composited animations and `prefers-reduced-motion` users are
14
- * left alone.
15
- *
16
- * 2. Transcript recycling. The transcript mounts every entry of the session and
17
- * collapsed rows keep their subtrees (`hidden="until-found"`), so a long
18
- * session costs more on every interaction. Turns that are old *and* have not
19
- * been looked at for a while are put behind CSS containment, or detached into
20
- * a fragment with their height held. Detaching is as far as the DOM alone can
21
- * go: React still holds every node of that subtree.
22
- *
23
- * 3. Aggressive release. The only way to hand a turn's memory back is to make
24
- * React let go of it, which means unmounting, not detaching. This tier drops
25
- * the oldest part of the session's loaded history window through the session
26
- * controller's own window API, so React unmounts those turns and their fibers
27
- * release the DOM they own. `hasMore` stays true, so 加载更早 pages the same
28
- * history back from disk.
29
- *
30
- * 4. Settings. Every threshold and the desktop background-throttle switch live
31
- * in one config owned by the host half, edited in Settings → 流畅性.
32
- */
33
-
34
- window.__ModuleLoader__.load({
35
- id: 'dsh-ui-smooth',
36
- factory: (requireExternal) => {
37
- const registry = {}
38
- const cache = {}
39
-
40
- function require(specifier) {
41
- if (!specifier.startsWith('.')) return requireExternal(specifier)
42
- const id = specifier.endsWith('.js') ? specifier : `${specifier}.js`
43
- const cached = cache[id]
44
- if (cached !== undefined) return cached.exports
45
- const factory = registry[id]
46
- if (factory === undefined) throw new Error(`dsh-ui-smooth: unknown module ${id}`)
47
- const module = { exports: {} }
48
- cache[id] = module
49
- factory(module, module.exports, require)
50
- return module.exports
51
- }
52
-
53
- registry['./animate.js'] = function (module, exports, require) {
54
- /**
55
- * The page keeps adding stylesheets, so the plan is rebuilt whenever one arrives
56
- * and the result lives in a single injected stylesheet.
57
- */
58
-
59
- const { debugEnabled, getConfig, onConfig } = require('./config.js')
60
- const { planSheets } = require('./animations.js')
61
-
62
- const STYLE_ID = 'dsh-ui-smooth/animations'
63
-
64
- function pageSheets(own) {
65
- const sheets = []
66
- const adopted = document.adoptedStyleSheets
67
- if (adopted !== undefined && adopted !== null) {
68
- for (const sheet of adopted) sheets.push(sheet)
69
- }
70
- const list = document.styleSheets
71
- for (let index = 0; index < list.length; index += 1) {
72
- const sheet = list[index]
73
- if (sheet === own) continue
74
- sheets.push(sheet)
75
- }
76
- return sheets
77
- }
78
-
79
- function installAnimations() {
80
- const element = document.createElement('style')
81
- element.id = STYLE_ID
82
- element.setAttribute('data-dsh-ui-smooth', '')
83
- const host = document.head ?? document.documentElement
84
- host.appendChild(element)
85
-
86
- const state = { entries: [], css: '', scans: 0 }
87
- let scheduled = false
88
- let disposed = false
89
-
90
- /** The switch is on by default; off means the page's own animations stay as written. */
91
- const enabled = () => getConfig().animations !== false
92
-
93
- const clear = () => {
94
- if (state.css === '') return
95
- state.css = ''
96
- state.entries = []
97
- element.textContent = ''
98
- }
99
-
100
- const run = () => {
101
- if (disposed) return
102
- if (!enabled()) {
103
- clear()
104
- return
105
- }
106
- const plan = planSheets(pageSheets(element.sheet))
107
- state.entries = plan.entries
108
- state.scans += 1
109
- if (plan.css !== state.css) {
110
- state.css = plan.css
111
- element.textContent = plan.css
112
- }
113
- if (debugEnabled()) {
114
- console.info(`[dsh-ui-smooth] ${plan.entries.length} idle animation(s) moved off the layout/paint path`, plan.entries)
115
- }
116
- }
117
-
118
- const schedule = () => {
119
- if (scheduled || disposed || !enabled()) return
120
- scheduled = true
121
- requestAnimationFrame(() => {
122
- scheduled = false
123
- run()
124
- })
125
- }
126
-
127
- const observer = new MutationObserver((records) => {
128
- for (const record of records) {
129
- if (record.target === element) continue
130
- for (const node of record.addedNodes ?? []) {
131
- if (node === element) continue
132
- if (node.nodeType === 1) {
133
- const tag = node.tagName
134
- if (tag === 'STYLE' || tag === 'LINK') return schedule()
135
- }
136
- }
137
- for (const node of record.removedNodes ?? []) {
138
- if (node !== element && node.nodeType === 1) {
139
- const tag = node.tagName
140
- if (tag === 'STYLE' || tag === 'LINK') return schedule()
141
- }
142
- }
143
- }
144
- })
145
- observer.observe(host, { childList: true, subtree: true })
146
-
147
- const onResource = (event) => {
148
- if (event.target instanceof HTMLLinkElement) schedule()
149
- }
150
- document.addEventListener('load', onResource, true)
151
- document.addEventListener('error', onResource, true)
152
-
153
- const stopListening = onConfig(() => {
154
- if (enabled()) schedule()
155
- else clear()
156
- })
157
-
158
- run()
159
- schedule()
160
-
161
- return {
162
- status: () => ({ scans: state.scans, entries: state.entries.slice() }),
163
- rescan: () => {
164
- run()
165
- return state.entries.slice()
166
- },
167
- restore: () => {
168
- element.textContent = ''
169
- state.css = ''
170
- state.entries = []
171
- },
172
- dispose: () => {
173
- disposed = true
174
- stopListening()
175
- observer.disconnect()
176
- document.removeEventListener('load', onResource, true)
177
- document.removeEventListener('error', onResource, true)
178
- element.remove()
179
- }
180
- }
181
- }
182
-
183
- module.exports = { installAnimations }
184
- }
185
-
186
- registry['./animations.js'] = function (module, exports, require) {
187
- /**
188
- * Animation budget: find the expensive idle animations and rewrite the rule.
189
- *
190
- * Only `infinite` animations are touched. A sweep on the layout path becomes the
191
- * same trajectory on `transform`; everything else is stepped down to a rate the
192
- * renderer can afford. Finite, composited and reduced-motion animations are left
193
- * exactly as they are.
194
- */
195
-
196
- /**
197
- * Update rates kept for a coarsened animation. A layout update is cheap per
198
- * sample and visibly choppy when under-sampled, so it keeps more steps; a
199
- * paint-path shimmer re-rasterizes its glyphs on every update, so it is stepped
200
- * harder.
201
- */
202
- const LAYOUT_UPDATES_PER_SECOND = 8
203
- const PAINT_UPDATES_PER_SECOND = 4
204
-
205
- /* ------------------------------------------------------------------ *
206
- * Property classification
207
- * ------------------------------------------------------------------ */
208
-
209
- const LAYOUT_PROPERTIES = new Set([
210
- 'left', 'right', 'top', 'bottom', 'inset',
211
- 'inset-block', 'inset-block-start', 'inset-block-end',
212
- 'inset-inline', 'inset-inline-start', 'inset-inline-end',
213
- 'width', 'height', 'min-width', 'min-height', 'max-width', 'max-height',
214
- 'inline-size', 'block-size', 'min-inline-size', 'min-block-size', 'max-inline-size', 'max-block-size',
215
- 'margin', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
216
- 'margin-block', 'margin-block-start', 'margin-block-end',
217
- 'margin-inline', 'margin-inline-start', 'margin-inline-end',
218
- 'padding', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
219
- 'padding-block', 'padding-block-start', 'padding-block-end',
220
- 'padding-inline', 'padding-inline-start', 'padding-inline-end',
221
- 'border-width', 'border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width',
222
- 'gap', 'row-gap', 'column-gap', 'flex-basis',
223
- 'grid-template-columns', 'grid-template-rows', 'grid-auto-columns', 'grid-auto-rows',
224
- 'font-size', 'line-height', 'letter-spacing', 'word-spacing', 'text-indent',
225
- 'column-width', 'column-count'
226
- ])
227
-
228
- const PAINT_PROPERTIES = new Set([
229
- 'background', 'background-image', 'background-position',
230
- 'background-position-x', 'background-position-y', 'background-size'
231
- ])
232
-
233
- /* ------------------------------------------------------------------ *
234
- * CSSOM helpers
235
- * ------------------------------------------------------------------ */
236
-
237
- function splitList(value) {
238
- const parts = []
239
- let depth = 0
240
- let current = ''
241
- for (const character of value ?? '') {
242
- if (character === '(') depth += 1
243
- else if (character === ')') depth = Math.max(0, depth - 1)
244
- if (character === ',' && depth === 0) {
245
- parts.push(current.trim())
246
- current = ''
247
- continue
248
- }
249
- current += character
250
- }
251
- if (current.trim() !== '') parts.push(current.trim())
252
- return parts
253
- }
254
-
255
- function at(list, index) {
256
- if (list.length === 0) return ''
257
- return list[index % list.length]
258
- }
259
-
260
- function parseTime(value) {
261
- const match = /^(-?\d*\.?\d+)(ms|s)$/.exec((value ?? '').trim())
262
- if (match === null) return 0
263
- const amount = Number(match[1])
264
- return match[2] === 'ms' ? amount : amount * 1000
265
- }
266
-
267
- function pixelValue(value) {
268
- const match = /^(-?\d*\.?\d+)px$/.exec((value ?? '').trim())
269
- return match === null ? null : Number(match[1])
270
- }
271
-
272
- function declarationEntries(style) {
273
- const entries = []
274
- if (style === undefined || style === null) return entries
275
- const count = typeof style.length === 'number' ? style.length : 0
276
- for (let index = 0; index < count; index += 1) {
277
- const property = style.item === undefined ? style[index] : style.item(index)
278
- if (typeof property !== 'string' || property === '') continue
279
- entries.push([property, style.getPropertyValue(property)])
280
- }
281
- return entries
282
- }
283
-
284
- function readAnimations(style) {
285
- const names = splitList(style.getPropertyValue('animation-name'))
286
- if (names.length === 0) return []
287
- const durations = splitList(style.getPropertyValue('animation-duration'))
288
- const iterations = splitList(style.getPropertyValue('animation-iteration-count'))
289
- return names.map((name, index) => ({
290
- name,
291
- durationMs: parseTime(at(durations, index)),
292
- infinite: at(iterations, index).trim() === 'infinite'
293
- }))
294
- }
295
-
296
- function keyframeOffsets(keyText) {
297
- return splitList(keyText).map((token) => {
298
- const trimmed = token.toLowerCase()
299
- if (trimmed === 'from') return 0
300
- if (trimmed === 'to') return 1
301
- const match = /^(-?\d*\.?\d+)%$/.exec(trimmed)
302
- return match === null ? null : Number(match[1]) / 100
303
- })
304
- }
305
-
306
- function readKeyframes(rule) {
307
- const frames = []
308
- const frames_ = rule.cssRules ?? []
309
- for (let index = 0; index < frames_.length; index += 1) {
310
- const frame = frames_[index]
311
- const offsets = keyframeOffsets(frame.keyText ?? '')
312
- if (offsets.length === 0 || offsets.some((offset) => offset === null)) continue
313
- frames.push({ offsets, declarations: declarationEntries(frame.style) })
314
- }
315
- frames.sort((left, right) => left.offsets[0] - right.offsets[0])
316
- return frames
317
- }
318
-
319
- function animatedProperties(frames) {
320
- const properties = new Set()
321
- for (const frame of frames) {
322
- for (const [property] of frame.declarations) properties.add(property)
323
- }
324
- return properties
325
- }
326
-
327
- function classify(properties) {
328
- for (const property of properties) {
329
- if (LAYOUT_PROPERTIES.has(property)) return 'layout'
330
- }
331
- for (const property of properties) {
332
- if (PAINT_PROPERTIES.has(property)) return 'paint'
333
- }
334
- return null
335
- }
336
-
337
- /* ------------------------------------------------------------------ *
338
- * Animation repairs
339
- * ------------------------------------------------------------------ */
340
-
341
- function stepCount(durationMs, updatesPerSecond) {
342
- const duration = durationMs > 0 ? durationMs : 2600
343
- return Math.min(60, Math.max(3, Math.round((duration / 1000) * updatesPerSecond)))
344
- }
345
-
346
- function coarsen(name, frames, durationMs, updatesPerSecond) {
347
- const total = stepCount(durationMs, updatesPerSecond)
348
- const body = []
349
- for (let index = 0; index < frames.length; index += 1) {
350
- const frame = frames[index]
351
- const next = frames[index + 1]
352
- const declarations = frame.declarations.map(([property, value]) => `${property}: ${value}`)
353
- if (next !== undefined) {
354
- const share = Math.max(0, (next.offsets[0] ?? 1) - (frame.offsets[0] ?? 0))
355
- const steps = Math.max(2, Math.round(total * (share === 0 ? 1 : share)))
356
- declarations.push(`animation-timing-function: steps(${steps}, end)`)
357
- }
358
- const selectorText = frame.offsets.map((offset) => `${round(offset * 100)}%`).join(', ')
359
- body.push(` ${selectorText} { ${declarations.join('; ')} }`)
360
- }
361
- return { name, body: body.join('\n') }
362
- }
363
-
364
- function round(value) {
365
- return Math.round(value * 10000) / 10000
366
- }
367
-
368
- function planSweep(selector, style, frames) {
369
- if (!/::?(after|before)\s*$/.test(selector)) return null
370
-
371
- const properties = animatedProperties(frames)
372
- if (properties.size !== 1 || !properties.has('left')) return null
373
- if (frames.length < 2) return null
374
-
375
- const values = []
376
- for (const frame of frames) {
377
- const left = frame.declarations.find(([property]) => property === 'left')
378
- if (left === undefined) return null
379
- values.push(left[1].trim())
380
- }
381
-
382
- const start = pixelValue(values[0])
383
- if (start === null || start >= 0) return null
384
- if (!/^100%$/.test(values[values.length - 1])) return null
385
- for (const value of values.slice(1, -1)) {
386
- if (pixelValue(value) === null && !/^-?\d*\.?\d+%$/.test(value)) return null
387
- }
388
-
389
- const base = new Map(declarationEntries(style))
390
- const position = (base.get('position') ?? '').trim()
391
- if (position !== 'absolute' && position !== 'fixed') return null
392
- const backgroundImage = (base.get('background-image') ?? '').trim()
393
- if (backgroundImage === '' || backgroundImage === 'none') return null
394
- const backgroundColor = (base.get('background-color') ?? '').trim()
395
- if (backgroundColor !== '' && backgroundColor !== 'transparent' && backgroundColor !== 'rgba(0, 0, 0, 0)') return null
396
-
397
- const bandWidth = pixelValue(base.get('width') ?? '')
398
- const width = bandWidth === null ? Math.abs(start) : bandWidth
399
- if (width <= 0) return null
400
-
401
- return {
402
- declarations: [
403
- 'left: 0 !important',
404
- 'width: 100% !important',
405
- `background-size: ${width}px 100% !important`,
406
- 'background-repeat: no-repeat !important'
407
- ],
408
- keyframes: {
409
- body: frames
410
- .map((frame) => {
411
- const left = frame.declarations.find(([property]) => property === 'left')[1].trim()
412
- const selectorText = frame.offsets.map((offset) => `${round(offset * 100)}%`).join(', ')
413
- return ` ${selectorText} { transform: translateX(${left}) }`
414
- })
415
- .join('\n')
416
- }
417
- }
418
- }
419
-
420
- function isKeyframesRule(rule) {
421
- if (rule === null || typeof rule !== 'object') return false
422
- if (rule.type === 7) return true
423
- return typeof rule.name === 'string' && typeof rule.appendRule === 'function'
424
- }
425
-
426
- function isStyleRule(rule) {
427
- if (rule === null || typeof rule !== 'object') return false
428
- if (typeof rule.selectorText !== 'string' || rule.style === undefined) return false
429
- return rule.selectorText.trim() !== ''
430
- }
431
-
432
- function walkRules(rules, visit) {
433
- for (let index = 0; index < rules.length; index += 1) {
434
- const rule = rules[index]
435
- if (rule === null || typeof rule !== 'object') continue
436
- visit(rule)
437
- const nested = rule.cssRules
438
- if (nested !== undefined && nested !== null && nested.length > 0 && !isKeyframesRule(rule)) {
439
- walkRules(nested, visit)
440
- }
441
- }
442
- }
443
-
444
- function planSheets(sheets) {
445
- const keyframesByName = new Map()
446
- const styleRules = []
447
-
448
- for (const sheet of sheets) {
449
- let rules
450
- try {
451
- rules = sheet.cssRules
452
- } catch (reason) {
453
- continue
454
- }
455
- if (rules === undefined || rules === null) continue
456
- walkRules(rules, (rule) => {
457
- if (isKeyframesRule(rule)) {
458
- keyframesByName.set(rule.name, rule)
459
- return
460
- }
461
- if (isStyleRule(rule)) styleRules.push(rule)
462
- })
463
- }
464
-
465
- const entries = []
466
- const blocks = []
467
- let generated = 0
468
-
469
- for (const rule of styleRules) {
470
- const animations = readAnimations(rule.style)
471
- if (animations.length === 0) continue
472
-
473
- const patches = []
474
- for (const animation of animations) {
475
- if (!animation.infinite) continue
476
- const keyframes = keyframesByName.get(animation.name)
477
- if (keyframes === undefined) continue
478
- const frames = readKeyframes(keyframes)
479
- const kind = classify(animatedProperties(frames))
480
- if (kind === null) continue
481
-
482
- if (kind === 'layout' && animations.length === 1) {
483
- const sweep = planSweep(rule.selectorText, rule.style, frames)
484
- if (sweep !== null) {
485
- generated += 1
486
- patches.push({
487
- animation,
488
- kind: 'sweep',
489
- name: `dsh-ui-smooth-sweep-${generated}`,
490
- declarations: sweep.declarations,
491
- keyframes: sweep.keyframes
492
- })
493
- continue
494
- }
495
- }
496
-
497
- generated += 1
498
- patches.push({
499
- animation,
500
- kind: kind === 'layout' ? 'steps-layout' : 'steps-paint',
501
- name: `dsh-ui-smooth-steps-${generated}`,
502
- declarations: [],
503
- keyframes: coarsen(
504
- `dsh-ui-smooth-steps-${generated}`,
505
- frames,
506
- animation.durationMs,
507
- kind === 'layout' ? LAYOUT_UPDATES_PER_SECOND : PAINT_UPDATES_PER_SECOND
508
- )
509
- })
510
- }
511
-
512
- if (patches.length === 0) continue
513
-
514
- const renamed = new Map(patches.map((patch) => [patch.animation.name, patch.name]))
515
- const declarations = patches.flatMap((patch) => patch.declarations)
516
- declarations.push(`animation-name: ${animations.map((animation) => renamed.get(animation.name) ?? animation.name).join(', ')} !important`)
517
-
518
- blocks.push(`${rule.selectorText} {\n ${declarations.join(';\n ')};\n}`)
519
- for (const patch of patches) blocks.push(`@keyframes ${patch.name} {\n${patch.keyframes.body}\n}`)
520
-
521
- for (const patch of patches) {
522
- entries.push({ selector: rule.selectorText, animation: patch.animation.name, kind: patch.kind })
523
- }
524
- }
525
-
526
- const css = blocks.length === 0
527
- ? ''
528
- : `@media (prefers-reduced-motion: no-preference) {\n${blocks.join('\n')}\n}\n`
529
-
530
- return { css, entries }
531
- }
532
-
533
- module.exports = {
534
- LAYOUT_PROPERTIES,
535
- PAINT_PROPERTIES,
536
- classify,
537
- coarsen,
538
- planSheets,
539
- planSweep,
540
- readAnimations,
541
- readKeyframes
542
- }
543
- }
544
-
545
- registry['./config.js'] = function (module, exports, require) {
546
- /**
547
- * The host half owns the file at `$DSH_HOME/dsh-ui-smooth.json` and serves it over
548
- * `/dsh-ui-smooth/config`; the page keeps a copy, publishes it to every listener,
549
- * and writes back through the same route.
550
- */
551
-
552
- const CONFIG_URL = '/dsh-ui-smooth/config'
553
- const DEBUG_KEY = 'dsh-ui-smooth:debug'
554
-
555
- /** Shown in the settings header and reported by the debug handle. */
556
- const VERSION = '0.1.0'
557
-
558
- /* ------------------------------------------------------------------ *
559
- * Config
560
- * ------------------------------------------------------------------ */
561
-
562
- const DEFAULTS = {
563
- animations: true,
564
- backgroundThrottle: true,
565
- duringStream: true,
566
- skip: { enabled: true, turns: 3, minutes: 5 },
567
- unmount: { enabled: true, turns: 5, minutes: 16 },
568
- release: { enabled: false, turns: 8, minutes: 20 }
569
- }
570
-
571
- let config = cloneConfig(DEFAULTS)
572
- let hostElectron = false
573
- const configListeners = new Set()
574
-
575
- /** Read one tier of the thresholds; anything missing falls back to the default. */
576
- function readTier(source, key) {
577
- const tier = source?.[key] ?? {}
578
- return {
579
- enabled: tier.enabled !== false,
580
- turns: numberOr(tier.turns, DEFAULTS[key].turns),
581
- minutes: numberOr(tier.minutes, DEFAULTS[key].minutes)
582
- }
583
- }
584
-
585
- /** The aggressive tier keeps a tail and drops what has been quiet long enough. */
586
- function readRelease(source) {
587
- const tier = source?.release ?? {}
588
- return {
589
- enabled: tier.enabled === true,
590
- turns: Math.max(2, numberOr(tier.turns, DEFAULTS.release.turns)),
591
- minutes: numberOr(tier.minutes, DEFAULTS.release.minutes)
592
- }
593
- }
594
-
595
- function cloneConfig(source) {
596
- const base = source !== null && typeof source === 'object' ? source : {}
597
- return {
598
- animations: base.animations !== false,
599
- backgroundThrottle: base.backgroundThrottle !== false,
600
- duringStream: base.duringStream !== false,
601
- skip: readTier(base, 'skip'),
602
- unmount: readTier(base, 'unmount'),
603
- release: readRelease(base)
604
- }
605
- }
606
-
607
- function numberOr(value, fallback) {
608
- const number = Number(value)
609
- if (!Number.isFinite(number) || number < 0) return fallback
610
- return Math.min(10000, Math.floor(number))
611
- }
612
-
613
- function publishConfig(next) {
614
- config = cloneConfig(next)
615
- for (const listener of configListeners) {
616
- try {
617
- listener(config)
618
- } catch (reason) {
619
- /* a settings panel that threw must not stop the rest */
620
- }
621
- }
622
- }
623
-
624
- async function loadConfig() {
625
- try {
626
- const response = await fetch(CONFIG_URL, { headers: { accept: 'application/json' } })
627
- if (!response.ok) return
628
- const body = await response.json()
629
- hostElectron = body?.electron === true
630
- if (body?.config !== undefined) publishConfig(body.config)
631
- } catch (reason) {
632
- /* a page without the host route keeps the defaults */
633
- }
634
- }
635
-
636
- async function saveConfig(patch) {
637
- publishConfig({ ...config, ...patch })
638
- try {
639
- await fetch(CONFIG_URL, {
640
- method: 'POST',
641
- headers: { 'content-type': 'application/json' },
642
- body: JSON.stringify(config)
643
- })
644
- } catch (reason) {
645
- /* the in-memory value still applies; the next page reads the stored one */
646
- }
647
- }
648
-
649
- /** Whether the page asked for the console diagnostics. */
650
- function debugEnabled() {
651
- try {
652
- return window.localStorage.getItem(DEBUG_KEY) === '1'
653
- } catch (reason) {
654
- return false
655
- }
656
- }
657
-
658
- /** Whether this page runs inside the Electron shell rather than a browser. */
659
- function desktop() {
660
- try {
661
- return typeof navigator !== 'undefined' && navigator.userAgent.indexOf('Electron/') >= 0
662
- } catch (reason) {
663
- return false
664
- }
665
- }
666
-
667
- /** Subscribe to config changes; returns the unsubscribe. */
668
- function onConfig(listener) {
669
- configListeners.add(listener)
670
- return () => configListeners.delete(listener)
671
- }
672
-
673
- module.exports = {
674
- DEFAULTS,
675
- VERSION,
676
- cloneConfig,
677
- debugEnabled,
678
- desktop,
679
- getConfig: () => config,
680
- hostElectron: () => hostElectron,
681
- loadConfig,
682
- onConfig,
683
- publishConfig,
684
- saveConfig
685
- }
686
- }
687
-
688
- registry['./keepawake.js'] = function (module, exports, require) {
689
- /**
690
- * Keep the desktop page running while it is not in front.
691
- *
692
- * Chromium throttles a hidden renderer, and Electron's own escape hatch —
693
- * `webContents.setBackgroundThrottling(false)` — lives in the shell's main
694
- * process. The DSH host is a Node-mode child of that shell with no channel to
695
- * it, so the host half can configure the switch but cannot reach the window.
696
- *
697
- * What a page can do for itself is hold an audio stream open: Chromium keeps a
698
- * renderer that is playing audio out of the throttled set. The stream here is a
699
- * 40 Hz oscillator at a gain far below audibility, so it adds no sound.
700
- */
701
-
702
- const INAUDIBLE_GAIN = 0.0001
703
- const INAUDIBLE_HZ = 40
704
-
705
- function createKeepAwake() {
706
- let context = null
707
- let source = null
708
-
709
- const start = () => {
710
- if (context !== null) return false
711
- const AudioContext = window.AudioContext ?? window.webkitAudioContext
712
- if (typeof AudioContext !== 'function') return false
713
- try {
714
- const next = new AudioContext()
715
- const gain = next.createGain()
716
- gain.gain.value = INAUDIBLE_GAIN
717
- const oscillator = next.createOscillator()
718
- oscillator.frequency.value = INAUDIBLE_HZ
719
- oscillator.connect(gain)
720
- gain.connect(next.destination)
721
- oscillator.start()
722
- context = next
723
- source = oscillator
724
- // A shell that has not seen a gesture yet starts the context suspended.
725
- if (next.state === 'suspended') next.resume().catch(() => {})
726
- return true
727
- } catch (reason) {
728
- context = null
729
- source = null
730
- return false
731
- }
732
- }
733
-
734
- const stop = () => {
735
- if (context === null) return false
736
- try {
737
- source?.stop()
738
- source?.disconnect()
739
- context.close()
740
- } catch (reason) {
741
- /* a closed context has nothing left to release */
742
- }
743
- context = null
744
- source = null
745
- return true
746
- }
747
-
748
- return {
749
- start,
750
- stop,
751
- status: () => ({
752
- active: context !== null,
753
- state: context === null ? 'idle' : context.state
754
- })
755
- }
756
- }
757
-
758
- module.exports = { createKeepAwake }
759
- }
760
-
761
- registry['./main.js'] = function (module, exports, require) {
762
- /**
763
- * Module face: install the page halves into one cordis plugin.
764
- *
765
- * Everything the page does hangs off this `apply`: the animation stylesheet, the
766
- * transcript recycler, the settings section, and the debug handle that reports
767
- * what they are doing.
768
- */
769
-
770
- const { installAnimations } = require('./animate.js')
771
- const { LAYOUT_PROPERTIES, PAINT_PROPERTIES, classify, coarsen, planSheets, planSweep, readAnimations, readKeyframes } = require('./animations.js')
772
- const { VERSION, cloneConfig, desktop, getConfig, hostElectron, loadConfig, onConfig } = require('./config.js')
773
- const { createKeepAwake } = require('./keepawake.js')
774
- const { CONTAINMENT_CSS, createRecycler } = require('./recycle.js')
775
- const { mainSessions, sliceHistory } = require('./release.js')
776
- const { SETTINGS_CSS, SettingsSection } = require('./settings.js')
777
-
778
- const CSS_ID = 'dsh-ui-smooth/css'
779
-
780
- function installStyleSheet() {
781
- if (document.getElementById(CSS_ID) !== null) return
782
- const element = document.createElement('style')
783
- element.id = CSS_ID
784
- element.textContent = `${CONTAINMENT_CSS}\n${SETTINGS_CSS}`
785
- ;(document.head ?? document.documentElement).appendChild(element)
786
- }
787
-
788
- function apply(ctx) {
789
- installStyleSheet()
790
- const animations = installAnimations()
791
- const recycler = createRecycler(ctx)
792
- const keepAwake = createKeepAwake()
793
- const slotIds = () => {
794
- try {
795
- return ctx?.slots?.entries?.('settings.section')?.map?.((entry) => entry.id) ?? []
796
- } catch (reason) {
797
- return []
798
- }
799
- }
800
-
801
- const handle = {
802
- version: VERSION,
803
- status: () => ({
804
- animations: animations.status(),
805
- recycling: recycler.stats(),
806
- config: cloneConfig(getConfig()),
807
- electron: hostElectron(),
808
- settingsSection: slotIds()
809
- }),
810
- rescan: () => animations.rescan(),
811
- recycle: () => recycler.pass(),
812
- refreshConfig: () => loadConfig().then(() => {
813
- recycler.pass()
814
- return cloneConfig(getConfig())
815
- }),
816
- restore: () => animations.restore(),
817
- config: () => cloneConfig(getConfig()),
818
- throttle: () => ({ host: hostElectron(), desktop: desktop(), ...keepAwake.status() }),
819
- /** What the aggressive tier sees: the loaded window it would trim. */
820
- history: () => {
821
- const session = mainSessions(ctx?.sessions)[0]
822
- if (session === undefined || session === null) return null
823
- let entries = []
824
- try {
825
- entries = session.eventSource?.getSnapshot?.()?.entries ?? []
826
- } catch (reason) {
827
- entries = []
828
- }
829
- return {
830
- sessionId: session.sessionId,
831
- entries: entries.length,
832
- turns: entries.filter((entry) => entry?.event?.type === 'turn/start').length,
833
- baseSeq: session.baseSeq,
834
- hasMore: session.hasMore === true
835
- }
836
- }
837
- }
838
- window.__dshUiSmooth = handle
839
-
840
- /**
841
- * The switch reads "throttle me in the background". Off means the page keeps
842
- * running there: the host half asks the shell when it is inside one, and the
843
- * page holds an inaudible audio stream open for the case where it is not.
844
- */
845
- const syncThrottle = () => {
846
- const off = getConfig().backgroundThrottle === false
847
- if (off && (hostElectron() || desktop())) keepAwake.start()
848
- else keepAwake.stop()
849
- }
850
-
851
- onConfig(() => {
852
- recycler.restoreAll()
853
- syncThrottle()
854
- })
855
-
856
- loadConfig().then(() => {
857
- recycler.pass()
858
- syncThrottle()
859
- })
860
-
861
- if (ctx !== undefined && ctx !== null && typeof ctx.slots?.inject === 'function') {
862
- ctx.slots.inject('settings.section', () =>
863
- ctx.slots.register({
864
- name: 'settings.section',
865
- id: 'dsh-ui-smooth',
866
- order: 60,
867
- label: () => '流畅性',
868
- registrant: 'dsh-ui-smooth'
869
- }, SettingsSection)
870
- )
871
- }
872
-
873
- if (ctx !== undefined && ctx !== null && typeof ctx.effect === 'function') {
874
- ctx.effect(() => () => {
875
- animations.dispose()
876
- keepAwake.stop()
877
- recycler.dispose()
878
- const css = document.getElementById(CSS_ID)
879
- if (css !== null) css.remove()
880
- if (window.__dshUiSmooth === handle) delete window.__dshUiSmooth
881
- }, 'dsh-ui-smooth: page passes')
882
- }
883
- }
884
-
885
- exports.apply = apply
886
- exports.inject = ['slots', 'sessions']
887
- exports.internals = {
888
- LAYOUT_PROPERTIES,
889
- PAINT_PROPERTIES,
890
- classify,
891
- coarsen,
892
- planSheets,
893
- planSweep,
894
- readAnimations,
895
- readKeyframes,
896
- sliceHistory
897
- }
898
- }
899
-
900
- registry['./recycle.js'] = function (module, exports, require) {
901
- /**
902
- * Transcript recycling: keep old turns out of the render path.
903
- *
904
- * Two tiers, both gated on "old enough and cold enough". `skip` asks the browser
905
- * to stop rendering the subtree (`content-visibility: hidden`); `unmount` moves
906
- * the row's nodes into a detached fragment and holds its measured height, so the
907
- * transcript does not jump, and puts them back before the row can scroll into
908
- * view. Neither frees memory: React still owns every node.
909
- */
910
-
911
- const { debugEnabled, getConfig, loadConfig } = require('./config.js')
912
- const { releaseHistory } = require('./release.js')
913
-
914
- /* ------------------------------------------------------------------ *
915
- * Transcript recycling
916
- * ------------------------------------------------------------------ */
917
-
918
- const ROW_ATTRIBUTE = 'data-ui-smooth'
919
- const HEIGHT_PROPERTY = '--ui-smooth-height'
920
-
921
- const CONTAINMENT_CSS = `
922
- [data-conversation-content] [${ROW_ATTRIBUTE}="skip"] {
923
- content-visibility: hidden;
924
- contain-intrinsic-size: auto 320px;
925
- }
926
- [data-conversation-content] [${ROW_ATTRIBUTE}="parked"] {
927
- display: block;
928
- min-height: var(${HEIGHT_PROPERTY}, 40px);
929
- }
930
- `
931
-
932
- /**
933
- * Two tiers, both gated on "old enough and cold enough" — a turn has to
934
- * be more than N turns behind the newest one *and* have been out of the
935
- * viewport for M minutes:
936
- *
937
- * skip the browser stops rendering the subtree (`content-visibility:
938
- * hidden`), which drops its layout, style and paint work while
939
- * the DOM stays where React put it.
940
- * unmount the subtree's nodes are moved out of the document into a
941
- * detached fragment, and the row keeps its measured height, so
942
- * the transcript does not jump. Scrolling anywhere near the
943
- * row puts the nodes back before it can be seen.
944
- *
945
- * Nothing is destroyed: React still owns the nodes, and a plugin that
946
- * deleted them would fail the next time React reconciles that subtree.
947
- * Detaching is the furthest a plugin can go, and it does drop the
948
- * browser's per-node layout and style bookkeeping along with the paint.
949
- */
950
- function createRecycler(ctx) {
951
- const seenAt = new WeakMap()
952
- /** When each turn was last mounted or looked at; outlives the row itself. */
953
- const warmth = new Map()
954
- const parked = new WeakMap()
955
- let root = null
956
- let nearObserver = null
957
- let timer = 0
958
- let idleHandle = 0
959
- let releases = 0
960
-
961
- /** The top-level flow and the turn rows directly inside it. */
962
- function inspect() {
963
- const flow = document.querySelector('[data-conversation-content] [data-chat-flow]')
964
- if (flow === null) return null
965
- const rows = []
966
- const candidates = flow.querySelectorAll('[data-chat-turn]')
967
- for (const row of candidates) {
968
- if (row.closest('[data-chat-flow]') !== flow) continue
969
- const turn = Number(row.getAttribute('data-chat-turn'))
970
- if (!Number.isSafeInteger(turn)) continue
971
- rows.push({ row, turn })
972
- }
973
- return rows.length === 0 ? null : { flow, rows }
974
- }
975
-
976
- function watchNear(flow, rows) {
977
- const scroller = flow.closest('[data-conversation-scroll]')
978
- if (nearObserver === null || root !== scroller) {
979
- if (nearObserver !== null) nearObserver.disconnect()
980
- nearObserver = new IntersectionObserver((records) => {
981
- for (const record of records) {
982
- if (!record.isIntersecting) continue
983
- const seen = Date.now()
984
- seenAt.set(record.target, seen)
985
- const turn = Number(record.target.getAttribute('data-chat-turn'))
986
- if (Number.isSafeInteger(turn)) warmth.set(turn, seen)
987
- unpark(record.target)
988
- record.target.removeAttribute(ROW_ATTRIBUTE)
989
- }
990
- }, { root: scroller ?? null, rootMargin: '600px 0px 600px 0px' })
991
- root = scroller ?? null
992
- }
993
- // History arrives in chunks, so rows appear long after the observer was
994
- // built: observe on every pass or the late ones are never watched and
995
- // their parked content is never released.
996
- for (const entry of rows) nearObserver.observe(entry.row)
997
- }
998
-
999
- /**
1000
- * Move a turn's content out of the document, keeping its height so the
1001
- * scroll position and every measurement around it stay stable.
1002
- */
1003
- function park(row, measuredHeight) {
1004
- if (parked.has(row)) return false
1005
- if (row.contains(document.activeElement)) return false
1006
- const selection = window.getSelection()
1007
- const anchor = selection === null || selection === undefined ? null : selection.anchorNode
1008
- if (anchor !== null && row.contains(anchor)) return false
1009
-
1010
- const height = Math.round(measuredHeight)
1011
- const fragment = document.createDocumentFragment()
1012
- while (row.firstChild !== null) fragment.appendChild(row.firstChild)
1013
- row.style.setProperty(HEIGHT_PROPERTY, `${Math.max(1, height)}px`)
1014
- row.setAttribute(ROW_ATTRIBUTE, 'parked')
1015
- parked.set(row, fragment)
1016
- return true
1017
- }
1018
-
1019
- /** Put a parked turn's content back where it was. */
1020
- function unpark(row) {
1021
- const fragment = parked.get(row)
1022
- if (fragment === undefined) return false
1023
- while (fragment.firstChild !== null) row.appendChild(fragment.firstChild)
1024
- row.style.removeProperty(HEIGHT_PROPERTY)
1025
- if (row.getAttribute(ROW_ATTRIBUTE) === 'parked') row.removeAttribute(ROW_ATTRIBUTE)
1026
- parked.delete(row)
1027
- return true
1028
- }
1029
-
1030
- /** Put everything back: the cheapest safe answer to any doubt. */
1031
- function restoreAll() {
1032
- for (const row of document.querySelectorAll(`[${ROW_ATTRIBUTE}="parked"]`)) unpark(row)
1033
- for (const row of document.querySelectorAll(`[${ROW_ATTRIBUTE}="skip"]`)) row.removeAttribute(ROW_ATTRIBUTE)
1034
- }
1035
-
1036
- function pass() {
1037
- const found = inspect()
1038
- if (found === null) return
1039
- watchNear(found.flow, found.rows)
1040
-
1041
- const config = getConfig()
1042
-
1043
- // Streaming is the one moment the app re-renders on its own, so the pass
1044
- // stays away from the transcript unless the reader asked it not to.
1045
- if (!config.duringStream && document.querySelector('[data-streaming]') !== null) return
1046
-
1047
- let newest = 0
1048
- for (const entry of found.rows) newest = Math.max(newest, entry.turn)
1049
- const now = Date.now()
1050
- const skipMinutes = config.skip.minutes * 60000
1051
- const unmountMinutes = config.unmount.minutes * 60000
1052
- const scroller = found.flow.closest('[data-conversation-scroll]')
1053
- const viewport = scroller === null ? null : scroller.getBoundingClientRect()
1054
- let skipped = 0
1055
- let unmounted = 0
1056
-
1057
- if (warmth.size > 5000) warmth.clear()
1058
- for (const entry of found.rows) {
1059
- if (!seenAt.has(entry.row)) {
1060
- seenAt.set(entry.row, now)
1061
- warmth.set(entry.turn, now)
1062
- }
1063
- const age = newest - entry.turn
1064
- const cold = now - (seenAt.get(entry.row) ?? 0)
1065
- const unmount = config.unmount.enabled
1066
- && age > config.unmount.turns
1067
- && age > config.skip.turns
1068
- && cold > unmountMinutes
1069
- const skip = config.skip.enabled
1070
- && age > config.skip.turns
1071
- && cold > skipMinutes
1072
-
1073
- if (unmount) {
1074
- if (entry.row.getAttribute(ROW_ATTRIBUTE) === 'parked') {
1075
- unmounted += 1
1076
- continue
1077
- }
1078
- // One read answers both questions: how tall is it, and is it far
1079
- // enough from the viewport that nothing on screen moves.
1080
- const box = entry.row.getBoundingClientRect()
1081
- const near = viewport !== null && box.bottom > viewport.top - 800 && box.top < viewport.bottom + 800
1082
- if (!near && park(entry.row, box.height)) unmounted += 1
1083
- continue
1084
- }
1085
-
1086
- unpark(entry.row)
1087
- if (skip) {
1088
- if (entry.row.getAttribute(ROW_ATTRIBUTE) !== 'skip') entry.row.setAttribute(ROW_ATTRIBUTE, 'skip')
1089
- skipped += 1
1090
- } else if (entry.row.hasAttribute(ROW_ATTRIBUTE)) {
1091
- entry.row.removeAttribute(ROW_ATTRIBUTE)
1092
- }
1093
- }
1094
-
1095
- if (config.release.enabled) {
1096
- const quietMs = config.release.minutes * 60000
1097
- releases += releaseHistory(ctx?.sessions, config.release, (turn) => now - (warmth.get(turn) ?? 0) > quietMs)
1098
- }
1099
-
1100
- if (debugEnabled()) {
1101
- console.info(`[dsh-ui-smooth] ${skipped} turn(s) not rendered, ${unmounted} turn(s) parked outside the document, ${releases} window trim(s) total`, config)
1102
- }
1103
- }
1104
-
1105
- function schedule(delayMs) {
1106
- if (idleHandle !== 0 || timer !== 0) return
1107
- const run = () => {
1108
- idleHandle = 0
1109
- timer = 0
1110
- pass()
1111
- }
1112
- if (typeof requestIdleCallback === 'function') {
1113
- idleHandle = requestIdleCallback(run, { timeout: Math.max(500, delayMs) })
1114
- } else {
1115
- timer = setTimeout(run, delayMs)
1116
- }
1117
- }
1118
-
1119
- const onScroll = () => schedule(150)
1120
- const onVisibility = () => {
1121
- if (document.visibilityState !== 'visible') return
1122
- restoreAll()
1123
- schedule(0)
1124
- }
1125
- const onResize = () => {
1126
- restoreAll()
1127
- schedule(200)
1128
- }
1129
- const mutations = new MutationObserver(() => schedule(400))
1130
- const ticker = setInterval(() => {
1131
- loadConfig().then(() => schedule(0))
1132
- }, 30000)
1133
-
1134
- document.addEventListener('scroll', onScroll, { capture: true, passive: true })
1135
- document.addEventListener('visibilitychange', onVisibility)
1136
- window.addEventListener('resize', onResize)
1137
- mutations.observe(document.body, { childList: true, subtree: true })
1138
- schedule(0)
1139
-
1140
- return {
1141
- pass: () => pass(),
1142
- restoreAll: () => restoreAll(),
1143
- stats: () => ({
1144
- skipped: document.querySelectorAll(`[${ROW_ATTRIBUTE}="skip"]`).length,
1145
- parked: document.querySelectorAll(`[${ROW_ATTRIBUTE}="parked"]`).length,
1146
- released: releases
1147
- }),
1148
- dispose: () => {
1149
- restoreAll()
1150
- if (nearObserver !== null) nearObserver.disconnect()
1151
- mutations.disconnect()
1152
- clearInterval(ticker)
1153
- if (timer !== 0) clearTimeout(timer)
1154
- if (idleHandle !== 0 && typeof cancelIdleCallback === 'function') cancelIdleCallback(idleHandle)
1155
- document.removeEventListener('scroll', onScroll, { capture: true })
1156
- document.removeEventListener('visibilitychange', onVisibility)
1157
- window.removeEventListener('resize', onResize)
1158
- }
1159
- }
1160
- }
1161
-
1162
- module.exports = { CONTAINMENT_CSS, createRecycler }
1163
- }
1164
-
1165
- registry['./release.js'] = function (module, exports, require) {
1166
- /**
1167
- * React owns the transcript, so a plugin that deletes nodes fails the next
1168
- * reconcile. The one safe way to free them is to make React unmount those turns,
1169
- * and the session controller already knows how: replace its loaded window with a
1170
- * shorter one, then move the paging stream`s head with it so 加载更早 can bring the
1171
- * history back from disk.
1172
- */
1173
-
1174
- /* ------------------------------------------------------------------ *
1175
- * Aggressive release
1176
- * ------------------------------------------------------------------ */
1177
-
1178
- /**
1179
- * Never bother dropping fewer turns than this: the next 加载更早 brings a
1180
- * whole page (up to 500 messages) back, so a one-turn trim would only buy
1181
- * a refetch loop.
1182
- */
1183
- const MIN_RELEASED_TURNS = 4
1184
-
1185
- /**
1186
- * Cut a loaded history window down to its newest `keepTurns` turns.
1187
- *
1188
- * Only a prefix goes: a turn is dropped when it sits before the kept tail *and*
1189
- * nothing has looked at it for a while — a turn that was just paged back in
1190
- * stays put until its own quiet period runs out. One warm turn stops the cut
1191
- * there, because everything older goes with it.
1192
- *
1193
- * @param entries - the session's loaded window, oldest first.
1194
- * @param keepTurns - turns to keep at the tail.
1195
- * @param isCold - whether a turn has been out of sight long enough to drop.
1196
- * @returns the slice to keep, or `null` when there is nothing worth dropping.
1197
- */
1198
- function sliceHistory(entries, keepTurns, isCold) {
1199
- if (!Array.isArray(entries) || entries.length === 0) return null
1200
- if (!Number.isSafeInteger(keepTurns) || keepTurns < 1) return null
1201
- const starts = []
1202
- const turns = []
1203
- for (let index = 0; index < entries.length; index += 1) {
1204
- const event = entries[index]?.event
1205
- if (event?.type !== 'turn/start') continue
1206
- const turn = Number(event.data?.turn)
1207
- starts.push(index)
1208
- turns.push(Number.isSafeInteger(turn) ? turn : starts.length)
1209
- }
1210
- const droppable = starts.length - keepTurns
1211
- if (droppable < MIN_RELEASED_TURNS) return null
1212
- let cut = -1
1213
- for (let group = 0; group < droppable; group += 1) {
1214
- if (typeof isCold === 'function' && !isCold(turns[group])) break
1215
- cut = group
1216
- }
1217
- if (cut < MIN_RELEASED_TURNS - 1) return null
1218
- return entries.slice(starts[cut + 1])
1219
- }
1220
-
1221
- /** The sessions the main view is showing (a retained session may also be a background one). */
1222
- function mainSessions(service) {
1223
- const sessions = []
1224
- if (service === undefined || service === null) return sessions
1225
- let snapshot
1226
- try {
1227
- snapshot = service.list?.getSnapshot?.()
1228
- } catch (reason) {
1229
- return sessions
1230
- }
1231
- for (const [id, row] of Object.entries(snapshot?.byId ?? {})) {
1232
- if ((row?.retainedBy?.mainView ?? 0) === 0) continue
1233
- try {
1234
- const session = service.manager?.get?.(id)
1235
- if (session !== undefined && session !== null) sessions.push(session)
1236
- } catch (reason) {
1237
- /* a session still opening simply is not a candidate yet */
1238
- }
1239
- }
1240
- return sessions
1241
- }
1242
-
1243
- /**
1244
- * Hand the oldest turns back to the disk.
1245
- *
1246
- * React owns the transcript, so a node a plugin deletes comes back as a
1247
- * `NotFoundError` on the next reconcile. The one safe way to free those
1248
- * nodes is to make React itself unmount the turns, and the session
1249
- * controller already knows how: replace its loaded window with a shorter
1250
- * one. `hasMore` stays true, so the app offers 加载更早 for exactly the
1251
- * history that was dropped.
1252
- *
1253
- * A session that is streaming is left alone: the answer is still being written
1254
- * into its tail, and trimming under it would move the page the reader is
1255
- * watching. Everything else is fair game, wherever the reader has scrolled to.
1256
- *
1257
- * @returns how many sessions were trimmed.
1258
- */
1259
- function releaseHistory(service, release, isCold) {
1260
- const keepTurns = release.turns
1261
- let released = 0
1262
- for (const session of mainSessions(service)) {
1263
- if (session.openState !== 'open') continue
1264
- if (session.running === true || session.loadingOlder === true) continue
1265
- if (typeof session.installWindow !== 'function') continue
1266
- let entries
1267
- try {
1268
- entries = session.eventSource?.getSnapshot?.()?.entries
1269
- } catch (reason) {
1270
- continue
1271
- }
1272
- const kept = sliceHistory(entries, keepTurns, isCold)
1273
- if (kept === null) continue
1274
- try {
1275
- session.installWindow(kept, true)
1276
- } catch (reason) {
1277
- if (typeof console !== 'undefined') console.warn('[dsh-ui-smooth] release failed:', reason)
1278
- continue
1279
- }
1280
- // The paging stream keeps its own idea of the oldest seq it holds,
1281
- // and prepend drops every record newer than that idea. Move it with
1282
- // the window or the dropped history can never be paged back.
1283
- const stream = session.events
1284
- if (stream !== null && stream !== undefined && 'firstCursor' in stream) {
1285
- stream.firstCursor = kept[0]?.event?.seq
1286
- }
1287
- released += 1
1288
- }
1289
- return released
1290
- }
1291
-
1292
- module.exports = { mainSessions, releaseHistory, sliceHistory }
1293
- }
1294
-
1295
- registry['./settings.js'] = function (module, exports, require) {
1296
- /**
1297
- * The 流畅性 settings panel.
1298
- *
1299
- * Rendered into the app's own settings section slot, so it inherits the shell's
1300
- * tokens and needs no portal of its own. Every switch here maps to one field of
1301
- * the shared config, and each card states what the switch does to the page.
1302
- */
1303
-
1304
- const react = require('react')
1305
- const h = react.createElement
1306
-
1307
- const { VERSION, cloneConfig, desktop, getConfig, hostElectron, onConfig, saveConfig } = require('./config.js')
1308
-
1309
- function Switch({ checked, disabled, onChange }) {
1310
- return h('button', {
1311
- type: 'button',
1312
- role: 'switch',
1313
- 'aria-checked': checked ? 'true' : 'false',
1314
- disabled: disabled === true,
1315
- className: `uis-switch${checked ? ' is-on' : ''}`,
1316
- onClick: () => onChange(!checked)
1317
- }, h('span', { className: 'uis-knob' }))
1318
- }
1319
-
1320
- function NumberField({ value, min, max, suffix, onChange }) {
1321
- return h('label', { className: 'uis-number' },
1322
- h('input', {
1323
- type: 'number',
1324
- value: String(value),
1325
- min: String(min),
1326
- max: String(max),
1327
- onChange: (event) => {
1328
- const next = Number(event.target.value)
1329
- if (!Number.isFinite(next)) return
1330
- onChange(Math.min(max, Math.max(min, Math.floor(next))))
1331
- }
1332
- }),
1333
- suffix !== undefined ? h('span', { className: 'uis-suffix' }, suffix) : null
1334
- )
1335
- }
1336
-
1337
- function Card({ title, hint, control, children }) {
1338
- return h('div', { className: 'uis-card' }, [
1339
- h('div', { className: 'uis-row' }, [
1340
- h('div', { className: 'uis-text' }, [
1341
- h('div', { className: 'uis-title' }, title),
1342
- hint === undefined ? null : h('div', { className: 'uis-hint' }, hint)
1343
- ]),
1344
- control
1345
- ]),
1346
- children === undefined ? null : h('div', { className: 'uis-thresholds' }, children)
1347
- ])
1348
- }
1349
-
1350
- function SettingsSection() {
1351
- const [state, setState] = react.useState(getConfig)
1352
- const electron = hostElectron() || desktop()
1353
- react.useEffect(() => onConfig((next) => setState(cloneConfig(next))), [])
1354
-
1355
- const patch = (next) => {
1356
- saveConfig(next)
1357
- setState((current) => cloneConfig({ ...current, ...next }))
1358
- }
1359
- const patchTier = (key, changes) => patch({ [key]: { ...state[key], ...changes } })
1360
- const toggle = (key) => h(Switch, {
1361
- checked: state[key],
1362
- onChange: (checked) => patch({ [key]: checked })
1363
- })
1364
-
1365
- return h('div', { className: 'uis-section' }, [
1366
- h('div', { className: 'uis-head' }, [
1367
- h('span', { className: 'uis-brand' }, 'DSH-UI-Smooth'),
1368
- h('span', { className: 'uis-version' }, `v${VERSION}`)
1369
- ]),
1370
- h(Card, {
1371
- title: '启用动画优化',
1372
- hint: '降低无限循环动画布局/重绘次数。DSH 已经对自身的旧动画进行了优化,此项主要解决其他插件/后续引入的动画每帧布局/重绘问题。',
1373
- control: toggle('animations')
1374
- }),
1375
-
1376
- h(Card, {
1377
- title: '后台节流',
1378
- hint: electron
1379
- ? '当关闭后 DSH 不是前台窗口时仍然保持界面照常推进,这样的好处是可以在切换回前台窗口时不用一次性加载积压的内容,保证观感流畅。'
1380
- : '当关闭后 DSH 不是前台窗口时仍然保持界面照常推进,这样的好处是可以在切换回前台窗口时不用一次性加载积压的内容,保证观感流畅。该项仅在 Electron 壳的桌面端有效。',
1381
- control: h(Switch, {
1382
- checked: state.backgroundThrottle,
1383
- disabled: !electron,
1384
- onChange: (checked) => patch({ backgroundThrottle: checked })
1385
- })
1386
- }),
1387
-
1388
- h(Card, {
1389
- title: '流式输出期间回收',
1390
- hint: '在流式输出期间仍按下方阈值处理。',
1391
- control: toggle('duringStream')
1392
- }),
1393
-
1394
- h(Card, {
1395
- title: '旧轮次跳过渲染',
1396
- hint: '当满足以下设置条件时,将不再渲染该条目的子树,在滚动接近时恢复渲染。',
1397
- control: h(Switch, {
1398
- checked: state.skip.enabled,
1399
- onChange: (checked) => patchTier('skip', { enabled: checked })
1400
- }),
1401
- children: [
1402
- h(NumberField, {
1403
- value: state.skip.turns, min: 1, max: 200, suffix: '轮以前',
1404
- onChange: (turns) => patchTier('skip', { turns })
1405
- }),
1406
- h('span', { className: 'uis-label' }, '且'),
1407
- h(NumberField, {
1408
- value: state.skip.minutes, min: 1, max: 1440, suffix: '分钟未查看',
1409
- onChange: (minutes) => patchTier('skip', { minutes })
1410
- })
1411
- ]
1412
- }),
1413
-
1414
- h(Card, {
1415
- title: '旧轮次从文档流摘除',
1416
- hint: '当满足以下设置条件时,将条目从文档流摘除,在滚动接近时重新填入。',
1417
- control: h(Switch, {
1418
- checked: state.unmount.enabled,
1419
- onChange: (checked) => patchTier('unmount', { enabled: checked })
1420
- }),
1421
- children: [
1422
- h(NumberField, {
1423
- value: state.unmount.turns, min: 1, max: 500, suffix: '轮以前',
1424
- onChange: (turns) => patchTier('unmount', { turns })
1425
- }),
1426
- h('span', { className: 'uis-label' }, '且'),
1427
- h(NumberField, {
1428
- value: state.unmount.minutes, min: 1, max: 4320, suffix: '分钟未查看',
1429
- onChange: (minutes) => patchTier('unmount', { minutes })
1430
- })
1431
- ]
1432
- }),
1433
-
1434
- h(Card, {
1435
- title: '激进策略:旧轮次从内存卸载',
1436
- hint: '当满足以下设置条件时,将条目从内存卸载,重新加载需要从硬盘获取。',
1437
- control: h(Switch, {
1438
- checked: state.release.enabled,
1439
- onChange: (checked) => patch({ release: { ...state.release, enabled: checked } })
1440
- }),
1441
- children: [
1442
- h(NumberField, {
1443
- value: state.release.turns, min: 2, max: 500, suffix: '轮以前',
1444
- onChange: (turns) => patch({ release: { ...state.release, turns } })
1445
- }),
1446
- h('span', { className: 'uis-label' }, '且重新加载后'),
1447
- h(NumberField, {
1448
- value: state.release.minutes, min: 1, max: 4320, suffix: '分钟未查看',
1449
- onChange: (minutes) => patch({ release: { ...state.release, minutes } })
1450
- })
1451
- ]
1452
- })
1453
- ])
1454
- }
1455
-
1456
- const SETTINGS_CSS = `
1457
- .uis-section { display: flex; flex-direction: column; gap: 12px; font-size: 13px; color: var(--dsw-alias-label-primary, inherit); }
1458
- .uis-head { display: flex; align-items: baseline; gap: 8px; }
1459
- .uis-brand { font-weight: 600; letter-spacing: .01em; }
1460
- .uis-version { color: var(--dsw-alias-label-tertiary, inherit); font-family: var(--dsw-font-mono, ui-monospace, monospace); font-size: 12px; }
1461
- .uis-card { border: 1px solid var(--dsw-alias-border-secondary, rgba(127,127,127,.24)); border-radius: 10px; padding: 12px 14px; display: flex; flex-direction: column; gap: 10px; }
1462
- .uis-row { display: flex; align-items: flex-start; gap: 16px; justify-content: space-between; }
1463
- .uis-text { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
1464
- .uis-title { font-weight: 600; }
1465
- .uis-hint { color: var(--dsw-alias-label-tertiary, inherit); line-height: 1.5; }
1466
- .uis-thresholds { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; color: var(--dsw-alias-label-secondary, inherit); }
1467
- .uis-label { white-space: nowrap; }
1468
- .uis-number { display: inline-flex; align-items: center; gap: 4px; }
1469
- .uis-number input { width: 62px; padding: 3px 6px; border-radius: 6px; border: 1px solid var(--dsw-alias-border-secondary, rgba(127,127,127,.32)); background: var(--dsw-alias-fill-secondary, transparent); color: inherit; font: inherit; }
1470
- .uis-suffix { color: var(--dsw-alias-label-tertiary, inherit); white-space: nowrap; }
1471
- .uis-switch { width: 38px; height: 22px; border-radius: 999px; border: 1px solid var(--dsw-alias-border-secondary, rgba(127,127,127,.32)); background: var(--dsw-alias-fill-secondary, rgba(127,127,127,.2)); padding: 2px; cursor: pointer; flex: none; transition: background .15s ease; }
1472
- .uis-switch.is-on { background: var(--dsw-alias-state-success-primary, #3b82f6); border-color: transparent; }
1473
- .uis-switch:disabled { opacity: .5; cursor: not-allowed; }
1474
- .uis-knob { display: block; width: 16px; height: 16px; border-radius: 50%; background: #fff; transition: transform .15s ease; }
1475
- .uis-switch.is-on .uis-knob { transform: translateX(16px); }
1476
- `
1477
-
1478
- module.exports = { SETTINGS_CSS, SettingsSection }
1479
- }
1480
-
1481
- return require('./main.js')
1482
- }
1483
- })
1
+ /**
2
+ * GENERATED FILE — do not edit. Sources live in src/, built by scripts/build.mjs.
3
+ *
4
+ * dsh-ui-smooth — client half.
5
+ *
6
+ * Four jobs, all of them about keeping the Web UI's main thread and heap free:
7
+ *
8
+ * 1. Animation budget. Idle CPU comes from decorative animations that run
9
+ * forever on properties the renderer cannot composite: `infinite` on `left`
10
+ * relayouts its subtree every frame, and `background-position` behind
11
+ * `background-clip: text` re-rasterizes glyphs. Those are rewritten onto
12
+ * `transform` (same trajectory) or stepped with `steps()`. Finite
13
+ * animations, composited animations and `prefers-reduced-motion` users are
14
+ * left alone.
15
+ *
16
+ * 2. Transcript recycling. The transcript mounts every entry of the session and
17
+ * collapsed rows keep their subtrees (`hidden="until-found"`), so a long
18
+ * session costs more on every interaction. Turns that are old *and* have not
19
+ * been looked at for a while are put behind CSS containment, or detached into
20
+ * a fragment with their height held. Detaching is as far as the DOM alone can
21
+ * go: React still holds every node of that subtree.
22
+ *
23
+ * 3. Aggressive release. The only way to hand a turn's memory back is to make
24
+ * React let go of it, which means unmounting, not detaching. This tier drops
25
+ * the oldest part of the session's loaded history window through the session
26
+ * controller's own window API, so React unmounts those turns and their fibers
27
+ * release the DOM they own. `hasMore` stays true, so 加载更早 pages the same
28
+ * history back from disk.
29
+ *
30
+ * 4. Settings. Every threshold and the desktop background-throttle switch live
31
+ * in one config owned by the host half, edited in Settings → 流畅性.
32
+ */
33
+
34
+ window.__ModuleLoader__.load({
35
+ id: 'dsh-ui-smooth',
36
+ factory: (requireExternal) => {
37
+ const registry = {}
38
+ const cache = {}
39
+
40
+ function require(specifier) {
41
+ if (!specifier.startsWith('.')) return requireExternal(specifier)
42
+ const id = specifier.endsWith('.js') ? specifier : `${specifier}.js`
43
+ const cached = cache[id]
44
+ if (cached !== undefined) return cached.exports
45
+ const factory = registry[id]
46
+ if (factory === undefined) throw new Error(`dsh-ui-smooth: unknown module ${id}`)
47
+ const module = { exports: {} }
48
+ cache[id] = module
49
+ factory(module, module.exports, require)
50
+ return module.exports
51
+ }
52
+
53
+ registry['./animate.js'] = function (module, exports, require) {
54
+ /**
55
+ * The page keeps adding stylesheets, so the plan is rebuilt whenever one arrives
56
+ * and the result lives in a single injected stylesheet.
57
+ */
58
+
59
+ const { debugEnabled, getConfig, onConfig } = require('./config.js')
60
+ const { planSheets } = require('./animations.js')
61
+
62
+ const STYLE_ID = 'dsh-ui-smooth/animations'
63
+
64
+ function pageSheets(own) {
65
+ const sheets = []
66
+ const adopted = document.adoptedStyleSheets
67
+ if (adopted !== undefined && adopted !== null) {
68
+ for (const sheet of adopted) sheets.push(sheet)
69
+ }
70
+ const list = document.styleSheets
71
+ for (let index = 0; index < list.length; index += 1) {
72
+ const sheet = list[index]
73
+ if (sheet === own) continue
74
+ sheets.push(sheet)
75
+ }
76
+ return sheets
77
+ }
78
+
79
+ function installAnimations() {
80
+ const element = document.createElement('style')
81
+ element.id = STYLE_ID
82
+ element.setAttribute('data-dsh-ui-smooth', '')
83
+ const host = document.head ?? document.documentElement
84
+ host.appendChild(element)
85
+
86
+ const state = { entries: [], css: '', scans: 0 }
87
+ let scheduled = false
88
+ let disposed = false
89
+
90
+ /** The switch is on by default; off means the page's own animations stay as written. */
91
+ const enabled = () => getConfig().animations !== false
92
+
93
+ const clear = () => {
94
+ if (state.css === '') return
95
+ state.css = ''
96
+ state.entries = []
97
+ element.textContent = ''
98
+ }
99
+
100
+ const run = () => {
101
+ if (disposed) return
102
+ if (!enabled()) {
103
+ clear()
104
+ return
105
+ }
106
+ const plan = planSheets(pageSheets(element.sheet))
107
+ state.entries = plan.entries
108
+ state.scans += 1
109
+ if (plan.css !== state.css) {
110
+ state.css = plan.css
111
+ element.textContent = plan.css
112
+ }
113
+ if (debugEnabled()) {
114
+ console.info(`[dsh-ui-smooth] ${plan.entries.length} idle animation(s) moved off the layout/paint path`, plan.entries)
115
+ }
116
+ }
117
+
118
+ const schedule = () => {
119
+ if (scheduled || disposed || !enabled()) return
120
+ scheduled = true
121
+ requestAnimationFrame(() => {
122
+ scheduled = false
123
+ run()
124
+ })
125
+ }
126
+
127
+ const observer = new MutationObserver((records) => {
128
+ for (const record of records) {
129
+ if (record.target === element) continue
130
+ for (const node of record.addedNodes ?? []) {
131
+ if (node === element) continue
132
+ if (node.nodeType === 1) {
133
+ const tag = node.tagName
134
+ if (tag === 'STYLE' || tag === 'LINK') return schedule()
135
+ }
136
+ }
137
+ for (const node of record.removedNodes ?? []) {
138
+ if (node !== element && node.nodeType === 1) {
139
+ const tag = node.tagName
140
+ if (tag === 'STYLE' || tag === 'LINK') return schedule()
141
+ }
142
+ }
143
+ }
144
+ })
145
+ observer.observe(host, { childList: true, subtree: true })
146
+
147
+ const onResource = (event) => {
148
+ if (event.target instanceof HTMLLinkElement) schedule()
149
+ }
150
+ document.addEventListener('load', onResource, true)
151
+ document.addEventListener('error', onResource, true)
152
+
153
+ const stopListening = onConfig(() => {
154
+ if (enabled()) schedule()
155
+ else clear()
156
+ })
157
+
158
+ run()
159
+ schedule()
160
+
161
+ return {
162
+ status: () => ({ scans: state.scans, entries: state.entries.slice() }),
163
+ rescan: () => {
164
+ run()
165
+ return state.entries.slice()
166
+ },
167
+ restore: () => {
168
+ element.textContent = ''
169
+ state.css = ''
170
+ state.entries = []
171
+ },
172
+ dispose: () => {
173
+ disposed = true
174
+ stopListening()
175
+ observer.disconnect()
176
+ document.removeEventListener('load', onResource, true)
177
+ document.removeEventListener('error', onResource, true)
178
+ element.remove()
179
+ }
180
+ }
181
+ }
182
+
183
+ module.exports = { installAnimations }
184
+ }
185
+
186
+ registry['./animations.js'] = function (module, exports, require) {
187
+ /**
188
+ * Animation budget: find the expensive idle animations and rewrite the rule.
189
+ *
190
+ * Only `infinite` animations are touched. A sweep on the layout path becomes the
191
+ * same trajectory on `transform`; everything else is stepped down to a rate the
192
+ * renderer can afford. Finite, composited and reduced-motion animations are left
193
+ * exactly as they are.
194
+ */
195
+
196
+ /**
197
+ * Update rates kept for a coarsened animation. A layout update is cheap per
198
+ * sample and visibly choppy when under-sampled, so it keeps more steps; a
199
+ * paint-path shimmer re-rasterizes its glyphs on every update, so it is stepped
200
+ * harder.
201
+ */
202
+ const LAYOUT_UPDATES_PER_SECOND = 8
203
+ const PAINT_UPDATES_PER_SECOND = 4
204
+
205
+ /* ------------------------------------------------------------------ *
206
+ * Property classification
207
+ * ------------------------------------------------------------------ */
208
+
209
+ const LAYOUT_PROPERTIES = new Set([
210
+ 'left', 'right', 'top', 'bottom', 'inset',
211
+ 'inset-block', 'inset-block-start', 'inset-block-end',
212
+ 'inset-inline', 'inset-inline-start', 'inset-inline-end',
213
+ 'width', 'height', 'min-width', 'min-height', 'max-width', 'max-height',
214
+ 'inline-size', 'block-size', 'min-inline-size', 'min-block-size', 'max-inline-size', 'max-block-size',
215
+ 'margin', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
216
+ 'margin-block', 'margin-block-start', 'margin-block-end',
217
+ 'margin-inline', 'margin-inline-start', 'margin-inline-end',
218
+ 'padding', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
219
+ 'padding-block', 'padding-block-start', 'padding-block-end',
220
+ 'padding-inline', 'padding-inline-start', 'padding-inline-end',
221
+ 'border-width', 'border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width',
222
+ 'gap', 'row-gap', 'column-gap', 'flex-basis',
223
+ 'grid-template-columns', 'grid-template-rows', 'grid-auto-columns', 'grid-auto-rows',
224
+ 'font-size', 'line-height', 'letter-spacing', 'word-spacing', 'text-indent',
225
+ 'column-width', 'column-count'
226
+ ])
227
+
228
+ const PAINT_PROPERTIES = new Set([
229
+ 'background', 'background-image', 'background-position',
230
+ 'background-position-x', 'background-position-y', 'background-size'
231
+ ])
232
+
233
+ /* ------------------------------------------------------------------ *
234
+ * CSSOM helpers
235
+ * ------------------------------------------------------------------ */
236
+
237
+ function splitList(value) {
238
+ const parts = []
239
+ let depth = 0
240
+ let current = ''
241
+ for (const character of value ?? '') {
242
+ if (character === '(') depth += 1
243
+ else if (character === ')') depth = Math.max(0, depth - 1)
244
+ if (character === ',' && depth === 0) {
245
+ parts.push(current.trim())
246
+ current = ''
247
+ continue
248
+ }
249
+ current += character
250
+ }
251
+ if (current.trim() !== '') parts.push(current.trim())
252
+ return parts
253
+ }
254
+
255
+ function at(list, index) {
256
+ if (list.length === 0) return ''
257
+ return list[index % list.length]
258
+ }
259
+
260
+ function parseTime(value) {
261
+ const match = /^(-?\d*\.?\d+)(ms|s)$/.exec((value ?? '').trim())
262
+ if (match === null) return 0
263
+ const amount = Number(match[1])
264
+ return match[2] === 'ms' ? amount : amount * 1000
265
+ }
266
+
267
+ function pixelValue(value) {
268
+ const match = /^(-?\d*\.?\d+)px$/.exec((value ?? '').trim())
269
+ return match === null ? null : Number(match[1])
270
+ }
271
+
272
+ function declarationEntries(style) {
273
+ const entries = []
274
+ if (style === undefined || style === null) return entries
275
+ const count = typeof style.length === 'number' ? style.length : 0
276
+ for (let index = 0; index < count; index += 1) {
277
+ const property = style.item === undefined ? style[index] : style.item(index)
278
+ if (typeof property !== 'string' || property === '') continue
279
+ entries.push([property, style.getPropertyValue(property)])
280
+ }
281
+ return entries
282
+ }
283
+
284
+ function readAnimations(style) {
285
+ const names = splitList(style.getPropertyValue('animation-name'))
286
+ if (names.length === 0) return []
287
+ const durations = splitList(style.getPropertyValue('animation-duration'))
288
+ const iterations = splitList(style.getPropertyValue('animation-iteration-count'))
289
+ return names.map((name, index) => ({
290
+ name,
291
+ durationMs: parseTime(at(durations, index)),
292
+ infinite: at(iterations, index).trim() === 'infinite'
293
+ }))
294
+ }
295
+
296
+ function keyframeOffsets(keyText) {
297
+ return splitList(keyText).map((token) => {
298
+ const trimmed = token.toLowerCase()
299
+ if (trimmed === 'from') return 0
300
+ if (trimmed === 'to') return 1
301
+ const match = /^(-?\d*\.?\d+)%$/.exec(trimmed)
302
+ return match === null ? null : Number(match[1]) / 100
303
+ })
304
+ }
305
+
306
+ function readKeyframes(rule) {
307
+ const frames = []
308
+ const frames_ = rule.cssRules ?? []
309
+ for (let index = 0; index < frames_.length; index += 1) {
310
+ const frame = frames_[index]
311
+ const offsets = keyframeOffsets(frame.keyText ?? '')
312
+ if (offsets.length === 0 || offsets.some((offset) => offset === null)) continue
313
+ frames.push({ offsets, declarations: declarationEntries(frame.style) })
314
+ }
315
+ frames.sort((left, right) => left.offsets[0] - right.offsets[0])
316
+ return frames
317
+ }
318
+
319
+ function animatedProperties(frames) {
320
+ const properties = new Set()
321
+ for (const frame of frames) {
322
+ for (const [property] of frame.declarations) properties.add(property)
323
+ }
324
+ return properties
325
+ }
326
+
327
+ function classify(properties) {
328
+ for (const property of properties) {
329
+ if (LAYOUT_PROPERTIES.has(property)) return 'layout'
330
+ }
331
+ for (const property of properties) {
332
+ if (PAINT_PROPERTIES.has(property)) return 'paint'
333
+ }
334
+ return null
335
+ }
336
+
337
+ /* ------------------------------------------------------------------ *
338
+ * Animation repairs
339
+ * ------------------------------------------------------------------ */
340
+
341
+ function stepCount(durationMs, updatesPerSecond) {
342
+ const duration = durationMs > 0 ? durationMs : 2600
343
+ return Math.min(60, Math.max(3, Math.round((duration / 1000) * updatesPerSecond)))
344
+ }
345
+
346
+ function coarsen(name, frames, durationMs, updatesPerSecond) {
347
+ const total = stepCount(durationMs, updatesPerSecond)
348
+ const body = []
349
+ for (let index = 0; index < frames.length; index += 1) {
350
+ const frame = frames[index]
351
+ const next = frames[index + 1]
352
+ const declarations = frame.declarations.map(([property, value]) => `${property}: ${value}`)
353
+ if (next !== undefined) {
354
+ const share = Math.max(0, (next.offsets[0] ?? 1) - (frame.offsets[0] ?? 0))
355
+ const steps = Math.max(2, Math.round(total * (share === 0 ? 1 : share)))
356
+ declarations.push(`animation-timing-function: steps(${steps}, end)`)
357
+ }
358
+ const selectorText = frame.offsets.map((offset) => `${round(offset * 100)}%`).join(', ')
359
+ body.push(` ${selectorText} { ${declarations.join('; ')} }`)
360
+ }
361
+ return { name, body: body.join('\n') }
362
+ }
363
+
364
+ function round(value) {
365
+ return Math.round(value * 10000) / 10000
366
+ }
367
+
368
+ function planSweep(selector, style, frames) {
369
+ if (!/::?(after|before)\s*$/.test(selector)) return null
370
+
371
+ const properties = animatedProperties(frames)
372
+ if (properties.size !== 1 || !properties.has('left')) return null
373
+ if (frames.length < 2) return null
374
+
375
+ const values = []
376
+ for (const frame of frames) {
377
+ const left = frame.declarations.find(([property]) => property === 'left')
378
+ if (left === undefined) return null
379
+ values.push(left[1].trim())
380
+ }
381
+
382
+ const start = pixelValue(values[0])
383
+ if (start === null || start >= 0) return null
384
+ if (!/^100%$/.test(values[values.length - 1])) return null
385
+ for (const value of values.slice(1, -1)) {
386
+ if (pixelValue(value) === null && !/^-?\d*\.?\d+%$/.test(value)) return null
387
+ }
388
+
389
+ const base = new Map(declarationEntries(style))
390
+ const position = (base.get('position') ?? '').trim()
391
+ if (position !== 'absolute' && position !== 'fixed') return null
392
+ const backgroundImage = (base.get('background-image') ?? '').trim()
393
+ if (backgroundImage === '' || backgroundImage === 'none') return null
394
+ const backgroundColor = (base.get('background-color') ?? '').trim()
395
+ if (backgroundColor !== '' && backgroundColor !== 'transparent' && backgroundColor !== 'rgba(0, 0, 0, 0)') return null
396
+
397
+ const bandWidth = pixelValue(base.get('width') ?? '')
398
+ const width = bandWidth === null ? Math.abs(start) : bandWidth
399
+ if (width <= 0) return null
400
+
401
+ return {
402
+ declarations: [
403
+ 'left: 0 !important',
404
+ 'width: 100% !important',
405
+ `background-size: ${width}px 100% !important`,
406
+ 'background-repeat: no-repeat !important'
407
+ ],
408
+ keyframes: {
409
+ body: frames
410
+ .map((frame) => {
411
+ const left = frame.declarations.find(([property]) => property === 'left')[1].trim()
412
+ const selectorText = frame.offsets.map((offset) => `${round(offset * 100)}%`).join(', ')
413
+ return ` ${selectorText} { transform: translateX(${left}) }`
414
+ })
415
+ .join('\n')
416
+ }
417
+ }
418
+ }
419
+
420
+ function isKeyframesRule(rule) {
421
+ if (rule === null || typeof rule !== 'object') return false
422
+ if (rule.type === 7) return true
423
+ return typeof rule.name === 'string' && typeof rule.appendRule === 'function'
424
+ }
425
+
426
+ function isStyleRule(rule) {
427
+ if (rule === null || typeof rule !== 'object') return false
428
+ if (typeof rule.selectorText !== 'string' || rule.style === undefined) return false
429
+ return rule.selectorText.trim() !== ''
430
+ }
431
+
432
+ function walkRules(rules, visit) {
433
+ for (let index = 0; index < rules.length; index += 1) {
434
+ const rule = rules[index]
435
+ if (rule === null || typeof rule !== 'object') continue
436
+ visit(rule)
437
+ const nested = rule.cssRules
438
+ if (nested !== undefined && nested !== null && nested.length > 0 && !isKeyframesRule(rule)) {
439
+ walkRules(nested, visit)
440
+ }
441
+ }
442
+ }
443
+
444
+ function planSheets(sheets) {
445
+ const keyframesByName = new Map()
446
+ const styleRules = []
447
+
448
+ for (const sheet of sheets) {
449
+ let rules
450
+ try {
451
+ rules = sheet.cssRules
452
+ } catch (reason) {
453
+ continue
454
+ }
455
+ if (rules === undefined || rules === null) continue
456
+ walkRules(rules, (rule) => {
457
+ if (isKeyframesRule(rule)) {
458
+ keyframesByName.set(rule.name, rule)
459
+ return
460
+ }
461
+ if (isStyleRule(rule)) styleRules.push(rule)
462
+ })
463
+ }
464
+
465
+ const entries = []
466
+ const blocks = []
467
+ let generated = 0
468
+
469
+ for (const rule of styleRules) {
470
+ const animations = readAnimations(rule.style)
471
+ if (animations.length === 0) continue
472
+
473
+ const patches = []
474
+ for (const animation of animations) {
475
+ if (!animation.infinite) continue
476
+ const keyframes = keyframesByName.get(animation.name)
477
+ if (keyframes === undefined) continue
478
+ const frames = readKeyframes(keyframes)
479
+ const kind = classify(animatedProperties(frames))
480
+ if (kind === null) continue
481
+
482
+ if (kind === 'layout' && animations.length === 1) {
483
+ const sweep = planSweep(rule.selectorText, rule.style, frames)
484
+ if (sweep !== null) {
485
+ generated += 1
486
+ patches.push({
487
+ animation,
488
+ kind: 'sweep',
489
+ name: `dsh-ui-smooth-sweep-${generated}`,
490
+ declarations: sweep.declarations,
491
+ keyframes: sweep.keyframes
492
+ })
493
+ continue
494
+ }
495
+ }
496
+
497
+ generated += 1
498
+ patches.push({
499
+ animation,
500
+ kind: kind === 'layout' ? 'steps-layout' : 'steps-paint',
501
+ name: `dsh-ui-smooth-steps-${generated}`,
502
+ declarations: [],
503
+ keyframes: coarsen(
504
+ `dsh-ui-smooth-steps-${generated}`,
505
+ frames,
506
+ animation.durationMs,
507
+ kind === 'layout' ? LAYOUT_UPDATES_PER_SECOND : PAINT_UPDATES_PER_SECOND
508
+ )
509
+ })
510
+ }
511
+
512
+ if (patches.length === 0) continue
513
+
514
+ const renamed = new Map(patches.map((patch) => [patch.animation.name, patch.name]))
515
+ const declarations = patches.flatMap((patch) => patch.declarations)
516
+ declarations.push(`animation-name: ${animations.map((animation) => renamed.get(animation.name) ?? animation.name).join(', ')} !important`)
517
+
518
+ blocks.push(`${rule.selectorText} {\n ${declarations.join(';\n ')};\n}`)
519
+ for (const patch of patches) blocks.push(`@keyframes ${patch.name} {\n${patch.keyframes.body}\n}`)
520
+
521
+ for (const patch of patches) {
522
+ entries.push({ selector: rule.selectorText, animation: patch.animation.name, kind: patch.kind })
523
+ }
524
+ }
525
+
526
+ const css = blocks.length === 0
527
+ ? ''
528
+ : `@media (prefers-reduced-motion: no-preference) {\n${blocks.join('\n')}\n}\n`
529
+
530
+ return { css, entries }
531
+ }
532
+
533
+ module.exports = {
534
+ LAYOUT_PROPERTIES,
535
+ PAINT_PROPERTIES,
536
+ classify,
537
+ coarsen,
538
+ planSheets,
539
+ planSweep,
540
+ readAnimations,
541
+ readKeyframes
542
+ }
543
+ }
544
+
545
+ registry['./config.js'] = function (module, exports, require) {
546
+ /**
547
+ * The host half owns the file at `$DSH_HOME/dsh-ui-smooth.json` and serves it over
548
+ * `/dsh-ui-smooth/config`; the page keeps a copy, publishes it to every listener,
549
+ * and writes back through the same route.
550
+ */
551
+
552
+ const CONFIG_URL = '/dsh-ui-smooth/config'
553
+ const DEBUG_KEY = 'dsh-ui-smooth:debug'
554
+
555
+ /** Shown in the settings header and reported by the debug handle. */
556
+ const VERSION = '0.1.1'
557
+
558
+ /* ------------------------------------------------------------------ *
559
+ * Config
560
+ * ------------------------------------------------------------------ */
561
+
562
+ const DEFAULTS = {
563
+ animations: true,
564
+ backgroundThrottle: true,
565
+ duringStream: true,
566
+ follow: true,
567
+ skip: { enabled: true, turns: 3, minutes: 5 },
568
+ unmount: { enabled: true, turns: 5, minutes: 16 },
569
+ release: { enabled: false, turns: 8, minutes: 20 }
570
+ }
571
+
572
+ let config = cloneConfig(DEFAULTS)
573
+ const configListeners = new Set()
574
+
575
+ /** Read one tier of the thresholds; anything missing falls back to the default. */
576
+ function readTier(source, key) {
577
+ const tier = source?.[key] ?? {}
578
+ return {
579
+ enabled: tier.enabled !== false,
580
+ turns: numberOr(tier.turns, DEFAULTS[key].turns),
581
+ minutes: numberOr(tier.minutes, DEFAULTS[key].minutes)
582
+ }
583
+ }
584
+
585
+ /** The aggressive tier keeps a tail and drops what has been quiet long enough. */
586
+ function readRelease(source) {
587
+ const tier = source?.release ?? {}
588
+ return {
589
+ enabled: tier.enabled === true,
590
+ turns: Math.max(2, numberOr(tier.turns, DEFAULTS.release.turns)),
591
+ minutes: numberOr(tier.minutes, DEFAULTS.release.minutes)
592
+ }
593
+ }
594
+
595
+ function cloneConfig(source) {
596
+ const base = source !== null && typeof source === 'object' ? source : {}
597
+ return {
598
+ animations: base.animations !== false,
599
+ backgroundThrottle: base.backgroundThrottle !== false,
600
+ duringStream: base.duringStream !== false,
601
+ follow: base.follow !== false,
602
+ skip: readTier(base, 'skip'),
603
+ unmount: readTier(base, 'unmount'),
604
+ release: readRelease(base)
605
+ }
606
+ }
607
+
608
+ function numberOr(value, fallback) {
609
+ const number = Number(value)
610
+ if (!Number.isFinite(number) || number < 0) return fallback
611
+ return Math.min(10000, Math.floor(number))
612
+ }
613
+
614
+ function publishConfig(next) {
615
+ config = cloneConfig(next)
616
+ for (const listener of configListeners) {
617
+ try {
618
+ listener(config)
619
+ } catch (reason) {
620
+ /* a settings panel that threw must not stop the rest */
621
+ }
622
+ }
623
+ }
624
+
625
+ async function loadConfig() {
626
+ try {
627
+ const response = await fetch(CONFIG_URL, { headers: { accept: 'application/json' } })
628
+ if (!response.ok) return
629
+ const body = await response.json()
630
+ if (body?.config !== undefined) publishConfig(body.config)
631
+ } catch (reason) {
632
+ /* a page without the host route keeps the defaults */
633
+ }
634
+ }
635
+
636
+ async function saveConfig(patch) {
637
+ publishConfig({ ...config, ...patch })
638
+ try {
639
+ await fetch(CONFIG_URL, {
640
+ method: 'POST',
641
+ headers: { 'content-type': 'application/json' },
642
+ body: JSON.stringify(config)
643
+ })
644
+ } catch (reason) {
645
+ /* the in-memory value still applies; the next page reads the stored one */
646
+ }
647
+ }
648
+
649
+ /** Whether the page asked for the console diagnostics. */
650
+ function debugEnabled() {
651
+ try {
652
+ return window.localStorage.getItem(DEBUG_KEY) === '1'
653
+ } catch (reason) {
654
+ return false
655
+ }
656
+ }
657
+
658
+ /** Subscribe to config changes; returns the unsubscribe. */
659
+ function onConfig(listener) {
660
+ configListeners.add(listener)
661
+ return () => configListeners.delete(listener)
662
+ }
663
+
664
+ module.exports = {
665
+ DEFAULTS,
666
+ VERSION,
667
+ cloneConfig,
668
+ debugEnabled,
669
+ getConfig: () => config,
670
+ loadConfig,
671
+ onConfig,
672
+ publishConfig,
673
+ saveConfig
674
+ }
675
+ }
676
+
677
+ registry['./follow.js'] = function (module, exports, require) {
678
+ /**
679
+ * Come back to the tail.
680
+ *
681
+ * A hidden window produces no frames, so the transcript keeps growing unseen
682
+ * while the scroll offset stays where the reader left it: the burst that lands
683
+ * on return is added above the viewport, and the newest answer sits below it.
684
+ *
685
+ * A reader who was at the bottom before the window left wanted to see that
686
+ * answer, so returning puts them back on it — one scroll past the frames the
687
+ * renderer queued while hidden, which is after the app's own catch-up. A reader
688
+ * who was somewhere in the history keeps their place: the offset they were
689
+ * reading at is the one thing that must not move.
690
+ */
691
+
692
+ const { getConfig } = require('./config.js')
693
+
694
+ const SCROLL_SELECTOR = '[data-conversation-scroll]'
695
+
696
+ /** Slack allowed when deciding the reader was at the bottom. */
697
+ const TAIL_SLACK = 24
698
+
699
+ function createFollow() {
700
+ /** Whether the reader was at the bottom when the window left; null until it does. */
701
+ let pinned = null
702
+
703
+ function remember() {
704
+ if (getConfig().follow === false) {
705
+ pinned = null
706
+ return
707
+ }
708
+ const scroller = document.querySelector(SCROLL_SELECTOR)
709
+ if (scroller === null) {
710
+ pinned = null
711
+ return
712
+ }
713
+ pinned = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight <= TAIL_SLACK
714
+ }
715
+
716
+ function land() {
717
+ const scroller = document.querySelector(SCROLL_SELECTOR)
718
+ if (scroller === null) return
719
+ scroller.scrollTop = scroller.scrollHeight
720
+ }
721
+
722
+ function onVisibility() {
723
+ if (document.visibilityState === 'hidden') {
724
+ remember()
725
+ return
726
+ }
727
+ const wasPinned = pinned
728
+ pinned = null
729
+ if (wasPinned !== true) return
730
+ // Two frames: the first lets the app finish the paint it owed the reader,
731
+ // the second lands on the tail that paint produced.
732
+ requestAnimationFrame(() => {
733
+ land()
734
+ requestAnimationFrame(land)
735
+ })
736
+ }
737
+
738
+ document.addEventListener('visibilitychange', onVisibility)
739
+
740
+ return {
741
+ dispose: () => document.removeEventListener('visibilitychange', onVisibility)
742
+ }
743
+ }
744
+
745
+ module.exports = { createFollow }
746
+ }
747
+
748
+ registry['./keepawake.js'] = function (module, exports, require) {
749
+ /**
750
+ * Keep the page running while it is not in front.
751
+ *
752
+ * Every Chromium browser, and the Electron shell around DSH, throttles a
753
+ * renderer whose window is hidden or covered: timers slow to a crawl and frames
754
+ * stop, so a streamed answer piles up and lands in one burst when the reader
755
+ * comes back. A page that is playing audio is exempt from that throttling,
756
+ * wherever it runs, so the switch holds an audio stream open — a 40 Hz
757
+ * oscillator at a gain far below audibility, which adds no sound.
758
+ */
759
+
760
+ const INAUDIBLE_GAIN = 0.0001
761
+ const INAUDIBLE_HZ = 40
762
+
763
+ const GESTURES = ['pointerdown', 'keydown', 'wheel', 'touchstart']
764
+
765
+ function createKeepAwake() {
766
+ let context = null
767
+ let source = null
768
+ let waiting = false
769
+
770
+ const start = () => {
771
+ if (context !== null) return false
772
+ if (typeof window.AudioContext !== 'function') return false
773
+ try {
774
+ const next = new window.AudioContext()
775
+ const gain = next.createGain()
776
+ gain.gain.value = INAUDIBLE_GAIN
777
+ const oscillator = next.createOscillator()
778
+ oscillator.frequency.value = INAUDIBLE_HZ
779
+ oscillator.connect(gain)
780
+ gain.connect(next.destination)
781
+ oscillator.start()
782
+ context = next
783
+ source = oscillator
784
+ wake()
785
+ return true
786
+ } catch (reason) {
787
+ context = null
788
+ source = null
789
+ return false
790
+ }
791
+ }
792
+
793
+ /**
794
+ * A context built before the page saw a gesture starts suspended, and a
795
+ * suspended context buys nothing: Chromium only exempts a renderer that is
796
+ * actually playing. Hold the first gesture and the return to the front as
797
+ * the moments to ask again.
798
+ */
799
+ function wake() {
800
+ if (context === null || context.state !== 'suspended') {
801
+ waiting = false
802
+ return
803
+ }
804
+ context.resume().then(() => {
805
+ if (context !== null && context.state === 'running') waiting = false
806
+ }).catch(() => {})
807
+ if (waiting) return
808
+ waiting = true
809
+ for (const name of GESTURES) window.addEventListener(name, wake, { capture: true, once: true, passive: true })
810
+ document.addEventListener('visibilitychange', wake)
811
+ }
812
+
813
+ function unwind() {
814
+ for (const name of GESTURES) window.removeEventListener(name, wake, { capture: true })
815
+ document.removeEventListener('visibilitychange', wake)
816
+ waiting = false
817
+ }
818
+
819
+ const stop = () => {
820
+ if (context === null) return false
821
+ try {
822
+ source?.stop()
823
+ source?.disconnect()
824
+ context.close()
825
+ } catch (reason) {
826
+ /* a closed context has nothing left to release */
827
+ }
828
+ context = null
829
+ source = null
830
+ unwind()
831
+ return true
832
+ }
833
+
834
+ return {
835
+ start,
836
+ stop,
837
+ status: () => ({
838
+ active: context !== null,
839
+ state: context === null ? 'idle' : context.state
840
+ })
841
+ }
842
+ }
843
+
844
+ module.exports = { createKeepAwake }
845
+ }
846
+
847
+ registry['./main.js'] = function (module, exports, require) {
848
+ /**
849
+ * Module face: install the page halves into one cordis plugin.
850
+ *
851
+ * Everything the page does hangs off this `apply`: the animation stylesheet, the
852
+ * transcript recycler, the settings section, and the debug handle that reports
853
+ * what they are doing.
854
+ */
855
+
856
+ const { installAnimations } = require('./animate.js')
857
+ const { LAYOUT_PROPERTIES, PAINT_PROPERTIES, classify, coarsen, planSheets, planSweep, readAnimations, readKeyframes } = require('./animations.js')
858
+ const { VERSION, cloneConfig, getConfig, loadConfig, onConfig } = require('./config.js')
859
+ const { createFollow } = require('./follow.js')
860
+ const { createKeepAwake } = require('./keepawake.js')
861
+ const { CONTAINMENT_CSS, createRecycler } = require('./recycle.js')
862
+ const { mainSessions, sliceHistory } = require('./release.js')
863
+ const { SETTINGS_CSS, SettingsSection } = require('./settings.js')
864
+
865
+ const CSS_ID = 'dsh-ui-smooth/css'
866
+
867
+ function installStyleSheet() {
868
+ if (document.getElementById(CSS_ID) !== null) return
869
+ const element = document.createElement('style')
870
+ element.id = CSS_ID
871
+ element.textContent = `${CONTAINMENT_CSS}\n${SETTINGS_CSS}`
872
+ ;(document.head ?? document.documentElement).appendChild(element)
873
+ }
874
+
875
+ function apply(ctx) {
876
+ installStyleSheet()
877
+ const animations = installAnimations()
878
+ const recycler = createRecycler(ctx)
879
+ const follow = createFollow()
880
+ const keepAwake = createKeepAwake()
881
+ const slotIds = () => {
882
+ try {
883
+ return ctx?.slots?.entries?.('settings.section')?.map?.((entry) => entry.id) ?? []
884
+ } catch (reason) {
885
+ return []
886
+ }
887
+ }
888
+
889
+ const handle = {
890
+ version: VERSION,
891
+ status: () => ({
892
+ animations: animations.status(),
893
+ recycling: recycler.stats(),
894
+ config: cloneConfig(getConfig()),
895
+ settingsSection: slotIds()
896
+ }),
897
+ rescan: () => animations.rescan(),
898
+ recycle: () => recycler.pass(),
899
+ refreshConfig: () => loadConfig().then(() => {
900
+ recycler.pass()
901
+ return cloneConfig(getConfig())
902
+ }),
903
+ restore: () => animations.restore(),
904
+ config: () => cloneConfig(getConfig()),
905
+ throttle: () => keepAwake.status(),
906
+ /** What the aggressive tier sees: the loaded window it would trim. */
907
+ history: () => {
908
+ const session = mainSessions(ctx?.sessions)[0]
909
+ if (session === undefined || session === null) return null
910
+ let entries = []
911
+ try {
912
+ entries = session.eventSource?.getSnapshot?.()?.entries ?? []
913
+ } catch (reason) {
914
+ entries = []
915
+ }
916
+ return {
917
+ sessionId: session.sessionId,
918
+ entries: entries.length,
919
+ turns: entries.filter((entry) => entry?.event?.type === 'turn/start').length,
920
+ baseSeq: session.baseSeq,
921
+ hasMore: session.hasMore === true
922
+ }
923
+ }
924
+ }
925
+ window.__dshUiSmooth = handle
926
+
927
+ /**
928
+ * The switch reads "throttle me in the background". Off means the page keeps
929
+ * running there: the host half asks the shell when it is inside one, and the
930
+ * page holds an inaudible audio stream open for the case where it is not.
931
+ */
932
+ const syncThrottle = () => {
933
+ // "Do not throttle in the background" is a request the page can honour
934
+ // whatever hosts it: the shell's own escape hatch is out of reach from a
935
+ // Node-mode host, so the audio stream is the only lever, and a browser
936
+ // tab wants the same thing. Asking for it twice would only cost an
937
+ // idle oscillator.
938
+ if (getConfig().backgroundThrottle === false) keepAwake.start()
939
+ else keepAwake.stop()
940
+ }
941
+
942
+ onConfig(() => {
943
+ recycler.restoreAll()
944
+ syncThrottle()
945
+ })
946
+
947
+ loadConfig().then(() => {
948
+ recycler.pass()
949
+ syncThrottle()
950
+ })
951
+
952
+ if (ctx !== undefined && ctx !== null && typeof ctx.slots?.inject === 'function') {
953
+ ctx.slots.inject('settings.section', () =>
954
+ ctx.slots.register({
955
+ name: 'settings.section',
956
+ id: 'dsh-ui-smooth',
957
+ order: 60,
958
+ label: () => '流畅性',
959
+ registrant: 'dsh-ui-smooth'
960
+ }, SettingsSection)
961
+ )
962
+ }
963
+
964
+ if (ctx !== undefined && ctx !== null && typeof ctx.effect === 'function') {
965
+ ctx.effect(() => () => {
966
+ animations.dispose()
967
+ follow.dispose()
968
+ keepAwake.stop()
969
+ recycler.dispose()
970
+ const css = document.getElementById(CSS_ID)
971
+ if (css !== null) css.remove()
972
+ if (window.__dshUiSmooth === handle) delete window.__dshUiSmooth
973
+ }, 'dsh-ui-smooth: page passes')
974
+ }
975
+ }
976
+
977
+ exports.apply = apply
978
+ exports.inject = ['slots', 'sessions']
979
+ exports.internals = {
980
+ LAYOUT_PROPERTIES,
981
+ PAINT_PROPERTIES,
982
+ classify,
983
+ coarsen,
984
+ planSheets,
985
+ planSweep,
986
+ readAnimations,
987
+ readKeyframes,
988
+ sliceHistory
989
+ }
990
+ }
991
+
992
+ registry['./recycle.js'] = function (module, exports, require) {
993
+ /**
994
+ * Transcript recycling: keep old turns out of the render path.
995
+ *
996
+ * Two tiers, both gated on "old enough and cold enough". `skip` asks the browser
997
+ * to stop rendering the subtree (`content-visibility: hidden`); `unmount` moves
998
+ * the row's nodes into a detached fragment and holds its measured height, so the
999
+ * transcript does not jump, and puts them back before the row can scroll into
1000
+ * view. Neither frees memory: React still owns every node.
1001
+ */
1002
+
1003
+ const { debugEnabled, getConfig, loadConfig } = require('./config.js')
1004
+ const { releaseHistory } = require('./release.js')
1005
+
1006
+ /* ------------------------------------------------------------------ *
1007
+ * Transcript recycling
1008
+ * ------------------------------------------------------------------ */
1009
+
1010
+ const ROW_ATTRIBUTE = 'data-ui-smooth'
1011
+ const HEIGHT_PROPERTY = '--ui-smooth-height'
1012
+
1013
+ /** How far outside the viewport a row still counts as being looked at. */
1014
+ const NEAR_BAND = 800
1015
+
1016
+ /**
1017
+ * Frames kept free of recycling work after the window comes back: the renderer
1018
+ * owes that moment to everything it skipped while hidden, and the transcript is
1019
+ * the heaviest thing to lay out.
1020
+ */
1021
+ const RESUME_GRACE_MS = 900
1022
+
1023
+ const CONTAINMENT_CSS = `
1024
+ [data-conversation-content] [${ROW_ATTRIBUTE}] {
1025
+ box-sizing: border-box;
1026
+ }
1027
+ [data-conversation-content] [${ROW_ATTRIBUTE}="skip"] {
1028
+ content-visibility: hidden;
1029
+ contain-intrinsic-size: auto var(${HEIGHT_PROPERTY}, 320px);
1030
+ min-height: var(${HEIGHT_PROPERTY}, 0);
1031
+ }
1032
+ [data-conversation-content] [${ROW_ATTRIBUTE}="parked"] {
1033
+ display: block;
1034
+ min-height: var(${HEIGHT_PROPERTY}, 40px);
1035
+ }
1036
+ `
1037
+
1038
+ /**
1039
+ * Two tiers, both gated on "old enough and cold enough" — a turn has to
1040
+ * be more than N turns behind the newest one *and* have been out of the
1041
+ * viewport for M minutes:
1042
+ *
1043
+ * skip the browser stops rendering the subtree (`content-visibility:
1044
+ * hidden`), which drops its layout, style and paint work while
1045
+ * the DOM stays where React put it.
1046
+ * unmount the subtree's nodes are moved out of the document into a
1047
+ * detached fragment, and the row keeps its measured height, so
1048
+ * the transcript does not jump. Scrolling anywhere near the
1049
+ * row puts the nodes back before it can be seen.
1050
+ *
1051
+ * Nothing is destroyed: React still owns the nodes, and a plugin that
1052
+ * deleted them would fail the next time React reconciles that subtree.
1053
+ * Detaching is the furthest a plugin can go, and it does drop the
1054
+ * browser's per-node layout and style bookkeeping along with the paint.
1055
+ */
1056
+ function createRecycler(ctx) {
1057
+ const seenAt = new WeakMap()
1058
+ /** When each turn was last mounted or looked at; outlives the row itself. */
1059
+ const warmth = new Map()
1060
+ const parked = new WeakMap()
1061
+ let root = null
1062
+ let nearObserver = null
1063
+ let timer = 0
1064
+ let idleHandle = 0
1065
+ let resumedAt = 0
1066
+ let releases = 0
1067
+
1068
+ /** The top-level flow and the turn rows directly inside it. */
1069
+ function inspect() {
1070
+ const flow = document.querySelector('[data-conversation-content] [data-chat-flow]')
1071
+ if (flow === null) return null
1072
+ const rows = []
1073
+ const candidates = flow.querySelectorAll('[data-chat-turn]')
1074
+ for (const row of candidates) {
1075
+ if (row.closest('[data-chat-flow]') !== flow) continue
1076
+ const turn = Number(row.getAttribute('data-chat-turn'))
1077
+ if (!Number.isSafeInteger(turn)) continue
1078
+ rows.push({ row, turn })
1079
+ }
1080
+ return rows.length === 0 ? null : { flow, rows }
1081
+ }
1082
+
1083
+ function watchNear(flow, rows) {
1084
+ const scroller = flow.closest('[data-conversation-scroll]')
1085
+ if (nearObserver === null || root !== scroller) {
1086
+ if (nearObserver !== null) nearObserver.disconnect()
1087
+ nearObserver = new IntersectionObserver((records) => {
1088
+ for (const record of records) {
1089
+ if (!record.isIntersecting) continue
1090
+ const seen = Date.now()
1091
+ seenAt.set(record.target, seen)
1092
+ const turn = Number(record.target.getAttribute('data-chat-turn'))
1093
+ if (Number.isSafeInteger(turn)) warmth.set(turn, seen)
1094
+ unpark(record.target)
1095
+ record.target.removeAttribute(ROW_ATTRIBUTE)
1096
+ }
1097
+ }, { root: scroller ?? null, rootMargin: '600px 0px 600px 0px' })
1098
+ root = scroller ?? null
1099
+ }
1100
+ // History arrives in chunks, so rows appear long after the observer was
1101
+ // built: observe on every pass or the late ones are never watched and
1102
+ // their parked content is never released.
1103
+ for (const entry of rows) nearObserver.observe(entry.row)
1104
+ }
1105
+
1106
+ /**
1107
+ * Move a turn's content out of the document, keeping its height so the
1108
+ * scroll position and every measurement around it stay stable.
1109
+ */
1110
+ function park(row, measuredHeight) {
1111
+ if (parked.has(row)) return false
1112
+ if (row.contains(document.activeElement)) return false
1113
+ const selection = window.getSelection()
1114
+ const anchor = selection === null || selection === undefined ? null : selection.anchorNode
1115
+ if (anchor !== null && row.contains(anchor)) return false
1116
+
1117
+ const fragment = document.createDocumentFragment()
1118
+ while (row.firstChild !== null) fragment.appendChild(row.firstChild)
1119
+ row.style.setProperty(HEIGHT_PROPERTY, `${Math.max(1, measuredHeight).toFixed(2)}px`)
1120
+ row.setAttribute(ROW_ATTRIBUTE, 'parked')
1121
+ parked.set(row, fragment)
1122
+ return true
1123
+ }
1124
+
1125
+ function keepHeight(row, measured) {
1126
+ if (!(measured >= 1)) return
1127
+ row.style.setProperty(HEIGHT_PROPERTY, `${measured.toFixed(2)}px`)
1128
+ }
1129
+
1130
+ /** Put a parked turn's content back where it was. */
1131
+ function unpark(row) {
1132
+ const fragment = parked.get(row)
1133
+ if (fragment === undefined) return false
1134
+ while (fragment.firstChild !== null) row.appendChild(fragment.firstChild)
1135
+ row.style.removeProperty(HEIGHT_PROPERTY)
1136
+ if (row.getAttribute(ROW_ATTRIBUTE) === 'parked') row.removeAttribute(ROW_ATTRIBUTE)
1137
+ parked.delete(row)
1138
+ return true
1139
+ }
1140
+
1141
+ /** Put everything back: the cheapest safe answer to any doubt. */
1142
+ function restoreAll() {
1143
+ for (const row of document.querySelectorAll(`[${ROW_ATTRIBUTE}="parked"]`)) unpark(row)
1144
+ for (const row of document.querySelectorAll(`[${ROW_ATTRIBUTE}="skip"]`)) {
1145
+ row.removeAttribute(ROW_ATTRIBUTE)
1146
+ row.style.removeProperty(HEIGHT_PROPERTY)
1147
+ }
1148
+ }
1149
+
1150
+ function pass() {
1151
+ const found = inspect()
1152
+ if (found === null) return
1153
+ watchNear(found.flow, found.rows)
1154
+
1155
+ const config = getConfig()
1156
+
1157
+ // Streaming is the one moment the app re-renders on its own, so the pass
1158
+ // stays away from the transcript unless the reader asked it not to.
1159
+ if (!config.duringStream && document.querySelector('[data-streaming]') !== null) return
1160
+
1161
+ // A hidden window paints nothing, so every measurement here would only
1162
+ // cost layout for a frame nobody sees — and parking by a box measured
1163
+ // while hidden risks a wrong height. The next visible frame re-measures.
1164
+ if (document.visibilityState !== 'visible') return
1165
+
1166
+ let newest = 0
1167
+ for (const entry of found.rows) newest = Math.max(newest, entry.turn)
1168
+ const now = Date.now()
1169
+ // The app is still catching up on the frames the hidden window skipped;
1170
+ // measuring the transcript in the same window would queue behind it.
1171
+ if (now - resumedAt < RESUME_GRACE_MS) {
1172
+ schedule(RESUME_GRACE_MS - (now - resumedAt) + 50)
1173
+ return
1174
+ }
1175
+ const skipMinutes = config.skip.minutes * 60000
1176
+ const unmountMinutes = config.unmount.minutes * 60000
1177
+ const scroller = found.flow.closest('[data-conversation-scroll]')
1178
+ const viewport = scroller === null
1179
+ ? { top: 0, bottom: window.innerHeight }
1180
+ : scroller.getBoundingClientRect()
1181
+
1182
+ // Read every box before the first mutation: interleaving the two forces a
1183
+ // fresh layout per row, which is the whole transcript's height at once.
1184
+ const boxes = new Map()
1185
+ const slots = new Map()
1186
+ const gap = parseFloat(getComputedStyle(found.flow).rowGap)
1187
+ const flowBottom = found.flow.getBoundingClientRect().bottom
1188
+ let previous = null
1189
+ for (const entry of found.rows) {
1190
+ const box = entry.row.getBoundingClientRect()
1191
+ boxes.set(entry.row, box)
1192
+ // The space a row takes in the flow is not its border box: a turn's
1193
+ // children carry margins that collapse through the row and count in the
1194
+ // layout without ever landing inside its measured height. Taking the gap
1195
+ // to the next row keeps that space, so parking one row moves nothing
1196
+ // below it.
1197
+ if (previous !== null) slots.set(previous.row, previous.top === null ? box.height : box.top - previous.top - (Number.isFinite(gap) ? gap : 0))
1198
+ previous = { row: entry.row, top: box.top }
1199
+ }
1200
+ if (previous !== null) slots.set(previous.row, flowBottom - previous.top - (Number.isFinite(gap) ? gap : 0))
1201
+
1202
+ let skipped = 0
1203
+ let unmounted = 0
1204
+
1205
+ if (warmth.size > 5000) warmth.clear()
1206
+ for (const entry of found.rows) {
1207
+ const box = boxes.get(entry.row)
1208
+ // A row in or near the viewport was just looked at, whatever the
1209
+ // observer has had time to report: keep it warm and leave it alone.
1210
+ const near = box.bottom > viewport.top - NEAR_BAND && box.top < viewport.bottom + NEAR_BAND
1211
+ if (near || !seenAt.has(entry.row)) {
1212
+ seenAt.set(entry.row, now)
1213
+ warmth.set(entry.turn, now)
1214
+ }
1215
+ const age = newest - entry.turn
1216
+ const cold = now - (seenAt.get(entry.row) ?? 0)
1217
+ const unmount = config.unmount.enabled
1218
+ && age > config.unmount.turns
1219
+ && age > config.skip.turns
1220
+ && cold > unmountMinutes
1221
+ const skip = config.skip.enabled
1222
+ && age > config.skip.turns
1223
+ && cold > skipMinutes
1224
+
1225
+ if (unmount) {
1226
+ if (entry.row.getAttribute(ROW_ATTRIBUTE) === 'parked') {
1227
+ unmounted += 1
1228
+ continue
1229
+ }
1230
+ if (!near && box.height >= 1 && park(entry.row, slots.get(entry.row) ?? box.height)) unmounted += 1
1231
+ continue
1232
+ }
1233
+
1234
+ unpark(entry.row)
1235
+ // A row with nothing to measure has nothing to hold open either: skipping
1236
+ // it would leave the transcript a 320px placeholder it never had.
1237
+ if (skip && box.height >= 1) {
1238
+ if (entry.row.getAttribute(ROW_ATTRIBUTE) !== 'skip') {
1239
+ keepHeight(entry.row, box.height)
1240
+ entry.row.setAttribute(ROW_ATTRIBUTE, 'skip')
1241
+ }
1242
+ skipped += 1
1243
+ } else if (entry.row.hasAttribute(ROW_ATTRIBUTE)) {
1244
+ entry.row.removeAttribute(ROW_ATTRIBUTE)
1245
+ entry.row.style.removeProperty(HEIGHT_PROPERTY)
1246
+ }
1247
+ }
1248
+
1249
+ if (config.release.enabled) {
1250
+ const quietMs = config.release.minutes * 60000
1251
+ releases += releaseHistory(ctx?.sessions, config.release, (turn) => now - (warmth.get(turn) ?? 0) > quietMs)
1252
+ }
1253
+
1254
+ if (debugEnabled()) {
1255
+ console.info(`[dsh-ui-smooth] ${skipped} turn(s) not rendered, ${unmounted} turn(s) parked outside the document, ${releases} window trim(s) total`, config)
1256
+ }
1257
+ }
1258
+
1259
+ function schedule(delayMs) {
1260
+ if (idleHandle !== 0 || timer !== 0) return
1261
+ const run = () => {
1262
+ idleHandle = 0
1263
+ timer = 0
1264
+ pass()
1265
+ }
1266
+ if (typeof requestIdleCallback === 'function') {
1267
+ idleHandle = requestIdleCallback(run, { timeout: Math.max(500, delayMs) })
1268
+ } else {
1269
+ timer = setTimeout(run, delayMs)
1270
+ }
1271
+ }
1272
+
1273
+ const onScroll = () => schedule(150)
1274
+ const onVisibility = () => {
1275
+ // Coming back must not put every parked row back into the document at
1276
+ // once: that lays the whole transcript out in one frame, on top of the
1277
+ // app's own catch-up. The observer returns only the rows near the
1278
+ // viewport, and this pass waits out the grace period first.
1279
+ if (document.visibilityState !== 'visible') return
1280
+ resumedAt = Date.now()
1281
+ schedule(RESUME_GRACE_MS + 200)
1282
+ }
1283
+ const onResize = () => {
1284
+ // Restoring a minimized window fires this, and putting every parked row
1285
+ // back here is the same whole-transcript burst the visibility handler
1286
+ // used to cause. The heights held for distant rows are stale, but only
1287
+ // the ones on screen need a real number now: the near band returns
1288
+ // those, and the rest re-measure when they are next looked at.
1289
+ resumedAt = Date.now()
1290
+ schedule(RESUME_GRACE_MS + 200)
1291
+ }
1292
+ const mutations = new MutationObserver(() => schedule(400))
1293
+ const ticker = setInterval(() => {
1294
+ if (document.visibilityState !== 'visible') return
1295
+ loadConfig().then(() => schedule(0))
1296
+ }, 30000)
1297
+
1298
+ document.addEventListener('scroll', onScroll, { capture: true, passive: true })
1299
+ document.addEventListener('visibilitychange', onVisibility)
1300
+ window.addEventListener('resize', onResize)
1301
+ mutations.observe(document.body, { childList: true, subtree: true })
1302
+ schedule(0)
1303
+
1304
+ return {
1305
+ pass: () => pass(),
1306
+ restoreAll: () => restoreAll(),
1307
+ stats: () => ({
1308
+ skipped: document.querySelectorAll(`[${ROW_ATTRIBUTE}="skip"]`).length,
1309
+ parked: document.querySelectorAll(`[${ROW_ATTRIBUTE}="parked"]`).length,
1310
+ released: releases
1311
+ }),
1312
+ dispose: () => {
1313
+ restoreAll()
1314
+ if (nearObserver !== null) nearObserver.disconnect()
1315
+ mutations.disconnect()
1316
+ clearInterval(ticker)
1317
+ if (timer !== 0) clearTimeout(timer)
1318
+ if (idleHandle !== 0 && typeof cancelIdleCallback === 'function') cancelIdleCallback(idleHandle)
1319
+ document.removeEventListener('scroll', onScroll, { capture: true })
1320
+ document.removeEventListener('visibilitychange', onVisibility)
1321
+ window.removeEventListener('resize', onResize)
1322
+ }
1323
+ }
1324
+ }
1325
+
1326
+ module.exports = { CONTAINMENT_CSS, createRecycler }
1327
+ }
1328
+
1329
+ registry['./release.js'] = function (module, exports, require) {
1330
+ /**
1331
+ * React owns the transcript, so a plugin that deletes nodes fails the next
1332
+ * reconcile. The one safe way to free them is to make React unmount those turns,
1333
+ * and the session controller already knows how: replace its loaded window with a
1334
+ * shorter one, then move the paging stream`s head with it so 加载更早 can bring the
1335
+ * history back from disk.
1336
+ */
1337
+
1338
+ /* ------------------------------------------------------------------ *
1339
+ * Aggressive release
1340
+ * ------------------------------------------------------------------ */
1341
+
1342
+ /**
1343
+ * Never bother dropping fewer turns than this: the next 加载更早 brings a
1344
+ * whole page (up to 500 messages) back, so a one-turn trim would only buy
1345
+ * a refetch loop.
1346
+ */
1347
+ const MIN_RELEASED_TURNS = 4
1348
+
1349
+ /**
1350
+ * Cut a loaded history window down to its newest `keepTurns` turns.
1351
+ *
1352
+ * Only a prefix goes: a turn is dropped when it sits before the kept tail *and*
1353
+ * nothing has looked at it for a while — a turn that was just paged back in
1354
+ * stays put until its own quiet period runs out. One warm turn stops the cut
1355
+ * there, because everything older goes with it.
1356
+ *
1357
+ * @param entries - the session's loaded window, oldest first.
1358
+ * @param keepTurns - turns to keep at the tail.
1359
+ * @param isCold - whether a turn has been out of sight long enough to drop.
1360
+ * @returns the slice to keep, or `null` when there is nothing worth dropping.
1361
+ */
1362
+ function sliceHistory(entries, keepTurns, isCold) {
1363
+ if (!Array.isArray(entries) || entries.length === 0) return null
1364
+ if (!Number.isSafeInteger(keepTurns) || keepTurns < 1) return null
1365
+ const starts = []
1366
+ const turns = []
1367
+ for (let index = 0; index < entries.length; index += 1) {
1368
+ const event = entries[index]?.event
1369
+ if (event?.type !== 'turn/start') continue
1370
+ const turn = Number(event.data?.turn)
1371
+ starts.push(index)
1372
+ turns.push(Number.isSafeInteger(turn) ? turn : starts.length)
1373
+ }
1374
+ const droppable = starts.length - keepTurns
1375
+ if (droppable < MIN_RELEASED_TURNS) return null
1376
+ let cut = -1
1377
+ for (let group = 0; group < droppable; group += 1) {
1378
+ if (typeof isCold === 'function' && !isCold(turns[group])) break
1379
+ cut = group
1380
+ }
1381
+ if (cut < MIN_RELEASED_TURNS - 1) return null
1382
+ return entries.slice(starts[cut + 1])
1383
+ }
1384
+
1385
+ /** The sessions the main view is showing (a retained session may also be a background one). */
1386
+ function mainSessions(service) {
1387
+ const sessions = []
1388
+ if (service === undefined || service === null) return sessions
1389
+ let snapshot
1390
+ try {
1391
+ snapshot = service.list?.getSnapshot?.()
1392
+ } catch (reason) {
1393
+ return sessions
1394
+ }
1395
+ for (const [id, row] of Object.entries(snapshot?.byId ?? {})) {
1396
+ if ((row?.retainedBy?.mainView ?? 0) === 0) continue
1397
+ try {
1398
+ const session = service.manager?.get?.(id)
1399
+ if (session !== undefined && session !== null) sessions.push(session)
1400
+ } catch (reason) {
1401
+ /* a session still opening simply is not a candidate yet */
1402
+ }
1403
+ }
1404
+ return sessions
1405
+ }
1406
+
1407
+ /**
1408
+ * Hand the oldest turns back to the disk.
1409
+ *
1410
+ * React owns the transcript, so a node a plugin deletes comes back as a
1411
+ * `NotFoundError` on the next reconcile. The one safe way to free those
1412
+ * nodes is to make React itself unmount the turns, and the session
1413
+ * controller already knows how: replace its loaded window with a shorter
1414
+ * one. `hasMore` stays true, so the app offers 加载更早 for exactly the
1415
+ * history that was dropped.
1416
+ *
1417
+ * A session that is streaming is left alone: the answer is still being written
1418
+ * into its tail, and trimming under it would move the page the reader is
1419
+ * watching. Everything else is fair game, wherever the reader has scrolled to.
1420
+ *
1421
+ * @returns how many sessions were trimmed.
1422
+ */
1423
+ function releaseHistory(service, release, isCold) {
1424
+ const keepTurns = release.turns
1425
+ let released = 0
1426
+ for (const session of mainSessions(service)) {
1427
+ if (session.openState !== 'open') continue
1428
+ if (session.running === true || session.loadingOlder === true) continue
1429
+ if (typeof session.installWindow !== 'function') continue
1430
+ let entries
1431
+ try {
1432
+ entries = session.eventSource?.getSnapshot?.()?.entries
1433
+ } catch (reason) {
1434
+ continue
1435
+ }
1436
+ const kept = sliceHistory(entries, keepTurns, isCold)
1437
+ if (kept === null) continue
1438
+ try {
1439
+ session.installWindow(kept, true)
1440
+ } catch (reason) {
1441
+ if (typeof console !== 'undefined') console.warn('[dsh-ui-smooth] release failed:', reason)
1442
+ continue
1443
+ }
1444
+ // The paging stream keeps its own idea of the oldest seq it holds,
1445
+ // and prepend drops every record newer than that idea. Move it with
1446
+ // the window or the dropped history can never be paged back.
1447
+ const stream = session.events
1448
+ if (stream !== null && stream !== undefined && 'firstCursor' in stream) {
1449
+ stream.firstCursor = kept[0]?.event?.seq
1450
+ }
1451
+ released += 1
1452
+ }
1453
+ return released
1454
+ }
1455
+
1456
+ module.exports = { mainSessions, releaseHistory, sliceHistory }
1457
+ }
1458
+
1459
+ registry['./settings.js'] = function (module, exports, require) {
1460
+ /**
1461
+ * The 流畅性 settings panel.
1462
+ *
1463
+ * Rendered into the app's own settings section slot, so it inherits the shell's
1464
+ * tokens and needs no portal of its own. Every switch here maps to one field of
1465
+ * the shared config, and each card states what the switch does to the page.
1466
+ */
1467
+
1468
+ const react = require('react')
1469
+ const h = react.createElement
1470
+
1471
+ const { VERSION, cloneConfig, getConfig, onConfig, saveConfig } = require('./config.js')
1472
+
1473
+ function Switch({ checked, disabled, onChange }) {
1474
+ return h('button', {
1475
+ type: 'button',
1476
+ role: 'switch',
1477
+ 'aria-checked': checked ? 'true' : 'false',
1478
+ disabled: disabled === true,
1479
+ className: `uis-switch${checked ? ' is-on' : ''}`,
1480
+ onClick: () => onChange(!checked)
1481
+ }, h('span', { className: 'uis-knob' }))
1482
+ }
1483
+
1484
+ function NumberField({ value, min, max, suffix, onChange }) {
1485
+ return h('label', { className: 'uis-number' },
1486
+ h('input', {
1487
+ type: 'number',
1488
+ value: String(value),
1489
+ min: String(min),
1490
+ max: String(max),
1491
+ onChange: (event) => {
1492
+ const next = Number(event.target.value)
1493
+ if (!Number.isFinite(next)) return
1494
+ onChange(Math.min(max, Math.max(min, Math.floor(next))))
1495
+ }
1496
+ }),
1497
+ suffix !== undefined ? h('span', { className: 'uis-suffix' }, suffix) : null
1498
+ )
1499
+ }
1500
+
1501
+ function Card({ title, hint, control, children }) {
1502
+ return h('div', { className: 'uis-card' }, [
1503
+ h('div', { className: 'uis-row' }, [
1504
+ h('div', { className: 'uis-text' }, [
1505
+ h('div', { className: 'uis-title' }, title),
1506
+ hint === undefined ? null : h('div', { className: 'uis-hint' }, hint)
1507
+ ]),
1508
+ control
1509
+ ]),
1510
+ children === undefined ? null : h('div', { className: 'uis-thresholds' }, children)
1511
+ ])
1512
+ }
1513
+
1514
+ function Group({ title, children }) {
1515
+ return h('div', { className: 'uis-group' }, [
1516
+ h('div', { className: 'uis-group-title' }, title),
1517
+ ...children
1518
+ ])
1519
+ }
1520
+
1521
+ function SettingsSection() {
1522
+ const [state, setState] = react.useState(getConfig)
1523
+ react.useEffect(() => onConfig((next) => setState(cloneConfig(next))), [])
1524
+
1525
+ const patch = (next) => {
1526
+ saveConfig(next)
1527
+ setState((current) => cloneConfig({ ...current, ...next }))
1528
+ }
1529
+ const patchTier = (key, changes) => patch({ [key]: { ...state[key], ...changes } })
1530
+ const toggle = (key) => h(Switch, {
1531
+ checked: state[key],
1532
+ onChange: (checked) => patch({ [key]: checked })
1533
+ })
1534
+
1535
+ return h('div', { className: 'uis-section' }, [
1536
+ h('div', { className: 'uis-head' }, [
1537
+ h('span', { className: 'uis-brand' }, 'DSH-UI-Smooth'),
1538
+ h('span', { className: 'uis-version' }, `v${VERSION}`)
1539
+ ]),
1540
+
1541
+ h(Group, { title: '渲染' }, [
1542
+ h(Card, {
1543
+ title: '启用动画优化',
1544
+ hint: '降低无限循环动画布局/重绘次数。DSH 已经对自身的旧动画进行了优化,此项主要解决其他插件/后续引入的动画每帧布局/重绘问题。',
1545
+ control: toggle('animations')
1546
+ })
1547
+ ]),
1548
+
1549
+ h(Group, { title: '前台与后台' }, [
1550
+ h(Card, {
1551
+ title: '后台节流',
1552
+ hint: '当关闭后 DSH 不是前台窗口时仍然保持界面照常推进,这样的好处是可以在切换回前台窗口时不用一次性加载积压的内容,保证观感流畅。',
1553
+ control: h(Switch, {
1554
+ checked: state.backgroundThrottle,
1555
+ onChange: (checked) => patch({ backgroundThrottle: checked })
1556
+ })
1557
+ }),
1558
+ h(Card, {
1559
+ title: '切回前台滚动到最新',
1560
+ hint: '切出前停在对话最底部时,切回前台后自动滚动到最新内容;切出前正在翻看历史时保持原位置不动。',
1561
+ control: toggle('follow')
1562
+ })
1563
+ ]),
1564
+
1565
+ h(Group, { title: '旧轮次回收' }, [
1566
+ h(Card, {
1567
+ title: '流式输出期间回收',
1568
+ hint: '在流式输出期间仍按下方阈值处理。',
1569
+ control: toggle('duringStream')
1570
+ }),
1571
+
1572
+ h(Card, {
1573
+ title: '旧轮次跳过渲染',
1574
+ hint: '当满足以下设置条件时,将不再渲染该条目的子树,在滚动接近时恢复渲染。',
1575
+ control: h(Switch, {
1576
+ checked: state.skip.enabled,
1577
+ onChange: (checked) => patchTier('skip', { enabled: checked })
1578
+ }),
1579
+ children: [
1580
+ h(NumberField, {
1581
+ value: state.skip.turns, min: 1, max: 200, suffix: '轮以前',
1582
+ onChange: (turns) => patchTier('skip', { turns })
1583
+ }),
1584
+ h('span', { className: 'uis-label' }, '且'),
1585
+ h(NumberField, {
1586
+ value: state.skip.minutes, min: 1, max: 1440, suffix: '分钟未查看',
1587
+ onChange: (minutes) => patchTier('skip', { minutes })
1588
+ })
1589
+ ]
1590
+ }),
1591
+
1592
+ h(Card, {
1593
+ title: '旧轮次从文档流摘除',
1594
+ hint: '当满足以下设置条件时,将条目从文档流摘除,在滚动接近时重新填入。',
1595
+ control: h(Switch, {
1596
+ checked: state.unmount.enabled,
1597
+ onChange: (checked) => patchTier('unmount', { enabled: checked })
1598
+ }),
1599
+ children: [
1600
+ h(NumberField, {
1601
+ value: state.unmount.turns, min: 1, max: 500, suffix: '轮以前',
1602
+ onChange: (turns) => patchTier('unmount', { turns })
1603
+ }),
1604
+ h('span', { className: 'uis-label' }, '且'),
1605
+ h(NumberField, {
1606
+ value: state.unmount.minutes, min: 1, max: 4320, suffix: '分钟未查看',
1607
+ onChange: (minutes) => patchTier('unmount', { minutes })
1608
+ })
1609
+ ]
1610
+ }),
1611
+
1612
+ h(Card, {
1613
+ title: '激进策略:旧轮次从内存卸载',
1614
+ hint: '当满足以下设置条件时,将条目从内存卸载,重新加载需要从硬盘获取。',
1615
+ control: h(Switch, {
1616
+ checked: state.release.enabled,
1617
+ onChange: (checked) => patch({ release: { ...state.release, enabled: checked } })
1618
+ }),
1619
+ children: [
1620
+ h(NumberField, {
1621
+ value: state.release.turns, min: 2, max: 500, suffix: '轮以前',
1622
+ onChange: (turns) => patch({ release: { ...state.release, turns } })
1623
+ }),
1624
+ h('span', { className: 'uis-label' }, '且重新加载后'),
1625
+ h(NumberField, {
1626
+ value: state.release.minutes, min: 1, max: 4320, suffix: '分钟未查看',
1627
+ onChange: (minutes) => patch({ release: { ...state.release, minutes } })
1628
+ })
1629
+ ]
1630
+ })
1631
+ ])
1632
+ ])
1633
+ }
1634
+
1635
+ const SETTINGS_CSS = `
1636
+ .uis-group { display: flex; flex-direction: column; gap: 8px; }
1637
+ .uis-group + .uis-group { margin-top: 10px; }
1638
+ .uis-group-title { color: var(--dsw-alias-label-secondary, inherit); font-size: 12px; font-weight: 600; letter-spacing: .04em; }
1639
+ .uis-section { display: flex; flex-direction: column; gap: 12px; font-size: 13px; color: var(--dsw-alias-label-primary, inherit); }
1640
+ .uis-head { display: flex; align-items: baseline; gap: 8px; }
1641
+ .uis-brand { font-weight: 600; letter-spacing: .01em; }
1642
+ .uis-version { color: var(--dsw-alias-label-tertiary, inherit); font-family: var(--dsw-font-mono, ui-monospace, monospace); font-size: 12px; }
1643
+ .uis-card { border: 1px solid var(--dsw-alias-border-secondary, rgba(127,127,127,.24)); border-radius: 10px; padding: 12px 14px; display: flex; flex-direction: column; gap: 10px; }
1644
+ .uis-row { display: flex; align-items: flex-start; gap: 16px; justify-content: space-between; }
1645
+ .uis-text { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
1646
+ .uis-title { font-weight: 600; }
1647
+ .uis-hint { color: var(--dsw-alias-label-tertiary, inherit); line-height: 1.5; }
1648
+ .uis-thresholds { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; color: var(--dsw-alias-label-secondary, inherit); }
1649
+ .uis-label { white-space: nowrap; }
1650
+ .uis-number { display: inline-flex; align-items: center; gap: 4px; }
1651
+ .uis-number input { width: 62px; padding: 3px 6px; border-radius: 6px; border: 1px solid var(--dsw-alias-border-secondary, rgba(127,127,127,.32)); background: var(--dsw-alias-fill-secondary, transparent); color: inherit; font: inherit; }
1652
+ .uis-suffix { color: var(--dsw-alias-label-tertiary, inherit); white-space: nowrap; }
1653
+ .uis-switch { width: 38px; height: 22px; border-radius: 999px; border: 1px solid var(--dsw-alias-border-secondary, rgba(127,127,127,.32)); background: var(--dsw-alias-fill-secondary, rgba(127,127,127,.2)); padding: 2px; cursor: pointer; flex: none; transition: background .15s ease; }
1654
+ .uis-switch.is-on { background: var(--dsw-alias-state-success-primary, #3b82f6); border-color: transparent; }
1655
+ .uis-switch:disabled { opacity: .5; cursor: not-allowed; }
1656
+ .uis-knob { display: block; width: 16px; height: 16px; border-radius: 50%; background: #fff; transition: transform .15s ease; }
1657
+ .uis-switch.is-on .uis-knob { transform: translateX(16px); }
1658
+ `
1659
+
1660
+ module.exports = { SETTINGS_CSS, SettingsSection }
1661
+ }
1662
+
1663
+ return require('./main.js')
1664
+ }
1665
+ })