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
2 changes: 1 addition & 1 deletion .agents/skills/frontend-feature/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ Put the code of an area in `frontend/src/domain/<area>/`: the hooks and the keys

1. **The contract.** The Server endpoints exist, and the generated client is current. Use the `backend-feature` skill for the Server and the `api-contract` skill for the client. The list endpoint takes a page number, a page size, and a search or a filter. The DTO has `allowedActions` and `version`. Each text field and number field of a request DTO has a limit in the contract, and so does the `search` query parameter (`[MaxLength]` on the handler parameter, frontend.md). Done when `src/api/generated/<tag>/clients/` has a client for each call, and `maxLengthOf` and `maximumOf` do not throw for the fields of the form.
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 schema from the generated query schemas with `.catch(undefined)`, so that a bad URL falls back to the default (frontend.md, "Routes"). If the list takes QueryKit `filters` and no `search`, write the `search` schema by hand (`z.string().optional().catch(undefined)`), and turn the text into a filter in a pure function with a unit test. Use the operator `@=*` (contains, ignore case). QueryKit has no escape in a quoted value: put text with a `"` in a raw string (`"""text"""`). Give the unit test a text with a `"`, and search for such a text 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.
3. **The list page.** Read `search` and `page` from the URL with `validateSearch`. Build the schema from the generated query schemas with `.catch(undefined)`, so that a bad URL falls back to the default (frontend.md, "Routes"). If the list takes QueryKit `filters` and no `search`, write the `search` schema by hand (`z.string().optional().catch(undefined)`), and turn the text into a filter in a pure function with a unit test. Use the operator `@=*` (contains, ignore case). QueryKit has no escape in a quoted value: put text with a `"` in a raw string with one space of padding on each side (`""" text """`). Make the delimiter one quote longer than the longest run of quotes in the text, and at least three quotes long. Give the unit test a text with a `"`, and search for such a text 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. 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. 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.
Expand Down
2 changes: 1 addition & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
<!-- Reverse proxy -->
<PackageVersion Include="Yarp.ReverseProxy" Version="2.3.0" />
<!-- Dependency Injection -->
<PackageVersion Include="QueryKit" Version="1.17.0" />
<PackageVersion Include="QueryKit" Version="1.17.1" />
<PackageVersion Include="Scrutor" Version="7.0.0" />
<PackageVersion Include="MediatR" Version="12.5.0" />
<PackageVersion Include="Riok.Mapperly" Version="4.3.1" />
Expand Down
2 changes: 1 addition & 1 deletion docs/frontend.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ const filterConfig = [
/>
```

The control types are text, number, date, boolean, and multiselect. Groups can use AND or OR. QueryKit cannot hold a text value that starts or ends with a quote, so the text control refuses it. The multiselect control refuses an option with a quote at an end. If a preset or an initial state has such a value, `toQueryKitString` leaves out its filter, and the badge tells the user that the filter is not used. For a date of a place, give the config the `timeZone` of the place. See "Dates and times" in [code-style.md](frontend/code-style.md).
The control types are text, number, date, boolean, and multiselect. Groups can use AND or OR. For a date of a place, give the config the `timeZone` of the place. See "Dates and times" in [code-style.md](frontend/code-style.md).

<!-- example:start -->
"Starts At in Pago Pago" in `routes/(examples)/filter-demo.tsx` gives the `timeZone` of a place.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,51 +21,16 @@ async function choose(label: string): Promise<void> {
await page.getByText(label, { exact: true }).click()
}

test('refuses an option that starts or ends with a quote and names it', async () => {
test('adds options that start or end with a quote', async () => {
// Arrange
const onSubmit = vi.fn()
await render(<MultiSelectFilter config={names} surface="dialog" onSubmit={onSubmit} />)
const quotedPaul = page.getByRole('checkbox', { name: 'Quoted Paul' })

// Act
await choose('Quoted Paul')
await choose('Paul')

// Assert
const message = 'A filter value cannot start or end with a quote. Clear the option Quoted Paul.'
await expect.element(page.getByRole('alert')).toHaveTextContent(message)
await expect.element(quotedPaul).toHaveAccessibleDescription(message)
await expect.element(page.getByRole('checkbox', { name: 'Paul', exact: true })).not.toHaveAccessibleDescription(message)
await expect.element(page.getByRole('button', { name: 'Add (2)' })).toBeDisabled()
expect(onSubmit).not.toHaveBeenCalled()
})

test('names each option with a quote at an end', async () => {
// Arrange
await render(<MultiSelectFilter config={names} surface="dialog" onSubmit={() => {}} />)

// Act
await choose('Quoted Paul')
await choose('Ann with a quote')
await page.getByRole('button', { name: 'Add (2)' }).click()

// Assert
await expect
.element(page.getByRole('alert'))
.toHaveTextContent('A filter value cannot start or end with a quote. Clear the options Quoted Paul, Ann with a quote.')
})

test('adds the filter when the user clears the option with the quote', async () => {
// Arrange
const onSubmit = vi.fn()
await render(<MultiSelectFilter config={names} surface="dialog" onSubmit={onSubmit} />)
await choose('Quoted Paul')
await choose('Paul')

// Act
await choose('Quoted Paul')
await page.getByRole('button', { name: 'Add (1)' }).click()

// Assert
await expect.element(page.getByRole('alert')).not.toBeInTheDocument()
expect(onSubmit.mock.lastCall?.[0].value).toEqual(['Paul'])
expect(onSubmit.mock.lastCall?.[0].value).toEqual(['"Paul"', 'Ann"'])
})
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { useId, useState, useMemo } from 'react'
import { useState, useMemo } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Checkbox } from '@/components/ui/checkbox'
import type { OperatorType, Filter, FilterControlProps, FilterOption } from '../types'
import { getDefaultOperator, Operators, pickOperator } from '../utils/operators'
import { hasEndQuote, optionsEndQuoteMessage } from '../utils/querykit-text'
import { FilterControlFooter } from './filter-control-footer'
import { OperatorSelect } from './operator-select'

Expand Down Expand Up @@ -49,9 +48,7 @@ export function MultiSelectFilter({
const allRootSelected = rootOptions.length > 0 && rootOptions.every(opt => selected.includes(opt.value))

const labelOf = (value: string) => options.find((opt) => opt.value === value)?.label ?? value
const endQuoteValues = selected.filter(hasEndQuote)
const canSubmit = selected.length > 0 && endQuoteValues.length === 0
const errorId = useId()
const canSubmit = selected.length > 0

const toggleOption = (value: string) => {
setSelected((prev) =>
Expand Down Expand Up @@ -142,8 +139,6 @@ export function MultiSelectFilter({
>
<Checkbox
isSelected={selected.includes(option.value)}
isInvalid={endQuoteValues.includes(option.value)}
aria-describedby={endQuoteValues.includes(option.value) ? errorId : undefined}
onChange={() => toggleOption(option.value)}
className="flex-1"
>
Expand All @@ -163,12 +158,6 @@ export function MultiSelectFilter({
))
)}
</div>

{endQuoteValues.length > 0 && (
<p id={errorId} role="alert" className="text-destructive text-sm">
{optionsEndQuoteMessage(endQuoteValues.map(labelOf))}
</p>
)}
</div>

<FilterControlFooter surface={surface}>
Expand Down
Loading
Loading