@gopherium/godmin 0.29.1 → 0.30.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
@@ -49,7 +49,7 @@ those two lines do for you.
49
49
 
50
50
  | Entry point | Contents |
51
51
  | --- | --- |
52
- | `@gopherium/godmin` | `AdminRoot`, `Frame`, `Page`, `PageTitle`, `PageTabs`, `PageTab`, `SectionTitle`, `InitialsAvatar`, `NavigationScreen`, `MenuCount`, `ErrorNotice`, `LoadMore`, `LogList`, `LogItem`, `LogTime`, `LoadingScreen`, `Toaster`, `useToaster`, `RepeatRows`, `RowControls`, `useRowKeys`, `keyFromLabel`, `listChromeCatalogFor`, `LIST_CHROME_DOMAIN`, `ListEmpty`, `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`, `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` |
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
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 |
@@ -61,8 +61,9 @@ those two lines do for you.
61
61
  ## Translations
62
62
 
63
63
  GodMin speaks a few words of its own: Back on a sidebar screen, the name of
64
- the sidebar column and its phone drawer, and the phone menu button and the
65
- drawer's close button, which only a screen reader meets. It
64
+ the sidebar column and its phone drawer, the phone menu button and the
65
+ drawer's close button, which only a screen reader meets, and "No results
66
+ found" with the line under it, which `ListNoResults` shows. It
66
67
  translates them in the WordPress `default` text domain, as `@wordpress/ui`
67
68
  translates its own, so `@wordpress/i18n` is a required peer. Every app
68
69
  already has it, since
package/dist/base.css CHANGED
@@ -88,6 +88,55 @@ body {
88
88
  line-height: var(--wpds-typography-line-height-sm);
89
89
  }
90
90
 
91
+ /* Freezes the checkbox and title of a wide DataViews table on a list page wider than 782px, as Jetpack Forms does. */
92
+ @media (width > 782px) {
93
+ /* Sets where the frozen title starts, the width of the checkbox column. */
94
+ .godmin-page__list--wide:has(td .dataviews-title-field) .dataviews-view-table.has-bulk-actions {
95
+ --godmin-list-frozen-start: calc(var(--wpds-dimension-padding-2xl) + var(--wpds-dimension-size-sm));
96
+ }
97
+
98
+ /* Sizes the checkbox column to the width where the frozen title starts. */
99
+ .godmin-page__list--wide:has(td .dataviews-title-field) .dataviews-view-table.has-bulk-actions col.dataviews-view-table__col-checkbox.dataviews-view-table__col-checkbox {
100
+ inline-size: var(--godmin-list-frozen-start);
101
+ }
102
+
103
+ /* Freezes the checkbox column at the start edge, on the list background. */
104
+ .godmin-page__list--wide:has(td .dataviews-title-field) .dataviews-view-table.has-bulk-actions .dataviews-view-table__checkbox-column {
105
+ position: sticky;
106
+ inset-inline-start: 0;
107
+ background-color: var(--wp-dataviews-color-background, var(--wpds-color-background-surface-neutral-strong));
108
+ }
109
+
110
+ /* Freezes the title column after the checkbox column, on the list background. */
111
+ .godmin-page__list--wide:has(td .dataviews-title-field) .dataviews-view-table.has-bulk-actions .dataviews-view-table__checkbox-column + * {
112
+ position: sticky;
113
+ inset-inline-start: var(--godmin-list-frozen-start);
114
+ padding-inline-end: var(--wpds-dimension-padding-2xl);
115
+ min-inline-size: 280px;
116
+ background-color: var(--wp-dataviews-color-background, var(--wpds-color-background-surface-neutral-strong));
117
+ }
118
+
119
+ /* Draws the line at the end of a frozen title, as DataViews draws the line beside its pinned actions. */
120
+ .godmin-page__list--wide:has(td .dataviews-title-field) .dataviews-view-table.has-bulk-actions .dataviews-view-table__checkbox-column + *::after {
121
+ content: '';
122
+ position: absolute;
123
+ inset-block: 0;
124
+ inset-inline-end: 0;
125
+ inline-size: var(--wpds-border-width-xs);
126
+ background-color: var(--wpds-color-stroke-surface-neutral-weak);
127
+ }
128
+
129
+ /* Repeats the tint of a selected row on its frozen cells, which paint over the row. */
130
+ .godmin-page__list--wide:has(td .dataviews-title-field) .dataviews-view-table.has-bulk-actions .dataviews-view-table__row.is-selected > :is(.dataviews-view-table__checkbox-column, .dataviews-view-table__checkbox-column + *) {
131
+ background-color: var(--wpds-color-background-interactive-brand-weak-active);
132
+ }
133
+
134
+ /* Keeps the frozen header cells over the rest of their row as it scrolls under them. */
135
+ .godmin-page__list--wide:has(td .dataviews-title-field) .dataviews-view-table.has-bulk-actions thead .dataviews-view-table__row > :is(.dataviews-view-table__checkbox-column, .dataviews-view-table__checkbox-column + *) {
136
+ z-index: 2;
137
+ }
138
+ }
139
+
91
140
  @layer godmin {
92
141
  body {
93
142
  margin: 0;
@@ -718,6 +767,26 @@ body {
718
767
  margin: 0;
719
768
  }
720
769
 
770
+ /* Draws the WordPress region focus ring in place of the browser's inside a list region that holds the keyboard focus. */
771
+ .godmin-page__list[tabindex] {
772
+ position: relative;
773
+ }
774
+
775
+ .godmin-page__list:focus-visible {
776
+ outline: none;
777
+ }
778
+
779
+ .godmin-page__list:focus-visible::after {
780
+ content: '';
781
+ position: absolute;
782
+ inset: 0;
783
+ z-index: 2;
784
+ outline: calc(2 * var(--wpds-border-width-focus)) solid var(--wpds-color-stroke-focus);
785
+ outline-offset: calc(-2 * var(--wpds-border-width-focus));
786
+ box-shadow: inset 0 0 0 calc(2 * var(--wpds-border-width-focus) + var(--wpds-border-width-xs)) var(--wpds-color-background-surface-neutral-strong);
787
+ pointer-events: none;
788
+ }
789
+
721
790
  .godmin-page__tabs {
722
791
  margin-inline: calc(-1 * var(--godmin-canvas-gutter, 0px));
723
792
  padding-inline: var(--godmin-canvas-gutter, 0px);
@@ -878,6 +947,10 @@ body {
878
947
  padding-block: 48px;
879
948
  }
880
949
 
950
+ .dataviews-wrapper .godmin-empty {
951
+ padding-block: 0;
952
+ }
953
+
881
954
  .godmin-table {
882
955
  width: 100%;
883
956
  border-collapse: collapse;
@@ -1,11 +1,11 @@
1
1
  import type { BulkWords } from './bulk.js';
2
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. */
3
+ /** Runs one call over each item, reports what the run reached in the given words and then reloads the list. */
4
4
  export type BulkRun<Item> = (items: Item[], call: (item: Item) => Promise<unknown>, words: BulkWords<Item>) => Promise<void>;
5
5
  /**
6
- * Returns the handler that runs one call per item, refreshes the list, shows one toast and settles the run.
6
+ * Returns the handler that runs a call per item, marks the list reloading at the first that works, toasts at the last.
7
7
  * @param list - What the list does around a run.
8
- * @param refresh - Reloads the list, given the items the run acted on.
8
+ * @param refresh - Reloads the list once the last call ended, given the items the run acted on.
9
9
  * @returns The run handler, the same while the list run and the refresh stay the same.
10
10
  */
11
11
  export declare function useBulkRun<Item>(list: ListRun, refresh: (items: Item[]) => Promise<unknown>): BulkRun<Item>;
package/dist/bulk-run.js CHANGED
@@ -2,6 +2,35 @@
2
2
  import { useCallback } from 'react';
3
3
  import { bulkNotes, runEach } from './bulk.js';
4
4
  import { useToaster } from './toaster.js';
5
+ /**
6
+ * Returns what marks a list reloading once in a run, and what ends that reload.
7
+ * @param list - What the list does around a run.
8
+ * @returns The mark and the end.
9
+ */
10
+ function reloadOnce(list) {
11
+ let ended;
12
+ return {
13
+ mark: () => {
14
+ ended ??= list.onRefresh();
15
+ },
16
+ end: () => ended?.(),
17
+ };
18
+ }
19
+ /**
20
+ * Returns the call on one item that fails as the given call fails, and calls `worked` once it works.
21
+ * @param call - The action on one item.
22
+ * @param worked - What runs each time the call on an item works.
23
+ * @returns The call that reports each item it finished.
24
+ */
25
+ function reporting(call, worked) {
26
+ return async (item) => {
27
+ const { failures } = await runEach([item], call);
28
+ if (failures.length > 0) {
29
+ throw failures[0].error;
30
+ }
31
+ worked();
32
+ };
33
+ }
5
34
  /**
6
35
  * Returns the one message a bulk outcome shows: the failure words when an item failed, else the done words.
7
36
  * @param items - The items the run was given.
@@ -14,29 +43,28 @@ function bulkToast(items, outcome, words) {
14
43
  return notes.notice ?? notes.toast;
15
44
  }
16
45
  /**
17
- * Returns the handler that runs one call per item, refreshes the list, shows one toast and settles the run.
46
+ * Returns the handler that runs a call per item, marks the list reloading at the first that works, toasts at the last.
18
47
  * @param list - What the list does around a run.
19
- * @param refresh - Reloads the list, given the items the run acted on.
48
+ * @param refresh - Reloads the list once the last call ended, given the items the run acted on.
20
49
  * @returns The run handler, the same while the list run and the refresh stay the same.
21
50
  */
22
51
  export function useBulkRun(list, refresh) {
23
52
  const toaster = useToaster();
24
53
  return useCallback(async (items, call, words) => {
25
54
  const settle = list.onStart();
26
- const outcome = await runEach(items, call);
55
+ const reload = reloadOnce(list);
56
+ const outcome = await runEach(items, reporting(call, reload.mark));
57
+ void Promise.resolve()
58
+ .then(() => refresh(items))
59
+ .then(reload.end, reload.end);
27
60
  try {
28
- await refresh(items);
61
+ const message = bulkToast(items, outcome, words);
62
+ if (message !== undefined) {
63
+ toaster.show(message);
64
+ }
29
65
  }
30
66
  finally {
31
- try {
32
- const message = bulkToast(items, outcome, words);
33
- if (message !== undefined) {
34
- toaster.show(message);
35
- }
36
- }
37
- finally {
38
- settle(outcome.done > 0);
39
- }
67
+ settle(outcome.done > 0);
40
68
  }
41
69
  }, [list, refresh, toaster]);
42
70
  }
@@ -1,4 +1,6 @@
1
1
  import type { RefObject } from 'react';
2
+ /** Finds the card of a grid, the row of a phone list or the row of a table holding an item. */
3
+ export declare const HOLDERS = ".dataviews-view-grid__card, .dataviews-view-list__item-wrapper, .dataviews-view-table__row";
2
4
  /** Finds each trigger a dialog on an item opens from, inside the card or the row holding the item. */
3
5
  declare const TRIGGERS: {
4
6
  title: string;
@@ -3,7 +3,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
3
3
  /** Finds each cell an app marks with the id DataViews keys its item by, the title cell at least. */
4
4
  const MARKED = '[data-item-id]';
5
5
  /** Finds the card of a grid, the row of a phone list or the row of a table holding an item. */
6
- const HOLDERS = '.dataviews-view-grid__card, .dataviews-view-list__item-wrapper, .dataviews-view-table__row';
6
+ export const HOLDERS = '.dataviews-view-grid__card, .dataviews-view-list__item-wrapper, .dataviews-view-table__row';
7
7
  /** Finds each trigger a dialog on an item opens from, inside the card or the row holding the item. */
8
8
  const TRIGGERS = {
9
9
  title: '.dataviews-title-field[role="button"]',
package/dist/index.d.ts CHANGED
@@ -22,7 +22,7 @@ export { keyFromLabel } from './keys.js';
22
22
  export type { KeyOptions, KeyStyle } from './keys.js';
23
23
  export { LIST_CHROME_DOMAIN, listChromeCatalogFor } from './list-chrome.js';
24
24
  export type { ListChromeCatalog } from './list-chrome.js';
25
- export { ListEmpty } from './list-empty.js';
25
+ export { ListEmpty, ListNoResults } from './list-empty.js';
26
26
  export type { ListEmptyProps } from './list-empty.js';
27
27
  export { focusInDialog, useListRun } from './list-run.js';
28
28
  export type { ListRun, ListRunState, RunSettled } from './list-run.js';
package/dist/index.js CHANGED
@@ -12,7 +12,7 @@ export { FormBody } from './form.js';
12
12
  export { Frame } from './frame.js';
13
13
  export { keyFromLabel } from './keys.js';
14
14
  export { LIST_CHROME_DOMAIN, listChromeCatalogFor } from './list-chrome.js';
15
- export { ListEmpty } from './list-empty.js';
15
+ export { ListEmpty, ListNoResults } from './list-empty.js';
16
16
  export { focusInDialog, useListRun } from './list-run.js';
17
17
  export { LoadingScreen } from './loading.js';
18
18
  export { LogItem, LogList, LogTime } from './log-list.js';
@@ -1,4 +1,4 @@
1
1
  import type { ListChromeCatalog } from '../list-chrome.js';
2
- /** The Spanish list chrome, list dates and sidebar words, compiled from the es-ES.po source beside it. */
2
+ /** The Spanish list chrome, list dates, sidebar and no results words, compiled from the es-ES.po source beside it. */
3
3
  declare const catalog: ListChromeCatalog;
4
4
  export default catalog;
@@ -1,5 +1,5 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
- /** The Spanish list chrome, list dates and sidebar words, compiled from the es-ES.po source beside it. */
2
+ /** The Spanish list chrome, list dates, sidebar and no results words, compiled from the es-ES.po source beside it. */
3
3
  const catalog = {
4
4
  '': { lang: 'es-ES', 'plural-forms': 'nplurals=2; plural=(n != 1);' },
5
5
  '%1$d of %2$d Item': ['%1$d de %2$d elemento', '%1$d de %2$d elementos'],
@@ -197,6 +197,9 @@ const catalog = {
197
197
  'Today, %s': ['Hoy, %s'],
198
198
  'Today, %s, selected': ['Hoy, %s, seleccionado'],
199
199
  True: ['Verdadero'],
200
+ "Try adjusting your search or filters to find what you're looking for.": [
201
+ 'Prueba a ajustar tu búsqueda o tus filtros para encontrar lo que buscas.',
202
+ ],
200
203
  Tue: ['Mar'],
201
204
  Tuesday: ['martes'],
202
205
  'Unknown status for %1$s': ['Estado desconocido para %1$s'],
@@ -1,4 +1,4 @@
1
1
  import type { ListChromeCatalog } from '../list-chrome.js';
2
- /** The French list dates, dialog words and sidebar words, compiled from the fr-FR.po source beside it. */
2
+ /** The French list dates, dialog, sidebar and no results words, compiled from the fr-FR.po source beside it. */
3
3
  declare const catalog: ListChromeCatalog;
4
4
  export default catalog;
@@ -1,5 +1,5 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
- /** The French list dates, dialog words and sidebar words, compiled from the fr-FR.po source beside it. */
2
+ /** The French list dates, dialog, sidebar and no results words, compiled from the fr-FR.po source beside it. */
3
3
  const catalog = {
4
4
  '': { lang: 'fr-FR', 'plural-forms': 'nplurals=2; plural=(n > 1);' },
5
5
  AM: ['AM'],
@@ -31,6 +31,7 @@ const catalog = {
31
31
  Mon: ['Lun'],
32
32
  Monday: ['lundi'],
33
33
  Navigation: ['Navigation'],
34
+ 'No results found': ['Aucun résultat trouvé'],
34
35
  November: ['novembre'],
35
36
  'November abbreviation\u0004Nov': ['Nov'],
36
37
  October: ['octobre'],
@@ -46,6 +47,9 @@ const catalog = {
46
47
  Sunday: ['dimanche'],
47
48
  Thu: ['Jeu'],
48
49
  Thursday: ['jeudi'],
50
+ "Try adjusting your search or filters to find what you're looking for.": [
51
+ "Essayez d'ajuster votre recherche ou vos filtres pour trouver ce que vous cherchez.",
52
+ ],
49
53
  Tue: ['Mar'],
50
54
  Tuesday: ['mardi'],
51
55
  Wed: ['Mer'],
@@ -1,16 +1,23 @@
1
1
  import { EmptyState } from '@wordpress/ui';
2
- import type { ComponentProps } from 'react';
2
+ import type { ComponentProps, ReactNode } from 'react';
3
3
  export interface ListEmptyProps {
4
4
  /** The icon drawn above the title, from `@wordpress/icons`. */
5
5
  icon: ComponentProps<typeof EmptyState.Icon>['icon'];
6
- /** The sentence saying the list is empty. */
6
+ /** The words saying the list is empty, one short phrase. */
7
7
  title: string;
8
- /** The line under the title, such as what to do to fill the list. */
9
- hint?: string;
8
+ /** The sentence under the title, such as what fills the list. */
9
+ description?: string;
10
+ /** The buttons under the description, such as the add button of the list at its default size. */
11
+ actions?: ReactNode;
10
12
  }
11
13
  /**
12
- * Renders what a list shows when it has no rows: an icon, a title one level under the page title and an optional hint.
13
- * @param props - The icon, the title and the hint.
14
+ * Renders what a list with no rows shows: an icon, a title one level under the page title, a description and buttons.
15
+ * @param props - The icon, the title, the description and the buttons.
14
16
  * @returns The empty state element.
15
17
  */
16
- export declare function ListEmpty({ icon, title, hint }: ListEmptyProps): import("react").JSX.Element;
18
+ export declare function ListEmpty({ icon, title, description, actions }: ListEmptyProps): import("react").JSX.Element;
19
+ /**
20
+ * Renders what a list shows when a search or a filter finds no rows, as Jetpack Forms says it.
21
+ * @returns The empty state element with the search icon and no buttons.
22
+ */
23
+ export declare function ListNoResults(): import("react").JSX.Element;
@@ -1,13 +1,23 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  // SPDX-License-Identifier: Apache-2.0
3
+ import { __ } from '@wordpress/i18n';
4
+ import { search } from '@wordpress/icons';
3
5
  import { EmptyState } from '@wordpress/ui';
4
6
  import { useHeadingUnderPage } from './page.js';
5
7
  /**
6
- * Renders what a list shows when it has no rows: an icon, a title one level under the page title and an optional hint.
7
- * @param props - The icon, the title and the hint.
8
+ * Renders what a list with no rows shows: an icon, a title one level under the page title, a description and buttons.
9
+ * @param props - The icon, the title, the description and the buttons.
8
10
  * @returns The empty state element.
9
11
  */
10
- export function ListEmpty({ icon, title, hint }) {
12
+ export function ListEmpty({ icon, title, description, actions }) {
11
13
  const Heading = useHeadingUnderPage();
12
- return (_jsxs(EmptyState.Root, { className: "godmin-empty", children: [_jsx(EmptyState.Icon, { icon: icon }), _jsx(EmptyState.Title, { render: _jsx(Heading, {}), children: title }), hint === undefined ? null : _jsx(EmptyState.Description, { children: hint })] }));
14
+ const buttons = actions ?? false;
15
+ return (_jsxs(EmptyState.Root, { className: "godmin-empty", children: [_jsx(EmptyState.Icon, { icon: icon }), _jsx(EmptyState.Title, { render: _jsx(Heading, {}), children: title }), description === undefined ? null : _jsx(EmptyState.Description, { children: description }), buttons === false ? null : _jsx(EmptyState.Actions, { children: buttons })] }));
16
+ }
17
+ /**
18
+ * Renders what a list shows when a search or a filter finds no rows, as Jetpack Forms says it.
19
+ * @returns The empty state element with the search icon and no buttons.
20
+ */
21
+ export function ListNoResults() {
22
+ return (_jsx(ListEmpty, { icon: search, title: __('No results found'), description: __("Try adjusting your search or filters to find what you're looking for.") }));
13
23
  }
@@ -1,17 +1,21 @@
1
1
  import type { RefObject } from 'react';
2
- /** Settles a run on its list, focusing the list once an item moved while the reader is still on it. */
2
+ /** Settles a run on its list, focusing the list with no scroll once an item moved while the reader is still on it. */
3
3
  export type RunSettled = (moved: boolean) => void;
4
4
  /** What a list does around a run over its items. */
5
5
  export interface ListRun {
6
6
  /** Starts a run on this list and returns what settles it. */
7
7
  onStart: () => RunSettled;
8
+ /** Marks the list as reloading after its own write and returns what ends that reload. */
9
+ onRefresh: () => () => void;
8
10
  }
9
- /** The run a list's actions start and the region a finished run focuses. */
11
+ /** The run a list's actions start, the region a finished run focuses, and whether the list reloads. */
10
12
  export interface ListRunState {
11
13
  /** What the list does around a run, the same object for as long as the screen stays. */
12
14
  run: ListRun;
13
15
  /** The list region a finished run focuses, handed to `Page` as `listRef`. */
14
16
  region: RefObject<HTMLDivElement | null>;
17
+ /** Whether a run reloads the list after its own write, to pass to DataViews `isLoading`. */
18
+ refreshing: boolean;
15
19
  }
16
20
  /**
17
21
  * Reports whether a dialog holds the focus, which a write finished in the background leaves where it is.
@@ -19,9 +23,9 @@ export interface ListRunState {
19
23
  */
20
24
  export declare function focusInDialog(): boolean;
21
25
  /**
22
- * Holds the region a run focuses while the reader stays on it, and drops older runs and ticked rows on a list change.
26
+ * Holds the region a run focuses, gives its focus back once the list reloaded, and drops old runs on a list change.
23
27
  * @param scope - Names the list on show.
24
28
  * @param onChangeSelection - Replaces the ticked rows, emptied when the list changes.
25
- * @returns The run and the region.
29
+ * @returns The run, the region and whether the list reloads.
26
30
  */
27
31
  export declare function useListRun(scope: string, onChangeSelection: (selection: string[]) => void): ListRunState;
package/dist/list-run.js CHANGED
@@ -1,9 +1,47 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  import { useLayoutEffect, useRef, useState } from 'react';
3
+ import { HOLDERS } from './focus-back.js';
3
4
  /** Finds the dialog or the alert dialog holding the focus. */
4
5
  const DIALOG_IN_FOCUS = '[role="dialog"]:focus-within, [role="alertdialog"]:focus-within';
6
+ /** Finds a part that turned inert while it holds the focus. */
7
+ const INERT_IN_FOCUS = '[inert]:focus-within';
8
+ /** Finds a dialog or an alert dialog that a control of the list opens. */
9
+ const DIALOG = '[role="dialog"], [role="alertdialog"]';
10
+ /** Finds every control a reader can focus inside a card or a row. */
11
+ const CONTROLS = 'a[href], button, input, select, textarea, [tabindex]';
12
+ /** Finds a button of a row that runs an action, never the actions menu button, which only opens a menu. */
13
+ const ACTION_BUTTON = '.dataviews-item-actions button:not(.dataviews-all-actions-button)';
5
14
  /** Stops nothing, for a run that watches no focus. */
6
15
  function stopNothing() { }
16
+ /**
17
+ * Counts the reloads a list has open, each ended once, and drops them all when the list changes.
18
+ * @returns Whether a reload is open, and how to start one or drop them all.
19
+ */
20
+ function useReloads() {
21
+ const [open, setOpen] = useState(0);
22
+ const [reloads] = useState(() => {
23
+ let generation = 0;
24
+ return {
25
+ start: () => {
26
+ const startedIn = generation;
27
+ let ended = false;
28
+ setOpen((count) => count + 1);
29
+ return () => {
30
+ if (ended || startedIn !== generation) {
31
+ return;
32
+ }
33
+ ended = true;
34
+ setOpen((count) => count - 1);
35
+ };
36
+ },
37
+ drop: () => {
38
+ generation += 1;
39
+ setOpen(0);
40
+ },
41
+ };
42
+ });
43
+ return [open !== 0, reloads];
44
+ }
7
45
  /**
8
46
  * Reports whether a dialog holds the focus, which a write finished in the background leaves where it is.
9
47
  * @returns Whether the focus sits inside a dialog or an alert dialog.
@@ -40,6 +78,71 @@ function watchLanding(startedIn) {
40
78
  function stillWhereDialogLeftIt(startedIn, landed) {
41
79
  return startedIn?.isConnected === false && document.activeElement === landed && !focusInDialog();
42
80
  }
81
+ /**
82
+ * Moves the focus to the list region, scrolling nothing, when it sits in a part of that list that turned inert.
83
+ * @param list - The list region, none while the screen draws no list.
84
+ */
85
+ function keepOnList(list) {
86
+ if (list?.querySelector(INERT_IN_FOCUS)) {
87
+ list.focus({ preventScroll: true });
88
+ }
89
+ }
90
+ /**
91
+ * Returns where a control stands in the list, its card or row, none for the region or outside it.
92
+ * @param list - The list region, none while the screen draws no list.
93
+ * @param focused - The element that holds the focus or just lost it.
94
+ * @returns The place, none when the element is the list region itself or sits outside it.
95
+ */
96
+ function placeOf(list, focused) {
97
+ if (focused === list || !list?.contains(focused)) {
98
+ return null;
99
+ }
100
+ const control = focused;
101
+ return { control, row: [...list.querySelectorAll(HOLDERS)].indexOf(control.closest(HOLDERS)) };
102
+ }
103
+ /**
104
+ * Returns the first control of the card or row that now sits where the place's sat, the last one when fewer came back.
105
+ * @param list - The list region.
106
+ * @param place - Where the reader stood.
107
+ * @returns The control, its box in a list with bulk actions, none for an action button or with no row in that place.
108
+ */
109
+ function firstInPlace(list, { row }) {
110
+ const rows = list.querySelectorAll(HOLDERS);
111
+ const first = rows.item(Math.min(row, rows.length - 1))?.querySelector(CONTROLS);
112
+ return first?.matches(ACTION_BUTTON) ? null : first;
113
+ }
114
+ /**
115
+ * Gives the focus back from the list region to the pressed control, else to the first control of the row in its place.
116
+ * @param list - The list region, none while the screen draws no list.
117
+ * @param place - Where the reader stood as the list took the focus, none when they stood nowhere in it.
118
+ */
119
+ function putBack(list, place) {
120
+ if (list === null || place === null) {
121
+ return;
122
+ }
123
+ const preventScroll = !list.matches(':focus-visible');
124
+ for (const control of [place.control, firstInPlace(list, place)]) {
125
+ if (document.activeElement === list) {
126
+ control?.focus({ preventScroll });
127
+ }
128
+ }
129
+ }
130
+ /**
131
+ * Notes the place of the control the focus leaves the list from for a dialog, none when it goes elsewhere.
132
+ * @param region - The list region, none while the screen draws no list.
133
+ * @param opener - Where the note goes.
134
+ * @returns What stops noting.
135
+ */
136
+ function noteOpener(region, opener) {
137
+ const note = (event) => {
138
+ const list = region.current;
139
+ if (list?.contains(event.target)) {
140
+ opener.current = event.relatedTarget?.closest(DIALOG) ? placeOf(list, event.target) : null;
141
+ }
142
+ };
143
+ document.addEventListener('focusout', note, true);
144
+ return () => document.removeEventListener('focusout', note, true);
145
+ }
43
146
  /**
44
147
  * Reports whether the focus sits on the page, in the list, in the dialog that ran, or where that dialog left it.
45
148
  * @param list - The list region, none while the screen draws no list.
@@ -53,16 +156,20 @@ function readerOnList(list, startedIn, landed) {
53
156
  return active === document.body || holds || stillWhereDialogLeftIt(startedIn, landed);
54
157
  }
55
158
  /**
56
- * Holds the region a run focuses while the reader stays on it, and drops older runs and ticked rows on a list change.
159
+ * Holds the region a run focuses, gives its focus back once the list reloaded, and drops old runs on a list change.
57
160
  * @param scope - Names the list on show.
58
161
  * @param onChangeSelection - Replaces the ticked rows, emptied when the list changes.
59
- * @returns The run and the region.
162
+ * @returns The run, the region and whether the list reloads.
60
163
  */
61
164
  export function useListRun(scope, onChangeSelection) {
62
165
  const region = useRef(null);
63
166
  const latest = useRef(0);
64
167
  const watching = useRef(stopNothing);
65
168
  const committed = useRef(scope);
169
+ const place = useRef(null);
170
+ const opener = useRef(null);
171
+ const [refreshing, reloads] = useReloads();
172
+ useLayoutEffect(() => noteOpener(region, opener), []);
66
173
  useLayoutEffect(() => {
67
174
  latest.current += 1;
68
175
  return () => watching.current();
@@ -70,27 +177,47 @@ export function useListRun(scope, onChangeSelection) {
70
177
  useLayoutEffect(() => {
71
178
  if (committed.current !== scope) {
72
179
  committed.current = scope;
180
+ place.current = null;
181
+ reloads.drop();
73
182
  onChangeSelection([]);
74
183
  }
75
- }, [scope, onChangeSelection]);
184
+ }, [scope, onChangeSelection, reloads]);
185
+ useLayoutEffect(() => {
186
+ if (refreshing) {
187
+ keepOnList(region.current);
188
+ return;
189
+ }
190
+ putBack(region.current, place.current);
191
+ place.current = null;
192
+ }, [refreshing]);
76
193
  const [run] = useState(() => ({
77
194
  onStart: () => {
78
195
  watching.current();
79
196
  latest.current += 1;
80
197
  const id = latest.current;
81
198
  const startedIn = document.querySelector(DIALOG_IN_FOCUS);
199
+ place.current = startedIn === null ? null : opener.current;
82
200
  const landing = watchLanding(startedIn);
83
201
  watching.current = landing.stop;
84
202
  return (moved) => {
85
203
  landing.stop();
86
- if (latest.current !== id || !moved) {
204
+ if (latest.current !== id) {
205
+ return;
206
+ }
207
+ if (!moved) {
208
+ place.current = null;
87
209
  return;
88
210
  }
89
211
  if (readerOnList(region.current, startedIn, landing.element)) {
90
- region.current?.focus();
212
+ place.current ??= placeOf(region.current, document.activeElement);
213
+ region.current?.focus({ preventScroll: true });
91
214
  }
92
215
  };
93
216
  },
217
+ onRefresh: () => {
218
+ place.current = placeOf(region.current, document.activeElement) ?? place.current;
219
+ return reloads.start();
220
+ },
94
221
  }));
95
- return { run, region };
222
+ return { run, region, refreshing };
96
223
  }