-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPond.tsx
More file actions
1817 lines (1636 loc) · 64.3 KB
/
Pond.tsx
File metadata and controls
1817 lines (1636 loc) · 64.3 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 { useRef, useState, useEffect, useLayoutEffect, useCallback, useMemo, createContext, useContext, useSyncExternalStore } from 'react';
import {
DockviewReact,
themeAbyss,
type DockviewTheme,
type DockviewReadyEvent,
type DockviewApi,
type SerializedDockview,
type IDockviewPanelProps,
type IDockviewPanelHeaderProps,
} from 'dockview-react';
import 'dockview-react/dist/styles/dockview.css';
import { createPortal } from 'react-dom';
import { TerminalPane } from './TerminalPane';
import { Baseboard } from './Baseboard';
import { tv } from 'tailwind-variants';
import { BellIcon, BellSlashIcon, SplitHorizontalIcon, SplitVerticalIcon, ArrowsOutIcon, ArrowsInIcon, ArrowLineDownIcon, XIcon } from '@phosphor-icons/react';
import {
type AlarmButtonActionResult,
clearSessionAttention,
clearSessionTodo,
DEFAULT_SESSION_UI_STATE,
disableSessionAlarm,
dismissOrToggleAlarm,
focusTerminal,
getSessionState,
getSessionStateSnapshot,
markSessionAttention,
markSessionTodo,
subscribeToSessionStateChanges,
toggleSessionAlarm,
toggleSessionTodo,
destroyTerminal,
swapTerminals,
type SessionStatus,
isSoftTodo,
isHardTodo,
hasTodo,
TODO_OFF,
} from '../lib/terminal-registry';
import { resolvePanelElement, findPanelInDirection, findRestoreNeighbor, type DetachDirection } from '../lib/spatial-nav';
import { cloneLayout, getLayoutStructureSignature } from '../lib/layout-snapshot';
import { getPlatform } from '../lib/platform';
import { saveSession } from '../lib/session-save';
import type { PersistedDetachedItem } from '../lib/session-types';
import { cfg } from '../cfg';
// --- Theme ---
const mousetermTheme: DockviewTheme = {
...themeAbyss,
name: 'mouseterm',
gap: 6,
dndOverlayMounting: 'absolute',
dndPanelOverlay: 'group',
};
let dialogKeyboardActive = false;
// --- Types ---
export interface DetachedItem {
id: string;
title: string;
neighborId: string | null; // panel that was adjacent before detach
direction: DetachDirection; // where we were relative to that neighbor
remainingPanelIds: string[]; // sorted panel IDs after detach (for layout-changed check)
restoreLayout: SerializedDockview | null;
detachedLayoutSignature: string;
}
function toDetachedItem(item: PersistedDetachedItem): DetachedItem {
return {
...item,
restoreLayout: item.restoreLayout as SerializedDockview | null,
};
}
interface ConfirmKill {
id: string;
char: string;
}
export type PondMode = 'command' | 'passthrough';
export type PondEvent =
| { type: 'modeChange'; mode: PondMode }
| { type: 'zoomChange'; zoomed: boolean }
| { type: 'detachChange'; count: number }
| { type: 'split'; direction: 'horizontal' | 'vertical'; source: 'keyboard' | 'mouse' }
| { type: 'selectionChange'; id: string | null; kind: 'pane' | 'door' };
// --- Variants ---
const tabVariant = tv({
base: 'flex h-full w-full cursor-grab items-center gap-1.5 rounded-t pl-2 pr-[5px] text-[12px] leading-none font-mono tracking-normal select-none active:cursor-grabbing',
variants: {
state: {
selected: 'bg-tab-selected-bg text-tab-selected-fg',
inactive: 'bg-tab-inactive-bg text-tab-inactive-fg',
},
},
});
interface HeaderActionButtonProps {
className: string;
ariaLabel: string;
tooltip?: string;
onMouseDownCapture?: (e: React.MouseEvent<HTMLButtonElement>) => void;
onMouseDown?: (e: React.MouseEvent<HTMLButtonElement>) => void;
onClick: (e: React.MouseEvent<HTMLButtonElement>) => void;
onContextMenu?: (e: React.MouseEvent<HTMLButtonElement>) => void;
children: React.ReactNode;
dataAlarmButtonFor?: string;
}
function HeaderActionButton({
className,
ariaLabel,
tooltip,
onMouseDownCapture,
onMouseDown,
onClick,
onContextMenu,
children,
dataAlarmButtonFor,
}: HeaderActionButtonProps) {
const buttonRef = useRef<HTMLButtonElement>(null);
const [isVisible, setIsVisible] = useState(false);
const [tooltipStyle, setTooltipStyle] = useState<React.CSSProperties | null>(null);
const tooltipText = tooltip ?? ariaLabel;
useEffect(() => {
if (!isVisible || !buttonRef.current) return;
const updatePosition = () => {
const rect = buttonRef.current?.getBoundingClientRect();
if (!rect) return;
setTooltipStyle({
position: 'fixed',
left: rect.left + rect.width / 2,
top: rect.top - 8,
transform: 'translate(-50%, -100%)',
});
};
updatePosition();
window.addEventListener('scroll', updatePosition, true);
window.addEventListener('resize', updatePosition);
return () => {
window.removeEventListener('scroll', updatePosition, true);
window.removeEventListener('resize', updatePosition);
};
}, [isVisible]);
return (
<>
<div className="relative flex shrink-0 items-center">
<button
ref={buttonRef}
type="button"
className={className}
data-alarm-button-for={dataAlarmButtonFor}
onMouseDownCapture={onMouseDownCapture}
onMouseDown={(e) => {
e.preventDefault();
e.stopPropagation();
onMouseDown?.(e);
}}
onClick={(e) => {
e.stopPropagation();
onClick(e);
}}
onContextMenu={onContextMenu ? (e) => {
e.preventDefault();
e.stopPropagation();
onContextMenu(e);
} : undefined}
aria-label={ariaLabel}
onMouseEnter={() => setIsVisible(true)}
onMouseLeave={() => setIsVisible(false)}
onFocus={() => setIsVisible(true)}
onBlur={() => setIsVisible(false)}
>
{children}
</button>
</div>
{isVisible && tooltipStyle && createPortal(
<span
className="pointer-events-none z-[9999] whitespace-nowrap rounded border border-border bg-surface-raised px-2 py-1.5 text-[11px] leading-none text-foreground shadow-sm"
style={tooltipStyle}
>
{tooltipText}
</span>,
document.body,
)}
</>
);
}
// --- Alarm context menu (right-click on bell) ---
function clampOverlayPosition({ left, top, width, height }: {
left: number;
top: number;
width: number;
height: number;
}): React.CSSProperties {
const margin = 12;
const maxLeft = Math.max(margin, window.innerWidth - width - margin);
const maxTop = Math.max(margin, window.innerHeight - height - margin);
return {
position: 'fixed',
left: Math.min(Math.max(left, margin), maxLeft),
top: Math.min(Math.max(top, margin), maxTop),
};
}
/**
* Manages focus trapping, Escape-to-close, and click-outside-to-close for
* portal-based popovers. Scopes keyboard handling to the popover's DOM subtree
* so Tab/Escape don't leak to the rest of the app.
*/
function usePopoverFocusTrap(
ref: React.RefObject<HTMLElement | null>,
onClose: () => void,
restoreFocusSelector?: string,
) {
useEffect(() => {
const el = ref.current;
if (!el) return;
const handleMouseDown = (e: MouseEvent) => {
if (!el.contains(e.target as Node)) onClose();
};
const handleKeyDown = (e: KeyboardEvent) => {
// Only handle keys when focus is inside the popover
if (!el.contains(document.activeElement)) return;
if (e.key === 'Escape') {
e.preventDefault();
e.stopPropagation();
onClose();
return;
}
if (e.key !== 'Tab') return;
const focusables = Array.from(
el.querySelectorAll<HTMLElement>('button:not([disabled]), [tabindex]:not([tabindex="-1"])'),
);
if (focusables.length === 0) return;
const currentIndex = focusables.findIndex((f) => f === document.activeElement);
const nextIndex = currentIndex === -1
? 0
: (currentIndex + (e.shiftKey ? -1 : 1) + focusables.length) % focusables.length;
e.preventDefault();
focusables[nextIndex]?.focus();
};
window.addEventListener('mousedown', handleMouseDown);
window.addEventListener('keydown', handleKeyDown, true);
return () => {
window.removeEventListener('mousedown', handleMouseDown);
window.removeEventListener('keydown', handleKeyDown, true);
if (restoreFocusSelector) {
document.querySelector<HTMLElement>(restoreFocusSelector)?.focus();
}
};
}, [ref, onClose, restoreFocusSelector]);
}
function TodoAlarmDialog({
position,
sessionId,
onClose,
}: {
position: { x: number; y: number };
sessionId: string;
onClose: () => void;
}) {
const sessionStates = useSyncExternalStore(subscribeToSessionStateChanges, getSessionStateSnapshot);
const sessionState = sessionStates.get(sessionId) ?? DEFAULT_SESSION_UI_STATE;
const alarmEnabled = sessionState.status !== 'ALARM_DISABLED';
const dialogRef = useRef<HTMLDivElement>(null);
usePopoverFocusTrap(dialogRef, onClose, `[data-alarm-button-for="${sessionId}"]`);
useEffect(() => {
dialogRef.current?.querySelector<HTMLElement>('button')?.focus();
}, []);
// Keyboard shortcuts within dialog
useEffect(() => {
const el = dialogRef.current;
if (!el) return;
dialogKeyboardActive = true;
const handler = (e: KeyboardEvent) => {
if (!el.contains(document.activeElement)) return;
if (e.key === 'a') {
e.preventDefault();
e.stopImmediatePropagation();
dismissOrToggleAlarm(sessionId, getSessionState(sessionId).status);
}
if (e.key === 't') {
e.preventDefault();
e.stopImmediatePropagation();
toggleSessionTodo(sessionId);
}
};
window.addEventListener('keydown', handler, true);
return () => {
dialogKeyboardActive = false;
window.removeEventListener('keydown', handler, true);
};
}, [sessionId]);
const toggleBtn = (active: boolean) => [
'rounded px-2 py-1 text-[11px] font-medium transition-colors',
active
? 'bg-accent/20 text-accent border border-accent/40'
: 'text-muted border border-border hover:bg-foreground/10 hover:text-foreground',
].join(' ');
return createPortal(
<div
ref={dialogRef}
className="z-[9999] w-[280px] rounded-lg border border-border bg-surface-raised p-3 shadow-lg"
style={clampOverlayPosition({ left: position.x, top: position.y, width: 280, height: 160 })}
role="dialog"
aria-modal="true"
aria-label="TODO and alarm settings"
>
{/* TODO row */}
<div className="flex items-center gap-2 mb-2">
<span className="text-[10px] font-mono text-muted">[t]</span>
<span className="text-[11px] text-foreground font-medium w-10">TODO</span>
<div className="flex gap-1 ml-auto">
<button type="button" className={toggleBtn(isHardTodo(sessionState.todo))}
onClick={() => { if (!isHardTodo(sessionState.todo)) markSessionTodo(sessionId); }}>
hard
</button>
<button type="button" className={toggleBtn(sessionState.todo === TODO_OFF)}
onClick={() => { if (sessionState.todo !== TODO_OFF) clearSessionTodo(sessionId); }}>
off
</button>
</div>
</div>
{/* Alarm row */}
<div className="flex items-center gap-2 mb-3">
<span className="text-[10px] font-mono text-muted">[a]</span>
<span className="text-[11px] text-foreground font-medium w-10">alarm</span>
<div className="flex gap-1 ml-auto">
<button type="button" className={toggleBtn(alarmEnabled)}
onClick={() => { if (!alarmEnabled) toggleSessionAlarm(sessionId); }}>
enabled
</button>
<button type="button" className={toggleBtn(!alarmEnabled)}
onClick={() => { if (alarmEnabled) disableSessionAlarm(sessionId); }}>
disabled
</button>
</div>
</div>
{/* Help text */}
<div className="border-t border-border pt-2 text-[9px] leading-relaxed text-muted">
When an alarming tab is selected,<br />
the alarm is cleared and the tab gets a soft TODO.<br />
Typing drains the soft TODO; stop typing and it refills.
</div>
</div>,
document.body,
);
}
// --- Contexts ---
// We own selection/focus, not dockview. These contexts let panel components read our state.
export const ModeContext = createContext<PondMode>('command');
export const SelectedIdContext = createContext<string | null>(null);
// Map of panel ID → stable panel mount element. We resolve the current
// Dockview group wrapper lazily so panel refs survive layout deserialization.
interface PanelElementsState {
elements: Map<string, HTMLElement>;
version: number;
bumpVersion: () => void;
}
const PanelElementsContext = createContext<PanelElementsState>({
elements: new Map(),
version: 0,
bumpVersion: () => {},
});
export const DoorElementsContext = createContext<PanelElementsState>({
elements: new Map(),
version: 0,
bumpVersion: () => {},
});
export interface PondActions {
onKill: (id: string) => void;
onDetach: (id: string) => void;
onAlarmButton: (id: string, displayedStatus: SessionStatus) => AlarmButtonActionResult;
onToggleTodo: (id: string) => void;
onSplitH: (id: string | null, source?: 'keyboard' | 'mouse') => void;
onSplitV: (id: string | null, source?: 'keyboard' | 'mouse') => void;
onZoom: (id: string) => void;
onClickPanel: (id: string) => void;
onStartRename: (id: string) => void;
onFinishRename: (id: string, value: string) => void;
onCancelRename: () => void;
}
export const PondActionsContext = createContext<PondActions>({
onKill: () => {},
onDetach: () => {},
onAlarmButton: () => 'noop',
onToggleTodo: () => {},
onSplitH: () => {},
onSplitV: () => {},
onZoom: () => {},
onClickPanel: () => {},
onStartRename: () => {},
onFinishRename: () => {},
onCancelRename: () => {},
});
export const RenamingIdContext = createContext<string | null>(null);
export const ZoomedContext = createContext(false);
const ARROW_OPPOSITES: Record<string, string> = {
ArrowLeft: 'ArrowRight', ArrowRight: 'ArrowLeft',
ArrowUp: 'ArrowDown', ArrowDown: 'ArrowUp',
};
/** Compare two sorted ID arrays by value. */
function idsMatch(a: string[], b: string[]): boolean {
if (import.meta.env.DEV) {
const isSorted = (arr: string[]) => arr.every((v, i) => i === 0 || v >= arr[i - 1]);
console.assert(isSorted(a) && isSorted(b), 'idsMatch: inputs must be sorted');
}
return a.length === b.length && a.every((id, i) => id === b[i]);
}
/** Random A-Z excluding X (prevents accidental double-tap on kill shortcut) */
const KILL_CONFIRM_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWYZ'; // no X
function randomKillChar(): string {
return KILL_CONFIRM_CHARS[Math.floor(Math.random() * KILL_CONFIRM_CHARS.length)];
}
// --- Panel content component ---
function TerminalPanel({ api }: IDockviewPanelProps) {
const mode = useContext(ModeContext);
const selectedId = useContext(SelectedIdContext);
const actions = useContext(PondActionsContext);
const { elements: panelElements, bumpVersion } = useContext(PanelElementsContext);
const isFocused = mode === 'passthrough' && selectedId === api.id;
const elRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!elRef.current) return;
panelElements.set(api.id, elRef.current);
bumpVersion();
return () => {
panelElements.delete(api.id);
bumpVersion();
};
}, [api.id, panelElements, bumpVersion]);
return (
<div ref={elRef} className="h-full w-full" onMouseDown={() => actions.onClickPanel(api.id)}>
<TerminalPane id={api.id} isFocused={isFocused} />
</div>
);
}
// --- Custom tab component ---
type HeaderTier = 'full' | 'compact' | 'minimal';
export function TerminalPaneHeader({ api }: IDockviewPanelHeaderProps) {
const mode = useContext(ModeContext);
const selectedId = useContext(SelectedIdContext);
const renamingId = useContext(RenamingIdContext);
const zoomed = useContext(ZoomedContext);
const sessionStates = useSyncExternalStore(subscribeToSessionStateChanges, getSessionStateSnapshot);
const actions = useContext(PondActionsContext);
const sessionState = sessionStates.get(api.id) ?? DEFAULT_SESSION_UI_STATE;
const isSelected = selectedId === api.id;
const showSelectedHeader = mode === 'passthrough' && isSelected;
const isRenaming = renamingId === api.id;
const tabRef = useRef<HTMLDivElement>(null);
const suppressAlarmClickRef = useRef(false);
const [tier, setTier] = useState<HeaderTier>('full');
const [dialogPosition, setDialogPosition] = useState<{ x: number; y: number } | null>(null);
const showTodoPill = hasTodo(sessionState.todo) && tier !== 'minimal';
const alarmButtonAriaLabel = sessionState.status === 'ALARM_RINGING'
? 'Alarm ringing'
: sessionState.status === 'ALARM_DISABLED'
? 'Enable alarm'
: 'Disable alarm';
const alarmButtonTooltip = sessionState.status === 'ALARM_RINGING'
? 'Alarm ringing - Click to dismiss and show options'
: sessionState.status === 'ALARM_DISABLED'
? 'Enable alarm [a] - Right-click for options'
: 'Disable alarm [a] - Right-click for options';
const openDialogFromButton = useCallback((button: HTMLButtonElement) => {
const rect = button.getBoundingClientRect();
setDialogPosition({
x: rect.left + rect.width / 2 - 140,
y: rect.bottom + 6,
});
}, []);
const triggerAlarmButtonAction = useCallback((displayedStatus: SessionStatus, button: HTMLButtonElement) => {
const result = actions.onAlarmButton(api.id, displayedStatus);
if (result === 'dismissed') {
openDialogFromButton(button);
}
}, [actions, api.id, openDialogFromButton]);
useEffect(() => {
const el = tabRef.current;
if (!el) return;
const ro = new ResizeObserver(([entry]) => {
const w = entry.contentRect.width;
if (w > 280) setTier('full');
else if (w > 160) setTier('compact');
else setTier('minimal');
});
ro.observe(el);
return () => ro.disconnect();
}, []);
return (
<div
ref={tabRef}
className={tabVariant({ state: showSelectedHeader ? 'selected' : 'inactive' })}
onMouseDown={() => actions.onClickPanel(api.id)}
>
<div className="flex flex-1 min-w-0 items-center gap-2">
{isRenaming ? (
<input
className="bg-transparent outline-none border-none text-inherit font-medium font-mono tracking-normal w-full min-w-0 p-0 m-0"
defaultValue={api.title}
autoFocus
ref={(el) => el?.select()}
onKeyDown={(e) => {
if (e.key === 'Enter') {
actions.onFinishRename(api.id, (e.target as HTMLInputElement).value);
}
if (e.key === 'Escape') actions.onCancelRename();
e.stopPropagation();
}}
onBlur={(e) => actions.onFinishRename(api.id, e.target.value)}
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => e.stopPropagation()}
/>
) : (
<span
className="min-w-0 truncate cursor-text font-medium text-inherit decoration-current/50 underline-offset-2 hover:underline"
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => { e.stopPropagation(); actions.onStartRename(api.id); }}
>{api.title}</span>
)}
<HeaderActionButton
className={[
'flex h-5 min-w-5 items-center justify-center rounded transition-colors shrink-0',
sessionState.status === 'ALARM_RINGING'
? 'bg-warning/15 text-warning hover:bg-warning/20 motion-safe:animate-pulse motion-reduce:animate-none'
: 'text-muted hover:bg-foreground/10 hover:text-foreground',
].join(' ')}
onMouseDownCapture={(e) => {
if (e.button !== 0) return;
suppressAlarmClickRef.current = true;
e.preventDefault();
e.stopPropagation();
e.nativeEvent.stopImmediatePropagation?.();
triggerAlarmButtonAction(sessionState.status, e.currentTarget);
}}
onClick={(e) => {
if (suppressAlarmClickRef.current) {
suppressAlarmClickRef.current = false;
return;
}
triggerAlarmButtonAction(sessionState.status, e.currentTarget);
}}
onContextMenu={(e) => { e.preventDefault(); setDialogPosition({ x: e.clientX, y: e.clientY }); }}
ariaLabel={alarmButtonAriaLabel}
tooltip={alarmButtonTooltip}
dataAlarmButtonFor={api.id}
>
<span className="relative flex items-center justify-center">
{sessionState.status === 'ALARM_DISABLED' ? (
<BellSlashIcon size={14} />
) : (
<BellIcon size={14} weight="fill" />
)}
{(sessionState.status === 'MIGHT_BE_BUSY' || sessionState.status === 'BUSY' || sessionState.status === 'MIGHT_NEED_ATTENTION') && (
<span className={[
'absolute -top-0.5 -right-0.5 h-[6px] w-[6px] rounded-full border border-surface-alt',
sessionState.status === 'MIGHT_BE_BUSY' && 'bg-foreground/40',
sessionState.status === 'BUSY' && 'bg-accent motion-safe:animate-alarm-dot motion-reduce:animate-none',
sessionState.status === 'MIGHT_NEED_ATTENTION' && 'bg-warning/60 motion-safe:animate-alarm-dot motion-reduce:animate-none',
].filter(Boolean).join(' ')} />
)}
</span>
</HeaderActionButton>
{showTodoPill && (
<button
type="button"
data-session-todo-for={api.id}
className={[
'shrink-0 rounded px-1.5 py-px text-[9px] font-semibold tracking-[0.08em] text-muted transition-colors hover:bg-foreground/10',
isSoftTodo(sessionState.todo) ? 'border border-dashed border-muted' : 'border border-muted',
].join(' ')}
style={isSoftTodo(sessionState.todo) ? {
opacity: 0.3 + 0.7 * sessionState.todo,
transform: `scale(${0.7 + 0.3 * sessionState.todo})`,
transition: 'opacity 0.15s ease, transform 0.15s ease',
} : undefined}
aria-label="TODO settings"
onMouseDown={(e) => e.stopPropagation()}
onClick={(e) => {
e.stopPropagation();
const rect = e.currentTarget.getBoundingClientRect();
setDialogPosition({ x: rect.left + rect.width / 2 - 140, y: rect.bottom + 6 });
}}
>
TODO
</button>
)}
</div>
{!isRenaming && (
<>
{/* Split/Zoom controls — hidden at compact and minimal tiers */}
{tier === 'full' && (
<div className="ml-1 flex shrink-0 items-center gap-0.5">
<HeaderActionButton
className="flex h-5 min-w-5 items-center justify-center rounded text-muted transition-colors hover:bg-foreground/10 hover:text-foreground"
onClick={(e) => { e.stopPropagation(); actions.onSplitH(api.id); }}
ariaLabel="Split horizontal"
tooltip='Split horizontal ["]'
><SplitHorizontalIcon size={14} /></HeaderActionButton>
<HeaderActionButton
className="flex h-5 min-w-5 items-center justify-center rounded text-muted transition-colors hover:bg-foreground/10 hover:text-foreground"
onClick={(e) => { e.stopPropagation(); actions.onSplitV(api.id); }}
ariaLabel="Split vertical"
tooltip="Split vertical [%]"
><SplitVerticalIcon size={14} /></HeaderActionButton>
<HeaderActionButton
className="flex h-5 min-w-5 items-center justify-center rounded text-muted transition-colors hover:bg-foreground/10 hover:text-foreground"
onClick={(e) => { e.stopPropagation(); actions.onZoom(api.id); }}
ariaLabel={zoomed ? 'Unzoom' : 'Zoom'}
tooltip={zoomed ? 'Unzoom [z]' : 'Zoom [z]'}
>{zoomed ? <ArrowsInIcon size={14} /> : <ArrowsOutIcon size={14} />}</HeaderActionButton>
</div>
)}
{/* Detach / Kill controls — always visible */}
<div className="ml-1 flex shrink-0 items-center gap-0.5">
<HeaderActionButton
className="flex h-5 min-w-5 items-center justify-center rounded text-muted transition-colors hover:bg-foreground/10 hover:text-foreground"
onClick={(e) => { e.stopPropagation(); actions.onDetach(api.id); }}
ariaLabel="Detach"
tooltip="Detach [d]"
><ArrowLineDownIcon size={14} /></HeaderActionButton>
<HeaderActionButton
className="flex h-5 min-w-5 items-center justify-center rounded text-muted transition-colors hover:bg-error/10 hover:text-error"
onClick={(e) => { e.stopPropagation(); actions.onKill(api.id); }}
ariaLabel="Kill"
tooltip="Kill [x]"
><XIcon size={14} /></HeaderActionButton>
</div>
</>
)}
{dialogPosition && (
<TodoAlarmDialog
position={dialogPosition}
sessionId={api.id}
onClose={() => setDialogPosition(null)}
/>
)}
</div>
);
}
const components = { terminal: TerminalPanel };
const tabComponents = { terminal: TerminalPaneHeader };
// --- Selection overlay ---
function useWindowFocused(): boolean {
const [focused, setFocused] = useState(() => document.hasFocus());
useEffect(() => {
const onFocus = () => setFocused(true);
const onBlur = () => setFocused(false);
window.addEventListener('focus', onFocus);
window.addEventListener('blur', onBlur);
return () => {
window.removeEventListener('focus', onFocus);
window.removeEventListener('blur', onBlur);
};
}, []);
return focused;
}
function readSelectionColor() {
return getComputedStyle(document.documentElement).getPropertyValue('--mt-selection-terminal').trim();
}
function useSelectionColor() {
const [color, setColor] = useState(readSelectionColor);
useEffect(() => {
const mo = new MutationObserver(() => setColor(readSelectionColor()));
mo.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style'] });
return () => mo.disconnect();
}, []);
return color;
}
/** Build a closed SVG path for a rounded rectangle.
* Starts at the midpoint of the top edge so the seam falls in a straight segment. */
export function roundedRectPath(
w: number, h: number,
tl: number, tr: number, br: number, bl: number,
inset: number,
): string {
const i = inset;
const rtl = Math.max(0, tl - i);
const rtr = Math.max(0, tr - i);
const rbr = Math.max(0, br - i);
const rbl = Math.max(0, bl - i);
const mx = w / 2;
return (
`M ${mx},${i} ` +
`L ${w - i - rtr},${i} ` +
`Q ${w - i},${i} ${w - i},${i + rtr} ` +
`L ${w - i},${h - i - rbr} ` +
`Q ${w - i},${h - i} ${w - i - rbr},${h - i} ` +
`L ${i + rbl},${h - i} ` +
`Q ${i},${h - i} ${i},${h - i - rbl} ` +
`L ${i},${i + rtl} ` +
`Q ${i},${i} ${i + rtl},${i} ` +
`Z`
);
}
/** SVG marching-ants border that adapts its dash pattern to tile evenly. */
export function MarchingAntsRect({ width, height, isDoor, color, paused }: {
width: number;
height: number;
isDoor: boolean;
color: string;
paused?: boolean;
}) {
const svgRef = useRef<SVGPathElement>(null);
const [dashStyle, setDashStyle] = useState<{ dasharray: string; offset: number } | null>(null);
const ma = cfg.marchingAnts;
// Door: rounded top, flat bottom. Pane: all corners rounded.
const r = 8; // ~0.5rem
const rDoor = 6; // ~0.375rem
const tl = isDoor ? rDoor : r;
const tr = isDoor ? rDoor : r;
const br = isDoor ? 0 : r;
const bl = isDoor ? 0 : r;
const inset = ma.strokeWidth / 2;
const d = roundedRectPath(width, height, tl, tr, br, bl, inset);
useLayoutEffect(() => {
const path = svgRef.current;
if (!path) return;
const len = path.getTotalLength();
const count = Math.max(1, Math.round(len / ma.segLen));
const adjusted = len / count;
const dash = adjusted * ma.dashFraction;
const gap = adjusted * (1 - ma.dashFraction);
setDashStyle({ dasharray: `${dash} ${gap}`, offset: adjusted });
}, [width, height, isDoor]);
return (
<svg
xmlns="http://www.w3.org/2000/svg"
style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', overflow: 'visible' }}
>
<path
ref={svgRef}
d={d}
fill="none"
stroke={color}
strokeWidth={ma.strokeWidth}
strokeDasharray={dashStyle?.dasharray}
style={dashStyle ? {
animation: `marching-ants ${ma.cycleDuration}s linear infinite`,
animationPlayState: (ma.paused || paused) ? 'paused' : 'running',
['--march-offset' as string]: `-${dashStyle.offset}px`,
} : undefined}
/>
</svg>
);
}
function SelectionOverlay({ apiRef, selectedId, selectedType, mode }: {
apiRef: React.RefObject<DockviewApi | null>;
selectedId: string | null;
selectedType: 'pane' | 'door';
mode: PondMode;
}) {
const { elements: panelElements, version: panelVersion } = useContext(PanelElementsContext);
const { elements: doorElements, version: doorVersion } = useContext(DoorElementsContext);
const selectionColor = useSelectionColor();
const windowFocused = useWindowFocused();
const [rect, setRect] = useState<{ top: number; left: number; width: number; height: number } | null>(null);
const isDoor = selectedType === 'door';
useEffect(() => {
const api = apiRef.current;
if (!api || !selectedId) { setRect(null); return; }
const INFLATE = 3; // half the 6px gap
const update = () => {
const targetEl = selectedType === 'door'
? doorElements.get(selectedId)
: resolvePanelElement(panelElements.get(selectedId));
// Keep stale rect while the element is temporarily missing (e.g. during
// detach → door transition) so the overlay stays mounted and can animate.
if (!targetEl) return;
const targetRect = targetEl.getBoundingClientRect();
const inflate = selectedType === 'door' ? 2 : INFLATE;
setRect({
top: targetRect.top - inflate,
left: targetRect.left - inflate,
width: targetRect.width + inflate * 2,
height: targetRect.height + inflate * 2,
});
};
update();
const ro = new ResizeObserver(update);
const panelEl = resolvePanelElement(panelElements.get(selectedId));
if (panelEl) ro.observe(panelEl);
const doorEl = doorElements.get(selectedId);
if (doorEl) ro.observe(doorEl);
const d = api.onDidLayoutChange(update);
return () => { ro.disconnect(); d.dispose(); };
}, [apiRef, selectedId, selectedType, panelVersion, doorVersion]);
if (!rect || !selectedId) return null;
const style: React.CSSProperties = {
position: 'fixed',
pointerEvents: 'none',
top: rect.top,
left: rect.left,
width: rect.width,
height: rect.height,
zIndex: 50,
transition: 'top 150ms, left 150ms, width 150ms, height 150ms, filter 200ms',
filter: windowFocused ? undefined : 'saturate(0.3)',
};
if (mode === 'passthrough') {
style.borderRadius = isDoor ? '0.375rem 0.375rem 0 0' : '0.5rem';
style.border = `1px solid ${selectionColor}`;
return <div style={style} />;
}
return (
<div style={style}>
<MarchingAntsRect
width={rect.width}
height={rect.height}
isDoor={isDoor}
color={selectionColor}
paused={!windowFocused}
/>
</div>
);
}
// --- Kill confirmation overlay ---
function KillConfirmCard({ char }: { char: string }) {
return (
<div className="bg-surface-raised border border-error/30 px-6 py-4 rounded-lg text-center shadow-lg">
<h2 className="text-sm font-bold mb-2 text-foreground">Kill Session?</h2>
<div className="bg-black py-2 px-6 rounded border border-border inline-block mb-2">
<span className="text-2xl font-black text-error">{char}</span>
</div>
<div className="text-[9px] text-muted uppercase tracking-widest leading-relaxed">
<div>[{char}] to confirm</div>
<div>[ESC] to cancel</div>
</div>
</div>
);
}
function KillConfirmOverlay({ confirmKill, panelElements }: {
confirmKill: ConfirmKill;
panelElements: Map<string, HTMLElement>;
}) {
const [rect, setRect] = useState<{ top: number; left: number; width: number; height: number } | null>(null);
useEffect(() => {
const panelEl = resolvePanelElement(panelElements.get(confirmKill.id));
if (!panelEl) { setRect(null); return; }
const update = () => {
const r = panelEl.getBoundingClientRect();
setRect({ top: r.top, left: r.left, width: r.width, height: r.height });
};
update();
const ro = new ResizeObserver(update);
ro.observe(panelEl);
window.addEventListener('resize', update);
return () => { ro.disconnect(); window.removeEventListener('resize', update); };
}, [confirmKill.id, panelElements]);
if (rect) {
return (
<div
style={{ position: 'fixed', top: rect.top, left: rect.left, width: rect.width, height: rect.height, zIndex: 100 }}
className="flex items-center justify-center bg-surface/50 rounded"
>
<KillConfirmCard char={confirmKill.char} />
</div>
);
}
// Fallback: centered in viewport
return (
<div className="fixed inset-0 bg-surface/50 z-[100] flex items-center justify-center">
<KillConfirmCard char={confirmKill.char} />
</div>
);
}
// --- Main component ---
export function Pond({
initialPaneIds,
restoredLayout,
initialDetached,
onApiReady,
onEvent,
}: {
initialPaneIds?: string[];
restoredLayout?: unknown;
initialDetached?: PersistedDetachedItem[];
onApiReady?: (api: DockviewApi) => void;
onEvent?: (event: PondEvent) => void;
} = {}) {
const apiRef = useRef<DockviewApi | null>(null);
const [dockviewApi, setDockviewApi] = useState<DockviewApi | null>(null);
const dockviewContainerRef = useRef<HTMLDivElement | null>(null);
// Pane ID generation (instance-scoped, not module-level)
const paneCounterRef = useRef(0);
const generatePaneId = useCallback(() => {
return `pane-${(++paneCounterRef.current).toString(36)}-${Math.random().toString(36).substring(2, 7)}`;
}, []);
// Consumed once in handleReady to restore existing sessions
const initialPaneIdsRef = useRef(initialPaneIds);
const restoredLayoutRef = useRef(restoredLayout);
const initialDetachedRef = useRef((initialDetached ?? []).map(toDetachedItem));
// Mutable maps shared via context — consumers must call bumpVersion() after
// any mutation so that dependent effects/components re-run.
const panelElementsRef = useRef(new Map<string, HTMLElement>());
const panelElements = panelElementsRef.current;
const [panelElementsVersion, setPanelElementsVersion] = useState(0);
const doorElementsRef = useRef(new Map<string, HTMLElement>());
const doorElements = doorElementsRef.current;
const [doorElementsVersion, setDoorElementsVersion] = useState(0);
const bumpPanelElementsVersion = useCallback(() => {
setPanelElementsVersion((v) => v + 1);
}, []);
const bumpDoorElementsVersion = useCallback(() => {
setDoorElementsVersion((v) => v + 1);
}, []);
// We own these — dockview is just for spatial layout and DnD