|
| 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