dsh-panel-dock 0.0.0-stage → 1.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,1868 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-panel-dock',
3
+ factory(require) {
4
+ const React = require('react')
5
+ const h = React.createElement
6
+ // Portals are how a card survives being moved between the sidebar and the band.
7
+ // The loader exposes react-dom (dshmarket relies on it); if a host ever does not,
8
+ // the dock falls back to the plain two-host rendering instead of failing.
9
+ const createPortal = (() => {
10
+ try {
11
+ const dom = require('react-dom')
12
+ return dom && typeof dom.createPortal === 'function' ? dom.createPortal : null
13
+ } catch { return null }
14
+ })()
15
+
16
+ // dsh-panel-dock is a slot negotiation layer, not a UI of its own: plugins
17
+ // register a card here and the dock decides where it renders. It never adds a
18
+ // navigation entry, a button or a dialog -- the only affordances belong to the
19
+ // cards themselves.
20
+ const VERSION = '1.0.42'
21
+ const NS = 'panel-dock'
22
+ const STORE_KEY = 'dsh.panel-dock.v1'
23
+ const GAP = 6
24
+ const STACK_GAP = GAP
25
+ // Cards own their shadow, and a scroll container clips at its padding box. So the
26
+ // band only becomes a scroll container when the cards no longer fit the column,
27
+ // and then it grows by the shadow's reach and pads the same amount back.
28
+ const SHADOW_GUTTER = 16
29
+ // The panel declares the width below which its own content is no longer useful
30
+ // (`minWidth` in define()). The dock never renders it narrower than that, and when
31
+ // the whitespace is short it takes exactly the missing pixels out of the transcript.
32
+ // 280 is the default because it is measured, not guessed: at 280 both shipped cards
33
+ // render every value in full, while at 264 the quota card already cuts its 24h column
34
+ // to "35.2/1..." and at 200 it cuts 19 elements.
35
+ const DEFAULT_MIN_WIDTH = 280
36
+ // Nothing is drawn narrower than this, whatever a panel declares.
37
+ const MIN_WIDTH_FLOOR = 120
38
+ // A card wider than this stops reading as a card; the band may be wider than the
39
+ // card and the surplus stays with the conversation.
40
+ const MAX_PANEL_WIDTH = 480
41
+ // A card may eat into the conversation, but not more than half of it: past that the
42
+ // card belongs in the sidebar stack instead of on top of the text.
43
+ const MAX_COVER_RATIO = 0.5
44
+ // A conversation switch tears the transcript down and rebuilds it, so for a few frames
45
+ // the turn rail has no marks at all. Remembering where it was keeps the band's width
46
+ // stable across that gap instead of letting inner mode collapse to intrude.
47
+ const RAIL_MEMORY_MS = 1500
48
+ let railMemory = null
49
+ // The band must not clip: any scroll container turns its children's box-shadow into
50
+ // a hard-edged rectangle. Cards own their shadow, and it has to fall naturally the
51
+ // way it does in the sidebar.
52
+
53
+ const zh = { bandUnavailable: '此页无对话区',
54
+ empty: '暂无面板', toLeft: '移到左侧', toRight: '移到右侧', cardCrashed: '渲染失败(已隔离)',
55
+ }
56
+ const en = { bandUnavailable: 'No conversation on this page',
57
+ empty: 'No panels yet', toLeft: 'Move to the left panel', toRight: 'Move to the right panel',
58
+ cardCrashed: 'failed to render (isolated)',
59
+ }
60
+ let T = (key) => key
61
+
62
+ // The registry lives on the window, not in this module's closure: a hot reload of
63
+ // the dock creates a fresh closure while the panels keep their existing
64
+ // registrations -- wiping them would silently empty both docks.
65
+ const registry = (() => {
66
+ const existing = typeof window === 'undefined' ? null : window.__dshPanelDockRegistry
67
+ const map = existing instanceof Map ? existing : new Map()
68
+ if (typeof window !== 'undefined') window.__dshPanelDockRegistry = map
69
+ return map
70
+ })()
71
+ const listeners = (() => {
72
+ const existing = typeof window === 'undefined' ? null : window.__dshPanelDockListeners
73
+ const set = existing instanceof Set ? existing : new Set()
74
+ if (typeof window !== 'undefined') window.__dshPanelDockListeners = set
75
+ return set
76
+ })()
77
+
78
+ function emit() { for (const fn of listeners) { try { fn() } catch {} } }
79
+ function subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn) }
80
+ // Stacking order: `order` ascending (missing = 100), ties keep registration order.
81
+ // Registration order alone made a card's position depend on which plugin happened to
82
+ // activate first -- nothing a card could reason about or fix from its own side.
83
+ function orderOf(panel) {
84
+ const value = Number(panel.order)
85
+ return Number.isFinite(value) ? value : 100
86
+ }
87
+ function panels() {
88
+ // Array.prototype.sort is stable, so equal orders keep the Map's registration order.
89
+ return [...registry.values()].sort((a, b) => orderOf(a) - orderOf(b))
90
+ }
91
+
92
+ function readSides() {
93
+ try {
94
+ const raw = window.localStorage.getItem(STORE_KEY)
95
+ if (!raw) return {}
96
+ const parsed = JSON.parse(raw)
97
+ const source = parsed && typeof parsed.sides === 'object' && parsed.sides ? parsed.sides : {}
98
+ const sides = {}
99
+ for (const id of Object.keys(source)) {
100
+ const side = source[id]
101
+ if (side === 'left' || side === 'right') sides[id] = side
102
+ }
103
+ return sides
104
+ } catch { return {} }
105
+ }
106
+
107
+ function writeSides(sides) {
108
+ try { window.localStorage.setItem(STORE_KEY, JSON.stringify({ sides })) } catch {}
109
+ }
110
+
111
+ function sideOf(id, fallback) {
112
+ const sides = readSides()
113
+ if (sides[id] === 'left' || sides[id] === 'right') return sides[id]
114
+ return fallback === 'right' ? 'right' : 'left'
115
+ }
116
+
117
+ function setSide(id, side) {
118
+ const next = side === 'right' ? 'right' : 'left'
119
+ const sides = readSides()
120
+ sides[id] = next
121
+ writeSides(sides)
122
+ emit()
123
+ return next
124
+ }
125
+
126
+ function toggleSide(id) {
127
+ const panel = registry.get(id)
128
+ const current = sideOf(id, panel ? panel.side : 'left')
129
+ return setSide(id, current === 'right' ? 'left' : 'right')
130
+ }
131
+
132
+ function define(definition) {
133
+ if (!definition || typeof definition.id !== 'string' || definition.id === '') {
134
+ throw new Error('panel-dock: define() needs a non-empty id')
135
+ }
136
+ if (typeof definition.component !== 'function') {
137
+ throw new Error('panel-dock: define(' + definition.id + ') needs a component')
138
+ }
139
+ // minWidth is the panel's own statement of "below this my content stops being
140
+ // useful". The dock honours it as the width it will never undercut, taking the
141
+ // difference out of the transcript only when there is no whitespace left.
142
+ const declared = Number(definition.minWidth)
143
+ const minWidth = Number.isFinite(declared) && declared > 0
144
+ ? Math.min(MAX_PANEL_WIDTH, Math.max(MIN_WIDTH_FLOOR, Math.round(declared)))
145
+ : DEFAULT_MIN_WIDTH
146
+ // version is what a shared CardShell shows next to the title; it is the plugin's
147
+ // own version, not the dock's.
148
+ const version = typeof definition.version === 'string' || typeof definition.version === 'number'
149
+ ? String(definition.version)
150
+ : null
151
+ revisions.set(definition.id, revisionOf(definition.id) + 1)
152
+ // frame: the dock owns the visible rectangle (background, border, radius, padding,
153
+ // shadow) for every card. Default ON since 0.8.0 -- three cards each painting their
154
+ // own surface is how three cards end up in three different greys and shadows.
155
+ // A card that genuinely needs its own box opts out with frame: false.
156
+ // frameDeclared separates "said false" from "defaulted false": the registry lives on
157
+ // window and survives client reloads, so records written by 0.7.x carry the old
158
+ // default (false) and would otherwise keep their own surface forever.
159
+ const frameDeclared = definition.frame === true || definition.frame === false
160
+ const frame = frameDeclared ? definition.frame === true : true
161
+ // Keep the exact record so the disposer can tell "mine" from "a newer one's".
162
+ const stored = Object.assign({}, definition, { minWidth, version, frame, frameDeclared })
163
+ registry.set(definition.id, stored)
164
+ emit()
165
+ return () => {
166
+ // HMR race: when a module reloads, the new instance defines first and the old
167
+ // one disposes second. Deleting by id alone would remove the *new* registration
168
+ // and leave the card defined nowhere. Only remove the record we created.
169
+ if (registry.get(definition.id) !== stored) return
170
+ registry.delete(definition.id)
171
+ emit()
172
+ }
173
+ }
174
+
175
+ function useRegistry() {
176
+ const [, force] = React.useState(0)
177
+ React.useEffect(() => subscribe(() => force((n) => n + 1)), [])
178
+ return panels()
179
+ }
180
+
181
+ // Effective surface ownership. Records written before 0.8.0 have no frameDeclared and
182
+ // a defaulted `frame: false`; they must follow the new default rather than keep it.
183
+ function frameEnabled(panel) {
184
+ if (!panel) return false
185
+ if (panel.frameDeclared === true) return panel.frame === true
186
+ if (panel.frameDeclared === false) return true
187
+ return true
188
+ }
189
+
190
+ // Cards that opt in with `frame: true` hand the rectangle to the dock: one token set,
191
+ // one radius, one border, so three cards cannot end up in three different greys. The
192
+ // default stays off -- the dock must not repaint a card that draws itself.
193
+ // The host exposes no theme attribute and no surface tokens (verified: empty --dsw-* set,
194
+ // no data-theme, color-scheme:light), so the theme is read from what is actually painted:
195
+ // a dark page background means dark mode. Cards then switch to their dark palette.
196
+ const darkCache = { at: 0, dark: false }
197
+ const hostIsDark = () => {
198
+ const now = Date.now()
199
+ if (now - darkCache.at < 500) return darkCache.dark
200
+ let dark = false
201
+ try {
202
+ const bg = getComputedStyle(document.body).backgroundColor || ''
203
+ const m = bg.match(/rgba?\(([^)]+)\)/)
204
+ if (m) {
205
+ const p = m[1].split(',').map((v) => parseFloat(v))
206
+ const a = p.length > 3 ? p[3] : 1
207
+ const lum = (0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]) / 255
208
+ dark = a > 0.1 && lum < 0.45
209
+ }
210
+ } catch (e) {}
211
+ darkCache.at = now
212
+ darkCache.dark = dark
213
+ return dark
214
+ }
215
+
216
+ // --- theme contract (dock side) -------------------------------------------------
217
+ // Dock owns the card SURFACE (background, border, radius, shadow) and publishes the
218
+ // theme to the cards; cards own their inner content and read these instead of hardcoding
219
+ // colours. Signals, in priority order: data-pd-theme > prefers-color-scheme > currentColor.
220
+ const THEME_TOKENS = {
221
+ light: {
222
+ border: 'rgba(15,23,42,0.08)', fg: 'rgb(15,17,21)',
223
+ muted: 'rgba(15,17,21,0.55)', surface2: 'rgba(15,17,21,0.04)',
224
+ },
225
+ dark: {
226
+ border: 'rgba(255,255,255,0.10)', fg: 'rgb(232,234,237)',
227
+ muted: 'rgba(232,234,237,0.60)', surface2: 'rgba(255,255,255,0.07)',
228
+ },
229
+ }
230
+ const stampTheme = () => {
231
+ const dark = hostIsDark()
232
+ const base = THEME_TOKENS[dark ? 'dark' : 'light']
233
+ // Semantic colours live here because the host's --dsw-alias-state-* are tuned for the
234
+ // host surface, not for the dock card fill; cards asked for a stable set.
235
+ // Semantic colours belong to the dock: the host's state palette is tuned for the host
236
+ // surface, not for the card fill. success/error are aliases of ok/danger so cards can
237
+ // use either naming.
238
+ const tokens = dark
239
+ ? { ...base, ok: 'rgb(74,222,128)', warn: 'rgb(251,191,36)', danger: 'rgb(248,113,113)', idle: 'rgba(232,234,237,0.55)', accent: 'rgb(96,165,250)', track: 'rgba(255,255,255,0.14)', shadow: '0 4px 16px rgba(0,0,0,0.55)' }
240
+ : { ...base, ok: 'rgb(34,197,94)', warn: 'rgb(217,119,6)', danger: 'rgb(239,68,68)', idle: 'rgba(15,17,21,0.55)', accent: 'rgb(37,99,235)', track: 'rgba(15,23,42,0.08)', shadow: '0 3px 12px rgba(0,0,0,0.16)' }
241
+ tokens.success = tokens.ok
242
+ tokens.error = tokens.danger
243
+ // Also on :root: internal overlays and portals do not live inside the frame and would
244
+ // otherwise inherit nothing (Loci's map tip / peek are exactly that case).
245
+ const root = document.documentElement
246
+ root.setAttribute('data-pd-theme', dark ? 'dark' : 'light')
247
+ // :root gets a neutral default too: a card rendered outside a frame (or a portal) has no
248
+ // frame to read --pd-card-bg from. Per-frame values still win inside the frame.
249
+ root.style.setProperty('--pd-card-bg', dark ? '#26282b' : 'rgb(249,250,251)')
250
+ // Header metrics: one scale for every card so the logo/title/version row lines up.
251
+ // Values are the ones the three cards already agree on (13/700 title, gap 6) with the
252
+ // mark pinned to 14 and the version to 9 so the outliers have a target.
253
+ root.style.setProperty('--pd-header-gap', '6px')
254
+ root.style.setProperty('--pd-header-mark', '14px')
255
+ root.style.setProperty('--pd-header-title-size', '13px')
256
+ root.style.setProperty('--pd-header-title-weight', '700')
257
+ root.style.setProperty('--pd-header-version-size', '9px')
258
+ root.style.setProperty('--pd-header-actions-gap', '5px')
259
+ root.style.setProperty('--pd-header-bottom', '6px')
260
+ Object.keys(tokens).forEach((k) => {
261
+ const name = k === 'ok' || k === 'warn' || k === 'danger' || k === 'idle' ||
262
+ k === 'success' || k === 'error' || k === 'accent' || k === 'track' || k === 'shadow'
263
+ ? '--pd-card-' + k
264
+ : (k === 'surface2' ? '--pd-card-surface-2' : (k === 'border' || k === 'fg' || k === 'muted' ? '--pd-card-' + k : null))
265
+ if (name) root.style.setProperty(name, tokens[k])
266
+ })
267
+ const frames = document.querySelectorAll('[data-panel-dock-frame]')
268
+ for (let i = 0; i < frames.length; i++) {
269
+ const frame = frames[i]
270
+ const inLeft = Boolean(frame.closest('[data-panel-dock-left]'))
271
+ const bg = dark
272
+ ? (inLeft ? '#2e3135' : '#232528')
273
+ : (inLeft ? '#ffffff' : (THEME_TOKENS.light.bgRight || 'rgb(249,250,251)'))
274
+ frame.setAttribute('data-pd-theme', dark ? 'dark' : 'light')
275
+ if (dark) frame.setAttribute('data-pd-dark', '')
276
+ else frame.removeAttribute('data-pd-dark')
277
+ const s = frame.style
278
+ s.setProperty('--pd-card-bg', bg)
279
+ s.setProperty('--pd-card-fg', tokens.fg)
280
+ s.setProperty('--pd-card-muted', tokens.muted)
281
+ s.setProperty('--pd-card-border', tokens.border)
282
+ s.setProperty('--pd-card-surface-2', tokens.surface2)
283
+ s.setProperty('--pd-card-ok', tokens.ok)
284
+ s.setProperty('--pd-card-warn', tokens.warn)
285
+ s.setProperty('--pd-card-danger', tokens.danger)
286
+ s.setProperty('--pd-card-idle', tokens.idle)
287
+ s.setProperty('--pd-card-success', tokens.success)
288
+ s.setProperty('--pd-card-error', tokens.error)
289
+ s.setProperty('--pd-card-accent', tokens.accent)
290
+ s.setProperty('--pd-card-track', tokens.track)
291
+ s.setProperty('--pd-card-shadow', tokens.shadow)
292
+ }
293
+ }
294
+ const themeTimer = setInterval(() => { try { stampTheme() } catch (e) {} }, 2000)
295
+
296
+ const FRAME_STYLE = {
297
+ boxSizing: 'border-box',
298
+ width: '100%',
299
+ minWidth: 0,
300
+ padding: '10px 9px 8px',
301
+ borderRadius: 12,
302
+ border: '1px solid var(--dsw-alias-border-l1, rgba(0,0,0,0.08))',
303
+ background: 'var(--dsw-specific-sidebar-fill, rgba(249,250,251,1))',
304
+ color: 'var(--dsw-alias-label-primary, inherit)',
305
+ // Surface is the dock's business as of 0.8.0: one background, one border, one
306
+ // radius, one shadow for every card. Values are the ones the cards themselves used
307
+ // to write (Codex Advisor's shadow, measured: 0 3px 12px rgba(0,0,0,.16)); they are
308
+ // the user's pick, so changing them needs the user, not a passing maintainer.
309
+ boxShadow: '0 3px 12px 0 rgba(0,0,0,0.16)',
310
+ }
311
+
312
+ // A panel owns its own rectangle: the dock passes sizing through `style` and the
313
+ // component must spread it onto its single root element.
314
+ function renderPanel(panel) {
315
+ const card = h(panel.component, {
316
+ key: panel.id,
317
+ active: true,
318
+ 'data-panel-dock-item': panel.id,
319
+ style: {
320
+ width: '100%',
321
+ minWidth: 0,
322
+ boxSizing: 'border-box',
323
+ // Cards carry their own sidebar-footer layout (flex basis, order, margins).
324
+ // Inside a dock those must not leak: the dock owns placement and spacing.
325
+ flex: '0 0 auto',
326
+ order: 0,
327
+ margin: 0,
328
+ pointerEvents: 'auto',
329
+ },
330
+ })
331
+ if (!frameEnabled(panel)) return card
332
+ return h('div', {
333
+ 'data-panel-dock-frame': panel.id,
334
+ style: Object.assign({}, FRAME_STYLE, { display: 'flex', flexDirection: 'column' }),
335
+ }, card)
336
+ }
337
+
338
+ // Left panels live in the sidebar footer, in registration order.
339
+ function LeftHost() {
340
+ const layout = useRegistry()
341
+ // No room on the right (narrow conversation, or the right sidebar is open): a card
342
+ // reads better here than squeezed over the transcript.
343
+ const items = layout.filter((panel) => placement.fallback || sideOf(panel.id, panel.side) === 'left')
344
+ if (items.length === 0) return null
345
+ return h('div', {
346
+ 'data-panel-dock-left': '',
347
+ style: {
348
+ display: 'flex',
349
+ flexDirection: 'column',
350
+ gap: STACK_GAP,
351
+ // The host footer is a nowrap flex row; claim it and refuse to shrink,
352
+ // otherwise the stack collapses to a sliver of a few pixels.
353
+ flex: '0 0 100%',
354
+ width: '100%',
355
+ minWidth: 0,
356
+ boxSizing: 'border-box',
357
+ },
358
+ }, items.map((panel) => h(CardBoundary, {
359
+ key: panel.id + ':' + revisionOf(panel.id),
360
+ id: panel.id,
361
+ fallback: () => errorCard(panel),
362
+ }, renderPanel(panel))))
363
+ }
364
+
365
+ // Geometry of the right strip: between the transcript drag handle and the turn
366
+ // navigator, starting under the conversation tabs. Both anchors belong to the
367
+ // shipped layout, so they are measured rather than assumed.
368
+ function measureAnchors() {
369
+ if (typeof document === 'undefined') return null
370
+ const box = (el) => el.getBoundingClientRect()
371
+ let left = null
372
+ let right = null
373
+ let top = 8
374
+ let handleRight = null
375
+ let handleLeft = null
376
+ let railRight = null
377
+ let areaRight = null
378
+ let areaLeft = null
379
+ let railInfo = null
380
+ let tabsSeen = false
381
+ let pageRight = null
382
+ let pageTop = 0
383
+ try {
384
+ // Views such as 轨迹/看板 keep the splitter in the DOM at 0x0 while it is not
385
+ // shown. Measuring it yields `left:0/right:0`, which used to drag the band to the
386
+ // top-left corner. Only a splitter with real area is an anchor.
387
+ const handles = [...document.querySelectorAll('[class*="widthHandle"]')]
388
+ .filter((el) => el.getAttribute('data-side') === 'right')
389
+ .filter((el) => { const r = box(el); return r.width > 0 && r.height > 0 })
390
+ const handle = handles[0]
391
+ if (handle) {
392
+ handleRight = Math.round(box(handle).right)
393
+ // The splitter is the only way to widen the conversation back: a squeezed
394
+ // card must stop at its left edge instead of swallowing it.
395
+ handleLeft = Math.round(box(handle).left)
396
+ left = handleRight + GAP
397
+ }
398
+ // The turn rail sits to the right of the band; other turn-navigation buttons live
399
+ // on its left edge. Keep the smallest x that is still right of the handle -- a wide
400
+ // conversation can leave only a few pixels, so the tolerance has to stay small.
401
+ const railMarks = [...document.querySelectorAll('button[aria-label]')]
402
+ .filter((el) => /turnNavigation|轮次|跳转/i.test(el.getAttribute('aria-label') || ''))
403
+ .filter((el) => { const r = box(el); return r.width > 0 && r.height > 0 })
404
+ .map((el) => ({ left: Math.round(box(el).left), right: Math.round(box(el).right) }))
405
+ // Everything to the right of the handle belongs to the rail side; a squeezed
406
+ // band can leave the rail a single pixel right of the handle.
407
+ .filter((mark) => handleRight === null || mark.left > handleRight)
408
+ const rail = railColumn(railMarks)
409
+ railInfo = rail !== null ? { right: rail.left - GAP, railRight: rail.right } : null
410
+ const pageTabs = document.querySelector('[role="tablist"]')
411
+ if (pageTabs) {
412
+ const pr = box(pageTabs)
413
+ if (pr.width > 0) pageTop = Math.round(pr.bottom) + GAP
414
+ // An arbitrary main-area page decides its own content width. Climb from its tab
415
+ // strip to the first ancestor that no longer spans the window: that edge is the
416
+ // page's content boundary, and the gutter right of it is where the band belongs.
417
+ let node = pageTabs.parentElement
418
+ while (node && node !== document.body) {
419
+ const r = box(node)
420
+ if (r.width > 0 && r.height > 40 && r.right < window.innerWidth - 2) {
421
+ pageRight = Math.round(r.right)
422
+ break
423
+ }
424
+ node = node.parentElement
425
+ }
426
+ }
427
+ const tabs = document.querySelector('[data-conversation-tabs]')
428
+ tabsSeen = Boolean(tabs)
429
+ if (tabs) {
430
+ top = Math.round(box(tabs.parentElement || tabs).bottom) + GAP
431
+ // The right sidebar (开始 / 终端 / 浏览器) owns the window's right side. The column
432
+ // that holds the tabs is the conversation area: climb to the outermost ancestor
433
+ // that still ends where the column ends (the tab strip itself is padded, so it
434
+ // is skipped), and take that edge as the hard limit.
435
+ let node = tabs.parentElement
436
+ let columnRight = null
437
+ while (node && node !== document.body) {
438
+ const rect = box(node)
439
+ if (rect.width === 0 || rect.height < 40) { node = node.parentElement; continue }
440
+ if (columnRight === null) columnRight = rect.right
441
+ else if (Math.abs(rect.right - columnRight) > 3) break
442
+ node = node.parentElement
443
+ }
444
+ if (columnRight !== null && columnRight < window.innerWidth - 2) {
445
+ areaRight = Math.round(columnRight)
446
+ areaLeft = Math.round(box(tabs).left)
447
+ let up = tabs.parentElement
448
+ while (up && up !== document.body) {
449
+ const r = box(up)
450
+ if (r.width > 0 && r.height >= 40 && Math.abs(r.right - columnRight) <= 3) areaLeft = Math.round(r.left)
451
+ up = up.parentElement
452
+ }
453
+ }
454
+ }
455
+ if (railInfo !== null) {
456
+ right = railInfo.right
457
+ railRight = railInfo.railRight
458
+ railMemory = { right, railRight, handleRight, areaRight, at: Date.now() }
459
+ } else if (
460
+ railMemory !== null
461
+ && Date.now() - railMemory.at < RAIL_MEMORY_MS
462
+ && railMemory.handleRight === handleRight
463
+ && railMemory.areaRight === areaRight
464
+ ) {
465
+ // Same window geometry, rail momentarily missing: keep the last known rail.
466
+ right = railMemory.right
467
+ railRight = railMemory.railRight
468
+ }
469
+ } catch {}
470
+ return { left, right, top, handleLeft, handleRight, railRight, areaRight, areaLeft, pageTop, tabsSeen, pageRight }
471
+ }
472
+
473
+ function sameAnchors(a, b) {
474
+ if (!a || !b) return a === b
475
+ return a.left === b.left && a.right === b.right && a.top === b.top
476
+ && a.handleLeft === b.handleLeft && a.handleRight === b.handleRight
477
+ && a.railRight === b.railRight && a.areaRight === b.areaRight && a.areaLeft === b.areaLeft
478
+ }
479
+
480
+ // What the cards want, gap included.
481
+ function stackedHeight(el) {
482
+ const kids = [...el.children]
483
+ let total = 0
484
+ for (const kid of kids) total += kid.getBoundingClientRect().height
485
+ return total + STACK_GAP * Math.max(0, kids.length - 1)
486
+ }
487
+
488
+ // The turn rail is a *column*: dozens of marks share one x. Message-level actions
489
+ // ("跳转到该消息", ...) match the same words but stand alone, and one of them sitting
490
+ // left of the rail used to drag the whole band left with it -- cards then rendered
491
+ // at the 200px floor while their real whitespace stayed empty. Pick the column.
492
+ function railColumn(marks) {
493
+ if (!marks.length) return null
494
+ const groups = []
495
+ for (const mark of marks) {
496
+ const group = groups.find((g) => Math.abs(g.left - mark.left) <= 2)
497
+ if (group) {
498
+ group.count += 1
499
+ group.right = Math.max(group.right, mark.right)
500
+ } else {
501
+ groups.push({ left: mark.left, right: mark.right, count: 1 })
502
+ }
503
+ }
504
+ const columns = groups.filter((g) => g.count >= 4).sort((a, b) => (b.count - a.count) || (a.left - b.left))
505
+ if (columns.length) return columns[0]
506
+ // A short conversation has few marks, but they still share one x. A *single* mark is
507
+ // usually an unrelated "跳转" button floating in the view (轨迹/看板 do that): treating
508
+ // it as the rail put the band at x≈6. Require at least two marks in one column.
509
+ const short = groups.filter((g) => g.count >= 2).sort((a, b) => (b.count - a.count) || (a.left - b.left))
510
+ return short.length ? short[0] : null
511
+ }
512
+
513
+ // Where right-side cards can live: the gutter left of the turn rail, the gutter right
514
+ // of it, or -- when neither can hold a readable card -- back in the sidebar stack.
515
+ // A card squeezed over the transcript is not an option: it hides text to buy a width
516
+ // that is still too small to read.
517
+ const placement = { fallback: false }
518
+ function setFallback(next) {
519
+ if (placement.fallback === next) return
520
+ placement.fallback = next
521
+ emit()
522
+ }
523
+
524
+ // `required` is the widest minimum any right-side card declared: the band is one
525
+ // column, so it has to satisfy the most demanding card in it.
526
+ // Kept so a main-area page shows the card at the same width it had beside the
527
+ // conversation: dropping to `required` there made the card visibly jump narrower.
528
+ let lastPlannedWidth = 0
529
+ // Switching conversations unmounts the turn rail for a moment ("载入历史…"). Treating
530
+ // that as "no conversation surface" flung the band to the window edge and pulled it
531
+ // back once loading finished -- the shrink-then-expand the user sees. Keep the last
532
+ // anchored plan through that gap instead of re-deciding on a half-built page.
533
+ const STICKY_PLAN_MS = 2500
534
+ let lastAnchoredPlan = null
535
+ let lastAnchoredAt = 0
536
+
537
+ // A main-area page (Memory, settings, a plugin panel, 轨迹/看板) has no conversation
538
+ // column to measure, so the band is laid out against the page's own content boundary:
539
+ // sit in the gutter right of the content when it is wide enough, otherwise take only
540
+ // the minimum width so as little content as possible is covered.
541
+ function pagePlan(anchors, required, top) {
542
+ const vw = typeof window === 'undefined' ? 0 : window.innerWidth
543
+ const limit = Math.min(vw, anchors && anchors.areaRight ? anchors.areaRight : vw) - GAP
544
+ const desired = Math.min(MAX_PANEL_WIDTH, Math.max(required, lastPlannedWidth || required))
545
+ const contentRight = anchors && anchors.pageRight ? anchors.pageRight : null
546
+ // Default to the width the band had beside the conversation, so switching between a
547
+ // page and a conversation does not visibly resize the card.
548
+ let width = desired
549
+ if (contentRight !== null) {
550
+ const gutter = vw - contentRight - GAP * 2
551
+ // Only a real gutter may shrink it; a full-width page has nowhere to put the band,
552
+ // so keep the familiar width and let the hover dim signal what it covers.
553
+ if (gutter >= required) width = Math.min(desired, gutter)
554
+ }
555
+ return { mode: 'page', pageTop: top, rightEdge: limit, width, limit }
556
+ }
557
+
558
+ function planBand(anchors, required) {
559
+ const vw = typeof window === 'undefined' ? 0 : window.innerWidth
560
+ const areaEdge = Math.min(vw, anchors && anchors.areaRight ? anchors.areaRight : vw)
561
+ const limit = areaEdge - GAP
562
+ // The band only makes sense beside a conversation. Other main-area surfaces (a plugin
563
+ // panel, settings) have no conversation column, no splitter and no turn rail -- with no
564
+ // surface to dock against, the band used to pin itself to the window top-right corner and
565
+ // cover that page. Fall back to the sidebar stack instead.
566
+ const hasSurface = Boolean(anchors) && (
567
+ anchors.tabsSeen === true
568
+ || (anchors.handleRight !== null && anchors.handleRight !== undefined)
569
+ || (anchors.areaRight !== null && anchors.areaRight !== undefined)
570
+ || (anchors.railRight !== null && anchors.railRight !== undefined)
571
+ )
572
+ if (!hasSurface) {
573
+ const t = (anchors && anchors.pageTop) || 56
574
+ return pagePlan(anchors, required, t)
575
+ }
576
+ const hasRail = Boolean(anchors) && anchors.railRight !== null && anchors.railRight !== undefined
577
+ // 轨迹 / 看板 / Codex are conversation views without a turn rail: they keep the band
578
+ // flush to the right edge. But a *conversation* also loses its rail for a moment
579
+ // while history loads, and that is not a view change -- reuse the anchored plan for
580
+ // a short window so the band does not jump to the edge and back.
581
+ if (!hasRail && anchors !== null && anchors.tabsSeen === true) {
582
+ const now = Date.now()
583
+ if (lastAnchoredPlan && now - lastAnchoredAt < STICKY_PLAN_MS) return lastAnchoredPlan
584
+ return pagePlan(anchors, required, anchors.top || 8)
585
+ }
586
+ // A conversation without turns has no rail yet. That is not "no space": the column
587
+ // simply runs to its own right edge, and that edge is the boundary the band must
588
+ // respect. Treating the missing rail as a wall collapsed the band into the sidebar
589
+ // for the first frames of every new conversation, then brought it back when the
590
+ // rail appeared -- the "shrink in and come back" the user saw.
591
+ const innerRight = anchors && anchors.right !== null ? anchors.right : limit
592
+ const inner = anchors && anchors.left !== null ? innerRight - anchors.left : null
593
+ // The whitespace is used where it exists.
594
+ const remember = (plan) => {
595
+ lastAnchoredPlan = plan
596
+ lastAnchoredAt = Date.now()
597
+ if (plan.width) lastPlannedWidth = plan.width
598
+ return plan
599
+ }
600
+ if (inner !== null && inner >= required) {
601
+ return remember({ mode: 'inner', left: anchors.left, width: Math.min(inner, MAX_PANEL_WIDTH), limit })
602
+ }
603
+ const outer = hasRail ? limit - (anchors.railRight + GAP) : null
604
+ if (outer !== null && outer >= required) {
605
+ return remember({ mode: 'outer', rightEdge: limit, width: Math.min(outer, MAX_PANEL_WIDTH), limit })
606
+ }
607
+ // No whitespace wide enough: take the minimum a card needs out of the transcript,
608
+ // and only that much. The card sits flush with the conversation column so it takes
609
+ // the least possible text out of view; covering the turn rail is accepted.
610
+ const rightEdge = limit
611
+ const column = anchors && anchors.areaRight && anchors.areaLeft
612
+ ? Math.max(1, anchors.areaRight - anchors.areaLeft)
613
+ : Math.max(1, areaEdge)
614
+ // The card may cover at most half of the conversation column.
615
+ if (required > column * MAX_COVER_RATIO) return { mode: 'fallback', width: 0, limit }
616
+ return remember({ mode: 'intrude', rightEdge, width: required, limit })
617
+ }
618
+
619
+ function RightHost() {
620
+ const all = useRegistry()
621
+ const [anchors, setAnchors] = React.useState(() => measureAnchors())
622
+ const [scrolls, setScrolls] = React.useState(false)
623
+ const stack = React.useRef(null)
624
+ const measureStack = React.useRef(() => {})
625
+
626
+ React.useEffect(() => {
627
+ let raf = 0
628
+ const sync = () => {
629
+ raf = 0
630
+ const next = measureAnchors()
631
+ // measureAnchors() builds a fresh object on every tick; keep the previous one
632
+ // while nothing moved, otherwise every card re-renders four times a second.
633
+ setAnchors((prev) => (sameAnchors(prev, next) ? prev : next))
634
+ // The tick also re-checks the stack: a minimised or occluded window holds
635
+ // ResizeObserver notifications back far longer than the user can see.
636
+ measureStack.current()
637
+ }
638
+ const schedule = () => { if (!raf) raf = requestAnimationFrame(sync) }
639
+ window.addEventListener('resize', schedule)
640
+ const timer = setInterval(schedule, 700)
641
+ return () => {
642
+ window.removeEventListener('resize', schedule)
643
+ clearInterval(timer)
644
+ if (raf) cancelAnimationFrame(raf)
645
+ }
646
+ }, [])
647
+
648
+ const items = all.filter((panel) => sideOf(panel.id, panel.side) === 'right')
649
+ // Default 280 applies only to a panel that declared nothing; a panel that says it
650
+ // can live with 160 gets 160, so it never takes more text than it needs.
651
+ const required = Math.min(MAX_PANEL_WIDTH, Math.max(MIN_WIDTH_FLOOR,
652
+ items.reduce((widest, panel) => Math.max(widest, panel.minWidth || DEFAULT_MIN_WIDTH), 0)))
653
+ const plan = planBand(anchors, required)
654
+ const top = plan.mode === 'page' ? plan.pageTop : (anchors ? anchors.top : 8)
655
+
656
+ // Publish the decision so the sidebar stack can take the cards over.
657
+ React.useEffect(() => { setFallback(plan.mode === 'fallback') })
658
+
659
+ // A stack that fits stays a plain, non-clipping column, because a card may draw
660
+ // outside its own box (its shadow). Scroll only when the cards exceed the column.
661
+ // Cards reach their real height asynchronously (data arrives after mount), and
662
+ // that never re-renders the dock -- so watch the cards themselves.
663
+ React.useEffect(() => {
664
+ const el = stack.current
665
+ const measure = () => {
666
+ if (!el) { setScrolls(false); return }
667
+ const column = Math.max(0, window.innerHeight - 8 - top)
668
+ const next = stackedHeight(el) > column + 0.5
669
+ setScrolls((prev) => (prev === next ? prev : next))
670
+ }
671
+ measureStack.current = measure
672
+ measure()
673
+ if (!el || typeof ResizeObserver === 'undefined') return undefined
674
+ const observer = new ResizeObserver(measure)
675
+ for (const kid of el.children) observer.observe(kid)
676
+ return () => { observer.disconnect(); measureStack.current = () => {} }
677
+ }, [items.length, top])
678
+
679
+ // An empty column must cost nothing: no panels, no strip, no reserved width.
680
+ // The same goes for a column the band cannot hold: the cards moved to the sidebar.
681
+ if (items.length === 0 || plan.mode === 'fallback') return null
682
+
683
+ const width = plan.width
684
+
685
+ const style = {
686
+ position: 'fixed',
687
+ top,
688
+ bottom: 8,
689
+ display: 'flex',
690
+ flexDirection: 'column',
691
+ gap: STACK_GAP,
692
+ minWidth: 0,
693
+ boxSizing: 'border-box',
694
+ overflow: 'visible',
695
+ // The band is a transparent overlay over the transcript's right margin: it
696
+ // must not swallow clicks meant for the conversation behind it.
697
+ pointerEvents: 'none',
698
+ zIndex: 10000,
699
+ }
700
+ style.width = width
701
+ if (plan.mode === 'inner') {
702
+ // The gutter between the transcript handle and the turn rail.
703
+ style.left = plan.left
704
+ } else {
705
+ // Right of the rail (or, before any conversation is measured, the area's edge).
706
+ style.right = Math.max(GAP, window.innerWidth - plan.rightEdge)
707
+ }
708
+
709
+ if (scrolls) {
710
+ // Grow the box by the shadow's reach, pad the same amount back, and only then
711
+ // scroll. Every card keeps the exact rectangle it had; the scrollport's clip
712
+ // line lands in the gutter instead of across a card's shadow.
713
+ const gutter = SHADOW_GUTTER
714
+ style.top = top - gutter
715
+ style.height = Math.max(0, window.innerHeight - 8 - top) + gutter * 2
716
+ style.bottom = 'auto'
717
+ style.width = width + gutter * 2
718
+ if (style.left !== undefined) style.left -= gutter
719
+ if (style.right !== undefined) style.right -= gutter
720
+ style.padding = gutter
721
+ style.overflowY = 'auto'
722
+ style.overflowX = 'hidden'
723
+ // No scrollbar: it would sit in the gutter as a foreign affordance, and a
724
+ // classic scrollbar would also narrow every card by its own width.
725
+ style.scrollbarWidth = 'none'
726
+ }
727
+
728
+ return h('div', {
729
+ 'data-panel-dock-strip': '',
730
+ 'data-panel-dock-scrolls': scrolls ? '' : undefined,
731
+ ref: stack,
732
+ style,
733
+ }, items.map((panel) => h(CardBoundary, {
734
+ key: panel.id + ':' + revisionOf(panel.id),
735
+ id: panel.id,
736
+ fallback: () => errorCard(panel),
737
+ }, renderPanel(panel))))
738
+ }
739
+
740
+
741
+ // ---- tray (portal transport) ----
742
+ // Moving a card between the sidebar and the band must not remount it: a data card
743
+ // would refetch and flash. So each card lives in a portal whose *container* is moved
744
+ // in the DOM (appendChild / insertBefore) instead of being recreated. React keeps the
745
+ // subtree mounted across a DOM move -- measured on a live card: content and data stay,
746
+ // loading never flips back on.
747
+ const tray = { cells: new Map(), leftSlot: null, leftStack: null, poke: null }
748
+
749
+ function cellOf(id) {
750
+ let el = tray.cells.get(id)
751
+ if (!el) {
752
+ el = document.createElement('div')
753
+ el.setAttribute('data-panel-dock-cell', id)
754
+ // The card is the visible rectangle; the cell is only a transport box.
755
+ el.style.cssText = 'display:flex;flex-direction:column;flex:0 0 auto;min-width:0;pointer-events:none'
756
+ tray.cells.set(id, el)
757
+ }
758
+ return el
759
+ }
760
+
761
+ function dropDeadCells(alive) {
762
+ for (const [id, el] of [...tray.cells]) {
763
+ if (alive.has(id)) continue
764
+ if (el.parentNode) el.parentNode.removeChild(el)
765
+ tray.cells.delete(id)
766
+ }
767
+ }
768
+
769
+ // ---- deck: same-side cards as a stack (one full card + 24px peek strips) ----
770
+ // Column behaviour up to 0.6.13 is a plain list. A deck trades height for order:
771
+ // every rear card shows only its top strip and the wheel shuffles the front one.
772
+ // WeChat's stacked card set (公众号/收藏 的「堆叠态」): each card behind sits a little
773
+ // higher and to the right, very slightly rotated and scaled, so the stack reads as
774
+ // physical cards rather than tabs. Values are deliberately small -- at 3 cards the
775
+ // whole fan is only a couple of degrees wide.
776
+ // Mostly horizontal: the stack fans to the right, so a card going to the back reads as
777
+ // sliding sideways (WeChat's stack does), not as sliding up or down.
778
+ // The step must clear the card radius, otherwise a rear card can only be clipped by
779
+ // slicing through its rounded corner (5px step vs 12px radius = the "dirty corner").
780
+ // 14px is the smallest step that keeps a whole corner and still reads as a stack.
781
+ // Measured from WeChat 4.2 (60 s window recording, 10 fps): behind the upright front card
782
+ // the pile peeks on the LEFT, each card tilted about 2 degrees, so the visible sliver is a
783
+ // thin diagonal strip rather than a straight band. The band is 14px tall to clear the radius.
784
+ const DECK_STEP_Y = 14
785
+ const DECK_STEP_X = 18
786
+ // The operator's call: keep the flow offsets, no tilt at all. Every card stays upright.
787
+ const DECK_REAR_TILT = 0
788
+ const DECK_ROT = 0.7
789
+ const DECK_SCALE_STEP = 0.014
790
+ // The sidebar keeps the flat tab stack; its step is a readable strip, not a fan.
791
+ const DECK_LEFT_PEEK = 24
792
+ const DECK_PEEK = DECK_LEFT_PEEK
793
+ const DECK_KEY = 'dsh.panel-dock.deck'
794
+ // Which card sits in front is the user's choice, so it outlives the module: a page
795
+ // reload, a client hot-reload or a card that unmounts for a moment all used to drop it
796
+ // back to "lowest order wins", which read as the stack resetting itself at random.
797
+ const DECK_FRONT_KEY = 'dsh.panel-dock.front'
798
+ const loadFront = () => {
799
+ try {
800
+ const raw = localStorage.getItem(DECK_FRONT_KEY)
801
+ const parsed = raw ? JSON.parse(raw) : null
802
+ return parsed && typeof parsed === 'object' ? parsed : {}
803
+ } catch { return {} }
804
+ }
805
+ const savedFront = loadFront()
806
+ const deck = {
807
+ on: null,
808
+ front: { band: savedFront.band || null, left: savedFront.left || null },
809
+ order: { band: null, left: null },
810
+ resync: null, wheelAt: 0, leaving: { band: null, left: null },
811
+ leavingAnim: { band: null, left: null },
812
+ }
813
+ function rememberFront(key, id) {
814
+ if (deck.front[key] === id) return
815
+ deck.front[key] = id
816
+ try {
817
+ localStorage.setItem(DECK_FRONT_KEY, JSON.stringify({ band: deck.front.band, left: deck.front.left }))
818
+ } catch {}
819
+ }
820
+
821
+ function deckOn() {
822
+ if (deck.on === null) {
823
+ try { deck.on = localStorage.getItem(DECK_KEY) === '1' } catch { deck.on = false }
824
+ }
825
+ return deck.on
826
+ }
827
+
828
+ function setDeckMode(next) {
829
+ if (deckOn() === next) return
830
+ deck.on = next
831
+ try { localStorage.setItem(DECK_KEY, next ? '1' : '0') } catch {}
832
+ if (deck.resync) deck.resync()
833
+ if (tray.poke) tray.poke()
834
+ }
835
+
836
+ function deckKeyOf(container) {
837
+ return container && container.hasAttribute('data-panel-dock-strip') ? 'band' : 'left'
838
+ }
839
+
840
+ function cellAt(container, index) {
841
+ const cells = []
842
+ for (const kid of container.children) {
843
+ if (kid.hasAttribute && kid.hasAttribute('data-panel-dock-cell')) cells.push(kid)
844
+ }
845
+ return cells[index] || null
846
+ }
847
+
848
+ function deckBarOf(container) {
849
+ for (const kid of container.children) {
850
+ if (kid.hasAttribute && kid.hasAttribute('data-panel-dock-deck-bar')) return kid
851
+ }
852
+ return null
853
+ }
854
+
855
+ // The affordance is the card edge itself: a narrow strip that drops into a gradient
856
+ // band with three travelling chevrons when the pointer arrives. It is absolutely
857
+ // positioned so it never takes part in the column's flow.
858
+ function ensureDeckBar(container) {
859
+ let bar = deckBarOf(container)
860
+ if (bar) return bar
861
+ // The strip is positioned against this column: without a positioning context it
862
+ // resolved against the viewport and sat at y=-6, off screen (measured).
863
+ if (typeof getComputedStyle === 'function') {
864
+ const position = getComputedStyle(container).position
865
+ if (position === 'static') container.style.position = 'relative'
866
+ }
867
+ bar = document.createElement('div')
868
+ bar.setAttribute('data-panel-dock-deck-bar', '')
869
+ bar.setAttribute('role', 'button')
870
+ bar.setAttribute('tabindex', '-1')
871
+ bar.setAttribute('aria-label', '堆叠 / 并列')
872
+ bar.setAttribute('title', '堆叠 / 并列')
873
+ bar.appendChild(document.createElement('i'))
874
+ bar.appendChild(document.createElement('i'))
875
+ bar.appendChild(document.createElement('i'))
876
+ bar.addEventListener('click', (event) => {
877
+ event.preventDefault()
878
+ event.stopPropagation()
879
+ setDeckMode(!deckOn())
880
+ })
881
+ container.appendChild(bar)
882
+ return bar
883
+ }
884
+
885
+ function rotateDeck(container, step) {
886
+ const key = deckKeyOf(container)
887
+ const order = deck.order[key]
888
+ if (!order || order.length < 2) return
889
+ const at = order.indexOf(deck.front[key])
890
+ const from = at < 0 ? 0 : at
891
+ const next = (from + step + order.length) % order.length
892
+ // The card being replaced first leans out to the left and dims (the "turning over"
893
+ // beat), then drops to the back of the stack; everything else moves up one slot.
894
+ deck.leaving[key] = { id: order[from], until: Date.now() + 170, dir: step >= 0 ? 1 : -1 }
895
+ rememberFront(key, order[next])
896
+ if (deck.resync) deck.resync()
897
+ window.setTimeout(() => {
898
+ if (deck.leaving[key] && Date.now() >= deck.leaving[key].until) {
899
+ deck.leaving[key] = null
900
+ if (deck.resync) deck.resync()
901
+ }
902
+ }, 180)
903
+ }
904
+
905
+ function wireDeckInput(container) {
906
+ if (!container || container.__pdDeckWired) return
907
+ container.__pdDeckWired = true
908
+ container.addEventListener('wheel', (event) => {
909
+ if (!deckOn()) return
910
+ const key = deckKeyOf(container)
911
+ const order = deck.order[key]
912
+ if (!order || order.length < 2) return
913
+ event.preventDefault()
914
+ event.stopPropagation()
915
+ const now = Date.now()
916
+ if (now - deck.wheelAt < 130) return
917
+ deck.wheelAt = now
918
+ rotateDeck(container, event.deltaY > 0 ? 1 : -1)
919
+ }, { passive: false })
920
+ // A click on a rear card's strip promotes that card instead of reaching the card.
921
+ container.addEventListener('pointerdown', (event) => {
922
+ if (!deckOn()) return
923
+ const key = deckKeyOf(container)
924
+ const order = deck.order[key]
925
+ if (!order || order.length < 2) return
926
+ // Anything interactive keeps its own behaviour: only the front card is live (the
927
+ // rest are inert), so a side-toggle press must never be swallowed here.
928
+ const hit = event.target && event.target.closest
929
+ ? event.target.closest('button,a,input,select,textarea,[role="button"],[data-panel-dock-toggle]')
930
+ : null
931
+ if (hit) return
932
+ const box = container.getBoundingClientRect()
933
+ const y = event.clientY - box.top
934
+ const slot = Math.floor(y / DECK_STEP_Y)
935
+ if (slot < 0 || slot >= order.length - 1) return
936
+ const target = order[order.length - 1 - slot]
937
+ event.preventDefault()
938
+ event.stopPropagation()
939
+ rememberFront(key, target)
940
+ if (deck.resync) deck.resync()
941
+ }, true)
942
+ }
943
+
944
+ // The strip must sit on the front card's own rectangle. It is positioned during the
945
+ // layout pass, but by then the front card may still be animating into place (measured:
946
+ // bar at y=121 while the front card had settled at 131), so this re-runs after the
947
+ // transitions land.
948
+ function alignDeckBar(container) {
949
+ if (!container || !container.hasAttribute('data-panel-dock-deck')) return
950
+ const key = deckKeyOf(container)
951
+ const order = deck.order[key]
952
+ const bar = deckBarOf(container)
953
+ if (!order || !order.length || !bar) return
954
+ const front = tray.cells.get(order[0])
955
+ if (!front) return
956
+ const containerBox = container.getBoundingClientRect()
957
+ const frontBox = front.getBoundingClientRect()
958
+ if (!frontBox.width) return
959
+ bar.style.top = Math.round(frontBox.top - containerBox.top) + 'px'
960
+ bar.style.left = Math.round(frontBox.left - containerBox.left) + 'px'
961
+ bar.style.right = 'auto'
962
+ bar.style.width = Math.round(frontBox.width) + 'px'
963
+ }
964
+
965
+ // Cards reach their real height asynchronously (data arrives after mount) and never
966
+ // re-render the dock, so the deck height has to follow the front card's size.
967
+ function refreshDeckHeight(container) {
968
+ if (!container || !container.hasAttribute('data-panel-dock-deck')) return
969
+ const key = deckKeyOf(container)
970
+ const order = deck.order[key]
971
+ if (!order || !order.length) return
972
+ const front = tray.cells.get(order[0])
973
+ if (!front) return
974
+ alignDeckBar(container)
975
+ const frontHeight = Math.round(front.getBoundingClientRect().height)
976
+ if (!frontHeight) return
977
+ // Same rule as syncDeck: the box ends at the lowest card bottom, using each cell's real
978
+ // offset inside the container (a card's own height alone over-counts by its step).
979
+ const step = container.hasAttribute('data-panel-dock-strip') ? DECK_STEP_Y : DECK_PEEK
980
+ let bottom = frontHeight
981
+ let tallest = frontHeight
982
+ const containerTop = container.getBoundingClientRect().top
983
+ for (const id of order) {
984
+ const cell = tray.cells.get(id)
985
+ if (!cell) continue
986
+ const box = cell.getBoundingClientRect()
987
+ if (!box.height) continue
988
+ tallest = Math.max(tallest, Math.round(box.height))
989
+ bottom = Math.max(bottom, Math.round(box.bottom - containerTop))
990
+ }
991
+ deck.stackHeights = deck.stackHeights || {}
992
+ deck.stackHeights[key] = tallest
993
+ const total = bottom
994
+ const box = container.getBoundingClientRect()
995
+ const room = box.top > 0 ? Math.max(0, Math.round(window.innerHeight - box.top - 8)) : 0
996
+ // Only the band may cap: it has a fixed top. The sidebar stack is bottom-anchored,
997
+ // so capping by (innerHeight - top) feeds back on itself -- smaller height pushes
998
+ // the top down, which shrinks the room again (measured: 268px content collapsed to
999
+ // an overflowing 201px box).
1000
+ const capped = container.hasAttribute('data-panel-dock-strip') && room > 0 && total > room
1001
+ const next = (capped ? room : total) + 'px'
1002
+ if (container.style.height !== next) container.style.height = next
1003
+ const overflow = capped ? 'auto' : ''
1004
+ if (container.style.overflowY !== overflow) container.style.overflowY = overflow
1005
+ }
1006
+
1007
+ function watchDeckCells(container) {
1008
+ if (!container || typeof ResizeObserver === 'undefined') return
1009
+ if (!container.__pdDeckObserver) {
1010
+ container.__pdDeckObserver = new ResizeObserver(() => refreshDeckHeight(container))
1011
+ }
1012
+ const observer = container.__pdDeckObserver
1013
+ const seen = container.__pdDeckSeen || new Set()
1014
+ for (const kid of container.children) {
1015
+ if (!kid.hasAttribute || !kid.hasAttribute('data-panel-dock-cell')) continue
1016
+ if (seen.has(kid)) continue
1017
+ seen.add(kid)
1018
+ observer.observe(kid)
1019
+ }
1020
+ container.__pdDeckSeen = seen
1021
+ }
1022
+
1023
+ function syncDeck(container, ids, active) {
1024
+ if (!container) return
1025
+ wireDeckInput(container)
1026
+ const key = deckKeyOf(container)
1027
+ const usable = active && deckOn() && ids.length >= 2
1028
+ const bar = ensureDeckBar(container)
1029
+ if (!usable) {
1030
+ deck.order[key] = null
1031
+ container.removeAttribute('data-panel-dock-deck')
1032
+ container.style.perspective = ''
1033
+ container.style.transformStyle = ''
1034
+ container.style.height = ''
1035
+ bar.removeAttribute('data-panel-dock-deck-on')
1036
+ if (bar) {
1037
+ if (ids.length >= 2) bar.removeAttribute('data-panel-dock-hidden')
1038
+ else bar.setAttribute('data-panel-dock-hidden', '')
1039
+ bar.style.top = '0'
1040
+ bar.style.left = '0'
1041
+ bar.style.right = '0'
1042
+ bar.style.width = ''
1043
+ }
1044
+ container.style.overflowY = ''
1045
+ container.style.flex = ''
1046
+ for (const id of ids) {
1047
+ const el = tray.cells.get(id)
1048
+ if (!el) continue
1049
+ el.style.position = ''
1050
+ el.style.left = ''
1051
+ el.style.right = ''
1052
+ el.style.top = ''
1053
+ el.style.transform = ''
1054
+ el.style.zIndex = ''
1055
+ el.style.clipPath = ''
1056
+ el.style.opacity = ''
1057
+ el.style.transition = ''
1058
+ el.style.transformOrigin = ''
1059
+ el.removeAttribute('data-panel-dock-rear')
1060
+ const frame = el.firstElementChild
1061
+ if (frame && frame.hasAttribute && frame.hasAttribute('data-panel-dock-frame')) {
1062
+ frame.style.boxShadow = FRAME_STYLE.boxShadow
1063
+ }
1064
+ // (fill is per side, via CSS: sidebar #fff on a #f9fafb column, band #f9fafb on
1065
+ // a #fff page -- the operator's contrast-by-inversion, not a border)
1066
+ }
1067
+ return
1068
+ }
1069
+ const wechat = container.hasAttribute('data-panel-dock-strip')
1070
+ container.setAttribute('data-panel-dock-deck', '')
1071
+ // Keep the pile FLAT: with `preserve-3d` the browser sorts the cards by their Z
1072
+ // depth instead of by z-index, and a card that swings through a Z offset during the
1073
+ // flip gets painted under the whole pile (then snaps back when the animation ends).
1074
+ container.style.perspective = ''
1075
+ container.style.transformStyle = ''
1076
+ bar.setAttribute('data-panel-dock-deck-on', '')
1077
+ // The "hidden" flag is set when a side has fewer than two cards; nothing used to
1078
+ // clear it when cards arrived later, so the strip stayed display:none forever
1079
+ // (measured: 2 cards in the band, bar rect 0x0, hidden=true).
1080
+ bar.removeAttribute('data-panel-dock-hidden')
1081
+ let front = deck.front[key]
1082
+ // Only fall back when the remembered card is *gone from the dock*, and remember the
1083
+ // fallback so the order stops flickering between two choices while ids settle.
1084
+ if (!front || ids.indexOf(front) < 0) {
1085
+ front = ids[0]
1086
+ rememberFront(key, front)
1087
+ } else {
1088
+ deck.front[key] = front
1089
+ }
1090
+ const start = ids.indexOf(front)
1091
+ const order = ids.slice(start).concat(ids.slice(0, start))
1092
+ deck.order[key] = order
1093
+ let frontHeight = 0
1094
+ const heights = new Map()
1095
+ const leaving = deck.leaving[key]
1096
+ const leavingLive = Boolean(leaving && leaving.id && Date.now() < leaving.until)
1097
+ // Wheel down sends the front card out towards "backwards" of the stack (left / down);
1098
+ // wheel up mirrors it (right / up). Same beat, opposite direction.
1099
+ const leavingDir = leaving && leaving.dir < 0 ? -1 : 1
1100
+ const n = order.length
1101
+ order.forEach((id, position) => {
1102
+ const el = tray.cells.get(id)
1103
+ if (!el) return
1104
+ el.style.position = 'absolute'
1105
+ el.style.left = '0'
1106
+ el.style.right = '0'
1107
+ el.style.top = '0'
1108
+ el.style.transformOrigin = '50% 0%'
1109
+ el.style.zIndex = String(200 - position)
1110
+ const isLeaving = leavingLive && leaving.id === id && position !== 0
1111
+ if (isLeaving && wechat) {
1112
+ // Slide out to the LEFT while shrinking, then settle at the back of the stack.
1113
+ // A CSS transition cannot turn a corner mid-flight (it interpolates straight to
1114
+ // the target), which is why the card used to shrink in place; a keyframe
1115
+ // animation with a midpoint gives the "toss it back under the pile" arc.
1116
+ const slotTransform =
1117
+ 'translate3d(' + (-position * DECK_STEP_X) + 'px,' +
1118
+ ((n - 1 - position) * DECK_STEP_Y) + 'px,0)' +
1119
+ ' rotate(' + (-position * DECK_REAR_TILT) + 'deg)'
1120
+ el.style.transition = 'none'
1121
+ el.style.transform = slotTransform
1122
+ el.style.opacity = '1'
1123
+ // Guard on playState, not on "an animation object exists": a cancelled or
1124
+ // finished animation never clears the slot when its element is re-created, and
1125
+ // every later rotation was silently skipped (measured: no 380ms animation in
1126
+ // document.getAnimations() after the first click).
1127
+ const running = deck.leavingAnim[key]
1128
+ const busy = running && running.playState === 'running'
1129
+ if (el.animate && !busy) {
1130
+ const width = el.offsetWidth || 300
1131
+ const frontTop = (n - 1) * DECK_STEP_Y
1132
+ const anim = el.animate([
1133
+ { transform: 'translate3d(0px,' + frontTop + 'px,0)', opacity: 1, offset: 0 },
1134
+ {
1135
+ // The card leans TOWARDS the way it is travelling: moving left tilts the top
1136
+ // edge left (negative CSS rotation), moving right tilts it right. The old
1137
+ // mirror kept the tilt on the opposite side of the motion, which is what
1138
+ // "the angle is wrong when it flips left/right" was about.
1139
+ transform: 'translate3d(' + Math.round(leavingDir * -width * 0.42) + 'px,' +
1140
+ (frontTop + 10) + 'px,-150px) rotateY(' + (leavingDir * -16) + 'deg) rotate(' +
1141
+ (leavingDir * -6) + 'deg) scale(.86)',
1142
+ opacity: 0.85,
1143
+ offset: 0.5,
1144
+ },
1145
+ { transform: slotTransform, opacity: 1, offset: 1 },
1146
+ ], { duration: 380, easing: 'cubic-bezier(.3,.7,.25,1)' })
1147
+ deck.leavingAnim[key] = anim
1148
+ anim.onfinish = () => {
1149
+ deck.leavingAnim[key] = null
1150
+ try { anim.cancel() } catch (e) {}
1151
+ el.style.transition = 'transform 260ms cubic-bezier(.2,.9,.25,1),opacity 160ms ease'
1152
+ }
1153
+ }
1154
+ } else if (isLeaving) {
1155
+ // Sidebar mirrors WeChat vertically: the front card slides DOWN while shrinking,
1156
+ // then settles at the back (the top strip). Same keyframe trick as the band --
1157
+ // a transition would interpolate straight to the target and read as "shrinking
1158
+ // in place", which is what the user complained about.
1159
+ const slotTransform = 'translateY(' + ((n - 1 - position) * DECK_PEEK) + 'px)'
1160
+ el.style.transition = 'none'
1161
+ el.style.transform = slotTransform
1162
+ el.style.opacity = '1'
1163
+ const running = deck.leavingAnim[key]
1164
+ const busy = running && running.playState === 'running'
1165
+ if (el.animate && !busy) {
1166
+ const height = el.offsetHeight || 160
1167
+ const frontTop = (n - 1) * DECK_PEEK
1168
+ const anim = el.animate([
1169
+ { transform: 'translateY(' + frontTop + 'px)', opacity: 1, offset: 0 },
1170
+ {
1171
+ transform: 'translateY(' +
1172
+ (frontTop + leavingDir * Math.round(height * 0.34)) + 'px) scale(.9)',
1173
+ opacity: 0.9,
1174
+ offset: 0.5,
1175
+ },
1176
+ { transform: slotTransform, opacity: 1, offset: 1 },
1177
+ ], { duration: 360, easing: 'cubic-bezier(.3,.7,.25,1)' })
1178
+ deck.leavingAnim[key] = anim
1179
+ anim.onfinish = () => {
1180
+ deck.leavingAnim[key] = null
1181
+ try { anim.cancel() } catch (e) {}
1182
+ el.style.transition = 'transform 220ms cubic-bezier(.2,.8,.2,1),opacity 160ms ease'
1183
+ }
1184
+ }
1185
+ } else if (wechat) {
1186
+ // Right band: a physical stack -- cards behind sit right, very slightly up and
1187
+ // pushed back on Z so the perspective does the shrinking, with a small Y-fan.
1188
+ // Cards that have been pushed back sit at the BACK-LEFT, not back-right, and the
1189
+ // front card stays perfectly upright (position 0 => no rotation, no scale).
1190
+ // The cascade: back-left by DECK_STEP_X a level, up by DECK_STEP_Y a level. Aligned
1191
+ // corner modes were tried and dropped -- with a front card twice as tall as a rear
1192
+ // one, a pinned corner hides the short cards completely.
1193
+ const x = -position * DECK_STEP_X
1194
+ const y = (n - 1 - position) * DECK_STEP_Y
1195
+ el.style.transformOrigin = '50% 0%'
1196
+ el.style.transition = 'transform 260ms cubic-bezier(.2,.9,.25,1),opacity 160ms ease'
1197
+ el.style.transform =
1198
+ 'translate3d(' + x + 'px,' + y + 'px,0)' +
1199
+ ' rotate(' + (-position * DECK_REAR_TILT) + 'deg)'
1200
+ el.style.opacity = '1'
1201
+ } else {
1202
+ // Sidebar: narrow and never overlapping the transcript, so it keeps the flat
1203
+ // strip stack (one full card + 24px tabs) instead of a fan.
1204
+ el.style.transition = 'transform 220ms cubic-bezier(.2,.8,.2,1),opacity 160ms ease'
1205
+ el.style.transform = 'translateY(' + ((n - 1 - position) * DECK_PEEK) + 'px)'
1206
+ el.style.opacity = '1'
1207
+ }
1208
+ // Nothing is clipped: in a real pile a short card on top does not shorten the long
1209
+ // one underneath, it just covers part of it. The cards are fully drawn and the
1210
+ // z-order does the covering; the container is sized to the tallest card so the
1211
+ // long one's bottom still lands inside the visible area.
1212
+ el.style.clipPath = ''
1213
+ heights.set(id, el.offsetHeight)
1214
+ // Only the front card is live. The rear cards keep hit-testing (a press on a
1215
+ // strip promotes that card) but every control inside them is disabled by CSS,
1216
+ // so the side-toggle of a card behind cannot switch sides any more.
1217
+ if (position === 0) el.removeAttribute('data-panel-dock-rear')
1218
+ else el.setAttribute('data-panel-dock-rear', '')
1219
+ const frame = el.firstElementChild
1220
+ if (frame && frame.hasAttribute && frame.hasAttribute('data-panel-dock-frame')) {
1221
+ const dark = hostIsDark()
1222
+ if (dark) frame.setAttribute('data-pd-dark', '')
1223
+ else frame.removeAttribute('data-pd-dark')
1224
+ frame.style.boxShadow = dark
1225
+ ? (position === 0 ? '0 8px 20px 0 rgba(0,0,0,0.62)' : '0 2px 8px 0 rgba(0,0,0,0.46)')
1226
+ : (position === 0 ? '0 8px 20px 0 rgba(0,0,0,0.16)' : '0 2px 8px 0 rgba(0,0,0,0.12)')
1227
+ }
1228
+ if (position === 0) frontHeight = el.offsetHeight
1229
+ })
1230
+ const step = wechat ? DECK_STEP_Y : DECK_PEEK
1231
+
1232
+ // The affordance belongs to the card the user is looking at, not to the column:
1233
+ // align it with the front card's own rectangle (it used to start at the deepest
1234
+ // rear card's top edge, so it floated above the stack).
1235
+ const frontCell = tray.cells.get(order[0])
1236
+ if (bar && frontCell) {
1237
+ const containerBox = container.getBoundingClientRect()
1238
+ const frontBox = frontCell.getBoundingClientRect()
1239
+ bar.style.top = Math.round(frontBox.top - containerBox.top) + 'px'
1240
+ bar.style.left = Math.round(frontBox.left - containerBox.left) + 'px'
1241
+ bar.style.right = 'auto'
1242
+ bar.style.width = Math.round(frontBox.width) + 'px'
1243
+ bar.style.borderRadius = '12px 12px 0 0'
1244
+ }
1245
+ // The stack is as tall as its TALLEST card, not as tall as the front one: otherwise
1246
+ // a tall card promoted to the front was clipped by a container sized for a short
1247
+ // predecessor, and the column jumped on every rotation. Left and right stacks keep
1248
+ // their own maximum.
1249
+ // The container ends where the LOWEST card bottom ends, computed from each card's own
1250
+ // offset: "tallest + (n-1)*step" double-counted, because the front card already sits
1251
+ // (n-1)*step further down. In the sidebar that surplus showed up as dead space between
1252
+ // the stack and the account row.
1253
+ let bottom = 0
1254
+ order.forEach((id, position) => {
1255
+ const h = heights.get(id) || 0
1256
+ if (h > 0) bottom = Math.max(bottom, (n - 1 - position) * step + h)
1257
+ })
1258
+ // The front card is translated by 0 (position 0), so it contributes its own height only.
1259
+ bottom = Math.max(bottom, frontHeight)
1260
+ const tallest = frontHeight
1261
+ deck.stackHeights = deck.stackHeights || {}
1262
+ deck.stackHeights[key] = tallest
1263
+ const total = bottom
1264
+ deck.frontHeights = deck.frontHeights || {}
1265
+ deck.frontHeights[key] = frontHeight
1266
+ const box = container.getBoundingClientRect()
1267
+ const room = box.top > 0 ? Math.max(0, Math.round(window.innerHeight - box.top - 8)) : 0
1268
+ // A deck taller than the column still has to be reachable; cap and scroll rather
1269
+ // than push the rear strips off the top of the screen.
1270
+ const capped = wechat && room > 0 && total > room
1271
+ container.style.height = total > 0 ? (capped ? room : total) + 'px' : ''
1272
+ container.style.overflowY = capped ? 'auto' : ''
1273
+ watchDeckCells(container)
1274
+ // The sidebar stack is a flex child sized to 100%; with an explicit height it has
1275
+ // to opt out or the host's basis wins.
1276
+ container.style.flex = container.hasAttribute('data-panel-dock-left') ? '0 0 auto' : ''
1277
+ // The new front card is measured before its un-clipped paint settles; without these
1278
+ // two follow-ups a tall card stayed visually cut until an unrelated resize.
1279
+ if (typeof requestAnimationFrame === 'function') requestAnimationFrame(() => refreshDeckHeight(container))
1280
+ window.setTimeout(() => refreshDeckHeight(container), 260)
1281
+ }
1282
+
1283
+ function leftStackNode() {
1284
+ if (!tray.leftStack) {
1285
+ const el = document.createElement('div')
1286
+ el.setAttribute('data-panel-dock-left', '')
1287
+ el.style.cssText = [
1288
+ 'display:flex', 'flex-direction:column', 'gap:' + STACK_GAP + 'px',
1289
+ 'flex:0 0 100%', 'width:100%', 'min-width:0', 'box-sizing:border-box',
1290
+ ].join(';')
1291
+ tray.leftStack = el
1292
+ }
1293
+ return tray.leftStack
1294
+ }
1295
+
1296
+ // The sidebar column does not scroll on its own: the host lays it out with
1297
+ // overflow:visible and simply clips at the window edge, so a stack taller than the
1298
+ // space below it hides its last cards with no way to reach them (verified at
1299
+ // 1280x560: last card bottom 567 in a 560px viewport, no scrollable ancestor).
1300
+ // Cap the stack at the room that actually exists and let it scroll instead.
1301
+ function syncLeftStackScroll() {
1302
+ const el = tray.leftStack
1303
+ if (!el || !el.parentNode) return false
1304
+ const rect = el.getBoundingClientRect()
1305
+ if (rect.top <= 0 && rect.height === 0) return false
1306
+ const room = Math.max(0, Math.round(window.innerHeight - rect.top - 8))
1307
+ const over = el.scrollHeight > room + 0.5
1308
+ el.style.maxHeight = over ? room + 'px' : ''
1309
+ el.style.overflowY = over ? 'auto' : ''
1310
+ el.style.scrollbarWidth = over ? 'thin' : ''
1311
+ if (over) el.setAttribute('data-panel-dock-left-scrolls', '')
1312
+ else el.removeAttribute('data-panel-dock-left-scrolls')
1313
+ return over
1314
+ }
1315
+
1316
+ // The sidebar half is only a placeholder: the tray moves the cell containers in.
1317
+ function LeftSlot() {
1318
+ const ref = React.useRef(null)
1319
+ React.useEffect(() => {
1320
+ tray.leftSlot = ref.current
1321
+ if (tray.poke) tray.poke()
1322
+ return () => { if (tray.leftSlot === ref.current) tray.leftSlot = null }
1323
+ }, [])
1324
+ return h('div', { 'data-panel-dock-left-slot': '', ref, style: { display: 'contents' } })
1325
+ }
1326
+
1327
+ function TrayHost() {
1328
+ const all = useRegistry()
1329
+ const [anchors, setAnchors] = React.useState(() => measureAnchors())
1330
+ const [scrolls, setScrolls] = React.useState(false)
1331
+ const [, bump] = React.useState(0)
1332
+ const band = React.useRef(null)
1333
+ const measureStack = React.useRef(null)
1334
+ const lastPlacement = React.useRef({ left: [], right: [], inBand: false })
1335
+
1336
+ React.useEffect(() => {
1337
+ tray.poke = () => bump((n) => n + 1)
1338
+ return () => { tray.poke = null }
1339
+ }, [])
1340
+
1341
+ const right = all.filter((panel) => sideOf(panel.id, panel.side) === 'right')
1342
+ const needsBand = right.length > 0
1343
+
1344
+ React.useEffect(() => {
1345
+ // Nothing lives on the right: the anchors are irrelevant, and measuring them is a
1346
+ // full-document scan plus ~20 layout reads. Polling that while every card sits in
1347
+ // the sidebar made the dock the busiest thing on the page for no benefit.
1348
+ if (!needsBand) {
1349
+ setAnchors(null)
1350
+ return undefined
1351
+ }
1352
+ let raf = 0
1353
+ const sync = () => {
1354
+ raf = 0
1355
+ const next = measureAnchors()
1356
+ setAnchors((prev) => (sameAnchors(prev, next) ? prev : next))
1357
+ if (measureStack.current) measureStack.current()
1358
+ }
1359
+ const schedule = () => { if (!raf) raf = requestAnimationFrame(sync) }
1360
+ schedule()
1361
+ window.addEventListener('resize', schedule)
1362
+ // The band's anchors move when the window resizes, when the right sidebar opens or
1363
+ // closes, or when the conversation column is dragged -- all of them resize the
1364
+ // column, so observing it replaces the old 700ms poll. The timer stays as a slow
1365
+ // safety net for anything that moves without changing the column's size.
1366
+ let observer = null
1367
+ if (typeof ResizeObserver !== 'undefined') {
1368
+ observer = new ResizeObserver(schedule)
1369
+ const tabs = document.querySelector('[data-conversation-tabs]')
1370
+ const column = tabs && (tabs.parentElement || tabs)
1371
+ if (column) observer.observe(column)
1372
+ }
1373
+ const timer = setInterval(schedule, 2500)
1374
+ return () => {
1375
+ window.removeEventListener('resize', schedule)
1376
+ if (observer) observer.disconnect()
1377
+ clearInterval(timer)
1378
+ if (raf) cancelAnimationFrame(raf)
1379
+ }
1380
+ }, [needsBand])
1381
+
1382
+ const required = Math.min(MAX_PANEL_WIDTH, Math.max(MIN_WIDTH_FLOOR,
1383
+ right.reduce((widest, panel) => Math.max(widest, panel.minWidth || DEFAULT_MIN_WIDTH), 0)))
1384
+ const plan = planBand(anchors, required)
1385
+ const top = plan.mode === 'page' ? plan.pageTop : (anchors ? anchors.top : 8)
1386
+ const inBand = plan.mode !== 'fallback' && right.length > 0
1387
+ React.useEffect(() => { setFallback(plan.mode === 'fallback') }, [plan.mode])
1388
+
1389
+ // The wheel/click path must not wait for a React render: it re-applies the deck
1390
+ // straight from the last placement it knows about.
1391
+ React.useEffect(() => {
1392
+ deck.resync = () => {
1393
+ const last = lastPlacement.current
1394
+ if (tray.leftStack) syncDeck(tray.leftStack, last.left, true)
1395
+ if (band.current) syncDeck(band.current, last.right, last.inBand)
1396
+ }
1397
+ return () => { deck.resync = null }
1398
+ }, [])
1399
+
1400
+ // Placement: every frame after render, put each cell into the stack that owns it.
1401
+ React.useEffect(() => {
1402
+ const alive = new Set(all.map((panel) => panel.id))
1403
+ dropDeadCells(alive)
1404
+ const wantLeft = []
1405
+ const wantRight = []
1406
+ for (const panel of all) {
1407
+ const side = sideOf(panel.id, panel.side)
1408
+ if (side === 'right' && inBand) wantRight.push(panel.id)
1409
+ else wantLeft.push(panel.id)
1410
+ }
1411
+ if (wantLeft.length && tray.leftSlot) {
1412
+ const stack = leftStackNode()
1413
+ if (stack.parentNode !== tray.leftSlot) tray.leftSlot.appendChild(stack)
1414
+ wantLeft.forEach((id, index) => {
1415
+ const el = cellOf(id)
1416
+ const at = cellAt(stack, index)
1417
+ if (at !== el) stack.insertBefore(el, at || deckBarOf(stack) || null)
1418
+ })
1419
+ } else if (tray.leftStack && tray.leftStack.parentNode) {
1420
+ tray.leftStack.parentNode.removeChild(tray.leftStack)
1421
+ }
1422
+ const bandEl = band.current
1423
+ if (bandEl) {
1424
+ wantRight.forEach((id, index) => {
1425
+ const el = cellOf(id)
1426
+ const at = cellAt(bandEl, index)
1427
+ if (at !== el) bandEl.insertBefore(el, at || deckBarOf(bandEl) || null)
1428
+ })
1429
+ }
1430
+ // Deck last: it needs the cells already in their containers to measure the front
1431
+ // card and to compute the strips.
1432
+ lastPlacement.current = { left: wantLeft, right: wantRight, inBand }
1433
+ if (tray.leftStack) syncDeck(tray.leftStack, wantLeft, true)
1434
+ if (bandEl) syncDeck(bandEl, wantRight, inBand)
1435
+ if (wantLeft.length && !deckOn()) syncLeftStackScroll()
1436
+ })
1437
+
1438
+ // The stack scrolls only when the cards outgrow the column (see SHADOW_GUTTER).
1439
+ React.useEffect(() => {
1440
+ const el = band.current
1441
+ const measure = () => {
1442
+ if (!el) { setScrolls(false); return }
1443
+ const column = Math.max(0, window.innerHeight - 8 - top)
1444
+ const next = stackedHeight(el) > column + 0.5
1445
+ setScrolls((prev) => (prev === next ? prev : next))
1446
+ }
1447
+ measureStack.current = measure
1448
+ measure()
1449
+ // The left stack is not covered by the band's own observer above.
1450
+ if (!deckOn()) syncLeftStackScroll()
1451
+ if (typeof ResizeObserver === 'undefined') return () => { measureStack.current = null }
1452
+ const observer = new ResizeObserver(() => { measure(); syncLeftStackScroll() })
1453
+ if (el) for (const kid of el.children) observer.observe(kid)
1454
+ if (tray.leftStack) observer.observe(tray.leftStack)
1455
+ return () => { observer.disconnect(); measureStack.current = null }
1456
+ }, [inBand, right.length, top])
1457
+
1458
+ // Cards in detached containers look perfectly healthy from the registry side, so
1459
+ // say it out loud once if nothing ever mounted a host for them.
1460
+ React.useEffect(() => {
1461
+ if (all.length === 0) return undefined
1462
+ const timer = setTimeout(() => {
1463
+ if (!tray.leftSlot && !band.current) {
1464
+ try {
1465
+ console.error('[panel-dock] ' + all.length + ' card(s) registered but no host slot is mounted (sidebar footer / overlay).')
1466
+ } catch {}
1467
+ }
1468
+ }, 1500)
1469
+ return () => clearTimeout(timer)
1470
+ }, [all.length])
1471
+
1472
+ React.useEffect(() => () => {
1473
+ for (const el of tray.cells.values()) if (el.parentNode) el.parentNode.removeChild(el)
1474
+ tray.cells.clear()
1475
+ if (tray.leftStack && tray.leftStack.parentNode) tray.leftStack.parentNode.removeChild(tray.leftStack)
1476
+ tray.leftStack = null
1477
+ }, [])
1478
+
1479
+ const nodes = []
1480
+ if (inBand) {
1481
+ const style = {
1482
+ position: 'fixed',
1483
+ top,
1484
+ bottom: 8,
1485
+ display: 'flex',
1486
+ flexDirection: 'column',
1487
+ gap: STACK_GAP,
1488
+ minWidth: 0,
1489
+ boxSizing: 'border-box',
1490
+ overflow: 'visible',
1491
+ pointerEvents: 'none',
1492
+ zIndex: 10000,
1493
+ }
1494
+ style.width = plan.width
1495
+ if (plan.mode === 'inner') style.left = plan.left
1496
+ else style.right = Math.max(GAP, window.innerWidth - plan.rightEdge)
1497
+ if (scrolls) {
1498
+ const gutter = SHADOW_GUTTER
1499
+ style.top = top - gutter
1500
+ style.height = Math.max(0, window.innerHeight - 8 - top) + gutter * 2
1501
+ style.bottom = 'auto'
1502
+ style.width = plan.width + gutter * 2
1503
+ if (style.left !== undefined) style.left -= gutter
1504
+ if (style.right !== undefined) style.right -= gutter
1505
+ style.padding = gutter
1506
+ style.overflowY = 'auto'
1507
+ style.overflowX = 'hidden'
1508
+ style.scrollbarWidth = 'none'
1509
+ }
1510
+ nodes.push(h('div', {
1511
+ key: 'band',
1512
+ 'data-panel-dock-strip': '',
1513
+ 'data-panel-dock-scrolls': scrolls ? '' : undefined,
1514
+ ref: band,
1515
+ style,
1516
+ }))
1517
+ }
1518
+ for (const panel of all) {
1519
+ nodes.push(createPortal(h(CardBoundary, {
1520
+ key: panel.id + ':' + revisionOf(panel.id),
1521
+ id: panel.id,
1522
+ fallback: () => errorCard(panel),
1523
+ }, renderPanel(panel)), cellOf(panel.id), panel.id))
1524
+ }
1525
+ return h(React.Fragment, null, nodes)
1526
+ }
1527
+
1528
+
1529
+ // CardShell: the one shared top bar for a 侧栏卡片 (a card the dock hosts). It is NOT
1530
+ // a layout container -- the card still renders its own frame and body; the shell is
1531
+ // only the row above them: [logo = side toggle] [title] [version] ... [actions].
1532
+ const SHELL_STYLE = {
1533
+ display: 'flex',
1534
+ alignItems: 'center',
1535
+ gap: 6,
1536
+ minWidth: 0,
1537
+ marginBottom: 6,
1538
+ color: 'var(--dsw-alias-label-primary)',
1539
+ }
1540
+ const SHELL_TOGGLE_STYLE = {
1541
+ display: 'inline-flex',
1542
+ alignItems: 'center',
1543
+ justifyContent: 'center',
1544
+ width: 18,
1545
+ height: 18,
1546
+ padding: 0,
1547
+ border: 0,
1548
+ borderRadius: 4,
1549
+ background: 'transparent',
1550
+ color: 'inherit',
1551
+ cursor: 'pointer',
1552
+ flex: '0 0 auto',
1553
+ }
1554
+ const SHELL_TITLE_STYLE = {
1555
+ fontSize: 13,
1556
+ fontWeight: 600,
1557
+ lineHeight: 1.2,
1558
+ whiteSpace: 'nowrap',
1559
+ overflow: 'hidden',
1560
+ textOverflow: 'ellipsis',
1561
+ minWidth: 0,
1562
+ }
1563
+ const SHELL_VERSION_STYLE = {
1564
+ fontSize: 10,
1565
+ fontWeight: 400,
1566
+ lineHeight: 1.2,
1567
+ color: 'var(--dsw-alias-label-secondary)',
1568
+ flex: '0 0 auto',
1569
+ }
1570
+ const SHELL_ACTIONS_STYLE = { display: 'inline-flex', alignItems: 'center', gap: 4, flex: '0 0 auto' }
1571
+
1572
+ // Monochrome logo that doubles as the side toggle: a panel glyph with an arrow
1573
+ // pointing at the side the card would move to.
1574
+ function shellLogo(docked) {
1575
+ return h('svg', {
1576
+ width: 15, height: 15, viewBox: '0 0 16 16', fill: 'none',
1577
+ 'aria-hidden': 'true', focusable: 'false',
1578
+ },
1579
+ h('rect', { x: 1.6, y: 2.6, width: 12.8, height: 10.8, rx: 2.4, stroke: 'currentColor', strokeWidth: 1.3 }),
1580
+ h('path', { d: docked ? 'M10.4 2.8 V13.2' : 'M5.6 2.8 V13.2', stroke: 'currentColor', strokeWidth: 1.3 }),
1581
+ h('path', {
1582
+ d: docked ? 'M7.1 6.4 L5.3 8 L7.1 9.6' : 'M8.9 6.4 L10.7 8 L8.9 9.6',
1583
+ stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round', strokeLinejoin: 'round',
1584
+ }),
1585
+ )
1586
+ }
1587
+
1588
+ // Header only, by design: the card renders its own frame and body *under* this row.
1589
+ // Children are deliberately not rendered -- but silently dropping them would be the
1590
+ // worst kind of bug, so passing them is reported once per card instead of ignored.
1591
+ const shellWarned = new Set()
1592
+
1593
+ function CardShell(props) {
1594
+ const id = props.id
1595
+ if (props.children !== undefined && props.children !== null && !shellWarned.has(id)) {
1596
+ shellWarned.add(id)
1597
+ try {
1598
+ console.warn('[panel-dock] CardShell renders the header row only; put your body next to it, not inside it (card: ' + id + ').')
1599
+ } catch {}
1600
+ }
1601
+ const [, force] = React.useState(0)
1602
+ React.useEffect(() => subscribe(() => force((n) => n + 1)), [])
1603
+ const panel = registry.get(id)
1604
+ const preferred = sideOf(id, panel ? panel.side : 'left')
1605
+ const side = effectiveSide(id)
1606
+ const docked = side === 'right'
1607
+ const blocked = preferred !== side
1608
+ const title = props.title || (panel && panel.title) || id
1609
+ const version = props.version || (panel && panel.version) || null
1610
+ const label = blocked ? T('bandUnavailable') : (docked ? T('toLeft') : T('toRight'))
1611
+ return h('div', {
1612
+ 'data-panel-dock-shell': id,
1613
+ style: Object.assign({}, SHELL_STYLE, props.style),
1614
+ },
1615
+ h('button', {
1616
+ type: 'button',
1617
+ 'data-panel-dock-shell-toggle': '',
1618
+ 'aria-label': label,
1619
+ title: label,
1620
+ disabled: blocked,
1621
+ onClick: () => { try { if (!blocked) toggleSide(id) } catch {} },
1622
+ style: blocked ? Object.assign({}, SHELL_TOGGLE_STYLE, { opacity: 0.4, cursor: 'default' }) : SHELL_TOGGLE_STYLE,
1623
+ }, shellLogo(docked)),
1624
+ h('span', { style: SHELL_TITLE_STYLE, title }, title),
1625
+ version ? h('span', { style: SHELL_VERSION_STYLE }, 'v' + version) : null,
1626
+ h('span', { style: { flex: '1 1 auto', minWidth: 0 } }),
1627
+ props.actions ? h('span', { style: SHELL_ACTIONS_STYLE }, props.actions) : null,
1628
+ )
1629
+ }
1630
+
1631
+
1632
+ // ---- crash isolation ----
1633
+ // The host treats a slot entry that throws as broken and drops the *whole entry*:
1634
+ // one bad card used to take every card down with it, and nothing recovered until a
1635
+ // reload. Each card therefore gets its own boundary, and each slot entry is sealed
1636
+ // so a dock bug cannot be mistaken for a broken host slot.
1637
+ class CardBoundary extends React.Component {
1638
+ constructor(props) {
1639
+ super(props)
1640
+ this.state = { failed: false }
1641
+ }
1642
+ static getDerivedStateFromError() {
1643
+ return { failed: true }
1644
+ }
1645
+ componentDidCatch(error) {
1646
+ try { console.error('[panel-dock] card crashed and was isolated: ' + this.props.id, error) } catch {}
1647
+ }
1648
+ render() {
1649
+ if (!this.state.failed) return this.props.children
1650
+ return this.props.fallback ? this.props.fallback() : null
1651
+ }
1652
+ }
1653
+
1654
+ function errorCard(panel) {
1655
+ return h('div', {
1656
+ 'data-panel-dock-item': panel.id,
1657
+ 'data-panel-dock-error': '',
1658
+ style: {
1659
+ width: '100%', minWidth: 0, boxSizing: 'border-box', padding: '8px 9px',
1660
+ border: '1px solid var(--dsw-alias-border-l1)', borderRadius: 12,
1661
+ background: 'var(--dsw-alias-bg-layer-1)',
1662
+ color: 'var(--dsw-alias-label-secondary)',
1663
+ fontSize: 11, lineHeight: 1.35, pointerEvents: 'auto',
1664
+ },
1665
+ }, (panel.title || panel.id) + ' · ' + T('cardCrashed'))
1666
+ }
1667
+
1668
+ // Re-registering an id means a new component: remount the boundary instead of leaving
1669
+ // it stuck in the failed state forever.
1670
+ const revisions = new Map()
1671
+ function revisionOf(id) {
1672
+ return revisions.get(id) || 0
1673
+ }
1674
+
1675
+ // A sealed slot entry renders nothing instead of throwing into the host.
1676
+ function seal(Component, name, Alt) {
1677
+ return function SealedSlot() {
1678
+ return h(CardBoundary, { id: name, fallback: Alt ? () => h(Alt) : null }, h(Component))
1679
+ }
1680
+ }
1681
+
1682
+ function effectiveSide(id) {
1683
+ const panel = registry.get(id)
1684
+ const preferred = sideOf(id, panel ? panel.side : 'left')
1685
+ return preferred === 'right' && placement.fallback ? 'left' : preferred
1686
+ }
1687
+
1688
+ // The band floats over the transcript, so a card that swallows the pointer is
1689
+ // worse than one that merely looks solid. Hovering dims it to show what it covers;
1690
+ // it stays hit-testable (click-through is self-contradictory in CSS: an element
1691
+ // that ignores the pointer can never observe hover, so it would flicker).
1692
+ const BAND_CSS = [
1693
+ // Hover used to fade the whole card to 45%, text included. Only the surface goes
1694
+ // translucent now: the content stays at full opacity, so the card reads as glass
1695
+ // over the transcript instead of as a disabled control.
1696
+ '[data-panel-dock-strip] [data-panel-dock-cell] > [data-panel-dock-frame]{',
1697
+ 'transition:background-color 140ms ease,box-shadow 140ms ease,border-color 140ms ease;}',
1698
+ // !important is required: the frame's background/border/shadow are written inline by
1699
+ // renderPanel, and an inline declaration beats a plain CSS rule (measured: the card
1700
+ // stayed opaque with the rule present).
1701
+ // Stacked mode is for cycling cards: a card that fades while you reach for the
1702
+ // wheel only adds noise, so the glass hover is limited to the plain column.
1703
+ '[data-panel-dock-strip]:not([data-panel-dock-deck]) [data-panel-dock-cell]:hover > [data-panel-dock-frame]{',
1704
+ 'background:color-mix(in srgb,var(--dsw-specific-sidebar-fill,#f9fafb) 34%,transparent) !important;',
1705
+ 'border-color:transparent !important;box-shadow:none !important;}',
1706
+ // ---- deck ----
1707
+ '[data-panel-dock-deck]{position:relative;transition:height 200ms cubic-bezier(.2,.8,.2,1)}',
1708
+ '[data-panel-dock-deck] > [data-panel-dock-cell]{position:absolute;left:0;right:0;top:0;',
1709
+ 'transition:transform 200ms cubic-bezier(.2,.8,.2,1),opacity 160ms ease}',
1710
+ // Rear cards are only strips: keep them clickable but not visually loud.
1711
+
1712
+ '[data-panel-dock-deck-bar][data-panel-dock-hidden]{display:none}',
1713
+ // Rear cards are visible but not operable: their controls (side toggle, refresh,
1714
+ // links) must not fire while the card sits behind. Clicks fall through to the card
1715
+ // body, which promotes that card to the front.
1716
+ // The card tone is the INVERSE of its column: the sidebar is #f9fafb so its cards are
1717
+ // white, the main page is #ffffff so band cards are #f9fafb. That is the contrast
1718
+ // mechanism the operator designed; a ring was the wrong answer.
1719
+ // The card tone is derived from the host token, not hardcoded: `#ffffff` in dark mode
1720
+ // is a glaring white card under light text (the unreadable state on the dark build).
1721
+ // Light theme: sidebar #f9fafb -> card almost white; band #fff -> card #f9fafb.
1722
+ // Dark theme: both lift a little off the surrounding surface instead of going white.
1723
+ '[data-panel-dock-left] [data-panel-dock-frame]{background:#ffffff !important}',
1724
+ '[data-panel-dock-strip] [data-panel-dock-frame]{',
1725
+ 'background:color-mix(in srgb,var(--dsw-specific-sidebar-fill,#f9fafb) 94%,#ffffff) !important}',
1726
+ // Dark palette: `#ffffff` under the light text of a dark host is the unreadable state.
1727
+ // These are keyed on the attribute the renderer sets from hostIsDark().
1728
+ '[data-panel-dock-frame][data-pd-dark]{',
1729
+ 'background:#26282b !important;border-color:rgba(255,255,255,.10) !important;',
1730
+ 'box-shadow:0 3px 12px 0 rgba(0,0,0,.55) !important;color-scheme:dark}',
1731
+ '[data-panel-dock-left] [data-panel-dock-frame][data-pd-dark]{background:#2e3135 !important}',
1732
+ '[data-panel-dock-strip] [data-panel-dock-frame][data-pd-dark]{background:#232528 !important}',
1733
+ '[data-panel-dock-deck] > [data-panel-dock-cell][data-panel-dock-rear] button,',
1734
+ '[data-panel-dock-deck] > [data-panel-dock-cell][data-panel-dock-rear] a,',
1735
+ '[data-panel-dock-deck] > [data-panel-dock-cell][data-panel-dock-rear] input,',
1736
+ '[data-panel-dock-deck] > [data-panel-dock-cell][data-panel-dock-rear] select,',
1737
+ '[data-panel-dock-deck] > [data-panel-dock-cell][data-panel-dock-rear] textarea,',
1738
+ '[data-panel-dock-deck] > [data-panel-dock-cell][data-panel-dock-rear] summary,',
1739
+ '[data-panel-dock-deck] > [data-panel-dock-cell][data-panel-dock-rear] [role="button"],',
1740
+ '[data-panel-dock-deck] > [data-panel-dock-cell][data-panel-dock-rear] [tabindex]{',
1741
+ 'pointer-events:none;}',
1742
+ // The strip is easy to miss at 10px when the pointer approaches from the middle of
1743
+ // the card, so a transparent tab hangs below the centre (ends untouched, nothing
1744
+ // painted): the middle catches the pointer 16px lower, the sides behave as before.
1745
+ '[data-panel-dock-deck-bar]::after{content:"";position:absolute;left:25%;right:25%;',
1746
+ 'top:100%;height:16px;border-radius:0 0 10px 10px;}',
1747
+ // frame:true means the dock owns the rectangle, so the card body must not paint a
1748
+ // second one. Cards get this for free -- a card that keeps its own border shows a
1749
+ // box inside a box (seen live: loci drew 12px radius + white fill inside the frame).
1750
+ // !important is deliberate and scoped: the card's own `.card-root` rule has equal
1751
+ // specificity and lands later in the cascade, so without it the frame keeps a box
1752
+ // inside a box (verified: padding/border/radius survived the plain rule).
1753
+ // Surface AND outer inset: the frame already supplies 10px 9px 8px, so a card that also
1754
+ // pads its own root shifts its header by a different amount per card (measured: USTC 17px,
1755
+ // Codex 18px, Memory 9px from the card edge) -- that is the "headers don't line up" report.
1756
+ // Inner blocks keep their own padding; only the root's is dropped.
1757
+ '[data-panel-dock-frame] > *{padding:0 !important;margin:0 !important;border:0 !important;',
1758
+ 'border-radius:0 !important;background:transparent !important;box-shadow:none !important;}',
1759
+ // ---- affordance: the card edge drops into a gradient band ----
1760
+ // The affordance is a glass overlay, not a row: it takes no layout space, sits on
1761
+ // the column's own top edge (not above it) and stays invisible until the pointer
1762
+ // arrives -- a permanently visible bar read as "the column got taller".
1763
+ // pointer-events:auto is essential: the band is pointer-events:none, and a child
1764
+ // inherits that, so the strip was unclickable (reported as "click does nothing").
1765
+ // Exactly the card's width: the strip used to stick out 4px on each side, which read
1766
+ // as a floating bar rather than a drawer pulled out of the card. Top corners follow
1767
+ // the card radius (12) so the square edge does not poke out of the rounded corner.
1768
+ '[data-panel-dock-deck-bar]{--pd-chev:45deg;position:absolute;left:0;right:0;top:0;height:10px;',
1769
+ 'z-index:400;box-sizing:border-box;pointer-events:auto;cursor:pointer;',
1770
+ 'display:flex;align-items:center;justify-content:center;gap:3px;',
1771
+ // Top corners follow the card (12px); the bottom edge is square on purpose --
1772
+ // it reads as a drawer face pulled out of the card, not a floating pill.
1773
+ 'border-radius:12px 12px 0 0;border-bottom:1px solid transparent;',
1774
+ 'background:linear-gradient(180deg,rgba(0,0,0,0),rgba(0,0,0,0));',
1775
+ 'opacity:0;transition:height 170ms ease,opacity 140ms ease,background 170ms ease,',
1776
+ 'border-color 170ms ease;-webkit-backdrop-filter:blur(0px);backdrop-filter:blur(0px);}',
1777
+ '[data-panel-dock-deck-bar]:hover,[data-panel-dock-deck-bar]:focus-visible{',
1778
+ 'height:30px;opacity:1;',
1779
+ // Real frosted glass needs a *translucent* veil: at 96% the fill hid everything
1780
+ // behind it, so backdrop-filter had nothing to blur and the strip read as opaque.
1781
+ // Keep the veil low-opacity, blur hard, and let a white top highlight carry the
1782
+ // glass edge; the darker tone is now only the bottom hairline.
1783
+ 'background:',
1784
+ 'linear-gradient(180deg,rgba(255,255,255,.26),rgba(255,255,255,.06)),',
1785
+ 'linear-gradient(180deg,',
1786
+ 'color-mix(in srgb,var(--dsw-specific-sidebar-fill,#f9fafb) 52%,transparent),',
1787
+ 'color-mix(in srgb,var(--dsw-specific-sidebar-fill,#f9fafb) 28%,transparent));',
1788
+ 'border-bottom-color:rgba(15,23,42,.09);',
1789
+ 'box-shadow:inset 0 1px 0 rgba(255,255,255,.55),inset 0 -1px 0 rgba(15,23,42,.04);',
1790
+ '-webkit-backdrop-filter:blur(14px) saturate(1.25);backdrop-filter:blur(14px) saturate(1.25);}',
1791
+ '[data-panel-dock-deck-bar] > i{display:block;width:7px;height:7px;margin-top:-6px;',
1792
+ 'border-right:1.8px solid var(--dsw-alias-label-secondary,rgba(15,23,42,.62));',
1793
+ 'border-bottom:1.8px solid var(--dsw-alias-label-secondary,rgba(15,23,42,.62));',
1794
+ 'transform:rotate(45deg);opacity:0;',
1795
+ 'transition:opacity 140ms ease;animation:pdDeckChevron 1.2s ease-in-out infinite}',
1796
+ '[data-panel-dock-deck-bar]:hover > i,[data-panel-dock-deck-bar]:focus-visible > i{opacity:.92}',
1797
+ // Deck already on: the same press unfolds the stack, so the chevrons point UP.
1798
+ // Only the variable changes -- the running keyframes read it every frame.
1799
+ '[data-panel-dock-deck-bar][data-panel-dock-deck-on]{--pd-chev:-135deg}',
1800
+ '[data-panel-dock-deck-bar][data-panel-dock-deck-on] > i{margin-top:5px}',
1801
+ '@media (prefers-reduced-motion: reduce){[data-panel-dock-deck-bar] > i{animation:none}}',
1802
+ '[data-panel-dock-deck-bar] > i:nth-child(2){animation-delay:.14s}',
1803
+ '[data-panel-dock-deck-bar] > i:nth-child(3){animation-delay:.28s}',
1804
+ // The direction lives in a custom property: the keyframes below run every frame and
1805
+ // used to hard-code rotate(45deg), which silently overrode the deck-on -135deg --
1806
+ // the strip pointed down even while the cards were stacked.
1807
+ '@keyframes pdDeckChevron{0%{opacity:.15;transform:translateY(-2px) rotate(var(--pd-chev,45deg))}',
1808
+ '50%{opacity:.95;transform:translateY(2px) rotate(var(--pd-chev,45deg))}',
1809
+ '100%{opacity:.15;transform:translateY(-2px) rotate(var(--pd-chev,45deg))}}',
1810
+ '@media (prefers-reduced-motion: reduce){',
1811
+ '[data-panel-dock-strip] [data-panel-dock-cell]{transition:none}',
1812
+ '[data-panel-dock-deck]{transition:none}',
1813
+ '[data-panel-dock-deck] > [data-panel-dock-cell]{transition:none}}',
1814
+ ].join('')
1815
+ function apply(ctx) {
1816
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-panel-dock: locale')
1817
+ // Dock-level affordance: every card in the band dims on hover without opting in.
1818
+ ctx.effect(() => {
1819
+ if (typeof document === 'undefined') return undefined
1820
+ const style = document.createElement('style')
1821
+ style.setAttribute('data-dsh-panel-dock', 'band-hover')
1822
+ style.textContent = BAND_CSS
1823
+ document.head.appendChild(style)
1824
+ return () => { try { style.remove() } catch {} }
1825
+ }, 'dsh-panel-dock: band css')
1826
+ T = ctx.locale.bind(NS)
1827
+ // The tray keeps cards mounted when they change hosts; without portals the dock
1828
+ // falls back to rendering each host directly (0.3.x behaviour, cards remount).
1829
+ const leftHost = createPortal ? seal(LeftSlot, 'panel-dock-left', LeftHost) : seal(LeftHost, 'panel-dock-left')
1830
+ const rightHost = createPortal ? seal(TrayHost, 'panel-dock-right', RightHost) : seal(RightHost, 'panel-dock-right')
1831
+ ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register({
1832
+ name: 'sidebar.footer.action', id: 'panel-dock-left', order: 900, locale: NS,
1833
+ }, leftHost))
1834
+ ctx.slots.inject('shell.overlay', () => ctx.slots.register({
1835
+ name: 'shell.overlay', id: 'panel-dock-right', order: 40, locale: NS,
1836
+ }, rightHost))
1837
+ const api = {
1838
+ version: VERSION,
1839
+ define,
1840
+ placementOf: effectiveSide,
1841
+ // Consumers use this to decide whether their native fallback must draw: with the
1842
+ // dock present but their registration missing, neither side used to render.
1843
+ has: (id) => registry.has(id),
1844
+ panel: (id) => {
1845
+ const p = registry.get(id)
1846
+ return p ? { id: p.id, title: p.title, order: p.order, side: sideOf(p.id, p.side), effective: effectiveSide(p.id), minWidth: p.minWidth, version: p.version, frame: frameEnabled(p) } : null
1847
+ },
1848
+ panels: () => panels().map((p) => ({ id: p.id, title: p.title, order: p.order, side: sideOf(p.id, p.side), effective: effectiveSide(p.id), minWidth: p.minWidth, version: p.version, frame: frameEnabled(p) })),
1849
+ CardShell,
1850
+ getSide: (id) => sideOf(id, registry.has(id) ? registry.get(id).side : 'left'),
1851
+ setSide,
1852
+ toggleSide,
1853
+ subscribe,
1854
+ }
1855
+ ctx.effect(() => {
1856
+ try { window.__dshPanelDock = api } catch {}
1857
+ // Disabling the plugin must hand the panels back to their own fallbacks, so the
1858
+ // global has to disappear with us -- leaving it behind silently keeps every card
1859
+ // believing the dock is alive.
1860
+ return () => {
1861
+ try { if (window.__dshPanelDock === api) delete window.__dshPanelDock } catch {}
1862
+ }
1863
+ }, 'dsh-panel-dock: global')
1864
+ }
1865
+
1866
+ return { inject: ['slots', 'locale'], apply }
1867
+ },
1868
+ })