@inflector/keeno-router 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 iliesw
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,24 @@
1
- # Temporary Holding Version
1
+ # @inflector/keeno-router
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Client-side router for [Keeno](https://github.com/iliesw/Keeno): `<Router>`, `<Link>`, `navigate()`, `useRoute()` and the `link` click handler. It also supports a base path, lazy routes and server rendering.
4
+
5
+ ```bash
6
+ bun add @inflector/keeno-router
7
+ ```
8
+
9
+ ```html
10
+ <script lang="ts">
11
+ import { Link, Router } from '@inflector/keeno-router'
12
+ import Home from './Home.kn'
13
+ import User from './User.kn'
14
+ const routes = [
15
+ { path: '/', component: Home },
16
+ { path: '/users/:id', component: User },
17
+ ]
18
+ </script>
19
+
20
+ <Link href="/users/1">Ada</Link>
21
+ <Router routes={routes} />
22
+ ```
23
+
24
+ See [Routing](https://github.com/iliesw/Keeno/blob/main/docs/routing.md). MIT license.
@@ -0,0 +1,81 @@
1
+ import { type Children, type Component } from '@inflector/keeno';
2
+ export type Params = Record<string, string>;
3
+ /** Props passed to a route's component. */
4
+ export interface RouteProps {
5
+ /** Path parameters (`/users/:id` → `{ id }`); updates in place when only they change. */
6
+ params: Params;
7
+ }
8
+ export interface RouteDefinition {
9
+ /**
10
+ * `/users/:id` matches one segment per `:name`; a final `*` (or `*name`) matches the rest of the
11
+ * path (`params['*']` or `params.name`). Routes are tried in order: put specific ones first.
12
+ */
13
+ path: string;
14
+ /** Receives `RouteProps`. Typed loosely so components can declare their own params type. */
15
+ component: Component<any>;
16
+ }
17
+ /** The current route. Its fields are reactive: reading them in a template or `update` tracks them. */
18
+ export interface Route {
19
+ /** Path without the router's `base`, e.g. `/users/1`. */
20
+ readonly path: string;
21
+ readonly params: Params;
22
+ readonly query: URLSearchParams;
23
+ /** Including the `#`, or ''. */
24
+ readonly hash: string;
25
+ /** The matched route definition, or null. */
26
+ readonly matched: RouteDefinition | null;
27
+ }
28
+ /** The URL for an app path, with the router's `base` in front: `href('/users/1')`. */
29
+ export declare function href(path: string): string;
30
+ export interface NavigateOptions {
31
+ /** Replace the current history entry instead of adding one. */
32
+ replace?: boolean;
33
+ /** `history.state` for the new entry. */
34
+ state?: unknown;
35
+ /** Scroll to the top after navigating (default true, unless the URL has a hash). */
36
+ scroll?: boolean;
37
+ }
38
+ /** Go to an app path (`/users/1`, prefixed with `base`) or a relative URL (`?tab=2`). */
39
+ export declare function navigate(to: string, options?: NavigateOptions): void;
40
+ /**
41
+ * Click handler for your own `<a>` elements: `<a href="/about" onClick={link}>About</a>`. With a
42
+ * `base`, write `href={href('/about')}`.
43
+ */
44
+ export declare function link(e: MouseEvent): void;
45
+ /** Match `path` against a route pattern; returns its params, or null. */
46
+ export declare function matchPath(pattern: string | RouteDefinition, path: string): Params | null;
47
+ /** True if the browser's current path is `path` or below it (`exact`: only `path` itself). Tracked. */
48
+ export declare function isActive(path: string, exact?: boolean): boolean;
49
+ export interface RouterProps {
50
+ routes: RouteDefinition[];
51
+ /** Path prefix the app is served under, e.g. `/app`. */
52
+ base?: string;
53
+ /** Server rendering: the request URL to render, instead of the browser location. */
54
+ url?: string;
55
+ /** Rendered when no route matches. */
56
+ fallback?: () => unknown;
57
+ }
58
+ /**
59
+ * Render the component of the first route matching the URL. The component is kept when only
60
+ * the params change, and replaced when another route matches.
61
+ */
62
+ export declare function Router(props: RouterProps): unknown;
63
+ /** The current route of the closest `<Router>` (call it while the component is created). */
64
+ export declare function useRoute(): Route;
65
+ export interface LinkProps {
66
+ /** App path (`/users/1`) or relative URL. */
67
+ href: string;
68
+ /** Replace the current history entry. */
69
+ replace?: boolean;
70
+ /** Class added while the link's path is active (default `active`). */
71
+ activeClass?: string;
72
+ /** Only active on exactly this path, not below it. */
73
+ exact?: boolean;
74
+ class?: unknown;
75
+ children?: Children;
76
+ }
77
+ /**
78
+ * A link that navigates without reloading the page, with `aria-current="page"` and `activeClass`
79
+ * while active. The scoped styles of the component that renders it apply to its `<a>`.
80
+ */
81
+ export declare function Link(props: LinkProps): unknown;
package/dist/index.js ADDED
@@ -0,0 +1,280 @@
1
+ // ../../../../../../../tmp/keeno-build/_inflector_keeno-router/src/index.ts
2
+ import { State, createContext, derived, inject, provide, untrack } from "@inflector/keeno";
3
+ import { attr, callerScope, createComponent, insert, on, template } from "@inflector/keeno/internal";
4
+ var hasWindow = typeof window !== "undefined" && typeof location !== "undefined";
5
+ function readLocation() {
6
+ if (!hasWindow)
7
+ return { pathname: "/", search: "", hash: "" };
8
+ return { pathname: location.pathname, search: location.search, hash: location.hash };
9
+ }
10
+ function parseUrl(url) {
11
+ const u = new URL(url, "http://localhost");
12
+ return { pathname: u.pathname, search: u.search, hash: u.hash };
13
+ }
14
+ var current = new State(readLocation(), {
15
+ equals: (a, b) => a.pathname === b.pathname && a.search === b.search && a.hash === b.hash
16
+ });
17
+ var listening = false;
18
+ var base = new State("");
19
+ var scrollPositions = new Map;
20
+ var locKey = (l) => l.pathname + l.search + l.hash;
21
+ function saveScroll(l) {
22
+ if (typeof window.scrollY === "number")
23
+ scrollPositions.set(locKey(l), [window.scrollX, window.scrollY]);
24
+ }
25
+ function setScrollRestoration(mode) {
26
+ try {
27
+ if ("scrollRestoration" in history)
28
+ history.scrollRestoration = mode;
29
+ } catch {}
30
+ }
31
+ function restoreScroll(l) {
32
+ const saved = scrollPositions.get(locKey(l));
33
+ if (!saved && l.hash)
34
+ return scrollToHash(l.hash);
35
+ const run = () => {
36
+ try {
37
+ window.scrollTo(saved?.[0] ?? 0, saved?.[1] ?? 0);
38
+ } catch {}
39
+ };
40
+ if (typeof requestAnimationFrame === "function")
41
+ requestAnimationFrame(run);
42
+ else
43
+ setTimeout(run, 0);
44
+ }
45
+ function sync() {
46
+ if (!hasWindow)
47
+ return;
48
+ current.set(readLocation());
49
+ if (listening)
50
+ return;
51
+ listening = true;
52
+ window.addEventListener("popstate", () => {
53
+ saveScroll(current.peek());
54
+ const next = readLocation();
55
+ current.set(next);
56
+ restoreScroll(next);
57
+ });
58
+ setScrollRestoration("manual");
59
+ window.addEventListener("pagehide", () => setScrollRestoration("auto"));
60
+ window.addEventListener("pageshow", () => setScrollRestoration("manual"));
61
+ }
62
+ function normalizeBase(b) {
63
+ if (!b || b === "/")
64
+ return "";
65
+ return "/" + b.replace(/^\/+|\/+$/g, "");
66
+ }
67
+ function underBase(pathname, b) {
68
+ return !b || pathname === b || pathname.startsWith(b + "/");
69
+ }
70
+ function stripBase(pathname, b) {
71
+ if (!b)
72
+ return pathname;
73
+ if (pathname === b)
74
+ return "/";
75
+ return pathname.startsWith(b + "/") ? pathname.slice(b.length) : pathname;
76
+ }
77
+ function withBase(b, path) {
78
+ return path.startsWith("/") ? b + "/" + path.replace(/^\/+/, "") : path;
79
+ }
80
+ function href(path) {
81
+ return withBase(base.get(), path);
82
+ }
83
+ function scrollToHash(hash) {
84
+ const id = decode(hash.slice(1));
85
+ const run = () => {
86
+ const el = id && document.getElementById(id);
87
+ if (el && typeof el.scrollIntoView === "function")
88
+ el.scrollIntoView();
89
+ };
90
+ if (typeof requestAnimationFrame === "function")
91
+ requestAnimationFrame(run);
92
+ else
93
+ setTimeout(run, 0);
94
+ }
95
+ function navigate(to, options = {}) {
96
+ if (!hasWindow)
97
+ throw new Error("[keeno-router] navigate() only works in the browser");
98
+ const url = new URL(href(to), location.href);
99
+ if (url.origin !== location.origin) {
100
+ location.assign(url.href);
101
+ return;
102
+ }
103
+ saveScroll(current.peek());
104
+ if (options.replace)
105
+ history.replaceState(options.state ?? null, "", url);
106
+ else
107
+ history.pushState(options.state ?? null, "", url);
108
+ window.dispatchEvent(new CustomEvent("keeno:navigate", { detail: { url: url.href, state: options.state ?? null } }));
109
+ current.set(readLocation());
110
+ if (options.scroll === false)
111
+ return;
112
+ if (url.hash)
113
+ scrollToHash(url.hash);
114
+ else if (typeof window.scrollTo === "function") {
115
+ try {
116
+ window.scrollTo(0, 0);
117
+ } catch {}
118
+ }
119
+ }
120
+ function isExternalClick(e, a) {
121
+ if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)
122
+ return true;
123
+ if (a.target && a.target !== "_self" || a.hasAttribute("download"))
124
+ return true;
125
+ const url = new URL(a.href, location.href);
126
+ return url.origin !== location.origin;
127
+ }
128
+ function link(e) {
129
+ const a = e.currentTarget?.closest("a");
130
+ if (!a || isExternalClick(e, a))
131
+ return;
132
+ const url = new URL(a.href, location.href);
133
+ if (!underBase(url.pathname, base.peek()))
134
+ return;
135
+ e.preventDefault();
136
+ navigate(stripBase(url.pathname, base.peek()) + url.search + url.hash, { replace: a.hasAttribute("data-replace") });
137
+ }
138
+ var compiled = new WeakMap;
139
+ function compile(route) {
140
+ let c = compiled.get(route);
141
+ if (c)
142
+ return c;
143
+ const segments = route.path.split("/").filter(Boolean);
144
+ let rest = null;
145
+ const last = segments[segments.length - 1];
146
+ if (last?.startsWith("*")) {
147
+ rest = last.slice(1) || "*";
148
+ segments.pop();
149
+ }
150
+ compiled.set(route, c = { segments, rest });
151
+ return c;
152
+ }
153
+ function decode(s) {
154
+ try {
155
+ return decodeURIComponent(s);
156
+ } catch {
157
+ return s;
158
+ }
159
+ }
160
+ function matchPath(pattern, path) {
161
+ const { segments, rest } = compile(typeof pattern === "string" ? { path: pattern, component: () => null } : pattern);
162
+ const parts = path.split("/").filter(Boolean);
163
+ if (rest === null ? parts.length !== segments.length : parts.length < segments.length)
164
+ return null;
165
+ const params = {};
166
+ for (let i = 0;i < segments.length; i++) {
167
+ const seg = segments[i];
168
+ if (seg.startsWith(":"))
169
+ params[seg.slice(1)] = decode(parts[i]);
170
+ else if (seg !== parts[i])
171
+ return null;
172
+ }
173
+ if (rest !== null)
174
+ params[rest] = parts.slice(segments.length).map(decode).join("/");
175
+ return params;
176
+ }
177
+ var RouteContext = createContext(null, "route");
178
+ var BaseContext = createContext(null, "route-base");
179
+ function pathIsActive(here, path, exact) {
180
+ if (here === path)
181
+ return true;
182
+ if (exact || path === "/")
183
+ return false;
184
+ return here.startsWith(path.endsWith("/") ? path : path + "/");
185
+ }
186
+ function isActive(path, exact = false) {
187
+ return pathIsActive(stripBase(current.get().pathname, base.get()), path, exact);
188
+ }
189
+ function Router(props) {
190
+ const routerBase = normalizeBase(untrack(() => props.base));
191
+ const url = untrack(() => props.url);
192
+ const loc = url != null ? new State(parseUrl(url)) : current;
193
+ if (url == null) {
194
+ base.set(routerBase);
195
+ sync();
196
+ }
197
+ const outside = (l) => !underBase(l.pathname, routerBase);
198
+ const info = derived(() => {
199
+ const l = loc.get();
200
+ const path = stripBase(l.pathname, routerBase);
201
+ if (outside(l))
202
+ return { l, path, matched: null, params: {} };
203
+ for (const r of props.routes) {
204
+ const params = matchPath(r, path);
205
+ if (params)
206
+ return { l, path, matched: r, params };
207
+ }
208
+ return { l, path, matched: null, params: {} };
209
+ });
210
+ const matched = derived(() => info.get().matched);
211
+ const route = {
212
+ get path() {
213
+ return info.get().path;
214
+ },
215
+ get params() {
216
+ return info.get().params;
217
+ },
218
+ get query() {
219
+ return new URLSearchParams(info.get().l.search);
220
+ },
221
+ get hash() {
222
+ return info.get().l.hash;
223
+ },
224
+ get matched() {
225
+ return matched.get();
226
+ }
227
+ };
228
+ provide(RouteContext, route);
229
+ provide(BaseContext, routerBase);
230
+ return () => {
231
+ const r = matched.get();
232
+ if (!r)
233
+ return props.fallback ? untrack(props.fallback) : null;
234
+ return untrack(() => createComponent(r.component, {
235
+ get params() {
236
+ return info.get().params;
237
+ }
238
+ }));
239
+ };
240
+ }
241
+ function useRoute() {
242
+ const route = inject(RouteContext);
243
+ if (!route)
244
+ throw new Error("[keeno-router] useRoute() must be called inside a <Router>");
245
+ return route;
246
+ }
247
+ var anchor = template("<a></a>");
248
+ function Link(props) {
249
+ const a = anchor();
250
+ const scope = callerScope();
251
+ const route = inject(RouteContext);
252
+ const routerBase = inject(BaseContext);
253
+ if (!route)
254
+ sync();
255
+ const active = derived(() => {
256
+ const path = props.href.split(/[?#]/)[0];
257
+ return route ? pathIsActive(route.path, path, !!props.exact) : isActive(path, props.exact);
258
+ });
259
+ attr(a, "href", () => withBase(routerBase ?? base.get(), props.href));
260
+ attr(a, "class", () => [props.class, active.get() && (props.activeClass ?? "active")], scope ?? undefined);
261
+ attr(a, "aria-current", () => active.get() ? "page" : null);
262
+ on(a, "click", (e) => {
263
+ if (isExternalClick(e, a))
264
+ return;
265
+ e.preventDefault();
266
+ navigate(props.href, { replace: props.replace });
267
+ });
268
+ insert(a, () => props.children?.());
269
+ return a;
270
+ }
271
+ export {
272
+ Link,
273
+ Router,
274
+ href,
275
+ isActive,
276
+ link,
277
+ matchPath,
278
+ navigate,
279
+ useRoute
280
+ };
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@inflector/keeno-router",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Client-side router for Keeno (.kn) apps",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/iliesw/Keeno.git",
9
+ "directory": "packages/router"
10
+ },
11
+ "homepage": "https://github.com/iliesw/Keeno/tree/main/packages/router#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/iliesw/Keeno/issues"
14
+ },
15
+ "keywords": [
16
+ "keeno",
17
+ "router",
18
+ "routing",
19
+ "spa"
20
+ ],
21
+ "type": "module",
22
+ "sideEffects": false,
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "keeno-source": "./src/index.ts",
28
+ "types": "./dist/index.d.ts",
29
+ "import": "./dist/index.js",
30
+ "default": "./dist/index.js"
31
+ },
32
+ "./package.json": "./package.json"
33
+ },
34
+ "files": [
35
+ "dist"
36
+ ],
37
+ "scripts": {
38
+ "build": "bun ../../scripts/build-package.ts --target=browser",
39
+ "prepack": "bun run build"
40
+ },
41
+ "peerDependencies": {
42
+ "@inflector/keeno": ">=0.3.0 <1.0.0"
43
+ },
44
+ "devDependencies": {
45
+ "@inflector/keeno": "0.3.0"
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ }
50
+ }