From ee27cb85ff20b02ecd18d9f6190a79ded68f2fc0 Mon Sep 17 00:00:00 2001 From: Danial Beg Date: Sun, 1 Nov 2026 17:54:50 -0800 Subject: [PATCH 1/2] Route Aid Tracker's scholarship, and stop prev/next filling history MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two follow-ups from the review of #90. Aid Tracker's open scholarship was closed by a counter the module bumped on every sidebar click, because the Engine's detail next to it is a scored object out of a paginated in-memory list that an id could not rebuild. That reasoning never applied to Aid Tracker: it holds a bare id and resolves it against the tracked list, so it can be routed like the articles. It now is. That gives it the exits it was missing — a breadcrumb that names it and goes back, the browser's Back, and a refresh that keeps it — and leaves the counter needed in one place rather than two. It also removes the bespoke mechanism rather than testing it. Aid Tracker now leaves on exactly the behaviour hashRoute already covers: picking a tab clears the open page, including the tab already active. Paging through articles with prev/next wrote a history entry each, so reading Scholarships 101 end to end buried the way out under eighteen of them and Back walked back article by article instead of leaving the module. writeRoute takes a `replace`, useRoutedTab's item setter takes `{ replace: true }`, and the readers pass it for prev/next only — a step inside a page rather than a move to a new one. Opening and closing still push, because those are places you can reasonably come back to. replaceState fires no hashchange, and that event is how a module hears about a route it did not write itself, so writeRoute dispatches one. --- web/src/components/FinancialAidModule.tsx | 75 +++++++++++---------- web/src/components/ModuleOverviewTab.tsx | 6 +- web/src/components/moduleReaderNav.test.tsx | 21 +++++- web/src/lib/hashRoute.test.ts | 15 +++++ web/src/lib/hashRoute.ts | 35 ++++++++-- 5 files changed, 106 insertions(+), 46 deletions(-) diff --git a/web/src/components/FinancialAidModule.tsx b/web/src/components/FinancialAidModule.tsx index 4046d00..9ef9efd 100644 --- a/web/src/components/FinancialAidModule.tsx +++ b/web/src/components/FinancialAidModule.tsx @@ -294,12 +294,14 @@ function useChecklistReader( progress: ChecklistProgressMap, onToggle: (itemId: string) => void, activeId: string | null, - setActiveId: (itemId: string | null) => void, + setActiveId: (itemId: string | null, opts?: { replace?: boolean }) => void, ) { const statusOf = (id: string): ChecklistItemStatus => progress[id] ?? 'available' - const open = (itemId: string) => { + // `replace` for prev/next inside the reader: a step within the page, not a + // move to a new one, so it should not cost a history entry. + const open = (itemId: string, opts?: { replace?: boolean }) => { if (statusOf(itemId) === 'available') onToggle(itemId) - setActiveId(itemId) + setActiveId(itemId, opts) } const markComplete = (itemId: string) => { onToggle(itemId) @@ -339,7 +341,7 @@ export const Scholarships101Tab = ({ progress, onToggle, activeId, onOpenContent onToggle: (itemId: string) => void /** The article being read, owned by the module so the sidebar can leave it. */ activeId: string | null - onOpenContent: (itemId: string | null) => void + onOpenContent: (itemId: string | null, opts?: { replace?: boolean }) => void }) => { const reader = useChecklistReader(progress, onToggle, activeId, onOpenContent) const [expanded, setExpanded] = useState>({}) @@ -354,7 +356,7 @@ export const Scholarships101Tab = ({ progress, onToggle, activeId, onOpenContent backLabel="Back to Scholarships 101" onBack={() => reader.setActiveId(null)} onMarkComplete={reader.markComplete} - onNavigate={reader.open} + onNavigate={(id) => reader.open(id, { replace: true })} /> ) } @@ -785,25 +787,19 @@ const TaskBox = ({ done }: { done: boolean }) => ( ) -const ScholarshipsTab = ({ api, aid, ownDates, gradeStartIdx, initialOpenId, onFindScholarships, navSignal }: { - navSignal: number +const ScholarshipsTab = ({ api, aid, ownDates, gradeStartIdx, openId, onOpenId, onFindScholarships }: { api: TrackerApi /** The student's schools, for the FAFSA and CSS Profile boxes on top. */ aid: AidCollegesState ownDates: OwnAidDates gradeStartIdx: number | null | undefined - /** Open straight onto this scholarship's page (from the Scholarship Engine's strip). */ - initialOpenId: string | null + /** The open scholarship's page, owned by the module and kept in the URL, so + * the sidebar, the breadcrumb and Back can all leave it. */ + openId: string | null + onOpenId: (id: string | null) => void /** Go to the Scholarship Engine, where scholarships are found. */ onFindScholarships: () => void }) => { - const [openId, setOpenId] = useState(initialOpenId) - // A sidebar click leaves the scholarship's page, even a click on the tab it - // is already on. Adjusted during render rather than in an effect, as the - // module does with `wasOpen`: starting level with navSignal also means the - // page this tab was opened straight onto is not closed on arrival. - const [seenNav, setSeenNav] = useState(navSignal) - if (navSignal !== seenNav) { setSeenNav(navSignal); setOpenId(null) } const [sort, setSort] = useState('deadline') const [filter, setFilter] = useState(null) const [adding, setAdding] = useState(false) @@ -906,12 +902,12 @@ const ScholarshipsTab = ({ api, aid, ownDates, gradeStartIdx, initialOpenId, onF sharedCounts={sharedCounts} event={eventFor.get(openItem.id) ?? null} daysLeft={daysFor(openItem)} - onBack={() => setOpenId(null)} + onBack={() => onOpenId(null)} onStatus={(s) => setStatus(openItem, s)} onTasks={(tasks) => setTasks(openItem, tasks)} onToggleShared={setShared} onUpdate={api.update} - onRemove={() => { setOpenId(null); api.remove(openItem.id) }} + onRemove={() => { onOpenId(null); api.remove(openItem.id) }} /> {confetti} @@ -970,7 +966,7 @@ const ScholarshipsTab = ({ api, aid, ownDates, gradeStartIdx, initialOpenId, onF {nextItem && ( : {FA_TABS.find((t) => t.id === tab)?.label}} - {article && <> + {pageTitle && <> / - {CHECKLIST_CONTENT_MAP[article]?.title} + {pageTitle} } } @@ -2500,14 +2505,14 @@ export default function FinancialAidModule({ open, onClose, year = 11, aside }: {/* Full-width content */}
-
{content}
+
{content}
) : (
setShowTour(true)} />
-
{content}
+
{content}
)} diff --git a/web/src/components/ModuleOverviewTab.tsx b/web/src/components/ModuleOverviewTab.tsx index 284d05d..70052f9 100644 --- a/web/src/components/ModuleOverviewTab.tsx +++ b/web/src/components/ModuleOverviewTab.tsx @@ -51,7 +51,9 @@ interface Props { /** The checklist item being read, or null for the list. Owned by the module * so the sidebar, the breadcrumb and the browser's Back can all leave it. */ activeContentId: string | null - onOpenContent: (itemId: string | null) => void + /** `replace` for a step within the reader (prev/next), so paging through + * articles does not bury the way out under one history entry each. */ + onOpenContent: (itemId: string | null, opts?: { replace?: boolean }) => void /** Back's label in the article reader, when this isn't the Overview tab. */ backLabel?: string } @@ -92,7 +94,7 @@ export default function ModuleOverviewTab({ backLabel={backLabel} onBack={() => onOpenContent(null)} onMarkComplete={onMarkComplete} - onNavigate={onOpenContent} + onNavigate={(id) => onOpenContent(id, { replace: true })} /> ) } diff --git a/web/src/components/moduleReaderNav.test.tsx b/web/src/components/moduleReaderNav.test.tsx index 243deda..2d23745 100644 --- a/web/src/components/moduleReaderNav.test.tsx +++ b/web/src/components/moduleReaderNav.test.tsx @@ -27,9 +27,13 @@ const TABS = [ { id: 'other' as const, label: 'Other', icon: MODULE_ICONS.article }, ] const VALID = ['overview', 'other'] as const -const CHECKLIST = [{ title: 'Section', items: [{ id: 'a-1', label: 'How to read this', type: 'article' as const }] }] +const CHECKLIST = [{ title: 'Section', items: [ + { id: 'a-1', label: 'How to read this', type: 'article' as const }, + { id: 'a-2', label: 'And then this', type: 'article' as const }, +] }] const CONTENT: Record = { 'a-1': { id: 'a-1', title: 'How to read this', type: 'article', body: [{ kind: 'paragraph', text: 'Body text.' }] }, + 'a-2': { id: 'a-2', title: 'And then this', type: 'article', body: [{ kind: 'paragraph', text: 'Second body.' }] }, } /** The wiring every module uses: the open page lives in the route under its @@ -43,7 +47,7 @@ const Harness = ({ open = true }: { open?: boolean }) => { setWasOpen(open) if (open) { setTab(routedTab('Application Tracking', VALID) ?? 'overview'); setPage(routedItem('Application Tracking', VALID)) } } - const article = tab === 'overview' && routedPage && ['a-1'].includes(routedPage) ? routedPage : null + const article = tab === 'overview' && routedPage && ['a-1', 'a-2'].includes(routedPage) ? routedPage : null if (!open) return
closed
return (
@@ -51,7 +55,7 @@ const Harness = ({ open = true }: { open?: boolean }) => { {tab === 'overview' ? { expect(screen.queryByText('Body text.')).not.toBeInTheDocument() }) + it('pages on with next without burying the way out in history', async () => { + const user = userEvent.setup() + await openArticle() + const afterOpen = window.history.length + await user.click(screen.getByRole('button', { name: /And then this/ })) + expect(screen.getByText('Second body.')).toBeInTheDocument() + // Reading on is a step inside the reader, not a new place to come back to. + expect(window.history.length).toBe(afterOpen) + expect(window.location.hash).toBe('#/dashboard/application-tracking/overview/a-2') + }) + it('puts the article in the URL, so Back leaves it too', async () => { await openArticle() expect(window.location.hash).toBe('#/dashboard/application-tracking/overview/a-1') diff --git a/web/src/lib/hashRoute.test.ts b/web/src/lib/hashRoute.test.ts index 49a7866..0d55cb6 100644 --- a/web/src/lib/hashRoute.test.ts +++ b/web/src/lib/hashRoute.test.ts @@ -117,6 +117,21 @@ describe('useRoutedTab', () => { expect([result.current[0], result.current[2]]).toEqual(['discover', 'sr-5']) expect(window.location.hash).toBe('#/dashboard/application-tracking/discover/sr-5') }) + it('replaces rather than pushes when asked, so a step inside a page costs no entry', () => { + window.location.hash = '#/dashboard/application-tracking' + const { result } = renderHook(() => useRoutedTab('Application Tracking', true, TABS, 'status')) + act(() => { result.current[3]('sc-1') }) + const afterOpen = window.history.length + // Paging on: the same page, a different item. Pushing here is what made + // Back walk back item by item instead of leaving the module. + act(() => { result.current[3]('sc-2', { replace: true }) }) + expect(window.history.length).toBe(afterOpen) + expect(window.location.hash).toBe('#/dashboard/application-tracking/status/sc-2') + expect(result.current[2]).toBe('sc-2') + // Without it, a move to a new page still earns its entry. + act(() => { result.current[3]('sc-3') }) + expect(window.history.length).toBe(afterOpen + 1) + }) it('opens on the school in the URL', () => { window.location.hash = '#/dashboard/application-tracking/status/sc-1' expect(renderHook(() => useRoutedTab('Application Tracking', true, TABS, 'status')).result.current[2]).toBe('sc-1') diff --git a/web/src/lib/hashRoute.ts b/web/src/lib/hashRoute.ts index 4c00e68..0fcc0b0 100644 --- a/web/src/lib/hashRoute.ts +++ b/web/src/lib/hashRoute.ts @@ -8,7 +8,7 @@ * Only hashes starting with `#/` are ours: Supabase's sign-in and recovery * tokens also live in the hash, and are never touched. */ -import { useCallback, useEffect, useState } from 'react' +import { useCallback, useEffect, useRef, useState } from 'react' import { moduleEnabled } from './features' const PAGES = ['dashboard', 'timeline', 'calendar', 'profile', 'settings'] as const @@ -46,10 +46,23 @@ export function formatRoute({ page, module, tab, item }: Route): string { return `#/${page}${module ? `/${slug(module)}${tab ? `/${tab}${item ? `/${item}` : ''}` : ''}` : ''}` } -/** Write the route, adding a history entry. Leaves a hash that isn't ours alone. */ -export function writeRoute(route: Route): void { +/** + * Write the route. Adds a history entry by default; `replace` swaps the + * current one instead, for a move that is a step *within* a page rather than + * a move to a new one. Paging through articles with prev/next is the case + * that needs it: pushing there made Back walk back article by article instead + * of leaving the module. Leaves a hash that isn't ours alone. + */ +export function writeRoute(route: Route, replace = false): void { const next = formatRoute(route) if (window.location.hash === next || !ours(window.location.hash)) return + if (replace) { + window.history.replaceState(window.history.state, '', window.location.pathname + window.location.search + next) + // replaceState fires no hashchange, and the listener is how a module hears + // about a route it did not write itself. + window.dispatchEvent(new HashChangeEvent('hashchange')) + return + } window.location.hash = next } @@ -87,16 +100,26 @@ export function useRoutedTab( open: boolean, valid: readonly T[], fallback: T, -): [T, (t: T) => void, string | null, (item: string | null) => void] { +): [T, (t: T) => void, string | null, (item: string | null, opts?: { replace?: boolean }) => void] { const [tab, setTabOnly] = useState(() => (open && routedTab(moduleKey, valid)) || fallback) const [item, setItem] = useState(() => (open ? routedItem(moduleKey, valid) : null)) const setTab = useCallback((t: T) => { setTabOnly(t); setItem(null) }, []) + // Read and cleared by the write effect below. A ref rather than state so + // asking for a replace does not itself cause a render. + const replaceNext = useRef(false) + const setRoutedItem = useCallback((i: string | null, opts?: { replace?: boolean }) => { + replaceNext.current = opts?.replace ?? false + setItem(i) + }, []) useEffect(() => { if (!open) return const r = readRoute() // The default tab right after opening stays implied, or Back would need an // extra press to leave a tab nobody picked. - if (r.module === moduleKey && (r.tab !== tab || r.item !== item) && !(r.tab == null && tab === fallback && item == null)) writeRoute({ ...r, tab, item }) + if (r.module === moduleKey && (r.tab !== tab || r.item !== item) && !(r.tab == null && tab === fallback && item == null)) { + writeRoute({ ...r, tab, item }, replaceNext.current) + } + replaceNext.current = false }, [open, tab, item, moduleKey, fallback]) useEffect(() => { if (!open) return @@ -110,5 +133,5 @@ export function useRoutedTab( window.addEventListener('hashchange', onHash) return () => window.removeEventListener('hashchange', onHash) }, [open, moduleKey, valid, fallback]) - return [tab, setTab, item, setItem] + return [tab, setTab, item, setRoutedItem] } From a7a03f9446630703cbcc2c10bd1390962ebca2dc Mon Sep 17 00:00:00 2001 From: Danial Beg Date: Sun, 1 Nov 2026 18:26:59 -0800 Subject: [PATCH 2/2] Fix the review's findings on the follow-ups MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The replace intent was a ref the write effect cleared, and React can skip the set that arms it — asking to replace with the value already held is a no-op, so the effect never ran and the intent survived. The next write by anyone, a tab change included, then replaced instead of pushing: the Back exit deleted by the thing meant to protect it. It now travels with the open page in one state value, so there is no set for React to skip, and nothing mutates a ref during render, which both modules were doing in their open transition. Widening the content wrapper's key to the open page reset the scroll by throwing the tab away. Aid Tracker lost its sort, its status filter and any half-filled add form every time a scholarship was opened or left, and its own scroll-to-top effect became unreachable, since each remount re-armed the first-render guard. ModuleShell already solves this for the other modules with a scrollTop effect and no remount; Financial Aid's hand-rolled shell now does the same and keys on the tab again. Removing a tracked scholarship closed its page with a push, so Back landed on the removed row's URL and did nothing visible — the list rendered, the URL still named a page, and it took two presses to leave. A dismissal is not a place to come back to, so it replaces. The breadcrumb's way back was gated on a resolved title. Articles read theirs from a static map, but a scholarship's name comes from the tracker fetch, so a refresh or a shared link had no exit until it landed and none at all when it failed. The exit now follows whether a page is open; the title only decides what it is called. Dropped the synthetic hashchange on a replace. The only two listeners are this hook's own, recomputing the state it just wrote, and the dashboard's, which reads page and module — neither of which a replace changes. It woke both for nothing, and now that the page state is a fresh object each set, waking this one costs a render. Known and left: an id the tracker cannot resolve leaves the URL naming a page while the list renders. Validating it against the tracked list would fight the async load and blank a deep link before it arrives; with the breadcrumb exit no longer tied to the title, the disagreement is cosmetic and recoverable. --- web/src/components/FinancialAidModule.tsx | 33 +++++++++++------ web/src/components/moduleReaderNav.test.tsx | 2 +- web/src/lib/hashRoute.test.ts | 12 +++++++ web/src/lib/hashRoute.ts | 40 ++++++++++++--------- 4 files changed, 59 insertions(+), 28 deletions(-) diff --git a/web/src/components/FinancialAidModule.tsx b/web/src/components/FinancialAidModule.tsx index 9ef9efd..be38b0e 100644 --- a/web/src/components/FinancialAidModule.tsx +++ b/web/src/components/FinancialAidModule.tsx @@ -796,7 +796,9 @@ const ScholarshipsTab = ({ api, aid, ownDates, gradeStartIdx, openId, onOpenId, /** The open scholarship's page, owned by the module and kept in the URL, so * the sidebar, the breadcrumb and Back can all leave it. */ openId: string | null - onOpenId: (id: string | null) => void + /** `replace` when the page is being dismissed rather than navigated away + * from, so Back does not land on a scholarship that no longer exists. */ + onOpenId: (id: string | null, opts?: { replace?: boolean }) => void /** Go to the Scholarship Engine, where scholarships are found. */ onFindScholarships: () => void }) => { @@ -907,7 +909,7 @@ const ScholarshipsTab = ({ api, aid, ownDates, gradeStartIdx, openId, onOpenId, onTasks={(tasks) => setTasks(openItem, tasks)} onToggleShared={setShared} onUpdate={api.update} - onRemove={() => { onOpenId(null); api.remove(openItem.id) }} + onRemove={() => { onOpenId(null, { replace: true }); api.remove(openItem.id) }} /> {confetti}
@@ -2139,6 +2141,12 @@ export default function FinancialAidModule({ open, onClose, year = 11, aside }: }, [open, tourSeen]) const isNarrow = useIsNarrow() + // Scrolled back to the top when the page within a tab changes, the way + // ModuleShell does it for the other modules. This used to be a React `key` + // on the wrapper, which reset the scroll by throwing the tab away — and with + // it Aid Tracker's sort, status filter and half-filled add form every time a + // scholarship was opened or left. + const contentRef = useRef(null) // Opens on Overview, as Application Tracking does. The article being read // lives in the URL under its tab, so the sidebar, the breadcrumb and Back // can all leave it. @@ -2153,6 +2161,8 @@ export default function FinancialAidModule({ open, onClose, year = 11, aside }: // rebuild it — which buys it the same exits the articles have and leaves the // counter below needed in one place rather than two. const scholarship = tab === 'scholarships' ? routedPage : null + const scrollKey = `${tab}/${routedPage ?? ''}` + useEffect(() => { if (contentRef.current) contentRef.current.scrollTop = 0 }, [scrollKey]) // Bumped on every sidebar click, including one on the tab already active. // The Engine's detail is a scored object out of a paginated in-memory list, // not something an id in the URL could rebuild after a refresh, so it closes @@ -2416,8 +2426,11 @@ export default function FinancialAidModule({ open, onClose, year = 11, aside }: }, } const openTracked = (id: string | null) => { setTab('scholarships'); setPage(id) } - // What the breadcrumb names, and what its tab label goes back to: an article - // in Scholarships 101, or a scholarship's page in Aid Tracker. + // Whether a page is open at all decides the way back; the title only decides + // what it is called. The tracker loads async, so tying the exit to a + // resolved name left a deep link with none until the fetch landed, and none + // at all when it failed. + const openPage = article ?? scholarship const pageTitle = article ? CHECKLIST_CONTENT_MAP[article]?.title : scholarship @@ -2455,12 +2468,12 @@ export default function FinancialAidModule({ open, onClose, year = 11, aside }: {/* On a phone the tab strip right below already says which tab. */} {!isNarrow && <> · - {pageTitle - ? + {openPage + ? : {FA_TABS.find((t) => t.id === tab)?.label}} - {pageTitle && <> + {openPage && pageTitle && <> / - {pageTitle} + {pageTitle} } } @@ -2505,14 +2518,14 @@ export default function FinancialAidModule({ open, onClose, year = 11, aside }: {/* Full-width content */}
-
{content}
+
{content}
) : (
setShowTour(true)} />
-
{content}
+
{content}
)} diff --git a/web/src/components/moduleReaderNav.test.tsx b/web/src/components/moduleReaderNav.test.tsx index 2d23745..6b3d6f0 100644 --- a/web/src/components/moduleReaderNav.test.tsx +++ b/web/src/components/moduleReaderNav.test.tsx @@ -51,7 +51,7 @@ const Harness = ({ open = true }: { open?: boolean }) => { if (!open) return
closed
return (
-
+
{tab === 'overview' ? { act(() => { result.current[3]('sc-3') }) expect(window.history.length).toBe(afterOpen + 1) }) + it('does not let a replace leak into the next write', () => { + // Asking to replace with the value already held is a no-op React skips, so + // anything carrying the intent outside state is never cleared and the next + // write silently replaces — deleting the Back exit this is meant to keep. + window.location.hash = '#/dashboard/application-tracking' + const { result } = renderHook(() => useRoutedTab('Application Tracking', true, TABS, 'status')) + act(() => { result.current[3]('sc-1') }) + act(() => { result.current[3]('sc-1', { replace: true }) }) // same value: React skips it + const before = window.history.length + act(() => { result.current[1]('discover') }) // a different writer: must push + expect(window.history.length).toBe(before + 1) + }) it('opens on the school in the URL', () => { window.location.hash = '#/dashboard/application-tracking/status/sc-1' expect(renderHook(() => useRoutedTab('Application Tracking', true, TABS, 'status')).result.current[2]).toBe('sc-1') diff --git a/web/src/lib/hashRoute.ts b/web/src/lib/hashRoute.ts index 0fcc0b0..71918e7 100644 --- a/web/src/lib/hashRoute.ts +++ b/web/src/lib/hashRoute.ts @@ -8,7 +8,7 @@ * Only hashes starting with `#/` are ours: Supabase's sign-in and recovery * tokens also live in the hash, and are never touched. */ -import { useCallback, useEffect, useRef, useState } from 'react' +import { useCallback, useEffect, useState } from 'react' import { moduleEnabled } from './features' const PAGES = ['dashboard', 'timeline', 'calendar', 'profile', 'settings'] as const @@ -57,10 +57,11 @@ export function writeRoute(route: Route, replace = false): void { const next = formatRoute(route) if (window.location.hash === next || !ours(window.location.hash)) return if (replace) { + // No synthetic hashchange to go with it. replaceState fires none, and the + // only two listeners are useRoutedTab's own — recomputing the state it + // just wrote — and the dashboard's, which reads page and module, neither + // of which a replace changes. Dispatching one woke both for nothing. window.history.replaceState(window.history.state, '', window.location.pathname + window.location.search + next) - // replaceState fires no hashchange, and the listener is how a module hears - // about a route it did not write itself. - window.dispatchEvent(new HashChangeEvent('hashchange')) return } window.location.hash = next @@ -102,25 +103,30 @@ export function useRoutedTab( fallback: T, ): [T, (t: T) => void, string | null, (item: string | null, opts?: { replace?: boolean }) => void] { const [tab, setTabOnly] = useState(() => (open && routedTab(moduleKey, valid)) || fallback) - const [item, setItem] = useState(() => (open ? routedItem(moduleKey, valid) : null)) - const setTab = useCallback((t: T) => { setTabOnly(t); setItem(null) }, []) - // Read and cleared by the write effect below. A ref rather than state so - // asking for a replace does not itself cause a render. - const replaceNext = useRef(false) - const setRoutedItem = useCallback((i: string | null, opts?: { replace?: boolean }) => { - replaceNext.current = opts?.replace ?? false - setItem(i) - }, []) + // The open page and how it should be written travel together. Carrying the + // replace intent outside this — in a ref cleared by the write effect — meant + // a set React skipped (the same value again) left the intent armed, and the + // next write by anyone, a tab change included, silently replaced instead of + // pushing: the Back exit deleted by the thing meant to protect it. Each set + // makes a new object, so there is no set for React to skip. + const [page, setPage] = useState<{ id: string | null; replace: boolean }>( + () => ({ id: open ? routedItem(moduleKey, valid) : null, replace: false }), + ) + const item = page.id + const setTab = useCallback((t: T) => { setTabOnly(t); setPage({ id: null, replace: false }) }, []) + const setRoutedItem = useCallback( + (i: string | null, opts?: { replace?: boolean }) => setPage({ id: i, replace: opts?.replace ?? false }), + [], + ) useEffect(() => { if (!open) return const r = readRoute() // The default tab right after opening stays implied, or Back would need an // extra press to leave a tab nobody picked. if (r.module === moduleKey && (r.tab !== tab || r.item !== item) && !(r.tab == null && tab === fallback && item == null)) { - writeRoute({ ...r, tab, item }, replaceNext.current) + writeRoute({ ...r, tab, item }, page.replace) } - replaceNext.current = false - }, [open, tab, item, moduleKey, fallback]) + }, [open, tab, item, page, moduleKey, fallback]) useEffect(() => { if (!open) return // Back or forward within this module: its tab, or the default when the @@ -128,7 +134,7 @@ export function useRoutedTab( const onHash = () => { if (readRoute().module !== moduleKey) return setTabOnly(routedTab(moduleKey, valid) ?? fallback) - setItem(routedItem(moduleKey, valid)) + setPage({ id: routedItem(moduleKey, valid), replace: false }) } window.addEventListener('hashchange', onHash) return () => window.removeEventListener('hashchange', onHash)