wcz-layout 10.1.10 → 10.2.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.
Files changed (80) hide show
  1. package/dist/Approval-D1TfISUL.mjs.map +1 -1
  2. package/dist/{LayoutTable-CxQNMuwo.d.mts → ChatLayout-BmLySLXy.d.mts} +11 -2
  3. package/dist/ChatLayout-Tpuwo8-b.mjs +1622 -0
  4. package/dist/ChatLayout-Tpuwo8-b.mjs.map +1 -0
  5. package/dist/DialogsContext-D23fJjYR.mjs.map +1 -1
  6. package/dist/Email-rnz3H0x3.mjs.map +1 -1
  7. package/dist/FileMeta-CPBWI_jA.mjs.map +1 -1
  8. package/dist/RouterListItemButton-CF-8w-08.mjs +62 -0
  9. package/dist/RouterListItemButton-CF-8w-08.mjs.map +1 -0
  10. package/dist/{approval-ByDIMRhe.mjs → approval-HB2w5jzc.mjs} +2 -2
  11. package/dist/approval-HB2w5jzc.mjs.map +1 -0
  12. package/dist/auth.mjs +4 -4
  13. package/dist/auth.mjs.map +1 -1
  14. package/dist/components.d.mts +3 -2
  15. package/dist/components.mjs +522 -627
  16. package/dist/components.mjs.map +1 -1
  17. package/dist/{createApi-L3ypB1gH.mjs → createApi-CKgFi53y.mjs} +3 -4
  18. package/dist/createApi-CKgFi53y.mjs.map +1 -0
  19. package/dist/data/client.mjs +3 -4
  20. package/dist/data/client.mjs.map +1 -1
  21. package/dist/data/server.mjs +4 -4
  22. package/dist/data/server.mjs.map +1 -1
  23. package/dist/env-BwFl7nWc.mjs +48 -0
  24. package/dist/env-BwFl7nWc.mjs.map +1 -0
  25. package/dist/{file-CwumKq_P.mjs → file-X1sK4ok6.mjs} +5 -4
  26. package/dist/file-X1sK4ok6.mjs.map +1 -0
  27. package/dist/{file-B4Q_bGLN.mjs → file-tkfsnk5F.mjs} +6 -5
  28. package/dist/file-tkfsnk5F.mjs.map +1 -0
  29. package/dist/generatedChart-k7NEdi5Z.mjs +211 -0
  30. package/dist/generatedChart-k7NEdi5Z.mjs.map +1 -0
  31. package/dist/hooks.d.mts +30 -2
  32. package/dist/hooks.mjs +1750 -1227
  33. package/dist/hooks.mjs.map +1 -1
  34. package/dist/index.d.mts +9 -2
  35. package/dist/index.mjs +1250 -1010
  36. package/dist/index.mjs.map +1 -1
  37. package/dist/middleware.mjs +2 -2
  38. package/dist/middleware.mjs.map +1 -1
  39. package/dist/models.d.mts +2 -2
  40. package/dist/models.mjs.map +1 -1
  41. package/dist/{peoplesoft-D1jPlXr9.mjs → peoplesoft-RnvfLbWH.mjs} +4 -23
  42. package/dist/peoplesoft-RnvfLbWH.mjs.map +1 -0
  43. package/dist/{providers-gKUqnVV5.mjs → providers-BfFg_3eo.mjs} +4 -20
  44. package/dist/providers-BfFg_3eo.mjs.map +1 -0
  45. package/dist/{tokens-DODxwvZ2.mjs → tokens-C4SErO-K.mjs} +10 -4
  46. package/dist/tokens-C4SErO-K.mjs.map +1 -0
  47. package/dist/{utils-obBGIuT3.mjs → utils-C2MZoH9U.mjs} +4 -31
  48. package/dist/utils-C2MZoH9U.mjs.map +1 -0
  49. package/dist/{utils-giYfiv39.d.mts → utils-CNYCSgip.d.mts} +2 -2
  50. package/dist/utils-DnMFybj3.mjs +27 -0
  51. package/dist/utils-DnMFybj3.mjs.map +1 -0
  52. package/dist/utils.d.mts +11 -2
  53. package/dist/utils.mjs +3 -5
  54. package/dist/vite.mjs.map +1 -1
  55. package/package.json +19 -21
  56. package/skills/ai/SKILL.md +156 -97
  57. package/skills/client-db/SKILL.md +104 -90
  58. package/skills/db-schema/SKILL.md +28 -20
  59. package/skills/dialogs/SKILL.md +26 -38
  60. package/skills/forms/SKILL.md +133 -73
  61. package/skills/general/SKILL.md +111 -126
  62. package/skills/general/references/auth.md +3 -7
  63. package/skills/routing/SKILL.md +60 -66
  64. package/skills/server-functions/SKILL.md +71 -26
  65. package/skills/services/SKILL.md +1 -1
  66. package/skills/services/docs/approval.md +4 -4
  67. package/skills/table/SKILL.md +113 -130
  68. package/dist/AggregatedCell-3CIdlmt6.mjs +0 -615
  69. package/dist/AggregatedCell-3CIdlmt6.mjs.map +0 -1
  70. package/dist/RouterListItemButton-B-cQ1XwU.mjs +0 -78
  71. package/dist/RouterListItemButton-B-cQ1XwU.mjs.map +0 -1
  72. package/dist/approval-ByDIMRhe.mjs.map +0 -1
  73. package/dist/createApi-L3ypB1gH.mjs.map +0 -1
  74. package/dist/file-B4Q_bGLN.mjs.map +0 -1
  75. package/dist/file-CwumKq_P.mjs.map +0 -1
  76. package/dist/peoplesoft-D1jPlXr9.mjs.map +0 -1
  77. package/dist/providers-gKUqnVV5.mjs.map +0 -1
  78. package/dist/tokens-DODxwvZ2.mjs.map +0 -1
  79. package/dist/utils-obBGIuT3.mjs.map +0 -1
  80. package/skills/general/references/exports.md +0 -117
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wcz-layout",
3
- "version": "10.1.10",
3
+ "version": "10.2.0",
4
4
  "private": false,
5
5
  "keywords": [
6
6
  "tanstack-intent"
@@ -69,14 +69,14 @@
69
69
  },
70
70
  "dependencies": {
71
71
  "@t3-oss/env-core": "^0.13.11",
72
- "@tanstack/ai-react": "^1.0.0",
73
- "@tanstack/markdown": "^1.0.0",
74
- "i18next": "^26.5.11",
75
- "i18next-browser-languagedetector": "^8.2.3",
72
+ "@tanstack/ai-react": "^1.0.2",
73
+ "@tanstack/markdown": "^1.2.0",
74
+ "i18next": "^26.7.1",
75
+ "i18next-browser-languagedetector": "^8.3.0",
76
76
  "iron-session": "^9.0.1",
77
- "jose": "^6.2.13",
77
+ "jose": "^6.2.15",
78
78
  "react-dropzone": "^20.1.4",
79
- "react-i18next": "^17.1.9",
79
+ "react-i18next": "^17.1.12",
80
80
  "react-intersection-observer": "^11.0.1",
81
81
  "react-number-format": "^5.4.5",
82
82
  "tus-js-client": "^4.3.1",
@@ -84,23 +84,22 @@
84
84
  },
85
85
  "devDependencies": {
86
86
  "@arethetypeswrong/core": "^0.18.5",
87
- "@rolldown/plugin-babel": "^0.2.4",
88
- "@tanstack/ai": "^1.0.0",
89
- "@tanstack/ai-client": "^1.0.0",
90
- "@tanstack/ai-openai": "^1.0.0",
91
- "@tanstack/highlight": "^1.2.0",
87
+ "@tanstack/ai": "^1.1.0",
88
+ "@tanstack/ai-openai": "^1.1.0",
89
+ "@tanstack/highlight": "^1.2.11",
92
90
  "@tanstack/intent": "^0.5.6",
93
91
  "@tanstack/react-pacer": "^0.24.1",
94
- "@types/node": "^24.10.13",
92
+ "@types/node": "^26.6.6",
95
93
  "@types/react": "^19.3.0",
96
94
  "@types/react-dom": "^19.3.0",
97
- "@vitejs/plugin-react": "^6.1.2",
98
- "babel-plugin-react-compiler": "^1.0.0",
99
- "nitro": "npm:nitro-nightly@latest",
95
+ "@vitejs/plugin-react": "^6.2.1",
96
+ "jsdom": "^30.1.3",
97
+ "nitro": "3.0.261103-rc",
98
+ "oxc-transform-react": "^0.157.0",
100
99
  "publint": "^0.3.25",
101
100
  "typescript": "^7.0.2",
102
- "vite": "npm:@voidzero-dev/vite-plus-core@1.4.0",
103
- "vite-plus": "1.4.0"
101
+ "vite": "npm:@voidzero-dev/vite-plus-core@1.5.0",
102
+ "vite-plus": "1.5.0"
104
103
  },
105
104
  "peerDependencies": {
106
105
  "@emotion/cache": "11.x",
@@ -109,8 +108,7 @@
109
108
  "@mui/icons-material": "9.x",
110
109
  "@mui/material": "9.x",
111
110
  "@mui/x-date-pickers": "9.x",
112
- "@tanstack/query-db-collection": "1.x",
113
- "@tanstack/react-db": "0.x",
111
+ "@tanstack/charts": "1.x",
114
112
  "@tanstack/react-form": "1.x",
115
113
  "@tanstack/react-hotkeys": "0.x",
116
114
  "@tanstack/react-pacer": "0.x",
@@ -129,5 +127,5 @@
129
127
  "overrides": {
130
128
  "vite": "$vite"
131
129
  },
132
- "packageManager": "npm@12.2.1"
130
+ "packageManager": "npm@12.2.2"
133
131
  }
@@ -1,97 +1,156 @@
1
- ---
2
- name: ai
3
- description: "Use when adding LLM features (chat, streamed text, structured output, tools, media generation)"
4
- metadata:
5
- type: convention
6
- library: wcz-layout
7
- ---
8
-
9
- > Mechanics are covered by TanStack's own `@tanstack/ai` skills.
10
- > This skill adds the wcz-layout conventions on top of that.
11
-
12
- ## Rules
13
-
14
- - The gateway needs three server-side inputs:
15
- - Ensure that required env are present: `AI_BASE_URL` (`z.url()`) and `AI_SUBSCRIPTION_KEY` (`z.string()`) in `src/env.ts`.
16
- - Pass `getAppToken("cognitiveServices")` as the API key.
17
- - The subscription key sent as the `Ocp-Apim-Subscription-Key` header.
18
- - Build the adapter in one place, `src/server/ai.ts`, and call it per request. `getAppToken`
19
- caches and refreshes the token.
20
- - Build every chat with `createLayoutChatHook(chatFn)` from `wcz-layout/hooks`.
21
- - The model renders MUI components itself (`show_ui`) and asks the user with MUI forms
22
- (`ask_user`). The client sends both tools with every request, so the server function only
23
- merges them: `tools: mergeAgentTools(serverTools, tools)`. It must also forward `parentRunId`
24
- and `resume`, or tool results and approvals never continue the run.
25
- - App tools are server tools (`toolDefinition(...).server(...)`) in `serverTools`; they check the
26
- signed-in user themselves. Give every tool that writes `needsApproval: true`: the chat shows an
27
- Approve / Deny card for it. Their calls show only the progress bar in the transcript.
28
- - Structured output (one typed object, e.g. a generated document) stays raw `useChat` with
29
- `outputSchema` and `partial`, not the chat.
30
- - Render streamed text outside the chat with `@tanstack/markdown` (install if missing):
31
- `<Markdown>` from `@tanstack/markdown/react`.
32
-
33
- ## Example
34
-
35
- ```ts
36
- // src/server/ai.ts
37
- import { createOpenaiChat } from "@tanstack/ai-openai";
38
- import { getAppToken } from "wcz-layout/auth";
39
- import { serverEnv } from "~/env";
40
-
41
- export const aiText = async () =>
42
- createOpenaiChat("some-model", await getAppToken("cognitiveServices"), {
43
- baseURL: serverEnv.AI_BASE_URL,
44
- defaultHeaders: { "Ocp-Apim-Subscription-Key": serverEnv.AI_SUBSCRIPTION_KEY },
45
- });
46
-
47
- // src/server/actions/<feature>.ts
48
- import {
49
- chat,
50
- chatParamsFromRequestBody,
51
- mergeAgentTools,
52
- toServerSentEventsResponse,
53
- toolDefinition,
54
- } from "@tanstack/ai";
55
- import type { RunAgentInput } from "@tanstack/ai/client";
56
- import { createServerFn } from "@tanstack/react-start";
57
- import z from "zod";
58
- import { authMiddleware } from "wcz-layout/middleware";
59
- import { aiText } from "~/server/ai";
60
-
61
- const getOrders = toolDefinition({
62
- name: "get_orders",
63
- description: "Orders of the signed-in user",
64
- inputSchema: z.object({ status: z.enum(["open", "closed"]) }),
65
- }).server(async ({ status }) => findOrders(status));
66
-
67
- export const chatFn = createServerFn({ method: "POST" })
68
- .validator(z.custom<RunAgentInput>())
69
- .middleware([authMiddleware()])
70
- .handler(async ({ data }) => {
71
- const { messages, threadId, runId, parentRunId, resume, tools } =
72
- await chatParamsFromRequestBody(data);
73
- const abortController = new AbortController();
74
- const stream = chat({
75
- adapter: await aiText(),
76
- threadId,
77
- runId,
78
- parentRunId,
79
- resume,
80
- systemPrompts: [SYSTEM_PROMPT],
81
- messages,
82
- tools: mergeAgentTools([getOrders], tools),
83
- abortController,
84
- });
85
- return toServerSentEventsResponse(stream, { abortController });
86
- });
87
- ```
88
-
89
- ```tsx
90
- // client component
91
- import { createLayoutChatHook } from "wcz-layout/hooks";
92
- import { chatFn } from "~/server/actions/chat";
93
-
94
- const { useLayoutChat, LayoutChat } = createLayoutChatHook(chatFn);
95
-
96
- const chat = useLayoutChat({ threadId: "assistant" });
97
- ```
1
+ ---
2
+ name: ai
3
+ description: "Use when adding LLM features (chat, streamed text, structured output, tools, media generation)"
4
+ metadata:
5
+ type: convention
6
+ library: wcz-layout
7
+ ---
8
+
9
+ > Mechanics are covered by TanStack's own `@tanstack/ai` skills.
10
+ > This skill adds the wcz-layout conventions on top of that.
11
+
12
+ ## Rules
13
+
14
+ - Install `@tanstack/ai` in the app (if missing); the server function imports it directly.
15
+ `@tanstack/charts` is a peer of wcz-layout, which npm installs with it; the chat loads it with
16
+ the first chart the model draws, so an app never defines a chart tool of its own.
17
+ - Require the gateway env in the app's `src/env.ts` `server` block, so a missing value fails at
18
+ startup: `AI_BASE_URL: z.url()` and `AI_SUBSCRIPTION_KEY: z.string()`. The gateway token also
19
+ uses the Entra app registration: `ENTRA_TENANT_ID`, `ENTRA_CLIENT_ID`, `ENTRA_CLIENT_SECRET`.
20
+ Values come from `.env.local` or Vault.
21
+ - Import the adapter from `wcz-layout/utils`: `adapter: await chatAdapter("gpt-5.5")`, created
22
+ per request inside the server function. It sends the app token and the subscription key itself.
23
+ Never build an OpenAI adapter in the app: `createOpenaiChat` (Responses API) fails on follow-ups
24
+ with `400 invalid_encrypted_content`, because the gateway load-balances Azure deployments.
25
+ - Call `chatAdapter` only in server functions (`src/server/...`): it reads server env and tokens.
26
+ - Build every chat with `createLayoutChatHook(chatFn)` from `wcz-layout/hooks`. Its labels are
27
+ `Layout.Chat.*` keys: copy the `Layout.Chat` object from wcz-layout's `src/lib/locales/*.json`
28
+ into each of the app's locale files, or the chat shows raw keys.
29
+ - An app-wide assistant is one chat on every page: a component rendering
30
+ `<LayoutChat chat={useLayoutChat({ threadId })} />`, passed as `LayoutProvider`'s
31
+ `options.chat`. It shows for a signed-in user, opens from the app bar and mounts on the first
32
+ open. From `lg` up it docks beside the page and remembers its width and whether it is open;
33
+ below `lg` it covers the page right of the navigation rail, opens only from the button and
34
+ closes when a page opens, so a link, `navigate` or the rail shows the page. A chat page of its own sits in a
35
+ parent with a height (e.g. `Fullscreen`). `LayoutChat` takes `sx` for its root, e.g. a background;
36
+ it has none of its own.
37
+ - Every chat has these client tools built in: `show_ui` (the model renders MUI components, and
38
+ charts: a `Chart` node with TanStack Charts marks as children, their official options as
39
+ props), `ask_user` (asks with an MUI form), `get_user` (the signed-in user), `set_app_theme` (light,
40
+ dark or system), `navigate` (opens one of the app's pages, listed from its route tree, and
41
+ leaves a page whose record was just deleted), `get_time` (the user's current time and zone,
42
+ so the prompt never states it), and `read_page`, `click`, `fill` and `press_key` (the model
43
+ uses the page the user is on as they would: it reads the text and numbered controls, clicks,
44
+ types and presses keys, and never answers a `useDialogs` confirmation). Never define them
45
+ again. The client sends its tools with every request, so the
46
+ server function only merges them: `tools: mergeAgentTools(serverTools, tools)`. It must also
47
+ forward `parentRunId` and `resume`, or tool results and approvals never continue the run.
48
+ - The chat sends the page the user is on as AG-UI context. Put it in the prompt: each
49
+ `aguiContext` item becomes a `"<description>: <value>"` line in `systemPrompts` (see the example).
50
+ - Data and writes are server tools (`toolDefinition(...).server(...)`) in `serverTools` that
51
+ call the app's own server functions, `deleteOrder({ data: id })`: called on the server they run
52
+ in the same request, with the screens' middleware, validation and permission checks. Never
53
+ reimplement a server function for a tool. After a write,
54
+ `context?.emitCustomEvent("invalidate", { queryKey })` makes the chat invalidate that query, so
55
+ open screens refetch.
56
+ - Only tools that delete get `needsApproval: true`: the chat asks "Are you sure?" (Cancel /
57
+ Confirm) before they run, so the prompt tells the model to say first what it will delete.
58
+ Creating and changing run straight away, and the model says what it did.
59
+ - Give feature tools `lazy: true` and pass `lazyToolsConfig: { includeDescription:
60
+ "first-sentence" }` to `chat()`: the model sees names and first sentences, and loads a feature's
61
+ schemas only when a request needs them. Write each description's first sentence to stand alone.
62
+ Pass `agentLoopStrategy: maxIterations(20)` too: the default 5 turns end a run without a reply
63
+ once discovering, looking up and saving add up.
64
+ - The page tools read what a screen reader would, so a page the model can use has a name on
65
+ every control: a `Tooltip` title or `aria-label` on each icon button, a label on each field,
66
+ and a button, link or `CardActionArea` for anything clickable. Deletes confirm through
67
+ `useDialogs`, which the model never clicks.
68
+ - Other browser actions are client tools:
69
+ `useLayoutChat({ threadId, tools: [def.client(run)] })`, with `run` using the screen's hooks.
70
+ - The chat renders markdown links to the app's own pages (`/...`) through the router; tell the
71
+ model the page paths so it links the records it mentions.
72
+ - Structured output (one typed object, e.g. a generated document) stays raw `useChat` with
73
+ `outputSchema` and `partial`, not the chat.
74
+ - Render streamed text outside the chat with `@tanstack/markdown` (install if missing):
75
+ `<Markdown>` from `@tanstack/markdown/react`.
76
+
77
+ ## Example
78
+
79
+ ```ts
80
+ // src/env.ts (server block)
81
+ AI_BASE_URL: z.url(),
82
+ AI_SUBSCRIPTION_KEY: z.string(),
83
+
84
+ // src/server/actions/assistant.ts
85
+ import {
86
+ chat,
87
+ chatParamsFromRequestBody,
88
+ maxIterations,
89
+ mergeAgentTools,
90
+ toServerSentEventsResponse,
91
+ toolDefinition,
92
+ } from "@tanstack/ai";
93
+ import type { RunAgentInput } from "@tanstack/ai/client";
94
+ import { createServerFn } from "@tanstack/react-start";
95
+ import { authMiddleware } from "wcz-layout/middleware";
96
+ import { chatAdapter } from "wcz-layout/utils";
97
+ import z from "zod";
98
+ import { deleteOrder } from "./order"; // the server function the screens call
99
+
100
+ const orderTools = () => [
101
+ toolDefinition({
102
+ name: "delete_order",
103
+ description: "Delete one of the user's orders.",
104
+ inputSchema: z.object({ id: z.uuid() }),
105
+ needsApproval: true,
106
+ lazy: true,
107
+ }).server(async ({ id }, context) => {
108
+ await deleteOrder({ data: id });
109
+ context?.emitCustomEvent("invalidate", { queryKey: ["orders"] });
110
+ return { deleted: id };
111
+ }),
112
+ ];
113
+
114
+ export const assistant = createServerFn({ method: "POST" })
115
+ .validator(z.custom<RunAgentInput>())
116
+ .middleware([authMiddleware()])
117
+ .handler(async ({ data }) => {
118
+ const { messages, threadId, runId, parentRunId, resume, tools, aguiContext } =
119
+ await chatParamsFromRequestBody(data);
120
+ const abortController = new AbortController();
121
+ const stream = chat({
122
+ adapter: await chatAdapter("gpt-5.5"),
123
+ threadId,
124
+ runId,
125
+ parentRunId,
126
+ resume,
127
+ systemPrompts: [
128
+ SYSTEM_PROMPT,
129
+ ...aguiContext.map(({ description, value }) => `${description}: ${value}`),
130
+ ],
131
+ messages,
132
+ tools: mergeAgentTools(orderTools(), tools),
133
+ lazyToolsConfig: { includeDescription: "first-sentence" },
134
+ agentLoopStrategy: maxIterations(20),
135
+ abortController,
136
+ });
137
+ return toServerSentEventsResponse(stream, { abortController });
138
+ });
139
+ ```
140
+
141
+ ```tsx
142
+ // src/components/Assistant.tsx
143
+ import { createLayoutChatHook } from "wcz-layout/hooks";
144
+ import { assistant } from "~/server/actions/assistant";
145
+
146
+ const { useLayoutChat, LayoutChat } = createLayoutChatHook(assistant);
147
+
148
+ export function Assistant() {
149
+ const chat = useLayoutChat({ threadId: "assistant" });
150
+
151
+ return <LayoutChat chat={chat} />;
152
+ }
153
+
154
+ // src/routes/__root.tsx
155
+ <LayoutProvider navigation={navigation} theme={theme} options={{ chat: <Assistant /> }}>
156
+ ```
@@ -1,136 +1,150 @@
1
1
  ---
2
2
  name: client-db
3
- description: "Use when reading or writing client data with TanStack DB: collections, live queries, route preloading, optimistic writes, eager/on-demand sync, or browser SQLite persistence."
3
+ description: "Use when routes or components read/write application-owned records with TanStack DB: collection descriptors, shared live query options, useLiveQuery/useLiveSuspenseQuery, loader preloading and SSR hydration, optimistic CRUD, joins, on-demand sync and paging, or data that is empty, fetched too broadly, stale or rolled back."
4
4
  metadata:
5
5
  type: convention
6
6
  library: wcz-layout
7
7
  ---
8
8
 
9
- > Mechanics (the live-query builder, `createOptimisticAction`, collection adapters,
10
- > browser persistence) are covered by TanStack's own skills. List the skills shipped by
11
- > `@tanstack/db` and `@tanstack/react-db` and load whichever cover the task at hand.
12
- > This skill adds the wcz-layout conventions on top, and overrides upstream where noted.
9
+ Query builder, operators, hooks and the transaction API: load `@tanstack/db#db-core` with its
10
+ `live-queries` and `mutations-optimistic` sub-skills, and `@tanstack/react-db#react-db`.
13
11
 
14
12
  ## Rules
15
13
 
16
- - One `DbClient` per request, built in `src/router.tsx` and put on the router context
17
- next to `queryClient`. Components reach it with `useDbClient()`, loaders with
18
- `context.dbClient`.
19
- - Declare collections as descriptors: `collectionOptions(id, (client) => ...)`. Take the
20
- query client from the factory with `client.requireDependency<QueryClient>("queryClient")`,
21
- never a module-scope one — it is built per request and a singleton leaks across SSR.
22
- - Export a `use<Table>Collection` hook next to each collection. It is the only way components
23
- get a live collection to write to.
24
- - Define every live query once in `src/db/queries/<table>.ts` as
25
- `{ query: (q: InitialQueryBuilder) => ... }`. Reuse that definition in loaders and
26
- components.
27
- - Preload in the route loader and return the promise:
28
- `loader: ({ context }) => context.dbClient.preloadLiveQuery(<x>QueryOptions)`.
29
- This transports the query result, so `useLiveQuery` has rows on the first render. Never
30
- fire it with `void`: the server then renders an empty table and the browser fetches
31
- again. Explicit collection preload transports source rows and is a no-op for on-demand
32
- collections.
33
- - A detail route awaits the preload, then throws `notFound()` when the row is missing,
34
- and shows a skeleton `pendingComponent` meanwhile (see the example).
35
- - `useLiveQuery` for list pages, `useLiveSuspenseQuery` for detail components under
36
- suspense. `.findOne()` still returns `T | undefined` after the loader's check, so keep
37
- an `if (!data) return null` guard.
38
- - Shape data in the query: filter, order, group and aggregate only the fields the
39
- consumer needs. Do not load broad results and transform them in component code.
40
- - Mutations go through `createOptimisticAction`: mirror the server write in `onMutate`,
41
- call the server function in `mutationFn`, then
42
- `await utils.refetch({ throwOnError: true })` on every collection that function writes.
43
- Await `transaction.isPersisted.promise` at the call site and surface failures with
44
- `alert()`.
45
- - `syncMode: "eager"` for top-level collections, `"on-demand"` for child data and anything expected past ~10k rows.
14
+ - `src/router.tsx` creates one `DbClient({ queryClient })` per request,
15
+ puts both on the router context and returns `routerWithDbClient(router, dbClient)`.
16
+ - A collection is a `collectionOptions` descriptor, never `createCollection` or a
17
+ module-scope `QueryClient`: both leak between SSR requests. `use<Entity>Collection`, next to
18
+ it, is how components get the collection to write to. `queryFn` calls the entity's select
19
+ server function with its Query `signal`, `schema` is its row schema. Include dynamic
20
+ collection scope in both `id` and `queryKey`; one client reuses the first descriptor per id.
21
+ - Each live query is defined once in `src/db/queries/<entity>.ts` and shared by loader and
22
+ component as the same config form, not just its `.query` callback. Business filters,
23
+ ordering, joins and aggregates belong there.
24
+ - Loaders preload and return the promise:
25
+ `loader: ({ context }) => context.dbClient.preloadLiveQuery(featuresQueryOptions)`, or
26
+ `Promise.all([...])` of every live query the page reads (a form's picker options too). SSR
27
+ then ships those queries' rows and the first render has data. Never `void` it (empty SSR),
28
+ never `collection.preload()` (a no-op on-demand), never `dbClient.collection()` in a loader
29
+ (it ships the collection's rows a second time).
30
+ - `setupRouterSsrQueryIntegration` also ships every query in the `QueryClient`: an eager
31
+ collection's whole table goes out even when the page preloads one row; on-demand collections
32
+ ship only the subsets they loaded. The browser still refetches after hydration.
33
+ - Lists read `useLiveQuery(options)` (`data`, `isLoading`). Detail and edit pages read
34
+ `useLiveSuspenseQuery(byIdOptions(id))` under the route's `pendingComponent`. `.findOne()`
35
+ still yields `T | undefined`: render `<RouterNotFound />` for a missing row, which also
36
+ covers one deleted while the page is open.
37
+ - Every write is a `createOptimisticAction`: `onMutate` mirrors the change on the collection;
38
+ `mutationFn` awaits the server function, then `utils.refetch({ throwOnError: true })` on
39
+ every collection it changed. The caller awaits `when("settled")` in `try`; `catch` alerts
40
+ `error.message` (the optimistic change has already rolled back).
41
+ - Serialize writes that can overlap on one collection (scanner input, repeated Enter): each
42
+ `utils.refetch` cancels the one in flight, and with three or more overlapping writes all but
43
+ the last two actions roll back with `CancelledError` although the server saved. Queue them
44
+ with `usePacedMutations` + `queueStrategy` or a promise chain.
45
+ - One query per parent, never `useLiveQuery` per row: `DbClient` queries don't pool, so 50 rows
46
+ make 50 queries and requests. Load children with `inArray(child.parentId, ids)` and split
47
+ them in the component.
48
+ - `groupBy` selects grouped columns, expressions over them (`coalesce(a, b)`) and aggregates.
49
+ A grouped row has no `id`; select one when `LayoutTable` shows it (table).
50
+
51
+ ## Sync mode
52
+
53
+ - **eager** (default): the collection loads whole. Small reference data/top-level tables;
54
+ ~10k rows is a sizing heuristic, not a safe payload or memory limit.
55
+ - **on-demand**: each live query loads only its subset, with `where`, `orderBy` and `limit`
56
+ eligible for server push-down, not a guarantee for every query plan. Bigger tables and child
57
+ rows read per parent. agnostic-query carries
58
+ the subset to Drizzle (`agnostic-query#adapters`; server function in server-functions). The
59
+ collection adds:
60
+
61
+ ```ts
62
+ // fromTanDb from agnostic-query/tanstack-db, BasicIndex from @tanstack/react-db
63
+ syncMode: "on-demand",
64
+ queryFn: ({ meta, signal }) =>
65
+ selectFeatures({ data: fromTanDb(meta?.loadSubsetOptions), signal }),
66
+ autoIndex: "eager",
67
+ defaultIndexType: BasicIndex,
68
+ defaultStringCollation: { stringSort: "lexical" },
69
+ ```
70
+
71
+ Without the index, an ordered `limit` query warns and can load the whole table; with the
72
+ default locale string sort, ordering by any text field (uuid ids included) does. Lexical
73
+ order matches Postgres for uuid, number and date columns; a text sort column needs
74
+ `COLLATE "C"` on the server.
75
+
76
+ - Joining two on-demand collections: `leftJoin` from the side the `where` narrows. `innerJoin`
77
+ loads the smaller side first and, on a tie (both still empty), the joined collection whole.
78
+ - Collections don't page on the server: page N's first request reads rows 0 to N × size (no
79
+ offset reaches `queryFn`), and nothing counts the server's rows for the pager. Tables over
80
+ more rows than the browser should hold page with TanStack Query (table).
46
81
 
47
82
  ## Examples
48
83
 
49
84
  ```ts
50
- // src/db/collections/<table>.ts
85
+ // src/db/collections/feature.ts
51
86
  import { queryCollectionOptions } from "@tanstack/query-db-collection";
52
87
  import { collectionOptions, useDbClient } from "@tanstack/react-db";
53
88
  import type { QueryClient } from "@tanstack/react-query";
54
- import { TodoSchema } from "~/lib/schemas/todo";
55
- import { selectTodos } from "~/server/actions/todo";
89
+ import { FeatureSchema } from "~/lib/schemas/feature";
90
+ import { selectFeatures } from "~/server/actions/feature";
56
91
 
57
- const TODOS_ID = "todos";
92
+ const FEATURES_ID = "features";
58
93
 
59
- export const todoCollection = collectionOptions(TODOS_ID, (client) =>
94
+ export const featureCollection = collectionOptions(FEATURES_ID, (client) =>
60
95
  queryCollectionOptions({
61
- id: TODOS_ID,
62
- queryKey: [TODOS_ID],
63
- queryFn: () => selectTodos(),
96
+ id: FEATURES_ID,
97
+ queryKey: [FEATURES_ID],
98
+ queryFn: ({ signal }) => selectFeatures({ signal }),
64
99
  getKey: ({ id }) => id,
65
- schema: TodoSchema,
100
+ schema: FeatureSchema,
66
101
  queryClient: client.requireDependency<QueryClient>("queryClient"),
67
- syncMode: "eager",
68
102
  }),
69
103
  );
70
104
 
71
- export const useTodoCollection = () => useDbClient().collection(todoCollection);
105
+ export const useFeatureCollection = () => useDbClient().collection(featureCollection);
72
106
  ```
73
107
 
74
108
  ```ts
75
- // src/db/queries/<table>.ts
109
+ // src/db/queries/feature.ts
76
110
  import type { InitialQueryBuilder } from "@tanstack/react-db";
77
111
  import { eq } from "@tanstack/react-db";
78
- import { todoCollection } from "../collections/todo";
112
+ import { featureCollection } from "../collections/feature";
79
113
 
80
- export const todosQueryOptions = {
114
+ // uuidv7 sorts client creation time, not database insertion order.
115
+ export const featuresQueryOptions = {
81
116
  query: (q: InitialQueryBuilder) =>
82
- q.from({ todo: todoCollection }).orderBy(({ todo }) => todo.id, "desc"),
117
+ q.from({ feature: featureCollection }).orderBy(({ feature }) => feature.id, "desc"),
83
118
  };
84
119
 
85
- export const todoByIdQueryOptions = (id: string) => ({
120
+ export const featureByIdQueryOptions = (id: string) => ({
86
121
  query: (q: InitialQueryBuilder) =>
87
122
  q
88
- .from({ todo: todoCollection })
89
- .where(({ todo }) => eq(todo.id, id))
123
+ .from({ feature: featureCollection })
124
+ .where(({ feature }) => eq(feature.id, id))
90
125
  .findOne(),
91
126
  });
92
127
  ```
93
128
 
94
129
  ```tsx
95
- // detail route: src/routes/todos/$id.tsx
96
- export const Route = createFileRoute("/todos/$id")({
97
- component: RouteComponent,
98
- pendingComponent: TodoSkeleton,
99
- beforeLoad: requireAuth("admin"),
100
- loader: async ({ context, params }) => {
101
- await context.dbClient.preloadLiveQuery(todoByIdQueryOptions(params.id));
102
- if (!context.dbClient.collection(todoCollection).has(params.id)) throw notFound();
130
+ // a write in a component. update: features.update(id, (draft) => Object.assign(draft, value));
131
+ // delete: ids.forEach((id) => features.delete(id)) with deleteFeatures({ data: ids })
132
+ const features = useFeatureCollection();
133
+
134
+ const handleOnSubmit = createOptimisticAction<Feature>({
135
+ onMutate: (value) => {
136
+ features.insert(value);
137
+ },
138
+ mutationFn: async (value) => {
139
+ await insertFeature({ data: value });
140
+ await features.utils.refetch({ throwOnError: true });
103
141
  },
104
142
  });
105
143
 
106
- function RouteComponent() {
107
- const { id } = Route.useParams();
108
- const { alert } = useDialogs();
109
- const navigate = useNavigate();
110
- const todos = useTodoCollection();
111
- const { data } = useLiveSuspenseQuery(todoByIdQueryOptions(id));
112
-
113
- const handleOnDelete = createOptimisticAction<string>({
114
- onMutate: (id) => {
115
- todos.delete(id);
116
- },
117
- mutationFn: async (id) => {
118
- await deleteTodos({ data: [id] });
119
- await todos.utils.refetch({ throwOnError: true });
120
- },
121
- });
122
-
123
- const handleDelete = async () => {
124
- try {
125
- const transaction = handleOnDelete(id);
126
- await transaction.isPersisted.promise;
127
- await navigate({ to: "/todos" });
128
- } catch (error) {
129
- if (error instanceof Error) await alert(error.message);
130
- }
131
- };
132
-
133
- if (!data) return null;
134
- // render data; call handleDelete from the delete button...
144
+ try {
145
+ await handleOnSubmit(value).when("settled");
146
+ await navigate({ to: "/features" });
147
+ } catch (error) {
148
+ if (error instanceof Error) await alert(error.message);
135
149
  }
136
150
  ```