import { paneNavigatorProxyKey } from './replaceUrl'; import * as React from 'react'; import { StateNavigator } from 'navigation'; import { BackHandler, Platform, StyleSheet, View, useWindowDimensions, type StyleProp, type ViewStyle, } from 'react-native'; import { NavigationHandler } from 'navigation-react'; import OptimizedContext, { OptimizedContextProvider, } from './contexts/OptimizedContext'; import RidgeNavigationContext from './contexts/RidgeNavigationContext'; import FullScreenPushContext from './contexts/FullScreenPushContext'; import SplitPaneContext from './contexts/SplitPaneContext'; import useLatest from './useLatest'; import useCurrentRoot from './useCurrentRoot'; import useBottomTabIndex from './useBottomTabIndex'; import { consumePaneApplyIntent, resolvePaneBackAction, resolveSelectionHistoryAction, stepPaneDrillBack, shouldPreloadMirroredSelection, type PaneApplyIntent, type SelectionHistory, } from './selectionHistory'; import { createNormalRoot, generatePath, getScreenKey, makeVariablesNavigationFriendly, rootKeyAndPaths, } from './navigationUtils'; /** * A snapshot of the selection-relevant query params (section + detail hrefs). * The selection-history stack (see below) records one of these per URL entry. * Native in-app Back uses it synchronously; web consumes the corresponding * browser-history entry so the next outer Back cannot land on a duplicate URL. */ type SelectionSnapshot = Record; function selectionSnapshot( data: Record | undefined, keys: Array ): SelectionSnapshot { const snap: SelectionSnapshot = {}; for (const key of keys) { if (key && data?.[key] != null) { snap[key] = data[key]; } } return snap; } function sameSelection(a: SelectionSnapshot, b: SelectionSnapshot): boolean { const ak = Object.keys(a); const bk = Object.keys(b); return ak.length === bk.length && ak.every((k) => a[k] === b[k]); } export type TripleSplitViewProps = { /** * Column 1 — the primary sidebar (a source list / category nav). Pushes made * from inside it SELECT the middle column (they reset it to the pushed * screen), iPad Settings/Mail style. */ sidebar: React.ReactNode; /** Shown in the middle column until the sidebar selects something. */ masterPlaceholder?: React.ReactNode; /** Shown in the detail column until the middle column selects something. */ detailPlaceholder?: React.ReactNode; /** * Below this width the whole thing collapses to just the sidebar; pushes go * to the main navigator (normal single-column stack), exactly like phones. */ breakingPointWidth?: number; sidebarWidth?: number; masterWidth?: number; sidebarStyle?: StyleProp; masterStyle?: StyleProp; detailStyle?: StyleProp; /** * Health-app style: float the sidebar as an absolutely-positioned TRANSLUCENT * glass panel ON TOP of the content columns, instead of reserving a column to * its left. The middle/detail content then spans edge-to-edge from x=0, so a * colored/gradient background visibly bleeds UNDER the sidebar. Make the * sidebar surface translucent via `sidebarStyle` (and/or a native BlurView on * iOS / `backdrop-filter` on web) for the frosted-glass look. Default false. */ floatingSidebar?: boolean; /** * Restore a previous middle/detail selection on mount — the hook that makes * the three columns deep-linkable. Paths are the registered `screen.path` * values (stable across reloads), NOT the internal per-instance pane keys. * The host typically reads these from the URL. */ initialSelection?: TripleSelection; /** * Fires whenever the middle or detail selection changes, with the full * current selection expressed as stable `screen.path` + params. The host * writes this to the URL (query string / route params) so the columns become * shareable, bookmarkable links without the panes fighting the main * navigator for browser history. */ onSelectionChange?: (selection: TripleSelection) => void; /** * Opt in to making the SIDEBAR→MIDDLE selection (which section is open) part * of navigation state. When set to a query-param name (e.g. `"section"`), * selecting a section from the sidebar: * * - reflects the selection in the URL of the MAIN navigator as a query param * (`…/more?section=werknemers`), so it is deep-linkable and restored on a * cold reload, * - keeps it on the MAIN navigator's single history timeline. Peer picks * replace the current entry by default; `selectionHistory="push"` opts into * browser/native Back and Forward stepping through previous selections. * * Switching to another section also drops any `detailParam` from the URL, so * the detail column empties (iPad Mail: changing mailbox clears the message). * * This is the three-column analogue of SplitView's `selectionParam`, applied * to the first level. Pair it with `detailParam` for the second level. */ sectionParam?: string; /** * Opt in to making the MIDDLE→DETAIL selection (which item is open) part of * navigation state. When set to a query-param name (e.g. `"detail"`), * selecting an item from the middle column reflects it in the MAIN URL * (`…/more?section=werknemers&detail=user/42`) and re-derives the detail pane * from that URL — so it is deep-linkable and cold-restorable, exactly like * SplitView's `selectionParam`. Peer picks replace history by default; * `selectionHistory="push"` opts into replaying them with Back/Forward. */ detailParam?: string; /** * How peer selections from the sidebar and middle column affect navigation * history. Defaults to `replace`; use `push` when Back/Forward should replay * previously selected sections/items. Narrow layouts and detail drill-downs * keep their normal push behaviour. */ selectionHistory?: SelectionHistory; }; /** One column's current selection: the registered screen path plus its params, * or null when that column is showing its placeholder. */ export type TripleSelection = { middle: TripleSelectionEntry | null; detail: TripleSelectionEntry | null; }; export type TripleSelectionEntry = { path: string; params?: any }; /** * Three-column master/detail (iPad Mail / macOS Settings style) for wide * screens: sidebar → middle list → detail. * * Built on the same history-less-navigator technique as SplitView, applied * twice: pushes from the sidebar select the MIDDLE column (a second history- * less navigator); pushes from the middle column select the DETAIL column (a * third history-less navigator). On narrow screens the sidebar renders as-is * and navigation behaves exactly like today — full-screen pushes on the main * stack — so phones (iOS + Android) are unaffected. * * Cross-platform: no UIKit UISplitViewController dependency, so it renders * identically on iOS, Android and web (Android has no native 3-column * controller; this is the portable equivalent). */ export default function TripleSplitView({ sidebar, masterPlaceholder, detailPlaceholder, breakingPointWidth = 900, sidebarWidth = 260, masterWidth = 360, sidebarStyle, masterStyle, detailStyle, floatingSidebar, initialSelection, onSelectionChange, sectionParam, detailParam, selectionHistory = 'replace', }: TripleSplitViewProps) { // Seed from window width so it renders on first paint (no null-until-onLayout // flash / background-tab breakage); onLayout refines the container width. const windowWidth = useWindowDimensions().width; const [width, setWidth] = React.useState(windowWidth); const isWide = width >= breakingPointWidth; return ( setWidth(e.nativeEvent.layout.width)} > {isWide ? ( {sidebar} ) : ( sidebar )} ); } /** Builds a history-less navigator that renders every registered screen under a * scoped rootKey, plus a placeholder at the root. */ function useScopedPaneNavigator( screens: any[], SuspenseContainer: any, rootKey: string ) { return React.useMemo(() => { const stateInfos = [ { key: rootKey, route: rootKey, trackCrumbTrail: false, renderScene: () => null, preloadId: rootKey, }, ...screens.map((screen) => ({ key: rootKeyAndPaths(rootKey, screen.path), route: makeVariablesNavigationFriendly( rootKeyAndPaths(rootKey, screen.path) ), renderScene: () => ( ), trackCrumbTrail: true, screen, preloadId: screen.path, })), ]; const navigator = new StateNavigator(stateInfos as any); navigator.historyManager.disabled = true; navigator.historyManager.stop(); navigator.navigate(rootKey); return navigator; }, [SuspenseContainer, rootKey, screens]); } function WideTripleSplitView({ children, masterPlaceholder, detailPlaceholder, sidebarWidth, masterWidth, sidebarStyle, masterStyle, detailStyle, floatingSidebar, initialSelection, onSelectionChange, sectionParam, detailParam, selectionHistory, }: Omit & { children: React.ReactNode; }) { const id = React.useId(); const safe = id.replace(/:/g, '--'); const middleRootKey = 'tripleMiddle_' + safe; const detailRootKey = 'tripleDetail_' + safe; const ridge = React.useContext(RidgeNavigationContext); const outerOptimized = React.useContext(OptimizedContext); const { screens, navigationRoot, SuspenseContainer } = ridge; const theme = outerOptimized.theme; // The MAIN navigator the split itself lives on. With `sectionParam`/ // `detailParam` set, selections flow through it (URL query + single history // timeline) instead of staying private to the panes — see below. // Web URL-backed panes must target the stable root navigator. The ambient // state navigator is a transient NavigationHandler wrapper and can commit an // older selection after a fast drill. Native keeps its current nested/tab // navigator because that is the stack which hosts the split. const mainNavigator = Platform.OS === 'web' ? outerOptimized.rootNavigator : outerOptimized.stateNavigator; const { preloadScreen } = outerOptimized; const { currentRootKey } = useCurrentRoot(); const { currentTab } = useBottomTabIndex(); const urlDriven = Boolean(sectionParam || detailParam); const fullScreenPush = React.useCallback( (screen: any, params: any, options?: { preload?: boolean }) => { if (options?.preload ?? true) { preloadScreen(screen, params); } const screenKey = getScreenKey(currentRootKey!, currentTab, screen.path); mainNavigator.navigate(screenKey, params, 'add'); }, [mainNavigator, preloadScreen, currentRootKey, currentTab] ); // In-app back for URL-selection mode. Each selection level (section, detail, // and any sub-form drilled inside the detail) is a MAIN-navigator history // entry created by `refresh(..., 'add')` — the state stays put, only the // query data changes. Browser Back walks those data entries via the History // API, but `mainNavigator.navigateBack` walks the CRUMB trail instead and // would jump out of the whole split. Web must consume the real browser entry; // native steps the recorded pane selection before falling back to the outer // crumb navigator. // The applied selection snapshots, oldest→newest, mirroring the main // navigator's selection history. Maintained by the URL-mirror effect below; // consumed by native `paneGoBack` for its synchronous state step. const selectionStackRef = React.useRef([]); const paneCanGoBack = React.useCallback(() => { const data: any = mainNavigator.stateContext.data ?? {}; const hasSelection = (sectionParam && data[sectionParam] != null) || (detailParam && data[detailParam] != null); return Boolean(hasSelection) || mainNavigator.canNavigateBack(1); }, [mainNavigator, sectionParam, detailParam]); const masterPlaceholderRef = useLatest(masterPlaceholder); const detailPlaceholderRef = useLatest(detailPlaceholder); // Third column: the detail navigator. const detailNavigator = useScopedPaneNavigator( screens, SuspenseContainer, detailRootKey ); // Second column: the middle/list navigator. const middleNavigator = useScopedPaneNavigator( screens, SuspenseContainer, middleRootKey ); const paneGoBack = React.useCallback( (n = 1) => { const stack = selectionStackRef.current; const data: any = mainNavigator.stateContext.data ?? {}; const selectedKey = detailParam && data[detailParam] != null ? detailParam : sectionParam && data[sectionParam] != null ? sectionParam : undefined; const action = resolvePaneBackAction( urlDriven ? stack.length : 0, n, Platform.OS === 'web' && typeof window !== 'undefined', Boolean(urlDriven && selectedKey) ); if (action.type === 'browser') { if (stepPaneDrillBack(detailNavigator, action.distance)) { window.history.go(-action.distance); } return; } if (action.type === 'deselect') { const next: any = { ...data }; delete next[selectedKey as string]; selectionStackRef.current.pop(); mainNavigator.refresh(next, 'replace'); return; } // Native has no browser timeline to consume. Keep its synchronous pane // refresh so nested detail Back stays inside the three-column workspace. if (action.type === 'selection') { if (!urlDriven) { return; } const target = stack[action.targetIndex]!; const next: any = { ...(mainNavigator.stateContext.data ?? {}) }; for (const key of [sectionParam, detailParam]) { if (!key) continue; if (target[key] != null) { next[key] = target[key]; } else { delete next[key]; } } mainNavigator.refresh(next, 'replace'); return; } if (mainNavigator.canNavigateBack(action.distance)) { mainNavigator.navigateBack(action.distance); } }, [mainNavigator, urlDriven, sectionParam, detailParam, detailNavigator] ); // Report the current selection (both columns) as stable screen paths + params // so the host can mirror it into the URL. A column showing its placeholder // (navigator at its root, no `screen`) reports null. const onSelectionChangeRef = useLatest(onSelectionChange); const reportSelection = React.useCallback(() => { const report = onSelectionChangeRef.current; if (!report) { return; } const toEntry = (nav: StateNavigator): TripleSelectionEntry | null => { const state: any = nav.stateContext.state; return state?.screen?.path ? { path: state.screen.path, params: nav.stateContext.data } : null; }; report({ middle: toEntry(middleNavigator), detail: toEntry(detailNavigator), }); }, [onSelectionChangeRef, middleNavigator, detailNavigator]); // Selecting a new middle section clears the detail column back to its // placeholder (iPad Mail: switching mailbox empties the message pane). const resetDetail = React.useCallback(() => { detailNavigator.navigate(detailRootKey); }, [detailNavigator, detailRootKey]); const onMiddleSelected = React.useCallback(() => { resetDetail(); reportSelection(); }, [resetDetail, reportSelection]); // Encode a pane route key + params (what a row push carries) into the compact // href stored in the main URL, e.g. key `/user/:id` + {id:'42'} -> // `user/42`. Relative to the pane rootKey, so the reverse is just // `rootKey + '/' + href`. Mirrors SplitView's encodeSelectionHref. const encodeHref = React.useCallback( (rootKey: string, key: string, params?: any) => { const template = key.startsWith(rootKey + '/') ? key.slice(rootKey.length + 1) : key; return generatePath(template, params ?? {}); }, [] ); // Sidebar pushes select the middle column (and reset detail); middle-column // pushes select the detail column. // // With `sectionParam`/`detailParam`, that selection instead flows through the // MAIN navigator: a row push records the selection as a query param on the // current main URL, and the pane is re-derived from that URL by the effect // below. Peer selections replace by default; selectionHistory="push" makes // them separate entries. Either way the panes never drive themselves out of // sync with the single URL timeline. Unset params keep the original // history-less behaviour. const sectionApplyIntentRef = React.useRef(null); const detailApplyIntentRef = React.useRef(null); const sidebarSelect = React.useMemo(() => { const selectViaUrl = ( key: string, params?: any, historyAction?: 'add' | 'replace' | 'none' ) => { sectionApplyIntentRef.current = 'replace'; const href = encodeHref(middleRootKey, key, params); const currentData = mainNavigator.stateContext.data ?? {}; const next: any = { ...currentData, [sectionParam as string]: href }; // Switching section clears any detail selection (iPad Mail behaviour). if (detailParam) { delete next[detailParam]; } const resolvedHistoryAction = resolveSelectionHistoryAction( historyAction, selectionHistory ); if (resolvedHistoryAction === 'replace') { selectionStackRef.current.pop(); } mainNavigator.refresh(next, resolvedHistoryAction); }; const selectLocal = (key: string, params?: any) => { const fluent = createHistorylessClone(middleNavigator) .fluent() .navigate(middleRootKey) .navigate(key, params); middleNavigator.navigateLink(fluent.url); onMiddleSelected(); }; return new Proxy(middleNavigator, { get(target: any, prop) { if (prop === paneNavigatorProxyKey) { return true; } if (prop === 'navigate') { return sectionParam ? selectViaUrl : selectLocal; } // In URL mode the selection lives on the MAIN navigator's history, so // in-app back (BackLink/pop) must step through that history — the panes // re-derive from the resulting URL. Popping the history-less pane would // be a no-op. if (sectionParam && prop === 'navigateBack') { return paneGoBack; } if (sectionParam && prop === 'canNavigateBack') { return () => paneCanGoBack(); } const value = target[prop]; return typeof value === 'function' ? value.bind(target) : value; }, }) as StateNavigator; }, [ middleNavigator, middleRootKey, sectionParam, detailParam, selectionHistory, mainNavigator, encodeHref, onMiddleSelected, paneGoBack, paneCanGoBack, ]); // Master (middle→detail) REPLACE vs detail-internal STACK intents, same as // SplitView: middle-column row taps replace the detail; a push from inside // the detail stacks a sub-form on top while still recording a URL entry. const middleSelect = React.useMemo(() => { const selectViaUrl = ( key: string, params?: any, historyAction?: 'add' | 'replace' | 'none' ) => { detailApplyIntentRef.current = 'replace'; const href = encodeHref(detailRootKey, key, params); const currentData = mainNavigator.stateContext.data ?? {}; const resolvedHistoryAction = resolveSelectionHistoryAction( historyAction, selectionHistory ); if (resolvedHistoryAction === 'replace') { selectionStackRef.current.pop(); } mainNavigator.refresh( { ...currentData, [detailParam as string]: href }, resolvedHistoryAction ); }; const selectLocal = (key: string, params?: any) => { const fluent = createHistorylessClone(detailNavigator) .fluent() .navigate(detailRootKey) .navigate(key, params); detailNavigator.navigateLink(fluent.url); reportSelection(); }; return new Proxy(detailNavigator, { get(target: any, prop) { if (prop === paneNavigatorProxyKey) { return true; } if (prop === 'navigate') { return detailParam ? selectViaUrl : selectLocal; } // URL mode: in-app back steps the MAIN navigator's history (which owns // the detail selection + any deeper drill), keeping Terug consistent // with browser Back. This proxy also backs the DETAIL column itself, so // a card push inside the detail (a sub-form) becomes a new `?detail=` // entry and Terug/back walks it back one level. if (detailParam && prop === 'navigateBack') { return paneGoBack; } if (detailParam && prop === 'canNavigateBack') { return () => paneCanGoBack(); } const value = target[prop]; return typeof value === 'function' ? value.bind(target) : value; }, }) as StateNavigator; }, [ detailNavigator, detailRootKey, detailParam, selectionHistory, mainNavigator, encodeHref, reportSelection, paneGoBack, paneCanGoBack, ]); // Detail-column proxy: drills STACK on top (URL + pane crumb trail). const detailStackSelect = React.useMemo(() => { const stackViaUrl = ( key: string, params?: any, historyAction?: 'add' | 'replace' | 'none' ) => { detailApplyIntentRef.current = historyAction === 'replace' ? 'replace' : 'push'; const href = encodeHref(detailRootKey, key, params); const currentData = mainNavigator.stateContext.data ?? {}; if (historyAction === 'replace') { selectionStackRef.current.pop(); } mainNavigator.refresh( { ...currentData, [detailParam as string]: href }, historyAction === 'replace' ? 'replace' : 'add' ); }; return new Proxy(detailNavigator, { get(target: any, prop) { if (prop === paneNavigatorProxyKey) { return true; } if (prop === 'navigate') { return detailParam ? stackViaUrl : (key: string, params?: any) => detailNavigator.navigate(key, params); } if (detailParam && prop === 'navigateBack') { return paneGoBack; } if (detailParam && prop === 'canNavigateBack') { return () => paneCanGoBack(); } const value = target[prop]; return typeof value === 'function' ? value.bind(target) : value; }, }) as StateNavigator; }, [ detailNavigator, detailRootKey, detailParam, mainNavigator, encodeHref, paneGoBack, paneCanGoBack, ]); // URL-mirror: when a param is set the corresponding pane is a pure function of // the main navigator's query. Re-derive whenever the main navigator navigates // (row tap -> refresh, browser Back/Forward, native back, deep-link/cold // load), so both selections live on the single main history timeline and are // deep-linkable. Mirrors SplitView's URL-mirror effect, applied per level. // // Detail drills STACK (navigate on top of the crumb trail) so sub-forms sit // on top of each other; middle-column row taps still REPLACE the detail. const appliedSectionRef = React.useRef(undefined); const appliedDetailRef = React.useRef(undefined); React.useEffect(() => { if (!urlDriven) { return undefined; } const replacePaneSelection = ( navigator: StateNavigator, rootKey: string, key: string, params?: any ) => { const fluent = createHistorylessClone(navigator) .fluent() .navigate(rootKey) .navigate(key, params); navigator.navigateLink(fluent.url); }; const hrefOfScene = (rootKey: string, state: any, data: any) => { if (!state?.key || state.key === rootKey) { return undefined; } return encodeHref(rootKey, state.key, data); }; const applyPane = ( navigator: StateNavigator, rootKey: string, href: string | undefined, intent: 'replace' | 'push' | null ) => { if (!href) { // No selection in the URL -> pane shows its placeholder. if (navigator.stateContext.state?.key !== rootKey) { navigator.navigate(rootKey); } return; } const targetUrl = rootKey + '/' + href; let parsed: { state?: any; data?: any } | null = null; try { parsed = navigator.parseLink(targetUrl); if ( shouldPreloadMirroredSelection(intent) && (parsed as any)?.state?.screen ) { preloadScreen((parsed as any).state.screen, (parsed as any).data); } } catch { // Unresolvable href (stale/foreign link) -> fall back to placeholder. navigator.navigate(rootKey); return; } if (!parsed?.state) { navigator.navigate(rootKey); return; } if (intent === 'push') { navigator.navigate(parsed.state.key, parsed.data); return; } if (intent == null) { const { crumbs, state, data } = navigator.stateContext; const scenes = [ ...crumbs.map((c) => ({ state: c.state, data: c.data })), ...(state ? [{ state, data }] : []), ]; let backDistance = -1; for (let i = scenes.length - 1; i >= 0; i -= 1) { if ( hrefOfScene(rootKey, scenes[i]!.state, scenes[i]!.data) === href ) { backDistance = scenes.length - 1 - i; break; } } if (backDistance === 0) { return; } if (backDistance > 0) { navigator.navigateBack(backDistance); return; } } replacePaneSelection(navigator, rootKey, parsed.state.key, parsed.data); }; const syncPanesFromUrl = () => { const data: any = mainNavigator.stateContext.data ?? {}; // Keep the selection-history stack in step with the URL. Every navigation // (row push, in-app back, browser Back/Forward, native back, deep link) // funnels through here, so reconciling against the applied stack keeps it // authoritative for `paneGoBack`: a snapshot already present below the top // means we moved back to it (truncate to it); a new snapshot is a push. const snap = selectionSnapshot(data, [sectionParam, detailParam]); const stack = selectionStackRef.current; const top = stack[stack.length - 1]; if (!top || !sameSelection(top, snap)) { let existing = -1; for (let i = stack.length - 1; i >= 0; i -= 1) { if (sameSelection(stack[i]!, snap)) { existing = i; break; } } if (existing === -1) { stack.push(snap); } else { stack.length = existing + 1; } } // Section first (it can empty the detail param), then detail on top. // Middle section selection always replaces (sidebar picks are peers). if (sectionParam) { const href: string | undefined = data[sectionParam]; if (appliedSectionRef.current !== href) { const intent = consumePaneApplyIntent(sectionApplyIntentRef); appliedSectionRef.current = href; applyPane(middleNavigator, middleRootKey, href, intent); } } if (detailParam) { const href: string | undefined = data[detailParam]; if (appliedDetailRef.current !== href) { const intent = consumePaneApplyIntent(detailApplyIntentRef); appliedDetailRef.current = href; applyPane(detailNavigator, detailRootKey, href, intent); } } }; // Initial derive (deep-link / cold load) + subscribe to future changes. syncPanesFromUrl(); mainNavigator.onNavigate(syncPanesFromUrl); return () => mainNavigator.offNavigate(syncPanesFromUrl); }, [ urlDriven, sectionParam, detailParam, mainNavigator, middleNavigator, detailNavigator, middleRootKey, detailRootKey, preloadScreen, encodeHref, ]); // Restore a deep-linked selection once, after the panes exist. Middle first // (which resets detail), then detail on top — mirroring the interactive // order — so a shared URL reopens exactly where it pointed. Skipped when // `sectionParam`/`detailParam` drive the panes from the URL instead. const didRestore = React.useRef(false); React.useEffect(() => { if (didRestore.current || !initialSelection || urlDriven) { return; } didRestore.current = true; const { middle, detail } = initialSelection; if (middle?.path) { sidebarSelect.navigate( rootKeyAndPaths(middleRootKey, middle.path), middle.params ); } if (detail?.path) { middleSelect.navigate( rootKeyAndPaths(detailRootKey, detail.path), detail.params ); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [initialSelection]); // Root maps so both scoped navigators resolve their placeholder root. const navigationRootWithPanes = React.useMemo( () => ({ [middleRootKey]: createNormalRoot({ path: middleRootKey, preload: () => {}, element: EmptyElement as any, }), [detailRootKey]: createNormalRoot({ path: detailRootKey, preload: () => {}, element: EmptyElement as any, }), ...navigationRoot, }), [navigationRoot, middleRootKey, detailRootKey] ); // Context for the SIDEBAR: its pushes go to the middle navigator. const sidebarRidgeValue = React.useMemo( () => ({ ...ridge, rootNavigator: middleNavigator, navigationRoot: navigationRootWithPanes, }), [ridge, middleNavigator, navigationRootWithPanes] ); const sidebarOptimizedValue = React.useMemo( () => ({ ...outerOptimized, rootNavigator: middleNavigator, stateNavigator: sidebarSelect, }), [outerOptimized, middleNavigator, sidebarSelect] ); // Context for the MIDDLE column screens: their pushes go to the detail nav. const middleRidgeValue = React.useMemo( () => ({ ...ridge, rootNavigator: detailNavigator, navigationRoot: navigationRootWithPanes, }), [ridge, detailNavigator, navigationRootWithPanes] ); const middleOptimizedValue = React.useMemo( () => ({ ...outerOptimized, rootNavigator: detailNavigator, stateNavigator: middleSelect, }), [outerOptimized, detailNavigator, middleSelect] ); // Android hardware back: pop detail first, then middle, then defer. React.useEffect(() => { if (Platform.OS !== 'android') { return undefined; } const subscription = BackHandler.addEventListener( 'hardwareBackPress', () => { // URL-driven mode: selections live on the MAIN navigator's history, so // step IT back (the panes re-derive from the URL). Popping the panes // directly would just be undone by the URL-mirror effect. if (urlDriven) { const data: any = mainNavigator.stateContext.data ?? {}; const hasSelection = (sectionParam && data[sectionParam] != null) || (detailParam && data[detailParam] != null); if (!hasSelection) { return false; } if (mainNavigator.canNavigateBack(1)) { mainNavigator.navigateBack(1); } else { // Only selection on the stack -> clear our params so back returns // to the empty/placeholder panes. const rest = { ...data }; if (sectionParam) { delete rest[sectionParam]; } if (detailParam) { delete rest[detailParam]; } mainNavigator.refresh(rest, 'replace'); } return true; } if (detailNavigator.canNavigateBack(1)) { detailNavigator.navigateBack(1); return true; } if (middleNavigator.canNavigateBack(1)) { middleNavigator.navigateBack(1); return true; } return false; } ); return () => subscription.remove(); }, [ detailNavigator, middleNavigator, urlDriven, sectionParam, detailParam, mainNavigator, ]); const renderMasterPlaceholder = () => masterPlaceholderRef.current ?? null; const renderDetailPlaceholder = () => detailPlaceholderRef.current ?? null; // Column 1 — sidebar. Floating (Health) = an absolute translucent overlay ON // TOP of the content so the color bleeds under it; otherwise a normal column. const sidebarNode = ( {children} ); return ( {/* Normal layout: sidebar reserves the leftmost column. Floating layout: the content spans from x=0 and the sidebar overlays it (rendered last, below). */} {!floatingSidebar && sidebarNode} {/* Column 2 — middle/list, whose pushes select the detail column. No NavigationHandler here on purpose: the middle scene stack is driven by the middleNavigator prop, and the Links inside must push through `middleSelect` (reset the detail column) — passed as linkNavigator so OptimizedContextProvider overrides the ambient stateNavigator. Wrapping this in a NavigationHandler(middleSelect) would fight the detail column's own NavigationHandler for ownership of detailNavigator and leave the middle showing only its placeholder. Mirrors how SplitView's master renders its children with no handler at all. */} {/* Master/middle: role=master so entity lists drop nested SplitViews and product headers suppress auto-Back on the list column. */} {/* Column 3 — detail. Wrapped in the pane ridge context (rootNavigator = detailNavigator, navigationRoot incl. the pane rootKeys) so pushes from INSIDE a detail screen (a sub-form card) resolve against the detail pane's own root instead of the main app root — without this they compute a screenKey the pane navigator has no state for and dead-click. Mirrors how SplitView wraps its detail in splitRidgeValue. JS scene stack on every platform (including web): NavigationMotion was unreliable for history-less pane navigators and did not stack drills on top of each other. PaneScenes keeps crumbs mounted. When `detailParam` is set, inner pushes route through `detailStackSelect`: each becomes a stacked pane scene + a new `?detail=` history entry (deep-linkable, Back/Terug one level). */} {/* Floating sidebar overlay, painted on top of the content. */} {floatingSidebar && sidebarNode} ); } /** Renders a history-less navigator's crumb stack as absolutely-stacked scenes * (top interactive). Used for the middle column and the detail column on every * platform (mirrors SplitView's DetailPaneScenes). */ function PaneScenes({ navigator, rootKey, renderPlaceholder, backgroundColor, linkNavigator, }: { navigator: StateNavigator; rootKey: string; renderPlaceholder: () => React.ReactNode; backgroundColor: any; /** When set, Links inside the rendered scenes push through this navigator * instead of the ambient NavigationContext one (used by the middle column so * its rows select the detail column). */ linkNavigator?: StateNavigator; }) { const [stateContext, setStateContext] = React.useState< StateNavigator['stateContext'] >(() => navigator.stateContext); React.useEffect(() => { const handler = () => setStateContext(navigator.stateContext); navigator.onNavigate(handler); return () => navigator.offNavigate(handler); }, [navigator]); const scenes = [ ...stateContext.crumbs.map((crumb) => ({ state: crumb.state, data: crumb.data, })), ...(stateContext.state ? [{ state: stateContext.state, data: stateContext.data }] : []), ]; return ( {scenes.map((scene, index) => { const isTop = index === scenes.length - 1; return ( {scene.state.key === rootKey ? renderPlaceholder() : scene.state.renderScene()} ); })} ); } function EmptyElement() { return null; } function createHistorylessClone(navigator: StateNavigator) { const clone = new StateNavigator(navigator); clone.historyManager.disabled = true; clone.historyManager.stop(); return clone; } const styles = StyleSheet.create({ root: { flex: 1, }, row: { flex: 1, flexDirection: 'row', }, paneScenes: { flex: 1, overflow: 'hidden', }, detail: { flex: 1, overflow: 'hidden', }, floatingSidebar: { position: 'absolute', left: 0, top: 0, bottom: 0, zIndex: 2, overflow: 'hidden', }, });