@gopherium/godmin 0.20.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -52,11 +52,12 @@ two lines do for you.
52
52
 
53
53
  | Entry point | Contents |
54
54
  | --- | --- |
55
- | `@gopherium/godmin` | `AdminRoot`, `Frame`, `Page`, `PageTitle`, `PageTabs`, `PageTab`, `SectionTitle`, `InitialsAvatar`, `NavScreen`, `ErrorNotice`, `LoadMore`, `LogList`, `LogItem`, `LogTime`, `LoadingScreen`, `LoadingRows`, `Toaster`, `useToaster`, `RepeatRows`, `RowControls`, `useRowKeys`, `keyFromLabel`, `listChromeCatalogFor`, `LIST_CHROME_DOMAIN`, `ListEmpty`, `ConfirmBody`, `RenameBody`, `FileButton`, `useServerPaging`, `pageWindow`, `paginationOf`, `runEach`, `bulkNotes`, `useMediaQuery`, `useTokenDocument`, the breakpoints, `SUPPORTED_WPDS` |
55
+ | `@gopherium/godmin` | `AdminRoot`, `Frame`, `Page`, `PageTitle`, `PageTabs`, `PageTab`, `SectionTitle`, `InitialsAvatar`, `NavScreen`, `ErrorNotice`, `LoadMore`, `LogList`, `LogItem`, `LogTime`, `LoadingScreen`, `LoadingRows`, `Toaster`, `useToaster`, `RepeatRows`, `RowControls`, `useRowKeys`, `keyFromLabel`, `listChromeCatalogFor`, `LIST_CHROME_DOMAIN`, `ListEmpty`, `ConfirmBody`, `RenameBody`, `FileButton`, `useServerPaging`, `pageWindow`, `paginationOf`, `runEach`, `bulkNotes`, `useListRun`, `useBulkRun`, `RunConfirm`, `viewNarrows`, `offeredView`, `offeredSize`, `sizedView`, `useMediaQuery`, `useTokenDocument`, the breakpoints `RAIL_BREAKPOINT`, `EDGE_BREAKPOINT`, `DENSE_BREAKPOINT`, `SHEET_BREAKPOINT`, `TITLE_BREAKPOINT` and `SMALL_VIEWPORT`, `SUPPORTED_WPDS` |
56
56
  | `@gopherium/godmin/base.css` | Cascade layer order, design tokens, host rules, frame and screen styles |
57
57
  | `@gopherium/godmin/dates` | `startListDates`, `listDate`, the only entry that loads `@wordpress/date` |
58
+ | `@gopherium/godmin/dialogs` | `ConfirmDialog`, the only entry that loads `@wordpress/components`. Load `@wordpress/components/build-style/style.css` once in your app, as DataViews asks |
58
59
  | `@gopherium/godmin/router` | `useListView`, `listSearch`, `openOnTap`, `useCanvas`, `useFrameLocation`, the `canvas` route static data |
59
- | `@gopherium/godmin/testing` | `installTestEnvironment`, `renderAdmin`, `setViewport`, `getAnnouncement`, `clearAnnouncements`, `assertElementPatched`, `WPDS_IGNORE_SELECTOR`, `textClasses`, `badgeClasses`, `buttonClasses` |
60
+ | `@gopherium/godmin/testing` | `installTestEnvironment`, `renderAdmin`, `setViewport` and its `TestViewport` type, `getAnnouncement`, `clearAnnouncements`, `assertElementPatched`, `WPDS_IGNORE_SELECTOR`, `textClasses`, `badgeClasses`, `buttonClasses`, `stubLayout` |
60
61
  | `@gopherium/godmin/vite` | `godminDedupe`, `godminSingleCopy`, `godminStylesheetFirst`, `duplicateCopies`, `hoistStylesheet` |
61
62
  | `@gopherium/godmin/stylelint` | The design system stylelint rules |
62
63
 
@@ -10,6 +10,14 @@ export declare const EDGE_BREAKPOINT = 782;
10
10
  * The viewport width below which the canvas gutter narrows to 16px.
11
11
  */
12
12
  export declare const DENSE_BREAKPOINT = 640;
13
+ /**
14
+ * The viewport width below which modals rise as sheets and toasts widen to the screen, the WordPress small breakpoint.
15
+ */
16
+ export declare const SHEET_BREAKPOINT = 600;
17
+ /**
18
+ * The viewport width below which an editor header drops its document title, as the WordPress editor does.
19
+ */
20
+ export declare const TITLE_BREAKPOINT = 404;
13
21
  /**
14
22
  * The media query the frame folds its rail at.
15
23
  */
@@ -10,6 +10,14 @@ export const EDGE_BREAKPOINT = 782;
10
10
  * The viewport width below which the canvas gutter narrows to 16px.
11
11
  */
12
12
  export const DENSE_BREAKPOINT = 640;
13
+ /**
14
+ * The viewport width below which modals rise as sheets and toasts widen to the screen, the WordPress small breakpoint.
15
+ */
16
+ export const SHEET_BREAKPOINT = 600;
17
+ /**
18
+ * The viewport width below which an editor header drops its document title, as the WordPress editor does.
19
+ */
20
+ export const TITLE_BREAKPOINT = 404;
13
21
  /**
14
22
  * The media query the frame folds its rail at.
15
23
  */
@@ -0,0 +1,11 @@
1
+ import type { BulkWords } from './bulk.js';
2
+ import type { ListRun } from './list-run.js';
3
+ /** Runs one call over each item, refreshes the list and reports what the run reached in the given words. */
4
+ export type BulkRun<Item> = (items: Item[], call: (item: Item) => Promise<unknown>, words: BulkWords<Item>) => Promise<void>;
5
+ /**
6
+ * Returns the handler that runs one call per item, refreshes the list, toasts what finished and settles the run.
7
+ * @param list - What the list does around a run.
8
+ * @param refresh - Reloads the list, given the items the run acted on.
9
+ * @returns The run handler, the same while the list run and the refresh stay the same.
10
+ */
11
+ export declare function useBulkRun<Item>(list: ListRun, refresh: (items: Item[]) => Promise<unknown>): BulkRun<Item>;
@@ -0,0 +1,32 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { useCallback } from 'react';
3
+ import { bulkNotes, runEach } from './bulk.js';
4
+ import { useToaster } from './toaster.js';
5
+ /**
6
+ * Returns the handler that runs one call per item, refreshes the list, toasts what finished and settles the run.
7
+ * @param list - What the list does around a run.
8
+ * @param refresh - Reloads the list, given the items the run acted on.
9
+ * @returns The run handler, the same while the list run and the refresh stay the same.
10
+ */
11
+ export function useBulkRun(list, refresh) {
12
+ const toaster = useToaster();
13
+ return useCallback(async (items, call, words) => {
14
+ const settle = list.onStart();
15
+ const outcome = await runEach(items, call);
16
+ let notes = {};
17
+ try {
18
+ await refresh(items);
19
+ }
20
+ finally {
21
+ try {
22
+ notes = bulkNotes(items, outcome, words);
23
+ if (notes.toast !== undefined) {
24
+ toaster.show(notes.toast);
25
+ }
26
+ }
27
+ finally {
28
+ settle(notes.notice, outcome.done > 0);
29
+ }
30
+ }
31
+ }, [list, refresh, toaster]);
32
+ }
@@ -0,0 +1,24 @@
1
+ import type { ReactNode } from 'react';
2
+ /** The props of a confirmation dialog for an action outside a list. */
3
+ export interface ConfirmDialogProps {
4
+ /** The question the dialog asks, its name when it has no title. */
5
+ children: ReactNode;
6
+ /** The title of a plain confirm, drawn in a header with a close button, none on a confirm that removes something. */
7
+ title?: string;
8
+ /** The width of the card from 600px up, small at 400px or medium at 560px, the default. */
9
+ size?: 'small' | 'medium';
10
+ /** The label of the button that carries the action out. */
11
+ confirmLabel: string;
12
+ /** The label of the button that closes the dialog. */
13
+ cancelLabel: string;
14
+ /** Carries the action out, resolving with the failure to show, or with nothing once it is done. */
15
+ onConfirm: () => Promise<string | undefined>;
16
+ /** Takes the dialog away after Cancel, Escape, a click outside it, its close button or a confirm that finished. */
17
+ onClose: () => void;
18
+ }
19
+ /**
20
+ * Renders a confirmation dialog for an action outside a list, as WordPress dialogs ask, Cancel focused.
21
+ * @param props - The question, the title, the size, the labels and the handlers.
22
+ * @returns The dialog.
23
+ */
24
+ export declare function ConfirmDialog({ children, title, size, confirmLabel, cancelLabel, onConfirm, onClose, }: ConfirmDialogProps): import("react").JSX.Element;
@@ -0,0 +1,32 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { Modal } from '@wordpress/components';
4
+ import { useId, useState } from 'react';
5
+ import { ConfirmBody } from './confirm.js';
6
+ /**
7
+ * Renders a confirmation dialog for an action outside a list, as WordPress dialogs ask, Cancel focused.
8
+ * @param props - The question, the title, the size, the labels and the handlers.
9
+ * @returns The dialog.
10
+ */
11
+ export function ConfirmDialog({ children, title, size = 'medium', confirmLabel, cancelLabel, onConfirm, onClose, }) {
12
+ const [busy, setBusy] = useState(false);
13
+ const [failure, setFailure] = useState();
14
+ const question = useId();
15
+ const confirm = async () => {
16
+ setBusy(true);
17
+ setFailure(undefined);
18
+ let failed;
19
+ try {
20
+ failed = await onConfirm();
21
+ }
22
+ finally {
23
+ setBusy(false);
24
+ }
25
+ if (failed === undefined) {
26
+ onClose();
27
+ return;
28
+ }
29
+ setFailure(failed);
30
+ };
31
+ return (_jsx(Modal, { size: size, focusOnMount: "firstContentElement", title: title, __experimentalHideHeader: title === undefined, aria: { labelledby: question, describedby: title === undefined ? undefined : question }, isDismissible: !busy, shouldCloseOnEsc: !busy, shouldCloseOnClickOutside: !busy, onRequestClose: onClose, children: _jsx(ConfirmBody, { confirmLabel: confirmLabel, cancelLabel: cancelLabel, busy: busy, failure: failure, onConfirm: () => void confirm(), onCancel: onClose, children: _jsx("span", { id: question, children: children }) }) }));
32
+ }
package/dist/confirm.d.ts CHANGED
@@ -16,7 +16,7 @@ export interface ConfirmBodyProps {
16
16
  onCancel?: () => void;
17
17
  }
18
18
  /**
19
- * Renders the body of a confirmation modal: the question, a failure notice, a neutral Cancel and the confirm button.
19
+ * Renders a confirmation modal body: the question, a failure notice, an accent text Cancel and the confirm button.
20
20
  * @param props - The question, the labels, the busy flag, the failure and the handlers.
21
21
  * @returns The confirmation body.
22
22
  */
package/dist/confirm.js CHANGED
@@ -3,10 +3,10 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  import { Button, Stack, Text } from '@wordpress/ui';
4
4
  import { ErrorNotice } from './page.js';
5
5
  /**
6
- * Renders the body of a confirmation modal: the question, a failure notice, a neutral Cancel and the confirm button.
6
+ * Renders a confirmation modal body: the question, a failure notice, an accent text Cancel and the confirm button.
7
7
  * @param props - The question, the labels, the busy flag, the failure and the handlers.
8
8
  * @returns The confirmation body.
9
9
  */
10
10
  export function ConfirmBody({ children, confirmLabel, cancelLabel, busy = false, failure, onConfirm, onCancel, }) {
11
- return (_jsxs(Stack, { direction: "column", gap: "lg", children: [_jsx(Text, { children: children }), failure === undefined ? null : _jsx(ErrorNotice, { children: failure }), _jsxs(Stack, { direction: "row", gap: "sm", justify: "flex-end", children: [_jsx(Button, { variant: "minimal", tone: "neutral", disabled: busy, onClick: onCancel, children: cancelLabel }), _jsx(Button, { loading: busy, onClick: onConfirm, children: confirmLabel })] })] }));
11
+ return (_jsxs(Stack, { direction: "column", gap: "lg", children: [_jsx(Text, { children: children }), failure === undefined ? null : _jsx(ErrorNotice, { children: failure }), _jsxs(Stack, { direction: "row", gap: "sm", justify: "flex-end", children: [_jsx(Button, { variant: "minimal", disabled: busy, onClick: onCancel, children: cancelLabel }), _jsx(Button, { loading: busy, onClick: onConfirm, children: confirmLabel })] })] }));
12
12
  }
@@ -0,0 +1,2 @@
1
+ export { ConfirmDialog } from './confirm-dialog.js';
2
+ export type { ConfirmDialogProps } from './confirm-dialog.js';
@@ -0,0 +1,2 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ export { ConfirmDialog } from './confirm-dialog.js';
@@ -11,14 +11,20 @@ export interface FileButtonProps {
11
11
  icon?: ComponentProps<typeof Button.Icon>['icon'];
12
12
  /** The name of the hidden file input. */
13
13
  inputLabel?: string;
14
+ /** The button look, solid when absent. */
15
+ variant?: ComponentProps<typeof Button>['variant'];
16
+ /** The button tone, the brand one when absent. */
17
+ tone?: ComponentProps<typeof Button>['tone'];
18
+ /** The button size, compact when absent, as a page header button. */
19
+ size?: ComponentProps<typeof Button>['size'];
14
20
  /** Takes the files the reader chose, never called for a dialog closed with none. */
15
21
  onChoose: (files: File[]) => void;
16
22
  /** The button label. */
17
23
  children: ReactNode;
18
24
  }
19
25
  /**
20
- * Renders a compact solid button that opens the file dialog of a hidden file input.
21
- * @param props - The file types, the many flag, the busy flag, the icon, the input name, the handler and the label.
26
+ * Renders a button, compact and solid unless told otherwise, that opens the file dialog of a hidden file input.
27
+ * @param props - The file types, the many and busy flags, the icon, the input name, the look, the handler, the label.
22
28
  * @returns The button beside its hidden input.
23
29
  */
24
- export declare function FileButton({ accept, multiple, busy, icon, inputLabel, onChoose, children, }: FileButtonProps): import("react").JSX.Element;
30
+ export declare function FileButton({ accept, multiple, busy, icon, inputLabel, variant, tone, size, onChoose, children, }: FileButtonProps): import("react").JSX.Element;
@@ -15,11 +15,11 @@ function handOver(event, onChoose) {
15
15
  }
16
16
  }
17
17
  /**
18
- * Renders a compact solid button that opens the file dialog of a hidden file input.
19
- * @param props - The file types, the many flag, the busy flag, the icon, the input name, the handler and the label.
18
+ * Renders a button, compact and solid unless told otherwise, that opens the file dialog of a hidden file input.
19
+ * @param props - The file types, the many and busy flags, the icon, the input name, the look, the handler, the label.
20
20
  * @returns The button beside its hidden input.
21
21
  */
22
- export function FileButton({ accept, multiple = false, busy = false, icon, inputLabel, onChoose, children, }) {
22
+ export function FileButton({ accept, multiple = false, busy = false, icon, inputLabel, variant = 'solid', tone, size = 'compact', onChoose, children, }) {
23
23
  const input = useRef(null);
24
- return (_jsxs(_Fragment, { children: [_jsxs(Button, { variant: "solid", size: "compact", loading: busy, onClick: () => input.current.click(), children: [icon === undefined ? null : _jsx(Button.Icon, { icon: icon }), children] }), _jsx("input", { ref: input, type: "file", accept: accept, multiple: multiple, hidden: true, "aria-label": inputLabel, onChange: (event) => handOver(event, onChoose) })] }));
24
+ return (_jsxs(_Fragment, { children: [_jsxs(Button, { variant: variant, tone: tone, size: size, loading: busy, onClick: () => input.current.click(), children: [icon === undefined ? null : _jsx(Button.Icon, { icon: icon }), children] }), _jsx("input", { ref: input, type: "file", accept: accept, multiple: multiple, hidden: true, "aria-label": inputLabel, onChange: (event) => handOver(event, onChoose) })] }));
25
25
  }
@@ -0,0 +1,21 @@
1
+ /** How DataViews 20 filters a field of one type. */
2
+ export interface TypeOffer {
3
+ /** The operators a field of the type filters with when it names none. */
4
+ defaults: readonly string[];
5
+ /** The operators a field of the type may name. */
6
+ valid: readonly string[];
7
+ /** Whether the type draws a control of its own. */
8
+ control: boolean;
9
+ }
10
+ /** The operators DataViews 20 picks one value with. */
11
+ export declare const SINGLE_OPERATORS: readonly string[];
12
+ /** The field types DataViews 20 knows. */
13
+ export declare const TYPE_NAMES: (string | undefined)[];
14
+ /** The controls DataViews 20 draws, by the name a field's Edit gives. */
15
+ export declare const CONTROLS: readonly string[];
16
+ /**
17
+ * Returns how DataViews 20 filters a field of the given type.
18
+ * @param type - The field type, none when undefined.
19
+ * @returns The offer of the type, the untyped one for a type DataViews does not know.
20
+ */
21
+ export declare function offerOf(type: string | undefined): TypeOffer;
@@ -0,0 +1,89 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ /** The operators DataViews 20 picks one value with. */
3
+ export const SINGLE_OPERATORS = [
4
+ 'is',
5
+ 'isNot',
6
+ 'lessThan',
7
+ 'greaterThan',
8
+ 'lessThanOrEqual',
9
+ 'greaterThanOrEqual',
10
+ 'before',
11
+ 'after',
12
+ 'beforeInc',
13
+ 'afterInc',
14
+ 'contains',
15
+ 'notContains',
16
+ 'startsWith',
17
+ 'on',
18
+ 'notOn',
19
+ ];
20
+ /** Every operator DataViews 20 knows. */
21
+ const ALL_OPERATORS = ['isAny', 'isNone', 'isAll', 'isNotAll', 'between', 'inThePast', 'over', ...SINGLE_OPERATORS];
22
+ /** The operators a text field may name. */
23
+ const TEXT_VALID = ['is', 'isNot', 'contains', 'notContains', 'startsWith', 'isAny', 'isNone', 'isNotAll'];
24
+ /** The operators a number field filters with when it names none. */
25
+ const NUMBER_DEFAULTS = ['is', 'isNot', 'lessThan', 'greaterThan', 'lessThanOrEqual', 'greaterThanOrEqual', 'between'];
26
+ /** The operators every date and time type takes. */
27
+ const MOMENT = ['on', 'notOn', 'before', 'after', 'beforeInc', 'afterInc'];
28
+ /** The operators a date and time field takes. */
29
+ const DATETIME = [...MOMENT, 'inThePast', 'over'];
30
+ /** How DataViews 20 filters a text field. */
31
+ const TEXT = { defaults: ['isAny', 'isNone'], valid: TEXT_VALID, control: true };
32
+ /** How DataViews 20 filters a number field. */
33
+ const NUMBER = {
34
+ defaults: NUMBER_DEFAULTS,
35
+ valid: [...NUMBER_DEFAULTS, 'isAny', 'isNone', 'isNotAll'],
36
+ control: true,
37
+ };
38
+ /** How DataViews 20 filters each field type it knows, by type name. */
39
+ const TYPE_OFFERS = new Map([
40
+ ['text', TEXT],
41
+ ['email', TEXT],
42
+ ['telephone', TEXT],
43
+ ['url', TEXT],
44
+ ['integer', NUMBER],
45
+ ['number', NUMBER],
46
+ ['datetime', { defaults: DATETIME, valid: DATETIME, control: true }],
47
+ ['date', { defaults: [...DATETIME, 'between'], valid: [...DATETIME, 'between'], control: true }],
48
+ ['time', { defaults: [...MOMENT, 'between'], valid: [...MOMENT, 'between'], control: true }],
49
+ ['boolean', { defaults: ['is', 'isNot'], valid: ['is', 'isNot'], control: true }],
50
+ ['array', { defaults: ['isAny', 'isNone'], valid: ['isAny', 'isNone', 'isAll', 'isNotAll'], control: true }],
51
+ ['color', { defaults: ['isAny', 'isNone'], valid: ['is', 'isNot', 'isAny', 'isNone'], control: true }],
52
+ ['media', { defaults: [], valid: [], control: false }],
53
+ ['password', { defaults: [], valid: [], control: true }],
54
+ ]);
55
+ /** How DataViews 20 filters a field of no type, or of a type it does not know. */
56
+ const UNTYPED = { defaults: ['is', 'isNot'], valid: ALL_OPERATORS, control: false };
57
+ /** The field types DataViews 20 knows. */
58
+ export const TYPE_NAMES = [...TYPE_OFFERS.keys()];
59
+ /** The controls DataViews 20 draws, by the name a field's Edit gives. */
60
+ export const CONTROLS = [
61
+ 'adaptiveSelect',
62
+ 'array',
63
+ 'checkbox',
64
+ 'color',
65
+ 'combobox',
66
+ 'datetime',
67
+ 'date',
68
+ 'email',
69
+ 'telephone',
70
+ 'url',
71
+ 'integer',
72
+ 'number',
73
+ 'password',
74
+ 'radio',
75
+ 'select',
76
+ 'text',
77
+ 'time',
78
+ 'toggle',
79
+ 'textarea',
80
+ 'toggleGroup',
81
+ ];
82
+ /**
83
+ * Returns how DataViews 20 filters a field of the given type.
84
+ * @param type - The field type, none when undefined.
85
+ * @returns The offer of the type, the untyped one for a type DataViews does not know.
86
+ */
87
+ export function offerOf(type) {
88
+ return TYPE_OFFERS.get(type) ?? UNTYPED;
89
+ }
package/dist/index.d.ts CHANGED
@@ -2,7 +2,9 @@ export { AdminRoot } from './admin-root.js';
2
2
  export type { AdminRootProps } from './admin-root.js';
3
3
  export { InitialsAvatar } from './avatar.js';
4
4
  export type { InitialsAvatarProps } from './avatar.js';
5
- export { DENSE_BREAKPOINT, EDGE_BREAKPOINT, RAIL_BREAKPOINT, SMALL_VIEWPORT } from './breakpoints.js';
5
+ export { DENSE_BREAKPOINT, EDGE_BREAKPOINT, RAIL_BREAKPOINT, SHEET_BREAKPOINT, SMALL_VIEWPORT, TITLE_BREAKPOINT, } from './breakpoints.js';
6
+ export { useBulkRun } from './bulk-run.js';
7
+ export type { BulkRun } from './bulk-run.js';
6
8
  export { bulkNotes, runEach } from './bulk.js';
7
9
  export type { BulkFailure, BulkNotes, BulkOutcome, BulkWords } from './bulk.js';
8
10
  export { ConfirmBody } from './confirm.js';
@@ -17,6 +19,8 @@ export { LIST_CHROME_DOMAIN, listChromeCatalogFor } from './list-chrome.js';
17
19
  export type { ListChromeCatalog } from './list-chrome.js';
18
20
  export { ListEmpty } from './list-empty.js';
19
21
  export type { ListEmptyProps } from './list-empty.js';
22
+ export { useListRun } from './list-run.js';
23
+ export type { ListRun, ListRunState, RunSettled } from './list-run.js';
20
24
  export { LoadingRows, LoadingScreen } from './loading.js';
21
25
  export { LogItem, LogList, LogTime } from './log-list.js';
22
26
  export type { LogItemProps, LogListProps, LogTimeProps } from './log-list.js';
@@ -32,12 +36,16 @@ export { useRowKeys } from './row-keys.js';
32
36
  export type { RowBounds, RowKeys } from './row-keys.js';
33
37
  export { RepeatRows, RowControls } from './rows.js';
34
38
  export type { RepeatRowsProps, RowControlsProps, RowLabels } from './rows.js';
35
- export { pageWindow, paginationOf, useServerPaging } from './server-page.js';
39
+ export { RunConfirm } from './run-confirm.js';
40
+ export type { RunConfirmProps } from './run-confirm.js';
41
+ export { offeredSize, pageWindow, paginationOf, sizedView, useServerPaging } from './server-page.js';
36
42
  export type { PagedView, PageWindow, PaginationInfo, ServedPage, ServedSize, ServerPaging } from './server-page.js';
37
43
  export { Toaster, useToaster } from './toaster.js';
38
44
  export type { ToastAction, ToasterHandle, ToasterProps } from './toaster.js';
39
45
  export { useMediaQuery } from './use-media-query.js';
40
46
  export { useTokenDocument } from './use-token-document.js';
47
+ export { offeredView, viewNarrows } from './view-guard.js';
48
+ export type { GuardedField, OfferedView, ViewGuard } from './view-guard.js';
41
49
  /**
42
50
  * The design system version window this build was tested against.
43
51
  */
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  export { AdminRoot } from './admin-root.js';
3
3
  export { InitialsAvatar } from './avatar.js';
4
- export { DENSE_BREAKPOINT, EDGE_BREAKPOINT, RAIL_BREAKPOINT, SMALL_VIEWPORT } from './breakpoints.js';
4
+ export { DENSE_BREAKPOINT, EDGE_BREAKPOINT, RAIL_BREAKPOINT, SHEET_BREAKPOINT, SMALL_VIEWPORT, TITLE_BREAKPOINT, } from './breakpoints.js';
5
+ export { useBulkRun } from './bulk-run.js';
5
6
  export { bulkNotes, runEach } from './bulk.js';
6
7
  export { ConfirmBody } from './confirm.js';
7
8
  export { FileButton } from './file-button.js';
@@ -9,6 +10,7 @@ export { Frame } from './frame.js';
9
10
  export { keyFromLabel } from './keys.js';
10
11
  export { LIST_CHROME_DOMAIN, listChromeCatalogFor } from './list-chrome.js';
11
12
  export { ListEmpty } from './list-empty.js';
13
+ export { useListRun } from './list-run.js';
12
14
  export { LoadingRows, LoadingScreen } from './loading.js';
13
15
  export { LogItem, LogList, LogTime } from './log-list.js';
14
16
  export { NavScreen } from './nav-screen.js';
@@ -17,10 +19,12 @@ export { PageTab, PageTabs } from './page-tabs.js';
17
19
  export { RenameBody } from './rename.js';
18
20
  export { useRowKeys } from './row-keys.js';
19
21
  export { RepeatRows, RowControls } from './rows.js';
20
- export { pageWindow, paginationOf, useServerPaging } from './server-page.js';
22
+ export { RunConfirm } from './run-confirm.js';
23
+ export { offeredSize, pageWindow, paginationOf, sizedView, useServerPaging } from './server-page.js';
21
24
  export { Toaster, useToaster } from './toaster.js';
22
25
  export { useMediaQuery } from './use-media-query.js';
23
26
  export { useTokenDocument } from './use-token-document.js';
27
+ export { offeredView, viewNarrows } from './view-guard.js';
24
28
  /**
25
29
  * The design system version window this build was tested against.
26
30
  */
@@ -133,6 +133,7 @@ const catalog = {
133
133
  'Less than or equal': ['Inferior a o igual'],
134
134
  List: ['Lista'],
135
135
  'List of: %1$s': ['Lista de: %1$s'],
136
+ Loading: ['Cargando'],
136
137
  'M j, Y g:i a': ['j M Y H:i'],
137
138
  March: ['marzo'],
138
139
  'March abbreviation\u0004Mar': ['Mar'],
@@ -173,6 +174,7 @@ const catalog = {
173
174
  'Row %d': ['Fila %d'],
174
175
  Sat: ['Sáb'],
175
176
  Saturday: ['sábado'],
177
+ 'Scrollable section': ['Sección desplazable'],
176
178
  Search: ['Buscar'],
177
179
  'Search items': ['Buscar elementos'],
178
180
  'Select all': ['Seleccionar todo'],
@@ -20,6 +20,7 @@ const catalog = {
20
20
  'July abbreviation\u0004Jul': ['Juil'],
21
21
  June: ['juin'],
22
22
  'June abbreviation\u0004Jun': ['Juin'],
23
+ Loading: ['Chargement'],
23
24
  'M j, Y g:i a': ['d F Y G\\hi'],
24
25
  March: ['mars'],
25
26
  'March abbreviation\u0004Mar': ['Mar'],
@@ -34,6 +35,7 @@ const catalog = {
34
35
  PM: ['PM'],
35
36
  Sat: ['Sam'],
36
37
  Saturday: ['samedi'],
38
+ 'Scrollable section': ['Section défilable'],
37
39
  September: ['septembre'],
38
40
  'September abbreviation\u0004Sep': ['Sep'],
39
41
  Sun: ['Dim'],
@@ -0,0 +1,24 @@
1
+ import type { RefObject } from 'react';
2
+ /** Settles a run on its list: shows its failure, none when all finished, and focuses the list once an item moved. */
3
+ export type RunSettled = (failure: string | undefined, moved: boolean) => void;
4
+ /** What a list does around a run over its items. */
5
+ export interface ListRun {
6
+ /** Clears the failure the last run left above the list and returns what settles this run. */
7
+ onStart: () => RunSettled;
8
+ }
9
+ /** The failure a list shows above its rows, the run its actions start and the region a finished run focuses. */
10
+ export interface ListRunState {
11
+ /** The failure of the last run on this list, absent while none failed. */
12
+ failure?: string;
13
+ /** What the list does around a run, the same object while the list stays the same. */
14
+ run: ListRun;
15
+ /** The list region a finished run focuses, handed to `Page` as `listRef`. */
16
+ region: RefObject<HTMLDivElement | null>;
17
+ }
18
+ /**
19
+ * Holds the failure shown above one list and the region a finished run focuses, and forgets both when the list changes.
20
+ * @param scope - Names the list on show.
21
+ * @param onChangeSelection - Replaces the ticked rows, emptied when the list changes.
22
+ * @returns The failure on show, the run and the region.
23
+ */
24
+ export declare function useListRun(scope: string, onChangeSelection: (selection: string[]) => void): ListRunState;
@@ -0,0 +1,43 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { useLayoutEffect, useMemo, useRef, useState } from 'react';
3
+ /**
4
+ * Holds the failure shown above one list and the region a finished run focuses, and forgets both when the list changes.
5
+ * @param scope - Names the list on show.
6
+ * @param onChangeSelection - Replaces the ticked rows, emptied when the list changes.
7
+ * @returns The failure on show, the run and the region.
8
+ */
9
+ export function useListRun(scope, onChangeSelection) {
10
+ const [shown, setShown] = useState({ scope });
11
+ const region = useRef(null);
12
+ const latest = useRef(0);
13
+ const committed = useRef(scope);
14
+ useLayoutEffect(() => {
15
+ latest.current += 1;
16
+ }, [scope]);
17
+ useLayoutEffect(() => {
18
+ if (committed.current !== scope) {
19
+ committed.current = scope;
20
+ onChangeSelection([]);
21
+ }
22
+ }, [scope, onChangeSelection]);
23
+ if (shown.scope !== scope) {
24
+ setShown({ scope });
25
+ }
26
+ const run = useMemo(() => ({
27
+ onStart: () => {
28
+ latest.current += 1;
29
+ const id = latest.current;
30
+ setShown({ scope });
31
+ return (failure, moved) => {
32
+ if (latest.current !== id) {
33
+ return;
34
+ }
35
+ setShown({ scope, failure });
36
+ if (moved) {
37
+ region.current?.focus();
38
+ }
39
+ };
40
+ },
41
+ }), [scope]);
42
+ return { failure: shown.failure, run, region };
43
+ }
package/dist/page.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Text } from '@wordpress/ui';
2
- import type { ComponentProps, ReactNode } from 'react';
2
+ import type { ComponentProps, ReactNode, Ref } from 'react';
3
3
  type TextVariant = ComponentProps<typeof Text>['variant'];
4
4
  /**
5
5
  * Renders a screen's title as the page heading.
@@ -28,15 +28,19 @@ export interface PageProps {
28
28
  tabs?: ReactNode;
29
29
  aside?: ReactNode;
30
30
  list?: boolean;
31
+ /** The name of the list region. */
32
+ listLabel?: string;
33
+ /** The ref to the list region. */
34
+ listRef?: Ref<HTMLDivElement>;
31
35
  className?: string;
32
36
  children: ReactNode;
33
37
  }
34
38
  /**
35
39
  * Renders a screen: a header with the title, actions and subtitle, then optional tabs and the content.
36
- * @param props - The title, subtitle, actions, tabs, aside, list flag, extra class and content.
40
+ * @param props - The title, subtitle, actions, tabs, aside, list flag, list name and ref, extra class and content.
37
41
  * @returns The page element.
38
42
  */
39
- export declare function Page({ title, subtitle, actions, tabs, aside, list, className, children }: PageProps): import("react").JSX.Element;
43
+ export declare function Page({ title, subtitle, actions, tabs, aside, list, listLabel, listRef, className, children, }: PageProps): import("react").JSX.Element;
40
44
  /**
41
45
  * Renders a failure message that a screen reader announces.
42
46
  * @param props - The message to announce.
package/dist/page.js CHANGED
@@ -19,14 +19,24 @@ export function SectionTitle({ children, level = 2, id, tabIndex, }) {
19
19
  const second = level === 2;
20
20
  return (_jsx(Text, { variant: second ? 'heading-lg' : 'heading-md', render: second ? _jsx("h2", {}) : _jsx("h3", {}), id: id, tabIndex: tabIndex, children: children }));
21
21
  }
22
+ /**
23
+ * Returns the props that let code focus a list with a name or a ref, and name a list region given a label.
24
+ * @param label - The name of the list region.
25
+ * @param reached - Whether code holds a ref to the list.
26
+ * @returns A tab index that keeps the list out of the tab order, and the role and the name of a named one.
27
+ */
28
+ function regionOf(label, reached) {
29
+ const focus = label === undefined && !reached ? {} : { tabIndex: -1 };
30
+ return label === undefined ? focus : { ...focus, role: 'region', 'aria-label': label };
31
+ }
22
32
  /**
23
33
  * Renders a screen: a header with the title, actions and subtitle, then optional tabs and the content.
24
- * @param props - The title, subtitle, actions, tabs, aside, list flag, extra class and content.
34
+ * @param props - The title, subtitle, actions, tabs, aside, list flag, list name and ref, extra class and content.
25
35
  * @returns The page element.
26
36
  */
27
- export function Page({ title, subtitle, actions, tabs, aside, list = false, className, children }) {
37
+ export function Page({ title, subtitle, actions, tabs, aside, list = false, listLabel, listRef, className, children, }) {
28
38
  const classes = className === undefined ? 'godmin-page' : `godmin-page ${className}`;
29
- return (_jsxs(Stack, { direction: "column", gap: "lg", className: classes, children: [_jsxs(Stack, { direction: "column", render: _jsx("header", {}), className: "godmin-page__header", children: [_jsxs(Stack, { direction: "row", wrap: "wrap", gap: "md", align: "center", justify: "space-between", className: "godmin-page__head", children: [_jsx(PageTitle, { children: title }), actions !== undefined && (_jsx(Stack, { direction: "row", gap: "sm", align: "center", children: actions }))] }), subtitle !== undefined && (_jsx(Text, { variant: "body-md", render: _jsx("p", {}), className: "godmin-page__subtitle", children: subtitle }))] }), tabs !== undefined && _jsx("div", { className: "godmin-page__tabs", children: tabs }), _jsx(PageBody, { aside: aside, children: list ? _jsx("div", { className: "godmin-page__list", children: children }) : children })] }));
39
+ return (_jsxs(Stack, { direction: "column", gap: "lg", className: classes, children: [_jsxs(Stack, { direction: "column", render: _jsx("header", {}), className: "godmin-page__header", children: [_jsxs(Stack, { direction: "row", wrap: "wrap", gap: "md", align: "center", justify: "space-between", className: "godmin-page__head", children: [_jsx(PageTitle, { children: title }), actions !== undefined && (_jsx(Stack, { direction: "row", gap: "sm", align: "center", children: actions }))] }), subtitle !== undefined && (_jsx(Text, { variant: "body-md", render: _jsx("p", {}), className: "godmin-page__subtitle", children: subtitle }))] }), tabs !== undefined && _jsx("div", { className: "godmin-page__tabs", children: tabs }), _jsx(PageBody, { aside: aside, children: list ? (_jsx("div", { className: "godmin-page__list", ref: listRef, ...regionOf(listLabel, listRef !== undefined), children: children })) : (children) })] }));
30
40
  }
31
41
  /**
32
42
  * Renders a page's content, beside its aside when it has one.
package/dist/rename.d.ts CHANGED
@@ -17,7 +17,7 @@ export interface RenameBodyProps {
17
17
  onCancel?: () => void;
18
18
  }
19
19
  /**
20
- * Renders the body of a rename modal: the name field, a failure notice, a minimal neutral Cancel and the submit button.
20
+ * Renders the body of a rename modal: the name field, a failure notice, an accent text Cancel and the submit button.
21
21
  * @param props - The current name, the labels, the busy flag, the failure and the handlers.
22
22
  * @returns The rename form.
23
23
  */
package/dist/rename.js CHANGED
@@ -4,7 +4,7 @@ import { Button, InputControl, Stack } from '@wordpress/ui';
4
4
  import { useState } from 'react';
5
5
  import { ErrorNotice } from './page.js';
6
6
  /**
7
- * Renders the body of a rename modal: the name field, a failure notice, a minimal neutral Cancel and the submit button.
7
+ * Renders the body of a rename modal: the name field, a failure notice, an accent text Cancel and the submit button.
8
8
  * @param props - The current name, the labels, the busy flag, the failure and the handlers.
9
9
  * @returns The rename form.
10
10
  */
@@ -16,5 +16,5 @@ export function RenameBody({ name, fieldLabel, submitLabel, cancelLabel, busy =
16
16
  if (writable) {
17
17
  onSubmit(value);
18
18
  }
19
- }, children: _jsxs(Stack, { direction: "column", gap: "lg", children: [_jsx(InputControl, { label: fieldLabel, value: value, onChange: (event) => setValue(event.target.value) }), failure === undefined ? null : _jsx(ErrorNotice, { children: failure }), _jsxs(Stack, { direction: "row", gap: "sm", justify: "flex-end", children: [_jsx(Button, { variant: "minimal", tone: "neutral", disabled: busy, onClick: onCancel, children: cancelLabel }), _jsx(Button, { type: "submit", loading: busy, disabled: !writable, children: submitLabel })] })] }) }));
19
+ }, children: _jsxs(Stack, { direction: "column", gap: "lg", children: [_jsx(InputControl, { label: fieldLabel, value: value, onChange: (event) => setValue(event.target.value) }), failure === undefined ? null : _jsx(ErrorNotice, { children: failure }), _jsxs(Stack, { direction: "row", gap: "sm", justify: "flex-end", children: [_jsx(Button, { variant: "minimal", disabled: busy, onClick: onCancel, children: cancelLabel }), _jsx(Button, { type: "submit", loading: busy, disabled: !writable, children: submitLabel })] })] }) }));
20
20
  }
@@ -0,0 +1,22 @@
1
+ import type { ReactNode } from 'react';
2
+ /** The props of a run confirm, the first two as a DataViews modal hands them. */
3
+ export interface RunConfirmProps<Item> {
4
+ /** The items the action runs over. */
5
+ items: Item[];
6
+ /** Closes the modal. */
7
+ closeModal?: () => void;
8
+ /** The question the modal asks. */
9
+ children: ReactNode;
10
+ /** The label of the button that starts the run. */
11
+ confirmLabel: string;
12
+ /** The label of the button that closes the modal. */
13
+ cancelLabel: string;
14
+ /** Runs the action over the items, settling once the list shows how it went. */
15
+ run: (items: Item[]) => Promise<void>;
16
+ }
17
+ /**
18
+ * Renders a confirmation that runs the action, keeps Cancel inert while it runs and closes once it settles.
19
+ * @param props - The items, the close handler, the question, the labels and the run.
20
+ * @returns The confirmation body.
21
+ */
22
+ export declare function RunConfirm<Item>({ items, closeModal, children, confirmLabel, cancelLabel, run, }: RunConfirmProps<Item>): import("react").JSX.Element;
@@ -0,0 +1,21 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { useState } from 'react';
4
+ import { ConfirmBody } from './confirm.js';
5
+ /**
6
+ * Renders a confirmation that runs the action, keeps Cancel inert while it runs and closes once it settles.
7
+ * @param props - The items, the close handler, the question, the labels and the run.
8
+ * @returns The confirmation body.
9
+ */
10
+ export function RunConfirm({ items, closeModal, children, confirmLabel, cancelLabel, run, }) {
11
+ const [busy, setBusy] = useState(false);
12
+ return (_jsx(ConfirmBody, { confirmLabel: confirmLabel, cancelLabel: cancelLabel, busy: busy, onCancel: closeModal, onConfirm: () => {
13
+ setBusy(true);
14
+ void Promise.resolve()
15
+ .then(() => run(items))
16
+ .finally(() => {
17
+ setBusy(false);
18
+ closeModal?.();
19
+ });
20
+ }, children: children }));
21
+ }
@@ -54,6 +54,21 @@ export declare function pageWindow({ page, perPage }: PagedView, last?: ServedSi
54
54
  * @returns The pagination info.
55
55
  */
56
56
  export declare function paginationOf(page: ServedPage | undefined): PaginationInfo;
57
+ /**
58
+ * Returns the page size a list shows: the one asked while the sizes offer it or are unknown, the fallback otherwise.
59
+ * @param asked - The page size the view holds, absent when it names none.
60
+ * @param sizes - The page sizes the list offers, absent while unknown.
61
+ * @param fallback - The size the list opens on, taken in place of one the sizes do not offer.
62
+ * @returns The page size.
63
+ */
64
+ export declare function offeredSize(asked: number | undefined, sizes: readonly number[] | undefined, fallback: number | undefined): number | undefined;
65
+ /**
66
+ * Returns the part of a view a server pages by, leaving its page size out while the sizes are unknown.
67
+ * @param view - The view the list shows.
68
+ * @param sizes - The page sizes the list offers, absent while unknown.
69
+ * @returns The page alone while the sizes are unknown, else the page and its size.
70
+ */
71
+ export declare function sizedView(view: PagedView, sizes: readonly number[] | undefined): PagedView;
57
72
  /**
58
73
  * Holds the size the server last served and answers the rows to ask for the page a view shows.
59
74
  * @param view - The view the list shows.
@@ -1,5 +1,14 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  import { useState } from 'react';
3
+ /**
4
+ * Reports whether the size the server last served answered this same ask with rows on the page.
5
+ * @param limit - The rows asked for on one page, or null for the size the server serves by default.
6
+ * @param last - The size the server last served, absent before it served any.
7
+ * @returns Whether that size answered the ask and is above zero.
8
+ */
9
+ function answers(limit, last) {
10
+ return last !== undefined && last.asked === limit && last.served > 0;
11
+ }
3
12
  /**
4
13
  * Returns how many rows each page before the shown one holds.
5
14
  * @param limit - The rows asked for on one page, or null for the size the server serves by default.
@@ -7,10 +16,7 @@ import { useState } from 'react';
7
16
  * @returns The size served when it answered this same ask, the size asked otherwise.
8
17
  */
9
18
  function stepOf(limit, last) {
10
- if (last !== undefined && last.asked === limit && last.served > 0) {
11
- return last.served;
12
- }
13
- return limit ?? 0;
19
+ return answers(limit, last) ? last.served : (limit ?? 0);
14
20
  }
15
21
  /**
16
22
  * Returns the rows to ask the server for the page a view shows.
@@ -35,6 +41,28 @@ export function paginationOf(page) {
35
41
  const totalPages = page.limit > 0 ? Math.ceil(page.total / page.limit) : Math.min(page.total, 1);
36
42
  return { totalItems: page.total, totalPages };
37
43
  }
44
+ /**
45
+ * Returns the page size a list shows: the one asked while the sizes offer it or are unknown, the fallback otherwise.
46
+ * @param asked - The page size the view holds, absent when it names none.
47
+ * @param sizes - The page sizes the list offers, absent while unknown.
48
+ * @param fallback - The size the list opens on, taken in place of one the sizes do not offer.
49
+ * @returns The page size.
50
+ */
51
+ export function offeredSize(asked, sizes, fallback) {
52
+ if (sizes === undefined || sizes.some((size) => size === asked)) {
53
+ return asked;
54
+ }
55
+ return fallback;
56
+ }
57
+ /**
58
+ * Returns the part of a view a server pages by, leaving its page size out while the sizes are unknown.
59
+ * @param view - The view the list shows.
60
+ * @param sizes - The page sizes the list offers, absent while unknown.
61
+ * @returns The page alone while the sizes are unknown, else the page and its size.
62
+ */
63
+ export function sizedView(view, sizes) {
64
+ return sizes === undefined ? { page: view.page } : { page: view.page, perPage: view.perPage };
65
+ }
38
66
  /**
39
67
  * Holds the size the server last served and answers the rows to ask for the page a view shows.
40
68
  * @param view - The view the list shows.
package/dist/testing.d.ts CHANGED
@@ -30,12 +30,22 @@ export type LoadModule = () => Promise<Record<string, unknown>>;
30
30
  */
31
31
  export declare function assertElementPatched(load?: LoadModule): Promise<void>;
32
32
  /**
33
- * Sets what every media query reports, and tells its listeners.
34
- * @param viewport - Whether queries should report a match.
33
+ * What the media queries report: one answer for every query, or each width query answered by a width in pixels.
35
34
  */
36
- export declare function setViewport(viewport: {
35
+ export type TestViewport = {
37
36
  matches: boolean;
38
- }): void;
37
+ } | {
38
+ width: number;
39
+ };
40
+ /**
41
+ * Sets what the media queries report, and tells their listeners.
42
+ * @param next - Whether every query reports a match, or the width in pixels the width queries are answered by.
43
+ */
44
+ export declare function setViewport(next: TestViewport): void;
45
+ /**
46
+ * Makes every element report one layout box until the test ends, as a browser does for an element on screen.
47
+ */
48
+ export declare function stubLayout(): void;
39
49
  /**
40
50
  * Prepares the test environment a design system application needs.
41
51
  */
package/dist/testing.js CHANGED
@@ -2,7 +2,7 @@ import { jsx as _jsx } from "react/jsx-runtime";
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
  import { cleanup, configure, render } from '@testing-library/react';
4
4
  import { Badge, Button, Text } from '@wordpress/ui';
5
- import { afterEach } from 'vitest';
5
+ import { afterEach, vi } from 'vitest';
6
6
  import { AdminRoot } from './admin-root.js';
7
7
  /**
8
8
  * The elements the design system announces through rather than displays.
@@ -56,19 +56,27 @@ export async function assertElementPatched(load = () => import('@wordpress/eleme
56
56
  }
57
57
  }
58
58
  /**
59
- * Whether every media query currently reports a match.
59
+ * The viewport the media queries currently read.
60
60
  */
61
- let viewportMatches = false;
61
+ let viewport = { matches: false };
62
62
  /**
63
63
  * The listeners registered on the media query lists handed out so far.
64
64
  */
65
65
  const viewportListeners = new Set();
66
66
  /**
67
- * Sets what every media query reports, and tells its listeners.
68
- * @param viewport - Whether queries should report a match.
67
+ * One width condition of a media query, such as `(max-width: 599px)`.
69
68
  */
70
- export function setViewport(viewport) {
71
- viewportMatches = viewport.matches;
69
+ const WIDTH_CONDITION = /^\(\s*(min|max)-width\s*:\s*(\d+(?:\.\d+)?)px\s*\)$/;
70
+ /**
71
+ * The media types a screen matches, such as `screen` or `only all`.
72
+ */
73
+ const SCREEN_MEDIA = /^(?:only\s+)?(?:all|screen)$/;
74
+ /**
75
+ * Sets what the media queries report, and tells their listeners.
76
+ * @param next - Whether every query reports a match, or the width in pixels the width queries are answered by.
77
+ */
78
+ export function setViewport(next) {
79
+ viewport = next;
72
80
  for (const listener of [...viewportListeners]) {
73
81
  listener();
74
82
  }
@@ -77,9 +85,55 @@ export function setViewport(viewport) {
77
85
  * Returns every media query to reporting no match, with no listeners left.
78
86
  */
79
87
  function resetViewport() {
80
- viewportMatches = false;
88
+ viewport = { matches: false };
81
89
  viewportListeners.clear();
82
90
  }
91
+ /**
92
+ * Tells whether one condition of a media query holds at a width.
93
+ * @param condition - The condition, such as `screen` or `(max-width: 599px)`.
94
+ * @param width - The viewport width in pixels.
95
+ * @returns Whether it holds, always for a screen media type, never for a condition other than a width in pixels.
96
+ */
97
+ function conditionHolds(condition, width) {
98
+ const part = condition.trim();
99
+ if (SCREEN_MEDIA.test(part)) {
100
+ return true;
101
+ }
102
+ const found = WIDTH_CONDITION.exec(part);
103
+ if (found === null) {
104
+ return false;
105
+ }
106
+ const bound = Number(found[2]);
107
+ return found[1] === 'min' ? width >= bound : width <= bound;
108
+ }
109
+ /**
110
+ * Tells whether a media query list matches at a width.
111
+ * @param media - The media query text, queries parted by commas and conditions joined by and.
112
+ * @param width - The viewport width in pixels.
113
+ * @returns Whether every condition of any one query holds.
114
+ */
115
+ function matchesWidth(media, width) {
116
+ return media
117
+ .toLowerCase()
118
+ .split(',')
119
+ .some((query) => conditionsOf(query).every((condition) => conditionHolds(condition, width)));
120
+ }
121
+ /**
122
+ * Returns the conditions a media query joins with and, its spaces folded to one.
123
+ * @param query - One query of a media query list, in lower case.
124
+ * @returns The conditions, such as `screen` and `(max-width: 599px)`.
125
+ */
126
+ function conditionsOf(query) {
127
+ return query.trim().split(/\s+/).join(' ').split(' and ');
128
+ }
129
+ /**
130
+ * Answers a media query from the viewport this module controls.
131
+ * @param media - The media query text.
132
+ * @returns Whether the query matches.
133
+ */
134
+ function answer(media) {
135
+ return 'width' in viewport ? matchesWidth(media, viewport.width) : viewport.matches;
136
+ }
83
137
  /**
84
138
  * Returns a media query list reading the viewport this module controls.
85
139
  * @param media - The media query text.
@@ -89,7 +143,7 @@ function mediaQueryList(media) {
89
143
  return {
90
144
  media,
91
145
  get matches() {
92
- return viewportMatches;
146
+ return answer(media);
93
147
  },
94
148
  addEventListener: (_type, listener) => {
95
149
  viewportListeners.add(listener);
@@ -145,6 +199,25 @@ function installResizeObserver() {
145
199
  };
146
200
  }
147
201
  }
202
+ /** The one layout box every element reports while the layout is stubbed. */
203
+ const LAYOUT_BOX = { x: 0, y: 0, width: 1, height: 1, top: 0, right: 1, bottom: 1, left: 0 };
204
+ /** The stub that gives every element a layout box, held until the test ends. */
205
+ let layoutStub;
206
+ /**
207
+ * Makes every element report one layout box until the test ends, as a browser does for an element on screen.
208
+ */
209
+ export function stubLayout() {
210
+ layoutStub = vi
211
+ .spyOn(Element.prototype, 'getClientRects')
212
+ .mockReturnValue([LAYOUT_BOX]);
213
+ }
214
+ /**
215
+ * Gives every element back the layout jsdom reports, none.
216
+ */
217
+ function restoreLayout() {
218
+ layoutStub?.mockRestore();
219
+ layoutStub = undefined;
220
+ }
148
221
  /**
149
222
  * Prepares the test environment a design system application needs.
150
223
  */
@@ -156,6 +229,7 @@ export function installTestEnvironment() {
156
229
  afterEach(cleanup);
157
230
  afterEach(clearAnnouncements);
158
231
  afterEach(resetViewport);
232
+ afterEach(restoreLayout);
159
233
  }
160
234
  /**
161
235
  * Returns the classes the outer element of a tree draws with, removing the tree once read.
@@ -0,0 +1,53 @@
1
+ import type { ListSortDirection, ListViewShape } from './list-view.js';
2
+ /** The parts of a list field the guard reads, as a DataViews field holds them. */
3
+ export interface GuardedField {
4
+ /** The id a sort or a filter names. */
5
+ id: string;
6
+ /** The DataViews type of the field, such as text or media. */
7
+ type?: string;
8
+ /** Whether the list sorts by the field, when absent true unless the field holds media or a password. */
9
+ enableSorting?: boolean;
10
+ /** The operators the field filters with, its type's defaults when it names none, none when false. */
11
+ filterBy?: {
12
+ operators?: readonly string[];
13
+ } | false;
14
+ /** The values a filter on the field may hold, any value its check takes when absent or empty. */
15
+ elements?: readonly {
16
+ value: unknown;
17
+ }[];
18
+ /** Loads the values a filter on the field may hold in place of elements, any value its check takes then. */
19
+ getElements?: unknown;
20
+ /** The control that edits the field: a component, a control name or a control config. */
21
+ Edit?: unknown;
22
+ }
23
+ /** How a field with no elements to match checks a filter value, keyed by field id. */
24
+ type ValueChecks = Record<string, (value: unknown) => boolean>;
25
+ /** The order a list falls back to and how it checks a filter value with no elements to match. */
26
+ export interface ViewGuard {
27
+ /** The order the list opens in, taken in place of a sort the fields do not offer. */
28
+ opening: {
29
+ field: string;
30
+ direction: ListSortDirection;
31
+ };
32
+ /** How a field with no elements to match checks a filter value, keyed by field id, any value taken when absent. */
33
+ checks?: ValueChecks;
34
+ }
35
+ /** A view as its fields can draw it, every filter it holds one the list offers. */
36
+ export type OfferedView<V extends ListViewShape> = V & {
37
+ filters: NonNullable<V['filters']>;
38
+ };
39
+ /**
40
+ * Reports whether a search, or a filter holding a value, narrows a list.
41
+ * @param view - The view the list shows.
42
+ * @returns Whether the list may show fewer items than it holds.
43
+ */
44
+ export declare function viewNarrows(view: Pick<ListViewShape, 'search' | 'filters'>): boolean;
45
+ /**
46
+ * Returns the view as its fields can draw it, a sort or a filter naming what the list never offers dropped.
47
+ * @param view - The view the address and the reader hold.
48
+ * @param fields - The fields the list shows.
49
+ * @param guard - The opening order and the value checks.
50
+ * @returns The view the list shows and asks the server for.
51
+ */
52
+ export declare function offeredView<V extends ListViewShape>(view: V, fields: readonly GuardedField[], guard: ViewGuard): OfferedView<V>;
53
+ export {};
@@ -0,0 +1,146 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { CONTROLS, offerOf, SINGLE_OPERATORS } from './filter-offer.js';
3
+ /** The field types DataViews never sorts by unless the field says it sorts. */
4
+ const UNSORTED_TYPES = ['media', 'password'];
5
+ /**
6
+ * Reports whether a filter holds a value, a pick of none being no value.
7
+ * @param value - The value the filter holds.
8
+ * @returns Whether the value narrows the list.
9
+ */
10
+ function holdsValue(value) {
11
+ return Array.isArray(value) ? value.length > 0 : value !== undefined;
12
+ }
13
+ /**
14
+ * Reports whether a search, or a filter holding a value, narrows a list.
15
+ * @param view - The view the list shows.
16
+ * @returns Whether the list may show fewer items than it holds.
17
+ */
18
+ export function viewNarrows(view) {
19
+ return Boolean(view.search) || (view.filters ?? []).some((filter) => holdsValue(filter.value));
20
+ }
21
+ /**
22
+ * Reports whether the list sorts by a field, as DataViews reads it.
23
+ * @param field - The field a sort names.
24
+ * @returns The field's own setting, else whether its type sorts.
25
+ */
26
+ function sorts(field) {
27
+ return field.enableSorting ?? !UNSORTED_TYPES.includes(field.type);
28
+ }
29
+ /**
30
+ * Reports whether a field holds the values a filter on it may pick, as DataViews reads it.
31
+ * @param field - The field a filter names.
32
+ * @returns Whether it holds at least one element or loads them.
33
+ */
34
+ function hasElements(field) {
35
+ return (field.elements?.length ?? 0) > 0 || typeof field.getElements === 'function';
36
+ }
37
+ /**
38
+ * Reports whether a field draws a control, as DataViews reads its Edit and else its type.
39
+ * @param field - The field a filter names.
40
+ * @returns Whether its Edit is a component or names a control DataViews knows, or else its type draws one.
41
+ */
42
+ function hasControl(field) {
43
+ const edit = field.Edit;
44
+ if (typeof edit === 'function') {
45
+ return true;
46
+ }
47
+ const name = typeof edit === 'object' && edit !== null ? edit.control : edit;
48
+ return typeof name === 'string' ? CONTROLS.includes(name) : offerOf(field.type).control;
49
+ }
50
+ /**
51
+ * Reports whether DataViews can draw a filter for a field, from its elements or its control.
52
+ * @param field - The field a filter names.
53
+ * @returns Whether the field has elements or a control.
54
+ */
55
+ function canDraw(field) {
56
+ return hasElements(field) || hasControl(field);
57
+ }
58
+ /**
59
+ * Returns the operators a field filters with, as DataViews resolves them.
60
+ * @param field - The field a filter names.
61
+ * @returns The named operators its type takes, else its type's defaults, none when DataViews draws no filter.
62
+ */
63
+ function operatorsOf(field) {
64
+ const filterBy = field.filterBy;
65
+ if (filterBy === false || !canDraw(field)) {
66
+ return [];
67
+ }
68
+ const offer = offerOf(field.type);
69
+ return filterBy?.operators?.filter((operator) => offer.valid.includes(operator)) ?? offer.defaults;
70
+ }
71
+ /**
72
+ * Reports whether a field picks one value, as DataViews reads it from the field's operators.
73
+ * @param operators - The operators the field filters with.
74
+ * @returns Whether any of them picks one value.
75
+ */
76
+ function picksOne(operators) {
77
+ return operators.some((operator) => SINGLE_OPERATORS.includes(operator));
78
+ }
79
+ /**
80
+ * Reports whether a value has the shape DataViews writes on a field with elements.
81
+ * @param field - The field the filter narrows by.
82
+ * @param operators - The operators the field filters with.
83
+ * @param value - The value the filter holds.
84
+ * @returns Whether it is one value where the field picks one or a list where it picks many, or it has no elements.
85
+ */
86
+ function fitsShape(field, operators, value) {
87
+ return !hasElements(field) || Array.isArray(value) !== picksOne(operators);
88
+ }
89
+ /**
90
+ * Returns the elements a filter value must be one of, as DataViews shows them.
91
+ * @param field - The field the filter narrows by.
92
+ * @returns Its elements, none when it loads its own.
93
+ */
94
+ function matchedElements(field) {
95
+ return typeof field.getElements === 'function' ? [] : (field.elements ?? []);
96
+ }
97
+ /**
98
+ * Reports whether a field takes the value a filter holds.
99
+ * @param field - The field the filter narrows by.
100
+ * @param value - The value the filter holds, one value or a pick of many.
101
+ * @param checks - How a field with no elements to match checks a value.
102
+ * @returns Whether each picked value is one of the elements, or the value passes the field's check, or it has none.
103
+ */
104
+ function takes(field, value, checks) {
105
+ const elements = matchedElements(field);
106
+ if (elements.length > 0) {
107
+ const picked = Array.isArray(value) ? value : [value];
108
+ return picked.every((one) => elements.some((element) => element.value === one));
109
+ }
110
+ const check = checks?.[field.id];
111
+ return check === undefined || check(value);
112
+ }
113
+ /**
114
+ * Reports whether a filter names a field the list filters by, with an operator and a value that field offers.
115
+ * @param filter - The filter the view carries.
116
+ * @param fields - The fields the list shows.
117
+ * @param checks - How a field with no elements to match checks a value.
118
+ * @returns Whether the list can apply the filter, one still waiting for its value included.
119
+ */
120
+ function offers(filter, fields, checks) {
121
+ const field = fields.find((held) => held.id === filter.field);
122
+ if (field === undefined) {
123
+ return false;
124
+ }
125
+ const operators = operatorsOf(field);
126
+ if (!operators.includes(filter.operator)) {
127
+ return false;
128
+ }
129
+ const value = filter.value;
130
+ return value === undefined || (fitsShape(field, operators, value) && takes(field, value, checks));
131
+ }
132
+ /**
133
+ * Returns the view as its fields can draw it, a sort or a filter naming what the list never offers dropped.
134
+ * @param view - The view the address and the reader hold.
135
+ * @param fields - The fields the list shows.
136
+ * @param guard - The opening order and the value checks.
137
+ * @returns The view the list shows and asks the server for.
138
+ */
139
+ export function offeredView(view, fields, guard) {
140
+ const sorted = fields.some((field) => field.id === view.sort?.field && sorts(field));
141
+ return {
142
+ ...view,
143
+ sort: sorted ? view.sort : { ...guard.opening },
144
+ filters: (view.filters ?? []).filter((filter) => offers(filter, fields, guard.checks)),
145
+ };
146
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gopherium/godmin",
3
- "version": "0.20.0",
3
+ "version": "0.22.0",
4
4
  "description": "The admin kit for Gopherium projects: host layer for React admin applications on the WordPress Design System.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -30,6 +30,10 @@
30
30
  "types": "./dist/dates.d.ts",
31
31
  "default": "./dist/dates.js"
32
32
  },
33
+ "./dialogs": {
34
+ "types": "./dist/dialogs.d.ts",
35
+ "default": "./dist/dialogs.js"
36
+ },
33
37
  "./router": {
34
38
  "types": "./dist/router.d.ts",
35
39
  "default": "./dist/router.js"
@@ -63,6 +67,8 @@
63
67
  "@tanstack/react-router": "^1.170.0",
64
68
  "@testing-library/react": "^16.3.2",
65
69
  "@wordpress/a11y": ">=4.57.0 <5.0.0",
70
+ "@wordpress/components": ">=42.0.0 <43.0.0",
71
+ "@wordpress/dataviews": ">=20.0.0 <21.0.0",
66
72
  "@wordpress/date": ">=5.57.0 <6.0.0",
67
73
  "@wordpress/i18n": ">=6.30.0 <7.0.0",
68
74
  "@wordpress/icons": ">=18.0.0 <19.0.0",
@@ -80,6 +86,12 @@
80
86
  "@testing-library/react": {
81
87
  "optional": true
82
88
  },
89
+ "@wordpress/components": {
90
+ "optional": true
91
+ },
92
+ "@wordpress/dataviews": {
93
+ "optional": true
94
+ },
83
95
  "@wordpress/date": {
84
96
  "optional": true
85
97
  },
@@ -102,6 +114,7 @@
102
114
  "@vitejs/plugin-react": "^6.0.3",
103
115
  "@vitest/coverage-v8": "^5.0.3",
104
116
  "@wordpress/a11y": "4.57.0",
117
+ "@wordpress/components": "42.0.0",
105
118
  "@wordpress/dataviews": "20.0.0",
106
119
  "@wordpress/date": "5.57.0",
107
120
  "@wordpress/element": "9.0.0",