@riebeckite/spa 0.0.0-stage → 0.0.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright Rerurate_514
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,71 @@
1
- # Temporary Holding Version
1
+ # @riebeckite/spa
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Opt-in browser navigation runtime for Riebeckite sites.
4
+
5
+ [日本語](./README_ja.md)
6
+
7
+ ## Installation
8
+
9
+ `@riebeckite/honox` loads this package when the site enables `spa` in its
10
+ Riebeckite configuration. Applications using the HonoX integration do not need
11
+ to import it directly.
12
+
13
+ ```sh
14
+ pnpm add @riebeckite/spa
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ Enable navigation in `riebeckite.config.ts`:
20
+
21
+ ```ts
22
+ import { defineConfig } from "@riebeckite/core";
23
+
24
+ export default defineConfig({
25
+ spa: true,
26
+ });
27
+ ```
28
+
29
+ Set `spa: false` or omit `spa` to disable navigation. Pass an options object
30
+ instead of `true` to customize the runtime:
31
+
32
+ ```ts
33
+ export default defineConfig({
34
+ spa: { prefetch: "hover", viewTransitions: true },
35
+ });
36
+ ```
37
+
38
+ The server renderer must provide one `<main id="main-content" tabindex="-1">`
39
+ per page. The runtime replaces this root after a successful same-origin GET
40
+ navigation. It keeps the application shell in place, reconciles page-specific
41
+ head metadata, restores history and scroll state, moves focus to the page root,
42
+ and announces the new page to assistive technology.
43
+
44
+ Links with a modifier key, another target, `download`, or `data-spa="false"`
45
+ keep normal browser behavior. Failed transitions fall back to document
46
+ navigation.
47
+
48
+ ## Head ownership
49
+
50
+ Page-specific head elements should set `data-riebeckite-head="page"`. The
51
+ runtime replaces these on navigation, keeps `data-riebeckite-head="global"` and
52
+ `"runtime"` elements, and preserves unowned elements. Plugin `meta` and `link`
53
+ tags generated by `PluginHeadTags` are page-owned; executable scripts are never
54
+ cloned or re-run.
55
+
56
+ ## Prefetch
57
+
58
+ `prefetch: "hover"` reuses successful page responses for 30 seconds and keeps at
59
+ most 20 completed least-recently-used entries. Concurrent requests for the same
60
+ URL are deduplicated. Prefetch is skipped when the browser reports data saving
61
+ or a connection at 2G or slower.
62
+
63
+ ## Public API
64
+
65
+ - `spa(options)` — creates a Riebeckite SPA configuration value.
66
+ - `startSpaNavigation(options)` — starts navigation and returns a cleanup
67
+ function for custom browser integrations.
68
+
69
+ See the [SPA navigation guide](../../docs/docs/guides/spa-navigation.md) to
70
+ enable it, and [SPA runtime internals](../../docs/docs/framework/spa-runtime.md)
71
+ for the implementation constraints.
package/README_ja.md ADDED
@@ -0,0 +1,52 @@
1
+ # @riebeckite/spa
2
+
3
+ RiebeckiteのサイトでSPAナビゲーションを有効にするための、任意のブラウザランタイムです。
4
+
5
+ [English](./README.md)
6
+
7
+ ## インストール
8
+
9
+ サイトのRiebeckite設定で `spa` を有効にすると、`@riebeckite/honox` がこのパッケージを読み込みます。HonoXとの連携を使うアプリケーションでは、直接importする必要はありません。
10
+
11
+ ```sh
12
+ pnpm add @riebeckite/spa
13
+ ```
14
+
15
+ ## 使い方
16
+
17
+ `riebeckite.config.ts` でSPAナビゲーションを有効にします。
18
+
19
+ ```ts
20
+ import { defineConfig } from "@riebeckite/core";
21
+
22
+ export default defineConfig({
23
+ spa: true,
24
+ });
25
+ ```
26
+
27
+ `spa: false` を指定するか `spa` を省略すると、SPAナビゲーションを無効にできます。設定を変える場合は、`true` の代わりにオプションオブジェクトを渡します。
28
+
29
+ ```ts
30
+ export default defineConfig({
31
+ spa: { prefetch: "hover", viewTransitions: true },
32
+ });
33
+ ```
34
+
35
+ サーバー側のレンダラーは、ページごとに1つの `<main id="main-content" tabindex="-1">` を出力する必要があります。ランタイムは、同一オリジンへのGETリクエストが成功した後にこのルートを置き換えます。アプリケーションシェルはそのまま残し、ページ固有のheadメタデータを更新し、履歴とスクロール位置を復元し、ページのルートへフォーカスを移して、支援技術に新しいページを通知します。
36
+
37
+ 修飾キーを押したリンク、別の `target` を持つリンク、`download` を指定したリンク、`data-spa="false"` を指定したリンクは、通常のブラウザ動作を維持します。ページ移動に失敗した場合は、ページ全体の読み込みにフォールバックします。
38
+
39
+ ## head要素の所有権
40
+
41
+ ページ固有のhead要素には `data-riebeckite-head="page"` を指定します。ランタイムはページ移動時にこれらを置き換え、`data-riebeckite-head="global"` と `"runtime"` の要素を残し、所有権のない要素も保持します。`PluginHeadTags` が生成するPluginの `meta` と `link` はページ所有になり、実行可能なスクリプトは複製も再実行もされません。
42
+
43
+ ## 先読み
44
+
45
+ `prefetch: "hover"` は、成功したページのレスポンスを30秒間再利用し、完了した項目を最近使った順に最大20件保持します。同じURLへの同時リクエストは重複排除されます。ブラウザがデータ節約設定や2G以下の接続を報告している場合は、先読みしません。
46
+
47
+ ## 公開API
48
+
49
+ - `spa(options)` — RiebeckiteのSPA設定値を作成します。
50
+ - `startSpaNavigation(options)` — 独自のブラウザ連携向けにページ移動の処理を開始し、クリーンアップ関数を返します。
51
+
52
+ 有効にする手順は [SPAナビゲーションガイド](../../docs/docs/guides/spa-navigation.ja.md)、実装上の制約は [SPAランタイムの内部実装](../../docs/docs/framework/spa-runtime.ja.md) を参照してください。
@@ -0,0 +1,4 @@
1
+ export declare function reconcileDocument(page: Document): void;
2
+ export declare function focusPage(root: HTMLElement, url: URL): void;
3
+ export declare function focusHashTarget(url: URL): void;
4
+ export declare function announceNavigation(): void;
@@ -0,0 +1,3 @@
1
+ export { startSpaNavigation } from "./navigation.js";
2
+ export type { SpaNavigationEventDetail, SpaNavigationOptions, SpaOptions, SpaPageCommit, } from "./options.js";
3
+ export { spa } from "./options.js";
package/dist/index.js ADDED
@@ -0,0 +1,523 @@
1
+ // document.ts
2
+ var HEAD_OWNER_ATTRIBUTE = "data-riebeckite-head";
3
+ function reconcileDocument(page) {
4
+ document.title = page.title;
5
+ reconcilePageHead(page);
6
+ copyDocumentAttribute(page, "lang");
7
+ copyDocumentAttribute(page, "dir");
8
+ }
9
+ function reconcilePageHead(page) {
10
+ for (const node of Array.from(document.head.children)) {
11
+ if (isPageHeadNode(node)) node.remove();
12
+ }
13
+ for (const node of Array.from(page.head.children)) {
14
+ if (isPageHeadNode(node)) document.head.append(node.cloneNode(true));
15
+ }
16
+ }
17
+ function copyDocumentAttribute(page, name) {
18
+ const value = page.documentElement.getAttribute(name);
19
+ if (value) document.documentElement.setAttribute(name, value);
20
+ else document.documentElement.removeAttribute(name);
21
+ }
22
+ function isPageHeadNode(node) {
23
+ if (node.matches("script") && !isDataScript(node)) return false;
24
+ const owner = node.getAttribute(HEAD_OWNER_ATTRIBUTE);
25
+ if (owner === "page") return true;
26
+ if (owner === "global" || owner === "runtime") return false;
27
+ return isLegacyPageHeadNode(node);
28
+ }
29
+ function isDataScript(node) {
30
+ const type = node.getAttribute("type")?.trim().toLowerCase();
31
+ return type === "application/ld+json" || type === "application/json";
32
+ }
33
+ function isLegacyPageHeadNode(node) {
34
+ if (node.matches('link[rel="canonical"], link[hreflang]')) return true;
35
+ if (node.matches('script[type="application/ld+json"]')) return true;
36
+ if (!node.matches("meta")) return false;
37
+ const name = node.getAttribute("name");
38
+ if (name && ["description", "author", "robots"].includes(name)) return true;
39
+ if (name?.startsWith("twitter:")) return true;
40
+ const property = node.getAttribute("property");
41
+ return property?.startsWith("og:") === true || property?.startsWith("article:") === true;
42
+ }
43
+ function focusPage(root, url) {
44
+ if (url.hash) return;
45
+ if (!root.hasAttribute("tabindex")) root.tabIndex = -1;
46
+ root.focus({ preventScroll: true });
47
+ }
48
+ function focusHashTarget(url) {
49
+ const target = hashTarget(url);
50
+ if (!target) return;
51
+ if (!target.hasAttribute("tabindex")) target.tabIndex = -1;
52
+ target.focus({ preventScroll: true });
53
+ }
54
+ function hashTarget(url) {
55
+ if (!url.hash) return null;
56
+ let id = url.hash.slice(1);
57
+ try {
58
+ id = decodeURIComponent(id);
59
+ } catch {
60
+ return null;
61
+ }
62
+ return document.getElementById(id);
63
+ }
64
+ function announceNavigation() {
65
+ let announcer = document.getElementById("riebeckite-navigation-announcer");
66
+ if (!announcer) {
67
+ announcer = document.createElement("div");
68
+ announcer.id = "riebeckite-navigation-announcer";
69
+ announcer.setAttribute("aria-live", "polite");
70
+ announcer.setAttribute("aria-atomic", "true");
71
+ announcer.className = "riebeckite-visually-hidden";
72
+ document.body.append(announcer);
73
+ }
74
+ announcer.textContent = document.title;
75
+ }
76
+
77
+ // options.ts
78
+ function spa(options = {}) {
79
+ validateSpaOptions(options);
80
+ return Object.freeze({ ...options });
81
+ }
82
+ function validateSpaOptions(options) {
83
+ if (options.prefetch !== void 0 && options.prefetch !== false && options.prefetch !== "hover") {
84
+ throw new TypeError('SPA prefetch must be false or "hover".');
85
+ }
86
+ if (options.scrollRestoration !== void 0 && typeof options.scrollRestoration !== "boolean") {
87
+ throw new TypeError("SPA scrollRestoration must be a boolean.");
88
+ }
89
+ if (options.viewTransitions !== void 0 && typeof options.viewTransitions !== "boolean") {
90
+ throw new TypeError("SPA viewTransitions must be a boolean.");
91
+ }
92
+ }
93
+
94
+ // prefetch.ts
95
+ var DEFAULT_TTL_MS = 3e4;
96
+ var DEFAULT_MAX_ENTRIES = 20;
97
+ var FETCH_TIMEOUT_MS = 15e3;
98
+ var PageCache = class {
99
+ entries = /* @__PURE__ */ new Map();
100
+ ttlMs;
101
+ maxEntries;
102
+ now;
103
+ canPrefetch;
104
+ fetcher;
105
+ constructor(options = {}) {
106
+ this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
107
+ this.maxEntries = options.maxEntries ?? DEFAULT_MAX_ENTRIES;
108
+ this.now = options.now ?? Date.now;
109
+ this.canPrefetch = options.canPrefetch ?? allowsPrefetch;
110
+ this.fetcher = options.fetcher ?? fetchPage;
111
+ }
112
+ get size() {
113
+ return this.entries.size;
114
+ }
115
+ get(url, signal) {
116
+ const href = cacheKey(url);
117
+ const cached = this.freshEntry(href);
118
+ if (cached) {
119
+ this.touch(href, cached);
120
+ return abortable(cached.promise, signal);
121
+ }
122
+ return abortable(this.load(href).promise, signal);
123
+ }
124
+ prefetch(url) {
125
+ if (!this.canPrefetch()) return;
126
+ const href = cacheKey(url);
127
+ if (this.freshEntry(href)) return;
128
+ void this.load(href).promise.catch(() => void 0);
129
+ }
130
+ dispose() {
131
+ for (const entry of this.entries.values()) entry.controller.abort();
132
+ this.entries.clear();
133
+ }
134
+ load(href) {
135
+ if (this.entries.size >= this.maxEntries) this.evictOldest();
136
+ const controller = new AbortController();
137
+ let entry;
138
+ let fetched;
139
+ try {
140
+ fetched = this.fetcher(new URL(href), controller.signal);
141
+ } catch (error) {
142
+ fetched = Promise.reject(error);
143
+ }
144
+ const promise = fetched.then((page) => {
145
+ entry.settled = true;
146
+ entry.createdAt = this.now();
147
+ this.evictOverflow();
148
+ return page;
149
+ }).catch((error) => {
150
+ if (this.entries.get(href) === entry) this.entries.delete(href);
151
+ throw error;
152
+ });
153
+ entry = {
154
+ controller,
155
+ createdAt: this.now(),
156
+ settled: false,
157
+ promise
158
+ };
159
+ this.entries.set(href, entry);
160
+ return entry;
161
+ }
162
+ freshEntry(href) {
163
+ const entry = this.entries.get(href);
164
+ if (!entry) return void 0;
165
+ if (entry.settled && this.now() - entry.createdAt > this.ttlMs) {
166
+ this.entries.delete(href);
167
+ entry.controller.abort();
168
+ return void 0;
169
+ }
170
+ return entry;
171
+ }
172
+ touch(href, entry) {
173
+ this.entries.delete(href);
174
+ this.entries.set(href, entry);
175
+ }
176
+ evictOldest() {
177
+ for (const [href, entry] of this.entries) {
178
+ if (!entry.settled) continue;
179
+ this.entries.delete(href);
180
+ return;
181
+ }
182
+ }
183
+ evictOverflow() {
184
+ while (this.entries.size > this.maxEntries) {
185
+ const before = this.entries.size;
186
+ this.evictOldest();
187
+ if (this.entries.size === before) return;
188
+ }
189
+ }
190
+ };
191
+ async function fetchPage(url, signal) {
192
+ const timeout = timeoutSignal(signal, FETCH_TIMEOUT_MS);
193
+ try {
194
+ const response = await fetch(url, {
195
+ headers: { Accept: "text/html,application/xhtml+xml" },
196
+ signal: timeout.signal
197
+ });
198
+ if (!response.ok) {
199
+ throw new Error(`Navigation request failed: ${response.status}`);
200
+ }
201
+ const contentType = response.headers.get("content-type");
202
+ if (contentType && !isHtmlContentType(contentType)) {
203
+ throw new Error(`Navigation response is not HTML: ${contentType}`);
204
+ }
205
+ return { html: await response.text(), url: response.url || url.href };
206
+ } finally {
207
+ timeout.clear();
208
+ }
209
+ }
210
+ function isHtmlContentType(value) {
211
+ const mediaType = value.split(";", 1)[0]?.trim().toLowerCase();
212
+ return mediaType === "text/html" || mediaType === "application/xhtml+xml";
213
+ }
214
+ function cacheKey(url) {
215
+ const key = new URL(url.href);
216
+ key.hash = "";
217
+ return key.href;
218
+ }
219
+ function allowsPrefetch() {
220
+ const connection = navigator.connection;
221
+ if (!connection) return true;
222
+ if (connection.saveData) return false;
223
+ return connection.effectiveType !== "slow-2g" && connection.effectiveType !== "2g";
224
+ }
225
+ function abortable(promise, signal) {
226
+ if (!signal) return promise;
227
+ if (signal.aborted) return Promise.reject(abortReason(signal));
228
+ return new Promise((resolve, reject) => {
229
+ const abort = () => reject(abortReason(signal));
230
+ signal.addEventListener("abort", abort, { once: true });
231
+ promise.then(
232
+ (value) => {
233
+ signal.removeEventListener("abort", abort);
234
+ resolve(value);
235
+ },
236
+ (error) => {
237
+ signal.removeEventListener("abort", abort);
238
+ reject(error);
239
+ }
240
+ );
241
+ });
242
+ }
243
+ function timeoutSignal(signal, timeoutMs) {
244
+ const controller = new AbortController();
245
+ const abort = () => controller.abort(abortReason(signal));
246
+ if (signal.aborted) abort();
247
+ else signal.addEventListener("abort", abort, { once: true });
248
+ const timer = setTimeout(() => {
249
+ controller.abort(new DOMException("Navigation timed out.", "TimeoutError"));
250
+ }, timeoutMs);
251
+ return {
252
+ signal: controller.signal,
253
+ clear: () => {
254
+ clearTimeout(timer);
255
+ signal.removeEventListener("abort", abort);
256
+ }
257
+ };
258
+ }
259
+ function abortReason(signal) {
260
+ return signal.reason ?? new DOMException("Navigation aborted.", "AbortError");
261
+ }
262
+
263
+ // scroll.ts
264
+ var SCROLL_RECORD_DELAY_MS = 100;
265
+ var ScrollRestoration = class {
266
+ previous;
267
+ enabled;
268
+ timer;
269
+ constructor(enabled) {
270
+ this.enabled = enabled;
271
+ this.previous = history.scrollRestoration;
272
+ }
273
+ start() {
274
+ if (!this.enabled) return;
275
+ history.scrollRestoration = "manual";
276
+ window.addEventListener("scroll", this.onScroll, { passive: true });
277
+ }
278
+ stop() {
279
+ if (!this.enabled) return;
280
+ this.cancel();
281
+ window.removeEventListener("scroll", this.onScroll);
282
+ history.scrollRestoration = this.previous;
283
+ }
284
+ cancel() {
285
+ if (this.timer !== void 0) window.clearTimeout(this.timer);
286
+ this.timer = void 0;
287
+ }
288
+ record() {
289
+ if (!this.enabled) return;
290
+ this.cancel();
291
+ history.replaceState(
292
+ {
293
+ ...history.state ?? {},
294
+ scroll: [window.scrollX, window.scrollY]
295
+ },
296
+ ""
297
+ );
298
+ }
299
+ push(url) {
300
+ if (this.enabled) this.cancel();
301
+ history.pushState({ scroll: [0, 0] }, "", url);
302
+ }
303
+ restore(url, popstate) {
304
+ if (!this.enabled) return;
305
+ this.cancel();
306
+ if (url.hash) {
307
+ document.getElementById(readHashId(url.hash))?.scrollIntoView();
308
+ return;
309
+ }
310
+ const saved = popstate ? readSavedScrollPosition(history.state) : void 0;
311
+ if (saved) {
312
+ window.scrollTo(saved[0], saved[1]);
313
+ return;
314
+ }
315
+ if (!popstate) window.scrollTo(0, 0);
316
+ }
317
+ onScroll = () => {
318
+ if (this.timer !== void 0) return;
319
+ this.timer = window.setTimeout(() => {
320
+ this.timer = void 0;
321
+ this.record();
322
+ }, SCROLL_RECORD_DELAY_MS);
323
+ };
324
+ };
325
+ function readHashId(hash) {
326
+ try {
327
+ return decodeURIComponent(hash.slice(1));
328
+ } catch {
329
+ return "";
330
+ }
331
+ }
332
+ function readSavedScrollPosition(value) {
333
+ if (!value || typeof value !== "object") return void 0;
334
+ const scroll = value.scroll;
335
+ if (!Array.isArray(scroll) || scroll.length !== 2) return void 0;
336
+ return typeof scroll[0] === "number" && typeof scroll[1] === "number" ? [scroll[0], scroll[1]] : void 0;
337
+ }
338
+
339
+ // navigation.ts
340
+ function startSpaNavigation(options = {}) {
341
+ return new SpaNavigation(options).start();
342
+ }
343
+ var SpaNavigation = class {
344
+ options;
345
+ cache = new PageCache();
346
+ scroll;
347
+ navigationId = 0;
348
+ currentPath = window.location.pathname + window.location.search;
349
+ active;
350
+ constructor(options) {
351
+ validateSpaOptions(options);
352
+ this.options = {
353
+ prefetch: options.prefetch ?? false,
354
+ scrollRestoration: options.scrollRestoration ?? true,
355
+ viewTransitions: options.viewTransitions ?? false,
356
+ onBeforePageCommit: options.onBeforePageCommit,
357
+ onPageCommit: options.onPageCommit
358
+ };
359
+ this.scroll = new ScrollRestoration(this.options.scrollRestoration);
360
+ }
361
+ start() {
362
+ this.scroll.start();
363
+ document.addEventListener("click", this.onClick);
364
+ window.addEventListener("popstate", this.onPopState);
365
+ if (this.options.prefetch === "hover") {
366
+ document.addEventListener("pointerover", this.onPointerOver);
367
+ }
368
+ return () => this.stop();
369
+ }
370
+ stop() {
371
+ this.navigationId += 1;
372
+ this.cancelActive();
373
+ this.cache.dispose();
374
+ this.scroll.stop();
375
+ document.removeEventListener("click", this.onClick);
376
+ window.removeEventListener("popstate", this.onPopState);
377
+ document.removeEventListener("pointerover", this.onPointerOver);
378
+ }
379
+ onClick = (event) => {
380
+ if (event.defaultPrevented || event.button !== 0) return;
381
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
382
+ return;
383
+ const anchor = event.target?.closest(
384
+ "a[href]"
385
+ );
386
+ if (!anchor || !this.shouldNavigate(anchor)) return;
387
+ const url = new URL(anchor.href, window.location.href);
388
+ if (isHashOnlyNavigation(url)) return;
389
+ event.preventDefault();
390
+ void this.navigate(url, false);
391
+ };
392
+ onPopState = () => {
393
+ void this.navigate(new URL(window.location.href), true);
394
+ };
395
+ onPointerOver = (event) => {
396
+ const anchor = event.target?.closest(
397
+ "a[href]"
398
+ );
399
+ if (!anchor || !this.shouldNavigate(anchor)) return;
400
+ const url = new URL(anchor.href, window.location.href);
401
+ if (isHashOnlyNavigation(url)) return;
402
+ this.cache.prefetch(url);
403
+ };
404
+ shouldNavigate(anchor) {
405
+ if (anchor.target && anchor.target !== "_self") return false;
406
+ if (anchor.hasAttribute("download")) return false;
407
+ if (anchor.dataset.spa === "false") return false;
408
+ const url = new URL(anchor.href, window.location.href);
409
+ return url.origin === window.location.origin && url.protocol === window.location.protocol;
410
+ }
411
+ async navigate(url, popstate) {
412
+ const id = ++this.navigationId;
413
+ this.cancelActive();
414
+ if (popstate) this.scroll.cancel();
415
+ if (popstate && this.isSamePage(url)) {
416
+ this.scroll.restore(url, true);
417
+ if (url.hash) {
418
+ focusHashTarget(url);
419
+ } else {
420
+ const root = document.querySelector("main#main-content");
421
+ if (root) focusPage(root, url);
422
+ }
423
+ return;
424
+ }
425
+ const controller = new AbortController();
426
+ const active = { id, controller };
427
+ this.active = active;
428
+ let committed = false;
429
+ let commitFailure;
430
+ let destination = url;
431
+ try {
432
+ if (!popstate) this.scroll.record();
433
+ const page = await this.loadPage(url, controller.signal);
434
+ if (!this.isCurrent(id, controller)) return;
435
+ destination = page.url;
436
+ const current = document.querySelector("main#main-content");
437
+ if (!current) throw new Error("SPA page root is missing.");
438
+ const commit = async () => {
439
+ try {
440
+ if (!this.isCurrent(id, controller)) return;
441
+ await this.options.onBeforePageCommit?.(controller.signal);
442
+ if (!this.isCurrent(id, controller)) return;
443
+ reconcileDocument(page.document);
444
+ current.replaceWith(page.root);
445
+ committed = true;
446
+ await this.options.onPageCommit?.({
447
+ root: page.root,
448
+ signal: controller.signal
449
+ });
450
+ } catch (error) {
451
+ commitFailure = { error };
452
+ }
453
+ };
454
+ if (this.shouldUseViewTransition()) {
455
+ const startViewTransition = document.startViewTransition?.bind(document);
456
+ if (startViewTransition) {
457
+ const transition = startViewTransition(commit);
458
+ active.transition = transition;
459
+ await (transition.updateCallbackDone ?? transition.finished);
460
+ if (commitFailure) throw commitFailure.error;
461
+ } else {
462
+ await commit();
463
+ if (commitFailure) throw commitFailure.error;
464
+ }
465
+ } else {
466
+ await commit();
467
+ if (commitFailure) throw commitFailure.error;
468
+ }
469
+ if (!this.isCurrent(id, controller)) return;
470
+ if (!popstate) this.scroll.push(page.url);
471
+ this.scroll.restore(page.url, popstate);
472
+ focusPage(page.root, page.url);
473
+ focusHashTarget(page.url);
474
+ announceNavigation();
475
+ document.dispatchEvent(
476
+ new CustomEvent("riebeckite:navigation", {
477
+ detail: { url: page.url.href, popstate }
478
+ })
479
+ );
480
+ this.currentPath = page.url.pathname + page.url.search;
481
+ } catch (error) {
482
+ if (!this.isCurrent(id, controller)) return;
483
+ if (committed) {
484
+ console.error("[riebeckite] SPA navigation commit failed.", error);
485
+ }
486
+ window.location.assign(destination.href);
487
+ } finally {
488
+ if (this.active === active) this.active = void 0;
489
+ }
490
+ }
491
+ async loadPage(url, signal) {
492
+ const fetched = await this.cache.get(url, signal);
493
+ const page = new DOMParser().parseFromString(fetched.html, "text/html");
494
+ const root = page.querySelector("main#main-content");
495
+ if (!root) throw new Error("SPA page root is missing.");
496
+ const finalUrl = new URL(fetched.url, url.href);
497
+ if (finalUrl.origin !== window.location.origin) {
498
+ throw new Error("SPA navigation redirected to another origin.");
499
+ }
500
+ return { document: page, root, url: finalUrl };
501
+ }
502
+ cancelActive() {
503
+ this.active?.controller.abort();
504
+ this.active?.transition?.skipTransition();
505
+ this.active = void 0;
506
+ }
507
+ isCurrent(id, controller) {
508
+ return this.navigationId === id && !controller.signal.aborted;
509
+ }
510
+ isSamePage(url) {
511
+ return url.pathname + url.search === this.currentPath;
512
+ }
513
+ shouldUseViewTransition() {
514
+ return this.options.viewTransitions && "startViewTransition" in document && !window.matchMedia("(prefers-reduced-motion: reduce)").matches;
515
+ }
516
+ };
517
+ function isHashOnlyNavigation(url) {
518
+ return url.pathname === window.location.pathname && url.search === window.location.search && url.hash.length > 0;
519
+ }
520
+ export {
521
+ spa,
522
+ startSpaNavigation
523
+ };
@@ -0,0 +1,2 @@
1
+ import { type SpaNavigationOptions } from "./options.js";
2
+ export declare function startSpaNavigation(options?: SpaNavigationOptions): () => void;
@@ -0,0 +1,19 @@
1
+ export type SpaOptions = {
2
+ prefetch?: false | "hover";
3
+ scrollRestoration?: boolean;
4
+ viewTransitions?: boolean;
5
+ };
6
+ export type SpaPageCommit = (context: {
7
+ root: HTMLElement;
8
+ signal: AbortSignal;
9
+ }) => void | Promise<void>;
10
+ export type SpaNavigationEventDetail = {
11
+ url: string;
12
+ popstate: boolean;
13
+ };
14
+ export type SpaNavigationOptions = SpaOptions & {
15
+ onBeforePageCommit?: (signal: AbortSignal) => void | Promise<void>;
16
+ onPageCommit?: SpaPageCommit;
17
+ };
18
+ export declare function spa(options?: SpaOptions): Readonly<SpaOptions>;
19
+ export declare function validateSpaOptions(options: SpaOptions): void;
@@ -0,0 +1,31 @@
1
+ export type FetchedPage = {
2
+ html: string;
3
+ url: string;
4
+ };
5
+ export type PageFetcher = (url: URL, signal: AbortSignal) => Promise<FetchedPage>;
6
+ export type PageCacheOptions = {
7
+ ttlMs?: number;
8
+ maxEntries?: number;
9
+ now?: () => number;
10
+ canPrefetch?: () => boolean;
11
+ fetcher?: PageFetcher;
12
+ };
13
+ export declare class PageCache {
14
+ private readonly entries;
15
+ private readonly ttlMs;
16
+ private readonly maxEntries;
17
+ private readonly now;
18
+ private readonly canPrefetch;
19
+ private readonly fetcher;
20
+ constructor(options?: PageCacheOptions);
21
+ get size(): number;
22
+ get(url: URL, signal?: AbortSignal): Promise<FetchedPage>;
23
+ prefetch(url: URL): void;
24
+ dispose(): void;
25
+ private load;
26
+ private freshEntry;
27
+ private touch;
28
+ private evictOldest;
29
+ private evictOverflow;
30
+ }
31
+ export declare function fetchPage(url: URL, signal: AbortSignal): Promise<FetchedPage>;
@@ -0,0 +1,13 @@
1
+ export declare class ScrollRestoration {
2
+ private readonly previous;
3
+ private readonly enabled;
4
+ private timer?;
5
+ constructor(enabled: boolean);
6
+ start(): void;
7
+ stop(): void;
8
+ cancel(): void;
9
+ record(): void;
10
+ push(url: URL): void;
11
+ restore(url: URL, popstate: boolean): void;
12
+ private readonly onScroll;
13
+ }
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@riebeckite/spa",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.0.32",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "source": "./index.ts",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "publishConfig": {
17
+ "access": "public"
18
+ },
19
+ "files": [
20
+ "LICENSE",
21
+ "README.md",
22
+ "README_ja.md",
23
+ "dist"
24
+ ],
25
+ "devDependencies": {
26
+ "tsx": "^4.22.4"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "https://github.com/Rerurate514/riebeckite.git",
31
+ "directory": "packages/spa"
32
+ },
33
+ "homepage": "https://github.com/Rerurate514/riebeckite#readme",
34
+ "bugs": {
35
+ "url": "https://github.com/Rerurate514/riebeckite/issues"
36
+ },
37
+ "description": "Opt-in SPA navigation runtime for Riebeckite sites.",
38
+ "keywords": [
39
+ "riebeckite",
40
+ "spa",
41
+ "navigation"
42
+ ],
43
+ "engines": {
44
+ "node": "^20.19.0 || >=22.12.0"
45
+ },
46
+ "sideEffects": false,
47
+ "scripts": {
48
+ "build": "node ../../scripts/build_package.mjs",
49
+ "test": "node --import tsx --test \"test/*.test.ts\""
50
+ }
6
51
  }