From b55d327194fc0b13614c4b49d218178615e9526f Mon Sep 17 00:00:00 2001 From: James Koster Date: Fri, 6 Nov 2026 16:13:19 +0000 Subject: [PATCH 01/13] Storybook: Add Settings Page design system patterns Add templates for settings screens composed from the admin-ui Page, @wordpress/ui components, theme tokens and DataViews: a simple page, adjacent pages, subpages with breadcrumbs, and records that open a subpage, dialog or drawer. Document the manual save model's unsaved changes guard in the Save & Submit pattern. Co-authored-by: Cursor --- .../patterns/save-and-submit.mdx | 5 + .../design-system/patterns/settings-page.mdx | 128 +++++ .../patterns/settings-page.story.tsx | 55 +++ .../adjacent-pages-and-subpages.tsx | 76 +++ .../patterns/settings-page/adjacent-pages.tsx | 56 +++ .../patterns/settings-page/api-keys.tsx | 338 +++++++++++++ .../patterns/settings-page/records-dialog.tsx | 140 ++++++ .../patterns/settings-page/records-drawer.tsx | 181 +++++++ .../settings-page/records-subpage.tsx | 91 ++++ .../patterns/settings-page/router.tsx | 238 +++++++++ .../patterns/settings-page/shared.tsx | 452 ++++++++++++++++++ .../patterns/settings-page/simple.tsx | 56 +++ .../patterns/settings-page/store-pages.tsx | 289 +++++++++++ .../patterns/settings-page/style.module.css | 106 ++++ .../patterns/settings-page/subpages.tsx | 75 +++ .../settings-page/unsaved-changes.tsx | 65 +++ 16 files changed, 2351 insertions(+) create mode 100644 storybook/stories/design-system/patterns/settings-page.mdx create mode 100644 storybook/stories/design-system/patterns/settings-page.story.tsx create mode 100644 storybook/stories/design-system/patterns/settings-page/adjacent-pages-and-subpages.tsx create mode 100644 storybook/stories/design-system/patterns/settings-page/adjacent-pages.tsx create mode 100644 storybook/stories/design-system/patterns/settings-page/api-keys.tsx create mode 100644 storybook/stories/design-system/patterns/settings-page/records-dialog.tsx create mode 100644 storybook/stories/design-system/patterns/settings-page/records-drawer.tsx create mode 100644 storybook/stories/design-system/patterns/settings-page/records-subpage.tsx create mode 100644 storybook/stories/design-system/patterns/settings-page/router.tsx create mode 100644 storybook/stories/design-system/patterns/settings-page/shared.tsx create mode 100644 storybook/stories/design-system/patterns/settings-page/simple.tsx create mode 100644 storybook/stories/design-system/patterns/settings-page/store-pages.tsx create mode 100644 storybook/stories/design-system/patterns/settings-page/style.module.css create mode 100644 storybook/stories/design-system/patterns/settings-page/subpages.tsx create mode 100644 storybook/stories/design-system/patterns/settings-page/unsaved-changes.tsx diff --git a/storybook/stories/design-system/patterns/save-and-submit.mdx b/storybook/stories/design-system/patterns/save-and-submit.mdx index 62c95c8ea4f031..a5b60027d8439b 100644 --- a/storybook/stories/design-system/patterns/save-and-submit.mdx +++ b/storybook/stories/design-system/patterns/save-and-submit.mdx @@ -49,6 +49,11 @@ When all changes are saved, the Save button is disabled and can reveal a “No u If the user navigates away with unsaved edits, prompt them to confirm before leaving so their changes aren’t lost. This guard exists **only** in the manual save model; an autosave surface never needs it. +- **Only ask when something would be lost.** Prompt only while there are unsaved edits. Once the user saves, or changes a field back to its saved value, navigation is free again. +- **Inside the app, use an `AlertDialog`.** Hold the navigation (switching between adjacent pages, following a breadcrumb or opening a record) and ask “Discard unsaved changes?” with the `irreversible` intent. Offer two choices: “Keep editing”, which cancels the navigation and is the safe default, and “Discard changes”, which continues. Don’t add a “Save and leave” option: a save can fail validation, and the dialog is the wrong place to show that. +- **When leaving the app, rely on the browser.** Reloading, closing the tab or following an external link can only be guarded with the `beforeunload` event, which shows the browser’s own warning. Its wording can’t be customized, so don’t try to imitate it. +- **Dialogs and drawers that hold a draft close only through their actions.** Give them a footer with Cancel and Save, and omit the close icon and closing by clicking outside, so the user always makes an explicit choice. Cancel discards the draft without asking again, because choosing it is the decision. If the user presses Escape with unsaved edits, ask with the same dialog before closing. + ### Invalid fields, partial saves, and failed saves For automatic saving methods, an invalid field can require being addressed before saving, e.g. by outputting an error message right below the relevant input control. diff --git a/storybook/stories/design-system/patterns/settings-page.mdx b/storybook/stories/design-system/patterns/settings-page.mdx new file mode 100644 index 00000000000000..57f5c271d9fa45 --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page.mdx @@ -0,0 +1,128 @@ +import { Canvas, Markdown, Meta } from '@storybook/addon-docs/blocks'; +import * as SettingsPageStories from './settings-page.story'; +import SimpleSource from './settings-page/simple.tsx?raw'; +import AdjacentPagesSource from './settings-page/adjacent-pages.tsx?raw'; +import SubpagesSource from './settings-page/subpages.tsx?raw'; +import AdjacentPagesAndSubpagesSource from './settings-page/adjacent-pages-and-subpages.tsx?raw'; +import RecordsSubpageSource from './settings-page/records-subpage.tsx?raw'; +import RecordsDialogSource from './settings-page/records-dialog.tsx?raw'; +import RecordsDrawerSource from './settings-page/records-drawer.tsx?raw'; + + + +# Settings Page + +Templates for settings screens, composed from the admin-ui `Page`, `@wordpress/ui` components, `@wordpress/theme` tokens and DataViews. Start from the template closest to your settings, then replace the fields. + +## Building blocks + +Every template uses the same parts: + +- **`Page`** from `@wordpress/admin-ui` provides the header: a title or breadcrumbs, optional section navigation, and the actions area where Save lives. +- **`Card`** from `@wordpress/ui` groups related settings. Give each card a short title, and a description when the title alone doesn't say what the settings affect. Cap form cards at `--wpds-dimension-surface-width-xl` so fields stay a readable length, and give tables of records `--wpds-dimension-surface-width-2xl` so their columns fit. +- **`DataForm`** from `@wordpress/dataviews` renders the fields, so labels, descriptions, validation and spacing stay consistent. +- **`DataViews`** from `@wordpress/dataviews` lists records people can add and edit. +- **`Dialog`**, **`Drawer`** and **`AlertDialog`** from `@wordpress/ui` hold record editors and confirmations. +- **Snackbars** confirm saves that have no other visible effect. `SnackbarList` comes from `@wordpress/components`, since `@wordpress/ui` doesn't offer an equivalent yet. + +Each example's code shows its template. The helpers it imports, such as the manual-save draft, the sample fields and the in-canvas router, live alongside it in `storybook/stories/design-system/patterns/settings-page/`. + +## Saving + +These templates use the manual save model from [Save & Submit](?path=/docs/design-system-patterns-save-submit--docs): edits are held in a draft until the user clicks Save. Autosave remains the preferred default when every field can be saved independently. If you adopt autosave, remove the Save button rather than mixing the two models on one page. + +- **One Save per page**, in the `Page` header actions. It covers every field on that page and nothing else. +- **Disabled when there is nothing to save**, and busy while saving. +- **Checkboxes, not toggles, for on/off settings.** A toggle implies the change takes effect immediately, which isn't true until Save is clicked. Toggles belong on autosave surfaces. +- **A snackbar confirms the save.** Errors belong next to the field, or in a `Notice` when a save fails or only partly succeeds. +- **Pages that only list records have no page-level Save.** Each record editor saves on its own, and the header holds the action that adds a record. +- **Leaving with unsaved edits asks first.** Switching pages or following a breadcrumb holds the navigation and asks “Discard unsaved changes?”, and reloading or closing the tab shows the browser’s own warning. Try it in any template by changing a field, then navigating away. See [Unsaved changes on exit](?path=/docs/design-system-patterns-save-submit--docs#unsaved-changes-on-exit). + +## Simple settings page + +A single page with a few groups of settings. Use it when everything fits on one screen. + + + +## Adjacent pages + +Peer sections of one settings area, such as General, Payments and Emails, switched with the `Page` `navigation`. Use it when the sections are independent and each one is substantial enough to deserve a page. + +- Keep the page title the same across adjacent pages; the navigation shows which section is current. +- Each page has its own draft and Save. Saving one page doesn't save another. +- Pass a router link through `components.link`, so switching pages doesn't reload the screen. + + + +## Subpages + +A subpage holds detail that would crowd the main page, such as the credentials for each payment gateway. Open it from the page body with a full-width row at the bottom of the card: an unstyled `ButtonLink` with a trailing chevron to signal that it navigates. A status badge in the row tells people what they will find there. + +When a card leads to several subpages, put the rows in a list: + +- **Use a `ul`, named by the card title.** Render the title as a heading, and point the list's `aria-labelledby` at it, so screen readers announce “Payment gateways, list, 3 items”. +- **Keep `role="list"` on the unstyled list.** Safari drops list semantics when the bullets are removed. +- **Name each link after its destination.** The row label matches the subpage's heading, so the link's name is just “Card payments”. Show the status in a `Badge` and connect it with `aria-describedby`, so screen readers announce it as a description rather than as part of the name. + +On the subpage, breadcrumbs replace the title and lead back to the parent page. Repeat the row's status next to the breadcrumbs with the `Page` `badges` prop, and update it from the saved settings, not the draft, so it changes when people click Save. + + + +## Adjacent pages and subpages + +When a subpage belongs to one of several adjacent pages, the breadcrumb ancestor stays the same as the area title, for example "Settings / Card payments", whichever adjacent page the subpage belongs to. Adjacent pages are peers, not levels, so they never appear in the trail. The ancestor links back to the adjacent page the subpage was opened from, and the subpage drops the section navigation. + + + +## Records + +Some settings are lists of records, such as API keys, webhooks or redirects. These examples use API keys. Show them in a `DataViews` table, and choose how each record opens by the size of its editor. + +{ ` +| Editor | Use when | +| --- | --- | +| Subpage | The editor is long, has its own sections, or people need to link to a record. | +| Dialog | The editor is short and people should stay focused on one record. | +| Drawer | The editor is medium-sized, people benefit from seeing the table, or the record has secondary actions. | +` } + +### Records that open a subpage + +The record title links to the subpage, and the Edit action goes to the same place. The subpage uses breadcrumbs, and its Save sits in the `Page` header like any other settings page. + + + +### Records that open a dialog + +The dialog saves on its own. Cancel discards the draft, and Save applies it, closes the dialog and confirms with a snackbar. The same dialog adds new records. + +The footer actions are the only way out: there is no close icon, and clicking outside does nothing, so people always choose between keeping and discarding their edits. Pressing Escape closes an untouched dialog, but asks first when there are unsaved edits. + + + +### Records that open a drawer + +The drawer works like the dialog, including closing only through its footer actions, with room for secondary actions. Revoking a key can't be undone, so it asks for confirmation in an `AlertDialog` with the `irreversible` intent, following [Destructive Actions](?path=/docs/design-system-patterns-destructive-actions--docs). + + diff --git a/storybook/stories/design-system/patterns/settings-page.story.tsx b/storybook/stories/design-system/patterns/settings-page.story.tsx new file mode 100644 index 00000000000000..43981c81c9fab3 --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page.story.tsx @@ -0,0 +1,55 @@ +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { AdjacentPagesExample } from './settings-page/adjacent-pages'; +import { AdjacentPagesAndSubpagesExample } from './settings-page/adjacent-pages-and-subpages'; +import { RecordsDialogExample } from './settings-page/records-dialog'; +import { RecordsDrawerExample } from './settings-page/records-drawer'; +import { RecordsSubpageExample } from './settings-page/records-subpage'; +import { SimpleSettingsExample } from './settings-page/simple'; +import { SubpagesExample } from './settings-page/subpages'; + +const meta: Meta = { + title: 'Design System/Patterns/Settings Page', + parameters: { + controls: { disable: true }, + layout: 'fullscreen', + }, + tags: [ 'docs-only' ], +}; + +export default meta; + +type Story = StoryObj; + +export const Simple: Story = { + name: 'Simple settings page', + render: () => , +}; + +export const AdjacentPages: Story = { + name: 'Adjacent pages', + render: () => , +}; + +export const Subpages: Story = { + render: () => , +}; + +export const AdjacentPagesAndSubpages: Story = { + name: 'Adjacent pages and subpages', + render: () => , +}; + +export const RecordsWithSubpages: Story = { + name: 'Records that open a subpage', + render: () => , +}; + +export const RecordsWithDialog: Story = { + name: 'Records that open a dialog', + render: () => , +}; + +export const RecordsWithDrawer: Story = { + name: 'Records that open a drawer', + render: () => , +}; diff --git a/storybook/stories/design-system/patterns/settings-page/adjacent-pages-and-subpages.tsx b/storybook/stories/design-system/patterns/settings-page/adjacent-pages-and-subpages.tsx new file mode 100644 index 00000000000000..c3f9b322e27290 --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/adjacent-pages-and-subpages.tsx @@ -0,0 +1,76 @@ +import { SettingsRouter, useSettingsPath } from './router'; +import { SettingsExample } from './shared'; +import { + adjacentPageHeader, + EmailsPage, + GatewayPage, + gatewayFromPath, + GeneralPage, + PaymentsPage, + subpageHeader, + useStoreSettings, +} from './store-pages'; + +function AdjacentPagesAndSubpagesScreen() { + const path = useSettingsPath(); + const settings = useStoreSettings(); + const gateway = gatewayFromPath( path ); + + if ( gateway ) { + // The ancestor is always the area title, while its link returns to + // the adjacent page the subpage belongs to. + return ( + + ); + } + + switch ( path ) { + case '/payments': + return ( + + ); + case '/emails': + return ( + + ); + default: + return ( + + ); + } +} + +/** + * Adjacent pages where one page leads to a subpage. The subpage drops the + * section navigation and shows breadcrumbs rooted at the area title. + */ +export function AdjacentPagesAndSubpagesExample() { + return ( + + + + + + ); +} diff --git a/storybook/stories/design-system/patterns/settings-page/adjacent-pages.tsx b/storybook/stories/design-system/patterns/settings-page/adjacent-pages.tsx new file mode 100644 index 00000000000000..09af2723050c8b --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/adjacent-pages.tsx @@ -0,0 +1,56 @@ +import { SettingsRouter, useSettingsPath } from './router'; +import { SettingsExample } from './shared'; +import { + adjacentPageHeader, + EmailsPage, + GeneralPage, + PaymentsPage, + useStoreSettings, +} from './store-pages'; + +function AdjacentPagesScreen() { + const path = useSettingsPath(); + const settings = useStoreSettings(); + const header = adjacentPageHeader( path ); + + switch ( path ) { + case '/payments': + return ( + + ); + case '/emails': + return ( + + ); + default: + return ( + + ); + } +} + +/** + * Peer sections of one settings area, switched with the `Page` navigation. + * Each page keeps its own draft and Save. + */ +export function AdjacentPagesExample() { + return ( + + + + + + ); +} diff --git a/storybook/stories/design-system/patterns/settings-page/api-keys.tsx b/storybook/stories/design-system/patterns/settings-page/api-keys.tsx new file mode 100644 index 00000000000000..e96b0df30a33ed --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/api-keys.tsx @@ -0,0 +1,338 @@ +import type { ComponentProps, ReactElement } from 'react'; +import type { Action, Field, View } from '@wordpress/dataviews'; +import { + DataForm, + DataViews, + filterSortAndPaginate, + useFormValidity, +} from '@wordpress/dataviews'; +import { useMemo, useState } from '@wordpress/element'; +import { Badge, Card } from '@wordpress/ui'; +import { simulateRequest, useNotify } from './shared'; + +export type ApiKey = { + id: string; + name: string; + notes: string; + prefix: string; + access: string; + lastUsed: string; + active: boolean; +}; + +export const initialKeys: ApiKey[] = [ + { + id: 'mobile-app', + name: 'Mobile app', + notes: 'Used by the iOS and Android apps.', + prefix: 'wp_live_4f2a', + access: 'write', + lastUsed: '2 hours ago', + active: true, + }, + { + id: 'analytics', + name: 'Analytics dashboard', + notes: '', + prefix: 'wp_live_9c1e', + access: 'read', + lastUsed: 'Yesterday', + active: true, + }, + { + id: 'backup', + name: 'Backup service', + notes: 'Paused while we switch providers.', + prefix: 'wp_live_77bd', + access: 'admin', + lastUsed: '3 weeks ago', + active: false, + }, + { + id: 'staging', + name: 'Staging site', + notes: '', + prefix: 'wp_test_02f8', + access: 'write', + lastUsed: 'Never', + active: true, + }, +]; + +export const emptyKey: ApiKey = { + id: '', + name: '', + notes: '', + prefix: '', + access: 'read', + lastUsed: 'Never', + active: true, +}; + +const ACCESS_LEVELS = [ + { value: 'read', label: 'Read only' }, + { value: 'write', label: 'Read and write' }, + { value: 'admin', label: 'Full access' }, +]; + +export const keyFields: Field< ApiKey >[] = [ + { + id: 'name', + label: 'Name', + type: 'text', + enableHiding: false, + isValid: { required: true }, + }, + { + id: 'notes', + label: 'Notes', + type: 'text', + Edit: 'textarea', + description: 'Where the key is used, for whoever manages it next.', + enableSorting: false, + }, + { + id: 'prefix', + label: 'Key', + type: 'text', + render: ( { item } ) => <>{ item.prefix }…, + enableSorting: false, + readOnly: true, + }, + { + id: 'access', + label: 'Access', + type: 'text', + Edit: 'radio', + elements: ACCESS_LEVELS, + enableSorting: false, + }, + { + id: 'lastUsed', + label: 'Last used', + type: 'text', + enableSorting: false, + readOnly: true, + }, + { + id: 'active', + label: 'Status', + type: 'boolean', + Edit: 'checkbox', + render: ( { item } ) => + item.active ? ( + Active + ) : ( + Inactive + ), + }, +]; + +/** + * The fields people edit. `active` gets its own label in the editors, + * where "Status" alone would not say what the checkbox does. + */ +export const keyFormFields: Field< ApiKey >[] = keyFields.map( ( field ) => + field.id === 'active' + ? { ...field, label: 'Allow requests with this key' } + : field +); + +export const keyForm = { + layout: { type: 'regular' as const }, + fields: [ 'name', 'notes', 'access', 'active' ], +}; + +/** + * The editor for one record, used by the subpage, dialog and drawer. + */ +export function KeyForm( { + data, + onChange, +}: { + data: ApiKey; + onChange: ( edits: Partial< ApiKey > ) => void; +} ) { + const { validity } = useFormValidity( data, keyFormFields, keyForm ); + return ( + + data={ data } + fields={ keyFormFields } + form={ keyForm } + validity={ validity } + onChange={ onChange } + /> + ); +} + +/** + * State for editing one record in an overlay. The overlay saves on its own: + * its Save applies the draft, closes the overlay and confirms in a snackbar. + */ +export function useKeyEditor( onSave: ( key: ApiKey ) => void ) { + const [ isOpen, setIsOpen ] = useState( false ); + // The record stays set after closing, so the overlay keeps its content + // while it animates out. + const [ record, setRecord ] = useState< ApiKey >( emptyKey ); + const [ draft, setDraft ] = useState< ApiKey >( emptyKey ); + const [ isSaving, setIsSaving ] = useState( false ); + const { isValid } = useFormValidity( draft, keyFormFields, keyForm ); + const notify = useNotify(); + + const open = ( key: ApiKey ) => { + setRecord( key ); + setDraft( key ); + setIsOpen( true ); + }; + + const close = () => { + if ( ! isSaving ) { + setIsOpen( false ); + } + }; + + const onChange = ( edits: Partial< ApiKey > ) => + setDraft( ( previous ) => ( { ...previous, ...edits } ) ); + + const isDirty = JSON.stringify( draft ) !== JSON.stringify( record ); + const [ isConfirmingDiscard, setIsConfirmingDiscard ] = useState( false ); + + /** + * Cancel is an explicit choice to discard the draft. Any other way of + * closing (Escape, or swiping a drawer) asks first when there are + * unsaved edits. + */ + const onOpenChange = ( + nextOpen: boolean, + { reason }: { reason: string } + ) => { + if ( nextOpen || isSaving ) { + return; + } + if ( reason === 'close-press' || ! isDirty ) { + close(); + } else { + setIsConfirmingDiscard( true ); + } + }; + + const discard = { + isConfirming: isConfirmingDiscard, + keepEditing: () => setIsConfirmingDiscard( false ), + confirm: () => { + setIsConfirmingDiscard( false ); + close(); + }, + }; + + const save = async () => { + setIsSaving( true ); + await simulateRequest(); + onSave( draft ); + setIsSaving( false ); + setIsOpen( false ); + notify( 'API key saved.' ); + }; + + return { + record, + isOpen, + isNew: ! record.id, + draft, + onChange, + isDirty, + isValid, + isSaving, + open, + close, + onOpenChange, + discard, + save, + }; +} + +/** + * Holds the saved records, above any route or overlay that edits them. + */ +export function useKeys() { + const [ keys, setKeys ] = useState( initialKeys ); + + const saveKey = ( key: ApiKey ) => { + setKeys( ( current ) => { + if ( key.id && current.some( ( { id } ) => id === key.id ) ) { + return current.map( ( item ) => + item.id === key.id ? key : item + ); + } + const suffix = Date.now().toString( 16 ).slice( -4 ); + return [ + ...current, + { + ...key, + id: `key-${ suffix }`, + prefix: `wp_live_${ suffix }`, + }, + ]; + } ); + }; + + const revokeKey = ( key: ApiKey ) => { + setKeys( ( current ) => current.filter( ( { id } ) => id !== key.id ) ); + }; + + return { keys, saveKey, revokeKey }; +} + +/** + * The records table, in a card. The page title already names the records, + * so the card has no title of its own. + */ +export function KeysTable( { + keys, + actions, + onClickItem, + renderItemLink, +}: { + keys: ApiKey[]; + actions?: Action< ApiKey >[]; + onClickItem?: ( item: ApiKey ) => void; + renderItemLink?: ( + props: { item: ApiKey } & ComponentProps< 'a' > + ) => ReactElement; +} ) { + const [ view, setView ] = useState< View >( { + type: 'table', + search: '', + page: 1, + perPage: 10, + filters: [], + layout: {}, + titleField: 'name', + fields: [ 'prefix', 'access', 'lastUsed', 'active' ], + } ); + + const { data, paginationInfo } = useMemo( + () => filterSortAndPaginate( keys, view, keyFields ), + [ keys, view ] + ); + + return ( + + + + + + + + ); +} diff --git a/storybook/stories/design-system/patterns/settings-page/records-dialog.tsx b/storybook/stories/design-system/patterns/settings-page/records-dialog.tsx new file mode 100644 index 00000000000000..9cbbaacf4210de --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/records-dialog.tsx @@ -0,0 +1,140 @@ +import { Page } from '@wordpress/admin-ui'; +import type { Action } from '@wordpress/dataviews'; +import { pencil } from '@wordpress/icons'; +import { Button, Dialog } from '@wordpress/ui'; +import type { ApiKey } from './api-keys'; +import { + emptyKey, + KeyForm, + KeysTable, + useKeyEditor, + useKeys, +} from './api-keys'; +import { + SettingsContent, + SettingsExample, + useOverlayContainer, +} from './shared'; +import { DiscardChangesDialog } from './unsaved-changes'; + +/** + * Edits one record in a dialog. People leave through Cancel, which discards + * the draft, or Save, which applies it; there is no close button and + * clicking outside does nothing, so the choice is always explicit. + */ +export function KeyDialog( { + editor, +}: { + editor: ReturnType< typeof useKeyEditor >; +} ) { + const overlayContainer = useOverlayContainer(); + // The alert dialog sits outside `Dialog.Root`: Base UI doesn't render a + // backdrop for a dialog nested inside another, which would leave this + // dialog undimmed behind it. + return ( + <> + + } + > + + + { editor.isNew ? 'Add API key' : 'Edit API key' } + + + + + + + + Cancel + + + + + + + + ); +} + +export function AddKeyButton( { onClick }: { onClick: () => void } ) { + return ( + + ); +} + +function RecordsDialogPage() { + const { keys, saveKey } = useKeys(); + const editor = useKeyEditor( saveKey ); + const actions: Action< ApiKey >[] = [ + { + id: 'edit', + label: 'Edit', + icon: pencil, + isPrimary: true, + callback: ( [ key ] ) => editor.open( key ), + }, + ]; + + return ( + editor.open( emptyKey ) } /> + } + > + + + + + + ); +} + +/** + * A table of records where each record opens a dialog. Use it for short + * editors, when people should stay in the context of the table. + */ +export function RecordsDialogExample() { + return ( + + + + ); +} diff --git a/storybook/stories/design-system/patterns/settings-page/records-drawer.tsx b/storybook/stories/design-system/patterns/settings-page/records-drawer.tsx new file mode 100644 index 00000000000000..dc450170bafc84 --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/records-drawer.tsx @@ -0,0 +1,181 @@ +import { Page } from '@wordpress/admin-ui'; +import type { Action } from '@wordpress/dataviews'; +import { useRef, useState } from '@wordpress/element'; +import { isRTL } from '@wordpress/i18n'; +import { pencil } from '@wordpress/icons'; +import { AlertDialog, Button, Drawer } from '@wordpress/ui'; +import type { ApiKey } from './api-keys'; +import { + emptyKey, + KeyForm, + KeysTable, + useKeyEditor, + useKeys, +} from './api-keys'; +import { AddKeyButton } from './records-dialog'; +import { + SettingsContent, + SettingsExample, + simulateRequest, + useNotify, + useOverlayContainer, +} from './shared'; +import styles from './style.module.css'; +import { DiscardChangesDialog } from './unsaved-changes'; + +/** + * Edits one record in a drawer, which keeps the table in view and leaves + * room for secondary actions. Like the dialog, it closes only through its + * footer actions. Revoking asks for confirmation first, because it cannot + * be undone. + */ +function KeyDrawer( { + editor, + onRevoke, +}: { + editor: ReturnType< typeof useKeyEditor >; + onRevoke: ( key: ApiKey ) => void; +} ) { + const [ isConfirmingRevoke, setIsConfirmingRevoke ] = useState( false ); + const revokeButtonRef = useRef< HTMLButtonElement >( null ); + const notify = useNotify(); + const overlayContainer = useOverlayContainer(); + + const revokeKey = async () => { + await simulateRequest(); + onRevoke( editor.record ); + editor.close(); + notify( 'API key revoked.' ); + }; + + // The alert dialogs sit outside `Drawer.Root`: Base UI doesn't render a + // backdrop for a dialog nested inside another, which would leave the + // drawer undimmed behind them. + return ( + <> + + } + > + + + { editor.isNew ? 'Add API key' : 'Edit API key' } + + + + + + + { ! editor.isNew && ( + + ) } + + Cancel + + + + + + + + } + finalFocus={ revokeButtonRef } + intent="irreversible" + title={ `Revoke “${ editor.record.name }”?` } + description="Apps using this key will lose access immediately. This can’t be undone." + confirmButtonText="Revoke key" + /> + + + + ); +} + +function RecordsDrawerPage() { + const { keys, saveKey, revokeKey } = useKeys(); + const editor = useKeyEditor( saveKey ); + const actions: Action< ApiKey >[] = [ + { + id: 'edit', + label: 'Edit', + icon: pencil, + isPrimary: true, + callback: ( [ key ] ) => editor.open( key ), + }, + ]; + + return ( + editor.open( emptyKey ) } /> + } + > + + + + + + ); +} + +/** + * A table of records where each record opens a drawer, which holds the + * editor and a destructive action that opens a confirmation dialog. + */ +export function RecordsDrawerExample() { + return ( + + + + ); +} diff --git a/storybook/stories/design-system/patterns/settings-page/records-subpage.tsx b/storybook/stories/design-system/patterns/settings-page/records-subpage.tsx new file mode 100644 index 00000000000000..ed24e76f69b62b --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/records-subpage.tsx @@ -0,0 +1,91 @@ +import { Breadcrumbs, Page } from '@wordpress/admin-ui'; +import type { Action } from '@wordpress/dataviews'; +import { pencil } from '@wordpress/icons'; +import { Link as RouterLink, useNavigate } from '@wordpress/route'; +import type { ApiKey } from './api-keys'; +import { KeyForm, KeysTable, useKeys } from './api-keys'; +import { SettingsRouter, useSettingsPath } from './router'; +import { + SettingsContent, + SettingsExample, + SettingsFormPage, + SettingsSection, +} from './shared'; + +function KeysPage( { keys }: { keys: ApiKey[] } ) { + const navigate = useNavigate(); + const actions: Action< ApiKey >[] = [ + { + id: 'edit', + label: 'Edit', + icon: pencil, + isPrimary: true, + callback: ( [ key ] ) => navigate( { to: `/keys/${ key.id }` } ), + }, + ]; + + return ( + + + ( + + ) } + /> + + + ); +} + +function RecordsSubpageScreen() { + const path = useSettingsPath(); + const { keys, saveKey } = useKeys(); + const key = keys.find( ( { id } ) => path === `/keys/${ id }` ); + + if ( ! key ) { + return ; + } + + return ( + + } + saved={ key } + onSave={ saveKey } + > + { ( { data, onChange } ) => ( + + + + ) } + + ); +} + +/** + * A table of records where each record opens its own subpage. The subpage + * has room for a full editor and its Save sits in the `Page` header. + */ +export function RecordsSubpageExample() { + return ( + + + + + + ); +} diff --git a/storybook/stories/design-system/patterns/settings-page/router.tsx b/storybook/stories/design-system/patterns/settings-page/router.tsx new file mode 100644 index 00000000000000..17b25f94b83e82 --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/router.tsx @@ -0,0 +1,238 @@ +import type { AnchorHTMLAttributes, ComponentProps, ReactNode } from 'react'; +import { createContext, useContext, useId, useState } from '@wordpress/element'; +import { isRTL } from '@wordpress/i18n'; +import { chevronLeft, chevronRight } from '@wordpress/icons'; +import { __dangerousOptInToUnstableAPIsOnlyForCoreModules } from '@wordpress/private-apis'; +import { + Link as RouterLink, + privateApis as routePrivateApis, +} from '@wordpress/route'; +import { Badge, ButtonLink, Icon, Text } from '@wordpress/ui'; +import styles from './style.module.css'; + +const { unlock } = __dangerousOptInToUnstableAPIsOnlyForCoreModules( + 'I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.', + '@wordpress/storybook' +); + +const { + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + parseHref, + RouterProvider, + useBlocker, + useLocation, +} = unlock( routePrivateApis ); + +type NavigationType = 'PUSH' | 'REPLACE'; + +type Blocker = { + blockerFn: ( args: { + currentLocation: unknown; + nextLocation: unknown; + action: NavigationType; + } ) => boolean | Promise< boolean >; + enableBeforeUnload?: boolean | ( () => boolean ); +}; + +type Navigate = ( + path: string, + state: unknown, + navigateOpts?: { ignoreBlocker?: boolean } +) => void; + +/** + * An in-memory history, so examples navigate inside the canvas without + * touching the URL. TanStack's memory history ignores blockers, unlike the + * browser history admin pages use, so this one runs them itself. + */ +function createBlockingMemoryHistory( initialPath: string ) { + const history = createMemoryHistory( { initialEntries: [ initialPath ] } ); + let blockers: Blocker[] = []; + + const isBlocked = async ( + action: NavigationType, + path: string, + state: unknown + ) => { + for ( const blocker of blockers ) { + if ( + await blocker.blockerFn( { + currentLocation: history.location, + nextLocation: parseHref( path, state ), + action, + } ) + ) { + return true; + } + } + return false; + }; + + const guard = + ( action: NavigationType, navigate: Navigate ): Navigate => + async ( path, state, navigateOpts ) => { + if ( + navigateOpts?.ignoreBlocker || + ! ( await isBlocked( action, path, state ) ) + ) { + navigate( path, state, navigateOpts ); + } + }; + + const onBeforeUnload = ( event: BeforeUnloadEvent ) => { + const shouldWarn = blockers.some( ( { enableBeforeUnload = true } ) => + typeof enableBeforeUnload === 'function' + ? enableBeforeUnload() + : enableBeforeUnload + ); + if ( shouldWarn ) { + event.preventDefault(); + } + }; + + history.push = guard( 'PUSH', history.push ); + history.replace = guard( 'REPLACE', history.replace ); + history.block = ( blocker: Blocker ) => { + blockers = [ ...blockers, blocker ]; + window.addEventListener( 'beforeunload', onBeforeUnload ); + return () => { + blockers = blockers.filter( ( item ) => item !== blocker ); + if ( ! blockers.length ) { + window.removeEventListener( 'beforeunload', onBeforeUnload ); + } + }; + }; + + return history; +} + +// `useBlocker` re-registers whenever its options change identity, which +// re-renders the router, so they must stay stable between renders. +const alwaysBlock = () => true; + +/** + * Holds navigation while `isDirty` is true, so the page can ask before its + * draft is lost. Leaving the app (reloading or closing the tab) falls back to + * the browser's own warning, which can't be customized. + */ +export function useNavigationBlocker( isDirty: boolean ) { + return useBlocker( { + shouldBlockFn: alwaysBlock, + enableBeforeUnload: true, + disabled: ! isDirty, + withResolver: true, + } ); +} + +const ScreenContext = createContext< ReactNode >( null ); + +function Screen() { + return <>{ useContext( ScreenContext ) }; +} + +function createSettingsRouter( initialPath: string ) { + // The screen renders from the root route, so it stays mounted (and keeps + // its state) while the child routes only make every path a match. + const rootRoute = createRootRoute( { component: Screen } ); + const routeTree = rootRoute.addChildren( [ + createRoute( { + getParentRoute: () => rootRoute, + path: '/', + component: () => null, + } ), + createRoute( { + getParentRoute: () => rootRoute, + path: '$', + component: () => null, + } ), + ] ); + return createRouter( { + routeTree, + history: createBlockingMemoryHistory( initialPath ), + defaultNotFoundComponent: () => null, + } ); +} + +/** + * Gives an example an in-memory router, so `Breadcrumbs`, `Page` navigation + * and subpage links navigate inside the canvas without touching the URL. + */ +export function SettingsRouter( { + initialPath = '/', + children, +}: { + initialPath?: string; + children: ReactNode; +} ) { + const [ router ] = useState( () => createSettingsRouter( initialPath ) ); + return ( + + + + ); +} + +export function useSettingsPath(): string { + return useLocation().pathname; +} + +/** + * Passed to `Page` as `components.link`, so the section navigation routes + * through the router instead of reloading the page. + */ +export function RouterNavLink( { + href, + ...props +}: AnchorHTMLAttributes< HTMLAnchorElement > & { href: string } ) { + return ; +} + +export type SubpageStatus = { + label: string; + intent?: ComponentProps< typeof Badge >[ 'intent' ]; +}; + +/** + * Opens a subpage from the page body, as a full-width row. It is a link + * because it changes location; the trailing chevron signals that it + * navigates. The link is named by its label alone, which matches the + * subpage's heading, and the status badge describes it. + */ +export function SubpageLink( { + to, + status, + children, +}: { + to: string; + status?: SubpageStatus; + children: ReactNode; +} ) { + const labelId = useId(); + const statusId = useId(); + return ( + } + aria-labelledby={ labelId } + aria-describedby={ status ? statusId : undefined } + > + + { children } + + { status && ( + + { status.label } + + ) } + + + ); +} diff --git a/storybook/stories/design-system/patterns/settings-page/shared.tsx b/storybook/stories/design-system/patterns/settings-page/shared.tsx new file mode 100644 index 00000000000000..f3506f75e69d0d --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/shared.tsx @@ -0,0 +1,452 @@ +import clsx from 'clsx'; +import type { ComponentProps, ReactNode } from 'react'; +import { Page } from '@wordpress/admin-ui'; +import { SnackbarList } from '@wordpress/components'; +import type { Field } from '@wordpress/dataviews'; +import { DataForm } from '@wordpress/dataviews'; +import { + createContext, + useCallback, + useContext, + useRef, + useState, +} from '@wordpress/element'; +import { Button, Card, Stack, Text } from '@wordpress/ui'; +import type { SubpageStatus } from './router'; +import styles from './style.module.css'; +import { UnsavedChangesGuard } from './unsaved-changes'; + +const SAVE_DELAY = 800; + +export function simulateRequest() { + return new Promise( ( resolve ) => setTimeout( resolve, SAVE_DELAY ) ); +} + +const NotifyContext = createContext< ( message: string ) => void >( () => {} ); + +/** + * Confirms a save that has no other visible effect. + */ +export function useNotify() { + return useContext( NotifyContext ); +} + +const OverlayContainerContext = createContext< HTMLElement | null >( null ); + +/** + * The element dialogs and drawers portal into, so they stay inside their + * example instead of covering the whole docs page. + */ +export function useOverlayContainer() { + return useContext( OverlayContainerContext ); +} + +/** + * The frame every example renders in. It hosts the snackbar list, which the + * Save & Submit guidance uses to confirm a successful save, and the + * container that overlays render into. + */ +export function SettingsExample( { children }: { children: ReactNode } ) { + const [ notices, setNotices ] = useState< + Array< { id: string; content: string } > + >( [] ); + const [ overlayContainer, setOverlayContainer ] = + useState< HTMLDivElement | null >( null ); + const noticeIdRef = useRef( 0 ); + + const notify = useCallback( ( message: string ) => { + noticeIdRef.current += 1; + setNotices( [ + { id: String( noticeIdRef.current ), content: message }, + ] ); + }, [] ); + + return ( + + +
+ { children } + + setNotices( ( current ) => + current.filter( ( notice ) => notice.id !== id ) + ) + } + /> +
+
+ + + ); +} + +/** + * Manual save model: edits are held in a local draft and applied together + * when the user saves. The saved value lives above the page, so it survives + * navigating between pages. + */ +export function useManualSave< T extends object >( + saved: T, + onSave: ( data: T ) => void, + message = 'Settings saved.' +) { + const [ data, setData ] = useState( saved ); + const [ isSaving, setIsSaving ] = useState( false ); + const notify = useNotify(); + + const isDirty = JSON.stringify( data ) !== JSON.stringify( saved ); + + const onChange = useCallback( ( edits: Partial< T > ) => { + setData( ( previous ) => ( { ...previous, ...edits } ) ); + }, [] ); + + const save = async () => { + setIsSaving( true ); + await simulateRequest(); + onSave( data ); + setIsSaving( false ); + notify( message ); + }; + + return { data, onChange, isDirty, isSaving, save }; +} + +/** + * The page-level Save, placed in the `Page` header actions. It is disabled + * while there is nothing to save and shows a busy state while saving. + */ +export function SaveButton( { + isDirty, + isSaving, + onClick, +}: { + isDirty: boolean; + isSaving: boolean; + onClick: () => void; +} ) { + return ( + + ); +} + +type PageHeaderProps = Omit< + ComponentProps< typeof Page >, + 'children' | 'actions' +>; + +/** + * A settings page (or subpage) that owns one manual-save draft, with its + * Save in the `Page` header actions. Render it with a `key` per location, + * so each page starts from its saved values, and inside a router, which the + * unsaved changes guard uses to hold navigation. + */ +export function SettingsFormPage< T extends object >( { + saved, + onSave, + children, + ...pageProps +}: PageHeaderProps & { + saved: T; + onSave: ( data: T ) => void; + children: ( form: { + data: T; + onChange: ( edits: Partial< T > ) => void; + } ) => ReactNode; +} ) { + const { data, onChange, isDirty, isSaving, save } = useManualSave( + saved, + onSave + ); + + return ( + + } + > + + { children( { data, onChange } ) } + + + + ); +} + +/** + * Constrains settings content to a readable width. Forms stay narrow so + * fields don't stretch; tables need room for their columns, so they can + * be wide. + */ +export function SettingsContent( { + wide = false, + children, +}: { + wide?: boolean; + children: ReactNode; +} ) { + return ( + + { children } + + ); +} + +/** + * A group of related settings in a card. + */ +export function SettingsSection( { + title, + titleId, + description, + children, +}: { + title: string; + titleId?: string; + description?: string; + children: ReactNode; +} ) { + return ( + + + + }> + { title } + + { description && ( + + { description } + + ) } + + + { children } + + ); +} + +/** + * A `DataForm` with the regular layout, bound to a manual-save draft. + */ +export function SettingsForm< T extends object >( { + data, + fields, + onChange, +}: { + data: T; + fields: Field< T >[]; + onChange: ( edits: Partial< T > ) => void; +} ) { + return ( + + data={ data } + fields={ fields } + form={ { + layout: { type: 'regular' }, + fields: fields.map( ( field ) => field.id ), + } } + onChange={ ( edits ) => onChange( edits as Partial< T > ) } + /> + ); +} + +export type GeneralSettings = { + storeName: string; + tagline: string; + contactEmail: string; + country: string; + guestCheckout: boolean; + orderNotes: boolean; + orderPrefix: string; +}; + +export const generalSettings: GeneralSettings = { + storeName: 'Pizza Planet', + tagline: 'Out of this world pizza.', + contactEmail: 'hello@example.com', + country: 'us', + guestCheckout: true, + orderNotes: false, + orderPrefix: 'PP-', +}; + +export const generalFields: Field< GeneralSettings >[] = [ + { id: 'storeName', label: 'Store name', type: 'text' }, + { + id: 'tagline', + label: 'Tagline', + type: 'text', + description: 'A short description shown in search results.', + }, + { id: 'contactEmail', label: 'Contact email', type: 'email' }, + { + id: 'country', + label: 'Country', + type: 'text', + elements: [ + { value: 'us', label: 'United States' }, + { value: 'gb', label: 'United Kingdom' }, + { value: 'de', label: 'Germany' }, + { value: 'jp', label: 'Japan' }, + ], + }, +]; + +export const checkoutFields: Field< GeneralSettings >[] = [ + { + id: 'guestCheckout', + label: 'Allow guest checkout', + type: 'boolean', + Edit: 'checkbox', + }, + { + id: 'orderNotes', + label: 'Show order notes field', + type: 'boolean', + Edit: 'checkbox', + }, + { + id: 'orderPrefix', + label: 'Order number prefix', + type: 'text', + }, +]; + +export type PaymentSettings = { + currency: string; + testMode: boolean; + statementDescriptor: string; +}; + +export const paymentSettings: PaymentSettings = { + currency: 'usd', + testMode: true, + statementDescriptor: 'PIZZA PLANET', +}; + +export const paymentFields: Field< PaymentSettings >[] = [ + { + id: 'currency', + label: 'Currency', + type: 'text', + elements: [ + { value: 'usd', label: 'US dollar' }, + { value: 'gbp', label: 'Pound sterling' }, + { value: 'eur', label: 'Euro' }, + { value: 'jpy', label: 'Japanese yen' }, + ], + }, + { + id: 'testMode', + label: 'Use test mode', + type: 'boolean', + Edit: 'checkbox', + description: 'Process payments without charging customers.', + }, + { + id: 'statementDescriptor', + label: 'Statement descriptor', + type: 'text', + description: 'Shown on customers’ bank statements.', + }, +]; + +export type GatewaySettings = { + apiKey: string; + webhookSecret: string; + captureMode: string; +}; + +export const GATEWAYS = [ + { id: 'cards', name: 'Card payments' }, + { id: 'wallets', name: 'Digital wallets' }, + { id: 'pay-later', name: 'Buy now, pay later' }, +]; + +export const gatewaySettings: Record< string, GatewaySettings > = { + cards: { + apiKey: 'pk_test_4eC39HqLyjWDarjtT1zdp7dc', + webhookSecret: '', + captureMode: 'automatic', + }, + wallets: { + apiKey: 'pk_live_9fB27KdMwqZrLpX4', + webhookSecret: 'whsec_51Hq', + captureMode: 'automatic', + }, + 'pay-later': { apiKey: '', webhookSecret: '', captureMode: 'manual' }, +}; + +export function gatewayStatus( { apiKey }: GatewaySettings ): SubpageStatus { + if ( ! apiKey ) { + return { label: 'Not connected', intent: 'none' }; + } + return apiKey.startsWith( 'pk_test_' ) + ? { label: 'Test API key', intent: 'informational' } + : { label: 'Connected', intent: 'stable' }; +} + +export const gatewayFields: Field< GatewaySettings >[] = [ + { id: 'apiKey', label: 'API key', type: 'text' }, + { id: 'webhookSecret', label: 'Webhook secret', type: 'password' }, + { + id: 'captureMode', + label: 'Capture payments', + type: 'text', + Edit: 'radio', + elements: [ + { value: 'automatic', label: 'Automatically' }, + { value: 'manual', label: 'Manually, after review' }, + ], + }, +]; + +export type EmailSettings = { + senderName: string; + senderEmail: string; + footerText: string; +}; + +export const emailSettings: EmailSettings = { + senderName: 'Pizza Planet', + senderEmail: 'orders@example.com', + footerText: 'Thanks for ordering from Pizza Planet.', +}; + +export const emailFields: Field< EmailSettings >[] = [ + { id: 'senderName', label: 'Sender name', type: 'text' }, + { id: 'senderEmail', label: 'Sender email', type: 'email' }, + { + id: 'footerText', + label: 'Footer text', + type: 'text', + Edit: 'textarea', + }, +]; diff --git a/storybook/stories/design-system/patterns/settings-page/simple.tsx b/storybook/stories/design-system/patterns/settings-page/simple.tsx new file mode 100644 index 00000000000000..a94bb8ebaeff2b --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/simple.tsx @@ -0,0 +1,56 @@ +import { useState } from '@wordpress/element'; +import { SettingsRouter } from './router'; +import { + checkoutFields, + generalFields, + generalSettings, + SettingsExample, + SettingsForm, + SettingsFormPage, + SettingsSection, +} from './shared'; + +function SimpleSettingsPage() { + const [ saved, setSaved ] = useState( generalSettings ); + + return ( + + { ( { data, onChange } ) => ( + <> + + + + + + + + ) } + + ); +} + +export function SimpleSettingsExample() { + return ( + + + + + + ); +} diff --git a/storybook/stories/design-system/patterns/settings-page/store-pages.tsx b/storybook/stories/design-system/patterns/settings-page/store-pages.tsx new file mode 100644 index 00000000000000..f8e1527f46030e --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/store-pages.tsx @@ -0,0 +1,289 @@ +import type { ComponentProps } from 'react'; +import { Breadcrumbs } from '@wordpress/admin-ui'; +import { useId, useState } from '@wordpress/element'; +import { Badge, Card } from '@wordpress/ui'; +import type { SubpageStatus } from './router'; +import { RouterNavLink, SubpageLink } from './router'; +import type { GatewaySettings } from './shared'; +import { + checkoutFields, + emailFields, + emailSettings, + gatewayFields, + GATEWAYS, + gatewaySettings, + gatewayStatus, + generalFields, + generalSettings, + paymentFields, + paymentSettings, + SettingsForm, + SettingsFormPage, + SettingsSection, +} from './shared'; +import styles from './style.module.css'; + +export const ADJACENT_PAGES = [ + { label: 'General', href: '/general' }, + { label: 'Payments', href: '/payments' }, + { label: 'Emails', href: '/emails' }, +]; + +/** + * The saved values for every page, held above the router so they survive + * navigation. + */ +export function useStoreSettings() { + const [ general, setGeneral ] = useState( generalSettings ); + const [ payments, setPayments ] = useState( paymentSettings ); + const [ gateways, setGateways ] = useState( gatewaySettings ); + const [ emails, setEmails ] = useState( emailSettings ); + const setGateway = ( id: string, value: GatewaySettings ) => + setGateways( ( current ) => ( { ...current, [ id ]: value } ) ); + return { + general, + setGeneral, + payments, + setPayments, + gateways, + setGateway, + emails, + setEmails, + }; +} + +export const GATEWAYS_PATH = '/payment-gateways'; + +/** + * The gateway a subpage path points to, if any. + */ +export function gatewayFromPath( path: string ) { + return GATEWAYS.find( + ( gateway ) => path === `${ GATEWAYS_PATH }/${ gateway.id }` + ); +} + +type StoreSettings = ReturnType< typeof useStoreSettings >; + +type HeaderProps = Pick< + ComponentProps< typeof SettingsFormPage >, + 'title' | 'subTitle' | 'breadcrumbs' | 'navigation' | 'components' +>; + +/** + * Header props for a page that sits among adjacent pages. + */ +export function adjacentPageHeader( currentHref: string ): HeaderProps { + return { + title: 'Settings', + navigation: { items: ADJACENT_PAGES, currentHref }, + components: { link: RouterNavLink }, + }; +} + +/** + * Header props for a subpage. The breadcrumb trail stands in for the title. + */ +export function subpageHeader( + trail: Array< { label: string; to?: string } > +): HeaderProps { + return { breadcrumbs: }; +} + +export function GeneralPage( { + settings, + header, +}: { + settings: StoreSettings; + header: HeaderProps; +} ) { + return ( + + { ( { data, onChange } ) => ( + <> + + + + + + + + ) } + + ); +} + +/** + * A card that lists subpages, one row each. The rows are links in a list + * named by the card title, so screen readers announce the group and its + * size. + */ +export function SubpageListSection( { + title, + description, + items, +}: { + title: string; + description: string; + items: Array< { to: string; label: string; status?: SubpageStatus } >; +} ) { + const titleId = useId(); + return ( + + + { /* + * Disable reason: The `list` ARIA role is redundant but + * Safari+VoiceOver won't announce the list otherwise. + */ + /* eslint-disable jsx-a11y/no-redundant-roles */ } +
    + { items.map( ( item ) => ( +
  • + + { item.label } + +
  • + ) ) } +
+ { /* eslint-enable jsx-a11y/no-redundant-roles */ } +
+
+ ); +} + +/** + * The payment gateways card, with a row for each gateway's subpage. + */ +export function GatewaysSection( { settings }: { settings: StoreSettings } ) { + return ( + ( { + to: `${ GATEWAYS_PATH }/${ gateway.id }`, + label: gateway.name, + status: gatewayStatus( settings.gateways[ gateway.id ] ), + } ) ) } + /> + ); +} + +export function PaymentsPage( { + settings, + header, + showGateways, +}: { + settings: StoreSettings; + header: HeaderProps; + showGateways?: boolean; +} ) { + return ( + + { ( { data, onChange } ) => ( + <> + + + + { showGateways && ( + + ) } + + ) } + + ); +} + +export function GatewayPage( { + gatewayId, + settings, + header, +}: { + gatewayId: string; + settings: StoreSettings; + header: HeaderProps; +} ) { + // The badge reflects the saved settings, so it changes on Save, not while + // the draft is being edited. + const status = gatewayStatus( settings.gateways[ gatewayId ] ); + return ( + { status.label } } + saved={ settings.gateways[ gatewayId ] } + onSave={ ( value ) => settings.setGateway( gatewayId, value ) } + > + { ( { data, onChange } ) => ( + + + + ) } + + ); +} + +export function EmailsPage( { + settings, + header, +}: { + settings: StoreSettings; + header: HeaderProps; +} ) { + return ( + + { ( { data, onChange } ) => ( + + + + ) } + + ); +} diff --git a/storybook/stories/design-system/patterns/settings-page/style.module.css b/storybook/stories/design-system/patterns/settings-page/style.module.css new file mode 100644 index 00000000000000..ff97776ef18d64 --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/style.module.css @@ -0,0 +1,106 @@ +/* + * Layout containment makes the frame the containing block for the fixed + * overlays portalled into it, and clipping hides a drawer while it slides in. + */ +.example { + position: relative; + min-block-size: 640px; + display: flex; + flex-direction: column; + contain: layout; + overflow: clip; + isolation: isolate; +} + +.example > * { + flex: 1; +} + +/* + * Modal overlays lock page scrolling with inline styles. Here they only cover + * their example, so the docs page around it keeps scrolling. + */ +:global(html):has(.overlays:not(:empty)), +:global(body):has(.overlays:not(:empty)) { + overflow: revert !important; + position: revert !important; + block-size: revert !important; + inline-size: revert !important; +} + +/* `Page` sets `z-index: 1`, so overlays need their own layer above it. */ +.example > .overlays { + flex: none; + position: relative; + z-index: 2; +} + +.content { + inline-size: 100%; + max-inline-size: var(--wpds-dimension-surface-width-xl); + + &.is-wide { + max-inline-size: var(--wpds-dimension-surface-width-2xl); + } + margin-inline: auto; +} + +.description { + color: var(--wpds-color-foreground-content-neutral-weak); +} + +/* + * A full-width row at the bottom of a card. The focus ring is inset because + * the card clips anything drawn outside it. + */ +.subpage-link { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--wpds-dimension-gap-md); + inline-size: 100%; + padding-block: var(--wpds-dimension-padding-lg); + padding-inline: var(--wpds-dimension-padding-2xl); + border-block-start: var(--wpds-border-width-xs) solid var(--wpds-color-stroke-surface-neutral); + color: var(--wpds-color-foreground-content-neutral); + text-decoration: none; + + &:hover { + background-color: var(--wpds-color-background-interactive-neutral-weak-active); + } + + &:focus-visible { + outline-offset: calc(-1 * var(--wpds-border-width-focus)); + } +} + +.subpage-list { + margin: 0; + padding: 0; + list-style: none; +} + +.subpage-label { + flex: 1; + font-weight: var(--wpds-typography-font-weight-emphasis); +} + +.footer-start { + margin-inline-end: auto; +} + +.snackbars:global(.components-snackbar-list) { + position: absolute; + inset-block-start: auto; + inset-inline-end: 0; + inset-block-end: var(--wpds-dimension-padding-lg); + inset-inline-start: 0; + width: auto; + display: flex; + flex-direction: column; + align-items: center; +} + +.snackbars :global(.components-snackbar) { + margin-inline: auto; +} diff --git a/storybook/stories/design-system/patterns/settings-page/subpages.tsx b/storybook/stories/design-system/patterns/settings-page/subpages.tsx new file mode 100644 index 00000000000000..819d51685086d9 --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/subpages.tsx @@ -0,0 +1,75 @@ +import { SettingsRouter, useSettingsPath } from './router'; +import { + generalFields, + SettingsExample, + SettingsForm, + SettingsFormPage, + SettingsSection, +} from './shared'; +import { + GatewayPage, + gatewayFromPath, + GatewaysSection, + subpageHeader, + useStoreSettings, +} from './store-pages'; + +function SubpagesScreen() { + const path = useSettingsPath(); + const settings = useStoreSettings(); + const gateway = gatewayFromPath( path ); + + if ( gateway ) { + return ( + + ); + } + + return ( + + { ( { data, onChange } ) => ( + <> + + + + + + ) } + + ); +} + +/** + * A settings page with a subpage for detail that would crowd the main + * page. The subpage replaces the title with breadcrumbs that lead back. + */ +export function SubpagesExample() { + return ( + + + + + + ); +} diff --git a/storybook/stories/design-system/patterns/settings-page/unsaved-changes.tsx b/storybook/stories/design-system/patterns/settings-page/unsaved-changes.tsx new file mode 100644 index 00000000000000..337a10209da03b --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/unsaved-changes.tsx @@ -0,0 +1,65 @@ +import { useEffect, useRef } from '@wordpress/element'; +import { AlertDialog } from '@wordpress/ui'; +import { useNavigationBlocker } from './router'; +import { useOverlayContainer } from './shared'; + +/** + * Asks before unsaved edits are thrown away. Keep editing is the safe + * default; discarding can't be undone, so it uses the irreversible intent. + */ +export function DiscardChangesDialog( { + open, + onKeepEditing, + onDiscard, +}: { + open: boolean; + onKeepEditing: () => void; + onDiscard: () => void; +} ) { + const overlayContainer = useOverlayContainer(); + // Confirming also closes the dialog, which must not count as keeping. + const isDiscardingRef = useRef( false ); + useEffect( () => { + if ( open ) { + isDiscardingRef.current = false; + } + }, [ open ] ); + + return ( + { + if ( ! nextOpen && ! isDiscardingRef.current ) { + onKeepEditing(); + } + } } + onConfirm={ () => { + isDiscardingRef.current = true; + onDiscard(); + } } + > + } + intent="irreversible" + title="Discard unsaved changes?" + description="If you leave, your changes will be lost." + confirmButtonText="Discard changes" + cancelButtonText="Keep editing" + /> + + ); +} + +/** + * Guards a manual-save page: navigating away with unsaved edits asks first. + */ +export function UnsavedChangesGuard( { isDirty }: { isDirty: boolean } ) { + const blocker = useNavigationBlocker( isDirty ); + return ( + blocker.reset?.() } + onDiscard={ () => blocker.proceed?.() } + /> + ); +} From c78efeab40558a69408461225536d898976776b9 Mon Sep 17 00:00:00 2001 From: James Koster Date: Fri, 6 Nov 2026 16:16:34 +0000 Subject: [PATCH 02/13] Storybook: Clarify that Settings Page templates aren't prescriptive Co-authored-by: Cursor --- storybook/stories/design-system/patterns/settings-page.mdx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/storybook/stories/design-system/patterns/settings-page.mdx b/storybook/stories/design-system/patterns/settings-page.mdx index 57f5c271d9fa45..7b19797b142297 100644 --- a/storybook/stories/design-system/patterns/settings-page.mdx +++ b/storybook/stories/design-system/patterns/settings-page.mdx @@ -14,6 +14,8 @@ import RecordsDrawerSource from './settings-page/records-drawer.tsx?raw'; Templates for settings screens, composed from the admin-ui `Page`, `@wordpress/ui` components, `@wordpress/theme` tokens and DataViews. Start from the template closest to your settings, then replace the fields. +These templates are starting points, not requirements. Not every settings page needs to match one exactly: adapt the structure to what your settings need, and combine or depart from the templates where that serves people better. + ## Building blocks Every template uses the same parts: From baed5e88bbad1af1c992948dc2587a390229084b Mon Sep 17 00:00:00 2001 From: James Koster Date: Tue, 10 Nov 2026 12:38:15 +0000 Subject: [PATCH 03/13] Storybook: Include adjacent pages in Settings Page breadcrumbs Adjacent pages now show a "Settings / " breadcrumb, with Settings leading to the first adjacent page since the area has no page of its own. Subpages of an adjacent page pass through it, for example "Settings / Payments / Card payments". Co-authored-by: Cursor --- .../design-system/patterns/settings-page.mdx | 4 ++-- .../adjacent-pages-and-subpages.tsx | 9 +++++---- .../patterns/settings-page/store-pages.tsx | 19 +++++++++++++++++-- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/storybook/stories/design-system/patterns/settings-page.mdx b/storybook/stories/design-system/patterns/settings-page.mdx index 7b19797b142297..4f8a9c551ac909 100644 --- a/storybook/stories/design-system/patterns/settings-page.mdx +++ b/storybook/stories/design-system/patterns/settings-page.mdx @@ -53,7 +53,7 @@ A single page with a few groups of settings. Use it when everything fits on one Peer sections of one settings area, such as General, Payments and Emails, switched with the `Page` `navigation`. Use it when the sections are independent and each one is substantial enough to deserve a page. -- Keep the page title the same across adjacent pages; the navigation shows which section is current. +- Name the current page in a breadcrumb under the area, for example "Settings / General", and keep the navigation to show its peers. There is no separate Settings page, so "Settings" links to the first adjacent page. - Each page has its own draft and Save. Saving one page doesn't save another. - Pass a router link through `components.link`, so switching pages doesn't reload the screen. @@ -81,7 +81,7 @@ On the subpage, breadcrumbs replace the title and lead back to the parent page. ## Adjacent pages and subpages -When a subpage belongs to one of several adjacent pages, the breadcrumb ancestor stays the same as the area title, for example "Settings / Card payments", whichever adjacent page the subpage belongs to. Adjacent pages are peers, not levels, so they never appear in the trail. The ancestor links back to the adjacent page the subpage was opened from, and the subpage drops the section navigation. +When a subpage belongs to one of several adjacent pages, its trail passes through that page, for example "Settings / Payments / Card payments". "Payments" leads back to the page the subpage was opened from, and the subpage drops the section navigation. @@ -63,7 +63,8 @@ function AdjacentPagesAndSubpagesScreen() { /** * Adjacent pages where one page leads to a subpage. The subpage drops the - * section navigation and shows breadcrumbs rooted at the area title. + * section navigation, and its breadcrumbs pass through the adjacent page it + * belongs to. */ export function AdjacentPagesAndSubpagesExample() { return ( diff --git a/storybook/stories/design-system/patterns/settings-page/store-pages.tsx b/storybook/stories/design-system/patterns/settings-page/store-pages.tsx index f8e1527f46030e..2be98bf785b618 100644 --- a/storybook/stories/design-system/patterns/settings-page/store-pages.tsx +++ b/storybook/stories/design-system/patterns/settings-page/store-pages.tsx @@ -71,11 +71,26 @@ type HeaderProps = Pick< >; /** - * Header props for a page that sits among adjacent pages. + * The settings area at the root of every adjacent page's trail. There is no + * separate Settings page, so it leads to the first adjacent page. + */ +export const SETTINGS_CRUMB = { + label: 'Settings', + to: ADJACENT_PAGES[ 0 ].href, +}; + +/** + * Header props for a page that sits among adjacent pages. The breadcrumb + * names the current page, and the navigation shows its peers. */ export function adjacentPageHeader( currentHref: string ): HeaderProps { + const page = ADJACENT_PAGES.find( ( { href } ) => href === currentHref ); return { - title: 'Settings', + breadcrumbs: ( + + ), navigation: { items: ADJACENT_PAGES, currentHref }, components: { link: RouterNavLink }, }; From 92bd0598e6e493dc45553b8946ce8e63e2d8a36f Mon Sep 17 00:00:00 2001 From: James Koster Date: Tue, 10 Nov 2026 13:14:56 +0000 Subject: [PATCH 04/13] Storybook: Keep the Settings title on adjacent pages The navigation already shows which adjacent page is current, so the title stays "Settings" rather than repeating it in a breadcrumb. Subpages keep a trail through their adjacent page, for example "Settings / Payments / Card payments". Co-authored-by: Cursor --- .../design-system/patterns/settings-page.mdx | 4 ++-- .../patterns/settings-page/store-pages.tsx | 15 +++++---------- 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/storybook/stories/design-system/patterns/settings-page.mdx b/storybook/stories/design-system/patterns/settings-page.mdx index 4f8a9c551ac909..fa9ddfa628e317 100644 --- a/storybook/stories/design-system/patterns/settings-page.mdx +++ b/storybook/stories/design-system/patterns/settings-page.mdx @@ -53,7 +53,7 @@ A single page with a few groups of settings. Use it when everything fits on one Peer sections of one settings area, such as General, Payments and Emails, switched with the `Page` `navigation`. Use it when the sections are independent and each one is substantial enough to deserve a page. -- Name the current page in a breadcrumb under the area, for example "Settings / General", and keep the navigation to show its peers. There is no separate Settings page, so "Settings" links to the first adjacent page. +- Keep the page title the same across adjacent pages; the navigation shows which page is current, so the title doesn't need to name it. - Each page has its own draft and Save. Saving one page doesn't save another. - Pass a router link through `components.link`, so switching pages doesn't reload the screen. @@ -81,7 +81,7 @@ On the subpage, breadcrumbs replace the title and lead back to the parent page. ## Adjacent pages and subpages -When a subpage belongs to one of several adjacent pages, its trail passes through that page, for example "Settings / Payments / Card payments". "Payments" leads back to the page the subpage was opened from, and the subpage drops the section navigation. +When a subpage belongs to one of several adjacent pages, its trail passes through that page, for example "Settings / Payments / Card payments". "Payments" leads back to the page the subpage was opened from, with its navigation item current, and "Settings" leads to the first adjacent page. The subpage drops the section navigation. ; /** - * The settings area at the root of every adjacent page's trail. There is no - * separate Settings page, so it leads to the first adjacent page. + * The settings area at the root of a subpage's trail. There is no separate + * Settings page, so it leads to the first adjacent page. */ export const SETTINGS_CRUMB = { label: 'Settings', @@ -80,17 +80,12 @@ export const SETTINGS_CRUMB = { }; /** - * Header props for a page that sits among adjacent pages. The breadcrumb - * names the current page, and the navigation shows its peers. + * Header props for a page that sits among adjacent pages. The title names + * the area, and the navigation shows which page is current. */ export function adjacentPageHeader( currentHref: string ): HeaderProps { - const page = ADJACENT_PAGES.find( ( { href } ) => href === currentHref ); return { - breadcrumbs: ( - - ), + title: 'Settings', navigation: { items: ADJACENT_PAGES, currentHref }, components: { link: RouterNavLink }, }; From efd184f2db2a74a79f85a5e0cf36586f4236b81d Mon Sep 17 00:00:00 2001 From: James Koster Date: Wed, 11 Nov 2026 13:05:22 +0000 Subject: [PATCH 05/13] Place focus after navigating between Settings Page templates Following a breadcrumb or subpage row moves focus to the new page's heading, so screen readers announce it. The section navigation keeps focus on the newly current item. Document the guidance. Co-authored-by: Cursor --- .../design-system/patterns/settings-page.mdx | 9 +++ .../patterns/settings-page/router.tsx | 77 ++++++++++++++++++- .../patterns/settings-page/style.module.css | 12 +++ 3 files changed, 95 insertions(+), 3 deletions(-) diff --git a/storybook/stories/design-system/patterns/settings-page.mdx b/storybook/stories/design-system/patterns/settings-page.mdx index fa9ddfa628e317..af0e54ac39e96f 100644 --- a/storybook/stories/design-system/patterns/settings-page.mdx +++ b/storybook/stories/design-system/patterns/settings-page.mdx @@ -40,6 +40,15 @@ These templates use the manual save model from [Save & Submit](?path=/docs/desig - **Pages that only list records have no page-level Save.** Each record editor saves on its own, and the header holds the action that adds a record. - **Leaving with unsaved edits asks first.** Switching pages or following a breadcrumb holds the navigation and asks “Discard unsaved changes?”, and reloading or closing the tab shows the browser’s own warning. Try it in any template by changing a field, then navigating away. See [Unsaved changes on exit](?path=/docs/design-system-patterns-save-submit--docs#unsaved-changes-on-exit). +## Focus after navigation + +Moving between adjacent pages and subpages replaces the page, including the link that was just used. Without help, keyboard focus falls back to the start of the document and screen readers don't announce the new page. Place focus once the new page renders: + +- **After a breadcrumb or subpage row, focus the new page's heading.** The link is gone, and the heading is the first thing that tells people where they are. Give the heading `tabindex="-1"` so it can take focus, and hide the focus ring, since it isn't interactive. Screen readers then read the heading out. +- **After the section navigation, focus the newly current item.** The navigation is still on screen, so people can keep moving between pages from where they were. + +The templates do this in their in-canvas router. Try it by following a breadcrumb with the keyboard. + ## Simple settings page A single page with a few groups of settings. Use it when everything fits on one screen. diff --git a/storybook/stories/design-system/patterns/settings-page/router.tsx b/storybook/stories/design-system/patterns/settings-page/router.tsx index 17b25f94b83e82..be0a6b08db2374 100644 --- a/storybook/stories/design-system/patterns/settings-page/router.tsx +++ b/storybook/stories/design-system/patterns/settings-page/router.tsx @@ -1,5 +1,17 @@ -import type { AnchorHTMLAttributes, ComponentProps, ReactNode } from 'react'; -import { createContext, useContext, useId, useState } from '@wordpress/element'; +import type { + AnchorHTMLAttributes, + ComponentProps, + MouseEvent, + ReactNode, +} from 'react'; +import { + createContext, + useContext, + useEffect, + useId, + useRef, + useState, +} from '@wordpress/element'; import { isRTL } from '@wordpress/i18n'; import { chevronLeft, chevronRight } from '@wordpress/icons'; import { __dangerousOptInToUnstableAPIsOnlyForCoreModules } from '@wordpress/private-apis'; @@ -129,8 +141,67 @@ export function useNavigationBlocker( isDirty: boolean ) { const ScreenContext = createContext< ReactNode >( null ); +/** + * Places focus after navigating, since the page that held the activated link + * is replaced and focus would otherwise fall back to the document. A link in + * navigation the new page also has, like the section navigation, hands focus + * to that navigation's current item. Any other link, like a breadcrumb or a + * subpage row, hands it to the new page's heading, so screen readers announce + * the page. + */ +function useFocusAfterNavigate() { + const containerRef = useRef< HTMLDivElement >( null ); + const activatedNavigationRef = useRef< string | null >( null ); + const { pathname } = useLocation(); + const previousPathnameRef = useRef( pathname ); + + useEffect( () => { + if ( previousPathnameRef.current === pathname ) { + return; + } + previousPathnameRef.current = pathname; + const container = containerRef.current; + const { activeElement } = container?.ownerDocument ?? document; + if ( ! container || container.contains( activeElement ) ) { + return; + } + const navigationLabel = activatedNavigationRef.current; + const currentItem = navigationLabel + ? container.querySelector< HTMLElement >( + `nav[aria-label="${ CSS.escape( + navigationLabel + ) }"] [aria-current="page"]` + ) + : null; + if ( currentItem ) { + currentItem.focus(); + return; + } + const heading = container.querySelector( 'h1' ); + heading?.setAttribute( 'tabindex', '-1' ); + heading?.focus(); + }, [ pathname ] ); + + // Clicks that aren't on a link, like confirming a discard prompt, keep the + // link that started the navigation. + const onClickCapture = ( event: MouseEvent< HTMLDivElement > ) => { + const link = ( event.target as Element ).closest( 'a' ); + if ( link ) { + activatedNavigationRef.current = + link.closest( 'nav' )?.getAttribute( 'aria-label' ) ?? null; + } + }; + + return { ref: containerRef, onClickCapture }; +} + function Screen() { - return <>{ useContext( ScreenContext ) }; + const containerProps = useFocusAfterNavigate(); + return ( +
+ { useContext( ScreenContext ) } +
+ ); } function createSettingsRouter( initialPath: string ) { diff --git a/storybook/stories/design-system/patterns/settings-page/style.module.css b/storybook/stories/design-system/patterns/settings-page/style.module.css index ff97776ef18d64..7186cda959244c 100644 --- a/storybook/stories/design-system/patterns/settings-page/style.module.css +++ b/storybook/stories/design-system/patterns/settings-page/style.module.css @@ -29,6 +29,18 @@ } /* `Page` sets `z-index: 1`, so overlays need their own layer above it. */ +.screen { + display: contents; +} + +/* + * The heading takes focus after navigation so screen readers announce the + * new page. It isn't interactive, so it shows no focus ring. + */ +.screen h1[tabindex="-1"]:focus { + outline: none; +} + .example > .overlays { flex: none; position: relative; From dab05c08109ec8c0af35c2fbf6f23189d903d815 Mon Sep 17 00:00:00 2001 From: James Koster Date: Thu, 12 Nov 2026 10:15:19 +0000 Subject: [PATCH 06/13] Storybook: Focus the Page region after Settings Page navigation Match @wordpress/boot, which moves focus to the new page's Page region when a navigation removes the focused element. Name subpage regions after the current page, since their breadcrumbs replace the title, and update the guidance. Co-authored-by: Cursor --- .../design-system/patterns/settings-page.mdx | 7 ++- .../settings-page/records-subpage.tsx | 1 + .../patterns/settings-page/router.tsx | 49 +++---------------- .../patterns/settings-page/store-pages.tsx | 15 ++++-- .../patterns/settings-page/style.module.css | 10 +--- 5 files changed, 25 insertions(+), 57 deletions(-) diff --git a/storybook/stories/design-system/patterns/settings-page.mdx b/storybook/stories/design-system/patterns/settings-page.mdx index af0e54ac39e96f..fb1ab75ecbdff8 100644 --- a/storybook/stories/design-system/patterns/settings-page.mdx +++ b/storybook/stories/design-system/patterns/settings-page.mdx @@ -42,12 +42,11 @@ These templates use the manual save model from [Save & Submit](?path=/docs/desig ## Focus after navigation -Moving between adjacent pages and subpages replaces the page, including the link that was just used. Without help, keyboard focus falls back to the start of the document and screen readers don't announce the new page. Place focus once the new page renders: +Moving between adjacent pages and subpages replaces the page, including the link that was just used. Without help, keyboard focus falls back to the start of the document and screen readers don't announce the new page. -- **After a breadcrumb or subpage row, focus the new page's heading.** The link is gone, and the heading is the first thing that tells people where they are. Give the heading `tabindex="-1"` so it can take focus, and hide the focus ring, since it isn't interactive. Screen readers then read the heading out. -- **After the section navigation, focus the newly current item.** The navigation is still on screen, so people can keep moving between pages from where they were. +Admin pages built on `@wordpress/boot` handle this for you: when a navigation removes the focused element, focus moves to the new page's `Page` region, and screen readers announce it by name. The region takes its name from `title`, so a subpage whose breadcrumbs replace the title needs an `ariaLabel` naming the page, such as "Card payments". Don't move focus yourself on those pages. If your app routes without `@wordpress/boot`, do the same after each navigation that loses focus. -The templates do this in their in-canvas router. Try it by following a breadcrumb with the keyboard. +The templates' in-canvas router follows the same behavior. Try it by following a breadcrumb with the keyboard. ## Simple settings page diff --git a/storybook/stories/design-system/patterns/settings-page/records-subpage.tsx b/storybook/stories/design-system/patterns/settings-page/records-subpage.tsx index ed24e76f69b62b..1af5f3ab5413d8 100644 --- a/storybook/stories/design-system/patterns/settings-page/records-subpage.tsx +++ b/storybook/stories/design-system/patterns/settings-page/records-subpage.tsx @@ -64,6 +64,7 @@ function RecordsSubpageScreen() { ] } /> } + ariaLabel={ key.name } saved={ key } onSave={ saveKey } > diff --git a/storybook/stories/design-system/patterns/settings-page/router.tsx b/storybook/stories/design-system/patterns/settings-page/router.tsx index be0a6b08db2374..b27f379e2fe780 100644 --- a/storybook/stories/design-system/patterns/settings-page/router.tsx +++ b/storybook/stories/design-system/patterns/settings-page/router.tsx @@ -1,9 +1,4 @@ -import type { - AnchorHTMLAttributes, - ComponentProps, - MouseEvent, - ReactNode, -} from 'react'; +import type { AnchorHTMLAttributes, ComponentProps, ReactNode } from 'react'; import { createContext, useContext, @@ -142,16 +137,12 @@ export function useNavigationBlocker( isDirty: boolean ) { const ScreenContext = createContext< ReactNode >( null ); /** - * Places focus after navigating, since the page that held the activated link - * is replaced and focus would otherwise fall back to the document. A link in - * navigation the new page also has, like the section navigation, hands focus - * to that navigation's current item. Any other link, like a breadcrumb or a - * subpage row, hands it to the new page's heading, so screen readers announce - * the page. + * Moves focus to the new `Page` region when a navigation removes the focused + * link, as `@wordpress/boot` does for admin pages. Focus would otherwise fall + * back to the document, and screen readers wouldn't announce the new page. */ function useFocusAfterNavigate() { const containerRef = useRef< HTMLDivElement >( null ); - const activatedNavigationRef = useRef< string | null >( null ); const { pathname } = useLocation(); const previousPathnameRef = useRef( pathname ); @@ -165,40 +156,16 @@ function useFocusAfterNavigate() { if ( ! container || container.contains( activeElement ) ) { return; } - const navigationLabel = activatedNavigationRef.current; - const currentItem = navigationLabel - ? container.querySelector< HTMLElement >( - `nav[aria-label="${ CSS.escape( - navigationLabel - ) }"] [aria-current="page"]` - ) - : null; - if ( currentItem ) { - currentItem.focus(); - return; - } - const heading = container.querySelector( 'h1' ); - heading?.setAttribute( 'tabindex', '-1' ); - heading?.focus(); + container.querySelector< HTMLElement >( '[role="region"]' )?.focus(); }, [ pathname ] ); - // Clicks that aren't on a link, like confirming a discard prompt, keep the - // link that started the navigation. - const onClickCapture = ( event: MouseEvent< HTMLDivElement > ) => { - const link = ( event.target as Element ).closest( 'a' ); - if ( link ) { - activatedNavigationRef.current = - link.closest( 'nav' )?.getAttribute( 'aria-label' ) ?? null; - } - }; - - return { ref: containerRef, onClickCapture }; + return containerRef; } function Screen() { - const containerProps = useFocusAfterNavigate(); + const containerRef = useFocusAfterNavigate(); return ( -
+
{ useContext( ScreenContext ) }
); diff --git a/storybook/stories/design-system/patterns/settings-page/store-pages.tsx b/storybook/stories/design-system/patterns/settings-page/store-pages.tsx index 4fbe7a0a1279cb..140c27c71460bb 100644 --- a/storybook/stories/design-system/patterns/settings-page/store-pages.tsx +++ b/storybook/stories/design-system/patterns/settings-page/store-pages.tsx @@ -67,7 +67,12 @@ type StoreSettings = ReturnType< typeof useStoreSettings >; type HeaderProps = Pick< ComponentProps< typeof SettingsFormPage >, - 'title' | 'subTitle' | 'breadcrumbs' | 'navigation' | 'components' + | 'title' + | 'subTitle' + | 'breadcrumbs' + | 'ariaLabel' + | 'navigation' + | 'components' >; /** @@ -92,12 +97,16 @@ export function adjacentPageHeader( currentHref: string ): HeaderProps { } /** - * Header props for a subpage. The breadcrumb trail stands in for the title. + * Header props for a subpage. The breadcrumb trail stands in for the title, + * so the page region takes its name from the last crumb. */ export function subpageHeader( trail: Array< { label: string; to?: string } > ): HeaderProps { - return { breadcrumbs: }; + return { + breadcrumbs: , + ariaLabel: trail[ trail.length - 1 ].label, + }; } export function GeneralPage( { diff --git a/storybook/stories/design-system/patterns/settings-page/style.module.css b/storybook/stories/design-system/patterns/settings-page/style.module.css index 7186cda959244c..f0006bfd915e4a 100644 --- a/storybook/stories/design-system/patterns/settings-page/style.module.css +++ b/storybook/stories/design-system/patterns/settings-page/style.module.css @@ -28,19 +28,11 @@ inline-size: revert !important; } -/* `Page` sets `z-index: 1`, so overlays need their own layer above it. */ .screen { display: contents; } -/* - * The heading takes focus after navigation so screen readers announce the - * new page. It isn't interactive, so it shows no focus ring. - */ -.screen h1[tabindex="-1"]:focus { - outline: none; -} - +/* `Page` sets `z-index: 1`, so overlays need their own layer above it. */ .example > .overlays { flex: none; position: relative; From 3e627a3dc1eb4b4ae5b28f2b16d424b7df97fa4d Mon Sep 17 00:00:00 2001 From: James Koster Date: Thu, 12 Nov 2026 10:16:04 +0000 Subject: [PATCH 07/13] Storybook: Document Settings Page structure and add a sections example Explain when to use cards and how to plan headings: card titles are h2s on a page without sections, and h3s under an h2 section heading on the canvas. Add a Settings page with sections example. Co-authored-by: Cursor --- .../design-system/patterns/settings-page.mdx | 21 +++- .../patterns/settings-page.story.tsx | 6 + .../patterns/settings-page/sections.tsx | 90 +++++++++++++ .../patterns/settings-page/shared.tsx | 118 +++++++++++++++++- 4 files changed, 232 insertions(+), 3 deletions(-) create mode 100644 storybook/stories/design-system/patterns/settings-page/sections.tsx diff --git a/storybook/stories/design-system/patterns/settings-page.mdx b/storybook/stories/design-system/patterns/settings-page.mdx index fb1ab75ecbdff8..aeb92e7159a5ce 100644 --- a/storybook/stories/design-system/patterns/settings-page.mdx +++ b/storybook/stories/design-system/patterns/settings-page.mdx @@ -1,6 +1,7 @@ import { Canvas, Markdown, Meta } from '@storybook/addon-docs/blocks'; import * as SettingsPageStories from './settings-page.story'; import SimpleSource from './settings-page/simple.tsx?raw'; +import SectionsSource from './settings-page/sections.tsx?raw'; import AdjacentPagesSource from './settings-page/adjacent-pages.tsx?raw'; import SubpagesSource from './settings-page/subpages.tsx?raw'; import AdjacentPagesAndSubpagesSource from './settings-page/adjacent-pages-and-subpages.tsx?raw'; @@ -21,7 +22,7 @@ These templates are starting points, not requirements. Not every settings page n Every template uses the same parts: - **`Page`** from `@wordpress/admin-ui` provides the header: a title or breadcrumbs, optional section navigation, and the actions area where Save lives. -- **`Card`** from `@wordpress/ui` groups related settings. Give each card a short title, and a description when the title alone doesn't say what the settings affect. Cap form cards at `--wpds-dimension-surface-width-xl` so fields stay a readable length, and give tables of records `--wpds-dimension-surface-width-2xl` so their columns fit. +- **`Card`** from `@wordpress/ui` groups related settings. Give each card a short title, and a description when the title alone doesn't say what the settings affect. The Structure section below covers when to use one. Cap form cards at `--wpds-dimension-surface-width-xl` so fields stay a readable length, and give tables of records `--wpds-dimension-surface-width-2xl` so their columns fit. - **`DataForm`** from `@wordpress/dataviews` renders the fields, so labels, descriptions, validation and spacing stay consistent. - **`DataViews`** from `@wordpress/dataviews` lists records people can add and edit. - **`Dialog`**, **`Drawer`** and **`AlertDialog`** from `@wordpress/ui` hold record editors and confirmations. @@ -29,6 +30,15 @@ Every template uses the same parts: Each example's code shows its template. The helpers it imports, such as the manual-save draft, the sample fields and the in-canvas router, live alongside it in `storybook/stories/design-system/patterns/settings-page/`. +## Structure + +Plan a settings page like a document's outline before choosing how it looks. The headings decide how assistive technology reads the page and lets people jump through it, and the same kind of content should get the same treatment wherever it appears. + +- **Put each group of related fields in a card.** A card bounds a group and separates it from the groups around it. Keep the card even when a page has a single group, so every settings page reads the same way. +- **Title each card after its group of fields.** The page title is the `h1`, and on a page without sections the card titles are `h2`s. +- **Add sections when cards form larger groups.** A section heading sits on the canvas above its cards, as an `h2` with an optional description, and the cards inside it take `h3` titles. Use `Text` with `variant="heading-lg"` for the section heading. Each section gets its own heading, and a page with only a few cards needs none. +- **Don't skip heading levels**, and don't choose a level for its size. The level follows the structure, so a card title looks the same whether it's an `h2` or an `h3`. + ## Saving These templates use the manual save model from [Save & Submit](?path=/docs/design-system-patterns-save-submit--docs): edits are held in a draft until the user clicks Save. Autosave remains the preferred default when every field can be saved independently. If you adopt autosave, remove the Save button rather than mixing the two models on one page. @@ -57,6 +67,15 @@ A single page with a few groups of settings. Use it when everything fits on one source={ { code: SimpleSource, language: 'tsx', type: 'code' } } /> +## Settings page with sections + +A longer page whose cards fall into larger groups, here "Accepting payments" and "Payouts". Each section has an `h2` heading on the canvas, and its cards take `h3` titles. Use it when one page holds several distinct areas, but they are too closely related, or too small, to split into adjacent pages. + + + ## Adjacent pages Peer sections of one settings area, such as General, Payments and Emails, switched with the `Page` `navigation`. Use it when the sections are independent and each one is substantial enough to deserve a page. diff --git a/storybook/stories/design-system/patterns/settings-page.story.tsx b/storybook/stories/design-system/patterns/settings-page.story.tsx index 43981c81c9fab3..57ef1f8f5f452b 100644 --- a/storybook/stories/design-system/patterns/settings-page.story.tsx +++ b/storybook/stories/design-system/patterns/settings-page.story.tsx @@ -4,6 +4,7 @@ import { AdjacentPagesAndSubpagesExample } from './settings-page/adjacent-pages- import { RecordsDialogExample } from './settings-page/records-dialog'; import { RecordsDrawerExample } from './settings-page/records-drawer'; import { RecordsSubpageExample } from './settings-page/records-subpage'; +import { SectionsExample } from './settings-page/sections'; import { SimpleSettingsExample } from './settings-page/simple'; import { SubpagesExample } from './settings-page/subpages'; @@ -25,6 +26,11 @@ export const Simple: Story = { render: () => , }; +export const Sections: Story = { + name: 'Settings page with sections', + render: () => , +}; + export const AdjacentPages: Story = { name: 'Adjacent pages', render: () => , diff --git a/storybook/stories/design-system/patterns/settings-page/sections.tsx b/storybook/stories/design-system/patterns/settings-page/sections.tsx new file mode 100644 index 00000000000000..faeea7b248f1ce --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/sections.tsx @@ -0,0 +1,90 @@ +import { useState } from '@wordpress/element'; +import { Stack } from '@wordpress/ui'; +import { SettingsRouter } from './router'; +import { + bankStatementFields, + paymentOptionFields, + paymentsAndPayoutsSettings, + payoutNotificationFields, + payoutScheduleFields, + SettingsExample, + SettingsForm, + SettingsFormPage, + SettingsGroup, + SettingsSection, +} from './shared'; + +function SectionsPage() { + const [ saved, setSaved ] = useState( paymentsAndPayoutsSettings ); + + return ( + + { ( { data, onChange } ) => ( + + + + + + + + + + + + + + + + + + + ) } + + ); +} + +export function SectionsExample() { + return ( + + + + + + ); +} diff --git a/storybook/stories/design-system/patterns/settings-page/shared.tsx b/storybook/stories/design-system/patterns/settings-page/shared.tsx index f3506f75e69d0d..201cbdf7850e11 100644 --- a/storybook/stories/design-system/patterns/settings-page/shared.tsx +++ b/storybook/stories/design-system/patterns/settings-page/shared.tsx @@ -217,24 +217,28 @@ export function SettingsContent( { } /** - * A group of related settings in a card. + * A group of related settings in a card. Its title is an `h2`, or an `h3` + * when the card sits inside a `SettingsGroup`. */ export function SettingsSection( { title, titleId, + headingLevel = 2, description, children, }: { title: string; titleId?: string; + headingLevel?: 2 | 3; description?: string; children: ReactNode; } ) { + const Heading = headingLevel === 3 ? 'h3' : 'h2'; return ( - }> + }> { title } { description && ( @@ -252,6 +256,36 @@ export function SettingsSection( { ); } +/** + * A section of a page that holds several cards, with an `h2` heading on the + * canvas. The cards inside it take `h3` titles. + */ +export function SettingsGroup( { + title, + description, + children, +}: { + title: string; + description?: string; + children: ReactNode; +} ) { + return ( + + + }> + { title } + + { description && ( + + { description } + + ) } + + { children } + + ); +} + /** * A `DataForm` with the regular layout, bound to a manual-save draft. */ @@ -378,6 +412,86 @@ export const paymentFields: Field< PaymentSettings >[] = [ }, ]; +export type PaymentsAndPayoutsSettings = PaymentSettings & { + payoutSchedule: string; + minimumPayout: string; + notifyPayoutSent: boolean; + notifyPayoutFailed: boolean; +}; + +export const paymentsAndPayoutsSettings: PaymentsAndPayoutsSettings = { + ...paymentSettings, + payoutSchedule: 'weekly', + minimumPayout: '50', + notifyPayoutSent: true, + notifyPayoutFailed: true, +}; + +export const paymentOptionFields: Field< PaymentsAndPayoutsSettings >[] = [ + { + id: 'currency', + label: 'Currency', + type: 'text', + elements: [ + { value: 'usd', label: 'US dollar' }, + { value: 'gbp', label: 'Pound sterling' }, + { value: 'eur', label: 'Euro' }, + { value: 'jpy', label: 'Japanese yen' }, + ], + }, + { + id: 'testMode', + label: 'Use test mode', + type: 'boolean', + Edit: 'checkbox', + description: 'Process payments without charging customers.', + }, +]; + +export const bankStatementFields: Field< PaymentsAndPayoutsSettings >[] = [ + { + id: 'statementDescriptor', + label: 'Statement descriptor', + type: 'text', + description: 'Shown on customers’ bank statements.', + }, +]; + +export const payoutScheduleFields: Field< PaymentsAndPayoutsSettings >[] = [ + { + id: 'payoutSchedule', + label: 'Pay out', + type: 'text', + Edit: 'radio', + elements: [ + { value: 'daily', label: 'Daily' }, + { value: 'weekly', label: 'Weekly' }, + { value: 'monthly', label: 'Monthly' }, + ], + }, + { + id: 'minimumPayout', + label: 'Minimum payout amount', + type: 'text', + description: 'Balances below this amount roll over to the next payout.', + }, +]; + +export const payoutNotificationFields: Field< PaymentsAndPayoutsSettings >[] = [ + { + id: 'notifyPayoutSent', + label: 'Email me when a payout is sent', + type: 'boolean', + Edit: 'checkbox', + }, + { + id: 'notifyPayoutFailed', + label: 'Email me when a payout fails', + type: 'boolean', + Edit: 'checkbox', + }, +]; + export type GatewaySettings = { apiKey: string; webhookSecret: string; From 9ff2f093b606b15f8716027907249580d51986a7 Mon Sep 17 00:00:00 2001 From: James Koster Date: Thu, 12 Nov 2026 10:31:02 +0000 Subject: [PATCH 08/13] Storybook: Address Settings Page review feedback Keep Save enabled when fields are invalid and let form submission show the errors, keep editors open when the draft changes during a save, warn before unloading with an open dirty editor, add a failed save example, and move the unsaved changes guidance to the Save and submit pattern (#86725). Co-authored-by: Cursor --- .../patterns/save-and-submit.mdx | 5 - .../design-system/patterns/settings-page.mdx | 26 ++- .../patterns/settings-page.story.tsx | 6 + .../patterns/settings-page/api-keys.tsx | 95 ++++++++--- .../patterns/settings-page/failed-save.tsx | 66 ++++++++ .../patterns/settings-page/records-dialog.tsx | 47 ++++-- .../patterns/settings-page/records-drawer.tsx | 25 +-- .../patterns/settings-page/shared.tsx | 156 +++++++++++++----- .../patterns/settings-page/style.module.css | 8 + 9 files changed, 322 insertions(+), 112 deletions(-) create mode 100644 storybook/stories/design-system/patterns/settings-page/failed-save.tsx diff --git a/storybook/stories/design-system/patterns/save-and-submit.mdx b/storybook/stories/design-system/patterns/save-and-submit.mdx index a5b60027d8439b..62c95c8ea4f031 100644 --- a/storybook/stories/design-system/patterns/save-and-submit.mdx +++ b/storybook/stories/design-system/patterns/save-and-submit.mdx @@ -49,11 +49,6 @@ When all changes are saved, the Save button is disabled and can reveal a “No u If the user navigates away with unsaved edits, prompt them to confirm before leaving so their changes aren’t lost. This guard exists **only** in the manual save model; an autosave surface never needs it. -- **Only ask when something would be lost.** Prompt only while there are unsaved edits. Once the user saves, or changes a field back to its saved value, navigation is free again. -- **Inside the app, use an `AlertDialog`.** Hold the navigation (switching between adjacent pages, following a breadcrumb or opening a record) and ask “Discard unsaved changes?” with the `irreversible` intent. Offer two choices: “Keep editing”, which cancels the navigation and is the safe default, and “Discard changes”, which continues. Don’t add a “Save and leave” option: a save can fail validation, and the dialog is the wrong place to show that. -- **When leaving the app, rely on the browser.** Reloading, closing the tab or following an external link can only be guarded with the `beforeunload` event, which shows the browser’s own warning. Its wording can’t be customized, so don’t try to imitate it. -- **Dialogs and drawers that hold a draft close only through their actions.** Give them a footer with Cancel and Save, and omit the close icon and closing by clicking outside, so the user always makes an explicit choice. Cancel discards the draft without asking again, because choosing it is the decision. If the user presses Escape with unsaved edits, ask with the same dialog before closing. - ### Invalid fields, partial saves, and failed saves For automatic saving methods, an invalid field can require being addressed before saving, e.g. by outputting an error message right below the relevant input control. diff --git a/storybook/stories/design-system/patterns/settings-page.mdx b/storybook/stories/design-system/patterns/settings-page.mdx index aeb92e7159a5ce..1b6c91ec3e795f 100644 --- a/storybook/stories/design-system/patterns/settings-page.mdx +++ b/storybook/stories/design-system/patterns/settings-page.mdx @@ -2,6 +2,7 @@ import { Canvas, Markdown, Meta } from '@storybook/addon-docs/blocks'; import * as SettingsPageStories from './settings-page.story'; import SimpleSource from './settings-page/simple.tsx?raw'; import SectionsSource from './settings-page/sections.tsx?raw'; +import FailedSaveSource from './settings-page/failed-save.tsx?raw'; import AdjacentPagesSource from './settings-page/adjacent-pages.tsx?raw'; import SubpagesSource from './settings-page/subpages.tsx?raw'; import AdjacentPagesAndSubpagesSource from './settings-page/adjacent-pages-and-subpages.tsx?raw'; @@ -17,6 +18,8 @@ Templates for settings screens, composed from the admin-ui `Page`, `@wordpress/u These templates are starting points, not requirements. Not every settings page needs to match one exactly: adapt the structure to what your settings need, and combine or depart from the templates where that serves people better. +Several of the `@wordpress/ui` components they use, including `Button`, `ButtonLink`, `Dialog`, `Drawer` and `AlertDialog`, are still marked “Use with caution”, so their APIs may change. Treat the templates as the direction settings pages are heading, not as a recommendation to migrate existing screens yet. + ## Building blocks Every template uses the same parts: @@ -41,14 +44,25 @@ Plan a settings page like a document's outline before choosing how it looks. The ## Saving -These templates use the manual save model from [Save & Submit](?path=/docs/design-system-patterns-save-submit--docs): edits are held in a draft until the user clicks Save. Autosave remains the preferred default when every field can be saved independently. If you adopt autosave, remove the Save button rather than mixing the two models on one page. +These templates use the manual save model from [Save & Submit](?path=/docs/design-system-patterns-save-submit--docs), the usual choice for settings: edits are held in a draft until the user clicks “Save changes”. Autosave suits pages of independent preferences that each take effect on their own. If you adopt it, remove the Save button rather than mixing the two models on one page. -- **One Save per page**, in the `Page` header actions. It covers every field on that page and nothing else. -- **Disabled when there is nothing to save**, and busy while saving. -- **Checkboxes, not toggles, for on/off settings.** A toggle implies the change takes effect immediately, which isn't true until Save is clicked. Toggles belong on autosave surfaces. -- **A snackbar confirms the save.** Errors belong next to the field, or in a `Notice` when a save fails or only partly succeeds. +- **One “Save changes” button per page**, in the `Page` header actions. It covers every field on that page and nothing else. +- **Disabled only when there is nothing to save**, with a “No unsaved changes” tooltip, and busy while saving. +- **Invalid fields don't disable Save.** The fields sit in a `
`, and Save submits it: invalid fields show their errors below them and the first one takes focus, and nothing is saved until they're fixed. The record editors work the same way. +- **Edits made while saving stay unsaved.** People can keep typing while a save is in progress. Once it finishes, anything they changed in the meantime is still an unsaved change, and a record editor stays open to hold it. +- **Checkboxes, not switches, for on/off settings.** A switch implies the change takes effect immediately, which isn't true until Save is clicked. Switches belong on autosave surfaces. +- **A snackbar confirms the save.** Errors belong next to the field, or in a `Notice` at the top of the form when a save fails or only partly succeeds. - **Pages that only list records have no page-level Save.** Each record editor saves on its own, and the header holds the action that adds a record. -- **Leaving with unsaved edits asks first.** Switching pages or following a breadcrumb holds the navigation and asks “Discard unsaved changes?”, and reloading or closing the tab shows the browser’s own warning. Try it in any template by changing a field, then navigating away. See [Unsaved changes on exit](?path=/docs/design-system-patterns-save-submit--docs#unsaved-changes-on-exit). +- **Leaving with unsaved edits asks first.** Switching pages, following a breadcrumb or closing a record editor with Escape asks “Discard unsaved changes?”, and reloading or closing the tab shows the browser’s own warning. Try it in any template by changing a field, then navigating away. See [Unsaved changes on exit](?path=/docs/design-system-patterns-save-submit--docs#unsaved-changes-on-exit). + +### When a save fails + +Keep the draft, so nothing the user entered is lost, and explain the failure in a `Notice` at the top of the form with a “Try again” action. Retrying submits the form again, so validation runs first. In this example the first save fails: change a field, click “Save changes”, then try again. + + ## Focus after navigation diff --git a/storybook/stories/design-system/patterns/settings-page.story.tsx b/storybook/stories/design-system/patterns/settings-page.story.tsx index 57ef1f8f5f452b..608a54230a51c1 100644 --- a/storybook/stories/design-system/patterns/settings-page.story.tsx +++ b/storybook/stories/design-system/patterns/settings-page.story.tsx @@ -1,6 +1,7 @@ import type { Meta, StoryObj } from '@storybook/react-vite'; import { AdjacentPagesExample } from './settings-page/adjacent-pages'; import { AdjacentPagesAndSubpagesExample } from './settings-page/adjacent-pages-and-subpages'; +import { FailedSaveExample } from './settings-page/failed-save'; import { RecordsDialogExample } from './settings-page/records-dialog'; import { RecordsDrawerExample } from './settings-page/records-drawer'; import { RecordsSubpageExample } from './settings-page/records-subpage'; @@ -26,6 +27,11 @@ export const Simple: Story = { render: () => , }; +export const FailedSave: Story = { + name: 'Failed save', + render: () => , +}; + export const Sections: Story = { name: 'Settings page with sections', render: () => , diff --git a/storybook/stories/design-system/patterns/settings-page/api-keys.tsx b/storybook/stories/design-system/patterns/settings-page/api-keys.tsx index e96b0df30a33ed..3c7c71d29763d2 100644 --- a/storybook/stories/design-system/patterns/settings-page/api-keys.tsx +++ b/storybook/stories/design-system/patterns/settings-page/api-keys.tsx @@ -1,4 +1,4 @@ -import type { ComponentProps, ReactElement } from 'react'; +import type { ComponentProps, FormEvent, ReactElement } from 'react'; import type { Action, Field, View } from '@wordpress/dataviews'; import { DataForm, @@ -6,7 +6,13 @@ import { filterSortAndPaginate, useFormValidity, } from '@wordpress/dataviews'; -import { useMemo, useState } from '@wordpress/element'; +import { + useEffect, + useId, + useMemo, + useRef, + useState, +} from '@wordpress/element'; import { Badge, Card } from '@wordpress/ui'; import { simulateRequest, useNotify } from './shared'; @@ -167,16 +173,22 @@ export function KeyForm( { /** * State for editing one record in an overlay. The overlay saves on its own: - * its Save applies the draft, closes the overlay and confirms in a snackbar. + * its Save submits the form, which applies the draft, closes the overlay and + * confirms in a snackbar. Invalid fields stop the submission and show their + * errors instead. */ -export function useKeyEditor( onSave: ( key: ApiKey ) => void ) { +export function useKeyEditor( onSave: ( key: ApiKey ) => ApiKey ) { const [ isOpen, setIsOpen ] = useState( false ); // The record stays set after closing, so the overlay keeps its content // while it animates out. const [ record, setRecord ] = useState< ApiKey >( emptyKey ); const [ draft, setDraft ] = useState< ApiKey >( emptyKey ); const [ isSaving, setIsSaving ] = useState( false ); - const { isValid } = useFormValidity( draft, keyFormFields, keyForm ); + const draftRef = useRef( draft ); + useEffect( () => { + draftRef.current = draft; + }, [ draft ] ); + const formId = useId(); const notify = useNotify(); const open = ( key: ApiKey ) => { @@ -197,6 +209,20 @@ export function useKeyEditor( onSave: ( key: ApiKey ) => void ) { const isDirty = JSON.stringify( draft ) !== JSON.stringify( record ); const [ isConfirmingDiscard, setIsConfirmingDiscard ] = useState( false ); + // Reloading or closing the tab can only be guarded by the browser's own + // warning. + const shouldWarnOnUnload = isOpen && isDirty; + useEffect( () => { + if ( ! shouldWarnOnUnload ) { + return; + } + const onBeforeUnload = ( event: BeforeUnloadEvent ) => + event.preventDefault(); + window.addEventListener( 'beforeunload', onBeforeUnload ); + return () => + window.removeEventListener( 'beforeunload', onBeforeUnload ); + }, [ shouldWarnOnUnload ] ); + /** * Cancel is an explicit choice to discard the draft. Any other way of * closing (Escape, or swiping a drawer) asks first when there are @@ -226,12 +252,28 @@ export function useKeyEditor( onSave: ( key: ApiKey ) => void ) { }; const save = async () => { + const submitted = draft; setIsSaving( true ); await simulateRequest(); - onSave( draft ); + const saved = onSave( submitted ); setIsSaving( false ); - setIsOpen( false ); notify( 'API key saved.' ); + // Edits made while the save was pending stay open as unsaved changes, + // on top of the record that was just saved. + const latest = draftRef.current; + if ( JSON.stringify( latest ) === JSON.stringify( submitted ) ) { + setIsOpen( false ); + } else { + setRecord( saved ); + setDraft( { ...latest, id: saved.id, prefix: saved.prefix } ); + } + }; + + const onSubmit = ( event: FormEvent ) => { + event.preventDefault(); + if ( ! isSaving ) { + save(); + } }; return { @@ -241,8 +283,9 @@ export function useKeyEditor( onSave: ( key: ApiKey ) => void ) { draft, onChange, isDirty, - isValid, isSaving, + formId, + onSubmit, open, close, onOpenChange, @@ -257,23 +300,25 @@ export function useKeyEditor( onSave: ( key: ApiKey ) => void ) { export function useKeys() { const [ keys, setKeys ] = useState( initialKeys ); - const saveKey = ( key: ApiKey ) => { - setKeys( ( current ) => { - if ( key.id && current.some( ( { id } ) => id === key.id ) ) { - return current.map( ( item ) => - item.id === key.id ? key : item - ); - } - const suffix = Date.now().toString( 16 ).slice( -4 ); - return [ - ...current, - { - ...key, - id: `key-${ suffix }`, - prefix: `wp_live_${ suffix }`, - }, - ]; - } ); + /** + * Applies a record and returns it as saved, with an id and key when it + * is new. + */ + const saveKey = ( key: ApiKey ): ApiKey => { + if ( key.id ) { + setKeys( ( current ) => + current.map( ( item ) => ( item.id === key.id ? key : item ) ) + ); + return key; + } + const suffix = Date.now().toString( 16 ).slice( -4 ); + const saved = { + ...key, + id: `key-${ suffix }`, + prefix: `wp_live_${ suffix }`, + }; + setKeys( ( current ) => [ ...current, saved ] ); + return saved; }; const revokeKey = ( key: ApiKey ) => { diff --git a/storybook/stories/design-system/patterns/settings-page/failed-save.tsx b/storybook/stories/design-system/patterns/settings-page/failed-save.tsx new file mode 100644 index 00000000000000..c0cd4bab1d11f9 --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/failed-save.tsx @@ -0,0 +1,66 @@ +import { useRef, useState } from '@wordpress/element'; +import type { GeneralSettings } from './shared'; +import { SettingsRouter } from './router'; +import { + checkoutFields, + generalFields, + generalSettings, + SettingsExample, + SettingsForm, + SettingsFormPage, + SettingsSection, +} from './shared'; + +function FailedSavePage() { + const [ saved, setSaved ] = useState( generalSettings ); + // The first save fails, so the example can show the retry. + const hasFailedRef = useRef( false ); + + const save = async ( data: GeneralSettings ) => { + if ( ! hasFailedRef.current ) { + hasFailedRef.current = true; + throw new Error( 'The request failed.' ); + } + setSaved( data ); + }; + + return ( + + { ( { data, onChange } ) => ( + <> + + + + + + + + ) } + + ); +} + +/** + * A page whose first save fails. The draft is kept, a notice at the top of + * the form explains what happened, and "Try again" submits the form again. + */ +export function FailedSaveExample() { + return ( + + + + + + ); +} diff --git a/storybook/stories/design-system/patterns/settings-page/records-dialog.tsx b/storybook/stories/design-system/patterns/settings-page/records-dialog.tsx index 9cbbaacf4210de..b9573ef6e82a2a 100644 --- a/storybook/stories/design-system/patterns/settings-page/records-dialog.tsx +++ b/storybook/stories/design-system/patterns/settings-page/records-dialog.tsx @@ -11,6 +11,7 @@ import { useKeys, } from './api-keys'; import { + SaveButton, SettingsContent, SettingsExample, useOverlayContainer, @@ -19,7 +20,7 @@ import { DiscardChangesDialog } from './unsaved-changes'; /** * Edits one record in a dialog. People leave through Cancel, which discards - * the draft, or Save, which applies it; there is no close button and + * the draft, or Save changes, which applies it; there is no close button and * clicking outside does nothing, so the choice is always explicit. */ export function KeyDialog( { @@ -47,10 +48,12 @@ export function KeyDialog( { - + + + Cancel - + @@ -84,6 +76,27 @@ export function KeyDialog( { ); } +/** + * Submits a record editor. A new record has nothing to compare against, so + * its button stays enabled, and submitting an empty form explains what's + * missing. + */ +export function KeySaveButton( { + editor, +}: { + editor: ReturnType< typeof useKeyEditor >; +} ) { + return ( + + { editor.isNew ? 'Add API key' : 'Save changes' } + + ); +} + export function AddKeyButton( { onClick }: { onClick: () => void } ) { return ( + diff --git a/storybook/stories/design-system/patterns/settings-page/shared.tsx b/storybook/stories/design-system/patterns/settings-page/shared.tsx index 201cbdf7850e11..bd5eae38c425fa 100644 --- a/storybook/stories/design-system/patterns/settings-page/shared.tsx +++ b/storybook/stories/design-system/patterns/settings-page/shared.tsx @@ -3,15 +3,16 @@ import type { ComponentProps, ReactNode } from 'react'; import { Page } from '@wordpress/admin-ui'; import { SnackbarList } from '@wordpress/components'; import type { Field } from '@wordpress/dataviews'; -import { DataForm } from '@wordpress/dataviews'; +import { DataForm, useFormValidity } from '@wordpress/dataviews'; import { createContext, useCallback, useContext, + useId, useRef, useState, } from '@wordpress/element'; -import { Button, Card, Stack, Text } from '@wordpress/ui'; +import { Button, Card, Notice, Stack, Text, Tooltip } from '@wordpress/ui'; import type { SubpageStatus } from './router'; import styles from './style.module.css'; import { UnsavedChangesGuard } from './unsaved-changes'; @@ -88,15 +89,17 @@ export function SettingsExample( { children }: { children: ReactNode } ) { /** * Manual save model: edits are held in a local draft and applied together * when the user saves. The saved value lives above the page, so it survives - * navigating between pages. + * navigating between pages. A save that fails keeps the draft, so people can + * try again. Edits made while a save is pending stay in the draft, unsaved. */ export function useManualSave< T extends object >( saved: T, - onSave: ( data: T ) => void, + onSave: ( data: T ) => unknown, message = 'Settings saved.' ) { const [ data, setData ] = useState( saved ); const [ isSaving, setIsSaving ] = useState( false ); + const [ hasFailed, setHasFailed ] = useState( false ); const notify = useNotify(); const isDirty = JSON.stringify( data ) !== JSON.stringify( saved ); @@ -107,39 +110,88 @@ export function useManualSave< T extends object >( const save = async () => { setIsSaving( true ); - await simulateRequest(); - onSave( data ); + setHasFailed( false ); + try { + await simulateRequest(); + await onSave( data ); + notify( message ); + } catch { + setHasFailed( true ); + } setIsSaving( false ); - notify( message ); }; - return { data, onChange, isDirty, isSaving, save }; + return { data, onChange, isDirty, isSaving, hasFailed, save }; } /** - * The page-level Save, placed in the `Page` header actions. It is disabled - * while there is nothing to save and shows a busy state while saving. + * Submits the form it belongs to, so the form's own validation runs first: + * invalid fields show their errors and take focus instead of saving. It stays + * enabled while fields are invalid, and is only disabled while there is + * nothing to save, which its tooltip explains, or while saving. */ export function SaveButton( { - isDirty, + form, + hasChanges, isSaving, - onClick, + size, + children = 'Save changes', }: { - isDirty: boolean; + form: string; + hasChanges: boolean; isSaving: boolean; - onClick: () => void; + size?: ComponentProps< typeof Button >[ 'size' ]; + children?: ReactNode; } ) { return ( - + + + { children } + + } + /> + No unsaved changes + + ); +} + +/** + * Explains a failed save at the top of the form and offers a retry. The list + * stays mounted so the notice is announced when it appears. + */ +export function SaveFailedNotice( { + hasFailed, + onRetry, +}: { + hasFailed: boolean; + onRetry: () => void; +} ) { + return ( + + { hasFailed && ( + + Your changes couldn’t be saved. + + They’re still here. Check your connection, then try + again. + + + + Try again + + + + ) } + ); } @@ -149,10 +201,11 @@ type PageHeaderProps = Omit< >; /** - * A settings page (or subpage) that owns one manual-save draft, with its - * Save in the `Page` header actions. Render it with a `key` per location, - * so each page starts from its saved values, and inside a router, which the - * unsaved changes guard uses to hold navigation. + * A settings page (or subpage) that owns one manual-save draft. Its fields + * sit in a form, which the Save in the `Page` header actions submits. Render + * it with a `key` per location, so each page starts from its saved values, + * and inside a router, which the unsaved changes guard uses to hold + * navigation. */ export function SettingsFormPage< T extends object >( { saved, @@ -161,16 +214,16 @@ export function SettingsFormPage< T extends object >( { ...pageProps }: PageHeaderProps & { saved: T; - onSave: ( data: T ) => void; + onSave: ( data: T ) => unknown; children: ( form: { data: T; onChange: ( edits: Partial< T > ) => void; } ) => ReactNode; } ) { - const { data, onChange, isDirty, isSaving, save } = useManualSave( - saved, - onSave - ); + const { data, onChange, isDirty, isSaving, hasFailed, save } = + useManualSave( saved, onSave ); + const formId = useId(); + const formRef = useRef< HTMLFormElement >( null ); return ( ( { { ...pageProps } actions={ } > - - { children( { data, onChange } ) } - +
{ + event.preventDefault(); + if ( isDirty && ! isSaving ) { + save(); + } + } } + > + + formRef.current?.requestSubmit() } + /> + { children( { data, onChange } ) } + +
); @@ -298,14 +367,17 @@ export function SettingsForm< T extends object >( { fields: Field< T >[]; onChange: ( edits: Partial< T > ) => void; } ) { + const form = { + layout: { type: 'regular' as const }, + fields: fields.map( ( field ) => field.id ), + }; + const { validity } = useFormValidity( data, fields, form ); return ( data={ data } fields={ fields } - form={ { - layout: { type: 'regular' }, - fields: fields.map( ( field ) => field.id ), - } } + form={ form } + validity={ validity } onChange={ ( edits ) => onChange( edits as Partial< T > ) } /> ); diff --git a/storybook/stories/design-system/patterns/settings-page/style.module.css b/storybook/stories/design-system/patterns/settings-page/style.module.css index f0006bfd915e4a..87fcc7fad638cc 100644 --- a/storybook/stories/design-system/patterns/settings-page/style.module.css +++ b/storybook/stories/design-system/patterns/settings-page/style.module.css @@ -49,6 +49,14 @@ margin-inline: auto; } +/* + * The notice list stays mounted so it can announce a failed save. Its notices + * join the content stack, so the empty list adds no gap. + */ +.content > .notices { + display: contents; +} + .description { color: var(--wpds-color-foreground-content-neutral-weak); } From 77b302dc9f1315e32e00355c5922b80f46a2f8b8 Mon Sep 17 00:00:00 2001 From: James Koster Date: Fri, 13 Nov 2026 15:54:15 +0000 Subject: [PATCH 09/13] Storybook: Address further Settings Page review feedback Hold navigation until a pending save settles, clear the failed save notice once there's nothing to retry, name each adjacent page's region, drop the disabled Save tooltip, and describe focus restoration as something the example provides until #86701 lands. Co-authored-by: Cursor --- .../design-system/patterns/settings-page.mdx | 8 ++-- .../patterns/settings-page/router.tsx | 2 +- .../patterns/settings-page/shared.tsx | 38 +++++++++---------- .../patterns/settings-page/store-pages.tsx | 12 +++++- .../settings-page/unsaved-changes.tsx | 21 ++++++++-- 5 files changed, 52 insertions(+), 29 deletions(-) diff --git a/storybook/stories/design-system/patterns/settings-page.mdx b/storybook/stories/design-system/patterns/settings-page.mdx index 1b6c91ec3e795f..b9417bab78369a 100644 --- a/storybook/stories/design-system/patterns/settings-page.mdx +++ b/storybook/stories/design-system/patterns/settings-page.mdx @@ -47,13 +47,13 @@ Plan a settings page like a document's outline before choosing how it looks. The These templates use the manual save model from [Save & Submit](?path=/docs/design-system-patterns-save-submit--docs), the usual choice for settings: edits are held in a draft until the user clicks “Save changes”. Autosave suits pages of independent preferences that each take effect on their own. If you adopt it, remove the Save button rather than mixing the two models on one page. - **One “Save changes” button per page**, in the `Page` header actions. It covers every field on that page and nothing else. -- **Disabled only when there is nothing to save**, with a “No unsaved changes” tooltip, and busy while saving. +- **Disabled only when there is nothing to save**, and busy while saving. Don't explain the disabled state with a tooltip: tooltips aren't available to screen readers or on touch devices. - **Invalid fields don't disable Save.** The fields sit in a `
`, and Save submits it: invalid fields show their errors below them and the first one takes focus, and nothing is saved until they're fixed. The record editors work the same way. - **Edits made while saving stay unsaved.** People can keep typing while a save is in progress. Once it finishes, anything they changed in the meantime is still an unsaved change, and a record editor stays open to hold it. - **Checkboxes, not switches, for on/off settings.** A switch implies the change takes effect immediately, which isn't true until Save is clicked. Switches belong on autosave surfaces. - **A snackbar confirms the save.** Errors belong next to the field, or in a `Notice` at the top of the form when a save fails or only partly succeeds. - **Pages that only list records have no page-level Save.** Each record editor saves on its own, and the header holds the action that adds a record. -- **Leaving with unsaved edits asks first.** Switching pages, following a breadcrumb or closing a record editor with Escape asks “Discard unsaved changes?”, and reloading or closing the tab shows the browser’s own warning. Try it in any template by changing a field, then navigating away. See [Unsaved changes on exit](?path=/docs/design-system-patterns-save-submit--docs#unsaved-changes-on-exit). +- **Leaving with unsaved edits asks first.** Switching pages, following a breadcrumb or closing a record editor with Escape asks “Discard unsaved changes?”, and reloading or closing the tab shows the browser’s own warning. Navigating while a save is in progress waits for it to finish, then asks only if something changed after clicking Save. Try it in any template by changing a field, then navigating away. See [Unsaved changes on exit](?path=/docs/design-system-patterns-save-submit--docs#unsaved-changes-on-exit). ### When a save fails @@ -68,9 +68,9 @@ Keep the draft, so nothing the user entered is lost, and explain the failure in Moving between adjacent pages and subpages replaces the page, including the link that was just used. Without help, keyboard focus falls back to the start of the document and screen readers don't announce the new page. -Admin pages built on `@wordpress/boot` handle this for you: when a navigation removes the focused element, focus moves to the new page's `Page` region, and screen readers announce it by name. The region takes its name from `title`, so a subpage whose breadcrumbs replace the title needs an `ariaLabel` naming the page, such as "Card payments". Don't move focus yourself on those pages. If your app routes without `@wordpress/boot`, do the same after each navigation that loses focus. +The templates' in-canvas router handles this: when a navigation removes the focused element, focus moves to the new page's `Page` region, and screen readers announce it by name. Try it by following a breadcrumb with the keyboard. `@wordpress/boot` currently updates and announces the route title, and will move focus the same way once [#86701](https://github.com/WordPress/gutenberg/pull/86701) lands. Until then, or if your app routes without `@wordpress/boot`, move focus to the `Page` region yourself after each navigation that loses focus. -The templates' in-canvas router follows the same behavior. Try it by following a breadcrumb with the keyboard. +The region takes its name from `title`, so give it an `ariaLabel` whenever the title doesn't identify the page: on a subpage whose breadcrumbs replace the title, name it after the page, such as “Card payments”. On adjacent pages that share a title, name each one after its page, such as “Payments settings”. ## Simple settings page diff --git a/storybook/stories/design-system/patterns/settings-page/router.tsx b/storybook/stories/design-system/patterns/settings-page/router.tsx index b27f379e2fe780..5b3480f3437174 100644 --- a/storybook/stories/design-system/patterns/settings-page/router.tsx +++ b/storybook/stories/design-system/patterns/settings-page/router.tsx @@ -138,7 +138,7 @@ const ScreenContext = createContext< ReactNode >( null ); /** * Moves focus to the new `Page` region when a navigation removes the focused - * link, as `@wordpress/boot` does for admin pages. Focus would otherwise fall + * link, as `@wordpress/boot` will once #86701 lands. Focus would otherwise fall * back to the document, and screen readers wouldn't announce the new page. */ function useFocusAfterNavigate() { diff --git a/storybook/stories/design-system/patterns/settings-page/shared.tsx b/storybook/stories/design-system/patterns/settings-page/shared.tsx index bd5eae38c425fa..7a7496922c7438 100644 --- a/storybook/stories/design-system/patterns/settings-page/shared.tsx +++ b/storybook/stories/design-system/patterns/settings-page/shared.tsx @@ -12,7 +12,7 @@ import { useRef, useState, } from '@wordpress/element'; -import { Button, Card, Notice, Stack, Text, Tooltip } from '@wordpress/ui'; +import { Button, Card, Notice, Stack, Text } from '@wordpress/ui'; import type { SubpageStatus } from './router'; import styles from './style.module.css'; import { UnsavedChangesGuard } from './unsaved-changes'; @@ -104,6 +104,11 @@ export function useManualSave< T extends object >( const isDirty = JSON.stringify( data ) !== JSON.stringify( saved ); + // Once the draft matches what's saved, there's nothing left to retry. + if ( hasFailed && ! isDirty ) { + setHasFailed( false ); + } + const onChange = useCallback( ( edits: Partial< T > ) => { setData( ( previous ) => ( { ...previous, ...edits } ) ); }, [] ); @@ -128,7 +133,7 @@ export function useManualSave< T extends object >( * Submits the form it belongs to, so the form's own validation runs first: * invalid fields show their errors and take focus instead of saving. It stays * enabled while fields are invalid, and is only disabled while there is - * nothing to save, which its tooltip explains, or while saving. + * nothing to save or while saving. */ export function SaveButton( { form, @@ -144,23 +149,16 @@ export function SaveButton( { children?: ReactNode; } ) { return ( - - - { children } - - } - /> - No unsaved changes - + ); } @@ -257,7 +255,7 @@ export function SettingsFormPage< T extends object >( { { children( { data, onChange } ) }
- + ); } diff --git a/storybook/stories/design-system/patterns/settings-page/store-pages.tsx b/storybook/stories/design-system/patterns/settings-page/store-pages.tsx index 140c27c71460bb..fe9dce5ee80088 100644 --- a/storybook/stories/design-system/patterns/settings-page/store-pages.tsx +++ b/storybook/stories/design-system/patterns/settings-page/store-pages.tsx @@ -29,6 +29,14 @@ export const ADJACENT_PAGES = [ { label: 'Emails', href: '/emails' }, ]; +// Adjacent pages share the visible "Settings" title, so each page region +// needs its own name for screen readers to identify the destination. +const ADJACENT_PAGE_REGION_LABELS: Record< string, string > = { + '/general': 'General settings', + '/payments': 'Payments settings', + '/emails': 'Email settings', +}; + /** * The saved values for every page, held above the router so they survive * navigation. @@ -86,11 +94,13 @@ export const SETTINGS_CRUMB = { /** * Header props for a page that sits among adjacent pages. The title names - * the area, and the navigation shows which page is current. + * the area, the navigation shows which page is current, and the region's + * label names the page itself. */ export function adjacentPageHeader( currentHref: string ): HeaderProps { return { title: 'Settings', + ariaLabel: ADJACENT_PAGE_REGION_LABELS[ currentHref ], navigation: { items: ADJACENT_PAGES, currentHref }, components: { link: RouterNavLink }, }; diff --git a/storybook/stories/design-system/patterns/settings-page/unsaved-changes.tsx b/storybook/stories/design-system/patterns/settings-page/unsaved-changes.tsx index 337a10209da03b..b8ec4d7608e46a 100644 --- a/storybook/stories/design-system/patterns/settings-page/unsaved-changes.tsx +++ b/storybook/stories/design-system/patterns/settings-page/unsaved-changes.tsx @@ -52,12 +52,27 @@ export function DiscardChangesDialog( { /** * Guards a manual-save page: navigating away with unsaved edits asks first. + * Navigating during a save waits for it to settle, then asks only if the + * draft still differs from what was saved. */ -export function UnsavedChangesGuard( { isDirty }: { isDirty: boolean } ) { - const blocker = useNavigationBlocker( isDirty ); +export function UnsavedChangesGuard( { + isDirty, + isSaving, +}: { + isDirty: boolean; + isSaving: boolean; +} ) { + const blocker = useNavigationBlocker( isDirty || isSaving ); + const isBlocked = blocker.status === 'blocked'; + const shouldProceed = isBlocked && ! isSaving && ! isDirty; + useEffect( () => { + if ( shouldProceed ) { + blocker.proceed?.(); + } + }, [ shouldProceed, blocker ] ); return ( blocker.reset?.() } onDiscard={ () => blocker.proceed?.() } /> From ab36e8366e3e7085438464205cefa041f949c55b Mon Sep 17 00:00:00 2001 From: James Koster Date: Mon, 16 Nov 2026 10:18:40 +0000 Subject: [PATCH 10/13] Storybook: Move focus after revoking an API key After a key is revoked, focus the next record, the previous one when it was last, or Add API key when the list is empty. Canceling the confirmation still returns focus to Revoke. Co-authored-by: Cursor --- .../design-system/patterns/settings-page.mdx | 2 +- .../patterns/settings-page/records-dialog.tsx | 16 ++- .../patterns/settings-page/records-drawer.tsx | 101 ++++++++++++++---- 3 files changed, 98 insertions(+), 21 deletions(-) diff --git a/storybook/stories/design-system/patterns/settings-page.mdx b/storybook/stories/design-system/patterns/settings-page.mdx index b9417bab78369a..ca985130d26720 100644 --- a/storybook/stories/design-system/patterns/settings-page.mdx +++ b/storybook/stories/design-system/patterns/settings-page.mdx @@ -163,7 +163,7 @@ The footer actions are the only way out: there is no close icon, and clicking ou ### Records that open a drawer -The drawer works like the dialog, including closing only through its footer actions, with room for secondary actions. Revoking a key can't be undone, so it asks for confirmation in an `AlertDialog` with the `irreversible` intent, following [Destructive Actions](?path=/docs/design-system-patterns-destructive-actions--docs). +The drawer works like the dialog, including closing only through its footer actions, with room for secondary actions. Revoking a key can't be undone, so it asks for confirmation in an `AlertDialog` with the `irreversible` intent, following [Destructive Actions](?path=/docs/design-system-patterns-destructive-actions--docs). Canceling returns focus to Revoke. After the key is revoked, focus moves to the next record, or to the previous one when it was last, and to Add API key when none remain. void } ) { +export function AddKeyButton( { + onClick, + buttonRef, +}: { + onClick: () => void; + buttonRef?: Ref< HTMLButtonElement >; +} ) { return ( - ); diff --git a/storybook/stories/design-system/patterns/settings-page/records-drawer.tsx b/storybook/stories/design-system/patterns/settings-page/records-drawer.tsx index f1cd422563fc7a..eb8910c95d8d82 100644 --- a/storybook/stories/design-system/patterns/settings-page/records-drawer.tsx +++ b/storybook/stories/design-system/patterns/settings-page/records-drawer.tsx @@ -23,6 +23,34 @@ import { import styles from './style.module.css'; import { DiscardChangesDialog } from './unsaved-changes'; +/** + * Where focus should land once a revoked record and its drawer are gone: + * the next record, the previous one when it was last, or Add API key when + * the list is empty. Captured before the record is removed, so the element + * is still the one that remains. + */ +function focusTargetAfterRevoke( + name: string, + scope: ParentNode | null, + addButton: HTMLElement | null +) { + const root = scope ?? document; + const titles = [ + ...root.querySelectorAll< HTMLElement >( + '.dataviews-title-field[role="button"]' + ), + ]; + const index = titles.findIndex( + ( title ) => title.textContent?.trim() === name + ); + // `titles[-1]` is undefined, so the first record falls through to the next. + const remaining = titles[ index + 1 ] ?? titles[ index - 1 ]; + if ( index !== -1 && remaining ) { + return remaining; + } + return addButton; +} + /** * Edits one record in a drawer, which keeps the table in view and leaves * room for secondary actions. Like the dialog, it closes only through its @@ -32,20 +60,42 @@ import { DiscardChangesDialog } from './unsaved-changes'; function KeyDrawer( { editor, onRevoke, + pageRef, + addButtonRef, }: { editor: ReturnType< typeof useKeyEditor >; onRevoke: ( key: ApiKey ) => void; + pageRef: { current: HTMLElement | null }; + addButtonRef: { current: HTMLElement | null }; } ) { const [ isConfirmingRevoke, setIsConfirmingRevoke ] = useState( false ); const revokeButtonRef = useRef< HTMLButtonElement >( null ); + // Set only for a revoke that succeeded, so canceling still returns to + // Revoke while closing the drawer focuses whatever remains. + const revokedFocusRef = useRef< HTMLElement | null >( null ); const notify = useNotify(); const overlayContainer = useOverlayContainer(); const revokeKey = async () => { await simulateRequest(); + const target = focusTargetAfterRevoke( + editor.record.name, + pageRef.current, + addButtonRef.current + ); + // Read by the dialog and drawer as they close. Cleared afterwards so + // a later close returns focus normally. + revokedFocusRef.current = target; onRevoke( editor.record ); editor.close(); notify( 'API key revoked.' ); + // Both overlays restore focus while closing, and the record they + // opened from is gone by then. Place focus once that has settled, + // then drop the target so the next close behaves normally. + window.setTimeout( () => target?.focus(), 50 ); + window.setTimeout( () => { + revokedFocusRef.current = null; + }, 300 ); }; // The alert dialogs sit outside `Drawer.Root`: Base UI doesn't render a @@ -61,6 +111,7 @@ function KeyDrawer( { > } + finalFocus={ () => revokedFocusRef.current ?? true } > @@ -108,7 +159,9 @@ function KeyDrawer( { portal={ } - finalFocus={ revokeButtonRef } + finalFocus={ () => + revokedFocusRef.current ?? revokeButtonRef.current + } intent="irreversible" title={ `Revoke “${ editor.record.name }”?` } description="Apps using this key will lose access immediately. This can’t be undone." @@ -127,6 +180,8 @@ function KeyDrawer( { function RecordsDrawerPage() { const { keys, saveKey, revokeKey } = useKeys(); const editor = useKeyEditor( saveKey ); + const pageRef = useRef< HTMLDivElement >( null ); + const addButtonRef = useRef< HTMLButtonElement >( null ); const actions: Action< ApiKey >[] = [ { id: 'edit', @@ -138,24 +193,34 @@ function RecordsDrawerPage() { ]; return ( - editor.open( emptyKey ) } /> - } - > - - + editor.open( emptyKey ) } + /> + } + > + + + + - - - + +
); } From 710046bf6dae575d233fb051788154b275dc8047 Mon Sep 17 00:00:00 2001 From: James Koster Date: Mon, 16 Nov 2026 17:23:45 +0000 Subject: [PATCH 11/13] Storybook: Find the revoked API key's row by ID After revoking a key from the drawer, focus moves to a neighbouring row. The row was found by name, so when two keys shared a name it could pick the row being removed and focus fell to the document body. Mark each row with its record ID and match on that instead. Co-Authored-By: Claude Opus 5.5 --- .../design-system/patterns/settings-page/api-keys.tsx | 5 +++++ .../patterns/settings-page/records-drawer.tsx | 11 +++++++---- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/storybook/stories/design-system/patterns/settings-page/api-keys.tsx b/storybook/stories/design-system/patterns/settings-page/api-keys.tsx index 3c7c71d29763d2..b2cb2abdea2ace 100644 --- a/storybook/stories/design-system/patterns/settings-page/api-keys.tsx +++ b/storybook/stories/design-system/patterns/settings-page/api-keys.tsx @@ -86,6 +86,11 @@ export const keyFields: Field< ApiKey >[] = [ id: 'name', label: 'Name', type: 'text', + // Marks each row with its record, so a pattern can find the row for a + // record by ID rather than by name, which needn't be unique. + render: ( { item } ) => ( + { item.name } + ), enableHiding: false, isValid: { required: true }, }, diff --git a/storybook/stories/design-system/patterns/settings-page/records-drawer.tsx b/storybook/stories/design-system/patterns/settings-page/records-drawer.tsx index eb8910c95d8d82..4ad2f63f73b66a 100644 --- a/storybook/stories/design-system/patterns/settings-page/records-drawer.tsx +++ b/storybook/stories/design-system/patterns/settings-page/records-drawer.tsx @@ -27,10 +27,11 @@ import { DiscardChangesDialog } from './unsaved-changes'; * Where focus should land once a revoked record and its drawer are gone: * the next record, the previous one when it was last, or Add API key when * the list is empty. Captured before the record is removed, so the element - * is still the one that remains. + * is still the one that remains. Rows are matched by record ID, since two + * records can share a name. */ function focusTargetAfterRevoke( - name: string, + id: string, scope: ParentNode | null, addButton: HTMLElement | null ) { @@ -41,7 +42,9 @@ function focusTargetAfterRevoke( ), ]; const index = titles.findIndex( - ( title ) => title.textContent?.trim() === name + ( title ) => + title.querySelector< HTMLElement >( '[data-key-id]' )?.dataset + .keyId === id ); // `titles[-1]` is undefined, so the first record falls through to the next. const remaining = titles[ index + 1 ] ?? titles[ index - 1 ]; @@ -79,7 +82,7 @@ function KeyDrawer( { const revokeKey = async () => { await simulateRequest(); const target = focusTargetAfterRevoke( - editor.record.name, + editor.record.id, pageRef.current, addButtonRef.current ); From 1cfa68773d5b66985f0fa7527c910c380547d2ac Mon Sep 17 00:00:00 2001 From: James Koster Date: Mon, 16 Nov 2026 18:51:32 +0000 Subject: [PATCH 12/13] Storybook: Address settings page pattern review feedback - Make the record name searchable. - Keep focus in the table when a save moves a record out of the filtered view, in both the dialog and the drawer. - Warn before reloading while a record save is in progress. - Use an unstyled Link for subpage rows, as admin UI does for its navigation links. - Align the saving guidance with Save & Submit. Co-Authored-By: Claude Opus 5.5 --- .../design-system/patterns/settings-page.mdx | 6 +- .../patterns/settings-page/api-keys.tsx | 89 ++++++++++++++++++- .../patterns/settings-page/records-dialog.tsx | 51 +++++++---- .../patterns/settings-page/records-drawer.tsx | 43 ++------- .../patterns/settings-page/router.tsx | 6 +- 5 files changed, 134 insertions(+), 61 deletions(-) diff --git a/storybook/stories/design-system/patterns/settings-page.mdx b/storybook/stories/design-system/patterns/settings-page.mdx index ca985130d26720..e8f71f5a620dd4 100644 --- a/storybook/stories/design-system/patterns/settings-page.mdx +++ b/storybook/stories/design-system/patterns/settings-page.mdx @@ -18,7 +18,7 @@ Templates for settings screens, composed from the admin-ui `Page`, `@wordpress/u These templates are starting points, not requirements. Not every settings page needs to match one exactly: adapt the structure to what your settings need, and combine or depart from the templates where that serves people better. -Several of the `@wordpress/ui` components they use, including `Button`, `ButtonLink`, `Dialog`, `Drawer` and `AlertDialog`, are still marked “Use with caution”, so their APIs may change. Treat the templates as the direction settings pages are heading, not as a recommendation to migrate existing screens yet. +Several of the `@wordpress/ui` components they use, including `Button`, `Dialog`, `Drawer` and `AlertDialog`, are still marked “Use with caution”, so their APIs may change. Treat the templates as the direction settings pages are heading, not as a recommendation to migrate existing screens yet. ## Building blocks @@ -44,7 +44,7 @@ Plan a settings page like a document's outline before choosing how it looks. The ## Saving -These templates use the manual save model from [Save & Submit](?path=/docs/design-system-patterns-save-submit--docs), the usual choice for settings: edits are held in a draft until the user clicks “Save changes”. Autosave suits pages of independent preferences that each take effect on their own. If you adopt it, remove the Save button rather than mixing the two models on one page. +These templates use the manual save model from [Save & Submit](?path=/docs/design-system-patterns-save-submit--docs): edits are held in a draft until the user clicks “Save changes”. Manual save is the usual choice for settings, because their fields often depend on each other and should apply together. Autosave suits a page of independent preferences that each take effect on their own, such as the block editor’s Preferences modal. Choose one model for the whole page and don't mix the two: if you choose autosave, remove the Save button. [Choose one save model per surface](?path=/docs/design-system-patterns-save-submit--docs#choose-one-save-model-per-surface) explains how to decide. - **One “Save changes” button per page**, in the `Page` header actions. It covers every field on that page and nothing else. - **Disabled only when there is nothing to save**, and busy while saving. Don't explain the disabled state with a tooltip: tooltips aren't available to screen readers or on touch devices. @@ -105,7 +105,7 @@ Peer sections of one settings area, such as General, Payments and Emails, switch ## Subpages -A subpage holds detail that would crowd the main page, such as the credentials for each payment gateway. Open it from the page body with a full-width row at the bottom of the card: an unstyled `ButtonLink` with a trailing chevron to signal that it navigates. A status badge in the row tells people what they will find there. +A subpage holds detail that would crowd the main page, such as the credentials for each payment gateway. Open it from the page body with a full-width row at the bottom of the card: a `Link` with `variant="unstyled"`, styled as a row, with a trailing chevron to signal that it navigates. A status badge in the row tells people what they will find there. When a card leads to several subpages, put the rows in a list: diff --git a/storybook/stories/design-system/patterns/settings-page/api-keys.tsx b/storybook/stories/design-system/patterns/settings-page/api-keys.tsx index b2cb2abdea2ace..9d5f02b3fd22fb 100644 --- a/storybook/stories/design-system/patterns/settings-page/api-keys.tsx +++ b/storybook/stories/design-system/patterns/settings-page/api-keys.tsx @@ -91,6 +91,7 @@ export const keyFields: Field< ApiKey >[] = [ render: ( { item } ) => ( { item.name } ), + enableGlobalSearch: true, enableHiding: false, isValid: { required: true }, }, @@ -176,13 +177,56 @@ export function KeyForm( { ); } +/** + * Where focus should land once a record's row leaves the table, because it + * was revoked or a save moved it out of the filtered view: the next record, + * the previous one when it was last, or Add API key when none remain. + * Captured before the row is removed, so the element is one that stays. + * Rows are matched by record ID, since two records can share a name. + */ +export function focusTargetAfterRemoval( + id: string, + scope: ParentNode | null, + addButton: HTMLElement | null +) { + const titles = findRowTitles( scope ); + const index = titles.findIndex( ( title ) => rowTitleId( title ) === id ); + // `titles[-1]` is undefined, so the first record falls through to the next. + const remaining = titles[ index + 1 ] ?? titles[ index - 1 ]; + if ( index !== -1 && remaining ) { + return remaining; + } + return addButton; +} + +function findRowTitles( scope: ParentNode | null ) { + return [ + ...( scope ?? document ).querySelectorAll< HTMLElement >( + '.dataviews-title-field[role="button"]' + ), + ]; +} + +function rowTitleId( title: HTMLElement ) { + return title.querySelector< HTMLElement >( '[data-key-id]' )?.dataset.keyId; +} + /** * State for editing one record in an overlay. The overlay saves on its own: * its Save submits the form, which applies the draft, closes the overlay and * confirms in a snackbar. Invalid fields stop the submission and show their * errors instead. */ -export function useKeyEditor( onSave: ( key: ApiKey ) => ApiKey ) { +export function useKeyEditor( + onSave: ( key: ApiKey ) => ApiKey, + { + scopeRef, + addButtonRef, + }: { + scopeRef: { current: HTMLElement | null }; + addButtonRef: { current: HTMLElement | null }; + } +) { const [ isOpen, setIsOpen ] = useState( false ); // The record stays set after closing, so the overlay keeps its content // while it animates out. @@ -196,7 +240,16 @@ export function useKeyEditor( onSave: ( key: ApiKey ) => ApiKey ) { const formId = useId(); const notify = useNotify(); + // Set by a save, for the overlay to read as it closes. A filtered table + // drops a row whose saved values no longer match, and the overlay would + // otherwise return focus to a control that's gone. + const savedFocusRef = useRef< { + row: HTMLElement | undefined; + target: HTMLElement | null; + } | null >( null ); + const open = ( key: ApiKey ) => { + savedFocusRef.current = null; setRecord( key ); setDraft( key ); setIsOpen( true ); @@ -216,7 +269,8 @@ export function useKeyEditor( onSave: ( key: ApiKey ) => ApiKey ) { // Reloading or closing the tab can only be guarded by the browser's own // warning. - const shouldWarnOnUnload = isOpen && isDirty; + // A pending save counts too: it hasn't been applied yet. + const shouldWarnOnUnload = isOpen && ( isDirty || isSaving ); useEffect( () => { if ( ! shouldWarnOnUnload ) { return; @@ -260,6 +314,19 @@ export function useKeyEditor( onSave: ( key: ApiKey ) => ApiKey ) { const submitted = draft; setIsSaving( true ); await simulateRequest(); + if ( submitted.id ) { + // The row is still in the table until the save re-renders it. + savedFocusRef.current = { + row: findRowTitles( scopeRef.current ).find( + ( title ) => rowTitleId( title ) === submitted.id + ), + target: focusTargetAfterRemoval( + submitted.id, + scopeRef.current, + addButtonRef.current + ), + }; + } const saved = onSave( submitted ); setIsSaving( false ); notify( 'API key saved.' ); @@ -274,6 +341,23 @@ export function useKeyEditor( onSave: ( key: ApiKey ) => ApiKey ) { } }; + /** + * Passed to the overlay's `finalFocus`. Returns focus to whatever opened + * the overlay, unless a save just took the record's row out of the table. + */ + const finalFocus = () => { + const saved = savedFocusRef.current; + savedFocusRef.current = null; + if ( + saved?.row && + ! saved.row.isConnected && + saved.target?.isConnected + ) { + return saved.target; + } + return true; + }; + const onSubmit = ( event: FormEvent ) => { event.preventDefault(); if ( ! isSaving ) { @@ -296,6 +380,7 @@ export function useKeyEditor( onSave: ( key: ApiKey ) => ApiKey ) { onOpenChange, discard, save, + finalFocus, }; } diff --git a/storybook/stories/design-system/patterns/settings-page/records-dialog.tsx b/storybook/stories/design-system/patterns/settings-page/records-dialog.tsx index 24dfc8396d5df5..ec293849d9a11f 100644 --- a/storybook/stories/design-system/patterns/settings-page/records-dialog.tsx +++ b/storybook/stories/design-system/patterns/settings-page/records-dialog.tsx @@ -1,6 +1,7 @@ import type { Ref } from 'react'; import { Page } from '@wordpress/admin-ui'; import type { Action } from '@wordpress/dataviews'; +import { useRef } from '@wordpress/element'; import { pencil } from '@wordpress/icons'; import { Button, Dialog } from '@wordpress/ui'; import type { ApiKey } from './api-keys'; @@ -17,6 +18,7 @@ import { SettingsExample, useOverlayContainer, } from './shared'; +import styles from './style.module.css'; import { DiscardChangesDialog } from './unsaved-changes'; /** @@ -42,6 +44,7 @@ export function KeyDialog( { > } + finalFocus={ editor.finalFocus } > @@ -119,7 +122,12 @@ export function AddKeyButton( { function RecordsDialogPage() { const { keys, saveKey } = useKeys(); - const editor = useKeyEditor( saveKey ); + const pageRef = useRef< HTMLDivElement >( null ); + const addButtonRef = useRef< HTMLButtonElement >( null ); + const editor = useKeyEditor( saveKey, { + scopeRef: pageRef, + addButtonRef, + } ); const actions: Action< ApiKey >[] = [ { id: 'edit', @@ -131,24 +139,29 @@ function RecordsDialogPage() { ]; return ( - editor.open( emptyKey ) } /> - } - > - - - - - +
+ editor.open( emptyKey ) } + /> + } + > + + + + + +
); } diff --git a/storybook/stories/design-system/patterns/settings-page/records-drawer.tsx b/storybook/stories/design-system/patterns/settings-page/records-drawer.tsx index 4ad2f63f73b66a..35277e0a10cbd5 100644 --- a/storybook/stories/design-system/patterns/settings-page/records-drawer.tsx +++ b/storybook/stories/design-system/patterns/settings-page/records-drawer.tsx @@ -7,6 +7,7 @@ import { AlertDialog, Button, Drawer } from '@wordpress/ui'; import type { ApiKey } from './api-keys'; import { emptyKey, + focusTargetAfterRemoval, KeyForm, KeysTable, useKeyEditor, @@ -23,37 +24,6 @@ import { import styles from './style.module.css'; import { DiscardChangesDialog } from './unsaved-changes'; -/** - * Where focus should land once a revoked record and its drawer are gone: - * the next record, the previous one when it was last, or Add API key when - * the list is empty. Captured before the record is removed, so the element - * is still the one that remains. Rows are matched by record ID, since two - * records can share a name. - */ -function focusTargetAfterRevoke( - id: string, - scope: ParentNode | null, - addButton: HTMLElement | null -) { - const root = scope ?? document; - const titles = [ - ...root.querySelectorAll< HTMLElement >( - '.dataviews-title-field[role="button"]' - ), - ]; - const index = titles.findIndex( - ( title ) => - title.querySelector< HTMLElement >( '[data-key-id]' )?.dataset - .keyId === id - ); - // `titles[-1]` is undefined, so the first record falls through to the next. - const remaining = titles[ index + 1 ] ?? titles[ index - 1 ]; - if ( index !== -1 && remaining ) { - return remaining; - } - return addButton; -} - /** * Edits one record in a drawer, which keeps the table in view and leaves * room for secondary actions. Like the dialog, it closes only through its @@ -81,7 +51,7 @@ function KeyDrawer( { const revokeKey = async () => { await simulateRequest(); - const target = focusTargetAfterRevoke( + const target = focusTargetAfterRemoval( editor.record.id, pageRef.current, addButtonRef.current @@ -114,7 +84,9 @@ function KeyDrawer( { > } - finalFocus={ () => revokedFocusRef.current ?? true } + finalFocus={ () => + revokedFocusRef.current ?? editor.finalFocus() + } > @@ -182,9 +154,12 @@ function KeyDrawer( { function RecordsDrawerPage() { const { keys, saveKey, revokeKey } = useKeys(); - const editor = useKeyEditor( saveKey ); const pageRef = useRef< HTMLDivElement >( null ); const addButtonRef = useRef< HTMLButtonElement >( null ); + const editor = useKeyEditor( saveKey, { + scopeRef: pageRef, + addButtonRef, + } ); const actions: Action< ApiKey >[] = [ { id: 'edit', diff --git a/storybook/stories/design-system/patterns/settings-page/router.tsx b/storybook/stories/design-system/patterns/settings-page/router.tsx index 5b3480f3437174..dccf2d4678906f 100644 --- a/storybook/stories/design-system/patterns/settings-page/router.tsx +++ b/storybook/stories/design-system/patterns/settings-page/router.tsx @@ -14,7 +14,7 @@ import { Link as RouterLink, privateApis as routePrivateApis, } from '@wordpress/route'; -import { Badge, ButtonLink, Icon, Text } from '@wordpress/ui'; +import { Badge, Icon, Link, Text } from '@wordpress/ui'; import styles from './style.module.css'; const { unlock } = __dangerousOptInToUnstableAPIsOnlyForCoreModules( @@ -251,7 +251,7 @@ export function SubpageLink( { const labelId = useId(); const statusId = useId(); return ( - } @@ -271,6 +271,6 @@ export function SubpageLink( { ) } - + ); } From f79ee1a222a739553284c445ea6ee649d82985c6 Mon Sep 17 00:00:00 2001 From: James Koster Date: Wed, 18 Nov 2026 10:17:24 +0000 Subject: [PATCH 13/13] Storybook: Keep focus and table view in settings page patterns - Move focus to Save changes when a valid retry removes the failed save notice and its Try again button. - Keep the records table's search, filters and page when returning from a record's subpage. - Keep the first save's focus target when a later save follows edits made while saving, and only read it in finalFocus, which Base UI also calls on re-renders while the overlay is open. Co-Authored-By: Claude Opus 5.5 --- .../design-system/patterns/settings-page.mdx | 4 +- .../patterns/settings-page/api-keys.tsx | 57 ++++++++++++------- .../settings-page/records-subpage.tsx | 24 ++++++-- .../patterns/settings-page/shared.tsx | 29 +++++++++- 4 files changed, 86 insertions(+), 28 deletions(-) diff --git a/storybook/stories/design-system/patterns/settings-page.mdx b/storybook/stories/design-system/patterns/settings-page.mdx index e8f71f5a620dd4..88d50bbb0cc29a 100644 --- a/storybook/stories/design-system/patterns/settings-page.mdx +++ b/storybook/stories/design-system/patterns/settings-page.mdx @@ -57,7 +57,7 @@ These templates use the manual save model from [Save & Submit](?path=/docs/desig ### When a save fails -Keep the draft, so nothing the user entered is lost, and explain the failure in a `Notice` at the top of the form with a “Try again” action. Retrying submits the form again, so validation runs first. In this example the first save fails: change a field, click “Save changes”, then try again. +Keep the draft, so nothing the user entered is lost, and explain the failure in a `Notice` at the top of the form with a “Try again” action. Retrying submits the form again, so validation runs first. A retry that goes through removes the notice, and the focused button with it, so move focus to “Save changes” first. In this example the first save fails: change a field, click “Save changes”, then try again. ( null ); @@ -314,12 +314,17 @@ export function useKeyEditor( const submitted = draft; setIsSaving( true ); await simulateRequest(); - if ( submitted.id ) { - // The row is still in the table until the save re-renders it. - savedFocusRef.current = { - row: findRowTitles( scopeRef.current ).find( + // The row is still in the table until the save re-renders it. When an + // earlier save already took it out, and edits made meanwhile kept the + // overlay open, keep the target that save found. + const row = submitted.id + ? findRowTitles( scopeRef.current ).find( ( title ) => rowTitleId( title ) === submitted.id - ), + ) + : undefined; + if ( row ) { + savedFocusRef.current = { + row, target: focusTargetAfterRemoval( submitted.id, scopeRef.current, @@ -343,11 +348,12 @@ export function useKeyEditor( /** * Passed to the overlay's `finalFocus`. Returns focus to whatever opened - * the overlay, unless a save just took the record's row out of the table. + * the overlay, unless a save took the record's row out of the table. + * Base UI also calls it on re-renders while the overlay is open, so it + * only reads the target; opening the editor again clears it. */ const finalFocus = () => { const saved = savedFocusRef.current; - savedFocusRef.current = null; if ( saved?.row && ! saved.row.isConnected && @@ -418,6 +424,17 @@ export function useKeys() { return { keys, saveKey, revokeKey }; } +export const defaultKeysView: View = { + type: 'table', + search: '', + page: 1, + perPage: 10, + filters: [], + layout: {}, + titleField: 'name', + fields: [ 'prefix', 'access', 'lastUsed', 'active' ], +}; + /** * The records table, in a card. The page title already names the records, * so the card has no title of its own. @@ -427,24 +444,26 @@ export function KeysTable( { actions, onClickItem, renderItemLink, + view: controlledView, + onChangeView, }: { keys: ApiKey[]; + /** + * Pass the view from above when the table unmounts while people edit a + * record, as it does when records open a subpage, so their search, + * filters and page are still there when they come back. + */ + view?: View; + onChangeView?: ( view: View ) => void; actions?: Action< ApiKey >[]; onClickItem?: ( item: ApiKey ) => void; renderItemLink?: ( props: { item: ApiKey } & ComponentProps< 'a' > ) => ReactElement; } ) { - const [ view, setView ] = useState< View >( { - type: 'table', - search: '', - page: 1, - perPage: 10, - filters: [], - layout: {}, - titleField: 'name', - fields: [ 'prefix', 'access', 'lastUsed', 'active' ], - } ); + const [ ownView, setOwnView ] = useState< View >( defaultKeysView ); + const view = controlledView ?? ownView; + const setView = onChangeView ?? setOwnView; const { data, paginationInfo } = useMemo( () => filterSortAndPaginate( keys, view, keyFields ), diff --git a/storybook/stories/design-system/patterns/settings-page/records-subpage.tsx b/storybook/stories/design-system/patterns/settings-page/records-subpage.tsx index 1af5f3ab5413d8..aea5ace677eb31 100644 --- a/storybook/stories/design-system/patterns/settings-page/records-subpage.tsx +++ b/storybook/stories/design-system/patterns/settings-page/records-subpage.tsx @@ -1,9 +1,10 @@ import { Breadcrumbs, Page } from '@wordpress/admin-ui'; -import type { Action } from '@wordpress/dataviews'; +import type { Action, View } from '@wordpress/dataviews'; +import { useState } from '@wordpress/element'; import { pencil } from '@wordpress/icons'; import { Link as RouterLink, useNavigate } from '@wordpress/route'; import type { ApiKey } from './api-keys'; -import { KeyForm, KeysTable, useKeys } from './api-keys'; +import { defaultKeysView, KeyForm, KeysTable, useKeys } from './api-keys'; import { SettingsRouter, useSettingsPath } from './router'; import { SettingsContent, @@ -12,7 +13,15 @@ import { SettingsSection, } from './shared'; -function KeysPage( { keys }: { keys: ApiKey[] } ) { +function KeysPage( { + keys, + view, + onChangeView, +}: { + keys: ApiKey[]; + view: View; + onChangeView: ( view: View ) => void; +} ) { const navigate = useNavigate(); const actions: Action< ApiKey >[] = [ { @@ -34,6 +43,8 @@ function KeysPage( { keys }: { keys: ApiKey[] } ) { ( @@ -47,10 +58,15 @@ function KeysPage( { keys }: { keys: ApiKey[] } ) { function RecordsSubpageScreen() { const path = useSettingsPath(); const { keys, saveKey } = useKeys(); + // Held above the routes, so returning from a record restores the + // table's search, filters and page. + const [ view, setView ] = useState< View >( defaultKeysView ); const key = keys.find( ( { id } ) => path === `/keys/${ id }` ); if ( ! key ) { - return ; + return ( + + ); } return ( diff --git a/storybook/stories/design-system/patterns/settings-page/shared.tsx b/storybook/stories/design-system/patterns/settings-page/shared.tsx index 7a7496922c7438..38fc57c812420d 100644 --- a/storybook/stories/design-system/patterns/settings-page/shared.tsx +++ b/storybook/stories/design-system/patterns/settings-page/shared.tsx @@ -1,5 +1,5 @@ import clsx from 'clsx'; -import type { ComponentProps, ReactNode } from 'react'; +import type { ComponentProps, MouseEvent, ReactNode, Ref } from 'react'; import { Page } from '@wordpress/admin-ui'; import { SnackbarList } from '@wordpress/components'; import type { Field } from '@wordpress/dataviews'; @@ -140,16 +140,19 @@ export function SaveButton( { hasChanges, isSaving, size, + buttonRef, children = 'Save changes', }: { form: string; hasChanges: boolean; isSaving: boolean; size?: ComponentProps< typeof Button >[ 'size' ]; + buttonRef?: Ref< HTMLButtonElement >; children?: ReactNode; } ) { return (