|
| 1 | +import { HyperkitElement } from "./hyperkit-element"; |
| 2 | + |
| 3 | + |
| 4 | +class HyperkitLink extends HyperkitElement<{ |
| 5 | + propTypes: { timeout: "number" }; |
| 6 | +}> { |
| 7 | + static isPopstateBound = false; |
| 8 | + loading = false; |
| 9 | + propTypes = { timeout: "number" } as const; |
| 10 | + |
| 11 | + requiredChildren = ["a[href]"]; |
| 12 | + cacheLimit = 5; |
| 13 | + maxCacheSize = 100 * 1024; |
| 14 | + |
| 15 | + connectedCallback() { |
| 16 | + super.connectedCallback(); |
| 17 | + window.history.scrollRestoration = "manual"; |
| 18 | + |
| 19 | + requestAnimationFrame(() => { |
| 20 | + this.anchor?.addEventListener("mousedown", (event) => |
| 21 | + this.handleNavigation(event), |
| 22 | + ); |
| 23 | + this.anchor?.addEventListener("touchstart", (event) => |
| 24 | + this.handleNavigation(event), |
| 25 | + ); |
| 26 | + this.anchor?.addEventListener("mouseover", () => this.prefetchContent()); |
| 27 | + }); |
| 28 | + |
| 29 | + if (!HyperkitLink.isPopstateBound) { |
| 30 | + window.addEventListener("popstate", () => this.handlePopstate()); |
| 31 | + HyperkitLink.isPopstateBound = true; |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + get anchor() { |
| 36 | + return this.querySelector<HTMLAnchorElement>("a"); |
| 37 | + } |
| 38 | + |
| 39 | + get href() { |
| 40 | + return String(this.anchor?.getAttribute("href")); |
| 41 | + } |
| 42 | + |
| 43 | + get timeout() { |
| 44 | + return this.prop("timeout") || 5000; |
| 45 | + } |
| 46 | + |
| 47 | + async handleNavigation(event: Event) { |
| 48 | + event.preventDefault(); |
| 49 | + |
| 50 | + sessionStorage.setItem( |
| 51 | + `scrollPosition:${document.location.href}`, |
| 52 | + String(window.scrollY), |
| 53 | + ); |
| 54 | + |
| 55 | + await this.startViewTransition(); |
| 56 | + await this.loadBodyContent(); |
| 57 | + |
| 58 | + history.pushState(null, "", this.href); |
| 59 | + |
| 60 | + requestAnimationFrame(() => |
| 61 | + window.scrollTo({ top: 0, left: 0, behavior: "smooth" }), |
| 62 | + ); |
| 63 | + } |
| 64 | + |
| 65 | + async prefetchContent() { |
| 66 | + const href = this.href; |
| 67 | + |
| 68 | + if (sessionStorage.getItem(`prefetchedContent:${href}`)) return; |
| 69 | + |
| 70 | + try { |
| 71 | + const html = String(await this.fetch({ href })); |
| 72 | + |
| 73 | + if (new Blob([html]).size <= this.maxCacheSize) { |
| 74 | + this.cachePage(href, html); |
| 75 | + } |
| 76 | + } catch (error) { |
| 77 | + console.warn("Prefetch failed:", error); |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + cachePage(href: string, html: string) { |
| 82 | + const cacheOrder = JSON.parse(sessionStorage.getItem("cacheOrder") || "[]"); |
| 83 | + |
| 84 | + if (cacheOrder.length >= this.cacheLimit) { |
| 85 | + const oldestHref = cacheOrder.shift(); |
| 86 | + sessionStorage.removeItem(`prefetchedContent:${oldestHref}`); |
| 87 | + } |
| 88 | + |
| 89 | + sessionStorage.setItem(`prefetchedContent:${href}`, html); |
| 90 | + |
| 91 | + cacheOrder.push(href); |
| 92 | + sessionStorage.setItem("cacheOrder", JSON.stringify(cacheOrder)); |
| 93 | + } |
| 94 | + |
| 95 | + async loadBodyContent({ href }: { href?: string } = {}) { |
| 96 | + if (this.loading) return; |
| 97 | + |
| 98 | + this.loading = true; |
| 99 | + document.body.setAttribute("aria-busy", "true"); |
| 100 | + |
| 101 | + const hrefToFetch = href || this.href; |
| 102 | + |
| 103 | + const cachedHtml = sessionStorage.getItem( |
| 104 | + `prefetchedContent:${hrefToFetch}`, |
| 105 | + ); |
| 106 | + const html = String( |
| 107 | + cachedHtml || (await this.fetch({ href: hrefToFetch })), |
| 108 | + ); |
| 109 | + |
| 110 | + if (cachedHtml) |
| 111 | + sessionStorage.removeItem(`prefetchedContent:${hrefToFetch}`); |
| 112 | + |
| 113 | + await this.insertContent({ html }); |
| 114 | + |
| 115 | + this.loading = false; |
| 116 | + document.body.setAttribute("aria-busy", "false"); |
| 117 | + } |
| 118 | + |
| 119 | + async insertContent({ html }: { html: string }) { |
| 120 | + const parser = new DOMParser(); |
| 121 | + const doc = parser.parseFromString(html, "text/html"); |
| 122 | + document.body.innerHTML = doc.body.innerHTML; |
| 123 | + } |
| 124 | + |
| 125 | + async handlePopstate() { |
| 126 | + const href = document.location.href; |
| 127 | + |
| 128 | + if (!href) { |
| 129 | + location.reload(); |
| 130 | + return; |
| 131 | + } |
| 132 | + |
| 133 | + try { |
| 134 | + await this.startViewTransition(); |
| 135 | + await this.loadBodyContent({ href }); |
| 136 | + |
| 137 | + const savedScroll = sessionStorage.getItem(`scrollPosition:${href}`); |
| 138 | + if (savedScroll !== null) { |
| 139 | + requestAnimationFrame(() => { |
| 140 | + window.scrollTo({ |
| 141 | + top: Number(savedScroll, 10), |
| 142 | + behavior: "smooth", |
| 143 | + }); |
| 144 | + }); |
| 145 | + } |
| 146 | + } catch (error) { |
| 147 | + console.error("Failed to load content on navigation:", error); |
| 148 | + location.reload(); |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + startViewTransition() { |
| 153 | + return document.startViewTransition |
| 154 | + ? new Promise((resolve) => |
| 155 | + document.startViewTransition(() => resolve(true)), |
| 156 | + ) |
| 157 | + : true; |
| 158 | + } |
| 159 | + |
| 160 | + async fetch({ href }: { href: string }) { |
| 161 | + const controller = new AbortController(); |
| 162 | + const timeoutId = setTimeout(() => controller.abort(), this.timeout); |
| 163 | + |
| 164 | + try { |
| 165 | + const response = await fetch(href, { signal: controller.signal }); |
| 166 | + if (!response.ok) throw new Error(`Non-2xx response: ${response.status}`); |
| 167 | + return await response.text(); |
| 168 | + } catch (error) { |
| 169 | + console.warn("Fetch failed or timed out", error); |
| 170 | + window.location.href = href; |
| 171 | + } finally { |
| 172 | + clearTimeout(timeoutId); |
| 173 | + } |
| 174 | + } |
| 175 | +} |
| 176 | + |
| 177 | +if (!customElements.get("hyperkit-link")) |
| 178 | + customElements.define("hyperkit-link", HyperkitLink); |
0 commit comments