dsh-conversation-float 0.0.0-stage → 0.1.2

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,1471 @@
1
+ /**
2
+ * Client half of the conversation-float bundle.
3
+ *
4
+ * The floating window is DSH's own: the right-sidebar dock kit can host a tab
5
+ * in a floating panel, and its controller accepts `destination: 'float'`. One
6
+ * click on the entry opens our tab type straight into that panel — no dragging,
7
+ * no browser window, no second process.
8
+ *
9
+ * The panel's body hosts the live Conversation column: the column is moved into
10
+ * the panel (same document, same React root, so events and reconciliation keep
11
+ * working) and moved back to its seat when the panel closes.
12
+ *
13
+ * While the float is on screen it can be dragged onto three drop bands:
14
+ *
15
+ * left the float is stowed — still mounted, hidden — and the left sidebar
16
+ * grows a row that brings it back; the centre column stays empty,
17
+ * exactly as it is while the float is on screen
18
+ * center the float closes and the Conversation returns to its column
19
+ * right the tab is handed to the right sidebar, where DSH docks it
20
+ *
21
+ * The bands are measured once per drag. Holding the press for {@link DWELL_MS}
22
+ * switches the drag into judging: from that moment the outline follows the band
23
+ * under the pointer and the drop takes that band. One wait per drag, never one
24
+ * per band. The outline uses `transform`, so repainting costs no layout pass.
25
+ */
26
+ window.__ModuleLoader__.load({
27
+ id: 'dsh-conversation-float',
28
+ factory(require) {
29
+ 'use strict'
30
+
31
+ const React = require('react')
32
+ const h = React.createElement
33
+
34
+ const NS = 'dsh-conversation-float'
35
+
36
+ /**
37
+ * Copy for every locale DSH ships. The word for the Conversation is read
38
+ * from this table only, so the panel title, the sidebar row and the entry
39
+ * button all say what the View tab strip says in the same language.
40
+ */
41
+ const COPY = {
42
+ "zh": {
43
+ "conversation": "会话",
44
+ "floatTitle": "会话浮窗",
45
+ "showDsh": "显示 DSH 界面",
46
+ "stow": "放进左栏",
47
+ "center": "回到中间",
48
+ "dock": "停到右栏",
49
+ "description": "把会话视图做成 DSH 自带的浮窗:拖到左边收进左栏抽屉、拖到中间回到中栏、拖到右边停进右侧栏。"
50
+ },
51
+ "en": {
52
+ "conversation": "Conversation",
53
+ "floatTitle": "Conversation float",
54
+ "showDsh": "Show DSH",
55
+ "stow": "Stow in the left sidebar",
56
+ "center": "Return to the middle",
57
+ "dock": "Dock in the right sidebar",
58
+ "description": "Turns the Conversation view into DSH own floating panel: drag it left to stow it in the sidebar drawer, centre to return it to the middle column, right to dock it in the right sidebar."
59
+ },
60
+ "de": {
61
+ "conversation": "Konversation",
62
+ "floatTitle": "Konversations-Float",
63
+ "showDsh": "DSH anzeigen",
64
+ "stow": "In der linken Seitenleiste ablegen",
65
+ "center": "Zurück in die Mitte",
66
+ "dock": "In der rechten Seitenleiste andocken",
67
+ "description": "Macht die Konversationsansicht zu DSH eigenem schwebenden Panel: nach links ziehen legt sie in der linken Seitenleiste ab, Mitte bringt sie zurück, rechts dockt sie rechts an."
68
+ },
69
+ "es": {
70
+ "conversation": "Conversación",
71
+ "floatTitle": "Ventana flotante de conversación",
72
+ "showDsh": "Mostrar DSH",
73
+ "stow": "Guardar en la barra izquierda",
74
+ "center": "Volver al centro",
75
+ "dock": "Acoplar en la barra derecha",
76
+ "description": "Convierte la vista de conversación en el panel flotante propio de DSH: a la izquierda se guarda en la barra lateral, al centro vuelve a la columna central, a la derecha se acopla a la barra derecha."
77
+ },
78
+ "fr": {
79
+ "conversation": "Conversation",
80
+ "floatTitle": "Fenêtre flottante de conversation",
81
+ "showDsh": "Afficher DSH",
82
+ "stow": "Placer dans la barre latérale gauche",
83
+ "center": "Revenir au centre",
84
+ "dock": "Ancrer dans la barre latérale droite",
85
+ "description": "Transforme la vue de conversation en panneau flottant propre à DSH : à gauche il se range dans la barre latérale, au centre il revient dans la colonne, à droite il s ancre à droite."
86
+ },
87
+ "ja": {
88
+ "conversation": "会話",
89
+ "floatTitle": "会話フロート",
90
+ "showDsh": "DSH を表示",
91
+ "stow": "左サイドバーにしまう",
92
+ "center": "中央に戻す",
93
+ "dock": "右サイドバーにドッキング",
94
+ "description": "会話ビューを DSH 自身のフロートパネルにします。左へドラッグで左サイドバーに収納、中央で中央列に戻り、右で右サイドバーにドッキングします。"
95
+ },
96
+ "pt": {
97
+ "conversation": "Conversa",
98
+ "floatTitle": "Janela flutuante da conversa",
99
+ "showDsh": "Mostrar DSH",
100
+ "stow": "Guardar na barra lateral esquerda",
101
+ "center": "Voltar ao centro",
102
+ "dock": "Ancorar na barra lateral direita",
103
+ "description": "Transforma a vista de conversa no painel flutuante do próprio DSH: à esquerda guarda na barra lateral, no centro volta à coluna central, à direita ancora na barra direita."
104
+ },
105
+ "ru": {
106
+ "conversation": "Беседа",
107
+ "floatTitle": "Плавающее окно беседы",
108
+ "showDsh": "Показать DSH",
109
+ "stow": "Убрать в левую панель",
110
+ "center": "Вернуть в центр",
111
+ "dock": "Закрепить в правой панели",
112
+ "description": "Превращает вид беседы в собственное плавающее окно DSH: влево — убрать в левую панель, в центр — вернуть в средний столбец, вправо — закрепить в правой панели."
113
+ }
114
+ }
115
+
116
+ const LOCALES = ['zh', 'en', 'de', 'es', 'fr', 'ja', 'pt', 'ru']
117
+
118
+ function localeKey() {
119
+ const fromDocument = (document.documentElement.lang || '').toLowerCase().slice(0, 2)
120
+ const fromBrowser = (navigator.language || '').toLowerCase().slice(0, 2)
121
+ const key = LOCALES.includes(fromDocument) ? fromDocument : fromBrowser
122
+ return LOCALES.includes(key) ? key : 'en'
123
+ }
124
+
125
+ function t(key) {
126
+ const table = COPY[localeKey()] ?? COPY.en
127
+ return table[key] ?? COPY.en[key] ?? key
128
+ }
129
+ const ANCHOR_ATTR = 'data-dsh-conversation-float-anchor'
130
+ const CHAT_ID = 'conversation-float-panel'
131
+ const CHAT_KIND = 'conversation-float-panel'
132
+ /** A resource address our own tab type claims; the panel is opened by it. */
133
+ const CHAT_ADDRESS = 'dsh-resource://conversation-float'
134
+ /** The left sidebar row, and the main-panel key it addresses. */
135
+ const DOCK_ROW_ID = 'conversation-float'
136
+ /** How long a band must be held before it draws and before it can land. */
137
+ const DWELL_MS = 1200
138
+ /** The dock kit's own marker for a floating panel. */
139
+ const FLOAT_ATTR = 'data-dockkit-float'
140
+ /** Set on the float panel while it is stowed in the left drawer. */
141
+ const STOW_ATTR = 'data-dsh-conversation-float-stowed'
142
+ /** Marks the float that hosts our tab, so our rules hit no other panel. */
143
+ const OWN_FLOAT_ATTR = 'data-dsh-conversation-float-float'
144
+ /** Set on every frame column that the float is temporarily hiding. */
145
+ const CHROME_ATTR = 'data-dsh-conversation-float-chromeless'
146
+
147
+ let sidebarRight = null
148
+ let layout = null
149
+ let movedColumn = null
150
+ let movedFrom = null
151
+ /** Whether the left sidebar currently holds a re-opener for the float. */
152
+ let dockedLeft = false
153
+ /** Whether the rest of DSH is currently hidden behind the float. */
154
+ let chromeless = false
155
+
156
+ /** Re-render subscribers: the entry button says one thing per state. */
157
+ const stateListeners = new Set()
158
+
159
+ function notifyState() {
160
+ for (const fn of stateListeners) fn()
161
+ }
162
+ /** Set when the hide was requested before the float finished mounting. */
163
+ let pendingChromeless = false
164
+ /** The last sane band geometry, kept for when the columns are hidden. */
165
+ let lastBand = null
166
+ /** Sidebar state captured when the float opened; restored when it closes. */
167
+ let savedChrome = null
168
+ /** Set when the user changed a sidebar while the float was open. */
169
+ let chromeTouched = false
170
+ /** How long after a press or a key a column change still counts as the user's. */
171
+ const GESTURE_WINDOW = 900
172
+ /** How long the float's own force-open needs to settle before sampling. */
173
+ const FORCE_SETTLE_MS = 1200
174
+ /** The last time the user pressed a key or a mouse button, in ms. */
175
+ let gestureAt = 0
176
+ /** While the plugin moves the columns itself, changes are not the user's. */
177
+ let holdOffUntil = 0
178
+ /** Set while docking to the right sidebar: the column is not going home. */
179
+ let dockingRight = false
180
+ /** Set while the float is being reopened from the drawer. */
181
+ let suspendRestore = false
182
+ /** Disposer of the `sidebar.panellist` row, while it is registered. */
183
+ let dockRow = null
184
+ /** The drop preview overlay, created on demand. */
185
+ let preview = null
186
+
187
+ /* ------------------------------------------------------- the live column */
188
+
189
+ function findColumn() {
190
+ if (movedColumn !== null && movedColumn.isConnected) return movedColumn
191
+ const candidates = [
192
+ document.querySelector('[data-conversation-session]'),
193
+ document.querySelector(`[${ANCHOR_ATTR}]`),
194
+ document.querySelector('[data-conversation-header-corner]'),
195
+ document.querySelector('[data-conversation-tabs]'),
196
+ ]
197
+ for (const anchor of candidates) {
198
+ if (anchor === null) continue
199
+ let node = anchor
200
+ while (node.parentElement !== null) {
201
+ const parent = node.parentElement
202
+ if (parent.querySelector(':scope > [data-shell-overlay]') !== null) return node
203
+ node = parent
204
+ }
205
+ }
206
+ return null
207
+ }
208
+
209
+ /** DSH's layout grid: every panel edge lands on a multiple of it. */
210
+ const GRID = 8
211
+ /**
212
+ * The float's size: 450 x 720 by request, never larger than the room the
213
+ * window actually has. Asking for more makes the dock kit clamp on its own
214
+ * and hands back a half-sized panel with no room left for the messages.
215
+ */
216
+ function floatSize() {
217
+ return {
218
+ width: Math.max(320, Math.min(450, window.innerWidth - 80)),
219
+ height: Math.max(320, Math.min(720, window.innerHeight - 80)),
220
+ }
221
+ }
222
+
223
+ /** Upper-left corner of that seat: centred, snapped, clear of the frame. */
224
+ function floatSeat(size) {
225
+ const snap = (value) => Math.max(0, Math.round(value / GRID) * GRID)
226
+ return {
227
+ x: snap((window.innerWidth - size.width) / 2),
228
+ y: Math.max(48, snap((window.innerHeight - size.height) / 2)),
229
+ }
230
+ }
231
+
232
+ /**
233
+ * Give the float a readable size on open. DSH's dock kit builds a fresh
234
+ * float at a small default; the plugin cannot write the panel's inline box,
235
+ * but the kit exposes the very intent its own resize drag dispatches:
236
+ * `sidebarRight.require()` -> `actions.resizeFloat(sessionId, paneId, rect)`.
237
+ * The pane id is the float element's own `data-dockkit-float` value.
238
+ */
239
+ function sizeFloat() {
240
+ const panel = floatPanel()
241
+ if (panel === null) return
242
+ const paneId = panel.getAttribute(FLOAT_ATTR) ?? document.querySelector(`[${FLOAT_ATTR}]`)?.getAttribute(FLOAT_ATTR)
243
+ if (paneId === null || paneId === undefined) return
244
+ let seat = null
245
+ try {
246
+ seat = sidebarRight?.require?.() ?? null
247
+ } catch {
248
+ seat = null
249
+ }
250
+ if (seat === null) {
251
+ // The mounted-session shortcut can be missing right after a docked tab
252
+ // is floated again; fall back to the per-session action face.
253
+ try {
254
+ const sessionId = sidebarRight?.mounted?.getSnapshot?.()
255
+ const actions = sessionId === undefined ? undefined : sidebarRight?.actionsFor?.(sessionId)
256
+ if (actions !== undefined && actions !== null) seat = { sessionId, actions }
257
+ } catch {
258
+ seat = null
259
+ }
260
+ }
261
+ if (seat === null || typeof seat.actions?.resizeFloat !== 'function') return
262
+ const size = floatSize()
263
+ const corner = floatSeat(size)
264
+ const rect = { ...corner, width: size.width, height: size.height }
265
+ try {
266
+ seat.actions.resizeFloat(seat.sessionId, paneId, rect)
267
+ } catch (error) {
268
+ console.warn('[conversation-float] could not size the floating panel:', error)
269
+ }
270
+ }
271
+ /** The session's dock-kit action face, or null when it is not reachable. */
272
+ function sessionSeat() {
273
+ try {
274
+ const direct = sidebarRight?.require?.()
275
+ if (direct !== undefined && direct !== null) return direct
276
+ } catch {
277
+ /* fall through to the per-session face */
278
+ }
279
+ try {
280
+ const sessionId = sidebarRight?.mounted?.getSnapshot?.()
281
+ const actions = sessionId === undefined ? undefined : sidebarRight?.actionsFor?.(sessionId)
282
+ if (actions !== undefined && actions !== null) return { sessionId, actions }
283
+ } catch {
284
+ return null
285
+ }
286
+ return null
287
+ }
288
+
289
+ /** Float our tab for real, with the size we want. */
290
+ function floatExistingTab() {
291
+ if (floatPanel() !== null) {
292
+ sizeFloat()
293
+ return true
294
+ }
295
+ const tabId = floatTabId()
296
+ if (tabId === null) return false
297
+ const seat = sessionSeat()
298
+ if (seat === null || typeof seat.actions?.floatTab !== 'function') return false
299
+ const size = floatSize()
300
+ const corner = floatSeat(size)
301
+ try {
302
+ seat.actions.floatTab(seat.sessionId, tabId, { ...corner, width: size.width, height: size.height })
303
+ return true
304
+ } catch (error) {
305
+ console.warn('[conversation-float] could not float the docked tab:', error)
306
+ return false
307
+ }
308
+ }
309
+ function attachColumn(container) {
310
+ const column = findColumn()
311
+ if (column === null || container === null) return null
312
+ movedFrom = { parent: column.parentNode, next: column.nextSibling }
313
+ movedColumn = column
314
+ column.style.width = "100%"
315
+ column.style.height = "100%"
316
+ column.style.minWidth = "0"
317
+ column.style.minHeight = "0"
318
+ column.style.overflow = "hidden"
319
+ container.appendChild(column)
320
+ const ownPanel = floatPanel()
321
+ if (ownPanel !== null) ownPanel.setAttribute(OWN_FLOAT_ATTR, '')
322
+ // The dock kit gives a new float its own seat; ask it — through the same
323
+ // intent its own resize drag uses — for the configured one.
324
+ sizeFloat()
325
+
326
+ // The float body is mounted now, so a hide that was waiting for it can be
327
+ // applied against a real float element.
328
+ if (pendingChromeless) setChromeless(true)
329
+ return column
330
+ }
331
+
332
+
333
+ /** The frame's middle column, used when the recorded home was re-rendered. */
334
+ function currentCenter() {
335
+ const overlay = document.querySelector('[data-shell-overlay]')
336
+ const frame = overlay === null ? null : overlay.parentElement
337
+ if (frame === null) return null
338
+ for (const child of Array.from(frame.children)) {
339
+ if (child === frame.firstElementChild) continue
340
+ if (child.hasAttribute('data-rightbar-col')) continue
341
+ if (child.hasAttribute('data-shell-bottom')) continue
342
+ if (child.hasAttribute('data-shell-overlay')) continue
343
+ if (child.hasAttribute('data-shell-leading')) continue
344
+ return child
345
+ }
346
+ return null
347
+ }
348
+
349
+ function detachColumn() {
350
+ const column = movedColumn
351
+ const home = movedFrom
352
+ movedColumn = null
353
+ movedFrom = null
354
+ for (const el of document.querySelectorAll(`[${OWN_FLOAT_ATTR}]`)) el.removeAttribute(OWN_FLOAT_ATTR)
355
+ // The float is leaving the screen: the rest of DSH has to come back.
356
+ if (chromeless) setChromeless(false)
357
+ // A float that goes home hands the sidebars back as they were — but only
358
+ // when it really goes home. Moving the live column between hosts (back
359
+ // out of the left drawer, a remounted float body) also detaches it for
360
+ // a frame; restoring there would collapse the sidebars under a float
361
+ // that is still on screen.
362
+ if (!dockingRight && !suspendRestore) scheduleRestoreChrome()
363
+ dockingRight = false
364
+ if (column === null) return
365
+ column.style.width = ''
366
+ column.style.height = ''
367
+ column.style.minWidth = ''
368
+ column.style.minHeight = ''
369
+ column.style.overflow = ''
370
+ if (home !== null && home.parent !== null && home.parent.isConnected) {
371
+ home.parent.insertBefore(column, home.next)
372
+ return
373
+ }
374
+ // The recorded seat is gone (the panel took it down with it): put the
375
+ // column back in the middle column so the session is never lost.
376
+ const center = currentCenter()
377
+ if (center !== null) center.appendChild(column)
378
+ }
379
+
380
+ /**
381
+ * A closed floating panel can take our body down without running its
382
+ * cleanup first, so the column is watched directly: as soon as its container
383
+ * leaves the document it goes home.
384
+ */
385
+ function watchColumn() {
386
+ /** The float element the last repair ran against. */
387
+ let seenFloat = null
388
+ /** The float whose fixed size was last applied. */
389
+ let sizedFloat = null
390
+ /** Attempts made to settle that float size. */
391
+ let sizeTries = 0
392
+ let seenParent = null
393
+ let seenHost = null
394
+ let frame = 0
395
+ const check = () => {
396
+ frame = 0
397
+ if (movedColumn !== null && !movedColumn.isConnected) detachColumn()
398
+ const panel = floatPanel()
399
+ // Never stay hidden without a float: that is a blank window.
400
+ if (chromeless && panel === null) setChromeless(false)
401
+ // The repairs below walk the whole frame, so they run only when the
402
+ // float moves house (a new panel, a new parent column, or a new body)
403
+ // and never on every mutation a drag produces.
404
+ const parent = panel === null ? null : panel.parentElement
405
+ const host = panel === null ? null : panel.querySelector(".dsw-host")
406
+ if (panel !== null) {
407
+ if (panel !== sizedFloat) {
408
+ sizedFloat = panel
409
+ sizeTries = 0
410
+ }
411
+ const want = floatSize()
412
+ const box = panel.getBoundingClientRect()
413
+ const off = Math.abs(box.width - want.width) > 24 || Math.abs(box.height - want.height) > 24
414
+ if (off && sizeTries < 4) {
415
+ sizeTries += 1
416
+ sizeFloat()
417
+ }
418
+ }
419
+ if (panel !== seenFloat || parent !== seenParent || host !== seenHost) {
420
+ seenFloat = panel
421
+ seenParent = parent
422
+ seenHost = host
423
+ if (panel !== null) {
424
+ healFloatBody()
425
+ if (chromeless) refreshChromeless()
426
+ }
427
+ }
428
+ noteChromeChange()
429
+ }
430
+
431
+
432
+ const schedule = () => {
433
+ if (frame !== 0) return
434
+ frame = window.requestAnimationFrame(check)
435
+ }
436
+ const observer = new MutationObserver(schedule)
437
+ observer.observe(document.body, { childList: true, subtree: true })
438
+
439
+ return () => {
440
+ observer.disconnect()
441
+ if (frame !== 0) window.cancelAnimationFrame(frame)
442
+ }
443
+ }
444
+
445
+ /**
446
+ * A float that lost its body — clicking the drawer row re-lays the main
447
+ * column, the panel remounts, and the Conversation is momentarily out of the
448
+ * document — is put back together here. An empty float is worse than a flash.
449
+ */
450
+ function healFloatBody() {
451
+ const panel = floatPanel()
452
+ if (panel === null) return
453
+ const host = panel.querySelector('.dsw-host')
454
+ if (host === null) return
455
+ if (movedColumn !== null && host.contains(movedColumn)) return
456
+ const column = findColumn()
457
+ if (column === null || host.contains(column)) return
458
+ attachColumn(host)
459
+ }
460
+ /** Re-apply the hide list: the float may have moved to another branch. */
461
+ function refreshChromeless() {
462
+ for (const el of document.querySelectorAll(`[${CHROME_ATTR}]`)) el.removeAttribute(CHROME_ATTR)
463
+ for (const el of chromeTargets()) el.setAttribute(CHROME_ATTR, '')
464
+ }
465
+ /* ---------------------------------------------------------- the chrome */
466
+
467
+ /**
468
+ * Hide everything the float does not need. Clicking the entry opens the
469
+ * float and leaves the window showing nothing but the float; the same
470
+ * button then brings the rest of DSH back (and hides it again).
471
+ */
472
+ function chromeTargets() {
473
+ const overlay = document.querySelector('[data-shell-overlay]')
474
+ const frame = overlay === null ? null : overlay.parentElement
475
+ if (frame === null) return []
476
+ const floatEl = floatPanel()
477
+ const hidden = []
478
+ /** Keep the branch that holds the float; hide every sibling beside it. */
479
+ const walk = (el) => {
480
+ if (floatEl !== null && (el === floatEl || el.contains(floatEl))) {
481
+ if (el === floatEl) return
482
+ for (const kid of Array.from(el.children)) walk(kid)
483
+ return
484
+ }
485
+ hidden.push(el)
486
+ }
487
+ for (const el of Array.from(frame.children)) {
488
+ if (el === overlay) continue
489
+ walk(el)
490
+ }
491
+ return hidden
492
+ }
493
+
494
+ function setChromeless(next) {
495
+ if (next) {
496
+ // The float mounts asynchronously: hiding before it exists would hide
497
+ // every column, including the one that is about to host it.
498
+ if (floatPanel() === null) {
499
+ pendingChromeless = true
500
+ return
501
+ }
502
+ }
503
+ pendingChromeless = false
504
+ chromeless = next
505
+ notifyState()
506
+ const targets = chromeTargets()
507
+ if (next) {
508
+ for (const el of targets) el.setAttribute(CHROME_ATTR, '')
509
+ } else {
510
+ for (const el of document.querySelectorAll(`[${CHROME_ATTR}]`)) el.removeAttribute(CHROME_ATTR)
511
+ }
512
+ try {
513
+ const button = document.querySelector(`[${ANCHOR_ATTR}]`)
514
+ if (button !== null) button.title = next ? t('showDsh') : t('floatTitle')
515
+ } catch {
516
+ /* the button may not be mounted */
517
+ }
518
+ }
519
+
520
+ /**
521
+ * Bring the rest of DSH back. Hiding the columns lets DSH re-rail the left
522
+ * sidebar, so the window used to come back as "only the right column": a
523
+ * reveal opens the drawer again, the same way opening the float does.
524
+ */
525
+ function revealChrome() {
526
+ setChromeless(false)
527
+ // The columns opened here are the plugin's doing, not the user's: a
528
+ // short settle, not a long one, or the user's own first click after the
529
+ // reveal would be ignored as if it were the plugin's.
530
+ holdOff(400)
531
+ // The design: while the window is only the float, both sidebars are open —
532
+ // the drawer holds a stowed float, the right column is where "收回到侧边栏"
533
+ // docks. The reveal opens both, whatever DSH railed away while hidden.
534
+ try {
535
+ if (leftCollapsed()) layout?.toggleSidebar?.()
536
+ } catch (error) {
537
+ console.warn('[conversation-float] could not expand the left sidebar:', error)
538
+ }
539
+ try {
540
+ if (sidebarRight !== null && sidebarRight.isExpanded?.() === false) sidebarRight.toggleExpanded?.()
541
+ } catch (error) {
542
+ console.warn('[conversation-float] could not expand the right sidebar:', error)
543
+ }
544
+ }
545
+
546
+ /**
547
+ * Match the sidebars to the snapshot, and report whether they already do.
548
+ * Right goes first because opening the left drawer rails the right column
549
+ * on a narrow window; doing the left last leaves the pair the snapshot
550
+ * asked for.
551
+ */
552
+ function applyChromeSnapshot(saved) {
553
+ if (saved === null || saved === undefined) return true
554
+ let matched = true
555
+ const wantRight = saved.rightExpanded
556
+ const wantLeft = saved.leftCollapsed
557
+ // The right column first, the drawer last. A window wide enough holds
558
+ // both; a narrow one keeps whichever was asked for last, and that is the
559
+ // drawer — the side the float lives against.
560
+ try {
561
+ const right = rightExpanded()
562
+ // `null` means there is no mounted right column to read at all.
563
+ // Toggling blind there would collapse a column nobody closed.
564
+ if (right !== null && wantRight !== null && right !== (wantRight === true)) {
565
+ matched = false
566
+ sidebarRight?.toggleExpanded?.()
567
+ }
568
+ } catch (error) {
569
+ console.warn('[conversation-float] could not restore the right sidebar:', error)
570
+ }
571
+ try {
572
+ if (wantLeft !== null && wantLeft !== leftCollapsed()) {
573
+ matched = false
574
+ layout?.toggleSidebar?.()
575
+ }
576
+ } catch (error) {
577
+ console.warn('[conversation-float] could not restore the left sidebar:', error)
578
+ }
579
+ return matched
580
+ }
581
+
582
+ /* ------------------------------------------------------------- openings */
583
+
584
+ function leftCollapsed() {
585
+ // Width is the reliable signal: the narrow layout rails the sidebar
586
+ // without necessarily writing its collapsed marker.
587
+ const overlay = document.querySelector('[data-shell-overlay]')
588
+ const frame = overlay === null ? null : overlay.parentElement
589
+ const sidebar = frame === null ? null : frame.firstElementChild
590
+ if (sidebar !== null) {
591
+ const width = sidebar.getBoundingClientRect().width
592
+ if (width > 0) return width < 120
593
+ }
594
+ return document.querySelector('[data-sidebar-collapsed="true"]') !== null
595
+ }
596
+
597
+ function rightExpanded() {
598
+ try {
599
+ return sidebarRight?.isExpanded?.() ?? null
600
+ } catch {
601
+ return null
602
+ }
603
+ }
604
+
605
+ /** The two sidebars as they stand right now. */
606
+ function chromeNow() {
607
+ return { leftCollapsed: leftCollapsed(), rightExpanded: rightExpanded() }
608
+ }
609
+
610
+ /** The plugin is about to move a column itself: ignore the fallout. */
611
+ function holdOff(ms = 1200) {
612
+ holdOffUntil = performance.now() + ms
613
+ }
614
+
615
+ /**
616
+ * Only the user's own hand can author a column change: a press or a key
617
+ * just before it does, DSH railing a column on its own does not. The
618
+ * plugin's own entry button is excluded — it moves the columns by design.
619
+ */
620
+ function noteGesture(event) {
621
+ if (performance.now() < holdOffUntil) return
622
+ const target = event.target
623
+ if (target instanceof Element && target.closest(`[${ANCHOR_ATTR}]`) !== null) return
624
+ gestureAt = performance.now()
625
+ }
626
+
627
+ /**
628
+ * Remember the sidebars as they were before the float forced them open.
629
+ * The capture happens once, before the plugin touches anything, and is
630
+ * never refreshed while the float is up: a later sample would record the
631
+ * forced state instead, and then every close would look like the user's
632
+ * choice and nothing would ever be restored.
633
+ */
634
+ function saveChromeState() {
635
+ if (savedChrome !== null) return
636
+ savedChrome = chromeNow()
637
+ chromeTouched = false
638
+ // The force-open that follows is the plugin's doing, not the user's.
639
+ holdOff(FORCE_SETTLE_MS)
640
+ }
641
+
642
+ /**
643
+ * The float forces both sidebars open and hides them. A column that sits
644
+ * away from the snapshot after that was either moved by the user or railed
645
+ * by DSH on its own; only the first outranks the snapshot, and only a
646
+ * press or a key just before the change tells the two apart. Both
647
+ * directions count: closing a column the float opened, and opening one it
648
+ * failed to open, are equally the user's choice.
649
+ */
650
+ function noteChromeChange() {
651
+ if (savedChrome === null) return
652
+ // While the columns are hidden their geometry says nothing: DSH rails the
653
+ // left sidebar on its own there, and reading that as the user's choice
654
+ // would cancel the restore the float promised.
655
+ if (chromeless || pendingChromeless) return
656
+ // A re-host (out of the drawer, a remounted body) leaves the column out
657
+ // of the document and the right column reading "not expanded" for a
658
+ // frame. That is the plugin moving, never the user choosing.
659
+ if (dockedLeft || (floatPanel() !== null && movedColumn === null)) return
660
+ const now = performance.now()
661
+ if (now < holdOffUntil) return
662
+ const current = chromeNow()
663
+ // Back on the snapshot's own pair: there is nothing to remember, and the
664
+ // restore would be a no-op anyway.
665
+ if (current.leftCollapsed === savedChrome.leftCollapsed && current.rightExpanded === savedChrome.rightExpanded) return
666
+ if (now - gestureAt > GESTURE_WINDOW) return
667
+ chromeTouched = true
668
+ }
669
+
670
+ /**
671
+ * A detach is not a close until the float is really gone. The drawer row
672
+ * re-hosts the live column and a remounted body re-attaches it, and both
673
+ * detach it for a frame; the chrome is restored only when nothing took the
674
+ * column back and no panel is left to finish tearing down.
675
+ */
676
+ function scheduleRestoreChrome(depth = 0) {
677
+ window.requestAnimationFrame(() => {
678
+ // A host took the column back: the float is still open, not closed.
679
+ if (dockedLeft || movedColumn !== null) return
680
+ // The panel is still on its way out; give it a few frames.
681
+ if (floatPanel() !== null) {
682
+ if (depth < 12) scheduleRestoreChrome(depth + 1)
683
+ return
684
+ }
685
+ restoreChrome()
686
+ })
687
+ }
688
+
689
+ /**
690
+ * Put back what the user had, unless they changed it themselves. This runs
691
+ * while the float's tab is still being torn down, and the dock kit can
692
+ * swallow a toggle aimed at a surface that is on its way out: the snapshot
693
+ * is reapplied until both columns match it or the attempts run out.
694
+ */
695
+ function restoreChrome() {
696
+ const saved = savedChrome
697
+ const touched = chromeTouched
698
+ savedChrome = null
699
+ chromeTouched = false
700
+ if (saved === null || touched) return
701
+ holdOff(1500)
702
+ let tries = 0
703
+ const apply = () => {
704
+ tries += 1
705
+ if (applyChromeSnapshot(saved)) return
706
+ // A toggle the dock kit queued needs a moment to land; retrying on the
707
+ // next frame would read the old state and toggle straight back.
708
+ if (tries < 8) window.setTimeout(apply, 200)
709
+ }
710
+ window.requestAnimationFrame(apply)
711
+ }
712
+
713
+ /** Open (or focus) the float at the dock kit's own default seat. */
714
+ function openFloatAtDefault() {
715
+ saveChromeState()
716
+ // The left drawer is where "放进左栏" lands: a collapsed sidebar has no
717
+ // room to grow the row, so open it first — the right column's rule.
718
+ try {
719
+ if (leftCollapsed()) layout?.toggleSidebar?.()
720
+ } catch (error) {
721
+ console.warn('[conversation-float] could not expand the left sidebar:', error)
722
+ }
723
+ // The docked side of the panel is where "收回到侧边栏" lands: keep it open
724
+ // so the float always has a home to be returned to.
725
+ try {
726
+ if (sidebarRight !== null && sidebarRight.isExpanded?.() === false) sidebarRight.toggleExpanded?.()
727
+ } catch (error) {
728
+ console.warn('[conversation-float] could not expand the right sidebar:', error)
729
+ }
730
+ if (floatExistingTab()) {
731
+ setChromeless(true)
732
+ return
733
+ }
734
+ try {
735
+ sidebarRight?.openResource(CHAT_ADDRESS, { kind: CHAT_KIND, destination: 'float' })
736
+ } catch (error) {
737
+ console.warn('[conversation-float] could not open the floating panel:', error)
738
+ }
739
+ // Opening the float leaves the window to the float alone.
740
+ setChromeless(true)
741
+ }
742
+
743
+ function openFloating() {
744
+ if (!dockedLeft) {
745
+ unstowFloat()
746
+ openFloatAtDefault()
747
+ return
748
+ }
749
+ // Out of the drawer the float is still mounted, holding the only copy of
750
+ // the Conversation. Reopening it as a fresh panel raced the old one's
751
+ // cleanup and left an empty window, so take it back as it stands.
752
+ dockedLeft = false
753
+ syncDockRow()
754
+ unstowFloat()
755
+ // The drawer row lives on a normal window: taking the float back out
756
+ // puts it ON that window, not instead of it. Blanking the window here
757
+ // is what made the drawer and the right column look collapsed.
758
+ }
759
+
760
+ /** The tab id of our floating occurrence, or null when it is not minted. */
761
+ function floatTabId() {
762
+ try {
763
+ const active = sidebarRight?.active?.()
764
+ if (active !== undefined && active !== null && active.kind === CHAT_KIND) return active.id
765
+ } catch {
766
+ /* fall through to the inventory */
767
+ }
768
+ try {
769
+ const snapshot = sidebarRight?.openTabs?.getSnapshot?.()
770
+ const found = new Set()
771
+ const walk = (value, depth) => {
772
+ if (value === null || value === undefined || depth > 6) return
773
+ if (Array.isArray(value)) {
774
+ for (const item of value) walk(item, depth + 1)
775
+ return
776
+ }
777
+ if (typeof value !== 'object') return
778
+ if (value.kind === CHAT_KIND && typeof value.id === 'string') found.add(value.id)
779
+ for (const key of Object.keys(value)) walk(value[key], depth + 1)
780
+ }
781
+ walk(snapshot, 0)
782
+ const ids = Array.from(found)
783
+ return ids.length === 1 ? ids[0] : (ids[ids.length - 1] ?? null)
784
+ } catch {
785
+ return null
786
+ }
787
+ }
788
+
789
+ /** Close the float; the column comes home through the watcher. */
790
+ function closeFloat() {
791
+ const id = floatTabId()
792
+ if (id === null) {
793
+ console.warn('[conversation-float] no floating tab id; the float stays open')
794
+ return false
795
+ }
796
+ try {
797
+ sidebarRight.hide(id)
798
+ return true
799
+ } catch (error) {
800
+ console.warn('[conversation-float] could not hide the floating tab:', error)
801
+ return false
802
+ }
803
+ }
804
+
805
+ /* ---------------------------------------------------------------- bands */
806
+
807
+ /**
808
+ * The three drop bands, taken from the frame's own columns: the left
809
+ * sidebar is the frame's first child, the right sidebar carries
810
+ * `data-rightbar-col`, and the middle column is whatever lies between them.
811
+ * The preview therefore covers the same area the drop lands in.
812
+ */
813
+ function bands() {
814
+ const width = window.innerWidth
815
+ const height = window.innerHeight
816
+ // With the window showing nothing but the float, the columns are hidden:
817
+ // their rects read as a zero-width left band, which is exactly why "放进
818
+ // 左栏" could never be chosen. Judge by thirds of the window there.
819
+ if (chromeless) return thirds(width, height)
820
+ const overlay = document.querySelector('[data-shell-overlay]')
821
+ const frame = overlay === null ? null : overlay.parentElement
822
+ let left = 0
823
+ let right = 0
824
+ if (frame !== null) {
825
+ const sidebar = frame.firstElementChild
826
+ if (sidebar !== null) left = Math.round(sidebar.getBoundingClientRect().right)
827
+ const rightCol = frame.querySelector('[data-rightbar-col]')
828
+ if (rightCol !== null) right = Math.round(rightCol.getBoundingClientRect().left)
829
+ }
830
+ // While the columns are hidden the measurements collapse; keep the last
831
+ // geometry that made sense so a drag does not land in nonsense bands.
832
+ const sane = left >= 0 && right > left + 80 && right <= width + 1
833
+ if (!sane) return lastBand !== null ? { ...lastBand, width, height } : thirds(width, height)
834
+ // A railed drawer is too thin to aim at: widen its band to something a
835
+ // hand can actually hit.
836
+ lastBand = { left: Math.max(left, 96), right, width, height }
837
+ return lastBand
838
+ }
839
+
840
+ /** The window in thirds: the bands used while the float is alone. */
841
+ function thirds(width, height) {
842
+ return { left: Math.round(width / 3), right: Math.round((width * 2) / 3), width, height }
843
+ }
844
+ function zoneAt(x, band) {
845
+ if (x <= band.left) return 'left'
846
+ if (x >= band.right) return 'right'
847
+ return 'center'
848
+ }
849
+
850
+ const ZONE_LABEL = { left: t('stow'), center: t('center'), right: t('dock') }
851
+
852
+ function previewRect(zone, band) {
853
+ if (zone === 'left') return [0, 0, band.left, band.height]
854
+ if (zone === 'right') return [band.right, 0, band.width - band.right, band.height]
855
+ return [band.left, 0, band.right - band.left, band.height]
856
+ }
857
+
858
+ /**
859
+ * Draw the band outline. Only runs when the band changes: the first version
860
+ * rewrote four styles (after a layout read) on every pointer move, and that
861
+ * is what made the drag stutter next to DSH's own dragging.
862
+ */
863
+ function showPreview(zone, band) {
864
+ if (preview === null) {
865
+ const el = document.createElement('div')
866
+ el.className = 'dsw-preview'
867
+ const label = document.createElement('span')
868
+ label.className = 'dsw-preview-label'
869
+ el.appendChild(label)
870
+ document.body.appendChild(el)
871
+ preview = { el, label, zone: null }
872
+ }
873
+ if (preview.zone === zone) return
874
+ if (preview.el.style.display === 'none') preview.el.style.display = ''
875
+ preview.zone = zone
876
+ const [left, top, width, height] = previewRect(zone, band)
877
+ preview.el.style.transform = `translate3d(${left}px, ${top}px, 0)`
878
+ preview.el.style.width = `${width}px`
879
+ preview.el.style.height = `${height}px`
880
+ preview.label.textContent = ZONE_LABEL[zone] ?? ''
881
+ }
882
+
883
+ function hidePreview() {
884
+ // The node is kept, not destroyed: appending and removing it on every band
885
+ // change is a subtree mutation per change, which the DOM watcher then has
886
+ // to service in the middle of a drag.
887
+ if (preview === null) return
888
+ preview.zone = null
889
+ preview.el.style.display = 'none'
890
+ }
891
+
892
+ /* ------------------------------------------------------------ the drop */
893
+
894
+ /**
895
+ * Stow the float: the panel stays mounted (so the Conversation keeps its
896
+ * single host and the centre column stays empty, exactly as it does while
897
+ * the float is on screen) but becomes invisible. The left sidebar row is
898
+ * the way back.
899
+ */
900
+ function floatPanel() {
901
+ const column = movedColumn
902
+ const fromColumn = column === null ? null : column.closest(`[${FLOAT_ATTR}]`)
903
+ return fromColumn ?? document.querySelector(`[${FLOAT_ATTR}]`)
904
+ }
905
+
906
+ function stowFloat() {
907
+ const el = floatPanel()
908
+ if (el === null) return false
909
+ el.setAttribute(STOW_ATTR, '')
910
+ return true
911
+ }
912
+
913
+ function unstowFloat() {
914
+ for (const el of document.querySelectorAll(`[${STOW_ATTR}]`)) el.removeAttribute(STOW_ATTR)
915
+ }
916
+
917
+ function drop(zone) {
918
+ if (zone === 'right') {
919
+ dockedLeft = false
920
+ dockingRight = true
921
+ // The float leaves as an ordinary right-sidebar tab. The sidebar
922
+ // snapshot belonged to the float: keeping it would let a close of that
923
+ // tab — possibly hours later — move the sidebars back in time.
924
+ savedChrome = null
925
+ chromeTouched = false
926
+ unstowFloat()
927
+ syncDockRow()
928
+ try {
929
+ sidebarRight?.openResource(CHAT_ADDRESS, { kind: CHAT_KIND, destination: 'sidebar' })
930
+ } catch (error) {
931
+ console.warn('[conversation-float] could not dock to the right sidebar:', error)
932
+ }
933
+ return
934
+ }
935
+ if (zone === 'left') {
936
+ dockedLeft = true
937
+ syncDockRow()
938
+ if (!stowFloat()) closeFloat()
939
+ // The drawer row lives in the left sidebar: bring the chrome back so it
940
+ // can be seen and clicked.
941
+ revealChrome()
942
+ return
943
+ }
944
+ dockedLeft = false
945
+ syncDockRow()
946
+ revealChrome()
947
+ closeFloat()
948
+ }
949
+
950
+ /**
951
+ * Watch the float's own drag. DSH owns the dragging; we only listen. A press
952
+ * on the float's chrome opens a sequence; a press inside the Conversation
953
+ * column does not, because that one is a text selection.
954
+ */
955
+ function trackPanelDrag(container) {
956
+ let down = null
957
+ let band = null
958
+ let root = null
959
+ let frame = 0
960
+ let pending = null
961
+ /** The band under the pointer right now. */
962
+ let hovered = null
963
+ /** The band the outline currently shows. */
964
+ let drawn = null
965
+ /** Set once the press has been held long enough to mean business. */
966
+ let judging = false
967
+ let judgeTimer = 0
968
+ /** Finger jitter below this is not a move: touch always drifts. */
969
+ const SLOP = 10
970
+
971
+ /** Resolved per pointer sequence: the panel mounts after this body does. */
972
+ const floatRoot = () => {
973
+ if (root !== null && root.isConnected) return root
974
+ root = container.isConnected ? container.closest(`[${FLOAT_ATTR}]`) : null
975
+ return root
976
+ }
977
+
978
+ const stopJudge = () => {
979
+ if (judgeTimer === 0) return
980
+ window.clearTimeout(judgeTimer)
981
+ judgeTimer = 0
982
+ }
983
+
984
+ /** Redraw only when the band under the pointer actually differs. */
985
+ const paint = () => {
986
+ if (!judging || drawn === hovered) return
987
+ drawn = hovered
988
+ if (drawn === null) hidePreview()
989
+ else showPreview(drawn, band)
990
+ }
991
+
992
+ const onDown = (event) => {
993
+ if (event.button !== 0) return
994
+ const panel = floatRoot()
995
+ if (panel === null) {
996
+ down = null
997
+ return
998
+ }
999
+ // The handle is the float's own chrome. A press that lands anywhere
1000
+ // else — a sidebar row, the frame's title bar, another panel — must not
1001
+ // arm a drop: holding it for two seconds and then releasing over a band
1002
+ // would move a session the user never grabbed.
1003
+ const target = event.target
1004
+ const path = typeof event.composedPath === 'function' ? event.composedPath() : []
1005
+ const onPanel = path.includes(panel) || (target instanceof Node && panel.contains(target))
1006
+ if (!onPanel) {
1007
+ down = null
1008
+ return
1009
+ }
1010
+ // A press inside the Conversation is a text selection, not the panel's
1011
+ // drag. Everything else on the float is its chrome.
1012
+ if (movedColumn !== null && target instanceof Node && movedColumn.contains(target)) {
1013
+ down = null
1014
+ return
1015
+ }
1016
+ down = { x: event.clientX, y: event.clientY, lastX: event.clientX, lastY: event.clientY, moved: false, at: performance.now() }
1017
+ // The bands cannot move under a drag: read them once, here.
1018
+ band = bands()
1019
+ hovered = null
1020
+ drawn = null
1021
+ judging = false
1022
+ armJudge()
1023
+ }
1024
+
1025
+ /**
1026
+ * Arm the hold. It has to be a STILL hold: any movement past the slop
1027
+ * restarts this, so grabbing the panel and dragging at once never counts.
1028
+ */
1029
+ const armJudge = () => {
1030
+ stopJudge()
1031
+ judgeTimer = window.setTimeout(() => {
1032
+ judgeTimer = 0
1033
+ if (down === null) return
1034
+ // Coalesced or missed move events cannot fool this: compare the
1035
+ // last known pointer position before calling it a still hold.
1036
+ const stillFor = performance.now() - (down.movedAt ?? down.at)
1037
+ if (stillFor < DWELL_MS - 40) {
1038
+ armJudge()
1039
+ return
1040
+ }
1041
+ judging = true
1042
+ // A still hold never produced a move, so take the band from where
1043
+ // the pointer is right now instead of leaving it unset.
1044
+ if (hovered === null) hovered = zoneAt(down.lastX ?? down.x, band)
1045
+ paint()
1046
+ }, DWELL_MS)
1047
+ }
1048
+
1049
+ /** One layout-independent pass per animation frame, never per event. */
1050
+ const flush = () => {
1051
+ frame = 0
1052
+ const event = pending
1053
+ pending = null
1054
+ if (event === null || down === null) return
1055
+ down.lastX = event.clientX
1056
+ down.lastY = event.clientY
1057
+ const dx = event.clientX - down.x
1058
+ const dy = event.clientY - down.y
1059
+ if (dx * dx + dy * dy > SLOP * SLOP) {
1060
+ down.moved = true
1061
+ down.movedAt = performance.now()
1062
+ if (!judging) {
1063
+ // Still not armed: measure the hold from here, not from the press.
1064
+ down.x = event.clientX
1065
+ down.y = event.clientY
1066
+ armJudge()
1067
+ }
1068
+ }
1069
+ hovered = zoneAt(event.clientX, band)
1070
+ paint()
1071
+ }
1072
+
1073
+ const onMove = (event) => {
1074
+ if (down === null) return
1075
+ pending = event
1076
+ if (frame !== 0) return
1077
+ frame = window.requestAnimationFrame(flush)
1078
+ }
1079
+
1080
+ const settle = () => {
1081
+ if (frame !== 0) {
1082
+ window.cancelAnimationFrame(frame)
1083
+ frame = 0
1084
+ }
1085
+ if (pending !== null) flush()
1086
+ stopJudge()
1087
+ const target = judging ? hovered : null
1088
+ down = null
1089
+ band = null
1090
+ pending = null
1091
+ hovered = null
1092
+ drawn = null
1093
+ judging = false
1094
+ hidePreview()
1095
+ return { target }
1096
+ }
1097
+
1098
+ const onUp = () => {
1099
+ if (down === null) return
1100
+ const result = settle()
1101
+ if (result.target !== null) drop(result.target)
1102
+ }
1103
+
1104
+ const onCancel = () => {
1105
+ if (down === null) return
1106
+ settle()
1107
+ }
1108
+
1109
+ // Both channels: a real drag reports pointer events, while synthesised
1110
+ // input (and some remote-input paths) can report mouse events only. The
1111
+ // handlers are shared, and the frame gate keeps the doubled stream cheap.
1112
+ // Touch arrives as its own event family on some WebViews; wrap it in the
1113
+ // shape the shared handlers read. Pointer events also fire on modern
1114
+ // browsers and the frame gate keeps the doubled stream cheap.
1115
+ const touchPoint = (event) => {
1116
+ const touch = (event.touches && event.touches[0]) || (event.changedTouches && event.changedTouches[0])
1117
+ if (touch === undefined) return null
1118
+ return { button: 0, clientX: touch.clientX, clientY: touch.clientY, target: event.target, composedPath: () => event.composedPath?.() ?? [] }
1119
+ }
1120
+ const onTouchDown = (event) => {
1121
+ const point = touchPoint(event)
1122
+ if (point !== null) onDown(point)
1123
+ }
1124
+ const onTouchMove = (event) => {
1125
+ const point = touchPoint(event)
1126
+ if (point !== null) onMove(point)
1127
+ }
1128
+ const onTouchUp = (event) => {
1129
+ const point = touchPoint(event)
1130
+ if (point !== null) onUp(point)
1131
+ }
1132
+ const pairs = [
1133
+ ['pointerdown', onDown],
1134
+ ['pointermove', onMove],
1135
+ ['pointerup', onUp],
1136
+ ['pointercancel', onCancel],
1137
+ ['mousedown', onDown],
1138
+ ['mousemove', onMove],
1139
+ ['mouseup', onUp],
1140
+ ['touchstart', onTouchDown],
1141
+ ['touchmove', onTouchMove],
1142
+ ['touchend', onTouchUp],
1143
+ ['touchcancel', onCancel],
1144
+ ]
1145
+ for (const [name, handler] of pairs) window.addEventListener(name, handler, { capture: true, passive: name !== 'touchmove' })
1146
+ // Only the window's own blur. Captured, this would also fire for every
1147
+ // descendant losing focus — a focused input blurring would cancel a drag
1148
+ // that is still going on.
1149
+ const onWindowBlur = (event) => {
1150
+ if (event.target === window || event.target === document) onCancel()
1151
+ }
1152
+ window.addEventListener('blur', onWindowBlur)
1153
+ return () => {
1154
+ for (const [name, handler] of pairs) window.removeEventListener(name, handler, true)
1155
+ window.removeEventListener('blur', onWindowBlur)
1156
+ onCancel()
1157
+ }
1158
+ }
1159
+
1160
+ /* ----------------------------------------------------------- the drawer */
1161
+
1162
+ function syncDockRow() {
1163
+ if (dockedLeft && dockRow === null) {
1164
+ try {
1165
+ dockRow = ctxRef.slots.register(
1166
+ { name: 'sidebar.panellist', id: DOCK_ROW_ID, order: 20, label: () => t('floatTitle') },
1167
+ DockIcon,
1168
+ )
1169
+ } catch (error) {
1170
+ console.warn('[conversation-float] could not register the sidebar row:', error)
1171
+ dockRow = null
1172
+ }
1173
+ } else if (!dockedLeft && dockRow !== null) {
1174
+ try {
1175
+ dockRow()
1176
+ } catch {
1177
+ /* already disposed with the slot */
1178
+ }
1179
+ dockRow = null
1180
+ }
1181
+ }
1182
+
1183
+ let ctxRef = null
1184
+
1185
+ /* ---------------------------------------------------------- components */
1186
+
1187
+ function Icon({ name, size = 16 }) {
1188
+ const paths = ICONS[name] ?? ICONS.dot
1189
+ return h(
1190
+ 'svg',
1191
+ {
1192
+ viewBox: '0 0 24 24', width: size, height: size, fill: 'none',
1193
+ stroke: 'currentColor', strokeWidth: 1.7, strokeLinecap: 'round',
1194
+ strokeLinejoin: 'round', 'aria-hidden': true, style: { display: 'block' },
1195
+ },
1196
+ paths.map((d, index) => h('path', { key: index, d })),
1197
+ )
1198
+ }
1199
+
1200
+ const ICONS = {
1201
+ window: ['M4 6.5A2.5 2.5 0 0 1 6.5 4h11A2.5 2.5 0 0 1 20 6.5v11A2.5 2.5 0 0 1 17.5 20h-11A2.5 2.5 0 0 1 4 17.5z', 'M4 8.5h16'],
1202
+ dot: ['M12 12h.01'],
1203
+ }
1204
+
1205
+ const CSS = `
1206
+ .dsw-icon {
1207
+ display: inline-flex; align-items: center; justify-content: center;
1208
+ width: 26px; height: 26px; padding: 0; border: 0; border-radius: 7px;
1209
+ background: transparent; color: var(--dsw-alias-label-secondary); cursor: pointer;
1210
+ transition: background .12s ease, color .12s ease;
1211
+ }
1212
+ .dsw-icon:hover { background: var(--dsw-alias-bg-layer-2); color: var(--dsw-alias-label-primary); }
1213
+ .dsw-icon:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
1214
+ .dsw-host {
1215
+ position: relative;
1216
+ display: flex; flex-direction: column;
1217
+ width: 100%; height: 100%; min-height: 0; overflow: hidden;
1218
+ background: var(--dsw-alias-bg-base);
1219
+ }
1220
+ .dsw-preview {
1221
+ position: fixed; left: 0; top: 0; z-index: 90; pointer-events: none;
1222
+ will-change: transform, width, height;
1223
+ border: 2px dashed var(--dsw-alias-brand-primary, #4d6bfe);
1224
+ border-radius: 12px;
1225
+ box-sizing: border-box;
1226
+ background: color-mix(in srgb, var(--dsw-alias-brand-primary, #4d6bfe) 12%, transparent);
1227
+ display: flex; align-items: center; justify-content: center;
1228
+ transition: transform .09s ease, width .09s ease, height .09s ease;
1229
+ }
1230
+ /* The float, stowed in the left drawer: mounted, so the centre stays empty. */
1231
+ [data-dsh-conversation-float-stowed] {
1232
+ opacity: 0 !important;
1233
+ visibility: hidden !important;
1234
+ pointer-events: none !important;
1235
+ }
1236
+ /* Touch: the grip owns the gesture, so a press is not turned into a scroll. */
1237
+ [data-dsh-conversation-float-float] [data-dockkit-float-grip] {
1238
+ touch-action: none;
1239
+ -webkit-user-select: none; user-select: none;
1240
+ -webkit-touch-callout: none;
1241
+ }
1242
+ /* Everything the float hides while it is the only thing on screen. */
1243
+ [data-dsh-conversation-float-chromeless] {
1244
+ display: none !important;
1245
+ }
1246
+ .dsw-preview-label {
1247
+ font-size: 15px; font-weight: 600; letter-spacing: .04em;
1248
+ color: var(--dsw-alias-brand-primary, #4d6bfe);
1249
+ background: var(--dsw-alias-bg-base, #fff);
1250
+ border-radius: 999px; padding: 4px 14px;
1251
+ }
1252
+ `
1253
+
1254
+ function Styles() {
1255
+ return h('style', { 'data-plugin-css': NS }, CSS)
1256
+ }
1257
+
1258
+ /**
1259
+ * The entry's job depends on the state: with no float it opens one (leaving
1260
+ * the window to the float alone), and with a float on screen it brings the
1261
+ * rest of DSH back — or hides it again.
1262
+ */
1263
+ function onEntryClick() {
1264
+ // Docked in the right sidebar (or stowed in the drawer) there is no
1265
+ // float panel to toggle: the button must bring the float back instead.
1266
+ if (dockedLeft || floatPanel() === null) {
1267
+ openFloating()
1268
+ return
1269
+ }
1270
+ if (chromeless) revealChrome()
1271
+ else setChromeless(true)
1272
+ }
1273
+
1274
+ /** Escape always brings DSH back: the way out of a hidden window. */
1275
+ function escapeOnKey(event) {
1276
+ if (event.key !== 'Escape' || !chromeless) return
1277
+ revealChrome()
1278
+ }
1279
+
1280
+ /** Conversation-header entry: opens the float, or reveals DSH behind it. */
1281
+ function HeaderAction() {
1282
+ const [, bump] = React.useState(0)
1283
+ React.useEffect(() => {
1284
+ const fn = () => bump((n) => n + 1)
1285
+ stateListeners.add(fn)
1286
+ return () => stateListeners.delete(fn)
1287
+ }, [])
1288
+ return h(
1289
+ 'button',
1290
+ {
1291
+ type: 'button',
1292
+ className: 'dsw-icon',
1293
+ title: chromeless ? t('showDsh') : t('floatTitle'),
1294
+ 'aria-label': chromeless ? t('showDsh') : t('floatTitle'),
1295
+ [ANCHOR_ATTR]: '',
1296
+ onClick: onEntryClick,
1297
+ },
1298
+ h(Styles),
1299
+ h(Icon, { name: 'window' }),
1300
+ )
1301
+ }
1302
+
1303
+ /** The left sidebar row's glyph. The row itself is owned by the sidebar. */
1304
+ function DockIcon({ size = 16 }) {
1305
+ return h(Icon, { name: 'window', size })
1306
+ }
1307
+
1308
+ /**
1309
+ * The main panel this row addresses. It only exists so a click on the row
1310
+ * cannot leave the centre column on an empty page: the click re-opens the
1311
+ * float and hands the centre back to the conversation.
1312
+ */
1313
+ function DockPanel() {
1314
+ React.useEffect(() => {
1315
+ openFloating()
1316
+ try {
1317
+ layout?.selectPanel?.(null)
1318
+ } catch (error) {
1319
+ console.warn('[conversation-float] could not restore the conversation panel:', error)
1320
+ }
1321
+ }, [])
1322
+ return null
1323
+ }
1324
+
1325
+ /** The floating panel's body: it holds the live Conversation column. */
1326
+ function SessionPanel() {
1327
+ const host = React.useRef(null)
1328
+ React.useLayoutEffect(() => {
1329
+ const container = host.current
1330
+ if (container === null) return undefined
1331
+ attachColumn(container)
1332
+ // Only the floating occurrence is draggable; a tab docked in the right
1333
+ // sidebar must not arm the drop bands at all. The panel element mounts
1334
+ // after this body does, so the tracker resolves it per pointer sequence.
1335
+ const stop = trackPanelDrag(container)
1336
+ return () => {
1337
+ stop()
1338
+ detachColumn()
1339
+ }
1340
+ }, [])
1341
+ return h('div', { className: 'dsw-host', ref: host }, h(Styles))
1342
+ }
1343
+
1344
+ /* --------------------------------------------------------------- wiring */
1345
+
1346
+ return {
1347
+ inject: ['slots', 'locale'],
1348
+ apply(ctx) {
1349
+ ctxRef = ctx
1350
+ ctx.effect(() => {
1351
+ try {
1352
+ return ctx.locale.register(NS, Object.fromEntries(LOCALES.map((id) => [id, { title: COPY[id].floatTitle, description: COPY[id].description }])))
1353
+ } catch {
1354
+ return () => {}
1355
+ }
1356
+ })
1357
+
1358
+ const register = (slot, id, component, options = {}) =>
1359
+ ctx.effect(() =>
1360
+ ctx.slots.inject(slot, () =>
1361
+ ctx.slots.register({ name: slot, id, locale: NS, ...options }, component),
1362
+ ),
1363
+ )
1364
+
1365
+ register('conversation.session.header.utilities', 'conversation-float-control', HeaderAction, { order: 30 })
1366
+
1367
+ ctx.effect(() => watchColumn())
1368
+
1369
+ ctx.effect(() => {
1370
+ window.addEventListener('keydown', escapeOnKey, true)
1371
+ return () => window.removeEventListener('keydown', escapeOnKey, true)
1372
+ })
1373
+
1374
+ // A press or a key is the only evidence that a column moved by the
1375
+ // user's hand rather than by DSH re-railing it.
1376
+ ctx.effect(() => {
1377
+ document.addEventListener('pointerdown', noteGesture, true)
1378
+ document.addEventListener('keydown', noteGesture, true)
1379
+ return () => {
1380
+ document.removeEventListener('pointerdown', noteGesture, true)
1381
+ document.removeEventListener('keydown', noteGesture, true)
1382
+ }
1383
+ })
1384
+
1385
+ // One frame after load, give any float already on screen its size.
1386
+ ctx.effect(() => {
1387
+ const id = window.requestAnimationFrame(() => sizeFloat())
1388
+ return () => window.cancelAnimationFrame(id)
1389
+ })
1390
+ // A reload can leave the last run's hidden columns behind.
1391
+ // An earlier build parked the View tab strip in the main window; put it
1392
+ // back inside the Conversation column and drop the parked container.
1393
+ for (const dock of document.querySelectorAll('.dsw-tabdock')) {
1394
+ const strip = dock.querySelector('[data-conversation-tabs]')
1395
+ const column = document.querySelector('[data-conversation-session]')
1396
+ if (strip !== null && column !== null && !column.contains(strip)) {
1397
+ column.insertBefore(strip, column.firstChild)
1398
+ }
1399
+ dock.remove()
1400
+ }
1401
+ // A previous build hid the two shipped View buttons; put them back.
1402
+ for (const el of document.querySelectorAll('[data-dsh-conversation-float-core-tab]')) el.removeAttribute('data-dsh-conversation-float-core-tab')
1403
+ setChromeless(false)
1404
+
1405
+
1406
+ ctx.effect(() =>
1407
+ ctx.slots.inject('main', () =>
1408
+ ctx.slots.register({ name: 'main', key: DOCK_ROW_ID, locale: NS }, DockPanel),
1409
+ ),
1410
+ )
1411
+
1412
+ ctx.effect(() => {
1413
+ const dispose = ctx.inject(['layout'], (sub) => {
1414
+ layout = sub.layout ?? null
1415
+ return () => {
1416
+ layout = null
1417
+ }
1418
+ })
1419
+ return dispose
1420
+ })
1421
+
1422
+ ctx.effect(() =>
1423
+ ctx.inject(['sidebarRightTabs', 'sidebarRight'], (sub) => {
1424
+ sidebarRight = sub.sidebarRight ?? null
1425
+ sub.effect(() =>
1426
+ sub.sidebarRightTabs.register({
1427
+ id: CHAT_ID,
1428
+ kind: CHAT_KIND,
1429
+ title: () => t('conversation'),
1430
+ }),
1431
+ )
1432
+ sub.effect(() =>
1433
+ sub.slots.inject('sidebar.right.pane.tab', () =>
1434
+ sub.slots.register({ name: 'sidebar.right.pane.tab', key: CHAT_ID, locale: NS }, SessionPanel),
1435
+ ),
1436
+ )
1437
+ return () => {
1438
+ sidebarRight = null
1439
+ hidePreview()
1440
+ if (dockedLeft) {
1441
+ dockedLeft = false
1442
+ syncDockRow()
1443
+ }
1444
+ detachColumn()
1445
+ }
1446
+ }),
1447
+ )
1448
+
1449
+ window.__dshSessionWindow = {
1450
+ open: openFloating,
1451
+ findColumn,
1452
+ bands,
1453
+ get moved() {
1454
+ return movedColumn !== null
1455
+ },
1456
+ get dockedLeft() {
1457
+ return dockedLeft
1458
+ },
1459
+ }
1460
+ ctx.effect(() => () => {
1461
+ hidePreview()
1462
+ unstowFloat()
1463
+ // Unloading is not a user close: leave the sidebars alone.
1464
+ suspendRestore = true
1465
+ detachColumn()
1466
+ delete window.__dshSessionWindow
1467
+ })
1468
+ },
1469
+ }
1470
+ },
1471
+ })