Skip to content

Commit c3a8c19

Browse files
refactor(mobile): workspace tabs, home filters and connection status derive instead of syncing
The workspace tab controller, the Android root context, the home list filters and the connection-status delay each kept React state in step with something else through an effect: a layout effect copying the selected tab or navigation state into a ref, a render-phase dispatch moving the selection off a hidden tab, an effect persisting the list scope after it changed, and two timers driving the status fade. - WorkspaceTabsContext: the selection lives in a per-provider atom and the hidden-tab fallback is derived from preferences in a second atom, so handlers read the current selection from the registry at call time. Drops the layout effect and the render-phase dispatch. - AndroidWorkspaceTabsProvider: the rail reads the root state from rootNavigationRef when a tab is pressed instead of a ref updated in a layout effect; the context only carries key and settingsOpen. - home-list-options: the scope is saved from the handler that changes it. - WorkspaceConnectionTitle: the show delay and fade are deadlines on the shared clock store (useDeadlinePassed) instead of two timers. - WorkspaceToolbar (generic variant): Back uses the shared useHardwareBack. Effects: WorkspaceTabsContext 1 -> 0, AndroidWorkspaceTabsProvider 1 -> 0, home-list-options 1 -> 0, WorkspaceConnectionTitle 2 -> 1 (the Animated fade stays), WorkspaceToolbar 3 -> 2 (focus-after-commit effect stays). Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 96fc7b9 commit c3a8c19

6 files changed

Lines changed: 119 additions & 118 deletions

File tree

‎apps/mobile/src/features/home/WorkspaceConnectionTitle.tsx‎

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { NativeStackNavigationOptions } from "@react-navigation/native-stack";
2-
import { createContext, use, useEffect, useMemo, useState, type ReactNode } from "react";
2+
import { createContext, use, useEffect, useState, type ReactNode } from "react";
33
import { Animated, Platform, Pressable, View } from "react-native";
44

55
import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
@@ -11,6 +11,7 @@ import {
1111
CompactBrandTitle,
1212
getCompactBrandHeaderOptions,
1313
} from "../../components/CompactBrandTitle";
14+
import { useDeadlinePassed } from "../../lib/clock";
1415
import { useWorkspaceState } from "../../state/workspace";
1516
import {
1617
workspaceConnectionStatusPresentation,
@@ -37,29 +38,24 @@ export function WorkspaceConnectionStatusProvider(props: { readonly children: Re
3738
const { state } = useWorkspaceState();
3839
const presentation = workspaceConnectionStatusPresentation(state);
3940
const hasStatus = presentation !== null;
40-
const [phase, setPhase] = useState<"waiting" | "fading" | "shown">("waiting");
41-
42-
useEffect(() => {
43-
if (!hasStatus) return;
44-
const timers = [
45-
setTimeout(() => setPhase("fading"), STATUS_SHOW_DELAY_MS),
46-
setTimeout(() => setPhase("shown"), STATUS_SHOW_DELAY_MS + FADE_IN_MS),
47-
];
48-
return () => {
49-
for (const timer of timers) clearTimeout(timer);
50-
setPhase("waiting");
51-
};
52-
}, [hasStatus]);
41+
// When the current status run began; a gap in the status restarts the delay.
42+
const [statusSince, setStatusSince] = useState(() => (hasStatus ? Date.now() : null));
43+
if (hasStatus !== (statusSince !== null)) {
44+
// oxlint-disable-next-line react/purity -- Reads the clock only in the render-phase adjustment that runs when the status appears.
45+
setStatusSince(hasStatus ? Date.now() : null);
46+
}
47+
const since = hasStatus ? statusSince : null;
48+
const fadeStarted = useDeadlinePassed(since === null ? null : since + STATUS_SHOW_DELAY_MS);
49+
const fadeEnded = useDeadlinePassed(
50+
since === null ? null : since + STATUS_SHOW_DELAY_MS + FADE_IN_MS,
51+
);
5352

5453
const label = presentation?.label;
5554
const showsProgress = presentation?.showsProgress ?? false;
56-
const status = useMemo(
57-
() =>
58-
label === undefined || phase === "waiting"
59-
? null
60-
: { label, showsProgress, fadeIn: phase === "fading" },
61-
[label, showsProgress, phase],
62-
);
55+
const status =
56+
label === undefined || since === null || !fadeStarted
57+
? null
58+
: { label, showsProgress, fadeIn: !fadeEnded };
6359
return <ConnectionStatusContext value={status}>{props.children}</ConnectionStatusContext>;
6460
}
6561

@@ -72,7 +68,6 @@ function StatusFadeIn(props: {
7268
}) {
7369
const { animate } = props;
7470
const [opacity] = useState(() => new Animated.Value(0));
75-
7671
useEffect(() => {
7772
if (!animate) return;
7873
const animation = Animated.timing(opacity, {

‎apps/mobile/src/features/home/home-list-options.ts‎

Lines changed: 24 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,7 @@
11
import type { EnvironmentId, SidebarProjectGroupingMode } from "@t3tools/contracts";
22
import { DEFAULT_SIDEBAR_PROJECT_SORT_ORDER } from "@t3tools/contracts";
33
import { useAtomSet } from "@effect/atom-react";
4-
import {
5-
createContext,
6-
createElement,
7-
useContext,
8-
useEffect,
9-
useRef,
10-
useState,
11-
type PropsWithChildren,
12-
type Dispatch,
13-
type SetStateAction,
14-
} from "react";
4+
import { createContext, createElement, useContext, useState, type PropsWithChildren } from "react";
155

166
import type { ThreadListFilters } from "../../persistence/mobile-preferences";
177
import { updateMobilePreferencesAtom } from "../../state/preferences";
@@ -40,7 +30,7 @@ function defaultHomeListOptions(filters?: ThreadListFilters): HomeListOptions {
4030

4131
interface HomeListOptionsContextValue {
4232
readonly options: HomeListOptions;
43-
readonly setOptions: Dispatch<SetStateAction<HomeListOptions>>;
33+
readonly updateOptions: (patch: Partial<HomeListOptions>) => void;
4434
readonly projectGroupingMode: SidebarProjectGroupingMode;
4535
}
4636

@@ -56,26 +46,33 @@ export function HomeListOptionsProvider({
5646
}>) {
5747
const [options, setOptions] = useState(() => defaultHomeListOptions(savedFilters));
5848
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
59-
const saved = useRef(savedFilters);
60-
const { selectedEnvironmentId: environmentId, selectedProjectKey: projectKey } = options;
61-
useEffect(() => {
49+
// Only the scope persists; the sort order is per session.
50+
const updateOptions = (patch: Partial<HomeListOptions>) => {
51+
const next = { ...options, ...patch };
52+
setOptions((current) => ({ ...current, ...patch }));
6253
if (
63-
(saved.current?.environmentId ?? null) === environmentId &&
64-
(saved.current?.projectKey ?? null) === projectKey
65-
)
66-
return;
67-
saved.current = { environmentId, projectKey };
68-
savePreferences({ threadListFilters: saved.current });
69-
}, [environmentId, projectKey, savePreferences]);
70-
const value = { options, setOptions, projectGroupingMode };
54+
next.selectedEnvironmentId !== options.selectedEnvironmentId ||
55+
next.selectedProjectKey !== options.selectedProjectKey
56+
) {
57+
savePreferences({
58+
threadListFilters: {
59+
environmentId: next.selectedEnvironmentId,
60+
projectKey: next.selectedProjectKey,
61+
},
62+
});
63+
}
64+
};
65+
const value = { options, updateOptions, projectGroupingMode };
7166
return createElement(HomeListOptionsContext, { value }, children);
7267
}
7368

7469
export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<EnvironmentId>) {
7570
const shared = useContext(HomeListOptionsContext);
7671
const [localOptions, setLocalOptions] = useState<HomeListOptions>(defaultHomeListOptions);
7772
const options = shared?.options ?? localOptions;
78-
const setOptions = shared?.setOptions ?? setLocalOptions;
73+
const updateOptions =
74+
shared?.updateOptions ??
75+
((patch: Partial<HomeListOptions>) => setLocalOptions((current) => ({ ...current, ...patch })));
7976
const selectedEnvironmentId =
8077
options.selectedEnvironmentId !== null &&
8178
availableEnvironmentIds.has(options.selectedEnvironmentId)
@@ -91,13 +88,13 @@ export function useHomeListOptions(availableEnvironmentIds: ReadonlySet<Environm
9188
};
9289

9390
const setSelectedEnvironmentId = (value: EnvironmentId | null) => {
94-
setOptions((current) => ({ ...current, selectedEnvironmentId: value }));
91+
updateOptions({ selectedEnvironmentId: value });
9592
};
9693
const setSelectedProjectKey = (value: string | null) => {
97-
setOptions((current) => ({ ...current, selectedProjectKey: value }));
94+
updateOptions({ selectedProjectKey: value });
9895
};
9996
const setProjectSortOrder = (value: HomeProjectSortOrder) => {
100-
setOptions((current) => ({ ...current, projectSortOrder: value }));
97+
updateOptions({ projectSortOrder: value });
10198
};
10299
return {
103100
options: resolvedOptions,

‎apps/mobile/src/features/workspace/AndroidWorkspaceNavigation.android.tsx‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { useKeyboardState } from "react-native-keyboard-controller";
1313

1414
import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing";
1515
import { useToolbarLayout } from "../../components/ui/useToolbarLayout";
16+
import { rootNavigationRef } from "../../lib/rootNavigation";
1617
import { useWorkspaceConnectionState } from "../../state/workspace";
1718
import { androidWorkspaceNavigationColors } from "./android-workspace-navigation-colors";
1819
import {
@@ -116,9 +117,12 @@ export function AndroidWorkspaceNavigation(props: {
116117
const tab = event.nativeEvent.tab;
117118
if (tab !== "settings") workspace.dispatch({ type: "select", tab });
118119
// Reset the root stack even when a nested settings navigator has focus.
119-
if (root) {
120+
// The provider renders inside the root stack's layout, so the container's root state is
121+
// that stack's current state.
122+
const rootState = rootNavigationRef.getRootState();
123+
if (root && rootState) {
120124
navigation.dispatch({
121-
...CommonActions.reset(androidWorkspaceTabNavigationState(root.getState(), tab)),
125+
...CommonActions.reset(androidWorkspaceTabNavigationState(rootState, tab)),
122126
target: root.key,
123127
});
124128
}

‎apps/mobile/src/features/workspace/AndroidWorkspaceTabsProvider.tsx‎

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,15 @@
11
import type { NavigationState } from "@react-navigation/native";
2-
import {
3-
createContext,
4-
use,
5-
useCallback,
6-
useLayoutEffect,
7-
useMemo,
8-
useRef,
9-
type ReactNode,
10-
} from "react";
2+
import { createContext, use, type ReactNode } from "react";
113
import { Platform } from "react-native";
124
import { androidWorkspaceSettingsOpen } from "./android-workspace-tabs";
135
import { WorkspaceTabsProvider } from "./WorkspaceTabsContext";
146

157
interface AndroidWorkspaceRoot {
168
/**
179
* The rail's `useNavigation()` dispatches to the focused navigator, which may be nested Settings.
18-
* Use the root stack's state and key so a tab press resets the root.
10+
* Target the root stack's key (and read `rootNavigationRef`'s state) so a tab press resets the root.
1911
*/
2012
readonly key: string;
21-
readonly getState: () => NavigationState;
2213
/** Settings is derived from navigation rather than kept in the tab reducer. */
2314
readonly settingsOpen: boolean;
2415
}
@@ -34,14 +25,9 @@ export function AndroidWorkspaceTabsProvider(props: {
3425
readonly state: NavigationState;
3526
readonly children: ReactNode;
3627
}) {
37-
const stateRef = useRef(props.state);
38-
useLayoutEffect(() => {
39-
stateRef.current = props.state;
40-
}, [props.state]);
41-
const getState = useCallback(() => stateRef.current, []);
4228
const key = props.state.key;
4329
const settingsOpen = Platform.OS === "android" && androidWorkspaceSettingsOpen(props.state);
44-
const root = useMemo(() => ({ key, getState, settingsOpen }), [key, getState, settingsOpen]);
30+
const root = { key, settingsOpen };
4531
return Platform.OS === "android" ? (
4632
<WorkspaceTabsProvider>
4733
<AndroidWorkspaceRootContext value={root}>{props.children}</AndroidWorkspaceRootContext>
Lines changed: 63 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,16 @@
1-
import { resolveSelectedNavigationTab } from "./navigation-tab-order";
2-
import { useNavigationTabOrder, useHiddenNavigationTabs } from "./navigation-tabs";
1+
import { RegistryContext, useAtomValue } from "@effect/atom-react";
2+
import { AsyncResult, Atom } from "effect/reactivity";
3+
import { createContext, use, useState, type Dispatch, type ReactNode } from "react";
4+
5+
import { mobilePreferencesAtom } from "../../state/preferences";
36
import {
4-
createContext,
5-
use,
6-
useCallback,
7-
useLayoutEffect,
8-
useMemo,
9-
useReducer,
10-
useRef,
11-
type Dispatch,
12-
type ReactNode,
13-
} from "react";
7+
navigationCustomizationAvailable,
8+
resolveHiddenNavigationTabs,
9+
resolveSelectedNavigationTab,
10+
} from "./navigation-tab-order";
1411
import {
1512
initialWorkspaceTabsState,
13+
resolveWorkspaceTabOrder,
1614
workspaceTabsReducer,
1715
type WorkspaceSearchTab,
1816
type WorkspaceTab,
@@ -34,36 +32,62 @@ export function useWorkspaceTabs() {
3432
return use(WorkspaceTabsContext);
3533
}
3634

35+
type MobilePreferencesResult = Atom.Type<typeof mobilePreferencesAtom>;
36+
37+
/** Moves the selection off a tab the user has hidden or that no longer exists. */
38+
function resolveWorkspaceTabsSelection(
39+
state: WorkspaceTabsState,
40+
preferences: MobilePreferencesResult,
41+
): WorkspaceTabsState {
42+
const saved = AsyncResult.isSuccess(preferences) ? preferences.value : undefined;
43+
const order = resolveWorkspaceTabOrder(saved?.navigationTabOrder);
44+
const hidden = navigationCustomizationAvailable()
45+
? resolveHiddenNavigationTabs(saved?.hiddenNavigationTabs)
46+
: [];
47+
const selected = resolveSelectedNavigationTab(order, hidden, state.selectedTab);
48+
return selected && selected !== state.selectedTab
49+
? workspaceTabsReducer(state, { type: "select", tab: selected })
50+
: state;
51+
}
52+
53+
// One model per provider. Handlers on frozen screens keep stale closures, so
54+
// they read the current selection from the registry at call time.
55+
function createWorkspaceTabsModel() {
56+
const stored = Atom.make(initialWorkspaceTabsState());
57+
const scrollOffsets: Record<WorkspaceSearchTab, number> = {
58+
threads: 0,
59+
pullRequests: 0,
60+
usage: 0,
61+
settings: 0,
62+
};
63+
return {
64+
stored,
65+
resolved: Atom.make((get) =>
66+
resolveWorkspaceTabsSelection(get(stored), get(mobilePreferencesAtom)),
67+
),
68+
getScrollOffset: (tab: WorkspaceSearchTab) => scrollOffsets[tab],
69+
recordScrollOffset: (tab: WorkspaceSearchTab, offset: number) => {
70+
scrollOffsets[tab] = offset;
71+
},
72+
};
73+
}
74+
3775
export function WorkspaceTabsProvider(props: {
3876
readonly children: ReactNode;
3977
readonly settingsOpen?: boolean;
4078
}) {
41-
const [state, dispatch] = useReducer(workspaceTabsReducer, undefined, initialWorkspaceTabsState);
42-
const order = useNavigationTabOrder();
43-
const hidden = useHiddenNavigationTabs();
44-
const selected = resolveSelectedNavigationTab(order, hidden, state.selectedTab);
45-
if (selected && selected !== state.selectedTab) dispatch({ type: "select", tab: selected });
46-
const activeTab = useRef(state.selectedTab);
47-
useLayoutEffect(() => {
48-
activeTab.current = state.selectedTab;
49-
}, [state.selectedTab]);
50-
const isTabActive = useCallback((tab: WorkspaceTab) => activeTab.current === tab, []);
51-
const scrollOffsets = useRef({ threads: 0, pullRequests: 0, usage: 0, settings: 0 });
52-
const getScrollOffset = useCallback((tab: WorkspaceSearchTab) => scrollOffsets.current[tab], []);
53-
const recordScrollOffset = useCallback((tab: WorkspaceSearchTab, offset: number) => {
54-
scrollOffsets.current[tab] = offset;
55-
}, []);
56-
const context = useMemo(
57-
() => ({
58-
state,
59-
dispatch,
60-
isTabActive,
61-
bottomClearance: 0,
62-
settingsOpen: props.settingsOpen ?? false,
63-
getScrollOffset,
64-
recordScrollOffset,
65-
}),
66-
[state, isTabActive, getScrollOffset, recordScrollOffset, props.settingsOpen],
67-
);
79+
const registry = use(RegistryContext);
80+
const [model] = useState(createWorkspaceTabsModel);
81+
const state = useAtomValue(model.resolved);
82+
const context = {
83+
state,
84+
dispatch: (action: WorkspaceTabsAction) =>
85+
registry.set(model.stored, workspaceTabsReducer(registry.get(model.resolved), action)),
86+
isTabActive: (tab: WorkspaceTab) => registry.get(model.resolved).selectedTab === tab,
87+
bottomClearance: 0,
88+
settingsOpen: props.settingsOpen ?? false,
89+
getScrollOffset: model.getScrollOffset,
90+
recordScrollOffset: model.recordScrollOffset,
91+
};
6892
return <WorkspaceTabsContext value={context}>{props.children}</WorkspaceTabsContext>;
6993
}

‎apps/mobile/src/features/workspace/WorkspaceToolbar.tsx‎

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
import { useFocusEffect } from "@react-navigation/native";
2-
import { useCallback, useEffect, useEffectEvent, useRef, useState } from "react";
2+
import { useCallback, useEffect, useRef, useState } from "react";
33
import {
4-
BackHandler,
54
Keyboard,
6-
Platform,
75
Pressable,
86
View,
97
useWindowDimensions,
@@ -14,6 +12,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
1412

1513
import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
1614
import { GlassSurface } from "../../components/ui/GlassSurface";
15+
import { useHardwareBack } from "../../lib/backHandler";
1716
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
1817
import { WorkspaceDock } from "./WorkspaceDock";
1918
import { WorkspaceSearchField } from "./WorkspaceSearchField";
@@ -79,18 +78,14 @@ export function WorkspaceToolbar(props: {
7978
);
8079
workspace?.dispatch({ type: "cancel" });
8180
}, [workspace]);
82-
const handleBack = useEffectEvent(() => {
83-
if (!workspace || workspace.state.tabs[workspace.state.selectedTab].searchMode === "resting")
84-
return false;
81+
const searchOpen =
82+
workspace !== null &&
83+
workspace.state.tabs[workspace.state.selectedTab].searchMode !== "resting";
84+
useHardwareBack(searchOpen, () => {
8585
if (keyboardVisible) Keyboard.dismiss();
8686
else cancelSearch();
8787
return true;
8888
});
89-
useEffect(() => {
90-
if (Platform.OS !== "android") return;
91-
const subscription = BackHandler.addEventListener("hardwareBackPress", handleBack);
92-
return () => subscription.remove();
93-
}, []);
9489
useEffect(() => {
9590
if (focusRequest > 0) input.current?.focus();
9691
}, [focusRequest]);

0 commit comments

Comments
 (0)