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

terminalFocus.ts

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