Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

terminalFocus.ts

191 lines7.5 KB

1import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2import type { ScopedThreadRef } from "@t3tools/contracts";
3​
4import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore";
5import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
6​
7export type TerminalFocusOwner = "drawer" | "right-panel";
8​
9export function getTerminalFocusOwner(): TerminalFocusOwner | null {
10 const activeElement = document.activeElement;
11 if (!(activeElement instanceof HTMLElement)) return null;
12 if (!activeElement.isConnected) return null;
13 const owner = activeElement.closest<HTMLElement>("[data-terminal-owner]")?.dataset.terminalOwner;
14 if (owner === "drawer" || owner === "right-panel") return owner;
15 return null;
17​
18export function isTerminalFocused(): boolean {
19 return getTerminalFocusOwner() !== null;
21​
22export function subscribeToTerminalFocusChanges(listener: () => void): () => void {
23 window.addEventListener("focusin", listener, true);
24 window.addEventListener("focusout", listener, true);
25 return () => {
26 window.removeEventListener("focusin", listener, true);
27 window.removeEventListener("focusout", listener, true);
28 };
30​
31interface TerminalFocusTarget {
32 readonly threadRef: ScopedThreadRef;
33 readonly terminalId: string;
34 /** Returns false when the target cannot take focus yet (hidden, or no operate grant). */
35 readonly focus: () => boolean;
37​
38const focusTargets = new Set<TerminalFocusTarget>();
39// One request at a time: the newest terminal the user asked for wins, so an
40// older request never fires later and steals focus.
41let pendingFocus: { readonly threadKey: string; readonly terminalId: string } | null = null;
42// The thread ChatView currently shows, and the thread a navigating handler
43// asked to focus a terminal in. The mark outlives `pendingFocus`: the new
44// thread's viewports mount and consume the handler's request in the commit's
45// layout phase, before ChatView's thread-enter effect runs.
46let enteredThreadKey: string | null = null;
47let navigationRequestThreadKey: string | null = null;
48​
49function isPending(threadKey: string, terminalId: string): boolean {
50 return pendingFocus?.threadKey === threadKey && pendingFocus.terminalId === terminalId;
52​
53function focusMountedTarget(threadKey: string, terminalId: string): boolean {
54 for (const target of focusTargets) {
55 if (
56 target.terminalId === terminalId &&
57 scopedThreadKey(target.threadRef) === threadKey &&
58 target.focus()
59 ) {
60 return true;
61 }
62 }
63 return false;
65​
66/**
67 * Focuses a thread's terminal when its viewport can take focus, or once it can.
68 * Opening, creating or switching to a terminal usually mounts or shows its
69 * viewport after the handler returns, so the request waits for the viewport.
70 */
71export function focusTerminal(threadRef: ScopedThreadRef, terminalId: string): void {
72 const threadKey = scopedThreadKey(threadRef);
73 pendingFocus = focusMountedTarget(threadKey, terminalId) ? null : { threadKey, terminalId };
75​
76/**
77 * Focuses the drawer terminal the store now marks active, after an open, close
78 * or switch. A thread whose drawer ended up closed drops its waiting request.
79 */
80export function focusActiveDrawerTerminal(threadRef: ScopedThreadRef): void {
81 const { terminalOpen, activeTerminalId } = selectThreadTerminalUiState(
82 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
83 threadRef,
84 );
85 if (terminalOpen && activeTerminalId) focusTerminal(threadRef, activeTerminalId);
86 else cancelTerminalFocus(threadRef);
88​
89/** Focuses the active terminal of the right panel when it shows a terminal surface. */
90export function focusActivePanelTerminal(threadRef: ScopedThreadRef): void {
91 const { isOpen, activeSurfaceId, surfaces } = selectThreadRightPanelState(
92 useRightPanelStore.getState().byThreadKey,
93 threadRef,
94 );
95 const surface = isOpen ? surfaces.find((candidate) => candidate.id === activeSurfaceId) : null;
96 if (surface?.kind === "terminal") focusTerminal(threadRef, surface.activeTerminalId);
98​
99/**
100 * After a right panel surface closes, focuses the terminal surface the panel
101 * fell back to. A terminal surface that was already active keeps its focus as is.
102 */
103export function focusPanelTerminalAfterClose(
104 threadRef: ScopedThreadRef,
105 previousActiveSurfaceId: string | null,
106): void {
107 const { activeSurfaceId } = selectThreadRightPanelState(
108 useRightPanelStore.getState().byThreadKey,
109 threadRef,
110 );
111 if (activeSurfaceId !== previousActiveSurfaceId) focusActivePanelTerminal(threadRef);
113​
114/**
115 * Focuses a terminal from a handler that may also navigate to its thread (a
116 * sidebar terminal reveal). When it does, that thread's entry keeps this request
117 * instead of focusing the drawer.
118 */
119export function focusTerminalOnNavigation(threadRef: ScopedThreadRef, terminalId: string): void {
120 const threadKey = scopedThreadKey(threadRef);
121 navigationRequestThreadKey = threadKey === enteredThreadKey ? null : threadKey;
122 focusTerminal(threadRef, terminalId);
124​
125/**
126 * Entering a thread with its drawer open focuses the drawer terminal, unless a
127 * navigating handler already asked for a terminal there. Returns the leave
128 * cleanup for ChatView's effect.
129 */
130export function focusTerminalOnThreadEnter(threadRef: ScopedThreadRef): () => void {
131 const threadKey = scopedThreadKey(threadRef);
132 const requestedByHandler = navigationRequestThreadKey === threadKey;
133 navigationRequestThreadKey = null;
134 enteredThreadKey = threadKey;
135 if (!requestedByHandler) {
136 const { terminalOpen, activeTerminalId } = selectThreadTerminalUiState(
137 useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
138 threadRef,
139 );
140 if (terminalOpen && activeTerminalId) focusTerminal(threadRef, activeTerminalId);
141 }
142 return () => {
143 // A handler navigating elsewhere marks its target before this cleanup runs.
144 if (enteredThreadKey === threadKey) enteredThreadKey = null;
145 };
147​
148function cancelTerminalFocus(threadRef: ScopedThreadRef): void {
149 if (pendingFocus?.threadKey === scopedThreadKey(threadRef)) pendingFocus = null;
151​
152/**
153 * Retries a waiting request once a mounted viewport can take it: when it is
154 * shown (a viewport kept mounted while hidden has `display: none`) or when the
155 * operate grant arrives. Neither ever invents a request.
156 */
157export function consumePendingTerminalFocus(threadRef: ScopedThreadRef, terminalId: string): void {
158 const threadKey = scopedThreadKey(threadRef);
159 if (isPending(threadKey, terminalId) && focusMountedTarget(threadKey, terminalId)) {
160 pendingFocus = null;
161 }
163​
164export function registerTerminalFocusTarget(target: TerminalFocusTarget): () => void {
165 focusTargets.add(target);
166 if (isPending(scopedThreadKey(target.threadRef), target.terminalId) && target.focus()) {
167 pendingFocus = null;
168 }
169 return () => {
170 focusTargets.delete(target);
171 };
173​
174/**
175 * A viewport's `focus` for its target. Focus lands on the mount until the
176 * surface exists, and the surface takes it over from there.
177 */
178export function focusTerminalViewport(input: {
179 readonly mount: HTMLElement;
180 readonly surface: { focus(): void } | null;
181 readonly canOperate: boolean;
182 readonly visible: boolean;
183}): boolean {
184 // A hidden drawer is clipped, not display:none: the mount would take focus
185 // while the surface refuses it, and the request would be spent on a wrapper
186 // that ignores typing.
187 if (!input.canOperate || !input.visible) return false;
188 input.mount.focus({ preventScroll: true });
189 input.surface?.focus();
190 return input.mount.contains(document.activeElement);