Repository navigation
Expand file tree
/
Copy pathsession-tabs.tsx
More file actions
1779 lines (1740 loc) · 72.1 KB
/
Copy pathsession-tabs.tsx
File metadata and controls
1779 lines (1740 loc) · 72.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
BoxRenderable,
CliRenderEvents,
RGBA,
ScrollBoxRenderable,
TextAttributes,
type MouseEvent,
} from "@opentui/core"
import {
For,
Index,
Match,
Show,
Switch,
createComputed,
createEffect,
createMemo,
createSignal,
onCleanup,
untrack,
} from "solid-js"
import { Portal, useRenderer, useTerminalDimensions } from "@opentui/solid"
import { useConfig } from "../config"
import { useSessionTabs } from "../context/session-tabs"
import { useData } from "../context/data"
import { useClipboard } from "../context/clipboard"
import { useTheme } from "../context/theme"
import {
adaptiveSessionTabLayout,
moveSessionTab,
NEW_SESSION_TAB_TITLE,
sessionTabComplete,
sessionTabDetail,
sessionTabNumberLabel,
seedSessionTabMotion,
sessionTabOverflowWidth,
type SessionTab,
type SessionTabUnread,
} from "../context/session-tabs-model"
import { createAnimatable, spring, tween } from "../ui/animation"
import { Locale } from "../util/locale"
import { TabPulse, unreadGlowIntensity } from "./tab-pulse"
import { tint } from "../theme/color"
import { SESSION_SIDEBAR_WIDTH, SESSION_TABS_COMPACT_BREAKPOINT } from "../ui/layout"
import { projectName } from "../util/project"
import { marqueeCycleWidth, marqueeOverflows, marqueeTextParts } from "../util/marquee"
import { useDialog } from "../ui/dialog"
import { useToast } from "../ui/toast"
import { DialogSessionRename } from "./dialog-session-rename"
import { Keymap } from "../context/keymap"
import { registerOpencodeSpinner } from "./register-spinner"
import { SPINNER_FRAMES } from "./spinner-frames"
import { SessionTabsRailControls, SessionTabHalfRow } from "./session-tabs-rail"
import "./title-shimmer"
registerOpencodeSpinner()
export const TAB_SPINNERS = {
dots: { frames: SPINNER_FRAMES, interval: 80 },
arcs: { frames: ["◜", "◝", "◞", "◟"], interval: 120 },
quadrants: { frames: ["◴", "◷", "◶", "◵"], interval: 120 },
line: { frames: ["|", "/", "-", "\\"], interval: 120 },
}
export type TabSpinner = keyof typeof TAB_SPINNERS
export const TAB_UNREAD_MARKERS = {
"small-dot": "•",
dot: "●",
square: "▪",
"large-square": "■",
}
export type TabUnreadMarker = keyof typeof TAB_UNREAD_MARKERS
// A long title fades out over its last cells instead of cutting hard.
const FADE_WIDTH = 4
// The add button renders as " + " at the end of the strip, so the tab layout leaves it room.
const ADD_TAB_WIDTH = 3
const MARQUEE_DELAY = 600
const MARQUEE_INTERVAL = 80
const CONTEXT_MENU_WIDTH = 20
const MIDDLE_MOUSE_BUTTON = 1
const RIGHT_MOUSE_BUTTON = 2
const MOUSE_CLOSE_HOLD_MS = 5_000
type MouseCloseHold = {
items: string[]
ids: string[]
widths: number[]
closed: string
target: string
x: number
}
type TabContextMenuState = {
x: number
y: number
sessionID?: string
title?: string
}
type ContextController = ReturnType<typeof useSessionTabs>
export type SessionTabsStatus = Omit<ReturnType<ContextController["status"]>, "unread"> & {
unread: SessionTabUnread | undefined
}
export const EMPTY_SESSION_TAB_STATUS: SessionTabsStatus = {
unread: undefined,
promptPulse: 0,
attention: false,
busy: false,
renaming: false,
}
export type SessionTabsController = Pick<ContextController, "tabs" | "current" | "select" | "close" | "move"> & {
newTab?: () => boolean
add?: () => void
detail?: (sessionID: string) => string | undefined
rename?: (sessionID: string) => void
search?: () => void
status(sessionID: string): SessionTabsStatus
}
const NEW_SESSION_TAB: SessionTab = { sessionID: "new", title: NEW_SESSION_TAB_TITLE }
const glowTextColor = (base: RGBA, glow: RGBA, index: number, width: number, level = 1) =>
tint(base, glow, 0.12 * unreadGlowIntensity(index, width) * level)
function tabFeedbackColor(status: SessionTabsStatus, theme: ReturnType<typeof useTheme>) {
if (status.attention) return theme.hue.accent[200]
if (status.unread === "error") return theme.text.feedback.error.base
return undefined
}
function TabIndicator(props: {
status: SessionTabsStatus
label: string
idleLabel?: string
width: number
centered?: boolean
color: RGBA
unreadColor: RGBA
backgroundColor: RGBA
flashColor: RGBA
animations: boolean
numbers: boolean
selected?: boolean
spinner?: TabSpinner
unreadMarker?: TabUnreadMarker
attributes?: number
}) {
const runs = () => props.status.busy && !props.status.attention
const pending = createMemo(() => props.status.busy || Boolean(props.status.attention))
const unread = createMemo(() => Boolean(props.status.unread) && !pending())
const unreadColor = createMemo<RGBA>((previous) => (unread() ? props.unreadColor : previous), props.unreadColor)
const fade = createAnimatable(
{ opacity: unread() ? 1 : 0 },
{ enabled: () => props.animations, transition: tween({ duration: 0.18 }) },
)
createComputed(() => {
if (unread()) return fade.jump({ opacity: 1 })
if (pending()) return fade.jump({ opacity: 0 })
fade.animate({ opacity: 0 })
})
const fading = () => !props.status.unread && fade.value().opacity > 0
const color = () => {
if (props.numbers || props.selected) return props.color
if (unread()) return props.unreadColor
if (!fading()) return props.color
const opacity = fade.value().opacity
// Brighten during the first fifth, then dissolve into the tab background.
const flash = Math.max(0, 1 - Math.abs(opacity - 0.8) / 0.2)
return tint(props.backgroundColor, tint(unreadColor(), props.flashColor, flash * 0.3), Math.min(1, opacity / 0.8))
}
const spinner = () => TAB_SPINNERS[props.spinner ?? "dots"]
const label = () => {
if (props.numbers) return props.label
if (props.status.attention === "permission") return "!"
if (props.status.attention === "question") return "?"
if (runs()) return spinner().frames[0]
if (props.label === "+") return "+"
if (props.status.unread || fading()) return TAB_UNREAD_MARKERS[props.unreadMarker ?? "small-dot"]
return props.idleLabel ?? ""
}
return (
<box
width={props.width + (props.centered ? 0 : 1)}
height={props.centered ? 1 : undefined}
flexShrink={0}
flexDirection="row"
justifyContent={props.centered ? "center" : "flex-end"}
paddingRight={props.centered ? 0 : 1}
>
<Show
when={runs() && props.animations && !props.numbers}
fallback={
<text fg={color()} selectable={false} attributes={props.attributes}>
{label()}
</text>
}
>
<spinner frames={spinner().frames} interval={spinner().interval} color={props.color} />
</Show>
</box>
)
}
function createGlowLevel(dimmed: () => boolean, animations: () => boolean) {
const motion = createAnimatable(
{ level: dimmed() ? 0.7 : 1 },
{ enabled: animations, transition: tween({ duration: 0.2 }) },
)
createEffect(() => motion.animate({ level: dimmed() ? 0.7 : 1 }))
return () => motion.value().level
}
function createNumberIgnition(runs: () => boolean, prompt: () => number, animations: () => boolean) {
const ignition = createAnimatable({ level: 0 }, { enabled: animations, transition: tween({ duration: 0.7 }) })
let wasRunning = runs()
let promptPulse = prompt()
createEffect(() => {
const running = runs()
const nextPromptPulse = prompt()
if (running !== wasRunning || nextPromptPulse !== promptPulse) {
ignition.jump({ level: 0.85 })
ignition.animate({ level: 0 })
}
wasRunning = running
promptPulse = nextPromptPulse
})
return ignition
}
function fadeTitleColor(color: RGBA, background: RGBA, index: number, length: number, leading: number) {
const fade = (position: number) => (position <= 0 ? 0 : 0.2 + 0.72 * ((position - 1) / Math.max(1, FADE_WIDTH - 1)))
const start = index < FADE_WIDTH ? FADE_WIDTH - index : 0
const end = index - (length - FADE_WIDTH) + 1
const opacity = Math.max(fade(start) * leading, fade(end))
return opacity === 0 ? color : tint(color, background, opacity)
}
function heldSessionTabLayout(hold: MouseCloseHold, tabs: readonly SessionTab[]) {
const ids = tabs.map((tab) => tab.sessionID)
const expected = hold.items.filter((id) => id !== hold.closed)
const unchanged = ids.length === hold.items.length && ids.every((id, index) => id === hold.items[index])
const removed = ids.length === expected.length && ids.every((id, index) => id === expected[index])
if (!unchanged && !removed) return undefined
const visibleIDs = hold.ids.filter((id) => ids.includes(id))
if (removed && !visibleIDs.includes(hold.target)) {
visibleIDs.push(hold.target)
visibleIDs.sort((a, b) => ids.indexOf(a) - ids.indexOf(b))
}
const positions = visibleIDs.map((id) => ids.indexOf(id))
const start = positions[0]
if (start === undefined || positions.some((position, index) => position !== start + index)) return undefined
const visible = visibleIDs.flatMap((id) => tabs.find((tab) => tab.sessionID === id) ?? [])
if (visible.length !== visibleIDs.length) return undefined
const widths = visibleIDs.map((id) => hold.widths[hold.ids.indexOf(id)] ?? 1)
if (removed) {
const index = visibleIDs.indexOf(hold.target)
if (index === -1) return undefined
const leading = start > 0 ? sessionTabOverflowWidth(start) : 0
const preceding = widths.slice(0, index).reduce((sum, width) => sum + width, 0)
// The close glyph sits one cell in from the right edge: x = tab start + width - 2.
const width = hold.x - leading - preceding + 2
if (width < 1) return undefined
widths[index] = width
}
return {
tabs: visible,
widths,
before: start,
after: tabs.length - start - visible.length,
start,
total: widths.reduce((sum, width) => sum + width, 0),
}
}
export function createMarquee(animations: () => boolean) {
const [offset, setOffset] = createSignal(0)
const [active, setActive] = createSignal<string>()
const leading = createAnimatable({ opacity: 0 }, { enabled: animations, transition: tween({ duration: 0.25 }) })
let delay: ReturnType<typeof setTimeout> | undefined
let interval: ReturnType<typeof setInterval> | undefined
let cycleWidth = 0
const clear = () => {
if (delay) clearTimeout(delay)
if (interval) clearInterval(interval)
delay = undefined
interval = undefined
}
const scroll = () => {
interval = setInterval(
() =>
setOffset((value) => {
if (value + 1 < cycleWidth) return value + 1
clear()
leading.animate({ opacity: 0 })
return 0
}),
MARQUEE_INTERVAL,
)
}
const enter = (sessionID: string, title: string, width: number) => {
if (!marqueeOverflows(title, width)) {
reset()
return
}
if (active() === sessionID) return
clear()
cycleWidth = marqueeCycleWidth(title)
setActive(sessionID)
setOffset(0)
leading.jump({ opacity: 0 })
delay = setTimeout(() => {
setOffset(1)
leading.animate({ opacity: 1 })
scroll()
}, MARQUEE_DELAY)
}
const leave = (sessionID: string) => {
if (active() !== sessionID) return
reset()
}
const reset = () => {
clear()
setActive(undefined)
setOffset(0)
leading.jump({ opacity: 0 })
}
onCleanup(clear)
return { offset, active, enter, leave, reset, leading: () => leading.value().opacity }
}
export function createTabMarquee(animations: () => boolean) {
const [hovered, setHovered] = createSignal<string>()
const marquee = createMarquee(animations)
let hoverClear: ReturnType<typeof setTimeout> | undefined
const enter = (sessionID: string, title: string, width: number) => {
if (hoverClear) clearTimeout(hoverClear)
setHovered(sessionID)
marquee.enter(sessionID, title, width)
}
const leave = (sessionID: string) => {
if (hoverClear) clearTimeout(hoverClear)
hoverClear = setTimeout(() => {
if (hovered() !== sessionID) return
setHovered(undefined)
marquee.leave(sessionID)
})
}
const leaveHovered = () => {
const sessionID = hovered()
if (sessionID) leave(sessionID)
}
const reset = () => {
if (hoverClear) clearTimeout(hoverClear)
hoverClear = undefined
setHovered(undefined)
marquee.reset()
}
onCleanup(() => {
if (hoverClear) clearTimeout(hoverClear)
})
return { ...marquee, hovered, enter, leave, leaveHovered, reset }
}
function TabContextMenu(props: { state: TabContextMenuState; tabs: SessionTabsController; onClose: () => void }) {
const dimensions = useTerminalDimensions()
const theme = useTheme()
const background = () => theme.background.raised.base
const actionHovered = () => theme.background.raised.high
const dialog = useDialog()
const clipboard = useClipboard()
const toast = useToast()
onCleanup(Keymap.use().mode.push("menu"))
Keymap.createLayer(() => ({
mode: "menu",
commands: [{ bind: "escape,ctrl+c", title: "Close tab menu", group: "Tabs", run: props.onClose }],
}))
const actions = createMemo(() => {
const sessionID = props.state.sessionID
const title = props.state.title
return [
...(props.tabs.add ? [{ title: "New tab", run: () => props.tabs.add?.() }] : []),
...(sessionID
? [
{
title: "Rename",
run: () =>
props.tabs.rename ? props.tabs.rename(sessionID) : DialogSessionRename.show(dialog, sessionID, title),
},
{
title: "Copy session ID",
run: () =>
void clipboard
.write(sessionID)
.then(() => toast.show({ message: "Session ID copied to clipboard", variant: "info" }))
.catch(toast.error),
},
{ title: "Close", run: () => props.tabs.close(sessionID) },
]
: []),
]
})
const [selected, setSelected] = createSignal<number>()
const top = () => Math.max(0, Math.min(props.state.y + 1, dimensions().height - actions().length))
const left = () => Math.max(0, Math.min(props.state.x, dimensions().width - CONTEXT_MENU_WIDTH))
const run = (index: number) => {
const action = actions()[index]
props.onClose()
action?.run()
}
return (
<Portal
ref={(container) => {
if (!(container instanceof BoxRenderable)) return
// Portal's wrapper otherwise follows the full-height app in root layout.
container.position = "absolute"
container.left = 0
container.top = 0
container.zIndex = 2500
}}
>
<box
position="absolute"
left={0}
top={0}
width={dimensions().width}
height={dimensions().height}
zIndex={2500}
onMouseDown={(event) => {
props.onClose()
event.preventDefault()
event.stopPropagation()
}}
>
<box
position="absolute"
left={left()}
top={top()}
height={actions().length}
width={CONTEXT_MENU_WIDTH}
flexDirection="column"
backgroundColor={background()}
onMouseDown={(event) => {
if (event.button === RIGHT_MOUSE_BUTTON) props.onClose()
event.preventDefault()
event.stopPropagation()
}}
>
<For each={actions()}>
{(action, index) => (
<box
width="100%"
paddingLeft={1}
paddingRight={1}
backgroundColor={selected() === index() ? actionHovered() : undefined}
onMouseOver={() => setSelected(index())}
onMouseOut={() => setSelected(undefined)}
onMouseUp={(event) => {
event.preventDefault()
event.stopPropagation()
if (event.button === RIGHT_MOUSE_BUTTON) return
run(index())
}}
>
<text fg={theme.text.base} selectable={false}>
{action.title}
</text>
</box>
)}
</For>
</box>
</box>
</Portal>
)
}
export function SessionTabs(
props: {
controller?: SessionTabsController
animations?: boolean
spinner?: TabSpinner
unreadMarker?: TabUnreadMarker
indicators?: "status" | "numbers"
orientation?: "horizontal" | "vertical"
width?: number
} = {},
) {
const config = useConfig().data
return (
<Switch>
<Match when={props.orientation === "vertical"}>
<VerticalSessionTabs
controller={props.controller}
animations={props.animations}
spinner={props.spinner}
unreadMarker={props.unreadMarker}
numbers={(props.indicators ?? config.tabs.indicators) === "numbers"}
width={props.width}
/>
</Match>
<Match when={true}>
<HorizontalSessionTabs
controller={props.controller}
animations={props.animations}
spinner={props.spinner}
unreadMarker={props.unreadMarker}
numbers={(props.indicators ?? config.tabs.indicators) === "numbers"}
/>
</Match>
</Switch>
)
}
function VerticalSessionTabs(props: {
controller?: SessionTabsController
animations?: boolean
numbers: boolean
spinner?: TabSpinner
unreadMarker?: TabUnreadMarker
width?: number
}) {
const tabs: SessionTabsController = props.controller ?? useSessionTabs()
const data = props.controller ? undefined : useData()
const dimensions = useTerminalDimensions()
const renderer = useRenderer()
const theme = useTheme()
const background = () => theme.background.raised.base
const actionSelected = () => theme.background.action.primary.selected
const actionHovered = () => theme.background.raised.high
const base = useTheme()
const config = useConfig().data
const animations = () => props.animations ?? config.animations ?? true
const width = () => props.width ?? SESSION_SIDEBAR_WIDTH
const compact = createMemo(() => width() < SESSION_TABS_COMPACT_BREAKPOINT)
const tooltipWidth = () => Math.min(54, dimensions().width - width())
const stride = () => (compact() ? 2 : 3)
const unreadColor = () => theme.hue.accent[200]
const activeNumber = () => theme.hue.interactive[200]
const idleNumber = () => tint(theme.text.formfield.base, background(), 0.55)
const separatorUpperPulseColor = createMemo(() => tint(background(), theme.text.base, 0.04))
const separatorLowerPulseColor = createMemo(() => tint(background(), theme.text.base, 0.05))
const [addHovered, setAddHovered] = createSignal(false)
const marquee = createTabMarquee(animations)
const hovered = marquee.hovered
createEffect(() => {
compact()
untrack(marquee.reset)
})
const [hoverY, setHoverY] = createSignal(0)
const [scrollTop, setScrollTop] = createSignal(0)
const detail = (sessionID: string) => {
const fixture = tabs.detail?.(sessionID)
if (fixture !== undefined) return fixture
const session = data?.session.get(sessionID)
const project = session ? data?.project.get(session.projectID) : undefined
const vcs = session ? data?.location.vcs.info(session.location) : undefined
const location = session ? data?.location.info(session.location) : undefined
return sessionTabDetail(
projectName(project, session?.location.directory) ?? "",
vcs?.branch.current,
vcs?.branch.default,
!!location && location.project.directory !== location.project.canonical,
)
}
// OpenTUI captures the first drag target, which may differ from the tab pressed on a fast move.
const [dragging, setDragging] = createSignal<string>()
const [preview, setPreview] = createSignal<{ sessionID: string; index: number }>()
const [contextMenu, setContextMenu] = createSignal<TabContextMenuState>()
const newTab = () => tabs.newTab?.() ?? false
const activeID = createMemo(() => (newTab() ? undefined : tabs.current()))
const ordered = createMemo(() => {
const pending = preview()
if (!pending) return tabs.tabs()
return moveSessionTab(tabs.tabs(), pending.sessionID, pending.index)
})
const items = ordered
const highlightColor = createMemo(() =>
tint(background(), actionHovered(), actionHovered().a),
)
const highlighted = (sessionID: string | undefined) =>
sessionID !== undefined && (activeID() === sessionID || hovered() === sessionID || dragging() === sessionID)
const addHighlighted = () => newTab() || addHovered()
const belowHighlighted = createMemo(() => {
const tab = items()[Math.floor(scrollTop() / stride())]
return tab ? highlighted(tab.sessionID) : addHighlighted()
})
createEffect(() => {
const active = marquee.active()
if (active && !items().some((tab) => tab.sessionID === active)) marquee.reset()
})
const statuses = createMemo(
() =>
new Map(
items().map((tab) => {
const status = tabs.status(tab.sessionID)
return [
tab.sessionID,
{
...status,
complete: sessionTabComplete(status.unread, status.busy),
runs: status.busy && !status.attention,
glows: Boolean(
status.attention || (tab.sessionID !== activeID() && !status.busy && status.unread !== undefined),
),
},
] as const
}),
),
)
const itemStatus = (tab: SessionTab) => statuses().get(tab.sessionID)!
let rail: { screenX: number; screenY: number } | undefined
let scroll: ScrollBoxRenderable | undefined
const updateScroll = () => setScrollTop(scroll?.scrollTop ?? 0)
onCleanup(() => scroll?.verticalScrollBar.off("change", updateScroll))
let didDrag = false
let addPressed = false
// A captured drag ends with a synthetic up on its drop target; do not turn that into a click.
let suppressClick = false
createEffect(() => {
const pending = preview()
if (!pending || dragging()) return
const index = tabs.tabs().findIndex((tab) => tab.sessionID === pending.sessionID)
if (index === -1 || index === Math.min(pending.index, tabs.tabs().length - 1)) setPreview(undefined)
})
createEffect(() => {
if (!scroll) return
dimensions()
const index = newTab() ? items().length : items().findIndex((tab) => tab.sessionID === activeID())
if (index === -1) return
const top = index * stride()
const height = compact() ? 3 : newTab() ? 1 : 2
// Scroll after layout: newly opened tabs do not contribute to the scroll range yet.
const reveal = () => {
if (!scroll) return
if (top < scroll.scrollTop) return scroll.scrollTo(top)
if (top + height > scroll.scrollTop + scroll.viewport.height) {
scroll.scrollTo(top + height - scroll.viewport.height)
}
}
renderer.once(CliRenderEvents.FRAME, reveal)
renderer.requestRender()
onCleanup(() => renderer.off(CliRenderEvents.FRAME, reveal))
})
const release = () => {
const source = dragging()
if (!source) return
if (didDrag) suppressClick = true
setDragging(undefined)
const pending = preview()
if (pending?.sessionID === source) tabs.move(pending.sessionID, pending.index)
tabs.select(source)
}
const drag = (event: MouseEvent) => {
if (!rail) return
const source = dragging()
if (!source) return
didDrag = true
const target = Math.max(
0,
Math.min(
tabs.tabs().length - 1,
Math.floor(
(event.y - (scroll?.viewport.screenY ?? rail.screenY + 1) - (compact() ? 1 : 0) + (scroll?.scrollTop ?? 0)) /
stride(),
),
),
)
const sourceIndex = items().findIndex((item) => item.sessionID === source)
if (target !== sourceIndex && preview()?.index !== target) setPreview({ sessionID: source, index: target })
}
return (
<box
ref={(element) => (rail = element)}
width={width()}
height="100%"
flexShrink={0}
flexDirection="column"
position="relative"
paddingTop={1}
backgroundColor={background()}
onMouseOut={marquee.leaveHovered}
onMouseUp={(event) => {
if (event.button === RIGHT_MOUSE_BUTTON) return
release()
if (!didDrag) return
didDrag = false
queueMicrotask(() => (suppressClick = false))
}}
onMouseDrag={drag}
onMouseDragEnd={release}
>
<Show when={compact()}>
<SessionTabsRailControls width={width()} tabs={tabs} belowHighlighted={belowHighlighted()} />
</Show>
<scrollbox
ref={(element) => {
scroll = element
scroll.verticalScrollBar.on("change", updateScroll)
updateScroll()
}}
flexGrow={1}
minHeight={0}
backgroundColor={background()}
scrollbarOptions={{ visible: false }}
>
<box flexShrink={0} flexDirection="column" gap={1} paddingY={compact() ? 1 : 0}>
<For each={items()}>
{(tab, index) => {
const selected = () => activeID() === tab.sessionID
const status = createMemo(() => itemStatus(tab))
const [sweepLevel, setSweepLevel] = createSignal(0)
const [closeHovered, setCloseHovered] = createSignal(false)
const session = createMemo(() => data?.session.get(tab.sessionID))
const numberWidth = () => Math.max(2, String(items().length).length)
const prefixWidth = () => numberWidth() + 1
const restingTitleWidth = () => Math.max(1, width() - prefixWidth() - 1)
const hoveredTitleWidth = () => Math.max(1, restingTitleWidth() - 1)
const titleWidth = () => (hovered() === tab.sessionID ? hoveredTitleWidth() : restingTitleWidth())
const title = () => (props.controller ? undefined : session()?.title) ?? tab.title ?? "Untitled session"
const scrolling = () => marquee.active() === tab.sessionID
const visibleTitleParts = createMemo(() =>
scrolling()
? marqueeTextParts(title(), titleWidth(), marquee.offset())
: Locale.graphemes(Locale.takeWidth(title(), titleWidth())).map((value) => ({
value,
separator: false,
})),
)
const visibleTitle = createMemo(() =>
visibleTitleParts()
.map((part) => part.value)
.join(""),
)
const titleFades = createMemo(() => marqueeOverflows(title(), titleWidth()) && titleWidth() > FADE_WIDTH)
const tabDetail = createMemo(() => detail(tab.sessionID))
const visibleDetail = createMemo(() => Locale.takeWidth(tabDetail(), titleWidth()))
const visibleDetailParts = createMemo(() => Locale.graphemes(visibleDetail()))
const detailFades = createMemo(
() => marqueeOverflows(tabDetail(), titleWidth()) && titleWidth() > FADE_WIDTH,
)
const tabBackground = createMemo(() => {
if (selected() && !compact()) return actionSelected()
if ((compact() && selected()) || hovered() === tab.sessionID || dragging() === tab.sessionID)
return actionHovered()
return background()
})
const pulseBackground = createMemo(() => tint(background(), tabBackground(), tabBackground().a))
const runs = () => status().runs
const numberIgnition = createNumberIgnition(runs, () => status().promptPulse, animations)
const numberColor = () => {
const base =
hovered() === tab.sessionID && !selected()
? foreground()
: tint(idleNumber(), tint(theme.text.base, pulseBackground(), 0.25), Number(selected()))
const color = tabFeedbackColor(status(), theme) ?? tint(base, glowHue(), numberGlow.value().level)
const runningColor = runs() ? activeNumber() : color
return sweepLevel() === 0
? tint(runningColor, theme.text.base, numberIgnition.value().level)
: tint(runningColor, theme.text.base, Math.max(numberIgnition.value().level, 0.35 * sweepLevel()))
}
const foreground = () => {
if (hovered() === tab.sessionID) return theme.text.base
return selected() ? theme.text.base : theme.text.muted
}
const complete = () => status().complete
// Latched so a resolving glow fades out in the hue it lit with instead of snapping to the unread color.
let lastGlowHue: RGBA | undefined
const glowHue = () => {
const feedback = tabFeedbackColor(status(), theme)
if (feedback) return (lastGlowHue = feedback)
if (status().unread !== undefined) return (lastGlowHue = unreadColor())
return lastGlowHue ?? unreadColor()
}
const pulseColor = createMemo(() => tint(pulseBackground(), theme.text.base, 0.25))
const flashColor = createMemo(() => tint(pulseBackground(), theme.text.base, 0.7))
const glowLevel = createGlowLevel(() => selected() && Boolean(status().attention), animations)
const glowColor = createMemo(() => tint(pulseBackground(), glowHue(), 0.45 * glowLevel()))
const detailPulseColor = createMemo(() => tint(pulseBackground(), theme.text.base, 0.13))
const detailFlashColor = createMemo(() => tint(pulseBackground(), theme.text.base, 0.42))
const detailGlowColor = createMemo(() => tint(pulseBackground(), glowHue(), 0.25 * glowLevel()))
const detailColor = createMemo(() => tint(theme.text.muted, pulseBackground(), 0.35))
const detailTextColor = (index: number) =>
detailFades()
? fadeTitleColor(detailColor(), pulseBackground(), index, visibleDetailParts().length, 0)
: detailColor()
const glows = () => status().glows
// Text tints ride an eased level so they diffuse away with the background glow instead of snapping.
const titleGlow = createAnimatable(
{ level: 0 },
{ enabled: animations, transition: tween({ duration: 0.4 }) },
)
createEffect(() => titleGlow.animate({ level: glows() ? 1 : 0 }))
const numberGlow = createAnimatable(
{ level: 0 },
{ enabled: animations, transition: tween({ duration: 0.4 }) },
)
createEffect(() =>
numberGlow.animate({
level: status().attention || status().unread === "error" || complete() ? 1 : 0,
}),
)
const previous = createMemo(() => items()[index() - 1])
const previousStatus = createMemo(() => {
const tab = previous()
return tab
? itemStatus(tab)
: { ...EMPTY_SESSION_TAB_STATUS, complete: false, runs: false, glows: false }
})
const previousGlows = () => previousStatus().glows
const previousRuns = () => previousStatus().runs
const previousGlowLevel = createGlowLevel(
() => previous()?.sessionID === activeID() && Boolean(previousStatus().attention),
animations,
)
const indicatorWidth = 10
let lastPreviousGlowHue: RGBA | undefined
const previousGlowHue = () => {
const feedback = tabFeedbackColor(previousStatus(), theme)
if (feedback) return (lastPreviousGlowHue = feedback)
if (previousStatus().unread !== undefined) return (lastPreviousGlowHue = unreadColor())
return lastPreviousGlowHue ?? unreadColor()
}
const separatorUpperColor = createMemo(() =>
tint(background(), previousGlowHue(), 0.1 * previousGlowLevel()),
)
const separatorLowerColor = createMemo(() =>
tint(background(), glowHue(), 0.12 * glowLevel()),
)
const titleColor = (index: number, separator: boolean) => {
const level = titleGlow.value().level
const color =
level === 0
? foreground()
: glowTextColor(foreground(), glowColor(), 1 + numberWidth() + index, width(), level)
const faded = titleFades()
? fadeTitleColor(
color,
pulseBackground(),
index,
visibleTitleParts().length,
scrolling() ? marquee.leading() : 0,
)
: color
return separator ? tint(faded, pulseBackground(), 0.55) : faded
}
return (
<box
height={compact() ? 1 : 2}
width="100%"
position="relative"
flexDirection="column"
backgroundColor={tabBackground()}
onMouseOver={(event) => {
setHoverY(event.y)
marquee.enter(tab.sessionID, title(), compact() ? Infinity : hoveredTitleWidth())
}}
onMouseOut={() => marquee.leave(tab.sessionID)}
onMouseDown={(event) => {
if (event.button === MIDDLE_MOUSE_BUTTON) {
didDrag = false
setDragging(undefined)
tabs.close(tab.sessionID)
event.preventDefault()
event.stopPropagation()
return
}
if (event.button === RIGHT_MOUSE_BUTTON) {
didDrag = false
setDragging(undefined)
if (!rail) return
setContextMenu({
x: event.x,
y: event.y,
sessionID: tab.sessionID,
title: tab.title,
})
event.preventDefault()
event.stopPropagation()
return
}
didDrag = false
marquee.enter(tab.sessionID, title(), compact() ? Infinity : hoveredTitleWidth())
setDragging(tab.sessionID)
}}
>
<Show when={compact()}>
<Show when={highlighted(tab.sessionID)}>
<SessionTabHalfRow
top={-1}
edge="top"
width={width()}
color={pulseBackground()}
background={
highlighted(items()[index() - 1]?.sessionID) ? highlightColor() : background()
}
/>
<SessionTabHalfRow
top={1}
edge="bottom"
width={width()}
color={pulseBackground()}
background={
(
index() === items().length - 1
? addHighlighted()
: highlighted(items()[index() + 1]?.sessionID)
)
? highlightColor()
: background()
}
/>
</Show>
<box height={1} flexDirection="row" justifyContent="center">
<TabIndicator
centered
selected={selected()}
width={width()}
status={status()}
label={sessionTabNumberLabel(index())}
idleLabel={Locale.graphemes(title().trimStart())[0] ?? "U"}
color={
selected()
? theme.text.base
: props.numbers
? numberColor()
: (tabFeedbackColor(status(), theme) ?? (runs() ? activeNumber() : foreground()))
}
unreadColor={tabFeedbackColor(status(), theme) ?? unreadColor()}
backgroundColor={pulseBackground()}
flashColor={theme.text.base}
animations={animations()}
numbers={props.numbers}
spinner={props.spinner}
unreadMarker={props.unreadMarker}
attributes={selected() ? TextAttributes.BOLD : undefined}
/>
</box>
</Show>
<Show when={!compact()}>
<TabPulse
top={-1}
edge="above"
enabled={animations()}
active={runs()}
outerActive={previousRuns()}
promptPulse={status().promptPulse}
outerPromptPulse={previousStatus().promptPulse}
complete={complete() && !status().attention}
outerComplete={previousStatus().complete && !previousStatus().attention}
glow={glows()}
outerGlow={previousGlows()}
color={separatorLowerPulseColor()}
width={indicatorWidth}
outerColor={separatorUpperPulseColor()}
flashColor={tint(background(), theme.text.base, 0.22)}
outerFlashColor={tint(background(), theme.text.base, 0.18)}
flashTail={8}
glowColor={separatorLowerColor()}
outerGlowColor={separatorUpperColor()}
glowTail={8}
outerGlowTail={5}
completionColor={separatorLowerColor()}
outerCompletionColor={separatorUpperColor()}
backgroundColor={background()}
/>
<Show when={index() === items().length - 1}>
<TabPulse
top={2}
edge="below"
enabled={animations()}
active={runs()}
outerActive={false}
promptPulse={status().promptPulse}
outerPromptPulse={0}
complete={complete() && !status().attention}
outerComplete={false}
glow={glows()}
outerGlow={false}
color={tint(background(), theme.text.base, 0.04)}
width={indicatorWidth}
outerColor={tint(background(), theme.text.base, 0.006)}
flashColor={tint(background(), theme.text.base, 0.18)}
flashTail={8}
glowColor={tint(background(), glowHue(), 0.1 * glowLevel())}
outerGlowColor={background()}
glowTail={8}
outerGlowTail={5}
completionColor={tint(background(), glowHue(), 0.1 * glowLevel())}
outerCompletionColor={background()}