keits 0.0.2 → 0.0.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.
Files changed (39) hide show
  1. package/dist/dev/index.js +409 -122
  2. package/dist/dev/router.js +443 -0
  3. package/dist/dev/shared/{element-By0uLZli.js → element-C4DfKtZW.js} +2 -291
  4. package/dist/dev/shared/graph-D6-x_CWC.js +324 -0
  5. package/dist/dev/shared/owner-DlUsXKXE.js +122 -0
  6. package/dist/dev/svg.js +1 -1
  7. package/dist/prod/index.js +350 -166
  8. package/dist/prod/router.js +343 -0
  9. package/dist/prod/shared/element-DUtXb3px.js +187 -0
  10. package/dist/prod/shared/graph-C_aA46c6.js +240 -0
  11. package/dist/prod/shared/owner-DgJNPM0P.js +104 -0
  12. package/dist/prod/svg.js +1 -1
  13. package/dist/types/async/index.d.ts +2 -0
  14. package/dist/types/async/lazy.d.ts +7 -0
  15. package/dist/types/async/resource.d.ts +23 -0
  16. package/dist/types/async/suspense-context.d.ts +4 -0
  17. package/dist/types/core/graph.d.ts +8 -0
  18. package/dist/types/dom/types.d.ts +1 -1
  19. package/dist/types/flow/catch.d.ts +2 -0
  20. package/dist/types/flow/dynamic.d.ts +6 -0
  21. package/dist/types/flow/for.d.ts +7 -0
  22. package/dist/types/flow/if.d.ts +4 -0
  23. package/dist/types/flow/index.d.ts +8 -0
  24. package/dist/types/flow/portal.d.ts +2 -0
  25. package/dist/types/flow/range.d.ts +11 -0
  26. package/dist/types/flow/show.d.ts +1 -0
  27. package/dist/types/flow/suspense.d.ts +2 -0
  28. package/dist/types/flow/switch.d.ts +9 -0
  29. package/dist/types/index.d.ts +2 -0
  30. package/dist/types/router/history.d.ts +21 -0
  31. package/dist/types/router/index.d.ts +3 -0
  32. package/dist/types/router/links.d.ts +1 -0
  33. package/dist/types/router/match.d.ts +15 -0
  34. package/dist/types/router/router.d.ts +10 -0
  35. package/dist/types/router/scroll.d.ts +5 -0
  36. package/dist/types/router/types.d.ts +87 -0
  37. package/dist/types/svg/types.d.ts +1 -1
  38. package/package.json +23 -6
  39. package/dist/prod/shared/element-C8c5hIhH.js +0 -394
@@ -0,0 +1,443 @@
1
+ import { c as computed, i as onCleanup, l as signal } from "./shared/owner-DlUsXKXE.js";
2
+ import { c as handleError, h as untrack, i as batch, n as addMount, p as runWithOwner, s as getOwner } from "./shared/graph-D6-x_CWC.js";
3
+ // src/router/history.ts
4
+ var newKey = () => Math.random().toString(36).slice(2, 10);
5
+ var stateKey = () => window.history.state?.keitsKey ?? "start";
6
+ function browserHistory(base = "") {
7
+ const prefix = base.replace(/\/+$/, "");
8
+ return {
9
+ read() {
10
+ let path = window.location.pathname;
11
+ if (prefix !== "" && path.startsWith(prefix)) path = path.slice(prefix.length);
12
+ return {
13
+ path: path || "/",
14
+ search: window.location.search,
15
+ hash: window.location.hash
16
+ };
17
+ },
18
+ push: (url) => window.history.pushState({ keitsKey: newKey() }, "", prefix + url),
19
+ replace: (url) => window.history.replaceState(window.history.state, "", prefix + url),
20
+ listen(callback) {
21
+ window.addEventListener("popstate", callback);
22
+ return () => window.removeEventListener("popstate", callback);
23
+ },
24
+ href: (url) => prefix + url,
25
+ toAppUrl(url) {
26
+ let path = url.pathname;
27
+ if (prefix !== "") {
28
+ if (path !== prefix && !path.startsWith(`${prefix}/`)) return null;
29
+ path = path.slice(prefix.length) || "/";
30
+ }
31
+ return path + url.search + url.hash;
32
+ },
33
+ key: stateKey
34
+ };
35
+ }
36
+ function hashHistory() {
37
+ return {
38
+ read() {
39
+ const raw = window.location.hash.slice(1) || "/";
40
+ return splitUrl(raw.startsWith("/") ? raw : `/${raw}`);
41
+ },
42
+ push: (url) => window.history.pushState({ keitsKey: newKey() }, "", `#${url}`),
43
+ replace: (url) => window.history.replaceState(window.history.state, "", `#${url}`),
44
+ listen(callback) {
45
+ window.addEventListener("popstate", callback);
46
+ window.addEventListener("hashchange", callback);
47
+ return () => {
48
+ window.removeEventListener("popstate", callback);
49
+ window.removeEventListener("hashchange", callback);
50
+ };
51
+ },
52
+ href: (url) => `#${url}`,
53
+ toAppUrl(url) {
54
+ if (url.pathname !== window.location.pathname || url.search !== window.location.search) return null;
55
+ return url.hash.startsWith("#/") ? url.hash.slice(1) : null;
56
+ },
57
+ key: stateKey
58
+ };
59
+ }
60
+ function memoryHistory(initial = "/") {
61
+ const entries = [initial];
62
+ const keys = ["start"];
63
+ let index = 0;
64
+ const listeners = /* @__PURE__ */ new Set();
65
+ const notify = () => {
66
+ for (const listener of listeners) listener();
67
+ };
68
+ return {
69
+ read: () => splitUrl(entries[index]),
70
+ push(url) {
71
+ entries.splice(index + 1, entries.length, url);
72
+ keys.splice(index + 1, keys.length, newKey());
73
+ index++;
74
+ },
75
+ replace(url) {
76
+ entries[index] = url;
77
+ },
78
+ listen(callback) {
79
+ listeners.add(callback);
80
+ return () => listeners.delete(callback);
81
+ },
82
+ href: (url) => url,
83
+ toAppUrl: (url) => url.pathname + url.search + url.hash,
84
+ key: () => keys[index],
85
+ back() {
86
+ if (index > 0) index--;
87
+ notify();
88
+ },
89
+ forward() {
90
+ if (index < entries.length - 1) index++;
91
+ notify();
92
+ }
93
+ };
94
+ }
95
+ function splitUrl(url) {
96
+ const hashAt = url.indexOf("#");
97
+ const hash = hashAt >= 0 ? url.slice(hashAt) : "";
98
+ const rest = hashAt >= 0 ? url.slice(0, hashAt) : url;
99
+ const searchAt = rest.indexOf("?");
100
+ const search = searchAt >= 0 ? rest.slice(searchAt) : "";
101
+ return {
102
+ path: (searchAt >= 0 ? rest.slice(0, searchAt) : rest) || "/",
103
+ search: search === "?" ? "" : search,
104
+ hash: hash === "#" ? "" : hash
105
+ };
106
+ }
107
+ // src/router/links.ts
108
+ function linkTarget(event, toAppUrl) {
109
+ if (event.defaultPrevented || event.button !== 0) return null;
110
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return null;
111
+ const start = event.target;
112
+ if (!(start instanceof Element)) return null;
113
+ const link = start.closest("a");
114
+ if (link === null) return null;
115
+ const href = link.getAttribute("href");
116
+ if (href === null || link.hasAttribute("download") || link.hasAttribute("data-native")) return null;
117
+ const target = link.getAttribute("target");
118
+ if (target !== null && target !== "" && target !== "_self") return null;
119
+ if (/(^|\s)external(\s|$)/i.test(link.getAttribute("rel") ?? "")) return null;
120
+ let url;
121
+ try {
122
+ url = new URL(href, document.baseURI);
123
+ } catch {
124
+ return null;
125
+ }
126
+ if (url.origin !== window.location.origin) return null;
127
+ return toAppUrl(url);
128
+ }
129
+ // src/router/match.ts
130
+ function joinPath(parent, path) {
131
+ if (path.startsWith("/")) return path;
132
+ if (path === "") return parent === "" ? "/" : parent;
133
+ if (parent === "" || parent === "/") return `/${path}`;
134
+ return `${parent}/${path}`;
135
+ }
136
+ function compileRoutes(routes) {
137
+ const branches = [];
138
+ const walk = (list, parentPath, parents) => {
139
+ for (const route of list) {
140
+ const path = joinPath(parentPath, route.path);
141
+ const chain = [...parents, route];
142
+ if (route.children && route.children.length > 0) walk(route.children, path, chain);
143
+ if (route.component || !route.children) branches.push(compileBranch(path, chain));
144
+ }
145
+ };
146
+ walk(routes, "", []);
147
+ return branches.map((branch, order) => ({
148
+ branch,
149
+ order
150
+ })).sort((a, b) => b.branch.score - a.branch.score || a.order - b.order).map(({ branch }) => branch);
151
+ }
152
+ function compileBranch(path, routes) {
153
+ const keys = [];
154
+ let score = 0;
155
+ const source = path.split("/").filter((segment) => segment !== "").map((segment) => {
156
+ if (segment === "*") {
157
+ keys.push("*");
158
+ score -= 100;
159
+ return "(?:/(.*))?";
160
+ }
161
+ if (segment.startsWith(":")) {
162
+ keys.push(segment.slice(1));
163
+ score += 2;
164
+ return "/([^/]+)";
165
+ }
166
+ score += 3;
167
+ return `/${segment.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`;
168
+ }).join("");
169
+ return {
170
+ path,
171
+ routes,
172
+ keys,
173
+ score,
174
+ pattern: new RegExp(`^${source || ""}/?$`)
175
+ };
176
+ }
177
+ function matchPath(branches, pathname) {
178
+ for (const branch of branches) {
179
+ const result = branch.pattern.exec(pathname);
180
+ if (result === null) continue;
181
+ const params = {};
182
+ branch.keys.forEach((key, i) => {
183
+ params[key] = safeDecode(result[i + 1] ?? "");
184
+ });
185
+ return {
186
+ path: branch.path,
187
+ routes: branch.routes,
188
+ params
189
+ };
190
+ }
191
+ return null;
192
+ }
193
+ function safeDecode(value) {
194
+ try {
195
+ return decodeURIComponent(value);
196
+ } catch {
197
+ return value;
198
+ }
199
+ }
200
+ function branchSchema(match) {
201
+ const schema = {};
202
+ for (const route of match?.routes ?? []) Object.assign(schema, route.query);
203
+ return schema;
204
+ }
205
+ function parseQuery(schema, search) {
206
+ const raw = new URLSearchParams(search);
207
+ const values = {};
208
+ for (const [key, spec] of Object.entries(schema)) {
209
+ const text = raw.get(key);
210
+ if (text === null) continue;
211
+ if (spec === "string") values[key] = text;
212
+ else if (spec === "number") {
213
+ const n = Number(text);
214
+ if (text.trim() !== "" && Number.isFinite(n)) values[key] = n;
215
+ } else if (spec === "boolean") {
216
+ if (text === "true" || text === "1" || text === "") values[key] = true;
217
+ else if (text === "false" || text === "0") values[key] = false;
218
+ } else if (spec.includes(text)) values[key] = text;
219
+ }
220
+ return values;
221
+ }
222
+ function buildSearch(values) {
223
+ const search = new URLSearchParams();
224
+ for (const [key, value] of Object.entries(values)) if (value !== void 0) search.set(key, String(value));
225
+ const text = search.toString();
226
+ return text === "" ? "" : `?${text}`;
227
+ }
228
+ function fillParams(path, params) {
229
+ return path.replace(/:([^/]+)/g, (_, name) => {
230
+ const value = params?.[name];
231
+ if (value === void 0) throw new Error(`[keits/router] Missing param "${name}" for "${path}".`);
232
+ return encodeURIComponent(String(value));
233
+ });
234
+ }
235
+ // src/router/scroll.ts
236
+ function createScroller() {
237
+ const positions = /* @__PURE__ */ new Map();
238
+ if ("scrollRestoration" in window.history) window.history.scrollRestoration = "manual";
239
+ return {
240
+ save(key) {
241
+ positions.set(key, [window.scrollX, window.scrollY]);
242
+ },
243
+ restore(key, popped, pathChanged, hash, hashChanged) {
244
+ const saved = popped ? positions.get(key) : void 0;
245
+ if (saved !== void 0) {
246
+ window.scrollTo(saved[0], saved[1]);
247
+ return;
248
+ }
249
+ if (hash !== "" && (pathChanged || hashChanged)) {
250
+ const element = document.getElementById(decodeHash(hash));
251
+ if (element !== null) {
252
+ element.scrollIntoView();
253
+ return;
254
+ }
255
+ }
256
+ if (pathChanged) window.scrollTo(0, 0);
257
+ }
258
+ };
259
+ }
260
+ function decodeHash(hash) {
261
+ try {
262
+ return decodeURIComponent(hash.slice(1));
263
+ } catch {
264
+ return hash.slice(1);
265
+ }
266
+ }
267
+ // src/router/router.ts
268
+ function createRouter(config) {
269
+ const history = typeof config.history === "object" ? config.history : config.history === "hash" ? hashHistory() : browserHistory(config.base);
270
+ const owner = getOwner();
271
+ const branches = compileRoutes(config.routes);
272
+ const sameLocation = (a, b) => a.path === b.path && a.search === b.search && a.hash === b.hash;
273
+ const location = signal(history.read(), { equals: sameLocation });
274
+ const started = signal(false);
275
+ const pending = signal(false);
276
+ const leaveChecks = /* @__PURE__ */ new Set();
277
+ let navigationId = 0;
278
+ const scroller = config.scroll ?? typeof window !== "undefined" ? createScroller() : null;
279
+ let currentKey = history.key();
280
+ const match = computed(() => started() ? matchPath(branches, location().path) : null);
281
+ const params = computed(() => match()?.params ?? {}, { equals: shallowEqual });
282
+ const query = computed(() => parseQuery(branchSchema(match()), location().search), { equals: shallowEqual });
283
+ const toUrl = (path, options) => {
284
+ const filled = fillParams(path, options?.params);
285
+ const search = options?.query ? buildSearch(options.query) : "";
286
+ const hash = options?.hash ? `#${options.hash.replace(/^#/, "")}` : "";
287
+ return filled + search + hash;
288
+ };
289
+ function resolve(url, mode, redirects = 0) {
290
+ const id = ++navigationId;
291
+ const target = splitUrl(url);
292
+ const from = untrack(started) ? untrack(location) : null;
293
+ const commit = () => {
294
+ if (from !== null) scroller?.save(currentKey);
295
+ if (mode === "push") history.push(url);
296
+ else if (mode === "replace" || redirects > 0) history.replace(url);
297
+ currentKey = history.key();
298
+ const key = currentKey;
299
+ batch(() => {
300
+ pending.set(false);
301
+ started.set(true);
302
+ location.set(history.read());
303
+ if (scroller !== null && from !== null) {
304
+ const pathChanged = from.path !== target.path;
305
+ const hashChanged = from.hash !== target.hash;
306
+ runWithOwner(null, () => addMount(() => scroller.restore(key, mode === "pop", pathChanged, target.hash, hashChanged)));
307
+ }
308
+ });
309
+ return true;
310
+ };
311
+ if (from !== null && from.path === target.path) return Promise.resolve(commit());
312
+ const found = matchPath(branches, target.path);
313
+ const to = {
314
+ path: target.path,
315
+ route: found?.path ?? null,
316
+ params: found?.params ?? {},
317
+ search: target.search,
318
+ from: from?.path ?? null
319
+ };
320
+ const checks = [];
321
+ if (from !== null) for (const check of leaveChecks) checks.push(() => check(to));
322
+ for (const route of found?.routes ?? []) {
323
+ const guard = route.guard;
324
+ if (guard) checks.push(() => guard(to));
325
+ }
326
+ const finish = (result) => {
327
+ if (id !== navigationId) return false;
328
+ if (result === true) return commit();
329
+ pending.set(false);
330
+ if (typeof result === "string") {
331
+ if (redirects >= 10) throw new Error(`[keits/router] Too many redirects (last: "${result}"). Do two guards redirect to each other?`);
332
+ return resolve(result, mode === "pop" ? "replace" : mode, redirects + 1);
333
+ }
334
+ if (mode === "pop" && from !== null) {
335
+ history.push(from.path + from.search + from.hash);
336
+ currentKey = history.key();
337
+ }
338
+ return false;
339
+ };
340
+ const fail = (error) => {
341
+ if (id === navigationId) pending.set(false);
342
+ try {
343
+ handleError(error, owner);
344
+ return Promise.resolve(false);
345
+ } catch (unhandled) {
346
+ return Promise.reject(unhandled);
347
+ }
348
+ };
349
+ const safeFinish = (result) => {
350
+ try {
351
+ return Promise.resolve(finish(result));
352
+ } catch (error) {
353
+ return fail(error);
354
+ }
355
+ };
356
+ let outcome;
357
+ try {
358
+ outcome = runChecks(checks, 0);
359
+ } catch (error) {
360
+ return fail(error);
361
+ }
362
+ if (!isPromiseLike(outcome)) return safeFinish(outcome);
363
+ pending.set(true);
364
+ return outcome.then(safeFinish, fail);
365
+ }
366
+ const stopListening = history.listen(() => {
367
+ const now = history.read();
368
+ resolve(now.path + now.search + now.hash, "pop");
369
+ });
370
+ const initial = history.read();
371
+ resolve(initial.path + initial.search + initial.hash, "start");
372
+ const onClick = (event) => {
373
+ const url = linkTarget(event, (target) => history.toAppUrl(target));
374
+ if (url === null) return;
375
+ event.preventDefault();
376
+ const now = untrack(location);
377
+ resolve(url, url === now.path + now.search + now.hash ? "replace" : "push");
378
+ };
379
+ const listenToLinks = config.links !== false && typeof document !== "undefined";
380
+ if (listenToLinks) document.addEventListener("click", onClick);
381
+ return {
382
+ location: () => location(),
383
+ match: () => match(),
384
+ params: () => params(),
385
+ query: () => query(),
386
+ pending: () => pending(),
387
+ navigate: (path, options) => resolve(path.includes(":") || options?.query || options?.hash ? toUrl(path, options) : path, options?.replace ? "replace" : "push"),
388
+ href: (path, options) => history.href(toUrl(path, options)),
389
+ setQuery(values, options) {
390
+ const current = untrack(location);
391
+ const merged = {
392
+ ...Object.fromEntries(new URLSearchParams(current.search)),
393
+ ...values
394
+ };
395
+ resolve(current.path + buildSearch(merged) + current.hash, options?.push ? "push" : "replace");
396
+ },
397
+ onLeave(check) {
398
+ leaveChecks.add(check);
399
+ onCleanup(() => leaveChecks.delete(check));
400
+ },
401
+ view() {
402
+ const level = (depth, parent) => {
403
+ const route = computed(() => match()?.routes[depth] ?? null);
404
+ return () => {
405
+ const current = route();
406
+ return untrack(() => {
407
+ if (current === null) return parent?.component ? parent.component() : null;
408
+ const outlet = level(depth + 1, current);
409
+ return current.layout ? current.layout({ children: outlet }) : outlet;
410
+ });
411
+ };
412
+ };
413
+ return level(0, null);
414
+ },
415
+ isActive(path, exact = false) {
416
+ const current = location().path.replace(/\/$/, "") || "/";
417
+ const target = splitUrl(path).path.replace(/\/$/, "") || "/";
418
+ if (exact) return current === target;
419
+ return current === target || current.startsWith(`${target}/`);
420
+ },
421
+ dispose() {
422
+ stopListening();
423
+ if (listenToLinks) document.removeEventListener("click", onClick);
424
+ }
425
+ };
426
+ }
427
+ function runChecks(checks, from) {
428
+ for (let i = from; i < checks.length; i++) {
429
+ const result = checks[i]();
430
+ if (isPromiseLike(result)) return Promise.resolve(result).then((value) => value === true ? runChecks(checks, i + 1) : value);
431
+ if (result !== true) return result;
432
+ }
433
+ return true;
434
+ }
435
+ function isPromiseLike(value) {
436
+ return typeof value?.then === "function";
437
+ }
438
+ function shallowEqual(a, b) {
439
+ const keys = Object.keys(a);
440
+ if (keys.length !== Object.keys(b).length) return false;
441
+ return keys.every((key) => Object.is(a[key], b[key]));
442
+ }
443
+ export { browserHistory, createRouter, hashHistory, memoryHistory };