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

useCollapsedSplitColumn.ts

62 lines2.6 KB

1import type { NavigationAction, NavigationState } from "@react-navigation/native";
2import { useEffect, useRef, type RefObject } from "react";
3import type { SplitHostCommands } from "react-native-screens";
4import {
5 collapsedSplitTransition,
6 type CollapsedSplitColumn,
7} from "../../native/workspace-stack-projection";
8import { setNativelyPoppingWorkspaceRoute } from "./workspace/workspace-detail-selection";
9​
10type Appearance = "willAppear" | "didAppear" | "willDisappear" | "didDisappear";
11​
12/** Keeps the column a collapsed split shows in step with the router's active detail. */
13export function useCollapsedSplitColumn(input: {
14 readonly hostRef: RefObject<SplitHostCommands | null>;
15 readonly usesSplitView: boolean;
16 readonly compactColumn: CollapsedSplitColumn["visible"];
17 readonly primaryKey: string;
18 readonly navigation: {
19 readonly getState: () => Pick<NavigationState, "key" | "index" | "routes">;
20 readonly dispatch: (action: NavigationAction) => void;
21 };
22}) {
23 const { hostRef, usesSplitView, compactColumn } = input;
24 const collapsed = useRef(!usesSplitView);
25 const column = useRef<CollapsedSplitColumn>({ visible: compactColumn, leaving: null });
26​
27 const showCompactColumn = () => {
28 if (usesSplitView || column.current.visible === compactColumn) return;
29 column.current = { ...column.current, visible: compactColumn };
30 hostRef.current?.show(compactColumn);
31 };
32 // Every commit, not only when compactColumn changes: a thread picked while folded Back reveals
33 // the list survives Back's pop, so the router keeps a detail while UIKit shows the list.
34 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- tells the native split host which column to show while collapsed
35 useEffect(showCompactColumn);
36​
37 return {
38 followAppearance: (type: Appearance, key: string) => {
39 if (!collapsed.current || usesSplitView) return;
40 const transition = collapsedSplitTransition(
41 column.current,
42 { type, key },
43 input.navigation.getState(),
44 input.primaryKey,
45 );
46 column.current = transition.column;
47 setNativelyPoppingWorkspaceRoute(transition.column.leaving);
48 // A pop re-renders and the effect above follows it; without one, nothing would re-render.
49 if (transition.pop) input.navigation.dispatch(transition.pop);
50 else showCompactColumn();
51 },
52 onCollapse: () => {
53 collapsed.current = true;
54 column.current = { visible: compactColumn, leaving: null };
55 setNativelyPoppingWorkspaceRoute(null);
56 },
57 onExpand: () => {
58 collapsed.current = false;
59 setNativelyPoppingWorkspaceRoute(null);
60 },
61 };