stimeo-ui 0.2.1 → 0.3.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 +104 -0
- package/dist/cable/index.d.ts +16 -16
- package/dist/cable/index.js.map +1 -1
- package/dist/controllers/accordion_controller.js +10 -0
- package/dist/controllers/accordion_controller.js.map +1 -1
- package/dist/controllers/alert_dialog_controller.js.map +1 -1
- package/dist/controllers/breadcrumb_controller.d.ts +97 -10
- package/dist/controllers/breadcrumb_controller.js +225 -13
- package/dist/controllers/breadcrumb_controller.js.map +1 -1
- package/dist/controllers/calendar_controller.d.ts +11 -1
- package/dist/controllers/calendar_controller.js +89 -22
- package/dist/controllers/calendar_controller.js.map +1 -1
- package/dist/controllers/carousel_controller.d.ts +16 -1
- package/dist/controllers/carousel_controller.js +47 -6
- package/dist/controllers/carousel_controller.js.map +1 -1
- package/dist/controllers/collapsible_controller.js +2 -2
- package/dist/controllers/collapsible_controller.js.map +1 -1
- package/dist/controllers/color_picker_controller.d.ts +12 -1
- package/dist/controllers/color_picker_controller.js +46 -7
- package/dist/controllers/color_picker_controller.js.map +1 -1
- package/dist/controllers/combobox_controller.d.ts +14 -1
- package/dist/controllers/combobox_controller.js +162 -23
- package/dist/controllers/combobox_controller.js.map +1 -1
- package/dist/controllers/command_palette_controller.d.ts +2 -0
- package/dist/controllers/command_palette_controller.js +194 -17
- package/dist/controllers/command_palette_controller.js.map +1 -1
- package/dist/controllers/confirm_controller.js.map +1 -1
- package/dist/controllers/context_menu_controller.d.ts +7 -6
- package/dist/controllers/context_menu_controller.js +32 -10
- package/dist/controllers/context_menu_controller.js.map +1 -1
- package/dist/controllers/count_up_controller.js.map +1 -1
- package/dist/controllers/data_grid_controller.d.ts +19 -1
- package/dist/controllers/data_grid_controller.js +82 -4
- package/dist/controllers/data_grid_controller.js.map +1 -1
- package/dist/controllers/date_range_picker_controller.d.ts +1 -0
- package/dist/controllers/date_range_picker_controller.js +27 -3
- package/dist/controllers/date_range_picker_controller.js.map +1 -1
- package/dist/controllers/dialog_controller.js.map +1 -1
- package/dist/controllers/dismissible_controller.js.map +1 -1
- package/dist/controllers/drawer_controller.js.map +1 -1
- package/dist/controllers/dropdown_controller.d.ts +1 -2
- package/dist/controllers/dropdown_controller.js.map +1 -1
- package/dist/controllers/editable_controller.js +1 -0
- package/dist/controllers/editable_controller.js.map +1 -1
- package/dist/controllers/focus_controller.d.ts +1 -1
- package/dist/controllers/focus_controller.js.map +1 -1
- package/dist/controllers/form_field_controller.js.map +1 -1
- package/dist/controllers/form_validation_controller.js +1 -1
- package/dist/controllers/form_validation_controller.js.map +1 -1
- package/dist/controllers/highlight_controller.js.map +1 -1
- package/dist/controllers/hover_card_controller.d.ts +1 -1
- package/dist/controllers/hover_card_controller.js.map +1 -1
- package/dist/controllers/intersection_controller.js +36 -11
- package/dist/controllers/intersection_controller.js.map +1 -1
- package/dist/controllers/lazy_frame_controller.js +31 -10
- package/dist/controllers/lazy_frame_controller.js.map +1 -1
- package/dist/controllers/listbox_controller.d.ts +9 -2
- package/dist/controllers/listbox_controller.js +257 -53
- package/dist/controllers/listbox_controller.js.map +1 -1
- package/dist/controllers/local_time_controller.js +2 -2
- package/dist/controllers/local_time_controller.js.map +1 -1
- package/dist/controllers/menu_controller.d.ts +29 -11
- package/dist/controllers/menu_controller.js +104 -17
- package/dist/controllers/menu_controller.js.map +1 -1
- package/dist/controllers/menubar_controller.d.ts +91 -11
- package/dist/controllers/menubar_controller.js +415 -63
- package/dist/controllers/menubar_controller.js.map +1 -1
- package/dist/controllers/meter_controller.js.map +1 -1
- package/dist/controllers/multi_select_controller.d.ts +31 -5
- package/dist/controllers/multi_select_controller.js +312 -29
- package/dist/controllers/multi_select_controller.js.map +1 -1
- package/dist/controllers/navigation_menu_controller.d.ts +65 -18
- package/dist/controllers/navigation_menu_controller.js +154 -27
- package/dist/controllers/navigation_menu_controller.js.map +1 -1
- package/dist/controllers/nested_form_controller.d.ts +4 -5
- package/dist/controllers/nested_form_controller.js.map +1 -1
- package/dist/controllers/number_input_controller.d.ts +1 -1
- package/dist/controllers/number_input_controller.js +7 -0
- package/dist/controllers/number_input_controller.js.map +1 -1
- package/dist/controllers/otp_controller.js +18 -1
- package/dist/controllers/otp_controller.js.map +1 -1
- package/dist/controllers/overflow_indicator_controller.d.ts +3 -2
- package/dist/controllers/overflow_indicator_controller.js +81 -13
- package/dist/controllers/overflow_indicator_controller.js.map +1 -1
- package/dist/controllers/overflow_menu_controller.d.ts +78 -19
- package/dist/controllers/overflow_menu_controller.js +381 -57
- package/dist/controllers/overflow_menu_controller.js.map +1 -1
- package/dist/controllers/pagination_controller.d.ts +36 -5
- package/dist/controllers/pagination_controller.js +163 -32
- package/dist/controllers/pagination_controller.js.map +1 -1
- package/dist/controllers/persist_controller.js +6 -6
- package/dist/controllers/persist_controller.js.map +1 -1
- package/dist/controllers/pointer_drag_controller.d.ts +2 -3
- package/dist/controllers/pointer_drag_controller.js +9 -1
- package/dist/controllers/pointer_drag_controller.js.map +1 -1
- package/dist/controllers/popover_controller.d.ts +1 -2
- package/dist/controllers/popover_controller.js +2 -2
- package/dist/controllers/popover_controller.js.map +1 -1
- package/dist/controllers/portal_controller.d.ts +4 -4
- package/dist/controllers/portal_controller.js.map +1 -1
- package/dist/controllers/progress_controller.js.map +1 -1
- package/dist/controllers/radio_group_controller.js +22 -3
- package/dist/controllers/radio_group_controller.js.map +1 -1
- package/dist/controllers/range_slider_controller.d.ts +14 -4
- package/dist/controllers/range_slider_controller.js +32 -6
- package/dist/controllers/range_slider_controller.js.map +1 -1
- package/dist/controllers/rating_controller.js +16 -2
- package/dist/controllers/rating_controller.js.map +1 -1
- package/dist/controllers/read_more_controller.js +63 -19
- package/dist/controllers/read_more_controller.js.map +1 -1
- package/dist/controllers/reading_progress_controller.js.map +1 -1
- package/dist/controllers/resizable_controller.d.ts +3 -1
- package/dist/controllers/resizable_controller.js +65 -1
- package/dist/controllers/resizable_controller.js.map +1 -1
- package/dist/controllers/roving_controller.js +17 -2
- package/dist/controllers/roving_controller.js.map +1 -1
- package/dist/controllers/scroll_area_controller.js +86 -12
- package/dist/controllers/scroll_area_controller.js.map +1 -1
- package/dist/controllers/scroll_restore_controller.js +1 -1
- package/dist/controllers/scroll_restore_controller.js.map +1 -1
- package/dist/controllers/scroll_visibility_controller.d.ts +6 -3
- package/dist/controllers/scroll_visibility_controller.js +33 -3
- package/dist/controllers/scroll_visibility_controller.js.map +1 -1
- package/dist/controllers/scrollspy_controller.d.ts +64 -15
- package/dist/controllers/scrollspy_controller.js +346 -73
- package/dist/controllers/scrollspy_controller.js.map +1 -1
- package/dist/controllers/separator_controller.d.ts +20 -5
- package/dist/controllers/separator_controller.js +9 -0
- package/dist/controllers/separator_controller.js.map +1 -1
- package/dist/controllers/sidebar_controller.d.ts +1 -1
- package/dist/controllers/sidebar_controller.js.map +1 -1
- package/dist/controllers/skeleton_controller.js +1 -1
- package/dist/controllers/skeleton_controller.js.map +1 -1
- package/dist/controllers/slider_controller.d.ts +11 -1
- package/dist/controllers/slider_controller.js +32 -6
- package/dist/controllers/slider_controller.js.map +1 -1
- package/dist/controllers/sortable_controller.d.ts +3 -1
- package/dist/controllers/sortable_controller.js +34 -3
- package/dist/controllers/sortable_controller.js.map +1 -1
- package/dist/controllers/spinner_controller.js +1 -1
- package/dist/controllers/spinner_controller.js.map +1 -1
- package/dist/controllers/stick_to_bottom_controller.d.ts +5 -6
- package/dist/controllers/stick_to_bottom_controller.js +2 -1
- package/dist/controllers/stick_to_bottom_controller.js.map +1 -1
- package/dist/controllers/sticky_observer_controller.js +32 -11
- package/dist/controllers/sticky_observer_controller.js.map +1 -1
- package/dist/controllers/submit_once_controller.d.ts +2 -2
- package/dist/controllers/submit_once_controller.js.map +1 -1
- package/dist/controllers/switch_controller.js +1 -0
- package/dist/controllers/switch_controller.js.map +1 -1
- package/dist/controllers/tabs_controller.d.ts +11 -3
- package/dist/controllers/tabs_controller.js +26 -3
- package/dist/controllers/tabs_controller.js.map +1 -1
- package/dist/controllers/tags_input_controller.js +22 -2
- package/dist/controllers/tags_input_controller.js.map +1 -1
- package/dist/controllers/theme_controller.d.ts +1 -1
- package/dist/controllers/theme_controller.js +22 -3
- package/dist/controllers/theme_controller.js.map +1 -1
- package/dist/controllers/time_picker_controller.js +20 -1
- package/dist/controllers/time_picker_controller.js.map +1 -1
- package/dist/controllers/toast_controller.d.ts +4 -5
- package/dist/controllers/toast_controller.js +4 -5
- package/dist/controllers/toast_controller.js.map +1 -1
- package/dist/controllers/toggle_group_controller.js +23 -2
- package/dist/controllers/toggle_group_controller.js.map +1 -1
- package/dist/controllers/toolbar_controller.d.ts +53 -13
- package/dist/controllers/toolbar_controller.js +230 -31
- package/dist/controllers/toolbar_controller.js.map +1 -1
- package/dist/controllers/tooltip_controller.d.ts +1 -1
- package/dist/controllers/tooltip_controller.js.map +1 -1
- package/dist/controllers/transition_controller.js.map +1 -1
- package/dist/controllers/tree_view_controller.d.ts +87 -6
- package/dist/controllers/tree_view_controller.js +467 -51
- package/dist/controllers/tree_view_controller.js.map +1 -1
- package/dist/index.js +3514 -689
- package/dist/index.js.map +1 -1
- package/dist/inspector/cli.d.ts +375 -39
- package/dist/inspector/cli.js +228 -14
- package/dist/inspector/cli.js.map +1 -1
- package/dist/inspector/cli_bin.js +419 -48
- package/dist/inspector/cli_bin.js.map +1 -1
- package/dist/inspector/examples.json +24 -24
- package/dist/inspector/manifest.json +1040 -125
- package/package.json +5 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/controllers/pagination_controller.ts"],"names":[],"mappings":";;;AAoCO,IAAM,oBAAA,GAAN,cAAmC,UAAA,CAAwB;AAAA,EAChE,OAAgB,OAAA,GAAU,CAAC,MAAA,EAAQ,QAAQ,MAAM,CAAA;AAAA,EACjD,OAAgB,MAAA,GAAS;AAAA,IACvB,IAAA,EAAM,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,CAAA,EAAE;AAAA,IAC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,MAAA,IAAA,CAAK,mBAAmB,MAAM,CAAA;AAAA,IAChC;AACA,IAAA,MAAA,CAAO,QAAA,GAAW,QAAA;AAAA,EACpB;AAAA;AAAA,EAGA,mBAAmB,MAAA,EAAiC;AAClD,IAAA,MAAM,QAAA,GACJ,MAAA,MAAY,IAAA,CAAK,aAAA,GAAgB,KAAK,UAAA,GAAa,IAAA,CAAA,GAC/C,IAAA,CAAK,aAAA,GACH,KAAK,UAAA,GACL,IAAA,GACF,IAAA,CAAK,aAAA,GACH,KAAK,UAAA,GACL,IAAA;AACR,IAAA,MAAM,WAAA,GAAc,KAAK,WAAA,CAAY,IAAA;AAAA,MACnC,CAAC,SAAA,KAAc,MAAA,CAAO,UAAU,OAAA,CAAQ,IAAI,MAAM,IAAA,CAAK;AAAA,KACzD;AACA,IAAA,MAAM,WAAA,GAAc,QAAA,IAAY,CAAC,QAAA,CAAS,WAAW,QAAA,GAAW,WAAA;AAChE,IAAA,IAAI,WAAA,EAAa;AACf,MAAA,WAAA,CAAY,KAAA,EAAM;AAClB,MAAA;AAAA,IACF;AAKA,IAAA,IAAI,CAAC,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,UAAU,GAAG,IAAA,CAAK,OAAA,CAAQ,YAAA,CAAa,UAAA,EAAY,IAAI,CAAA;AACtF,IAAA,IAAA,CAAK,QAAQ,KAAA,EAAM;AAAA,EACrB;AACF","file":"pagination_controller.js","sourcesContent":["import { Controller } from \"@hotwired/stimulus\";\n\n/**\n * Headless, accessible pagination behavior.\n *\n * Markup contract (identifier: `stimeo--pagination`):\n * <nav data-controller=\"stimeo--pagination\" aria-label=\"Pagination\"\n * data-stimeo--pagination-page-value=\"1\"\n * data-stimeo--pagination-total-value=\"5\">\n * <button type=\"button\" data-stimeo--pagination-target=\"prev\"\n * data-action=\"stimeo--pagination#prev\">Prev</button>\n * <button type=\"button\" data-page=\"1\" aria-current=\"page\"\n * data-stimeo--pagination-target=\"page\"\n * data-action=\"stimeo--pagination#select\">1</button>\n * <!-- more page buttons -->\n * <button type=\"button\" data-stimeo--pagination-target=\"next\"\n * data-action=\"stimeo--pagination#next\">Next</button>\n * </nav>\n *\n * There is no dedicated APG pattern; this uses a navigation landmark plus\n * `aria-current=\"page\"`. The controller owns current-page state, the\n * `aria-current` sync, boundary disabling of prev/next, and the change event.\n * Generating/eliding the page buttons and fetching data stay with the consumer.\n *\n * @remarks\n * Behavior only — each control is in the natural Tab order (no roving). When a\n * boundary disables the button that currently has focus, focus is moved first so\n * it is never lost to a `disabled` element.\n *\n * Behavior provided:\n * - `select` reads the clicked button's `data-page` and makes it current.\n * - `prev`/`next` step by one, clamped to `[1, total]`.\n * - The current page button gets `aria-current=\"page\"` (removed from the rest);\n * `prev` is `disabled` at page 1 and `next` at `total`.\n * - Every change dispatches `stimeo--pagination:change`.\n */\nexport class PaginationController extends Controller<HTMLElement> {\n static override targets = [\"page\", \"prev\", \"next\"];\n static override values = {\n page: { type: Number, default: 1 },\n total: { type: Number, default: 1 },\n };\n static actions = [\"next\", \"prev\", \"select\"] as const;\n static events = [\"change\"] as const;\n\n declare readonly pageTargets: HTMLElement[];\n declare readonly prevTarget: HTMLButtonElement;\n declare readonly nextTarget: HTMLButtonElement;\n declare readonly hasPrevTarget: boolean;\n declare readonly hasNextTarget: boolean;\n declare pageValue: number;\n declare totalValue: number;\n\n /** Normalizes out-of-range initial values and renders the initial state. */\n override connect(): void {\n this.totalValue = Math.max(1, Math.trunc(this.totalValue));\n this.pageValue = Math.min(this.totalValue, Math.max(1, Math.trunc(this.pageValue)));\n this.#render();\n }\n\n /** Makes the clicked page button (its `data-page`) current. */\n select(event: Event): void {\n const button = event.currentTarget as HTMLElement;\n const page = Number(button.dataset.page);\n if (!Number.isFinite(page)) return;\n this.#goto(page);\n }\n\n /** Steps to the previous page. */\n prev(): void {\n this.#goto(this.pageValue - 1);\n }\n\n /** Steps to the next page. */\n next(): void {\n this.#goto(this.pageValue + 1);\n }\n\n /** Moves to `page` (clamped to `[1, total]`), re-renders, and dispatches `change`. */\n #goto(page: number): void {\n // Normalize total first so a stray total<=0 can't clamp the 1-based page to 0.\n const total = Math.max(1, Math.trunc(this.totalValue));\n const target = Math.min(total, Math.max(1, Math.trunc(page)));\n if (target === this.pageValue) return;\n const previous = this.pageValue;\n this.pageValue = target;\n this.#render();\n this.dispatch(\"change\", {\n detail: { page: target, total: this.totalValue, previous },\n });\n }\n\n /** Syncs `aria-current` on the page buttons and the prev/next `disabled` state. */\n #render(): void {\n for (const button of this.pageTargets) {\n if (Number(button.dataset.page) === this.pageValue) {\n button.setAttribute(\"aria-current\", \"page\");\n } else {\n button.removeAttribute(\"aria-current\");\n }\n }\n this.#setDisabled(this.hasPrevTarget ? this.prevTarget : null, this.pageValue <= 1);\n this.#setDisabled(\n this.hasNextTarget ? this.nextTarget : null,\n this.pageValue >= this.totalValue,\n );\n }\n\n /**\n * Sets `disabled` on a boundary button, first moving focus off it if it is the\n * active element so disabling never strands focus.\n */\n #setDisabled(button: HTMLButtonElement | null, disabled: boolean): void {\n if (!button) return;\n if (disabled && button === document.activeElement) {\n this.#moveFocusAwayFrom(button);\n }\n button.disabled = disabled;\n }\n\n /** Moves focus to the opposite enabled control, falling back to the current page. */\n #moveFocusAwayFrom(button: HTMLButtonElement): void {\n const opposite =\n button === (this.hasPrevTarget ? this.prevTarget : null)\n ? this.hasNextTarget\n ? this.nextTarget\n : null\n : this.hasPrevTarget\n ? this.prevTarget\n : null;\n const currentPage = this.pageTargets.find(\n (candidate) => Number(candidate.dataset.page) === this.pageValue,\n );\n const destination = opposite && !opposite.disabled ? opposite : currentPage;\n if (destination) {\n destination.focus();\n return;\n }\n // Degenerate config (e.g. a lone boundary button, no page buttons): keep focus\n // inside the pagination landmark instead of letting the browser drop it to\n // <body> when the button disables. The root is made programmatically focusable\n // just-in-time with `tabindex=\"-1\"`, which is not a Tab stop.\n if (!this.element.hasAttribute(\"tabindex\")) this.element.setAttribute(\"tabindex\", \"-1\");\n this.element.focus();\n }\n}\n"]}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AA,EAGA,IAAI,KAAA,GAAgB;AAClB,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,SAAS,CAAA;AAAA,EACnC;AAAA;AAAA,EAGA,OAAO,IAAA,EAAsB;AAC3B,IAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,IAAI,GAAG,OAAO,CAAA;AACnC,IAAA,OAAO,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,MAAA,EAAQ,IAAA,CAAK,GAAA,CAAI,CAAA,EAAG,IAAA,CAAK,KAAA,CAAM,IAAI,CAAC,CAAC,CAAA;AAAA,EAC5D;AAAA;AAAA,EAGA,MAAM,MAAA,EAAoC;AACxC,IAAA,OAAO,MAAA,CAAO,YAAA,CAAa,qBAAA,CAAqB,cAAc,CAAA;AAAA,EAChE;AACF","file":"pagination_controller.js","sourcesContent":["/**\n * Whether a disabled `<fieldset>` ancestor actually reaches `control`.\n *\n * HTML exempts the contents of a fieldset's **first direct-child `<legend>`**, and\n * the exemption is per fieldset — a control legal in one legend can still be\n * disabled by a second, outer fieldset, so the walk continues upward.\n *\n * Exported for the consumer that needs this rule *without* the rest of\n * {@link canTakeFocus}: `toolbar` bounds its own `hidden` walk at the toolbar\n * root, which is a different rule, so it composes the two itself.\n */\nexport function inheritsFieldsetDisabled(control: HTMLElement): boolean {\n let fieldset: Element | null = control.closest(\"fieldset[disabled]\");\n while (fieldset) {\n const legend = Array.from(fieldset.children).find((child) => child.tagName === \"LEGEND\");\n if (!legend?.contains(control)) return true;\n fieldset = fieldset.parentElement?.closest(\"fieldset[disabled]\") ?? null;\n }\n return false;\n}\n\n/**\n * Whether an element can actually take focus, checked **before** `focus()` runs.\n *\n * A controller that must move focus off a control it is about to disable or hide\n * picks a destination and calls `focus()` on it. If that destination cannot take\n * focus, the call **fails silently**: `hidden` and natively `disabled` elements\n * swallow it, so the caret stays in the subtree that is disappearing and lands on\n * `<body>` a frame later — the exact outcome the rescue exists to prevent, minus\n * any signal that it happened.\n *\n * Testing after the fact is the obvious alternative and is deliberately not the\n * rule. Reading `document.activeElement` back only works in a real browser, and\n * looping over candidates that way performs a real focus move per failure —\n * observable to assistive technology. Checking first costs nothing and catches\n * the cases that actually occur.\n *\n * **`aria-disabled` is not disqualifying.** It is the attribute an author uses\n * for a control that must stay *discoverable*, and the roving contract keeps\n * such items reachable. Only the three conditions that make the platform refuse\n * focus are checked: `hidden` (an ancestor's counts), the native `disabled`\n * property, and `disabled` inherited from an ancestor `fieldset`. CSS-only\n * invisibility is not detectable here and stays the consumer's problem.\n *\n * Reading `:disabled` instead of walking the fieldset chain would be shorter, but\n * that pseudo-class is not evaluated consistently outside real browsers and this\n * has to be right headlessly too. happy-dom in particular focuses a `<button>`\n * inside a disabled fieldset where a real engine refuses, so the inheritance is\n * spelled out rather than delegated.\n *\n * What a consumer does when nothing survives is its own call: some fall back to\n * their landmark, while a widget whose caret already sits somewhere legitimate\n * refuses the move outright rather than relocating it.\n *\n * @example\n * ```ts\n * const target = candidates.find(canTakeFocus);\n * if (target) target.focus();\n * else {\n * this.#tabindex.lend(this.element); // nothing left: fall back to the landmark\n * this.element.focus();\n * }\n * ```\n *\n * @param element - the candidate destination\n */\nexport function canTakeFocus(element: HTMLElement): boolean {\n if (element.closest(\"[hidden]\")) return false;\n if (!(\"disabled\" in element)) return true;\n if ((element as HTMLElement & { disabled: boolean }).disabled) return false;\n return !inheritsFieldsetDisabled(element);\n}\n","/**\n * Shared bookkeeping for a `tabindex` a controller lends an element temporarily.\n *\n * A controller that must move focus somewhere the author never made focusable\n * (a landmark root, a scroll destination) reaches for the same trick: add a\n * `tabindex` just-in-time and hand it back once it is no longer needed. The\n * borrow is the easy half; the return is what the two conditions below are for.\n *\n * **Returning needs two conditions, not one.** Owning the borrow is not enough:\n * the attribute must also still hold the value this instance wrote. A consumer\n * that changed it afterwards — `tabindex=\"0\"` to make the root its own Tab stop\n * — owns it now, and removing it there silently discards authored markup. The\n * bookkeeping is dropped either way, since the loan is over regardless of who\n * ends up owning the value.\n *\n * **Never borrow over an existing value.** An element that already carries a\n * `tabindex` is the author's to control, so there is nothing to lend and nothing\n * to return.\n *\n * The registry is keyed by element, so a controller borrowing on a single\n * element (`this.element`) and one borrowing across a changing set of targets\n * use the same API — the single-element case is a set of one. It holds no\n * opinion about *when* to borrow or where focus goes next; that stays in the\n * controller.\n *\n * **The API is deliberately two methods.** This file's own doc block is dropped\n * from `dist`, but every member comment is inlined into **each** consumer entry\n * (`tsup` builds with `splitting: false`), so rationale belongs here, only the\n * contract belongs on the members, and every method no consumer calls is still\n * paid for once per consumer entry.\n *\n * @example\n * ```ts\n * readonly #tabindex = new TabindexLoan();\n *\n * #rescueFocus() {\n * this.#tabindex.lend(this.element);\n * this.element.focus();\n * }\n *\n * disconnect() {\n * this.#tabindex.returnAll();\n * }\n * ```\n */\nexport class TabindexLoan<T extends HTMLElement = HTMLElement> {\n readonly #value: string;\n readonly #lent = new Set<T>();\n\n /**\n * @param value - the `tabindex` to lend. `\"-1\"` (the default) is\n * programmatically focusable but not a Tab stop; `\"0\"` is a real Tab stop,\n * which a scroll region with no focusable content of its own needs.\n */\n constructor(value: string = \"-1\") {\n this.#value = value;\n }\n\n /** Lends `element` the value; no-ops when it already carries a `tabindex`. */\n lend(element: T): void {\n if (element.hasAttribute(\"tabindex\")) return;\n element.setAttribute(\"tabindex\", this.#value);\n this.#lent.add(element);\n }\n\n /** Takes back every loan whose value is still the one that was lent. */\n returnAll(): void {\n for (const element of this.#lent) {\n if (element.getAttribute(\"tabindex\") === this.#value) element.removeAttribute(\"tabindex\");\n }\n this.#lent.clear();\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { canTakeFocus } from \"../utils/focus_candidate\";\nimport { TabindexLoan } from \"../utils/tabindex_loan\";\n\n/**\n * Headless, accessible pagination behavior.\n *\n * Markup contract (identifier: `stimeo--pagination`):\n * <nav data-controller=\"stimeo--pagination\" aria-label=\"Pagination\"\n * data-stimeo--pagination-page-value=\"1\"\n * data-stimeo--pagination-total-value=\"5\">\n * <button type=\"button\" data-stimeo--pagination-target=\"prev\"\n * data-action=\"click->stimeo--pagination#prev\">Prev</button>\n * <button type=\"button\" data-page=\"1\" aria-current=\"page\"\n * data-stimeo--pagination-target=\"page\"\n * data-action=\"click->stimeo--pagination#select\">1</button>\n * <!-- more page buttons -->\n * <button type=\"button\" data-stimeo--pagination-target=\"next\"\n * data-action=\"click->stimeo--pagination#next\">Next</button>\n * </nav>\n *\n * There is no dedicated APG pattern; this uses a navigation landmark plus\n * `aria-current=\"page\"`. The controller owns current-page state, the\n * `aria-current` sync, boundary disabling of prev/next, and the change event.\n * Generating/eliding the page buttons and fetching data stay with the consumer.\n *\n * `prev`/`next` must be real `<button>` elements: the boundary state is applied\n * through the native `disabled` property, which no other element honors.\n *\n * @remarks\n * Behavior only — each control is in the natural Tab order (no roving). When a\n * boundary disables the button that currently has focus, focus is moved first so\n * it is never lost to a `disabled` element.\n *\n * Behavior provided:\n * - `select` reads the clicked button's `data-page` and makes it current. The\n * value must parse as an integer; blank/fractional/non-numeric ones are ignored.\n * - `prev`/`next` step by one, clamped to `[1, total]`.\n * - The current page button gets `aria-current=\"page\"` (removed from the rest);\n * `prev` is `disabled` at page 1 and `next` at `total`.\n * - `page`/`total` are normalized (`total` to a finite integer >= 1, `page` into\n * `[1, total]`) on connect **and** on every runtime Value change, so JS-driven\n * updates re-render. Normalization never dispatches `change`: it is a display\n * correction, not a user navigation, and the initial render is consumer-owned.\n * - Page/boundary buttons swapped in at runtime re-render through the Stimulus\n * target callbacks, so a consumer-regenerated button list stays in sync.\n * - Every navigation dispatches `stimeo--pagination:change`, whose `detail.total`\n * is the same normalized total the boundary state is derived from.\n *\n * The boundary `disabled` is **owned**: the controller marks what it disabled\n * with `data-stimeo--pagination-boundary-disabled` and releases only that. A\n * button already disabled by the consumer is never marked when it overlaps a\n * boundary, so loading / permission state survives both entering and leaving the\n * boundary. The marker lives in the DOM rather than in a field so ownership\n * survives a Turbo cache restore, where a fresh instance would otherwise either\n * strand or steal the flag.\n */\nexport class PaginationController extends Controller<HTMLElement> {\n static override targets = [\"page\", \"prev\", \"next\"];\n static override values = {\n page: { type: Number, default: 1 },\n total: { type: Number, default: 1 },\n };\n static actions = [\"next\", \"prev\", \"select\"] as const;\n static events = [\"change\"] as const;\n\n /** Marks a `disabled` this controller applied at a boundary (ownership flag). */\n static readonly #BOUNDARY_ATTR = \"data-stimeo--pagination-boundary-disabled\";\n\n declare readonly pageTargets: HTMLElement[];\n declare readonly prevTarget: HTMLButtonElement;\n declare readonly nextTarget: HTMLButtonElement;\n declare readonly hasPrevTarget: boolean;\n declare readonly hasNextTarget: boolean;\n declare pageValue: number;\n declare totalValue: number;\n\n #isConnected = false;\n /** The `tabindex` this instance lends the root for the focus fallback. */\n readonly #tabindex = new TabindexLoan();\n\n /** Normalizes out-of-range initial values and renders the initial state. */\n override connect(): void {\n this.#isConnected = true;\n this.#normalizeAndRender();\n }\n\n /** Reverts the one attribute the controller adds outside its state hooks. */\n override disconnect(): void {\n this.#isConnected = false;\n this.#tabindex.returnAll();\n }\n\n /** Re-renders when application code (or a Turbo morph) changes `page` at runtime. */\n pageValueChanged(): void {\n if (!this.#isConnected) return;\n this.#normalizeAndRender();\n }\n\n /** Re-renders when application code (or a Turbo morph) changes `total` at runtime. */\n totalValueChanged(): void {\n if (!this.#isConnected) return;\n this.#normalizeAndRender();\n }\n\n /** Syncs a page button appended/replaced at runtime (the consumer owns the list). */\n pageTargetConnected(): void {\n if (!this.#isConnected) return;\n this.#render();\n }\n\n /** Syncs a `prev` button appended/replaced at runtime. */\n prevTargetConnected(): void {\n if (!this.#isConnected) return;\n this.#render();\n }\n\n /** Syncs a `next` button appended/replaced at runtime. */\n nextTargetConnected(): void {\n if (!this.#isConnected) return;\n this.#render();\n }\n\n /** Makes the clicked page button (its `data-page`) current. */\n select(event: Event): void {\n const button = event.currentTarget as HTMLElement;\n const raw = button.dataset.page;\n if (raw === undefined || raw.trim() === \"\") return;\n const page = Number(raw);\n // Integer-only, matching `stimeo--stepper`: `Number(\"\")` is 0 and `Number(\"2.7\")`\n // truncates, so a bare finite check would accept meaningless page numbers.\n if (!Number.isInteger(page)) return;\n this.#goto(page);\n }\n\n /** Steps to the previous page. */\n prev(): void {\n this.#goto(this.#page - 1);\n }\n\n /** Steps to the next page. */\n next(): void {\n this.#goto(this.#page + 1);\n }\n\n /** Moves to `page` (clamped to `[1, total]`), re-renders, and dispatches `change`. */\n #goto(page: number): void {\n if (!Number.isFinite(page)) return;\n const previous = this.#page;\n const target = this.#clamp(page);\n if (target === previous) return;\n this.pageValue = target;\n this.#render();\n this.dispatch(\"change\", {\n detail: { page: target, total: this.#total, previous },\n });\n }\n\n /** Writes the normalized Values back (only when they differ) and renders. */\n #normalizeAndRender(): void {\n // Stimulus setters rewrite the data attribute unconditionally, so guard the\n // no-op case to avoid waking consumer MutationObservers for nothing.\n const total = this.#total;\n if (!Object.is(total, this.totalValue)) this.totalValue = total;\n const page = this.#page;\n if (!Object.is(page, this.pageValue)) this.pageValue = page;\n this.#render();\n }\n\n /** Syncs `aria-current` on the page buttons and the prev/next `disabled` state. */\n #render(): void {\n const page = this.#page;\n for (const button of this.pageTargets) {\n if (Number(button.dataset.page) === page) {\n button.setAttribute(\"aria-current\", \"page\");\n } else {\n button.removeAttribute(\"aria-current\");\n }\n }\n\n const prev = this.hasPrevTarget ? this.prevTarget : null;\n const next = this.hasNextTarget ? this.nextTarget : null;\n const atStart = page <= 1;\n const atEnd = page >= this.#total;\n // Resolve both post-render states up front: a focus hand-off must target the\n // opposite button as it will be *after* this pass, not as it is now (moving\n // between the two boundaries of a 2-page set re-enables it in the same pass).\n const prevStaysDisabled = this.#disabledAfter(prev, atStart);\n const nextStaysDisabled = this.#disabledAfter(next, atEnd);\n // Release before disabling, so the hand-off can land on a button this same\n // pass re-enables (focusing a still-`disabled` button is a no-op).\n this.#release(prev, atStart);\n this.#release(next, atEnd);\n this.#disable(prev, atStart, nextStaysDisabled ? null : next);\n this.#disable(next, atEnd, prevStaysDisabled ? null : prev);\n }\n\n /** Whether a boundary button will still be `disabled` once this render applies. */\n #disabledAfter(button: HTMLButtonElement | null, atBoundary: boolean): boolean {\n if (!button) return true;\n if (atBoundary) return true;\n // Away from a boundary, only the controller's own `disabled` is released.\n return button.disabled && !this.#owns(button);\n }\n\n /** Releases the boundary `disabled` this controller owns, once away from it. */\n #release(button: HTMLButtonElement | null, atBoundary: boolean): void {\n if (!button || atBoundary || !this.#owns(button)) return;\n button.disabled = false;\n button.removeAttribute(PaginationController.#BOUNDARY_ATTR);\n }\n\n /**\n * Disables a boundary button, first moving focus off it when it is the active\n * element so disabling never strands focus.\n */\n #disable(\n button: HTMLButtonElement | null,\n atBoundary: boolean,\n opposite: HTMLButtonElement | null,\n ): void {\n if (!button || !atBoundary) return;\n if (button.disabled && !this.#owns(button)) return;\n if (button === document.activeElement) this.#moveFocusAwayFrom(opposite);\n button.disabled = true;\n button.setAttribute(PaginationController.#BOUNDARY_ATTR, \"\");\n }\n\n /**\n * Moves focus to `opposite` (already resolved to `null` when it will stay\n * disabled), else to the current page button, else to the landmark itself.\n */\n #moveFocusAwayFrom(opposite: HTMLButtonElement | null): void {\n const page = this.#page;\n const currentPage = this.pageTargets.find(\n (candidate) => Number(candidate.dataset.page) === page,\n );\n // Checked before the call, never after: `hidden` and natively disabled\n // elements swallow `focus()` silently, so an unchecked destination leaves the\n // caret in the subtree that is about to disable and drops it to <body> a frame\n // later — the outcome this rescue exists to prevent.\n // Narrowed to `HTMLElement`, not `HTMLButtonElement`: `pageTargets` is typed\n // `HTMLElement[]`, so a page control can legitimately be an `<a>`. The\n // destination is only ever focused, so the wider type is the honest one.\n const destination = [opposite, currentPage].find(\n (candidate): candidate is HTMLElement => candidate != null && canTakeFocus(candidate),\n );\n if (destination) {\n destination.focus();\n return;\n }\n // Nothing left to hand focus to (a lone boundary button, or every page button\n // disabled): keep it inside the pagination landmark instead of letting the\n // browser drop it to <body> when the button disables. The root is made\n // programmatically focusable just-in-time with `tabindex=\"-1\"`, which is not a\n // Tab stop; `disconnect()` removes it again when this controller added it.\n this.#tabindex.lend(this.element);\n this.element.focus();\n }\n\n /** Total pages, normalized to a finite integer >= 1. */\n get #total(): number {\n const total = this.totalValue;\n return Number.isFinite(total) ? Math.max(1, Math.trunc(total)) : 1;\n }\n\n /** The current page, normalized into `[1, total]`. */\n get #page(): number {\n return this.#clamp(this.pageValue);\n }\n\n /** Constrains `page` to `[1, total]`; a non-finite page falls back to page 1. */\n #clamp(page: number): number {\n if (!Number.isFinite(page)) return 1;\n return Math.min(this.#total, Math.max(1, Math.trunc(page)));\n }\n\n /** Whether the button's current `disabled` was applied by boundary control. */\n #owns(button: HTMLButtonElement): boolean {\n return button.hasAttribute(PaginationController.#BOUNDARY_ATTR);\n }\n}\n"]}
|
|
@@ -182,12 +182,12 @@ var PersistController = class extends Controller {
|
|
|
182
182
|
}
|
|
183
183
|
/**
|
|
184
184
|
* Persistable fields paired with a stable storage key. Uniquely-named fields key
|
|
185
|
-
* by their name
|
|
186
|
-
*
|
|
187
|
-
*
|
|
188
|
-
*
|
|
189
|
-
*
|
|
190
|
-
*
|
|
185
|
+
* by their name. Repeated same-name fields (e.g. a `tags[]` checkbox group or
|
|
186
|
+
* array text inputs) are disambiguated by DOM-order occurrence — the first keeps
|
|
187
|
+
* its plain `name`, later ones get a NUL-separated index suffix — so each is
|
|
188
|
+
* stored and restored individually instead of the last one clobbering the rest.
|
|
189
|
+
* Radios are the exception: a group intentionally shares one key (one value per
|
|
190
|
+
* name).
|
|
191
191
|
*/
|
|
192
192
|
#fieldEntries() {
|
|
193
193
|
const entries = [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/safe_timeout.ts","../../src/controllers/persist_controller.ts"],"names":[],"mappings":";;;;;AAwBA,IAAe,gBAAf,MAA6B;AAAA;AAAA,EAER,GAAA,uBAAU,GAAA,EAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA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AAA,OAAO,IAAA;AAAA,EACT;AAAA;AAAA,EAGA,OAAO,KAAA,EAAoC;AACzC,IAAA,OAAO,KAAA,CAAM,IAAA,IAAQ,KAAA,CAAM,EAAA,IAAM,IAAA;AAAA,EACnC;AAAA;AAAA,EAGA,IAAI,WAAA,GAA6B;AAC/B,IAAA,MAAM,GAAA,GAAM,IAAA,CAAK,QAAA,IAAY,IAAA,CAAK,OAAA,CAAQ,EAAA;AAC1C,IAAA,OAAO,GAAA,CAAI,MAAA,GAAS,CAAA,GAAI,GAAA,GAAM,IAAA;AAAA,EAChC;AAAA;AAAA,EAGA,IAAI,WAAA,GAA6B;AAC/B,IAAA,MAAM,UAAU,IAAA,CAAK,WAAA;AACrB,IAAA,OAAO,YAAY,IAAA,GAAO,IAAA,GAAO,CAAA,EAAG,cAAc,GAAG,OAAO,CAAA,CAAA;AAAA,EAC9D;AAAA,EAEA,SAAS,GAAA,EAA4B;AACnC,IAAA,IAAI;AACF,MAAA,OAAO,MAAA,CAAO,YAAA,CAAa,OAAA,CAAQ,GAAG,CAAA;AAAA,IACxC,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AAAA,EAEA,QAAA,CAAS,KAAa,KAAA,EAAqB;AACzC,IAAA,IAAI;AACF,MAAA,MAAA,CAAO,YAAA,CAAa,OAAA,CAAQ,GAAA,EAAK,KAAK,CAAA;AAAA,IACxC,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF;AAAA,EAEA,YAAY,GAAA,EAAmB;AAC7B,IAAA,IAAI;AACF,MAAA,MAAA,CAAO,YAAA,CAAa,WAAW,GAAG,CAAA;AAAA,IACpC,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF;AACF","file":"persist_controller.js","sourcesContent":["/**\n * Self-cleaning timer registries shared by Stimeo controllers.\n *\n * Stimulus controllers frequently schedule `setTimeout` / `setInterval` work\n * (auto-dismiss, debouncing, polling). When the element leaves the DOM — a\n * Turbo Drive navigation, a Turbo Stream replacement, or any `disconnect()` —\n * orphaned timers keep firing against a detached controller, leaking memory and\n * mutating stale state. {@link SafeTimeout} and {@link SafeInterval} track every\n * timer they create so a single {@link TimerRegistry.clearAll | clearAll()} call\n * in `disconnect()` tears them all down.\n *\n * These are intentionally low-level primitives: they own *registration and\n * cleanup only*. Higher-level policy (pause/resume, remaining-time accounting)\n * stays in the individual controllers so per-widget semantics are not flattened\n * into a lowest-common-denominator helper.\n */\n\n/**\n * Shared registry bookkeeping for the timeout/interval variants.\n *\n * Subclasses provide the scheduling primitive ({@link schedule}) and its matching\n * canceller ({@link cancel}); this base owns the set of live ids plus the\n * per-id and bulk teardown shared by both.\n */\nabstract class TimerRegistry {\n /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */\n protected readonly ids = new Set<number>();\n\n /** Schedules the underlying platform timer and returns its id. */\n protected abstract schedule(callback: () => void, delay: number): number;\n\n /** Cancels the underlying platform timer for `id`. */\n protected abstract cancel(id: number): void;\n\n /**\n * Cancels a single tracked timer.\n *\n * No-ops if the id is unknown (already cleared, fired, or never owned by this\n * registry), so callers can clear defensively without guarding.\n */\n clear(id: number): void {\n if (this.ids.delete(id)) {\n this.cancel(id);\n }\n }\n\n /**\n * Cancels every tracked timer. Call this from a controller's `disconnect()`\n * to guarantee no timer outlives the element.\n */\n clearAll(): void {\n for (const id of this.ids) {\n this.cancel(id);\n }\n this.ids.clear();\n }\n\n /** Number of timers currently tracked (pending). */\n get size(): number {\n return this.ids.size;\n }\n}\n\n/**\n * `setTimeout` wrapper that auto-forgets each timer once it fires and supports\n * bulk teardown on disconnect.\n *\n * @example\n * ```ts\n * #timers = new SafeTimeout();\n *\n * connect() {\n * this.#timers.set(() => this.dismiss(), 5000);\n * }\n *\n * disconnect() {\n * this.#timers.clearAll();\n * }\n * ```\n */\nexport class SafeTimeout extends TimerRegistry {\n /**\n * Schedules `callback` after `delay` ms and returns the timer id.\n *\n * The id is removed from the registry automatically when the timeout fires,\n * so {@link TimerRegistry.size | size} reflects only still-pending timers.\n */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(() => {\n this.ids.delete(id);\n callback();\n }, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setTimeout(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearTimeout(id);\n }\n}\n\n/**\n * `setInterval` wrapper that tracks every interval for bulk teardown on\n * disconnect. Unlike {@link SafeTimeout}, intervals are retained until they are\n * explicitly cleared because they fire repeatedly.\n *\n * @example\n * ```ts\n * #intervals = new SafeInterval();\n *\n * connect() {\n * this.#intervals.set(() => this.tick(), 1000);\n * }\n *\n * disconnect() {\n * this.#intervals.clearAll();\n * }\n * ```\n */\nexport class SafeInterval extends TimerRegistry {\n /** Schedules a repeating `callback` every `delay` ms and returns the timer id. */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(callback, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setInterval(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearInterval(id);\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/** Field controls this controller can persist. */\ntype PersistField = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;\n\n/** Input types that carry no meaningful, restorable value. */\nconst NON_VALUE_TYPES = new Set([\"file\", \"submit\", \"reset\", \"button\", \"image\"]);\n/** localStorage key prefix so drafts never clobber unrelated app storage. */\nconst STORAGE_PREFIX = \"stimeo--persist:\";\n/** Separator for disambiguating repeated same-name fields (cannot occur in a real field name). */\nconst OCCURRENCE_SEP = \"\\u0000\";\n\n/**\n * Headless draft-autosave behavior: persists a form's field values to\n * `localStorage` and restores them across Turbo navigations and reloads (no APG\n * pattern; a state-holding utility). The Alpine `persist` equivalent.\n *\n * Markup contract (identifier: `stimeo--persist`):\n * <form data-controller=\"stimeo--persist\"\n * data-stimeo--persist-key-value=\"contact-draft\">\n * <input name=\"name\">\n * <textarea name=\"message\"></textarea>\n * </form>\n *\n * On connect it restores any saved values under `key` (falling back to the\n * element's `id`), then debounce-saves on every input/change. Password fields (and\n * anything in `exclude`) are never written. A `clear()` action — or the `clearOn`\n * event (e.g. `submit`) — drops the draft. Restoring never moves focus.\n *\n * @remarks\n * Behavior only. State lives entirely in `localStorage` (no module-scope state), so\n * instances never interfere. The input listener and debounce timer are removed on\n * `disconnect()` (Turbo navigation included), where a pending save is flushed first\n * so an in-flight edit is not lost.\n */\nexport class PersistController extends Controller<HTMLElement> {\n static override targets = [\"field\"];\n static override values = {\n key: { type: String, default: \"\" },\n debounce: { type: Number, default: 400 },\n exclude: { type: Array, default: [\"password\"] },\n clearOn: { type: String, default: \"\" },\n };\n static actions = [\"clear\"] as const;\n static events = [\"restore\", \"save\", \"clear\"] as const;\n\n declare readonly fieldTargets: PersistField[];\n declare readonly hasFieldTarget: boolean;\n\n declare keyValue: string;\n declare debounceValue: number;\n declare excludeValue: string[];\n declare clearOnValue: string;\n\n readonly #timeouts = new SafeTimeout();\n #saveId: number | null = null;\n\n readonly #onInput = (): void => {\n this.#scheduleSave();\n };\n\n readonly #onClearEvent = (): void => {\n this.clear();\n };\n\n override connect(): void {\n if (this.#storageKey === null) return;\n this.#restore();\n this.element.addEventListener(\"input\", this.#onInput);\n this.element.addEventListener(\"change\", this.#onInput);\n if (this.clearOnValue.length > 0) {\n this.element.addEventListener(this.clearOnValue, this.#onClearEvent);\n }\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"input\", this.#onInput);\n this.element.removeEventListener(\"change\", this.#onInput);\n if (this.clearOnValue.length > 0) {\n this.element.removeEventListener(this.clearOnValue, this.#onClearEvent);\n }\n // Flush a pending save so an in-flight edit survives a Turbo navigation.\n if (this.#saveId !== null) {\n this.#timeouts.clear(this.#saveId);\n this.#saveId = null;\n this.#write();\n }\n this.#timeouts.clearAll();\n }\n\n /** Drops the saved draft and clears the restored marker. */\n clear(): void {\n const key = this.#storageKey;\n if (key === null) return;\n if (this.#saveId !== null) {\n this.#timeouts.clear(this.#saveId);\n this.#saveId = null;\n }\n this.#removeItem(key);\n this.element.removeAttribute(\"data-persist-restored\");\n this.dispatch(\"clear\", { detail: { key: this.#logicalKey } });\n }\n\n /** Schedules a debounced save. */\n #scheduleSave(): void {\n if (this.#saveId !== null) this.#timeouts.clear(this.#saveId);\n this.#saveId = this.#timeouts.set(() => {\n this.#saveId = null;\n this.#save();\n }, this.debounceValue);\n }\n\n /** Writes the current values and emits `save`. */\n #save(): void {\n this.#write();\n this.dispatch(\"save\", { detail: { key: this.#logicalKey } });\n }\n\n /** Serializes persistable fields and stores them under the storage key. */\n #write(): void {\n const key = this.#storageKey;\n if (key === null) return;\n const data: Record<string, unknown> = {};\n for (const { field, key: fieldKey } of this.#fieldEntries()) {\n if (field instanceof HTMLInputElement && field.type === \"checkbox\") {\n data[fieldKey] = field.checked;\n } else if (field instanceof HTMLInputElement && field.type === \"radio\") {\n if (field.checked) data[fieldKey] = field.value;\n } else if (field instanceof HTMLSelectElement && field.multiple) {\n data[fieldKey] = Array.from(field.selectedOptions).map((o) => o.value);\n } else {\n data[fieldKey] = field.value;\n }\n }\n this.#setItem(key, JSON.stringify(data));\n }\n\n /** Applies any saved values to the fields, without moving focus. */\n #restore(): void {\n const key = this.#storageKey;\n if (key === null) return;\n const raw = this.#getItem(key);\n if (raw === null) return;\n let data: Record<string, unknown>;\n try {\n data = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n return;\n }\n let restoredAny = false;\n for (const { field, key: fieldKey } of this.#fieldEntries()) {\n if (!Object.hasOwn(data, fieldKey)) continue;\n this.#applyValue(field, data[fieldKey]);\n restoredAny = true;\n }\n if (restoredAny) {\n this.element.setAttribute(\"data-persist-restored\", \"true\");\n this.dispatch(\"restore\", { detail: { key: this.#logicalKey } });\n }\n }\n\n /** Sets a single field's value from a stored entry. */\n #applyValue(field: PersistField, value: unknown): void {\n if (field instanceof HTMLInputElement && field.type === \"checkbox\") {\n field.checked = Boolean(value);\n } else if (field instanceof HTMLInputElement && field.type === \"radio\") {\n field.checked = field.value === value;\n } else if (field instanceof HTMLSelectElement && field.multiple) {\n const selected = new Set(Array.isArray(value) ? value.map(String) : []);\n for (const option of Array.from(field.options)) {\n option.selected = selected.has(option.value);\n }\n } else {\n field.value = String(value);\n }\n }\n\n /**\n * Persistable fields paired with a stable storage key. Uniquely-named fields key\n * by their name (unchanged, backward-compatible). Repeated same-name fields\n * (e.g. a `tags[]` checkbox group or array text inputs) are disambiguated by\n * DOM-order occurrence — the first keeps its plain `name` (backward-\n * compatible), later ones get a NUL-separated index suffix — so each is stored and\n * restored individually instead of the last one clobbering the rest. Radios are\n * the exception: a group intentionally shares one key (one value per name).\n */\n #fieldEntries(): Array<{ field: PersistField; key: string }> {\n const entries: Array<{ field: PersistField; key: string }> = [];\n const occurrence = new Map<string, number>();\n for (const field of this.#fields()) {\n const name = this.#keyOf(field);\n if (name === null) continue;\n if (field instanceof HTMLInputElement && field.type === \"radio\") {\n entries.push({ field, key: name });\n continue;\n }\n const seen = occurrence.get(name) ?? 0;\n occurrence.set(name, seen + 1);\n entries.push({ field, key: seen === 0 ? name : `${name}${OCCURRENCE_SEP}${seen}` });\n }\n return entries;\n }\n\n /** The fields to persist: `field` targets, or the element's named controls. */\n #fields(): PersistField[] {\n const candidates = this.hasFieldTarget\n ? this.fieldTargets\n : Array.from(this.element.querySelectorAll<PersistField>(\"input, textarea, select\"));\n return candidates.filter((field) => this.#persistable(field));\n }\n\n /** Whether a field carries a restorable, non-excluded value. */\n #persistable(field: PersistField): boolean {\n if (this.#keyOf(field) === null) return false;\n const type = field instanceof HTMLInputElement ? field.type : \"\";\n if (NON_VALUE_TYPES.has(type)) return false;\n if (this.excludeValue.includes(type)) return false;\n if (field.name.length > 0 && this.excludeValue.includes(field.name)) return false;\n return true;\n }\n\n /** A stable storage sub-key for a field (its name, else id). */\n #keyOf(field: PersistField): string | null {\n return field.name || field.id || null;\n }\n\n /** The logical key (key Value or element id), or null when neither is set. */\n get #logicalKey(): string | null {\n const key = this.keyValue || this.element.id;\n return key.length > 0 ? key : null;\n }\n\n /** The prefixed localStorage key, or null when persistence is disabled. */\n get #storageKey(): string | null {\n const logical = this.#logicalKey;\n return logical === null ? null : `${STORAGE_PREFIX}${logical}`;\n }\n\n #getItem(key: string): string | null {\n try {\n return window.localStorage.getItem(key);\n } catch {\n return null;\n }\n }\n\n #setItem(key: string, value: string): void {\n try {\n window.localStorage.setItem(key, value);\n } catch {\n // Storage full or unavailable (private mode): persistence is best-effort.\n }\n }\n\n #removeItem(key: string): void {\n try {\n window.localStorage.removeItem(key);\n } catch {\n // Ignore: nothing to clear if storage is unavailable.\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/safe_timeout.ts","../../src/controllers/persist_controller.ts"],"names":[],"mappings":";;;;;AAwBA,IAAe,gBAAf,MAA6B;AAAA;AAAA,EAER,GAAA,uBAAU,GAAA,EAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAczC,MAAM,EAAA,EAAkB;AACtB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,MAAA,CAAO,EAAE,CAAA,EAAG;AACvB,MAAA,IAAA,CAAK,OAAO,EAAE,CAAA;AAAA,IAChB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAA,GAAiB;AACf,IAAA,KAAA,MAAW,EAAA,IAAM,KAAK,GAAA,EAAK;AACzB,MAAA,IAAA,CAAK,OAAO,EAAE,CAAA;AAAA,IAChB;AACA,IAAA,IAAA,CAAK,IAAI,KAAA,EAAM;AAAA,EACjB;AAAA;AAAA,EAGA,IAAI,IAAA,GAAe;AACjB,IAAA,OAAO,KAAK,GAAA,CAAI,IAAA;AAAA,EAClB;AACF,CAAA;AAmBO,IAAM,WAAA,GAAN,cAA0B,aAAA,CAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO7C,GAAA,CAAI,UAAsB,KAAA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AAI;AACF,MAAA,OAAO,MAAA,CAAO,YAAA,CAAa,OAAA,CAAQ,GAAG,CAAA;AAAA,IACxC,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AAAA,EAEA,QAAA,CAAS,KAAa,KAAA,EAAqB;AACzC,IAAA,IAAI;AACF,MAAA,MAAA,CAAO,YAAA,CAAa,OAAA,CAAQ,GAAA,EAAK,KAAK,CAAA;AAAA,IACxC,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF;AAAA,EAEA,YAAY,GAAA,EAAmB;AAC7B,IAAA,IAAI;AACF,MAAA,MAAA,CAAO,YAAA,CAAa,WAAW,GAAG,CAAA;AAAA,IACpC,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF;AACF","file":"persist_controller.js","sourcesContent":["/**\n * Self-cleaning timer registries shared by Stimeo controllers.\n *\n * Stimulus controllers frequently schedule `setTimeout` / `setInterval` work\n * (auto-dismiss, debouncing, polling). When the element leaves the DOM — a\n * Turbo Drive navigation, a Turbo Stream replacement, or any `disconnect()` —\n * orphaned timers keep firing against a detached controller, leaking memory and\n * mutating stale state. {@link SafeTimeout} and {@link SafeInterval} track every\n * timer they create so a single {@link TimerRegistry.clearAll | clearAll()} call\n * in `disconnect()` tears them all down.\n *\n * These are intentionally low-level primitives: they own *registration and\n * cleanup only*. Higher-level policy (pause/resume, remaining-time accounting)\n * stays in the individual controllers so per-widget semantics are not flattened\n * into a lowest-common-denominator helper.\n */\n\n/**\n * Shared registry bookkeeping for the timeout/interval variants.\n *\n * Subclasses provide the scheduling primitive ({@link schedule}) and its matching\n * canceller ({@link cancel}); this base owns the set of live ids plus the\n * per-id and bulk teardown shared by both.\n */\nabstract class TimerRegistry {\n /** Live timer ids that have not yet been cleared (or, for timeouts, fired). */\n protected readonly ids = new Set<number>();\n\n /** Schedules the underlying platform timer and returns its id. */\n protected abstract schedule(callback: () => void, delay: number): number;\n\n /** Cancels the underlying platform timer for `id`. */\n protected abstract cancel(id: number): void;\n\n /**\n * Cancels a single tracked timer.\n *\n * No-ops if the id is unknown (already cleared, fired, or never owned by this\n * registry), so callers can clear defensively without guarding.\n */\n clear(id: number): void {\n if (this.ids.delete(id)) {\n this.cancel(id);\n }\n }\n\n /**\n * Cancels every tracked timer. Call this from a controller's `disconnect()`\n * to guarantee no timer outlives the element.\n */\n clearAll(): void {\n for (const id of this.ids) {\n this.cancel(id);\n }\n this.ids.clear();\n }\n\n /** Number of timers currently tracked (pending). */\n get size(): number {\n return this.ids.size;\n }\n}\n\n/**\n * `setTimeout` wrapper that auto-forgets each timer once it fires and supports\n * bulk teardown on disconnect.\n *\n * @example\n * ```ts\n * #timers = new SafeTimeout();\n *\n * connect() {\n * this.#timers.set(() => this.dismiss(), 5000);\n * }\n *\n * disconnect() {\n * this.#timers.clearAll();\n * }\n * ```\n */\nexport class SafeTimeout extends TimerRegistry {\n /**\n * Schedules `callback` after `delay` ms and returns the timer id.\n *\n * The id is removed from the registry automatically when the timeout fires,\n * so {@link TimerRegistry.size | size} reflects only still-pending timers.\n */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(() => {\n this.ids.delete(id);\n callback();\n }, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setTimeout(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearTimeout(id);\n }\n}\n\n/**\n * `setInterval` wrapper that tracks every interval for bulk teardown on\n * disconnect. Unlike {@link SafeTimeout}, intervals are retained until they are\n * explicitly cleared because they fire repeatedly.\n *\n * @example\n * ```ts\n * #intervals = new SafeInterval();\n *\n * connect() {\n * this.#intervals.set(() => this.tick(), 1000);\n * }\n *\n * disconnect() {\n * this.#intervals.clearAll();\n * }\n * ```\n */\nexport class SafeInterval extends TimerRegistry {\n /** Schedules a repeating `callback` every `delay` ms and returns the timer id. */\n set(callback: () => void, delay: number): number {\n const id = this.schedule(callback, delay);\n this.ids.add(id);\n return id;\n }\n\n protected schedule(callback: () => void, delay: number): number {\n return window.setInterval(callback, delay);\n }\n\n protected cancel(id: number): void {\n window.clearInterval(id);\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { SafeTimeout } from \"../utils/safe_timeout\";\n\n/** Field controls this controller can persist. */\ntype PersistField = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;\n\n/** Input types that carry no meaningful, restorable value. */\nconst NON_VALUE_TYPES = new Set([\"file\", \"submit\", \"reset\", \"button\", \"image\"]);\n/** localStorage key prefix so drafts never clobber unrelated app storage. */\nconst STORAGE_PREFIX = \"stimeo--persist:\";\n/** Separator for disambiguating repeated same-name fields (cannot occur in a real field name). */\nconst OCCURRENCE_SEP = \"\\u0000\";\n\n/**\n * Headless draft-autosave behavior: persists a form's field values to\n * `localStorage` and restores them across Turbo navigations and reloads (no APG\n * pattern; a state-holding utility). The Alpine `persist` equivalent.\n *\n * Markup contract (identifier: `stimeo--persist`):\n * <form data-controller=\"stimeo--persist\"\n * data-stimeo--persist-key-value=\"contact-draft\">\n * <input name=\"name\">\n * <textarea name=\"message\"></textarea>\n * </form>\n *\n * On connect it restores any saved values under `key` (falling back to the\n * element's `id`), then debounce-saves on every input/change. Password fields (and\n * anything in `exclude`) are never written. A `clear()` action — or the `clearOn`\n * event (e.g. `submit`) — drops the draft. Restoring never moves focus.\n *\n * @remarks\n * Behavior only. State lives entirely in `localStorage` (no module-scope state), so\n * instances never interfere. The input listener and debounce timer are removed on\n * `disconnect()` (Turbo navigation included), where a pending save is flushed first\n * so an in-flight edit is not lost.\n */\nexport class PersistController extends Controller<HTMLElement> {\n static override targets = [\"field\"];\n static override values = {\n key: { type: String, default: \"\" },\n debounce: { type: Number, default: 400 },\n exclude: { type: Array, default: [\"password\"] },\n clearOn: { type: String, default: \"\" },\n };\n static actions = [\"clear\"] as const;\n static events = [\"restore\", \"save\", \"clear\"] as const;\n\n declare readonly fieldTargets: PersistField[];\n declare readonly hasFieldTarget: boolean;\n\n declare keyValue: string;\n declare debounceValue: number;\n declare excludeValue: string[];\n declare clearOnValue: string;\n\n readonly #timeouts = new SafeTimeout();\n #saveId: number | null = null;\n\n readonly #onInput = (): void => {\n this.#scheduleSave();\n };\n\n readonly #onClearEvent = (): void => {\n this.clear();\n };\n\n override connect(): void {\n if (this.#storageKey === null) return;\n this.#restore();\n this.element.addEventListener(\"input\", this.#onInput);\n this.element.addEventListener(\"change\", this.#onInput);\n if (this.clearOnValue.length > 0) {\n this.element.addEventListener(this.clearOnValue, this.#onClearEvent);\n }\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"input\", this.#onInput);\n this.element.removeEventListener(\"change\", this.#onInput);\n if (this.clearOnValue.length > 0) {\n this.element.removeEventListener(this.clearOnValue, this.#onClearEvent);\n }\n // Flush a pending save so an in-flight edit survives a Turbo navigation.\n if (this.#saveId !== null) {\n this.#timeouts.clear(this.#saveId);\n this.#saveId = null;\n this.#write();\n }\n this.#timeouts.clearAll();\n }\n\n /** Drops the saved draft and clears the restored marker. */\n clear(): void {\n const key = this.#storageKey;\n if (key === null) return;\n if (this.#saveId !== null) {\n this.#timeouts.clear(this.#saveId);\n this.#saveId = null;\n }\n this.#removeItem(key);\n this.element.removeAttribute(\"data-persist-restored\");\n this.dispatch(\"clear\", { detail: { key: this.#logicalKey } });\n }\n\n /** Schedules a debounced save. */\n #scheduleSave(): void {\n if (this.#saveId !== null) this.#timeouts.clear(this.#saveId);\n this.#saveId = this.#timeouts.set(() => {\n this.#saveId = null;\n this.#save();\n }, this.debounceValue);\n }\n\n /** Writes the current values and emits `save`. */\n #save(): void {\n this.#write();\n this.dispatch(\"save\", { detail: { key: this.#logicalKey } });\n }\n\n /** Serializes persistable fields and stores them under the storage key. */\n #write(): void {\n const key = this.#storageKey;\n if (key === null) return;\n const data: Record<string, unknown> = {};\n for (const { field, key: fieldKey } of this.#fieldEntries()) {\n if (field instanceof HTMLInputElement && field.type === \"checkbox\") {\n data[fieldKey] = field.checked;\n } else if (field instanceof HTMLInputElement && field.type === \"radio\") {\n if (field.checked) data[fieldKey] = field.value;\n } else if (field instanceof HTMLSelectElement && field.multiple) {\n data[fieldKey] = Array.from(field.selectedOptions).map((o) => o.value);\n } else {\n data[fieldKey] = field.value;\n }\n }\n this.#setItem(key, JSON.stringify(data));\n }\n\n /** Applies any saved values to the fields, without moving focus. */\n #restore(): void {\n const key = this.#storageKey;\n if (key === null) return;\n const raw = this.#getItem(key);\n if (raw === null) return;\n let data: Record<string, unknown>;\n try {\n data = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n return;\n }\n let restoredAny = false;\n for (const { field, key: fieldKey } of this.#fieldEntries()) {\n if (!Object.hasOwn(data, fieldKey)) continue;\n this.#applyValue(field, data[fieldKey]);\n restoredAny = true;\n }\n if (restoredAny) {\n this.element.setAttribute(\"data-persist-restored\", \"true\");\n this.dispatch(\"restore\", { detail: { key: this.#logicalKey } });\n }\n }\n\n /** Sets a single field's value from a stored entry. */\n #applyValue(field: PersistField, value: unknown): void {\n if (field instanceof HTMLInputElement && field.type === \"checkbox\") {\n field.checked = Boolean(value);\n } else if (field instanceof HTMLInputElement && field.type === \"radio\") {\n field.checked = field.value === value;\n } else if (field instanceof HTMLSelectElement && field.multiple) {\n const selected = new Set(Array.isArray(value) ? value.map(String) : []);\n for (const option of Array.from(field.options)) {\n option.selected = selected.has(option.value);\n }\n } else {\n field.value = String(value);\n }\n }\n\n /**\n * Persistable fields paired with a stable storage key. Uniquely-named fields key\n * by their name. Repeated same-name fields (e.g. a `tags[]` checkbox group or\n * array text inputs) are disambiguated by DOM-order occurrence — the first keeps\n * its plain `name`, later ones get a NUL-separated index suffix — so each is\n * stored and restored individually instead of the last one clobbering the rest.\n * Radios are the exception: a group intentionally shares one key (one value per\n * name).\n */\n #fieldEntries(): Array<{ field: PersistField; key: string }> {\n const entries: Array<{ field: PersistField; key: string }> = [];\n const occurrence = new Map<string, number>();\n for (const field of this.#fields()) {\n const name = this.#keyOf(field);\n if (name === null) continue;\n if (field instanceof HTMLInputElement && field.type === \"radio\") {\n entries.push({ field, key: name });\n continue;\n }\n const seen = occurrence.get(name) ?? 0;\n occurrence.set(name, seen + 1);\n entries.push({ field, key: seen === 0 ? name : `${name}${OCCURRENCE_SEP}${seen}` });\n }\n return entries;\n }\n\n /** The fields to persist: `field` targets, or the element's named controls. */\n #fields(): PersistField[] {\n const candidates = this.hasFieldTarget\n ? this.fieldTargets\n : Array.from(this.element.querySelectorAll<PersistField>(\"input, textarea, select\"));\n return candidates.filter((field) => this.#persistable(field));\n }\n\n /** Whether a field carries a restorable, non-excluded value. */\n #persistable(field: PersistField): boolean {\n if (this.#keyOf(field) === null) return false;\n const type = field instanceof HTMLInputElement ? field.type : \"\";\n if (NON_VALUE_TYPES.has(type)) return false;\n if (this.excludeValue.includes(type)) return false;\n if (field.name.length > 0 && this.excludeValue.includes(field.name)) return false;\n return true;\n }\n\n /** A stable storage sub-key for a field (its name, else id). */\n #keyOf(field: PersistField): string | null {\n return field.name || field.id || null;\n }\n\n /** The logical key (key Value or element id), or null when neither is set. */\n get #logicalKey(): string | null {\n const key = this.keyValue || this.element.id;\n return key.length > 0 ? key : null;\n }\n\n /** The prefixed localStorage key, or null when persistence is disabled. */\n get #storageKey(): string | null {\n const logical = this.#logicalKey;\n return logical === null ? null : `${STORAGE_PREFIX}${logical}`;\n }\n\n #getItem(key: string): string | null {\n try {\n return window.localStorage.getItem(key);\n } catch {\n return null;\n }\n }\n\n #setItem(key: string, value: string): void {\n try {\n window.localStorage.setItem(key, value);\n } catch {\n // Storage full or unavailable (private mode): persistence is best-effort.\n }\n }\n\n #removeItem(key: string): void {\n try {\n window.localStorage.removeItem(key);\n } catch {\n // Ignore: nothing to clear if storage is unavailable.\n }\n }\n}\n"]}
|
|
@@ -34,9 +34,8 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
34
34
|
* survive), commits the offset on drop and restores it on cancel — the exact
|
|
35
35
|
* boilerplate every simple consumer would otherwise re-write. With `follow` the
|
|
36
36
|
* element's inline `translate` belongs to this controller (`connect()` re-reads
|
|
37
|
-
* a
|
|
38
|
-
*
|
|
39
|
-
* 1.1 deprecated `aria-grabbed`/`aria-dropeffect`, so the grabbed state is
|
|
37
|
+
* a committed `<x>px <y>px` offset, so Turbo restores stay consistent). ARIA 1.1
|
|
38
|
+
* deprecated `aria-grabbed`/`aria-dropeffect`, so the grabbed state is
|
|
40
39
|
* published as `data-grabbed` and the *meaning* of a drag must be announced by
|
|
41
40
|
* the consumer (pair with `stimeo--announcer`). `touch-action` on the handles is
|
|
42
41
|
* derived from `axis` (marker-guarded, authored values win) so the page does not
|
|
@@ -2,6 +2,12 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
2
2
|
|
|
3
3
|
// src/controllers/pointer_drag_controller.ts
|
|
4
4
|
|
|
5
|
+
// src/utils/arrow_step.ts
|
|
6
|
+
function isReservedArrowChord(event, allow = []) {
|
|
7
|
+
if (!event.key.startsWith("Arrow")) return false;
|
|
8
|
+
return event.altKey && !allow.includes("alt") || event.ctrlKey && !allow.includes("ctrl") || event.metaKey && !allow.includes("meta") || event.shiftKey && !allow.includes("shift");
|
|
9
|
+
}
|
|
10
|
+
|
|
5
11
|
// src/utils/detach_gate.ts
|
|
6
12
|
var DetachGate = class _DetachGate {
|
|
7
13
|
/** Set while a probe is queued, waiting for a reconnect to cancel it. */
|
|
@@ -186,8 +192,10 @@ var PointerDragController = class _PointerDragController extends Controller {
|
|
|
186
192
|
if (this.disabledValue) return;
|
|
187
193
|
const handle = this.#handleFor(event.target);
|
|
188
194
|
if (!handle) return;
|
|
195
|
+
if (event.defaultPrevented) return;
|
|
196
|
+
if (isReservedArrowChord(event)) return;
|
|
189
197
|
if (event.key === "Escape") {
|
|
190
|
-
if (event.
|
|
198
|
+
if (event.isComposing) return;
|
|
191
199
|
if (this.#pointer?.started) {
|
|
192
200
|
const { pointerType } = this.#pointer;
|
|
193
201
|
this.#teardownSessions();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/utils/detach_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ach\" discriminator for `disconnect()`.\n *\n * A mid-session `disconnect()` whose element is still in the document is\n * ambiguous. It can be:\n *\n * - an **in-page move** — a consumer (sortable, a teleport) re-inserted the\n * element; Stimulus reconnects the SAME instance in the same mutation batch\n * and the controller's runtime state must survive;\n * - a **detach that keeps the element** — `data-controller` no longer lists the\n * identifier (a Turbo 8 morph), or the element moved outside the observed\n * root (a scoped `Application.start(root)`, a shadow root); no reconnect will\n * ever come and the controller must tear down or it leaks its sessions,\n * document listeners, and moved nodes.\n *\n * Neither available signal decides this alone. A synchronous `data-controller`\n * token check catches the morph case but misses an observed-root exit (the\n * token stays, the reconnect never comes). Deferring teardown one microtask and\n * letting `connect()` cancel it catches the root exit, but leans on Stimulus\n * reconnecting moved elements within the same mutation batch — internal\n * behavior, not a public contract. {@link DetachGate} composes both: the token\n * check is the synchronous fast path (no probe, no reliance on batching), the\n * microtask probe is the fallback for the genuinely ambiguous remainder.\n *\n * Policy stays with the consumer (the `SafeTimeout` / `FocusTrap` lineage —\n * this util owns the discrimination only):\n *\n * - **Probe** ({@link disconnected}) when the teardown must eventually happen —\n * live drag sessions, document listeners, teleported *content*. Call\n * {@link cancel} from `connect()` (a reconnect means in-page move) and from\n * the head of any direct teardown path (see below).\n * - **Keep** (bare {@link DetachGate.isDetached}) when undoing the ambiguous\n * case would fight the controller's own effect: a controller that moves its\n * OWN element (portal's no-`content` form) exits a scoped observed root as\n * its normal job — a probe-driven teardown would restore the element into\n * the root, reconnect, re-teleport, and disconnect again, forever. Such\n * controllers keep their state on an ambiguous disconnect and tear down only\n * on {@link DetachGate.isDetached}.\n *\n * Event convention for probe consumers (pinned by `pointer_drag_controller.ts`\n * and its teardown contract): teardown into a dead (detached) tree is silent —\n * consumers restore from their own `connect()`; a detach that keeps the tree\n * alive must end an in-flight session with a `cancel` event, or composing\n * consumers strand their session bookkeeping.\n */\n\n/** The slice of a Stimulus controller the gate inspects. */\nexport interface DetachGateHost {\n readonly element: Element;\n readonly identifier: string;\n}\n\n/**\n * Per-controller-instance gate deciding whether a `disconnect()` is a real\n * detach. Hold one per controller (`#gate = new DetachGate()`) — Stimulus\n * reuses the instance across reconnects, so the pending probe state carries\n * over exactly as the protocol needs.\n *\n * @example\n * ```ts\n * #gate = new DetachGate();\n *\n * connect(): void {\n * this.#gate.cancel(); // a reconnect: the element moved in-page\n * // …\n * }\n *\n * disconnect(): void {\n * this.#gate.disconnected(this, () => this.#teardown());\n * }\n *\n * #teardown(): void {\n * this.#gate.cancel(); // disarm a still-queued probe (double-run guard)\n * // …\n * }\n * ```\n */\nexport class DetachGate {\n /** Set while a probe is queued, waiting for a reconnect to cancel it. */\n #pending = false;\n\n /**\n * True when the disconnect is definitely a real detach — the element left\n * the document, or `data-controller` no longer lists the identifier. False\n * means ambiguous (in-page move or observed-root exit), NOT \"alive\".\n */\n static isDetached(host: DetachGateHost): boolean {\n if (!host.element.isConnected) return true;\n const tokens = (host.element.getAttribute(\"data-controller\") ?? \"\").split(/\\s+/);\n return !tokens.includes(host.identifier);\n }\n\n /**\n * Call from `disconnect()`: runs `teardown` synchronously on a definite\n * detach (fast path), otherwise defers it one microtask — a reconnect\n * ({@link cancel} from `connect()`) keeps the state, no reconnect runs it.\n * One microtask is the whole probe window: Stimulus reconnects a moved\n * element within the same mutation batch, before the checkpoint drains.\n */\n disconnected(host: DetachGateHost, teardown: () => void): void {\n if (DetachGate.isDetached(host)) {\n // Also disarms a probe a previous ambiguous disconnect left queued\n // (defer, element removed, disconnect again) — exactly one teardown.\n this.#pending = false;\n teardown();\n return;\n }\n this.#pending = true;\n queueMicrotask(() => {\n if (!this.#pending) return;\n this.#pending = false;\n teardown();\n });\n }\n\n /**\n * Disarms a pending probe. Call from `connect()` (the reconnect that proves\n * an in-page move) and from the head of any teardown path not routed through\n * {@link disconnected} (disabled-toggle, Escape), so an orphaned probe can\n * never run the teardown a second time.\n */\n cancel(): void {\n this.#pending = false;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { DetachGate } from \"../utils/detach_gate\";\n\n/** How a drag session was initiated; surfaced in every event detail. */\ntype DragPointerType = \"mouse\" | \"touch\" | \"pen\" | \"keyboard\";\n\n/** A pointer drag in flight (from `pointerdown` until up/cancel). */\ninterface PointerSession {\n pointerId: number;\n handle: HTMLElement;\n originX: number;\n originY: number;\n /** True once the movement passed `threshold` and `start` was dispatched. */\n started: boolean;\n /** Last axis-filtered deltas, reported again by `end`. */\n dx: number;\n dy: number;\n pointerType: DragPointerType;\n}\n\n/** A keyboard \"grabbed\" session (Space/Enter on the handle until drop/cancel). */\ninterface KeyboardSession {\n handle: HTMLElement;\n /** Cumulative synthetic deltas accumulated by the arrow keys. */\n dx: number;\n dy: number;\n}\n\n/**\n * Headless **pointer-drag primitive**: a normalized pointer/touch/mouse drag\n * lifecycle with a built-in keyboard alternative. It deliberately does NOT decide\n * what a drag *means* (reorder, dismiss, resize…) — it only emits a clean,\n * accessibility-friendly drag signal that higher-level behaviors (sortable,\n * swipe-actions, bottom-sheet, split-pane…) compose from. No dedicated APG\n * pattern exists for drag-and-drop; the keyboard model below is the accepted\n * alternative-input technique (WCAG 2.1.1 / 2.5.7 Dragging Movements). Core\n * (zero dependencies).\n *\n * Markup contract (identifier: `stimeo--pointer-drag`):\n * <li data-controller=\"stimeo--pointer-drag\"\n * data-stimeo--pointer-drag-axis-value=\"y\">\n * <button data-stimeo--pointer-drag-target=\"handle\" aria-label=\"Reorder\">⠿</button>\n * </li>\n *\n * The `handle` target is optional — without one, the controller element itself\n * is the handle. Pointer flow: `pointerdown` on a handle arms the drag; once the\n * axis-filtered movement exceeds `threshold`, `start` fires, every subsequent\n * movement fires `move` (deltas cumulative from the origin), and release fires\n * `end` (`pointercancel` → `cancel`). Keyboard flow: Space/Enter on the handle\n * grabs (`start`, `data-grabbed`), the arrow keys emit synthetic `move` events of\n * `keyboardStep` px each, Space/Enter drops (`end`) and Escape cancels — so every\n * consumer gets a keyboard path for free.\n *\n * @remarks\n * Behavior only: consumers own all visuals (ghost, placeholder, transforms) by\n * reacting to the events and the `data-dragging` / `data-grabbed` hooks. The one\n * deliberate exception is the opt-in `follow` value for the \"just move the\n * element\" case: it applies the in-flight deltas to the element's CSS\n * `translate` (a property independent of `transform`, so authored transforms\n * survive), commits the offset on drop and restores it on cancel — the exact\n * boilerplate every simple consumer would otherwise re-write. With `follow` the\n * element's inline `translate` belongs to this controller (`connect()` re-reads\n * a previously committed `<x>px <y>px` offset, so Turbo restores stay\n * consistent). ARIA\n * 1.1 deprecated `aria-grabbed`/`aria-dropeffect`, so the grabbed state is\n * published as `data-grabbed` and the *meaning* of a drag must be announced by\n * the consumer (pair with `stimeo--announcer`). `touch-action` on the handles is\n * derived from `axis` (marker-guarded, authored values win) so the page does not\n * pan mid-drag. Deltas are physical (client coordinates): RTL semantics belong\n * to the consumer. `disconnect()` (Turbo navigation included) tears down any\n * active session — except across an in-page move, which the session survives\n * (the full lifecycle contract lives on `disconnect()`); `connect()` clears\n * stale hooks a Turbo cache restore may have preserved (a drag cannot survive\n * a navigation).\n */\nexport class PointerDragController extends Controller<HTMLElement> {\n static override targets = [\"handle\"];\n static override values = {\n axis: { type: String, default: \"both\" },\n threshold: { type: Number, default: 3 },\n keyboardStep: { type: Number, default: 10 },\n disabled: { type: Boolean, default: false },\n follow: { type: Boolean, default: false },\n };\n static events = [\"start\", \"move\", \"end\", \"cancel\"] as const;\n\n declare readonly handleTargets: HTMLElement[];\n declare readonly hasHandleTarget: boolean;\n declare axisValue: string;\n declare thresholdValue: number;\n declare keyboardStepValue: number;\n declare disabledValue: boolean;\n declare followValue: boolean;\n\n /** Marker attribute recording that this controller set the touch-action. */\n static readonly #TOUCH_ACTION_MARKER = \"data-pointer-drag-touch-action\";\n /** Marker attribute recording that this controller set `tabindex`. */\n static readonly #TABINDEX_MARKER = \"data-pointer-drag-tabindex\";\n\n #pointer: PointerSession | null = null;\n #keyboard: KeyboardSession | null = null;\n /** Committed follow offset from past drops; a new drag's deltas add onto it. */\n #followBase = { x: 0, y: 0 };\n /** Aborts in-progress pointer-drag listeners on drag end / teardown. */\n #dragAbort: AbortController | null = null;\n /** Decides whether a mid-session disconnect() is an in-page move or a detach. */\n readonly #gate = new DetachGate();\n\n override connect(): void {\n // A reconnect disarms the probe a mid-session disconnect() armed — the\n // element was moved in-page and the session survives (see disconnect).\n this.#gate.cancel();\n // Transient drag state cannot survive a navigation: clear hooks a Turbo\n // cache restore may have snapshotted mid-drag (idempotent reconnect). But a\n // session preserved across an in-page move keeps its hooks.\n if (!this.#pointer) this.element.removeAttribute(\"data-dragging\");\n if (!this.#keyboard) this.element.removeAttribute(\"data-grabbed\");\n // Follow mode owns the element's inline `translate`: re-read a committed\n // offset so reconnects (Turbo cache restore included) keep accumulating from\n // where the element visually sits. A session surviving an in-page move keeps\n // its base — mid-drag inline state must not be committed as a new base.\n if (this.followValue && !this.#pointer && !this.#keyboard) {\n this.#followBase = this.#parseFollowBase();\n }\n // Delegated on the container so dynamically added handles need no per-element\n // data-action (stimulus-lifecycle-turbo Rule A′).\n this.element.addEventListener(\"pointerdown\", this.#onPointerDown);\n this.element.addEventListener(\"keydown\", this.#onKeydown);\n if (!this.hasHandleTarget) this.#prepareHandle(this.element);\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"pointerdown\", this.#onPointerDown);\n this.element.removeEventListener(\"keydown\", this.#onKeydown);\n // A mid-session disconnect on a STILL-connected element is ambiguous: an\n // in-page move (a consumer like sortable re-inserts the item mid-grab —\n // Stimulus reconnects the same instance in the same mutation batch, and\n // the session must survive) vs a real detach that keeps the element\n // (`data-controller` removed, Turbo morph, element moved outside the\n // observed root). DetachGate discriminates: the token check is the\n // synchronous fast path (a morph's teardown — and its `cancel` — fires in\n // the same tick), the one-microtask probe cancelled by connect() covers\n // the rest — a detached-in-place controller never leaks its session or\n // document listeners. Probe only while a session needs protecting; an\n // idle controller tears down synchronously either way.\n if (this.#pointer || this.#keyboard) {\n this.#gate.disconnected(this, () => this.#teardown());\n return;\n }\n this.#teardown();\n }\n\n /** Prepares handles added at runtime (touch-action + focusability). */\n handleTargetConnected(handle: HTMLElement): void {\n this.#prepareHandle(handle);\n }\n\n handleTargetDisconnected(handle: HTMLElement): void {\n // A handle REMOVED mid-session can never deliver its keydown (the delegated\n // listener sits on the container it left), so the session would leak — and\n // the one-session guard would then reject every future pointerdown. End it\n // silently: the DOM is changing under the user, same as disconnect. But\n // target callbacks ALSO fire when the CONTROLLER disconnects (Stimulus\n // stops the target observer — including the in-page move a live session\n // must survive): a handle still inside the element was not removed, so\n // that case is left to disconnect()'s deferred probe.\n if (!this.element.contains(handle)) {\n if (this.#pointer?.handle === handle) this.#endPointerSession();\n if (this.#keyboard?.handle === handle) this.#clearKeyboardSession();\n }\n this.#restoreHandle(handle);\n }\n\n /** Re-derives the handles' touch-action when the axis changes. */\n axisValueChanged(): void {\n for (const handle of this.#handles()) {\n if (handle.hasAttribute(PointerDragController.#TOUCH_ACTION_MARKER)) {\n handle.style.touchAction = this.#touchActionForAxis();\n }\n }\n }\n\n /** Cancels any in-flight session when the controller is disabled mid-drag. */\n disabledValueChanged(): void {\n if (!this.disabledValue) return;\n if (this.#pointer?.started || this.#keyboard) {\n this.#dispatchCancel(this.#keyboard ? \"keyboard\" : (this.#pointer?.pointerType ?? \"mouse\"));\n }\n this.#teardownSessions();\n }\n\n /** Arms a pointer drag on a handle; `start` waits for the threshold. */\n readonly #onPointerDown = (event: PointerEvent): void => {\n // One session at a time: ignore a second pointerdown (multi-touch, an\n // errant tap, a grabbed keyboard session) so an in-flight drag is never\n // silently overwritten and its captured pointer orphaned.\n if (this.disabledValue || this.#pointer || this.#keyboard || event.button !== 0) return;\n const handle = this.#handleFor(event.target);\n if (!handle) return;\n\n // Suppress text selection / native image drag; restore the focus the\n // suppressed default would have given, so Escape and the keyboard path\n // stay reachable right after a pointer interaction (WCAG 2.1.1).\n event.preventDefault();\n handle.focus();\n\n this.#pointer = {\n pointerId: event.pointerId,\n handle,\n originX: event.clientX,\n originY: event.clientY,\n started: false,\n dx: 0,\n dy: 0,\n pointerType: this.#pointerTypeOf(event),\n };\n\n // Pointer capture keeps fast drags delivering to the handle even when the\n // pointer strays outside it — but a consumer may re-insert the dragged\n // element mid-drag (sortable's live reorder), which silently releases the\n // capture. Tracking listeners therefore live on the DOCUMENT (captured\n // events bubble there; uncaptured ones fire there anyway), and the\n // AbortController releases them on drag end and disconnect() (Turbo included).\n handle.setPointerCapture(event.pointerId);\n this.#dragAbort?.abort();\n const abort = new AbortController();\n this.#dragAbort = abort;\n document.addEventListener(\"pointermove\", this.#onPointerMove, { signal: abort.signal });\n document.addEventListener(\"pointerup\", this.#onPointerUp, { signal: abort.signal });\n document.addEventListener(\"pointercancel\", this.#onPointerCancel, { signal: abort.signal });\n };\n\n readonly #onPointerMove = (event: PointerEvent): void => {\n const session = this.#pointer;\n if (!session || event.pointerId !== session.pointerId) return;\n\n const [dx, dy] = this.#filterAxis(\n event.clientX - session.originX,\n event.clientY - session.originY,\n );\n if (!session.started) {\n if (Math.hypot(dx, dy) < this.thresholdValue) return;\n session.started = true;\n this.element.setAttribute(\"data-dragging\", \"true\");\n this.dispatch(\"start\", {\n detail: { x: event.clientX, y: event.clientY, pointerType: session.pointerType },\n });\n }\n\n session.dx = dx;\n session.dy = dy;\n this.#followMove(dx, dy);\n this.dispatch(\"move\", {\n detail: { dx, dy, x: event.clientX, y: event.clientY, pointerType: session.pointerType },\n });\n };\n\n readonly #onPointerUp = (event: PointerEvent): void => {\n const session = this.#pointer;\n if (!session || event.pointerId !== session.pointerId) return;\n const { started, dx, dy, pointerType } = session;\n this.#endPointerSession();\n // Below the threshold the gesture was a plain click, not a drag: stay silent.\n if (!started) return;\n this.#followCommit(dx, dy);\n this.dispatch(\"end\", { detail: { dx, dy, pointerType } });\n };\n\n /** OS gesture / scroll takeover interrupted the drag: cancel, don't drop. */\n readonly #onPointerCancel = (event: PointerEvent): void => {\n const session = this.#pointer;\n if (!session || event.pointerId !== session.pointerId) return;\n const { started, pointerType } = session;\n this.#endPointerSession();\n if (started) this.#dispatchCancel(pointerType);\n };\n\n /** Keyboard alternative: Space/Enter grab & drop, arrows move, Escape cancels. */\n readonly #onKeydown = (event: KeyboardEvent): void => {\n if (this.disabledValue) return;\n const handle = this.#handleFor(event.target);\n if (!handle) return;\n\n // Escape cancels whichever session is live (pointer drag or keyboard grab).\n if (event.key === \"Escape\") {\n // Layered-Escape rule 1: leave a press an inner handler already owned;\n // a press during IME composition steers the conversion, not the drag.\n if (event.defaultPrevented || event.isComposing) return;\n if (this.#pointer?.started) {\n const { pointerType } = this.#pointer;\n this.#teardownSessions();\n event.preventDefault();\n this.#dispatchCancel(pointerType);\n } else if (this.#keyboard) {\n this.#teardownSessions();\n event.preventDefault();\n this.#dispatchCancel(\"keyboard\");\n }\n return;\n }\n\n if (event.key === \" \" || event.key === \"Enter\") {\n // A live pointer drag owns the session: pressing Space mid-drag (the\n // pointerdown focused the handle) must not start a parallel grab.\n if (this.#pointer) return;\n event.preventDefault();\n if (this.#keyboard) this.#dropKeyboard();\n else this.#grabKeyboard(handle);\n return;\n }\n\n if (!this.#keyboard) return;\n const step = this.#keyboardDelta(event.key);\n if (!step) return;\n // Consume every arrow while grabbed (even on a locked axis) so the page\n // never scrolls mid-grab; only allowed-axis arrows emit a move.\n event.preventDefault();\n const [dx, dy] = this.#filterAxis(step[0], step[1]);\n if (dx === 0 && dy === 0) return;\n this.#keyboard.dx += dx;\n this.#keyboard.dy += dy;\n this.#followMove(this.#keyboard.dx, this.#keyboard.dy);\n this.dispatch(\"move\", {\n detail: {\n dx: this.#keyboard.dx,\n dy: this.#keyboard.dy,\n x: this.#keyboard.dx,\n y: this.#keyboard.dy,\n pointerType: \"keyboard\",\n },\n });\n };\n\n /** Enters the grabbed mode: `data-grabbed` on element + handle, then `start`. */\n #grabKeyboard(handle: HTMLElement): void {\n this.#keyboard = { handle, dx: 0, dy: 0 };\n this.element.setAttribute(\"data-grabbed\", \"true\");\n handle.setAttribute(\"data-grabbed\", \"true\");\n this.dispatch(\"start\", { detail: { x: 0, y: 0, pointerType: \"keyboard\" } });\n }\n\n #dropKeyboard(): void {\n const session = this.#keyboard;\n if (!session) return;\n this.#clearKeyboardSession();\n this.#followCommit(session.dx, session.dy);\n this.dispatch(\"end\", { detail: { dx: session.dx, dy: session.dy, pointerType: \"keyboard\" } });\n }\n\n /** Maps an arrow key to a raw (unfiltered) `keyboardStep` delta. */\n #keyboardDelta(key: string): [number, number] | null {\n const step = this.keyboardStepValue;\n switch (key) {\n case \"ArrowRight\":\n return [step, 0];\n case \"ArrowLeft\":\n return [-step, 0];\n case \"ArrowDown\":\n return [0, step];\n case \"ArrowUp\":\n return [0, -step];\n default:\n return null;\n }\n }\n\n /** Zeroes the delta on the locked axis (`axis` = x | y | both). */\n #filterAxis(dx: number, dy: number): [number, number] {\n if (this.axisValue === \"x\") return [dx, 0];\n if (this.axisValue === \"y\") return [0, dy];\n return [dx, dy];\n }\n\n /** Releases capture + listeners and clears the pointer session and its hook. */\n #endPointerSession(): void {\n this.#releasePointerCapture();\n this.#pointer = null;\n this.#dragAbort?.abort();\n this.#dragAbort = null;\n this.element.removeAttribute(\"data-dragging\");\n }\n\n /** Releases the pointer capture the active session set (idempotent, safe). */\n #releasePointerCapture(): void {\n const session = this.#pointer;\n if (session?.handle.hasPointerCapture(session.pointerId)) {\n session.handle.releasePointerCapture(session.pointerId);\n }\n }\n\n #clearKeyboardSession(): void {\n this.#keyboard?.handle.removeAttribute(\"data-grabbed\");\n this.#keyboard = null;\n this.element.removeAttribute(\"data-grabbed\");\n }\n\n /**\n * Full teardown for a controller whose element is going away or lost its\n * controller. Into a dead (detached) tree it is silent — consumers restore\n * from their own `connect()`, not from a cancel event. But a detach that\n * KEEPS the element (Turbo morph, `data-controller` removed) leaves the\n * consumers alive and listening: an in-flight session must end in `cancel`\n * there, or a composer like sortable strands its one-at-a-time session\n * bookkeeping forever.\n */\n #teardown(): void {\n // Disarm any probe still queued: without this, an immediate teardown\n // (element removed right after a deferring disconnect) would let the\n // orphaned probe run #teardown a second time — a double cancel.\n this.#gate.cancel();\n const interrupted = this.#pointer?.started\n ? this.#pointer.pointerType\n : this.#keyboard\n ? (\"keyboard\" as const)\n : null;\n this.#teardownSessions();\n for (const handle of this.#handles()) this.#restoreHandle(handle);\n if (interrupted && this.element.isConnected) this.#dispatchCancel(interrupted);\n }\n\n /**\n * Silently tears down whatever session is live (disconnect / disabled /\n * Escape). Composed from the two single-session teardowns so pointer and\n * keyboard cleanup cannot diverge as either path evolves.\n */\n #teardownSessions(): void {\n this.#endPointerSession();\n this.#clearKeyboardSession();\n }\n\n #dispatchCancel(pointerType: DragPointerType): void {\n // Every cancel path funnels here, so follow's snap-back can never be missed\n // (Escape, pointercancel, mid-session disable, detach-that-keeps-the-element).\n this.#followReset();\n this.dispatch(\"cancel\", { detail: { pointerType } });\n }\n\n /** Applies the in-flight offset to the element's `translate` (follow only). */\n #followMove(dx: number, dy: number): void {\n if (!this.followValue) return;\n this.#applyFollow(this.#followBase.x + dx, this.#followBase.y + dy);\n }\n\n /** Folds a drop's deltas into the committed base offset (follow only). */\n #followCommit(dx: number, dy: number): void {\n if (!this.followValue) return;\n this.#followBase = { x: this.#followBase.x + dx, y: this.#followBase.y + dy };\n this.#applyFollow(this.#followBase.x, this.#followBase.y);\n }\n\n /** Snaps back to the committed position (follow only) — the cancel contract. */\n #followReset(): void {\n if (!this.followValue) return;\n this.#applyFollow(this.#followBase.x, this.#followBase.y);\n }\n\n /**\n * Writes the offset as the standalone CSS `translate` property — independent\n * of `transform`, so an authored transform (scale, rotate…) is never\n * clobbered. At the origin the property is removed to keep the DOM clean.\n */\n #applyFollow(x: number, y: number): void {\n if (x === 0 && y === 0) this.element.style.removeProperty(\"translate\");\n else this.element.style.setProperty(\"translate\", `${x}px ${y}px`);\n }\n\n /**\n * Reads a committed follow offset back from the inline `translate`. Only the\n * controller's own `<x>px <y>px` shape is recognized; anything else (an\n * authored percentage, `none`, an empty string) starts the base at 0 — follow\n * mode owns this property, per the class contract.\n */\n #parseFollowBase(): { x: number; y: number } {\n const raw = this.element.style.getPropertyValue(\"translate\").trim();\n const match = /^(-?\\d+(?:\\.\\d+)?)px(?:\\s+(-?\\d+(?:\\.\\d+)?)px)?$/.exec(raw);\n if (!match) return { x: 0, y: 0 };\n return { x: Number(match[1]), y: Number(match[2] ?? \"0\") };\n }\n\n /** The active handles: the `handle` targets, else the element itself. */\n #handles(): HTMLElement[] {\n return this.hasHandleTarget ? this.handleTargets : [this.element];\n }\n\n /** Resolves the handle owning an event target (the handle or a descendant). */\n #handleFor(target: EventTarget | null): HTMLElement | null {\n const node = target as Node | null;\n if (!node) return null;\n return this.#handles().find((handle) => handle === node || handle.contains(node)) ?? null;\n }\n\n #pointerTypeOf(event: PointerEvent): DragPointerType {\n const type = event.pointerType;\n if (type === \"touch\" || type === \"pen\") return type;\n return \"mouse\";\n }\n\n /** `touch-action` that lets the page keep panning on the locked axis only. */\n #touchActionForAxis(): string {\n if (this.axisValue === \"x\") return \"pan-y\";\n if (this.axisValue === \"y\") return \"pan-x\";\n return \"none\";\n }\n\n /**\n * Establishes the handle contract: a `touch-action` derived from `axis`\n * (marker-guarded so an authored inline value wins and reconnects stay\n * idempotent) and focusability for the keyboard path (`tabindex=\"0\"` only when\n * the author supplied none — prefer a real `<button>` handle). Both additions\n * are marker-owned so `#restoreHandle` reverts them symmetrically on teardown.\n */\n #prepareHandle(handle: HTMLElement): void {\n if (\n handle.style.touchAction === \"\" ||\n handle.hasAttribute(PointerDragController.#TOUCH_ACTION_MARKER)\n ) {\n handle.style.touchAction = this.#touchActionForAxis();\n handle.setAttribute(PointerDragController.#TOUCH_ACTION_MARKER, \"true\");\n }\n if (handle.tabIndex < 0 && !handle.hasAttribute(\"tabindex\")) {\n handle.setAttribute(\"tabindex\", \"0\");\n handle.setAttribute(PointerDragController.#TABINDEX_MARKER, \"true\");\n }\n }\n\n /** Reverts the marker-owned touch-action + tabindex (authored values untouched). */\n #restoreHandle(handle: HTMLElement): void {\n if (handle.hasAttribute(PointerDragController.#TOUCH_ACTION_MARKER)) {\n handle.style.touchAction = \"\";\n handle.removeAttribute(PointerDragController.#TOUCH_ACTION_MARKER);\n }\n if (handle.hasAttribute(PointerDragController.#TABINDEX_MARKER)) {\n handle.removeAttribute(PointerDragController.#TABINDEX_MARKER);\n // Only remove what is verifiably still ours and safe to remove: another\n // owner (e.g. a roving list) may have rewritten the value since, and\n // stripping tabindex off the focused element would blur it to <body>\n // (losing the user's place — worse than leaking one tab stop).\n if (handle.getAttribute(\"tabindex\") === \"0\" && document.activeElement !== handle) {\n handle.removeAttribute(\"tabindex\");\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/utils/arrow_step.ts","../../src/utils/detach_gate.ts","../../src/controllers/pointer_drag_controller.ts"],"names":[],"mappings":";;;;;AA+FO,SAAS,oBAAA,CACd,KAAA,EACA,KAAA,GAAkC,EAAC,EAC1B;AACT,EAAA,IAAI,CAAC,KAAA,CAAM,GAAA,CAAI,UAAA,CAAW,OAAO,GAAG,OAAO,KAAA;AAC3C,EAAA,OACG,KAAA,CAAM,MAAA,IAAU,CAAC,KAAA,CAAM,QAAA,CAAS,KAAK,CAAA,IACrC,KAAA,CAAM,OAAA,IAAW,CAAC,KAAA,CAAM,QAAA,CAAS,MAAM,KACvC,KAAA,CAAM,OAAA,IAAW,CAAC,KAAA,CAAM,QAAA,CAAS,MAAM,CAAA,IACvC,KAAA,CAAM,QAAA,IAAY,CAAC,KAAA,CAAM,QAAA,CAAS,OAAO,CAAA;AAE9C;;;AC9BO,IAAM,UAAA,GAAN,MAAM,WAAA,CAAW;AAAA;AAAA,EAEtB,QAAA,GAAW,KAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOX,OAAO,WAAW,IAAA,EAA+B;AAC/C,IAAA,IAAI,CAAC,IAAA,CAAK,OAAA,CAAQ,WAAA,EAAa,OAAO,IAAA;AACtC,IAAA,MAAM,MAAA,GAAA,CAAU,KAAK,OAAA,CAAQ,YAAA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,mBAAA,EAAoB;AACpD,MAAA,MAAA,CAAO,YAAA,CAAa,sBAAA,CAAsB,oBAAA,EAAsB,MAAM,CAAA;AAAA,IACxE;AACA,IAAA,IAAI,OAAO,QAAA,GAAW,CAAA,IAAK,CAAC,MAAA,CAAO,YAAA,CAAa,UAAU,CAAA,EAAG;AAC3D,MAAA,MAAA,CAAO,YAAA,CAAa,YAAY,GAAG,CAAA;AACnC,MAAA,MAAA,CAAO,YAAA,CAAa,sBAAA,CAAsB,gBAAA,EAAkB,MAAM,CAAA;AAAA,IACpE;AAAA,EACF;AAAA;AAAA,EAGA,eAAe,MAAA,EAA2B;AACxC,IAAA,IAAI,MAAA,CAAO,YAAA,CAAa,sBAAA,CAAsB,oBAAoB,CAAA,EAAG;AACnE,MAAA,MAAA,CAAO,MAAM,WAAA,GAAc,EAAA;AAC3B,MAAA,MAAA,CAAO,eAAA,CAAgB,uBAAsB,oBAAoB,CAAA;AAAA,IACnE;AACA,IAAA,IAAI,MAAA,CAAO,YAAA,CAAa,sBAAA,CAAsB,gBAAgB,CAAA,EAAG;AAC/D,MAAA,MAAA,CAAO,eAAA,CAAgB,uBAAsB,gBAAgB,CAAA;AAK7D,MAAA,IAAI,OAAO,YAAA,CAAa,UAAU,MAAM,GAAA,IAAO,QAAA,CAAS,kBAAkB,MAAA,EAAQ;AAChF,QAAA,MAAA,CAAO,gBAAgB,UAAU,CAAA;AAAA,MACnC;AAAA,IACF;AAAA,EACF;AACF","file":"pointer_drag_controller.js","sourcesContent":["import { isRtl } from \"./logical_scroll\";\n\n/**\n * Turns an arrow key into a **logical** step: `+1` for \"next\", `-1` for\n * \"previous\", `0` when the key names neither.\n *\n * APG defines the horizontal pair as *next / previous* and says a vertical\n * arrangement swaps in Down/Up for the same meaning — so the pair is one axis's\n * spelling of an order, and the order reverses with the writing direction. Only\n * the horizontal pair reverses. Down/Up name an axis the writing direction does\n * not mirror, and returning them unchanged is the point: many controllers fold\n * both pairs into one branch, where swapping the branches under RTL would flip\n * the vertical axis too — a bug that reads as \"the arrows work\" until someone\n * presses Down.\n *\n * **Direction is read from the element the caller passes, which should be the\n * container that lays the items out** — not the focused child. A child may carry\n * its own `dir` (an LTR input inside an RTL form is ordinary authoring), and\n * probing per handler makes two handlers disagree at the boundary between them.\n *\n * This decides direction only. Whether the axis is even active (an\n * `orientation=\"horizontal\"` widget ignoring Down/Up), how far the step lands,\n * and what wrapping does all stay with the caller.\n *\n * **It encodes the list-order convention: `ArrowDown` is *next*.** Widgets that\n * pair the arrows by *value* instead — `ArrowUp` meaning \"more\", as a rating or a\n * slider does — must not use this, or their vertical axis inverts. Reverse the\n * horizontal pair on its own there.\n *\n * @example\n * ```ts\n * const step = logicalArrowStep(event.key, this.element);\n * if (step === 0) return;\n * this.#roving.setActive(rovingMove(current, length, step, \"wrap\"), { focus: true });\n * ```\n */\nexport function logicalArrowStep(key: string, element: Element): 1 | -1 | 0 {\n if (key === \"ArrowDown\") return 1;\n if (key === \"ArrowUp\") return -1;\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return 0;\n const forward = isRtl(element) ? \"ArrowLeft\" : \"ArrowRight\";\n return key === forward ? 1 : -1;\n}\n\n/**\n * Rewrites `key` so an existing LTR-shaped branch keeps working under RTL:\n * `ArrowRight` and `ArrowLeft` trade places, everything else passes through.\n *\n * The alternative — negating a delta — silently breaks handlers whose two\n * horizontal branches are **not mirror images**. A grid that clamps one edge but\n * not the other, or a segmented field guarding `index > 0` on one side and\n * `index < length - 1` on the other, ends up applying the wrong guard to the\n * wrong direction. Swapping the key leaves each branch, guards and all, exactly\n * where its author put it.\n *\n * Same rule as {@link logicalArrowStep} about which element to read: pass the\n * container that lays the items out, not the focused child.\n *\n * @example\n * ```ts\n * switch (logicalArrowKey(event.key, this.element)) {\n * case \"ArrowLeft\": // \"previous\" — whatever direction that is on screen\n * ```\n */\nexport function logicalArrowKey(key: string, element: Element): string {\n if (key !== \"ArrowRight\" && key !== \"ArrowLeft\") return key;\n if (!isRtl(element)) return key;\n return key === \"ArrowRight\" ? \"ArrowLeft\" : \"ArrowRight\";\n}\n\n/** Modifiers a widget may claim on an arrow key, named for the `allow` list. */\nexport type ArrowModifier = \"alt\" | \"ctrl\" | \"meta\" | \"shift\";\n\n/**\n * True when an arrow key arrived carrying a modifier the widget must leave to\n * the browser: return without calling `preventDefault()` and without moving any\n * state.\n *\n * A bare arrow belongs to the widget; a chorded one usually does not.\n * `Alt`/`Meta` plus a horizontal arrow is history back/forward on every desktop\n * browser, and a widget that swallows it makes the shortcut work or not\n * depending on where focus happens to sit — a coin-flip the user cannot see.\n *\n * `allow` is for the combinations APG assigns to a pattern **and the widget\n * actually implements** — today only Combobox's optional `Alt+Down`/`Alt+Up`.\n * Listing one the widget does not implement defeats the point: the chord then\n * runs the plain-arrow branch, which is exactly what this guard exists to stop.\n * Non-arrow keys return `false`, so chorded letters and\n * `Control+Home`/`Control+End` are untouched.\n *\n * @example\n * ```ts\n * if (isReservedArrowChord(event)) return;\n * ```\n */\nexport function isReservedArrowChord(\n event: KeyboardEvent,\n allow: readonly ArrowModifier[] = [],\n): boolean {\n if (!event.key.startsWith(\"Arrow\")) return false;\n return (\n (event.altKey && !allow.includes(\"alt\")) ||\n (event.ctrlKey && !allow.includes(\"ctrl\")) ||\n (event.metaKey && !allow.includes(\"meta\")) ||\n (event.shiftKey && !allow.includes(\"shift\"))\n );\n}\n","/**\n * Shared \"in-page move vs real detach\" discriminator for `disconnect()`.\n *\n * A mid-session `disconnect()` whose element is still in the document is\n * ambiguous. It can be:\n *\n * - an **in-page move** — a consumer (sortable, a teleport) re-inserted the\n * element; Stimulus reconnects the SAME instance in the same mutation batch\n * and the controller's runtime state must survive;\n * - a **detach that keeps the element** — `data-controller` no longer lists the\n * identifier (a Turbo 8 morph), or the element moved outside the observed\n * root (a scoped `Application.start(root)`, a shadow root); no reconnect will\n * ever come and the controller must tear down or it leaks its sessions,\n * document listeners, and moved nodes.\n *\n * Neither available signal decides this alone. A synchronous `data-controller`\n * token check catches the morph case but misses an observed-root exit (the\n * token stays, the reconnect never comes). Deferring teardown one microtask and\n * letting `connect()` cancel it catches the root exit, but leans on Stimulus\n * reconnecting moved elements within the same mutation batch — internal\n * behavior, not a public contract. {@link DetachGate} composes both: the token\n * check is the synchronous fast path (no probe, no reliance on batching), the\n * microtask probe is the fallback for the genuinely ambiguous remainder.\n *\n * Policy stays with the consumer (the `SafeTimeout` / `FocusTrap` lineage —\n * this util owns the discrimination only):\n *\n * - **Probe** ({@link disconnected}) when the teardown must eventually happen —\n * live drag sessions, document listeners, teleported *content*. Call\n * {@link cancel} from `connect()` (a reconnect means in-page move) and from\n * the head of any direct teardown path (see below).\n * - **Keep** (bare {@link DetachGate.isDetached}) when undoing the ambiguous\n * case would fight the controller's own effect: a controller that moves its\n * OWN element (portal's no-`content` form) exits a scoped observed root as\n * its normal job — a probe-driven teardown would restore the element into\n * the root, reconnect, re-teleport, and disconnect again, forever. Such\n * controllers keep their state on an ambiguous disconnect and tear down only\n * on {@link DetachGate.isDetached}.\n *\n * Event convention for probe consumers: teardown into a dead (detached) tree is\n * silent — consumers restore from their own `connect()`; a detach that keeps the\n * tree alive must end an in-flight session with a `cancel` event, or composing\n * consumers strand their session bookkeeping.\n */\n\n/** The slice of a Stimulus controller the gate inspects. */\nexport interface DetachGateHost {\n readonly element: Element;\n readonly identifier: string;\n}\n\n/**\n * Per-controller-instance gate deciding whether a `disconnect()` is a real\n * detach. Hold one per controller (`#gate = new DetachGate()`) — Stimulus\n * reuses the instance across reconnects, so the pending probe state carries\n * over exactly as the protocol needs.\n *\n * @example\n * ```ts\n * #gate = new DetachGate();\n *\n * connect(): void {\n * this.#gate.cancel(); // a reconnect: the element moved in-page\n * // …\n * }\n *\n * disconnect(): void {\n * this.#gate.disconnected(this, () => this.#teardown());\n * }\n *\n * #teardown(): void {\n * this.#gate.cancel(); // disarm a still-queued probe (double-run guard)\n * // …\n * }\n * ```\n */\nexport class DetachGate {\n /** Set while a probe is queued, waiting for a reconnect to cancel it. */\n #pending = false;\n\n /**\n * True when the disconnect is definitely a real detach — the element left\n * the document, or `data-controller` no longer lists the identifier. False\n * means ambiguous (in-page move or observed-root exit), NOT \"alive\".\n */\n static isDetached(host: DetachGateHost): boolean {\n if (!host.element.isConnected) return true;\n const tokens = (host.element.getAttribute(\"data-controller\") ?? \"\").split(/\\s+/);\n return !tokens.includes(host.identifier);\n }\n\n /**\n * Call from `disconnect()`: runs `teardown` synchronously on a definite\n * detach (fast path), otherwise defers it one microtask — a reconnect\n * ({@link cancel} from `connect()`) keeps the state, no reconnect runs it.\n * One microtask is the whole probe window: Stimulus reconnects a moved\n * element within the same mutation batch, before the checkpoint drains.\n */\n disconnected(host: DetachGateHost, teardown: () => void): void {\n if (DetachGate.isDetached(host)) {\n // Also disarms a probe a previous ambiguous disconnect left queued\n // (defer, element removed, disconnect again) — exactly one teardown.\n this.#pending = false;\n teardown();\n return;\n }\n this.#pending = true;\n queueMicrotask(() => {\n if (!this.#pending) return;\n this.#pending = false;\n teardown();\n });\n }\n\n /**\n * Disarms a pending probe. Call from `connect()` (the reconnect that proves\n * an in-page move) and from the head of any teardown path not routed through\n * {@link disconnected} (disabled-toggle, Escape), so an orphaned probe can\n * never run the teardown a second time.\n */\n cancel(): void {\n this.#pending = false;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { isReservedArrowChord } from \"../utils/arrow_step\";\nimport { DetachGate } from \"../utils/detach_gate\";\n\n/** How a drag session was initiated; surfaced in every event detail. */\ntype DragPointerType = \"mouse\" | \"touch\" | \"pen\" | \"keyboard\";\n\n/** A pointer drag in flight (from `pointerdown` until up/cancel). */\ninterface PointerSession {\n pointerId: number;\n handle: HTMLElement;\n originX: number;\n originY: number;\n /** True once the movement passed `threshold` and `start` was dispatched. */\n started: boolean;\n /** Last axis-filtered deltas, reported again by `end`. */\n dx: number;\n dy: number;\n pointerType: DragPointerType;\n}\n\n/** A keyboard \"grabbed\" session (Space/Enter on the handle until drop/cancel). */\ninterface KeyboardSession {\n handle: HTMLElement;\n /** Cumulative synthetic deltas accumulated by the arrow keys. */\n dx: number;\n dy: number;\n}\n\n/**\n * Headless **pointer-drag primitive**: a normalized pointer/touch/mouse drag\n * lifecycle with a built-in keyboard alternative. It deliberately does NOT decide\n * what a drag *means* (reorder, dismiss, resize…) — it only emits a clean,\n * accessibility-friendly drag signal that higher-level behaviors (sortable,\n * swipe-actions, bottom-sheet, split-pane…) compose from. No dedicated APG\n * pattern exists for drag-and-drop; the keyboard model below is the accepted\n * alternative-input technique (WCAG 2.1.1 / 2.5.7 Dragging Movements). Core\n * (zero dependencies).\n *\n * Markup contract (identifier: `stimeo--pointer-drag`):\n * <li data-controller=\"stimeo--pointer-drag\"\n * data-stimeo--pointer-drag-axis-value=\"y\">\n * <button data-stimeo--pointer-drag-target=\"handle\" aria-label=\"Reorder\">⠿</button>\n * </li>\n *\n * The `handle` target is optional — without one, the controller element itself\n * is the handle. Pointer flow: `pointerdown` on a handle arms the drag; once the\n * axis-filtered movement exceeds `threshold`, `start` fires, every subsequent\n * movement fires `move` (deltas cumulative from the origin), and release fires\n * `end` (`pointercancel` → `cancel`). Keyboard flow: Space/Enter on the handle\n * grabs (`start`, `data-grabbed`), the arrow keys emit synthetic `move` events of\n * `keyboardStep` px each, Space/Enter drops (`end`) and Escape cancels — so every\n * consumer gets a keyboard path for free.\n *\n * @remarks\n * Behavior only: consumers own all visuals (ghost, placeholder, transforms) by\n * reacting to the events and the `data-dragging` / `data-grabbed` hooks. The one\n * deliberate exception is the opt-in `follow` value for the \"just move the\n * element\" case: it applies the in-flight deltas to the element's CSS\n * `translate` (a property independent of `transform`, so authored transforms\n * survive), commits the offset on drop and restores it on cancel — the exact\n * boilerplate every simple consumer would otherwise re-write. With `follow` the\n * element's inline `translate` belongs to this controller (`connect()` re-reads\n * a committed `<x>px <y>px` offset, so Turbo restores stay consistent). ARIA 1.1\n * deprecated `aria-grabbed`/`aria-dropeffect`, so the grabbed state is\n * published as `data-grabbed` and the *meaning* of a drag must be announced by\n * the consumer (pair with `stimeo--announcer`). `touch-action` on the handles is\n * derived from `axis` (marker-guarded, authored values win) so the page does not\n * pan mid-drag. Deltas are physical (client coordinates): RTL semantics belong\n * to the consumer. `disconnect()` (Turbo navigation included) tears down any\n * active session — except across an in-page move, which the session survives\n * (the full lifecycle contract lives on `disconnect()`); `connect()` clears\n * stale hooks a Turbo cache restore may have preserved (a drag cannot survive\n * a navigation).\n */\nexport class PointerDragController extends Controller<HTMLElement> {\n static override targets = [\"handle\"];\n static override values = {\n axis: { type: String, default: \"both\" },\n threshold: { type: Number, default: 3 },\n keyboardStep: { type: Number, default: 10 },\n disabled: { type: Boolean, default: false },\n follow: { type: Boolean, default: false },\n };\n static events = [\"start\", \"move\", \"end\", \"cancel\"] as const;\n\n declare readonly handleTargets: HTMLElement[];\n declare readonly hasHandleTarget: boolean;\n declare axisValue: string;\n declare thresholdValue: number;\n declare keyboardStepValue: number;\n declare disabledValue: boolean;\n declare followValue: boolean;\n\n /** Marker attribute recording that this controller set the touch-action. */\n static readonly #TOUCH_ACTION_MARKER = \"data-pointer-drag-touch-action\";\n /** Marker attribute recording that this controller set `tabindex`. */\n static readonly #TABINDEX_MARKER = \"data-pointer-drag-tabindex\";\n\n #pointer: PointerSession | null = null;\n #keyboard: KeyboardSession | null = null;\n /** Committed follow offset from past drops; a new drag's deltas add onto it. */\n #followBase = { x: 0, y: 0 };\n /** Aborts in-progress pointer-drag listeners on drag end / teardown. */\n #dragAbort: AbortController | null = null;\n /** Decides whether a mid-session disconnect() is an in-page move or a detach. */\n readonly #gate = new DetachGate();\n\n override connect(): void {\n // A reconnect disarms the probe a mid-session disconnect() armed — the\n // element was moved in-page and the session survives (see disconnect).\n this.#gate.cancel();\n // Transient drag state cannot survive a navigation: clear hooks a Turbo\n // cache restore may have snapshotted mid-drag (idempotent reconnect). But a\n // session preserved across an in-page move keeps its hooks.\n if (!this.#pointer) this.element.removeAttribute(\"data-dragging\");\n if (!this.#keyboard) this.element.removeAttribute(\"data-grabbed\");\n // Follow mode owns the element's inline `translate`: re-read a committed\n // offset so reconnects (Turbo cache restore included) keep accumulating from\n // where the element visually sits. A session surviving an in-page move keeps\n // its base — mid-drag inline state must not be committed as a new base.\n if (this.followValue && !this.#pointer && !this.#keyboard) {\n this.#followBase = this.#parseFollowBase();\n }\n // Delegated on the container so dynamically added handles need no per-element\n // data-action.\n this.element.addEventListener(\"pointerdown\", this.#onPointerDown);\n this.element.addEventListener(\"keydown\", this.#onKeydown);\n if (!this.hasHandleTarget) this.#prepareHandle(this.element);\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"pointerdown\", this.#onPointerDown);\n this.element.removeEventListener(\"keydown\", this.#onKeydown);\n // A mid-session disconnect on a STILL-connected element is ambiguous: an\n // in-page move (a consumer like sortable re-inserts the item mid-grab —\n // Stimulus reconnects the same instance in the same mutation batch, and\n // the session must survive) vs a real detach that keeps the element\n // (`data-controller` removed, Turbo morph, element moved outside the\n // observed root). DetachGate discriminates: the token check is the\n // synchronous fast path (a morph's teardown — and its `cancel` — fires in\n // the same tick), the one-microtask probe cancelled by connect() covers\n // the rest — a detached-in-place controller never leaks its session or\n // document listeners. Probe only while a session needs protecting; an\n // idle controller tears down synchronously either way.\n if (this.#pointer || this.#keyboard) {\n this.#gate.disconnected(this, () => this.#teardown());\n return;\n }\n this.#teardown();\n }\n\n /** Prepares handles added at runtime (touch-action + focusability). */\n handleTargetConnected(handle: HTMLElement): void {\n this.#prepareHandle(handle);\n }\n\n handleTargetDisconnected(handle: HTMLElement): void {\n // A handle REMOVED mid-session can never deliver its keydown (the delegated\n // listener sits on the container it left), so the session would leak — and\n // the one-session guard would then reject every future pointerdown. End it\n // silently: the DOM is changing under the user, same as disconnect. But\n // target callbacks ALSO fire when the CONTROLLER disconnects (Stimulus\n // stops the target observer — including the in-page move a live session\n // must survive): a handle still inside the element was not removed, so\n // that case is left to disconnect()'s deferred probe.\n if (!this.element.contains(handle)) {\n if (this.#pointer?.handle === handle) this.#endPointerSession();\n if (this.#keyboard?.handle === handle) this.#clearKeyboardSession();\n }\n this.#restoreHandle(handle);\n }\n\n /** Re-derives the handles' touch-action when the axis changes. */\n axisValueChanged(): void {\n for (const handle of this.#handles()) {\n if (handle.hasAttribute(PointerDragController.#TOUCH_ACTION_MARKER)) {\n handle.style.touchAction = this.#touchActionForAxis();\n }\n }\n }\n\n /** Cancels any in-flight session when the controller is disabled mid-drag. */\n disabledValueChanged(): void {\n if (!this.disabledValue) return;\n if (this.#pointer?.started || this.#keyboard) {\n this.#dispatchCancel(this.#keyboard ? \"keyboard\" : (this.#pointer?.pointerType ?? \"mouse\"));\n }\n this.#teardownSessions();\n }\n\n /** Arms a pointer drag on a handle; `start` waits for the threshold. */\n readonly #onPointerDown = (event: PointerEvent): void => {\n // One session at a time: ignore a second pointerdown (multi-touch, an\n // errant tap, a grabbed keyboard session) so an in-flight drag is never\n // silently overwritten and its captured pointer orphaned.\n if (this.disabledValue || this.#pointer || this.#keyboard || event.button !== 0) return;\n const handle = this.#handleFor(event.target);\n if (!handle) return;\n\n // Suppress text selection / native image drag; restore the focus the\n // suppressed default would have given, so Escape and the keyboard path\n // stay reachable right after a pointer interaction (WCAG 2.1.1).\n event.preventDefault();\n handle.focus();\n\n this.#pointer = {\n pointerId: event.pointerId,\n handle,\n originX: event.clientX,\n originY: event.clientY,\n started: false,\n dx: 0,\n dy: 0,\n pointerType: this.#pointerTypeOf(event),\n };\n\n // Pointer capture keeps fast drags delivering to the handle even when the\n // pointer strays outside it — but a consumer may re-insert the dragged\n // element mid-drag (sortable's live reorder), which silently releases the\n // capture. Tracking listeners therefore live on the DOCUMENT (captured\n // events bubble there; uncaptured ones fire there anyway), and the\n // AbortController releases them on drag end and disconnect() (Turbo included).\n handle.setPointerCapture(event.pointerId);\n this.#dragAbort?.abort();\n const abort = new AbortController();\n this.#dragAbort = abort;\n document.addEventListener(\"pointermove\", this.#onPointerMove, { signal: abort.signal });\n document.addEventListener(\"pointerup\", this.#onPointerUp, { signal: abort.signal });\n document.addEventListener(\"pointercancel\", this.#onPointerCancel, { signal: abort.signal });\n };\n\n readonly #onPointerMove = (event: PointerEvent): void => {\n const session = this.#pointer;\n if (!session || event.pointerId !== session.pointerId) return;\n\n const [dx, dy] = this.#filterAxis(\n event.clientX - session.originX,\n event.clientY - session.originY,\n );\n if (!session.started) {\n if (Math.hypot(dx, dy) < this.thresholdValue) return;\n session.started = true;\n this.element.setAttribute(\"data-dragging\", \"true\");\n this.dispatch(\"start\", {\n detail: { x: event.clientX, y: event.clientY, pointerType: session.pointerType },\n });\n }\n\n session.dx = dx;\n session.dy = dy;\n this.#followMove(dx, dy);\n this.dispatch(\"move\", {\n detail: { dx, dy, x: event.clientX, y: event.clientY, pointerType: session.pointerType },\n });\n };\n\n readonly #onPointerUp = (event: PointerEvent): void => {\n const session = this.#pointer;\n if (!session || event.pointerId !== session.pointerId) return;\n const { started, dx, dy, pointerType } = session;\n this.#endPointerSession();\n // Below the threshold the gesture was a plain click, not a drag: stay silent.\n if (!started) return;\n this.#followCommit(dx, dy);\n this.dispatch(\"end\", { detail: { dx, dy, pointerType } });\n };\n\n /** OS gesture / scroll takeover interrupted the drag: cancel, don't drop. */\n readonly #onPointerCancel = (event: PointerEvent): void => {\n const session = this.#pointer;\n if (!session || event.pointerId !== session.pointerId) return;\n const { started, pointerType } = session;\n this.#endPointerSession();\n if (started) this.#dispatchCancel(pointerType);\n };\n\n /** Keyboard alternative: Space/Enter grab & drop, arrows move, Escape cancels. */\n readonly #onKeydown = (event: KeyboardEvent): void => {\n if (this.disabledValue) return;\n const handle = this.#handleFor(event.target);\n if (!handle) return;\n\n // A descendant widget that already claimed the key (a nested roving list, a\n // segmented field inside the handle) must not ALSO drive the drag —\n // composition depends on this yield. This controller is the \"grabbed drag\n // handle\" that the other yields name as the widget they defer to, so it owes\n // the same courtesy downward.\n if (event.defaultPrevented) return;\n // A chorded arrow belongs to the browser. \"Someone already consumed it\"\n // outranks that, so it is checked after the yield above.\n if (isReservedArrowChord(event)) return;\n\n // Escape cancels whichever session is live (pointer drag or keyboard grab).\n if (event.key === \"Escape\") {\n // A press an inner handler already owned is yielded at the top of this\n // handler. What is checked here is the IME half: a press during a\n // composition steers the conversion, not the drag.\n if (event.isComposing) return;\n if (this.#pointer?.started) {\n const { pointerType } = this.#pointer;\n this.#teardownSessions();\n event.preventDefault();\n this.#dispatchCancel(pointerType);\n } else if (this.#keyboard) {\n this.#teardownSessions();\n event.preventDefault();\n this.#dispatchCancel(\"keyboard\");\n }\n return;\n }\n\n if (event.key === \" \" || event.key === \"Enter\") {\n // A live pointer drag owns the session: pressing Space mid-drag (the\n // pointerdown focused the handle) must not start a parallel grab.\n if (this.#pointer) return;\n event.preventDefault();\n if (this.#keyboard) this.#dropKeyboard();\n else this.#grabKeyboard(handle);\n return;\n }\n\n if (!this.#keyboard) return;\n const step = this.#keyboardDelta(event.key);\n if (!step) return;\n // Consume every arrow while grabbed (even on a locked axis) so the page\n // never scrolls mid-grab; only allowed-axis arrows emit a move.\n event.preventDefault();\n const [dx, dy] = this.#filterAxis(step[0], step[1]);\n if (dx === 0 && dy === 0) return;\n this.#keyboard.dx += dx;\n this.#keyboard.dy += dy;\n this.#followMove(this.#keyboard.dx, this.#keyboard.dy);\n this.dispatch(\"move\", {\n detail: {\n dx: this.#keyboard.dx,\n dy: this.#keyboard.dy,\n x: this.#keyboard.dx,\n y: this.#keyboard.dy,\n pointerType: \"keyboard\",\n },\n });\n };\n\n /** Enters the grabbed mode: `data-grabbed` on element + handle, then `start`. */\n #grabKeyboard(handle: HTMLElement): void {\n this.#keyboard = { handle, dx: 0, dy: 0 };\n this.element.setAttribute(\"data-grabbed\", \"true\");\n handle.setAttribute(\"data-grabbed\", \"true\");\n this.dispatch(\"start\", { detail: { x: 0, y: 0, pointerType: \"keyboard\" } });\n }\n\n #dropKeyboard(): void {\n const session = this.#keyboard;\n if (!session) return;\n this.#clearKeyboardSession();\n this.#followCommit(session.dx, session.dy);\n this.dispatch(\"end\", { detail: { dx: session.dx, dy: session.dy, pointerType: \"keyboard\" } });\n }\n\n /** Maps an arrow key to a raw (unfiltered) `keyboardStep` delta. */\n #keyboardDelta(key: string): [number, number] | null {\n const step = this.keyboardStepValue;\n switch (key) {\n case \"ArrowRight\":\n return [step, 0];\n case \"ArrowLeft\":\n return [-step, 0];\n case \"ArrowDown\":\n return [0, step];\n case \"ArrowUp\":\n return [0, -step];\n default:\n return null;\n }\n }\n\n /** Zeroes the delta on the locked axis (`axis` = x | y | both). */\n #filterAxis(dx: number, dy: number): [number, number] {\n if (this.axisValue === \"x\") return [dx, 0];\n if (this.axisValue === \"y\") return [0, dy];\n return [dx, dy];\n }\n\n /** Releases capture + listeners and clears the pointer session and its hook. */\n #endPointerSession(): void {\n this.#releasePointerCapture();\n this.#pointer = null;\n this.#dragAbort?.abort();\n this.#dragAbort = null;\n this.element.removeAttribute(\"data-dragging\");\n }\n\n /** Releases the pointer capture the active session set (idempotent, safe). */\n #releasePointerCapture(): void {\n const session = this.#pointer;\n if (session?.handle.hasPointerCapture(session.pointerId)) {\n session.handle.releasePointerCapture(session.pointerId);\n }\n }\n\n #clearKeyboardSession(): void {\n this.#keyboard?.handle.removeAttribute(\"data-grabbed\");\n this.#keyboard = null;\n this.element.removeAttribute(\"data-grabbed\");\n }\n\n /**\n * Full teardown for a controller whose element is going away or lost its\n * controller. Into a dead (detached) tree it is silent — consumers restore\n * from their own `connect()`, not from a cancel event. But a detach that\n * KEEPS the element (Turbo morph, `data-controller` removed) leaves the\n * consumers alive and listening: an in-flight session must end in `cancel`\n * there, or a composer like sortable strands its one-at-a-time session\n * bookkeeping forever.\n */\n #teardown(): void {\n // Disarm any probe still queued: without this, an immediate teardown\n // (element removed right after a deferring disconnect) would let the\n // orphaned probe run #teardown a second time — a double cancel.\n this.#gate.cancel();\n const interrupted = this.#pointer?.started\n ? this.#pointer.pointerType\n : this.#keyboard\n ? (\"keyboard\" as const)\n : null;\n this.#teardownSessions();\n for (const handle of this.#handles()) this.#restoreHandle(handle);\n if (interrupted && this.element.isConnected) this.#dispatchCancel(interrupted);\n }\n\n /**\n * Silently tears down whatever session is live (disconnect / disabled /\n * Escape). Composed from the two single-session teardowns so pointer and\n * keyboard cleanup cannot diverge as either path evolves.\n */\n #teardownSessions(): void {\n this.#endPointerSession();\n this.#clearKeyboardSession();\n }\n\n #dispatchCancel(pointerType: DragPointerType): void {\n // Every cancel path funnels here, so follow's snap-back can never be missed\n // (Escape, pointercancel, mid-session disable, detach-that-keeps-the-element).\n this.#followReset();\n this.dispatch(\"cancel\", { detail: { pointerType } });\n }\n\n /** Applies the in-flight offset to the element's `translate` (follow only). */\n #followMove(dx: number, dy: number): void {\n if (!this.followValue) return;\n this.#applyFollow(this.#followBase.x + dx, this.#followBase.y + dy);\n }\n\n /** Folds a drop's deltas into the committed base offset (follow only). */\n #followCommit(dx: number, dy: number): void {\n if (!this.followValue) return;\n this.#followBase = { x: this.#followBase.x + dx, y: this.#followBase.y + dy };\n this.#applyFollow(this.#followBase.x, this.#followBase.y);\n }\n\n /** Snaps back to the committed position (follow only) — the cancel contract. */\n #followReset(): void {\n if (!this.followValue) return;\n this.#applyFollow(this.#followBase.x, this.#followBase.y);\n }\n\n /**\n * Writes the offset as the standalone CSS `translate` property — independent\n * of `transform`, so an authored transform (scale, rotate…) is never\n * clobbered. At the origin the property is removed to keep the DOM clean.\n */\n #applyFollow(x: number, y: number): void {\n if (x === 0 && y === 0) this.element.style.removeProperty(\"translate\");\n else this.element.style.setProperty(\"translate\", `${x}px ${y}px`);\n }\n\n /**\n * Reads a committed follow offset back from the inline `translate`. Only the\n * controller's own `<x>px <y>px` shape is recognized; anything else (an\n * authored percentage, `none`, an empty string) starts the base at 0 — follow\n * mode owns this property, per the class contract.\n */\n #parseFollowBase(): { x: number; y: number } {\n const raw = this.element.style.getPropertyValue(\"translate\").trim();\n const match = /^(-?\\d+(?:\\.\\d+)?)px(?:\\s+(-?\\d+(?:\\.\\d+)?)px)?$/.exec(raw);\n if (!match) return { x: 0, y: 0 };\n return { x: Number(match[1]), y: Number(match[2] ?? \"0\") };\n }\n\n /** The active handles: the `handle` targets, else the element itself. */\n #handles(): HTMLElement[] {\n return this.hasHandleTarget ? this.handleTargets : [this.element];\n }\n\n /** Resolves the handle owning an event target (the handle or a descendant). */\n #handleFor(target: EventTarget | null): HTMLElement | null {\n const node = target as Node | null;\n if (!node) return null;\n return this.#handles().find((handle) => handle === node || handle.contains(node)) ?? null;\n }\n\n #pointerTypeOf(event: PointerEvent): DragPointerType {\n const type = event.pointerType;\n if (type === \"touch\" || type === \"pen\") return type;\n return \"mouse\";\n }\n\n /** `touch-action` that lets the page keep panning on the locked axis only. */\n #touchActionForAxis(): string {\n if (this.axisValue === \"x\") return \"pan-y\";\n if (this.axisValue === \"y\") return \"pan-x\";\n return \"none\";\n }\n\n /**\n * Establishes the handle contract: a `touch-action` derived from `axis`\n * (marker-guarded so an authored inline value wins and reconnects stay\n * idempotent) and focusability for the keyboard path (`tabindex=\"0\"` only when\n * the author supplied none — prefer a real `<button>` handle). Both additions\n * are marker-owned so `#restoreHandle` reverts them symmetrically on teardown.\n */\n #prepareHandle(handle: HTMLElement): void {\n if (\n handle.style.touchAction === \"\" ||\n handle.hasAttribute(PointerDragController.#TOUCH_ACTION_MARKER)\n ) {\n handle.style.touchAction = this.#touchActionForAxis();\n handle.setAttribute(PointerDragController.#TOUCH_ACTION_MARKER, \"true\");\n }\n if (handle.tabIndex < 0 && !handle.hasAttribute(\"tabindex\")) {\n handle.setAttribute(\"tabindex\", \"0\");\n handle.setAttribute(PointerDragController.#TABINDEX_MARKER, \"true\");\n }\n }\n\n /** Reverts the marker-owned touch-action + tabindex (authored values untouched). */\n #restoreHandle(handle: HTMLElement): void {\n if (handle.hasAttribute(PointerDragController.#TOUCH_ACTION_MARKER)) {\n handle.style.touchAction = \"\";\n handle.removeAttribute(PointerDragController.#TOUCH_ACTION_MARKER);\n }\n if (handle.hasAttribute(PointerDragController.#TABINDEX_MARKER)) {\n handle.removeAttribute(PointerDragController.#TABINDEX_MARKER);\n // Only remove what is verifiably still ours and safe to remove: another\n // owner (e.g. a roving list) may have rewritten the value since, and\n // stripping tabindex off the focused element would blur it to <body>\n // (losing the user's place — worse than leaking one tab stop).\n if (handle.getAttribute(\"tabindex\") === \"0\" && document.activeElement !== handle) {\n handle.removeAttribute(\"tabindex\");\n }\n }\n }\n}\n"]}
|
|
@@ -32,8 +32,7 @@ import { Controller } from '@hotwired/stimulus';
|
|
|
32
32
|
* layer on the shared {@link EscapeLayer} stack; it claims a press only while
|
|
33
33
|
* focus is inside the controller or fell to the body (a click on non-focusable
|
|
34
34
|
* panel content), so a press aimed at another layer is never consumed here,
|
|
35
|
-
* and one keypress closes exactly one layer
|
|
36
|
-
* contract).
|
|
35
|
+
* and one keypress closes exactly one layer.
|
|
37
36
|
* - An outside click (anywhere off the controller element) closes without moving
|
|
38
37
|
* focus. Focus stays at the clicked element, or falls back to the document body
|
|
39
38
|
* for a non-focusable destination.
|
|
@@ -133,7 +133,7 @@ var PopoverController = class _PopoverController extends Controller {
|
|
|
133
133
|
/** Starts closed and registers the standing dismissal listeners. */
|
|
134
134
|
connect() {
|
|
135
135
|
this.close();
|
|
136
|
-
document.addEventListener("click", this.#onOutsideClick);
|
|
136
|
+
document.addEventListener("click", this.#onOutsideClick, true);
|
|
137
137
|
this.element.addEventListener("focusout", this.#onFocusOut);
|
|
138
138
|
}
|
|
139
139
|
/**
|
|
@@ -144,7 +144,7 @@ var PopoverController = class _PopoverController extends Controller {
|
|
|
144
144
|
*/
|
|
145
145
|
disconnect() {
|
|
146
146
|
this.#escapeLayer.deactivate();
|
|
147
|
-
document.removeEventListener("click", this.#onOutsideClick);
|
|
147
|
+
document.removeEventListener("click", this.#onOutsideClick, true);
|
|
148
148
|
this.element.removeEventListener("focusout", this.#onFocusOut);
|
|
149
149
|
this.#stopScrollDismiss?.();
|
|
150
150
|
this.#stopScrollDismiss = null;
|