diff --git a/web/src/components/FinancialAidModule.tsx b/web/src/components/FinancialAidModule.tsx index 4046d00..be38b0e 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,21 @@ 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 + /** `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 }) => { - 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 +904,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, { replace: true }); api.remove(openItem.id) }} /> {confetti} @@ -970,7 +968,7 @@ const ScholarshipsTab = ({ api, aid, ownDates, gradeStartIdx, initialOpenId, onF {nextItem && ( + {openPage + ? : {FA_TABS.find((t) => t.id === tab)?.label}} - {article && <> + {openPage && pageTitle && <> / - {CHECKLIST_CONTENT_MAP[article]?.title} + {pageTitle} } } @@ -2500,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/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..6b3d6f0 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,15 +47,15 @@ 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 (
-
+
{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..b6a78a6 100644 --- a/web/src/lib/hashRoute.test.ts +++ b/web/src/lib/hashRoute.test.ts @@ -117,6 +117,33 @@ 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('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 4c00e68..71918e7 100644 --- a/web/src/lib/hashRoute.ts +++ b/web/src/lib/hashRoute.ts @@ -46,10 +46,24 @@ 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) { + // 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) + return + } window.location.hash = next } @@ -87,17 +101,32 @@ 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) }, []) + // 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 }) - }, [open, tab, item, moduleKey, fallback]) + if (r.module === moduleKey && (r.tab !== tab || r.item !== item) && !(r.tab == null && tab === fallback && item == null)) { + writeRoute({ ...r, tab, item }, page.replace) + } + }, [open, tab, item, page, moduleKey, fallback]) useEffect(() => { if (!open) return // Back or forward within this module: its tab, or the default when the @@ -105,10 +134,10 @@ 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) }, [open, moduleKey, valid, fallback]) - return [tab, setTab, item, setItem] + return [tab, setTab, item, setRoutedItem] }