@luosuqwq/dsh-ui-appearance 0.1.8 → 0.1.12

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.
@@ -1,1336 +1,1341 @@
1
- window.__ModuleLoader__.load({ id: '@luosuqwq/dsh-ui-appearance', factory: (require) => {
2
- const module = { exports: {} }
3
- const React = require('react')
4
- const h = React.createElement
5
- const NS = 'dsh-ui-appearance'
6
- const STORE_KEY = 'dsh-ui-appearance:settings'
7
- // 与宿主保持同一个默认值:没配置过的用户开箱就有壁纸;显式选过「不使用壁纸」的用户存的是空串,不受影响。
8
- const DEFAULT_WALLPAPER = '/bg/' + encodeURIComponent('花与大肥鱼 version2.png')
9
- const defaults = {
10
- bgImage: DEFAULT_WALLPAPER, bgSize: 'cover', bgOpacity: 1, bgBlur: 0,
11
- bgMask: '#f8f7f7', bgMaskOpacity: 0,
12
- parallaxEnabled: true, parallaxAmplitude: 12, parallaxEasing: 'ease-out',
13
- conversationEnabled: true, conversationOpacity: 0.2, conversationBlur: 2, conversationColor: '#ffffff', conversationWidth: 870,
14
- chatBoxColor: '#ffffff', chatBoxOpacity: 0.59, chatBoxBlur: 0, chatBoxBorder: 'none', chatBoxRadius: 24,
15
- newChatBoxColor: '#ffffff', newChatBoxOpacity: 0.9, newChatBoxBlur: 8, newChatBoxBorder: 'thin', newChatBoxRadius: 16,
16
- existingChatBoxColor: '#ffffff', existingChatBoxOpacity: 0.82, existingChatBoxBlur: 10, existingChatBoxBorder: 'thin', existingChatBoxRadius: 16,
17
- settingsOpacity: 0.4, settingsBlur: 16, settingsColor: '#ffffff',
18
- sidebarOpacity: 0.4, sidebarAutoHide: false, prewarmFirstSlide: true,
19
- previewPopupShared: true, previewPopupInset: 8,
20
- pageCard: true,
21
- }
22
- const rgba = (color, a) => { const m = /^#?([0-9a-f]{6})$/i.exec(color || ''); if (!m) return color; const n = parseInt(m[1], 16); return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${a})` }
23
- const borderValue = (v) => v === 'thick' ? '2px solid rgba(120,130,145,.35)' : v === 'thin' ? '1px solid rgba(120,130,145,.24)' : 'none'
24
- const load = () => {
25
- try {
26
- const raw = JSON.parse(localStorage.getItem(STORE_KEY)) || {}
27
- const merged = { ...defaults, ...raw }
28
- if (!merged.v || merged.v < 2) {
29
- merged.chatBoxBorder = 'none'; merged.chatBoxBlur = 0
30
- merged.v = 2
31
- try { localStorage.setItem(STORE_KEY, JSON.stringify(merged)) } catch {}
32
- }
33
- return merged
34
- } catch { return { ...defaults } }
35
- }
36
- let current = load()
37
- const preloadBackground = (settings) => {
38
- if (typeof document === 'undefined') return null
39
- // Once the real wallpaper layer (.dsh-appearance-bg) exists, do NOT keep a
40
- // second always-100%-opaque wallpaper on <html>: it would duplicate the image
41
- // and show through (instead of a plain base) when wallpaper transparency drops.
42
- if (document.querySelector('.dsh-appearance-bg')) return null
43
- const old = document.getElementById('dsh-ui-appearance-preload')
44
- old?.remove()
45
- const tag = document.createElement('style')
46
- tag.id = 'dsh-ui-appearance-preload'
47
- const image = settings?.bgImage ? `url("${String(settings.bgImage).replace(/"/g, '\\"')}")` : 'none'
48
- tag.textContent = `html,body{background-color:transparent!important}html{background-image:${image}!important;background-size:${settings?.bgSize === 'contain' ? 'contain' : 'cover'}!important;background-repeat:no-repeat!important;background-position:center!important}#root{background:transparent!important}`
49
- document.head.appendChild(tag)
50
- if (!settings?.bgImage) tag.remove()
51
- return tag
52
- }
53
- preloadBackground(current)
54
- if (typeof document !== 'undefined') {
55
- fetch('/bg/config').then((response) => response.ok ? response.json() : null).then((config) => {
56
- if (!config || !config.bgImage) return
57
- current = { ...defaults, ...config }
58
- try { localStorage.setItem(STORE_KEY, JSON.stringify(current)) } catch {}
59
- preloadBackground(current)
60
- }).catch(() => {})
61
- }
62
- let persistTimer
63
- let stateRevision = 0
64
- const persistRemote = (s) => fetch('/bg/config', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(s) }).catch(() => {})
65
- const persist = (s) => {
66
- try { localStorage.setItem(STORE_KEY, JSON.stringify(s)) } catch {}
67
- clearTimeout(persistTimer)
68
- persistTimer = setTimeout(() => { void persistRemote(s) }, 120)
69
- }
70
- const hydrate = async () => {
71
- const revision = stateRevision
72
- let remote = null
73
- let backgrounds = null
74
- try {
75
- const response = await fetch('/bg/config')
76
- if (response.ok) remote = await response.json()
77
- } catch {}
78
- try {
79
- const response = await fetch('/bg/list')
80
- if (response.ok) backgrounds = await response.json()
81
- } catch {}
82
- if (revision !== stateRevision) return current
83
- const hasRemoteConfig = remote && typeof remote === 'object' && (remote.bgImage || Number(remote.v) >= 2)
84
- const next = { ...defaults, ...current, ...(hasRemoteConfig ? remote : {}) }
85
- if (Array.isArray(backgrounds) && next.bgImage && !backgrounds.includes(next.bgImage)) {
86
-
87
- next.bgImage = ''
88
-
89
- }
90
- current = next
91
- try { localStorage.setItem(STORE_KEY, JSON.stringify(current)) } catch {}
92
- if (!hasRemoteConfig) void persistRemote(current)
93
- return current
94
- }
95
- let instantSidebarExpand = false
96
- let sidebarWideWidth = 280
97
- let sidebarPointerHandledAt = 0
98
- let rightbarTrackPx = 0
99
- let sidebarRevealed = false
100
- let sidebarPinTimer = null
101
- /* —— 动效预算(motion budget)——
102
- 「首次滑入卡顿」的成因主要不在 CSS,而在动画窗口里还在做重活:
103
- · 挂载时会连跑两遍 applyBackground(几十个 CSS 变量 + theme token + 全量查询);
104
- · 每次 mousemove 都对侧栏 root 量一次 getBoundingClientRect(紧跟在一批 inline
105
- 样式写入之后 → 强制同步布局);
106
- · 右栏(文档预览)展开时,centerCol 的 ResizeObserver 每帧回调一次,而它调的是
107
- 全量 applyBackground。
108
- 这三件事在第一次发生时代价最大(样式/布局/字体缓存都是冷的),正好压在滑入动画的
109
- 前几帧上,于是"第一次特别卡、之后越来越顺"。下面的窗口只做一件事:动画期间不跑重活,
110
- 结束后补一次合并同步;几何同步照旧每帧做(它便宜)。 */
111
- let motionUntil = 0
112
- let motionTimer = null
113
- const motionActive = () => (typeof performance !== 'undefined' ? performance.now() : 0) < motionUntil
114
- const enterMotion = (ms) => {
115
- const now = typeof performance !== 'undefined' ? performance.now() : 0
116
- const until = now + ms
117
- if (until > motionUntil) motionUntil = until
118
- if (motionTimer !== null) clearTimeout(motionTimer)
119
- // 计时器按"当前窗口真正结束的时刻"重排:短窗口(hover 260ms)不能截断长窗口(右栏 420ms)。
120
- const remaining = Math.max(0, motionUntil - now)
121
- motionTimer = setTimeout(() => { motionTimer = null; motionUntil = 0; flushAfterMotion?.() }, remaining + 48)
122
- }
123
- // 由 shell effect 注入:把动画期间被推迟的合并同步补上。
124
- let flushAfterMotion = null
125
- // 侧栏几何是否已经初始化过(首帧直接归位,不做过渡)。
126
- let sidebarGeometryReady = false
127
- // 侧栏内容是否已经在屏幕内被光栅化过一次(首次展开的过渡只会在冷启动时掉帧)。
128
- let sidebarWarmed = false
129
- // 侧栏"瞬时定位"的令牌:每次瞬时写样式 +1,延迟还回过渡时对比,避免旧回调覆盖新状态。
130
- let sidebarInstantToken = 0
131
- // 首次展开前的静默预热(见 README §3.6)。为什么需要它:自动隐藏的侧栏是靠
132
- // margin-left 移出视口的,屏幕外的内容不会被光栅化,所以"第一次滑入"其实是
133
- // 这笔栅格化/字形缓存第一次被付账,代价正好落在过渡的头两帧上。
134
- // 预热做法:趁用户还没动它,把侧栏在屏幕内画一帧(opacity≈0,肉眼不可见)再收回去。
135
- const prewarmSidebar = () => {
136
- if (sidebarWarmed || !current.sidebarAutoHide || current.prewarmFirstSlide === false) return false
137
- const sidebar = document.querySelector('[class*="sidebarCol"]')
138
- const root = sidebar && sidebar.querySelector('[data-slot="sidebar"] > [class*="root"]')
139
- if (!root || !root.isConnected) return false
140
- if (sidebar.getAttribute('data-dsh-sidebar-revealed') !== 'false') return false
141
- if (root.querySelector('[role="dialog"]')) return false
142
- const width = sidebarWideWidth > 50 ? Math.round(sidebarWideWidth) : 280
143
- root.style.setProperty('transition', 'none', 'important')
144
- root.style.setProperty('margin-left', '0px', 'important')
145
- root.style.setProperty('opacity', '0.002', 'important')
146
- root.style.setProperty('pointer-events', 'none', 'important')
147
- sidebarWarmed = true
148
- const restore = () => {
149
- if (!root.isConnected) return
150
- root.style.setProperty('margin-left', '-' + width + 'px', 'important')
151
- requestAnimationFrame(() => {
152
- if (!root.isConnected) return
153
- root.style.setProperty('transition', 'margin-left .22s var(--ds-ease-in-out)', 'important')
154
- root.style.removeProperty('pointer-events')
155
- })
156
- }
157
- let restored = false
158
- const finish = () => {
159
- if (restored || !root.isConnected) return
160
- restored = true
161
- root.style.removeProperty('opacity')
162
- root.style.removeProperty('pointer-events')
163
- if (sidebar.getAttribute('data-dsh-sidebar-revealed') !== 'false') {
164
- // 预热期间用户已经在往左边缘移动了:把这帧直接当作展开态,别收回去。
165
- root.style.setProperty('transition', 'margin-left .22s var(--ds-ease-in-out)', 'important')
166
- return
167
- }
168
- restore()
169
- }
170
- requestAnimationFrame(() => requestAnimationFrame(finish))
171
- // 后台标签页里 rAF 不跑:兜底 400ms 后强制收回去,避免侧栏停在"不可见但占位"的状态。
172
- setTimeout(finish, 400)
173
- return true
174
- }
175
- const sidebarStyleState = new WeakMap()
176
- const sidebarStyleElements = new Set()
177
- const sidebarRootStyleState = new WeakMap()
178
- const sidebarRootStyleElements = new Set()
179
- const frameStyleState = new WeakMap()
180
- const rememberStyle = (map, el, properties) => {
181
- if (map.has(el)) return map.get(el)
182
- const state = Object.fromEntries(properties.map((name) => [name, [el.style.getPropertyValue(name), el.style.getPropertyPriority(name)]]))
183
- map.set(el, state)
184
- return state
185
- }
186
- const restoreStyleProperties = (map, el, properties) => {
187
- const state = map.get(el)
188
- if (!state) return
189
- properties.forEach((name) => {
190
- const entry = state[name]
191
- if (!entry) return
192
- const [value, priority] = entry
193
- if (value) el.style.setProperty(name, value, priority)
194
- else el.style.removeProperty(name)
195
- })
196
- }
197
- const restoreStyle = (map, el) => {
198
- const state = map.get(el)
199
- if (!state) return
200
- Object.entries(state).forEach(([name, [value, priority]]) => value ? el.style.setProperty(name, value, priority) : el.style.removeProperty(name))
201
- map.delete(el)
202
- }
203
- /* DSH 0.2.0 把官方的"收起侧边栏"按钮改成了 caption 里的固定按钮:Windows 下
204
- `[data-windows-titlebar] ._toggle{position:fixed;left:12px;top:calc((标题栏高-28px)/2);z-index:30}`,
205
- 而 macOS 下整个侧栏收起时改由框架 `shell.leading` 座里的 HeaderLeadingControls 提供
206
- (没有 `toggle` 类名,也不在 `sidebarCol` 内)。0.1.5 完全没有这套。
207
- 关键点:这个按钮仍然是本节点(侧栏 root)的后代。只要 root 上有非 `none` 的 transform
208
- (哪怕只是 `translateX(0)`)或 `will-change:transform`,root 就会成为 fixed 后代的
209
- 包含块——按钮会改以 root(在标题栏下方)为原点定位,并且跟着侧栏一起被拖出屏幕。
210
- 所以这里改用 `margin-left` 位移:隐藏时把 root 推到视口左侧外(列本身已被插件设成
211
- width:0 / overflow:visible,隐藏靠移出视口、显示靠溢出可见),效果与原来的
212
- translateX(-100%) 一致,但不产生包含块,官方按钮就始终以视口为参照。 */
213
- // instant=true 用于两种情况(见 README §3.6):
214
- // · 挂载后的第一次定位:侧栏要立刻停在自己的位置上,不能从 0 滑过去;
215
- // · 首次从屏幕外展开:此刻侧栏内容才第一次被光栅化,过渡只会把这笔开销摊成掉帧,
216
- // 不如直接显示(之后所有展开都正常走 .22s 过渡)。
217
- const syncSidebarRoot = (sidebar, autoHide, instant) => {
218
- const root = sidebar?.querySelector('[data-slot="sidebar"] > [class*="root"]')
219
- if (!root) return
220
- if (!sidebarRootStyleElements.has(root)) {
221
- sidebarRootStyleElements.add(root)
222
- sidebarRootStyleState.set(root, { marginLeft: [root.style.getPropertyValue('margin-left'), root.style.getPropertyPriority('margin-left')], transform: [root.style.getPropertyValue('transform'), root.style.getPropertyPriority('transform')], willChange: [root.style.getPropertyValue('will-change'), root.style.getPropertyPriority('will-change')], transition: [root.style.getPropertyValue('transition'), root.style.getPropertyPriority('transition')] })
223
- }
224
- const revealed = sidebar.getAttribute('data-dsh-sidebar-revealed') !== 'false'
225
- const hasDialog = !!root.querySelector('[role="dialog"]')
226
- // 隐藏偏移必须用**真实宽度**,缓存只能兜底。缓存会被写小/写旧:
227
- // · 标题栏的收起按钮在官方窄栏(56px)姿态下被点到(旧代码拿 >0 就写缓存);
228
- // · 拖分界线 / 切会话时量到过渡中的中间值;
229
- // · 自动隐藏期间 syncFrameColumns 不再读官方轨道(autoHide 时它把左轨当 0),
230
- // 缓存从此不会被刷新,和真实宽度越走越远。
231
- // 一旦缓存小于真实宽度,收起就只把侧栏推出去那么远 —— 表现就是左边永远留一条缝、
232
- // 或半截侧栏露在屏幕外,而且随"上次量到的是哪个姿态"随机复现。
233
- // 代价只有一次 getBoundingClientRect,并且放在下面这批 inline 写入之前(不额外制造回流);
234
- // 只在自动隐藏时测量:展开态根本不用宽度。
235
- const measuredWidth = autoHide ? Math.round(root.getBoundingClientRect().width) : 0
236
- if (measuredWidth > 200) sidebarWideWidth = measuredWidth
237
- // 取两者较大值:欠移会露出侧栏(可见的 bug),过移只是把空无一物的侧栏多推出去一点,
238
- // 视觉上无差别;展开动画的距离变大也不影响观感(时长固定 .22s)。
239
- const sidebarWidth = Math.max(
240
- measuredWidth > 50 ? measuredWidth : 0,
241
- Math.round(sidebarWideWidth) || 0,
242
- ) || 280
243
- // 把可能存在的 transform/will-change 清干净:任何一处都会让官方 fixed 按钮改换包含块。
244
- root.style.setProperty('transform', 'none', 'important')
245
- root.style.removeProperty('will-change')
246
- // 预热用的临时 opacity 必须在这里兜底清掉:任何一次同步都要保证侧栏是可见的。
247
- if (root.style.getPropertyValue('opacity')) root.style.removeProperty('opacity')
248
- const hidden = !!autoHide && !revealed && !hasDialog
249
- const firstReveal = !!autoHide && !hidden && !sidebarWarmed && current.prewarmFirstSlide !== false
250
- const instantNow = instant === true || !sidebarGeometryReady || firstReveal
251
- if (instantNow) root.style.setProperty('transition', 'none', 'important')
252
- else root.style.setProperty('transition', 'margin-left .22s var(--ds-ease-in-out)', 'important')
253
- if (hidden) root.style.setProperty('margin-left', '-' + sidebarWidth + 'px', 'important')
254
- else root.style.setProperty('margin-left', '0px', 'important')
255
- sidebarGeometryReady = true
256
- if (!hidden) sidebarWarmed = true
257
- if (instantNow && !hasDialog) {
258
- // 两帧后再把过渡还回去,确保浏览器已经用 transition:none 提交了这一帧。
259
- // 用递增令牌防止"这两帧里又发生了一次同步"时被旧回调覆盖。
260
- sidebarInstantToken += 1
261
- const token = sidebarInstantToken
262
- requestAnimationFrame(() => requestAnimationFrame(() => {
263
- if (token !== sidebarInstantToken || !root.isConnected) return
264
- root.style.setProperty('transition', 'margin-left .22s var(--ds-ease-in-out)', 'important')
265
- }))
266
- }
267
- if (hasDialog) {
268
- if (autoHide) sidebar.setAttribute('data-dsh-sidebar-revealed', 'true')
269
- root.style.setProperty('margin-left', '0px', 'important')
270
- root.style.setProperty('transition', 'none', 'important')
271
- root.style.setProperty('contain', 'none', 'important')
272
- sidebar.style.setProperty('z-index', autoHide ? '30' : '60', 'important')
273
- } else if (!autoHide) {
274
- sidebar.style.removeProperty('z-index')
275
- }
276
- }
277
-
278
- // applyBackground 的"几何半":只动侧栏列和 root。点击收起、Hover 展开、动画结束后的
279
- // 补同步都走这里,避免为了一个布尔开关重跑 applyBackground(它会重写几十个 CSS 变量、
280
- // 主题 token 和壁纸样式——第一次跑时这些写入会把整页样式重算一遍)。
281
- const applySidebarColumns = (s) => {
282
- const autoHide = !!s.sidebarAutoHide
283
- document.querySelectorAll('[class*="sidebarCol"]').forEach((sidebar) => {
284
- rememberStyle(sidebarStyleState, sidebar, ['background', 'position', 'width', 'min-width', 'height', 'overflow', 'z-index'])
285
- sidebar.setAttribute('data-dsh-auto-hide', String(autoHide))
286
- if (autoHide) {
287
- sidebar.setAttribute('data-dsh-sidebar-revealed', String(sidebarRevealed))
288
- sidebar.style.setProperty('position', 'relative', 'important')
289
- sidebar.style.setProperty('width', '0', 'important')
290
- sidebar.style.setProperty('min-width', '0', 'important')
291
- sidebar.style.setProperty('height', '100%', 'important')
292
- sidebar.style.setProperty('overflow', 'visible', 'important')
293
- sidebar.style.setProperty('z-index', '30', 'important')
294
- } else {
295
- sidebar.setAttribute('data-dsh-sidebar-revealed', 'true')
296
- restoreStyleProperties(sidebarStyleState, sidebar, ['position', 'width', 'min-width', 'height', 'overflow', 'z-index'])
297
- }
298
- syncSidebarRoot(sidebar, autoHide)
299
- })
300
- }
301
-
302
- // 给"非会话"的主面板根节点打标(供 PAGE_STYLE 使用)。判据:`.centerCol` 的直接子元素里,
303
- // 自身或子树带 [data-phase] / [data-conversation-scroll] 的是会话页;其余都是页面
304
- // (插件、自动化任务,以及以后新增的 main 面板)。不依赖 hashed 类名、不读 layout store。
305
- const tagMainPanels = () => {
306
- const keep = new Set()
307
- // 官方的 main 槽是 `div[data-slot="main"]{display:contents}` 锚点,真正的面板是它的子元素
308
- // (插件页 = section[data-plugin-panel],任务页 = section[data-testid="task-manager-page"])。
309
- // 锚点找不到时退回 `.centerCol` 的直接子元素,兼容布局略有差异的版本。
310
- const anchor = document.querySelector('[class*="centerCol"] [data-slot="main"]') || document.querySelector('[class*="centerCol"]')
311
- // 会话区自己的卡片由 STYLE 负责;「不启用区分」时两张卡片一起消失。
312
- const enabled = current.pageCard !== false && current.conversationEnabled !== false
313
- if (enabled && anchor !== null) {
314
- for (const el of Array.from(anchor.children)) {
315
- if (el.hasAttribute('data-phase') || el.querySelector('[data-phase]') !== null) continue
316
- if (el.querySelector('[data-conversation-scroll]') !== null) continue
317
- if (el.querySelector('[data-composer-seat]') !== null) continue
318
- keep.add(el)
319
- el.setAttribute('data-dsh-appearance-page', '')
320
- }
321
- }
322
- document.querySelectorAll('[data-dsh-appearance-page]').forEach((el) => { if (!keep.has(el)) el.removeAttribute('data-dsh-appearance-page') })
323
- }
324
-
325
- // DSH 0.1.5 的 frame 是"侧边栏 | 会话 | 右侧栏"三轨,右侧栏承载文档预览弹窗。
326
- // 本插件必须自己写 grid-template-columns(固定侧边栏宽度、侧边栏自动隐藏),但第三轨
327
- // 不能再写死 0:那会让弹窗浮在会话区之上、会话区也不跟着收窄("慢半拍")。
328
- // 判断依据以"弹窗自己是否展开"(data-sidebar-right-open)为准,而不是只看 frame 上的
329
- // data-rightbar-collapsed——后者只说明官方这一帧没给轨道(覆盖式弹窗),弹窗可能照样开着。
330
- // DSH 0.2.0 的官方轨道换成了 `Npx minmax(0|400px, 1fr) minmax(0px, Mpx)`:第三轨不再是
331
- // 裸的 `Npx`(右栏有轨道时中间轨还有 400px 最小值),旧正则因此永不匹配,插件会把右轨一直
332
- // 钉在 0、弹窗退化成覆盖式浮层。这里两种写法都接受,并读出官方给的第三轨上限。
333
- const FRAME_COLUMNS_RE = /^\s*[\d.]+px\s+minmax\(\s*(?:0(?:px)?|[\d.]+px)\s*,\s*1fr\s*\)\s+(?:minmax\(\s*0px?\s*,\s*([\d.]+)px\s*\)|([\d.]+)px)\s*$/
334
- const MIN_CENTER_PX = 300
335
- // 0.2.0 官方 grid 在右栏占轨道时给中间列的下限(见 AppFrame 的 gridTemplateColumns)。
336
- const HOST_CENTER_MIN_PX = 400
337
- // 官方 inline 轨道的**第一轨**(左列宽度)。拖动左侧分界线时,官方每次 pointermove 都会把
338
- // 新宽度写进同一条 inline `grid-template-columns`;而插件又必须自己重写整条轨道。不读这个值
339
- // 就等于每次都拿缓存宽度把用户拖出来的宽度按回去 —— 表现就是"左分界线拖不动 / 一松手就弹回"。
340
- const FRAME_SIDEBAR_TRACK_RE = /^\s*([\d.]+)px\s+/
341
- const frameSidebarTrackPx = (raw) => { const m = FRAME_SIDEBAR_TRACK_RE.exec(raw || ''); return m ? Math.round(parseFloat(m[1])) : 0 }
342
- const syncFrameColumns = (frameRoot, autoHide, wideW, instant) => {
343
- const raw = frameRoot.style.getPropertyValue('grid-template-columns')
344
- const priority = frameRoot.style.getPropertyPriority('grid-template-columns')
345
- // 右栏是按会话的:切换会话时旧会话的 SessionView 只是被 hidden,旧面板仍
346
- // 带着 data-sidebar-right-open。querySelector 若先命中这个隐藏面板,右栏明明
347
- // 已收起却仍给第三轨留宽,表现就是「侧栏消失、主栏不回撤」。只认可见面板。
348
- const panel = Array.from(document.querySelectorAll('[data-sidebar-right-panel]')).find((el) => el.closest('[hidden]') === null) || null
349
- const panelOpen = panel !== null && panel.hasAttribute('data-sidebar-right-open')
350
- // DSH 0.2.0 的右栏面板不再写行内 `width`:它把自己的宽度发布成 `--dsh-sidebar-width`,
351
- // 官方没给轨道时用这个值兜底(行内没有就退回计算值,兼容它挂在别的节点上的情况)。
352
- const panelInline = panel === null ? '' : panel.style.width
353
- const panelVarInline = panel === null ? '' : panel.style.getPropertyValue('--dsh-sidebar-width')
354
- const panelTrack = /^[\d.]+px$/.test(panelInline) ? panelInline
355
- : /^[\d.]+px$/.test(panelVarInline) ? panelVarInline
356
- : panel === null ? '' : getComputedStyle(panel).getPropertyValue('--dsh-sidebar-width').trim()
357
- const panelPx = /^[\d.]+px$/.test(panelTrack) ? Math.round(parseFloat(panelTrack)) : 0
358
- let track = 0
359
- if (panelOpen) {
360
- const native = priority === 'important' || raw === '' ? null : FRAME_COLUMNS_RE.exec(raw)
361
- if (native !== null) track = Math.max(0, Math.round(parseFloat(native[1] !== undefined ? native[1] : native[2])))
362
- else if (panelPx > 0) track = panelPx
363
- if (frameRoot.getAttribute('data-rightbar-collapsed') !== null && panelPx > 0) {
364
- // 官方这一帧把右轨收成 0(覆盖式弹窗),但弹窗确实开着:只要会话列还放得下,
365
- // 就替弹窗让出一条轨道,并保证会话列至少留 MIN_CENTER_PX;放不下才回退到官方覆盖式。
366
- const sidebarTrack = autoHide ? 0 : wideW
367
- const room = frameRoot.getBoundingClientRect().width - sidebarTrack - MIN_CENTER_PX
368
- const wanted = Math.min(panelPx, Math.max(0, room))
369
- track = wanted >= MIN_CENTER_PX ? wanted : 0
370
- }
371
- }
372
- rightbarTrackPx = Math.max(0, track)
373
- // 左轨宽度以官方 inline 第一轨为准(拖动分界线时它是唯一"当前值"),读不到才退回缓存。
374
- // 注意 56px 是官方的窄栏(rail)宽度,只有明显是展开宽度时才更新缓存——缓存同时被
375
- // 自动隐藏的负偏移使用,被窄栏覆盖会让侧栏只滑出 56px、剩下一截还留在屏幕里。
376
- const nativeSidebarPx = autoHide ? 0 : frameSidebarTrackPx(raw)
377
- if (nativeSidebarPx > 200) sidebarWideWidth = nativeSidebarPx
378
- const sidebarTrack = autoHide ? '0' : `${nativeSidebarPx > 0 ? nativeSidebarPx : wideW}px`
379
- // 官方拖拽分界线/即时切换期间([data-dragging] / [data-rightbar-instant])由官方自己接管网格:
380
- // 官方样式表里这两条会把 transition 关掉,好让列宽 1:1 跟手;但本插件之前用行内 !important
381
- // 写 transition,优先级压过了它们,于是拖拽期间列宽仍在走 .22s 缓动、指针追不上。这里拖拽
382
- // 期间不写 !important、并把插件写的过渡整个删掉,交还给官方。
383
- const dragging = frameRoot.hasAttribute('data-dragging') || frameRoot.hasAttribute('data-rightbar-instant')
384
- // 中间列的最小宽度对齐 0.2.0 官方写法 `${cols.rightbar === 0 ? 0 : 400}px`:右栏没占轨道时
385
- // 允许会话列被压到 0,右栏占轨道时保留 400px 下限(否则插件会把官方的 400px 下限抹掉)。
386
- const centerMin = rightbarTrackPx > 0 ? HOST_CENTER_MIN_PX : 0
387
- frameRoot.style.setProperty('grid-template-columns', `${sidebarTrack} minmax(${centerMin}px,1fr) ${rightbarTrackPx}px`, dragging ? '' : 'important')
388
- if (dragging) frameRoot.style.removeProperty('transition')
389
- else frameRoot.style.setProperty('transition', instant ? 'none' : 'grid-template-columns .22s var(--ds-ease-in-out)', 'important')
390
- document.documentElement.style.setProperty('--dsh-rightbar-track', `${rightbarTrackPx}px`)
391
- }
392
- // DSH 0.1.5 的右侧文档预览("弹窗预览")与会话区共享同一层玻璃:底色/透明度、毛玻璃强度
393
- // 直接取自 --dsh-conv-bg / --dsh-conv-blur,圆角与会话卡片一致(20px),不另开一套参数。
394
- // 宽度故意不写:面板保持官方给它的 inline px 宽,鼠标每动一次它才变一次;一旦写成
395
- // calc(100% - …) 就等于让面板宽度跟着被动画的网格轨道逐帧变化,预览里几千行代码会整篇
396
- // 反复重排(拖动分界线卡顿的元凶之一)。
397
- // 注意:这段必须单独放进自己的 <style>。STYLE 末尾的 `@media(max-width:640px){` 历史上就没
398
- // 闭合(补上它会唤醒一批 0.1.2 时代的旧规则,反而破坏 0.1.5 的会话区滚动/排版),而挂在那个
399
- // 标签后面会让本规则被解析成嵌套规则、永远不匹配——所以它不能复用主样式标签。
400
- // 玻璃部分对所有形态生效("push" 与点「全屏」后的 "fullscreen" 都是同一个 [data-sidebar-right-panel],
401
- // 全屏时官方背景同样是被主题 token 抹成透明的,必须一起补上);几何部分只针对 push。
402
- const POPUP_STYLE = `html[data-dsh-popup-sync="true"] [data-sidebar-right-panel]{background:var(--dsh-conv-bg)!important;backdrop-filter:blur(var(--dsh-conv-blur));-webkit-backdrop-filter:blur(var(--dsh-conv-blur));transition:backdrop-filter .16s linear}html[data-dsh-popup-sync="true"] [data-sidebar-right-panel="push"]{top:var(--dsh-popup-inset,12px)!important;bottom:var(--dsh-popup-inset,12px)!important;right:var(--dsh-popup-inset,12px)!important;border:none!important;box-shadow:none!important;border-radius:20px!important;overflow:hidden!important;transition:transform .22s var(--ds-ease-in-out,cubic-bezier(.4,0,.2,1)),backdrop-filter .16s linear}html[data-dsh-popup-sync="true"][data-dsh-popup-anim="false"] [data-sidebar-right-panel="push"],html[data-dsh-popup-sync="true"] [class*="frame"][data-rightbar-instant] [data-sidebar-right-panel="push"]{transition:none!important}html[data-dsh-popup-sync="true"] [data-sidebar-right-panel="push"]:not([data-sidebar-right-open]){transform:translateX(calc(100% + var(--dsh-popup-inset,12px)))!important}html[data-dsh-popup-sync="true"] [data-sidebar-right-panel="push"] [data-dockkit-host="dock"],html[data-dsh-popup-sync="true"] [data-sidebar-right-panel="push"] [data-dockkit-empty],html[data-dsh-popup-sync="true"] [data-sidebar-right-panel="push"] [data-dockkit-divider]{transform:none!important}html[data-dsh-popup-motion="true"] [data-sidebar-right-panel]{backdrop-filter:none!important;-webkit-backdrop-filter:none!important}html[data-dsh-popup-sync="true"][data-dsh-popup-motion="true"] [data-sidebar-right-panel="push"][data-sidebar-right-open] [data-dockkit-host="dock"]{animation:dsh-appearance-popup-in .16s linear .12s both}@keyframes dsh-appearance-popup-in{from{opacity:0}to{opacity:1}}@media(prefers-reduced-motion:reduce){html[data-dsh-popup-sync="true"] [data-sidebar-right-panel],html[data-dsh-popup-sync="true"] [data-sidebar-right-panel="push"]{transition:none}html[data-dsh-popup-sync="true"][data-dsh-popup-motion="true"] [data-sidebar-right-panel="push"][data-sidebar-right-open] [data-dockkit-host="dock"]{animation:none}}`
403
- // —— 主面板卡片(插件页 / 自动化任务页 …)——
404
- // 官方只有会话页自带卡片;其它 main 面板(插件、自动化任务,以及以后新增的)是整列铺满。
405
- // 这里给它们套一个与会话区**共用同一套变量**的毛玻璃容器:底色/透明度 → --dsh-conv-bg,
406
- // 毛玻璃强度 → --dsh-conv-blur,宽度 → --dsh-conversation-width,圆角 20px 与会话卡片一致。
407
- // 只改外观、不接管滚动:卡片自己 `overflow:hidden` 只负责裁圆角,页面内部原有的滚动容器
408
- // (以及它的 sticky 页头)保持原样。
409
- // 打标由 tagMainPanels() 完成(`.centerCol` 下非会话的直接子元素),不依赖 hashed 类名,
410
- // 以后新增主面板自动生效;卸载时属性与样式表一起清掉。
411
- const PAGE_STYLE = `[class*=centerCol] [data-dsh-appearance-page]{position:relative;width:min(var(--dsh-conversation-width,760px),calc(100% - 48px))!important;max-width:var(--dsh-conversation-width,760px)!important;margin:24px auto!important;height:calc(100% - 48px)!important;max-height:calc(100% - 48px)!important;min-height:0!important;box-sizing:border-box!important;border-radius:20px!important;overflow:auto!important;background:var(--dsh-conv-bg)!important;backdrop-filter:blur(var(--dsh-conv-blur))!important;-webkit-backdrop-filter:blur(var(--dsh-conv-blur))!important}[class*=centerCol] [data-dsh-appearance-page][data-testid="task-manager-page"]{overflow:hidden!important}[class*=centerCol] [data-dsh-appearance-page][data-testid="task-manager-page"] aside[class*="detail"]{background:color-mix(in srgb,var(--dsw-alias-label-primary) 4%,transparent)!important}`
412
- const STYLE = `.dsh-appearance-bg{position:fixed;inset:-80px;z-index:0;pointer-events:none;will-change:transform;background-image:var(--dsh-bg-image);background-size:var(--dsh-bg-size);background-repeat:var(--dsh-bg-repeat);background-position:center;opacity:var(--dsh-bg-opacity);filter:blur(var(--dsh-bg-blur));transition:transform .12s var(--dsh-parallax-easing)}[class*=frame]{position:relative;z-index:2;background:transparent!important}[class*=centerCol],[class*=sidebarCol]{background:transparent!important}[class*=centerCol] [data-phase="hero"],[class*=centerCol] [data-phase="active"]{width:min(var(--dsh-conversation-width,760px),calc(100% - 48px));max-width:var(--dsh-conversation-width,760px);margin:24px auto;min-height:0;border-radius:20px;box-sizing:border-box;overflow:hidden}[class*=centerCol] [data-phase="active"]{height:calc(100% - 48px)!important;max-height:calc(100% - 48px)!important;min-height:0!important;display:flex!important;flex:1 1 auto!important;flex-direction:column!important;background:var(--dsh-conv-bg)!important;overflow:visible!important;backdrop-filter:blur(var(--dsh-conv-blur));-webkit-backdrop-filter:blur(var(--dsh-conv-blur));will-change:backdrop-filter;contain:layout paint}[class*=centerCol] [data-phase="active"] [data-conversation-scroll]{display:grid!important;grid-template-rows:minmax(0,1fr) auto!important;min-height:0!important;overflow:visible!important}[class*=centerCol] [data-phase="active"] [data-conversation-scroll] [data-dsh-appearance-session]{grid-row:1;display:flex!important;flex-direction:column!important;min-width:0!important;min-height:0!important;overflow-y:auto!important;overflow-x:hidden!important}[class*=centerCol] [data-phase="active"] [data-conversation-scroll] [data-dsh-appearance-seat]{grid-row:2;position:relative!important;z-index:20!important;display:flex!important;flex-direction:column!important;flex:none!important;min-width:0!important;max-width:100%!important;overflow:visible!important}[class*=centerCol] [class*=composerSeat]{width:100%!important;max-width:100%!important;border:none!important;box-shadow:none!important;background:transparent!important}[data-dsh-appearance-composer]{background:var(--dsh-composer-bg)!important;backdrop-filter:blur(var(--dsh-composer-blur));-webkit-backdrop-filter:blur(var(--dsh-composer-blur));will-change:backdrop-filter;contain:layout paint;border:var(--dsh-composer-border)!important;border-radius:var(--dsh-composer-radius)!important;overflow:visible!important}/* DSH 0.2.0:设置面板由 SettingsPanel 用 createPortal(..., document.body) 渲染(0.1.5 是内联在
413
- sidebar.settings 槽里),所以原来那条 [data-slot='sidebar.settings'] [role='dialog'] 再也选不中它
414
- —— 玻璃效果整个失效。官方在面板元素上留了稳定标记 data-shortcut-modal="settings"
415
- (settings.open 快捷键的 modals: ["settings"] 就是它)。新旧两种选择器都留着;
416
- --dsh-settings-bg/blur 写在 <html> 上,body 下的 panel 照样继承得到。 */
417
- [data-slot='sidebar.settings'] [role='dialog'],[data-shortcut-modal='settings']{background:var(--dsh-settings-bg)!important;backdrop-filter:blur(var(--dsh-settings-blur));-webkit-backdrop-filter:blur(var(--dsh-settings-blur))}.dsh-appearance-settings{max-width:780px;color:var(--dsw-alias-label-primary)}.dsh-appearance-settings h2{font-size:18px;margin:0 0 10px}.dsh-appearance-settings h3{font-size:13px;margin:18px 0 6px;color:var(--dsw-alias-label-secondary)}.dsh-appearance-settings{max-width:780px;color:var(--dsw-alias-label-primary)}
418
- .dsh-appearance-settings h2{font-size:18px;margin:0 0 10px;letter-spacing:.01em}
419
- .dsh-appearance-settings h3{font-size:12px;margin:22px 0 6px;padding-top:14px;border-top:1px solid var(--dsw-alias-border-l2);color:var(--dsw-alias-label-secondary);font-weight:600;letter-spacing:.04em}
420
- .dsh-appearance-settings h3:first-of-type{margin-top:12px;padding-top:0;border-top:none}
421
- .dsh-appearance-row{display:flex;align-items:center;justify-content:space-between;gap:16px;min-height:38px;padding:5px 0}
422
- .dsh-appearance-row+.dsh-appearance-row{border-top:1px solid color-mix(in srgb,var(--dsw-alias-border-l2) 60%,transparent)}
423
- .dsh-appearance-label{flex:0 0 auto;max-width:56%;font-size:13px;line-height:20px;color:var(--dsw-alias-label-primary)}
424
- .dsh-appearance-control{display:flex;align-items:center;justify-content:flex-end;gap:10px;flex:1 1 auto;min-width:0}
425
- .dsh-appearance-value{flex:none;min-width:46px;padding:2px 7px;border-radius:999px;background:color-mix(in srgb,var(--dsw-alias-label-primary) 7%,transparent);text-align:center;font-size:11px;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary)}
426
- .dsh-appearance-range{appearance:none;-webkit-appearance:none;flex:1 1 auto;min-width:90px;height:18px;margin:0;background:transparent;cursor:pointer}
427
- .dsh-appearance-range::-webkit-slider-runnable-track{height:4px;border-radius:999px;background:color-mix(in srgb,var(--dsw-alias-label-primary) 16%,transparent)}
428
- .dsh-appearance-range::-webkit-slider-thumb{appearance:none;-webkit-appearance:none;width:14px;height:14px;margin-top:-5px;border-radius:50%;border:2px solid var(--dsw-alias-brand-primary,#1570ef);background:var(--dsw-alias-bg-module-platform,#fff);box-shadow:0 1px 3px rgba(0,0,0,.22);transition:transform .12s ease,box-shadow .12s ease}
429
- .dsh-appearance-range:hover::-webkit-slider-thumb{transform:scale(1.08)}
430
- .dsh-appearance-range:active::-webkit-slider-thumb{transform:scale(1.16)}
431
- .dsh-appearance-range:focus-visible::-webkit-slider-thumb{box-shadow:0 0 0 4px color-mix(in srgb,var(--dsw-alias-brand-primary,#1570ef) 26%,transparent)}
432
- .dsh-appearance-range::-moz-range-track{height:4px;border-radius:999px;background:color-mix(in srgb,var(--dsw-alias-label-primary) 16%,transparent)}
433
- .dsh-appearance-range::-moz-range-thumb{width:12px;height:12px;border-radius:50%;border:2px solid var(--dsw-alias-brand-primary,#1570ef);background:var(--dsw-alias-bg-module-platform,#fff)}
434
- .dsh-appearance-select{position:relative;display:flex;align-items:center;flex:1 1 auto;min-width:0;max-width:260px}
435
- .dsh-appearance-select select{appearance:none;-webkit-appearance:none;width:100%;height:30px;padding:0 28px 0 11px;border:1px solid var(--dsw-alias-border-l2);border-radius:9px;background:var(--dsw-alias-bg-module-platform,#fff);color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;line-height:28px;text-overflow:ellipsis;cursor:pointer;transition:border-color .15s ease,box-shadow .15s ease,background .15s ease}
436
- .dsh-appearance-select::after{content:'';position:absolute;right:11px;top:50%;width:6px;height:6px;margin-top:-5px;border-right:1.5px solid var(--dsw-alias-label-secondary);border-bottom:1.5px solid var(--dsw-alias-label-secondary);transform:rotate(45deg);pointer-events:none;opacity:.8}
437
- .dsh-appearance-select:hover select{border-color:color-mix(in srgb,var(--dsw-alias-label-primary) 26%,transparent)}
438
- .dsh-appearance-select select:focus-visible{outline:none;border-color:var(--dsw-alias-brand-primary,#1570ef);box-shadow:0 0 0 3px color-mix(in srgb,var(--dsw-alias-brand-primary,#1570ef) 24%,transparent)}
439
- .dsh-appearance-color{position:relative;display:inline-flex;width:34px;height:30px;flex:none;border:1px solid var(--dsw-alias-border-l2);border-radius:9px;padding:2px;background:var(--dsw-alias-bg-module-platform,#fff);cursor:pointer;transition:border-color .15s ease,box-shadow .15s ease}
440
- .dsh-appearance-color:hover{border-color:color-mix(in srgb,var(--dsw-alias-label-primary) 26%,transparent)}
441
- .dsh-appearance-color input[type=color]{width:100%;height:100%;padding:0;border:none;border-radius:6px;background:transparent;cursor:pointer}
442
- .dsh-appearance-color input[type=color]::-webkit-color-swatch-wrapper{padding:0}
443
- .dsh-appearance-color input[type=color]::-webkit-color-swatch{border:none;border-radius:6px}
444
- .dsh-appearance-color input[type=color]:focus-visible{outline:none;box-shadow:0 0 0 3px color-mix(in srgb,var(--dsw-alias-brand-primary,#1570ef) 24%,transparent)}
445
- .dsh-appearance-switch{position:relative;display:inline-flex;width:38px;height:22px;flex:none;cursor:pointer}
446
- .dsh-appearance-switch input{position:absolute;inset:0;margin:0;opacity:0;cursor:pointer}
447
- .dsh-appearance-switch i{position:absolute;inset:0;border-radius:999px;background:color-mix(in srgb,var(--dsw-alias-label-primary) 18%,transparent);transition:background .18s ease}
448
- .dsh-appearance-switch i::after{content:'';position:absolute;top:2px;left:2px;width:18px;height:18px;border-radius:50%;background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.28);transition:transform .18s cubic-bezier(.4,0,.2,1)}
449
- .dsh-appearance-switch input:checked+i{background:var(--dsw-alias-brand-primary,#1570ef)}
450
- .dsh-appearance-switch input:checked+i::after{transform:translateX(16px)}
451
- .dsh-appearance-switch input:focus-visible+i{box-shadow:0 0 0 3px color-mix(in srgb,var(--dsw-alias-brand-primary,#1570ef) 24%,transparent)}
452
- .dsh-appearance-switch input:active+i::after{width:19px}
453
- .dsh-appearance-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;flex:none;height:30px;padding:0 12px;border:1px solid var(--dsw-alias-border-l2);border-radius:9px;background:var(--dsw-alias-bg-module-platform,#fff);color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;font-weight:500;white-space:nowrap;cursor:pointer;transition:background .15s ease,border-color .15s ease,box-shadow .15s ease,transform .08s ease}
454
- .dsh-appearance-btn:hover{background:var(--dsw-alias-interactive-bg-hover,color-mix(in srgb,var(--dsw-alias-label-primary) 7%,transparent));border-color:color-mix(in srgb,var(--dsw-alias-label-primary) 26%,transparent)}
455
- .dsh-appearance-btn:focus-visible{outline:none;border-color:var(--dsw-alias-brand-primary,#1570ef);box-shadow:0 0 0 3px color-mix(in srgb,var(--dsw-alias-brand-primary,#1570ef) 24%,transparent)}
456
- .dsh-appearance-btn:active{transform:translateY(.5px)}
457
- .dsh-appearance-btn:disabled{opacity:.6;cursor:progress}
458
- .dsh-appearance-btn-icon{flex:none;display:block;opacity:.85}
459
- .dsh-appearance-hint{margin:6px 0 2px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary)}
460
- .dsh-appearance-notice{margin-top:6px;padding:7px 10px;border-radius:9px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-primary);background:color-mix(in srgb,var(--dsw-alias-brand-primary,#1570ef) 10%,transparent);border:1px solid color-mix(in srgb,var(--dsw-alias-brand-primary,#1570ef) 26%,transparent)}
461
- .dsh-appearance-previews{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-top:8px}.dsh-appearance-preview{position:relative;height:210px;border-radius:12px;overflow:hidden;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1)}.dsh-preview-bg{position:absolute;inset:0;background-image:var(--dsh-bg-image);background-size:var(--dsh-bg-size);background-repeat:var(--dsh-bg-repeat);background-position:center;opacity:var(--dsh-bg-opacity)}.dsh-preview-conv{position:absolute;inset:14px;border-radius:12px;padding:10px;display:flex;flex-direction:column;background:transparent}.dsh-preview-conv.active{background:var(--dsh-conv-bg);backdrop-filter:blur(var(--dsh-conv-blur));-webkit-backdrop-filter:blur(var(--dsh-conv-blur))}.dsh-preview-msgs{flex:1;display:flex;flex-direction:column;gap:6px;overflow:hidden}.dsh-preview-msg{align-self:flex-start;max-width:80%;background:var(--dsw-alias-bg-layer-2);border-radius:8px;padding:6px 10px;font-size:11px;color:var(--dsw-alias-label-primary)}.dsh-preview-msg.self{align-self:flex-end;background:var(--dsw-alias-brand-primary);color:var(--dsw-alias-label-inverse, #fff)}.dsh-preview-chat{margin-top:10px;background:var(--dsh-composer-bg);backdrop-filter:blur(var(--dsh-composer-blur));-webkit-backdrop-filter:blur(var(--dsh-composer-blur));border:var(--dsh-composer-border);border-radius:var(--dsh-composer-radius);padding:9px 12px;font-size:11px;color:var(--dsw-alias-label-primary)}@media(max-width:640px){.dsh-appearance-previews{grid-template-columns:1fr}}`
462
-
463
- const appearanceRootStyles = new Map()
464
- let appearanceThemeDisposer = null
465
-
466
- function applyBackground(s, theme) {
467
- const root = document.documentElement
468
- const set = (k, v) => {
469
- const appliedValue = String(v)
470
- if (!appearanceRootStyles.has(k)) appearanceRootStyles.set(k, [root.style.getPropertyValue(k), root.style.getPropertyPriority(k), appliedValue])
471
- else appearanceRootStyles.get(k)[2] = appliedValue
472
- root.style.setProperty(k, appliedValue)
473
- }
474
- const size = s.bgSize === 'tile' ? 'auto' : s.bgSize === 'stretch' ? '100% 100%' : s.bgSize === 'contain' ? 'contain' : s.bgSize || 'cover'
475
- const repeat = s.bgSize === 'tile' ? 'repeat' : 'no-repeat'
476
- const bgUrl = s.bgImage ? `url("${s.bgImage}")` : ''
477
- // Once the real wallpaper layer exists, drop the early full-opacity <html> wallpaper
478
- // so lowering the wallpaper transparency reveals a plain base, not a second image copy.
479
- if (document.querySelector('.dsh-appearance-bg')) {
480
- document.getElementById('dsh-ui-appearance-preload')?.remove()
481
- // 移除 host 首帧注入的 <style>(含标记),避免它盖住壁纸透明度/白底效果。
482
- document.querySelectorAll('style').forEach((el) => { if (el.textContent && el.textContent.includes('dsh-ui-appearance-head')) el.remove() })
483
- }
484
- // 遮罩层背景跟随 --dsh-wash-bg(=遮罩颜色+浓度);无壁纸时透明。
485
- const washEl = document.querySelector('.dsh-appearance-wash')
486
- if (washEl) washEl.style.background = bgUrl ? 'var(--dsh-wash-bg)' : 'transparent'
487
- let el = document.getElementById('dsh-ui-appearance-bg-css')
488
- if (!el) { el = document.createElement('style'); el.id = 'dsh-ui-appearance-bg-css'; document.head.appendChild(el) }
489
- // Base under a (possibly fading) wallpaper: while a wallpaper is active, faded area is a plain white base.
490
- const baseCss = bgUrl ? 'html{background-color:#ffffff!important}body{background:#ffffff!important}' : 'html, body { background-color: transparent !important; } body { background: transparent !important; }'
491
- // 侧边栏滚动渐隐条:0.2.2 起官方把它从 workspace 的 treeBody 里挪到了侧栏骨架自己的
492
- // scrollRegion 底部,类名也从 `..._fade_...` 变成 `..._scrollFade_...`(含大写 F),
493
- // 旧规则整个失效。该条的底色是**不透明**的 --dsw-specific-sidebar-fill,而本插件把
494
- // 侧栏做成了半透明,于是在壁纸上露出一条 24px 的白条。这里一并清掉新位置。
495
- el.textContent = baseCss + ' [class*="frame"], [class*="centerCol"] { background: transparent !important; } [role="dialog"]{z-index:10!important} [class*="sidebarCol"] [class*="treeBody"] [class*="fade"], [class*="sidebarCol"] [class*="scrollFade"] { background: none !important; }'
496
- const tokens = {}
497
- if (bgUrl) {
498
- tokens['--dsw-alias-bg-base'] = { light: 'rgba(0,0,0,0)', dark: 'rgba(0,0,0,0)' }
499
- }
500
- try {
501
- appearanceThemeDisposer?.()
502
- appearanceThemeDisposer = typeof theme?.overrideTokens === 'function' ? theme.overrideTokens(NS, tokens) : null
503
- } catch { appearanceThemeDisposer = null }
504
- document.querySelectorAll('[class*="sidebarCol"], [class*="sidebarCol"] [data-slot="sidebar"] > [class*="root"]').forEach((sidebar) => {
505
- sidebarStyleElements.add(sidebar)
506
- rememberStyle(sidebarStyleState, sidebar, ['background', 'position', 'width', 'min-width', 'height', 'overflow', 'z-index'])
507
- const opacity = Math.max(0, Math.min(1, Number.isFinite(Number(s.sidebarOpacity)) ? Number(s.sidebarOpacity) : 0.85)) * 100
508
- const fill = `color-mix(in srgb,var(--dsw-specific-sidebar-fill) ${opacity}%,transparent)`
509
- const ownsFill = String(sidebar.className || '').includes('root')
510
- sidebar.style.setProperty('background', ownsFill ? fill : 'transparent', 'important')
511
- })
512
- document.querySelectorAll('button[class*="newSession"]').forEach((el) => {
513
- sidebarStyleElements.add(el)
514
- rememberStyle(sidebarStyleState, el, ['background'])
515
- const opacity = Math.max(0, Math.min(1, Number.isFinite(Number(s.sidebarOpacity)) ? Number(s.sidebarOpacity) : 0.85)) * 100
516
- const fill = `color-mix(in srgb,var(--dsw-specific-sidebar-fill) ${opacity}%,transparent)`
517
- el.style.setProperty('background', fill, 'important')
518
- })
519
-
520
- const autoHide = !!s.sidebarAutoHide
521
- const frameRoot = document.querySelector('[class*="frame"]')
522
- if (frameRoot) {
523
- rememberStyle(frameStyleState, frameRoot, ['grid-template-columns', 'transition'])
524
- frameRoot.setAttribute('data-dsh-auto-hide', String(autoHide))
525
- const sideRootEl = document.querySelector('[class*="sidebarCol"] [data-slot="sidebar"] > [class*="root"]')
526
- const sideWidth = sideRootEl ? Math.round(sideRootEl.getBoundingClientRect().width) : 0
527
- const wideW = sideWidth > 50 ? sideWidth : (sidebarWideWidth > 50 ? sidebarWideWidth : 280)
528
- syncFrameColumns(frameRoot, autoHide, wideW, instantSidebarExpand)
529
- }
530
- applySidebarColumns(s)
531
- tagMainPanels()
532
-
533
- const bgDiv = document.querySelector('.dsh-appearance-bg')
534
- if (bgDiv) {
535
- bgDiv.style.backgroundImage = bgUrl || 'none'
536
- bgDiv.style.backgroundSize = size
537
- bgDiv.style.backgroundRepeat = repeat
538
- bgDiv.style.backgroundPosition = 'center'
539
- bgDiv.style.display = bgUrl ? 'block' : 'none'
540
- }
541
- set('--dsh-bg-image', bgUrl || 'none'); set('--dsh-bg-size', size); set('--dsh-bg-repeat', repeat)
542
- set('--dsh-bg-opacity', s.bgOpacity); set('--dsh-bg-blur', `${s.bgBlur}px`)
543
- set('--dsh-wash-bg', rgba(s.bgMask, s.bgMaskOpacity))
544
- set('--dsh-parallax-easing', s.parallaxEasing)
545
- set('--dsh-conv-bg', s.conversationEnabled ? rgba(s.conversationColor, s.conversationOpacity) : 'transparent'); set('--dsh-conversation-width', `${Math.max(320, Number(s.conversationWidth) || 760)}px`)
546
- set('--dsh-conv-solid', s.conversationEnabled ? s.conversationColor : 'transparent')
547
- set('--dsh-conv-blur', s.conversationEnabled ? `${s.conversationBlur}px` : '0px')
548
- set('--dsh-composer-bg', rgba(s.chatBoxColor, s.chatBoxOpacity)); set('--dsh-composer-blur', `${s.chatBoxBlur}px`); set('--dsh-composer-border', borderValue(s.chatBoxBorder)); set('--dsh-composer-radius', `${s.chatBoxRadius}px`)
549
- set('--dsh-settings-bg', rgba(s.settingsColor, s.settingsOpacity)); set('--dsh-settings-blur', `${s.settingsBlur}px`); set('--dsh-sidebar-opacity', `${Math.max(0, Math.min(1, Number.isFinite(Number(s.sidebarOpacity)) ? Number(s.sidebarOpacity) : 0.85)) * 100}%`)
550
- // 文档预览弹窗(0.1.5"弹窗预览")与会话区共享玻璃设置:这里只挂开关和内缩,
551
- // 底色/透明度/毛玻璃强度全部复用 --dsh-conv-*,不新增一套独立参数。
552
- document.documentElement.setAttribute('data-dsh-popup-sync', String(s.previewPopupShared !== false))
553
- set('--dsh-popup-inset', `${Math.max(0, Math.min(48, Number.isFinite(Number(s.previewPopupInset)) ? Number(s.previewPopupInset) : 12))}px`)
554
- }
555
-
556
- function LivePreview({ s }) {
557
- const source = typeof document !== 'undefined' ? document.querySelector('[data-phase="active"]') : null
558
- const page = source ? source.outerHTML : '<div data-phase="active"><div data-conversation-scroll><div data-slot="conversation.session" data-dsh-appearance-session><div data-variant="think">Think</div></div><div data-composer-seat data-dsh-appearance-seat><div data-dsh-appearance-composer><textarea placeholder="Compose..."></textarea></div></div></div></div>'
559
- const styles = typeof document !== 'undefined' ? [...document.querySelectorAll('style')].map((el) => el.textContent).join('\n') : ''
560
- const bg = s.bgImage ? `url("${String(s.bgImage).replace(/"/g, '\\"')}")` : 'none'
561
- const conv = s.conversationEnabled ? rgba(s.conversationColor, s.conversationOpacity) : 'transparent'
562
- const composer = rgba(s.chatBoxColor, s.chatBoxOpacity)
563
- const border = borderValue(s.chatBoxBorder)
564
- const srcDoc = `<!doctype html><html><head><meta charset="utf-8"><style>${styles}</style><style>
565
- html,body{margin:0!important;width:100%;height:100%;overflow:hidden!important;background:transparent!important}
566
- body{font-family:system-ui,sans-serif}
567
- .dsh-live-page{position:relative;width:100%;height:100%;overflow:hidden;background:transparent}
568
- .dsh-live-bg{position:absolute;inset:0;background-image:${bg};background-size:${s.bgSize === 'tile' ? 'auto' : s.bgSize === 'stretch' ? '100% 100%' : s.bgSize};background-repeat:${s.bgSize === 'tile' ? 'repeat' : 'no-repeat'};background-position:center;opacity:${s.bgOpacity};filter:blur(${s.bgBlur}px)}
569
- .dsh-live-center{position:relative;width:100%;height:100%;overflow:hidden;transform-origin:top left}
570
- .dsh-live-center>[data-phase="active"]{width:calc(100% - 32px)!important;height:calc(100% - 32px)!important;margin:16px!important;padding:10px!important;border-radius:12px!important;box-sizing:border-box!important;background:${conv}!important;backdrop-filter:blur(${s.conversationBlur}px)!important}
571
- .dsh-live-center [data-composer-seat]{background:transparent!important;border:0!important;box-shadow:none!important;padding:0!important}
572
- .dsh-live-center [data-dsh-appearance-composer]{background:${composer}!important;border:${border}!important;border-radius:${s.chatBoxRadius}px!important;backdrop-filter:blur(${s.chatBoxBlur}px)!important}
573
- .dsh-live-center [data-conversation-scroll]{display:grid!important;grid-template-rows:minmax(0,1fr) auto!important;min-height:0!important;overflow:hidden!important}
574
- .dsh-live-center [data-conversation-scroll] > [data-dsh-appearance-session]{grid-row:1;display:flex!important;flex-direction:column!important;min-height:0!important;overflow-y:auto!important;overflow-x:hidden!important}
575
- .dsh-live-center [data-conversation-scroll] > [data-dsh-appearance-seat]{grid-row:2;min-height:0!important;overflow:visible!important}
576
- .dsh-live-center [data-slot="conversation.session"] [data-variant]{flex:0 1 auto!important;height:auto!important;max-height:none!important}
577
- .dsh-live-center [data-slot="conversation.session"] [data-variant="think"]{display:flex!important;flex:0 1 auto!important;height:auto!important;overflow:visible!important}
578
- .dsh-live-center [data-slot="conversation.session"] [data-variant="think"] [class*="thinkBody"]{display:block!important;height:auto!important;overflow:visible!important}
579
- .dsh-live-center .Md3f7G_scroll{overflow-y:auto!important;scrollbar-width:none!important}
580
- .dsh-live-center .Md3f7G_scroll::-webkit-scrollbar{display:none}
581
- .dsh-live-center [data-slot="conversation.session"]{pointer-events:none!important}
582
- </style></head><body><div class="dsh-live-page"><div class="dsh-live-bg"></div><div class="dsh-live-center centerCol">${page}</div></div></body></html>`
583
- return h('iframe', { className: 'dsh-live-preview', title: '实时网页预览', srcDoc, scrolling: 'no' })
584
- }
585
-
586
- function Preview({ mode, s }) {
587
- return h('div', { className: 'dsh-appearance-preview dsh-live-preview-shell', 'data-preview-mode': mode }, h(LivePreview, { s }))
588
- }
589
-
590
- function Panel() {
591
- const [s, setS] = React.useState(load())
592
- const [files, setFiles] = React.useState([])
593
- const [revealing, setRevealing] = React.useState(false)
594
- const [notice, setNotice] = React.useState('')
595
- const update = (key, value) => { const next = { ...s, [key]: value }; stateRevision += 1; setS(next); persist(next); current = next; applyBackground(next, window.__dshClientTheme || null) }
596
- React.useEffect(() => { applyBackground(s, window.__dshClientTheme || null); current = s }, [s])
597
- // 壁纸名字由宿主给(解码后的原文件名)。兼容旧接口只回 URL 的情况:自己解一次码,
598
- // 否则中文文件名会显示成 %E5%B0%91%E5%A5%B3 这种样子。
599
- const normalize = (item) => {
600
- if (typeof item === 'string') {
601
- const raw = item.split('/').pop() || item
602
- return { url: item, name: decodeURIComponent(raw) }
603
- }
604
- const url = String(item?.url ?? '')
605
- const name = item?.name ? String(item.name) : decodeURIComponent(url.split('/').pop() || '')
606
- return { url, name }
607
- }
608
- const refreshFiles = () => fetch('/bg/list')
609
- .then((r) => r.json())
610
- .then((list) => { const items = (Array.isArray(list) ? list : []).map(normalize).filter((f) => f.url); setFiles(items); return items })
611
- .catch(() => [])
612
- React.useEffect(() => { void refreshFiles() }, [])
613
- const revealFolder = () => {
614
- if (revealing) return
615
- setRevealing(true)
616
- fetch('/bg/reveal', { method: 'POST' })
617
- .then((r) => r.json())
618
- .then((x) => { setNotice(x && x.opened ? '已在文件管理器中打开壁纸文件夹' : '打不开文件夹,请手动打开 dsh-ui-appearance 的 assets/backgrounds'); return refreshFiles() })
619
- .catch(() => setNotice('打不开文件夹,请手动打开 dsh-ui-appearance 的 assets/backgrounds'))
620
- .finally(() => { setRevealing(false); setTimeout(() => setNotice(''), 4000) })
621
- }
622
- // 选中的壁纸可能已经不在文件夹里(手工删了、换过机器):下拉框仍要能显示它。
623
- const missing = s.bgImage && !files.some((f) => f.url === s.bgImage) ? normalize(s.bgImage) : null
624
- const row = (label, control) => h('div', { className: 'dsh-appearance-row' }, h('span', { className: 'dsh-appearance-label' }, label), h('div', { className: 'dsh-appearance-control' }, control))
625
- const slider = (label, key, min, max, scale, unit) => row(label, [
626
- h('input', { key: 'in', className: 'dsh-appearance-range', type: 'range', min, max, step: 1, value: s[key] * scale, onChange: (e) => update(key, Number(e.target.value) / scale) }),
627
- h('span', { key: 'v', className: 'dsh-appearance-value' }, `${Math.round(s[key] * scale)}${unit}`),
628
- ])
629
- const colorRow = (label, key) => row(label, h('label', { className: 'dsh-appearance-color' }, h('input', { type: 'color', value: s[key], onChange: (e) => update(key, e.target.value) })))
630
- const selectRow = (label, key, options) => row(label, h('span', { className: 'dsh-appearance-select' }, h('select', { value: s[key], onChange: (e) => update(key, e.target.value) }, options.map((o) => h('option', { key: o.value, value: o.value }, o.label)))))
631
- const checkRow = (label, key) => row(label, h('label', { className: 'dsh-appearance-switch' }, h('input', { type: 'checkbox', checked: !!s[key], onChange: (e) => update(key, e.target.checked) }), h('i', { 'aria-hidden': 'true' })))
632
- const folderIcon = h('svg', { className: 'dsh-appearance-btn-icon', viewBox: '0 0 16 16', width: 15, height: 15, fill: 'none', 'aria-hidden': 'true' },
633
- h('path', { d: 'M1.9 4.1a1.2 1.2 0 0 1 1.2-1.2h3.1l1.35 1.5h5.5a1.2 1.2 0 0 1 1.2 1.2v6.3a1.2 1.2 0 0 1-1.2 1.2H3.1a1.2 1.2 0 0 1-1.2-1.2V4.1Z', stroke: 'currentColor', strokeWidth: 1.3, strokeLinejoin: 'round' }))
634
- const wallpaperRow = row('壁纸', [
635
- h('span', { key: 'sel', className: 'dsh-appearance-select' }, h('select', { value: s.bgImage, onChange: (e) => update('bgImage', e.target.value) },
636
- h('option', { value: '' }, '不使用壁纸'),
637
- files.map((f) => h('option', { key: f.url, value: f.url }, f.name)),
638
- missing ? h('option', { key: 'missing', value: missing.url }, `${missing.name}(已不在文件夹中)`) : null)),
639
- h('button', { key: 'btn', type: 'button', className: 'dsh-appearance-btn', onClick: revealFolder, disabled: revealing }, folderIcon, revealing ? '正在打开…' : '壁纸文件夹'),
640
- ])
641
- return h('div', { className: 'dsh-appearance-settings' },
642
- h('h2', null, '外观'),
643
- h('h3', null, '壁纸背景'),
644
- wallpaperRow,
645
- h('div', { className: 'dsh-appearance-hint' }, '把图片放进壁纸文件夹(JPEG / PNG / WebP / GIF,单张不超过 12 MB),它会出现在下拉框里。'),
646
- notice && h('div', { className: 'dsh-appearance-notice' }, notice),
647
- selectRow('尺寸模式', 'bgSize', [{ value: 'cover', label: '裁切 Cover' }, { value: 'contain', label: '居中 Contain' }, { value: 'tile', label: '平铺 Tile' }, { value: 'stretch', label: '拉伸 Stretch' }, { value: 'auto', label: '适应 Auto' }]),
648
- slider('壁纸透明度', 'bgOpacity', 0, 100, 100, '%'),
649
- slider('壁纸模糊', 'bgBlur', 0, 60, 1, 'px'),
650
- colorRow('遮罩颜色', 'bgMask'),
651
- slider('遮罩浓度', 'bgMaskOpacity', 0, 100, 100, '%'),
652
- h('h3', null, '视差动效'),
653
- checkRow('启用视差', 'parallaxEnabled'),
654
- slider('移动幅度', 'parallaxAmplitude', 0, 50, 1, 'px'),
655
- selectRow('缓动速度', 'parallaxEasing', [{ value: 'ease-out', label: '缓出' }, { value: 'ease-in', label: '缓入' }, { value: 'ease-in-out', label: '缓入缓出' }]),
656
- h('h3', null, '侧边栏'),
657
- slider('透明度', 'sidebarOpacity', 0, 100, 100, '%'),
658
- checkRow('自动隐藏到左侧', 'sidebarAutoHide'),
659
- checkRow('首次滑入前预热(减少首帧卡顿)', 'prewarmFirstSlide'),
660
- h('h3', null, '会话对话区'),
661
- checkRow('启用区分', 'conversationEnabled'),
662
- slider('透明度', 'conversationOpacity', 0, 100, 100, '%'),
663
- slider('毛玻璃强度', 'conversationBlur', 0, 60, 1, 'px'),
664
- colorRow('遮罩颜色', 'conversationColor'),
665
- slider('对话框宽度', 'conversationWidth', 420, 1200, 1, 'px'),
666
- checkRow('插件/任务页也用会话卡片', 'pageCard'),
667
- checkRow('应用到文档预览弹窗', 'previewPopupShared'),
668
- slider('弹窗外边距(上/下/右)', 'previewPopupInset', 0, 40, 1, 'px'),
669
- h('h3', null, '聊天框'),
670
- colorRow('背景颜色', 'chatBoxColor'),
671
- slider('透明度', 'chatBoxOpacity', 0, 100, 100, '%'),
672
- selectRow('边框样式', 'chatBoxBorder', [{ value: 'none', label: '无' }, { value: 'thin', label: '细' }, { value: 'thick', label: '粗' }]),
673
- slider('圆角大小', 'chatBoxRadius', 0, 24, 1, 'px'),
674
- h('h3', null, '设置面板'),
675
- slider('透明度', 'settingsOpacity', 0, 100, 100, '%'),
676
- slider('毛玻璃强度', 'settingsBlur', 0, 60, 1, 'px'),
677
- colorRow('背景颜色', 'settingsColor'))
678
-
679
- }
680
-
681
- function apply(ctx) {
682
- const slots = ctx.slots
683
- const theme = ctx.theme
684
- if (!slots) return
685
- try { window.__dshClientTheme = theme } catch {}
686
- ctx.effect(() => {
687
- let active = true
688
- applyBackground(current, theme)
689
- const tag = document.createElement('style'); tag.dataset.pluginCss = NS; tag.textContent = STYLE; document.head.appendChild(tag)
690
- // 弹窗外观单独一张样式表:与主样式表解耦(主表整段由 STYLE 常量一次性给出,这里不往里
691
- // 追加任何东西),这条规则也就稳定处在顶层,不会因为主表结构变化而被解析成嵌套规则。
692
- const popupTag = document.createElement('style'); popupTag.dataset.pluginCss = NS + ':popup'; popupTag.textContent = POPUP_STYLE; document.head.appendChild(popupTag)
693
- // 主面板卡片单独一张样式表(同 popup 的理由:主样式表一次性给出、不往里追加)。
694
- const pageTag = document.createElement('style'); pageTag.dataset.pluginCss = NS + ':page'; pageTag.textContent = PAGE_STYLE; document.head.appendChild(pageTag)
695
- // 右栏容器入场动画的闸门(见 README §3.6):插件第一次应用样式时会把面板从 none
696
- // 推到 translateX(100%+内缩),如果过渡此刻就已生效,面板会在页面加载时自己滑出去一次。
697
- // 先禁用过渡,等右栏第一次真正展开(或 3s 超时)再放行。
698
- try { document.documentElement.setAttribute('data-dsh-popup-anim', 'false') } catch { /* 无 document 时安静 */ }
699
-
700
- const bg = document.createElement('div'); bg.className = 'dsh-appearance-bg'; document.body.prepend(bg)
701
- // 遮罩层:整屏盖在壁纸(z-index:0)上方、内容(frame z-index:2)下方;背景=--dsh-wash-bg。
702
- const wash = document.createElement('div'); wash.className = 'dsh-appearance-wash'
703
- Object.assign(wash.style, { position: 'fixed', inset: '0', zIndex: '1', pointerEvents: 'none', background: 'var(--dsh-wash-bg)' })
704
- bg.insertAdjacentElement('afterend', wash)
705
-
706
- applyBackground(current, theme)
707
- const preloadTag = document.getElementById('dsh-ui-appearance-preload')
708
- let preloadProbe = null
709
- let preloadTimeout = null
710
- const finishPreload = () => {
711
- if (!active || !preloadTag || !preloadTag.isConnected || document.getElementById('dsh-ui-appearance-preload') !== preloadTag) return
712
- preloadTag.remove()
713
- }
714
- if (current.bgImage) {
715
- preloadProbe = new Image()
716
- preloadProbe.onload = finishPreload
717
- preloadProbe.onerror = () => { preloadTimeout = setTimeout(finishPreload, 300) }
718
- preloadProbe.src = current.bgImage
719
- } else finishPreload()
720
- // Cold-start self-heal: on a real app start the page can mount before
721
- // the host plugin's /bg routes are serving (or before the configured
722
- // image file is reachable), so a one-shot /bg/config fetch would 404
723
- // and leave the wallpaper blank until a manual refresh. Retry briefly
724
- // so the background appears as soon as the host is ready.
725
- let bootTimer = null
726
- const bootDelay = (ms) => new Promise((resolve) => { bootTimer = setTimeout(resolve, ms) })
727
- const bootImageReady = (url) => new Promise((resolve) => {
728
- if (!url) return resolve(true)
729
- const im = new Image()
730
- im.onload = () => resolve(true)
731
- im.onerror = () => resolve(false)
732
- im.src = url
733
- })
734
- const bootPaint = (s) => { applyBackground(s, theme); preloadBackground(s); tagDom() }
735
- const bootWallpaper = async () => {
736
- for (let i = 0; i < 48 && active; i++) {
737
- let reachable = false
738
- let cfg = null
739
- try {
740
- const res = await fetch('/bg/config')
741
- if (res.ok) { reachable = true; cfg = await res.json() }
742
- } catch { /* host not ready yet */ }
743
- if (reachable && cfg && typeof cfg === 'object') {
744
- current = { ...defaults, ...current, ...cfg }
745
- try { localStorage.setItem(STORE_KEY, JSON.stringify(current)) } catch {}
746
- }
747
- if (!current.bgImage) {
748
- if (reachable) { bootPaint(current); return } // authoritative: no wallpaper chosen
749
- await bootDelay(300)
750
- continue
751
- }
752
- bootPaint(current)
753
- if (await bootImageReady(current.bgImage)) return // image served: background active
754
- await bootDelay(250)
755
- }
756
- }
757
- void bootWallpaper()
758
- let frame
759
- let lastParallax = ''
760
- const move = (e) => {
761
- const s = current
762
- if (!s.parallaxEnabled || !s.bgImage) return
763
- const x = Math.round((e.clientX / innerWidth - 0.5) * 2 * -s.parallaxAmplitude * 2) / 2
764
- const y = Math.round((e.clientY / innerHeight - 0.5) * 2 * -s.parallaxAmplitude * 2) / 2
765
- const next = x + ',' + y
766
- if (next === lastParallax) return
767
- lastParallax = next
768
- cancelAnimationFrame(frame)
769
- // translate3d 走合成器;值没变就完全不写,避免壁纸层的 backdrop 反复重算。
770
- frame = requestAnimationFrame(() => { bg.style.transform = 'translate3d(' + x + 'px, ' + y + 'px, 0)' })
771
- }
772
- document.addEventListener('mousemove', move)
773
- // Hover 展开/收起:合并到每帧一次,并且只在"展开状态真的变了"时才写样式。
774
- // 原来每次 mousemove 都会 syncSidebarRoot → 量一次 root 的 rect + 重写 transition/margin,
775
- // 也就是每次指针移动都强制一次同步布局;滑入的那 220ms 里就是每帧一次。
776
- let sidebarHoverFrame = 0
777
- let sidebarHoverEvent = null
778
- const applySidebarHover = (e) => {
779
- const autoHide = !!current.sidebarAutoHide
780
- document.querySelectorAll('[class*="sidebarCol"]').forEach((sidebar) => {
781
- if (!autoHide) {
782
- if (sidebar.getAttribute('data-dsh-sidebar-revealed') !== 'true') {
783
- sidebar.setAttribute('data-dsh-sidebar-revealed', 'true')
784
- sidebarRevealed = true
785
- }
786
- return
787
- }
788
- const root = sidebar.querySelector('[data-slot="sidebar"] > [class*="root"]')
789
- const target = e.target
790
- const revealed = e.clientX <= 20 || (root && (() => { const rect = root.getBoundingClientRect(); return rect.width > 0 && e.clientX >= rect.left - 4 && e.clientX <= rect.right + 4 && e.clientY >= rect.top - 8 && e.clientY <= rect.bottom + 8 })()) || !!(root && (root === target || root.contains(target) || root.matches(':hover')))
791
- sidebarRevealed = revealed
792
- if (sidebar.getAttribute('data-dsh-sidebar-revealed') === String(revealed)) return
793
- sidebar.setAttribute('data-dsh-sidebar-revealed', String(revealed))
794
- enterMotion(260)
795
- syncSidebarRoot(sidebar, true)
796
- })
797
- }
798
- const sidebarHover = (e) => {
799
- sidebarHoverEvent = e
800
- if (sidebarHoverFrame !== 0) return
801
- sidebarHoverFrame = requestAnimationFrame(() => { sidebarHoverFrame = 0; if (active && sidebarHoverEvent) applySidebarHover(sidebarHoverEvent) })
802
- }
803
- document.addEventListener('mousemove', sidebarHover)
804
- // 静默预热:启动后挑一段空闲时间做,最多试 6 次(DOM 可能还没就绪);用户期间
805
- // 一旦已经把侧栏展开,prewarmSidebar 自己会放弃。
806
- let prewarmTimer = null
807
- let prewarmTries = 0
808
- const schedulePrewarm = (delay) => {
809
- if (prewarmTimer !== null) { clearTimeout(prewarmTimer); prewarmTimer = null }
810
- const run = () => {
811
- prewarmTimer = null
812
- if (!active) return
813
- if (prewarmSidebar()) return
814
- if (prewarmTries < 6 && !sidebarWarmed) { prewarmTries += 1; schedulePrewarm(900) }
815
- }
816
- prewarmTimer = setTimeout(() => {
817
- // 预热本身要画一帧,别和首屏/首轮渲染抢时间,交给空闲回调。
818
- if (typeof requestIdleCallback === 'function') requestIdleCallback(run, { timeout: 1500 })
819
- else run()
820
- }, delay)
821
- }
822
- schedulePrewarm(1200)
823
- let conversationScrollFrame
824
- let conversationScrollElement = null
825
- let conversationScrollListener = null
826
- let conversationScrollHost = null
827
- let conversationScrollHostPosition = null
828
- let conversationRoot = null
829
- let latestButton = null
830
- let followConversation = true
831
- // 气泡按钮的位置原来是每帧量 offsetWidth/clientWidth/offsetHeight 再写样式(一次强制布局),
832
- // 而它只在容器尺寸或输入框高度变化时才会变。改成量一次、变了才写。
833
- let latestMetrics = { right: -1, bottom: -1 }
834
- let scrollIdleTimer = 0
835
- const measureLatestButton = (scroll) => {
836
- if (!latestButton || !scroll) return
837
- const right = Math.max(8, scroll.offsetWidth - scroll.clientWidth + 8)
838
- const seat = conversationScrollHost ? conversationScrollHost.querySelector('[data-composer-seat]') : null
839
- const bottom = (seat ? seat.offsetHeight : 0) + 8
840
- if (right === latestMetrics.right && bottom === latestMetrics.bottom) return
841
- latestMetrics = { right, bottom }
842
- latestButton.style.right = right + 'px'
843
- latestButton.style.bottom = bottom + 'px'
844
- }
845
- const scrollConversationToLatest = (force = false) => {
846
- const active = document.querySelector('[data-phase="active"]')
847
- if (!active) return
848
- if (active !== conversationRoot) {
849
- conversationRoot = active
850
- followConversation = true
851
- conversationScrollElement = null
852
- }
853
-
854
-
855
-
856
- const scrollBody = active.querySelector('[data-conversation-scroll]')
857
- const scroll = scrollBody && (scrollBody.querySelector(':scope > [data-slot="conversation.session"]') || scrollBody.querySelector('[data-slot="conversation.session"]'))
858
-
859
- if (!scroll) return
860
- if (scroll !== conversationScrollElement) {
861
- // 只在换滚动容器时写:原来每次同步都写,等于每帧制造一次样式失效。
862
- scroll.style.setProperty('overflow-y', 'auto', 'important')
863
- scroll.style.setProperty('overflow-x', 'hidden', 'important')
864
- if (scrollBody) scrollBody.style.setProperty('overflow', 'hidden', 'important')
865
- if (conversationScrollElement && conversationScrollListener) conversationScrollElement.removeEventListener('scroll', conversationScrollListener)
866
- conversationScrollElement = scroll
867
- conversationScrollListener = () => {
868
- const distance = scroll.scrollHeight - scroll.clientHeight - scroll.scrollTop
869
- followConversation = distance <= 24
870
- if (latestButton) latestButton.hidden = distance <= 24
871
- }
872
- scroll.addEventListener('scroll', conversationScrollListener, { passive: true })
873
- }
874
-
875
- const scrollHost = scroll.parentElement || active
876
- if (conversationScrollHost !== scrollHost) {
877
- if (conversationScrollHost && conversationScrollHostPosition !== null) { if (conversationScrollHostPosition[0]) conversationScrollHost.style.setProperty('position', conversationScrollHostPosition[0], conversationScrollHostPosition[1]); else conversationScrollHost.style.removeProperty('position') }
878
- conversationScrollHost = scrollHost
879
- conversationScrollHostPosition = [scrollHost.style.getPropertyValue('position'), scrollHost.style.getPropertyPriority('position')]
880
- scrollHost.style.setProperty('position', 'relative')
881
- }
882
- if (latestButton && latestButton.parentElement !== scrollHost) {
883
- scrollHost.style.setProperty('position', 'relative')
884
- scrollHost.appendChild(latestButton)
885
- }
886
- if (followConversation || force) scroll.scrollTop = scroll.scrollHeight
887
- if (latestButton) latestButton.hidden = scroll.scrollHeight - scroll.clientHeight - scroll.scrollTop <= 24
888
- // 首次(还没量过)补量一次;之后只在全量同步/窗口 resize 时重算。
889
- if (latestButton && latestMetrics.right < 0) measureLatestButton(scroll)
890
- }
891
- const scheduleConversationScroll = () => {
892
- cancelAnimationFrame(conversationScrollFrame)
893
- conversationScrollFrame = requestAnimationFrame(() => {
894
- scrollConversationToLatest()
895
- // 第二帧:等流式内容完成布局后再贴到底,思考过程才跟得上。
896
- requestAnimationFrame(() => scrollConversationToLatest())
897
- })
898
- }
899
- const ensureLatestButton = () => {
900
- const active = document.querySelector('[data-phase="active"]')
901
- if (!active) return
902
- if (latestButton && latestButton.isConnected && latestButton.closest('[data-phase="active"]') === active) return
903
- latestButton?.remove()
904
- latestButton = document.createElement('button')
905
- latestButton.type = 'button'
906
- latestButton.textContent = '↓'
907
- latestButton.dataset.dshLatestButton = 'true'
908
- latestButton.title = '返回最新对话'
909
- latestButton.setAttribute('aria-label', '返回最新对话')
910
- latestButton.hidden = true
911
- Object.assign(latestButton.style, { position: 'absolute', right: '20px', bottom: '20px', zIndex: '20', width: '36px', height: '36px', border: '1px solid rgba(120,130,145,.35)', borderRadius: '50%', background: 'rgba(255,255,255,.92)', color: 'inherit', boxShadow: '0 4px 14px rgba(0,0,0,.16)', cursor: 'pointer', fontSize: '20px', lineHeight: '1' })
912
- latestButton.addEventListener('click', () => { followConversation = true; scrollConversationToLatest(true) })
913
- active.appendChild(latestButton)
914
- }
915
- const tagDom = () => {
916
- document.querySelectorAll('[data-phase="active"] button:not([data-dsh-latest-button])').forEach((button) => {
917
- const label = `${button.getAttribute('aria-label') || ''} ${button.getAttribute('title') || ''} ${button.textContent || ''}`.toLowerCase()
918
- if (/bottom|latest|scroll/.test(label)) button.style.setProperty('display', 'none', 'important')
919
- })
920
-
921
- const autoHideFrame = document.querySelector('[class*="frame"]')
922
-
923
- const autoHide = !!current.sidebarAutoHide
924
- /* 0.2.0 有两个官方开关:侧栏自带的那个(Windows 下被钉进标题栏左上角),以及整列
925
- 隐藏时框架 `shell.leading` 座里的 HeaderLeadingControls(没有 `toggle` 类名、
926
- 也不在 sidebarCol 内)。两个都同步标签;leading 座里只认第一个按钮,且先排除
927
- "新建会话",避免把标签贴到隔壁按钮上。 */
928
- const applyToggleLabel = (button) => {
929
- if (!button) return
930
- button.setAttribute('aria-label', autoHide ? '取消隐藏侧边栏' : '隐藏侧边栏')
931
- button.setAttribute('aria-pressed', String(autoHide))
932
- }
933
- applyToggleLabel(document.querySelector('[class*="sidebarCol"] button[class*="toggle"]'))
934
- const leadingSeat = document.querySelector('[class*="leadingSeat"]')
935
- const leadingButton = leadingSeat ? leadingSeat.querySelector('[class*="controls"] button') : null
936
- if (leadingButton && !/新建|新会话|new session/i.test(`${leadingButton.getAttribute('aria-label') || ''} ${leadingButton.getAttribute('title') || ''}`)) applyToggleLabel(leadingButton)
937
- if (autoHideFrame) autoHideFrame.setAttribute('data-dsh-auto-hide', String(autoHide));
938
- document.querySelectorAll('[class*="sidebarCol"]').forEach((sidebar) => {
939
- rememberStyle(sidebarStyleState, sidebar, ['background', 'position', 'width', 'min-width', 'height', 'overflow', 'z-index'])
940
- sidebar.setAttribute('data-dsh-auto-hide', String(autoHide))
941
- if (!autoHide) sidebar.setAttribute('data-dsh-sidebar-revealed', 'true')
942
- else sidebar.setAttribute('data-dsh-sidebar-revealed', String(sidebarRevealed))
943
- syncSidebarRoot(sidebar, autoHide)
944
- })
945
-
946
- const activePhase = document.querySelector('[data-phase="active"]')
947
- const heroPhase = document.querySelector('[data-phase="hero"]')
948
- const settlingPhase = document.querySelector('[data-phase="settling"]')
949
- const seat = activePhase?.querySelector('[data-composer-seat]') || heroPhase?.querySelector('[data-composer-seat]') || settlingPhase?.querySelector('[data-composer-seat]') || document.querySelector('[data-composer-seat]')
950
- document.querySelectorAll('[data-dsh-appearance-session], [data-dsh-appearance-seat]').forEach((el) => {
951
- el.removeAttribute('data-dsh-appearance-session')
952
- el.removeAttribute('data-dsh-appearance-seat')
953
- })
954
- const scrollBody = seat?.closest('[data-conversation-scroll]')
955
- const session = scrollBody?.querySelector('[data-slot="conversation.session"]')
956
- if (session) session.setAttribute('data-dsh-appearance-session', '')
957
- if (seat && scrollBody && seat.parentElement === scrollBody) seat.setAttribute('data-dsh-appearance-seat', '')
958
- const editable = seat ? seat.querySelector('textarea,[contenteditable=true]') : null
959
- let target = editable ? editable.parentElement : null
960
- if (target) {
961
- for (let i = 0; i < 6 && target; i++) {
962
- const cls = String(target.className || '')
963
- if (cls.includes('card')) break
964
- target = target.parentElement
965
- }
966
- if (target && target !== editable) target.setAttribute('data-dsh-appearance-composer', '')
967
- }
968
- document.querySelectorAll('[data-dsh-appearance-composer]').forEach((el) => {
969
- if (el !== target) el.removeAttribute('data-dsh-appearance-composer')
970
- })
971
- tagMainPanels()
972
- }
973
- tagDom()
974
- let sidebarRestoreFrame
975
- ensureLatestButton()
976
- scheduleConversationScroll()
977
- const sidebarToggleClick = (e) => {
978
- const path = typeof e.composedPath === 'function' ? e.composedPath() : []
979
- const button = path.find((node) => node && node.nodeType === 1 && node.matches && node.matches('[class*="sidebarCol"] button[class*="toggle"]')) || (e.target && e.target.closest ? e.target.closest('[class*="sidebarCol"] button[class*="toggle"]') : null)
980
- if (!button) return
981
- if (e.type === 'mousedown' && sidebarPointerHandledAt > 0 && performance.now() - sidebarPointerHandledAt < 500) {
982
- e.preventDefault()
983
- e.stopImmediatePropagation()
984
- return
985
- }
986
- if (e.type === 'click' && sidebarPointerHandledAt > 0 && performance.now() - sidebarPointerHandledAt < 500) {
987
- e.preventDefault()
988
- e.stopImmediatePropagation()
989
- return
990
- }
991
- if (e.type === 'pointerdown') sidebarPointerHandledAt = performance.now()
992
- e.preventDefault()
993
- e.stopImmediatePropagation()
994
- const wasAutoHide = !!current.sidebarAutoHide
995
- const revealedNow = sidebarRevealed
996
- const nativeSidebar = document.querySelector('[class*="sidebarCol"] [data-slot="sidebar"] > [class*="root"]')
997
- const measuredWidth = nativeSidebar ? nativeSidebar.getBoundingClientRect().width : 0
998
- if (measuredWidth > 200) sidebarWideWidth = measuredWidth
999
- const frameRoot = document.querySelector('[class*="frame"]')
1000
- if (wasAutoHide) document.querySelectorAll('[class*="sidebarCol"] [data-slot="sidebar"] > [class*="root"]').forEach((root) => root.style.setProperty('transition', 'margin-left .22s var(--ds-ease-in-out)', 'important'))
1001
- const next = { ...current, sidebarAutoHide: !wasAutoHide }
1002
- current = next
1003
- persist(next)
1004
- instantSidebarExpand = false
1005
- sidebarRevealed = !next.sidebarAutoHide
1006
- if (wasAutoHide && revealedNow) {
1007
- const pinSidebar = document.querySelector('[class*="sidebarCol"]')
1008
- const pinRoot = pinSidebar && pinSidebar.querySelector('[data-slot="sidebar"] > [class*="root"]')
1009
- // 「钉住」的语义是"原地冻结":必须钉在侧栏列**当前**所在的框上。列在 Windows 下
1010
- // 是从标题栏**下方**开始的(frame 有 padding-top: 标题栏高),原来写死的
1011
- // `left/top:0; height:100%` 会把 root 提到视口左上角(z-index 900),它顶部那一行
1012
- // ——deepseek 品牌行——就会盖到标题栏上闪一下。
1013
- // 量的必须是未受动画影响的量:left/top/height 取列(列不参与 root 的滑入过渡),
1014
- // width 取 root 自己。三个值都合理才钉,否则干脆不钉(正常过渡本来就安全)。
1015
- const colRect = pinSidebar ? pinSidebar.getBoundingClientRect() : null
1016
- const pinTop = colRect === null ? NaN : Math.round(colRect.top)
1017
- const pinLeft = colRect === null ? NaN : Math.round(colRect.left)
1018
- const pinHeight = colRect === null ? NaN : Math.round(colRect.height)
1019
- if (pinRoot && pinHeight > 1 && Number.isFinite(pinTop) && Number.isFinite(pinLeft)) {
1020
- // margin-left 只由 syncSidebarRoot 拥有:它不进快照,否则 360ms 后会把
1021
- // 隐藏态的负偏移又还原回来(按钮已展开、侧栏却滑走了)。
1022
- const names = ['position', 'left', 'top', 'width', 'height', 'z-index', 'transform', 'transition', 'will-change']
1023
- const read = (el, list) => { const o = {}; list.forEach((n) => { o[n] = [el.style.getPropertyValue(n), el.style.getPropertyPriority(n)] }); return o }
1024
- const snapRoot = read(pinRoot, names)
1025
- const snapCol = read(pinSidebar, ['z-index'])
1026
- const pw = Math.round(pinRoot.getBoundingClientRect().width) || sidebarWideWidth || 280
1027
- pinSidebar.style.setProperty('z-index', '30', 'important')
1028
- const rs = pinRoot.style
1029
- rs.setProperty('position', 'fixed', 'important')
1030
- rs.setProperty('left', pinLeft + 'px', 'important')
1031
- rs.setProperty('top', pinTop + 'px', 'important')
1032
- rs.setProperty('width', pw + 'px', 'important')
1033
- rs.setProperty('height', pinHeight + 'px', 'important')
1034
- rs.setProperty('z-index', '900', 'important')
1035
- rs.setProperty('margin-left', '0', 'important')
1036
- rs.setProperty('transform', 'none', 'important')
1037
- rs.setProperty('transition', 'none', 'important')
1038
- rs.setProperty('will-change', 'auto', 'important')
1039
- if (sidebarPinTimer !== null) clearTimeout(sidebarPinTimer)
1040
- sidebarPinTimer = setTimeout(() => {
1041
- sidebarPinTimer = null
1042
- const apply = (el, o) => { Object.entries(o).forEach(([n, [v, p]]) => v ? el.style.setProperty(n, v, p) : el.style.removeProperty(n)) }
1043
- apply(pinRoot, snapRoot)
1044
- apply(pinSidebar, snapCol)
1045
- }, 360)
1046
- }
1047
- }
1048
- if (!active) return
1049
- // 起手要轻:只同步几何与属性,重活交给动画结束后的合并同步。
1050
- // 原来这里同步跑 applyBackground(几十个 CSS 变量 + 主题 token + 全量查询)
1051
- // 再跑 tagDom,第一次执行时正好压在过渡的第一帧上。
1052
- enterMotion(340)
1053
- applySidebarColumns(next)
1054
- const frameNow = document.querySelector('[class*="frame"]')
1055
- if (frameNow) {
1056
- frameNow.setAttribute('data-dsh-auto-hide', String(!!next.sidebarAutoHide))
1057
- syncFrameColumns(frameNow, !!next.sidebarAutoHide, sidebarWideWidth || 280, false)
1058
- }
1059
- scheduleSync()
1060
- }
1061
- window.addEventListener('pointerdown', sidebarToggleClick, true)
1062
- window.addEventListener('mousedown', sidebarToggleClick, true)
1063
- window.addEventListener('click', sidebarToggleClick, true)
1064
- const onWindowResize = () => scheduleSync()
1065
- window.addEventListener('resize', onWindowResize)
1066
- document.addEventListener('click', sidebarToggleClick, true)
1067
-
1068
- // —— 合并同步(见文件顶部「动效预算」)——
1069
- // 一次 DOM 变更批次只同步一次;动画窗口内直接推迟到动画结束。以前每个批次都同步跑
1070
- // applyBackground + tagDom,正好压在滑入动画的每一帧上。
1071
- let syncFrame = 0
1072
- let syncTimer = null
1073
- let syncPending = false
1074
- const syncFrameNow = () => {
1075
- const frameRoot = document.querySelector('[class*="frame"]')
1076
- if (frameRoot) syncFrameColumns(frameRoot, !!current.sidebarAutoHide, sidebarWideWidth || 280, false)
1077
- }
1078
- // 拖拽分界线结束后再补一次同步:最后一帧官方可能刚写完 inline 宽度,而下一次
1079
- // ResizeObserver 不会再触发(布局已稳定),补齐才能让插件按"最终宽度"重写轨道。
1080
- const onPointerRelease = () => { if (active) scheduleSync() }
1081
- document.addEventListener('pointerup', onPointerRelease, true)
1082
- document.addEventListener('pointercancel', onPointerRelease, true)
1083
- const deferSync = () => {
1084
- if (syncTimer !== null) return
1085
- const wait = Math.max(48, motionUntil - performance.now() + 48)
1086
- syncTimer = setTimeout(() => { syncTimer = null; scheduleSync() }, wait)
1087
- }
1088
- const runSync = () => {
1089
- syncFrame = 0
1090
- if (!active) return
1091
- if (motionActive()) { syncPending = true; deferSync(); return }
1092
- syncPending = false
1093
- applyBackground(current, theme); tagDom(); ensureLatestButton(); watchColumns(); measureLatestButton(conversationScrollElement); scheduleConversationScroll()
1094
- }
1095
- const scheduleSync = () => {
1096
- if (syncFrame !== 0) return
1097
- if (motionActive()) { syncPending = true; deferSync(); return }
1098
- syncFrame = requestAnimationFrame(runSync)
1099
- }
1100
- // 串流期间 DOM 每秒要变几十次,而 applyBackground + tagDom 是"全文档查询 + 几十个
1101
- // CSS 变量 + 主题 token"的重活,只为让新内容被标记到。把它去抖到安静期:转写越长,
1102
- // 每次省下的越多,这正是"越用越卡"的来源。轻活(跟随最新、按钮位置)仍每帧做。
1103
- const FULL_SYNC_DEBOUNCE_MS = 160
1104
- let fullSyncTimer = null
1105
- const scheduleFullSync = () => {
1106
- if (fullSyncTimer !== null) return
1107
- fullSyncTimer = setTimeout(() => { fullSyncTimer = null; if (active) scheduleSync() }, FULL_SYNC_DEBOUNCE_MS)
1108
- }
1109
- let lightSyncFrame = 0
1110
- const scheduleLightSync = () => {
1111
- if (lightSyncFrame !== 0) return
1112
- lightSyncFrame = requestAnimationFrame(() => { lightSyncFrame = 0; if (active) scheduleConversationScroll() })
1113
- }
1114
- // 右栏(文档预览)滑动期间摘掉插件自己加的 backdrop-filter:官方面板本来是不透明的,
1115
- // 毛玻璃是本插件加的,而它在「面板首次从屏幕外滑入」这一帧要新建整块 render surface,
1116
- // 之后平移的每一帧还要按新背景重算模糊。摘掉后动画结束再淡回来(.16s)。
1117
- const setPopupMotion = (on) => {
1118
- try {
1119
- if (on) document.documentElement.setAttribute('data-dsh-popup-motion', 'true')
1120
- else document.documentElement.removeAttribute('data-dsh-popup-motion')
1121
- } catch { /* 无 document 时必须安静 */ }
1122
- }
1123
- flushAfterMotion = () => { setPopupMotion(false); if (syncPending) scheduleSync() }
1124
- // 放行容器过渡:第一次看到右栏真正展开(或 3s 都没打开过)时解除闸门。
1125
- let popupAnimGateTimer = setTimeout(() => { popupAnimGateTimer = null; try { document.documentElement.removeAttribute('data-dsh-popup-anim') } catch { /* 忽略 */ } }, 3000)
1126
- const openPopupAnimGate = () => {
1127
- if (popupAnimGateTimer === null) return
1128
- clearTimeout(popupAnimGateTimer)
1129
- popupAnimGateTimer = null
1130
- try { document.documentElement.removeAttribute('data-dsh-popup-anim') } catch { /* 忽略 */ }
1131
- }
1132
- // 只有"新增节点会改变插件标记目标"(切会话、换主面板、开右栏)才值得立刻全量同步;
1133
- // 普通消息行与流式 delta 只走轻活 + 去抖全量。
1134
- const STRUCTURAL_SELECTOR = '[data-phase], [data-conversation-scroll], [data-composer-seat], [data-sidebar-right-panel], [data-slot="main"]'
1135
- const hasStructuralAddition = (records) => {
1136
- for (const record of records) {
1137
- if (record.type !== 'childList') continue
1138
- for (const node of record.addedNodes) {
1139
- if (node.nodeType !== 1) continue
1140
- if (typeof node.matches === 'function' && node.matches(STRUCTURAL_SELECTOR)) return true
1141
- if (typeof node.querySelector === 'function' && node.querySelector(STRUCTURAL_SELECTOR) !== null) return true
1142
- }
1143
- }
1144
- return false
1145
- }
1146
- const mo = new MutationObserver((records) => {
1147
- let immediate = false
1148
- for (const record of records) {
1149
- // 官方在"同一次提交"里既翻转 data-sidebar-right-open、又首次渲染 tab 内容
1150
- // (iframe / Markdown 解析),所以它出现的那一刻就是动画的起手帧。
1151
- if (record.type === 'attributes' && record.attributeName === 'hidden') {
1152
- // 切换会话只翻 SessionView 的 hidden:右栏可见性变了但中心列宽度
1153
- // 未必变,ResizeObserver 不会回调,这里必须主动重算一次轨道。
1154
- syncFrameNow()
1155
- immediate = true
1156
- continue
1157
- }
1158
- if (record.type === 'attributes' && record.attributeName === 'data-sidebar-right-open') {
1159
- openPopupAnimGate()
1160
- enterMotion(420)
1161
- setPopupMotion(true)
1162
- syncFrameNow()
1163
- immediate = true
1164
- }
1165
- }
1166
- if (immediate || hasStructuralAddition(records)) scheduleSync()
1167
- else scheduleFullSync()
1168
- scheduleLightSync()
1169
- })
1170
- mo.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['aria-expanded', 'data-variant', 'data-sidebar-right-open', 'hidden'] })
1171
- // 0.1.5 的文档预览弹窗展开/收起会改 frame 的网格轨道(会话列随之收窄),而 React 只重写
1172
- // inline grid-template-columns,不一定产生 childList 变更。用 ResizeObserver 盯住会话列
1173
- // 宽度:宽度一变就立刻按官方轨道重排,弹窗弹出时会话区不会"慢半拍"。
1174
- let columnObserver = null
1175
- let columnTarget = null
1176
- let columnFrame = 0
1177
- const scheduleColumns = () => {
1178
- if (columnFrame !== 0) return
1179
- columnFrame = requestAnimationFrame(() => {
1180
- columnFrame = 0
1181
- if (!active) return
1182
- // 只同步几何。这个回调在轨道动画期间是"每帧一次",以前它调的是全量
1183
- // applyBackground(几十个 CSS 变量 + 主题 token + 全量查询)——右栏滑入时
1184
- // 每帧都要付一次全页样式重算,首次(缓存全冷)尤其贵。
1185
- syncFrameNow()
1186
- })
1187
- }
1188
- const watchColumns = () => {
1189
- const center = document.querySelector('[class*="centerCol"]')
1190
- if (center === columnTarget) return
1191
- if (columnObserver !== null) { columnObserver.disconnect(); columnObserver = null }
1192
- columnTarget = center
1193
- if (center !== null && typeof ResizeObserver === 'function') {
1194
- columnObserver = new ResizeObserver(scheduleColumns)
1195
- columnObserver.observe(center)
1196
- }
1197
- }
1198
- watchColumns()
1199
- return () => { active = false; flushAfterMotion = null; setPopupMotion(false); document.querySelectorAll('[data-dsh-appearance-page]').forEach((el) => el.removeAttribute('data-dsh-appearance-page')); document.querySelectorAll('style[data-plugin-css="' + NS + ':page"]').forEach((el) => el.remove()); if (popupAnimGateTimer !== null) { clearTimeout(popupAnimGateTimer); popupAnimGateTimer = null; try { document.documentElement.removeAttribute('data-dsh-popup-anim') } catch { /* 忽略 */ } } if (prewarmTimer !== null) { clearTimeout(prewarmTimer); prewarmTimer = null } if (syncFrame !== 0) { cancelAnimationFrame(syncFrame); syncFrame = 0 } if (fullSyncTimer !== null) { clearTimeout(fullSyncTimer); fullSyncTimer = null } if (lightSyncFrame !== 0) { cancelAnimationFrame(lightSyncFrame); lightSyncFrame = 0 } if (syncTimer !== null) { clearTimeout(syncTimer); syncTimer = null } if (sidebarHoverFrame !== 0) { cancelAnimationFrame(sidebarHoverFrame); sidebarHoverFrame = 0 } if (motionTimer !== null) { clearTimeout(motionTimer); motionTimer = null } motionUntil = 0; if (columnObserver !== null) { columnObserver.disconnect(); columnObserver = null } if (columnFrame !== 0) { cancelAnimationFrame(columnFrame); columnFrame = 0 } if (bootTimer !== null && bootTimer !== undefined) { clearTimeout(bootTimer); bootTimer = null } if (persistTimer !== null && persistTimer !== undefined) { clearTimeout(persistTimer); persistTimer = null } if (sidebarPinTimer !== null) { clearTimeout(sidebarPinTimer); sidebarPinTimer = null } cancelAnimationFrame(frame); cancelAnimationFrame(conversationScrollFrame); if (conversationScrollElement && conversationScrollListener) conversationScrollElement.removeEventListener('scroll', conversationScrollListener); if (conversationScrollHost && conversationScrollHostPosition !== null) { if (conversationScrollHostPosition[0]) conversationScrollHost.style.setProperty('position', conversationScrollHostPosition[0], conversationScrollHostPosition[1]); else conversationScrollHost.style.removeProperty('position') } cancelAnimationFrame(sidebarRestoreFrame); window.removeEventListener('pointerdown', sidebarToggleClick, true); window.removeEventListener('mousedown', sidebarToggleClick, true); window.removeEventListener('click', sidebarToggleClick, true); document.removeEventListener('click', sidebarToggleClick, true); window.removeEventListener('resize', onWindowResize); document.removeEventListener('mousemove', move); document.removeEventListener('mousemove', sidebarHover); document.removeEventListener('pointerup', onPointerRelease, true); document.removeEventListener('pointercancel', onPointerRelease, true); mo.disconnect(); sidebarStyleElements.forEach((sidebar) => restoreStyle(sidebarStyleState, sidebar)); sidebarStyleElements.clear(); sidebarRootStyleElements.forEach((root) => restoreStyle(sidebarRootStyleState, root)); sidebarRootStyleElements.clear(); document.querySelectorAll('[class*="frame"]').forEach((frameRoot) => restoreStyle(frameStyleState, frameRoot)); document.querySelectorAll('.dsh-appearance-wash, .dsh-appearance-bg').forEach((el) => el.remove()); document.querySelectorAll('#dsh-ui-appearance-bg-css').forEach((el) => el.remove()); document.querySelectorAll('[data-dsh-appearance-composer]').forEach((el) => el.removeAttribute('data-dsh-appearance-composer')); document.querySelectorAll('[data-dsh-appearance-session], [data-dsh-appearance-seat]').forEach((el) => { el.removeAttribute('data-dsh-appearance-session'); el.removeAttribute('data-dsh-appearance-seat') }); if (preloadProbe) { preloadProbe.onload = null; preloadProbe.onerror = null; preloadProbe = null } if (preloadTimeout !== null) { clearTimeout(preloadTimeout); preloadTimeout = null } if (latestButton?.isConnected) latestButton.remove(); latestButton = null; appearanceThemeDisposer?.(); appearanceThemeDisposer = null; document.getElementById('dsh-ui-appearance-bg-css')?.remove(); if (preloadTag?.isConnected && document.getElementById('dsh-ui-appearance-preload') === preloadTag) preloadTag.remove(); appearanceRootStyles.forEach(([value, priority, appliedValue], name) => { const currentValue = document.documentElement.style.getPropertyValue(name); if (currentValue === appliedValue) { if (value) document.documentElement.style.setProperty(name, value, priority); else document.documentElement.style.removeProperty(name) } }); appearanceRootStyles.clear(); appearanceRootStyles.clear(); document.documentElement.removeAttribute('data-dsh-popup-sync'); document.documentElement.style.removeProperty('--dsh-rightbar-track'); tag.remove(); popupTag.remove(); bg.remove() }
1200
- }, 'dsh-ui-appearance: shell')
1201
- // DSH 0.1.2 起 primitives 的 Tooltip 气泡不再 portal 到 document.body(0.1.1 是
1202
- // createPortal 到 body),但它仍是 position:fixed;本插件给会话卡片/输入框/设置面板
1203
- // 加了 backdrop-filter,这些卡片因此成为 fixed 元素的包含块,气泡会按卡片左上角定位,
1204
- // 视觉上飞出很远。
1205
- // 做法:气泡一进 DOM 就找出最近的"包含块祖先",把它的视口原点从气泡的 left/top 里扣掉。
1206
- // 量的是祖先的 rect,所以不受气泡自身入场动画影响;补偿值记在气泡的 data 属性上,
1207
- // 重复扫描(包括插件的多个实例)不会叠加,也不会形成"改样式 → 再次触发观察者"的死循环。
1208
- ctx.effect(() => {
1209
- const FIX_ATTR = 'data-dsh-tooltip-fix'
1210
- const createsContainingBlock = (style) => (
1211
- style.transform !== 'none'
1212
- || style.filter !== 'none'
1213
- || style.backdropFilter !== 'none'
1214
- || style.perspective !== 'none'
1215
- || style.willChange.includes('transform')
1216
- || style.willChange.includes('filter')
1217
- || style.willChange.includes('perspective')
1218
- || /paint|layout|strict|content/.test(style.contain)
1219
- )
1220
- // fixed 元素的包含块是那个祖先的 padding box,而 getBoundingClientRect 给的是 border box。
1221
- const originOf = (bubble) => {
1222
- let element = bubble.parentElement
1223
- while (element !== null && element !== document.documentElement) {
1224
- const style = getComputedStyle(element)
1225
- if (createsContainingBlock(style)) {
1226
- const rect = element.getBoundingClientRect()
1227
- return {
1228
- x: rect.left + (parseFloat(style.borderLeftWidth) || 0),
1229
- y: rect.top + (parseFloat(style.borderTopWidth) || 0),
1230
- }
1231
- }
1232
- element = element.parentElement
1233
- }
1234
- return null
1235
- }
1236
- const align = (bubble) => {
1237
- if (!(bubble instanceof HTMLElement) || bubble.getAttribute('role') !== 'tooltip') return
1238
- const left = bubble.style.left
1239
- const top = bubble.style.top
1240
- if (left === '' || top === '') return
1241
- // 当前值就是我们上次写下的补偿值 → 已经处理过,别再来一次。
1242
- const fixed = bubble.getAttribute(FIX_ATTR)
1243
- if (fixed !== null) {
1244
- const separator = fixed.indexOf('|')
1245
- if (fixed.slice(0, separator) === left && fixed.slice(separator + 1) === top) return
1246
- }
1247
- const origin = originOf(bubble)
1248
- if (origin === null) return
1249
- const x = parseFloat(left)
1250
- const y = parseFloat(top)
1251
- if (!Number.isFinite(x) || !Number.isFinite(y)) return
1252
- const nextLeft = `${x - origin.x}px`
1253
- const nextTop = `${y - origin.y}px`
1254
- if (nextLeft === left && nextTop === top) return
1255
- bubble.setAttribute(FIX_ATTR, `${nextLeft}|${nextTop}`)
1256
- bubble.style.left = nextLeft
1257
- bubble.style.top = nextTop
1258
- }
1259
- const scan = () => document.querySelectorAll('[role="tooltip"]').forEach(align)
1260
- // 观察者回调只做合并调度:一帧最多补一次,避免连续改样式时反复扫描。
1261
- let frame = 0
1262
- const schedule = () => {
1263
- if (frame !== 0) return
1264
- frame = requestAnimationFrame(() => { frame = 0; scan() })
1265
- }
1266
- // 只在这批变更真的涉及 tooltip 时才扫描:原来每次 DOM 变化都 querySelectorAll
1267
- // 一遍全文档,转写越长越贵,而 tooltip 出现/移动本身是低频事件。
1268
- const involvesTooltip = (records) => {
1269
- for (const record of records) {
1270
- if (record.type === 'attributes') {
1271
- const target = record.target
1272
- if (target && typeof target.getAttribute === 'function' && target.getAttribute('role') === 'tooltip') return true
1273
- continue
1274
- }
1275
- for (const node of record.addedNodes) {
1276
- if (node.nodeType !== 1) continue
1277
- if (typeof node.getAttribute === 'function' && node.getAttribute('role') === 'tooltip') return true
1278
- if (typeof node.querySelector === 'function' && node.querySelector('[role="tooltip"]') !== null) return true
1279
- }
1280
- }
1281
- return false
1282
- }
1283
- const observer = new MutationObserver((records) => { if (involvesTooltip(records)) schedule() })
1284
- if (document.body !== null) observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style'] })
1285
- window.addEventListener('resize', schedule)
1286
- schedule()
1287
- return () => {
1288
- observer.disconnect()
1289
- window.removeEventListener('resize', schedule)
1290
- if (frame !== 0) cancelAnimationFrame(frame)
1291
- }
1292
- }, 'dsh-ui-appearance: tooltip offset')
1293
- // 桌面端(Electron)默认拒绝一切权限,包括 clipboard-sanitized-write,
1294
- // navigator.clipboard.writeText 会抛 NotAllowedError;而 DSH 的 writeClipboard 在
1295
- // "异步 API 存在但抛错"时不会退回 execCommand,复制按钮于是毫无反应。
1296
- // 桌面端 preload 已暴露走 IPC 的原生剪贴板(window.dshDesktopClipboard),这里优先用它,
1297
- // 失败再退回浏览器 API。Web 端没有这个桥,effect 直接返回,行为不变。
1298
- // DSH 0.2.0 换成了 window.dshDesktop(且不含剪贴板写入器),这个桥已不存在,本 effect 在
1299
- // 桌面端因此变成空转——客户端自己的 writeClipboard 现在自带 execCommand 回退,功能不受影响。
1300
- // 整段包在 try 里:任何环境差异都不允许影响插件加载。
1301
- ctx.effect(() => {
1302
- try {
1303
- const bridge = window.dshDesktopClipboard
1304
- if (bridge === undefined || typeof bridge.writeText !== 'function') return
1305
- const clipboard = navigator.clipboard
1306
- if (clipboard === undefined || typeof clipboard.writeText !== 'function') return
1307
- const original = clipboard.writeText
1308
- const hadOwnWriteText = Object.prototype.hasOwnProperty.call(clipboard, 'writeText')
1309
- // 多个实例(HMR 重载)会串起来包装,链上每一环都记住最原始的实现,
1310
- // 这样卸载链头时还原到最初版本,而不是还原成上一个包装。
1311
- const root = typeof original.dshClipboardRoot === 'function' ? original.dshClipboardRoot : original
1312
- const patched = (text) => Promise.resolve()
1313
- .then(() => bridge.writeText(String(text)))
1314
- .then(() => undefined)
1315
- .catch(() => Promise.resolve(original.call(clipboard, text)).then(() => undefined))
1316
- patched.dshClipboardRoot = root
1317
- Object.defineProperty(clipboard, 'writeText', { value: patched, configurable: true, writable: true })
1318
- // 浏览器里 writeText 在 Clipboard.prototype 上,delete 就能还原;
1319
- // 若运行环境把它放在实例自身上,则写回原函数。
1320
- // 卸载时只在"自己仍是链头"时还原,否则会把更新实例的补丁一起删掉。
1321
- return () => {
1322
- try {
1323
- if (clipboard.writeText !== patched) return
1324
- if (hadOwnWriteText) Object.defineProperty(clipboard, 'writeText', { value: root, configurable: true, writable: true })
1325
- else delete clipboard.writeText
1326
- } catch (error) { /* 还原失败不影响卸载 */ }
1327
- }
1328
- } catch (error) { return }
1329
- }, 'dsh-ui-appearance: clipboard fallback')
1330
- ctx.effect(() => slots.inject('settings.section', () => slots.register({ name: 'settings.section', id: NS, order: 90, label: '外观' }, Panel)))
1331
- }
1332
- module.exports = { name: NS, inject: ['slots', 'theme'], apply }
1333
- return module.exports
1334
- }
1335
- })
1336
-
1
+ window.__ModuleLoader__.load({ id: '@luosuqwq/dsh-ui-appearance', factory: (require) => {
2
+ const module = { exports: {} }
3
+ const React = require('react')
4
+ const h = React.createElement
5
+ const NS = 'dsh-ui-appearance'
6
+ const STORE_KEY = 'dsh-ui-appearance:settings'
7
+ // 与宿主保持同一个默认值:没配置过的用户开箱就有壁纸;显式选过「不使用壁纸」的用户存的是空串,不受影响。
8
+ const DEFAULT_WALLPAPER = '/bg/' + encodeURIComponent('花与大肥鱼 version2.png')
9
+ const defaults = {
10
+ bgImage: DEFAULT_WALLPAPER, bgSize: 'cover', bgOpacity: 1, bgBlur: 0,
11
+ bgMask: '#f8f7f7', bgMaskOpacity: 0,
12
+ parallaxEnabled: true, parallaxAmplitude: 12, parallaxEasing: 'ease-out',
13
+ conversationEnabled: true, conversationOpacity: 0.2, conversationBlur: 2, conversationColor: '#ffffff', conversationWidth: 870,
14
+ chatBoxColor: '#ffffff', chatBoxOpacity: 0.59, chatBoxBlur: 0, chatBoxBorder: 'none', chatBoxRadius: 24,
15
+ newChatBoxColor: '#ffffff', newChatBoxOpacity: 0.9, newChatBoxBlur: 8, newChatBoxBorder: 'thin', newChatBoxRadius: 16,
16
+ existingChatBoxColor: '#ffffff', existingChatBoxOpacity: 0.82, existingChatBoxBlur: 10, existingChatBoxBorder: 'thin', existingChatBoxRadius: 16,
17
+ settingsOpacity: 0.4, settingsBlur: 16, settingsColor: '#ffffff',
18
+ sidebarOpacity: 0.4, sidebarAutoHide: false, prewarmFirstSlide: true,
19
+ previewPopupShared: true, previewPopupInset: 8,
20
+ pageCard: true,
21
+ }
22
+ const rgba = (color, a) => { const m = /^#?([0-9a-f]{6})$/i.exec(color || ''); if (!m) return color; const n = parseInt(m[1], 16); return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${a})` }
23
+ const borderValue = (v) => v === 'thick' ? '2px solid rgba(120,130,145,.35)' : v === 'thin' ? '1px solid rgba(120,130,145,.24)' : 'none'
24
+ const load = () => {
25
+ try {
26
+ const raw = JSON.parse(localStorage.getItem(STORE_KEY)) || {}
27
+ const merged = { ...defaults, ...raw }
28
+ if (!merged.v || merged.v < 2) {
29
+ merged.chatBoxBorder = 'none'; merged.chatBoxBlur = 0
30
+ merged.v = 2
31
+ try { localStorage.setItem(STORE_KEY, JSON.stringify(merged)) } catch {}
32
+ }
33
+ return merged
34
+ } catch { return { ...defaults } }
35
+ }
36
+ let current = load()
37
+ const preloadBackground = (settings) => {
38
+ if (typeof document === 'undefined') return null
39
+ // Once the real wallpaper layer (.dsh-appearance-bg) exists, do NOT keep a
40
+ // second always-100%-opaque wallpaper on <html>: it would duplicate the image
41
+ // and show through (instead of a plain base) when wallpaper transparency drops.
42
+ if (document.querySelector('.dsh-appearance-bg')) return null
43
+ const old = document.getElementById('dsh-ui-appearance-preload')
44
+ old?.remove()
45
+ const tag = document.createElement('style')
46
+ tag.id = 'dsh-ui-appearance-preload'
47
+ const image = settings?.bgImage ? `url("${String(settings.bgImage).replace(/"/g, '\\"')}")` : 'none'
48
+ tag.textContent = `html,body{background-color:transparent!important}html{background-image:${image}!important;background-size:${settings?.bgSize === 'contain' ? 'contain' : 'cover'}!important;background-repeat:no-repeat!important;background-position:center!important}#root{background:transparent!important}`
49
+ document.head.appendChild(tag)
50
+ if (!settings?.bgImage) tag.remove()
51
+ return tag
52
+ }
53
+ preloadBackground(current)
54
+ if (typeof document !== 'undefined') {
55
+ fetch('/bg/config').then((response) => response.ok ? response.json() : null).then((config) => {
56
+ if (!config || !config.bgImage) return
57
+ current = { ...defaults, ...config }
58
+ try { localStorage.setItem(STORE_KEY, JSON.stringify(current)) } catch {}
59
+ preloadBackground(current)
60
+ }).catch(() => {})
61
+ }
62
+ let persistTimer
63
+ let stateRevision = 0
64
+ const persistRemote = (s) => fetch('/bg/config', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(s) }).catch(() => {})
65
+ const persist = (s) => {
66
+ try { localStorage.setItem(STORE_KEY, JSON.stringify(s)) } catch {}
67
+ clearTimeout(persistTimer)
68
+ persistTimer = setTimeout(() => { void persistRemote(s) }, 120)
69
+ }
70
+ const hydrate = async () => {
71
+ const revision = stateRevision
72
+ let remote = null
73
+ let backgrounds = null
74
+ try {
75
+ const response = await fetch('/bg/config')
76
+ if (response.ok) remote = await response.json()
77
+ } catch {}
78
+ try {
79
+ const response = await fetch('/bg/list')
80
+ if (response.ok) backgrounds = await response.json()
81
+ } catch {}
82
+ if (revision !== stateRevision) return current
83
+ const hasRemoteConfig = remote && typeof remote === 'object' && (remote.bgImage || Number(remote.v) >= 2)
84
+ const next = { ...defaults, ...current, ...(hasRemoteConfig ? remote : {}) }
85
+ if (Array.isArray(backgrounds) && next.bgImage && !backgrounds.includes(next.bgImage)) {
86
+
87
+ next.bgImage = ''
88
+
89
+ }
90
+ current = next
91
+ try { localStorage.setItem(STORE_KEY, JSON.stringify(current)) } catch {}
92
+ if (!hasRemoteConfig) void persistRemote(current)
93
+ return current
94
+ }
95
+ let instantSidebarExpand = false
96
+ let sidebarWideWidth = 280
97
+ let sidebarPointerHandledAt = 0
98
+ let rightbarTrackPx = 0
99
+ let sidebarRevealed = false
100
+ let sidebarPinTimer = null
101
+ /* —— 动效预算(motion budget)——
102
+ 「首次滑入卡顿」的成因主要不在 CSS,而在动画窗口里还在做重活:
103
+ · 挂载时会连跑两遍 applyBackground(几十个 CSS 变量 + theme token + 全量查询);
104
+ · 每次 mousemove 都对侧栏 root 量一次 getBoundingClientRect(紧跟在一批 inline
105
+ 样式写入之后 → 强制同步布局);
106
+ · 右栏(文档预览)展开时,centerCol 的 ResizeObserver 每帧回调一次,而它调的是
107
+ 全量 applyBackground。
108
+ 这三件事在第一次发生时代价最大(样式/布局/字体缓存都是冷的),正好压在滑入动画的
109
+ 前几帧上,于是"第一次特别卡、之后越来越顺"。下面的窗口只做一件事:动画期间不跑重活,
110
+ 结束后补一次合并同步;几何同步照旧每帧做(它便宜)。 */
111
+ let motionUntil = 0
112
+ let motionTimer = null
113
+ const motionActive = () => (typeof performance !== 'undefined' ? performance.now() : 0) < motionUntil
114
+ const enterMotion = (ms) => {
115
+ const now = typeof performance !== 'undefined' ? performance.now() : 0
116
+ const until = now + ms
117
+ if (until > motionUntil) motionUntil = until
118
+ if (motionTimer !== null) clearTimeout(motionTimer)
119
+ // 计时器按"当前窗口真正结束的时刻"重排:短窗口(hover 260ms)不能截断长窗口(右栏 420ms)。
120
+ const remaining = Math.max(0, motionUntil - now)
121
+ motionTimer = setTimeout(() => { motionTimer = null; motionUntil = 0; flushAfterMotion?.() }, remaining + 48)
122
+ }
123
+ // 由 shell effect 注入:把动画期间被推迟的合并同步补上。
124
+ let flushAfterMotion = null
125
+ // 侧栏几何是否已经初始化过(首帧直接归位,不做过渡)。
126
+ let sidebarGeometryReady = false
127
+ // 侧栏内容是否已经在屏幕内被光栅化过一次(首次展开的过渡只会在冷启动时掉帧)。
128
+ let sidebarWarmed = false
129
+ // 侧栏"瞬时定位"的令牌:每次瞬时写样式 +1,延迟还回过渡时对比,避免旧回调覆盖新状态。
130
+ let sidebarInstantToken = 0
131
+ // 首次展开前的静默预热(见 README §3.6)。为什么需要它:自动隐藏的侧栏是靠
132
+ // margin-left 移出视口的,屏幕外的内容不会被光栅化,所以"第一次滑入"其实是
133
+ // 这笔栅格化/字形缓存第一次被付账,代价正好落在过渡的头两帧上。
134
+ // 预热做法:趁用户还没动它,把侧栏在屏幕内画一帧(opacity≈0,肉眼不可见)再收回去。
135
+ const prewarmSidebar = () => {
136
+ if (sidebarWarmed || !current.sidebarAutoHide || current.prewarmFirstSlide === false) return false
137
+ const sidebar = document.querySelector('[class*="sidebarCol"]')
138
+ const root = sidebar && sidebar.querySelector('[data-slot="sidebar"] > [class*="root"]')
139
+ if (!root || !root.isConnected) return false
140
+ if (sidebar.getAttribute('data-dsh-sidebar-revealed') !== 'false') return false
141
+ if (root.querySelector('[role="dialog"]')) return false
142
+ const width = sidebarWideWidth > 50 ? Math.round(sidebarWideWidth) : 280
143
+ root.style.setProperty('transition', 'none', 'important')
144
+ root.style.setProperty('margin-left', '0px', 'important')
145
+ root.style.setProperty('opacity', '0.002', 'important')
146
+ root.style.setProperty('pointer-events', 'none', 'important')
147
+ sidebarWarmed = true
148
+ const restore = () => {
149
+ if (!root.isConnected) return
150
+ root.style.setProperty('margin-left', '-' + width + 'px', 'important')
151
+ requestAnimationFrame(() => {
152
+ if (!root.isConnected) return
153
+ root.style.setProperty('transition', 'margin-left .22s var(--ds-ease-in-out)', 'important')
154
+ root.style.removeProperty('pointer-events')
155
+ })
156
+ }
157
+ let restored = false
158
+ const finish = () => {
159
+ if (restored || !root.isConnected) return
160
+ restored = true
161
+ root.style.removeProperty('opacity')
162
+ root.style.removeProperty('pointer-events')
163
+ if (sidebar.getAttribute('data-dsh-sidebar-revealed') !== 'false') {
164
+ // 预热期间用户已经在往左边缘移动了:把这帧直接当作展开态,别收回去。
165
+ root.style.setProperty('transition', 'margin-left .22s var(--ds-ease-in-out)', 'important')
166
+ return
167
+ }
168
+ restore()
169
+ }
170
+ requestAnimationFrame(() => requestAnimationFrame(finish))
171
+ // 后台标签页里 rAF 不跑:兜底 400ms 后强制收回去,避免侧栏停在"不可见但占位"的状态。
172
+ setTimeout(finish, 400)
173
+ return true
174
+ }
175
+ const sidebarStyleState = new WeakMap()
176
+ const sidebarStyleElements = new Set()
177
+ const sidebarRootStyleState = new WeakMap()
178
+ const sidebarRootStyleElements = new Set()
179
+ const frameStyleState = new WeakMap()
180
+ const rememberStyle = (map, el, properties) => {
181
+ if (map.has(el)) return map.get(el)
182
+ const state = Object.fromEntries(properties.map((name) => [name, [el.style.getPropertyValue(name), el.style.getPropertyPriority(name)]]))
183
+ map.set(el, state)
184
+ return state
185
+ }
186
+ const restoreStyleProperties = (map, el, properties) => {
187
+ const state = map.get(el)
188
+ if (!state) return
189
+ properties.forEach((name) => {
190
+ const entry = state[name]
191
+ if (!entry) return
192
+ const [value, priority] = entry
193
+ if (value) el.style.setProperty(name, value, priority)
194
+ else el.style.removeProperty(name)
195
+ })
196
+ }
197
+ const restoreStyle = (map, el) => {
198
+ const state = map.get(el)
199
+ if (!state) return
200
+ Object.entries(state).forEach(([name, [value, priority]]) => value ? el.style.setProperty(name, value, priority) : el.style.removeProperty(name))
201
+ map.delete(el)
202
+ }
203
+ /* DSH 0.2.0 把官方的"收起侧边栏"按钮改成了 caption 里的固定按钮:Windows 下
204
+ `[data-windows-titlebar] ._toggle{position:fixed;left:12px;top:calc((标题栏高-28px)/2);z-index:30}`,
205
+ 而 macOS 下整个侧栏收起时改由框架 `shell.leading` 座里的 HeaderLeadingControls 提供
206
+ (没有 `toggle` 类名,也不在 `sidebarCol` 内)。0.1.5 完全没有这套。
207
+ 关键点:这个按钮仍然是本节点(侧栏 root)的后代。只要 root 上有非 `none` 的 transform
208
+ (哪怕只是 `translateX(0)`)或 `will-change:transform`,root 就会成为 fixed 后代的
209
+ 包含块——按钮会改以 root(在标题栏下方)为原点定位,并且跟着侧栏一起被拖出屏幕。
210
+ 所以这里改用 `margin-left` 位移:隐藏时把 root 推到视口左侧外(列本身已被插件设成
211
+ width:0 / overflow:visible,隐藏靠移出视口、显示靠溢出可见),效果与原来的
212
+ translateX(-100%) 一致,但不产生包含块,官方按钮就始终以视口为参照。 */
213
+ // instant=true 用于两种情况(见 README §3.6):
214
+ // · 挂载后的第一次定位:侧栏要立刻停在自己的位置上,不能从 0 滑过去;
215
+ // · 首次从屏幕外展开:此刻侧栏内容才第一次被光栅化,过渡只会把这笔开销摊成掉帧,
216
+ // 不如直接显示(之后所有展开都正常走 .22s 过渡)。
217
+ const syncSidebarRoot = (sidebar, autoHide, instant) => {
218
+ const root = sidebar?.querySelector('[data-slot="sidebar"] > [class*="root"]')
219
+ if (!root) return
220
+ if (!sidebarRootStyleElements.has(root)) {
221
+ sidebarRootStyleElements.add(root)
222
+ sidebarRootStyleState.set(root, { marginLeft: [root.style.getPropertyValue('margin-left'), root.style.getPropertyPriority('margin-left')], transform: [root.style.getPropertyValue('transform'), root.style.getPropertyPriority('transform')], willChange: [root.style.getPropertyValue('will-change'), root.style.getPropertyPriority('will-change')], transition: [root.style.getPropertyValue('transition'), root.style.getPropertyPriority('transition')] })
223
+ }
224
+ const revealed = sidebar.getAttribute('data-dsh-sidebar-revealed') !== 'false'
225
+ const hasDialog = !!root.querySelector('[role="dialog"]')
226
+ // 隐藏偏移必须用**真实宽度**,缓存只能兜底。缓存会被写小/写旧:
227
+ // · 标题栏的收起按钮在官方窄栏(56px)姿态下被点到(旧代码拿 >0 就写缓存);
228
+ // · 拖分界线 / 切会话时量到过渡中的中间值;
229
+ // · 自动隐藏期间 syncFrameColumns 不再读官方轨道(autoHide 时它把左轨当 0),
230
+ // 缓存从此不会被刷新,和真实宽度越走越远。
231
+ // 一旦缓存小于真实宽度,收起就只把侧栏推出去那么远 —— 表现就是左边永远留一条缝、
232
+ // 或半截侧栏露在屏幕外,而且随"上次量到的是哪个姿态"随机复现。
233
+ // 代价只有一次 getBoundingClientRect,并且放在下面这批 inline 写入之前(不额外制造回流);
234
+ // 只在自动隐藏时测量:展开态根本不用宽度。
235
+ const measuredWidth = autoHide ? Math.round(root.getBoundingClientRect().width) : 0
236
+ if (measuredWidth > 200) sidebarWideWidth = measuredWidth
237
+ // 取两者较大值:欠移会露出侧栏(可见的 bug),过移只是把空无一物的侧栏多推出去一点,
238
+ // 视觉上无差别;展开动画的距离变大也不影响观感(时长固定 .22s)。
239
+ const sidebarWidth = Math.max(
240
+ measuredWidth > 50 ? measuredWidth : 0,
241
+ Math.round(sidebarWideWidth) || 0,
242
+ ) || 280
243
+ // 把可能存在的 transform/will-change 清干净:任何一处都会让官方 fixed 按钮改换包含块。
244
+ root.style.setProperty('transform', 'none', 'important')
245
+ root.style.removeProperty('will-change')
246
+ // 预热用的临时 opacity 必须在这里兜底清掉:任何一次同步都要保证侧栏是可见的。
247
+ if (root.style.getPropertyValue('opacity')) root.style.removeProperty('opacity')
248
+ const hidden = !!autoHide && !revealed && !hasDialog
249
+ const firstReveal = !!autoHide && !hidden && !sidebarWarmed && current.prewarmFirstSlide !== false
250
+ const instantNow = instant === true || !sidebarGeometryReady || firstReveal
251
+ if (instantNow) root.style.setProperty('transition', 'none', 'important')
252
+ else root.style.setProperty('transition', 'margin-left .22s var(--ds-ease-in-out)', 'important')
253
+ if (hidden) root.style.setProperty('margin-left', '-' + sidebarWidth + 'px', 'important')
254
+ else root.style.setProperty('margin-left', '0px', 'important')
255
+ sidebarGeometryReady = true
256
+ if (!hidden) sidebarWarmed = true
257
+ if (instantNow && !hasDialog) {
258
+ // 两帧后再把过渡还回去,确保浏览器已经用 transition:none 提交了这一帧。
259
+ // 用递增令牌防止"这两帧里又发生了一次同步"时被旧回调覆盖。
260
+ sidebarInstantToken += 1
261
+ const token = sidebarInstantToken
262
+ requestAnimationFrame(() => requestAnimationFrame(() => {
263
+ if (token !== sidebarInstantToken || !root.isConnected) return
264
+ root.style.setProperty('transition', 'margin-left .22s var(--ds-ease-in-out)', 'important')
265
+ }))
266
+ }
267
+ if (hasDialog) {
268
+ if (autoHide) sidebar.setAttribute('data-dsh-sidebar-revealed', 'true')
269
+ root.style.setProperty('margin-left', '0px', 'important')
270
+ root.style.setProperty('transition', 'none', 'important')
271
+ root.style.setProperty('contain', 'none', 'important')
272
+ sidebar.style.setProperty('z-index', autoHide ? '30' : '60', 'important')
273
+ } else if (!autoHide) {
274
+ sidebar.style.removeProperty('z-index')
275
+ }
276
+ }
277
+
278
+ // applyBackground 的"几何半":只动侧栏列和 root。点击收起、Hover 展开、动画结束后的
279
+ // 补同步都走这里,避免为了一个布尔开关重跑 applyBackground(它会重写几十个 CSS 变量、
280
+ // 主题 token 和壁纸样式——第一次跑时这些写入会把整页样式重算一遍)。
281
+ const applySidebarColumns = (s) => {
282
+ const autoHide = !!s.sidebarAutoHide
283
+ document.querySelectorAll('[class*="sidebarCol"]').forEach((sidebar) => {
284
+ rememberStyle(sidebarStyleState, sidebar, ['background', 'position', 'width', 'min-width', 'height', 'overflow', 'z-index'])
285
+ sidebar.setAttribute('data-dsh-auto-hide', String(autoHide))
286
+ if (autoHide) {
287
+ sidebar.setAttribute('data-dsh-sidebar-revealed', String(sidebarRevealed))
288
+ sidebar.style.setProperty('position', 'relative', 'important')
289
+ sidebar.style.setProperty('width', '0', 'important')
290
+ sidebar.style.setProperty('min-width', '0', 'important')
291
+ sidebar.style.setProperty('height', '100%', 'important')
292
+ sidebar.style.setProperty('overflow', 'visible', 'important')
293
+ sidebar.style.setProperty('z-index', '30', 'important')
294
+ } else {
295
+ sidebar.setAttribute('data-dsh-sidebar-revealed', 'true')
296
+ restoreStyleProperties(sidebarStyleState, sidebar, ['position', 'width', 'min-width', 'height', 'overflow', 'z-index'])
297
+ }
298
+ syncSidebarRoot(sidebar, autoHide)
299
+ })
300
+ }
301
+
302
+ // 给"非会话"的主面板根节点打标(供 PAGE_STYLE 使用)。判据:`.centerCol` 的直接子元素里,
303
+ // 自身或子树带 [data-phase] / [data-conversation-scroll] 的是会话页;其余都是页面
304
+ // (插件、自动化任务,以及以后新增的 main 面板)。不依赖 hashed 类名、不读 layout store。
305
+ const tagMainPanels = () => {
306
+ const keep = new Set()
307
+ // 官方的 main 槽是 `div[data-slot="main"]{display:contents}` 锚点,真正的面板是它的子元素
308
+ // (插件页 = section[data-plugin-panel],任务页 = section[data-testid="task-manager-page"])。
309
+ // 锚点找不到时退回 `.centerCol` 的直接子元素,兼容布局略有差异的版本。
310
+ const anchor = document.querySelector('[class*="centerCol"] [data-slot="main"]') || document.querySelector('[class*="centerCol"]')
311
+ // 会话区自己的卡片由 STYLE 负责;「不启用区分」时两张卡片一起消失。
312
+ const enabled = current.pageCard !== false && current.conversationEnabled !== false
313
+ if (enabled && anchor !== null) {
314
+ for (const el of Array.from(anchor.children)) {
315
+ if (el.hasAttribute('data-phase') || el.querySelector('[data-phase]') !== null) continue
316
+ if (el.querySelector('[data-conversation-scroll]') !== null) continue
317
+ if (el.querySelector('[data-composer-seat]') !== null) continue
318
+ keep.add(el)
319
+ el.setAttribute('data-dsh-appearance-page', '')
320
+ }
321
+ }
322
+ document.querySelectorAll('[data-dsh-appearance-page]').forEach((el) => { if (!keep.has(el)) el.removeAttribute('data-dsh-appearance-page') })
323
+ }
324
+
325
+ // DSH 0.1.5 的 frame 是"侧边栏 | 会话 | 右侧栏"三轨,右侧栏承载文档预览弹窗。
326
+ // 本插件必须自己写 grid-template-columns(固定侧边栏宽度、侧边栏自动隐藏),但第三轨
327
+ // 不能再写死 0:那会让弹窗浮在会话区之上、会话区也不跟着收窄("慢半拍")。
328
+ // 判断依据以"弹窗自己是否展开"(data-sidebar-right-open)为准,而不是只看 frame 上的
329
+ // data-rightbar-collapsed——后者只说明官方这一帧没给轨道(覆盖式弹窗),弹窗可能照样开着。
330
+ // DSH 0.2.0 的官方轨道换成了 `Npx minmax(0|400px, 1fr) minmax(0px, Mpx)`:第三轨不再是
331
+ // 裸的 `Npx`(右栏有轨道时中间轨还有 400px 最小值),旧正则因此永不匹配,插件会把右轨一直
332
+ // 钉在 0、弹窗退化成覆盖式浮层。这里两种写法都接受,并读出官方给的第三轨上限。
333
+ const FRAME_COLUMNS_RE = /^\s*[\d.]+px\s+minmax\(\s*(?:0(?:px)?|[\d.]+px)\s*,\s*1fr\s*\)\s+(?:minmax\(\s*0px?\s*,\s*([\d.]+)px\s*\)|([\d.]+)px)\s*$/
334
+ const MIN_CENTER_PX = 300
335
+ // 0.2.0 官方 grid 在右栏占轨道时给中间列的下限(见 AppFrame 的 gridTemplateColumns)。
336
+ const HOST_CENTER_MIN_PX = 400
337
+ // 官方 inline 轨道的**第一轨**(左列宽度)。拖动左侧分界线时,官方每次 pointermove 都会把
338
+ // 新宽度写进同一条 inline `grid-template-columns`;而插件又必须自己重写整条轨道。不读这个值
339
+ // 就等于每次都拿缓存宽度把用户拖出来的宽度按回去 —— 表现就是"左分界线拖不动 / 一松手就弹回"。
340
+ const FRAME_SIDEBAR_TRACK_RE = /^\s*([\d.]+)px\s+/
341
+ const frameSidebarTrackPx = (raw) => { const m = FRAME_SIDEBAR_TRACK_RE.exec(raw || ''); return m ? Math.round(parseFloat(m[1])) : 0 }
342
+ const syncFrameColumns = (frameRoot, autoHide, wideW, instant) => {
343
+ const raw = frameRoot.style.getPropertyValue('grid-template-columns')
344
+ const priority = frameRoot.style.getPropertyPriority('grid-template-columns')
345
+ // 右栏是按会话的:切换会话时旧会话的 SessionView 只是被 hidden,旧面板仍
346
+ // 带着 data-sidebar-right-open。querySelector 若先命中这个隐藏面板,右栏明明
347
+ // 已收起却仍给第三轨留宽,表现就是「侧栏消失、主栏不回撤」。只认可见面板。
348
+ const panel = Array.from(document.querySelectorAll('[data-sidebar-right-panel]')).find((el) => el.closest('[hidden]') === null) || null
349
+ const panelOpen = panel !== null && panel.hasAttribute('data-sidebar-right-open')
350
+ // DSH 0.2.0 的右栏面板不再写行内 `width`:它把自己的宽度发布成 `--dsh-sidebar-width`,
351
+ // 官方没给轨道时用这个值兜底(行内没有就退回计算值,兼容它挂在别的节点上的情况)。
352
+ const panelInline = panel === null ? '' : panel.style.width
353
+ const panelVarInline = panel === null ? '' : panel.style.getPropertyValue('--dsh-sidebar-width')
354
+ const panelTrack = /^[\d.]+px$/.test(panelInline) ? panelInline
355
+ : /^[\d.]+px$/.test(panelVarInline) ? panelVarInline
356
+ : panel === null ? '' : getComputedStyle(panel).getPropertyValue('--dsh-sidebar-width').trim()
357
+ const panelPx = /^[\d.]+px$/.test(panelTrack) ? Math.round(parseFloat(panelTrack)) : 0
358
+ let track = 0
359
+ if (panelOpen) {
360
+ const native = priority === 'important' || raw === '' ? null : FRAME_COLUMNS_RE.exec(raw)
361
+ if (native !== null) track = Math.max(0, Math.round(parseFloat(native[1] !== undefined ? native[1] : native[2])))
362
+ else if (panelPx > 0) track = panelPx
363
+ if (frameRoot.getAttribute('data-rightbar-collapsed') !== null && panelPx > 0) {
364
+ // 官方这一帧把右轨收成 0(覆盖式弹窗),但弹窗确实开着:只要会话列还放得下,
365
+ // 就替弹窗让出一条轨道,并保证会话列至少留 MIN_CENTER_PX;放不下才回退到官方覆盖式。
366
+ const sidebarTrack = autoHide ? 0 : wideW
367
+ const room = frameRoot.getBoundingClientRect().width - sidebarTrack - MIN_CENTER_PX
368
+ const wanted = Math.min(panelPx, Math.max(0, room))
369
+ track = wanted >= MIN_CENTER_PX ? wanted : 0
370
+ }
371
+ }
372
+ rightbarTrackPx = Math.max(0, track)
373
+ // 左轨宽度以官方 inline 第一轨为准(拖动分界线时它是唯一"当前值"),读不到才退回缓存。
374
+ // 注意 56px 是官方的窄栏(rail)宽度,只有明显是展开宽度时才更新缓存——缓存同时被
375
+ // 自动隐藏的负偏移使用,被窄栏覆盖会让侧栏只滑出 56px、剩下一截还留在屏幕里。
376
+ const nativeSidebarPx = autoHide ? 0 : frameSidebarTrackPx(raw)
377
+ if (nativeSidebarPx > 200) sidebarWideWidth = nativeSidebarPx
378
+ const sidebarTrack = autoHide ? '0' : `${nativeSidebarPx > 0 ? nativeSidebarPx : wideW}px`
379
+ // 官方拖拽分界线/即时切换期间([data-dragging] / [data-rightbar-instant])由官方自己接管网格:
380
+ // 官方样式表里这两条会把 transition 关掉,好让列宽 1:1 跟手;但本插件之前用行内 !important
381
+ // 写 transition,优先级压过了它们,于是拖拽期间列宽仍在走 .22s 缓动、指针追不上。这里拖拽
382
+ // 期间不写 !important、并把插件写的过渡整个删掉,交还给官方。
383
+ const dragging = frameRoot.hasAttribute('data-dragging') || frameRoot.hasAttribute('data-rightbar-instant')
384
+ // 中间列的最小宽度对齐 0.2.0 官方写法 `${cols.rightbar === 0 ? 0 : 400}px`:右栏没占轨道时
385
+ // 允许会话列被压到 0,右栏占轨道时保留 400px 下限(否则插件会把官方的 400px 下限抹掉)。
386
+ const centerMin = rightbarTrackPx > 0 ? HOST_CENTER_MIN_PX : 0
387
+ frameRoot.style.setProperty('grid-template-columns', `${sidebarTrack} minmax(${centerMin}px,1fr) ${rightbarTrackPx}px`, dragging ? '' : 'important')
388
+ if (dragging) frameRoot.style.removeProperty('transition')
389
+ else frameRoot.style.setProperty('transition', instant ? 'none' : 'grid-template-columns .22s var(--ds-ease-in-out)', 'important')
390
+ document.documentElement.style.setProperty('--dsh-rightbar-track', `${rightbarTrackPx}px`)
391
+ }
392
+ // DSH 0.1.5 的右侧文档预览("弹窗预览")与会话区共享同一层玻璃:底色/透明度、毛玻璃强度
393
+ // 直接取自 --dsh-conv-bg / --dsh-conv-blur,圆角与会话卡片一致(20px),不另开一套参数。
394
+ // 宽度故意不写:面板保持官方给它的 inline px 宽,鼠标每动一次它才变一次;一旦写成
395
+ // calc(100% - …) 就等于让面板宽度跟着被动画的网格轨道逐帧变化,预览里几千行代码会整篇
396
+ // 反复重排(拖动分界线卡顿的元凶之一)。
397
+ // 注意:这段必须单独放进自己的 <style>。STYLE 末尾的 `@media(max-width:640px){` 历史上就没
398
+ // 闭合(补上它会唤醒一批 0.1.2 时代的旧规则,反而破坏 0.1.5 的会话区滚动/排版),而挂在那个
399
+ // 标签后面会让本规则被解析成嵌套规则、永远不匹配——所以它不能复用主样式标签。
400
+ // 玻璃部分对所有形态生效("push" 与点「全屏」后的 "fullscreen" 都是同一个 [data-sidebar-right-panel],
401
+ // 全屏时官方背景同样是被主题 token 抹成透明的,必须一起补上);几何部分只针对 push。
402
+ const POPUP_STYLE = `html[data-dsh-popup-sync="true"] [data-sidebar-right-panel]{background:var(--dsh-conv-bg)!important;backdrop-filter:blur(var(--dsh-conv-blur));-webkit-backdrop-filter:blur(var(--dsh-conv-blur));transition:backdrop-filter .16s linear}html[data-dsh-popup-sync="true"] [data-sidebar-right-panel="push"]{top:var(--dsh-popup-inset,12px)!important;bottom:var(--dsh-popup-inset,12px)!important;right:var(--dsh-popup-inset,12px)!important;border:none!important;box-shadow:none!important;border-radius:20px!important;overflow:hidden!important;transition:transform .22s var(--ds-ease-in-out,cubic-bezier(.4,0,.2,1)),backdrop-filter .16s linear}html[data-dsh-popup-sync="true"][data-dsh-popup-anim="false"] [data-sidebar-right-panel="push"],html[data-dsh-popup-sync="true"] [class*="frame"][data-rightbar-instant] [data-sidebar-right-panel="push"]{transition:none!important}html[data-dsh-popup-sync="true"] [data-sidebar-right-panel="push"]:not([data-sidebar-right-open]){transform:translateX(calc(100% + var(--dsh-popup-inset,12px)))!important}html[data-dsh-popup-sync="true"] [data-sidebar-right-panel="push"] [data-dockkit-host="dock"],html[data-dsh-popup-sync="true"] [data-sidebar-right-panel="push"] [data-dockkit-empty],html[data-dsh-popup-sync="true"] [data-sidebar-right-panel="push"] [data-dockkit-divider]{transform:none!important}html[data-dsh-popup-motion="true"] [data-sidebar-right-panel]{backdrop-filter:none!important;-webkit-backdrop-filter:none!important}html[data-dsh-popup-sync="true"][data-dsh-popup-motion="true"] [data-sidebar-right-panel="push"][data-sidebar-right-open] [data-dockkit-host="dock"]{animation:dsh-appearance-popup-in .16s linear .12s both}@keyframes dsh-appearance-popup-in{from{opacity:0}to{opacity:1}}@media(prefers-reduced-motion:reduce){html[data-dsh-popup-sync="true"] [data-sidebar-right-panel],html[data-dsh-popup-sync="true"] [data-sidebar-right-panel="push"]{transition:none}html[data-dsh-popup-sync="true"][data-dsh-popup-motion="true"] [data-sidebar-right-panel="push"][data-sidebar-right-open] [data-dockkit-host="dock"]{animation:none}}`
403
+ // —— 主面板卡片(插件页 / 自动化任务页 …)——
404
+ // 官方只有会话页自带卡片;其它 main 面板(插件、自动化任务,以及以后新增的)是整列铺满。
405
+ // 这里给它们套一个与会话区**共用同一套变量**的毛玻璃容器:底色/透明度 → --dsh-conv-bg,
406
+ // 毛玻璃强度 → --dsh-conv-blur,宽度 → --dsh-conversation-width,圆角 20px 与会话卡片一致。
407
+ // 只改外观、不接管滚动:卡片自己 `overflow:hidden` 只负责裁圆角,页面内部原有的滚动容器
408
+ // (以及它的 sticky 页头)保持原样。
409
+ // 打标由 tagMainPanels() 完成(`.centerCol` 下非会话的直接子元素),不依赖 hashed 类名,
410
+ // 以后新增主面板自动生效;卸载时属性与样式表一起清掉。
411
+ const PAGE_STYLE = `[class*=centerCol] [data-dsh-appearance-page]{position:relative;width:min(var(--dsh-conversation-width,760px),calc(100% - 48px))!important;max-width:var(--dsh-conversation-width,760px)!important;margin:24px auto!important;height:calc(100% - 48px)!important;max-height:calc(100% - 48px)!important;min-height:0!important;box-sizing:border-box!important;border-radius:20px!important;overflow:auto!important;background:var(--dsh-conv-bg)!important;backdrop-filter:blur(var(--dsh-conv-blur))!important;-webkit-backdrop-filter:blur(var(--dsh-conv-blur))!important}[class*=centerCol] [data-dsh-appearance-page][data-testid="task-manager-page"]{overflow:hidden!important}[class*=centerCol] [data-dsh-appearance-page][data-testid="task-manager-page"] aside[class*="detail"]{background:color-mix(in srgb,var(--dsw-alias-label-primary) 4%,transparent)!important}`
412
+ // DSH 自带弹层是「半透明材质 + backdrop-filter」(data-menu-material="translucent")。
413
+ // 壁纸在背后时正文会透出来、糊成一片;这里把材质底改成不透明,并关掉那层模糊。
414
+ // 只动 data-menu-material 的材质层,不碰弹层自身的布局与层级。
415
+ const MENU_STYLE = `[data-menu-material] > [aria-hidden="true"]{background:var(--dsw-alias-bg-module-platform,#fcfdfe)!important;backdrop-filter:none!important;-webkit-backdrop-filter:none!important}[data-menu-material] > [aria-hidden="true"]{opacity:1!important}`
416
+
417
+ const STYLE = `.dsh-appearance-bg{position:fixed;inset:-80px;z-index:0;pointer-events:none;will-change:transform;background-image:var(--dsh-bg-image);background-size:var(--dsh-bg-size);background-repeat:var(--dsh-bg-repeat);background-position:center;opacity:var(--dsh-bg-opacity);filter:blur(var(--dsh-bg-blur));transition:transform .12s var(--dsh-parallax-easing)}[class*=frame]{position:relative;z-index:2;background:transparent!important}[class*=centerCol],[class*=sidebarCol]{background:transparent!important}[class*=centerCol] [data-phase="hero"],[class*=centerCol] [data-phase="active"]{width:min(var(--dsh-conversation-width,760px),calc(100% - 48px));max-width:var(--dsh-conversation-width,760px);margin:24px auto;min-height:0;border-radius:20px;box-sizing:border-box;overflow:hidden}[class*=centerCol] [data-phase="active"]{height:calc(100% - 48px)!important;max-height:calc(100% - 48px)!important;min-height:0!important;display:flex!important;flex:1 1 auto!important;flex-direction:column!important;background:var(--dsh-conv-bg)!important;overflow:visible!important;backdrop-filter:blur(var(--dsh-conv-blur));-webkit-backdrop-filter:blur(var(--dsh-conv-blur));will-change:backdrop-filter;contain:layout}[class*=centerCol] [data-phase="active"] [data-conversation-scroll]{display:grid!important;grid-template-rows:minmax(0,1fr) auto!important;min-height:0!important;overflow:visible!important}[class*=centerCol] [data-phase="active"] [data-conversation-scroll] [data-dsh-appearance-session]{grid-row:1;display:flex!important;flex-direction:column!important;min-width:0!important;min-height:0!important;overflow-y:auto!important;overflow-x:hidden!important}[class*=centerCol] [data-phase="active"] [data-conversation-scroll] [data-dsh-appearance-seat]{grid-row:2;position:relative!important;z-index:20!important;display:flex!important;flex-direction:column!important;flex:none!important;min-width:0!important;max-width:100%!important;overflow:visible!important}[class*=centerCol] [class*=composerSeat]{width:100%!important;max-width:100%!important;border:none!important;box-shadow:none!important;background:transparent!important}[data-dsh-appearance-composer]{background:var(--dsh-composer-bg)!important;backdrop-filter:blur(var(--dsh-composer-blur));-webkit-backdrop-filter:blur(var(--dsh-composer-blur));will-change:backdrop-filter;contain:layout;border:var(--dsh-composer-border)!important;border-radius:var(--dsh-composer-radius)!important;overflow:visible!important}/* DSH 0.2.0:设置面板由 SettingsPanel 用 createPortal(..., document.body) 渲染(0.1.5 是内联在
418
+ sidebar.settings 槽里),所以原来那条 [data-slot='sidebar.settings'] [role='dialog'] 再也选不中它
419
+ —— 玻璃效果整个失效。官方在面板元素上留了稳定标记 data-shortcut-modal="settings"
420
+ (settings.open 快捷键的 modals: ["settings"] 就是它)。新旧两种选择器都留着;
421
+ --dsh-settings-bg/blur 写在 <html> 上,body 下的 panel 照样继承得到。 */
422
+ [data-slot='sidebar.settings'] [role='dialog'],[data-shortcut-modal='settings']{background:var(--dsh-settings-bg)!important;backdrop-filter:blur(var(--dsh-settings-blur));-webkit-backdrop-filter:blur(var(--dsh-settings-blur))}.dsh-appearance-settings{max-width:780px;color:var(--dsw-alias-label-primary)}.dsh-appearance-settings h2{font-size:18px;margin:0 0 10px}.dsh-appearance-settings h3{font-size:13px;margin:18px 0 6px;color:var(--dsw-alias-label-secondary)}.dsh-appearance-settings{max-width:780px;color:var(--dsw-alias-label-primary)}
423
+ .dsh-appearance-settings h2{font-size:18px;margin:0 0 10px;letter-spacing:.01em}
424
+ .dsh-appearance-settings h3{font-size:12px;margin:22px 0 6px;padding-top:14px;border-top:1px solid var(--dsw-alias-border-l2);color:var(--dsw-alias-label-secondary);font-weight:600;letter-spacing:.04em}
425
+ .dsh-appearance-settings h3:first-of-type{margin-top:12px;padding-top:0;border-top:none}
426
+ .dsh-appearance-row{display:flex;align-items:center;justify-content:space-between;gap:16px;min-height:38px;padding:5px 0}
427
+ .dsh-appearance-row+.dsh-appearance-row{border-top:1px solid color-mix(in srgb,var(--dsw-alias-border-l2) 60%,transparent)}
428
+ .dsh-appearance-label{flex:0 0 auto;max-width:56%;font-size:13px;line-height:20px;color:var(--dsw-alias-label-primary)}
429
+ .dsh-appearance-control{display:flex;align-items:center;justify-content:flex-end;gap:10px;flex:1 1 auto;min-width:0}
430
+ .dsh-appearance-value{flex:none;min-width:46px;padding:2px 7px;border-radius:999px;background:color-mix(in srgb,var(--dsw-alias-label-primary) 7%,transparent);text-align:center;font-size:11px;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-secondary)}
431
+ .dsh-appearance-range{appearance:none;-webkit-appearance:none;flex:1 1 auto;min-width:90px;height:18px;margin:0;background:transparent;cursor:pointer}
432
+ .dsh-appearance-range::-webkit-slider-runnable-track{height:4px;border-radius:999px;background:color-mix(in srgb,var(--dsw-alias-label-primary) 16%,transparent)}
433
+ .dsh-appearance-range::-webkit-slider-thumb{appearance:none;-webkit-appearance:none;width:14px;height:14px;margin-top:-5px;border-radius:50%;border:2px solid var(--dsw-alias-brand-primary,#1570ef);background:var(--dsw-alias-bg-module-platform,#fff);box-shadow:0 1px 3px rgba(0,0,0,.22);transition:transform .12s ease,box-shadow .12s ease}
434
+ .dsh-appearance-range:hover::-webkit-slider-thumb{transform:scale(1.08)}
435
+ .dsh-appearance-range:active::-webkit-slider-thumb{transform:scale(1.16)}
436
+ .dsh-appearance-range:focus-visible::-webkit-slider-thumb{box-shadow:0 0 0 4px color-mix(in srgb,var(--dsw-alias-brand-primary,#1570ef) 26%,transparent)}
437
+ .dsh-appearance-range::-moz-range-track{height:4px;border-radius:999px;background:color-mix(in srgb,var(--dsw-alias-label-primary) 16%,transparent)}
438
+ .dsh-appearance-range::-moz-range-thumb{width:12px;height:12px;border-radius:50%;border:2px solid var(--dsw-alias-brand-primary,#1570ef);background:var(--dsw-alias-bg-module-platform,#fff)}
439
+ .dsh-appearance-select{position:relative;display:flex;align-items:center;flex:1 1 auto;min-width:0;max-width:260px}
440
+ .dsh-appearance-select select{appearance:none;-webkit-appearance:none;width:100%;height:30px;padding:0 28px 0 11px;border:1px solid var(--dsw-alias-border-l2);border-radius:9px;background:var(--dsw-alias-bg-module-platform,#fff);color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;line-height:28px;text-overflow:ellipsis;cursor:pointer;transition:border-color .15s ease,box-shadow .15s ease,background .15s ease}
441
+ .dsh-appearance-select::after{content:'';position:absolute;right:11px;top:50%;width:6px;height:6px;margin-top:-5px;border-right:1.5px solid var(--dsw-alias-label-secondary);border-bottom:1.5px solid var(--dsw-alias-label-secondary);transform:rotate(45deg);pointer-events:none;opacity:.8}
442
+ .dsh-appearance-select:hover select{border-color:color-mix(in srgb,var(--dsw-alias-label-primary) 26%,transparent)}
443
+ .dsh-appearance-select select:focus-visible{outline:none;border-color:var(--dsw-alias-brand-primary,#1570ef);box-shadow:0 0 0 3px color-mix(in srgb,var(--dsw-alias-brand-primary,#1570ef) 24%,transparent)}
444
+ .dsh-appearance-color{position:relative;display:inline-flex;width:34px;height:30px;flex:none;border:1px solid var(--dsw-alias-border-l2);border-radius:9px;padding:2px;background:var(--dsw-alias-bg-module-platform,#fff);cursor:pointer;transition:border-color .15s ease,box-shadow .15s ease}
445
+ .dsh-appearance-color:hover{border-color:color-mix(in srgb,var(--dsw-alias-label-primary) 26%,transparent)}
446
+ .dsh-appearance-color input[type=color]{width:100%;height:100%;padding:0;border:none;border-radius:6px;background:transparent;cursor:pointer}
447
+ .dsh-appearance-color input[type=color]::-webkit-color-swatch-wrapper{padding:0}
448
+ .dsh-appearance-color input[type=color]::-webkit-color-swatch{border:none;border-radius:6px}
449
+ .dsh-appearance-color input[type=color]:focus-visible{outline:none;box-shadow:0 0 0 3px color-mix(in srgb,var(--dsw-alias-brand-primary,#1570ef) 24%,transparent)}
450
+ .dsh-appearance-switch{position:relative;display:inline-flex;width:38px;height:22px;flex:none;cursor:pointer}
451
+ .dsh-appearance-switch input{position:absolute;inset:0;margin:0;opacity:0;cursor:pointer}
452
+ .dsh-appearance-switch i{position:absolute;inset:0;border-radius:999px;background:color-mix(in srgb,var(--dsw-alias-label-primary) 18%,transparent);transition:background .18s ease}
453
+ .dsh-appearance-switch i::after{content:'';position:absolute;top:2px;left:2px;width:18px;height:18px;border-radius:50%;background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.28);transition:transform .18s cubic-bezier(.4,0,.2,1)}
454
+ .dsh-appearance-switch input:checked+i{background:var(--dsw-alias-brand-primary,#1570ef)}
455
+ .dsh-appearance-switch input:checked+i::after{transform:translateX(16px)}
456
+ .dsh-appearance-switch input:focus-visible+i{box-shadow:0 0 0 3px color-mix(in srgb,var(--dsw-alias-brand-primary,#1570ef) 24%,transparent)}
457
+ .dsh-appearance-switch input:active+i::after{width:19px}
458
+ .dsh-appearance-btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;flex:none;height:30px;padding:0 12px;border:1px solid var(--dsw-alias-border-l2);border-radius:9px;background:var(--dsw-alias-bg-module-platform,#fff);color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;font-weight:500;white-space:nowrap;cursor:pointer;transition:background .15s ease,border-color .15s ease,box-shadow .15s ease,transform .08s ease}
459
+ .dsh-appearance-btn:hover{background:var(--dsw-alias-interactive-bg-hover,color-mix(in srgb,var(--dsw-alias-label-primary) 7%,transparent));border-color:color-mix(in srgb,var(--dsw-alias-label-primary) 26%,transparent)}
460
+ .dsh-appearance-btn:focus-visible{outline:none;border-color:var(--dsw-alias-brand-primary,#1570ef);box-shadow:0 0 0 3px color-mix(in srgb,var(--dsw-alias-brand-primary,#1570ef) 24%,transparent)}
461
+ .dsh-appearance-btn:active{transform:translateY(.5px)}
462
+ .dsh-appearance-btn:disabled{opacity:.6;cursor:progress}
463
+ .dsh-appearance-btn-icon{flex:none;display:block;opacity:.85}
464
+ .dsh-appearance-hint{margin:6px 0 2px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary)}
465
+ .dsh-appearance-notice{margin-top:6px;padding:7px 10px;border-radius:9px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-primary);background:color-mix(in srgb,var(--dsw-alias-brand-primary,#1570ef) 10%,transparent);border:1px solid color-mix(in srgb,var(--dsw-alias-brand-primary,#1570ef) 26%,transparent)}
466
+ .dsh-appearance-previews{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-top:8px}.dsh-appearance-preview{position:relative;height:210px;border-radius:12px;overflow:hidden;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1)}.dsh-preview-bg{position:absolute;inset:0;background-image:var(--dsh-bg-image);background-size:var(--dsh-bg-size);background-repeat:var(--dsh-bg-repeat);background-position:center;opacity:var(--dsh-bg-opacity)}.dsh-preview-conv{position:absolute;inset:14px;border-radius:12px;padding:10px;display:flex;flex-direction:column;background:transparent}.dsh-preview-conv.active{background:var(--dsh-conv-bg);backdrop-filter:blur(var(--dsh-conv-blur));-webkit-backdrop-filter:blur(var(--dsh-conv-blur))}.dsh-preview-msgs{flex:1;display:flex;flex-direction:column;gap:6px;overflow:hidden}.dsh-preview-msg{align-self:flex-start;max-width:80%;background:var(--dsw-alias-bg-layer-2);border-radius:8px;padding:6px 10px;font-size:11px;color:var(--dsw-alias-label-primary)}.dsh-preview-msg.self{align-self:flex-end;background:var(--dsw-alias-brand-primary);color:var(--dsw-alias-label-inverse, #fff)}.dsh-preview-chat{margin-top:10px;background:var(--dsh-composer-bg);backdrop-filter:blur(var(--dsh-composer-blur));-webkit-backdrop-filter:blur(var(--dsh-composer-blur));border:var(--dsh-composer-border);border-radius:var(--dsh-composer-radius);padding:9px 12px;font-size:11px;color:var(--dsw-alias-label-primary)}@media(max-width:640px){.dsh-appearance-previews{grid-template-columns:1fr}}`
467
+
468
+ const appearanceRootStyles = new Map()
469
+ let appearanceThemeDisposer = null
470
+
471
+ function applyBackground(s, theme) {
472
+ const root = document.documentElement
473
+ const set = (k, v) => {
474
+ const appliedValue = String(v)
475
+ if (!appearanceRootStyles.has(k)) appearanceRootStyles.set(k, [root.style.getPropertyValue(k), root.style.getPropertyPriority(k), appliedValue])
476
+ else appearanceRootStyles.get(k)[2] = appliedValue
477
+ root.style.setProperty(k, appliedValue)
478
+ }
479
+ const size = s.bgSize === 'tile' ? 'auto' : s.bgSize === 'stretch' ? '100% 100%' : s.bgSize === 'contain' ? 'contain' : s.bgSize || 'cover'
480
+ const repeat = s.bgSize === 'tile' ? 'repeat' : 'no-repeat'
481
+ const bgUrl = s.bgImage ? `url("${s.bgImage}")` : ''
482
+ // Once the real wallpaper layer exists, drop the early full-opacity <html> wallpaper
483
+ // so lowering the wallpaper transparency reveals a plain base, not a second image copy.
484
+ if (document.querySelector('.dsh-appearance-bg')) {
485
+ document.getElementById('dsh-ui-appearance-preload')?.remove()
486
+ // 移除 host 首帧注入的 <style>(含标记),避免它盖住壁纸透明度/白底效果。
487
+ document.querySelectorAll('style').forEach((el) => { if (el.textContent && el.textContent.includes('dsh-ui-appearance-head')) el.remove() })
488
+ }
489
+ // 遮罩层背景跟随 --dsh-wash-bg(=遮罩颜色+浓度);无壁纸时透明。
490
+ const washEl = document.querySelector('.dsh-appearance-wash')
491
+ if (washEl) washEl.style.background = bgUrl ? 'var(--dsh-wash-bg)' : 'transparent'
492
+ let el = document.getElementById('dsh-ui-appearance-bg-css')
493
+ if (!el) { el = document.createElement('style'); el.id = 'dsh-ui-appearance-bg-css'; document.head.appendChild(el) }
494
+ // Base under a (possibly fading) wallpaper: while a wallpaper is active, faded area is a plain white base.
495
+ const baseCss = bgUrl ? 'html{background-color:#ffffff!important}body{background:#ffffff!important}' : 'html, body { background-color: transparent !important; } body { background: transparent !important; }'
496
+ // 侧边栏滚动渐隐条:0.2.2 起官方把它从 workspace 的 treeBody 里挪到了侧栏骨架自己的
497
+ // scrollRegion 底部,类名也从 `..._fade_...` 变成 `..._scrollFade_...`(含大写 F),
498
+ // 旧规则整个失效。该条的底色是**不透明**的 --dsw-specific-sidebar-fill,而本插件把
499
+ // 侧栏做成了半透明,于是在壁纸上露出一条 24px 的白条。这里一并清掉新位置。
500
+ el.textContent = baseCss + ' [class*="frame"], [class*="centerCol"] { background: transparent !important; } [role="dialog"]{z-index:10!important} [class*="sidebarCol"] [class*="treeBody"] [class*="fade"], [class*="sidebarCol"] [class*="scrollFade"] { background: none !important; }'
501
+ const tokens = {}
502
+ if (bgUrl) {
503
+ tokens['--dsw-alias-bg-base'] = { light: 'rgba(0,0,0,0)', dark: 'rgba(0,0,0,0)' }
504
+ }
505
+ try {
506
+ appearanceThemeDisposer?.()
507
+ appearanceThemeDisposer = typeof theme?.overrideTokens === 'function' ? theme.overrideTokens(NS, tokens) : null
508
+ } catch { appearanceThemeDisposer = null }
509
+ document.querySelectorAll('[class*="sidebarCol"], [class*="sidebarCol"] [data-slot="sidebar"] > [class*="root"]').forEach((sidebar) => {
510
+ sidebarStyleElements.add(sidebar)
511
+ rememberStyle(sidebarStyleState, sidebar, ['background', 'position', 'width', 'min-width', 'height', 'overflow', 'z-index'])
512
+ const opacity = Math.max(0, Math.min(1, Number.isFinite(Number(s.sidebarOpacity)) ? Number(s.sidebarOpacity) : 0.85)) * 100
513
+ const fill = `color-mix(in srgb,var(--dsw-specific-sidebar-fill) ${opacity}%,transparent)`
514
+ const ownsFill = String(sidebar.className || '').includes('root')
515
+ sidebar.style.setProperty('background', ownsFill ? fill : 'transparent', 'important')
516
+ })
517
+ document.querySelectorAll('button[class*="newSession"]').forEach((el) => {
518
+ sidebarStyleElements.add(el)
519
+ rememberStyle(sidebarStyleState, el, ['background'])
520
+ const opacity = Math.max(0, Math.min(1, Number.isFinite(Number(s.sidebarOpacity)) ? Number(s.sidebarOpacity) : 0.85)) * 100
521
+ const fill = `color-mix(in srgb,var(--dsw-specific-sidebar-fill) ${opacity}%,transparent)`
522
+ el.style.setProperty('background', fill, 'important')
523
+ })
524
+
525
+ const autoHide = !!s.sidebarAutoHide
526
+ const frameRoot = document.querySelector('[class*="frame"]')
527
+ if (frameRoot) {
528
+ rememberStyle(frameStyleState, frameRoot, ['grid-template-columns', 'transition'])
529
+ frameRoot.setAttribute('data-dsh-auto-hide', String(autoHide))
530
+ const sideRootEl = document.querySelector('[class*="sidebarCol"] [data-slot="sidebar"] > [class*="root"]')
531
+ const sideWidth = sideRootEl ? Math.round(sideRootEl.getBoundingClientRect().width) : 0
532
+ const wideW = sideWidth > 50 ? sideWidth : (sidebarWideWidth > 50 ? sidebarWideWidth : 280)
533
+ syncFrameColumns(frameRoot, autoHide, wideW, instantSidebarExpand)
534
+ }
535
+ applySidebarColumns(s)
536
+ tagMainPanels()
537
+
538
+ const bgDiv = document.querySelector('.dsh-appearance-bg')
539
+ if (bgDiv) {
540
+ bgDiv.style.backgroundImage = bgUrl || 'none'
541
+ bgDiv.style.backgroundSize = size
542
+ bgDiv.style.backgroundRepeat = repeat
543
+ bgDiv.style.backgroundPosition = 'center'
544
+ bgDiv.style.display = bgUrl ? 'block' : 'none'
545
+ }
546
+ set('--dsh-bg-image', bgUrl || 'none'); set('--dsh-bg-size', size); set('--dsh-bg-repeat', repeat)
547
+ set('--dsh-bg-opacity', s.bgOpacity); set('--dsh-bg-blur', `${s.bgBlur}px`)
548
+ set('--dsh-wash-bg', rgba(s.bgMask, s.bgMaskOpacity))
549
+ set('--dsh-parallax-easing', s.parallaxEasing)
550
+ set('--dsh-conv-bg', s.conversationEnabled ? rgba(s.conversationColor, s.conversationOpacity) : 'transparent'); set('--dsh-conversation-width', `${Math.max(320, Number(s.conversationWidth) || 760)}px`)
551
+ set('--dsh-conv-solid', s.conversationEnabled ? s.conversationColor : 'transparent')
552
+ set('--dsh-conv-blur', s.conversationEnabled ? `${s.conversationBlur}px` : '0px')
553
+ set('--dsh-composer-bg', rgba(s.chatBoxColor, s.chatBoxOpacity)); set('--dsh-composer-blur', `${s.chatBoxBlur}px`); set('--dsh-composer-border', borderValue(s.chatBoxBorder)); set('--dsh-composer-radius', `${s.chatBoxRadius}px`)
554
+ set('--dsh-settings-bg', rgba(s.settingsColor, s.settingsOpacity)); set('--dsh-settings-blur', `${s.settingsBlur}px`); set('--dsh-sidebar-opacity', `${Math.max(0, Math.min(1, Number.isFinite(Number(s.sidebarOpacity)) ? Number(s.sidebarOpacity) : 0.85)) * 100}%`)
555
+ // 文档预览弹窗(0.1.5"弹窗预览")与会话区共享玻璃设置:这里只挂开关和内缩,
556
+ // 底色/透明度/毛玻璃强度全部复用 --dsh-conv-*,不新增一套独立参数。
557
+ document.documentElement.setAttribute('data-dsh-popup-sync', String(s.previewPopupShared !== false))
558
+ set('--dsh-popup-inset', `${Math.max(0, Math.min(48, Number.isFinite(Number(s.previewPopupInset)) ? Number(s.previewPopupInset) : 12))}px`)
559
+ }
560
+
561
+ function LivePreview({ s }) {
562
+ const source = typeof document !== 'undefined' ? document.querySelector('[data-phase="active"]') : null
563
+ const page = source ? source.outerHTML : '<div data-phase="active"><div data-conversation-scroll><div data-slot="conversation.session" data-dsh-appearance-session><div data-variant="think">Think</div></div><div data-composer-seat data-dsh-appearance-seat><div data-dsh-appearance-composer><textarea placeholder="Compose..."></textarea></div></div></div></div>'
564
+ const styles = typeof document !== 'undefined' ? [...document.querySelectorAll('style')].map((el) => el.textContent).join('\n') : ''
565
+ const bg = s.bgImage ? `url("${String(s.bgImage).replace(/"/g, '\\"')}")` : 'none'
566
+ const conv = s.conversationEnabled ? rgba(s.conversationColor, s.conversationOpacity) : 'transparent'
567
+ const composer = rgba(s.chatBoxColor, s.chatBoxOpacity)
568
+ const border = borderValue(s.chatBoxBorder)
569
+ const srcDoc = `<!doctype html><html><head><meta charset="utf-8"><style>${styles}</style><style>
570
+ html,body{margin:0!important;width:100%;height:100%;overflow:hidden!important;background:transparent!important}
571
+ body{font-family:system-ui,sans-serif}
572
+ .dsh-live-page{position:relative;width:100%;height:100%;overflow:hidden;background:transparent}
573
+ .dsh-live-bg{position:absolute;inset:0;background-image:${bg};background-size:${s.bgSize === 'tile' ? 'auto' : s.bgSize === 'stretch' ? '100% 100%' : s.bgSize};background-repeat:${s.bgSize === 'tile' ? 'repeat' : 'no-repeat'};background-position:center;opacity:${s.bgOpacity};filter:blur(${s.bgBlur}px)}
574
+ .dsh-live-center{position:relative;width:100%;height:100%;overflow:hidden;transform-origin:top left}
575
+ .dsh-live-center>[data-phase="active"]{width:calc(100% - 32px)!important;height:calc(100% - 32px)!important;margin:16px!important;padding:10px!important;border-radius:12px!important;box-sizing:border-box!important;background:${conv}!important;backdrop-filter:blur(${s.conversationBlur}px)!important}
576
+ .dsh-live-center [data-composer-seat]{background:transparent!important;border:0!important;box-shadow:none!important;padding:0!important}
577
+ .dsh-live-center [data-dsh-appearance-composer]{background:${composer}!important;border:${border}!important;border-radius:${s.chatBoxRadius}px!important;backdrop-filter:blur(${s.chatBoxBlur}px)!important}
578
+ .dsh-live-center [data-conversation-scroll]{display:grid!important;grid-template-rows:minmax(0,1fr) auto!important;min-height:0!important;overflow:hidden!important}
579
+ .dsh-live-center [data-conversation-scroll] > [data-dsh-appearance-session]{grid-row:1;display:flex!important;flex-direction:column!important;min-height:0!important;overflow-y:auto!important;overflow-x:hidden!important}
580
+ .dsh-live-center [data-conversation-scroll] > [data-dsh-appearance-seat]{grid-row:2;min-height:0!important;overflow:visible!important}
581
+ .dsh-live-center [data-slot="conversation.session"] [data-variant]{flex:0 1 auto!important;height:auto!important;max-height:none!important}
582
+ .dsh-live-center [data-slot="conversation.session"] [data-variant="think"]{display:flex!important;flex:0 1 auto!important;height:auto!important;overflow:visible!important}
583
+ .dsh-live-center [data-slot="conversation.session"] [data-variant="think"] [class*="thinkBody"]{display:block!important;height:auto!important;overflow:visible!important}
584
+ .dsh-live-center .Md3f7G_scroll{overflow-y:auto!important;scrollbar-width:none!important}
585
+ .dsh-live-center .Md3f7G_scroll::-webkit-scrollbar{display:none}
586
+ .dsh-live-center [data-slot="conversation.session"]{pointer-events:none!important}
587
+ </style></head><body><div class="dsh-live-page"><div class="dsh-live-bg"></div><div class="dsh-live-center centerCol">${page}</div></div></body></html>`
588
+ return h('iframe', { className: 'dsh-live-preview', title: '实时网页预览', srcDoc, scrolling: 'no' })
589
+ }
590
+
591
+ function Preview({ mode, s }) {
592
+ return h('div', { className: 'dsh-appearance-preview dsh-live-preview-shell', 'data-preview-mode': mode }, h(LivePreview, { s }))
593
+ }
594
+
595
+ function Panel() {
596
+ const [s, setS] = React.useState(load())
597
+ const [files, setFiles] = React.useState([])
598
+ const [revealing, setRevealing] = React.useState(false)
599
+ const [notice, setNotice] = React.useState('')
600
+ const update = (key, value) => { const next = { ...s, [key]: value }; stateRevision += 1; setS(next); persist(next); current = next; applyBackground(next, window.__dshClientTheme || null) }
601
+ React.useEffect(() => { applyBackground(s, window.__dshClientTheme || null); current = s }, [s])
602
+ // 壁纸名字由宿主给(解码后的原文件名)。兼容旧接口只回 URL 的情况:自己解一次码,
603
+ // 否则中文文件名会显示成 %E5%B0%91%E5%A5%B3 这种样子。
604
+ const normalize = (item) => {
605
+ if (typeof item === 'string') {
606
+ const raw = item.split('/').pop() || item
607
+ return { url: item, name: decodeURIComponent(raw) }
608
+ }
609
+ const url = String(item?.url ?? '')
610
+ const name = item?.name ? String(item.name) : decodeURIComponent(url.split('/').pop() || '')
611
+ return { url, name }
612
+ }
613
+ const refreshFiles = () => fetch('/bg/list')
614
+ .then((r) => r.json())
615
+ .then((list) => { const items = (Array.isArray(list) ? list : []).map(normalize).filter((f) => f.url); setFiles(items); return items })
616
+ .catch(() => [])
617
+ React.useEffect(() => { void refreshFiles() }, [])
618
+ const revealFolder = () => {
619
+ if (revealing) return
620
+ setRevealing(true)
621
+ fetch('/bg/reveal', { method: 'POST' })
622
+ .then((r) => r.json())
623
+ .then((x) => { setNotice(x && x.opened ? '已在文件管理器中打开壁纸文件夹' : '打不开文件夹,请手动打开 dsh-ui-appearance 的 assets/backgrounds'); return refreshFiles() })
624
+ .catch(() => setNotice('打不开文件夹,请手动打开 dsh-ui-appearance 的 assets/backgrounds'))
625
+ .finally(() => { setRevealing(false); setTimeout(() => setNotice(''), 4000) })
626
+ }
627
+ // 选中的壁纸可能已经不在文件夹里(手工删了、换过机器):下拉框仍要能显示它。
628
+ const missing = s.bgImage && !files.some((f) => f.url === s.bgImage) ? normalize(s.bgImage) : null
629
+ const row = (label, control) => h('div', { className: 'dsh-appearance-row' }, h('span', { className: 'dsh-appearance-label' }, label), h('div', { className: 'dsh-appearance-control' }, control))
630
+ const slider = (label, key, min, max, scale, unit) => row(label, [
631
+ h('input', { key: 'in', className: 'dsh-appearance-range', type: 'range', min, max, step: 1, value: s[key] * scale, onChange: (e) => update(key, Number(e.target.value) / scale) }),
632
+ h('span', { key: 'v', className: 'dsh-appearance-value' }, `${Math.round(s[key] * scale)}${unit}`),
633
+ ])
634
+ const colorRow = (label, key) => row(label, h('label', { className: 'dsh-appearance-color' }, h('input', { type: 'color', value: s[key], onChange: (e) => update(key, e.target.value) })))
635
+ const selectRow = (label, key, options) => row(label, h('span', { className: 'dsh-appearance-select' }, h('select', { value: s[key], onChange: (e) => update(key, e.target.value) }, options.map((o) => h('option', { key: o.value, value: o.value }, o.label)))))
636
+ const checkRow = (label, key) => row(label, h('label', { className: 'dsh-appearance-switch' }, h('input', { type: 'checkbox', checked: !!s[key], onChange: (e) => update(key, e.target.checked) }), h('i', { 'aria-hidden': 'true' })))
637
+ const folderIcon = h('svg', { className: 'dsh-appearance-btn-icon', viewBox: '0 0 16 16', width: 15, height: 15, fill: 'none', 'aria-hidden': 'true' },
638
+ h('path', { d: 'M1.9 4.1a1.2 1.2 0 0 1 1.2-1.2h3.1l1.35 1.5h5.5a1.2 1.2 0 0 1 1.2 1.2v6.3a1.2 1.2 0 0 1-1.2 1.2H3.1a1.2 1.2 0 0 1-1.2-1.2V4.1Z', stroke: 'currentColor', strokeWidth: 1.3, strokeLinejoin: 'round' }))
639
+ const wallpaperRow = row('壁纸', [
640
+ h('span', { key: 'sel', className: 'dsh-appearance-select' }, h('select', { value: s.bgImage, onChange: (e) => update('bgImage', e.target.value) },
641
+ h('option', { value: '' }, '不使用壁纸'),
642
+ files.map((f) => h('option', { key: f.url, value: f.url }, f.name)),
643
+ missing ? h('option', { key: 'missing', value: missing.url }, `${missing.name}(已不在文件夹中)`) : null)),
644
+ h('button', { key: 'btn', type: 'button', className: 'dsh-appearance-btn', onClick: revealFolder, disabled: revealing }, folderIcon, revealing ? '正在打开…' : '壁纸文件夹'),
645
+ ])
646
+ return h('div', { className: 'dsh-appearance-settings' },
647
+ h('h2', null, '外观'),
648
+ h('h3', null, '壁纸背景'),
649
+ wallpaperRow,
650
+ h('div', { className: 'dsh-appearance-hint' }, '把图片放进壁纸文件夹(JPEG / PNG / WebP / GIF,单张不超过 12 MB),它会出现在下拉框里。'),
651
+ notice && h('div', { className: 'dsh-appearance-notice' }, notice),
652
+ selectRow('尺寸模式', 'bgSize', [{ value: 'cover', label: '裁切 Cover' }, { value: 'contain', label: '居中 Contain' }, { value: 'tile', label: '平铺 Tile' }, { value: 'stretch', label: '拉伸 Stretch' }, { value: 'auto', label: '适应 Auto' }]),
653
+ slider('壁纸透明度', 'bgOpacity', 0, 100, 100, '%'),
654
+ slider('壁纸模糊', 'bgBlur', 0, 60, 1, 'px'),
655
+ colorRow('遮罩颜色', 'bgMask'),
656
+ slider('遮罩浓度', 'bgMaskOpacity', 0, 100, 100, '%'),
657
+ h('h3', null, '视差动效'),
658
+ checkRow('启用视差', 'parallaxEnabled'),
659
+ slider('移动幅度', 'parallaxAmplitude', 0, 50, 1, 'px'),
660
+ selectRow('缓动速度', 'parallaxEasing', [{ value: 'ease-out', label: '缓出' }, { value: 'ease-in', label: '缓入' }, { value: 'ease-in-out', label: '缓入缓出' }]),
661
+ h('h3', null, '侧边栏'),
662
+ slider('透明度', 'sidebarOpacity', 0, 100, 100, '%'),
663
+ checkRow('自动隐藏到左侧', 'sidebarAutoHide'),
664
+ checkRow('首次滑入前预热(减少首帧卡顿)', 'prewarmFirstSlide'),
665
+ h('h3', null, '会话对话区'),
666
+ checkRow('启用区分', 'conversationEnabled'),
667
+ slider('透明度', 'conversationOpacity', 0, 100, 100, '%'),
668
+ slider('毛玻璃强度', 'conversationBlur', 0, 60, 1, 'px'),
669
+ colorRow('遮罩颜色', 'conversationColor'),
670
+ slider('对话框宽度', 'conversationWidth', 420, 1200, 1, 'px'),
671
+ checkRow('插件/任务页也用会话卡片', 'pageCard'),
672
+ checkRow('应用到文档预览弹窗', 'previewPopupShared'),
673
+ slider('弹窗外边距(上/下/右)', 'previewPopupInset', 0, 40, 1, 'px'),
674
+ h('h3', null, '聊天框'),
675
+ colorRow('背景颜色', 'chatBoxColor'),
676
+ slider('透明度', 'chatBoxOpacity', 0, 100, 100, '%'),
677
+ selectRow('边框样式', 'chatBoxBorder', [{ value: 'none', label: '无' }, { value: 'thin', label: '细' }, { value: 'thick', label: '粗' }]),
678
+ slider('圆角大小', 'chatBoxRadius', 0, 24, 1, 'px'),
679
+ h('h3', null, '设置面板'),
680
+ slider('透明度', 'settingsOpacity', 0, 100, 100, '%'),
681
+ slider('毛玻璃强度', 'settingsBlur', 0, 60, 1, 'px'),
682
+ colorRow('背景颜色', 'settingsColor'))
683
+
684
+ }
685
+
686
+ function apply(ctx) {
687
+ const slots = ctx.slots
688
+ const theme = ctx.theme
689
+ if (!slots) return
690
+ try { window.__dshClientTheme = theme } catch {}
691
+ ctx.effect(() => {
692
+ let active = true
693
+ applyBackground(current, theme)
694
+ const tag = document.createElement('style'); tag.dataset.pluginCss = NS; tag.textContent = STYLE + MENU_STYLE; document.head.appendChild(tag)
695
+ // 弹窗外观单独一张样式表:与主样式表解耦(主表整段由 STYLE 常量一次性给出,这里不往里
696
+ // 追加任何东西),这条规则也就稳定处在顶层,不会因为主表结构变化而被解析成嵌套规则。
697
+ const popupTag = document.createElement('style'); popupTag.dataset.pluginCss = NS + ':popup'; popupTag.textContent = POPUP_STYLE; document.head.appendChild(popupTag)
698
+ // 主面板卡片单独一张样式表(同 popup 的理由:主样式表一次性给出、不往里追加)。
699
+ const pageTag = document.createElement('style'); pageTag.dataset.pluginCss = NS + ':page'; pageTag.textContent = PAGE_STYLE; document.head.appendChild(pageTag)
700
+ // 右栏容器入场动画的闸门(见 README §3.6):插件第一次应用样式时会把面板从 none
701
+ // 推到 translateX(100%+内缩),如果过渡此刻就已生效,面板会在页面加载时自己滑出去一次。
702
+ // 先禁用过渡,等右栏第一次真正展开(或 3s 超时)再放行。
703
+ try { document.documentElement.setAttribute('data-dsh-popup-anim', 'false') } catch { /* 无 document 时安静 */ }
704
+
705
+ const bg = document.createElement('div'); bg.className = 'dsh-appearance-bg'; document.body.prepend(bg)
706
+ // 遮罩层:整屏盖在壁纸(z-index:0)上方、内容(frame z-index:2)下方;背景=--dsh-wash-bg。
707
+ const wash = document.createElement('div'); wash.className = 'dsh-appearance-wash'
708
+ Object.assign(wash.style, { position: 'fixed', inset: '0', zIndex: '1', pointerEvents: 'none', background: 'var(--dsh-wash-bg)' })
709
+ bg.insertAdjacentElement('afterend', wash)
710
+
711
+ applyBackground(current, theme)
712
+ const preloadTag = document.getElementById('dsh-ui-appearance-preload')
713
+ let preloadProbe = null
714
+ let preloadTimeout = null
715
+ const finishPreload = () => {
716
+ if (!active || !preloadTag || !preloadTag.isConnected || document.getElementById('dsh-ui-appearance-preload') !== preloadTag) return
717
+ preloadTag.remove()
718
+ }
719
+ if (current.bgImage) {
720
+ preloadProbe = new Image()
721
+ preloadProbe.onload = finishPreload
722
+ preloadProbe.onerror = () => { preloadTimeout = setTimeout(finishPreload, 300) }
723
+ preloadProbe.src = current.bgImage
724
+ } else finishPreload()
725
+ // Cold-start self-heal: on a real app start the page can mount before
726
+ // the host plugin's /bg routes are serving (or before the configured
727
+ // image file is reachable), so a one-shot /bg/config fetch would 404
728
+ // and leave the wallpaper blank until a manual refresh. Retry briefly
729
+ // so the background appears as soon as the host is ready.
730
+ let bootTimer = null
731
+ const bootDelay = (ms) => new Promise((resolve) => { bootTimer = setTimeout(resolve, ms) })
732
+ const bootImageReady = (url) => new Promise((resolve) => {
733
+ if (!url) return resolve(true)
734
+ const im = new Image()
735
+ im.onload = () => resolve(true)
736
+ im.onerror = () => resolve(false)
737
+ im.src = url
738
+ })
739
+ const bootPaint = (s) => { applyBackground(s, theme); preloadBackground(s); tagDom() }
740
+ const bootWallpaper = async () => {
741
+ for (let i = 0; i < 48 && active; i++) {
742
+ let reachable = false
743
+ let cfg = null
744
+ try {
745
+ const res = await fetch('/bg/config')
746
+ if (res.ok) { reachable = true; cfg = await res.json() }
747
+ } catch { /* host not ready yet */ }
748
+ if (reachable && cfg && typeof cfg === 'object') {
749
+ current = { ...defaults, ...current, ...cfg }
750
+ try { localStorage.setItem(STORE_KEY, JSON.stringify(current)) } catch {}
751
+ }
752
+ if (!current.bgImage) {
753
+ if (reachable) { bootPaint(current); return } // authoritative: no wallpaper chosen
754
+ await bootDelay(300)
755
+ continue
756
+ }
757
+ bootPaint(current)
758
+ if (await bootImageReady(current.bgImage)) return // image served: background active
759
+ await bootDelay(250)
760
+ }
761
+ }
762
+ void bootWallpaper()
763
+ let frame
764
+ let lastParallax = ''
765
+ const move = (e) => {
766
+ const s = current
767
+ if (!s.parallaxEnabled || !s.bgImage) return
768
+ const x = Math.round((e.clientX / innerWidth - 0.5) * 2 * -s.parallaxAmplitude * 2) / 2
769
+ const y = Math.round((e.clientY / innerHeight - 0.5) * 2 * -s.parallaxAmplitude * 2) / 2
770
+ const next = x + ',' + y
771
+ if (next === lastParallax) return
772
+ lastParallax = next
773
+ cancelAnimationFrame(frame)
774
+ // translate3d 走合成器;值没变就完全不写,避免壁纸层的 backdrop 反复重算。
775
+ frame = requestAnimationFrame(() => { bg.style.transform = 'translate3d(' + x + 'px, ' + y + 'px, 0)' })
776
+ }
777
+ document.addEventListener('mousemove', move)
778
+ // Hover 展开/收起:合并到每帧一次,并且只在"展开状态真的变了"时才写样式。
779
+ // 原来每次 mousemove 都会 syncSidebarRoot → 量一次 root 的 rect + 重写 transition/margin,
780
+ // 也就是每次指针移动都强制一次同步布局;滑入的那 220ms 里就是每帧一次。
781
+ let sidebarHoverFrame = 0
782
+ let sidebarHoverEvent = null
783
+ const applySidebarHover = (e) => {
784
+ const autoHide = !!current.sidebarAutoHide
785
+ document.querySelectorAll('[class*="sidebarCol"]').forEach((sidebar) => {
786
+ if (!autoHide) {
787
+ if (sidebar.getAttribute('data-dsh-sidebar-revealed') !== 'true') {
788
+ sidebar.setAttribute('data-dsh-sidebar-revealed', 'true')
789
+ sidebarRevealed = true
790
+ }
791
+ return
792
+ }
793
+ const root = sidebar.querySelector('[data-slot="sidebar"] > [class*="root"]')
794
+ const target = e.target
795
+ const revealed = e.clientX <= 20 || (root && (() => { const rect = root.getBoundingClientRect(); return rect.width > 0 && e.clientX >= rect.left - 4 && e.clientX <= rect.right + 4 && e.clientY >= rect.top - 8 && e.clientY <= rect.bottom + 8 })()) || !!(root && (root === target || root.contains(target) || root.matches(':hover')))
796
+ sidebarRevealed = revealed
797
+ if (sidebar.getAttribute('data-dsh-sidebar-revealed') === String(revealed)) return
798
+ sidebar.setAttribute('data-dsh-sidebar-revealed', String(revealed))
799
+ enterMotion(260)
800
+ syncSidebarRoot(sidebar, true)
801
+ })
802
+ }
803
+ const sidebarHover = (e) => {
804
+ sidebarHoverEvent = e
805
+ if (sidebarHoverFrame !== 0) return
806
+ sidebarHoverFrame = requestAnimationFrame(() => { sidebarHoverFrame = 0; if (active && sidebarHoverEvent) applySidebarHover(sidebarHoverEvent) })
807
+ }
808
+ document.addEventListener('mousemove', sidebarHover)
809
+ // 静默预热:启动后挑一段空闲时间做,最多试 6 次(DOM 可能还没就绪);用户期间
810
+ // 一旦已经把侧栏展开,prewarmSidebar 自己会放弃。
811
+ let prewarmTimer = null
812
+ let prewarmTries = 0
813
+ const schedulePrewarm = (delay) => {
814
+ if (prewarmTimer !== null) { clearTimeout(prewarmTimer); prewarmTimer = null }
815
+ const run = () => {
816
+ prewarmTimer = null
817
+ if (!active) return
818
+ if (prewarmSidebar()) return
819
+ if (prewarmTries < 6 && !sidebarWarmed) { prewarmTries += 1; schedulePrewarm(900) }
820
+ }
821
+ prewarmTimer = setTimeout(() => {
822
+ // 预热本身要画一帧,别和首屏/首轮渲染抢时间,交给空闲回调。
823
+ if (typeof requestIdleCallback === 'function') requestIdleCallback(run, { timeout: 1500 })
824
+ else run()
825
+ }, delay)
826
+ }
827
+ schedulePrewarm(1200)
828
+ let conversationScrollFrame
829
+ let conversationScrollElement = null
830
+ let conversationScrollListener = null
831
+ let conversationScrollHost = null
832
+ let conversationScrollHostPosition = null
833
+ let conversationRoot = null
834
+ let latestButton = null
835
+ let followConversation = true
836
+ // 气泡按钮的位置原来是每帧量 offsetWidth/clientWidth/offsetHeight 再写样式(一次强制布局),
837
+ // 而它只在容器尺寸或输入框高度变化时才会变。改成量一次、变了才写。
838
+ let latestMetrics = { right: -1, bottom: -1 }
839
+ let scrollIdleTimer = 0
840
+ const measureLatestButton = (scroll) => {
841
+ if (!latestButton || !scroll) return
842
+ const right = Math.max(8, scroll.offsetWidth - scroll.clientWidth + 8)
843
+ const seat = conversationScrollHost ? conversationScrollHost.querySelector('[data-composer-seat]') : null
844
+ const bottom = (seat ? seat.offsetHeight : 0) + 8
845
+ if (right === latestMetrics.right && bottom === latestMetrics.bottom) return
846
+ latestMetrics = { right, bottom }
847
+ latestButton.style.right = right + 'px'
848
+ latestButton.style.bottom = bottom + 'px'
849
+ }
850
+ const scrollConversationToLatest = (force = false) => {
851
+ const active = document.querySelector('[data-phase="active"]')
852
+ if (!active) return
853
+ if (active !== conversationRoot) {
854
+ conversationRoot = active
855
+ followConversation = true
856
+ conversationScrollElement = null
857
+ }
858
+
859
+
860
+
861
+ const scrollBody = active.querySelector('[data-conversation-scroll]')
862
+ const scroll = scrollBody && (scrollBody.querySelector(':scope > [data-slot="conversation.session"]') || scrollBody.querySelector('[data-slot="conversation.session"]'))
863
+
864
+ if (!scroll) return
865
+ if (scroll !== conversationScrollElement) {
866
+ // 只在换滚动容器时写:原来每次同步都写,等于每帧制造一次样式失效。
867
+ scroll.style.setProperty('overflow-y', 'auto', 'important')
868
+ scroll.style.setProperty('overflow-x', 'hidden', 'important')
869
+ if (scrollBody) scrollBody.style.setProperty('overflow', 'hidden', 'important')
870
+ if (conversationScrollElement && conversationScrollListener) conversationScrollElement.removeEventListener('scroll', conversationScrollListener)
871
+ conversationScrollElement = scroll
872
+ conversationScrollListener = () => {
873
+ const distance = scroll.scrollHeight - scroll.clientHeight - scroll.scrollTop
874
+ followConversation = distance <= 24
875
+ if (latestButton) latestButton.hidden = distance <= 24
876
+ }
877
+ scroll.addEventListener('scroll', conversationScrollListener, { passive: true })
878
+ }
879
+
880
+ const scrollHost = scroll.parentElement || active
881
+ if (conversationScrollHost !== scrollHost) {
882
+ if (conversationScrollHost && conversationScrollHostPosition !== null) { if (conversationScrollHostPosition[0]) conversationScrollHost.style.setProperty('position', conversationScrollHostPosition[0], conversationScrollHostPosition[1]); else conversationScrollHost.style.removeProperty('position') }
883
+ conversationScrollHost = scrollHost
884
+ conversationScrollHostPosition = [scrollHost.style.getPropertyValue('position'), scrollHost.style.getPropertyPriority('position')]
885
+ scrollHost.style.setProperty('position', 'relative')
886
+ }
887
+ if (latestButton && latestButton.parentElement !== scrollHost) {
888
+ scrollHost.style.setProperty('position', 'relative')
889
+ scrollHost.appendChild(latestButton)
890
+ }
891
+ if (followConversation || force) scroll.scrollTop = scroll.scrollHeight
892
+ if (latestButton) latestButton.hidden = scroll.scrollHeight - scroll.clientHeight - scroll.scrollTop <= 24
893
+ // 首次(还没量过)补量一次;之后只在全量同步/窗口 resize 时重算。
894
+ if (latestButton && latestMetrics.right < 0) measureLatestButton(scroll)
895
+ }
896
+ const scheduleConversationScroll = () => {
897
+ cancelAnimationFrame(conversationScrollFrame)
898
+ conversationScrollFrame = requestAnimationFrame(() => {
899
+ scrollConversationToLatest()
900
+ // 第二帧:等流式内容完成布局后再贴到底,思考过程才跟得上。
901
+ requestAnimationFrame(() => scrollConversationToLatest())
902
+ })
903
+ }
904
+ const ensureLatestButton = () => {
905
+ const active = document.querySelector('[data-phase="active"]')
906
+ if (!active) return
907
+ if (latestButton && latestButton.isConnected && latestButton.closest('[data-phase="active"]') === active) return
908
+ latestButton?.remove()
909
+ latestButton = document.createElement('button')
910
+ latestButton.type = 'button'
911
+ latestButton.textContent = '↓'
912
+ latestButton.dataset.dshLatestButton = 'true'
913
+ latestButton.title = '返回最新对话'
914
+ latestButton.setAttribute('aria-label', '返回最新对话')
915
+ latestButton.hidden = true
916
+ Object.assign(latestButton.style, { position: 'absolute', right: '20px', bottom: '20px', zIndex: '20', width: '36px', height: '36px', border: '1px solid rgba(120,130,145,.35)', borderRadius: '50%', background: 'rgba(255,255,255,.92)', color: 'inherit', boxShadow: '0 4px 14px rgba(0,0,0,.16)', cursor: 'pointer', fontSize: '20px', lineHeight: '1' })
917
+ latestButton.addEventListener('click', () => { followConversation = true; scrollConversationToLatest(true) })
918
+ active.appendChild(latestButton)
919
+ }
920
+ const tagDom = () => {
921
+ document.querySelectorAll('[data-phase="active"] button:not([data-dsh-latest-button])').forEach((button) => {
922
+ const label = `${button.getAttribute('aria-label') || ''} ${button.getAttribute('title') || ''} ${button.textContent || ''}`.toLowerCase()
923
+ if (/bottom|latest|scroll/.test(label)) button.style.setProperty('display', 'none', 'important')
924
+ })
925
+
926
+ const autoHideFrame = document.querySelector('[class*="frame"]')
927
+
928
+ const autoHide = !!current.sidebarAutoHide
929
+ /* 0.2.0 有两个官方开关:侧栏自带的那个(Windows 下被钉进标题栏左上角),以及整列
930
+ 隐藏时框架 `shell.leading` 座里的 HeaderLeadingControls(没有 `toggle` 类名、
931
+ 也不在 sidebarCol 内)。两个都同步标签;leading 座里只认第一个按钮,且先排除
932
+ "新建会话",避免把标签贴到隔壁按钮上。 */
933
+ const applyToggleLabel = (button) => {
934
+ if (!button) return
935
+ button.setAttribute('aria-label', autoHide ? '取消隐藏侧边栏' : '隐藏侧边栏')
936
+ button.setAttribute('aria-pressed', String(autoHide))
937
+ }
938
+ applyToggleLabel(document.querySelector('[class*="sidebarCol"] button[class*="toggle"]'))
939
+ const leadingSeat = document.querySelector('[class*="leadingSeat"]')
940
+ const leadingButton = leadingSeat ? leadingSeat.querySelector('[class*="controls"] button') : null
941
+ if (leadingButton && !/新建|新会话|new session/i.test(`${leadingButton.getAttribute('aria-label') || ''} ${leadingButton.getAttribute('title') || ''}`)) applyToggleLabel(leadingButton)
942
+ if (autoHideFrame) autoHideFrame.setAttribute('data-dsh-auto-hide', String(autoHide));
943
+ document.querySelectorAll('[class*="sidebarCol"]').forEach((sidebar) => {
944
+ rememberStyle(sidebarStyleState, sidebar, ['background', 'position', 'width', 'min-width', 'height', 'overflow', 'z-index'])
945
+ sidebar.setAttribute('data-dsh-auto-hide', String(autoHide))
946
+ if (!autoHide) sidebar.setAttribute('data-dsh-sidebar-revealed', 'true')
947
+ else sidebar.setAttribute('data-dsh-sidebar-revealed', String(sidebarRevealed))
948
+ syncSidebarRoot(sidebar, autoHide)
949
+ })
950
+
951
+ const activePhase = document.querySelector('[data-phase="active"]')
952
+ const heroPhase = document.querySelector('[data-phase="hero"]')
953
+ const settlingPhase = document.querySelector('[data-phase="settling"]')
954
+ const seat = activePhase?.querySelector('[data-composer-seat]') || heroPhase?.querySelector('[data-composer-seat]') || settlingPhase?.querySelector('[data-composer-seat]') || document.querySelector('[data-composer-seat]')
955
+ document.querySelectorAll('[data-dsh-appearance-session], [data-dsh-appearance-seat]').forEach((el) => {
956
+ el.removeAttribute('data-dsh-appearance-session')
957
+ el.removeAttribute('data-dsh-appearance-seat')
958
+ })
959
+ const scrollBody = seat?.closest('[data-conversation-scroll]')
960
+ const session = scrollBody?.querySelector('[data-slot="conversation.session"]')
961
+ if (session) session.setAttribute('data-dsh-appearance-session', '')
962
+ if (seat && scrollBody && seat.parentElement === scrollBody) seat.setAttribute('data-dsh-appearance-seat', '')
963
+ const editable = seat ? seat.querySelector('textarea,[contenteditable=true]') : null
964
+ let target = editable ? editable.parentElement : null
965
+ if (target) {
966
+ for (let i = 0; i < 6 && target; i++) {
967
+ const cls = String(target.className || '')
968
+ if (cls.includes('card')) break
969
+ target = target.parentElement
970
+ }
971
+ if (target && target !== editable) target.setAttribute('data-dsh-appearance-composer', '')
972
+ }
973
+ document.querySelectorAll('[data-dsh-appearance-composer]').forEach((el) => {
974
+ if (el !== target) el.removeAttribute('data-dsh-appearance-composer')
975
+ })
976
+ tagMainPanels()
977
+ }
978
+ tagDom()
979
+ let sidebarRestoreFrame
980
+ ensureLatestButton()
981
+ scheduleConversationScroll()
982
+ const sidebarToggleClick = (e) => {
983
+ const path = typeof e.composedPath === 'function' ? e.composedPath() : []
984
+ const button = path.find((node) => node && node.nodeType === 1 && node.matches && node.matches('[class*="sidebarCol"] button[class*="toggle"]')) || (e.target && e.target.closest ? e.target.closest('[class*="sidebarCol"] button[class*="toggle"]') : null)
985
+ if (!button) return
986
+ if (e.type === 'mousedown' && sidebarPointerHandledAt > 0 && performance.now() - sidebarPointerHandledAt < 500) {
987
+ e.preventDefault()
988
+ e.stopImmediatePropagation()
989
+ return
990
+ }
991
+ if (e.type === 'click' && sidebarPointerHandledAt > 0 && performance.now() - sidebarPointerHandledAt < 500) {
992
+ e.preventDefault()
993
+ e.stopImmediatePropagation()
994
+ return
995
+ }
996
+ if (e.type === 'pointerdown') sidebarPointerHandledAt = performance.now()
997
+ e.preventDefault()
998
+ e.stopImmediatePropagation()
999
+ const wasAutoHide = !!current.sidebarAutoHide
1000
+ const revealedNow = sidebarRevealed
1001
+ const nativeSidebar = document.querySelector('[class*="sidebarCol"] [data-slot="sidebar"] > [class*="root"]')
1002
+ const measuredWidth = nativeSidebar ? nativeSidebar.getBoundingClientRect().width : 0
1003
+ if (measuredWidth > 200) sidebarWideWidth = measuredWidth
1004
+ const frameRoot = document.querySelector('[class*="frame"]')
1005
+ if (wasAutoHide) document.querySelectorAll('[class*="sidebarCol"] [data-slot="sidebar"] > [class*="root"]').forEach((root) => root.style.setProperty('transition', 'margin-left .22s var(--ds-ease-in-out)', 'important'))
1006
+ const next = { ...current, sidebarAutoHide: !wasAutoHide }
1007
+ current = next
1008
+ persist(next)
1009
+ instantSidebarExpand = false
1010
+ sidebarRevealed = !next.sidebarAutoHide
1011
+ if (wasAutoHide && revealedNow) {
1012
+ const pinSidebar = document.querySelector('[class*="sidebarCol"]')
1013
+ const pinRoot = pinSidebar && pinSidebar.querySelector('[data-slot="sidebar"] > [class*="root"]')
1014
+ // 「钉住」的语义是"原地冻结":必须钉在侧栏列**当前**所在的框上。列在 Windows 下
1015
+ // 是从标题栏**下方**开始的(frame 有 padding-top: 标题栏高),原来写死的
1016
+ // `left/top:0; height:100%` 会把 root 提到视口左上角(z-index 900),它顶部那一行
1017
+ // ——deepseek 品牌行——就会盖到标题栏上闪一下。
1018
+ // 量的必须是未受动画影响的量:left/top/height 取列(列不参与 root 的滑入过渡),
1019
+ // width 取 root 自己。三个值都合理才钉,否则干脆不钉(正常过渡本来就安全)。
1020
+ const colRect = pinSidebar ? pinSidebar.getBoundingClientRect() : null
1021
+ const pinTop = colRect === null ? NaN : Math.round(colRect.top)
1022
+ const pinLeft = colRect === null ? NaN : Math.round(colRect.left)
1023
+ const pinHeight = colRect === null ? NaN : Math.round(colRect.height)
1024
+ if (pinRoot && pinHeight > 1 && Number.isFinite(pinTop) && Number.isFinite(pinLeft)) {
1025
+ // margin-left 只由 syncSidebarRoot 拥有:它不进快照,否则 360ms 后会把
1026
+ // 隐藏态的负偏移又还原回来(按钮已展开、侧栏却滑走了)。
1027
+ const names = ['position', 'left', 'top', 'width', 'height', 'z-index', 'transform', 'transition', 'will-change']
1028
+ const read = (el, list) => { const o = {}; list.forEach((n) => { o[n] = [el.style.getPropertyValue(n), el.style.getPropertyPriority(n)] }); return o }
1029
+ const snapRoot = read(pinRoot, names)
1030
+ const snapCol = read(pinSidebar, ['z-index'])
1031
+ const pw = Math.round(pinRoot.getBoundingClientRect().width) || sidebarWideWidth || 280
1032
+ pinSidebar.style.setProperty('z-index', '30', 'important')
1033
+ const rs = pinRoot.style
1034
+ rs.setProperty('position', 'fixed', 'important')
1035
+ rs.setProperty('left', pinLeft + 'px', 'important')
1036
+ rs.setProperty('top', pinTop + 'px', 'important')
1037
+ rs.setProperty('width', pw + 'px', 'important')
1038
+ rs.setProperty('height', pinHeight + 'px', 'important')
1039
+ rs.setProperty('z-index', '900', 'important')
1040
+ rs.setProperty('margin-left', '0', 'important')
1041
+ rs.setProperty('transform', 'none', 'important')
1042
+ rs.setProperty('transition', 'none', 'important')
1043
+ rs.setProperty('will-change', 'auto', 'important')
1044
+ if (sidebarPinTimer !== null) clearTimeout(sidebarPinTimer)
1045
+ sidebarPinTimer = setTimeout(() => {
1046
+ sidebarPinTimer = null
1047
+ const apply = (el, o) => { Object.entries(o).forEach(([n, [v, p]]) => v ? el.style.setProperty(n, v, p) : el.style.removeProperty(n)) }
1048
+ apply(pinRoot, snapRoot)
1049
+ apply(pinSidebar, snapCol)
1050
+ }, 360)
1051
+ }
1052
+ }
1053
+ if (!active) return
1054
+ // 起手要轻:只同步几何与属性,重活交给动画结束后的合并同步。
1055
+ // 原来这里同步跑 applyBackground(几十个 CSS 变量 + 主题 token + 全量查询)
1056
+ // 再跑 tagDom,第一次执行时正好压在过渡的第一帧上。
1057
+ enterMotion(340)
1058
+ applySidebarColumns(next)
1059
+ const frameNow = document.querySelector('[class*="frame"]')
1060
+ if (frameNow) {
1061
+ frameNow.setAttribute('data-dsh-auto-hide', String(!!next.sidebarAutoHide))
1062
+ syncFrameColumns(frameNow, !!next.sidebarAutoHide, sidebarWideWidth || 280, false)
1063
+ }
1064
+ scheduleSync()
1065
+ }
1066
+ window.addEventListener('pointerdown', sidebarToggleClick, true)
1067
+ window.addEventListener('mousedown', sidebarToggleClick, true)
1068
+ window.addEventListener('click', sidebarToggleClick, true)
1069
+ const onWindowResize = () => scheduleSync()
1070
+ window.addEventListener('resize', onWindowResize)
1071
+ document.addEventListener('click', sidebarToggleClick, true)
1072
+
1073
+ // —— 合并同步(见文件顶部「动效预算」)——
1074
+ // 一次 DOM 变更批次只同步一次;动画窗口内直接推迟到动画结束。以前每个批次都同步跑
1075
+ // applyBackground + tagDom,正好压在滑入动画的每一帧上。
1076
+ let syncFrame = 0
1077
+ let syncTimer = null
1078
+ let syncPending = false
1079
+ const syncFrameNow = () => {
1080
+ const frameRoot = document.querySelector('[class*="frame"]')
1081
+ if (frameRoot) syncFrameColumns(frameRoot, !!current.sidebarAutoHide, sidebarWideWidth || 280, false)
1082
+ }
1083
+ // 拖拽分界线结束后再补一次同步:最后一帧官方可能刚写完 inline 宽度,而下一次
1084
+ // ResizeObserver 不会再触发(布局已稳定),补齐才能让插件按"最终宽度"重写轨道。
1085
+ const onPointerRelease = () => { if (active) scheduleSync() }
1086
+ document.addEventListener('pointerup', onPointerRelease, true)
1087
+ document.addEventListener('pointercancel', onPointerRelease, true)
1088
+ const deferSync = () => {
1089
+ if (syncTimer !== null) return
1090
+ const wait = Math.max(48, motionUntil - performance.now() + 48)
1091
+ syncTimer = setTimeout(() => { syncTimer = null; scheduleSync() }, wait)
1092
+ }
1093
+ const runSync = () => {
1094
+ syncFrame = 0
1095
+ if (!active) return
1096
+ if (motionActive()) { syncPending = true; deferSync(); return }
1097
+ syncPending = false
1098
+ applyBackground(current, theme); tagDom(); ensureLatestButton(); watchColumns(); measureLatestButton(conversationScrollElement); scheduleConversationScroll()
1099
+ }
1100
+ const scheduleSync = () => {
1101
+ if (syncFrame !== 0) return
1102
+ if (motionActive()) { syncPending = true; deferSync(); return }
1103
+ syncFrame = requestAnimationFrame(runSync)
1104
+ }
1105
+ // 串流期间 DOM 每秒要变几十次,而 applyBackground + tagDom 是"全文档查询 + 几十个
1106
+ // CSS 变量 + 主题 token"的重活,只为让新内容被标记到。把它去抖到安静期:转写越长,
1107
+ // 每次省下的越多,这正是"越用越卡"的来源。轻活(跟随最新、按钮位置)仍每帧做。
1108
+ const FULL_SYNC_DEBOUNCE_MS = 160
1109
+ let fullSyncTimer = null
1110
+ const scheduleFullSync = () => {
1111
+ if (fullSyncTimer !== null) return
1112
+ fullSyncTimer = setTimeout(() => { fullSyncTimer = null; if (active) scheduleSync() }, FULL_SYNC_DEBOUNCE_MS)
1113
+ }
1114
+ let lightSyncFrame = 0
1115
+ const scheduleLightSync = () => {
1116
+ if (lightSyncFrame !== 0) return
1117
+ lightSyncFrame = requestAnimationFrame(() => { lightSyncFrame = 0; if (active) scheduleConversationScroll() })
1118
+ }
1119
+ // 右栏(文档预览)滑动期间摘掉插件自己加的 backdrop-filter:官方面板本来是不透明的,
1120
+ // 毛玻璃是本插件加的,而它在「面板首次从屏幕外滑入」这一帧要新建整块 render surface,
1121
+ // 之后平移的每一帧还要按新背景重算模糊。摘掉后动画结束再淡回来(.16s)。
1122
+ const setPopupMotion = (on) => {
1123
+ try {
1124
+ if (on) document.documentElement.setAttribute('data-dsh-popup-motion', 'true')
1125
+ else document.documentElement.removeAttribute('data-dsh-popup-motion')
1126
+ } catch { /* 无 document 时必须安静 */ }
1127
+ }
1128
+ flushAfterMotion = () => { setPopupMotion(false); if (syncPending) scheduleSync() }
1129
+ // 放行容器过渡:第一次看到右栏真正展开(或 3s 都没打开过)时解除闸门。
1130
+ let popupAnimGateTimer = setTimeout(() => { popupAnimGateTimer = null; try { document.documentElement.removeAttribute('data-dsh-popup-anim') } catch { /* 忽略 */ } }, 3000)
1131
+ const openPopupAnimGate = () => {
1132
+ if (popupAnimGateTimer === null) return
1133
+ clearTimeout(popupAnimGateTimer)
1134
+ popupAnimGateTimer = null
1135
+ try { document.documentElement.removeAttribute('data-dsh-popup-anim') } catch { /* 忽略 */ }
1136
+ }
1137
+ // 只有"新增节点会改变插件标记目标"(切会话、换主面板、开右栏)才值得立刻全量同步;
1138
+ // 普通消息行与流式 delta 只走轻活 + 去抖全量。
1139
+ const STRUCTURAL_SELECTOR = '[data-phase], [data-conversation-scroll], [data-composer-seat], [data-sidebar-right-panel], [data-slot="main"]'
1140
+ const hasStructuralAddition = (records) => {
1141
+ for (const record of records) {
1142
+ if (record.type !== 'childList') continue
1143
+ for (const node of record.addedNodes) {
1144
+ if (node.nodeType !== 1) continue
1145
+ if (typeof node.matches === 'function' && node.matches(STRUCTURAL_SELECTOR)) return true
1146
+ if (typeof node.querySelector === 'function' && node.querySelector(STRUCTURAL_SELECTOR) !== null) return true
1147
+ }
1148
+ }
1149
+ return false
1150
+ }
1151
+ const mo = new MutationObserver((records) => {
1152
+ let immediate = false
1153
+ for (const record of records) {
1154
+ // 官方在"同一次提交"里既翻转 data-sidebar-right-open、又首次渲染 tab 内容
1155
+ // (iframe / Markdown 解析),所以它出现的那一刻就是动画的起手帧。
1156
+ if (record.type === 'attributes' && record.attributeName === 'hidden') {
1157
+ // 切换会话只翻 SessionView 的 hidden:右栏可见性变了但中心列宽度
1158
+ // 未必变,ResizeObserver 不会回调,这里必须主动重算一次轨道。
1159
+ syncFrameNow()
1160
+ immediate = true
1161
+ continue
1162
+ }
1163
+ if (record.type === 'attributes' && record.attributeName === 'data-sidebar-right-open') {
1164
+ openPopupAnimGate()
1165
+ enterMotion(420)
1166
+ setPopupMotion(true)
1167
+ syncFrameNow()
1168
+ immediate = true
1169
+ }
1170
+ }
1171
+ if (immediate || hasStructuralAddition(records)) scheduleSync()
1172
+ else scheduleFullSync()
1173
+ scheduleLightSync()
1174
+ })
1175
+ mo.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['aria-expanded', 'data-variant', 'data-sidebar-right-open', 'hidden'] })
1176
+ // 0.1.5 的文档预览弹窗展开/收起会改 frame 的网格轨道(会话列随之收窄),而 React 只重写
1177
+ // inline grid-template-columns,不一定产生 childList 变更。用 ResizeObserver 盯住会话列
1178
+ // 宽度:宽度一变就立刻按官方轨道重排,弹窗弹出时会话区不会"慢半拍"。
1179
+ let columnObserver = null
1180
+ let columnTarget = null
1181
+ let columnFrame = 0
1182
+ const scheduleColumns = () => {
1183
+ if (columnFrame !== 0) return
1184
+ columnFrame = requestAnimationFrame(() => {
1185
+ columnFrame = 0
1186
+ if (!active) return
1187
+ // 只同步几何。这个回调在轨道动画期间是"每帧一次",以前它调的是全量
1188
+ // applyBackground(几十个 CSS 变量 + 主题 token + 全量查询)——右栏滑入时
1189
+ // 每帧都要付一次全页样式重算,首次(缓存全冷)尤其贵。
1190
+ syncFrameNow()
1191
+ })
1192
+ }
1193
+ const watchColumns = () => {
1194
+ const center = document.querySelector('[class*="centerCol"]')
1195
+ if (center === columnTarget) return
1196
+ if (columnObserver !== null) { columnObserver.disconnect(); columnObserver = null }
1197
+ columnTarget = center
1198
+ if (center !== null && typeof ResizeObserver === 'function') {
1199
+ columnObserver = new ResizeObserver(scheduleColumns)
1200
+ columnObserver.observe(center)
1201
+ }
1202
+ }
1203
+ watchColumns()
1204
+ return () => { active = false; flushAfterMotion = null; setPopupMotion(false); document.querySelectorAll('[data-dsh-appearance-page]').forEach((el) => el.removeAttribute('data-dsh-appearance-page')); document.querySelectorAll('style[data-plugin-css="' + NS + ':page"]').forEach((el) => el.remove()); if (popupAnimGateTimer !== null) { clearTimeout(popupAnimGateTimer); popupAnimGateTimer = null; try { document.documentElement.removeAttribute('data-dsh-popup-anim') } catch { /* 忽略 */ } } if (prewarmTimer !== null) { clearTimeout(prewarmTimer); prewarmTimer = null } if (syncFrame !== 0) { cancelAnimationFrame(syncFrame); syncFrame = 0 } if (fullSyncTimer !== null) { clearTimeout(fullSyncTimer); fullSyncTimer = null } if (lightSyncFrame !== 0) { cancelAnimationFrame(lightSyncFrame); lightSyncFrame = 0 } if (syncTimer !== null) { clearTimeout(syncTimer); syncTimer = null } if (sidebarHoverFrame !== 0) { cancelAnimationFrame(sidebarHoverFrame); sidebarHoverFrame = 0 } if (motionTimer !== null) { clearTimeout(motionTimer); motionTimer = null } motionUntil = 0; if (columnObserver !== null) { columnObserver.disconnect(); columnObserver = null } if (columnFrame !== 0) { cancelAnimationFrame(columnFrame); columnFrame = 0 } if (bootTimer !== null && bootTimer !== undefined) { clearTimeout(bootTimer); bootTimer = null } if (persistTimer !== null && persistTimer !== undefined) { clearTimeout(persistTimer); persistTimer = null } if (sidebarPinTimer !== null) { clearTimeout(sidebarPinTimer); sidebarPinTimer = null } cancelAnimationFrame(frame); cancelAnimationFrame(conversationScrollFrame); if (conversationScrollElement && conversationScrollListener) conversationScrollElement.removeEventListener('scroll', conversationScrollListener); if (conversationScrollHost && conversationScrollHostPosition !== null) { if (conversationScrollHostPosition[0]) conversationScrollHost.style.setProperty('position', conversationScrollHostPosition[0], conversationScrollHostPosition[1]); else conversationScrollHost.style.removeProperty('position') } cancelAnimationFrame(sidebarRestoreFrame); window.removeEventListener('pointerdown', sidebarToggleClick, true); window.removeEventListener('mousedown', sidebarToggleClick, true); window.removeEventListener('click', sidebarToggleClick, true); document.removeEventListener('click', sidebarToggleClick, true); window.removeEventListener('resize', onWindowResize); document.removeEventListener('mousemove', move); document.removeEventListener('mousemove', sidebarHover); document.removeEventListener('pointerup', onPointerRelease, true); document.removeEventListener('pointercancel', onPointerRelease, true); mo.disconnect(); sidebarStyleElements.forEach((sidebar) => restoreStyle(sidebarStyleState, sidebar)); sidebarStyleElements.clear(); sidebarRootStyleElements.forEach((root) => restoreStyle(sidebarRootStyleState, root)); sidebarRootStyleElements.clear(); document.querySelectorAll('[class*="frame"]').forEach((frameRoot) => restoreStyle(frameStyleState, frameRoot)); document.querySelectorAll('.dsh-appearance-wash, .dsh-appearance-bg').forEach((el) => el.remove()); document.querySelectorAll('#dsh-ui-appearance-bg-css').forEach((el) => el.remove()); document.querySelectorAll('[data-dsh-appearance-composer]').forEach((el) => el.removeAttribute('data-dsh-appearance-composer')); document.querySelectorAll('[data-dsh-appearance-session], [data-dsh-appearance-seat]').forEach((el) => { el.removeAttribute('data-dsh-appearance-session'); el.removeAttribute('data-dsh-appearance-seat') }); if (preloadProbe) { preloadProbe.onload = null; preloadProbe.onerror = null; preloadProbe = null } if (preloadTimeout !== null) { clearTimeout(preloadTimeout); preloadTimeout = null } if (latestButton?.isConnected) latestButton.remove(); latestButton = null; appearanceThemeDisposer?.(); appearanceThemeDisposer = null; document.getElementById('dsh-ui-appearance-bg-css')?.remove(); if (preloadTag?.isConnected && document.getElementById('dsh-ui-appearance-preload') === preloadTag) preloadTag.remove(); appearanceRootStyles.forEach(([value, priority, appliedValue], name) => { const currentValue = document.documentElement.style.getPropertyValue(name); if (currentValue === appliedValue) { if (value) document.documentElement.style.setProperty(name, value, priority); else document.documentElement.style.removeProperty(name) } }); appearanceRootStyles.clear(); appearanceRootStyles.clear(); document.documentElement.removeAttribute('data-dsh-popup-sync'); document.documentElement.style.removeProperty('--dsh-rightbar-track'); tag.remove(); popupTag.remove(); bg.remove() }
1205
+ }, 'dsh-ui-appearance: shell')
1206
+ // DSH 0.1.2 起 primitives 的 Tooltip 气泡不再 portal 到 document.body(0.1.1 是
1207
+ // createPortal 到 body),但它仍是 position:fixed;本插件给会话卡片/输入框/设置面板
1208
+ // 加了 backdrop-filter,这些卡片因此成为 fixed 元素的包含块,气泡会按卡片左上角定位,
1209
+ // 视觉上飞出很远。
1210
+ // 做法:气泡一进 DOM 就找出最近的"包含块祖先",把它的视口原点从气泡的 left/top 里扣掉。
1211
+ // 量的是祖先的 rect,所以不受气泡自身入场动画影响;补偿值记在气泡的 data 属性上,
1212
+ // 重复扫描(包括插件的多个实例)不会叠加,也不会形成"改样式 → 再次触发观察者"的死循环。
1213
+ ctx.effect(() => {
1214
+ const FIX_ATTR = 'data-dsh-tooltip-fix'
1215
+ const createsContainingBlock = (style) => (
1216
+ style.transform !== 'none'
1217
+ || style.filter !== 'none'
1218
+ || style.backdropFilter !== 'none'
1219
+ || style.perspective !== 'none'
1220
+ || style.willChange.includes('transform')
1221
+ || style.willChange.includes('filter')
1222
+ || style.willChange.includes('perspective')
1223
+ || /paint|layout|strict|content/.test(style.contain)
1224
+ )
1225
+ // fixed 元素的包含块是那个祖先的 padding box,而 getBoundingClientRect 给的是 border box。
1226
+ const originOf = (bubble) => {
1227
+ let element = bubble.parentElement
1228
+ while (element !== null && element !== document.documentElement) {
1229
+ const style = getComputedStyle(element)
1230
+ if (createsContainingBlock(style)) {
1231
+ const rect = element.getBoundingClientRect()
1232
+ return {
1233
+ x: rect.left + (parseFloat(style.borderLeftWidth) || 0),
1234
+ y: rect.top + (parseFloat(style.borderTopWidth) || 0),
1235
+ }
1236
+ }
1237
+ element = element.parentElement
1238
+ }
1239
+ return null
1240
+ }
1241
+ const align = (bubble) => {
1242
+ if (!(bubble instanceof HTMLElement) || bubble.getAttribute('role') !== 'tooltip') return
1243
+ const left = bubble.style.left
1244
+ const top = bubble.style.top
1245
+ if (left === '' || top === '') return
1246
+ // 当前值就是我们上次写下的补偿值 → 已经处理过,别再来一次。
1247
+ const fixed = bubble.getAttribute(FIX_ATTR)
1248
+ if (fixed !== null) {
1249
+ const separator = fixed.indexOf('|')
1250
+ if (fixed.slice(0, separator) === left && fixed.slice(separator + 1) === top) return
1251
+ }
1252
+ const origin = originOf(bubble)
1253
+ if (origin === null) return
1254
+ const x = parseFloat(left)
1255
+ const y = parseFloat(top)
1256
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return
1257
+ const nextLeft = `${x - origin.x}px`
1258
+ const nextTop = `${y - origin.y}px`
1259
+ if (nextLeft === left && nextTop === top) return
1260
+ bubble.setAttribute(FIX_ATTR, `${nextLeft}|${nextTop}`)
1261
+ bubble.style.left = nextLeft
1262
+ bubble.style.top = nextTop
1263
+ }
1264
+ const scan = () => document.querySelectorAll('[role="tooltip"]').forEach(align)
1265
+ // 观察者回调只做合并调度:一帧最多补一次,避免连续改样式时反复扫描。
1266
+ let frame = 0
1267
+ const schedule = () => {
1268
+ if (frame !== 0) return
1269
+ frame = requestAnimationFrame(() => { frame = 0; scan() })
1270
+ }
1271
+ // 只在这批变更真的涉及 tooltip 时才扫描:原来每次 DOM 变化都 querySelectorAll
1272
+ // 一遍全文档,转写越长越贵,而 tooltip 出现/移动本身是低频事件。
1273
+ const involvesTooltip = (records) => {
1274
+ for (const record of records) {
1275
+ if (record.type === 'attributes') {
1276
+ const target = record.target
1277
+ if (target && typeof target.getAttribute === 'function' && target.getAttribute('role') === 'tooltip') return true
1278
+ continue
1279
+ }
1280
+ for (const node of record.addedNodes) {
1281
+ if (node.nodeType !== 1) continue
1282
+ if (typeof node.getAttribute === 'function' && node.getAttribute('role') === 'tooltip') return true
1283
+ if (typeof node.querySelector === 'function' && node.querySelector('[role="tooltip"]') !== null) return true
1284
+ }
1285
+ }
1286
+ return false
1287
+ }
1288
+ const observer = new MutationObserver((records) => { if (involvesTooltip(records)) schedule() })
1289
+ if (document.body !== null) observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style'] })
1290
+ window.addEventListener('resize', schedule)
1291
+ schedule()
1292
+ return () => {
1293
+ observer.disconnect()
1294
+ window.removeEventListener('resize', schedule)
1295
+ if (frame !== 0) cancelAnimationFrame(frame)
1296
+ }
1297
+ }, 'dsh-ui-appearance: tooltip offset')
1298
+ // 桌面端(Electron)默认拒绝一切权限,包括 clipboard-sanitized-write,
1299
+ // navigator.clipboard.writeText 会抛 NotAllowedError;而 DSH 的 writeClipboard 在
1300
+ // "异步 API 存在但抛错"时不会退回 execCommand,复制按钮于是毫无反应。
1301
+ // 桌面端 preload 已暴露走 IPC 的原生剪贴板(window.dshDesktopClipboard),这里优先用它,
1302
+ // 失败再退回浏览器 API。Web 端没有这个桥,effect 直接返回,行为不变。
1303
+ // DSH 0.2.0 换成了 window.dshDesktop(且不含剪贴板写入器),这个桥已不存在,本 effect 在
1304
+ // 桌面端因此变成空转——客户端自己的 writeClipboard 现在自带 execCommand 回退,功能不受影响。
1305
+ // 整段包在 try 里:任何环境差异都不允许影响插件加载。
1306
+ ctx.effect(() => {
1307
+ try {
1308
+ const bridge = window.dshDesktopClipboard
1309
+ if (bridge === undefined || typeof bridge.writeText !== 'function') return
1310
+ const clipboard = navigator.clipboard
1311
+ if (clipboard === undefined || typeof clipboard.writeText !== 'function') return
1312
+ const original = clipboard.writeText
1313
+ const hadOwnWriteText = Object.prototype.hasOwnProperty.call(clipboard, 'writeText')
1314
+ // 多个实例(HMR 重载)会串起来包装,链上每一环都记住最原始的实现,
1315
+ // 这样卸载链头时还原到最初版本,而不是还原成上一个包装。
1316
+ const root = typeof original.dshClipboardRoot === 'function' ? original.dshClipboardRoot : original
1317
+ const patched = (text) => Promise.resolve()
1318
+ .then(() => bridge.writeText(String(text)))
1319
+ .then(() => undefined)
1320
+ .catch(() => Promise.resolve(original.call(clipboard, text)).then(() => undefined))
1321
+ patched.dshClipboardRoot = root
1322
+ Object.defineProperty(clipboard, 'writeText', { value: patched, configurable: true, writable: true })
1323
+ // 浏览器里 writeText 在 Clipboard.prototype 上,delete 就能还原;
1324
+ // 若运行环境把它放在实例自身上,则写回原函数。
1325
+ // 卸载时只在"自己仍是链头"时还原,否则会把更新实例的补丁一起删掉。
1326
+ return () => {
1327
+ try {
1328
+ if (clipboard.writeText !== patched) return
1329
+ if (hadOwnWriteText) Object.defineProperty(clipboard, 'writeText', { value: root, configurable: true, writable: true })
1330
+ else delete clipboard.writeText
1331
+ } catch (error) { /* 还原失败不影响卸载 */ }
1332
+ }
1333
+ } catch (error) { return }
1334
+ }, 'dsh-ui-appearance: clipboard fallback')
1335
+ ctx.effect(() => slots.inject('settings.section', () => slots.register({ name: 'settings.section', id: NS, order: 90, label: '外观' }, Panel)))
1336
+ }
1337
+ module.exports = { name: NS, inject: ['slots', 'theme'], apply }
1338
+ return module.exports
1339
+ }
1340
+ })
1341
+