create-rasti 0.0.2 → 0.1.0-alpha.1

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 (56) hide show
  1. package/README.md +21 -2
  2. package/extras/cn/src/index.js +14 -1
  3. package/extras/micro-router/README.md +36 -4
  4. package/extras/micro-router/package.json +1 -1
  5. package/extras/micro-router/src/index.js +129 -47
  6. package/extras/rasti-icons/README.md +15 -5
  7. package/extras/rasti-icons/src/generate.js +96 -49
  8. package/package.json +9 -6
  9. package/src/apply/agents.js +68 -0
  10. package/src/apply/base.js +1 -1
  11. package/src/apply/description.js +2 -0
  12. package/src/apply/featuresInclude.js +3 -2
  13. package/src/apply/index.js +13 -37
  14. package/src/apply/router.js +2 -2
  15. package/src/apply/ssr.js +1 -1
  16. package/src/apply/typescript.js +38 -0
  17. package/src/args.js +3 -0
  18. package/src/cli.js +2 -0
  19. package/src/plan.js +2 -1
  20. package/src/prompts.js +17 -0
  21. package/src/utils/template.js +32 -15
  22. package/src/versions.js +16 -12
  23. package/templates/AGENTS.md +31 -8
  24. package/templates/_base/App-cssfun.js +40 -23
  25. package/templates/_base/App-cssfun.ts +107 -0
  26. package/templates/_base/App-tailwind.js +39 -22
  27. package/templates/_base/App-tailwind.ts +77 -0
  28. package/templates/_base/App.js +39 -22
  29. package/templates/_base/App.ts +77 -0
  30. package/templates/_base/components/Button-cssfun.ts +54 -0
  31. package/templates/_base/components/Button-tailwind.ts +55 -0
  32. package/templates/_base/components/Button.ts +25 -0
  33. package/templates/_base/components/Header-cssfun.ts +71 -0
  34. package/templates/_base/components/Header-tailwind.ts +19 -0
  35. package/templates/_base/components/Header.ts +19 -0
  36. package/templates/_base/components/Home-cssfun.ts +101 -0
  37. package/templates/_base/components/Home-tailwind.ts +38 -0
  38. package/templates/_base/components/Home.ts +38 -0
  39. package/templates/_extras/router/components/About-cssfun.ts +45 -0
  40. package/templates/_extras/router/components/About-tailwind.ts +16 -0
  41. package/templates/_extras/router/components/About.ts +18 -0
  42. package/templates/_extras/router/router-setup.js +21 -21
  43. package/templates/_extras/router/router-setup.ts +52 -0
  44. package/templates/_features/cssfun/index.html +1 -1
  45. package/templates/_features/typescript/tsconfig.json +30 -0
  46. package/templates/spa/index.html +1 -1
  47. package/templates/spa/src/main.js +1 -2
  48. package/templates/spa/src/main.ts +14 -0
  49. package/templates/ssr/app.js +10 -10
  50. package/templates/ssr/index.html +1 -1
  51. package/templates/ssr/package.json +1 -1
  52. package/templates/ssr/src/entry-client.js +2 -1
  53. package/templates/ssr/src/entry-client.ts +28 -0
  54. package/templates/ssr/src/entry-server.js +31 -25
  55. package/templates/ssr/src/entry-server.ts +62 -0
  56. package/templates/static/scripts/build-static.js +11 -1
package/README.md CHANGED
@@ -34,6 +34,14 @@ Styling options are mutually exclusive:
34
34
 
35
35
  Without either flag, the generated project uses plain CSS.
36
36
 
37
+ ## TypeScript
38
+
39
+ **`--ts`** (or `--typescript`) writes the app in TypeScript, with every template and styling option:
40
+
41
+ - The sources in `src/` are `.ts`, with components written as `Component` subclasses, the form Rasti types best.
42
+ - `tsconfig.json` is strict, and Vite strips the types. `npm run typecheck` runs `tsc`, and so does `npm run build` before building.
43
+ - The router, `cn` and icon components stay JavaScript typed with JSDoc, and so does the Express server in SSR projects. `tsc` checks them too (`checkJs`).
44
+
37
45
  ## Extras
38
46
 
39
47
  ### `--router`
@@ -47,10 +55,18 @@ The router is intentionally narrow: route matching, URL creation, browser histor
47
55
  Generates one Rasti component per SVG icon under `src/icons/`:
48
56
 
49
57
  ```js
58
+ import { Component } from 'rasti';
50
59
  import Heart from './icons/Heart.js';
51
- // <Heart className="..." width={24} height={24} />
60
+
61
+ const LikeButton = Component.create`
62
+ <button>
63
+ <${Heart} className="icon" size="20" label="Like" />
64
+ </button>
65
+ `;
52
66
  ```
53
67
 
68
+ Icons are decorative (`aria-hidden`) unless they get a `label`. See [rasti-icons](extras/rasti-icons/README.md) for all props.
69
+
54
70
  A single preset writes components directly to `src/icons/`. Multiple presets write each set under `src/icons/<preset>/`.
55
71
 
56
72
  | Preset | Source | License |
@@ -63,7 +79,9 @@ A single preset writes components directly to `src/icons/`. Multiple presets wri
63
79
 
64
80
  SVGs are downloaded from GitHub when the project is generated, so this option requires an internet connection.
65
81
 
66
- The CLI writes an `AGENTS.md` to the generated project root with project-specific context (stack, commands, architecture, conventions). It also tries to fetch Rasti's `AGENTS.md` as `AGENTS-RASTI.md`; if that request fails, project generation continues without it.
82
+ ## Agents
83
+
84
+ The CLI writes an `AGENTS.md` to the generated project root with project-specific context (stack, commands, architecture, conventions). It also installs the [Agent Skills](https://agentskills.io) that ship with the libraries the project uses — `rasti` always, `cssfun` with `--cssfun` — in `.agents/skills/`, linked from `.claude/skills/`. The skills come from the CLI's own copy of each package, on the same version range the project depends on, so no network is needed.
67
85
 
68
86
  ## Flags
69
87
 
@@ -75,6 +93,7 @@ The CLI writes an `AGENTS.md` to the generated project root with project-specifi
75
93
  | `--cssfun` | Add CSSFUN |
76
94
  | `--router` | Add micro-router |
77
95
  | `--icons [preset[,preset]]` | Add rasti-icons (default preset: `heroicons-outline`) |
96
+ | `--ts` | Write the app in TypeScript (alias: `--typescript`) |
78
97
  | `--help` | Show help |
79
98
 
80
99
  `--ssr`/`--static` and `--tailwind`/`--cssfun` are mutually exclusive.
@@ -1,5 +1,18 @@
1
+ /**
2
+ * @typedef {string|number|boolean|null|undefined|Record<string, *>|Array<*>} ClassValue
3
+ */
4
+
5
+ /**
6
+ * @param {string} a
7
+ * @param {string|number} b
8
+ * @returns {string}
9
+ */
1
10
  const add = (a, b) => a && b ? a + ' ' + b : '' + (a || b);
2
11
 
12
+ /**
13
+ * @param {Array<*>} classes
14
+ * @returns {string}
15
+ */
3
16
  const parse = (classes) => {
4
17
  let out = '';
5
18
 
@@ -23,7 +36,7 @@ const parse = (classes) => {
23
36
  * Accepts strings, numbers, arrays (nested supported) and objects whose keys
24
37
  * are included when their value is truthy. Falsy values are skipped.
25
38
  *
26
- * @param {...(string|number|Array|Object|null|undefined|boolean)} args - Class name values to join.
39
+ * @param {...ClassValue} args - Class name values to join.
27
40
  * @returns {string} The merged class name string.
28
41
  *
29
42
  * @example
@@ -46,19 +46,51 @@ 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 }`. |
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. |
50
50
  | `createUrl(path, params?, query?)` | Builds a URL from a route path, route params, and query params. |
51
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. 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. |
53
53
 
54
- **Options:** `{ baseUrl?: string }` — prepended to generated URLs and stripped before matching.
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
56
  **Route:** `{ path: string, action: (location) => any }`.
57
57
 
58
- **Location:** `{ path, params, query, test(url): boolean }` — `params` and `query` are plain objects; `test(url)` reports whether a URL matches the same route.
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
+
60
+ The fragment is dropped before matching: `/about#section` matches `/about`, and `#section` never leaks into `query`.
59
61
 
60
62
  Full type signatures live in the JSDoc of `src/index.js`.
61
63
 
64
+ ## Untrusted input
65
+
66
+ `params` and `query` are decoded but never transformed. They are attacker-controlled: anyone can craft a URL.
67
+
68
+ The router does not escape them. Escaping is only meaningful against a known sink — HTML text, an attribute, a `href`, a query, JSON — and the router does not know where a value ends up.
69
+
70
+ Escape at the point of output, in the context of that output. Template engines that escape interpolations automatically — Rasti's `Component.sanitize` among them — already cover the common case; manual `innerHTML`, `href`, or query building do not.
71
+
72
+ Note that a param matches any single segment: `/user/:id` matches `/user/abc` as readily as `/user/123`. `path-to-regexp` v8 dropped inline patterns, so a route cannot narrow this — validate in the action and decide there what a bad param means (404, redirect, coercion).
73
+
74
+ ## Redirects
75
+
76
+ `navigate` updates history before running the action, so an action that redirects can replace the entry it was reached through:
77
+
78
+ ```javascript
79
+ {
80
+ path : '/admin',
81
+ action : (location) => {
82
+ if (!session.user) return router.navigate('/login', { replaceHistory : true });
83
+ // ...
84
+ }
85
+ }
86
+ ```
87
+
88
+ Without `replaceHistory`, the redirect leaves `/admin` in the back stack and the back button lands on a route that redirects again.
89
+
90
+ ## Links
91
+
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.
93
+
62
94
  ## Copy model
63
95
 
64
96
  This package is meant to be copied into an application, not installed as a public runtime dependency. `create-rasti --router` copies `src/index.js` into the generated project as `src/lib/router.js` and adds `path-to-regexp` to that project's dependencies.
@@ -6,7 +6,7 @@
6
6
  "type" : "module",
7
7
  "main" : "src/index.js",
8
8
  "dependencies" : {
9
- "path-to-regexp" : "^8.0.0"
9
+ "path-to-regexp" : "^9.0.0"
10
10
  },
11
11
  "license" : "MIT"
12
12
  }
@@ -1,30 +1,46 @@
1
1
  import { match, compile } from 'path-to-regexp';
2
2
 
3
+ /**
4
+ * Route parameters by name. Wildcard parameters (e.g. `*rest`) are arrays of path segments.
5
+ * @typedef {Record<string, (string|Array<string>)>} Params
6
+ */
7
+
3
8
  /**
4
9
  * @typedef {Object} Location
5
10
  * @property {string} path - The route path pattern (e.g., `/user/:id`).
6
- * @property {Object.<string, string>} params - The route parameters extracted from the URL path, sanitized to prevent injection attacks.
7
- * @property {Object.<string, string>} query - The query parameters parsed from the URL query string.
8
- * @property {function(string): boolean} test - A function to test if a given URL matches this route. Returns `true` if the URL matches the route, `false` otherwise.
11
+ * @property {Params} params - Route parameters decoded from the URL path. Wildcard parameters (e.g. `*rest`) are arrays of path segments. Untrusted input: escape at the point of output.
12
+ * @property {Record<string, string>} query - Query parameters parsed from the URL query string. Untrusted input, same as `params`.
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.
9
14
  */
10
15
 
11
16
  /**
12
17
  * @typedef {Object} Route
13
18
  * @property {string} path - The route path pattern (e.g., `/user/:id`).
14
- * @property {function(Location): *} action - The action function to call when the route matches. Receives a `Location` object as parameter.
19
+ * @property {(location: Location) => *} action - The action function to call when the route matches. Receives a `Location` object as parameter.
20
+ */
21
+
22
+ /**
23
+ * @typedef {Object} NavigateOptions
24
+ * @property {boolean} [addToHistory=true] - Whether to add the navigation to the browser's history.
25
+ * @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.
15
27
  */
16
28
 
17
29
  /**
18
30
  * @typedef {Object} Router
19
- * @property {function(string, Object=): *} navigate - Navigates to a given URL, matches a route, and returns its action result.
20
- * @property {function(string, Object=, Object=): string} createUrl - Creates a URL from a route path, parameters, and query string.
21
- * @property {function(HTMLElement): function(): void} delegateNavigation - Delegates navigation events for links with `data-router` attributes. Returns a cleanup function.
22
- * @property {function(): function(): void} bindHistory - Binds browser history changes to the navigation logic. Returns a cleanup function.
31
+ * @property {(url: string, options?: NavigateOptions) => *} navigate - Navigates to a given URL, matches a route, and returns its action result.
32
+ * @property {(path: string, params?: Params, query?: Record<string, string>) => string} createUrl - Creates a URL from a route path, parameters, and query string.
33
+ * @property {(rootElement: HTMLElement) => () => void} delegateNavigation - Delegates navigation events for links with `data-router` attributes. Returns a cleanup function.
34
+ * @property {() => () => void} bindHistory - Binds browser history changes to the navigation logic. Returns a cleanup function.
23
35
  */
24
36
 
25
37
  /**
26
38
  * Creates a router with navigation, URL creation, and event delegation.
27
- * @param {Array.<Route>} routes - Array of route objects. Each route must have a `path` and an `action` function.
39
+ *
40
+ * `params` and `query` on a `Location` come from the URL and are decoded but not
41
+ * escaped. Escape them at the point of output, in the context of that output.
42
+ *
43
+ * @param {Array<Route>} routes - Array of route objects. Each route must have a `path` and an `action` function.
28
44
  * @param {Object} [routerOptions={}] - Options for the router.
29
45
  * @param {string} [routerOptions.baseUrl=''] - A base URL to prepend to all routes and navigation.
30
46
  * @returns {Router} - Router object with navigation, URL creation, and event delegation methods.
@@ -32,33 +48,76 @@ import { match, compile } from 'path-to-regexp';
32
48
  export default function createRouter(routes, routerOptions = {}) {
33
49
  const { baseUrl = '' } = routerOptions;
34
50
 
51
+ /**
52
+ * Compiled matchers, keyed by route path. Built on first match and reused afterwards.
53
+ * @type {Map<string, import('path-to-regexp').MatchFunction<Params>>}
54
+ */
55
+ const matchers = new Map();
56
+
57
+ /**
58
+ * Path and query of the last URL routed, to tell a new page from an in-page anchor jump.
59
+ * @type {string|null}
60
+ */
61
+ let currentUrl = null;
62
+
63
+ /**
64
+ * Removes `baseUrl` from the start of a pathname.
65
+ * Only strips on a path segment boundary, so a `baseUrl` of `/app` leaves
66
+ * `/application/x` untouched.
67
+ * @param {string} pathname - The pathname to strip.
68
+ * @returns {string} - The pathname without the base url.
69
+ * @private
70
+ */
71
+ const stripBaseUrl = (pathname) => {
72
+ if (!baseUrl || !pathname.startsWith(baseUrl)) return pathname;
73
+
74
+ const rest = pathname.slice(baseUrl.length);
75
+ return rest === '' || rest.startsWith('/') ? rest : pathname;
76
+ };
77
+
35
78
  /**
36
79
  * Gets the pathname and query string from a given url.
80
+ * The fragment is dropped: it takes no part in matching.
37
81
  * @param {string} url - The url to get the pathname and query string from.
38
- * @returns {Object} - The pathname and query string.
82
+ * @returns {{ pathname: string, query: (string|undefined) }} - The pathname and query string.
39
83
  * @private
40
84
  */
41
85
  const getUrlParts = (url) => {
42
- const [pathname, query] = url.replace(baseUrl, '').split('?');
43
- return { pathname, query };
86
+ const [pathname, query] = url.split('#')[0].split('?');
87
+ // Stripping the whole pathname (a url equal to `baseUrl`) leaves the root route.
88
+ return { pathname : stripBaseUrl(pathname) || '/', query };
89
+ };
90
+
91
+ /**
92
+ * Gets the memoized matcher for a route path.
93
+ * @param {string} routePath - The route path to match against.
94
+ * @returns {import('path-to-regexp').MatchFunction<Params>} - The matcher function.
95
+ * @private
96
+ */
97
+ const getMatcher = (routePath) => {
98
+ let matcher = matchers.get(routePath);
99
+
100
+ if (!matcher) {
101
+ matcher = /** @type {import('path-to-regexp').MatchFunction<Params>} */ (match(routePath, { decode : decodeURIComponent }));
102
+ matchers.set(routePath, matcher);
103
+ }
104
+
105
+ return matcher;
44
106
  };
45
107
 
46
108
  /**
47
109
  * Gets the match result from a given pathname and route path.
48
110
  * @param {string} pathname - The pathname to match.
49
111
  * @param {string} routePath - The route path to match.
50
- * @returns {Object|null} - The match result, or `null` if no match is found.
112
+ * @returns {import('path-to-regexp').Match<Params>} - The match result, or `false` if no match is found.
51
113
  * @private
52
114
  */
53
- const getMatch = (pathname, routePath) => {
54
- const matcher = match(routePath, { decode : decodeURIComponent });
55
- return matcher(pathname);
56
- };
115
+ const getMatch = (pathname, routePath) => getMatcher(routePath)(pathname);
57
116
 
58
117
  /**
59
118
  * Matches a given url against the routes.
60
119
  * @param {string} url - The url to match.
61
- * @returns {(function(): *)|null} - A function that calls the matched route's action with a `Location` object, or `null` if no match is found.
120
+ * @returns {(() => *)|null} - A function that calls the matched route's action with a `Location` object, or `null` if no match is found.
62
121
  * @private
63
122
  */
64
123
  const matchRoute = (url) => {
@@ -71,7 +130,7 @@ export default function createRouter(routes, routerOptions = {}) {
71
130
  /** @type {Location} */
72
131
  const location = {
73
132
  path : route.path,
74
- params : sanitizeParams(matched.params),
133
+ params : matched.params,
75
134
  query : Object.fromEntries(new URLSearchParams(query).entries()),
76
135
  test : (url) => !!getMatch(getUrlParts(url).pathname, route.path)
77
136
  };
@@ -85,21 +144,26 @@ export default function createRouter(routes, routerOptions = {}) {
85
144
 
86
145
  /**
87
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
+ *
88
152
  * @param {string} url - The path to navigate to, including query string.
89
- * @param {Object} [options={}] - Options for navigation.
90
- * @param {boolean} [options.addToHistory=true] - Whether to add the navigation to the browser's history.
91
- * @param {boolean} [options.replaceHistory=false] - Whether to replace the current history entry instead of adding a new one.
153
+ * @param {NavigateOptions} [options={}] - Options for navigation.
92
154
  * @returns {*} The matched route action result, or `undefined` if no route matches. Async actions return a Promise.
93
155
  */
94
156
  const navigate = (url, options = {}) => {
95
- const { addToHistory = true, replaceHistory = false } = options;
157
+ const { addToHistory = true, replaceHistory = false, resetScroll = true } = options;
96
158
  // Match the route and query
97
159
  const matched = matchRoute(url);
98
160
 
99
161
  if (matched) {
162
+ currentUrl = url.split('#')[0];
100
163
  // Handle browser history
101
164
  if (addToHistory && typeof window !== 'undefined') {
102
165
  window.history[replaceHistory ? 'replaceState' : 'pushState']({}, '', url);
166
+ if (resetScroll) window.scrollTo({ top : 0, behavior : 'instant' });
103
167
  }
104
168
  // Call the route's action
105
169
  return matched();
@@ -113,8 +177,8 @@ export default function createRouter(routes, routerOptions = {}) {
113
177
  /**
114
178
  * Creates a URL from a route path, parameters, and query string.
115
179
  * @param {string} path - The route path (e.g., `/user/:id`).
116
- * @param {Object.<string, string>} [params={}] - Parameters to replace in the path (e.g., `{ id : '123' }` for `/user/:id`).
117
- * @param {Object.<string, string>} [query={}] - Query parameters to append to the URL (e.g., `{ page : '1', sort : 'name' }`).
180
+ * @param {Params} [params={}] - Parameters to replace in the path (e.g., `{ id : '123' }` for `/user/:id`). Wildcard parameters take an array of segments.
181
+ * @param {Record<string, string>} [query={}] - Query parameters to append to the URL (e.g., `{ page : '1', sort : 'name' }`).
118
182
  * @returns {string} - The generated URL with query parameters.
119
183
  */
120
184
  const createUrl = (path, params = {}, query = {}) => {
@@ -127,10 +191,13 @@ export default function createRouter(routes, routerOptions = {}) {
127
191
 
128
192
  /**
129
193
  * Delegates navigation events for links with `data-router` attributes.
194
+ * Links the router cannot own (cross-origin, `target`, `download`, `rel="external"`)
195
+ * are left to the browser's default handling.
130
196
  * @param {HTMLElement} rootElement - The root element to listen for click events.
131
- * @returns {Function} - A function to undelegate the event listener.
197
+ * @returns {() => void} - A function to undelegate the event listener.
132
198
  */
133
199
  const delegateNavigation = (rootElement) => {
200
+ /** @param {MouseEvent} event */
134
201
  const handleClick = (event) => {
135
202
  if (
136
203
  event.defaultPrevented ||
@@ -140,14 +207,35 @@ export default function createRouter(routes, routerOptions = {}) {
140
207
  return;
141
208
  }
142
209
 
143
- const anchor = event.target.closest('a[data-router]');
210
+ const target = /** @type {Element|null} */ (event.target);
211
+ const anchor = /** @type {HTMLAnchorElement|SVGAElement|null} */ (
212
+ typeof target?.closest === 'function' ? target.closest('a[data-router]') : null
213
+ );
214
+
215
+ if (!anchor) return;
144
216
 
145
- if (anchor && anchor.href) {
146
- event.preventDefault();
147
- const url = new URL(anchor.href);
148
- window.scrollTo({ top : 0, behavior : 'instant' });
149
- navigate(url.pathname + url.search);
217
+ const anchorTarget = anchor.getAttribute('target');
218
+ const rel = anchor.getAttribute('rel');
219
+
220
+ if (
221
+ anchor.hasAttribute('download') ||
222
+ (anchorTarget && anchorTarget !== '_self') ||
223
+ (rel && rel.split(/\s+/).includes('external'))
224
+ ) {
225
+ return;
150
226
  }
227
+
228
+ // `href` is an absolute string on HTML anchors; SVG anchors need the raw attribute.
229
+ const href = typeof anchor.href === 'string' ? anchor.href : anchor.getAttribute('href');
230
+
231
+ if (href === null) return;
232
+
233
+ const url = new URL(href, window.location.href);
234
+
235
+ if (url.origin !== window.location.origin) return;
236
+
237
+ event.preventDefault();
238
+ navigate(url.pathname + url.search);
151
239
  };
152
240
  // Bind the click event to the root element.
153
241
  rootElement.addEventListener('click', handleClick);
@@ -159,12 +247,19 @@ export default function createRouter(routes, routerOptions = {}) {
159
247
 
160
248
  /**
161
249
  * Binds browser history changes to the navigation logic.
162
- * @returns {Function} - A function to unbind the `popstate` event listener.
250
+ * 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.
252
+ * @returns {() => void} - A function to unbind the `popstate` event listener.
163
253
  */
164
254
  const bindHistory = () => {
255
+ if (typeof window === 'undefined') return () => {};
256
+
165
257
  const handlePopState = () => {
258
+ const url = window.location.pathname + window.location.search;
259
+ // Routing the same URL again would re-render the page under the reader.
260
+ if (url === currentUrl) return;
166
261
  // On popstate, navigate to the current URL
167
- navigate(window.location.pathname + window.location.search, { addToHistory : false });
262
+ navigate(url, { addToHistory : false });
168
263
  };
169
264
 
170
265
  window.addEventListener('popstate', handlePopState);
@@ -175,18 +270,5 @@ export default function createRouter(routes, routerOptions = {}) {
175
270
  };
176
271
  };
177
272
 
178
- /**
179
- * Sanitizes route parameters to prevent injection attacks.
180
- * @param {Object} params - The route parameters.
181
- * @returns {Object} - The sanitized parameters.
182
- */
183
- const sanitizeParams = (params) => {
184
- const sanitized = {};
185
- for (const [key, value] of Object.entries(params)) {
186
- sanitized[key] = String(value).replace(/[<>]/g, '');
187
- }
188
- return sanitized;
189
- };
190
-
191
273
  return { navigate, createUrl, delegateNavigation, bindHistory };
192
274
  }
@@ -42,18 +42,28 @@ node bin/rasti-icons.js \
42
42
 
43
43
  ## Generated components
44
44
 
45
- Each SVG file becomes a Rasti component. The generated component accepts optional `props.className`, `props.width`, and `props.height`. If width or height is not provided, the original SVG dimensions are used.
45
+ Each SVG file becomes a Rasti component. All props are optional:
46
+
47
+ | Prop | Description |
48
+ |---|---|
49
+ | `className` | Class of the `<svg>` element. Without it, no `class` attribute is written. |
50
+ | `size` | Width and height. Defaults to the original SVG dimensions. |
51
+ | `width`, `height` | Override `size` for one dimension. |
52
+ | `label` | Accessible name: renders `role="img"` and `aria-label`. Without it the icon is decorative and gets `aria-hidden="true"`. |
46
53
 
47
54
  ```javascript
55
+ import { Component } from 'rasti';
48
56
  import Heart from './icons/Heart.js';
49
57
 
50
- // Mount with default size.
51
- Heart.mount({}, container);
58
+ // In a template — decorative, at the original size.
59
+ const Liked = Component.create`<p><${Heart} className="icon" /> Liked</p>`;
52
60
 
53
- // Mount with custom class and size.
54
- Heart.mount({ className : 'icon icon-red', width : '32', height : '32' }, container);
61
+ // Standalone — custom size, with an accessible name.
62
+ Heart.mount({ size : 32, label : 'Favorite' }, container);
55
63
  ```
56
64
 
65
+ Icons follow the text color: hardcoded black fills and strokes are turned into `currentColor`. The generator also drops what an inline icon doesn't need — XML prolog, comments, `title`, `desc`, namespace declarations and unreferenced ids.
66
+
57
67
  Icon filenames are converted from `kebab-case.svg` to `PascalCase.js`.
58
68
 
59
69
  ## Licenses
@@ -1,6 +1,15 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
 
4
+ /** Hardcoded black, which keeps an icon from following the text color. */
5
+ const BLACK_PAINT = /\s(fill|stroke)="(?:black|#000|#000000)"/gi;
6
+
7
+ /**
8
+ * Root attributes the component renders from its props, plus namespace
9
+ * declarations, which inline SVG in HTML takes from the parser instead.
10
+ */
11
+ const ROOT_ATTRIBUTES = /\s(?:class|width|height|role|aria-label|aria-hidden|xmlns(?::\w+)?)="[^"]*"/g;
12
+
4
13
  /**
5
14
  * Convert kebab-case SVG filename to PascalCase component name.
6
15
  * @param {string} filename - e.g. 'arrow-right.svg'
@@ -21,8 +30,8 @@ function toPascalCase(filename) {
21
30
  * @returns {string} Numeric string, e.g. '24'
22
31
  */
23
32
  function extractSize(tag, dim) {
24
- // Match only real SVG width/height attributes (not stroke-width, etc.)
25
- const direct = tag.match(new RegExp(`\\s${dim}="(\\d+(?:\\.\\d+)?)"`));
33
+ // Match only real SVG width/height attributes (not stroke-width, etc.); `px` units are dropped.
34
+ const direct = tag.match(new RegExp(`\\s${dim}="(\\d+(?:\\.\\d+)?)(?:px)?"`));
26
35
  if (direct) return direct[1];
27
36
  const vb = tag.match(/\bviewBox="[\d.]+ [\d.]+ ([\d.]+) ([\d.]+)"/);
28
37
  if (vb) return dim === 'width' ? vb[1] : vb[2];
@@ -30,34 +39,92 @@ function extractSize(tag, dim) {
30
39
  }
31
40
 
32
41
  /**
33
- * Transform raw SVG content into a Rasti component template body.
34
- * Replaces/adds class, width, height with dynamic props expressions.
42
+ * Re-indent the lines inside the `<svg>` element, one level per nesting step
43
+ * of the source, whatever indentation width the source used.
44
+ * @param {string} body - Markup between the opening and closing `<svg>` tags
45
+ * @param {string} indent - Indentation of the children
46
+ * @returns {string} Re-indented lines
47
+ */
48
+ function reindent(body, indent) {
49
+ const lines = body.split('\n').filter(line => line.trim());
50
+ const leads = lines.map(line => line.match(/^\s*/)[0].length);
51
+ const min = Math.min(...leads);
52
+ const step = Math.min(...leads.map(lead => lead - min).filter(Boolean)) || 1;
53
+
54
+ return lines
55
+ .map((line, i) => indent + ' '.repeat((leads[i] - min) / step) + line.trim())
56
+ .join('\n');
57
+ }
58
+
59
+ /**
60
+ * Clean an SVG file and split it into the parts a component template needs.
61
+ * Drops what an inline icon doesn't need (XML prolog, doctype, comments, `title`,
62
+ * `desc`, unreferenced ids), and turns hardcoded black into `currentColor`.
35
63
  * @param {string} svgContent - Raw SVG file content
36
- * @returns {string} Indented SVG ready to embed in Component.create`...`
64
+ * @returns {{ attributes: string, body: string, width: string, height: string }}
37
65
  */
38
- function transformSvg(svgContent) {
39
- const openEnd = svgContent.indexOf('>');
40
- const openTag = svgContent.slice(0, openEnd + 1);
41
- const rest = svgContent.slice(openEnd + 1);
42
-
43
- const origW = extractSize(openTag, 'width');
44
- const origH = extractSize(openTag, 'height');
45
-
46
- // Build template expression strings (written as literal text to output files)
47
- const classExpr = 'class="${({ props }) => props.className || \'\'}"';
48
- const widthExpr = `width="\${({ props }) => props.width || '${origW}'}"`;
49
- const heightExpr = `height="\${({ props }) => props.height || '${origH}'}"`;
50
-
51
- const newTag = openTag
52
- .replace(/\s+class="[^"]*"/g, '')
53
- .replace(/\s+width="[^"]*"/g, '')
54
- .replace(/\s+height="[^"]*"/g, '')
55
- .replace('<svg', `<svg ${classExpr} ${widthExpr} ${heightExpr}`);
56
-
57
- return (newTag + rest)
58
- .replace(/\n$/, '')
59
- .replace(/^ {2}/gm, ' ')
60
- .replace(/^/gm, ' ');
66
+ export function transformSvg(svgContent) {
67
+ const svg = svgContent
68
+ .replace(/<\?xml[\s\S]*?\?>/g, '')
69
+ .replace(/<!DOCTYPE[\s\S]*?>/gi, '')
70
+ .replace(/<!--[\s\S]*?-->/g, '')
71
+ .replace(/<(title|desc)\b[^>]*>[\s\S]*?<\/\1>/g, '')
72
+ .replace(BLACK_PAINT, ' $1="currentColor"')
73
+ // Ids repeat across icons on a page; keep only those the icon references itself.
74
+ .replace(/\sid="([^"]*)"/g, (attr, id, _offset, all) => all.includes(`#${id}`) ? attr : '')
75
+ // The markup lands in a template literal.
76
+ .replace(/[`\\]|\$\{/g, m => '\\' + m);
77
+
78
+ const open = svg.match(/<svg\b[^>]*>/);
79
+ const close = svg.lastIndexOf('</svg>');
80
+ if (!open || close === -1) throw new Error('No <svg> element found');
81
+
82
+ return {
83
+ attributes : open[0].slice(4, -1).replace(ROOT_ATTRIBUTES, '').trim(),
84
+ body : svg.slice(open.index + open[0].length, close),
85
+ width : extractSize(open[0], 'width'),
86
+ height : extractSize(open[0], 'height')
87
+ };
88
+ }
89
+
90
+ /**
91
+ * Build the source of a Rasti icon component from an SVG file.
92
+ * @param {string} name - Component name
93
+ * @param {string} svgContent - Raw SVG file content
94
+ * @returns {string} Module source
95
+ */
96
+ export function buildComponent(name, svgContent) {
97
+ const { attributes, body, width, height } = transformSvg(svgContent);
98
+ const sizeDefaults = width === height ?
99
+ `size = '${width}', width = size, height = size` :
100
+ `size, width = size ?? '${width}', height = size ?? '${height}'`;
101
+
102
+ return [
103
+ `import { Component } from 'rasti';`,
104
+ ``,
105
+ `/**`,
106
+ ` * @typedef {Object} IconProps`,
107
+ ` * @property {string} [className]`,
108
+ ` * @property {string|number} [size] - Width and height, unless set apart.`,
109
+ ` * @property {string|number} [width]`,
110
+ ` * @property {string|number} [height]`,
111
+ ` * @property {string} [label] - Accessible name. Without it the icon is decorative and hidden from assistive technology.`,
112
+ ` */`,
113
+ ``,
114
+ `/** @type {typeof Component<IconProps>} */`,
115
+ `const ${name} = Component.create(/** @this {import('rasti').Component<IconProps>} */ function() {`,
116
+ ` const { className, ${sizeDefaults}, label } = this.props;`,
117
+ ``,
118
+ ` return this.html\``,
119
+ ` <svg class="\${className}" width="\${width}" height="\${height}" role="\${label ? 'img' : null}" aria-label="\${label}" aria-hidden="\${label ? null : 'true'}"${attributes ? ' ' + attributes : ''}>`,
120
+ reindent(body, ' '),
121
+ ` </svg>`,
122
+ ` \`;`,
123
+ `});`,
124
+ ``,
125
+ `export default ${name};`,
126
+ ``
127
+ ].join('\n');
61
128
  }
62
129
 
63
130
  /**
@@ -91,27 +158,7 @@ export async function generateIcons({ source, license, output }) {
91
158
  const iconName = toPascalCase(item.name);
92
159
  const svgRes = await fetch(item.download_url);
93
160
  if (!svgRes.ok) throw new Error(`SVG fetch failed for ${item.name}: ${svgRes.status}`);
94
- const svgContent = await svgRes.text();
95
- const transformed = transformSvg(svgContent);
96
- const component = [
97
- `import { Component } from 'rasti';`,
98
- ``,
99
- `/**`,
100
- ` * @typedef {Object} IconProps`,
101
- ` * @property {string} [className]`,
102
- ` * @property {string} [width]`,
103
- ` * @property {string} [height]`,
104
- ` */`,
105
- ``,
106
- `/** @type {typeof import('rasti').Component<IconProps>} */`,
107
- `const ${iconName} = Component.create\``,
108
- transformed,
109
- `\`;`,
110
- ``,
111
- `export default ${iconName};`,
112
- ``
113
- ].join('\n');
114
- fs.writeFileSync(path.join(output, `${iconName}.js`), component);
161
+ fs.writeFileSync(path.join(output, `${iconName}.js`), buildComponent(iconName, await svgRes.text()));
115
162
  count++;
116
163
  }
117
164