stimeo-ui 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -0
- package/dist/controllers/alert_dialog_controller.js +32 -5
- package/dist/controllers/alert_dialog_controller.js.map +1 -1
- package/dist/controllers/announcer_controller.d.ts +32 -6
- package/dist/controllers/announcer_controller.js +255 -20
- package/dist/controllers/announcer_controller.js.map +1 -1
- package/dist/controllers/color_picker_controller.d.ts +2 -1
- package/dist/controllers/color_picker_controller.js +46 -0
- package/dist/controllers/color_picker_controller.js.map +1 -1
- package/dist/controllers/command_palette_controller.js +32 -5
- package/dist/controllers/command_palette_controller.js.map +1 -1
- package/dist/controllers/confirm_controller.js +32 -5
- package/dist/controllers/confirm_controller.js.map +1 -1
- package/dist/controllers/countdown_controller.d.ts +19 -5
- package/dist/controllers/countdown_controller.js +112 -12
- package/dist/controllers/countdown_controller.js.map +1 -1
- package/dist/controllers/date_range_picker_controller.d.ts +4 -1
- package/dist/controllers/date_range_picker_controller.js +50 -0
- package/dist/controllers/date_range_picker_controller.js.map +1 -1
- package/dist/controllers/dialog_controller.js +32 -5
- package/dist/controllers/dialog_controller.js.map +1 -1
- package/dist/controllers/dismissible_controller.js.map +1 -1
- package/dist/controllers/drawer_controller.js +32 -5
- package/dist/controllers/drawer_controller.js.map +1 -1
- package/dist/controllers/empty_state_controller.d.ts +9 -4
- package/dist/controllers/empty_state_controller.js +24 -10
- package/dist/controllers/empty_state_controller.js.map +1 -1
- package/dist/controllers/focus_controller.js +32 -5
- package/dist/controllers/focus_controller.js.map +1 -1
- package/dist/controllers/form_validation_controller.js.map +1 -1
- package/dist/controllers/frame_loading_controller.d.ts +14 -3
- package/dist/controllers/frame_loading_controller.js +177 -15
- package/dist/controllers/frame_loading_controller.js.map +1 -1
- package/dist/controllers/local_time_controller.d.ts +19 -3
- package/dist/controllers/local_time_controller.js +100 -6
- package/dist/controllers/local_time_controller.js.map +1 -1
- package/dist/controllers/meter_controller.d.ts +22 -2
- package/dist/controllers/meter_controller.js +145 -26
- package/dist/controllers/meter_controller.js.map +1 -1
- package/dist/controllers/network_status_controller.d.ts +13 -1
- package/dist/controllers/network_status_controller.js +28 -8
- package/dist/controllers/network_status_controller.js.map +1 -1
- package/dist/controllers/overflow_menu_controller.js +33 -6
- package/dist/controllers/overflow_menu_controller.js.map +1 -1
- package/dist/controllers/progress_controller.d.ts +16 -1
- package/dist/controllers/progress_controller.js +116 -9
- package/dist/controllers/progress_controller.js.map +1 -1
- package/dist/controllers/range_slider_controller.d.ts +4 -1
- package/dist/controllers/range_slider_controller.js +68 -3
- package/dist/controllers/range_slider_controller.js.map +1 -1
- package/dist/controllers/rating_controller.d.ts +4 -1
- package/dist/controllers/rating_controller.js +53 -0
- package/dist/controllers/rating_controller.js.map +1 -1
- package/dist/controllers/relative_time_controller.d.ts +13 -0
- package/dist/controllers/relative_time_controller.js +133 -12
- package/dist/controllers/relative_time_controller.js.map +1 -1
- package/dist/controllers/sidebar_controller.d.ts +1 -11
- package/dist/controllers/sidebar_controller.js +37 -8
- package/dist/controllers/sidebar_controller.js.map +1 -1
- package/dist/controllers/skeleton_controller.d.ts +7 -2
- package/dist/controllers/skeleton_controller.js +73 -20
- package/dist/controllers/skeleton_controller.js.map +1 -1
- package/dist/controllers/slider_controller.js +17 -2
- package/dist/controllers/slider_controller.js.map +1 -1
- package/dist/controllers/spinner_controller.d.ts +37 -4
- package/dist/controllers/spinner_controller.js +228 -27
- package/dist/controllers/spinner_controller.js.map +1 -1
- package/dist/controllers/step_indicator_controller.d.ts +12 -1
- package/dist/controllers/step_indicator_controller.js +82 -5
- package/dist/controllers/step_indicator_controller.js.map +1 -1
- package/dist/controllers/stick_to_bottom_controller.d.ts +26 -2
- package/dist/controllers/stick_to_bottom_controller.js +60 -10
- package/dist/controllers/stick_to_bottom_controller.js.map +1 -1
- package/dist/index.js +1056 -281
- package/dist/index.js.map +1 -1
- package/dist/inspector/cli.js +785 -76
- package/dist/inspector/cli.js.map +1 -1
- package/dist/inspector/cli_bin.js +785 -76
- package/dist/inspector/cli_bin.js.map +1 -1
- package/dist/inspector/examples.json +5 -5
- package/dist/inspector/manifest.json +21 -8
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/coerce.ts","../../src/controllers/progress_controller.ts"],"names":[],"mappings":";;;;;AAeO,SAAS,eAAe,GAAA,EAAwD;AACrF,EAAA,IAAI,QAAQ,IAAA,IAAQ,GAAA,KAAQ,MAAA,IAAa,GAAA,KAAQ,IAAI,OAAO,IAAA;AAC5D,EAAA,MAAM,QAAQ,OAAO,GAAA,KAAQ,QAAA,GAAW,GAAA,GAAM,OAAO,GAAG,CAAA;AACxD,EAAA,OAAO,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA,GAAI,KAAA,GAAQ,IAAA;AAC1C;;;ACkBO,IAAM,kBAAA,GAAN,cAAiC,UAAA,CAAwB;AAAA,EAC9D,OAAgB,OAAA,GAAU,CAAC,KAAK,CAAA;AAAA,EAChC,OAAgB,MAAA,GAAS;AAAA,IACvB,KAAA,EAAO,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,CAAA,EAAE;AAAA,IAClC,GAAA,EAAK,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,CAAA,EAAE;AAAA,IAChC,GAAA,EAAK,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,GAAA,EAAI;AAAA,IAClC,aAAA,EAAe,EAAE,IAAA,EAAM,OAAA,EAAS,SAAS,KAAA,EAAM;AAAA,IAC/C,SAAA,EAAW,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,EAAA;AAAG,GACzC;AAAA,EACA,OAAO,OAAA,GAAU,CAAC,UAAU,CAAA;AAAA,EAC5B,OAAO,MAAA,GAAS,CAAC,QAAA,EAAU,UAAU,CAAA;AAAA,EAW5B,OAAA,GAAgB;AACvB,IAAA,IAAA,CAAK,OAAA,EA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AS,GAAG,CAAA;AAC5C,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,cAAA,CACf,UAAA,CAAW,SAAA,EAAW,MAAA,CAAO,KAAK,CAAC,CAAA,CACnC,UAAA,CAAW,WAAA,EAAa,MAAA,CAAO,OAAO,CAAC,CAAA;AAC1C,IAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,gBAAA,EAAkB,IAAI,CAAA;AAAA,EAClD;AACF","file":"progress_controller.js","sourcesContent":["/**\n * Numeric coercion shared by the value-bearing controllers (progress, meter,\n * color-picker).\n *\n * Stimulus already coerces numeric action params to numbers, but a value can also\n * arrive as a string — via a `*:set` CustomEvent `detail`, or an action param\n * whose attribute does not look numeric. Centralizing the parse keeps `setValue`\n * tolerant of either form while rejecting anything that is not a finite number.\n */\n\n/**\n * Coerces `raw` to a finite number, or returns `null` when it is absent, empty,\n * or not parseable. Empty strings are treated as \"no value\" rather than `0`, so a\n * stray blank param cannot silently reset the value.\n */\nexport function toFiniteNumber(raw: number | string | null | undefined): number | null {\n if (raw === null || raw === undefined || raw === \"\") return null;\n const value = typeof raw === \"number\" ? raw : Number(raw);\n return Number.isFinite(value) ? value : null;\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { toFiniteNumber } from \"../utils/coerce\";\n\n/**\n * Event shape `setValue` accepts: an action param `amount` or a `detail.value`.\n * Both are typed `number | string` because, while Stimulus coerces numeric action\n * params to numbers, a `progress:set` CustomEvent (or a non-numeric-looking param)\n * may carry a string; {@link ProgressController.setValue} normalizes either form.\n */\ntype SetValueEvent = Event & {\n params?: { amount?: number | string };\n detail?: { value?: number | string };\n};\n\n/**\n * Headless progress-bar behavior backed by the WAI-ARIA `progressbar` role.\n *\n * Markup contract (identifier: `stimeo--progress`):\n * <div data-controller=\"stimeo--progress\" role=\"progressbar\"\n * aria-label=\"Upload\" aria-valuemin=\"0\" aria-valuemax=\"100\" aria-valuenow=\"0\"\n * data-stimeo--progress-value-value=\"0\"\n * data-action=\"progress:set->stimeo--progress#setValue\">\n * <div data-stimeo--progress-target=\"bar\"></div>\n * </div>\n *\n * This is the *progress over time* role (a task advancing toward completion),\n * deliberately distinct from {@link MeterController}'s point-in-time `meter`. The\n * controller owns value normalization and ARIA value-attribute synchronization;\n * the bar's width/animation is the consumer's, driven off the\n * `--stimeo-progress-ratio` (0–1) custom property and `data-state`.\n *\n * @remarks\n * Behavior only — no styling is emitted. An indeterminate bar drops\n * `aria-valuenow` (per ARIA) so assistive tech announces \"busy\" rather than a\n * stale value; the consumer animates the indeterminate look off\n * `data-state=\"indeterminate\"`.\n */\nexport class ProgressController extends Controller<HTMLElement> {\n static override targets = [\"bar\"];\n static override values = {\n value: { type: Number, default: 0 },\n min: { type: Number, default: 0 },\n max: { type: Number, default: 100 },\n indeterminate: { type: Boolean, default: false },\n valueText: { type: String, default: \"\" },\n };\n static actions = [\"setValue\"] as const;\n static events = [\"change\", \"complete\"] as const;\n\n declare readonly barTarget: HTMLElement;\n declare readonly hasBarTarget: boolean;\n\n declare valueValue: number;\n declare minValue: number;\n declare maxValue: number;\n declare indeterminateValue: boolean;\n declare valueTextValue: string;\n\n override connect(): void {\n this.#render();\n }\n\n /**\n * Updates the progress value from an action param (`amount`) or a\n * `detail.value` CustomEvent, normalizes it into range, syncs ARIA, and\n * dispatches `change` (always) plus `complete` when `max` is reached.\n */\n setValue(event: SetValueEvent): void {\n const next = toFiniteNumber(event.params?.amount ?? event.detail?.value);\n if (next === null) return;\n const value = this.#clamp(next);\n this.valueValue = value;\n this.indeterminateValue = false;\n this.#render();\n this.dispatch(\"change\", { detail: { value, ratio: this.#ratio } });\n if (value >= this.maxValue) {\n this.dispatch(\"complete\", { detail: { value } });\n }\n }\n\n /** Re-render when the indeterminate flag is toggled via its data attribute. */\n indeterminateValueChanged(): void {\n // Stimulus fires this once during initialization (before `connect`), where\n // touching the DOM is still safe; guard nothing.\n this.#render();\n }\n\n /** Clamps `raw` into the configured `[min, max]` range. */\n #clamp(raw: number): number {\n return Math.min(this.maxValue, Math.max(this.minValue, raw));\n }\n\n /** Current fraction of the range in `[0, 1]`; `0` when the range is empty. */\n get #ratio(): number {\n const span = this.maxValue - this.minValue;\n if (span <= 0) return 0;\n // Clamp first so an out-of-range value (e.g. an initial value past `max`)\n // can never push the ratio — and thus the bar width / percent — outside 0–1.\n return (this.#clamp(this.valueValue) - this.minValue) / span;\n }\n\n /** Reflects value/range/indeterminate onto ARIA, `data-state`, and the ratio. */\n #render(): void {\n this.element.setAttribute(\"aria-valuemin\", String(this.minValue));\n this.element.setAttribute(\"aria-valuemax\", String(this.maxValue));\n\n if (this.indeterminateValue) {\n this.element.removeAttribute(\"aria-valuenow\");\n this.element.removeAttribute(\"aria-valuetext\");\n this.element.style.removeProperty(\"--stimeo-progress-ratio\");\n this.element.setAttribute(\"data-state\", \"indeterminate\");\n return;\n }\n\n const value = this.#clamp(this.valueValue);\n this.element.setAttribute(\"aria-valuenow\", String(value));\n this.element.style.setProperty(\"--stimeo-progress-ratio\", String(this.#ratio));\n this.element.setAttribute(\"data-state\", \"determinate\");\n this.#applyValueText(value);\n }\n\n /**\n * Sets `aria-valuetext` from the consumer-provided template, substituting\n * `{value}` and `{percent}`. Left to the consumer so the human-readable text\n * stays i18n-neutral in the library; cleared when no template is given.\n */\n #applyValueText(value: number): void {\n if (this.valueTextValue.length === 0) {\n this.element.removeAttribute(\"aria-valuetext\");\n return;\n }\n const percent = Math.round(this.#ratio * 100);\n const text = this.valueTextValue\n .replaceAll(\"{value}\", String(value))\n .replaceAll(\"{percent}\", String(percent));\n this.element.setAttribute(\"aria-valuetext\", text);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/announce.ts","../../src/utils/coerce.ts","../../src/utils/microtask_coalescer.ts","../../src/utils/range.ts","../../src/controllers/progress_controller.ts"],"names":[],"mappings":";;;;;AAoBO,SAAS,QAAA,CAAS,OAAA,EAAiB,OAAA,GAAmC,EAAC,EAAS;AACrF,EAAA,MAAM,IAAA,GAAO,QAA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A,CAAa,YAAA,EAAc,aAAa,CAAA;AACrD,IAAA,IAAA,CAAK,gBAAgB,KAAK,CAAA;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,gBAAgB,KAAA,EAAqB;AACnC,IAAA,IAAI,IAAA,CAAK,cAAA,CAAe,MAAA,KAAW,CAAA,EAAG;AACpC,MAAA,IAAA,CAAK,kBAAA,EAAmB;AACxB,MAAA;AAAA,IACF;AACA,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,SAAS,GAAG,CAAA;AAC5C,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,cAAA,CACf,UAAA,CAAW,SAAA,EAAW,MAAA,CAAO,KAAK,CAAC,CAAA,CACnC,UAAA,CAAW,WAAA,EAAa,MAAA,CAAO,OAAO,CAAC,CAAA;AAC1C,IAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,gBAAA,EAAkB,IAAI,CAAA;AAChD,IAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,gBAAA,EAAkB,EAAE,CAAA;AAAA,EAChD;AAAA;AAAA,EAGA,kBAAA,GAA2B;AACzB,IAAA,IAAI,CAAC,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,gBAAgB,CAAA,EAAG;AAClD,IAAA,IAAA,CAAK,OAAA,CAAQ,gBAAgB,gBAAgB,CAAA;AAC7C,IAAA,IAAA,CAAK,OAAA,CAAQ,gBAAgB,gBAAgB,CAAA;AAAA,EAC/C;AACF","file":"progress_controller.js","sourcesContent":["/**\n * Sends one message to the page's shared `stimeo--announcer`.\n *\n * A component that has to reach assistive tech does not carry a live region of its\n * own: a region only announces what changes *after* assistive tech already knows\n * about it, which a region that appears (or is un-hidden) with its message cannot\n * satisfy. The one region that can is the announcer sitting in the page from the\n * start, so state changes are handed to it as an event and it does the reading.\n *\n * The event goes to `window` because the announcer is usually a sibling high in the\n * document rather than an ancestor of the component dispatching it.\n *\n * Wording comes from the consumer — the library ships no English strings — so an\n * empty message is silently dropped and nothing is announced.\n *\n * @example\n * ```ts\n * announce(this.announceTextValue, { assertive: false });\n * ```\n */\nexport function announce(message: string, options: { assertive?: boolean } = {}): void {\n const text = message.trim();\n if (text.length === 0) return;\n window.dispatchEvent(\n new CustomEvent(\"stimeo--announcer:announce\", {\n detail: { message: text, assertive: options.assertive === true },\n }),\n );\n}\n\n/**\n * Fills `{name}` placeholders in an announcement template from `values`.\n *\n * The same substitution the value-text templates use, so a consumer writes\n * `\"{percent}% complete\"` in one attribute and gets the same rules everywhere. A\n * placeholder with no matching entry is left as authored rather than blanked, which\n * keeps a typo visible instead of silently swallowing the word.\n */\nexport function fillTemplate(template: string, values: Record<string, string | number>): string {\n return template.replace(/\\{([a-zA-Z][a-zA-Z0-9]*)\\}/g, (match, name: string) => {\n const replacement = values[name];\n return replacement === undefined ? match : String(replacement);\n });\n}\n","/**\n * Numeric coercion shared by the value-bearing controllers (progress, meter,\n * color-picker).\n *\n * Stimulus already coerces numeric action params to numbers, but a value can also\n * arrive as a string — via a `*:set` CustomEvent `detail`, or an action param\n * whose attribute does not look numeric. Centralizing the parse keeps `setValue`\n * tolerant of either form while rejecting anything that is not a finite number.\n */\n\n/**\n * Coerces `raw` to a finite number, or returns `null` when it is absent, empty,\n * or not parseable. Empty strings are treated as \"no value\" rather than `0`, so a\n * stray blank param cannot silently reset the value.\n */\nexport function toFiniteNumber(raw: number | string | null | undefined): number | null {\n if (raw === null || raw === undefined || raw === \"\") return null;\n const value = typeof raw === \"number\" ? raw : Number(raw);\n return Number.isFinite(value) ? value : null;\n}\n","/**\n * Collapses many target callbacks from one DOM mutation into a single pass.\n *\n * Stimulus fires `<name>TargetConnected` / `Disconnected` once per element, so\n * replacing a list of N options delivers N callbacks — but the useful unit of\n * work is \"reconcile against the DOM that resulted\", once, after the batch has\n * settled. Every controller that owns a reconcilable target set needs the same\n * shape: a `queued` flag plus `queueMicrotask`.\n *\n * **A microtask is the right horizon, and the reason is specific.** Stimulus\n * drives these callbacks from a `MutationObserver`, whose own callback already\n * runs as a microtask with the whole batch in hand; scheduling one more lands\n * after the last sibling callback of that batch and still before paint or any\n * event handler. A timer would be later than it needs to be, and reconciling\n * synchronously would run once per element against a half-applied DOM.\n *\n * **The two guards are not the same guard.** Scheduling is refused before the\n * controller connects, and running is refused after it disconnects:\n *\n * - **Before `connect()`** — Stimulus delivers the *initial* target callbacks\n * ahead of `connect()`. Reconciling there would compute a fallback against a\n * controller whose own state has not been initialised, and `connect()` is\n * about to do a full pass anyway.\n * - **After `disconnect()`** — Stimulus fires a callback for **every** target\n * during teardown, and a microtask queued just before it would otherwise run\n * against a detached tree. {@link MicrotaskCoalescer.cancel} exists for the\n * teardown path to drop the pending pass outright.\n *\n * Both guards are part of one contract here rather than something each consumer\n * has to remember separately.\n *\n * Scope is the scheduling only. *What* to reconcile — keep the surviving active\n * option, fall back to the next / previous / first visible one, rebuild derived\n * chips or hidden fields — stays in the controller, because no two consumers\n * answer it the same way.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileOptions());\n *\n * connect() { this.#reconcile.activate(); }\n * disconnect() { this.#reconcile.cancel(); }\n *\n * optionTargetConnected() { this.#reconcile.schedule(); }\n * optionTargetDisconnected() { this.#reconcile.schedule(); }\n * ```\n */\nexport class MicrotaskCoalescer {\n readonly #run: () => void;\n #queued = false;\n #active = false;\n #generation = 0;\n\n /** @param run - the single reconciliation pass, invoked at most once per batch. */\n constructor(run: () => void) {\n this.#run = run;\n }\n\n /** Opens the window in which {@link schedule} is honoured; call from `connect()`. */\n activate(): void {\n this.#active = true;\n }\n\n /** Closes the window and drops any pending pass; call from `disconnect()`. */\n cancel(): void {\n this.#active = false;\n this.#queued = false;\n this.#generation += 1;\n }\n\n /** Requests one pass after the batch settles. Idempotent; inert outside the window. */\n schedule(): void {\n if (!this.#active || this.#queued) return;\n this.#queued = true;\n const generation = this.#generation;\n queueMicrotask(() => {\n // A cancelled callback must not consume a pass queued after reconnect.\n if (generation !== this.#generation || !this.#queued || !this.#active) return;\n this.#queued = false;\n this.#run();\n });\n }\n}\n","/**\n * Range normalization shared by the value-bearing controllers (progress, meter,\n * slider, range-slider).\n *\n * Each of them publishes \"where the value sits inside `[min, max]`\" as a CSS\n * custom property the consumer multiplies a track by, and each has to answer the\n * same degenerate cases: empty and inverted ranges cannot express progress, and\n * malformed Number Values can produce `NaN`. Keeping the rule in one place is\n * what makes those answers identical across the four.\n */\n\n/**\n * Fraction of `[min, max]` that `value` occupies, always within `[0, 1]`.\n *\n * `value` is clamped into the range first, so a value outside it reports a full\n * or empty track rather than pushing the fraction past the ends.\n *\n * An empty, inverted, or non-numeric range yields `0`. That is a deliberate\n * floor rather than a computed result: `min === max` would produce `NaN`, and\n * `min > max` would report a full track for a value that is really out of range.\n * Non-finite results are floored for the same reason. These results reach\n * assistive tech, because the same fraction drives the percentage substituted\n * into `aria-valuetext`.\n */\nexport function rangeFraction(value: number, min: number, max: number): number {\n const span = max - min;\n if (!(span > 0)) return 0;\n\n const clamped = Math.min(max, Math.max(min, value));\n let fraction: number;\n if (Number.isFinite(span)) {\n fraction = (clamped - min) / span;\n } else {\n // Scaling preserves the ratio when two finite endpoints straddle zero so\n // widely that their subtraction overflows to Infinity.\n const scale = Math.max(Math.abs(min), Math.abs(max));\n fraction = (clamped / scale - min / scale) / (max / scale - min / scale);\n }\n\n if (!Number.isFinite(fraction)) return 0;\n return Math.min(1, Math.max(0, fraction));\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { announce, fillTemplate } from \"../utils/announce\";\nimport { toFiniteNumber } from \"../utils/coerce\";\nimport { MicrotaskCoalescer } from \"../utils/microtask_coalescer\";\nimport { rangeFraction } from \"../utils/range\";\n\n/**\n * Event shape `setValue` accepts: an action param `amount` or a `detail.value`.\n * Both are typed `number | string` because, while Stimulus coerces numeric action\n * params to numbers, a `progress:set` CustomEvent (or a non-numeric-looking param)\n * may carry a string; {@link ProgressController.setValue} normalizes either form.\n */\ntype SetValueEvent = Event & {\n params?: { amount?: number | string };\n detail?: { value?: number | string };\n};\n\n/**\n * Marks an `aria-valuetext` this controller wrote, so a render takes back only\n * its own text. `aria-valuetext` is shared: a consumer may author it instead of\n * supplying a template, and that text is theirs to keep across renders.\n */\nconst OWNED_VALUE_TEXT = \"data-stimeo--progress-owns-valuetext\";\n\n/**\n * Headless progress-bar behavior backed by the WAI-ARIA `progressbar` role.\n *\n * Markup contract (identifier: `stimeo--progress`):\n * <div data-controller=\"stimeo--progress\" role=\"progressbar\"\n * aria-label=\"Upload\" aria-valuemin=\"0\" aria-valuemax=\"100\" aria-valuenow=\"0\"\n * data-stimeo--progress-value-value=\"0\"\n * data-action=\"progress:set->stimeo--progress#setValue\">\n * <div data-stimeo--progress-target=\"bar\"></div>\n * </div>\n *\n * This is the *progress over time* role (a task advancing toward completion),\n * deliberately distinct from {@link MeterController}'s point-in-time `meter`. The\n * controller owns value normalization and ARIA value-attribute synchronization;\n * the bar's width/animation is the consumer's, driven off the\n * `--stimeo-progress-ratio` (0–1) custom property and `data-state`.\n *\n * @remarks\n * Behavior only — no styling is emitted. An indeterminate bar drops\n * `aria-valuenow` (per ARIA) so assistive tech announces \"busy\" rather than a\n * stale value; the consumer animates the indeterminate look off\n * `data-state=\"indeterminate\"`.\n */\nexport class ProgressController extends Controller<HTMLElement> {\n static override targets = [\"bar\"];\n static override values = {\n value: { type: Number, default: 0 },\n min: { type: Number, default: 0 },\n max: { type: Number, default: 100 },\n indeterminate: { type: Boolean, default: false },\n valueText: { type: String, default: \"\" },\n announceText: { type: String, default: \"\" },\n };\n static actions = [\"setValue\"] as const;\n static events = [\"change\", \"complete\"] as const;\n\n declare readonly barTarget: HTMLElement;\n declare readonly hasBarTarget: boolean;\n\n declare valueValue: number;\n declare minValue: number;\n declare maxValue: number;\n declare indeterminateValue: boolean;\n declare valueTextValue: string;\n declare announceTextValue: string;\n\n /**\n * Collapses a morph that swaps several render inputs at once into one repaint.\n * A single update usually rewrites the whole set, and each Value would otherwise\n * repaint on its own.\n */\n readonly #repaint = new MicrotaskCoalescer(() => {\n this.#render();\n });\n\n override connect(): void {\n this.#repaint.activate();\n this.#render();\n }\n\n /** Closes the window in which a queued repaint may still run. */\n override disconnect(): void {\n this.#repaint.cancel();\n }\n\n /**\n * Updates the progress value from an action param (`amount`) or a\n * `detail.value` CustomEvent, normalizes it into range, syncs ARIA, and\n * dispatches `change` (always) plus `complete` when `max` is reached.\n */\n setValue(event: SetValueEvent): void {\n const next = toFiniteNumber(event.params?.amount ?? event.detail?.value);\n if (next === null) return;\n const value = this.#clamp(next);\n this.valueValue = value;\n this.indeterminateValue = false;\n this.#render();\n this.dispatch(\"change\", { detail: { value, ratio: this.#ratio } });\n if (value >= this.maxValue) {\n this.dispatch(\"complete\", { detail: { value } });\n // Reaching the end is the transition worth reading out; the running numbers in\n // between are state the consumer can see, not news.\n announce(\n fillTemplate(this.announceTextValue, { value, percent: Math.round(this.#ratio * 100) }),\n );\n }\n }\n\n /** Repaints when application code (or a Turbo morph) changes `indeterminate` at runtime. */\n indeterminateValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /** Repaints when application code (or a Turbo morph) changes `value` at runtime. */\n valueValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /** Repaints when application code (or a Turbo morph) changes `min` at runtime. */\n minValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /** Repaints when application code (or a Turbo morph) changes `max` at runtime. */\n maxValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /** Repaints when application code (or a Turbo morph) changes `valueText` at runtime. */\n valueTextValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /** Clamps `raw` into the configured `[min, max]` range. */\n #clamp(raw: number): number {\n return Math.min(this.maxValue, Math.max(this.minValue, raw));\n }\n\n /** Current fraction of the range in `[0, 1]`; `0` when the range is empty. */\n get #ratio(): number {\n return rangeFraction(this.valueValue, this.minValue, this.maxValue);\n }\n\n /** Reflects value/range/indeterminate onto ARIA, `data-state`, and the ratio. */\n #render(): void {\n this.element.setAttribute(\"aria-valuemin\", String(this.minValue));\n this.element.setAttribute(\"aria-valuemax\", String(this.maxValue));\n\n if (this.indeterminateValue) {\n this.element.removeAttribute(\"aria-valuenow\");\n // `aria-valuetext` outranks `aria-valuenow` for assistive tech, so a text\n // this controller derived from a value would announce the very number the\n // indeterminate state drops.\n this.#clearOwnValueText();\n this.element.style.removeProperty(\"--stimeo-progress-ratio\");\n this.element.setAttribute(\"data-state\", \"indeterminate\");\n return;\n }\n\n const value = this.#clamp(this.valueValue);\n this.element.setAttribute(\"aria-valuenow\", String(value));\n this.element.style.setProperty(\"--stimeo-progress-ratio\", String(this.#ratio));\n this.element.setAttribute(\"data-state\", \"determinate\");\n this.#applyValueText(value);\n }\n\n /**\n * Sets `aria-valuetext` from the consumer-provided template, substituting\n * `{value}` and `{percent}`. Left to the consumer so the human-readable text\n * stays i18n-neutral in the library. With no template the attribute belongs to\n * the consumer, so only a text this controller wrote is taken back\n * ({@link OWNED_VALUE_TEXT}).\n */\n #applyValueText(value: number): void {\n if (this.valueTextValue.length === 0) {\n this.#clearOwnValueText();\n return;\n }\n const percent = Math.round(this.#ratio * 100);\n const text = this.valueTextValue\n .replaceAll(\"{value}\", String(value))\n .replaceAll(\"{percent}\", String(percent));\n this.element.setAttribute(\"aria-valuetext\", text);\n this.element.setAttribute(OWNED_VALUE_TEXT, \"\");\n }\n\n /** Removes `aria-valuetext` only when this controller is the one that wrote it. */\n #clearOwnValueText(): void {\n if (!this.element.hasAttribute(OWNED_VALUE_TEXT)) return;\n this.element.removeAttribute(\"aria-valuetext\");\n this.element.removeAttribute(OWNED_VALUE_TEXT);\n }\n}\n"]}
|
|
@@ -84,10 +84,13 @@ declare class RangeSliderController extends Controller<HTMLElement> {
|
|
|
84
84
|
startValue: number;
|
|
85
85
|
endValue: number;
|
|
86
86
|
logicalTrackValue: boolean;
|
|
87
|
-
/** Normalizes the initial pair (clamped, snapped, ordered) and renders. */
|
|
88
87
|
connect(): void;
|
|
89
88
|
/** Cancels any active pointer drag so document listeners never leak. */
|
|
90
89
|
disconnect(): void;
|
|
90
|
+
/** Repaints when application code (or a Turbo morph) changes `min` at runtime. */
|
|
91
|
+
minValueChanged(): void;
|
|
92
|
+
/** Repaints when application code (or a Turbo morph) changes `max` at runtime. */
|
|
93
|
+
maxValueChanged(): void;
|
|
91
94
|
/** Keyboard stepping for whichever thumb is focused (the action's element). */
|
|
92
95
|
onKeydown(event: KeyboardEvent): void;
|
|
93
96
|
/** Begins a pointer drag on the track, moving the thumb nearest the press. */
|
|
@@ -18,6 +18,55 @@ function isReservedArrowChord(event, allow = []) {
|
|
|
18
18
|
return event.altKey && !allow.includes("alt") || event.ctrlKey && !allow.includes("ctrl") || event.metaKey && !allow.includes("meta") || event.shiftKey && !allow.includes("shift");
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
// src/utils/microtask_coalescer.ts
|
|
22
|
+
var MicrotaskCoalescer = class {
|
|
23
|
+
#run;
|
|
24
|
+
#queued = false;
|
|
25
|
+
#active = false;
|
|
26
|
+
#generation = 0;
|
|
27
|
+
/** @param run - the single reconciliation pass, invoked at most once per batch. */
|
|
28
|
+
constructor(run) {
|
|
29
|
+
this.#run = run;
|
|
30
|
+
}
|
|
31
|
+
/** Opens the window in which {@link schedule} is honoured; call from `connect()`. */
|
|
32
|
+
activate() {
|
|
33
|
+
this.#active = true;
|
|
34
|
+
}
|
|
35
|
+
/** Closes the window and drops any pending pass; call from `disconnect()`. */
|
|
36
|
+
cancel() {
|
|
37
|
+
this.#active = false;
|
|
38
|
+
this.#queued = false;
|
|
39
|
+
this.#generation += 1;
|
|
40
|
+
}
|
|
41
|
+
/** Requests one pass after the batch settles. Idempotent; inert outside the window. */
|
|
42
|
+
schedule() {
|
|
43
|
+
if (!this.#active || this.#queued) return;
|
|
44
|
+
this.#queued = true;
|
|
45
|
+
const generation = this.#generation;
|
|
46
|
+
queueMicrotask(() => {
|
|
47
|
+
if (generation !== this.#generation || !this.#queued || !this.#active) return;
|
|
48
|
+
this.#queued = false;
|
|
49
|
+
this.#run();
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// src/utils/range.ts
|
|
55
|
+
function rangeFraction(value, min, max) {
|
|
56
|
+
const span = max - min;
|
|
57
|
+
if (!(span > 0)) return 0;
|
|
58
|
+
const clamped = Math.min(max, Math.max(min, value));
|
|
59
|
+
let fraction;
|
|
60
|
+
if (Number.isFinite(span)) {
|
|
61
|
+
fraction = (clamped - min) / span;
|
|
62
|
+
} else {
|
|
63
|
+
const scale = Math.max(Math.abs(min), Math.abs(max));
|
|
64
|
+
fraction = (clamped / scale - min / scale) / (max / scale - min / scale);
|
|
65
|
+
}
|
|
66
|
+
if (!Number.isFinite(fraction)) return 0;
|
|
67
|
+
return Math.min(1, Math.max(0, fraction));
|
|
68
|
+
}
|
|
69
|
+
|
|
21
70
|
// src/controllers/range_slider_controller.ts
|
|
22
71
|
var START_PROPERTY = "--stimeo-range-start";
|
|
23
72
|
var END_PROPERTY = "--stimeo-range-end";
|
|
@@ -40,16 +89,33 @@ var RangeSliderController = class extends Controller {
|
|
|
40
89
|
return this.logicalTrackValue && isRtl(this.element);
|
|
41
90
|
}
|
|
42
91
|
/** Normalizes the initial pair (clamped, snapped, ordered) and renders. */
|
|
92
|
+
/**
|
|
93
|
+
* Collapses a morph that swaps render inputs into one repaint, and refuses the
|
|
94
|
+
* pass Stimulus delivers before `connect()`.
|
|
95
|
+
*/
|
|
96
|
+
#repaint = new MicrotaskCoalescer(() => {
|
|
97
|
+
this.#render(this.startValue, this.endValue);
|
|
98
|
+
});
|
|
43
99
|
connect() {
|
|
100
|
+
this.#repaint.activate();
|
|
44
101
|
const lo = Math.min(this.startValue, this.endValue);
|
|
45
102
|
const hi = Math.max(this.startValue, this.endValue);
|
|
46
103
|
this.#commit(lo, hi, false);
|
|
47
104
|
}
|
|
48
105
|
/** Cancels any active pointer drag so document listeners never leak. */
|
|
49
106
|
disconnect() {
|
|
107
|
+
this.#repaint.cancel();
|
|
50
108
|
this.#dragAbort?.abort();
|
|
51
109
|
this.#dragAbort = null;
|
|
52
110
|
}
|
|
111
|
+
/** Repaints when application code (or a Turbo morph) changes `min` at runtime. */
|
|
112
|
+
minValueChanged() {
|
|
113
|
+
this.#repaint.schedule();
|
|
114
|
+
}
|
|
115
|
+
/** Repaints when application code (or a Turbo morph) changes `max` at runtime. */
|
|
116
|
+
maxValueChanged() {
|
|
117
|
+
this.#repaint.schedule();
|
|
118
|
+
}
|
|
53
119
|
/** Keyboard stepping for whichever thumb is focused (the action's element). */
|
|
54
120
|
onKeydown(event) {
|
|
55
121
|
if (isReservedArrowChord(event)) return;
|
|
@@ -165,14 +231,13 @@ var RangeSliderController = class extends Controller {
|
|
|
165
231
|
this.endThumbTarget.setAttribute("aria-valuemax", String(this.maxValue));
|
|
166
232
|
this.endThumbTarget.setAttribute("aria-valuenow", String(end));
|
|
167
233
|
}
|
|
168
|
-
const span = this.maxValue - this.minValue;
|
|
169
234
|
this.element.style.setProperty(
|
|
170
235
|
START_PROPERTY,
|
|
171
|
-
String(
|
|
236
|
+
String(rangeFraction(start, this.minValue, this.maxValue))
|
|
172
237
|
);
|
|
173
238
|
this.element.style.setProperty(
|
|
174
239
|
END_PROPERTY,
|
|
175
|
-
String(
|
|
240
|
+
String(rangeFraction(end, this.minValue, this.maxValue))
|
|
176
241
|
);
|
|
177
242
|
}
|
|
178
243
|
/** Clamps `raw` to `[min, max]` and snaps it to the nearest step from `min`. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/logical_scroll.ts","../../src/utils/arrow_step.ts","../../src/controllers/range_slider_controller.ts"],"names":[],"mappings":";;;;;AAiBO,SAAS,MAAM,OAAA,EAA2B;AAC/C,E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A,CAAK,QAAA,GAAW,IAAA,CAAK,QAAA;AAClC,IAAA,IAAA,CAAK,QAAQ,KAAA,CAAM,WAAA;AAAA,MACjB,cAAA;AAAA,MACA,OAAO,IAAA,GAAO,CAAA,GAAA,CAAK,QAAQ,IAAA,CAAK,QAAA,IAAY,OAAO,CAAC;AAAA,KACtD;AACA,IAAA,IAAA,CAAK,QAAQ,KAAA,CAAM,WAAA;AAAA,MACjB,YAAA;AAAA,MACA,OAAO,IAAA,GAAO,CAAA,GAAA,CAAK,MAAM,IAAA,CAAK,QAAA,IAAY,OAAO,CAAC;AAAA,KACpD;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,GAAA,EAAqB;AACzB,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,QAAA,EAAU,KAAK,GAAA,CAAI,IAAA,CAAK,QAAA,EAAU,GAAG,CAAC,CAAA;AACpE,IAAA,IAAI,IAAA,CAAK,SAAA,IAAa,CAAA,EAAG,OAAO,OAAA;AAChC,IAAA,MAAM,OAAA,GACJ,IAAA,CAAK,KAAA,CAAA,CAAO,OAAA,GAAU,IAAA,CAAK,QAAA,IAAY,IAAA,CAAK,SAAS,CAAA,GAAI,IAAA,CAAK,SAAA,GAAY,IAAA,CAAK,QAAA;AACjF,IAAA,OAAO,IAAA,CAAK,IAAI,IAAA,CAAK,QAAA,EAAU,KAAK,GAAA,CAAI,IAAA,CAAK,QAAA,EAAU,OAAO,CAAC,CAAA;AAAA,EACjE;AACF;AAOA,SAAS,iBAAA,CACP,KAAA,EACA,SAAA,EACA,GAAA,EACA,OAAA,EACS;AACT,EAAA,OAAO,KAAA,KAAU,aAAa,GAAA,KAAQ,OAAA;AACxC","file":"range_slider_controller.js","sourcesContent":["/** Normalized scroll position and maximum distance on one logical axis. */\nexport interface LogicalScrollMetrics {\n position: number;\n max: number;\n}\n\n/**\n * Whether horizontal scrolling on `element` follows right-to-left inline flow.\n *\n * Resolved from the **computed** `direction`, so the authoring contract is the\n * usual `dir=\"rtl\"` (or a stylesheet) on the element or any ancestor.\n *\n * Scope: horizontal writing modes. A vertical writing mode (`writing-mode:\n * vertical-rl`) also inverts the horizontal axis, which this check does not\n * model — vertical writing modes are out of scope for the scroll utilities\n * (their consumers describe axes as horizontal/vertical, not inline/block).\n */\nexport function isRtl(element: Element): boolean {\n return window.getComputedStyle(element).direction === \"rtl\";\n}\n\n/**\n * Returns scroll distance from the logical start edge.\n *\n * CSSOM View exposes standards-mode RTL horizontal offsets as `0` at the inline\n * start (right) and increasingly negative values toward the inline end (left).\n * The normalized position is always clamped to `[0, max]`, which also absorbs\n * Safari's elastic overscroll values.\n */\nexport function logicalScrollMetrics(\n element: HTMLElement,\n horizontal: boolean,\n): LogicalScrollMetrics {\n const max = Math.max(\n 0,\n horizontal\n ? element.scrollWidth - element.clientWidth\n : element.scrollHeight - element.clientHeight,\n );\n const raw = horizontal ? element.scrollLeft : element.scrollTop;\n const position = horizontal && isRtl(element) ? -raw : raw;\n return { position: Math.min(max, Math.max(0, position)), max };\n}\n\n/**\n * Converts a logical start/end delta to the physical value accepted by\n * `Element.scrollBy`.\n */\nexport function physicalScrollDelta(\n element: HTMLElement,\n horizontal: boolean,\n logicalDelta: number,\n): number {\n return horizontal && isRtl(element) ? -logicalDelta : logicalDelta;\n}\n","import { isRtl } from \"./logical_scroll\";\n\n/**\n * Turns an arrow key into a **logical** step: `+1` for \"next\", `-1` for\n * \"previous\", `0` when the key names neither.\n *\n * APG defines the horizontal pair as *next / previous* and says a vertical\n * arrangement swaps in Down/Up for the same meaning — so the pair is one axis's\n * spelling of an order, and the order reverses with the writing direction. Only\n * the horizontal pair reverses. Down/Up name an axis the writing direction does\n * not mirror, and returning them unchanged is the point: many controllers fold\n * both pairs into one branch, where swapping the branches under RTL would flip\n * the vertical axis too — a bug that reads as \"the arrows work\" until someone\n * presses Down.\n *\n * **Direction is read from the element the caller passes, which should be the\n * container that lays the items out** — not the focused child. A child may carry\n * its own `dir` (an LTR input inside an RTL form is ordinary authoring), and\n * probing per handler makes two handlers disagree at the boundary between them.\n *\n * This decides direction only. Whether the axis is even active (an\n * `orientation=\"horizontal\"` widget ignoring Down/Up), how far the step lands,\n * and what wrapping does all stay with the caller.\n *\n * **It encodes the list-order convention: `ArrowDown` is *next*.** Widgets that\n * pair the arrows by *value* instead — `ArrowUp` meaning \"more\", as a rating or a\n * slider does — must not use this, or their vertical axis inverts. Reverse the\n * horizontal pair on its own there.\n *\n * @example\n * ```ts\n * const step = logicalArrowStep(event.key, this.element);\n * if (step === 0) return;\n * this.#roving.setActive(rovingMove(current, length, step, \"wrap\"), { focus: true });\n * ```\n */\nexport function logicalArrowStep(key: string, element: Element): 1 | -1 | 0 {\n if (key === \"ArrowDown\") return 1;\n if (key === \"ArrowUp\") return -1;\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return 0;\n const forward = isRtl(element) ? \"ArrowLeft\" : \"ArrowRight\";\n return key === forward ? 1 : -1;\n}\n\n/**\n * Rewrites `key` so an existing LTR-shaped branch keeps working under RTL:\n * `ArrowRight` and `ArrowLeft` trade places, everything else passes through.\n *\n * The alternative — negating a delta — silently breaks handlers whose two\n * horizontal branches are **not mirror images**. A grid that clamps one edge but\n * not the other, or a segmented field guarding `index > 0` on one side and\n * `index < length - 1` on the other, ends up applying the wrong guard to the\n * wrong direction. Swapping the key leaves each branch, guards and all, exactly\n * where its author put it.\n *\n * Same rule as {@link logicalArrowStep} about which element to read: pass the\n * container that lays the items out, not the focused child.\n *\n * @example\n * ```ts\n * switch (logicalArrowKey(event.key, this.element)) {\n * case \"ArrowLeft\": // \"previous\" — whatever direction that is on screen\n * ```\n */\nexport function logicalArrowKey(key: string, element: Element): string {\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return key;\n if (!isRtl(element)) return key;\n return key === \"ArrowRight\" ? \"ArrowLeft\" : \"ArrowRight\";\n}\n\n/** Modifiers a widget may claim on an arrow key, named for the `allow` list. */\nexport type ArrowModifier = \"alt\" | \"ctrl\" | \"meta\" | \"shift\";\n\n/**\n * True when an arrow key arrived carrying a modifier the widget must leave to\n * the browser: return without calling `preventDefault()` and without moving any\n * state.\n *\n * A bare arrow belongs to the widget; a chorded one usually does not.\n * `Alt`/`Meta` plus a horizontal arrow is history back/forward on every desktop\n * browser, and a widget that swallows it makes the shortcut work or not\n * depending on where focus happens to sit — a coin-flip the user cannot see.\n *\n * `allow` is for the combinations APG assigns to a pattern **and the widget\n * actually implements** — today only Combobox's optional `Alt+Down`/`Alt+Up`.\n * Listing one the widget does not implement defeats the point: the chord then\n * runs the plain-arrow branch, which is exactly what this guard exists to stop.\n * Non-arrow keys return `false`, so chorded letters and\n * `Control+Home`/`Control+End` are untouched.\n *\n * @example\n * ```ts\n * if (isReservedArrowChord(event)) return;\n * ```\n */\nexport function isReservedArrowChord(\n event: KeyboardEvent,\n allow: readonly ArrowModifier[] = [],\n): boolean {\n if (!event.key.startsWith(\"Arrow\")) return false;\n return (\n (event.altKey && !allow.includes(\"alt\")) ||\n (event.ctrlKey && !allow.includes(\"ctrl\")) ||\n (event.metaKey && !allow.includes(\"meta\")) ||\n (event.shiftKey && !allow.includes(\"shift\"))\n );\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { isReservedArrowChord, logicalArrowKey } from \"../utils/arrow_step\";\nimport { isRtl } from \"../utils/logical_scroll\";\n\n/** CSS custom properties exposing each thumb's position (0..1) to the consumer. */\nconst START_PROPERTY = \"--stimeo-range-start\";\nconst END_PROPERTY = \"--stimeo-range-end\";\n\n/**\n * Headless, accessible **two-thumb range slider** behavior (APG Slider —\n * Multi-Thumb). A derivative of {@link SliderController}: it manages two thumbs\n * (`start` ≤ `end`) that constrain each other.\n *\n * Markup contract (identifier: `stimeo--range-slider`):\n * <div data-controller=\"stimeo--range-slider\"\n * data-stimeo--range-slider-min-value=\"0\"\n * data-stimeo--range-slider-max-value=\"100\"\n * data-stimeo--range-slider-step-value=\"1\"\n * data-stimeo--range-slider-start-value=\"20\"\n * data-stimeo--range-slider-end-value=\"80\">\n * <div data-stimeo--range-slider-target=\"track\"\n * data-action=\"pointerdown->stimeo--range-slider#onPointerDown\">\n * <div role=\"slider\" tabindex=\"0\" aria-label=\"Minimum\"\n * data-stimeo--range-slider-target=\"startThumb\"\n * data-action=\"keydown->stimeo--range-slider#onKeydown\"></div>\n * <div role=\"slider\" tabindex=\"0\" aria-label=\"Maximum\"\n * data-stimeo--range-slider-target=\"endThumb\"\n * data-action=\"keydown->stimeo--range-slider#onKeydown\"></div>\n * </div>\n * </div>\n *\n * @remarks\n * Behavior only — the consumer owns all layout (positioning the thumbs and the\n * selected range from the fractions). Only the horizontal orientation is handled.\n * Each thumb's movable range is bounded by the *other* thumb's current value,\n * reflected on its `aria-valuemin`/`aria-valuemax` so assistive tech announces the\n * live constraint.\n *\n * Behavior provided (per focused thumb):\n * - `ArrowRight`/`ArrowUp` increase and `ArrowLeft`/`ArrowDown` decrease by one\n * step; `Home`/`End` jump to that thumb's movable min/max; `PageUp`/`PageDown`\n * move by ten steps. A thumb never crosses the other.\n * - Pointer press/drag on the track moves the nearest thumb.\n *\n * The fractions are value ratios, not positions, so only the consumer knows\n * whether their track mirrors under RTL. Set `logicalTrack` to declare that it\n * does: the pointer mapping and the horizontal arrow pair then follow the\n * writing direction. Left unset, nothing here reads `direction`.\n */\nexport class RangeSliderController extends Controller<HTMLElement> {\n static override targets = [\"track\", \"startThumb\", \"endThumb\"];\n static override values = {\n min: { type: Number, default: 0 },\n max: { type: Number, default: 100 },\n step: { type: Number, default: 1 },\n start: { type: Number, default: 0 },\n end: { type: Number, default: 100 },\n logicalTrack: { type: Boolean, default: false },\n };\n static actions = [\"onKeydown\", \"onPointerDown\"] as const;\n static events = [\"change\"] as const;\n\n declare readonly trackTarget: HTMLElement;\n declare readonly startThumbTarget: HTMLElement;\n declare readonly endThumbTarget: HTMLElement;\n declare readonly hasTrackTarget: boolean;\n declare readonly hasStartThumbTarget: boolean;\n declare readonly hasEndThumbTarget: boolean;\n declare minValue: number;\n declare maxValue: number;\n declare stepValue: number;\n declare startValue: number;\n declare endValue: number;\n declare logicalTrackValue: boolean;\n\n /** Aborts in-progress pointer-drag listeners when the drag ends or on teardown. */\n #dragAbort: AbortController | null = null;\n\n /** Whether the consumer declared a mirroring track and the direction mirrors it. */\n get #mirrored(): boolean {\n return this.logicalTrackValue && isRtl(this.element);\n }\n\n /** Normalizes the initial pair (clamped, snapped, ordered) and renders. */\n override connect(): void {\n // Order the initial pair up front so a reversed start/end is corrected by\n // swapping (preserving both values) rather than collapsing one onto the other.\n const lo = Math.min(this.startValue, this.endValue);\n const hi = Math.max(this.startValue, this.endValue);\n this.#commit(lo, hi, false);\n }\n\n /** Cancels any active pointer drag so document listeners never leak. */\n override disconnect(): void {\n this.#dragAbort?.abort();\n this.#dragAbort = null;\n }\n\n /** Keyboard stepping for whichever thumb is focused (the action's element). */\n onKeydown(event: KeyboardEvent): void {\n if (isReservedArrowChord(event)) return;\n const thumb = event.currentTarget as HTMLElement;\n const isStart = this.hasStartThumbTarget && thumb === this.startThumbTarget;\n const current = isStart ? this.startValue : this.endValue;\n // The opposing thumb caps this one's travel so the two never cross.\n const lower = isStart ? this.minValue : this.startValue;\n const upper = isStart ? this.endValue : this.maxValue;\n const big = this.stepValue * 10;\n\n let next: number | null = null;\n // On a mirrored track the greater value sits at the visual left, so the\n // horizontal pair trades places; `Home`/`End` name bounds, not a direction.\n switch (this.#mirrored ? logicalArrowKey(event.key, this.element) : event.key) {\n case \"ArrowRight\":\n case \"ArrowUp\":\n next = current + this.stepValue;\n break;\n case \"ArrowLeft\":\n case \"ArrowDown\":\n next = current - this.stepValue;\n break;\n case \"PageUp\":\n next = current + big;\n break;\n case \"PageDown\":\n next = current - big;\n break;\n case \"Home\":\n next = lower;\n break;\n case \"End\":\n next = upper;\n break;\n default:\n return;\n }\n event.preventDefault();\n this.#moveThumb(isStart, next);\n }\n\n /** Begins a pointer drag on the track, moving the thumb nearest the press. */\n onPointerDown(event: PointerEvent): void {\n if (!this.hasTrackTarget) return;\n // Resolve the direction once for the whole gesture: reading it per move\n // would query computed style on every frame, and a drag that flipped\n // mid-gesture would be incoherent anyway.\n const mirrored = this.#mirrored;\n const value = this.#valueFromClientX(event.clientX, mirrored);\n if (value === null) return;\n event.preventDefault();\n\n // Pick the nearer thumb; ties go to the start thumb so a press exactly\n // between them stays deterministic. Only read the target getter behind its\n // has*Target guard — Stimulus throws when an absent target is accessed.\n const useStart = Math.abs(value - this.startValue) <= Math.abs(value - this.endValue);\n if (useStart) {\n if (this.hasStartThumbTarget) this.startThumbTarget.focus();\n } else if (this.hasEndThumbTarget) {\n this.endThumbTarget.focus();\n }\n this.#moveThumb(useStart, value);\n\n this.#dragAbort?.abort();\n const abort = new AbortController();\n this.#dragAbort = abort;\n const onMove = (move: PointerEvent): void => {\n const moved = this.#valueFromClientX(move.clientX, mirrored);\n if (moved !== null) this.#moveThumb(useStart, moved);\n };\n const onUp = (): void => {\n abort.abort();\n this.#dragAbort = null;\n };\n document.addEventListener(\"pointermove\", onMove, { signal: abort.signal });\n document.addEventListener(\"pointerup\", onUp, { signal: abort.signal });\n // pointercancel fires when the gesture is interrupted (OS gesture, scroll\n // takeover, device switch); clean up the same way so no listener leaks.\n document.addEventListener(\"pointercancel\", onUp, { signal: abort.signal });\n }\n\n /** Maps a pointer X coordinate to a raw value using the track geometry. */\n #valueFromClientX(clientX: number, mirrored: boolean): number | null {\n const rect = this.trackTarget.getBoundingClientRect();\n if (rect.width === 0) return null;\n const offset = (clientX - rect.left) / rect.width;\n const fraction = mirrored ? 1 - offset : offset;\n return this.minValue + fraction * (this.maxValue - this.minValue);\n }\n\n /** Moves one thumb to a new raw value, keeping the pair ordered. */\n #moveThumb(isStart: boolean, raw: number): void {\n if (isStart) {\n this.#commit(raw, this.endValue, true);\n } else {\n this.#commit(this.startValue, raw, true);\n }\n }\n\n /**\n * Clamps and snaps `start`/`end`, enforces `start ≤ end`, stores the pair, and\n * reflects it onto the thumbs' ARIA attributes and the range custom\n * properties. Dispatches `change` only on user-driven updates (`notify`).\n */\n #commit(start: number, end: number, notify: boolean): void {\n const prevStart = this.startValue;\n const prevEnd = this.endValue;\n\n let nextStart = this.#snap(start);\n let nextEnd = this.#snap(end);\n // Keep them ordered: a thumb pushed past its partner stops at the partner.\n if (nextStart > nextEnd) {\n if (isUserMovingStart(start, prevStart, end, prevEnd)) nextStart = nextEnd;\n else nextEnd = nextStart;\n }\n\n this.startValue = nextStart;\n this.endValue = nextEnd;\n this.#render(nextStart, nextEnd);\n\n if (notify && (nextStart !== prevStart || nextEnd !== prevEnd)) {\n this.dispatch(\"change\", { detail: { start: nextStart, end: nextEnd } });\n }\n }\n\n /** Reflects the current pair onto thumb ARIA attributes and CSS properties. */\n #render(start: number, end: number): void {\n if (this.hasStartThumbTarget) {\n this.startThumbTarget.setAttribute(\"aria-valuemin\", String(this.minValue));\n this.startThumbTarget.setAttribute(\"aria-valuemax\", String(end));\n this.startThumbTarget.setAttribute(\"aria-valuenow\", String(start));\n }\n if (this.hasEndThumbTarget) {\n this.endThumbTarget.setAttribute(\"aria-valuemin\", String(start));\n this.endThumbTarget.setAttribute(\"aria-valuemax\", String(this.maxValue));\n this.endThumbTarget.setAttribute(\"aria-valuenow\", String(end));\n }\n const span = this.maxValue - this.minValue;\n this.element.style.setProperty(\n START_PROPERTY,\n String(span > 0 ? (start - this.minValue) / span : 0),\n );\n this.element.style.setProperty(\n END_PROPERTY,\n String(span > 0 ? (end - this.minValue) / span : 0),\n );\n }\n\n /** Clamps `raw` to `[min, max]` and snaps it to the nearest step from `min`. */\n #snap(raw: number): number {\n const clamped = Math.min(this.maxValue, Math.max(this.minValue, raw));\n if (this.stepValue <= 0) return clamped;\n const stepped =\n Math.round((clamped - this.minValue) / this.stepValue) * this.stepValue + this.minValue;\n return Math.min(this.maxValue, Math.max(this.minValue, stepped));\n }\n}\n\n/**\n * Decides which thumb yields when a move would cross the pair. The moving thumb\n * is the one whose requested value differs from its previous value; it stops at\n * the partner rather than dragging the partner along.\n */\nfunction isUserMovingStart(\n start: number,\n prevStart: number,\n end: number,\n prevEnd: number,\n): boolean {\n return start !== prevStart && end === prevEnd;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/logical_scroll.ts","../../src/utils/arrow_step.ts","../../src/utils/microtask_coalescer.ts","../../src/utils/range.ts","../../src/controllers/range_slider_controller.ts"],"names":[],"mappings":";;;;;AAiBO,SAAS,MAAM,OAAA,EAA2B;AAC/C,EAAA,OAAO,MAAA,CAAO,gBAAA,CAAiB,OAAO,CAAA,CAAE,SAAA,KAAc,KAAA;AACxD;;;AC6CO,SAAS,eAAA,CAAgB,KAAa,OAAA,EAA0B;AACrE,EAAA,IAAI,GAAA,KAAQ,YAAA,IAAgB,GAAA,KAAQ,WAAA,EAAa,OAAO,GAAA;AACxD,EAAA,IAAI,CAAC,KAAA,CAAM,OAAO,CAAA,EAAG,OAAO,GAAA;AAC5B,EAAA,OAAO,GAAA,KAAQ,eAAe,WAAA,GAAc,YAAA;AAC9C;AA2BO,SAAS,oBAAA,CACd,KAAA,EACA,KAAA,GAAkC,EAAC,EAC1B;AACT,EAAA,IAAI,CAAC,KAAA,CAAM,GAAA,CAAI,UAAA,CAAW,OAAO,GAAG,OAAO,KAAA;AAC3C,EAAA,OACG,KAAA,CAAM,MAAA,IAAU,CAAC,KAAA,CAAM,QAAA,CAAS,KAAK,CAAA,IACrC,KAAA,CAAM,OAAA,IAAW,CAAC,KAAA,CAAM,QAAA,CAAS,MAAM,KACvC,KAAA,CAAM,OAAA,IAAW,CAAC,KAAA,CAAM,QAAA,CAAS,MAAM,CAAA,IACvC,KAAA,CAAM,QAAA,IAAY,CAAC,KAAA,CAAM,QAAA,CAAS,OAAO,CAAA;AAE9C;;;ACvDO,IAAM,qBAAN,MAAyB;AAAA,EACrB,IAAA;AAAA,EACT,OAAA,GAAU,KAAA;AAAA,EACV,OAAA,GAAU,KAAA;AAAA,EACV,WAAA,GAAc,CAAA;AAAA;AAAA,EAG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,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,IAC/D;AACA,IAAA,IAAA,CAAK,QAAQ,KAAA,CAAM,WAAA;AAAA,MACjB,cAAA;AAAA,MACA,OAAO,aAAA,CAAc,KAAA,EAAO,KAAK,QAAA,EAAU,IAAA,CAAK,QAAQ,CAAC;AAAA,KAC3D;AACA,IAAA,IAAA,CAAK,QAAQ,KAAA,CAAM,WAAA;AAAA,MACjB,YAAA;AAAA,MACA,OAAO,aAAA,CAAc,GAAA,EAAK,KAAK,QAAA,EAAU,IAAA,CAAK,QAAQ,CAAC;AAAA,KACzD;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,GAAA,EAAqB;AACzB,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,QAAA,EAAU,KAAK,GAAA,CAAI,IAAA,CAAK,QAAA,EAAU,GAAG,CAAC,CAAA;AACpE,IAAA,IAAI,IAAA,CAAK,SAAA,IAAa,CAAA,EAAG,OAAO,OAAA;AAChC,IAAA,MAAM,OAAA,GACJ,IAAA,CAAK,KAAA,CAAA,CAAO,OAAA,GAAU,IAAA,CAAK,QAAA,IAAY,IAAA,CAAK,SAAS,CAAA,GAAI,IAAA,CAAK,SAAA,GAAY,IAAA,CAAK,QAAA;AACjF,IAAA,OAAO,IAAA,CAAK,IAAI,IAAA,CAAK,QAAA,EAAU,KAAK,GAAA,CAAI,IAAA,CAAK,QAAA,EAAU,OAAO,CAAC,CAAA;AAAA,EACjE;AACF;AAOA,SAAS,iBAAA,CACP,KAAA,EACA,SAAA,EACA,GAAA,EACA,OAAA,EACS;AACT,EAAA,OAAO,KAAA,KAAU,aAAa,GAAA,KAAQ,OAAA;AACxC","file":"range_slider_controller.js","sourcesContent":["/** Normalized scroll position and maximum distance on one logical axis. */\nexport interface LogicalScrollMetrics {\n position: number;\n max: number;\n}\n\n/**\n * Whether horizontal scrolling on `element` follows right-to-left inline flow.\n *\n * Resolved from the **computed** `direction`, so the authoring contract is the\n * usual `dir=\"rtl\"` (or a stylesheet) on the element or any ancestor.\n *\n * Scope: horizontal writing modes. A vertical writing mode (`writing-mode:\n * vertical-rl`) also inverts the horizontal axis, which this check does not\n * model — vertical writing modes are out of scope for the scroll utilities\n * (their consumers describe axes as horizontal/vertical, not inline/block).\n */\nexport function isRtl(element: Element): boolean {\n return window.getComputedStyle(element).direction === \"rtl\";\n}\n\n/**\n * Returns scroll distance from the logical start edge.\n *\n * CSSOM View exposes standards-mode RTL horizontal offsets as `0` at the inline\n * start (right) and increasingly negative values toward the inline end (left).\n * The normalized position is always clamped to `[0, max]`, which also absorbs\n * Safari's elastic overscroll values.\n */\nexport function logicalScrollMetrics(\n element: HTMLElement,\n horizontal: boolean,\n): LogicalScrollMetrics {\n const max = Math.max(\n 0,\n horizontal\n ? element.scrollWidth - element.clientWidth\n : element.scrollHeight - element.clientHeight,\n );\n const raw = horizontal ? element.scrollLeft : element.scrollTop;\n const position = horizontal && isRtl(element) ? -raw : raw;\n return { position: Math.min(max, Math.max(0, position)), max };\n}\n\n/**\n * Converts a logical start/end delta to the physical value accepted by\n * `Element.scrollBy`.\n */\nexport function physicalScrollDelta(\n element: HTMLElement,\n horizontal: boolean,\n logicalDelta: number,\n): number {\n return horizontal && isRtl(element) ? -logicalDelta : logicalDelta;\n}\n","import { isRtl } from \"./logical_scroll\";\n\n/**\n * Turns an arrow key into a **logical** step: `+1` for \"next\", `-1` for\n * \"previous\", `0` when the key names neither.\n *\n * APG defines the horizontal pair as *next / previous* and says a vertical\n * arrangement swaps in Down/Up for the same meaning — so the pair is one axis's\n * spelling of an order, and the order reverses with the writing direction. Only\n * the horizontal pair reverses. Down/Up name an axis the writing direction does\n * not mirror, and returning them unchanged is the point: many controllers fold\n * both pairs into one branch, where swapping the branches under RTL would flip\n * the vertical axis too — a bug that reads as \"the arrows work\" until someone\n * presses Down.\n *\n * **Direction is read from the element the caller passes, which should be the\n * container that lays the items out** — not the focused child. A child may carry\n * its own `dir` (an LTR input inside an RTL form is ordinary authoring), and\n * probing per handler makes two handlers disagree at the boundary between them.\n *\n * This decides direction only. Whether the axis is even active (an\n * `orientation=\"horizontal\"` widget ignoring Down/Up), how far the step lands,\n * and what wrapping does all stay with the caller.\n *\n * **It encodes the list-order convention: `ArrowDown` is *next*.** Widgets that\n * pair the arrows by *value* instead — `ArrowUp` meaning \"more\", as a rating or a\n * slider does — must not use this, or their vertical axis inverts. Reverse the\n * horizontal pair on its own there.\n *\n * @example\n * ```ts\n * const step = logicalArrowStep(event.key, this.element);\n * if (step === 0) return;\n * this.#roving.setActive(rovingMove(current, length, step, \"wrap\"), { focus: true });\n * ```\n */\nexport function logicalArrowStep(key: string, element: Element): 1 | -1 | 0 {\n if (key === \"ArrowDown\") return 1;\n if (key === \"ArrowUp\") return -1;\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return 0;\n const forward = isRtl(element) ? \"ArrowLeft\" : \"ArrowRight\";\n return key === forward ? 1 : -1;\n}\n\n/**\n * Rewrites `key` so an existing LTR-shaped branch keeps working under RTL:\n * `ArrowRight` and `ArrowLeft` trade places, everything else passes through.\n *\n * The alternative — negating a delta — silently breaks handlers whose two\n * horizontal branches are **not mirror images**. A grid that clamps one edge but\n * not the other, or a segmented field guarding `index > 0` on one side and\n * `index < length - 1` on the other, ends up applying the wrong guard to the\n * wrong direction. Swapping the key leaves each branch, guards and all, exactly\n * where its author put it.\n *\n * Same rule as {@link logicalArrowStep} about which element to read: pass the\n * container that lays the items out, not the focused child.\n *\n * @example\n * ```ts\n * switch (logicalArrowKey(event.key, this.element)) {\n * case \"ArrowLeft\": // \"previous\" — whatever direction that is on screen\n * ```\n */\nexport function logicalArrowKey(key: string, element: Element): string {\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return key;\n if (!isRtl(element)) return key;\n return key === \"ArrowRight\" ? \"ArrowLeft\" : \"ArrowRight\";\n}\n\n/** Modifiers a widget may claim on an arrow key, named for the `allow` list. */\nexport type ArrowModifier = \"alt\" | \"ctrl\" | \"meta\" | \"shift\";\n\n/**\n * True when an arrow key arrived carrying a modifier the widget must leave to\n * the browser: return without calling `preventDefault()` and without moving any\n * state.\n *\n * A bare arrow belongs to the widget; a chorded one usually does not.\n * `Alt`/`Meta` plus a horizontal arrow is history back/forward on every desktop\n * browser, and a widget that swallows it makes the shortcut work or not\n * depending on where focus happens to sit — a coin-flip the user cannot see.\n *\n * `allow` is for the combinations APG assigns to a pattern **and the widget\n * actually implements** — today only Combobox's optional `Alt+Down`/`Alt+Up`.\n * Listing one the widget does not implement defeats the point: the chord then\n * runs the plain-arrow branch, which is exactly what this guard exists to stop.\n * Non-arrow keys return `false`, so chorded letters and\n * `Control+Home`/`Control+End` are untouched.\n *\n * @example\n * ```ts\n * if (isReservedArrowChord(event)) return;\n * ```\n */\nexport function isReservedArrowChord(\n event: KeyboardEvent,\n allow: readonly ArrowModifier[] = [],\n): boolean {\n if (!event.key.startsWith(\"Arrow\")) return false;\n return (\n (event.altKey && !allow.includes(\"alt\")) ||\n (event.ctrlKey && !allow.includes(\"ctrl\")) ||\n (event.metaKey && !allow.includes(\"meta\")) ||\n (event.shiftKey && !allow.includes(\"shift\"))\n );\n}\n","/**\n * Collapses many target callbacks from one DOM mutation into a single pass.\n *\n * Stimulus fires `<name>TargetConnected` / `Disconnected` once per element, so\n * replacing a list of N options delivers N callbacks — but the useful unit of\n * work is \"reconcile against the DOM that resulted\", once, after the batch has\n * settled. Every controller that owns a reconcilable target set needs the same\n * shape: a `queued` flag plus `queueMicrotask`.\n *\n * **A microtask is the right horizon, and the reason is specific.** Stimulus\n * drives these callbacks from a `MutationObserver`, whose own callback already\n * runs as a microtask with the whole batch in hand; scheduling one more lands\n * after the last sibling callback of that batch and still before paint or any\n * event handler. A timer would be later than it needs to be, and reconciling\n * synchronously would run once per element against a half-applied DOM.\n *\n * **The two guards are not the same guard.** Scheduling is refused before the\n * controller connects, and running is refused after it disconnects:\n *\n * - **Before `connect()`** — Stimulus delivers the *initial* target callbacks\n * ahead of `connect()`. Reconciling there would compute a fallback against a\n * controller whose own state has not been initialised, and `connect()` is\n * about to do a full pass anyway.\n * - **After `disconnect()`** — Stimulus fires a callback for **every** target\n * during teardown, and a microtask queued just before it would otherwise run\n * against a detached tree. {@link MicrotaskCoalescer.cancel} exists for the\n * teardown path to drop the pending pass outright.\n *\n * Both guards are part of one contract here rather than something each consumer\n * has to remember separately.\n *\n * Scope is the scheduling only. *What* to reconcile — keep the surviving active\n * option, fall back to the next / previous / first visible one, rebuild derived\n * chips or hidden fields — stays in the controller, because no two consumers\n * answer it the same way.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileOptions());\n *\n * connect() { this.#reconcile.activate(); }\n * disconnect() { this.#reconcile.cancel(); }\n *\n * optionTargetConnected() { this.#reconcile.schedule(); }\n * optionTargetDisconnected() { this.#reconcile.schedule(); }\n * ```\n */\nexport class MicrotaskCoalescer {\n readonly #run: () => void;\n #queued = false;\n #active = false;\n #generation = 0;\n\n /** @param run - the single reconciliation pass, invoked at most once per batch. */\n constructor(run: () => void) {\n this.#run = run;\n }\n\n /** Opens the window in which {@link schedule} is honoured; call from `connect()`. */\n activate(): void {\n this.#active = true;\n }\n\n /** Closes the window and drops any pending pass; call from `disconnect()`. */\n cancel(): void {\n this.#active = false;\n this.#queued = false;\n this.#generation += 1;\n }\n\n /** Requests one pass after the batch settles. Idempotent; inert outside the window. */\n schedule(): void {\n if (!this.#active || this.#queued) return;\n this.#queued = true;\n const generation = this.#generation;\n queueMicrotask(() => {\n // A cancelled callback must not consume a pass queued after reconnect.\n if (generation !== this.#generation || !this.#queued || !this.#active) return;\n this.#queued = false;\n this.#run();\n });\n }\n}\n","/**\n * Range normalization shared by the value-bearing controllers (progress, meter,\n * slider, range-slider).\n *\n * Each of them publishes \"where the value sits inside `[min, max]`\" as a CSS\n * custom property the consumer multiplies a track by, and each has to answer the\n * same degenerate cases: empty and inverted ranges cannot express progress, and\n * malformed Number Values can produce `NaN`. Keeping the rule in one place is\n * what makes those answers identical across the four.\n */\n\n/**\n * Fraction of `[min, max]` that `value` occupies, always within `[0, 1]`.\n *\n * `value` is clamped into the range first, so a value outside it reports a full\n * or empty track rather than pushing the fraction past the ends.\n *\n * An empty, inverted, or non-numeric range yields `0`. That is a deliberate\n * floor rather than a computed result: `min === max` would produce `NaN`, and\n * `min > max` would report a full track for a value that is really out of range.\n * Non-finite results are floored for the same reason. These results reach\n * assistive tech, because the same fraction drives the percentage substituted\n * into `aria-valuetext`.\n */\nexport function rangeFraction(value: number, min: number, max: number): number {\n const span = max - min;\n if (!(span > 0)) return 0;\n\n const clamped = Math.min(max, Math.max(min, value));\n let fraction: number;\n if (Number.isFinite(span)) {\n fraction = (clamped - min) / span;\n } else {\n // Scaling preserves the ratio when two finite endpoints straddle zero so\n // widely that their subtraction overflows to Infinity.\n const scale = Math.max(Math.abs(min), Math.abs(max));\n fraction = (clamped / scale - min / scale) / (max / scale - min / scale);\n }\n\n if (!Number.isFinite(fraction)) return 0;\n return Math.min(1, Math.max(0, fraction));\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { isReservedArrowChord, logicalArrowKey } from \"../utils/arrow_step\";\nimport { isRtl } from \"../utils/logical_scroll\";\nimport { MicrotaskCoalescer } from \"../utils/microtask_coalescer\";\nimport { rangeFraction } from \"../utils/range\";\n\n/** CSS custom properties exposing each thumb's position (0..1) to the consumer. */\nconst START_PROPERTY = \"--stimeo-range-start\";\nconst END_PROPERTY = \"--stimeo-range-end\";\n\n/**\n * Headless, accessible **two-thumb range slider** behavior (APG Slider —\n * Multi-Thumb). A derivative of {@link SliderController}: it manages two thumbs\n * (`start` ≤ `end`) that constrain each other.\n *\n * Markup contract (identifier: `stimeo--range-slider`):\n * <div data-controller=\"stimeo--range-slider\"\n * data-stimeo--range-slider-min-value=\"0\"\n * data-stimeo--range-slider-max-value=\"100\"\n * data-stimeo--range-slider-step-value=\"1\"\n * data-stimeo--range-slider-start-value=\"20\"\n * data-stimeo--range-slider-end-value=\"80\">\n * <div data-stimeo--range-slider-target=\"track\"\n * data-action=\"pointerdown->stimeo--range-slider#onPointerDown\">\n * <div role=\"slider\" tabindex=\"0\" aria-label=\"Minimum\"\n * data-stimeo--range-slider-target=\"startThumb\"\n * data-action=\"keydown->stimeo--range-slider#onKeydown\"></div>\n * <div role=\"slider\" tabindex=\"0\" aria-label=\"Maximum\"\n * data-stimeo--range-slider-target=\"endThumb\"\n * data-action=\"keydown->stimeo--range-slider#onKeydown\"></div>\n * </div>\n * </div>\n *\n * @remarks\n * Behavior only — the consumer owns all layout (positioning the thumbs and the\n * selected range from the fractions). Only the horizontal orientation is handled.\n * Each thumb's movable range is bounded by the *other* thumb's current value,\n * reflected on its `aria-valuemin`/`aria-valuemax` so assistive tech announces the\n * live constraint.\n *\n * Behavior provided (per focused thumb):\n * - `ArrowRight`/`ArrowUp` increase and `ArrowLeft`/`ArrowDown` decrease by one\n * step; `Home`/`End` jump to that thumb's movable min/max; `PageUp`/`PageDown`\n * move by ten steps. A thumb never crosses the other.\n * - Pointer press/drag on the track moves the nearest thumb.\n *\n * The fractions are value ratios, not positions, so only the consumer knows\n * whether their track mirrors under RTL. Set `logicalTrack` to declare that it\n * does: the pointer mapping and the horizontal arrow pair then follow the\n * writing direction. Left unset, nothing here reads `direction`.\n */\nexport class RangeSliderController extends Controller<HTMLElement> {\n static override targets = [\"track\", \"startThumb\", \"endThumb\"];\n static override values = {\n min: { type: Number, default: 0 },\n max: { type: Number, default: 100 },\n step: { type: Number, default: 1 },\n start: { type: Number, default: 0 },\n end: { type: Number, default: 100 },\n logicalTrack: { type: Boolean, default: false },\n };\n static actions = [\"onKeydown\", \"onPointerDown\"] as const;\n static events = [\"change\"] as const;\n\n declare readonly trackTarget: HTMLElement;\n declare readonly startThumbTarget: HTMLElement;\n declare readonly endThumbTarget: HTMLElement;\n declare readonly hasTrackTarget: boolean;\n declare readonly hasStartThumbTarget: boolean;\n declare readonly hasEndThumbTarget: boolean;\n declare minValue: number;\n declare maxValue: number;\n declare stepValue: number;\n declare startValue: number;\n declare endValue: number;\n declare logicalTrackValue: boolean;\n\n /** Aborts in-progress pointer-drag listeners when the drag ends or on teardown. */\n #dragAbort: AbortController | null = null;\n\n /** Whether the consumer declared a mirroring track and the direction mirrors it. */\n get #mirrored(): boolean {\n return this.logicalTrackValue && isRtl(this.element);\n }\n\n /** Normalizes the initial pair (clamped, snapped, ordered) and renders. */\n /**\n * Collapses a morph that swaps render inputs into one repaint, and refuses the\n * pass Stimulus delivers before `connect()`.\n */\n readonly #repaint = new MicrotaskCoalescer(() => {\n this.#render(this.startValue, this.endValue);\n });\n\n override connect(): void {\n this.#repaint.activate();\n // Order the initial pair up front so a reversed start/end is corrected by\n // swapping (preserving both values) rather than collapsing one onto the other.\n const lo = Math.min(this.startValue, this.endValue);\n const hi = Math.max(this.startValue, this.endValue);\n this.#commit(lo, hi, false);\n }\n\n /** Cancels any active pointer drag so document listeners never leak. */\n override disconnect(): void {\n this.#repaint.cancel();\n this.#dragAbort?.abort();\n this.#dragAbort = null;\n }\n\n /** Repaints when application code (or a Turbo morph) changes `min` at runtime. */\n minValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /** Repaints when application code (or a Turbo morph) changes `max` at runtime. */\n maxValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /** Keyboard stepping for whichever thumb is focused (the action's element). */\n onKeydown(event: KeyboardEvent): void {\n if (isReservedArrowChord(event)) return;\n const thumb = event.currentTarget as HTMLElement;\n const isStart = this.hasStartThumbTarget && thumb === this.startThumbTarget;\n const current = isStart ? this.startValue : this.endValue;\n // The opposing thumb caps this one's travel so the two never cross.\n const lower = isStart ? this.minValue : this.startValue;\n const upper = isStart ? this.endValue : this.maxValue;\n const big = this.stepValue * 10;\n\n let next: number | null = null;\n // On a mirrored track the greater value sits at the visual left, so the\n // horizontal pair trades places; `Home`/`End` name bounds, not a direction.\n switch (this.#mirrored ? logicalArrowKey(event.key, this.element) : event.key) {\n case \"ArrowRight\":\n case \"ArrowUp\":\n next = current + this.stepValue;\n break;\n case \"ArrowLeft\":\n case \"ArrowDown\":\n next = current - this.stepValue;\n break;\n case \"PageUp\":\n next = current + big;\n break;\n case \"PageDown\":\n next = current - big;\n break;\n case \"Home\":\n next = lower;\n break;\n case \"End\":\n next = upper;\n break;\n default:\n return;\n }\n event.preventDefault();\n this.#moveThumb(isStart, next);\n }\n\n /** Begins a pointer drag on the track, moving the thumb nearest the press. */\n onPointerDown(event: PointerEvent): void {\n if (!this.hasTrackTarget) return;\n // Resolve the direction once for the whole gesture: reading it per move\n // would query computed style on every frame, and a drag that flipped\n // mid-gesture would be incoherent anyway.\n const mirrored = this.#mirrored;\n const value = this.#valueFromClientX(event.clientX, mirrored);\n if (value === null) return;\n event.preventDefault();\n\n // Pick the nearer thumb; ties go to the start thumb so a press exactly\n // between them stays deterministic. Only read the target getter behind its\n // has*Target guard — Stimulus throws when an absent target is accessed.\n const useStart = Math.abs(value - this.startValue) <= Math.abs(value - this.endValue);\n if (useStart) {\n if (this.hasStartThumbTarget) this.startThumbTarget.focus();\n } else if (this.hasEndThumbTarget) {\n this.endThumbTarget.focus();\n }\n this.#moveThumb(useStart, value);\n\n this.#dragAbort?.abort();\n const abort = new AbortController();\n this.#dragAbort = abort;\n const onMove = (move: PointerEvent): void => {\n const moved = this.#valueFromClientX(move.clientX, mirrored);\n if (moved !== null) this.#moveThumb(useStart, moved);\n };\n const onUp = (): void => {\n abort.abort();\n this.#dragAbort = null;\n };\n document.addEventListener(\"pointermove\", onMove, { signal: abort.signal });\n document.addEventListener(\"pointerup\", onUp, { signal: abort.signal });\n // pointercancel fires when the gesture is interrupted (OS gesture, scroll\n // takeover, device switch); clean up the same way so no listener leaks.\n document.addEventListener(\"pointercancel\", onUp, { signal: abort.signal });\n }\n\n /** Maps a pointer X coordinate to a raw value using the track geometry. */\n #valueFromClientX(clientX: number, mirrored: boolean): number | null {\n const rect = this.trackTarget.getBoundingClientRect();\n if (rect.width === 0) return null;\n const offset = (clientX - rect.left) / rect.width;\n const fraction = mirrored ? 1 - offset : offset;\n return this.minValue + fraction * (this.maxValue - this.minValue);\n }\n\n /** Moves one thumb to a new raw value, keeping the pair ordered. */\n #moveThumb(isStart: boolean, raw: number): void {\n if (isStart) {\n this.#commit(raw, this.endValue, true);\n } else {\n this.#commit(this.startValue, raw, true);\n }\n }\n\n /**\n * Clamps and snaps `start`/`end`, enforces `start ≤ end`, stores the pair, and\n * reflects it onto the thumbs' ARIA attributes and the range custom\n * properties. Dispatches `change` only on user-driven updates (`notify`).\n */\n #commit(start: number, end: number, notify: boolean): void {\n const prevStart = this.startValue;\n const prevEnd = this.endValue;\n\n let nextStart = this.#snap(start);\n let nextEnd = this.#snap(end);\n // Keep them ordered: a thumb pushed past its partner stops at the partner.\n if (nextStart > nextEnd) {\n if (isUserMovingStart(start, prevStart, end, prevEnd)) nextStart = nextEnd;\n else nextEnd = nextStart;\n }\n\n this.startValue = nextStart;\n this.endValue = nextEnd;\n this.#render(nextStart, nextEnd);\n\n if (notify && (nextStart !== prevStart || nextEnd !== prevEnd)) {\n this.dispatch(\"change\", { detail: { start: nextStart, end: nextEnd } });\n }\n }\n\n /** Reflects the current pair onto thumb ARIA attributes and CSS properties. */\n #render(start: number, end: number): void {\n if (this.hasStartThumbTarget) {\n this.startThumbTarget.setAttribute(\"aria-valuemin\", String(this.minValue));\n this.startThumbTarget.setAttribute(\"aria-valuemax\", String(end));\n this.startThumbTarget.setAttribute(\"aria-valuenow\", String(start));\n }\n if (this.hasEndThumbTarget) {\n this.endThumbTarget.setAttribute(\"aria-valuemin\", String(start));\n this.endThumbTarget.setAttribute(\"aria-valuemax\", String(this.maxValue));\n this.endThumbTarget.setAttribute(\"aria-valuenow\", String(end));\n }\n this.element.style.setProperty(\n START_PROPERTY,\n String(rangeFraction(start, this.minValue, this.maxValue)),\n );\n this.element.style.setProperty(\n END_PROPERTY,\n String(rangeFraction(end, this.minValue, this.maxValue)),\n );\n }\n\n /** Clamps `raw` to `[min, max]` and snaps it to the nearest step from `min`. */\n #snap(raw: number): number {\n const clamped = Math.min(this.maxValue, Math.max(this.minValue, raw));\n if (this.stepValue <= 0) return clamped;\n const stepped =\n Math.round((clamped - this.minValue) / this.stepValue) * this.stepValue + this.minValue;\n return Math.min(this.maxValue, Math.max(this.minValue, stepped));\n }\n}\n\n/**\n * Decides which thumb yields when a move would cross the pair. The moving thumb\n * is the one whose requested value differs from its previous value; it stops at\n * the partner rather than dragging the partner along.\n */\nfunction isUserMovingStart(\n start: number,\n prevStart: number,\n end: number,\n prevEnd: number,\n): boolean {\n return start !== prevStart && end === prevEnd;\n}\n"]}
|
|
@@ -67,8 +67,11 @@ declare class RatingController extends Controller<HTMLElement> {
|
|
|
67
67
|
maxValue: number;
|
|
68
68
|
clearableValue: boolean;
|
|
69
69
|
readonlyValue: boolean;
|
|
70
|
-
/** Reflects the initial value, or switches to the non-interactive readonly view. */
|
|
71
70
|
connect(): void;
|
|
71
|
+
/** Closes the window in which a queued repaint may still run. */
|
|
72
|
+
disconnect(): void;
|
|
73
|
+
/** Repaints when application code (or a Turbo morph) changes `value` at runtime. */
|
|
74
|
+
valueValueChanged(): void;
|
|
72
75
|
/** Selects (or clears) the clicked symbol. Bound via `data-action` (click). */
|
|
73
76
|
select(event: Event): void;
|
|
74
77
|
/** Previews a fill range on hover/focus. Bound via `data-action` (mouseenter/focus). */
|
|
@@ -13,6 +13,39 @@ function isReservedArrowChord(event, allow = []) {
|
|
|
13
13
|
return event.altKey && !allow.includes("alt") || event.ctrlKey && !allow.includes("ctrl") || event.metaKey && !allow.includes("meta") || event.shiftKey && !allow.includes("shift");
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
+
// src/utils/microtask_coalescer.ts
|
|
17
|
+
var MicrotaskCoalescer = class {
|
|
18
|
+
#run;
|
|
19
|
+
#queued = false;
|
|
20
|
+
#active = false;
|
|
21
|
+
#generation = 0;
|
|
22
|
+
/** @param run - the single reconciliation pass, invoked at most once per batch. */
|
|
23
|
+
constructor(run) {
|
|
24
|
+
this.#run = run;
|
|
25
|
+
}
|
|
26
|
+
/** Opens the window in which {@link schedule} is honoured; call from `connect()`. */
|
|
27
|
+
activate() {
|
|
28
|
+
this.#active = true;
|
|
29
|
+
}
|
|
30
|
+
/** Closes the window and drops any pending pass; call from `disconnect()`. */
|
|
31
|
+
cancel() {
|
|
32
|
+
this.#active = false;
|
|
33
|
+
this.#queued = false;
|
|
34
|
+
this.#generation += 1;
|
|
35
|
+
}
|
|
36
|
+
/** Requests one pass after the batch settles. Idempotent; inert outside the window. */
|
|
37
|
+
schedule() {
|
|
38
|
+
if (!this.#active || this.#queued) return;
|
|
39
|
+
this.#queued = true;
|
|
40
|
+
const generation = this.#generation;
|
|
41
|
+
queueMicrotask(() => {
|
|
42
|
+
if (generation !== this.#generation || !this.#queued || !this.#active) return;
|
|
43
|
+
this.#queued = false;
|
|
44
|
+
this.#run();
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
|
|
16
49
|
// src/utils/roving_tabindex.ts
|
|
17
50
|
var RovingTabindex = class {
|
|
18
51
|
/** Returns the current ordered item elements; called on every operation. */
|
|
@@ -59,13 +92,33 @@ var RatingController = class extends Controller {
|
|
|
59
92
|
static events = ["change"];
|
|
60
93
|
#roving = new RovingTabindex(() => this.symbolTargets);
|
|
61
94
|
/** Reflects the initial value, or switches to the non-interactive readonly view. */
|
|
95
|
+
/**
|
|
96
|
+
* Collapses a morph that swaps render inputs into one repaint, and refuses the
|
|
97
|
+
* pass Stimulus delivers before `connect()`.
|
|
98
|
+
*/
|
|
99
|
+
#repaint = new MicrotaskCoalescer(() => {
|
|
100
|
+
if (this.readonlyValue) {
|
|
101
|
+
this.#applyReadonly();
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
this.#apply(this.#clamp(this.valueValue), { focus: false });
|
|
105
|
+
});
|
|
62
106
|
connect() {
|
|
107
|
+
this.#repaint.activate();
|
|
63
108
|
if (this.readonlyValue) {
|
|
64
109
|
this.#applyReadonly();
|
|
65
110
|
return;
|
|
66
111
|
}
|
|
67
112
|
this.#apply(this.#clamp(this.valueValue), { focus: false });
|
|
68
113
|
}
|
|
114
|
+
/** Closes the window in which a queued repaint may still run. */
|
|
115
|
+
disconnect() {
|
|
116
|
+
this.#repaint.cancel();
|
|
117
|
+
}
|
|
118
|
+
/** Repaints when application code (or a Turbo morph) changes `value` at runtime. */
|
|
119
|
+
valueValueChanged() {
|
|
120
|
+
this.#repaint.schedule();
|
|
121
|
+
}
|
|
69
122
|
/** Selects (or clears) the clicked symbol. Bound via `data-action` (click). */
|
|
70
123
|
select(event) {
|
|
71
124
|
if (this.readonlyValue) return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/logical_scroll.ts","../../src/utils/arrow_step.ts","../../src/utils/roving_tabindex.ts","../../src/controllers/rating_controller.ts"],"names":[],"mappings":";;;;;AAiBO,SAAS,MAAM,OAAA,EAA2B;AAC/C,EAAA,OAAO,MAAA,CAAO,gBAAA,CAAiB,OAAO,CAAA,CAAE,SAAA,KAAc,KAAA;AACxD;;;AC4EO,SAAS,oBAAA,CACd,KAAA,EACA,KAAA,GAAkC,EAAC,EAC1B;AACT,EAAA,IAAI,CAAC,KAAA,CAAM,GAAA,CAAI,UAAA,CAAW,OAAO,GAAG,OAAO,KAAA;AAC3C,EAAA,OACG,KAAA,CAAM,MAAA,IAAU,CAAC,KAAA,CAAM,QAAA,CAAS,KAAK,CAAA,IACrC,KAAA,CAAM,OAAA,IAAW,CAAC,KAAA,CAAM,QAAA,CAAS,MAAM,KACvC,KAAA,CAAM,OAAA,IAAW,CAAC,KAAA,CAAM,QAAA,CAAS,MAAM,CAAA,IACvC,KAAA,CAAM,QAAA,IAAY,CAAC,KAAA,CAAM,QAAA,CAAS,OAAO,CAAA;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UAAA,GAAa,KAAA;AAClB,IAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,MAAA,EAAQ,KAAK,CAAA;AACvC,IAAA,KAAA,MAAW,MAAA,IAAU,KAAK,aAAA,EAAe;AAGvC,MAAA,MAAA,CAAO,gBAAgB,MAAM,CAAA;AAC7B,MAAA,MAAA,CAAO,YAAA,CAAa,eAAe,MAAM,CAAA;AACzC,MAAA,MAAA,CAAO,QAAA,GAAW,EAAA;AAAA,IACpB;AACA,IAAA,IAAI,KAAK,cAAA,EAAgB,IAAA,CAAK,WAAA,CAAY,KAAA,GAAQ,OAAO,KAAK,CAAA;AAC9D,IAAA,IAAA,CAAK,cAAc,KAAK,CAAA;AAAA,EAC1B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,OAAO,KAAA,EAAuB;AAC5B,IAAA,MAAM,MAAM,IAAA,CAAK,GAAA,CAAI,KAAK,QAAA,EAAU,IAAA,CAAK,cAAc,MAAM,CAAA;AAC7D,IAAA,OAAO,IAAA,CAAK,IAAI,GAAA,EAAK,IAAA,CAAK,IAAI,IAAA,CAAK,SAAA,EAAW,KAAK,CAAC,CAAA;AAAA,EACtD;AAAA;AAAA,EAGA,IAAI,SAAA,GAAoB;AACtB,IAAA,OAAO,IAAA,CAAK,iBAAiB,CAAA,GAAI,CAAA;AAAA,EACnC;AAAA;AAAA,EAGA,aAAa,MAAA,EAA6B;AACxC,IAAA,MAAM,GAAA,GAAM,MAAA,CAAO,MAAA,CAAO,YAAA,CAAa,mBAAmB,CAAC,CAAA;AAC3D,IAAA,OAAO,MAAA,CAAO,QAAA,CAAS,GAAG,CAAA,IAAK,GAAA,GAAM,CAAA,GAAI,GAAA,GAAM,IAAA,CAAK,aAAA,CAAc,OAAA,CAAQ,MAAM,CAAA,GAAI,CAAA;AAAA,EACtF;AACF","file":"rating_controller.js","sourcesContent":["/** Normalized scroll position and maximum distance on one logical axis. */\nexport interface LogicalScrollMetrics {\n position: number;\n max: number;\n}\n\n/**\n * Whether horizontal scrolling on `element` follows right-to-left inline flow.\n *\n * Resolved from the **computed** `direction`, so the authoring contract is the\n * usual `dir=\"rtl\"` (or a stylesheet) on the element or any ancestor.\n *\n * Scope: horizontal writing modes. A vertical writing mode (`writing-mode:\n * vertical-rl`) also inverts the horizontal axis, which this check does not\n * model — vertical writing modes are out of scope for the scroll utilities\n * (their consumers describe axes as horizontal/vertical, not inline/block).\n */\nexport function isRtl(element: Element): boolean {\n return window.getComputedStyle(element).direction === \"rtl\";\n}\n\n/**\n * Returns scroll distance from the logical start edge.\n *\n * CSSOM View exposes standards-mode RTL horizontal offsets as `0` at the inline\n * start (right) and increasingly negative values toward the inline end (left).\n * The normalized position is always clamped to `[0, max]`, which also absorbs\n * Safari's elastic overscroll values.\n */\nexport function logicalScrollMetrics(\n element: HTMLElement,\n horizontal: boolean,\n): LogicalScrollMetrics {\n const max = Math.max(\n 0,\n horizontal\n ? element.scrollWidth - element.clientWidth\n : element.scrollHeight - element.clientHeight,\n );\n const raw = horizontal ? element.scrollLeft : element.scrollTop;\n const position = horizontal && isRtl(element) ? -raw : raw;\n return { position: Math.min(max, Math.max(0, position)), max };\n}\n\n/**\n * Converts a logical start/end delta to the physical value accepted by\n * `Element.scrollBy`.\n */\nexport function physicalScrollDelta(\n element: HTMLElement,\n horizontal: boolean,\n logicalDelta: number,\n): number {\n return horizontal && isRtl(element) ? -logicalDelta : logicalDelta;\n}\n","import { isRtl } from \"./logical_scroll\";\n\n/**\n * Turns an arrow key into a **logical** step: `+1` for \"next\", `-1` for\n * \"previous\", `0` when the key names neither.\n *\n * APG defines the horizontal pair as *next / previous* and says a vertical\n * arrangement swaps in Down/Up for the same meaning — so the pair is one axis's\n * spelling of an order, and the order reverses with the writing direction. Only\n * the horizontal pair reverses. Down/Up name an axis the writing direction does\n * not mirror, and returning them unchanged is the point: many controllers fold\n * both pairs into one branch, where swapping the branches under RTL would flip\n * the vertical axis too — a bug that reads as \"the arrows work\" until someone\n * presses Down.\n *\n * **Direction is read from the element the caller passes, which should be the\n * container that lays the items out** — not the focused child. A child may carry\n * its own `dir` (an LTR input inside an RTL form is ordinary authoring), and\n * probing per handler makes two handlers disagree at the boundary between them.\n *\n * This decides direction only. Whether the axis is even active (an\n * `orientation=\"horizontal\"` widget ignoring Down/Up), how far the step lands,\n * and what wrapping does all stay with the caller.\n *\n * **It encodes the list-order convention: `ArrowDown` is *next*.** Widgets that\n * pair the arrows by *value* instead — `ArrowUp` meaning \"more\", as a rating or a\n * slider does — must not use this, or their vertical axis inverts. Reverse the\n * horizontal pair on its own there.\n *\n * @example\n * ```ts\n * const step = logicalArrowStep(event.key, this.element);\n * if (step === 0) return;\n * this.#roving.setActive(rovingMove(current, length, step, \"wrap\"), { focus: true });\n * ```\n */\nexport function logicalArrowStep(key: string, element: Element): 1 | -1 | 0 {\n if (key === \"ArrowDown\") return 1;\n if (key === \"ArrowUp\") return -1;\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return 0;\n const forward = isRtl(element) ? \"ArrowLeft\" : \"ArrowRight\";\n return key === forward ? 1 : -1;\n}\n\n/**\n * Rewrites `key` so an existing LTR-shaped branch keeps working under RTL:\n * `ArrowRight` and `ArrowLeft` trade places, everything else passes through.\n *\n * The alternative — negating a delta — silently breaks handlers whose two\n * horizontal branches are **not mirror images**. A grid that clamps one edge but\n * not the other, or a segmented field guarding `index > 0` on one side and\n * `index < length - 1` on the other, ends up applying the wrong guard to the\n * wrong direction. Swapping the key leaves each branch, guards and all, exactly\n * where its author put it.\n *\n * Same rule as {@link logicalArrowStep} about which element to read: pass the\n * container that lays the items out, not the focused child.\n *\n * @example\n * ```ts\n * switch (logicalArrowKey(event.key, this.element)) {\n * case \"ArrowLeft\": // \"previous\" — whatever direction that is on screen\n * ```\n */\nexport function logicalArrowKey(key: string, element: Element): string {\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return key;\n if (!isRtl(element)) return key;\n return key === \"ArrowRight\" ? \"ArrowLeft\" : \"ArrowRight\";\n}\n\n/** Modifiers a widget may claim on an arrow key, named for the `allow` list. */\nexport type ArrowModifier = \"alt\" | \"ctrl\" | \"meta\" | \"shift\";\n\n/**\n * True when an arrow key arrived carrying a modifier the widget must leave to\n * the browser: return without calling `preventDefault()` and without moving any\n * state.\n *\n * A bare arrow belongs to the widget; a chorded one usually does not.\n * `Alt`/`Meta` plus a horizontal arrow is history back/forward on every desktop\n * browser, and a widget that swallows it makes the shortcut work or not\n * depending on where focus happens to sit — a coin-flip the user cannot see.\n *\n * `allow` is for the combinations APG assigns to a pattern **and the widget\n * actually implements** — today only Combobox's optional `Alt+Down`/`Alt+Up`.\n * Listing one the widget does not implement defeats the point: the chord then\n * runs the plain-arrow branch, which is exactly what this guard exists to stop.\n * Non-arrow keys return `false`, so chorded letters and\n * `Control+Home`/`Control+End` are untouched.\n *\n * @example\n * ```ts\n * if (isReservedArrowChord(event)) return;\n * ```\n */\nexport function isReservedArrowChord(\n event: KeyboardEvent,\n allow: readonly ArrowModifier[] = [],\n): boolean {\n if (!event.key.startsWith(\"Arrow\")) return false;\n return (\n (event.altKey && !allow.includes(\"alt\")) ||\n (event.ctrlKey && !allow.includes(\"ctrl\")) ||\n (event.metaKey && !allow.includes(\"meta\")) ||\n (event.shiftKey && !allow.includes(\"shift\"))\n );\n}\n","/**\n * Low-level roving-tabindex primitive shared by composite-widget controllers.\n *\n * The APG roving-tabindex pattern keeps a composite widget a single Tab stop:\n * exactly one item is in the Tab sequence (`tabindex=\"0\"`) while the rest are\n * removed from it (`tabindex=\"-1\"`), and the arrow keys move both DOM focus and\n * that single tabbable position together. {@link RovingTabindex} owns *only* that\n * mechanical bookkeeping — \"which one item is tabbable, and move focus there\".\n *\n * It is intentionally **policy-free**. Orientation, wrapping vs. clamping,\n * selection-follows-focus, typeahead, and `Home`/`End` semantics differ per APG\n * pattern (Radio Group, Toolbar, Rating, …); folding them into one helper would\n * flatten those widgets to a lowest common denominator and lose each pattern's\n * correctness. Those decisions therefore stay in each controller, which calls\n * {@link RovingTabindex.setActive} with an index it computed itself (optionally\n * via the pure {@link rovingMove} helper).\n *\n * @remarks\n * Items are read lazily through a getter so a controller can add or remove\n * targets (Stimulus re-scans the DOM) without re-wiring this helper.\n */\nexport class RovingTabindex {\n /** Returns the current ordered item elements; called on every operation. */\n readonly #getItems: () => HTMLElement[];\n\n /**\n * @param getItems - Returns the current ordered item elements. Called on every\n * operation so the live target list is always used.\n */\n constructor(getItems: () => HTMLElement[]) {\n this.#getItems = getItems;\n }\n\n /** Index of the currently tabbable item (`tabindex=\"0\"`), or `-1` if none. */\n get activeIndex(): number {\n return this.#getItems().findIndex((item) => item.tabIndex === 0);\n }\n\n /**\n * Makes exactly the item at `index` tabbable (`tabindex=\"0\"`) and removes every\n * other item from the Tab sequence (`tabindex=\"-1\"`). An out-of-range `index`\n * (e.g. `-1`) leaves all items at `-1`, which a controller can use to express\n * \"nothing is currently tabbable\".\n *\n * @param index - Position of the item to make tabbable.\n * @param options - Pass `{ focus: true }` to also move DOM focus to that item.\n */\n setActive(index: number, { focus = false }: { focus?: boolean } = {}): void {\n const items = this.#getItems();\n items.forEach((item, i) => {\n item.tabIndex = i === index ? 0 : -1;\n });\n if (focus) items[index]?.focus();\n }\n}\n\n/** Edge behavior for {@link rovingMove}: cycle past the ends, or stop at them. */\nexport type RovingWrap = \"wrap\" | \"clamp\";\n\n/**\n * Pure helper that resolves the target index for a one-step directional move.\n *\n * Keyboard/orientation mapping stays in the caller: it decides that a key means\n * `delta` `+1` (next) or `-1` (previous) and whether the widget should `\"wrap\"`\n * (Radio Group, Toolbar) or `\"clamp\"` at the ends.\n *\n * @param current - The index focus is moving from.\n * @param length - Number of items in the set.\n * @param delta - `+1` to move to the next item, `-1` for the previous.\n * @param wrap - `\"wrap\"` cycles around the ends; `\"clamp\"` stops at them.\n * @returns The resolved index, or `-1` when there are no items.\n */\nexport function rovingMove(\n current: number,\n length: number,\n delta: number,\n wrap: RovingWrap,\n): number {\n if (length === 0) return -1;\n const next = current + delta;\n if (wrap === \"wrap\") return (next + length) % length;\n return Math.min(length - 1, Math.max(0, next));\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { isReservedArrowChord } from \"../utils/arrow_step\";\nimport { isRtl } from \"../utils/logical_scroll\";\nimport { RovingTabindex } from \"../utils/roving_tabindex\";\n\n/**\n * Headless, accessible rating (star) behavior.\n *\n * Markup contract (identifier: `stimeo--rating`):\n * <div data-controller=\"stimeo--rating\" role=\"radiogroup\" aria-label=\"Rating\"\n * data-stimeo--rating-value-value=\"3\" data-stimeo--rating-max-value=\"5\">\n * <span role=\"radio\" aria-checked=\"false\" aria-label=\"1 star\" tabindex=\"-1\"\n * data-rating-value=\"1\" data-stimeo--rating-target=\"symbol\"\n * data-action=\"click->stimeo--rating#select\n * mouseenter->stimeo--rating#preview\n * mouseleave->stimeo--rating#endPreview\n * focus->stimeo--rating#preview\n * blur->stimeo--rating#endPreview\n * keydown->stimeo--rating#onKeydown\">★</span>\n * <!-- symbols 2..max; the selected one (or the first when unrated) tabindex=0 -->\n * <input type=\"hidden\" data-stimeo--rating-target=\"field\" />\n * </div>\n *\n * Implements the WAI-ARIA APG **Radio Group** pattern (an ordinal scale): exactly\n * one symbol is `aria-checked`. Unlike a generic radio group it deliberately does\n * **not** wrap — being ordinal, arrows clamp at the bounds.\n *\n * @remarks\n * Behavior only — symbols are styled by the consumer off `[aria-checked]` and the\n * `data-rating-hover` fill hook. In `readonly` mode the group becomes\n * `role=\"img\"`: because Stimeo never emits human-readable prose, the accessible\n * name (e.g. \"Rated 3 of 5\") is the consumer's `aria-label`/`aria-labelledby`.\n *\n * Behavior provided:\n * - Click selects a symbol; clicking the selected symbol clears to 0 when\n * `clearable`.\n * - `ArrowRight`/`ArrowUp` raise and `ArrowLeft`/`ArrowDown` lower the value\n * (clamped, down to 0 when `clearable`); `Home`/`End` jump to min/max;\n * `Space`/`Enter` select the focused symbol.\n * - Hover/focus previews a fill range via `data-rating-hover`; leaving restores\n * the selected range. `stimeo--rating:change` is dispatched on every change.\n */\nexport class RatingController extends Controller<HTMLElement> {\n static override targets = [\"symbol\", \"field\"];\n static override values = {\n value: { type: Number, default: 0 },\n max: { type: Number, default: 5 },\n clearable: { type: Boolean, default: true },\n readonly: { type: Boolean, default: false },\n };\n static actions = [\"endPreview\", \"onKeydown\", \"preview\", \"select\"] as const;\n static events = [\"change\"] as const;\n\n declare readonly symbolTargets: HTMLElement[];\n declare readonly fieldTarget: HTMLInputElement;\n declare readonly hasFieldTarget: boolean;\n declare valueValue: number;\n declare maxValue: number;\n declare clearableValue: boolean;\n declare readonlyValue: boolean;\n\n readonly #roving = new RovingTabindex(() => this.symbolTargets);\n\n /** Reflects the initial value, or switches to the non-interactive readonly view. */\n override connect(): void {\n if (this.readonlyValue) {\n this.#applyReadonly();\n return;\n }\n this.#apply(this.#clamp(this.valueValue), { focus: false });\n }\n\n /** Selects (or clears) the clicked symbol. Bound via `data-action` (click). */\n select(event: Event): void {\n if (this.readonlyValue) return;\n // Clamp the clicked value so a malformed data-rating-value can never push the\n // roving Tab stop out of range.\n const value = this.#clamp(this.#symbolValue(event.currentTarget as HTMLElement));\n if (this.clearableValue && value === this.valueValue) {\n // Clicking the selected symbol clears the rating; focus returns to the first.\n this.#render(0, { focus: true });\n } else {\n this.#render(value, { focus: false });\n }\n }\n\n /** Previews a fill range on hover/focus. Bound via `data-action` (mouseenter/focus). */\n preview(event: Event): void {\n if (this.readonlyValue) return;\n this.#setFillRange(this.#clamp(this.#symbolValue(event.currentTarget as HTMLElement)));\n }\n\n /** Restores the fill range to the selected value. Bound via `data-action` (mouseleave/blur). */\n endPreview(): void {\n if (this.readonlyValue) return;\n this.#setFillRange(this.valueValue);\n }\n\n /** Arrow/Home/End/Space keyboard control, clamped (no wrap). */\n onKeydown(event: KeyboardEvent): void {\n // A descendant widget that already claimed the key must not ALSO change the rating —\n // composition depends on this yield.\n if (event.defaultPrevented) return;\n if (isReservedArrowChord(event)) return;\n if (this.readonlyValue) return;\n let next: number | null = null;\n // Logical, not physical, for the horizontal pair only: the stars are an\n // ordered row, so which one is \"next\" follows the writing direction.\n //\n // The shared `logicalArrowStep` is deliberately not used here. It encodes the\n // list-order convention (`ArrowDown` = next), and this widget pairs the arrows\n // by *value* instead — `ArrowUp` means \"more\" — so borrowing it would silently\n // invert the vertical axis.\n const rtl = isRtl(this.element);\n switch (event.key) {\n case \"ArrowRight\":\n case \"ArrowUp\":\n next = this.valueValue + (event.key === \"ArrowRight\" && rtl ? -1 : 1);\n break;\n case \"ArrowLeft\":\n case \"ArrowDown\":\n next = this.valueValue - (event.key === \"ArrowLeft\" && rtl ? -1 : 1);\n break;\n case \"Home\":\n next = this.#minValue;\n break;\n case \"End\":\n next = this.maxValue;\n break;\n case \" \":\n case \"Enter\":\n next = this.#symbolValue(event.currentTarget as HTMLElement);\n break;\n default:\n return;\n }\n event.preventDefault();\n this.#render(this.#clamp(next), { focus: true });\n }\n\n /**\n * Applies `value` (already clamped) everywhere, then dispatches `change`.\n * Use for user-driven changes; on connect call `#apply` directly so\n * initialization mirrors state without emitting an event.\n */\n #render(value: number, { focus }: { focus: boolean }): void {\n this.#apply(value, { focus });\n this.dispatch(\"change\", { detail: { value } });\n }\n\n /**\n * Stores `value`, syncs `aria-checked` and the roving Tab stop, the hidden\n * field, and the fill range — without dispatching `change`. Idempotent and\n * safe on connect (and across Turbo morphing).\n */\n #apply(value: number, { focus }: { focus: boolean }): void {\n this.valueValue = value;\n this.symbolTargets.forEach((symbol) => {\n symbol.setAttribute(\n \"aria-checked\",\n value > 0 && this.#symbolValue(symbol) === value ? \"true\" : \"false\",\n );\n });\n // The selected symbol is the Tab stop; when unrated, the first symbol is.\n this.#roving.setActive(value > 0 ? value - 1 : 0, { focus });\n if (this.hasFieldTarget) this.fieldTarget.value = String(value);\n this.#setFillRange(value);\n }\n\n /** Marks symbols up to `range` with `data-rating-hover` (the consumer's fill hook). */\n #setFillRange(range: number): void {\n for (const symbol of this.symbolTargets) {\n if (this.#symbolValue(symbol) <= range && range > 0) {\n symbol.setAttribute(\"data-rating-hover\", \"\");\n } else {\n symbol.removeAttribute(\"data-rating-hover\");\n }\n }\n }\n\n /** Turns the group into a non-interactive `role=\"img\"` snapshot of the value. */\n #applyReadonly(): void {\n const value = this.#clamp(this.valueValue);\n this.valueValue = value;\n this.element.setAttribute(\"role\", \"img\");\n for (const symbol of this.symbolTargets) {\n // Drop the interactive radio role so the img has no nested interactive\n // descendants; aria-hidden removes them from the tree entirely.\n symbol.removeAttribute(\"role\");\n symbol.setAttribute(\"aria-hidden\", \"true\");\n symbol.tabIndex = -1;\n }\n if (this.hasFieldTarget) this.fieldTarget.value = String(value);\n this.#setFillRange(value);\n }\n\n /**\n * Clamps `value` to `[min, max]` (min is 0 when clearable, else 1). The upper\n * bound is also capped at the number of symbols so the roving Tab stop\n * (`value - 1`) always maps to a real symbol — even if the consumer's `max`\n * value and rendered symbol count disagree, the tabbable item is never lost.\n */\n #clamp(value: number): number {\n const max = Math.min(this.maxValue, this.symbolTargets.length);\n return Math.min(max, Math.max(this.#minValue, value));\n }\n\n /** Lowest selectable value: 0 when clearable, otherwise 1. */\n get #minValue(): number {\n return this.clearableValue ? 0 : 1;\n }\n\n /** A symbol's ordinal value (`data-rating-value`, defaulting to its position). */\n #symbolValue(symbol: HTMLElement): number {\n const raw = Number(symbol.getAttribute(\"data-rating-value\"));\n return Number.isFinite(raw) && raw > 0 ? raw : this.symbolTargets.indexOf(symbol) + 1;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/logical_scroll.ts","../../src/utils/arrow_step.ts","../../src/utils/microtask_coalescer.ts","../../src/utils/roving_tabindex.ts","../../src/controllers/rating_controller.ts"],"names":[],"mappings":";;;;;AAiBO,SAAS,MAAM,OAAA,EAA2B;AAC/C,EAAA,OAAO,MAAA,CAAO,gBAAA,CAAiB,OAAO,CAAA,CAAE,SAAA,KAAc,KAAA;AACxD;;;AC4EO,SAAS,oBAAA,CACd,KAAA,EACA,KAAA,GA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A,OAAO,IAAA,CAAK,IAAI,GAAA,EAAK,IAAA,CAAK,IAAI,IAAA,CAAK,SAAA,EAAW,KAAK,CAAC,CAAA;AAAA,EACtD;AAAA;AAAA,EAGA,IAAI,SAAA,GAAoB;AACtB,IAAA,OAAO,IAAA,CAAK,iBAAiB,CAAA,GAAI,CAAA;AAAA,EACnC;AAAA;AAAA,EAGA,aAAa,MAAA,EAA6B;AACxC,IAAA,MAAM,GAAA,GAAM,MAAA,CAAO,MAAA,CAAO,YAAA,CAAa,mBAAmB,CAAC,CAAA;AAC3D,IAAA,OAAO,MAAA,CAAO,QAAA,CAAS,GAAG,CAAA,IAAK,GAAA,GAAM,CAAA,GAAI,GAAA,GAAM,IAAA,CAAK,aAAA,CAAc,OAAA,CAAQ,MAAM,CAAA,GAAI,CAAA;AAAA,EACtF;AACF","file":"rating_controller.js","sourcesContent":["/** Normalized scroll position and maximum distance on one logical axis. */\nexport interface LogicalScrollMetrics {\n position: number;\n max: number;\n}\n\n/**\n * Whether horizontal scrolling on `element` follows right-to-left inline flow.\n *\n * Resolved from the **computed** `direction`, so the authoring contract is the\n * usual `dir=\"rtl\"` (or a stylesheet) on the element or any ancestor.\n *\n * Scope: horizontal writing modes. A vertical writing mode (`writing-mode:\n * vertical-rl`) also inverts the horizontal axis, which this check does not\n * model — vertical writing modes are out of scope for the scroll utilities\n * (their consumers describe axes as horizontal/vertical, not inline/block).\n */\nexport function isRtl(element: Element): boolean {\n return window.getComputedStyle(element).direction === \"rtl\";\n}\n\n/**\n * Returns scroll distance from the logical start edge.\n *\n * CSSOM View exposes standards-mode RTL horizontal offsets as `0` at the inline\n * start (right) and increasingly negative values toward the inline end (left).\n * The normalized position is always clamped to `[0, max]`, which also absorbs\n * Safari's elastic overscroll values.\n */\nexport function logicalScrollMetrics(\n element: HTMLElement,\n horizontal: boolean,\n): LogicalScrollMetrics {\n const max = Math.max(\n 0,\n horizontal\n ? element.scrollWidth - element.clientWidth\n : element.scrollHeight - element.clientHeight,\n );\n const raw = horizontal ? element.scrollLeft : element.scrollTop;\n const position = horizontal && isRtl(element) ? -raw : raw;\n return { position: Math.min(max, Math.max(0, position)), max };\n}\n\n/**\n * Converts a logical start/end delta to the physical value accepted by\n * `Element.scrollBy`.\n */\nexport function physicalScrollDelta(\n element: HTMLElement,\n horizontal: boolean,\n logicalDelta: number,\n): number {\n return horizontal && isRtl(element) ? -logicalDelta : logicalDelta;\n}\n","import { isRtl } from \"./logical_scroll\";\n\n/**\n * Turns an arrow key into a **logical** step: `+1` for \"next\", `-1` for\n * \"previous\", `0` when the key names neither.\n *\n * APG defines the horizontal pair as *next / previous* and says a vertical\n * arrangement swaps in Down/Up for the same meaning — so the pair is one axis's\n * spelling of an order, and the order reverses with the writing direction. Only\n * the horizontal pair reverses. Down/Up name an axis the writing direction does\n * not mirror, and returning them unchanged is the point: many controllers fold\n * both pairs into one branch, where swapping the branches under RTL would flip\n * the vertical axis too — a bug that reads as \"the arrows work\" until someone\n * presses Down.\n *\n * **Direction is read from the element the caller passes, which should be the\n * container that lays the items out** — not the focused child. A child may carry\n * its own `dir` (an LTR input inside an RTL form is ordinary authoring), and\n * probing per handler makes two handlers disagree at the boundary between them.\n *\n * This decides direction only. Whether the axis is even active (an\n * `orientation=\"horizontal\"` widget ignoring Down/Up), how far the step lands,\n * and what wrapping does all stay with the caller.\n *\n * **It encodes the list-order convention: `ArrowDown` is *next*.** Widgets that\n * pair the arrows by *value* instead — `ArrowUp` meaning \"more\", as a rating or a\n * slider does — must not use this, or their vertical axis inverts. Reverse the\n * horizontal pair on its own there.\n *\n * @example\n * ```ts\n * const step = logicalArrowStep(event.key, this.element);\n * if (step === 0) return;\n * this.#roving.setActive(rovingMove(current, length, step, \"wrap\"), { focus: true });\n * ```\n */\nexport function logicalArrowStep(key: string, element: Element): 1 | -1 | 0 {\n if (key === \"ArrowDown\") return 1;\n if (key === \"ArrowUp\") return -1;\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return 0;\n const forward = isRtl(element) ? \"ArrowLeft\" : \"ArrowRight\";\n return key === forward ? 1 : -1;\n}\n\n/**\n * Rewrites `key` so an existing LTR-shaped branch keeps working under RTL:\n * `ArrowRight` and `ArrowLeft` trade places, everything else passes through.\n *\n * The alternative — negating a delta — silently breaks handlers whose two\n * horizontal branches are **not mirror images**. A grid that clamps one edge but\n * not the other, or a segmented field guarding `index > 0` on one side and\n * `index < length - 1` on the other, ends up applying the wrong guard to the\n * wrong direction. Swapping the key leaves each branch, guards and all, exactly\n * where its author put it.\n *\n * Same rule as {@link logicalArrowStep} about which element to read: pass the\n * container that lays the items out, not the focused child.\n *\n * @example\n * ```ts\n * switch (logicalArrowKey(event.key, this.element)) {\n * case \"ArrowLeft\": // \"previous\" — whatever direction that is on screen\n * ```\n */\nexport function logicalArrowKey(key: string, element: Element): string {\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return key;\n if (!isRtl(element)) return key;\n return key === \"ArrowRight\" ? \"ArrowLeft\" : \"ArrowRight\";\n}\n\n/** Modifiers a widget may claim on an arrow key, named for the `allow` list. */\nexport type ArrowModifier = \"alt\" | \"ctrl\" | \"meta\" | \"shift\";\n\n/**\n * True when an arrow key arrived carrying a modifier the widget must leave to\n * the browser: return without calling `preventDefault()` and without moving any\n * state.\n *\n * A bare arrow belongs to the widget; a chorded one usually does not.\n * `Alt`/`Meta` plus a horizontal arrow is history back/forward on every desktop\n * browser, and a widget that swallows it makes the shortcut work or not\n * depending on where focus happens to sit — a coin-flip the user cannot see.\n *\n * `allow` is for the combinations APG assigns to a pattern **and the widget\n * actually implements** — today only Combobox's optional `Alt+Down`/`Alt+Up`.\n * Listing one the widget does not implement defeats the point: the chord then\n * runs the plain-arrow branch, which is exactly what this guard exists to stop.\n * Non-arrow keys return `false`, so chorded letters and\n * `Control+Home`/`Control+End` are untouched.\n *\n * @example\n * ```ts\n * if (isReservedArrowChord(event)) return;\n * ```\n */\nexport function isReservedArrowChord(\n event: KeyboardEvent,\n allow: readonly ArrowModifier[] = [],\n): boolean {\n if (!event.key.startsWith(\"Arrow\")) return false;\n return (\n (event.altKey && !allow.includes(\"alt\")) ||\n (event.ctrlKey && !allow.includes(\"ctrl\")) ||\n (event.metaKey && !allow.includes(\"meta\")) ||\n (event.shiftKey && !allow.includes(\"shift\"))\n );\n}\n","/**\n * Collapses many target callbacks from one DOM mutation into a single pass.\n *\n * Stimulus fires `<name>TargetConnected` / `Disconnected` once per element, so\n * replacing a list of N options delivers N callbacks — but the useful unit of\n * work is \"reconcile against the DOM that resulted\", once, after the batch has\n * settled. Every controller that owns a reconcilable target set needs the same\n * shape: a `queued` flag plus `queueMicrotask`.\n *\n * **A microtask is the right horizon, and the reason is specific.** Stimulus\n * drives these callbacks from a `MutationObserver`, whose own callback already\n * runs as a microtask with the whole batch in hand; scheduling one more lands\n * after the last sibling callback of that batch and still before paint or any\n * event handler. A timer would be later than it needs to be, and reconciling\n * synchronously would run once per element against a half-applied DOM.\n *\n * **The two guards are not the same guard.** Scheduling is refused before the\n * controller connects, and running is refused after it disconnects:\n *\n * - **Before `connect()`** — Stimulus delivers the *initial* target callbacks\n * ahead of `connect()`. Reconciling there would compute a fallback against a\n * controller whose own state has not been initialised, and `connect()` is\n * about to do a full pass anyway.\n * - **After `disconnect()`** — Stimulus fires a callback for **every** target\n * during teardown, and a microtask queued just before it would otherwise run\n * against a detached tree. {@link MicrotaskCoalescer.cancel} exists for the\n * teardown path to drop the pending pass outright.\n *\n * Both guards are part of one contract here rather than something each consumer\n * has to remember separately.\n *\n * Scope is the scheduling only. *What* to reconcile — keep the surviving active\n * option, fall back to the next / previous / first visible one, rebuild derived\n * chips or hidden fields — stays in the controller, because no two consumers\n * answer it the same way.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileOptions());\n *\n * connect() { this.#reconcile.activate(); }\n * disconnect() { this.#reconcile.cancel(); }\n *\n * optionTargetConnected() { this.#reconcile.schedule(); }\n * optionTargetDisconnected() { this.#reconcile.schedule(); }\n * ```\n */\nexport class MicrotaskCoalescer {\n readonly #run: () => void;\n #queued = false;\n #active = false;\n #generation = 0;\n\n /** @param run - the single reconciliation pass, invoked at most once per batch. */\n constructor(run: () => void) {\n this.#run = run;\n }\n\n /** Opens the window in which {@link schedule} is honoured; call from `connect()`. */\n activate(): void {\n this.#active = true;\n }\n\n /** Closes the window and drops any pending pass; call from `disconnect()`. */\n cancel(): void {\n this.#active = false;\n this.#queued = false;\n this.#generation += 1;\n }\n\n /** Requests one pass after the batch settles. Idempotent; inert outside the window. */\n schedule(): void {\n if (!this.#active || this.#queued) return;\n this.#queued = true;\n const generation = this.#generation;\n queueMicrotask(() => {\n // A cancelled callback must not consume a pass queued after reconnect.\n if (generation !== this.#generation || !this.#queued || !this.#active) return;\n this.#queued = false;\n this.#run();\n });\n }\n}\n","/**\n * Low-level roving-tabindex primitive shared by composite-widget controllers.\n *\n * The APG roving-tabindex pattern keeps a composite widget a single Tab stop:\n * exactly one item is in the Tab sequence (`tabindex=\"0\"`) while the rest are\n * removed from it (`tabindex=\"-1\"`), and the arrow keys move both DOM focus and\n * that single tabbable position together. {@link RovingTabindex} owns *only* that\n * mechanical bookkeeping — \"which one item is tabbable, and move focus there\".\n *\n * It is intentionally **policy-free**. Orientation, wrapping vs. clamping,\n * selection-follows-focus, typeahead, and `Home`/`End` semantics differ per APG\n * pattern (Radio Group, Toolbar, Rating, …); folding them into one helper would\n * flatten those widgets to a lowest common denominator and lose each pattern's\n * correctness. Those decisions therefore stay in each controller, which calls\n * {@link RovingTabindex.setActive} with an index it computed itself (optionally\n * via the pure {@link rovingMove} helper).\n *\n * @remarks\n * Items are read lazily through a getter so a controller can add or remove\n * targets (Stimulus re-scans the DOM) without re-wiring this helper.\n */\nexport class RovingTabindex {\n /** Returns the current ordered item elements; called on every operation. */\n readonly #getItems: () => HTMLElement[];\n\n /**\n * @param getItems - Returns the current ordered item elements. Called on every\n * operation so the live target list is always used.\n */\n constructor(getItems: () => HTMLElement[]) {\n this.#getItems = getItems;\n }\n\n /** Index of the currently tabbable item (`tabindex=\"0\"`), or `-1` if none. */\n get activeIndex(): number {\n return this.#getItems().findIndex((item) => item.tabIndex === 0);\n }\n\n /**\n * Makes exactly the item at `index` tabbable (`tabindex=\"0\"`) and removes every\n * other item from the Tab sequence (`tabindex=\"-1\"`). An out-of-range `index`\n * (e.g. `-1`) leaves all items at `-1`, which a controller can use to express\n * \"nothing is currently tabbable\".\n *\n * @param index - Position of the item to make tabbable.\n * @param options - Pass `{ focus: true }` to also move DOM focus to that item.\n */\n setActive(index: number, { focus = false }: { focus?: boolean } = {}): void {\n const items = this.#getItems();\n items.forEach((item, i) => {\n item.tabIndex = i === index ? 0 : -1;\n });\n if (focus) items[index]?.focus();\n }\n}\n\n/** Edge behavior for {@link rovingMove}: cycle past the ends, or stop at them. */\nexport type RovingWrap = \"wrap\" | \"clamp\";\n\n/**\n * Pure helper that resolves the target index for a one-step directional move.\n *\n * Keyboard/orientation mapping stays in the caller: it decides that a key means\n * `delta` `+1` (next) or `-1` (previous) and whether the widget should `\"wrap\"`\n * (Radio Group, Toolbar) or `\"clamp\"` at the ends.\n *\n * @param current - The index focus is moving from.\n * @param length - Number of items in the set.\n * @param delta - `+1` to move to the next item, `-1` for the previous.\n * @param wrap - `\"wrap\"` cycles around the ends; `\"clamp\"` stops at them.\n * @returns The resolved index, or `-1` when there are no items.\n */\nexport function rovingMove(\n current: number,\n length: number,\n delta: number,\n wrap: RovingWrap,\n): number {\n if (length === 0) return -1;\n const next = current + delta;\n if (wrap === \"wrap\") return (next + length) % length;\n return Math.min(length - 1, Math.max(0, next));\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { isReservedArrowChord } from \"../utils/arrow_step\";\nimport { isRtl } from \"../utils/logical_scroll\";\nimport { MicrotaskCoalescer } from \"../utils/microtask_coalescer\";\nimport { RovingTabindex } from \"../utils/roving_tabindex\";\n\n/**\n * Headless, accessible rating (star) behavior.\n *\n * Markup contract (identifier: `stimeo--rating`):\n * <div data-controller=\"stimeo--rating\" role=\"radiogroup\" aria-label=\"Rating\"\n * data-stimeo--rating-value-value=\"3\" data-stimeo--rating-max-value=\"5\">\n * <span role=\"radio\" aria-checked=\"false\" aria-label=\"1 star\" tabindex=\"-1\"\n * data-rating-value=\"1\" data-stimeo--rating-target=\"symbol\"\n * data-action=\"click->stimeo--rating#select\n * mouseenter->stimeo--rating#preview\n * mouseleave->stimeo--rating#endPreview\n * focus->stimeo--rating#preview\n * blur->stimeo--rating#endPreview\n * keydown->stimeo--rating#onKeydown\">★</span>\n * <!-- symbols 2..max; the selected one (or the first when unrated) tabindex=0 -->\n * <input type=\"hidden\" data-stimeo--rating-target=\"field\" />\n * </div>\n *\n * Implements the WAI-ARIA APG **Radio Group** pattern (an ordinal scale): exactly\n * one symbol is `aria-checked`. Unlike a generic radio group it deliberately does\n * **not** wrap — being ordinal, arrows clamp at the bounds.\n *\n * @remarks\n * Behavior only — symbols are styled by the consumer off `[aria-checked]` and the\n * `data-rating-hover` fill hook. In `readonly` mode the group becomes\n * `role=\"img\"`: because Stimeo never emits human-readable prose, the accessible\n * name (e.g. \"Rated 3 of 5\") is the consumer's `aria-label`/`aria-labelledby`.\n *\n * Behavior provided:\n * - Click selects a symbol; clicking the selected symbol clears to 0 when\n * `clearable`.\n * - `ArrowRight`/`ArrowUp` raise and `ArrowLeft`/`ArrowDown` lower the value\n * (clamped, down to 0 when `clearable`); `Home`/`End` jump to min/max;\n * `Space`/`Enter` select the focused symbol.\n * - Hover/focus previews a fill range via `data-rating-hover`; leaving restores\n * the selected range. `stimeo--rating:change` is dispatched on every change.\n */\nexport class RatingController extends Controller<HTMLElement> {\n static override targets = [\"symbol\", \"field\"];\n static override values = {\n value: { type: Number, default: 0 },\n max: { type: Number, default: 5 },\n clearable: { type: Boolean, default: true },\n readonly: { type: Boolean, default: false },\n };\n static actions = [\"endPreview\", \"onKeydown\", \"preview\", \"select\"] as const;\n static events = [\"change\"] as const;\n\n declare readonly symbolTargets: HTMLElement[];\n declare readonly fieldTarget: HTMLInputElement;\n declare readonly hasFieldTarget: boolean;\n declare valueValue: number;\n declare maxValue: number;\n declare clearableValue: boolean;\n declare readonlyValue: boolean;\n\n readonly #roving = new RovingTabindex(() => this.symbolTargets);\n\n /** Reflects the initial value, or switches to the non-interactive readonly view. */\n /**\n * Collapses a morph that swaps render inputs into one repaint, and refuses the\n * pass Stimulus delivers before `connect()`.\n */\n readonly #repaint = new MicrotaskCoalescer(() => {\n if (this.readonlyValue) {\n this.#applyReadonly();\n return;\n }\n this.#apply(this.#clamp(this.valueValue), { focus: false });\n });\n\n override connect(): void {\n this.#repaint.activate();\n if (this.readonlyValue) {\n this.#applyReadonly();\n return;\n }\n this.#apply(this.#clamp(this.valueValue), { focus: false });\n }\n\n /** Closes the window in which a queued repaint may still run. */\n override disconnect(): void {\n this.#repaint.cancel();\n }\n\n /** Repaints when application code (or a Turbo morph) changes `value` at runtime. */\n valueValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /** Selects (or clears) the clicked symbol. Bound via `data-action` (click). */\n select(event: Event): void {\n if (this.readonlyValue) return;\n // Clamp the clicked value so a malformed data-rating-value can never push the\n // roving Tab stop out of range.\n const value = this.#clamp(this.#symbolValue(event.currentTarget as HTMLElement));\n if (this.clearableValue && value === this.valueValue) {\n // Clicking the selected symbol clears the rating; focus returns to the first.\n this.#render(0, { focus: true });\n } else {\n this.#render(value, { focus: false });\n }\n }\n\n /** Previews a fill range on hover/focus. Bound via `data-action` (mouseenter/focus). */\n preview(event: Event): void {\n if (this.readonlyValue) return;\n this.#setFillRange(this.#clamp(this.#symbolValue(event.currentTarget as HTMLElement)));\n }\n\n /** Restores the fill range to the selected value. Bound via `data-action` (mouseleave/blur). */\n endPreview(): void {\n if (this.readonlyValue) return;\n this.#setFillRange(this.valueValue);\n }\n\n /** Arrow/Home/End/Space keyboard control, clamped (no wrap). */\n onKeydown(event: KeyboardEvent): void {\n // A descendant widget that already claimed the key must not ALSO change the rating —\n // composition depends on this yield.\n if (event.defaultPrevented) return;\n if (isReservedArrowChord(event)) return;\n if (this.readonlyValue) return;\n let next: number | null = null;\n // Logical, not physical, for the horizontal pair only: the stars are an\n // ordered row, so which one is \"next\" follows the writing direction.\n //\n // The shared `logicalArrowStep` is deliberately not used here. It encodes the\n // list-order convention (`ArrowDown` = next), and this widget pairs the arrows\n // by *value* instead — `ArrowUp` means \"more\" — so borrowing it would silently\n // invert the vertical axis.\n const rtl = isRtl(this.element);\n switch (event.key) {\n case \"ArrowRight\":\n case \"ArrowUp\":\n next = this.valueValue + (event.key === \"ArrowRight\" && rtl ? -1 : 1);\n break;\n case \"ArrowLeft\":\n case \"ArrowDown\":\n next = this.valueValue - (event.key === \"ArrowLeft\" && rtl ? -1 : 1);\n break;\n case \"Home\":\n next = this.#minValue;\n break;\n case \"End\":\n next = this.maxValue;\n break;\n case \" \":\n case \"Enter\":\n next = this.#symbolValue(event.currentTarget as HTMLElement);\n break;\n default:\n return;\n }\n event.preventDefault();\n this.#render(this.#clamp(next), { focus: true });\n }\n\n /**\n * Applies `value` (already clamped) everywhere, then dispatches `change`.\n * Use for user-driven changes; on connect call `#apply` directly so\n * initialization mirrors state without emitting an event.\n */\n #render(value: number, { focus }: { focus: boolean }): void {\n this.#apply(value, { focus });\n this.dispatch(\"change\", { detail: { value } });\n }\n\n /**\n * Stores `value`, syncs `aria-checked` and the roving Tab stop, the hidden\n * field, and the fill range — without dispatching `change`. Idempotent and\n * safe on connect (and across Turbo morphing).\n */\n #apply(value: number, { focus }: { focus: boolean }): void {\n this.valueValue = value;\n this.symbolTargets.forEach((symbol) => {\n symbol.setAttribute(\n \"aria-checked\",\n value > 0 && this.#symbolValue(symbol) === value ? \"true\" : \"false\",\n );\n });\n // The selected symbol is the Tab stop; when unrated, the first symbol is.\n this.#roving.setActive(value > 0 ? value - 1 : 0, { focus });\n if (this.hasFieldTarget) this.fieldTarget.value = String(value);\n this.#setFillRange(value);\n }\n\n /** Marks symbols up to `range` with `data-rating-hover` (the consumer's fill hook). */\n #setFillRange(range: number): void {\n for (const symbol of this.symbolTargets) {\n if (this.#symbolValue(symbol) <= range && range > 0) {\n symbol.setAttribute(\"data-rating-hover\", \"\");\n } else {\n symbol.removeAttribute(\"data-rating-hover\");\n }\n }\n }\n\n /** Turns the group into a non-interactive `role=\"img\"` snapshot of the value. */\n #applyReadonly(): void {\n const value = this.#clamp(this.valueValue);\n this.valueValue = value;\n this.element.setAttribute(\"role\", \"img\");\n for (const symbol of this.symbolTargets) {\n // Drop the interactive radio role so the img has no nested interactive\n // descendants; aria-hidden removes them from the tree entirely.\n symbol.removeAttribute(\"role\");\n symbol.setAttribute(\"aria-hidden\", \"true\");\n symbol.tabIndex = -1;\n }\n if (this.hasFieldTarget) this.fieldTarget.value = String(value);\n this.#setFillRange(value);\n }\n\n /**\n * Clamps `value` to `[min, max]` (min is 0 when clearable, else 1). The upper\n * bound is also capped at the number of symbols so the roving Tab stop\n * (`value - 1`) always maps to a real symbol — even if the consumer's `max`\n * value and rendered symbol count disagree, the tabbable item is never lost.\n */\n #clamp(value: number): number {\n const max = Math.min(this.maxValue, this.symbolTargets.length);\n return Math.min(max, Math.max(this.#minValue, value));\n }\n\n /** Lowest selectable value: 0 when clearable, otherwise 1. */\n get #minValue(): number {\n return this.clearableValue ? 0 : 1;\n }\n\n /** A symbol's ordinal value (`data-rating-value`, defaulting to its position). */\n #symbolValue(symbol: HTMLElement): number {\n const raw = Number(symbol.getAttribute(\"data-rating-value\"));\n return Number.isFinite(raw) && raw > 0 ? raw : this.symbolTargets.indexOf(symbol) + 1;\n }\n}\n"]}
|
|
@@ -21,6 +21,13 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
21
21
|
* a live region (silent updates, no announcement interruptions). The polling
|
|
22
22
|
* timer is owned by {@link SafeTimeout} and torn down on `disconnect()` (Turbo
|
|
23
23
|
* navigation included).
|
|
24
|
+
*
|
|
25
|
+
* Render inputs are followed at runtime: a morph that swaps `locale`, `threshold`,
|
|
26
|
+
* or `tickInterval` on the live element repaints through one coalesced pass
|
|
27
|
+
* ({@link MicrotaskCoalescer}) rather than leaving the reading frozen. The authored
|
|
28
|
+
* absolute text goes back on the element via {@link BeforeCacheReset} before Turbo
|
|
29
|
+
* caches the page — a snapshot taken mid-render would carry the relative form
|
|
30
|
+
* alone, and that is a form `connect()` must not adopt as the fallback.
|
|
24
31
|
*/
|
|
25
32
|
declare class RelativeTimeController extends Controller<HTMLElement> {
|
|
26
33
|
#private;
|
|
@@ -43,6 +50,12 @@ declare class RelativeTimeController extends Controller<HTMLElement> {
|
|
|
43
50
|
tickIntervalValue: number;
|
|
44
51
|
connect(): void;
|
|
45
52
|
disconnect(): void;
|
|
53
|
+
/** Repaints when application code (or a Turbo morph) changes `locale` at runtime. */
|
|
54
|
+
localeValueChanged(): void;
|
|
55
|
+
/** Repaints when application code (or a Turbo morph) changes `threshold` at runtime. */
|
|
56
|
+
thresholdValueChanged(): void;
|
|
57
|
+
/** Repaints when application code (or a Turbo morph) changes `tickInterval` at runtime. */
|
|
58
|
+
tickIntervalValueChanged(): void;
|
|
46
59
|
}
|
|
47
60
|
|
|
48
61
|
export { RelativeTimeController };
|