create-rasti 0.1.0-alpha.2 → 0.1.0-alpha.3

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/README.md CHANGED
@@ -46,7 +46,7 @@ Without either flag, the generated project uses plain CSS.
46
46
 
47
47
  ### `--router`
48
48
 
49
- Adds a small universal router built on [path-to-regexp](https://github.com/pillarjs/path-to-regexp). It is copied into the generated project as `src/lib/router.js`, then wired through `src/router-setup.js`, example pages, and an App shell with navigation.
49
+ Adds a small universal router built on [path-to-regexp](https://github.com/pillarjs/path-to-regexp). It is copied into the generated project as `src/lib/router.js`, then wired through `src/router-setup.js`, example pages, and an App shell with navigation. The project routes before mounting `App`, so a route can load its page as a chunk of its own: the example `About` page is code-split, and the hydrating client waits for it before rendering. The server loads every code-split page before its first render, so each response renders the same way whatever pages earlier requests loaded (with CSSFUN, every page embeds the style sheets of all of them).
50
50
 
51
51
  The router is intentionally narrow: route matching, URL creation, browser history, and delegated `a[data-router]` links. It works with SPA, SSR, and Static templates.
52
52
 
@@ -46,14 +46,14 @@ In the browser, links opt in to client-side navigation with `data-router`:
46
46
 
47
47
  | Method | Description |
48
48
  |---|---|
49
- | `navigate(url, options?)` | Matches `url`, updates browser history when available, invokes the matched route's `action(location)`, and returns the action result. Async actions return a Promise. Options: `{ addToHistory = true, replaceHistory = false, resetScroll = true }`. A navigation that adds or replaces a history entry scrolls to the top; pass `resetScroll : false` to keep the position, e.g. for a tab switch that only updates the query. |
49
+ | `navigate(url, options?)` | Matches `url`, updates browser history when available, invokes the matched route's `action(location, { signal })`, and returns the action result. Async actions return a Promise. Options: `{ addToHistory = true, replaceHistory = false, resetScroll = true }`. A navigation that adds or replaces a history entry scrolls once the action is done: to the element the URL hash names, or to the top. Pass `resetScroll : false` to keep the position, e.g. for a tab switch that only updates the query. |
50
50
  | `createUrl(path, params?, query?)` | Builds a URL from a route path, route params, and query params. |
51
- | `delegateNavigation(rootElement)` | Intercepts left-clicks on descendant `a[data-router]` links and routes them through `navigate`. Returns a cleanup function. |
52
- | `bindHistory()` | Listens for `popstate` and navigates to the current URL without pushing a new history entry or scrolling, so the browser restores the position. A `popstate` that keeps the path and query — a jump to an in-page anchor — is ignored. Returns a cleanup function. |
51
+ | `delegateNavigation(rootElement)` | Intercepts left-clicks on descendant `a[data-router]` links and routes them through `navigate`, hash included. If the action rejects, the link is followed with a full page load. Returns a cleanup function. |
52
+ | `bindHistory()` | Listens for `popstate` and navigates to the current URL without pushing a new history entry or scrolling, so the browser restores the position. A `popstate` that keeps the path and query — a jump to an in-page anchor — is ignored. If the action rejects, the page is reloaded. Returns a cleanup function. |
53
53
 
54
54
  **Options:** `{ baseUrl?: string }` — prepended to generated URLs and stripped before matching. It is only stripped as a prefix, on a path segment boundary: with `baseUrl: '/app'`, `/app/about` matches `/about` while `/application/x` and `/en/app-store/x` are left alone.
55
55
 
56
- **Route:** `{ path: string, action: (location) => any }`.
56
+ **Route:** `{ path: string, action: (location, context) => any }`. `context` is `{ signal: AbortSignal }`.
57
57
 
58
58
  **Location:** `{ path, params, query, test(url): boolean }` — `params` and `query` are plain objects; `test(url)` reports whether a URL matches the same route. Wildcard params (`/files/*rest`) are arrays of path segments, matching what `path-to-regexp` produces and what `createUrl` expects back.
59
59
 
@@ -87,9 +87,31 @@ Note that a param matches any single segment: `/user/:id` matches `/user/abc` as
87
87
 
88
88
  Without `replaceHistory`, the redirect leaves `/admin` in the back stack and the back button lands on a route that redirects again.
89
89
 
90
+ ## Async actions
91
+
92
+ An action may return a Promise, e.g. to import the module of a page before rendering it. `navigate` returns that Promise, and the scroll waits for it, so a hash target rendered by the page is there to scroll to.
93
+
94
+ A slow action can finish after the reader has moved on. Each action receives a `signal`, aborted as soon as a newer navigation starts — a click, a `popstate`, or a redirect from the action itself. Check it before rendering, so a late page does not replace the current one:
95
+
96
+ ```javascript
97
+ {
98
+ path : '/reports',
99
+ action : async (location, { signal }) => {
100
+ // The page is a chunk of its own, loaded on first visit.
101
+ const { default : Reports } = await import('./Reports.js');
102
+ if (signal.aborted) return;
103
+ model.page = Reports;
104
+ }
105
+ }
106
+ ```
107
+
108
+ The signal can also be handed to the requests the action makes, e.g. `fetch(url, { signal })`, to cancel them.
109
+
110
+ A rejected action rejects the Promise `navigate` returns, unless a newer navigation replaced it: then it resolves to `undefined`. Navigations the router starts on its own recover with a full page load instead: a link click loads its URL, and a `popstate` reloads the page. That covers a chunk that no longer exists after a new deploy.
111
+
90
112
  ## Links
91
113
 
92
- `delegateNavigation` only takes over a link it can own. It leaves the browser's default handling in place — no `preventDefault` — for cross-origin hrefs, `target` other than `_self`, `download`, and `rel="external"`. Modified and non-left clicks are ignored as usual.
114
+ `delegateNavigation` only takes over a link it can own. It leaves the browser's default handling in place — no `preventDefault` — for cross-origin hrefs, `target` other than `_self`, `download`, and `rel="external"`. Modified and non-left clicks are ignored as usual. A link to an anchor on the current page (same path and query, with a hash) is also left to the browser, which jumps to it without routing the page again.
93
115
 
94
116
  ## Copy model
95
117
 
@@ -13,17 +13,22 @@ import { match, compile } from 'path-to-regexp';
13
13
  * @property {(url: string) => boolean} test - A function to test if a given URL matches this route. Returns `true` if the URL matches the route, `false` otherwise.
14
14
  */
15
15
 
16
+ /**
17
+ * @typedef {Object} ActionContext
18
+ * @property {AbortSignal} signal - Aborted when a newer navigation starts, so an async action can skip rendering a page that is no longer current.
19
+ */
20
+
16
21
  /**
17
22
  * @typedef {Object} Route
18
23
  * @property {string} path - The route path pattern (e.g., `/user/:id`).
19
- * @property {(location: Location) => *} action - The action function to call when the route matches. Receives a `Location` object as parameter.
24
+ * @property {(location: Location, context: ActionContext) => *} action - The action function to call when the route matches. Receives a `Location` object and an `ActionContext`. It may return a Promise, e.g. to load the page before rendering it.
20
25
  */
21
26
 
22
27
  /**
23
28
  * @typedef {Object} NavigateOptions
24
29
  * @property {boolean} [addToHistory=true] - Whether to add the navigation to the browser's history.
25
30
  * @property {boolean} [replaceHistory=false] - Whether to replace the current history entry instead of adding a new one.
26
- * @property {boolean} [resetScroll=true] - Whether to scroll to the top when the navigation adds or replaces a history entry. A `popstate` never scrolls: the browser restores the position.
31
+ * @property {boolean} [resetScroll=true] - Whether to scroll when the navigation adds or replaces a history entry: to the element the URL hash names, or to the top. It happens once the action is done. A `popstate` never scrolls: the browser restores the position.
27
32
  */
28
33
 
29
34
  /**
@@ -54,6 +59,12 @@ export default function createRouter(routes, routerOptions = {}) {
54
59
  */
55
60
  const matchers = new Map();
56
61
 
62
+ /**
63
+ * Controller of the navigation in progress, aborted when a newer one starts.
64
+ * @type {AbortController|null}
65
+ */
66
+ let controller = null;
67
+
57
68
  /**
58
69
  * Path and query of the last URL routed, to tell a new page from an in-page anchor jump.
59
70
  * @type {string|null}
@@ -117,7 +128,7 @@ export default function createRouter(routes, routerOptions = {}) {
117
128
  /**
118
129
  * Matches a given url against the routes.
119
130
  * @param {string} url - The url to match.
120
- * @returns {(() => *)|null} - A function that calls the matched route's action with a `Location` object, or `null` if no match is found.
131
+ * @returns {({ route: Route, location: Location })|null} - The matched route and its `Location`, or `null` if no match is found.
121
132
  * @private
122
133
  */
123
134
  const matchRoute = (url) => {
@@ -135,7 +146,7 @@ export default function createRouter(routes, routerOptions = {}) {
135
146
  test : (url) => !!getMatch(getUrlParts(url).pathname, route.path)
136
147
  };
137
148
 
138
- return () => route.action(location);
149
+ return { route, location };
139
150
  }
140
151
  }
141
152
 
@@ -143,37 +154,96 @@ export default function createRouter(routes, routerOptions = {}) {
143
154
  };
144
155
 
145
156
  /**
146
- * Navigates to a given path, matches a route, and calls its action with a `Location` object.
147
- *
148
- * History is updated before the action runs, so an action that redirects can
149
- * replace the entry it was reached through: `navigate('/login', { replaceHistory : true })`.
150
- * The page scrolls to the top along with the history update, unless `resetScroll` is `false`.
151
- *
157
+ * Scrolls to the element the url hash names, or to the top of the page.
158
+ * @param {string} url - The url navigated to.
159
+ * @private
160
+ */
161
+ const scrollToUrl = (url) => {
162
+ const hash = url.split('#')[1];
163
+ let id = hash;
164
+ if (hash) {
165
+ try {
166
+ id = decodeURIComponent(hash);
167
+ } catch {
168
+ // A malformed escape names the element as written.
169
+ }
170
+ }
171
+ const target = id ? document.getElementById(id) : null;
172
+ if (target) target.scrollIntoView({ behavior : 'instant' });
173
+ else window.scrollTo({ top : 0, behavior : 'instant' });
174
+ };
175
+
176
+ /**
177
+ * Navigates to a url, calling `onError` if an async action rejects.
152
178
  * @param {string} url - The path to navigate to, including query string.
153
- * @param {NavigateOptions} [options={}] - Options for navigation.
154
- * @returns {*} The matched route action result, or `undefined` if no route matches. Async actions return a Promise.
179
+ * @param {NavigateOptions} options - Options for navigation.
180
+ * @param {(error: *) => *} [onError] - Handles a rejected action. Without it, the returned promise rejects.
181
+ * @returns {*} The matched route action result, or `undefined` if no route matches.
182
+ * @private
155
183
  */
156
- const navigate = (url, options = {}) => {
184
+ const go = (url, options, onError) => {
157
185
  const { addToHistory = true, replaceHistory = false, resetScroll = true } = options;
158
186
  // Match the route and query
159
187
  const matched = matchRoute(url);
160
188
 
161
- if (matched) {
162
- currentUrl = url.split('#')[0];
163
- // Handle browser history
164
- if (addToHistory && typeof window !== 'undefined') {
165
- window.history[replaceHistory ? 'replaceState' : 'pushState']({}, '', url);
166
- if (resetScroll) window.scrollTo({ top : 0, behavior : 'instant' });
167
- }
168
- // Call the route's action
169
- return matched();
170
- } else {
189
+ if (!matched) {
171
190
  console.error('No route matched:', url);
191
+ return undefined;
172
192
  }
173
193
 
174
- return undefined;
194
+ // A newer navigation supersedes the one in progress
195
+ controller?.abort();
196
+ const navigation = controller = new AbortController();
197
+ const { signal } = navigation;
198
+
199
+ currentUrl = url.split('#')[0];
200
+ // Handle browser history
201
+ if (addToHistory && typeof window !== 'undefined') {
202
+ window.history[replaceHistory ? 'replaceState' : 'pushState']({}, '', url);
203
+ }
204
+
205
+ // Scroll once the page is rendered, unless a newer navigation took over (e.g. a redirect)
206
+ const scroll = () => {
207
+ if (addToHistory && resetScroll && !signal.aborted && typeof window !== 'undefined') scrollToUrl(url);
208
+ };
209
+
210
+ // Call the route's action
211
+ const result = matched.route.action(matched.location, { signal });
212
+
213
+ if (!result || typeof result.then !== 'function') {
214
+ scroll();
215
+ return result;
216
+ }
217
+
218
+ return Promise.resolve(result).then(
219
+ (value) => {
220
+ scroll();
221
+ return value;
222
+ },
223
+ (error) => {
224
+ if (signal.aborted) return undefined;
225
+ if (onError) return onError(error);
226
+ throw error;
227
+ }
228
+ );
175
229
  };
176
230
 
231
+ /**
232
+ * Navigates to a given path, matches a route, and calls its action with a `Location` object.
233
+ *
234
+ * History is updated before the action runs, so an action that redirects can
235
+ * replace the entry it was reached through: `navigate('/login', { replaceHistory : true })`.
236
+ *
237
+ * The action receives a `signal` that is aborted when a newer navigation starts. When
238
+ * the action returns a Promise, `navigate` returns it, and the scroll waits for it. A
239
+ * superseded navigation that rejects resolves to `undefined` instead.
240
+ *
241
+ * @param {string} url - The path to navigate to, including query string.
242
+ * @param {NavigateOptions} [options={}] - Options for navigation.
243
+ * @returns {*} The matched route action result, or `undefined` if no route matches. Async actions return a Promise.
244
+ */
245
+ const navigate = (url, options = {}) => go(url, options);
246
+
177
247
  /**
178
248
  * Creates a URL from a route path, parameters, and query string.
179
249
  * @param {string} path - The route path (e.g., `/user/:id`).
@@ -192,7 +262,8 @@ export default function createRouter(routes, routerOptions = {}) {
192
262
  /**
193
263
  * Delegates navigation events for links with `data-router` attributes.
194
264
  * Links the router cannot own (cross-origin, `target`, `download`, `rel="external"`)
195
- * are left to the browser's default handling.
265
+ * are left to the browser's default handling, and so is an anchor on the current
266
+ * page. If the action rejects, the link is followed with a full page load.
196
267
  * @param {HTMLElement} rootElement - The root element to listen for click events.
197
268
  * @returns {() => void} - A function to undelegate the event listener.
198
269
  */
@@ -234,8 +305,12 @@ export default function createRouter(routes, routerOptions = {}) {
234
305
 
235
306
  if (url.origin !== window.location.origin) return;
236
307
 
308
+ const path = url.pathname + url.search;
309
+ // An anchor on the current page is a jump the browser already does.
310
+ if (url.hash && path === currentUrl) return;
311
+
237
312
  event.preventDefault();
238
- navigate(url.pathname + url.search);
313
+ go(path + url.hash, {}, () => window.location.replace(url.href));
239
314
  };
240
315
  // Bind the click event to the root element.
241
316
  rootElement.addEventListener('click', handleClick);
@@ -248,7 +323,7 @@ export default function createRouter(routes, routerOptions = {}) {
248
323
  /**
249
324
  * Binds browser history changes to the navigation logic.
250
325
  * A `popstate` that keeps the routed path and query, such as a jump to an in-page
251
- * anchor, is ignored. No-op outside the browser.
326
+ * anchor, is ignored. If the action rejects, the page is reloaded. No-op outside the browser.
252
327
  * @returns {() => void} - A function to unbind the `popstate` event listener.
253
328
  */
254
329
  const bindHistory = () => {
@@ -259,7 +334,7 @@ export default function createRouter(routes, routerOptions = {}) {
259
334
  // Routing the same URL again would re-render the page under the reader.
260
335
  if (url === currentUrl) return;
261
336
  // On popstate, navigate to the current URL
262
- navigate(url, { addToHistory : false });
337
+ go(url, { addToHistory : false }, () => window.location.reload());
263
338
  };
264
339
 
265
340
  window.addEventListener('popstate', handlePopState);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-rasti",
3
- "version": "0.1.0-alpha.2",
3
+ "version": "0.1.0-alpha.3",
4
4
  "description": "Create Rasti projects with Vite",
5
5
  "type": "module",
6
6
  "bin": {
@@ -40,16 +40,16 @@
40
40
  "author": "Alberto Masuelli <alberto.masuelli@gmail.com> (https://github.com/8tentaculos)",
41
41
  "license": "MIT",
42
42
  "dependencies": {
43
- "@clack/prompts": "^1.8.1",
44
- "cssfun": "^0.4.0-alpha.0",
45
- "rasti": "^5.0.0-alpha.4"
43
+ "@clack/prompts": "^1.9.0",
44
+ "cssfun": "^0.4.0-alpha.1",
45
+ "rasti": "^5.0.0-alpha.7"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@eslint/js": "^10.0.1",
49
- "eslint": "^10.13.0",
50
- "globals": "^17.13.0",
49
+ "eslint": "^10.15.0",
50
+ "globals": "^17.14.0",
51
51
  "path-to-regexp": "^9.0.0",
52
- "vitest": "^5.0.5"
52
+ "vitest": "^5.1.1"
53
53
  },
54
54
  "engines": {
55
55
  "node": ">=22"
@@ -17,7 +17,8 @@ function getRouterContext(plan) {
17
17
  ROUTE_ABOUT : routeAbout,
18
18
  CSSFUN : plan.features.cssfun ? 'true' : '',
19
19
  TAILWIND : plan.features.tailwind ? 'true' : '',
20
- ROUTER : 'true'
20
+ ROUTER : 'true',
21
+ SSR : plan.base === 'ssr' || plan.base === 'static' ? 'true' : ''
21
22
  };
22
23
  }
23
24
 
package/src/versions.js CHANGED
@@ -4,15 +4,15 @@
4
4
  * path-to-regexp are mirrored in package.json files, kept in sync by test/versions.test.js).
5
5
  */
6
6
  export const VERSIONS = {
7
- rasti : '^5.0.0-alpha.4',
8
- vite : '^8.3.5',
7
+ rasti : '^5.0.0-alpha.7',
8
+ vite : '^8.3.8',
9
9
  express : '^5.3.0',
10
10
  compression : '^1.8.2',
11
11
  sirv : '^3.0.2',
12
12
  crossEnv : '^10.1.0',
13
- tailwindcss : '^4.3.3',
14
- tailwindVite : '^4.3.3',
15
- cssfun : '^0.4.0-alpha.0',
13
+ tailwindcss : '^4.3.5',
14
+ tailwindVite : '^4.3.5',
15
+ cssfun : '^0.4.0-alpha.1',
16
16
  pathToRegexp : '^9.0.0',
17
17
  typescript : '^7.0.2',
18
18
  typesNode : '^22.20.5',
@@ -38,7 +38,7 @@ Presentational components live in `src/components/` and are written with `Compon
38
38
  Theming uses `src/theme.js` (light/dark via `data-color-scheme` on `<html>`; CSS variables prefixed `--fun-*`).
39
39
  {{#endif}}
40
40
  {{#if ROUTER}}
41
- Routing is handled by `src/router-setup.js` — routes update `state.location`; client-side links use the `data-router` attribute.
41
+ Routing is handled by `src/router-setup.{{SRC_EXT}}`: `route(url)` creates the model `App` renders and the router that sets its `location`, and the entry files await it before mounting. Rendering is synchronous, so a page kept in a chunk of its own (`lazy(() => import(...))`, like `About`) is loaded by its route action before the model changes.{{#if SSR}} The server loads every page `lazy` created before its first render (`loadPages`), so a new lazy page needs no other change.{{#endif}} Client-side links use the `data-router` attribute.
42
42
  {{#endif}}
43
43
  {{#if STATIC}}
44
44
  Routes to pre-render are listed in `static.config.js`.
@@ -58,6 +58,11 @@ Icon components generated from SVG live in `src/icons/`.
58
58
  - Spaces around colons in objects: `{ key : value }`
59
59
  - Component files are PascalCase; utilities are camelCase
60
60
  - Name callback props `handle*` (`handleIncrement`), never `on*`: those names belong to DOM events and lifecycle hooks
61
+ {{#if CSSFUN}}
62
+ {{#if ROUTER}}
63
+ - `@global` rules and the theme go in modules the entry imports (`App`, `theme.js`), never in a lazy page: once it loads, its global rules apply to every page
64
+ {{#endif}}
65
+ {{#endif}}
61
66
 
62
67
  ## Agent skills
63
68
 
@@ -3,8 +3,7 @@ import { css } from 'cssfun';
3
3
  import Header from './components/Header.js';
4
4
  import Home from './components/Home.js';
5
5
  {{#if ROUTER}}
6
- import About from './components/About.js';
7
- import { createAppRouter } from './router-setup.js';
6
+ import { About } from './router-setup.js';
8
7
  {{#endif}}
9
8
 
10
9
  const { classes } = css({
@@ -39,46 +38,38 @@ const { classes } = css({
39
38
  /**
40
39
  * @typedef {Object} AppState
41
40
  * @property {number} count
42
- {{#if ROUTER}}
43
- * @property {import('./lib/router.js').Location | null} location
44
- {{#endif}}
45
41
  */
46
42
  {{#if ROUTER}}
47
43
 
48
44
  /**
49
- * Options `App` is created with. Rasti keeps the ones it doesn't reserve as props.
45
+ * Options `App` is created with, along with the `model` from `route`. Rasti keeps the ones it doesn't reserve as props.
50
46
  * @typedef {Object} AppProps
51
- * @property {string} [url] - URL to route on creation (the request URL on the server).
47
+ * @property {import('./lib/router.js').Router} router - Router that updates the model, bound to links and history once hydrated.
52
48
  */
53
49
  {{#endif}}
54
50
 
55
51
  /**
56
52
  * Root application component with the global styles. Owns the state and passes values and callbacks down as props.
57
53
  {{#if ROUTER}}
58
- * @extends {Component<AppProps, AppState>}
54
+ * Renders the page at `model.location`, which `route` in `router-setup.js` sets.
55
+ * @extends {Component<AppProps, AppState, import('./router-setup.js').RouteState>}
59
56
  {{#else}}
60
57
  * @extends {Component<{}, AppState>}
61
58
  {{#endif}}
62
59
  */
63
60
  class App extends Component {
64
- {{#if ROUTER}}
65
- /** @param {AppProps} [options] */
66
- onCreate(options = {}) {
67
- this.state = new Model({ location : null, count : 0 });
68
- this.router = createAppRouter(this.state);
69
- this.router.navigate(options.url ?? '/', { addToHistory : false });
61
+ onCreate() {
62
+ this.state = new Model({ count : 0 });
70
63
  }
64
+ {{#if ROUTER}}
71
65
 
72
66
  onHydrate() {
67
+ const { router } = this.props;
73
68
  this.destroyQueue.push(
74
- this.router.delegateNavigation(this.el),
75
- this.router.bindHistory()
69
+ router.delegateNavigation(this.el),
70
+ router.bindHistory()
76
71
  );
77
72
  }
78
- {{#else}}
79
- onCreate() {
80
- this.state = new Model({ count : 0 });
81
- }
82
73
  {{#endif}}
83
74
 
84
75
  /** Created once per instance, so `Home` doesn't re-render for a new callback on every render. */
@@ -87,13 +78,18 @@ class App extends Component {
87
78
  };
88
79
 
89
80
  template() {
81
+ {{#if ROUTER}}
82
+ // `location` is null for a URL no route matches: no page renders.
83
+ const { location } = this.model;
84
+
85
+ {{#endif}}
90
86
  return this.html`
91
87
  <div class="${classes.root}">
92
88
  <${Header} />
93
89
  {{#if ROUTER}}
94
- ${this.state.location?.test('/') ?
90
+ ${location?.test('/') ?
95
91
  this.html`<${Home} count="${this.state.count}" handleIncrement=${this.handleIncrement} />` :
96
- this.html`<${About} />`}
92
+ location && this.html`<${About.Component} />`}
97
93
  {{#else}}
98
94
  <${Home} count="${this.state.count}" handleIncrement=${this.handleIncrement} />
99
95
  {{#endif}}
@@ -3,9 +3,9 @@ import { css } from 'cssfun';
3
3
  import Header from './components/Header.ts';
4
4
  import Home from './components/Home.ts';
5
5
  {{#if ROUTER}}
6
- import About from './components/About.ts';
7
- import { createAppRouter } from './router-setup.ts';
8
- import type { Location, Router } from './lib/router.js';
6
+ import { About } from './router-setup.ts';
7
+ import type { RouteModel } from './router-setup.ts';
8
+ import type { Router } from './lib/router.js';
9
9
  {{#endif}}
10
10
 
11
11
  const { classes } = css({
@@ -39,9 +39,6 @@ const { classes } = css({
39
39
 
40
40
  interface AppAttributes {
41
41
  count: number;
42
- {{#if ROUTER}}
43
- location: Location | null;
44
- {{#endif}}
45
42
  }
46
43
 
47
44
  /** Application state. Mutating it re-renders `App`. */
@@ -49,36 +46,31 @@ class AppState extends Model<AppAttributes> {}
49
46
  interface AppState extends AppAttributes {} // exposes the attributes on the model
50
47
 
51
48
  {{#if ROUTER}}
52
- /** Options `App` is created with. Rasti keeps the ones it doesn't reserve as props. */
49
+ /** Options `App` is created with, along with the `model` from `route`. Rasti keeps the ones it doesn't reserve as props. */
53
50
  export interface AppProps {
54
- /** URL to route on creation (the request URL on the server). */
55
- url?: string;
51
+ /** Router that updates the model, bound to links and history once hydrated. */
52
+ router: Router;
56
53
  }
57
54
 
58
55
  {{#endif}}
59
56
  /** Root application component with the global styles. Owns the state and passes values and callbacks down as props. */
60
57
  {{#if ROUTER}}
61
- class App extends Component<AppProps, AppState> {
62
- /** Set in `onCreate`, which runs in the base constructor: `declare` keeps a field initializer from resetting it. */
63
- declare router: Router;
64
-
65
- onCreate(options: AppProps = {}) {
66
- this.state = new AppState({ location : null, count : 0 });
67
- this.router = createAppRouter(this.state);
68
- this.router.navigate(options.url ?? '/', { addToHistory : false });
58
+ class App extends Component<AppProps, AppState, RouteModel> {
59
+ {{#else}}
60
+ class App extends Component<{}, AppState> {
61
+ {{#endif}}
62
+ onCreate() {
63
+ this.state = new AppState({ count : 0 });
69
64
  }
65
+ {{#if ROUTER}}
70
66
 
71
67
  onHydrate() {
68
+ const { router } = this.props;
72
69
  this.destroyQueue.push(
73
- this.router.delegateNavigation(this.el),
74
- this.router.bindHistory()
70
+ router.delegateNavigation(this.el),
71
+ router.bindHistory()
75
72
  );
76
73
  }
77
- {{#else}}
78
- class App extends Component<{}, AppState> {
79
- onCreate() {
80
- this.state = new AppState({ count : 0 });
81
- }
82
74
  {{#endif}}
83
75
 
84
76
  /** Created once per instance, so `Home` doesn't re-render for a new callback on every render. */
@@ -88,14 +80,18 @@ class App extends Component<{}, AppState> {
88
80
 
89
81
  template() {
90
82
  const state = this.state!;
83
+ {{#if ROUTER}}
84
+ // `location` is null for a URL no route matches: no page renders.
85
+ const { location } = this.model!;
86
+ {{#endif}}
91
87
 
92
88
  return this.html`
93
89
  <div class="${classes.root}">
94
90
  <${Header} />
95
91
  {{#if ROUTER}}
96
- ${state.location?.test('/') ?
92
+ ${location?.test('/') ?
97
93
  this.html`<${Home} count="${state.count}" handleIncrement=${this.handleIncrement} />` :
98
- this.html`<${About} />`}
94
+ location && this.html`<${About.Component} />`}
99
95
  {{#else}}
100
96
  <${Home} count="${state.count}" handleIncrement=${this.handleIncrement} />
101
97
  {{#endif}}
@@ -2,53 +2,44 @@ import { Component, Model } from 'rasti';
2
2
  import Header from './components/Header.js';
3
3
  import Home from './components/Home.js';
4
4
  {{#if ROUTER}}
5
- import About from './components/About.js';
6
- import { createAppRouter } from './router-setup.js';
5
+ import { About } from './router-setup.js';
7
6
  {{#endif}}
8
7
 
9
8
  /**
10
9
  * @typedef {Object} AppState
11
10
  * @property {number} count
12
- {{#if ROUTER}}
13
- * @property {import('./lib/router.js').Location | null} location
14
- {{#endif}}
15
11
  */
16
12
  {{#if ROUTER}}
17
13
 
18
14
  /**
19
- * Options `App` is created with. Rasti keeps the ones it doesn't reserve as props.
15
+ * Options `App` is created with, along with the `model` from `route`. Rasti keeps the ones it doesn't reserve as props.
20
16
  * @typedef {Object} AppProps
21
- * @property {string} [url] - URL to route on creation (the request URL on the server).
17
+ * @property {import('./lib/router.js').Router} router - Router that updates the model, bound to links and history once hydrated.
22
18
  */
23
19
  {{#endif}}
24
20
 
25
21
  /**
26
22
  * Root application component. Owns the state and passes values and callbacks down as props.
27
23
  {{#if ROUTER}}
28
- * @extends {Component<AppProps, AppState>}
24
+ * Renders the page at `model.location`, which `route` in `router-setup.js` sets.
25
+ * @extends {Component<AppProps, AppState, import('./router-setup.js').RouteState>}
29
26
  {{#else}}
30
27
  * @extends {Component<{}, AppState>}
31
28
  {{#endif}}
32
29
  */
33
30
  class App extends Component {
34
- {{#if ROUTER}}
35
- /** @param {AppProps} [options] */
36
- onCreate(options = {}) {
37
- this.state = new Model({ location : null, count : 0 });
38
- this.router = createAppRouter(this.state);
39
- this.router.navigate(options.url ?? '/', { addToHistory : false });
31
+ onCreate() {
32
+ this.state = new Model({ count : 0 });
40
33
  }
34
+ {{#if ROUTER}}
41
35
 
42
36
  onHydrate() {
37
+ const { router } = this.props;
43
38
  this.destroyQueue.push(
44
- this.router.delegateNavigation(this.el),
45
- this.router.bindHistory()
39
+ router.delegateNavigation(this.el),
40
+ router.bindHistory()
46
41
  );
47
42
  }
48
- {{#else}}
49
- onCreate() {
50
- this.state = new Model({ count : 0 });
51
- }
52
43
  {{#endif}}
53
44
 
54
45
  /** Created once per instance, so `Home` doesn't re-render for a new callback on every render. */
@@ -57,13 +48,18 @@ class App extends Component {
57
48
  };
58
49
 
59
50
  template() {
51
+ {{#if ROUTER}}
52
+ // `location` is null for a URL no route matches: no page renders.
53
+ const { location } = this.model;
54
+
55
+ {{#endif}}
60
56
  return this.html`
61
57
  <div class="font-sans flex min-h-dvh flex-col items-center gap-6 md:gap-10 max-w-[1000px] mx-auto p-5 md:p-12 box-border text-white">
62
58
  <${Header} />
63
59
  {{#if ROUTER}}
64
- ${this.state.location?.test('/') ?
60
+ ${location?.test('/') ?
65
61
  this.html`<${Home} count="${this.state.count}" handleIncrement=${this.handleIncrement} />` :
66
- this.html`<${About} />`}
62
+ location && this.html`<${About.Component} />`}
67
63
  {{#else}}
68
64
  <${Home} count="${this.state.count}" handleIncrement=${this.handleIncrement} />
69
65
  {{#endif}}