@ismailnakkar/ui-behaviours 0.0.0-stage → 0.1.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,344 @@
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. One call
5
+ installs them as listeners 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
+ No dependencies for the behaviours. The [range picker](#range-picker) needs Cally 0.9, an optional peer dependency:
18
+ `npm i cally`. Type declarations are included.
19
+
20
+ ## Usage
21
+
22
+ Call it once from the layout's script, on every page:
23
+
24
+ ```js
25
+ import {installUiBehaviours} from '@ismailnakkar/ui-behaviours';
26
+
27
+ installUiBehaviours();
28
+ ```
29
+
30
+ Run it after the page is parsed (a module script, or a deferred one): it opens the `data-open-on-load` dialogs there and
31
+ then. A second call does nothing.
32
+
33
+ `copyText(text)` is the clipboard write the copy buttons use, for a page's own script (copying a link it just made):
34
+ it resolves to `true` when the clipboard took the text, `false` where `navigator.clipboard` is absent (plain http) or
35
+ refuses.
36
+
37
+ ```js
38
+ import {copyText} from '@ismailnakkar/ui-behaviours';
39
+
40
+ if (!(await copyText(url))) {
41
+ field.select();
42
+ }
43
+ ```
44
+
45
+ ## The attributes
46
+
47
+ | Attribute | On | Does |
48
+ |---|---|---|
49
+ | [`data-copy="id"`](#data-copyid) | a button | copies the element with that id |
50
+ | [`data-copy-value`](#data-copyid) | the copied element | the text to copy instead of what it shows |
51
+ | [`data-confirm="question"`](#data-confirmquestion) | a form or a submit button | asks before submitting |
52
+ | [`data-submit-once`](#data-submit-once) | a form | refuses a second submit |
53
+ | [`data-show-modal="id"`](#data-show-modalid) | a button or a link | opens the dialog with that id as a modal |
54
+ | [`data-close-modal`](#data-close-modal) | a button in a dialog | closes that dialog |
55
+ | [`closedby="any"`](#closedbyany) | a dialog | closes it on a backdrop click |
56
+ | [`data-open-on-load`](#data-open-on-load) | a dialog | opens it on install |
57
+ | [`data-check-all="name"`](#data-check-allname) | a header checkbox | checks every row named `name` |
58
+ | [`data-autoselect`](#data-autoselect) | an input or a textarea | selects its text on a click |
59
+
60
+ ### `data-copy="id"`
61
+
62
+ On a button: a click copies the element with that id. That is its `data-copy-value` when it has one (text grouped on
63
+ screen for reading, such as a setup key), else an input's or a textarea's current value, else its text as laid out
64
+ (`innerText`: one line per block, so a list copies one item a line), trimmed.
65
+
66
+ ```html
67
+ <input id="short-url" value="https://example.com/abcd" readonly data-autoselect>
68
+ <button type="button" data-copy="short-url"><span>Copy</span><span>Copied</span></button>
69
+
70
+ <code id="setup-key" data-copy-value="JBSWY3DPEHPK3PXP">JBSW Y3DP EHPK 3PXP</code>
71
+ <button type="button" data-copy="setup-key">Copy key</button>
72
+ ```
73
+
74
+ The button gets `data-copied` for 1.5 seconds when the copy worked, or `data-copy-failed` when the browser refused;
75
+ the field or text is then selected, focused for a field, so the user copies it by hand. A second click restarts the
76
+ 1.5 seconds and replaces the other mark. A missing source copies nothing.
77
+
78
+ To refuse a copy (asking for a missing field first), call `event.preventDefault()` in a click listener of the page's
79
+ own on the button or an element around it: the copy skips a cancelled click.
80
+
81
+ ### `data-confirm="question"`
82
+
83
+ On a form, or on one of its submit buttons: the browser's `confirm()` asks that question, and only a yes submits. The
84
+ pressed button's question wins over the form's, so buttons sharing a form ask their own; a button without one asks the
85
+ form's. A submit the page already cancelled asks nothing.
86
+
87
+ ```html
88
+ <form method="POST" action="/links/5" data-confirm="Delete this link?">…</form>
89
+
90
+ <button formaction="/admin/withdrawals/5/approve" data-confirm="Approve withdrawal #5?">Approve</button>
91
+ ```
92
+
93
+ ### `data-submit-once`
94
+
95
+ On a form: the first submit goes and marks the form `data-submitting`; every later one is refused, so a double click on
96
+ a payment button pays once. The buttons stay enabled, as a disabled submitter would drop its `name` and `value` from
97
+ the form; style the mark to show the wait. A submit `data-confirm` refused was never sent and leaves no mark. A page
98
+ restored from the back-forward cache (Back from a provider's page) drops the mark, so its forms send again.
99
+
100
+ ```html
101
+ <form method="POST" action="/subscription" data-submit-once>
102
+ <button name="gateway" value="stripe">Pay by card</button>
103
+ <button name="gateway" value="balance">Pay with balance</button>
104
+ </form>
105
+ ```
106
+
107
+ ### `data-show-modal="id"`
108
+
109
+ On a button or a link: a click opens the `<dialog>` with that id with `showModal()` (Escape closes it, focus moves in,
110
+ the page behind is inert). On a link, the `href` is the fallback: a modified click (new tab, new window) follows it, as
111
+ does any click on a page without that dialog. A click the page cancelled opens nothing, and an open dialog stays open.
112
+
113
+ ```html
114
+ <a href="/links/create" data-show-modal="shorten-dialog">Shorten a link</a>
115
+ ```
116
+
117
+ ### `data-close-modal`
118
+
119
+ On a button inside a dialog: a click closes that dialog (the native `close` event fires). On a submit button it closes
120
+ without sending the form, so a Cancel button may sit in the dialog's form.
121
+
122
+ ```html
123
+ <button type="button" data-close-modal>Cancel</button>
124
+ ```
125
+
126
+ The native `<form method="dialog">` closes a dialog without script, as does Escape.
127
+
128
+ ### `closedby="any"`
129
+
130
+ On a dialog: the native attribute for light dismiss. A click on the backdrop closes the dialog; a press inside its box
131
+ dragged out onto the backdrop (a text selection) does not. Where the browser supports `closedby` the package leaves it
132
+ to the browser, elsewhere it does it itself.
133
+
134
+ ```html
135
+ <dialog id="shorten-dialog" aria-labelledby="shorten-dialog-title" closedby="any">…</dialog>
136
+ ```
137
+
138
+ ### `data-open-on-load`
139
+
140
+ On a dialog: it opens with `showModal()` when the behaviours are installed, say to show a dialog again after a failed
141
+ submit inside it, or a one-time result.
142
+
143
+ ```html
144
+ <dialog id="recovery-codes" data-open-on-load>…</dialog>
145
+ ```
146
+
147
+ ### `data-check-all="name"`
148
+
149
+ On a header checkbox: checking or unchecking it does the same to every enabled checkbox named `name`. When a row
150
+ changes, the header follows: checked when every row is, indeterminate when some are.
151
+
152
+ ```html
153
+ <input type="checkbox" data-check-all="ids[]" aria-label="Select all">
154
+ <input type="checkbox" name="ids[]" value="5">
155
+ ```
156
+
157
+ Setting the rows from the header fires no `change` on them: a page counting selected rows listens to the header too.
158
+
159
+ ### `data-autoselect`
160
+
161
+ On an input or a textarea: a click selects all of its text, as tabbing in already does natively.
162
+
163
+ ```html
164
+ <input value="https://example.com/abcd" readonly data-autoselect>
165
+ ```
166
+
167
+ ## Styling
168
+
169
+ The package sets attributes and the browser's own states; the app styles them:
170
+
171
+ - `[data-copied]` and `[data-copy-failed]` on a copy button: show its "Copied" or "Copy it by hand" label, hide
172
+ "Copy". The words are the app's, in the button.
173
+ - `dialog`, `dialog::backdrop`, and `dialog[open]` for an opening transition.
174
+ - `:indeterminate` on a header checkbox, if the app restyles checkboxes.
175
+
176
+ ```html
177
+ <button type="button" data-copy="short-url">
178
+ <span class="copy-label">Copy</span>
179
+ <span class="copied-label">Copied</span>
180
+ <span class="failed-label">Copy it by hand</span>
181
+ </button>
182
+ ```
183
+
184
+ ```css
185
+ .copied-label,
186
+ .failed-label,
187
+ [data-copied] > .copy-label,
188
+ [data-copy-failed] > .copy-label {
189
+ display: none;
190
+ }
191
+
192
+ [data-copied] > .copied-label,
193
+ [data-copy-failed] > .failed-label {
194
+ display: inline;
195
+ }
196
+ ```
197
+
198
+ ## Events
199
+
200
+ The package fires none of its own. A dialog's native `close` event fires when a close button or the backdrop closes it.
201
+
202
+ ## Accessibility
203
+
204
+ - Dialogs are native `<dialog>` opened with `showModal()`: focus moves in, the page behind is inert, Escape closes,
205
+ and focus goes back to the opener on close. Give each one an `aria-labelledby`.
206
+ - Put the copy state in the button's text (two spans, one hidden), so it never relies on colour alone.
207
+ - A refused copy selects and focuses the field, so the user can copy it with the keyboard.
208
+ - The copy marks change an attribute only, so screen readers announce nothing. A page that needs it adds a
209
+ `role="status"` line and fills it when `data-copied` appears (a `MutationObserver`).
210
+
211
+ ## Testing
212
+
213
+ The listeners need a DOM, so run your app's tests in happy-dom or jsdom (Vitest: `environment: 'happy-dom'`). They sit
214
+ on the document and outlive a test's markup: install them once per test file (`beforeAll`).
215
+
216
+ Run this package's suite with `npm test`.
217
+
218
+ ## Range picker
219
+
220
+ A date range for a GET form: a button opens a native popover with the app's preset ranges beside a Cally
221
+ `<calendar-range>`, and the picks fill the form's `from` and `to` fields. It is its own entry, which loads Cally:
222
+
223
+ ```js
224
+ import {installRangePicker} from '@ismailnakkar/ui-behaviours/range-picker';
225
+
226
+ installRangePicker();
227
+ ```
228
+
229
+ As with `installUiBehaviours()`, call it after the page is parsed; a second call does nothing. For each picker already
230
+ on the page it rewrites the labels from the fields and moves the calendar to the end day. A picker added later works
231
+ too, but keeps the server's labels and view until its first pick.
232
+
233
+ It needs the browser's Popover API (Chrome 114, Safari 17, Firefox 125), which npm cannot check: without it the button
234
+ opens nothing and the box shows in place, where its radios and fields still submit.
235
+
236
+ ### The markup
237
+
238
+ ```html
239
+ <form method="get" action="/reports">
240
+ <button type="button" popovertarget="report-range" data-range-state="preset">
241
+ <svg aria-hidden="true">…</svg>
242
+ <span data-range-name>Last 7 days</span>
243
+ <span data-range-dates="compact">14 Nov – 20 Nov</span>
244
+ </button>
245
+
246
+ <div id="report-range" popover data-range-picker data-range-state="preset">
247
+ <div role="radiogroup" aria-label="Range">
248
+ <label><input type="radio" name="range" value="today" data-from="2026-11-20" data-to="2026-11-20"> Today</label>
249
+ <label><input type="radio" name="range" value="last7" data-from="2026-11-14" data-to="2026-11-20" checked> Last 7 days</label>
250
+ <label><input type="radio" name="range" value="custom" data-range-custom> Custom range</label>
251
+ </div>
252
+
253
+ <calendar-range months="2" page-by="single" value="2026-11-14/2026-11-20" focused-date="2026-11-20"
254
+ min="2025-03-02" max="2026-11-20" today="2026-11-20" locale="en-GB" first-day-of-week="1">
255
+ <svg slot="previous" role="img" aria-label="Previous">…</svg>
256
+ <svg slot="next" role="img" aria-label="Next">…</svg>
257
+ <calendar-select-year slot="heading"><span slot="label">Year</span></calendar-select-year>
258
+ <calendar-month></calendar-month>
259
+ <calendar-month offset="1"></calendar-month>
260
+ </calendar-range>
261
+
262
+ <p aria-live="polite">
263
+ <span class="when-preset"><b data-range-name>Last 7 days</b>, </span>
264
+ <span data-range-dates>14 Nov – 20 Nov 2026</span>
265
+ <span class="when-pending">– pick the end day</span>
266
+ </p>
267
+
268
+ <input type="hidden" name="from" value="2026-11-14" data-range-from>
269
+ <input type="hidden" name="to" value="2026-11-20" data-range-to>
270
+ <button>Show</button>
271
+ </div>
272
+ </form>
273
+ ```
274
+
275
+ - **`data-range-picker`** marks the box holding the rest, a `popover` here. Its buttons are the elements whose
276
+ `popovertarget` names its id.
277
+ - **`data-from` and `data-to`** on a preset's radio give its days as `YYYY-MM-DD`; the server works them out, the
278
+ package does no calendar maths. Picking it sets the calendar's `value` and moves its view so the two months end on
279
+ the end day's, with keyboard focus on that day (this needs `page-by="single"`), then fills the fields and labels.
280
+ - **`data-range-custom`** on the Custom range radio: two days picked on the calendar check it and fill the fields.
281
+ While only the start is picked, the picker shows that day alone, named as Custom range, and the radios, the fields and
282
+ the buttons keep the range the form sends. Paging the calendar or changing its year or month only moves the view and
283
+ keeps the pick; picking a radio, this one too, drops it.
284
+ - **`data-range-from` and `data-range-to`** on the two hidden fields the form sends, inside the picker.
285
+ - **`<calendar-range>`** is set up and styled (`::part`) by the app: its months, `min`, `max`, `today`, `locale`,
286
+ `page-by` and slots. The package sets only its `value`, `focusedDate` and `tentative`.
287
+ - **`data-range-name`**, in the picker or a button: the checked radio's label text.
288
+ - **`data-range-dates`**, in the picker or a button: each end by `Intl.DateTimeFormat` (day, short month) in the
289
+ calendar's `locale`, else the page's `lang`, joined by a spaced en dash, with the year once when both ends share it
290
+ ("14 Nov – 20 Nov 2026"), on both when not ("28 Dec 2025 – 3 Jan 2026"), and one day alone ("20 Nov 2026").
291
+ `data-range-dates="compact"` leaves a shared year out ("14 Nov – 20 Nov"). Days that are no range (a field the
292
+ server refused) keep their text.
293
+ - **`data-range-state`**: `preset` or `custom` for the checked radio, and on the picker `pending` while only the start
294
+ is picked. The buttons show the range the form sends, so never `pending`.
295
+
296
+ Render the labels and the states on the server too: they are what shows before the script runs, and on a picker added
297
+ later until its first pick.
298
+
299
+ ### Styling
300
+
301
+ The words for each state are the app's, in the markup; the app shows the ones `data-range-state` calls for:
302
+
303
+ ```css
304
+ .when-pending,
305
+ [data-range-state="custom"] .when-preset,
306
+ [data-range-state="pending"] .when-preset,
307
+ [data-range-state="custom"] > [data-range-name] {
308
+ display: none;
309
+ }
310
+
311
+ [data-range-state="pending"] .when-pending {
312
+ display: inline;
313
+ }
314
+ ```
315
+
316
+ While `pending` the checked radio is still the range the form sends. To show Custom range as the one being picked,
317
+ style `[data-range-state="pending"] label:has([data-range-custom])` as checked, and the checked label as not.
318
+
319
+ ### Events
320
+
321
+ The package fires none of its own. Cally's `change` and `rangestart` do not bubble, so listen to them in the capture
322
+ phase, as the package does. The radios fire the native `change`.
323
+
324
+ ### Accessibility
325
+
326
+ - Label the radio group (`aria-label`) and the button (`aria-labelledby` on its field label and itself), and give the
327
+ summary `aria-live="polite"`, so a pick is read out.
328
+ - Give Cally's previous and next slots an `aria-label`, and its year select a `label` slot.
329
+
330
+ ### Testing
331
+
332
+ happy-dom and jsdom cannot run Cally. Mock it, and define a `calendar-range` of your own that holds `value`,
333
+ `focusedDate` and `tentative`, and dispatches Cally's events, not bubbling: `change` once `value` holds both days,
334
+ `rangestart` with the start day as a `Date` in `detail`.
335
+
336
+ ```js
337
+ vi.mock('cally', () => ({}));
338
+
339
+ customElements.define('calendar-range', class extends HTMLElement {
340
+ value = '';
341
+ focusedDate = undefined;
342
+ tentative = '';
343
+ });
344
+ ```
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.1.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', copyButton);
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.querySelectorAll('input[type="checkbox"]')].filter((box) => box.name === name && !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 copyButton(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
+ flashCopied(button, copied);
151
+
152
+ if (!copied) {
153
+ selectForManualCopy(source);
154
+ }
155
+ }
156
+
157
+ function flashCopied(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
+ // Explicit focus(): Safari does not focus a clicked button.
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,244 @@
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: "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
+ const DAY = {day: 'numeric', month: 'short', timeZone: 'UTC'};
21
+ const DAY_AND_YEAR = {...DAY, year: 'numeric'};
22
+
23
+ const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/;
24
+
25
+ export const installRangePicker = once(() => {
26
+ // Cally's change and rangestart don't bubble: listen in the capture phase.
27
+ document.addEventListener('change', pickRange, true);
28
+ document.addEventListener('rangestart', pickStart, true);
29
+
30
+ for (const picker of document.querySelectorAll(PICKER)) {
31
+ showRange(picker);
32
+ viewEndDay(picker, fieldsOf(picker).to?.value);
33
+ }
34
+ });
35
+
36
+ function isCalendar(element) {
37
+ return element.localName === CALENDAR;
38
+ }
39
+
40
+ function isRadio(element) {
41
+ return element instanceof HTMLInputElement && element.type === 'radio';
42
+ }
43
+
44
+ function pickRange(event) {
45
+ const picker = closestTo(event, PICKER);
46
+ const target = event.target;
47
+
48
+ if (!picker) {
49
+ return;
50
+ }
51
+
52
+ if (isCalendar(target)) {
53
+ const [from, to] = target.value.split(VALUE_SEPARATOR);
54
+
55
+ checkCustom(picker);
56
+ applyRange(picker, from, to);
57
+ } else if (isRadio(target)) {
58
+ const preset = presetOf(target);
59
+
60
+ dropStart(picker);
61
+
62
+ if (preset) {
63
+ moveCalendar(picker, preset.from, preset.to);
64
+ applyRange(picker, preset.from, preset.to);
65
+ } else if (target.hasAttribute('data-range-custom')) {
66
+ showRange(picker);
67
+ }
68
+ }
69
+ }
70
+
71
+ // Only the picker shows the start, as a custom range: the radios, fields and buttons keep the range the form sends.
72
+ function pickStart(event) {
73
+ const picker = closestTo(event, PICKER);
74
+
75
+ if (!picker || !isCalendar(event.target)) {
76
+ return;
77
+ }
78
+
79
+ const start = isoOf(event.detail);
80
+
81
+ showIn(picker, {state: State.pending, name: nameOf(customRadioOf(picker)), from: start, to: start}, localeOf(picker));
82
+ }
83
+
84
+ /** A preset radio's days, worked out by the server; null for Custom range. */
85
+ function presetOf(radio) {
86
+ const {from, to} = radio?.dataset ?? {};
87
+
88
+ return from && to ? {from, to} : null;
89
+ }
90
+
91
+ function checkedRadioOf(picker) {
92
+ return picker.querySelector('input[type="radio"]:checked');
93
+ }
94
+
95
+ function customRadioOf(picker) {
96
+ return picker.querySelector('input[type="radio"][data-range-custom]');
97
+ }
98
+
99
+ function checkCustom(picker) {
100
+ const custom = customRadioOf(picker);
101
+
102
+ if (custom) {
103
+ custom.checked = true;
104
+ }
105
+ }
106
+
107
+ /** Drops a start still waiting for its end day. */
108
+ function dropStart(picker) {
109
+ const calendar = picker.querySelector(CALENDAR);
110
+
111
+ if (calendar) {
112
+ calendar.tentative = '';
113
+ }
114
+ }
115
+
116
+ function moveCalendar(picker, from, to) {
117
+ const calendar = picker.querySelector(CALENDAR);
118
+
119
+ if (calendar) {
120
+ calendar.value = from + VALUE_SEPARATOR + to;
121
+ viewEndDay(picker, to);
122
+ }
123
+ }
124
+
125
+ /**
126
+ * 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
127
+ * it in the first month: so first the month before, then, a task later once Cally has redrawn, the day itself, one
128
+ * month on (page-by="single").
129
+ */
130
+ function viewEndDay(picker, to) {
131
+ const calendar = picker.querySelector(CALENDAR);
132
+ const monthBefore = dayOf(to);
133
+
134
+ if (!calendar || !monthBefore) {
135
+ return;
136
+ }
137
+
138
+ monthBefore.setUTCDate(1);
139
+ monthBefore.setUTCMonth(monthBefore.getUTCMonth() - 1);
140
+ calendar.focusedDate = isoOf(monthBefore);
141
+ setTimeout(() => {
142
+ calendar.focusedDate = to;
143
+ });
144
+ }
145
+
146
+ function fieldsOf(picker) {
147
+ return {
148
+ from: picker.querySelector('input[data-range-from]'),
149
+ to: picker.querySelector('input[data-range-to]'),
150
+ };
151
+ }
152
+
153
+ function applyRange(picker, from, to) {
154
+ const fields = fieldsOf(picker);
155
+
156
+ if (fields.from && fields.to) {
157
+ fields.from.value = from;
158
+ fields.to.value = to;
159
+ }
160
+
161
+ showRange(picker);
162
+ }
163
+
164
+ /** Shows the range the form sends on the picker and the buttons that open it. */
165
+ function showRange(picker) {
166
+ const radio = checkedRadioOf(picker);
167
+ const fields = fieldsOf(picker);
168
+ const range = {
169
+ state: presetOf(radio) ? State.preset : State.custom,
170
+ name: nameOf(radio),
171
+ from: fields.from?.value,
172
+ to: fields.to?.value,
173
+ };
174
+ const locale = localeOf(picker);
175
+
176
+ for (const display of [picker, ...openersOf(picker)]) {
177
+ showIn(display, range, locale);
178
+ }
179
+ }
180
+
181
+ function showIn(display, {state, name, from, to}, locale) {
182
+ display.setAttribute(STATE, state);
183
+
184
+ for (const label of display.querySelectorAll('[data-range-name]')) {
185
+ label.textContent = name;
186
+ }
187
+
188
+ for (const label of display.querySelectorAll('[data-range-dates]')) {
189
+ const dates = datesOf(from, to, locale, label.dataset.rangeDates === COMPACT);
190
+
191
+ // Days that aren't a range (a field the server refused) keep the server's words.
192
+ if (dates !== null) {
193
+ label.textContent = dates;
194
+ }
195
+ }
196
+ }
197
+
198
+ function nameOf(radio) {
199
+ return radio?.labels?.[0]?.textContent.replace(/\s+/g, ' ').trim() ?? '';
200
+ }
201
+
202
+ function openersOf(picker) {
203
+ if (!picker.id) {
204
+ return [];
205
+ }
206
+
207
+ return [...document.querySelectorAll('[popovertarget]')].filter((opener) => opener.getAttribute('popovertarget') === picker.id);
208
+ }
209
+
210
+ /** The calendar's locale, so the labels match its months; else the page's lang. */
211
+ function localeOf(picker) {
212
+ return picker.querySelector(CALENDAR)?.getAttribute('locale') || picker.closest('[lang]')?.lang || undefined;
213
+ }
214
+
215
+ function isoOf(day) {
216
+ return day.toISOString().slice(0, 10);
217
+ }
218
+
219
+ function dayOf(iso) {
220
+ const day = ISO_DAY.test(iso) ? new Date(`${iso}T00:00:00Z`) : null;
221
+
222
+ return day && !Number.isNaN(day.getTime()) ? day : null;
223
+ }
224
+
225
+ // The year once when both ends share it (none on a compact label), on both when not; one day alone.
226
+ function datesOf(from, to, locale, compact) {
227
+ const start = dayOf(from);
228
+ const end = dayOf(to);
229
+
230
+ if (!start || !end || start > end) {
231
+ return null;
232
+ }
233
+
234
+ const sameYear = start.getUTCFullYear() === end.getUTCFullYear();
235
+ const day = new Intl.DateTimeFormat(locale, DAY);
236
+ const dayAndYear = new Intl.DateTimeFormat(locale, DAY_AND_YEAR);
237
+ const last = (compact && sameYear ? day : dayAndYear).format(end);
238
+
239
+ if (start.getTime() === end.getTime()) {
240
+ return last;
241
+ }
242
+
243
+ return (sameYear ? day : dayAndYear).format(start) + DATES_SEPARATOR + last;
244
+ }