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
49 changes: 49 additions & 0 deletions src/viewer/app/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/// <reference types="bun" />
/// <reference types="node" />
/// <reference lib="esnext" />
// The page in the address: today's pages, the pages of the tree, the site map; never an account number or a group name
import { expect, test } from 'bun:test';
import { PAGES } from './pages';
import { MAIN_TABS } from './prefs';
import { REFERENCE_HASH, ROUTE_SCOPES, hashOf, hashToWrite, parseHash, tabOfHash, type Route } from './route';

test('today\'s seven pages have their own addresses, read back to the same page', () => {
expect(MAIN_TABS.map((tab) => hashOf({ kind: 'reference', tab }))).toEqual(['#fidelity-summary', '#fidelity-positions', '#fidelity-activity', '#fidelity-reports', '#fidelity-taxes', '#adp-summary', '#adp-activity']);
MAIN_TABS.forEach((tab) => expect(parseHash(hashOf({ kind: 'reference', tab }))).toEqual({ kind: 'reference', tab }));
});

test('the pages of the tree: #<page> or #<page>/<all|fidelity|adp>; #sitemap', () => {
PAGES.forEach((page) => {
expect(parseHash(`#${page}`)).toEqual({ kind: 'page', page, scope: null });
ROUTE_SCOPES.forEach((scope) => expect(parseHash(hashOf({ kind: 'page', page, scope }))).toEqual({ kind: 'page', page, scope }));
});
expect(hashOf({ kind: 'page', page: 'taxes', scope: 'adp' })).toBe('#taxes/adp');
expect(hashOf({ kind: 'page', page: 'summary', scope: null })).toBe('#summary');
expect(parseHash('#sitemap')).toEqual({ kind: 'sitemap' });
expect(hashOf({ kind: 'sitemap' })).toBe('#sitemap');
});

test('typed by hand: the case, a leading slash and spaces do not matter; anything else names no page', () => {
expect(parseHash('#ADP-Summary')).toEqual({ kind: 'reference', tab: 'adpSummary' });
expect(parseHash('#/positions/Fidelity')).toEqual({ kind: 'page', page: 'positions', scope: 'fidelity' });
expect(parseHash('# summary ')).toEqual({ kind: 'page', page: 'summary', scope: null });
['', '#', '#nope', '#summary/X10000001', '#summary/investment', '#summary/all/more', '#account:X10000001'].forEach((h) => expect(parseHash(h)).toBeNull());
});

test('an address holds only fixed words, never an account number or a group name', () => {
const routes: Route[] = MAIN_TABS.map((tab): Route => ({ kind: 'reference', tab }))
.concat(PAGES.flatMap((page) => [null, ...ROUTE_SCOPES].map((scope): Route => ({ kind: 'page', page, scope }))), [{ kind: 'sitemap' }]);
routes.forEach((r) => expect(hashOf(r)).toMatch(/^#[a-z]+(-[a-z]+)?(\/[a-z]+)?$/));
expect(Object.values(REFERENCE_HASH).every((h) => !/\d/.test(h))).toBe(true);
});

test('while today\'s pages are drawn, only their addresses choose a page; the saved page is written back', () => {
expect(tabOfHash('#adp-activity')).toBe('adpActivity');
expect(tabOfHash('#summary')).toBeNull();
expect(tabOfHash('#sitemap')).toBeNull();
expect(tabOfHash('')).toBeNull();
expect(hashToWrite('', 'summary')).toBe('#fidelity-summary');
expect(hashToWrite('#fidelity-summary', 'positions')).toBe('#fidelity-positions');
expect(hashToWrite('#adp-summary', 'adpSummary')).toBeNull();
expect(hashToWrite('#sitemap', 'taxes')).toBe('#fidelity-taxes');
});
63 changes: 63 additions & 0 deletions src/viewer/app/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/// <reference lib="esnext" />
// The page in the address (owner 2026-12-03, the scope tree plan: "a hash wins on load, a page click writes it"), so a page
// can be bookmarked and Back goes to the page before. Three kinds of address:
// - today's seven pages, kept forever as the addresses of the reference copies: #fidelity-summary ... #adp-activity
// - the pages of the scope tree: #<page> or #<page>/<all|fidelity|adp> (drawn once the tree takes over)
// - #sitemap, reserved for the site map of every page
// Never an account number or a group name: only these fixed words ever go into an address
import { PAGES, type Page } from './pages';
import type { MainTab } from './prefs';

/** the address of each page of today */
export const REFERENCE_HASH: Readonly<Record<MainTab, string>> = {
summary: 'fidelity-summary',
positions: 'fidelity-positions',
activity: 'fidelity-activity',
reports: 'fidelity-reports',
taxes: 'fidelity-taxes',
adpSummary: 'adp-summary',
adpActivity: 'adp-activity',
};
export const SITEMAP_HASH = 'sitemap';
export const ROUTE_SCOPES = ['all', 'fidelity', 'adp'] as const;
export type RouteScope = (typeof ROUTE_SCOPES)[number];

export type Route =
| { kind: 'reference'; tab: MainTab }
| { kind: 'page'; page: Page; scope: RouteScope | null }
| { kind: 'sitemap' };

/** an address -> the page it names; null for an empty or unknown one (the saved page stays) */
export function parseHash(hash: string): Route | null {
const h = decodeURIComponent(hash.replace(/^#\/?/, '')).trim().toLowerCase();
if (!h) return null;
if (h === SITEMAP_HASH) return { kind: 'sitemap' };
const tab = (Object.keys(REFERENCE_HASH) as MainTab[]).find((k) => REFERENCE_HASH[k] === h);
if (tab) return { kind: 'reference', tab };
const [page, scope, ...rest] = h.split('/');
if (rest.length || (PAGES as readonly string[]).indexOf(page!) < 0) return null;
if (scope === undefined) return { kind: 'page', page: page as Page, scope: null };
return (ROUTE_SCOPES as readonly string[]).indexOf(scope) >= 0 ? { kind: 'page', page: page as Page, scope: scope as RouteScope } : null;
}

/** a page -> its address, '#' first */
export function hashOf(route: Route): string {
if (route.kind === 'sitemap') return `#${SITEMAP_HASH}`;
if (route.kind === 'reference') return `#${REFERENCE_HASH[route.tab]}`;
return `#${route.page}${route.scope ? `/${route.scope}` : ''}`;
}

/**
* What the address does to the saved page while the app draws today's pages: the page of today it names, or null (none,
* unknown, or an address of a page that is not drawn yet: the saved page stays and the address follows it)
*/
export const tabOfHash = (hash: string): MainTab | null => {
const r = parseHash(hash);
return r && r.kind === 'reference' ? r.tab : null;
};

/** the address to write for the saved page, or null when the address already says it */
export function hashToWrite(current: string, tab: MainTab): string | null {
const want = hashOf({ kind: 'reference', tab });
return current === want ? null : want;
}
3 changes: 3 additions & 0 deletions src/viewer/ui/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import { Taxes } from './Taxes';
import { animate } from './animate';
import { readTime } from './format';
import { GutterScrollbars } from './GutterScrollbars';
import { useRoute } from './useRoute';
import { useStore } from './useStore';
import { useTheme } from './useTheme';
import { PHONE_QUERY, useMedia } from './useMedia';
Expand All @@ -60,6 +61,8 @@ export function App() {
// shown falls back to Summary
const taxYearsRead = taxYears(rawDs?.taxSummary).length > 0;
const tabs = useMemo(() => referenceTabs({ adp: !!adp, taxYears: taxYearsRead }), [adp, taxYearsRead]);
// the page in the address (app/route.ts): a hash wins on load, a page click writes it, so Back works
useRoute(pr.tab);
const openTab: MainTab = tabs.indexOf(pr.tab) >= 0 ? pr.tab : 'summary';
// the pages of the ADP 401k show its money sources in the strip, the rest the Fidelity accounts (app/pages.ts)
const adpPage = referenceSource(openTab) === 'adp';
Expand Down
55 changes: 55 additions & 0 deletions src/viewer/ui/use-route.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/// <reference types="bun" />
/// <reference types="node" />
/// <reference lib="esnext" />
// The page in the address with the app's own hook: the address wins on load, a page chosen later adds a history step,
// Back opens the page before
import { afterAll, beforeAll, expect, test } from 'bun:test';
import { GlobalRegistrator } from '@happy-dom/global-registrator';

beforeAll(() => {
GlobalRegistrator.register({ url: 'https://daggerok.github.io/accounts/#adp-summary' });
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
});
afterAll(() => GlobalRegistrator.unregister());

test('a hash wins on load, a tab click writes it, Back and a typed address open their page', async () => {
const { act } = await import('react');
const { createRoot } = await import('react-dom/client');
const { prefs, setPrefs } = await import('../app/prefs');
const { useStore } = await import('./useStore');
const { useRoute } = await import('./useRoute');
setPrefs({ tab: 'positions' });
const drawn: string[] = [];
function Page() {
const pr = useStore(prefs);
useRoute(pr.tab);
drawn.push(pr.tab);
return <span>{pr.tab}</span>;
}
document.body.innerHTML = '<div id="root"></div>';
const root = createRoot(document.getElementById('root')!);
const steps = history.length;
await act(async () => root.render(<Page />));
// the saved Positions gave way to the page in the address, and the address stayed as it was, with no new step
expect(prefs.get().tab).toBe('adpSummary');
expect(location.hash).toBe('#adp-summary');
expect(history.length).toBe(steps);
expect(location.pathname).toBe('/accounts/');
// a page chosen: its address, one step more
await act(async () => setPrefs({ tab: 'reports' }));
expect(location.hash).toBe('#fidelity-reports');
expect(history.length).toBe(steps + 1);
// Back: the page before
await act(async () => { history.back(); await new Promise((r) => setTimeout(r, 20)); });
expect(location.hash).toBe('#adp-summary');
expect(prefs.get().tab).toBe('adpSummary');
// an address typed by hand opens its page; an unknown one keeps the page and is written over
await act(async () => { location.hash = '#fidelity-taxes'; window.dispatchEvent(new Event('hashchange')); });
expect(prefs.get().tab).toBe('taxes');
await act(async () => { history.replaceState(null, '', '#X10000001'); window.dispatchEvent(new Event('hashchange')); });
expect(prefs.get().tab).toBe('taxes');
expect(location.hash).toBe('#fidelity-taxes');
await act(async () => setPrefs({ tab: 'summary' }));
expect(location.hash).toBe('#fidelity-summary');
await act(async () => root.unmount());
});
39 changes: 39 additions & 0 deletions src/viewer/ui/useRoute.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/// <reference lib="esnext" />
import { useEffect, useLayoutEffect, useRef } from 'react';
import { prefs, setPrefs, type MainTab } from '../app/prefs';
import { hashToWrite, tabOfHash } from '../app/route';

/**
* Keeps the address and the saved page (`prefs.tab`) in step (app/route.ts): on load a page in the address wins over the
* saved one, and the address is put right in place; a page chosen later (a tab, the logo, the merge switch) adds a step
* to the history, so Back and Forward walk the pages; an address typed or walked to opens its page. The saved page is
* the wanted one: the address says it even while the page waits for its data
*/
export function useRoute(tab: MainTab): void {
const first = useRef(true);
// before the first paint, so the saved page never flashes before the one in the address
useLayoutEffect(() => {
const named = tabOfHash(location.hash);
if (named && named !== prefs.get().tab) setPrefs({ tab: named });
// an address that names no page keeps the page shown and is written over in place
const onWalk = () => {
const t = tabOfHash(location.hash);
if (t) { if (t !== prefs.get().tab) setPrefs({ tab: t }); return; }
const next = hashToWrite(location.hash, prefs.get().tab);
if (next !== null) history.replaceState(history.state, '', `${location.pathname}${location.search}${next}`);
};
window.addEventListener('popstate', onWalk);
window.addEventListener('hashchange', onWalk);
return () => { window.removeEventListener('popstate', onWalk); window.removeEventListener('hashchange', onWalk); };
}, []);
useEffect(() => {
// the store, not `tab`: on load the page of the address was saved a moment ago, after this draw began
const next = hashToWrite(location.hash, prefs.get().tab);
const wasFirst = first.current;
first.current = false;
if (next === null) return;
// the path and the query stay (Pages serves the app under /accounts/)
const url = `${location.pathname}${location.search}${next}`;
if (wasFirst) history.replaceState(history.state, '', url); else history.pushState(null, '', url);
}, [tab]);
}