@optionfactory/fml 9.0.0-rc26 → 9.0.0-rc28

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.
@@ -1 +1 @@
1
- {"version":3,"file":"ful.min.mjs","sources":["../src/ful/storage.mjs","../src/ful/events/async.mjs","../src/ful/events/leave.mjs","../src/ful/claims.mjs","../src/ful/descriptions.mjs","../src/ful/timing.mjs","../src/ful/forms/bindings.mjs","../src/ful/forms/field.mjs","../src/ful/forms/form.mjs","../src/ful/forms/input.mjs","../src/ful/forms/temporals.mjs","../src/ful/forms/files.mjs","../src/ful/disclosures/anchors.mjs","../src/ful/forms/select.mjs","../src/ful/forms/radio.mjs","../src/ful/forms/checkbox.mjs","../src/ful/navigation/table.mjs","../src/ful/disclosures/menu-keys.mjs","../src/ful/forms/choice-button.mjs","../src/ful/forms/filters.mjs","../src/ful/disclosures/tooltip.mjs","../src/ful/events/sections.mjs","../src/ful/disclosures/dialog-sections.mjs","../src/ful/disclosures/targets.mjs","../src/ful/disclosures/dialog.mjs","../src/ful/disclosures/drawer.mjs","../src/ful/disclosures/menu.mjs","../src/ful/disclosures/toast.mjs","../src/ful/navigation/tabs.mjs","../src/ful/disclosures/accordion.mjs","../src/ful/navigation/wizard.mjs","../src/ful/plugin.mjs","../src/ful/l10n/en.mjs","../src/ful/l10n/it.mjs","../src/ful/l10n/es.mjs","../src/ful/l10n/fr.mjs"],"sourcesContent":["/**\n * One of the page's storages, holding values encoded as json. The functions\n * do not use `this`, so they keep working when destructured. Reads never\n * throw: where the storage cannot be reached at all (blocked cookies, some\n * embedded or private contexts) a read is a miss and a removal does nothing.\n * @typedef {Object} JsonStorage\n * @property {(k: string, v: any) => void} save stores `JSON.stringify(v)`\n * under `k`, throwing what the encoding or the storage throws: an unreachable\n * storage, a full quota, a value json cannot encode\n * @property {(k: string) => any} load the value stored under `k`, decoded;\n * undefined when there is none, when the storage cannot be reached, or when the\n * stored text is not json, in which case the entry is also removed\n * @property {(k: string) => void} remove removes the entry under `k`\n * @property {(k: string) => any} pop what `load` answers for `k`, removing the\n * entry\n */\n/**\n * One of the page's storages holding values beside a revision.\n * @typedef {Object} VersionedJsonStorage\n * @property {(key: string, revision: string, data: any) => void} save stores\n * `data` with `revision` under `key`, throwing what `JsonStorage.save` throws\n * @property {(key: string, revision: string) => any} load the data stored under\n * `key` when it was saved with this exact revision; otherwise undefined, and the\n * entry is removed, whether it holds another revision, holds no revision at\n * all, or is missing\n */\n/**\n * @param {() => globalThis.Storage} backing called on every operation, so an\n * unreachable storage fails that operation rather than the module's load\n * @returns {JsonStorage}\n */\nconst storage = (backing) => {\n const remove = (k) => {\n try {\n backing().removeItem(k);\n } catch {}\n };\n const load = (k) => {\n let got;\n try {\n got = backing().getItem(k);\n } catch {\n return undefined;\n }\n if (got === null) {\n return undefined;\n }\n try {\n return JSON.parse(got);\n } catch {\n remove(k);\n return undefined;\n }\n };\n const save = (k, v) => {\n backing().setItem(k, JSON.stringify(v));\n };\n const pop = (k) => {\n const decoded = load(k);\n remove(k);\n return decoded;\n };\n return { save, load, remove, pop };\n};\n\n/**\n * @param {JsonStorage} store\n * @returns {VersionedJsonStorage}\n */\nconst versioned = (store) => ({\n save(key, revision, data) {\n store.save(key, { revision, data });\n },\n load(key, revision) {\n const stored = store.load(key);\n if (stored == null || typeof stored !== 'object' || stored.revision !== revision) {\n store.remove(key);\n return undefined;\n }\n return stored.data;\n },\n});\n\n/** `localStorage`, holding json. */\nconst LocalStorage = storage(() => localStorage);\n/** `sessionStorage`, holding json. */\nconst SessionStorage = storage(() => sessionStorage);\n/** `localStorage`, holding json beside a revision. */\nconst VersionedLocalStorage = versioned(LocalStorage);\n/** `sessionStorage`, holding json beside a revision. */\nconst VersionedSessionStorage = versioned(SessionStorage);\n\nexport { LocalStorage, VersionedLocalStorage, SessionStorage, VersionedSessionStorage };\n","/**\n * @typedef {Object} AsyncExtension\n * @property {Promise<any>[]} promises one per `asyncOn` listener the event\n * reached, in the order they ran\n * @typedef {Event & { async?: AsyncExtension }} AsyncEvent\n */\n/**\n * Dispatching an event and waiting for what its listeners answer. A listener\n * registered through `asyncOn` attaches its promise to the event, and\n * `fireAsync` resolves once they have all settled: `broadcast` collects every\n * answer, `pipeline` allows at most one, `delegate` requires exactly one.\n */\nclass AsyncEvents {\n /**\n * Dispatches `evt` on `el` synchronously, then waits for the answers of the\n * `asyncOn` listeners it reached, on `el` or, for a bubbling event, on its\n * ancestors. Listeners added with a plain `addEventListener` run but are not\n * awaited. In `broadcast` mode, the default, it resolves with every answer\n * in the order the listeners ran, an empty array when none did. In\n * `pipeline` mode it accepts at most one listener and resolves with its\n * answer, or undefined when none ran. In `delegate` mode it requires exactly\n * one listener and resolves with its answer.\n * @param {HTMLElement} el the element to dispatch on\n * @param {AsyncEvent} evt the event to dispatch\n * @param {{mode?: 'broadcast' | 'pipeline' | 'delegate'}} [options]\n * @returns {Promise<any>} the answer or answers as the mode describes\n * @throws what the first answer to fail threw or rejected with; or an\n * Error naming the event and the mode when `pipeline` reached more than one\n * listener or `delegate` did not reach exactly one, in which case the\n * listeners have already run and their outcome is discarded. Both arrive as\n * the rejection of the returned promise.\n */\n static async fireAsync(el, evt, options) {\n el.dispatchEvent(evt);\n const promises = evt.async?.promises ?? [];\n const mode = options?.mode ?? 'broadcast';\n if ((mode === 'pipeline' && promises.length > 1) || (mode === 'delegate' && promises.length !== 1)) {\n Promise.all(promises).catch(() => {});\n throw new Error(\n mode === 'pipeline'\n ? `[AsyncEvents] Event \"${evt.type}\" is configured in 'pipeline' mode and expects at most one async listener, but ${promises.length} listeners were triggered on this element.`\n : `[AsyncEvents] Event \"${evt.type}\" is configured in 'delegate' mode and requires exactly one async listener, but ${promises.length} were registered.`,\n );\n }\n return mode === 'broadcast' ? Promise.all(promises) : Promise.resolve(promises[0]);\n }\n\n /**\n * Adds a listener whose answer `fireAsync` can await. When the event\n * reaches it, the listener attaches a promise to `evt.async.promises`,\n * creating the list when it is the first, then calls `fn` with the event;\n * the promise settles with what `fn` returns or throws, awaited when it is a\n * promise. The event is dispatched the usual way, so an event fired with a\n * plain `dispatchEvent` runs `fn` too, and nobody awaits its answer.\n * @param {HTMLElement} el the element to listen on\n * @param {string} type the event type\n * @param {(evt: any) => any} fn called with the event; its result is the answer\n * @param {AddEventListenerOptions} [options] passed to `addEventListener`\n * @returns {EventListener} the listener actually added, which `asyncOff` takes\n */\n static asyncOn(el, type, fn, options) {\n /** @type {(evt: Event) => Promise<void>} */\n const listener = async (event) => {\n const ae = /** @type {AsyncEvent} */ (event);\n if (!ae.async) {\n ae.async = { promises: [] };\n }\n const { promise, resolve, reject } = Promise.withResolvers();\n ae.async.promises.push(promise);\n try {\n resolve(await fn(ae));\n } catch (e) {\n reject(e);\n }\n };\n\n el.addEventListener(type, listener, options);\n return listener;\n }\n\n /**\n * Removes a listener added by `asyncOn`.\n * @param {HTMLElement} el the element it listens on\n * @param {string} type the event type it was added for\n * @param {EventListener} listener what `asyncOn` returned, not the `fn` given to it\n * @param {EventListenerOptions} [options] passed to `removeEventListener`\n * @returns {void}\n */\n static asyncOff(el, type, listener, options) {\n el.removeEventListener(type, listener, options);\n }\n /**\n * Assigns `fireAsync(evt, options)`, `asyncOn(type, fn, options)` and\n * `asyncOff(type, listener, options)` onto each class's prototype, each\n * calling the static of the same name with the instance as the element.\n * Members of those names already on the prototype are overwritten.\n * @param {...Function} classes the classes to extend\n * @returns {void}\n */\n static mixInto(...classes) {\n for (const k of classes) {\n Object.assign(k.prototype, {\n /**\n * @this {HTMLElement}\n * @param {AsyncEvent} evt\n * @param {{mode?: 'broadcast' | 'pipeline' | 'delegate'}} [options]\n * @returns {Promise<any>}\n */\n async fireAsync(evt, options) {\n return await AsyncEvents.fireAsync(this, evt, options);\n },\n\n /**\n * @this {HTMLElement}\n * @param {string} type\n * @param {(evt: any) => any} fn\n * @param {AddEventListenerOptions} [options]\n * @returns {EventListener}\n */\n asyncOn(type, fn, options) {\n return AsyncEvents.asyncOn(this, type, fn, options);\n },\n\n /**\n * @this {HTMLElement}\n * @param {string} type\n * @param {EventListener} listener\n * @param {EventListenerOptions} [options]\n * @returns {void}\n */\n asyncOff(type, listener, options) {\n AsyncEvents.asyncOff(this, type, listener, options);\n },\n });\n }\n }\n}\n\nexport { AsyncEvents };\n","/**\n * Asks before the page is left, through the browser's own `beforeunload`\n * prompt.\n */\nclass PageLeave {\n /**\n * Asks before the page is left while `isDirty()` answers true, until\n * `signal` aborts. The browser words the prompt, and asks only once the\n * user has interacted with the page.\n * @param {() => boolean} isDirty\n * @param {AbortSignal} [signal]\n */\n static guard(isDirty, signal) {\n window.addEventListener(\n 'beforeunload',\n (evt) => {\n if (isDirty()) {\n evt.preventDefault();\n }\n },\n { signal },\n );\n }\n}\n\nexport { PageLeave };\n","/**\n * A hold on one generation of a `Claims`: `stale` turns true once a later\n * `take()` or `invalidate()` on it starts a newer generation.\n * @typedef {{ readonly stale: boolean }} Claim\n */\n/**\n * The generations of claims over one contended resource. Every take() starts a\n * new generation, superseding every claim before it, and a holder asks its\n * claim `stale` before painting chrome, storing state or throwing towards a\n * caller: a superseded outcome owns nothing. hold() joins the current\n * generation without superseding it (a fetch that any later reconfiguration\n * must detach), and invalidate() supersedes without claiming (a hide ending\n * every pending show). One Claims per contended resource: a component whose\n * dropdown, value labels and loader configuration contend separately holds one\n * each.\n */\nclass Claims {\n #generation = 0;\n /**\n * Starts a new generation, superseding every earlier claim, and holds it.\n * @returns {Claim}\n */\n take() {\n ++this.#generation;\n return this.hold();\n }\n /**\n * Holds the current generation without superseding anything.\n * @returns {Claim}\n */\n hold() {\n const held = this.#generation;\n const claims = this;\n return {\n /** true once a later take() or invalidate() superseded this claim */\n get stale() {\n return held !== claims.#generation;\n },\n };\n }\n /**\n * Supersedes every claim without holding a new one.\n * @returns {void}\n */\n invalidate() {\n ++this.#generation;\n }\n}\n\nexport { Claims };\n","/**\n * Something that adds elements to the accessible description of the control it\n * owns, such as a field: `describedBy(el)` adds `el` to the control's\n * `aria-describedby` and answers whether it did.\n * @typedef {{ describedBy(el: HTMLElement): boolean }} Describable\n */\n\n/**\n * The nearest ancestor of `el` that has a `describedBy` method. Content\n * slotted inside a field does not write the control's `aria-describedby`\n * itself: once it has something to offer, it hands the element carrying the\n * words to the `describedBy` of the ancestor this answers.\n * @param {Element} el\n * @returns {(Element & Describable) | null} null when no ancestor has one\n */\nconst describable = (el) => {\n for (let at = el.parentElement; at; at = at.parentElement) {\n if (typeof (/** @type {any} */ (at).describedBy) === 'function') {\n return /** @type {any} */ (at);\n }\n }\n return null;\n};\n\nexport { describable };\n","/**\n * Sleeping, debouncing and throttling. `debounce` and `throttle` both return\n * the wrapped function together with an abort function, which cancels the call\n * pending and leaves the wrapped function working.\n */\nclass Timing {\n /**\n * @param {number} ms\n * @returns {Promise<void>} resolving after `ms` milliseconds\n */\n static sleep(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n /**\n * Collapses a burst of calls into one call of `func`, a burst ending once\n * `timeoutMs` pass without a call. By default `func` is called at the end\n * of the burst with the arguments of its last call. With `immediate` it is\n * called at the first call of a burst, with that call's arguments, and not\n * at the end. Without `immediate`, a call the wrapped function receives\n * from inside `func` starts a new burst.\n * @param {number} timeoutMs\n * @param {(...args: any[]) => any} func\n * @param {{ immediate?: boolean }} [options]\n * @returns {[(...args: any[]) => void, () => void]} the wrapped function\n * and the abort function\n */\n static debounce(timeoutMs, func, options) {\n const immediate = options?.immediate ?? false;\n let tid = /** @type {number | null} */ (null);\n let args = [];\n let previousTimestamp = 0;\n\n const later = () => {\n const elapsed = performance.now() - previousTimestamp;\n if (timeoutMs > elapsed) {\n tid = setTimeout(later, timeoutMs - elapsed);\n return;\n }\n tid = null;\n if (!immediate) {\n func(...args);\n }\n if (tid === null) {\n args = [];\n }\n };\n\n const debounced = (...called) => {\n args = called;\n previousTimestamp = performance.now();\n if (tid === null) {\n tid = setTimeout(later, timeoutMs);\n if (immediate) {\n func(...args);\n }\n }\n };\n const abort = () => {\n clearTimeout(tid ?? undefined);\n tid = null;\n args = [];\n };\n return [debounced, abort];\n }\n /**\n * Calls `func` at most once per `timeoutMs`, always with the arguments of\n * the latest call. With `leading`, on by default, a call arriving once the\n * interval since the previous call of `func` has passed calls it at once;\n * without it, the first call only starts the interval. With `trailing`, on\n * by default, a call arriving inside the interval schedules `func` for the\n * interval's end; without it, such a call is dropped.\n * @param {number} timeoutMs\n * @param {(...args: any[]) => any} func\n * @param {{ leading?: boolean, trailing?: boolean }} [options]\n * @returns {[(...args: any[]) => void, () => void]} the wrapped function\n * and the abort function\n */\n static throttle(timeoutMs, func, options) {\n const leading = options?.leading ?? true;\n const trailing = options?.trailing ?? true;\n let tid = /** @type {number | null} */ (null);\n let args = [];\n let previousTimestamp = 0;\n\n const later = () => {\n previousTimestamp = leading ? performance.now() : 0;\n tid = null;\n func(...args);\n if (tid === null) {\n args = [];\n }\n };\n const throttled = (...called) => {\n const now = performance.now();\n if (!previousTimestamp && !leading) {\n previousTimestamp = now;\n }\n const remaining = previousTimestamp === 0 ? 0 : timeoutMs - (now - previousTimestamp);\n args = called;\n if (remaining <= 0 || remaining > timeoutMs) {\n if (tid !== null) {\n clearTimeout(tid);\n tid = null;\n }\n previousTimestamp = now;\n func(...args);\n if (tid === null) {\n args = [];\n }\n } else if (tid === null && trailing) {\n tid = setTimeout(later, remaining);\n }\n };\n const abort = () => {\n clearTimeout(tid ?? undefined);\n tid = null;\n args = [];\n };\n return [throttled, abort];\n }\n}\n\nexport { Timing };\n","/**\n * Moves values between a form's named controls and a nested object, and pins\n * problems onto the controls they name. Works on any native form, not only\n * the one inside a `ful-form`. Every method reads the controls through\n * `form.elements`, so a control in the subtree that belongs to another form\n * (a nested form, a `form` attribute pointing elsewhere) is never read,\n * written or marked.\n */\nclass Bindings {\n /**\n * Flattens a nested object into dotted keys, array indexes becoming numeric\n * segments (`a.0.b`). It does not descend below a key that `stops` names, so\n * with a field named `address` the whole object is kept under `address`,\n * while with one named `address.city` the leaf is kept under `address.city`.\n * A null value is kept as a leaf.\n * @param {{ [x: string]: any; }} obj\n * @param {string} prefix prepended to every key, `''` at the root\n * @param {Set<string>} stops the dotted keys to keep whole\n * @returns {{ [x: string]: any; }} a flat object keyed by dotted path\n */\n static flatten(obj, prefix, stops) {\n return Object.keys(obj).reduce((acc, k) => {\n const pre = prefix.length ? `${prefix}.${k}` : k;\n if (!stops.has(pre) && typeof obj[k] === 'object' && obj[k] !== null) {\n Object.assign(acc, Bindings.flatten(obj[k], pre, stops));\n } else {\n acc[pre] = obj[k];\n }\n return acc;\n }, {});\n }\n\n static #FORBIDDEN = new Set(['__proto__', 'prototype', 'constructor']);\n /**\n * Writes a value into an object at a dotted path, creating the intermediate\n * objects and arrays the path implies: a numeric segment makes its container\n * an array. Brackets are not parsed, so `a[0]` is a plain key.\n *\n * An undefined value declares the path without filling it: an entry already\n * there is kept, a missing one is set to null. A scalar or a null left on the\n * path by a shorter overlapping name (`a` written before `a.b`) is replaced\n * by a container, so the longer name wins whichever order they arrive in.\n * @param {any} result the object or array to write into\n * @param {string} path a dotted name such as `a.b` or `a.0.b`\n * @param {any} value\n * @returns {any} the root written into, to be used in place of `result`: a\n * new array replaces it when the first segment is numeric and `result` is\n * not an array\n * @throws {Error} when a segment is `__proto__`, `prototype` or `constructor`,\n * before anything is written\n */\n static providePath(result, path, value) {\n const keys = path.split('.').map((k) => (/^[0-9]+$/.test(k) ? +k : k));\n for (const key of keys) {\n if (Bindings.#FORBIDDEN.has(/** @type any */ (key))) {\n throw new Error(`unsupported name segment '${key}' in '${path}'`);\n }\n }\n let current = result ?? {};\n let previous = /** @type {any} */ (null);\n for (let i = 0; ; ++i) {\n const ckey = keys[i];\n const pkey = keys[i - 1];\n if (Number.isInteger(ckey) && !Array.isArray(current)) {\n if (previous !== null) {\n previous[pkey] = current = [];\n } else {\n result = current = [];\n }\n }\n if (i === keys.length - 1) {\n current[ckey] = value !== undefined ? value : ckey in current ? current[ckey] : null;\n return result;\n }\n if (typeof current[ckey] !== 'object' || current[ckey] === null) {\n current[ckey] = {};\n }\n previous = current;\n current = current[ckey];\n }\n }\n /**\n * Reads one control's value by its kind. The kind is read from the `type`\n * attribute and the tag, so a ful element answers its own `value`.\n *\n * - a radio answers its `value` when checked and undefined otherwise\n * - a checkbox answers its `checked` state\n * - `data-ful-bind-type=\"boolean\"` decodes the value: a radio answers\n * whether its value is `'true'`, any other control answers null when\n * blank and whether its value is `'true'` otherwise\n * - a multiple select answers the array of its selected values\n * - a native input, select or textarea answers null when blank\n * - anything else answers its `value` unchanged\n * @param {Element & {dataset?: any} & {checked?: boolean} & {value?: any}} el\n * @returns {any} the value; undefined for an unchecked radio\n */\n static extract(el) {\n if (el.getAttribute('type') === 'radio') {\n if (!el.checked) {\n return undefined;\n }\n return el.dataset.fulBindType === 'boolean' ? el.value === 'true' : el.value;\n }\n if (el.getAttribute('type') === 'checkbox') {\n return el.checked;\n }\n if (el.dataset.fulBindType === 'boolean') {\n return !el.value ? null : el.value === 'true';\n }\n if (el.tagName === 'SELECT' && /** @type {HTMLSelectElement} */ (el).multiple) {\n return Array.from(/** @type {HTMLSelectElement} */ (el).selectedOptions).map((o) => o.value);\n }\n if (el.tagName === 'INPUT' || el.tagName === 'SELECT' || el.tagName === 'TEXTAREA') {\n return el.value === '' || el.value === undefined ? null : el.value;\n }\n return el.value;\n }\n\n /**\n * @param {Element & {type?: string}} el\n */\n static #submits(el) {\n return el.type === 'submit' || el.type === 'reset' || el.type === 'button';\n }\n /**\n * Reads the form's named controls into a nested object, the dotted names\n * deciding its shape (see `providePath`) and each value read by `extract`.\n * Controls are read in document order, so of two overlapping names the\n * later one decides. A control is skipped when it has no `name`, when it\n * matches `:disabled` (its own `disabled` or a disabled fieldset's), or when\n * it is a submit, reset or plain button. The submitter is the exception to\n * both of the last two: it contributes its name and value even while\n * disabled.\n * @param {HTMLFormElement} form\n * @param {HTMLElement} [submitter] the button that submitted, when there is one\n * @returns {any} the nested values; an array when the first segment of a name is numeric\n * @throws {Error} when a name has a segment `providePath` refuses\n */\n static extractFrom(form, submitter) {\n let result = {};\n for (const el of form.elements) {\n if (!el.hasAttribute('name')) {\n continue;\n }\n if (Bindings.#submits(el) && el !== submitter) {\n continue;\n }\n if (el.matches(':disabled') && el !== submitter) {\n continue;\n }\n result = Bindings.providePath(\n result,\n /** @type {string} */ (el.getAttribute('name')),\n Bindings.extract(el),\n );\n }\n return result;\n }\n\n /**\n * Writes a value into one control, the inverse of `extract`.\n *\n * - a radio is checked when `raw` is not null and its `value` attribute\n * equals `String(raw)`, so a number or a boolean matches its text\n * - a checkbox takes `raw` as its `checked` state\n * - a multiple select selects the options whose value is in `raw`, compared\n * as text: an array selects each entry, a scalar selects one, null selects none\n * - anything else takes `raw` as its `value`\n * @param {Element & {dataset?: any} & {checked?: boolean} & {value?: any}} el\n * @param {any} raw\n */\n static mutate(el, raw) {\n if (el.getAttribute('type') === 'radio') {\n el.checked = raw != null && el.getAttribute('value') === String(raw);\n return;\n }\n if (el.getAttribute('type') === 'checkbox') {\n el.checked = raw;\n return;\n }\n if (el.tagName === 'SELECT' && /** @type {HTMLSelectElement} */ (el).multiple) {\n const values = Array.isArray(raw) ? raw.map(String) : raw == null ? [] : [String(raw)];\n Array.from(/** @type {HTMLSelectElement} */ (el).options).forEach((o) => {\n o.selected = values.includes(o.value);\n });\n return;\n }\n el.value = raw;\n }\n\n /**\n * Writes a nested object onto the form's named controls: the object is\n * flattened with the control names as stops (see `flatten`), and each key\n * is written by `mutate` into every control carrying exactly that name. A\n * key naming no control is ignored, and a control the object does not name\n * keeps its value.\n * @param {HTMLFormElement} form\n * @param {{ [x: string]: any; }} values\n */\n static mutateIn(form, values) {\n const named = Bindings.#named(form);\n for (const [flattenedKey, value] of Object.entries(Bindings.flatten(values, '', new Set(named.keys())))) {\n for (const el of named.get(flattenedKey) ?? []) {\n Bindings.mutate(el, value);\n }\n }\n }\n\n /**\n * @param {HTMLFormElement} form\n * @returns {Map<string, any[]>} the controls of `form.elements` grouped by name\n */\n static #named(form) {\n const named = new Map();\n for (const el of form.elements) {\n const name = el.getAttribute('name');\n if (!name) {\n continue;\n }\n const bucket = named.get(name);\n if (bucket) {\n bucket.push(el);\n } else {\n named.set(name, [el]);\n }\n }\n return named;\n }\n\n /**\n * Shows problems on the form, replacing whatever the previous call showed.\n *\n * Every named control's custom validity is first cleared. A problem whose\n * `type` is `FIELD_ERROR` or `INVALID_FORMAT` and whose `context` is not\n * empty is pinned to a control: brackets in the context are turned into\n * dots (`users[0].name` becomes `users.0.name`), and the longest leading\n * part of it that names a control wins, so an exact field takes the problem\n * alone and a composite field named for a prefix catches the problems of its\n * subtree. Each control of that name gets `setCustomValidity(reason, rest)`,\n * `rest` being the remainder of the path (`''` on an exact match) that a\n * composite can use to route the problem to an inner control.\n *\n * A control counts only when it can show a problem, through a\n * `setCustomValidity` of its own: a form-associated element that has none is\n * skipped, so its problems fall to a shorter prefix or to the banner instead\n * of being dropped.\n *\n * Every other problem, and a field problem naming no control, is shown in\n * each `ful-errors` banner of the form: the banner gets `role=\"alert\"`, is\n * revealed and holds the reasons one per line. With no such problem the\n * banner is emptied and hidden.\n *\n * Each `ful-field-error` of the form gets `aria-live=\"off\"` when\n * `scrollOnError` is set, since focusing the field announces its error, and\n * `aria-live=\"polite\"` otherwise. With `scrollOnError` and at least one\n * problem, the topmost `:invalid` control is focused.\n *\n * A banner or `ful-field-error` belongs to the nearest enclosing form, so\n * those of a nested form are left alone.\n * @param {HTMLFormElement} form\n * @param {{ type: string; context?: string | null; reason: string; }[]} es the problems, as an httpc `Failure` carries them\n * @param {boolean} scrollOnError\n */\n static errors(form, es, scrollOnError) {\n const ofForm = (el) => el.closest('form') === form;\n Array.from(form.querySelectorAll('ful-field-error'))\n .filter(ofForm)\n .forEach((el) => {\n el.setAttribute('aria-live', scrollOnError ? 'off' : 'polite');\n });\n const pinned = (e) => (e.type === 'FIELD_ERROR' || e.type === 'INVALID_FORMAT') && e.context;\n const fieldErrors = es.filter(pinned);\n const globalErrors = es.filter((e) => !pinned(e));\n const named = Bindings.#named(form);\n for (const targets of named.values()) {\n targets.forEach((el) => {\n el.setCustomValidity?.('');\n });\n }\n const unmatched = [];\n fieldErrors.forEach((e) => {\n const name = /** @type {string} */ (e.context).replace(/\\[/g, '.').replace(/\\]\\./g, '.').replace(/\\]/g, '');\n const parts = name.split('.');\n for (let i = parts.length; i !== 0; --i) {\n const prefix = parts.slice(0, i).join('.');\n const targets = (named.get(prefix) ?? []).filter((el) => typeof el.setCustomValidity === 'function');\n if (targets.length === 0) {\n continue;\n }\n const context = parts.slice(i).join('.');\n targets.forEach((input) => {\n input.setCustomValidity?.(e.reason, context);\n });\n return;\n }\n unmatched.push(e);\n });\n const bannered = [...globalErrors, ...unmatched];\n form.querySelectorAll('ful-errors').forEach((el) => {\n if (!ofForm(el)) {\n return;\n }\n const hel = /** @type {HTMLElement} */ (el);\n el.setAttribute('role', 'alert');\n if (bannered.length === 0) {\n el.replaceChildren();\n el.setAttribute('hidden', '');\n return;\n }\n el.removeAttribute('hidden');\n hel.innerText = bannered.map((e) => e.reason).join('\\n');\n });\n if (es.length === 0 || !scrollOnError) {\n return;\n }\n /** @type {HTMLElement[]} */ (Array.from(form.elements))\n .filter((el) => el.matches(':invalid'))\n .sort((a, b) => a.getBoundingClientRect().y - b.getBoundingClientRect().y)[0]\n ?.focus();\n }\n}\n\nexport { Bindings };\n","import { Attributes, ParsedElement } from '../../ftl/index.mjs';\n\n/**\n * The base of every form-associated ful field: a form-associated custom element\n * carrying the validity protocol, the field error live region, focus\n * delegation, the label chrome and the disabled, readonly and required claims.\n *\n * A subclass owns its template, its value semantics and its change events. It\n * implements `_build(conf)`, which builds its dom and returns the pieces the\n * base drives (see `_build`), and the `value` pair. The base wires the pieces,\n * mounts the fragment and applies the declared state. Nothing in the base is\n * there to be called from a subclass's build.\n *\n * The claim setters, the validity protocol and the aria wiring all act on the\n * pieces, so a field with no native control returns a focusable piece of its\n * own chrome as the control. The claim getters and `focus()` are the only\n * members that tolerate a not yet rendered element; the other members need the\n * pieces and so work only after the render.\n *\n * The inner controls carry `form=\"\"`, so the host is the only element the form\n * sees. Enter pressed in an inner `<input>` of any type but `file`, `button`,\n * `submit`, `reset` and `image` submits the field's form through\n * `_requestSubmit()`, as Enter in a native input would. It does not when a\n * listener inside the field already called `preventDefault()` on the keydown,\n * while an input method is composing, or when the input is still associated\n * with the form itself and so submits on its own.\n */\nclass Field extends ParsedElement {\n static formAssociated = true;\n /**\n * The claim attributes and the value, observed so that every field,\n * including a custom one that never lists them, keeps them live after the\n * upgrade. A subclass's own `static observed` adds to this list. The value\n * is read with the string mapper; a field with another vocabulary redeclares\n * it with its own (`value:bool`, `value:csv`, `value:json`).\n * @type {string[]}\n */\n static observed = ['disabled:presence', 'readonly:presence', 'required:presence', 'value'];\n /**\n * The role set on the element internals at construction. A field whose host\n * is the widget itself overrides it, as `RadioGroup` does with `'radiogroup'`.\n * @type {string}\n */\n static ROLE = 'presentation';\n #control;\n #pendingFocus = /** @type {FocusOptions | null} */ (null);\n #described;\n #descriptions = [];\n #errorId = null;\n #fieldError;\n #claims;\n #announces;\n #also = [];\n /** Sets the internals' role from the subclass's `static ROLE`. */\n constructor() {\n super();\n this.internals.role = /** @type {typeof Field} */ (this.constructor).ROLE;\n }\n #mirrors() {\n return [this.#claims ?? this.#control, ...this.#also].filter((el) => el);\n }\n /**\n * @param {{fragment: any, control: any, error?: any, label?: any, described?: any,\n * claims?: any, announces?: any, freeze?: any, also?: any[]}} pieces\n */\n #wire({\n fragment,\n control,\n error,\n label = null,\n described = null,\n claims = null,\n announces = control,\n freeze = null,\n also = [],\n }) {\n this.#control = control;\n this.#fieldError = error;\n this.#claims = claims;\n this.#announces = announces;\n this.#also = also;\n if (freeze) {\n freeze.addEventListener(\n 'click',\n (evt) => {\n if (this.readonly) {\n evt.preventDefault();\n }\n },\n true,\n );\n }\n this.#described = described ?? control;\n if (error) {\n error.id = error.id || Attributes.uid('ful-field-error');\n this.#errorId = error.id;\n }\n this.#describe();\n if (label) {\n Field.#name(this, label, control);\n }\n this.addEventListener('keydown', (evt) => {\n if (evt.key !== 'Enter' || evt.defaultPrevented || evt.isComposing) {\n return;\n }\n const target = /** @type {HTMLInputElement} */ (evt.target);\n if (target.form === this.form || !Field.#submitsOnEnter(target)) {\n return;\n }\n this._requestSubmit();\n });\n this.replaceChildren(fragment);\n if (this.#pendingFocus !== null) {\n const options = this.#pendingFocus;\n this.#pendingFocus = null;\n control.focus(options);\n }\n }\n /**\n * @param {EventTarget} el\n * @returns {boolean} whether Enter in `el` submits a form on the platform\n */\n static #submitsOnEnter(el) {\n return el instanceof HTMLInputElement && !['file', 'button', 'submit', 'reset', 'image'].includes(el.type);\n }\n /**\n * Adds an element to the accessible description of the field and answers\n * whether the field took it.\n *\n * The field takes a description before its own render as readily as after:\n * one handed over early is written as soon as the field has rendered, so the\n * caller does not need to know which of the two upgraded first. The element\n * is given an id (`ful-described-*`) when it has none, is added once however\n * often it is offered, and is referenced from the `aria-describedby`\n * attribute of the `described` piece (the control by default). The\n * descriptions come in the order they were offered, the error region always\n * last.\n *\n * Pass the element that carries the words rather than a wrapper around it:\n * a hidden element is part of a description only where it is referenced\n * directly, so a popover that is closed until opened must be passed itself.\n *\n * This is the field's half of the description protocol; `describable` in\n * `ful/descriptions.mjs` is the half the content uses to find the field.\n * @param {HTMLElement | null | undefined} el\n * @returns {boolean} false only when `el` is missing\n */\n describedBy(el) {\n if (!el) {\n return false;\n }\n if (!el.id) {\n el.id = Attributes.uid('ful-described');\n }\n if (!this.#descriptions.includes(el.id)) {\n this.#descriptions.push(el.id);\n }\n this.#describe();\n return true;\n }\n #describe() {\n if (!this.#described) {\n return;\n }\n const ids = [...this.#descriptions, this.#errorId].filter((id) => id);\n if (ids.length) {\n this.#described.setAttribute('aria-describedby', ids.join(' '));\n }\n }\n /**\n * Moves the focus to the `control` piece. Asked before the render, the\n * request is kept (the last one wins) and applied once the control is\n * mounted.\n * @param {FocusOptions} [options]\n */\n focus(options) {\n if (this.#control) {\n this.#control.focus(options);\n return;\n }\n this.#pendingFocus = options ?? {};\n }\n /**\n * Clears or reports one validation problem. A message sets a custom error on\n * the element internals, which makes the host match `:invalid`, renders the\n * message into the `error` piece and sets `aria-invalid=\"true\"` on the\n * `announces` piece, or on the `control` when the field announces nowhere.\n * An empty or missing message clears all three.\n *\n * Validation is the server's: the submit is sent regardless, and the form's\n * error mapping calls this with the problems that come back. It calls the\n * field with the most specific name a problem's context reaches and passes\n * the rest of the path as `context`. The base ignores `context`; a composite\n * field owning a whole subtree overrides this to route the message to the\n * inner control the path names.\n *\n * Needs the render: before it there is no error region to write to.\n * @param {string} [error] the message, empty or missing to clear\n * @param {string} [context] the path below this field's name, '' on an exact match\n */\n setCustomValidity(error, context) {\n Attributes.set(this.#announces ?? this.#control, 'aria-invalid', error ? 'true' : null);\n if (!error) {\n this.internals.setValidity({});\n this.#fieldError.innerText = '';\n return;\n }\n this.internals.setValidity({ customError: true }, ' ');\n this.#fieldError.innerText = error;\n }\n /**\n * The form the platform associated the field with, as a native control's\n * own `form`.\n * @returns {HTMLFormElement | null} null outside a form\n */\n get form() {\n return this.internals.form;\n }\n /**\n * Submits the associated form with `requestSubmit`, so constraint validation\n * and the `submit` event run as for a user's submit. The submitter is the\n * first enabled `button` or `input` of type `submit` in the form whose own\n * `form` is that form; with none the form is submitted without one. Does\n * nothing outside a form.\n */\n _requestSubmit() {\n const form = this.form;\n if (!form) {\n return;\n }\n const candidates = /** @type {NodeListOf<HTMLButtonElement|HTMLInputElement>} */ (\n form.querySelectorAll('button:not(:disabled), input:not(:disabled)')\n );\n form.requestSubmit([...candidates].find((el) => el.type === 'submit' && el.form === form));\n }\n /**\n * Dispatches the field's `change` event on the host: bubbling, not\n * cancelable, with `{ value: this.value, ...extras }` as the detail. Call it\n * for a change the user made. Every field in the library announces through this method and\n * passes no `value` key in `extras`, so a listener can rely on\n * `el.value === evt.detail.value`. The extras are spread after `value`, so a\n * `value` key among them would replace it.\n * @param {Record<string, any>} [extras] further detail keys beside `value`\n */\n _notifyChange(extras = {}) {\n this.dispatchEvent(\n new CustomEvent('change', {\n bubbles: true,\n cancelable: false,\n detail: { value: this.value, ...extras },\n }),\n );\n }\n static #LABELABLE = new Set(['BUTTON', 'INPUT', 'METER', 'OUTPUT', 'PROGRESS', 'SELECT', 'TEXTAREA']);\n /**\n * @param {Field} field\n * @param {HTMLElement} label\n * @param {HTMLElement} control\n */\n static #name(field, label, control) {\n const labelable =\n Field.#LABELABLE.has(control.tagName) && control.getAttribute('type') !== 'hidden';\n if (!labelable) {\n if (!label.id) {\n label.id = Attributes.uid('ful-label');\n }\n control.setAttribute('aria-labelledby', label.id);\n label.addEventListener('click', () => field.focus());\n return;\n }\n if (!control.id) {\n control.id = Attributes.uid('ful-control');\n }\n label.setAttribute('for', control.id);\n }\n /**\n * Whether the field's own chrome should act on a gesture. Badges, dropzones,\n * menus and labels are not form controls, so the platform does not disable\n * them: every handler on them asks this first. False while the host matches\n * `:disabled`, which covers a disabled `<fieldset>` ancestry as well as the\n * claim, or while the readonly claim holds.\n * @returns {boolean}\n */\n _interactive() {\n return !this.matches(':disabled') && !this.readonly;\n }\n /**\n * The field's value, `null` when empty. Every concrete field overrides the\n * pair with its own semantics; the form extraction, `values =` assignment,\n * the `change` detail and `formResetCallback` all go through it. The base\n * pair reads `undefined` and ignores writes.\n * @type {any}\n */\n get value() {\n return undefined;\n }\n set value(v) {}\n /**\n * Restores the declared value on a form reset, as a native control restores\n * its markup default: the current `value` attribute is decoded with the\n * element's own mapper and written through the `value` setter. A field whose\n * value is not attribute backed overrides this.\n */\n formResetCallback() {\n this.value = this.unmarshal('value', this.getAttribute('value'));\n }\n /**\n * The field's own disabled claim, which follows a native form control:\n *\n * - the `disabled` attribute on the host is the claim. Only the author writes\n * or removes it, in markup or through this property; the library never\n * claims on a form's or fieldset's behalf. A field declared disabled inside\n * a disabled `<fieldset>` stays disabled when the fieldset is re-enabled.\n * - the effective state is the claim or a disabled `<fieldset>` ancestry:\n * `:disabled` matches both, and a disabled field is left out of the\n * submitted values.\n * - the property reads the claim only: a field disabled by its ancestry reads\n * `false` while `matches(':disabled')` is true. Removing the claim inside a\n * disabled fieldset does not enable the field.\n * - writing it sets or removes the `disabled` attribute on the `claims`\n * piece (the control by default) and on every `also` control. The\n * ancestry is never written anywhere: the browser disables those controls\n * as descendants of the fieldset. A subclass setter calls super, then\n * reaches any further controls of its own.\n * @type {boolean}\n */\n get disabled() {\n return this.hasAttribute('disabled');\n }\n set disabled(d) {\n this.reflectTo('disabled', d);\n for (const el of this.#mirrors()) {\n el.toggleAttribute('disabled', d);\n }\n }\n /**\n * The readonly claim, read from the host attribute. Writing it sets\n * `readOnly` on the `claims` piece (the control by default) and on every\n * `also` control, sets `aria-readonly` on the `announces` piece, and\n * reflects the attribute. A text control stays focusable and selectable\n * with only editing off. A field whose control has no usable native\n * `readOnly` names a `freeze` piece, whose clicks are cancelled while the\n * claim holds.\n * @type {boolean}\n */\n get readonly() {\n return this.hasAttribute('readonly');\n }\n set readonly(v) {\n for (const el of this.#mirrors()) {\n el.readOnly = v;\n }\n if (this.#announces) {\n Attributes.set(this.#announces, 'aria-readonly', v ? 'true' : null);\n }\n this.reflectTo('readonly', v);\n }\n /**\n * The required claim, read from the host attribute. Writing it sets\n * `aria-required` on the `announces` piece and reflects the attribute; no\n * native `required` is set, since validation is the server's.\n * @type {boolean}\n */\n get required() {\n return this.hasAttribute('required');\n }\n set required(d) {\n if (this.#announces) {\n Attributes.set(this.#announces, 'aria-required', d ? 'true' : null);\n }\n this.reflectTo('required', d);\n }\n /**\n * Calls `_build(conf)` and wires the pieces it answers. When `_build`\n * returns a promise the pieces are wired once it settles; a field that\n * builds synchronously renders synchronously.\n * @param {{ slots: Record<string, DocumentFragment> | undefined }} conf\n * @returns {void | Promise<void>}\n */\n render(conf) {\n const built = /** @type {any} */ (this._build(conf));\n if (built instanceof Promise) {\n return built.then((pieces) => this.#wire(pieces));\n }\n this.#wire(built);\n return undefined;\n }\n /**\n * Builds the field's dom and answers the pieces the base drives, or a\n * promise of them. The one method a concrete field implements beside its\n * value pair, and the only place its dom is created. A subclass extending\n * another field's build spreads the pieces it answered and overrides the\n * keys it owns.\n *\n * - `fragment` (required) replaces the host's children.\n * - `control` (required) is the focus target of `focus()`. By default it also\n * carries the description, `aria-invalid`, `aria-readonly`,\n * `aria-required`, and the mirrored `disabled` and `readOnly`.\n * - `error` (required) is the live region `setCustomValidity` writes into.\n * It is given an id (`ful-field-error-*`) when it has none and is always\n * the last entry of the description.\n * - `label` names the control. For a labelable control (`button`, `input`\n * other than hidden, `meter`, `output`, `progress`, `select`, `textarea`)\n * the control is given an id when it has none and the label's `for`\n * points at it, so a click on the label does what it does in a plain\n * form. For any other control the label is given an id, the control's\n * `aria-labelledby` points at it, and a click on the label calls `focus()`.\n * - `described` carries `aria-describedby` in place of the control: the\n * host, for a field with no single control to describe.\n * - `claims` receives the mirrored `disabled` and `readOnly` in place of the\n * control, for a wrapper such as a `<fieldset>` the field disables as a\n * whole. Focus and the aria stay on the control.\n * - `announces` carries `aria-readonly`, `aria-required` and `aria-invalid`\n * in place of the control: the host, where the widget role lives there.\n * `null` for a field whose control has no role that accepts\n * `aria-readonly` and `aria-required`; `aria-invalid` then goes on the\n * control.\n * - `freeze` is for a field with no usable native `readOnly`: a capturing\n * click listener on it cancels the default action of every click inside\n * it while the readonly claim holds. It stays focusable and in the\n * accessibility tree.\n * - `also` are further controls that mirror `disabled` and `readOnly`\n * beside the claim target.\n *\n * The pieces are elements the field rendered itself, native controls or\n * wrappers of its own. A ful field is not one: it has no `readOnly`, its\n * host's role takes no aria, and a label's `for` names its host rather than\n * its control. A composite built from ful fields answers the inner field as\n * `control`, which forwards `focus()`, lets it render its own label with\n * `label` and `announces` null, and forwards the claims in its setters,\n * calling super first.\n * @param {{ slots: Record<string, DocumentFragment> | undefined }} conf\n * @returns {any} the pieces, or a promise of them\n * @throws {Error} when the subclass does not implement it\n */\n _build(conf) {\n throw new Error(`${this.constructor.name} must implement _build`);\n }\n}\n\nexport { Field };\n","import { Attributes, Localization, ParsedElement, Rendering } from '../../ftl/index.mjs';\nimport { Failure } from '../../httpc/index.mjs';\nimport { Bindings } from './bindings.mjs';\nimport { AsyncEvents } from '../events/async.mjs';\nimport { PageLeave } from '../events/leave.mjs';\n\n/** Sends a form's request as a json body to a url, mapping the request and the response through the configured mappers. */\nclass RemoteJsonFormLoader {\n #http;\n #url;\n #method;\n #requestMapper;\n #responseMapper;\n /**\n * @param {{ request(method: string, url: string): { json(body: any): { fetch(): Promise<any> } } }} http the `http-client` component\n * @param {string} url\n * @param {string} method\n * @param {(value: any, form: Form) => any} requestMapper\n * @param {(value: any, form: Form) => any} responseMapper\n */\n constructor(http, url, method, requestMapper, responseMapper) {\n this.#http = http;\n this.#url = url;\n this.#method = method;\n this.#requestMapper = requestMapper;\n this.#responseMapper = responseMapper;\n }\n /**\n * @param {any} values\n * @param {Form} form\n * @returns {any} what the request mapper returns\n */\n prepare(values, form) {\n return this.#requestMapper(values, form);\n }\n /**\n * @param {any} request\n * @param {Form} form\n * @returns {Promise<any>} what the client's `fetch()` resolves to: with the\n * library's client, the `Response` of a 2xx status, rejecting with an\n * `HttpClientError` (a `Failure`) otherwise\n */\n async submit(request, form) {\n return await this.#http.request(this.#method, this.#url).json(request).fetch();\n }\n /**\n * @param {any} response\n * @param {Form} form\n * @returns {any} what the response mapper returns\n */\n transform(response, form) {\n return this.#responseMapper(response, form);\n }\n}\n\n/** Submits a form without a request: the request mapper produces the result the response mapper then reads, for a form handled entirely on the page. */\nclass LocalFormLoader {\n #requestMapper;\n #responseMapper;\n /**\n * @param {(value: any, form: Form) => any} requestMapper\n * @param {(value: any, form: Form) => any} responseMapper\n */\n constructor(requestMapper, responseMapper) {\n this.#requestMapper = requestMapper;\n this.#responseMapper = responseMapper;\n }\n /**\n * @param {any} values\n * @param {Form} form\n * @returns {Promise<any>} what the request mapper returns or resolves to\n */\n async prepare(values, form) {\n return await this.#requestMapper(values, form);\n }\n /**\n * Sends nothing.\n * @param {any} request\n * @param {Form} form\n * @param {any} response what a `submit:requested` listener answered\n * @returns {Promise<any>} `response`, unchanged\n */\n async submit(request, form, response) {\n return response;\n }\n /**\n * @param {any} response\n * @param {Form} form\n * @returns {Promise<any>} what the response mapper returns or resolves to\n */\n async transform(response, form) {\n return await this.#responseMapper(response, form);\n }\n}\n\n/**\n * Builds the form's loader from its attributes: a local one when no action is\n * declared, a json post to it otherwise.\n *\n * A component registered under the `loader` attribute replaces this one and\n * must implement three methods, called in this order:\n *\n * - `prepare(values, form)` turns the extracted values into the request to send\n * - `submit(request, form, response)` performs it and returns the response. The\n * third argument is whatever a `submit:requested` listener already answered,\n * which is how a loader with nothing to send returns it unchanged\n * - `transform(response, form)` turns that response into the `response` of the\n * `submit:success` detail\n *\n * A rejection from any of the three is reported as a `submit:failure`.\n */\nclass FormLoader {\n /**\n * The `request-mapper` and `response-mapper` attributes name registry\n * components called as `(value, form)`; each defaults to the identity. A\n * remote loader sends through the `http-client` component, with the\n * `method` attribute or `POST`.\n * @param {Form} el the form submitting\n * @param {unknown} [conf] not read\n * @returns {LocalFormLoader | RemoteJsonFormLoader}\n */\n static create(el, conf) {\n const http = el.component('http-client');\n const requestMapper = el.declared('request-mapper') ? el.component(el.declared('request-mapper')) : (v) => v;\n const responseMapper = el.declared('response-mapper') ? el.component(el.declared('response-mapper')) : (v) => v;\n const url = el.declared('action');\n if (!url) {\n return new LocalFormLoader(requestMapper, responseMapper);\n }\n const method = el.declared('method') ?? 'POST';\n return new RemoteJsonFormLoader(http, url, method, requestMapper, responseMapper);\n }\n}\n\n/**\n * The form owning an element: its `form` property, or `internals.form` for a\n * form-associated element that has none. An element no form can own answers\n * undefined, its internals, which every ParsedElement holds, throwing on a\n * read of `form` unless the element is form-associated.\n * @param {any} el\n * @returns {HTMLFormElement|null|undefined}\n */\nconst ownerOf = (el) =>\n el.form !== undefined ? el.form : el.constructor?.formAssociated ? el.internals?.form : undefined;\n\n/**\n * Moves its children into a native `<form novalidate>`, extracts their values\n * on submit and hands them to a loader, reporting problems through `errors`.\n * Being `novalidate`, the form submits whatever the validity of its fields:\n * the browser does not block a submit on a field still marked invalid.\n *\n * Attributes on the host starting with `form-` are forwarded, without the\n * prefix, to the native form. `autocomplete` is copied onto the native form as\n * well and stays on the host, the fields reading it from either; a\n * `form-autocomplete` has the last word on the native form.\n * `clear-invalid-on-change` clears the custom validity of a field of this form\n * when a `change` event bubbles from it; the field's form is read from its\n * `form` property, or from `internals.form` for a form-associated element\n * that has none. `scroll-on-error` is passed to `Bindings.errors` as\n * `scrollOnError`.\n *\n * A native submit, by a button or by Enter in a field, is stopped and runs\n * `submit` instead.\n *\n * `track-changes` keeps track of the edits not saved yet (see `dirty`), and\n * `guard-leave`, which implies it, asks before the page is left while there\n * are any.\n */\nclass Form extends ParsedElement {\n /** Read once at the upgrade: changing one afterwards has no effect. */\n static attributes = [\n 'action',\n 'method',\n 'loader',\n 'request-mapper',\n 'response-mapper',\n 'clear-invalid-on-change:presence',\n 'scroll-on-error:presence',\n 'autocomplete',\n 'track-changes:presence',\n 'guard-leave:presence',\n ];\n /** The native form holding the fields, created by the render. */\n form;\n /** Builds the native form and moves the element's children into it. */\n render() {\n const form = document.createElement('form');\n this.form = form;\n form.setAttribute('novalidate', '');\n Attributes.set(form, 'autocomplete', this.declared('autocomplete'));\n Attributes.forward('form-', this, form);\n form.replaceChildren(...this.childNodes);\n form.addEventListener('submit', async (e) => {\n e.preventDefault();\n e.stopPropagation();\n await this.submit(e.submitter ?? undefined);\n });\n this.addEventListener(\n 'click',\n (evt) => {\n const target = /** @type Element */ (evt.target);\n if (!target.closest?.('[aria-disabled=\"true\"]')) {\n return;\n }\n evt.preventDefault();\n evt.stopImmediatePropagation();\n },\n true,\n );\n if (this.declared('clear-invalid-on-change')) {\n this.addEventListener('change', (/** @type any */ evt) => {\n if (ownerOf(evt.target) !== this.form) {\n return;\n }\n evt.target.setCustomValidity?.('');\n });\n }\n this.replaceChildren(form);\n this.#tracking = this.declared('track-changes') || this.declared('guard-leave');\n if (!this.#tracking) {\n return;\n }\n this.addEventListener('input', (evt) => this.#touch(evt.target));\n this.addEventListener('change', (evt) => this.#touch(evt.target));\n this.addEventListener('focusin', (evt) => this.#focus(evt.target));\n Rendering.waitForChildren(this)\n .catch(() => undefined)\n .then(() => this.commit());\n this.#guard();\n }\n connectedCallback() {\n super.connectedCallback();\n if (this.#tracking) {\n this.#guard();\n }\n }\n disconnectedCallback() {\n this.#leave?.abort();\n this.#leave = null;\n }\n #submitting = false;\n /**\n * Runs the submit pipeline, with the spinner up for its whole length:\n *\n * 1. builds the loader: the component the `loader` attribute names\n * (`loaders:form` by default), called as `create(form)`\n * 2. extracts the values with `Bindings.extractFrom` and has the loader\n * `prepare` them into the request\n * 3. fires a cancelable `submit` with `{ submitter, values, request }`.\n * Cancelling it ends the submit there, reporting nothing and leaving the\n * problems shown; a listener may replace `values` or `request` on the detail\n * 4. clears the problems shown\n * 5. fires `submit:requested` through `AsyncEvents.fireAsync` in `pipeline`\n * mode: at most one async listener, whose answer is handed to the\n * loader's `submit` as its third argument. A listener may replace\n * `request` on the detail\n * 6. has the loader `submit` the request and `transform` the response\n * 7. under `track-changes`, commits the values extracted at step 2 (see\n * `commit`): an edit made while the submit was in flight stays unsaved\n * 8. fires `submit:success` with `{ submitter, values, request, response }`,\n * `response` being the transformed one\n *\n * Anything thrown from step 1 on, a missing loader or a throwing mapper\n * included, fires `submit:failure` with `{ submitter, values, request,\n * exception }` instead; the returned promise does not reject. A `Failure`\n * has its problems shown through `errors`, anything else is logged with\n * `console.warn`. The `values` of both outcome events are the extracted\n * ones, not a replacement a `submit` listener put on its detail.\n *\n * A call while a submit is in flight returns at once, doing nothing.\n * @param {HTMLElement} [submitter] the button that submitted, if any; it is\n * the only button whose name and value are submitted\n * @returns {Promise<boolean>} settling once the submit has finished: true\n * after `submit:success`, false when it failed, was cancelled or was dropped\n * for one in flight\n */\n async submit(submitter) {\n if (this.#submitting) {\n return false;\n }\n this.#submitting = true;\n this.spinner(true);\n let values;\n let request;\n try {\n const loader = this.component(this.declared('loader') ?? 'loaders:form').create(this);\n values = Bindings.extractFrom(this.form, submitter);\n const submitted = this.#tracking ? { saved: this.#snapshot(), upTo: this.#sequence } : null;\n request = await loader.prepare(values, this);\n const se = new CustomEvent('submit', {\n bubbles: true,\n cancelable: true,\n detail: { submitter, values, request },\n });\n if (!this.dispatchEvent(se)) {\n return false;\n }\n this.errors = [];\n const sre = new CustomEvent('submit:requested', {\n bubbles: true,\n cancelable: false,\n detail: { submitter, values: se.detail.values, request: se.detail.request },\n });\n let response = await AsyncEvents.fireAsync(this, sre, { mode: 'pipeline' });\n request = sre.detail.request;\n\n response = await loader.submit(request, this, response);\n const mapped = await loader.transform(response, this);\n if (submitted) {\n this.#commitFrom(submitted.saved, submitted.upTo);\n }\n this.dispatchEvent(\n new CustomEvent('submit:success', {\n bubbles: true,\n cancelable: false,\n detail: { submitter, values, request, response: mapped },\n }),\n );\n return true;\n } catch (e) {\n this.dispatchEvent(\n new CustomEvent('submit:failure', {\n bubbles: true,\n cancelable: false,\n detail: { submitter, values, request, exception: e },\n }),\n );\n if (e instanceof Failure) {\n this.errors = e.problems;\n } else {\n console.warn('failed to submit form', this, 'reason:', e);\n }\n return false;\n } finally {\n this.#submitting = false;\n this.spinner(false);\n }\n }\n /**\n * Saves the unsaved edits, for a page action that would lose them, such as\n * one reloading the page: under `track-changes` it submits only while the\n * form is dirty, and without it always submits.\n * @param {HTMLElement} [submitter] as `submit` takes it\n * @returns {Promise<boolean>} whether no unsaved edit is left: false when\n * the submit did not succeed, or when the user edited the form while it\n * was in flight\n */\n async save(submitter) {\n if (this.#tracking && !this.dirty) {\n return true;\n }\n return (await this.submit(submitter)) && !this.dirty;\n }\n /**\n * Resets the native form, each field returning to its default value. Under\n * `track-changes` every control counts as edited: the form is dirty if the\n * defaults differ from what was last committed.\n */\n reset() {\n this.form.reset();\n if (!this.#tracking) {\n return;\n }\n for (const name of new Set([...this.#saved.keys(), ...this.#snapshot().keys()])) {\n this.#edits.set(name, ++this.#sequence);\n }\n this.#refresh();\n }\n /** name → the serialized values the last commit recorded */\n #saved = new Map();\n /** name → the serialized values when first focused, for a name the last commit did not see */\n #focused = new Map();\n /** name → the sequence number of its latest edit since the last commit */\n #edits = new Map();\n #sequence = 0;\n #wasDirty = false;\n #frame = 0;\n /** @type {AbortController|null} */\n #leave = null;\n #tracking = false;\n /**\n * Whether, under `track-changes`, a control the user edited since the last\n * commit holds a value other than the one committed. An edit is what the\n * controls report as one: an `input` or a `change` bubbling from a control\n * of this form (0019), so assigning `value`, a select's vocabulary dropping\n * a key or a section delivering its fields is not one, and an edit undone\n * is no longer dirty. A control the last commit did not see compares with\n * its value when it was first focused. Always false without\n * `track-changes`.\n *\n * While dirty, the host matches `:state(dirty)` and the submit buttons of\n * this form carry `data-ful-dirty`; a change of the state dispatches\n * `dirty:change` with `{ dirty }`. Both are refreshed at the next frame\n * after an edit, while the property is exact at any time.\n * @returns {boolean}\n */\n get dirty() {\n if (!this.#tracking) {\n return false;\n }\n for (const name of this.#edits.keys()) {\n const now = this.#valuesOf(name);\n if (!this.#saved.has(name) && now === '[]') {\n continue;\n }\n const was = this.#saved.get(name) ?? this.#focused.get(name);\n if (was !== now) {\n return true;\n }\n }\n return false;\n }\n /**\n * Records the values of the controls as saved, so that the form is no\n * longer dirty. A submit commits by itself on success, and the form\n * commits once its fields have rendered: a page calls this for a save of\n * its own, or after writing the values it loaded. Does nothing without\n * `track-changes`.\n */\n commit() {\n if (this.#tracking) {\n this.#commitFrom(this.#snapshot(), this.#sequence);\n }\n }\n /**\n * Counts controls as edited by the user, for values the page writes on\n * the user's behalf: assigning `value` reports nothing, as 0019 wants.\n * @param {...Element} els each a control, or an element inside one\n */\n edited(...els) {\n for (const el of els) {\n this.#touch(el);\n }\n }\n /**\n * @param {Map<string, string>} saved\n * @param {number} upTo the sequence number of the latest edit the values include\n */\n #commitFrom(saved, upTo) {\n this.#saved = saved;\n for (const [name, sequence] of this.#edits) {\n if (sequence <= upTo) {\n this.#edits.delete(name);\n }\n }\n for (const name of this.#focused.keys()) {\n if (saved.has(name)) {\n this.#focused.delete(name);\n }\n }\n this.#refresh();\n }\n /**\n * The named control of this form `target` is or sits in, if any: a field's\n * inner control is unnamed or carries `form=\"\"`, a control of a form nested\n * in this one, like a table's filters, belongs to that form, and a\n * form-associated element with no `form` property answers its owner\n * through `internals.form`.\n * @param {any} target\n * @returns {string|null} its name\n */\n #nameOf(target) {\n for (let el = target; el && el !== this; el = el.parentElement) {\n if (ownerOf(el) === this.form && el.hasAttribute('name')) {\n return el.getAttribute('name');\n }\n }\n return null;\n }\n /** @param {EventTarget|null} target */\n #touch(target) {\n if (!this.#tracking) {\n return;\n }\n const name = this.#nameOf(target);\n if (name === null) {\n return;\n }\n this.#edits.set(name, ++this.#sequence);\n if (this.#frame === 0) {\n this.#frame = requestAnimationFrame(() => this.#refresh());\n }\n }\n /** @param {EventTarget|null} target */\n #focus(target) {\n const name = this.#nameOf(target);\n if (name !== null && !this.#saved.has(name) && !this.#focused.has(name)) {\n this.#focused.set(name, this.#valuesOf(name));\n }\n }\n /**\n * The controls that contribute to the values, as `Bindings.extractFrom`\n * reads them, with no submitter.\n * @returns {any[]}\n */\n #contributing() {\n return Array.from(this.form.elements).filter(\n (el) =>\n el.hasAttribute('name') &&\n !['submit', 'reset', 'button'].includes(/** @type {any} */ (el).type) &&\n !el.matches(':disabled'),\n );\n }\n /** @returns {Map<string, string>} each name to its serialized values */\n #snapshot() {\n /** @type {Map<string, any[]>} */\n const values = new Map();\n for (const el of this.#contributing()) {\n const name = el.getAttribute('name');\n values.set(name, [...(values.get(name) ?? []), Bindings.extract(el)]);\n }\n return new Map(Array.from(values, ([name, vs]) => [name, JSON.stringify(vs)]));\n }\n /**\n * @param {string} name\n * @returns {string} the serialized values of the controls carrying it\n */\n #valuesOf(name) {\n return JSON.stringify(\n this.#contributing()\n .filter((el) => el.getAttribute('name') === name)\n .map((el) => Bindings.extract(el)),\n );\n }\n #refresh() {\n cancelAnimationFrame(this.#frame);\n this.#frame = 0;\n const dirty = this.dirty;\n this.querySelectorAll('button').forEach((el) => {\n const button = /** @type HTMLButtonElement */ (el);\n if (button.form === this.form && button.type === 'submit') {\n button.toggleAttribute('data-ful-dirty', dirty);\n }\n });\n if (dirty === this.#wasDirty) {\n return;\n }\n this.#wasDirty = dirty;\n if (dirty) {\n this.internals.states.add('dirty');\n } else {\n this.internals.states.delete('dirty');\n }\n this.dispatchEvent(\n new CustomEvent('dirty:change', {\n bubbles: true,\n cancelable: false,\n detail: { dirty },\n }),\n );\n }\n #guard() {\n if (!this.declared('guard-leave') || this.#leave) {\n return;\n }\n this.#leave = new AbortController();\n PageLeave.guard(() => this.dirty, this.#leave.signal);\n }\n #spinning = 0;\n /**\n * @param {HTMLElement} el\n */\n #announce(el) {\n Attributes.defaultValue(el, 'role', 'status');\n el.hidden = false;\n if (el.textContent.trim() !== '') {\n return;\n }\n const label = document.createElement('span');\n label.className = 'ful-sr-only';\n label.dataset.ref = 'spinner-label';\n el.append(label);\n label.textContent = Localization.of().t('spinner.loading');\n }\n /**\n * Marks the form busy or releases it. Calls nest: only the first\n * `spinner(true)` and the matching last `spinner(false)` act, so a caller's\n * own spin may wrap a submit.\n *\n * Busy, the host carries `aria-busy=\"true\"` and each `ful-spinner` of this\n * form is revealed; one without text of its own is given `role=\"status\"`\n * (unless it has a role) and a visually hidden localized `spinner.loading`\n * label. Each submit and reset button of this form is held off with\n * `aria-disabled=\"true\"`, keeping its focus, and a click on it is refused\n * ahead of any listener on the button. Holding the buttons off does not\n * stop a programmatic `submit`.\n *\n * Released, the spinners are hidden and lose the label they were given, and\n * each held button gets back the `aria-disabled` it had. A button that\n * joined the form while it was busy keeps its own state.\n * @param {boolean} spin\n */\n spinner(spin) {\n if (spin) {\n ++this.#spinning;\n if (this.#spinning !== 1) {\n return;\n }\n } else {\n this.#spinning = Math.max(0, this.#spinning - 1);\n if (this.#spinning !== 0) {\n return;\n }\n }\n Attributes.set(this, 'aria-busy', spin ? 'true' : null);\n this.querySelectorAll('ful-spinner').forEach((el) => {\n if (el.closest('form') !== this.form) {\n return;\n }\n const hel = /** @type HTMLElement */ (el);\n if (spin) {\n this.#announce(hel);\n return;\n }\n hel.hidden = true;\n hel.querySelector(':scope > [data-ref=spinner-label]')?.remove();\n });\n this.querySelectorAll('input,button').forEach((el) => {\n const hel = /** @type HTMLButtonElement|HTMLInputElement */ (el);\n if (hel.form !== this.form || (hel.type !== 'submit' && hel.type !== 'reset')) {\n return;\n }\n if (spin) {\n hel.dataset.wd = hel.getAttribute('aria-disabled') ?? '';\n hel.setAttribute('aria-disabled', 'true');\n } else {\n if (hel.dataset.wd === undefined) {\n return;\n }\n Attributes.set(hel, 'aria-disabled', hel.dataset.wd || null);\n delete hel.dataset.wd;\n }\n });\n }\n /**\n * Writes a nested object onto the fields of this form through\n * `Bindings.mutateIn`: fields the object does not name keep their values.\n * @param {{ [x: string]: any; }} vs\n */\n set values(vs) {\n Bindings.mutateIn(this.form, vs);\n }\n /**\n * The fields of this form read into a nested object by\n * `Bindings.extractFrom`, with no submitter, so no button contributes.\n * @returns {any}\n */\n get values() {\n return Bindings.extractFrom(this.form);\n }\n /**\n * Shows problems through `Bindings.errors`, replacing the ones shown\n * before: each is pinned to the field it names, and the rest go to the\n * form's `ful-errors` banners. An empty array clears them.\n * @param {{ type: string; context?: string | null; reason: string; }[]} es\n */\n set errors(es) {\n Bindings.errors(this.form, es, this.declared('scroll-on-error'));\n }\n}\n\nexport { FormLoader, Form };\n","import { Attributes, BoundedCache } from '../../ftl/index.mjs';\nimport { Field } from './field.mjs';\n\nconst patternCache = new BoundedCache(100);\nconst compiled = (attr, pattern) =>\n patternCache.getOrCompute(`${attr}:${pattern}`, () => {\n try {\n return new RegExp(pattern, 'g');\n } catch (/** @type any */ e) {\n console.warn(`invalid ${attr} attribute`, pattern, e);\n return null;\n }\n });\n\nconst inheritedAutocomplete = (el) => el.closest('form')?.getAttribute('autocomplete') ?? null;\n\nconst INPUT_MODES = { numeric: 'numeric', decimal: 'decimal' };\n\nconst SEGMENTED = new Set(['date', 'time', 'datetime-local', 'month', 'week']);\n\nconst signed = (v, digits) => (v.startsWith('-') ? '-' : '') + digits(v);\n\nconst NUMERIC_DIGITS = {\n numeric: (t) => t.replace(/\\D/g, ''),\n decimal: (t) => {\n const kept = t.replace(/[^\\d.,]/g, '');\n const at = kept.search(/[.,]/);\n return at === -1 ? kept : kept.slice(0, at + 1) + kept.slice(at + 1).replace(/[.,]/g, '');\n },\n};\n\nconst numericFilter = (type, unsigned) => {\n const digits = NUMERIC_DIGITS[type];\n if (!digits) {\n return null;\n }\n return unsigned ? digits : (v) => signed(v, digits);\n};\n\nconst filterOf = (el) => {\n const keep = el.declared('keep');\n const reject = el.declared('reject');\n if (keep !== null && reject !== null) {\n console.warn('a ful-input declares both keep and reject: keep is applied, reject is ignored', el);\n }\n if (keep !== null) {\n const re = compiled('keep', keep);\n return re && ((v) => (v.match(re) ?? []).join(''));\n }\n if (reject !== null) {\n const re = compiled('reject', reject);\n return re && ((v) => v.replace(re, ''));\n }\n return numericFilter(el._type(), el.declared('unsigned'));\n};\n\n/**\n * A labelled text input over any native input type, or a `<textarea>` under\n * `type=\"textarea\"`; the temporal inputs are its subclasses. The label is the\n * default slot, `info` follows it, and `before` and `after` are rendered as\n * affixes around the control. Every `input-*` attribute is forwarded onto the\n * control, after everything the field sets there, so it has the last word.\n *\n * `type`, `v-type`, `keep`, `reject`, `uppercase`, `trim`, `unsigned` and\n * `autocomplete` are configuration: read once at the upgrade, so a later write\n * to them changes nothing. `placeholder` stays live.\n *\n * - `type=\"numeric\"` and `type=\"decimal\"` render a text input carrying that\n * `inputmode`, so the native `min`, `max` and `step` do not apply. Typing is\n * filtered to digits and a leading minus; a decimal also keeps its first `.`\n * or `,` and drops any later one; `unsigned` drops the minus.\n * - `keep` and `reject` are regular expressions filtering what is typed:\n * `keep` leaves every match, concatenated, and `reject` removes every match.\n * Either replaces the type's own filter, and `keep` wins over `reject` with a\n * warning. A pattern that does not compile is warned about once and filters\n * nothing. The caret stays next to the same character when text before it\n * is removed.\n * - `autocomplete` is put on the control. Without one the field takes the\n * `autocomplete` attribute of the nearest enclosing `<form>`, which the\n * platform does not pass on because the control carries `form=\"\"`.\n * - `uppercase`, `trim` and `v-type` shape the value as it is read; see `value`.\n * - The control's native `change` is stopped and the field dispatches its own\n * once the user commits a new value, as a text input does. A date, time,\n * datetime-local, month or week control fires its native `change` while its\n * segments are typed, as soon as they make a valid value; for those the field\n * reports when the control is left or Enter is pressed, at once for a value\n * picked from the browser's picker, never with the dates a year passes\n * through while it is typed. A control left incomplete reads as `null`, as\n * the native one does.\n *\n * A subclass template may render more than one control, as the compare filters\n * render the two bounds of a range: the first is `_input`, the one the field is\n * named by, and every one of them gets the inputmode, `autocomplete`, the\n * `input-` passthrough, the keystroke filter, the placeholder and the `change`\n * reporting. The passthrough leaves `input-id` to the first alone, so no\n * two controls share an id.\n */\nclass Input extends Field {\n /** @type {string[]} */\n static observed = ['placeholder'];\n /** @type {string[]} */\n static attributes = [\n 'type',\n 'v-type',\n 'keep',\n 'reject',\n 'uppercase:presence',\n 'trim:presence',\n 'unsigned:presence',\n 'autocomplete',\n ];\n static slots = true;\n static template = `\n <label>{{{{ slots.default }}}}</label>\n {{{{ slots.info }}}}\n <ful-control-group>\n <ful-affix data-tpl-if=\"slots.before\">{{{{ slots.before }}}}</ful-affix>\n <input data-tpl-if=\"type != 'textarea'\" data-tpl-type=\"type\" placeholder=\" \" form=\"\">\n <textarea data-tpl-if=\"type == 'textarea'\" placeholder=\" \" form=\"\"></textarea>\n <ful-affix data-tpl-if=\"slots.after\">{{{{ slots.after }}}}</ful-affix>\n </ful-control-group>\n <ful-field-error></ful-field-error>\n `;\n /**\n * The inner control, set by `_build`: the `<input>`, or the `<textarea>`\n * under `type=\"textarea\"`. A subclass reads and writes it for the\n * attributes it adds. Typed `any` so that a subclass can treat it as the\n * one of the two it renders.\n * @type {any}\n */\n _input;\n /** @type {(HTMLInputElement|HTMLTextAreaElement)[]} */\n #controls = [];\n /**\n * The type the field renders, which a subclass overrides to wrap another\n * native type. The base answers the declared `type`, else `number` under\n * `v-type=\"number\"`, else `text`. It is also what selects the keystroke\n * filter of `numeric` and `decimal` and the separator handling of `value`.\n * @returns {string}\n */\n _type() {\n return this.declared('type') ?? (this.declared('v-type') === 'number' ? 'number' : 'text');\n }\n /**\n * @param {{ slots: Record<string, DocumentFragment> | undefined }} conf\n * @returns {{fragment: DocumentFragment, control: any, error: Element | null, label: HTMLLabelElement | null}}\n */\n _build({ slots }) {\n const declared = this._type();\n const mode = INPUT_MODES[declared];\n const type = mode ? 'text' : declared;\n const fragment = this.template().withOverlay({ type, slots }).render();\n this.#controls = /** @type {(HTMLInputElement|HTMLTextAreaElement)[]} */ ([\n ...fragment.querySelectorAll(':is(ful-control-group, ful-control) > :is(input, textarea)'),\n ]);\n this._input = this.#controls[0];\n const autocomplete = this.declared('autocomplete') ?? inheritedAutocomplete(this);\n const strip = filterOf(this);\n for (const control of this.#controls) {\n this.#configure(control, mode, autocomplete, strip);\n }\n return {\n fragment,\n control: this._input,\n error: fragment.querySelector('ful-field-error'),\n label: fragment.querySelector('label'),\n };\n }\n /**\n * @param {HTMLInputElement|HTMLTextAreaElement} control\n * @param {string|undefined} mode the inputmode the type names\n * @param {string|null} autocomplete\n * @param {((text: string) => string)|null} strip the keystroke filter\n */\n #configure(control, mode, autocomplete, strip) {\n if (mode) {\n Attributes.set(control, 'inputmode', mode);\n }\n Attributes.set(control, 'autocomplete', autocomplete);\n const id = control.id;\n Attributes.forward('input-', this, control);\n if (control !== this._input) {\n Attributes.set(control, 'id', id || null);\n }\n this.#reportChanges(control);\n control.addEventListener('input', () => {\n if (!strip) {\n return;\n }\n const before = control.value;\n const after = strip(before);\n if (before === after) {\n return;\n }\n const start = control.selectionStart;\n control.value = after;\n if (start === null) {\n return;\n }\n const caret = strip(before.slice(0, start)).length;\n control.setSelectionRange(caret, caret);\n });\n }\n /** @param {HTMLInputElement|HTMLTextAreaElement} control */\n #reportChanges(control) {\n if (!SEGMENTED.has(control.type)) {\n control.addEventListener('change', (evt) => {\n evt.stopPropagation();\n this._notifyChange();\n });\n return;\n }\n /** @type {string|null} */\n let committed = null;\n let typed = false;\n const commit = () => {\n typed = false;\n const now = JSON.stringify(this.value);\n if (now === committed) {\n return;\n }\n committed = now;\n this._notifyChange();\n };\n control.addEventListener('focus', () => {\n committed = JSON.stringify(this.value);\n });\n control.addEventListener('keydown', (/** @type any */ evt) => {\n if (evt.key === 'Enter' && !evt.isComposing) {\n commit();\n return;\n }\n typed = true;\n });\n control.addEventListener('blur', commit);\n control.addEventListener('change', (evt) => {\n evt.stopPropagation();\n if (!typed) {\n commit();\n }\n });\n }\n /**\n * The control's text, shaped in this order: upper cased under `uppercase`,\n * trimmed under `trim`, `null` when that leaves it empty, every `,` read as\n * `.` for `type=\"decimal\"`, and decoded to a number under\n * `v-type=\"number\"`, where text that does not decode is answered as it is.\n * Writing `null`, `undefined` or `''` empties the control; anything else is\n * written as its string, replacing whatever was being typed, as a native\n * control's value does. Answers a `string`, a `number` or `null`; typed\n * `any` because subclasses answer other values.\n * @type {any}\n */\n get value() {\n const uppercase = this.declared('uppercase');\n const trim = this.declared('trim');\n const v = this._input.value;\n const uppercased = uppercase ? v.toUpperCase() : v;\n const trimmed = trim ? uppercased.trim() : uppercased;\n if (trimmed === '') {\n return null;\n }\n const normalized = this._type() === 'decimal' ? trimmed.replaceAll(',', '.') : trimmed;\n if (this.declared('v-type') === 'number') {\n const n = Number(normalized);\n return Number.isNaN(n) ? normalized : n;\n }\n return normalized;\n }\n set value(value) {\n this._input.value = value === '' || value === undefined || value === null ? '' : `${value}`;\n }\n /**\n * The control's placeholder, `null` when there is none. The control always\n * carries one, a single space standing in for none, so `:placeholder-shown`\n * matches an empty control and a floating label can rely on it; the blank\n * one is neither answered here nor reflected onto the host.\n * @type {string | null}\n */\n get placeholder() {\n const v = this._input.getAttribute('placeholder');\n return v === ' ' ? null : v;\n }\n set placeholder(d) {\n for (const control of this.#controls) {\n Attributes.set(control, 'placeholder', d ?? ' ');\n }\n this.reflectTo('placeholder', d);\n }\n}\n\nexport { Input };\n","import { ParsedElement, Localization } from '../../ftl/index.mjs';\nimport { Input } from './input.mjs';\n\nconst blankAsNull = (v) => (v === '' ? null : v);\n\n/**\n * Formats the yyyy-mm-dd date in its content as a numeric date, in the locale\n * its `locale` attribute names, else the page's, else the platform default.\n * Blank content, or content that does not name a date, renders the `default`\n * attribute, or nothing without one.\n */\nclass LocalDate extends ParsedElement {\n static attributes = ['locale', 'default'];\n render() {\n const content = this.textContent.trim();\n const [y, m, d] = content.split('-').map(Number);\n const parsed = content === '' ? null : new Date(y, m - 1, d);\n if (parsed === null || Number.isNaN(parsed.getTime())) {\n this.replaceChildren(this.declared('default') ?? '');\n return;\n }\n const { date } = Localization.of({ locale: this.declared('locale') ?? undefined });\n this.replaceChildren(date(parsed, { year: 'numeric', month: 'numeric', day: 'numeric' }));\n }\n}\n\n/**\n * Formats the ISO instant in its content as a numeric date and 24 hour time\n * with seconds, in the page's timezone and in the locale chosen as ful-local-date\n * chooses it. Blank content, or content that does not name an instant, renders\n * the `default` attribute, or nothing without one. A date-only value is read as\n * local midnight of that day.\n */\nclass Instant extends ParsedElement {\n static attributes = ['locale', 'default'];\n render() {\n const content = this.textContent.trim();\n const parsed = content === '' ? null : new Date(Instant.isoToLocal(content));\n if (parsed === null || Number.isNaN(parsed.getTime())) {\n this.replaceChildren(this.declared('default') ?? '');\n return;\n }\n const { date } = Localization.of({ locale: this.declared('locale') ?? undefined });\n this.replaceChildren(\n date(parsed, {\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n hour12: false,\n }),\n );\n }\n static #parse(v) {\n return /^\\d{4}-\\d{2}-\\d{2}$/.test(v) ? new Date(`${v}T00:00:00`) : new Date(v);\n }\n /**\n * Converts an ISO instant to the `yyyy-mm-ddThh:mm:ss.sss` wall clock time\n * a datetime-local input takes, in the page's timezone. A date-only value is\n * read as local midnight of the day it names, not as UTC midnight.\n * @param {string} iso\n * @returns {string} with NaN fields for a value that does not parse\n */\n static isoToLocal(iso) {\n const d = Instant.#parse(iso);\n const pad = (n, v) => String(v).padStart(n, '0');\n const date = `${d.getFullYear()}-${pad(2, d.getMonth() + 1)}-${pad(2, d.getDate())}`;\n const time = `${pad(2, d.getHours())}:${pad(2, d.getMinutes())}:${pad(2, d.getSeconds())}.${pad(3, d.getMilliseconds())}`;\n return `${date}T${time}`;\n }\n /**\n * Converts a datetime-local wall clock time in the page's timezone to a UTC\n * ISO instant. A date-only value is read as local midnight of that day.\n * @param {string} local\n * @returns {string|null} null for a value that does not parse\n */\n static localToIso(local) {\n const d = Instant.#parse(local);\n return Number.isNaN(d.getTime()) ? null : d.toISOString();\n }\n}\n\n/**\n * A date input whose `min` and `max` accept a yyyy-mm-dd date, `now` for\n * today, or an offset from today such as `+1d`, `-2m` or `+1y` (days, months,\n * years). A month offset landing past the end of the target month takes its\n * last day. Anything else is passed to the input unchanged. The `step`\n * attribute is applied before `min` and `max`.\n */\nclass InputLocalDate extends Input {\n static observed = ['step', 'min', 'max'];\n _type() {\n return 'date';\n }\n /**\n * The resolved lower bound, a yyyy-mm-dd date or whatever the input was given.\n * @returns {string|null} null when unset\n */\n get min() {\n return blankAsNull(this._input.min);\n }\n /** @param {string|null} v a date, `now` or an offset; null or blank removes the bound */\n set min(v) {\n this._input.min = InputLocalDate.#fromIsoOrOffset(v);\n }\n /**\n * The resolved upper bound, a yyyy-mm-dd date or whatever the input was given.\n * @returns {string|null} null when unset\n */\n get max() {\n return blankAsNull(this._input.max);\n }\n /** @param {string|null} v a date, `now` or an offset; null or blank removes the bound */\n set max(v) {\n this._input.max = InputLocalDate.#fromIsoOrOffset(v);\n }\n /**\n * The input's native step, in days on a date input and in seconds on a time input.\n * @returns {string|null} null when unset\n */\n get step() {\n return blankAsNull(this._input.step);\n }\n /** @param {string|null} v */\n set step(v) {\n this._input.step = v ?? '';\n }\n static #fromIsoOrOffset(v) {\n if (!v) {\n return '';\n }\n const formatLocalDate = (date) =>\n new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().split('T')[0];\n if (v === 'now') {\n return formatLocalDate(new Date());\n }\n const re = /^([+-])(\\d+)([dmy])$/;\n const match = re.exec(v);\n if (!match) {\n return v;\n }\n const sign = match[1] === '-' ? -1 : 1;\n const offset = +match[2];\n const r = new Date();\n r.setHours(0, 0, 0, 0);\n switch (match[3]) {\n case 'd':\n r.setDate(r.getDate() + offset * sign);\n break;\n case 'm': {\n const originalDay = r.getDate();\n r.setMonth(r.getMonth() + offset * sign);\n if (r.getDate() !== originalDay) {\n r.setDate(0);\n }\n break;\n }\n case 'y':\n r.setFullYear(r.getFullYear() + offset * sign);\n break;\n }\n return formatLocalDate(r);\n }\n}\n\n/**\n * A time input whose `min` and `max` accept a hh:mm time, `now`, or an offset\n * from now such as `+2h` or `-30m` (hours, minutes: `m` is minutes here, not\n * months), wrapping around midnight. A bound resolved from `now` or an offset\n * is floored to the `step` grid (60 seconds when unset), so that the values\n * on the grid stay valid, and carries seconds only when the step is not whole\n * minutes. A literal bound, and anything else, is passed to the input unchanged.\n */\nclass InputLocalTime extends InputLocalDate {\n _type() {\n return 'time';\n }\n /**\n * The resolved lower bound, a time or whatever the input was given.\n * @returns {string|null} null when unset\n */\n get min() {\n return blankAsNull(this._input.min);\n }\n /** @param {string|null} v a time, `now` or an offset; null or blank removes the bound */\n set min(v) {\n this._input.min = this.#fromNowOrOffset(v);\n }\n /**\n * The resolved upper bound, a time or whatever the input was given.\n * @returns {string|null} null when unset\n */\n get max() {\n return blankAsNull(this._input.max);\n }\n /** @param {string|null} v a time, `now` or an offset; null or blank removes the bound */\n set max(v) {\n this._input.max = this.#fromNowOrOffset(v);\n }\n #fromNowOrOffset(v) {\n if (!v) {\n return '';\n }\n const resolved = new Date();\n if (v !== 'now') {\n const re = /^([+-])(\\d+)([hm])$/;\n const match = re.exec(v);\n if (!match) {\n return v;\n }\n const sign = match[1] === '-' ? -1 : 1;\n const offset = +match[2] * sign;\n if (match[3] === 'h') {\n resolved.setHours(resolved.getHours() + offset);\n } else {\n resolved.setMinutes(resolved.getMinutes() + offset);\n }\n }\n return InputLocalTime.#snapped(resolved, Number(this._input.step) || 60);\n }\n static #snapped(date, stepSeconds) {\n const pad = (n) => String(n).padStart(2, '0');\n const seconds = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds();\n const snapped = Math.floor(seconds / stepSeconds) * stepSeconds;\n const hh = pad(Math.floor(snapped / 3600));\n const mm = pad(Math.floor((snapped % 3600) / 60));\n return stepSeconds % 60 === 0 ? `${hh}:${mm}` : `${hh}:${mm}:${pad(snapped % 60)}`;\n }\n}\n\n/**\n * A datetime-local input whose value and bounds are read and written as UTC\n * ISO instants, shown as wall clock time in the page's timezone. A date-only\n * value is read as local midnight of that day.\n */\nclass InputInstant extends Input {\n static observed = ['step', 'min', 'max'];\n _type() {\n return 'datetime-local';\n }\n /**\n * The entered time as a UTC ISO instant.\n * @returns {string|null} null when empty or when the input holds text that does not parse\n */\n get value() {\n return Instant.localToIso(this._input.value);\n }\n /** @param {string|null|undefined} v an ISO instant; a falsy value empties the input */\n set value(v) {\n super.value = v ? Instant.isoToLocal(v) : '';\n }\n /**\n * The lower bound as a UTC ISO instant.\n * @returns {string|null} null when unset\n */\n get min() {\n return Instant.localToIso(this._input.min);\n }\n /** @param {string|null} v an ISO instant; a falsy value removes the bound */\n set min(v) {\n this._input.min = v ? Instant.isoToLocal(v) : '';\n }\n /**\n * The upper bound as a UTC ISO instant.\n * @returns {string|null} null when unset\n */\n get max() {\n return Instant.localToIso(this._input.max);\n }\n /** @param {string|null} v an ISO instant; a falsy value removes the bound */\n set max(v) {\n this._input.max = v ? Instant.isoToLocal(v) : '';\n }\n /**\n * The input's native step, in seconds.\n * @returns {string|null} null when unset\n */\n get step() {\n return blankAsNull(this._input.step);\n }\n /** @param {string|null} v */\n set step(v) {\n this._input.step = v ?? '';\n }\n}\n\nexport { Instant, LocalDate, InputLocalDate, InputLocalTime, InputInstant };\n","import { Fragments, Localization, Templates } from '../../ftl/index.mjs';\nimport { Input } from './input.mjs';\n\n/**\n * A file input with an optional dropzone and item list, enforcing the type,\n * size and count limits it declares.\n *\n * The `dropzone` and `item-list` attributes show the dropzone and the list of\n * chosen files. A `dropzone` slot replaces the default dropzone's content, and\n * an `items` slot holding a template replaces the stock item, rendered with the\n * same `files` overlay so that it reads the File objects it lists. Clicking the\n * dropzone opens the picker, and the host carries a `dragover` attribute while\n * a drag hovers it. A drop selects the files it carries, ignoring entries that\n * are not files; a drop with no file, or with several on a field that is not\n * `multiple`, changes nothing.\n *\n * Every selection, picked, dropped or assigned, goes through the constraints\n * in order: `accept` and `max-file-size` drop the files they refuse,\n * `max-total-size` and `max-files` clear the whole selection. Each violation\n * shows a warning. The change event fires for a pick, a drop and a removal\n * through an item's button; the `files`, `file` and `value` setters are silent,\n * like a native input's.\n *\n * While disabled or readonly, the picker, the dropzone and the item removals\n * do nothing, and a drop still does not reach the browser's default handling.\n */\nclass InputFile extends Input {\n /**\n * Milliseconds a warning stays before the field removes it, whether or not\n * its css animation ran; read each time a warning is shown.\n * @type {number}\n */\n static WARNING_TIMEOUT = 5000;\n /**\n * Builds a FileList holding exactly these files, the form `files` takes.\n * @param {Iterable<File>} [files]\n * @returns {FileList}\n */\n static list(files = []) {\n const dt = new DataTransfer();\n for (const file of files) {\n dt.items.add(file);\n }\n return dt.files;\n }\n static observed = [\n 'placeholder',\n 'accept:csv',\n 'multiple:presence',\n 'item-list:presence',\n 'dropzone:presence',\n 'max-files:number',\n 'max-file-size:number',\n 'max-total-size:number',\n 'value',\n ];\n #accept;\n #items;\n #dropzone;\n #warnings;\n #group;\n _type() {\n return 'file';\n }\n static template = `\n <label>{{{{ slots.default }}}}</label>\n {{{{ slots.info }}}}\n <ful-control-group>\n <ful-affix data-tpl-if=\"slots.before\">{{{{ slots.before }}}}</ful-affix>\n <input data-tpl-type=\"type\" placeholder=\" \" form=\"\">\n <ful-affix data-tpl-if=\"slots.after\">{{{{ slots.after }}}}</ful-affix>\n </ful-control-group>\n <div data-ref=\"dropzone\" class=\"dropzone\" data-tpl-if=\"slots.dropzone\">\n {{{{ slots.dropzone }}}}\n </div>\n <div data-ref=\"dropzone\" class=\"default-dropzone\" data-tpl-if=\"!slots.dropzone\">\n {{ #l10n:t('files.dropzone-label') }}\n </div>\n <ful-item-list></ful-item-list>\n <ful-field-warnings role=\"status\" aria-live=\"polite\"></ful-field-warnings>\n <ful-field-error></ful-field-error>\n `;\n static templates = {\n items: `\n <ful-item data-tpl-each=\"files\" data-tpl-var=\"file\" data-tpl-data-name=\"file.name\">\n <div><span>{{ file.name }}</span><span>{{ #l10n:bytes(file.size) }}</span><button type=\"button\" data-tpl-aria-label=\"#l10n:t('files.remove')\"><ful-icon name=\"x-lg\" aria-hidden=\"true\"></ful-icon></button></div>\n </ful-item>\n `,\n warning: `<ful-field-warning>{{ #l10n:t(key, args) }}</ful-field-warning>`,\n };\n #itemstemplate;\n _build(conf) {\n const pieces = super._build(conf);\n const fragment = pieces.fragment;\n this.#items = fragment.querySelector('ful-item-list');\n this.#itemstemplate =\n conf.slots?.items && !Fragments.isBlank(conf.slots.items) ? Templates.fromFragment(conf.slots.items) : null;\n this.#dropzone = fragment.querySelector('[data-ref=dropzone]');\n this.#warnings = fragment.querySelector('ful-field-warnings');\n this.#group = fragment.querySelector('ful-control-group');\n this.#warnings.addEventListener('animationend', (e) => {\n e.target.remove();\n });\n this.#items.addEventListener('click', (e) => {\n if (!e.target.closest('button')) {\n return;\n }\n if (!this._interactive()) {\n return;\n }\n const idx = [...this.#items.children].indexOf(e.target.closest('ful-item'));\n if (idx === -1) {\n return;\n }\n this.files = InputFile.list([...this.files].filter((f, i) => i !== idx));\n this._notifyChange();\n });\n this.#dropzone.addEventListener('click', (e) => {\n if (!this._interactive()) {\n return;\n }\n this._input.click();\n });\n\n this.#dropzone.addEventListener('dragover', (e) => {\n e.preventDefault();\n this.toggleAttribute('dragover', true);\n });\n this.#dropzone.addEventListener('dragleave', () => {\n this.toggleAttribute('dragover', false);\n });\n this.#dropzone.addEventListener('drop', (e) => {\n e.preventDefault();\n this.toggleAttribute('dragover', false);\n if (!this._interactive()) {\n return;\n }\n const dropped = [...e.dataTransfer.items].filter((i) => i.kind === 'file');\n const files = dropped.map((i) => i.getAsFile()).filter((f) => f !== null);\n if (files.length === 0 || (files.length > 1 && !this.multiple)) {\n return;\n }\n this.files = InputFile.list(files);\n this._notifyChange();\n });\n this._input.addEventListener('change', (e) => {\n this.#update();\n });\n return { ...pieces, freeze: this.#group };\n }\n #update() {\n this.setCustomValidity();\n this.#warnings.replaceChildren();\n this.#ensureAcceptable();\n this.#ensureFileSizes();\n this.#ensureTotalSize();\n this.#ensureFilesCount();\n (this.#itemstemplate ?? this.template('items')).withOverlay({ files: this.files }).renderTo(this.#items);\n }\n /**\n * Shows a warning in the field's polite live region: the localized message\n * for an l10n key and its arguments. It is removed when its animation ends,\n * or after `WARNING_TIMEOUT` milliseconds at the latest. The warnings are\n * cleared whenever the selection changes.\n * @param {string} key\n * @param {Record<string, any>} [args]\n */\n warning(key, args) {\n this.template('warning').withOverlay({ key, args }).appendTo(this.#warnings);\n const warning = /** @type HTMLElement */ (this.#warnings.lastElementChild);\n setTimeout(() => warning.remove(), InputFile.WARNING_TIMEOUT);\n }\n #acceptable(file) {\n const name = file.name.toLowerCase();\n return this.#accept.some((token) => {\n const t = token.toLowerCase().split(';')[0].trim();\n if (t.startsWith('.')) {\n return name.endsWith(t);\n }\n if (t.endsWith('/*')) {\n return file.type.startsWith(`${t.slice(0, -1)}`);\n }\n return t.includes('/') && file.type === t;\n });\n }\n #ensureAcceptable() {\n if (!this.#accept.length) {\n return;\n }\n const unacceptable = [...this.files].filter((file) => !this.#acceptable(file));\n\n if (unacceptable.length === 0) {\n return;\n }\n this.warning('files.unacceptable-file-type', { types: this.#accept.join(', ') });\n this._input.files = InputFile.list([...this.files].filter((f) => !unacceptable.includes(f)));\n }\n #ensureFilesCount() {\n if (this.#maxFiles === null) {\n return;\n }\n if (this.files.length <= this.#maxFiles) {\n return;\n }\n this.warning('files.max-files-exceeded', { count: this.#maxFiles });\n this._input.files = InputFile.list();\n }\n\n #ensureFileSizes() {\n if (this.#maxFileSize === null) {\n return;\n }\n const oversized = [...this.files].filter((file) => file.size > this.#maxFileSize);\n if (oversized.length === 0) {\n return;\n }\n this.warning('files.max-file-size-exceeded', { size: Localization.of().bytes(this.#maxFileSize) });\n this._input.files = InputFile.list([...this.files].filter((f) => !oversized.includes(f)));\n }\n #ensureTotalSize() {\n if (this.#maxTotalSize === null) {\n return;\n }\n const totalSize = [...this.files].reduce((acc, file) => acc + file.size, 0);\n if (totalSize <= this.#maxTotalSize) {\n return;\n }\n this.warning('files.max-total-size-exceeded', { size: Localization.of().bytes(this.#maxTotalSize) });\n this._input.files = InputFile.list();\n }\n\n /**\n * The accepted types, also set on the native input for its picker. A token\n * is a dot-prefixed extension matched against the end of the file name, a\n * mime type matched against the file's type with any parameters ignored, or\n * a family such as `image/*`; case is ignored, and any other token matches\n * nothing. A file matching no token is dropped with a warning; an empty list\n * accepts every file. Enforced from the next selection on.\n * @returns {string[]}\n */\n get accept() {\n return this.#accept;\n }\n /** @param {string[]} vs */\n set accept(vs) {\n this._input.accept = vs.join(',');\n this.#accept = vs;\n this.reflectTo('accept', vs);\n }\n /**\n * Whether the field takes several files; a single-file field ignores a drop of several.\n * @returns {boolean}\n */\n get multiple() {\n return this._input.multiple;\n }\n /** @param {boolean} v */\n set multiple(v) {\n this._input.multiple = v;\n this.reflectTo('multiple', v);\n }\n /**\n * The selected files, after the constraints.\n * @returns {FileList}\n */\n get files() {\n return this._input.files;\n }\n /**\n * Replaces the selection and runs the constraints over it, refreshing the\n * warnings and the item list, without firing change.\n * @param {FileList} vs\n */\n set files(vs) {\n this._input.files = vs;\n this.#update();\n }\n /**\n * The first selected file.\n * @returns {File|null}\n */\n get file() {\n return this.files[0] ?? null;\n }\n /**\n * Replaces the selection with this one file, or empties it, as `files` does.\n * @param {File|null|undefined} v\n */\n set file(v) {\n this.files = InputFile.list(v ? [v] : []);\n }\n /**\n * The names of the selected files: an array when `multiple`, otherwise the\n * one name or null.\n * @returns {string[]|string|null}\n */\n get value() {\n const names = Array.from(this._input.files).map((f) => f.name);\n return this.multiple ? names : (names[0] ?? null);\n }\n /**\n * Empties the selection for a falsy value and ignores any other, since a\n * file name cannot select a file.\n * @param {any} v\n */\n set value(v) {\n if (v) {\n return;\n }\n this.files = InputFile.list();\n }\n /** Empties the selection, as a native file input's reset does, whatever the `value` attribute says. */\n formResetCallback() {\n this.value = null;\n }\n /**\n * The size of the selected files together, in bytes.\n * @returns {number}\n */\n get totalsize() {\n return Array.from(this.files).reduce((a, f) => a + f.size, 0);\n }\n #maxFiles;\n /**\n * The most files a selection may hold; a larger selection is cleared\n * entirely with a warning. Enforced from the next selection on.\n * @returns {number|null} null for no limit\n */\n get maxFiles() {\n return this.#maxFiles;\n }\n /** @param {number|null} v */\n set maxFiles(v) {\n this.#maxFiles = v;\n this.reflectTo('max-files', v);\n }\n #maxFileSize;\n /**\n * The largest size one file may have, in bytes; a larger file is dropped\n * from the selection with a warning. Enforced from the next selection on.\n * @returns {number|null} null for no limit\n */\n get maxFileSize() {\n return this.#maxFileSize;\n }\n /** @param {number|null} v */\n set maxFileSize(v) {\n this.#maxFileSize = v;\n this.reflectTo('max-file-size', v);\n }\n #maxTotalSize;\n /**\n * The largest size the selected files may have together, in bytes; a\n * larger selection is cleared entirely with a warning. Enforced from the\n * next selection on.\n * @returns {number|null} null for no limit\n */\n get maxTotalSize() {\n return this.#maxTotalSize;\n }\n /** @param {number|null} v */\n set maxTotalSize(v) {\n this.#maxTotalSize = v;\n this.reflectTo('max-total-size', v);\n }\n #useItemList;\n /**\n * Whether the chosen files are listed, each with a button removing it; the\n * stylesheet shows the list from the reflected `item-list` attribute.\n * @returns {boolean}\n */\n get itemList() {\n return this.#useItemList;\n }\n /** @param {boolean} v */\n set itemList(v) {\n this.#useItemList = v;\n this.reflectTo('item-list', v);\n }\n #useDropzone;\n /**\n * Whether the dropzone is shown; the stylesheet shows it from the reflected\n * `dropzone` attribute.\n * @returns {boolean}\n */\n get dropzone() {\n return this.#useDropzone;\n }\n /** @param {boolean} v */\n set dropzone(v) {\n\n this.#useDropzone = v;\n this.reflectTo('dropzone', v);\n }\n}\n\nexport { InputFile };\n","import { Attributes } from '../../ftl/index.mjs';\n\n/** the viewport's breathing room when clamping, in pixels */\nconst PAD = 8;\nconst open = new Map();\nlet frame = 0;\nlet reflowWired = false;\n\nconst platformAnchors = () =>\n CSS.supports('anchor-name: --ful-probe') &&\n CSS.supports('position-anchor: --ful-probe') &&\n CSS.supports('position-area: bottom') &&\n CSS.supports('top: anchor(bottom)') &&\n CSS.supports('width: anchor-size(width)');\n\nconst clamp = (value, low, high) => Math.min(Math.max(value, low), Math.max(low, high));\n\n/** a popover that reads `placement` and gets the callout offsets */\nconst isNote = (popover) => popover.matches('ful-note, .ful-note, [placement]');\n\n/**\n * Writes the invoker's centre, measured from the popover's padding box, as\n * `--ful-note-callout-inline` and `--ful-note-callout-block` on the popover.\n */\nconst reportCallout = (popover, invoker) => {\n const box = invoker.getBoundingClientRect();\n const here = popover.getBoundingClientRect();\n popover.style.setProperty(\n '--ful-note-callout-inline',\n `${box.left + box.width / 2 - here.left - popover.clientLeft}px`,\n );\n popover.style.setProperty(\n '--ful-note-callout-block',\n `${box.top + box.height / 2 - here.top - popover.clientTop}px`,\n );\n};\n\nconst place = (popover, anchored) => {\n const { invoker, stretch } = anchored;\n const box = invoker.getBoundingClientRect();\n const viewport = document.documentElement;\n const vw = viewport.clientWidth;\n const vh = viewport.clientHeight;\n popover.style.removeProperty('margin');\n const computed = getComputedStyle(popover);\n const gap = {\n top: parseFloat(computed.marginTop) || 0,\n right: parseFloat(computed.marginRight) || 0,\n bottom: parseFloat(computed.marginBottom) || 0,\n left: parseFloat(computed.marginLeft) || 0,\n };\n popover.style.right = 'auto';\n popover.style.bottom = 'auto';\n popover.style.margin = '0';\n if (stretch) {\n popover.style.removeProperty('width');\n popover.style.removeProperty('min-width');\n popover.style.removeProperty('max-width');\n const cap = Math.min(parseFloat(computed.maxWidth) || vw, vw - 2 * PAD);\n popover.style.minWidth = `${Math.min(box.width, vw - 2 * PAD)}px`;\n popover.style.maxWidth = `${cap}px`;\n const width = popover.getBoundingClientRect().width;\n popover.style.left = `${clamp(box.left, PAD, vw - width - PAD)}px`;\n const height = popover.getBoundingClientRect().height;\n const below = box.bottom + gap.top;\n const top = below + height <= vh - PAD ? below : box.top - gap.bottom - height;\n popover.style.top = `${clamp(top, PAD, vh - height - PAD)}px`;\n return;\n }\n const note = isNote(popover);\n const placement = note ? (popover.getAttribute('placement') ?? 'bottom') : 'bottom';\n popover.style.removeProperty('max-width');\n const cap = Math.min(parseFloat(computed.maxWidth) || vw, vw - 2 * PAD);\n popover.style.maxWidth = `${cap}px`;\n popover.style.left = `${PAD}px`;\n const wide = popover.getBoundingClientRect().width;\n let left =\n placement === 'right'\n ? box.right + gap.left\n : placement === 'left'\n ? box.left - gap.right - wide\n : note\n ? box.left + box.width / 2 - wide / 2\n : box.left;\n left = clamp(left, PAD, vw - wide - PAD);\n popover.style.left = `${left}px`;\n popover.style.maxWidth = `${Math.min(cap, vw - PAD - left)}px`;\n const height = popover.getBoundingClientRect().height;\n const top =\n placement === 'top'\n ? box.top - gap.bottom - height\n : placement === 'right' || placement === 'left'\n ? box.top + box.height / 2 - height / 2\n : box.bottom + gap.top;\n popover.style.top = `${clamp(top, PAD, vh - height - PAD)}px`;\n if (note) {\n reportCallout(popover, invoker);\n }\n};\n\nconst unplace = (popover) => {\n for (const property of [\n 'top',\n 'left',\n 'right',\n 'bottom',\n 'margin',\n 'max-width',\n 'min-width',\n 'width',\n 'visibility',\n '--ful-note-callout-inline',\n '--ful-note-callout-block',\n ]) {\n popover.style.removeProperty(property);\n }\n};\n\nconst showOncePlaced = (popover, anchored) => {\n popover.style.visibility = 'hidden';\n queueMicrotask(() => {\n if (popover.matches(':popover-open')) {\n place(popover, anchored);\n }\n popover.style.removeProperty('visibility');\n });\n};\n\nconst reflow = () => {\n frame = 0;\n for (const [popover, anchored] of open) {\n if (!popover.isConnected || !anchored.invoker.isConnected) {\n open.delete(popover);\n continue;\n }\n place(popover, anchored);\n }\n};\n\nconst schedule = () => {\n if (!frame && open.size > 0) {\n frame = requestAnimationFrame(reflow);\n }\n};\n\n/**\n * Places a popover beside the element or the rectangle it belongs to.\n *\n * `wire` pairs a popover with one invoker for its lifetime and relies on css\n * anchor positioning, placing the popover in script only where the platform\n * lacks it or the caller asks for it. `show` places a popover once, beside\n * whatever anchor the call hands over.\n */\nclass Anchors {\n /**\n * Anchors a popover to its invoker for the popover's lifetime.\n *\n * On every platform the invoker is given an inline `anchor-name` and the\n * popover a `position-anchor` naming it, `--` followed by a unique id\n * built from `prefix`. That is what a stylesheet needs to place the popover\n * itself: the library's own menus say `top: anchor(bottom); left:\n * anchor(left)`. **Writing that css is the caller's half of this.** Without\n * it the popover lands wherever the user agent puts a popover, which is not\n * beside the invoker.\n *\n * Where the platform has no css anchor positioning, or under `handPlace`,\n * the popover is placed in script instead: beside the invoker whenever it\n * opens, clamped 8px inside the viewport, placed again on every scroll and\n * resize while open, and its inline placement removed on close. The gap to\n * the invoker is read from the popover's css margins. From `beforetoggle`\n * to the placing, in a microtask before the `toggle` event, the popover\n * carries an inline `visibility: hidden`, so a stylesheet setting\n * `visibility` on it competes with that. A popover removed from the\n * document while open, or whose invoker was removed, stops being placed.\n *\n * The script placement puts a plain popover below the invoker,\n * start-aligned. A popover matching `ful-note`, `.ful-note` or\n * `[placement]` reads its `placement` attribute instead: `top`, `right`,\n * `left`, or `bottom` by default, centred on the invoker along the other\n * axis. Such a popover is also given `--ful-note-callout-inline` and\n * `--ful-note-callout-block`: the invoker's centre, in pixels, measured\n * from the popover's padding box, which stays on the invoker when the\n * viewport pushes the popover off it.\n *\n * Wiring the same pair twice adds its listeners twice.\n *\n * @param {HTMLElement} invoker the element the popover belongs to\n * @param {HTMLElement} popover the `[popover]` element to place\n * @param {object} [options]\n * @param {string} [options.prefix] prefixes the generated anchor name and\n * id, `ful-anchor` by default, so the dom says which component a name\n * belongs to\n * @param {boolean} [options.invoke] makes the invoker toggle the popover,\n * which light dismiss then closes with no script of your own. The popover\n * is given the generated id when it has none. A `button` or `input`\n * invoker gets a `popovertarget` naming it; any other element toggles it\n * on click and on the Enter and Space keys\n * @param {boolean} [options.expanded] sets the invoker's `aria-expanded` to\n * `false` at once and keeps it in step with the popover's `toggle` events\n * @param {boolean} [options.stretch] in the script placement, sizes the\n * popover to at least its invoker's width, capped by its own `max-width`\n * and the viewport, and flips it above the invoker where the viewport\n * leaves no room below, which is what a combobox dropdown wants. The\n * `placement` attribute is not read\n * @param {boolean} [options.handPlace] places in script on every platform\n * rather than only as a fallback, for a popover that needs to know where\n * its invoker ended up, such as a note pointing a callout at it. Such a\n * popover declares no anchor placement in css\n */\n static wire(\n invoker,\n popover,\n { prefix = 'ful-anchor', invoke = false, expanded = false, stretch = false, handPlace = false } = {},\n ) {\n const uid = Attributes.uid(prefix);\n if (invoke) {\n popover.id = popover.id || uid;\n if (invoker.localName === 'button' || invoker.localName === 'input') {\n invoker.setAttribute('popovertarget', popover.id);\n } else {\n invoker.addEventListener('click', () => popover.togglePopover());\n invoker.addEventListener('keydown', (/** @type any */ evt) => {\n if (evt.key !== 'Enter' && evt.key !== ' ') {\n return;\n }\n evt.preventDefault();\n popover.togglePopover();\n });\n }\n }\n const anchor = `--${uid}`;\n invoker.style.anchorName = anchor;\n popover.style.positionAnchor = anchor;\n if (expanded) {\n invoker.setAttribute('aria-expanded', 'false');\n popover.addEventListener('toggle', (/** @type any */ evt) => {\n invoker.setAttribute('aria-expanded', evt.newState === 'open' ? 'true' : 'false');\n });\n }\n if (!handPlace && platformAnchors()) {\n return;\n }\n const anchored = { invoker, stretch };\n popover.addEventListener('beforetoggle', (/** @type any */ evt) => {\n if (evt.newState === 'open') {\n showOncePlaced(popover, anchored);\n }\n });\n popover.addEventListener('toggle', (/** @type any */ evt) => {\n if (evt.newState === 'open') {\n open.set(popover, anchored);\n place(popover, anchored);\n } else {\n open.delete(popover);\n unplace(popover);\n }\n });\n if (!reflowWired) {\n reflowWired = true;\n document.addEventListener('scroll', schedule, true);\n window.addEventListener('resize', schedule);\n }\n }\n /**\n * Shows a popover and places it beside an anchor, once. It serves a\n * popover shared by many invokers, each open handing over its own anchor,\n * and an anchor that is a rectangle rather than an element, such as one\n * read out of an iframe. Nothing is paired and nothing follows a later\n * scroll or resize; closing is the caller's, or the platform's for a\n * light-dismissing popover.\n *\n * The popover goes below the anchor, start-aligned, clamped 8px inside the\n * viewport. `flip` moves it above the anchor where there is no room below\n * and there is room above. The placement is written as inline `top`, `left`,\n * `right`, `bottom` and `margin`, which stay after the popover closes and\n * are overwritten by the next call.\n *\n * A popover not already open is shown with `showPopover()` and placed\n * before the call returns, so the first position anybody sees is the right\n * one and the caller can move the focus into it on the next line. One\n * already open is placed without being shown again.\n *\n * @param {HTMLElement} popover the `[popover]` element to show, or an\n * already-shown element to place\n * @param {Element|DOMRect} anchor the element, or the rectangle in\n * viewport coordinates, to place beside\n * @param {object} [options]\n * @param {boolean} [options.flip] place above the anchor where no room is\n * left below, `false` by default\n * @param {number} [options.gap] the distance from the anchor, in pixels,\n * `0` by default\n * @returns {HTMLElement} the popover\n */\n static show(popover, anchor, { flip = false, gap = 0 } = {}) {\n const placeShown = () => {\n const box = anchor instanceof Element ? anchor.getBoundingClientRect() : anchor;\n const viewport = document.documentElement;\n const here = popover.getBoundingClientRect();\n const below = box.bottom + gap;\n const above = box.top - gap - here.height;\n const top = flip && below + here.height > viewport.clientHeight - PAD && above >= PAD ? above : below;\n popover.style.right = 'auto';\n popover.style.bottom = 'auto';\n popover.style.margin = '0';\n popover.style.left = `${clamp(box.left, PAD, Math.max(PAD, viewport.clientWidth - here.width - PAD))}px`;\n popover.style.top = `${clamp(top, PAD, Math.max(PAD, viewport.clientHeight - here.height - PAD))}px`;\n };\n if (typeof popover.showPopover === 'function' && !popover.matches(':popover-open')) {\n popover.showPopover();\n }\n placeShown();\n return popover;\n }\n}\n\nexport { Anchors };\n","import { Attributes, Fragments, ParsedElement, Templates } from '../../ftl/index.mjs';\nimport { Claims } from '../claims.mjs';\nimport { Anchors } from '../disclosures/anchors.mjs';\nimport { Field } from './field.mjs';\nimport { VersionedLocalStorage } from '../storage.mjs';\nimport { Timing } from '../timing.mjs';\n\n/**\n * @typedef {{ key: any, label: string, metadata: any }} SelectEntry\n */\n/**\n * @typedef {{ request(method: string, url: string): any }} SelectHttpClient\n */\n\nconst byKeys = (entries, keys) => entries.filter(({ key }) => keys.some((r) => r == key));\nconst byLabel = (entries, needle) =>\n entries.filter(({ label }) => (label ?? '').toLowerCase().includes(needle?.toLowerCase() ?? ''));\n\n/**\n * Fetches a select's whole vocabulary from a url and serves every later read\n * from it. Concurrent callers share one request, the options may be cached in\n * local storage under a revision, and invalidating discards both.\n */\nclass RemoteLoader {\n #http;\n #url;\n #method;\n #responseMapper;\n #prefetch;\n #revision;\n #data = null;\n /** @type {Promise<void>|null} */\n #inFlight = null;\n #configs = new Claims();\n /**\n * @param {{ http: SelectHttpClient, url: string, method: string, responseMapper: (response: any) => SelectEntry[], prefetch: boolean, revision: string|null }} conf\n * a null revision never reads nor writes local storage\n */\n constructor({ http, url, method, responseMapper, prefetch, revision }) {\n this.#http = http;\n this.#url = url;\n this.#method = method;\n this.#responseMapper = responseMapper;\n this.#prefetch = prefetch;\n this.#revision = revision;\n }\n /**\n * Fetches the vocabulary now when the loader was built with prefetch, and\n * does nothing otherwise.\n * @returns {Promise<void>}\n * @throws when the fetch fails, or when an invalidation supersedes it\n */\n async prefetch() {\n if (!this.#prefetch) {\n return;\n }\n await this.#ensureFetched();\n }\n /**\n * The entries whose key loosely equals one of the keys, in vocabulary order.\n * @param {...any} keys\n * @returns {Promise<SelectEntry[]>}\n * @throws when the fetch fails, or when an invalidation supersedes it\n */\n async exact(...keys) {\n return byKeys(await this.#ensureFetched(), keys);\n }\n /**\n * The entries whose label contains the needle, ignoring case; every entry\n * for a nullish or empty needle.\n * @param {string|null} [needle]\n * @returns {Promise<SelectEntry[]>}\n * @throws when the fetch fails, or when an invalidation supersedes it\n */\n async load(needle) {\n return byLabel(await this.#ensureFetched(), needle);\n }\n /**\n * Drops the vocabulary held in memory so the next question refetches it,\n * which may still be answered from local storage under the same revision.\n * A fetch still in flight is detached: its outcome is neither served nor\n * stored, and the callers waiting on it reject.\n * @returns {Promise<void>}\n */\n async invalidate() {\n this.#configs.invalidate();\n this.#data = null;\n this.#inFlight = null;\n }\n async #ensureFetched() {\n if (this.#data === null) {\n if (this.#inFlight === null) {\n const claim = this.#configs.hold();\n this.#inFlight = RemoteLoader.#revisionedData(this.#http, this.#method, this.#url, this.#revision)\n .then((raw) => {\n if (!claim.stale) {\n this.#data = this.#responseMapper(raw);\n }\n })\n .finally(() => {\n if (!claim.stale) {\n this.#inFlight = null;\n }\n });\n }\n await this.#inFlight;\n }\n if (this.#data === null) {\n throw new Error('superseded by an invalidation');\n }\n return this.#data;\n }\n static async #revisionedData(http, method, url, revision) {\n const storageKey = `${method}@${url}`;\n if (revision !== null) {\n const data = VersionedLocalStorage.load(storageKey, revision);\n if (data !== undefined) {\n return data;\n }\n }\n const data = await http.request(method, url).fetchJson();\n if (revision !== null) {\n try {\n VersionedLocalStorage.save(storageKey, revision, data);\n } catch (/** @type any */ e) {\n console.warn('failed to cache the select options', e);\n }\n }\n return data;\n }\n}\n\n/** Asks the endpoint per query instead of fetching the vocabulary once, for a list too large to hold in memory. */\nclass PartialRemoteLoader {\n #http;\n #url;\n #method;\n #responseMapper;\n /**\n * @param {{ http: SelectHttpClient, url: string, method: string, responseMapper: (response: any) => SelectEntry[] }} conf\n */\n constructor({ http, url, method, responseMapper }) {\n this.#http = http;\n this.#url = url;\n this.#method = method;\n this.#responseMapper = responseMapper;\n }\n /**\n * Does nothing, since nothing is held between queries.\n * @returns {Promise<void>}\n */\n async invalidate() {}\n /**\n * Asks the endpoint for the entries of the keys, sent as repeated `k`\n * parameters.\n * @param {...any} keys\n * @returns {Promise<SelectEntry[]>}\n * @throws when the request fails\n */\n async exact(...keys) {\n const response = await this.#http\n .request(this.#method, this.#url)\n .param('k', ...keys)\n .fetchJson();\n return this.#responseMapper(response);\n }\n /**\n * Asks the endpoint for the entries matching the needle, sent as the `s`\n * parameter; the filtering is the endpoint's.\n * @param {string|null} [needle]\n * @returns {Promise<SelectEntry[]>}\n * @throws when the request fails\n */\n async load(needle) {\n const response = await this.#http.request(this.#method, this.#url).param('s', needle).fetchJson();\n return this.#responseMapper(response);\n }\n}\n\n/** Serves a select's options from an array held in memory, which is what the slotted `<option>` elements become. */\nclass InMemoryLoader {\n #data;\n /**\n * @param {SelectEntry[]} data\n */\n constructor(data) {\n this.#data = data;\n }\n /**\n * Replaces the vocabulary every later question is answered from.\n * @param {SelectEntry[]} data\n */\n update(data) {\n this.#data = data;\n }\n /**\n * Does nothing: the vocabulary is the data itself, which only update replaces.\n * @returns {Promise<void>}\n */\n async invalidate() {}\n /**\n * The entries whose key loosely equals one of the keys, in vocabulary order.\n * @param {...any} keys\n * @returns {SelectEntry[]}\n */\n exact(...keys) {\n return byKeys(this.#data, keys);\n }\n /**\n * The entries whose label contains the needle, ignoring case; every entry\n * for a nullish or empty needle.\n * @param {string|null} [needle]\n * @returns {SelectEntry[]}\n */\n load(needle) {\n return byLabel(this.#data, needle);\n }\n}\n\n/**\n * Builds the select's loader from its attributes: the slotted options in\n * memory, or a remote or chunked loader over src. It is registered as the\n * `loaders:select` component.\n *\n * A component named by the select's `loader` attribute replaces this one: its\n * `create(el, conf)` answers an object with these methods, each answering\n * `{ key, label, metadata }` entries, directly or through a promise:\n *\n * - `load(needle)` answers the entries matching the typed text, all of them\n * when the needle is empty, which is the search the list opens with\n * - `exact(...keys)` answers the entries for those keys, used to label a value\n * assigned without going through the list; a key it leaves out is dropped\n * from the selection\n * - `prefetch()`, optional, warms the vocabulary; the select calls it at the\n * upgrade without waiting, and awaits it in `reload()`\n * - `invalidate()`, optional, drops whatever the loader holds, called by\n * `reload()`\n *\n * An entry whose `metadata.disabled` is truthy is shown and cannot be picked,\n * with `metadata.reason`, when present, as the row's title.\n */\nclass SelectLoader {\n /**\n * Builds a loader from a plain configuration, reading no dom: `data` alone\n * is the in-memory vocabulary, a `url` is fetched whole or, under\n * `mode: 'chunked'`, per query. A test, or a caller holding its own\n * configuration, builds a loader this way; `create` is the same thing with\n * an element's attributes parsed first.\n *\n * A remote loader fetches once and filters in memory, caching the response\n * in local storage under `method@url` when a revision is given; a chunked\n * one sends every search as `s` and every key lookup as `k`. The response\n * mapper turns the parsed response body into entries.\n * @param {{ data?: SelectEntry[], url?: undefined, http?: undefined, method?: undefined, mode?: undefined, prefetch?: undefined, revision?: undefined, responseMapper?: undefined }\n * | { data?: undefined, url: string, http: SelectHttpClient, method?: string, mode?: string, prefetch?: boolean, revision?: string|null, responseMapper: (response: any) => SelectEntry[] }} conf\n * `method` defaults to POST\n * @returns {InMemoryLoader|PartialRemoteLoader|RemoteLoader}\n */\n static from({ data, http, url, method = 'POST', mode, prefetch = false, revision = null, responseMapper }) {\n if (!url) {\n return new InMemoryLoader(data ?? []);\n }\n if ('chunked' === mode) {\n return new PartialRemoteLoader({ http, url, method, responseMapper });\n }\n return new RemoteLoader({ http, url, method, responseMapper, prefetch, revision });\n }\n /**\n * Builds the loader an element's attributes describe. Without `src` the\n * vocabulary is the `<option>` elements of `conf.options`, each keyed by its\n * `value` attribute or else its trimmed text. With `src` the url is\n * requested through the `http-client` component with `method` (POST by\n * default): once on first use, or at the upgrade under `preload`, or per\n * query under `mode=\"chunked\"`. A `revision` caches the whole response in local storage; a\n * valueless one takes the `revision` component, calling it when it is a\n * function, and warns and does not cache when none is registered.\n *\n * The response becomes entries through `k-expr` and `l-expr` evaluated on\n * each row of `d-expr` (the response itself by default), with `m-expr` as\n * the metadata (the row by default); else through the `response-mapper`\n * component; else each row is read as a `[key, label, metadata]` array.\n * @param {ParsedElement} el the element declaring the loader attributes\n * @param {{ options?: DocumentFragment }} conf\n * @returns {InMemoryLoader|PartialRemoteLoader|RemoteLoader}\n */\n static create(el, conf) {\n if (!el.declared('src')) {\n const els = Array.from(conf.options?.querySelectorAll('option') ?? []);\n return SelectLoader.from({\n data: els.map((e) => ({\n key: e.getAttribute('value') ?? e.innerText.trim(),\n label: e.innerText.trim(),\n metadata: undefined,\n })),\n });\n }\n return SelectLoader.from({\n http: el.component('http-client'),\n url: el.declared('src'),\n method: el.declared('method') ?? 'POST',\n mode: el.declared('mode'),\n prefetch: el.declared('preload'),\n revision: SelectLoader.#revisionFrom(el),\n responseMapper: SelectLoader.#responseMapperFrom(el),\n });\n }\n static #revisionFrom(el) {\n const declared = el.declared('revision');\n if (declared !== '') {\n return declared;\n }\n const configured = el.component('revision');\n if (configured === undefined || configured === null) {\n console.warn(\n \"a valueless revision asks the registry for one, and no 'revision' component is defined: the vocabulary will not be cached\",\n el,\n );\n return null;\n }\n return typeof configured === 'function' ? configured() : configured;\n }\n static #responseMapperFrom(el) {\n if (el.declared('k-expr') && el.declared('l-expr')) {\n return (response) => {\n const rows = el._registry\n .evaluator()\n .withOverlay(response)\n .evaluateExpression(el.declared('d-expr') ?? 'self');\n return rows.map((row) => {\n const evaluator = el._registry.evaluator().withOverlay(row);\n return {\n key: evaluator.evaluateExpression(el.declared('k-expr')),\n label: evaluator.evaluateExpression(el.declared('l-expr')),\n metadata: evaluator.evaluateExpression(el.declared('m-expr') ?? 'self'),\n };\n });\n };\n }\n if (el.declared('response-mapper')) {\n return el.component(el.declared('response-mapper'));\n }\n return (/** @type any[] */ response) => response.map(([key, label, metadata]) => ({ key, label, metadata }));\n }\n}\n\n/**\n * The options popup of a select, a `<ful-dropdown>` the owner shows as a\n * popover: a spinner while the loader runs, a localized empty state, and a\n * `role=\"listbox\"` menu of `role=\"option\"` rows.\n *\n * The owner drives it and listens to it. A pick dispatches a bubbling\n * `change` whose detail is `{ index, entry }`, the row's index as a string\n * and the entry it was rendered from. The active row is announced by a\n * non-bubbling `activechange` whose detail is `{ id }`, the row's id or null\n * when none is active, for the owner to set `aria-activedescendant`. A\n * pressed row does not take the focus from the owner's control.\n */\nclass Dropdown extends ParsedElement {\n /**\n * `listbox` is the id given to the menu, so an owner can set\n * `aria-controls` before this element upgrades; a generated id otherwise.\n */\n static attributes = ['listbox'];\n /** The default slot, when not blank, is the row template in place of the `options` template. */\n static slots = true;\n static template = `\n <ful-spinner class=\"centered\" role=\"status\" hidden><span class=\"ful-sr-only\">{{ #l10n:t('spinner.loading') }}</span></ful-spinner>\n <ful-empty data-ref=\"empty\" aria-live=\"polite\" hidden>{{ #l10n:t('dropdown.empty') }}</ful-empty>\n <menu tabindex=\"-1\" role=\"listbox\" hidden></menu>\n `;\n /**\n * `options` renders one row per entry, each entry carrying its `index`\n * beside its own keys. A replacement must keep one `<li>` per entry, in\n * order, with the index as its `value`: picking reads the entry back from it.\n */\n static templates = {\n options: `\n <li data-tpl-each=\"self\" data-tpl-selected=\"index == 0\" data-tpl-value=\"index\" role=\"option\">\n {{ label }}\n </li>\n `,\n };\n #spinner;\n #menu;\n #empty;\n #optionstemplate;\n #options = new Map();\n #shows = new Claims();\n /**\n * @param {{ slots: Record<string, DocumentFragment> }} conf\n */\n render({ slots }) {\n const fragment = this.template().render();\n this.#optionstemplate = Fragments.isBlank(slots.default)\n ? this.template('options')\n : Templates.fromFragment(slots.default);\n this.#spinner = fragment.querySelector('ful-spinner');\n this.#empty = fragment.querySelector('[data-ref=empty]');\n this.#menu = fragment.querySelector('menu');\n this.#menu.id = this.declared('listbox') || Attributes.uid('ful-listbox');\n this.#menu.addEventListener('mousedown', (evt) => {\n if (evt.target.closest('li')) {\n evt.preventDefault();\n }\n });\n this.#menu.addEventListener('click', (evt) => {\n evt.stopPropagation();\n const li = evt.target.closest('li');\n if (!li) {\n this.hide();\n return;\n }\n if (li.matches('[aria-disabled=\"true\"]')) {\n return;\n }\n this.#change(li);\n });\n this.replaceChildren(fragment);\n }\n #selected() {\n return (\n this.#menu?.querySelector('[selected]:not([aria-disabled=\"true\"])') ??\n this.#menu?.querySelector('li:not([aria-disabled=\"true\"])') ??\n null\n );\n }\n #highlight(li) {\n if (!li) {\n this.#activated(null);\n return;\n }\n for (const el of this.#menu.querySelectorAll('li')) {\n el.toggleAttribute('selected', el === li);\n }\n li.id ||= Attributes.uid('ful-option');\n this.#activated(li.id);\n li.scrollIntoView({\n block: 'nearest',\n behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth',\n });\n }\n /**\n * Picks the highlighted row, or the first enabled one when none is: hides\n * the dropdown and dispatches `change`. Does nothing when no row is enabled.\n */\n acceptSelection() {\n const selected = this.#selected();\n if (!selected) {\n return;\n }\n this.#change(selected);\n }\n /**\n * Renders the entries as rows and highlights the first one whose key is\n * picked, else the row the template marked `selected`, else the first\n * enabled row. A row is marked `picked` and\n * `aria-selected=\"true\"` when its key loosely equals one of the keys, and\n * `aria-disabled=\"true\"` when its `metadata.disabled` is truthy, titled with\n * `metadata.reason`. No entries shows the empty state instead of the menu.\n * @param {SelectEntry[]} values\n * @param {any[]} [keys] the keys currently selected\n * @throws {Error} when values is undefined\n */\n update(values, keys = []) {\n if (values === undefined) {\n throw new Error('null data');\n }\n this.#options = new Map(values.map((v, i) => [String(i), v]));\n const data = values.map((entry, index) => ({ index, ...entry }));\n this.#optionstemplate.withOverlay(data).renderTo(this.#menu);\n for (const [index, li] of [...this.#menu.children].entries()) {\n const entry = values[index];\n const picked = keys.some((r) => r == entry?.key);\n li.toggleAttribute('picked', picked);\n li.setAttribute('aria-selected', picked ? 'true' : 'false');\n const disabled = !!entry?.metadata?.disabled;\n if (disabled) {\n li.setAttribute('aria-disabled', 'true');\n } else {\n li.removeAttribute('aria-disabled');\n }\n if (disabled && entry.metadata.reason) {\n li.setAttribute('title', String(entry.metadata.reason));\n } else {\n li.removeAttribute('title');\n }\n }\n this.#empty.toggleAttribute('hidden', values.length !== 0);\n this.#menu.toggleAttribute('hidden', values.length === 0);\n const current = values.findIndex(({ key }) => keys.some((r) => r == key));\n this.#highlight(current >= 0 ? this.#menu.children[current] : this.#selected());\n }\n #change(target) {\n const index = target.getAttribute('value');\n const entry = this.#options.get(index);\n this.hide();\n this.dispatchEvent(\n new CustomEvent('change', {\n bubbles: true,\n cancelable: false,\n detail: { index, entry },\n }),\n );\n }\n /**\n * Closes the popover, if open, and announces that no row is active. A\n * `show` still waiting on its loader is superseded: its outcome is neither\n * rendered nor thrown.\n */\n hide() {\n this.#shows.invalidate();\n if (this.matches(':popover-open')) {\n this.hidePopover();\n }\n this.#activated(null);\n }\n #activated(id) {\n this.dispatchEvent(new CustomEvent('activechange', { bubbles: false, cancelable: false, detail: { id } }));\n }\n /**\n * Whether the popover is open.\n * @returns {boolean}\n */\n get shown() {\n return this.matches(':popover-open');\n }\n /**\n * Opens the popover with the spinner showing, then renders what the loader\n * answers as `update` does. A show overtaken by a later `show` or by `hide`\n * before its loader settles leaves the dropdown alone and resolves, even\n * when its loader rejected.\n * @param {() => SelectEntry[]|Promise<SelectEntry[]>} loader\n * @param {any[]} [keys] the keys currently selected\n * @returns {Promise<void>}\n * @throws what the loader threw, after hiding the dropdown, when this show\n * is still the current one\n */\n async show(loader, keys = []) {\n const claim = this.#shows.take();\n if (!this.matches(':popover-open')) {\n this.showPopover();\n }\n this.#menu.setAttribute('hidden', '');\n this.#spinner.removeAttribute('hidden');\n try {\n const data = await loader();\n if (claim.stale) {\n return;\n }\n this.update(data, keys);\n } catch (/** @type any */ e) {\n if (claim.stale) {\n return;\n }\n this.hide();\n throw e;\n } finally {\n if (!claim.stale) {\n this.#spinner.setAttribute('hidden', '');\n }\n }\n }\n /**\n * Moves the highlight to the next or previous enabled row when the dropdown\n * is shown, staying put at the edge, and shows it otherwise.\n * @param {boolean} forward\n * @param {() => SelectEntry[]|Promise<SelectEntry[]>} loader used only to show\n * @param {any[]} [keys] the keys currently selected, used only to show\n * @returns {Promise<void>}\n * @throws what `show` throws\n */\n async moveOrShow(forward, loader, keys = []) {\n if (this.shown) {\n const selected = this.#selected();\n const candidate = selected?.[`${forward ? 'next' : 'previous'}ElementSibling`];\n const target = candidate ? this.#walk(candidate, forward) : null;\n if (selected && target) {\n this.#highlight(target);\n }\n return;\n }\n await this.show(loader, keys);\n }\n #walk(from, forward) {\n for (let li = from; li; li = li[`${forward ? 'next' : 'previous'}ElementSibling`]) {\n if (!li.matches('[aria-disabled=\"true\"]')) {\n return li;\n }\n }\n return null;\n }\n /**\n * Highlights the first enabled row, or the last one.\n * @param {boolean} first\n */\n jump(first) {\n const edge = first ? this.#menu.firstElementChild : this.#menu.lastElementChild;\n const target = this.#walk(edge, first);\n if (target) {\n this.#highlight(target);\n }\n }\n /**\n * Moves the highlight by as many enabled rows as the menu shows at once,\n * one when that cannot be measured, stopping at the last enabled row.\n * @param {boolean} forward\n */\n page(forward) {\n const selected = this.#selected();\n if (!selected) {\n return;\n }\n let target = selected;\n for (let i = 0; i !== this.#page(); ++i) {\n const next = this.#walk(target[`${forward ? 'next' : 'previous'}ElementSibling`], forward);\n if (!next) {\n break;\n }\n target = next;\n }\n this.#highlight(target);\n }\n #page() {\n const first = this.#menu.firstElementChild;\n if (!first || first.offsetHeight === 0) {\n return 1;\n }\n return Math.max(1, Math.trunc(this.#menu.clientHeight / first.offsetHeight));\n }\n}\n\n/**\n * A `<ful-select>`: a combobox over a loader's vocabulary of\n * `{ key, label, metadata }` entries, holding one key or, under `multiple`,\n * several. Typing filters the list, opening it from rest offers the whole\n * vocabulary, and the keyboard follows the combobox pattern: arrows move and\n * open (Alt+ArrowDown opens, Alt+ArrowUp closes), Home, End, PageUp and\n * PageDown move in the open list, Enter accepts the highlighted entry or,\n * with the list closed, submits the form, Escape reverts the edit, and Tab\n * or leaving the field commits it. Emptying the text of a single select and\n * leaving the field clears it. Backspace with the caret at the start removes\n * the last entry, and ArrowLeft there moves the focus to the badges of a\n * multiple select, where Enter, Space, Backspace or Delete remove one.\n *\n * Slots: the default one is the label, `info` sits beside it, `before` and\n * `after` are affixes around the control, `options` holds the `<option>`\n * elements of an in-memory vocabulary, `dropdown` replaces the dropdown's\n * row template and `items` the `items` template.\n *\n * Every change of the selection made through the element dispatches a\n * bubbling `change` whose detail carries `value` and `entry`, as the getters\n * answer them; assigning `value` dispatches none.\n */\nclass Select extends Field {\n /**\n * Read once at the upgrade, so a later write changes nothing: `name`,\n * `loader` (the component building the loader, `loaders:select` by\n * default), `k-type` (`number` or `boolean` coerce the keys, strings\n * otherwise), and the loader configuration `SelectLoader.create` reads,\n * but for `src` and `method`, which stay live.\n */\n static attributes = [\n 'name',\n 'loader',\n 'k-type',\n 'mode',\n 'preload:presence',\n 'revision',\n 'k-expr',\n 'l-expr',\n 'd-expr',\n 'm-expr',\n 'response-mapper',\n ];\n /**\n * Beside the field's claims: `multiple`, `item-list`, `value` as a comma\n * separated list of keys, trimmed, whether or not the select is multiple,\n * and `src` and `method`.\n */\n static observed = ['multiple:presence', 'item-list:presence', 'value:csv', 'src', 'method'];\n /**\n * Reads a present but empty `value` attribute of a single select as the\n * empty key, which an `<option value=\"\">` can carry; a multiple select reads\n * it as no keys.\n * @param {string} attr\n * @param {string|null} str\n * @returns {any}\n * @throws when the class declares no such attribute\n */\n unmarshal(attr, str) {\n if (attr === 'value' && str === '' && !this.hasAttribute('multiple')) {\n return [''];\n }\n return super.unmarshal(attr, str);\n }\n static slots = true;\n static template = `\n <label>{{{{ slots.default }}}}</label>\n {{{{ slots.info }}}}\n <ful-control-group>\n <ful-affix data-tpl-if=\"slots.before\">{{{{ slots.before }}}}</ful-affix>\n <ful-control>\n <input type=\"text\" form=\"\" autocomplete=\"off\" role=\"combobox\" aria-autocomplete=\"list\" aria-haspopup=\"listbox\" aria-expanded=\"false\">\n </ful-control>\n <ful-affix data-tpl-if=\"slots.after\">{{{{ slots.after }}}}</ful-affix>\n <ful-dropdown popover=\"manual\">{{{{ slots.dropdown }}}}</ful-dropdown>\n </ful-control-group>\n <ful-item-list></ful-item-list>\n <ful-field-error></ful-field-error>\n `;\n /**\n * `items` renders the selection below the control, shown under `item-list`,\n * over `entries`, the selected entries in order. A replacement must keep one\n * `<ful-item>` per entry, in order, each with a `<button>` that removes it.\n */\n static templates = {\n items: `\n <ful-item data-tpl-each=\"entries\" data-tpl-var=\"entry\" data-tpl-data-key=\"entry.key\">\n <div><span>{{ entry.label }}</span><button type=\"button\" data-tpl-aria-label=\"#l10n:t('select.remove')\"><ful-icon name=\"x-lg\" aria-hidden=\"true\"></ful-icon></button></div>\n </ful-item>\n `,\n };\n #loader;\n /** @type {{ src: string|null, method: string|null }} */\n #builtFrom = { src: null, method: null };\n #options;\n #control;\n #ddmenu;\n #input;\n #items;\n #itemstemplate;\n #multiple;\n #warnedComma = false;\n #values = new Map();\n #assignments = new Claims();\n #editing = false;\n #dload;\n #abortdload;\n /**\n * @param {{ slots: Record<string, DocumentFragment> }} conf\n * @returns {{ fragment: DocumentFragment, control: HTMLInputElement, error: Element|null, label: Element|null }}\n */\n _build({ slots }) {\n const name = this.declared('name');\n this.#options = slots.options;\n this.#buildLoader();\n\n this.#multiple = this.declared('multiple');\n this.#loader.prefetch?.()?.catch((/** @type any */ e) => {\n console.warn('failed to prefetch select options', this, 'reason:', e);\n });\n const fragment = this.template().withOverlay({ slots, name }).render();\n this.#input = fragment.querySelector('ful-control > input');\n this.#items = fragment.querySelector('ful-item-list');\n this.#itemstemplate =\n slots.items && !Fragments.isBlank(slots.items) ? Templates.fromFragment(slots.items) : null;\n Attributes.forward('input-', this, this.#input);\n this.#control = fragment.querySelector('ful-control');\n\n this.#ddmenu = fragment.querySelector('ful-dropdown');\n const listbox = Attributes.uid('ful-listbox');\n this.#ddmenu.setAttribute('listbox', listbox);\n this.#input.setAttribute('aria-controls', listbox);\n this.#ddmenu.addEventListener('beforetoggle', (/** @type any */ e) => {\n const open = e.newState === 'open';\n this.#input.setAttribute('aria-expanded', open ? 'true' : 'false');\n if (!open) {\n this.#input.removeAttribute('aria-activedescendant');\n }\n });\n this.#ddmenu.addEventListener('activechange', (/** @type any */ e) => {\n Attributes.set(this.#input, 'aria-activedescendant', e.detail.id);\n });\n const group = /** @type {HTMLElement} */ (fragment.querySelector('ful-control-group'));\n Anchors.wire(group, this.#ddmenu, { prefix: 'ful-select', stretch: true });\n [this.#dload, this.#abortdload] = Timing.throttle(400, () => this.#open());\n this.#wireChrome();\n this.#wireChips();\n this.#wireInput();\n this.#wireSelection();\n return {\n fragment,\n control: this.#input,\n error: fragment.querySelector('ful-field-error'),\n label: fragment.querySelector('label'),\n };\n }\n /**\n * Pointer interaction: the element toggles the dropdown, the item list's\n * remove buttons and the control's badges drop their entry.\n */\n #wireChrome() {\n this.addEventListener('click', (/** @type any */ e) => {\n if (!this._interactive()) {\n return;\n }\n const elsewhere = e.target.closest('button, [role=\"button\"], a[href], input, select, textarea');\n if (elsewhere && elsewhere !== this.#input) {\n return;\n }\n if (this.#ddmenu.shown) {\n this.#close();\n return;\n }\n this.#input.focus();\n this.#dload();\n });\n this.#items.addEventListener('click', (e) => {\n e.stopPropagation();\n if (!e.target.closest('button')) {\n return;\n }\n if (!this._interactive()) {\n return;\n }\n this.#removeKeyAt([...this.#items.children].indexOf(e.target.closest('ful-item')));\n });\n this.#control.addEventListener('click', (e) => {\n const badge = e.target instanceof Element ? e.target.closest('ful-badge') : null;\n if (!badge) {\n return;\n }\n e.stopPropagation();\n this.#removeBadge(badge);\n });\n }\n /**\n * Keyboard interaction over the chips: Enter/Space/Backspace/Delete remove,\n * arrows move between badges and the input, Escape returns to the input.\n */\n #wireChips() {\n this.addEventListener('keydown', (/** @type any */ e) => {\n const badge = e.target instanceof Element ? e.target.closest('ful-badge') : null;\n if (badge) {\n this.#chipKeydown(e, badge);\n return;\n }\n if (\n 'ArrowLeft' === e.code &&\n e.target === this.#input &&\n this.#input.selectionStart === 0 &&\n this.#input.selectionEnd === 0\n ) {\n this.#badges().at(-1)?.focus();\n }\n });\n }\n #wireInput() {\n this.#input.addEventListener('change', (e) => {\n e.stopPropagation();\n });\n this.#input.addEventListener('focus', () => {\n if (this.#editing) {\n return;\n }\n this.#input.select();\n });\n this.#input.addEventListener('blur', (e) => {\n e.stopPropagation();\n if (e.relatedTarget && this.contains(e.relatedTarget)) {\n return;\n }\n this.#abortdload();\n this.#close(true);\n });\n this.#input.addEventListener('keydown', (e) => {\n if (!this._interactive()) {\n return;\n }\n this.#comboboxKeydown(e);\n });\n this.#input.addEventListener('input', (e) => {\n e.stopPropagation();\n if (!this._interactive()) {\n return;\n }\n this.#editing = true;\n this.#dload();\n });\n }\n #wireSelection() {\n this.#ddmenu.addEventListener('change', (e) => {\n e.stopPropagation();\n if (!this._interactive()) {\n this.#close();\n return;\n }\n if (!this.#multiple) {\n this.#values.clear();\n }\n this.#editing = false;\n this.#values.set(this.#coerceKey(e.detail.entry.key), e.detail.entry);\n this.#changed();\n this.#input.focus();\n this.#ddmenu.hide();\n if (!this.#multiple) {\n this.#input.select();\n }\n });\n }\n /**\n * Hands the loader to the callback, for runtime changes such as\n * `update(entries)` on an in-memory loader.\n * @template T\n * @param {(loader: any) => T|Promise<T>} fn\n * @returns {Promise<T>} what the callback answers\n */\n async withLoader(fn) {\n return await fn(this.#loader);\n }\n /**\n * Drops whatever the loader is holding, awaits its prefetch (which fetches\n * again when the select declares `preload`), and asks it about the current\n * selection again, which is what a select whose vocabulary depends on\n * another control needs when that control changes. A key the loader no\n * longer knows is dropped from the selection, so a value invalidated by the\n * change does not survive it, and one it still knows keeps its place with a\n * fresh label. The badges and items follow, and no `change` is dispatched.\n *\n * Where the vocabulary lives at a different address, write `src` or call\n * `reconfigure`, which build the loader for the new url and reload.\n * @returns {Promise<void>}\n * @throws what the loader's invalidate, prefetch or key lookup throws\n */\n async reload() {\n await this.#loader.invalidate?.();\n await this.#loader.prefetch?.();\n const keys = [...this.#values.keys()];\n if (keys.length === 0) {\n return;\n }\n await this.#resolve(keys, this.#assignments.take());\n }\n /**\n * The url the loader asks for the vocabulary, reflected as the `src`\n * attribute.\n * @returns {string|null}\n */\n get src() {\n return this.getAttribute('src');\n }\n /**\n * Points the select at another vocabulary: the dropdown closes, the loader\n * is built again through its component's `create`, as at the render, and\n * the select reloads as `reload()` does, so a selected key the new\n * vocabulary does not know is dropped and one it knows is labelled again,\n * with no `change` dispatched. A write that does not change the url does\n * nothing.\n *\n * The reload is not awaited: a failed fetch or lookup surfaces as an\n * unhandled rejection.\n * @param {string|null|undefined} value null or undefined removes the url,\n * which the default loader answers with the slotted options\n */\n set src(value) {\n this.reflectTo('src', value ?? null);\n if (this.#followAttributes()) {\n this.reload();\n }\n }\n /**\n * The http method the default loader sends, reflected as the `method`\n * attribute; `POST` when absent.\n * @returns {string|null}\n */\n get method() {\n return this.getAttribute('method');\n }\n /**\n * Changes the http method the way `src` changes the url: the loader is\n * built again and the select reloads.\n * @param {string|null|undefined} value\n */\n set method(value) {\n this.reflectTo('method', value ?? null);\n if (this.#followAttributes()) {\n this.reload();\n }\n }\n /**\n * Writes `src` and `method` together and reloads once: the loader is built\n * again for the pair when either changed, as a single write of either does,\n * and the select then reloads as `reload()` does, whether or not they\n * changed.\n *\n * citta.addEventListener('change', () => {\n * cap.reconfigure({ src: `/api/cap?citta=${citta.value}` }, { notify: true });\n * });\n * @param {{ src?: string|null, method?: string|null }} attributes a name\n * left out keeps its value, null removes the attribute\n * @param {{ notify?: boolean }} [options] `notify` dispatches `change` when\n * the reload dropped a selected key, so a form or a table filtered by the\n * select sees the value it lost; nothing is dispatched otherwise\n * @returns {Promise<void>} settling once the reload has\n * @throws what the loader's invalidate, prefetch or key lookup throws\n */\n async reconfigure(attributes, { notify = false } = {}) {\n for (const name of ['src', 'method']) {\n if (name in attributes) {\n this.reflectTo(name, attributes[name] ?? null);\n }\n }\n this.#followAttributes();\n const before = [...this.#values.keys()];\n await this.reload();\n const after = [...this.#values.keys()];\n if (notify && after.length !== before.length) {\n this._notifyChange({ entry: this.entry });\n }\n }\n #buildLoader() {\n this.#builtFrom = { src: this.getAttribute('src'), method: this.getAttribute('method') };\n this.#loader = this.component(this.declared('loader') ?? 'loaders:select').create(this, {\n options: this.#options,\n });\n }\n /** @returns {boolean} whether the loader was built again */\n #followAttributes() {\n if (\n this.getAttribute('src') === this.#builtFrom.src &&\n this.getAttribute('method') === this.#builtFrom.method\n ) {\n return false;\n }\n this.#abortdload();\n this.#close();\n this.#buildLoader();\n return true;\n }\n #badges() {\n return Array.from(this.#control.querySelectorAll(':scope > ful-badge'));\n }\n #removeBadge(badge) {\n if (!this._interactive()) {\n return;\n }\n this.#removeKeyAt(this.#badges().indexOf(badge));\n }\n /** Badges and item list entries share the selection's order, so one index serves both. */\n #removeKeyAt(index) {\n const key = Array.from(this.#values.keys())[index];\n if (key === undefined) {\n return;\n }\n this.#values.delete(key);\n this.#changed();\n }\n #chipKeydown(e, badge) {\n switch (e.code) {\n case 'NumpadEnter':\n case 'Enter':\n case 'Space':\n case 'Backspace':\n case 'Delete': {\n e.preventDefault();\n this.#removeBadge(badge);\n this.#input.focus();\n break;\n }\n case 'ArrowLeft': {\n e.preventDefault();\n (this.#badges()[this.#badges().indexOf(badge) - 1] ?? this.#input).focus();\n break;\n }\n case 'ArrowRight': {\n e.preventDefault();\n (this.#badges()[this.#badges().indexOf(badge) + 1] ?? this.#input).focus();\n break;\n }\n case 'Escape': {\n this.#input.focus();\n break;\n }\n }\n }\n /**\n * The combobox keyboard contract: arrows browse and move, Home/End and\n * PageUp/PageDown navigate the open list, Enter accepts or submits,\n * Escape/Tab close, Backspace at the caret's leftmost spot drops the last\n * entry.\n */\n #comboboxKeydown(e) {\n switch (e.code) {\n case 'ArrowUp':\n case 'ArrowDown': {\n e.preventDefault();\n this.#arrowKeydown(e);\n break;\n }\n case 'Home': {\n if (this.#ddmenu.shown) {\n e.preventDefault();\n this.#ddmenu.jump(true);\n }\n break;\n }\n case 'End': {\n if (this.#ddmenu.shown) {\n e.preventDefault();\n this.#ddmenu.jump(false);\n }\n break;\n }\n case 'PageDown':\n case 'PageUp': {\n if (this.#ddmenu.shown) {\n e.preventDefault();\n this.#ddmenu.page('PageDown' === e.code);\n }\n break;\n }\n case 'Escape': {\n this.#abortdload();\n this.#close();\n break;\n }\n case 'NumpadEnter':\n case 'Enter': {\n if (!this.#ddmenu.shown) {\n return;\n }\n e.preventDefault();\n this.#editing = false;\n this.#display();\n this.#ddmenu.acceptSelection();\n break;\n }\n case 'Backspace': {\n if (this.#input.selectionStart === 0 && this.#input.selectionEnd === 0) {\n this.#removeKeyAt(this.#values.size - 1);\n }\n break;\n }\n case 'Tab': {\n this.#abortdload();\n this.#close(true);\n break;\n }\n }\n }\n #arrowKeydown(e) {\n const forward = 'ArrowDown' === e.code;\n if (e.altKey) {\n if (forward && !this.#ddmenu.shown) {\n this.#open();\n } else if (!forward && this.#ddmenu.shown) {\n this.#close();\n }\n return;\n }\n this.#ddmenu.moveOrShow(forward, () => this.#loader.load(this.#query()), [...this.#values.keys()]);\n }\n /**\n * @param {boolean} [commit] whether the user is leaving the field, which\n * only a blur or a Tab is: an emptied single select is then cleared\n */\n #close(commit = false) {\n this.#ddmenu.hide();\n const cleared =\n commit && this.#editing && !this.#multiple && this.#input.value === '' && this.#values.size !== 0;\n this.#editing = false;\n if (cleared) {\n this.#values.clear();\n this.#changed();\n }\n this.#display();\n }\n #open() {\n return this.#ddmenu.show(() => this.#loader.load(this.#query()), [...this.#values.keys()]);\n }\n #query() {\n return this.#editing ? this.#input.value : '';\n }\n /**\n * The text typed to search the vocabulary: what the dropdown was last\n * asked to match. `''` while the field is not being searched, its control\n * then showing the selection's label rather than a query.\n * @returns {string}\n */\n get query() {\n return this.#query();\n }\n #display() {\n const entry = this.#values.values().next().value;\n this.#input.value = this.#multiple ? '' : (entry?.label ?? '');\n }\n #selection() {\n return [...this.#values.values()];\n }\n #changed() {\n this.#syncBadges();\n this._notifyChange({ entry: this.entry });\n }\n #syncBadges() {\n const badges = this.#multiple\n ? Array.from(this.#values.entries()).map(([k, entry], index) => {\n const b = document.createElement('ful-badge');\n b.setAttribute('role', 'button');\n b.setAttribute('tabindex', index === 0 ? '0' : '-1');\n b.setAttribute('value', k);\n b.innerText = entry.label;\n return b;\n })\n : [];\n for (const b of this.#control.querySelectorAll(':scope > ful-badge')) {\n b.remove();\n }\n this.#input.before(...badges);\n if (!this.#editing) {\n this.#display();\n }\n this.#items.replaceChildren();\n (this.#itemstemplate ?? this.template('items'))\n .withOverlay({ entries: this.#selection() })\n .renderTo(this.#items);\n }\n /**\n * The selection is a Map keyed strictly, and keys arrive both as attribute\n * text and as whatever a loader's endpoint carries: every key entering it\n * goes through here. A key that does not decode is left as it is.\n */\n #coerceKey(k) {\n switch (this.declared('k-type')) {\n case 'number': {\n const n = k === '' ? Number.NaN : Number(k);\n return Number.isNaN(n) ? k : n;\n }\n case 'boolean': {\n if (k === true || k === 'true') {\n return true;\n }\n if (k === false || k === 'false') {\n return false;\n }\n return k;\n }\n default:\n return String(k);\n }\n }\n /**\n * Selects the keys, coerced by `k-type`: a key, an array of keys, or null or\n * undefined for none. The empty string is a key like any other. The keys\n * are applied at once, each labeled by itself until the loader's `exact`\n * answers; a key it does not answer is then dropped, a key removed in the\n * meantime stays removed, and a later assignment wins over the late answer.\n * A failed lookup keeps the keys and surfaces as an unhandled rejection.\n * No `change` is dispatched. A key containing a\n * comma, which the value attribute cannot carry, is kept and warned about\n * once per element.\n * @param {any} vs\n */\n set value(vs) {\n const keys = (vs == null ? [] : Array.isArray(vs) ? vs : [vs]).map((k) => this.#coerceKey(k));\n if (!this.#warnedComma && keys.some((k) => typeof k === 'string' && k.includes(','))) {\n this.#warnedComma = true;\n console.warn('a ful-select key cannot contain a comma: it is unexpressible in the value attribute', this);\n }\n this.#values = new Map(keys.map((k) => [k, { key: k, label: k, metadata: undefined }]));\n const claim = this.#assignments.take();\n if (!this.#control) {\n return;\n }\n this.#syncBadges();\n if (keys.length === 0) {\n return;\n }\n this.#resolve(keys, claim);\n }\n async #resolve(keys, claim) {\n const entries = await this.#loader.exact(...keys);\n if (claim.stale) {\n return;\n }\n const resolved = new Map(entries.map((e) => [this.#coerceKey(e.key), e]));\n for (const key of keys) {\n if (!this.#values.has(key)) {\n continue;\n }\n if (resolved.has(key)) {\n this.#values.set(key, resolved.get(key));\n } else {\n this.#values.delete(key);\n }\n }\n this.#syncBadges();\n }\n /**\n * The selected keys, in selection order, for a multiple select; the one\n * key, or null, for a single one.\n * @returns {any}\n */\n get value() {\n if (this.#multiple) {\n return [...this.#values.keys()];\n }\n return [...this.#values.keys()][0] ?? null;\n }\n /**\n * The selection as entries, the ones in the `change` detail: an array for\n * a multiple select, the one entry or null for a single one. An entry whose\n * label has not been resolved yet carries its key as the label.\n * @returns {SelectEntry|SelectEntry[]|null}\n */\n get entry() {\n const selection = this.#selection();\n if (this.#multiple) {\n return selection;\n }\n return selection[0] ?? null;\n }\n #useItemList;\n /**\n * Whether the select holds several keys: `value` and `entry` answer arrays,\n * the input stays empty and the selection shows as removable badges in the\n * control.\n * @returns {boolean}\n */\n get multiple() {\n return this.#multiple;\n }\n /** @param {boolean} v */\n set multiple(v) {\n this.#multiple = v;\n this.reflectTo('multiple', v);\n }\n /**\n * Whether the selection shows as the `items` list below the control instead\n * of as badges in it.\n * @returns {boolean}\n */\n get itemList() {\n return this.#useItemList;\n }\n /** @param {boolean} v */\n set itemList(v) {\n this.#useItemList = v;\n this.reflectTo('item-list', v);\n }\n}\n\nexport { Dropdown, Select, SelectLoader };\n","import { Attributes, Fragments } from '../../ftl/index.mjs';\nimport { Field } from './field.mjs';\n\n/**\n * A group of radios declared as `ful-radio` children. Each `ful-radio` becomes\n * a radio input carrying its attributes, labelled by its content; every\n * `input-*` attribute on the group is forwarded onto each radio as well. The\n * default slot is the `<legend>`, and `header` and `footer` slots frame the\n * list. The radios share a name of their own (derived from `name`, or minted\n * when there is none) and carry `form=\"\"`, so the group is the only element\n * the form sees. A radio's native `change` is stopped and republished as the\n * group's own.\n *\n * The host carries the `radiogroup` role, `aria-readonly`, `aria-required`,\n * `aria-invalid` and the description. The disabled and readonly claims act on\n * the group's `<fieldset>`, and readonly refuses every click inside it.\n * `focus()` lands on the first radio.\n */\nclass RadioGroup extends Field {\n /** @type {string[]} */\n static attributes = ['name', 'type'];\n static slots = true;\n /** @type {string} */\n static ROLE = 'radiogroup';\n static template = `\n <fieldset>\n <legend>\n {{{{ slots.default }}}}\n </legend>\n <header data-tpl-if=\"slots.header\">\n {{{{ slots.header }}}}\n </header>\n <ful-radio-list>\n <div class=\"label-wrapper\" data-tpl-each=\"inputsAndLabels\" data-tpl-var=\"ial\">\n <label>\n {{{{ ial[0] }}}}\n <div>{{{{ ial[1] }}}}</div>\n </label>\n </div>\n </ful-radio-list>\n <ful-field-error></ful-field-error>\n <footer data-tpl-if=\"slots.footer\">\n {{{{ slots.footer }}}}\n </footer>\n </fieldset>\n `;\n #fieldset;\n #firstRadio;\n #booleanType;\n /**\n * @param {{slots: any}} conf\n * @returns {any} the pieces: the first radio as the control, the fieldset\n * as the `claims` and `freeze` pieces, and the host as the `described` and\n * `announces` pieces\n */\n _build({ slots }) {\n const name = this.declared('name') ?? Attributes.uid('ful-radiogroup');\n const radioEls = Array.from(slots.default.querySelectorAll('ful-radio'));\n const inputsAndLabels = radioEls.map((el) => {\n const input = document.createElement('input');\n input.setAttribute('type', 'radio');\n Attributes.forward('input-', this, input);\n Attributes.forward('', el, input);\n input.setAttribute('name', `${name}-ignore`);\n input.setAttribute('form', ``);\n input.addEventListener('change', (evt) => {\n evt.stopPropagation();\n this._notifyChange();\n });\n const label = Fragments.fromChildNodes(el);\n return [input, label];\n });\n\n radioEls.forEach((el) => {\n el.remove();\n });\n const fragment = this.template().withOverlay({ name, slots, inputsAndLabels }).render();\n this.#fieldset = /** @type HTMLElement */ (fragment.firstElementChild);\n this.#firstRadio = fragment.querySelector('input[type=radio]');\n this.#booleanType = this.declared('type') === 'boolean';\n return {\n fragment,\n control: this.#firstRadio,\n error: fragment.querySelector('ful-field-error'),\n described: this,\n claims: this.#fieldset,\n announces: this,\n freeze: this.#fieldset,\n };\n }\n /**\n * The value of the checked radio, `null` when none is. Under\n * `type=\"boolean\"` it answers `true` for a radio whose value is `true` and\n * `false` for any other. Writing a value checks the radio carrying it, and\n * writing `null` or a value no radio carries clears the selection.\n * @type {string | boolean | null}\n */\n get value() {\n /** @type {HTMLInputElement|null} */\n const checked = this.querySelector('input[type=radio]:checked');\n return checked ? (this.#booleanType ? checked.value === 'true' : checked.value) : null;\n }\n set value(value) {\n const radios = this.querySelectorAll(`input[type=radio]`);\n const clear = () => {\n radios.forEach((el) => {\n /** @type {HTMLInputElement} */ (el).checked = false;\n });\n };\n if (value === null) {\n clear();\n return;\n }\n /** @type {HTMLInputElement|null} */\n const el = this.querySelector(`input[type=radio][value=\"${CSS.escape(String(value))}\"]`);\n if (el === null) {\n clear();\n return;\n }\n el.checked = true;\n }\n}\n\nexport { RadioGroup };\n","import { Attributes } from '../../ftl/index.mjs';\nimport { Field } from './field.mjs';\n\n/**\n * A checkbox, or a switch with the `switch` role under `type=\"switch\"`. The\n * label is the default slot, pointed at the input with `for` and `id`, so a\n * click on it toggles the value. Every `input-*` attribute is forwarded onto\n * the input. The input's native `change` is stopped and republished as the\n * field's own. Readonly freezes the whole choice, label included: no click\n * inside it toggles the value while the claim holds.\n */\nclass Checkbox extends Field {\n /** @type {string[]} */\n static attributes = ['type'];\n /** @type {string[]} */\n static observed = ['value:bool'];\n static slots = true;\n static template = `\n <ful-choice data-tpl-switch=\"isSwitch\">\n <input type=\"checkbox\" data-tpl-role=\"isSwitch ? 'switch' : false\" form=\"\">\n <label>{{{{ slots.default }}}}</label>\n {{{{ slots.info }}}}\n </ful-choice>\n <ful-field-error></ful-field-error>\n `;\n #container;\n #input;\n /**\n * @param {{ slots: Record<string, DocumentFragment> | undefined }} conf\n * @returns {any} the pieces, the `ful-choice` container being the `freeze` piece\n */\n _build({ slots }) {\n const isSwitch = this.declared('type') === 'switch';\n const fragment = this.template().withOverlay({ slots, isSwitch }).render();\n this.#container = fragment.firstElementChild;\n this.#input = fragment.querySelector('input');\n Attributes.forward('input-', this, this.#input);\n this.#input.addEventListener('change', (evt) => {\n evt.stopPropagation();\n this._notifyChange();\n });\n const label = fragment.querySelector('label');\n return {\n fragment,\n control: this.#input,\n error: fragment.querySelector('ful-field-error'),\n label,\n freeze: this.#container,\n };\n }\n /**\n * Whether the box is checked. The `value` attribute is read with the `bool`\n * mapper, where only the text `true` means checked.\n * @type {boolean}\n */\n get value() {\n return this.#input.checked;\n }\n set value(value) {\n this.#input.checked = value;\n }\n}\n\nexport { Checkbox };\n","import { Attributes, Fragments, Localization, Nodes, ParsedElement, Rendering, Templates } from '../../ftl/index.mjs';\nimport { Claims } from '../claims.mjs';\n\n/**\n * @typedef {{ page: number, size: number }} TablePageRequest the zero based\n * index of the page and the number of rows in a page\n */\n/**\n * @typedef {{ sorter: string, order: string }} TableSortRequest the sort key\n * of a column and its direction, `asc` or `desc`\n */\n/**\n * @typedef {{ data: any[], size: number }} TablePageResponse the rows of the\n * requested page and the total number of rows across every page\n */\n/**\n * @typedef {{ load(pageRequest: TablePageRequest, sortRequest: TableSortRequest|null, filterRequest: Record<string, any>): Promise<TablePageResponse> }} TableRowLoader\n */\n\n/**\n * The sort control of a table header, `ful-sorter`: a `role=\"button\"` with\n * `tabindex=\"0\"`, activated by a click or by Enter, NumpadEnter or Space.\n *\n * Each activation dispatches `sort:requested` (bubbling, not cancelable) with\n * `detail.value` set to `{ sorter, order }`: `sorter` is the `sorter`\n * attribute, read once at the upgrade, and `order` is the one after the\n * current `order` in the cycle `asc`, `desc`, `null`. The button does not\n * change its own `order`: whoever handles the event sets it, which `ful-table`\n * does once the sorted page has loaded.\n */\nclass SortButton extends ParsedElement {\n static attributes = ['sorter'];\n static observed = ['order'];\n #order;\n render() {\n const sorter = this.declared('sorter');\n const orders = ['asc', 'desc', null];\n this.setAttribute('role', 'button');\n this.setAttribute('tabindex', '0');\n this.addEventListener('click', () => {\n const nextOrder = orders[(orders.indexOf(this.order) + 1) % 3];\n this.dispatchEvent(\n new CustomEvent('sort:requested', {\n bubbles: true,\n cancelable: false,\n detail: {\n value: { sorter, order: nextOrder },\n },\n }),\n );\n });\n this.addEventListener('keydown', (/** @type any */ evt) => {\n if (!['Enter', 'NumpadEnter', 'Space'].includes(evt.code)) {\n return;\n }\n evt.preventDefault();\n this.click();\n });\n }\n\n /**\n * The direction the column is sorted in, `null` when unsorted.\n * @returns {string|null}\n */\n get order() {\n return this.#order || null;\n }\n\n /**\n * Reflects the direction to the `order` attribute and sets `aria-sort` on\n * the enclosing `<th>`, if any: `ascending` for `asc`, `descending` for any\n * other non-empty value, removed for an empty one.\n * @param {string|null} value an empty string or `null` means unsorted\n */\n set order(value) {\n this.#order = value || null;\n this.reflectTo('order', this.#order);\n const th = this.closest('th');\n if (!th) {\n return;\n }\n Attributes.set(th, 'aria-sort', this.#order ? ('asc' === this.#order ? 'ascending' : 'descending') : null);\n }\n}\n\n/**\n * The pager, `ful-pagination`: a previous button, a window of page buttons\n * around the current page, a next button, a reload button and a line saying\n * which page of how many is shown.\n *\n * The window holds at most `pages` buttons (read once at the upgrade, default 5),\n * centred on the current page and shifted back on the last pages so it stays\n * full. The current page's button carries `aria-current=\"page\"` and stays\n * enabled. Previous and next are disabled where there is no page to go to.\n *\n * A click on an enabled button other than the current page dispatches\n * `page:requested` (bubbling, not cancelable) with `detail.value` the zero based\n * index of the page asked for; the reload button asks for the current page.\n * The pager does not move itself: whoever handles the event calls `update`,\n * which `ful-table` does once the page has loaded.\n *\n * The icons are the `ful-icon` names in `Pagination.config`.\n */\nclass Pagination extends ParsedElement {\n static observed = ['total:number', 'current:number'];\n static attributes = ['pages:number'];\n static config = {\n prevIcon: 'chevron-left',\n nextIcon: 'chevron-right',\n reloadIcon: 'arrow-clockwise',\n };\n static template = `\n <ful-pagination-bar role=\"navigation\" data-tpl-aria-label=\"#l10n:t('pagination.navigation')\">\n <ul>\n <li data-ref=\"index\"> {{ #l10n:t('pagination.showing', { 'current': curr.label, 'total': total }) }}</li>\n <li data-ref=\"reload\"><button type=\"button\" data-tpl-aria-label=\"#l10n:t('pagination.reload')\"><ful-icon data-tpl-name=\"config.reloadIcon\" aria-hidden=\"true\"></ful-icon></button></li>\n <li data-ref=\"prev\">\n <button type=\"button\" data-tpl-disabled=\"prev.enabled ? false : true\" data-tpl-aria-label=\"#l10n:t('pagination.previous')\" data-tpl-data-page=\"prev.index\">\n <ful-icon data-tpl-name=\"config.prevIcon\" aria-hidden=\"true\"></ful-icon>\n </button>\n </li>\n <li data-ref=\"page\" data-tpl-each=\"pages\" data-tpl-var=\"page\">\n <button type=\"button\" data-tpl-aria-current=\"curr.index == page.index ? 'page' : false\" data-tpl-data-page=\"page.index\" >\n {{ page.label }}\n </button>\n </li>\n <li data-ref=\"next\">\n <button type=\"button\" data-tpl-disabled=\"next.enabled ? false : true\" data-tpl-aria-label=\"#l10n:t('pagination.next')\" data-tpl-data-page=\"next.index\">\n <ful-icon data-tpl-name=\"config.nextIcon\" aria-hidden=\"true\"></ful-icon>\n </button>\n </li>\n </ul>\n </ful-pagination-bar>\n `;\n #total = 0;\n #current = 0;\n render() {\n this.addEventListener('click', (/** @type any */ evt) => {\n const el = evt.target.closest('button');\n if (!el || el.hasAttribute('disabled')) {\n return;\n }\n if (el.getAttribute('aria-current') === 'page') {\n return;\n }\n this.dispatchEvent(\n new CustomEvent('page:requested', {\n bubbles: true,\n cancelable: false,\n detail: {\n value: Number(el.dataset.page ?? this.#current),\n },\n }),\n );\n });\n }\n /**\n * Moves the pager to a page, a page count, or both, reflects both to their\n * attributes and repaints the bar once. A key left out keeps its value; a\n * `null` one becomes 0. A count below one is shown as one empty page.\n *\n * The bar is replaced on every repaint. When the focus was inside it, it\n * moves to the equivalent control of the new bar: the button of the same\n * page, else the same enabled control, else the current page's button.\n * @param {{ current?: number|null, total?: number|null }} [state] `current`\n * is the zero based index of the page shown, `total` the number of pages\n */\n update({ current: toCurrent, total: toTotal } = {}) {\n if (toCurrent !== undefined) {\n this.#current = toCurrent ?? 0;\n }\n if (toTotal !== undefined) {\n this.#total = toTotal ?? 0;\n }\n this.reflectTo('current', this.#current);\n this.reflectTo('total', this.#total);\n const current = this.#current;\n const total = this.#total;\n const maxRender = this.declared('pages') ?? 5;\n const pageCount = Math.max(total, 1);\n const hasPrev = current > 0;\n const hasNext = current + 1 < pageCount;\n const prev = { index: hasPrev ? current - 1 : null, enabled: hasPrev };\n const curr = { index: current, label: current + 1 };\n const next = { index: hasNext ? current + 1 : null, enabled: hasNext };\n const rendered = Math.max(1, Math.min(maxRender, pageCount));\n const first = Math.max(0, Math.min(current - Math.floor((rendered - 1) / 2), pageCount - rendered));\n const pages = Array.from({ length: rendered }, (_, offset) => ({\n index: first + offset,\n label: first + offset + 1,\n }));\n const focused = this.contains(document.activeElement)\n ? /** @type HTMLElement */ (document.activeElement).closest('li')?.getAttribute('data-ref')\n : null;\n const page = focused === 'page' ? /** @type any */ (document.activeElement).dataset.page : null;\n this.template().withOverlay({ total: pageCount, prev, curr, next, pages }).renderTo(this);\n if (!focused) {\n return;\n }\n const back =\n (page === null ? null : this.querySelector(`li[data-ref=page] button[data-page=\"${page}\"]`)) ??\n this.querySelector(`li[data-ref=${focused}] button:not(:disabled)`) ??\n this.querySelector('li[data-ref=page] button[aria-current=page]');\n /** @type HTMLElement */ (back)?.focus();\n }\n /**\n * The number of pages, as last written.\n * @returns {number}\n */\n get total() {\n return this.#total;\n }\n /**\n * Same as `update({ total: value })`.\n * @param {number|null} value\n */\n set total(value) {\n this.update({ total: value });\n }\n /**\n * The zero based index of the page shown.\n * @returns {number}\n */\n get current() {\n return this.#current;\n }\n /**\n * Same as `update({ current: value })`.\n * @param {number|null} value\n */\n set current(value) {\n this.update({ current: value });\n }\n}\n\n/** Reads the schema declaration into the header and row templates a table renders from. */\nclass TableSchemaParser {\n /**\n * Builds a header `<tr>` and a row `<tr data-tpl-each=\"rows\">` from the\n * `<schema>` child of the slot. The `<schema>` attributes are copied onto\n * both rows. Each `<column>` becomes a `<th>` and a `<td>` carrying the\n * column's attributes except `title`, `sorter` and `order`, so a\n * `data-tpl-*` on a column applies to both cells; the two templates carry\n * `inHeaders` and `inRows` in their scope, so a column can tell them apart,\n * as in `data-tpl-if=\"inRows\"`. The header cell holds the `<title>` child\n * element of the column, else the text of its `title` attribute, wrapped\n * in a `ful-sorter` when the column declares `sorter` or `order`. The body\n * cell holds the column's remaining children.\n *\n * The column elements are consumed: their `<title>`, `title`, `sorter` and\n * `order` are removed and their children moved into the cells.\n * @param {DocumentFragment|Element|undefined} nodeOrFragment the `schema`\n * slot, undefined when the table has none\n * @param {ReturnType<ParsedElement['template']>} template the template the\n * header and row templates derive from, keeping its scope\n * @returns {{ headersTemplate: ReturnType<ParsedElement['template']>, rowsTemplate: ReturnType<ParsedElement['template']>, sort: { sorter: string|null, order: string|null } | null, length: number }}\n * `sort` is the initial sort, taken from the first column declaring both\n * `order` and `sorter` (a column with only `order` gets an arrow but no\n * initial sort), `null` when none does; `length` is the number of columns\n * @throws {Error} when the slot is missing or holds no `<schema>`\n */\n static parse(nodeOrFragment, template) {\n const schema = nodeOrFragment ? Nodes.queryChildren(nodeOrFragment, 'schema') : null;\n if (!schema) {\n throw new Error('missing expected <schema>: ful-table needs a <template slot=\"schema\"> holding one');\n }\n const headersTr = document.createElement('tr');\n const rowsTr = document.createElement('tr');\n rowsTr.setAttribute('data-tpl-each', 'rows');\n for (const attr of schema.getAttributeNames()) {\n const value = schema.getAttribute(attr);\n headersTr.setAttribute(attr, value ?? '');\n rowsTr.setAttribute(attr, value ?? '');\n }\n const columns = Nodes.queryChildrenAll(schema, 'column');\n const sort =\n columns\n .filter((v) => v.hasAttribute('order') && v.hasAttribute('sorter'))\n .map((v) => ({ sorter: v.getAttribute('sorter'), order: v.getAttribute('order') }))[0] ?? null;\n for (const column of columns) {\n const maybeTitleTag = Nodes.queryChildren(column, 'title');\n const sorter = column.getAttribute('sorter');\n const order = column.getAttribute('order');\n const titleNode = maybeTitleTag ?? document.createTextNode(column.getAttribute('title') ?? '');\n maybeTitleTag?.remove();\n column.removeAttribute('sorter');\n column.removeAttribute('order');\n column.removeAttribute('title');\n const wrappedTitleNode =\n !sorter && !order\n ? titleNode\n : (() => {\n const fulSorter = document.createElement('ful-sorter');\n if (sorter) {\n fulSorter.setAttribute('sorter', sorter);\n }\n if (order) {\n fulSorter.setAttribute('order', order);\n }\n fulSorter.append(titleNode);\n return fulSorter;\n })();\n const th = document.createElement('th');\n const td = document.createElement('td');\n for (const attr of column.getAttributeNames()) {\n const value = column.getAttribute(attr);\n th.setAttribute(attr, value ?? '');\n td.setAttribute(attr, value ?? '');\n }\n th.append(wrappedTitleNode);\n td.append(...column.childNodes);\n headersTr.append(th);\n rowsTr.append(td);\n }\n\n return {\n headersTemplate: template\n .withOverlay({ inHeaders: true, inRows: false })\n .withFragment(Fragments.from(headersTr)),\n rowsTemplate: template.withOverlay({ inHeaders: false, inRows: true }).withFragment(Fragments.from(rowsTr)),\n sort,\n length: columns.length,\n };\n }\n}\n\n/** Serves a table's rows from an array held in memory, applying the sort and the paging itself. */\nclass InMemoryTableLoader {\n #data;\n /**\n * @param {any[]} data the rows\n */\n constructor(data) {\n this.#data = data;\n }\n /**\n * Sorts a copy of the rows by the `sorter` property, rows missing it last\n * in either direction and rows with equal values in their original order,\n * then slices the requested page. The filters are ignored.\n * @param {TablePageRequest} pageRequest\n * @param {{ sorter?: string|null, order?: string|null } | null} sortRequest\n * `order` `desc` sorts descending, anything else ascending; no `sorter`\n * keeps the original order\n * @param {Record<string, any>} filterRequest not read\n * @returns {Promise<TablePageResponse>}\n */\n async load(pageRequest, sortRequest, filterRequest) {\n const rows = this.#sorted(sortRequest);\n const begin = pageRequest.page * pageRequest.size;\n const end = begin + pageRequest.size;\n const page = rows.slice(begin, end);\n const totalElements = rows.length;\n return {\n data: page,\n size: totalElements,\n };\n }\n #sorted(sortRequest) {\n if (!sortRequest?.sorter) {\n return this.#data;\n }\n const { sorter, order } = sortRequest;\n const sign = order === 'desc' ? -1 : 1;\n return [...this.#data].sort((l, r) => {\n const a = l?.[sorter];\n const b = r?.[sorter];\n if (a === b) {\n return 0;\n }\n if (a == null) {\n return 1;\n }\n if (b == null) {\n return -1;\n }\n return (a < b ? -1 : 1) * sign;\n });\n }\n /**\n * Replaces the rows. The table shows them at its next load.\n * @param {any[]} data\n */\n update(data) {\n this.#data = data;\n }\n}\n\n/** Requests one page of rows from a url, passing the page, the sort and the filters to the endpoint. */\nclass RemoteTableLoader {\n #http;\n #url;\n #method;\n #responseMapper;\n /**\n * @param {{ request(method: string, url: string): any }} http the `http-client` component\n * @param {string} url\n * @param {string} method\n * @param {(response: any) => TablePageResponse} [responseMapper] turns the\n * parsed json body into the page response; the identity when omitted\n */\n constructor(http, url, method, responseMapper = (response) => response) {\n this.#http = http;\n this.#url = url;\n this.#method = method;\n this.#responseMapper = responseMapper;\n }\n /**\n * Sends the query parameters `page`, `size`, `sort` as `sorter,order`\n * (left out when `sortRequest` is null) and `filters` as a json object of\n * the filters with a truthy value (left out when there is none), and\n * answers the json body through the response mapper.\n * @param {TablePageRequest} pageRequest\n * @param {TableSortRequest|null} sortRequest\n * @param {Record<string, any>} filterRequest\n * @returns {Promise<TablePageResponse>} rejecting with what the client's\n * `fetchJson()` rejects with\n */\n async load(pageRequest, sortRequest, filterRequest) {\n const filters = Object.entries(filterRequest).filter(([k, v]) => v);\n return await this.#http\n .request(this.#method, this.#url)\n .param('page', pageRequest.page)\n .param('size', pageRequest.size)\n .param('sort', sortRequest ? `${sortRequest.sorter},${sortRequest.order}` : null)\n .param('filters', filters.length > 0 ? JSON.stringify(Object.fromEntries(filters)) : null)\n .fetchJson()\n .then((response) => this.#responseMapper(response));\n }\n}\n\n/**\n * Builds the table's loader from its attributes: an in-memory one, or the\n * remote loader over src.\n *\n * A component registered under the `loader` attribute replaces this one and\n * must implement `load(pageRequest, sortRequest, filterRequest)`, answering\n * `{ data, size }`: the rows of the requested page and the total count of\n * rows. `pageRequest` carries the page index and its size, `sortRequest` the column and direction, and\n * `filterRequest` the values of the filters in the slot.\n */\nclass TableLoader {\n /**\n * A table with a `src` attribute gets a `RemoteTableLoader` sending through\n * the `http-client` component with the `method` attribute or `GET`, and\n * mapping the response through the component named by `response-mapper`,\n * if any. A table without `src` gets an empty `InMemoryTableLoader`, which\n * `withLoader` reaches to give it rows.\n * @param {Element & { component(name: string): any }} el the table\n * @param {unknown} [conf] not read\n * @returns {InMemoryTableLoader | RemoteTableLoader}\n */\n static create(el, conf) {\n const url = el.getAttribute('src');\n if (url) {\n const http = el.component('http-client');\n const method = el.getAttribute('method') ?? 'GET';\n const responseMapper = el.hasAttribute('response-mapper')\n ? el.component(/** @type {string} */ (el.getAttribute('response-mapper')))\n : (/** @type any */ response) => response;\n return new RemoteTableLoader(http, url, method, responseMapper);\n }\n return new InMemoryTableLoader([]);\n }\n}\n\n/**\n * A table, `ful-table`, loading its rows a page at a time from a loader, with\n * a header sorter per sortable column, a `ful-pagination` under it and an\n * optional filter form.\n *\n * The loader is the component named by `loader`, default `loaders:table`\n * (see `TableLoader`). The `schema` slot declares the columns (see\n * `TableSchemaParser.parse`); the `filters` slot is wrapped in a `ful-form`,\n * whose values are the filter request; the `caption`, `footer` and `empty`\n * slots go in the table's caption, its `<tfoot>` and the panel shown for a\n * load answering no rows. Attributes starting with `table-` are forwarded,\n * without the prefix, to the inner `<table>`.\n *\n * With `autoload` the first load starts at the upgrade, which does not wait\n * for it. Without it the table shows an initial panel until `load`,\n * `reload` or `resetWithFilter` is called.\n *\n * Inside the table a `page:requested` loads that page with the current size,\n * sort and filters; a `sort:requested` loads the current page with the new\n * sort (none for a `null` order) and, once that load is the one showing, sets\n * the order of the sorter that asked and clears the others; a `submit:success`\n * of the filter form loads the first page with the submitted request as the\n * filters. The loads these start, and the autoload, are not awaited by\n * anything: a failure shows the error panel and its rejection is unhandled.\n */\nclass Table extends ParsedElement {\n /** Read once at the upgrade. */\n static attributes = ['loader', 'autoload:presence'];\n /** These stay live after the upgrade: see `pageSize`, `src` and `method`. */\n static observed = ['page-size:number', 'src', 'method'];\n static slots = true;\n static config = {\n searchIcon: 'search',\n emptyIcon: 'inbox',\n };\n static template = `\n <ful-form data-tpl-if=\"slots.filters\">\n {{{{ slots.filters }}}}\n </ful-form>\n <ful-table-wrapper>\n <table>\n <caption data-tpl-if=\"slots.caption\">{{{{ slots.caption }}}}</caption>\n <thead></thead>\n <tbody></tbody>\n <tbody data-ref=\"initial\">\n <tr>\n <td data-tpl-colspan=\"schema.length\">\n <ful-empty>\n <ful-icon data-tpl-if=\"config.searchIcon\" data-tpl-name=\"config.searchIcon\" aria-hidden=\"true\"></ful-icon>\n {{ #l10n:t('table.initial') }}\n </ful-empty>\n </td>\n </tr>\n </tbody>\n <tbody data-ref=\"empty\" hidden>\n <tr>\n <td data-tpl-colspan=\"schema.length\">\n <ful-empty data-tpl-if=\"slots.empty\" data-ref=\"empty-authors\"></ful-empty>\n <ful-empty data-tpl-if=\"!slots.empty\">\n <ful-icon data-tpl-if=\"config.emptyIcon\" data-tpl-name=\"config.emptyIcon\" aria-hidden=\"true\"></ful-icon>\n {{ #l10n:t('table.no-data') }}\n </ful-empty>\n </td>\n </tr>\n </tbody>\n <tbody data-ref=\"loading\" hidden>\n <tr>\n <td data-tpl-colspan=\"schema.length\">\n <ful-spinner class=\"big\" role=\"status\"><span class=\"ful-sr-only\">{{ #l10n:t('spinner.loading') }}</span></ful-spinner>\n </td>\n </tr>\n </tbody>\n <tbody data-ref=\"feedback\" hidden>\n <tr>\n <td data-tpl-colspan=\"schema.length\">\n <div role=\"alert\">\n <p>{{ #l10n:t('table.error') }}</p>\n <div data-ref=\"feedback-error\"></div>\n </div>\n </td>\n </tr>\n </tbody>\n <tfoot data-tpl-if=\"slots.footer\">\n {{{{ slots.footer }}}}\n </tfoot>\n </table>\n </ful-table-wrapper>\n <ful-pagination current=\"0\" total=\"1\"></ful-pagination>\n `;\n static templates = {\n row: `\n {{{{ schema.rowsTemplate.withOverlay({'rows': pageResponse.data}).render() }}}}\n `,\n };\n #loader;\n #schema;\n #body;\n #loading;\n #noAutoload;\n #empty;\n #emptyAuthors;\n #emptyTemplate;\n #feedback;\n #paginator;\n #sorters;\n /** @type {{ pageRequest: { page: number, size: number }, sortRequest: any, filterRequest: any }} */\n #latestRequest = { pageRequest: { page: 0, size: 10 }, sortRequest: null, filterRequest: {} };\n /** whether a load has been asked for, by autoload or by a caller */\n #loadRequested = false;\n #loads = new Claims();\n /** @type {{ src: string|null, method: string|null }} */\n #builtFrom = { src: null, method: null };\n /**\n * How many rows a page asks the loader for: the size the next load will\n * carry. Ten before the render.\n * @returns {number}\n */\n get pageSize() {\n return this.#latestRequest.pageRequest.size;\n }\n /**\n * Changes the page size and reloads from the first page, keeping the sort\n * and the filters. A table that has not loaded yet only records it:\n * writing the size is not a request to start loading, which is what\n * `autoload` and `reload()` are for. A write that does not change the size\n * does nothing. A write made before the render is replaced by the declared\n * `page-size` when the table renders.\n *\n * The reload is not awaited: a failure shows the error panel and its\n * rejection is unhandled.\n * @param {number|null|undefined} value absent or null is the default of\n * ten, so removing the attribute restores it\n */\n set pageSize(value) {\n const size = value ?? 10;\n if (size === this.#latestRequest.pageRequest.size) {\n return;\n }\n this.#latestRequest = { ...this.#latestRequest, pageRequest: { page: 0, size } };\n if (!this.#loadRequested) {\n return;\n }\n this.reload();\n }\n /**\n * The url the loader asks for rows, reflected as the `src` attribute.\n * @returns {string|null}\n */\n get src() {\n return this.getAttribute('src');\n }\n /**\n * Points the table at another url: the loader is built again through its\n * component's `create`, as at the render, and the table reloads from the\n * first page, keeping the size, the sort and the filters. A table that has\n * not loaded yet only rebuilds its loader. A write that does not change the\n * url does nothing.\n *\n * The reload is not awaited: a failure shows the error panel and its\n * rejection is unhandled.\n * @param {string|null|undefined} value null or undefined removes the url,\n * which the default loader answers with an empty in-memory loader\n */\n set src(value) {\n this.reflectTo('src', value ?? null);\n if (this.#followAttributes() && this.#loadRequested) {\n this.reload();\n }\n }\n /**\n * The http method the default loader sends with, reflected as the `method`\n * attribute; `GET` when absent.\n * @returns {string|null}\n */\n get method() {\n return this.getAttribute('method');\n }\n /**\n * Changes the http method the way `src` changes the url: the loader is\n * built again and the table reloads from the first page.\n * @param {string|null|undefined} value\n */\n set method(value) {\n this.reflectTo('method', value ?? null);\n if (this.#followAttributes() && this.#loadRequested) {\n this.reload();\n }\n }\n /**\n * Writes `src` and `method` together and loads once: the loader is built\n * again for the pair when either changed, the page going back to the first\n * one as a single write of either does, and the table then reloads as\n * `reload()` does, whether or not they changed. Unlike a write of either,\n * it loads a table that has not loaded yet.\n * @param {{ src?: string|null, method?: string|null }} attributes a name\n * left out keeps its value, null removes the attribute\n * @returns {Promise<void>} as `load`\n */\n async reconfigure(attributes) {\n for (const name of ['src', 'method']) {\n if (name in attributes) {\n this.reflectTo(name, attributes[name] ?? null);\n }\n }\n this.#followAttributes();\n return await this.reload();\n }\n #buildLoader() {\n this.#builtFrom = { src: this.getAttribute('src'), method: this.getAttribute('method') };\n this.#loader = this.component(this.declared('loader') ?? 'loaders:table').create(this);\n }\n /** @returns {boolean} whether the loader was built again */\n #followAttributes() {\n if (\n this.getAttribute('src') === this.#builtFrom.src &&\n this.getAttribute('method') === this.#builtFrom.method\n ) {\n return false;\n }\n this.#buildLoader();\n this.#latestRequest = { ...this.#latestRequest, pageRequest: { ...this.#latestRequest.pageRequest, page: 0 } };\n return true;\n }\n /**\n * @param {{ slots: Record<string, DocumentFragment> }} c\n * @returns {Promise<void>}\n * @throws {Error} when the `schema` slot is missing or holds no `<schema>`\n */\n async render({ slots }) {\n const template = this.template();\n const schema = TableSchemaParser.parse(slots.schema, template);\n const fragment = template.withOverlay({ slots, schema }).render();\n const tableWrapper = /** @type HTMLTableElement */ (Nodes.queryChildren(fragment, 'ful-table-wrapper'));\n const table = /** @type HTMLTableElement */ (tableWrapper.querySelector('table'));\n Attributes.forward('table-', this, table);\n this.#buildLoader();\n\n this.#schema = schema;\n this.#body = table.querySelector(':scope > tbody');\n this.#loading = table.querySelector(':scope > tbody[data-ref=loading]');\n this.#noAutoload = table.querySelector(':scope > tbody[data-ref=initial]');\n this.#empty = table.querySelector(':scope > tbody[data-ref=empty]');\n this.#emptyAuthors = this.#empty.querySelector('ful-empty[data-ref=empty-authors]');\n this.#emptyTemplate =\n slots.empty && !Fragments.isBlank(slots.empty) ? Templates.fromFragment(slots.empty) : null;\n this.#feedback = table.querySelector(':scope > tbody[data-ref=feedback]');\n this.#paginator = Nodes.queryChildren(fragment, 'ful-pagination');\n this.replaceChildren(fragment);\n const thead = /** @type HTMLTableSectionElement */ (this.querySelector('thead'));\n schema.headersTemplate.renderTo(thead);\n this.#sorters = thead.querySelectorAll('ful-sorter');\n await Rendering.waitForChildren(this);\n\n const maybeForm = /** @type any */ (Nodes.queryChildren(this, 'ful-form'));\n this.#latestRequest = {\n pageRequest: {\n page: 0,\n size: this.declared('page-size') ?? 10,\n },\n sortRequest: schema.sort,\n filterRequest: maybeForm?.values ?? {},\n };\n maybeForm?.addEventListener('submit:success', async (evt) => {\n await this.#loadPage(0, evt.detail.request);\n });\n this.addEventListener('page:requested', async (/** @type any */ e) => {\n await this.#loadPage(e.detail.value, this.#latestRequest.filterRequest);\n });\n this.addEventListener('sort:requested', async (/** @type any */ e) => {\n const sortRequest = e.detail.value.order ? e.detail.value : null;\n await this.load(this.#latestRequest.pageRequest, sortRequest, this.#latestRequest.filterRequest);\n if (this.#latestRequest.sortRequest !== sortRequest) {\n return;\n }\n this.#sorters.forEach((s) => {\n s.order = null;\n });\n e.target.order = e.detail.value.order;\n });\n if (this.declared('autoload')) {\n this.reload();\n }\n }\n\n /**\n * Loads the last request that loaded, or, before any has, the first page\n * with the declared size and sort and the values of the filters slot. A\n * size written through `pageSize` since then replaces the page with the\n * first one at that size.\n * @returns {Promise<void>} as `load`\n */\n async reload() {\n return await this.load(\n this.#latestRequest.pageRequest,\n this.#latestRequest.sortRequest,\n this.#latestRequest.filterRequest,\n );\n }\n /**\n * Asks the loader for a page and shows it.\n *\n * While the load runs the table carries `aria-busy=\"true\"`, and the rows\n * already shown stay; the spinner panel shows only when there are none.\n * When the loader answers, the rows and the pager are replaced, the empty\n * panel shows for an answer with no rows (the `empty` slot rendered with\n * `schema`, `pageRequest`, `filterRequest` and `pageResponse` in scope),\n * the request becomes the one\n * `reload` repeats, `aria-busy` is removed and `load:success` is\n * dispatched (bubbling, not cancelable) with `detail` set to\n * `{ pageRequest, sortRequest, filterRequest, response }`. A page beyond\n * the last one the answer reports is not shown: the last page is loaded\n * instead, and the returned promise settles with that load.\n *\n * When the loader rejects, the rows are removed, the error panel shows the\n * `reason` of each of the error's `problems`, one per line, or the error as text,\n * `aria-busy` is removed, `load:failure` is dispatched (bubbling, not\n * cancelable) with `detail` set to\n * `{ pageRequest, sortRequest, filterRequest, exception }`, and the\n * returned promise rejects with the same error.\n *\n * A load started after this one supersedes it: when this one's answer or\n * failure arrives it changes nothing, dispatches nothing and resolves.\n * @param {TablePageRequest} pageRequest\n * @param {TableSortRequest|null} sortRequest\n * @param {Record<string, any>} filterRequest\n * @returns {Promise<void>}\n * @throws what the loader rejects with, unless a newer load superseded this one\n */\n async load(pageRequest, sortRequest, filterRequest) {\n this.#loadRequested = true;\n const claim = this.#loads.take();\n this.#loading.toggleAttribute('hidden', this.#body.childElementCount > 0);\n this.#feedback.setAttribute('hidden', '');\n this.#noAutoload.setAttribute('hidden', '');\n this.#empty.setAttribute('hidden', '');\n this.setAttribute('aria-busy', 'true');\n let lastPage;\n try {\n const pageResponse = await this.#loader.load(pageRequest, sortRequest, filterRequest);\n if (claim.stale) {\n return;\n }\n lastPage = Math.max(0, Math.ceil(pageResponse.size / pageRequest.size) - 1);\n if (pageRequest.page <= lastPage) {\n this.#latestRequest = { pageRequest, sortRequest, filterRequest };\n this.#update(pageRequest, sortRequest, filterRequest, pageResponse);\n this.removeAttribute('aria-busy');\n this.dispatchEvent(\n new CustomEvent('load:success', {\n bubbles: true,\n cancelable: false,\n detail: { pageRequest, sortRequest, filterRequest, response: pageResponse },\n }),\n );\n return;\n }\n } catch (/** @type any */ error) {\n if (claim.stale) {\n return;\n }\n this.#loading.setAttribute('hidden', '');\n this.#body.replaceChildren();\n this.#feedback.removeAttribute('hidden');\n this.#feedback.querySelector('[data-ref=feedback-error]').textContent = Localization.of().failure(error);\n this.removeAttribute('aria-busy');\n this.dispatchEvent(\n new CustomEvent('load:failure', {\n bubbles: true,\n cancelable: false,\n detail: { pageRequest, sortRequest, filterRequest, exception: error },\n }),\n );\n throw error;\n }\n return await this.load({ page: lastPage, size: pageRequest.size }, sortRequest, filterRequest);\n }\n /**\n * Hands the loader to the callback, for runtime reconfigurations, such as\n * `update(rows)` on the in-memory loader. The loader exists from the\n * render on. Nothing is reloaded.\n * @template T\n * @param {(loader: any) => T | Promise<T>} fn\n * @returns {Promise<T>} what `fn` returns or resolves to\n */\n async withLoader(fn) {\n return await fn(this.#loader);\n }\n /**\n * Loads the first page with the given filters, keeping the size and the sort.\n * @param {Record<string, any>} filterRequest\n * @returns {Promise<void>} as `load`\n */\n async resetWithFilter(filterRequest) {\n return await this.#loadPage(0, filterRequest);\n }\n #loadPage(page, filterRequest) {\n return this.load(\n { page, size: this.#latestRequest.pageRequest.size },\n this.#latestRequest.sortRequest,\n filterRequest,\n );\n }\n #update(pageRequest, sortRequest, filterRequest, pageResponse) {\n const pages = Math.ceil(pageResponse.size / pageRequest.size);\n this.#loading.setAttribute('hidden', '');\n this.#body.replaceChildren(\n this.template('row')\n .withOverlay({\n schema: this.#schema,\n pageRequest,\n filterRequest,\n pageResponse,\n })\n .render(),\n );\n this.#empty.toggleAttribute('hidden', pageResponse.data.length !== 0);\n if (this.#emptyTemplate && pageResponse.data.length === 0) {\n this.#emptyAuthors.replaceChildren(\n this.#emptyTemplate\n .withOverlay({ schema: this.#schema, pageRequest, filterRequest, pageResponse })\n .render(),\n );\n }\n this.#paginator.update({ current: pageRequest.page, total: pages });\n }\n}\n\nexport { TableLoader, SortButton, Table, TableSchemaParser, Pagination };\n","/** how long, in milliseconds, a type-ahead search waits for its next character */\nconst TYPEAHEAD_WINDOW = 500;\n\n/**\n * Wires the keyboard protocol of a menu popover onto it.\n *\n * - As the menu opens, the focus moves to the item `current` answers, or to\n * the first item when it answers none.\n * - As the menu closes, the focus moves back to the invoker, but only when it\n * was inside the menu, so a close caused by a click elsewhere leaves it\n * where it went.\n * - ArrowDown and ArrowUp move the focus to the next and previous item,\n * wrapping at both ends; Home and End move it to the first and last.\n * - Enter, the numpad Enter and Space call `click()` on the focused item and\n * move the focus to the invoker. Closing the menu is left to the item's\n * click handling.\n * - Escape moves the focus to the invoker and leaves the close to the\n * platform.\n * - A printable character typed without Ctrl, Alt or Meta searches the\n * items' trimmed text, ignoring case, wrapping past the last item.\n * Characters typed within 500ms of each other add to one search. A search\n * of one character, or of one character repeated, moves the focus to the\n * next item after the focused one starting with it, so repeating a letter\n * cycles through those items; a longer search moves it to the first item,\n * from the focused one on, starting with the whole search. A search that\n * matches nothing leaves the focus where it is.\n *\n * The keys are read by `KeyboardEvent.code`, the typed characters by\n * `KeyboardEvent.key`. A handled key has its default prevented, except\n * Escape and a search that matched nothing. A key whose target is not inside\n * an item is ignored.\n *\n * `items` answers the items in the order they are walked, and is called on\n * every gesture, so a menu that fills itself later needs no rewiring.\n *\n * @param {() => HTMLElement|null} invoker answers the element the menu belongs to\n * now, where the focus goes back; called on every gesture, so a menu shared\n * by several invokers hands the focus back to the one that opened it\n * @param {HTMLElement} menu the `[popover]` holding the items\n * @param {{items: () => HTMLElement[], current?: () => HTMLElement|null|undefined}} conf\n * `items` answers the items; `current` answers the item an opening focuses\n */\nconst wireMenuKeys = (invoker, menu, { items, current = () => null }) => {\n let typed = '';\n let typedAt = 0;\n menu.addEventListener('beforetoggle', (/** @type any */ evt) => {\n if (evt.newState === 'closed' && menu.contains(document.activeElement)) {\n invoker()?.focus();\n }\n });\n menu.addEventListener('toggle', (/** @type any */ evt) => {\n if (evt.newState !== 'open') {\n return;\n }\n const all = items();\n (current() ?? all[0])?.focus();\n });\n menu.addEventListener('keydown', (evt) => {\n const target = /** @type HTMLElement */ (evt.target);\n const all = items();\n const item = all.find((candidate) => candidate === target || candidate.contains(target));\n if (!item) {\n return;\n }\n const at = all.indexOf(item);\n switch (evt.code) {\n case 'ArrowDown': {\n evt.preventDefault();\n all[(at + 1) % all.length]?.focus();\n return;\n }\n case 'ArrowUp': {\n evt.preventDefault();\n all[(at - 1 + all.length) % all.length]?.focus();\n return;\n }\n case 'Home': {\n evt.preventDefault();\n all[0]?.focus();\n return;\n }\n case 'End': {\n evt.preventDefault();\n all[all.length - 1]?.focus();\n return;\n }\n case 'Enter':\n case 'NumpadEnter':\n case 'Space': {\n evt.preventDefault();\n item.click();\n invoker()?.focus();\n return;\n }\n case 'Escape': {\n invoker()?.focus();\n return;\n }\n }\n if (evt.key.length !== 1 || evt.ctrlKey || evt.altKey || evt.metaKey) {\n return;\n }\n const now = Date.now();\n typed = now - typedAt > TYPEAHEAD_WINDOW ? evt.key : typed + evt.key;\n typedAt = now;\n const wanted = typed.toLowerCase();\n const repeated = [...wanted].every((character) => character === wanted[0]);\n const search = repeated ? wanted[0] : wanted;\n const from = repeated ? at + 1 : at;\n const found = [...all.slice(from), ...all.slice(0, from)].find((candidate) =>\n (candidate.textContent ?? '').trim().toLowerCase().startsWith(search),\n );\n if (found) {\n evt.preventDefault();\n found.focus();\n }\n });\n};\n\nexport { wireMenuKeys };\n","import { Attributes } from '../../ftl/index.mjs';\nimport { Anchors } from '../disclosures/anchors.mjs';\nimport { wireMenuKeys } from '../disclosures/menu-keys.mjs';\n\n/**\n * An invoker button paired with the `ul[popover][role=menu]` that follows it:\n * the chrome behind every filter's operator, sensitivity and boolean value.\n *\n * It fills the menu from a vocabulary, wires it the first time more than one\n * choice survives the whitelist, pins the button to a static glyph when a\n * single one does, takes the shared menu keyboard protocol, and keeps the\n * button's value, glyph and aria-label in step. A pick that changes the value\n * calls back; the host decides what that means.\n *\n * The button's `value` attribute is the store, as it is for a native control:\n * the menu protocol finds the current item by it, and nothing mirrors it.\n */\nclass ChoiceButton {\n /**\n * The declared choices narrowed to a vocabulary, in the declared order.\n * When none of them is in the vocabulary, or none is declared, the answer\n * is a copy of the whole vocabulary.\n * @param {string[] | null | undefined} declared\n * @param {string[]} vocabulary\n * @returns {string[]}\n */\n static narrow(declared, vocabulary) {\n const narrowed = (declared ?? []).filter((choice) => vocabulary.includes(choice));\n return narrowed.length > 0 ? narrowed : [...vocabulary];\n }\n #button;\n #menu;\n #vocabulary;\n #glyphs;\n #labelFor;\n #display;\n #interactive;\n #onPick;\n #allowed;\n #claimed = false;\n #wired = false;\n /**\n * Takes the button's next sibling as its menu and listens for picks on it.\n * The menu is neither filled nor wired until `allowed` is first written.\n *\n * A click on an item, while `interactive()` answers true, sets the value,\n * hides the menu and, when the value changed, calls `onPick`.\n * @param {HTMLElement} button the invoker, whose next sibling is its menu\n * @param {{vocabulary: string[], glyphs?: Record<string,string>, labelFor?: (v: string) => string,\n * display?: ((v: string) => string)|null, interactive?: () => boolean, onPick?: (v: string) => void}} conf\n * `vocabulary` lists every choice; `glyphs` maps a choice to its compact\n * glyph; `labelFor` answers the localized word, used as the button's\n * `aria-label` and beside the glyph in the menu (the choice itself by\n * default); `display` answers the button's text (by default the glyph,\n * or the choice where it has none); `interactive` is asked before a\n * pick is taken; `onPick` receives a pick that changed the value\n */\n constructor(\n button,\n { vocabulary, glyphs = {}, labelFor = (v) => v, display = null, interactive = () => true, onPick = () => {} },\n ) {\n this.#button = button;\n this.#menu = /** @type HTMLElement */ (button.nextElementSibling);\n this.#vocabulary = vocabulary;\n this.#glyphs = glyphs;\n this.#labelFor = labelFor;\n this.#display = display ?? ((choice) => glyphs[choice] ?? choice);\n this.#interactive = interactive;\n this.#onPick = onPick;\n this.#allowed = [...vocabulary];\n this.#menu.addEventListener('click', (evt) => {\n const target = /** @type HTMLElement */ (evt.target);\n const item = /** @type HTMLElement | null */ (target.closest('li > a'));\n if (!item || !this.#interactive()) {\n return;\n }\n const picked = /** @type string */ (item.getAttribute('value'));\n const previous = this.value;\n this.value = picked;\n /** @type any */ (this.#menu).hidePopover?.();\n if (previous !== picked) {\n this.#onPick(picked);\n }\n });\n }\n /**\n * The choices the menu offers. Writing it narrows the declared set with\n * `narrow`, refills the menu, wires the popover and the menu keyboard the\n * first time more than one choice is allowed, and updates the button's\n * disabled state and popup attributes. When one choice is left the button\n * is pinned and the value is set to it.\n * @type {string[]}\n */\n get allowed() {\n return this.#allowed;\n }\n set allowed(declared) {\n this.#allowed = ChoiceButton.narrow(declared, this.#vocabulary);\n this.#fill();\n if (!this.#wired && this.#allowed.length > 1) {\n this.#wire();\n this.#wired = true;\n }\n this.#sync();\n if (this.pinned) {\n this.value = this.#allowed[0];\n }\n }\n /**\n * The choice when the menu allows it, otherwise the first allowed one.\n * @param {string|null} choice\n * @returns {string}\n */\n preferring(choice) {\n return choice !== null && this.#allowed.includes(choice) ? choice : this.#allowed[0];\n }\n /**\n * Whether fewer than two choices are allowed. A pinned button is disabled,\n * opens no menu and shows the single choice as its value.\n * @returns {boolean}\n */\n get pinned() {\n return this.#allowed.length < 2;\n }\n /**\n * The host's fixed claim: hides the button with the `hidden` attribute\n * while `value` keeps answering.\n * @param {boolean} fixed\n */\n set fixed(fixed) {\n this.#button.toggleAttribute('hidden', !!fixed);\n }\n /**\n * The current choice, stored as the button's `value` attribute, where the\n * menu keyboard also finds it. Writing it sets the button's text from\n * `display`, its `aria-label` from `labelFor`, and `aria-checked` on the\n * menu item carrying it. It does not call `onPick`.\n * @type {string | null}\n */\n get value() {\n return this.#button.getAttribute('value');\n }\n set value(choice) {\n this.#button.setAttribute('value', /** @type {string} */ (choice));\n this.#button.textContent = this.#display(choice);\n Attributes.set(this.#button, 'aria-label', this.#labelFor(choice));\n this.#mark();\n }\n #mark() {\n const current = this.value;\n for (const item of this.#items()) {\n item.setAttribute('aria-checked', String(item.getAttribute('value') === current));\n }\n }\n /**\n * The host's disabled claim. The button is disabled while either the claim\n * or the pin holds, so lifting one does not enable it while the other holds.\n * @param {boolean} claimed\n */\n set claimed(claimed) {\n this.#claimed = claimed;\n this.#sync();\n }\n #fill() {\n this.#menu.replaceChildren(\n ...this.#allowed.map((choice) => {\n const li = document.createElement('li');\n li.setAttribute('role', 'none');\n const a = document.createElement('a');\n a.setAttribute('role', 'menuitemradio');\n a.setAttribute('tabindex', '-1');\n a.setAttribute('value', choice);\n const word = this.#labelFor(choice);\n const glyph = this.#glyphs[choice] ?? choice;\n if (word === choice && glyph === choice) {\n a.innerText = choice;\n } else {\n const glyphSpan = document.createElement('span');\n glyphSpan.innerText = glyph;\n const wordSpan = document.createElement('span');\n wordSpan.innerText = word;\n a.append(glyphSpan, wordSpan);\n }\n li.append(a);\n return li;\n }),\n );\n this.#mark();\n }\n #sync() {\n const pinned = this.pinned;\n this.#button.toggleAttribute('disabled', pinned || this.#claimed);\n Attributes.set(this.#button, 'aria-haspopup', pinned ? null : 'true');\n Attributes.set(this.#button, 'aria-expanded', pinned ? null : 'false');\n if (pinned) {\n this.#button.removeAttribute('popovertarget');\n } else if (this.#menu.id) {\n this.#button.setAttribute('popovertarget', this.#menu.id);\n }\n }\n #items() {\n return Array.from(this.#menu.querySelectorAll('li > a'), (a) => /** @type HTMLAnchorElement */ (a));\n }\n #wire() {\n Anchors.wire(this.#button, this.#menu, { prefix: 'ful-filter-menu', invoke: true, expanded: true });\n wireMenuKeys(() => this.#button, this.#menu, {\n items: () => this.#items(),\n current: () => this.#items().find((a) => a.getAttribute('value') === this.value),\n });\n }\n}\n\nexport { ChoiceButton };\n","import { Localization } from '../../ftl/index.mjs';\nimport { ChoiceButton } from './choice-button.mjs';\nimport { Field } from './field.mjs';\nimport { Instant } from './temporals.mjs';\nimport { Input } from './input.mjs';\nimport { Select } from './select.mjs';\n\nconst GLYPHS = {\n EQ: '=',\n NEQ: '≠',\n LT: '<',\n GT: '>',\n LTE: '≤',\n GTE: '≥',\n BETWEEN: '↔',\n CONTAINS: '…a…',\n STARTS_WITH: 'a…',\n ENDS_WITH: '…a',\n};\nconst COMPARE_OPERATORS = ['EQ', 'NEQ', 'LT', 'GT', 'LTE', 'GTE', 'BETWEEN'];\nconst TEXT_OPERATORS = [...COMPARE_OPERATORS, 'CONTAINS', 'STARTS_WITH', 'ENDS_WITH'];\nconst SENSITIVITIES = ['IGNORE_CASE', 'CASE_SENSITIVE'];\n\nconst SENSITIVITY_GLYPHS = {\n IGNORE_CASE: 'aa',\n CASE_SENSITIVE: 'Aa',\n};\n\nconst { t } = Localization.of();\nconst operatorLabel = (op) => t(`filters.op.${op}`);\nconst sensitivityLabel = (sensitivity) => t(`filters.sensitivity.${sensitivity}`);\nconst booleanValueLabel = (token) => t(token === '' ? 'filters.boolean.any' : `filters.boolean.${token}`);\n\n/**\n * What a filter currently filters on, in the words a reader sees: the text of\n * its label, the operator in force (null for a set membership filter declaring\n * none) and the non-empty operands as text. The operands are what the controls\n * show, such as a select's labels, not the keys the value carries.\n * @typedef {{ label: string|null, operator: string|null, operands: string[] }} FilterCriterion\n */\n\nconst labelTextOf = (filter) => filter.querySelector(':scope > label')?.textContent.trim() || null;\n\n/**\n * Pins a button to the choice the singular attribute names, hiding it. A name\n * outside the vocabulary pins the fallback instead, and declaring the plural\n * beside the singular is ignored: both are warned about.\n * @param {HTMLElement & { declared(name: string): any }} el\n * @param {ChoiceButton} button\n * @param {{ singular: string, plural: string, vocabulary: string[], fallback: string }} names\n */\nconst fixChoice = (el, button, { singular, plural, vocabulary, fallback }) => {\n const fixed = el.declared(singular);\n if (fixed === null) {\n return;\n }\n if (el.hasAttribute(plural)) {\n console.warn(`${el.localName}: ${singular} fixes what ${plural} offers a menu for, the plural is ignored`, el);\n }\n const known = vocabulary.includes(fixed);\n if (!known) {\n console.warn(`${el.localName}: '${fixed}' is not one of its ${plural}, the default is pinned instead`, el);\n }\n button.allowed = [known ? fixed : fallback];\n button.fixed = true;\n};\n\n/** @returns {FilterCriterion|null} */\nconst asCriterion = (label, operator, operands) => {\n const shown = operands.filter((o) => o !== null && o !== undefined && `${o}` !== '');\n return shown.length === 0 ? null : { label, operator, operands: shown.map((o) => `${o}`) };\n};\n\n/**\n * The shared shape of every operator-and-operands filter: an operator menu, one\n * or two operands of the type the subclass declares, and a tuple that mirrors\n * the data-jpa compare annotations.\n *\n * The value is `[operator, operand]`, or `[operator, from, to]` for BETWEEN,\n * the only operator that shows the second operand. The `operators` attribute\n * whitelists the menu; the `operator` attribute fixes the operator for the\n * element's life instead, hiding its button, and every tuple then carries it.\n * Declaring both warns and the singular wins; a fixed name outside the\n * vocabulary warns and fixes the default operator.\n *\n * Both operands mirror the disabled and readonly claims, and readonly also\n * refuses the clicks that would open the operator menu. The change event fires\n * when either operand changes or a different operator is picked.\n */\nclass CompareFilter extends Input {\n static observed = ['value:json', 'operators:csv'];\n static attributes = ['operator'];\n static template = `\n <label>{{{{ slots.default }}}}</label>\n {{{{ slots.info }}}}\n <ful-control-group>\n <ful-affix data-tpl-if=\"slots.before\">{{{{ slots.before }}}}</ful-affix>\n <ful-affix>\n <button data-ref=\"operator\" type=\"button\" form=\"\" aria-expanded=\"false\" aria-haspopup=\"true\"></button>\n <ul popover role=\"menu\"></ul>\n </ful-affix>\n <ful-control>\n <input data-ref=\"value1\" data-tpl-type=\"type\" form=\"\">\n <input data-ref=\"value2\" data-tpl-type=\"type\" form=\"\" hidden>\n </ful-control>\n <ful-affix data-tpl-if=\"slots.after\">{{{{ slots.after }}}}</ful-affix>\n </ful-control-group>\n <ful-field-error></ful-field-error>\n `;\n _operator;\n _container;\n _value1;\n _value2;\n _build(conf) {\n const pieces = super._build(conf);\n const fragment = pieces.fragment;\n this._container = fragment.querySelector('ful-control-group');\n this._value1 = fragment.querySelector('[data-ref=value1]');\n this._value2 = fragment.querySelector('[data-ref=value2]');\n this._operator = new ChoiceButton(/** @type HTMLElement */ (fragment.querySelector('[data-ref=operator]')), {\n vocabulary: this._vocabulary(),\n glyphs: GLYPHS,\n labelFor: operatorLabel,\n interactive: () => this._interactive(),\n onPick: () => {\n this._syncBetween();\n this._notifyChange();\n },\n });\n this.operators = this.declared('operators');\n if (this._operator.value === null) {\n this._showDefaultOperator();\n }\n fixChoice(this, this._operator, {\n singular: 'operator',\n plural: 'operators',\n vocabulary: this._vocabulary(),\n fallback: this._defaultOperator(),\n });\n return { ...pieces, freeze: this._container, also: [this._value2] };\n }\n _showDefaultOperator() {\n this._showOperator(this._operator.preferring(this._defaultOperator()));\n }\n /**\n * Restores the declared `value` tuple, operator included, as a field reset\n * does. Without a `value` attribute it empties the operands and also shows\n * the default operator again, or the first whitelisted one where the\n * default is not allowed.\n */\n formResetCallback() {\n super.formResetCallback();\n if (!this.hasAttribute('value')) {\n this._showDefaultOperator();\n }\n }\n /**\n * The native input type both operands render with.\n * @returns {string}\n */\n _type() {\n return 'text';\n }\n /**\n * Converts an operand from its input's value to the form the tuple carries.\n * @param {string} v\n * @returns {string|null}\n */\n _serialize(v) {\n return v;\n }\n /**\n * Converts an operand from the tuple to the value its input shows.\n * @param {string} v\n * @returns {string}\n */\n _deserialize(v) {\n return v;\n }\n /**\n * The operator shown on render and after a valueless reset, when the whitelist allows it.\n * @returns {string}\n */\n _defaultOperator() {\n return 'EQ';\n }\n /**\n * Every operator the filter knows, which `operators` narrows.\n * @returns {string[]}\n */\n _vocabulary() {\n return COMPARE_OPERATORS;\n }\n _declaredOperators;\n /**\n * The operators the menu offers, narrowed to the vocabulary: an empty list,\n * or one where no name is known, offers all of it. A single operator pins\n * the button, and an assigned tuple then carries that operator whatever it\n * names. An assignment made before the upgrade is held narrowed and\n * answered back until the render, when the `operators` attribute is applied\n * over it, an absent attribute meaning the whole vocabulary. Assignments are\n * ignored while the `operator` attribute fixes the operator.\n * @returns {string[]|undefined} undefined before the upgrade when nothing was assigned\n */\n get operators() {\n return this._operator ? this._operator.allowed : this._declaredOperators;\n }\n /** @param {string[]|null} declared */\n set operators(declared) {\n if (this.declared('operator') !== null) {\n return;\n }\n if (!this._operator) {\n this._declaredOperators = ChoiceButton.narrow(declared, this._vocabulary());\n return;\n }\n this._operator.allowed = declared;\n this._syncBetween();\n }\n /**\n * The filter's tuple, `[operator, operand]` or `[operator, from, to]` for\n * BETWEEN, each operand converted by `_serialize` (an ISO instant for the\n * instant filter). Null while any operand the operator uses is empty.\n * @returns {any[]|null}\n */\n get value() {\n return this._tuple();\n }\n /**\n * Shows a tuple: the operator it names, unless a pinned or fixed operator\n * replaces it, and its operands, an operand missing from a shorter tuple\n * leaving its input empty. Null or undefined empties both operands and\n * keeps the operator.\n * @param {any[]|null|undefined} v\n */\n set value(v) {\n this._applyTuple(v);\n }\n _tuple() {\n const operator = this._operator.value;\n const values = this.#operands();\n return values.some((v) => v === '') ? null : [operator, ...values.map((v) => this._serialize(v))];\n }\n _applyTuple(v) {\n if (v == null) {\n this._value1.value = '';\n this._value2.value = '';\n return;\n }\n const [declared, ...values] = v;\n const operator = this._operator.pinned ? this._operator.allowed[0] : declared;\n this._showOperator(operator);\n this._value1.value = values[0] ? this._deserialize(values[0]) : (values[0] ?? '');\n this._value2.value = values[1] ? this._deserialize(values[1]) : (values[1] ?? '');\n }\n _showOperator(operator) {\n this._operator.value = operator;\n this._syncBetween();\n }\n /** Shows the second operand only while the operator is BETWEEN. */\n _syncBetween() {\n this._value2.toggleAttribute('hidden', this._operator.value !== 'BETWEEN');\n }\n /**\n * The operator and the operands the operator uses, as their inputs show\n * them rather than as serialized: a date filter describes what is in its\n * control, not the ISO string it sends. Null while every one of those\n * operands is empty, so a BETWEEN with one bound answers that bound while\n * its value is still null.\n * @returns {FilterCriterion|null}\n */\n get criterion() {\n return asCriterion(labelTextOf(this), this._operator.value, this.#operands());\n }\n #operands() {\n return this._operator.value === 'BETWEEN' ? [this._value1.value, this._value2.value] : [this._value1.value];\n }\n /**\n * The field's own disabled claim. Setting it disables both operands and\n * every menu button the filter composes; a button pinned to one choice\n * stays disabled when the claim is lifted.\n * @returns {boolean}\n */\n get disabled() {\n return super.disabled;\n }\n /** @param {boolean} d */\n set disabled(d) {\n super.disabled = d;\n for (const choice of this._choices()) {\n choice.claimed = d;\n }\n }\n /**\n * The menu buttons the filter composes, which the disabled claim reaches. A\n * subclass adding a menu appends its own to the base's.\n * @returns {ChoiceButton[]}\n */\n _choices() {\n return [this._operator].filter((c) => c);\n }\n}\n\n/**\n * The compare filter over ISO instants, defaulting to LTE. The operands are\n * shown as local date and time in the page's timezone and carried in the tuple\n * as UTC ISO instants.\n */\nclass InstantFilter extends CompareFilter {\n _defaultOperator() {\n return 'LTE';\n }\n _type() {\n return 'datetime-local';\n }\n _serialize(v) {\n return Instant.localToIso(v);\n }\n _deserialize(v) {\n return Instant.isoToLocal(v);\n }\n}\n\n/** The compare filter over dates. */\nclass LocalDateFilter extends CompareFilter {\n _type() {\n return 'date';\n }\n}\n\n/** The compare filter over numbers. */\nclass NumberFilter extends CompareFilter {\n _type() {\n return 'number';\n }\n}\n\n/**\n * The compare filter over text, defaulting to CONTAINS and adding CONTAINS,\n * STARTS_WITH and ENDS_WITH to the compare operators.\n *\n * Its tuple carries a case sensitivity after the operator, `[operator,\n * sensitivity, operand]` or `[operator, sensitivity, from, to]`, the\n * sensitivity being IGNORE_CASE (the default) or CASE_SENSITIVE and switched\n * through a second menu. The `sensitivities` attribute whitelists that menu and\n * `sensitivity` fixes one mode, with the same rules and warnings as\n * `operators` and `operator`.\n */\nclass TextFilter extends CompareFilter {\n static observed = ['sensitivities:csv'];\n static attributes = ['sensitivity'];\n static template = `\n <label>{{{{ slots.default }}}}</label>\n {{{{ slots.info }}}}\n <ful-control-group>\n <ful-affix data-tpl-if=\"slots.before\">{{{{ slots.before }}}}</ful-affix>\n <ful-affix>\n <button data-ref=\"operator\" type=\"button\" form=\"\" aria-expanded=\"false\" aria-haspopup=\"true\"></button>\n <ul popover role=\"menu\"></ul>\n <button data-ref=\"sensitivity\" type=\"button\" form=\"\" aria-expanded=\"false\" aria-haspopup=\"true\"></button>\n <ul popover role=\"menu\"></ul>\n </ful-affix>\n <ful-control>\n <input data-ref=\"value1\" data-tpl-type=\"type\" form=\"\">\n <input data-ref=\"value2\" data-tpl-type=\"type\" form=\"\" hidden>\n </ful-control>\n <ful-affix data-tpl-if=\"slots.after\">{{{{ slots.after }}}}</ful-affix>\n </ful-control-group>\n <ful-field-error></ful-field-error>\n `;\n _defaultOperator() {\n return 'CONTAINS';\n }\n _vocabulary() {\n return TEXT_OPERATORS;\n }\n _sensitivityButton;\n _build(conf) {\n const pieces = super._build(conf);\n this._sensitivityButton = new ChoiceButton(\n /** @type HTMLElement */ (pieces.fragment.querySelector('[data-ref=sensitivity]')),\n {\n vocabulary: SENSITIVITIES,\n glyphs: SENSITIVITY_GLYPHS,\n labelFor: sensitivityLabel,\n interactive: () => this._interactive(),\n onPick: () => this._notifyChange(),\n },\n );\n this._sensitivityButton.allowed = null;\n this._sensitivityButton.value = SENSITIVITIES[0];\n fixChoice(this, this._sensitivityButton, {\n singular: 'sensitivity',\n plural: 'sensitivities',\n vocabulary: SENSITIVITIES,\n fallback: 'IGNORE_CASE',\n });\n return pieces;\n }\n _choices() {\n return [...super._choices(), this._sensitivityButton].filter((c) => c);\n }\n get _sensitivity() {\n return this._sensitivityButton.value;\n }\n _declaredSensitivities;\n /**\n * The sensitivities the menu offers, narrowed to IGNORE_CASE and\n * CASE_SENSITIVE: an empty list, or one where no name is known, offers both.\n * When the mode shown leaves the list, the first listed one is shown. Held\n * before the upgrade and ignored under a fixed `sensitivity`, as `operators` is.\n * @returns {string[]|undefined} undefined before the upgrade when nothing was assigned\n */\n get sensitivities() {\n return this._sensitivityButton ? this._sensitivityButton.allowed : this._declaredSensitivities;\n }\n /** @param {string[]|null} declared */\n set sensitivities(declared) {\n if (this.declared('sensitivity') !== null) {\n return;\n }\n if (!this._sensitivityButton) {\n this._declaredSensitivities = ChoiceButton.narrow(declared, SENSITIVITIES);\n return;\n }\n const previous = this._sensitivityButton.value;\n this._sensitivityButton.allowed = declared;\n this._sensitivityButton.value = this._sensitivityButton.preferring(previous);\n }\n /**\n * The tuple with the sensitivity after the operator, `[operator,\n * sensitivity, ...operands]`. Null while any operand the operator uses is empty.\n * @returns {any[]|null}\n */\n get value() {\n const tuple = this._tuple();\n return tuple == null ? null : [tuple[0], this._sensitivity, ...tuple.slice(1)];\n }\n /**\n * Shows a tuple as the compare filter does, reading the sensitivity at\n * index 1. A sensitivity the whitelist does not allow leaves the current\n * one in place. Null or undefined empties the operands and keeps the\n * operator and the sensitivity.\n * @param {any[]|null|undefined} v\n */\n set value(v) {\n if (v == null) {\n this._applyTuple(v);\n return;\n }\n if (this._sensitivityButton.allowed.includes(v[1])) {\n this._sensitivityButton.value = v[1];\n }\n this._applyTuple([v[0], ...v.slice(2)]);\n }\n /**\n * Restores the declared `value` tuple, sensitivity included. Without a\n * `value` attribute it also shows the default operator and IGNORE_CASE\n * again, or the first whitelisted mode where IGNORE_CASE is not allowed.\n */\n formResetCallback() {\n super.formResetCallback();\n if (!this.hasAttribute('value')) {\n this._sensitivityButton.value = this._sensitivityButton.preferring('IGNORE_CASE');\n }\n }\n}\n\nconst BOOLEAN_VALUES = ['', 'true', 'false'];\nconst BOOLEAN_VALUE_GLYPHS = { true: '✓', false: '✗' };\n\n/**\n * The boolean filter: an EQ or NEQ operator menu and a value menu of any, yes\n * and no, the value button showing the localized word.\n *\n * The value is `[operator, 'true']` or `[operator, 'false']`, null while the\n * value menu is on any. The `operators` attribute whitelists the operator menu\n * as on the compare filters. The disabled claim reaches the value button and\n * both menus, and readonly refuses the clicks that would open them. The\n * required and readonly claims reflect on the host only: no `aria-required` or\n * `aria-readonly` is written, since the value button's role accepts neither.\n */\nclass BooleanFilter extends Field {\n static observed = ['value:json', 'operators:csv'];\n static slots = true;\n /**\n * The operators the filter knows, which `operators` narrows.\n * @type {string[]}\n */\n static OPERATORS = ['EQ', 'NEQ'];\n /**\n * The operator shown on render and after a valueless reset, or the first\n * whitelisted one where the whitelist excludes it.\n * @type {string}\n */\n static DEFAULT_OPERATOR = 'EQ';\n static template = `\n <label>{{{{ slots.default }}}}</label>\n {{{{ slots.info }}}}\n <ful-control-group>\n <ful-affix data-tpl-if=\"slots.before\">{{{{ slots.before }}}}</ful-affix>\n <ful-affix>\n <button data-ref=\"operator\" type=\"button\" form=\"\" aria-expanded=\"false\" aria-haspopup=\"true\"></button>\n <ul popover role=\"menu\"></ul>\n </ful-affix>\n <button data-ref=\"value\" type=\"button\" form=\"\"></button>\n <ul popover role=\"menu\"></ul>\n <ful-affix data-tpl-if=\"slots.after\">{{{{ slots.after }}}}</ful-affix>\n </ful-control-group>\n <ful-field-error></ful-field-error>\n `;\n _operator;\n _value;\n _container;\n _build({ slots }) {\n const fragment = this.template().withOverlay({ slots }).render();\n this._container = fragment.querySelector('ful-control-group');\n const valueButton = /** @type {HTMLElement} */ (fragment.querySelector('[data-ref=value]'));\n this._operator = new ChoiceButton(/** @type {HTMLElement} */ (fragment.querySelector('[data-ref=operator]')), {\n vocabulary: BooleanFilter.OPERATORS,\n glyphs: GLYPHS,\n labelFor: operatorLabel,\n interactive: () => this._interactive(),\n onPick: () => this._notifyChange(),\n });\n this._value = new ChoiceButton(valueButton, {\n vocabulary: BOOLEAN_VALUES,\n glyphs: BOOLEAN_VALUE_GLYPHS,\n labelFor: booleanValueLabel,\n display: booleanValueLabel,\n interactive: () => this._interactive(),\n onPick: () => this._notifyChange(),\n });\n this.operators = this.declared('operators');\n this._operator.value = this._operator.preferring(BooleanFilter.DEFAULT_OPERATOR);\n this._value.allowed = null;\n this._value.value = '';\n return {\n fragment,\n control: valueButton,\n error: fragment.querySelector('ful-field-error'),\n label: fragment.querySelector('label'),\n announces: null,\n freeze: this._container,\n };\n }\n _declaredOperators;\n /**\n * The operators the menu offers, narrowed to EQ and NEQ: an empty list, or\n * one where no name is known, offers both, and a single one pins the\n * button. Held before the upgrade and replaced by the `operators` attribute\n * at the render, as on the compare filters.\n * @returns {string[]|undefined} undefined before the upgrade when nothing was assigned\n */\n get operators() {\n return this._operator ? this._operator.allowed : this._declaredOperators;\n }\n /** @param {string[]|null} declared */\n set operators(declared) {\n if (!this._operator) {\n this._declaredOperators = ChoiceButton.narrow(declared, this._vocabulary());\n return;\n }\n this._operator.allowed = declared;\n }\n /** @returns {string[]} */\n _vocabulary() {\n return BooleanFilter.OPERATORS;\n }\n /**\n * `[operator, token]`, the token being 'true' or 'false'; null while the value menu is on any.\n * @returns {string[]|null}\n */\n get value() {\n return this._value.value === '' ? null : [this._operator.value, this._value.value];\n }\n /**\n * Shows a tuple: its operator, unless a pinned operator replaces it, and its\n * token, a missing token meaning any. Null or undefined sets the value menu\n * back to any and keeps the operator.\n * @param {any[]|null|undefined} v\n */\n set value(v) {\n if (v == null) {\n this._value.value = '';\n return;\n }\n this._operator.value = this._operator.pinned ? this._operator.allowed[0] : v[0];\n this._value.value = v[1] ?? '';\n }\n /**\n * Restores the declared `value` tuple. Without a `value` attribute it sets\n * the value menu back to any and also shows the default operator again.\n */\n formResetCallback() {\n super.formResetCallback();\n if (!this.hasAttribute('value')) {\n this._operator.value = this._operator.preferring(BooleanFilter.DEFAULT_OPERATOR);\n }\n }\n /**\n * The operator and the localized word the value menu shows, not the token.\n * Null while the value menu is on any.\n * @returns {FilterCriterion|null}\n */\n get criterion() {\n const token = this._value.value;\n return asCriterion(labelTextOf(this), this._operator.value, [token === '' ? '' : booleanValueLabel(token)]);\n }\n /**\n * The field's own disabled claim. Setting it disables the value button and\n * both menu buttons; an operator button pinned to one choice stays disabled\n * when the claim is lifted.\n * @returns {boolean}\n */\n get disabled() {\n return super.disabled;\n }\n /** @param {boolean} d */\n set disabled(d) {\n super.disabled = d;\n for (const choice of [this._operator, this._value].filter((c) => c)) {\n choice.claimed = d;\n }\n }\n}\n\n/**\n * Set membership over a select's vocabulary, answering for both of data-jpa's\n * set annotations: InEnum and InList take the same bare array of values and no\n * operator, differing only in what the server converts them to. A declared\n * `operator` attribute is sent in front of the keys instead, for a server field\n * that reads the set through a compare.\n */\nclass InFilter extends Select {\n static attributes = ['operator'];\n #keys() {\n const chosen = super.value;\n if (this.multiple) {\n return chosen;\n }\n return chosen === null || chosen === undefined ? [] : [chosen];\n }\n /**\n * The chosen keys as an array, a single choice included, led by the\n * declared `operator` when there is one. Null while nothing is chosen, so\n * that a table drops the filter instead of sending an empty set that\n * matches nothing.\n * @returns {any[]|null}\n */\n get value() {\n const keys = this.#keys();\n if (keys.length === 0) {\n return null;\n }\n const operator = this.declared('operator');\n return operator ? [operator, ...keys] : keys;\n }\n /**\n * Selects the keys of an array or a single bare key; a leading element equal\n * to the declared `operator` is dropped first, so the filter takes back what\n * it answered. A single select takes the first key. Null or undefined clears\n * the selection.\n * @param {any} v\n */\n set value(v) {\n const operator = this.declared('operator');\n let keys = v === null || v === undefined ? [] : Array.isArray(v) ? v : [v];\n if (operator && keys[0] === operator) {\n keys = keys.slice(1);\n }\n super.value = this.multiple ? keys : (keys[0] ?? null);\n }\n /**\n * The declared operator, or null, and the labels of the chosen entries. Null\n * while nothing is chosen.\n * @returns {FilterCriterion|null}\n */\n get criterion() {\n return asCriterion(\n labelTextOf(this),\n this.declared('operator'),\n [super.entry]\n .flat()\n .filter((e) => e)\n .map((e) => /** @type {{ label: string }} */ (e).label),\n );\n }\n}\n\nexport { BooleanFilter, CompareFilter, InFilter, InstantFilter, LocalDateFilter, NumberFilter, TextFilter };\n","import { ParsedElement } from '../../ftl/index.mjs';\nimport { describable } from '../descriptions.mjs';\nimport { Anchors } from './anchors.mjs';\n\n/**\n * An icon button that toggles a native popover, a `ful-note`, holding the\n * default slot as a short explanation. The popover gives light dismiss and\n * Escape, and the button carries an `aria-expanded` kept in step with it and\n * a localized `aria-label`.\n *\n * The marker is the `ful-icon` that `Tooltip.config.icon` names for the whole\n * page, or the one the `icon` attribute names for a single tooltip. A name the\n * library does not paint is declared by the page as\n * `ful-icon[name='...'] { mask-image: ... }`.\n *\n * `placement` picks the side of the marker the note opens on: `top` (the\n * default), `bottom`, `left` or `right`. The note is placed in script on every\n * platform, centred on the marker, clamped into the viewport and following the\n * marker on scroll and resize, with a callout on the edge facing the marker.\n *\n * `describes` offers the note to the nearest ancestor that takes a description\n * (see `describable`), a field's control in practice: when it is taken, the\n * note becomes part of that control's accessible description and the marker\n * leaves the tab order, staying clickable. When nothing takes it, the marker\n * keeps its tab stop and a warning is logged.\n */\nclass Tooltip extends ParsedElement {\n static slots = true;\n static attributes = ['placement', 'icon', 'describes:presence'];\n /** The page-wide defaults: `icon` is the `ful-icon` name of the marker. */\n static config = {\n icon: 'info-circle-fill',\n };\n static template = `\n <span role=\"button\" tabindex=\"0\" class=\"ful-tip\" data-ref=\"trigger\" data-tpl-aria-label=\"#l10n:t('info.tooltip')\"><ful-icon data-tpl-name=\"icon ?? config.icon\" aria-hidden=\"true\"></ful-icon></span>\n <ful-note popover data-ref=\"content\">{{{{ slots.default }}}}</ful-note>\n `;\n /**\n * @param {{ slots: Record<string, DocumentFragment> }} c\n */\n render({ slots }) {\n const fragment = this.template().withOverlay({ slots, icon: this.declared('icon') }).render();\n const trigger = /** @type {HTMLElement} */ (fragment.querySelector('[data-ref=trigger]'));\n const content = /** @type {HTMLElement} */ (fragment.querySelector('[data-ref=content]'));\n Anchors.wire(trigger, content, { prefix: 'ful-tooltip', invoke: true, expanded: true, handPlace: true });\n content.setAttribute('placement', this.declared('placement') ?? 'top');\n this.replaceChildren(fragment);\n if (this.declared('describes')) {\n Tooltip.#describe(this, trigger, content);\n }\n }\n /**\n * @param {Tooltip} tooltip\n * @param {HTMLElement} trigger\n * @param {HTMLElement} content\n */\n static #describe(tooltip, trigger, content) {\n if (!describable(tooltip)?.describedBy(content)) {\n console.warn('a ful-tooltip declares describes but stands in nothing that takes a description', tooltip);\n return;\n }\n trigger.tabIndex = -1;\n }\n}\n\nexport { Tooltip };\n","import { Localization } from '../../ftl/index.mjs';\nimport { Claims } from '../claims.mjs';\n\n/**\n * The section requests shared by ful-tabs, ful-wizard, ful-dialog and\n * ful-drawer. Each activation of a section fires a family of events on the host\n * component and waits for the answers that listeners registered through\n * `AsyncEvents.asyncOn` attach to them. The events target the component, so\n * `e.target.localName` names the family and `e.target === e.currentTarget`\n * separates a host's own sections from those of a nested component, while\n * `detail.section` is the element the content goes in.\n *\n * While an answer is pending, from the next animation frame, the section\n * carries the `loading` attribute and `aria-busy=\"true\"`; answers that settle\n * before that frame show neither. A new request for the same section\n * supersedes the one in flight, which then no longer touches the section's\n * chrome. A failure removes the section's previous error and prepends a\n * `.ful-section-error` with the `alert` role, holding the reasons of the\n * failure's problems, one per line, or its message when it carries none.\n */\nclass SectionRequests {\n /** @type {WeakSet<Element>} */\n #entered = new WeakSet();\n /** @type {WeakMap<Element, Claims>} */\n #claims = new WeakMap();\n\n /**\n * Fires `section:requested`, then `section:requested:#<index>` when an index\n * is given, then `section:requested:<name>` when a name is given, each\n * bubbling from `host` with the same detail `{ name, section, index, first }`,\n * and awaits every answer attached to any of them. `first` is true until a\n * request for the section is answered by at least one listener, so a request\n * nobody listened to does not spend it. A request with answers removes the\n * error a previous failure painted before it waits.\n * @param {Element} host the component the events are dispatched on\n * @param {Element} section the element the answers deliver into\n * @param {string|null} name the section's `data-step`, when it has one\n * @param {number|null} index the section's zero-based position, when it has one\n * @returns {Promise<any[]|undefined>} the answers in the order they were\n * attached, or undefined when nobody listened\n * @throws what the first failing answer rejected with, after painting its\n * problems in the section unless a newer request superseded this one\n */\n async request(host, section, name, index) {\n const first = !this.#entered.has(section);\n const detail = { name, section, index, first };\n const types = [\n 'section:requested',\n ...(index !== null && index !== undefined ? [`section:requested:#${index}`] : []),\n ...(name ? [`section:requested:${name}`] : []),\n ];\n const promises = [];\n for (const type of types) {\n const evt = /** @type {CustomEvent & { async?: { promises: Promise<any>[] } }} */ (\n new CustomEvent(type, { bubbles: true, detail })\n );\n host.dispatchEvent(evt);\n promises.push(...(evt.async?.promises ?? []));\n }\n if (promises.length === 0) {\n return undefined;\n }\n this.#entered.add(section);\n let claims = this.#claims.get(section);\n if (!claims) {\n claims = new Claims();\n this.#claims.set(section, claims);\n }\n const claim = claims.take();\n const owned = () => !claim.stale;\n section.querySelector(':scope > .ful-section-error')?.remove();\n const frame = requestAnimationFrame(() => {\n if (owned()) {\n section.toggleAttribute('loading', true);\n section.setAttribute('aria-busy', 'true');\n }\n });\n try {\n return await Promise.all(promises);\n } catch (cause) {\n if (owned()) {\n this.#paintError(section, cause);\n }\n throw cause;\n } finally {\n cancelAnimationFrame(frame);\n if (owned()) {\n section.toggleAttribute('loading', false);\n section.removeAttribute('aria-busy');\n }\n }\n }\n\n /**\n * @param {Element} section\n * @param {unknown} cause\n */\n #paintError(section, cause) {\n section.querySelector(':scope > .ful-section-error')?.remove();\n const error = document.createElement('div');\n error.className = 'ful-section-error';\n error.setAttribute('role', 'alert');\n error.textContent = Localization.of().failure(cause);\n section.prepend(error);\n }\n}\n\nexport { SectionRequests };\n","import { Localization, Nodes } from '../../ftl/index.mjs';\nimport { Claims } from '../claims.mjs';\nimport { SectionRequests } from '../events/sections.mjs';\n\n/**\n * The sections a modal disclosure renders inside its native `<dialog>`: the\n * content section a caller fills, and the loading and error sections shown\n * while `update()` waits and when it fails. It also wires the gestures the\n * dialog and the drawer share: a dismissal on a press and release both on the\n * backdrop, and an answer on a `ful-form` submit in the content.\n *\n * The element owning it keeps the opening, the closing and the outcome; the\n * sections only paint and request.\n */\nclass DialogSections {\n #host;\n #dialog;\n #section;\n #loading;\n #error;\n #requests = new SectionRequests();\n #updates = new Claims();\n /** @type {Promise<boolean>|null} */\n #confirming = null;\n /**\n * @param {HTMLElement} host the element the section requests are dispatched on\n * @param {DocumentFragment} fragment the rendered template, holding a\n * `[data-ref=dialog]` and, optionally, the content section and the\n * `[data-ref=loading]` and `[data-ref=error]` sections: a subclass template\n * without a content section can be opened and closed, but not updated\n * @param {string} content the `data-ref` of the content section\n */\n constructor(host, fragment, content) {\n this.#host = host;\n this.#dialog = /** @type {HTMLDialogElement} */ (fragment.querySelector('[data-ref=dialog]'));\n this.#section = /** @type {HTMLElement} */ (fragment.querySelector(`[data-ref=${content}]`));\n this.#loading = fragment.querySelector('[data-ref=loading]');\n this.#error = fragment.querySelector('[data-ref=error]');\n }\n /** @returns {HTMLDialogElement} */\n get dialog() {\n return this.#dialog;\n }\n /** @returns {HTMLElement} the content section */\n get section() {\n return this.#section;\n }\n /**\n * Whether a `ful-form` of this dialog, not one of a dialog nested in it,\n * holds unsaved edits (see `Form.dirty`).\n * @returns {boolean}\n */\n get dirty() {\n return Array.from(this.#dialog.querySelectorAll('ful-form')).some(\n (form) => form.closest('dialog') === this.#dialog && /** @type {any} */ (form).dirty,\n );\n }\n /**\n * Dispatches the dismissal on the host and calls `close` unless a listener\n * prevented it or, with `confirm` given and the dialog `dirty`, `confirm`\n * answers false. A dismissal that is not cancelable announces a close the\n * platform makes whatever the page does, so nothing is asked and `close` is\n * not called for it. While `confirm` is pending a further dismissal waits\n * for the same answer, and a dialog closed meanwhile is not closed again.\n * @param {CustomEvent} asked\n * @param {() => void} close\n * @param {(() => Promise<boolean>)|null} confirm asks whether to drop the unsaved edits\n * @returns {Promise<boolean>} whether the dismissal closes the dialog\n */\n dismiss(asked, close, confirm) {\n if (this.#confirming) {\n return this.#confirming;\n }\n if (!this.#host.dispatchEvent(asked)) {\n return Promise.resolve(false);\n }\n if (!asked.cancelable) {\n return Promise.resolve(true);\n }\n if (!confirm || !this.dirty) {\n close();\n return Promise.resolve(true);\n }\n this.#confirming = confirm()\n .then((drop) => {\n if (drop && this.#dialog.open) {\n close();\n }\n return drop;\n })\n .finally(() => {\n this.#confirming = null;\n });\n return this.#confirming;\n }\n /**\n * Calls `dismiss` when a press and its release both land on the backdrop,\n * so a selection dragged out of the panel and released outside does not.\n * @param {() => void} dismiss\n */\n onBackdrop(dismiss) {\n let pressedOutside = false;\n this.#dialog.addEventListener('mousedown', (e) => {\n pressedOutside = e.target === this.#dialog;\n });\n this.#dialog.addEventListener('click', (e) => {\n if (pressedOutside && e.target === this.#dialog) {\n dismiss();\n }\n });\n }\n /**\n * Calls `answer` with `detail.response` when a `ful-form` that is a direct\n * child of the content section dispatches `submit:success`. The listener sits\n * on the section, so a form delivered by `update()` is covered, and a form\n * deeper in the content, such as a `ful-table`'s filters, is not.\n * @param {(response: any) => void} answer\n */\n onSubmitted(answer) {\n this.#section.addEventListener('submit:success', (/** @type any */ e) => {\n if (e.target !== Nodes.queryChildren(this.#section, 'ful-form')) {\n return;\n }\n answer(e.detail.response);\n });\n }\n /** Hides and empties the error section, hides the loading one and shows the content. */\n restChrome() {\n this.#error?.replaceChildren();\n this.#error?.setAttribute('hidden', '');\n this.#loading?.setAttribute('hidden', '');\n this.#section?.removeAttribute('hidden');\n }\n /**\n * Dispatches `section:requested` for the content section on the host. A\n * failed request is painted into the section.\n * @returns {Promise<any[]|undefined>} the listeners' answers, undefined when\n * nobody answered or the request failed; it never rejects\n */\n request() {\n return this.#requests.request(this.#host, this.#section, null, null).catch(() => undefined);\n }\n /**\n * Empties and hides the content section, shows the loading section, calls\n * `show`, and fills the content with what the callback resolves to. A\n * rejection is shown, as the problems' reasons, in the error section, and\n * the content is hidden. When a newer `update()` starts before the callback\n * settles, this call paints nothing and resolves `null`, the section being\n * the newer call's; it still rejects with the callback's error.\n * @param {() => Node|string|Promise<Node|string>} cb producing the content\n * @param {() => void} show opens the dialog when it is closed\n * @returns {Promise<HTMLElement|null>} the content section, or `null` for a\n * call a newer one overtook\n * @throws {any} what the callback threw or rejected with\n */\n async update(cb, show) {\n const claim = this.#updates.take();\n this.#section.replaceChildren();\n this.restChrome();\n this.#loading?.removeAttribute('hidden');\n this.#section.setAttribute('hidden', '');\n show();\n try {\n const delivered = await cb();\n if (claim.stale) {\n return null;\n }\n this.#section.replaceChildren(delivered);\n this.#loading?.setAttribute('hidden', '');\n this.#section.removeAttribute('hidden');\n return this.#section;\n } catch (/** @type any */ e) {\n if (!claim.stale) {\n this.#error?.removeAttribute('hidden');\n if (this.#error) {\n this.#error.textContent = Localization.of().failure(e);\n }\n this.#loading?.setAttribute('hidden', '');\n this.#section.setAttribute('hidden', '');\n }\n throw e;\n }\n }\n}\n\nexport { DialogSections };\n","let targetsWired = false;\n/**\n * Makes any element carrying `dialog-target` open the element whose id it\n * names, clones included, which is how the dialog and the drawer are opened\n * from markup. One click listener on the document finds the nearest\n * `[dialog-target]` around the click target and calls `open()` on the named\n * element when it has one; an id naming nothing is ignored. Calls after the\n * first do nothing.\n */\nconst wireTargets = () => {\n if (targetsWired) {\n return;\n }\n targetsWired = true;\n document.addEventListener('click', (/** @type any */ e) => {\n const trigger = e.target.closest?.('[dialog-target]');\n if (!trigger) {\n return;\n }\n /** @type {any} */ (document.getElementById(trigger.getAttribute('dialog-target')))?.open?.();\n });\n};\n\nexport { wireTargets };\n","import { Attributes, Localization, ParsedElement, Rendering } from '../../ftl/index.mjs';\nimport { DialogSections } from './dialog-sections.mjs';\nimport { wireTargets } from './targets.mjs';\n\n/**\n * How a dialog ended. `dismissed` is true for Escape, the close button, a\n * backdrop click, a `data-result=\"\"` button, `close()` without a result and a\n * removal from the document; `result` is the `data-result` of the button, or\n * the argument of `close(result)`, that answered; `response` is what the form\n * answered with under `close-on-submit`. Whichever of `result` and `response`\n * did not answer is null, as both are on a dismissal.\n * @typedef {{ dismissed: boolean, result: string|null, response: any }} DialogOutcome\n */\n\n/**\n * A modal dialog on the native `<dialog>`, rendered with a header, a body and\n * a footer. `open()` and `ask()` show it and resolve with a `DialogOutcome`.\n *\n * The `header` attribute is the title, rendered as an `h2` that names the\n * dialog through `aria-labelledby`; without it the dialog is unnamed. The\n * `header` slot is rendered in the header before the title, the default slot\n * is the body, and the `buttons` slot is rendered in the footer. Without a\n * `buttons` slot, and without `close-on-submit`, the footer holds a localized\n * acknowledge button answering `acknowledged`.\n *\n * Any button inside the dialog carrying `data-result` closes it with that\n * result, an empty one being a dismissal. The header carries a close button,\n * and a press and release both on the backdrop close the dialog, each as a\n * dismissal, as Escape does.\n *\n * Those three gestures go through `dismiss(reason)`, the reason being\n * `button`, `backdrop` or `escape`: before it closes the dialog, the element\n * dispatches a cancelable, non-bubbling `dialog:dismiss` with\n * `detail: { reason }`, and a listener calling `preventDefault()` keeps it\n * open. Under `guard-dismiss`, a dismissal nobody refused, while a `ful-form`\n * of the dialog holds unsaved edits (see `Form.dirty`), first asks the user,\n * through `Dialog.confirm`, whether to close and drop them. A `data-result`\n * button, `close-on-submit`, `close()` and `update()` are answers or the page\n * deciding: they dispatch nothing and ask nothing.\n *\n * The platform lets a page refuse Escape once per user interaction: a second\n * Escape with no click or keystroke in between closes the dialog whatever the\n * page does, `requires-answer` and `guard-dismiss` included. That close is\n * still announced by a `dialog:dismiss`, which is then not cancelable.\n *\n * `requires-answer` withholds the close button and refuses Escape and the\n * backdrop, so the dialog is closed only by a button carrying `data-result`\n * or from code, through `close()` or `dismiss()`.\n *\n * `close-on-submit` closes the dialog when a `ful-form` that is a direct child\n * of the body dispatches `submit:success`, answering with its\n * `detail.response`. A form deeper in the body, such as the filter form of a\n * `ful-table`, does not close it. The listener sits on the body, so a form\n * delivered by `update()` is covered as well.\n *\n * Every close dispatches a non-bubbling `close` event on the element carrying\n * the `DialogOutcome` as `detail`, before the pending `ask()` calls resolve.\n * An element anywhere in the page carrying `dialog-target` set to the\n * element's id opens it on click.\n *\n * The chrome is styled by class as well as by tag, so a plain `<dialog\n * class=\"ful-dialog\">` written by a page gets the same look: the tag form\n * matches a direct child, and `ful-dialog-header`, `ful-dialog-body` and\n * `ful-dialog-footer` match at any depth, as a dialog whose content is wrapped\n * in a form needs.\n */\nclass Dialog extends ParsedElement {\n static attributes = ['header', 'requires-answer:presence', 'close-on-submit:presence', 'guard-dismiss:presence'];\n static slots = true;\n static template = `\n <dialog data-ref=\"dialog\" class=\"ful-dialog\">\n <header data-tpl-if=\"header || slots.header || !requiresAnswer\" class=\"ful-dialog-header\">\n {{{{ slots.header }}}}\n <h2 data-tpl-if=\"header\">{{ header }}</h2>\n <button data-tpl-if=\"!requiresAnswer\" type=\"button\" data-ref=\"close\" data-tpl-aria-label=\"#l10n:t('dialog.close')\"><ful-icon name=\"x-lg\" aria-hidden=\"true\"></ful-icon></button>\n </header>\n <section data-ref=\"loading\" hidden><ful-spinner class=\"centered\" role=\"status\"><span class=\"ful-sr-only\">{{ #l10n:t('spinner.loading') }}</span></ful-spinner></section>\n <section data-ref=\"error\" role=\"alert\" hidden></section>\n <div data-ref=\"body\" class=\"ful-dialog-body\">{{{{ slots.default }}}}</div>\n <footer class=\"ful-dialog-footer\">\n <button type=\"button\" data-ref=\"acknowledge\" data-result=\"acknowledged\" data-tpl-if=\"!slots.buttons && !closeOnSubmit\" data-tpl-aria-label=\"#l10n:t('dialog.acknowledge')\">{{ #l10n:t('dialog.acknowledge') }}</button>\n {{{{ slots.buttons }}}}\n </footer>\n </dialog>\n `;\n #dialog;\n #sections;\n #resolvers = [];\n /** @type {DialogOutcome|null} */\n #answer = null;\n /**\n * @param {{ slots: Record<string, DocumentFragment> }} c\n */\n render({ slots }) {\n const requiresAnswer = this.declared('requires-answer');\n const closeOnSubmit = this.declared('close-on-submit');\n const fragment = this.template()\n .withOverlay({ slots, header: this.declared('header') ?? '', requiresAnswer, closeOnSubmit })\n .render();\n this.#sections = new DialogSections(this, fragment, 'body');\n this.#dialog = this.#sections.dialog;\n const heading = fragment.querySelector('h2');\n if (heading) {\n heading.id ||= Attributes.uid('ful-dialog-title');\n this.#dialog.setAttribute('aria-labelledby', heading.id);\n }\n this.#dialog.addEventListener('close', () => {\n const outcome = this.#outcome();\n this.dispatchEvent(new CustomEvent('close', { detail: outcome }));\n this.#settle(outcome);\n });\n this.#dialog.addEventListener('click', (/** @type any */ e) => {\n const result = e.target.closest('button[data-result]')?.dataset.result;\n if (result !== undefined) {\n this.#dialog.close(result);\n }\n });\n if (!requiresAnswer) {\n this.#sections.onBackdrop(() => this.dismiss('backdrop'));\n }\n fragment.querySelector('[data-ref=close]')?.addEventListener('click', () => this.dismiss('button'));\n if (closeOnSubmit) {\n this.#sections.onSubmitted((response) => {\n this.#answer = { dismissed: false, result: null, response };\n this.#dialog.close('submitted');\n });\n }\n this.#dialog.addEventListener('cancel', (/** @type any */ e) => {\n if (!e.cancelable) {\n this.#dialog.returnValue = '';\n this.#dismiss('escape', false);\n return;\n }\n e.preventDefault();\n if (!requiresAnswer) {\n this.dismiss('escape');\n }\n });\n this.replaceChildren(fragment);\n wireTargets();\n }\n /** @returns {DialogOutcome} */\n #outcome() {\n if (this.#answer) {\n return this.#answer;\n }\n const result = this.#dialog?.returnValue ?? '';\n return result === ''\n ? { dismissed: true, result: null, response: null }\n : { dismissed: false, result, response: null };\n }\n /** @param {DialogOutcome} outcome */\n #settle(outcome) {\n const resolvers = this.#resolvers;\n this.#resolvers = [];\n for (const resolve of resolvers) {\n resolve(outcome);\n }\n }\n /**\n * Resolves every pending `ask()` and `open()` with the outcome so far,\n * a dismissal for a dialog still open, so that no caller waits on a dialog\n * that left the document. The native dialog is not closed and no `close`\n * event is dispatched.\n */\n disconnectedCallback() {\n this.#settle(this.#outcome());\n }\n /**\n * The same as `ask()`.\n * @returns {Promise<DialogOutcome>}\n */\n open() {\n return this.ask();\n }\n /**\n * Shows the dialog as a modal and resolves with how it ends.\n *\n * The call that opens the dialog resets the outcome of the previous\n * opening, hides the error and loading sections, and dispatches\n * `section:requested` on the element (bubbling, with\n * `detail: { section, first, name: null, index: null }`, `section` being\n * the body and `first` true only on the first answered request), so a\n * listener can fill the body. A failed request is painted into the body\n * and does not reject. On a dialog already open nothing is shown or\n * requested, and the call waits for the same ending as the calls before it.\n * @returns {Promise<DialogOutcome>} resolving on close, or on removal from\n * the document with a dismissal\n */\n ask() {\n if (this.#show()) {\n this.#sections.restChrome();\n this.#sections.request();\n }\n return new Promise((resolve) => {\n this.#resolvers.push(resolve);\n });\n }\n /**\n * Empties and hides the body, shows the loading section, opens the dialog\n * if it is closed, and fills the body with what the callback resolves to.\n * A rejection is shown, as the problems' reasons, in the error section,\n * which has `role=\"alert\"`, and the body is hidden. The title stays the\n * `header` attribute.\n *\n * No `section:requested` is dispatched, and no `ask()` waiter is added:\n * listen for the `close` event to learn how the dialog ended. When a newer\n * `update()` starts before the callback settles, this call paints nothing\n * and resolves `null`, the body being the newer call's; it still rejects\n * with the callback's error.\n * @param {() => Node|string|Promise<Node|string>} cb producing the body content\n * @returns {Promise<Element|null>} the body section, in the document, or\n * `null` for a call a newer one overtook\n * @throws {any} what the callback threw or rejected with\n */\n async update(cb) {\n return await this.#sections.update(cb, () => this.#show());\n }\n /**\n * Dispatches `section:requested` for the body again, as `ask()` does,\n * whether the dialog is open or closed. A failed request is painted into\n * the body.\n * @returns {Promise<any[]|undefined>} the listeners' answers, undefined when\n * nobody answered or the request failed; it never rejects\n */\n refresh() {\n return this.#sections.request();\n }\n /**\n * Dismisses the dialog as the user would: dispatches the cancelable\n * `dialog:dismiss` with `detail: { reason }` and, under `guard-dismiss`,\n * asks before dropping unsaved edits, closing the dialog as a dismissal\n * unless either refused. `requires-answer` does not refuse it, as it does\n * not refuse `close()`. Does nothing on a closed dialog.\n * @param {string} reason why it is dismissed, such as `navigation`\n * @returns {Promise<boolean>} whether the dialog is closed, false when a\n * listener or the user kept it open\n */\n dismiss(reason) {\n if (!this.#dialog.open) {\n return Promise.resolve(true);\n }\n return this.#dismiss(reason, true);\n }\n /**\n * @param {string} reason\n * @param {boolean} cancelable false for a close the platform makes anyway\n * @returns {Promise<boolean>}\n */\n #dismiss(reason, cancelable) {\n return this.#sections.dismiss(\n new CustomEvent('dialog:dismiss', { cancelable, detail: { reason } }),\n () => this.#dialog.close(''),\n this.declared('guard-dismiss') ? discardEdits : null,\n );\n }\n /**\n * Closes an open dialog, doing nothing on a closed one. A non-empty result\n * answers as the button carrying that `data-result` would; no result, or\n * an empty one, is a dismissal.\n * @param {string} [result]\n */\n close(result) {\n this.#dialog.close(result ?? '');\n }\n /** @returns {boolean} whether this call is the one that opened the modal */\n #show() {\n if (this.#dialog.open) {\n return false;\n }\n this.#dialog.returnValue = '';\n this.#answer = null;\n this.#dialog.showModal();\n return true;\n }\n /**\n * Appends a new `ful-dialog` to `document.body`, asks it, and removes it\n * once it is answered or its render fails.\n *\n * A string body is set as text and never parsed as markup; a node is\n * appended as it is. Each button is either a `[result, label, className?]`\n * tuple, rendered as a `button` carrying `data-result`, or a node the\n * caller built, placed in the footer in the order given. With no buttons\n * the dialog shows its localized acknowledge button.\n * @param {string} header the title\n * @param {string|Node} body\n * @param {([string, string, string?]|Node)[]} [buttons]\n * @param {{ className?: string }} [options] `className` is set as the class\n * of the `ful-dialog` element\n * @returns {Promise<DialogOutcome>} rejecting with what the render threw\n */\n static async ask(header, body, buttons = [], { className } = {}) {\n const dialog = document.createElement('ful-dialog');\n dialog.setAttribute('header', header);\n if (className) {\n dialog.className = className;\n }\n if (typeof body === 'string') {\n dialog.textContent = body;\n } else if (body) {\n dialog.append(body);\n }\n if (buttons.length > 0) {\n const choices = document.createElement('template');\n choices.setAttribute('slot', 'buttons');\n for (const choice of buttons) {\n if (choice instanceof Node) {\n choices.content.append(choice);\n continue;\n }\n const [result, label, buttonClass] = choice;\n const button = document.createElement('button');\n button.type = 'button';\n button.dataset.result = result;\n if (buttonClass) {\n button.className = buttonClass;\n }\n button.textContent = label;\n choices.content.append(button);\n }\n dialog.append(choices);\n }\n document.body.append(dialog);\n try {\n await Rendering.waitFor(dialog);\n return await /** @type {Dialog} */ (dialog).ask();\n } finally {\n dialog.remove();\n }\n }\n /**\n * Asks a yes/no question through `Dialog.ask`, with a cancel button and a\n * confirm button carrying the `ful-button` class.\n * @param {string} header the title\n * @param {string|Node} body as `Dialog.ask` takes it\n * @param {{ confirm?: string, cancel?: string }} [labels] the button labels,\n * `dialog.confirm` and `dialog.cancel` localized by default\n * @param {{ className?: string }} [options] as `Dialog.ask` takes them\n * @returns {Promise<boolean>} true only for the confirm button; the cancel\n * button, the close button and Escape answer false\n */\n static async confirm(header, body, labels = {}, options = {}) {\n const outcome = await Dialog.ask(\n header,\n body,\n [\n ['cancel', labels.cancel ?? Localization.of().t('dialog.cancel')],\n ['confirm', labels.confirm ?? Localization.of().t('dialog.confirm'), 'ful-button'],\n ],\n options,\n );\n return !outcome.dismissed && outcome.result === 'confirm';\n }\n}\n\n/**\n * Asks, through `Dialog.confirm`, whether to close and drop the unsaved edits,\n * with the localized `dialog.discard.*` texts.\n * @returns {Promise<boolean>} true to drop them\n */\nconst discardEdits = () => {\n const l10n = Localization.of();\n return Dialog.confirm(l10n.t('dialog.discard.header'), l10n.t('dialog.discard.body'), {\n confirm: l10n.t('dialog.discard.confirm'),\n cancel: l10n.t('dialog.discard.cancel'),\n });\n};\n\nexport { Dialog, discardEdits };\n","import { Attributes, ParsedElement } from '../../ftl/index.mjs';\nimport { discardEdits } from './dialog.mjs';\nimport { DialogSections } from './dialog-sections.mjs';\nimport { wireTargets } from './targets.mjs';\n\n/**\n * A side panel on the native `<dialog>`, shown as a modal: a header holding\n * the title and a localized close button, then loading, error and content\n * sections, the default slot being the content.\n *\n * The `header` attribute is the initial title, rendered as an `h2` that names\n * the panel through `aria-labelledby`. The `header` slot is rendered in the\n * header before the title and outside it, so setting the title as text does\n * not remove it. `placement` is copied onto the native dialog: `end` (the\n * default, when absent) or `start`, following the writing direction.\n *\n * The close button, Escape, and a press and release both on the backdrop all\n * go through `dismiss(reason)`, the reason being `button`, `backdrop` or\n * `escape`: before it closes the drawer, the element dispatches a cancelable,\n * non-bubbling `drawer:dismiss` with `detail: { reason }`, and a listener\n * calling `preventDefault()` keeps it open. Under `guard-dismiss`, a dismissal\n * nobody refused, while a `ful-form` of the drawer holds unsaved edits (see\n * `Form.dirty`), first asks the user, through `Dialog.confirm`, whether to\n * close and drop them. A `data-result` button, `close-on-submit`, `close()`\n * and `update()` are answers or the page deciding: they dispatch nothing and\n * ask nothing. The platform lets a page refuse Escape once per user\n * interaction: a second Escape with no click or keystroke in between closes\n * the drawer at once, without the slide, `guard-dismiss` included, and its\n * `drawer:dismiss` is then not cancelable.\n *\n * Any button inside the drawer carrying `data-result` closes it with that\n * result, an empty one being a dismissal. Every close dispatches a\n * non-bubbling `close` event on the element carrying the `DialogOutcome` as\n * `detail`, before the pending `ask()` calls resolve.\n *\n * `close-on-submit` closes the drawer when a `ful-form` that is a direct child\n * of the content section dispatches `submit:success`, carrying its\n * `detail.response`, which may be null. A form deeper in the content, such as\n * the filter form of a `ful-table`, does not close it. The listener sits on\n * the content section, so a form delivered by `update()` is covered as well.\n *\n * An element anywhere in the page carrying `dialog-target` set to the\n * element's id calls `open()` on click.\n */\nclass Drawer extends ParsedElement {\n static attributes = ['header', 'placement', 'close-on-submit:presence', 'guard-dismiss:presence'];\n static slots = true;\n static template = `\n <dialog data-ref=\"dialog\" class=\"ful-drawer\">\n <header>\n {{{{ slots.header }}}}\n <h2 data-ref=\"title\">{{ title }}</h2>\n <button type=\"button\" data-ref=\"close\" data-tpl-aria-label=\"#l10n:t('drawer.close')\"><ful-icon name=\"x-lg\" aria-hidden=\"true\"></ful-icon></button>\n </header>\n <section data-ref=\"loading\" hidden><ful-spinner class=\"centered\" role=\"status\"><span class=\"ful-sr-only\">{{ #l10n:t('spinner.loading') }}</span></ful-spinner></section>\n <section data-ref=\"error\" role=\"alert\" hidden></section>\n <section data-ref=\"content\">{{{{ slots.default }}}}</section>\n </dialog>\n `;\n #dialog;\n #title;\n #sections;\n /** @type {{ dismissed: boolean, result: string|null, response: any }|null} */\n #answer = null;\n #resolvers = [];\n #closing = false;\n #slideOutEnded = (/** @type AnimationEvent */ e) => {\n if (e.target === this.#dialog) {\n this.#closeNow();\n }\n };\n /**\n * @param {{ slots: Record<string, DocumentFragment> }} c\n */\n render({ slots }) {\n const fragment = this.template()\n .withOverlay({ slots, title: this.declared('header') ?? '' })\n .render();\n this.#sections = new DialogSections(this, fragment, 'content');\n this.#dialog = this.#sections.dialog;\n this.#title = fragment.querySelector('[data-ref=title]');\n this.#title.id ||= Attributes.uid('ful-drawer-title');\n this.#dialog.setAttribute('aria-labelledby', this.#title.id);\n const placement = this.declared('placement');\n if (placement) {\n this.#dialog.setAttribute('placement', placement);\n }\n /** @type {HTMLElement} */ (fragment.querySelector('[data-ref=close]')).addEventListener('click', () =>\n this.dismiss('button'),\n );\n this.#sections.onBackdrop(() => this.dismiss('backdrop'));\n this.#dialog.addEventListener('cancel', (e) => {\n if (!e.cancelable) {\n this.#stopSlidingOut();\n this.#dismiss('escape', false);\n return;\n }\n e.preventDefault();\n this.dismiss('escape');\n });\n this.#dialog.addEventListener('click', (/** @type any */ e) => {\n const result = e.target.closest('button[data-result]')?.dataset.result;\n if (result !== undefined) {\n this.close(result);\n }\n });\n this.#dialog.addEventListener('close', () => {\n const outcome = this.#outcome();\n this.dispatchEvent(new CustomEvent('close', { detail: outcome }));\n this.#settle(outcome);\n });\n if (this.declared('close-on-submit')) {\n this.#sections.onSubmitted((response) => {\n this.#answer = { dismissed: false, result: null, response };\n this.close();\n });\n }\n this.replaceChildren(fragment);\n wireTargets();\n }\n /**\n * The title, read and written as the heading's text.\n * @type {string}\n */\n get header() {\n return this.#title.textContent;\n }\n /** @param {string|null|undefined} v written as text, `''` for null or undefined */\n set header(v) {\n this.#title.textContent = v ?? '';\n }\n /**\n * Sets the title, empties and hides the content section, shows the loading\n * section, opens the drawer if it is closed (putting back one that is\n * sliding out), and fills the content with what the callback resolves to.\n * A rejection is shown, as the problems' reasons, in the error section,\n * which has `role=\"alert\"`, and the content is hidden.\n *\n * No `section:requested` is dispatched. When a newer `update()` starts\n * before the callback settles, this call paints nothing and resolves\n * `null`, the content section being the newer call's; it still rejects with\n * the callback's error.\n * @param {string} header the title, set as text\n * @param {() => Node|string|Promise<Node|string>} cb producing the content\n * @returns {Promise<Element|null>} the content section, in the document, or\n * `null` for a call a newer one overtook\n * @throws {any} what the callback threw or rejected with\n */\n async update(header, cb) {\n this.header = header;\n return await this.#sections.update(cb, () => this.#show());\n }\n /**\n * Dispatches `section:requested` for the content again, as `open()` does,\n * whether the drawer is open or closed. A failed request is painted into\n * the content section.\n * @returns {Promise<any[]|undefined>} the listeners' answers, undefined when\n * nobody answered or the request failed; it never rejects\n */\n refresh() {\n return this.#sections.request();\n }\n /** @returns {{ dismissed: boolean, result: string|null, response: any }} */\n #outcome() {\n return this.#answer ?? { dismissed: true, result: null, response: null };\n }\n /** @param {{ dismissed: boolean, result: string|null, response: any }} outcome */\n #settle(outcome) {\n const resolvers = this.#resolvers;\n this.#resolvers = [];\n for (const resolve of resolvers) {\n resolve(outcome);\n }\n }\n /**\n * Resolves every pending `ask()` and `open()` with the outcome so far,\n * a dismissal for a drawer still open, so that no caller waits on a drawer\n * that left the document. The native dialog is not closed and no `close`\n * event is dispatched.\n */\n disconnectedCallback() {\n this.#settle(this.#outcome());\n }\n /**\n * The same as `ask()`.\n * @returns {Promise<{ dismissed: boolean, result: string|null, response: any }>}\n */\n open() {\n return this.ask();\n }\n /**\n * Shows the drawer as a modal and resolves with how it ends.\n *\n * The call that opens the drawer resets the outcome of the previous\n * opening, hides the error and loading sections, and dispatches\n * `section:requested` on the element (bubbling, with\n * `detail: { section, first, name: null, index: null }`, `section` being\n * the content section and `first` true only on the first answered request),\n * so a listener can fill the content. A failed request is painted into the\n * content section and does not reject. On a drawer already open nothing is\n * shown or requested, except that one sliding out stops and stays open, and\n * the call waits for the same ending as the calls before it, which is how\n * a caller learns the outcome of the opening an `update()` made.\n * @returns {Promise<{ dismissed: boolean, result: string|null, response: any }>} resolving on\n * close, or on removal from the document with a dismissal\n */\n ask() {\n if (this.#show()) {\n this.#sections.restChrome();\n this.#sections.request();\n }\n return new Promise((resolve) => {\n this.#resolvers.push(resolve);\n });\n }\n /**\n * Dismisses the drawer as the user would: dispatches the cancelable\n * `drawer:dismiss` with `detail: { reason }` and, under `guard-dismiss`,\n * asks before dropping unsaved edits, sliding the drawer out as a\n * dismissal unless either refused. Does nothing on a drawer that is closed\n * or already sliding out.\n * @param {string} reason why it is dismissed, such as `navigation`\n * @returns {Promise<boolean>} whether the drawer is closed or closing,\n * false when a listener or the user kept it open\n */\n dismiss(reason) {\n if (this.#closing || !this.#dialog.open) {\n return Promise.resolve(true);\n }\n return this.#dismiss(reason, true);\n }\n /**\n * @param {string} reason\n * @param {boolean} cancelable false for a close the platform makes anyway\n * @returns {Promise<boolean>}\n */\n #dismiss(reason, cancelable) {\n return this.#sections.dismiss(\n new CustomEvent('drawer:dismiss', { cancelable, detail: { reason } }),\n () => this.close(),\n this.declared('guard-dismiss') ? discardEdits : null,\n );\n }\n /**\n * Slides the drawer out and closes it when the animation ends, setting the\n * `closing` attribute on the native dialog meanwhile; the `close` event is\n * dispatched then, after this call has returned. Where the user prefers\n * reduced motion, or no animation runs, it closes at once. A non-empty\n * result answers as the button carrying that `data-result` would; no\n * result, or an empty one, is a dismissal. Does nothing on a drawer that is\n * closed or already sliding out.\n * @param {string} [result]\n */\n close(result) {\n if (this.#closing || !this.#dialog.open) {\n return;\n }\n if (result) {\n this.#answer = { dismissed: false, result, response: null };\n }\n if (matchMedia('(prefers-reduced-motion: reduce)').matches) {\n this.#dialog.close();\n return;\n }\n this.#dialog.setAttribute('closing', '');\n if (this.#dialog.getAnimations().length === 0) {\n this.#closeNow();\n return;\n }\n this.#closing = true;\n this.#dialog.addEventListener('animationend', this.#slideOutEnded);\n }\n #closeNow() {\n this.#stopSlidingOut();\n this.#dialog.close();\n }\n #stopSlidingOut() {\n this.#closing = false;\n this.#dialog.removeEventListener('animationend', this.#slideOutEnded);\n this.#dialog.removeAttribute('closing');\n }\n /** @returns {boolean} whether this call is the one that opened the modal */\n #show() {\n this.#stopSlidingOut();\n if (this.#dialog.open) {\n return false;\n }\n this.#answer = null;\n this.#dialog.showModal();\n return true;\n }\n}\n\nexport { Drawer };\n","import { ParsedElement } from '../../ftl/index.mjs';\nimport { Anchors } from './anchors.mjs';\nimport { wireMenuKeys } from './menu-keys.mjs';\n\n/**\n * A menu of commands on the native popover platform. The menu is the popover\n * itself: light dismiss and Escape come from the browser.\n *\n * A menu naming an invoker by id through `for` belongs to that element: the\n * invoker toggles it, and it is anchored to the invoker through\n * `Anchors.wire`, placed in script where the platform has no css anchor\n * positioning. A menu without `for` is shared: one menu serves many\n * invokers, such as the \"more\" button of every row of a list, and a page\n * opens it beside the invoker it is for with `showFor(invoker)`.\n *\n * The items are the buttons and `a[href]` links written as its direct\n * children, kept as they are. Activation is the item's own click, which the\n * menu follows by hiding itself, so a page listens for the click where it\n * already listens. The menu fires no events of its own.\n *\n * The keyboard is the ARIA menu protocol: the focus moves to the\n * first item as the menu opens, the arrows, Home and End walk the items,\n * typing searches their text, Enter and Space activate the focused one, and\n * Escape and a close from inside the menu hand the focus back to the invoker\n * that opened it.\n */\nclass Menu extends ParsedElement {\n /** @type {string[]} */\n static attributes = ['for'];\n /** @type {HTMLElement|null} */\n #invoker = null;\n /** @type {HTMLElement|null} */\n #pressed = null;\n /**\n * Gives the menu the `menu` role and an empty `popover` attribute unless\n * it already has one, and marks the items. With `for`, read here once, it\n * also gives the invoker `aria-haspopup=\"menu\"`, an `aria-expanded` kept\n * in step, and the toggle of the menu.\n * @returns {void}\n * @throws {Error} when `for` is given and names no element in the document at the render\n */\n render() {\n const named = this.declared('for');\n const invoker = named ? document.getElementById(named) : null;\n if (named && !invoker) {\n throw new Error(\n `ful-menu names no invoker: for=\"${named}\" must name an element already in the page when the menu upgrades`,\n );\n }\n this.setAttribute('role', 'menu');\n if (!this.hasAttribute('popover')) {\n this.setAttribute('popover', '');\n }\n if (invoker) {\n this.#invoker = invoker;\n invoker.setAttribute('aria-haspopup', 'menu');\n Anchors.wire(invoker, this, { prefix: 'ful-menu', invoke: true, expanded: true });\n } else {\n this.#wireShared();\n }\n wireMenuKeys(() => this.#invoker, this, { items: () => this.items });\n this.#mark();\n this.addEventListener('click', (evt) => {\n const target = /** @type HTMLElement */ (evt.target);\n if (this.items.some((item) => item === target || item.contains(target))) {\n this.hidePopover();\n }\n });\n }\n /**\n * Opens a shared menu, one without `for`, beside `invoker`, or moves it\n * there when it is open for another one. The menu goes below the invoker,\n * or above it where there is no room below, and is placed once, as\n * `Anchors.show` places it. The invoker gets `aria-haspopup=\"menu\"` and an\n * `aria-expanded` that reads true until the menu closes, and the focus\n * goes back to it on Escape. A call for the invoker whose press has just\n * closed the menu does nothing, so a second click on the same button\n * closes the menu rather than opening it again.\n * @param {HTMLElement} invoker the element the menu opens for\n * @returns {void}\n * @throws {Error} when the menu names its invoker through `for`\n */\n showFor(invoker) {\n if (this.declared('for')) {\n throw new Error('ful-menu: showFor serves a menu without for; a menu with for is opened by its invoker');\n }\n const pressed = this.#pressed;\n this.#pressed = null;\n if (pressed === invoker) {\n return;\n }\n if (this.#invoker && this.#invoker !== invoker) {\n this.#invoker.setAttribute('aria-expanded', 'false');\n }\n this.#invoker = invoker;\n invoker.setAttribute('aria-haspopup', 'menu');\n invoker.setAttribute('aria-expanded', 'true');\n //the previous placement wrote margin: 0 inline, hiding the stylesheet's gap\n this.style.margin = '';\n const gap = Number.parseFloat(getComputedStyle(this).marginBlockStart) || 0;\n const moving = this.matches(':popover-open');\n Anchors.show(this, invoker, { flip: true, gap });\n if (moving) {\n this.items[0]?.focus();\n }\n }\n /**\n * The commands, in the order the arrows walk them: the menu's direct\n * `button` and `a[href]` children, minus those carrying a `disabled` or\n * `hidden` attribute, which keep their role and leave the walk. Reading it\n * also marks any child added since the render, giving it the `menuitem`\n * role, unless it has a role already, and a `tabIndex` of -1.\n * @type {HTMLElement[]}\n */\n get items() {\n return this.#mark().filter((item) => !item.hasAttribute('disabled') && !item.hasAttribute('hidden'));\n }\n #wireShared() {\n document.addEventListener(\n 'pointerdown',\n (evt) => {\n const target = /** @type Node */ (evt.target);\n this.#pressed = this.matches(':popover-open') && this.#invoker?.contains(target) ? this.#invoker : null;\n },\n true,\n );\n this.addEventListener('toggle', (/** @type any */ evt) => {\n if (evt.newState === 'closed') {\n this.#invoker?.setAttribute('aria-expanded', 'false');\n }\n });\n }\n /** @returns {HTMLElement[]} every item, disabled and hidden ones included, once marked */\n #mark() {\n const all = /** @type HTMLElement[] */ ([...this.querySelectorAll(':scope > button, :scope > a[href]')]);\n for (const item of all) {\n if (!item.hasAttribute('role')) {\n item.setAttribute('role', 'menuitem');\n }\n item.tabIndex = -1;\n }\n return all;\n }\n}\n\nexport { Menu };\n","import { Localization, ParsedElement } from '../../ftl/index.mjs';\n\nconst SEVERITIES = ['info', 'success', 'warning', 'error'];\n\nconst REGIONS = new Set();\nlet listenerWired = false;\n\n/**\n * @typedef {object} ToastOptions\n * @property {'info'|'success'|'warning'|'error'} [severity] the theme class and\n * the announcement, `info` when absent or unknown\n * @property {number} [timeout] the milliseconds before the toast retires, the\n * region's own timeout when absent\n * @property {{ label: any, onClick?: () => void }} [action] a button labelled\n * with `label` as text, beside the message\n */\n\n/**\n * A region of transient messages, with `role=\"region\"` and a localized\n * `aria-label`. Each `show()` appends a `ful-toast` that retires on its own\n * timer, so concurrent toasts stack.\n *\n * The region is a manual popover, whatever `popover` the page declared, and\n * each `show()` shows it again, so it is on top of the top layer when a toast\n * arrives: above a modal dialog or drawer opened before it. While a modal is\n * open the page outside it is inert, the region included: its toasts show and\n * retire on their timers, and their buttons answer once the modal closes.\n *\n * `timeout` is the region's default timer in milliseconds, 5000 when absent\n * or zero.\n *\n * A `show-toast` event dispatched on the document, or bubbling to it, shows its\n * `detail` in every connected region that has rendered, `detail.message` being\n * the message and the other fields the `ToastOptions`. The document listener is\n * added once, so a second region shows each toast once, and an event with no\n * detail is ignored.\n */\nclass Toasts extends ParsedElement {\n static attributes = ['timeout:number'];\n #timeout;\n /** Upgrades the region, and makes a re-attached one answer `show-toast` again. */\n connectedCallback() {\n super.connectedCallback();\n if (this.rendered) {\n REGIONS.add(this);\n }\n }\n /** Stops the region answering `show-toast` while it is out of the document. */\n disconnectedCallback() {\n REGIONS.delete(this);\n }\n render() {\n this.#timeout = this.declared('timeout') || 5000;\n this.setAttribute('role', 'region');\n this.setAttribute('tabindex', '-1');\n this.setAttribute('aria-label', Localization.of().t('toast.region'));\n this.setAttribute('popover', 'manual');\n if (!listenerWired) {\n listenerWired = true;\n document.addEventListener('show-toast', (/** @type any */ e) => {\n if (!e.detail) {\n return;\n }\n for (const region of REGIONS) {\n region.show(e.detail.message, e.detail);\n }\n });\n }\n REGIONS.add(this);\n }\n /**\n * Appends a `ful-toast` holding the message as text, a `Failure` showing\n * its problems' reasons one per line and anything else its string form\n * (`''` for null or undefined). The toast carries the severity as a class\n * and has `role=\"alert\"` for `error` and `role=\"status\"` otherwise.\n *\n * The toast retires when its timer runs out, when its localized dismiss\n * button is clicked, or when its action button is clicked, after\n * `action.onClick` runs. The timer pauses while the pointer is over the\n * toast or the focus is inside it, and resumes with the time that was left\n * once both have gone. A retiring toast holding the focus moves it to the\n * region, which has `tabindex=\"-1\"` for this. The toast is removed once its\n * `ful-toast-out` animation ends, or at once where the user prefers reduced\n * motion or no animation runs.\n *\n * A connected region is shown again as a popover, which puts it above\n * whatever opened in the top layer since; the focus stays where it was.\n * @param {any} message\n * @param {ToastOptions} [options]\n * @returns {HTMLElement} the toast, already in the region\n */\n show(message, options = {}) {\n const severity = /** @type {string} */ (\n SEVERITIES.includes(/** @type {string} */ (options.severity)) ? options.severity : 'info'\n );\n const item = document.createElement('ful-toast');\n item.classList.add(severity);\n item.setAttribute('role', severity === 'error' ? 'alert' : 'status');\n const body = document.createElement('div');\n body.textContent = Localization.of().failure(message);\n const dismiss = document.createElement('button');\n dismiss.type = 'button';\n dismiss.setAttribute('aria-label', Localization.of().t('toast.dismiss'));\n const icon = document.createElement('ful-icon');\n icon.setAttribute('name', 'x-lg');\n icon.setAttribute('aria-hidden', 'true');\n dismiss.append(icon);\n item.append(body);\n let remaining = options.timeout ?? this.#timeout;\n let startedAt = performance.now();\n let timer = 0;\n const retire = () => {\n clearTimeout(timer);\n if (item.contains(document.activeElement)) {\n /** @type HTMLElement */ (this).focus();\n }\n if (matchMedia('(prefers-reduced-motion: reduce)').matches) {\n item.remove();\n return;\n }\n item.classList.add('ful-toast-out');\n if (item.getAnimations().length === 0) {\n item.remove();\n }\n };\n if (options.action?.label) {\n const action = document.createElement('button');\n action.type = 'button';\n action.className = 'ful-toast-action';\n action.textContent = String(options.action.label);\n action.addEventListener('click', () => {\n /** @type {NonNullable<ToastOptions['action']>} */ (options.action).onClick?.();\n retire();\n });\n item.append(action);\n }\n item.append(dismiss);\n item.addEventListener('animationend', () => {\n if (item.classList.contains('ful-toast-out')) {\n item.remove();\n }\n });\n let holds = 0;\n const hold = () => {\n if (holds === 0) {\n clearTimeout(timer);\n remaining = Math.max(0, remaining - (performance.now() - startedAt));\n }\n ++holds;\n };\n const release = () => {\n if (holds === 0) {\n return;\n }\n if (--holds === 0) {\n startedAt = performance.now();\n timer = setTimeout(retire, remaining);\n }\n };\n item.addEventListener('mouseenter', hold);\n item.addEventListener('mouseleave', release);\n item.addEventListener('focusin', hold);\n item.addEventListener('focusout', release);\n dismiss.addEventListener('click', retire);\n this.append(item);\n this.#raise();\n timer = setTimeout(retire, remaining);\n return item;\n }\n #raise() {\n if (!this.isConnected) {\n return;\n }\n if (this.matches(':popover-open')) {\n this.hidePopover();\n }\n this.showPopover();\n }\n}\n\nexport { Toasts };\n","import { Attributes, ParsedElement } from '../../ftl/index.mjs';\nimport { SectionRequests } from '../events/sections.mjs';\n\n/**\n * A tab panel: one visible panel at a time, announced through the tab pattern\n * (a tablist of tab buttons, each panel a tabpanel labelled by its tab). The\n * tabs are declared as `<tab>` elements in the `tabs` slot, the panels as the\n * slotless children, paired in order. Each `<tab>` becomes a `button` with the\n * `tab` role carrying the tab's content, inside a `ful-tablist` with the\n * `tablist` role. A panel that already has an id keeps it and its tab points at\n * it; a panel without one gets a generated id. Every panel carries\n * `tabindex=\"0\"`, so the visible one follows its tab in the tab order and the\n * hidden ones stay out of it.\n *\n * The tabs use a roving tabindex and automatic activation: a click activates\n * its tab, and on the tablist ArrowRight and ArrowLeft move to the next and\n * previous tab, wrapping around, while Home and End jump to the first and the\n * last, moving the focus with the activation.\n *\n * Entering a panel fires `section:requested` and `section:requested:#<index>`\n * on the host, bubbling, with detail `{ name: null, section, index, first }`,\n * and awaits the answers registered through `AsyncEvents.asyncOn`, so a panel\n * can deliver itself asynchronously: see `SectionRequests`.\n */\nclass Tabs extends ParsedElement {\n static slots = true;\n static observed = ['active:number'];\n static template = `\n <ful-tablist role=\"tablist\">{{{{ slots.tabs }}}}</ful-tablist>\n {{{{ slots.default }}}}\n `;\n #tablist;\n #tabs = [];\n #panels = [];\n #requests = new SectionRequests();\n #active = 0;\n /**\n * Pairs the declared tabs with the panels in order. When the counts\n * differ, the unpaired tabs and panels are left in the dom as they are and\n * a warning is logged.\n * @param {{ slots: Record<string, DocumentFragment> }} conf\n * @returns {void}\n */\n render({ slots }) {\n const fragment = this.template().withOverlay({ slots }).render();\n this.#tablist = fragment.querySelector('ful-tablist');\n const declared = [...this.#tablist.children];\n this.#panels = [...fragment.children].filter((el) => el !== this.#tablist);\n if (declared.length !== this.#panels.length) {\n console.warn(\n `ful-tabs: ${declared.length} tabs declared for ${this.#panels.length} panels, the surplus is left alone`,\n );\n }\n const count = Math.min(declared.length, this.#panels.length);\n this.#tabs = [];\n for (let i = 0; i !== count; ++i) {\n const panel = this.#panels[i];\n const tab = document.createElement('button');\n tab.type = 'button';\n tab.role = 'tab';\n tab.id = Attributes.uid('ful-tab');\n if (!panel.id) {\n panel.id = Attributes.uid('ful-tabpanel');\n }\n tab.setAttribute('aria-controls', panel.id);\n panel.role = 'tabpanel';\n panel.setAttribute('aria-labelledby', tab.id);\n panel.tabIndex = 0;\n tab.append(...declared[i].childNodes);\n tab.addEventListener('click', () => {\n this.active = i;\n });\n declared[i].replaceWith(tab);\n this.#tabs.push(tab);\n }\n this.#tablist.addEventListener('keydown', (e) => {\n const current = this.#active;\n /** @type {number|null} */\n let target = null;\n if (e.key === 'ArrowRight') {\n target = (current + 1) % this.#tabs.length;\n } else if (e.key === 'ArrowLeft') {\n target = (current - 1 + this.#tabs.length) % this.#tabs.length;\n } else if (e.key === 'Home') {\n target = 0;\n } else if (e.key === 'End') {\n target = this.#tabs.length - 1;\n }\n if (target === null || target === current) {\n return;\n }\n e.preventDefault();\n this.active = target;\n this.#tabs[target].focus();\n });\n this.replaceChildren(fragment);\n }\n /**\n * The index of the visible panel, reflected to the `active` attribute.\n * Writing it clamps the value to the paired tabs, a value that is not a\n * number counting as 0, and selects that tab and shows its panel. When the\n * index changes on a rendered element it dispatches `tabs:change` on the\n * host (not bubbling) with detail `{ active, previous }`, then fires the\n * section requests for the entered panel. The first write, which applies\n * the attribute after the render, fires the requests without the event.\n * A failed delivery paints the panel's error and rejects nowhere.\n * @type {number}\n */\n get active() {\n return this.#active;\n }\n /**\n * Fires the section requests again for a panel, whether it is visible or\n * not, with `first` false once an earlier request was answered.\n * @param {number | Element} ref the panel's index, or the panel itself\n * @returns {Promise<any[] | undefined> | undefined} a promise resolving to\n * the answers, or to undefined when nobody listened or the delivery\n * failed (its error painted in the panel); undefined, with a warning, when\n * `ref` names no panel\n */\n refresh(ref) {\n const index = ref instanceof Element ? this.#panels.indexOf(ref) : Number.isInteger(ref) ? ref : NaN;\n const panel = this.#panels[index];\n if (!panel) {\n console.warn(`ful-tabs: no panel answers to \"${ref}\"`);\n return undefined;\n }\n return this.#requests.request(this, panel, null, index).catch(() => undefined);\n }\n set active(v) {\n const index = Math.min(Math.max(0, Number(v) || 0), Math.max(0, this.#tabs.length - 1));\n const previous = this.#active;\n for (const [i, tab] of this.#tabs.entries()) {\n tab.setAttribute('aria-selected', i === index ? 'true' : 'false');\n tab.tabIndex = i === index ? 0 : -1;\n this.#panels[i].hidden = i !== index;\n }\n this.#active = index;\n this.reflectTo('active', index);\n if (this.rendered && index !== previous) {\n this.dispatchEvent(new CustomEvent('tabs:change', { detail: { active: index, previous } }));\n }\n if (this.#panels.length > 0 && (index !== previous || !this.rendered)) {\n this.#requests.request(this, this.#panels[index], null, index).catch(() => undefined);\n }\n }\n}\n\nexport { Tabs };\n","import { Attributes, ParsedElement } from '../../ftl/index.mjs';\n\n/**\n * An accordion over native `details`/`summary` disclosures: the browser\n * provides the semantics, the keyboard and the toggling, and the element adds\n * the group's styling. The `details` written as its children are rendered,\n * unchanged, inside a `ful-accordion-group`.\n */\nclass Accordion extends ParsedElement {\n static slots = true;\n /** @type {string[]} */\n static observed = ['exclusive:presence'];\n static template = `\n <ful-accordion-group>{{{{ slots.default }}}}</ful-accordion-group>\n `;\n #group;\n #exclusive = false;\n /**\n * @param {{ slots: Record<string, DocumentFragment> | undefined }} c\n * @returns {void}\n */\n render({ slots }) {\n const fragment = this.template().withOverlay({ slots }).render();\n this.#group = fragment.querySelector('ful-accordion-group');\n this.replaceChildren(fragment);\n }\n /**\n * Whether opening one panel closes the others, reflected to the\n * `exclusive` attribute; only `true` turns it on. Setting it gives the\n * group's direct `details` children one shared, newly generated `name`,\n * the platform's exclusive grouping, or removes their `name` when off.\n * A `details` added to the group afterwards is not named until the next\n * write.\n * @type {boolean}\n */\n get exclusive() {\n return this.#exclusive;\n }\n set exclusive(v) {\n this.#exclusive = v === true;\n this.reflectTo('exclusive', this.#exclusive);\n const name = this.#exclusive ? Attributes.uid('ful-accordion') : null;\n for (const details of this.#group.querySelectorAll(':scope > details')) {\n if (name === null) {\n details.removeAttribute('name');\n } else {\n details.setAttribute('name', name);\n }\n }\n }\n}\n\nexport { Accordion };\n","import { ParsedElement } from '../../ftl/index.mjs';\nimport { SectionRequests } from '../events/sections.mjs';\n\n/**\n * A wizard: a progress of steps over one-of-N sections. The steps are declared\n * as `<step>` elements in the `steps` slot, the sections as the slotless\n * children, paired in order; each section may carry a `data-step` name, which\n * is what `move()` and `refresh()` answer to. The steps become the items of an\n * `ol` inside `ful-steps`, labelled by the localized `wizard.progress`.\n *\n * The current step is the `aria-current=\"step\"` claim, carried by the step and\n * its section together, and the stylesheet hides every `section` child that\n * does not carry it. A section that carries the claim in the markup when the\n * wizard renders stays current; otherwise the first section is. Every paired\n * section gets `tabindex=\"-1\"`, so a move can focus it.\n *\n * Entering a section, the first one at the render included, fires\n * `section:requested`, `section:requested:#<index>` and, when the section has a\n * `data-step`, `section:requested:<name>` on the host, bubbling, with detail\n * `{ name, section, index, first }`, and awaits the answers registered through\n * `AsyncEvents.asyncOn`: see `SectionRequests`. A failure of the initial entry\n * paints the section's error and rejects nowhere.\n */\nclass Wizard extends ParsedElement {\n static slots = true;\n static observed = ['progress'];\n static template = `\n <ful-steps><ol data-tpl-aria-label=\"#l10n:t('wizard.progress')\">{{{{ slots.steps }}}}</ol></ful-steps>\n {{{{ slots.default }}}}\n `;\n #steps = [];\n #sections = [];\n #requests = new SectionRequests();\n #index = 0;\n #progress;\n /**\n * Pairs the declared steps with the sections in order. When the counts\n * differ, the unpaired steps and sections are left in the dom as they are\n * and a warning is logged.\n * @param {{ slots: Record<string, DocumentFragment> }} conf\n * @returns {void}\n */\n render({ slots }) {\n const fragment = this.template().withOverlay({ slots }).render();\n const list = /** @type {HTMLElement} */ (fragment.querySelector('ful-steps ol'));\n const declared = [...list.children];\n this.#sections = [...fragment.children].filter((el) => el.localName !== 'ful-steps');\n if (declared.length !== this.#sections.length) {\n console.warn(\n `ful-wizard: ${declared.length} steps declared for ${this.#sections.length} sections, the surplus is left alone`,\n );\n }\n const count = Math.min(declared.length, this.#sections.length);\n this.#steps = [];\n for (let i = 0; i !== count; ++i) {\n const li = document.createElement('li');\n li.append(...declared[i].childNodes);\n declared[i].replaceWith(li);\n this.#steps.push(li);\n this.#sections[i].tabIndex = -1;\n }\n this.replaceChildren(fragment);\n if (count > 0) {\n const claimed = this.#sections.findIndex((s) => s.getAttribute('aria-current') === 'step');\n this.#apply(claimed === -1 ? 0 : Math.min(claimed, count - 1));\n this.#enter(this.#index).catch(() => undefined);\n }\n }\n /**\n * The zero-based position of the current step.\n * @type {number}\n */\n get index() {\n return this.#index;\n }\n /**\n * The `data-step` of the current section, or null when it has none or no\n * section is paired.\n * @type {string | null}\n */\n get step() {\n return this.#sections[this.#index]?.getAttribute('data-step') ?? null;\n }\n /**\n * The shape of the progress chrome, reflected to the `progress` attribute:\n * unset shows the current step alone, `timeline` every step as done,\n * current or future, `dots` one dot per step, `none` no progress at all.\n * The value only drives the stylesheet; the moves are the same in every\n * shape.\n * @type {string | null}\n */\n get progress() {\n return this.#progress;\n }\n set progress(v) {\n this.#progress = v;\n this.reflectTo('progress', v);\n }\n /**\n * Moves to the following step; at the last step nothing happens.\n * @returns {Promise<any[] | undefined> | undefined} what `move()` answers\n * @throws what the entered section's delivery rejected with, as the rejection\n * of the returned promise\n */\n next() {\n return this.#move(this.#index + 1);\n }\n /**\n * Moves to the preceding step; at the first step nothing happens.\n * @returns {Promise<any[] | undefined> | undefined} what `move()` answers\n * @throws what the entered section's delivery rejected with, as the rejection\n * of the returned promise\n */\n prev() {\n return this.#move(this.#index - 1);\n }\n /**\n * Moves to the section carrying `data-step=\"<ref>\"`. A move makes that step\n * and section current, moves the focus to the section, dispatches\n * `wizard:change` on the host (not bubbling) with detail `{ index, step }`,\n * then fires the section requests for it.\n * @param {string} ref the section's `data-step`\n * @returns {Promise<any[] | undefined> | undefined} a promise resolving to\n * the answers once they are delivered, or to undefined when nobody\n * listened; undefined when the section is already current, and undefined\n * with a warning when no section carries `ref`\n * @throws what the entered section's delivery rejected with, as the rejection\n * of the returned promise, after its error is painted in the section\n */\n move(ref) {\n const index = this.#sections.findIndex((s) => s.getAttribute('data-step') === ref);\n if (index === -1) {\n console.warn(`ful-wizard: no section carries data-step=\"${ref}\"`);\n return undefined;\n }\n return this.#move(index);\n }\n /**\n * Fires the section requests again for a section, whether it is current or\n * not, with `first` false once an earlier request was answered.\n * @param {string | Element} ref the section's `data-step`, or the section\n * itself\n * @returns {Promise<any[] | undefined> | undefined} a promise resolving to\n * the answers, or to undefined when nobody listened or the delivery failed\n * (its error painted in the section); undefined, with a warning, when `ref`\n * names no section\n */\n refresh(ref) {\n const section =\n ref instanceof Element\n ? ref\n : typeof ref === 'string'\n ? this.#sections.find((s) => s.getAttribute('data-step') === ref)\n : undefined;\n const index = this.#sections.indexOf(section);\n if (index === -1) {\n console.warn(`ful-wizard: no section answers to \"${ref}\"`);\n return undefined;\n }\n return this.#enter(index).catch(() => undefined);\n }\n #enter(index) {\n return this.#requests.request(\n this,\n this.#sections[index],\n this.#sections[index].getAttribute('data-step'),\n index,\n );\n }\n #move(index) {\n const clamped = Math.min(Math.max(0, index), Math.max(0, this.#steps.length - 1));\n if (clamped === this.#index) {\n return undefined;\n }\n this.#apply(clamped);\n this.#sections[this.#index].focus();\n if (this.rendered) {\n this.dispatchEvent(new CustomEvent('wizard:change', { detail: { index: this.#index, step: this.step } }));\n }\n return this.#enter(clamped);\n }\n #apply(index) {\n for (const [i, step] of this.#steps.entries()) {\n if (i === index) {\n step.setAttribute('aria-current', 'step');\n this.#sections[i].setAttribute('aria-current', 'step');\n } else {\n step.removeAttribute('aria-current');\n this.#sections[i].removeAttribute('aria-current');\n }\n }\n this.#index = index;\n }\n}\n\nexport { Wizard };\n","import { HttpClient } from '../httpc/index.mjs';\nimport { Localization } from '../ftl/index.mjs';\nimport { Checkbox } from './forms/checkbox.mjs';\nimport { LocalDate, Instant, InputLocalDate, InputLocalTime, InputInstant } from './forms/temporals.mjs';\nimport { BooleanFilter, InFilter, InstantFilter, LocalDateFilter, NumberFilter, TextFilter } from './forms/filters.mjs';\nimport { FormLoader, Form } from './forms/form.mjs';\nimport { Input } from './forms/input.mjs';\nimport { InputFile } from './forms/files.mjs';\nimport { RadioGroup } from './forms/radio.mjs';\nimport { SelectLoader, Dropdown, Select } from './forms/select.mjs';\nimport { Tooltip } from './disclosures/tooltip.mjs';\nimport { Dialog } from './disclosures/dialog.mjs';\nimport { Drawer } from './disclosures/drawer.mjs';\nimport { Menu } from './disclosures/menu.mjs';\nimport { Toasts } from './disclosures/toast.mjs';\nimport { Tabs } from './navigation/tabs.mjs';\nimport { Accordion } from './disclosures/accordion.mjs';\nimport { Wizard } from './navigation/wizard.mjs';\nimport { TableLoader, Table, Pagination, SortButton } from './navigation/table.mjs';\nimport en from './l10n/en.mjs';\nimport it from './l10n/it.mjs';\nimport es from './l10n/es.mjs';\nimport fr from './l10n/fr.mjs';\n\nconst BUILTIN = { en, it, es, fr };\n\n/**\n * Registers everything ful provides on a registry: the elements, the loader\n * components, an http client, and the translations for the configured\n * language. A page calls `registry.plugin(new Plugin({…})).configure()` once;\n * `registry.plugin` calls this plugin's `configure`.\n */\nclass Plugin {\n #language;\n #translations;\n #httpClient;\n\n /**\n * @param {{ language?: string, translations?: Record<string, any>, httpClient?: HttpClient }} [options]\n * `language` is fixed for the page: a full BCP-47 tag or a primary subtag,\n * defaulting to `navigator.language`, then to 'en'. Its primary subtag,\n * lowercased, picks the built-in translations (en, it, es, fr); the messages\n * are the english ones, overridden by that language's, overridden by\n * `translations`, so a language without built-in translations reads in\n * english. `translations` is a flat map of keys to messages: reword built-in\n * keys ('pagination.showing', …) or add your own ('checkout.total', …).\n * `httpClient` is the client every ful component fetches through, registered\n * as the `http-client` component; without one, `configure` builds a client\n * that sends the csrf token and navigates to '/' on a 401 response.\n */\n constructor(options = {}) {\n this.#language = options.language ?? navigator?.language ?? 'en';\n this.#translations = options.translations ?? {};\n this.#httpClient = options.httpClient ?? null;\n }\n\n /**\n * Defines on `registry` the `l10n` module, the `http-client` component,\n * every `ful-*` element, the `loaders:select`, `loaders:form` and\n * `loaders:table` components, and an overlay publishing `l10n` (the merged\n * messages) and `locale` (the `language` as given) to every template.\n * @param {{ defineModule(name: string, module: any): any, defineComponent(name: string, component: any): any, defineElement(tag: string, klass: CustomElementConstructor): any, defineOverlay(...data: any[]): any }} registry\n * the ftl `Registry`, each of those methods answering the registry itself\n * @returns {void}\n */\n configure(registry) {\n const httpClient =\n this.#httpClient ?? HttpClient.builder().withCsrfToken().withRedirectOnUnauthorized('/').build();\n const language = this.#language.split('-')[0].toLowerCase();\n const l10n = { ...BUILTIN.en, ...BUILTIN[language], ...this.#translations };\n registry\n .defineModule('l10n', Localization)\n .defineComponent('http-client', httpClient)\n .defineElement('ful-tooltip', Tooltip)\n .defineElement('ful-dialog', Dialog)\n .defineElement('ful-drawer', Drawer)\n .defineElement('ful-menu', Menu)\n .defineElement('ful-toasts', Toasts)\n .defineElement('ful-tabs', Tabs)\n .defineElement('ful-accordion', Accordion)\n .defineElement('ful-wizard', Wizard)\n .defineElement('ful-form', Form)\n .defineElement('ful-checkbox', Checkbox)\n .defineElement('ful-input', Input)\n .defineElement('ful-input-file', InputFile)\n .defineElement('ful-local-date', LocalDate)\n .defineElement('ful-instant', Instant)\n .defineElement('ful-input-local-date', InputLocalDate)\n .defineElement('ful-input-local-time', InputLocalTime)\n .defineElement('ful-input-instant', InputInstant)\n .defineElement('ful-radio-group', RadioGroup)\n .defineElement('ful-table', Table)\n .defineElement('ful-pagination', Pagination)\n .defineElement('ful-sorter', SortButton)\n .defineElement('ful-filter-instant', InstantFilter)\n .defineElement('ful-filter-local-date', LocalDateFilter)\n .defineElement('ful-filter-number', NumberFilter)\n .defineElement('ful-filter-boolean', BooleanFilter)\n .defineElement('ful-filter-text', TextFilter)\n .defineElement('ful-filter-in', InFilter)\n .defineElement('ful-select', Select)\n .defineElement('ful-dropdown', Dropdown)\n .defineComponent('loaders:select', SelectLoader)\n .defineComponent('loaders:form', FormLoader)\n .defineComponent('loaders:table', TableLoader)\n .defineOverlay({\n l10n,\n locale: this.#language,\n });\n }\n}\n\nexport { Plugin };\n","export default {\n 'pagination.showing': 'Page {current} of {total}',\n 'pagination.navigation': 'Page navigation',\n 'pagination.previous': 'Previous',\n 'pagination.next': 'Next',\n 'pagination.reload': 'Reload',\n 'table.initial': 'Start searching to see results.',\n 'table.error': 'Error while loading data:',\n 'table.no-data': 'No elements found.',\n 'dropdown.empty': 'No results',\n 'select.remove': 'Remove',\n 'files.dropzone-label': 'Click or drop your files here',\n 'files.remove': 'Remove',\n 'files.unacceptable-file-type': 'Only files of type {types} are supported',\n 'files.max-file-size-exceeded': 'Maximum supported file size is {size}',\n 'files.max-total-size-exceeded': 'Maximum supported total file size is {size}',\n 'files.max-files-exceeded': { one: 'Maximum of {count} file exceeded', other: 'Maximum of {count} files exceeded' },\n 'filters.op.EQ': 'Equals',\n 'filters.op.NEQ': 'Not equal',\n 'filters.op.LT': 'Less than',\n 'filters.op.GT': 'Greater than',\n 'filters.op.LTE': 'At most',\n 'filters.op.GTE': 'At least',\n 'filters.op.BETWEEN': 'Between',\n 'filters.op.CONTAINS': 'Contains',\n 'filters.op.STARTS_WITH': 'Starts with',\n 'filters.op.ENDS_WITH': 'Ends with',\n 'filters.sensitivity.IGNORE_CASE': 'Ignore case',\n 'filters.sensitivity.CASE_SENSITIVE': 'Case sensitive',\n 'filters.boolean.any': 'Any',\n 'filters.boolean.true': 'Yes',\n 'filters.boolean.false': 'No',\n 'info.tooltip': 'More information',\n 'failure.no-reason': 'Something went wrong',\n 'dialog.acknowledge': 'Got it',\n 'dialog.close': 'Close',\n 'dialog.confirm': 'Confirm',\n 'dialog.cancel': 'Cancel',\n 'dialog.discard.header': 'Unsaved changes',\n 'dialog.discard.body': 'There are unsaved changes: close anyway?',\n 'dialog.discard.confirm': 'Close without saving',\n 'dialog.discard.cancel': 'Keep editing',\n 'drawer.close': 'Close',\n 'spinner.loading': 'Loading…',\n 'toast.region': 'Notifications',\n 'toast.dismiss': 'Dismiss',\n 'wizard.progress': 'Progress',\n};\n","export default {\n 'pagination.showing': 'Pagina {current} di {total}',\n 'pagination.navigation': 'Navigazione pagine',\n 'pagination.previous': 'Precedente',\n 'pagination.next': 'Successivo',\n 'pagination.reload': 'Ricarica',\n 'table.initial': 'Avvia la ricerca per visualizzare i risultati.',\n 'table.error': 'Errore nel caricamento dei dati:',\n 'table.no-data': 'Nessun elemento trovato.',\n 'dropdown.empty': 'Nessun risultato',\n 'select.remove': 'Rimuovi',\n 'files.dropzone-label': 'Clicca o trascina i file qui',\n 'files.remove': 'Rimuovi',\n 'files.unacceptable-file-type': 'Solo i file di tipo {types} sono supportati',\n 'files.max-file-size-exceeded': 'La dimensione massima di un file è di {size}',\n 'files.max-total-size-exceeded': 'La dimensione massima complessiva dei file è di {size}',\n 'files.max-files-exceeded': { other: 'Superato il numero massimo di {count} file' },\n 'filters.op.EQ': 'Uguale',\n 'filters.op.NEQ': 'Diverso',\n 'filters.op.LT': 'Minore',\n 'filters.op.GT': 'Maggiore',\n 'filters.op.LTE': 'Al massimo',\n 'filters.op.GTE': 'Almeno',\n 'filters.op.BETWEEN': 'Tra',\n 'filters.op.CONTAINS': 'Contiene',\n 'filters.op.STARTS_WITH': 'Inizia con',\n 'filters.op.ENDS_WITH': 'Termina con',\n 'filters.sensitivity.IGNORE_CASE': 'Ignora maiuscole',\n 'filters.sensitivity.CASE_SENSITIVE': 'Distingui maiuscole',\n 'filters.boolean.any': 'Qualsiasi',\n 'filters.boolean.true': 'Sì',\n 'filters.boolean.false': 'No',\n 'info.tooltip': 'Maggiori informazioni',\n 'failure.no-reason': 'Si è verificato un errore',\n 'dialog.acknowledge': 'Ho capito',\n 'dialog.close': 'Chiudi',\n 'dialog.confirm': 'Conferma',\n 'dialog.cancel': 'Annulla',\n 'dialog.discard.header': 'Modifiche non salvate',\n 'dialog.discard.body': 'Ci sono modifiche non salvate: chiudere comunque?',\n 'dialog.discard.confirm': 'Chiudi senza salvare',\n 'dialog.discard.cancel': 'Continua a modificare',\n 'drawer.close': 'Chiudi',\n 'spinner.loading': 'Caricamento…',\n 'toast.region': 'Notifiche',\n 'toast.dismiss': 'Chiudi',\n 'wizard.progress': 'Avanzamento',\n};\n","export default {\n 'pagination.showing': 'Página {current} de {total}',\n 'pagination.navigation': 'Navegación de páginas',\n 'pagination.previous': 'Anterior',\n 'pagination.next': 'Siguiente',\n 'pagination.reload': 'Recargar',\n 'table.initial': 'Inicia la búsqueda para ver los resultados.',\n 'table.error': 'Error al cargar los datos:',\n 'table.no-data': 'No se encontraron elementos.',\n 'dropdown.empty': 'Sin resultados',\n 'select.remove': 'Eliminar',\n 'files.dropzone-label': 'Haz clic o arrastra tus archivos aquí',\n 'files.remove': 'Eliminar',\n 'files.unacceptable-file-type': 'Solo se admiten archivos de tipo {types}',\n 'files.max-file-size-exceeded': 'El tamaño máximo de archivo admitido es {size}',\n 'files.max-total-size-exceeded': 'El tamaño total máximo admitido es {size}',\n 'files.max-files-exceeded': {\n one: 'Se ha superado el número máximo de {count} archivo',\n other: 'Se ha superado el número máximo de {count} archivos',\n },\n 'filters.op.EQ': 'Igual',\n 'filters.op.NEQ': 'Distinto',\n 'filters.op.LT': 'Menor',\n 'filters.op.GT': 'Mayor',\n 'filters.op.LTE': 'Como máximo',\n 'filters.op.GTE': 'Al menos',\n 'filters.op.BETWEEN': 'Entre',\n 'filters.op.CONTAINS': 'Contiene',\n 'filters.op.STARTS_WITH': 'Empieza por',\n 'filters.op.ENDS_WITH': 'Termina por',\n 'filters.sensitivity.IGNORE_CASE': 'Ignorar mayúsculas',\n 'filters.sensitivity.CASE_SENSITIVE': 'Distinguir mayúsculas',\n 'filters.boolean.any': 'Cualquiera',\n 'filters.boolean.true': 'Sí',\n 'filters.boolean.false': 'No',\n 'info.tooltip': 'Más información',\n 'failure.no-reason': 'Se ha producido un error',\n 'dialog.acknowledge': 'Entendido',\n 'dialog.close': 'Cerrar',\n 'dialog.confirm': 'Confirmar',\n 'dialog.cancel': 'Cancelar',\n 'dialog.discard.header': 'Cambios sin guardar',\n 'dialog.discard.body': 'Hay cambios sin guardar: ¿cerrar de todos modos?',\n 'dialog.discard.confirm': 'Cerrar sin guardar',\n 'dialog.discard.cancel': 'Seguir editando',\n 'drawer.close': 'Cerrar',\n 'spinner.loading': 'Cargando…',\n 'toast.region': 'Notificaciones',\n 'toast.dismiss': 'Cerrar',\n 'wizard.progress': 'Progreso',\n};\n","export default {\n 'pagination.showing': 'Page {current} sur {total}',\n 'pagination.navigation': 'Navigation des pages',\n 'pagination.previous': 'Précédent',\n 'pagination.next': 'Suivant',\n 'pagination.reload': 'Recharger',\n 'table.initial': 'Lancez la recherche pour voir les résultats.',\n 'table.error': 'Erreur lors du chargement des données :',\n 'table.no-data': 'Aucun élément trouvé.',\n 'dropdown.empty': 'Aucun résultat',\n 'select.remove': 'Retirer',\n 'files.dropzone-label': 'Cliquez ou déposez vos fichiers ici',\n 'files.remove': 'Retirer',\n 'files.unacceptable-file-type': 'Seuls les fichiers de type {types} sont pris en charge',\n 'files.max-file-size-exceeded': 'La taille maximale de fichier prise en charge est {size}',\n 'files.max-total-size-exceeded': 'La taille totale maximale prise en charge est {size}',\n 'files.max-files-exceeded': {\n one: 'Nombre maximal de {count} fichier dépassé',\n other: 'Nombre maximal de {count} fichiers dépassé',\n },\n 'filters.op.EQ': 'Égal',\n 'filters.op.NEQ': 'Différent',\n 'filters.op.LT': 'Inférieur',\n 'filters.op.GT': 'Supérieur',\n 'filters.op.LTE': 'Au plus',\n 'filters.op.GTE': 'Au moins',\n 'filters.op.BETWEEN': 'Entre',\n 'filters.op.CONTAINS': 'Contient',\n 'filters.op.STARTS_WITH': 'Commence par',\n 'filters.op.ENDS_WITH': 'Finit par',\n 'filters.sensitivity.IGNORE_CASE': 'Ignorer la casse',\n 'filters.sensitivity.CASE_SENSITIVE': 'Respecter la casse',\n 'filters.boolean.any': 'Indifférent',\n 'filters.boolean.true': 'Oui',\n 'filters.boolean.false': 'Non',\n 'info.tooltip': 'Plus d’informations',\n 'failure.no-reason': \"Une erreur s'est produite\",\n 'dialog.acknowledge': 'J’ai compris',\n 'dialog.close': 'Fermer',\n 'dialog.confirm': 'Confirmer',\n 'dialog.cancel': 'Annuler',\n 'dialog.discard.header': 'Modifications non enregistrées',\n 'dialog.discard.body': 'Des modifications ne sont pas enregistrées : fermer quand même ?',\n 'dialog.discard.confirm': 'Fermer sans enregistrer',\n 'dialog.discard.cancel': 'Continuer à modifier',\n 'drawer.close': 'Fermer',\n 'spinner.loading': 'Chargement…',\n 'toast.region': 'Notifications',\n 'toast.dismiss': 'Fermer',\n 'wizard.progress': 'Progression',\n};\n"],"names":["storage","backing","remove","k","removeItem","load","got","getItem","JSON","parse","save","v","setItem","stringify","pop","decoded","versioned","store","key","revision","data","stored","LocalStorage","localStorage","SessionStorage","sessionStorage","VersionedLocalStorage","VersionedSessionStorage","AsyncEvents","fireAsync","el","evt","options","dispatchEvent","promises","async","mode","length","Promise","all","catch","Error","type","resolve","asyncOn","fn","listener","event","ae","promise","reject","withResolvers","push","e","addEventListener","asyncOff","removeEventListener","mixInto","classes","Object","assign","prototype","this","PageLeave","guard","isDirty","signal","window","preventDefault","Claims","generation","take","hold","held","claims","stale","invalidate","describable","at","parentElement","Timing","sleep","ms","setTimeout","debounce","timeoutMs","func","immediate","tid","args","previousTimestamp","later","elapsed","performance","now","called","clearTimeout","undefined","throttle","leading","trailing","remaining","Bindings","flatten","obj","prefix","stops","keys","reduce","acc","pre","has","static","Set","providePath","result","path","value","split","map","test","FORBIDDEN","current","previous","i","ckey","pkey","Number","isInteger","Array","isArray","extract","getAttribute","checked","dataset","fulBindType","tagName","multiple","from","selectedOptions","o","submits","extractFrom","form","submitter","elements","hasAttribute","matches","mutate","raw","values","String","forEach","selected","includes","mutateIn","named","flattenedKey","entries","get","Map","name","bucket","set","errors","es","scrollOnError","ofForm","closest","querySelectorAll","filter","setAttribute","pinned","context","fieldErrors","globalErrors","targets","setCustomValidity","unmatched","parts","replace","slice","join","input","reason","bannered","hel","replaceChildren","removeAttribute","innerText","sort","a","b","getBoundingClientRect","y","focus","Field","ParsedElement","control","pendingFocus","described","descriptions","errorId","fieldError","announces","also","constructor","super","internals","role","ROLE","mirrors","wire","fragment","error","label","freeze","readonly","id","Attributes","uid","describe","defaultPrevented","isComposing","target","submitsOnEnter","_requestSubmit","HTMLInputElement","describedBy","ids","setValidity","customError","candidates","requestSubmit","find","_notifyChange","extras","CustomEvent","bubbles","cancelable","detail","field","LABELABLE","_interactive","formResetCallback","unmarshal","disabled","d","reflectTo","toggleAttribute","readOnly","required","render","conf","built","_build","then","pieces","RemoteJsonFormLoader","http","url","method","requestMapper","responseMapper","prepare","submit","request","json","fetch","transform","response","LocalFormLoader","FormLoader","create","component","declared","ownerOf","formAssociated","Form","document","createElement","forward","childNodes","stopPropagation","stopImmediatePropagation","tracking","touch","Rendering","waitForChildren","commit","connectedCallback","disconnectedCallback","leave","abort","submitting","spinner","loader","submitted","saved","snapshot","upTo","sequence","se","sre","mapped","commitFrom","exception","Failure","problems","console","warn","dirty","reset","edits","refresh","focused","wasDirty","frame","valuesOf","edited","els","delete","nameOf","requestAnimationFrame","contributing","vs","cancelAnimationFrame","button","states","add","AbortController","spinning","announce","defaultValue","hidden","textContent","trim","className","ref","append","Localization","of","t","spin","Math","max","querySelector","wd","patternCache","BoundedCache","compiled","attr","pattern","getOrCompute","RegExp","INPUT_MODES","numeric","decimal","SEGMENTED","NUMERIC_DIGITS","kept","search","Input","_input","controls","_type","slots","template","withOverlay","autocomplete","strip","keep","re","match","unsigned","digits","startsWith","signed","numericFilter","filterOf","configure","reportChanges","before","after","start","selectionStart","caret","setSelectionRange","committed","typed","uppercase","uppercased","toUpperCase","trimmed","normalized","replaceAll","n","isNaN","placeholder","blankAsNull","LocalDate","content","m","parsed","Date","getTime","date","locale","year","month","day","Instant","isoToLocal","hour","minute","second","hour12","iso","pad","padStart","getFullYear","getMonth","getDate","getHours","getMinutes","getSeconds","getMilliseconds","localToIso","local","toISOString","InputLocalDate","min","fromIsoOrOffset","step","formatLocalDate","getTimezoneOffset","exec","sign","offset","r","setHours","setDate","originalDay","setMonth","setFullYear","InputLocalTime","fromNowOrOffset","resolved","setMinutes","snapped","stepSeconds","seconds","floor","hh","mm","InputInstant","InputFile","list","files","dt","DataTransfer","file","items","accept","dropzone","warnings","group","warning","itemstemplate","Fragments","isBlank","Templates","fromFragment","idx","children","indexOf","f","click","dataTransfer","kind","getAsFile","update","ensureAcceptable","ensureFileSizes","ensureTotalSize","ensureFilesCount","renderTo","appendTo","WARNING_TIMEOUT","acceptable","toLowerCase","some","token","endsWith","unacceptable","types","maxFiles","count","maxFileSize","oversized","size","bytes","maxTotalSize","names","totalsize","useItemList","itemList","useDropzone","open","reflowWired","clamp","low","high","place","popover","anchored","invoker","stretch","box","viewport","documentElement","vw","clientWidth","vh","clientHeight","style","removeProperty","computed","getComputedStyle","gap","parseFloat","marginTop","marginRight","marginBottom","marginLeft","right","bottom","margin","cap","maxWidth","minWidth","width","left","height","below","top","note","isNote","placement","wide","here","setProperty","clientLeft","clientTop","reportCallout","reflow","isConnected","schedule","Anchors","invoke","expanded","handPlace","localName","togglePopover","anchor","anchorName","positionAnchor","newState","CSS","supports","visibility","queueMicrotask","showOncePlaced","property","unplace","show","flip","showPopover","Element","above","placeShown","byKeys","byLabel","needle","RemoteLoader","prefetch","inFlight","configs","ensureFetched","exact","claim","revisionedData","finally","storageKey","fetchJson","PartialRemoteLoader","param","InMemoryLoader","SelectLoader","metadata","revisionFrom","responseMapperFrom","configured","_registry","evaluator","evaluateExpression","row","Dropdown","menu","empty","optionstemplate","shows","default","li","change","hide","highlight","activated","scrollIntoView","block","behavior","matchMedia","acceptSelection","entry","index","picked","findIndex","hidePopover","shown","moveOrShow","candidate","walk","jump","first","edge","firstElementChild","lastElementChild","page","next","offsetHeight","trunc","Select","str","builtFrom","src","ddmenu","warnedComma","assignments","editing","dload","abortdload","buildLoader","listbox","wireChrome","wireChips","wireInput","wireSelection","elsewhere","close","removeKeyAt","badge","removeBadge","chipKeydown","code","selectionEnd","badges","select","relatedTarget","contains","comboboxKeydown","clear","coerceKey","changed","withLoader","reload","followAttributes","reconfigure","attributes","notify","arrowKeydown","display","altKey","query","cleared","selection","syncBadges","NaN","RadioGroup","fieldset","firstRadio","booleanType","radioEls","inputsAndLabels","fromChildNodes","radios","escape","Checkbox","container","isSwitch","SortButton","order","sorter","orders","nextOrder","th","Pagination","prevIcon","nextIcon","reloadIcon","total","toCurrent","toTotal","maxRender","pageCount","hasPrev","hasNext","prev","enabled","curr","rendered","pages","_","activeElement","back","TableSchemaParser","nodeOrFragment","schema","Nodes","queryChildren","headersTr","rowsTr","getAttributeNames","columns","queryChildrenAll","column","maybeTitleTag","titleNode","createTextNode","wrappedTitleNode","fulSorter","td","headersTemplate","inHeaders","inRows","withFragment","rowsTemplate","InMemoryTableLoader","pageRequest","sortRequest","filterRequest","rows","sorted","begin","end","l","RemoteTableLoader","filters","fromEntries","TableLoader","Table","searchIcon","emptyIcon","body","loading","noAutoload","emptyAuthors","emptyTemplate","feedback","paginator","sorters","latestRequest","loadRequested","loads","pageSize","table","thead","maybeForm","loadPage","s","lastPage","childElementCount","pageResponse","ceil","failure","resetWithFilter","wireMenuKeys","typedAt","item","ctrlKey","metaKey","wanted","repeated","every","character","found","ChoiceButton","narrow","vocabulary","narrowed","choice","glyphs","labelFor","interactive","onPick","allowed","claimed","wired","fill","sync","preferring","fixed","mark","word","glyph","glyphSpan","wordSpan","GLYPHS","EQ","NEQ","LT","GT","LTE","GTE","BETWEEN","CONTAINS","STARTS_WITH","ENDS_WITH","COMPARE_OPERATORS","TEXT_OPERATORS","SENSITIVITIES","SENSITIVITY_GLYPHS","IGNORE_CASE","CASE_SENSITIVE","operatorLabel","op","sensitivityLabel","sensitivity","booleanValueLabel","labelTextOf","fixChoice","singular","plural","fallback","known","asCriterion","operator","operands","CompareFilter","_operator","_container","_value1","_value2","_vocabulary","_syncBetween","operators","_showDefaultOperator","_defaultOperator","_showOperator","_serialize","_deserialize","_declaredOperators","_tuple","_applyTuple","criterion","_choices","c","InstantFilter","LocalDateFilter","NumberFilter","TextFilter","_sensitivityButton","_sensitivity","_declaredSensitivities","sensitivities","tuple","BOOLEAN_VALUES","BOOLEAN_VALUE_GLYPHS","true","false","BooleanFilter","_value","valueButton","OPERATORS","DEFAULT_OPERATOR","InFilter","chosen","flat","Tooltip","icon","trigger","tooltip","tabIndex","SectionRequests","entered","WeakSet","WeakMap","host","section","owned","cause","paintError","prepend","DialogSections","dialog","requests","updates","confirming","dismiss","asked","confirm","drop","onBackdrop","pressedOutside","onSubmitted","answer","restChrome","cb","delivered","targetsWired","wireTargets","getElementById","Dialog","sections","resolvers","requiresAnswer","closeOnSubmit","header","heading","outcome","settle","dismissed","returnValue","ask","discardEdits","showModal","buttons","choices","Node","buttonClass","waitFor","labels","cancel","l10n","Drawer","title","closing","slideOutEnded","closeNow","stopSlidingOut","getAnimations","Menu","pressed","wireShared","showFor","marginBlockStart","moving","SEVERITIES","REGIONS","listenerWired","Toasts","timeout","region","message","severity","classList","startedAt","timer","retire","action","onClick","holds","release","raise","Tabs","tablist","tabs","panels","active","panel","tab","replaceWith","Accordion","exclusive","details","Wizard","steps","progress","apply","enter","move","clamped","BUILTIN","en","one","other","it","fr","Plugin","language","translations","httpClient","navigator","registry","HttpClient","builder","withCsrfToken","withRedirectOnUnauthorized","build","defineModule","defineComponent","defineElement","defineOverlay"],"mappings":"oNA+BA,MAAMA,EAAWC,IACb,MAAMC,EAAUC,IACZ,IACIF,IAAUG,WAAWD,EACzB,CAAE,MAAO,GAEPE,EAAQF,IACV,IAAIG,EACJ,IACIA,EAAML,IAAUM,QAAQJ,EAC5B,CAAE,MACE,MACJ,CACA,GAAY,OAARG,EAGJ,IACI,OAAOE,KAAKC,MAAMH,EACtB,CAAE,MAEE,YADAJ,EAAOC,EAEX,GAUJ,MAAO,CAAEO,KARI,CAACP,EAAGQ,KACbV,IAAUW,QAAQT,EAAGK,KAAKK,UAAUF,KAOzBN,OAAMH,SAAQY,IALhBX,IACT,MAAMY,EAAUV,EAAKF,GAErB,OADAD,EAAOC,GACAY,KASTC,EAAaC,IAAK,CACpB,IAAAP,CAAKQ,EAAKC,EAAUC,GAChBH,EAAMP,KAAKQ,EAAK,CAAEC,WAAUC,QAChC,EACA,IAAAf,CAAKa,EAAKC,GACN,MAAME,EAASJ,EAAMZ,KAAKa,GAC1B,GAAc,MAAVG,GAAoC,iBAAXA,GAAuBA,EAAOF,WAAaA,EAIxE,OAAOE,EAAOD,KAHVH,EAAMf,OAAOgB,EAIrB,IAIEI,EAAetB,EAAQ,IAAMuB,cAE7BC,EAAiBxB,EAAQ,IAAMyB,gBAE/BC,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AAc,eAAgBnZ,IAC9BkZ,gBAAgB,iBAAkB3Z,IAClC2Z,gBAAgB,eAAgBjuB,GAChCiuB,gBAAgB,gBAAiB3P,IACjC6P,cAAc,CACXrE,OACAvhB,OAAQzV,MAAKw6B,IAEzB"}
1
+ {"version":3,"file":"ful.min.mjs","sources":["../src/ful/storage.mjs","../src/ful/events/async.mjs","../src/ful/events/leave.mjs","../src/ful/claims.mjs","../src/ful/descriptions.mjs","../src/ful/timing.mjs","../src/ful/forms/bindings.mjs","../src/ful/forms/field.mjs","../src/ful/forms/form.mjs","../src/ful/forms/input.mjs","../src/ful/forms/temporals.mjs","../src/ful/forms/files.mjs","../src/ful/disclosures/anchors.mjs","../src/ful/forms/select.mjs","../src/ful/forms/radio.mjs","../src/ful/forms/checkbox.mjs","../src/ful/navigation/table.mjs","../src/ful/disclosures/menu-keys.mjs","../src/ful/forms/choice-button.mjs","../src/ful/forms/filters.mjs","../src/ful/disclosures/tooltip.mjs","../src/ful/events/sections.mjs","../src/ful/disclosures/dialog-sections.mjs","../src/ful/disclosures/targets.mjs","../src/ful/disclosures/dialog.mjs","../src/ful/disclosures/drawer.mjs","../src/ful/disclosures/menu.mjs","../src/ful/disclosures/toast.mjs","../src/ful/navigation/tabs.mjs","../src/ful/disclosures/accordion.mjs","../src/ful/navigation/wizard.mjs","../src/ful/plugin.mjs","../src/ful/l10n/en.mjs","../src/ful/l10n/it.mjs","../src/ful/l10n/es.mjs","../src/ful/l10n/fr.mjs"],"sourcesContent":["/**\n * One of the page's storages, holding values encoded as json. The functions\n * do not use `this`, so they keep working when destructured. Reads never\n * throw: where the storage cannot be reached at all (blocked cookies, some\n * embedded or private contexts) a read is a miss and a removal does nothing.\n * @typedef {Object} JsonStorage\n * @property {(k: string, v: any) => void} save stores `JSON.stringify(v)`\n * under `k`, throwing what the encoding or the storage throws: an unreachable\n * storage, a full quota, a value json cannot encode\n * @property {(k: string) => any} load the value stored under `k`, decoded;\n * undefined when there is none, when the storage cannot be reached, or when the\n * stored text is not json, in which case the entry is also removed\n * @property {(k: string) => void} remove removes the entry under `k`\n * @property {(k: string) => any} pop what `load` answers for `k`, removing the\n * entry\n */\n/**\n * One of the page's storages holding values beside a revision.\n * @typedef {Object} VersionedJsonStorage\n * @property {(key: string, revision: string, data: any) => void} save stores\n * `data` with `revision` under `key`, throwing what `JsonStorage.save` throws\n * @property {(key: string, revision: string) => any} load the data stored under\n * `key` when it was saved with this exact revision; otherwise undefined, and the\n * entry is removed, whether it holds another revision, holds no revision at\n * all, or is missing\n */\n/**\n * @param {() => globalThis.Storage} backing called on every operation, so an\n * unreachable storage fails that operation rather than the module's load\n * @returns {JsonStorage}\n */\nconst storage = (backing) => {\n const remove = (k) => {\n try {\n backing().removeItem(k);\n } catch {}\n };\n const load = (k) => {\n let got;\n try {\n got = backing().getItem(k);\n } catch {\n return undefined;\n }\n if (got === null) {\n return undefined;\n }\n try {\n return JSON.parse(got);\n } catch {\n remove(k);\n return undefined;\n }\n };\n const save = (k, v) => {\n backing().setItem(k, JSON.stringify(v));\n };\n const pop = (k) => {\n const decoded = load(k);\n remove(k);\n return decoded;\n };\n return { save, load, remove, pop };\n};\n\n/**\n * @param {JsonStorage} store\n * @returns {VersionedJsonStorage}\n */\nconst versioned = (store) => ({\n save(key, revision, data) {\n store.save(key, { revision, data });\n },\n load(key, revision) {\n const stored = store.load(key);\n if (stored == null || typeof stored !== 'object' || stored.revision !== revision) {\n store.remove(key);\n return undefined;\n }\n return stored.data;\n },\n});\n\n/** `localStorage`, holding json. */\nconst LocalStorage = storage(() => localStorage);\n/** `sessionStorage`, holding json. */\nconst SessionStorage = storage(() => sessionStorage);\n/** `localStorage`, holding json beside a revision. */\nconst VersionedLocalStorage = versioned(LocalStorage);\n/** `sessionStorage`, holding json beside a revision. */\nconst VersionedSessionStorage = versioned(SessionStorage);\n\nexport { LocalStorage, VersionedLocalStorage, SessionStorage, VersionedSessionStorage };\n","/**\n * @typedef {Object} AsyncExtension\n * @property {Promise<any>[]} promises one per `asyncOn` listener the event\n * reached, in the order they ran\n * @typedef {Event & { async?: AsyncExtension }} AsyncEvent\n */\n/**\n * Dispatching an event and waiting for what its listeners answer. A listener\n * registered through `asyncOn` attaches its promise to the event, and\n * `fireAsync` resolves once they have all settled: `broadcast` collects every\n * answer, `pipeline` allows at most one, `delegate` requires exactly one.\n */\nclass AsyncEvents {\n /**\n * Dispatches `evt` on `el` synchronously, then waits for the answers of the\n * `asyncOn` listeners it reached, on `el` or, for a bubbling event, on its\n * ancestors. Listeners added with a plain `addEventListener` run but are not\n * awaited. In `broadcast` mode, the default, it resolves with every answer\n * in the order the listeners ran, an empty array when none did. In\n * `pipeline` mode it accepts at most one listener and resolves with its\n * answer, or undefined when none ran. In `delegate` mode it requires exactly\n * one listener and resolves with its answer.\n * @param {HTMLElement} el the element to dispatch on\n * @param {AsyncEvent} evt the event to dispatch\n * @param {{mode?: 'broadcast' | 'pipeline' | 'delegate'}} [options]\n * @returns {Promise<any>} the answer or answers as the mode describes\n * @throws what the first answer to fail threw or rejected with; or an\n * Error naming the event and the mode when `pipeline` reached more than one\n * listener or `delegate` did not reach exactly one, in which case the\n * listeners have already run and their outcome is discarded. Both arrive as\n * the rejection of the returned promise.\n */\n static async fireAsync(el, evt, options) {\n el.dispatchEvent(evt);\n const promises = evt.async?.promises ?? [];\n const mode = options?.mode ?? 'broadcast';\n if ((mode === 'pipeline' && promises.length > 1) || (mode === 'delegate' && promises.length !== 1)) {\n Promise.all(promises).catch(() => {});\n throw new Error(\n mode === 'pipeline'\n ? `[AsyncEvents] Event \"${evt.type}\" is configured in 'pipeline' mode and expects at most one async listener, but ${promises.length} listeners were triggered on this element.`\n : `[AsyncEvents] Event \"${evt.type}\" is configured in 'delegate' mode and requires exactly one async listener, but ${promises.length} were registered.`,\n );\n }\n return mode === 'broadcast' ? Promise.all(promises) : Promise.resolve(promises[0]);\n }\n\n /**\n * Adds a listener whose answer `fireAsync` can await. When the event\n * reaches it, the listener attaches a promise to `evt.async.promises`,\n * creating the list when it is the first, then calls `fn` with the event;\n * the promise settles with what `fn` returns or throws, awaited when it is a\n * promise. The event is dispatched the usual way, so an event fired with a\n * plain `dispatchEvent` runs `fn` too, and nobody awaits its answer.\n * @param {HTMLElement} el the element to listen on\n * @param {string} type the event type\n * @param {(evt: any) => any} fn called with the event; its result is the answer\n * @param {AddEventListenerOptions} [options] passed to `addEventListener`\n * @returns {EventListener} the listener actually added, which `asyncOff` takes\n */\n static asyncOn(el, type, fn, options) {\n /** @type {(evt: Event) => Promise<void>} */\n const listener = async (event) => {\n const ae = /** @type {AsyncEvent} */ (event);\n if (!ae.async) {\n ae.async = { promises: [] };\n }\n const { promise, resolve, reject } = Promise.withResolvers();\n ae.async.promises.push(promise);\n try {\n resolve(await fn(ae));\n } catch (e) {\n reject(e);\n }\n };\n\n el.addEventListener(type, listener, options);\n return listener;\n }\n\n /**\n * Removes a listener added by `asyncOn`.\n * @param {HTMLElement} el the element it listens on\n * @param {string} type the event type it was added for\n * @param {EventListener} listener what `asyncOn` returned, not the `fn` given to it\n * @param {EventListenerOptions} [options] passed to `removeEventListener`\n * @returns {void}\n */\n static asyncOff(el, type, listener, options) {\n el.removeEventListener(type, listener, options);\n }\n /**\n * Assigns `fireAsync(evt, options)`, `asyncOn(type, fn, options)` and\n * `asyncOff(type, listener, options)` onto each class's prototype, each\n * calling the static of the same name with the instance as the element.\n * Members of those names already on the prototype are overwritten.\n * @param {...Function} classes the classes to extend\n * @returns {void}\n */\n static mixInto(...classes) {\n for (const k of classes) {\n Object.assign(k.prototype, {\n /**\n * @this {HTMLElement}\n * @param {AsyncEvent} evt\n * @param {{mode?: 'broadcast' | 'pipeline' | 'delegate'}} [options]\n * @returns {Promise<any>}\n */\n async fireAsync(evt, options) {\n return await AsyncEvents.fireAsync(this, evt, options);\n },\n\n /**\n * @this {HTMLElement}\n * @param {string} type\n * @param {(evt: any) => any} fn\n * @param {AddEventListenerOptions} [options]\n * @returns {EventListener}\n */\n asyncOn(type, fn, options) {\n return AsyncEvents.asyncOn(this, type, fn, options);\n },\n\n /**\n * @this {HTMLElement}\n * @param {string} type\n * @param {EventListener} listener\n * @param {EventListenerOptions} [options]\n * @returns {void}\n */\n asyncOff(type, listener, options) {\n AsyncEvents.asyncOff(this, type, listener, options);\n },\n });\n }\n }\n}\n\nexport { AsyncEvents };\n","/**\n * Asks before the page is left, through the browser's own `beforeunload`\n * prompt.\n */\nclass PageLeave {\n /**\n * Asks before the page is left while `isDirty()` answers true, until\n * `signal` aborts. The browser words the prompt, and asks only once the\n * user has interacted with the page.\n * @param {() => boolean} isDirty\n * @param {AbortSignal} [signal]\n */\n static guard(isDirty, signal) {\n window.addEventListener(\n 'beforeunload',\n (evt) => {\n if (isDirty()) {\n evt.preventDefault();\n }\n },\n { signal },\n );\n }\n}\n\nexport { PageLeave };\n","/**\n * A hold on one generation of a `Claims`: `stale` turns true once a later\n * `take()` or `invalidate()` on it starts a newer generation.\n * @typedef {{ readonly stale: boolean }} Claim\n */\n/**\n * The generations of claims over one contended resource. Every take() starts a\n * new generation, superseding every claim before it, and a holder asks its\n * claim `stale` before painting chrome, storing state or throwing towards a\n * caller: a superseded outcome owns nothing. hold() joins the current\n * generation without superseding it (a fetch that any later reconfiguration\n * must detach), and invalidate() supersedes without claiming (a hide ending\n * every pending show). One Claims per contended resource: a component whose\n * dropdown, value labels and loader configuration contend separately holds one\n * each.\n */\nclass Claims {\n #generation = 0;\n /**\n * Starts a new generation, superseding every earlier claim, and holds it.\n * @returns {Claim}\n */\n take() {\n ++this.#generation;\n return this.hold();\n }\n /**\n * Holds the current generation without superseding anything.\n * @returns {Claim}\n */\n hold() {\n const held = this.#generation;\n const claims = this;\n return {\n /** true once a later take() or invalidate() superseded this claim */\n get stale() {\n return held !== claims.#generation;\n },\n };\n }\n /**\n * Supersedes every claim without holding a new one.\n * @returns {void}\n */\n invalidate() {\n ++this.#generation;\n }\n}\n\nexport { Claims };\n","/**\n * Something that adds elements to the accessible description of the control it\n * owns, such as a field: `describedBy(el)` adds `el` to the control's\n * `aria-describedby` and answers whether it did.\n * @typedef {{ describedBy(el: HTMLElement): boolean }} Describable\n */\n\n/**\n * The nearest ancestor of `el` that has a `describedBy` method. Content\n * slotted inside a field does not write the control's `aria-describedby`\n * itself: once it has something to offer, it hands the element carrying the\n * words to the `describedBy` of the ancestor this answers.\n * @param {Element} el\n * @returns {(Element & Describable) | null} null when no ancestor has one\n */\nconst describable = (el) => {\n for (let at = el.parentElement; at; at = at.parentElement) {\n if (typeof (/** @type {any} */ (at).describedBy) === 'function') {\n return /** @type {any} */ (at);\n }\n }\n return null;\n};\n\nexport { describable };\n","/**\n * Sleeping, debouncing and throttling. `debounce` and `throttle` both return\n * the wrapped function together with an abort function, which cancels the call\n * pending and leaves the wrapped function working.\n */\nclass Timing {\n /**\n * @param {number} ms\n * @returns {Promise<void>} resolving after `ms` milliseconds\n */\n static sleep(ms) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n /**\n * Collapses a burst of calls into one call of `func`, a burst ending once\n * `timeoutMs` pass without a call. By default `func` is called at the end\n * of the burst with the arguments of its last call. With `immediate` it is\n * called at the first call of a burst, with that call's arguments, and not\n * at the end. Without `immediate`, a call the wrapped function receives\n * from inside `func` starts a new burst.\n * @param {number} timeoutMs\n * @param {(...args: any[]) => any} func\n * @param {{ immediate?: boolean }} [options]\n * @returns {[(...args: any[]) => void, () => void]} the wrapped function\n * and the abort function\n */\n static debounce(timeoutMs, func, options) {\n const immediate = options?.immediate ?? false;\n let tid = /** @type {number | null} */ (null);\n let args = [];\n let previousTimestamp = 0;\n\n const later = () => {\n const elapsed = performance.now() - previousTimestamp;\n if (timeoutMs > elapsed) {\n tid = setTimeout(later, timeoutMs - elapsed);\n return;\n }\n tid = null;\n if (!immediate) {\n func(...args);\n }\n if (tid === null) {\n args = [];\n }\n };\n\n const debounced = (...called) => {\n args = called;\n previousTimestamp = performance.now();\n if (tid === null) {\n tid = setTimeout(later, timeoutMs);\n if (immediate) {\n func(...args);\n }\n }\n };\n const abort = () => {\n clearTimeout(tid ?? undefined);\n tid = null;\n args = [];\n };\n return [debounced, abort];\n }\n /**\n * Calls `func` at most once per `timeoutMs`, always with the arguments of\n * the latest call. With `leading`, on by default, a call arriving once the\n * interval since the previous call of `func` has passed calls it at once;\n * without it, the first call only starts the interval. With `trailing`, on\n * by default, a call arriving inside the interval schedules `func` for the\n * interval's end; without it, such a call is dropped.\n * @param {number} timeoutMs\n * @param {(...args: any[]) => any} func\n * @param {{ leading?: boolean, trailing?: boolean }} [options]\n * @returns {[(...args: any[]) => void, () => void]} the wrapped function\n * and the abort function\n */\n static throttle(timeoutMs, func, options) {\n const leading = options?.leading ?? true;\n const trailing = options?.trailing ?? true;\n let tid = /** @type {number | null} */ (null);\n let args = [];\n let previousTimestamp = 0;\n\n const later = () => {\n previousTimestamp = leading ? performance.now() : 0;\n tid = null;\n func(...args);\n if (tid === null) {\n args = [];\n }\n };\n const throttled = (...called) => {\n const now = performance.now();\n if (!previousTimestamp && !leading) {\n previousTimestamp = now;\n }\n const remaining = previousTimestamp === 0 ? 0 : timeoutMs - (now - previousTimestamp);\n args = called;\n if (remaining <= 0 || remaining > timeoutMs) {\n if (tid !== null) {\n clearTimeout(tid);\n tid = null;\n }\n previousTimestamp = now;\n func(...args);\n if (tid === null) {\n args = [];\n }\n } else if (tid === null && trailing) {\n tid = setTimeout(later, remaining);\n }\n };\n const abort = () => {\n clearTimeout(tid ?? undefined);\n tid = null;\n args = [];\n };\n return [throttled, abort];\n }\n}\n\nexport { Timing };\n","/**\n * Moves values between a form's named controls and a nested object, and pins\n * problems onto the controls they name. Works on any native form, not only\n * the one inside a `ful-form`. Every method reads the controls through\n * `form.elements`, so a control in the subtree that belongs to another form\n * (a nested form, a `form` attribute pointing elsewhere) is never read,\n * written or marked.\n */\nclass Bindings {\n /**\n * Flattens a nested object into dotted keys, array indexes becoming numeric\n * segments (`a.0.b`). It does not descend below a key that `stops` names, so\n * with a field named `address` the whole object is kept under `address`,\n * while with one named `address.city` the leaf is kept under `address.city`.\n * A null value is kept as a leaf.\n * @param {{ [x: string]: any; }} obj\n * @param {string} prefix prepended to every key, `''` at the root\n * @param {Set<string>} stops the dotted keys to keep whole\n * @returns {{ [x: string]: any; }} a flat object keyed by dotted path\n */\n static flatten(obj, prefix, stops) {\n return Object.keys(obj).reduce((acc, k) => {\n const pre = prefix.length ? `${prefix}.${k}` : k;\n if (!stops.has(pre) && typeof obj[k] === 'object' && obj[k] !== null) {\n Object.assign(acc, Bindings.flatten(obj[k], pre, stops));\n } else {\n acc[pre] = obj[k];\n }\n return acc;\n }, {});\n }\n\n static #FORBIDDEN = new Set(['__proto__', 'prototype', 'constructor']);\n /**\n * Writes a value into an object at a dotted path, creating the intermediate\n * objects and arrays the path implies: a numeric segment makes its container\n * an array. Brackets are not parsed, so `a[0]` is a plain key.\n *\n * An undefined value declares the path without filling it: an entry already\n * there is kept, a missing one is set to null. A scalar or a null left on the\n * path by a shorter overlapping name (`a` written before `a.b`) is replaced\n * by a container, so the longer name wins whichever order they arrive in.\n * @param {any} result the object or array to write into\n * @param {string} path a dotted name such as `a.b` or `a.0.b`\n * @param {any} value\n * @returns {any} the root written into, to be used in place of `result`: a\n * new array replaces it when the first segment is numeric and `result` is\n * not an array\n * @throws {Error} when a segment is `__proto__`, `prototype` or `constructor`,\n * before anything is written\n */\n static providePath(result, path, value) {\n const keys = path.split('.').map((k) => (/^[0-9]+$/.test(k) ? +k : k));\n for (const key of keys) {\n if (Bindings.#FORBIDDEN.has(/** @type any */ (key))) {\n throw new Error(`unsupported name segment '${key}' in '${path}'`);\n }\n }\n let current = result ?? {};\n let previous = /** @type {any} */ (null);\n for (let i = 0; ; ++i) {\n const ckey = keys[i];\n const pkey = keys[i - 1];\n if (Number.isInteger(ckey) && !Array.isArray(current)) {\n if (previous !== null) {\n previous[pkey] = current = [];\n } else {\n result = current = [];\n }\n }\n if (i === keys.length - 1) {\n current[ckey] = value !== undefined ? value : ckey in current ? current[ckey] : null;\n return result;\n }\n if (typeof current[ckey] !== 'object' || current[ckey] === null) {\n current[ckey] = {};\n }\n previous = current;\n current = current[ckey];\n }\n }\n /**\n * Reads one control's value by its kind. The kind is read from the `type`\n * attribute and the tag, so a ful element answers its own `value`.\n *\n * - a radio answers its `value` when checked and undefined otherwise\n * - a checkbox answers its `checked` state\n * - `data-ful-bind-type=\"boolean\"` decodes the value: a radio answers\n * whether its value is `'true'`, any other control answers null when\n * blank and whether its value is `'true'` otherwise\n * - a multiple select answers the array of its selected values\n * - a native input, select or textarea answers null when blank\n * - anything else answers its `value` unchanged\n * @param {Element & {dataset?: any} & {checked?: boolean} & {value?: any}} el\n * @returns {any} the value; undefined for an unchecked radio\n */\n static extract(el) {\n if (el.getAttribute('type') === 'radio') {\n if (!el.checked) {\n return undefined;\n }\n return el.dataset.fulBindType === 'boolean' ? el.value === 'true' : el.value;\n }\n if (el.getAttribute('type') === 'checkbox') {\n return el.checked;\n }\n if (el.dataset.fulBindType === 'boolean') {\n return !el.value ? null : el.value === 'true';\n }\n if (el.tagName === 'SELECT' && /** @type {HTMLSelectElement} */ (el).multiple) {\n return Array.from(/** @type {HTMLSelectElement} */ (el).selectedOptions).map((o) => o.value);\n }\n if (el.tagName === 'INPUT' || el.tagName === 'SELECT' || el.tagName === 'TEXTAREA') {\n return el.value === '' || el.value === undefined ? null : el.value;\n }\n return el.value;\n }\n\n /**\n * @param {Element & {type?: string}} el\n */\n static #submits(el) {\n return el.type === 'submit' || el.type === 'reset' || el.type === 'button';\n }\n /**\n * Reads the form's named controls into a nested object, the dotted names\n * deciding its shape (see `providePath`) and each value read by `extract`.\n * Controls are read in document order, so of two overlapping names the\n * later one decides. A control is skipped when it has no `name`, when it\n * matches `:disabled` (its own `disabled` or a disabled fieldset's), or when\n * it is a submit, reset or plain button. The submitter is the exception to\n * both of the last two: it contributes its name and value even while\n * disabled.\n * @param {HTMLFormElement} form\n * @param {HTMLElement} [submitter] the button that submitted, when there is one\n * @returns {any} the nested values; an array when the first segment of a name is numeric\n * @throws {Error} when a name has a segment `providePath` refuses\n */\n static extractFrom(form, submitter) {\n let result = {};\n for (const el of form.elements) {\n if (!el.hasAttribute('name')) {\n continue;\n }\n if (Bindings.#submits(el) && el !== submitter) {\n continue;\n }\n if (el.matches(':disabled') && el !== submitter) {\n continue;\n }\n result = Bindings.providePath(\n result,\n /** @type {string} */ (el.getAttribute('name')),\n Bindings.extract(el),\n );\n }\n return result;\n }\n\n /**\n * Writes a value into one control, the inverse of `extract`.\n *\n * - a radio is checked when `raw` is not null and its `value` attribute\n * equals `String(raw)`, so a number or a boolean matches its text\n * - a checkbox takes `raw` as its `checked` state\n * - a multiple select selects the options whose value is in `raw`, compared\n * as text: an array selects each entry, a scalar selects one, null selects none\n * - anything else takes `raw` as its `value`\n * @param {Element & {dataset?: any} & {checked?: boolean} & {value?: any}} el\n * @param {any} raw\n */\n static mutate(el, raw) {\n if (el.getAttribute('type') === 'radio') {\n el.checked = raw != null && el.getAttribute('value') === String(raw);\n return;\n }\n if (el.getAttribute('type') === 'checkbox') {\n el.checked = raw;\n return;\n }\n if (el.tagName === 'SELECT' && /** @type {HTMLSelectElement} */ (el).multiple) {\n const values = Array.isArray(raw) ? raw.map(String) : raw == null ? [] : [String(raw)];\n Array.from(/** @type {HTMLSelectElement} */ (el).options).forEach((o) => {\n o.selected = values.includes(o.value);\n });\n return;\n }\n el.value = raw;\n }\n\n /**\n * Writes a nested object onto the form's named controls: the object is\n * flattened with the control names as stops (see `flatten`), and each key\n * is written by `mutate` into every control carrying exactly that name. A\n * key naming no control is ignored, and a control the object does not name\n * keeps its value.\n * @param {HTMLFormElement} form\n * @param {{ [x: string]: any; }} values\n */\n static mutateIn(form, values) {\n const named = Bindings.#named(form);\n for (const [flattenedKey, value] of Object.entries(Bindings.flatten(values, '', new Set(named.keys())))) {\n for (const el of named.get(flattenedKey) ?? []) {\n Bindings.mutate(el, value);\n }\n }\n }\n\n /**\n * @param {HTMLFormElement} form\n * @returns {Map<string, any[]>} the controls of `form.elements` grouped by name\n */\n static #named(form) {\n const named = new Map();\n for (const el of form.elements) {\n const name = el.getAttribute('name');\n if (!name) {\n continue;\n }\n const bucket = named.get(name);\n if (bucket) {\n bucket.push(el);\n } else {\n named.set(name, [el]);\n }\n }\n return named;\n }\n\n /**\n * Shows problems on the form, replacing whatever the previous call showed.\n *\n * Every named control's custom validity is first cleared. A problem whose\n * `type` is `FIELD_ERROR` or `INVALID_FORMAT` and whose `context` is not\n * empty is pinned to a control: brackets in the context are turned into\n * dots (`users[0].name` becomes `users.0.name`), and the longest leading\n * part of it that names a control wins, so an exact field takes the problem\n * alone and a composite field named for a prefix catches the problems of its\n * subtree. Each control of that name gets `setCustomValidity(reason, rest)`,\n * `rest` being the remainder of the path (`''` on an exact match) that a\n * composite can use to route the problem to an inner control.\n *\n * A control counts only when it can show a problem, through a\n * `setCustomValidity` of its own: a form-associated element that has none is\n * skipped, so its problems fall to a shorter prefix or to the banner instead\n * of being dropped.\n *\n * Every other problem, and a field problem naming no control, is shown in\n * each `ful-errors` banner of the form: the banner gets `role=\"alert\"`, is\n * revealed and holds the reasons one per line. With no such problem the\n * banner is emptied and hidden.\n *\n * Each `ful-field-error` of the form gets `aria-live=\"off\"` when\n * `scrollOnError` is set, since focusing the field announces its error, and\n * `aria-live=\"polite\"` otherwise. With `scrollOnError` and at least one\n * problem, the topmost `:invalid` control is focused.\n *\n * A banner or `ful-field-error` belongs to the nearest enclosing form, so\n * those of a nested form are left alone.\n * @param {HTMLFormElement} form\n * @param {{ type: string; context?: string | null; reason: string; }[]} es the problems, as an httpc `Failure` carries them\n * @param {boolean} scrollOnError\n */\n static errors(form, es, scrollOnError) {\n const ofForm = (el) => el.closest('form') === form;\n Array.from(form.querySelectorAll('ful-field-error'))\n .filter(ofForm)\n .forEach((el) => {\n el.setAttribute('aria-live', scrollOnError ? 'off' : 'polite');\n });\n const pinned = (e) => (e.type === 'FIELD_ERROR' || e.type === 'INVALID_FORMAT') && e.context;\n const fieldErrors = es.filter(pinned);\n const globalErrors = es.filter((e) => !pinned(e));\n const named = Bindings.#named(form);\n for (const targets of named.values()) {\n targets.forEach((el) => {\n el.setCustomValidity?.('');\n });\n }\n const unmatched = [];\n fieldErrors.forEach((e) => {\n const name = /** @type {string} */ (e.context).replace(/\\[/g, '.').replace(/\\]\\./g, '.').replace(/\\]/g, '');\n const parts = name.split('.');\n for (let i = parts.length; i !== 0; --i) {\n const prefix = parts.slice(0, i).join('.');\n const targets = (named.get(prefix) ?? []).filter((el) => typeof el.setCustomValidity === 'function');\n if (targets.length === 0) {\n continue;\n }\n const context = parts.slice(i).join('.');\n targets.forEach((input) => {\n input.setCustomValidity?.(e.reason, context);\n });\n return;\n }\n unmatched.push(e);\n });\n const bannered = [...globalErrors, ...unmatched];\n form.querySelectorAll('ful-errors').forEach((el) => {\n if (!ofForm(el)) {\n return;\n }\n const hel = /** @type {HTMLElement} */ (el);\n el.setAttribute('role', 'alert');\n if (bannered.length === 0) {\n el.replaceChildren();\n el.setAttribute('hidden', '');\n return;\n }\n el.removeAttribute('hidden');\n hel.innerText = bannered.map((e) => e.reason).join('\\n');\n });\n if (es.length === 0 || !scrollOnError) {\n return;\n }\n /** @type {HTMLElement[]} */ (Array.from(form.elements))\n .filter((el) => el.matches(':invalid'))\n .sort((a, b) => a.getBoundingClientRect().y - b.getBoundingClientRect().y)[0]\n ?.focus();\n }\n}\n\nexport { Bindings };\n","import { Attributes, ParsedElement } from '../../ftl/index.mjs';\n\n/**\n * The base of every form-associated ful field: a form-associated custom element\n * carrying the validity protocol, the field error live region, focus\n * delegation, the label chrome and the disabled, readonly and required claims.\n *\n * A subclass owns its template, its value semantics and its change events. It\n * implements `_build(conf)`, which builds its dom and returns the pieces the\n * base drives (see `_build`), and the `value` pair. The base wires the pieces,\n * mounts the fragment and applies the declared state. Nothing in the base is\n * there to be called from a subclass's build.\n *\n * The claim setters, the validity protocol and the aria wiring all act on the\n * pieces, so a field with no native control returns a focusable piece of its\n * own chrome as the control. The claim getters and `focus()` are the only\n * members that tolerate a not yet rendered element; the other members need the\n * pieces and so work only after the render.\n *\n * The inner controls carry `form=\"\"`, so the host is the only element the form\n * sees. Enter pressed in an inner `<input>` of any type but `file`, `button`,\n * `submit`, `reset` and `image` submits the field's form through\n * `_requestSubmit()`, as Enter in a native input would. It does not when a\n * listener inside the field already called `preventDefault()` on the keydown,\n * while an input method is composing, or when the input is still associated\n * with the form itself and so submits on its own.\n */\nclass Field extends ParsedElement {\n static formAssociated = true;\n /**\n * The claim attributes and the value, observed so that every field,\n * including a custom one that never lists them, keeps them live after the\n * upgrade. A subclass's own `static observed` adds to this list. The value\n * is read with the string mapper; a field with another vocabulary redeclares\n * it with its own (`value:bool`, `value:csv`, `value:json`).\n * @type {string[]}\n */\n static observed = ['disabled:presence', 'readonly:presence', 'required:presence', 'value'];\n /**\n * The role set on the element internals at construction. A field whose host\n * is the widget itself overrides it, as `RadioGroup` does with `'radiogroup'`.\n * @type {string}\n */\n static ROLE = 'presentation';\n #control;\n #pendingFocus = /** @type {FocusOptions | null} */ (null);\n #described;\n #descriptions = [];\n #errorId = null;\n #fieldError;\n #claims;\n #announces;\n #also = [];\n /** Sets the internals' role from the subclass's `static ROLE`. */\n constructor() {\n super();\n this.internals.role = /** @type {typeof Field} */ (this.constructor).ROLE;\n }\n #mirrors() {\n return [this.#claims ?? this.#control, ...this.#also].filter((el) => el);\n }\n /**\n * @param {{fragment: any, control: any, error?: any, label?: any, described?: any,\n * claims?: any, announces?: any, freeze?: any, also?: any[]}} pieces\n */\n #wire({\n fragment,\n control,\n error,\n label = null,\n described = null,\n claims = null,\n announces = control,\n freeze = null,\n also = [],\n }) {\n this.#control = control;\n this.#fieldError = error;\n this.#claims = claims;\n this.#announces = announces;\n this.#also = also;\n if (freeze) {\n freeze.addEventListener(\n 'click',\n (evt) => {\n if (this.readonly) {\n evt.preventDefault();\n }\n },\n true,\n );\n }\n this.#described = described ?? control;\n if (error) {\n error.id = error.id || Attributes.uid('ful-field-error');\n this.#errorId = error.id;\n }\n this.#describe();\n if (label) {\n Field.#name(this, label, control);\n }\n this.addEventListener('keydown', (evt) => {\n if (evt.key !== 'Enter' || evt.defaultPrevented || evt.isComposing) {\n return;\n }\n const target = /** @type {HTMLInputElement} */ (evt.target);\n if (target.form === this.form || !Field.#submitsOnEnter(target)) {\n return;\n }\n this._requestSubmit();\n });\n this.replaceChildren(fragment);\n if (this.#pendingFocus !== null) {\n const options = this.#pendingFocus;\n this.#pendingFocus = null;\n control.focus(options);\n }\n }\n /**\n * @param {EventTarget} el\n * @returns {boolean} whether Enter in `el` submits a form on the platform\n */\n static #submitsOnEnter(el) {\n return el instanceof HTMLInputElement && !['file', 'button', 'submit', 'reset', 'image'].includes(el.type);\n }\n /**\n * Adds an element to the accessible description of the field and answers\n * whether the field took it.\n *\n * The field takes a description before its own render as readily as after:\n * one handed over early is written as soon as the field has rendered, so the\n * caller does not need to know which of the two upgraded first. The element\n * is given an id (`ful-described-*`) when it has none, is added once however\n * often it is offered, and is referenced from the `aria-describedby`\n * attribute of the `described` piece (the control by default). The\n * descriptions come in the order they were offered, the error region always\n * last.\n *\n * Pass the element that carries the words rather than a wrapper around it:\n * a hidden element is part of a description only where it is referenced\n * directly, so a popover that is closed until opened must be passed itself.\n *\n * This is the field's half of the description protocol; `describable` in\n * `ful/descriptions.mjs` is the half the content uses to find the field.\n * @param {HTMLElement | null | undefined} el\n * @returns {boolean} false only when `el` is missing\n */\n describedBy(el) {\n if (!el) {\n return false;\n }\n if (!el.id) {\n el.id = Attributes.uid('ful-described');\n }\n if (!this.#descriptions.includes(el.id)) {\n this.#descriptions.push(el.id);\n }\n this.#describe();\n return true;\n }\n #describe() {\n if (!this.#described) {\n return;\n }\n const ids = [...this.#descriptions, this.#errorId].filter((id) => id);\n if (ids.length) {\n this.#described.setAttribute('aria-describedby', ids.join(' '));\n }\n }\n /**\n * Moves the focus to the `control` piece. Asked before the render, the\n * request is kept (the last one wins) and applied once the control is\n * mounted.\n * @param {FocusOptions} [options]\n */\n focus(options) {\n if (this.#control) {\n this.#control.focus(options);\n return;\n }\n this.#pendingFocus = options ?? {};\n }\n /**\n * Clears or reports one validation problem. A message sets a custom error on\n * the element internals, which makes the host match `:invalid`, renders the\n * message into the `error` piece and sets `aria-invalid=\"true\"` on the\n * `announces` piece, or on the `control` when the field announces nowhere.\n * An empty or missing message clears all three.\n *\n * Validation is the server's: the submit is sent regardless, and the form's\n * error mapping calls this with the problems that come back. It calls the\n * field with the most specific name a problem's context reaches and passes\n * the rest of the path as `context`. The base ignores `context`; a composite\n * field owning a whole subtree overrides this to route the message to the\n * inner control the path names.\n *\n * Needs the render: before it there is no error region to write to.\n * @param {string} [error] the message, empty or missing to clear\n * @param {string} [context] the path below this field's name, '' on an exact match\n */\n setCustomValidity(error, context) {\n Attributes.set(this.#announces ?? this.#control, 'aria-invalid', error ? 'true' : null);\n if (!error) {\n this.internals.setValidity({});\n this.#fieldError.innerText = '';\n return;\n }\n this.internals.setValidity({ customError: true }, ' ');\n this.#fieldError.innerText = error;\n }\n /**\n * The form the platform associated the field with, as a native control's\n * own `form`.\n * @returns {HTMLFormElement | null} null outside a form\n */\n get form() {\n return this.internals.form;\n }\n /**\n * Submits the associated form with `requestSubmit`, so constraint validation\n * and the `submit` event run as for a user's submit. The submitter is the\n * first enabled `button` or `input` of type `submit` in the form whose own\n * `form` is that form; with none the form is submitted without one. Does\n * nothing outside a form.\n */\n _requestSubmit() {\n const form = this.form;\n if (!form) {\n return;\n }\n const candidates = /** @type {NodeListOf<HTMLButtonElement|HTMLInputElement>} */ (\n form.querySelectorAll('button:not(:disabled), input:not(:disabled)')\n );\n form.requestSubmit([...candidates].find((el) => el.type === 'submit' && el.form === form));\n }\n /**\n * Dispatches the field's `change` event on the host: bubbling, not\n * cancelable, with `{ value: this.value, ...extras }` as the detail. Call it\n * for a change the user made. Every field in the library announces through this method and\n * passes no `value` key in `extras`, so a listener can rely on\n * `el.value === evt.detail.value`. The extras are spread after `value`, so a\n * `value` key among them would replace it.\n * @param {Record<string, any>} [extras] further detail keys beside `value`\n */\n _notifyChange(extras = {}) {\n this.dispatchEvent(\n new CustomEvent('change', {\n bubbles: true,\n cancelable: false,\n detail: { value: this.value, ...extras },\n }),\n );\n }\n static #LABELABLE = new Set(['BUTTON', 'INPUT', 'METER', 'OUTPUT', 'PROGRESS', 'SELECT', 'TEXTAREA']);\n /**\n * @param {Field} field\n * @param {HTMLElement} label\n * @param {HTMLElement} control\n */\n static #name(field, label, control) {\n const labelable =\n Field.#LABELABLE.has(control.tagName) && control.getAttribute('type') !== 'hidden';\n if (!labelable) {\n if (!label.id) {\n label.id = Attributes.uid('ful-label');\n }\n control.setAttribute('aria-labelledby', label.id);\n label.addEventListener('click', () => field.focus());\n return;\n }\n if (!control.id) {\n control.id = Attributes.uid('ful-control');\n }\n label.setAttribute('for', control.id);\n }\n /**\n * Whether the field's own chrome should act on a gesture. Badges, dropzones,\n * menus and labels are not form controls, so the platform does not disable\n * them: every handler on them asks this first. False while the host matches\n * `:disabled`, which covers a disabled `<fieldset>` ancestry as well as the\n * claim, or while the readonly claim holds.\n * @returns {boolean}\n */\n _interactive() {\n return !this.matches(':disabled') && !this.readonly;\n }\n /**\n * The field's value, `null` when empty. Every concrete field overrides the\n * pair with its own semantics; the form extraction, `values =` assignment,\n * the `change` detail and `formResetCallback` all go through it. The base\n * pair reads `undefined` and ignores writes.\n * @type {any}\n */\n get value() {\n return undefined;\n }\n set value(v) {}\n /**\n * Restores the declared value on a form reset, as a native control restores\n * its markup default: the current `value` attribute is decoded with the\n * element's own mapper and written through the `value` setter. A field whose\n * value is not attribute backed overrides this.\n */\n formResetCallback() {\n this.value = this.unmarshal('value', this.getAttribute('value'));\n }\n /**\n * The field's own disabled claim, which follows a native form control:\n *\n * - the `disabled` attribute on the host is the claim. Only the author writes\n * or removes it, in markup or through this property; the library never\n * claims on a form's or fieldset's behalf. A field declared disabled inside\n * a disabled `<fieldset>` stays disabled when the fieldset is re-enabled.\n * - the effective state is the claim or a disabled `<fieldset>` ancestry:\n * `:disabled` matches both, and a disabled field is left out of the\n * submitted values.\n * - the property reads the claim only: a field disabled by its ancestry reads\n * `false` while `matches(':disabled')` is true. Removing the claim inside a\n * disabled fieldset does not enable the field.\n * - writing it sets or removes the `disabled` attribute on the `claims`\n * piece (the control by default) and on every `also` control. The\n * ancestry is never written anywhere: the browser disables those controls\n * as descendants of the fieldset. A subclass setter calls super, then\n * reaches any further controls of its own.\n * @type {boolean}\n */\n get disabled() {\n return this.hasAttribute('disabled');\n }\n set disabled(d) {\n this.reflectTo('disabled', d);\n for (const el of this.#mirrors()) {\n el.toggleAttribute('disabled', d);\n }\n }\n /**\n * The readonly claim, read from the host attribute. Writing it sets\n * `readOnly` on the `claims` piece (the control by default) and on every\n * `also` control, sets `aria-readonly` on the `announces` piece, and\n * reflects the attribute. A text control stays focusable and selectable\n * with only editing off. A field whose control has no usable native\n * `readOnly` names a `freeze` piece, whose clicks are cancelled while the\n * claim holds.\n * @type {boolean}\n */\n get readonly() {\n return this.hasAttribute('readonly');\n }\n set readonly(v) {\n for (const el of this.#mirrors()) {\n el.readOnly = v;\n }\n if (this.#announces) {\n Attributes.set(this.#announces, 'aria-readonly', v ? 'true' : null);\n }\n this.reflectTo('readonly', v);\n }\n /**\n * The required claim, read from the host attribute. Writing it sets\n * `aria-required` on the `announces` piece and reflects the attribute; no\n * native `required` is set, since validation is the server's.\n * @type {boolean}\n */\n get required() {\n return this.hasAttribute('required');\n }\n set required(d) {\n if (this.#announces) {\n Attributes.set(this.#announces, 'aria-required', d ? 'true' : null);\n }\n this.reflectTo('required', d);\n }\n /**\n * Calls `_build(conf)` and wires the pieces it answers. When `_build`\n * returns a promise the pieces are wired once it settles; a field that\n * builds synchronously renders synchronously.\n * @param {{ slots: Record<string, DocumentFragment> | undefined }} conf\n * @returns {void | Promise<void>}\n */\n render(conf) {\n const built = /** @type {any} */ (this._build(conf));\n if (built instanceof Promise) {\n return built.then((pieces) => this.#wire(pieces));\n }\n this.#wire(built);\n return undefined;\n }\n /**\n * Builds the field's dom and answers the pieces the base drives, or a\n * promise of them. The one method a concrete field implements beside its\n * value pair, and the only place its dom is created. A subclass extending\n * another field's build spreads the pieces it answered and overrides the\n * keys it owns.\n *\n * - `fragment` (required) replaces the host's children.\n * - `control` (required) is the focus target of `focus()`. By default it also\n * carries the description, `aria-invalid`, `aria-readonly`,\n * `aria-required`, and the mirrored `disabled` and `readOnly`.\n * - `error` (required) is the live region `setCustomValidity` writes into.\n * It is given an id (`ful-field-error-*`) when it has none and is always\n * the last entry of the description.\n * - `label` names the control. For a labelable control (`button`, `input`\n * other than hidden, `meter`, `output`, `progress`, `select`, `textarea`)\n * the control is given an id when it has none and the label's `for`\n * points at it, so a click on the label does what it does in a plain\n * form. For any other control the label is given an id, the control's\n * `aria-labelledby` points at it, and a click on the label calls `focus()`.\n * - `described` carries `aria-describedby` in place of the control: the\n * host, for a field with no single control to describe.\n * - `claims` receives the mirrored `disabled` and `readOnly` in place of the\n * control, for a wrapper such as a `<fieldset>` the field disables as a\n * whole. Focus and the aria stay on the control.\n * - `announces` carries `aria-readonly`, `aria-required` and `aria-invalid`\n * in place of the control: the host, where the widget role lives there.\n * `null` for a field whose control has no role that accepts\n * `aria-readonly` and `aria-required`; `aria-invalid` then goes on the\n * control.\n * - `freeze` is for a field with no usable native `readOnly`: a capturing\n * click listener on it cancels the default action of every click inside\n * it while the readonly claim holds. It stays focusable and in the\n * accessibility tree.\n * - `also` are further controls that mirror `disabled` and `readOnly`\n * beside the claim target.\n *\n * The pieces are elements the field rendered itself, native controls or\n * wrappers of its own. A ful field is not one: it has no `readOnly`, its\n * host's role takes no aria, and a label's `for` names its host rather than\n * its control. A composite built from ful fields answers the inner field as\n * `control`, which forwards `focus()`, lets it render its own label with\n * `label` and `announces` null, and forwards the claims in its setters,\n * calling super first.\n * @param {{ slots: Record<string, DocumentFragment> | undefined }} conf\n * @returns {any} the pieces, or a promise of them\n * @throws {Error} when the subclass does not implement it\n */\n _build(conf) {\n throw new Error(`${this.constructor.name} must implement _build`);\n }\n}\n\nexport { Field };\n","import { Attributes, Localization, ParsedElement, Rendering } from '../../ftl/index.mjs';\nimport { Failure } from '../../httpc/index.mjs';\nimport { Bindings } from './bindings.mjs';\nimport { AsyncEvents } from '../events/async.mjs';\nimport { PageLeave } from '../events/leave.mjs';\n\n/** Sends a form's request as a json body to a url, mapping the request and the response through the configured mappers. */\nclass RemoteJsonFormLoader {\n #http;\n #url;\n #method;\n #requestMapper;\n #responseMapper;\n /**\n * @param {{ request(method: string, url: string): { json(body: any): { fetch(): Promise<any> } } }} http the `http-client` component\n * @param {string} url\n * @param {string} method\n * @param {(value: any, form: Form) => any} requestMapper\n * @param {(value: any, form: Form) => any} responseMapper\n */\n constructor(http, url, method, requestMapper, responseMapper) {\n this.#http = http;\n this.#url = url;\n this.#method = method;\n this.#requestMapper = requestMapper;\n this.#responseMapper = responseMapper;\n }\n /**\n * @param {any} values\n * @param {Form} form\n * @returns {any} what the request mapper returns\n */\n prepare(values, form) {\n return this.#requestMapper(values, form);\n }\n /**\n * @param {any} request\n * @param {Form} form\n * @returns {Promise<any>} what the client's `fetch()` resolves to: with the\n * library's client, the `Response` of a 2xx status, rejecting with an\n * `HttpClientError` (a `Failure`) otherwise\n */\n async submit(request, form) {\n return await this.#http.request(this.#method, this.#url).json(request).fetch();\n }\n /**\n * @param {any} response\n * @param {Form} form\n * @returns {any} what the response mapper returns\n */\n transform(response, form) {\n return this.#responseMapper(response, form);\n }\n}\n\n/** Submits a form without a request: the request mapper produces the result the response mapper then reads, for a form handled entirely on the page. */\nclass LocalFormLoader {\n #requestMapper;\n #responseMapper;\n /**\n * @param {(value: any, form: Form) => any} requestMapper\n * @param {(value: any, form: Form) => any} responseMapper\n */\n constructor(requestMapper, responseMapper) {\n this.#requestMapper = requestMapper;\n this.#responseMapper = responseMapper;\n }\n /**\n * @param {any} values\n * @param {Form} form\n * @returns {Promise<any>} what the request mapper returns or resolves to\n */\n async prepare(values, form) {\n return await this.#requestMapper(values, form);\n }\n /**\n * Sends nothing.\n * @param {any} request\n * @param {Form} form\n * @param {any} response what a `submit:requested` listener answered\n * @returns {Promise<any>} `response`, unchanged\n */\n async submit(request, form, response) {\n return response;\n }\n /**\n * @param {any} response\n * @param {Form} form\n * @returns {Promise<any>} what the response mapper returns or resolves to\n */\n async transform(response, form) {\n return await this.#responseMapper(response, form);\n }\n}\n\n/**\n * Builds the form's loader from its attributes: a local one when no action is\n * declared, a json post to it otherwise.\n *\n * A component registered under the `loader` attribute replaces this one and\n * must implement three methods, called in this order:\n *\n * - `prepare(values, form)` turns the extracted values into the request to send\n * - `submit(request, form, response)` performs it and returns the response. The\n * third argument is whatever a `submit:requested` listener already answered,\n * which is how a loader with nothing to send returns it unchanged\n * - `transform(response, form)` turns that response into the `response` of the\n * `submit:success` detail\n *\n * A rejection from any of the three is reported as a `submit:failure`.\n */\nclass FormLoader {\n /**\n * The `request-mapper` and `response-mapper` attributes name registry\n * components called as `(value, form)`; each defaults to the identity. A\n * remote loader sends through the `http-client` component, with the\n * `method` attribute or `POST`.\n * @param {Form} el the form submitting\n * @param {unknown} [conf] not read\n * @returns {LocalFormLoader | RemoteJsonFormLoader}\n */\n static create(el, conf) {\n const http = el.component('http-client');\n const requestMapper = el.declared('request-mapper') ? el.component(el.declared('request-mapper')) : (v) => v;\n const responseMapper = el.declared('response-mapper') ? el.component(el.declared('response-mapper')) : (v) => v;\n const url = el.declared('action');\n if (!url) {\n return new LocalFormLoader(requestMapper, responseMapper);\n }\n const method = el.declared('method') ?? 'POST';\n return new RemoteJsonFormLoader(http, url, method, requestMapper, responseMapper);\n }\n}\n\n/**\n * The form owning an element: its `form` property, or `internals.form` for a\n * form-associated element that has none. An element no form can own answers\n * undefined, its internals, which every ParsedElement holds, throwing on a\n * read of `form` unless the element is form-associated.\n * @param {any} el\n * @returns {HTMLFormElement|null|undefined}\n */\nconst ownerOf = (el) =>\n el.form !== undefined ? el.form : el.constructor?.formAssociated ? el.internals?.form : undefined;\n\n/**\n * Moves its children into a native `<form novalidate>`, extracts their values\n * on submit and hands them to a loader, reporting problems through `errors`.\n * Being `novalidate`, the form submits whatever the validity of its fields:\n * the browser does not block a submit on a field still marked invalid.\n *\n * Attributes on the host starting with `form-` are forwarded, without the\n * prefix, to the native form. `autocomplete` is copied onto the native form as\n * well and stays on the host, the fields reading it from either; a\n * `form-autocomplete` has the last word on the native form.\n * `clear-invalid-on-change` clears the custom validity of a field of this form\n * when a `change` event bubbles from it; the field's form is read from its\n * `form` property, or from `internals.form` for a form-associated element\n * that has none. `scroll-on-error` is passed to `Bindings.errors` as\n * `scrollOnError`.\n *\n * A native submit, by a button or by Enter in a field, is stopped and runs\n * `submit` instead.\n *\n * `track-changes` keeps track of the edits not saved yet (see `dirty`), and\n * `guard-leave`, which implies it, asks before the page is left while there\n * are any.\n */\nclass Form extends ParsedElement {\n /** Read once at the upgrade: changing one afterwards has no effect. */\n static attributes = [\n 'action',\n 'method',\n 'loader',\n 'request-mapper',\n 'response-mapper',\n 'clear-invalid-on-change:presence',\n 'scroll-on-error:presence',\n 'autocomplete',\n 'track-changes:presence',\n 'guard-leave:presence',\n ];\n /** The native form holding the fields, created by the render. */\n form;\n /** Builds the native form and moves the element's children into it. */\n render() {\n const form = document.createElement('form');\n this.form = form;\n form.setAttribute('novalidate', '');\n Attributes.set(form, 'autocomplete', this.declared('autocomplete'));\n Attributes.forward('form-', this, form);\n form.replaceChildren(...this.childNodes);\n form.addEventListener('submit', async (e) => {\n e.preventDefault();\n e.stopPropagation();\n await this.submit(e.submitter ?? undefined);\n });\n this.addEventListener(\n 'click',\n (evt) => {\n const target = /** @type Element */ (evt.target);\n if (!target.closest?.('[aria-disabled=\"true\"]')) {\n return;\n }\n evt.preventDefault();\n evt.stopImmediatePropagation();\n },\n true,\n );\n if (this.declared('clear-invalid-on-change')) {\n this.addEventListener('change', (/** @type any */ evt) => {\n if (ownerOf(evt.target) !== this.form) {\n return;\n }\n evt.target.setCustomValidity?.('');\n });\n }\n this.replaceChildren(form);\n this.#tracking = this.declared('track-changes') || this.declared('guard-leave');\n if (!this.#tracking) {\n return;\n }\n this.addEventListener('input', (evt) => this.#touch(evt.target));\n this.addEventListener('change', (evt) => this.#touch(evt.target));\n this.addEventListener('focusin', (evt) => this.#focus(evt.target));\n Rendering.waitForChildren(this)\n .catch(() => undefined)\n .then(() => this.commit());\n this.#guard();\n }\n connectedCallback() {\n super.connectedCallback();\n if (this.#tracking) {\n this.#guard();\n }\n }\n disconnectedCallback() {\n this.#leave?.abort();\n this.#leave = null;\n }\n #submitting = false;\n /**\n * Runs the submit pipeline, with the spinner up for its whole length:\n *\n * 1. builds the loader: the component the `loader` attribute names\n * (`loaders:form` by default), called as `create(form)`\n * 2. extracts the values with `Bindings.extractFrom` and has the loader\n * `prepare` them into the request\n * 3. fires a cancelable `submit` with `{ submitter, values, request }`.\n * Cancelling it ends the submit there, reporting nothing and leaving the\n * problems shown; a listener may replace `values` or `request` on the detail\n * 4. clears the problems shown\n * 5. fires `submit:requested` through `AsyncEvents.fireAsync` in `pipeline`\n * mode: at most one async listener, whose answer is handed to the\n * loader's `submit` as its third argument. A listener may replace\n * `request` on the detail\n * 6. has the loader `submit` the request and `transform` the response\n * 7. under `track-changes`, commits the values extracted at step 2 (see\n * `commit`): an edit made while the submit was in flight stays unsaved\n * 8. fires `submit:success` with `{ submitter, values, request, response }`,\n * `response` being the transformed one\n *\n * Anything thrown from step 1 on, a missing loader or a throwing mapper\n * included, fires `submit:failure` with `{ submitter, values, request,\n * exception }` instead; the returned promise does not reject. A `Failure`\n * has its problems shown through `errors`, anything else is logged with\n * `console.warn`. The `values` of both outcome events are the extracted\n * ones, not a replacement a `submit` listener put on its detail.\n *\n * A call while a submit is in flight returns at once, doing nothing.\n * @param {HTMLElement} [submitter] the button that submitted, if any; it is\n * the only button whose name and value are submitted\n * @returns {Promise<boolean>} settling once the submit has finished: true\n * after `submit:success`, false when it failed, was cancelled or was dropped\n * for one in flight\n */\n async submit(submitter) {\n if (this.#submitting) {\n return false;\n }\n this.#submitting = true;\n this.spinner(true);\n let values;\n let request;\n try {\n const loader = this.component(this.declared('loader') ?? 'loaders:form').create(this);\n values = Bindings.extractFrom(this.form, submitter);\n const submitted = this.#tracking ? { saved: this.#snapshot(), upTo: this.#sequence } : null;\n request = await loader.prepare(values, this);\n const se = new CustomEvent('submit', {\n bubbles: true,\n cancelable: true,\n detail: { submitter, values, request },\n });\n if (!this.dispatchEvent(se)) {\n return false;\n }\n this.errors = [];\n const sre = new CustomEvent('submit:requested', {\n bubbles: true,\n cancelable: false,\n detail: { submitter, values: se.detail.values, request: se.detail.request },\n });\n let response = await AsyncEvents.fireAsync(this, sre, { mode: 'pipeline' });\n request = sre.detail.request;\n\n response = await loader.submit(request, this, response);\n const mapped = await loader.transform(response, this);\n if (submitted) {\n this.#commitFrom(submitted.saved, submitted.upTo);\n }\n this.dispatchEvent(\n new CustomEvent('submit:success', {\n bubbles: true,\n cancelable: false,\n detail: { submitter, values, request, response: mapped },\n }),\n );\n return true;\n } catch (e) {\n this.dispatchEvent(\n new CustomEvent('submit:failure', {\n bubbles: true,\n cancelable: false,\n detail: { submitter, values, request, exception: e },\n }),\n );\n if (e instanceof Failure) {\n this.errors = e.problems;\n } else {\n console.warn('failed to submit form', this, 'reason:', e);\n }\n return false;\n } finally {\n this.#submitting = false;\n this.spinner(false);\n }\n }\n /**\n * Saves the unsaved edits, for a page action that would lose them, such as\n * one reloading the page: under `track-changes` it submits only while the\n * form is dirty, and without it always submits.\n * @param {HTMLElement} [submitter] as `submit` takes it\n * @returns {Promise<boolean>} whether no unsaved edit is left: false when\n * the submit did not succeed, or when the user edited the form while it\n * was in flight\n */\n async save(submitter) {\n if (this.#tracking && !this.dirty) {\n return true;\n }\n return (await this.submit(submitter)) && !this.dirty;\n }\n /**\n * Resets the native form, each field returning to its default value. Under\n * `track-changes` every control counts as edited: the form is dirty if the\n * defaults differ from what was last committed.\n */\n reset() {\n this.form.reset();\n if (!this.#tracking) {\n return;\n }\n for (const name of new Set([...this.#saved.keys(), ...this.#snapshot().keys()])) {\n this.#edits.set(name, ++this.#sequence);\n }\n this.#refresh();\n }\n /** name → the serialized values the last commit recorded */\n #saved = new Map();\n /** name → the serialized values when first focused, for a name the last commit did not see */\n #focused = new Map();\n /** name → the sequence number of its latest edit since the last commit */\n #edits = new Map();\n #sequence = 0;\n #wasDirty = false;\n #frame = 0;\n /** @type {AbortController|null} */\n #leave = null;\n #tracking = false;\n /**\n * Whether, under `track-changes`, a control the user edited since the last\n * commit holds a value other than the one committed. An edit is what the\n * controls report as one: an `input` or a `change` bubbling from a control\n * of this form (0019), so assigning `value`, a select's vocabulary dropping\n * a key or a section delivering its fields is not one, and an edit undone\n * is no longer dirty. A control the last commit did not see compares with\n * its value when it was first focused. Always false without\n * `track-changes`.\n *\n * While dirty, the host matches `:state(dirty)` and the submit buttons of\n * this form carry `data-ful-dirty`; a change of the state dispatches\n * `dirty:change` with `{ dirty }`. Both are refreshed at the next frame\n * after an edit, while the property is exact at any time.\n * @returns {boolean}\n */\n get dirty() {\n if (!this.#tracking) {\n return false;\n }\n for (const name of this.#edits.keys()) {\n const now = this.#valuesOf(name);\n if (!this.#saved.has(name) && now === '[]') {\n continue;\n }\n const was = this.#saved.get(name) ?? this.#focused.get(name);\n if (was !== now) {\n return true;\n }\n }\n return false;\n }\n /**\n * Records the values of the controls as saved, so that the form is no\n * longer dirty. A submit commits by itself on success, and the form\n * commits once its fields have rendered: a page calls this for a save of\n * its own, or after writing the values it loaded. Does nothing without\n * `track-changes`.\n */\n commit() {\n if (this.#tracking) {\n this.#commitFrom(this.#snapshot(), this.#sequence);\n }\n }\n /**\n * Counts controls as edited by the user, for values the page writes on\n * the user's behalf: assigning `value` reports nothing, as 0019 wants.\n * @param {...Element} els each a control, or an element inside one\n */\n edited(...els) {\n for (const el of els) {\n this.#touch(el);\n }\n }\n /**\n * @param {Map<string, string>} saved\n * @param {number} upTo the sequence number of the latest edit the values include\n */\n #commitFrom(saved, upTo) {\n this.#saved = saved;\n for (const [name, sequence] of this.#edits) {\n if (sequence <= upTo) {\n this.#edits.delete(name);\n }\n }\n for (const name of this.#focused.keys()) {\n if (saved.has(name)) {\n this.#focused.delete(name);\n }\n }\n this.#refresh();\n }\n /**\n * The named control of this form `target` is or sits in, if any: a field's\n * inner control is unnamed or carries `form=\"\"`, a control of a form nested\n * in this one, like a table's filters, belongs to that form, and a\n * form-associated element with no `form` property answers its owner\n * through `internals.form`.\n * @param {any} target\n * @returns {string|null} its name\n */\n #nameOf(target) {\n for (let el = target; el && el !== this; el = el.parentElement) {\n if (ownerOf(el) === this.form && el.hasAttribute('name')) {\n return el.getAttribute('name');\n }\n }\n return null;\n }\n /** @param {EventTarget|null} target */\n #touch(target) {\n if (!this.#tracking) {\n return;\n }\n const name = this.#nameOf(target);\n if (name === null) {\n return;\n }\n this.#edits.set(name, ++this.#sequence);\n if (this.#frame === 0) {\n this.#frame = requestAnimationFrame(() => this.#refresh());\n }\n }\n /** @param {EventTarget|null} target */\n #focus(target) {\n const name = this.#nameOf(target);\n if (name !== null && !this.#saved.has(name) && !this.#focused.has(name)) {\n this.#focused.set(name, this.#valuesOf(name));\n }\n }\n /**\n * The controls that contribute to the values, as `Bindings.extractFrom`\n * reads them, with no submitter.\n * @returns {any[]}\n */\n #contributing() {\n return Array.from(this.form.elements).filter(\n (el) =>\n el.hasAttribute('name') &&\n !['submit', 'reset', 'button'].includes(/** @type {any} */ (el).type) &&\n !el.matches(':disabled'),\n );\n }\n /** @returns {Map<string, string>} each name to its serialized values */\n #snapshot() {\n /** @type {Map<string, any[]>} */\n const values = new Map();\n for (const el of this.#contributing()) {\n const name = el.getAttribute('name');\n values.set(name, [...(values.get(name) ?? []), Bindings.extract(el)]);\n }\n return new Map(Array.from(values, ([name, vs]) => [name, JSON.stringify(vs)]));\n }\n /**\n * @param {string} name\n * @returns {string} the serialized values of the controls carrying it\n */\n #valuesOf(name) {\n return JSON.stringify(\n this.#contributing()\n .filter((el) => el.getAttribute('name') === name)\n .map((el) => Bindings.extract(el)),\n );\n }\n #refresh() {\n cancelAnimationFrame(this.#frame);\n this.#frame = 0;\n const dirty = this.dirty;\n this.querySelectorAll('button').forEach((el) => {\n const button = /** @type HTMLButtonElement */ (el);\n if (button.form === this.form && button.type === 'submit') {\n button.toggleAttribute('data-ful-dirty', dirty);\n }\n });\n if (dirty === this.#wasDirty) {\n return;\n }\n this.#wasDirty = dirty;\n if (dirty) {\n this.internals.states.add('dirty');\n } else {\n this.internals.states.delete('dirty');\n }\n this.dispatchEvent(\n new CustomEvent('dirty:change', {\n bubbles: true,\n cancelable: false,\n detail: { dirty },\n }),\n );\n }\n #guard() {\n if (!this.declared('guard-leave') || this.#leave) {\n return;\n }\n this.#leave = new AbortController();\n PageLeave.guard(() => this.dirty, this.#leave.signal);\n }\n #spinning = 0;\n /**\n * @param {HTMLElement} el\n */\n #announce(el) {\n Attributes.defaultValue(el, 'role', 'status');\n el.hidden = false;\n if (el.textContent.trim() !== '') {\n return;\n }\n const label = document.createElement('span');\n label.className = 'ful-sr-only';\n label.dataset.ref = 'spinner-label';\n el.append(label);\n label.textContent = Localization.of().t('spinner.loading');\n }\n /**\n * Marks the form busy or releases it. Calls nest: only the first\n * `spinner(true)` and the matching last `spinner(false)` act, so a caller's\n * own spin may wrap a submit.\n *\n * Busy, the host carries `aria-busy=\"true\"` and each `ful-spinner` of this\n * form is revealed; one without text of its own is given `role=\"status\"`\n * (unless it has a role) and a visually hidden localized `spinner.loading`\n * label. Each submit and reset button of this form is held off with\n * `aria-disabled=\"true\"`, keeping its focus, and a click on it is refused\n * ahead of any listener on the button. Holding the buttons off does not\n * stop a programmatic `submit`.\n *\n * Released, the spinners are hidden and lose the label they were given, and\n * each held button gets back the `aria-disabled` it had. A button that\n * joined the form while it was busy keeps its own state.\n * @param {boolean} spin\n */\n spinner(spin) {\n if (spin) {\n ++this.#spinning;\n if (this.#spinning !== 1) {\n return;\n }\n } else {\n this.#spinning = Math.max(0, this.#spinning - 1);\n if (this.#spinning !== 0) {\n return;\n }\n }\n Attributes.set(this, 'aria-busy', spin ? 'true' : null);\n this.querySelectorAll('ful-spinner').forEach((el) => {\n if (el.closest('form') !== this.form) {\n return;\n }\n const hel = /** @type HTMLElement */ (el);\n if (spin) {\n this.#announce(hel);\n return;\n }\n hel.hidden = true;\n hel.querySelector(':scope > [data-ref=spinner-label]')?.remove();\n });\n this.querySelectorAll('input,button').forEach((el) => {\n const hel = /** @type HTMLButtonElement|HTMLInputElement */ (el);\n if (hel.form !== this.form || (hel.type !== 'submit' && hel.type !== 'reset')) {\n return;\n }\n if (spin) {\n hel.dataset.wd = hel.getAttribute('aria-disabled') ?? '';\n hel.setAttribute('aria-disabled', 'true');\n } else {\n if (hel.dataset.wd === undefined) {\n return;\n }\n Attributes.set(hel, 'aria-disabled', hel.dataset.wd || null);\n delete hel.dataset.wd;\n }\n });\n }\n /**\n * Writes a nested object onto the fields of this form through\n * `Bindings.mutateIn`: fields the object does not name keep their values.\n * @param {{ [x: string]: any; }} vs\n */\n set values(vs) {\n Bindings.mutateIn(this.form, vs);\n }\n /**\n * The fields of this form read into a nested object by\n * `Bindings.extractFrom`, with no submitter, so no button contributes.\n * @returns {any}\n */\n get values() {\n return Bindings.extractFrom(this.form);\n }\n /**\n * Shows problems through `Bindings.errors`, replacing the ones shown\n * before: each is pinned to the field it names, and the rest go to the\n * form's `ful-errors` banners. An empty array clears them.\n * @param {{ type: string; context?: string | null; reason: string; }[]} es\n */\n set errors(es) {\n Bindings.errors(this.form, es, this.declared('scroll-on-error'));\n }\n}\n\nexport { FormLoader, Form };\n","import { Attributes, BoundedCache } from '../../ftl/index.mjs';\nimport { Field } from './field.mjs';\n\nconst patternCache = new BoundedCache(100);\nconst compiled = (attr, pattern) =>\n patternCache.getOrCompute(`${attr}:${pattern}`, () => {\n try {\n return new RegExp(pattern, 'g');\n } catch (/** @type any */ e) {\n console.warn(`invalid ${attr} attribute`, pattern, e);\n return null;\n }\n });\n\nconst inheritedAutocomplete = (el) => el.closest('form')?.getAttribute('autocomplete') ?? null;\n\nconst INPUT_MODES = { numeric: 'numeric', decimal: 'decimal' };\n\nconst SEGMENTED = new Set(['date', 'time', 'datetime-local', 'month', 'week']);\n\nconst signed = (v, digits) => (v.startsWith('-') ? '-' : '') + digits(v);\n\nconst NUMERIC_DIGITS = {\n numeric: (t) => t.replace(/\\D/g, ''),\n decimal: (t) => {\n const kept = t.replace(/[^\\d.,]/g, '');\n const at = kept.search(/[.,]/);\n return at === -1 ? kept : kept.slice(0, at + 1) + kept.slice(at + 1).replace(/[.,]/g, '');\n },\n};\n\nconst numericFilter = (type, unsigned) => {\n const digits = NUMERIC_DIGITS[type];\n if (!digits) {\n return null;\n }\n return unsigned ? digits : (v) => signed(v, digits);\n};\n\nconst filterOf = (el) => {\n const keep = el.declared('keep');\n const reject = el.declared('reject');\n if (keep !== null && reject !== null) {\n console.warn('a ful-input declares both keep and reject: keep is applied, reject is ignored', el);\n }\n if (keep !== null) {\n const re = compiled('keep', keep);\n return re && ((v) => (v.match(re) ?? []).join(''));\n }\n if (reject !== null) {\n const re = compiled('reject', reject);\n return re && ((v) => v.replace(re, ''));\n }\n return numericFilter(el._type(), el.declared('unsigned'));\n};\n\n/**\n * A labelled text input over any native input type, or a `<textarea>` under\n * `type=\"textarea\"`; the temporal inputs are its subclasses. The label is the\n * default slot, `info` follows it, and `before` and `after` are rendered as\n * affixes around the control. Every `input-*` attribute is forwarded onto the\n * control, after everything the field sets there, so it has the last word.\n *\n * `type`, `v-type`, `keep`, `reject`, `uppercase`, `trim`, `unsigned` and\n * `autocomplete` are configuration: read once at the upgrade, so a later write\n * to them changes nothing. `placeholder` stays live.\n *\n * - `type=\"numeric\"` and `type=\"decimal\"` render a text input carrying that\n * `inputmode`, so the native `min`, `max` and `step` do not apply. Typing is\n * filtered to digits and a leading minus; a decimal also keeps its first `.`\n * or `,` and drops any later one; `unsigned` drops the minus.\n * - `keep` and `reject` are regular expressions filtering what is typed:\n * `keep` leaves every match, concatenated, and `reject` removes every match.\n * Either replaces the type's own filter, and `keep` wins over `reject` with a\n * warning. A pattern that does not compile is warned about once and filters\n * nothing. The caret stays next to the same character when text before it\n * is removed.\n * - `autocomplete` is put on the control. Without one the field takes the\n * `autocomplete` attribute of the nearest enclosing `<form>`, which the\n * platform does not pass on because the control carries `form=\"\"`.\n * - `uppercase`, `trim` and `v-type` shape the value as it is read; see `value`.\n * - The control's native `change` is stopped and the field dispatches its own\n * once the user commits a new value, as a text input does. A date, time,\n * datetime-local, month or week control fires its native `change` while its\n * segments are typed, as soon as they make a valid value; for those the field\n * reports when the control is left or Enter is pressed, at once for a value\n * picked from the browser's picker, never with the dates a year passes\n * through while it is typed. A control left incomplete reads as `null`, as\n * the native one does.\n *\n * A subclass template may render more than one control, as the compare filters\n * render the two bounds of a range: the first is `_input`, the one the field is\n * named by, and every one of them gets the inputmode, `autocomplete`, the\n * `input-` passthrough, the keystroke filter, the placeholder and the `change`\n * reporting. The passthrough leaves `input-id` to the first alone, so no\n * two controls share an id.\n */\nclass Input extends Field {\n /** @type {string[]} */\n static observed = ['placeholder'];\n /** @type {string[]} */\n static attributes = [\n 'type',\n 'v-type',\n 'keep',\n 'reject',\n 'uppercase:presence',\n 'trim:presence',\n 'unsigned:presence',\n 'autocomplete',\n ];\n static slots = true;\n static template = `\n <label>{{{{ slots.default }}}}</label>\n {{{{ slots.info }}}}\n <ful-control-group>\n <ful-affix data-tpl-if=\"slots.before\">{{{{ slots.before }}}}</ful-affix>\n <input data-tpl-if=\"type != 'textarea'\" data-tpl-type=\"type\" placeholder=\" \" form=\"\">\n <textarea data-tpl-if=\"type == 'textarea'\" placeholder=\" \" form=\"\"></textarea>\n <ful-affix data-tpl-if=\"slots.after\">{{{{ slots.after }}}}</ful-affix>\n </ful-control-group>\n <ful-field-error></ful-field-error>\n `;\n /**\n * The inner control, set by `_build`: the `<input>`, or the `<textarea>`\n * under `type=\"textarea\"`. A subclass reads and writes it for the\n * attributes it adds. Typed `any` so that a subclass can treat it as the\n * one of the two it renders.\n * @type {any}\n */\n _input;\n /** @type {(HTMLInputElement|HTMLTextAreaElement)[]} */\n #controls = [];\n /**\n * The type the field renders, which a subclass overrides to wrap another\n * native type. The base answers the declared `type`, else `number` under\n * `v-type=\"number\"`, else `text`. It is also what selects the keystroke\n * filter of `numeric` and `decimal` and the separator handling of `value`.\n * @returns {string}\n */\n _type() {\n return this.declared('type') ?? (this.declared('v-type') === 'number' ? 'number' : 'text');\n }\n /**\n * @param {{ slots: Record<string, DocumentFragment> | undefined }} conf\n * @returns {{fragment: DocumentFragment, control: any, error: Element | null, label: HTMLLabelElement | null}}\n */\n _build({ slots }) {\n const declared = this._type();\n const mode = INPUT_MODES[declared];\n const type = mode ? 'text' : declared;\n const fragment = this.template().withOverlay({ type, slots }).render();\n this.#controls = /** @type {(HTMLInputElement|HTMLTextAreaElement)[]} */ ([\n ...fragment.querySelectorAll(':is(ful-control-group, ful-control) > :is(input, textarea)'),\n ]);\n this._input = this.#controls[0];\n const autocomplete = this.declared('autocomplete') ?? inheritedAutocomplete(this);\n const strip = filterOf(this);\n for (const control of this.#controls) {\n this.#configure(control, mode, autocomplete, strip);\n }\n return {\n fragment,\n control: this._input,\n error: fragment.querySelector('ful-field-error'),\n label: fragment.querySelector('label'),\n };\n }\n /**\n * @param {HTMLInputElement|HTMLTextAreaElement} control\n * @param {string|undefined} mode the inputmode the type names\n * @param {string|null} autocomplete\n * @param {((text: string) => string)|null} strip the keystroke filter\n */\n #configure(control, mode, autocomplete, strip) {\n if (mode) {\n Attributes.set(control, 'inputmode', mode);\n }\n Attributes.set(control, 'autocomplete', autocomplete);\n const id = control.id;\n Attributes.forward('input-', this, control);\n if (control !== this._input) {\n Attributes.set(control, 'id', id || null);\n }\n this.#reportChanges(control);\n control.addEventListener('input', () => {\n if (!strip) {\n return;\n }\n const before = control.value;\n const after = strip(before);\n if (before === after) {\n return;\n }\n const start = control.selectionStart;\n control.value = after;\n if (start === null) {\n return;\n }\n const caret = strip(before.slice(0, start)).length;\n control.setSelectionRange(caret, caret);\n });\n }\n /** @param {HTMLInputElement|HTMLTextAreaElement} control */\n #reportChanges(control) {\n if (!SEGMENTED.has(control.type)) {\n control.addEventListener('change', (evt) => {\n evt.stopPropagation();\n this._notifyChange();\n });\n return;\n }\n /** @type {string|null} */\n let committed = null;\n let typed = false;\n const commit = () => {\n typed = false;\n const now = JSON.stringify(this.value);\n if (now === committed) {\n return;\n }\n committed = now;\n this._notifyChange();\n };\n control.addEventListener('focus', () => {\n committed = JSON.stringify(this.value);\n });\n control.addEventListener('keydown', (/** @type any */ evt) => {\n if (evt.key === 'Enter' && !evt.isComposing) {\n commit();\n return;\n }\n typed = true;\n });\n control.addEventListener('blur', commit);\n control.addEventListener('change', (evt) => {\n evt.stopPropagation();\n if (!typed) {\n commit();\n }\n });\n }\n /**\n * The control's text, shaped in this order: upper cased under `uppercase`,\n * trimmed under `trim`, `null` when that leaves it empty, every `,` read as\n * `.` for `type=\"decimal\"`, and decoded to a number under\n * `v-type=\"number\"`, where text that does not decode is answered as it is.\n * Writing `null`, `undefined` or `''` empties the control; anything else is\n * written as its string, replacing whatever was being typed, as a native\n * control's value does. Answers a `string`, a `number` or `null`; typed\n * `any` because subclasses answer other values.\n * @type {any}\n */\n get value() {\n const uppercase = this.declared('uppercase');\n const trim = this.declared('trim');\n const v = this._input.value;\n const uppercased = uppercase ? v.toUpperCase() : v;\n const trimmed = trim ? uppercased.trim() : uppercased;\n if (trimmed === '') {\n return null;\n }\n const normalized = this._type() === 'decimal' ? trimmed.replaceAll(',', '.') : trimmed;\n if (this.declared('v-type') === 'number') {\n const n = Number(normalized);\n return Number.isNaN(n) ? normalized : n;\n }\n return normalized;\n }\n set value(value) {\n this._input.value = value === '' || value === undefined || value === null ? '' : `${value}`;\n }\n /**\n * The control's placeholder, `null` when there is none. The control always\n * carries one, a single space standing in for none, so `:placeholder-shown`\n * matches an empty control and a floating label can rely on it; the blank\n * one is neither answered here nor reflected onto the host.\n * @type {string | null}\n */\n get placeholder() {\n const v = this._input.getAttribute('placeholder');\n return v === ' ' ? null : v;\n }\n set placeholder(d) {\n for (const control of this.#controls) {\n Attributes.set(control, 'placeholder', d ?? ' ');\n }\n this.reflectTo('placeholder', d);\n }\n}\n\nexport { Input };\n","import { ParsedElement, Localization } from '../../ftl/index.mjs';\nimport { Input } from './input.mjs';\n\nconst blankAsNull = (v) => (v === '' ? null : v);\n\n/**\n * Formats the yyyy-mm-dd date in its content as a numeric date, in the locale\n * its `locale` attribute names, else the page's, else the platform default.\n * Blank content, or content that does not name a date, renders the `default`\n * attribute, or nothing without one.\n */\nclass LocalDate extends ParsedElement {\n static attributes = ['locale', 'default'];\n render() {\n const content = this.textContent.trim();\n const [y, m, d] = content.split('-').map(Number);\n const parsed = content === '' ? null : new Date(y, m - 1, d);\n if (parsed === null || Number.isNaN(parsed.getTime())) {\n this.replaceChildren(this.declared('default') ?? '');\n return;\n }\n const { date } = Localization.of({ locale: this.declared('locale') ?? undefined });\n this.replaceChildren(date(parsed, { year: 'numeric', month: 'numeric', day: 'numeric' }));\n }\n}\n\n/**\n * Formats the ISO instant in its content as a numeric date and 24 hour time\n * with seconds, in the page's timezone and in the locale chosen as ful-local-date\n * chooses it. Blank content, or content that does not name an instant, renders\n * the `default` attribute, or nothing without one. A date-only value is read as\n * local midnight of that day.\n */\nclass Instant extends ParsedElement {\n static attributes = ['locale', 'default'];\n render() {\n const content = this.textContent.trim();\n const parsed = content === '' ? null : new Date(Instant.isoToLocal(content));\n if (parsed === null || Number.isNaN(parsed.getTime())) {\n this.replaceChildren(this.declared('default') ?? '');\n return;\n }\n const { date } = Localization.of({ locale: this.declared('locale') ?? undefined });\n this.replaceChildren(\n date(parsed, {\n year: 'numeric',\n month: 'numeric',\n day: 'numeric',\n hour: 'numeric',\n minute: 'numeric',\n second: 'numeric',\n hour12: false,\n }),\n );\n }\n static #parse(v) {\n return /^\\d{4}-\\d{2}-\\d{2}$/.test(v) ? new Date(`${v}T00:00:00`) : new Date(v);\n }\n /**\n * Converts an ISO instant to the `yyyy-mm-ddThh:mm:ss.sss` wall clock time\n * a datetime-local input takes, in the page's timezone. A date-only value is\n * read as local midnight of the day it names, not as UTC midnight.\n * @param {string} iso\n * @returns {string} with NaN fields for a value that does not parse\n */\n static isoToLocal(iso) {\n const d = Instant.#parse(iso);\n const pad = (n, v) => String(v).padStart(n, '0');\n const date = `${d.getFullYear()}-${pad(2, d.getMonth() + 1)}-${pad(2, d.getDate())}`;\n const time = `${pad(2, d.getHours())}:${pad(2, d.getMinutes())}:${pad(2, d.getSeconds())}.${pad(3, d.getMilliseconds())}`;\n return `${date}T${time}`;\n }\n /**\n * Converts a datetime-local wall clock time in the page's timezone to a UTC\n * ISO instant. A date-only value is read as local midnight of that day.\n * @param {string} local\n * @returns {string|null} null for a value that does not parse\n */\n static localToIso(local) {\n const d = Instant.#parse(local);\n return Number.isNaN(d.getTime()) ? null : d.toISOString();\n }\n}\n\n/**\n * A date input whose `min` and `max` accept a yyyy-mm-dd date, `now` for\n * today, or an offset from today such as `+1d`, `-2m` or `+1y` (days, months,\n * years). A month offset landing past the end of the target month takes its\n * last day. Anything else is passed to the input unchanged. The `step`\n * attribute is applied before `min` and `max`.\n */\nclass InputLocalDate extends Input {\n static observed = ['step', 'min', 'max'];\n _type() {\n return 'date';\n }\n /**\n * The resolved lower bound, a yyyy-mm-dd date or whatever the input was given.\n * @returns {string|null} null when unset\n */\n get min() {\n return blankAsNull(this._input.min);\n }\n /** @param {string|null} v a date, `now` or an offset; null or blank removes the bound */\n set min(v) {\n this._input.min = InputLocalDate.#fromIsoOrOffset(v);\n }\n /**\n * The resolved upper bound, a yyyy-mm-dd date or whatever the input was given.\n * @returns {string|null} null when unset\n */\n get max() {\n return blankAsNull(this._input.max);\n }\n /** @param {string|null} v a date, `now` or an offset; null or blank removes the bound */\n set max(v) {\n this._input.max = InputLocalDate.#fromIsoOrOffset(v);\n }\n /**\n * The input's native step, in days on a date input and in seconds on a time input.\n * @returns {string|null} null when unset\n */\n get step() {\n return blankAsNull(this._input.step);\n }\n /** @param {string|null} v */\n set step(v) {\n this._input.step = v ?? '';\n }\n static #fromIsoOrOffset(v) {\n if (!v) {\n return '';\n }\n const formatLocalDate = (date) =>\n new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().split('T')[0];\n if (v === 'now') {\n return formatLocalDate(new Date());\n }\n const re = /^([+-])(\\d+)([dmy])$/;\n const match = re.exec(v);\n if (!match) {\n return v;\n }\n const sign = match[1] === '-' ? -1 : 1;\n const offset = +match[2];\n const r = new Date();\n r.setHours(0, 0, 0, 0);\n switch (match[3]) {\n case 'd':\n r.setDate(r.getDate() + offset * sign);\n break;\n case 'm': {\n const originalDay = r.getDate();\n r.setMonth(r.getMonth() + offset * sign);\n if (r.getDate() !== originalDay) {\n r.setDate(0);\n }\n break;\n }\n case 'y':\n r.setFullYear(r.getFullYear() + offset * sign);\n break;\n }\n return formatLocalDate(r);\n }\n}\n\n/**\n * A time input whose `min` and `max` accept a hh:mm time, `now`, or an offset\n * from now such as `+2h` or `-30m` (hours, minutes: `m` is minutes here, not\n * months), wrapping around midnight. A bound resolved from `now` or an offset\n * is floored to the `step` grid (60 seconds when unset), so that the values\n * on the grid stay valid, and carries seconds only when the step is not whole\n * minutes. A literal bound, and anything else, is passed to the input unchanged.\n */\nclass InputLocalTime extends InputLocalDate {\n _type() {\n return 'time';\n }\n /**\n * The resolved lower bound, a time or whatever the input was given.\n * @returns {string|null} null when unset\n */\n get min() {\n return blankAsNull(this._input.min);\n }\n /** @param {string|null} v a time, `now` or an offset; null or blank removes the bound */\n set min(v) {\n this._input.min = this.#fromNowOrOffset(v);\n }\n /**\n * The resolved upper bound, a time or whatever the input was given.\n * @returns {string|null} null when unset\n */\n get max() {\n return blankAsNull(this._input.max);\n }\n /** @param {string|null} v a time, `now` or an offset; null or blank removes the bound */\n set max(v) {\n this._input.max = this.#fromNowOrOffset(v);\n }\n #fromNowOrOffset(v) {\n if (!v) {\n return '';\n }\n const resolved = new Date();\n if (v !== 'now') {\n const re = /^([+-])(\\d+)([hm])$/;\n const match = re.exec(v);\n if (!match) {\n return v;\n }\n const sign = match[1] === '-' ? -1 : 1;\n const offset = +match[2] * sign;\n if (match[3] === 'h') {\n resolved.setHours(resolved.getHours() + offset);\n } else {\n resolved.setMinutes(resolved.getMinutes() + offset);\n }\n }\n return InputLocalTime.#snapped(resolved, Number(this._input.step) || 60);\n }\n static #snapped(date, stepSeconds) {\n const pad = (n) => String(n).padStart(2, '0');\n const seconds = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds();\n const snapped = Math.floor(seconds / stepSeconds) * stepSeconds;\n const hh = pad(Math.floor(snapped / 3600));\n const mm = pad(Math.floor((snapped % 3600) / 60));\n return stepSeconds % 60 === 0 ? `${hh}:${mm}` : `${hh}:${mm}:${pad(snapped % 60)}`;\n }\n}\n\n/**\n * A datetime-local input whose value and bounds are read and written as UTC\n * ISO instants, shown as wall clock time in the page's timezone. A date-only\n * value is read as local midnight of that day.\n */\nclass InputInstant extends Input {\n static observed = ['step', 'min', 'max'];\n _type() {\n return 'datetime-local';\n }\n /**\n * The entered time as a UTC ISO instant.\n * @returns {string|null} null when empty or when the input holds text that does not parse\n */\n get value() {\n return Instant.localToIso(this._input.value);\n }\n /** @param {string|null|undefined} v an ISO instant; a falsy value empties the input */\n set value(v) {\n super.value = v ? Instant.isoToLocal(v) : '';\n }\n /**\n * The lower bound as a UTC ISO instant.\n * @returns {string|null} null when unset\n */\n get min() {\n return Instant.localToIso(this._input.min);\n }\n /** @param {string|null} v an ISO instant; a falsy value removes the bound */\n set min(v) {\n this._input.min = v ? Instant.isoToLocal(v) : '';\n }\n /**\n * The upper bound as a UTC ISO instant.\n * @returns {string|null} null when unset\n */\n get max() {\n return Instant.localToIso(this._input.max);\n }\n /** @param {string|null} v an ISO instant; a falsy value removes the bound */\n set max(v) {\n this._input.max = v ? Instant.isoToLocal(v) : '';\n }\n /**\n * The input's native step, in seconds.\n * @returns {string|null} null when unset\n */\n get step() {\n return blankAsNull(this._input.step);\n }\n /** @param {string|null} v */\n set step(v) {\n this._input.step = v ?? '';\n }\n}\n\nexport { Instant, LocalDate, InputLocalDate, InputLocalTime, InputInstant };\n","import { Fragments, Localization, Templates } from '../../ftl/index.mjs';\nimport { Input } from './input.mjs';\n\n/**\n * A file input with an optional dropzone and item list, enforcing the type,\n * size and count limits it declares.\n *\n * The `dropzone` and `item-list` attributes show the dropzone and the list of\n * chosen files. A `dropzone` slot replaces the default dropzone's content, and\n * an `items` slot holding a template replaces the stock item, rendered with the\n * same `files` overlay so that it reads the File objects it lists. Clicking the\n * dropzone opens the picker, and the host carries a `dragover` attribute while\n * a drag hovers it. A drop selects the files it carries, ignoring entries that\n * are not files; a drop with no file, or with several on a field that is not\n * `multiple`, changes nothing.\n *\n * Every selection, picked, dropped or assigned, goes through the constraints\n * in order: `accept` and `max-file-size` drop the files they refuse,\n * `max-total-size` and `max-files` clear the whole selection. Each violation\n * shows a warning. The change event fires for a pick, a drop and a removal\n * through an item's button; the `files`, `file` and `value` setters are silent,\n * like a native input's.\n *\n * While disabled or readonly, the picker, the dropzone and the item removals\n * do nothing, and a drop still does not reach the browser's default handling.\n */\nclass InputFile extends Input {\n /**\n * Milliseconds a warning stays before the field removes it, whether or not\n * its css animation ran; read each time a warning is shown.\n * @type {number}\n */\n static WARNING_TIMEOUT = 5000;\n /**\n * Builds a FileList holding exactly these files, the form `files` takes.\n * @param {Iterable<File>} [files]\n * @returns {FileList}\n */\n static list(files = []) {\n const dt = new DataTransfer();\n for (const file of files) {\n dt.items.add(file);\n }\n return dt.files;\n }\n static observed = [\n 'placeholder',\n 'accept:csv',\n 'multiple:presence',\n 'item-list:presence',\n 'dropzone:presence',\n 'max-files:number',\n 'max-file-size:number',\n 'max-total-size:number',\n 'value',\n ];\n #accept;\n #items;\n #dropzone;\n #warnings;\n #group;\n _type() {\n return 'file';\n }\n static template = `\n <label>{{{{ slots.default }}}}</label>\n {{{{ slots.info }}}}\n <ful-control-group>\n <ful-affix data-tpl-if=\"slots.before\">{{{{ slots.before }}}}</ful-affix>\n <input data-tpl-type=\"type\" placeholder=\" \" form=\"\">\n <ful-affix data-tpl-if=\"slots.after\">{{{{ slots.after }}}}</ful-affix>\n </ful-control-group>\n <div data-ref=\"dropzone\" class=\"dropzone\" data-tpl-if=\"slots.dropzone\">\n {{{{ slots.dropzone }}}}\n </div>\n <div data-ref=\"dropzone\" class=\"default-dropzone\" data-tpl-if=\"!slots.dropzone\">\n {{ #l10n:t('files.dropzone-label') }}\n </div>\n <ful-item-list></ful-item-list>\n <ful-field-warnings role=\"status\" aria-live=\"polite\"></ful-field-warnings>\n <ful-field-error></ful-field-error>\n `;\n static templates = {\n items: `\n <ful-item data-tpl-each=\"files\" data-tpl-var=\"file\" data-tpl-data-name=\"file.name\">\n <div><span>{{ file.name }}</span><span>{{ #l10n:bytes(file.size) }}</span><button type=\"button\" data-tpl-aria-label=\"#l10n:t('files.remove')\"><ful-icon name=\"x-lg\" aria-hidden=\"true\"></ful-icon></button></div>\n </ful-item>\n `,\n warning: `<ful-field-warning>{{ #l10n:t(key, args) }}</ful-field-warning>`,\n };\n #itemstemplate;\n _build(conf) {\n const pieces = super._build(conf);\n const fragment = pieces.fragment;\n this.#items = fragment.querySelector('ful-item-list');\n this.#itemstemplate =\n conf.slots?.items && !Fragments.isBlank(conf.slots.items) ? Templates.fromFragment(conf.slots.items) : null;\n this.#dropzone = fragment.querySelector('[data-ref=dropzone]');\n this.#warnings = fragment.querySelector('ful-field-warnings');\n this.#group = fragment.querySelector('ful-control-group');\n this.#warnings.addEventListener('animationend', (e) => {\n e.target.remove();\n });\n this.#items.addEventListener('click', (e) => {\n if (!e.target.closest('button')) {\n return;\n }\n if (!this._interactive()) {\n return;\n }\n const idx = [...this.#items.children].indexOf(e.target.closest('ful-item'));\n if (idx === -1) {\n return;\n }\n this.files = InputFile.list([...this.files].filter((f, i) => i !== idx));\n this._notifyChange();\n });\n this.#dropzone.addEventListener('click', (e) => {\n if (!this._interactive()) {\n return;\n }\n this._input.click();\n });\n\n this.#dropzone.addEventListener('dragover', (e) => {\n e.preventDefault();\n this.toggleAttribute('dragover', true);\n });\n this.#dropzone.addEventListener('dragleave', () => {\n this.toggleAttribute('dragover', false);\n });\n this.#dropzone.addEventListener('drop', (e) => {\n e.preventDefault();\n this.toggleAttribute('dragover', false);\n if (!this._interactive()) {\n return;\n }\n const dropped = [...e.dataTransfer.items].filter((i) => i.kind === 'file');\n const files = dropped.map((i) => i.getAsFile()).filter((f) => f !== null);\n if (files.length === 0 || (files.length > 1 && !this.multiple)) {\n return;\n }\n this.files = InputFile.list(files);\n this._notifyChange();\n });\n this._input.addEventListener('change', (e) => {\n this.#update();\n });\n return { ...pieces, freeze: this.#group };\n }\n #update() {\n this.setCustomValidity();\n this.#warnings.replaceChildren();\n this.#ensureAcceptable();\n this.#ensureFileSizes();\n this.#ensureTotalSize();\n this.#ensureFilesCount();\n (this.#itemstemplate ?? this.template('items')).withOverlay({ files: this.files }).renderTo(this.#items);\n }\n /**\n * Shows a warning in the field's polite live region: the localized message\n * for an l10n key and its arguments. It is removed when its animation ends,\n * or after `WARNING_TIMEOUT` milliseconds at the latest. The warnings are\n * cleared whenever the selection changes.\n * @param {string} key\n * @param {Record<string, any>} [args]\n */\n warning(key, args) {\n this.template('warning').withOverlay({ key, args }).appendTo(this.#warnings);\n const warning = /** @type HTMLElement */ (this.#warnings.lastElementChild);\n setTimeout(() => warning.remove(), InputFile.WARNING_TIMEOUT);\n }\n #acceptable(file) {\n const name = file.name.toLowerCase();\n return this.#accept.some((token) => {\n const t = token.toLowerCase().split(';')[0].trim();\n if (t.startsWith('.')) {\n return name.endsWith(t);\n }\n if (t.endsWith('/*')) {\n return file.type.startsWith(`${t.slice(0, -1)}`);\n }\n return t.includes('/') && file.type === t;\n });\n }\n #ensureAcceptable() {\n if (!this.#accept.length) {\n return;\n }\n const unacceptable = [...this.files].filter((file) => !this.#acceptable(file));\n\n if (unacceptable.length === 0) {\n return;\n }\n this.warning('files.unacceptable-file-type', { types: this.#accept.join(', ') });\n this._input.files = InputFile.list([...this.files].filter((f) => !unacceptable.includes(f)));\n }\n #ensureFilesCount() {\n if (this.#maxFiles === null) {\n return;\n }\n if (this.files.length <= this.#maxFiles) {\n return;\n }\n this.warning('files.max-files-exceeded', { count: this.#maxFiles });\n this._input.files = InputFile.list();\n }\n\n #ensureFileSizes() {\n if (this.#maxFileSize === null) {\n return;\n }\n const oversized = [...this.files].filter((file) => file.size > this.#maxFileSize);\n if (oversized.length === 0) {\n return;\n }\n this.warning('files.max-file-size-exceeded', { size: Localization.of().bytes(this.#maxFileSize) });\n this._input.files = InputFile.list([...this.files].filter((f) => !oversized.includes(f)));\n }\n #ensureTotalSize() {\n if (this.#maxTotalSize === null) {\n return;\n }\n const totalSize = [...this.files].reduce((acc, file) => acc + file.size, 0);\n if (totalSize <= this.#maxTotalSize) {\n return;\n }\n this.warning('files.max-total-size-exceeded', { size: Localization.of().bytes(this.#maxTotalSize) });\n this._input.files = InputFile.list();\n }\n\n /**\n * The accepted types, also set on the native input for its picker. A token\n * is a dot-prefixed extension matched against the end of the file name, a\n * mime type matched against the file's type with any parameters ignored, or\n * a family such as `image/*`; case is ignored, and any other token matches\n * nothing. A file matching no token is dropped with a warning; an empty list\n * accepts every file. Enforced from the next selection on.\n * @returns {string[]}\n */\n get accept() {\n return this.#accept;\n }\n /** @param {string[]} vs */\n set accept(vs) {\n this._input.accept = vs.join(',');\n this.#accept = vs;\n this.reflectTo('accept', vs);\n }\n /**\n * Whether the field takes several files; a single-file field ignores a drop of several.\n * @returns {boolean}\n */\n get multiple() {\n return this._input.multiple;\n }\n /** @param {boolean} v */\n set multiple(v) {\n this._input.multiple = v;\n this.reflectTo('multiple', v);\n }\n /**\n * The selected files, after the constraints.\n * @returns {FileList}\n */\n get files() {\n return this._input.files;\n }\n /**\n * Replaces the selection and runs the constraints over it, refreshing the\n * warnings and the item list, without firing change.\n * @param {FileList} vs\n */\n set files(vs) {\n this._input.files = vs;\n this.#update();\n }\n /**\n * The first selected file.\n * @returns {File|null}\n */\n get file() {\n return this.files[0] ?? null;\n }\n /**\n * Replaces the selection with this one file, or empties it, as `files` does.\n * @param {File|null|undefined} v\n */\n set file(v) {\n this.files = InputFile.list(v ? [v] : []);\n }\n /**\n * The names of the selected files: an array when `multiple`, otherwise the\n * one name or null.\n * @returns {string[]|string|null}\n */\n get value() {\n const names = Array.from(this._input.files).map((f) => f.name);\n return this.multiple ? names : (names[0] ?? null);\n }\n /**\n * Empties the selection for a falsy value and ignores any other, since a\n * file name cannot select a file.\n * @param {any} v\n */\n set value(v) {\n if (v) {\n return;\n }\n this.files = InputFile.list();\n }\n /** Empties the selection, as a native file input's reset does, whatever the `value` attribute says. */\n formResetCallback() {\n this.value = null;\n }\n /**\n * The size of the selected files together, in bytes.\n * @returns {number}\n */\n get totalsize() {\n return Array.from(this.files).reduce((a, f) => a + f.size, 0);\n }\n #maxFiles;\n /**\n * The most files a selection may hold; a larger selection is cleared\n * entirely with a warning. Enforced from the next selection on.\n * @returns {number|null} null for no limit\n */\n get maxFiles() {\n return this.#maxFiles;\n }\n /** @param {number|null} v */\n set maxFiles(v) {\n this.#maxFiles = v;\n this.reflectTo('max-files', v);\n }\n #maxFileSize;\n /**\n * The largest size one file may have, in bytes; a larger file is dropped\n * from the selection with a warning. Enforced from the next selection on.\n * @returns {number|null} null for no limit\n */\n get maxFileSize() {\n return this.#maxFileSize;\n }\n /** @param {number|null} v */\n set maxFileSize(v) {\n this.#maxFileSize = v;\n this.reflectTo('max-file-size', v);\n }\n #maxTotalSize;\n /**\n * The largest size the selected files may have together, in bytes; a\n * larger selection is cleared entirely with a warning. Enforced from the\n * next selection on.\n * @returns {number|null} null for no limit\n */\n get maxTotalSize() {\n return this.#maxTotalSize;\n }\n /** @param {number|null} v */\n set maxTotalSize(v) {\n this.#maxTotalSize = v;\n this.reflectTo('max-total-size', v);\n }\n #useItemList;\n /**\n * Whether the chosen files are listed, each with a button removing it; the\n * stylesheet shows the list from the reflected `item-list` attribute.\n * @returns {boolean}\n */\n get itemList() {\n return this.#useItemList;\n }\n /** @param {boolean} v */\n set itemList(v) {\n this.#useItemList = v;\n this.reflectTo('item-list', v);\n }\n #useDropzone;\n /**\n * Whether the dropzone is shown; the stylesheet shows it from the reflected\n * `dropzone` attribute.\n * @returns {boolean}\n */\n get dropzone() {\n return this.#useDropzone;\n }\n /** @param {boolean} v */\n set dropzone(v) {\n\n this.#useDropzone = v;\n this.reflectTo('dropzone', v);\n }\n}\n\nexport { InputFile };\n","import { Attributes } from '../../ftl/index.mjs';\n\n/** the viewport's breathing room when clamping, in pixels */\nconst PAD = 8;\nconst open = new Map();\nlet frame = 0;\nlet reflowWired = false;\n\nconst platformAnchors = () =>\n CSS.supports('anchor-name: --ful-probe') &&\n CSS.supports('position-anchor: --ful-probe') &&\n CSS.supports('position-area: bottom') &&\n CSS.supports('top: anchor(bottom)') &&\n CSS.supports('width: anchor-size(width)');\n\nconst clamp = (value, low, high) => Math.min(Math.max(value, low), Math.max(low, high));\n\n/** a popover that reads `placement` and gets the callout offsets */\nconst isNote = (popover) => popover.matches('ful-note, .ful-note, [placement]');\n\n/**\n * Writes the invoker's centre, measured from the popover's padding box, as\n * `--ful-note-callout-inline` and `--ful-note-callout-block` on the popover.\n */\nconst reportCallout = (popover, invoker) => {\n const box = invoker.getBoundingClientRect();\n const here = popover.getBoundingClientRect();\n popover.style.setProperty(\n '--ful-note-callout-inline',\n `${box.left + box.width / 2 - here.left - popover.clientLeft}px`,\n );\n popover.style.setProperty(\n '--ful-note-callout-block',\n `${box.top + box.height / 2 - here.top - popover.clientTop}px`,\n );\n};\n\nconst place = (popover, anchored) => {\n const { invoker, stretch } = anchored;\n const box = invoker.getBoundingClientRect();\n const viewport = document.documentElement;\n const vw = viewport.clientWidth;\n const vh = viewport.clientHeight;\n popover.style.removeProperty('margin');\n const computed = getComputedStyle(popover);\n const gap = {\n top: parseFloat(computed.marginTop) || 0,\n right: parseFloat(computed.marginRight) || 0,\n bottom: parseFloat(computed.marginBottom) || 0,\n left: parseFloat(computed.marginLeft) || 0,\n };\n popover.style.right = 'auto';\n popover.style.bottom = 'auto';\n popover.style.margin = '0';\n if (stretch) {\n popover.style.removeProperty('width');\n popover.style.removeProperty('min-width');\n popover.style.removeProperty('max-width');\n const cap = Math.min(parseFloat(computed.maxWidth) || vw, vw - 2 * PAD);\n popover.style.minWidth = `${Math.min(box.width, vw - 2 * PAD)}px`;\n popover.style.maxWidth = `${cap}px`;\n const width = popover.getBoundingClientRect().width;\n popover.style.left = `${clamp(box.left, PAD, vw - width - PAD)}px`;\n const height = popover.getBoundingClientRect().height;\n const below = box.bottom + gap.top;\n const top = below + height <= vh - PAD ? below : box.top - gap.bottom - height;\n popover.style.top = `${clamp(top, PAD, vh - height - PAD)}px`;\n return;\n }\n const note = isNote(popover);\n const placement = note ? (popover.getAttribute('placement') ?? 'bottom') : 'bottom';\n popover.style.removeProperty('max-width');\n const cap = Math.min(parseFloat(computed.maxWidth) || vw, vw - 2 * PAD);\n popover.style.maxWidth = `${cap}px`;\n popover.style.left = `${PAD}px`;\n const wide = popover.getBoundingClientRect().width;\n let left =\n placement === 'right'\n ? box.right + gap.left\n : placement === 'left'\n ? box.left - gap.right - wide\n : note\n ? box.left + box.width / 2 - wide / 2\n : box.left;\n left = clamp(left, PAD, vw - wide - PAD);\n popover.style.left = `${left}px`;\n popover.style.maxWidth = `${Math.min(cap, vw - PAD - left)}px`;\n const height = popover.getBoundingClientRect().height;\n const top =\n placement === 'top'\n ? box.top - gap.bottom - height\n : placement === 'right' || placement === 'left'\n ? box.top + box.height / 2 - height / 2\n : box.bottom + gap.top;\n popover.style.top = `${clamp(top, PAD, vh - height - PAD)}px`;\n if (note) {\n reportCallout(popover, invoker);\n }\n};\n\nconst unplace = (popover) => {\n for (const property of [\n 'top',\n 'left',\n 'right',\n 'bottom',\n 'margin',\n 'max-width',\n 'min-width',\n 'width',\n 'visibility',\n '--ful-note-callout-inline',\n '--ful-note-callout-block',\n ]) {\n popover.style.removeProperty(property);\n }\n};\n\nconst showOncePlaced = (popover, anchored) => {\n popover.style.visibility = 'hidden';\n queueMicrotask(() => {\n if (popover.matches(':popover-open')) {\n place(popover, anchored);\n }\n popover.style.removeProperty('visibility');\n });\n};\n\nconst reflow = () => {\n frame = 0;\n for (const [popover, anchored] of open) {\n if (!popover.isConnected || !anchored.invoker.isConnected) {\n open.delete(popover);\n continue;\n }\n place(popover, anchored);\n }\n};\n\nconst schedule = () => {\n if (!frame && open.size > 0) {\n frame = requestAnimationFrame(reflow);\n }\n};\n\n/**\n * Places a popover beside the element or the rectangle it belongs to.\n *\n * `wire` pairs a popover with one invoker for its lifetime and relies on css\n * anchor positioning, placing the popover in script only where the platform\n * lacks it or the caller asks for it. `show` places a popover once, beside\n * whatever anchor the call hands over.\n */\nclass Anchors {\n /**\n * Anchors a popover to its invoker for the popover's lifetime.\n *\n * On every platform the invoker is given an inline `anchor-name` and the\n * popover a `position-anchor` naming it, `--` followed by a unique id\n * built from `prefix`. That is what a stylesheet needs to place the popover\n * itself: the library's own menus say `top: anchor(bottom); left:\n * anchor(left)`. **Writing that css is the caller's half of this.** Without\n * it the popover lands wherever the user agent puts a popover, which is not\n * beside the invoker.\n *\n * Where the platform has no css anchor positioning, or under `handPlace`,\n * the popover is placed in script instead: beside the invoker whenever it\n * opens, clamped 8px inside the viewport, placed again on every scroll and\n * resize while open, and its inline placement removed on close. The gap to\n * the invoker is read from the popover's css margins. From `beforetoggle`\n * to the placing, in a microtask before the `toggle` event, the popover\n * carries an inline `visibility: hidden`, so a stylesheet setting\n * `visibility` on it competes with that. A popover removed from the\n * document while open, or whose invoker was removed, stops being placed.\n *\n * The script placement puts a plain popover below the invoker,\n * start-aligned. A popover matching `ful-note`, `.ful-note` or\n * `[placement]` reads its `placement` attribute instead: `top`, `right`,\n * `left`, or `bottom` by default, centred on the invoker along the other\n * axis. Such a popover is also given `--ful-note-callout-inline` and\n * `--ful-note-callout-block`: the invoker's centre, in pixels, measured\n * from the popover's padding box, which stays on the invoker when the\n * viewport pushes the popover off it.\n *\n * Wiring the same pair twice adds its listeners twice.\n *\n * @param {HTMLElement} invoker the element the popover belongs to\n * @param {HTMLElement} popover the `[popover]` element to place\n * @param {object} [options]\n * @param {string} [options.prefix] prefixes the generated anchor name and\n * id, `ful-anchor` by default, so the dom says which component a name\n * belongs to\n * @param {boolean} [options.invoke] makes the invoker toggle the popover,\n * which light dismiss then closes with no script of your own. The popover\n * is given the generated id when it has none. A `button` or `input`\n * invoker gets a `popovertarget` naming it; any other element toggles it\n * on click and on the Enter and Space keys\n * @param {boolean} [options.expanded] sets the invoker's `aria-expanded` to\n * `false` at once and keeps it in step with the popover's `toggle` events\n * @param {boolean} [options.stretch] in the script placement, sizes the\n * popover to at least its invoker's width, capped by its own `max-width`\n * and the viewport, and flips it above the invoker where the viewport\n * leaves no room below, which is what a combobox dropdown wants. The\n * `placement` attribute is not read\n * @param {boolean} [options.handPlace] places in script on every platform\n * rather than only as a fallback, for a popover that needs to know where\n * its invoker ended up, such as a note pointing a callout at it. Such a\n * popover declares no anchor placement in css\n */\n static wire(\n invoker,\n popover,\n { prefix = 'ful-anchor', invoke = false, expanded = false, stretch = false, handPlace = false } = {},\n ) {\n const uid = Attributes.uid(prefix);\n if (invoke) {\n popover.id = popover.id || uid;\n if (invoker.localName === 'button' || invoker.localName === 'input') {\n invoker.setAttribute('popovertarget', popover.id);\n } else {\n invoker.addEventListener('click', () => popover.togglePopover());\n invoker.addEventListener('keydown', (/** @type any */ evt) => {\n if (evt.key !== 'Enter' && evt.key !== ' ') {\n return;\n }\n evt.preventDefault();\n popover.togglePopover();\n });\n }\n }\n const anchor = `--${uid}`;\n invoker.style.anchorName = anchor;\n popover.style.positionAnchor = anchor;\n if (expanded) {\n invoker.setAttribute('aria-expanded', 'false');\n popover.addEventListener('toggle', (/** @type any */ evt) => {\n invoker.setAttribute('aria-expanded', evt.newState === 'open' ? 'true' : 'false');\n });\n }\n if (!handPlace && platformAnchors()) {\n return;\n }\n const anchored = { invoker, stretch };\n popover.addEventListener('beforetoggle', (/** @type any */ evt) => {\n if (evt.newState === 'open') {\n showOncePlaced(popover, anchored);\n }\n });\n popover.addEventListener('toggle', (/** @type any */ evt) => {\n if (evt.newState === 'open') {\n open.set(popover, anchored);\n place(popover, anchored);\n } else {\n open.delete(popover);\n unplace(popover);\n }\n });\n if (!reflowWired) {\n reflowWired = true;\n document.addEventListener('scroll', schedule, true);\n window.addEventListener('resize', schedule);\n }\n }\n /**\n * Shows a popover and places it beside an anchor, once. It serves a\n * popover shared by many invokers, each open handing over its own anchor,\n * and an anchor that is a rectangle rather than an element, such as one\n * read out of an iframe. Nothing is paired and nothing follows a later\n * scroll or resize; closing is the caller's, or the platform's for a\n * light-dismissing popover.\n *\n * The popover goes below the anchor, start-aligned, clamped 8px inside the\n * viewport. `flip` moves it above the anchor where there is no room below\n * and there is room above. The placement is written as inline `top`, `left`,\n * `right`, `bottom` and `margin`, which stay after the popover closes and\n * are overwritten by the next call.\n *\n * A popover not already open is shown with `showPopover()` and placed\n * before the call returns, so the first position anybody sees is the right\n * one and the caller can move the focus into it on the next line. One\n * already open is placed without being shown again.\n *\n * @param {HTMLElement} popover the `[popover]` element to show, or an\n * already-shown element to place\n * @param {Element|DOMRect} anchor the element, or the rectangle in\n * viewport coordinates, to place beside\n * @param {object} [options]\n * @param {boolean} [options.flip] place above the anchor where no room is\n * left below, `false` by default\n * @param {number} [options.gap] the distance from the anchor, in pixels,\n * `0` by default\n * @returns {HTMLElement} the popover\n */\n static show(popover, anchor, { flip = false, gap = 0 } = {}) {\n const placeShown = () => {\n const box = anchor instanceof Element ? anchor.getBoundingClientRect() : anchor;\n const viewport = document.documentElement;\n const here = popover.getBoundingClientRect();\n const below = box.bottom + gap;\n const above = box.top - gap - here.height;\n const top = flip && below + here.height > viewport.clientHeight - PAD && above >= PAD ? above : below;\n popover.style.right = 'auto';\n popover.style.bottom = 'auto';\n popover.style.margin = '0';\n popover.style.left = `${clamp(box.left, PAD, Math.max(PAD, viewport.clientWidth - here.width - PAD))}px`;\n popover.style.top = `${clamp(top, PAD, Math.max(PAD, viewport.clientHeight - here.height - PAD))}px`;\n };\n if (typeof popover.showPopover === 'function' && !popover.matches(':popover-open')) {\n popover.showPopover();\n }\n placeShown();\n return popover;\n }\n}\n\nexport { Anchors };\n","import { Attributes, Fragments, ParsedElement, Templates } from '../../ftl/index.mjs';\nimport { Claims } from '../claims.mjs';\nimport { Anchors } from '../disclosures/anchors.mjs';\nimport { Field } from './field.mjs';\nimport { VersionedLocalStorage } from '../storage.mjs';\nimport { Timing } from '../timing.mjs';\n\n/**\n * @typedef {{ key: any, label: string, metadata: any }} SelectEntry\n */\n/**\n * @typedef {{ request(method: string, url: string): any }} SelectHttpClient\n */\n\nconst byKeys = (entries, keys) => entries.filter(({ key }) => keys.some((r) => r == key));\nconst byLabel = (entries, needle) =>\n entries.filter(({ label }) => (label ?? '').toLowerCase().includes(needle?.toLowerCase() ?? ''));\n\n/**\n * Fetches a select's whole vocabulary from a url and serves every later read\n * from it. Concurrent callers share one request, the options may be cached in\n * local storage under a revision, and invalidating discards both.\n */\nclass RemoteLoader {\n #http;\n #url;\n #method;\n #responseMapper;\n #prefetch;\n #revision;\n #data = null;\n /** @type {Promise<void>|null} */\n #inFlight = null;\n #configs = new Claims();\n /**\n * @param {{ http: SelectHttpClient, url: string, method: string, responseMapper: (response: any) => SelectEntry[], prefetch: boolean, revision: string|null }} conf\n * a null revision never reads nor writes local storage\n */\n constructor({ http, url, method, responseMapper, prefetch, revision }) {\n this.#http = http;\n this.#url = url;\n this.#method = method;\n this.#responseMapper = responseMapper;\n this.#prefetch = prefetch;\n this.#revision = revision;\n }\n /**\n * Fetches the vocabulary now when the loader was built with prefetch, and\n * does nothing otherwise.\n * @returns {Promise<void>}\n * @throws when the fetch fails, or when an invalidation supersedes it\n */\n async prefetch() {\n if (!this.#prefetch) {\n return;\n }\n await this.#ensureFetched();\n }\n /**\n * The entries whose key loosely equals one of the keys, in vocabulary order.\n * @param {...any} keys\n * @returns {Promise<SelectEntry[]>}\n * @throws when the fetch fails, or when an invalidation supersedes it\n */\n async exact(...keys) {\n return byKeys(await this.#ensureFetched(), keys);\n }\n /**\n * The entries whose label contains the needle, ignoring case; every entry\n * for a nullish or empty needle.\n * @param {string|null} [needle]\n * @returns {Promise<SelectEntry[]>}\n * @throws when the fetch fails, or when an invalidation supersedes it\n */\n async load(needle) {\n return byLabel(await this.#ensureFetched(), needle);\n }\n /**\n * Drops the vocabulary held in memory so the next question refetches it,\n * which may still be answered from local storage under the same revision.\n * A fetch still in flight is detached: its outcome is neither served nor\n * stored, and the callers waiting on it reject.\n * @returns {Promise<void>}\n */\n async invalidate() {\n this.#configs.invalidate();\n this.#data = null;\n this.#inFlight = null;\n }\n async #ensureFetched() {\n if (this.#data === null) {\n if (this.#inFlight === null) {\n const claim = this.#configs.hold();\n this.#inFlight = RemoteLoader.#revisionedData(this.#http, this.#method, this.#url, this.#revision)\n .then((raw) => {\n if (!claim.stale) {\n this.#data = this.#responseMapper(raw);\n }\n })\n .finally(() => {\n if (!claim.stale) {\n this.#inFlight = null;\n }\n });\n }\n await this.#inFlight;\n }\n if (this.#data === null) {\n throw new Error('superseded by an invalidation');\n }\n return this.#data;\n }\n static async #revisionedData(http, method, url, revision) {\n const storageKey = `${method}@${url}`;\n if (revision !== null) {\n const data = VersionedLocalStorage.load(storageKey, revision);\n if (data !== undefined) {\n return data;\n }\n }\n const data = await http.request(method, url).fetchJson();\n if (revision !== null) {\n try {\n VersionedLocalStorage.save(storageKey, revision, data);\n } catch (/** @type any */ e) {\n console.warn('failed to cache the select options', e);\n }\n }\n return data;\n }\n}\n\n/** Asks the endpoint per query instead of fetching the vocabulary once, for a list too large to hold in memory. */\nclass PartialRemoteLoader {\n #http;\n #url;\n #method;\n #responseMapper;\n /**\n * @param {{ http: SelectHttpClient, url: string, method: string, responseMapper: (response: any) => SelectEntry[] }} conf\n */\n constructor({ http, url, method, responseMapper }) {\n this.#http = http;\n this.#url = url;\n this.#method = method;\n this.#responseMapper = responseMapper;\n }\n /**\n * Does nothing, since nothing is held between queries.\n * @returns {Promise<void>}\n */\n async invalidate() {}\n /**\n * Asks the endpoint for the entries of the keys, sent as repeated `k`\n * parameters.\n * @param {...any} keys\n * @returns {Promise<SelectEntry[]>}\n * @throws when the request fails\n */\n async exact(...keys) {\n const response = await this.#http\n .request(this.#method, this.#url)\n .param('k', ...keys)\n .fetchJson();\n return this.#responseMapper(response);\n }\n /**\n * Asks the endpoint for the entries matching the needle, sent as the `s`\n * parameter; the filtering is the endpoint's.\n * @param {string|null} [needle]\n * @returns {Promise<SelectEntry[]>}\n * @throws when the request fails\n */\n async load(needle) {\n const response = await this.#http.request(this.#method, this.#url).param('s', needle).fetchJson();\n return this.#responseMapper(response);\n }\n}\n\n/** Serves a select's options from an array held in memory, which is what the slotted `<option>` elements become. */\nclass InMemoryLoader {\n #data;\n /**\n * @param {SelectEntry[]} data\n */\n constructor(data) {\n this.#data = data;\n }\n /**\n * Replaces the vocabulary every later question is answered from.\n * @param {SelectEntry[]} data\n */\n update(data) {\n this.#data = data;\n }\n /**\n * Does nothing: the vocabulary is the data itself, which only update replaces.\n * @returns {Promise<void>}\n */\n async invalidate() {}\n /**\n * The entries whose key loosely equals one of the keys, in vocabulary order.\n * @param {...any} keys\n * @returns {SelectEntry[]}\n */\n exact(...keys) {\n return byKeys(this.#data, keys);\n }\n /**\n * The entries whose label contains the needle, ignoring case; every entry\n * for a nullish or empty needle.\n * @param {string|null} [needle]\n * @returns {SelectEntry[]}\n */\n load(needle) {\n return byLabel(this.#data, needle);\n }\n}\n\n/**\n * Builds the select's loader from its attributes: the slotted options in\n * memory, or a remote or chunked loader over src. It is registered as the\n * `loaders:select` component.\n *\n * A component named by the select's `loader` attribute replaces this one: its\n * `create(el, conf)` answers an object with these methods, each answering\n * `{ key, label, metadata }` entries, directly or through a promise:\n *\n * - `load(needle)` answers the entries matching the typed text, all of them\n * when the needle is empty, which is the search the list opens with\n * - `exact(...keys)` answers the entries for those keys, used to label a value\n * assigned without going through the list; a key it leaves out is dropped\n * from the selection\n * - `prefetch()`, optional, warms the vocabulary; the select calls it at the\n * upgrade without waiting, and awaits it in `reload()`\n * - `invalidate()`, optional, drops whatever the loader holds, called by\n * `reload()`\n *\n * An entry whose `metadata.disabled` is truthy is shown and cannot be picked,\n * with `metadata.reason`, when present, as the row's title.\n */\nclass SelectLoader {\n /**\n * Builds a loader from a plain configuration, reading no dom: `data` alone\n * is the in-memory vocabulary, a `url` is fetched whole or, under\n * `mode: 'chunked'`, per query. A test, or a caller holding its own\n * configuration, builds a loader this way; `create` is the same thing with\n * an element's attributes parsed first.\n *\n * A remote loader fetches once and filters in memory, caching the response\n * in local storage under `method@url` when a revision is given; a chunked\n * one sends every search as `s` and every key lookup as `k`. The response\n * mapper turns the parsed response body into entries.\n * @param {{ data?: SelectEntry[], url?: undefined, http?: undefined, method?: undefined, mode?: undefined, prefetch?: undefined, revision?: undefined, responseMapper?: undefined }\n * | { data?: undefined, url: string, http: SelectHttpClient, method?: string, mode?: string, prefetch?: boolean, revision?: string|null, responseMapper: (response: any) => SelectEntry[] }} conf\n * `method` defaults to POST\n * @returns {InMemoryLoader|PartialRemoteLoader|RemoteLoader}\n */\n static from({ data, http, url, method = 'POST', mode, prefetch = false, revision = null, responseMapper }) {\n if (!url) {\n return new InMemoryLoader(data ?? []);\n }\n if ('chunked' === mode) {\n return new PartialRemoteLoader({ http, url, method, responseMapper });\n }\n return new RemoteLoader({ http, url, method, responseMapper, prefetch, revision });\n }\n /**\n * Builds the loader an element's attributes describe. Without `src` the\n * vocabulary is the `<option>` elements of `conf.options`, each keyed by its\n * `value` attribute or else its trimmed text. With `src` the url is\n * requested through the `http-client` component with `method` (POST by\n * default): once on first use, or at the upgrade under `preload`, or per\n * query under `mode=\"chunked\"`. A `revision` caches the whole response in local storage; a\n * valueless one takes the `revision` component, calling it when it is a\n * function, and warns and does not cache when none is registered.\n *\n * The response becomes entries through `k-expr` and `l-expr` evaluated on\n * each row of `d-expr` (the response itself by default), with `m-expr` as\n * the metadata (the row by default); else through the `response-mapper`\n * component; else each row is read as a `[key, label, metadata]` array.\n * @param {ParsedElement} el the element declaring the loader attributes\n * @param {{ options?: DocumentFragment }} conf\n * @returns {InMemoryLoader|PartialRemoteLoader|RemoteLoader}\n */\n static create(el, conf) {\n if (!el.declared('src')) {\n const els = Array.from(conf.options?.querySelectorAll('option') ?? []);\n return SelectLoader.from({\n data: els.map((e) => ({\n key: e.getAttribute('value') ?? e.innerText.trim(),\n label: e.innerText.trim(),\n metadata: undefined,\n })),\n });\n }\n return SelectLoader.from({\n http: el.component('http-client'),\n url: el.declared('src'),\n method: el.declared('method') ?? 'POST',\n mode: el.declared('mode'),\n prefetch: el.declared('preload'),\n revision: SelectLoader.#revisionFrom(el),\n responseMapper: SelectLoader.#responseMapperFrom(el),\n });\n }\n static #revisionFrom(el) {\n const declared = el.declared('revision');\n if (declared !== '') {\n return declared;\n }\n const configured = el.component('revision');\n if (configured === undefined || configured === null) {\n console.warn(\n \"a valueless revision asks the registry for one, and no 'revision' component is defined: the vocabulary will not be cached\",\n el,\n );\n return null;\n }\n return typeof configured === 'function' ? configured() : configured;\n }\n static #responseMapperFrom(el) {\n if (el.declared('k-expr') && el.declared('l-expr')) {\n return (response) => {\n const rows = el._registry\n .evaluator()\n .withOverlay(response)\n .evaluateExpression(el.declared('d-expr') ?? 'self');\n return rows.map((row) => {\n const evaluator = el._registry.evaluator().withOverlay(row);\n return {\n key: evaluator.evaluateExpression(el.declared('k-expr')),\n label: evaluator.evaluateExpression(el.declared('l-expr')),\n metadata: evaluator.evaluateExpression(el.declared('m-expr') ?? 'self'),\n };\n });\n };\n }\n if (el.declared('response-mapper')) {\n return el.component(el.declared('response-mapper'));\n }\n return (/** @type any[] */ response) => response.map(([key, label, metadata]) => ({ key, label, metadata }));\n }\n}\n\n/**\n * The options popup of a select, a `<ful-dropdown>` the owner shows as a\n * popover: a spinner while the loader runs, a localized empty state, and a\n * `role=\"listbox\"` menu of `role=\"option\"` rows.\n *\n * The owner drives it and listens to it. A pick dispatches a bubbling\n * `change` whose detail is `{ index, entry }`, the row's index as a string\n * and the entry it was rendered from. The active row is announced by a\n * non-bubbling `activechange` whose detail is `{ id }`, the row's id or null\n * when none is active, for the owner to set `aria-activedescendant`. A\n * pressed row does not take the focus from the owner's control.\n */\nclass Dropdown extends ParsedElement {\n /**\n * `listbox` is the id given to the menu, so an owner can set\n * `aria-controls` before this element upgrades; a generated id otherwise.\n */\n static attributes = ['listbox'];\n /** The default slot, when not blank, is the row template in place of the `options` template. */\n static slots = true;\n static template = `\n <ful-spinner class=\"centered\" role=\"status\" hidden><span class=\"ful-sr-only\">{{ #l10n:t('spinner.loading') }}</span></ful-spinner>\n <ful-empty data-ref=\"empty\" aria-live=\"polite\" hidden>{{ #l10n:t('dropdown.empty') }}</ful-empty>\n <menu tabindex=\"-1\" role=\"listbox\" hidden></menu>\n `;\n /**\n * `options` renders one row per entry, each entry carrying its `index`\n * beside its own keys. A replacement must keep one `<li>` per entry, in\n * order, with the index as its `value`: picking reads the entry back from it.\n */\n static templates = {\n options: `\n <li data-tpl-each=\"self\" data-tpl-selected=\"index == 0\" data-tpl-value=\"index\" role=\"option\">\n {{ label }}\n </li>\n `,\n };\n #spinner;\n #menu;\n #empty;\n #optionstemplate;\n #options = new Map();\n #shows = new Claims();\n /**\n * @param {{ slots: Record<string, DocumentFragment> }} conf\n */\n render({ slots }) {\n const fragment = this.template().render();\n this.#optionstemplate = Fragments.isBlank(slots.default)\n ? this.template('options')\n : Templates.fromFragment(slots.default);\n this.#spinner = fragment.querySelector('ful-spinner');\n this.#empty = fragment.querySelector('[data-ref=empty]');\n this.#menu = fragment.querySelector('menu');\n this.#menu.id = this.declared('listbox') || Attributes.uid('ful-listbox');\n this.#menu.addEventListener('mousedown', (evt) => {\n if (evt.target.closest('li')) {\n evt.preventDefault();\n }\n });\n this.#menu.addEventListener('click', (evt) => {\n evt.stopPropagation();\n const li = evt.target.closest('li');\n if (!li) {\n this.hide();\n return;\n }\n if (li.matches('[aria-disabled=\"true\"]')) {\n return;\n }\n this.#change(li);\n });\n this.replaceChildren(fragment);\n }\n #selected() {\n return (\n this.#menu?.querySelector('[selected]:not([aria-disabled=\"true\"])') ??\n this.#menu?.querySelector('li:not([aria-disabled=\"true\"])') ??\n null\n );\n }\n #highlight(li) {\n if (!li) {\n this.#activated(null);\n return;\n }\n for (const el of this.#menu.querySelectorAll('li')) {\n el.toggleAttribute('selected', el === li);\n }\n li.id ||= Attributes.uid('ful-option');\n this.#activated(li.id);\n li.scrollIntoView({\n block: 'nearest',\n behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth',\n });\n }\n /**\n * Picks the highlighted row, or the first enabled one when none is: hides\n * the dropdown and dispatches `change`. Does nothing when no row is enabled.\n */\n acceptSelection() {\n const selected = this.#selected();\n if (!selected) {\n return;\n }\n this.#change(selected);\n }\n /**\n * Renders the entries as rows and highlights the first one whose key is\n * picked, else the row the template marked `selected`, else the first\n * enabled row. A row is marked `picked` and\n * `aria-selected=\"true\"` when its key loosely equals one of the keys, and\n * `aria-disabled=\"true\"` when its `metadata.disabled` is truthy, titled with\n * `metadata.reason`. No entries shows the empty state instead of the menu.\n * @param {SelectEntry[]} values\n * @param {any[]} [keys] the keys currently selected\n * @throws {Error} when values is undefined\n */\n update(values, keys = []) {\n if (values === undefined) {\n throw new Error('null data');\n }\n this.#options = new Map(values.map((v, i) => [String(i), v]));\n const data = values.map((entry, index) => ({ index, ...entry }));\n this.#optionstemplate.withOverlay(data).renderTo(this.#menu);\n for (const [index, li] of [...this.#menu.children].entries()) {\n const entry = values[index];\n const picked = keys.some((r) => r == entry?.key);\n li.toggleAttribute('picked', picked);\n li.setAttribute('aria-selected', picked ? 'true' : 'false');\n const disabled = !!entry?.metadata?.disabled;\n if (disabled) {\n li.setAttribute('aria-disabled', 'true');\n } else {\n li.removeAttribute('aria-disabled');\n }\n if (disabled && entry.metadata.reason) {\n li.setAttribute('title', String(entry.metadata.reason));\n } else {\n li.removeAttribute('title');\n }\n }\n this.#empty.toggleAttribute('hidden', values.length !== 0);\n this.#menu.toggleAttribute('hidden', values.length === 0);\n const current = values.findIndex(({ key }) => keys.some((r) => r == key));\n this.#highlight(current >= 0 ? this.#menu.children[current] : this.#selected());\n }\n #change(target) {\n const index = target.getAttribute('value');\n const entry = this.#options.get(index);\n this.hide();\n this.dispatchEvent(\n new CustomEvent('change', {\n bubbles: true,\n cancelable: false,\n detail: { index, entry },\n }),\n );\n }\n /**\n * Closes the popover, if open, and announces that no row is active. A\n * `show` still waiting on its loader is superseded: its outcome is neither\n * rendered nor thrown.\n */\n hide() {\n this.#shows.invalidate();\n if (this.matches(':popover-open')) {\n this.hidePopover();\n }\n this.#activated(null);\n }\n #activated(id) {\n this.dispatchEvent(new CustomEvent('activechange', { bubbles: false, cancelable: false, detail: { id } }));\n }\n /**\n * Whether the popover is open.\n * @returns {boolean}\n */\n get shown() {\n return this.matches(':popover-open');\n }\n /**\n * Opens the popover with the spinner showing, then renders what the loader\n * answers as `update` does. A show overtaken by a later `show` or by `hide`\n * before its loader settles leaves the dropdown alone and resolves, even\n * when its loader rejected.\n * @param {() => SelectEntry[]|Promise<SelectEntry[]>} loader\n * @param {any[]} [keys] the keys currently selected\n * @returns {Promise<void>}\n * @throws what the loader threw, after hiding the dropdown, when this show\n * is still the current one\n */\n async show(loader, keys = []) {\n const claim = this.#shows.take();\n if (!this.matches(':popover-open')) {\n this.showPopover();\n }\n this.#menu.setAttribute('hidden', '');\n this.#spinner.removeAttribute('hidden');\n try {\n const data = await loader();\n if (claim.stale) {\n return;\n }\n this.update(data, keys);\n } catch (/** @type any */ e) {\n if (claim.stale) {\n return;\n }\n this.hide();\n throw e;\n } finally {\n if (!claim.stale) {\n this.#spinner.setAttribute('hidden', '');\n }\n }\n }\n /**\n * Moves the highlight to the next or previous enabled row when the dropdown\n * is shown, staying put at the edge, and shows it otherwise.\n * @param {boolean} forward\n * @param {() => SelectEntry[]|Promise<SelectEntry[]>} loader used only to show\n * @param {any[]} [keys] the keys currently selected, used only to show\n * @returns {Promise<void>}\n * @throws what `show` throws\n */\n async moveOrShow(forward, loader, keys = []) {\n if (this.shown) {\n const selected = this.#selected();\n const candidate = selected?.[`${forward ? 'next' : 'previous'}ElementSibling`];\n const target = candidate ? this.#walk(candidate, forward) : null;\n if (selected && target) {\n this.#highlight(target);\n }\n return;\n }\n await this.show(loader, keys);\n }\n #walk(from, forward) {\n for (let li = from; li; li = li[`${forward ? 'next' : 'previous'}ElementSibling`]) {\n if (!li.matches('[aria-disabled=\"true\"]')) {\n return li;\n }\n }\n return null;\n }\n /**\n * Highlights the first enabled row, or the last one.\n * @param {boolean} first\n */\n jump(first) {\n const edge = first ? this.#menu.firstElementChild : this.#menu.lastElementChild;\n const target = this.#walk(edge, first);\n if (target) {\n this.#highlight(target);\n }\n }\n /**\n * Moves the highlight by as many enabled rows as the menu shows at once,\n * one when that cannot be measured, stopping at the last enabled row.\n * @param {boolean} forward\n */\n page(forward) {\n const selected = this.#selected();\n if (!selected) {\n return;\n }\n let target = selected;\n for (let i = 0; i !== this.#page(); ++i) {\n const next = this.#walk(target[`${forward ? 'next' : 'previous'}ElementSibling`], forward);\n if (!next) {\n break;\n }\n target = next;\n }\n this.#highlight(target);\n }\n #page() {\n const first = this.#menu.firstElementChild;\n if (!first || first.offsetHeight === 0) {\n return 1;\n }\n return Math.max(1, Math.trunc(this.#menu.clientHeight / first.offsetHeight));\n }\n}\n\n/**\n * A `<ful-select>`: a combobox over a loader's vocabulary of\n * `{ key, label, metadata }` entries, holding one key or, under `multiple`,\n * several. Typing filters the list, opening it from rest offers the whole\n * vocabulary, and the keyboard follows the combobox pattern: arrows move and\n * open (Alt+ArrowDown opens, Alt+ArrowUp closes), Home, End, PageUp and\n * PageDown move in the open list, Enter accepts the highlighted entry or,\n * with the list closed, submits the form, Escape reverts the edit, and Tab\n * or leaving the field commits it. Emptying the text of a single select and\n * leaving the field clears it. Backspace with the caret at the start removes\n * the last entry, and ArrowLeft there moves the focus to the badges of a\n * multiple select, where Enter, Space, Backspace or Delete remove one.\n *\n * Slots: the default one is the label, `info` sits beside it, `before` and\n * `after` are affixes around the control, `options` holds the `<option>`\n * elements of an in-memory vocabulary, `dropdown` replaces the dropdown's\n * row template and `items` the `items` template.\n *\n * Every change of the selection made through the element dispatches a\n * bubbling `change` whose detail carries `value` and `entry`, as the getters\n * answer them; assigning `value` dispatches none.\n */\nclass Select extends Field {\n /**\n * Read once at the upgrade, so a later write changes nothing: `name`,\n * `loader` (the component building the loader, `loaders:select` by\n * default), `k-type` (`number` or `boolean` coerce the keys, strings\n * otherwise), and the loader configuration `SelectLoader.create` reads,\n * but for `src` and `method`, which stay live.\n */\n static attributes = [\n 'name',\n 'loader',\n 'k-type',\n 'mode',\n 'preload:presence',\n 'revision',\n 'k-expr',\n 'l-expr',\n 'd-expr',\n 'm-expr',\n 'response-mapper',\n ];\n /**\n * Beside the field's claims: `multiple`, `item-list`, `value` as a comma\n * separated list of keys, trimmed, whether or not the select is multiple,\n * and `src` and `method`.\n */\n static observed = ['multiple:presence', 'item-list:presence', 'value:csv', 'src', 'method'];\n /**\n * Reads a present but empty `value` attribute of a single select as the\n * empty key, which an `<option value=\"\">` can carry; a multiple select reads\n * it as no keys.\n * @param {string} attr\n * @param {string|null} str\n * @returns {any}\n * @throws when the class declares no such attribute\n */\n unmarshal(attr, str) {\n if (attr === 'value' && str === '' && !this.hasAttribute('multiple')) {\n return [''];\n }\n return super.unmarshal(attr, str);\n }\n static slots = true;\n static template = `\n <label>{{{{ slots.default }}}}</label>\n {{{{ slots.info }}}}\n <ful-control-group>\n <ful-affix data-tpl-if=\"slots.before\">{{{{ slots.before }}}}</ful-affix>\n <ful-control>\n <input type=\"text\" form=\"\" autocomplete=\"off\" role=\"combobox\" aria-autocomplete=\"list\" aria-haspopup=\"listbox\" aria-expanded=\"false\">\n </ful-control>\n <ful-affix data-tpl-if=\"slots.after\">{{{{ slots.after }}}}</ful-affix>\n <ful-dropdown popover=\"manual\">{{{{ slots.dropdown }}}}</ful-dropdown>\n </ful-control-group>\n <ful-item-list></ful-item-list>\n <ful-field-error></ful-field-error>\n `;\n /**\n * `items` renders the selection below the control, shown under `item-list`,\n * over `entries`, the selected entries in order. A replacement must keep one\n * `<ful-item>` per entry, in order, each with a `<button>` that removes it.\n */\n static templates = {\n items: `\n <ful-item data-tpl-each=\"entries\" data-tpl-var=\"entry\" data-tpl-data-key=\"entry.key\">\n <div><span>{{ entry.label }}</span><button type=\"button\" data-tpl-aria-label=\"#l10n:t('select.remove')\"><ful-icon name=\"x-lg\" aria-hidden=\"true\"></ful-icon></button></div>\n </ful-item>\n `,\n };\n #loader;\n /** @type {{ src: string|null, method: string|null }} */\n #builtFrom = { src: null, method: null };\n #options;\n #control;\n #ddmenu;\n #input;\n #items;\n #itemstemplate;\n #multiple;\n #warnedComma = false;\n #values = new Map();\n #assignments = new Claims();\n #editing = false;\n #dload;\n #abortdload;\n /**\n * @param {{ slots: Record<string, DocumentFragment> }} conf\n * @returns {{ fragment: DocumentFragment, control: HTMLInputElement, error: Element|null, label: Element|null }}\n */\n _build({ slots }) {\n const name = this.declared('name');\n this.#options = slots.options;\n this.#buildLoader();\n\n this.#multiple = this.declared('multiple');\n this.#loader.prefetch?.()?.catch((/** @type any */ e) => {\n console.warn('failed to prefetch select options', this, 'reason:', e);\n });\n const fragment = this.template().withOverlay({ slots, name }).render();\n this.#input = fragment.querySelector('ful-control > input');\n this.#items = fragment.querySelector('ful-item-list');\n this.#itemstemplate =\n slots.items && !Fragments.isBlank(slots.items) ? Templates.fromFragment(slots.items) : null;\n Attributes.forward('input-', this, this.#input);\n this.#control = fragment.querySelector('ful-control');\n\n this.#ddmenu = fragment.querySelector('ful-dropdown');\n const listbox = Attributes.uid('ful-listbox');\n this.#ddmenu.setAttribute('listbox', listbox);\n this.#input.setAttribute('aria-controls', listbox);\n this.#ddmenu.addEventListener('beforetoggle', (/** @type any */ e) => {\n const open = e.newState === 'open';\n this.#input.setAttribute('aria-expanded', open ? 'true' : 'false');\n if (!open) {\n this.#input.removeAttribute('aria-activedescendant');\n }\n });\n this.#ddmenu.addEventListener('activechange', (/** @type any */ e) => {\n Attributes.set(this.#input, 'aria-activedescendant', e.detail.id);\n });\n const group = /** @type {HTMLElement} */ (fragment.querySelector('ful-control-group'));\n Anchors.wire(group, this.#ddmenu, { prefix: 'ful-select', stretch: true });\n [this.#dload, this.#abortdload] = Timing.throttle(400, () => this.#open());\n this.#wireChrome();\n this.#wireChips();\n this.#wireInput();\n this.#wireSelection();\n return {\n fragment,\n control: this.#input,\n error: fragment.querySelector('ful-field-error'),\n label: fragment.querySelector('label'),\n };\n }\n /**\n * Pointer interaction: the element toggles the dropdown, the item list's\n * remove buttons and the control's badges drop their entry.\n */\n #wireChrome() {\n this.addEventListener('click', (/** @type any */ e) => {\n if (!this._interactive()) {\n return;\n }\n const elsewhere = e.target.closest('button, [role=\"button\"], a[href], input, select, textarea');\n if (elsewhere && elsewhere !== this.#input) {\n return;\n }\n if (this.#ddmenu.shown) {\n this.#close();\n return;\n }\n this.#input.focus();\n this.#dload();\n });\n this.#items.addEventListener('click', (e) => {\n e.stopPropagation();\n if (!e.target.closest('button')) {\n return;\n }\n if (!this._interactive()) {\n return;\n }\n this.#removeKeyAt([...this.#items.children].indexOf(e.target.closest('ful-item')));\n });\n this.#control.addEventListener('click', (e) => {\n const badge = e.target instanceof Element ? e.target.closest('ful-badge') : null;\n if (!badge) {\n return;\n }\n e.stopPropagation();\n this.#removeBadge(badge);\n });\n }\n /**\n * Keyboard interaction over the chips: Enter/Space/Backspace/Delete remove,\n * arrows move between badges and the input, Escape returns to the input.\n */\n #wireChips() {\n this.addEventListener('keydown', (/** @type any */ e) => {\n const badge = e.target instanceof Element ? e.target.closest('ful-badge') : null;\n if (badge) {\n this.#chipKeydown(e, badge);\n return;\n }\n if (\n 'ArrowLeft' === e.code &&\n e.target === this.#input &&\n this.#input.selectionStart === 0 &&\n this.#input.selectionEnd === 0\n ) {\n this.#badges().at(-1)?.focus();\n }\n });\n }\n #wireInput() {\n this.#input.addEventListener('change', (e) => {\n e.stopPropagation();\n });\n this.#input.addEventListener('focus', () => {\n if (this.#editing) {\n return;\n }\n this.#input.select();\n });\n this.#input.addEventListener('blur', (e) => {\n e.stopPropagation();\n if (e.relatedTarget && this.contains(e.relatedTarget)) {\n return;\n }\n this.#abortdload();\n this.#close(true);\n });\n this.#input.addEventListener('keydown', (e) => {\n if (!this._interactive()) {\n return;\n }\n this.#comboboxKeydown(e);\n });\n this.#input.addEventListener('input', (e) => {\n e.stopPropagation();\n if (!this._interactive()) {\n return;\n }\n this.#editing = true;\n this.#dload();\n });\n }\n #wireSelection() {\n this.#ddmenu.addEventListener('change', (e) => {\n e.stopPropagation();\n if (!this._interactive()) {\n this.#close();\n return;\n }\n if (!this.#multiple) {\n this.#values.clear();\n }\n this.#editing = false;\n this.#values.set(this.#coerceKey(e.detail.entry.key), e.detail.entry);\n this.#changed();\n this.#input.focus();\n this.#ddmenu.hide();\n if (!this.#multiple) {\n this.#input.select();\n }\n });\n }\n /**\n * Hands the loader to the callback, for runtime changes such as\n * `update(entries)` on an in-memory loader.\n * @template T\n * @param {(loader: any) => T|Promise<T>} fn\n * @returns {Promise<T>} what the callback answers\n */\n async withLoader(fn) {\n return await fn(this.#loader);\n }\n /**\n * Drops whatever the loader is holding, awaits its prefetch (which fetches\n * again when the select declares `preload`), and asks it about the current\n * selection again, which is what a select whose vocabulary depends on\n * another control needs when that control changes. A key the loader no\n * longer knows is dropped from the selection, so a value invalidated by the\n * change does not survive it, and one it still knows keeps its place with a\n * fresh label. The badges and items follow, and no `change` is dispatched.\n *\n * Where the vocabulary lives at a different address, write `src` or call\n * `reconfigure`, which build the loader for the new url and reload.\n * @returns {Promise<void>}\n * @throws what the loader's invalidate, prefetch or key lookup throws\n */\n async reload() {\n await this.#loader.invalidate?.();\n await this.#loader.prefetch?.();\n const keys = [...this.#values.keys()];\n if (keys.length === 0) {\n return;\n }\n await this.#resolve(keys, this.#assignments.take());\n }\n /**\n * The url the loader asks for the vocabulary, reflected as the `src`\n * attribute.\n * @returns {string|null}\n */\n get src() {\n return this.getAttribute('src');\n }\n /**\n * Points the select at another vocabulary: the dropdown closes, the loader\n * is built again through its component's `create`, as at the render, and\n * the select reloads as `reload()` does, so a selected key the new\n * vocabulary does not know is dropped and one it knows is labelled again,\n * with no `change` dispatched. A write that does not change the url does\n * nothing.\n *\n * The reload is not awaited: a failed fetch or lookup surfaces as an\n * unhandled rejection.\n * @param {string|null|undefined} value null or undefined removes the url,\n * which the default loader answers with the slotted options\n */\n set src(value) {\n this.reflectTo('src', value ?? null);\n if (this.#followAttributes()) {\n this.reload();\n }\n }\n /**\n * The http method the default loader sends, reflected as the `method`\n * attribute; `POST` when absent.\n * @returns {string|null}\n */\n get method() {\n return this.getAttribute('method');\n }\n /**\n * Changes the http method the way `src` changes the url: the loader is\n * built again and the select reloads.\n * @param {string|null|undefined} value\n */\n set method(value) {\n this.reflectTo('method', value ?? null);\n if (this.#followAttributes()) {\n this.reload();\n }\n }\n /**\n * Writes `src` and `method` together and reloads once: the loader is built\n * again for the pair when either changed, as a single write of either does,\n * and the select then reloads as `reload()` does, whether or not they\n * changed.\n *\n * citta.addEventListener('change', () => {\n * cap.reconfigure({ src: `/api/cap?citta=${citta.value}` }, { notify: true });\n * });\n * @param {{ src?: string|null, method?: string|null }} attributes a name\n * left out keeps its value, null removes the attribute\n * @param {{ notify?: boolean }} [options] `notify` dispatches `change` when\n * the reload dropped a selected key, so a form or a table filtered by the\n * select sees the value it lost; nothing is dispatched otherwise\n * @returns {Promise<void>} settling once the reload has\n * @throws what the loader's invalidate, prefetch or key lookup throws\n */\n async reconfigure(attributes, { notify = false } = {}) {\n for (const name of ['src', 'method']) {\n if (name in attributes) {\n this.reflectTo(name, attributes[name] ?? null);\n }\n }\n this.#followAttributes();\n const before = [...this.#values.keys()];\n await this.reload();\n const after = [...this.#values.keys()];\n if (notify && after.length !== before.length) {\n this._notifyChange({ entry: this.entry });\n }\n }\n #buildLoader() {\n this.#builtFrom = { src: this.getAttribute('src'), method: this.getAttribute('method') };\n this.#loader = this.component(this.declared('loader') ?? 'loaders:select').create(this, {\n options: this.#options,\n });\n }\n /** @returns {boolean} whether the loader was built again */\n #followAttributes() {\n if (\n this.getAttribute('src') === this.#builtFrom.src &&\n this.getAttribute('method') === this.#builtFrom.method\n ) {\n return false;\n }\n this.#abortdload();\n this.#close();\n this.#buildLoader();\n return true;\n }\n #badges() {\n return Array.from(this.#control.querySelectorAll(':scope > ful-badge'));\n }\n #removeBadge(badge) {\n if (!this._interactive()) {\n return;\n }\n this.#removeKeyAt(this.#badges().indexOf(badge));\n }\n /** Badges and item list entries share the selection's order, so one index serves both. */\n #removeKeyAt(index) {\n const key = Array.from(this.#values.keys())[index];\n if (key === undefined) {\n return;\n }\n this.#values.delete(key);\n this.#changed();\n }\n #chipKeydown(e, badge) {\n switch (e.code) {\n case 'NumpadEnter':\n case 'Enter':\n case 'Space':\n case 'Backspace':\n case 'Delete': {\n e.preventDefault();\n this.#removeBadge(badge);\n this.#input.focus();\n break;\n }\n case 'ArrowLeft': {\n e.preventDefault();\n (this.#badges()[this.#badges().indexOf(badge) - 1] ?? this.#input).focus();\n break;\n }\n case 'ArrowRight': {\n e.preventDefault();\n (this.#badges()[this.#badges().indexOf(badge) + 1] ?? this.#input).focus();\n break;\n }\n case 'Escape': {\n this.#input.focus();\n break;\n }\n }\n }\n /**\n * The combobox keyboard contract: arrows browse and move, Home/End and\n * PageUp/PageDown navigate the open list, Enter accepts or submits,\n * Escape/Tab close, Backspace at the caret's leftmost spot drops the last\n * entry.\n */\n #comboboxKeydown(e) {\n switch (e.code) {\n case 'ArrowUp':\n case 'ArrowDown': {\n e.preventDefault();\n this.#arrowKeydown(e);\n break;\n }\n case 'Home': {\n if (this.#ddmenu.shown) {\n e.preventDefault();\n this.#ddmenu.jump(true);\n }\n break;\n }\n case 'End': {\n if (this.#ddmenu.shown) {\n e.preventDefault();\n this.#ddmenu.jump(false);\n }\n break;\n }\n case 'PageDown':\n case 'PageUp': {\n if (this.#ddmenu.shown) {\n e.preventDefault();\n this.#ddmenu.page('PageDown' === e.code);\n }\n break;\n }\n case 'Escape': {\n this.#abortdload();\n this.#close();\n break;\n }\n case 'NumpadEnter':\n case 'Enter': {\n if (!this.#ddmenu.shown) {\n return;\n }\n e.preventDefault();\n this.#editing = false;\n this.#display();\n this.#ddmenu.acceptSelection();\n break;\n }\n case 'Backspace': {\n if (this.#input.selectionStart === 0 && this.#input.selectionEnd === 0) {\n this.#removeKeyAt(this.#values.size - 1);\n }\n break;\n }\n case 'Tab': {\n this.#abortdload();\n this.#close(true);\n break;\n }\n }\n }\n #arrowKeydown(e) {\n const forward = 'ArrowDown' === e.code;\n if (e.altKey) {\n if (forward && !this.#ddmenu.shown) {\n this.#open();\n } else if (!forward && this.#ddmenu.shown) {\n this.#close();\n }\n return;\n }\n this.#ddmenu.moveOrShow(forward, () => this.#loader.load(this.#query()), [...this.#values.keys()]);\n }\n /**\n * @param {boolean} [commit] whether the user is leaving the field, which\n * only a blur or a Tab is: an emptied single select is then cleared\n */\n #close(commit = false) {\n this.#ddmenu.hide();\n const cleared =\n commit && this.#editing && !this.#multiple && this.#input.value === '' && this.#values.size !== 0;\n this.#editing = false;\n if (cleared) {\n this.#values.clear();\n this.#changed();\n }\n this.#display();\n }\n #open() {\n return this.#ddmenu.show(() => this.#loader.load(this.#query()), [...this.#values.keys()]);\n }\n #query() {\n return this.#editing ? this.#input.value : '';\n }\n /**\n * The text typed to search the vocabulary: what the dropdown was last\n * asked to match. `''` while the field is not being searched, its control\n * then showing the selection's label rather than a query.\n * @returns {string}\n */\n get query() {\n return this.#query();\n }\n #display() {\n const entry = this.#values.values().next().value;\n this.#input.value = this.#multiple ? '' : (entry?.label ?? '');\n }\n #selection() {\n return [...this.#values.values()];\n }\n #changed() {\n this.#syncBadges();\n this._notifyChange({ entry: this.entry });\n }\n #syncBadges() {\n const badges = this.#multiple\n ? Array.from(this.#values.entries()).map(([k, entry], index) => {\n const b = document.createElement('ful-badge');\n b.setAttribute('role', 'button');\n b.setAttribute('tabindex', index === 0 ? '0' : '-1');\n b.setAttribute('value', k);\n b.innerText = entry.label;\n return b;\n })\n : [];\n for (const b of this.#control.querySelectorAll(':scope > ful-badge')) {\n b.remove();\n }\n this.#input.before(...badges);\n if (!this.#editing) {\n this.#display();\n }\n this.#items.replaceChildren();\n (this.#itemstemplate ?? this.template('items'))\n .withOverlay({ entries: this.#selection() })\n .renderTo(this.#items);\n }\n /**\n * The selection is a Map keyed strictly, and keys arrive both as attribute\n * text and as whatever a loader's endpoint carries: every key entering it\n * goes through here. A key that does not decode is left as it is.\n */\n #coerceKey(k) {\n switch (this.declared('k-type')) {\n case 'number': {\n const n = k === '' ? Number.NaN : Number(k);\n return Number.isNaN(n) ? k : n;\n }\n case 'boolean': {\n if (k === true || k === 'true') {\n return true;\n }\n if (k === false || k === 'false') {\n return false;\n }\n return k;\n }\n default:\n return String(k);\n }\n }\n /**\n * Selects the keys, coerced by `k-type`: a key, an array of keys, or null or\n * undefined for none. The empty string is a key like any other. The keys\n * are applied at once, each labeled by itself until the loader's `exact`\n * answers; a key it does not answer is then dropped, a key removed in the\n * meantime stays removed, and a later assignment wins over the late answer.\n * A failed lookup keeps the keys and surfaces as an unhandled rejection.\n * No `change` is dispatched. A key containing a\n * comma, which the value attribute cannot carry, is kept and warned about\n * once per element.\n * @param {any} vs\n */\n set value(vs) {\n const keys = (vs == null ? [] : Array.isArray(vs) ? vs : [vs]).map((k) => this.#coerceKey(k));\n if (!this.#warnedComma && keys.some((k) => typeof k === 'string' && k.includes(','))) {\n this.#warnedComma = true;\n console.warn('a ful-select key cannot contain a comma: it is unexpressible in the value attribute', this);\n }\n this.#values = new Map(keys.map((k) => [k, { key: k, label: k, metadata: undefined }]));\n const claim = this.#assignments.take();\n if (!this.#control) {\n return;\n }\n this.#syncBadges();\n if (keys.length === 0) {\n return;\n }\n this.#resolve(keys, claim);\n }\n async #resolve(keys, claim) {\n const entries = await this.#loader.exact(...keys);\n if (claim.stale) {\n return;\n }\n const resolved = new Map(entries.map((e) => [this.#coerceKey(e.key), e]));\n for (const key of keys) {\n if (!this.#values.has(key)) {\n continue;\n }\n if (resolved.has(key)) {\n this.#values.set(key, resolved.get(key));\n } else {\n this.#values.delete(key);\n }\n }\n this.#syncBadges();\n }\n /**\n * The selected keys, in selection order, for a multiple select; the one\n * key, or null, for a single one.\n * @returns {any}\n */\n get value() {\n if (this.#multiple) {\n return [...this.#values.keys()];\n }\n return [...this.#values.keys()][0] ?? null;\n }\n /**\n * The selection as entries, the ones in the `change` detail: an array for\n * a multiple select, the one entry or null for a single one. An entry whose\n * label has not been resolved yet carries its key as the label.\n * @returns {SelectEntry|SelectEntry[]|null}\n */\n get entry() {\n const selection = this.#selection();\n if (this.#multiple) {\n return selection;\n }\n return selection[0] ?? null;\n }\n #useItemList;\n /**\n * Whether the select holds several keys: `value` and `entry` answer arrays,\n * the input stays empty and the selection shows as removable badges in the\n * control.\n * @returns {boolean}\n */\n get multiple() {\n return this.#multiple;\n }\n /** @param {boolean} v */\n set multiple(v) {\n this.#multiple = v;\n this.reflectTo('multiple', v);\n }\n /**\n * Whether the selection shows as the `items` list below the control instead\n * of as badges in it.\n * @returns {boolean}\n */\n get itemList() {\n return this.#useItemList;\n }\n /** @param {boolean} v */\n set itemList(v) {\n this.#useItemList = v;\n this.reflectTo('item-list', v);\n }\n}\n\nexport { Dropdown, Select, SelectLoader };\n","import { Attributes, Fragments } from '../../ftl/index.mjs';\nimport { Field } from './field.mjs';\n\n/**\n * A group of radios declared as `ful-radio` children. Each `ful-radio` becomes\n * a radio input carrying its attributes, labelled by its content; every\n * `input-*` attribute on the group is forwarded onto each radio as well. The\n * default slot is the `<legend>`, and `header` and `footer` slots frame the\n * list. The radios share a name of their own (derived from `name`, or minted\n * when there is none) and carry `form=\"\"`, so the group is the only element\n * the form sees. A radio's native `change` is stopped and republished as the\n * group's own.\n *\n * The host carries the `radiogroup` role, `aria-readonly`, `aria-required`,\n * `aria-invalid` and the description. The disabled and readonly claims act on\n * the group's `<fieldset>`, and readonly refuses every click inside it.\n * `focus()` lands on the first radio.\n */\nclass RadioGroup extends Field {\n /** @type {string[]} */\n static attributes = ['name', 'type'];\n static slots = true;\n /** @type {string} */\n static ROLE = 'radiogroup';\n static template = `\n <fieldset>\n <legend>\n {{{{ slots.default }}}}\n </legend>\n <header data-tpl-if=\"slots.header\">\n {{{{ slots.header }}}}\n </header>\n <ful-radio-list>\n <div class=\"label-wrapper\" data-tpl-each=\"inputsAndLabels\" data-tpl-var=\"ial\">\n <label>\n {{{{ ial[0] }}}}\n <div>{{{{ ial[1] }}}}</div>\n </label>\n </div>\n </ful-radio-list>\n <ful-field-error></ful-field-error>\n <footer data-tpl-if=\"slots.footer\">\n {{{{ slots.footer }}}}\n </footer>\n </fieldset>\n `;\n #fieldset;\n #firstRadio;\n #booleanType;\n /**\n * @param {{slots: any}} conf\n * @returns {any} the pieces: the first radio as the control, the fieldset\n * as the `claims` and `freeze` pieces, and the host as the `described` and\n * `announces` pieces\n */\n _build({ slots }) {\n const name = this.declared('name') ?? Attributes.uid('ful-radiogroup');\n const radioEls = Array.from(slots.default.querySelectorAll('ful-radio'));\n const inputsAndLabels = radioEls.map((el) => {\n const input = document.createElement('input');\n input.setAttribute('type', 'radio');\n Attributes.forward('input-', this, input);\n Attributes.forward('', el, input);\n input.setAttribute('name', `${name}-ignore`);\n input.setAttribute('form', ``);\n input.addEventListener('change', (evt) => {\n evt.stopPropagation();\n this._notifyChange();\n });\n const label = Fragments.fromChildNodes(el);\n return [input, label];\n });\n\n radioEls.forEach((el) => {\n el.remove();\n });\n const fragment = this.template().withOverlay({ name, slots, inputsAndLabels }).render();\n this.#fieldset = /** @type HTMLElement */ (fragment.firstElementChild);\n this.#firstRadio = fragment.querySelector('input[type=radio]');\n this.#booleanType = this.declared('type') === 'boolean';\n return {\n fragment,\n control: this.#firstRadio,\n error: fragment.querySelector('ful-field-error'),\n described: this,\n claims: this.#fieldset,\n announces: this,\n freeze: this.#fieldset,\n };\n }\n /**\n * The value of the checked radio, `null` when none is. Under\n * `type=\"boolean\"` it answers `true` for a radio whose value is `true` and\n * `false` for any other. Writing a value checks the radio carrying it, and\n * writing `null` or a value no radio carries clears the selection.\n * @type {string | boolean | null}\n */\n get value() {\n /** @type {HTMLInputElement|null} */\n const checked = this.querySelector('input[type=radio]:checked');\n return checked ? (this.#booleanType ? checked.value === 'true' : checked.value) : null;\n }\n set value(value) {\n const radios = this.querySelectorAll(`input[type=radio]`);\n const clear = () => {\n radios.forEach((el) => {\n /** @type {HTMLInputElement} */ (el).checked = false;\n });\n };\n if (value === null) {\n clear();\n return;\n }\n /** @type {HTMLInputElement|null} */\n const el = this.querySelector(`input[type=radio][value=\"${CSS.escape(String(value))}\"]`);\n if (el === null) {\n clear();\n return;\n }\n el.checked = true;\n }\n}\n\nexport { RadioGroup };\n","import { Attributes } from '../../ftl/index.mjs';\nimport { Field } from './field.mjs';\n\n/**\n * A checkbox, or a switch with the `switch` role under `type=\"switch\"`. The\n * label is the default slot, pointed at the input with `for` and `id`, so a\n * click on it toggles the value. Every `input-*` attribute is forwarded onto\n * the input. The input's native `change` is stopped and republished as the\n * field's own. Readonly freezes the whole choice, label included: no click\n * inside it toggles the value while the claim holds.\n */\nclass Checkbox extends Field {\n /** @type {string[]} */\n static attributes = ['type'];\n /** @type {string[]} */\n static observed = ['value:bool'];\n static slots = true;\n static template = `\n <ful-choice data-tpl-switch=\"isSwitch\">\n <input type=\"checkbox\" data-tpl-role=\"isSwitch ? 'switch' : false\" form=\"\">\n <label>{{{{ slots.default }}}}</label>\n {{{{ slots.info }}}}\n </ful-choice>\n <ful-field-error></ful-field-error>\n `;\n #container;\n #input;\n /**\n * @param {{ slots: Record<string, DocumentFragment> | undefined }} conf\n * @returns {any} the pieces, the `ful-choice` container being the `freeze` piece\n */\n _build({ slots }) {\n const isSwitch = this.declared('type') === 'switch';\n const fragment = this.template().withOverlay({ slots, isSwitch }).render();\n this.#container = fragment.firstElementChild;\n this.#input = fragment.querySelector('input');\n Attributes.forward('input-', this, this.#input);\n this.#input.addEventListener('change', (evt) => {\n evt.stopPropagation();\n this._notifyChange();\n });\n const label = fragment.querySelector('label');\n return {\n fragment,\n control: this.#input,\n error: fragment.querySelector('ful-field-error'),\n label,\n freeze: this.#container,\n };\n }\n /**\n * Whether the box is checked. The `value` attribute is read with the `bool`\n * mapper, where only the text `true` means checked.\n * @type {boolean}\n */\n get value() {\n return this.#input.checked;\n }\n set value(value) {\n this.#input.checked = value;\n }\n}\n\nexport { Checkbox };\n","import { Attributes, Fragments, Localization, Nodes, ParsedElement, Rendering, Templates } from '../../ftl/index.mjs';\nimport { Claims } from '../claims.mjs';\n\n/**\n * @typedef {{ page: number, size: number }} TablePageRequest the zero based\n * index of the page and the number of rows in a page\n */\n/**\n * @typedef {{ sorter: string, order: string }} TableSortRequest the sort key\n * of a column and its direction, `asc` or `desc`\n */\n/**\n * @typedef {{ data: any[], size: number }} TablePageResponse the rows of the\n * requested page and the total number of rows across every page\n */\n/**\n * @typedef {{ load(pageRequest: TablePageRequest, sortRequest: TableSortRequest|null, filterRequest: Record<string, any>): Promise<TablePageResponse> }} TableRowLoader\n */\n\n/**\n * The sort control of a table header, `ful-sorter`: a `role=\"button\"` with\n * `tabindex=\"0\"`, activated by a click or by Enter, NumpadEnter or Space.\n *\n * Each activation dispatches `sort:requested` (bubbling, not cancelable) with\n * `detail.value` set to `{ sorter, order }`: `sorter` is the `sorter`\n * attribute, read once at the upgrade, and `order` is the one after the\n * current `order` in the cycle `asc`, `desc`, `null`. The button does not\n * change its own `order`: whoever handles the event sets it, which `ful-table`\n * does once the sorted page has loaded.\n */\nclass SortButton extends ParsedElement {\n static attributes = ['sorter'];\n static observed = ['order'];\n #order;\n render() {\n const sorter = this.declared('sorter');\n const orders = ['asc', 'desc', null];\n this.setAttribute('role', 'button');\n this.setAttribute('tabindex', '0');\n this.addEventListener('click', () => {\n const nextOrder = orders[(orders.indexOf(this.order) + 1) % 3];\n this.dispatchEvent(\n new CustomEvent('sort:requested', {\n bubbles: true,\n cancelable: false,\n detail: {\n value: { sorter, order: nextOrder },\n },\n }),\n );\n });\n this.addEventListener('keydown', (/** @type any */ evt) => {\n if (!['Enter', 'NumpadEnter', 'Space'].includes(evt.code)) {\n return;\n }\n evt.preventDefault();\n this.click();\n });\n }\n\n /**\n * The direction the column is sorted in, `null` when unsorted.\n * @returns {string|null}\n */\n get order() {\n return this.#order || null;\n }\n\n /**\n * Reflects the direction to the `order` attribute and sets `aria-sort` on\n * the enclosing `<th>`, if any: `ascending` for `asc`, `descending` for any\n * other non-empty value, removed for an empty one.\n * @param {string|null} value an empty string or `null` means unsorted\n */\n set order(value) {\n this.#order = value || null;\n this.reflectTo('order', this.#order);\n const th = this.closest('th');\n if (!th) {\n return;\n }\n Attributes.set(th, 'aria-sort', this.#order ? ('asc' === this.#order ? 'ascending' : 'descending') : null);\n }\n}\n\n/**\n * The pager, `ful-pagination`: a previous button, a window of page buttons\n * around the current page, a next button, a reload button and a line saying\n * which page of how many is shown.\n *\n * The window holds at most `pages` buttons (read once at the upgrade, default 5),\n * centred on the current page and shifted back on the last pages so it stays\n * full. The current page's button carries `aria-current=\"page\"` and stays\n * enabled. Previous and next are disabled where there is no page to go to.\n *\n * A click on an enabled button other than the current page dispatches\n * `page:requested` (bubbling, not cancelable) with `detail.value` the zero based\n * index of the page asked for; the reload button asks for the current page.\n * The pager does not move itself: whoever handles the event calls `update`,\n * which `ful-table` does once the page has loaded.\n *\n * The icons are the `ful-icon` names in `Pagination.config`.\n */\nclass Pagination extends ParsedElement {\n static observed = ['total:number', 'current:number'];\n static attributes = ['pages:number'];\n static config = {\n prevIcon: 'chevron-left',\n nextIcon: 'chevron-right',\n reloadIcon: 'arrow-clockwise',\n };\n static template = `\n <ful-pagination-bar role=\"navigation\" data-tpl-aria-label=\"#l10n:t('pagination.navigation')\">\n <ul>\n <li data-ref=\"index\"> {{ #l10n:t('pagination.showing', { 'current': curr.label, 'total': total }) }}</li>\n <li data-ref=\"reload\"><button type=\"button\" data-tpl-aria-label=\"#l10n:t('pagination.reload')\"><ful-icon data-tpl-name=\"config.reloadIcon\" aria-hidden=\"true\"></ful-icon></button></li>\n <li data-ref=\"prev\">\n <button type=\"button\" data-tpl-disabled=\"prev.enabled ? false : true\" data-tpl-aria-label=\"#l10n:t('pagination.previous')\" data-tpl-data-page=\"prev.index\">\n <ful-icon data-tpl-name=\"config.prevIcon\" aria-hidden=\"true\"></ful-icon>\n </button>\n </li>\n <li data-ref=\"page\" data-tpl-each=\"pages\" data-tpl-var=\"page\">\n <button type=\"button\" data-tpl-aria-current=\"curr.index == page.index ? 'page' : false\" data-tpl-data-page=\"page.index\" >\n {{ page.label }}\n </button>\n </li>\n <li data-ref=\"next\">\n <button type=\"button\" data-tpl-disabled=\"next.enabled ? false : true\" data-tpl-aria-label=\"#l10n:t('pagination.next')\" data-tpl-data-page=\"next.index\">\n <ful-icon data-tpl-name=\"config.nextIcon\" aria-hidden=\"true\"></ful-icon>\n </button>\n </li>\n </ul>\n </ful-pagination-bar>\n `;\n #total = 0;\n #current = 0;\n render() {\n this.addEventListener('click', (/** @type any */ evt) => {\n const el = evt.target.closest('button');\n if (!el || el.hasAttribute('disabled')) {\n return;\n }\n if (el.getAttribute('aria-current') === 'page') {\n return;\n }\n this.dispatchEvent(\n new CustomEvent('page:requested', {\n bubbles: true,\n cancelable: false,\n detail: {\n value: Number(el.dataset.page ?? this.#current),\n },\n }),\n );\n });\n }\n /**\n * Moves the pager to a page, a page count, or both, reflects both to their\n * attributes and repaints the bar once. A key left out keeps its value; a\n * `null` one becomes 0. A count below one is shown as one empty page.\n *\n * The bar is replaced on every repaint. When the focus was inside it, it\n * moves to the equivalent control of the new bar: the button of the same\n * page, else the same enabled control, else the current page's button.\n * @param {{ current?: number|null, total?: number|null }} [state] `current`\n * is the zero based index of the page shown, `total` the number of pages\n */\n update({ current: toCurrent, total: toTotal } = {}) {\n if (toCurrent !== undefined) {\n this.#current = toCurrent ?? 0;\n }\n if (toTotal !== undefined) {\n this.#total = toTotal ?? 0;\n }\n this.reflectTo('current', this.#current);\n this.reflectTo('total', this.#total);\n const current = this.#current;\n const total = this.#total;\n const maxRender = this.declared('pages') ?? 5;\n const pageCount = Math.max(total, 1);\n const hasPrev = current > 0;\n const hasNext = current + 1 < pageCount;\n const prev = { index: hasPrev ? current - 1 : null, enabled: hasPrev };\n const curr = { index: current, label: current + 1 };\n const next = { index: hasNext ? current + 1 : null, enabled: hasNext };\n const rendered = Math.max(1, Math.min(maxRender, pageCount));\n const first = Math.max(0, Math.min(current - Math.floor((rendered - 1) / 2), pageCount - rendered));\n const pages = Array.from({ length: rendered }, (_, offset) => ({\n index: first + offset,\n label: first + offset + 1,\n }));\n const focused = this.contains(document.activeElement)\n ? /** @type HTMLElement */ (document.activeElement).closest('li')?.getAttribute('data-ref')\n : null;\n const page = focused === 'page' ? /** @type any */ (document.activeElement).dataset.page : null;\n this.template().withOverlay({ total: pageCount, prev, curr, next, pages }).renderTo(this);\n if (!focused) {\n return;\n }\n const back =\n (page === null ? null : this.querySelector(`li[data-ref=page] button[data-page=\"${page}\"]`)) ??\n this.querySelector(`li[data-ref=${focused}] button:not(:disabled)`) ??\n this.querySelector('li[data-ref=page] button[aria-current=page]');\n /** @type HTMLElement */ (back)?.focus();\n }\n /**\n * The number of pages, as last written.\n * @returns {number}\n */\n get total() {\n return this.#total;\n }\n /**\n * Same as `update({ total: value })`.\n * @param {number|null} value\n */\n set total(value) {\n this.update({ total: value });\n }\n /**\n * The zero based index of the page shown.\n * @returns {number}\n */\n get current() {\n return this.#current;\n }\n /**\n * Same as `update({ current: value })`.\n * @param {number|null} value\n */\n set current(value) {\n this.update({ current: value });\n }\n}\n\n/** Reads the schema declaration into the header and row templates a table renders from. */\nclass TableSchemaParser {\n /**\n * Builds a header `<tr>` and a row `<tr data-tpl-each=\"rows\">` from the\n * `<schema>` child of the slot. The `<schema>` attributes are copied onto\n * both rows. Each `<column>` becomes a `<th>` and a `<td>` carrying the\n * column's attributes except `title`, `sorter` and `order`, so a\n * `data-tpl-*` on a column applies to both cells; the two templates carry\n * `inHeaders` and `inRows` in their scope, so a column can tell them apart,\n * as in `data-tpl-if=\"inRows\"`. The header cell holds the `<title>` child\n * element of the column, else the text of its `title` attribute, wrapped\n * in a `ful-sorter` when the column declares `sorter` or `order`. The body\n * cell holds the column's remaining children.\n *\n * The column elements are consumed: their `<title>`, `title`, `sorter` and\n * `order` are removed and their children moved into the cells.\n * @param {DocumentFragment|Element|undefined} nodeOrFragment the `schema`\n * slot, undefined when the table has none\n * @param {ReturnType<ParsedElement['template']>} template the template the\n * header and row templates derive from, keeping its scope\n * @returns {{ headersTemplate: ReturnType<ParsedElement['template']>, rowsTemplate: ReturnType<ParsedElement['template']>, sort: { sorter: string|null, order: string|null } | null, length: number }}\n * `sort` is the initial sort, taken from the first column declaring both\n * `order` and `sorter` (a column with only `order` gets an arrow but no\n * initial sort), `null` when none does; `length` is the number of columns\n * @throws {Error} when the slot is missing or holds no `<schema>`\n */\n static parse(nodeOrFragment, template) {\n const schema = nodeOrFragment ? Nodes.queryChildren(nodeOrFragment, 'schema') : null;\n if (!schema) {\n throw new Error('missing expected <schema>: ful-table needs a <template slot=\"schema\"> holding one');\n }\n const headersTr = document.createElement('tr');\n const rowsTr = document.createElement('tr');\n rowsTr.setAttribute('data-tpl-each', 'rows');\n for (const attr of schema.getAttributeNames()) {\n const value = schema.getAttribute(attr);\n headersTr.setAttribute(attr, value ?? '');\n rowsTr.setAttribute(attr, value ?? '');\n }\n const columns = Nodes.queryChildrenAll(schema, 'column');\n const sort =\n columns\n .filter((v) => v.hasAttribute('order') && v.hasAttribute('sorter'))\n .map((v) => ({ sorter: v.getAttribute('sorter'), order: v.getAttribute('order') }))[0] ?? null;\n for (const column of columns) {\n const maybeTitleTag = Nodes.queryChildren(column, 'title');\n const sorter = column.getAttribute('sorter');\n const order = column.getAttribute('order');\n const titleNode = maybeTitleTag ?? document.createTextNode(column.getAttribute('title') ?? '');\n maybeTitleTag?.remove();\n column.removeAttribute('sorter');\n column.removeAttribute('order');\n column.removeAttribute('title');\n const wrappedTitleNode =\n !sorter && !order\n ? titleNode\n : (() => {\n const fulSorter = document.createElement('ful-sorter');\n if (sorter) {\n fulSorter.setAttribute('sorter', sorter);\n }\n if (order) {\n fulSorter.setAttribute('order', order);\n }\n fulSorter.append(titleNode);\n return fulSorter;\n })();\n const th = document.createElement('th');\n const td = document.createElement('td');\n for (const attr of column.getAttributeNames()) {\n const value = column.getAttribute(attr);\n th.setAttribute(attr, value ?? '');\n td.setAttribute(attr, value ?? '');\n }\n th.append(wrappedTitleNode);\n td.append(...column.childNodes);\n headersTr.append(th);\n rowsTr.append(td);\n }\n\n return {\n headersTemplate: template\n .withOverlay({ inHeaders: true, inRows: false })\n .withFragment(Fragments.from(headersTr)),\n rowsTemplate: template.withOverlay({ inHeaders: false, inRows: true }).withFragment(Fragments.from(rowsTr)),\n sort,\n length: columns.length,\n };\n }\n}\n\n/** Serves a table's rows from an array held in memory, applying the sort and the paging itself. */\nclass InMemoryTableLoader {\n #data;\n /**\n * @param {any[]} data the rows\n */\n constructor(data) {\n this.#data = data;\n }\n /**\n * Sorts a copy of the rows by the `sorter` property, rows missing it last\n * in either direction and rows with equal values in their original order,\n * then slices the requested page. The filters are ignored.\n * @param {TablePageRequest} pageRequest\n * @param {{ sorter?: string|null, order?: string|null } | null} sortRequest\n * `order` `desc` sorts descending, anything else ascending; no `sorter`\n * keeps the original order\n * @param {Record<string, any>} filterRequest not read\n * @returns {Promise<TablePageResponse>}\n */\n async load(pageRequest, sortRequest, filterRequest) {\n const rows = this.#sorted(sortRequest);\n const begin = pageRequest.page * pageRequest.size;\n const end = begin + pageRequest.size;\n const page = rows.slice(begin, end);\n const totalElements = rows.length;\n return {\n data: page,\n size: totalElements,\n };\n }\n #sorted(sortRequest) {\n if (!sortRequest?.sorter) {\n return this.#data;\n }\n const { sorter, order } = sortRequest;\n const sign = order === 'desc' ? -1 : 1;\n return [...this.#data].sort((l, r) => {\n const a = l?.[sorter];\n const b = r?.[sorter];\n if (a === b) {\n return 0;\n }\n if (a == null) {\n return 1;\n }\n if (b == null) {\n return -1;\n }\n return (a < b ? -1 : 1) * sign;\n });\n }\n /**\n * Replaces the rows. The table shows them at its next load.\n * @param {any[]} data\n */\n update(data) {\n this.#data = data;\n }\n}\n\n/** Requests one page of rows from a url, passing the page, the sort and the filters to the endpoint. */\nclass RemoteTableLoader {\n #http;\n #url;\n #method;\n #responseMapper;\n /**\n * @param {{ request(method: string, url: string): any }} http the `http-client` component\n * @param {string} url\n * @param {string} method\n * @param {(response: any) => TablePageResponse} [responseMapper] turns the\n * parsed json body into the page response; the identity when omitted\n */\n constructor(http, url, method, responseMapper = (response) => response) {\n this.#http = http;\n this.#url = url;\n this.#method = method;\n this.#responseMapper = responseMapper;\n }\n /**\n * Sends the query parameters `page`, `size`, `sort` as `sorter,order`\n * (left out when `sortRequest` is null) and `filters` as a json object of\n * the filters with a truthy value (left out when there is none), and\n * answers the json body through the response mapper.\n * @param {TablePageRequest} pageRequest\n * @param {TableSortRequest|null} sortRequest\n * @param {Record<string, any>} filterRequest\n * @returns {Promise<TablePageResponse>} rejecting with what the client's\n * `fetchJson()` rejects with\n */\n async load(pageRequest, sortRequest, filterRequest) {\n const filters = Object.entries(filterRequest).filter(([k, v]) => v);\n return await this.#http\n .request(this.#method, this.#url)\n .param('page', pageRequest.page)\n .param('size', pageRequest.size)\n .param('sort', sortRequest ? `${sortRequest.sorter},${sortRequest.order}` : null)\n .param('filters', filters.length > 0 ? JSON.stringify(Object.fromEntries(filters)) : null)\n .fetchJson()\n .then((response) => this.#responseMapper(response));\n }\n}\n\n/**\n * Builds the table's loader from its attributes: an in-memory one, or the\n * remote loader over src.\n *\n * A component registered under the `loader` attribute replaces this one and\n * must implement `load(pageRequest, sortRequest, filterRequest)`, answering\n * `{ data, size }`: the rows of the requested page and the total count of\n * rows. `pageRequest` carries the page index and its size, `sortRequest` the column and direction, and\n * `filterRequest` the values of the filters in the slot.\n */\nclass TableLoader {\n /**\n * A table with a `src` attribute gets a `RemoteTableLoader` sending through\n * the `http-client` component with the `method` attribute or `GET`, and\n * mapping the response through the component named by `response-mapper`,\n * if any. A table without `src` gets an empty `InMemoryTableLoader`, which\n * `withLoader` reaches to give it rows.\n * @param {Element & { component(name: string): any }} el the table\n * @param {unknown} [conf] not read\n * @returns {InMemoryTableLoader | RemoteTableLoader}\n */\n static create(el, conf) {\n const url = el.getAttribute('src');\n if (url) {\n const http = el.component('http-client');\n const method = el.getAttribute('method') ?? 'GET';\n const responseMapper = el.hasAttribute('response-mapper')\n ? el.component(/** @type {string} */ (el.getAttribute('response-mapper')))\n : (/** @type any */ response) => response;\n return new RemoteTableLoader(http, url, method, responseMapper);\n }\n return new InMemoryTableLoader([]);\n }\n}\n\n/**\n * A table, `ful-table`, loading its rows a page at a time from a loader, with\n * a header sorter per sortable column, a `ful-pagination` under it and an\n * optional filter form.\n *\n * The loader is the component named by `loader`, default `loaders:table`\n * (see `TableLoader`). The `schema` slot declares the columns (see\n * `TableSchemaParser.parse`); the `filters` slot is wrapped in a `ful-form`,\n * whose values are the filter request; the `caption`, `footer` and `empty`\n * slots go in the table's caption, its `<tfoot>` and the panel shown for a\n * load answering no rows. Attributes starting with `table-` are forwarded,\n * without the prefix, to the inner `<table>`.\n *\n * With `autoload` the first load starts at the upgrade, which does not wait\n * for it. Without it the table shows an initial panel until `load`,\n * `reload` or `resetWithFilter` is called.\n *\n * Inside the table a `page:requested` loads that page with the current size,\n * sort and filters; a `sort:requested` loads the current page with the new\n * sort (none for a `null` order) and, once that load is the one showing, sets\n * the order of the sorter that asked and clears the others; a `submit:success`\n * of the filter form loads the first page with the submitted request as the\n * filters. The loads these start, and the autoload, are not awaited by\n * anything: a failure shows the error panel and its rejection is unhandled.\n */\nclass Table extends ParsedElement {\n /** Read once at the upgrade. */\n static attributes = ['loader', 'autoload:presence'];\n /** These stay live after the upgrade: see `pageSize`, `src` and `method`. */\n static observed = ['page-size:number', 'src', 'method'];\n static slots = true;\n static config = {\n searchIcon: 'search',\n emptyIcon: 'inbox',\n };\n static template = `\n <ful-form data-tpl-if=\"slots.filters\">\n {{{{ slots.filters }}}}\n </ful-form>\n <ful-table-wrapper>\n <table>\n <caption data-tpl-if=\"slots.caption\">{{{{ slots.caption }}}}</caption>\n <thead></thead>\n <tbody></tbody>\n <tbody data-ref=\"initial\">\n <tr>\n <td data-tpl-colspan=\"schema.length\">\n <ful-empty>\n <ful-icon data-tpl-if=\"config.searchIcon\" data-tpl-name=\"config.searchIcon\" aria-hidden=\"true\"></ful-icon>\n {{ #l10n:t('table.initial') }}\n </ful-empty>\n </td>\n </tr>\n </tbody>\n <tbody data-ref=\"empty\" hidden>\n <tr>\n <td data-tpl-colspan=\"schema.length\">\n <ful-empty data-tpl-if=\"slots.empty\" data-ref=\"empty-authors\"></ful-empty>\n <ful-empty data-tpl-if=\"!slots.empty\">\n <ful-icon data-tpl-if=\"config.emptyIcon\" data-tpl-name=\"config.emptyIcon\" aria-hidden=\"true\"></ful-icon>\n {{ #l10n:t('table.no-data') }}\n </ful-empty>\n </td>\n </tr>\n </tbody>\n <tbody data-ref=\"loading\" hidden>\n <tr>\n <td data-tpl-colspan=\"schema.length\">\n <ful-spinner class=\"big\" role=\"status\"><span class=\"ful-sr-only\">{{ #l10n:t('spinner.loading') }}</span></ful-spinner>\n </td>\n </tr>\n </tbody>\n <tbody data-ref=\"feedback\" hidden>\n <tr>\n <td data-tpl-colspan=\"schema.length\">\n <div role=\"alert\">\n <p>{{ #l10n:t('table.error') }}</p>\n <div data-ref=\"feedback-error\"></div>\n </div>\n </td>\n </tr>\n </tbody>\n <tfoot data-tpl-if=\"slots.footer\">\n {{{{ slots.footer }}}}\n </tfoot>\n </table>\n </ful-table-wrapper>\n <ful-pagination current=\"0\" total=\"1\"></ful-pagination>\n `;\n static templates = {\n row: `\n {{{{ schema.rowsTemplate.withOverlay({'rows': pageResponse.data}).render() }}}}\n `,\n };\n #loader;\n #schema;\n #body;\n #loading;\n #noAutoload;\n #empty;\n #emptyAuthors;\n #emptyTemplate;\n #feedback;\n #paginator;\n #sorters;\n /** @type {{ pageRequest: { page: number, size: number }, sortRequest: any, filterRequest: any }} */\n #latestRequest = { pageRequest: { page: 0, size: 10 }, sortRequest: null, filterRequest: {} };\n /** whether a load has been asked for, by autoload or by a caller */\n #loadRequested = false;\n #loads = new Claims();\n /** @type {{ src: string|null, method: string|null }} */\n #builtFrom = { src: null, method: null };\n /**\n * How many rows a page asks the loader for: the size the next load will\n * carry. Ten before the render.\n * @returns {number}\n */\n get pageSize() {\n return this.#latestRequest.pageRequest.size;\n }\n /**\n * Changes the page size and reloads from the first page, keeping the sort\n * and the filters. A table that has not loaded yet only records it:\n * writing the size is not a request to start loading, which is what\n * `autoload` and `reload()` are for. A write that does not change the size\n * does nothing. A write made before the render is replaced by the declared\n * `page-size` when the table renders.\n *\n * The reload is not awaited: a failure shows the error panel and its\n * rejection is unhandled.\n * @param {number|null|undefined} value absent or null is the default of\n * ten, so removing the attribute restores it\n */\n set pageSize(value) {\n const size = value ?? 10;\n if (size === this.#latestRequest.pageRequest.size) {\n return;\n }\n this.#latestRequest = { ...this.#latestRequest, pageRequest: { page: 0, size } };\n if (!this.#loadRequested) {\n return;\n }\n this.reload();\n }\n /**\n * The url the loader asks for rows, reflected as the `src` attribute.\n * @returns {string|null}\n */\n get src() {\n return this.getAttribute('src');\n }\n /**\n * Points the table at another url: the loader is built again through its\n * component's `create`, as at the render, and the table reloads from the\n * first page, keeping the size, the sort and the filters. A table that has\n * not loaded yet only rebuilds its loader. A write that does not change the\n * url does nothing.\n *\n * The reload is not awaited: a failure shows the error panel and its\n * rejection is unhandled.\n * @param {string|null|undefined} value null or undefined removes the url,\n * which the default loader answers with an empty in-memory loader\n */\n set src(value) {\n this.reflectTo('src', value ?? null);\n if (this.#followAttributes() && this.#loadRequested) {\n this.reload();\n }\n }\n /**\n * The http method the default loader sends with, reflected as the `method`\n * attribute; `GET` when absent.\n * @returns {string|null}\n */\n get method() {\n return this.getAttribute('method');\n }\n /**\n * Changes the http method the way `src` changes the url: the loader is\n * built again and the table reloads from the first page.\n * @param {string|null|undefined} value\n */\n set method(value) {\n this.reflectTo('method', value ?? null);\n if (this.#followAttributes() && this.#loadRequested) {\n this.reload();\n }\n }\n /**\n * Writes `src` and `method` together and loads once: the loader is built\n * again for the pair when either changed, the page going back to the first\n * one as a single write of either does, and the table then reloads as\n * `reload()` does, whether or not they changed. Unlike a write of either,\n * it loads a table that has not loaded yet.\n * @param {{ src?: string|null, method?: string|null }} attributes a name\n * left out keeps its value, null removes the attribute\n * @returns {Promise<void>} as `load`\n */\n async reconfigure(attributes) {\n for (const name of ['src', 'method']) {\n if (name in attributes) {\n this.reflectTo(name, attributes[name] ?? null);\n }\n }\n this.#followAttributes();\n return await this.reload();\n }\n #buildLoader() {\n this.#builtFrom = { src: this.getAttribute('src'), method: this.getAttribute('method') };\n this.#loader = this.component(this.declared('loader') ?? 'loaders:table').create(this);\n }\n /** @returns {boolean} whether the loader was built again */\n #followAttributes() {\n if (\n this.getAttribute('src') === this.#builtFrom.src &&\n this.getAttribute('method') === this.#builtFrom.method\n ) {\n return false;\n }\n this.#buildLoader();\n this.#latestRequest = { ...this.#latestRequest, pageRequest: { ...this.#latestRequest.pageRequest, page: 0 } };\n return true;\n }\n /**\n * @param {{ slots: Record<string, DocumentFragment> }} c\n * @returns {Promise<void>}\n * @throws {Error} when the `schema` slot is missing or holds no `<schema>`\n */\n async render({ slots }) {\n const template = this.template();\n const schema = TableSchemaParser.parse(slots.schema, template);\n const fragment = template.withOverlay({ slots, schema }).render();\n const tableWrapper = /** @type HTMLTableElement */ (Nodes.queryChildren(fragment, 'ful-table-wrapper'));\n const table = /** @type HTMLTableElement */ (tableWrapper.querySelector('table'));\n Attributes.forward('table-', this, table);\n this.#buildLoader();\n\n this.#schema = schema;\n this.#body = table.querySelector(':scope > tbody');\n this.#loading = table.querySelector(':scope > tbody[data-ref=loading]');\n this.#noAutoload = table.querySelector(':scope > tbody[data-ref=initial]');\n this.#empty = table.querySelector(':scope > tbody[data-ref=empty]');\n this.#emptyAuthors = this.#empty.querySelector('ful-empty[data-ref=empty-authors]');\n this.#emptyTemplate =\n slots.empty && !Fragments.isBlank(slots.empty) ? Templates.fromFragment(slots.empty) : null;\n this.#feedback = table.querySelector(':scope > tbody[data-ref=feedback]');\n this.#paginator = Nodes.queryChildren(fragment, 'ful-pagination');\n this.replaceChildren(fragment);\n const thead = /** @type HTMLTableSectionElement */ (this.querySelector('thead'));\n schema.headersTemplate.renderTo(thead);\n this.#sorters = thead.querySelectorAll('ful-sorter');\n await Rendering.waitForChildren(this);\n\n const maybeForm = /** @type any */ (Nodes.queryChildren(this, 'ful-form'));\n this.#latestRequest = {\n pageRequest: {\n page: 0,\n size: this.declared('page-size') ?? 10,\n },\n sortRequest: schema.sort,\n filterRequest: maybeForm?.values ?? {},\n };\n maybeForm?.addEventListener('submit:success', async (evt) => {\n await this.#loadPage(0, evt.detail.request);\n });\n this.addEventListener('page:requested', async (/** @type any */ e) => {\n await this.#loadPage(e.detail.value, this.#latestRequest.filterRequest);\n });\n this.addEventListener('sort:requested', async (/** @type any */ e) => {\n const sortRequest = e.detail.value.order ? e.detail.value : null;\n await this.load(this.#latestRequest.pageRequest, sortRequest, this.#latestRequest.filterRequest);\n if (this.#latestRequest.sortRequest !== sortRequest) {\n return;\n }\n this.#sorters.forEach((s) => {\n s.order = null;\n });\n e.target.order = e.detail.value.order;\n });\n if (this.declared('autoload')) {\n this.reload();\n }\n }\n\n /**\n * Loads the last request that loaded, or, before any has, the first page\n * with the declared size and sort and the values of the filters slot. A\n * size written through `pageSize` since then replaces the page with the\n * first one at that size.\n * @returns {Promise<void>} as `load`\n */\n async reload() {\n return await this.load(\n this.#latestRequest.pageRequest,\n this.#latestRequest.sortRequest,\n this.#latestRequest.filterRequest,\n );\n }\n /**\n * Asks the loader for a page and shows it.\n *\n * While the load runs the table carries `aria-busy=\"true\"`, and the rows\n * already shown stay; the spinner panel shows only when there are none.\n * When the loader answers, the rows and the pager are replaced, the empty\n * panel shows for an answer with no rows (the `empty` slot rendered with\n * `schema`, `pageRequest`, `filterRequest` and `pageResponse` in scope),\n * the request becomes the one\n * `reload` repeats, `aria-busy` is removed and `load:success` is\n * dispatched (bubbling, not cancelable) with `detail` set to\n * `{ pageRequest, sortRequest, filterRequest, response }`. A page beyond\n * the last one the answer reports is not shown: the last page is loaded\n * instead, and the returned promise settles with that load.\n *\n * When the loader rejects, the rows are removed, the error panel shows the\n * `reason` of each of the error's `problems`, one per line, or the error as text,\n * `aria-busy` is removed, `load:failure` is dispatched (bubbling, not\n * cancelable) with `detail` set to\n * `{ pageRequest, sortRequest, filterRequest, exception }`, and the\n * returned promise rejects with the same error.\n *\n * A load started after this one supersedes it: when this one's answer or\n * failure arrives it changes nothing, dispatches nothing and resolves.\n * @param {TablePageRequest} pageRequest\n * @param {TableSortRequest|null} sortRequest\n * @param {Record<string, any>} filterRequest\n * @returns {Promise<void>}\n * @throws what the loader rejects with, unless a newer load superseded this one\n */\n async load(pageRequest, sortRequest, filterRequest) {\n this.#loadRequested = true;\n const claim = this.#loads.take();\n this.#loading.toggleAttribute('hidden', this.#body.childElementCount > 0);\n this.#feedback.setAttribute('hidden', '');\n this.#noAutoload.setAttribute('hidden', '');\n this.#empty.setAttribute('hidden', '');\n this.setAttribute('aria-busy', 'true');\n let lastPage;\n try {\n const pageResponse = await this.#loader.load(pageRequest, sortRequest, filterRequest);\n if (claim.stale) {\n return;\n }\n lastPage = Math.max(0, Math.ceil(pageResponse.size / pageRequest.size) - 1);\n if (pageRequest.page <= lastPage) {\n this.#latestRequest = { pageRequest, sortRequest, filterRequest };\n this.#update(pageRequest, sortRequest, filterRequest, pageResponse);\n this.removeAttribute('aria-busy');\n this.dispatchEvent(\n new CustomEvent('load:success', {\n bubbles: true,\n cancelable: false,\n detail: { pageRequest, sortRequest, filterRequest, response: pageResponse },\n }),\n );\n return;\n }\n } catch (/** @type any */ error) {\n if (claim.stale) {\n return;\n }\n this.#loading.setAttribute('hidden', '');\n this.#body.replaceChildren();\n this.#feedback.removeAttribute('hidden');\n this.#feedback.querySelector('[data-ref=feedback-error]').textContent = Localization.of().failure(error);\n this.removeAttribute('aria-busy');\n this.dispatchEvent(\n new CustomEvent('load:failure', {\n bubbles: true,\n cancelable: false,\n detail: { pageRequest, sortRequest, filterRequest, exception: error },\n }),\n );\n throw error;\n }\n return await this.load({ page: lastPage, size: pageRequest.size }, sortRequest, filterRequest);\n }\n /**\n * Hands the loader to the callback, for runtime reconfigurations, such as\n * `update(rows)` on the in-memory loader. The loader exists from the\n * render on. Nothing is reloaded.\n * @template T\n * @param {(loader: any) => T | Promise<T>} fn\n * @returns {Promise<T>} what `fn` returns or resolves to\n */\n async withLoader(fn) {\n return await fn(this.#loader);\n }\n /**\n * Loads the first page with the given filters, keeping the size and the sort.\n * @param {Record<string, any>} filterRequest\n * @returns {Promise<void>} as `load`\n */\n async resetWithFilter(filterRequest) {\n return await this.#loadPage(0, filterRequest);\n }\n #loadPage(page, filterRequest) {\n return this.load(\n { page, size: this.#latestRequest.pageRequest.size },\n this.#latestRequest.sortRequest,\n filterRequest,\n );\n }\n #update(pageRequest, sortRequest, filterRequest, pageResponse) {\n const pages = Math.ceil(pageResponse.size / pageRequest.size);\n this.#loading.setAttribute('hidden', '');\n this.#body.replaceChildren(\n this.template('row')\n .withOverlay({\n schema: this.#schema,\n pageRequest,\n filterRequest,\n pageResponse,\n })\n .render(),\n );\n this.#empty.toggleAttribute('hidden', pageResponse.data.length !== 0);\n if (this.#emptyTemplate && pageResponse.data.length === 0) {\n this.#emptyAuthors.replaceChildren(\n this.#emptyTemplate\n .withOverlay({ schema: this.#schema, pageRequest, filterRequest, pageResponse })\n .render(),\n );\n }\n this.#paginator.update({ current: pageRequest.page, total: pages });\n }\n}\n\nexport { TableLoader, SortButton, Table, TableSchemaParser, Pagination };\n","/** how long, in milliseconds, a type-ahead search waits for its next character */\nconst TYPEAHEAD_WINDOW = 500;\n\n/**\n * Wires the keyboard protocol of a menu popover onto it.\n *\n * - As the menu opens, the focus moves to the item `current` answers, or to\n * the first item when it answers none.\n * - As the menu closes, the focus moves back to the invoker, but only when it\n * was inside the menu, so a close caused by a click elsewhere leaves it\n * where it went.\n * - ArrowDown and ArrowUp move the focus to the next and previous item,\n * wrapping at both ends; Home and End move it to the first and last.\n * - Enter, the numpad Enter and Space call `click()` on the focused item and\n * move the focus to the invoker. Closing the menu is left to the item's\n * click handling.\n * - Escape moves the focus to the invoker and leaves the close to the\n * platform.\n * - A printable character typed without Ctrl, Alt or Meta searches the\n * items' trimmed text, ignoring case, wrapping past the last item.\n * Characters typed within 500ms of each other add to one search. A search\n * of one character, or of one character repeated, moves the focus to the\n * next item after the focused one starting with it, so repeating a letter\n * cycles through those items; a longer search moves it to the first item,\n * from the focused one on, starting with the whole search. A search that\n * matches nothing leaves the focus where it is.\n *\n * The keys are read by `KeyboardEvent.code`, the typed characters by\n * `KeyboardEvent.key`. A handled key has its default prevented, except\n * Escape and a search that matched nothing. A key whose target is not inside\n * an item is ignored.\n *\n * `items` answers the items in the order they are walked, and is called on\n * every gesture, so a menu that fills itself later needs no rewiring.\n *\n * @param {() => HTMLElement|null} invoker answers the element the menu belongs to\n * now, where the focus goes back; called on every gesture, so a menu shared\n * by several invokers hands the focus back to the one that opened it\n * @param {HTMLElement} menu the `[popover]` holding the items\n * @param {{items: () => HTMLElement[], current?: () => HTMLElement|null|undefined}} conf\n * `items` answers the items; `current` answers the item an opening focuses\n */\nconst wireMenuKeys = (invoker, menu, { items, current = () => null }) => {\n let typed = '';\n let typedAt = 0;\n menu.addEventListener('beforetoggle', (/** @type any */ evt) => {\n if (evt.newState === 'closed' && menu.contains(document.activeElement)) {\n invoker()?.focus();\n }\n });\n menu.addEventListener('toggle', (/** @type any */ evt) => {\n if (evt.newState !== 'open') {\n return;\n }\n const all = items();\n (current() ?? all[0])?.focus();\n });\n menu.addEventListener('keydown', (evt) => {\n const target = /** @type HTMLElement */ (evt.target);\n const all = items();\n const item = all.find((candidate) => candidate === target || candidate.contains(target));\n if (!item) {\n return;\n }\n const at = all.indexOf(item);\n switch (evt.code) {\n case 'ArrowDown': {\n evt.preventDefault();\n all[(at + 1) % all.length]?.focus();\n return;\n }\n case 'ArrowUp': {\n evt.preventDefault();\n all[(at - 1 + all.length) % all.length]?.focus();\n return;\n }\n case 'Home': {\n evt.preventDefault();\n all[0]?.focus();\n return;\n }\n case 'End': {\n evt.preventDefault();\n all[all.length - 1]?.focus();\n return;\n }\n case 'Enter':\n case 'NumpadEnter':\n case 'Space': {\n evt.preventDefault();\n item.click();\n invoker()?.focus();\n return;\n }\n case 'Escape': {\n invoker()?.focus();\n return;\n }\n }\n if (evt.key.length !== 1 || evt.ctrlKey || evt.altKey || evt.metaKey) {\n return;\n }\n const now = Date.now();\n typed = now - typedAt > TYPEAHEAD_WINDOW ? evt.key : typed + evt.key;\n typedAt = now;\n const wanted = typed.toLowerCase();\n const repeated = [...wanted].every((character) => character === wanted[0]);\n const search = repeated ? wanted[0] : wanted;\n const from = repeated ? at + 1 : at;\n const found = [...all.slice(from), ...all.slice(0, from)].find((candidate) =>\n (candidate.textContent ?? '').trim().toLowerCase().startsWith(search),\n );\n if (found) {\n evt.preventDefault();\n found.focus();\n }\n });\n};\n\nexport { wireMenuKeys };\n","import { Attributes } from '../../ftl/index.mjs';\nimport { Anchors } from '../disclosures/anchors.mjs';\nimport { wireMenuKeys } from '../disclosures/menu-keys.mjs';\n\n/**\n * An invoker button paired with the `ul[popover][role=menu]` that follows it:\n * the chrome behind every filter's operator, sensitivity and boolean value.\n *\n * It fills the menu from a vocabulary, wires it the first time more than one\n * choice survives the whitelist, pins the button to a static glyph when a\n * single one does, takes the shared menu keyboard protocol, and keeps the\n * button's value, glyph and aria-label in step. A pick that changes the value\n * calls back; the host decides what that means.\n *\n * The button's `value` attribute is the store, as it is for a native control:\n * the menu protocol finds the current item by it, and nothing mirrors it.\n */\nclass ChoiceButton {\n /**\n * The declared choices narrowed to a vocabulary, in the declared order.\n * When none of them is in the vocabulary, or none is declared, the answer\n * is a copy of the whole vocabulary.\n * @param {string[] | null | undefined} declared\n * @param {string[]} vocabulary\n * @returns {string[]}\n */\n static narrow(declared, vocabulary) {\n const narrowed = (declared ?? []).filter((choice) => vocabulary.includes(choice));\n return narrowed.length > 0 ? narrowed : [...vocabulary];\n }\n #button;\n #menu;\n #vocabulary;\n #glyphs;\n #labelFor;\n #display;\n #interactive;\n #onPick;\n #allowed;\n #claimed = false;\n #wired = false;\n /**\n * Takes the button's next sibling as its menu and listens for picks on it.\n * The menu is neither filled nor wired until `allowed` is first written.\n *\n * A click on an item, while `interactive()` answers true, sets the value,\n * hides the menu and, when the value changed, calls `onPick`.\n * @param {HTMLElement} button the invoker, whose next sibling is its menu\n * @param {{vocabulary: string[], glyphs?: Record<string,string>, labelFor?: (v: string) => string,\n * display?: ((v: string) => string)|null, interactive?: () => boolean, onPick?: (v: string) => void}} conf\n * `vocabulary` lists every choice; `glyphs` maps a choice to its compact\n * glyph; `labelFor` answers the localized word, used as the button's\n * `aria-label` and beside the glyph in the menu (the choice itself by\n * default); `display` answers the button's text (by default the glyph,\n * or the choice where it has none); `interactive` is asked before a\n * pick is taken; `onPick` receives a pick that changed the value\n */\n constructor(\n button,\n { vocabulary, glyphs = {}, labelFor = (v) => v, display = null, interactive = () => true, onPick = () => {} },\n ) {\n this.#button = button;\n this.#menu = /** @type HTMLElement */ (button.nextElementSibling);\n this.#vocabulary = vocabulary;\n this.#glyphs = glyphs;\n this.#labelFor = labelFor;\n this.#display = display ?? ((choice) => glyphs[choice] ?? choice);\n this.#interactive = interactive;\n this.#onPick = onPick;\n this.#allowed = [...vocabulary];\n this.#menu.addEventListener('click', (evt) => {\n const target = /** @type HTMLElement */ (evt.target);\n const item = /** @type HTMLElement | null */ (target.closest('li > a'));\n if (!item || !this.#interactive()) {\n return;\n }\n const picked = /** @type string */ (item.getAttribute('value'));\n const previous = this.value;\n this.value = picked;\n /** @type any */ (this.#menu).hidePopover?.();\n if (previous !== picked) {\n this.#onPick(picked);\n }\n });\n }\n /**\n * The choices the menu offers. Writing it narrows the declared set with\n * `narrow`, refills the menu, wires the popover and the menu keyboard the\n * first time more than one choice is allowed, and updates the button's\n * disabled state and popup attributes. When one choice is left the button\n * is pinned and the value is set to it.\n * @type {string[]}\n */\n get allowed() {\n return this.#allowed;\n }\n set allowed(declared) {\n this.#allowed = ChoiceButton.narrow(declared, this.#vocabulary);\n this.#fill();\n if (!this.#wired && this.#allowed.length > 1) {\n this.#wire();\n this.#wired = true;\n }\n this.#sync();\n if (this.pinned) {\n this.value = this.#allowed[0];\n }\n }\n /**\n * The choice when the menu allows it, otherwise the first allowed one.\n * @param {string|null} choice\n * @returns {string}\n */\n preferring(choice) {\n return choice !== null && this.#allowed.includes(choice) ? choice : this.#allowed[0];\n }\n /**\n * Whether fewer than two choices are allowed. A pinned button is disabled,\n * opens no menu and shows the single choice as its value.\n * @returns {boolean}\n */\n get pinned() {\n return this.#allowed.length < 2;\n }\n /**\n * The host's fixed claim: hides the button with the `hidden` attribute\n * while `value` keeps answering.\n * @param {boolean} fixed\n */\n set fixed(fixed) {\n this.#button.toggleAttribute('hidden', !!fixed);\n }\n /**\n * The current choice, stored as the button's `value` attribute, where the\n * menu keyboard also finds it. Writing it sets the button's text from\n * `display`, its `aria-label` from `labelFor`, and `aria-checked` on the\n * menu item carrying it. It does not call `onPick`.\n * @type {string | null}\n */\n get value() {\n return this.#button.getAttribute('value');\n }\n set value(choice) {\n this.#button.setAttribute('value', /** @type {string} */ (choice));\n this.#button.textContent = this.#display(choice);\n Attributes.set(this.#button, 'aria-label', this.#labelFor(choice));\n this.#mark();\n }\n #mark() {\n const current = this.value;\n for (const item of this.#items()) {\n item.setAttribute('aria-checked', String(item.getAttribute('value') === current));\n }\n }\n /**\n * The host's disabled claim. The button is disabled while either the claim\n * or the pin holds, so lifting one does not enable it while the other holds.\n * @param {boolean} claimed\n */\n set claimed(claimed) {\n this.#claimed = claimed;\n this.#sync();\n }\n #fill() {\n this.#menu.replaceChildren(\n ...this.#allowed.map((choice) => {\n const li = document.createElement('li');\n li.setAttribute('role', 'none');\n const a = document.createElement('a');\n a.setAttribute('role', 'menuitemradio');\n a.setAttribute('tabindex', '-1');\n a.setAttribute('value', choice);\n const word = this.#labelFor(choice);\n const glyph = this.#glyphs[choice] ?? choice;\n if (word === choice && glyph === choice) {\n a.innerText = choice;\n } else {\n const glyphSpan = document.createElement('span');\n glyphSpan.innerText = glyph;\n const wordSpan = document.createElement('span');\n wordSpan.innerText = word;\n a.append(glyphSpan, wordSpan);\n }\n li.append(a);\n return li;\n }),\n );\n this.#mark();\n }\n #sync() {\n const pinned = this.pinned;\n this.#button.toggleAttribute('disabled', pinned || this.#claimed);\n Attributes.set(this.#button, 'aria-haspopup', pinned ? null : 'true');\n Attributes.set(this.#button, 'aria-expanded', pinned ? null : 'false');\n if (pinned) {\n this.#button.removeAttribute('popovertarget');\n } else if (this.#menu.id) {\n this.#button.setAttribute('popovertarget', this.#menu.id);\n }\n }\n #items() {\n return Array.from(this.#menu.querySelectorAll('li > a'), (a) => /** @type HTMLAnchorElement */ (a));\n }\n #wire() {\n Anchors.wire(this.#button, this.#menu, { prefix: 'ful-filter-menu', invoke: true, expanded: true });\n wireMenuKeys(() => this.#button, this.#menu, {\n items: () => this.#items(),\n current: () => this.#items().find((a) => a.getAttribute('value') === this.value),\n });\n }\n}\n\nexport { ChoiceButton };\n","import { Localization } from '../../ftl/index.mjs';\nimport { ChoiceButton } from './choice-button.mjs';\nimport { Field } from './field.mjs';\nimport { Instant } from './temporals.mjs';\nimport { Input } from './input.mjs';\nimport { Select } from './select.mjs';\n\nconst GLYPHS = {\n EQ: '=',\n NEQ: '≠',\n LT: '<',\n GT: '>',\n LTE: '≤',\n GTE: '≥',\n BETWEEN: '↔',\n CONTAINS: '…a…',\n STARTS_WITH: 'a…',\n ENDS_WITH: '…a',\n};\nconst COMPARE_OPERATORS = ['EQ', 'NEQ', 'LT', 'GT', 'LTE', 'GTE', 'BETWEEN'];\nconst TEXT_OPERATORS = [...COMPARE_OPERATORS, 'CONTAINS', 'STARTS_WITH', 'ENDS_WITH'];\nconst SENSITIVITIES = ['IGNORE_CASE', 'CASE_SENSITIVE'];\n\nconst SENSITIVITY_GLYPHS = {\n IGNORE_CASE: 'aa',\n CASE_SENSITIVE: 'Aa',\n};\n\nconst { t } = Localization.of();\nconst operatorLabel = (op) => t(`filters.op.${op}`);\nconst sensitivityLabel = (sensitivity) => t(`filters.sensitivity.${sensitivity}`);\nconst booleanValueLabel = (token) => t(token === '' ? 'filters.boolean.any' : `filters.boolean.${token}`);\n\n/**\n * What a filter currently filters on, in the words a reader sees: the text of\n * its label, the operator in force (null for a set membership filter declaring\n * none) and the non-empty operands as text. The operands are what the controls\n * show, such as a select's labels, not the keys the value carries.\n * @typedef {{ label: string|null, operator: string|null, operands: string[] }} FilterCriterion\n */\n\nconst labelTextOf = (filter) => filter.querySelector(':scope > label')?.textContent.trim() || null;\n\n/**\n * Pins a button to the choice the singular attribute names, hiding it. A name\n * outside the vocabulary pins the fallback instead, and declaring the plural\n * beside the singular is ignored: both are warned about.\n * @param {HTMLElement & { declared(name: string): any }} el\n * @param {ChoiceButton} button\n * @param {{ singular: string, plural: string, vocabulary: string[], fallback: string }} names\n */\nconst fixChoice = (el, button, { singular, plural, vocabulary, fallback }) => {\n const fixed = el.declared(singular);\n if (fixed === null) {\n return;\n }\n if (el.hasAttribute(plural)) {\n console.warn(`${el.localName}: ${singular} fixes what ${plural} offers a menu for, the plural is ignored`, el);\n }\n const known = vocabulary.includes(fixed);\n if (!known) {\n console.warn(`${el.localName}: '${fixed}' is not one of its ${plural}, the default is pinned instead`, el);\n }\n button.allowed = [known ? fixed : fallback];\n button.fixed = true;\n};\n\n/** @returns {FilterCriterion|null} */\nconst asCriterion = (label, operator, operands) => {\n const shown = operands.filter((o) => o !== null && o !== undefined && `${o}` !== '');\n return shown.length === 0 ? null : { label, operator, operands: shown.map((o) => `${o}`) };\n};\n\n/**\n * The shared shape of every operator-and-operands filter: an operator menu, one\n * or two operands of the type the subclass declares, and a tuple that mirrors\n * the data-jpa compare annotations.\n *\n * The value is `[operator, operand]`, or `[operator, from, to]` for BETWEEN,\n * the only operator that shows the second operand. The `operators` attribute\n * whitelists the menu; the `operator` attribute fixes the operator for the\n * element's life instead, hiding its button, and every tuple then carries it.\n * Declaring both warns and the singular wins; a fixed name outside the\n * vocabulary warns and fixes the default operator.\n *\n * Both operands mirror the disabled and readonly claims, and readonly also\n * refuses the clicks that would open the operator menu. The change event fires\n * when either operand changes or a different operator is picked.\n */\nclass CompareFilter extends Input {\n static observed = ['value:json', 'operators:csv'];\n static attributes = ['operator'];\n static template = `\n <label>{{{{ slots.default }}}}</label>\n {{{{ slots.info }}}}\n <ful-control-group>\n <ful-affix data-tpl-if=\"slots.before\">{{{{ slots.before }}}}</ful-affix>\n <ful-affix>\n <button data-ref=\"operator\" type=\"button\" form=\"\" aria-expanded=\"false\" aria-haspopup=\"true\"></button>\n <ul popover role=\"menu\"></ul>\n </ful-affix>\n <ful-control>\n <input data-ref=\"value1\" data-tpl-type=\"type\" form=\"\">\n <input data-ref=\"value2\" data-tpl-type=\"type\" form=\"\" hidden>\n </ful-control>\n <ful-affix data-tpl-if=\"slots.after\">{{{{ slots.after }}}}</ful-affix>\n </ful-control-group>\n <ful-field-error></ful-field-error>\n `;\n _operator;\n _container;\n _value1;\n _value2;\n _build(conf) {\n const pieces = super._build(conf);\n const fragment = pieces.fragment;\n this._container = fragment.querySelector('ful-control-group');\n this._value1 = fragment.querySelector('[data-ref=value1]');\n this._value2 = fragment.querySelector('[data-ref=value2]');\n this._operator = new ChoiceButton(/** @type HTMLElement */ (fragment.querySelector('[data-ref=operator]')), {\n vocabulary: this._vocabulary(),\n glyphs: GLYPHS,\n labelFor: operatorLabel,\n interactive: () => this._interactive(),\n onPick: () => {\n this._syncBetween();\n this._notifyChange();\n },\n });\n this.operators = this.declared('operators');\n if (this._operator.value === null) {\n this._showDefaultOperator();\n }\n fixChoice(this, this._operator, {\n singular: 'operator',\n plural: 'operators',\n vocabulary: this._vocabulary(),\n fallback: this._defaultOperator(),\n });\n return { ...pieces, freeze: this._container, also: [this._value2] };\n }\n _showDefaultOperator() {\n this._showOperator(this._operator.preferring(this._defaultOperator()));\n }\n /**\n * Restores the declared `value` tuple, operator included, as a field reset\n * does. Without a `value` attribute it empties the operands and also shows\n * the default operator again, or the first whitelisted one where the\n * default is not allowed.\n */\n formResetCallback() {\n super.formResetCallback();\n if (!this.hasAttribute('value')) {\n this._showDefaultOperator();\n }\n }\n /**\n * The native input type both operands render with.\n * @returns {string}\n */\n _type() {\n return 'text';\n }\n /**\n * Converts an operand from its input's value to the form the tuple carries.\n * @param {string} v\n * @returns {string|null}\n */\n _serialize(v) {\n return v;\n }\n /**\n * Converts an operand from the tuple to the value its input shows.\n * @param {string} v\n * @returns {string}\n */\n _deserialize(v) {\n return v;\n }\n /**\n * The operator shown on render and after a valueless reset, when the whitelist allows it.\n * @returns {string}\n */\n _defaultOperator() {\n return 'EQ';\n }\n /**\n * Every operator the filter knows, which `operators` narrows.\n * @returns {string[]}\n */\n _vocabulary() {\n return COMPARE_OPERATORS;\n }\n _declaredOperators;\n /**\n * The operators the menu offers, narrowed to the vocabulary: an empty list,\n * or one where no name is known, offers all of it. A single operator pins\n * the button, and an assigned tuple then carries that operator whatever it\n * names. An assignment made before the upgrade is held narrowed and\n * answered back until the render, when the `operators` attribute is applied\n * over it, an absent attribute meaning the whole vocabulary. Assignments are\n * ignored while the `operator` attribute fixes the operator.\n * @returns {string[]|undefined} undefined before the upgrade when nothing was assigned\n */\n get operators() {\n return this._operator ? this._operator.allowed : this._declaredOperators;\n }\n /** @param {string[]|null} declared */\n set operators(declared) {\n if (this.declared('operator') !== null) {\n return;\n }\n if (!this._operator) {\n this._declaredOperators = ChoiceButton.narrow(declared, this._vocabulary());\n return;\n }\n this._operator.allowed = declared;\n this._syncBetween();\n }\n /**\n * The filter's tuple, `[operator, operand]` or `[operator, from, to]` for\n * BETWEEN, each operand converted by `_serialize` (an ISO instant for the\n * instant filter). Null while any operand the operator uses is empty.\n * @returns {any[]|null}\n */\n get value() {\n return this._tuple();\n }\n /**\n * Shows a tuple: the operator it names, unless a pinned or fixed operator\n * replaces it, and its operands, an operand missing from a shorter tuple\n * leaving its input empty. Null or undefined empties both operands and\n * keeps the operator.\n * @param {any[]|null|undefined} v\n */\n set value(v) {\n this._applyTuple(v);\n }\n _tuple() {\n const operator = this._operator.value;\n const values = this.#operands();\n return values.some((v) => v === '') ? null : [operator, ...values.map((v) => this._serialize(v))];\n }\n _applyTuple(v) {\n if (v == null) {\n this._value1.value = '';\n this._value2.value = '';\n return;\n }\n const [declared, ...values] = v;\n const operator = this._operator.pinned ? this._operator.allowed[0] : declared;\n this._showOperator(operator);\n this._value1.value = values[0] ? this._deserialize(values[0]) : (values[0] ?? '');\n this._value2.value = values[1] ? this._deserialize(values[1]) : (values[1] ?? '');\n }\n _showOperator(operator) {\n this._operator.value = operator;\n this._syncBetween();\n }\n /** Shows the second operand only while the operator is BETWEEN. */\n _syncBetween() {\n this._value2.toggleAttribute('hidden', this._operator.value !== 'BETWEEN');\n }\n /**\n * The operator and the operands the operator uses, as their inputs show\n * them rather than as serialized: a date filter describes what is in its\n * control, not the ISO string it sends. Null while every one of those\n * operands is empty, so a BETWEEN with one bound answers that bound while\n * its value is still null.\n * @returns {FilterCriterion|null}\n */\n get criterion() {\n return asCriterion(labelTextOf(this), this._operator.value, this.#operands());\n }\n #operands() {\n return this._operator.value === 'BETWEEN' ? [this._value1.value, this._value2.value] : [this._value1.value];\n }\n /**\n * The field's own disabled claim. Setting it disables both operands and\n * every menu button the filter composes; a button pinned to one choice\n * stays disabled when the claim is lifted.\n * @returns {boolean}\n */\n get disabled() {\n return super.disabled;\n }\n /** @param {boolean} d */\n set disabled(d) {\n super.disabled = d;\n for (const choice of this._choices()) {\n choice.claimed = d;\n }\n }\n /**\n * The menu buttons the filter composes, which the disabled claim reaches. A\n * subclass adding a menu appends its own to the base's.\n * @returns {ChoiceButton[]}\n */\n _choices() {\n return [this._operator].filter((c) => c);\n }\n}\n\n/**\n * The compare filter over ISO instants, defaulting to LTE. The operands are\n * shown as local date and time in the page's timezone and carried in the tuple\n * as UTC ISO instants.\n */\nclass InstantFilter extends CompareFilter {\n _defaultOperator() {\n return 'LTE';\n }\n _type() {\n return 'datetime-local';\n }\n _serialize(v) {\n return Instant.localToIso(v);\n }\n _deserialize(v) {\n return Instant.isoToLocal(v);\n }\n}\n\n/** The compare filter over dates. */\nclass LocalDateFilter extends CompareFilter {\n _type() {\n return 'date';\n }\n}\n\n/** The compare filter over numbers. */\nclass NumberFilter extends CompareFilter {\n _type() {\n return 'number';\n }\n}\n\n/**\n * The compare filter over text, defaulting to CONTAINS and adding CONTAINS,\n * STARTS_WITH and ENDS_WITH to the compare operators.\n *\n * Its tuple carries a case sensitivity after the operator, `[operator,\n * sensitivity, operand]` or `[operator, sensitivity, from, to]`, the\n * sensitivity being IGNORE_CASE (the default) or CASE_SENSITIVE and switched\n * through a second menu. The `sensitivities` attribute whitelists that menu and\n * `sensitivity` fixes one mode, with the same rules and warnings as\n * `operators` and `operator`.\n */\nclass TextFilter extends CompareFilter {\n static observed = ['sensitivities:csv'];\n static attributes = ['sensitivity'];\n static template = `\n <label>{{{{ slots.default }}}}</label>\n {{{{ slots.info }}}}\n <ful-control-group>\n <ful-affix data-tpl-if=\"slots.before\">{{{{ slots.before }}}}</ful-affix>\n <ful-affix>\n <button data-ref=\"operator\" type=\"button\" form=\"\" aria-expanded=\"false\" aria-haspopup=\"true\"></button>\n <ul popover role=\"menu\"></ul>\n <button data-ref=\"sensitivity\" type=\"button\" form=\"\" aria-expanded=\"false\" aria-haspopup=\"true\"></button>\n <ul popover role=\"menu\"></ul>\n </ful-affix>\n <ful-control>\n <input data-ref=\"value1\" data-tpl-type=\"type\" form=\"\">\n <input data-ref=\"value2\" data-tpl-type=\"type\" form=\"\" hidden>\n </ful-control>\n <ful-affix data-tpl-if=\"slots.after\">{{{{ slots.after }}}}</ful-affix>\n </ful-control-group>\n <ful-field-error></ful-field-error>\n `;\n _defaultOperator() {\n return 'CONTAINS';\n }\n _vocabulary() {\n return TEXT_OPERATORS;\n }\n _sensitivityButton;\n _build(conf) {\n const pieces = super._build(conf);\n this._sensitivityButton = new ChoiceButton(\n /** @type HTMLElement */ (pieces.fragment.querySelector('[data-ref=sensitivity]')),\n {\n vocabulary: SENSITIVITIES,\n glyphs: SENSITIVITY_GLYPHS,\n labelFor: sensitivityLabel,\n interactive: () => this._interactive(),\n onPick: () => this._notifyChange(),\n },\n );\n this._sensitivityButton.allowed = null;\n this._sensitivityButton.value = SENSITIVITIES[0];\n fixChoice(this, this._sensitivityButton, {\n singular: 'sensitivity',\n plural: 'sensitivities',\n vocabulary: SENSITIVITIES,\n fallback: 'IGNORE_CASE',\n });\n return pieces;\n }\n _choices() {\n return [...super._choices(), this._sensitivityButton].filter((c) => c);\n }\n get _sensitivity() {\n return this._sensitivityButton.value;\n }\n _declaredSensitivities;\n /**\n * The sensitivities the menu offers, narrowed to IGNORE_CASE and\n * CASE_SENSITIVE: an empty list, or one where no name is known, offers both.\n * When the mode shown leaves the list, the first listed one is shown. Held\n * before the upgrade and ignored under a fixed `sensitivity`, as `operators` is.\n * @returns {string[]|undefined} undefined before the upgrade when nothing was assigned\n */\n get sensitivities() {\n return this._sensitivityButton ? this._sensitivityButton.allowed : this._declaredSensitivities;\n }\n /** @param {string[]|null} declared */\n set sensitivities(declared) {\n if (this.declared('sensitivity') !== null) {\n return;\n }\n if (!this._sensitivityButton) {\n this._declaredSensitivities = ChoiceButton.narrow(declared, SENSITIVITIES);\n return;\n }\n const previous = this._sensitivityButton.value;\n this._sensitivityButton.allowed = declared;\n this._sensitivityButton.value = this._sensitivityButton.preferring(previous);\n }\n /**\n * The tuple with the sensitivity after the operator, `[operator,\n * sensitivity, ...operands]`. Null while any operand the operator uses is empty.\n * @returns {any[]|null}\n */\n get value() {\n const tuple = this._tuple();\n return tuple == null ? null : [tuple[0], this._sensitivity, ...tuple.slice(1)];\n }\n /**\n * Shows a tuple as the compare filter does, reading the sensitivity at\n * index 1. A sensitivity the whitelist does not allow leaves the current\n * one in place. Null or undefined empties the operands and keeps the\n * operator and the sensitivity.\n * @param {any[]|null|undefined} v\n */\n set value(v) {\n if (v == null) {\n this._applyTuple(v);\n return;\n }\n if (this._sensitivityButton.allowed.includes(v[1])) {\n this._sensitivityButton.value = v[1];\n }\n this._applyTuple([v[0], ...v.slice(2)]);\n }\n /**\n * Restores the declared `value` tuple, sensitivity included. Without a\n * `value` attribute it also shows the default operator and IGNORE_CASE\n * again, or the first whitelisted mode where IGNORE_CASE is not allowed.\n */\n formResetCallback() {\n super.formResetCallback();\n if (!this.hasAttribute('value')) {\n this._sensitivityButton.value = this._sensitivityButton.preferring('IGNORE_CASE');\n }\n }\n}\n\nconst BOOLEAN_VALUES = ['', 'true', 'false'];\nconst BOOLEAN_VALUE_GLYPHS = { true: '✓', false: '✗' };\n\n/**\n * The boolean filter: an EQ or NEQ operator menu and a value menu of any, yes\n * and no, the value button showing the localized word.\n *\n * The value is `[operator, 'true']` or `[operator, 'false']`, null while the\n * value menu is on any. The `operators` attribute whitelists the operator menu\n * as on the compare filters. The disabled claim reaches the value button and\n * both menus, and readonly refuses the clicks that would open them. The\n * required and readonly claims reflect on the host only: no `aria-required` or\n * `aria-readonly` is written, since the value button's role accepts neither.\n */\nclass BooleanFilter extends Field {\n static observed = ['value:json', 'operators:csv'];\n static slots = true;\n /**\n * The operators the filter knows, which `operators` narrows.\n * @type {string[]}\n */\n static OPERATORS = ['EQ', 'NEQ'];\n /**\n * The operator shown on render and after a valueless reset, or the first\n * whitelisted one where the whitelist excludes it.\n * @type {string}\n */\n static DEFAULT_OPERATOR = 'EQ';\n static template = `\n <label>{{{{ slots.default }}}}</label>\n {{{{ slots.info }}}}\n <ful-control-group>\n <ful-affix data-tpl-if=\"slots.before\">{{{{ slots.before }}}}</ful-affix>\n <ful-affix>\n <button data-ref=\"operator\" type=\"button\" form=\"\" aria-expanded=\"false\" aria-haspopup=\"true\"></button>\n <ul popover role=\"menu\"></ul>\n </ful-affix>\n <button data-ref=\"value\" type=\"button\" form=\"\"></button>\n <ul popover role=\"menu\"></ul>\n <ful-affix data-tpl-if=\"slots.after\">{{{{ slots.after }}}}</ful-affix>\n </ful-control-group>\n <ful-field-error></ful-field-error>\n `;\n _operator;\n _value;\n _container;\n _build({ slots }) {\n const fragment = this.template().withOverlay({ slots }).render();\n this._container = fragment.querySelector('ful-control-group');\n const valueButton = /** @type {HTMLElement} */ (fragment.querySelector('[data-ref=value]'));\n this._operator = new ChoiceButton(/** @type {HTMLElement} */ (fragment.querySelector('[data-ref=operator]')), {\n vocabulary: BooleanFilter.OPERATORS,\n glyphs: GLYPHS,\n labelFor: operatorLabel,\n interactive: () => this._interactive(),\n onPick: () => this._notifyChange(),\n });\n this._value = new ChoiceButton(valueButton, {\n vocabulary: BOOLEAN_VALUES,\n glyphs: BOOLEAN_VALUE_GLYPHS,\n labelFor: booleanValueLabel,\n display: booleanValueLabel,\n interactive: () => this._interactive(),\n onPick: () => this._notifyChange(),\n });\n this.operators = this.declared('operators');\n this._operator.value = this._operator.preferring(BooleanFilter.DEFAULT_OPERATOR);\n this._value.allowed = null;\n this._value.value = '';\n return {\n fragment,\n control: valueButton,\n error: fragment.querySelector('ful-field-error'),\n label: fragment.querySelector('label'),\n announces: null,\n freeze: this._container,\n };\n }\n _declaredOperators;\n /**\n * The operators the menu offers, narrowed to EQ and NEQ: an empty list, or\n * one where no name is known, offers both, and a single one pins the\n * button. Held before the upgrade and replaced by the `operators` attribute\n * at the render, as on the compare filters.\n * @returns {string[]|undefined} undefined before the upgrade when nothing was assigned\n */\n get operators() {\n return this._operator ? this._operator.allowed : this._declaredOperators;\n }\n /** @param {string[]|null} declared */\n set operators(declared) {\n if (!this._operator) {\n this._declaredOperators = ChoiceButton.narrow(declared, this._vocabulary());\n return;\n }\n this._operator.allowed = declared;\n }\n /** @returns {string[]} */\n _vocabulary() {\n return BooleanFilter.OPERATORS;\n }\n /**\n * `[operator, token]`, the token being 'true' or 'false'; null while the value menu is on any.\n * @returns {string[]|null}\n */\n get value() {\n return this._value.value === '' ? null : [this._operator.value, this._value.value];\n }\n /**\n * Shows a tuple: its operator, unless a pinned operator replaces it, and its\n * token, a missing token meaning any. Null or undefined sets the value menu\n * back to any and keeps the operator.\n * @param {any[]|null|undefined} v\n */\n set value(v) {\n if (v == null) {\n this._value.value = '';\n return;\n }\n this._operator.value = this._operator.pinned ? this._operator.allowed[0] : v[0];\n this._value.value = v[1] ?? '';\n }\n /**\n * Restores the declared `value` tuple. Without a `value` attribute it sets\n * the value menu back to any and also shows the default operator again.\n */\n formResetCallback() {\n super.formResetCallback();\n if (!this.hasAttribute('value')) {\n this._operator.value = this._operator.preferring(BooleanFilter.DEFAULT_OPERATOR);\n }\n }\n /**\n * The operator and the localized word the value menu shows, not the token.\n * Null while the value menu is on any.\n * @returns {FilterCriterion|null}\n */\n get criterion() {\n const token = this._value.value;\n return asCriterion(labelTextOf(this), this._operator.value, [token === '' ? '' : booleanValueLabel(token)]);\n }\n /**\n * The field's own disabled claim. Setting it disables the value button and\n * both menu buttons; an operator button pinned to one choice stays disabled\n * when the claim is lifted.\n * @returns {boolean}\n */\n get disabled() {\n return super.disabled;\n }\n /** @param {boolean} d */\n set disabled(d) {\n super.disabled = d;\n for (const choice of [this._operator, this._value].filter((c) => c)) {\n choice.claimed = d;\n }\n }\n}\n\n/**\n * Set membership over a select's vocabulary, answering for both of data-jpa's\n * set annotations: InEnum and InList take the same bare array of values and no\n * operator, differing only in what the server converts them to. A declared\n * `operator` attribute is sent in front of the keys instead, for a server field\n * that reads the set through a compare.\n */\nclass InFilter extends Select {\n static attributes = ['operator'];\n #keys() {\n const chosen = super.value;\n if (this.multiple) {\n return chosen;\n }\n return chosen === null || chosen === undefined ? [] : [chosen];\n }\n /**\n * The chosen keys as an array, a single choice included, led by the\n * declared `operator` when there is one. Null while nothing is chosen, so\n * that a table drops the filter instead of sending an empty set that\n * matches nothing.\n * @returns {any[]|null}\n */\n get value() {\n const keys = this.#keys();\n if (keys.length === 0) {\n return null;\n }\n const operator = this.declared('operator');\n return operator ? [operator, ...keys] : keys;\n }\n /**\n * Selects the keys of an array or a single bare key; a leading element equal\n * to the declared `operator` is dropped first, so the filter takes back what\n * it answered. A single select takes the first key. Null or undefined clears\n * the selection.\n * @param {any} v\n */\n set value(v) {\n const operator = this.declared('operator');\n let keys = v === null || v === undefined ? [] : Array.isArray(v) ? v : [v];\n if (operator && keys[0] === operator) {\n keys = keys.slice(1);\n }\n super.value = this.multiple ? keys : (keys[0] ?? null);\n }\n /**\n * The declared operator, or null, and the labels of the chosen entries. Null\n * while nothing is chosen.\n * @returns {FilterCriterion|null}\n */\n get criterion() {\n return asCriterion(\n labelTextOf(this),\n this.declared('operator'),\n [super.entry]\n .flat()\n .filter((e) => e)\n .map((e) => /** @type {{ label: string }} */ (e).label),\n );\n }\n}\n\nexport { BooleanFilter, CompareFilter, InFilter, InstantFilter, LocalDateFilter, NumberFilter, TextFilter };\n","import { ParsedElement } from '../../ftl/index.mjs';\nimport { describable } from '../descriptions.mjs';\nimport { Anchors } from './anchors.mjs';\n\n/**\n * An icon button that toggles a native popover, a `ful-note`, holding the\n * default slot as a short explanation. The popover gives light dismiss and\n * Escape, and the button carries an `aria-expanded` kept in step with it and\n * a localized `aria-label`.\n *\n * The marker is the `ful-icon` that `Tooltip.config.icon` names for the whole\n * page, or the one the `icon` attribute names for a single tooltip. A name the\n * library does not paint is declared by the page as\n * `ful-icon[name='...'] { mask-image: ... }`.\n *\n * `placement` picks the side of the marker the note opens on: `top` (the\n * default), `bottom`, `left` or `right`. The note is placed in script on every\n * platform, centred on the marker, clamped into the viewport and following the\n * marker on scroll and resize, with a callout on the edge facing the marker.\n *\n * `describes` offers the note to the nearest ancestor that takes a description\n * (see `describable`), a field's control in practice: when it is taken, the\n * note becomes part of that control's accessible description and the marker\n * leaves the tab order, staying clickable. When nothing takes it, the marker\n * keeps its tab stop and a warning is logged.\n */\nclass Tooltip extends ParsedElement {\n static slots = true;\n static attributes = ['placement', 'icon', 'describes:presence'];\n /** The page-wide defaults: `icon` is the `ful-icon` name of the marker. */\n static config = {\n icon: 'info-circle-fill',\n };\n static template = `\n <span role=\"button\" tabindex=\"0\" class=\"ful-tip\" data-ref=\"trigger\" data-tpl-aria-label=\"#l10n:t('info.tooltip')\"><ful-icon data-tpl-name=\"icon ?? config.icon\" aria-hidden=\"true\"></ful-icon></span>\n <ful-note popover data-ref=\"content\">{{{{ slots.default }}}}</ful-note>\n `;\n /**\n * @param {{ slots: Record<string, DocumentFragment> }} c\n */\n render({ slots }) {\n const fragment = this.template().withOverlay({ slots, icon: this.declared('icon') }).render();\n const trigger = /** @type {HTMLElement} */ (fragment.querySelector('[data-ref=trigger]'));\n const content = /** @type {HTMLElement} */ (fragment.querySelector('[data-ref=content]'));\n Anchors.wire(trigger, content, { prefix: 'ful-tooltip', invoke: true, expanded: true, handPlace: true });\n content.setAttribute('placement', this.declared('placement') ?? 'top');\n this.replaceChildren(fragment);\n if (this.declared('describes')) {\n Tooltip.#describe(this, trigger, content);\n }\n }\n /**\n * @param {Tooltip} tooltip\n * @param {HTMLElement} trigger\n * @param {HTMLElement} content\n */\n static #describe(tooltip, trigger, content) {\n if (!describable(tooltip)?.describedBy(content)) {\n console.warn('a ful-tooltip declares describes but stands in nothing that takes a description', tooltip);\n return;\n }\n trigger.tabIndex = -1;\n }\n}\n\nexport { Tooltip };\n","import { Localization } from '../../ftl/index.mjs';\nimport { Claims } from '../claims.mjs';\n\n/**\n * The section requests shared by ful-tabs, ful-wizard, ful-dialog and\n * ful-drawer. Each activation of a section fires a family of events on the host\n * component and waits for the answers that listeners registered through\n * `AsyncEvents.asyncOn` attach to them. The events target the component, so\n * `e.target.localName` names the family and `e.target === e.currentTarget`\n * separates a host's own sections from those of a nested component, while\n * `detail.section` is the element the content goes in.\n *\n * While an answer is pending, from the next animation frame, the section\n * carries the `loading` attribute and `aria-busy=\"true\"`; answers that settle\n * before that frame show neither. A new request for the same section\n * supersedes the one in flight, which then no longer touches the section's\n * chrome. A failure removes the section's previous error and prepends a\n * `.ful-section-error` with the `alert` role, holding the reasons of the\n * failure's problems, one per line, or its message when it carries none.\n */\nclass SectionRequests {\n /** @type {WeakSet<Element>} */\n #entered = new WeakSet();\n /** @type {WeakMap<Element, Claims>} */\n #claims = new WeakMap();\n\n /**\n * Fires `section:requested`, then `section:requested:#<index>` when an index\n * is given, then `section:requested:<name>` when a name is given, each\n * bubbling from `host` with the same detail `{ name, section, index, first }`,\n * and awaits every answer attached to any of them. `first` is true until a\n * request for the section is answered by at least one listener, so a request\n * nobody listened to does not spend it. A request with answers removes the\n * error a previous failure painted before it waits.\n * @param {Element} host the component the events are dispatched on\n * @param {Element} section the element the answers deliver into\n * @param {string|null} name the section's `data-step`, when it has one\n * @param {number|null} index the section's zero-based position, when it has one\n * @returns {Promise<any[]|undefined>} the answers in the order they were\n * attached, or undefined when nobody listened\n * @throws what the first failing answer rejected with, after painting its\n * problems in the section unless a newer request superseded this one\n */\n async request(host, section, name, index) {\n const first = !this.#entered.has(section);\n const detail = { name, section, index, first };\n const types = [\n 'section:requested',\n ...(index !== null && index !== undefined ? [`section:requested:#${index}`] : []),\n ...(name ? [`section:requested:${name}`] : []),\n ];\n const promises = [];\n for (const type of types) {\n const evt = /** @type {CustomEvent & { async?: { promises: Promise<any>[] } }} */ (\n new CustomEvent(type, { bubbles: true, detail })\n );\n host.dispatchEvent(evt);\n promises.push(...(evt.async?.promises ?? []));\n }\n if (promises.length === 0) {\n return undefined;\n }\n this.#entered.add(section);\n let claims = this.#claims.get(section);\n if (!claims) {\n claims = new Claims();\n this.#claims.set(section, claims);\n }\n const claim = claims.take();\n const owned = () => !claim.stale;\n section.querySelector(':scope > .ful-section-error')?.remove();\n const frame = requestAnimationFrame(() => {\n if (owned()) {\n section.toggleAttribute('loading', true);\n section.setAttribute('aria-busy', 'true');\n }\n });\n try {\n return await Promise.all(promises);\n } catch (cause) {\n if (owned()) {\n this.#paintError(section, cause);\n }\n throw cause;\n } finally {\n cancelAnimationFrame(frame);\n if (owned()) {\n section.toggleAttribute('loading', false);\n section.removeAttribute('aria-busy');\n }\n }\n }\n\n /**\n * @param {Element} section\n * @param {unknown} cause\n */\n #paintError(section, cause) {\n section.querySelector(':scope > .ful-section-error')?.remove();\n const error = document.createElement('div');\n error.className = 'ful-section-error';\n error.setAttribute('role', 'alert');\n error.textContent = Localization.of().failure(cause);\n section.prepend(error);\n }\n}\n\nexport { SectionRequests };\n","import { Localization, Nodes } from '../../ftl/index.mjs';\nimport { Claims } from '../claims.mjs';\nimport { SectionRequests } from '../events/sections.mjs';\n\n/**\n * The sections a modal disclosure renders inside its native `<dialog>`: the\n * content section a caller fills, and the loading and error sections shown\n * while `update()` waits and when it fails. It also wires the gestures the\n * dialog and the drawer share: a dismissal on a press and release both on the\n * backdrop, and an answer on a `ful-form` submit in the content.\n *\n * The element owning it keeps the opening, the closing and the outcome; the\n * sections only paint and request.\n */\nclass DialogSections {\n #host;\n #dialog;\n #section;\n #loading;\n #error;\n #requests = new SectionRequests();\n #updates = new Claims();\n /** @type {Promise<boolean>|null} */\n #confirming = null;\n /**\n * @param {HTMLElement} host the element the section requests are dispatched on\n * @param {DocumentFragment} fragment the rendered template, holding a\n * `[data-ref=dialog]` and, optionally, the content section and the\n * `[data-ref=loading]` and `[data-ref=error]` sections: a subclass template\n * without a content section can be opened and closed, but not updated\n * @param {string} content the `data-ref` of the content section\n */\n constructor(host, fragment, content) {\n this.#host = host;\n this.#dialog = /** @type {HTMLDialogElement} */ (fragment.querySelector('[data-ref=dialog]'));\n this.#section = /** @type {HTMLElement} */ (fragment.querySelector(`[data-ref=${content}]`));\n this.#loading = fragment.querySelector('[data-ref=loading]');\n this.#error = fragment.querySelector('[data-ref=error]');\n }\n /** @returns {HTMLDialogElement} */\n get dialog() {\n return this.#dialog;\n }\n /** @returns {HTMLElement} the content section */\n get section() {\n return this.#section;\n }\n /**\n * Whether a `ful-form` of this dialog, not one of a dialog nested in it,\n * holds unsaved edits (see `Form.dirty`).\n * @returns {boolean}\n */\n get dirty() {\n return Array.from(this.#dialog.querySelectorAll('ful-form')).some(\n (form) => form.closest('dialog') === this.#dialog && /** @type {any} */ (form).dirty,\n );\n }\n /**\n * Dispatches the dismissal on the host and calls `close` unless a listener\n * prevented it or, with `confirm` given and the dialog `dirty`, `confirm`\n * answers false. A dismissal that is not cancelable announces a close the\n * platform makes whatever the page does, so nothing is asked and `close` is\n * not called for it. While `confirm` is pending a further dismissal waits\n * for the same answer, and a dialog closed meanwhile is not closed again.\n * @param {CustomEvent} asked\n * @param {() => void} close\n * @param {(() => Promise<boolean>)|null} confirm asks whether to drop the unsaved edits\n * @returns {Promise<boolean>} whether the dismissal closes the dialog\n */\n dismiss(asked, close, confirm) {\n if (this.#confirming) {\n return this.#confirming;\n }\n if (!this.#host.dispatchEvent(asked)) {\n return Promise.resolve(false);\n }\n if (!asked.cancelable) {\n return Promise.resolve(true);\n }\n if (!confirm || !this.dirty) {\n close();\n return Promise.resolve(true);\n }\n this.#confirming = confirm()\n .then((drop) => {\n if (drop && this.#dialog.open) {\n close();\n }\n return drop;\n })\n .finally(() => {\n this.#confirming = null;\n });\n return this.#confirming;\n }\n /**\n * Calls `dismiss` when a press and its release both land on the backdrop,\n * so a selection dragged out of the panel and released outside does not.\n * @param {() => void} dismiss\n */\n onBackdrop(dismiss) {\n let pressedOutside = false;\n this.#dialog.addEventListener('mousedown', (e) => {\n pressedOutside = e.target === this.#dialog;\n });\n this.#dialog.addEventListener('click', (e) => {\n if (pressedOutside && e.target === this.#dialog) {\n dismiss();\n }\n });\n }\n /**\n * Calls `answer` with `detail.response` when a `ful-form` that is a direct\n * child of the content section dispatches `submit:success`. The listener sits\n * on the section, so a form delivered by `update()` is covered, and a form\n * deeper in the content, such as a `ful-table`'s filters, is not.\n * @param {(response: any) => void} answer\n */\n onSubmitted(answer) {\n this.#section.addEventListener('submit:success', (/** @type any */ e) => {\n if (e.target !== Nodes.queryChildren(this.#section, 'ful-form')) {\n return;\n }\n answer(e.detail.response);\n });\n }\n /** Hides and empties the error section, hides the loading one and shows the content. */\n restChrome() {\n this.#error?.replaceChildren();\n this.#error?.setAttribute('hidden', '');\n this.#loading?.setAttribute('hidden', '');\n this.#section?.removeAttribute('hidden');\n }\n /**\n * Dispatches `section:requested` for the content section on the host. A\n * failed request is painted into the section.\n * @returns {Promise<any[]|undefined>} the listeners' answers, undefined when\n * nobody answered or the request failed; it never rejects\n */\n request() {\n return this.#requests.request(this.#host, this.#section, null, null).catch(() => undefined);\n }\n /**\n * Empties and hides the content section, shows the loading section, calls\n * `show`, and fills the content with what the callback resolves to. A\n * rejection is shown, as the problems' reasons, in the error section, and\n * the content is hidden. When a newer `update()` starts before the callback\n * settles, this call paints nothing and resolves `null`, the section being\n * the newer call's; it still rejects with the callback's error.\n * @param {() => Node|string|Promise<Node|string>} cb producing the content\n * @param {() => void} show opens the dialog when it is closed\n * @returns {Promise<HTMLElement|null>} the content section, or `null` for a\n * call a newer one overtook\n * @throws {any} what the callback threw or rejected with\n */\n async update(cb, show) {\n const claim = this.#updates.take();\n this.#section.replaceChildren();\n this.restChrome();\n this.#loading?.removeAttribute('hidden');\n this.#section.setAttribute('hidden', '');\n show();\n try {\n const delivered = await cb();\n if (claim.stale) {\n return null;\n }\n this.#section.replaceChildren(delivered);\n this.#loading?.setAttribute('hidden', '');\n this.#section.removeAttribute('hidden');\n return this.#section;\n } catch (/** @type any */ e) {\n if (!claim.stale) {\n this.#error?.removeAttribute('hidden');\n if (this.#error) {\n this.#error.textContent = Localization.of().failure(e);\n }\n this.#loading?.setAttribute('hidden', '');\n this.#section.setAttribute('hidden', '');\n }\n throw e;\n }\n }\n}\n\nexport { DialogSections };\n","let targetsWired = false;\n/**\n * Makes any element carrying `dialog-target` open the element whose id it\n * names, clones included, which is how the dialog and the drawer are opened\n * from markup. One click listener on the document finds the nearest\n * `[dialog-target]` around the click target and calls `open()` on the named\n * element when it has one; an id naming nothing is ignored. Calls after the\n * first do nothing.\n */\nconst wireTargets = () => {\n if (targetsWired) {\n return;\n }\n targetsWired = true;\n document.addEventListener('click', (/** @type any */ e) => {\n const trigger = e.target.closest?.('[dialog-target]');\n if (!trigger) {\n return;\n }\n /** @type {any} */ (document.getElementById(trigger.getAttribute('dialog-target')))?.open?.();\n });\n};\n\nexport { wireTargets };\n","import { Attributes, Localization, ParsedElement, Rendering } from '../../ftl/index.mjs';\nimport { DialogSections } from './dialog-sections.mjs';\nimport { wireTargets } from './targets.mjs';\n\n/**\n * How a dialog ended. `dismissed` is true for Escape, the close button, a\n * backdrop click, a `data-result=\"\"` button, `close()` without a result and a\n * removal from the document; `result` is the `data-result` of the button, or\n * the argument of `close(result)`, that answered; `response` is what the form\n * answered with under `close-on-submit`. Whichever of `result` and `response`\n * did not answer is null, as both are on a dismissal.\n * @typedef {{ dismissed: boolean, result: string|null, response: any }} DialogOutcome\n */\n\n/**\n * A modal dialog on the native `<dialog>`, rendered with a header, a body and\n * a footer. `open()` and `ask()` show it and resolve with a `DialogOutcome`.\n *\n * The `header` attribute is the title, rendered as an `h2` that names the\n * dialog through `aria-labelledby`; without it the dialog is unnamed. The\n * `header` slot is rendered in the header before the title, the default slot\n * is the body, and the `buttons` slot is rendered in the footer. Without a\n * `buttons` slot, and without `close-on-submit`, the footer holds a localized\n * acknowledge button answering `acknowledged`.\n *\n * Any button inside the dialog carrying `data-result` closes it with that\n * result, an empty one being a dismissal. The header carries a close button,\n * and a press and release both on the backdrop close the dialog, each as a\n * dismissal, as Escape does.\n *\n * Those three gestures go through `dismiss(reason)`, the reason being\n * `button`, `backdrop` or `escape`: before it closes the dialog, the element\n * dispatches a cancelable, non-bubbling `dialog:dismiss` with\n * `detail: { reason }`, and a listener calling `preventDefault()` keeps it\n * open. Under `guard-dismiss`, a dismissal nobody refused, while a `ful-form`\n * of the dialog holds unsaved edits (see `Form.dirty`), first asks the user,\n * through `Dialog.confirm`, whether to close and drop them. A `data-result`\n * button, `close-on-submit`, `close()` and `update()` are answers or the page\n * deciding: they dispatch nothing and ask nothing.\n *\n * The platform lets a page refuse Escape once per user interaction: a second\n * Escape with no click or keystroke in between closes the dialog whatever the\n * page does, `requires-answer` and `guard-dismiss` included. That close is\n * still announced by a `dialog:dismiss`, which is then not cancelable.\n *\n * `requires-answer` withholds the close button and refuses Escape and the\n * backdrop, so the dialog is closed only by a button carrying `data-result`\n * or from code, through `close()` or `dismiss()`.\n *\n * `close-on-submit` closes the dialog when a `ful-form` that is a direct child\n * of the body dispatches `submit:success`, answering with its\n * `detail.response`. A form deeper in the body, such as the filter form of a\n * `ful-table`, does not close it. The listener sits on the body, so a form\n * delivered by `update()` is covered as well.\n *\n * Every close dispatches a non-bubbling `close` event on the element carrying\n * the `DialogOutcome` as `detail`, before the pending `ask()` calls resolve.\n * An element anywhere in the page carrying `dialog-target` set to the\n * element's id opens it on click.\n *\n * The chrome is styled by class as well as by tag, so a plain `<dialog\n * class=\"ful-dialog\">` written by a page gets the same look: the tag form\n * matches a direct child, and `ful-dialog-header`, `ful-dialog-body` and\n * `ful-dialog-footer` match at any depth, as a dialog whose content is wrapped\n * in a form needs.\n */\nclass Dialog extends ParsedElement {\n static attributes = ['header', 'requires-answer:presence', 'close-on-submit:presence', 'guard-dismiss:presence'];\n static slots = true;\n static template = `\n <dialog data-ref=\"dialog\" class=\"ful-dialog\">\n <header data-tpl-if=\"header || slots.header || !requiresAnswer\" class=\"ful-dialog-header\">\n {{{{ slots.header }}}}\n <h2 data-tpl-if=\"header\">{{ header }}</h2>\n <button data-tpl-if=\"!requiresAnswer\" type=\"button\" data-ref=\"close\" data-tpl-aria-label=\"#l10n:t('dialog.close')\"><ful-icon name=\"x-lg\" aria-hidden=\"true\"></ful-icon></button>\n </header>\n <section data-ref=\"loading\" hidden><ful-spinner class=\"centered\" role=\"status\"><span class=\"ful-sr-only\">{{ #l10n:t('spinner.loading') }}</span></ful-spinner></section>\n <section data-ref=\"error\" role=\"alert\" hidden></section>\n <div data-ref=\"body\" class=\"ful-dialog-body\">{{{{ slots.default }}}}</div>\n <footer class=\"ful-dialog-footer\">\n <button type=\"button\" data-ref=\"acknowledge\" data-result=\"acknowledged\" data-tpl-if=\"!slots.buttons && !closeOnSubmit\" data-tpl-aria-label=\"#l10n:t('dialog.acknowledge')\">{{ #l10n:t('dialog.acknowledge') }}</button>\n {{{{ slots.buttons }}}}\n </footer>\n </dialog>\n `;\n #dialog;\n #sections;\n #resolvers = [];\n /** @type {DialogOutcome|null} */\n #answer = null;\n /**\n * @param {{ slots: Record<string, DocumentFragment> }} c\n */\n render({ slots }) {\n const requiresAnswer = this.declared('requires-answer');\n const closeOnSubmit = this.declared('close-on-submit');\n const fragment = this.template()\n .withOverlay({ slots, header: this.declared('header') ?? '', requiresAnswer, closeOnSubmit })\n .render();\n this.#sections = new DialogSections(this, fragment, 'body');\n this.#dialog = this.#sections.dialog;\n const heading = fragment.querySelector('h2');\n if (heading) {\n heading.id ||= Attributes.uid('ful-dialog-title');\n this.#dialog.setAttribute('aria-labelledby', heading.id);\n }\n this.#dialog.addEventListener('close', () => {\n const outcome = this.#outcome();\n this.dispatchEvent(new CustomEvent('close', { detail: outcome }));\n this.#settle(outcome);\n });\n this.#dialog.addEventListener('click', (/** @type any */ e) => {\n const result = e.target.closest('button[data-result]')?.dataset.result;\n if (result !== undefined) {\n this.#dialog.close(result);\n }\n });\n if (!requiresAnswer) {\n this.#sections.onBackdrop(() => this.dismiss('backdrop'));\n }\n fragment.querySelector('[data-ref=close]')?.addEventListener('click', () => this.dismiss('button'));\n if (closeOnSubmit) {\n this.#sections.onSubmitted((response) => {\n this.#answer = { dismissed: false, result: null, response };\n this.#dialog.close('submitted');\n });\n }\n this.#dialog.addEventListener('cancel', (/** @type any */ e) => {\n if (!e.cancelable) {\n this.#dialog.returnValue = '';\n this.#dismiss('escape', false);\n return;\n }\n e.preventDefault();\n if (!requiresAnswer) {\n this.dismiss('escape');\n }\n });\n this.replaceChildren(fragment);\n wireTargets();\n }\n /** @returns {DialogOutcome} */\n #outcome() {\n if (this.#answer) {\n return this.#answer;\n }\n const result = this.#dialog?.returnValue ?? '';\n return result === ''\n ? { dismissed: true, result: null, response: null }\n : { dismissed: false, result, response: null };\n }\n /** @param {DialogOutcome} outcome */\n #settle(outcome) {\n const resolvers = this.#resolvers;\n this.#resolvers = [];\n for (const resolve of resolvers) {\n resolve(outcome);\n }\n }\n /**\n * Resolves every pending `ask()` and `open()` with the outcome so far,\n * a dismissal for a dialog still open, so that no caller waits on a dialog\n * that left the document. The native dialog is not closed and no `close`\n * event is dispatched.\n */\n disconnectedCallback() {\n this.#settle(this.#outcome());\n }\n /**\n * The same as `ask()`.\n * @returns {Promise<DialogOutcome>}\n */\n open() {\n return this.ask();\n }\n /**\n * Shows the dialog as a modal and resolves with how it ends.\n *\n * The call that opens the dialog resets the outcome of the previous\n * opening, hides the error and loading sections, and dispatches\n * `section:requested` on the element (bubbling, with\n * `detail: { section, first, name: null, index: null }`, `section` being\n * the body and `first` true only on the first answered request), so a\n * listener can fill the body. A failed request is painted into the body\n * and does not reject. On a dialog already open nothing is shown or\n * requested, and the call waits for the same ending as the calls before it.\n * @returns {Promise<DialogOutcome>} resolving on close, or on removal from\n * the document with a dismissal\n */\n ask() {\n if (this.#show()) {\n this.#sections.restChrome();\n this.#sections.request();\n }\n return new Promise((resolve) => {\n this.#resolvers.push(resolve);\n });\n }\n /**\n * Empties and hides the body, shows the loading section, opens the dialog\n * if it is closed, and fills the body with what the callback resolves to.\n * A rejection is shown, as the problems' reasons, in the error section,\n * which has `role=\"alert\"`, and the body is hidden. The title stays the\n * `header` attribute.\n *\n * No `section:requested` is dispatched, and no `ask()` waiter is added:\n * listen for the `close` event to learn how the dialog ended. When a newer\n * `update()` starts before the callback settles, this call paints nothing\n * and resolves `null`, the body being the newer call's; it still rejects\n * with the callback's error.\n * @param {() => Node|string|Promise<Node|string>} cb producing the body content\n * @returns {Promise<Element|null>} the body section, in the document, or\n * `null` for a call a newer one overtook\n * @throws {any} what the callback threw or rejected with\n */\n async update(cb) {\n return await this.#sections.update(cb, () => this.#show());\n }\n /**\n * Dispatches `section:requested` for the body again, as `ask()` does,\n * whether the dialog is open or closed. A failed request is painted into\n * the body.\n * @returns {Promise<any[]|undefined>} the listeners' answers, undefined when\n * nobody answered or the request failed; it never rejects\n */\n refresh() {\n return this.#sections.request();\n }\n /**\n * Dismisses the dialog as the user would: dispatches the cancelable\n * `dialog:dismiss` with `detail: { reason }` and, under `guard-dismiss`,\n * asks before dropping unsaved edits, closing the dialog as a dismissal\n * unless either refused. `requires-answer` does not refuse it, as it does\n * not refuse `close()`. Does nothing on a closed dialog.\n * @param {string} reason why it is dismissed, such as `navigation`\n * @returns {Promise<boolean>} whether the dialog is closed, false when a\n * listener or the user kept it open\n */\n dismiss(reason) {\n if (!this.#dialog.open) {\n return Promise.resolve(true);\n }\n return this.#dismiss(reason, true);\n }\n /**\n * @param {string} reason\n * @param {boolean} cancelable false for a close the platform makes anyway\n * @returns {Promise<boolean>}\n */\n #dismiss(reason, cancelable) {\n return this.#sections.dismiss(\n new CustomEvent('dialog:dismiss', { cancelable, detail: { reason } }),\n () => this.#dialog.close(''),\n this.declared('guard-dismiss') ? discardEdits : null,\n );\n }\n /**\n * Closes an open dialog, doing nothing on a closed one. A non-empty result\n * answers as the button carrying that `data-result` would; no result, or\n * an empty one, is a dismissal.\n * @param {string} [result]\n */\n close(result) {\n this.#dialog.close(result ?? '');\n }\n /** @returns {boolean} whether this call is the one that opened the modal */\n #show() {\n if (this.#dialog.open) {\n return false;\n }\n this.#dialog.returnValue = '';\n this.#answer = null;\n this.#dialog.showModal();\n return true;\n }\n /**\n * Appends a new `ful-dialog` to `document.body`, asks it, and removes it\n * once it is answered or its render fails.\n *\n * A string body is set as text and never parsed as markup; a node is\n * appended as it is. Each button is either a `[result, label, className?]`\n * tuple, rendered as a `button` carrying `data-result`, or a node the\n * caller built, placed in the footer in the order given. With no buttons\n * the dialog shows its localized acknowledge button.\n * @param {string} header the title\n * @param {string|Node} body\n * @param {([string, string, string?]|Node)[]} [buttons]\n * @param {{ className?: string }} [options] `className` is set as the class\n * of the `ful-dialog` element\n * @returns {Promise<DialogOutcome>} rejecting with what the render threw\n */\n static async ask(header, body, buttons = [], { className } = {}) {\n const dialog = document.createElement('ful-dialog');\n dialog.setAttribute('header', header);\n if (className) {\n dialog.className = className;\n }\n if (typeof body === 'string') {\n dialog.textContent = body;\n } else if (body) {\n dialog.append(body);\n }\n if (buttons.length > 0) {\n const choices = document.createElement('template');\n choices.setAttribute('slot', 'buttons');\n for (const choice of buttons) {\n if (choice instanceof Node) {\n choices.content.append(choice);\n continue;\n }\n const [result, label, buttonClass] = choice;\n const button = document.createElement('button');\n button.type = 'button';\n button.dataset.result = result;\n if (buttonClass) {\n button.className = buttonClass;\n }\n button.textContent = label;\n choices.content.append(button);\n }\n dialog.append(choices);\n }\n document.body.append(dialog);\n try {\n await Rendering.waitFor(dialog);\n return await /** @type {Dialog} */ (dialog).ask();\n } finally {\n dialog.remove();\n }\n }\n /**\n * Asks a yes/no question through `Dialog.ask`, with a cancel button and a\n * confirm button carrying the `ful-button` class.\n * @param {string} header the title\n * @param {string|Node} body as `Dialog.ask` takes it\n * @param {{ confirm?: string, cancel?: string }} [labels] the button labels,\n * `dialog.confirm` and `dialog.cancel` localized by default\n * @param {{ className?: string }} [options] as `Dialog.ask` takes them\n * @returns {Promise<boolean>} true only for the confirm button; the cancel\n * button, the close button and Escape answer false\n */\n static async confirm(header, body, labels = {}, options = {}) {\n const outcome = await Dialog.ask(\n header,\n body,\n [\n ['cancel', labels.cancel ?? Localization.of().t('dialog.cancel')],\n ['confirm', labels.confirm ?? Localization.of().t('dialog.confirm'), 'ful-button'],\n ],\n options,\n );\n return !outcome.dismissed && outcome.result === 'confirm';\n }\n}\n\n/**\n * Asks, through `Dialog.confirm`, whether to close and drop the unsaved edits,\n * with the localized `dialog.discard.*` texts.\n * @returns {Promise<boolean>} true to drop them\n */\nconst discardEdits = () => {\n const l10n = Localization.of();\n return Dialog.confirm(l10n.t('dialog.discard.header'), l10n.t('dialog.discard.body'), {\n confirm: l10n.t('dialog.discard.confirm'),\n cancel: l10n.t('dialog.discard.cancel'),\n });\n};\n\nexport { Dialog, discardEdits };\n","import { Attributes, ParsedElement } from '../../ftl/index.mjs';\nimport { discardEdits } from './dialog.mjs';\nimport { DialogSections } from './dialog-sections.mjs';\nimport { wireTargets } from './targets.mjs';\n\n/**\n * A side panel on the native `<dialog>`, shown as a modal: a header holding\n * the title and a localized close button, then loading, error and content\n * sections, the default slot being the content.\n *\n * The `header` attribute is the initial title, rendered as an `h2` that names\n * the panel through `aria-labelledby`. The `header` slot is rendered in the\n * header before the title and outside it, so setting the title as text does\n * not remove it. `placement` is copied onto the native dialog: `end` (the\n * default, when absent) or `start`, following the writing direction.\n *\n * The close button, Escape, and a press and release both on the backdrop all\n * go through `dismiss(reason)`, the reason being `button`, `backdrop` or\n * `escape`: before it closes the drawer, the element dispatches a cancelable,\n * non-bubbling `drawer:dismiss` with `detail: { reason }`, and a listener\n * calling `preventDefault()` keeps it open. Under `guard-dismiss`, a dismissal\n * nobody refused, while a `ful-form` of the drawer holds unsaved edits (see\n * `Form.dirty`), first asks the user, through `Dialog.confirm`, whether to\n * close and drop them. A `data-result` button, `close-on-submit`, `close()`\n * and `update()` are answers or the page deciding: they dispatch nothing and\n * ask nothing. The platform lets a page refuse Escape once per user\n * interaction: a second Escape with no click or keystroke in between closes\n * the drawer at once, without the slide, `guard-dismiss` included, and its\n * `drawer:dismiss` is then not cancelable.\n *\n * Any button inside the drawer carrying `data-result` closes it with that\n * result, an empty one being a dismissal. Every close dispatches a\n * non-bubbling `close` event on the element carrying the `DialogOutcome` as\n * `detail`, before the pending `ask()` calls resolve.\n *\n * `close-on-submit` closes the drawer when a `ful-form` that is a direct child\n * of the content section dispatches `submit:success`, carrying its\n * `detail.response`, which may be null. A form deeper in the content, such as\n * the filter form of a `ful-table`, does not close it. The listener sits on\n * the content section, so a form delivered by `update()` is covered as well.\n *\n * An element anywhere in the page carrying `dialog-target` set to the\n * element's id calls `open()` on click.\n */\nclass Drawer extends ParsedElement {\n static attributes = ['header', 'placement', 'close-on-submit:presence', 'guard-dismiss:presence'];\n static slots = true;\n static template = `\n <dialog data-ref=\"dialog\" class=\"ful-drawer\">\n <header>\n {{{{ slots.header }}}}\n <h2 data-ref=\"title\">{{ title }}</h2>\n <button type=\"button\" data-ref=\"close\" data-tpl-aria-label=\"#l10n:t('drawer.close')\"><ful-icon name=\"x-lg\" aria-hidden=\"true\"></ful-icon></button>\n </header>\n <section data-ref=\"loading\" hidden><ful-spinner class=\"centered\" role=\"status\"><span class=\"ful-sr-only\">{{ #l10n:t('spinner.loading') }}</span></ful-spinner></section>\n <section data-ref=\"error\" role=\"alert\" hidden></section>\n <section data-ref=\"content\">{{{{ slots.default }}}}</section>\n </dialog>\n `;\n #dialog;\n #title;\n #sections;\n /** @type {{ dismissed: boolean, result: string|null, response: any }|null} */\n #answer = null;\n #resolvers = [];\n #closing = false;\n #slideOutEnded = (/** @type AnimationEvent */ e) => {\n if (e.target === this.#dialog) {\n this.#closeNow();\n }\n };\n /**\n * @param {{ slots: Record<string, DocumentFragment> }} c\n */\n render({ slots }) {\n const fragment = this.template()\n .withOverlay({ slots, title: this.declared('header') ?? '' })\n .render();\n this.#sections = new DialogSections(this, fragment, 'content');\n this.#dialog = this.#sections.dialog;\n this.#title = fragment.querySelector('[data-ref=title]');\n this.#title.id ||= Attributes.uid('ful-drawer-title');\n this.#dialog.setAttribute('aria-labelledby', this.#title.id);\n const placement = this.declared('placement');\n if (placement) {\n this.#dialog.setAttribute('placement', placement);\n }\n /** @type {HTMLElement} */ (fragment.querySelector('[data-ref=close]')).addEventListener('click', () =>\n this.dismiss('button'),\n );\n this.#sections.onBackdrop(() => this.dismiss('backdrop'));\n this.#dialog.addEventListener('cancel', (e) => {\n if (!e.cancelable) {\n this.#stopSlidingOut();\n this.#dismiss('escape', false);\n return;\n }\n e.preventDefault();\n this.dismiss('escape');\n });\n this.#dialog.addEventListener('click', (/** @type any */ e) => {\n const result = e.target.closest('button[data-result]')?.dataset.result;\n if (result !== undefined) {\n this.close(result);\n }\n });\n this.#dialog.addEventListener('close', () => {\n const outcome = this.#outcome();\n this.dispatchEvent(new CustomEvent('close', { detail: outcome }));\n this.#settle(outcome);\n });\n if (this.declared('close-on-submit')) {\n this.#sections.onSubmitted((response) => {\n this.#answer = { dismissed: false, result: null, response };\n this.close();\n });\n }\n this.replaceChildren(fragment);\n wireTargets();\n }\n /**\n * The title, read and written as the heading's text.\n * @type {string}\n */\n get header() {\n return this.#title.textContent;\n }\n /** @param {string|null|undefined} v written as text, `''` for null or undefined */\n set header(v) {\n this.#title.textContent = v ?? '';\n }\n /**\n * Sets the title, empties and hides the content section, shows the loading\n * section, opens the drawer if it is closed (putting back one that is\n * sliding out), and fills the content with what the callback resolves to.\n * A rejection is shown, as the problems' reasons, in the error section,\n * which has `role=\"alert\"`, and the content is hidden.\n *\n * No `section:requested` is dispatched. When a newer `update()` starts\n * before the callback settles, this call paints nothing and resolves\n * `null`, the content section being the newer call's; it still rejects with\n * the callback's error.\n * @param {string} header the title, set as text\n * @param {() => Node|string|Promise<Node|string>} cb producing the content\n * @returns {Promise<Element|null>} the content section, in the document, or\n * `null` for a call a newer one overtook\n * @throws {any} what the callback threw or rejected with\n */\n async update(header, cb) {\n this.header = header;\n return await this.#sections.update(cb, () => this.#show());\n }\n /**\n * Dispatches `section:requested` for the content again, as `open()` does,\n * whether the drawer is open or closed. A failed request is painted into\n * the content section.\n * @returns {Promise<any[]|undefined>} the listeners' answers, undefined when\n * nobody answered or the request failed; it never rejects\n */\n refresh() {\n return this.#sections.request();\n }\n /** @returns {{ dismissed: boolean, result: string|null, response: any }} */\n #outcome() {\n return this.#answer ?? { dismissed: true, result: null, response: null };\n }\n /** @param {{ dismissed: boolean, result: string|null, response: any }} outcome */\n #settle(outcome) {\n const resolvers = this.#resolvers;\n this.#resolvers = [];\n for (const resolve of resolvers) {\n resolve(outcome);\n }\n }\n /**\n * Resolves every pending `ask()` and `open()` with the outcome so far,\n * a dismissal for a drawer still open, so that no caller waits on a drawer\n * that left the document. The native dialog is not closed and no `close`\n * event is dispatched.\n */\n disconnectedCallback() {\n this.#settle(this.#outcome());\n }\n /**\n * The same as `ask()`.\n * @returns {Promise<{ dismissed: boolean, result: string|null, response: any }>}\n */\n open() {\n return this.ask();\n }\n /**\n * Shows the drawer as a modal and resolves with how it ends.\n *\n * The call that opens the drawer resets the outcome of the previous\n * opening, hides the error and loading sections, and dispatches\n * `section:requested` on the element (bubbling, with\n * `detail: { section, first, name: null, index: null }`, `section` being\n * the content section and `first` true only on the first answered request),\n * so a listener can fill the content. A failed request is painted into the\n * content section and does not reject. On a drawer already open nothing is\n * shown or requested, except that one sliding out stops and stays open, and\n * the call waits for the same ending as the calls before it, which is how\n * a caller learns the outcome of the opening an `update()` made.\n * @returns {Promise<{ dismissed: boolean, result: string|null, response: any }>} resolving on\n * close, or on removal from the document with a dismissal\n */\n ask() {\n if (this.#show()) {\n this.#sections.restChrome();\n this.#sections.request();\n }\n return new Promise((resolve) => {\n this.#resolvers.push(resolve);\n });\n }\n /**\n * Dismisses the drawer as the user would: dispatches the cancelable\n * `drawer:dismiss` with `detail: { reason }` and, under `guard-dismiss`,\n * asks before dropping unsaved edits, sliding the drawer out as a\n * dismissal unless either refused. Does nothing on a drawer that is closed\n * or already sliding out.\n * @param {string} reason why it is dismissed, such as `navigation`\n * @returns {Promise<boolean>} whether the drawer is closed or closing,\n * false when a listener or the user kept it open\n */\n dismiss(reason) {\n if (this.#closing || !this.#dialog.open) {\n return Promise.resolve(true);\n }\n return this.#dismiss(reason, true);\n }\n /**\n * @param {string} reason\n * @param {boolean} cancelable false for a close the platform makes anyway\n * @returns {Promise<boolean>}\n */\n #dismiss(reason, cancelable) {\n return this.#sections.dismiss(\n new CustomEvent('drawer:dismiss', { cancelable, detail: { reason } }),\n () => this.close(),\n this.declared('guard-dismiss') ? discardEdits : null,\n );\n }\n /**\n * Slides the drawer out and closes it when the animation ends, setting the\n * `closing` attribute on the native dialog meanwhile; the `close` event is\n * dispatched then, after this call has returned. Where the user prefers\n * reduced motion, or no animation runs, it closes at once. A non-empty\n * result answers as the button carrying that `data-result` would; no\n * result, or an empty one, is a dismissal. Does nothing on a drawer that is\n * closed or already sliding out.\n * @param {string} [result]\n */\n close(result) {\n if (this.#closing || !this.#dialog.open) {\n return;\n }\n if (result) {\n this.#answer = { dismissed: false, result, response: null };\n }\n if (matchMedia('(prefers-reduced-motion: reduce)').matches) {\n this.#dialog.close();\n return;\n }\n this.#dialog.setAttribute('closing', '');\n if (this.#dialog.getAnimations().length === 0) {\n this.#closeNow();\n return;\n }\n this.#closing = true;\n this.#dialog.addEventListener('animationend', this.#slideOutEnded);\n }\n #closeNow() {\n this.#stopSlidingOut();\n this.#dialog.close();\n }\n #stopSlidingOut() {\n this.#closing = false;\n this.#dialog.removeEventListener('animationend', this.#slideOutEnded);\n this.#dialog.removeAttribute('closing');\n }\n /** @returns {boolean} whether this call is the one that opened the modal */\n #show() {\n this.#stopSlidingOut();\n if (this.#dialog.open) {\n return false;\n }\n this.#answer = null;\n this.#dialog.showModal();\n return true;\n }\n}\n\nexport { Drawer };\n","import { ParsedElement } from '../../ftl/index.mjs';\nimport { Anchors } from './anchors.mjs';\nimport { wireMenuKeys } from './menu-keys.mjs';\n\n/**\n * A menu of commands on the native popover platform. The menu is the popover\n * itself: light dismiss and Escape come from the browser.\n *\n * A menu naming an invoker by id through `for` belongs to that element: the\n * invoker toggles it, and it is anchored to the invoker through\n * `Anchors.wire`, placed in script where the platform has no css anchor\n * positioning. A menu without `for` is shared: one menu serves many\n * invokers, such as the \"more\" button of every row of a list, and a page\n * opens it beside the invoker it is for with `showFor(invoker)`.\n *\n * The items are the buttons and `a[href]` links written as its direct\n * children, kept as they are. Activation is the item's own click, which the\n * menu follows by hiding itself, so a page listens for the click where it\n * already listens. The menu fires no events of its own.\n *\n * The keyboard is the ARIA menu protocol: the focus moves to the\n * first item as the menu opens, the arrows, Home and End walk the items,\n * typing searches their text, Enter and Space activate the focused one, and\n * Escape and a close from inside the menu hand the focus back to the invoker\n * that opened it.\n */\nclass Menu extends ParsedElement {\n /** @type {string[]} */\n static attributes = ['for'];\n /** @type {HTMLElement|null} */\n #invoker = null;\n /** @type {HTMLElement|null} */\n #pressed = null;\n /**\n * Gives the menu the `menu` role and an empty `popover` attribute unless\n * it already has one, and marks the items. With `for`, read here once, it\n * also gives the invoker `aria-haspopup=\"menu\"`, an `aria-expanded` kept\n * in step, and the toggle of the menu.\n * @returns {void}\n * @throws {Error} when `for` is given and names no element in the document at the render\n */\n render() {\n const named = this.declared('for');\n const invoker = named ? document.getElementById(named) : null;\n if (named && !invoker) {\n throw new Error(\n `ful-menu names no invoker: for=\"${named}\" must name an element already in the page when the menu upgrades`,\n );\n }\n this.setAttribute('role', 'menu');\n if (!this.hasAttribute('popover')) {\n this.setAttribute('popover', '');\n }\n if (invoker) {\n this.#invoker = invoker;\n invoker.setAttribute('aria-haspopup', 'menu');\n Anchors.wire(invoker, this, { prefix: 'ful-menu', invoke: true, expanded: true });\n } else {\n this.#wireShared();\n }\n wireMenuKeys(() => this.#invoker, this, { items: () => this.items });\n this.#mark();\n this.addEventListener('click', (evt) => {\n const target = /** @type HTMLElement */ (evt.target);\n if (this.items.some((item) => item === target || item.contains(target))) {\n this.hidePopover();\n }\n });\n }\n /**\n * Opens a shared menu, one without `for`, beside `invoker`, or moves it\n * there when it is open for another one. The menu goes below the invoker,\n * or above it where there is no room below, and is placed once, as\n * `Anchors.show` places it. The invoker gets `aria-haspopup=\"menu\"` and an\n * `aria-expanded` that reads true until the menu closes, and the focus\n * goes back to it on Escape. A call for the invoker whose press has just\n * closed the menu does nothing, so a second click on the same button\n * closes the menu rather than opening it again.\n * @param {HTMLElement} invoker the element the menu opens for\n * @returns {void}\n * @throws {Error} when the menu names its invoker through `for`\n */\n showFor(invoker) {\n if (this.declared('for')) {\n throw new Error('ful-menu: showFor serves a menu without for; a menu with for is opened by its invoker');\n }\n const pressed = this.#pressed;\n this.#pressed = null;\n if (pressed === invoker) {\n return;\n }\n if (this.#invoker && this.#invoker !== invoker) {\n this.#invoker.setAttribute('aria-expanded', 'false');\n }\n this.#invoker = invoker;\n invoker.setAttribute('aria-haspopup', 'menu');\n invoker.setAttribute('aria-expanded', 'true');\n //the previous placement wrote margin: 0 inline, hiding the stylesheet's gap\n this.style.margin = '';\n const gap = Number.parseFloat(getComputedStyle(this).marginBlockStart) || 0;\n const moving = this.matches(':popover-open');\n Anchors.show(this, invoker, { flip: true, gap });\n if (moving) {\n this.items[0]?.focus();\n }\n }\n /**\n * The commands, in the order the arrows walk them: the menu's direct\n * `button` and `a[href]` children, minus those carrying a `disabled` or\n * `hidden` attribute, which keep their role and leave the walk. Reading it\n * also marks any child added since the render, giving it the `menuitem`\n * role, unless it has a role already, and a `tabIndex` of -1.\n * @type {HTMLElement[]}\n */\n get items() {\n return this.#mark().filter((item) => !item.hasAttribute('disabled') && !item.hasAttribute('hidden'));\n }\n #wireShared() {\n document.addEventListener(\n 'pointerdown',\n (evt) => {\n const target = /** @type Node */ (evt.target);\n this.#pressed = this.matches(':popover-open') && this.#invoker?.contains(target) ? this.#invoker : null;\n },\n true,\n );\n this.addEventListener('toggle', (/** @type any */ evt) => {\n if (evt.newState === 'closed') {\n this.#invoker?.setAttribute('aria-expanded', 'false');\n }\n });\n }\n /** @returns {HTMLElement[]} every item, disabled and hidden ones included, once marked */\n #mark() {\n const all = /** @type HTMLElement[] */ ([...this.querySelectorAll(':scope > button, :scope > a[href]')]);\n for (const item of all) {\n if (!item.hasAttribute('role')) {\n item.setAttribute('role', 'menuitem');\n }\n item.tabIndex = -1;\n }\n return all;\n }\n}\n\nexport { Menu };\n","import { Localization, ParsedElement } from '../../ftl/index.mjs';\n\nconst SEVERITIES = ['info', 'success', 'warning', 'error'];\n\nconst REGIONS = new Set();\nlet listenerWired = false;\n\n/**\n * @typedef {object} ToastOptions\n * @property {'info'|'success'|'warning'|'error'} [severity] the theme class and\n * the announcement, `info` when absent or unknown\n * @property {number} [timeout] the milliseconds before the toast retires, the\n * region's own timeout when absent\n * @property {{ label: any, onClick?: () => void }} [action] a button labelled\n * with `label` as text, beside the message\n */\n\n/**\n * A region of transient messages, with `role=\"region\"` and a localized\n * `aria-label`. Each `show()` appends a `ful-toast` that retires on its own\n * timer, so concurrent toasts stack.\n *\n * The region is a manual popover, whatever `popover` the page declared, and\n * each `show()` shows it again, so it is on top of the top layer when a toast\n * arrives: above a modal dialog or drawer opened before it. While a modal is\n * open the page outside it is inert, the region included: its toasts show and\n * retire on their timers, and their buttons answer once the modal closes.\n *\n * `timeout` is the region's default timer in milliseconds, 5000 when absent\n * or zero.\n *\n * A `show-toast` event dispatched on the document, or bubbling to it, shows its\n * `detail` in every connected region that has rendered, `detail.message` being\n * the message and the other fields the `ToastOptions`. The document listener is\n * added once, so a second region shows each toast once, and an event with no\n * detail is ignored.\n */\nclass Toasts extends ParsedElement {\n static attributes = ['timeout:number'];\n #timeout;\n /** Upgrades the region, and makes a re-attached one answer `show-toast` again. */\n connectedCallback() {\n super.connectedCallback();\n if (this.rendered) {\n REGIONS.add(this);\n }\n }\n /** Stops the region answering `show-toast` while it is out of the document. */\n disconnectedCallback() {\n REGIONS.delete(this);\n }\n render() {\n this.#timeout = this.declared('timeout') || 5000;\n this.setAttribute('role', 'region');\n this.setAttribute('tabindex', '-1');\n this.setAttribute('aria-label', Localization.of().t('toast.region'));\n this.setAttribute('popover', 'manual');\n if (!listenerWired) {\n listenerWired = true;\n document.addEventListener('show-toast', (/** @type any */ e) => {\n if (!e.detail) {\n return;\n }\n for (const region of REGIONS) {\n region.show(e.detail.message, e.detail);\n }\n });\n }\n REGIONS.add(this);\n }\n /**\n * Appends a `ful-toast` holding the message as text, a `Failure` showing\n * its problems' reasons one per line and anything else its string form\n * (`''` for null or undefined). The toast carries the severity as a class\n * and has `role=\"alert\"` for `error` and `role=\"status\"` otherwise.\n *\n * The toast retires when its timer runs out, when its localized dismiss\n * button is clicked, or when its action button is clicked, after\n * `action.onClick` runs. The timer pauses while the pointer is over the\n * toast or the focus is inside it, and resumes with the time that was left\n * once both have gone. A retiring toast holding the focus moves it to the\n * region, which has `tabindex=\"-1\"` for this. The toast is removed once its\n * `ful-toast-out` animation ends, or at once where the user prefers reduced\n * motion or no animation runs.\n *\n * A connected region is shown again as a popover, which puts it above\n * whatever opened in the top layer since; the focus stays where it was.\n * @param {any} message\n * @param {ToastOptions} [options]\n * @returns {HTMLElement} the toast, already in the region\n */\n show(message, options = {}) {\n const severity = /** @type {string} */ (\n SEVERITIES.includes(/** @type {string} */ (options.severity)) ? options.severity : 'info'\n );\n const item = document.createElement('ful-toast');\n item.classList.add(severity);\n item.setAttribute('role', severity === 'error' ? 'alert' : 'status');\n const body = document.createElement('div');\n body.textContent = Localization.of().failure(message);\n const dismiss = document.createElement('button');\n dismiss.type = 'button';\n dismiss.setAttribute('aria-label', Localization.of().t('toast.dismiss'));\n const icon = document.createElement('ful-icon');\n icon.setAttribute('name', 'x-lg');\n icon.setAttribute('aria-hidden', 'true');\n dismiss.append(icon);\n item.append(body);\n let remaining = options.timeout ?? this.#timeout;\n let startedAt = performance.now();\n let timer = 0;\n const retire = () => {\n clearTimeout(timer);\n if (item.contains(document.activeElement)) {\n /** @type HTMLElement */ (this).focus();\n }\n if (matchMedia('(prefers-reduced-motion: reduce)').matches) {\n item.remove();\n return;\n }\n item.classList.add('ful-toast-out');\n if (item.getAnimations().length === 0) {\n item.remove();\n }\n };\n if (options.action?.label) {\n const action = document.createElement('button');\n action.type = 'button';\n action.className = 'ful-toast-action';\n action.textContent = String(options.action.label);\n action.addEventListener('click', () => {\n /** @type {NonNullable<ToastOptions['action']>} */ (options.action).onClick?.();\n retire();\n });\n item.append(action);\n }\n item.append(dismiss);\n item.addEventListener('animationend', () => {\n if (item.classList.contains('ful-toast-out')) {\n item.remove();\n }\n });\n let holds = 0;\n const hold = () => {\n if (holds === 0) {\n clearTimeout(timer);\n remaining = Math.max(0, remaining - (performance.now() - startedAt));\n }\n ++holds;\n };\n const release = () => {\n if (holds === 0) {\n return;\n }\n if (--holds === 0) {\n startedAt = performance.now();\n timer = setTimeout(retire, remaining);\n }\n };\n item.addEventListener('mouseenter', hold);\n item.addEventListener('mouseleave', release);\n item.addEventListener('focusin', hold);\n item.addEventListener('focusout', release);\n dismiss.addEventListener('click', retire);\n this.append(item);\n this.#raise();\n timer = setTimeout(retire, remaining);\n return item;\n }\n #raise() {\n if (!this.isConnected) {\n return;\n }\n if (this.matches(':popover-open')) {\n this.hidePopover();\n }\n this.showPopover();\n }\n}\n\nexport { Toasts };\n","import { Attributes, ParsedElement } from '../../ftl/index.mjs';\nimport { SectionRequests } from '../events/sections.mjs';\n\n/**\n * A tab panel: one visible panel at a time, announced through the tab pattern\n * (a tablist of tab buttons, each panel a tabpanel labelled by its tab). The\n * tabs are declared as `<tab>` elements in the `tabs` slot, the panels as the\n * slotless children, paired in order. Each `<tab>` becomes a `button` with the\n * `tab` role carrying the tab's content, inside a `ful-tablist` with the\n * `tablist` role. A panel that already has an id keeps it and its tab points at\n * it; a panel without one gets a generated id. Every panel carries\n * `tabindex=\"0\"`, so the visible one follows its tab in the tab order and the\n * hidden ones stay out of it.\n *\n * The tabs use a roving tabindex and automatic activation: a click activates\n * its tab, and on the tablist ArrowRight and ArrowLeft move to the next and\n * previous tab, wrapping around, while Home and End jump to the first and the\n * last, moving the focus with the activation.\n *\n * Entering a panel fires `section:requested` and `section:requested:#<index>`\n * on the host, bubbling, with detail `{ name: null, section, index, first }`,\n * and awaits the answers registered through `AsyncEvents.asyncOn`, so a panel\n * can deliver itself asynchronously: see `SectionRequests`.\n *\n * The tablist stays on one line. When the tabs do not fit it scrolls sideways,\n * and a previous and a next button appear at the side that has more tabs,\n * each bringing the next hidden tab into view. They stay out of the tab order:\n * the keyboard moves through the tabs with the arrow keys. The active tab is\n * kept in view when it changes and when the tablist changes width.\n */\nclass Tabs extends ParsedElement {\n static slots = true;\n static observed = ['active:number'];\n static template = `\n <button type=\"button\" class=\"ful-tabs-scroll\" data-ref=\"scroll-start\" tabindex=\"-1\" hidden data-tpl-aria-label=\"#l10n:t('tabs.previous')\"><ful-icon name=\"chevron-left\" aria-hidden=\"true\"></ful-icon></button>\n <ful-tablist role=\"tablist\">{{{{ slots.tabs }}}}</ful-tablist>\n <button type=\"button\" class=\"ful-tabs-scroll\" data-ref=\"scroll-end\" tabindex=\"-1\" hidden data-tpl-aria-label=\"#l10n:t('tabs.next')\"><ful-icon name=\"chevron-right\" aria-hidden=\"true\"></ful-icon></button>\n {{{{ slots.default }}}}\n `;\n #tablist;\n #scrollStart;\n #scrollEnd;\n #tabs = [];\n #panels = [];\n #requests = new SectionRequests();\n #active = 0;\n /**\n * Pairs the declared tabs with the panels in order. When the counts\n * differ, the unpaired tabs and panels are left in the dom as they are and\n * a warning is logged.\n * @param {{ slots: Record<string, DocumentFragment> }} conf\n * @returns {void}\n */\n render({ slots }) {\n const fragment = this.template().withOverlay({ slots }).render();\n this.#tablist = fragment.querySelector('ful-tablist');\n this.#scrollStart = fragment.querySelector('[data-ref=\"scroll-start\"]');\n this.#scrollEnd = fragment.querySelector('[data-ref=\"scroll-end\"]');\n const chrome = [this.#tablist, this.#scrollStart, this.#scrollEnd];\n const declared = [...this.#tablist.children];\n this.#panels = [...fragment.children].filter((el) => !chrome.includes(el));\n if (declared.length !== this.#panels.length) {\n console.warn(\n `ful-tabs: ${declared.length} tabs declared for ${this.#panels.length} panels, the surplus is left alone`,\n );\n }\n const count = Math.min(declared.length, this.#panels.length);\n this.#tabs = [];\n for (let i = 0; i !== count; ++i) {\n const panel = this.#panels[i];\n const tab = document.createElement('button');\n tab.type = 'button';\n tab.role = 'tab';\n tab.id = Attributes.uid('ful-tab');\n if (!panel.id) {\n panel.id = Attributes.uid('ful-tabpanel');\n }\n tab.setAttribute('aria-controls', panel.id);\n panel.role = 'tabpanel';\n panel.setAttribute('aria-labelledby', tab.id);\n panel.tabIndex = 0;\n tab.append(...declared[i].childNodes);\n tab.addEventListener('click', () => {\n this.active = i;\n });\n declared[i].replaceWith(tab);\n this.#tabs.push(tab);\n }\n this.#tablist.addEventListener('keydown', (e) => {\n const current = this.#active;\n /** @type {number|null} */\n let target = null;\n if (e.key === 'ArrowRight') {\n target = (current + 1) % this.#tabs.length;\n } else if (e.key === 'ArrowLeft') {\n target = (current - 1 + this.#tabs.length) % this.#tabs.length;\n } else if (e.key === 'Home') {\n target = 0;\n } else if (e.key === 'End') {\n target = this.#tabs.length - 1;\n }\n if (target === null || target === current) {\n return;\n }\n e.preventDefault();\n this.active = target;\n this.#tabs[target].focus();\n });\n this.#scrollStart.addEventListener('click', () => this.#scrollByOneTab(-1));\n this.#scrollEnd.addEventListener('click', () => this.#scrollByOneTab(1));\n this.#tablist.addEventListener('scroll', () => this.#showScrollButtons(), { passive: true });\n let width = -1;\n const resizes = new ResizeObserver(() => {\n this.#showScrollButtons();\n if (this.#tablist.clientWidth !== width) {\n width = this.#tablist.clientWidth;\n this.#bringIntoView(this.#tabs[this.#active], 'auto');\n }\n });\n resizes.observe(this.#tablist);\n for (const tab of this.#tabs) {\n resizes.observe(tab);\n }\n this.replaceChildren(fragment);\n }\n /**\n * Shows each scroll button only when there are tabs beyond its side, and\n * sizes both to the height of the tablist above its border.\n * @returns {void}\n */\n #showScrollButtons() {\n const list = this.#tablist;\n const overflow = list.scrollWidth - list.clientWidth;\n this.#scrollStart.hidden = list.scrollLeft <= 1;\n this.#scrollEnd.hidden = list.scrollLeft >= overflow - 1;\n this.#scrollStart.style.blockSize = this.#scrollEnd.style.blockSize = `${list.clientHeight}px`;\n }\n /**\n * The part of the tablist that no scroll button covers.\n * @returns {{ start: number, end: number }}\n */\n #visibleRange() {\n const view = this.#tablist.getBoundingClientRect();\n return { start: view.left + this.#scrollStart.offsetWidth, end: view.right - this.#scrollEnd.offsetWidth };\n }\n /**\n * Scrolls the tablist so that the first tab cut by the side the direction\n * points to is wholly visible.\n * @param {1 | -1} direction 1 towards the end, -1 towards the start\n * @returns {void}\n */\n #scrollByOneTab(direction) {\n const { start, end } = this.#visibleRange();\n const target =\n direction > 0\n ? this.#tabs.find((tab) => tab.getBoundingClientRect().right > end + 1)\n : this.#tabs.findLast((tab) => tab.getBoundingClientRect().left < start - 1);\n this.#bringIntoView(target, matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth');\n }\n /**\n * Scrolls the tablist, and only the tablist, the least needed to show a tab\n * wholly.\n * @param {HTMLElement | undefined} tab\n * @param {ScrollBehavior} behavior\n * @returns {void}\n */\n #bringIntoView(tab, behavior) {\n if (!tab) {\n return;\n }\n const { start, end } = this.#visibleRange();\n const box = tab.getBoundingClientRect();\n const delta = box.right > end ? Math.ceil(box.right - end) : box.left < start ? Math.floor(box.left - start) : 0;\n if (delta !== 0) {\n this.#tablist.scrollBy({ left: delta, behavior });\n }\n }\n /**\n * The index of the visible panel, reflected to the `active` attribute.\n * Writing it clamps the value to the paired tabs, a value that is not a\n * number counting as 0, and selects that tab and shows its panel. When the\n * index changes on a rendered element it dispatches `tabs:change` on the\n * host (not bubbling) with detail `{ active, previous }`, then fires the\n * section requests for the entered panel. The first write, which applies\n * the attribute after the render, fires the requests without the event.\n * A failed delivery paints the panel's error and rejects nowhere.\n * @type {number}\n */\n get active() {\n return this.#active;\n }\n /**\n * Fires the section requests again for a panel, whether it is visible or\n * not, with `first` false once an earlier request was answered.\n * @param {number | Element} ref the panel's index, or the panel itself\n * @returns {Promise<any[] | undefined> | undefined} a promise resolving to\n * the answers, or to undefined when nobody listened or the delivery\n * failed (its error painted in the panel); undefined, with a warning, when\n * `ref` names no panel\n */\n refresh(ref) {\n const index = ref instanceof Element ? this.#panels.indexOf(ref) : Number.isInteger(ref) ? ref : NaN;\n const panel = this.#panels[index];\n if (!panel) {\n console.warn(`ful-tabs: no panel answers to \"${ref}\"`);\n return undefined;\n }\n return this.#requests.request(this, panel, null, index).catch(() => undefined);\n }\n set active(v) {\n const index = Math.min(Math.max(0, Number(v) || 0), Math.max(0, this.#tabs.length - 1));\n const previous = this.#active;\n for (const [i, tab] of this.#tabs.entries()) {\n tab.setAttribute('aria-selected', i === index ? 'true' : 'false');\n tab.tabIndex = i === index ? 0 : -1;\n this.#panels[i].hidden = i !== index;\n }\n this.#active = index;\n this.reflectTo('active', index);\n this.#bringIntoView(this.#tabs[index], 'auto');\n if (this.rendered && index !== previous) {\n this.dispatchEvent(new CustomEvent('tabs:change', { detail: { active: index, previous } }));\n }\n if (this.#panels.length > 0 && (index !== previous || !this.rendered)) {\n this.#requests.request(this, this.#panels[index], null, index).catch(() => undefined);\n }\n }\n}\n\nexport { Tabs };\n","import { Attributes, ParsedElement } from '../../ftl/index.mjs';\n\n/**\n * An accordion over native `details`/`summary` disclosures: the browser\n * provides the semantics, the keyboard and the toggling, and the element adds\n * the group's styling. The `details` written as its children are rendered,\n * unchanged, inside a `ful-accordion-group`.\n */\nclass Accordion extends ParsedElement {\n static slots = true;\n /** @type {string[]} */\n static observed = ['exclusive:presence'];\n static template = `\n <ful-accordion-group>{{{{ slots.default }}}}</ful-accordion-group>\n `;\n #group;\n #exclusive = false;\n /**\n * @param {{ slots: Record<string, DocumentFragment> | undefined }} c\n * @returns {void}\n */\n render({ slots }) {\n const fragment = this.template().withOverlay({ slots }).render();\n this.#group = fragment.querySelector('ful-accordion-group');\n this.replaceChildren(fragment);\n }\n /**\n * Whether opening one panel closes the others, reflected to the\n * `exclusive` attribute; only `true` turns it on. Setting it gives the\n * group's direct `details` children one shared, newly generated `name`,\n * the platform's exclusive grouping, or removes their `name` when off.\n * A `details` added to the group afterwards is not named until the next\n * write.\n * @type {boolean}\n */\n get exclusive() {\n return this.#exclusive;\n }\n set exclusive(v) {\n this.#exclusive = v === true;\n this.reflectTo('exclusive', this.#exclusive);\n const name = this.#exclusive ? Attributes.uid('ful-accordion') : null;\n for (const details of this.#group.querySelectorAll(':scope > details')) {\n if (name === null) {\n details.removeAttribute('name');\n } else {\n details.setAttribute('name', name);\n }\n }\n }\n}\n\nexport { Accordion };\n","import { ParsedElement } from '../../ftl/index.mjs';\nimport { SectionRequests } from '../events/sections.mjs';\n\n/**\n * A wizard: a progress of steps over one-of-N sections. The steps are declared\n * as `<step>` elements in the `steps` slot, the sections as the slotless\n * children, paired in order; each section may carry a `data-step` name, which\n * is what `move()` and `refresh()` answer to. The steps become the items of an\n * `ol` inside `ful-steps`, labelled by the localized `wizard.progress`.\n *\n * The current step is the `aria-current=\"step\"` claim, carried by the step and\n * its section together, and the stylesheet hides every `section` child that\n * does not carry it. A section that carries the claim in the markup when the\n * wizard renders stays current; otherwise the first section is. Every paired\n * section gets `tabindex=\"-1\"`, so a move can focus it.\n *\n * Entering a section, the first one at the render included, fires\n * `section:requested`, `section:requested:#<index>` and, when the section has a\n * `data-step`, `section:requested:<name>` on the host, bubbling, with detail\n * `{ name, section, index, first }`, and awaits the answers registered through\n * `AsyncEvents.asyncOn`: see `SectionRequests`. A failure of the initial entry\n * paints the section's error and rejects nowhere.\n */\nclass Wizard extends ParsedElement {\n static slots = true;\n static observed = ['progress'];\n static template = `\n <ful-steps><ol data-tpl-aria-label=\"#l10n:t('wizard.progress')\">{{{{ slots.steps }}}}</ol></ful-steps>\n {{{{ slots.default }}}}\n `;\n #steps = [];\n #sections = [];\n #requests = new SectionRequests();\n #index = 0;\n #progress;\n /**\n * Pairs the declared steps with the sections in order. When the counts\n * differ, the unpaired steps and sections are left in the dom as they are\n * and a warning is logged.\n * @param {{ slots: Record<string, DocumentFragment> }} conf\n * @returns {void}\n */\n render({ slots }) {\n const fragment = this.template().withOverlay({ slots }).render();\n const list = /** @type {HTMLElement} */ (fragment.querySelector('ful-steps ol'));\n const declared = [...list.children];\n this.#sections = [...fragment.children].filter((el) => el.localName !== 'ful-steps');\n if (declared.length !== this.#sections.length) {\n console.warn(\n `ful-wizard: ${declared.length} steps declared for ${this.#sections.length} sections, the surplus is left alone`,\n );\n }\n const count = Math.min(declared.length, this.#sections.length);\n this.#steps = [];\n for (let i = 0; i !== count; ++i) {\n const li = document.createElement('li');\n li.append(...declared[i].childNodes);\n declared[i].replaceWith(li);\n this.#steps.push(li);\n this.#sections[i].tabIndex = -1;\n }\n this.replaceChildren(fragment);\n if (count > 0) {\n const claimed = this.#sections.findIndex((s) => s.getAttribute('aria-current') === 'step');\n this.#apply(claimed === -1 ? 0 : Math.min(claimed, count - 1));\n this.#enter(this.#index).catch(() => undefined);\n }\n }\n /**\n * The zero-based position of the current step.\n * @type {number}\n */\n get index() {\n return this.#index;\n }\n /**\n * The `data-step` of the current section, or null when it has none or no\n * section is paired.\n * @type {string | null}\n */\n get step() {\n return this.#sections[this.#index]?.getAttribute('data-step') ?? null;\n }\n /**\n * The shape of the progress chrome, reflected to the `progress` attribute:\n * unset shows the current step alone, `timeline` every step as done,\n * current or future, `dots` one dot per step, `none` no progress at all.\n * The value only drives the stylesheet; the moves are the same in every\n * shape.\n * @type {string | null}\n */\n get progress() {\n return this.#progress;\n }\n set progress(v) {\n this.#progress = v;\n this.reflectTo('progress', v);\n }\n /**\n * Moves to the following step; at the last step nothing happens.\n * @returns {Promise<any[] | undefined> | undefined} what `move()` answers\n * @throws what the entered section's delivery rejected with, as the rejection\n * of the returned promise\n */\n next() {\n return this.#move(this.#index + 1);\n }\n /**\n * Moves to the preceding step; at the first step nothing happens.\n * @returns {Promise<any[] | undefined> | undefined} what `move()` answers\n * @throws what the entered section's delivery rejected with, as the rejection\n * of the returned promise\n */\n prev() {\n return this.#move(this.#index - 1);\n }\n /**\n * Moves to the section carrying `data-step=\"<ref>\"`. A move makes that step\n * and section current, moves the focus to the section, dispatches\n * `wizard:change` on the host (not bubbling) with detail `{ index, step }`,\n * then fires the section requests for it.\n * @param {string} ref the section's `data-step`\n * @returns {Promise<any[] | undefined> | undefined} a promise resolving to\n * the answers once they are delivered, or to undefined when nobody\n * listened; undefined when the section is already current, and undefined\n * with a warning when no section carries `ref`\n * @throws what the entered section's delivery rejected with, as the rejection\n * of the returned promise, after its error is painted in the section\n */\n move(ref) {\n const index = this.#sections.findIndex((s) => s.getAttribute('data-step') === ref);\n if (index === -1) {\n console.warn(`ful-wizard: no section carries data-step=\"${ref}\"`);\n return undefined;\n }\n return this.#move(index);\n }\n /**\n * Fires the section requests again for a section, whether it is current or\n * not, with `first` false once an earlier request was answered.\n * @param {string | Element} ref the section's `data-step`, or the section\n * itself\n * @returns {Promise<any[] | undefined> | undefined} a promise resolving to\n * the answers, or to undefined when nobody listened or the delivery failed\n * (its error painted in the section); undefined, with a warning, when `ref`\n * names no section\n */\n refresh(ref) {\n const section =\n ref instanceof Element\n ? ref\n : typeof ref === 'string'\n ? this.#sections.find((s) => s.getAttribute('data-step') === ref)\n : undefined;\n const index = this.#sections.indexOf(section);\n if (index === -1) {\n console.warn(`ful-wizard: no section answers to \"${ref}\"`);\n return undefined;\n }\n return this.#enter(index).catch(() => undefined);\n }\n #enter(index) {\n return this.#requests.request(\n this,\n this.#sections[index],\n this.#sections[index].getAttribute('data-step'),\n index,\n );\n }\n #move(index) {\n const clamped = Math.min(Math.max(0, index), Math.max(0, this.#steps.length - 1));\n if (clamped === this.#index) {\n return undefined;\n }\n this.#apply(clamped);\n this.#sections[this.#index].focus();\n if (this.rendered) {\n this.dispatchEvent(new CustomEvent('wizard:change', { detail: { index: this.#index, step: this.step } }));\n }\n return this.#enter(clamped);\n }\n #apply(index) {\n for (const [i, step] of this.#steps.entries()) {\n if (i === index) {\n step.setAttribute('aria-current', 'step');\n this.#sections[i].setAttribute('aria-current', 'step');\n } else {\n step.removeAttribute('aria-current');\n this.#sections[i].removeAttribute('aria-current');\n }\n }\n this.#index = index;\n }\n}\n\nexport { Wizard };\n","import { HttpClient } from '../httpc/index.mjs';\nimport { Localization } from '../ftl/index.mjs';\nimport { Checkbox } from './forms/checkbox.mjs';\nimport { LocalDate, Instant, InputLocalDate, InputLocalTime, InputInstant } from './forms/temporals.mjs';\nimport { BooleanFilter, InFilter, InstantFilter, LocalDateFilter, NumberFilter, TextFilter } from './forms/filters.mjs';\nimport { FormLoader, Form } from './forms/form.mjs';\nimport { Input } from './forms/input.mjs';\nimport { InputFile } from './forms/files.mjs';\nimport { RadioGroup } from './forms/radio.mjs';\nimport { SelectLoader, Dropdown, Select } from './forms/select.mjs';\nimport { Tooltip } from './disclosures/tooltip.mjs';\nimport { Dialog } from './disclosures/dialog.mjs';\nimport { Drawer } from './disclosures/drawer.mjs';\nimport { Menu } from './disclosures/menu.mjs';\nimport { Toasts } from './disclosures/toast.mjs';\nimport { Tabs } from './navigation/tabs.mjs';\nimport { Accordion } from './disclosures/accordion.mjs';\nimport { Wizard } from './navigation/wizard.mjs';\nimport { TableLoader, Table, Pagination, SortButton } from './navigation/table.mjs';\nimport en from './l10n/en.mjs';\nimport it from './l10n/it.mjs';\nimport es from './l10n/es.mjs';\nimport fr from './l10n/fr.mjs';\n\nconst BUILTIN = { en, it, es, fr };\n\n/**\n * Registers everything ful provides on a registry: the elements, the loader\n * components, an http client, and the translations for the configured\n * language. A page calls `registry.plugin(new Plugin({…})).configure()` once;\n * `registry.plugin` calls this plugin's `configure`.\n */\nclass Plugin {\n #language;\n #translations;\n #httpClient;\n\n /**\n * @param {{ language?: string, translations?: Record<string, any>, httpClient?: HttpClient }} [options]\n * `language` is fixed for the page: a full BCP-47 tag or a primary subtag,\n * defaulting to `navigator.language`, then to 'en'. Its primary subtag,\n * lowercased, picks the built-in translations (en, it, es, fr); the messages\n * are the english ones, overridden by that language's, overridden by\n * `translations`, so a language without built-in translations reads in\n * english. `translations` is a flat map of keys to messages: reword built-in\n * keys ('pagination.showing', …) or add your own ('checkout.total', …).\n * `httpClient` is the client every ful component fetches through, registered\n * as the `http-client` component; without one, `configure` builds a client\n * that sends the csrf token and navigates to '/' on a 401 response.\n */\n constructor(options = {}) {\n this.#language = options.language ?? navigator?.language ?? 'en';\n this.#translations = options.translations ?? {};\n this.#httpClient = options.httpClient ?? null;\n }\n\n /**\n * Defines on `registry` the `l10n` module, the `http-client` component,\n * every `ful-*` element, the `loaders:select`, `loaders:form` and\n * `loaders:table` components, and an overlay publishing `l10n` (the merged\n * messages) and `locale` (the `language` as given) to every template.\n * @param {{ defineModule(name: string, module: any): any, defineComponent(name: string, component: any): any, defineElement(tag: string, klass: CustomElementConstructor): any, defineOverlay(...data: any[]): any }} registry\n * the ftl `Registry`, each of those methods answering the registry itself\n * @returns {void}\n */\n configure(registry) {\n const httpClient =\n this.#httpClient ?? HttpClient.builder().withCsrfToken().withRedirectOnUnauthorized('/').build();\n const language = this.#language.split('-')[0].toLowerCase();\n const l10n = { ...BUILTIN.en, ...BUILTIN[language], ...this.#translations };\n registry\n .defineModule('l10n', Localization)\n .defineComponent('http-client', httpClient)\n .defineElement('ful-tooltip', Tooltip)\n .defineElement('ful-dialog', Dialog)\n .defineElement('ful-drawer', Drawer)\n .defineElement('ful-menu', Menu)\n .defineElement('ful-toasts', Toasts)\n .defineElement('ful-tabs', Tabs)\n .defineElement('ful-accordion', Accordion)\n .defineElement('ful-wizard', Wizard)\n .defineElement('ful-form', Form)\n .defineElement('ful-checkbox', Checkbox)\n .defineElement('ful-input', Input)\n .defineElement('ful-input-file', InputFile)\n .defineElement('ful-local-date', LocalDate)\n .defineElement('ful-instant', Instant)\n .defineElement('ful-input-local-date', InputLocalDate)\n .defineElement('ful-input-local-time', InputLocalTime)\n .defineElement('ful-input-instant', InputInstant)\n .defineElement('ful-radio-group', RadioGroup)\n .defineElement('ful-table', Table)\n .defineElement('ful-pagination', Pagination)\n .defineElement('ful-sorter', SortButton)\n .defineElement('ful-filter-instant', InstantFilter)\n .defineElement('ful-filter-local-date', LocalDateFilter)\n .defineElement('ful-filter-number', NumberFilter)\n .defineElement('ful-filter-boolean', BooleanFilter)\n .defineElement('ful-filter-text', TextFilter)\n .defineElement('ful-filter-in', InFilter)\n .defineElement('ful-select', Select)\n .defineElement('ful-dropdown', Dropdown)\n .defineComponent('loaders:select', SelectLoader)\n .defineComponent('loaders:form', FormLoader)\n .defineComponent('loaders:table', TableLoader)\n .defineOverlay({\n l10n,\n locale: this.#language,\n });\n }\n}\n\nexport { Plugin };\n","export default {\n 'pagination.showing': 'Page {current} of {total}',\n 'pagination.navigation': 'Page navigation',\n 'pagination.previous': 'Previous',\n 'pagination.next': 'Next',\n 'pagination.reload': 'Reload',\n 'table.initial': 'Start searching to see results.',\n 'table.error': 'Error while loading data:',\n 'table.no-data': 'No elements found.',\n 'dropdown.empty': 'No results',\n 'select.remove': 'Remove',\n 'files.dropzone-label': 'Click or drop your files here',\n 'files.remove': 'Remove',\n 'files.unacceptable-file-type': 'Only files of type {types} are supported',\n 'files.max-file-size-exceeded': 'Maximum supported file size is {size}',\n 'files.max-total-size-exceeded': 'Maximum supported total file size is {size}',\n 'files.max-files-exceeded': { one: 'Maximum of {count} file exceeded', other: 'Maximum of {count} files exceeded' },\n 'filters.op.EQ': 'Equals',\n 'filters.op.NEQ': 'Not equal',\n 'filters.op.LT': 'Less than',\n 'filters.op.GT': 'Greater than',\n 'filters.op.LTE': 'At most',\n 'filters.op.GTE': 'At least',\n 'filters.op.BETWEEN': 'Between',\n 'filters.op.CONTAINS': 'Contains',\n 'filters.op.STARTS_WITH': 'Starts with',\n 'filters.op.ENDS_WITH': 'Ends with',\n 'filters.sensitivity.IGNORE_CASE': 'Ignore case',\n 'filters.sensitivity.CASE_SENSITIVE': 'Case sensitive',\n 'filters.boolean.any': 'Any',\n 'filters.boolean.true': 'Yes',\n 'filters.boolean.false': 'No',\n 'info.tooltip': 'More information',\n 'failure.no-reason': 'Something went wrong',\n 'dialog.acknowledge': 'Got it',\n 'dialog.close': 'Close',\n 'dialog.confirm': 'Confirm',\n 'dialog.cancel': 'Cancel',\n 'dialog.discard.header': 'Unsaved changes',\n 'dialog.discard.body': 'There are unsaved changes: close anyway?',\n 'dialog.discard.confirm': 'Close without saving',\n 'dialog.discard.cancel': 'Keep editing',\n 'drawer.close': 'Close',\n 'spinner.loading': 'Loading…',\n 'tabs.previous': 'Previous tabs',\n 'tabs.next': 'Next tabs',\n 'toast.region': 'Notifications',\n 'toast.dismiss': 'Dismiss',\n 'wizard.progress': 'Progress',\n};\n","export default {\n 'pagination.showing': 'Pagina {current} di {total}',\n 'pagination.navigation': 'Navigazione pagine',\n 'pagination.previous': 'Precedente',\n 'pagination.next': 'Successivo',\n 'pagination.reload': 'Ricarica',\n 'table.initial': 'Avvia la ricerca per visualizzare i risultati.',\n 'table.error': 'Errore nel caricamento dei dati:',\n 'table.no-data': 'Nessun elemento trovato.',\n 'dropdown.empty': 'Nessun risultato',\n 'select.remove': 'Rimuovi',\n 'files.dropzone-label': 'Clicca o trascina i file qui',\n 'files.remove': 'Rimuovi',\n 'files.unacceptable-file-type': 'Solo i file di tipo {types} sono supportati',\n 'files.max-file-size-exceeded': 'La dimensione massima di un file è di {size}',\n 'files.max-total-size-exceeded': 'La dimensione massima complessiva dei file è di {size}',\n 'files.max-files-exceeded': { other: 'Superato il numero massimo di {count} file' },\n 'filters.op.EQ': 'Uguale',\n 'filters.op.NEQ': 'Diverso',\n 'filters.op.LT': 'Minore',\n 'filters.op.GT': 'Maggiore',\n 'filters.op.LTE': 'Al massimo',\n 'filters.op.GTE': 'Almeno',\n 'filters.op.BETWEEN': 'Tra',\n 'filters.op.CONTAINS': 'Contiene',\n 'filters.op.STARTS_WITH': 'Inizia con',\n 'filters.op.ENDS_WITH': 'Termina con',\n 'filters.sensitivity.IGNORE_CASE': 'Ignora maiuscole',\n 'filters.sensitivity.CASE_SENSITIVE': 'Distingui maiuscole',\n 'filters.boolean.any': 'Qualsiasi',\n 'filters.boolean.true': 'Sì',\n 'filters.boolean.false': 'No',\n 'info.tooltip': 'Maggiori informazioni',\n 'failure.no-reason': 'Si è verificato un errore',\n 'dialog.acknowledge': 'Ho capito',\n 'dialog.close': 'Chiudi',\n 'dialog.confirm': 'Conferma',\n 'dialog.cancel': 'Annulla',\n 'dialog.discard.header': 'Modifiche non salvate',\n 'dialog.discard.body': 'Ci sono modifiche non salvate: chiudere comunque?',\n 'dialog.discard.confirm': 'Chiudi senza salvare',\n 'dialog.discard.cancel': 'Continua a modificare',\n 'drawer.close': 'Chiudi',\n 'spinner.loading': 'Caricamento…',\n 'tabs.previous': 'Schede precedenti',\n 'tabs.next': 'Schede successive',\n 'toast.region': 'Notifiche',\n 'toast.dismiss': 'Chiudi',\n 'wizard.progress': 'Avanzamento',\n};\n","export default {\n 'pagination.showing': 'Página {current} de {total}',\n 'pagination.navigation': 'Navegación de páginas',\n 'pagination.previous': 'Anterior',\n 'pagination.next': 'Siguiente',\n 'pagination.reload': 'Recargar',\n 'table.initial': 'Inicia la búsqueda para ver los resultados.',\n 'table.error': 'Error al cargar los datos:',\n 'table.no-data': 'No se encontraron elementos.',\n 'dropdown.empty': 'Sin resultados',\n 'select.remove': 'Eliminar',\n 'files.dropzone-label': 'Haz clic o arrastra tus archivos aquí',\n 'files.remove': 'Eliminar',\n 'files.unacceptable-file-type': 'Solo se admiten archivos de tipo {types}',\n 'files.max-file-size-exceeded': 'El tamaño máximo de archivo admitido es {size}',\n 'files.max-total-size-exceeded': 'El tamaño total máximo admitido es {size}',\n 'files.max-files-exceeded': {\n one: 'Se ha superado el número máximo de {count} archivo',\n other: 'Se ha superado el número máximo de {count} archivos',\n },\n 'filters.op.EQ': 'Igual',\n 'filters.op.NEQ': 'Distinto',\n 'filters.op.LT': 'Menor',\n 'filters.op.GT': 'Mayor',\n 'filters.op.LTE': 'Como máximo',\n 'filters.op.GTE': 'Al menos',\n 'filters.op.BETWEEN': 'Entre',\n 'filters.op.CONTAINS': 'Contiene',\n 'filters.op.STARTS_WITH': 'Empieza por',\n 'filters.op.ENDS_WITH': 'Termina por',\n 'filters.sensitivity.IGNORE_CASE': 'Ignorar mayúsculas',\n 'filters.sensitivity.CASE_SENSITIVE': 'Distinguir mayúsculas',\n 'filters.boolean.any': 'Cualquiera',\n 'filters.boolean.true': 'Sí',\n 'filters.boolean.false': 'No',\n 'info.tooltip': 'Más información',\n 'failure.no-reason': 'Se ha producido un error',\n 'dialog.acknowledge': 'Entendido',\n 'dialog.close': 'Cerrar',\n 'dialog.confirm': 'Confirmar',\n 'dialog.cancel': 'Cancelar',\n 'dialog.discard.header': 'Cambios sin guardar',\n 'dialog.discard.body': 'Hay cambios sin guardar: ¿cerrar de todos modos?',\n 'dialog.discard.confirm': 'Cerrar sin guardar',\n 'dialog.discard.cancel': 'Seguir editando',\n 'drawer.close': 'Cerrar',\n 'spinner.loading': 'Cargando…',\n 'tabs.previous': 'Pestañas anteriores',\n 'tabs.next': 'Pestañas siguientes',\n 'toast.region': 'Notificaciones',\n 'toast.dismiss': 'Cerrar',\n 'wizard.progress': 'Progreso',\n};\n","export default {\n 'pagination.showing': 'Page {current} sur {total}',\n 'pagination.navigation': 'Navigation des pages',\n 'pagination.previous': 'Précédent',\n 'pagination.next': 'Suivant',\n 'pagination.reload': 'Recharger',\n 'table.initial': 'Lancez la recherche pour voir les résultats.',\n 'table.error': 'Erreur lors du chargement des données :',\n 'table.no-data': 'Aucun élément trouvé.',\n 'dropdown.empty': 'Aucun résultat',\n 'select.remove': 'Retirer',\n 'files.dropzone-label': 'Cliquez ou déposez vos fichiers ici',\n 'files.remove': 'Retirer',\n 'files.unacceptable-file-type': 'Seuls les fichiers de type {types} sont pris en charge',\n 'files.max-file-size-exceeded': 'La taille maximale de fichier prise en charge est {size}',\n 'files.max-total-size-exceeded': 'La taille totale maximale prise en charge est {size}',\n 'files.max-files-exceeded': {\n one: 'Nombre maximal de {count} fichier dépassé',\n other: 'Nombre maximal de {count} fichiers dépassé',\n },\n 'filters.op.EQ': 'Égal',\n 'filters.op.NEQ': 'Différent',\n 'filters.op.LT': 'Inférieur',\n 'filters.op.GT': 'Supérieur',\n 'filters.op.LTE': 'Au plus',\n 'filters.op.GTE': 'Au moins',\n 'filters.op.BETWEEN': 'Entre',\n 'filters.op.CONTAINS': 'Contient',\n 'filters.op.STARTS_WITH': 'Commence par',\n 'filters.op.ENDS_WITH': 'Finit par',\n 'filters.sensitivity.IGNORE_CASE': 'Ignorer la casse',\n 'filters.sensitivity.CASE_SENSITIVE': 'Respecter la casse',\n 'filters.boolean.any': 'Indifférent',\n 'filters.boolean.true': 'Oui',\n 'filters.boolean.false': 'Non',\n 'info.tooltip': 'Plus d’informations',\n 'failure.no-reason': \"Une erreur s'est produite\",\n 'dialog.acknowledge': 'J’ai compris',\n 'dialog.close': 'Fermer',\n 'dialog.confirm': 'Confirmer',\n 'dialog.cancel': 'Annuler',\n 'dialog.discard.header': 'Modifications non enregistrées',\n 'dialog.discard.body': 'Des modifications ne sont pas enregistrées : fermer quand même ?',\n 'dialog.discard.confirm': 'Fermer sans enregistrer',\n 'dialog.discard.cancel': 'Continuer à modifier',\n 'drawer.close': 'Fermer',\n 'spinner.loading': 'Chargement…',\n 'tabs.previous': 'Onglets précédents',\n 'tabs.next': 'Onglets suivants',\n 'toast.region': 'Notifications',\n 'toast.dismiss': 'Fermer',\n 'wizard.progress': 'Progression',\n};\n"],"names":["storage","backing","remove","k","removeItem","load","got","getItem","JSON","parse","save","v","setItem","stringify","pop","decoded","versioned","store","key","revision","data","stored","LocalStorage","localStorage","SessionStorage","sessionStorage","VersionedLocalStorage","VersionedSessionStorage","AsyncEvents","fireAsync","el","evt","options","dispatchEvent","promises","async","mode","length","Promise","all","catch","Error","type","resolve","asyncOn","fn","listener","event","ae","promise","reject","withResolvers","push","e","addEventListener","asyncOff","removeEventListener","mixInto","classes","Object","assign","prototype","this","PageLeave","guard","isDirty","signal","window","preventDefault","Claims","generation","take","hold","held","claims","stale","invalidate","describable","at","parentElement","Timing","sleep","ms","setTimeout","debounce","timeoutMs","func","immediate","tid","args","previousTimestamp","later","elapsed","performance","now","called","clearTimeout","undefined","throttle","leading","trailing","remaining","Bindings","flatten","obj","prefix","stops","keys","reduce","acc","pre","has","static","Set","providePath","result","path","value","split","map","test","FORBIDDEN","current","previous","i","ckey","pkey","Number","isInteger","Array","isArray","extract","getAttribute","checked","dataset","fulBindType","tagName","multiple","from","selectedOptions","o","submits","extractFrom","form","submitter","elements","hasAttribute","matches","mutate","raw","values","String","forEach","selected","includes","mutateIn","named","flattenedKey","entries","get","Map","name","bucket","set","errors","es","scrollOnError","ofForm","closest","querySelectorAll","filter","setAttribute","pinned","context","fieldErrors","globalErrors","targets","setCustomValidity","unmatched","parts","replace","slice","join","input","reason","bannered","hel","replaceChildren","removeAttribute","innerText","sort","a","b","getBoundingClientRect","y","focus","Field","ParsedElement","control","pendingFocus","described","descriptions","errorId","fieldError","announces","also","constructor","super","internals","role","ROLE","mirrors","wire","fragment","error","label","freeze","readonly","id","Attributes","uid","describe","defaultPrevented","isComposing","target","submitsOnEnter","_requestSubmit","HTMLInputElement","describedBy","ids","setValidity","customError","candidates","requestSubmit","find","_notifyChange","extras","CustomEvent","bubbles","cancelable","detail","field","LABELABLE","_interactive","formResetCallback","unmarshal","disabled","d","reflectTo","toggleAttribute","readOnly","required","render","conf","built","_build","then","pieces","RemoteJsonFormLoader","http","url","method","requestMapper","responseMapper","prepare","submit","request","json","fetch","transform","response","LocalFormLoader","FormLoader","create","component","declared","ownerOf","formAssociated","Form","document","createElement","forward","childNodes","stopPropagation","stopImmediatePropagation","tracking","touch","Rendering","waitForChildren","commit","connectedCallback","disconnectedCallback","leave","abort","submitting","spinner","loader","submitted","saved","snapshot","upTo","sequence","se","sre","mapped","commitFrom","exception","Failure","problems","console","warn","dirty","reset","edits","refresh","focused","wasDirty","frame","valuesOf","edited","els","delete","nameOf","requestAnimationFrame","contributing","vs","cancelAnimationFrame","button","states","add","AbortController","spinning","announce","defaultValue","hidden","textContent","trim","className","ref","append","Localization","of","t","spin","Math","max","querySelector","wd","patternCache","BoundedCache","compiled","attr","pattern","getOrCompute","RegExp","INPUT_MODES","numeric","decimal","SEGMENTED","NUMERIC_DIGITS","kept","search","Input","_input","controls","_type","slots","template","withOverlay","autocomplete","strip","keep","re","match","unsigned","digits","startsWith","signed","numericFilter","filterOf","configure","reportChanges","before","after","start","selectionStart","caret","setSelectionRange","committed","typed","uppercase","uppercased","toUpperCase","trimmed","normalized","replaceAll","n","isNaN","placeholder","blankAsNull","LocalDate","content","m","parsed","Date","getTime","date","locale","year","month","day","Instant","isoToLocal","hour","minute","second","hour12","iso","pad","padStart","getFullYear","getMonth","getDate","getHours","getMinutes","getSeconds","getMilliseconds","localToIso","local","toISOString","InputLocalDate","min","fromIsoOrOffset","step","formatLocalDate","getTimezoneOffset","exec","sign","offset","r","setHours","setDate","originalDay","setMonth","setFullYear","InputLocalTime","fromNowOrOffset","resolved","setMinutes","snapped","stepSeconds","seconds","floor","hh","mm","InputInstant","InputFile","list","files","dt","DataTransfer","file","items","accept","dropzone","warnings","group","warning","itemstemplate","Fragments","isBlank","Templates","fromFragment","idx","children","indexOf","f","click","dataTransfer","kind","getAsFile","update","ensureAcceptable","ensureFileSizes","ensureTotalSize","ensureFilesCount","renderTo","appendTo","WARNING_TIMEOUT","acceptable","toLowerCase","some","token","endsWith","unacceptable","types","maxFiles","count","maxFileSize","oversized","size","bytes","maxTotalSize","names","totalsize","useItemList","itemList","useDropzone","open","reflowWired","clamp","low","high","place","popover","anchored","invoker","stretch","box","viewport","documentElement","vw","clientWidth","vh","clientHeight","style","removeProperty","computed","getComputedStyle","gap","parseFloat","marginTop","marginRight","marginBottom","marginLeft","right","bottom","margin","cap","maxWidth","minWidth","width","left","height","below","top","note","isNote","placement","wide","here","setProperty","clientLeft","clientTop","reportCallout","reflow","isConnected","schedule","Anchors","invoke","expanded","handPlace","localName","togglePopover","anchor","anchorName","positionAnchor","newState","CSS","supports","visibility","queueMicrotask","showOncePlaced","property","unplace","show","flip","showPopover","Element","above","placeShown","byKeys","byLabel","needle","RemoteLoader","prefetch","inFlight","configs","ensureFetched","exact","claim","revisionedData","finally","storageKey","fetchJson","PartialRemoteLoader","param","InMemoryLoader","SelectLoader","metadata","revisionFrom","responseMapperFrom","configured","_registry","evaluator","evaluateExpression","row","Dropdown","menu","empty","optionstemplate","shows","default","li","change","hide","highlight","activated","scrollIntoView","block","behavior","matchMedia","acceptSelection","entry","index","picked","findIndex","hidePopover","shown","moveOrShow","candidate","walk","jump","first","edge","firstElementChild","lastElementChild","page","next","offsetHeight","trunc","Select","str","builtFrom","src","ddmenu","warnedComma","assignments","editing","dload","abortdload","buildLoader","listbox","wireChrome","wireChips","wireInput","wireSelection","elsewhere","close","removeKeyAt","badge","removeBadge","chipKeydown","code","selectionEnd","badges","select","relatedTarget","contains","comboboxKeydown","clear","coerceKey","changed","withLoader","reload","followAttributes","reconfigure","attributes","notify","arrowKeydown","display","altKey","query","cleared","selection","syncBadges","NaN","RadioGroup","fieldset","firstRadio","booleanType","radioEls","inputsAndLabels","fromChildNodes","radios","escape","Checkbox","container","isSwitch","SortButton","order","sorter","orders","nextOrder","th","Pagination","prevIcon","nextIcon","reloadIcon","total","toCurrent","toTotal","maxRender","pageCount","hasPrev","hasNext","prev","enabled","curr","rendered","pages","_","activeElement","back","TableSchemaParser","nodeOrFragment","schema","Nodes","queryChildren","headersTr","rowsTr","getAttributeNames","columns","queryChildrenAll","column","maybeTitleTag","titleNode","createTextNode","wrappedTitleNode","fulSorter","td","headersTemplate","inHeaders","inRows","withFragment","rowsTemplate","InMemoryTableLoader","pageRequest","sortRequest","filterRequest","rows","sorted","begin","end","l","RemoteTableLoader","filters","fromEntries","TableLoader","Table","searchIcon","emptyIcon","body","loading","noAutoload","emptyAuthors","emptyTemplate","feedback","paginator","sorters","latestRequest","loadRequested","loads","pageSize","table","thead","maybeForm","loadPage","s","lastPage","childElementCount","pageResponse","ceil","failure","resetWithFilter","wireMenuKeys","typedAt","item","ctrlKey","metaKey","wanted","repeated","every","character","found","ChoiceButton","narrow","vocabulary","narrowed","choice","glyphs","labelFor","interactive","onPick","allowed","claimed","wired","fill","sync","preferring","fixed","mark","word","glyph","glyphSpan","wordSpan","GLYPHS","EQ","NEQ","LT","GT","LTE","GTE","BETWEEN","CONTAINS","STARTS_WITH","ENDS_WITH","COMPARE_OPERATORS","TEXT_OPERATORS","SENSITIVITIES","SENSITIVITY_GLYPHS","IGNORE_CASE","CASE_SENSITIVE","operatorLabel","op","sensitivityLabel","sensitivity","booleanValueLabel","labelTextOf","fixChoice","singular","plural","fallback","known","asCriterion","operator","operands","CompareFilter","_operator","_container","_value1","_value2","_vocabulary","_syncBetween","operators","_showDefaultOperator","_defaultOperator","_showOperator","_serialize","_deserialize","_declaredOperators","_tuple","_applyTuple","criterion","_choices","c","InstantFilter","LocalDateFilter","NumberFilter","TextFilter","_sensitivityButton","_sensitivity","_declaredSensitivities","sensitivities","tuple","BOOLEAN_VALUES","BOOLEAN_VALUE_GLYPHS","true","false","BooleanFilter","_value","valueButton","OPERATORS","DEFAULT_OPERATOR","InFilter","chosen","flat","Tooltip","icon","trigger","tooltip","tabIndex","SectionRequests","entered","WeakSet","WeakMap","host","section","owned","cause","paintError","prepend","DialogSections","dialog","requests","updates","confirming","dismiss","asked","confirm","drop","onBackdrop","pressedOutside","onSubmitted","answer","restChrome","cb","delivered","targetsWired","wireTargets","getElementById","Dialog","sections","resolvers","requiresAnswer","closeOnSubmit","header","heading","outcome","settle","dismissed","returnValue","ask","discardEdits","showModal","buttons","choices","Node","buttonClass","waitFor","labels","cancel","l10n","Drawer","title","closing","slideOutEnded","closeNow","stopSlidingOut","getAnimations","Menu","pressed","wireShared","showFor","marginBlockStart","moving","SEVERITIES","REGIONS","listenerWired","Toasts","timeout","region","message","severity","classList","startedAt","timer","retire","action","onClick","holds","release","raise","Tabs","tablist","scrollStart","scrollEnd","tabs","panels","active","chrome","panel","tab","replaceWith","scrollByOneTab","showScrollButtons","passive","resizes","ResizeObserver","bringIntoView","observe","overflow","scrollWidth","scrollLeft","blockSize","visibleRange","view","offsetWidth","direction","findLast","delta","scrollBy","Accordion","exclusive","details","Wizard","steps","progress","apply","enter","move","clamped","BUILTIN","en","one","other","it","fr","Plugin","language","translations","httpClient","navigator","registry","HttpClient","builder","withCsrfToken","withRedirectOnUnauthorized","build","defineModule","defineComponent","defineElement","defineOverlay"],"mappings":"oNA+BA,MAAMA,EAAWC,IACb,MAAMC,EAAUC,IACZ,IACIF,IAAUG,WAAWD,EACzB,CAAE,MAAO,GAEPE,EAAQF,IACV,IAAIG,EACJ,IACIA,EAAML,IAAUM,QAAQJ,EAC5B,CAAE,MACE,MACJ,CACA,GAAY,OAARG,EAGJ,IACI,OAAOE,KAAKC,MAAMH,EACtB,CAAE,MAEE,YADAJ,EAAOC,EAEX,GAUJ,MAAO,CAAEO,KARI,CAACP,EAAGQ,KACbV,IAAUW,QAAQT,EAAGK,KAAKK,UAAUF,KAOzBN,OAAMH,SAAQY,IALhBX,IACT,MAAMY,EAAUV,EAAKF,GAErB,OADAD,EAAOC,GACAY,KASTC,EAAaC,IAAK,CACpB,IAAAP,CAAKQ,EAAKC,EAAUC,GAChBH,EAAMP,KAAKQ,EAAK,CAAEC,WAAUC,QAChC,EACA,IAAAf,CAAKa,EAAKC,GACN,MAAME,EAASJ,EAAMZ,KAAKa,GAC1B,GAAc,MAAVG,GAAoC,iBAAXA,GAAuBA,EAAOF,WAAaA,EAIxE,OAAOE,EAAOD,KAHVH,EAAMf,OAAOgB,EAIrB,IAIEI,EAAetB,EAAQ,IAAMuB,cAE7BC,EAAiBxB,EAAQ,IAAMyB,gBAE/BC,EAAwBV,EAAUM,GAElCK,EAA0BX,EAAUQ,GC9E1C,MAAMI,EAoBF,sBAAaC,CAAUC,EAAIC,EAAKC,GAC5BF,EAAG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