stimeo-ui 0.8.0 → 0.10.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.
Files changed (167) hide show
  1. package/CHANGELOG.md +163 -0
  2. package/dist/controllers/accordion_controller.js.map +1 -1
  3. package/dist/controllers/alert_dialog_controller.js +17 -7
  4. package/dist/controllers/alert_dialog_controller.js.map +1 -1
  5. package/dist/controllers/announcer_controller.js +1 -1
  6. package/dist/controllers/announcer_controller.js.map +1 -1
  7. package/dist/controllers/auto_submit_controller.js.map +1 -1
  8. package/dist/controllers/avatar_controller.js.map +1 -1
  9. package/dist/controllers/breadcrumb_controller.js.map +1 -1
  10. package/dist/controllers/bulk_select_controller.d.ts +62 -15
  11. package/dist/controllers/bulk_select_controller.js +139 -28
  12. package/dist/controllers/bulk_select_controller.js.map +1 -1
  13. package/dist/controllers/calendar_controller.js.map +1 -1
  14. package/dist/controllers/carousel_controller.js.map +1 -1
  15. package/dist/controllers/character_counter_controller.js.map +1 -1
  16. package/dist/controllers/clipboard_controller.d.ts +48 -15
  17. package/dist/controllers/clipboard_controller.js +102 -20
  18. package/dist/controllers/clipboard_controller.js.map +1 -1
  19. package/dist/controllers/collapsible_controller.d.ts +1 -1
  20. package/dist/controllers/collapsible_controller.js +1 -1
  21. package/dist/controllers/collapsible_controller.js.map +1 -1
  22. package/dist/controllers/color_picker_controller.d.ts +37 -6
  23. package/dist/controllers/color_picker_controller.js +180 -43
  24. package/dist/controllers/color_picker_controller.js.map +1 -1
  25. package/dist/controllers/combobox_controller.js.map +1 -1
  26. package/dist/controllers/command_palette_controller.js +15 -5
  27. package/dist/controllers/command_palette_controller.js.map +1 -1
  28. package/dist/controllers/conditional_fields_controller.js.map +1 -1
  29. package/dist/controllers/confirm_controller.js +15 -5
  30. package/dist/controllers/confirm_controller.js.map +1 -1
  31. package/dist/controllers/context_menu_controller.d.ts +5 -4
  32. package/dist/controllers/context_menu_controller.js.map +1 -1
  33. package/dist/controllers/count_up_controller.js.map +1 -1
  34. package/dist/controllers/countdown_controller.js +1 -1
  35. package/dist/controllers/countdown_controller.js.map +1 -1
  36. package/dist/controllers/data_grid_controller.d.ts +25 -9
  37. package/dist/controllers/data_grid_controller.js +151 -25
  38. package/dist/controllers/data_grid_controller.js.map +1 -1
  39. package/dist/controllers/date_range_picker_controller.js.map +1 -1
  40. package/dist/controllers/dialog_controller.js +15 -5
  41. package/dist/controllers/dialog_controller.js.map +1 -1
  42. package/dist/controllers/direct_upload_controller.d.ts +2 -2
  43. package/dist/controllers/direct_upload_controller.js +1 -5
  44. package/dist/controllers/direct_upload_controller.js.map +1 -1
  45. package/dist/controllers/dismissible_controller.js.map +1 -1
  46. package/dist/controllers/drawer_controller.d.ts +2 -2
  47. package/dist/controllers/drawer_controller.js +17 -7
  48. package/dist/controllers/drawer_controller.js.map +1 -1
  49. package/dist/controllers/editable_controller.d.ts +34 -9
  50. package/dist/controllers/editable_controller.js +83 -30
  51. package/dist/controllers/editable_controller.js.map +1 -1
  52. package/dist/controllers/file_dropzone_controller.js.map +1 -1
  53. package/dist/controllers/filter_controller.d.ts +15 -3
  54. package/dist/controllers/filter_controller.js +32 -1
  55. package/dist/controllers/filter_controller.js.map +1 -1
  56. package/dist/controllers/flash_controller.js.map +1 -1
  57. package/dist/controllers/focus_controller.d.ts +5 -0
  58. package/dist/controllers/focus_controller.js +45 -7
  59. package/dist/controllers/focus_controller.js.map +1 -1
  60. package/dist/controllers/form_field_controller.js +1 -1
  61. package/dist/controllers/form_field_controller.js.map +1 -1
  62. package/dist/controllers/form_validation_controller.js.map +1 -1
  63. package/dist/controllers/frame_loading_controller.js.map +1 -1
  64. package/dist/controllers/highlight_controller.js.map +1 -1
  65. package/dist/controllers/input_mask_controller.js.map +1 -1
  66. package/dist/controllers/intersection_controller.d.ts +4 -3
  67. package/dist/controllers/intersection_controller.js.map +1 -1
  68. package/dist/controllers/lazy_frame_controller.d.ts +2 -2
  69. package/dist/controllers/lazy_frame_controller.js.map +1 -1
  70. package/dist/controllers/listbox_controller.js.map +1 -1
  71. package/dist/controllers/masonry_controller.d.ts +36 -5
  72. package/dist/controllers/masonry_controller.js +129 -17
  73. package/dist/controllers/masonry_controller.js.map +1 -1
  74. package/dist/controllers/menu_controller.d.ts +1 -1
  75. package/dist/controllers/menu_controller.js.map +1 -1
  76. package/dist/controllers/menubar_controller.js +2 -2
  77. package/dist/controllers/menubar_controller.js.map +1 -1
  78. package/dist/controllers/meter_controller.d.ts +1 -1
  79. package/dist/controllers/meter_controller.js.map +1 -1
  80. package/dist/controllers/multi_select_controller.js +1 -1
  81. package/dist/controllers/multi_select_controller.js.map +1 -1
  82. package/dist/controllers/navigation_menu_controller.js.map +1 -1
  83. package/dist/controllers/nested_form_controller.js.map +1 -1
  84. package/dist/controllers/number_input_controller.js.map +1 -1
  85. package/dist/controllers/otp_controller.d.ts +4 -1
  86. package/dist/controllers/otp_controller.js +29 -16
  87. package/dist/controllers/otp_controller.js.map +1 -1
  88. package/dist/controllers/overflow_indicator_controller.js.map +1 -1
  89. package/dist/controllers/overflow_menu_controller.js +2 -2
  90. package/dist/controllers/overflow_menu_controller.js.map +1 -1
  91. package/dist/controllers/pagination_controller.d.ts +1 -1
  92. package/dist/controllers/pagination_controller.js.map +1 -1
  93. package/dist/controllers/password_reveal_controller.d.ts +27 -2
  94. package/dist/controllers/password_reveal_controller.js +102 -3
  95. package/dist/controllers/password_reveal_controller.js.map +1 -1
  96. package/dist/controllers/password_strength_controller.d.ts +71 -17
  97. package/dist/controllers/password_strength_controller.js +287 -42
  98. package/dist/controllers/password_strength_controller.js.map +1 -1
  99. package/dist/controllers/pointer_drag_controller.d.ts +3 -2
  100. package/dist/controllers/pointer_drag_controller.js.map +1 -1
  101. package/dist/controllers/popover_controller.js.map +1 -1
  102. package/dist/controllers/portal_controller.d.ts +1 -1
  103. package/dist/controllers/portal_controller.js.map +1 -1
  104. package/dist/controllers/progress_controller.js.map +1 -1
  105. package/dist/controllers/radio_group_controller.js.map +1 -1
  106. package/dist/controllers/range_slider_controller.js.map +1 -1
  107. package/dist/controllers/rating_controller.js.map +1 -1
  108. package/dist/controllers/read_more_controller.js.map +1 -1
  109. package/dist/controllers/relative_time_controller.js.map +1 -1
  110. package/dist/controllers/reset_before_cache_controller.d.ts +26 -4
  111. package/dist/controllers/reset_before_cache_controller.js +51 -5
  112. package/dist/controllers/reset_before_cache_controller.js.map +1 -1
  113. package/dist/controllers/resizable_controller.d.ts +23 -7
  114. package/dist/controllers/resizable_controller.js +128 -55
  115. package/dist/controllers/resizable_controller.js.map +1 -1
  116. package/dist/controllers/roving_controller.d.ts +2 -1
  117. package/dist/controllers/roving_controller.js.map +1 -1
  118. package/dist/controllers/scroll_area_controller.js.map +1 -1
  119. package/dist/controllers/scroll_restore_controller.d.ts +33 -11
  120. package/dist/controllers/scroll_restore_controller.js +127 -27
  121. package/dist/controllers/scroll_restore_controller.js.map +1 -1
  122. package/dist/controllers/scroll_visibility_controller.d.ts +42 -10
  123. package/dist/controllers/scroll_visibility_controller.js +167 -14
  124. package/dist/controllers/scroll_visibility_controller.js.map +1 -1
  125. package/dist/controllers/scrollspy_controller.js.map +1 -1
  126. package/dist/controllers/separator_controller.js.map +1 -1
  127. package/dist/controllers/sidebar_controller.js +15 -5
  128. package/dist/controllers/sidebar_controller.js.map +1 -1
  129. package/dist/controllers/skeleton_controller.js.map +1 -1
  130. package/dist/controllers/slider_controller.js.map +1 -1
  131. package/dist/controllers/spinner_controller.js.map +1 -1
  132. package/dist/controllers/step_indicator_controller.js +0 -5
  133. package/dist/controllers/step_indicator_controller.js.map +1 -1
  134. package/dist/controllers/stick_to_bottom_controller.d.ts +3 -2
  135. package/dist/controllers/stick_to_bottom_controller.js.map +1 -1
  136. package/dist/controllers/submit_once_controller.js.map +1 -1
  137. package/dist/controllers/switch_controller.js.map +1 -1
  138. package/dist/controllers/tabs_controller.js.map +1 -1
  139. package/dist/controllers/tags_input_controller.js.map +1 -1
  140. package/dist/controllers/textarea_autosize_controller.js.map +1 -1
  141. package/dist/controllers/theme_controller.d.ts +32 -6
  142. package/dist/controllers/theme_controller.js +151 -40
  143. package/dist/controllers/theme_controller.js.map +1 -1
  144. package/dist/controllers/time_picker_controller.js.map +1 -1
  145. package/dist/controllers/toast_controller.d.ts +2 -2
  146. package/dist/controllers/toast_controller.js +2 -2
  147. package/dist/controllers/toast_controller.js.map +1 -1
  148. package/dist/controllers/toggle_group_controller.js.map +1 -1
  149. package/dist/controllers/toolbar_controller.js.map +1 -1
  150. package/dist/controllers/transition_controller.d.ts +11 -7
  151. package/dist/controllers/transition_controller.js +79 -15
  152. package/dist/controllers/transition_controller.js.map +1 -1
  153. package/dist/controllers/tree_view_controller.js.map +1 -1
  154. package/dist/index.d.ts +6 -3
  155. package/dist/index.js +1612 -529
  156. package/dist/index.js.map +1 -1
  157. package/dist/inspector/cli.d.ts +3 -4
  158. package/dist/inspector/cli.js +3 -0
  159. package/dist/inspector/cli.js.map +1 -1
  160. package/dist/inspector/cli_bin.js +8 -5
  161. package/dist/inspector/cli_bin.js.map +1 -1
  162. package/dist/inspector/examples.json +25 -25
  163. package/dist/inspector/manifest.json +18 -11
  164. package/dist/positioning/index.d.ts +18 -4
  165. package/dist/positioning/index.js +84 -25
  166. package/dist/positioning/index.js.map +1 -1
  167. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/announce.ts","../../src/utils/attribute_lease.ts","../../src/utils/before_cache_reset.ts","../../src/utils/composition_tracker.ts","../../src/utils/microtask_coalescer.ts","../../src/utils/safe_timeout.ts","../../src/controllers/character_counter_controller.ts"],"names":[],"mappings":";;;;;AAoBO,SAAS,QAAA,CAAS,OAAA,EAAiB,OAAA,GAAmC,EAAC,EAAS;AACrF,EAAA,MAAM,IAAA,GAAO,QAAQ,IAAA,EAAK;AAC1B,EAAA,IAAI,IAAA,CAAK,WAAW,CAAA,EAAG;AACvB,EAAA,MAAA,CAAO,aAAA;AAAA,IACL,IAAI,YAAY,4BAAA,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KAAK,CAAA;AAAA,EACvC;AAAA;AAAA,EAGA,eAAA,GAAwB;AACtB,IAAA,IAAA,CAAK,mBAAA,EAAoB;AACzB,IAAA,IAAA,CAAK,aAAa,SAAA,EAAU;AAC5B,IAAA,IAAA,CAAK,cAAA,GAAiB,IAAA;AACtB,IAAA,IAAA,CAAK,gBAAA,EAAiB;AAAA,EACxB;AAAA;AAAA,EAGA,gBAAgB,GAAA,EAAqB;AACnC,IAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,GAAG,GAAG,OAAO,CAAA;AAClC,IAAA,OAAO,KAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,KAAA,CAAM,GAAG,CAAC,CAAA;AAAA,EACpC;AAAA;AAAA,EAGA,IAAI,KAAA,GAAqB;AACvB,IAAA,IAAI,KAAK,SAAA,KAAc,MAAA,IAAU,KAAK,SAAA,KAAc,MAAA,SAAe,IAAA,CAAK,SAAA;AACxE,IAAA,OAAO,WAAA;AAAA,EACT;AAAA;AAAA,EAGA,IAAI,MAAA,GAAuC;AACzC,IAAA,IAAI,IAAA,CAAK,cAAA,EAAgB,OAAO,IAAA,CAAK,WAAA;AACrC,IAAA,MAAM,UAAuB,IAAA,CAAK,OAAA;AAClC,IAAA,IAAI,OAAA,YAAmB,oBAAoB,OAAA,YAAmB,mBAAA;AAC5D,MAAA,OAAO,OAAA;AACT,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"character_counter_controller.js","sourcesContent":["/**\n * Sends one message to the page's shared `stimeo--announcer`.\n *\n * A component that has to reach assistive tech does not carry a live region of its\n * own: a region only announces what changes *after* assistive tech already knows\n * about it, which a region that appears (or is un-hidden) with its message cannot\n * satisfy. The one region that can is the announcer sitting in the page from the\n * start, so state changes are handed to it as an event and it does the reading.\n *\n * The event goes to `window` because the announcer is usually a sibling high in the\n * document rather than an ancestor of the component dispatching it.\n *\n * Wording comes from the consumer — the library ships no English strings — so an\n * empty message is silently dropped and nothing is announced.\n *\n * @example\n * ```ts\n * announce(this.announceTextValue, { assertive: false });\n * ```\n */\nexport function announce(message: string, options: { assertive?: boolean } = {}): void {\n const text = message.trim();\n if (text.length === 0) return;\n window.dispatchEvent(\n new CustomEvent(\"stimeo--announcer:announce\", {\n detail: { message: text, assertive: options.assertive === true },\n }),\n );\n}\n\n/**\n * Fills `{name}` placeholders in an announcement template from `values`.\n *\n * The same substitution the value-text templates use, so a consumer writes\n * `\"{percent}% complete\"` in one attribute and gets the same rules everywhere. A\n * placeholder with no matching entry is left as authored rather than blanked, which\n * keeps a typo visible instead of silently swallowing the word.\n */\nexport function fillTemplate(template: string, values: Record<string, string | number>): string {\n return template.replace(/\\{([a-zA-Z][a-zA-Z0-9]*)\\}/g, (match, name: string) => {\n const replacement = values[name];\n return replacement === undefined ? match : String(replacement);\n });\n}\n","/** One temporarily controlled attribute value and the authored value it displaced. */\ninterface AttributeLeaseRecord {\n readonly original: string | null;\n written: string | null;\n}\n\n/**\n * Temporarily controls one attribute across a changing set of elements.\n *\n * The first write remembers the authored value, including the distinction between\n * an absent attribute and an authored empty string. Returning a lease restores that\n * value only while the attribute still matches the controller's last write. If a\n * consumer changed it in the meantime, the consumer owns the new value and teardown\n * leaves it alone.\n *\n * A `null` write deliberately removes the attribute while retaining the lease. This\n * is useful for derived ARIA whose valid absence is itself controller state, such as\n * an unbounded `aria-valuemin` or a blank spinbutton's `aria-valuenow`.\n *\n * The lease has no lifecycle of its own, so it never subscribes to document events.\n * A consumer that must not let a derived value become the authored baseline of a\n * cached page returns its leases from its own `turbo:before-cache` rewind, where the\n * matching `disconnect()` also releases the subscription.\n */\nexport class AttributeLease<T extends Element = Element> {\n readonly #attribute: string;\n readonly #records = new Map<T, AttributeLeaseRecord>();\n\n /** @param attribute - The attribute whose temporary values this lease owns. */\n constructor(attribute: string) {\n this.#attribute = attribute;\n }\n\n /** Writes or removes the leased attribute while preserving its authored value. */\n write(element: T, value: string | null): void {\n const existing = this.#records.get(element);\n if (existing) {\n existing.written = value;\n } else {\n this.#records.set(element, {\n original: element.getAttribute(this.#attribute),\n written: value,\n });\n }\n\n this.#reflect(element, value);\n }\n\n /** Returns one lease without overwriting a value subsequently authored by a consumer. */\n return(element: T): void {\n const record = this.#records.get(element);\n if (!record) return;\n this.#records.delete(element);\n const stillOwned = element.getAttribute(this.#attribute) === record.written;\n if (stillOwned) this.#reflect(element, record.original);\n }\n\n /** Reflects only a real value transition, avoiding self-triggered mutation work. */\n #reflect(element: T, value: string | null): void {\n if (element.getAttribute(this.#attribute) === value) return;\n if (value === null) element.removeAttribute(this.#attribute);\n else element.setAttribute(this.#attribute, value);\n }\n\n /** Returns every outstanding lease using the same ownership check as {@link return}. */\n returnAll(): void {\n for (const element of Array.from(this.#records.keys())) this.return(element);\n }\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","/** Minimal event shape carrying the platform's per-event composition signal. */\nexport interface CompositionSignal {\n readonly isComposing?: boolean;\n}\n\n/** Hooks that keep component-specific work outside {@link CompositionTracker}. */\nexport interface CompositionTrackerOptions {\n /** Runs after lifecycle state is set for a `compositionstart` event. */\n readonly onStart?: (event: Event) => void;\n /** Runs after lifecycle state is cleared for a `compositionend` event. */\n readonly onEnd?: (event: Event) => void;\n}\n\n/**\n * Owns IME composition listeners and transient state for one or more event targets.\n *\n * Some browsers omit `KeyboardEvent.isComposing` on the keydown that confirms a\n * conversion. Tracking `compositionstart` through `compositionend` supplies the\n * missing lifecycle signal without relying on deprecated numeric key codes.\n * Component policy stays with the consumer: filtering, validation, and submission\n * belong in the optional {@link CompositionTrackerOptions.onEnd} callback.\n *\n * @example\n * ```ts\n * #composition = new CompositionTracker({ onEnd: () => this.filter() });\n *\n * connect(): void {\n * this.#composition.observe(this.inputTarget);\n * }\n *\n * disconnect(): void {\n * this.#composition.disconnect();\n * }\n *\n * onKeydown(event: KeyboardEvent): void {\n * if (this.#composition.isComposing(event)) return;\n * }\n * ```\n */\nexport class CompositionTracker {\n readonly #observedTargets = new Set<EventTarget>();\n readonly #activeTargets = new Set<EventTarget>();\n readonly #onStart: ((event: Event) => void) | undefined;\n readonly #onEnd: ((event: Event) => void) | undefined;\n\n constructor(options: CompositionTrackerOptions = {}) {\n this.#onStart = options.onStart;\n this.#onEnd = options.onEnd;\n }\n\n /** Starts lifecycle tracking for `target`; repeated calls are idempotent. */\n observe(target: EventTarget): void {\n if (this.#observedTargets.has(target)) return;\n target.addEventListener(\"compositionstart\", this.#handleStart);\n target.addEventListener(\"compositionend\", this.#handleEnd);\n this.#observedTargets.add(target);\n }\n\n /** Stops tracking one target and clears any active composition it owned. */\n unobserve(target: EventTarget): void {\n if (!this.#observedTargets.delete(target)) return;\n target.removeEventListener(\"compositionstart\", this.#handleStart);\n target.removeEventListener(\"compositionend\", this.#handleEnd);\n this.#activeTargets.delete(target);\n }\n\n /** Releases every listener and clears state so reconnect starts cleanly. */\n disconnect(): void {\n for (const target of this.#observedTargets) {\n target.removeEventListener(\"compositionstart\", this.#handleStart);\n target.removeEventListener(\"compositionend\", this.#handleEnd);\n }\n this.#observedTargets.clear();\n this.#activeTargets.clear();\n }\n\n /** True when lifecycle tracking or the current event reports composition. */\n isComposing(event?: CompositionSignal): boolean {\n return this.#activeTargets.size > 0 || event?.isComposing === true;\n }\n\n readonly #handleStart = (event: Event): void => {\n if (event.currentTarget) this.#activeTargets.add(event.currentTarget);\n this.#onStart?.(event);\n };\n\n readonly #handleEnd = (event: Event): void => {\n if (event.currentTarget) this.#activeTargets.delete(event.currentTarget);\n this.#onEnd?.(event);\n };\n}\n","/**\n * Collapses many Stimulus lifecycle callbacks from one DOM mutation into a\n * single pass.\n *\n * Stimulus fires `<name>TargetConnected` / `Disconnected` once per element and\n * `<name>ValueChanged` once per changed attribute. Replacing a list of N options\n * or morphing several render Values therefore delivers N callbacks — but the\n * useful unit of work is \"reconcile against the resulting declarative input\",\n * once, after the batch has settled. Every controller with reconcilable targets\n * or render Values needs the same shape: a `queued` flag plus `queueMicrotask`.\n *\n * **A microtask is the right horizon, and the reason is specific.** Stimulus\n * drives these callbacks from a `MutationObserver`, whose own callback already\n * runs as a microtask with the whole batch in hand; scheduling one more lands\n * after the last sibling callback of that batch and still before paint or any\n * event handler. A timer would be later than it needs to be, and reconciling\n * synchronously would run once per element against a half-applied DOM.\n *\n * **The two guards are not the same guard.** Scheduling is refused before the\n * controller connects, and running is refused after it disconnects:\n *\n * - **Before `connect()`** — Stimulus delivers initial target and Value callbacks\n * ahead of `connect()`. Reconciling there would compute output against a\n * controller whose own state has not been initialised, and `connect()` is\n * about to do a full pass anyway.\n * - **After `disconnect()`** — Stimulus fires a callback for **every** target\n * during teardown, and a microtask queued just before it would otherwise run\n * against a detached tree. {@link MicrotaskCoalescer.cancel} exists for the\n * teardown path to drop the pending pass outright.\n *\n * Both guards are part of one contract here rather than something each consumer\n * has to remember separately.\n *\n * Scope is the scheduling only. *What* to reconcile — keep the surviving active\n * option, fall back to the next / previous / first visible one, rebuild derived\n * chips or hidden fields — stays in the controller, because no two consumers\n * answer it the same way.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileOptions());\n *\n * connect() { this.#reconcile.activate(); }\n * disconnect() { this.#reconcile.cancel(); }\n *\n * optionTargetConnected() { this.#reconcile.schedule(); }\n * optionTargetDisconnected() { this.#reconcile.schedule(); }\n * ```\n */\nexport class MicrotaskCoalescer {\n readonly #run: () => void;\n #queued = false;\n #active = false;\n #generation = 0;\n\n /** @param run - the single reconciliation pass, invoked at most once per batch. */\n constructor(run: () => void) {\n this.#run = run;\n }\n\n /** Opens the window in which {@link schedule} is honoured; call from `connect()`. */\n activate(): void {\n this.#active = true;\n }\n\n /** Closes the window and drops any pending pass; call from `disconnect()`. */\n cancel(): void {\n this.#active = false;\n this.#queued = false;\n this.#generation += 1;\n }\n\n /** Requests one pass after the batch settles. Idempotent; inert outside the window. */\n schedule(): void {\n if (!this.#active || this.#queued) return;\n this.#queued = true;\n const generation = this.#generation;\n queueMicrotask(() => {\n // A cancelled callback must not consume a pass queued after reconnect.\n if (generation !== this.#generation || !this.#queued || !this.#active) return;\n this.#queued = false;\n this.#run();\n });\n }\n}\n","/**\n * 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 { announce, fillTemplate } from \"../utils/announce\";\nimport { AttributeLease } from \"../utils/attribute_lease\";\nimport { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { CompositionTracker } from \"../utils/composition_tracker\";\nimport { MicrotaskCoalescer } from \"../utils/microtask_coalescer\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\ntype CharacterCounterField = HTMLInputElement | HTMLTextAreaElement;\ntype DisplayMode = \"remaining\" | \"used\" | \"both\";\n\ninterface CharacterCountReading {\n readonly length: number;\n readonly remaining: number | null;\n readonly over: boolean;\n readonly max: number;\n readonly text: string;\n}\n\ntype CharacterCounterDetail = Pick<CharacterCountReading, \"length\" | \"remaining\" | \"over\">;\n\n/**\n * Headless character-counter behavior for a text field (no dedicated APG\n * pattern; follows the WCAG 2.2 \"status messages\" practice, 4.1.3).\n *\n * Markup contract (identifier: `stimeo--character-counter`):\n * <div data-controller=\"stimeo--character-counter\"\n * data-stimeo--character-counter-max-value=\"140\"\n * data-stimeo--character-counter-announce-text-value=\"{remaining} characters remaining\">\n * <textarea data-stimeo--character-counter-target=\"input\"\n * aria-describedby=\"cc\"></textarea>\n * <span id=\"cc\" data-stimeo--character-counter-target=\"output\"></span>\n * </div>\n *\n * Watches the field's UTF-16 code-unit length, writes the remaining/used count\n * into `output`, and toggles the `data-near-limit` / `data-over-limit` state\n * hooks. While over the limit it temporarily leases `aria-invalid=\"true\"` on\n * the field and returns the consumer's authored value on recovery or teardown.\n * The field is the first `input` target, or — when the controller is attached\n * straight onto an `<input>`/`<textarea>` — the controller element itself.\n *\n * `change` and `reconcile` dispatch\n * `{ length: number, remaining: number | null, over: boolean }`.\n *\n * @remarks\n * Behavior only — count text and state update synchronously, with no styling.\n * Confirmed user input dispatches `stimeo--character-counter:change` only when\n * the measured length actually changes. Its detail is `{ length, remaining,\n * over }`; `remaining` is `null` when `max` is disabled. IME intermediate input\n * is ignored, and `compositionend` commits the confirmed value exactly once.\n *\n * Assistive notification is opt-in and i18n-neutral. `announceText` accepts\n * `{count}`, `{length}`, `{remaining}`, `{max}`, and `{over}` placeholders and\n * sends the settled message to the page's shared `stimeo--announcer` after a\n * short debounce. The visible `output` is not itself required to be a live\n * region. Initial reflection and Turbo restoration never dispatch or announce.\n * Runtime target/Value reconciliation dispatches\n * `stimeo--character-counter:reconcile` only when the public derived state\n * changes, and never announces.\n */\nexport class CharacterCounterController extends Controller<HTMLElement> {\n static override targets = [\"input\", \"output\"];\n static override values = {\n max: { type: Number, default: 0 },\n warnAt: { type: Number, default: 0 },\n mode: { type: String, default: \"remaining\" },\n announceText: { type: String, default: \"\" },\n };\n static events = [\"change\", \"reconcile\"] as const;\n\n declare readonly inputTarget: CharacterCounterField;\n declare readonly outputTarget: HTMLElement;\n declare readonly hasInputTarget: boolean;\n declare readonly hasOutputTarget: boolean;\n\n declare maxValue: number;\n declare warnAtValue: number;\n declare modeValue: string;\n declare announceTextValue: string;\n\n /** Delay (ms) before one settled count is sent to the shared announcer. */\n static readonly #announceDelay = 200;\n\n readonly #timeouts = new SafeTimeout();\n readonly #ariaInvalid = new AttributeLease<CharacterCounterField>(\"aria-invalid\");\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());\n readonly #repaint = new MicrotaskCoalescer(() => this.#reconcile(true));\n readonly #composition = new CompositionTracker({\n onEnd: (event) => this.#commitFrom(event.currentTarget),\n });\n #announceId: number | null = null;\n #boundField: CharacterCounterField | null = null;\n #lastLength: number | null = null;\n #lastDetail: CharacterCounterDetail | null = null;\n #reflectedOver: boolean | null = null;\n\n readonly #onInput = (event: Event): void => {\n const field = this.#boundField;\n if (!field || event.currentTarget !== field || this.#field !== field) return;\n if (this.#composition.isComposing(event as InputEvent)) return;\n this.#commit(field);\n };\n\n /** Reflects the current DOM state and opens the mutation-reconciliation window. */\n override connect(): void {\n this.#repaint.activate();\n this.#beforeCache.activate();\n this.#reconcile(false);\n }\n\n /** Releases listeners, timers, borrowed ARIA, and controller-owned state hooks. */\n override disconnect(): void {\n this.#repaint.cancel();\n this.#beforeCache.deactivate();\n this.#cancelAnnouncement();\n this.#bindField(null);\n this.#composition.disconnect();\n this.#clearStateHooks();\n this.#lastLength = null;\n this.#lastDetail = null;\n }\n\n /** Rebinds and repaints after an input target is added or replaced at runtime. */\n inputTargetConnected(): void {\n this.#repaint.schedule();\n }\n\n /** Releases and repaints after an input target is removed or replaced at runtime. */\n inputTargetDisconnected(): void {\n this.#repaint.schedule();\n }\n\n /** Initializes a display target inserted after the controller connected. */\n outputTargetConnected(): void {\n this.#repaint.schedule();\n }\n\n /** Reconciles the optional display target set after a removal or replacement. */\n outputTargetDisconnected(): void {\n this.#repaint.schedule();\n }\n\n /** Repaints when application code or a Turbo morph changes `max`. */\n maxValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /** Repaints when application code or a Turbo morph changes `warnAt`. */\n warnAtValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /** Repaints when application code or a Turbo morph changes `mode`. */\n modeValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /** Cancels a pending old message when its consumer-authored template changes. */\n announceTextValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /** Rebinds one mutation batch and reports a changed controller-derived state. */\n #reconcile(report: boolean): void {\n const previous = this.#lastDetail;\n // An edit inside the debounce window has already earned an announcement.\n // Reconciliation never originates one, but it must not swallow that one\n // either: the pending message is retargeted at the settled reading, so the\n // user hears the count that ends up displayed rather than nothing. A\n // replaced field is the exception — its pending message describes a field\n // the reader can no longer reach.\n const owedField = this.#announceId === null ? null : this.#boundField;\n this.#cancelAnnouncement();\n this.#bindField(this.#field);\n if (this.#composition.isComposing()) return;\n const field = this.#boundField;\n if (!field) {\n this.#renderEmpty();\n this.#lastLength = null;\n this.#lastDetail = null;\n return;\n }\n const reading = this.#render(field);\n const detail = this.#detail(reading);\n this.#lastLength = reading.length;\n this.#lastDetail = detail;\n if (owedField === field) this.#scheduleAnnouncement(reading);\n if (report && previous && this.#detailsDiffer(previous, detail)) {\n this.dispatch(\"reconcile\", { detail });\n }\n }\n\n /** Commits a composition only when it came from the field still owned here. */\n #commitFrom(target: EventTarget | null): void {\n const field = this.#boundField;\n if (!field || target !== field || this.#field !== field) return;\n this.#commit(field);\n }\n\n /** Reflects one confirmed user input and reports only a real length transition. */\n #commit(field: CharacterCounterField): void {\n const reading = this.#render(field);\n const previousLength = this.#lastLength;\n const previousDetail = this.#lastDetail;\n const detail = this.#detail(reading);\n this.#lastLength = reading.length;\n this.#lastDetail = detail;\n if (previousLength === reading.length) {\n if (previousDetail && this.#detailsDiffer(previousDetail, detail)) {\n this.dispatch(\"reconcile\", { detail });\n }\n return;\n }\n\n this.dispatch(\"change\", { detail });\n this.#scheduleAnnouncement(reading);\n }\n\n /** Selects the public event state from the richer internal reading. */\n #detail(reading: CharacterCountReading): CharacterCounterDetail {\n return {\n length: reading.length,\n remaining: reading.remaining,\n over: reading.over,\n };\n }\n\n /** Compares exactly the state carried by `change` and `reconcile`. */\n #detailsDiffer(left: CharacterCounterDetail, right: CharacterCounterDetail): boolean {\n return (\n left.length !== right.length || left.remaining !== right.remaining || left.over !== right.over\n );\n }\n\n /**\n * Synchronizes visible count, state hooks, and temporary validation ARIA.\n *\n * @stimeoRenderRoot\n */\n #render(field: CharacterCounterField): CharacterCountReading {\n const length = field.value.length;\n const max = this.#normalizeCount(this.maxValue);\n const warnAt = this.#normalizeCount(this.warnAtValue);\n const remaining = max > 0 ? max - length : null;\n const over = remaining !== null && remaining < 0;\n const near = remaining !== null && warnAt > 0 && !over && remaining <= warnAt;\n\n this.#toggle(\"data-over-limit\", over);\n this.#toggle(\"data-near-limit\", near);\n this.#reflectInvalid(field, over);\n\n const text = this.#format(length, remaining, max);\n this.#writeOutput(text);\n return { length, remaining, over, max, text };\n }\n\n /** Clears derived output when the declarative input set has no usable field. */\n #renderEmpty(): void {\n this.#ariaInvalid.returnAll();\n this.#reflectedOver = null;\n this.#clearStateHooks();\n this.#writeOutput(\"\");\n }\n\n /** Replaces the observed field symmetrically, returning state from the old one. */\n #bindField(field: CharacterCounterField | null): void {\n if (field === this.#boundField) return;\n\n const previous = this.#boundField;\n if (previous) {\n previous.removeEventListener(\"input\", this.#onInput);\n this.#composition.unobserve(previous);\n this.#ariaInvalid.return(previous);\n }\n\n this.#boundField = field;\n this.#lastLength = null;\n this.#reflectedOver = null;\n if (!field) return;\n\n field.addEventListener(\"input\", this.#onInput);\n this.#composition.observe(field);\n }\n\n /** Leases `aria-invalid` only on the edge into over-limit, then returns it. */\n #reflectInvalid(field: CharacterCounterField, over: boolean): void {\n if (this.#reflectedOver === over) return;\n this.#reflectedOver = over;\n if (over) this.#ariaInvalid.write(field, \"true\");\n else this.#ariaInvalid.return(field);\n }\n\n /** Builds the visible count for the normalized display mode. */\n #format(length: number, remaining: number | null, max: number): string {\n if (remaining === null) return String(length);\n switch (this.#mode) {\n case \"used\":\n return String(length);\n case \"both\":\n return `${length}/${max}`;\n default:\n return String(remaining);\n }\n }\n\n /** Debounces one i18n-neutral message into the shared polite announcer. */\n #scheduleAnnouncement(reading: CharacterCountReading): void {\n this.#cancelAnnouncement();\n const message = fillTemplate(this.announceTextValue, {\n count: reading.text,\n length: reading.length,\n remaining: reading.remaining ?? \"\",\n max: reading.max,\n over: String(reading.over),\n });\n if (message.trim().length === 0) return;\n\n this.#announceId = this.#timeouts.set(() => {\n announce(message);\n this.#announceId = null;\n }, CharacterCounterController.#announceDelay);\n }\n\n /** Cancels the one outstanding announcement without touching visible output. */\n #cancelAnnouncement(): void {\n if (this.#announceId !== null) this.#timeouts.clear(this.#announceId);\n this.#announceId = null;\n }\n\n /** Writes the optional display only when its text actually changed. */\n #writeOutput(text: string): void {\n if (!this.hasOutputTarget || this.outputTarget.textContent === text) return;\n this.outputTarget.textContent = text;\n }\n\n /** Reflects a presence-style state hook without redundant attribute writes. */\n #toggle(name: string, on: boolean): void {\n if (on) {\n if (this.element.getAttribute(name) !== \"true\") this.element.setAttribute(name, \"true\");\n } else if (this.element.hasAttribute(name)) {\n this.element.removeAttribute(name);\n }\n }\n\n /** Removes both state hooks owned by this controller. */\n #clearStateHooks(): void {\n this.#toggle(\"data-over-limit\", false);\n this.#toggle(\"data-near-limit\", false);\n }\n\n /** Returns borrowed ARIA and transient hooks before Turbo snapshots the page. */\n #rewindForCache(): void {\n this.#cancelAnnouncement();\n this.#ariaInvalid.returnAll();\n this.#reflectedOver = null;\n this.#clearStateHooks();\n }\n\n /** Converts a public count Value into a finite non-negative integer. */\n #normalizeCount(raw: number): number {\n if (!Number.isFinite(raw)) return 0;\n return Math.max(0, Math.trunc(raw));\n }\n\n /** Falls back to `remaining` when an authored display mode is unknown. */\n get #mode(): DisplayMode {\n if (this.modeValue === \"used\" || this.modeValue === \"both\") return this.modeValue;\n return \"remaining\";\n }\n\n /** The watched field: the first target, or a directly controlled form field. */\n get #field(): CharacterCounterField | null {\n if (this.hasInputTarget) return this.inputTarget;\n const element: HTMLElement = this.element;\n if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement)\n return element;\n return null;\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/announce.ts","../../src/utils/attribute_lease.ts","../../src/utils/before_cache_reset.ts","../../src/utils/composition_tracker.ts","../../src/utils/microtask_coalescer.ts","../../src/utils/safe_timeout.ts","../../src/controllers/character_counter_controller.ts"],"names":[],"mappings":";;;;;AAoBO,SAAS,QAAA,CAAS,OAAA,EAAiB,OAAA,GAAmC,EAAC,EAAS;AACrF,EAAA,MAAM,IAAA,GAAO,QAAQ,IAAA,EAAK;AAC1B,EAAA,IAAI,IAAA,CAAK,WAAW,CAAA,EAAG;AACvB,EAAA,MAAA,CAAO,aAAA;AAAA,IACL,IAAI,YAAY,4BAAA,EAA8B;AAAA,MAC5C,QAAQ,EAAE,OAAA,EAAS,MAAM,SAAA,EAAW,OAAA,CAAQ,cAAc,IAA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EAAoB;AACzB,IAAA,IAAA,CAAK,aAAa,SAAA,EAAU;AAC5B,IAAA,IAAA,CAAK,cAAA,GAAiB,IAAA;AACtB,IAAA,IAAA,CAAK,gBAAA,EAAiB;AAAA,EACxB;AAAA;AAAA,EAGA,gBAAgB,GAAA,EAAqB;AACnC,IAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,GAAG,GAAG,OAAO,CAAA;AAClC,IAAA,OAAO,KAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,KAAA,CAAM,GAAG,CAAC,CAAA;AAAA,EACpC;AAAA;AAAA,EAGA,IAAI,KAAA,GAAqB;AACvB,IAAA,IAAI,KAAK,SAAA,KAAc,MAAA,IAAU,KAAK,SAAA,KAAc,MAAA,SAAe,IAAA,CAAK,SAAA;AACxE,IAAA,OAAO,WAAA;AAAA,EACT;AAAA;AAAA,EAGA,IAAI,MAAA,GAAuC;AACzC,IAAA,IAAI,IAAA,CAAK,cAAA,EAAgB,OAAO,IAAA,CAAK,WAAA;AACrC,IAAA,MAAM,UAAuB,IAAA,CAAK,OAAA;AAClC,IAAA,IAAI,OAAA,YAAmB,oBAAoB,OAAA,YAAmB,mBAAA;AAC5D,MAAA,OAAO,OAAA;AACT,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"character_counter_controller.js","sourcesContent":["/**\n * Sends one message to the page's shared `stimeo--announcer`.\n *\n * A component that has to reach assistive tech does not carry a live region of its\n * own: a region only announces what changes *after* assistive tech already knows\n * about it, which a region that appears (or is un-hidden) with its message cannot\n * satisfy. The one region that can is the announcer sitting in the page from the\n * start, so state changes are handed to it as an event and it does the reading.\n *\n * The event goes to `window` because the announcer is usually a sibling high in the\n * document rather than an ancestor of the component dispatching it.\n *\n * Wording comes from the consumer — the library ships no English strings — so an\n * empty message is silently dropped and nothing is announced.\n *\n * @example\n * ```ts\n * announce(this.announceTextValue, { assertive: false });\n * ```\n */\nexport function announce(message: string, options: { assertive?: boolean } = {}): void {\n const text = message.trim();\n if (text.length === 0) return;\n window.dispatchEvent(\n new CustomEvent(\"stimeo--announcer:announce\", {\n detail: { message: text, assertive: options.assertive === true },\n }),\n );\n}\n\n/**\n * Fills `{name}` placeholders in an announcement template from `values`.\n *\n * The same substitution the value-text templates use, so a consumer writes\n * `\"{percent}% complete\"` in one attribute and gets the same rules everywhere. A\n * placeholder with no matching entry is left as authored rather than blanked, which\n * keeps a typo visible instead of silently swallowing the word.\n */\nexport function fillTemplate(template: string, values: Record<string, string | number>): string {\n return template.replace(/\\{([a-zA-Z][a-zA-Z0-9]*)\\}/g, (match, name: string) => {\n const replacement = values[name];\n return replacement === undefined ? match : String(replacement);\n });\n}\n","/** One temporarily controlled attribute value and the authored value it displaced. */\ninterface AttributeLeaseRecord {\n readonly original: string | null;\n written: string | null;\n}\n\n/**\n * Temporarily controls one attribute across a changing set of elements.\n *\n * The first write remembers the authored value, including the distinction between\n * an absent attribute and an authored empty string. Returning a lease restores that\n * value only while the attribute still matches the controller's last write. If a\n * consumer changed it in the meantime, the consumer owns the new value and teardown\n * leaves it alone.\n *\n * A `null` write deliberately removes the attribute while retaining the lease. This\n * is useful for derived ARIA whose valid absence is itself controller state, such as\n * an unbounded `aria-valuemin` or a blank spinbutton's `aria-valuenow`.\n *\n * The lease has no lifecycle of its own, so it never subscribes to document events.\n * A consumer that must not let a derived value become the authored baseline of a\n * cached page returns its leases from its own `turbo:before-cache` rewind, where the\n * matching `disconnect()` also releases the subscription.\n */\nexport class AttributeLease<T extends Element = Element> {\n readonly #attribute: string;\n readonly #records = new Map<T, AttributeLeaseRecord>();\n\n /** @param attribute - The attribute whose temporary values this lease owns. */\n constructor(attribute: string) {\n this.#attribute = attribute;\n }\n\n /** Writes or removes the leased attribute while preserving its authored value. */\n write(element: T, value: string | null): void {\n const existing = this.#records.get(element);\n if (existing) {\n existing.written = value;\n } else {\n this.#records.set(element, {\n original: element.getAttribute(this.#attribute),\n written: value,\n });\n }\n\n this.#reflect(element, value);\n }\n\n /** Returns one lease without overwriting a value subsequently authored by a consumer. */\n return(element: T): void {\n const record = this.#records.get(element);\n if (!record) return;\n this.#records.delete(element);\n const stillOwned = element.getAttribute(this.#attribute) === record.written;\n if (stillOwned) this.#reflect(element, record.original);\n }\n\n /** Reflects only a real value transition, avoiding self-triggered mutation work. */\n #reflect(element: T, value: string | null): void {\n if (element.getAttribute(this.#attribute) === value) return;\n if (value === null) element.removeAttribute(this.#attribute);\n else element.setAttribute(this.#attribute, value);\n }\n\n /** Returns every outstanding lease using the same ownership check as {@link return}. */\n returnAll(): void {\n for (const element of Array.from(this.#records.keys())) this.return(element);\n }\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.\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","/** Minimal event shape carrying the platform's per-event composition signal. */\nexport interface CompositionSignal {\n readonly isComposing?: boolean;\n}\n\n/** Hooks that keep component-specific work outside {@link CompositionTracker}. */\nexport interface CompositionTrackerOptions {\n /** Runs after lifecycle state is set for a `compositionstart` event. */\n readonly onStart?: (event: Event) => void;\n /** Runs after lifecycle state is cleared for a `compositionend` event. */\n readonly onEnd?: (event: Event) => void;\n}\n\n/**\n * Owns IME composition listeners and transient state for one or more event targets.\n *\n * Some browsers omit `KeyboardEvent.isComposing` on the keydown that confirms a\n * conversion. Tracking `compositionstart` through `compositionend` supplies the\n * missing lifecycle signal without relying on deprecated numeric key codes.\n * Component policy stays with the consumer: filtering, validation, and submission\n * belong in the optional {@link CompositionTrackerOptions.onEnd} callback.\n *\n * @example\n * ```ts\n * #composition = new CompositionTracker({ onEnd: () => this.filter() });\n *\n * connect(): void {\n * this.#composition.observe(this.inputTarget);\n * }\n *\n * disconnect(): void {\n * this.#composition.disconnect();\n * }\n *\n * onKeydown(event: KeyboardEvent): void {\n * if (this.#composition.isComposing(event)) return;\n * }\n * ```\n */\nexport class CompositionTracker {\n readonly #observedTargets = new Set<EventTarget>();\n readonly #activeTargets = new Set<EventTarget>();\n readonly #onStart: ((event: Event) => void) | undefined;\n readonly #onEnd: ((event: Event) => void) | undefined;\n\n constructor(options: CompositionTrackerOptions = {}) {\n this.#onStart = options.onStart;\n this.#onEnd = options.onEnd;\n }\n\n /** Starts lifecycle tracking for `target`; repeated calls are idempotent. */\n observe(target: EventTarget): void {\n if (this.#observedTargets.has(target)) return;\n target.addEventListener(\"compositionstart\", this.#handleStart);\n target.addEventListener(\"compositionend\", this.#handleEnd);\n this.#observedTargets.add(target);\n }\n\n /** Stops tracking one target and clears any active composition it owned. */\n unobserve(target: EventTarget): void {\n if (!this.#observedTargets.delete(target)) return;\n target.removeEventListener(\"compositionstart\", this.#handleStart);\n target.removeEventListener(\"compositionend\", this.#handleEnd);\n this.#activeTargets.delete(target);\n }\n\n /** Releases every listener and clears state so reconnect starts cleanly. */\n disconnect(): void {\n for (const target of this.#observedTargets) {\n target.removeEventListener(\"compositionstart\", this.#handleStart);\n target.removeEventListener(\"compositionend\", this.#handleEnd);\n }\n this.#observedTargets.clear();\n this.#activeTargets.clear();\n }\n\n /** True when lifecycle tracking or the current event reports composition. */\n isComposing(event?: CompositionSignal): boolean {\n return this.#activeTargets.size > 0 || event?.isComposing === true;\n }\n\n readonly #handleStart = (event: Event): void => {\n if (event.currentTarget) this.#activeTargets.add(event.currentTarget);\n this.#onStart?.(event);\n };\n\n readonly #handleEnd = (event: Event): void => {\n if (event.currentTarget) this.#activeTargets.delete(event.currentTarget);\n this.#onEnd?.(event);\n };\n}\n","/**\n * Collapses many Stimulus lifecycle callbacks from one DOM mutation into a\n * single pass.\n *\n * Stimulus fires `<name>TargetConnected` / `Disconnected` once per element and\n * `<name>ValueChanged` once per changed attribute. Replacing a list of N options\n * or morphing several render Values therefore delivers N callbacks — but the\n * useful unit of work is \"reconcile against the resulting declarative input\",\n * once, after the batch has settled. Every controller with reconcilable targets\n * or render Values needs the same shape: a `queued` flag plus `queueMicrotask`.\n *\n * **A microtask is the right horizon, and the reason is specific.** Stimulus\n * drives these callbacks from a `MutationObserver`, whose own callback already\n * runs as a microtask with the whole batch in hand; scheduling one more lands\n * after the last sibling callback of that batch and still before paint or any\n * event handler. A timer would be later than it needs to be, and reconciling\n * synchronously would run once per element against a half-applied DOM.\n *\n * **The two guards are not the same guard.** Scheduling is refused before the\n * controller connects, and running is refused after it disconnects:\n *\n * - **Before `connect()`** — Stimulus delivers initial target and Value callbacks\n * ahead of `connect()`. Reconciling there would compute output against a\n * controller whose own state has not been initialised, and `connect()` is\n * about to do a full pass anyway.\n * - **After `disconnect()`** — Stimulus fires a callback for **every** target\n * during teardown, and a microtask queued just before it would otherwise run\n * against a detached tree. {@link MicrotaskCoalescer.cancel} exists for the\n * teardown path to drop the pending pass outright.\n *\n * Both guards are part of one contract here rather than something each consumer\n * has to remember separately.\n *\n * Scope is the scheduling only. *What* to reconcile — keep the surviving active\n * option, fall back to the next / previous / first visible one, rebuild derived\n * chips or hidden fields — stays in the controller, because no two consumers\n * answer it the same way.\n *\n * This file's own doc block is dropped from `dist`, but every member comment is\n * inlined into each consumer entry (`tsup` builds with `splitting: false`), so\n * rationale belongs here and only the contract belongs on the members.\n *\n * @example\n * ```ts\n * readonly #reconcile = new MicrotaskCoalescer(() => this.#reconcileOptions());\n *\n * connect() { this.#reconcile.activate(); }\n * disconnect() { this.#reconcile.cancel(); }\n *\n * optionTargetConnected() { this.#reconcile.schedule(); }\n * optionTargetDisconnected() { this.#reconcile.schedule(); }\n * ```\n */\nexport class MicrotaskCoalescer {\n readonly #run: () => void;\n #queued = false;\n #active = false;\n #generation = 0;\n\n /** @param run - the single reconciliation pass, invoked at most once per batch. */\n constructor(run: () => void) {\n this.#run = run;\n }\n\n /** Opens the window in which {@link schedule} is honoured; call from `connect()`. */\n activate(): void {\n this.#active = true;\n }\n\n /** Closes the window and drops any pending pass; call from `disconnect()`. */\n cancel(): void {\n this.#active = false;\n this.#queued = false;\n this.#generation += 1;\n }\n\n /** Requests one pass after the batch settles. Idempotent; inert outside the window. */\n schedule(): void {\n if (!this.#active || this.#queued) return;\n this.#queued = true;\n const generation = this.#generation;\n queueMicrotask(() => {\n // A cancelled callback must not consume a pass queued after reconnect.\n if (generation !== this.#generation || !this.#queued || !this.#active) return;\n this.#queued = false;\n this.#run();\n });\n }\n}\n","/**\n * 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 { announce, fillTemplate } from \"../utils/announce\";\nimport { AttributeLease } from \"../utils/attribute_lease\";\nimport { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { CompositionTracker } from \"../utils/composition_tracker\";\nimport { MicrotaskCoalescer } from \"../utils/microtask_coalescer\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\ntype CharacterCounterField = HTMLInputElement | HTMLTextAreaElement;\ntype DisplayMode = \"remaining\" | \"used\" | \"both\";\n\ninterface CharacterCountReading {\n readonly length: number;\n readonly remaining: number | null;\n readonly over: boolean;\n readonly max: number;\n readonly text: string;\n}\n\ntype CharacterCounterDetail = Pick<CharacterCountReading, \"length\" | \"remaining\" | \"over\">;\n\n/**\n * Headless character-counter behavior for a text field (no dedicated APG\n * pattern; follows the WCAG 2.2 \"status messages\" practice, 4.1.3).\n *\n * Markup contract (identifier: `stimeo--character-counter`):\n * <div data-controller=\"stimeo--character-counter\"\n * data-stimeo--character-counter-max-value=\"140\"\n * data-stimeo--character-counter-announce-text-value=\"{remaining} characters remaining\">\n * <textarea data-stimeo--character-counter-target=\"input\"\n * aria-describedby=\"cc\"></textarea>\n * <span id=\"cc\" data-stimeo--character-counter-target=\"output\"></span>\n * </div>\n *\n * Watches the field's UTF-16 code-unit length, writes the remaining/used count\n * into `output`, and toggles the `data-near-limit` / `data-over-limit` state\n * hooks. While over the limit it temporarily leases `aria-invalid=\"true\"` on\n * the field and returns the consumer's authored value on recovery or teardown.\n * The field is the first `input` target, or — when the controller is attached\n * straight onto an `<input>`/`<textarea>` — the controller element itself.\n *\n * `change` and `reconcile` dispatch\n * `{ length: number, remaining: number | null, over: boolean }`.\n *\n * @remarks\n * Behavior only — count text and state update synchronously, with no styling.\n * Confirmed user input dispatches `stimeo--character-counter:change` only when\n * the measured length actually changes. Its detail is `{ length, remaining,\n * over }`; `remaining` is `null` when `max` is disabled. IME intermediate input\n * is ignored, and `compositionend` commits the confirmed value exactly once.\n *\n * Assistive notification is opt-in and i18n-neutral. `announceText` accepts\n * `{count}`, `{length}`, `{remaining}`, `{max}`, and `{over}` placeholders and\n * sends the settled message to the page's shared `stimeo--announcer` after a\n * short debounce. The visible `output` is not itself required to be a live\n * region. Initial reflection and Turbo restoration never dispatch or announce.\n * Runtime target/Value reconciliation dispatches\n * `stimeo--character-counter:reconcile` only when the public derived state\n * changes, and never announces.\n */\nexport class CharacterCounterController extends Controller<HTMLElement> {\n static override targets = [\"input\", \"output\"];\n static override values = {\n max: { type: Number, default: 0 },\n warnAt: { type: Number, default: 0 },\n mode: { type: String, default: \"remaining\" },\n announceText: { type: String, default: \"\" },\n };\n static events = [\"change\", \"reconcile\"] as const;\n\n declare readonly inputTarget: CharacterCounterField;\n declare readonly outputTarget: HTMLElement;\n declare readonly hasInputTarget: boolean;\n declare readonly hasOutputTarget: boolean;\n\n declare maxValue: number;\n declare warnAtValue: number;\n declare modeValue: string;\n declare announceTextValue: string;\n\n /** Delay (ms) before one settled count is sent to the shared announcer. */\n static readonly #announceDelay = 200;\n\n readonly #timeouts = new SafeTimeout();\n readonly #ariaInvalid = new AttributeLease<CharacterCounterField>(\"aria-invalid\");\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());\n readonly #repaint = new MicrotaskCoalescer(() => this.#reconcile(true));\n readonly #composition = new CompositionTracker({\n onEnd: (event) => this.#commitFrom(event.currentTarget),\n });\n #announceId: number | null = null;\n #boundField: CharacterCounterField | null = null;\n #lastLength: number | null = null;\n #lastDetail: CharacterCounterDetail | null = null;\n #reflectedOver: boolean | null = null;\n\n readonly #onInput = (event: Event): void => {\n const field = this.#boundField;\n if (!field || event.currentTarget !== field || this.#field !== field) return;\n if (this.#composition.isComposing(event as InputEvent)) return;\n this.#commit(field);\n };\n\n /** Reflects the current DOM state and opens the mutation-reconciliation window. */\n override connect(): void {\n this.#repaint.activate();\n this.#beforeCache.activate();\n this.#reconcile(false);\n }\n\n /** Releases listeners, timers, borrowed ARIA, and controller-owned state hooks. */\n override disconnect(): void {\n this.#repaint.cancel();\n this.#beforeCache.deactivate();\n this.#cancelAnnouncement();\n this.#bindField(null);\n this.#composition.disconnect();\n this.#clearStateHooks();\n this.#lastLength = null;\n this.#lastDetail = null;\n }\n\n /** Rebinds and repaints after an input target is added or replaced at runtime. */\n inputTargetConnected(): void {\n this.#repaint.schedule();\n }\n\n /** Releases and repaints after an input target is removed or replaced at runtime. */\n inputTargetDisconnected(): void {\n this.#repaint.schedule();\n }\n\n /** Initializes a display target inserted after the controller connected. */\n outputTargetConnected(): void {\n this.#repaint.schedule();\n }\n\n /** Reconciles the optional display target set after a removal or replacement. */\n outputTargetDisconnected(): void {\n this.#repaint.schedule();\n }\n\n /** Repaints when application code or a Turbo morph changes `max`. */\n maxValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /** Repaints when application code or a Turbo morph changes `warnAt`. */\n warnAtValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /** Repaints when application code or a Turbo morph changes `mode`. */\n modeValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /** Cancels a pending old message when its consumer-authored template changes. */\n announceTextValueChanged(): void {\n this.#repaint.schedule();\n }\n\n /** Rebinds one mutation batch and reports a changed controller-derived state. */\n #reconcile(report: boolean): void {\n const previous = this.#lastDetail;\n // An edit inside the debounce window has already earned an announcement.\n // Reconciliation never originates one, but it must not swallow that one\n // either: the pending message is retargeted at the settled reading, so the\n // user hears the count that ends up displayed rather than nothing. A\n // replaced field is the exception — its pending message describes a field\n // the reader can no longer reach.\n const owedField = this.#announceId === null ? null : this.#boundField;\n this.#cancelAnnouncement();\n this.#bindField(this.#field);\n if (this.#composition.isComposing()) return;\n const field = this.#boundField;\n if (!field) {\n this.#renderEmpty();\n this.#lastLength = null;\n this.#lastDetail = null;\n return;\n }\n const reading = this.#render(field);\n const detail = this.#detail(reading);\n this.#lastLength = reading.length;\n this.#lastDetail = detail;\n if (owedField === field) this.#scheduleAnnouncement(reading);\n if (report && previous && this.#detailsDiffer(previous, detail)) {\n this.dispatch(\"reconcile\", { detail });\n }\n }\n\n /** Commits a composition only when it came from the field still owned here. */\n #commitFrom(target: EventTarget | null): void {\n const field = this.#boundField;\n if (!field || target !== field || this.#field !== field) return;\n this.#commit(field);\n }\n\n /** Reflects one confirmed user input and reports only a real length transition. */\n #commit(field: CharacterCounterField): void {\n const reading = this.#render(field);\n const previousLength = this.#lastLength;\n const previousDetail = this.#lastDetail;\n const detail = this.#detail(reading);\n this.#lastLength = reading.length;\n this.#lastDetail = detail;\n if (previousLength === reading.length) {\n if (previousDetail && this.#detailsDiffer(previousDetail, detail)) {\n this.dispatch(\"reconcile\", { detail });\n }\n return;\n }\n\n this.dispatch(\"change\", { detail });\n this.#scheduleAnnouncement(reading);\n }\n\n /** Selects the public event state from the richer internal reading. */\n #detail(reading: CharacterCountReading): CharacterCounterDetail {\n return {\n length: reading.length,\n remaining: reading.remaining,\n over: reading.over,\n };\n }\n\n /** Compares exactly the state carried by `change` and `reconcile`. */\n #detailsDiffer(left: CharacterCounterDetail, right: CharacterCounterDetail): boolean {\n return (\n left.length !== right.length || left.remaining !== right.remaining || left.over !== right.over\n );\n }\n\n /**\n * Synchronizes visible count, state hooks, and temporary validation ARIA.\n *\n * @stimeoRenderRoot\n */\n #render(field: CharacterCounterField): CharacterCountReading {\n const length = field.value.length;\n const max = this.#normalizeCount(this.maxValue);\n const warnAt = this.#normalizeCount(this.warnAtValue);\n const remaining = max > 0 ? max - length : null;\n const over = remaining !== null && remaining < 0;\n const near = remaining !== null && warnAt > 0 && !over && remaining <= warnAt;\n\n this.#toggle(\"data-over-limit\", over);\n this.#toggle(\"data-near-limit\", near);\n this.#reflectInvalid(field, over);\n\n const text = this.#format(length, remaining, max);\n this.#writeOutput(text);\n return { length, remaining, over, max, text };\n }\n\n /** Clears derived output when the declarative input set has no usable field. */\n #renderEmpty(): void {\n this.#ariaInvalid.returnAll();\n this.#reflectedOver = null;\n this.#clearStateHooks();\n this.#writeOutput(\"\");\n }\n\n /** Replaces the observed field symmetrically, returning state from the old one. */\n #bindField(field: CharacterCounterField | null): void {\n if (field === this.#boundField) return;\n\n const previous = this.#boundField;\n if (previous) {\n previous.removeEventListener(\"input\", this.#onInput);\n this.#composition.unobserve(previous);\n this.#ariaInvalid.return(previous);\n }\n\n this.#boundField = field;\n this.#lastLength = null;\n this.#reflectedOver = null;\n if (!field) return;\n\n field.addEventListener(\"input\", this.#onInput);\n this.#composition.observe(field);\n }\n\n /** Leases `aria-invalid` only on the edge into over-limit, then returns it. */\n #reflectInvalid(field: CharacterCounterField, over: boolean): void {\n if (this.#reflectedOver === over) return;\n this.#reflectedOver = over;\n if (over) this.#ariaInvalid.write(field, \"true\");\n else this.#ariaInvalid.return(field);\n }\n\n /** Builds the visible count for the normalized display mode. */\n #format(length: number, remaining: number | null, max: number): string {\n if (remaining === null) return String(length);\n switch (this.#mode) {\n case \"used\":\n return String(length);\n case \"both\":\n return `${length}/${max}`;\n default:\n return String(remaining);\n }\n }\n\n /** Debounces one i18n-neutral message into the shared polite announcer. */\n #scheduleAnnouncement(reading: CharacterCountReading): void {\n this.#cancelAnnouncement();\n const message = fillTemplate(this.announceTextValue, {\n count: reading.text,\n length: reading.length,\n remaining: reading.remaining ?? \"\",\n max: reading.max,\n over: String(reading.over),\n });\n if (message.trim().length === 0) return;\n\n this.#announceId = this.#timeouts.set(() => {\n announce(message);\n this.#announceId = null;\n }, CharacterCounterController.#announceDelay);\n }\n\n /** Cancels the one outstanding announcement without touching visible output. */\n #cancelAnnouncement(): void {\n if (this.#announceId !== null) this.#timeouts.clear(this.#announceId);\n this.#announceId = null;\n }\n\n /** Writes the optional display only when its text actually changed. */\n #writeOutput(text: string): void {\n if (!this.hasOutputTarget || this.outputTarget.textContent === text) return;\n this.outputTarget.textContent = text;\n }\n\n /** Reflects a presence-style state hook without redundant attribute writes. */\n #toggle(name: string, on: boolean): void {\n if (on) {\n if (this.element.getAttribute(name) !== \"true\") this.element.setAttribute(name, \"true\");\n } else if (this.element.hasAttribute(name)) {\n this.element.removeAttribute(name);\n }\n }\n\n /** Removes both state hooks owned by this controller. */\n #clearStateHooks(): void {\n this.#toggle(\"data-over-limit\", false);\n this.#toggle(\"data-near-limit\", false);\n }\n\n /** Returns borrowed ARIA and transient hooks before Turbo snapshots the page. */\n #rewindForCache(): void {\n this.#cancelAnnouncement();\n this.#ariaInvalid.returnAll();\n this.#reflectedOver = null;\n this.#clearStateHooks();\n }\n\n /** Converts a public count Value into a finite non-negative integer. */\n #normalizeCount(raw: number): number {\n if (!Number.isFinite(raw)) return 0;\n return Math.max(0, Math.trunc(raw));\n }\n\n /** Falls back to `remaining` when an authored display mode is unknown. */\n get #mode(): DisplayMode {\n if (this.modeValue === \"used\" || this.modeValue === \"both\") return this.modeValue;\n return \"remaining\";\n }\n\n /** The watched field: the first target, or a directly controlled form field. */\n get #field(): CharacterCounterField | null {\n if (this.hasInputTarget) return this.inputTarget;\n const element: HTMLElement = this.element;\n if (element instanceof HTMLInputElement || element instanceof HTMLTextAreaElement)\n return element;\n return null;\n }\n}\n"]}
@@ -1,30 +1,52 @@
1
1
  import { Controller } from '@hotwired/stimulus';
2
2
 
3
3
  /**
4
- * Headless copy-to-clipboard behavior with a live-region completion notice.
4
+ * Headless copy-to-clipboard behavior with a completion slot and a screen-reader
5
+ * announcement.
5
6
  *
6
7
  * Markup contract (identifier: `stimeo--clipboard`):
7
8
  * <div data-controller="stimeo--clipboard"
8
- * data-stimeo--clipboard-feedback-duration-value="2000">
9
+ * data-stimeo--clipboard-feedback-duration-value="2000"
10
+ * data-stimeo--clipboard-announce-copied-text-value="Copied to clipboard"
11
+ * data-stimeo--clipboard-announce-error-text-value="Copy failed">
9
12
  * <input type="text" value="https://example.com" readonly
10
13
  * data-stimeo--clipboard-target="source">
11
14
  * <button type="button" data-stimeo--clipboard-target="button"
12
15
  * data-action="stimeo--clipboard#copy">Copy</button>
13
- * <span role="status" aria-live="polite"
14
- * data-stimeo--clipboard-target="feedback"></span>
16
+ * <span data-stimeo--clipboard-target="feedback"></span>
15
17
  * </div>
16
18
  *
17
- * No dedicated APG pattern; this follows the Button + live-region practice. The
18
- * copy uses the standard `navigator.clipboard` API (no extra dependency); when
19
- * it is unavailable or rejects, the failure is surfaced rather than silently
20
- * swallowed, and never communicated by icon alone — the `role="status"` region
21
- * carries text so screen readers announce the outcome.
19
+ * No dedicated APG pattern; this follows the Button practice plus a status message
20
+ * ({@link https://www.w3.org/WAI/WCAG22/Understanding/status-changes.html | WCAG 2.2 SC 4.1.3}).
21
+ * The copy uses the standard `navigator.clipboard` API (no extra dependency); every
22
+ * failure mode — an API the browser withholds outside a secure context as much as a
23
+ * rejected permission — settles the same way, as `data-state="error"` plus the
24
+ * `copy` event's `success: false`.
25
+ *
26
+ * Targets: `source` (the text to copy, when `text` is not set), `button` (the
27
+ * control that triggers `copy`), `feedback` (the **visible** completion slot).
28
+ *
29
+ * Values: `text` (copy this instead of reading `source`), `feedbackDuration` (ms the
30
+ * completion state is held; `0` or less arms no timer, so it stands until the next
31
+ * copy — a reconnect and the before-cache rewind still clear it), `copiedLabel` /
32
+ * `errorLabel` (what the visible slot shows), `announceCopiedText` /
33
+ * `announceErrorText` (what assistive tech hears; empty announces nothing).
22
34
  *
23
35
  * @remarks
24
- * Behavior only — icon swaps and styling are the consumer's, keyed off
25
- * `data-state` (`idle` / `copied` / `error`). The completion notice clears
26
- * itself after `feedbackDuration`; that timer is torn down on disconnect (Turbo)
27
- * via {@link SafeTimeout}.
36
+ * Behavior only — icon swaps and styling are the consumer's, keyed off `data-state`
37
+ * (`idle` / `copied` / `error`).
38
+ *
39
+ * **The `feedback` slot must not carry live-region semantics.** Announcing is the
40
+ * page's shared `stimeo--announcer` job: it is seated before the change it reads,
41
+ * which a slot filled on demand cannot be, and it already collapses a repeat of the
42
+ * same wording so a second copy is still heard. A `role="status"` on the slot as
43
+ * well would say everything twice.
44
+ *
45
+ * `copied` and `error` are transient: the timer that clears them belongs to one
46
+ * connection, so a fresh `connect()` that finds either — a restored snapshot, an
47
+ * in-page move — returns to `idle`, and the state is rewound before Turbo caches
48
+ * the page ({@link BeforeCacheReset}). The rewind is silent: it discards nothing a
49
+ * reconnect does not derive again.
28
50
  */
29
51
  declare class ClipboardController extends Controller<HTMLElement> {
30
52
  #private;
@@ -46,6 +68,14 @@ declare class ClipboardController extends Controller<HTMLElement> {
46
68
  type: StringConstructor;
47
69
  default: string;
48
70
  };
71
+ announceCopiedText: {
72
+ type: StringConstructor;
73
+ default: string;
74
+ };
75
+ announceErrorText: {
76
+ type: StringConstructor;
77
+ default: string;
78
+ };
49
79
  };
50
80
  static actions: readonly ["copy"];
51
81
  static events: readonly ["copy"];
@@ -59,12 +89,15 @@ declare class ClipboardController extends Controller<HTMLElement> {
59
89
  feedbackDurationValue: number;
60
90
  copiedLabelValue: string;
61
91
  errorLabelValue: string;
92
+ announceCopiedTextValue: string;
93
+ announceErrorTextValue: string;
62
94
  connect(): void;
63
95
  disconnect(): void;
64
96
  /**
65
97
  * Copies the resolved text and reports the outcome. Bound via `data-action`
66
- * (click). Always dispatches `stimeo--clipboard:copy` with `{ success, text }`
67
- * — including on failure — so consumers can react either way.
98
+ * (click). Dispatches `stimeo--clipboard:copy` with `{ success, text }` once per
99
+ * completed attempt — including on failure — so consumers can react either way.
100
+ * An attempt whose connection ended while it was in flight reports nothing.
68
101
  */
69
102
  copy(): Promise<void>;
70
103
  }
@@ -2,6 +2,46 @@ import { Controller } from '@hotwired/stimulus';
2
2
 
3
3
  // src/controllers/clipboard_controller.ts
4
4
 
5
+ // src/utils/announce.ts
6
+ function announce(message, options = {}) {
7
+ const text = message.trim();
8
+ if (text.length === 0) return;
9
+ window.dispatchEvent(
10
+ new CustomEvent("stimeo--announcer:announce", {
11
+ detail: { message: text, assertive: options.assertive === true }
12
+ })
13
+ );
14
+ }
15
+
16
+ // src/utils/before_cache_reset.ts
17
+ var BeforeCacheReset = class _BeforeCacheReset {
18
+ /** Every subscribed instance, iterated by the one shared document listener. */
19
+ static #subscribers = /* @__PURE__ */ new Set();
20
+ /** The shared listener; installed while at least one instance is subscribed. */
21
+ static #onBeforeCache = () => {
22
+ for (const subscriber of _BeforeCacheReset.#subscribers) subscriber.#rewind();
23
+ };
24
+ #rewind;
25
+ /** @param rewind - the pass that returns this controller's state to its initial form. */
26
+ constructor(rewind) {
27
+ this.#rewind = rewind;
28
+ }
29
+ /** Subscribes to `turbo:before-cache`; call from `connect()`. Idempotent. */
30
+ activate() {
31
+ const first = _BeforeCacheReset.#subscribers.size === 0;
32
+ _BeforeCacheReset.#subscribers.add(this);
33
+ if (first) {
34
+ document.addEventListener("turbo:before-cache", _BeforeCacheReset.#onBeforeCache);
35
+ }
36
+ }
37
+ /** Unsubscribes; call from `disconnect()`. Safe when never subscribed. */
38
+ deactivate() {
39
+ _BeforeCacheReset.#subscribers.delete(this);
40
+ if (_BeforeCacheReset.#subscribers.size > 0) return;
41
+ document.removeEventListener("turbo:before-cache", _BeforeCacheReset.#onBeforeCache);
42
+ }
43
+ };
44
+
5
45
  // src/utils/default_attribute.ts
6
46
  function setDefaultAttribute(element, name, value) {
7
47
  if (element.hasAttribute(name)) return false;
@@ -63,45 +103,59 @@ var SafeTimeout = class extends TimerRegistry {
63
103
  };
64
104
 
65
105
  // src/controllers/clipboard_controller.ts
106
+ var TRANSIENT_STATES = /* @__PURE__ */ new Set(["copied", "error"]);
66
107
  var ClipboardController = class extends Controller {
67
108
  static targets = ["source", "button", "feedback"];
68
109
  static values = {
69
110
  text: { type: String, default: "" },
70
111
  feedbackDuration: { type: Number, default: 2e3 },
71
112
  copiedLabel: { type: String, default: "Copied" },
72
- errorLabel: { type: String, default: "Copy failed" }
113
+ errorLabel: { type: String, default: "Copy failed" },
114
+ announceCopiedText: { type: String, default: "" },
115
+ announceErrorText: { type: String, default: "" }
73
116
  };
74
117
  static actions = ["copy"];
75
118
  static events = ["copy"];
76
- /** Auto-clear timer for the completion notice; torn down on disconnect. */
119
+ /**
120
+ * The pending return to idle — the only timer this controller schedules, so
121
+ * `clearAll()` is exactly "drop the auto-clear" and needs no id of its own.
122
+ */
77
123
  #timers = new SafeTimeout();
124
+ /** Returns the completion state to idle for the snapshot Turbo takes. */
125
+ #beforeCache = new BeforeCacheReset(() => this.#rewind());
78
126
  /**
79
- * The pending auto-clear timer id, or `null` when none is scheduled. Tracked so
80
- * a rapid second copy cancels the first window instead of letting a stale timer
81
- * reset the freshly-shown notice early.
127
+ * Whether this connection is still live. `copy()` suspends on the Clipboard API,
128
+ * and a teardown that lands while it is suspended must win: the continuation
129
+ * would otherwise write to an element nobody owns and arm a timer past the
130
+ * `clearAll()` that was supposed to be the last word.
82
131
  */
83
- #resetTimerId = null;
132
+ #connected = false;
84
133
  connect() {
85
- setDefaultAttribute(this.element, "data-state", "idle");
134
+ this.#connected = true;
135
+ this.#adopt();
136
+ this.#beforeCache.activate();
86
137
  }
87
138
  disconnect() {
139
+ this.#connected = false;
140
+ this.#beforeCache.deactivate();
88
141
  this.#timers.clearAll();
89
142
  }
90
143
  /**
91
144
  * Copies the resolved text and reports the outcome. Bound via `data-action`
92
- * (click). Always dispatches `stimeo--clipboard:copy` with `{ success, text }`
93
- * — including on failure — so consumers can react either way.
145
+ * (click). Dispatches `stimeo--clipboard:copy` with `{ success, text }` once per
146
+ * completed attempt — including on failure — so consumers can react either way.
147
+ * An attempt whose connection ended while it was in flight reports nothing.
94
148
  */
95
149
  async copy() {
96
150
  const text = this.#resolveText();
97
151
  let success = false;
98
152
  try {
99
- if (!navigator.clipboard?.writeText) throw new Error("Clipboard API unavailable");
100
153
  await navigator.clipboard.writeText(text);
101
154
  success = true;
102
155
  } catch {
103
156
  success = false;
104
157
  }
158
+ if (!this.#connected) return;
105
159
  this.#reportResult(success);
106
160
  this.dispatch("copy", { detail: { success, text } });
107
161
  }
@@ -118,24 +172,52 @@ var ClipboardController = class extends Controller {
118
172
  }
119
173
  return source.textContent ?? "";
120
174
  }
121
- /** Reflects the result on `data-state`, announces it, and schedules a reset. */
175
+ /**
176
+ * Reads the current state back from the DOM.
177
+ *
178
+ * A `copied` or `error` found at connect time is this controller's own output
179
+ * from a connection that is gone, and so is the timer that would have cleared it
180
+ * — nothing else would ever return the element to `idle`. Any other authored
181
+ * value belongs to the consumer and only a missing attribute takes the default.
182
+ */
183
+ #adopt() {
184
+ if (this.#inTransientState()) {
185
+ this.#reset();
186
+ return;
187
+ }
188
+ setDefaultAttribute(this.element, "data-state", "idle");
189
+ }
190
+ /** Whether `data-state` currently holds one of the values this controller writes. */
191
+ #inTransientState() {
192
+ const state = this.element.getAttribute("data-state");
193
+ return state !== null && TRANSIENT_STATES.has(state);
194
+ }
195
+ /**
196
+ * Returns the completion state to idle for the snapshot Turbo is about to take,
197
+ * so a page reached with the Back button does not report a copy that happened
198
+ * before the navigation. Only a state this controller wrote is rewound — an
199
+ * authored one is the consumer's and has to survive into the snapshot, exactly as
200
+ * `connect()` leaves it alone. State only — no `copy` is dispatched, which would
201
+ * claim a fresh copy ran.
202
+ */
203
+ #rewind() {
204
+ if (!this.#inTransientState()) return;
205
+ this.#timers.clearAll();
206
+ this.#reset();
207
+ }
208
+ /** Reflects the result, announces it, and schedules the return to idle. */
122
209
  #reportResult(success) {
123
210
  this.element.setAttribute("data-state", success ? "copied" : "error");
124
211
  if (this.hasFeedbackTarget) {
125
212
  this.feedbackTarget.textContent = success ? this.copiedLabelValue : this.errorLabelValue;
126
213
  }
127
- if (this.#resetTimerId !== null) {
128
- this.#timers.clear(this.#resetTimerId);
129
- this.#resetTimerId = null;
130
- }
214
+ announce(success ? this.announceCopiedTextValue : this.announceErrorTextValue);
215
+ this.#timers.clearAll();
131
216
  if (this.feedbackDurationValue > 0) {
132
- this.#resetTimerId = this.#timers.set(() => {
133
- this.#resetTimerId = null;
134
- this.#reset();
135
- }, this.feedbackDurationValue);
217
+ this.#timers.set(() => this.#reset(), this.feedbackDurationValue);
136
218
  }
137
219
  }
138
- /** Returns to the idle state and clears the completion notice. */
220
+ /** Returns to the idle state and empties the completion slot. */
139
221
  #reset() {
140
222
  this.element.setAttribute("data-state", "idle");
141
223
  if (this.hasFeedbackTarget) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/default_attribute.ts","../../src/utils/safe_timeout.ts","../../src/controllers/clipboard_controller.ts"],"names":[],"mappings":";;;;;AAYO,SAAS,mBAAA,CAAoB,OAAA,EAAkB,IAAA,EAAc,KAAA,EAAwB;AAC1F,EAAA,IAAI,OAAA,CAAQ,YAAA,CAAa,IAAI,CAAA,EAAG,OAAO,KAAA;AACvC,EAAA,OAAA,CAAQ,YAAA,CAAa,MAAM,KAAK,CAAA;AAChC,EAAA,OAAO,IAAA;AACT;;;ACQA,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;A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AAA,IAAI,IAAA,CAAK,kBAAkB,IAAA,EAAM;AAC/B,MAAA,IAAA,CAAK,OAAA,CAAQ,KAAA,CAAM,IAAA,CAAK,aAAa,CAAA;AACrC,MAAA,IAAA,CAAK,aAAA,GAAgB,IAAA;AAAA,IACvB;AACA,IAAA,IAAI,IAAA,CAAK,wBAAwB,CAAA,EAAG;AAClC,MAAA,IAAA,CAAK,aAAA,GAAgB,IAAA,CAAK,OAAA,CAAQ,GAAA,CAAI,MAAM;AAC1C,QAAA,IAAA,CAAK,aAAA,GAAgB,IAAA;AACrB,QAAA,IAAA,CAAK,MAAA,EAAO;AAAA,MACd,CAAA,EAAG,KAAK,qBAAqB,CAAA;AAAA,IAC/B;AAAA,EACF;AAAA;AAAA,EAGA,MAAA,GAAe;AACb,IAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,YAAA,EAAc,MAAM,CAAA;AAC9C,IAAA,IAAI,KAAK,iBAAA,EAAmB;AAC1B,MAAA,IAAA,CAAK,eAAe,WAAA,GAAc,EAAA;AAAA,IACpC;AAAA,EACF;AACF","file":"clipboard_controller.js","sourcesContent":["/**\n * Adds an attribute default without displacing an authored value.\n *\n * Attribute presence — including an authored empty string — is the ownership\n * boundary. The return value lets a caller remember that it supplied the\n * default when that caller must later restore the authored state.\n *\n * @param element - Element that owns the attribute\n * @param name - Attribute name\n * @param value - Value to write only when the attribute is absent\n * @returns Whether this call added the attribute\n */\nexport function setDefaultAttribute(element: Element, name: string, value: string): boolean {\n if (element.hasAttribute(name)) return false;\n element.setAttribute(name, value);\n return true;\n}\n","/**\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 { setDefaultAttribute } from \"../utils/default_attribute\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/**\n * Headless copy-to-clipboard behavior with a live-region completion notice.\n *\n * Markup contract (identifier: `stimeo--clipboard`):\n * <div data-controller=\"stimeo--clipboard\"\n * data-stimeo--clipboard-feedback-duration-value=\"2000\">\n * <input type=\"text\" value=\"https://example.com\" readonly\n * data-stimeo--clipboard-target=\"source\">\n * <button type=\"button\" data-stimeo--clipboard-target=\"button\"\n * data-action=\"stimeo--clipboard#copy\">Copy</button>\n * <span role=\"status\" aria-live=\"polite\"\n * data-stimeo--clipboard-target=\"feedback\"></span>\n * </div>\n *\n * No dedicated APG pattern; this follows the Button + live-region practice. The\n * copy uses the standard `navigator.clipboard` API (no extra dependency); when\n * it is unavailable or rejects, the failure is surfaced rather than silently\n * swallowed, and never communicated by icon alone — the `role=\"status\"` region\n * carries text so screen readers announce the outcome.\n *\n * @remarks\n * Behavior only — icon swaps and styling are the consumer's, keyed off\n * `data-state` (`idle` / `copied` / `error`). The completion notice clears\n * itself after `feedbackDuration`; that timer is torn down on disconnect (Turbo)\n * via {@link SafeTimeout}.\n */\nexport class ClipboardController extends Controller<HTMLElement> {\n static override targets = [\"source\", \"button\", \"feedback\"];\n static override values = {\n text: { type: String, default: \"\" },\n feedbackDuration: { type: Number, default: 2000 },\n copiedLabel: { type: String, default: \"Copied\" },\n errorLabel: { type: String, default: \"Copy failed\" },\n };\n static actions = [\"copy\"] as const;\n static events = [\"copy\"] as const;\n\n declare readonly sourceTarget: HTMLElement;\n declare readonly buttonTarget: HTMLElement;\n declare readonly feedbackTarget: HTMLElement;\n declare readonly hasSourceTarget: boolean;\n declare readonly hasButtonTarget: boolean;\n declare readonly hasFeedbackTarget: boolean;\n\n declare textValue: string;\n declare feedbackDurationValue: number;\n declare copiedLabelValue: string;\n declare errorLabelValue: string;\n\n /** Auto-clear timer for the completion notice; torn down on disconnect. */\n #timers = new SafeTimeout();\n\n /**\n * The pending auto-clear timer id, or `null` when none is scheduled. Tracked so\n * a rapid second copy cancels the first window instead of letting a stale timer\n * reset the freshly-shown notice early.\n */\n #resetTimerId: number | null = null;\n\n override connect(): void {\n setDefaultAttribute(this.element, \"data-state\", \"idle\");\n }\n\n override disconnect(): void {\n this.#timers.clearAll();\n }\n\n /**\n * Copies the resolved text and reports the outcome. Bound via `data-action`\n * (click). Always dispatches `stimeo--clipboard:copy` with `{ success, text }`\n * — including on failure — so consumers can react either way.\n */\n async copy(): Promise<void> {\n const text = this.#resolveText();\n let success = false;\n try {\n if (!navigator.clipboard?.writeText) throw new Error(\"Clipboard API unavailable\");\n await navigator.clipboard.writeText(text);\n success = true;\n } catch {\n success = false;\n }\n\n this.#reportResult(success);\n this.dispatch(\"copy\", { detail: { success, text } });\n }\n\n /**\n * The text to copy: the explicit `text` value when set, otherwise the source\n * target's current value (inputs/textareas) or text content.\n */\n #resolveText(): string {\n if (this.textValue.length > 0) return this.textValue;\n if (!this.hasSourceTarget) return \"\";\n const source = this.sourceTarget;\n if (source instanceof HTMLInputElement || source instanceof HTMLTextAreaElement) {\n return source.value;\n }\n return source.textContent ?? \"\";\n }\n\n /** Reflects the result on `data-state`, announces it, and schedules a reset. */\n #reportResult(success: boolean): void {\n this.element.setAttribute(\"data-state\", success ? \"copied\" : \"error\");\n if (this.hasFeedbackTarget) {\n this.feedbackTarget.textContent = success ? this.copiedLabelValue : this.errorLabelValue;\n }\n\n // Cancel any in-flight reset so consecutive copies restart the full window\n // rather than having the earlier timer clear the new notice prematurely.\n if (this.#resetTimerId !== null) {\n this.#timers.clear(this.#resetTimerId);\n this.#resetTimerId = null;\n }\n if (this.feedbackDurationValue > 0) {\n this.#resetTimerId = this.#timers.set(() => {\n this.#resetTimerId = null;\n this.#reset();\n }, this.feedbackDurationValue);\n }\n }\n\n /** Returns to the idle state and clears the completion notice. */\n #reset(): void {\n this.element.setAttribute(\"data-state\", \"idle\");\n if (this.hasFeedbackTarget) {\n this.feedbackTarget.textContent = \"\";\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/announce.ts","../../src/utils/before_cache_reset.ts","../../src/utils/default_attribute.ts","../../src/utils/safe_timeout.ts","../../src/controllers/clipboard_controller.ts"],"names":[],"mappings":";;;;;AAoBO,SAAS,QAAA,CAAS,OAAA,EAAiB,OAAA,GAAmC,EAAC,EAAS;AACrF,EAAA,MAAM,IAAA,GAAO,QAAQ,IAAA,EAAK;AAC1B,EAAA,IAAI,IAAA,CAAK,WAAW,CAAA,EAAG;AACvB,EAAA,MAAA,CAAO,aAAA;AAAA,IACL,IAAI,YAAY,4BAAA,EAA8B;AAAA,MAC5C,QAAQ,EAAE,OAAA,EAAS,MAAM,SAAA,EAAW,OAAA,CAAQ,cAAc,IAAA;AAAK,KAChE;AAAA,GACH;AACF;;;ACeO,IAAM,gBAAA,GAAN,MAAM,iBAAA,CAAiB;AAAA;AAAA,EAE5B,OAAgB,YAAA,mBAAe,IAAI,GAAA,EAAsB;AAAA;AAAA,EAGzD,OAAgB,iBAAiB,MAAY;AAC3C,IAAA,KAAA,MAAW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AAA;AAAA;AAAA;AAAA,EAUA,OAAA,GAAgB;AACd,IAAA,IAAI,CAAC,IAAA,CAAK,iBAAA,EAAkB,EAAG;AAC/B,IAAA,IAAA,CAAK,QAAQ,QAAA,EAAS;AACtB,IAAA,IAAA,CAAK,MAAA,EAAO;AAAA,EACd;AAAA;AAAA,EAGA,cAAc,OAAA,EAAwB;AACpC,IAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,YAAA,EAAc,OAAA,GAAU,WAAW,OAAO,CAAA;AACpE,IAAA,IAAI,KAAK,iBAAA,EAAmB;AAC1B,MAAA,IAAA,CAAK,cAAA,CAAe,WAAA,GAAc,OAAA,GAAU,IAAA,CAAK,mBAAmB,IAAA,CAAK,eAAA;AAAA,IAC3E;AACA,IAAA,QAAA,CAAS,OAAA,GAAU,IAAA,CAAK,uBAAA,GAA0B,IAAA,CAAK,sBAAsB,CAAA;AAI7E,IAAA,IAAA,CAAK,QAAQ,QAAA,EAAS;AACtB,IAAA,IAAI,IAAA,CAAK,wBAAwB,CAAA,EAAG;AAClC,MAAA,IAAA,CAAK,QAAQ,GAAA,CAAI,MAAM,KAAK,MAAA,EAAO,EAAG,KAAK,qBAAqB,CAAA;AAAA,IAClE;AAAA,EACF;AAAA;AAAA,EAGA,MAAA,GAAe;AACb,IAAA,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,YAAA,EAAc,MAAM,CAAA;AAC9C,IAAA,IAAI,KAAK,iBAAA,EAAmB;AAC1B,MAAA,IAAA,CAAK,eAAe,WAAA,GAAc,EAAA;AAAA,IACpC;AAAA,EACF;AACF","file":"clipboard_controller.js","sourcesContent":["/**\n * Sends one message to the page's shared `stimeo--announcer`.\n *\n * A component that has to reach assistive tech does not carry a live region of its\n * own: a region only announces what changes *after* assistive tech already knows\n * about it, which a region that appears (or is un-hidden) with its message cannot\n * satisfy. The one region that can is the announcer sitting in the page from the\n * start, so state changes are handed to it as an event and it does the reading.\n *\n * The event goes to `window` because the announcer is usually a sibling high in the\n * document rather than an ancestor of the component dispatching it.\n *\n * Wording comes from the consumer — the library ships no English strings — so an\n * empty message is silently dropped and nothing is announced.\n *\n * @example\n * ```ts\n * announce(this.announceTextValue, { assertive: false });\n * ```\n */\nexport function announce(message: string, options: { assertive?: boolean } = {}): void {\n const text = message.trim();\n if (text.length === 0) return;\n window.dispatchEvent(\n new CustomEvent(\"stimeo--announcer:announce\", {\n detail: { message: text, assertive: options.assertive === true },\n }),\n );\n}\n\n/**\n * Fills `{name}` placeholders in an announcement template from `values`.\n *\n * The same substitution the value-text templates use, so a consumer writes\n * `\"{percent}% complete\"` in one attribute and gets the same rules everywhere. A\n * placeholder with no matching entry is left as authored rather than blanked, which\n * keeps a typo visible instead of silently swallowing the word.\n */\nexport function fillTemplate(template: string, values: Record<string, string | number>): string {\n return template.replace(/\\{([a-zA-Z][a-zA-Z0-9]*)\\}/g, (match, name: string) => {\n const replacement = values[name];\n return replacement === undefined ? match : String(replacement);\n });\n}\n","/**\n * 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.\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","/**\n * Adds an attribute default without displacing an authored value.\n *\n * Attribute presence — including an authored empty string — is the ownership\n * boundary. The return value lets a caller remember that it supplied the\n * default when that caller must later restore the authored state.\n *\n * @param element - Element that owns the attribute\n * @param name - Attribute name\n * @param value - Value to write only when the attribute is absent\n * @returns Whether this call added the attribute\n */\nexport function setDefaultAttribute(element: Element, name: string, value: string): boolean {\n if (element.hasAttribute(name)) return false;\n element.setAttribute(name, value);\n return true;\n}\n","/**\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 { announce } from \"../utils/announce\";\nimport { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { setDefaultAttribute } from \"../utils/default_attribute\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/**\n * The `data-state` values this controller writes itself. Any other value on the\n * attribute was authored by the consumer and is left alone.\n */\nconst TRANSIENT_STATES = new Set([\"copied\", \"error\"]);\n\n/**\n * Headless copy-to-clipboard behavior with a completion slot and a screen-reader\n * announcement.\n *\n * Markup contract (identifier: `stimeo--clipboard`):\n * <div data-controller=\"stimeo--clipboard\"\n * data-stimeo--clipboard-feedback-duration-value=\"2000\"\n * data-stimeo--clipboard-announce-copied-text-value=\"Copied to clipboard\"\n * data-stimeo--clipboard-announce-error-text-value=\"Copy failed\">\n * <input type=\"text\" value=\"https://example.com\" readonly\n * data-stimeo--clipboard-target=\"source\">\n * <button type=\"button\" data-stimeo--clipboard-target=\"button\"\n * data-action=\"stimeo--clipboard#copy\">Copy</button>\n * <span data-stimeo--clipboard-target=\"feedback\"></span>\n * </div>\n *\n * No dedicated APG pattern; this follows the Button practice plus a status message\n * ({@link https://www.w3.org/WAI/WCAG22/Understanding/status-changes.html | WCAG 2.2 SC 4.1.3}).\n * The copy uses the standard `navigator.clipboard` API (no extra dependency); every\n * failure mode — an API the browser withholds outside a secure context as much as a\n * rejected permission — settles the same way, as `data-state=\"error\"` plus the\n * `copy` event's `success: false`.\n *\n * Targets: `source` (the text to copy, when `text` is not set), `button` (the\n * control that triggers `copy`), `feedback` (the **visible** completion slot).\n *\n * Values: `text` (copy this instead of reading `source`), `feedbackDuration` (ms the\n * completion state is held; `0` or less arms no timer, so it stands until the next\n * copy — a reconnect and the before-cache rewind still clear it), `copiedLabel` /\n * `errorLabel` (what the visible slot shows), `announceCopiedText` /\n * `announceErrorText` (what assistive tech hears; empty announces nothing).\n *\n * @remarks\n * Behavior only — icon swaps and styling are the consumer's, keyed off `data-state`\n * (`idle` / `copied` / `error`).\n *\n * **The `feedback` slot must not carry live-region semantics.** Announcing is the\n * page's shared `stimeo--announcer` job: it is seated before the change it reads,\n * which a slot filled on demand cannot be, and it already collapses a repeat of the\n * same wording so a second copy is still heard. A `role=\"status\"` on the slot as\n * well would say everything twice.\n *\n * `copied` and `error` are transient: the timer that clears them belongs to one\n * connection, so a fresh `connect()` that finds either — a restored snapshot, an\n * in-page move — returns to `idle`, and the state is rewound before Turbo caches\n * the page ({@link BeforeCacheReset}). The rewind is silent: it discards nothing a\n * reconnect does not derive again.\n */\nexport class ClipboardController extends Controller<HTMLElement> {\n static override targets = [\"source\", \"button\", \"feedback\"];\n static override values = {\n text: { type: String, default: \"\" },\n feedbackDuration: { type: Number, default: 2000 },\n copiedLabel: { type: String, default: \"Copied\" },\n errorLabel: { type: String, default: \"Copy failed\" },\n announceCopiedText: { type: String, default: \"\" },\n announceErrorText: { type: String, default: \"\" },\n };\n static actions = [\"copy\"] as const;\n static events = [\"copy\"] as const;\n\n declare readonly sourceTarget: HTMLElement;\n declare readonly buttonTarget: HTMLElement;\n declare readonly feedbackTarget: HTMLElement;\n declare readonly hasSourceTarget: boolean;\n declare readonly hasButtonTarget: boolean;\n declare readonly hasFeedbackTarget: boolean;\n\n declare textValue: string;\n declare feedbackDurationValue: number;\n declare copiedLabelValue: string;\n declare errorLabelValue: string;\n declare announceCopiedTextValue: string;\n declare announceErrorTextValue: string;\n\n /**\n * The pending return to idle — the only timer this controller schedules, so\n * `clearAll()` is exactly \"drop the auto-clear\" and needs no id of its own.\n */\n readonly #timers = new SafeTimeout();\n\n /** Returns the completion state to idle for the snapshot Turbo takes. */\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewind());\n\n /**\n * Whether this connection is still live. `copy()` suspends on the Clipboard API,\n * and a teardown that lands while it is suspended must win: the continuation\n * would otherwise write to an element nobody owns and arm a timer past the\n * `clearAll()` that was supposed to be the last word.\n */\n #connected = false;\n\n override connect(): void {\n this.#connected = true;\n this.#adopt();\n this.#beforeCache.activate();\n }\n\n override disconnect(): void {\n this.#connected = false;\n this.#beforeCache.deactivate();\n this.#timers.clearAll();\n }\n\n /**\n * Copies the resolved text and reports the outcome. Bound via `data-action`\n * (click). Dispatches `stimeo--clipboard:copy` with `{ success, text }` once per\n * completed attempt — including on failure — so consumers can react either way.\n * An attempt whose connection ended while it was in flight reports nothing.\n */\n async copy(): Promise<void> {\n const text = this.#resolveText();\n let success = false;\n try {\n await navigator.clipboard.writeText(text);\n success = true;\n } catch {\n success = false;\n }\n if (!this.#connected) return;\n\n this.#reportResult(success);\n this.dispatch(\"copy\", { detail: { success, text } });\n }\n\n /**\n * The text to copy: the explicit `text` value when set, otherwise the source\n * target's current value (inputs/textareas) or text content.\n */\n #resolveText(): string {\n if (this.textValue.length > 0) return this.textValue;\n if (!this.hasSourceTarget) return \"\";\n const source = this.sourceTarget;\n if (source instanceof HTMLInputElement || source instanceof HTMLTextAreaElement) {\n return source.value;\n }\n return source.textContent ?? \"\";\n }\n\n /**\n * Reads the current state back from the DOM.\n *\n * A `copied` or `error` found at connect time is this controller's own output\n * from a connection that is gone, and so is the timer that would have cleared it\n * — nothing else would ever return the element to `idle`. Any other authored\n * value belongs to the consumer and only a missing attribute takes the default.\n */\n #adopt(): void {\n if (this.#inTransientState()) {\n this.#reset();\n return;\n }\n setDefaultAttribute(this.element, \"data-state\", \"idle\");\n }\n\n /** Whether `data-state` currently holds one of the values this controller writes. */\n #inTransientState(): boolean {\n const state = this.element.getAttribute(\"data-state\");\n return state !== null && TRANSIENT_STATES.has(state);\n }\n\n /**\n * Returns the completion state to idle for the snapshot Turbo is about to take,\n * so a page reached with the Back button does not report a copy that happened\n * before the navigation. Only a state this controller wrote is rewound — an\n * authored one is the consumer's and has to survive into the snapshot, exactly as\n * `connect()` leaves it alone. State only — no `copy` is dispatched, which would\n * claim a fresh copy ran.\n */\n #rewind(): void {\n if (!this.#inTransientState()) return;\n this.#timers.clearAll();\n this.#reset();\n }\n\n /** Reflects the result, announces it, and schedules the return to idle. */\n #reportResult(success: boolean): void {\n this.element.setAttribute(\"data-state\", success ? \"copied\" : \"error\");\n if (this.hasFeedbackTarget) {\n this.feedbackTarget.textContent = success ? this.copiedLabelValue : this.errorLabelValue;\n }\n announce(success ? this.announceCopiedTextValue : this.announceErrorTextValue);\n\n // Drop any in-flight reset so consecutive copies restart the full window\n // rather than having the earlier timer clear the new result prematurely.\n this.#timers.clearAll();\n if (this.feedbackDurationValue > 0) {\n this.#timers.set(() => this.#reset(), this.feedbackDurationValue);\n }\n }\n\n /** Returns to the idle state and empties the completion slot. */\n #reset(): void {\n this.element.setAttribute(\"data-state\", \"idle\");\n if (this.hasFeedbackTarget) {\n this.feedbackTarget.textContent = \"\";\n }\n }\n}\n"]}