@jskit-ai/http-web 0.2.45 → 0.2.47

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/CHANGELOG.md CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - The CRUD screens' command buttons keep keyboard focus while they run, through shell-web's `pending` and `v-pending`: the form's Save while it saves or the record reloads after it (`addEdit.isSubmitPending`, new on `useAddEdit()` and the runtimes built on it, alongside `isSubmitDisabled`, which still includes it), the list's Refresh and "Load more", the Retry of a list, record or form that failed to load, and the delete dialog's Delete. Each reads as unavailable and ignores a second press meanwhile, where it was `disabled` and dropped focus to the page body (the dialog's Delete kept focus but never read as unavailable). A save the server refuses with a field error moves focus to that field. When the last page of "Load more" takes the button away, focus moves to the first record that page added.
5
6
  - A `useCommand()` run refused because the person lacks its `runPermissions` (`canRun` false) is no longer silent: it shows, through the command's feedback (its `message` and `messageType`, and the shell's action feedback), the notice the server's 403 for the same request shows (`ACTION_PERMISSION_DENIED`, "Forbidden." in the person's language). It still sends nothing and resolves `null`, so callers are unchanged, and `onRunError` does not run, as nothing was sent. Before, `run()` answered null with no request and no notice, so a tap did nothing visible. A run while the command is already running still answers null without a notice.
6
7
  - A list's, a record's or a form's load notice offers Retry only when trying again can help: after a network failure (no status), a timeout (408), a rate limit (429) or a server error (5xx). Before, it offered Retry on every failed load, also when the server had refused it (401, 403, 404, 422 and the other 4xx), where Retry only failed again; such a notice now has no action. One helper decides it for `useView()`, `useList()` and `useAddEdit()` (whose notice still offers nothing while `readEnabled` is false, and whose `canRetryLoad` and `refresh()` are unchanged).
7
8
  - `CrudListScreen`, `CrudViewScreen` and `CrudAddEditScreen` show their own Retry button under the same rule, so a refused load shows no Retry anywhere on the screen, and the three say the same thing about a refusal: the server's own message when the error carries one, otherwise a neutral text for its kind ("Sign in again to see this." for a 401, "You don't have access to this." for a 403, "This wasn't found." for a 404, "This couldn't be loaded." for another 4xx). Before, the button showed after every failed load, also next to a notice that offered none; the list screen said "Check the connection and try again." after a refusal too, and the record and form screens said "Unable to load resource." when the server sent no message. A failure trying again can help keeps its text: the list screen's `loadErrorBody` (by default "Check the connection and try again."), now shown only then, and the record and form screens' `loadError`. A runtime without `errorStatus`, such as one a page builds itself, keeps its Retry button and text as before; the list screen shows the `loadError` of a refusal from a runtime without `loadRefusalMessage`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/http-web",
3
- "version": "0.2.45",
3
+ "version": "0.2.47",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -52,15 +52,15 @@
52
52
  "peerDependencies": {
53
53
  "@jskit-ai/http-runtime": "0.2.27",
54
54
  "@jskit-ai/kernel": "0.2.27",
55
- "@jskit-ai/realtime": "0.2.41",
56
- "@jskit-ai/shell-web": "0.2.38",
55
+ "@jskit-ai/realtime": "0.2.43",
56
+ "@jskit-ai/shell-web": "0.2.40",
57
57
  "@tanstack/vue-query": "^5.90.5",
58
58
  "vue": "^3.5.13",
59
59
  "vue-router": "^5.0.4",
60
60
  "vuetify": "^4.3.0"
61
61
  },
62
62
  "devDependencies": {
63
- "@jskit-ai/material-web": "0.1.8"
63
+ "@jskit-ai/material-web": "0.1.9"
64
64
  },
65
65
  "description": "Neutral Vue request, command, resource, and CRUD UI runtime for JSKIT web applications.",
66
66
  "jskit": {
@@ -4,6 +4,7 @@ import ShellPageAction from "@jskit-ai/shell-web/client/components/ShellPageActi
4
4
  import ShellPageActions from "@jskit-ai/shell-web/client/components/ShellPageActions";
5
5
  import { useShellPageClose } from "@jskit-ai/shell-web/client/composables/useShellPageClose";
6
6
  import { useShellNavigation } from "@jskit-ai/shell-web/client/navigation/useShellNavigation";
7
+ import { vPending } from "@jskit-ai/shell-web/client/directives/vPending";
7
8
  import { isRetryableLoadStatus } from "../composables/support/resourceLoadStateHelpers.js";
8
9
  import { useJskitText } from "../i18n.js";
9
10
 
@@ -99,6 +100,7 @@ useShellPageClose({ label: () => t("jskit.http.actions.cancel"), close: cancel }
99
100
  primary
100
101
  :label="addEdit.isSaving ? t('jskit.http.actions.saving') : saveLabel"
101
102
  :disabled="addEdit.isSubmitDisabled"
103
+ :pending="addEdit.isSubmitPending"
102
104
  @click="addEdit.submit"
103
105
  />
104
106
  </slot>
@@ -111,7 +113,7 @@ useShellPageClose({ label: () => t("jskit.http.actions.cancel"), close: cancel }
111
113
  v-if="addEdit.canRetryLoad && loadFailureIsRetryable"
112
114
  color="secondary-container"
113
115
  prepend-icon="$refresh"
114
- :disabled="addEdit.isFetching"
116
+ v-pending="addEdit.isFetching"
115
117
  @click="addEdit.refresh"
116
118
  >
117
119
  {{ addEdit.isFetching ? t("jskit.http.actions.retrying") : t("jskit.http.actions.retry") }}
@@ -1,6 +1,7 @@
1
1
  <script setup>
2
2
  import { computed, useId } from "vue";
3
3
  import ShellPageAction from "@jskit-ai/shell-web/client/components/ShellPageAction";
4
+ import { vPending } from "@jskit-ai/shell-web/client/directives/vPending";
4
5
  import { useJskitText } from "../i18n.js";
5
6
 
6
7
  // Delete as a page action (in the top app bar, an icon on compact windows), confirmed in a Material 3 dialog.
@@ -84,6 +85,7 @@ function handleDialogModelUpdate(isOpen) {
84
85
  {{ t("jskit.http.actions.cancel") }}
85
86
  </v-btn>
86
87
  <v-btn
88
+ v-pending="action.isDeleting"
87
89
  color="error"
88
90
  variant="text"
89
91
  :disabled="!action.canDelete"
@@ -1,9 +1,10 @@
1
1
  <script setup>
2
- import { computed, unref } from "vue";
2
+ import { computed, nextTick, ref, unref, watch } from "vue";
3
3
  import { useRoute, useRouter } from "vue-router";
4
4
  import ShellPageAction from "@jskit-ai/shell-web/client/components/ShellPageAction";
5
5
  import ShellPageActions from "@jskit-ai/shell-web/client/components/ShellPageActions";
6
6
  import ShellPrimaryAction from "@jskit-ai/shell-web/client/components/ShellPrimaryAction";
7
+ import { vPending } from "@jskit-ai/shell-web/client/directives/vPending";
7
8
  import CrudListBulkActionSurface from "./CrudListBulkActionSurface.vue";
8
9
  import CrudListFilterSurface from "./CrudListFilterSurface.vue";
9
10
  import CrudListRecordActionMenu from "./CrudListRecordActionMenu.vue";
@@ -105,6 +106,43 @@ function openRow(row, event) {
105
106
  void router.push(location);
106
107
  }
107
108
 
109
+ // "Load more" keeps focus while the next page loads (v-pending). The last page takes the button away; if it had focus,
110
+ // focus goes where reading goes on, to the first record that page added, instead of falling back to the page body.
111
+ const listRoot = ref(null);
112
+ const moreButton = ref(null);
113
+ const ROW_FOCUSABLE = "a[href], button:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex='-1'])";
114
+ let firstAddedRow = -1;
115
+
116
+ function loadMore() {
117
+ firstAddedRow = displayRows.value.length;
118
+ return records.value.loadMore();
119
+ }
120
+
121
+ function focusRow(index) {
122
+ const root = listRoot.value;
123
+ const candidates = [
124
+ root?.querySelectorAll(".crud-list-cards > .crud-list-card")[index],
125
+ root?.querySelectorAll(".crud-list-table tbody > tr")[index]
126
+ ];
127
+ const row = candidates.find((element) => element && element.getClientRects().length > 0);
128
+ row?.querySelector(ROW_FOCUSABLE)?.focus();
129
+ }
130
+
131
+ watch(
132
+ () => records.value.hasMore,
133
+ (hasMore) => {
134
+ const row = firstAddedRow;
135
+ if (hasMore || row < 0) {
136
+ return;
137
+ }
138
+ firstAddedRow = -1;
139
+ if (moreButton.value?.$el?.contains(document.activeElement)) {
140
+ void nextTick(() => focusRow(row));
141
+ }
142
+ },
143
+ { flush: "pre" }
144
+ );
145
+
108
146
  function hasRowActionsFor(record, index) {
109
147
  return rowActions.value.hasVisibleActionsFor(record, index);
110
148
  }
@@ -133,12 +171,12 @@ function setSelectableRowsSelected(selected = true) {
133
171
  </script>
134
172
 
135
173
  <template>
136
- <section class="crud-screen crud-list">
174
+ <section ref="listRoot" class="crud-screen crud-list">
137
175
  <ShellPageActions>
138
176
  <ShellPageAction
139
177
  icon="$refresh"
140
178
  :label="records.isFetching ? t('jskit.http.actions.refreshing') : t('jskit.http.actions.refresh')"
141
- :disabled="records.isFetching"
179
+ :pending="records.isFetching"
142
180
  @click="records.reload"
143
181
  />
144
182
  </ShellPageActions>
@@ -177,7 +215,7 @@ function setSelectableRowsSelected(selected = true) {
177
215
  v-if="canRetryLoad"
178
216
  color="secondary-container"
179
217
  prepend-icon="$refresh"
180
- :disabled="records.isFetching"
218
+ v-pending="records.isFetching"
181
219
  @click="records.reload"
182
220
  >
183
221
  {{ records.isFetching ? t("jskit.http.actions.retrying") : t("jskit.http.actions.retry") }}
@@ -327,10 +365,11 @@ function setSelectableRowsSelected(selected = true) {
327
365
 
328
366
  <div v-if="records.hasMore" class="crud-list-more">
329
367
  <v-btn
368
+ ref="moreButton"
369
+ v-pending="records.isLoadingMore"
330
370
  variant="outlined"
331
371
  color="primary"
332
- :disabled="records.isLoadingMore"
333
- @click="records.loadMore"
372
+ @click="loadMore"
334
373
  >
335
374
  {{ records.isLoadingMore ? t("jskit.http.actions.loadingMore") : t("jskit.http.actions.loadMore") }}
336
375
  </v-btn>
@@ -3,6 +3,7 @@ import { computed, unref, watch } from "vue";
3
3
  import ShellPageAction from "@jskit-ai/shell-web/client/components/ShellPageAction";
4
4
  import ShellPageActions from "@jskit-ai/shell-web/client/components/ShellPageActions";
5
5
  import { useShellNavigation } from "@jskit-ai/shell-web/client/navigation/useShellNavigation";
6
+ import { vPending } from "@jskit-ai/shell-web/client/directives/vPending";
6
7
  import { isRetryableLoadStatus } from "../composables/support/resourceLoadStateHelpers.js";
7
8
  import { useJskitText } from "../i18n.js";
8
9
 
@@ -66,7 +67,7 @@ watch(isUnavailable, (unavailable) => {
66
67
  v-if="canRetryLoad"
67
68
  color="secondary-container"
68
69
  prepend-icon="$refresh"
69
- :disabled="view.isFetching"
70
+ v-pending="view.isFetching"
70
71
  @click="view.refresh"
71
72
  >
72
73
  {{ view.isFetching ? t("jskit.http.actions.retrying") : t("jskit.http.actions.retry") }}
@@ -180,6 +180,9 @@ function useAddEdit({
180
180
  const isSubmitDisabled = computed(() =>
181
181
  Boolean(isInitialLoading.value || isRefetching.value || !canSave.value || addEdit.saving.value)
182
182
  );
183
+ // The part of isSubmitDisabled that passes by itself: the save, or the record's reload, is running. Save keeps
184
+ // keyboard focus meanwhile (ShellPageAction's `pending`, or v-pending), instead of being disabled.
185
+ const isSubmitPending = computed(() => Boolean(addEdit.saving.value || isRefetching.value));
183
186
  const loadError = operationScope.loadError(endpointResource.loadError);
184
187
  // The HTTP status of the failed load, or 0: the form's Retry and its notice offer Retry only when it can help.
185
188
  const errorStatus = computed(() => resolveLoadErrorStatus(endpointResource.query.error.value));
@@ -218,6 +221,7 @@ function useAddEdit({
218
221
  isRefetching,
219
222
  isFieldLocked,
220
223
  isSubmitDisabled,
224
+ isSubmitPending,
221
225
  canRetryLoad,
222
226
  isLoading,
223
227
  isSaving: addEdit.saving,
@@ -312,6 +312,7 @@ test("permission gating and duplicate-submit protection cover the request and su
312
312
  canSave.value = false;
313
313
  await nextTick();
314
314
  assert.equal(button("Save book").props.disabled, true);
315
+ assert.equal(addEdit.isSubmitPending, false, "a Save the person may not use is unavailable, not running");
315
316
  await addEdit.submit();
316
317
  assert.equal(calls.length, 0);
317
318
  assert.equal(addEdit.validationAttempted, false);
@@ -323,17 +324,22 @@ test("permission gating and duplicate-submit protection cover the request and su
323
324
  await nextTick();
324
325
  assert.equal(calls.length, 1);
325
326
  assert.equal(button("Saving…").props.disabled, true);
327
+ // While it runs Save is pending, which wins over disabled, so the button keeps keyboard focus.
328
+ assert.equal(addEdit.isSubmitPending, true);
329
+ assert.equal(button("Saving…").props.pending, true);
326
330
  assert.equal(addEdit.isFieldLocked, true);
327
331
  response.resolve({ id: 1, title: "Book", author: "Author" });
328
332
  await new Promise((resolve) => setImmediate(resolve));
329
333
  assert.equal(addEdit.resource.isSaving.value, false);
330
334
  assert.equal(addEdit.isSaving, true);
335
+ assert.equal(addEdit.isSubmitPending, true, "Save stays pending through the success callback");
331
336
  await addEdit.submit();
332
337
  assert.equal(calls.length, 1);
333
338
  success.resolve();
334
339
  await pending;
335
340
  assert.equal(addEdit.isSaving, false);
336
341
  assert.equal(addEdit.isSubmitDisabled, false);
342
+ assert.equal(addEdit.isSubmitPending, false);
337
343
  });
338
344
 
339
345
  test("local validation feedback opt-out preserves permission, network, and server failure feedback", async (t) => {
@@ -0,0 +1,293 @@
1
+ import assert from "node:assert/strict";
2
+ import path from "node:path";
3
+ import process from "node:process";
4
+ import test from "node:test";
5
+ import { fileURLToPath } from "node:url";
6
+ import { expect } from "@playwright/test";
7
+ import { sharedBrowserFixture } from "../../../tooling/testUtils/browserFixture.mjs";
8
+
9
+ // A command button that is disabled while its action runs loses keyboard focus: in Chromium the focused button that
10
+ // becomes `disabled` hands focus to the page body, so a keyboard user who pressed Save or "Load more" lands back at
11
+ // the top of the page. These tests drive the CRUD screens (the crud-screen-set pattern's pages in the real shell) by
12
+ // keyboard alone: Tab to the button, Enter, hold the request, then let it settle, and check that focus never fell to
13
+ // the body, that the button read as unavailable meanwhile and that a second Enter did nothing.
14
+ const SKIP = process.env.JSKIT_HTTP_WEB_PENDING_FOCUS_BROWSER === "1"
15
+ ? false
16
+ : "set JSKIT_HTTP_WEB_PENDING_FOCUS_BROWSER=1 to check that pending CRUD buttons keep keyboard focus";
17
+ const FIXTURE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../fixtures/crud-screens");
18
+ const open = sharedBrowserFixture({ fixtureRoot: FIXTURE_ROOT });
19
+ // An expanded window: the app bar shows its actions labelled, and the list draws its table.
20
+ const VIEWPORT = Object.freeze({ width: 1280, height: 900 });
21
+
22
+ function book(id) {
23
+ return {
24
+ type: "books",
25
+ id: String(id),
26
+ attributes: {
27
+ title: `Book ${id}`,
28
+ author: `Author ${id}`,
29
+ notes: null,
30
+ createdAt: "2026-01-02T10:00:00.000Z",
31
+ updatedAt: "2026-01-02T10:00:00.000Z"
32
+ }
33
+ };
34
+ }
35
+
36
+ const JSON_API = "application/vnd.api+json";
37
+
38
+ // The books API, with the requests a test holds: `hold(method, pathname)` makes the next matching request wait until
39
+ // the test answers it, and resolves to `{ request, answer(response) }` once that request arrives.
40
+ async function serveBooks(page, { pages = [[1, 2, 3]] } = {}) {
41
+ const held = [];
42
+ const requests = [];
43
+ function hold(method, pathname) {
44
+ return new Promise((resolve) => held.push({ method, pathname, resolve }));
45
+ }
46
+ await page.route("**/api/**", async (route) => {
47
+ const request = route.request();
48
+ const url = new URL(request.url());
49
+ const method = request.method();
50
+ requests.push(`${method} ${url.pathname}${url.search}`);
51
+ if (url.pathname === "/api/session") {
52
+ await route.fulfill({ contentType: "application/json", body: JSON.stringify({ csrfToken: "test-token" }) });
53
+ return;
54
+ }
55
+ const waiting = held.findIndex((entry) => entry.method === method && entry.pathname === url.pathname);
56
+ if (waiting >= 0) {
57
+ const [entry] = held.splice(waiting, 1);
58
+ await new Promise((answered) => {
59
+ entry.resolve({
60
+ request,
61
+ answer: async (response) => {
62
+ await route.fulfill(response).catch(() => {});
63
+ answered();
64
+ }
65
+ });
66
+ });
67
+ return;
68
+ }
69
+ if (method === "GET" && url.pathname === "/api/books") {
70
+ const cursor = [...url.searchParams.values()].find((value) => value.startsWith("cursor-"));
71
+ const index = cursor ? Number(cursor.slice("cursor-".length)) : 0;
72
+ await route.fulfill(listPage(pages, index));
73
+ return;
74
+ }
75
+ const record = /^\/api\/books\/([^/]+)$/u.exec(url.pathname);
76
+ if (method === "GET" && record) {
77
+ await route.fulfill({ contentType: JSON_API, body: JSON.stringify({ data: book(record[1]) }) });
78
+ return;
79
+ }
80
+ await route.fulfill({
81
+ status: 404,
82
+ contentType: JSON_API,
83
+ body: JSON.stringify({ errors: [{ status: "404", title: "Not found" }] })
84
+ });
85
+ });
86
+ return { hold, requests };
87
+ }
88
+
89
+ // Page `index` of the list: its books, and the next page's cursor (JSON:API `meta.pagination.cursor.next`) while there
90
+ // is one.
91
+ function listPage(pages, index) {
92
+ const meta = index + 1 < pages.length ? { pagination: { cursor: { next: `cursor-${index + 1}` } } } : {};
93
+ return {
94
+ contentType: JSON_API,
95
+ body: JSON.stringify({ data: pages[index].map(book), meta })
96
+ };
97
+ }
98
+
99
+ // Records, at every frame until stopped, each time focus is on the page body (or nowhere): what a keyboard or
100
+ // screen-reader user would land on.
101
+ async function watchFocus(page) {
102
+ await page.evaluate(() => {
103
+ const lost = [];
104
+ let watching = true;
105
+ const sample = () => {
106
+ const active = document.activeElement;
107
+ if (!active || active === document.body || active === document.documentElement) {
108
+ lost.push(performance.now());
109
+ }
110
+ if (watching) {
111
+ requestAnimationFrame(sample);
112
+ }
113
+ };
114
+ requestAnimationFrame(sample);
115
+ globalThis.jskitPendingFocusWatch = () => {
116
+ watching = false;
117
+ return lost.length;
118
+ };
119
+ });
120
+ return {
121
+ framesOnBody: () => page.evaluate(() => globalThis.jskitPendingFocusWatch())
122
+ };
123
+ }
124
+
125
+ // Presses Tab (from wherever focus is) until `locator` has focus, as a keyboard user reaches it.
126
+ async function tabTo(page, locator, { max = 80 } = {}) {
127
+ await locator.waitFor({ state: "visible", timeout: 10_000 });
128
+ for (let presses = 0; presses <= max; presses += 1) {
129
+ if (await locator.evaluate((element) => element === document.activeElement)) {
130
+ return;
131
+ }
132
+ await page.keyboard.press("Tab");
133
+ }
134
+ throw new Error(`Tab never reached ${locator}`);
135
+ }
136
+
137
+ async function openPage(t) {
138
+ const { vite, browser } = await open(t);
139
+ return browser.newPage({
140
+ baseURL: vite.baseURL,
141
+ viewport: VIEWPORT,
142
+ locale: "en-US",
143
+ reducedMotion: "reduce",
144
+ timezoneId: "UTC"
145
+ });
146
+ }
147
+
148
+ // No second request arrives while the first is held: Enter on the pending button did nothing.
149
+ async function expectNoSecondRequest(page, requests, label) {
150
+ const before = requests.filter((entry) => entry.startsWith(label)).length;
151
+ await page.keyboard.press("Enter");
152
+ await page.waitForTimeout(300);
153
+ assert.equal(requests.filter((entry) => entry.startsWith(label)).length, before, `a second Enter sent another ${label}`);
154
+ }
155
+
156
+ test("the edit form's Save keeps focus while it saves, and a refusal that marks a field focuses that field", {
157
+ skip: SKIP,
158
+ timeout: 120_000
159
+ }, async (t) => {
160
+ const page = await openPage(t);
161
+ const { hold, requests } = await serveBooks(page);
162
+ await page.goto("/books/1/edit");
163
+ await expect(page.locator(".crud-add-edit-form__fields .v-field--dirty").first()).toBeVisible();
164
+
165
+ const save = page.getByRole("button", { name: "Save changes" });
166
+ await tabTo(page, save);
167
+ const watch = await watchFocus(page);
168
+ const patch = hold("PATCH", "/api/books/1");
169
+ await page.keyboard.press("Enter");
170
+ const pending = await patch;
171
+
172
+ const saving = page.getByRole("button", { name: "Saving…" });
173
+ await expect(saving).toBeFocused();
174
+ await expect(saving).toHaveAttribute("aria-disabled", "true");
175
+ await expectNoSecondRequest(page, requests, "PATCH /api/books/1");
176
+ await expect(saving).toBeFocused();
177
+
178
+ await pending.answer({
179
+ status: 422,
180
+ contentType: JSON_API,
181
+ body: JSON.stringify({
182
+ errors: [{
183
+ status: "422",
184
+ title: "Validation failed",
185
+ detail: "Another book has this author.",
186
+ source: { pointer: "/data/attributes/author" }
187
+ }]
188
+ })
189
+ });
190
+ const author = page.getByRole("textbox", { name: "Author" });
191
+ await expect(page.locator(".crud-add-edit-form__fields .v-input--error")).toHaveCount(1);
192
+ await expect(author).toBeFocused();
193
+ assert.equal(await watch.framesOnBody(), 0, "focus fell to the page body while Save was pending");
194
+ await expect(page.getByRole("button", { name: "Save changes" })).not.toHaveAttribute("aria-disabled", "true");
195
+ });
196
+
197
+ test("the list's Refresh keeps focus while the list reloads", { skip: SKIP, timeout: 120_000 }, async (t) => {
198
+ const page = await openPage(t);
199
+ const { hold, requests } = await serveBooks(page);
200
+ await page.goto("/books");
201
+ await expect(page.locator(".crud-list-table tbody tr").first()).toBeVisible();
202
+
203
+ const refresh = page.getByRole("button", { name: "Refresh", exact: true });
204
+ await tabTo(page, refresh);
205
+ const watch = await watchFocus(page);
206
+ const reload = hold("GET", "/api/books");
207
+ await page.keyboard.press("Enter");
208
+ const pending = await reload;
209
+
210
+ const refreshing = page.getByRole("button", { name: "Refreshing…" });
211
+ await expect(refreshing).toBeFocused();
212
+ await expect(refreshing).toHaveAttribute("aria-disabled", "true");
213
+ await expectNoSecondRequest(page, requests, "GET /api/books");
214
+
215
+ await pending.answer(listPage([[1, 2, 3]], 0));
216
+ await expect(refresh).toBeFocused();
217
+ await expect(refresh).not.toHaveAttribute("aria-disabled", "true");
218
+ assert.equal(await watch.framesOnBody(), 0, "focus fell to the page body while Refresh was pending");
219
+ });
220
+
221
+ test("\"Load more\" keeps focus while each page loads, and the last page hands focus to its first record", {
222
+ skip: SKIP,
223
+ timeout: 120_000
224
+ }, async (t) => {
225
+ const page = await openPage(t);
226
+ const { hold, requests } = await serveBooks(page, { pages: [[1, 2, 3], [4, 5, 6], [7, 8]] });
227
+ await page.goto("/books");
228
+ await expect(page.locator(".crud-list-table tbody tr")).toHaveCount(3);
229
+
230
+ const loadMore = page.getByRole("button", { name: "Load more" });
231
+ await tabTo(page, loadMore);
232
+ const watch = await watchFocus(page);
233
+
234
+ // A middle page: the button stays, with focus.
235
+ let next = hold("GET", "/api/books");
236
+ await page.keyboard.press("Enter");
237
+ let pending = await next;
238
+ const loading = page.getByRole("button", { name: "Loading more…" });
239
+ await expect(loading).toBeFocused();
240
+ await expect(loading).toHaveAttribute("aria-disabled", "true");
241
+ await expectNoSecondRequest(page, requests, "GET /api/books");
242
+ await pending.answer(listPage([[1, 2, 3], [4, 5, 6], [7, 8]], 1));
243
+ await expect(page.locator(".crud-list-table tbody tr")).toHaveCount(6);
244
+ await expect(loadMore).toBeFocused();
245
+
246
+ // The last page: the button goes, and focus moves to the first record it added.
247
+ next = hold("GET", "/api/books");
248
+ await page.keyboard.press("Enter");
249
+ pending = await next;
250
+ await expect(loading).toBeFocused();
251
+ await pending.answer(listPage([[1, 2, 3], [4, 5, 6], [7, 8]], 2));
252
+ await expect(page.locator(".crud-list-table tbody tr")).toHaveCount(8);
253
+ await expect(loadMore).toHaveCount(0);
254
+ const seventh = page.locator(".crud-list-table tbody tr").nth(6);
255
+ await expect.poll(() => seventh.evaluate((row) => row.contains(document.activeElement))).toBe(true);
256
+ assert.equal(await watch.framesOnBody(), 0, "focus fell to the page body while \"Load more\" was pending");
257
+ });
258
+
259
+ test("the delete dialog's Delete keeps focus while it deletes, and stays in the dialog when the delete fails", {
260
+ skip: SKIP,
261
+ timeout: 120_000
262
+ }, async (t) => {
263
+ const page = await openPage(t);
264
+ const { hold, requests } = await serveBooks(page);
265
+ await page.goto("/books/1");
266
+ await expect(page.locator(".crud-view-header")).toBeVisible();
267
+
268
+ await tabTo(page, page.getByRole("button", { name: "Delete book" }));
269
+ await page.keyboard.press("Enter");
270
+ const dialog = page.getByRole("alertdialog");
271
+ await expect(dialog).toBeVisible();
272
+ const confirm = dialog.getByRole("button", { name: "Delete", exact: true });
273
+ await tabTo(page, confirm, { max: 4 });
274
+ const watch = await watchFocus(page);
275
+ const remove = hold("DELETE", "/api/books/1");
276
+ await page.keyboard.press("Enter");
277
+ const pending = await remove;
278
+
279
+ const deleting = dialog.getByRole("button", { name: "Deleting…" });
280
+ await expect(deleting).toBeFocused();
281
+ await expect(deleting).toHaveAttribute("aria-disabled", "true");
282
+ await expectNoSecondRequest(page, requests, "DELETE /api/books/1");
283
+
284
+ await pending.answer({
285
+ status: 500,
286
+ contentType: JSON_API,
287
+ body: JSON.stringify({ errors: [{ status: "500", title: "Server error", detail: "The book is on loan." }] })
288
+ });
289
+ await expect(dialog.getByText("The book is on loan.")).toBeVisible();
290
+ await expect(confirm).toBeFocused();
291
+ await expect(confirm).not.toHaveAttribute("aria-disabled", "true");
292
+ assert.equal(await watch.framesOnBody(), 0, "focus fell to the page body while Delete was pending");
293
+ });