@ismailnakkar/ui-behaviours 0.3.0 → 0.4.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
@@ -1,8 +1,9 @@
1
1
  # @ismailnakkar/ui-behaviours
2
2
 
3
- Page behaviours from plain HTML attributes: copy to the clipboard, confirm a submit, send a form once, open, close and
4
- light-dismiss a native `<dialog>`, walk a form's steps one at a time, show a radio's own hints, check every row from a
5
- header box, and select a field's text on a click. They listen on the document, so markup added later works too.
3
+ Page behaviours from plain HTML attributes: copy to the clipboard and say the result to screen readers, confirm
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.
6
7
 
7
8
  A date range picker over [Cally](https://wicky.nillia.ms/cally/) has its own entry, so pages without one never load the
8
9
  calendar, and an optional stylesheet themed by custom properties. Nothing else ships styles, and nothing ships wording:
@@ -35,14 +36,16 @@ Then mark up the page:
35
36
  |---|---|---|
36
37
  | [`data-copy="id"`](#data-copyid) | a button | copies the element with that id |
37
38
  | [`data-copy-value`](#data-copyid) | the copied element | the text to copy instead of what it shows |
39
+ | [`data-copy-status="id"`](#data-copy-statusid) | a copy button | says the result in the live region with that id |
38
40
  | [`data-confirm="question"`](#data-confirmquestion) | a form or a submit button | asks before submitting |
39
41
  | [`data-submit-once`](#data-submit-once) | a form | refuses a second submit |
42
+ | [`data-submit-on-change`](#data-submit-on-change) | a select, a checkbox or a radio in a form | submits the form when it changes |
40
43
  | [`data-show-modal="id"`](#data-show-modalid) | a button or a link | opens the dialog with that id as a modal |
41
44
  | [`data-close-modal`](#data-close-modal) | a button in a dialog | closes that dialog |
42
45
  | [`closedby="any"`](#closedbyany) | a dialog | closes it on a backdrop click |
43
46
  | [`data-open-on-load`](#data-open-on-load) | a dialog | opens it on install |
44
47
  | [`data-steps`](#data-steps) | a dialog or any box | shows its `data-step` sections one at a time |
45
- | [`data-show-if="name=value"`](#data-show-ifnamevalue-and-data-clear-onname) | any element in a form | shows it only while the radio `name` has that value |
48
+ | [`data-show-if="name=value"`](#data-show-ifnamevalue-and-data-clear-onname) | any element in a form | shows it only while the radio, checkbox or select `name` holds that value |
46
49
  | [`data-clear-on="name"`](#data-show-ifnamevalue-and-data-clear-onname) | a field in a form | empties it when another radio `name` is picked |
47
50
  | [`data-check-all="name"`](#data-check-allname) | a header checkbox | checks every row named `name` |
48
51
  | [`data-autoselect`](#data-autoselect) | an input or a textarea | selects its text on a click |
@@ -70,6 +73,26 @@ focused too, so the user copies it by hand. A missing source copies nothing.
70
73
  To refuse a copy (asking for a missing field first), call `event.preventDefault()` in a click listener of your own on
71
74
  the button or an element around it: the copy skips a cancelled click.
72
75
 
76
+ ### `data-copy-status="id"`
77
+
78
+ On a copy button: names a live region (`role="status"`) that says the result, as the button's own marks are not read
79
+ out. The region holds the words: its `data-copied-text` for a copy that worked, its `data-copy-failed-text` for a
80
+ refusal; a result it has no words for says nothing.
81
+
82
+ ```html
83
+ <input id="short-url" value="https://example.com/abcd" readonly data-autoselect>
84
+ <button type="button" data-copy="short-url" data-copy-status="short-url-status">
85
+ <span>Copy</span><span>Copied</span>
86
+ </button>
87
+ <p id="short-url-status" role="status" class="sr-only"
88
+ data-copied-text="Link copied" data-copy-failed-text="Copy blocked: copy the selected link by hand"></p>
89
+ ```
90
+
91
+ The click empties the region, so the same words said again are read out again; the words go in once the clipboard
92
+ answers and leave with the button's marks, 1.5 seconds later, unless the page has written something else there since.
93
+ Buttons may share one region, and the page may use it for its own news too. Keep the region in place, never `hidden`:
94
+ a hidden element is out of the accessibility tree, and one that appears as it speaks is not reliably read.
95
+
73
96
  ### `data-confirm="question"`
74
97
 
75
98
  On a form, or on one of its submit buttons: the browser's `confirm()` asks that question, and only a yes submits. The
@@ -97,6 +120,20 @@ forms send again.
97
120
  </form>
98
121
  ```
99
122
 
123
+ ### `data-submit-on-change`
124
+
125
+ On a select, a checkbox or a radio in a form: a change submits the form with `requestSubmit()`, as its submit button
126
+ would, so the browser checks the fields and `data-confirm` and `data-submit-once` apply. A field in no form sends
127
+ nothing. Mark only choices whose result the label makes plain, such as a sort or a filter.
128
+
129
+ ```html
130
+ <form method="GET" action="/admin/reports">
131
+ <label for="sort">Sort by</label>
132
+ <select id="sort" name="sort" data-submit-on-change>…</select>
133
+ <noscript><button>Sort</button></noscript>
134
+ </form>
135
+ ```
136
+
100
137
  ### `data-show-modal="id"`
101
138
 
102
139
  On a button or a link: a click opens the `<dialog>` with that id with `showModal()`. On a link the `href` is the
@@ -208,9 +245,16 @@ before the script runs. A stepper added later works, but opens at nothing.
208
245
 
209
246
  ### `data-show-if="name=value"` and `data-clear-on="name"`
210
247
 
211
- In a form, for a choice made with radios: picking a radio named `name` shows the form's elements whose `data-show-if`
212
- names that radio's value and hides those naming another, and empties the fields marked `data-clear-on="name"`, which
213
- belonged to the value picked before. A payout destination is one: the account depends on the method.
248
+ In a form, for a choice: an element marked `data-show-if="name=value"` shows while the field named `name` holds that
249
+ value, and hides once it does not.
250
+
251
+ - **A radio**: picking one shows the elements naming its value and hides those naming another.
252
+ - **A checkbox**: ticking the box with that value shows them, unticking it hides them, and another box of the same name
253
+ leaves them alone. A box without a `value` has the value `on`.
254
+ - **A select**: a change shows the elements naming a selected option's value and hides the rest.
255
+
256
+ Picking a radio named `name` also empties the fields marked `data-clear-on="name"`, which belonged to the value picked
257
+ before. A payout destination is one: the account depends on the method.
214
258
 
215
259
  ```html
216
260
  <form method="POST" action="/withdrawals/destination">
@@ -225,8 +269,21 @@ belonged to the value picked before. A payout destination is one: the account de
225
269
  </form>
226
270
  ```
227
271
 
228
- The server draws the checked radio's elements shown and the others `hidden`; the script changes them on a pick only. It
229
- reads radios only, within the picked radio's form (the page, for a radio in no form).
272
+ ```html
273
+ <select name="driver">
274
+ <option value="local" selected>Local disk</option>
275
+ <option value="s3">S3</option>
276
+ </select>
277
+ <fieldset data-show-if="driver=s3" hidden>…</fieldset>
278
+
279
+ <label><input type="checkbox" name="report" value="1"> Report it</label>
280
+ <div data-show-if="report=1" hidden>…</div>
281
+ ```
282
+
283
+ The server draws the chosen value's elements shown and the others `hidden`, a refused submit's page from the values
284
+ sent back; the script changes them on a change only. It reads within the changed field's form (the page, for a field in
285
+ no form). A hidden element's fields still submit, and a hidden `required` one blocks the submit: leave `required` off
286
+ them and let the server require each for its own value.
230
287
 
231
288
  ### `data-check-all="name"`
232
289
 
@@ -287,8 +344,11 @@ The package sets attributes and the browser's own states; the app styles them:
287
344
  and focus goes back to the opener on close. Give each one an `aria-labelledby`.
288
345
  - Put the copy state in the button's text (two spans, one hidden), so it never relies on colour alone.
289
346
  - A refused copy selects and focuses the field, so the user can copy it with the keyboard.
290
- - The copy marks change an attribute only, so screen readers announce nothing. A page that needs it adds a
291
- `role="status"` line and fills it when `data-copied` appears (a `MutationObserver`).
347
+ - The copy marks change an attribute only, which screen readers do not read out: give the button a
348
+ [`data-copy-status`](#data-copy-statusid) region with the words for both results, so the result is heard.
349
+ - A change that submits moves the page under the user, and on some desktop browsers an arrow key on a closed select
350
+ 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
+ submit button for a page without script.
292
352
  - A stepper moves focus to the new step's heading, so a screen reader starts where the step does: give each a
293
353
  `tabindex="-1"`. Hide the progress marks (`aria-hidden="true"`) and put the step's words in a `data-step-label` inside
294
354
  an `aria-live="polite"` region.
@@ -521,9 +581,9 @@ if (!(await copyText(url))) {
521
581
 
522
582
  ## Events
523
583
 
524
- The package fires none of its own. A dialog's native `close` fires when a close button or the backdrop closes it, and
525
- the range picker's radios fire the native `change`. Cally's `change` and `rangestart` do not bubble: listen to them in
526
- the capture phase, as the package does.
584
+ The package fires none of its own. A dialog's native `close` fires when a close button or the backdrop closes it, the
585
+ range picker's radios fire the native `change`, and a `data-submit-on-change` field's form the native `submit`. Cally's
586
+ `change` and `rangestart` do not bubble: listen to them in the capture phase, as the package does.
527
587
 
528
588
  ## Testing
529
589
 
@@ -552,6 +612,50 @@ Run this package's suite with `npm test`.
552
612
 
553
613
  ## Upgrading
554
614
 
615
+ ### From 0.3
616
+
617
+ Nothing changes for a page on 0.3: copy buttons without `data-copy-status` and radios work as before, a select or a
618
+ checkbox changes nothing unless a `data-show-if` names its field, and only a field marked `data-submit-on-change`
619
+ submits. An app replacing its own copies changes these:
620
+
621
+ - **cuty, the Full Page Script copy** (`resources/js/members/tools/fps.js`, `members/tools/fps.blade.php`). Delete the
622
+ `MutationObserver` at the end of `fps.js` with its `COPIED` and `status` constants, give the Copy button
623
+ `data-copy-status="fps-copy-status"`, and give the `.copy-status` span that id; its `data-copied-text` stays. Add a
624
+ `data-copy-failed-text` to say a refusal too.
625
+ - **exe, both shorten forms' copy** (`resources/js/site/shorten.ts` and `shorten.test.ts`, the home page's form in
626
+ `public/home.blade.php` and the nav dialog's in `layouts/member.blade.php`: one `bind()` serves every
627
+ `form[data-shorten]`). In each form, give the `data-shorten-copy` button `data-copy` naming the form's link
628
+ (`shorten-link`, `shorten-dialog-link`) and `data-copy-status` naming its `data-shorten-status` paragraph, give that
629
+ paragraph the id (`shorten-status`, `shorten-dialog-status`), rename its `data-copied` to `data-copied-text`, and add
630
+ a `data-copy-failed-text` holding the `general.shorten.copy-blocked` words.
631
+ - Restyle each form from the button's own marks, as `x-ui.copy-button` does: the button becomes a `group`,
632
+ `group-data-[copy-state=done]:` becomes `data-copied:` on it (hover repeats included) and `group-data-copied:` on
633
+ its labels, `=failed` the same with `data-copy-failed`, and the copy-blocked line shows with
634
+ `group-has-[[data-copy-failed]]:block`.
635
+ - Delete the copy state machine from `shorten.ts`: the `CopyState` and `Timer` types, `copyState` and its calls, the
636
+ `copied` timer, `copyLink()` and the copy listener. Drop the `failed` hook and the `data-shorten-copy-failed`
637
+ attribute of both copy-blocked lines in the same change: `hooks()` binds nothing while a hook it asks for is
638
+ missing. `copy` and `copyUrl` stay: `showResult()` focuses the one and fills the other.
639
+ - In `shorten.test.ts`, drop `data-shorten-copy-failed` and `data-copied` from the markup, delete "selects the link
640
+ when the clipboard refuses" (this package's tests select a refused copy), and keep "clears a Copied state when a
641
+ new link arrives" as "shows a new link and says it is ready": its submit and answer, without the copy click and the
642
+ `copyState` assertions.
643
+ - Both marks then last 1.5 seconds, as on exe's other copy buttons. Today a copy shows for 2 seconds, a refusal and
644
+ its copy-blocked line stay until the next copy or submit, and a new link clears either at once.
645
+ - **upfiles, the admin's conditional fields** (`resources/js/admin/conditional-fields.js`, its
646
+ `tests/js/conditional-fields.test.mjs`, the `initConditionalFields()` call in `resources/js/admin/index.js`). Delete
647
+ the three, and turn each `data-cond-field="x" data-cond-value="v"` into `data-show-if="x=v"`
648
+ (`admin/delete.blade.php`, `components/storages/form.blade.php`). The storages form now draws its first state on the
649
+ server: each role hint and driver section `hidden` unless it is the role or driver its select shows (`old()`, else the
650
+ storage's, else the default role or the first driver), as the CSAM origin field already is.
651
+ - **upfiles, the auto-submitting select** (`resources/js/lib/form-affordances.js`, called from
652
+ `resources/js/admin/index.js` and `resources/js/member/index.js`). Delete it and its two calls, and rename
653
+ `data-autosubmit` to `data-submit-on-change` (`admin/moderation/index.blade.php`); both bundles already call
654
+ `installUiBehaviours()`. Rename it in the two `assertDontSee('data-autosubmit', false)` of
655
+ `tests/Feature/StatisticsDashboardsTest.php` too, or they pass whatever the month pickers carry.
656
+ - **centratag, the dashboard's select** (`resources/js/dashboard.ts`). Add `@ismailnakkar/ui-behaviours` and replace the
657
+ file's change listener with `installUiBehaviours()`; `data-submit-on-change` in `tags/show.blade.php` stays as it is.
658
+
555
659
  ### From 0.2
556
660
 
557
661
  Nothing changes for a page on 0.2: the stepper, `data-show-if` and `data-clear-on` read only attributes of their own,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ismailnakkar/ui-behaviours",
3
- "version": "0.3.0",
4
- "description": "Page behaviours from plain HTML attributes (copy, confirm, submit once, native dialogs, steps, show by a radio, check all, autoselect), and a date range picker over Cally with an optional stylesheet.",
3
+ "version": "0.4.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.",
5
5
  "keywords": [
6
6
  "clipboard",
7
7
  "dialog",
package/src/helpers.js CHANGED
@@ -18,3 +18,7 @@ export function closestTo({target}, selector) {
18
18
  export function isRadio(element) {
19
19
  return element instanceof HTMLInputElement && element.type === 'radio';
20
20
  }
21
+
22
+ export function isCheckbox(element) {
23
+ return element instanceof HTMLInputElement && element.type === 'checkbox';
24
+ }
package/src/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import {closestTo, isRadio, once} from './helpers.js';
1
+ import {closestTo, isCheckbox, isRadio, once} from './helpers.js';
2
2
  import {installSteps} from './steps.js';
3
3
 
4
4
  const COPY_FLASH_MS = 1500;
@@ -10,7 +10,7 @@ const SUBMITTING = 'data-submitting';
10
10
  /** closedby's light-dismiss value, polyfilled where the browser lacks it. */
11
11
  const CLOSED_BY_ANY = 'any';
12
12
 
13
- /** Between a radio's name and its value in data-show-if: "method=paypal". */
13
+ /** Between a field's name and its value in data-show-if: "method=paypal". */
14
14
  const SHOW_IF_SEPARATOR = '=';
15
15
 
16
16
  const copyTimers = new WeakMap();
@@ -24,7 +24,10 @@ export const installUiBehaviours = once(() => {
24
24
  document.addEventListener('submit', submitOnce);
25
25
  window.addEventListener('pageshow', releaseSubmitted);
26
26
  document.addEventListener('change', checkAll);
27
- document.addEventListener('change', switchOnPick);
27
+ document.addEventListener('change', showOnChange);
28
+ document.addEventListener('change', clearOnPick);
29
+ // Last: the form goes as the other behaviours leave it.
30
+ document.addEventListener('change', submitOnChange);
28
31
  document.addEventListener('click', autoselect);
29
32
  document.addEventListener('click', copyOnClick);
30
33
  document.addEventListener('click', showModal);
@@ -94,12 +97,19 @@ function releaseSubmitted({persisted}) {
94
97
  }
95
98
  }
96
99
 
100
+ // requestSubmit(), not submit(): the browser checks the fields, and data-confirm and data-submit-once apply.
101
+ function submitOnChange({target}) {
102
+ if (target instanceof Element && target.hasAttribute('data-submit-on-change')) {
103
+ target.form?.requestSubmit();
104
+ }
105
+ }
106
+
97
107
  function checkboxesNamed(name) {
98
- return [...document.getElementsByName(name)].filter((box) => box.type === 'checkbox' && !box.disabled);
108
+ return [...document.getElementsByName(name)].filter((box) => isCheckbox(box) && !box.disabled);
99
109
  }
100
110
 
101
111
  function checkAll({target}) {
102
- if (!(target instanceof HTMLInputElement) || target.type !== 'checkbox') {
112
+ if (!isCheckbox(target)) {
103
113
  return;
104
114
  }
105
115
 
@@ -125,25 +135,42 @@ function checkAll({target}) {
125
135
  }
126
136
 
127
137
  /**
128
- * A radio picked shows its form's data-show-if="name=value" elements for its own value and hides those for another,
129
- * and empties the fields marked data-clear-on="name", which belong to the value picked before.
138
+ * A radio picked, a box ticked or a select changed shows its form's data-show-if="name=value" elements while it holds
139
+ * that value and hides them once it does not.
130
140
  */
131
- function switchOnPick({target}) {
132
- if (!isRadio(target)) {
141
+ function showOnChange({target}) {
142
+ if (!isRadio(target) && !isCheckbox(target) && !(target instanceof HTMLSelectElement)) {
133
143
  return;
134
144
  }
135
145
 
136
- const scope = target.form ?? document;
137
-
138
- for (const element of scope.querySelectorAll('[data-show-if]')) {
146
+ for (const element of (target.form ?? document).querySelectorAll('[data-show-if]')) {
139
147
  const condition = showIfOf(element);
140
148
 
141
- if (condition?.name === target.name) {
142
- element.hidden = condition.value !== target.value;
149
+ if (condition?.name === target.name && speaksFor(target, condition.value)) {
150
+ element.hidden = !holds(target, condition.value);
143
151
  }
144
152
  }
153
+ }
154
+
155
+ /** A box speaks for its own value alone, as other boxes of its name keep theirs; a radio or select for every value. */
156
+ function speaksFor(field, value) {
157
+ return !isCheckbox(field) || field.value === value;
158
+ }
159
+
160
+ // options, not selectedOptions: happy-dom's list goes stale after its first read, so app tests would see an old pick.
161
+ function holds(field, value) {
162
+ return field instanceof HTMLSelectElement
163
+ ? [...field.options].some((option) => option.selected && option.value === value)
164
+ : field.checked && field.value === value;
165
+ }
166
+
167
+ /** A radio picked empties its form's fields marked data-clear-on="name", which belong to the value picked before. */
168
+ function clearOnPick({target}) {
169
+ if (!isRadio(target)) {
170
+ return;
171
+ }
145
172
 
146
- for (const field of scope.querySelectorAll('[data-clear-on]')) {
173
+ for (const field of (target.form ?? document).querySelectorAll('[data-clear-on]')) {
147
174
  if (field.dataset.clearOn === target.name) {
148
175
  field.value = '';
149
176
  }
@@ -185,25 +212,44 @@ async function copyOnClick(event) {
185
212
  return;
186
213
  }
187
214
 
215
+ const status = button.dataset.copyStatus ? document.getElementById(button.dataset.copyStatus) : null;
216
+
217
+ // Emptied first, so the same words said again are read out again.
218
+ status?.replaceChildren();
219
+
188
220
  const copied = await copyText(copiedTextOf(source));
189
221
 
190
- flashCopyResult(button, copied);
222
+ flashCopyResult(button, copied, status);
191
223
 
192
224
  if (!copied) {
193
225
  selectForManualCopy(source);
194
226
  }
195
227
  }
196
228
 
197
- function flashCopyResult(button, copied) {
229
+ function flashCopyResult(button, copied, status) {
230
+ const said = status ? sayCopyResult(status, copied) : null;
231
+
198
232
  clearTimeout(copyTimers.get(button));
199
233
  button.toggleAttribute(COPIED, copied);
200
234
  button.toggleAttribute(COPY_FAILED, !copied);
201
235
  copyTimers.set(button, setTimeout(() => {
202
236
  button.removeAttribute(COPIED);
203
237
  button.removeAttribute(COPY_FAILED);
238
+
239
+ // Its own words only: the page may have said something else there since.
240
+ if (status?.textContent === said) {
241
+ status.textContent = '';
242
+ }
204
243
  }, COPY_FLASH_MS));
205
244
  }
206
245
 
246
+ /** Writes the live region's words for the result, its data-copied-text or data-copy-failed-text, and returns them. */
247
+ function sayCopyResult(status, copied) {
248
+ status.textContent = (copied ? status.dataset.copiedText : status.dataset.copyFailedText) ?? '';
249
+
250
+ return status.textContent;
251
+ }
252
+
207
253
  // select() alone may leave the field unfocused; focused, Ctrl/Cmd+C copies it by hand.
208
254
  function selectForManualCopy(source) {
209
255
  if (isField(source)) {