@ismailnakkar/ui-behaviours 0.6.0 → 0.7.1

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
 
@@ -190,15 +194,15 @@ by one form.
190
194
 
191
195
  <form id="two-factor-enable" method="POST" action="/user/two-factor-authentication">
192
196
  <section data-step="scan">
193
- <h3 tabindex="-1">Scan the QR code</h3>
197
+ <h3>Scan the QR code</h3>
194
198
  …
195
199
  </section>
196
200
  <section data-step="email" hidden>
197
- <h3 tabindex="-1">Confirm your email</h3>
201
+ <h3>Confirm your email</h3>
198
202
  <input name="email_code" required autocomplete="one-time-code">
199
203
  </section>
200
204
  <section data-step="app" hidden>
201
- <h3 tabindex="-1">Enter the code from your app</h3>
205
+ <h3>Enter the code from your app</h3>
202
206
  <input name="code" required aria-invalid="true" aria-describedby="code-error" autocomplete="one-time-code">
203
207
  <p id="code-error">The code is not valid.</p>
204
208
  </section>
@@ -215,9 +219,9 @@ by one form.
215
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
216
220
  not `hidden`. Its fields are the inputs, selects and textareas in it.
217
221
  - **`data-step-next`**: checks the step's fields (`reportValidity()`, so the browser says what is missing), then shows
218
- the next step and focuses its first heading; give the heading `tabindex="-1"`. From the last step it submits, as
219
- `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
220
- check; Enter while an input method composes is left alone.
222
+ the next step and focuses its first heading. From the last step it submits, as `data-step-submit` does. Enter in an
223
+ input of a step does the same, so the form's own submit never skips a step's check; Enter while an input method
224
+ composes is left alone.
221
225
  - **`data-step-back`** shows the step before.
222
226
  - **`data-step-submit`**: checks every step's fields; one left empty shows its step and the browser's message, else the
223
227
  form is sent (`requestSubmit()`, so `data-confirm` and `data-submit-once` apply).
@@ -306,6 +310,34 @@ On an input or a textarea: a click selects all of its text, as tabbing in alread
306
310
  <input value="https://example.com/abcd" readonly data-autoselect>
307
311
  ```
308
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
+
309
341
  ## Styling
310
342
 
311
343
  The package sets attributes and the browser's own states; the app styles them:
@@ -313,6 +345,10 @@ The package sets attributes and the browser's own states; the app styles them:
313
345
  - `[data-copied]` and `[data-copy-failed]` on a copy button: show its "Copied" or "Copy it by hand" label instead of
314
346
  "Copy". The words are the app's, in the button.
315
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`.
316
352
  - `[data-step-state="done"]` and `[data-step-state="current"]` on a stepper's progress marks.
317
353
  - `dialog`, `dialog::backdrop`, and `dialog[open]` for an opening transition.
318
354
  - `:indeterminate` on a header checkbox, if the app restyles checkboxes.
@@ -350,11 +386,16 @@ The package sets attributes and the browser's own states; the app styles them:
350
386
  - A change that submits moves the page under the user, and on some desktop browsers an arrow key on a closed select
351
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
352
388
  submit button for a page without script.
353
- - A stepper moves focus to the new step's heading, so a screen reader starts where the step does: give each a
354
- `tabindex="-1"`. Hide the progress marks (`aria-hidden="true"`) and put the step's words in a `data-step-label` inside
355
- an `aria-live="polite"` region.
389
+ - A stepper moves focus to the new step's heading, so a screen reader starts where the step does. Hide the progress
390
+ marks (`aria-hidden="true"`) and give the `data-step-progress` element `aria-live="polite"`.
356
391
  - Point a field's `aria-describedby` at its `data-show-if` hints' box, in an `aria-live="polite"` region, so a warning
357
392
  shown on a pick is read out.
393
+ - A dismissed banner hands focus to `<main>`; on a page without one, focus falls to `<body>`. Give a `data-dismiss`
394
+ button that shows only an icon an `aria-label`.
395
+ - A heading or a `<main>` the package focuses takes no focus of its own: one without a `tabindex` gets
396
+ `tabindex="-1"` first, so script can focus it and Tab still skips it. A `tabindex` of the page's own is kept.
397
+ - A `data-dropdown`'s `<summary>` is its button: put the menu's name in it, and a `<details>` says itself whether it is
398
+ open.
358
399
 
359
400
  ## Range picker
360
401
 
@@ -556,6 +597,7 @@ stylesheet does.
556
597
  |---|---|
557
598
  | `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 |
558
599
  | `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 |
600
+ | `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` |
559
601
  | `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 |
560
602
  | `@ismailnakkar/ui-behaviours/range-picker.css` | the range picker's [stylesheet](#styling-the-picker) |
561
603
 
@@ -569,11 +611,29 @@ if (!(await copyText(url))) {
569
611
  }
570
612
  ```
571
613
 
614
+ `post()` serves a page script that sends a form itself. It sends `X-Requested-With: XMLHttpRequest` (so
615
+ `$request->ajax()` holds), `Accept: application/json` (so a refusal comes back as JSON: a 422 with the field errors, not
616
+ a redirect), the `<meta name="csrf-token" content="{{ csrf_token() }}">` token as `X-CSRF-TOKEN`, and the page's
617
+ `<html lang>` as `Accept-Language`, so a route with no language in its URL answers in the page's language. A page
618
+ without the meta tag sends the form's `@csrf` field instead; one without a `lang` sends the browser's language. Like
619
+ `fetch()`, it rejects only when the request fails: check `response.ok` or `response.status` for a refusal.
620
+
621
+ ```js
622
+ import {post} from '@ismailnakkar/ui-behaviours';
623
+
624
+ const response = await post(form.action, new FormData(form));
625
+
626
+ if (response.status === 422) {
627
+ showErrors((await response.json()).errors);
628
+ }
629
+ ```
630
+
572
631
  ## Events
573
632
 
574
- The package fires none of its own. A dialog's native `close` fires when a close button or the backdrop closes it, the
575
- range picker's radios fire the native `change`, and a `data-submit-on-change` field's form the native `submit`. Cally's
576
- `change` and `rangestart` do not bubble: listen to them in the capture phase, as the package does.
633
+ The package fires none of its own. A dialog's native `close` fires when a close button or the backdrop closes it, a
634
+ `data-dropdown`'s native `toggle` when it closes, the range picker's radios fire the native `change`, and a
635
+ `data-submit-on-change` field's form the native `submit`. Cally's `change` and `rangestart` do not bubble: listen to
636
+ them in the capture phase, as the package does.
577
637
 
578
638
  ## Testing
579
639
 
@@ -594,14 +654,34 @@ customElements.define('calendar-range', class extends HTMLElement {
594
654
  });
595
655
  ```
596
656
 
657
+ A dismissed banner hides once its 150ms fade ends: wait for it (`vi.waitFor`), or stub `matchMedia` to match
658
+ `(prefers-reduced-motion: reduce)` so it hides at once. A test of a script that calls `post()` stubs `fetch`
659
+ (`vi.stubGlobal('fetch', …)`).
660
+
597
661
  A stepper needs nothing more: happy-dom and jsdom check `required` fields and send a form with `requestSubmit()`. To
598
662
  test one opening on load, put its markup in place before installing, in a test file of its own or after
599
663
  `vi.resetModules()` with a fresh `import()`.
600
664
 
601
- Run this package's suite with `npm test`.
665
+ Run this package's suite with `npm test`: oxlint, then Vitest.
602
666
 
603
667
  ## Upgrading
604
668
 
669
+ ### From 0.7.0
670
+
671
+ Nothing changes for a page on 0.7.0. `<main>` and a stepper's headings no longer need `tabindex="-1"` in the markup
672
+ for the package to focus them: it sets one where there is none. A page may delete its own; leaving it changes nothing.
673
+
674
+ ### From 0.6
675
+
676
+ The package now acts on `data-dismiss` and `details[data-dropdown]`. A page without either works as before; one with
677
+ them:
678
+
679
+ - Remove any script of your own for either attribute, or both run (a banner faded twice).
680
+ - A `data-dismiss` that another script reads, such as Bootstrap 4's `data-dismiss="modal"`, now also hides its button's
681
+ parent: give that script an attribute of its own (Bootstrap 5's `data-bs-dismiss`).
682
+ - A dismissed banner is `hidden`, not removed: a test that checked it was gone checks `hidden`, and a `display` of
683
+ your own on the banner needs `[hidden] { display: none !important; }` to lose to it (see [Styling](#styling)).
684
+
605
685
  ### From 0.5
606
686
 
607
687
  Steppers go by order and name, never by number:
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ismailnakkar/ui-behaviours",
3
- "version": "0.6.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.1",
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/helpers.js CHANGED
@@ -1,3 +1,6 @@
1
+ /** tabindex="-1": script may focus the element, Tab still skips it. */
2
+ const FOCUSABLE_FROM_SCRIPT = -1;
3
+
1
4
  /** Wraps an install function so only its first call runs. */
2
5
  export function once(install) {
3
6
  let installed = false;
@@ -22,3 +25,19 @@ export function isRadio(element) {
22
25
  export function isCheckbox(element) {
23
26
  return element instanceof HTMLInputElement && element.type === 'checkbox';
24
27
  }
28
+
29
+ /**
30
+ * Focuses an element that takes no focus of its own, such as <main> or a heading, giving it tabindex="-1" first, so the
31
+ * page needs none in its markup; a tabindex the page set is kept. A missing element leaves focus where it is.
32
+ */
33
+ export function moveFocusTo(element, options) {
34
+ if (!element) {
35
+ return;
36
+ }
37
+
38
+ if (!element.hasAttribute('tabindex')) {
39
+ element.tabIndex = FOCUSABLE_FROM_SCRIPT;
40
+ }
41
+
42
+ element.focus(options);
43
+ }
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
@@ -1,4 +1,4 @@
1
- import {closestTo, isCheckbox, isRadio, once} from './helpers.js';
1
+ import {closestTo, isCheckbox, isRadio, moveFocusTo, once} from './helpers.js';
2
2
  import {installSteps} from './steps.js';
3
3
 
4
4
  const COPY_FLASH_MS = 1500;
@@ -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
+ moveFocusTo(document.querySelector('main'), {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
@@ -1,4 +1,4 @@
1
- import {closestTo} from './helpers.js';
1
+ import {closestTo, moveFocusTo} from './helpers.js';
2
2
 
3
3
  const STEPPER = '[data-steps]';
4
4
  const STEP = '[data-step]';
@@ -133,7 +133,7 @@ function submit(stepper) {
133
133
  // To the new step's heading, so a screen reader starts where the step does.
134
134
  function moveTo(stepper, step) {
135
135
  show(stepper, step);
136
- stepsOf(stepper)[step]?.querySelector(HEADING)?.focus();
136
+ moveFocusTo(stepsOf(stepper)[step]?.querySelector(HEADING));
137
137
  }
138
138
 
139
139
  function show(stepper, step) {