@ismailnakkar/ui-behaviours 0.5.0 → 0.7.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
@@ -2,8 +2,10 @@
2
2
 
3
3
  Page behaviours from plain HTML attributes: copy to the clipboard and say the result to screen readers, confirm
4
4
  a submit, send a form once, send a form on a change, open, close and light-dismiss a native `<dialog>`, walk a form's
5
- steps one at a time, show what a radio, a checkbox or a select chose, check every row from a header box, and select a
6
- field's text on a click. They listen on the document, so markup added later works too.
5
+ steps one at a time, show what a radio, a checkbox or a select chose, check every row from a header box, select a
6
+ field's text on a click, dismiss a banner, and close a `<details>` menu on an outside click or Escape. They listen on
7
+ the document, so markup added later works too. A `post()` helper sends a page script's request the way Laravel expects
8
+ one.
7
9
 
8
10
  A date range picker over [Cally](https://wicky.nillia.ms/cally/) has its own entry, so pages without one never load the
9
11
  calendar, and an optional stylesheet themed by custom properties. Nothing else ships styles, and nothing ships wording:
@@ -49,6 +51,8 @@ Then mark up the page:
49
51
  | [`data-clear-on="name"`](#data-show-ifnamevalue-and-data-clear-onname) | a field in a form | empties it when another radio `name` is picked |
50
52
  | [`data-check-all="name"`](#data-check-allname) | a header checkbox | checks every row named `name` |
51
53
  | [`data-autoselect`](#data-autoselect) | an input or a textarea | selects its text on a click |
54
+ | [`data-dismiss`](#data-dismiss) | a button in a banner | fades the banner out and hides it |
55
+ | [`data-dropdown`](#data-dropdown) | a `<details>` | closes it on a click outside it or Escape |
52
56
 
53
57
  ### `data-copy="id"`
54
58
 
@@ -184,24 +188,20 @@ by one form.
184
188
  <dialog id="two-factor-dialog" aria-labelledby="two-factor-title" data-steps>
185
189
  <h2 id="two-factor-title">Turn on two-factor</h2>
186
190
  <div aria-hidden="true">
187
- <i data-step-mark="1" data-step-state="current"></i><i data-step-mark="2"></i><i data-step-mark="3"></i>
191
+ <i data-step-mark data-step-state="current"></i><i data-step-mark></i><i data-step-mark></i>
188
192
  </div>
189
- <p aria-live="polite">
190
- <span data-step-label="1">Step 1 of 3</span>
191
- <span data-step-label="2" hidden>Step 2 of 3</span>
192
- <span data-step-label="3" hidden>Step 3 of 3</span>
193
- </p>
193
+ <p aria-live="polite" data-step-progress="Step :step of :steps"></p>
194
194
 
195
195
  <form id="two-factor-enable" method="POST" action="/user/two-factor-authentication">
196
- <section data-step="1">
196
+ <section data-step="scan">
197
197
  <h3 tabindex="-1">Scan the QR code</h3>
198
198
  …
199
199
  </section>
200
- <section data-step="2" hidden>
200
+ <section data-step="email" hidden>
201
201
  <h3 tabindex="-1">Confirm your email</h3>
202
202
  <input name="email_code" required autocomplete="one-time-code">
203
203
  </section>
204
- <section data-step="3" hidden>
204
+ <section data-step="app" hidden>
205
205
  <h3 tabindex="-1">Enter the code from your app</h3>
206
206
  <input name="code" required aria-invalid="true" aria-describedby="code-error" autocomplete="one-time-code">
207
207
  <p id="code-error">The code is not valid.</p>
@@ -215,8 +215,9 @@ by one form.
215
215
  </dialog>
216
216
  ```
217
217
 
218
- - **`data-step="n"`** on each step, numbered from 1 in the order they come, all inside one form. Only the step showing
219
- is not `hidden`. Its fields are the inputs, selects and textareas in it.
218
+ - **`data-step`** on each step, all inside one form: the steps go in the order they come, so none is numbered. Its
219
+ value is a name, needed only for `data-open-at-step` to point at; `data-step` alone is fine. Only the step showing is
220
+ not `hidden`. Its fields are the inputs, selects and textareas in it.
220
221
  - **`data-step-next`**: checks the step's fields (`reportValidity()`, so the browser says what is missing), then shows
221
222
  the next step and focuses its first heading; give the heading `tabindex="-1"`. From the last step it submits, as
222
223
  `data-step-submit` does. Enter in an input of a step does the same, so the form's own submit never skips a step's
@@ -224,9 +225,12 @@ by one form.
224
225
  - **`data-step-back`** shows the step before.
225
226
  - **`data-step-submit`**: checks every step's fields; one left empty shows its step and the browser's message, else the
226
227
  form is sent (`requestSubmit()`, so `data-confirm` and `data-submit-once` apply).
227
- - **`data-step-mark="n"`**, a progress mark: gets `data-step-state="done"` behind the step showing and `"current"` for
228
- it; the marks ahead have none.
229
- - **`data-step-label="n"`**: shown only while step `n` shows, such as "Step 2 of 3" in a live region.
228
+ - **`data-step-mark`**, a progress mark, one per step in the same order: gets `data-step-state="done"` behind the step
229
+ showing and `"current"` for it; the marks ahead have none.
230
+ - **`data-step-progress="…"`**: the stepper writes this wording as the element's text, with `:step` as the showing
231
+ step's place from 1 and `:steps` as the count, such as "Step 2 of 3" in a live region. Laravel's `__()` given no
232
+ replacements leaves both placeholders in, so `data-step-progress="{{ __('enrolment.progress') }}"` works in every
233
+ locale.
230
234
 
231
235
  The controls may sit anywhere in the stepper, in or out of the form; one that is a submit button moves the steps without
232
236
  sending the form. Back is hidden on the first step, Next on the last, and Submit on every other.
@@ -237,11 +241,12 @@ On install, a stepper opens (`showModal()` on a dialog) at:
237
241
  refused submit came back as. A field the server never hands back, such as a mailed code, is empty again, so its step
238
242
  comes first. `aria-invalid="true"` is the one error mark the stepper reads: set it on each field the server refused,
239
243
  with its message.
240
- 2. else **`data-open-at-step="n"`** on the stepper, such as the email step on the page after "Email me a code";
244
+ 2. else **`data-open-at-step="name"`** on the stepper, the step whose `data-step` has that name, such as the email
245
+ step on the page after "Email me a code";
241
246
  3. else nowhere: a dialog stays shut, and the stepper shows the step the server drew.
242
247
 
243
- Draw the first state on the server too (step 1 showing, its mark current, Back and Submit hidden): it is what shows
244
- before the script runs. A stepper added later works, but opens at nothing.
248
+ Draw the first state on the server too (the first step showing, its mark current, Back and Submit hidden): it is what
249
+ shows before the script runs. The `data-step-progress` text is written on install. A stepper added later works, but opens at nothing.
245
250
 
246
251
  ### `data-show-if="name=value"` and `data-clear-on="name"`
247
252
 
@@ -305,6 +310,34 @@ On an input or a textarea: a click selects all of its text, as tabbing in alread
305
310
  <input value="https://example.com/abcd" readonly data-autoselect>
306
311
  ```
307
312
 
313
+ ### `data-dismiss`
314
+
315
+ On a button that is a direct child of a banner (a flash message, a toast): a click fades the banner out over 150ms,
316
+ `inert` meanwhile, then sets `hidden` on it. Under reduced motion, or without the Web Animations API, it hides at once.
317
+ The banner stays in the page, so a script may show it again by clearing `hidden` (`banner.hidden = false`); during the
318
+ fade, cancel it first (`banner.getAnimations().forEach((animation) => animation.cancel())`), or it hides. When focus
319
+ was inside the banner it moves to the page's `<main>` first, so a keyboard user keeps their place. A click the page
320
+ cancelled dismisses nothing.
321
+
322
+ ```html
323
+ <div role="status" class="flash">
324
+ <p>Link saved.</p>
325
+ <button type="button" data-dismiss aria-label="Dismiss">×</button>
326
+ </div>
327
+ ```
328
+
329
+ ### `data-dropdown`
330
+
331
+ On a `<details>` used as a menu: a click anywhere outside an open one closes it, and Escape closes every open one and
332
+ focuses its `<summary>`, which a `<details>` does not do itself. Other `<details>` (an FAQ) are left alone.
333
+
334
+ ```html
335
+ <details data-dropdown>
336
+ <summary>English</summary>
337
+ <form method="POST" action="/locale">…</form>
338
+ </details>
339
+ ```
340
+
308
341
  ## Styling
309
342
 
310
343
  The package sets attributes and the browser's own states; the app styles them:
@@ -312,6 +345,10 @@ The package sets attributes and the browser's own states; the app styles them:
312
345
  - `[data-copied]` and `[data-copy-failed]` on a copy button: show its "Copied" or "Copy it by hand" label instead of
313
346
  "Copy". The words are the app's, in the button.
314
347
  - `[data-submitting]` on a form sent once, to show the wait.
348
+ - `[hidden]` on a dismissed banner. A `display` of the app's own on the banner (a `flex` class, an inline
349
+ `style="display: flex"`) beats the attribute: hide it with `[hidden] { display: none !important; }` (Tailwind 4's
350
+ preflight has this rule), and show a reused banner by clearing `hidden`, not by setting `display`.
351
+ - `details[open]` for an open `data-dropdown`.
315
352
  - `[data-step-state="done"]` and `[data-step-state="current"]` on a stepper's progress marks.
316
353
  - `dialog`, `dialog::backdrop`, and `dialog[open]` for an opening transition.
317
354
  - `:indeterminate` on a header checkbox, if the app restyles checkboxes.
@@ -350,10 +387,14 @@ The package sets attributes and the browser's own states; the app styles them:
350
387
  changes it at once: keep `data-submit-on-change` to a sort or a filter that is cheap to redo, and give the form a
351
388
  submit button for a page without script.
352
389
  - A stepper moves focus to the new step's heading, so a screen reader starts where the step does: give each a
353
- `tabindex="-1"`. Hide the progress marks (`aria-hidden="true"`) and put the step's words in a `data-step-label` inside
354
- an `aria-live="polite"` region.
390
+ `tabindex="-1"`. Hide the progress marks (`aria-hidden="true"`) and give the `data-step-progress` element
391
+ `aria-live="polite"`.
355
392
  - Point a field's `aria-describedby` at its `data-show-if` hints' box, in an `aria-live="polite"` region, so a warning
356
393
  shown on a pick is read out.
394
+ - A dismissed banner hands focus to `<main>`: give it `tabindex="-1"` (a skip link's target already has it), or focus
395
+ falls to `<body>`. Give a `data-dismiss` button that shows only an icon an `aria-label`.
396
+ - A `data-dropdown`'s `<summary>` is its button: put the menu's name in it, and a `<details>` says itself whether it is
397
+ open.
357
398
 
358
399
  ## Range picker
359
400
 
@@ -555,6 +596,7 @@ stylesheet does.
555
596
  |---|---|
556
597
  | `installUiBehaviours()` | listens on the document for every behaviour above, opens the `data-open-on-load` dialogs and shows each stepper at the step it opens at; later calls do nothing |
557
598
  | `copyText(text)` | the copy buttons' clipboard write: resolves to `true` when the clipboard took the text, `false` where `navigator.clipboard` is absent (plain http) or refuses |
599
+ | `post(url, body)` | `fetch()`es a `FormData` or `URLSearchParams` body to `url` as a POST that Laravel answers as an AJAX request; resolves to the `Response` |
558
600
  | `installRangePicker()`, from `@ismailnakkar/ui-behaviours/range-picker` | listens on the document for range pickers and writes those already on the page; later calls do nothing |
559
601
  | `@ismailnakkar/ui-behaviours/range-picker.css` | the range picker's [stylesheet](#styling-the-picker) |
560
602
 
@@ -568,11 +610,29 @@ if (!(await copyText(url))) {
568
610
  }
569
611
  ```
570
612
 
613
+ `post()` serves a page script that sends a form itself. It sends `X-Requested-With: XMLHttpRequest` (so
614
+ `$request->ajax()` holds), `Accept: application/json` (so a refusal comes back as JSON: a 422 with the field errors, not
615
+ a redirect), the `<meta name="csrf-token" content="{{ csrf_token() }}">` token as `X-CSRF-TOKEN`, and the page's
616
+ `<html lang>` as `Accept-Language`, so a route with no language in its URL answers in the page's language. A page
617
+ without the meta tag sends the form's `@csrf` field instead; one without a `lang` sends the browser's language. Like
618
+ `fetch()`, it rejects only when the request fails: check `response.ok` or `response.status` for a refusal.
619
+
620
+ ```js
621
+ import {post} from '@ismailnakkar/ui-behaviours';
622
+
623
+ const response = await post(form.action, new FormData(form));
624
+
625
+ if (response.status === 422) {
626
+ showErrors((await response.json()).errors);
627
+ }
628
+ ```
629
+
571
630
  ## Events
572
631
 
573
- The package fires none of its own. A dialog's native `close` fires when a close button or the backdrop closes it, the
574
- range picker's radios fire the native `change`, and a `data-submit-on-change` field's form the native `submit`. Cally's
575
- `change` and `rangestart` do not bubble: listen to them in the capture phase, as the package does.
632
+ The package fires none of its own. A dialog's native `close` fires when a close button or the backdrop closes it, a
633
+ `data-dropdown`'s native `toggle` when it closes, the range picker's radios fire the native `change`, and a
634
+ `data-submit-on-change` field's form the native `submit`. Cally's `change` and `rangestart` do not bubble: listen to
635
+ them in the capture phase, as the package does.
576
636
 
577
637
  ## Testing
578
638
 
@@ -593,14 +653,38 @@ customElements.define('calendar-range', class extends HTMLElement {
593
653
  });
594
654
  ```
595
655
 
656
+ A dismissed banner hides once its 150ms fade ends: wait for it (`vi.waitFor`), or stub `matchMedia` to match
657
+ `(prefers-reduced-motion: reduce)` so it hides at once. A test of a script that calls `post()` stubs `fetch`
658
+ (`vi.stubGlobal('fetch', …)`).
659
+
596
660
  A stepper needs nothing more: happy-dom and jsdom check `required` fields and send a form with `requestSubmit()`. To
597
661
  test one opening on load, put its markup in place before installing, in a test file of its own or after
598
662
  `vi.resetModules()` with a fresh `import()`.
599
663
 
600
- Run this package's suite with `npm test`.
664
+ Run this package's suite with `npm test`: oxlint, then Vitest.
601
665
 
602
666
  ## Upgrading
603
667
 
668
+ ### From 0.6
669
+
670
+ The package now acts on `data-dismiss` and `details[data-dropdown]`. A page without either works as before; one with
671
+ them:
672
+
673
+ - Remove any script of your own for either attribute, or both run (a banner faded twice).
674
+ - A `data-dismiss` that another script reads, such as Bootstrap 4's `data-dismiss="modal"`, now also hides its button's
675
+ parent: give that script an attribute of its own (Bootstrap 5's `data-bs-dismiss`).
676
+ - A dismissed banner is `hidden`, not removed: a test that checked it was gone checks `hidden`, and a `display` of
677
+ your own on the banner needs `[hidden] { display: none !important; }` to lose to it (see [Styling](#styling)).
678
+
679
+ ### From 0.5
680
+
681
+ Steppers go by order and name, never by number:
682
+
683
+ - `data-step="1"`, `"2"`, … become `data-step`, or `data-step="name"` for a step that `data-open-at-step` points at.
684
+ - `data-open-at-step` takes that name: `data-open-at-step="2"` opens nothing now.
685
+ - `data-step-mark="n"` becomes `data-step-mark`, one per step in the same order.
686
+ - `data-step-label="n"` is gone: one `data-step-progress="Step :step of :steps"` element replaces the labels.
687
+
604
688
  ### From 0.4
605
689
 
606
690
  - The stylesheet no longer reads `--range-picker-shadow`, `--range-picker-font-size`, `--range-picker-window-gap`,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ismailnakkar/ui-behaviours",
3
- "version": "0.5.0",
4
- "description": "Page behaviours from plain HTML attributes (copy with a spoken result, confirm, submit once or on a change, native dialogs, steps, show by a radio, checkbox or select, check all, autoselect), and a date range picker over Cally with an optional stylesheet.",
3
+ "version": "0.7.0",
4
+ "description": "Page behaviours from plain HTML attributes (copy with a spoken result, confirm, submit once or on a change, native dialogs, steps, show by a radio, checkbox or select, check all, autoselect, dismiss a banner, light-dismiss a details menu), a Laravel-ready post(), and a date range picker over Cally with an optional stylesheet.",
5
5
  "keywords": [
6
6
  "clipboard",
7
7
  "dialog",
@@ -10,6 +10,9 @@
10
10
  "cally",
11
11
  "data-attributes",
12
12
  "stepper",
13
+ "dropdown",
14
+ "dismiss",
15
+ "fetch",
13
16
  "laravel"
14
17
  ],
15
18
  "homepage": "https://github.com/ismailnakkar/ui-behaviours",
@@ -53,7 +56,7 @@
53
56
  "access": "public"
54
57
  },
55
58
  "scripts": {
56
- "test": "vitest run",
59
+ "test": "oxlint --deny-warnings && vitest run",
57
60
  "prepublishOnly": "npm test"
58
61
  },
59
62
  "peerDependencies": {
@@ -67,6 +70,7 @@
67
70
  "devDependencies": {
68
71
  "cally": "^0.9.2",
69
72
  "happy-dom": "^21.0.4",
73
+ "oxlint": "^1.95.0",
70
74
  "vitest": "^5.1.0"
71
75
  }
72
76
  }
package/src/index.d.ts CHANGED
@@ -6,3 +6,10 @@ export function installUiBehaviours(): void;
6
6
 
7
7
  /** Writes text to the clipboard: false where navigator.clipboard is absent (plain http) or refuses. */
8
8
  export function copyText(text: string): Promise<boolean>;
9
+
10
+ /**
11
+ * POSTs body to url with fetch() as a Laravel AJAX request: X-Requested-With, Accept: application/json and, when the
12
+ * page has them, its meta csrf-token as X-CSRF-TOKEN and its <html lang> as Accept-Language. Rejects only when the
13
+ * request fails; a refusal resolves with its status.
14
+ */
15
+ export function post(url: string, body: FormData | URLSearchParams): Promise<Response>;
package/src/index.js CHANGED
@@ -13,6 +13,13 @@ const CLOSED_BY_ANY = 'any';
13
13
  /** Between a field's name and its value in data-show-if: "method=paypal". */
14
14
  const SHOW_IF_SEPARATOR = '=';
15
15
 
16
+ const DISMISS_FADE_MS = 150;
17
+
18
+ const OPEN_DROPDOWNS = 'details[data-dropdown][open]';
19
+
20
+ /** Laravel's layout tag for the session's CSRF token: <meta name="csrf-token" content="{{ csrf_token() }}">. */
21
+ const CSRF_TOKEN = 'meta[name="csrf-token"]';
22
+
16
23
  const copyTimers = new WeakMap();
17
24
 
18
25
  /** The dialog a press landed on outside its box: a selection dragged out of the body must not close it. */
@@ -34,6 +41,9 @@ export const installUiBehaviours = once(() => {
34
41
  document.addEventListener('click', closeModal);
35
42
  document.addEventListener('pointerdown', pressBackdrop);
36
43
  document.addEventListener('click', closeOnBackdrop);
44
+ document.addEventListener('click', dismissBanner);
45
+ document.addEventListener('click', closeDropdownsOutside);
46
+ document.addEventListener('keydown', closeDropdownsOnEscape);
37
47
 
38
48
  // First: a stepper dialog opened on load shows its step before showModal() moves focus in.
39
49
  installSteps();
@@ -51,6 +61,26 @@ export async function copyText(text) {
51
61
  }
52
62
  }
53
63
 
64
+ /**
65
+ * X-Requested-With makes it $request->ajax(); Accept has Laravel answer a refusal (422, 419) as JSON, not a redirect;
66
+ * the page's language serves a route with none in its URL, where the browser's own would win.
67
+ */
68
+ export function post(url, body) {
69
+ const headers = {'X-Requested-With': 'XMLHttpRequest', Accept: 'application/json'};
70
+ const token = document.querySelector(CSRF_TOKEN)?.content;
71
+ const language = document.documentElement.lang;
72
+
73
+ if (token) {
74
+ headers['X-CSRF-TOKEN'] = token;
75
+ }
76
+
77
+ if (language) {
78
+ headers['Accept-Language'] = language;
79
+ }
80
+
81
+ return fetch(url, {method: 'POST', headers, body});
82
+ }
83
+
54
84
  function isField(element) {
55
85
  return element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement;
56
86
  }
@@ -323,3 +353,59 @@ function closeOnBackdrop(event) {
323
353
  dialog.close();
324
354
  }
325
355
  }
356
+
357
+ // Focus is moved out first: focus inside a hidden element falls to <body> and loses the keyboard user's place.
358
+ function dismissBanner(event) {
359
+ const banner = closestTo(event, '[data-dismiss]')?.parentElement;
360
+
361
+ if (!banner || event.defaultPrevented) {
362
+ return;
363
+ }
364
+
365
+ if (banner.contains(document.activeElement)) {
366
+ document.querySelector('main')?.focus({preventScroll: true});
367
+ }
368
+
369
+ fadeOut(banner);
370
+ }
371
+
372
+ // Hidden, not removed, so a page may show the banner again; inert while it fades, at once under reduced motion or
373
+ // without the Web Animations API. A cancelled fade leaves it shown: that is how a page shows it again mid-fade.
374
+ function fadeOut(banner) {
375
+ const release = () => {
376
+ banner.inert = false;
377
+ };
378
+ const hide = () => {
379
+ banner.hidden = true;
380
+ release();
381
+ };
382
+
383
+ if (typeof banner.animate !== 'function' || matchMedia('(prefers-reduced-motion: reduce)').matches) {
384
+ hide();
385
+
386
+ return;
387
+ }
388
+
389
+ banner.inert = true;
390
+ banner.animate({opacity: [1, 0]}, {duration: DISMISS_FADE_MS, easing: 'ease-in'}).finished.then(hide, release);
391
+ }
392
+
393
+ // A <details> has no light dismiss of its own, unlike a popover.
394
+ function closeDropdownsOutside({target}) {
395
+ for (const dropdown of document.querySelectorAll(OPEN_DROPDOWNS)) {
396
+ if (!(target instanceof Node && dropdown.contains(target))) {
397
+ dropdown.open = false;
398
+ }
399
+ }
400
+ }
401
+
402
+ function closeDropdownsOnEscape({key}) {
403
+ if (key !== 'Escape') {
404
+ return;
405
+ }
406
+
407
+ for (const dropdown of document.querySelectorAll(OPEN_DROPDOWNS)) {
408
+ dropdown.open = false;
409
+ dropdown.querySelector(':scope > summary')?.focus();
410
+ }
411
+ }
package/src/steps.js CHANGED
@@ -2,6 +2,8 @@ import {closestTo} from './helpers.js';
2
2
 
3
3
  const STEPPER = '[data-steps]';
4
4
  const STEP = '[data-step]';
5
+ const MARK = '[data-step-mark]';
6
+ const PROGRESS = '[data-step-progress]';
5
7
  const FIELDS = 'input, select, textarea';
6
8
  const HEADING = 'h1, h2, h3, h4, h5, h6';
7
9
  const BACK = '[data-step-back]';
@@ -9,8 +11,11 @@ const NEXT = '[data-step-next]';
9
11
  const SUBMIT = '[data-step-submit]';
10
12
  const MARK_STATE = 'data-step-state';
11
13
 
12
- /** Steps are numbered from 1, in the order they come. */
13
- const FIRST_STEP = 1;
14
+ /** Steps go by their place in the markup: the first is 0 here, and 1 in data-step-progress's wording. */
15
+ const FIRST_STEP = 0;
16
+
17
+ /** data-step-progress's placeholders, as Laravel's __() leaves them when given none: the showing step's place and the count. */
18
+ const PROGRESS_PLACEHOLDER = /:(steps|step)\b/g;
14
19
 
15
20
  /** The values of data-step-state on a progress mark: the steps behind are done, the one showing is current. */
16
21
  const MarkState = Object.freeze({done: 'done', current: 'current'});
@@ -60,8 +65,8 @@ function stepOnEnter(event) {
60
65
 
61
66
  /**
62
67
  * A refused submit comes back with its errors in the stepper: it opens at the earliest step with a refused or an empty
63
- * field, as a field the server never hands back (a mailed code) is empty again. Otherwise at data-open-at-step, or
64
- * shut at the step it shows.
68
+ * field, as a field the server never hands back (a mailed code) is empty again. Otherwise at the step
69
+ * data-open-at-step names, or shut at the step it shows.
65
70
  */
66
71
  function openStepper(stepper) {
67
72
  const opening = openingStepOf(stepper);
@@ -77,12 +82,14 @@ function openingStepOf(stepper) {
77
82
  const fields = fieldsOf(stepper);
78
83
 
79
84
  if (fields.some(isRefused)) {
80
- return stepOf(fields.find((field) => isRefused(field) || !field.checkValidity()));
85
+ return stepOf(stepper, fields.find((field) => isRefused(field) || !field.checkValidity()));
81
86
  }
82
87
 
83
- const asked = Number(stepper.dataset.openAtStep);
88
+ // Unnamed steps carry an empty data-step, which an empty data-open-at-step must not pick.
89
+ const name = stepper.dataset.openAtStep;
90
+ const named = name ? stepsOf(stepper).findIndex((section) => section.dataset.step === name) : -1;
84
91
 
85
- return sectionOf(stepper, asked) ? asked : null;
92
+ return named === -1 ? null : named;
86
93
  }
87
94
 
88
95
  /** A field the server refused: aria-invalid="true" beside its message. */
@@ -104,7 +111,7 @@ function advance(stepper) {
104
111
 
105
112
  if (isLast(stepper, step)) {
106
113
  submit(stepper);
107
- } else if (fieldsOf(sectionOf(stepper, step)).every((field) => field.reportValidity())) {
114
+ } else if (fieldsOf(stepsOf(stepper)[step]).every((field) => field.reportValidity())) {
108
115
  moveTo(stepper, step + 1);
109
116
  }
110
117
  }
@@ -114,7 +121,7 @@ function submit(stepper) {
114
121
  const invalid = fieldsOf(stepper).find((field) => !field.checkValidity());
115
122
 
116
123
  if (invalid) {
117
- show(stepper, stepOf(invalid));
124
+ show(stepper, stepOf(stepper, invalid));
118
125
  invalid.reportValidity();
119
126
 
120
127
  return;
@@ -126,26 +133,32 @@ function submit(stepper) {
126
133
  // To the new step's heading, so a screen reader starts where the step does.
127
134
  function moveTo(stepper, step) {
128
135
  show(stepper, step);
129
- sectionOf(stepper, step)?.querySelector(HEADING)?.focus();
136
+ stepsOf(stepper)[step]?.querySelector(HEADING)?.focus();
130
137
  }
131
138
 
132
139
  function show(stepper, step) {
133
- for (const section of stepsOf(stepper)) {
134
- section.hidden = stepOf(section) !== step;
135
- }
140
+ const steps = stepsOf(stepper);
141
+
142
+ steps.forEach((section, place) => {
143
+ section.hidden = place !== step;
144
+ });
136
145
 
137
- for (const mark of stepper.querySelectorAll('[data-step-mark]')) {
138
- const state = markStateOf(Number(mark.dataset.stepMark), step);
146
+ // Marks pair with the steps by place: the first mark is the first step's.
147
+ stepper.querySelectorAll(MARK).forEach((mark, place) => {
148
+ const state = markStateOf(place, step);
139
149
 
140
150
  if (state === null) {
141
151
  mark.removeAttribute(MARK_STATE);
142
152
  } else {
143
153
  mark.setAttribute(MARK_STATE, state);
144
154
  }
145
- }
155
+ });
146
156
 
147
- for (const label of stepper.querySelectorAll('[data-step-label]')) {
148
- label.hidden = Number(label.dataset.stepLabel) !== step;
157
+ for (const progress of stepper.querySelectorAll(PROGRESS)) {
158
+ progress.textContent = progress.dataset.stepProgress.replace(
159
+ PROGRESS_PLACEHOLDER,
160
+ (_placeholder, name) => String(name === 'steps' ? steps.length : step + 1),
161
+ );
149
162
  }
150
163
 
151
164
  hideAll(stepper, BACK, step === FIRST_STEP);
@@ -171,24 +184,20 @@ function stepsOf(stepper) {
171
184
  return [...stepper.querySelectorAll(STEP)];
172
185
  }
173
186
 
174
- function sectionOf(stepper, step) {
175
- return stepsOf(stepper).find((section) => stepOf(section) === step);
176
- }
177
-
178
- /** The step a section or a field belongs to. */
179
- function stepOf(element) {
180
- return Number(element.closest(STEP).dataset.step);
187
+ /** The place of the step a field belongs to. */
188
+ function stepOf(stepper, field) {
189
+ return stepsOf(stepper).indexOf(field.closest(STEP));
181
190
  }
182
191
 
183
192
  /** The step showing; the first when none does. */
184
193
  function currentStepOf(stepper) {
185
- const showing = stepsOf(stepper).find((section) => !section.hidden);
194
+ const showing = stepsOf(stepper).findIndex((section) => !section.hidden);
186
195
 
187
- return showing ? stepOf(showing) : FIRST_STEP;
196
+ return showing === -1 ? FIRST_STEP : showing;
188
197
  }
189
198
 
190
199
  function isLast(stepper, step) {
191
- return step >= stepsOf(stepper).length;
200
+ return step >= stepsOf(stepper).length - 1;
192
201
  }
193
202
 
194
203
  /** The fields of a step, or of every step in a stepper. */