@gopherium/godmin 0.25.0 → 0.27.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 (40) hide show
  1. package/README.md +9 -15
  2. package/dist/base.css +3 -2
  3. package/dist/close-while-open.d.ts +6 -0
  4. package/dist/close-while-open.js +21 -0
  5. package/dist/drilldown-item.d.ts +5 -3
  6. package/dist/drilldown-item.js +6 -6
  7. package/dist/focus-back.d.ts +25 -0
  8. package/dist/focus-back.js +125 -0
  9. package/dist/index.d.ts +9 -1
  10. package/dist/index.js +5 -1
  11. package/dist/list-run.d.ts +7 -2
  12. package/dist/list-run.js +64 -2
  13. package/dist/list-view.d.ts +1 -7
  14. package/dist/list-view.js +1 -16
  15. package/dist/menu-item.d.ts +7 -0
  16. package/dist/navigation-item.d.ts +8 -0
  17. package/dist/navigation-item.js +9 -1
  18. package/dist/navigation-list.js +12 -2
  19. package/dist/open-on-tap.d.ts +14 -0
  20. package/dist/open-on-tap.js +17 -0
  21. package/dist/run-confirm.d.ts +1 -1
  22. package/dist/run-confirm.js +4 -2
  23. package/dist/unsaved-text.d.ts +14 -0
  24. package/dist/unsaved-text.js +25 -0
  25. package/docs/build-and-versioning.md +190 -0
  26. package/docs/design-system/accessibility.md +206 -0
  27. package/docs/design-system/color.md +74 -0
  28. package/docs/design-system/custom-properties.md +63 -0
  29. package/docs/design-system/layout.md +157 -0
  30. package/docs/design-system/motion.md +116 -0
  31. package/docs/design-system/overview.md +101 -0
  32. package/docs/design-system/radius-and-elevation.md +129 -0
  33. package/docs/design-system/typography.md +83 -0
  34. package/docs/framing-an-application.md +386 -0
  35. package/docs/lists.md +1511 -0
  36. package/docs/loading-and-feedback.md +207 -0
  37. package/docs/overview.md +159 -0
  38. package/docs/screens.md +419 -0
  39. package/docs/testing.md +193 -0
  40. package/package.json +6 -1
package/docs/lists.md ADDED
@@ -0,0 +1,1511 @@
1
+ ---
2
+ title: Lists with DataViews
3
+ description: Hosting a WordPress DataViews list in a godmin page, its view in the address, paging it on the server, empty states, runs over the picked rows, confirmations, confirms outside a list, renames, forms in a dialog, the focus back on a row, bulk messages, uploads, its Spanish chrome, its dates, and the table look for lists that stay custom.
4
+ ---
5
+
6
+ DataViews is the WordPress list component. It draws the search box,
7
+ the filters, the sort menus, the paging and the row actions you know
8
+ from the Posts screen. godmin never imports it. Your application
9
+ installs `@wordpress/dataviews` and loads its stylesheet, and godmin
10
+ makes the list sit well inside a page.
11
+
12
+ ## A list page
13
+
14
+ Give `Page` the `list` flag when its content is a list:
15
+
16
+ ```tsx
17
+ import { Page } from '@gopherium/godmin'
18
+ import { DataViews, filterSortAndPaginate } from '@wordpress/dataviews'
19
+ import type { View } from '@wordpress/dataviews'
20
+ import { useState } from 'react'
21
+
22
+ export function UsersScreen({ users }: { users: User[] }) {
23
+ const [view, setView] = useState<View>({ type: 'table', titleField: 'name', fields: ['email'] })
24
+ const { data, paginationInfo } = filterSortAndPaginate(users, view, fields)
25
+ return (
26
+ <Page title="Users" list>
27
+ <DataViews
28
+ data={data}
29
+ fields={fields}
30
+ view={view}
31
+ onChangeView={setView}
32
+ paginationInfo={paginationInfo}
33
+ defaultLayouts={{ table: {} }}
34
+ />
35
+ </Page>
36
+ )
37
+ }
38
+ ```
39
+
40
+ `fields` describes your columns, as the DataViews documentation
41
+ shows. DataViews needs `paginationInfo`, the item and page totals
42
+ its paging reads. For a list you hold whole, `filterSortAndPaginate`
43
+ searches, sorts and pages it, and answers the page of rows with those
44
+ totals. `defaultLayouts` names the layouts a reader may switch to.
45
+
46
+ DataViews pads its toolbar, its table and its footer by 24px on each
47
+ side. The canvas pads its content by 24px as well. Without help the
48
+ list starts 48px in, while the title starts at 24px. `list` takes the
49
+ content out to the canvas edges, so the list's own 24px lines up with
50
+ the title and its row lines run from edge to edge, as they do in
51
+ WordPress.
52
+
53
+ Below 640px the canvas pads by 16px and the list reaches out by 16px.
54
+ DataViews keeps its own 24px there, so on a phone a list page pads its
55
+ title row by the 8px between the two, and the title still lines up
56
+ with the list.
57
+
58
+ A page with an `aside` keeps its list inside the main column, because
59
+ the aside needs its own room.
60
+
61
+ The canvas names its side padding `--godmin-canvas-gutter` and its
62
+ top and bottom padding `--godmin-canvas-gutter-block`. Read them for
63
+ anything else that has to line up with the canvas edge.
64
+ [The canvas](./design-system/layout.md#the-canvas) gives their
65
+ values.
66
+
67
+ ## The view in the address
68
+
69
+ `useListView` keeps the search, the filters, the sort and the page of
70
+ a list in the address. A reader who reloads or shares the page gets
71
+ the same rows. It comes from `@gopherium/godmin/router` and needs
72
+ TanStack Router:
73
+
74
+ ```tsx
75
+ import { listSearch, useListView } from '@gopherium/godmin/router'
76
+
77
+ const usersRoute = createRoute({
78
+ getParentRoute: () => rootRoute,
79
+ path: '/users',
80
+ validateSearch: listSearch,
81
+ component: UsersScreen,
82
+ })
83
+
84
+ function UsersScreen() {
85
+ const list = useListView<View>({
86
+ fields: ['email', 'role'],
87
+ titleField: 'name',
88
+ sort: { field: 'name', direction: 'asc' },
89
+ perPage: 20,
90
+ })
91
+ const { data, paginationInfo } = filterSortAndPaginate(users, list.view, fields)
92
+ return (
93
+ <Page title="Users" list>
94
+ <DataViews
95
+ data={data}
96
+ fields={fields}
97
+ paginationInfo={paginationInfo}
98
+ view={list.view}
99
+ onChangeView={list.onChangeView}
100
+ defaultLayouts={list.defaultLayouts}
101
+ selection={list.selection}
102
+ onChangeSelection={list.onChangeSelection}
103
+ />
104
+ </Page>
105
+ )
106
+ }
107
+ ```
108
+
109
+ `View` is the DataViews view type, so `list.view` and the controls
110
+ fit DataViews as they are. godmin itself never imports DataViews.
111
+
112
+ The object you pass is what the list opens on. The address holds
113
+ only what the reader changed, in the keys `search`, `page`,
114
+ `perPage`, `sort`, `order` and `filters`, so a fresh list has a bare
115
+ address. Other keys, such as a tab, stay as they are. A change
116
+ replaces the address instead of adding a history entry, so Back
117
+ leaves the list.
118
+
119
+ `listSearch` keeps those keys and drops anything malformed. When the
120
+ route holds a key of its own, add it:
121
+ `validateSearch: (raw) => ({ ...listSearch(raw), status: raw.status })`.
122
+
123
+ A list shows one layout at a time and no Layout menu: the table from
124
+ 640px and the list below. `layouts: { wide: 'grid', phone: 'list' }`
125
+ names others, and `layoutSettings` says what a layout opens on, such
126
+ as `{ grid: { layout: { previewSize: 230 } } }`. `phoneFields` names
127
+ the fields the phone list shows. The columns a reader picks stay in
128
+ memory while the list is open, one set for each layout. When the screen
129
+ moves to another list address, for example from one content type to
130
+ the next, the list forgets the picked columns and the ticked rows.
131
+
132
+ A tap on a phone list selects nothing. `openOnTap(list, open)` gives
133
+ you a handler that opens the record instead. Pass it as
134
+ `onChangeSelection`. `list.phone` tells you which side of 640px the
135
+ screen is on. `openOnTap` comes from `@gopherium/godmin/router`, like
136
+ `useListView`, and from the main entry too, so a package that draws a
137
+ list without TanStack Router can call it with the `list` an app hands
138
+ it. It reads only `phone` and `onChangeSelection`. The list view
139
+ types, such as `ListView` and `ListDefaults`, come from the main entry
140
+ too, so such a package can type that `list` and its defaults without
141
+ the router. This needs godmin 0.27.0 or later.
142
+
143
+ Leave `perPage` out while you do not know it yet, for example while
144
+ your settings load. The list then shows every row.
145
+
146
+ ## Keeping the view to what the list offers
147
+
148
+ An address can hold a sort or a filter the list never offers, from
149
+ an old link or one typed by hand. DataViews would show it, and your
150
+ server would get a request it cannot answer. `offeredView` keeps only
151
+ what the fields offer:
152
+
153
+ ```tsx
154
+ import { offeredView } from '@gopherium/godmin'
155
+
156
+ const view = offeredView(list.view, fields, {
157
+ opening: { field: 'date', direction: 'desc' },
158
+ checks: { author: namesAccounts },
159
+ })
160
+ ```
161
+
162
+ Hand `view` to DataViews and to your request in place of `list.view`.
163
+
164
+ A sort stays when a field with that id sorts. Any other sort, or
165
+ none, falls back to `opening`, the order the list opens in. As in
166
+ DataViews, a field sorts unless it says `enableSorting: false`, and a
167
+ field of type `media` or `password` sorts only when it says
168
+ `enableSorting: true`.
169
+
170
+ A filter stays when DataViews offers it. `offeredView` reads the
171
+ field as DataViews 20 does:
172
+
173
+ - The field does not say `filterBy: false`.
174
+ - The operator is one the field names in `filterBy.operators` and its
175
+ type takes, or one of its type's defaults when it names none. A
176
+ `text` field with no `filterBy` offers `isAny` and `isNone`, and a
177
+ field with no type offers `is` and `isNot`.
178
+ - The field can draw the filter: it has `elements` or `getElements`,
179
+ its type draws a control, or its own `Edit` gives one. A field of
180
+ type `media` or `password` offers no filter, and neither does a
181
+ field with no type, no elements and no `Edit`.
182
+
183
+ A filter still waiting for its value stays too. Otherwise its value
184
+ has to fit the field:
185
+
186
+ - For a field with `elements` or `getElements`, the value has the
187
+ shape DataViews writes. When any operator of the field picks one
188
+ value, such as `is`, every filter on it holds one value, `isAny`
189
+ included. Otherwise it holds a list. A value of the other shape
190
+ goes away.
191
+ - For a field with `elements` and no `getElements`, each value must
192
+ be one of them. An empty `elements` list counts as none.
193
+ - For any other field, `checks` can name a function that takes or
194
+ refuses the value, such as one that wants account ids. A field with
195
+ `getElements` is one of them, since DataViews shows the values it
196
+ loads in place of `elements`.
197
+ - Such a field with no check takes any value. Name a check for any
198
+ value your server has to read, such as a date.
199
+
200
+ Everything else in the view, such as the search, the page and the
201
+ columns, comes back as it was. `filters` always comes back as a list,
202
+ empty when nothing stayed.
203
+
204
+ ## The list fills the page
205
+
206
+ A list page fills the canvas from the title down to the bottom edge.
207
+ The DataViews footer, with the item count and the select all box,
208
+ rests on the bottom edge of the canvas, the way the list already
209
+ reaches the side edges. With a few rows, the rows sit at the top,
210
+ the empty space sits under them, and no line closes the last row.
211
+ The next line is the footer's own, at the bottom.
212
+
213
+ When the list is longer than the screen, only the rows scroll. The
214
+ title, the tabs, the search box and the column headers stay where
215
+ they are, and the footer stays on the bottom edge. A toast floats
216
+ over the footer, as it does in WordPress.
217
+
218
+ A list that is not DataViews, such as a `godmin-table`, grows the
219
+ page instead, and the canvas scrolls as it does for any other page.
220
+
221
+ ## Tabs above a list
222
+
223
+ Give the page `tabs` to show [page tabs](./screens.md#pagetabs)
224
+ between the title and the list. On a list page the tab labels line up
225
+ with the title, the light line under them runs from edge to edge, and
226
+ the search box sits 16px under that line, as on a WordPress list. A
227
+ notice or a `godmin-table` right under the tabs keeps the same 16px
228
+ from that line.
229
+
230
+ ## Notices above a list
231
+
232
+ Anything you put in a list page before the list itself, such as an
233
+ `ErrorNotice` for a list that failed to load, lines up with the title
234
+ rather than the canvas edge, and keeps 16px between itself and the
235
+ list:
236
+
237
+ ```tsx
238
+ <Page title="Users" list>
239
+ {loadFailure === undefined ? null : <ErrorNotice>{loadFailure}</ErrorNotice>}
240
+ <DataViews {...props} />
241
+ </Page>
242
+ ```
243
+
244
+ A write that fails from a row action goes in a toast instead, as
245
+ [what goes in a toast](./loading-and-feedback.md#what-goes-in-a-toast)
246
+ explains.
247
+
248
+ ## A drop zone over a list
249
+
250
+ Give an element the `godmin-list-overlay` class and put it after the
251
+ list. It then covers the whole list region, toolbar and footer
252
+ included, without the margin a notice takes. A WordPress `DropZone`
253
+ is the usual one:
254
+
255
+ ```tsx
256
+ <Page title="Media" list>
257
+ <DataViews {...props} />
258
+ <DropZone className="godmin-list-overlay" label="Drop files to upload" onFilesDrop={upload} />
259
+ </Page>
260
+ ```
261
+
262
+ The list stays the first child of its region, so its footer stays on
263
+ the canvas bottom. The class works the same in the main column of a
264
+ page with an `aside`, and inside a `godmin-list`.
265
+
266
+ ## Empty lists
267
+
268
+ `ListEmpty` is what a list shows when it has no rows. Pass it to
269
+ DataViews as `empty`:
270
+
271
+ ```tsx
272
+ import { ListEmpty } from '@gopherium/godmin'
273
+ import { people } from '@wordpress/icons'
274
+
275
+ <DataViews
276
+ {...props}
277
+ empty={<ListEmpty icon={people} title="No users yet." hint="Add one with New user." />}
278
+ />
279
+ ```
280
+
281
+ It draws the design system empty state, centred: the icon, the title
282
+ as a heading and the hint under it. `hint` is optional. Leave it out
283
+ when a search narrowed the list, as in `No users found.`
284
+
285
+ `viewNarrows(view)` tells you whether a search, or a filter holding a
286
+ value, narrows the list. Use it to pick between the two messages:
287
+
288
+ ```tsx
289
+ import { ListEmpty, viewNarrows } from '@gopherium/godmin'
290
+
291
+ const empty = viewNarrows(view) ? (
292
+ <ListEmpty icon={people} title="No users found." />
293
+ ) : (
294
+ <ListEmpty icon={people} title="No users yet." hint="Add one with New user." />
295
+ )
296
+ ```
297
+
298
+ A filter with an empty pick, or one still waiting for its value,
299
+ narrows nothing.
300
+
301
+ ## Paging on the server
302
+
303
+ `filterSortAndPaginate` needs every row in the browser. A long list
304
+ asks the server for one page at a time instead. The server needs two
305
+ numbers: the limit, how many rows to send, and the offset, how many
306
+ rows to skip first. `useServerPaging` works both out from the view:
307
+
308
+ ```tsx
309
+ import { Page, paginationOf, useServerPaging } from '@gopherium/godmin'
310
+
311
+ export function OrdersScreen() {
312
+ const [view, setView] = useState<View>({ type: 'table', page: 1, perPage: 20, fields: ['total'] })
313
+ const paging = useServerPaging(view, 100)
314
+ const { page, asked } = useOrderPage(paging.window)
315
+ paging.record(page, asked)
316
+ return (
317
+ <Page title="Orders" list>
318
+ <DataViews
319
+ data={page?.items ?? []}
320
+ paginationInfo={paginationOf(page)}
321
+ fields={fields}
322
+ view={view}
323
+ onChangeView={setView}
324
+ defaultLayouts={{ table: {} }}
325
+ />
326
+ </Page>
327
+ )
328
+ }
329
+ ```
330
+
331
+ `useOrderPage` stands for your own request. On page 3 with 20 rows a
332
+ page, `paging.window` is `{ limit: 20, offset: 40 }`. The second
333
+ argument is the largest page your server sends. A bigger page size
334
+ is held under it. Leave it out when your server has no such limit.
335
+
336
+ The server answers with the rows, `total`, how many rows match in
337
+ all, and `limit`, the page size it used. Hand that page to
338
+ `paging.record` and to `paginationOf`, or `undefined` while it has
339
+ not arrived. `paginationOf` turns it into the totals DataViews shows.
340
+
341
+ `useOrderPage` also gives back `asked`, the limit of the request that
342
+ got this page. With urql, that is `result.operation?.variables.limit`.
343
+ Call `paging.record(page, asked)` in the same component, right after
344
+ your request, as the example does.
345
+
346
+ `paging.record` remembers the page size the server used for that
347
+ request. When the server used another size than you asked for, the
348
+ next pages step by the size it used, and no row goes missing or shows
349
+ twice. An answer to an older request, with another page size, never
350
+ changes the step. A view with no `perPage` asks with a `null` limit.
351
+ The server then picks the size, and the pages step by it once the
352
+ first one arrives.
353
+
354
+ `pageWindow(view, last, cap)` is the plain function behind the hook,
355
+ for code outside a component. `last` is the size the server last sent
356
+ together with the size it was asked for, or `undefined` before the
357
+ first page.
358
+
359
+ ### Page sizes from your settings
360
+
361
+ When your settings name the page sizes a reader may pick, an address
362
+ can still hold a size they do not offer. `offeredSize` keeps a size
363
+ the settings offer and falls back to the opening size for any other.
364
+ `sizedView` leaves the size out of the request while the settings are
365
+ on their way, so the server serves its own size:
366
+
367
+ ```tsx
368
+ import { offeredSize, sizedView, useServerPaging } from '@gopherium/godmin'
369
+
370
+ const sizes = settings.data?.pageSizes
371
+ const view = { ...list.view, perPage: offeredSize(list.view.perPage, sizes, settings.data?.pageSize) }
372
+ const paging = useServerPaging(sizedView(view, sizes), 100)
373
+ const { page, asked } = useOrderPage(paging.window, { pause: settings.isPending })
374
+ ```
375
+
376
+ While the sizes are unknown, `offeredSize` keeps the size the view
377
+ asks for. Hold the request back while the settings load, with your
378
+ query library's own flag, such as `pause` in urql or `enabled` in
379
+ TanStack Query. If the settings fail to load, the sizes stay unknown,
380
+ so the request goes without a size and the server serves its own.
381
+ godmin never picks a query library for you.
382
+
383
+ ## Bulk actions
384
+
385
+ A bulk action runs on every row the reader picked. `runEach` makes one
386
+ call per row, all at once, and counts how they went:
387
+
388
+ ```tsx
389
+ import { runEach, useToaster } from '@gopherium/godmin'
390
+ import type { Action } from '@wordpress/dataviews'
391
+
392
+ export function useArchiveAction(): Action<Order> {
393
+ const toaster = useToaster()
394
+ return {
395
+ id: 'archive',
396
+ label: 'Archive',
397
+ supportsBulk: true,
398
+ callback: async (orders) => {
399
+ const { asked, done, failures } = await runEach(orders, (order) => archiveOrder(order.id))
400
+ if (failures.length > 0) {
401
+ toaster.show(`Could not archive ${failures.length} of ${asked}.`)
402
+ } else {
403
+ toaster.show(`Archived ${done} of ${asked}.`)
404
+ }
405
+ },
406
+ }
407
+ }
408
+ ```
409
+
410
+ The action lives in a hook, because `useToaster` only works inside a
411
+ component.
412
+
413
+ `asked` is how many rows `runEach` got and `done` is how many calls
414
+ worked. `failures` holds each row that failed with its error, in the
415
+ order of the rows. A call fails when its promise rejects, when it
416
+ throws, or when it answers an object whose `error` holds an error. An
417
+ `error` of `null` or `undefined` counts as done. Many GraphQL clients
418
+ report an error that way, so a call can hand back the client's result
419
+ as it is. `runEach` itself never fails, so one bad row
420
+ never hides the others.
421
+
422
+ Show one toast. When a row failed, it says what failed, because that
423
+ is what the reader has to act on. Otherwise it says what worked. The
424
+ WordPress Trash action does the same, and
425
+ [what goes in a toast](./loading-and-feedback.md#what-goes-in-a-toast)
426
+ explains why a failure goes there.
427
+
428
+ ## Bulk messages
429
+
430
+ `bulkNotes` turns the outcome into those messages, in your own words:
431
+
432
+ ```tsx
433
+ const notes = bulkNotes(orders, outcome, {
434
+ done: (count, only) => (only === undefined ? `${count} orders archived.` : `"${only.title}" archived.`),
435
+ failed: (failures, asked) => `${failures.length} of ${asked} orders could not be archived.`,
436
+ })
437
+ const message = notes.notice ?? notes.toast
438
+ if (message !== undefined) {
439
+ toaster.show(message)
440
+ }
441
+ ```
442
+
443
+ Pass the rows you gave `runEach` and its outcome. `done` runs when at
444
+ least one row worked, with how many did, and fills `toast`. `only` is
445
+ the row itself when the reader picked exactly one, so the message can
446
+ name it. `failed` runs when at least one row failed, with every
447
+ failure and its error, so it can count them or join their reasons,
448
+ and fills `notice`. A message nothing calls for is `undefined`.
449
+
450
+ Toast `notice` in place of `toast` when both are there, as the
451
+ example does, so the reader sees one toast.
452
+
453
+ ## Running an action over the picked rows
454
+
455
+ Every list action that changes rows does the same things around the
456
+ calls: the list reloaded, one toast, and the focus moved back to the
457
+ list once a row moved, while the reader is still with the run.
458
+ `useListRun` and `useBulkRun` hold those things for you:
459
+
460
+ ```tsx
461
+ import { Page, RunConfirm, useBulkRun, useListRun } from '@gopherium/godmin'
462
+
463
+ function OrdersScreen() {
464
+ const client = useQueryClient()
465
+ const list = useListView<View>(defaults)
466
+ const { run, region } = useListRun('orders', list.onChangeSelection)
467
+ const refresh = useCallback(() => client.invalidateQueries({ queryKey: ['orders'] }), [client])
468
+ const bulk = useBulkRun<Order>(run, refresh)
469
+ const actions = useMemo<Action<Order>[]>(
470
+ () => [
471
+ {
472
+ id: 'delete',
473
+ label: 'Delete…',
474
+ supportsBulk: true,
475
+ hideModalHeader: true,
476
+ modalFocusOnMount: 'firstContentElement',
477
+ RenderModal: (props) => (
478
+ <RunConfirm {...props} confirmLabel="Delete" cancelLabel="Cancel" run={(orders) => bulk(orders, (order) => deleteOrder(order.id), words)}>
479
+ Delete these orders for good?
480
+ </RunConfirm>
481
+ ),
482
+ },
483
+ ],
484
+ [bulk],
485
+ )
486
+ return (
487
+ <Page title="Orders" list listLabel="Orders" listRef={region}>
488
+ <DataViews {...props} actions={actions} />
489
+ </Page>
490
+ )
491
+ }
492
+ ```
493
+
494
+ Build the actions once with `useMemo`, as the example does. A run
495
+ renders the screen again, and DataViews draws the confirm of a bulk
496
+ action from the actions you pass. A new `RenderModal` would start the
497
+ confirm over in the middle of the run: Cancel would work again, and
498
+ the confirm button could start a second run. When your words or your
499
+ calls change with the screen, list them in the dependencies too.
500
+
501
+ `useListRun` keeps track of the runs on the list. Once a run moved a
502
+ row, the list region takes the focus, so a keyboard reader is not
503
+ left on a button that went away with its row. When two runs overlap,
504
+ only the latest one moves the focus. The list holds no failure. A run
505
+ shows how it went in its toast.
506
+
507
+ A run can end while the reader works somewhere else, such as in a
508
+ dialog they opened on another row. So the list takes the focus only
509
+ while the reader is still with the run:
510
+
511
+ - the focus fell to the page,
512
+ - the focus sits inside the list,
513
+ - the focus sits in the dialog the run started in,
514
+ - or that dialog closed before the run ended, the focus still sits
515
+ where it first went outside that dialog while the dialog was open,
516
+ and no dialog holds the focus. A confirm that closes at once gives
517
+ the focus back to the button that opened it, and the list then
518
+ takes the focus from that button.
519
+
520
+ A dialog opened since keeps the focus, so typing still lands in it
521
+ and Escape still closes it. A reader who moved on to another control
522
+ outside the list keeps their place: during a run started outside
523
+ every dialog, while the dialog the run started in is still open, and
524
+ after that dialog gave the focus back or closed with nowhere to give
525
+ it. One move is the exception. A dialog that lets the focus out,
526
+ unlike a WordPress modal, can be left for another control while it
527
+ is still open. That control then counts as where the dialog gave the
528
+ focus back, since the focus moves the same way in both cases. So when
529
+ the dialog closes and the run ends with the focus still there, the
530
+ list takes the focus from it. Every list run does this, with nothing
531
+ to add to your screen. This needs godmin 0.27.0 or later. Before it,
532
+ the list took the focus wherever the focus sat.
533
+
534
+ `focusInDialog()` tells whether a dialog holds the focus, for a write
535
+ you finish yourself outside a run. It also needs godmin 0.27.0 or
536
+ later.
537
+
538
+ `useListRun` hands the same `run` for as long as the screen stays,
539
+ whichever list it shows. So when the reader moves to another tab, the
540
+ handler `useBulkRun` builds from it stays the same too, as long as
541
+ your `refresh` does.
542
+
543
+ Its first argument names the list on show. Put the list and its tab
544
+ in it, such as `'orders trash'`. When that name changes, the list
545
+ clears the ticked rows and ignores any run started on the list
546
+ before. The second argument replaces the ticked
547
+ rows. Pass the setter that holds them, such as
548
+ `list.onChangeSelection`, or a setter from a parent component. The
549
+ rows clear in the same frame the new list appears.
550
+
551
+ `useBulkRun` makes one call per row with `runEach`, waits for
552
+ `refresh`, shows one toast in your [bulk words](#bulk-messages) and
553
+ then settles the run. The toast holds your `failed` words when any
554
+ row failed, and your `done` words when every row worked. Wrap
555
+ `refresh` in `useCallback`, or the handler changes on every render.
556
+ `refresh` gets the rows the run acted on, so it can also forget each
557
+ row's own cached copy. If `refresh` rejects, the run still shows its
558
+ toast and settles, then rejects with that error.
559
+
560
+ `RunConfirm` is the body of the confirm modal. It runs the action
561
+ when the reader confirms, shows the confirm button busy and keeps
562
+ Cancel inert while the run goes, and closes once the run settles. A
563
+ failure shows in the run's toast, never inside the modal. It also
564
+ closes when the run rejects, and the error still reaches your app.
565
+ It closes only itself. DataViews keeps one dialog for a row's actions
566
+ menu and another for its primary action buttons. A reader can dismiss
567
+ a busy confirm by clicking the dimmed page and open another dialog in
568
+ its place, from the same menu or the same buttons. When the run then
569
+ ends, that other dialog stays open, with what the reader typed in it.
570
+
571
+ `listLabel` and `listRef` make the list a region with a name, which
572
+ a screen reader announces, and give the focus its target. The region
573
+ stays out of the Tab order. Pass both. A list with a ref and no label
574
+ still takes the focus, but a screen reader has no name to announce.
575
+
576
+ A button outside the list, such as one in the page header, can share
577
+ the same run. Call `run.onStart()` as its write starts. It answers a
578
+ function, typed `RunSettled`. Call that function once the write ends,
579
+ with whether a row moved, and show how it went in a toast.
580
+
581
+ Such a run starts outside every dialog. So when it ends, the list
582
+ takes the focus only if the focus fell to the page or sits inside the
583
+ list. While the focus is still on your button, or on another control
584
+ the reader moved to, it stays there. When your button opens a
585
+ `ConfirmDialog` first, as Empty Trash does, call `run.onStart()`
586
+ inside `onConfirm`, as [a confirm outside a list](#a-confirm-outside-a-list)
587
+ explains. The list then takes the focus once the run moved a row,
588
+ even after the dialog closed, while the focus is still on the button
589
+ the dialog gave it back to. A reader who moved to another control by
590
+ then keeps their place. This needs godmin 0.27.0 or later.
591
+
592
+ ## Confirming an action
593
+
594
+ An action that cannot be undone asks first. DataViews opens a modal
595
+ for an action that has a `RenderModal`, and `RunConfirm` is the body
596
+ of that modal for a
597
+ [run over the picked rows](#running-an-action-over-the-picked-rows):
598
+
599
+ ```tsx
600
+ const trash = useMemo<Action<Post>>(
601
+ () => ({
602
+ id: 'move-to-trash',
603
+ label: 'Move to trash',
604
+ supportsBulk: true,
605
+ hideModalHeader: true,
606
+ modalFocusOnMount: 'firstContentElement',
607
+ RenderModal: (props) => (
608
+ <RunConfirm {...props} confirmLabel="Move to trash" cancelLabel="Cancel" run={(posts) => bulk(posts, (post) => trashPost(post.id), words)}>
609
+ Move the picked posts to the trash?
610
+ </RunConfirm>
611
+ ),
612
+ }),
613
+ [bulk],
614
+ )
615
+ ```
616
+
617
+ A confirm that removes something, such as Move to trash or Delete
618
+ permanently, has no header, as in WordPress. Give the action
619
+ `hideModalHeader: true`, and the question is the only text. A plain
620
+ confirm, such as making an item the default, keeps its title through
621
+ `modalHeader`. Leave `modalSize` out, so the modal takes the DataViews
622
+ width, 560px, as WordPress list confirms do.
623
+ `modalFocusOnMount: 'firstContentElement'` puts the focus on Cancel.
624
+ Cancel is borderless text in your accent colour, left of the confirm
625
+ button.
626
+
627
+ For a run you write yourself, `ConfirmBody` is the same body without
628
+ the run:
629
+
630
+ ```tsx
631
+ import { ConfirmBody, runEach, useCloseWhileOpen, useToaster } from '@gopherium/godmin'
632
+
633
+ function TrashModal({ items, closeModal }: RenderModalProps<Post>) {
634
+ const toaster = useToaster()
635
+ const close = useCloseWhileOpen(closeModal)
636
+ const [busy, setBusy] = useState(false)
637
+ const confirm = async () => {
638
+ setBusy(true)
639
+ const outcome = await runEach(items, (post) => trashPost(post.id))
640
+ const moved = outcome.failures.length === 0
641
+ toaster.show(moved ? 'Post moved to the trash.' : 'The post could not be moved to the trash.')
642
+ close()
643
+ }
644
+ return (
645
+ <ConfirmBody
646
+ confirmLabel="Move to trash"
647
+ cancelLabel="Cancel"
648
+ busy={busy}
649
+ onConfirm={() => void confirm()}
650
+ onCancel={closeModal}
651
+ >
652
+ Move the post to the trash?
653
+ </ConfirmBody>
654
+ )
655
+ }
656
+ ```
657
+
658
+ It draws the question, then Cancel as accent text and the solid
659
+ confirm button at the end, 20px under the question. While `busy`,
660
+ the confirm button shows a spinner and ignores a second press, and
661
+ Cancel closes nothing.
662
+
663
+ The body never shows a failure. Close the modal once the write ends,
664
+ whether it worked or not, and say how it went in a toast, as the
665
+ WordPress list confirms do.
666
+
667
+ Close it through `useCloseWhileOpen(closeModal)`, as the example
668
+ does. DataViews keeps one dialog for a row's actions menu and another
669
+ for its primary action buttons. Every dialog that opens in one of
670
+ them gets the same `closeModal`, so a write that ends after the reader
671
+ dismissed your modal and opened another one in its place would shut
672
+ the new one. The close `useCloseWhileOpen` returns does nothing once
673
+ your modal left the screen. `RunConfirm` closes this way already.
674
+ This needs godmin 0.27.0 or later.
675
+
676
+ ## A confirm outside a list
677
+
678
+ Some confirms open from a button outside any list, such as Move to
679
+ trash in an editor or Empty Trash above a list. `ConfirmDialog` asks
680
+ those, as WordPress dialogs do. A confirm above a list can also start
681
+ a [list run](#running-an-action-over-the-picked-rows), as Empty Trash
682
+ does. This section says where the focus goes once that run ends.
683
+ Here the dialog asks before Move to trash in an editor:
684
+
685
+ ```tsx
686
+ import { useToaster } from '@gopherium/godmin'
687
+ import { ConfirmDialog } from '@gopherium/godmin/dialogs'
688
+ import { Button } from '@wordpress/ui'
689
+
690
+ function TrashButton({ post }: { post: Post }) {
691
+ const toaster = useToaster()
692
+ const [asking, setAsking] = useState(false)
693
+ const [trashing, setTrashing] = useState(false)
694
+ const trash = () => {
695
+ setTrashing(true)
696
+ trashPost(post.id)
697
+ .then(() => toaster.show('Post moved to the trash.'))
698
+ .catch((failure) => toaster.show(failure.message))
699
+ .finally(() => setTrashing(false))
700
+ }
701
+ return (
702
+ <>
703
+ <Button variant="outline" loading={trashing} onClick={() => setAsking(true)}>Move to trash</Button>
704
+ {asking ? (
705
+ <ConfirmDialog size="small" confirmLabel="Move to trash" cancelLabel="Cancel" onConfirm={trash} onClose={() => setAsking(false)}>
706
+ Move "Hello" to the trash?
707
+ </ConfirmDialog>
708
+ ) : null}
709
+ </>
710
+ )
711
+ }
712
+ ```
713
+
714
+ It draws the WordPress modal: a card from 600px up, and a sheet
715
+ along the bottom of the screen below 600px, the width
716
+ `SHEET_BREAKPOINT` names. `size` picks the card width. `small` draws
717
+ it 400px wide, as WordPress does for the Move to trash button in its
718
+ editor sidebar, so the example asks for it. `medium`, the default,
719
+ is the 560px card WordPress opens for the Trash action of a list or
720
+ of an actions menu. Both sizes are the same sheet on a phone.
721
+
722
+ Leave `title` out for a confirm that removes something, so the
723
+ question is the only text. Give a plain confirm a `title`, and it
724
+ gets a header with a close button. Cancel has the focus when the
725
+ dialog opens.
726
+
727
+ What `onConfirm` returns decides when the dialog goes:
728
+
729
+ - Return nothing, and the dialog closes at once while your write
730
+ runs. WordPress does this for a confirm that opens from a button or
731
+ a screen menu, such as Move to trash in its editor or Empty Trash
732
+ above a list. Show the write as busy on the button that opened the
733
+ dialog, as the example does with `loading`. Make `onConfirm` a
734
+ plain function, as `trash` is. An `async` function always returns
735
+ a promise, so the dialog would stay open until the write ends. When
736
+ the write is a list run, call `run.onStart()` inside `onConfirm`,
737
+ while the dialog still holds the focus. The dialog gives the focus
738
+ back to its button as it closes, and the list takes the focus once
739
+ the run moved a row, while the focus is still on that button. A
740
+ reader who moved to another control or opened another dialog by
741
+ then keeps their place.
742
+ - Return the write's promise, and the dialog stays open while it
743
+ runs. The confirm button shows a spinner and Cancel greys out. When
744
+ the promise ends, worked or failed, the dialog closes. WordPress
745
+ does this for a confirm that opens from a row's own menu, so use it
746
+ for the rows of a list you draw yourself, outside DataViews:
747
+
748
+ ```tsx
749
+ <ConfirmDialog
750
+ confirmLabel="Delete"
751
+ cancelLabel="Cancel"
752
+ onConfirm={() => deleteGroup(group.id).catch((failure) => toaster.show(failure.message))}
753
+ onClose={() => setAsking(false)}
754
+ >
755
+ Delete "{group.name}"?
756
+ </ConfirmDialog>
757
+ ```
758
+
759
+ Either way, show a failure in a toast. The dialog never shows one
760
+ inside. Put the `.catch` inside `onConfirm` and return what it
761
+ answers, as [a failure from a dialog](#a-failure-from-a-dialog)
762
+ explains.
763
+
764
+ The dialog calls `onClose` after Cancel, Escape, a click outside it,
765
+ the close button of a titled confirm, or a confirm that finished.
766
+ Escape, a click outside it and its close button work at any time,
767
+ even while the write runs. The write then goes on, and `onClose`
768
+ still runs only once. When the dialog goes away, the focus goes back
769
+ to the button that opened it, unless your action already moved it.
770
+
771
+ A list run started in `onConfirm` moves the focus to the list once it
772
+ moved a row, whether the dialog stayed open until then or closed
773
+ before. A dialog that stayed open lets the list keep the focus as it
774
+ closes. A dialog that closed before has given the focus back to its
775
+ button, and the list then takes the focus from that button, while
776
+ the focus is still there. Either way, a reader who moved to another
777
+ control or opened another dialog since keeps their place. This needs
778
+ godmin 0.27.0 or later.
779
+
780
+ Render the dialog only while you ask, as the example does. Each new
781
+ ask then starts fresh.
782
+
783
+ `ConfirmDialog` comes from its own entry, `@gopherium/godmin/dialogs`,
784
+ because it needs `@wordpress/components`, a large package the main
785
+ entry never loads. Install `@wordpress/components` and load its
786
+ stylesheet once, `@wordpress/components/build-style/style.css`, as
787
+ DataViews already asks.
788
+
789
+ ## Renaming an item
790
+
791
+ A rename asks for one new name. `RenameBody` is the body of that
792
+ modal: a field that starts with the current name, an accent text
793
+ Cancel and the submit button:
794
+
795
+ ```tsx
796
+ import { RenameBody, markLatest, useToaster, useUnsavedText } from '@gopherium/godmin'
797
+ import type { Action } from '@wordpress/dataviews'
798
+
799
+ function useRenameAction(): Action<Post> {
800
+ const toaster = useToaster()
801
+ const renames = useUnsavedText()
802
+ return useMemo<Action<Post>>(
803
+ () => ({
804
+ id: 'rename',
805
+ label: 'Rename',
806
+ modalHeader: 'Rename',
807
+ modalFocusOnMount: 'firstContentElement',
808
+ RenderModal: ({ items: [post], closeModal }) => (
809
+ <RenameBody
810
+ name={renames.get(post.id) ?? post.title}
811
+ fieldLabel="Name"
812
+ submitLabel="Save"
813
+ cancelLabel="Cancel"
814
+ onSubmit={(title) => {
815
+ closeModal?.()
816
+ renames.delete(post.id)
817
+ const stillLatest = markLatest(renames, post.id)
818
+ renamePost(post.id, title)
819
+ .then(() => toaster.show('Name updated.'))
820
+ .catch((failure) => {
821
+ if (stillLatest()) {
822
+ renames.set(post.id, title)
823
+ }
824
+ toaster.show(failure.message)
825
+ })
826
+ }}
827
+ onCancel={closeModal}
828
+ />
829
+ ),
830
+ }),
831
+ [toaster, renames],
832
+ )
833
+ }
834
+ ```
835
+
836
+ Leave `modalSize` out, so the rename takes the DataViews width, 560px,
837
+ as the WordPress rename does. WordPress titles it Rename and labels
838
+ its button Save, and the example does the same.
839
+
840
+ The submit button is off only while the field is blank. A name left
841
+ as it was can still be sent, as in the WordPress rename. Enter in the
842
+ field does what the submit button does. `onSubmit` gets the name
843
+ exactly as typed, and your code does the write and the toast.
844
+
845
+ A rename closes the moment the reader presses Save, before its write,
846
+ as WordPress closes its rename. So the body is never busy and never
847
+ shows a failure. When the write fails, say so in a toast and keep
848
+ what the reader typed. `name` is the text the field starts with, so
849
+ hand that text back on the next open. The reader then finds the name
850
+ they typed and can try once more.
851
+
852
+ `useUnsavedText` holds that text, by item id, for as long as the
853
+ screen stays. Keep it in the hook that builds the action, never in the
854
+ modal, which goes the moment the reader saves. Clear the item's text
855
+ before each write, so a save that works leaves nothing behind.
856
+ `markLatest` marks the write as the latest one sent to the item and
857
+ returns a check. Keep the failed text only while the check holds, so
858
+ an earlier save that fails late never overwrites what a later save
859
+ sent, and a later save that works is never undone. The store holds
860
+ any value, so a form with several fields keeps them all, as
861
+ `useUnsavedText<Fields>()`. This needs godmin 0.24.1, or 0.27.0 or
862
+ later. 0.25.0 and 0.26.0 do not have it.
863
+
864
+ Every word comes from you: the field label, both button labels and
865
+ the toasts. Pass them through your translations.
866
+
867
+ `modalFocusOnMount: 'firstContentElement'` puts the cursor in the
868
+ field when the modal opens, as the WordPress rename does. Without it,
869
+ the modal window itself takes the focus, and the reader has to press
870
+ Tab to reach the field.
871
+
872
+ ## A form in a row action
873
+
874
+ Some row actions ask for more than a yes or a name, such as a copy
875
+ with a title of its own or a new role for a user. `FormBody` is the
876
+ body of that modal: the fields you give it, an accent text Cancel and
877
+ the submit button. It is a real form, so Enter in a field sends it:
878
+
879
+ ```tsx
880
+ import { FormBody, useCloseWhileOpen, useToaster } from '@gopherium/godmin'
881
+ import type { Action, RenderModalProps } from '@wordpress/dataviews'
882
+ import { InputControl } from '@wordpress/ui'
883
+
884
+ function DuplicateModal({ items: [post], closeModal }: RenderModalProps<Post>) {
885
+ const toaster = useToaster()
886
+ const close = useCloseWhileOpen(closeModal)
887
+ const [title, setTitle] = useState(`${post.title} (Copy)`)
888
+ const [busy, setBusy] = useState(false)
889
+ const duplicate = () => {
890
+ setBusy(true)
891
+ duplicatePost(post.id, title)
892
+ .then(() => toaster.show(`"${toaster.name(title)}" created.`))
893
+ .catch((failure) => toaster.show(failure.message))
894
+ .finally(close)
895
+ }
896
+ return (
897
+ <FormBody
898
+ kind="copy"
899
+ submitLabel="Duplicate"
900
+ cancelLabel="Cancel"
901
+ canSubmit={title.trim() !== ''}
902
+ busy={busy}
903
+ onSubmit={duplicate}
904
+ onCancel={closeModal}
905
+ >
906
+ <InputControl label="Title" value={title} onChange={(event) => setTitle(event.target.value)} />
907
+ </FormBody>
908
+ )
909
+ }
910
+
911
+ const duplicateAction: Action<Post> = {
912
+ id: 'duplicate',
913
+ label: 'Duplicate',
914
+ modalHeader: 'Duplicate',
915
+ modalFocusOnMount: 'firstContentElement',
916
+ RenderModal: DuplicateModal,
917
+ }
918
+ ```
919
+
920
+ `submitLabel` and `cancelLabel` name the two buttons. `onSubmit` runs
921
+ from the submit button or from Enter, and `onCancel` from Cancel.
922
+ `canSubmit` turns the submit button off, for example while a needed
923
+ field is empty. The button stays reachable with Tab, so a keyboard
924
+ reader still finds it. While `busy`, the submit button shows a
925
+ spinner and a second send does nothing. Cancel stays live the whole
926
+ time, as in WordPress forms.
927
+
928
+ `kind` says what the form does, and sets the space above the buttons
929
+ as WordPress spaces it:
930
+
931
+ | `kind` | For | Space above the buttons |
932
+ | --- | --- | --- |
933
+ | `edit`, the default | A change to one item, such as a new role | 20px |
934
+ | `copy` | A copy of an item, such as Duplicate | 12px |
935
+ | `create` | Something new | 16px |
936
+
937
+ When the modal closes depends on the action, as in WordPress:
938
+
939
+ - A change to one item closes the moment the reader sends it, before
940
+ its write, like the [rename](#renaming-an-item). Call `closeModal`
941
+ first, then write.
942
+ - A copy, something new, or a change to several items stays open with
943
+ its button busy, then closes when the write ends, worked or failed.
944
+ Set `busy` while it runs, and close it through
945
+ `useCloseWhileOpen(closeModal)`, as the example does.
946
+ [Confirming an action](#confirming-an-action) says why. This needs
947
+ godmin 0.27.0 or later.
948
+
949
+ Either way, a failure goes in a toast. `FormBody` never shows one. To
950
+ give the reader back what they typed after a failure, keep it in a
951
+ `useUnsavedText` store outside the modal and pass it in as the first
952
+ value of the fields, as the rename does.
953
+
954
+ Leave `modalSize` out, so the form takes the DataViews width, 560px,
955
+ as WordPress row forms do. `modalFocusOnMount: 'firstContentElement'`
956
+ puts the cursor in the first field.
957
+
958
+ ## A form dialog
959
+
960
+ Some forms open from a button outside any list, such as Add Project
961
+ in a page header. `FormDialog` asks those, as WordPress opens its Add
962
+ Page dialog: a card with a title and a close button, the cursor in
963
+ the first field, and the same form as `FormBody` inside:
964
+
965
+ ```tsx
966
+ import { useToaster } from '@gopherium/godmin'
967
+ import { FormDialog } from '@gopherium/godmin/dialogs'
968
+ import { Button, InputControl } from '@wordpress/ui'
969
+
970
+ function AddProjectDialog({ onClose }: { onClose: () => void }) {
971
+ const toaster = useToaster()
972
+ const [name, setName] = useState('')
973
+ const add = async () => {
974
+ await addProject(name)
975
+ toaster.show(`"${toaster.name(name)}" added.`)
976
+ onClose()
977
+ }
978
+ return (
979
+ <FormDialog
980
+ title="Add Project"
981
+ submitLabel="Add"
982
+ cancelLabel="Cancel"
983
+ canSubmit={name.trim() !== ''}
984
+ onSubmit={() => add().catch((failure) => toaster.show(failure.message))}
985
+ onClose={onClose}
986
+ >
987
+ <InputControl label="Name" value={name} onChange={(event) => setName(event.target.value)} />
988
+ </FormDialog>
989
+ )
990
+ }
991
+
992
+ export function AddProjectButton() {
993
+ const [asking, setAsking] = useState(false)
994
+ return (
995
+ <>
996
+ <Button size="compact" onClick={() => setAsking(true)}>
997
+ Add Project
998
+ </Button>
999
+ {asking ? <AddProjectDialog onClose={() => setAsking(false)} /> : null}
1000
+ </>
1001
+ )
1002
+ }
1003
+ ```
1004
+
1005
+ Render the dialog only while you ask, as the example does. Keep the
1006
+ state of the fields in the dialog's own component, as
1007
+ `AddProjectDialog` does, so each new ask starts with empty fields.
1008
+
1009
+ `size` picks the card width from 600px up. `small`, the default,
1010
+ draws it 400px wide, as WordPress draws Add Page. `medium` draws it
1011
+ 560px wide, for a form whose controls need the room. Below 600px both
1012
+ are the same sheet along the bottom of the screen. `title` is the
1013
+ heading beside the close button. `submitLabel`, `cancelLabel` and
1014
+ `canSubmit` work as in `FormBody`. So does `kind`, but a dialog is a
1015
+ `create` by default, 16px above its buttons.
1016
+
1017
+ `onSubmit` runs from the submit button or from Enter. Return the
1018
+ write's promise, and the submit button shows a spinner until the
1019
+ write ends. A second send meanwhile does nothing. The dialog never
1020
+ closes itself after a send:
1021
+
1022
+ - When the write worked, close it yourself, as `add` does with
1023
+ `onClose`.
1024
+ - When the write failed, leave it open, as WordPress leaves Add Page.
1025
+ The reader keeps what they typed and can try again. Show the
1026
+ failure in a toast, with the `.catch` inside `onSubmit`, as
1027
+ [a failure from a dialog](#a-failure-from-a-dialog) explains.
1028
+
1029
+ A form that opens from a row's own menu, in a list you draw yourself,
1030
+ and changes that one item closes before its write, like the
1031
+ [rename](#renaming-an-item). Give it `size="medium"`, the width
1032
+ WordPress gives its row forms, and `kind="edit"`. In `onSubmit`, take
1033
+ the dialog away first, then start the write, and return nothing.
1034
+
1035
+ Cancel, Escape, a click outside the dialog and its close button all
1036
+ call `onClose`, even while the write runs. When the dialog goes away,
1037
+ the focus goes back to the button that opened it.
1038
+
1039
+ `FormDialog` comes from `@gopherium/godmin/dialogs`, like
1040
+ `ConfirmDialog`, so it needs `@wordpress/components` and its
1041
+ stylesheet the same way.
1042
+
1043
+ ## Putting the focus back on a row
1044
+
1045
+ A dialog your screen holds open on one row, such as Change role on a
1046
+ user, goes away once the reader is done. WordPress then gives the
1047
+ focus back to what opened it. When the list drew that row again in
1048
+ the meantime, for example because the write moved it to another
1049
+ place, the button that opened the dialog is gone and the focus falls
1050
+ to the page. `useFocusBack` finds the row again and puts the focus
1051
+ back:
1052
+
1053
+ ```tsx
1054
+ import { focusedTrigger, useFocusBack, useListRun } from '@gopherium/godmin'
1055
+ import type { Trigger } from '@gopherium/godmin'
1056
+
1057
+ const { run, region } = useListRun('users', list.onChangeSelection)
1058
+ const focusBack = useFocusBack(users.isFetching, region)
1059
+ const [opened, setOpened] = useState<{ user: User, trigger: Trigger }>()
1060
+
1061
+ const close = (shown: { user: User, trigger: Trigger }) => {
1062
+ setOpened(undefined)
1063
+ focusBack(shown.user.id, shown.trigger)
1064
+ }
1065
+ ```
1066
+
1067
+ Mark the title cell of each row with the id DataViews keys the row
1068
+ by, as `data-item-id`. That mark is how the hook finds the row in any
1069
+ layout:
1070
+
1071
+ ```tsx
1072
+ render: ({ item }) => <span data-item-id={item.id}>{item.name}</span>
1073
+ ```
1074
+
1075
+ Then note the trigger each dialog opened from. `focusedTrigger()`
1076
+ reads it from the focus the click, tap or key left:
1077
+
1078
+ ```tsx
1079
+ onClickItem={(user) => setOpened({ user, trigger: focusedTrigger() })}
1080
+ callback: ([user]) => setOpened({ user, trigger: focusedTrigger() })
1081
+ ```
1082
+
1083
+ The hook knows four triggers on a row: the title and the media a
1084
+ click opens from, the phone row a tap opens from and the actions
1085
+ menu. It finds the grid card, the phone list row or the table row
1086
+ that holds the item now and focuses the same trigger there. When that
1087
+ layout has no such trigger, such as a title in the phone list, it
1088
+ focuses the row's actions menu. When the item left the list, or its
1089
+ row has no actions menu, the list region takes the focus.
1090
+
1091
+ An action chosen in the bulk bar reads `bulk` from `focusedTrigger()`.
1092
+ The bar goes away once the selection clears, so the list region
1093
+ takes the focus.
1094
+
1095
+ The hook only moves a focus the page lost. When WordPress already put
1096
+ the focus back, or the reader moved it, it stays where it is. While
1097
+ the first argument is `true`, for example while the list reads its
1098
+ rows again, the hook waits, since a busy list is out of reach of the
1099
+ focus. Pass the same `region` you hand `Page` as `listRef`. The hook
1100
+ looks for the region when the focus is asked back. When the list is
1101
+ busy then, it looks once the wait ends. A screen that draws no region
1102
+ at that point gets no focus moved, even when it draws one later.
1103
+
1104
+ A list can draw the row again just after the focus went back to it.
1105
+ The grid does this as it measures how many cards fit side by side,
1106
+ since a card that moves to another row of cards is drawn anew. The
1107
+ focus then falls to the page. The hook watches the list for this and
1108
+ puts the focus on the same trigger of that row again, each time the
1109
+ list draws it anew. When the item leaves the list instead, the list
1110
+ region takes the focus and the hook stops watching. It also stops
1111
+ once the reader moves the focus or presses somewhere else, the focus
1112
+ is asked back again or the screen goes away, so a control the reader
1113
+ moved to keeps the focus. This needs godmin 0.27.0 or later.
1114
+
1115
+ ## A failure from a dialog
1116
+
1117
+ A write that fails never shows inside a dialog. It shows in a toast,
1118
+ as WordPress shows it in its snackbar. When `onSubmit` or `onConfirm`
1119
+ returns a promise, show the toast from inside that same function, and
1120
+ return the promise that `.catch` answers:
1121
+
1122
+ ```tsx
1123
+ onSubmit={() => save(values).catch((failure) => toaster.show(failure.message))}
1124
+ ```
1125
+
1126
+ `.catch` answers a new promise. That one ends with no error once the
1127
+ toast shows. The dialog stops its spinner, a `ConfirmDialog` closes,
1128
+ and no error goes on to your app. An `async` function that catches
1129
+ its own error inside works the same way, as long as you return what
1130
+ it answers.
1131
+
1132
+ The line works whatever `save` ends with, the saved item or nothing,
1133
+ since the dialog only waits for the promise to end. This needs godmin
1134
+ 0.23.1 or later.
1135
+
1136
+ `.catch` sees a failure only when the write's promise
1137
+ rejects. Many GraphQL clients answer an object with `error` instead,
1138
+ as [bulk actions](#bulk-actions) says. With such a client, throw that
1139
+ `error` inside your write. Otherwise the dialog takes the write as
1140
+ one that worked.
1141
+
1142
+ Do not add the `.catch` as a separate step and then return the first
1143
+ promise:
1144
+
1145
+ ```tsx
1146
+ onSubmit={() => {
1147
+ const saving = save(values)
1148
+ saving.catch((failure) => toaster.show(failure.message))
1149
+ return saving
1150
+ }}
1151
+ ```
1152
+
1153
+ The toast shows, but `saving` itself still fails. The dialog waits on
1154
+ `saving`, so it gets the error too and hands it on to your app as an
1155
+ error nobody caught. The same failure reaches your app a second
1156
+ time, after you already showed it.
1157
+
1158
+ That handing on is on purpose. A failure you did not catch is one you
1159
+ did not expect, and it should not go quiet. It reaches your app,
1160
+ where the browser console and your error reporting see it.
1161
+
1162
+ ## An upload button
1163
+
1164
+ `FileButton` is a compact button that opens the file dialog:
1165
+
1166
+ ```tsx
1167
+ import { FileButton } from '@gopherium/godmin'
1168
+ import { upload } from '@wordpress/icons'
1169
+
1170
+ <FileButton accept="image/*" multiple icon={upload} busy={uploading} onChoose={uploadAll}>
1171
+ Upload media
1172
+ </FileButton>
1173
+ ```
1174
+
1175
+ It keeps a hidden file input beside it. `onChoose` gets the chosen
1176
+ files, and is not called when the reader closes the dialog with none.
1177
+ The input is emptied after each choice, so the same file can be
1178
+ chosen again. `icon` is drawn before the label. `inputLabel` names
1179
+ the hidden input, so a test can find it with `getByLabelText`. While
1180
+ `busy`, the button shows a spinner and ignores a press.
1181
+
1182
+ It is compact and solid unless you say otherwise, as a page header
1183
+ button is. `variant`, `tone` and `size` take the design system
1184
+ button's values. In a dialog header, draw it as WordPress draws the
1185
+ upload button of its media dialog, a default size button with no
1186
+ fill:
1187
+
1188
+ ```tsx
1189
+ <FileButton variant="minimal" tone="neutral" size="default" onChoose={uploadAll}>
1190
+ Upload files
1191
+ </FileButton>
1192
+ ```
1193
+
1194
+ ## Buttons in the list header
1195
+
1196
+ A list page puts its actions beside the title, in `actions`. As in
1197
+ WordPress lists, the main action is one solid compact button, and
1198
+ every other one is an outline compact button:
1199
+
1200
+ ```tsx
1201
+ <Page
1202
+ title="Media"
1203
+ list
1204
+ actions={
1205
+ <>
1206
+ <Button variant="outline" size="compact" onClick={exportAll}>
1207
+ Export
1208
+ </Button>
1209
+ <FileButton accept="image/*" multiple onChoose={uploadAll}>
1210
+ Upload media
1211
+ </FileButton>
1212
+ </>
1213
+ }
1214
+ >
1215
+ <DataViews {...props} />
1216
+ </Page>
1217
+ ```
1218
+
1219
+ ## Naming an item in a toast
1220
+
1221
+ A toast that names an item, such as `"Hello" moved to the trash.`,
1222
+ can get long. `name` on the toaster handle cuts a long name and ends
1223
+ it with an ellipsis:
1224
+
1225
+ ```tsx
1226
+ const toaster = useToaster()
1227
+
1228
+ toaster.show(`"${toaster.name(post.title)}" moved to the trash.`)
1229
+ ```
1230
+
1231
+ A name of 45 characters or fewer shows in full. A longer one keeps
1232
+ its first 45, drops the spaces left at its end, and gets `…`. An
1233
+ emoji counts as one character and is never split. `Toaster` takes
1234
+ `nameLength` to change the 45.
1235
+
1236
+ ## The canvas colour
1237
+
1238
+ The frame seeds the canvas with the design system default background,
1239
+ which [the three seeds](./design-system/color.md#the-three-seeds)
1240
+ gives. The canvas then paints white, the row lines are `#f0f0f0` and
1241
+ the muted text `#707070`, as in WordPress. The canvas also sets
1242
+ `--wp-dataviews-color-background`, so the list, its sticky header and
1243
+ its footer stay the same white as the page around them. You do
1244
+ nothing.
1245
+
1246
+ ## The accent colour
1247
+
1248
+ DataViews and `@wordpress/components` draw their accents, such as a
1249
+ selected row or a focus ring, from `--wp-admin-theme-color`.
1250
+ `AdminRoot` sets that variable from the `primary` colour you pass it.
1251
+ It sets it on the document root, so menus and modals that render
1252
+ outside your tree follow it too.
1253
+
1254
+ ```tsx
1255
+ <AdminRoot color={{ primary: '#c9356e' }}>
1256
+ <App />
1257
+ </AdminRoot>
1258
+ ```
1259
+
1260
+ ## The title field
1261
+
1262
+ Name the field that links to the record as the view's `titleField`:
1263
+
1264
+ ```ts
1265
+ const view = { type: 'table', titleField: 'name', fields: ['email', 'status'] }
1266
+ ```
1267
+
1268
+ DataViews then draws that field with a link that has no underline,
1269
+ like the Posts list. A link in any other field keeps the browser's
1270
+ underline.
1271
+
1272
+ Name a second field as `descriptionField` to show it under the title,
1273
+ such as an email address under a name:
1274
+
1275
+ ```ts
1276
+ const view = { type: 'table', titleField: 'name', descriptionField: 'email', fields: ['status'] }
1277
+ ```
1278
+
1279
+ In a list page godmin sets the pair the way the WordPress subscriber
1280
+ list does. The title is 13px and bold, and the
1281
+ description is a 12px muted line 4px under it. A row with both is
1282
+ 64px tall. A title on its own stays centered in a 32px line, level
1283
+ with the other cells of its row.
1284
+
1285
+ ## Avatars
1286
+
1287
+ `InitialsAvatar` draws a round avatar with the first letter of a
1288
+ name, on a colour the name picks. Use it as the render of the view's
1289
+ `mediaField`:
1290
+
1291
+ ```tsx
1292
+ import { InitialsAvatar } from '@gopherium/godmin'
1293
+
1294
+ const avatar = {
1295
+ id: 'avatar',
1296
+ label: 'Avatar',
1297
+ render: ({ item }) => <InitialsAvatar name={item.name} />,
1298
+ enableSorting: false,
1299
+ }
1300
+ const fields = [nameField, emailField, avatar]
1301
+ const view = { type: 'table', titleField: 'name', mediaField: 'avatar', fields: ['status'] }
1302
+ ```
1303
+
1304
+ It is 32px wide with a 12px semibold letter, and the name starts 8px
1305
+ after it, as in the WordPress subscriber list. The capital of the
1306
+ letter sits in the middle of the circle, as the WordPress avatar
1307
+ draws it. godmin trims the letter's line to the capital and the
1308
+ baseline with the CSS `text-box` property, so the letter stays
1309
+ centred whatever font the page uses. A browser without `text-box`
1310
+ draws it about a pixel low.
1311
+
1312
+ Pass `size` to draw it at another width in pixels, such as
1313
+ `size={16}` for the small avatar WordPress puts before an author
1314
+ name. The letter keeps its share of the circle, 12px in 32px, so it
1315
+ is 6px at 16px.
1316
+
1317
+ Pass `src` to show a picture in the same round box, such as the
1318
+ address gouncer's [`avatar` package](https://docs.gopherium.org/authentication/avatars/) builds
1319
+ from the site's avatar setting. When the address is empty or the
1320
+ picture fails to load, the letter comes back.
1321
+
1322
+ DataViews draws media in a square box with 4px corners and a thin
1323
+ dark ring. godmin rounds that box and drops the ring when it holds an
1324
+ avatar, in the table and in the list layout, because the WordPress
1325
+ avatar has no dark edge. In the list layout the avatar fills the
1326
+ larger box and its letter grows with it.
1327
+
1328
+ On a list page the media of a row sits in the middle of the row. Next
1329
+ to a title with a description under it, the avatar is level with the
1330
+ pair, as in the WordPress subscriber list, instead of with the title
1331
+ alone.
1332
+
1333
+ The same name always gets the same colour, whatever its case and the
1334
+ browser's language. The six
1335
+ colours start with the blue, raspberry and purple of the WordPress
1336
+ subscriber avatars, each with the pale letter WordPress draws on it,
1337
+ then a green, an amber and a grey with a white letter. All six reach
1338
+ 4.5 to 1 against their letter, the contrast a screen needs for small
1339
+ text. The avatar is hidden from screen readers, because the
1340
+ name next to it already says who it is. Without `src` it never loads
1341
+ a picture, so no address leaves your application.
1342
+
1343
+ ## Lists that stay custom
1344
+
1345
+ Some lists cannot be DataViews, such as a list the user orders by
1346
+ hand with arrows. Keep those a `godmin-table`. It looks like the
1347
+ DataViews table: 13px text on 20px lines, small capital headers, 12px
1348
+ of padding in every cell but only 8px above and below a header,
1349
+ rows as tall as the DataViews rows, and a
1350
+ light line between rows. Rows also tint under the pointer and while
1351
+ keyboard focus is inside them, which DataViews does not do.
1352
+
1353
+ Mark the cell that names the record `godmin-table__title`. It draws
1354
+ the name bold, as DataViews draws its titles. A link inside it has no
1355
+ underline and turns the accent colour under the pointer, like a
1356
+ DataViews title field:
1357
+
1358
+ ```tsx
1359
+ <td className="godmin-table__title">
1360
+ <Link to="/fields/$id" params={{ id: field.id }}>{field.label}</Link>
1361
+ </td>
1362
+ ```
1363
+
1364
+ Inside a `list` page the table reaches the canvas edges too, and its
1365
+ first and last cells pad by 24px, as DataViews does. A custom list
1366
+ and a DataViews list then line up with each other and with the title.
1367
+
1368
+ ## The list chrome in Spanish
1369
+
1370
+ DataViews speaks English until you load its translations. Its words,
1371
+ such as Search, View options, Items per page and Next page, live in
1372
+ the WordPress `default` text domain. godmin ships a Spanish catalogue
1373
+ for them. Add it to the domains you load at startup:
1374
+
1375
+ ```ts
1376
+ import { LIST_CHROME_DOMAIN, listChromeCatalogFor } from '@gopherium/godmin'
1377
+ import { startLocale } from '@gopherium/gottext'
1378
+
1379
+ await startLocale(resolveLocale, [
1380
+ { domain: 'myapp', load: myappCatalog },
1381
+ { domain: LIST_CHROME_DOMAIN, load: listChromeCatalogFor },
1382
+ ])
1383
+ ```
1384
+
1385
+ `listChromeCatalogFor` answers the catalogue for `es-ES`, and one
1386
+ for `fr-FR` with the loading words, the [list date](#dates-in-a-list)
1387
+ words and
1388
+ [godmin's own words](./framing-an-application.md#godmins-own-words).
1389
+ For any other language it answers `undefined`. French readers and
1390
+ those others keep the English chrome. Each catalogue is its own small
1391
+ module, so a bundler loads it only for a reader who needs it.
1392
+
1393
+ The Spanish one covers every word DataViews shows around a list: the
1394
+ search box, the view options, the filters, the column menus, the
1395
+ paging and the bulk bar. It also covers the two words
1396
+ `@wordpress/components` shows inside a list, the search reset button
1397
+ and the modal close button. It does not cover DataForm.
1398
+
1399
+ The translations are machine made. They stay marked fuzzy in the
1400
+ sources, `src/list-chrome/es-ES.po` and `src/list-chrome/fr-FR.po`
1401
+ in the godmin repository, until a translator checks them. A test
1402
+ holds every word of the Spanish one against the DataViews build, so a
1403
+ DataViews release that adds or renames one fails the godmin tests
1404
+ instead of showing English.
1405
+
1406
+ Keep one copy of `@wordpress/i18n` on the page. `godminDedupe` lists
1407
+ it for Vite. With two copies, the catalogue would land in one while
1408
+ DataViews reads the other.
1409
+
1410
+ ## Dates in a list
1411
+
1412
+ WordPress lists write a date and time in a short form, such as
1413
+ Oct 13, 2026 5:04 pm. `listDate` writes that form, in a column's
1414
+ `render`:
1415
+
1416
+ ```tsx
1417
+ import { listDate } from '@gopherium/godmin/dates'
1418
+
1419
+ const created = {
1420
+ id: 'created',
1421
+ label: 'Created',
1422
+ render: ({ item }) => listDate(item.createdAt),
1423
+ }
1424
+ ```
1425
+
1426
+ It takes a `Date` or the text a server stored. Empty text writes the
1427
+ current moment, so a cell with no date should not call it.
1428
+
1429
+ The dates live in their own entry, `@gopherium/godmin/dates`, because
1430
+ they bring `@wordpress/date`, moment and its time zone data, close to
1431
+ 800 KB. Install `@wordpress/date` and `@wordpress/i18n` to use it. The
1432
+ main entry never loads them. If your first paint has a size limit,
1433
+ import the dates entry only from code that loads on demand with your
1434
+ lists, never from the code that runs before first paint.
1435
+
1436
+ Set the list dates up once the catalogues load, before the first list
1437
+ renders. `startLocale` answers the language it settled on:
1438
+
1439
+ ```ts
1440
+ import { startListDates } from '@gopherium/godmin/dates'
1441
+
1442
+ const locale = await startLocale(resolveLocale, [
1443
+ { domain: 'myapp', load: myappCatalog },
1444
+ { domain: LIST_CHROME_DOMAIN, load: listChromeCatalogFor },
1445
+ ])
1446
+ startListDates(locale)
1447
+ ```
1448
+
1449
+ Until then `listDate` writes English on the UTC clock.
1450
+
1451
+ `startListDates` takes the month and weekday names, am and pm, the
1452
+ two date-and-time formats and the first weekday from the loaded
1453
+ catalogue, as WordPress does. The same moment then reads:
1454
+
1455
+ | Reader | Writes |
1456
+ | --- | --- |
1457
+ | English | Oct 13, 2026 5:04 pm |
1458
+ | Spanish, `es-ES` | 13 Oct 2026 17:04 |
1459
+ | French, `fr-FR` | 13 octobre 2026 17h04 |
1460
+
1461
+ Any other language writes English. The messages are the WordPress
1462
+ core ones, such as `F j, Y g:i a` and `M j, Y g:i a` for the two
1463
+ formats, so your own catalogue for the `default` domain can answer
1464
+ them too.
1465
+
1466
+ Dates show on the reader's clock, the browser's time zone. Pass a
1467
+ time zone to show another one, such as
1468
+ `startListDates(locale, 'Europe/Madrid')`. Text with no offset, such
1469
+ as `2026-10-13T17:04`, is read as a time on that clock.
1470
+
1471
+ The same call sets the calendar language and the clock that the
1472
+ DataViews date fields and filters read. It does not reach their
1473
+ format or their first weekday. DataViews copies those into each field
1474
+ type when it first loads, before the call. So give a `date` or
1475
+ `datetime` field its own `format`, built after the call, in the code
1476
+ that builds the fields at render:
1477
+
1478
+ ```tsx
1479
+ import { listDate } from '@gopherium/godmin/dates'
1480
+ import { getSettings } from '@wordpress/date'
1481
+
1482
+ function listFields() {
1483
+ return [
1484
+ {
1485
+ id: 'created',
1486
+ label: 'Created',
1487
+ type: 'datetime',
1488
+ render: ({ item }) => listDate(item.createdAt),
1489
+ format: {
1490
+ datetime: getSettings().formats.datetime,
1491
+ weekStartsOn: getSettings().l10n.startOfWeek,
1492
+ },
1493
+ },
1494
+ ]
1495
+ }
1496
+ ```
1497
+
1498
+ Call `listFields()` in the component that draws the list, never at
1499
+ the top of a module, which can run before the call.
1500
+
1501
+ A `date` field reads `formats.date` instead, which the call leaves at
1502
+ the English `F j, Y`. Give it a `date` format of your own.
1503
+
1504
+ Call `startListDates` again when the reader changes language, once
1505
+ the new catalogues load. Then build the fields again, so their
1506
+ `format` follows.
1507
+
1508
+ godmin keeps each set of words under a private language name, such
1509
+ as `es-ES-x-g0`. So `getSettings().l10n.locale` from `@wordpress/date`
1510
+ no longer holds the bare language. Read it from what `startLocale`
1511
+ answered instead.