Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 54 additions & 36 deletions web/src/components/FinancialAidModule.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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<Record<number, boolean>>({})
Expand All @@ -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 })}
/>
)
}
Expand Down Expand Up @@ -785,25 +787,21 @@ const TaskBox = ({ done }: { done: boolean }) => (
</span>
)

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<string | null>(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<ScholarshipSort>('deadline')
const [filter, setFilter] = useState<StageKey | null>(null)
const [adding, setAdding] = useState(false)
Expand Down Expand Up @@ -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}
</div>
Expand Down Expand Up @@ -970,7 +968,7 @@ const ScholarshipsTab = ({ api, aid, ownDates, gradeStartIdx, initialOpenId, onF

{nextItem && (
<button
onClick={() => setOpenId(nextItem.id)}
onClick={() => onOpenId(nextItem.id)}
className="ast-card"
aria-label={`Next up: ${nextItem.name}, ${nextItem.dateDisplay}`}
style={{ flex: '0 1 280px', minWidth: 230, display: 'flex', flexDirection: 'column', gap: 8, padding: '12px 14px', background: nextUrgent ? `${nextUrgent}0D` : C.surface, border: `1px solid ${nextUrgent ? `${nextUrgent}40` : C.border}`, borderRadius: 12, cursor: 'pointer', textAlign: 'left' }}
Expand Down Expand Up @@ -1053,7 +1051,7 @@ const ScholarshipsTab = ({ api, aid, ownDates, gradeStartIdx, initialOpenId, onF
const urgent = urgencyColor(days)
const open = isOpenStatus(item.status)
const dateKind = open && !event ? scholarshipDeadlineState(item).kind : null
const openRow = () => setOpenId(item.id)
const openRow = () => onOpenId(item.id)
return (
// A div, not a button: the date cue inside holds an input.
<div
Expand Down Expand Up @@ -2143,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<HTMLDivElement>(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.
Expand All @@ -2152,23 +2156,27 @@ export default function FinancialAidModule({ open, onClose, year = 11, aside }:
// id in Scholarships 101's reader, where indexOf is -1, the header reads
// "0 of 6" and both prev and next vanish. Articles all live here since #89.
const article = tab === 'scholarships-101' && routedPage && CHECKLIST_ALL_IDS.includes(routedPage) ? routedPage : null
// A tracked scholarship to open straight onto when switching to Aid Tracker
// (from the Scholarship Engine's strip). Any other tab change clears it.
const [openItem, setOpenItem] = useState<string | null>(null)
// Aid Tracker's open scholarship is routed too. Unlike the Engine's scored
// object it is a bare id resolved against the tracked list, so the URL can
// 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.
// A scholarship 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 those two
// tabs close their detail on this instead of routing it like the articles.
// 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
// on this instead of routing like everything else.
const [navSignal, setNavSignal] = useState(0)
const switchTab = useCallback((t: TabId) => { setNavSignal((n) => n + 1); setOpenItem(null); setTab(t) }, [setTab])
const switchTab = useCallback((t: TabId) => { setNavSignal((n) => n + 1); setTab(t) }, [setTab])
// Reopens on Overview rather than wherever it was left. The module
// stays mounted while closed, so the tab would otherwise survive from a
// visit the student no longer remembers. Adjusted on the open transition,
// not in an effect, so the first paint is already the right tab.
const [wasOpen, setWasOpen] = useState(open)
if (open !== wasOpen) {
setWasOpen(open)
if (open) { setTab(routedTab('Financial Aid', FA_TAB_IDS) ?? 'overview'); setPage(routedItem('Financial Aid', FA_TAB_IDS)); setOpenItem(null) } // a tab in the URL wins
if (open) { setTab(routedTab('Financial Aid', FA_TAB_IDS) ?? 'overview'); setPage(routedItem('Financial Aid', FA_TAB_IDS)) } // a tab in the URL wins
}
const [progress, setProgress] = useState<ChecklistProgressMap>({})
const [progressError, setProgressError] = useState<string | null>(null)
Expand Down Expand Up @@ -2417,7 +2425,17 @@ export default function FinancialAidModule({ open, onClose, year = 11, aside }:
if (!(await saveShared(next))) toast.error('Could not save that — try again')
},
}
const openTracked = (id: string | null) => { setTab('scholarships'); setOpenItem(id) }
const openTracked = (id: string | null) => { setTab('scholarships'); setPage(id) }
// 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
? tracker.find((i) => i.id === scholarship)?.name
: undefined
// Routed, so the article it opens has the same exits as any other.
const read101 = (id: string) => { setTab('scholarships-101'); setPage(id) }
const saveAidPrefsOrSay = async (p: AidPrefs) => {
Expand All @@ -2429,7 +2447,7 @@ export default function FinancialAidModule({ open, onClose, year = 11, aside }:
const content =
tab === 'overview' ? <OverviewTab year={year} aside={aside} homeState={stateFromZip(userDemographics?.zipcode)} aid={aidColleges} onGoToTab={switchTab} onRead={read101} ownDates={ownDates} gradeStartIdx={profile?.grade_start_idx} /> :
tab === 'scholarships-101' ? <Scholarships101Tab progress={progress} onToggle={handleToggleChecklist} activeId={article} onOpenContent={setPage} /> :
tab === 'scholarships' ? <ScholarshipsTab key={openItem ?? ''} navSignal={navSignal} api={trackerApi} aid={aidColleges} ownDates={ownDates} gradeStartIdx={profile?.grade_start_idx} initialOpenId={openItem} onFindScholarships={() => switchTab('scholarship-search')} /> :
tab === 'scholarships' ? <ScholarshipsTab api={trackerApi} aid={aidColleges} ownDates={ownDates} gradeStartIdx={profile?.grade_start_idx} openId={scholarship} onOpenId={setPage} onFindScholarships={() => switchTab('scholarship-search')} /> :
<AidEngineTab navSignal={navSignal} api={trackerApi} userDemoTags={userDemoTags} userDemographics={userDemographics} prefs={aidPrefs} prefsLoaded={aidPrefsLoaded} onSavePrefs={(p) => void saveAidPrefsOrSay(p)} dismissals={dismissals} onOpenTracked={openTracked} year={year} />

return (
Expand All @@ -2450,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 && <>
<span style={{ fontFamily: "'Outfit',sans-serif", fontSize: 13, color: C.textFaint }}>·</span>
{article
? <button onClick={() => setPage(null)} style={{ fontFamily: "'Outfit',sans-serif", fontSize: 13, color: C.textMuted, background: 'none', border: 'none', cursor: 'pointer', padding: 0, whiteSpace: 'nowrap' }}>{FA_TABS.find((t) => t.id === tab)?.label}</button>
{openPage
? <button onClick={() => setPage(null)} style={{ fontFamily: "'Outfit',sans-serif", fontSize: 13, color: C.textMuted, background: 'none', border: 'none', cursor: 'pointer', padding: 0 }}>{FA_TABS.find((t) => t.id === tab)?.label}</button>
: <span style={{ fontFamily: "'Outfit',sans-serif", fontSize: 13, color: C.textMuted }}>{FA_TABS.find((t) => t.id === tab)?.label}</span>}
{article && <>
{openPage && pageTitle && <>
<span style={{ color: C.textFaint }}>/</span>
<span style={{ fontFamily: "'Outfit',sans-serif", fontSize: 13, color: C.text, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' }}>{CHECKLIST_CONTENT_MAP[article]?.title}</span>
<span style={{ fontFamily: "'Outfit',sans-serif", fontSize: 13, color: C.text, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis' }}>{pageTitle}</span>
</>}
</>}
<ModuleHeaderEnd year={year} onClose={onClose} />
Expand Down Expand Up @@ -2500,14 +2518,14 @@ export default function FinancialAidModule({ open, onClose, year = 11, aside }:

{/* Full-width content */}
<div style={{ position: 'relative', flex: 1, overflow: 'hidden' }}>
<div key={`${tab}/${article ?? ''}`} data-tour="content" style={{ height: '100%', overflowY: 'auto' }}>{content}</div>
<div ref={contentRef} key={tab} data-tour="content" style={{ height: '100%', overflowY: 'auto' }}>{content}</div>
</div>
</>
) : (
<div style={{ display: 'flex', flex: 1, overflow: 'hidden' }}>
<ModuleTabNav active={tab} onTab={switchTab} progress={progress} totalItems={CHECKLIST_TOTAL_ITEMS} accent={MC} title="Financial Aid" subtitle="Scholarship Hunt" tabs={FA_TABS} onTour={() => setShowTour(true)} />
<div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>
<div key={`${tab}/${article ?? ''}`} className="mov-scroll" data-tour="content" style={{ flex: 1, overflowY: 'auto' }}>{content}</div>
<div ref={contentRef} key={tab} className="mov-scroll" data-tour="content" style={{ flex: 1, overflowY: 'auto' }}>{content}</div>
</div>
</div>
)}
Expand Down
6 changes: 4 additions & 2 deletions web/src/components/ModuleOverviewTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ interface Props<T extends string> {
/** 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
}
Expand Down Expand Up @@ -92,7 +94,7 @@ export default function ModuleOverviewTab<T extends string>({
backLabel={backLabel}
onBack={() => onOpenContent(null)}
onMarkComplete={onMarkComplete}
onNavigate={onOpenContent}
onNavigate={(id) => onOpenContent(id, { replace: true })}
/>
)
}
Expand Down
23 changes: 19 additions & 4 deletions web/src/components/moduleReaderNav.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, ChecklistContent> = {
'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
Expand All @@ -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 <div>closed</div>
return (
<div>
<div data-testid="sidebar"><ModuleTabNav active={tab} onTab={setTab} progress={{}} totalItems={1} accent="#333" title="M" subtitle="S" tabs={TABS} /></div>
<div data-testid="sidebar"><ModuleTabNav active={tab} onTab={setTab} progress={{}} totalItems={2} accent="#333" title="M" subtitle="S" tabs={TABS} /></div>
{tab === 'overview'
? <ModuleOverviewTab
progress={{}} onToggle={vi.fn()} onMarkComplete={vi.fn()}
checklist={CHECKLIST} contentMap={CONTENT} allIds={['a-1']} totalItems={1}
checklist={CHECKLIST} contentMap={CONTENT} allIds={['a-1', 'a-2']} totalItems={2}
accent="#333" title="Overview" subtitle="sub"
itemTypeIcon={{ article: null }}
activeContentId={article} onOpenContent={setPage}
Expand Down Expand Up @@ -108,6 +112,17 @@ describe('leaving a checklist article', () => {
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')
Expand Down
27 changes: 27 additions & 0 deletions web/src/lib/hashRoute.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
Loading
Loading