Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .agents/skills/frontend-feature/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ Put the code of an area in `frontend/src/domain/<area>/`: the hooks and the keys
2. **The keys and the hooks.** Write `<area>.keys.ts` (server-state.md, "Key factory"). Give all the params of the list to the list key. When the area has a list and a picker, give each its own key under `lists()`, because one is a `useQuery` and one a `useInfiniteQuery` and they cannot share a cache entry. Write one hook for each call: the list with `keepPreviousData` and `parsePagination`, the detail as `queryOptions`, the picker search with `useInfiniteQuery`, and one mutation for each write. Make each mutation update the cache as the table below says. Done when `pnpm lint` passes. In the key factory, put each parameter in the key whole, such as `(params: ListParams) => [...lists(), params]`. The lint fails on each other form. In the hooks, the lint finds the common forms of a value that the query function reads and the key does not have. It does not find all of them: read "Check" in server-state.md for the forms that it does not find, and check those forms in your hooks by reading them.
3. **The list page.** Read `search` and `page` from the URL with `validateSearch`. Build the `page` schema from the generated query schema with `.catch(undefined)`, so that a bad URL falls back to the default (frontend.md, "Routes"). The contract has no `search`, so write its schema by hand, with the max length of the field that the search matches (`z.string().max(searchMaxLength).optional().catch(undefined)`). In the list hook, send the text as `filters: containsText<RoomDto>('name', params.search)`. `containsText` in `lib/querykit-text.ts` writes the filter `name @=* <text>` (contains, ignore case), and puts text with a `"` in a padded raw string. Do not write a second encoder. Search for a text with a `"` on the stack in step 9. Show each state with an early return: loading (`role="status"`), error (`QueryError`), empty on a page after page 1 (a link to page 1), empty for a search (the search in quotes), and empty (how to add one, if the area has a create page). Use `SearchBox` for the search, and take its `maxLength` from the contract. The limit of `filters` is for the whole filter text, not for the text that the user types, so take the `maxLength` of the box from the field that the filter matches, such as `maxLengthOf(roomForCreationDtoSchema.shape.name)`. In its `onSearch`, navigate with `replace: true`, and change the URL only when it still has the search that the box started from (`base`), as the list pattern below does. Give the table `aria-label`, and give `whitespace-nowrap` to each cell that is not prose (code-style.md, "Styles"). On a phone (`useIsMobile`), drop the columns that do not wrap, and show their values under the name. A list of tenant data waits for `useMembership`: it gives `enabled: false` to the list query while the status is `loading` or `no-tenant`, and it shows a link to `/start-tenant` when the user has no tenant. Done when the page in the URL survives a reload, and Back from a detail page shows the list with its search in the box. The search uses `replace: true`, so Back does not step through the typed searches.
4. **The detail page.** Return early for loading and error. Show the title in `PageHeading`. Show a button only for each entry of `allowedActions` (server-state.md, rule 8). An action that needs input, such as a role, asks for it in a form in the dialog. Give each option of that form its label in a `Record` too (messages.md). Give each action its label in a `Record` of the generated union, so that a new action on the Server fails the build until it has a label. Ask for a confirm in a `ResponsiveDialog` before an action that cannot be undone. Close the dialog when the user confirms: make the confirm button a `ResponsiveDialogClose` that calls the action. A dialog that is still open keeps the focus inside it, and it gives the focus back to its trigger when it closes, so a focus move while it is open has no effect. Read the JSDoc of `components/ui/responsive-dialog.tsx` for the gap under the header. After an action, move the focus to the heading. For a delete, ask first, then call `leaveDeletedRecord` in the `onSuccess` of `mutate`, as the detail pattern below does: show the toast with `Notification.success`, go to the list, and let the root layout move the focus to the heading of the list. After a failed delete, the user stays on the page, and the focus goes to the heading. Do not remove the detail in the mutation hook, because the page that is still on the screen reads it again and gets a 404. Done when a user with no permission sees no button, and, for a delete, a functional test sees one toast (count it one time, as testing.md, "Facts about this app", says), one `GET` of the record, and the focus on the heading of the list.
5. **The edit form.** The page renders the form only after the detail query has data, and only when `allowedActions` has `Update`. Otherwise it says why. The form schema takes each limit from the generated Zod schema of the request DTO (frontend.md, "Forms"). Put the `version` in `defaultValues` and in the PUT body (server-state.md, "Forms with server data"). Use `shouldFocusError: false` with `focusFirstError`. Before a save, clear the refusals. After a refusal, show it with `useServerErrors`. The mutation hook of the form sends `options: { suppressErrorToast: true }` to the generated client, because `apiClient` shows each refusal in a toast, and the form already shows it (server-state.md, "Errors"). For a stale save (a 409 with the stale-version type), keep the edits in the form, and show `StaleVersionAlert` with the name of the record. Its button calls `load` of `useLoadLatest` with a function that refetches the detail query and gives the form values of the new record. Each field that the new record changed takes the saved value, each other field keeps the edit of the user, and the focus goes to the first changed field. `LatestLoadedNote` names the fields that changed. Clear the refusals after the load, and clear the note before a save. A failed read changes no field, and `load` returns false, so the page gives the form the error of the detail query (`isRefetchError ? error : null`). The form shows it in `StaleVersionAlert` (`loadFailure`) while that alert is open, and otherwise in a `QueryError` "The latest room did not load." above the fields, whose Try again calls the same `load`. The refetch of the page on open can fail too, and this alert is its way out. Do not send the PUT again with the new version. After a save, show a toast with `Notification.success` and go to the detail page. Done when the component test of the stale save passes, and a functional test of a refused save sees the refusal on its field and no toast.
5. **The edit form.** The page renders the form only after the detail query has data, and only when `allowedActions` has `Update`. Otherwise it says why. The form schema takes each limit from the generated Zod schema of the request DTO (frontend.md, "Forms"). Put the `version` in `defaultValues` and in the PUT body (server-state.md, "Forms with server data"). Use `shouldFocusError: false` with `focusFirstError`. Before a save, clear the refusals. After a refusal, show it with `useServerErrors`. The mutation hook of the form sends `options: { suppressErrorToast: true }` to the generated client, because `apiClient` shows each refusal in a toast, and the form already shows it (server-state.md, "Errors"). For a stale save (a 409 with the stale-version type), keep the edits in the form, and show `StaleVersionAlert` with the name of the record. Its button calls `load` of `useLoadLatest` with a function that refetches the detail query and gives the form values of the new record. Each field that the new record changed takes the saved value, each other field keeps the edit of the user, and the focus goes to the first changed field. `LatestLoadedNote` names the fields that changed. Clear the refusals after the load, and clear the note before a save. A failed read changes no field, and `load` returns false, so the page gives the form the error of the detail query (`isRefetchError ? error : null`). The form shows it in `StaleVersionAlert` (`loadError`) while that alert is open, and otherwise in a `QueryError` "The latest room did not load." above the fields, whose Try again calls the same `load`. The refetch of the page on open can fail too, and this alert is its way out. Do not send the PUT again with the new version. After a save, show a toast with `Notification.success` and go to the detail page. Done when the component test of the stale save passes, and a functional test of a refused save sees the refusal on its field and no toast.
6. **The create form.** Do step 5 with no `version` and no stale reload. Put the form in `RequireTenant` from `domain/membership/components/require-tenant.tsx`, so that a user with no tenant gets the way to start one, not a form that the Server refuses. Put each hook that loads tenant data in a component inside `RequireTenant`. Its mutation hook also sends `suppressErrorToast`. If the entity has a `ForStaleVersion` index, show the create race in its own alert, because the text of `StaleVersionAlert` says that the record changed. A create that gets a 409 keeps the input of the user. After a save, go to the detail page of the new record.
7. **The search picker.** Build it on `Combobox` with the `items` prop, so that React Aria does not filter again what the Server filtered. Load the picked record by its ID with the detail hook. Put the pick first in the options when no loaded page has it. Send the search with `containsText`, as the list does (step 3), and take the `maxLength` of the input from the field that the search matches. The text of the input after a pick is the name of the pick, so it is not a search. On a pick, put the record in the detail cache. Take the pick from the detail query also when a loaded page has it, so that a rename shows. In the `select` of the search hook, join the pages with `uniqueById`. A row that the Server adds between two page loads puts the same row on two pages, and a repeated key freezes the page in a production build. Load the next page with `ComboboxLoadMore`. Give it `isLoading` from `isFetchingNextPage`, `isFailed` from `isFetchNextPageError`, `failedText` that says what did not load, and `onLoadMore` with a plain `fetchNextPage()`. While `isLoading` is true, it does not call `onLoadMore`, so a slow answer gets one request. Do not give `fetchNextPage` the option `cancelRefetch: false`: when the list opens while page 1 loads again, the call does nothing and the next page does not load. After a next page fails, `ComboboxLoadMore` asks for nothing until the user picks its `Try again` option. The list shows this failure, so give the search the option `suppressErrorToast` for a page after the first that the query does not have yet. A page that the query already has fails only when the list loads again. The list has no message for that failure, so it keeps its toast. When the search fails, the empty state says so and what to do (messages.md, rules 3 and 7), not that no record matches, and the list searches again when it opens again. Do not search again on an open when only a next page failed (`isError && !isFetchNextPageError`), because that starts the load again with no request from the user. In a form, wrap the picker in a `Controller`, and give `field.ref` to the input. Done when component tests show that a pick from page 2 and a pick from a link show their names, that a rename of a pick from a link and of a pick from page 1 shows after the detail query reads the record again, and that a failed search shows its message and searches again on the next open, that a slow next page gets one request, that a next page that repeats a row shows that row one time and still loads the page after it, and that a failed next page gets one request, shows its message with no toast, sends no request on a close and an open, and loads when the user asks, and that a later page that fails when the list loads again shows a toast.
8. **The tests.** Use the `writing-tests` skill. Write a test for each limit of a form schema, in the component test of the form or in a unit test of the schema. Put a schema that a test imports in its own `*-schema.ts` file, because `react-refresh/only-export-components` refuses it in a component file. Write component tests for each part that the area has: the stale save of the edit form, the picker (step 7), and the search and the page of the list in the URL. Write a builder in `tests/support/builders/` and an API file in `tests/support/api/` for the area, or add to the ones that exist, then a functional spec that goes from the list to the detail and to each form of the area. Read back the list query and the PUT body with `api.last`. Done when `pnpm lint`, `pnpm test`, `pnpm build`, and `pnpm test:e2e` pass, and the new spec passes 10 times (`pnpm test:e2e <spec> --repeat-each=10`).
Expand Down Expand Up @@ -168,7 +168,7 @@ const handleLoadLatest = async () => {
}

// First in the form. refetchError is `room.isRefetchError ? room.error : null` from the page:
{refetchError && serverErrors.problem?.kind !== 'stale' && !form.formState.isSubmitting && (
{refetchError !== null && serverErrors.problem?.kind !== 'stale' && !form.formState.isSubmitting && (
<QueryError title="The latest room did not load." error={refetchError} isRetrying={latest.isLoading} onRetry={handleLoadLatest} />
)}

Expand All @@ -177,7 +177,7 @@ const handleLoadLatest = async () => {
noun="room"
problem={serverErrors.problem}
isLoadingLatest={latest.isLoading}
loadFailure={refetchError?.message ?? null}
loadError={refetchError}
onLoadLatest={handleLoadLatest}
/>
<LatestLoadedNote noun="room" changed={latest.changed} labels={FIELD_LABELS} />
Expand Down
6 changes: 3 additions & 3 deletions docs/frontend.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ frontend/src/
│ └── theme-toggle.tsx # Light, dark, and system toggle
├── routes/ # TanStack Router file routes
├── hooks/ # Shared React hooks
├── lib/ # api-client.ts, pagination.ts, problem-details.ts, utils.ts
├── lib/ # api-client.ts, pagination.ts, problem-details.ts, request-failure.ts, utils.ts
└── main.tsx # App entry point
```

Expand All @@ -65,7 +65,7 @@ Wrap the `cva` call of a `*-variants.ts` file in `withMergedClasses` from `@/lib
- `withCredentials: true` sends the BFF cookie.
- The `X-CSRF: 1` header is necessary for the BFF CSRF protection.
- An error response that has problem details becomes a `ProblemDetailsError`. The client shows it as a toast by default. To stop the toast, send `{ suppressErrorToast: true }` with the request.
- The `message` of each error that the client throws is the text for the user, so a toast, a form, and a page show the same text. A refusal (a 4xx problem) gives the `detail` of the Server, or its `title`. A 5xx, an answer with no problem details, a request that reaches its time limit, and a request with no answer give the text of the SPA in `lib/problem-details.ts`. See [In the SPA](messages.md#in-the-spa).
- `failureText(error)` of `lib/request-failure.ts` gives the text for the user of each error that the client throws, so a toast, a form, and a page show the same text. A refusal (a 4xx problem) gives the `detail` of the Server, or its `title`. A 5xx, an answer with no problem details, a request that reaches its time limit, and a request with no answer give the text of the SPA. The `message` of the error is for a developer. See [In the SPA](messages.md#in-the-spa).

The generated API clients send each request through `apiClient`. `main.tsx` imports `lib/api-client.ts` to connect them before the first request. Use `apiClient` directly only for endpoints that are not in the OpenAPI document, such as `/bff/user`.

Expand Down Expand Up @@ -181,7 +181,7 @@ The app does not poll the session. It finds an ended BFF session, for example af
| The check gives | `apiClient` |
|---|---|
| `null` | Shows no toast. The root route goes to the login. |
| Claims | Shows "The Server did not accept your sign-in for this request." unless the call sets `suppressErrorToast`. The page stays. |
| Claims | Shows "The server did not accept your sign-in for this request." unless the call sets `suppressErrorToast`. The page stays. |
| An error | Shows the same toast as for claims. The root route keeps the last answer. |

A 401 of `/bff/user` is a failed check. It does not start a check again.
Expand Down
Loading
Loading