stimeo-ui 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +151 -0
- package/dist/controllers/auto_submit_controller.d.ts +14 -3
- package/dist/controllers/auto_submit_controller.js +94 -16
- package/dist/controllers/auto_submit_controller.js.map +1 -1
- package/dist/controllers/bulk_select_controller.d.ts +62 -15
- package/dist/controllers/bulk_select_controller.js +139 -28
- package/dist/controllers/bulk_select_controller.js.map +1 -1
- package/dist/controllers/carousel_controller.d.ts +81 -47
- package/dist/controllers/carousel_controller.js +451 -100
- package/dist/controllers/carousel_controller.js.map +1 -1
- package/dist/controllers/clipboard_controller.d.ts +48 -15
- package/dist/controllers/clipboard_controller.js +102 -20
- package/dist/controllers/clipboard_controller.js.map +1 -1
- package/dist/controllers/color_picker_controller.d.ts +37 -6
- package/dist/controllers/color_picker_controller.js +180 -43
- package/dist/controllers/color_picker_controller.js.map +1 -1
- package/dist/controllers/currency_input_controller.d.ts +39 -5
- package/dist/controllers/currency_input_controller.js +305 -74
- package/dist/controllers/currency_input_controller.js.map +1 -1
- package/dist/controllers/data_grid_controller.d.ts +25 -9
- package/dist/controllers/data_grid_controller.js +150 -24
- package/dist/controllers/data_grid_controller.js.map +1 -1
- package/dist/controllers/direct_upload_controller.d.ts +3 -1
- package/dist/controllers/direct_upload_controller.js +12 -2
- package/dist/controllers/direct_upload_controller.js.map +1 -1
- package/dist/controllers/editable_controller.d.ts +34 -9
- package/dist/controllers/editable_controller.js +83 -30
- package/dist/controllers/editable_controller.js.map +1 -1
- package/dist/controllers/file_dropzone_controller.d.ts +123 -29
- package/dist/controllers/file_dropzone_controller.js +386 -63
- package/dist/controllers/file_dropzone_controller.js.map +1 -1
- package/dist/controllers/filter_controller.d.ts +15 -3
- package/dist/controllers/filter_controller.js +32 -1
- package/dist/controllers/filter_controller.js.map +1 -1
- package/dist/controllers/flash_controller.d.ts +3 -1
- package/dist/controllers/flash_controller.js +3 -1
- package/dist/controllers/flash_controller.js.map +1 -1
- package/dist/controllers/frame_loading_controller.d.ts +4 -2
- package/dist/controllers/frame_loading_controller.js +2 -1
- package/dist/controllers/frame_loading_controller.js.map +1 -1
- package/dist/controllers/input_mask_controller.d.ts +42 -16
- package/dist/controllers/input_mask_controller.js +251 -76
- package/dist/controllers/input_mask_controller.js.map +1 -1
- package/dist/controllers/masonry_controller.d.ts +34 -5
- package/dist/controllers/masonry_controller.js +129 -17
- package/dist/controllers/masonry_controller.js.map +1 -1
- package/dist/controllers/nested_form_controller.d.ts +51 -14
- package/dist/controllers/nested_form_controller.js +450 -42
- package/dist/controllers/nested_form_controller.js.map +1 -1
- package/dist/controllers/otp_controller.d.ts +64 -25
- package/dist/controllers/otp_controller.js +485 -114
- package/dist/controllers/otp_controller.js.map +1 -1
- package/dist/controllers/reset_before_cache_controller.d.ts +25 -2
- package/dist/controllers/reset_before_cache_controller.js +51 -5
- package/dist/controllers/reset_before_cache_controller.js.map +1 -1
- package/dist/controllers/resizable_controller.d.ts +23 -7
- package/dist/controllers/resizable_controller.js +128 -55
- package/dist/controllers/resizable_controller.js.map +1 -1
- package/dist/controllers/spinner_controller.d.ts +3 -2
- package/dist/controllers/spinner_controller.js +7 -5
- package/dist/controllers/spinner_controller.js.map +1 -1
- package/dist/controllers/submit_once_controller.d.ts +4 -1
- package/dist/controllers/submit_once_controller.js +3 -1
- package/dist/controllers/submit_once_controller.js.map +1 -1
- package/dist/controllers/textarea_autosize_controller.d.ts +30 -10
- package/dist/controllers/textarea_autosize_controller.js +131 -3
- package/dist/controllers/textarea_autosize_controller.js.map +1 -1
- package/dist/index.js +2764 -923
- package/dist/index.js.map +1 -1
- package/dist/inspector/cli.d.ts +8 -1
- package/dist/inspector/cli.js +5 -1
- package/dist/inspector/cli.js.map +1 -1
- package/dist/inspector/cli_bin.js +5 -1
- package/dist/inspector/cli_bin.js.map +1 -1
- package/dist/inspector/examples.json +24 -24
- package/dist/inspector/manifest.json +193 -30
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/announce.ts","../../src/utils/before_cache_reset.ts","../../src/utils/safe_timeout.ts","../../src/controllers/direct_upload_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;AAUO,SAAS,YAAA,CAAa,UAAkB,MAAA,EAAiD;AAC9F,EAAA,OAAO,QAAA,CAAS,OAAA,CAAQ,6BAAA,EAA+B,CAAC,OAAO,IAAA,KAAiB;AAC9E,IAAA,MAAM,WAAA,GAAc,OAAO,IAAI,CAAA;AAC/B,IAAA,OAAO,WAAA,KAAgB,MAAA,GAAY,KAAA,GAAQ,MAAA,CAAO,WAAW,CAAA;AAAA,EAC/D,CAAC,CAAA;AACH;;;ACAO,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,UAAA,IAAc,iBAAA,CAAiB,YAAA,EAAc,UAAA,CAAW,OAAA,EAAQ;AAAA,EAC7E,CAAA;AAAA,EAES,OAAA;AAAA;AAAA,EAGT,YAAY,MAAA,EAAoB;AAC9B,IAAA,IAAA,CAAK,OAAA,GAAU,MAAA;AAAA,EACjB;AAAA;AAAA,EAGA,QAAA,GAAiB;AACf,IAAA,MAAM,KAAA,GAAQ,iBAAA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AC;AAAA,EACzD;AAAA;AAAA,EAGA,MAAM,MAAA,EAA8B;AAClC,IAAA,OAAO,MAAA,CAAO,MAAM,IAAA,IAAQ,EAAA;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,SAAS,KAAA,EAAuB;AAC9B,IAAA,IAAI,IAAA,CAAK,cAAA,CAAe,MAAA,KAAW,CAAA,EAAG,OAAO,IAAA;AAC7C,IAAA,MAAM,SAAS,KAAA,CAAM,MAAA;AACrB,IAAA,OAAO,kBAAkB,OAAA,IAAW,MAAA,CAAO,OAAA,CAAQ,IAAA,CAAK,cAAc,CAAA,KAAM,IAAA;AAAA,EAC9E;AAAA,EAEA,KAAK,EAAA,EAAyC;AAC5C,IAAA,OAAO,MAAA,CAAO,MAAM,EAAE,CAAA;AAAA,EACxB;AACF","file":"direct_upload_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 (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","/**\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 { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/** Detail shapes for the ActiveStorage `direct-upload:*` events. */\ninterface UploadDetail {\n id?: string | number;\n file?: { name?: string };\n progress?: number;\n error?: string;\n}\n\n/** Delay (ms) before a completed row is removed when `removeOnDone` is set. */\nconst REMOVE_DELAY = 4000;\n\n/**\n * Headless progress UI for ActiveStorage Direct Uploads: subscribes to the\n * `direct-upload:*` events and renders a per-file progress row (no dedicated APG\n * pattern; the rows follow the `role=\"progressbar\"` practice). The companion to\n * {@link \"file-dropzone\"}, which leaves transport out of scope.\n *\n * Markup contract (identifier: `stimeo--direct-upload`):\n * <div data-controller=\"stimeo--direct-upload\"\n * data-stimeo--direct-upload-announce-done-text-value=\"{name} uploaded\"\n * data-stimeo--direct-upload-announce-error-text-value=\"{name} failed\">\n * <div data-stimeo--direct-upload-target=\"list\"></div>\n * <template data-stimeo--direct-upload-target=\"row\">\n * <div role=\"progressbar\" aria-valuemin=\"0\" aria-valuemax=\"100\">\n * <span data-field=\"name\"></span><span data-field=\"percent\"></span>\n * </div>\n * </template>\n * </div>\n *\n * For each upload it clones the `row` template into `list`, then keeps\n * `aria-valuenow` / `aria-valuetext`, the `[data-field=\"percent\"]` text, and the\n * `--stimeo--upload-progress` custom property (0–100, rounded and clamped) in\n * sync as `direct-upload:progress` arrives. The file name carried by the events\n * fills `[data-field=\"name\"]` and becomes the row's `aria-label` unless the\n * template already authors one. The aggregate across live rows is mirrored on\n * the controller element as `data-upload-progress` plus the same custom\n * property, recomputed whenever a row is added, updated, or removed, and\n * withdrawn entirely once no rows remain.\n *\n * A row leaves `uploading` exactly once: `direct-upload:error` settles it as\n * `error`, and `direct-upload:end` — which ActiveStorage fires after success\n * *and* failure — completes only rows not already settled, pinning them at 100%\n * and flipping `data-upload-state` to `done`. Later events never rewrite a\n * settled row, so a failure survives the `end` that follows it.\n *\n * Completion and failure are handed to the page's shared `stimeo--announcer` as\n * one polite message each, worded by the consumer via `announceDoneText` /\n * `announceErrorText` (`{name}` expands to the file name; empty templates stay\n * silent, keeping announcements opt-in and i18n-neutral). Per-tick progress is\n * not announced — the progressbar's `aria-valuenow` conveys it — to avoid\n * flooding. A failure this controller has rendered also cancels the\n * `direct-upload:error` default, which suppresses ActiveStorage's native\n * `alert()`; when no row could be rendered the alert stays as the fallback.\n *\n * Events dispatched on the controller element (all bubble):\n * - `stimeo--direct-upload:progress` dispatches `{ id: string, percent: number }`\n * on each progress update, after clamping.\n * - `stimeo--direct-upload:done` dispatches `{ id: string }` when an upload\n * completes successfully.\n * - `stimeo--direct-upload:error` dispatches `{ id: string, error: string }`\n * when an upload fails.\n *\n * @remarks\n * Behavior only — no bars are drawn. The `direct-upload:*` listeners live on\n * `document` (the events bubble there) and are removed on `disconnect()` (Turbo\n * navigation included), along with any pending removal timers, so a callback\n * that arrives after teardown never touches a detached row. Rows are transient\n * UI: just before Turbo caches the page they are removed and the aggregate is\n * withdrawn, so a restored snapshot starts pristine instead of replaying stale\n * rows (a dead upload cannot resume after restoration). The live DOM stays the\n * source of truth — a row removed or replaced outside this controller is\n * forgotten and rebuilt on the next event for its id, and a clone stranded\n * outside the current `list` (a re-pointed target) is removed outright, so\n * generated rows only ever live there.\n *\n * With multiple upload widgets on one page, set `scope` to a selector for the\n * owning form/root so each widget only handles its own uploads. A `scope` that\n * does not parse as a selector falls back to the default (handle all) instead\n * of throwing from the event handlers, so one broken declaration cannot silence\n * the widget.\n */\nexport class DirectUploadController extends Controller<HTMLElement> {\n static override targets = [\"list\", \"row\"];\n static override values = {\n removeOnDone: { type: Boolean, default: false },\n announceDoneText: { type: String, default: \"\" },\n announceErrorText: { type: String, default: \"\" },\n scope: { type: String, default: \"\" },\n };\n static events = [\"progress\", \"done\", \"error\"] as const;\n\n declare readonly listTarget: HTMLElement;\n declare readonly rowTarget: HTMLTemplateElement;\n declare readonly hasListTarget: boolean;\n declare readonly hasRowTarget: boolean;\n\n declare removeOnDoneValue: boolean;\n declare announceDoneTextValue: string;\n declare announceErrorTextValue: string;\n declare scopeValue: string;\n\n readonly #timeouts = new SafeTimeout();\n readonly #rows = new Map<string, HTMLElement>();\n readonly #beforeCache = new BeforeCacheReset(() => this.#reset());\n\n /** The validated `scope` selector; a broken declaration falls back to `\"\"`. */\n #scopeSelector = \"\";\n\n readonly #onInitialize = (event: Event): void => {\n if (!this.#inScope(event)) return;\n const detail = this.#detail(event);\n this.#rowFor(detail.id, this.#name(detail));\n };\n\n readonly #onProgress = (event: Event): void => {\n if (!this.#inScope(event)) return;\n const detail = this.#detail(event);\n this.#updateProgress(this.#key(detail.id), detail.progress ?? 0, this.#name(detail));\n };\n\n readonly #onError = (event: Event): void => {\n if (!this.#inScope(event)) return;\n const detail = this.#detail(event);\n const rendered = this.#fail(this.#key(detail.id), detail.error ?? \"\", this.#name(detail));\n // ActiveStorage alert()s the raw error unless the event is cancelled. A\n // failure this widget displays is handled, so the blocking duplicate is\n // suppressed; an unrendered failure keeps the alert as its only signal.\n if (rendered) event.preventDefault();\n };\n\n readonly #onEnd = (event: Event): void => {\n if (!this.#inScope(event)) return;\n const detail = this.#detail(event);\n this.#complete(this.#key(detail.id), this.#name(detail));\n };\n\n override connect(): void {\n document.addEventListener(\"direct-upload:initialize\", this.#onInitialize);\n document.addEventListener(\"direct-upload:progress\", this.#onProgress);\n document.addEventListener(\"direct-upload:error\", this.#onError);\n document.addEventListener(\"direct-upload:end\", this.#onEnd);\n this.#beforeCache.activate();\n // An in-page move runs disconnect() → connect() on the same instance, and\n // teardown cancelled any pending removals; completed rows re-earn theirs.\n this.#rescheduleRemovals();\n }\n\n override disconnect(): void {\n document.removeEventListener(\"direct-upload:initialize\", this.#onInitialize);\n document.removeEventListener(\"direct-upload:progress\", this.#onProgress);\n document.removeEventListener(\"direct-upload:error\", this.#onError);\n document.removeEventListener(\"direct-upload:end\", this.#onEnd);\n this.#beforeCache.deactivate();\n this.#timeouts.clearAll();\n // `#rows` is kept: `disconnect()` also fires on an in-page move, where the\n // rows travel with the element and the next event should keep updating\n // them. Stale entries self-heal via `#prune`, and the Turbo-cache path\n // clears everything in `#reset()`.\n }\n\n /** Validates `scope` once so the per-event path never parses or throws. */\n scopeValueChanged(): void {\n const selector = this.scopeValue;\n if (selector.length > 0) {\n try {\n this.element.matches(selector);\n this.#scopeSelector = selector;\n return;\n } catch {\n // Unparsable selector: fall through to the default below.\n }\n }\n this.#scopeSelector = \"\";\n }\n\n /** Updates a row's progress and the aggregate, emitting `progress`. */\n #updateProgress(id: string, percent: number, name: string): void {\n const row = this.#rowFor(id, name);\n if (row === null || this.#isSettled(row)) return;\n const clamped = this.#applyProgress(row, percent);\n this.#syncAggregate();\n this.dispatch(\"progress\", { detail: { id, percent: clamped } });\n }\n\n /** Marks a not-yet-settled row done at 100%, announces it, and emits `done`. */\n #complete(id: string, name: string): void {\n // Resolve lazily like `#fail`/`#updateProgress` so an `end` that arrives\n // without a prior `initialize`/`progress` (no row yet) still records the\n // completion instead of silently dropping it.\n const row = this.#rowFor(id, name);\n if (row === null || this.#isSettled(row)) return;\n row.setAttribute(\"data-upload-state\", \"done\");\n this.#applyProgress(row, 100);\n this.#syncAggregate();\n this.#announce(this.announceDoneTextValue, name, row);\n this.dispatch(\"done\", { detail: { id } });\n if (this.removeOnDoneValue) {\n this.#timeouts.set(() => this.#removeRow(id), REMOVE_DELAY);\n }\n }\n\n /**\n * Marks a not-yet-settled row failed, announces it, and emits `error`.\n * Returns whether the failure is rendered by this widget (used to decide the\n * `direct-upload:error` default), which also holds when the row already\n * displays an earlier failure.\n */\n #fail(id: string, error: string, name: string): boolean {\n const row = this.#rowFor(id, name);\n if (row === null) return false;\n if (this.#isSettled(row)) return row.getAttribute(\"data-upload-state\") === \"error\";\n row.setAttribute(\"data-upload-state\", \"error\");\n this.#announce(this.announceErrorTextValue, name, row);\n this.dispatch(\"error\", { detail: { id, error } });\n return true;\n }\n\n /** Whether the row reached a terminal state; settled rows are never rewritten. */\n #isSettled(row: HTMLElement): boolean {\n const state = row.getAttribute(\"data-upload-state\");\n return state === \"done\" || state === \"error\";\n }\n\n /** Re-arms `removeOnDone` for completed rows after a reconnect. */\n #rescheduleRemovals(): void {\n if (!this.removeOnDoneValue) return;\n this.#prune();\n for (const [id, row] of this.#rows) {\n if (row.getAttribute(\"data-upload-state\") === \"done\") {\n this.#timeouts.set(() => this.#removeRow(id), REMOVE_DELAY);\n }\n }\n }\n\n /** Returns the live row for `id`, creating (and labeling) one on first sight. */\n #rowFor(id: string | number | undefined, name: string): HTMLElement | null {\n const key = this.#key(id);\n const existing = this.#rows.get(key);\n if (existing !== undefined) {\n if (this.#tracksRow(existing)) {\n this.#applyName(existing, name);\n return existing;\n }\n // Removed, replaced, or no longer inside the current list: retire the\n // clone (removing it is a no-op when something else already did) and\n // rebuild from the live DOM.\n existing.remove();\n this.#rows.delete(key);\n }\n if (!this.hasRowTarget || !this.hasListTarget) return null;\n const clone = this.rowTarget.content.firstElementChild?.cloneNode(true);\n if (!(clone instanceof HTMLElement)) return null;\n this.#applyName(clone, name);\n clone.setAttribute(\"data-upload-state\", \"uploading\");\n this.#applyProgress(clone, 0);\n this.listTarget.appendChild(clone);\n this.#rows.set(key, clone);\n this.#syncAggregate();\n return clone;\n }\n\n /**\n * Writes the event's file name into `[data-field=\"name\"]` and, unless the row\n * already carries a non-blank `aria-label` — authored on the template or\n * applied by an earlier event — makes it the accessible name too. The visible\n * name never depends on the label: an authored label keeps its wording while\n * the field still shows which file this row tracks.\n */\n #applyName(row: HTMLElement, name: string): void {\n if (name.length === 0) return;\n this.#setField(row, \"name\", name);\n // A whitespace-only label computes to no accessible name, so only a\n // non-blank one counts as authored.\n if ((row.getAttribute(\"aria-label\") ?? \"\").trim().length > 0) return;\n row.setAttribute(\"aria-label\", name);\n }\n\n /** Writes one progress value to every per-row hook; returns the clamped percent. */\n #applyProgress(row: HTMLElement, percent: number): number {\n const clamped = Math.max(0, Math.min(100, Math.round(percent)));\n row.setAttribute(\"aria-valuenow\", String(clamped));\n row.setAttribute(\"aria-valuetext\", `${clamped}%`);\n row.style.setProperty(\"--stimeo--upload-progress\", `${clamped}%`);\n this.#setField(row, \"percent\", `${clamped}%`);\n return clamped;\n }\n\n #removeRow(id: string): void {\n const row = this.#rows.get(id);\n if (row === undefined) return;\n row.remove();\n this.#rows.delete(id);\n this.#syncAggregate();\n }\n\n /**\n * Reflects the average progress across live rows on the controller element,\n * withdrawing both hooks once no rows remain.\n */\n #syncAggregate(): void {\n this.#prune();\n if (this.#rows.size === 0) {\n this.element.removeAttribute(\"data-upload-progress\");\n this.element.style.removeProperty(\"--stimeo--upload-progress\");\n return;\n }\n let total = 0;\n for (const row of this.#rows.values()) {\n total += Number(row.getAttribute(\"aria-valuenow\") ?? \"0\");\n }\n const overall = Math.round(total / this.#rows.size);\n this.element.setAttribute(\"data-upload-progress\", String(overall));\n this.element.style.setProperty(\"--stimeo--upload-progress\", `${overall}%`);\n }\n\n /**\n * Whether a bookkept row is still this widget's live UI: connected, and — when\n * a `list` target is present — inside the *current* one, so re-pointing the\n * target attribute at a new element retires rows kept alive in the old list.\n */\n #tracksRow(row: HTMLElement): boolean {\n if (!row.isConnected) return false;\n return !this.hasListTarget || this.listTarget.contains(row);\n }\n\n /**\n * Retires rows that left the live UI (list swap, external removal). A retired\n * clone is removed outright — generated rows only ever live under the current\n * `list`, so the before-cache rewind never has an untracked leftover to miss.\n */\n #prune(): void {\n for (const [id, row] of this.#rows) {\n if (this.#tracksRow(row)) continue;\n row.remove();\n this.#rows.delete(id);\n }\n }\n\n /**\n * Returns the widget to its pre-upload state just before Turbo caches the\n * page, so the snapshot never replays rows for uploads that cannot resume.\n */\n #reset(): void {\n for (const row of this.#rows.values()) row.remove();\n this.#rows.clear();\n this.#timeouts.clearAll();\n this.#syncAggregate();\n }\n\n /**\n * Sends one consumer-worded message to the page's shared announcer. `{name}`\n * resolves to the row's displayed name first — the event that settles an\n * upload may omit the file although an earlier event already named the row —\n * then the event's own name, then the accessible name (which an authored\n * label owns, so it is the last resort, not the primary source).\n */\n #announce(template: string, name: string, row: HTMLElement): void {\n const stored = this.#field(row, \"name\")?.textContent ?? \"\";\n const label =\n stored.length > 0 ? stored : name.length > 0 ? name : (row.getAttribute(\"aria-label\") ?? \"\");\n announce(fillTemplate(template, { name: label }));\n }\n\n #field(row: HTMLElement, name: string): HTMLElement | null {\n return row.querySelector<HTMLElement>(`[data-field=\"${name}\"]`);\n }\n\n #setField(row: HTMLElement, name: string, text: string): void {\n const field = this.#field(row, name);\n if (field !== null) field.textContent = text;\n }\n\n #detail(event: Event): UploadDetail {\n return (event as CustomEvent<UploadDetail>).detail ?? {};\n }\n\n /** The file name every ActiveStorage `direct-upload:*` event carries. */\n #name(detail: UploadDetail): string {\n return detail.file?.name ?? \"\";\n }\n\n /**\n * Whether an event belongs to this controller. With `scope` set, only events\n * whose target (the file input) sits inside an element matching `scope` are\n * handled, so several upload widgets on one page do not cross-populate.\n * Resolved with `closest()` from the target itself, so the chatty `progress`\n * stream never pays a document-wide query. Empty `scope` handles all.\n */\n #inScope(event: Event): boolean {\n if (this.#scopeSelector.length === 0) return true;\n const target = event.target;\n return target instanceof Element && target.closest(this.#scopeSelector) !== null;\n }\n\n #key(id: string | number | undefined): string {\n return String(id ?? \"\");\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/announce.ts","../../src/utils/before_cache_reset.ts","../../src/utils/safe_timeout.ts","../../src/controllers/direct_upload_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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C;AAAA,EACzD;AAAA;AAAA,EAGA,MAAM,MAAA,EAA8B;AAClC,IAAA,OAAO,MAAA,CAAO,MAAM,IAAA,IAAQ,EAAA;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,SAAS,KAAA,EAAuB;AAC9B,IAAA,IAAI,IAAA,CAAK,cAAA,CAAe,MAAA,KAAW,CAAA,EAAG,OAAO,IAAA;AAC7C,IAAA,MAAM,SAAS,KAAA,CAAM,MAAA;AACrB,IAAA,OAAO,kBAAkB,OAAA,IAAW,MAAA,CAAO,OAAA,CAAQ,IAAA,CAAK,cAAc,CAAA,KAAM,IAAA;AAAA,EAC9E;AAAA,EAEA,KAAK,EAAA,EAAyC;AAC5C,IAAA,OAAO,MAAA,CAAO,MAAM,EAAE,CAAA;AAAA,EACxB;AACF","file":"direct_upload_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 (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","/**\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 { BeforeCacheReset } from \"../utils/before_cache_reset\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/** Detail shapes for the ActiveStorage `direct-upload:*` events. */\ninterface UploadDetail {\n id?: string | number;\n file?: { name?: string };\n progress?: number;\n error?: string;\n}\n\n/** Delay (ms) before a completed row is removed when `removeOnDone` is set. */\nconst REMOVE_DELAY = 4000;\n\n/**\n * Headless progress UI for ActiveStorage Direct Uploads: subscribes to the\n * `direct-upload:*` events and renders a per-file progress row (no dedicated APG\n * pattern; the rows follow the `role=\"progressbar\"` practice). The companion to\n * {@link \"file-dropzone\"}, which leaves transport out of scope.\n *\n * Markup contract (identifier: `stimeo--direct-upload`):\n * <div data-controller=\"stimeo--direct-upload\"\n * data-stimeo--direct-upload-announce-done-text-value=\"{name} uploaded\"\n * data-stimeo--direct-upload-announce-error-text-value=\"{name} failed\">\n * <div data-stimeo--direct-upload-target=\"list\"></div>\n * <template data-stimeo--direct-upload-target=\"row\">\n * <div role=\"progressbar\" aria-valuemin=\"0\" aria-valuemax=\"100\">\n * <span data-field=\"name\"></span><span data-field=\"percent\"></span>\n * </div>\n * </template>\n * </div>\n *\n * For each upload it clones the `row` template into `list`, then keeps\n * `aria-valuenow` / `aria-valuetext`, the `[data-field=\"percent\"]` text, and the\n * `--stimeo--upload-progress` custom property (0–100, rounded and clamped) in\n * sync as `direct-upload:progress` arrives. The file name carried by the events\n * fills `[data-field=\"name\"]` and becomes the row's `aria-label` unless the\n * template already authors one. The aggregate across live rows is mirrored on\n * the controller element as `data-upload-progress` plus the same custom\n * property, recomputed whenever a row is added, updated, or removed, and\n * withdrawn entirely once no rows remain.\n *\n * A row leaves `uploading` exactly once: `direct-upload:error` settles it as\n * `error`, and `direct-upload:end` — which ActiveStorage fires after success\n * *and* failure — completes only rows not already settled, pinning them at 100%\n * and flipping `data-upload-state` to `done`. Later events never rewrite a\n * settled row, so a failure survives the `end` that follows it.\n *\n * Completion and failure are handed to the page's shared `stimeo--announcer` as\n * one polite message each, worded by the consumer via `announceDoneText` /\n * `announceErrorText` (`{name}` expands to the file name; empty templates stay\n * silent, keeping announcements opt-in and i18n-neutral). Per-tick progress is\n * not announced — the progressbar's `aria-valuenow` conveys it — to avoid\n * flooding. A failure this controller has rendered also cancels the\n * `direct-upload:error` default, which suppresses ActiveStorage's native\n * `alert()`; when no row could be rendered the alert stays as the fallback.\n *\n * Events dispatched on the controller element (all bubble):\n * - `stimeo--direct-upload:progress` dispatches `{ id: string, percent: number }`\n * on each progress update, after clamping.\n * - `stimeo--direct-upload:done` dispatches `{ id: string }` when an upload\n * completes successfully.\n * - `stimeo--direct-upload:reconcile` dispatches `{ ids: string[] }` — the uploads\n * the Turbo cache rewind discarded, none of which can still finish\n * - `stimeo--direct-upload:error` dispatches `{ id: string, error: string }`\n * when an upload fails.\n *\n * @remarks\n * Behavior only — no bars are drawn. The `direct-upload:*` listeners live on\n * `document` (the events bubble there) and are removed on `disconnect()` (Turbo\n * navigation included), along with any pending removal timers, so a callback\n * that arrives after teardown never touches a detached row. Rows are transient\n * UI: just before Turbo caches the page they are removed and the aggregate is\n * withdrawn, so a restored snapshot starts pristine instead of replaying stale\n * rows (a dead upload cannot resume after restoration). The live DOM stays the\n * source of truth — a row removed or replaced outside this controller is\n * forgotten and rebuilt on the next event for its id, and a clone stranded\n * outside the current `list` (a re-pointed target) is removed outright, so\n * generated rows only ever live there.\n *\n * With multiple upload widgets on one page, set `scope` to a selector for the\n * owning form/root so each widget only handles its own uploads. A `scope` that\n * does not parse as a selector falls back to the default (handle all) instead\n * of throwing from the event handlers, so one broken declaration cannot silence\n * the widget.\n */\nexport class DirectUploadController extends Controller<HTMLElement> {\n static override targets = [\"list\", \"row\"];\n static override values = {\n removeOnDone: { type: Boolean, default: false },\n announceDoneText: { type: String, default: \"\" },\n announceErrorText: { type: String, default: \"\" },\n scope: { type: String, default: \"\" },\n };\n static events = [\"progress\", \"done\", \"error\", \"reconcile\"] as const;\n\n declare readonly listTarget: HTMLElement;\n declare readonly rowTarget: HTMLTemplateElement;\n declare readonly hasListTarget: boolean;\n declare readonly hasRowTarget: boolean;\n\n declare removeOnDoneValue: boolean;\n declare announceDoneTextValue: string;\n declare announceErrorTextValue: string;\n declare scopeValue: string;\n\n readonly #timeouts = new SafeTimeout();\n readonly #rows = new Map<string, HTMLElement>();\n readonly #beforeCache = new BeforeCacheReset(() => this.#rewindForCache());\n\n /** The validated `scope` selector; a broken declaration falls back to `\"\"`. */\n #scopeSelector = \"\";\n\n readonly #onInitialize = (event: Event): void => {\n if (!this.#inScope(event)) return;\n const detail = this.#detail(event);\n this.#rowFor(detail.id, this.#name(detail));\n };\n\n readonly #onProgress = (event: Event): void => {\n if (!this.#inScope(event)) return;\n const detail = this.#detail(event);\n this.#updateProgress(this.#key(detail.id), detail.progress ?? 0, this.#name(detail));\n };\n\n readonly #onError = (event: Event): void => {\n if (!this.#inScope(event)) return;\n const detail = this.#detail(event);\n const rendered = this.#fail(this.#key(detail.id), detail.error ?? \"\", this.#name(detail));\n // ActiveStorage alert()s the raw error unless the event is cancelled. A\n // failure this widget displays is handled, so the blocking duplicate is\n // suppressed; an unrendered failure keeps the alert as its only signal.\n if (rendered) event.preventDefault();\n };\n\n readonly #onEnd = (event: Event): void => {\n if (!this.#inScope(event)) return;\n const detail = this.#detail(event);\n this.#complete(this.#key(detail.id), this.#name(detail));\n };\n\n override connect(): void {\n document.addEventListener(\"direct-upload:initialize\", this.#onInitialize);\n document.addEventListener(\"direct-upload:progress\", this.#onProgress);\n document.addEventListener(\"direct-upload:error\", this.#onError);\n document.addEventListener(\"direct-upload:end\", this.#onEnd);\n this.#beforeCache.activate();\n // An in-page move runs disconnect() → connect() on the same instance, and\n // teardown cancelled any pending removals; completed rows re-earn theirs.\n this.#rescheduleRemovals();\n }\n\n override disconnect(): void {\n document.removeEventListener(\"direct-upload:initialize\", this.#onInitialize);\n document.removeEventListener(\"direct-upload:progress\", this.#onProgress);\n document.removeEventListener(\"direct-upload:error\", this.#onError);\n document.removeEventListener(\"direct-upload:end\", this.#onEnd);\n this.#beforeCache.deactivate();\n this.#timeouts.clearAll();\n // `#rows` is kept: `disconnect()` also fires on an in-page move, where the\n // rows travel with the element and the next event should keep updating\n // them. Stale entries self-heal via `#prune`, and the Turbo-cache path\n // clears everything in `#reset()`.\n }\n\n /** Validates `scope` once so the per-event path never parses or throws. */\n scopeValueChanged(): void {\n const selector = this.scopeValue;\n if (selector.length > 0) {\n try {\n this.element.matches(selector);\n this.#scopeSelector = selector;\n return;\n } catch {\n // Unparsable selector: fall through to the default below.\n }\n }\n this.#scopeSelector = \"\";\n }\n\n /** Updates a row's progress and the aggregate, emitting `progress`. */\n #updateProgress(id: string, percent: number, name: string): void {\n const row = this.#rowFor(id, name);\n if (row === null || this.#isSettled(row)) return;\n const clamped = this.#applyProgress(row, percent);\n this.#syncAggregate();\n this.dispatch(\"progress\", { detail: { id, percent: clamped } });\n }\n\n /** Marks a not-yet-settled row done at 100%, announces it, and emits `done`. */\n #complete(id: string, name: string): void {\n // Resolve lazily like `#fail`/`#updateProgress` so an `end` that arrives\n // without a prior `initialize`/`progress` (no row yet) still records the\n // completion instead of silently dropping it.\n const row = this.#rowFor(id, name);\n if (row === null || this.#isSettled(row)) return;\n row.setAttribute(\"data-upload-state\", \"done\");\n this.#applyProgress(row, 100);\n this.#syncAggregate();\n this.#announce(this.announceDoneTextValue, name, row);\n this.dispatch(\"done\", { detail: { id } });\n if (this.removeOnDoneValue) {\n this.#timeouts.set(() => this.#removeRow(id), REMOVE_DELAY);\n }\n }\n\n /**\n * Marks a not-yet-settled row failed, announces it, and emits `error`.\n * Returns whether the failure is rendered by this widget (used to decide the\n * `direct-upload:error` default), which also holds when the row already\n * displays an earlier failure.\n */\n #fail(id: string, error: string, name: string): boolean {\n const row = this.#rowFor(id, name);\n if (row === null) return false;\n if (this.#isSettled(row)) return row.getAttribute(\"data-upload-state\") === \"error\";\n row.setAttribute(\"data-upload-state\", \"error\");\n this.#announce(this.announceErrorTextValue, name, row);\n this.dispatch(\"error\", { detail: { id, error } });\n return true;\n }\n\n /** Whether the row reached a terminal state; settled rows are never rewritten. */\n #isSettled(row: HTMLElement): boolean {\n const state = row.getAttribute(\"data-upload-state\");\n return state === \"done\" || state === \"error\";\n }\n\n /** Re-arms `removeOnDone` for completed rows after a reconnect. */\n #rescheduleRemovals(): void {\n if (!this.removeOnDoneValue) return;\n this.#prune();\n for (const [id, row] of this.#rows) {\n if (row.getAttribute(\"data-upload-state\") === \"done\") {\n this.#timeouts.set(() => this.#removeRow(id), REMOVE_DELAY);\n }\n }\n }\n\n /** Returns the live row for `id`, creating (and labeling) one on first sight. */\n #rowFor(id: string | number | undefined, name: string): HTMLElement | null {\n const key = this.#key(id);\n const existing = this.#rows.get(key);\n if (existing !== undefined) {\n if (this.#tracksRow(existing)) {\n this.#applyName(existing, name);\n return existing;\n }\n // Removed, replaced, or no longer inside the current list: retire the\n // clone (removing it is a no-op when something else already did) and\n // rebuild from the live DOM.\n existing.remove();\n this.#rows.delete(key);\n }\n if (!this.hasRowTarget || !this.hasListTarget) return null;\n const clone = this.rowTarget.content.firstElementChild?.cloneNode(true);\n if (!(clone instanceof HTMLElement)) return null;\n this.#applyName(clone, name);\n clone.setAttribute(\"data-upload-state\", \"uploading\");\n this.#applyProgress(clone, 0);\n this.listTarget.appendChild(clone);\n this.#rows.set(key, clone);\n this.#syncAggregate();\n return clone;\n }\n\n /**\n * Writes the event's file name into `[data-field=\"name\"]` and, unless the row\n * already carries a non-blank `aria-label` — authored on the template or\n * applied by an earlier event — makes it the accessible name too. The visible\n * name never depends on the label: an authored label keeps its wording while\n * the field still shows which file this row tracks.\n */\n #applyName(row: HTMLElement, name: string): void {\n if (name.length === 0) return;\n this.#setField(row, \"name\", name);\n // A whitespace-only label computes to no accessible name, so only a\n // non-blank one counts as authored.\n if ((row.getAttribute(\"aria-label\") ?? \"\").trim().length > 0) return;\n row.setAttribute(\"aria-label\", name);\n }\n\n /** Writes one progress value to every per-row hook; returns the clamped percent. */\n #applyProgress(row: HTMLElement, percent: number): number {\n const clamped = Math.max(0, Math.min(100, Math.round(percent)));\n row.setAttribute(\"aria-valuenow\", String(clamped));\n row.setAttribute(\"aria-valuetext\", `${clamped}%`);\n row.style.setProperty(\"--stimeo--upload-progress\", `${clamped}%`);\n this.#setField(row, \"percent\", `${clamped}%`);\n return clamped;\n }\n\n #removeRow(id: string): void {\n const row = this.#rows.get(id);\n if (row === undefined) return;\n row.remove();\n this.#rows.delete(id);\n this.#syncAggregate();\n }\n\n /**\n * Reflects the average progress across live rows on the controller element,\n * withdrawing both hooks once no rows remain.\n */\n #syncAggregate(): void {\n this.#prune();\n if (this.#rows.size === 0) {\n this.element.removeAttribute(\"data-upload-progress\");\n this.element.style.removeProperty(\"--stimeo--upload-progress\");\n return;\n }\n let total = 0;\n for (const row of this.#rows.values()) {\n total += Number(row.getAttribute(\"aria-valuenow\") ?? \"0\");\n }\n const overall = Math.round(total / this.#rows.size);\n this.element.setAttribute(\"data-upload-progress\", String(overall));\n this.element.style.setProperty(\"--stimeo--upload-progress\", `${overall}%`);\n }\n\n /**\n * Whether a bookkept row is still this widget's live UI: connected, and — when\n * a `list` target is present — inside the *current* one, so re-pointing the\n * target attribute at a new element retires rows kept alive in the old list.\n */\n #tracksRow(row: HTMLElement): boolean {\n if (!row.isConnected) return false;\n return !this.hasListTarget || this.listTarget.contains(row);\n }\n\n /**\n * Retires rows that left the live UI (list swap, external removal). A retired\n * clone is removed outright — generated rows only ever live under the current\n * `list`, so the before-cache rewind never has an untracked leftover to miss.\n */\n #prune(): void {\n for (const [id, row] of this.#rows) {\n if (this.#tracksRow(row)) continue;\n row.remove();\n this.#rows.delete(id);\n }\n }\n\n /**\n * Returns the widget to its pre-upload state just before Turbo caches the\n * page, so the snapshot never replays rows for uploads that cannot resume.\n */\n /**\n * Rewinds for the snapshot and reports what that discarded. An upload in flight\n * cannot survive the navigation, so a consumer mirroring the rows would keep a\n * progress bar that never resolves.\n */\n #rewindForCache(): void {\n const ids = [...this.#rows.keys()];\n this.#reset();\n if (ids.length > 0) this.dispatch(\"reconcile\", { detail: { ids } });\n }\n\n #reset(): void {\n for (const row of this.#rows.values()) row.remove();\n this.#rows.clear();\n this.#timeouts.clearAll();\n this.#syncAggregate();\n }\n\n /**\n * Sends one consumer-worded message to the page's shared announcer. `{name}`\n * resolves to the row's displayed name first — the event that settles an\n * upload may omit the file although an earlier event already named the row —\n * then the event's own name, then the accessible name (which an authored\n * label owns, so it is the last resort, not the primary source).\n */\n #announce(template: string, name: string, row: HTMLElement): void {\n const stored = this.#field(row, \"name\")?.textContent ?? \"\";\n const label =\n stored.length > 0 ? stored : name.length > 0 ? name : (row.getAttribute(\"aria-label\") ?? \"\");\n announce(fillTemplate(template, { name: label }));\n }\n\n #field(row: HTMLElement, name: string): HTMLElement | null {\n return row.querySelector<HTMLElement>(`[data-field=\"${name}\"]`);\n }\n\n #setField(row: HTMLElement, name: string, text: string): void {\n const field = this.#field(row, name);\n if (field !== null) field.textContent = text;\n }\n\n #detail(event: Event): UploadDetail {\n return (event as CustomEvent<UploadDetail>).detail ?? {};\n }\n\n /** The file name every ActiveStorage `direct-upload:*` event carries. */\n #name(detail: UploadDetail): string {\n return detail.file?.name ?? \"\";\n }\n\n /**\n * Whether an event belongs to this controller. With `scope` set, only events\n * whose target (the file input) sits inside an element matching `scope` are\n * handled, so several upload widgets on one page do not cross-populate.\n * Resolved with `closest()` from the target itself, so the chatty `progress`\n * stream never pays a document-wide query. Empty `scope` handles all.\n */\n #inScope(event: Event): boolean {\n if (this.#scopeSelector.length === 0) return true;\n const target = event.target;\n return target instanceof Element && target.closest(this.#scopeSelector) !== null;\n }\n\n #key(id: string | number | undefined): string {\n return String(id ?? \"\");\n }\n}\n"]}
|
|
@@ -12,8 +12,7 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
12
12
|
* keydown->stimeo--editable#onDisplayKeydown">Current title</button>
|
|
13
13
|
* <input type="text" aria-label="Title" hidden
|
|
14
14
|
* data-stimeo--editable-target="input"
|
|
15
|
-
* data-action="keydown->stimeo--editable#onKeydown
|
|
16
|
-
* blur->stimeo--editable#onBlur" />
|
|
15
|
+
* data-action="keydown->stimeo--editable#onKeydown" />
|
|
17
16
|
* </div>
|
|
18
17
|
*
|
|
19
18
|
* There is no dedicated APG pattern; this implements a display ⇄ edit toggle with
|
|
@@ -31,10 +30,26 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
31
30
|
* `Enter` never saves (lifecycle-tracked, covering events that omit
|
|
32
31
|
* `isComposing`).
|
|
33
32
|
* - Losing focus while editing saves when `submitOnBlur` is true (the default),
|
|
34
|
-
* honoring wherever focus moved
|
|
33
|
+
* honoring wherever focus moved. The departure is watched on the controller
|
|
34
|
+
* element, so it is seen from wherever focus sat — the input, or a Save or
|
|
35
|
+
* Cancel button beside it — and no per-control wiring is required. Focus
|
|
36
|
+
* landing on another element inside this controller has not left the edit, so
|
|
37
|
+
* it commits nothing. When `submitOnBlur` is false, editing is kept.
|
|
38
|
+
* - `save()`, `cancel()`, and `revert()` are actions, so a pointer-only user
|
|
39
|
+
* reaches every path a keyboard user does. `revert()` restores the value from
|
|
40
|
+
* before the last save once, for a consumer whose server rejected it.
|
|
35
41
|
* - Saving dispatches `stimeo--editable:change` with `{ value, previous }` only
|
|
36
42
|
* when the value actually changed; cancelling dispatches
|
|
37
|
-
* `stimeo--editable:cancel
|
|
43
|
+
* `stimeo--editable:cancel` with an empty `{}` detail.
|
|
44
|
+
*
|
|
45
|
+
* The value is whatever the display element declares. A `data-value` attribute
|
|
46
|
+
* holds it when the element's text is a rendering of the value rather than the
|
|
47
|
+
* value itself — a formatted date, a grouped number, an icon beside a label.
|
|
48
|
+
* Without that attribute the trimmed text is the value, and it must then be a
|
|
49
|
+
* string the editing control accepts: `<input type="date">` keeps `2026-08-23`
|
|
50
|
+
* but sanitizes `August 23, 2026` away to an empty string. Saving updates
|
|
51
|
+
* whichever of the two carries the value, so a rendered display keeps its markup
|
|
52
|
+
* and the consumer re-renders it from the `change` event.
|
|
38
53
|
*/
|
|
39
54
|
declare class EditableController extends Controller<HTMLElement> {
|
|
40
55
|
#private;
|
|
@@ -45,7 +60,7 @@ declare class EditableController extends Controller<HTMLElement> {
|
|
|
45
60
|
default: boolean;
|
|
46
61
|
};
|
|
47
62
|
};
|
|
48
|
-
static actions: readonly ["
|
|
63
|
+
static actions: readonly ["cancel", "edit", "onDisplayKeydown", "onKeydown", "revert", "save"];
|
|
49
64
|
static events: readonly ["cancel", "change"];
|
|
50
65
|
readonly displayTarget: HTMLElement;
|
|
51
66
|
readonly inputTarget: HTMLInputElement | HTMLTextAreaElement;
|
|
@@ -54,20 +69,30 @@ declare class EditableController extends Controller<HTMLElement> {
|
|
|
54
69
|
submitOnBlurValue: boolean;
|
|
55
70
|
/** Establishes the initial display mode (display shown, input hidden). */
|
|
56
71
|
connect(): void;
|
|
57
|
-
/** Releases the composition listeners so nothing outlives the element. */
|
|
72
|
+
/** Releases the composition and focus listeners so nothing outlives the element. */
|
|
58
73
|
disconnect(): void;
|
|
59
74
|
/** Tracks an input added initially or after connect (e.g. a Turbo swap). */
|
|
60
75
|
inputTargetConnected(input: HTMLElement): void;
|
|
61
76
|
/** Removes composition listeners when the active input is replaced or removed. */
|
|
62
77
|
inputTargetDisconnected(input: HTMLElement): void;
|
|
63
|
-
/**
|
|
78
|
+
/** Re-hides or re-shows a display element that arrived after the mode was set. */
|
|
79
|
+
displayTargetConnected(): void;
|
|
80
|
+
/** Enters edit mode: seeds the input from the declared value, focuses, selects. */
|
|
64
81
|
edit(): void;
|
|
82
|
+
/** Commits the edit and returns focus to the display element. */
|
|
83
|
+
save(): void;
|
|
84
|
+
/** Discards edits, returns to display mode, and dispatches `cancel`. */
|
|
85
|
+
cancel(): void;
|
|
86
|
+
/**
|
|
87
|
+
* Puts back the value the last save replaced — for a consumer whose server
|
|
88
|
+
* rejected it. Silent by design: a `change` here would re-enter the same
|
|
89
|
+
* handler that asked for the undo. One save, one undo.
|
|
90
|
+
*/
|
|
91
|
+
revert(): void;
|
|
65
92
|
/** Adds `F2` as an editing entry point alongside the button's native activation. */
|
|
66
93
|
onDisplayKeydown(event: KeyboardEvent): void;
|
|
67
94
|
/** Commits on `Enter` (or `Ctrl+Enter` when multiline) and cancels on `Escape`. */
|
|
68
95
|
onKeydown(event: KeyboardEvent): void;
|
|
69
|
-
/** Saves on blur when `submitOnBlur` is set; otherwise keeps editing. */
|
|
70
|
-
onBlur(): void;
|
|
71
96
|
}
|
|
72
97
|
|
|
73
98
|
export { EditableController };
|
|
@@ -55,33 +55,64 @@ var EditableController = class extends Controller {
|
|
|
55
55
|
static values = {
|
|
56
56
|
submitOnBlur: { type: Boolean, default: true }
|
|
57
57
|
};
|
|
58
|
-
static actions = ["
|
|
58
|
+
static actions = ["cancel", "edit", "onDisplayKeydown", "onKeydown", "revert", "save"];
|
|
59
59
|
static events = ["cancel", "change"];
|
|
60
60
|
/** The value captured when edit mode began, used to detect real changes. */
|
|
61
61
|
#previousValue = "";
|
|
62
|
+
/**
|
|
63
|
+
* The value the last save replaced, or `null` when there is nothing to undo.
|
|
64
|
+
* Cleared on connect: a value from before a page restore is unrecoverable, so
|
|
65
|
+
* `revert()` must not resurrect one.
|
|
66
|
+
*/
|
|
67
|
+
#revertValue = null;
|
|
62
68
|
/**
|
|
63
69
|
* Owns IME lifecycle state for the edit surface, so a keydown that belongs to
|
|
64
70
|
* a composition (cancel or confirm) is never treated as an edit command.
|
|
65
71
|
*/
|
|
66
72
|
#composition = new CompositionTracker();
|
|
73
|
+
/**
|
|
74
|
+
* Watches focus leaving the editor from wherever it currently sits.
|
|
75
|
+
*
|
|
76
|
+
* `focusout` bubbles where `blur` does not, so one listener on the root sees
|
|
77
|
+
* every departure — including one from a Save or Cancel button the consumer
|
|
78
|
+
* placed beside the input. Binding the input alone would make the promise
|
|
79
|
+
* "saves wherever focus moved" true only for focus that leaves the input
|
|
80
|
+
* itself, and tabbing straight past an inner button would strand the editor
|
|
81
|
+
* open.
|
|
82
|
+
*/
|
|
83
|
+
#onFocusOut = (event) => {
|
|
84
|
+
const from = event.target;
|
|
85
|
+
if (this.hasDisplayTarget && from instanceof Node && this.displayTarget.contains(from)) return;
|
|
86
|
+
const next = event.relatedTarget;
|
|
87
|
+
if (next instanceof Node && this.element.contains(next)) return;
|
|
88
|
+
if (this.submitOnBlurValue) this.#commit(false);
|
|
89
|
+
};
|
|
67
90
|
/** Establishes the initial display mode (display shown, input hidden). */
|
|
68
91
|
connect() {
|
|
69
92
|
if (this.hasInputTarget) this.#composition.observe(this.inputTarget);
|
|
93
|
+
this.element.addEventListener("focusout", this.#onFocusOut);
|
|
94
|
+
this.#revertValue = null;
|
|
70
95
|
this.#setMode("display");
|
|
71
96
|
}
|
|
72
|
-
/** Releases the composition listeners so nothing outlives the element. */
|
|
97
|
+
/** Releases the composition and focus listeners so nothing outlives the element. */
|
|
73
98
|
disconnect() {
|
|
74
99
|
this.#composition.disconnect();
|
|
100
|
+
this.element.removeEventListener("focusout", this.#onFocusOut);
|
|
75
101
|
}
|
|
76
102
|
/** Tracks an input added initially or after connect (e.g. a Turbo swap). */
|
|
77
103
|
inputTargetConnected(input) {
|
|
78
104
|
this.#composition.observe(input);
|
|
105
|
+
this.#applyMode();
|
|
79
106
|
}
|
|
80
107
|
/** Removes composition listeners when the active input is replaced or removed. */
|
|
81
108
|
inputTargetDisconnected(input) {
|
|
82
109
|
this.#composition.unobserve(input);
|
|
83
110
|
}
|
|
84
|
-
/**
|
|
111
|
+
/** Re-hides or re-shows a display element that arrived after the mode was set. */
|
|
112
|
+
displayTargetConnected() {
|
|
113
|
+
this.#applyMode();
|
|
114
|
+
}
|
|
115
|
+
/** Enters edit mode: seeds the input from the declared value, focuses, selects. */
|
|
85
116
|
edit() {
|
|
86
117
|
if (this.#isEditing || !this.hasInputTarget || !this.hasDisplayTarget) return;
|
|
87
118
|
this.#previousValue = this.#currentValue;
|
|
@@ -90,6 +121,27 @@ var EditableController = class extends Controller {
|
|
|
90
121
|
this.inputTarget.focus();
|
|
91
122
|
this.inputTarget.select();
|
|
92
123
|
}
|
|
124
|
+
/** Commits the edit and returns focus to the display element. */
|
|
125
|
+
save() {
|
|
126
|
+
this.#commit(true);
|
|
127
|
+
}
|
|
128
|
+
/** Discards edits, returns to display mode, and dispatches `cancel`. */
|
|
129
|
+
cancel() {
|
|
130
|
+
if (!this.#isEditing) return;
|
|
131
|
+
this.#setMode("display");
|
|
132
|
+
if (this.hasDisplayTarget) this.displayTarget.focus();
|
|
133
|
+
this.dispatch("cancel", { detail: {} });
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Puts back the value the last save replaced — for a consumer whose server
|
|
137
|
+
* rejected it. Silent by design: a `change` here would re-enter the same
|
|
138
|
+
* handler that asked for the undo. One save, one undo.
|
|
139
|
+
*/
|
|
140
|
+
revert() {
|
|
141
|
+
if (this.#revertValue === null || this.#isEditing) return;
|
|
142
|
+
this.#writeValue(this.#revertValue);
|
|
143
|
+
this.#revertValue = null;
|
|
144
|
+
}
|
|
93
145
|
/** Adds `F2` as an editing entry point alongside the button's native activation. */
|
|
94
146
|
onDisplayKeydown(event) {
|
|
95
147
|
if (event.key === "F2") {
|
|
@@ -103,56 +155,57 @@ var EditableController = class extends Controller {
|
|
|
103
155
|
if (event.key === "Escape") {
|
|
104
156
|
if (event.defaultPrevented) return;
|
|
105
157
|
event.preventDefault();
|
|
106
|
-
this
|
|
158
|
+
this.cancel();
|
|
107
159
|
return;
|
|
108
160
|
}
|
|
109
161
|
if (event.key === "Enter") {
|
|
110
162
|
if (event.defaultPrevented) return;
|
|
111
163
|
if (this.#isMultiline && !(event.ctrlKey || event.metaKey)) return;
|
|
112
164
|
event.preventDefault();
|
|
113
|
-
this.#
|
|
165
|
+
this.#commit(true);
|
|
114
166
|
}
|
|
115
167
|
}
|
|
116
|
-
/** Saves on blur when `submitOnBlur` is set; otherwise keeps editing. */
|
|
117
|
-
onBlur() {
|
|
118
|
-
if (!this.#isEditing) return;
|
|
119
|
-
if (this.submitOnBlurValue) this.#save(false);
|
|
120
|
-
}
|
|
121
168
|
/**
|
|
122
|
-
* Returns to display mode,
|
|
123
|
-
*
|
|
169
|
+
* Returns to display mode, storing the input's value and dispatching `change`
|
|
170
|
+
* when it differs from where editing began.
|
|
124
171
|
*
|
|
125
172
|
* @param restoreFocus - Move focus back to the display element (explicit
|
|
126
|
-
*
|
|
173
|
+
* commit) rather than honoring the user's new focus target (blur).
|
|
127
174
|
*/
|
|
128
|
-
#
|
|
129
|
-
if (!this.#isEditing) return;
|
|
130
|
-
const value = this.inputTarget.value;
|
|
175
|
+
#commit(restoreFocus) {
|
|
176
|
+
if (!this.#isEditing || !this.hasInputTarget) return;
|
|
177
|
+
const value = this.inputTarget.value.trim();
|
|
131
178
|
const previous = this.#previousValue;
|
|
132
|
-
this
|
|
179
|
+
this.#writeValue(value);
|
|
133
180
|
this.#setMode("display");
|
|
134
|
-
if (restoreFocus) this.displayTarget.focus();
|
|
181
|
+
if (restoreFocus && this.hasDisplayTarget) this.displayTarget.focus();
|
|
135
182
|
if (value !== previous) {
|
|
183
|
+
this.#revertValue = previous;
|
|
136
184
|
this.dispatch("change", { detail: { value, previous } });
|
|
137
185
|
}
|
|
138
186
|
}
|
|
139
|
-
/**
|
|
140
|
-
#
|
|
141
|
-
if (!this
|
|
142
|
-
this
|
|
143
|
-
|
|
144
|
-
|
|
187
|
+
/** Stores `value` wherever the display element declares it. */
|
|
188
|
+
#writeValue(value) {
|
|
189
|
+
if (!this.hasDisplayTarget) return;
|
|
190
|
+
const display = this.displayTarget;
|
|
191
|
+
if (display.hasAttribute("data-value")) display.dataset.value = value;
|
|
192
|
+
else display.textContent = value;
|
|
145
193
|
}
|
|
146
|
-
/**
|
|
147
|
-
#
|
|
148
|
-
|
|
149
|
-
const editing = mode === "editing";
|
|
194
|
+
/** Derives both elements' visibility from the mode currently in the DOM. */
|
|
195
|
+
#applyMode() {
|
|
196
|
+
const editing = this.#isEditing;
|
|
150
197
|
if (this.hasDisplayTarget) this.displayTarget.hidden = editing;
|
|
151
198
|
if (this.hasInputTarget) this.inputTarget.hidden = !editing;
|
|
152
199
|
}
|
|
153
|
-
/**
|
|
200
|
+
/** Records the mode, then brings both elements in line with it. */
|
|
201
|
+
#setMode(mode) {
|
|
202
|
+
this.element.dataset.mode = mode;
|
|
203
|
+
this.#applyMode();
|
|
204
|
+
}
|
|
205
|
+
/** The value the display element declares, trimmed. */
|
|
154
206
|
get #currentValue() {
|
|
155
|
-
|
|
207
|
+
const display = this.displayTarget;
|
|
208
|
+
return (display.dataset.value ?? display.textContent ?? "").trim();
|
|
156
209
|
}
|
|
157
210
|
/** Whether the editing control is a multi-line `<textarea>`. */
|
|
158
211
|
get #isMultiline() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/composition_tracker.ts","../../src/controllers/editable_controller.ts"],"names":[],"mappings":";;;;;AAuCO,IAAM,qBAAN,MAAyB;AAAA,EACrB,gBAAA,uBAAuB,GAAA,EAAiB;AAAA,EACxC,cAAA,uBAAqB,GAAA,EAAiB;AAAA,EACtC,QAAA;AAAA,EACA,MAAA;AAAA,EAET,WAAA,CAAY,OAAA,GAAqC,EAAC,EAAG;AACnD,IAAA,IAAA,CAAK,WAAW,OAAA,CAAQ,OAAA;AACxB,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,KAAA;AAAA,EACxB;AAAA;AAAA,EAGA,QAAQ,MAAA,EAA2B;AACjC,IAAA,IAAI,IAAA,CAAK,gBAAA,CAAiB,GAAA,CAAI,MAAM,CAAA,EAAG;AACvC,IAAA,MAAA,CAAO,gBAAA,CAAiB,kBAAA,EAAoB,IAAA,CAAK,YAAY,CAAA;AAC7D,IAAA,MAAA,CAAO,gBAAA,CA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;AAAA,EACtC;AAAA;AAAA,EAGA,IAAI,UAAA,GAAsB;AACxB,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,OAAA,CAAQ,IAAA,KAAS,SAAA;AAAA,EACvC;AACF","file":"editable_controller.js","sourcesContent":["/** 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","import { Controller } from \"@hotwired/stimulus\";\nimport { CompositionTracker } from \"../utils/composition_tracker\";\n\n/**\n * Headless, accessible inline-editing behavior.\n *\n * Markup contract (identifier: `stimeo--editable`):\n * <div data-controller=\"stimeo--editable\"\n * data-stimeo--editable-submit-on-blur-value=\"true\">\n * <button type=\"button\" aria-label=\"Edit title\"\n * data-stimeo--editable-target=\"display\"\n * data-action=\"click->stimeo--editable#edit\n * keydown->stimeo--editable#onDisplayKeydown\">Current title</button>\n * <input type=\"text\" aria-label=\"Title\" hidden\n * data-stimeo--editable-target=\"input\"\n * data-action=\"keydown->stimeo--editable#onKeydown\n * blur->stimeo--editable#onBlur\" />\n * </div>\n *\n * There is no dedicated APG pattern; this implements a display ⇄ edit toggle with\n * focus management and keyboard commit/cancel, leaning on native form-control\n * labeling (WCAG 1.3.1 / 4.1.2). The look is the consumer's CSS, keyed off\n * `data-mode`.\n *\n * Behavior provided:\n * - Activating the display element (`Enter`/`Space` via the `<button>`, or `F2`)\n * enters edit mode, focuses the input, and selects its text.\n * - `Enter` (single-line) or `Ctrl+Enter` / `Cmd+Enter` (multiline `<textarea>`)\n * saves; `Escape` cancels. Both return focus to the display element. Keys\n * pressed during an IME composition act on the composition, never the edit:\n * a conversion-cancelling `Escape` keeps editing and a conversion-confirming\n * `Enter` never saves (lifecycle-tracked, covering events that omit\n * `isComposing`).\n * - Losing focus while editing saves when `submitOnBlur` is true (the default),\n * honoring wherever focus moved; when false, editing is kept.\n * - Saving dispatches `stimeo--editable:change` with `{ value, previous }` only\n * when the value actually changed; cancelling dispatches\n * `stimeo--editable:cancel`.\n */\nexport class EditableController extends Controller<HTMLElement> {\n static override targets = [\"display\", \"input\"];\n static override values = {\n submitOnBlur: { type: Boolean, default: true },\n };\n static actions = [\"edit\", \"onBlur\", \"onDisplayKeydown\", \"onKeydown\"] as const;\n static events = [\"cancel\", \"change\"] as const;\n\n declare readonly displayTarget: HTMLElement;\n declare readonly inputTarget: HTMLInputElement | HTMLTextAreaElement;\n declare readonly hasDisplayTarget: boolean;\n declare readonly hasInputTarget: boolean;\n\n declare submitOnBlurValue: boolean;\n\n /** The value captured when edit mode began, used to detect real changes. */\n #previousValue = \"\";\n\n /**\n * Owns IME lifecycle state for the edit surface, so a keydown that belongs to\n * a composition (cancel or confirm) is never treated as an edit command.\n */\n readonly #composition = new CompositionTracker();\n\n /** Establishes the initial display mode (display shown, input hidden). */\n override connect(): void {\n if (this.hasInputTarget) this.#composition.observe(this.inputTarget);\n this.#setMode(\"display\");\n }\n\n /** Releases the composition listeners so nothing outlives the element. */\n override disconnect(): void {\n this.#composition.disconnect();\n }\n\n /** Tracks an input added initially or after connect (e.g. a Turbo swap). */\n inputTargetConnected(input: HTMLElement): void {\n this.#composition.observe(input);\n }\n\n /** Removes composition listeners when the active input is replaced or removed. */\n inputTargetDisconnected(input: HTMLElement): void {\n this.#composition.unobserve(input);\n }\n\n /** Enters edit mode: seeds the input from the display text, focuses, selects. */\n edit(): void {\n if (this.#isEditing || !this.hasInputTarget || !this.hasDisplayTarget) return;\n this.#previousValue = this.#currentValue;\n this.inputTarget.value = this.#previousValue;\n this.#setMode(\"editing\");\n this.inputTarget.focus();\n this.inputTarget.select();\n }\n\n /** Adds `F2` as an editing entry point alongside the button's native activation. */\n onDisplayKeydown(event: KeyboardEvent): void {\n if (event.key === \"F2\") {\n event.preventDefault();\n this.edit();\n }\n }\n\n /** Commits on `Enter` (or `Ctrl+Enter` when multiline) and cancels on `Escape`. */\n onKeydown(event: KeyboardEvent): void {\n // Keys fired during IME composition steer the composition (cancel a\n // conversion, confirm a candidate) and must never cancel or save the edit.\n if (this.#composition.isComposing(event)) return;\n if (event.key === \"Escape\") {\n // Leave a press an inner handler already owned.\n if (event.defaultPrevented) return;\n event.preventDefault();\n this.#cancel();\n return;\n }\n if (event.key === \"Enter\") {\n // A descendant widget that already claimed the key (a completion popup\n // confirming its candidate) must not ALSO commit the edit — composition\n // depends on this yield. Kept separate from the Escape guard above, which\n // answers a different question: who owns an Escape press.\n if (event.defaultPrevented) return;\n // A bare Enter inserts a newline in a textarea; only Ctrl+Enter (or Cmd+Enter on\n // macOS, the platform-conventional commit chord) saves there.\n if (this.#isMultiline && !(event.ctrlKey || event.metaKey)) return;\n event.preventDefault();\n this.#save(true);\n }\n }\n\n /** Saves on blur when `submitOnBlur` is set; otherwise keeps editing. */\n onBlur(): void {\n if (!this.#isEditing) return;\n if (this.submitOnBlurValue) this.#save(false);\n }\n\n /**\n * Returns to display mode, reflecting the input into the display text and\n * dispatching `change` when the value differs from where editing began.\n *\n * @param restoreFocus - Move focus back to the display element (explicit\n * keyboard commit) rather than honoring the user's new focus target (blur).\n */\n #save(restoreFocus: boolean): void {\n if (!this.#isEditing) return;\n const value = this.inputTarget.value;\n const previous = this.#previousValue;\n this.displayTarget.textContent = value;\n this.#setMode(\"display\");\n if (restoreFocus) this.displayTarget.focus();\n if (value !== previous) {\n this.dispatch(\"change\", { detail: { value, previous } });\n }\n }\n\n /** Discards edits, returns to display mode, and dispatches `cancel`. */\n #cancel(): void {\n if (!this.#isEditing) return;\n this.#setMode(\"display\");\n this.displayTarget.focus();\n this.dispatch(\"cancel\", { detail: {} });\n }\n\n /** Toggles the `data-mode` flag and the `hidden` state of both elements. */\n #setMode(mode: \"display\" | \"editing\"): void {\n this.element.dataset.mode = mode;\n const editing = mode === \"editing\";\n if (this.hasDisplayTarget) this.displayTarget.hidden = editing;\n if (this.hasInputTarget) this.inputTarget.hidden = !editing;\n }\n\n /** Current display text, trimmed — the value shown when not editing. */\n get #currentValue(): string {\n return (this.displayTarget.textContent ?? \"\").trim();\n }\n\n /** Whether the editing control is a multi-line `<textarea>`. */\n get #isMultiline(): boolean {\n return this.inputTarget.tagName === \"TEXTAREA\";\n }\n\n /** Whether the controller is currently in edit mode. */\n get #isEditing(): boolean {\n return this.element.dataset.mode === \"editing\";\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/composition_tracker.ts","../../src/controllers/editable_controller.ts"],"names":[],"mappings":";;;;;AAuCO,IAAM,qBAAN,MAAyB;AAAA,EACrB,gBAAA,uBAAuB,GAAA,EAAiB;AAAA,EACxC,cAAA,uBAAqB,GAAA,EAAiB;AAAA,EACtC,QAAA;AAAA,EACA,MAAA;AAAA,EAET,WAAA,CAAY,OAAA,GAAqC,EAAC,EAAG;AACnD,IAAA,IAAA,CAAK,WAAW,OAAA,CAAQ,OAAA;AACxB,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,KAAA;AAAA,EACxB;AAAA;AAAA,EAGA,QAAQ,MAAA,EAA2B;AACjC,IAAA,IAAI,IAAA,CAAK,gBAAA,CAAiB,GAAA,CAAI,MAAM,CAAA,EAAG;AACvC,IAAA,MAAA,CAAO,gBAAA,CAAiB,kBAAA,EAAoB,IAAA,CAAK,YAAY,CAAA;AAC7D,IAAA,MAAA,CAAO,gBAAA,CAAiB,gBAAA,EAAkB,IAAA,CAAK,UAAU,CAAA;AACzD,IAAA,IAAA,CAAK,gBAAA,CAAiB,IAAI,MAAM,CAAA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AAW;AAAA,EAClB;AAAA;AAAA,EAGA,IAAI,aAAA,GAAwB;AAC1B,IAAA,MAAM,UAAU,IAAA,CAAK,aAAA;AACrB,IAAA,OAAA,CAAQ,QAAQ,OAAA,CAAQ,KAAA,IAAS,OAAA,CAAQ,WAAA,IAAe,IAAI,IAAA,EAAK;AAAA,EACnE;AAAA;AAAA,EAGA,IAAI,YAAA,GAAwB;AAC1B,IAAA,OAAO,IAAA,CAAK,YAAY,OAAA,KAAY,UAAA;AAAA,EACtC;AAAA;AAAA,EAGA,IAAI,UAAA,GAAsB;AACxB,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,OAAA,CAAQ,IAAA,KAAS,SAAA;AAAA,EACvC;AACF","file":"editable_controller.js","sourcesContent":["/** 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","import { Controller } from \"@hotwired/stimulus\";\nimport { CompositionTracker } from \"../utils/composition_tracker\";\n\n/**\n * Headless, accessible inline-editing behavior.\n *\n * Markup contract (identifier: `stimeo--editable`):\n * <div data-controller=\"stimeo--editable\"\n * data-stimeo--editable-submit-on-blur-value=\"true\">\n * <button type=\"button\" aria-label=\"Edit title\"\n * data-stimeo--editable-target=\"display\"\n * data-action=\"click->stimeo--editable#edit\n * keydown->stimeo--editable#onDisplayKeydown\">Current title</button>\n * <input type=\"text\" aria-label=\"Title\" hidden\n * data-stimeo--editable-target=\"input\"\n * data-action=\"keydown->stimeo--editable#onKeydown\" />\n * </div>\n *\n * There is no dedicated APG pattern; this implements a display ⇄ edit toggle with\n * focus management and keyboard commit/cancel, leaning on native form-control\n * labeling (WCAG 1.3.1 / 4.1.2). The look is the consumer's CSS, keyed off\n * `data-mode`.\n *\n * Behavior provided:\n * - Activating the display element (`Enter`/`Space` via the `<button>`, or `F2`)\n * enters edit mode, focuses the input, and selects its text.\n * - `Enter` (single-line) or `Ctrl+Enter` / `Cmd+Enter` (multiline `<textarea>`)\n * saves; `Escape` cancels. Both return focus to the display element. Keys\n * pressed during an IME composition act on the composition, never the edit:\n * a conversion-cancelling `Escape` keeps editing and a conversion-confirming\n * `Enter` never saves (lifecycle-tracked, covering events that omit\n * `isComposing`).\n * - Losing focus while editing saves when `submitOnBlur` is true (the default),\n * honoring wherever focus moved. The departure is watched on the controller\n * element, so it is seen from wherever focus sat — the input, or a Save or\n * Cancel button beside it — and no per-control wiring is required. Focus\n * landing on another element inside this controller has not left the edit, so\n * it commits nothing. When `submitOnBlur` is false, editing is kept.\n * - `save()`, `cancel()`, and `revert()` are actions, so a pointer-only user\n * reaches every path a keyboard user does. `revert()` restores the value from\n * before the last save once, for a consumer whose server rejected it.\n * - Saving dispatches `stimeo--editable:change` with `{ value, previous }` only\n * when the value actually changed; cancelling dispatches\n * `stimeo--editable:cancel` with an empty `{}` detail.\n *\n * The value is whatever the display element declares. A `data-value` attribute\n * holds it when the element's text is a rendering of the value rather than the\n * value itself — a formatted date, a grouped number, an icon beside a label.\n * Without that attribute the trimmed text is the value, and it must then be a\n * string the editing control accepts: `<input type=\"date\">` keeps `2026-08-23`\n * but sanitizes `August 23, 2026` away to an empty string. Saving updates\n * whichever of the two carries the value, so a rendered display keeps its markup\n * and the consumer re-renders it from the `change` event.\n */\nexport class EditableController extends Controller<HTMLElement> {\n static override targets = [\"display\", \"input\"];\n static override values = {\n submitOnBlur: { type: Boolean, default: true },\n };\n static actions = [\"cancel\", \"edit\", \"onDisplayKeydown\", \"onKeydown\", \"revert\", \"save\"] as const;\n static events = [\"cancel\", \"change\"] as const;\n\n declare readonly displayTarget: HTMLElement;\n declare readonly inputTarget: HTMLInputElement | HTMLTextAreaElement;\n declare readonly hasDisplayTarget: boolean;\n declare readonly hasInputTarget: boolean;\n\n declare submitOnBlurValue: boolean;\n\n /** The value captured when edit mode began, used to detect real changes. */\n #previousValue = \"\";\n\n /**\n * The value the last save replaced, or `null` when there is nothing to undo.\n * Cleared on connect: a value from before a page restore is unrecoverable, so\n * `revert()` must not resurrect one.\n */\n #revertValue: string | null = null;\n\n /**\n * Owns IME lifecycle state for the edit surface, so a keydown that belongs to\n * a composition (cancel or confirm) is never treated as an edit command.\n */\n readonly #composition = new CompositionTracker();\n\n /**\n * Watches focus leaving the editor from wherever it currently sits.\n *\n * `focusout` bubbles where `blur` does not, so one listener on the root sees\n * every departure — including one from a Save or Cancel button the consumer\n * placed beside the input. Binding the input alone would make the promise\n * \"saves wherever focus moved\" true only for focus that leaves the input\n * itself, and tabbing straight past an inner button would strand the editor\n * open.\n */\n readonly #onFocusOut = (event: FocusEvent): void => {\n // Entering edit mode hides the display element, and hiding the element that\n // holds focus reports a departure with nowhere to go. That hand-off is the\n // edit starting, not the user leaving it, and the input is focused moments\n // later in the same task. The display is hidden for the whole edit, so it\n // can never be the source of a real departure from one.\n const from = event.target;\n if (this.hasDisplayTarget && from instanceof Node && this.displayTarget.contains(from)) return;\n // Focus reaching another element inside this controller has not left the\n // edit. Without this the commit would beat an inner button's own click —\n // and a Cancel button would save what it promises to discard.\n const next = event.relatedTarget;\n if (next instanceof Node && this.element.contains(next)) return;\n if (this.submitOnBlurValue) this.#commit(false);\n };\n\n /** Establishes the initial display mode (display shown, input hidden). */\n override connect(): void {\n // The tracker is idempotent, so observing here and in the target callback\n // keeps IME tracking correct whichever of the two the framework runs first.\n if (this.hasInputTarget) this.#composition.observe(this.inputTarget);\n this.element.addEventListener(\"focusout\", this.#onFocusOut);\n this.#revertValue = null;\n this.#setMode(\"display\");\n }\n\n /** Releases the composition and focus listeners so nothing outlives the element. */\n override disconnect(): void {\n this.#composition.disconnect();\n this.element.removeEventListener(\"focusout\", this.#onFocusOut);\n }\n\n /** Tracks an input added initially or after connect (e.g. a Turbo swap). */\n inputTargetConnected(input: HTMLElement): void {\n this.#composition.observe(input);\n this.#applyMode();\n }\n\n /** Removes composition listeners when the active input is replaced or removed. */\n inputTargetDisconnected(input: HTMLElement): void {\n this.#composition.unobserve(input);\n }\n\n /** Re-hides or re-shows a display element that arrived after the mode was set. */\n displayTargetConnected(): void {\n this.#applyMode();\n }\n\n /** Enters edit mode: seeds the input from the declared value, focuses, selects. */\n edit(): void {\n if (this.#isEditing || !this.hasInputTarget || !this.hasDisplayTarget) return;\n this.#previousValue = this.#currentValue;\n this.inputTarget.value = this.#previousValue;\n this.#setMode(\"editing\");\n this.inputTarget.focus();\n this.inputTarget.select();\n }\n\n /** Commits the edit and returns focus to the display element. */\n save(): void {\n this.#commit(true);\n }\n\n /** Discards edits, returns to display mode, and dispatches `cancel`. */\n cancel(): void {\n if (!this.#isEditing) return;\n this.#setMode(\"display\");\n if (this.hasDisplayTarget) this.displayTarget.focus();\n this.dispatch(\"cancel\", { detail: {} });\n }\n\n /**\n * Puts back the value the last save replaced — for a consumer whose server\n * rejected it. Silent by design: a `change` here would re-enter the same\n * handler that asked for the undo. One save, one undo.\n */\n revert(): void {\n if (this.#revertValue === null || this.#isEditing) return;\n this.#writeValue(this.#revertValue);\n this.#revertValue = null;\n }\n\n /** Adds `F2` as an editing entry point alongside the button's native activation. */\n onDisplayKeydown(event: KeyboardEvent): void {\n if (event.key === \"F2\") {\n event.preventDefault();\n this.edit();\n }\n }\n\n /** Commits on `Enter` (or `Ctrl+Enter` when multiline) and cancels on `Escape`. */\n onKeydown(event: KeyboardEvent): void {\n // Keys fired during IME composition steer the composition (cancel a\n // conversion, confirm a candidate) and must never cancel or save the edit.\n if (this.#composition.isComposing(event)) return;\n if (event.key === \"Escape\") {\n // Leave a press an inner handler already owned.\n if (event.defaultPrevented) return;\n event.preventDefault();\n this.cancel();\n return;\n }\n if (event.key === \"Enter\") {\n // A descendant widget that already claimed the key (a completion popup\n // confirming its candidate) must not ALSO commit the edit — composition\n // depends on this yield. Kept separate from the Escape guard above, which\n // answers a different question: who owns an Escape press.\n if (event.defaultPrevented) return;\n // A bare Enter inserts a newline in a textarea; only Ctrl+Enter (or Cmd+Enter on\n // macOS, the platform-conventional commit chord) saves there.\n if (this.#isMultiline && !(event.ctrlKey || event.metaKey)) return;\n event.preventDefault();\n this.#commit(true);\n }\n }\n\n /**\n * Returns to display mode, storing the input's value and dispatching `change`\n * when it differs from where editing began.\n *\n * @param restoreFocus - Move focus back to the display element (explicit\n * commit) rather than honoring the user's new focus target (blur).\n */\n #commit(restoreFocus: boolean): void {\n if (!this.#isEditing || !this.hasInputTarget) return;\n // One normalization for all three consumers below, so the stored value, the\n // comparison, and the detail can never disagree about what was saved.\n const value = this.inputTarget.value.trim();\n const previous = this.#previousValue;\n this.#writeValue(value);\n this.#setMode(\"display\");\n if (restoreFocus && this.hasDisplayTarget) this.displayTarget.focus();\n if (value !== previous) {\n this.#revertValue = previous;\n this.dispatch(\"change\", { detail: { value, previous } });\n }\n }\n\n /** Stores `value` wherever the display element declares it. */\n #writeValue(value: string): void {\n if (!this.hasDisplayTarget) return;\n const display = this.displayTarget;\n // Text that renders the value is the consumer's to compose; overwriting it\n // with the raw value would destroy a rendering this controller cannot rebuild.\n if (display.hasAttribute(\"data-value\")) display.dataset.value = value;\n else display.textContent = value;\n }\n\n /** Derives both elements' visibility from the mode currently in the DOM. */\n #applyMode(): void {\n const editing = this.#isEditing;\n if (this.hasDisplayTarget) this.displayTarget.hidden = editing;\n if (this.hasInputTarget) this.inputTarget.hidden = !editing;\n }\n\n /** Records the mode, then brings both elements in line with it. */\n #setMode(mode: \"display\" | \"editing\"): void {\n this.element.dataset.mode = mode;\n this.#applyMode();\n }\n\n /** The value the display element declares, trimmed. */\n get #currentValue(): string {\n const display = this.displayTarget;\n return (display.dataset.value ?? display.textContent ?? \"\").trim();\n }\n\n /** Whether the editing control is a multi-line `<textarea>`. */\n get #isMultiline(): boolean {\n return this.inputTarget.tagName === \"TEXTAREA\";\n }\n\n /** Whether the controller is currently in edit mode. */\n get #isEditing(): boolean {\n return this.element.dataset.mode === \"editing\";\n }\n}\n"]}
|