@gopherium/godmin 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +2 -3
  2. package/dist/base.css +9 -16
  3. package/dist/breakpoints.d.ts +1 -1
  4. package/dist/breakpoints.js +1 -1
  5. package/dist/bulk-run.d.ts +10 -0
  6. package/dist/bulk-run.js +59 -10
  7. package/dist/bulk.d.ts +3 -0
  8. package/dist/confirm-dialog.d.ts +14 -14
  9. package/dist/confirm-dialog.js +8 -28
  10. package/dist/dialog-open.d.ts +63 -0
  11. package/dist/dialog-open.js +110 -0
  12. package/dist/form-dialog.d.ts +14 -16
  13. package/dist/form-dialog.js +53 -13
  14. package/dist/index.d.ts +9 -11
  15. package/dist/index.js +4 -6
  16. package/dist/list-chrome/fr-FR.js +1 -0
  17. package/dist/list-run.js +25 -44
  18. package/dist/rename-dialog.d.ts +24 -0
  19. package/dist/rename-dialog.js +16 -0
  20. package/dist/router.d.ts +2 -0
  21. package/dist/router.js +1 -0
  22. package/dist/toaster.js +21 -2
  23. package/dist/unsaved-changes-dialog.d.ts +19 -0
  24. package/dist/unsaved-changes-dialog.js +33 -0
  25. package/docs/build-and-versioning.md +90 -7
  26. package/docs/design-system/accessibility.md +5 -3
  27. package/docs/design-system/dialogs.md +240 -0
  28. package/docs/design-system/layout.md +1 -1
  29. package/docs/design-system/lists.md +3 -1
  30. package/docs/design-system/motion.md +3 -2
  31. package/docs/design-system/overview.md +4 -1
  32. package/docs/design-system/record-pages.md +4 -2
  33. package/docs/design-system/toasts.md +11 -7
  34. package/docs/lists.md +311 -432
  35. package/docs/loading-and-feedback.md +11 -6
  36. package/docs/overview.md +2 -3
  37. package/docs/screens.md +10 -2
  38. package/docs/testing.md +11 -9
  39. package/package.json +1 -9
  40. package/dist/close-while-open.d.ts +0 -6
  41. package/dist/close-while-open.js +0 -21
  42. package/dist/confirm.d.ts +0 -21
  43. package/dist/confirm.js +0 -11
  44. package/dist/dialogs.d.ts +0 -4
  45. package/dist/dialogs.js +0 -3
  46. package/dist/form.d.ts +0 -28
  47. package/dist/form.js +0 -23
  48. package/dist/rename.d.ts +0 -20
  49. package/dist/rename.js +0 -14
  50. package/dist/run-confirm.d.ts +0 -22
  51. package/dist/run-confirm.js +0 -23
package/README.md CHANGED
@@ -49,11 +49,10 @@ those two lines do for you.
49
49
 
50
50
  | Entry point | Contents |
51
51
  | --- | --- |
52
- | `@gopherium/godmin` | `AdminRoot`, `Frame`, `Page`, `PageTitle`, `PageTabs`, `PageTab`, `PageBreadcrumbs`, `PageBreadcrumb`, `SectionTitle`, `InitialsAvatar`, `NavigationScreen`, `MenuCount`, `ErrorNotice`, `LoadMore`, `LogList`, `LogItem`, `LogTime`, `LoadingScreen`, `Toaster`, `useToaster`, `RepeatRows`, `RowControls`, `useRowKeys`, `keyFromLabel`, `listChromeCatalogFor`, `LIST_CHROME_DOMAIN`, `ListEmpty`, `ListNoResults`, `ConfirmBody`, `RenameBody`, `FormBody`, `FileButton`, `useServerPaging`, `pageWindow`, `paginationOf`, `runEach`, `bulkNotes`, `useListRun`, `useBulkRun`, `RunConfirm`, `useCloseWhileOpen`, `focusInDialog`, `useFocusBack`, `focusedTrigger`, `openOnTap`, `useUnsavedText`, `markLatest`, `viewNarrows`, `offeredView`, `offeredSize`, `sizedView`, `useMediaQuery`, `useTokenDocument`, the breakpoints `HUGE_BREAKPOINT`, `SIDEBAR_BREAKPOINT`, `EDGE_BREAKPOINT`, `DENSE_BREAKPOINT`, `SHEET_BREAKPOINT`, `TITLE_BREAKPOINT` and `SMALL_VIEWPORT`, `SUPPORTED_WPDS` |
52
+ | `@gopherium/godmin` | `AdminRoot`, `Frame`, `Page`, `PageTitle`, `PageTabs`, `PageTab`, `PageBreadcrumbs`, `PageBreadcrumb`, `SectionTitle`, `InitialsAvatar`, `NavigationScreen`, `MenuCount`, `ErrorNotice`, `LoadMore`, `LogList`, `LogItem`, `LogTime`, `LoadingScreen`, `Toaster`, `useToaster`, `RepeatRows`, `RowControls`, `useRowKeys`, `keyFromLabel`, `listChromeCatalogFor`, `LIST_CHROME_DOMAIN`, `ListEmpty`, `ListNoResults`, `ConfirmDialog`, `FormDialog`, `RenameDialog`, `FileButton`, `useServerPaging`, `pageWindow`, `paginationOf`, `runEach`, `bulkNotes`, `useListRun`, `useBulkRun`, `useDialogRun`, `focusInDialog`, `useFocusBack`, `focusedTrigger`, `openOnTap`, `useUnsavedText`, `markLatest`, `viewNarrows`, `offeredView`, `offeredSize`, `sizedView`, `useMediaQuery`, `useTokenDocument`, the breakpoints `HUGE_BREAKPOINT`, `SIDEBAR_BREAKPOINT`, `EDGE_BREAKPOINT`, `DENSE_BREAKPOINT`, `SHEET_BREAKPOINT`, `TITLE_BREAKPOINT` and `SMALL_VIEWPORT`, `SUPPORTED_WPDS` |
53
53
  | `@gopherium/godmin/base.css` | Cascade layer order, design tokens, host rules, frame and screen styles |
54
54
  | `@gopherium/godmin/dates` | `startListDates`, `listDate`, the only entry that loads `@wordpress/date` |
55
- | `@gopherium/godmin/dialogs` | `ConfirmDialog`, `FormDialog`, the only entry that loads `@wordpress/components`. Load `@wordpress/components/build-style/style.css` once in your app, as DataViews asks |
56
- | `@gopherium/godmin/router` | `Navigation`, `NavigationList`, `NavigationItem`, `DrilldownItem`, `useCanAccess` and the `MenuItem` type with its optional `count`, `useListView`, `listSearch`, `openOnTap`, `useCanvas`, `useFrameLocation`, `routerDefaults`, the `canvas`, `Sidebar` and `capability` route static data |
55
+ | `@gopherium/godmin/router` | `Navigation`, `NavigationList`, `NavigationItem`, `DrilldownItem`, `useCanAccess` and the `MenuItem` type with its optional `count`, `useListView`, `listSearch`, `openOnTap`, `useCanvas`, `useFrameLocation`, `routerDefaults`, `UnsavedChangesDialog`, the `canvas`, `Sidebar` and `capability` route static data |
57
56
  | `@gopherium/godmin/testing` | `installTestEnvironment`, `renderAdmin`, `setViewport` and its `TestViewport` type, `getAnnouncement`, `clearAnnouncements`, `assertElementPatched`, `WPDS_IGNORE_SELECTOR`, `textClasses`, `badgeClasses`, `buttonClasses`, `stubLayout` |
58
57
  | `@gopherium/godmin/vite` | `godminDedupe`, `godminSingleCopy`, `godminStylesheetFirst`, `duplicateCopies`, `hoistStylesheet` |
59
58
  | `@gopherium/godmin/stylelint` | The design system stylelint rules |
package/dist/base.css CHANGED
@@ -415,6 +415,7 @@ body {
415
415
  }
416
416
 
417
417
  .godmin-toast__action {
418
+ position: relative;
418
419
  flex: none;
419
420
  margin-inline-start: var(--wpds-dimension-gap-2xl);
420
421
  padding: 0;
@@ -429,6 +430,12 @@ body {
429
430
  cursor: var(--wpds-cursor-control);
430
431
  }
431
432
 
433
+ .godmin-toast__action::after {
434
+ content: '';
435
+ position: absolute;
436
+ inset: min(calc(-1 * var(--wpds-dimension-gap-sm)), calc(50% - 12px));
437
+ }
438
+
432
439
  .godmin-toast__action:hover {
433
440
  text-decoration: none;
434
441
  }
@@ -1039,22 +1046,8 @@ body {
1039
1046
  align-self: flex-start;
1040
1047
  }
1041
1048
 
1042
- .godmin-modal-body {
1043
- display: flex;
1044
- flex-direction: column;
1045
- gap: calc(var(--wpds-dimension-gap-lg) + var(--wpds-dimension-gap-xs));
1046
- }
1047
-
1048
- .godmin-modal-body--copy {
1049
- gap: var(--wpds-dimension-gap-md);
1050
- }
1051
-
1052
- .godmin-modal-body--create {
1053
- gap: var(--wpds-dimension-gap-lg);
1054
- }
1055
-
1056
- .godmin-modal-body__question {
1057
- line-height: 1.4;
1049
+ .godmin-dialog-popup {
1050
+ overflow-wrap: anywhere;
1058
1051
  }
1059
1052
 
1060
1053
  .godmin-form__row {
@@ -15,7 +15,7 @@ export declare const EDGE_BREAKPOINT = 782;
15
15
  */
16
16
  export declare const DENSE_BREAKPOINT = 640;
17
17
  /**
18
- * The viewport width below which modals rise as sheets and toasts widen to the screen, the WordPress small breakpoint.
18
+ * The viewport width below which toasts widen to the screen, the WordPress small breakpoint.
19
19
  */
20
20
  export declare const SHEET_BREAKPOINT = 600;
21
21
  /**
@@ -15,7 +15,7 @@ export const EDGE_BREAKPOINT = 782;
15
15
  */
16
16
  export const DENSE_BREAKPOINT = 640;
17
17
  /**
18
- * The viewport width below which modals rise as sheets and toasts widen to the screen, the WordPress small breakpoint.
18
+ * The viewport width below which toasts widen to the screen, the WordPress small breakpoint.
19
19
  */
20
20
  export const SHEET_BREAKPOINT = 600;
21
21
  /**
@@ -1,7 +1,10 @@
1
1
  import type { BulkWords } from './bulk.js';
2
+ import type { DialogAnswer } from './dialog-open.js';
2
3
  import type { ListRun } from './list-run.js';
3
4
  /** Runs one call over each item, reports what the run reached in the given words and then reloads the list. */
4
5
  export type BulkRun<Item> = (items: Item[], call: (item: Item) => Promise<unknown>, words: BulkWords<Item>) => Promise<void>;
6
+ /** Runs a dialog's write over one item or several, and answers the dialog what to do next. */
7
+ export type DialogRun<Item> = (items: Item[], call: (item: Item) => Promise<unknown>, words: BulkWords<Item>) => Promise<DialogAnswer | undefined>;
5
8
  /**
6
9
  * Returns the handler that runs a call per item, marks the list reloading at the first that works, toasts at the last.
7
10
  * @param list - What the list does around a run.
@@ -9,3 +12,10 @@ export type BulkRun<Item> = (items: Item[], call: (item: Item) => Promise<unknow
9
12
  * @returns The run handler, the same while the list run and the refresh stay the same.
10
13
  */
11
14
  export declare function useBulkRun<Item>(list: ListRun, refresh: (items: Item[]) => Promise<unknown>): BulkRun<Item>;
15
+ /**
16
+ * Returns the handler that runs a dialog's write on a list: one item that failed answers its words, else a toast.
17
+ * @param list - What the list does around a run.
18
+ * @param refresh - Reloads the list once the last call ended, given the items the run acted on.
19
+ * @returns The run handler, the same while the list run and the refresh stay the same.
20
+ */
21
+ export declare function useDialogRun<Item>(list: ListRun, refresh: (items: Item[]) => Promise<unknown>): DialogRun<Item>;
package/dist/bulk-run.js CHANGED
@@ -43,14 +43,38 @@ function bulkToast(items, outcome, words) {
43
43
  return notes.notice ?? notes.toast;
44
44
  }
45
45
  /**
46
- * Returns the handler that runs a call per item, marks the list reloading at the first that works, toasts at the last.
46
+ * Returns the action the toast of a run offers, the words' Undo once every item finished, none otherwise.
47
+ * @param items - The items the run was given.
48
+ * @param outcome - What the run reached.
49
+ * @param words - The words of the run.
50
+ * @returns The action, none when an item failed or the words give no Undo.
51
+ */
52
+ function doneAction(items, outcome, words) {
53
+ return outcome.failures.length === 0 ? words.undo?.(items) : undefined;
54
+ }
55
+ /**
56
+ * Shows the one toast a run's outcome reads as, with the words' Undo once every item finished.
57
+ * @param toaster - Where the toast shows.
58
+ * @param items - The items the run was given.
59
+ * @param outcome - What the run reached.
60
+ * @param words - The words of the run.
61
+ */
62
+ function toastOutcome(toaster, items, outcome, words) {
63
+ const message = bulkToast(items, outcome, words);
64
+ if (message !== undefined) {
65
+ toaster.show(message, doneAction(items, outcome, words));
66
+ }
67
+ }
68
+ /**
69
+ * Returns the handler that runs a call per item, marks the list reloading at the first that works, reports at the last.
47
70
  * @param list - What the list does around a run.
48
71
  * @param refresh - Reloads the list once the last call ended, given the items the run acted on.
49
- * @returns The run handler, the same while the list run and the refresh stay the same.
72
+ * @param report - Reports what the run reached and gives what the handler answers.
73
+ * @returns The run handler, the same while the list run, the refresh and the report stay the same.
50
74
  */
51
- export function useBulkRun(list, refresh) {
52
- const toaster = useToaster();
53
- return useCallback(async (items, call, words) => {
75
+ function useListWrite(list, refresh, report) {
76
+ return useCallback(async (given, call, words) => {
77
+ const items = given.filter(() => true);
54
78
  const settle = list.onStart();
55
79
  const reload = reloadOnce(list);
56
80
  const outcome = await runEach(items, reporting(call, reload.mark));
@@ -58,13 +82,38 @@ export function useBulkRun(list, refresh) {
58
82
  .then(() => refresh(items))
59
83
  .then(reload.end, reload.end);
60
84
  try {
61
- const message = bulkToast(items, outcome, words);
62
- if (message !== undefined) {
63
- toaster.show(message);
64
- }
85
+ return report(items, outcome, words);
65
86
  }
66
87
  finally {
67
88
  settle(outcome.done > 0);
68
89
  }
69
- }, [list, refresh, toaster]);
90
+ }, [list, refresh, report]);
91
+ }
92
+ /**
93
+ * Returns the handler that runs a call per item, marks the list reloading at the first that works, toasts at the last.
94
+ * @param list - What the list does around a run.
95
+ * @param refresh - Reloads the list once the last call ended, given the items the run acted on.
96
+ * @returns The run handler, the same while the list run and the refresh stay the same.
97
+ */
98
+ export function useBulkRun(list, refresh) {
99
+ const toaster = useToaster();
100
+ const report = useCallback((items, outcome, words) => toastOutcome(toaster, items, outcome, words), [toaster]);
101
+ return useListWrite(list, refresh, report);
102
+ }
103
+ /**
104
+ * Returns the handler that runs a dialog's write on a list: one item that failed answers its words, else a toast.
105
+ * @param list - What the list does around a run.
106
+ * @param refresh - Reloads the list once the last call ended, given the items the run acted on.
107
+ * @returns The run handler, the same while the list run and the refresh stay the same.
108
+ */
109
+ export function useDialogRun(list, refresh) {
110
+ const toaster = useToaster();
111
+ const report = useCallback((items, outcome, words) => {
112
+ if (outcome.asked === 1 && outcome.done === 0) {
113
+ return { error: words.failed(outcome.failures, 1) };
114
+ }
115
+ toastOutcome(toaster, items, outcome, words);
116
+ return undefined;
117
+ }, [toaster]);
118
+ return useListWrite(list, refresh, report);
70
119
  }
package/dist/bulk.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { ToastAction } from './toaster.js';
1
2
  /** An item a bulk run could not finish, with the error its call failed with. */
2
3
  export interface BulkFailure<Item> {
3
4
  /** The item the call was made for. */
@@ -27,6 +28,8 @@ export interface BulkWords<Item> {
27
28
  done: (count: number, only: Item | undefined) => string;
28
29
  /** The toast for the items that failed, shown instead of the done one, given each failure and how many were asked. */
29
30
  failed: (failures: BulkFailure<Item>[], asked: number) => string;
31
+ /** The action the done toast offers once every item finished, such as Undo, given the items. */
32
+ undo?: (items: Item[]) => ToastAction;
30
33
  }
31
34
  /** The messages a bulk outcome reads as, each absent when nothing calls for it. */
32
35
  export interface BulkNotes {
@@ -1,24 +1,24 @@
1
- import type { ReactNode } from 'react';
2
- /** The props of a confirmation dialog for an action outside a list. */
1
+ import type { DialogAnswer } from './dialog-open.js';
2
+ /** The props of a dialog that asks one question before an action. */
3
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';
4
+ /** The question the dialog asks, its name. */
5
+ title: string;
6
+ /** What will happen, in plain words. */
7
+ description?: string;
8
+ /** Whether the action cannot be undone, which draws its button red. */
9
+ intent?: 'default' | 'irreversible';
10
10
  /** The label of the button that carries the action out. */
11
11
  confirmLabel: string;
12
12
  /** The label of the button that closes the dialog. */
13
13
  cancelLabel: string;
14
- /** Carries the action out. Return nothing to close at once, or the write's promise to stay busy until it ends. */
15
- onConfirm: () => void | Promise<unknown>;
16
- /** Takes the dialog away after Cancel, Escape, a click outside it, its close button or a confirm that finished. */
14
+ /** Carries the action out. Return nothing to close at once, the write to stay busy, or an answer to stay open. */
15
+ onConfirm: () => void | DialogAnswer | PromiseLike<unknown>;
16
+ /** Takes the dialog away, once its card has left the page. */
17
17
  onClose: () => void;
18
18
  }
19
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.
20
+ * Renders a dialog that asks one question before an action, on the WPDS alert dialog, with Cancel focused.
21
+ * @param props - The question, what will happen, the intent, the labels and the handlers.
22
22
  * @returns The dialog.
23
23
  */
24
- export declare function ConfirmDialog({ children, title, size, confirmLabel, cancelLabel, onConfirm, onClose, }: ConfirmDialogProps): import("react").JSX.Element;
24
+ export declare function ConfirmDialog({ title, description, intent, confirmLabel, cancelLabel, onConfirm, onClose, }: ConfirmDialogProps): import("react").JSX.Element;
@@ -1,34 +1,14 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- import { Modal } from '@wordpress/components';
4
- import { useId, useRef, useState } from 'react';
5
- import { ConfirmBody } from './confirm.js';
3
+ import { AlertDialog } from '@wordpress/ui';
4
+ import { POPUP_CLASS, answered, refuseRepeatedEnter, refuseSecondClick, useDialogOpen, useFinalFocus, } from './dialog-open.js';
6
5
  /**
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.
6
+ * Renders a dialog that asks one question before an action, on the WPDS alert dialog, with Cancel focused.
7
+ * @param props - The question, what will happen, the intent, the labels and the handlers.
9
8
  * @returns The dialog.
10
9
  */
11
- export function ConfirmDialog({ children, title, size = 'medium', confirmLabel, cancelLabel, onConfirm, onClose, }) {
12
- const [busy, setBusy] = useState(false);
13
- const open = useRef(true);
14
- const question = useId();
15
- const close = () => {
16
- if (open.current) {
17
- open.current = false;
18
- onClose();
19
- }
20
- };
21
- const confirm = () => {
22
- const running = onConfirm();
23
- if (!(running instanceof Promise)) {
24
- close();
25
- return;
26
- }
27
- setBusy(true);
28
- void running.finally(() => {
29
- setBusy(false);
30
- close();
31
- });
32
- };
33
- return (_jsx(Modal, { size: size, focusOnMount: "firstContentElement", title: title, __experimentalHideHeader: title === undefined, aria: { labelledby: question, describedby: title === undefined ? undefined : question }, onRequestClose: close, children: _jsx(ConfirmBody, { confirmLabel: confirmLabel, cancelLabel: cancelLabel, busy: busy, onConfirm: confirm, onCancel: close, children: _jsx("span", { id: question, children: children }) }) }));
10
+ export function ConfirmDialog({ title, description, intent, confirmLabel, cancelLabel, onConfirm, onClose, }) {
11
+ const { open, change, exitWatch } = useDialogOpen(onClose);
12
+ const finalFocus = useFinalFocus();
13
+ return (_jsx(AlertDialog.Root, { open: open, onOpenChange: change, onConfirm: () => answered(onConfirm), children: _jsx(AlertDialog.Popup, { className: POPUP_CLASS, intent: intent, title: title, description: description, confirmButtonText: confirmLabel, cancelButtonText: cancelLabel, finalFocus: finalFocus, onClickCapture: refuseSecondClick, onKeyDownCapture: refuseRepeatedEnter, children: exitWatch }) }));
34
14
  }
@@ -0,0 +1,63 @@
1
+ import type { KeyboardEvent, MouseEvent, ReactNode } from 'react';
2
+ /** The class every dialog's popup carries, so a long word breaks inside the card. */
3
+ export declare const POPUP_CLASS = "godmin-dialog-popup";
4
+ /** What a write may answer a dialog: words to show, or a plain stay. Any other answer closes it. */
5
+ export type DialogAnswer = {
6
+ error: string;
7
+ } | {
8
+ close: false;
9
+ };
10
+ /** What a dialog takes from the hook that holds it open. */
11
+ export interface DialogOpen {
12
+ /** Whether the dialog is open, false on the first render so its entry plays. */
13
+ open: boolean;
14
+ /** Takes the next open state, for the dialog's `onOpenChange`. */
15
+ change: (next: boolean) => void;
16
+ /** A child of the popup that draws nothing and reports when the popup left the page. */
17
+ exitWatch: ReactNode;
18
+ }
19
+ /**
20
+ * Holds a dialog open from its first commit and runs its close once the popup left the page.
21
+ * @param onClose - What runs after a close, once the popup left the page.
22
+ * @returns The open state, what changes it and the child that watches the popup leave.
23
+ */
24
+ export declare function useDialogOpen(onClose: () => void): DialogOpen;
25
+ /**
26
+ * Notes the control that held the focus as a dialog was asked, for the place the focus goes once the popup left.
27
+ * @returns What answers `finalFocus`: that control while the focus sits on the page, otherwise false to leave it.
28
+ */
29
+ export declare function useFinalFocus(): () => HTMLElement | false;
30
+ /**
31
+ * Reads what a write answered a dialog, whatever its shape.
32
+ * @param answer - What the write answered.
33
+ * @returns The words to show or a plain stay, none for a dialog that closes.
34
+ */
35
+ export declare function answerOf(answer: unknown): DialogAnswer | undefined;
36
+ /**
37
+ * Reports whether a value is a write still running, a promise or any object with a `then` method.
38
+ * @param value - What the write's handler returned.
39
+ * @returns Whether the value is one to wait for.
40
+ */
41
+ export declare function isThenable(value: unknown): value is PromiseLike<unknown>;
42
+ /**
43
+ * Keeps a dialog open after a rejection and hands the rejection on to the app as one nobody caught.
44
+ * @param error - What the write rejected with.
45
+ * @returns A plain stay.
46
+ */
47
+ export declare function passRejectionOn(error: unknown): DialogAnswer;
48
+ /**
49
+ * Carries a dialog's action out and reads what it answers, handing what it throws or rejects with on to the app.
50
+ * @param action - The action.
51
+ * @returns What the dialog reads, at once unless the action returned a write still running.
52
+ */
53
+ export declare function answered(action: () => unknown): DialogAnswer | undefined | Promise<DialogAnswer | undefined>;
54
+ /**
55
+ * Refuses the second click of a double click, while Enter and Space still press.
56
+ * @param event - The click on its way into the popup.
57
+ */
58
+ export declare function refuseSecondClick(event: MouseEvent): void;
59
+ /**
60
+ * Refuses an Enter a held key repeats, so holding it sends once.
61
+ * @param event - The key press on its way into the popup.
62
+ */
63
+ export declare function refuseRepeatedEnter(event: KeyboardEvent): void;
@@ -0,0 +1,110 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { useCallback, useLayoutEffect, useRef, useState } from 'react';
4
+ /** The class every dialog's popup carries, so a long word breaks inside the card. */
5
+ export const POPUP_CLASS = 'godmin-dialog-popup';
6
+ /**
7
+ * Renders nothing and reports when it leaves the page.
8
+ * @param props - What it runs as it leaves.
9
+ * @returns Nothing.
10
+ */
11
+ function ExitWatch({ left }) {
12
+ useLayoutEffect(() => left, [left]);
13
+ return null;
14
+ }
15
+ /**
16
+ * Holds a dialog open from its first commit and runs its close once the popup left the page.
17
+ * @param onClose - What runs after a close, once the popup left the page.
18
+ * @returns The open state, what changes it and the child that watches the popup leave.
19
+ */
20
+ export function useDialogOpen(onClose) {
21
+ const [open, setOpen] = useState(false);
22
+ const closing = useRef(false);
23
+ const latest = useRef(onClose);
24
+ useLayoutEffect(() => {
25
+ latest.current = onClose;
26
+ });
27
+ useLayoutEffect(() => {
28
+ setOpen(true);
29
+ }, []);
30
+ const left = useCallback(() => {
31
+ if (closing.current) {
32
+ latest.current();
33
+ }
34
+ }, []);
35
+ const change = (next) => {
36
+ closing.current = !next;
37
+ setOpen(next);
38
+ };
39
+ return { open, change, exitWatch: _jsx(ExitWatch, { left: left }) };
40
+ }
41
+ /**
42
+ * Notes the control that held the focus as a dialog was asked, for the place the focus goes once the popup left.
43
+ * @returns What answers `finalFocus`: that control while the focus sits on the page, otherwise false to leave it.
44
+ */
45
+ export function useFinalFocus() {
46
+ const [opener] = useState(() => document.activeElement);
47
+ return () => (document.activeElement === document.body && opener !== document.body ? opener : false);
48
+ }
49
+ /**
50
+ * Reads what a write answered a dialog, whatever its shape.
51
+ * @param answer - What the write answered.
52
+ * @returns The words to show or a plain stay, none for a dialog that closes.
53
+ */
54
+ export function answerOf(answer) {
55
+ const { error, close } = (answer ?? {});
56
+ if (typeof error === 'string' && error !== '') {
57
+ return { error };
58
+ }
59
+ return close === false ? { close } : undefined;
60
+ }
61
+ /**
62
+ * Reports whether a value is a write still running, a promise or any object with a `then` method.
63
+ * @param value - What the write's handler returned.
64
+ * @returns Whether the value is one to wait for.
65
+ */
66
+ export function isThenable(value) {
67
+ return typeof value?.then === 'function';
68
+ }
69
+ /**
70
+ * Keeps a dialog open after a rejection and hands the rejection on to the app as one nobody caught.
71
+ * @param error - What the write rejected with.
72
+ * @returns A plain stay.
73
+ */
74
+ export function passRejectionOn(error) {
75
+ void Promise.reject(error);
76
+ return { close: false };
77
+ }
78
+ /**
79
+ * Carries a dialog's action out and reads what it answers, handing what it throws or rejects with on to the app.
80
+ * @param action - The action.
81
+ * @returns What the dialog reads, at once unless the action returned a write still running.
82
+ */
83
+ export function answered(action) {
84
+ try {
85
+ const running = action();
86
+ return isThenable(running) ? Promise.resolve(running).then(answerOf, passRejectionOn) : answerOf(running);
87
+ }
88
+ catch (error) {
89
+ return passRejectionOn(error);
90
+ }
91
+ }
92
+ /**
93
+ * Refuses the second click of a double click, while Enter and Space still press.
94
+ * @param event - The click on its way into the popup.
95
+ */
96
+ export function refuseSecondClick(event) {
97
+ if (event.detail > 1) {
98
+ event.preventDefault();
99
+ event.stopPropagation();
100
+ }
101
+ }
102
+ /**
103
+ * Refuses an Enter a held key repeats, so holding it sends once.
104
+ * @param event - The key press on its way into the popup.
105
+ */
106
+ export function refuseRepeatedEnter(event) {
107
+ if (event.repeat && event.key === 'Enter') {
108
+ event.preventDefault();
109
+ }
110
+ }
@@ -1,29 +1,27 @@
1
1
  import type { ReactNode } from 'react';
2
- import type { FormKind } from './form.js';
2
+ import type { DialogAnswer } from './dialog-open.js';
3
3
  /** The props of a form dialog opened from a button outside a list row. */
4
4
  export interface FormDialogProps {
5
- /** The fields, and any help sentence before them, in the order the reader meets them. */
6
- children: ReactNode;
7
- /** The title in the dialog header, beside its close button. */
5
+ /** The fields in the order the reader meets them, or a function of whether the write runs that draws them. */
6
+ children: ReactNode | ((busy: boolean) => ReactNode);
7
+ /** The title in the dialog header, beside its close icon, the name of the dialog. */
8
8
  title: string;
9
- /** The width from 600px up: small at 400px, the default, or medium at 560px when a control needs the room. */
10
- size?: 'small' | 'medium';
9
+ /** A help sentence before the fields, which describes the dialog. */
10
+ description?: string;
11
11
  /** The label of the button that sends the form. */
12
12
  submitLabel: string;
13
- /** The label of the button that closes the dialog. */
14
- cancelLabel: string;
13
+ /** The label of the button that closes the dialog, none on a last step with nothing to cancel. */
14
+ cancelLabel?: string;
15
15
  /** Whether the form may be sent now, false while a needed field is empty, true when left out. */
16
16
  canSubmit?: boolean;
17
- /** What the form does: 16px above the buttons for a create, the default, 20px for an edit, 12px for a copy. */
18
- kind?: FormKind;
19
- /** Sends the form. Return the write's promise to keep the button busy until it ends. */
20
- onSubmit: () => void | Promise<unknown>;
21
- /** Takes the dialog away after Cancel, Escape, a click on the dimmed page or the close button. */
17
+ /** Sends the form. Return nothing to close at once, the write to hold the dialog until it ends, or an answer. */
18
+ onSubmit: () => void | DialogAnswer | PromiseLike<unknown>;
19
+ /** Takes the dialog away, once its card has left the page. */
22
20
  onClose: () => void;
23
21
  }
24
22
  /**
25
- * Renders a form dialog opened from a button outside a list row, as WordPress opens Add Page, the first field focused.
26
- * @param props - The fields, the title, the size, the labels, the send gate, the kind and the handlers.
23
+ * Renders a form dialog opened from a button outside a list row, on the WPDS dialog, the first field focused.
24
+ * @param props - The fields, the title, the help sentence, the labels, the send gate and the handlers.
27
25
  * @returns The dialog.
28
26
  */
29
- export declare function FormDialog({ children, title, size, submitLabel, cancelLabel, canSubmit, kind, onSubmit, onClose, }: FormDialogProps): import("react").JSX.Element;
27
+ export declare function FormDialog({ children, title, description, submitLabel, cancelLabel, canSubmit, onSubmit, onClose, }: FormDialogProps): import("react").JSX.Element;
@@ -1,21 +1,61 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- import { Modal } from '@wordpress/components';
4
- import { useState } from 'react';
5
- import { FormBody } from './form.js';
3
+ import { speak } from '@wordpress/a11y';
4
+ import { Button, Dialog, Notice, Stack } from '@wordpress/ui';
5
+ import { useId, useLayoutEffect, useRef, useState } from 'react';
6
+ import { POPUP_CLASS, answered, isThenable, refuseSecondClick, useDialogOpen, useFinalFocus } from './dialog-open.js';
6
7
  /**
7
- * Renders a form dialog opened from a button outside a list row, as WordPress opens Add Page, the first field focused.
8
- * @param props - The fields, the title, the size, the labels, the send gate, the kind and the handlers.
8
+ * Renders a form dialog opened from a button outside a list row, on the WPDS dialog, the first field focused.
9
+ * @param props - The fields, the title, the help sentence, the labels, the send gate and the handlers.
9
10
  * @returns The dialog.
10
11
  */
11
- export function FormDialog({ children, title, size = 'small', submitLabel, cancelLabel, canSubmit, kind = 'create', onSubmit, onClose, }) {
12
+ export function FormDialog({ children, title, description, submitLabel, cancelLabel, canSubmit = true, onSubmit, onClose, }) {
13
+ const { open, change, exitWatch } = useDialogOpen(onClose);
14
+ const finalFocus = useFinalFocus();
12
15
  const [busy, setBusy] = useState(false);
13
- const send = () => {
14
- const sending = onSubmit();
15
- if (sending instanceof Promise) {
16
- setBusy(true);
17
- void sending.finally(() => setBusy(false));
16
+ const [failure, setFailure] = useState();
17
+ const [failures, setFailures] = useState(0);
18
+ const content = useRef(null);
19
+ const form = useId();
20
+ const sendable = canSubmit && !busy && open;
21
+ useLayoutEffect(() => {
22
+ const body = content.current;
23
+ if (failures > 0 && body !== null) {
24
+ body.scrollTop = body.scrollHeight;
18
25
  }
26
+ }, [failures]);
27
+ const guarded = (next) => {
28
+ if (next || !busy) {
29
+ change(next);
30
+ }
31
+ };
32
+ const clear = () => setFailure(undefined);
33
+ const settle = (answer) => {
34
+ if (answer === undefined) {
35
+ change(false);
36
+ }
37
+ else if ('error' in answer) {
38
+ setFailure(answer.error);
39
+ setFailures((count) => count + 1);
40
+ speak(answer.error, 'assertive');
41
+ }
42
+ };
43
+ const submit = (event) => {
44
+ event.preventDefault();
45
+ if (!sendable) {
46
+ return;
47
+ }
48
+ clear();
49
+ const answer = answered(onSubmit);
50
+ if (!isThenable(answer)) {
51
+ settle(answer);
52
+ return;
53
+ }
54
+ setBusy(true);
55
+ void answer.then((reply) => {
56
+ setBusy(false);
57
+ settle(reply);
58
+ });
19
59
  };
20
- return (_jsx(Modal, { title: title, size: size, focusOnMount: "firstContentElement", onRequestClose: onClose, children: _jsx(FormBody, { submitLabel: submitLabel, cancelLabel: cancelLabel, canSubmit: canSubmit, busy: busy, kind: kind, onSubmit: send, onCancel: onClose, children: children }) }));
60
+ return (_jsx(Dialog.Root, { open: open, onOpenChange: guarded, children: _jsxs(Dialog.Popup, { className: POPUP_CLASS, finalFocus: finalFocus, children: [_jsxs(Dialog.Header, { children: [_jsx(Dialog.Title, { children: title }), _jsx(Dialog.CloseIconButton, { disabled: busy })] }), _jsx(Dialog.Content, { ref: content, children: _jsxs(Stack, { render: _jsx("form", { id: form, onSubmit: submit, onChange: clear }), direction: "column", gap: "lg", children: [description === undefined ? null : _jsx(Dialog.Description, { children: description }), typeof children === 'function' ? children(busy) : children, failure === undefined ? null : (_jsx(Notice.Root, { intent: "error", children: _jsx(Notice.Description, { children: failure }) }))] }) }), _jsxs(Dialog.Footer, { children: [cancelLabel === undefined ? null : (_jsx(Dialog.Action, { variant: "outline", tone: "neutral", disabled: busy, children: cancelLabel })), _jsx(Button, { type: "submit", form: form, loading: busy, disabled: !sendable, onClick: refuseSecondClick, children: submitLabel })] }), exitWatch] }) }));
21
61
  }
package/dist/index.d.ts CHANGED
@@ -3,19 +3,19 @@ export type { AdminRootProps } from './admin-root.js';
3
3
  export { InitialsAvatar } from './avatar.js';
4
4
  export type { InitialsAvatarProps } from './avatar.js';
5
5
  export { DENSE_BREAKPOINT, EDGE_BREAKPOINT, HUGE_BREAKPOINT, SHEET_BREAKPOINT, SIDEBAR_BREAKPOINT, SMALL_VIEWPORT, TITLE_BREAKPOINT, } from './breakpoints.js';
6
- export { useBulkRun } from './bulk-run.js';
7
- export type { BulkRun } from './bulk-run.js';
6
+ export { useBulkRun, useDialogRun } from './bulk-run.js';
7
+ export type { BulkRun, DialogRun } from './bulk-run.js';
8
8
  export { bulkNotes, runEach } from './bulk.js';
9
9
  export type { BulkFailure, BulkNotes, BulkOutcome, BulkWords } from './bulk.js';
10
- export { useCloseWhileOpen } from './close-while-open.js';
11
- export { ConfirmBody } from './confirm.js';
12
- export type { ConfirmBodyProps } from './confirm.js';
10
+ export { ConfirmDialog } from './confirm-dialog.js';
11
+ export type { ConfirmDialogProps } from './confirm-dialog.js';
12
+ export type { DialogAnswer } from './dialog-open.js';
13
13
  export { FileButton } from './file-button.js';
14
14
  export type { FileButtonProps } from './file-button.js';
15
15
  export { focusedTrigger, useFocusBack } from './focus-back.js';
16
16
  export type { Trigger } from './focus-back.js';
17
- export { FormBody } from './form.js';
18
- export type { FormBodyProps, FormKind } from './form.js';
17
+ export { FormDialog } from './form-dialog.js';
18
+ export type { FormDialogProps } from './form-dialog.js';
19
19
  export { Frame } from './frame.js';
20
20
  export type { CanvasMode, FrameCanvasProps, FrameRootProps, FrameSidebarProps, } from './frame.js';
21
21
  export { keyFromLabel } from './keys.js';
@@ -42,14 +42,12 @@ export { PageBreadcrumb, PageBreadcrumbs } from './page-breadcrumbs.js';
42
42
  export type { PageBreadcrumbProps, PageBreadcrumbsProps } from './page-breadcrumbs.js';
43
43
  export { PageTab, PageTabs } from './page-tabs.js';
44
44
  export type { PageTabProps, PageTabsProps } from './page-tabs.js';
45
- export { RenameBody } from './rename.js';
46
- export type { RenameBodyProps } from './rename.js';
45
+ export { RenameDialog } from './rename-dialog.js';
46
+ export type { RenameDialogProps } from './rename-dialog.js';
47
47
  export { useRowKeys } from './row-keys.js';
48
48
  export type { RowBounds, RowKeys } from './row-keys.js';
49
49
  export { RepeatRows, RowControls } from './rows.js';
50
50
  export type { RepeatRowsProps, RowControlsProps, RowLabels } from './rows.js';
51
- export { RunConfirm } from './run-confirm.js';
52
- export type { RunConfirmProps } from './run-confirm.js';
53
51
  export { offeredSize, pageWindow, paginationOf, sizedView, useServerPaging } from './server-page.js';
54
52
  export type { PagedView, PageWindow, PaginationInfo, ServedPage, ServedSize, ServerPaging } from './server-page.js';
55
53
  export { Toaster, useToaster } from './toaster.js';