toiljs 0.0.12 → 0.0.15

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.
Files changed (41) hide show
  1. package/README.md +1 -1
  2. package/build/cli/.tsbuildinfo +1 -1
  3. package/build/cli/index.js +2926 -191
  4. package/build/client/.tsbuildinfo +1 -1
  5. package/build/client/head/metadata.d.ts +3 -1
  6. package/build/client/head/metadata.js +8 -0
  7. package/build/client/index.d.ts +4 -4
  8. package/build/client/index.js +2 -2
  9. package/build/client/navigation/navigation.d.ts +2 -0
  10. package/build/client/navigation/navigation.js +9 -1
  11. package/build/client/routing/loader.d.ts +2 -0
  12. package/build/compiler/.tsbuildinfo +1 -1
  13. package/build/compiler/config.d.ts +2 -0
  14. package/build/compiler/config.js +1 -0
  15. package/build/compiler/generate.js +10 -1
  16. package/build/compiler/index.js +2 -0
  17. package/build/compiler/prerender.js +1 -0
  18. package/build/compiler/seo.d.ts +1 -1
  19. package/build/compiler/seo.js +3 -2
  20. package/build/compiler/ssg.d.ts +5 -0
  21. package/build/compiler/ssg.js +90 -0
  22. package/examples/basic/client/routes/search.tsx +61 -61
  23. package/package.json +4 -3
  24. package/src/client/head/metadata.ts +112 -94
  25. package/src/client/index.ts +89 -79
  26. package/src/client/navigation/navigation.ts +235 -215
  27. package/src/client/routing/loader.ts +10 -0
  28. package/src/client/search/search.ts +189 -189
  29. package/src/client/search/use-page-search.ts +73 -73
  30. package/src/compiler/config.ts +182 -173
  31. package/src/compiler/generate.ts +394 -378
  32. package/src/compiler/index.ts +3 -0
  33. package/src/compiler/pages.ts +2 -2
  34. package/src/compiler/prerender.ts +156 -152
  35. package/src/compiler/seo.ts +390 -381
  36. package/src/compiler/ssg.ts +126 -0
  37. package/test/dom/error-overlay.test.tsx +44 -44
  38. package/test/dom/router-loading.test.tsx +1 -1
  39. package/test/dom/use-metadata.test.tsx +58 -0
  40. package/test/seo.test.ts +164 -164
  41. package/test/ssg.test.ts +36 -0
@@ -1,215 +1,235 @@
1
- /**
2
- * History-based navigation core. Owns the location subscribers, the single `popstate` handler, and
3
- * the per-entry history keys used for scroll restoration. Consumed by `useLocation` (to re-render),
4
- * `Link` / `navigate` (to change location), and `Router` (which calls `applyScroll` after commit).
5
- */
6
- import { startTransition } from 'react';
7
- import { flushSync } from 'react-dom';
8
-
9
- import { enableManualScrollRestoration, planScroll, rememberScroll } from './scroll.js';
10
- import type { Href } from '../types.js';
11
-
12
- const listeners = new Set<() => void>();
13
- let popstateBound = false;
14
-
15
- /** `document.startViewTransition`, present only where the View Transitions API is supported. */
16
- interface ViewTransitionDocument {
17
- startViewTransition?: (callback: () => void) => unknown;
18
- }
19
- let viewTransitions = false;
20
-
21
- /** Enables animated View Transitions for navigation. Called once by `mount` from `client.viewTransitions`. */
22
- export function setViewTransitions(enabled: boolean): void {
23
- viewTransitions = enabled;
24
- }
25
-
26
- /** Whether the current navigation should animate via the View Transitions API. */
27
- function shouldViewTransition(): boolean {
28
- if (!viewTransitions || typeof document === 'undefined' || typeof window === 'undefined') {
29
- return false;
30
- }
31
- if (typeof (document as ViewTransitionDocument).startViewTransition !== 'function')
32
- return false;
33
- return !window.matchMedia('(prefers-reduced-motion: reduce)').matches;
34
- }
35
-
36
- interface ToilHistoryState {
37
- __toilKey?: string;
38
- }
39
- let keyCounter = 0;
40
- let currentKey = 'initial';
41
- function nextKey(): string {
42
- keyCounter += 1;
43
- return `t${String(keyCounter)}`;
44
- }
45
-
46
- function runListeners(): void {
47
- for (const listener of listeners) listener();
48
- }
49
-
50
- /**
51
- * Re-renders subscribers for a location change. Normally wrapped in `startTransition` (smooth: the
52
- * current page stays while the next route loads). When View Transitions are enabled and supported,
53
- * the commit runs synchronously inside `document.startViewTransition` so the browser animates the
54
- * old and new DOM (a crossfade, or shared-element transitions via `view-transition-name`).
55
- */
56
- function notify(): void {
57
- if (shouldViewTransition()) {
58
- (document as ViewTransitionDocument).startViewTransition?.(() => {
59
- flushSync(runListeners);
60
- });
61
- } else {
62
- startTransition(runListeners);
63
- }
64
- }
65
-
66
- // Soft vs hard navigation, for intercepting routes. The initial page load (and any full refresh) is
67
- // "hard"; client navigations (`navigate` / back / forward) are "soft". `previousPath` is the path we
68
- // were on before the latest soft navigation, the route the main view keeps showing while an
69
- // intercepting route fills a slot (the modal overlay).
70
- let softNav = false;
71
- let currentPath = typeof window === 'undefined' ? '/' : window.location.pathname;
72
- let previousPath = currentPath;
73
-
74
- /** Records a transition to the live location; `soft` is false only for the initial load. */
75
- function recordTransition(soft: boolean): void {
76
- previousPath = currentPath;
77
- currentPath = typeof window === 'undefined' ? '/' : window.location.pathname;
78
- softNav = soft;
79
- }
80
-
81
- /** Whether the current location was reached by a client navigation (not an initial load / refresh). */
82
- export function isSoftNavigation(): boolean {
83
- return softNav;
84
- }
85
-
86
- /** The path the app was on before the latest navigation (what the main view keeps during an intercept). */
87
- export function previousPathname(): string {
88
- return previousPath;
89
- }
90
-
91
- // Navigation-pending tracking: a navigation is "pending" from when it starts until the new route
92
- // commits. Drives useNavigationPending() (e.g. a top loading bar).
93
- let startedTick = 0;
94
- let committedTick = 0;
95
- const pendingListeners = new Set<() => void>();
96
- function emitPending(): void {
97
- for (const listener of pendingListeners) listener();
98
- }
99
- function beginNavigation(): void {
100
- startedTick += 1;
101
- emitPending();
102
- }
103
-
104
- /** Marks the in-flight navigation as committed. Called by `Router` after each commit. */
105
- export function settleNavigation(): void {
106
- if (committedTick !== startedTick) {
107
- committedTick = startedTick;
108
- emitPending();
109
- }
110
- }
111
-
112
- /** Whether a navigation is in flight (started but not yet committed). */
113
- export function isNavigationPending(): boolean {
114
- return startedTick !== committedTick;
115
- }
116
-
117
- /** Monotonic id incremented on each navigation, used to key/revalidate per-navigation route data. */
118
- export function navigationEpoch(): number {
119
- return startedTick;
120
- }
121
-
122
- /** Subscribes to navigation-pending changes; returns an unsubscribe function. */
123
- export function subscribePending(listener: () => void): () => void {
124
- pendingListeners.add(listener);
125
- return () => {
126
- pendingListeners.delete(listener);
127
- };
128
- }
129
-
130
- /** Options for {@link navigate}. */
131
- export interface NavigateOptions {
132
- /** Replace the current history entry instead of pushing a new one. Default `false`. */
133
- readonly replace?: boolean;
134
- /** Scroll to the top of the page after navigating. Default `true`. */
135
- readonly scroll?: boolean;
136
- }
137
-
138
- /** Initializes manual scroll restoration and the initial history key. Called once by `mount`. */
139
- export function initNavigation(): void {
140
- enableManualScrollRestoration();
141
- const state = window.history.state as ToilHistoryState | null;
142
- if (state?.__toilKey) {
143
- currentKey = state.__toilKey;
144
- } else {
145
- currentKey = nextKey();
146
- window.history.replaceState({ ...state, __toilKey: currentKey }, '');
147
- }
148
- }
149
-
150
- /** Navigates to `href` without a full page reload (history push/replace + subscriber re-render). */
151
- export function navigate(href: Href, options?: NavigateOptions): void {
152
- beginNavigation();
153
- rememberScroll(currentKey);
154
- let hash = '';
155
- try {
156
- hash = new URL(href, window.location.href).hash;
157
- } catch {
158
- hash = '';
159
- }
160
- if (options?.replace) {
161
- window.history.replaceState({ __toilKey: currentKey }, '', href);
162
- } else {
163
- currentKey = nextKey();
164
- window.history.pushState({ __toilKey: currentKey }, '', href);
165
- }
166
- recordTransition(true);
167
- planScroll({ hash, toTop: options?.scroll !== false });
168
- notify();
169
- }
170
-
171
- /** Goes back one entry in history (fires `popstate`, which notifies subscribers). */
172
- export function back(): void {
173
- window.history.back();
174
- }
175
-
176
- /** Goes forward one entry in history. */
177
- export function forward(): void {
178
- window.history.forward();
179
- }
180
-
181
- /**
182
- * Re-renders the current route, bumping the navigation epoch so a revalidation of the *same* URL
183
- * re-keys its Suspense boundary (its `loading.tsx` shows while the loader re-runs) and
184
- * `useNavigationPending` reports the in-flight refetch, instead of silently freezing the old page.
185
- */
186
- export function refresh(): void {
187
- beginNavigation();
188
- notify();
189
- }
190
-
191
- /** Handles browser back/forward: restores the saved scroll for the target entry, then re-renders. */
192
- function handlePopState(event: PopStateEvent): void {
193
- beginNavigation();
194
- rememberScroll(currentKey);
195
- const state = event.state as ToilHistoryState | null;
196
- currentKey = state?.__toilKey ?? 'initial';
197
- recordTransition(true);
198
- planScroll({ restoreKey: currentKey, hash: window.location.hash, toTop: false });
199
- notify();
200
- }
201
-
202
- /**
203
- * Subscribes `listener` to location changes and returns an unsubscribe function. Browser
204
- * back/forward is wired once, on the first subscription, via a shared `popstate` handler.
205
- */
206
- export function subscribeLocation(listener: () => void): () => void {
207
- if (!popstateBound) {
208
- window.addEventListener('popstate', handlePopState);
209
- popstateBound = true;
210
- }
211
- listeners.add(listener);
212
- return () => {
213
- listeners.delete(listener);
214
- };
215
- }
1
+ /**
2
+ * History-based navigation core. Owns the location subscribers, the single `popstate` handler, and
3
+ * the per-entry history keys used for scroll restoration. Consumed by `useLocation` (to re-render),
4
+ * `Link` / `navigate` (to change location), and `Router` (which calls `applyScroll` after commit).
5
+ */
6
+ import { startTransition } from 'react';
7
+ import { flushSync } from 'react-dom';
8
+
9
+ import { enableManualScrollRestoration, planScroll, rememberScroll } from './scroll.js';
10
+ import type { Href } from '../types.js';
11
+
12
+ /**
13
+ * Asserts a runtime-computed string is a valid {@link Href}, the escape hatch for hrefs built from
14
+ * data (e.g. `` `/${category}/${slug}` ``) that can't be checked against the static route union.
15
+ * Use at the call site: `<Link href={href(path)} />`, `navigate(href(path))`.
16
+ */
17
+ export const href = (path: string): Href => path as Href;
18
+
19
+ const listeners = new Set<() => void>();
20
+ let popstateBound = false;
21
+
22
+ /** `document.startViewTransition`, present only where the View Transitions API is supported. */
23
+ interface ViewTransitionDocument {
24
+ startViewTransition?: (callback: () => void) => unknown;
25
+ }
26
+ let viewTransitions = false;
27
+
28
+ /** Enables animated View Transitions for navigation. Called once by `mount` from `client.viewTransitions`. */
29
+ export function setViewTransitions(enabled: boolean): void {
30
+ viewTransitions = enabled;
31
+ }
32
+
33
+ // Whether to wrap navigations in a React transition. Off by default: a navigation commits eagerly, so
34
+ // a route's `loading.tsx` shows immediately while its loader runs. On, the current page is kept
35
+ // visible until the next route is ready (smoother, but no loading state). Set from `client.transitions`.
36
+ let navTransitions = false;
37
+
38
+ /** Enables React-transition (keep-current-page) navigation. Called once by `mount` from `client.transitions`. */
39
+ export function setTransitions(enabled: boolean): void {
40
+ navTransitions = enabled;
41
+ }
42
+
43
+ /** Whether the current navigation should animate via the View Transitions API. */
44
+ function shouldViewTransition(): boolean {
45
+ if (!viewTransitions || typeof document === 'undefined' || typeof window === 'undefined') {
46
+ return false;
47
+ }
48
+ if (typeof (document as ViewTransitionDocument).startViewTransition !== 'function')
49
+ return false;
50
+ return !window.matchMedia('(prefers-reduced-motion: reduce)').matches;
51
+ }
52
+
53
+ interface ToilHistoryState {
54
+ __toilKey?: string;
55
+ }
56
+ let keyCounter = 0;
57
+ let currentKey = 'initial';
58
+ function nextKey(): string {
59
+ keyCounter += 1;
60
+ return `t${String(keyCounter)}`;
61
+ }
62
+
63
+ function runListeners(): void {
64
+ for (const listener of listeners) listener();
65
+ }
66
+
67
+ /**
68
+ * Re-renders subscribers for a location change. When View Transitions are enabled and supported, the
69
+ * commit runs synchronously inside `document.startViewTransition` so the browser animates the old and
70
+ * new DOM. Otherwise, with `client.transitions` on, it's wrapped in `startTransition` (the current
71
+ * page stays while the next route loads); by default it commits eagerly, so a route's `loading.tsx`
72
+ * shows right away instead of holding the previous page.
73
+ */
74
+ function notify(): void {
75
+ if (shouldViewTransition()) {
76
+ (document as ViewTransitionDocument).startViewTransition?.(() => {
77
+ flushSync(runListeners);
78
+ });
79
+ } else if (navTransitions) {
80
+ startTransition(runListeners);
81
+ } else {
82
+ runListeners();
83
+ }
84
+ }
85
+
86
+ // Soft vs hard navigation, for intercepting routes. The initial page load (and any full refresh) is
87
+ // "hard"; client navigations (`navigate` / back / forward) are "soft". `previousPath` is the path we
88
+ // were on before the latest soft navigation, the route the main view keeps showing while an
89
+ // intercepting route fills a slot (the modal overlay).
90
+ let softNav = false;
91
+ let currentPath = typeof window === 'undefined' ? '/' : window.location.pathname;
92
+ let previousPath = currentPath;
93
+
94
+ /** Records a transition to the live location; `soft` is false only for the initial load. */
95
+ function recordTransition(soft: boolean): void {
96
+ previousPath = currentPath;
97
+ currentPath = typeof window === 'undefined' ? '/' : window.location.pathname;
98
+ softNav = soft;
99
+ }
100
+
101
+ /** Whether the current location was reached by a client navigation (not an initial load / refresh). */
102
+ export function isSoftNavigation(): boolean {
103
+ return softNav;
104
+ }
105
+
106
+ /** The path the app was on before the latest navigation (what the main view keeps during an intercept). */
107
+ export function previousPathname(): string {
108
+ return previousPath;
109
+ }
110
+
111
+ // Navigation-pending tracking: a navigation is "pending" from when it starts until the new route
112
+ // commits. Drives useNavigationPending() (e.g. a top loading bar).
113
+ let startedTick = 0;
114
+ let committedTick = 0;
115
+ const pendingListeners = new Set<() => void>();
116
+ function emitPending(): void {
117
+ for (const listener of pendingListeners) listener();
118
+ }
119
+ function beginNavigation(): void {
120
+ startedTick += 1;
121
+ emitPending();
122
+ }
123
+
124
+ /** Marks the in-flight navigation as committed. Called by `Router` after each commit. */
125
+ export function settleNavigation(): void {
126
+ if (committedTick !== startedTick) {
127
+ committedTick = startedTick;
128
+ emitPending();
129
+ }
130
+ }
131
+
132
+ /** Whether a navigation is in flight (started but not yet committed). */
133
+ export function isNavigationPending(): boolean {
134
+ return startedTick !== committedTick;
135
+ }
136
+
137
+ /** Monotonic id incremented on each navigation, used to key/revalidate per-navigation route data. */
138
+ export function navigationEpoch(): number {
139
+ return startedTick;
140
+ }
141
+
142
+ /** Subscribes to navigation-pending changes; returns an unsubscribe function. */
143
+ export function subscribePending(listener: () => void): () => void {
144
+ pendingListeners.add(listener);
145
+ return () => {
146
+ pendingListeners.delete(listener);
147
+ };
148
+ }
149
+
150
+ /** Options for {@link navigate}. */
151
+ export interface NavigateOptions {
152
+ /** Replace the current history entry instead of pushing a new one. Default `false`. */
153
+ readonly replace?: boolean;
154
+ /** Scroll to the top of the page after navigating. Default `true`. */
155
+ readonly scroll?: boolean;
156
+ }
157
+
158
+ /** Initializes manual scroll restoration and the initial history key. Called once by `mount`. */
159
+ export function initNavigation(): void {
160
+ enableManualScrollRestoration();
161
+ const state = window.history.state as ToilHistoryState | null;
162
+ if (state?.__toilKey) {
163
+ currentKey = state.__toilKey;
164
+ } else {
165
+ currentKey = nextKey();
166
+ window.history.replaceState({ ...state, __toilKey: currentKey }, '');
167
+ }
168
+ }
169
+
170
+ /** Navigates to `href` without a full page reload (history push/replace + subscriber re-render). */
171
+ export function navigate(href: Href, options?: NavigateOptions): void {
172
+ beginNavigation();
173
+ rememberScroll(currentKey);
174
+ let hash = '';
175
+ try {
176
+ hash = new URL(href, window.location.href).hash;
177
+ } catch {
178
+ hash = '';
179
+ }
180
+ if (options?.replace) {
181
+ window.history.replaceState({ __toilKey: currentKey }, '', href);
182
+ } else {
183
+ currentKey = nextKey();
184
+ window.history.pushState({ __toilKey: currentKey }, '', href);
185
+ }
186
+ recordTransition(true);
187
+ planScroll({ hash, toTop: options?.scroll !== false });
188
+ notify();
189
+ }
190
+
191
+ /** Goes back one entry in history (fires `popstate`, which notifies subscribers). */
192
+ export function back(): void {
193
+ window.history.back();
194
+ }
195
+
196
+ /** Goes forward one entry in history. */
197
+ export function forward(): void {
198
+ window.history.forward();
199
+ }
200
+
201
+ /**
202
+ * Re-renders the current route, bumping the navigation epoch so a revalidation of the *same* URL
203
+ * re-keys its Suspense boundary (its `loading.tsx` shows while the loader re-runs) and
204
+ * `useNavigationPending` reports the in-flight refetch, instead of silently freezing the old page.
205
+ */
206
+ export function refresh(): void {
207
+ beginNavigation();
208
+ notify();
209
+ }
210
+
211
+ /** Handles browser back/forward: restores the saved scroll for the target entry, then re-renders. */
212
+ function handlePopState(event: PopStateEvent): void {
213
+ beginNavigation();
214
+ rememberScroll(currentKey);
215
+ const state = event.state as ToilHistoryState | null;
216
+ currentKey = state?.__toilKey ?? 'initial';
217
+ recordTransition(true);
218
+ planScroll({ restoreKey: currentKey, hash: window.location.hash, toTop: false });
219
+ notify();
220
+ }
221
+
222
+ /**
223
+ * Subscribes `listener` to location changes and returns an unsubscribe function. Browser
224
+ * back/forward is wired once, on the first subscription, via a shared `popstate` handler.
225
+ */
226
+ export function subscribeLocation(listener: () => void): () => void {
227
+ if (!popstateBound) {
228
+ window.addEventListener('popstate', handlePopState);
229
+ popstateBound = true;
230
+ }
231
+ listeners.add(listener);
232
+ return () => {
233
+ listeners.delete(listener);
234
+ };
235
+ }
@@ -27,6 +27,16 @@ export interface LoaderArgs {
27
27
  /** A route `loader`: `export const loader = ({ params }) => …` (sync or async). */
28
28
  export type LoaderFunction<T = unknown> = (args: LoaderArgs) => T | Promise<T>;
29
29
 
30
+ /** One concrete set of route params (a dynamic segment maps to a string, a catch-all to a string[]). */
31
+ export type StaticParams = Record<string, string | string[]>;
32
+
33
+ /**
34
+ * A route's `export const generateStaticParams`: returns the concrete param sets to pre-render at
35
+ * build time (SSG). toil enumerates them, runs the route's `generateMetadata` per set, and bakes a
36
+ * `<url>/index.html` + sitemap entry for each, so dynamic routes get build-time SEO. Build-only.
37
+ */
38
+ export type GenerateStaticParams = () => StaticParams[] | Promise<StaticParams[]>;
39
+
30
40
  /**
31
41
  * Per-route cache policy, set with `export const revalidate` in a route file:
32
42
  * - `0` (default): re-run the loader on every navigation to the route.