stimeo-ui 0.1.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +72 -0
- package/dist/controllers/accordion_controller.d.ts +59 -0
- package/dist/controllers/accordion_controller.js +76 -0
- package/dist/controllers/accordion_controller.js.map +1 -0
- package/dist/controllers/announcer_controller.d.ts +78 -0
- package/dist/controllers/announcer_controller.js +184 -0
- package/dist/controllers/announcer_controller.js.map +1 -0
- package/dist/controllers/aspect_ratio_controller.d.ts +39 -0
- package/dist/controllers/aspect_ratio_controller.js +36 -0
- package/dist/controllers/aspect_ratio_controller.js.map +1 -0
- package/dist/controllers/auto_submit_controller.d.ts +74 -0
- package/dist/controllers/auto_submit_controller.js +147 -0
- package/dist/controllers/auto_submit_controller.js.map +1 -0
- package/dist/controllers/avatar_controller.d.ts +50 -0
- package/dist/controllers/avatar_controller.js +66 -0
- package/dist/controllers/avatar_controller.js.map +1 -0
- package/dist/controllers/breadcrumb_controller.d.ts +60 -0
- package/dist/controllers/breadcrumb_controller.js +123 -0
- package/dist/controllers/breadcrumb_controller.js.map +1 -0
- package/dist/controllers/bulk_select_controller.d.ts +67 -0
- package/dist/controllers/bulk_select_controller.js +104 -0
- package/dist/controllers/bulk_select_controller.js.map +1 -0
- package/dist/controllers/calendar_controller.d.ts +100 -0
- package/dist/controllers/calendar_controller.js +394 -0
- package/dist/controllers/calendar_controller.js.map +1 -0
- package/dist/controllers/character_counter_controller.d.ts +63 -0
- package/dist/controllers/character_counter_controller.js +179 -0
- package/dist/controllers/character_counter_controller.js.map +1 -0
- package/dist/controllers/checkbox_controller.d.ts +52 -0
- package/dist/controllers/checkbox_controller.js +73 -0
- package/dist/controllers/checkbox_controller.js.map +1 -0
- package/dist/controllers/combobox_controller.d.ts +76 -0
- package/dist/controllers/combobox_controller.js +186 -0
- package/dist/controllers/combobox_controller.js.map +1 -0
- package/dist/controllers/command_palette_controller.d.ts +103 -0
- package/dist/controllers/command_palette_controller.js +381 -0
- package/dist/controllers/command_palette_controller.js.map +1 -0
- package/dist/controllers/conditional_fields_controller.d.ts +56 -0
- package/dist/controllers/conditional_fields_controller.js +112 -0
- package/dist/controllers/conditional_fields_controller.js.map +1 -0
- package/dist/controllers/confirm_controller.d.ts +83 -0
- package/dist/controllers/confirm_controller.js +276 -0
- package/dist/controllers/confirm_controller.js.map +1 -0
- package/dist/controllers/context_menu_controller.d.ts +81 -0
- package/dist/controllers/context_menu_controller.js +112 -0
- package/dist/controllers/context_menu_controller.js.map +1 -0
- package/dist/controllers/countdown_controller.d.ts +93 -0
- package/dist/controllers/countdown_controller.js +202 -0
- package/dist/controllers/countdown_controller.js.map +1 -0
- package/dist/controllers/dialog_controller.d.ts +57 -0
- package/dist/controllers/dialog_controller.js +207 -0
- package/dist/controllers/dialog_controller.js.map +1 -0
- package/dist/controllers/direct_upload_controller.d.ts +77 -0
- package/dist/controllers/direct_upload_controller.js +212 -0
- package/dist/controllers/direct_upload_controller.js.map +1 -0
- package/dist/controllers/dirty_form_controller.d.ts +52 -0
- package/dist/controllers/dirty_form_controller.js +128 -0
- package/dist/controllers/dirty_form_controller.js.map +1 -0
- package/dist/controllers/dropdown_controller.d.ts +49 -0
- package/dist/controllers/dropdown_controller.js +66 -0
- package/dist/controllers/dropdown_controller.js.map +1 -0
- package/dist/controllers/empty_state_controller.d.ts +60 -0
- package/dist/controllers/empty_state_controller.js +67 -0
- package/dist/controllers/empty_state_controller.js.map +1 -0
- package/dist/controllers/flash_controller.d.ts +63 -0
- package/dist/controllers/flash_controller.js +221 -0
- package/dist/controllers/flash_controller.js.map +1 -0
- package/dist/controllers/focus_controller.d.ts +69 -0
- package/dist/controllers/focus_controller.js +216 -0
- package/dist/controllers/focus_controller.js.map +1 -0
- package/dist/controllers/form_field_controller.d.ts +79 -0
- package/dist/controllers/form_field_controller.js +154 -0
- package/dist/controllers/form_field_controller.js.map +1 -0
- package/dist/controllers/form_validation_controller.d.ts +114 -0
- package/dist/controllers/form_validation_controller.js +202 -0
- package/dist/controllers/form_validation_controller.js.map +1 -0
- package/dist/controllers/frame_loading_controller.d.ts +58 -0
- package/dist/controllers/frame_loading_controller.js +177 -0
- package/dist/controllers/frame_loading_controller.js.map +1 -0
- package/dist/controllers/highlight_controller.d.ts +50 -0
- package/dist/controllers/highlight_controller.js +107 -0
- package/dist/controllers/highlight_controller.js.map +1 -0
- package/dist/controllers/hover_card_controller.d.ts +79 -0
- package/dist/controllers/hover_card_controller.js +165 -0
- package/dist/controllers/hover_card_controller.js.map +1 -0
- package/dist/controllers/idle_controller.d.ts +51 -0
- package/dist/controllers/idle_controller.js +141 -0
- package/dist/controllers/idle_controller.js.map +1 -0
- package/dist/controllers/input_mask_controller.d.ts +74 -0
- package/dist/controllers/input_mask_controller.js +166 -0
- package/dist/controllers/input_mask_controller.js.map +1 -0
- package/dist/controllers/lazy_frame_controller.d.ts +53 -0
- package/dist/controllers/lazy_frame_controller.js +68 -0
- package/dist/controllers/lazy_frame_controller.js.map +1 -0
- package/dist/controllers/listbox_controller.d.ts +88 -0
- package/dist/controllers/listbox_controller.js +256 -0
- package/dist/controllers/listbox_controller.js.map +1 -0
- package/dist/controllers/local_time_controller.d.ts +60 -0
- package/dist/controllers/local_time_controller.js +81 -0
- package/dist/controllers/local_time_controller.js.map +1 -0
- package/dist/controllers/menu_controller.d.ts +81 -0
- package/dist/controllers/menu_controller.js +134 -0
- package/dist/controllers/menu_controller.js.map +1 -0
- package/dist/controllers/meter_controller.d.ts +93 -0
- package/dist/controllers/meter_controller.js +96 -0
- package/dist/controllers/meter_controller.js.map +1 -0
- package/dist/controllers/nested_form_controller.d.ts +85 -0
- package/dist/controllers/nested_form_controller.js +131 -0
- package/dist/controllers/nested_form_controller.js.map +1 -0
- package/dist/controllers/network_status_controller.d.ts +49 -0
- package/dist/controllers/network_status_controller.js +126 -0
- package/dist/controllers/network_status_controller.js.map +1 -0
- package/dist/controllers/number_input_controller.d.ts +93 -0
- package/dist/controllers/number_input_controller.js +306 -0
- package/dist/controllers/number_input_controller.js.map +1 -0
- package/dist/controllers/otp_controller.d.ts +68 -0
- package/dist/controllers/otp_controller.js +201 -0
- package/dist/controllers/otp_controller.js.map +1 -0
- package/dist/controllers/overflow_indicator_controller.d.ts +62 -0
- package/dist/controllers/overflow_indicator_controller.js +169 -0
- package/dist/controllers/overflow_indicator_controller.js.map +1 -0
- package/dist/controllers/overflow_menu_controller.d.ts +64 -0
- package/dist/controllers/overflow_menu_controller.js +274 -0
- package/dist/controllers/overflow_menu_controller.js.map +1 -0
- package/dist/controllers/pagination_controller.d.ts +69 -0
- package/dist/controllers/pagination_controller.js +89 -0
- package/dist/controllers/pagination_controller.js.map +1 -0
- package/dist/controllers/password_strength_controller.d.ts +67 -0
- package/dist/controllers/password_strength_controller.js +175 -0
- package/dist/controllers/password_strength_controller.js.map +1 -0
- package/dist/controllers/persist_controller.d.ts +63 -0
- package/dist/controllers/persist_controller.js +259 -0
- package/dist/controllers/persist_controller.js.map +1 -0
- package/dist/controllers/popover_controller.d.ts +63 -0
- package/dist/controllers/popover_controller.js +94 -0
- package/dist/controllers/popover_controller.js.map +1 -0
- package/dist/controllers/portal_controller.d.ts +58 -0
- package/dist/controllers/portal_controller.js +63 -0
- package/dist/controllers/portal_controller.js.map +1 -0
- package/dist/controllers/preview_guard_controller.d.ts +47 -0
- package/dist/controllers/preview_guard_controller.js +69 -0
- package/dist/controllers/preview_guard_controller.js.map +1 -0
- package/dist/controllers/progress_controller.d.ts +85 -0
- package/dist/controllers/progress_controller.js +93 -0
- package/dist/controllers/progress_controller.js.map +1 -0
- package/dist/controllers/radio_group_controller.d.ts +49 -0
- package/dist/controllers/radio_group_controller.js +128 -0
- package/dist/controllers/radio_group_controller.js.map +1 -0
- package/dist/controllers/rating_controller.d.ts +82 -0
- package/dist/controllers/rating_controller.js +179 -0
- package/dist/controllers/rating_controller.js.map +1 -0
- package/dist/controllers/relative_time_controller.d.ts +48 -0
- package/dist/controllers/relative_time_controller.js +129 -0
- package/dist/controllers/relative_time_controller.js.map +1 -0
- package/dist/controllers/reset_before_cache_controller.d.ts +54 -0
- package/dist/controllers/reset_before_cache_controller.js +62 -0
- package/dist/controllers/reset_before_cache_controller.js.map +1 -0
- package/dist/controllers/resizable_controller.d.ts +81 -0
- package/dist/controllers/resizable_controller.js +163 -0
- package/dist/controllers/resizable_controller.js.map +1 -0
- package/dist/controllers/roving_controller.d.ts +63 -0
- package/dist/controllers/roving_controller.js +116 -0
- package/dist/controllers/roving_controller.js.map +1 -0
- package/dist/controllers/scroll_area_controller.d.ts +45 -0
- package/dist/controllers/scroll_area_controller.js +183 -0
- package/dist/controllers/scroll_area_controller.js.map +1 -0
- package/dist/controllers/scroll_visibility_controller.d.ts +72 -0
- package/dist/controllers/scroll_visibility_controller.js +103 -0
- package/dist/controllers/scroll_visibility_controller.js.map +1 -0
- package/dist/controllers/scrollspy_controller.d.ts +65 -0
- package/dist/controllers/scrollspy_controller.js +171 -0
- package/dist/controllers/scrollspy_controller.js.map +1 -0
- package/dist/controllers/skeleton_controller.d.ts +50 -0
- package/dist/controllers/skeleton_controller.js +125 -0
- package/dist/controllers/skeleton_controller.js.map +1 -0
- package/dist/controllers/slider_controller.d.ts +76 -0
- package/dist/controllers/slider_controller.js +109 -0
- package/dist/controllers/slider_controller.js.map +1 -0
- package/dist/controllers/spinner_controller.d.ts +62 -0
- package/dist/controllers/spinner_controller.js +164 -0
- package/dist/controllers/spinner_controller.js.map +1 -0
- package/dist/controllers/step_indicator_controller.d.ts +55 -0
- package/dist/controllers/step_indicator_controller.js +55 -0
- package/dist/controllers/step_indicator_controller.js.map +1 -0
- package/dist/controllers/stepper_controller.d.ts +66 -0
- package/dist/controllers/stepper_controller.js +78 -0
- package/dist/controllers/stepper_controller.js.map +1 -0
- package/dist/controllers/stick_to_bottom_controller.d.ts +61 -0
- package/dist/controllers/stick_to_bottom_controller.js +100 -0
- package/dist/controllers/stick_to_bottom_controller.js.map +1 -0
- package/dist/controllers/sticky_observer_controller.d.ts +54 -0
- package/dist/controllers/sticky_observer_controller.js +53 -0
- package/dist/controllers/sticky_observer_controller.js.map +1 -0
- package/dist/controllers/submit_once_controller.d.ts +66 -0
- package/dist/controllers/submit_once_controller.js +206 -0
- package/dist/controllers/submit_once_controller.js.map +1 -0
- package/dist/controllers/switch_controller.d.ts +43 -0
- package/dist/controllers/switch_controller.js +50 -0
- package/dist/controllers/switch_controller.js.map +1 -0
- package/dist/controllers/tabs_controller.d.ts +48 -0
- package/dist/controllers/tabs_controller.js +63 -0
- package/dist/controllers/tabs_controller.js.map +1 -0
- package/dist/controllers/textarea_autosize_controller.d.ts +47 -0
- package/dist/controllers/textarea_autosize_controller.js +72 -0
- package/dist/controllers/textarea_autosize_controller.js.map +1 -0
- package/dist/controllers/theme_controller.d.ts +70 -0
- package/dist/controllers/theme_controller.js +154 -0
- package/dist/controllers/theme_controller.js.map +1 -0
- package/dist/controllers/toast_controller.d.ts +123 -0
- package/dist/controllers/toast_controller.js +310 -0
- package/dist/controllers/toast_controller.js.map +1 -0
- package/dist/controllers/toggle_group_controller.d.ts +56 -0
- package/dist/controllers/toggle_group_controller.js +130 -0
- package/dist/controllers/toggle_group_controller.js.map +1 -0
- package/dist/controllers/toolbar_controller.d.ts +59 -0
- package/dist/controllers/toolbar_controller.js +113 -0
- package/dist/controllers/toolbar_controller.js.map +1 -0
- package/dist/controllers/tooltip_controller.d.ts +74 -0
- package/dist/controllers/tooltip_controller.js +165 -0
- package/dist/controllers/tooltip_controller.js.map +1 -0
- package/dist/controllers/transition_controller.d.ts +86 -0
- package/dist/controllers/transition_controller.js +203 -0
- package/dist/controllers/transition_controller.js.map +1 -0
- package/dist/index.d.ts +1931 -0
- package/dist/index.js +12241 -0
- package/dist/index.js.map +1 -0
- package/dist/inspector/cli.d.ts +149 -0
- package/dist/inspector/cli.js +663 -0
- package/dist/inspector/cli.js.map +1 -0
- package/dist/inspector/cli_bin.d.ts +2 -0
- package/dist/inspector/cli_bin.js +665 -0
- package/dist/inspector/cli_bin.js.map +1 -0
- package/dist/inspector/manifest.json +2235 -0
- package/dist/positioning/index.d.ts +226 -0
- package/dist/positioning/index.js +145 -0
- package/dist/positioning/index.js.map +1 -0
- package/package.json +93 -0
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { Controller } from '@hotwired/stimulus';
|
|
2
|
+
|
|
3
|
+
// src/controllers/password_strength_controller.ts
|
|
4
|
+
|
|
5
|
+
// src/utils/safe_timeout.ts
|
|
6
|
+
var TimerRegistry = class {
|
|
7
|
+
/** Live timer ids that have not yet been cleared (or, for timeouts, fired). */
|
|
8
|
+
ids = /* @__PURE__ */ new Set();
|
|
9
|
+
/**
|
|
10
|
+
* Cancels a single tracked timer.
|
|
11
|
+
*
|
|
12
|
+
* No-ops if the id is unknown (already cleared, fired, or never owned by this
|
|
13
|
+
* registry), so callers can clear defensively without guarding.
|
|
14
|
+
*/
|
|
15
|
+
clear(id) {
|
|
16
|
+
if (this.ids.delete(id)) {
|
|
17
|
+
this.cancel(id);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Cancels every tracked timer. Call this from a controller's `disconnect()`
|
|
22
|
+
* to guarantee no timer outlives the element.
|
|
23
|
+
*/
|
|
24
|
+
clearAll() {
|
|
25
|
+
for (const id of this.ids) {
|
|
26
|
+
this.cancel(id);
|
|
27
|
+
}
|
|
28
|
+
this.ids.clear();
|
|
29
|
+
}
|
|
30
|
+
/** Number of timers currently tracked (pending). */
|
|
31
|
+
get size() {
|
|
32
|
+
return this.ids.size;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
var SafeTimeout = class extends TimerRegistry {
|
|
36
|
+
/**
|
|
37
|
+
* Schedules `callback` after `delay` ms and returns the timer id.
|
|
38
|
+
*
|
|
39
|
+
* The id is removed from the registry automatically when the timeout fires,
|
|
40
|
+
* so {@link TimerRegistry.size | size} reflects only still-pending timers.
|
|
41
|
+
*/
|
|
42
|
+
set(callback, delay) {
|
|
43
|
+
const id = this.schedule(() => {
|
|
44
|
+
this.ids.delete(id);
|
|
45
|
+
callback();
|
|
46
|
+
}, delay);
|
|
47
|
+
this.ids.add(id);
|
|
48
|
+
return id;
|
|
49
|
+
}
|
|
50
|
+
schedule(callback, delay) {
|
|
51
|
+
return window.setTimeout(callback, delay);
|
|
52
|
+
}
|
|
53
|
+
cancel(id) {
|
|
54
|
+
window.clearTimeout(id);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
// src/controllers/password_strength_controller.ts
|
|
59
|
+
var CLASS_PATTERNS = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/];
|
|
60
|
+
var LENGTH_MILESTONES = [8, 12, 16];
|
|
61
|
+
var MAX_POINTS = LENGTH_MILESTONES.length + (CLASS_PATTERNS.length - 1);
|
|
62
|
+
var STRENGTH_BANDS = ["weak", "fair", "good", "strong"];
|
|
63
|
+
var PasswordStrengthController = class _PasswordStrengthController extends Controller {
|
|
64
|
+
static targets = ["input", "meter", "label"];
|
|
65
|
+
static values = {
|
|
66
|
+
minScore: { type: Number, default: 0 },
|
|
67
|
+
levels: { type: Array, default: ["weak", "fair", "good", "strong"] }
|
|
68
|
+
};
|
|
69
|
+
static actions = ["evaluate"];
|
|
70
|
+
static events = ["change"];
|
|
71
|
+
/** Delay (ms) before the polite live-region label is written, to throttle SR flooding. */
|
|
72
|
+
static #announceDelay = 200;
|
|
73
|
+
#timers = new SafeTimeout();
|
|
74
|
+
#announceId = null;
|
|
75
|
+
connect() {
|
|
76
|
+
this.#update({ announce: false });
|
|
77
|
+
}
|
|
78
|
+
disconnect() {
|
|
79
|
+
this.#timers.clearAll();
|
|
80
|
+
this.#announceId = null;
|
|
81
|
+
}
|
|
82
|
+
/** Re-evaluates strength from the input. Bound via `data-action` (`input`). */
|
|
83
|
+
evaluate() {
|
|
84
|
+
this.#update();
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Recomputes the strength. The meter ARIA, data hooks, the custom property and
|
|
88
|
+
* the `change` event apply immediately; the live-region label text is debounced
|
|
89
|
+
* unless `announce` is `false` (the initial render).
|
|
90
|
+
*/
|
|
91
|
+
#update(options = {}) {
|
|
92
|
+
const password = this.hasInputTarget ? this.inputTarget.value : "";
|
|
93
|
+
const labels = this.levelsValue;
|
|
94
|
+
const max = labels.length;
|
|
95
|
+
const score = this.#score(password, max);
|
|
96
|
+
const label = score > 0 ? labels[score - 1] ?? "" : "";
|
|
97
|
+
this.#reflectMeter(score, max);
|
|
98
|
+
this.#reflectRoot(score, max);
|
|
99
|
+
if (options.announce === false) {
|
|
100
|
+
this.#writeLabel(label);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
this.dispatch("change", {
|
|
104
|
+
detail: { score, level: label, max, meetsMin: score > 0 && score >= this.minScoreValue }
|
|
105
|
+
});
|
|
106
|
+
if (this.#announceId !== null) this.#timers.clear(this.#announceId);
|
|
107
|
+
this.#announceId = this.#timers.set(() => {
|
|
108
|
+
this.#writeLabel(label);
|
|
109
|
+
this.#announceId = null;
|
|
110
|
+
}, _PasswordStrengthController.#announceDelay);
|
|
111
|
+
}
|
|
112
|
+
/** Syncs the meter target's ARIA value attributes (`0..levels.length`). */
|
|
113
|
+
#reflectMeter(score, max) {
|
|
114
|
+
if (!this.hasMeterTarget) return;
|
|
115
|
+
this.meterTarget.setAttribute("aria-valuemin", "0");
|
|
116
|
+
this.meterTarget.setAttribute("aria-valuemax", String(max));
|
|
117
|
+
this.meterTarget.setAttribute("aria-valuenow", String(score));
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Reflects the level onto the root: the stable `data-strength` band (absent when
|
|
121
|
+
* empty), the `data-below-min` hook when the score is under `minScore`, and the
|
|
122
|
+
* `0–1` fill the consumer's CSS turns into the bar width.
|
|
123
|
+
*/
|
|
124
|
+
#reflectRoot(score, max) {
|
|
125
|
+
const band = this.#band(score, max);
|
|
126
|
+
this.#toggle("data-strength", band, band.length > 0);
|
|
127
|
+
this.#toggle("data-below-min", "true", score > 0 && score < this.minScoreValue);
|
|
128
|
+
const ratio = max > 0 ? score / max : 0;
|
|
129
|
+
this.element.style.setProperty("--stimeo-password-strength", String(ratio));
|
|
130
|
+
}
|
|
131
|
+
#writeLabel(label) {
|
|
132
|
+
if (this.hasLabelTarget) this.labelTarget.textContent = label;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Locale-independent styling band (one of {@link STRENGTH_BANDS}) for `score`
|
|
136
|
+
* out of `max`. Empty input → `""`. Quantizes the `score/max` ratio into the
|
|
137
|
+
* four fixed bands, so a non-default level count still maps onto a stable hook.
|
|
138
|
+
*/
|
|
139
|
+
#band(score, max) {
|
|
140
|
+
if (score <= 0 || max <= 0) return "";
|
|
141
|
+
const index = Math.ceil(score / max * STRENGTH_BANDS.length) - 1;
|
|
142
|
+
return STRENGTH_BANDS[Math.min(STRENGTH_BANDS.length - 1, Math.max(0, index))] ?? "";
|
|
143
|
+
}
|
|
144
|
+
/** Sets `name` to `value` when `on`, else removes it (value/presence data hook). */
|
|
145
|
+
#toggle(name, value, on) {
|
|
146
|
+
if (on) {
|
|
147
|
+
this.element.setAttribute(name, value);
|
|
148
|
+
} else {
|
|
149
|
+
this.element.removeAttribute(name);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Lightweight zero-dependency strength heuristic returning an integer in
|
|
154
|
+
* `[0, max]` (`max` = number of levels). Empty input is `0` (no level); any
|
|
155
|
+
* non-empty password is at least `1`. Points accrue from length milestones and
|
|
156
|
+
* character-class variety, then bucket into the level scale. A tiny alphabet
|
|
157
|
+
* (≤ 2 distinct characters, e.g. "aaaa") is capped as the weakest, so length
|
|
158
|
+
* alone cannot mask trivial repetition.
|
|
159
|
+
*/
|
|
160
|
+
#score(password, max) {
|
|
161
|
+
if (password.length === 0 || max === 0) return 0;
|
|
162
|
+
let points = 0;
|
|
163
|
+
for (const milestone of LENGTH_MILESTONES) {
|
|
164
|
+
if (password.length >= milestone) points += 1;
|
|
165
|
+
}
|
|
166
|
+
points += CLASS_PATTERNS.filter((re) => re.test(password)).length - 1;
|
|
167
|
+
if (new Set(password).size <= 2) points = 0;
|
|
168
|
+
const bucketed = Math.round(points / MAX_POINTS * max);
|
|
169
|
+
return Math.min(max, Math.max(1, bucketed));
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
export { PasswordStrengthController };
|
|
174
|
+
//# sourceMappingURL=password_strength_controller.js.map
|
|
175
|
+
//# sourceMappingURL=password_strength_controller.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utils/safe_timeout.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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AA,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","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"]}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { Controller } from '@hotwired/stimulus';
|
|
2
|
+
|
|
3
|
+
/** Field controls this controller can persist. */
|
|
4
|
+
type PersistField = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
|
|
5
|
+
/**
|
|
6
|
+
* Headless draft-autosave behavior: persists a form's field values to
|
|
7
|
+
* `localStorage` and restores them across Turbo navigations and reloads (no APG
|
|
8
|
+
* pattern; a state-holding utility). The Alpine `persist` equivalent.
|
|
9
|
+
*
|
|
10
|
+
* Markup contract (identifier: `stimeo--persist`):
|
|
11
|
+
* <form data-controller="stimeo--persist"
|
|
12
|
+
* data-stimeo--persist-key-value="contact-draft">
|
|
13
|
+
* <input name="name">
|
|
14
|
+
* <textarea name="message"></textarea>
|
|
15
|
+
* </form>
|
|
16
|
+
*
|
|
17
|
+
* On connect it restores any saved values under `key` (falling back to the
|
|
18
|
+
* element's `id`), then debounce-saves on every input/change. Password fields (and
|
|
19
|
+
* anything in `exclude`) are never written. A `clear()` action — or the `clearOn`
|
|
20
|
+
* event (e.g. `submit`) — drops the draft. Restoring never moves focus.
|
|
21
|
+
*
|
|
22
|
+
* @remarks
|
|
23
|
+
* Behavior only. State lives entirely in `localStorage` (no module-scope state), so
|
|
24
|
+
* instances never interfere. The input listener and debounce timer are removed on
|
|
25
|
+
* `disconnect()` (Turbo navigation included), where a pending save is flushed first
|
|
26
|
+
* so an in-flight edit is not lost.
|
|
27
|
+
*/
|
|
28
|
+
declare class PersistController extends Controller<HTMLElement> {
|
|
29
|
+
#private;
|
|
30
|
+
static targets: string[];
|
|
31
|
+
static values: {
|
|
32
|
+
key: {
|
|
33
|
+
type: StringConstructor;
|
|
34
|
+
default: string;
|
|
35
|
+
};
|
|
36
|
+
debounce: {
|
|
37
|
+
type: NumberConstructor;
|
|
38
|
+
default: number;
|
|
39
|
+
};
|
|
40
|
+
exclude: {
|
|
41
|
+
type: ArrayConstructor;
|
|
42
|
+
default: string[];
|
|
43
|
+
};
|
|
44
|
+
clearOn: {
|
|
45
|
+
type: StringConstructor;
|
|
46
|
+
default: string;
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
static actions: readonly ["clear"];
|
|
50
|
+
static events: readonly ["restore", "save", "clear"];
|
|
51
|
+
readonly fieldTargets: PersistField[];
|
|
52
|
+
readonly hasFieldTarget: boolean;
|
|
53
|
+
keyValue: string;
|
|
54
|
+
debounceValue: number;
|
|
55
|
+
excludeValue: string[];
|
|
56
|
+
clearOnValue: string;
|
|
57
|
+
connect(): void;
|
|
58
|
+
disconnect(): void;
|
|
59
|
+
/** Drops the saved draft and clears the restored marker. */
|
|
60
|
+
clear(): void;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export { PersistController };
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import { Controller } from '@hotwired/stimulus';
|
|
2
|
+
|
|
3
|
+
// src/controllers/persist_controller.ts
|
|
4
|
+
|
|
5
|
+
// src/utils/safe_timeout.ts
|
|
6
|
+
var TimerRegistry = class {
|
|
7
|
+
/** Live timer ids that have not yet been cleared (or, for timeouts, fired). */
|
|
8
|
+
ids = /* @__PURE__ */ new Set();
|
|
9
|
+
/**
|
|
10
|
+
* Cancels a single tracked timer.
|
|
11
|
+
*
|
|
12
|
+
* No-ops if the id is unknown (already cleared, fired, or never owned by this
|
|
13
|
+
* registry), so callers can clear defensively without guarding.
|
|
14
|
+
*/
|
|
15
|
+
clear(id) {
|
|
16
|
+
if (this.ids.delete(id)) {
|
|
17
|
+
this.cancel(id);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Cancels every tracked timer. Call this from a controller's `disconnect()`
|
|
22
|
+
* to guarantee no timer outlives the element.
|
|
23
|
+
*/
|
|
24
|
+
clearAll() {
|
|
25
|
+
for (const id of this.ids) {
|
|
26
|
+
this.cancel(id);
|
|
27
|
+
}
|
|
28
|
+
this.ids.clear();
|
|
29
|
+
}
|
|
30
|
+
/** Number of timers currently tracked (pending). */
|
|
31
|
+
get size() {
|
|
32
|
+
return this.ids.size;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
var SafeTimeout = class extends TimerRegistry {
|
|
36
|
+
/**
|
|
37
|
+
* Schedules `callback` after `delay` ms and returns the timer id.
|
|
38
|
+
*
|
|
39
|
+
* The id is removed from the registry automatically when the timeout fires,
|
|
40
|
+
* so {@link TimerRegistry.size | size} reflects only still-pending timers.
|
|
41
|
+
*/
|
|
42
|
+
set(callback, delay) {
|
|
43
|
+
const id = this.schedule(() => {
|
|
44
|
+
this.ids.delete(id);
|
|
45
|
+
callback();
|
|
46
|
+
}, delay);
|
|
47
|
+
this.ids.add(id);
|
|
48
|
+
return id;
|
|
49
|
+
}
|
|
50
|
+
schedule(callback, delay) {
|
|
51
|
+
return window.setTimeout(callback, delay);
|
|
52
|
+
}
|
|
53
|
+
cancel(id) {
|
|
54
|
+
window.clearTimeout(id);
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
// src/controllers/persist_controller.ts
|
|
59
|
+
var NON_VALUE_TYPES = /* @__PURE__ */ new Set(["file", "submit", "reset", "button", "image"]);
|
|
60
|
+
var STORAGE_PREFIX = "stimeo--persist:";
|
|
61
|
+
var OCCURRENCE_SEP = "\0";
|
|
62
|
+
var PersistController = class extends Controller {
|
|
63
|
+
static targets = ["field"];
|
|
64
|
+
static values = {
|
|
65
|
+
key: { type: String, default: "" },
|
|
66
|
+
debounce: { type: Number, default: 400 },
|
|
67
|
+
exclude: { type: Array, default: ["password"] },
|
|
68
|
+
clearOn: { type: String, default: "" }
|
|
69
|
+
};
|
|
70
|
+
static actions = ["clear"];
|
|
71
|
+
static events = ["restore", "save", "clear"];
|
|
72
|
+
#timeouts = new SafeTimeout();
|
|
73
|
+
#saveId = null;
|
|
74
|
+
#onInput = () => {
|
|
75
|
+
this.#scheduleSave();
|
|
76
|
+
};
|
|
77
|
+
#onClearEvent = () => {
|
|
78
|
+
this.clear();
|
|
79
|
+
};
|
|
80
|
+
connect() {
|
|
81
|
+
if (this.#storageKey === null) return;
|
|
82
|
+
this.#restore();
|
|
83
|
+
this.element.addEventListener("input", this.#onInput);
|
|
84
|
+
this.element.addEventListener("change", this.#onInput);
|
|
85
|
+
if (this.clearOnValue.length > 0) {
|
|
86
|
+
this.element.addEventListener(this.clearOnValue, this.#onClearEvent);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
disconnect() {
|
|
90
|
+
this.element.removeEventListener("input", this.#onInput);
|
|
91
|
+
this.element.removeEventListener("change", this.#onInput);
|
|
92
|
+
if (this.clearOnValue.length > 0) {
|
|
93
|
+
this.element.removeEventListener(this.clearOnValue, this.#onClearEvent);
|
|
94
|
+
}
|
|
95
|
+
if (this.#saveId !== null) {
|
|
96
|
+
this.#timeouts.clear(this.#saveId);
|
|
97
|
+
this.#saveId = null;
|
|
98
|
+
this.#write();
|
|
99
|
+
}
|
|
100
|
+
this.#timeouts.clearAll();
|
|
101
|
+
}
|
|
102
|
+
/** Drops the saved draft and clears the restored marker. */
|
|
103
|
+
clear() {
|
|
104
|
+
const key = this.#storageKey;
|
|
105
|
+
if (key === null) return;
|
|
106
|
+
if (this.#saveId !== null) {
|
|
107
|
+
this.#timeouts.clear(this.#saveId);
|
|
108
|
+
this.#saveId = null;
|
|
109
|
+
}
|
|
110
|
+
this.#removeItem(key);
|
|
111
|
+
this.element.removeAttribute("data-persist-restored");
|
|
112
|
+
this.dispatch("clear", { detail: { key: this.#logicalKey } });
|
|
113
|
+
}
|
|
114
|
+
/** Schedules a debounced save. */
|
|
115
|
+
#scheduleSave() {
|
|
116
|
+
if (this.#saveId !== null) this.#timeouts.clear(this.#saveId);
|
|
117
|
+
this.#saveId = this.#timeouts.set(() => {
|
|
118
|
+
this.#saveId = null;
|
|
119
|
+
this.#save();
|
|
120
|
+
}, this.debounceValue);
|
|
121
|
+
}
|
|
122
|
+
/** Writes the current values and emits `save`. */
|
|
123
|
+
#save() {
|
|
124
|
+
this.#write();
|
|
125
|
+
this.dispatch("save", { detail: { key: this.#logicalKey } });
|
|
126
|
+
}
|
|
127
|
+
/** Serializes persistable fields and stores them under the storage key. */
|
|
128
|
+
#write() {
|
|
129
|
+
const key = this.#storageKey;
|
|
130
|
+
if (key === null) return;
|
|
131
|
+
const data = {};
|
|
132
|
+
for (const { field, key: fieldKey } of this.#fieldEntries()) {
|
|
133
|
+
if (field instanceof HTMLInputElement && field.type === "checkbox") {
|
|
134
|
+
data[fieldKey] = field.checked;
|
|
135
|
+
} else if (field instanceof HTMLInputElement && field.type === "radio") {
|
|
136
|
+
if (field.checked) data[fieldKey] = field.value;
|
|
137
|
+
} else if (field instanceof HTMLSelectElement && field.multiple) {
|
|
138
|
+
data[fieldKey] = Array.from(field.selectedOptions).map((o) => o.value);
|
|
139
|
+
} else {
|
|
140
|
+
data[fieldKey] = field.value;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
this.#setItem(key, JSON.stringify(data));
|
|
144
|
+
}
|
|
145
|
+
/** Applies any saved values to the fields, without moving focus. */
|
|
146
|
+
#restore() {
|
|
147
|
+
const key = this.#storageKey;
|
|
148
|
+
if (key === null) return;
|
|
149
|
+
const raw = this.#getItem(key);
|
|
150
|
+
if (raw === null) return;
|
|
151
|
+
let data;
|
|
152
|
+
try {
|
|
153
|
+
data = JSON.parse(raw);
|
|
154
|
+
} catch {
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
let restoredAny = false;
|
|
158
|
+
for (const { field, key: fieldKey } of this.#fieldEntries()) {
|
|
159
|
+
if (!Object.hasOwn(data, fieldKey)) continue;
|
|
160
|
+
this.#applyValue(field, data[fieldKey]);
|
|
161
|
+
restoredAny = true;
|
|
162
|
+
}
|
|
163
|
+
if (restoredAny) {
|
|
164
|
+
this.element.setAttribute("data-persist-restored", "true");
|
|
165
|
+
this.dispatch("restore", { detail: { key: this.#logicalKey } });
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/** Sets a single field's value from a stored entry. */
|
|
169
|
+
#applyValue(field, value) {
|
|
170
|
+
if (field instanceof HTMLInputElement && field.type === "checkbox") {
|
|
171
|
+
field.checked = Boolean(value);
|
|
172
|
+
} else if (field instanceof HTMLInputElement && field.type === "radio") {
|
|
173
|
+
field.checked = field.value === value;
|
|
174
|
+
} else if (field instanceof HTMLSelectElement && field.multiple) {
|
|
175
|
+
const selected = new Set(Array.isArray(value) ? value.map(String) : []);
|
|
176
|
+
for (const option of Array.from(field.options)) {
|
|
177
|
+
option.selected = selected.has(option.value);
|
|
178
|
+
}
|
|
179
|
+
} else {
|
|
180
|
+
field.value = String(value);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Persistable fields paired with a stable storage key. Uniquely-named fields key
|
|
185
|
+
* by their name (unchanged, backward-compatible). Repeated same-name fields
|
|
186
|
+
* (e.g. a `tags[]` checkbox group or array text inputs) are disambiguated by
|
|
187
|
+
* DOM-order occurrence — the first keeps its plain `name` (backward-
|
|
188
|
+
* compatible), later ones get a NUL-separated index suffix — so each is stored and
|
|
189
|
+
* restored individually instead of the last one clobbering the rest. Radios are
|
|
190
|
+
* the exception: a group intentionally shares one key (one value per name).
|
|
191
|
+
*/
|
|
192
|
+
#fieldEntries() {
|
|
193
|
+
const entries = [];
|
|
194
|
+
const occurrence = /* @__PURE__ */ new Map();
|
|
195
|
+
for (const field of this.#fields()) {
|
|
196
|
+
const name = this.#keyOf(field);
|
|
197
|
+
if (name === null) continue;
|
|
198
|
+
if (field instanceof HTMLInputElement && field.type === "radio") {
|
|
199
|
+
entries.push({ field, key: name });
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
const seen = occurrence.get(name) ?? 0;
|
|
203
|
+
occurrence.set(name, seen + 1);
|
|
204
|
+
entries.push({ field, key: seen === 0 ? name : `${name}${OCCURRENCE_SEP}${seen}` });
|
|
205
|
+
}
|
|
206
|
+
return entries;
|
|
207
|
+
}
|
|
208
|
+
/** The fields to persist: `field` targets, or the element's named controls. */
|
|
209
|
+
#fields() {
|
|
210
|
+
const candidates = this.hasFieldTarget ? this.fieldTargets : Array.from(this.element.querySelectorAll("input, textarea, select"));
|
|
211
|
+
return candidates.filter((field) => this.#persistable(field));
|
|
212
|
+
}
|
|
213
|
+
/** Whether a field carries a restorable, non-excluded value. */
|
|
214
|
+
#persistable(field) {
|
|
215
|
+
if (this.#keyOf(field) === null) return false;
|
|
216
|
+
const type = field instanceof HTMLInputElement ? field.type : "";
|
|
217
|
+
if (NON_VALUE_TYPES.has(type)) return false;
|
|
218
|
+
if (this.excludeValue.includes(type)) return false;
|
|
219
|
+
if (field.name.length > 0 && this.excludeValue.includes(field.name)) return false;
|
|
220
|
+
return true;
|
|
221
|
+
}
|
|
222
|
+
/** A stable storage sub-key for a field (its name, else id). */
|
|
223
|
+
#keyOf(field) {
|
|
224
|
+
return field.name || field.id || null;
|
|
225
|
+
}
|
|
226
|
+
/** The logical key (key Value or element id), or null when neither is set. */
|
|
227
|
+
get #logicalKey() {
|
|
228
|
+
const key = this.keyValue || this.element.id;
|
|
229
|
+
return key.length > 0 ? key : null;
|
|
230
|
+
}
|
|
231
|
+
/** The prefixed localStorage key, or null when persistence is disabled. */
|
|
232
|
+
get #storageKey() {
|
|
233
|
+
const logical = this.#logicalKey;
|
|
234
|
+
return logical === null ? null : `${STORAGE_PREFIX}${logical}`;
|
|
235
|
+
}
|
|
236
|
+
#getItem(key) {
|
|
237
|
+
try {
|
|
238
|
+
return window.localStorage.getItem(key);
|
|
239
|
+
} catch {
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
#setItem(key, value) {
|
|
244
|
+
try {
|
|
245
|
+
window.localStorage.setItem(key, value);
|
|
246
|
+
} catch {
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
#removeItem(key) {
|
|
250
|
+
try {
|
|
251
|
+
window.localStorage.removeItem(key);
|
|
252
|
+
} catch {
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
export { PersistController };
|
|
258
|
+
//# sourceMappingURL=persist_controller.js.map
|
|
259
|
+
//# sourceMappingURL=persist_controller.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utils/safe_timeout.ts","../../src/controllers/persist_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,EAA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O,KAAA,CAAM,IAAA,IAAQ,KAAA,CAAM,EAAA,IAAM,IAAA;AAAA,EACnC;AAAA;AAAA,EAGA,IAAI,WAAA,GAA6B;AAC/B,IAAA,MAAM,GAAA,GAAM,IAAA,CAAK,QAAA,IAAY,IAAA,CAAK,OAAA,CAAQ,EAAA;AAC1C,IAAA,OAAO,GAAA,CAAI,MAAA,GAAS,CAAA,GAAI,GAAA,GAAM,IAAA;AAAA,EAChC;AAAA;AAAA,EAGA,IAAI,WAAA,GAA6B;AAC/B,IAAA,MAAM,UAAU,IAAA,CAAK,WAAA;AACrB,IAAA,OAAO,YAAY,IAAA,GAAO,IAAA,GAAO,CAAA,EAAG,cAAc,GAAG,OAAO,CAAA,CAAA;AAAA,EAC9D;AAAA,EAEA,SAAS,GAAA,EAA4B;AACnC,IAAA,IAAI;AACF,MAAA,OAAO,MAAA,CAAO,YAAA,CAAa,OAAA,CAAQ,GAAG,CAAA;AAAA,IACxC,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AAAA,EAEA,QAAA,CAAS,KAAa,KAAA,EAAqB;AACzC,IAAA,IAAI;AACF,MAAA,MAAA,CAAO,YAAA,CAAa,OAAA,CAAQ,GAAA,EAAK,KAAK,CAAA;AAAA,IACxC,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF;AAAA,EAEA,YAAY,GAAA,EAAmB;AAC7B,IAAA,IAAI;AACF,MAAA,MAAA,CAAO,YAAA,CAAa,WAAW,GAAG,CAAA;AAAA,IACpC,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF;AACF","file":"persist_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/** Field controls this controller can persist. */\ntype PersistField = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;\n\n/** Input types that carry no meaningful, restorable value. */\nconst NON_VALUE_TYPES = new Set([\"file\", \"submit\", \"reset\", \"button\", \"image\"]);\n/** localStorage key prefix so drafts never clobber unrelated app storage. */\nconst STORAGE_PREFIX = \"stimeo--persist:\";\n/** Separator for disambiguating repeated same-name fields (cannot occur in a real field name). */\nconst OCCURRENCE_SEP = \"\\u0000\";\n\n/**\n * Headless draft-autosave behavior: persists a form's field values to\n * `localStorage` and restores them across Turbo navigations and reloads (no APG\n * pattern; a state-holding utility). The Alpine `persist` equivalent.\n *\n * Markup contract (identifier: `stimeo--persist`):\n * <form data-controller=\"stimeo--persist\"\n * data-stimeo--persist-key-value=\"contact-draft\">\n * <input name=\"name\">\n * <textarea name=\"message\"></textarea>\n * </form>\n *\n * On connect it restores any saved values under `key` (falling back to the\n * element's `id`), then debounce-saves on every input/change. Password fields (and\n * anything in `exclude`) are never written. A `clear()` action — or the `clearOn`\n * event (e.g. `submit`) — drops the draft. Restoring never moves focus.\n *\n * @remarks\n * Behavior only. State lives entirely in `localStorage` (no module-scope state), so\n * instances never interfere. The input listener and debounce timer are removed on\n * `disconnect()` (Turbo navigation included), where a pending save is flushed first\n * so an in-flight edit is not lost.\n */\nexport class PersistController extends Controller<HTMLElement> {\n static override targets = [\"field\"];\n static override values = {\n key: { type: String, default: \"\" },\n debounce: { type: Number, default: 400 },\n exclude: { type: Array, default: [\"password\"] },\n clearOn: { type: String, default: \"\" },\n };\n static actions = [\"clear\"] as const;\n static events = [\"restore\", \"save\", \"clear\"] as const;\n\n declare readonly fieldTargets: PersistField[];\n declare readonly hasFieldTarget: boolean;\n\n declare keyValue: string;\n declare debounceValue: number;\n declare excludeValue: string[];\n declare clearOnValue: string;\n\n readonly #timeouts = new SafeTimeout();\n #saveId: number | null = null;\n\n readonly #onInput = (): void => {\n this.#scheduleSave();\n };\n\n readonly #onClearEvent = (): void => {\n this.clear();\n };\n\n override connect(): void {\n if (this.#storageKey === null) return;\n this.#restore();\n this.element.addEventListener(\"input\", this.#onInput);\n this.element.addEventListener(\"change\", this.#onInput);\n if (this.clearOnValue.length > 0) {\n this.element.addEventListener(this.clearOnValue, this.#onClearEvent);\n }\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"input\", this.#onInput);\n this.element.removeEventListener(\"change\", this.#onInput);\n if (this.clearOnValue.length > 0) {\n this.element.removeEventListener(this.clearOnValue, this.#onClearEvent);\n }\n // Flush a pending save so an in-flight edit survives a Turbo navigation.\n if (this.#saveId !== null) {\n this.#timeouts.clear(this.#saveId);\n this.#saveId = null;\n this.#write();\n }\n this.#timeouts.clearAll();\n }\n\n /** Drops the saved draft and clears the restored marker. */\n clear(): void {\n const key = this.#storageKey;\n if (key === null) return;\n if (this.#saveId !== null) {\n this.#timeouts.clear(this.#saveId);\n this.#saveId = null;\n }\n this.#removeItem(key);\n this.element.removeAttribute(\"data-persist-restored\");\n this.dispatch(\"clear\", { detail: { key: this.#logicalKey } });\n }\n\n /** Schedules a debounced save. */\n #scheduleSave(): void {\n if (this.#saveId !== null) this.#timeouts.clear(this.#saveId);\n this.#saveId = this.#timeouts.set(() => {\n this.#saveId = null;\n this.#save();\n }, this.debounceValue);\n }\n\n /** Writes the current values and emits `save`. */\n #save(): void {\n this.#write();\n this.dispatch(\"save\", { detail: { key: this.#logicalKey } });\n }\n\n /** Serializes persistable fields and stores them under the storage key. */\n #write(): void {\n const key = this.#storageKey;\n if (key === null) return;\n const data: Record<string, unknown> = {};\n for (const { field, key: fieldKey } of this.#fieldEntries()) {\n if (field instanceof HTMLInputElement && field.type === \"checkbox\") {\n data[fieldKey] = field.checked;\n } else if (field instanceof HTMLInputElement && field.type === \"radio\") {\n if (field.checked) data[fieldKey] = field.value;\n } else if (field instanceof HTMLSelectElement && field.multiple) {\n data[fieldKey] = Array.from(field.selectedOptions).map((o) => o.value);\n } else {\n data[fieldKey] = field.value;\n }\n }\n this.#setItem(key, JSON.stringify(data));\n }\n\n /** Applies any saved values to the fields, without moving focus. */\n #restore(): void {\n const key = this.#storageKey;\n if (key === null) return;\n const raw = this.#getItem(key);\n if (raw === null) return;\n let data: Record<string, unknown>;\n try {\n data = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n return;\n }\n let restoredAny = false;\n for (const { field, key: fieldKey } of this.#fieldEntries()) {\n if (!Object.hasOwn(data, fieldKey)) continue;\n this.#applyValue(field, data[fieldKey]);\n restoredAny = true;\n }\n if (restoredAny) {\n this.element.setAttribute(\"data-persist-restored\", \"true\");\n this.dispatch(\"restore\", { detail: { key: this.#logicalKey } });\n }\n }\n\n /** Sets a single field's value from a stored entry. */\n #applyValue(field: PersistField, value: unknown): void {\n if (field instanceof HTMLInputElement && field.type === \"checkbox\") {\n field.checked = Boolean(value);\n } else if (field instanceof HTMLInputElement && field.type === \"radio\") {\n field.checked = field.value === value;\n } else if (field instanceof HTMLSelectElement && field.multiple) {\n const selected = new Set(Array.isArray(value) ? value.map(String) : []);\n for (const option of Array.from(field.options)) {\n option.selected = selected.has(option.value);\n }\n } else {\n field.value = String(value);\n }\n }\n\n /**\n * Persistable fields paired with a stable storage key. Uniquely-named fields key\n * by their name (unchanged, backward-compatible). Repeated same-name fields\n * (e.g. a `tags[]` checkbox group or array text inputs) are disambiguated by\n * DOM-order occurrence — the first keeps its plain `name` (backward-\n * compatible), later ones get a NUL-separated index suffix — so each is stored and\n * restored individually instead of the last one clobbering the rest. Radios are\n * the exception: a group intentionally shares one key (one value per name).\n */\n #fieldEntries(): Array<{ field: PersistField; key: string }> {\n const entries: Array<{ field: PersistField; key: string }> = [];\n const occurrence = new Map<string, number>();\n for (const field of this.#fields()) {\n const name = this.#keyOf(field);\n if (name === null) continue;\n if (field instanceof HTMLInputElement && field.type === \"radio\") {\n entries.push({ field, key: name });\n continue;\n }\n const seen = occurrence.get(name) ?? 0;\n occurrence.set(name, seen + 1);\n entries.push({ field, key: seen === 0 ? name : `${name}${OCCURRENCE_SEP}${seen}` });\n }\n return entries;\n }\n\n /** The fields to persist: `field` targets, or the element's named controls. */\n #fields(): PersistField[] {\n const candidates = this.hasFieldTarget\n ? this.fieldTargets\n : Array.from(this.element.querySelectorAll<PersistField>(\"input, textarea, select\"));\n return candidates.filter((field) => this.#persistable(field));\n }\n\n /** Whether a field carries a restorable, non-excluded value. */\n #persistable(field: PersistField): boolean {\n if (this.#keyOf(field) === null) return false;\n const type = field instanceof HTMLInputElement ? field.type : \"\";\n if (NON_VALUE_TYPES.has(type)) return false;\n if (this.excludeValue.includes(type)) return false;\n if (field.name.length > 0 && this.excludeValue.includes(field.name)) return false;\n return true;\n }\n\n /** A stable storage sub-key for a field (its name, else id). */\n #keyOf(field: PersistField): string | null {\n return field.name || field.id || null;\n }\n\n /** The logical key (key Value or element id), or null when neither is set. */\n get #logicalKey(): string | null {\n const key = this.keyValue || this.element.id;\n return key.length > 0 ? key : null;\n }\n\n /** The prefixed localStorage key, or null when persistence is disabled. */\n get #storageKey(): string | null {\n const logical = this.#logicalKey;\n return logical === null ? null : `${STORAGE_PREFIX}${logical}`;\n }\n\n #getItem(key: string): string | null {\n try {\n return window.localStorage.getItem(key);\n } catch {\n return null;\n }\n }\n\n #setItem(key: string, value: string): void {\n try {\n window.localStorage.setItem(key, value);\n } catch {\n // Storage full or unavailable (private mode): persistence is best-effort.\n }\n }\n\n #removeItem(key: string): void {\n try {\n window.localStorage.removeItem(key);\n } catch {\n // Ignore: nothing to clear if storage is unavailable.\n }\n }\n}\n"]}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { Controller } from '@hotwired/stimulus';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Headless, accessible **non-modal popover** behavior.
|
|
5
|
+
*
|
|
6
|
+
* Markup contract (identifier: `stimeo--popover`):
|
|
7
|
+
* <div data-controller="stimeo--popover">
|
|
8
|
+
* <button data-stimeo--popover-target="trigger"
|
|
9
|
+
* aria-haspopup="dialog" aria-expanded="false" aria-controls="pop"
|
|
10
|
+
* data-action="click->stimeo--popover#toggle">Edit profile</button>
|
|
11
|
+
* <div id="pop" data-stimeo--popover-target="panel"
|
|
12
|
+
* role="dialog" aria-label="Edit profile" hidden>…</div>
|
|
13
|
+
* </div>
|
|
14
|
+
*
|
|
15
|
+
* Implements the WAI-ARIA APG **Dialog** pattern run *non-modally* (no
|
|
16
|
+
* `aria-modal`, no focus trap, no `inert`/scroll lock). The background stays
|
|
17
|
+
* fully interactive; this is the modeless counterpart to `stimeo--dialog`. For
|
|
18
|
+
* a roving `role="menu"` of commands use `stimeo--menu`; for decorative-only
|
|
19
|
+
* text use `stimeo--tooltip`.
|
|
20
|
+
*
|
|
21
|
+
* @remarks
|
|
22
|
+
* Behavior only — static placement is the consumer's CSS, and dynamic
|
|
23
|
+
* edge-collision avoidance is delegated to the opt-in `stimeo-ui/positioning`
|
|
24
|
+
* module (this controller never imports it, preserving the zero-dep core). State
|
|
25
|
+
* is exposed via the trigger's `aria-expanded` and the panel's `hidden`.
|
|
26
|
+
*
|
|
27
|
+
* Behavior provided:
|
|
28
|
+
* - Click the trigger to toggle (`aria-expanded` + `hidden` reflect state).
|
|
29
|
+
* - On open, focus moves to the first focusable element inside the panel (or the
|
|
30
|
+
* panel itself if it has none).
|
|
31
|
+
* - `Escape` closes and restores focus to the trigger.
|
|
32
|
+
* - An outside click (anywhere off the controller element) closes and restores
|
|
33
|
+
* focus to the trigger.
|
|
34
|
+
* - Because it is modeless, focus is *not* trapped: when `Tab` moves focus out of
|
|
35
|
+
* the panel it closes (detected via `focusout`) without yanking focus back, so
|
|
36
|
+
* the natural tab destination is preserved.
|
|
37
|
+
*/
|
|
38
|
+
declare class PopoverController extends Controller<HTMLElement> {
|
|
39
|
+
#private;
|
|
40
|
+
static targets: string[];
|
|
41
|
+
static actions: readonly ["close", "open", "toggle"];
|
|
42
|
+
readonly triggerTarget: HTMLButtonElement;
|
|
43
|
+
readonly panelTarget: HTMLElement;
|
|
44
|
+
readonly hasTriggerTarget: boolean;
|
|
45
|
+
readonly hasPanelTarget: boolean;
|
|
46
|
+
/** Starts closed and registers the document-level dismissal listeners. */
|
|
47
|
+
connect(): void;
|
|
48
|
+
/**
|
|
49
|
+
* Removes the document-level listeners registered in {@link connect}, plus the
|
|
50
|
+
* panel's `focusout` listener if the popover is torn down while open (e.g. a
|
|
51
|
+
* Turbo navigation). `removeEventListener` is a no-op when it was never added,
|
|
52
|
+
* so this is safe in the closed state too — no listener outlives the element.
|
|
53
|
+
*/
|
|
54
|
+
disconnect(): void;
|
|
55
|
+
/** Toggles the popover. Bound via `data-action` (click on the trigger). */
|
|
56
|
+
toggle(): void;
|
|
57
|
+
/** Opens the panel, reflects state, and moves focus inside it. */
|
|
58
|
+
open(): void;
|
|
59
|
+
/** Closes the panel and reflects the collapsed state. Bound via `data-action`. */
|
|
60
|
+
close(): void;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export { PopoverController };
|