dsh-conversation-float 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js ADDED
@@ -0,0 +1,1441 @@
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 the user has not reshaped them meanwhile, and never while the tab
359
+ // is merely moving into the right sidebar.
360
+ if (!dockingRight && !suspendRestore) restoreChrome()
361
+ dockingRight = false
362
+ if (column === null) return
363
+ column.style.width = ''
364
+ column.style.height = ''
365
+ column.style.minWidth = ''
366
+ column.style.minHeight = ''
367
+ column.style.overflow = ''
368
+ if (home !== null && home.parent !== null && home.parent.isConnected) {
369
+ home.parent.insertBefore(column, home.next)
370
+ return
371
+ }
372
+ // The recorded seat is gone (the panel took it down with it): put the
373
+ // column back in the middle column so the session is never lost.
374
+ const center = currentCenter()
375
+ if (center !== null) center.appendChild(column)
376
+ }
377
+
378
+ /**
379
+ * A closed floating panel can take our body down without running its
380
+ * cleanup first, so the column is watched directly: as soon as its container
381
+ * leaves the document it goes home.
382
+ */
383
+ function watchColumn() {
384
+ /** The float element the last repair ran against. */
385
+ let seenFloat = null
386
+ /** The float whose fixed size was last applied. */
387
+ let sizedFloat = null
388
+ /** Attempts made to settle that float size. */
389
+ let sizeTries = 0
390
+ let seenParent = null
391
+ let seenHost = null
392
+ let frame = 0
393
+ const check = () => {
394
+ frame = 0
395
+ if (movedColumn !== null && !movedColumn.isConnected) detachColumn()
396
+ const panel = floatPanel()
397
+ // Never stay hidden without a float: that is a blank window.
398
+ if (chromeless && panel === null) setChromeless(false)
399
+ // The repairs below walk the whole frame, so they run only when the
400
+ // float moves house (a new panel, a new parent column, or a new body)
401
+ // and never on every mutation a drag produces.
402
+ const parent = panel === null ? null : panel.parentElement
403
+ const host = panel === null ? null : panel.querySelector(".dsw-host")
404
+ if (panel !== null) {
405
+ if (panel !== sizedFloat) {
406
+ sizedFloat = panel
407
+ sizeTries = 0
408
+ }
409
+ const want = floatSize()
410
+ const box = panel.getBoundingClientRect()
411
+ const off = Math.abs(box.width - want.width) > 24 || Math.abs(box.height - want.height) > 24
412
+ if (off && sizeTries < 4) {
413
+ sizeTries += 1
414
+ sizeFloat()
415
+ }
416
+ }
417
+ if (panel !== seenFloat || parent !== seenParent || host !== seenHost) {
418
+ seenFloat = panel
419
+ seenParent = parent
420
+ seenHost = host
421
+ if (panel !== null) {
422
+ healFloatBody()
423
+ if (chromeless) refreshChromeless()
424
+ }
425
+ }
426
+ noteChromeChange()
427
+ }
428
+ const schedule = () => {
429
+ if (frame !== 0) return
430
+ frame = window.requestAnimationFrame(check)
431
+ }
432
+ const observer = new MutationObserver(schedule)
433
+ observer.observe(document.body, { childList: true, subtree: true })
434
+
435
+ return () => {
436
+ observer.disconnect()
437
+ if (frame !== 0) window.cancelAnimationFrame(frame)
438
+ }
439
+ }
440
+
441
+ /**
442
+ * A float that lost its body — clicking the drawer row re-lays the main
443
+ * column, the panel remounts, and the Conversation is momentarily out of the
444
+ * document — is put back together here. An empty float is worse than a flash.
445
+ */
446
+ function healFloatBody() {
447
+ const panel = floatPanel()
448
+ if (panel === null) return
449
+ const host = panel.querySelector('.dsw-host')
450
+ if (host === null) return
451
+ if (movedColumn !== null && host.contains(movedColumn)) return
452
+ const column = findColumn()
453
+ if (column === null || host.contains(column)) return
454
+ attachColumn(host)
455
+ }
456
+ /** Re-apply the hide list: the float may have moved to another branch. */
457
+ function refreshChromeless() {
458
+ for (const el of document.querySelectorAll(`[${CHROME_ATTR}]`)) el.removeAttribute(CHROME_ATTR)
459
+ for (const el of chromeTargets()) el.setAttribute(CHROME_ATTR, '')
460
+ }
461
+ /* ---------------------------------------------------------- the chrome */
462
+
463
+ /**
464
+ * Hide everything the float does not need. Clicking the entry opens the
465
+ * float and leaves the window showing nothing but the float; the same
466
+ * button then brings the rest of DSH back (and hides it again).
467
+ */
468
+ function chromeTargets() {
469
+ const overlay = document.querySelector('[data-shell-overlay]')
470
+ const frame = overlay === null ? null : overlay.parentElement
471
+ if (frame === null) return []
472
+ const floatEl = floatPanel()
473
+ const hidden = []
474
+ /** Keep the branch that holds the float; hide every sibling beside it. */
475
+ const walk = (el) => {
476
+ if (floatEl !== null && (el === floatEl || el.contains(floatEl))) {
477
+ if (el === floatEl) return
478
+ for (const kid of Array.from(el.children)) walk(kid)
479
+ return
480
+ }
481
+ hidden.push(el)
482
+ }
483
+ for (const el of Array.from(frame.children)) {
484
+ if (el === overlay) continue
485
+ walk(el)
486
+ }
487
+ return hidden
488
+ }
489
+
490
+ function setChromeless(next) {
491
+ if (next) {
492
+ // The float mounts asynchronously: hiding before it exists would hide
493
+ // every column, including the one that is about to host it.
494
+ if (floatPanel() === null) {
495
+ pendingChromeless = true
496
+ return
497
+ }
498
+ }
499
+ pendingChromeless = false
500
+ chromeless = next
501
+ notifyState()
502
+ const targets = chromeTargets()
503
+ if (next) {
504
+ for (const el of targets) el.setAttribute(CHROME_ATTR, '')
505
+ } else {
506
+ for (const el of document.querySelectorAll(`[${CHROME_ATTR}]`)) el.removeAttribute(CHROME_ATTR)
507
+ }
508
+ try {
509
+ const button = document.querySelector(`[${ANCHOR_ATTR}]`)
510
+ if (button !== null) button.title = next ? t('showDsh') : t('floatTitle')
511
+ } catch {
512
+ /* the button may not be mounted */
513
+ }
514
+ }
515
+
516
+ /**
517
+ * Bring the rest of DSH back. Hiding the columns lets DSH re-rail the left
518
+ * sidebar, so the window used to come back as "only the right column": a
519
+ * reveal opens the drawer again, the same way opening the float does.
520
+ */
521
+ function revealChrome() {
522
+ setChromeless(false)
523
+ // The columns opened here are the plugin's doing, not the user's: a
524
+ // short settle, not a long one, or the user's own first click after the
525
+ // reveal would be ignored as if it were the plugin's.
526
+ holdOff(400)
527
+ // The design: while the window is only the float, both sidebars are open —
528
+ // the drawer holds a stowed float, the right column is where "收回到侧边栏"
529
+ // docks. The reveal opens both, whatever DSH railed away while hidden.
530
+ try {
531
+ if (leftCollapsed()) layout?.toggleSidebar?.()
532
+ } catch (error) {
533
+ console.warn('[conversation-float] could not expand the left sidebar:', error)
534
+ }
535
+ try {
536
+ if (sidebarRight !== null && sidebarRight.isExpanded?.() === false) sidebarRight.toggleExpanded?.()
537
+ } catch (error) {
538
+ console.warn('[conversation-float] could not expand the right sidebar:', error)
539
+ }
540
+ }
541
+
542
+ /**
543
+ * Match the sidebars to the snapshot, and report whether they already do.
544
+ * Right goes first because opening the left drawer rails the right column
545
+ * on a narrow window; doing the left last leaves the pair the snapshot
546
+ * asked for.
547
+ */
548
+ function applyChromeSnapshot(saved) {
549
+ if (saved === null || saved === undefined) return true
550
+ let matched = true
551
+ const wantRight = saved.rightExpanded
552
+ const wantLeft = saved.leftCollapsed
553
+ // The right column first, the drawer last. A window wide enough holds
554
+ // both; a narrow one keeps whichever was asked for last, and that is the
555
+ // drawer — the side the float lives against.
556
+ try {
557
+ const right = rightExpanded()
558
+ // `null` means there is no mounted right column to read at all.
559
+ // Toggling blind there would collapse a column nobody closed.
560
+ if (right !== null && wantRight !== null && right !== (wantRight === true)) {
561
+ matched = false
562
+ sidebarRight?.toggleExpanded?.()
563
+ }
564
+ } catch (error) {
565
+ console.warn('[conversation-float] could not restore the right sidebar:', error)
566
+ }
567
+ try {
568
+ if (wantLeft !== null && wantLeft !== leftCollapsed()) {
569
+ matched = false
570
+ layout?.toggleSidebar?.()
571
+ }
572
+ } catch (error) {
573
+ console.warn('[conversation-float] could not restore the left sidebar:', error)
574
+ }
575
+ return matched
576
+ }
577
+
578
+ /* ------------------------------------------------------------- openings */
579
+
580
+ function leftCollapsed() {
581
+ // Width is the reliable signal: the narrow layout rails the sidebar
582
+ // without necessarily writing its collapsed marker.
583
+ const overlay = document.querySelector('[data-shell-overlay]')
584
+ const frame = overlay === null ? null : overlay.parentElement
585
+ const sidebar = frame === null ? null : frame.firstElementChild
586
+ if (sidebar !== null) {
587
+ const width = sidebar.getBoundingClientRect().width
588
+ if (width > 0) return width < 120
589
+ }
590
+ return document.querySelector('[data-sidebar-collapsed="true"]') !== null
591
+ }
592
+
593
+ function rightExpanded() {
594
+ try {
595
+ return sidebarRight?.isExpanded?.() ?? null
596
+ } catch {
597
+ return null
598
+ }
599
+ }
600
+
601
+ /** The two sidebars as they stand right now. */
602
+ function chromeNow() {
603
+ return { leftCollapsed: leftCollapsed(), rightExpanded: rightExpanded() }
604
+ }
605
+
606
+ /** The plugin is about to move a column itself: ignore the fallout. */
607
+ function holdOff(ms = 1200) {
608
+ holdOffUntil = performance.now() + ms
609
+ }
610
+
611
+ /**
612
+ * Only the user's own hand can author a column change: a press or a key
613
+ * just before it does, DSH railing a column on its own does not. The
614
+ * plugin's own entry button is excluded — it moves the columns by design.
615
+ */
616
+ function noteGesture(event) {
617
+ if (performance.now() < holdOffUntil) return
618
+ const target = event.target
619
+ if (target instanceof Element && target.closest(`[${ANCHOR_ATTR}]`) !== null) return
620
+ gestureAt = performance.now()
621
+ }
622
+
623
+ /**
624
+ * Remember the sidebars as they were before the float forced them open.
625
+ * The capture happens once, before the plugin touches anything, and is
626
+ * never refreshed while the float is up: a later sample would record the
627
+ * forced state instead, and then every close would look like the user's
628
+ * choice and nothing would ever be restored.
629
+ */
630
+ function saveChromeState() {
631
+ if (savedChrome !== null) return
632
+ savedChrome = chromeNow()
633
+ chromeTouched = false
634
+ // The force-open that follows is the plugin's doing, not the user's.
635
+ holdOff(FORCE_SETTLE_MS)
636
+ }
637
+
638
+ /**
639
+ * The float forces both sidebars open and hides them. A column that sits
640
+ * away from the snapshot after that was either moved by the user or railed
641
+ * by DSH on its own; only the first outranks the snapshot, and only a
642
+ * press or a key just before the change tells the two apart. Both
643
+ * directions count: closing a column the float opened, and opening one it
644
+ * failed to open, are equally the user's choice.
645
+ */
646
+ function noteChromeChange() {
647
+ if (savedChrome === null) return
648
+ // While the columns are hidden their geometry says nothing: DSH rails the
649
+ // left sidebar on its own there, and reading that as the user's choice
650
+ // would cancel the restore the float promised.
651
+ if (chromeless || pendingChromeless) return
652
+ const now = performance.now()
653
+ if (now < holdOffUntil) return
654
+ const current = chromeNow()
655
+ // Back on the snapshot's own pair: there is nothing to remember, and the
656
+ // restore would be a no-op anyway.
657
+ if (current.leftCollapsed === savedChrome.leftCollapsed && current.rightExpanded === savedChrome.rightExpanded) return
658
+ if (now - gestureAt > GESTURE_WINDOW) return
659
+ chromeTouched = true
660
+ }
661
+
662
+ /**
663
+ * Put back what the user had, unless they changed it themselves. This runs
664
+ * while the float's tab is still being torn down, and the dock kit can
665
+ * swallow a toggle aimed at a surface that is on its way out: the snapshot
666
+ * is reapplied until both columns match it or the attempts run out.
667
+ */
668
+ function restoreChrome() {
669
+ const saved = savedChrome
670
+ const touched = chromeTouched
671
+ savedChrome = null
672
+ chromeTouched = false
673
+ if (saved === null || touched) return
674
+ holdOff(1500)
675
+ let tries = 0
676
+ const apply = () => {
677
+ tries += 1
678
+ if (applyChromeSnapshot(saved)) return
679
+ // A toggle the dock kit queued needs a moment to land; retrying on the
680
+ // next frame would read the old state and toggle straight back.
681
+ if (tries < 8) window.setTimeout(apply, 200)
682
+ }
683
+ window.requestAnimationFrame(apply)
684
+ }
685
+
686
+ /** Open (or focus) the float at the dock kit's own default seat. */
687
+ function openFloatAtDefault() {
688
+ saveChromeState()
689
+ // The left drawer is where "放进左栏" lands: a collapsed sidebar has no
690
+ // room to grow the row, so open it first — the right column's rule.
691
+ try {
692
+ if (leftCollapsed()) layout?.toggleSidebar?.()
693
+ } catch (error) {
694
+ console.warn('[conversation-float] could not expand the left sidebar:', error)
695
+ }
696
+ // The docked side of the panel is where "收回到侧边栏" lands: keep it open
697
+ // so the float always has a home to be returned to.
698
+ try {
699
+ if (sidebarRight !== null && sidebarRight.isExpanded?.() === false) sidebarRight.toggleExpanded?.()
700
+ } catch (error) {
701
+ console.warn('[conversation-float] could not expand the right sidebar:', error)
702
+ }
703
+ if (floatExistingTab()) {
704
+ setChromeless(true)
705
+ return
706
+ }
707
+ try {
708
+ sidebarRight?.openResource(CHAT_ADDRESS, { kind: CHAT_KIND, destination: 'float' })
709
+ } catch (error) {
710
+ console.warn('[conversation-float] could not open the floating panel:', error)
711
+ }
712
+ // Opening the float leaves the window to the float alone.
713
+ setChromeless(true)
714
+ }
715
+
716
+ function openFloating() {
717
+ if (!dockedLeft) {
718
+ unstowFloat()
719
+ openFloatAtDefault()
720
+ return
721
+ }
722
+ // Out of the drawer the float is still mounted, holding the only copy of
723
+ // the Conversation. Reopening it as a fresh panel raced the old one's
724
+ // cleanup and left an empty window, so take it back as it stands.
725
+ dockedLeft = false
726
+ syncDockRow()
727
+ unstowFloat()
728
+ setChromeless(true)
729
+ }
730
+
731
+ /** The tab id of our floating occurrence, or null when it is not minted. */
732
+ function floatTabId() {
733
+ try {
734
+ const active = sidebarRight?.active?.()
735
+ if (active !== undefined && active !== null && active.kind === CHAT_KIND) return active.id
736
+ } catch {
737
+ /* fall through to the inventory */
738
+ }
739
+ try {
740
+ const snapshot = sidebarRight?.openTabs?.getSnapshot?.()
741
+ const found = new Set()
742
+ const walk = (value, depth) => {
743
+ if (value === null || value === undefined || depth > 6) return
744
+ if (Array.isArray(value)) {
745
+ for (const item of value) walk(item, depth + 1)
746
+ return
747
+ }
748
+ if (typeof value !== 'object') return
749
+ if (value.kind === CHAT_KIND && typeof value.id === 'string') found.add(value.id)
750
+ for (const key of Object.keys(value)) walk(value[key], depth + 1)
751
+ }
752
+ walk(snapshot, 0)
753
+ const ids = Array.from(found)
754
+ return ids.length === 1 ? ids[0] : (ids[ids.length - 1] ?? null)
755
+ } catch {
756
+ return null
757
+ }
758
+ }
759
+
760
+ /** Close the float; the column comes home through the watcher. */
761
+ function closeFloat() {
762
+ const id = floatTabId()
763
+ if (id === null) {
764
+ console.warn('[conversation-float] no floating tab id; the float stays open')
765
+ return false
766
+ }
767
+ try {
768
+ sidebarRight.hide(id)
769
+ return true
770
+ } catch (error) {
771
+ console.warn('[conversation-float] could not hide the floating tab:', error)
772
+ return false
773
+ }
774
+ }
775
+
776
+ /* ---------------------------------------------------------------- bands */
777
+
778
+ /**
779
+ * The three drop bands, taken from the frame's own columns: the left
780
+ * sidebar is the frame's first child, the right sidebar carries
781
+ * `data-rightbar-col`, and the middle column is whatever lies between them.
782
+ * The preview therefore covers the same area the drop lands in.
783
+ */
784
+ function bands() {
785
+ const width = window.innerWidth
786
+ const height = window.innerHeight
787
+ // With the window showing nothing but the float, the columns are hidden:
788
+ // their rects read as a zero-width left band, which is exactly why "放进
789
+ // 左栏" could never be chosen. Judge by thirds of the window there.
790
+ if (chromeless) return thirds(width, height)
791
+ const overlay = document.querySelector('[data-shell-overlay]')
792
+ const frame = overlay === null ? null : overlay.parentElement
793
+ let left = 0
794
+ let right = 0
795
+ if (frame !== null) {
796
+ const sidebar = frame.firstElementChild
797
+ if (sidebar !== null) left = Math.round(sidebar.getBoundingClientRect().right)
798
+ const rightCol = frame.querySelector('[data-rightbar-col]')
799
+ if (rightCol !== null) right = Math.round(rightCol.getBoundingClientRect().left)
800
+ }
801
+ // While the columns are hidden the measurements collapse; keep the last
802
+ // geometry that made sense so a drag does not land in nonsense bands.
803
+ const sane = left >= 0 && right > left + 80 && right <= width + 1
804
+ if (!sane) return lastBand !== null ? { ...lastBand, width, height } : thirds(width, height)
805
+ // A railed drawer is too thin to aim at: widen its band to something a
806
+ // hand can actually hit.
807
+ lastBand = { left: Math.max(left, 96), right, width, height }
808
+ return lastBand
809
+ }
810
+
811
+ /** The window in thirds: the bands used while the float is alone. */
812
+ function thirds(width, height) {
813
+ return { left: Math.round(width / 3), right: Math.round((width * 2) / 3), width, height }
814
+ }
815
+ function zoneAt(x, band) {
816
+ if (x <= band.left) return 'left'
817
+ if (x >= band.right) return 'right'
818
+ return 'center'
819
+ }
820
+
821
+ const ZONE_LABEL = { left: t('stow'), center: t('center'), right: t('dock') }
822
+
823
+ function previewRect(zone, band) {
824
+ if (zone === 'left') return [0, 0, band.left, band.height]
825
+ if (zone === 'right') return [band.right, 0, band.width - band.right, band.height]
826
+ return [band.left, 0, band.right - band.left, band.height]
827
+ }
828
+
829
+ /**
830
+ * Draw the band outline. Only runs when the band changes: the first version
831
+ * rewrote four styles (after a layout read) on every pointer move, and that
832
+ * is what made the drag stutter next to DSH's own dragging.
833
+ */
834
+ function showPreview(zone, band) {
835
+ if (preview === null) {
836
+ const el = document.createElement('div')
837
+ el.className = 'dsw-preview'
838
+ const label = document.createElement('span')
839
+ label.className = 'dsw-preview-label'
840
+ el.appendChild(label)
841
+ document.body.appendChild(el)
842
+ preview = { el, label, zone: null }
843
+ }
844
+ if (preview.zone === zone) return
845
+ if (preview.el.style.display === 'none') preview.el.style.display = ''
846
+ preview.zone = zone
847
+ const [left, top, width, height] = previewRect(zone, band)
848
+ preview.el.style.transform = `translate3d(${left}px, ${top}px, 0)`
849
+ preview.el.style.width = `${width}px`
850
+ preview.el.style.height = `${height}px`
851
+ preview.label.textContent = ZONE_LABEL[zone] ?? ''
852
+ }
853
+
854
+ function hidePreview() {
855
+ // The node is kept, not destroyed: appending and removing it on every band
856
+ // change is a subtree mutation per change, which the DOM watcher then has
857
+ // to service in the middle of a drag.
858
+ if (preview === null) return
859
+ preview.zone = null
860
+ preview.el.style.display = 'none'
861
+ }
862
+
863
+ /* ------------------------------------------------------------ the drop */
864
+
865
+ /**
866
+ * Stow the float: the panel stays mounted (so the Conversation keeps its
867
+ * single host and the centre column stays empty, exactly as it does while
868
+ * the float is on screen) but becomes invisible. The left sidebar row is
869
+ * the way back.
870
+ */
871
+ function floatPanel() {
872
+ const column = movedColumn
873
+ const fromColumn = column === null ? null : column.closest(`[${FLOAT_ATTR}]`)
874
+ return fromColumn ?? document.querySelector(`[${FLOAT_ATTR}]`)
875
+ }
876
+
877
+ function stowFloat() {
878
+ const el = floatPanel()
879
+ if (el === null) return false
880
+ el.setAttribute(STOW_ATTR, '')
881
+ return true
882
+ }
883
+
884
+ function unstowFloat() {
885
+ for (const el of document.querySelectorAll(`[${STOW_ATTR}]`)) el.removeAttribute(STOW_ATTR)
886
+ }
887
+
888
+ function drop(zone) {
889
+ if (zone === 'right') {
890
+ dockedLeft = false
891
+ dockingRight = true
892
+ // The float leaves as an ordinary right-sidebar tab. The sidebar
893
+ // snapshot belonged to the float: keeping it would let a close of that
894
+ // tab — possibly hours later — move the sidebars back in time.
895
+ savedChrome = null
896
+ chromeTouched = false
897
+ unstowFloat()
898
+ syncDockRow()
899
+ try {
900
+ sidebarRight?.openResource(CHAT_ADDRESS, { kind: CHAT_KIND, destination: 'sidebar' })
901
+ } catch (error) {
902
+ console.warn('[conversation-float] could not dock to the right sidebar:', error)
903
+ }
904
+ return
905
+ }
906
+ if (zone === 'left') {
907
+ dockedLeft = true
908
+ syncDockRow()
909
+ if (!stowFloat()) closeFloat()
910
+ // The drawer row lives in the left sidebar: bring the chrome back so it
911
+ // can be seen and clicked.
912
+ revealChrome()
913
+ return
914
+ }
915
+ dockedLeft = false
916
+ syncDockRow()
917
+ revealChrome()
918
+ closeFloat()
919
+ }
920
+
921
+ /**
922
+ * Watch the float's own drag. DSH owns the dragging; we only listen. A press
923
+ * on the float's chrome opens a sequence; a press inside the Conversation
924
+ * column does not, because that one is a text selection.
925
+ */
926
+ function trackPanelDrag(container) {
927
+ let down = null
928
+ let band = null
929
+ let root = null
930
+ let frame = 0
931
+ let pending = null
932
+ /** The band under the pointer right now. */
933
+ let hovered = null
934
+ /** The band the outline currently shows. */
935
+ let drawn = null
936
+ /** Set once the press has been held long enough to mean business. */
937
+ let judging = false
938
+ let judgeTimer = 0
939
+ /** Finger jitter below this is not a move: touch always drifts. */
940
+ const SLOP = 10
941
+
942
+ /** Resolved per pointer sequence: the panel mounts after this body does. */
943
+ const floatRoot = () => {
944
+ if (root !== null && root.isConnected) return root
945
+ root = container.isConnected ? container.closest(`[${FLOAT_ATTR}]`) : null
946
+ return root
947
+ }
948
+
949
+ const stopJudge = () => {
950
+ if (judgeTimer === 0) return
951
+ window.clearTimeout(judgeTimer)
952
+ judgeTimer = 0
953
+ }
954
+
955
+ /** Redraw only when the band under the pointer actually differs. */
956
+ const paint = () => {
957
+ if (!judging || drawn === hovered) return
958
+ drawn = hovered
959
+ if (drawn === null) hidePreview()
960
+ else showPreview(drawn, band)
961
+ }
962
+
963
+ const onDown = (event) => {
964
+ if (event.button !== 0) return
965
+ const panel = floatRoot()
966
+ if (panel === null) {
967
+ down = null
968
+ return
969
+ }
970
+ // The handle is the float's own chrome. A press that lands anywhere
971
+ // else — a sidebar row, the frame's title bar, another panel — must not
972
+ // arm a drop: holding it for two seconds and then releasing over a band
973
+ // would move a session the user never grabbed.
974
+ const target = event.target
975
+ const path = typeof event.composedPath === 'function' ? event.composedPath() : []
976
+ const onPanel = path.includes(panel) || (target instanceof Node && panel.contains(target))
977
+ if (!onPanel) {
978
+ down = null
979
+ return
980
+ }
981
+ // A press inside the Conversation is a text selection, not the panel's
982
+ // drag. Everything else on the float is its chrome.
983
+ if (movedColumn !== null && target instanceof Node && movedColumn.contains(target)) {
984
+ down = null
985
+ return
986
+ }
987
+ down = { x: event.clientX, y: event.clientY, lastX: event.clientX, lastY: event.clientY, moved: false, at: performance.now() }
988
+ // The bands cannot move under a drag: read them once, here.
989
+ band = bands()
990
+ hovered = null
991
+ drawn = null
992
+ judging = false
993
+ armJudge()
994
+ }
995
+
996
+ /**
997
+ * Arm the hold. It has to be a STILL hold: any movement past the slop
998
+ * restarts this, so grabbing the panel and dragging at once never counts.
999
+ */
1000
+ const armJudge = () => {
1001
+ stopJudge()
1002
+ judgeTimer = window.setTimeout(() => {
1003
+ judgeTimer = 0
1004
+ if (down === null) return
1005
+ // Coalesced or missed move events cannot fool this: compare the
1006
+ // last known pointer position before calling it a still hold.
1007
+ const stillFor = performance.now() - (down.movedAt ?? down.at)
1008
+ if (stillFor < DWELL_MS - 40) {
1009
+ armJudge()
1010
+ return
1011
+ }
1012
+ judging = true
1013
+ // A still hold never produced a move, so take the band from where
1014
+ // the pointer is right now instead of leaving it unset.
1015
+ if (hovered === null) hovered = zoneAt(down.lastX ?? down.x, band)
1016
+ paint()
1017
+ }, DWELL_MS)
1018
+ }
1019
+
1020
+ /** One layout-independent pass per animation frame, never per event. */
1021
+ const flush = () => {
1022
+ frame = 0
1023
+ const event = pending
1024
+ pending = null
1025
+ if (event === null || down === null) return
1026
+ down.lastX = event.clientX
1027
+ down.lastY = event.clientY
1028
+ const dx = event.clientX - down.x
1029
+ const dy = event.clientY - down.y
1030
+ if (dx * dx + dy * dy > SLOP * SLOP) {
1031
+ down.moved = true
1032
+ down.movedAt = performance.now()
1033
+ if (!judging) {
1034
+ // Still not armed: measure the hold from here, not from the press.
1035
+ down.x = event.clientX
1036
+ down.y = event.clientY
1037
+ armJudge()
1038
+ }
1039
+ }
1040
+ hovered = zoneAt(event.clientX, band)
1041
+ paint()
1042
+ }
1043
+
1044
+ const onMove = (event) => {
1045
+ if (down === null) return
1046
+ pending = event
1047
+ if (frame !== 0) return
1048
+ frame = window.requestAnimationFrame(flush)
1049
+ }
1050
+
1051
+ const settle = () => {
1052
+ if (frame !== 0) {
1053
+ window.cancelAnimationFrame(frame)
1054
+ frame = 0
1055
+ }
1056
+ if (pending !== null) flush()
1057
+ stopJudge()
1058
+ const target = judging ? hovered : null
1059
+ down = null
1060
+ band = null
1061
+ pending = null
1062
+ hovered = null
1063
+ drawn = null
1064
+ judging = false
1065
+ hidePreview()
1066
+ return { target }
1067
+ }
1068
+
1069
+ const onUp = () => {
1070
+ if (down === null) return
1071
+ const result = settle()
1072
+ if (result.target !== null) drop(result.target)
1073
+ }
1074
+
1075
+ const onCancel = () => {
1076
+ if (down === null) return
1077
+ settle()
1078
+ }
1079
+
1080
+ // Both channels: a real drag reports pointer events, while synthesised
1081
+ // input (and some remote-input paths) can report mouse events only. The
1082
+ // handlers are shared, and the frame gate keeps the doubled stream cheap.
1083
+ // Touch arrives as its own event family on some WebViews; wrap it in the
1084
+ // shape the shared handlers read. Pointer events also fire on modern
1085
+ // browsers and the frame gate keeps the doubled stream cheap.
1086
+ const touchPoint = (event) => {
1087
+ const touch = (event.touches && event.touches[0]) || (event.changedTouches && event.changedTouches[0])
1088
+ if (touch === undefined) return null
1089
+ return { button: 0, clientX: touch.clientX, clientY: touch.clientY, target: event.target, composedPath: () => event.composedPath?.() ?? [] }
1090
+ }
1091
+ const onTouchDown = (event) => {
1092
+ const point = touchPoint(event)
1093
+ if (point !== null) onDown(point)
1094
+ }
1095
+ const onTouchMove = (event) => {
1096
+ const point = touchPoint(event)
1097
+ if (point !== null) onMove(point)
1098
+ }
1099
+ const onTouchUp = (event) => {
1100
+ const point = touchPoint(event)
1101
+ if (point !== null) onUp(point)
1102
+ }
1103
+ const pairs = [
1104
+ ['pointerdown', onDown],
1105
+ ['pointermove', onMove],
1106
+ ['pointerup', onUp],
1107
+ ['pointercancel', onCancel],
1108
+ ['mousedown', onDown],
1109
+ ['mousemove', onMove],
1110
+ ['mouseup', onUp],
1111
+ ['touchstart', onTouchDown],
1112
+ ['touchmove', onTouchMove],
1113
+ ['touchend', onTouchUp],
1114
+ ['touchcancel', onCancel],
1115
+ ]
1116
+ for (const [name, handler] of pairs) window.addEventListener(name, handler, { capture: true, passive: name !== 'touchmove' })
1117
+ // Only the window's own blur. Captured, this would also fire for every
1118
+ // descendant losing focus — a focused input blurring would cancel a drag
1119
+ // that is still going on.
1120
+ const onWindowBlur = (event) => {
1121
+ if (event.target === window || event.target === document) onCancel()
1122
+ }
1123
+ window.addEventListener('blur', onWindowBlur)
1124
+ return () => {
1125
+ for (const [name, handler] of pairs) window.removeEventListener(name, handler, true)
1126
+ window.removeEventListener('blur', onWindowBlur)
1127
+ onCancel()
1128
+ }
1129
+ }
1130
+
1131
+ /* ----------------------------------------------------------- the drawer */
1132
+
1133
+ function syncDockRow() {
1134
+ if (dockedLeft && dockRow === null) {
1135
+ try {
1136
+ dockRow = ctxRef.slots.register(
1137
+ { name: 'sidebar.panellist', id: DOCK_ROW_ID, order: 20, label: () => t('floatTitle') },
1138
+ DockIcon,
1139
+ )
1140
+ } catch (error) {
1141
+ console.warn('[conversation-float] could not register the sidebar row:', error)
1142
+ dockRow = null
1143
+ }
1144
+ } else if (!dockedLeft && dockRow !== null) {
1145
+ try {
1146
+ dockRow()
1147
+ } catch {
1148
+ /* already disposed with the slot */
1149
+ }
1150
+ dockRow = null
1151
+ }
1152
+ }
1153
+
1154
+ let ctxRef = null
1155
+
1156
+ /* ---------------------------------------------------------- components */
1157
+
1158
+ function Icon({ name, size = 16 }) {
1159
+ const paths = ICONS[name] ?? ICONS.dot
1160
+ return h(
1161
+ 'svg',
1162
+ {
1163
+ viewBox: '0 0 24 24', width: size, height: size, fill: 'none',
1164
+ stroke: 'currentColor', strokeWidth: 1.7, strokeLinecap: 'round',
1165
+ strokeLinejoin: 'round', 'aria-hidden': true, style: { display: 'block' },
1166
+ },
1167
+ paths.map((d, index) => h('path', { key: index, d })),
1168
+ )
1169
+ }
1170
+
1171
+ const ICONS = {
1172
+ 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'],
1173
+ dot: ['M12 12h.01'],
1174
+ }
1175
+
1176
+ const CSS = `
1177
+ .dsw-icon {
1178
+ display: inline-flex; align-items: center; justify-content: center;
1179
+ width: 26px; height: 26px; padding: 0; border: 0; border-radius: 7px;
1180
+ background: transparent; color: var(--dsw-alias-label-secondary); cursor: pointer;
1181
+ transition: background .12s ease, color .12s ease;
1182
+ }
1183
+ .dsw-icon:hover { background: var(--dsw-alias-bg-layer-2); color: var(--dsw-alias-label-primary); }
1184
+ .dsw-icon:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }
1185
+ .dsw-host {
1186
+ position: relative;
1187
+ display: flex; flex-direction: column;
1188
+ width: 100%; height: 100%; min-height: 0; overflow: hidden;
1189
+ background: var(--dsw-alias-bg-base);
1190
+ }
1191
+ .dsw-preview {
1192
+ position: fixed; left: 0; top: 0; z-index: 90; pointer-events: none;
1193
+ will-change: transform, width, height;
1194
+ border: 2px dashed var(--dsw-alias-brand-primary, #4d6bfe);
1195
+ border-radius: 12px;
1196
+ box-sizing: border-box;
1197
+ background: color-mix(in srgb, var(--dsw-alias-brand-primary, #4d6bfe) 12%, transparent);
1198
+ display: flex; align-items: center; justify-content: center;
1199
+ transition: transform .09s ease, width .09s ease, height .09s ease;
1200
+ }
1201
+ /* The float, stowed in the left drawer: mounted, so the centre stays empty. */
1202
+ [data-dsh-conversation-float-stowed] {
1203
+ opacity: 0 !important;
1204
+ visibility: hidden !important;
1205
+ pointer-events: none !important;
1206
+ }
1207
+ /* Touch: the grip owns the gesture, so a press is not turned into a scroll. */
1208
+ [data-dsh-conversation-float-float] [data-dockkit-float-grip] {
1209
+ touch-action: none;
1210
+ -webkit-user-select: none; user-select: none;
1211
+ -webkit-touch-callout: none;
1212
+ }
1213
+ /* Everything the float hides while it is the only thing on screen. */
1214
+ [data-dsh-conversation-float-chromeless] {
1215
+ display: none !important;
1216
+ }
1217
+ .dsw-preview-label {
1218
+ font-size: 15px; font-weight: 600; letter-spacing: .04em;
1219
+ color: var(--dsw-alias-brand-primary, #4d6bfe);
1220
+ background: var(--dsw-alias-bg-base, #fff);
1221
+ border-radius: 999px; padding: 4px 14px;
1222
+ }
1223
+ `
1224
+
1225
+ function Styles() {
1226
+ return h('style', { 'data-plugin-css': NS }, CSS)
1227
+ }
1228
+
1229
+ /**
1230
+ * The entry's job depends on the state: with no float it opens one (leaving
1231
+ * the window to the float alone), and with a float on screen it brings the
1232
+ * rest of DSH back — or hides it again.
1233
+ */
1234
+ function onEntryClick() {
1235
+ // Docked in the right sidebar (or stowed in the drawer) there is no
1236
+ // float panel to toggle: the button must bring the float back instead.
1237
+ if (dockedLeft || floatPanel() === null) {
1238
+ openFloating()
1239
+ return
1240
+ }
1241
+ if (chromeless) revealChrome()
1242
+ else setChromeless(true)
1243
+ }
1244
+
1245
+ /** Escape always brings DSH back: the way out of a hidden window. */
1246
+ function escapeOnKey(event) {
1247
+ if (event.key !== 'Escape' || !chromeless) return
1248
+ revealChrome()
1249
+ }
1250
+
1251
+ /** Conversation-header entry: opens the float, or reveals DSH behind it. */
1252
+ function HeaderAction() {
1253
+ const [, bump] = React.useState(0)
1254
+ React.useEffect(() => {
1255
+ const fn = () => bump((n) => n + 1)
1256
+ stateListeners.add(fn)
1257
+ return () => stateListeners.delete(fn)
1258
+ }, [])
1259
+ return h(
1260
+ 'button',
1261
+ {
1262
+ type: 'button',
1263
+ className: 'dsw-icon',
1264
+ title: chromeless ? t('showDsh') : t('floatTitle'),
1265
+ 'aria-label': chromeless ? t('showDsh') : t('floatTitle'),
1266
+ [ANCHOR_ATTR]: '',
1267
+ onClick: onEntryClick,
1268
+ },
1269
+ h(Styles),
1270
+ h(Icon, { name: 'window' }),
1271
+ )
1272
+ }
1273
+
1274
+ /** The left sidebar row's glyph. The row itself is owned by the sidebar. */
1275
+ function DockIcon({ size = 16 }) {
1276
+ return h(Icon, { name: 'window', size })
1277
+ }
1278
+
1279
+ /**
1280
+ * The main panel this row addresses. It only exists so a click on the row
1281
+ * cannot leave the centre column on an empty page: the click re-opens the
1282
+ * float and hands the centre back to the conversation.
1283
+ */
1284
+ function DockPanel() {
1285
+ React.useEffect(() => {
1286
+ openFloating()
1287
+ try {
1288
+ layout?.selectPanel?.(null)
1289
+ } catch (error) {
1290
+ console.warn('[conversation-float] could not restore the conversation panel:', error)
1291
+ }
1292
+ }, [])
1293
+ return null
1294
+ }
1295
+
1296
+ /** The floating panel's body: it holds the live Conversation column. */
1297
+ function SessionPanel() {
1298
+ const host = React.useRef(null)
1299
+ React.useLayoutEffect(() => {
1300
+ const container = host.current
1301
+ if (container === null) return undefined
1302
+ attachColumn(container)
1303
+ // Only the floating occurrence is draggable; a tab docked in the right
1304
+ // sidebar must not arm the drop bands at all. The panel element mounts
1305
+ // after this body does, so the tracker resolves it per pointer sequence.
1306
+ const stop = trackPanelDrag(container)
1307
+ return () => {
1308
+ stop()
1309
+ detachColumn()
1310
+ }
1311
+ }, [])
1312
+ return h('div', { className: 'dsw-host', ref: host }, h(Styles))
1313
+ }
1314
+
1315
+ /* --------------------------------------------------------------- wiring */
1316
+
1317
+ return {
1318
+ inject: ['slots', 'locale'],
1319
+ apply(ctx) {
1320
+ ctxRef = ctx
1321
+ ctx.effect(() => {
1322
+ try {
1323
+ return ctx.locale.register(NS, Object.fromEntries(LOCALES.map((id) => [id, { title: COPY[id].floatTitle, description: COPY[id].description }])))
1324
+ } catch {
1325
+ return () => {}
1326
+ }
1327
+ })
1328
+
1329
+ const register = (slot, id, component, options = {}) =>
1330
+ ctx.effect(() =>
1331
+ ctx.slots.inject(slot, () =>
1332
+ ctx.slots.register({ name: slot, id, locale: NS, ...options }, component),
1333
+ ),
1334
+ )
1335
+
1336
+ register('conversation.session.header.utilities', 'conversation-float-control', HeaderAction, { order: 30 })
1337
+
1338
+ ctx.effect(() => watchColumn())
1339
+
1340
+ ctx.effect(() => {
1341
+ window.addEventListener('keydown', escapeOnKey, true)
1342
+ return () => window.removeEventListener('keydown', escapeOnKey, true)
1343
+ })
1344
+
1345
+ // A press or a key is the only evidence that a column moved by the
1346
+ // user's hand rather than by DSH re-railing it.
1347
+ ctx.effect(() => {
1348
+ document.addEventListener('pointerdown', noteGesture, true)
1349
+ document.addEventListener('keydown', noteGesture, true)
1350
+ return () => {
1351
+ document.removeEventListener('pointerdown', noteGesture, true)
1352
+ document.removeEventListener('keydown', noteGesture, true)
1353
+ }
1354
+ })
1355
+
1356
+ // One frame after load, give any float already on screen its size.
1357
+ ctx.effect(() => {
1358
+ const id = window.requestAnimationFrame(() => sizeFloat())
1359
+ return () => window.cancelAnimationFrame(id)
1360
+ })
1361
+ // A reload can leave the last run's hidden columns behind.
1362
+ // An earlier build parked the View tab strip in the main window; put it
1363
+ // back inside the Conversation column and drop the parked container.
1364
+ for (const dock of document.querySelectorAll('.dsw-tabdock')) {
1365
+ const strip = dock.querySelector('[data-conversation-tabs]')
1366
+ const column = document.querySelector('[data-conversation-session]')
1367
+ if (strip !== null && column !== null && !column.contains(strip)) {
1368
+ column.insertBefore(strip, column.firstChild)
1369
+ }
1370
+ dock.remove()
1371
+ }
1372
+ // A previous build hid the two shipped View buttons; put them back.
1373
+ for (const el of document.querySelectorAll('[data-dsh-conversation-float-core-tab]')) el.removeAttribute('data-dsh-conversation-float-core-tab')
1374
+ setChromeless(false)
1375
+
1376
+ ctx.effect(() =>
1377
+ ctx.slots.inject('main', () =>
1378
+ ctx.slots.register({ name: 'main', key: DOCK_ROW_ID, locale: NS }, DockPanel),
1379
+ ),
1380
+ )
1381
+
1382
+ ctx.effect(() => {
1383
+ const dispose = ctx.inject(['layout'], (sub) => {
1384
+ layout = sub.layout ?? null
1385
+ return () => {
1386
+ layout = null
1387
+ }
1388
+ })
1389
+ return dispose
1390
+ })
1391
+
1392
+ ctx.effect(() =>
1393
+ ctx.inject(['sidebarRightTabs', 'sidebarRight'], (sub) => {
1394
+ sidebarRight = sub.sidebarRight ?? null
1395
+ sub.effect(() =>
1396
+ sub.sidebarRightTabs.register({
1397
+ id: CHAT_ID,
1398
+ kind: CHAT_KIND,
1399
+ title: () => t('conversation'),
1400
+ }),
1401
+ )
1402
+ sub.effect(() =>
1403
+ sub.slots.inject('sidebar.right.pane.tab', () =>
1404
+ sub.slots.register({ name: 'sidebar.right.pane.tab', key: CHAT_ID, locale: NS }, SessionPanel),
1405
+ ),
1406
+ )
1407
+ return () => {
1408
+ sidebarRight = null
1409
+ hidePreview()
1410
+ if (dockedLeft) {
1411
+ dockedLeft = false
1412
+ syncDockRow()
1413
+ }
1414
+ detachColumn()
1415
+ }
1416
+ }),
1417
+ )
1418
+
1419
+ window.__dshSessionWindow = {
1420
+ open: openFloating,
1421
+ findColumn,
1422
+ bands,
1423
+ get moved() {
1424
+ return movedColumn !== null
1425
+ },
1426
+ get dockedLeft() {
1427
+ return dockedLeft
1428
+ },
1429
+ }
1430
+ ctx.effect(() => () => {
1431
+ hidePreview()
1432
+ unstowFloat()
1433
+ // Unloading is not a user close: leave the sidebars alone.
1434
+ suspendRestore = true
1435
+ detachColumn()
1436
+ delete window.__dshSessionWindow
1437
+ })
1438
+ },
1439
+ }
1440
+ },
1441
+ })