diff --git a/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts b/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts index 3525e1782809..7b0a72b08386 100644 --- a/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts +++ b/apps/mobile/src/features/keyboard/hardwareKeyboardCommands.ts @@ -23,30 +23,35 @@ const handlers = new Map>(); const registrationListeners = new Set<() => void>(); let registrationVersion = 0; -export function useHardwareKeyboardCommand( +export function registerHardwareKeyboardCommand( command: HardwareKeyboardCommand | ReadonlyArray, handler: CommandHandler, -): void { - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the handler in the module-level hardware keyboard command registry - useEffect(() => { - const commands = typeof command === "string" ? [command] : command; +): () => void { + const commands = typeof command === "string" ? [command] : command; + for (const command of commands) { + const commandHandlers = handlers.get(command) ?? new Set(); + commandHandlers.add(handler); + handlers.set(command, commandHandlers); + } + registrationVersion += 1; + registrationListeners.forEach((listener) => listener()); + return () => { for (const command of commands) { - const commandHandlers = handlers.get(command) ?? new Set(); - commandHandlers.add(handler); - handlers.set(command, commandHandlers); + const commandHandlers = handlers.get(command); + commandHandlers?.delete(handler); + if (commandHandlers?.size === 0) handlers.delete(command); } registrationVersion += 1; registrationListeners.forEach((listener) => listener()); - return () => { - for (const command of commands) { - const commandHandlers = handlers.get(command); - commandHandlers?.delete(handler); - if (commandHandlers?.size === 0) handlers.delete(command); - } - registrationVersion += 1; - registrationListeners.forEach((listener) => listener()); - }; - }, [command, handler]); + }; +} + +export function useHardwareKeyboardCommand( + command: HardwareKeyboardCommand | ReadonlyArray, + handler: CommandHandler, +): void { + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the handler in the module-level hardware keyboard command registry + useEffect(() => registerHardwareKeyboardCommand(command, handler), [command, handler]); } export function getRegisteredHardwareKeyboardCommands(): ReadonlySet { diff --git a/apps/mobile/src/features/keyboard/threadKeyboardShortcuts.test.tsx b/apps/mobile/src/features/keyboard/threadKeyboardShortcuts.test.tsx new file mode 100644 index 000000000000..1f84b7bed5d8 --- /dev/null +++ b/apps/mobile/src/features/keyboard/threadKeyboardShortcuts.test.tsx @@ -0,0 +1,56 @@ +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import type { ThreadListV2ListItem } from "../threads/threadListV2"; +import { + dispatchHardwareKeyboardCommand, + getHardwareKeyboardCommandRegistrationVersion, +} from "./hardwareKeyboardCommands"; +import { useThreadJumpShortcuts } from "./threadKeyboardShortcuts"; + +function threadItem(id: string): ThreadListV2ListItem { + const thread = { environmentId: "environment-1", id } as unknown as EnvironmentThreadShell; + return { + type: "v2-thread", + key: id, + item: { thread, variant: "card", snoozed: false, pinned: false, isLast: false, wokeAt: null }, + snoozeWakeLabelText: undefined, + timeLabel: "", + snoozePresetMinute: undefined, + showTrailingDivider: false, + hasQueuedMessages: false, + canMoveUp: false, + canMoveDown: false, + }; +} + +function Probe(props: { + readonly items: ReadonlyArray; + readonly onSelectThread: (thread: EnvironmentThreadShell) => void; +}) { + useThreadJumpShortcuts(props.items, props.onSelectThread); + return null; +} + +describe("useThreadJumpShortcuts", () => { + it("registers once and jumps within the latest list", () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const root = createRoot(document.createElement("div")); + act(() => root.render()); + const registrationVersion = getHardwareKeyboardCommandRegistrationVersion(); + + const onSelectThread = vi.fn(); + for (const id of ["second", "third"]) { + act(() => root.render()); + } + + expect(getHardwareKeyboardCommandRegistrationVersion()).toBe(registrationVersion); + expect(dispatchHardwareKeyboardCommand("thread.jump.1")).toBe(true); + expect(onSelectThread).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ id: "third" }), + ); + act(() => root.unmount()); + }); +}); diff --git a/apps/mobile/src/features/keyboard/threadKeyboardShortcuts.ts b/apps/mobile/src/features/keyboard/threadKeyboardShortcuts.ts index 8d6f13170442..69b327cb5352 100644 --- a/apps/mobile/src/features/keyboard/threadKeyboardShortcuts.ts +++ b/apps/mobile/src/features/keyboard/threadKeyboardShortcuts.ts @@ -1,9 +1,10 @@ import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import { THREAD_JUMP_KEYBINDING_COMMANDS } from "@t3tools/contracts"; +import { useEffect, useEffectEvent } from "react"; import type { ThreadListV2ListItem } from "../threads/threadListV2"; import { - useHardwareKeyboardCommand, + registerHardwareKeyboardCommand, type HardwareKeyboardCommand, } from "./hardwareKeyboardCommands"; @@ -30,10 +31,17 @@ export function useThreadJumpShortcuts( items: ReadonlyArray, onSelectThread: (thread: EnvironmentThreadShell) => void, ) { - const jumpToThread = (command: HardwareKeyboardCommand) => { + const jumpToThread = useEffectEvent((command: HardwareKeyboardCommand) => { const thread = threadJumpTarget(items, command); if (thread !== null) onSelectThread(thread); - return true; - }; - useHardwareKeyboardCommand(THREAD_JUMP_KEYBINDING_COMMANDS, jumpToThread); + }); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the jump handlers in the module-level hardware keyboard command registry + useEffect( + () => + registerHardwareKeyboardCommand(THREAD_JUMP_KEYBINDING_COMMANDS, (command) => { + jumpToThread(command); + return true; + }), + [], + ); } diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index 96f0a8177111..30e48395cd35 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -18,7 +18,7 @@ import { AnimatedLegendList } from "@legendapp/list/reanimated"; import { THREAD_SIDEBAR_ROW_LAYOUT } from "./threadListAnimations"; import type { MenuAction } from "@react-native-menu/menu"; import { useAtomValue } from "@effect/atom-react"; -import { useMemo, useRef, useState } from "react"; +import { useRef, useState } from "react"; import type { LayoutChangeEvent, TextInputInstance } from "react-native"; import { Platform, StyleSheet, TextInput, View } from "react-native"; import { GestureDetector, useNativeGesture } from "react-native-gesture-handler"; @@ -144,6 +144,58 @@ function NativeSidebarContainer(props: ThreadNavigationSidebarProps) { ); } +function useSidebarListFilters() { + const projects = useProjects(); + const { savedConnectionsById } = useSavedRemoteConnections(); + const environments = Object.values(savedConnectionsById) + .map((connection) => ({ + environmentId: connection.environmentId, + label: connection.environmentLabel, + })) + .sort((left, right) => left.label.localeCompare(right.label)); + const { options, setSelectedEnvironmentId, setSelectedProjectKey } = useHomeListOptions( + new Set(environments.map((environment) => environment.environmentId)), + ); + // A legacy per-environment scratch key resolves here on every render; the stored + // value is only rewritten when the user picks a filter. + const resolvedProjectKey = resolveScratchProjectScopeKey(options.selectedProjectKey, projects, { + sidebarProjectGroupingMode: options.projectGroupingMode, + sidebarProjectGroupingOverrides: {}, + }); + const projectScopes = buildHomeProjectScopes({ + projects, + environmentId: options.selectedEnvironmentId, + projectGroupingMode: options.projectGroupingMode, + }); + const pickableScopes = pickableProjectGroups(projectScopes); + const projectByKey = new Map(); + for (const project of projects) { + projectByKey.set(scopedProjectKey(project.environmentId, project.id), project); + } + return { + savedConnectionsById, + environments, + options, + setSelectedEnvironmentId, + setSelectedProjectKey, + projectFilterOptions: pickableScopes.map((scope) => ({ key: scope.key, label: scope.title })), + projectTitleByProjectKey: new Map( + projectScopes.flatMap((scope) => + scope.projectRefs.map( + (projectRef) => + [ + scopedProjectKey(projectRef.environmentId, projectRef.projectId), + scope.title, + ] as const, + ), + ), + ), + projectByKey, + // An archived project's filter reads as all projects, matching the filter menu. + selectedProjectScope: pickableScopes.find((scope) => scope.key === resolvedProjectKey) ?? null, + }; +} + function ThreadNavigationSidebarPane( props: ThreadNavigationSidebarProps & { readonly nativeChrome: boolean }, ) { @@ -155,10 +207,8 @@ function ThreadNavigationSidebarPane( const { fabClearance, scale, fabSize } = useAndroidControlSizing(); const enabledTabs = useEnabledNavigationTabs(); const floatingTabs = floatingTabsMetrics(enabledTabs.length + 1, scale, fabSize, props.width); - const projects = useProjects(); const threads = useNavigationThreadShells(); const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState(); - const { savedConnectionsById } = useSavedRemoteConnections(); const searchInputRef = useRef(null); const searchBarRef = useRef(null); const openSwipeableRef = useRef(null); @@ -184,17 +234,17 @@ function ThreadNavigationSidebarPane( const { confirmDeletePendingTask } = usePendingTaskListActions((params) => selectDetail({ name: "Thread", params }), ); - const environments = Object.values(savedConnectionsById) - .map((connection) => ({ - environmentId: connection.environmentId, - label: connection.environmentLabel, - })) - .sort((left, right) => left.label.localeCompare(right.label)); - const availableEnvironmentIds = new Set( - environments.map((environment) => environment.environmentId), - ); - const { options, setSelectedEnvironmentId, setSelectedProjectKey } = - useHomeListOptions(availableEnvironmentIds); + const { + savedConnectionsById, + environments, + options, + setSelectedEnvironmentId, + setSelectedProjectKey, + projectFilterOptions, + projectTitleByProjectKey, + projectByKey, + selectedProjectScope, + } = useSidebarListFilters(); const searchEnvironmentIds = options.selectedEnvironmentId === null ? workspaceEnvironments @@ -207,43 +257,6 @@ function ThreadNavigationSidebarPane( ) ? [options.selectedEnvironmentId] : []; - // A legacy per-environment scratch key resolves here on every render; the stored - // value is only rewritten when the user picks a filter. - const resolvedProjectKey = resolveScratchProjectScopeKey(options.selectedProjectKey, projects, { - sidebarProjectGroupingMode: options.projectGroupingMode, - sidebarProjectGroupingOverrides: {}, - }); - const projectScopes = useMemo( - () => - buildHomeProjectScopes({ - projects, - environmentId: options.selectedEnvironmentId, - projectGroupingMode: options.projectGroupingMode, - }), - [projects, options.selectedEnvironmentId, options.projectGroupingMode], - ); - const projectFilterOptions = pickableProjectGroups(projectScopes).map((scope) => ({ - key: scope.key, - label: scope.title, - })); - const projectTitleByProjectKey = useMemo( - () => - new Map( - projectScopes.flatMap((scope) => - scope.projectRefs.map( - (projectRef) => - [ - scopedProjectKey(projectRef.environmentId, projectRef.projectId), - scope.title, - ] as const, - ), - ), - ), - [projectScopes], - ); - // An archived project's filter reads as all projects, matching the filter menu. - const selectedProjectScope = - pickableProjectGroups(projectScopes).find((scope) => scope.key === resolvedProjectKey) ?? null; const threadSearch = useThreadSearch( searchEnvironmentIds, props.searchQuery, @@ -255,13 +268,6 @@ function ThreadNavigationSidebarPane( // identity; the hook keeps it stable. const threadSearchMatchByKey = useThreadListSearchMatches(threads, threadSearch); const selectedProjectKey = selectedProjectScope?.key ?? null; - const projectByKey = useMemo(() => { - const map = new Map(); - for (const project of projects) { - map.set(scopedProjectKey(project.environmentId, project.id), project); - } - return map; - }, [projects]); const [settledVisibleCount, setSettledVisibleCount] = useState( THREAD_LIST_V2_SETTLED_INITIAL_COUNT, diff --git a/apps/mobile/src/reactCompilerCoverage.test.ts b/apps/mobile/src/reactCompilerCoverage.test.ts index 192b70edba47..b77c24164f25 100644 --- a/apps/mobile/src/reactCompilerCoverage.test.ts +++ b/apps/mobile/src/reactCompilerCoverage.test.ts @@ -200,6 +200,16 @@ describe("React Compiler coverage", () => { ).toEqual([true]); }); + // Uncached project scopes hand the thread list new project refs, rebuilding it every render. + it("caches the sidebar project scopes", () => { + expect( + compilerCachedCalls( + "src/features/threads/ThreadNavigationSidebar.tsx", + "buildHomeProjectScopes", + ), + ).toEqual([true]); + }); + it("lists only files that exist", () => { expect(Object.keys(KNOWN_BAILOUTS).filter((file) => !sourceFiles.includes(file))).toEqual([]); }); diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index 5e2e5a8e3560..5a972597f858 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -4,6 +4,7 @@ import { defineConfig, normalizePath } from "vite-plus"; import "vite-plus/test/config"; const reactTests = [ + "src/features/keyboard/threadKeyboardShortcuts.test.tsx", "src/features/threads/git/GitBranchesSheet.test.tsx", "src/features/threads/new-task-flow-provider.test.tsx", "src/features/workspace/workspace-tabs-state.test.ts",