@xzsv/router 0.0.0-stage → 0.3.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/src/utils.ts ADDED
@@ -0,0 +1,549 @@
1
+ import type { Component } from 'svelte'
2
+ import { log } from './log.ts'
3
+ import type {
4
+ ComponentTree,
5
+ ComponentTreeNode,
6
+ Cycle,
7
+ Hooks,
8
+ LayoutComponent,
9
+ LazyRouteComponent,
10
+ Location,
11
+ PathParams,
12
+ RouteComponent,
13
+ Routes,
14
+ } from './types.ts'
15
+
16
+ /**
17
+ * Get current location information
18
+ */
19
+ export function getLocation(): Location {
20
+ return {
21
+ pathname: globalThis.location.pathname,
22
+ search: globalThis.location.search,
23
+ state: history.state,
24
+ hash: globalThis.location.hash,
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Check if a component is lazy-loaded
30
+ */
31
+ export function isLazyImport(input: unknown): input is LazyRouteComponent {
32
+ return (
33
+ typeof input === 'function'
34
+ && !!/\(\)\s?=>\s?import\(.*\)/.test(String(input))
35
+ )
36
+ }
37
+
38
+ /**
39
+ * Resolve a single route component (lazy or eager)
40
+ */
41
+ export async function resolveRouteComponent(
42
+ input:
43
+ | RouteComponent
44
+ | [RouteComponent, { submodule?: string; params?: string[] }],
45
+ ): Promise<Component | [Component, { submodule?: string; params?: string[] }]> {
46
+ if (typeof input === 'function' && isLazyImport(input)) {
47
+ const module = await input()
48
+ const resolved = module.default
49
+ if (!resolved) {
50
+ throw new Error('Lazy route module has no default export')
51
+ }
52
+ return resolved
53
+ }
54
+
55
+ if (Array.isArray(input)) {
56
+ if (isLazyImport(input[0])) {
57
+ const module = await input[0]()
58
+ const name = input[1].submodule ?? 'default'
59
+ const resolved = module[name]
60
+ if (!resolved) {
61
+ throw new Error(`Lazy route module has no "${name}" export`)
62
+ }
63
+ return [resolved, input[1]]
64
+ }
65
+ return [input[0] as Component, input[1]]
66
+ }
67
+
68
+ return input as Component
69
+ }
70
+
71
+ /**
72
+ * Resolve multiple route components
73
+ */
74
+ export async function resolveRouteComponents(
75
+ input: (
76
+ | RouteComponent
77
+ | [RouteComponent, { submodule?: string; params?: string[] }]
78
+ )[],
79
+ ): Promise<
80
+ (Component | [Component, { submodule?: string; params?: string[] }])[]
81
+ > {
82
+ return Promise.all(input.map((c) => resolveRouteComponent(c)))
83
+ }
84
+
85
+ /**
86
+ * Join path segments ensuring no double slashes
87
+ */
88
+ export function join(...parts: string[]): string {
89
+ const segments: string[] = []
90
+ for (const part of parts) {
91
+ for (const segment of part.split('/')) {
92
+ if (segment) segments.push(segment)
93
+ }
94
+ }
95
+ return '/' + segments.join('/')
96
+ }
97
+
98
+ /**
99
+ * Construct a path by replacing params in the template
100
+ */
101
+ export function constructPath(
102
+ path: string,
103
+ params?: Record<string, string>,
104
+ ): string {
105
+ if (!params) return path
106
+
107
+ let result = path
108
+ for (const key of Object.keys(params)) {
109
+ result = result.replace(`:${key}`, params[key] ?? '')
110
+ }
111
+ return result
112
+ }
113
+
114
+ /**
115
+ * Build an encoded query string (`'?a=1&b=2'`) from an object. `undefined`,
116
+ * `null` and empty-string values are skipped, so conditional params are a
117
+ * one-liner: `q({ uid: maybeUid })`. Returns `''` when nothing survives —
118
+ * concat it onto any path unconditionally.
119
+ */
120
+ export function q(
121
+ params: Record<string, string | number | boolean | undefined | null>,
122
+ ): string {
123
+ const search = new URLSearchParams()
124
+ for (const [key, value] of Object.entries(params)) {
125
+ if (value === undefined || value === null || value === '') continue
126
+ search.append(key, String(value))
127
+ }
128
+ const encoded = search.toString()
129
+ return encoded ? '?' + encoded : ''
130
+ }
131
+
132
+ /**
133
+ * Check if a path is currently active.
134
+ * `currentPathname` is passed in (from the router's reactive location
135
+ * state) so reactive contexts — templates, effects — re-evaluate when
136
+ * navigation happens.
137
+ */
138
+ export function isActive(
139
+ currentPathname: string,
140
+ pathname: string,
141
+ params?: Record<string, string>,
142
+ ): boolean {
143
+ return compare((a, b) => a === b, currentPathname, pathname, params)
144
+ }
145
+
146
+ /**
147
+ * Check if current path starts with the given path
148
+ */
149
+ isActive.startsWith = (
150
+ currentPathname: string,
151
+ pathname: string,
152
+ params?: Record<string, string>,
153
+ ): boolean => {
154
+ return compare((a, b) => a.startsWith(b), currentPathname, pathname, params)
155
+ }
156
+
157
+ /**
158
+ * Compare current pathname with given pathname
159
+ */
160
+ function compare(
161
+ compareFn: (a: string, b: string) => boolean,
162
+ currentPathname: string,
163
+ pathname: string,
164
+ params?: Record<string, string>,
165
+ ): boolean {
166
+ if (!pathname.includes(':')) {
167
+ return compareFn(currentPathname, pathname)
168
+ }
169
+
170
+ if (params) {
171
+ return compareFn(currentPathname, constructPath(pathname, params))
172
+ }
173
+
174
+ const pathParts = pathname.split('/').slice(1)
175
+ const routeParts = currentPathname.split('/').slice(1)
176
+
177
+ for (const [index, pathPart] of pathParts.entries()) {
178
+ const routePart = routeParts[index] ?? ''
179
+ if (pathPart.startsWith(':')) {
180
+ continue
181
+ }
182
+ return compareFn(pathPart, routePart)
183
+ }
184
+
185
+ return false
186
+ }
187
+
188
+ /**
189
+ * Get all route paths from routes definition
190
+ */
191
+ export function getRoutePaths(routes: Routes): string[] {
192
+ const paths: string[] = []
193
+
194
+ for (const [key, value] of Object.entries(routes)) {
195
+ if (key === 'layout' || key === 'hooks') continue
196
+
197
+ if (
198
+ typeof value === 'object'
199
+ && !Array.isArray(value)
200
+ && typeof value !== 'function'
201
+ ) {
202
+ paths.push(
203
+ ...getRoutePaths(value).map((path) => {
204
+ if (path === '*') return key + '/*'
205
+ if (path === '/') return key
206
+ return key + path
207
+ }),
208
+ )
209
+ } else {
210
+ paths.push(key)
211
+ }
212
+ }
213
+
214
+ return paths
215
+ }
216
+
217
+ /**
218
+ * Validate routes for common issues
219
+ */
220
+ export function validateRoutes(routes: Routes): void {
221
+ const paths = getRoutePaths(routes)
222
+ const wildcardPaths = paths.filter((path) => path.endsWith('*'))
223
+
224
+ for (const wildcardPath of wildcardPaths) {
225
+ const parentPath = wildcardPath.slice(0, -1)
226
+ const dynamicPath = paths.find(
227
+ (p) =>
228
+ p !== '/'
229
+ && !p.endsWith('*')
230
+ && p.startsWith(parentPath === '' ? '/:' : parentPath)
231
+ && p.match(/:[^/]*$/g),
232
+ )
233
+
234
+ if (dynamicPath) {
235
+ console.warn(
236
+ `[Router] Wildcard route "${wildcardPath}" should not be at the same level as dynamic route "${dynamicPath}"`,
237
+ )
238
+ }
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Sort routes by priority (static > dynamic > wildcard)
244
+ */
245
+ export function sortRoutes(routes: string[]): string[] {
246
+ return [...routes].sort(
247
+ (a: string, b: string) => getRoutePriority(a) - getRoutePriority(b),
248
+ )
249
+ }
250
+
251
+ /**
252
+ * Get route priority for sorting
253
+ */
254
+ function getRoutePriority(route: string): number {
255
+ if (route === '' || route === '/') return 1
256
+ if (route.startsWith('*')) return 4
257
+ if (route.includes(':')) return 3
258
+ return 2
259
+ }
260
+
261
+ /**
262
+ * Match a pathname against routes and extract params
263
+ */
264
+ export function matchRoute(
265
+ pathname: string,
266
+ routes: Routes,
267
+ ): {
268
+ match: RouteComponent | undefined
269
+ layouts: LayoutComponent[]
270
+ hooks: Hooks[]
271
+ params: Record<string, string>
272
+ breakFromLayouts: boolean
273
+ } {
274
+ // Remove trailing slash
275
+ if (pathname.length > 1 && pathname.endsWith('/')) {
276
+ pathname = pathname.slice(0, -1)
277
+ }
278
+
279
+ const pathParts = pathname.split('/').slice(1)
280
+ const allRoutes = sortRoutes(
281
+ Object.keys(routes).filter((k) => k !== 'layout' && k !== 'hooks'),
282
+ )
283
+
284
+ let match: RouteComponent | undefined
285
+ let layouts: LayoutComponent[] = []
286
+ let hooks: Hooks[] = []
287
+ let params: Record<string, string> = {}
288
+ let breakFromLayouts = false
289
+
290
+ outer: for (const route of allRoutes) {
291
+ // Each candidate builds its own match state. A candidate that fails
292
+ // late (e.g. '/hub' against '/hub/ember', length mismatch after the
293
+ // layout push) must not leak entries into the next candidate.
294
+ match = undefined
295
+ layouts = []
296
+ hooks = []
297
+ params = {}
298
+ breakFromLayouts = false
299
+ const routeParts = route.split('/')
300
+ if (routeParts[0] === '') routeParts.shift()
301
+
302
+ for (let [index, routePart] of routeParts.entries()) {
303
+ breakFromLayouts = routePart.startsWith('(') && routePart.endsWith(')')
304
+ if (breakFromLayouts) {
305
+ routePart = routePart.slice(1, -1)
306
+ }
307
+
308
+ const pathPart = pathParts[index]
309
+
310
+ // Handle dynamic params
311
+ if (routePart.startsWith(':')) {
312
+ params[routePart.slice(1)] = pathPart ?? ''
313
+ } // Handle wildcards
314
+ else if (routePart.startsWith('*')) {
315
+ const param = routePart.slice(1)
316
+ if (param) {
317
+ params[param] = pathParts.slice(index).join('/')
318
+ }
319
+
320
+ if (breakFromLayouts) {
321
+ routePart = `(${routePart})`
322
+ } else if ('layout' in routes && routes.layout) {
323
+ layouts.push(routes.layout)
324
+ }
325
+
326
+ const resolvedPath = ((index ? '/' : '')
327
+ + routeParts.join('/')) as keyof Routes
328
+ match = routes[resolvedPath] as RouteComponent
329
+ break outer
330
+ } // Must match exactly
331
+ else if (routePart !== pathPart) {
332
+ break
333
+ }
334
+
335
+ // Not at the end yet, continue
336
+ if (index !== routeParts.length - 1) {
337
+ continue
338
+ }
339
+
340
+ const routeMatch = routes[
341
+ ('/' + routeParts.join('/')) as keyof Routes
342
+ ] as RouteComponent
343
+
344
+ if (!breakFromLayouts && 'layout' in routes && routes.layout) {
345
+ layouts.push(routes.layout)
346
+ }
347
+
348
+ if ('hooks' in routes && routes.hooks) {
349
+ hooks.push(routes.hooks)
350
+ }
351
+
352
+ // Direct match
353
+ if (typeof routeMatch === 'function' || Array.isArray(routeMatch)) {
354
+ if (routeParts.length === pathParts.length) {
355
+ match = routeMatch
356
+ break outer
357
+ }
358
+ continue
359
+ }
360
+
361
+ // Nested routes
362
+ const nestedPathname = '/' + pathParts.slice(index + 1).join('/')
363
+ const result = matchRoute(nestedPathname, routeMatch)
364
+
365
+ if (result) {
366
+ match = result.match
367
+ params = { ...params, ...result.params }
368
+ hooks.push(...result.hooks)
369
+
370
+ if (result.breakFromLayouts) {
371
+ layouts = []
372
+ } else {
373
+ layouts.push(...result.layouts)
374
+ }
375
+ }
376
+ break outer
377
+ }
378
+ }
379
+
380
+ return { match, layouts, hooks, params, breakFromLayouts }
381
+ }
382
+
383
+ /**
384
+ * Calculate the component tree for dual-tree rendering
385
+ */
386
+ export function calculateTree(args: {
387
+ prev: ComponentTree['value']
388
+ next: (Component | [Component, { submodule?: string; params?: string[] }])[]
389
+ cycle: Cycle
390
+ params: Record<string, string>
391
+ mountedComponents: Record<string, any>
392
+ }): ComponentTree['value'] {
393
+ const { prev, next, cycle, params, mountedComponents } = args
394
+
395
+ const outgoing = prev[cycle.from]?.length ? prev[cycle.from] : prev[cycle.to]
396
+ const keys = outgoing?.map((item) => item.key) ?? []
397
+
398
+ const tree = {
399
+ [cycle.from]: outgoing,
400
+ [cycle.to]: next.map((item, idx) => {
401
+ if (Array.isArray(item)) {
402
+ return {
403
+ C: item[0],
404
+ key: keys[idx] ?? 0,
405
+ params: 'params' in item[1]
406
+ ? Object.fromEntries(item[1].params!.map((p) => [p, params[p]]))
407
+ : undefined,
408
+ }
409
+ }
410
+ return {
411
+ C: item,
412
+ key: keys[idx] ?? 0,
413
+ }
414
+ }),
415
+ eq: -1,
416
+ } as ComponentTree['value']
417
+
418
+ // Find equality point
419
+ const fromNodes = tree[cycle.from] ?? []
420
+ const toNodes = tree[cycle.to] ?? []
421
+ const max = Math.min(tree.a.length, tree.b.length)
422
+ let i = -1
423
+
424
+ while (++i < max) {
425
+ if (
426
+ fromNodes[i]!.C !== toNodes[i]!.C
427
+ || fromNodes[i]!.params !== toNodes[i]!.params
428
+ ) {
429
+ toNodes[i]!.key++
430
+ i++
431
+ break
432
+ }
433
+ tree.eq = i
434
+ }
435
+
436
+ // Increment keys for remaining components
437
+ i--
438
+ while (++i < toNodes.length) {
439
+ toNodes[i]!.key++
440
+ }
441
+
442
+ // Initialize mounted components
443
+ for (let idx = 0; idx < toNodes.length; idx++) {
444
+ const { key } = toNodes[idx]!
445
+ mountedComponents[`${idx} ${key}`] = {}
446
+ }
447
+ log.debug({ tree })
448
+
449
+ return tree
450
+ }
451
+
452
+ /**
453
+ * Get component keys for in/out transitions
454
+ */
455
+ export function getCompKeys(
456
+ tree: ComponentTree['value'],
457
+ cycle: Cycle,
458
+ ): { in: string[]; out: string[] } {
459
+ const keys: { in: string[]; out: string[] } = { in: [], out: [] }
460
+
461
+ if (cycle.to) {
462
+ for (let i = tree.eq + 1; i < tree[cycle.to].length; i++) {
463
+ keys.in.push(`${i} ${tree[cycle.to][i]!.key}`)
464
+ }
465
+ }
466
+
467
+ if (cycle.from) {
468
+ for (let i = tree.eq + 1; i < tree[cycle.from].length; i++) {
469
+ keys.out.push(`${i} ${tree[cycle.from][i]!.key}`)
470
+ }
471
+ }
472
+
473
+ return keys
474
+ }
475
+
476
+ /**
477
+ * Clean up mounted components that are no longer in use
478
+ */
479
+ export function cleanMountedComponents(
480
+ mountedComponents: Record<string, any>,
481
+ componentTree: ComponentTree,
482
+ ): void {
483
+ const toClean = Object.entries(mountedComponents)
484
+ .filter(([k]) => {
485
+ const [depth = '0', key = '0'] = k.split(' ')
486
+ const depthNum = parseInt(depth)
487
+ const keyNum = parseInt(key)
488
+
489
+ if (
490
+ keyNum
491
+ < Math.min(
492
+ componentTree.value.a[depthNum]?.key ?? Infinity,
493
+ componentTree.value.b[depthNum]?.key ?? Infinity,
494
+ )
495
+ ) {
496
+ return true
497
+ }
498
+ return false
499
+ })
500
+ .map(([k]) => k)
501
+
502
+ for (const key of toClean) {
503
+ delete mountedComponents[key]
504
+ }
505
+ }
506
+
507
+ /**
508
+ * Setup preloading on hover for links
509
+ */
510
+ export function preloadOnHover(routes: Routes, baseName?: string): void {
511
+ const linkSet = new Set<Element>()
512
+
513
+ const observer = new MutationObserver(() => {
514
+ const links = document.querySelectorAll('a[data-preload]')
515
+
516
+ for (const link of links) {
517
+ if (linkSet.has(link)) continue
518
+ linkSet.add(link)
519
+
520
+ link.addEventListener('mouseenter', function callback() {
521
+ link.removeEventListener('mouseenter', callback)
522
+ const href = link.getAttribute('href')
523
+ if (!href) return
524
+
525
+ let path = new URL(href, globalThis.location.origin).pathname
526
+ if (baseName && path.startsWith(baseName)) {
527
+ path = path.slice(baseName.length) || '/'
528
+ }
529
+ const { match, layouts } = matchRoute(path, routes)
530
+ resolveRouteComponents(match ? [...layouts, match] : layouts)
531
+ })
532
+ }
533
+ })
534
+
535
+ observer.observe(document.body, {
536
+ subtree: true,
537
+ childList: true,
538
+ })
539
+ }
540
+
541
+ /**
542
+ * Use a simple **FNV-1a 32-bit** or **CRC32** hash. Both are ~5-10 lines of pure TS with no dependencies. FNV-1a is even simpler and faster than CRC32.
543
+ * **One caveat:** If you ever need to debug which params a mounted component has (via `mountedComponents` keys), you lose readability. You could keep `JSON.stringify` in dev mode only.
544
+ */
545
+ export function fnv1a(str: string): string {
546
+ let h = 2166136261 >>> 0
547
+ for (let i = 0; i < str.length; i++) h = (h ^ str.charCodeAt(i)) * 16777619 >>> 0
548
+ return (h >>> 0).toString(16).padStart(8, '0')
549
+ }