Skip to content

Commit feb4a6e

Browse files
committed
refactor(html): split page DOM utilities into page.mjs; extract shouldFollowLink
Move fetchPage, keyIslands, parsePage, showPage, transition, and the head diffing helpers out of router.mjs and into a new page.mjs so that router.mjs stays focused on routing decisions (Navigation API wiring, intercept logic, prefetch cache). Extract shouldFollowLink as a named, exported predicate so the anchor guard (download attribute, target != _self) can be unit tested independently. Also simplify useRemoteConfig to a single module-level promise (replacing the URL-keyed Map) and useOrama to a single module-level client via getClient. Assisted-by: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent da720ce commit feb4a6e

4 files changed

Lines changed: 170 additions & 147 deletions

File tree

‎packages/react/src/html/ui/hooks/useOrama.mjs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,12 @@ export default pathname => {
5656
const [db, setDb] = useState(null);
5757

5858
useEffect(() => {
59-
const url = new URL(
59+
const { href } = new URL(
6060
relativeOrAbsolute('/orama-db.json', pathname),
6161
location.href
62-
).href;
62+
);
6363

64-
queueMicrotask(() => setDb(getClient(url)));
64+
queueMicrotask(() => setDb(getClient(href)));
6565
}, [pathname]);
6666

6767
return db;

‎packages/react/src/html/ui/hooks/useRemoteConfig.mjs‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@ import { remoteConfigUrl } from '#theme/config';
2121
* it. Islands hydrate as separate roots, so no context provider could span
2222
* them; module scope is the shared store.
2323
*
24-
* @type {Promise<RemoteConfig | null> | null}
24+
* @type {Promise<RemoteConfig | undefined> | undefined}
2525
*/
26-
let remoteConfig = null;
26+
let remoteConfig;
2727

2828
/**
2929
* Fetches the remote config, unless it is already loaded or on its way.
@@ -35,9 +35,7 @@ const loadRemoteConfig = () => {
3535
.then(response => response.json())
3636
.catch(() => {
3737
// Not kept, so that the next island to mount tries again
38-
remoteConfig = null;
39-
40-
return null;
38+
remoteConfig = undefined;
4139
});
4240

4341
return remoteConfig;
@@ -46,12 +44,12 @@ const loadRemoteConfig = () => {
4644
/**
4745
* Fetches the remote site configuration once the component mounts.
4846
*
49-
* @returns {RemoteConfig | null} `null` until loaded, or when there is no
50-
* `remoteConfigUrl` or the fetch fails.
47+
* @returns {RemoteConfig | undefined} `undefined` until loaded, or when there
48+
* is no `remoteConfigUrl` or the fetch fails.
5149
*/
5250
export default () => {
5351
const [config, setConfig] = useState(
54-
/** @type {RemoteConfig | null} */ (null)
52+
/** @type {RemoteConfig | undefined} */ (undefined)
5553
);
5654

5755
// A layout effect, so that a page navigated to client-side renders with a
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
/**
2+
* DOM utilities for client-side page swaps: fetching, parsing, and replacing
3+
* the document body and page-specific head elements.
4+
*/
5+
6+
/**
7+
* @typedef {{ url: string, html: string }} Page A fetched page: its final
8+
* URL, after redirects, and its markup.
9+
*/
10+
11+
// The `<head>` elements that belong to the page rather than to the site, and
12+
// are replaced with it: `<meta>` tags (`og:title`) and the links that are not
13+
// resources (`canonical`). Scripts and stylesheets run and apply once.
14+
const PAGE_HEAD =
15+
':scope > meta, :scope > link:not([rel~="stylesheet"], [rel~="preload"], [rel~="modulepreload"])';
16+
17+
/**
18+
* Fetches a page, returning its final URL and HTML, or `null` on failure or a
19+
* non-HTML response.
20+
*
21+
* @param {string} url
22+
* @returns {Promise<Page | null>}
23+
*/
24+
export const fetchPage = url =>
25+
fetch(url, { priority: 'low', headers: { Accept: 'text/html' } })
26+
.then(async response =>
27+
response.ok &&
28+
response.headers.get('content-type')?.startsWith('text/html')
29+
? { url: response.url, html: await response.text() }
30+
: null
31+
)
32+
.catch(() => null);
33+
34+
/**
35+
* Keys an iterable of islands by name and occurrence, so that the same island
36+
* is found again on the next page.
37+
*
38+
* @param {Iterable<HTMLElement>} source
39+
* @returns {Map<string, HTMLElement>}
40+
*/
41+
export const keyIslands = source => {
42+
const counts = new Map();
43+
44+
return new Map(
45+
[...source].map(island => {
46+
const name = island.getAttribute('data-island-name');
47+
counts.set(name, (counts.get(name) ?? 0) + 1);
48+
49+
return [`${name}:${counts.get(name)}`, island];
50+
})
51+
);
52+
};
53+
54+
/**
55+
* Replaces the page-specific `<head>` elements with the next page's, leaving
56+
* the ones both pages share in place.
57+
*
58+
* @param {Document} doc - The next page
59+
*/
60+
const updateHead = doc => {
61+
document.title = doc.title;
62+
63+
const next = new Map(
64+
[...doc.head.querySelectorAll(PAGE_HEAD)].map(element => [
65+
element.outerHTML,
66+
element,
67+
])
68+
);
69+
70+
for (const element of document.head.querySelectorAll(PAGE_HEAD)) {
71+
// What is left in `next` afterwards is what the current page lacks
72+
if (!next.delete(element.outerHTML)) {
73+
element.remove();
74+
}
75+
}
76+
77+
document.head.append(...next.values());
78+
};
79+
80+
/**
81+
* Runs a DOM update, keeping the call-site uniform for a future transition.
82+
*
83+
* @param {() => void} update
84+
*/
85+
export const transition = update => update();
86+
87+
/**
88+
* Parses a fetched page and checks that its assets match this build.
89+
* Returns `null` when the page belongs to a different build (e.g. after a
90+
* new deploy) and only a full load can show it.
91+
*
92+
* @param {Page} page
93+
* @param {Set<string>} assets - Absolute hrefs of this build's scripts and stylesheets
94+
* @returns {Document | null}
95+
*/
96+
export const parsePage = ({ url, html }, assets) => {
97+
const doc = new DOMParser().parseFromString(html, 'text/html');
98+
const tag = doc.querySelector('script[data-router]');
99+
100+
if (!tag) {
101+
return null;
102+
}
103+
104+
/** @type {{ root: string, assets: Array<string> }} */
105+
const pageConfig = JSON.parse(tag.textContent);
106+
107+
return pageConfig.assets
108+
.map(href => new URL(href, url).href)
109+
.every(href => assets.has(href))
110+
? doc
111+
: null;
112+
};
113+
114+
/**
115+
* Swaps the current page for another, preserving island scroll positions.
116+
*
117+
* @param {Document} doc - The next page
118+
* @param {() => void} scroll - Scrolls to where the navigation leads
119+
* @param {(root: Node) => void} unmount - Unmounts islands before the swap
120+
* @param {Set<HTMLElement>} islands - The hydrated islands to save scroll for
121+
*/
122+
export const showPage = (doc, scroll, unmount, islands) => {
123+
const scrolled = [...keyIslands(islands)]
124+
.filter(([, island]) => island.scrollTop || island.scrollLeft)
125+
.map(([key, { scrollLeft, scrollTop }]) => [key, scrollLeft, scrollTop]);
126+
127+
unmount(document.body);
128+
updateHead(doc);
129+
document.body.replaceWith(doc.body);
130+
131+
// Styles can then keep what animates in as the site loads (the banner)
132+
// from animating again with every page
133+
document.documentElement.setAttribute('data-navigated', '');
134+
135+
const next = keyIslands(
136+
document.body.querySelectorAll('is-land[data-island-name]')
137+
);
138+
139+
for (const [key, left, top] of scrolled) {
140+
next.get(key)?.scrollTo({ left, top, behavior: 'instant' });
141+
}
142+
143+
scroll();
144+
};

0 commit comments

Comments
 (0)