stimeo-ui 0.5.0 → 0.7.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 +178 -0
- package/dist/controllers/alert_dialog_controller.d.ts +2 -0
- package/dist/controllers/alert_dialog_controller.js +75 -4
- package/dist/controllers/alert_dialog_controller.js.map +1 -1
- package/dist/controllers/aspect_ratio_controller.d.ts +1 -3
- package/dist/controllers/aspect_ratio_controller.js +19 -11
- package/dist/controllers/aspect_ratio_controller.js.map +1 -1
- package/dist/controllers/auto_submit_controller.d.ts +2 -0
- package/dist/controllers/auto_submit_controller.js.map +1 -1
- package/dist/controllers/avatar_controller.d.ts +36 -15
- package/dist/controllers/avatar_controller.js +237 -40
- package/dist/controllers/avatar_controller.js.map +1 -1
- package/dist/controllers/breadcrumb_controller.d.ts +2 -0
- package/dist/controllers/breadcrumb_controller.js.map +1 -1
- package/dist/controllers/bulk_select_controller.d.ts +2 -0
- package/dist/controllers/bulk_select_controller.js.map +1 -1
- package/dist/controllers/calendar_controller.d.ts +2 -0
- package/dist/controllers/calendar_controller.js.map +1 -1
- package/dist/controllers/carousel_controller.d.ts +12 -3
- package/dist/controllers/carousel_controller.js +85 -9
- package/dist/controllers/carousel_controller.js.map +1 -1
- package/dist/controllers/character_counter_controller.d.ts +52 -20
- package/dist/controllers/character_counter_controller.js +338 -63
- package/dist/controllers/character_counter_controller.js.map +1 -1
- package/dist/controllers/checkbox_controller.d.ts +34 -5
- package/dist/controllers/checkbox_controller.js +136 -25
- package/dist/controllers/checkbox_controller.js.map +1 -1
- package/dist/controllers/color_picker_controller.d.ts +10 -1
- package/dist/controllers/color_picker_controller.js +35 -9
- package/dist/controllers/color_picker_controller.js.map +1 -1
- package/dist/controllers/combobox_controller.d.ts +2 -0
- package/dist/controllers/combobox_controller.js.map +1 -1
- package/dist/controllers/command_palette_controller.d.ts +2 -0
- package/dist/controllers/command_palette_controller.js +75 -4
- package/dist/controllers/command_palette_controller.js.map +1 -1
- package/dist/controllers/conditional_fields_controller.d.ts +42 -14
- package/dist/controllers/conditional_fields_controller.js +345 -51
- package/dist/controllers/conditional_fields_controller.js.map +1 -1
- package/dist/controllers/confirm_controller.d.ts +2 -0
- package/dist/controllers/confirm_controller.js +75 -4
- package/dist/controllers/confirm_controller.js.map +1 -1
- package/dist/controllers/count_up_controller.d.ts +2 -0
- package/dist/controllers/count_up_controller.js.map +1 -1
- package/dist/controllers/countdown_controller.d.ts +4 -0
- package/dist/controllers/countdown_controller.js.map +1 -1
- package/dist/controllers/currency_input_controller.d.ts +2 -0
- package/dist/controllers/currency_input_controller.js.map +1 -1
- package/dist/controllers/data_grid_controller.d.ts +3 -0
- package/dist/controllers/data_grid_controller.js.map +1 -1
- package/dist/controllers/date_range_picker_controller.d.ts +23 -4
- package/dist/controllers/date_range_picker_controller.js +157 -30
- package/dist/controllers/date_range_picker_controller.js.map +1 -1
- package/dist/controllers/dialog_controller.js +75 -4
- package/dist/controllers/dialog_controller.js.map +1 -1
- package/dist/controllers/direct_upload_controller.d.ts +56 -24
- package/dist/controllers/direct_upload_controller.js +201 -45
- package/dist/controllers/direct_upload_controller.js.map +1 -1
- package/dist/controllers/dirty_form_controller.d.ts +14 -6
- package/dist/controllers/dirty_form_controller.js +192 -29
- package/dist/controllers/dirty_form_controller.js.map +1 -1
- package/dist/controllers/dismissible_controller.d.ts +2 -0
- package/dist/controllers/dismissible_controller.js +83 -18
- package/dist/controllers/dismissible_controller.js.map +1 -1
- package/dist/controllers/drawer_controller.js +75 -4
- package/dist/controllers/drawer_controller.js.map +1 -1
- package/dist/controllers/empty_state_controller.d.ts +2 -0
- package/dist/controllers/empty_state_controller.js.map +1 -1
- package/dist/controllers/file_dropzone_controller.d.ts +9 -1
- package/dist/controllers/file_dropzone_controller.js +26 -3
- package/dist/controllers/file_dropzone_controller.js.map +1 -1
- package/dist/controllers/filter_controller.d.ts +2 -0
- package/dist/controllers/filter_controller.js.map +1 -1
- package/dist/controllers/flash_controller.d.ts +4 -0
- package/dist/controllers/flash_controller.js.map +1 -1
- package/dist/controllers/focus_controller.d.ts +4 -3
- package/dist/controllers/focus_controller.js +75 -4
- package/dist/controllers/focus_controller.js.map +1 -1
- package/dist/controllers/form_field_controller.d.ts +50 -10
- package/dist/controllers/form_field_controller.js +280 -62
- package/dist/controllers/form_field_controller.js.map +1 -1
- package/dist/controllers/form_validation_controller.d.ts +10 -8
- package/dist/controllers/form_validation_controller.js +208 -83
- package/dist/controllers/form_validation_controller.js.map +1 -1
- package/dist/controllers/frame_loading_controller.d.ts +2 -0
- package/dist/controllers/frame_loading_controller.js.map +1 -1
- package/dist/controllers/highlight_controller.d.ts +2 -0
- package/dist/controllers/highlight_controller.js.map +1 -1
- package/dist/controllers/hover_card_controller.d.ts +2 -2
- package/dist/controllers/hover_card_controller.js.map +1 -1
- package/dist/controllers/idle_controller.d.ts +5 -3
- package/dist/controllers/idle_controller.js +27 -5
- package/dist/controllers/idle_controller.js.map +1 -1
- package/dist/controllers/input_mask_controller.d.ts +2 -0
- package/dist/controllers/input_mask_controller.js.map +1 -1
- package/dist/controllers/lazy_frame_controller.d.ts +2 -0
- package/dist/controllers/lazy_frame_controller.js.map +1 -1
- package/dist/controllers/listbox_controller.d.ts +2 -0
- package/dist/controllers/listbox_controller.js.map +1 -1
- package/dist/controllers/local_time_controller.d.ts +2 -0
- package/dist/controllers/local_time_controller.js.map +1 -1
- package/dist/controllers/masonry_controller.d.ts +2 -0
- package/dist/controllers/masonry_controller.js.map +1 -1
- package/dist/controllers/menubar_controller.js +5 -3
- package/dist/controllers/menubar_controller.js.map +1 -1
- package/dist/controllers/meter_controller.d.ts +2 -0
- package/dist/controllers/meter_controller.js.map +1 -1
- package/dist/controllers/multi_select_controller.d.ts +48 -12
- package/dist/controllers/multi_select_controller.js +460 -151
- package/dist/controllers/multi_select_controller.js.map +1 -1
- package/dist/controllers/nested_form_controller.d.ts +2 -0
- package/dist/controllers/nested_form_controller.js.map +1 -1
- package/dist/controllers/network_status_controller.d.ts +2 -0
- package/dist/controllers/network_status_controller.js.map +1 -1
- package/dist/controllers/number_input_controller.d.ts +26 -6
- package/dist/controllers/number_input_controller.js +317 -51
- package/dist/controllers/number_input_controller.js.map +1 -1
- package/dist/controllers/otp_controller.d.ts +3 -0
- package/dist/controllers/otp_controller.js.map +1 -1
- package/dist/controllers/overflow_indicator_controller.d.ts +2 -0
- package/dist/controllers/overflow_indicator_controller.js.map +1 -1
- package/dist/controllers/overflow_menu_controller.d.ts +2 -0
- package/dist/controllers/overflow_menu_controller.js +6 -1
- package/dist/controllers/overflow_menu_controller.js.map +1 -1
- package/dist/controllers/pagination_controller.d.ts +2 -0
- package/dist/controllers/pagination_controller.js +35 -1
- package/dist/controllers/pagination_controller.js.map +1 -1
- package/dist/controllers/password_reveal_controller.d.ts +2 -0
- package/dist/controllers/password_reveal_controller.js.map +1 -1
- package/dist/controllers/password_strength_controller.d.ts +5 -3
- package/dist/controllers/password_strength_controller.js +20 -2
- package/dist/controllers/password_strength_controller.js.map +1 -1
- package/dist/controllers/persist_controller.d.ts +33 -19
- package/dist/controllers/persist_controller.js +449 -120
- package/dist/controllers/persist_controller.js.map +1 -1
- package/dist/controllers/pointer_drag_controller.d.ts +3 -0
- package/dist/controllers/pointer_drag_controller.js.map +1 -1
- package/dist/controllers/popover_controller.d.ts +2 -2
- package/dist/controllers/popover_controller.js +77 -4
- package/dist/controllers/popover_controller.js.map +1 -1
- package/dist/controllers/portal_controller.d.ts +3 -2
- package/dist/controllers/portal_controller.js.map +1 -1
- package/dist/controllers/preview_guard_controller.d.ts +2 -0
- package/dist/controllers/preview_guard_controller.js.map +1 -1
- package/dist/controllers/progress_controller.d.ts +3 -0
- package/dist/controllers/progress_controller.js.map +1 -1
- package/dist/controllers/radio_group_controller.d.ts +44 -15
- package/dist/controllers/radio_group_controller.js +540 -56
- package/dist/controllers/radio_group_controller.js.map +1 -1
- package/dist/controllers/rating_controller.d.ts +38 -31
- package/dist/controllers/rating_controller.js +276 -89
- package/dist/controllers/rating_controller.js.map +1 -1
- package/dist/controllers/reading_progress_controller.d.ts +2 -0
- package/dist/controllers/reading_progress_controller.js.map +1 -1
- package/dist/controllers/resizable_controller.d.ts +2 -0
- package/dist/controllers/resizable_controller.js +33 -0
- package/dist/controllers/resizable_controller.js.map +1 -1
- package/dist/controllers/roving_controller.d.ts +6 -0
- package/dist/controllers/roving_controller.js +60 -5
- package/dist/controllers/roving_controller.js.map +1 -1
- package/dist/controllers/scroll_area_controller.d.ts +25 -11
- package/dist/controllers/scroll_area_controller.js +557 -125
- package/dist/controllers/scroll_area_controller.js.map +1 -1
- package/dist/controllers/scroll_visibility_controller.d.ts +2 -0
- package/dist/controllers/scroll_visibility_controller.js +33 -0
- package/dist/controllers/scroll_visibility_controller.js.map +1 -1
- package/dist/controllers/scrollspy_controller.d.ts +2 -0
- package/dist/controllers/scrollspy_controller.js.map +1 -1
- package/dist/controllers/separator_controller.d.ts +54 -11
- package/dist/controllers/separator_controller.js +354 -38
- package/dist/controllers/separator_controller.js.map +1 -1
- package/dist/controllers/sidebar_controller.js +83 -10
- package/dist/controllers/sidebar_controller.js.map +1 -1
- package/dist/controllers/skeleton_controller.d.ts +2 -0
- package/dist/controllers/skeleton_controller.js.map +1 -1
- package/dist/controllers/slider_controller.d.ts +2 -0
- package/dist/controllers/slider_controller.js.map +1 -1
- package/dist/controllers/smart_sticky_header_controller.d.ts +2 -0
- package/dist/controllers/smart_sticky_header_controller.js.map +1 -1
- package/dist/controllers/spinner_controller.d.ts +2 -0
- package/dist/controllers/spinner_controller.js.map +1 -1
- package/dist/controllers/step_indicator_controller.d.ts +2 -0
- package/dist/controllers/step_indicator_controller.js.map +1 -1
- package/dist/controllers/stepper_controller.d.ts +2 -0
- package/dist/controllers/stepper_controller.js.map +1 -1
- package/dist/controllers/stick_to_bottom_controller.d.ts +2 -0
- package/dist/controllers/stick_to_bottom_controller.js.map +1 -1
- package/dist/controllers/sticky_observer_controller.d.ts +2 -0
- package/dist/controllers/sticky_observer_controller.js.map +1 -1
- package/dist/controllers/submit_once_controller.d.ts +94 -38
- package/dist/controllers/submit_once_controller.js +399 -121
- package/dist/controllers/submit_once_controller.js.map +1 -1
- package/dist/controllers/switch_controller.d.ts +2 -0
- package/dist/controllers/switch_controller.js.map +1 -1
- package/dist/controllers/tags_input_controller.d.ts +43 -11
- package/dist/controllers/tags_input_controller.js +356 -120
- package/dist/controllers/tags_input_controller.js.map +1 -1
- package/dist/controllers/textarea_autosize_controller.d.ts +2 -0
- package/dist/controllers/textarea_autosize_controller.js.map +1 -1
- package/dist/controllers/theme_controller.d.ts +2 -0
- package/dist/controllers/theme_controller.js +8 -6
- package/dist/controllers/theme_controller.js.map +1 -1
- package/dist/controllers/time_picker_controller.d.ts +44 -13
- package/dist/controllers/time_picker_controller.js +296 -107
- package/dist/controllers/time_picker_controller.js.map +1 -1
- package/dist/controllers/toast_controller.d.ts +4 -0
- package/dist/controllers/toast_controller.js.map +1 -1
- package/dist/controllers/toggle_group_controller.d.ts +41 -13
- package/dist/controllers/toggle_group_controller.js +378 -55
- package/dist/controllers/toggle_group_controller.js.map +1 -1
- package/dist/controllers/toolbar_controller.js +5 -3
- package/dist/controllers/toolbar_controller.js.map +1 -1
- package/dist/controllers/tooltip_controller.d.ts +2 -2
- package/dist/controllers/tooltip_controller.js.map +1 -1
- package/dist/controllers/transition_controller.d.ts +4 -3
- package/dist/controllers/transition_controller.js.map +1 -1
- package/dist/controllers/tree_view_controller.d.ts +2 -0
- package/dist/controllers/tree_view_controller.js +7 -4
- package/dist/controllers/tree_view_controller.js.map +1 -1
- package/dist/index.js +4963 -1581
- package/dist/index.js.map +1 -1
- package/dist/inspector/cli.d.ts +123 -6
- package/dist/inspector/cli.js +212 -18
- package/dist/inspector/cli.js.map +1 -1
- package/dist/inspector/cli_bin.js +274 -50
- package/dist/inspector/cli_bin.js.map +1 -1
- package/dist/inspector/examples.json +15 -15
- package/dist/inspector/manifest.json +602 -80
- package/dist/positioning/index.d.ts +4 -2
- package/dist/positioning/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -13,16 +13,48 @@ function inheritsFieldsetDisabled(control) {
|
|
|
13
13
|
return false;
|
|
14
14
|
}
|
|
15
15
|
function canTakeFocus(element) {
|
|
16
|
-
if (element.closest("[hidden]")) return false;
|
|
16
|
+
if (element.closest("[hidden], [inert]")) return false;
|
|
17
|
+
if (element instanceof HTMLInputElement && element.type === "hidden") return false;
|
|
17
18
|
if (!("disabled" in element)) return true;
|
|
18
19
|
if (element.disabled) return false;
|
|
19
20
|
return !inheritsFieldsetDisabled(element);
|
|
20
21
|
}
|
|
21
22
|
|
|
23
|
+
// src/utils/before_cache_reset.ts
|
|
24
|
+
var BeforeCacheReset = class _BeforeCacheReset {
|
|
25
|
+
/** Every subscribed instance, iterated by the one shared document listener. */
|
|
26
|
+
static #subscribers = /* @__PURE__ */ new Set();
|
|
27
|
+
/** The shared listener; installed while at least one instance is subscribed. */
|
|
28
|
+
static #onBeforeCache = () => {
|
|
29
|
+
for (const subscriber of _BeforeCacheReset.#subscribers) subscriber.#rewind();
|
|
30
|
+
};
|
|
31
|
+
#rewind;
|
|
32
|
+
/** @param rewind - the pass that returns this controller's state to its initial form. */
|
|
33
|
+
constructor(rewind) {
|
|
34
|
+
this.#rewind = rewind;
|
|
35
|
+
}
|
|
36
|
+
/** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */
|
|
37
|
+
activate() {
|
|
38
|
+
const first = _BeforeCacheReset.#subscribers.size === 0;
|
|
39
|
+
_BeforeCacheReset.#subscribers.add(this);
|
|
40
|
+
if (first) {
|
|
41
|
+
document.addEventListener("turbo:before-cache", _BeforeCacheReset.#onBeforeCache);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */
|
|
45
|
+
deactivate() {
|
|
46
|
+
_BeforeCacheReset.#subscribers.delete(this);
|
|
47
|
+
if (_BeforeCacheReset.#subscribers.size > 0) return;
|
|
48
|
+
document.removeEventListener("turbo:before-cache", _BeforeCacheReset.#onBeforeCache);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
22
52
|
// src/utils/tabindex_loan.ts
|
|
23
53
|
var TabindexLoan = class {
|
|
24
54
|
#value;
|
|
25
55
|
#lent = /* @__PURE__ */ new Set();
|
|
56
|
+
/** Returns live loans before Turbo can copy them into its page snapshot. */
|
|
57
|
+
#beforeCache = new BeforeCacheReset(() => this.returnAll());
|
|
26
58
|
/**
|
|
27
59
|
* @param value - the `tabindex` to lend. `"-1"` (the default) is
|
|
28
60
|
* programmatically focusable but not a Tab stop; `"0"` is a real Tab stop,
|
|
@@ -36,6 +68,7 @@ var TabindexLoan = class {
|
|
|
36
68
|
if (element.hasAttribute("tabindex")) return;
|
|
37
69
|
element.setAttribute("tabindex", this.#value);
|
|
38
70
|
this.#lent.add(element);
|
|
71
|
+
this.#beforeCache.activate();
|
|
39
72
|
}
|
|
40
73
|
/** Takes back every loan whose value is still the one that was lent. */
|
|
41
74
|
returnAll() {
|
|
@@ -43,6 +76,7 @@ var TabindexLoan = class {
|
|
|
43
76
|
if (element.getAttribute("tabindex") === this.#value) element.removeAttribute("tabindex");
|
|
44
77
|
}
|
|
45
78
|
this.#lent.clear();
|
|
79
|
+
this.#beforeCache.deactivate();
|
|
46
80
|
}
|
|
47
81
|
};
|
|
48
82
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/focus_candidate.ts","../../src/utils/tabindex_loan.ts","../../src/controllers/pagination_controller.ts"],"names":[],"mappings":";;;;;AAWO,SAAS,yBAAyB,OAAA,EAA+B;AACtE,EAAA,IAAI,QAAA,GAA2B,OAAA,CAAQ,OAAA,CAAQ,oBAAoB,CAAA;AACnE,EAAA,OAAO,QAAA,EAAU;AACf,IAAA,MAAM,MAAA,GAAS,KAAA,CAAM,IAAA,CAAK,QAAA,CAAS,QAAQ,CAAA,CAAE,IAAA,CAAK,CAAC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AAA,CAAK,KAAA,CAAM,IAAI,CAAC,CAAC,CAAA;AAAA,EAC5D;AAAA;AAAA,EAGA,MAAM,MAAA,EAAoC;AACxC,IAAA,OAAO,MAAA,CAAO,YAAA,CAAa,qBAAA,CAAqB,cAAc,CAAA;AAAA,EAChE;AACF","file":"pagination_controller.js","sourcesContent":["/**\n * Whether a disabled `<fieldset>` ancestor actually reaches `control`.\n *\n * HTML exempts the contents of a fieldset's **first direct-child `<legend>`**, and\n * the exemption is per fieldset — a control legal in one legend can still be\n * disabled by a second, outer fieldset, so the walk continues upward.\n *\n * Exported for the consumer that needs this rule *without* the rest of\n * {@link canTakeFocus}: `toolbar` bounds its own `hidden` walk at the toolbar\n * root, which is a different rule, so it composes the two itself.\n */\nexport function inheritsFieldsetDisabled(control: HTMLElement): boolean {\n let fieldset: Element | null = control.closest(\"fieldset[disabled]\");\n while (fieldset) {\n const legend = Array.from(fieldset.children).find((child) => child.tagName === \"LEGEND\");\n if (!legend?.contains(control)) return true;\n fieldset = fieldset.parentElement?.closest(\"fieldset[disabled]\") ?? null;\n }\n return false;\n}\n\n/**\n * Whether an element can actually take focus, checked **before** `focus()` runs.\n *\n * A controller that must move focus off a control it is about to disable or hide\n * picks a destination and calls `focus()` on it. If that destination cannot take\n * focus, the call **fails silently**: `hidden` and natively `disabled` elements\n * swallow it, so the caret stays in the subtree that is disappearing and lands on\n * `<body>` a frame later — the exact outcome the rescue exists to prevent, minus\n * any signal that it happened.\n *\n * Testing after the fact is the obvious alternative and is deliberately not the\n * rule. Reading `document.activeElement` back only works in a real browser, and\n * looping over candidates that way performs a real focus move per failure —\n * observable to assistive technology. Checking first costs nothing and catches\n * the cases that actually occur.\n *\n * **`aria-disabled` is not disqualifying.** It is the attribute an author uses\n * for a control that must stay *discoverable*, and the roving contract keeps\n * such items reachable. Only the three conditions that make the platform refuse\n * focus are checked: `hidden` (an ancestor's counts), the native `disabled`\n * property, and `disabled` inherited from an ancestor `fieldset`. CSS-only\n * invisibility is not detectable here and stays the consumer's problem.\n *\n * Reading `:disabled` instead of walking the fieldset chain would be shorter, but\n * that pseudo-class is not evaluated consistently outside real browsers and this\n * has to be right headlessly too. happy-dom in particular focuses a `<button>`\n * inside a disabled fieldset where a real engine refuses, so the inheritance is\n * spelled out rather than delegated.\n *\n * What a consumer does when nothing survives is its own call: some fall back to\n * their landmark, while a widget whose caret already sits somewhere legitimate\n * refuses the move outright rather than relocating it.\n *\n * @example\n * ```ts\n * const target = candidates.find(canTakeFocus);\n * if (target) target.focus();\n * else {\n * this.#tabindex.lend(this.element); // nothing left: fall back to the landmark\n * this.element.focus();\n * }\n * ```\n *\n * @param element - the candidate destination\n */\nexport function canTakeFocus(element: HTMLElement): boolean {\n if (element.closest(\"[hidden]\")) return false;\n if (!(\"disabled\" in element)) return true;\n if ((element as HTMLElement & { disabled: boolean }).disabled) return false;\n return !inheritsFieldsetDisabled(element);\n}\n","/**\n * Shared bookkeeping for a `tabindex` a controller lends an element temporarily.\n *\n * A controller that must move focus somewhere the author never made focusable\n * (a landmark root, a scroll destination) reaches for the same trick: add a\n * `tabindex` just-in-time and hand it back once it is no longer needed. The\n * borrow is the easy half; the return is what the two conditions below are for.\n *\n * **Returning needs two conditions, not one.** Owning the borrow is not enough:\n * the attribute must also still hold the value this instance wrote. A consumer\n * that changed it afterwards — `tabindex=\"0\"` to make the root its own Tab stop\n * — owns it now, and removing it there silently discards authored markup. The\n * bookkeeping is dropped either way, since the loan is over regardless of who\n * ends up owning the value.\n *\n * **Never borrow over an existing value.** An element that already carries a\n * `tabindex` is the author's to control, so there is nothing to lend and nothing\n * to return.\n *\n * The registry is keyed by element, so a controller borrowing on a single\n * element (`this.element`) and one borrowing across a changing set of targets\n * use the same API — the single-element case is a set of one. It holds no\n * opinion about *when* to borrow or where focus goes next; that stays in the\n * controller.\n *\n * **The API is deliberately two methods.** This file's own doc block is dropped\n * from `dist`, but every member comment is inlined into **each** consumer entry\n * (`tsup` builds with `splitting: false`), so rationale belongs here, only the\n * contract belongs on the members, and every method no consumer calls is still\n * paid for once per consumer entry.\n *\n * @example\n * ```ts\n * readonly #tabindex = new TabindexLoan();\n *\n * #rescueFocus() {\n * this.#tabindex.lend(this.element);\n * this.element.focus();\n * }\n *\n * disconnect() {\n * this.#tabindex.returnAll();\n * }\n * ```\n */\nexport class TabindexLoan<T extends HTMLElement = HTMLElement> {\n readonly #value: string;\n readonly #lent = new Set<T>();\n\n /**\n * @param value - the `tabindex` to lend. `\"-1\"` (the default) is\n * programmatically focusable but not a Tab stop; `\"0\"` is a real Tab stop,\n * which a scroll region with no focusable content of its own needs.\n */\n constructor(value: string = \"-1\") {\n this.#value = value;\n }\n\n /** Lends `element` the value; no-ops when it already carries a `tabindex`. */\n lend(element: T): void {\n if (element.hasAttribute(\"tabindex\")) return;\n element.setAttribute(\"tabindex\", this.#value);\n this.#lent.add(element);\n }\n\n /** Takes back every loan whose value is still the one that was lent. */\n returnAll(): void {\n for (const element of this.#lent) {\n if (element.getAttribute(\"tabindex\") === this.#value) element.removeAttribute(\"tabindex\");\n }\n this.#lent.clear();\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { canTakeFocus } from \"../utils/focus_candidate\";\nimport { TabindexLoan } from \"../utils/tabindex_loan\";\n\n/**\n * Headless, accessible pagination behavior.\n *\n * Markup contract (identifier: `stimeo--pagination`):\n * <nav data-controller=\"stimeo--pagination\" aria-label=\"Pagination\"\n * data-stimeo--pagination-page-value=\"1\"\n * data-stimeo--pagination-total-value=\"5\">\n * <button type=\"button\" data-stimeo--pagination-target=\"prev\"\n * data-action=\"click->stimeo--pagination#prev\">Prev</button>\n * <button type=\"button\" data-page=\"1\" aria-current=\"page\"\n * data-stimeo--pagination-target=\"page\"\n * data-action=\"click->stimeo--pagination#select\">1</button>\n * <!-- more page buttons -->\n * <button type=\"button\" data-stimeo--pagination-target=\"next\"\n * data-action=\"click->stimeo--pagination#next\">Next</button>\n * </nav>\n *\n * There is no dedicated APG pattern; this uses a navigation landmark plus\n * `aria-current=\"page\"`. The controller owns current-page state, the\n * `aria-current` sync, boundary disabling of prev/next, and the change event.\n * Generating/eliding the page buttons and fetching data stay with the consumer.\n *\n * `prev`/`next` must be real `<button>` elements: the boundary state is applied\n * through the native `disabled` property, which no other element honors.\n *\n * @remarks\n * Behavior only — each control is in the natural Tab order (no roving). When a\n * boundary disables the button that currently has focus, focus is moved first so\n * it is never lost to a `disabled` element.\n *\n * Behavior provided:\n * - `select` reads the clicked button's `data-page` and makes it current. The\n * value must parse as an integer; blank/fractional/non-numeric ones are ignored.\n * - `prev`/`next` step by one, clamped to `[1, total]`.\n * - The current page button gets `aria-current=\"page\"` (removed from the rest);\n * `prev` is `disabled` at page 1 and `next` at `total`.\n * - `page`/`total` are normalized (`total` to a finite integer >= 1, `page` into\n * `[1, total]`) on connect **and** on every runtime Value change, so JS-driven\n * updates re-render. Normalization never dispatches `change`: it is a display\n * correction, not a user navigation, and the initial render is consumer-owned.\n * - Page/boundary buttons swapped in at runtime re-render through the Stimulus\n * target callbacks, so a consumer-regenerated button list stays in sync.\n * - Every navigation dispatches `stimeo--pagination:change`, whose `detail.total`\n * is the same normalized total the boundary state is derived from.\n *\n * The boundary `disabled` is **owned**: the controller marks what it disabled\n * with `data-stimeo--pagination-boundary-disabled` and releases only that. A\n * button already disabled by the consumer is never marked when it overlaps a\n * boundary, so loading / permission state survives both entering and leaving the\n * boundary. The marker lives in the DOM rather than in a field so ownership\n * survives a Turbo cache restore, where a fresh instance would otherwise either\n * strand or steal the flag.\n */\nexport class PaginationController extends Controller<HTMLElement> {\n static override targets = [\"page\", \"prev\", \"next\"];\n static override values = {\n page: { type: Number, default: 1 },\n total: { type: Number, default: 1 },\n };\n static actions = [\"next\", \"prev\", \"select\"] as const;\n static events = [\"change\"] as const;\n\n /** Marks a `disabled` this controller applied at a boundary (ownership flag). */\n static readonly #BOUNDARY_ATTR = \"data-stimeo--pagination-boundary-disabled\";\n\n declare readonly pageTargets: HTMLElement[];\n declare readonly prevTarget: HTMLButtonElement;\n declare readonly nextTarget: HTMLButtonElement;\n declare readonly hasPrevTarget: boolean;\n declare readonly hasNextTarget: boolean;\n declare pageValue: number;\n declare totalValue: number;\n\n #isConnected = false;\n /** The `tabindex` this instance lends the root for the focus fallback. */\n readonly #tabindex = new TabindexLoan();\n\n /** Normalizes out-of-range initial values and renders the initial state. */\n override connect(): void {\n this.#isConnected = true;\n this.#normalizeAndRender();\n }\n\n /** Reverts the one attribute the controller adds outside its state hooks. */\n override disconnect(): void {\n this.#isConnected = false;\n this.#tabindex.returnAll();\n }\n\n /** Re-renders when application code (or a Turbo morph) changes `page` at runtime. */\n pageValueChanged(): void {\n if (!this.#isConnected) return;\n this.#normalizeAndRender();\n }\n\n /** Re-renders when application code (or a Turbo morph) changes `total` at runtime. */\n totalValueChanged(): void {\n if (!this.#isConnected) return;\n this.#normalizeAndRender();\n }\n\n /** Syncs a page button appended/replaced at runtime (the consumer owns the list). */\n pageTargetConnected(): void {\n if (!this.#isConnected) return;\n this.#render();\n }\n\n /** Syncs a `prev` button appended/replaced at runtime. */\n prevTargetConnected(): void {\n if (!this.#isConnected) return;\n this.#render();\n }\n\n /** Syncs a `next` button appended/replaced at runtime. */\n nextTargetConnected(): void {\n if (!this.#isConnected) return;\n this.#render();\n }\n\n /** Makes the clicked page button (its `data-page`) current. */\n select(event: Event): void {\n const button = event.currentTarget as HTMLElement;\n const raw = button.dataset.page;\n if (raw === undefined || raw.trim() === \"\") return;\n const page = Number(raw);\n // Integer-only, matching `stimeo--stepper`: `Number(\"\")` is 0 and `Number(\"2.7\")`\n // truncates, so a bare finite check would accept meaningless page numbers.\n if (!Number.isInteger(page)) return;\n this.#goto(page);\n }\n\n /** Steps to the previous page. */\n prev(): void {\n this.#goto(this.#page - 1);\n }\n\n /** Steps to the next page. */\n next(): void {\n this.#goto(this.#page + 1);\n }\n\n /** Moves to `page` (clamped to `[1, total]`), re-renders, and dispatches `change`. */\n #goto(page: number): void {\n if (!Number.isFinite(page)) return;\n const previous = this.#page;\n const target = this.#clamp(page);\n if (target === previous) return;\n this.pageValue = target;\n this.#render();\n this.dispatch(\"change\", {\n detail: { page: target, total: this.#total, previous },\n });\n }\n\n /** Writes the normalized Values back (only when they differ) and renders. */\n #normalizeAndRender(): void {\n // Stimulus setters rewrite the data attribute unconditionally, so guard the\n // no-op case to avoid waking consumer MutationObservers for nothing.\n const total = this.#total;\n if (!Object.is(total, this.totalValue)) this.totalValue = total;\n const page = this.#page;\n if (!Object.is(page, this.pageValue)) this.pageValue = page;\n this.#render();\n }\n\n /**\n * Syncs `aria-current` on the page buttons and the prev/next `disabled` state.\n *\n * @stimeoRenderRoot\n */\n #render(): void {\n const page = this.#page;\n for (const button of this.pageTargets) {\n if (Number(button.dataset.page) === page) {\n button.setAttribute(\"aria-current\", \"page\");\n } else {\n button.removeAttribute(\"aria-current\");\n }\n }\n\n const prev = this.hasPrevTarget ? this.prevTarget : null;\n const next = this.hasNextTarget ? this.nextTarget : null;\n const atStart = page <= 1;\n const atEnd = page >= this.#total;\n // Resolve both post-render states up front: a focus hand-off must target the\n // opposite button as it will be *after* this pass, not as it is now (moving\n // between the two boundaries of a 2-page set re-enables it in the same pass).\n const prevStaysDisabled = this.#disabledAfter(prev, atStart);\n const nextStaysDisabled = this.#disabledAfter(next, atEnd);\n // Release before disabling, so the hand-off can land on a button this same\n // pass re-enables (focusing a still-`disabled` button is a no-op).\n this.#release(prev, atStart);\n this.#release(next, atEnd);\n this.#disable(prev, atStart, nextStaysDisabled ? null : next);\n this.#disable(next, atEnd, prevStaysDisabled ? null : prev);\n }\n\n /** Whether a boundary button will still be `disabled` once this render applies. */\n #disabledAfter(button: HTMLButtonElement | null, atBoundary: boolean): boolean {\n if (!button) return true;\n if (atBoundary) return true;\n // Away from a boundary, only the controller's own `disabled` is released.\n return button.disabled && !this.#owns(button);\n }\n\n /** Releases the boundary `disabled` this controller owns, once away from it. */\n #release(button: HTMLButtonElement | null, atBoundary: boolean): void {\n if (!button || atBoundary || !this.#owns(button)) return;\n button.disabled = false;\n button.removeAttribute(PaginationController.#BOUNDARY_ATTR);\n }\n\n /**\n * Disables a boundary button, first moving focus off it when it is the active\n * element so disabling never strands focus.\n */\n #disable(\n button: HTMLButtonElement | null,\n atBoundary: boolean,\n opposite: HTMLButtonElement | null,\n ): void {\n if (!button || !atBoundary) return;\n if (button.disabled && !this.#owns(button)) return;\n if (button === document.activeElement) this.#moveFocusAwayFrom(opposite);\n button.disabled = true;\n button.setAttribute(PaginationController.#BOUNDARY_ATTR, \"\");\n }\n\n /**\n * Moves focus to `opposite` (already resolved to `null` when it will stay\n * disabled), else to the current page button, else to the landmark itself.\n */\n #moveFocusAwayFrom(opposite: HTMLButtonElement | null): void {\n const page = this.#page;\n const currentPage = this.pageTargets.find(\n (candidate) => Number(candidate.dataset.page) === page,\n );\n // Checked before the call, never after: `hidden` and natively disabled\n // elements swallow `focus()` silently, so an unchecked destination leaves the\n // caret in the subtree that is about to disable and drops it to <body> a frame\n // later — the outcome this rescue exists to prevent.\n // Narrowed to `HTMLElement`, not `HTMLButtonElement`: `pageTargets` is typed\n // `HTMLElement[]`, so a page control can legitimately be an `<a>`. The\n // destination is only ever focused, so the wider type is the honest one.\n const destination = [opposite, currentPage].find(\n (candidate): candidate is HTMLElement => candidate != null && canTakeFocus(candidate),\n );\n if (destination) {\n destination.focus();\n return;\n }\n // Nothing left to hand focus to (a lone boundary button, or every page button\n // disabled): keep it inside the pagination landmark instead of letting the\n // browser drop it to <body> when the button disables. The root is made\n // programmatically focusable just-in-time with `tabindex=\"-1\"`, which is not a\n // Tab stop; `disconnect()` removes it again when this controller added it.\n this.#tabindex.lend(this.element);\n this.element.focus();\n }\n\n /** Total pages, normalized to a finite integer >= 1. */\n get #total(): number {\n const total = this.totalValue;\n return Number.isFinite(total) ? Math.max(1, Math.trunc(total)) : 1;\n }\n\n /** The current page, normalized into `[1, total]`. */\n get #page(): number {\n return this.#clamp(this.pageValue);\n }\n\n /** Constrains `page` to `[1, total]`; a non-finite page falls back to page 1. */\n #clamp(page: number): number {\n if (!Number.isFinite(page)) return 1;\n return Math.min(this.#total, Math.max(1, Math.trunc(page)));\n }\n\n /** Whether the button's current `disabled` was applied by boundary control. */\n #owns(button: HTMLButtonElement): boolean {\n return button.hasAttribute(PaginationController.#BOUNDARY_ATTR);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/focus_candidate.ts","../../src/utils/before_cache_reset.ts","../../src/utils/tabindex_loan.ts","../../src/controllers/pagination_controller.ts"],"names":[],"mappings":";;;;;AAWO,SAAS,yBAAyB,OAAA,EAA+B;AACtE,EAAA,IAAI,QAAA,GAA2B,OAAA,CAAQ,OAAA,CAAQ,oBAAoB,CAAA;AACnE,EAAA,OAAO,QAAA,EAAU;AACf,IAAA,MAAM,MAAA,GAAS,KAAA,CAAM,IAAA,CAAK,QAAA,CAAS,QAAQ,CAAA,CAAE,IAAA,CAAK,CAAC,KAAA,KAAU,KAAA,CAAM,OAAA,KAAY,QAAQ,CAAA;AACvF,IAAA,IAAI,CAAC,MAAA,EAAQ,QAAA,CAAS,OAAO,GAAG,OAAO,IAAA;AACvC,IAAA,QAAA,GAAW,QAAA,CAAS,aAAA,EAAe,OAAA,CAAQ,oBAAoB,CAAA,IAAK,IAAA;AAAA,EACtE;AACA,EAAA,OAAO,KAAA;AACT;AAgDO,SAAS,aAAa,OAAA,EAA+B;AAC1D,EAAA,IAAI,OAAA,CAAQ,OAAA,CAAQ,mBAAmB,CAAA,EAAG,OAAO,KAAA;AACjD,EAAA,IAAI,OAAA,YAAmB,gBAAA,IAAoB,OAAA,CAAQ,IAAA,KAAS,UAAU,OAAO,KAAA;AAC7E,EAAA,IAAI,EAAE,UAAA,IAAc,OAAA,CAAA,EAAU,OAAO,IAAA;AACrC,EAAA,IAAK,OAAA,CAAgD,UAAU,OAAO,KAAA;AACtE,EAAA,OAAO,CAAC,yBAAyB,OAAO,CAAA;AAC1C;;;AC9BO,IAAM,gBAAA,GAAN,MAAM,iBAAA,C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Q,IAAA,CAAK,UAAA;AACnB,IAAA,OAAO,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA,GAAI,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,KAAA,CAAM,KAAK,CAAC,CAAA,GAAI,CAAA;AAAA,EACnE;AAAA;AAAA,EAGA,IAAI,KAAA,GAAgB;AAClB,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,SAAS,CAAA;AAAA,EACnC;AAAA;AAAA,EAGA,OAAO,IAAA,EAAsB;AAC3B,IAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,IAAI,GAAG,OAAO,CAAA;AACnC,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,MAAA,EAAQ,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,KAAA,CAAM,IAAI,CAAC,CAAC,CAAA;AAAA,EAC5D;AAAA;AAAA,EAGA,MAAM,MAAA,EAAoC;AACxC,IAAA,OAAO,MAAA,CAAO,YAAA,CAAa,qBAAA,CAAqB,cAAc,CAAA;AAAA,EAChE;AACF","file":"pagination_controller.js","sourcesContent":["/**\n * Whether a disabled `<fieldset>` ancestor actually reaches `control`.\n *\n * HTML exempts the contents of a fieldset's **first direct-child `<legend>`**, and\n * the exemption is per fieldset — a control legal in one legend can still be\n * disabled by a second, outer fieldset, so the walk continues upward.\n *\n * Exported for the consumer that needs this rule *without* the rest of\n * {@link canTakeFocus}: `toolbar` bounds its own `hidden` walk at the toolbar\n * root, which is a different rule, so it composes the two itself.\n */\nexport function inheritsFieldsetDisabled(control: HTMLElement): boolean {\n let fieldset: Element | null = control.closest(\"fieldset[disabled]\");\n while (fieldset) {\n const legend = Array.from(fieldset.children).find((child) => child.tagName === \"LEGEND\");\n if (!legend?.contains(control)) return true;\n fieldset = fieldset.parentElement?.closest(\"fieldset[disabled]\") ?? null;\n }\n return false;\n}\n\n/**\n * Whether an element can actually take focus, checked **before** `focus()` runs.\n *\n * A controller that must move focus off a control it is about to disable or hide\n * picks a destination and calls `focus()` on it. If that destination cannot take\n * focus, the call **fails silently**: `hidden` and natively `disabled` elements\n * swallow it, so the caret stays in the subtree that is disappearing and lands on\n * `<body>` a frame later — the exact outcome the rescue exists to prevent, minus\n * any signal that it happened.\n *\n * Testing after the fact is the obvious alternative and is deliberately not the\n * rule. Reading `document.activeElement` back only works in a real browser, and\n * looping over candidates that way performs a real focus move per failure —\n * observable to assistive technology. Checking first costs nothing and catches\n * the cases that actually occur.\n *\n * **`aria-disabled` is not disqualifying.** It is the attribute an author uses\n * for a control that must stay *discoverable*, and the roving contract keeps\n * such items reachable. Only the three conditions that make the platform refuse\n * focus are checked: `hidden` / `inert` (an ancestor's counts),\n * `input[type=\"hidden\"]`, the native `disabled` property, and `disabled`\n * inherited from an ancestor `fieldset`. CSS-only invisibility is handled by\n * {@link isRenderedForFocus} when a consumer needs sequential-focus semantics.\n *\n * Reading `:disabled` instead of walking the fieldset chain would be shorter, but\n * that pseudo-class is not evaluated consistently outside real browsers and this\n * has to be right headlessly too. happy-dom in particular focuses a `<button>`\n * inside a disabled fieldset where a real engine refuses, so the inheritance is\n * spelled out rather than delegated.\n *\n * What a consumer does when nothing survives is its own call: some fall back to\n * their landmark, while a widget whose caret already sits somewhere legitimate\n * refuses the move outright rather than relocating it.\n *\n * @example\n * ```ts\n * const target = candidates.find(canTakeFocus);\n * if (target) target.focus();\n * else {\n * this.#tabindex.lend(this.element); // nothing left: fall back to the landmark\n * this.element.focus();\n * }\n * ```\n *\n * @param element - the candidate destination\n */\nexport function canTakeFocus(element: HTMLElement): boolean {\n if (element.closest(\"[hidden], [inert]\")) return false;\n if (element instanceof HTMLInputElement && element.type === \"hidden\") return false;\n if (!(\"disabled\" in element)) return true;\n if ((element as HTMLElement & { disabled: boolean }).disabled) return false;\n return !inheritsFieldsetDisabled(element);\n}\n\n/** Elements whose semantics or authored attributes can place them in sequential focus order. */\nexport const TAB_STOP_CANDIDATE_SELECTOR = [\n \"a[href]\",\n \"area[href]\",\n \"button\",\n \"input\",\n \"select\",\n \"textarea\",\n \"summary\",\n \"iframe\",\n \"audio[controls]\",\n \"video[controls]\",\n \"[tabindex]\",\n \"[contenteditable]\",\n].join(\",\");\n\n/** Optional browser visibility API used to exclude CSS-hidden candidates. */\ninterface VisibilityCheckable {\n checkVisibility?: (options?: { visibilityProperty?: boolean }) => boolean;\n}\n\n/** Whether CSS visibility allows an otherwise eligible element to participate in focus order. */\nexport function isRenderedForFocus(element: HTMLElement): boolean {\n const check = (element as HTMLElement & VisibilityCheckable).checkVisibility;\n return typeof check === \"function\" ? check.call(element, { visibilityProperty: true }) : true;\n}\n\n/** Parses an authored `tabindex`; invalid syntax has no explicit focus-order meaning. */\nfunction authoredTabindex(element: HTMLElement): number | null {\n const value = element.getAttribute(\"tabindex\");\n if (value === null || !/^[+-]?\\d+$/.test(value.trim())) return null;\n return Number(value);\n}\n\n/** Whether the element's native semantics place it in sequential focus order. */\nfunction hasNativeTabStop(element: HTMLElement): boolean {\n if (element instanceof HTMLAnchorElement || element instanceof HTMLAreaElement) {\n return element.hasAttribute(\"href\");\n }\n if (\n element instanceof HTMLButtonElement ||\n element instanceof HTMLSelectElement ||\n element instanceof HTMLTextAreaElement\n ) {\n return true;\n }\n if (element instanceof HTMLInputElement) return element.type !== \"hidden\";\n if (element instanceof HTMLIFrameElement) return true;\n if (element.tagName === \"AUDIO\" || element.tagName === \"VIDEO\") {\n return element.hasAttribute(\"controls\");\n }\n if (element instanceof HTMLElement && element.tagName === \"SUMMARY\") {\n const details = element.parentElement;\n return (\n details instanceof HTMLDetailsElement &&\n Array.from(details.children).find((child) => child.tagName === \"SUMMARY\") === element\n );\n }\n return false;\n}\n\n/** Whether an explicit `contenteditable` value creates an editable tab stop. */\nfunction hasEditableTabStop(element: HTMLElement): boolean {\n const value = element.getAttribute(\"contenteditable\")?.toLowerCase();\n return value === \"\" || value === \"true\" || value === \"plaintext-only\";\n}\n\n/**\n * Whether an element is a usable sequential Tab stop right now.\n *\n * Native semantics, authored `tabindex`, editable hosts, inherited disabled state,\n * HTML `hidden`/`inert`, and CSS visibility are evaluated together. `aria-disabled`\n * remains focusable because it communicates unavailability without removing the\n * control from discovery order.\n */\nexport function isTabStop(element: HTMLElement): boolean {\n if (!canTakeFocus(element) || !isRenderedForFocus(element)) return false;\n\n const tabindex = authoredTabindex(element);\n if (tabindex !== null) return tabindex >= 0;\n return hasNativeTabStop(element) || hasEditableTabStop(element);\n}\n\n/** Returns every usable sequential Tab stop below `root` in document order. */\nexport function tabStopsWithin(root: ParentNode): HTMLElement[] {\n return Array.from(root.querySelectorAll<HTMLElement>(TAB_STOP_CANDIDATE_SELECTOR)).filter(\n isTabStop,\n );\n}\n\n/** Returns the first usable sequential Tab stop below `root`, if one exists. */\nexport function firstTabStop(root: ParentNode): HTMLElement | null {\n for (const candidate of root.querySelectorAll<HTMLElement>(TAB_STOP_CANDIDATE_SELECTOR)) {\n if (isTabStop(candidate)) return candidate;\n }\n return null;\n}\n\n/** Whether `root` contains at least one usable sequential Tab stop. */\nexport function hasTabStop(root: ParentNode): boolean {\n return firstTabStop(root) !== null;\n}\n","/**\n * Runs a controller's \"return to the initial state\" pass just before Turbo\n * caches the page.\n *\n * **`disconnect()` cannot do this job, for two independent reasons.** Turbo\n * queues the clone from this event rather than taking it here, and the body swap\n * that runs the controller's `disconnect()` is queued separately — so which of\n * the two lands first is not something a controller can rely on, and a rewind\n * written in `disconnect()` may reach only the DOM being thrown away. In the\n * other direction, `disconnect()` also fires on an in-page move (Stimulus tears\n * down and reconnects the same element), where rewinding would wipe a\n * legitimately in-progress interaction — a spinner mid-load would vanish. One\n * timing is unreliable, the other is too eager; `turbo:before-cache` is the only\n * point that is exactly \"the page is about to be frozen\".\n *\n * Scope is the subscription only: registering on `activate()`, unregistering on\n * `deactivate()`, and one shared document listener no matter how many instances\n * are live. *What* to return to its initial state — which `data-state`, which\n * `hidden`, which `aria-busy` — stays in the controller, because no two\n * consumers answer it the same way (the `MicrotaskCoalescer` split).\n *\n * **Rewind state, not appearance.** The pass writes attributes the controller\n * itself owns; the visual result of those attributes is the consumer's CSS, and\n * a library that reached for style or class names would be guessing at markup\n * it does not own.\n *\n * Both entry points are idempotent, so the lifecycle hooks can call them\n * unconditionally: a second `activate()` does not double-subscribe and does not\n * make the callback run twice, and `deactivate()` on an instance that never\n * subscribed is a no-op.\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 #beforeCache = new BeforeCacheReset(() => this.#rewind());\n *\n * connect() { this.#beforeCache.activate(); }\n * disconnect() { this.#beforeCache.deactivate(); }\n * ```\n */\nexport class BeforeCacheReset {\n /** Every subscribed instance, iterated by the one shared document listener. */\n static readonly #subscribers = new Set<BeforeCacheReset>();\n\n /** The shared listener; installed while at least one instance is subscribed. */\n static readonly #onBeforeCache = (): void => {\n for (const subscriber of BeforeCacheReset.#subscribers) subscriber.#rewind();\n };\n\n readonly #rewind: () => void;\n\n /** @param rewind - the pass that returns this controller's state to its initial form. */\n constructor(rewind: () => void) {\n this.#rewind = rewind;\n }\n\n /** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */\n activate(): void {\n const first = BeforeCacheReset.#subscribers.size === 0;\n BeforeCacheReset.#subscribers.add(this);\n if (first) {\n document.addEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n }\n\n /** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */\n deactivate(): void {\n BeforeCacheReset.#subscribers.delete(this);\n if (BeforeCacheReset.#subscribers.size > 0) return;\n document.removeEventListener(\"turbo:before-cache\", BeforeCacheReset.#onBeforeCache);\n }\n}\n","import { BeforeCacheReset } from \"./before_cache_reset\";\n\n/**\n * Shared bookkeeping for a `tabindex` a controller lends an element temporarily.\n *\n * A controller that must move focus somewhere the author never made focusable\n * (a landmark root, a scroll destination) reaches for the same trick: add a\n * `tabindex` just-in-time and hand it back once it is no longer needed. The\n * borrow is the easy half; the return is what the two conditions below are for.\n *\n * **Returning needs two conditions, not one.** Owning the borrow is not enough:\n * the attribute must also still hold the value this instance wrote. A consumer\n * that changed it afterwards — `tabindex=\"0\"` to make the root its own Tab stop\n * — owns it now, and removing it there silently discards authored markup. The\n * bookkeeping is dropped either way, since the loan is over regardless of who\n * ends up owning the value.\n *\n * **Never borrow over an existing value.** An element that already carries a\n * `tabindex` is the author's to control, so there is nothing to lend and nothing\n * to return.\n *\n * Every live loan also owns a shared `turbo:before-cache` subscription. The loan\n * is returned before Turbo can copy it into a snapshot, so consumers get cache\n * safety without duplicating a lifecycle hook; `returnAll()` removes the\n * subscription again as soon as no loan remains.\n *\n * The registry is keyed by element, so a controller borrowing on a single\n * element (`this.element`) and one borrowing across a changing set of targets\n * use the same API — the single-element case is a set of one. It holds no\n * opinion about *when* to borrow or where focus goes next; that stays in the\n * controller.\n *\n * **The API is deliberately two methods.** This file's own doc block is dropped\n * from `dist`, but every member comment is inlined into **each** consumer entry\n * (`tsup` builds with `splitting: false`), so rationale belongs here, only the\n * contract belongs on the members, and every method no consumer calls is still\n * paid for once per consumer entry.\n *\n * @example\n * ```ts\n * readonly #tabindex = new TabindexLoan();\n *\n * #rescueFocus() {\n * this.#tabindex.lend(this.element);\n * this.element.focus();\n * }\n *\n * disconnect() {\n * this.#tabindex.returnAll();\n * }\n * ```\n */\nexport class TabindexLoan<T extends HTMLElement = HTMLElement> {\n readonly #value: string;\n readonly #lent = new Set<T>();\n /** Returns live loans before Turbo can copy them into its page snapshot. */\n readonly #beforeCache = new BeforeCacheReset(() => this.returnAll());\n\n /**\n * @param value - the `tabindex` to lend. `\"-1\"` (the default) is\n * programmatically focusable but not a Tab stop; `\"0\"` is a real Tab stop,\n * which a scroll region with no focusable content of its own needs.\n */\n constructor(value: string = \"-1\") {\n this.#value = value;\n }\n\n /** Lends `element` the value; no-ops when it already carries a `tabindex`. */\n lend(element: T): void {\n if (element.hasAttribute(\"tabindex\")) return;\n element.setAttribute(\"tabindex\", this.#value);\n this.#lent.add(element);\n // Subscribe only while a real loan exists. Keeping this guarantee here means\n // every consumer is Turbo-safe without another lifecycle hook to remember.\n this.#beforeCache.activate();\n }\n\n /** Takes back every loan whose value is still the one that was lent. */\n returnAll(): void {\n for (const element of this.#lent) {\n if (element.getAttribute(\"tabindex\") === this.#value) element.removeAttribute(\"tabindex\");\n }\n this.#lent.clear();\n this.#beforeCache.deactivate();\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { canTakeFocus } from \"../utils/focus_candidate\";\nimport { TabindexLoan } from \"../utils/tabindex_loan\";\n\n/**\n * Headless, accessible pagination behavior.\n *\n * Markup contract (identifier: `stimeo--pagination`):\n * <nav data-controller=\"stimeo--pagination\" aria-label=\"Pagination\"\n * data-stimeo--pagination-page-value=\"1\"\n * data-stimeo--pagination-total-value=\"5\">\n * <button type=\"button\" data-stimeo--pagination-target=\"prev\"\n * data-action=\"click->stimeo--pagination#prev\">Prev</button>\n * <button type=\"button\" data-page=\"1\" aria-current=\"page\"\n * data-stimeo--pagination-target=\"page\"\n * data-action=\"click->stimeo--pagination#select\">1</button>\n * <!-- more page buttons -->\n * <button type=\"button\" data-stimeo--pagination-target=\"next\"\n * data-action=\"click->stimeo--pagination#next\">Next</button>\n * </nav>\n *\n * There is no dedicated APG pattern; this uses a navigation landmark plus\n * `aria-current=\"page\"`. The controller owns current-page state, the\n * `aria-current` sync, boundary disabling of prev/next, and the change event.\n * Generating/eliding the page buttons and fetching data stay with the consumer.\n *\n * `prev`/`next` must be real `<button>` elements: the boundary state is applied\n * through the native `disabled` property, which no other element honors.\n *\n * `change` dispatches `{ page: number, total: number, previous: number }`.\n *\n * @remarks\n * Behavior only — each control is in the natural Tab order (no roving). When a\n * boundary disables the button that currently has focus, focus is moved first so\n * it is never lost to a `disabled` element.\n *\n * Behavior provided:\n * - `select` reads the clicked button's `data-page` and makes it current. The\n * value must parse as an integer; blank/fractional/non-numeric ones are ignored.\n * - `prev`/`next` step by one, clamped to `[1, total]`.\n * - The current page button gets `aria-current=\"page\"` (removed from the rest);\n * `prev` is `disabled` at page 1 and `next` at `total`.\n * - `page`/`total` are normalized (`total` to a finite integer >= 1, `page` into\n * `[1, total]`) on connect **and** on every runtime Value change, so JS-driven\n * updates re-render. Normalization never dispatches `change`: it is a display\n * correction, not a user navigation, and the initial render is consumer-owned.\n * - Page/boundary buttons swapped in at runtime re-render through the Stimulus\n * target callbacks, so a consumer-regenerated button list stays in sync.\n * - Every navigation dispatches `stimeo--pagination:change`, whose `detail.total`\n * is the same normalized total the boundary state is derived from.\n *\n * The boundary `disabled` is **owned**: the controller marks what it disabled\n * with `data-stimeo--pagination-boundary-disabled` and releases only that. A\n * button already disabled by the consumer is never marked when it overlaps a\n * boundary, so loading / permission state survives both entering and leaving the\n * boundary. The marker lives in the DOM rather than in a field so ownership\n * survives a Turbo cache restore, where a fresh instance would otherwise either\n * strand or steal the flag.\n */\nexport class PaginationController extends Controller<HTMLElement> {\n static override targets = [\"page\", \"prev\", \"next\"];\n static override values = {\n page: { type: Number, default: 1 },\n total: { type: Number, default: 1 },\n };\n static actions = [\"next\", \"prev\", \"select\"] as const;\n static events = [\"change\"] as const;\n\n /** Marks a `disabled` this controller applied at a boundary (ownership flag). */\n static readonly #BOUNDARY_ATTR = \"data-stimeo--pagination-boundary-disabled\";\n\n declare readonly pageTargets: HTMLElement[];\n declare readonly prevTarget: HTMLButtonElement;\n declare readonly nextTarget: HTMLButtonElement;\n declare readonly hasPrevTarget: boolean;\n declare readonly hasNextTarget: boolean;\n declare pageValue: number;\n declare totalValue: number;\n\n #isConnected = false;\n /** The `tabindex` this instance lends the root for the focus fallback. */\n readonly #tabindex = new TabindexLoan();\n\n /** Normalizes out-of-range initial values and renders the initial state. */\n override connect(): void {\n this.#isConnected = true;\n this.#normalizeAndRender();\n }\n\n /** Reverts the one attribute the controller adds outside its state hooks. */\n override disconnect(): void {\n this.#isConnected = false;\n this.#tabindex.returnAll();\n }\n\n /** Re-renders when application code (or a Turbo morph) changes `page` at runtime. */\n pageValueChanged(): void {\n if (!this.#isConnected) return;\n this.#normalizeAndRender();\n }\n\n /** Re-renders when application code (or a Turbo morph) changes `total` at runtime. */\n totalValueChanged(): void {\n if (!this.#isConnected) return;\n this.#normalizeAndRender();\n }\n\n /** Syncs a page button appended/replaced at runtime (the consumer owns the list). */\n pageTargetConnected(): void {\n if (!this.#isConnected) return;\n this.#render();\n }\n\n /** Syncs a `prev` button appended/replaced at runtime. */\n prevTargetConnected(): void {\n if (!this.#isConnected) return;\n this.#render();\n }\n\n /** Syncs a `next` button appended/replaced at runtime. */\n nextTargetConnected(): void {\n if (!this.#isConnected) return;\n this.#render();\n }\n\n /** Makes the clicked page button (its `data-page`) current. */\n select(event: Event): void {\n const button = event.currentTarget as HTMLElement;\n const raw = button.dataset.page;\n if (raw === undefined || raw.trim() === \"\") return;\n const page = Number(raw);\n // Integer-only, matching `stimeo--stepper`: `Number(\"\")` is 0 and `Number(\"2.7\")`\n // truncates, so a bare finite check would accept meaningless page numbers.\n if (!Number.isInteger(page)) return;\n this.#goto(page);\n }\n\n /** Steps to the previous page. */\n prev(): void {\n this.#goto(this.#page - 1);\n }\n\n /** Steps to the next page. */\n next(): void {\n this.#goto(this.#page + 1);\n }\n\n /** Moves to `page` (clamped to `[1, total]`), re-renders, and dispatches `change`. */\n #goto(page: number): void {\n if (!Number.isFinite(page)) return;\n const previous = this.#page;\n const target = this.#clamp(page);\n if (target === previous) return;\n this.pageValue = target;\n this.#render();\n this.dispatch(\"change\", {\n detail: { page: target, total: this.#total, previous },\n });\n }\n\n /** Writes the normalized Values back (only when they differ) and renders. */\n #normalizeAndRender(): void {\n // Stimulus setters rewrite the data attribute unconditionally, so guard the\n // no-op case to avoid waking consumer MutationObservers for nothing.\n const total = this.#total;\n if (!Object.is(total, this.totalValue)) this.totalValue = total;\n const page = this.#page;\n if (!Object.is(page, this.pageValue)) this.pageValue = page;\n this.#render();\n }\n\n /**\n * Syncs `aria-current` on the page buttons and the prev/next `disabled` state.\n *\n * @stimeoRenderRoot\n */\n #render(): void {\n const page = this.#page;\n for (const button of this.pageTargets) {\n if (Number(button.dataset.page) === page) {\n button.setAttribute(\"aria-current\", \"page\");\n } else {\n button.removeAttribute(\"aria-current\");\n }\n }\n\n const prev = this.hasPrevTarget ? this.prevTarget : null;\n const next = this.hasNextTarget ? this.nextTarget : null;\n const atStart = page <= 1;\n const atEnd = page >= this.#total;\n // Resolve both post-render states up front: a focus hand-off must target the\n // opposite button as it will be *after* this pass, not as it is now (moving\n // between the two boundaries of a 2-page set re-enables it in the same pass).\n const prevStaysDisabled = this.#disabledAfter(prev, atStart);\n const nextStaysDisabled = this.#disabledAfter(next, atEnd);\n // Release before disabling, so the hand-off can land on a button this same\n // pass re-enables (focusing a still-`disabled` button is a no-op).\n this.#release(prev, atStart);\n this.#release(next, atEnd);\n this.#disable(prev, atStart, nextStaysDisabled ? null : next);\n this.#disable(next, atEnd, prevStaysDisabled ? null : prev);\n }\n\n /** Whether a boundary button will still be `disabled` once this render applies. */\n #disabledAfter(button: HTMLButtonElement | null, atBoundary: boolean): boolean {\n if (!button) return true;\n if (atBoundary) return true;\n // Away from a boundary, only the controller's own `disabled` is released.\n return button.disabled && !this.#owns(button);\n }\n\n /** Releases the boundary `disabled` this controller owns, once away from it. */\n #release(button: HTMLButtonElement | null, atBoundary: boolean): void {\n if (!button || atBoundary || !this.#owns(button)) return;\n button.disabled = false;\n button.removeAttribute(PaginationController.#BOUNDARY_ATTR);\n }\n\n /**\n * Disables a boundary button, first moving focus off it when it is the active\n * element so disabling never strands focus.\n */\n #disable(\n button: HTMLButtonElement | null,\n atBoundary: boolean,\n opposite: HTMLButtonElement | null,\n ): void {\n if (!button || !atBoundary) return;\n if (button.disabled && !this.#owns(button)) return;\n if (button === document.activeElement) this.#moveFocusAwayFrom(opposite);\n button.disabled = true;\n button.setAttribute(PaginationController.#BOUNDARY_ATTR, \"\");\n }\n\n /**\n * Moves focus to `opposite` (already resolved to `null` when it will stay\n * disabled), else to the current page button, else to the landmark itself.\n */\n #moveFocusAwayFrom(opposite: HTMLButtonElement | null): void {\n const page = this.#page;\n const currentPage = this.pageTargets.find(\n (candidate) => Number(candidate.dataset.page) === page,\n );\n // Checked before the call, never after: `hidden` and natively disabled\n // elements swallow `focus()` silently, so an unchecked destination leaves the\n // caret in the subtree that is about to disable and drops it to <body> a frame\n // later — the outcome this rescue exists to prevent.\n // Narrowed to `HTMLElement`, not `HTMLButtonElement`: `pageTargets` is typed\n // `HTMLElement[]`, so a page control can legitimately be an `<a>`. The\n // destination is only ever focused, so the wider type is the honest one.\n const destination = [opposite, currentPage].find(\n (candidate): candidate is HTMLElement => candidate != null && canTakeFocus(candidate),\n );\n if (destination) {\n destination.focus();\n return;\n }\n // Nothing left to hand focus to (a lone boundary button, or every page button\n // disabled): keep it inside the pagination landmark instead of letting the\n // browser drop it to <body> when the button disables. The root is made\n // programmatically focusable just-in-time with `tabindex=\"-1\"`, which is not a\n // Tab stop; `disconnect()` removes it again when this controller added it.\n this.#tabindex.lend(this.element);\n this.element.focus();\n }\n\n /** Total pages, normalized to a finite integer >= 1. */\n get #total(): number {\n const total = this.totalValue;\n return Number.isFinite(total) ? Math.max(1, Math.trunc(total)) : 1;\n }\n\n /** The current page, normalized into `[1, total]`. */\n get #page(): number {\n return this.#clamp(this.pageValue);\n }\n\n /** Constrains `page` to `[1, total]`; a non-finite page falls back to page 1. */\n #clamp(page: number): number {\n if (!Number.isFinite(page)) return 1;\n return Math.min(this.#total, Math.max(1, Math.trunc(page)));\n }\n\n /** Whether the button's current `disabled` was applied by boundary control. */\n #owns(button: HTMLButtonElement): boolean {\n return button.hasAttribute(PaginationController.#BOUNDARY_ATTR);\n }\n}\n"]}
|
|
@@ -16,6 +16,8 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
16
16
|
* accessible name stays state-independent ("Show password") while the pressed
|
|
17
17
|
* state is conveyed by `aria-pressed`.
|
|
18
18
|
*
|
|
19
|
+
* `toggle` dispatches `{ visible: boolean }`.
|
|
20
|
+
*
|
|
19
21
|
* @remarks
|
|
20
22
|
* Behavior only — icon rendering is the consumer's, keyed off `aria-pressed` /
|
|
21
23
|
* `data-state` (`hidden` / `visible`). Flipping `input.type` can drop focus and
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/safe_timeout.ts","../../src/controllers/password_reveal_controller.ts"],"names":[],"mappings":";;;;;AAwBA,IAAe,gBAAf,MAA6B;AAAA;AAAA,EAER,GAAA,uBAAU,GAAA,EAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAczC,MAAM,EAAA,EAAkB;AACtB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,MAAA,CAAO,EAAE,CAAA,EAAG;AACvB,MAAA,IAAA,CAAK,OAAO,EAAE,CAAA;AAAA,IAChB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAA,GAAiB;AACf,IAAA,KAAA,MAAW,EAAA,IAAM,KAAK,GAAA,EAAK;AACzB,MAAA,IAAA,CAAK,OAAO,EAAE,CAAA;AAAA,IAChB;AACA,IAAA,IAAA,CAAK,IAAI,KAAA,EAAM;AAAA,EACjB;AAAA;AAAA,EAGA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,KAAK,GAAA,CAAI,IAAA;AAAA,EAClB;AACF,CAAA;AAmBO,IAAM,WAAA,GAAN,cAA0B,aAAA,CAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO7C,GAAA,CAAI,UAAsB,KAAA,EAAuB;AAC/C,IAAA,MAAM,EAAA,GAAK,IAAA,CAAK,QAAA,CAAS,MAAM;AAC7B,MAAA,IAAA,CAAK,GAAA,CAAI,OAAO,EAAE,CAAA;AAClB,MAAA,QAAA,EAAS;AAAA,IACX,GAAG,KAAK,CAAA;AACR,IAAA,IAAA,CAAK,GAAA,CAAI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,KAAkB,KAAA;AACrD,IAAA,MAAM,iBAAiB,KAAA,CAAM,cAAA;AAC7B,IAAA,MAAM,eAAe,KAAA,CAAM,YAAA;AAE3B,IAAA,KAAA,CAAM,IAAA,GAAO,UAAU,MAAA,GAAS,UAAA;AAEhC,IAAA,IAAI,iBAAA,EAAmB;AACrB,MAAA,KAAA,CAAM,KAAA,EAAM;AAGZ,MAAA,IAAI,cAAA,KAAmB,IAAA,IAAQ,YAAA,KAAiB,IAAA,EAAM;AACpD,QAAA,IAAI;AACF,UAAA,KAAA,CAAM,iBAAA,CAAkB,gBAAgB,YAAY,CAAA;AAAA,QACtD,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF;AAEA,IAAA,IAAA,CAAK,SAAS,OAAO,CAAA;AACrB,IAAA,IAAA,CAAK,SAAS,QAAA,EAAU,EAAE,QAAQ,EAAE,OAAA,IAAW,CAAA;AAE/C,IAAA,IAAA,CAAK,QAAQ,QAAA,EAAS;AACtB,IAAA,IAAI,OAAA,IAAW,IAAA,CAAK,aAAA,GAAgB,CAAA,EAAG;AACrC,MAAA,IAAA,CAAK,OAAA,CAAQ,IAAI,MAAM,IAAA,CAAK,YAAY,KAAK,CAAA,EAAG,KAAK,aAAa,CAAA;AAAA,IACpE;AAAA,EACF;AAAA;AAAA,EAGA,SAAS,OAAA,EAAwB;AAC/B,IAAA,IAAI,KAAK,eAAA,EAAiB;AACxB,MAAA,IAAA,CAAK,YAAA,CAAa,YAAA,CAAa,cAAA,EAAgB,OAAA,GAAU,SAAS,OAAO,CAAA;AAAA,IAC3E;AACA,IAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,YAAA,EAAc,OAAA,GAAU,YAAY,QAAQ,CAAA;AAAA,EACxE;AACF","file":"password_reveal_controller.js","sourcesContent":["/**\n * Self-cleaning timer registries shared by Stimeo controllers.\n *\n * Stimulus controllers frequently schedule `setTimeout` / `setInterval` work\n * (auto-dismiss, debouncing, polling). When the element leaves the DOM — a\n * Turbo Drive navigation, a Turbo Stream replacement, or any `disconnect()` —\n * orphaned timers keep firing against a detached controller, leaking memory and\n * mutating stale state. {@link SafeTimeout} and {@link SafeInterval} track every\n * timer they create so a single {@link TimerRegistry.clearAll | clearAll()} call\n * in `disconnect()` tears them all down.\n *\n * These are intentionally low-level primitives: they own *registration and\n * cleanup only*. Higher-level policy (pause/resume, remaining-time accounting)\n * stays in the individual controllers so per-widget semantics are not flattened\n * into a lowest-common-denominator helper.\n */\n\n/**\n * Shared registry bookkeeping for the timeout/interval variants.\n *\n * Subclasses provide the scheduling primitive ({@link schedule}) and its matching\n * canceller ({@link cancel}); this base owns the set of live ids plus the\n * per-id and bulk teardown shared by both.\n */\nabstract class TimerRegistry {\n /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */\n protected readonly ids = new Set<number>();\n\n /** Schedules the underlying platform timer and returns its id. */\n protected abstract schedule(callback: () => void, delay: number): number;\n\n /** Cancels the underlying platform timer for `id`. */\n protected abstract cancel(id: number): void;\n\n /**\n * Cancels a single tracked timer.\n *\n * No-ops if the id is unknown (already cleared, fired, or never owned by this\n * registry), so callers can clear defensively without guarding.\n */\n clear(id: number): void {\n if (this.ids.delete(id)) {\n this.cancel(id);\n }\n }\n\n /**\n * Cancels every tracked timer. Call this from a controller's `disconnect()`\n * to guarantee no timer outlives the element.\n */\n clearAll(): void {\n for (const id of this.ids) {\n this.cancel(id);\n }\n this.ids.clear();\n }\n\n /** Number of timers currently tracked (pending). */\n get size(): number {\n return this.ids.size;\n }\n}\n\n/**\n * `setTimeout` wrapper that auto-forgets each timer once it fires and supports\n * bulk teardown on disconnect.\n *\n * @example\n * ```ts\n * #timers = new SafeTimeout();\n *\n * connect() {\n * this.#timers.set(() => this.dismiss(), 5000);\n * }\n *\n * disconnect() {\n * this.#timers.clearAll();\n * }\n * ```\n */\nexport class SafeTimeout extends TimerRegistry {\n /**\n * Schedules `callback` after `delay` ms and returns the timer id.\n *\n * The id is removed from the registry automatically when the timeout fires,\n * so {@link TimerRegistry.size | size} reflects only still-pending timers.\n */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(() => {\n this.ids.delete(id);\n callback();\n }, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setTimeout(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearTimeout(id);\n }\n}\n\n/**\n * `setInterval` wrapper that tracks every interval for bulk teardown on\n * disconnect. Unlike {@link SafeTimeout}, intervals are retained until they are\n * explicitly cleared because they fire repeatedly.\n *\n * @example\n * ```ts\n * #intervals = new SafeInterval();\n *\n * connect() {\n * this.#intervals.set(() => this.tick(), 1000);\n * }\n *\n * disconnect() {\n * this.#intervals.clearAll();\n * }\n * ```\n */\nexport class SafeInterval extends TimerRegistry {\n /** Schedules a repeating `callback` every `delay` ms and returns the timer id. */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(callback, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setInterval(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearInterval(id);\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/**\n * Headless password show/hide (unmask) toggle behavior.\n *\n * Markup contract (identifier: `stimeo--password-reveal`):\n * <div data-controller=\"stimeo--password-reveal\">\n * <input type=\"password\" aria-label=\"Password\"\n * data-stimeo--password-reveal-target=\"input\">\n * <button type=\"button\" aria-pressed=\"false\" aria-label=\"Show password\"\n * data-stimeo--password-reveal-target=\"toggle\"\n * data-action=\"stimeo--password-reveal#toggle\"></button>\n * </div>\n *\n * No dedicated APG pattern; this follows the toggle **Button** practice. The\n * accessible name stays state-independent (\"Show password\") while the pressed\n * state is conveyed by `aria-pressed`.\n *\n * @remarks\n * Behavior only — icon rendering is the consumer's, keyed off `aria-pressed` /\n * `data-state` (`hidden` / `visible`). Flipping `input.type` can drop focus and\n * the caret, so when (and only when) the input was the focused element its focus\n * and selection are restored afterward; when the toggle button holds focus\n * (keyboard use) focus is left on the button. An optional `autoHide` re-masks\n * after a delay, and that timer is torn down on disconnect (Turbo).\n */\nexport class PasswordRevealController extends Controller<HTMLElement> {\n static override targets = [\"input\", \"toggle\"];\n static override values = {\n autoHide: { type: Number, default: 0 },\n };\n static actions = [\"toggle\"] as const;\n static events = [\"toggle\"] as const;\n\n declare readonly inputTarget: HTMLInputElement;\n declare readonly toggleTarget: HTMLElement;\n declare readonly hasInputTarget: boolean;\n declare readonly hasToggleTarget: boolean;\n\n declare autoHideValue: number;\n\n /** Auto re-mask timer; torn down on disconnect. */\n #timers = new SafeTimeout();\n\n override connect(): void {\n this.#reflect(this.#isVisible);\n }\n\n override disconnect(): void {\n this.#timers.clearAll();\n }\n\n /** Toggles the input between masked and revealed. Bound via `data-action`. */\n toggle(): void {\n this.#setVisible(!this.#isVisible);\n }\n\n /** Whether the input is currently revealed (`type=\"text\"`). */\n get #isVisible(): boolean {\n return this.hasInputTarget && this.inputTarget.type === \"text\";\n }\n\n /** Switches the masked/revealed state, preserving focus and caret. */\n #setVisible(visible: boolean): void {\n if (!this.hasInputTarget) return;\n const input = this.inputTarget;\n\n // Only the input's *own* focus is restored across the type change; if the\n // toggle button (keyboard) holds focus, it is left untouched.\n const restoreInputFocus = document.activeElement === input;\n const selectionStart = input.selectionStart;\n const selectionEnd = input.selectionEnd;\n\n input.type = visible ? \"text\" : \"password\";\n\n if (restoreInputFocus) {\n input.focus();\n // `selectionStart` / `selectionEnd` are `number | null` (null for input\n // types that don't expose a selection); only restore when both are present.\n if (selectionStart !== null && selectionEnd !== null) {\n try {\n input.setSelectionRange(selectionStart, selectionEnd);\n } catch {\n // Some input types reject selection access; focus alone is enough.\n }\n }\n }\n\n this.#reflect(visible);\n this.dispatch(\"toggle\", { detail: { visible } });\n\n this.#timers.clearAll();\n if (visible && this.autoHideValue > 0) {\n this.#timers.set(() => this.#setVisible(false), this.autoHideValue);\n }\n }\n\n /** Reflects the visible state onto `aria-pressed` and `data-state`. */\n #reflect(visible: boolean): void {\n if (this.hasToggleTarget) {\n this.toggleTarget.setAttribute(\"aria-pressed\", visible ? \"true\" : \"false\");\n }\n this.element.setAttribute(\"data-state\", visible ? \"visible\" : \"hidden\");\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/safe_timeout.ts","../../src/controllers/password_reveal_controller.ts"],"names":[],"mappings":";;;;;AAwBA,IAAe,gBAAf,MAA6B;AAAA;AAAA,EAER,GAAA,uBAAU,GAAA,EAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAczC,MAAM,EAAA,EAAkB;AACtB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,MAAA,CAAO,EAAE,CAAA,EAAG;AACvB,MAAA,IAAA,CAAK,OAAO,EAAE,CAAA;AAAA,IAChB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAA,GAAiB;AACf,IAAA,KAAA,MAAW,EAAA,IAAM,KAAK,GAAA,EAAK;AACzB,MAAA,IAAA,CAAK,OAAO,EAAE,CAAA;AAAA,IAChB;AACA,IAAA,IAAA,CAAK,IAAI,KAAA,EAAM;AAAA,EACjB;AAAA;AAAA,EAGA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,KAAK,GAAA,CAAI,IAAA;AAAA,EAClB;AACF,CAAA;AAmBO,IAAM,WAAA,GAAN,cAA0B,aAAA,CAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO7C,GAAA,CAAI,UAAsB,KAAA,EAAuB;AAC/C,IAAA,MAAM,EAAA,GAAK,IAAA,CAAK,QAAA,CAAS,MAAM;AAC7B,MAAA,IAAA,CAAK,GAAA,CAAI,OAAO,EAAE,CAAA;AAClB,MAAA,QAAA,EAAS;AAAA,IACX,GAAG,KAAK,CAAA;AACR,IAAA,IAAA,CAAK,GAAA,CAAI,IAAI,EAAE,CAAA;AACf,IAAA,OAAO,EAAA;AAAA,EACT;AAAA,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AAC7B,IAAA,MAAM,eAAe,KAAA,CAAM,YAAA;AAE3B,IAAA,KAAA,CAAM,IAAA,GAAO,UAAU,MAAA,GAAS,UAAA;AAEhC,IAAA,IAAI,iBAAA,EAAmB;AACrB,MAAA,KAAA,CAAM,KAAA,EAAM;AAGZ,MAAA,IAAI,cAAA,KAAmB,IAAA,IAAQ,YAAA,KAAiB,IAAA,EAAM;AACpD,QAAA,IAAI;AACF,UAAA,KAAA,CAAM,iBAAA,CAAkB,gBAAgB,YAAY,CAAA;AAAA,QACtD,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF;AAEA,IAAA,IAAA,CAAK,SAAS,OAAO,CAAA;AACrB,IAAA,IAAA,CAAK,SAAS,QAAA,EAAU,EAAE,QAAQ,EAAE,OAAA,IAAW,CAAA;AAE/C,IAAA,IAAA,CAAK,QAAQ,QAAA,EAAS;AACtB,IAAA,IAAI,OAAA,IAAW,IAAA,CAAK,aAAA,GAAgB,CAAA,EAAG;AACrC,MAAA,IAAA,CAAK,OAAA,CAAQ,IAAI,MAAM,IAAA,CAAK,YAAY,KAAK,CAAA,EAAG,KAAK,aAAa,CAAA;AAAA,IACpE;AAAA,EACF;AAAA;AAAA,EAGA,SAAS,OAAA,EAAwB;AAC/B,IAAA,IAAI,KAAK,eAAA,EAAiB;AACxB,MAAA,IAAA,CAAK,YAAA,CAAa,YAAA,CAAa,cAAA,EAAgB,OAAA,GAAU,SAAS,OAAO,CAAA;AAAA,IAC3E;AACA,IAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,YAAA,EAAc,OAAA,GAAU,YAAY,QAAQ,CAAA;AAAA,EACxE;AACF","file":"password_reveal_controller.js","sourcesContent":["/**\n * Self-cleaning timer registries shared by Stimeo controllers.\n *\n * Stimulus controllers frequently schedule `setTimeout` / `setInterval` work\n * (auto-dismiss, debouncing, polling). When the element leaves the DOM — a\n * Turbo Drive navigation, a Turbo Stream replacement, or any `disconnect()` —\n * orphaned timers keep firing against a detached controller, leaking memory and\n * mutating stale state. {@link SafeTimeout} and {@link SafeInterval} track every\n * timer they create so a single {@link TimerRegistry.clearAll | clearAll()} call\n * in `disconnect()` tears them all down.\n *\n * These are intentionally low-level primitives: they own *registration and\n * cleanup only*. Higher-level policy (pause/resume, remaining-time accounting)\n * stays in the individual controllers so per-widget semantics are not flattened\n * into a lowest-common-denominator helper.\n */\n\n/**\n * Shared registry bookkeeping for the timeout/interval variants.\n *\n * Subclasses provide the scheduling primitive ({@link schedule}) and its matching\n * canceller ({@link cancel}); this base owns the set of live ids plus the\n * per-id and bulk teardown shared by both.\n */\nabstract class TimerRegistry {\n /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */\n protected readonly ids = new Set<number>();\n\n /** Schedules the underlying platform timer and returns its id. */\n protected abstract schedule(callback: () => void, delay: number): number;\n\n /** Cancels the underlying platform timer for `id`. */\n protected abstract cancel(id: number): void;\n\n /**\n * Cancels a single tracked timer.\n *\n * No-ops if the id is unknown (already cleared, fired, or never owned by this\n * registry), so callers can clear defensively without guarding.\n */\n clear(id: number): void {\n if (this.ids.delete(id)) {\n this.cancel(id);\n }\n }\n\n /**\n * Cancels every tracked timer. Call this from a controller's `disconnect()`\n * to guarantee no timer outlives the element.\n */\n clearAll(): void {\n for (const id of this.ids) {\n this.cancel(id);\n }\n this.ids.clear();\n }\n\n /** Number of timers currently tracked (pending). */\n get size(): number {\n return this.ids.size;\n }\n}\n\n/**\n * `setTimeout` wrapper that auto-forgets each timer once it fires and supports\n * bulk teardown on disconnect.\n *\n * @example\n * ```ts\n * #timers = new SafeTimeout();\n *\n * connect() {\n * this.#timers.set(() => this.dismiss(), 5000);\n * }\n *\n * disconnect() {\n * this.#timers.clearAll();\n * }\n * ```\n */\nexport class SafeTimeout extends TimerRegistry {\n /**\n * Schedules `callback` after `delay` ms and returns the timer id.\n *\n * The id is removed from the registry automatically when the timeout fires,\n * so {@link TimerRegistry.size | size} reflects only still-pending timers.\n */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(() => {\n this.ids.delete(id);\n callback();\n }, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setTimeout(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearTimeout(id);\n }\n}\n\n/**\n * `setInterval` wrapper that tracks every interval for bulk teardown on\n * disconnect. Unlike {@link SafeTimeout}, intervals are retained until they are\n * explicitly cleared because they fire repeatedly.\n *\n * @example\n * ```ts\n * #intervals = new SafeInterval();\n *\n * connect() {\n * this.#intervals.set(() => this.tick(), 1000);\n * }\n *\n * disconnect() {\n * this.#intervals.clearAll();\n * }\n * ```\n */\nexport class SafeInterval extends TimerRegistry {\n /** Schedules a repeating `callback` every `delay` ms and returns the timer id. */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(callback, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setInterval(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearInterval(id);\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/**\n * Headless password show/hide (unmask) toggle behavior.\n *\n * Markup contract (identifier: `stimeo--password-reveal`):\n * <div data-controller=\"stimeo--password-reveal\">\n * <input type=\"password\" aria-label=\"Password\"\n * data-stimeo--password-reveal-target=\"input\">\n * <button type=\"button\" aria-pressed=\"false\" aria-label=\"Show password\"\n * data-stimeo--password-reveal-target=\"toggle\"\n * data-action=\"stimeo--password-reveal#toggle\"></button>\n * </div>\n *\n * No dedicated APG pattern; this follows the toggle **Button** practice. The\n * accessible name stays state-independent (\"Show password\") while the pressed\n * state is conveyed by `aria-pressed`.\n *\n * `toggle` dispatches `{ visible: boolean }`.\n *\n * @remarks\n * Behavior only — icon rendering is the consumer's, keyed off `aria-pressed` /\n * `data-state` (`hidden` / `visible`). Flipping `input.type` can drop focus and\n * the caret, so when (and only when) the input was the focused element its focus\n * and selection are restored afterward; when the toggle button holds focus\n * (keyboard use) focus is left on the button. An optional `autoHide` re-masks\n * after a delay, and that timer is torn down on disconnect (Turbo).\n */\nexport class PasswordRevealController extends Controller<HTMLElement> {\n static override targets = [\"input\", \"toggle\"];\n static override values = {\n autoHide: { type: Number, default: 0 },\n };\n static actions = [\"toggle\"] as const;\n static events = [\"toggle\"] as const;\n\n declare readonly inputTarget: HTMLInputElement;\n declare readonly toggleTarget: HTMLElement;\n declare readonly hasInputTarget: boolean;\n declare readonly hasToggleTarget: boolean;\n\n declare autoHideValue: number;\n\n /** Auto re-mask timer; torn down on disconnect. */\n #timers = new SafeTimeout();\n\n override connect(): void {\n this.#reflect(this.#isVisible);\n }\n\n override disconnect(): void {\n this.#timers.clearAll();\n }\n\n /** Toggles the input between masked and revealed. Bound via `data-action`. */\n toggle(): void {\n this.#setVisible(!this.#isVisible);\n }\n\n /** Whether the input is currently revealed (`type=\"text\"`). */\n get #isVisible(): boolean {\n return this.hasInputTarget && this.inputTarget.type === \"text\";\n }\n\n /** Switches the masked/revealed state, preserving focus and caret. */\n #setVisible(visible: boolean): void {\n if (!this.hasInputTarget) return;\n const input = this.inputTarget;\n\n // Only the input's *own* focus is restored across the type change; if the\n // toggle button (keyboard) holds focus, it is left untouched.\n const restoreInputFocus = document.activeElement === input;\n const selectionStart = input.selectionStart;\n const selectionEnd = input.selectionEnd;\n\n input.type = visible ? \"text\" : \"password\";\n\n if (restoreInputFocus) {\n input.focus();\n // `selectionStart` / `selectionEnd` are `number | null` (null for input\n // types that don't expose a selection); only restore when both are present.\n if (selectionStart !== null && selectionEnd !== null) {\n try {\n input.setSelectionRange(selectionStart, selectionEnd);\n } catch {\n // Some input types reject selection access; focus alone is enough.\n }\n }\n }\n\n this.#reflect(visible);\n this.dispatch(\"toggle\", { detail: { visible } });\n\n this.#timers.clearAll();\n if (visible && this.autoHideValue > 0) {\n this.#timers.set(() => this.#setVisible(false), this.autoHideValue);\n }\n }\n\n /** Reflects the visible state onto `aria-pressed` and `data-state`. */\n #reflect(visible: boolean): void {\n if (this.hasToggleTarget) {\n this.toggleTarget.setAttribute(\"aria-pressed\", visible ? \"true\" : \"false\");\n }\n this.element.setAttribute(\"data-state\", visible ? \"visible\" : \"hidden\");\n }\n}\n"]}
|
|
@@ -20,6 +20,8 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
20
20
|
* `--stimeo--password-strength`, and (when `minScore` is set) `data-below-min`,
|
|
21
21
|
* and writes the level label into the label target.
|
|
22
22
|
*
|
|
23
|
+
* `change` dispatches `{ score, level, max, meetsMin }`.
|
|
24
|
+
*
|
|
23
25
|
* @remarks
|
|
24
26
|
* Behavior only — the meter/bar look is the consumer's, keyed off the data hooks.
|
|
25
27
|
* `data-strength` is one of the fixed {@link STRENGTH_BANDS} (not the localizable
|
|
@@ -44,8 +46,8 @@ declare class PasswordStrengthController extends Controller<HTMLElement> {
|
|
|
44
46
|
default: number;
|
|
45
47
|
};
|
|
46
48
|
levels: {
|
|
47
|
-
type:
|
|
48
|
-
default: string
|
|
49
|
+
type: StringConstructor;
|
|
50
|
+
default: string;
|
|
49
51
|
};
|
|
50
52
|
};
|
|
51
53
|
static actions: readonly ["evaluate"];
|
|
@@ -57,7 +59,7 @@ declare class PasswordStrengthController extends Controller<HTMLElement> {
|
|
|
57
59
|
readonly hasMeterTarget: boolean;
|
|
58
60
|
readonly hasLabelTarget: boolean;
|
|
59
61
|
minScoreValue: number;
|
|
60
|
-
levelsValue: string
|
|
62
|
+
levelsValue: string;
|
|
61
63
|
connect(): void;
|
|
62
64
|
disconnect(): void;
|
|
63
65
|
/** Re-evaluates strength from the input. Bound via `data-action` (`input`). */
|
|
@@ -55,8 +55,23 @@ var SafeTimeout = class extends TimerRegistry {
|
|
|
55
55
|
}
|
|
56
56
|
};
|
|
57
57
|
|
|
58
|
+
// src/utils/string_list.ts
|
|
59
|
+
function parseStringList(raw, fallback = []) {
|
|
60
|
+
const text = raw.trim();
|
|
61
|
+
if (text.length === 0) return [...fallback];
|
|
62
|
+
let parsed;
|
|
63
|
+
try {
|
|
64
|
+
parsed = JSON.parse(text);
|
|
65
|
+
} catch {
|
|
66
|
+
return [...fallback];
|
|
67
|
+
}
|
|
68
|
+
if (!Array.isArray(parsed)) return [...fallback];
|
|
69
|
+
return parsed.filter((entry) => typeof entry === "string");
|
|
70
|
+
}
|
|
71
|
+
|
|
58
72
|
// src/controllers/password_strength_controller.ts
|
|
59
73
|
var CLASS_PATTERNS = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/];
|
|
74
|
+
var DEFAULT_LEVELS = ["weak", "fair", "good", "strong"];
|
|
60
75
|
var LENGTH_MILESTONES = [8, 12, 16];
|
|
61
76
|
var MAX_POINTS = LENGTH_MILESTONES.length + (CLASS_PATTERNS.length - 1);
|
|
62
77
|
var STRENGTH_BANDS = ["weak", "fair", "good", "strong"];
|
|
@@ -64,7 +79,10 @@ var PasswordStrengthController = class _PasswordStrengthController extends Contr
|
|
|
64
79
|
static targets = ["input", "meter", "label"];
|
|
65
80
|
static values = {
|
|
66
81
|
minScore: { type: Number, default: 0 },
|
|
67
|
-
|
|
82
|
+
// A JSON list read through `parseStringList` rather than Stimulus's `Array`
|
|
83
|
+
// type: that reader throws out of the value observer before any callback
|
|
84
|
+
// runs, so one malformed attribute would stop the meter connecting.
|
|
85
|
+
levels: { type: String, default: "" }
|
|
68
86
|
};
|
|
69
87
|
static actions = ["evaluate"];
|
|
70
88
|
static events = ["change"];
|
|
@@ -90,7 +108,7 @@ var PasswordStrengthController = class _PasswordStrengthController extends Contr
|
|
|
90
108
|
*/
|
|
91
109
|
#update(options = {}) {
|
|
92
110
|
const password = this.hasInputTarget ? this.inputTarget.value : "";
|
|
93
|
-
const labels = this.levelsValue;
|
|
111
|
+
const labels = parseStringList(this.levelsValue, DEFAULT_LEVELS);
|
|
94
112
|
const max = labels.length;
|
|
95
113
|
const score = this.#score(password, max);
|
|
96
114
|
const label = score > 0 ? labels[score - 1] ?? "" : "";
|
|
@@ -1 +1 @@
|
|
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Q,CAAC,CAAA;AAAA,EAC5C;AACF","file":"password_strength_controller.js","sourcesContent":["/**\n * Self-cleaning timer registries shared by Stimeo controllers.\n *\n * Stimulus controllers frequently schedule `setTimeout` / `setInterval` work\n * (auto-dismiss, debouncing, polling). When the element leaves the DOM — a\n * Turbo Drive navigation, a Turbo Stream replacement, or any `disconnect()` —\n * orphaned timers keep firing against a detached controller, leaking memory and\n * mutating stale state. {@link SafeTimeout} and {@link SafeInterval} track every\n * timer they create so a single {@link TimerRegistry.clearAll | clearAll()} call\n * in `disconnect()` tears them all down.\n *\n * These are intentionally low-level primitives: they own *registration and\n * cleanup only*. Higher-level policy (pause/resume, remaining-time accounting)\n * stays in the individual controllers so per-widget semantics are not flattened\n * into a lowest-common-denominator helper.\n */\n\n/**\n * Shared registry bookkeeping for the timeout/interval variants.\n *\n * Subclasses provide the scheduling primitive ({@link schedule}) and its matching\n * canceller ({@link cancel}); this base owns the set of live ids plus the\n * per-id and bulk teardown shared by both.\n */\nabstract class TimerRegistry {\n /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */\n protected readonly ids = new Set<number>();\n\n /** Schedules the underlying platform timer and returns its id. */\n protected abstract schedule(callback: () => void, delay: number): number;\n\n /** Cancels the underlying platform timer for `id`. */\n protected abstract cancel(id: number): void;\n\n /**\n * Cancels a single tracked timer.\n *\n * No-ops if the id is unknown (already cleared, fired, or never owned by this\n * registry), so callers can clear defensively without guarding.\n */\n clear(id: number): void {\n if (this.ids.delete(id)) {\n this.cancel(id);\n }\n }\n\n /**\n * Cancels every tracked timer. Call this from a controller's `disconnect()`\n * to guarantee no timer outlives the element.\n */\n clearAll(): void {\n for (const id of this.ids) {\n this.cancel(id);\n }\n this.ids.clear();\n }\n\n /** Number of timers currently tracked (pending). */\n get size(): number {\n return this.ids.size;\n }\n}\n\n/**\n * `setTimeout` wrapper that auto-forgets each timer once it fires and supports\n * bulk teardown on disconnect.\n *\n * @example\n * ```ts\n * #timers = new SafeTimeout();\n *\n * connect() {\n * this.#timers.set(() => this.dismiss(), 5000);\n * }\n *\n * disconnect() {\n * this.#timers.clearAll();\n * }\n * ```\n */\nexport class SafeTimeout extends TimerRegistry {\n /**\n * Schedules `callback` after `delay` ms and returns the timer id.\n *\n * The id is removed from the registry automatically when the timeout fires,\n * so {@link TimerRegistry.size | size} reflects only still-pending timers.\n */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(() => {\n this.ids.delete(id);\n callback();\n }, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setTimeout(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearTimeout(id);\n }\n}\n\n/**\n * `setInterval` wrapper that tracks every interval for bulk teardown on\n * disconnect. Unlike {@link SafeTimeout}, intervals are retained until they are\n * explicitly cleared because they fire repeatedly.\n *\n * @example\n * ```ts\n * #intervals = new SafeInterval();\n *\n * connect() {\n * this.#intervals.set(() => this.tick(), 1000);\n * }\n *\n * disconnect() {\n * this.#intervals.clearAll();\n * }\n * ```\n */\nexport class SafeInterval extends TimerRegistry {\n /** Schedules a repeating `callback` every `delay` ms and returns the timer id. */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(callback, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setInterval(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearInterval(id);\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/** Character classes that contribute to password variety (one point each beyond the first). */\nconst CLASS_PATTERNS: readonly RegExp[] = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/];\n\n/** Length milestones that each add a strength point. */\nconst LENGTH_MILESTONES: readonly number[] = [8, 12, 16];\n\n/** Upper bound of the raw heuristic points, used to bucket into the level scale. */\nconst MAX_POINTS = LENGTH_MILESTONES.length + (CLASS_PATTERNS.length - 1);\n\n/**\n * Fixed, locale-independent styling bands `data-strength` is drawn from. Kept\n * separate from the (localizable) `levels` labels so `data-strength` stays a\n * stable CSS hook (e.g. `[data-strength=\"weak\"]`) even when `levels` is\n * translated. Ascending: weakest → strongest.\n */\nconst STRENGTH_BANDS = [\"weak\", \"fair\", \"good\", \"strong\"] as const;\n\n/**\n * Headless password-strength behavior: scores the field with a lightweight\n * zero-dependency heuristic and drives a meter plus an `aria-live` label. No\n * dedicated APG pattern; the meter display follows {@link MeterController}.\n *\n * Markup contract (identifier: `stimeo--password-strength`):\n * <div data-controller=\"stimeo--password-strength\">\n * <input type=\"password\" data-stimeo--password-strength-target=\"input\"\n * data-action=\"input->stimeo--password-strength#evaluate\" aria-describedby=\"pw\">\n * <div data-stimeo--password-strength-target=\"meter\" role=\"meter\"\n * aria-valuemin=\"0\" aria-valuemax=\"4\"></div>\n * <span id=\"pw\" data-stimeo--password-strength-target=\"label\" aria-live=\"polite\"></span>\n * </div>\n *\n * On each input the controller scores the password (length milestones + character\n * variety, capped for trivial repetition), syncs the meter's `aria-valuenow`,\n * reflects a stable band on `data-strength`, the `0–1` fill on\n * `--stimeo--password-strength`, and (when `minScore` is set) `data-below-min`,\n * and writes the level label into the label target.\n *\n * @remarks\n * Behavior only — the meter/bar look is the consumer's, keyed off the data hooks.\n * `data-strength` is one of the fixed {@link STRENGTH_BANDS} (not the localizable\n * `levels` text), so consumers can style by it regardless of locale; the visible\n * label receives the matching `levels` entry. Non-text state (meter ARIA,\n * `data-strength`/`data-below-min`, the custom property, and the `change` event)\n * updates **immediately** on every keystroke so styling and consumers stay\n * responsive, while the label — in an `aria-live=\"polite\"` region — is written on\n * a short debounce so a screen reader is not flooded mid-typing. The score is a\n * pure function of the input value (no module-scope state), so `connect()`\n * re-evaluates idempotently after a Turbo cache restore; the debounce timer is\n * owned by {@link SafeTimeout} and torn down on `disconnect()` (Turbo included).\n * The estimator is intentionally not a dictionary/zxcvbn-grade one (kept\n * zero-dep); swap a stronger one in on the consumer side if needed.\n */\nexport class PasswordStrengthController extends Controller<HTMLElement> {\n static override targets = [\"input\", \"meter\", \"label\"];\n static override values = {\n minScore: { type: Number, default: 0 },\n levels: { type: Array, default: [\"weak\", \"fair\", \"good\", \"strong\"] },\n };\n static actions = [\"evaluate\"] as const;\n static events = [\"change\"] as const;\n\n declare readonly inputTarget: HTMLInputElement;\n declare readonly meterTarget: HTMLElement;\n declare readonly labelTarget: HTMLElement;\n declare readonly hasInputTarget: boolean;\n declare readonly hasMeterTarget: boolean;\n declare readonly hasLabelTarget: boolean;\n\n declare minScoreValue: number;\n declare levelsValue: string[];\n\n /** Delay (ms) before the polite live-region label is written, to throttle SR flooding. */\n static readonly #announceDelay = 200;\n\n readonly #timers = new SafeTimeout();\n #announceId: number | null = null;\n\n override connect(): void {\n // Reflect the current value synchronously (no announce): an autofilled or\n // cache-restored field shows the right strength without queuing an SR message.\n this.#update({ announce: false });\n }\n\n override disconnect(): void {\n this.#timers.clearAll();\n this.#announceId = null;\n }\n\n /** Re-evaluates strength from the input. Bound via `data-action` (`input`). */\n evaluate(): void {\n this.#update();\n }\n\n /**\n * Recomputes the strength. The meter ARIA, data hooks, the custom property and\n * the `change` event apply immediately; the live-region label text is debounced\n * unless `announce` is `false` (the initial render).\n */\n #update(options: { announce?: boolean } = {}): void {\n const password = this.hasInputTarget ? this.inputTarget.value : \"\";\n const labels = this.levelsValue;\n const max = labels.length;\n const score = this.#score(password, max);\n const label = score > 0 ? (labels[score - 1] ?? \"\") : \"\";\n\n this.#reflectMeter(score, max);\n this.#reflectRoot(score, max);\n\n if (options.announce === false) {\n // Initial render (connect / cache-restore): reflect without a change event\n // or a queued screen-reader announcement.\n this.#writeLabel(label);\n return;\n }\n\n this.dispatch(\"change\", {\n detail: { score, level: label, max, meetsMin: score > 0 && score >= this.minScoreValue },\n });\n\n if (this.#announceId !== null) this.#timers.clear(this.#announceId);\n this.#announceId = this.#timers.set(() => {\n this.#writeLabel(label);\n this.#announceId = null;\n }, PasswordStrengthController.#announceDelay);\n }\n\n /** Syncs the meter target's ARIA value attributes (`0..levels.length`). */\n #reflectMeter(score: number, max: number): void {\n if (!this.hasMeterTarget) return;\n this.meterTarget.setAttribute(\"aria-valuemin\", \"0\");\n this.meterTarget.setAttribute(\"aria-valuemax\", String(max));\n this.meterTarget.setAttribute(\"aria-valuenow\", String(score));\n }\n\n /**\n * Reflects the level onto the root: the stable `data-strength` band (absent when\n * empty), the `data-below-min` hook when the score is under `minScore`, and the\n * `0–1` fill the consumer's CSS turns into the bar width.\n */\n #reflectRoot(score: number, max: number): void {\n const band = this.#band(score, max);\n this.#toggle(\"data-strength\", band, band.length > 0);\n // Empty/pristine input (`score === 0`) is never \"below min\": that would let CSS\n // flag an untouched field as failing. Mirror the `change` event's `meetsMin`\n // (`score > 0 && …`) so the hook only marks a *non-empty* password under the\n // threshold. `minScore` defaults to 0, leaving the hook inert until set positive.\n this.#toggle(\"data-below-min\", \"true\", score > 0 && score < this.minScoreValue);\n const ratio = max > 0 ? score / max : 0;\n this.element.style.setProperty(\"--stimeo--password-strength\", String(ratio));\n }\n\n #writeLabel(label: string): void {\n if (this.hasLabelTarget) this.labelTarget.textContent = label;\n }\n\n /**\n * Locale-independent styling band (one of {@link STRENGTH_BANDS}) for `score`\n * out of `max`. Empty input → `\"\"`. Quantizes the `score/max` ratio into the\n * four fixed bands, so a non-default level count still maps onto a stable hook.\n */\n #band(score: number, max: number): string {\n if (score <= 0 || max <= 0) return \"\";\n const index = Math.ceil((score / max) * STRENGTH_BANDS.length) - 1;\n return STRENGTH_BANDS[Math.min(STRENGTH_BANDS.length - 1, Math.max(0, index))] ?? \"\";\n }\n\n /** Sets `name` to `value` when `on`, else removes it (value/presence data hook). */\n #toggle(name: string, value: string, on: boolean): void {\n if (on) {\n this.element.setAttribute(name, value);\n } else {\n this.element.removeAttribute(name);\n }\n }\n\n /**\n * Lightweight zero-dependency strength heuristic returning an integer in\n * `[0, max]` (`max` = number of levels). Empty input is `0` (no level); any\n * non-empty password is at least `1`. Points accrue from length milestones and\n * character-class variety, then bucket into the level scale. A tiny alphabet\n * (≤ 2 distinct characters, e.g. \"aaaa\") is capped as the weakest, so length\n * alone cannot mask trivial repetition.\n */\n #score(password: string, max: number): number {\n if (password.length === 0 || max === 0) return 0;\n\n let points = 0;\n for (const milestone of LENGTH_MILESTONES) {\n if (password.length >= milestone) points += 1;\n }\n // The first present character class is free; each additional one adds a point.\n points += CLASS_PATTERNS.filter((re) => re.test(password)).length - 1;\n\n if (new Set(password).size <= 2) points = 0; // trivial repetition → weakest\n\n const bucketed = Math.round((points / MAX_POINTS) * max);\n return Math.min(max, Math.max(1, bucketed));\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/safe_timeout.ts","../../src/utils/string_list.ts","../../src/controllers/password_strength_controller.ts"],"names":[],"mappings":";;;;;AAwBA,IAAe,gBAAf,MAA6B;AAAA;AAAA,EAER,GAAA,uBAAU,GAAA,EAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAczC,MAAM,EAAA,EAAkB;AACtB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,MAAA,CAAO,EAAE,CAAA,EAAG;AACvB,MAAA,IAAA,CAAK,OAAO,EAAE,CAAA;AAAA,IAChB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAA,GAAiB;AACf,IAAA,KAAA,MAAW,EAAA,IAAM,KAAK,GAAA,EAAK;AACzB,MAAA,IAAA,CAAK,OAAO,EAAE,CAAA;AAAA,IAChB;AACA,IAAA,IAAA,CAAK,IAAI,KAAA,EAAM;AAAA,EACjB;AAAA;AAAA,EAGA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,KAAK,GAAA,CAAI,IAAA;AAAA,EAClB;AACF,CAAA;AAmBO,IAAM,WAAA,GAAN,cAA0B,aAAA,CAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO7C,GAAA,CAAI,UAAsB,KAAA,EAAuB;AAC/C,IAAA,MAAM,EAAA,GAAK,IAAA,C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AA,IAAK,EAAA;AAAA,EACpF;AAAA;AAAA,EAGA,OAAA,CAAQ,IAAA,EAAc,KAAA,EAAe,EAAA,EAAmB;AACtD,IAAA,IAAI,EAAA,EAAI;AACN,MAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,IAAA,EAAM,KAAK,CAAA;AAAA,IACvC,CAAA,MAAO;AACL,MAAA,IAAA,CAAK,OAAA,CAAQ,gBAAgB,IAAI,CAAA;AAAA,IACnC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAA,CAAO,UAAkB,GAAA,EAAqB;AAC5C,IAAA,IAAI,QAAA,CAAS,MAAA,KAAW,CAAA,IAAK,GAAA,KAAQ,GAAG,OAAO,CAAA;AAE/C,IAAA,IAAI,MAAA,GAAS,CAAA;AACb,IAAA,KAAA,MAAW,aAAa,iBAAA,EAAmB;AACzC,MAAA,IAAI,QAAA,CAAS,MAAA,IAAU,SAAA,EAAW,MAAA,IAAU,CAAA;AAAA,IAC9C;AAEA,IAAA,MAAA,IAAU,cAAA,CAAe,OAAO,CAAC,EAAA,KAAO,GAAG,IAAA,CAAK,QAAQ,CAAC,CAAA,CAAE,MAAA,GAAS,CAAA;AAEpE,IAAA,IAAI,IAAI,GAAA,CAAI,QAAQ,CAAA,CAAE,IAAA,IAAQ,GAAG,MAAA,GAAS,CAAA;AAE1C,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,KAAA,CAAO,MAAA,GAAS,aAAc,GAAG,CAAA;AACvD,IAAA,OAAO,KAAK,GAAA,CAAI,GAAA,EAAK,KAAK,GAAA,CAAI,CAAA,EAAG,QAAQ,CAAC,CAAA;AAAA,EAC5C;AACF","file":"password_strength_controller.js","sourcesContent":["/**\n * Self-cleaning timer registries shared by Stimeo controllers.\n *\n * Stimulus controllers frequently schedule `setTimeout` / `setInterval` work\n * (auto-dismiss, debouncing, polling). When the element leaves the DOM — a\n * Turbo Drive navigation, a Turbo Stream replacement, or any `disconnect()` —\n * orphaned timers keep firing against a detached controller, leaking memory and\n * mutating stale state. {@link SafeTimeout} and {@link SafeInterval} track every\n * timer they create so a single {@link TimerRegistry.clearAll | clearAll()} call\n * in `disconnect()` tears them all down.\n *\n * These are intentionally low-level primitives: they own *registration and\n * cleanup only*. Higher-level policy (pause/resume, remaining-time accounting)\n * stays in the individual controllers so per-widget semantics are not flattened\n * into a lowest-common-denominator helper.\n */\n\n/**\n * Shared registry bookkeeping for the timeout/interval variants.\n *\n * Subclasses provide the scheduling primitive ({@link schedule}) and its matching\n * canceller ({@link cancel}); this base owns the set of live ids plus the\n * per-id and bulk teardown shared by both.\n */\nabstract class TimerRegistry {\n /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */\n protected readonly ids = new Set<number>();\n\n /** Schedules the underlying platform timer and returns its id. */\n protected abstract schedule(callback: () => void, delay: number): number;\n\n /** Cancels the underlying platform timer for `id`. */\n protected abstract cancel(id: number): void;\n\n /**\n * Cancels a single tracked timer.\n *\n * No-ops if the id is unknown (already cleared, fired, or never owned by this\n * registry), so callers can clear defensively without guarding.\n */\n clear(id: number): void {\n if (this.ids.delete(id)) {\n this.cancel(id);\n }\n }\n\n /**\n * Cancels every tracked timer. Call this from a controller's `disconnect()`\n * to guarantee no timer outlives the element.\n */\n clearAll(): void {\n for (const id of this.ids) {\n this.cancel(id);\n }\n this.ids.clear();\n }\n\n /** Number of timers currently tracked (pending). */\n get size(): number {\n return this.ids.size;\n }\n}\n\n/**\n * `setTimeout` wrapper that auto-forgets each timer once it fires and supports\n * bulk teardown on disconnect.\n *\n * @example\n * ```ts\n * #timers = new SafeTimeout();\n *\n * connect() {\n * this.#timers.set(() => this.dismiss(), 5000);\n * }\n *\n * disconnect() {\n * this.#timers.clearAll();\n * }\n * ```\n */\nexport class SafeTimeout extends TimerRegistry {\n /**\n * Schedules `callback` after `delay` ms and returns the timer id.\n *\n * The id is removed from the registry automatically when the timeout fires,\n * so {@link TimerRegistry.size | size} reflects only still-pending timers.\n */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(() => {\n this.ids.delete(id);\n callback();\n }, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setTimeout(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearTimeout(id);\n }\n}\n\n/**\n * `setInterval` wrapper that tracks every interval for bulk teardown on\n * disconnect. Unlike {@link SafeTimeout}, intervals are retained until they are\n * explicitly cleared because they fire repeatedly.\n *\n * @example\n * ```ts\n * #intervals = new SafeInterval();\n *\n * connect() {\n * this.#intervals.set(() => this.tick(), 1000);\n * }\n *\n * disconnect() {\n * this.#intervals.clearAll();\n * }\n * ```\n */\nexport class SafeInterval extends TimerRegistry {\n /** Schedules a repeating `callback` every `delay` ms and returns the timer id. */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(callback, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setInterval(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearInterval(id);\n }\n}\n","/**\n * JSON string-list parsing for the controllers that take a list as a Value.\n *\n * Stimulus offers an `Array` Value type, but its reader runs `JSON.parse` inside\n * the value observer — **before** the `<name>ValueChanged` callback — and\n * rethrows on malformed text. The throw propagates out of the observer that runs\n * during connection, so a single unparseable attribute stops the controller from\n * connecting at all: no lifecycle callback runs and the element is left inert\n * rather than degraded. A consumer cannot guard against it either, because the\n * callback that would hold the `try` never runs.\n *\n * Declaring the attribute as a `String` Value and parsing it here keeps a\n * malformed declaration local to the value it declares. The attribute text is\n * identical either way (`'[\"a\", \"b\"]'`), so markup does not change with the\n * declaration.\n */\n\n/**\n * Parses `raw` as a JSON array of strings.\n *\n * Returns `fallback` when the text is absent, unparseable, or not an array, so a\n * malformed declaration behaves like an omitted one. A parsed array keeps only\n * its string entries: every caller indexes or compares strings, and a stray\n * number would otherwise sit in the list without ever matching.\n *\n * An explicit `\"[]\"` is honoured as an empty list rather than falling back — it\n * is the only way to declare \"none\" against a non-empty default.\n *\n * @param raw - the attribute text, e.g. `'[\"password\"]'`.\n * @param fallback - the list to use when `raw` declares nothing usable.\n */\nexport function parseStringList(raw: string, fallback: readonly string[] = []): string[] {\n // The common case is an undeclared attribute, and `JSON.parse(\"\")` answers it\n // by throwing. Reaching the same fallback without building an exception keeps\n // the callers that ask per element off that path.\n const text = raw.trim();\n if (text.length === 0) return [...fallback];\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return [...fallback];\n }\n\n if (!Array.isArray(parsed)) return [...fallback];\n return parsed.filter((entry): entry is string => typeof entry === \"string\");\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\nimport { parseStringList } from \"../utils/string_list\";\n\n/** Character classes that contribute to password variety (one point each beyond the first). */\nconst CLASS_PATTERNS: readonly RegExp[] = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/];\n\n/** Strength labels used unless the consumer declares its own scale. */\nconst DEFAULT_LEVELS = [\"weak\", \"fair\", \"good\", \"strong\"];\n\n/** Length milestones that each add a strength point. */\nconst LENGTH_MILESTONES: readonly number[] = [8, 12, 16];\n\n/** Upper bound of the raw heuristic points, used to bucket into the level scale. */\nconst MAX_POINTS = LENGTH_MILESTONES.length + (CLASS_PATTERNS.length - 1);\n\n/**\n * Fixed, locale-independent styling bands `data-strength` is drawn from. Kept\n * separate from the (localizable) `levels` labels so `data-strength` stays a\n * stable CSS hook (e.g. `[data-strength=\"weak\"]`) even when `levels` is\n * translated. Ascending: weakest → strongest.\n */\nconst STRENGTH_BANDS = [\"weak\", \"fair\", \"good\", \"strong\"] as const;\n\n/**\n * Headless password-strength behavior: scores the field with a lightweight\n * zero-dependency heuristic and drives a meter plus an `aria-live` label. No\n * dedicated APG pattern; the meter display follows {@link MeterController}.\n *\n * Markup contract (identifier: `stimeo--password-strength`):\n * <div data-controller=\"stimeo--password-strength\">\n * <input type=\"password\" data-stimeo--password-strength-target=\"input\"\n * data-action=\"input->stimeo--password-strength#evaluate\" aria-describedby=\"pw\">\n * <div data-stimeo--password-strength-target=\"meter\" role=\"meter\"\n * aria-valuemin=\"0\" aria-valuemax=\"4\"></div>\n * <span id=\"pw\" data-stimeo--password-strength-target=\"label\" aria-live=\"polite\"></span>\n * </div>\n *\n * On each input the controller scores the password (length milestones + character\n * variety, capped for trivial repetition), syncs the meter's `aria-valuenow`,\n * reflects a stable band on `data-strength`, the `0–1` fill on\n * `--stimeo--password-strength`, and (when `minScore` is set) `data-below-min`,\n * and writes the level label into the label target.\n *\n * `change` dispatches `{ score, level, max, meetsMin }`.\n *\n * @remarks\n * Behavior only — the meter/bar look is the consumer's, keyed off the data hooks.\n * `data-strength` is one of the fixed {@link STRENGTH_BANDS} (not the localizable\n * `levels` text), so consumers can style by it regardless of locale; the visible\n * label receives the matching `levels` entry. Non-text state (meter ARIA,\n * `data-strength`/`data-below-min`, the custom property, and the `change` event)\n * updates **immediately** on every keystroke so styling and consumers stay\n * responsive, while the label — in an `aria-live=\"polite\"` region — is written on\n * a short debounce so a screen reader is not flooded mid-typing. The score is a\n * pure function of the input value (no module-scope state), so `connect()`\n * re-evaluates idempotently after a Turbo cache restore; the debounce timer is\n * owned by {@link SafeTimeout} and torn down on `disconnect()` (Turbo included).\n * The estimator is intentionally not a dictionary/zxcvbn-grade one (kept\n * zero-dep); swap a stronger one in on the consumer side if needed.\n */\nexport class PasswordStrengthController extends Controller<HTMLElement> {\n static override targets = [\"input\", \"meter\", \"label\"];\n static override values = {\n minScore: { type: Number, default: 0 },\n // A JSON list read through `parseStringList` rather than Stimulus's `Array`\n // type: that reader throws out of the value observer before any callback\n // runs, so one malformed attribute would stop the meter connecting.\n levels: { type: String, default: \"\" },\n };\n static actions = [\"evaluate\"] as const;\n static events = [\"change\"] as const;\n\n declare readonly inputTarget: HTMLInputElement;\n declare readonly meterTarget: HTMLElement;\n declare readonly labelTarget: HTMLElement;\n declare readonly hasInputTarget: boolean;\n declare readonly hasMeterTarget: boolean;\n declare readonly hasLabelTarget: boolean;\n\n declare minScoreValue: number;\n declare levelsValue: string;\n\n /** Delay (ms) before the polite live-region label is written, to throttle SR flooding. */\n static readonly #announceDelay = 200;\n\n readonly #timers = new SafeTimeout();\n #announceId: number | null = null;\n\n override connect(): void {\n // Reflect the current value synchronously (no announce): an autofilled or\n // cache-restored field shows the right strength without queuing an SR message.\n this.#update({ announce: false });\n }\n\n override disconnect(): void {\n this.#timers.clearAll();\n this.#announceId = null;\n }\n\n /** Re-evaluates strength from the input. Bound via `data-action` (`input`). */\n evaluate(): void {\n this.#update();\n }\n\n /**\n * Recomputes the strength. The meter ARIA, data hooks, the custom property and\n * the `change` event apply immediately; the live-region label text is debounced\n * unless `announce` is `false` (the initial render).\n */\n #update(options: { announce?: boolean } = {}): void {\n const password = this.hasInputTarget ? this.inputTarget.value : \"\";\n const labels = parseStringList(this.levelsValue, DEFAULT_LEVELS);\n const max = labels.length;\n const score = this.#score(password, max);\n const label = score > 0 ? (labels[score - 1] ?? \"\") : \"\";\n\n this.#reflectMeter(score, max);\n this.#reflectRoot(score, max);\n\n if (options.announce === false) {\n // Initial render (connect / cache-restore): reflect without a change event\n // or a queued screen-reader announcement.\n this.#writeLabel(label);\n return;\n }\n\n this.dispatch(\"change\", {\n detail: { score, level: label, max, meetsMin: score > 0 && score >= this.minScoreValue },\n });\n\n if (this.#announceId !== null) this.#timers.clear(this.#announceId);\n this.#announceId = this.#timers.set(() => {\n this.#writeLabel(label);\n this.#announceId = null;\n }, PasswordStrengthController.#announceDelay);\n }\n\n /** Syncs the meter target's ARIA value attributes (`0..levels.length`). */\n #reflectMeter(score: number, max: number): void {\n if (!this.hasMeterTarget) return;\n this.meterTarget.setAttribute(\"aria-valuemin\", \"0\");\n this.meterTarget.setAttribute(\"aria-valuemax\", String(max));\n this.meterTarget.setAttribute(\"aria-valuenow\", String(score));\n }\n\n /**\n * Reflects the level onto the root: the stable `data-strength` band (absent when\n * empty), the `data-below-min` hook when the score is under `minScore`, and the\n * `0–1` fill the consumer's CSS turns into the bar width.\n */\n #reflectRoot(score: number, max: number): void {\n const band = this.#band(score, max);\n this.#toggle(\"data-strength\", band, band.length > 0);\n // Empty/pristine input (`score === 0`) is never \"below min\": that would let CSS\n // flag an untouched field as failing. Mirror the `change` event's `meetsMin`\n // (`score > 0 && …`) so the hook only marks a *non-empty* password under the\n // threshold. `minScore` defaults to 0, leaving the hook inert until set positive.\n this.#toggle(\"data-below-min\", \"true\", score > 0 && score < this.minScoreValue);\n const ratio = max > 0 ? score / max : 0;\n this.element.style.setProperty(\"--stimeo--password-strength\", String(ratio));\n }\n\n #writeLabel(label: string): void {\n if (this.hasLabelTarget) this.labelTarget.textContent = label;\n }\n\n /**\n * Locale-independent styling band (one of {@link STRENGTH_BANDS}) for `score`\n * out of `max`. Empty input → `\"\"`. Quantizes the `score/max` ratio into the\n * four fixed bands, so a non-default level count still maps onto a stable hook.\n */\n #band(score: number, max: number): string {\n if (score <= 0 || max <= 0) return \"\";\n const index = Math.ceil((score / max) * STRENGTH_BANDS.length) - 1;\n return STRENGTH_BANDS[Math.min(STRENGTH_BANDS.length - 1, Math.max(0, index))] ?? \"\";\n }\n\n /** Sets `name` to `value` when `on`, else removes it (value/presence data hook). */\n #toggle(name: string, value: string, on: boolean): void {\n if (on) {\n this.element.setAttribute(name, value);\n } else {\n this.element.removeAttribute(name);\n }\n }\n\n /**\n * Lightweight zero-dependency strength heuristic returning an integer in\n * `[0, max]` (`max` = number of levels). Empty input is `0` (no level); any\n * non-empty password is at least `1`. Points accrue from length milestones and\n * character-class variety, then bucket into the level scale. A tiny alphabet\n * (≤ 2 distinct characters, e.g. \"aaaa\") is capped as the weakest, so length\n * alone cannot mask trivial repetition.\n */\n #score(password: string, max: number): number {\n if (password.length === 0 || max === 0) return 0;\n\n let points = 0;\n for (const milestone of LENGTH_MILESTONES) {\n if (password.length >= milestone) points += 1;\n }\n // The first present character class is free; each additional one adds a point.\n points += CLASS_PATTERNS.filter((re) => re.test(password)).length - 1;\n\n if (new Set(password).size <= 2) points = 0; // trivial repetition → weakest\n\n const bucketed = Math.round((points / MAX_POINTS) * max);\n return Math.min(max, Math.max(1, bucketed));\n }\n}\n"]}
|
|
@@ -1,11 +1,8 @@
|
|
|
1
1
|
import { Controller } from '@hotwired/stimulus';
|
|
2
2
|
|
|
3
|
-
/** Field controls this controller can persist. */
|
|
4
|
-
type PersistField = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
|
|
5
3
|
/**
|
|
6
|
-
* Headless draft-autosave behavior: persists
|
|
7
|
-
*
|
|
8
|
-
* pattern; a state-holding utility). The Alpine `persist` equivalent.
|
|
4
|
+
* Headless draft-autosave behavior: persists form controls to `localStorage`
|
|
5
|
+
* and restores them across Turbo navigation and reloads.
|
|
9
6
|
*
|
|
10
7
|
* Markup contract (identifier: `stimeo--persist`):
|
|
11
8
|
* <form data-controller="stimeo--persist"
|
|
@@ -14,16 +11,25 @@ type PersistField = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
|
|
|
14
11
|
* <textarea name="message"></textarea>
|
|
15
12
|
* </form>
|
|
16
13
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
14
|
+
* The optional `field` targets restrict persistence to explicitly targeted
|
|
15
|
+
* controls. The public `clear` action removes the active draft. `key`,
|
|
16
|
+
* `debounce`, `exclude`, and `clearOn` Values can change while connected;
|
|
17
|
+
* `clearOn` is an event name whose occurrence invokes `clear`.
|
|
18
|
+
*
|
|
19
|
+
* `restore`, `save`, and `clear` dispatch `{ key: string }`. `error` dispatches
|
|
20
|
+
* `{ key: string, operation: "read" | "write" | "remove", reason:
|
|
21
|
+
* "unavailable" | "invalid-payload" }`. Restore writes are intentionally
|
|
22
|
+
* silent native-control mutations; consumers synchronize from the bubbling
|
|
23
|
+
* `restore` event without treating a restored draft as user input.
|
|
21
24
|
*
|
|
22
25
|
* @remarks
|
|
23
|
-
* Behavior only
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
26
|
+
* Behavior only — restoration never moves focus. Passwords are never stored;
|
|
27
|
+
* the default exclusion also omits Rails request metadata while preserving
|
|
28
|
+
* application-owned hidden fields. Distinct logical keys isolate instances;
|
|
29
|
+
* instances using the same key intentionally share one last-writer-wins draft.
|
|
30
|
+
* Every listener, timer, observer, and queued reconciliation is released on
|
|
31
|
+
* `disconnect()`, after any pending edit is flushed through the normal save
|
|
32
|
+
* path. A reconnect removes stale restored state before reading storage.
|
|
27
33
|
*/
|
|
28
34
|
declare class PersistController extends Controller<HTMLElement> {
|
|
29
35
|
#private;
|
|
@@ -38,8 +44,8 @@ declare class PersistController extends Controller<HTMLElement> {
|
|
|
38
44
|
default: number;
|
|
39
45
|
};
|
|
40
46
|
exclude: {
|
|
41
|
-
type:
|
|
42
|
-
default: string
|
|
47
|
+
type: StringConstructor;
|
|
48
|
+
default: string;
|
|
43
49
|
};
|
|
44
50
|
clearOn: {
|
|
45
51
|
type: StringConstructor;
|
|
@@ -47,17 +53,25 @@ declare class PersistController extends Controller<HTMLElement> {
|
|
|
47
53
|
};
|
|
48
54
|
};
|
|
49
55
|
static actions: readonly ["clear"];
|
|
50
|
-
static events: readonly ["restore", "save", "clear"];
|
|
51
|
-
readonly fieldTargets:
|
|
56
|
+
static events: readonly ["restore", "save", "clear", "error"];
|
|
57
|
+
readonly fieldTargets: Element[];
|
|
52
58
|
readonly hasFieldTarget: boolean;
|
|
53
59
|
keyValue: string;
|
|
54
60
|
debounceValue: number;
|
|
55
|
-
excludeValue: string
|
|
61
|
+
excludeValue: string;
|
|
56
62
|
clearOnValue: string;
|
|
57
63
|
connect(): void;
|
|
58
64
|
disconnect(): void;
|
|
59
|
-
/** Drops the
|
|
65
|
+
/** Drops the active draft after storage confirms the removal. */
|
|
60
66
|
clear(): void;
|
|
67
|
+
/** Rebinds the external clear event when its Value changes. */
|
|
68
|
+
clearOnValueChanged(): void;
|
|
69
|
+
/** Switches storage namespaces without writing old edits under the new key. */
|
|
70
|
+
keyValueChanged(): void;
|
|
71
|
+
/** Reschedules a pending write against the current debounce delay. */
|
|
72
|
+
debounceValueChanged(): void;
|
|
73
|
+
/** Restores every field the new exclusion list makes eligible. */
|
|
74
|
+
excludeValueChanged(): void;
|
|
61
75
|
}
|
|
62
76
|
|
|
63
77
|
export { PersistController };
|