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..88d50bbb0cc29a --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page.mdx @@ -0,0 +1,171 @@ +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'; +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. + +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`, `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: + +- **`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. 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. +- **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/`. + +## 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 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. +- **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. 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 + +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. + + + +## 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. + +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 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 + +A single page with a few groups of settings. Use it when everything fits on one screen. + + + +## 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. + +- 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. + + + +## 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: 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: + +- **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, 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. + + + +## 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. The table goes away while a record is open, so keep its search, filters and page somewhere that outlives it, and people find their results as they left them when they come back. Real screens usually keep the view in the URL or in user preferences; this example holds it above its routes. + + + +### 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). 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. + + 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..608a54230a51c1 --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page.story.tsx @@ -0,0 +1,67 @@ +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'; +import { SectionsExample } from './settings-page/sections'; +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 FailedSave: Story = { + name: 'Failed save', + render: () => , +}; + +export const Sections: Story = { + name: 'Settings page with sections', + 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..bf99a219d9da06 --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/adjacent-pages-and-subpages.tsx @@ -0,0 +1,77 @@ +import { SettingsRouter, useSettingsPath } from './router'; +import { SettingsExample } from './shared'; +import { + adjacentPageHeader, + EmailsPage, + GatewayPage, + gatewayFromPath, + GeneralPage, + PaymentsPage, + SETTINGS_CRUMB, + subpageHeader, + useStoreSettings, +} from './store-pages'; + +function AdjacentPagesAndSubpagesScreen() { + const path = useSettingsPath(); + const settings = useStoreSettings(); + const gateway = gatewayFromPath( path ); + + if ( gateway ) { + 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 its breadcrumbs pass through the adjacent page it + * belongs to. + */ +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..3867619d1123e0 --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/api-keys.tsx @@ -0,0 +1,492 @@ +import type { ComponentProps, FormEvent, ReactElement } from 'react'; +import type { Action, Field, View } from '@wordpress/dataviews'; +import { + DataForm, + DataViews, + filterSortAndPaginate, + useFormValidity, +} from '@wordpress/dataviews'; +import { + useEffect, + useId, + useMemo, + useRef, + 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', + // 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 } + ), + enableGlobalSearch: true, + 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 } + /> + ); +} + +/** + * 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, + { + 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. + const [ record, setRecord ] = useState< ApiKey >( emptyKey ); + const [ draft, setDraft ] = useState< ApiKey >( emptyKey ); + const [ isSaving, setIsSaving ] = useState( false ); + const draftRef = useRef( draft ); + useEffect( () => { + draftRef.current = draft; + }, [ draft ] ); + const formId = useId(); + const notify = useNotify(); + + // Set by a save, for the overlay to read when 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; + target: HTMLElement | null; + } | null >( null ); + + const open = ( key: ApiKey ) => { + savedFocusRef.current = null; + 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 ); + + // Reloading or closing the tab can only be guarded by the browser's own + // warning. + // A pending save counts too: it hasn't been applied yet. + const shouldWarnOnUnload = isOpen && ( isDirty || isSaving ); + 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 + * 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 () => { + const submitted = draft; + setIsSaving( true ); + await simulateRequest(); + // 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, + addButtonRef.current + ), + }; + } + const saved = onSave( submitted ); + setIsSaving( 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 } ); + } + }; + + /** + * Passed to the overlay's `finalFocus`. Returns focus to whatever opened + * 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; + if ( + saved?.row && + ! saved.row.isConnected && + saved.target?.isConnected + ) { + return saved.target; + } + return true; + }; + + const onSubmit = ( event: FormEvent ) => { + event.preventDefault(); + if ( ! isSaving ) { + save(); + } + }; + + return { + record, + isOpen, + isNew: ! record.id, + draft, + onChange, + isDirty, + isSaving, + formId, + onSubmit, + open, + close, + onOpenChange, + discard, + save, + finalFocus, + }; +} + +/** + * Holds the saved records, above any route or overlay that edits them. + */ +export function useKeys() { + const [ keys, setKeys ] = useState( initialKeys ); + + /** + * 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 ) => { + setKeys( ( current ) => current.filter( ( { id } ) => id !== key.id ) ); + }; + + 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. + */ +export function KeysTable( { + keys, + 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 [ ownView, setOwnView ] = useState< View >( defaultKeysView ); + const view = controlledView ?? ownView; + const setView = onChangeView ?? setOwnView; + + const { data, paginationInfo } = useMemo( + () => filterSortAndPaginate( keys, view, keyFields ), + [ keys, view ] + ); + + return ( + + + + + + + + ); +} 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 new file mode 100644 index 00000000000000..ec293849d9a11f --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/records-dialog.tsx @@ -0,0 +1,178 @@ +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'; +import { + emptyKey, + KeyForm, + KeysTable, + useKeyEditor, + useKeys, +} from './api-keys'; +import { + SaveButton, + SettingsContent, + SettingsExample, + useOverlayContainer, +} from './shared'; +import styles from './style.module.css'; +import { DiscardChangesDialog } from './unsaved-changes'; + +/** + * Edits one record in a dialog. People leave through Cancel, which discards + * 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( { + 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 ( + <> + + } + finalFocus={ editor.finalFocus } + > + + + { editor.isNew ? 'Add API key' : 'Edit API key' } + + + + + + + + + + Cancel + + + + + + + + ); +} + +/** + * 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, + buttonRef, +}: { + onClick: () => void; + buttonRef?: Ref< HTMLButtonElement >; +} ) { + return ( + + ); +} + +function RecordsDialogPage() { + const { keys, saveKey } = useKeys(); + const pageRef = useRef< HTMLDivElement >( null ); + const addButtonRef = useRef< HTMLButtonElement >( null ); + const editor = useKeyEditor( saveKey, { + scopeRef: pageRef, + addButtonRef, + } ); + 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..35277e0a10cbd5 --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/records-drawer.tsx @@ -0,0 +1,215 @@ +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, + focusTargetAfterRemoval, + KeyForm, + KeysTable, + useKeyEditor, + useKeys, +} from './api-keys'; +import { AddKeyButton, KeySaveButton } 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, + 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 = focusTargetAfterRemoval( + editor.record.id, + 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 + // backdrop for a dialog nested inside another, which would leave the + // drawer undimmed behind them. + return ( + <> + + } + finalFocus={ () => + revokedFocusRef.current ?? editor.finalFocus() + } + > + + + { editor.isNew ? 'Add API key' : 'Edit API key' } + + + +
+ + +
+ + { ! editor.isNew && ( + + ) } + + Cancel + + + +
+
+ + + } + 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." + confirmButtonText="Revoke key" + /> + + + + ); +} + +function RecordsDrawerPage() { + const { keys, saveKey, revokeKey } = useKeys(); + const pageRef = useRef< HTMLDivElement >( null ); + const addButtonRef = useRef< HTMLButtonElement >( null ); + const editor = useKeyEditor( saveKey, { + scopeRef: pageRef, + addButtonRef, + } ); + 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..aea5ace677eb31 --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/records-subpage.tsx @@ -0,0 +1,108 @@ +import { Breadcrumbs, Page } from '@wordpress/admin-ui'; +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 { defaultKeysView, KeyForm, KeysTable, useKeys } from './api-keys'; +import { SettingsRouter, useSettingsPath } from './router'; +import { + SettingsContent, + SettingsExample, + SettingsFormPage, + SettingsSection, +} from './shared'; + +function KeysPage( { + keys, + view, + onChangeView, +}: { + keys: ApiKey[]; + view: View; + onChangeView: ( view: View ) => void; +} ) { + 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(); + // 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 ( + + } + ariaLabel={ key.name } + 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..dccf2d4678906f --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/router.tsx @@ -0,0 +1,276 @@ +import type { AnchorHTMLAttributes, ComponentProps, 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'; +import { + Link as RouterLink, + privateApis as routePrivateApis, +} from '@wordpress/route'; +import { Badge, Icon, Link, 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 ); + +/** + * Moves focus to the new `Page` region when a navigation removes the focused + * 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() { + const containerRef = useRef< HTMLDivElement >( 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; + } + container.querySelector< HTMLElement >( '[role="region"]' )?.focus(); + }, [ pathname ] ); + + return containerRef; +} + +function Screen() { + const containerRef = useFocusAfterNavigate(); + 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/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 new file mode 100644 index 00000000000000..38fc57c812420d --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/shared.tsx @@ -0,0 +1,659 @@ +import clsx from 'clsx'; +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'; +import { DataForm, useFormValidity } from '@wordpress/dataviews'; +import { + createContext, + useCallback, + useContext, + useId, + useRef, + useState, +} from '@wordpress/element'; +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'; + +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. 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 ) => 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 ); + + // 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 } ) ); + }, [] ); + + const save = async () => { + setIsSaving( true ); + setHasFailed( false ); + try { + await simulateRequest(); + await onSave( data ); + notify( message ); + } catch { + setHasFailed( true ); + } + setIsSaving( false ); + }; + + return { data, onChange, isDirty, isSaving, hasFailed, save }; +} + +/** + * 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 or while saving. + */ +export function SaveButton( { + form, + hasChanges, + isSaving, + size, + buttonRef, + children = 'Save changes', +}: { + form: string; + hasChanges: boolean; + isSaving: boolean; + size?: ComponentProps< typeof Button >[ 'size' ]; + buttonRef?: Ref< HTMLButtonElement >; + children?: ReactNode; +} ) { + return ( + + ); +} + +/** + * 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: ( event: MouseEvent< HTMLButtonElement > ) => void; +} ) { + return ( + + { hasFailed && ( + + Your changes couldn’t be saved. + + They’re still here. Check your connection, then try + again. + + + + Try again + + + + ) } + + ); +} + +type PageHeaderProps = Omit< + ComponentProps< typeof Page >, + 'children' | 'actions' +>; + +/** + * 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, + onSave, + children, + ...pageProps +}: PageHeaderProps & { + saved: T; + onSave: ( data: T ) => unknown; + children: ( form: { + data: T; + onChange: ( edits: Partial< T > ) => void; + } ) => ReactNode; +} ) { + const { data, onChange, isDirty, isSaving, hasFailed, save } = + useManualSave( saved, onSave ); + const formId = useId(); + const formRef = useRef< HTMLFormElement >( null ); + const saveButtonRef = useRef< HTMLButtonElement >( null ); + + /** + * Retrying submits the form, so invalid fields take focus as usual. A + * valid retry removes the notice and its button with it, so focus moves + * to Save first, which stays focusable while it's busy or disabled. + */ + const retry = ( event: MouseEvent< HTMLButtonElement > ) => { + const retryButton = event.currentTarget; + formRef.current?.requestSubmit(); + const { activeElement, body } = retryButton.ownerDocument; + if ( + ! activeElement || + activeElement === retryButton || + activeElement === body + ) { + saveButtonRef.current?.focus(); + } + }; + + return ( + + } + > +
{ + event.preventDefault(); + if ( isDirty && ! isSaving ) { + save(); + } + } } + > + + + { 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. 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 && ( + + { description } + + ) } + + + { children } + + ); +} + +/** + * 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. + */ +export function SettingsForm< T extends object >( { + data, + fields, + onChange, +}: { + data: T; + 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={ form } + validity={ validity } + 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 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; + 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..fe9dce5ee80088 --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/store-pages.tsx @@ -0,0 +1,318 @@ +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' }, +]; + +// 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. + */ +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' + | 'ariaLabel' + | 'navigation' + | 'components' +>; + +/** + * 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', + to: ADJACENT_PAGES[ 0 ].href, +}; + +/** + * Header props for a page that sits among adjacent pages. The title names + * 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 }, + }; +} + +/** + * 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: , + ariaLabel: trail[ trail.length - 1 ].label, + }; +} + +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..87fcc7fad638cc --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/style.module.css @@ -0,0 +1,118 @@ +/* + * 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; +} + +.screen { + display: contents; +} + +/* `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; +} + +/* + * 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); +} + +/* + * 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..b8ec4d7608e46a --- /dev/null +++ b/storybook/stories/design-system/patterns/settings-page/unsaved-changes.tsx @@ -0,0 +1,80 @@ +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. + * 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, + 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?.() } + /> + ); +}