@ismailnakkar/ui-behaviours 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ismail Nakkar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,356 @@
1
- # Temporary Holding Version
1
+ # @ismailnakkar/ui-behaviours
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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>`, check every row from a header box, and select a field's text on a click. They listen
5
+ on the document, so markup added later works too.
6
+
7
+ A date range picker over [Cally](https://wicky.nillia.ms/cally/) has its own entry, so pages without one never load the
8
+ calendar. The package ships no styles and no wording: the app styles the states it sets, and every word comes from the
9
+ app's markup.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ npm i @ismailnakkar/ui-behaviours
15
+ ```
16
+
17
+ The behaviours have no dependencies. The [range picker](#range-picker) needs Cally 0.9.2 or a later 0.9 release, an
18
+ optional peer dependency (`npm i cally`). Type declarations are included.
19
+
20
+ ## Usage
21
+
22
+ Call `installUiBehaviours()` once from the layout's script, on every page, after the page is parsed (a module or a
23
+ deferred script): it also opens the page's `data-open-on-load` dialogs. A second call does nothing.
24
+
25
+ ```js
26
+ import {installUiBehaviours} from '@ismailnakkar/ui-behaviours';
27
+
28
+ installUiBehaviours();
29
+ ```
30
+
31
+ Then mark up the page:
32
+
33
+ | Attribute | On | Does |
34
+ |---|---|---|
35
+ | [`data-copy="id"`](#data-copyid) | a button | copies the element with that id |
36
+ | [`data-copy-value`](#data-copyid) | the copied element | the text to copy instead of what it shows |
37
+ | [`data-confirm="question"`](#data-confirmquestion) | a form or a submit button | asks before submitting |
38
+ | [`data-submit-once`](#data-submit-once) | a form | refuses a second submit |
39
+ | [`data-show-modal="id"`](#data-show-modalid) | a button or a link | opens the dialog with that id as a modal |
40
+ | [`data-close-modal`](#data-close-modal) | a button in a dialog | closes that dialog |
41
+ | [`closedby="any"`](#closedbyany) | a dialog | closes it on a backdrop click |
42
+ | [`data-open-on-load`](#data-open-on-load) | a dialog | opens it on install |
43
+ | [`data-check-all="name"`](#data-check-allname) | a header checkbox | checks every row named `name` |
44
+ | [`data-autoselect`](#data-autoselect) | an input or a textarea | selects its text on a click |
45
+
46
+ ### `data-copy="id"`
47
+
48
+ On a button: a click copies the element with that id, taking the first of:
49
+
50
+ 1. its `data-copy-value`, for text grouped on screen for reading, such as a setup key;
51
+ 2. an input's or a textarea's current value;
52
+ 3. its text as laid out (`innerText`: one line per block, so a list copies one item a line), trimmed.
53
+
54
+ ```html
55
+ <input id="short-url" value="https://example.com/abcd" readonly data-autoselect>
56
+ <button type="button" data-copy="short-url"><span>Copy</span><span>Copied</span></button>
57
+
58
+ <code id="setup-key" data-copy-value="JBSWY3DPEHPK3PXP">JBSW Y3DP EHPK 3PXP</code>
59
+ <button type="button" data-copy="setup-key">Copy key</button>
60
+ ```
61
+
62
+ The button gets `data-copied` when the copy worked, or `data-copy-failed` when the browser refused, for 1.5 seconds; a
63
+ second click restarts the 1.5 seconds and replaces the other mark. On a refusal the field or text is selected, a field
64
+ focused too, so the user copies it by hand. A missing source copies nothing.
65
+
66
+ To refuse a copy (asking for a missing field first), call `event.preventDefault()` in a click listener of your own on
67
+ the button or an element around it: the copy skips a cancelled click.
68
+
69
+ ### `data-confirm="question"`
70
+
71
+ On a form, or on one of its submit buttons: the browser's `confirm()` asks that question, and only a yes submits. The
72
+ pressed button's question wins over the form's, so buttons sharing a form ask their own; a button without one asks the
73
+ form's. A submit the page already cancelled asks nothing.
74
+
75
+ ```html
76
+ <form method="POST" action="/links/5" data-confirm="Delete this link?">…</form>
77
+
78
+ <button formaction="/admin/withdrawals/5/approve" data-confirm="Approve withdrawal #5?">Approve</button>
79
+ ```
80
+
81
+ ### `data-submit-once`
82
+
83
+ On a form: the first submit goes and marks the form `data-submitting`; every later one is refused, so a double click on
84
+ a payment button pays once. The buttons stay enabled, as a disabled submitter would drop its `name` and `value`; style
85
+ the mark to show the wait. A submit refused by `data-confirm`, or cancelled by a listener on the form, was never sent
86
+ and leaves no mark. A page restored from the back-forward cache (Back from a provider's page) drops the mark, so its
87
+ forms send again.
88
+
89
+ ```html
90
+ <form method="POST" action="/subscription" data-submit-once>
91
+ <button name="gateway" value="stripe">Pay by card</button>
92
+ <button name="gateway" value="balance">Pay with balance</button>
93
+ </form>
94
+ ```
95
+
96
+ ### `data-show-modal="id"`
97
+
98
+ On a button or a link: a click opens the `<dialog>` with that id with `showModal()`. On a link the `href` is the
99
+ fallback: a modified click (new tab, new window) follows it, as does any click on a page without that dialog. A click
100
+ the page cancelled opens nothing, and an open dialog stays open.
101
+
102
+ ```html
103
+ <a href="/links/create" data-show-modal="shorten-dialog">Shorten a link</a>
104
+ ```
105
+
106
+ ### `data-close-modal`
107
+
108
+ On a button inside a dialog: a click closes that dialog, and the native `close` event fires. On a submit button it
109
+ closes without sending the form, so a Cancel button may sit in the dialog's form.
110
+
111
+ ```html
112
+ <button type="button" data-close-modal>Cancel</button>
113
+ ```
114
+
115
+ Without script, `<form method="dialog">` and Escape close a dialog natively.
116
+
117
+ ### `closedby="any"`
118
+
119
+ On a dialog: the native light-dismiss attribute. A click on the backdrop closes the dialog; a press inside its box
120
+ dragged out onto the backdrop (a text selection) does not. A browser that supports `closedby` does this itself;
121
+ elsewhere the package does.
122
+
123
+ ```html
124
+ <dialog id="shorten-dialog" aria-labelledby="shorten-dialog-title" closedby="any">…</dialog>
125
+ ```
126
+
127
+ ### `data-open-on-load`
128
+
129
+ On a dialog: it opens with `showModal()` when the behaviours are installed, say to show a dialog again after a failed
130
+ submit inside it, or a one-time result.
131
+
132
+ ```html
133
+ <dialog id="recovery-codes" data-open-on-load>…</dialog>
134
+ ```
135
+
136
+ ### `data-check-all="name"`
137
+
138
+ On a header checkbox: checking or unchecking it does the same to every enabled checkbox named `name`. When a row
139
+ changes, the header follows: checked when every row is, indeterminate when some are.
140
+
141
+ ```html
142
+ <input type="checkbox" data-check-all="ids[]" aria-label="Select all">
143
+ <input type="checkbox" name="ids[]" value="5">
144
+ ```
145
+
146
+ The header sets the rows without firing `change` on them, so a page counting selected rows listens to the header too.
147
+
148
+ ### `data-autoselect`
149
+
150
+ On an input or a textarea: a click selects all of its text, as tabbing in already does.
151
+
152
+ ```html
153
+ <input value="https://example.com/abcd" readonly data-autoselect>
154
+ ```
155
+
156
+ ## Styling
157
+
158
+ The package sets attributes and the browser's own states; the app styles them:
159
+
160
+ - `[data-copied]` and `[data-copy-failed]` on a copy button: show its "Copied" or "Copy it by hand" label instead of
161
+ "Copy". The words are the app's, in the button.
162
+ - `[data-submitting]` on a form sent once, to show the wait.
163
+ - `dialog`, `dialog::backdrop`, and `dialog[open]` for an opening transition.
164
+ - `:indeterminate` on a header checkbox, if the app restyles checkboxes.
165
+
166
+ ```html
167
+ <button type="button" data-copy="short-url">
168
+ <span class="copy-label">Copy</span>
169
+ <span class="copied-label">Copied</span>
170
+ <span class="failed-label">Copy it by hand</span>
171
+ </button>
172
+ ```
173
+
174
+ ```css
175
+ .copied-label,
176
+ .failed-label,
177
+ [data-copied] > .copy-label,
178
+ [data-copy-failed] > .copy-label {
179
+ display: none;
180
+ }
181
+
182
+ [data-copied] > .copied-label,
183
+ [data-copy-failed] > .failed-label {
184
+ display: inline;
185
+ }
186
+ ```
187
+
188
+ ## Accessibility
189
+
190
+ - Dialogs are native `<dialog>` opened with `showModal()`: focus moves in, the page behind is inert, Escape closes,
191
+ and focus goes back to the opener on close. Give each one an `aria-labelledby`.
192
+ - Put the copy state in the button's text (two spans, one hidden), so it never relies on colour alone.
193
+ - A refused copy selects and focuses the field, so the user can copy it with the keyboard.
194
+ - The copy marks change an attribute only, so screen readers announce nothing. A page that needs it adds a
195
+ `role="status"` line and fills it when `data-copied` appears (a `MutationObserver`).
196
+
197
+ ## Range picker
198
+
199
+ A date range for a GET form: a button opens a native popover with the app's preset ranges beside a Cally
200
+ `<calendar-range>`, and the picks fill the form's `from` and `to` fields. Its own entry loads Cally:
201
+
202
+ ```js
203
+ import {installRangePicker} from '@ismailnakkar/ui-behaviours/range-picker';
204
+
205
+ installRangePicker();
206
+ ```
207
+
208
+ Call it after the page is parsed; a second call does nothing. For each picker already on the page it rewrites the
209
+ labels from the fields and moves the calendar to the end day. A picker added later works too, but keeps the server's
210
+ labels and view until its first pick.
211
+
212
+ It needs the browser's Popover API (Chrome 114, Safari 17, Firefox 125), which npm cannot check: without it the button
213
+ opens nothing and the box shows in place, where its radios and fields still submit.
214
+
215
+ ### The markup
216
+
217
+ ```html
218
+ <form method="get" action="/reports">
219
+ <button type="button" popovertarget="report-range" data-range-state="preset">
220
+ <svg aria-hidden="true">…</svg>
221
+ <span data-range-name>Last 7 days</span>
222
+ <span data-range-dates="compact">14 Nov – 20 Nov</span>
223
+ </button>
224
+
225
+ <div id="report-range" popover data-range-picker data-range-state="preset">
226
+ <div role="radiogroup" aria-label="Range">
227
+ <label><input type="radio" name="range" value="today" data-range-preset="2026-11-20/2026-11-20"> Today</label>
228
+ <label><input type="radio" name="range" value="last7" data-range-preset="2026-11-14/2026-11-20" checked> Last 7 days</label>
229
+ <label><input type="radio" name="range" value="custom" data-range-custom> Custom range</label>
230
+ </div>
231
+
232
+ <calendar-range months="2" page-by="single" value="2026-11-14/2026-11-20" focused-date="2026-11-20"
233
+ min="2025-03-02" max="2026-11-20" today="2026-11-20" locale="en-GB" first-day-of-week="1">
234
+ <svg slot="previous" role="img" aria-label="Previous">…</svg>
235
+ <svg slot="next" role="img" aria-label="Next">…</svg>
236
+ <calendar-select-year slot="heading"><span slot="label">Year</span></calendar-select-year>
237
+ <calendar-month></calendar-month>
238
+ <calendar-month offset="1"></calendar-month>
239
+ </calendar-range>
240
+
241
+ <p aria-live="polite">
242
+ <span class="when-preset"><b data-range-name>Last 7 days</b>, </span>
243
+ <span data-range-dates>14 Nov – 20 Nov 2026</span>
244
+ <span class="when-pending">– pick the end day</span>
245
+ </p>
246
+
247
+ <input type="hidden" name="from" value="2026-11-14" data-range-from>
248
+ <input type="hidden" name="to" value="2026-11-20" data-range-to>
249
+ <button>Show</button>
250
+ </div>
251
+ </form>
252
+ ```
253
+
254
+ - **`data-range-picker`** marks the box holding the rest, a `popover` here. Its buttons are the elements whose
255
+ `popovertarget` names its id.
256
+ - **`data-range-preset="from/to"`** on a preset's radio gives its days as `YYYY-MM-DD/YYYY-MM-DD`, the format of
257
+ Cally's `value`; the server works them out, the package does no calendar maths. Picking it sets the calendar's
258
+ `value` and moves its view so the two months end on the end day's, with keyboard focus on that day (this needs
259
+ `page-by="single"`), then fills the fields and labels.
260
+ - **`data-range-custom`** on the Custom range radio: two days picked on the calendar check it and fill the fields.
261
+ While only the start is picked, the picker shows that day alone, named as Custom range, and the radios, the fields and
262
+ the buttons keep the range the form sends. Paging the calendar or changing its year or month only moves the view and
263
+ keeps the pick; picking a radio, this one too, drops it.
264
+ - **`data-range-from` and `data-range-to`** on the two hidden fields the form sends, inside the picker.
265
+ - **`<calendar-range>`** is set up and styled (`::part`) by the app: its months, `min`, `max`, `today`, `locale`,
266
+ `page-by` and slots. The package sets only its `value`, `focusedDate` and `tentative`.
267
+ - **`data-range-name`**, in the picker or a button: the checked radio's label text.
268
+ - **`data-range-dates`**, in the picker or a button: each end by `Intl.DateTimeFormat` (day, short month) in the
269
+ calendar's `locale`, else the page's `lang`, joined by a spaced en dash, with the year once when both ends share it
270
+ ("14 Nov – 20 Nov 2026"), on both when not ("28 Dec 2025 – 3 Jan 2026"), and one day alone ("20 Nov 2026").
271
+ `data-range-dates="compact"` leaves a shared year out ("14 Nov – 20 Nov"). Days that are no range (a field the
272
+ server refused) keep their text.
273
+ - **`data-range-state`**: `preset` or `custom` for the checked radio, and on the picker `pending` while only the start
274
+ is picked. The buttons show the range the form sends, so never `pending`.
275
+
276
+ Render the labels and the states on the server too: they are what shows before the script runs, and on a picker added
277
+ later until its first pick.
278
+
279
+ ### Styling the picker
280
+
281
+ The words for each state are the app's, in the markup; the app shows the ones `data-range-state` calls for:
282
+
283
+ ```css
284
+ .when-pending,
285
+ [data-range-state="custom"] .when-preset,
286
+ [data-range-state="pending"] .when-preset,
287
+ [data-range-state="custom"] > [data-range-name] {
288
+ display: none;
289
+ }
290
+
291
+ [data-range-state="pending"] .when-pending {
292
+ display: inline;
293
+ }
294
+ ```
295
+
296
+ While `pending` the checked radio is still the range the form sends. To show Custom range as the one being picked,
297
+ style `[data-range-state="pending"] label:has([data-range-custom])` as checked, and the checked label as not.
298
+
299
+ ### The picker's accessibility
300
+
301
+ - Label the radio group (`aria-label`) and the button (`aria-labelledby` on its field label and itself), and give the
302
+ summary `aria-live="polite"`, so a pick is read out.
303
+ - Give Cally's previous and next slots an `aria-label`, and its year select a `label` slot.
304
+
305
+ ## API
306
+
307
+ | Import | Does |
308
+ |---|---|
309
+ | `installUiBehaviours()` | listens on the document for every behaviour above and opens the `data-open-on-load` dialogs; later calls do nothing |
310
+ | `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 |
311
+ | `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 |
312
+
313
+ `copyText()` serves a page's own script, copying a link it just made:
314
+
315
+ ```js
316
+ import {copyText} from '@ismailnakkar/ui-behaviours';
317
+
318
+ if (!(await copyText(url))) {
319
+ field.select();
320
+ }
321
+ ```
322
+
323
+ ## Events
324
+
325
+ The package fires none of its own. A dialog's native `close` fires when a close button or the backdrop closes it, and
326
+ the range picker's radios fire the native `change`. Cally's `change` and `rangestart` do not bubble: listen to them in
327
+ the capture phase, as the package does.
328
+
329
+ ## Testing
330
+
331
+ The listeners need a DOM, so run your app's tests in happy-dom or jsdom (Vitest: `environment: 'happy-dom'`). They sit
332
+ on the document and outlive a test's markup: install them once per test file (`beforeAll`).
333
+
334
+ happy-dom and jsdom cannot run Cally. For the range picker, mock it, and define a `calendar-range` of your own that
335
+ holds `value`, `focusedDate` and `tentative`, and dispatches Cally's events, not bubbling: `change` once `value` holds
336
+ both days, `rangestart` with the start day as a `Date` in `detail`.
337
+
338
+ ```js
339
+ vi.mock('cally', () => ({}));
340
+
341
+ customElements.define('calendar-range', class extends HTMLElement {
342
+ value = '';
343
+ focusedDate = undefined;
344
+ tentative = '';
345
+ });
346
+ ```
347
+
348
+ Run this package's suite with `npm test`.
349
+
350
+ ## Upgrading
351
+
352
+ ### From 0.1
353
+
354
+ - A preset radio gives its days in one attribute, `data-range-preset="from/to"`, in place of `data-from` and `data-to`:
355
+ `data-from="2026-11-14" data-to="2026-11-20"` becomes `data-range-preset="2026-11-14/2026-11-20"`. The old pair is
356
+ no longer read: picking a radio marked with it fills nothing, and checked it shows as `custom`.
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
- "name": "@ismailnakkar/ui-behaviours",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@ismailnakkar/ui-behaviours",
3
+ "version": "0.2.0",
4
+ "description": "Page behaviours from plain HTML attributes (copy, confirm, submit once, native dialogs, check all, autoselect), and a date range picker over Cally.",
5
+ "keywords": [
6
+ "clipboard",
7
+ "dialog",
8
+ "confirm",
9
+ "date-range",
10
+ "cally",
11
+ "data-attributes",
12
+ "laravel"
13
+ ],
14
+ "homepage": "https://github.com/ismailnakkar/ui-behaviours",
15
+ "bugs": {
16
+ "url": "https://github.com/ismailnakkar/ui-behaviours/issues"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/ismailnakkar/ui-behaviours.git"
21
+ },
22
+ "license": "MIT",
23
+ "author": {
24
+ "name": "Ismail Nakkar",
25
+ "email": "juge.steam@gmail.com"
26
+ },
27
+ "type": "module",
28
+ "main": "src/index.js",
29
+ "types": "src/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "types": "./src/index.d.ts",
33
+ "default": "./src/index.js"
34
+ },
35
+ "./range-picker": {
36
+ "types": "./src/range-picker.d.ts",
37
+ "default": "./src/range-picker.js"
38
+ }
39
+ },
40
+ "files": [
41
+ "src"
42
+ ],
43
+ "sideEffects": [
44
+ "./src/range-picker.js"
45
+ ],
46
+ "publishConfig": {
47
+ "access": "public"
48
+ },
49
+ "scripts": {
50
+ "test": "vitest run",
51
+ "prepublishOnly": "npm test"
52
+ },
53
+ "peerDependencies": {
54
+ "cally": "^0.9.2"
55
+ },
56
+ "peerDependenciesMeta": {
57
+ "cally": {
58
+ "optional": true
59
+ }
60
+ },
61
+ "devDependencies": {
62
+ "cally": "^0.9.2",
63
+ "happy-dom": "^21.0.4",
64
+ "vitest": "^5.1.0"
65
+ }
66
+ }
package/src/helpers.js ADDED
@@ -0,0 +1,16 @@
1
+ /** Wraps an install function so only its first call runs. */
2
+ export function once(install) {
3
+ let installed = false;
4
+
5
+ return () => {
6
+ if (!installed) {
7
+ installed = true;
8
+ install();
9
+ }
10
+ };
11
+ }
12
+
13
+ /** The element matching selector at or above the event's target: a click on a button's icon lands on the icon. */
14
+ export function closestTo({target}, selector) {
15
+ return target instanceof Element ? target.closest(selector) : null;
16
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ /** Listens on the document for every behaviour and opens the data-open-on-load dialogs. Later calls do nothing. */
2
+ export function installUiBehaviours(): void;
3
+
4
+ /** Writes text to the clipboard: false where navigator.clipboard is absent (plain http) or refuses. */
5
+ export function copyText(text: string): Promise<boolean>;
package/src/index.js ADDED
@@ -0,0 +1,239 @@
1
+ import {closestTo, once} from './helpers.js';
2
+
3
+ const COPY_FLASH_MS = 1500;
4
+
5
+ const COPIED = 'data-copied';
6
+ const COPY_FAILED = 'data-copy-failed';
7
+ const SUBMITTING = 'data-submitting';
8
+
9
+ /** closedby's light-dismiss value, polyfilled where the browser lacks it. */
10
+ const CLOSED_BY_ANY = 'any';
11
+
12
+ const copyTimers = new WeakMap();
13
+
14
+ /** The dialog a press landed on outside its box: a selection dragged out of the body must not close it. */
15
+ let pressedBackdrop = null;
16
+
17
+ export const installUiBehaviours = once(() => {
18
+ document.addEventListener('submit', confirmSubmit);
19
+ // After the confirm: a refused submit was never sent.
20
+ document.addEventListener('submit', submitOnce);
21
+ window.addEventListener('pageshow', releaseSubmitted);
22
+ document.addEventListener('change', checkAll);
23
+ document.addEventListener('click', autoselect);
24
+ document.addEventListener('click', copyOnClick);
25
+ document.addEventListener('click', showModal);
26
+ document.addEventListener('click', closeModal);
27
+ document.addEventListener('pointerdown', pressBackdrop);
28
+ document.addEventListener('click', closeOnBackdrop);
29
+
30
+ openOnLoad();
31
+ });
32
+
33
+ export async function copyText(text) {
34
+ try {
35
+ await navigator.clipboard.writeText(text);
36
+
37
+ return true;
38
+ } catch {
39
+ // Absent on plain http, rejects when refused.
40
+ return false;
41
+ }
42
+ }
43
+
44
+ function isField(element) {
45
+ return element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement;
46
+ }
47
+
48
+ /** A link clicked to open elsewhere: a new tab, a new window, a download. */
49
+ function followsLink(opener, event) {
50
+ return opener instanceof HTMLAnchorElement
51
+ && (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey);
52
+ }
53
+
54
+ function confirmSubmit(event) {
55
+ if (event.defaultPrevented || !(event.target instanceof HTMLFormElement)) {
56
+ return;
57
+ }
58
+
59
+ const message = event.submitter?.dataset.confirm ?? event.target.dataset.confirm;
60
+
61
+ if (message && !confirm(message)) {
62
+ event.preventDefault();
63
+ }
64
+ }
65
+
66
+ // Refuses the submit rather than disabling the buttons: a disabled submitter drops its name and value.
67
+ function submitOnce(event) {
68
+ const form = event.target;
69
+
70
+ if (event.defaultPrevented || !(form instanceof HTMLFormElement) || !form.hasAttribute('data-submit-once')) {
71
+ return;
72
+ }
73
+
74
+ if (form.hasAttribute(SUBMITTING)) {
75
+ event.preventDefault();
76
+ } else {
77
+ form.setAttribute(SUBMITTING, '');
78
+ }
79
+ }
80
+
81
+ // A page back from the back-forward cache (Back from a payment page) may send its forms again.
82
+ function releaseSubmitted({persisted}) {
83
+ if (persisted) {
84
+ for (const form of document.querySelectorAll(`form[${SUBMITTING}]`)) {
85
+ form.removeAttribute(SUBMITTING);
86
+ }
87
+ }
88
+ }
89
+
90
+ function checkboxesNamed(name) {
91
+ return [...document.getElementsByName(name)].filter((box) => box.type === 'checkbox' && !box.disabled);
92
+ }
93
+
94
+ function checkAll({target}) {
95
+ if (!(target instanceof HTMLInputElement) || target.type !== 'checkbox') {
96
+ return;
97
+ }
98
+
99
+ const group = target.dataset.checkAll;
100
+
101
+ if (group !== undefined) {
102
+ for (const box of checkboxesNamed(group)) {
103
+ box.checked = target.checked;
104
+ }
105
+
106
+ return;
107
+ }
108
+
109
+ for (const header of document.querySelectorAll('input[data-check-all]')) {
110
+ if (header.dataset.checkAll === target.name) {
111
+ const rows = checkboxesNamed(target.name);
112
+ const checked = rows.filter((box) => box.checked).length;
113
+
114
+ header.checked = rows.length > 0 && checked === rows.length;
115
+ header.indeterminate = checked > 0 && checked < rows.length;
116
+ }
117
+ }
118
+ }
119
+
120
+ // Tabbing in selects a field's text natively; a click only places a caret.
121
+ function autoselect({target}) {
122
+ if (isField(target) && target.matches('[data-autoselect]')) {
123
+ target.select();
124
+ }
125
+ }
126
+
127
+ // innerText, not textContent: one line per block as laid out, so a list of recovery codes copies one a line.
128
+ function copiedTextOf(source) {
129
+ if (source.dataset.copyValue !== undefined) {
130
+ return source.dataset.copyValue;
131
+ }
132
+
133
+ if (isField(source)) {
134
+ return source.value;
135
+ }
136
+
137
+ return (source.innerText ?? source.textContent).trim();
138
+ }
139
+
140
+ async function copyOnClick(event) {
141
+ const button = closestTo(event, '[data-copy]');
142
+ const source = button ? document.getElementById(button.dataset.copy) : null;
143
+
144
+ if (!source || event.defaultPrevented) {
145
+ return;
146
+ }
147
+
148
+ const copied = await copyText(copiedTextOf(source));
149
+
150
+ flashCopyResult(button, copied);
151
+
152
+ if (!copied) {
153
+ selectForManualCopy(source);
154
+ }
155
+ }
156
+
157
+ function flashCopyResult(button, copied) {
158
+ clearTimeout(copyTimers.get(button));
159
+ button.toggleAttribute(COPIED, copied);
160
+ button.toggleAttribute(COPY_FAILED, !copied);
161
+ copyTimers.set(button, setTimeout(() => {
162
+ button.removeAttribute(COPIED);
163
+ button.removeAttribute(COPY_FAILED);
164
+ }, COPY_FLASH_MS));
165
+ }
166
+
167
+ // select() alone may leave the field unfocused; focused, Ctrl/Cmd+C copies it by hand.
168
+ function selectForManualCopy(source) {
169
+ if (isField(source)) {
170
+ source.focus();
171
+ source.select();
172
+ } else {
173
+ getSelection()?.selectAllChildren(source);
174
+ }
175
+ }
176
+
177
+ // A link's href stays the fallback: a modified click, or a page without the dialog, follows it.
178
+ function showModal(event) {
179
+ const opener = closestTo(event, '[data-show-modal]');
180
+ const dialog = opener ? document.getElementById(opener.dataset.showModal) : null;
181
+
182
+ if (!(dialog instanceof HTMLDialogElement) || event.defaultPrevented || followsLink(opener, event)) {
183
+ return;
184
+ }
185
+
186
+ event.preventDefault();
187
+
188
+ if (!dialog.open) {
189
+ dialog.showModal();
190
+ }
191
+ }
192
+
193
+ // preventDefault(): a submit button closes without sending its form.
194
+ function closeModal(event) {
195
+ const dialog = closestTo(event, '[data-close-modal]')?.closest('dialog');
196
+
197
+ if (dialog && !event.defaultPrevented) {
198
+ event.preventDefault();
199
+ dialog.close();
200
+ }
201
+ }
202
+
203
+ function openOnLoad() {
204
+ for (const dialog of document.querySelectorAll('dialog[data-open-on-load]')) {
205
+ if (!dialog.open) {
206
+ dialog.showModal();
207
+ }
208
+ }
209
+ }
210
+
211
+ function lightDismissIsNative() {
212
+ return 'closedBy' in HTMLDialogElement.prototype;
213
+ }
214
+
215
+ // A backdrop click lands on the dialog element itself, outside its box.
216
+ function backdropDialogOf({target, clientX, clientY}) {
217
+ if (!(target instanceof HTMLDialogElement) || !target.open || target.getAttribute('closedby') !== CLOSED_BY_ANY) {
218
+ return null;
219
+ }
220
+
221
+ const box = target.getBoundingClientRect();
222
+ const inside = clientX >= box.left && clientX <= box.right && clientY >= box.top && clientY <= box.bottom;
223
+
224
+ return inside ? null : target;
225
+ }
226
+
227
+ function pressBackdrop(event) {
228
+ pressedBackdrop = lightDismissIsNative() ? null : backdropDialogOf(event);
229
+ }
230
+
231
+ function closeOnBackdrop(event) {
232
+ const dialog = pressedBackdrop;
233
+
234
+ pressedBackdrop = null;
235
+
236
+ if (dialog && backdropDialogOf(event) === dialog) {
237
+ dialog.close();
238
+ }
239
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Listens on the document for range pickers, and writes the labels and calendar view of those already on the page.
3
+ * Later calls do nothing.
4
+ */
5
+ export function installRangePicker(): void;
@@ -0,0 +1,252 @@
1
+ import 'cally';
2
+ import {closestTo, once} from './helpers.js';
3
+
4
+ const PICKER = '[data-range-picker]';
5
+ const CALENDAR = 'calendar-range';
6
+ const STATE = 'data-range-state';
7
+
8
+ /** The values of data-range-state: a preset's days, days picked on the calendar, or only the start picked. */
9
+ const State = Object.freeze({preset: 'preset', custom: 'custom', pending: 'pending'});
10
+
11
+ /** data-range-dates="compact" leaves out a year both ends share. */
12
+ const COMPACT = 'compact';
13
+
14
+ /** Between the two days of a Cally range value, and of a preset's data-range-preset: "2026-11-14/2026-11-20". */
15
+ const VALUE_SEPARATOR = '/';
16
+
17
+ /** A spaced en dash: "14 Nov – 20 Nov 2026". */
18
+ const DATES_SEPARATOR = ' – ';
19
+
20
+ // In UTC, as dayOf() reads each day as its UTC midnight.
21
+ const DAY = {day: 'numeric', month: 'short', timeZone: 'UTC'};
22
+ const DAY_AND_YEAR = {...DAY, year: 'numeric'};
23
+
24
+ const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/;
25
+
26
+ export const installRangePicker = once(() => {
27
+ // Cally's change and rangestart don't bubble: listen in the capture phase.
28
+ document.addEventListener('change', pickRange, true);
29
+ document.addEventListener('rangestart', pickStart, true);
30
+
31
+ for (const picker of document.querySelectorAll(PICKER)) {
32
+ showRange(picker);
33
+ viewEndDay(picker, fieldsOf(picker).to?.value);
34
+ }
35
+ });
36
+
37
+ function isCalendar(element) {
38
+ return element.localName === CALENDAR;
39
+ }
40
+
41
+ function isRadio(element) {
42
+ return element instanceof HTMLInputElement && element.type === 'radio';
43
+ }
44
+
45
+ function pickRange(event) {
46
+ const picker = closestTo(event, PICKER);
47
+
48
+ if (!picker) {
49
+ return;
50
+ }
51
+
52
+ const target = event.target;
53
+
54
+ if (isCalendar(target)) {
55
+ const [from, to] = target.value.split(VALUE_SEPARATOR);
56
+
57
+ checkCustom(picker);
58
+ applyRange(picker, from, to);
59
+ } else if (isRadio(target)) {
60
+ const preset = presetOf(target);
61
+
62
+ dropStart(picker);
63
+
64
+ if (preset) {
65
+ moveCalendar(picker, preset.from, preset.to);
66
+ applyRange(picker, preset.from, preset.to);
67
+ } else if (target.hasAttribute('data-range-custom')) {
68
+ showRange(picker);
69
+ }
70
+ }
71
+ }
72
+
73
+ // Only the picker shows the start, as a custom range: the radios, fields and buttons keep the range the form sends.
74
+ function pickStart(event) {
75
+ const picker = closestTo(event, PICKER);
76
+
77
+ if (!picker || !isCalendar(event.target)) {
78
+ return;
79
+ }
80
+
81
+ const start = isoOf(event.detail);
82
+ const range = {state: State.pending, name: nameOf(customRadioOf(picker)), from: start, to: start};
83
+
84
+ showIn(picker, range, localeOf(picker));
85
+ }
86
+
87
+ /** A preset radio's days, worked out by the server, from its data-range-preset="from/to"; null for Custom range. */
88
+ function presetOf(radio) {
89
+ const [from, to] = radio?.dataset.rangePreset?.split(VALUE_SEPARATOR) ?? [];
90
+
91
+ return from && to ? {from, to} : null;
92
+ }
93
+
94
+ function calendarOf(picker) {
95
+ return picker.querySelector(CALENDAR);
96
+ }
97
+
98
+ function checkedRadioOf(picker) {
99
+ return picker.querySelector('input[type="radio"]:checked');
100
+ }
101
+
102
+ function customRadioOf(picker) {
103
+ return picker.querySelector('input[type="radio"][data-range-custom]');
104
+ }
105
+
106
+ function checkCustom(picker) {
107
+ const custom = customRadioOf(picker);
108
+
109
+ if (custom) {
110
+ custom.checked = true;
111
+ }
112
+ }
113
+
114
+ /** Drops a start still waiting for its end day. */
115
+ function dropStart(picker) {
116
+ const calendar = calendarOf(picker);
117
+
118
+ if (calendar) {
119
+ calendar.tentative = '';
120
+ }
121
+ }
122
+
123
+ function moveCalendar(picker, from, to) {
124
+ const calendar = calendarOf(picker);
125
+
126
+ if (calendar) {
127
+ calendar.value = from + VALUE_SEPARATOR + to;
128
+ viewEndDay(picker, to);
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Ends the two months on the end day's and focuses that day. Cally pages to a far day by whole pages, which can leave
134
+ * it in the first month. So the view goes to the month before first, then, a task later once Cally has redrawn, to the
135
+ * day itself: one page on with page-by="single".
136
+ */
137
+ function viewEndDay(picker, to) {
138
+ const calendar = calendarOf(picker);
139
+ const monthBefore = dayOf(to);
140
+
141
+ if (!calendar || !monthBefore) {
142
+ return;
143
+ }
144
+
145
+ monthBefore.setUTCDate(1);
146
+ monthBefore.setUTCMonth(monthBefore.getUTCMonth() - 1);
147
+ calendar.focusedDate = isoOf(monthBefore);
148
+ setTimeout(() => {
149
+ calendar.focusedDate = to;
150
+ });
151
+ }
152
+
153
+ function fieldsOf(picker) {
154
+ return {
155
+ from: picker.querySelector('input[data-range-from]'),
156
+ to: picker.querySelector('input[data-range-to]'),
157
+ };
158
+ }
159
+
160
+ function applyRange(picker, from, to) {
161
+ const fields = fieldsOf(picker);
162
+
163
+ if (fields.from && fields.to) {
164
+ fields.from.value = from;
165
+ fields.to.value = to;
166
+ }
167
+
168
+ showRange(picker);
169
+ }
170
+
171
+ /** Shows the range the form sends on the picker and the buttons that open it. */
172
+ function showRange(picker) {
173
+ const radio = checkedRadioOf(picker);
174
+ const fields = fieldsOf(picker);
175
+ const range = {
176
+ state: presetOf(radio) ? State.preset : State.custom,
177
+ name: nameOf(radio),
178
+ from: fields.from?.value,
179
+ to: fields.to?.value,
180
+ };
181
+ const locale = localeOf(picker);
182
+
183
+ for (const display of [picker, ...openersOf(picker)]) {
184
+ showIn(display, range, locale);
185
+ }
186
+ }
187
+
188
+ function showIn(display, {state, name, from, to}, locale) {
189
+ display.setAttribute(STATE, state);
190
+
191
+ for (const label of display.querySelectorAll('[data-range-name]')) {
192
+ label.textContent = name;
193
+ }
194
+
195
+ for (const label of display.querySelectorAll('[data-range-dates]')) {
196
+ const dates = datesOf(from, to, locale, label.dataset.rangeDates === COMPACT);
197
+
198
+ // Days that aren't a range (a field the server refused) keep the server's words.
199
+ if (dates !== null) {
200
+ label.textContent = dates;
201
+ }
202
+ }
203
+ }
204
+
205
+ function nameOf(radio) {
206
+ return radio?.labels?.[0]?.textContent.replace(/\s+/g, ' ').trim() ?? '';
207
+ }
208
+
209
+ function openersOf(picker) {
210
+ if (!picker.id) {
211
+ return [];
212
+ }
213
+
214
+ return [...document.querySelectorAll('[popovertarget]')]
215
+ .filter((opener) => opener.getAttribute('popovertarget') === picker.id);
216
+ }
217
+
218
+ /** The calendar's locale, so the labels match its months; else the page's lang. */
219
+ function localeOf(picker) {
220
+ return calendarOf(picker)?.getAttribute('locale') || picker.closest('[lang]')?.lang || undefined;
221
+ }
222
+
223
+ function isoOf(day) {
224
+ return day.toISOString().slice(0, 10);
225
+ }
226
+
227
+ function dayOf(iso) {
228
+ const day = ISO_DAY.test(iso) ? new Date(`${iso}T00:00:00Z`) : null;
229
+
230
+ return day && !Number.isNaN(day.getTime()) ? day : null;
231
+ }
232
+
233
+ // The year once when both ends share it (none on a compact label), on both when not; one day alone.
234
+ function datesOf(from, to, locale, compact) {
235
+ const start = dayOf(from);
236
+ const end = dayOf(to);
237
+
238
+ if (!start || !end || start > end) {
239
+ return null;
240
+ }
241
+
242
+ const sameYear = start.getUTCFullYear() === end.getUTCFullYear();
243
+ const day = new Intl.DateTimeFormat(locale, DAY);
244
+ const dayAndYear = new Intl.DateTimeFormat(locale, DAY_AND_YEAR);
245
+ const last = (compact && sameYear ? day : dayAndYear).format(end);
246
+
247
+ if (start.getTime() === end.getTime()) {
248
+ return last;
249
+ }
250
+
251
+ return (sameYear ? day : dayAndYear).format(start) + DATES_SEPARATOR + last;
252
+ }