@teyik0/furin 0.9.0-alpha.3 → 0.9.0-alpha.5

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 (75) hide show
  1. package/dist/adapter/runtime-build.d.ts +1 -0
  2. package/dist/build/index.js +65 -25
  3. package/dist/build/route-metadata.d.ts +1 -1
  4. package/dist/cli/index.js +65 -25
  5. package/dist/client/chunks/{client-rdxyrw11.js → client-hjqd5m3b.js} +1 -1
  6. package/dist/client/chunks/{client-d9v49jwz.js → client-whph3y67.js} +66 -3
  7. package/dist/client/chunks/{client-a7spxfnn.js → client-xf7r768c.js} +13 -1
  8. package/dist/client/define-route.d.ts +12 -0
  9. package/dist/client/internal/runtime-types.d.ts +7 -0
  10. package/dist/client/link.js +200 -40
  11. package/dist/client/query.d.ts +13 -0
  12. package/dist/client/route-element.d.ts +5 -0
  13. package/dist/client/router/history.d.ts +6 -0
  14. package/dist/client/router/link-utils.d.ts +7 -0
  15. package/dist/client/router/navigation-controller.d.ts +20 -2
  16. package/dist/client/router/pending.d.ts +17 -0
  17. package/dist/client/router/search/index.d.ts +2 -0
  18. package/dist/client/router/search/index.js +7 -3
  19. package/dist/client/router/types.d.ts +21 -1
  20. package/dist/client.d.ts +1 -1
  21. package/dist/client.js +21 -4
  22. package/dist/define-route.d.ts +37 -10
  23. package/dist/furin.js +92 -43
  24. package/dist/plugin/client-plugin.d.ts +1 -1
  25. package/dist/plugin/index.js +36 -17
  26. package/dist/plugin/route-manifest.d.ts +2 -1
  27. package/dist/plugin/strip-server-stages.d.ts +1 -1
  28. package/dist/server/dev/graph.d.ts +0 -1
  29. package/dist/server/internal.d.ts +1 -0
  30. package/dist/server/internal.js +46 -22
  31. package/dist/server/router/defined-route.d.ts +3 -0
  32. package/dist/server/router/hmr.d.ts +0 -1
  33. package/dist/server/router/source-version.d.ts +0 -1
  34. package/dist/server/router/types.d.ts +7 -1
  35. package/dist/server/static-export.js +49 -22
  36. package/dist/server/sync/index.js +1 -1
  37. package/dist/shared/pending.d.ts +13 -0
  38. package/dist/shared/search-params.d.ts +1 -0
  39. package/dist/sync-client.js +1 -1
  40. package/package.json +1 -1
  41. package/src/adapter/runtime-build.ts +4 -0
  42. package/src/build/hydrate.ts +11 -2
  43. package/src/build/preload-manifest.ts +3 -1
  44. package/src/build/route-metadata.ts +3 -2
  45. package/src/client/define-route.ts +23 -3
  46. package/src/client/internal/runtime-types.ts +7 -0
  47. package/src/client/link.tsx +26 -4
  48. package/src/client/query-store.ts +2 -1
  49. package/src/client/query.tsx +87 -0
  50. package/src/client/route-element.tsx +41 -15
  51. package/src/client/router/context.ts +29 -8
  52. package/src/client/router/history.ts +10 -0
  53. package/src/client/router/link-utils.ts +23 -0
  54. package/src/client/router/navigation-controller.ts +239 -19
  55. package/src/client/router/pending.ts +58 -0
  56. package/src/client/router/provider.tsx +5 -2
  57. package/src/client/router/search/index.ts +7 -2
  58. package/src/client/router/types.ts +29 -3
  59. package/src/client.ts +1 -1
  60. package/src/define-route.ts +74 -26
  61. package/src/plugin/client-plugin.ts +5 -4
  62. package/src/plugin/route-config.ts +9 -2
  63. package/src/plugin/route-manifest.ts +11 -3
  64. package/src/plugin/route-tree.ts +2 -2
  65. package/src/plugin/strip-server-stages.ts +60 -35
  66. package/src/server/dev/graph.ts +2 -7
  67. package/src/server/dev/runtime.ts +1 -2
  68. package/src/server/internal.ts +1 -0
  69. package/src/server/router/defined-route.ts +6 -0
  70. package/src/server/router/discovery.ts +5 -2
  71. package/src/server/router/hmr.ts +1 -5
  72. package/src/server/router/source-version.ts +3 -6
  73. package/src/server/router/types.ts +7 -1
  74. package/src/shared/pending.ts +16 -0
  75. package/src/shared/search-params.ts +1 -1
@@ -4,6 +4,8 @@ import type { RequestLoaderContext } from "../../define-route.ts";
4
4
  import type { ErrorComponent } from "../../shared/error.ts";
5
5
  import type { NotFoundComponent } from "../../shared/not-found.ts";
6
6
  import type { RemountDeps } from "../../shared/page-key.ts";
7
+ import type { RoutePending } from "../../shared/pending.ts";
8
+ import type { SearchParamsInput } from "../../shared/search-params.ts";
7
9
 
8
10
  /**
9
11
  * Loader data after type erasure: field name → value. Each route declares the
@@ -29,11 +31,15 @@ export interface RuntimeRoute {
29
31
  errorComponent?: ErrorComponent;
30
32
  layout?: React.FC<RuntimeData & { children: React.ReactNode }>;
31
33
  loader?: (ctx: RuntimeData) => Awaitable<RuntimeData>;
34
+ /** Page-only: the part of the validated query its loaders read. */
35
+ loaderDeps?: (query: SearchParamsInput) => object;
32
36
  mode?: RenderingMode;
33
37
  /** TanStack style: `.notFound()` of the route. */
34
38
  notFoundComponent?: NotFoundComponent;
35
39
  params?: unknown;
36
40
  parent?: RuntimeRoute;
41
+ /** TanStack style: `.pending()` of the route. */
42
+ pending?: RoutePending;
37
43
  query?: unknown;
38
44
  remountDeps?: RemountDeps<object, object>;
39
45
  requestLoader?: (ctx: RequestLoaderContext) => Awaitable<object>;
@@ -52,6 +58,7 @@ export interface RuntimePage {
52
58
  loader?: (ctx: RuntimeData) => Awaitable<RuntimeData>;
53
59
  mode?: RenderingMode;
54
60
  notFoundComponent?: NotFoundComponent;
61
+ pending?: RoutePending;
55
62
  revalidate?: number;
56
63
  staticParams?: RuntimeStaticParams;
57
64
  tags?: string[];
@@ -1,7 +1,14 @@
1
1
  "use client";
2
2
 
3
3
  import type React from "react";
4
- import { createElement, useCallback, useEffect, useRef, useSyncExternalStore } from "react";
4
+ import {
5
+ createElement,
6
+ useCallback,
7
+ useEffect,
8
+ useMemo,
9
+ useRef,
10
+ useSyncExternalStore,
11
+ } from "react";
5
12
  import {
6
13
  findSearchDefaultsForRouteTarget,
7
14
  type SearchParamsInput,
@@ -12,6 +19,7 @@ import {
12
19
  buildHref,
13
20
  navigationHrefPolicy,
14
21
  normalizeHref,
22
+ resolveTargetSearch,
15
23
  shouldInterceptClick,
16
24
  } from "./router/link-utils.ts";
17
25
  import type {
@@ -110,6 +118,7 @@ function LinkInteractive<To extends RouteTo>({
110
118
  replace,
111
119
  disabled,
112
120
  resetScroll,
121
+ shallow,
113
122
  activeProps,
114
123
  inactiveProps,
115
124
  onClick,
@@ -129,6 +138,18 @@ function LinkInteractive<To extends RouteTo>({
129
138
  // logicalHref: route-relative path (no basePath), used for navigation + active state.
130
139
  // physicalHref (href): what the browser sees — basePath + logicalHref.
131
140
  const { activeHref, logicalHref, href } = resolveLinkHref({ hash, params, search, to }, router);
141
+ // Keyed by `logicalHref`, which encodes `to`, `params` and `search`: inline objects keep one identity.
142
+ const targetSearch = useMemo(
143
+ () =>
144
+ resolveTargetSearch(
145
+ // biome-ignore lint/nursery/useReactCompiler: read through `logicalHref`, see above.
146
+ applyLinkParams(to as string, params as Record<string, string | number> | null | undefined),
147
+ search as SearchParamsInput | null | undefined,
148
+ router.searchRoutes
149
+ ),
150
+ // react-doctor-disable-next-line react-doctor/exhaustive-deps
151
+ [logicalHref, router.searchRoutes]
152
+ );
132
153
  // Select only this Link's active state so unrelated navigation state
133
154
  // (isNavigating, other hrefs, search) does not re-render it.
134
155
  const isActive = useSyncExternalStore(
@@ -158,9 +179,9 @@ function LinkInteractive<To extends RouteTo>({
158
179
  window.location.pathname
159
180
  );
160
181
  if (target !== null) {
161
- prefetch(target, { staleTime: effectiveStaleTime });
182
+ prefetch(target, { search: targetSearch, staleTime: effectiveStaleTime });
162
183
  }
163
- }, [prefetch, effectiveStaleTime, router.basePath]);
184
+ }, [prefetch, effectiveStaleTime, router.basePath, targetSearch]);
164
185
 
165
186
  // "render": preload immediately on mount, and again when the target changes.
166
187
  useEffect(() => {
@@ -235,7 +256,7 @@ function LinkInteractive<To extends RouteTo>({
235
256
  return;
236
257
  }
237
258
  // navigate() expects the logical href (no basePath prefix).
238
- router.navigate(target, { replace, resetScroll: resetScroll ?? true });
259
+ router.navigate(target, { replace, resetScroll, search: targetSearch, shallow });
239
260
  };
240
261
 
241
262
  const handleMouseEnter = (e: React.MouseEvent<HTMLAnchorElement>) => {
@@ -333,6 +354,7 @@ function renderLinkElement<To extends RouteTo>(
333
354
  preloadStaleTime: _ps,
334
355
  replace: _r,
335
356
  resetScroll: _rs,
357
+ shallow: _sh,
336
358
  onClick: _oc,
337
359
  onMouseEnter: _ome,
338
360
  onMouseLeave: _oml,
@@ -243,10 +243,11 @@ export class QueryStore {
243
243
  }
244
244
  }
245
245
  entry.snapshot = { ...entry.snapshot, data };
246
+ // Before any listener: a listener reading `revision()` must see this publish.
247
+ this.revisionValue += 1;
246
248
  for (const listener of entry.listeners) {
247
249
  listener();
248
250
  }
249
- this.revisionValue += 1;
250
251
  for (const listener of this.listeners) {
251
252
  listener();
252
253
  }
@@ -4,6 +4,7 @@ import {
4
4
  useCallback,
5
5
  useContext,
6
6
  useEffect,
7
+ useState,
7
8
  useSyncExternalStore,
8
9
  } from "react";
9
10
  import { LIVE_QUERY, type LiveQuery, type QueryStore, type ReadResult } from "./query-store.ts";
@@ -48,3 +49,89 @@ export function useQuery<Result extends ReadResult, Selected = LiveData<Result>>
48
49
  isFetching: state.isFetching,
49
50
  };
50
51
  }
52
+
53
+ /**
54
+ * Pages are ordinary store entries keyed by their URL: invalidation refetches every loaded page.
55
+ * The hook owns only how many pages are shown; a new first page (changed filters) restarts at one.
56
+ */
57
+ export function useInfiniteQuery<Result extends ReadResult>(
58
+ page: (index: number) => LiveQuery<Result>,
59
+ options: { next: (last: LiveData<Result>) => boolean }
60
+ ): {
61
+ error: Result["error"] | null;
62
+ fetchNext: () => void;
63
+ hasNext: boolean;
64
+ isFetching: boolean;
65
+ pages: LiveData<Result>[];
66
+ } {
67
+ const first = page(0)[LIVE_QUERY];
68
+ const context = useContext(QueryStoreContext);
69
+ const store = context ?? first.reference.client;
70
+ const firstUrl = store.readKey(first.reference, first.options);
71
+ const [loaded, setLoaded] = useState({ count: 1, firstUrl });
72
+ if (loaded.firstUrl !== firstUrl) {
73
+ setLoaded({ count: 1, firstUrl });
74
+ }
75
+ const count = loaded.firstUrl === firstUrl ? loaded.count : 1;
76
+ const urls = Array.from({ length: count }, (_, index) => {
77
+ const { options: readOptions, reference } = page(index)[LIVE_QUERY];
78
+ const url = store.readKey(reference, readOptions);
79
+ store.bind(url, () => reference.load(readOptions), reference.client);
80
+ return url;
81
+ });
82
+ // Encoded URLs never contain a newline: one stable string stands for the page list.
83
+ const key = urls.join("\n");
84
+ const subscribe = useCallback(
85
+ (listener: () => void) => {
86
+ const unsubscribes = key.split("\n").map((url) => store.subscribe(url, listener));
87
+ return () => {
88
+ for (const unsubscribe of unsubscribes) {
89
+ unsubscribe();
90
+ }
91
+ };
92
+ },
93
+ [store, key]
94
+ );
95
+ // The store revision changes on every publish, so it versions all pages at once.
96
+ useSyncExternalStore(subscribe, store.revision, store.revision);
97
+ useEffect(() => {
98
+ for (const url of key.split("\n")) {
99
+ store.fetch(url);
100
+ }
101
+ }, [store, key]);
102
+ const snapshots = urls.map((url) => store.snapshot(url));
103
+ const pages: LiveData<Result>[] = [];
104
+ for (const entry of snapshots) {
105
+ if (entry.data === undefined) {
106
+ break;
107
+ }
108
+ pages.push(entry.data as LiveData<Result>);
109
+ }
110
+ const last = pages.at(-1);
111
+ const hasNext = pages.length === count && last !== undefined && options.next(last);
112
+ const fetchNext = () => {
113
+ // A failed page stays stale in the store: retry it rather than skipping past it.
114
+ const failed = urls.filter((_, index) => snapshots[index]?.error !== null);
115
+ if (failed.length > 0) {
116
+ for (const url of failed) {
117
+ store.fetch(url);
118
+ }
119
+ } else if (hasNext) {
120
+ // Calls in the same render see the same `count`: only the first one adds a page.
121
+ setLoaded((previous) =>
122
+ previous.firstUrl === firstUrl && previous.count === count
123
+ ? { count: count + 1, firstUrl }
124
+ : previous
125
+ );
126
+ }
127
+ };
128
+ return {
129
+ error: (snapshots.find((entry) => entry.error !== null)?.error ?? null) as
130
+ | Result["error"]
131
+ | null,
132
+ fetchNext,
133
+ hasNext,
134
+ isFetching: snapshots.some((entry) => entry.isFetching),
135
+ pages,
136
+ };
137
+ }
@@ -31,6 +31,8 @@ export interface RouteElementInput {
31
31
  data: RuntimeData;
32
32
  /** `undefined` when no page matched the URL. */
33
33
  page: { component: ElementType; pattern: string } | undefined;
34
+ /** Client navigations only: renders in place of everything below the layout at `depth`. */
35
+ pending?: { component: ElementType; depth: number } | undefined;
34
36
  /** Passed to the rendered `error.tsx`. */
35
37
  reset: () => void;
36
38
  /** The root directory's own conventions, used when the root segment failed. */
@@ -77,6 +79,30 @@ function wrapLayout(route: RuntimeRoute | undefined, props: RuntimeData, element
77
79
  return route?.layout ? createElement(route.layout as ElementType, props, element) : element;
78
80
  }
79
81
 
82
+ /**
83
+ * Wraps `element` in the layouts from `depth` up to the root, inside-out: a
84
+ * boundary sits inside the layout at its depth, so it catches that layout's
85
+ * children but not the layout itself.
86
+ */
87
+ function wrapSegments(
88
+ input: RouteElementInput,
89
+ depth: number,
90
+ props: readonly RuntimeData[],
91
+ fallbackProps: RuntimeData,
92
+ element: ReactNode
93
+ ): ReactNode {
94
+ let wrapped = element;
95
+ for (let layout = depth; layout >= 0; layout -= 1) {
96
+ for (const boundary of input.boundaries.toReversed()) {
97
+ if (boundary.depth === layout) {
98
+ wrapped = wrapSegmentBoundaries(wrapped, boundary, input.boundaryOptions);
99
+ }
100
+ }
101
+ wrapped = wrapLayout(input.chain[layout], props[layout] ?? fallbackProps, wrapped);
102
+ }
103
+ return wrapped;
104
+ }
105
+
80
106
  function failureElement(
81
107
  failure: RouteMatchFailure,
82
108
  component: ErrorComponent | NotFoundComponent | undefined,
@@ -115,9 +141,10 @@ export function resolveRouteElement(input: RouteElementInput): ReactNode {
115
141
  props.push({ ...inherited, ...context });
116
142
  }
117
143
 
144
+ const { pending } = input;
118
145
  const index = matches.findIndex((match) => match.status !== "success");
119
146
  const failure = matches[index];
120
- if (failure && failure.status !== "success") {
147
+ if (failure && failure.status !== "success" && !pending) {
121
148
  const { component, depth } = selectRouteBoundary(
122
149
  boundaries,
123
150
  input.rootBoundary,
@@ -137,19 +164,18 @@ export function resolveRouteElement(input: RouteElementInput): ReactNode {
137
164
  const pageProps = Object.fromEntries(
138
165
  Object.entries(data).filter(([key]) => !key.startsWith("__furin"))
139
166
  );
140
- let element: ReactNode = createElement(page.component, {
141
- ...pageProps,
142
- key: pageKey(page.pattern, pageProps, chain.at(-1)?.remountDeps),
143
- });
144
- // Inside-out: a boundary sits inside the layout at its depth, so it catches
145
- // that layout's children but not the layout itself.
146
- for (let layout = chain.length - 1; layout >= 0; layout -= 1) {
147
- for (const boundary of boundaries.toReversed()) {
148
- if (boundary.depth === layout) {
149
- element = wrapSegmentBoundaries(element, boundary, input.boundaryOptions);
150
- }
151
- }
152
- element = wrapLayout(chain[layout], props[layout] ?? pageProps, element);
153
- }
167
+ // The pending screen keeps the page's tree above it, so shared layouts keep their state.
168
+ const element = pending
169
+ ? wrapSegments(input, pending.depth, props, pageProps, createElement(pending.component))
170
+ : wrapSegments(
171
+ input,
172
+ chain.length - 1,
173
+ props,
174
+ pageProps,
175
+ createElement(page.component, {
176
+ ...pageProps,
177
+ key: pageKey(page.pattern, pageProps, chain.at(-1)?.remountDeps),
178
+ })
179
+ );
154
180
  return withRouteSnapshot(element, page.pattern, pageProps);
155
181
  }
@@ -1,5 +1,11 @@
1
1
  import { type Context, createContext, use, useCallback, useContext, useMemo } from "react";
2
- import { navigationHrefPolicy, type RuntimeRouteTarget, resolveRouteTarget } from "./link-utils.ts";
2
+ import {
3
+ applyLinkParams,
4
+ navigationHrefPolicy,
5
+ type RuntimeRouteTarget,
6
+ resolveRouteTarget,
7
+ resolveTargetSearch,
8
+ } from "./link-utils.ts";
3
9
  import type {
4
10
  NavigationOptions,
5
11
  Prefetch,
@@ -8,6 +14,7 @@ import type {
8
14
  RouterNavigate,
9
15
  RouterStore,
10
16
  StableRouter,
17
+ TargetNavigationOptions,
11
18
  } from "./types.ts";
12
19
 
13
20
  // Duplicate module copies (separate entrypoints, client references) must share
@@ -80,10 +87,18 @@ export function useRouterStore(): RouterStore {
80
87
  return { getCurrentHref: () => value.currentHref, router: value, subscribe: subscribeNever };
81
88
  }
82
89
 
90
+ function targetSearch(target: RuntimeRouteTarget, routes: StableRouter["searchRoutes"]) {
91
+ return resolveTargetSearch(
92
+ applyLinkParams(target.to, target.params as Record<string, string | number> | undefined),
93
+ target.search,
94
+ routes
95
+ );
96
+ }
97
+
83
98
  export function useTypedNavigation(context: StableRouter): Pick<Router, "navigate" | "prefetch"> {
84
99
  const { navigate: navigateHref, prefetch: prefetchHref, searchRoutes } = context;
85
100
  const navigate: RouterNavigate = useCallback(
86
- (next: string | (RuntimeRouteTarget & NavigationOptions), opts?: NavigationOptions) => {
101
+ (next: string | (RuntimeRouteTarget & TargetNavigationOptions), opts?: NavigationOptions) => {
87
102
  const href = typeof next === "string" ? next : resolveRouteTarget(next, searchRoutes);
88
103
  const policy = navigationHrefPolicy(
89
104
  href,
@@ -99,11 +114,12 @@ export function useTypedNavigation(context: StableRouter): Pick<Router, "navigat
99
114
  if (typeof next === "string") {
100
115
  return navigateHref(href, opts);
101
116
  }
102
- const options =
103
- next.replace === undefined && next.resetScroll === undefined
104
- ? undefined
105
- : { replace: next.replace, resetScroll: next.resetScroll };
106
- return navigateHref(href, options);
117
+ return navigateHref(href, {
118
+ replace: next.replace,
119
+ resetScroll: next.resetScroll,
120
+ search: targetSearch(next, searchRoutes),
121
+ shallow: next.shallow,
122
+ });
107
123
  },
108
124
  [navigateHref, searchRoutes]
109
125
  );
@@ -120,7 +136,12 @@ export function useTypedNavigation(context: StableRouter): Pick<Router, "navigat
120
136
  if (policy !== "internal") {
121
137
  return;
122
138
  }
123
- prefetchHref(href, typeof next === "string" ? opts : { staleTime: next.staleTime });
139
+ prefetchHref(
140
+ href,
141
+ typeof next === "string"
142
+ ? opts
143
+ : { search: targetSearch(next, searchRoutes), staleTime: next.staleTime }
144
+ );
124
145
  },
125
146
  [prefetchHref, searchRoutes]
126
147
  );
@@ -1,9 +1,19 @@
1
+ import type { SearchParamsInput } from "../../shared/search-params.ts";
2
+
1
3
  export const SCROLL_STORAGE_KEY = "__furin_scroll__";
2
4
 
3
5
  export function getHistoryKey(state: unknown): string | undefined {
4
6
  return (state as { _furinKey?: string } | null)?._furinKey;
5
7
  }
6
8
 
9
+ /**
10
+ * Search furin recorded for the page committed at a history entry: the
11
+ * server-validated query, or the typed search an in-place commit was given.
12
+ */
13
+ export function getHistorySearch(state: unknown): SearchParamsInput | undefined {
14
+ return (state as { _furinSearch?: SearchParamsInput } | null)?._furinSearch;
15
+ }
16
+
7
17
  export function generateHistoryKey(): string {
8
18
  return Math.random().toString(36).slice(2, 9);
9
19
  }
@@ -132,6 +132,29 @@ export function resolveRouteTarget(
132
132
  );
133
133
  }
134
134
 
135
+ /**
136
+ * The validated search a structured destination will read, as far as the
137
+ * client knows it: `search` over the route's schema defaults, empty values
138
+ * dropped like the URL drops them. Undefined when `path` carries its own
139
+ * query string, which only the server parses.
140
+ */
141
+ export function resolveTargetSearch(
142
+ path: string,
143
+ search: object | null | undefined,
144
+ routes: SearchRouteMetadata[]
145
+ ): SearchParamsInput | undefined {
146
+ if (path.includes("?")) {
147
+ return;
148
+ }
149
+ const resolved: SearchParamsInput = { ...findSearchDefaultsForRouteTarget(path, routes) };
150
+ for (const [key, value] of Object.entries(search ?? {})) {
151
+ if (value !== null && value !== undefined) {
152
+ resolved[key] = value;
153
+ }
154
+ }
155
+ return resolved;
156
+ }
157
+
135
158
  /**
136
159
  * Builds a full href string from a pathname, optional search params, and optional hash.
137
160
  * Null/undefined search values are omitted.