meowjsx 0.3.0-alpha.2 → 0.3.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.
@@ -0,0 +1,94 @@
1
+ import type { Child, Component, ComponentRenderContext, Props, ReadableSignal } from "./types.js";
2
+ /** The standard URLSearchParams interface available in browsers and modern server runtimes. */
3
+ export interface RouterQuery {
4
+ readonly size: number;
5
+ append(name: string, value: string): void;
6
+ delete(name: string, value?: string): void;
7
+ set(name: string, value: string): void;
8
+ sort(): void;
9
+ get(name: string): string | null;
10
+ getAll(name: string): string[];
11
+ has(name: string, value?: string): boolean;
12
+ toString(): string;
13
+ entries(): IterableIterator<[string, string]>;
14
+ keys(): IterableIterator<string>;
15
+ values(): IterableIterator<string>;
16
+ forEach(callback: (value: string, key: string, parent: RouterQuery) => void): void;
17
+ [Symbol.iterator](): IterableIterator<[string, string]>;
18
+ }
19
+ export interface RouterLocation {
20
+ pathname: string;
21
+ search: string;
22
+ query: RouterQuery;
23
+ hash: string;
24
+ }
25
+ export interface RouterAdapter {
26
+ getLocation(): {
27
+ pathname: string;
28
+ search: string;
29
+ hash: string;
30
+ };
31
+ push(url: string, state?: unknown): void;
32
+ replace(url: string, state?: unknown): void;
33
+ back(): void;
34
+ subscribe(listener: () => void): () => void;
35
+ }
36
+ export interface RouteDefinition {
37
+ path: string;
38
+ component: Component<any>;
39
+ }
40
+ export interface RouteMatch {
41
+ route: RouteDefinition;
42
+ params: Record<string, string>;
43
+ pattern: string;
44
+ }
45
+ export interface Router {
46
+ readonly location: ReadableSignal<RouterLocation>;
47
+ readonly route: ReadableSignal<RouteMatch | null>;
48
+ resolve(to: string): string;
49
+ navigate(to: string, options?: {
50
+ replace?: boolean;
51
+ state?: unknown;
52
+ }): void;
53
+ back(): void;
54
+ dispose(): void;
55
+ }
56
+ export interface RouterOptions {
57
+ routes?: RouteDefinition[];
58
+ base?: string;
59
+ initialPath?: string;
60
+ adapter?: RouterAdapter;
61
+ }
62
+ /** Match whole path segments; a final wildcard also matches an empty suffix. */
63
+ export declare function matchPath(pattern: string, pathname: string): {
64
+ params: Record<string, string>;
65
+ pattern: string;
66
+ } | null;
67
+ /** In-memory history for server rendering and non-browser hosts. */
68
+ export declare function createMemoryRouterAdapter(initialPath?: string): RouterAdapter;
69
+ export declare function createRouter(options?: RouterOptions): Router;
70
+ export declare const RouterProvider: Component<{
71
+ value: Router | undefined;
72
+ children?: Child;
73
+ }>;
74
+ export declare function useRouter(): Router;
75
+ export interface LinkClickEvent {
76
+ button: number;
77
+ metaKey: boolean;
78
+ ctrlKey: boolean;
79
+ shiftKey: boolean;
80
+ altKey: boolean;
81
+ defaultPrevented: boolean;
82
+ preventDefault(): void;
83
+ }
84
+ export interface LinkProps extends Props {
85
+ href: string;
86
+ replace?: boolean;
87
+ target?: string;
88
+ download?: unknown;
89
+ onClick?: (event: LinkClickEvent) => void;
90
+ }
91
+ export declare function Link({ href, replace, target, download, onClick, children, ...props }: LinkProps, context: ComponentRenderContext): Child;
92
+ export declare function RouterView({ fallback }: {
93
+ fallback?: Child;
94
+ }, context: ComponentRenderContext): Child;
@@ -0,0 +1,207 @@
1
+ import { createContext, useContext } from "./context.js";
2
+ import { mapSignal, signal } from "./signal.js";
3
+ const URLConstructor = globalThis.URL;
4
+ const memoryOrigin = "http://meowjsx.invalid";
5
+ /** Match whole path segments; a final wildcard also matches an empty suffix. */
6
+ export function matchPath(pattern, pathname) {
7
+ if (pattern === "*")
8
+ return { params: {}, pattern };
9
+ const parts = pattern.split("/").filter(Boolean);
10
+ const path = pathname.split("/").filter(Boolean);
11
+ const params = {};
12
+ for (let i = 0; i < parts.length; i++) {
13
+ const part = parts[i];
14
+ if (part === "*" && i === parts.length - 1)
15
+ return { params, pattern };
16
+ const value = path[i];
17
+ if (value === undefined)
18
+ return null;
19
+ if (part.startsWith(":")) {
20
+ if (part.length === 1)
21
+ return null;
22
+ try {
23
+ params[part.slice(1)] = decodeURIComponent(value);
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ }
29
+ else if (part !== value)
30
+ return null;
31
+ }
32
+ return path.length === parts.length ? { params, pattern } : null;
33
+ }
34
+ function browserWindow() {
35
+ return globalThis.window;
36
+ }
37
+ function browserAdapter(win) {
38
+ return {
39
+ getLocation: () => win.location,
40
+ push: (url, state) => win.history.pushState(state ?? null, "", url),
41
+ replace: (url, state) => win.history.replaceState(state ?? null, "", url),
42
+ back: () => win.history.back(),
43
+ subscribe: (listener) => {
44
+ win.addEventListener("popstate", listener);
45
+ return () => win.removeEventListener("popstate", listener);
46
+ },
47
+ };
48
+ }
49
+ /** In-memory history for server rendering and non-browser hosts. */
50
+ export function createMemoryRouterAdapter(initialPath = "/") {
51
+ const initial = new URLConstructor(initialPath, memoryOrigin);
52
+ let entries = [initial.pathname + initial.search + initial.hash];
53
+ let index = 0;
54
+ const listeners = new Set();
55
+ return {
56
+ getLocation: () => new URLConstructor(entries[index], memoryOrigin),
57
+ push: (url) => {
58
+ entries = entries.slice(0, index + 1);
59
+ entries.push(url);
60
+ index++;
61
+ },
62
+ replace: (url) => {
63
+ entries[index] = url;
64
+ },
65
+ back: () => {
66
+ if (index > 0) {
67
+ index--;
68
+ for (const listener of Array.from(listeners))
69
+ listener();
70
+ }
71
+ },
72
+ subscribe: (listener) => {
73
+ listeners.add(listener);
74
+ return () => {
75
+ listeners.delete(listener);
76
+ };
77
+ },
78
+ };
79
+ }
80
+ export function createRouter(options = {}) {
81
+ const win = browserWindow();
82
+ const adapter = options.adapter ??
83
+ (win && options.initialPath === undefined
84
+ ? browserAdapter(win)
85
+ : createMemoryRouterAdapter(options.initialPath));
86
+ const base = options.base && options.base !== "/"
87
+ ? "/" + options.base.split("/").filter(Boolean).join("/")
88
+ : "";
89
+ const read = () => {
90
+ const location = adapter.getLocation();
91
+ const parsed = new URLConstructor(location.pathname + location.search + location.hash, memoryOrigin);
92
+ return {
93
+ pathname: location.pathname,
94
+ search: location.search,
95
+ hash: location.hash,
96
+ query: parsed.searchParams,
97
+ };
98
+ };
99
+ const location = signal(read());
100
+ const route = mapSignal(location, (current) => {
101
+ if (base && current.pathname !== base && !current.pathname.startsWith(base + "/"))
102
+ return null;
103
+ const path = current.pathname.slice(base.length) || "/";
104
+ for (const definition of options.routes ?? []) {
105
+ const match = matchPath(definition.path, path);
106
+ if (match)
107
+ return { route: definition, ...match };
108
+ }
109
+ return null;
110
+ });
111
+ const resolve = (to) => {
112
+ const current = location.value;
113
+ const origin = win?.location.origin ?? memoryOrigin;
114
+ const currentURL = origin + current.pathname + current.search + current.hash;
115
+ const absolute = /^[a-z][a-z\d+.-]*:/i.test(to) || to.startsWith("//");
116
+ const target = new URLConstructor(to, currentURL);
117
+ if (target.origin !== origin)
118
+ throw new Error("Cannot navigate to an external URL");
119
+ if (!absolute &&
120
+ to.startsWith("/") &&
121
+ base &&
122
+ target.pathname !== base &&
123
+ !target.pathname.startsWith(base + "/"))
124
+ target.pathname = base + target.pathname;
125
+ const hash = to.includes("#") ? target.hash : current.hash;
126
+ return target.pathname + target.search + hash;
127
+ };
128
+ let disposed = false;
129
+ const unsubscribe = adapter.subscribe(() => {
130
+ if (!disposed)
131
+ location.value = read();
132
+ });
133
+ return {
134
+ location,
135
+ route,
136
+ resolve,
137
+ navigate(to, navigation = {}) {
138
+ if (disposed)
139
+ return;
140
+ const url = resolve(to);
141
+ if (navigation.replace)
142
+ adapter.replace(url, navigation.state);
143
+ else
144
+ adapter.push(url, navigation.state);
145
+ location.value = read();
146
+ },
147
+ back() {
148
+ if (!disposed)
149
+ adapter.back();
150
+ },
151
+ dispose() {
152
+ if (!disposed) {
153
+ disposed = true;
154
+ unsubscribe();
155
+ }
156
+ },
157
+ };
158
+ }
159
+ const RouterContext = createContext(undefined);
160
+ export const RouterProvider = RouterContext.Provider;
161
+ export function useRouter() {
162
+ const router = useContext(RouterContext);
163
+ if (!router)
164
+ throw new Error("useRouter requires a RouterProvider");
165
+ return router;
166
+ }
167
+ export function Link({ href, replace, target, download, onClick, children, ...props }, context) {
168
+ const router = useRouter();
169
+ const click = (event) => {
170
+ onClick?.(event);
171
+ if (event.defaultPrevented ||
172
+ event.button !== 0 ||
173
+ event.metaKey ||
174
+ event.ctrlKey ||
175
+ event.shiftKey ||
176
+ event.altKey ||
177
+ (target && target.toLowerCase() !== "_self") ||
178
+ download !== undefined)
179
+ return;
180
+ const win = browserWindow();
181
+ const origin = win?.location.origin ?? memoryOrigin;
182
+ let url;
183
+ try {
184
+ url = new URLConstructor(href, origin + router.location.value.pathname);
185
+ }
186
+ catch {
187
+ return;
188
+ }
189
+ if (url.origin !== origin)
190
+ return;
191
+ event.preventDefault();
192
+ router.navigate(href, { replace });
193
+ };
194
+ const linkHref = mapSignal(router.location, () => {
195
+ try {
196
+ return router.resolve(href);
197
+ }
198
+ catch {
199
+ return href;
200
+ }
201
+ });
202
+ return context.runtime.h("a", { ...props, href: linkHref, target, download, onClick: click }, children);
203
+ }
204
+ export function RouterView({ fallback = null }, context) {
205
+ const router = useRouter();
206
+ return mapSignal(router.route, (match) => match ? context.runtime.h(match.route.component, { params: match.params }) : fallback);
207
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "meowjsx",
3
- "version": "0.3.0-alpha.2",
3
+ "version": "0.3.0-alpha.3",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -29,6 +29,10 @@
29
29
  "types": "./dist/src/signal.d.ts",
30
30
  "import": "./dist/src/signal.js"
31
31
  },
32
+ "./router": {
33
+ "types": "./dist/src/router.d.ts",
34
+ "import": "./dist/src/router.js"
35
+ },
32
36
  "./i18n": {
33
37
  "types": "./dist/src/i18n.d.ts",
34
38
  "import": "./dist/src/i18n.js"