TypeScript
refactor(mobile): workspace tabs, home filters and connection status derive instead of syncing (#25813)
Julius Marminge79f6cd30c7ed
diff --git a/apps/mobile/src/features/home/WorkspaceConnectionTitle.tsx b/apps/mobile/src/features/home/WorkspaceConnectionTitle.tsxindex b00fac55e18..d0963c1b9b8 100644--- a/apps/mobile/src/features/home/WorkspaceConnectionTitle.tsx+++ b/apps/mobile/src/features/home/WorkspaceConnectionTitle.tsx@@ -1,5 +1,5 @@import type { NativeStackNavigationOptions } from "@react-navigation/native-stack";-import { createContext, use, useEffect, useMemo, useState, type ReactNode } from "react";+import { createContext, use, useEffect, useState, type ReactNode } from "react";import { Animated, Platform, Pressable, View } from "react-native";import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";@@ -11,6 +11,7 @@ import {CompactBrandTitle,getCompactBrandHeaderOptions,} from "../../components/CompactBrandTitle";+import { useDeadlinePassed } from "../../lib/clock";import { useWorkspaceState } from "../../state/workspace";import {workspaceConnectionStatusPresentation,@@ -37,29 +38,24 @@ export function WorkspaceConnectionStatusProvider(props: { readonly children: Reconst { state } = useWorkspaceState();const presentation = workspaceConnectionStatusPresentation(state);const hasStatus = presentation !== null;- const [phase, setPhase] = useState<"waiting" | "fading" | "shown">("waiting");-- useEffect(() => {- if (!hasStatus) return;- const timers = [- setTimeout(() => setPhase("fading"), STATUS_SHOW_DELAY_MS),- setTimeout(() => setPhase("shown"), STATUS_SHOW_DELAY_MS + FADE_IN_MS),- ];- return () => {- for (const timer of timers) clearTimeout(timer);- setPhase("waiting");- };- }, [hasStatus]);+ // When the current status run began; a gap in the status restarts the delay.+ const [statusSince, setStatusSince] = useState(() => (hasStatus ? Date.now() : null));+ if (hasStatus !== (statusSince !== null)) {+ // oxlint-disable-next-line react/purity -- Reads the clock only in the render-phase adjustment that runs when the status appears.+ setStatusSince(hasStatus ? Date.now() : null);+ }+ const since = hasStatus ? statusSince : null;+ const fadeStarted = useDeadlinePassed(since === null ? null : since + STATUS_SHOW_DELAY_MS);+ const fadeEnded = useDeadlinePassed(+ since === null ? null : since + STATUS_SHOW_DELAY_MS + FADE_IN_MS,+ );const label = presentation?.label;const showsProgress = presentation?.showsProgress ?? false;- const status = useMemo(- () =>- label === undefined || phase === "waiting"- ? null- : { label, showsProgress, fadeIn: phase === "fading" },- [label, showsProgress, phase],- );+ const status =+ label === undefined || since === null || !fadeStarted+ ? null+ : { label, showsProgress, fadeIn: !fadeEnded };return <ConnectionStatusContext value={status}>{props.children}</ConnectionStatusContext>;}@@ -72,7 +68,6 @@ function StatusFadeIn(props: {}) {const { animate } = props;const [opacity] = useState(() => new Animated.Value(0));-useEffect(() => {if (!animate) return;const animation = Animated.timing(opacity, {diff --git a/apps/mobile/src/features/home/home-list-options.test.tsx b/apps/mobile/src/features/home/home-list-options.test.tsxnew file mode 100644index 00000000000..f25d4ff6908--- /dev/null+++ b/apps/mobile/src/features/home/home-list-options.test.tsx@@ -0,0 +1,49 @@+import type { EnvironmentId } from "@t3tools/contracts";+import { act, useLayoutEffect } from "react";+import { createRoot } from "react-dom/client";+import { expect, it, vi } from "vite-plus/test";++const harness = vi.hoisted(() => ({ saved: [] as unknown[] }));++vi.mock("../../state/preferences", () => ({ updateMobilePreferencesAtom: {} }));+vi.mock("@effect/atom-react", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@effect/atom-react")>()),+ useAtomSet: () => (value: unknown) => harness.saved.push(value),+}));++import { HomeListOptionsProvider, useHomeListOptions } from "./home-list-options";++const ENVIRONMENT = "env-1" as EnvironmentId;+const AVAILABLE = new Set([ENVIRONMENT]);++it("saves the scope from every update made in one event", async () => {+ harness.saved = [];+ let controls: ReturnType<typeof useHomeListOptions> | undefined;+ function Probe() {+ const result = useHomeListOptions(AVAILABLE);+ useLayoutEffect(() => {+ controls = result;+ });+ return null;+ }++ const root = createRoot(document.createElement("div"));+ await act(async () =>+ root.render(+ <HomeListOptionsProvider projectGroupingMode="repository">+ <Probe />+ </HomeListOptionsProvider>,+ ),+ );+ act(() => {+ controls!.setSelectedEnvironmentId(ENVIRONMENT);+ controls!.setSelectedProjectKey("env-1:project-1");+ });++ expect(harness.saved.at(-1)).toEqual({+ threadListFilters: { environmentId: ENVIRONMENT, projectKey: "env-1:project-1" },+ });+ expect(controls!.options.selectedEnvironmentId).toBe(ENVIRONMENT);+ expect(controls!.options.selectedProjectKey).toBe("env-1:project-1");+ act(() => root.unmount());+});diff --git a/apps/mobile/src/features/home/home-list-options.ts b/apps/mobile/src/features/home/home-list-options.tsindex 9ee8cadf676..09c8be2c9a7 100644--- a/apps/mobile/src/features/home/home-list-options.ts+++ b/apps/mobile/src/features/home/home-list-options.ts@@ -1,17 +1,8 @@import type { EnvironmentId, SidebarProjectGroupingMode } from "@t3tools/contracts";import { DEFAULT_SIDEBAR_PROJECT_SORT_ORDER } from "@t3tools/contracts";-import { useAtomSet } from "@effect/atom-react";-import {- createContext,- createElement,- useContext,- useEffect,- useRef,- useState,- type PropsWithChildren,- type Dispatch,- type SetStateAction,-} from "react";+import { RegistryContext, useAtomSet, useAtomValue } from "@effect/atom-react";+import { Atom } from "effect/reactivity";+import { createContext, createElement, useContext, useState, type PropsWithChildren } from "react";import type { ThreadListFilters } from "../../persistence/mobile-preferences";import { updateMobilePreferencesAtom } from "../../state/preferences";@@ -40,7 +31,7 @@ function defaultHomeListOptions(filters?: ThreadListFilters): HomeListOptions {interface HomeListOptionsContextValue {readonly options: HomeListOptions;- readonly setOptions: Dispatch<SetStateAction<HomeListOptions>>;+ readonly updateOptions: (patch: Partial<HomeListOptions>) => void;readonly projectGroupingMode: SidebarProjectGroupingMode;}@@ -54,20 +45,29 @@ export function HomeListOptionsProvider({readonly projectGroupingMode: SidebarProjectGroupingMode;readonly savedFilters?: ThreadListFilters | undefined;}>) {- const [options, setOptions] = useState(() => defaultHomeListOptions(savedFilters));+ const registry = useContext(RegistryContext);+ const [optionsAtom] = useState(() => Atom.make(defaultHomeListOptions(savedFilters)));+ const options = useAtomValue(optionsAtom);const savePreferences = useAtomSet(updateMobilePreferencesAtom);- const saved = useRef(savedFilters);- const { selectedEnvironmentId: environmentId, selectedProjectKey: projectKey } = options;- useEffect(() => {+ // Only the scope persists; the sort order is per session. Updates read the+ // registry, so several in one event each build on the last and save it.+ const updateOptions = (patch: Partial<HomeListOptions>) => {+ const current = registry.get(optionsAtom);+ const next = { ...current, ...patch };+ registry.set(optionsAtom, next);if (- (saved.current?.environmentId ?? null) === environmentId &&- (saved.current?.projectKey ?? null) === projectKey- )- return;- saved.current = { environmentId, projectKey };- savePreferences({ threadListFilters: saved.current });- }, [environmentId, projectKey, savePreferences]);- const value = { options, setOptions, projectGroupingMode };+ next.selectedEnvironmentId !== current.selectedEnvironmentId ||+ next.selectedProjectKey !== current.selectedProjectKey+ ) {+ savePreferences({+ threadListFilters: {+ environmentId: next.selectedEnvironmentId,+ projectKey: next.selectedProjectKey,+ },+ });+ }+ };+ const value = { options, updateOptions, projectGroupingMode };return createElement(HomeListOptionsContext, { value }, children);}@@ -75,7 +75,9 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environmconst shared = useContext(HomeListOptionsContext);const [localOptions, setLocalOptions] = useState<HomeListOptions>(defaultHomeListOptions);const options = shared?.options ?? localOptions;- const setOptions = shared?.setOptions ?? setLocalOptions;+ const updateOptions =+ shared?.updateOptions ??+ ((patch: Partial<HomeListOptions>) => setLocalOptions((current) => ({ ...current, ...patch })));const selectedEnvironmentId =options.selectedEnvironmentId !== null &&availableEnvironmentIds.has(options.selectedEnvironmentId)@@ -91,13 +93,13 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm};const setSelectedEnvironmentId = (value: EnvironmentId | null) => {- setOptions((current) => ({ ...current, selectedEnvironmentId: value }));+ updateOptions({ selectedEnvironmentId: value });};const setSelectedProjectKey = (value: string | null) => {- setOptions((current) => ({ ...current, selectedProjectKey: value }));+ updateOptions({ selectedProjectKey: value });};const setProjectSortOrder = (value: HomeProjectSortOrder) => {- setOptions((current) => ({ ...current, projectSortOrder: value }));+ updateOptions({ projectSortOrder: value });};return {options: resolvedOptions,diff --git a/apps/mobile/src/features/workspace/AndroidWorkspaceNavigation.android.tsx b/apps/mobile/src/features/workspace/AndroidWorkspaceNavigation.android.tsxindex ca5b415b476..67302833827 100644--- a/apps/mobile/src/features/workspace/AndroidWorkspaceNavigation.android.tsx+++ b/apps/mobile/src/features/workspace/AndroidWorkspaceNavigation.android.tsx@@ -13,6 +13,7 @@ import { useKeyboardState } from "react-native-keyboard-controller";import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";import { useToolbarLayout } from "../../components/ui/useToolbarLayout";+import { rootNavigationRef } from "../../lib/rootNavigation";import { useWorkspaceConnectionState } from "../../state/workspace";import { androidWorkspaceNavigationColors } from "./android-workspace-navigation-colors";import {@@ -116,11 +117,12 @@ export function AndroidWorkspaceNavigation(props: {const tab = event.nativeEvent.tab;if (tab !== "settings") workspace.dispatch({ type: "select", tab });// Reset the root stack even when a nested settings navigator has focus.- if (root) {+ // The provider renders inside the root stack's layout, so the container's root state is+ // that stack's current state.+ const rootState = rootNavigationRef.getRootState();+ if (root && rootState) {navigation.dispatch({- ...CommonActions.reset(- androidWorkspaceTabNavigationState(root.getState(), tab, rail),- ),+ ...CommonActions.reset(androidWorkspaceTabNavigationState(rootState, tab, rail)),target: root.key,});}diff --git a/apps/mobile/src/features/workspace/AndroidWorkspaceTabsProvider.tsx b/apps/mobile/src/features/workspace/AndroidWorkspaceTabsProvider.tsxindex 32e5f70d635..5fc9b50097b 100644--- a/apps/mobile/src/features/workspace/AndroidWorkspaceTabsProvider.tsx+++ b/apps/mobile/src/features/workspace/AndroidWorkspaceTabsProvider.tsx@@ -1,13 +1,5 @@import type { NavigationState } from "@react-navigation/native";-import {- createContext,- use,- useCallback,- useLayoutEffect,- useMemo,- useRef,- type ReactNode,-} from "react";+import { createContext, use, type ReactNode } from "react";import { Platform } from "react-native";import { androidWorkspaceSettingsOpen } from "./android-workspace-tabs";import { WorkspaceTabsProvider } from "./WorkspaceTabsContext";@@ -15,10 +7,9 @@ import { WorkspaceTabsProvider } from "./WorkspaceTabsContext";interface AndroidWorkspaceRoot {/*** The rail's `useNavigation()` dispatches to the focused navigator, which may be nested Settings.- * Use the root stack's state and key so a tab press resets the root.+ * Target the root stack's key (and read `rootNavigationRef`'s state) so a tab press resets the root.*/readonly key: string;- readonly getState: () => NavigationState;/** Settings is derived from navigation rather than kept in the tab reducer. */readonly settingsOpen: boolean;readonly settingsRoute: NavigationState["routes"][number] | undefined;@@ -36,21 +27,13 @@ export function AndroidWorkspaceTabsProvider(props: {readonly state: NavigationState;readonly children: ReactNode;}) {- const stateRef = useRef(props.state);- useLayoutEffect(() => {- stateRef.current = props.state;- }, [props.state]);- const getState = useCallback(() => stateRef.current, []);const key = props.state.key;const settingsOpen = Platform.OS === "android" && androidWorkspaceSettingsOpen(props.state);const settingsIndex = props.state.routes.findIndex((route) => route.name === "Settings");const settingsRoute = settingsIndex < 0 ? undefined : props.state.routes[settingsIndex];const settingsPage =settingsIndex < 0 ? null : (props.state.routes[settingsIndex + 1]?.name ?? null);- const root = useMemo(- () => ({ key, getState, settingsOpen, settingsRoute, settingsPage }),- [key, getState, settingsOpen, settingsRoute, settingsPage],- );+ const root = { key, settingsOpen, settingsRoute, settingsPage };return Platform.OS === "android" ? (<WorkspaceTabsProvider><AndroidWorkspaceRootContext value={root}>{props.children}</AndroidWorkspaceRootContext>diff --git a/apps/mobile/src/features/workspace/WorkspaceTabsContext.tsx b/apps/mobile/src/features/workspace/WorkspaceTabsContext.tsxindex 2c3a10e4b0c..6faa8c73d05 100644--- a/apps/mobile/src/features/workspace/WorkspaceTabsContext.tsx+++ b/apps/mobile/src/features/workspace/WorkspaceTabsContext.tsx@@ -1,18 +1,16 @@-import { resolveSelectedNavigationTab } from "./navigation-tab-order";-import { useNavigationTabOrder, useHiddenNavigationTabs } from "./navigation-tabs";+import { RegistryContext, useAtomValue } from "@effect/atom-react";+import { AsyncResult, Atom } from "effect/reactivity";+import { createContext, use, useState, type Dispatch, type ReactNode } from "react";++import { mobilePreferencesAtom } from "../../state/preferences";import {- createContext,- use,- useCallback,- useLayoutEffect,- useMemo,- useReducer,- useRef,- type Dispatch,- type ReactNode,-} from "react";+ navigationCustomizationAvailable,+ resolveHiddenNavigationTabs,+ resolveSelectedNavigationTab,+} from "./navigation-tab-order";import {initialWorkspaceTabsState,+ resolveWorkspaceTabOrder,workspaceTabsReducer,type WorkspaceSearchTab,type WorkspaceTab,@@ -34,36 +32,62 @@ export function useWorkspaceTabs() {return use(WorkspaceTabsContext);}+type MobilePreferencesResult = Atom.Type<typeof mobilePreferencesAtom>;++/** Moves the selection off a tab the user has hidden or that no longer exists. */+function resolveWorkspaceTabsSelection(+ state: WorkspaceTabsState,+ preferences: MobilePreferencesResult,+): WorkspaceTabsState {+ const saved = AsyncResult.isSuccess(preferences) ? preferences.value : undefined;+ const order = resolveWorkspaceTabOrder(saved?.navigationTabOrder);+ const hidden = navigationCustomizationAvailable()+ ? resolveHiddenNavigationTabs(saved?.hiddenNavigationTabs)+ : [];+ const selected = resolveSelectedNavigationTab(order, hidden, state.selectedTab);+ return selected && selected !== state.selectedTab+ ? workspaceTabsReducer(state, { type: "select", tab: selected })+ : state;+}++// One model per provider. Handlers on frozen screens keep stale closures, so+// they read the current selection from the registry at call time.+function createWorkspaceTabsModel() {+ const stored = Atom.make(initialWorkspaceTabsState());+ const scrollOffsets: Record<WorkspaceSearchTab, number> = {+ threads: 0,+ pullRequests: 0,+ usage: 0,+ settings: 0,+ };+ return {+ stored,+ resolved: Atom.make((get) =>+ resolveWorkspaceTabsSelection(get(stored), get(mobilePreferencesAtom)),+ ),+ getScrollOffset: (tab: WorkspaceSearchTab) => scrollOffsets[tab],+ recordScrollOffset: (tab: WorkspaceSearchTab, offset: number) => {+ scrollOffsets[tab] = offset;+ },+ };+}+export function WorkspaceTabsProvider(props: {readonly children: ReactNode;readonly settingsOpen?: boolean;}) {- const [state, dispatch] = useReducer(workspaceTabsReducer, undefined, initialWorkspaceTabsState);- const order = useNavigationTabOrder();- const hidden = useHiddenNavigationTabs();- const selected = resolveSelectedNavigationTab(order, hidden, state.selectedTab);- if (selected && selected !== state.selectedTab) dispatch({ type: "select", tab: selected });- const activeTab = useRef(state.selectedTab);- useLayoutEffect(() => {- activeTab.current = state.selectedTab;- }, [state.selectedTab]);- const isTabActive = useCallback((tab: WorkspaceTab) => activeTab.current === tab, []);- const scrollOffsets = useRef({ threads: 0, pullRequests: 0, usage: 0, settings: 0 });- const getScrollOffset = useCallback((tab: WorkspaceSearchTab) => scrollOffsets.current[tab], []);- const recordScrollOffset = useCallback((tab: WorkspaceSearchTab, offset: number) => {- scrollOffsets.current[tab] = offset;- }, []);- const context = useMemo(- () => ({- state,- dispatch,- isTabActive,- bottomClearance: 0,- settingsOpen: props.settingsOpen ?? false,- getScrollOffset,- recordScrollOffset,- }),- [state, isTabActive, getScrollOffset, recordScrollOffset, props.settingsOpen],- );+ const registry = use(RegistryContext);+ const [model] = useState(createWorkspaceTabsModel);+ const state = useAtomValue(model.resolved);+ const context = {+ state,+ dispatch: (action: WorkspaceTabsAction) =>+ registry.set(model.stored, workspaceTabsReducer(registry.get(model.resolved), action)),+ isTabActive: (tab: WorkspaceTab) => registry.get(model.resolved).selectedTab === tab,+ bottomClearance: 0,+ settingsOpen: props.settingsOpen ?? false,+ getScrollOffset: model.getScrollOffset,+ recordScrollOffset: model.recordScrollOffset,+ };return <WorkspaceTabsContext value={context}>{props.children}</WorkspaceTabsContext>;}diff --git a/apps/mobile/src/features/workspace/WorkspaceToolbar.tsx b/apps/mobile/src/features/workspace/WorkspaceToolbar.tsxindex 73c8a9e8733..70c606353dc 100644--- a/apps/mobile/src/features/workspace/WorkspaceToolbar.tsx+++ b/apps/mobile/src/features/workspace/WorkspaceToolbar.tsx@@ -1,9 +1,7 @@import { useFocusEffect } from "@react-navigation/native";-import { useCallback, useEffect, useEffectEvent, useRef, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import {- BackHandler,Keyboard,- Platform,Pressable,View,useWindowDimensions,@@ -14,6 +12,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";import { GlassSurface } from "../../components/ui/GlassSurface";+import { useHardwareBack } from "../../lib/backHandler";import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";import { WorkspaceDock } from "./WorkspaceDock";import { WorkspaceSearchField } from "./WorkspaceSearchField";@@ -79,18 +78,14 @@ export function WorkspaceToolbar(props: {);workspace?.dispatch({ type: "cancel" });}, [workspace]);- const handleBack = useEffectEvent(() => {- if (!workspace || workspace.state.tabs[workspace.state.selectedTab].searchMode === "resting")- return false;+ const searchOpen =+ workspace !== null &&+ workspace.state.tabs[workspace.state.selectedTab].searchMode !== "resting";+ useHardwareBack(searchOpen, () => {if (keyboardVisible) Keyboard.dismiss();else cancelSearch();return true;});- useEffect(() => {- if (Platform.OS !== "android") return;- const subscription = BackHandler.addEventListener("hardwareBackPress", handleBack);- return () => subscription.remove();- }, []);useEffect(() => {if (focusRequest > 0) input.current?.focus();}, [focusRequest]);diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.tsindex 28c1aeee58b..3e37faf60d0 100644--- a/apps/mobile/vite.config.ts+++ b/apps/mobile/vite.config.ts@@ -26,6 +26,7 @@ const reactTests = ["src/state/use-selected-thread-git-actions.test.tsx","src/features/terminal/useTerminalExitNavigation.test.tsx","src/features/threads/use-thread-list-now.test.tsx",+ "src/features/home/home-list-options.test.tsx",];const sourceRoot = `${normalizePath(NodeURL.fileURLToPath(new URL("./src", import.meta.url)))}/`;