create-rasti 0.0.1 → 0.1.0-alpha.0
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 +21 -2
- package/extras/cn/src/index.js +14 -1
- package/extras/micro-router/README.md +35 -3
- package/extras/micro-router/package.json +1 -1
- package/extras/micro-router/src/index.js +124 -44
- package/extras/rasti-icons/README.md +15 -5
- package/extras/rasti-icons/src/generate.js +95 -49
- package/package.json +9 -6
- package/src/apply/agents.js +68 -0
- package/src/apply/base.js +1 -1
- package/src/apply/description.js +2 -0
- package/src/apply/featuresInclude.js +3 -2
- package/src/apply/index.js +13 -37
- package/src/apply/router.js +2 -2
- package/src/apply/ssr.js +1 -1
- package/src/apply/typescript.js +38 -0
- package/src/args.js +3 -0
- package/src/cli.js +2 -0
- package/src/plan.js +2 -1
- package/src/prompts.js +17 -0
- package/src/utils/template.js +32 -15
- package/src/versions.js +16 -12
- package/templates/AGENTS.md +31 -8
- package/templates/_base/App-cssfun.js +40 -23
- package/templates/_base/App-cssfun.ts +107 -0
- package/templates/_base/App-tailwind.js +39 -22
- package/templates/_base/App-tailwind.ts +77 -0
- package/templates/_base/App.js +39 -22
- package/templates/_base/App.ts +77 -0
- package/templates/_base/components/Button-cssfun.ts +54 -0
- package/templates/_base/components/Button-tailwind.ts +55 -0
- package/templates/_base/components/Button.ts +25 -0
- package/templates/_base/components/Header-cssfun.ts +71 -0
- package/templates/_base/components/Header-tailwind.ts +19 -0
- package/templates/_base/components/Header.ts +19 -0
- package/templates/_base/components/Home-cssfun.ts +101 -0
- package/templates/_base/components/Home-tailwind.ts +38 -0
- package/templates/_base/components/Home.ts +38 -0
- package/templates/_extras/router/components/About-cssfun.ts +45 -0
- package/templates/_extras/router/components/About-tailwind.ts +16 -0
- package/templates/_extras/router/components/About.ts +18 -0
- package/templates/_extras/router/router-setup.js +21 -21
- package/templates/_extras/router/router-setup.ts +52 -0
- package/templates/_features/cssfun/index.html +1 -1
- package/templates/_features/typescript/tsconfig.json +30 -0
- package/templates/spa/index.html +1 -1
- package/templates/spa/src/main.js +1 -2
- package/templates/spa/src/main.ts +14 -0
- package/templates/ssr/app.js +10 -10
- package/templates/ssr/index.html +1 -1
- package/templates/ssr/package.json +1 -1
- package/templates/ssr/src/entry-client.js +2 -1
- package/templates/ssr/src/entry-client.ts +28 -0
- package/templates/ssr/src/entry-server.js +31 -25
- package/templates/ssr/src/entry-server.ts +62 -0
- 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
|
-
|
|
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
|
-
|
|
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.
|
package/extras/cn/src/index.js
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @typedef {string|number|boolean|null|undefined|Object.<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 {...
|
|
39
|
+
* @param {...ClassValue} args - Class name values to join.
|
|
27
40
|
* @returns {string} The merged class name string.
|
|
28
41
|
*
|
|
29
42
|
* @example
|
|
@@ -49,16 +49,48 @@ In the browser, links opt in to client-side navigation with `data-router`:
|
|
|
49
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 }`. |
|
|
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. 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.
|
|
@@ -1,29 +1,44 @@
|
|
|
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 {Object.<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 {
|
|
7
|
-
* @property {Object.<string, string>} query -
|
|
8
|
-
* @property {
|
|
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 {Object.<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 {
|
|
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.
|
|
15
26
|
*/
|
|
16
27
|
|
|
17
28
|
/**
|
|
18
29
|
* @typedef {Object} Router
|
|
19
|
-
* @property {
|
|
20
|
-
* @property {
|
|
21
|
-
* @property {
|
|
22
|
-
* @property {
|
|
30
|
+
* @property {(url: string, options?: NavigateOptions) => *} navigate - Navigates to a given URL, matches a route, and returns its action result.
|
|
31
|
+
* @property {(path: string, params?: Params, query?: Object.<string, string>) => string} createUrl - Creates a URL from a route path, parameters, and query string.
|
|
32
|
+
* @property {(rootElement: HTMLElement) => () => void} delegateNavigation - Delegates navigation events for links with `data-router` attributes. Returns a cleanup function.
|
|
33
|
+
* @property {() => () => void} bindHistory - Binds browser history changes to the navigation logic. Returns a cleanup function.
|
|
23
34
|
*/
|
|
24
35
|
|
|
25
36
|
/**
|
|
26
37
|
* Creates a router with navigation, URL creation, and event delegation.
|
|
38
|
+
*
|
|
39
|
+
* `params` and `query` on a `Location` come from the URL and are decoded but not
|
|
40
|
+
* escaped. Escape them at the point of output, in the context of that output.
|
|
41
|
+
*
|
|
27
42
|
* @param {Array.<Route>} routes - Array of route objects. Each route must have a `path` and an `action` function.
|
|
28
43
|
* @param {Object} [routerOptions={}] - Options for the router.
|
|
29
44
|
* @param {string} [routerOptions.baseUrl=''] - A base URL to prepend to all routes and navigation.
|
|
@@ -32,33 +47,76 @@ import { match, compile } from 'path-to-regexp';
|
|
|
32
47
|
export default function createRouter(routes, routerOptions = {}) {
|
|
33
48
|
const { baseUrl = '' } = routerOptions;
|
|
34
49
|
|
|
50
|
+
/**
|
|
51
|
+
* Compiled matchers, keyed by route path. Built on first match and reused afterwards.
|
|
52
|
+
* @type {Map<string, import('path-to-regexp').MatchFunction<Params>>}
|
|
53
|
+
*/
|
|
54
|
+
const matchers = new Map();
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Path and query of the last URL routed, to tell a new page from an in-page anchor jump.
|
|
58
|
+
* @type {string|null}
|
|
59
|
+
*/
|
|
60
|
+
let currentUrl = null;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Removes `baseUrl` from the start of a pathname.
|
|
64
|
+
* Only strips on a path segment boundary, so a `baseUrl` of `/app` leaves
|
|
65
|
+
* `/application/x` untouched.
|
|
66
|
+
* @param {string} pathname - The pathname to strip.
|
|
67
|
+
* @returns {string} - The pathname without the base url.
|
|
68
|
+
* @private
|
|
69
|
+
*/
|
|
70
|
+
const stripBaseUrl = (pathname) => {
|
|
71
|
+
if (!baseUrl || !pathname.startsWith(baseUrl)) return pathname;
|
|
72
|
+
|
|
73
|
+
const rest = pathname.slice(baseUrl.length);
|
|
74
|
+
return rest === '' || rest.startsWith('/') ? rest : pathname;
|
|
75
|
+
};
|
|
76
|
+
|
|
35
77
|
/**
|
|
36
78
|
* Gets the pathname and query string from a given url.
|
|
79
|
+
* The fragment is dropped: it takes no part in matching.
|
|
37
80
|
* @param {string} url - The url to get the pathname and query string from.
|
|
38
|
-
* @returns {
|
|
81
|
+
* @returns {{ pathname: string, query: (string|undefined) }} - The pathname and query string.
|
|
39
82
|
* @private
|
|
40
83
|
*/
|
|
41
84
|
const getUrlParts = (url) => {
|
|
42
|
-
const [pathname, query] = url.
|
|
43
|
-
|
|
85
|
+
const [pathname, query] = url.split('#')[0].split('?');
|
|
86
|
+
// Stripping the whole pathname (a url equal to `baseUrl`) leaves the root route.
|
|
87
|
+
return { pathname : stripBaseUrl(pathname) || '/', query };
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Gets the memoized matcher for a route path.
|
|
92
|
+
* @param {string} routePath - The route path to match against.
|
|
93
|
+
* @returns {import('path-to-regexp').MatchFunction<Params>} - The matcher function.
|
|
94
|
+
* @private
|
|
95
|
+
*/
|
|
96
|
+
const getMatcher = (routePath) => {
|
|
97
|
+
let matcher = matchers.get(routePath);
|
|
98
|
+
|
|
99
|
+
if (!matcher) {
|
|
100
|
+
matcher = /** @type {import('path-to-regexp').MatchFunction<Params>} */ (match(routePath, { decode : decodeURIComponent }));
|
|
101
|
+
matchers.set(routePath, matcher);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return matcher;
|
|
44
105
|
};
|
|
45
106
|
|
|
46
107
|
/**
|
|
47
108
|
* Gets the match result from a given pathname and route path.
|
|
48
109
|
* @param {string} pathname - The pathname to match.
|
|
49
110
|
* @param {string} routePath - The route path to match.
|
|
50
|
-
* @returns {
|
|
111
|
+
* @returns {import('path-to-regexp').Match<Params>} - The match result, or `false` if no match is found.
|
|
51
112
|
* @private
|
|
52
113
|
*/
|
|
53
|
-
const getMatch = (pathname, routePath) =>
|
|
54
|
-
const matcher = match(routePath, { decode : decodeURIComponent });
|
|
55
|
-
return matcher(pathname);
|
|
56
|
-
};
|
|
114
|
+
const getMatch = (pathname, routePath) => getMatcher(routePath)(pathname);
|
|
57
115
|
|
|
58
116
|
/**
|
|
59
117
|
* Matches a given url against the routes.
|
|
60
118
|
* @param {string} url - The url to match.
|
|
61
|
-
* @returns {(
|
|
119
|
+
* @returns {(() => *)|null} - A function that calls the matched route's action with a `Location` object, or `null` if no match is found.
|
|
62
120
|
* @private
|
|
63
121
|
*/
|
|
64
122
|
const matchRoute = (url) => {
|
|
@@ -71,7 +129,7 @@ export default function createRouter(routes, routerOptions = {}) {
|
|
|
71
129
|
/** @type {Location} */
|
|
72
130
|
const location = {
|
|
73
131
|
path : route.path,
|
|
74
|
-
params :
|
|
132
|
+
params : matched.params,
|
|
75
133
|
query : Object.fromEntries(new URLSearchParams(query).entries()),
|
|
76
134
|
test : (url) => !!getMatch(getUrlParts(url).pathname, route.path)
|
|
77
135
|
};
|
|
@@ -85,10 +143,12 @@ export default function createRouter(routes, routerOptions = {}) {
|
|
|
85
143
|
|
|
86
144
|
/**
|
|
87
145
|
* Navigates to a given path, matches a route, and calls its action with a `Location` object.
|
|
146
|
+
*
|
|
147
|
+
* History is updated before the action runs, so an action that redirects can
|
|
148
|
+
* replace the entry it was reached through: `navigate('/login', { replaceHistory : true })`.
|
|
149
|
+
*
|
|
88
150
|
* @param {string} url - The path to navigate to, including query string.
|
|
89
|
-
* @param {
|
|
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.
|
|
151
|
+
* @param {NavigateOptions} [options={}] - Options for navigation.
|
|
92
152
|
* @returns {*} The matched route action result, or `undefined` if no route matches. Async actions return a Promise.
|
|
93
153
|
*/
|
|
94
154
|
const navigate = (url, options = {}) => {
|
|
@@ -97,6 +157,7 @@ export default function createRouter(routes, routerOptions = {}) {
|
|
|
97
157
|
const matched = matchRoute(url);
|
|
98
158
|
|
|
99
159
|
if (matched) {
|
|
160
|
+
currentUrl = url.split('#')[0];
|
|
100
161
|
// Handle browser history
|
|
101
162
|
if (addToHistory && typeof window !== 'undefined') {
|
|
102
163
|
window.history[replaceHistory ? 'replaceState' : 'pushState']({}, '', url);
|
|
@@ -113,7 +174,7 @@ export default function createRouter(routes, routerOptions = {}) {
|
|
|
113
174
|
/**
|
|
114
175
|
* Creates a URL from a route path, parameters, and query string.
|
|
115
176
|
* @param {string} path - The route path (e.g., `/user/:id`).
|
|
116
|
-
* @param {
|
|
177
|
+
* @param {Params} [params={}] - Parameters to replace in the path (e.g., `{ id : '123' }` for `/user/:id`). Wildcard parameters take an array of segments.
|
|
117
178
|
* @param {Object.<string, string>} [query={}] - Query parameters to append to the URL (e.g., `{ page : '1', sort : 'name' }`).
|
|
118
179
|
* @returns {string} - The generated URL with query parameters.
|
|
119
180
|
*/
|
|
@@ -127,10 +188,13 @@ export default function createRouter(routes, routerOptions = {}) {
|
|
|
127
188
|
|
|
128
189
|
/**
|
|
129
190
|
* Delegates navigation events for links with `data-router` attributes.
|
|
191
|
+
* Links the router cannot own (cross-origin, `target`, `download`, `rel="external"`)
|
|
192
|
+
* are left to the browser's default handling.
|
|
130
193
|
* @param {HTMLElement} rootElement - The root element to listen for click events.
|
|
131
|
-
* @returns {
|
|
194
|
+
* @returns {() => void} - A function to undelegate the event listener.
|
|
132
195
|
*/
|
|
133
196
|
const delegateNavigation = (rootElement) => {
|
|
197
|
+
/** @param {MouseEvent} event */
|
|
134
198
|
const handleClick = (event) => {
|
|
135
199
|
if (
|
|
136
200
|
event.defaultPrevented ||
|
|
@@ -140,14 +204,36 @@ export default function createRouter(routes, routerOptions = {}) {
|
|
|
140
204
|
return;
|
|
141
205
|
}
|
|
142
206
|
|
|
143
|
-
const
|
|
207
|
+
const target = /** @type {Element|null} */ (event.target);
|
|
208
|
+
const anchor = /** @type {HTMLAnchorElement|SVGAElement|null} */ (
|
|
209
|
+
typeof target?.closest === 'function' ? target.closest('a[data-router]') : null
|
|
210
|
+
);
|
|
211
|
+
|
|
212
|
+
if (!anchor) return;
|
|
144
213
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
214
|
+
const anchorTarget = anchor.getAttribute('target');
|
|
215
|
+
const rel = anchor.getAttribute('rel');
|
|
216
|
+
|
|
217
|
+
if (
|
|
218
|
+
anchor.hasAttribute('download') ||
|
|
219
|
+
(anchorTarget && anchorTarget !== '_self') ||
|
|
220
|
+
(rel && rel.split(/\s+/).includes('external'))
|
|
221
|
+
) {
|
|
222
|
+
return;
|
|
150
223
|
}
|
|
224
|
+
|
|
225
|
+
// `href` is an absolute string on HTML anchors; SVG anchors need the raw attribute.
|
|
226
|
+
const href = typeof anchor.href === 'string' ? anchor.href : anchor.getAttribute('href');
|
|
227
|
+
|
|
228
|
+
if (href === null) return;
|
|
229
|
+
|
|
230
|
+
const url = new URL(href, window.location.href);
|
|
231
|
+
|
|
232
|
+
if (url.origin !== window.location.origin) return;
|
|
233
|
+
|
|
234
|
+
event.preventDefault();
|
|
235
|
+
window.scrollTo({ top : 0, behavior : 'instant' });
|
|
236
|
+
navigate(url.pathname + url.search);
|
|
151
237
|
};
|
|
152
238
|
// Bind the click event to the root element.
|
|
153
239
|
rootElement.addEventListener('click', handleClick);
|
|
@@ -159,12 +245,19 @@ export default function createRouter(routes, routerOptions = {}) {
|
|
|
159
245
|
|
|
160
246
|
/**
|
|
161
247
|
* Binds browser history changes to the navigation logic.
|
|
162
|
-
*
|
|
248
|
+
* A `popstate` that keeps the routed path and query, such as a jump to an in-page
|
|
249
|
+
* anchor, is ignored. No-op outside the browser.
|
|
250
|
+
* @returns {() => void} - A function to unbind the `popstate` event listener.
|
|
163
251
|
*/
|
|
164
252
|
const bindHistory = () => {
|
|
253
|
+
if (typeof window === 'undefined') return () => {};
|
|
254
|
+
|
|
165
255
|
const handlePopState = () => {
|
|
256
|
+
const url = window.location.pathname + window.location.search;
|
|
257
|
+
// Routing the same URL again would re-render the page under the reader.
|
|
258
|
+
if (url === currentUrl) return;
|
|
166
259
|
// On popstate, navigate to the current URL
|
|
167
|
-
navigate(
|
|
260
|
+
navigate(url, { addToHistory : false });
|
|
168
261
|
};
|
|
169
262
|
|
|
170
263
|
window.addEventListener('popstate', handlePopState);
|
|
@@ -175,18 +268,5 @@ export default function createRouter(routes, routerOptions = {}) {
|
|
|
175
268
|
};
|
|
176
269
|
};
|
|
177
270
|
|
|
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
271
|
return { navigate, createUrl, delegateNavigation, bindHistory };
|
|
192
272
|
}
|
|
@@ -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.
|
|
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
|
-
//
|
|
51
|
-
|
|
58
|
+
// In a template — decorative, at the original size.
|
|
59
|
+
const Liked = Component.create`<p><${Heart} className="icon" /> Liked</p>`;
|
|
52
60
|
|
|
53
|
-
//
|
|
54
|
-
Heart.mount({
|
|
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,91 @@ function extractSize(tag, dim) {
|
|
|
30
39
|
}
|
|
31
40
|
|
|
32
41
|
/**
|
|
33
|
-
*
|
|
34
|
-
*
|
|
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
|
|
64
|
+
* @returns {{ attributes: string, body: string, width: string, height: string }}
|
|
37
65
|
*/
|
|
38
|
-
function transformSvg(svgContent) {
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
.replace('
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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
|
+
`const ${name} = Component.create(/** @this {import('rasti').Component<IconProps>} */ function() {`,
|
|
115
|
+
` const { className, ${sizeDefaults}, label } = this.props;`,
|
|
116
|
+
``,
|
|
117
|
+
` return this.html\``,
|
|
118
|
+
` <svg class="\${className}" width="\${width}" height="\${height}" role="\${label ? 'img' : null}" aria-label="\${label}" aria-hidden="\${label ? null : 'true'}"${attributes ? ' ' + attributes : ''}>`,
|
|
119
|
+
reindent(body, ' '),
|
|
120
|
+
` </svg>`,
|
|
121
|
+
` \`;`,
|
|
122
|
+
`});`,
|
|
123
|
+
``,
|
|
124
|
+
`export default ${name};`,
|
|
125
|
+
``
|
|
126
|
+
].join('\n');
|
|
61
127
|
}
|
|
62
128
|
|
|
63
129
|
/**
|
|
@@ -91,27 +157,7 @@ export async function generateIcons({ source, license, output }) {
|
|
|
91
157
|
const iconName = toPascalCase(item.name);
|
|
92
158
|
const svgRes = await fetch(item.download_url);
|
|
93
159
|
if (!svgRes.ok) throw new Error(`SVG fetch failed for ${item.name}: ${svgRes.status}`);
|
|
94
|
-
|
|
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);
|
|
160
|
+
fs.writeFileSync(path.join(output, `${iconName}.js`), buildComponent(iconName, await svgRes.text()));
|
|
115
161
|
count++;
|
|
116
162
|
}
|
|
117
163
|
|