stimeo-ui 0.1.0-beta.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +6 -6
  3. package/dist/controllers/auto_submit_controller.js +56 -21
  4. package/dist/controllers/auto_submit_controller.js.map +1 -1
  5. package/dist/controllers/character_counter_controller.js +52 -15
  6. package/dist/controllers/character_counter_controller.js.map +1 -1
  7. package/dist/controllers/combobox_controller.d.ts +6 -2
  8. package/dist/controllers/combobox_controller.js +64 -3
  9. package/dist/controllers/combobox_controller.js.map +1 -1
  10. package/dist/controllers/command_palette_controller.d.ts +13 -6
  11. package/dist/controllers/command_palette_controller.js +256 -39
  12. package/dist/controllers/command_palette_controller.js.map +1 -1
  13. package/dist/controllers/confirm_controller.js +107 -8
  14. package/dist/controllers/confirm_controller.js.map +1 -1
  15. package/dist/controllers/context_menu_controller.d.ts +11 -6
  16. package/dist/controllers/context_menu_controller.js +191 -13
  17. package/dist/controllers/context_menu_controller.js.map +1 -1
  18. package/dist/controllers/countdown_controller.d.ts +2 -2
  19. package/dist/controllers/countdown_controller.js +2 -2
  20. package/dist/controllers/countdown_controller.js.map +1 -1
  21. package/dist/controllers/dialog_controller.js +107 -8
  22. package/dist/controllers/dialog_controller.js.map +1 -1
  23. package/dist/controllers/dropdown_controller.d.ts +9 -6
  24. package/dist/controllers/dropdown_controller.js +139 -16
  25. package/dist/controllers/dropdown_controller.js.map +1 -1
  26. package/dist/controllers/focus_controller.js +107 -8
  27. package/dist/controllers/focus_controller.js.map +1 -1
  28. package/dist/controllers/form_validation_controller.js +2 -2
  29. package/dist/controllers/form_validation_controller.js.map +1 -1
  30. package/dist/controllers/hover_card_controller.d.ts +15 -12
  31. package/dist/controllers/hover_card_controller.js +103 -27
  32. package/dist/controllers/hover_card_controller.js.map +1 -1
  33. package/dist/controllers/intersection_controller.js.map +1 -1
  34. package/dist/controllers/lazy_frame_controller.js.map +1 -1
  35. package/dist/controllers/listbox_controller.js +1 -0
  36. package/dist/controllers/listbox_controller.js.map +1 -1
  37. package/dist/controllers/menu_controller.d.ts +18 -11
  38. package/dist/controllers/menu_controller.js +181 -8
  39. package/dist/controllers/menu_controller.js.map +1 -1
  40. package/dist/controllers/otp_controller.js +62 -22
  41. package/dist/controllers/otp_controller.js.map +1 -1
  42. package/dist/controllers/overflow_menu_controller.d.ts +3 -2
  43. package/dist/controllers/overflow_menu_controller.js.map +1 -1
  44. package/dist/controllers/pointer_drag_controller.js +3 -3
  45. package/dist/controllers/pointer_drag_controller.js.map +1 -1
  46. package/dist/controllers/popover_controller.d.ts +18 -10
  47. package/dist/controllers/popover_controller.js +118 -27
  48. package/dist/controllers/popover_controller.js.map +1 -1
  49. package/dist/controllers/scroll_area_controller.js.map +1 -1
  50. package/dist/controllers/scrollspy_controller.js.map +1 -1
  51. package/dist/controllers/sortable_controller.d.ts +2 -2
  52. package/dist/controllers/sortable_controller.js +1 -1
  53. package/dist/controllers/sortable_controller.js.map +1 -1
  54. package/dist/controllers/sticky_observer_controller.js.map +1 -1
  55. package/dist/controllers/tabs_controller.d.ts +1 -2
  56. package/dist/controllers/tabs_controller.js.map +1 -1
  57. package/dist/controllers/toast_controller.d.ts +7 -9
  58. package/dist/controllers/toast_controller.js +108 -29
  59. package/dist/controllers/toast_controller.js.map +1 -1
  60. package/dist/controllers/tooltip_controller.d.ts +15 -18
  61. package/dist/controllers/tooltip_controller.js +148 -42
  62. package/dist/controllers/tooltip_controller.js.map +1 -1
  63. package/dist/index.d.ts +44 -14
  64. package/dist/index.js +847 -349
  65. package/dist/index.js.map +1 -1
  66. package/dist/inspector/cli.js.map +1 -1
  67. package/dist/inspector/cli_bin.js.map +1 -1
  68. package/dist/inspector/examples.json +6 -6
  69. package/dist/inspector/manifest.json +16 -3
  70. package/package.json +7 -9
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/layout_observer.ts","../../src/controllers/scroll_area_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,GAAa,KAAA;AAAA,IACpB;AAAA,EACF;AAAA,EAEA,qBAAqB,EAAA,EAA0B;AAC7C,IAAA,OAAO,EAAA,CAAG,aAAA,CAAc,kBAAkB,CAAA,KAAM,IAAA;AAAA,EAClD;AAAA,EAEA,mBAAmB,EAAA,EAA0B;AAC3C,IAAA,OAAO,GAAG,YAAA,CAAa,YAAY,CAAA,IAAK,EAAA,CAAG,aAAa,iBAAiB,CAAA;AAAA,EAC3E;AACF","file":"scroll_area_controller.js","sourcesContent":["/**\n * Unified element-size and viewport observation for Stimeo controllers.\n *\n * Layout-sensitive widgets (sliders, resizable panes, scroll spies, popovers)\n * need to react both to their *own* box changing — via {@link ResizeObserver} —\n * and to the *viewport* changing — via the `window` `resize` event. Wiring those\n * two sources by hand in every controller risks leaked listeners on\n * `disconnect()`. {@link LayoutObserver} owns both behind one callback and one\n * {@link LayoutObserver.disconnect | disconnect()} that releases everything.\n *\n * Behavior only: the helper reports *that* layout changed; it never reads or\n * writes styles. Consumers decide what to recompute.\n */\n\n/** Invoked whenever an observed element or the viewport changes size. */\nexport type LayoutCallback = () => void;\n\n/** Constructs a {@link ResizeObserver}; injectable so tests stay deterministic. */\nexport type ResizeObserverFactory = (callback: ResizeObserverCallback) => ResizeObserver;\n\n/** Options for {@link LayoutObserver}. */\nexport interface LayoutObserverOptions {\n /**\n * Factory for the {@link ResizeObserver} used by {@link LayoutObserver.observe}.\n * Defaults to the global constructor; override it in tests, or to no-op in\n * environments where `ResizeObserver` is unavailable.\n */\n resizeObserverFactory?: ResizeObserverFactory;\n}\n\n/**\n * Observes element resizes and/or viewport resizes through a single callback,\n * with guaranteed teardown.\n *\n * @example\n * ```ts\n * #layout = new LayoutObserver(() => this.#reposition());\n *\n * connect() {\n * this.#layout.observe(this.panelTarget);\n * this.#layout.observeViewport();\n * }\n *\n * disconnect() {\n * this.#layout.disconnect();\n * }\n * ```\n */\nexport class LayoutObserver {\n readonly #callback: LayoutCallback;\n readonly #resizeObserverFactory: ResizeObserverFactory | null;\n #resizeObserver: ResizeObserver | null = null;\n #observingViewport = false;\n\n /** Stable bound handler so add/removeEventListener target the same reference. */\n readonly #handleViewportResize = (): void => {\n this.#callback();\n };\n\n constructor(callback: LayoutCallback, options: LayoutObserverOptions = {}) {\n this.#callback = callback;\n this.#resizeObserverFactory =\n options.resizeObserverFactory ??\n (typeof ResizeObserver === \"undefined\" ? null : (cb) => new ResizeObserver(cb));\n }\n\n /**\n * Starts observing an element's size. Repeated calls observe additional\n * elements through the same shared observer. No-ops when no\n * `ResizeObserver` implementation is available.\n */\n observe(element: Element): void {\n if (!this.#resizeObserverFactory) return;\n if (!this.#resizeObserver) {\n this.#resizeObserver = this.#resizeObserverFactory(() => {\n this.#callback();\n });\n }\n this.#resizeObserver.observe(element);\n }\n\n /** Stops observing a single element while leaving any others in place. */\n unobserve(element: Element): void {\n this.#resizeObserver?.unobserve(element);\n }\n\n /** Starts observing viewport resizes. Idempotent: the listener is added once. */\n observeViewport(): void {\n if (this.#observingViewport) return;\n this.#observingViewport = true;\n window.addEventListener(\"resize\", this.#handleViewportResize);\n }\n\n /** Stops observing viewport resizes without affecting element observation. */\n unobserveViewport(): void {\n if (!this.#observingViewport) return;\n this.#observingViewport = false;\n window.removeEventListener(\"resize\", this.#handleViewportResize);\n }\n\n /**\n * Releases every observation: disconnects the {@link ResizeObserver} and\n * removes the viewport listener. Safe to call multiple times. Call this from a\n * controller's `disconnect()`.\n */\n disconnect(): void {\n this.#resizeObserver?.disconnect();\n this.#resizeObserver = null;\n this.unobserveViewport();\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { LayoutObserver } from \"../utils/layout_observer\";\n\n/** A CSS selector for natively focusable / author-focusable descendants. */\nconst FOCUSABLE_SELECTOR = [\n \"a[href]\",\n \"button:not([disabled])\",\n \"input:not([disabled])\",\n \"select:not([disabled])\",\n \"textarea:not([disabled])\",\n \"[tabindex]:not([tabindex='-1'])\",\n \"[contenteditable='true']\",\n].join(\",\");\n\n/** Distance from an edge (px) treated as fully reached; absorbs sub-pixel scroll. */\nconst EDGE_EPSILON = 1;\n\n/**\n * Headless **Scroll Area** behavior: keyboard reachability and scroll-state hooks\n * for a natively scrolling region. No custom scrollbar — the native one is\n * respected; this only adds a11y and CSS state.\n *\n * Markup contract (identifier: `stimeo--scroll-area`):\n * <div data-controller=\"stimeo--scroll-area\"\n * data-stimeo--scroll-area-orientation-value=\"vertical\">\n * <div data-stimeo--scroll-area-target=\"viewport\" aria-label=\"Log output\">\n * <!-- long content -->\n * </div>\n * </div>\n *\n * When the content overflows and the viewport holds no focusable elements of its\n * own, the viewport is made keyboard-scrollable (`tabindex=\"0\"`, plus `role=\"region\"`\n * when it already has an accessible name). Scroll position is published as\n * `data-scroll` (`start`/`middle`/`end`), overflow as `data-overflow`, and progress\n * as `--stimeo-scroll-progress` (0–1) so consumer CSS can draw scroll shadows.\n *\n * @remarks\n * Behavior only. The `scroll` listener and {@link LayoutObserver} (element +\n * viewport resize) are torn down on `disconnect()` (Turbo navigation included).\n * `role=\"region\"` is added only when the viewport is already named, so a scrollable\n * region never becomes an unlabeled landmark.\n */\nexport class ScrollAreaController extends Controller<HTMLElement> {\n static override targets = [\"viewport\"];\n static override values = {\n orientation: { type: String, default: \"vertical\" },\n };\n static events = [\"reach\"] as const;\n\n declare readonly viewportTarget: HTMLElement;\n declare readonly hasViewportTarget: boolean;\n\n declare orientationValue: string;\n\n readonly #layout = new LayoutObserver(() => this.#update());\n /** Last edge reported via `reach`, so the event fires once per arrival. */\n #lastEdge: \"start\" | \"end\" | null = null;\n /** Whether this controller added `tabindex`, so teardown only removes its own. */\n #addedTabindex = false;\n /** Whether this controller added `role=\"region\"`, for symmetric teardown. */\n #addedRole = false;\n\n readonly #onScroll = (): void => {\n this.#update();\n };\n\n override connect(): void {\n if (!this.hasViewportTarget) return;\n this.viewportTarget.addEventListener(\"scroll\", this.#onScroll, { passive: true });\n this.#layout.observe(this.viewportTarget);\n this.#layout.observeViewport();\n this.#update();\n }\n\n override disconnect(): void {\n if (this.hasViewportTarget) {\n this.viewportTarget.removeEventListener(\"scroll\", this.#onScroll);\n // Remove only the keyboard-reach attributes this controller added, so a\n // Turbo cache snapshot never preserves a controller-owned tab stop /\n // landmark (matches the spec's Turbo-compatibility requirement).\n this.#clearAddedAttributes(this.viewportTarget);\n }\n this.#layout.disconnect();\n this.#lastEdge = null;\n }\n\n /** Re-measures overflow and scroll position and reflects the state hooks. */\n #update(): void {\n if (!this.hasViewportTarget) return;\n const vp = this.viewportTarget;\n const overflowing = this.#measureOverflow(vp);\n\n this.element.setAttribute(\"data-overflow\", overflowing ? \"true\" : \"false\");\n this.#syncKeyboardReach(vp, overflowing);\n\n const { position, progress } = this.#measurePosition(vp);\n this.element.setAttribute(\"data-scroll\", position);\n this.element.style.setProperty(\"--stimeo-scroll-progress\", String(progress));\n\n const edge = position === \"start\" ? \"start\" : position === \"end\" ? \"end\" : null;\n if (overflowing && edge && edge !== this.#lastEdge) {\n this.#lastEdge = edge;\n this.dispatch(\"reach\", { detail: { edge } });\n } else if (!edge) {\n this.#lastEdge = null;\n }\n }\n\n /** Whether the viewport can scroll on the configured axis. */\n #measureOverflow(vp: HTMLElement): boolean {\n const o = this.orientationValue;\n const vertical = o !== \"horizontal\" && vp.scrollHeight > vp.clientHeight + EDGE_EPSILON;\n const horizontal = o !== \"vertical\" && vp.scrollWidth > vp.clientWidth + EDGE_EPSILON;\n return vertical || horizontal;\n }\n\n /**\n * Reports the scroll position bucket and 0–1 progress on the primary axis. For\n * `both`, the vertical axis is used when it overflows, otherwise the horizontal.\n */\n #measurePosition(vp: HTMLElement): {\n position: \"start\" | \"middle\" | \"end\";\n progress: number;\n } {\n const horizontalPrimary =\n this.orientationValue === \"horizontal\" ||\n (this.orientationValue === \"both\" && vp.scrollHeight <= vp.clientHeight + EDGE_EPSILON);\n\n const scrollPos = horizontalPrimary ? vp.scrollLeft : vp.scrollTop;\n const maxScroll = horizontalPrimary\n ? vp.scrollWidth - vp.clientWidth\n : vp.scrollHeight - vp.clientHeight;\n\n if (maxScroll <= EDGE_EPSILON) return { position: \"start\", progress: 0 };\n\n const progress = Math.min(1, Math.max(0, scrollPos / maxScroll));\n if (scrollPos <= EDGE_EPSILON) return { position: \"start\", progress };\n if (scrollPos >= maxScroll - EDGE_EPSILON) return { position: \"end\", progress };\n return { position: \"middle\", progress };\n }\n\n /**\n * Makes the viewport keyboard-scrollable when it overflows and contains no\n * focusable elements of its own (avoiding a double tab stop). Adds `role=\"region\"`\n * only when the viewport already carries an accessible name.\n */\n #syncKeyboardReach(vp: HTMLElement, overflowing: boolean): void {\n const wantsTabindex = overflowing && !this.#hasFocusableContent(vp);\n\n if (wantsTabindex) {\n if (!vp.hasAttribute(\"tabindex\")) {\n vp.setAttribute(\"tabindex\", \"0\");\n this.#addedTabindex = true;\n }\n if (!vp.hasAttribute(\"role\") && this.#hasAccessibleName(vp)) {\n vp.setAttribute(\"role\", \"region\");\n this.#addedRole = true;\n }\n } else {\n this.#clearAddedAttributes(vp);\n }\n }\n\n /** Removes (and resets the flags for) only the attributes this controller added. */\n #clearAddedAttributes(vp: HTMLElement): void {\n if (this.#addedTabindex) {\n vp.removeAttribute(\"tabindex\");\n this.#addedTabindex = false;\n }\n if (this.#addedRole) {\n vp.removeAttribute(\"role\");\n this.#addedRole = false;\n }\n }\n\n #hasFocusableContent(vp: HTMLElement): boolean {\n return vp.querySelector(FOCUSABLE_SELECTOR) !== null;\n }\n\n #hasAccessibleName(vp: HTMLElement): boolean {\n return vp.hasAttribute(\"aria-label\") || vp.hasAttribute(\"aria-labelledby\");\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/layout_observer.ts","../../src/controllers/scroll_area_controller.ts"],"names":[],"mappings":";;;;;AAgDO,IAAM,iBAAN,MAAqB;AAAA,EACjB,SAAA;AAAA,EACA,sBAAA;AAAA,EACT,eAAA,GAAyC,IAAA;AAAA,EACzC,kBAAA,GAAqB,KAAA;AAAA;AAAA,EAGZ,wBAAwB,MAA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;AAC3C,IAAA,OAAO,GAAG,YAAA,CAAa,YAAY,CAAA,IAAK,EAAA,CAAG,aAAa,iBAAiB,CAAA;AAAA,EAC3E;AACF","file":"scroll_area_controller.js","sourcesContent":["/**\n * Unified element-size and viewport observation for Stimeo controllers.\n *\n * Layout-sensitive widgets (sliders, resizable panes, scroll spies, popovers)\n * need to react both to their *own* box changing — via {@link ResizeObserver} —\n * and to the *viewport* changing — via the `window` `resize` event. Wiring those\n * two sources by hand in every controller risks leaked listeners on\n * `disconnect()`. {@link LayoutObserver} owns both behind one callback and one\n * {@link LayoutObserver.disconnect | disconnect()} that releases everything.\n *\n * Behavior only: the helper reports *that* layout changed; it never reads or\n * writes styles. Consumers decide what to recompute.\n */\n\n/** Invoked whenever an observed element or the viewport changes size. */\nexport type LayoutCallback = () => void;\n\n/** Constructs a {@link ResizeObserver}; injectable so tests stay deterministic. */\nexport type ResizeObserverFactory = (callback: ResizeObserverCallback) => ResizeObserver;\n\n/** Options for {@link LayoutObserver}. */\nexport interface LayoutObserverOptions {\n /**\n * Factory for the {@link ResizeObserver} used by {@link LayoutObserver.observe}.\n * Defaults to the global constructor; override it in tests, or to no-op in\n * environments where `ResizeObserver` is unavailable.\n */\n resizeObserverFactory?: ResizeObserverFactory;\n}\n\n/**\n * Observes element resizes and/or viewport resizes through a single callback,\n * with guaranteed teardown.\n *\n * @example\n * ```ts\n * #layout = new LayoutObserver(() => this.#reposition());\n *\n * connect() {\n * this.#layout.observe(this.panelTarget);\n * this.#layout.observeViewport();\n * }\n *\n * disconnect() {\n * this.#layout.disconnect();\n * }\n * ```\n */\nexport class LayoutObserver {\n readonly #callback: LayoutCallback;\n readonly #resizeObserverFactory: ResizeObserverFactory | null;\n #resizeObserver: ResizeObserver | null = null;\n #observingViewport = false;\n\n /** Stable bound handler so add/removeEventListener target the same reference. */\n readonly #handleViewportResize = (): void => {\n this.#callback();\n };\n\n constructor(callback: LayoutCallback, options: LayoutObserverOptions = {}) {\n this.#callback = callback;\n this.#resizeObserverFactory =\n options.resizeObserverFactory ??\n (typeof ResizeObserver === \"undefined\" ? null : (cb) => new ResizeObserver(cb));\n }\n\n /**\n * Starts observing an element's size. Repeated calls observe additional\n * elements through the same shared observer. No-ops when no\n * `ResizeObserver` implementation is available.\n */\n observe(element: Element): void {\n if (!this.#resizeObserverFactory) return;\n if (!this.#resizeObserver) {\n this.#resizeObserver = this.#resizeObserverFactory(() => {\n this.#callback();\n });\n }\n this.#resizeObserver.observe(element);\n }\n\n /** Stops observing a single element while leaving any others in place. */\n unobserve(element: Element): void {\n this.#resizeObserver?.unobserve(element);\n }\n\n /** Starts observing viewport resizes. Idempotent: the listener is added once. */\n observeViewport(): void {\n if (this.#observingViewport) return;\n this.#observingViewport = true;\n window.addEventListener(\"resize\", this.#handleViewportResize);\n }\n\n /** Stops observing viewport resizes without affecting element observation. */\n unobserveViewport(): void {\n if (!this.#observingViewport) return;\n this.#observingViewport = false;\n window.removeEventListener(\"resize\", this.#handleViewportResize);\n }\n\n /**\n * Releases every observation: disconnects the {@link ResizeObserver} and\n * removes the viewport listener. Safe to call multiple times. Call this from a\n * controller's `disconnect()`.\n */\n disconnect(): void {\n this.#resizeObserver?.disconnect();\n this.#resizeObserver = null;\n this.unobserveViewport();\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { LayoutObserver } from \"../utils/layout_observer\";\n\n/** A CSS selector for natively focusable / author-focusable descendants. */\nconst FOCUSABLE_SELECTOR = [\n \"a[href]\",\n \"button:not([disabled])\",\n \"input:not([disabled])\",\n \"select:not([disabled])\",\n \"textarea:not([disabled])\",\n \"[tabindex]:not([tabindex='-1'])\",\n \"[contenteditable='true']\",\n].join(\",\");\n\n/** Distance from an edge (px) treated as fully reached; absorbs sub-pixel scroll. */\nconst EDGE_EPSILON = 1;\n\n/**\n * Headless **Scroll Area** behavior: keyboard reachability and scroll-state hooks\n * for a natively scrolling region. No custom scrollbar — the native one is\n * respected; this only adds a11y and CSS state.\n *\n * Markup contract (identifier: `stimeo--scroll-area`):\n * <div data-controller=\"stimeo--scroll-area\"\n * data-stimeo--scroll-area-orientation-value=\"vertical\">\n * <div data-stimeo--scroll-area-target=\"viewport\" aria-label=\"Log output\">\n * <!-- long content -->\n * </div>\n * </div>\n *\n * When the content overflows and the viewport holds no focusable elements of its\n * own, the viewport is made keyboard-scrollable (`tabindex=\"0\"`, plus `role=\"region\"`\n * when it already has an accessible name). Scroll position is published as\n * `data-scroll` (`start`/`middle`/`end`), overflow as `data-overflow`, and progress\n * as `--stimeo-scroll-progress` (0–1) so consumer CSS can draw scroll shadows.\n *\n * @remarks\n * Behavior only. The `scroll` listener and {@link LayoutObserver} (element +\n * viewport resize) are torn down on `disconnect()` (Turbo navigation included).\n * `role=\"region\"` is added only when the viewport is already named, so a scrollable\n * region never becomes an unlabeled landmark.\n */\nexport class ScrollAreaController extends Controller<HTMLElement> {\n static override targets = [\"viewport\"];\n static override values = {\n orientation: { type: String, default: \"vertical\" },\n };\n static events = [\"reach\"] as const;\n\n declare readonly viewportTarget: HTMLElement;\n declare readonly hasViewportTarget: boolean;\n\n declare orientationValue: string;\n\n readonly #layout = new LayoutObserver(() => this.#update());\n /** Last edge reported via `reach`, so the event fires once per arrival. */\n #lastEdge: \"start\" | \"end\" | null = null;\n /** Whether this controller added `tabindex`, so teardown only removes its own. */\n #addedTabindex = false;\n /** Whether this controller added `role=\"region\"`, for symmetric teardown. */\n #addedRole = false;\n\n readonly #onScroll = (): void => {\n this.#update();\n };\n\n override connect(): void {\n if (!this.hasViewportTarget) return;\n this.viewportTarget.addEventListener(\"scroll\", this.#onScroll, { passive: true });\n this.#layout.observe(this.viewportTarget);\n this.#layout.observeViewport();\n this.#update();\n }\n\n override disconnect(): void {\n if (this.hasViewportTarget) {\n this.viewportTarget.removeEventListener(\"scroll\", this.#onScroll);\n // Remove only the keyboard-reach attributes this controller added, so a\n // Turbo cache snapshot never preserves a controller-owned tab stop /\n // landmark (controller-added state must not outlive the controller).\n this.#clearAddedAttributes(this.viewportTarget);\n }\n this.#layout.disconnect();\n this.#lastEdge = null;\n }\n\n /** Re-measures overflow and scroll position and reflects the state hooks. */\n #update(): void {\n if (!this.hasViewportTarget) return;\n const vp = this.viewportTarget;\n const overflowing = this.#measureOverflow(vp);\n\n this.element.setAttribute(\"data-overflow\", overflowing ? \"true\" : \"false\");\n this.#syncKeyboardReach(vp, overflowing);\n\n const { position, progress } = this.#measurePosition(vp);\n this.element.setAttribute(\"data-scroll\", position);\n this.element.style.setProperty(\"--stimeo-scroll-progress\", String(progress));\n\n const edge = position === \"start\" ? \"start\" : position === \"end\" ? \"end\" : null;\n if (overflowing && edge && edge !== this.#lastEdge) {\n this.#lastEdge = edge;\n this.dispatch(\"reach\", { detail: { edge } });\n } else if (!edge) {\n this.#lastEdge = null;\n }\n }\n\n /** Whether the viewport can scroll on the configured axis. */\n #measureOverflow(vp: HTMLElement): boolean {\n const o = this.orientationValue;\n const vertical = o !== \"horizontal\" && vp.scrollHeight > vp.clientHeight + EDGE_EPSILON;\n const horizontal = o !== \"vertical\" && vp.scrollWidth > vp.clientWidth + EDGE_EPSILON;\n return vertical || horizontal;\n }\n\n /**\n * Reports the scroll position bucket and 0–1 progress on the primary axis. For\n * `both`, the vertical axis is used when it overflows, otherwise the horizontal.\n */\n #measurePosition(vp: HTMLElement): {\n position: \"start\" | \"middle\" | \"end\";\n progress: number;\n } {\n const horizontalPrimary =\n this.orientationValue === \"horizontal\" ||\n (this.orientationValue === \"both\" && vp.scrollHeight <= vp.clientHeight + EDGE_EPSILON);\n\n const scrollPos = horizontalPrimary ? vp.scrollLeft : vp.scrollTop;\n const maxScroll = horizontalPrimary\n ? vp.scrollWidth - vp.clientWidth\n : vp.scrollHeight - vp.clientHeight;\n\n if (maxScroll <= EDGE_EPSILON) return { position: \"start\", progress: 0 };\n\n const progress = Math.min(1, Math.max(0, scrollPos / maxScroll));\n if (scrollPos <= EDGE_EPSILON) return { position: \"start\", progress };\n if (scrollPos >= maxScroll - EDGE_EPSILON) return { position: \"end\", progress };\n return { position: \"middle\", progress };\n }\n\n /**\n * Makes the viewport keyboard-scrollable when it overflows and contains no\n * focusable elements of its own (avoiding a double tab stop). Adds `role=\"region\"`\n * only when the viewport already carries an accessible name.\n */\n #syncKeyboardReach(vp: HTMLElement, overflowing: boolean): void {\n const wantsTabindex = overflowing && !this.#hasFocusableContent(vp);\n\n if (wantsTabindex) {\n if (!vp.hasAttribute(\"tabindex\")) {\n vp.setAttribute(\"tabindex\", \"0\");\n this.#addedTabindex = true;\n }\n if (!vp.hasAttribute(\"role\") && this.#hasAccessibleName(vp)) {\n vp.setAttribute(\"role\", \"region\");\n this.#addedRole = true;\n }\n } else {\n this.#clearAddedAttributes(vp);\n }\n }\n\n /** Removes (and resets the flags for) only the attributes this controller added. */\n #clearAddedAttributes(vp: HTMLElement): void {\n if (this.#addedTabindex) {\n vp.removeAttribute(\"tabindex\");\n this.#addedTabindex = false;\n }\n if (this.#addedRole) {\n vp.removeAttribute(\"role\");\n this.#addedRole = false;\n }\n }\n\n #hasFocusableContent(vp: HTMLElement): boolean {\n return vp.querySelector(FOCUSABLE_SELECTOR) !== null;\n }\n\n #hasAccessibleName(vp: HTMLElement): boolean {\n return vp.hasAttribute(\"aria-label\") || vp.hasAttribute(\"aria-labelledby\");\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/intersection_watcher.ts","../../src/controllers/scrollspy_controller.ts"],"names":[],"mappings":";;;;;AA8BO,IAAM,sBAAN,MAA0B;AAAA,EACtB,UAAA;AAAA,EACT,SAAA,GAAyC,IAAA;AAAA,EACzC,OAAA,GAAU,KAAA;AAAA,EAEV,YAAY,SAAA,EAA2D;AACrE,IAAA,IAAA,CAAK,UAAA,GAAa,SAAA;AAAA,EACpB;AAAA;AAAA,EAGA,IAAI,MAAA,GAAkB;AACpB,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,KAAA,CAAM,OA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,OAAO,IAAA;AACnC,IAAA,OAAO,IAAA,CAAK,UAAU,CAAC,CAAA;AAAA,EACzB;AACF","file":"scrollspy_controller.js","sourcesContent":["/**\n * Shared `IntersectionObserver` plumbing for Stimeo's scroll-triggered\n * controllers (`intersection`, `scrollspy`, `sticky-observer`, `lazy-frame`).\n *\n * These controllers each grew a separate implementation of the same idea;\n * this util is that idea written once — the boilerplate every consumer\n * repeated: the `IntersectionObserver` support guard, root resolution from a\n * selector, observer creation/teardown, the **active guard** (the browser may\n * flush a final queued callback batch right after `disconnect()`, and a\n * detached controller must not mutate possibly-cached DOM), and the\n * unobserve→observe **re-arm** that re-delivers the current state (the\n * infinite-scroll \"sentinel never left the viewport\" fix).\n *\n * Like {@link RovingTabindex} and `FocusTrap`, this is a policy-free internal\n * util: what an intersection *means* (a spied link, a stuck header, a lazy\n * load) stays in each controller. The public `stimeo--intersection` controller\n * is its thin declarative face.\n */\nexport interface IntersectionWatchOptions {\n /**\n * The observation root. Pass an element (or `null` for the viewport) when\n * the caller already resolved it; omit to resolve from `rootSelector`.\n */\n root?: Element | null;\n /** Selector for the observation root; empty/omitted = viewport. */\n rootSelector?: string;\n rootMargin?: string;\n threshold?: number | number[];\n}\n\nexport class IntersectionWatcher {\n readonly #onEntries: (entries: IntersectionObserverEntry[]) => void;\n #observer: IntersectionObserver | null = null;\n #active = false;\n\n constructor(onEntries: (entries: IntersectionObserverEntry[]) => void) {\n this.#onEntries = onEntries;\n }\n\n /** Whether an observer is live (started, `IntersectionObserver` supported). */\n get active(): boolean {\n return this.#active;\n }\n\n /**\n * (Re)creates the observer and observes `targets`. Returns `false` — leaving\n * the watcher inert — without `IntersectionObserver` support (very old\n * browsers; the caller's no-JS fallback stays in charge) or with no targets.\n */\n start(targets: Element | readonly Element[], options: IntersectionWatchOptions = {}): boolean {\n this.stop();\n if (typeof IntersectionObserver === \"undefined\") return false;\n const list = Array.isArray(targets) ? (targets as readonly Element[]) : [targets as Element];\n if (list.length === 0) return false;\n\n const root =\n \"root\" in options\n ? (options.root ?? null)\n : options.rootSelector\n ? document.querySelector(options.rootSelector)\n : null;\n\n this.#active = true;\n this.#observer = new IntersectionObserver(\n (entries) => {\n if (this.#active) this.#onEntries(entries);\n },\n { root, rootMargin: options.rootMargin, threshold: options.threshold },\n );\n for (const target of list) this.#observer.observe(target);\n return true;\n }\n\n /**\n * Re-delivers `target`'s CURRENT intersection state: `IntersectionObserver`\n * only reports *changes*, but `observe()` always reports the present state,\n * so unobserve→observe turns \"still intersecting\" into a fresh callback.\n */\n rearm(target: Element): void {\n if (!this.#observer) return;\n this.#observer.unobserve(target);\n this.#observer.observe(target);\n }\n\n /** Severs the observer; late queued callbacks become no-ops via the guard. */\n stop(): void {\n this.#active = false;\n this.#observer?.disconnect();\n this.#observer = null;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { IntersectionWatcher } from \"../utils/intersection_watcher\";\n\n/**\n * Headless, accessible Scrollspy / Navigation catalog synchronizer.\n *\n * Markup contract (identifier: `stimeo--scrollspy`):\n * <nav data-controller=\"stimeo--scrollspy\"\n * data-stimeo--scrollspy-offset-value=\"80\"\n * aria-label=\"Table of contents\">\n * <a href=\"#intro\" data-stimeo--scrollspy-target=\"link\">Intro</a>\n * <a href=\"#usage\" data-stimeo--scrollspy-target=\"link\">Usage</a>\n * </nav>\n * <section id=\"intro\">…</section>\n * <section id=\"usage\">…</section>\n *\n * Implements clean active location synchronization driven by `aria-current`:\n * - Leverages native `IntersectionObserver` to track viewport visibility.\n * - Robust evaluation algorithm: among all intersecting sections, the one closest\n * to the top offset trigger line (`boundingClientRect.top`) is prioritized as active.\n * - Toggles `aria-current=\"location\"` dynamically on active/inactive links.\n * - Gracefully handles teardown `disconnect()` by severing observer references to prevent leaks.\n *\n * @remarks\n * Behavior only. The controller manages state on catalog links via `aria-current`,\n * respects custom offsets, and dispatches `stimeo--scrollspy:change` events.\n */\nexport class ScrollspyController extends Controller<HTMLElement> {\n static override targets = [\"link\"];\n static override values = {\n offset: { type: Number, default: 0 },\n rootMargin: { type: String, default: \"\" },\n rootSelector: { type: String, default: \"\" },\n };\n static actions = [\"scrollTo\"] as const;\n static events = [\"change\"] as const;\n\n declare readonly linkTargets: HTMLElement[];\n\n declare offsetValue: number;\n declare rootMarginValue: string;\n declare rootSelectorValue: string;\n\n /** Shared IO plumbing (support guard, active guard, teardown). */\n readonly #watcher = new IntersectionWatcher((entries) => this.#onIntersection(entries));\n #isConnected = false;\n\n /** Track active/intersecting status of each section element by ID. */\n #intersectionStates = new Map<string, { isIntersecting: boolean; top: number }>();\n\n /** Current active section ID, used to avoid duplicate event dispatching. */\n #activeSectionId = \"\";\n\n override connect(): void {\n this.#isConnected = true;\n this.#initializeObserver();\n }\n\n override disconnect(): void {\n this.#isConnected = false;\n this.#watcher.stop();\n this.#intersectionStates.clear();\n this.#activeSectionId = \"\";\n }\n\n /**\n * Re-initializes the observer if the offset or rootMargin values change dynamically.\n */\n offsetValueChanged(): void {\n if (!this.#isConnected) return;\n this.#initializeObserver();\n }\n\n rootMarginValueChanged(): void {\n if (!this.#isConnected) return;\n this.#initializeObserver();\n }\n\n rootSelectorValueChanged(): void {\n if (!this.#isConnected) return;\n this.#initializeObserver();\n }\n\n /**\n * Smoothly scrolls to the target element mapped by the link anchor.\n * Prevents full window scroll jumps when tracking nested scrollable containers.\n */\n scrollTo(event: Event): void {\n const link = event.currentTarget as HTMLElement;\n const id = this.#getAnchorId(link);\n if (!id) return;\n\n event.preventDefault();\n\n const targetElement = document.getElementById(id);\n if (!targetElement) return;\n\n const rootElement = this.#getRootElement();\n if (rootElement) {\n const containerRect = rootElement.getBoundingClientRect();\n const targetRect = targetElement.getBoundingClientRect();\n const scrollPosition =\n rootElement.scrollTop + (targetRect.top - containerRect.top) - this.offsetValue;\n\n rootElement.scrollTo({\n top: scrollPosition,\n behavior: \"smooth\",\n });\n } else {\n const targetRect = targetElement.getBoundingClientRect();\n const scrollPosition = window.scrollY + targetRect.top - this.offsetValue;\n\n window.scrollTo({\n top: scrollPosition,\n behavior: \"smooth\",\n });\n }\n }\n\n #getRootElement(): HTMLElement | null {\n if (!this.rootSelectorValue) return null;\n return document.querySelector(this.rootSelectorValue);\n }\n\n #initializeObserver(): void {\n this.#watcher.stop();\n this.#intersectionStates.clear();\n this.#activeSectionId = \"\";\n\n if (this.linkTargets.length === 0) return;\n\n // Build the dynamic rootMargin string based on offset value\n const margin = this.rootMarginValue || `-${this.offsetValue}px 0px -80% 0px`;\n\n // Observe each target section mapped by the href anchors.\n const sections: Element[] = [];\n for (const link of this.linkTargets) {\n const id = this.#getAnchorId(link);\n if (!id) continue;\n const section = document.getElementById(id);\n if (section) sections.push(section);\n }\n\n this.#watcher.start(sections, {\n root: this.#getRootElement(),\n rootMargin: margin,\n threshold: [0, 0.2, 0.4, 0.6, 0.8, 1], // Multiple thresholds handle large sections safely\n });\n }\n\n readonly #onIntersection = (entries: IntersectionObserverEntry[]): void => {\n // Ignore any callback delivered after teardown: the browser may flush a\n // final queued batch right after `disconnect()`, and a detached controller\n // must not mutate `aria-current` on (possibly cached) links.\n if (!this.#isConnected) return;\n\n for (const entry of entries) {\n const id = entry.target.id;\n if (!id) continue;\n\n this.#intersectionStates.set(id, {\n isIntersecting: entry.isIntersecting,\n top: entry.boundingClientRect.top,\n });\n }\n\n this.#evaluateActiveSection();\n };\n\n #evaluateActiveSection(): void {\n // The trigger line is `offset` px below the top of the scroll root. When a\n // nested `rootSelector` container is used it is not at the viewport top, so\n // the line must be measured from the container's current top — comparing the\n // viewport-based `boundingClientRect.top` against a bare `offset` would\n // otherwise pick the section nearest the viewport top, not the container's.\n const rootEl = this.#getRootElement();\n const triggerLine = (rootEl ? rootEl.getBoundingClientRect().top : 0) + this.offsetValue;\n\n let bestId = \"\";\n let closestTop = Number.MAX_VALUE;\n\n // Evaluate among all intersecting elements\n for (const [id, state] of this.#intersectionStates.entries()) {\n if (state.isIntersecting) {\n // Evaluate the one closest to the offset trigger line\n const distance = Math.abs(state.top - triggerLine);\n if (distance < closestTop) {\n closestTop = distance;\n bestId = id;\n }\n }\n }\n\n // Fallback: when no section currently intersects (e.g. scrolled past the\n // bottom, or between sections), pick the tracked section whose top is closest\n // to the trigger line so something stays highlighted.\n if (!bestId && this.#intersectionStates.size > 0) {\n let absoluteClosestId = \"\";\n let absoluteClosestTop = Number.MAX_VALUE;\n\n for (const [id, state] of this.#intersectionStates.entries()) {\n const distance = Math.abs(state.top - triggerLine);\n if (distance < absoluteClosestTop) {\n absoluteClosestTop = distance;\n absoluteClosestId = id;\n }\n }\n bestId = absoluteClosestId;\n }\n\n if (bestId && bestId !== this.#activeSectionId) {\n this.#activeSectionId = bestId;\n this.#syncActiveStates();\n }\n }\n\n #syncActiveStates(): void {\n const activeLink = this.linkTargets.find((l) => this.#getAnchorId(l) === this.#activeSectionId);\n\n for (const link of this.linkTargets) {\n const isActive = link === activeLink;\n if (isActive) {\n link.setAttribute(\"aria-current\", \"location\");\n } else {\n link.removeAttribute(\"aria-current\");\n }\n }\n\n if (activeLink) {\n this.dispatch(\"change\", { detail: { id: this.#activeSectionId, link: activeLink } });\n }\n }\n\n #getAnchorId(link: HTMLElement): string | null {\n const href = link.getAttribute(\"href\") || link.getAttribute(\"data-href\");\n if (!href?.startsWith(\"#\")) return null;\n return href.substring(1);\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/intersection_watcher.ts","../../src/controllers/scrollspy_controller.ts"],"names":[],"mappings":";;;;;AA4BO,IAAM,sBAAN,MAA0B;AAAA,EACtB,UAAA;AAAA,EACT,SAAA,GAAyC,IAAA;AAAA,EACzC,OAAA,GAAU,KAAA;AAAA,EAEV,YAAY,SAAA,EAA2D;AACrE,IAAA,IAAA,CAAK,UAAA,GAAa,SAAA;AAAA,EACpB;AAAA;AAAA,EAGA,IAAI,MAAA,GAAkB;AACpB,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,KAAA,CAAM,OAAA,EAAu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AAA;AACnC,IAAA,OAAO,IAAA,CAAK,UAAU,CAAC,CAAA;AAAA,EACzB;AACF","file":"scrollspy_controller.js","sourcesContent":["/**\n * Shared `IntersectionObserver` plumbing for Stimeo's scroll-triggered\n * controllers (`intersection`, `scrollspy`, `sticky-observer`, `lazy-frame`).\n *\n * It centralizes the `IntersectionObserver` support guard, root resolution from\n * a selector, observer creation/teardown, the **active guard** (the browser may\n * flush a final queued callback batch right after `disconnect()`, and a\n * detached controller must not mutate possibly-cached DOM), and the\n * unobserve→observe **re-arm** that re-delivers the current state even when the\n * target never leaves the viewport.\n *\n * Like {@link RovingTabindex} and `FocusTrap`, this is a policy-free internal\n * util: what an intersection *means* (a spied link, a stuck header, a lazy\n * load) stays in each controller. The public `stimeo--intersection` controller\n * is its thin declarative face.\n */\nexport interface IntersectionWatchOptions {\n /**\n * The observation root. Pass an element (or `null` for the viewport) when\n * the caller already resolved it; omit to resolve from `rootSelector`.\n */\n root?: Element | null;\n /** Selector for the observation root; empty/omitted = viewport. */\n rootSelector?: string;\n rootMargin?: string;\n threshold?: number | number[];\n}\n\nexport class IntersectionWatcher {\n readonly #onEntries: (entries: IntersectionObserverEntry[]) => void;\n #observer: IntersectionObserver | null = null;\n #active = false;\n\n constructor(onEntries: (entries: IntersectionObserverEntry[]) => void) {\n this.#onEntries = onEntries;\n }\n\n /** Whether an observer is live (started, `IntersectionObserver` supported). */\n get active(): boolean {\n return this.#active;\n }\n\n /**\n * (Re)creates the observer and observes `targets`. Returns `false` — leaving\n * the watcher inert — without `IntersectionObserver` support (very old\n * browsers; the caller's no-JS fallback stays in charge) or with no targets.\n */\n start(targets: Element | readonly Element[], options: IntersectionWatchOptions = {}): boolean {\n this.stop();\n if (typeof IntersectionObserver === \"undefined\") return false;\n const list = Array.isArray(targets) ? (targets as readonly Element[]) : [targets as Element];\n if (list.length === 0) return false;\n\n const root =\n \"root\" in options\n ? (options.root ?? null)\n : options.rootSelector\n ? document.querySelector(options.rootSelector)\n : null;\n\n this.#active = true;\n this.#observer = new IntersectionObserver(\n (entries) => {\n if (this.#active) this.#onEntries(entries);\n },\n { root, rootMargin: options.rootMargin, threshold: options.threshold },\n );\n for (const target of list) this.#observer.observe(target);\n return true;\n }\n\n /**\n * Re-delivers `target`'s CURRENT intersection state: `IntersectionObserver`\n * only reports *changes*, but `observe()` always reports the present state,\n * so unobserve→observe turns \"still intersecting\" into a fresh callback.\n */\n rearm(target: Element): void {\n if (!this.#observer) return;\n this.#observer.unobserve(target);\n this.#observer.observe(target);\n }\n\n /** Severs the observer; late queued callbacks become no-ops via the guard. */\n stop(): void {\n this.#active = false;\n this.#observer?.disconnect();\n this.#observer = null;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { IntersectionWatcher } from \"../utils/intersection_watcher\";\n\n/**\n * Headless, accessible Scrollspy / Navigation catalog synchronizer.\n *\n * Markup contract (identifier: `stimeo--scrollspy`):\n * <nav data-controller=\"stimeo--scrollspy\"\n * data-stimeo--scrollspy-offset-value=\"80\"\n * aria-label=\"Table of contents\">\n * <a href=\"#intro\" data-stimeo--scrollspy-target=\"link\">Intro</a>\n * <a href=\"#usage\" data-stimeo--scrollspy-target=\"link\">Usage</a>\n * </nav>\n * <section id=\"intro\">…</section>\n * <section id=\"usage\">…</section>\n *\n * Implements clean active location synchronization driven by `aria-current`:\n * - Leverages native `IntersectionObserver` to track viewport visibility.\n * - Robust evaluation algorithm: among all intersecting sections, the one closest\n * to the top offset trigger line (`boundingClientRect.top`) is prioritized as active.\n * - Toggles `aria-current=\"location\"` dynamically on active/inactive links.\n * - Gracefully handles teardown `disconnect()` by severing observer references to prevent leaks.\n *\n * @remarks\n * Behavior only. The controller manages state on catalog links via `aria-current`,\n * respects custom offsets, and dispatches `stimeo--scrollspy:change` events.\n */\nexport class ScrollspyController extends Controller<HTMLElement> {\n static override targets = [\"link\"];\n static override values = {\n offset: { type: Number, default: 0 },\n rootMargin: { type: String, default: \"\" },\n rootSelector: { type: String, default: \"\" },\n };\n static actions = [\"scrollTo\"] as const;\n static events = [\"change\"] as const;\n\n declare readonly linkTargets: HTMLElement[];\n\n declare offsetValue: number;\n declare rootMarginValue: string;\n declare rootSelectorValue: string;\n\n /** Shared IO plumbing (support guard, active guard, teardown). */\n readonly #watcher = new IntersectionWatcher((entries) => this.#onIntersection(entries));\n #isConnected = false;\n\n /** Track active/intersecting status of each section element by ID. */\n #intersectionStates = new Map<string, { isIntersecting: boolean; top: number }>();\n\n /** Current active section ID, used to avoid duplicate event dispatching. */\n #activeSectionId = \"\";\n\n override connect(): void {\n this.#isConnected = true;\n this.#initializeObserver();\n }\n\n override disconnect(): void {\n this.#isConnected = false;\n this.#watcher.stop();\n this.#intersectionStates.clear();\n this.#activeSectionId = \"\";\n }\n\n /**\n * Re-initializes the observer if the offset or rootMargin values change dynamically.\n */\n offsetValueChanged(): void {\n if (!this.#isConnected) return;\n this.#initializeObserver();\n }\n\n rootMarginValueChanged(): void {\n if (!this.#isConnected) return;\n this.#initializeObserver();\n }\n\n rootSelectorValueChanged(): void {\n if (!this.#isConnected) return;\n this.#initializeObserver();\n }\n\n /**\n * Smoothly scrolls to the target element mapped by the link anchor.\n * Prevents full window scroll jumps when tracking nested scrollable containers.\n */\n scrollTo(event: Event): void {\n const link = event.currentTarget as HTMLElement;\n const id = this.#getAnchorId(link);\n if (!id) return;\n\n event.preventDefault();\n\n const targetElement = document.getElementById(id);\n if (!targetElement) return;\n\n const rootElement = this.#getRootElement();\n if (rootElement) {\n const containerRect = rootElement.getBoundingClientRect();\n const targetRect = targetElement.getBoundingClientRect();\n const scrollPosition =\n rootElement.scrollTop + (targetRect.top - containerRect.top) - this.offsetValue;\n\n rootElement.scrollTo({\n top: scrollPosition,\n behavior: \"smooth\",\n });\n } else {\n const targetRect = targetElement.getBoundingClientRect();\n const scrollPosition = window.scrollY + targetRect.top - this.offsetValue;\n\n window.scrollTo({\n top: scrollPosition,\n behavior: \"smooth\",\n });\n }\n }\n\n #getRootElement(): HTMLElement | null {\n if (!this.rootSelectorValue) return null;\n return document.querySelector(this.rootSelectorValue);\n }\n\n #initializeObserver(): void {\n this.#watcher.stop();\n this.#intersectionStates.clear();\n this.#activeSectionId = \"\";\n\n if (this.linkTargets.length === 0) return;\n\n // Build the dynamic rootMargin string based on offset value\n const margin = this.rootMarginValue || `-${this.offsetValue}px 0px -80% 0px`;\n\n // Observe each target section mapped by the href anchors.\n const sections: Element[] = [];\n for (const link of this.linkTargets) {\n const id = this.#getAnchorId(link);\n if (!id) continue;\n const section = document.getElementById(id);\n if (section) sections.push(section);\n }\n\n this.#watcher.start(sections, {\n root: this.#getRootElement(),\n rootMargin: margin,\n threshold: [0, 0.2, 0.4, 0.6, 0.8, 1], // Multiple thresholds handle large sections safely\n });\n }\n\n readonly #onIntersection = (entries: IntersectionObserverEntry[]): void => {\n // Ignore any callback delivered after teardown: the browser may flush a\n // final queued batch right after `disconnect()`, and a detached controller\n // must not mutate `aria-current` on (possibly cached) links.\n if (!this.#isConnected) return;\n\n for (const entry of entries) {\n const id = entry.target.id;\n if (!id) continue;\n\n this.#intersectionStates.set(id, {\n isIntersecting: entry.isIntersecting,\n top: entry.boundingClientRect.top,\n });\n }\n\n this.#evaluateActiveSection();\n };\n\n #evaluateActiveSection(): void {\n // The trigger line is `offset` px below the top of the scroll root. When a\n // nested `rootSelector` container is used it is not at the viewport top, so\n // the line must be measured from the container's current top — comparing the\n // viewport-based `boundingClientRect.top` against a bare `offset` would\n // otherwise pick the section nearest the viewport top, not the container's.\n const rootEl = this.#getRootElement();\n const triggerLine = (rootEl ? rootEl.getBoundingClientRect().top : 0) + this.offsetValue;\n\n let bestId = \"\";\n let closestTop = Number.MAX_VALUE;\n\n // Evaluate among all intersecting elements\n for (const [id, state] of this.#intersectionStates.entries()) {\n if (state.isIntersecting) {\n // Evaluate the one closest to the offset trigger line\n const distance = Math.abs(state.top - triggerLine);\n if (distance < closestTop) {\n closestTop = distance;\n bestId = id;\n }\n }\n }\n\n // Fallback: when no section currently intersects (e.g. scrolled past the\n // bottom, or between sections), pick the tracked section whose top is closest\n // to the trigger line so something stays highlighted.\n if (!bestId && this.#intersectionStates.size > 0) {\n let absoluteClosestId = \"\";\n let absoluteClosestTop = Number.MAX_VALUE;\n\n for (const [id, state] of this.#intersectionStates.entries()) {\n const distance = Math.abs(state.top - triggerLine);\n if (distance < absoluteClosestTop) {\n absoluteClosestTop = distance;\n absoluteClosestId = id;\n }\n }\n bestId = absoluteClosestId;\n }\n\n if (bestId && bestId !== this.#activeSectionId) {\n this.#activeSectionId = bestId;\n this.#syncActiveStates();\n }\n }\n\n #syncActiveStates(): void {\n const activeLink = this.linkTargets.find((l) => this.#getAnchorId(l) === this.#activeSectionId);\n\n for (const link of this.linkTargets) {\n const isActive = link === activeLink;\n if (isActive) {\n link.setAttribute(\"aria-current\", \"location\");\n } else {\n link.removeAttribute(\"aria-current\");\n }\n }\n\n if (activeLink) {\n this.dispatch(\"change\", { detail: { id: this.#activeSectionId, link: activeLink } });\n }\n }\n\n #getAnchorId(link: HTMLElement): string | null {\n const href = link.getAttribute(\"href\") || link.getAttribute(\"data-href\");\n if (!href?.startsWith(\"#\")) return null;\n return href.substring(1);\n }\n}\n"]}
@@ -54,8 +54,8 @@ import { Controller } from '@hotwired/stimulus';
54
54
  * no rewiring, and a Turbo cache restore reconnects idempotently (`connect()`
55
55
  * clears the transient root hook; a drag cannot survive a navigation). Only the
56
56
  * event listeners are held, and they are removed on `disconnect()`. Multi-list
57
- * / kanban, nested DnD, auto-scroll at the edges, and virtualized lists are the
58
- * premium tier — deliberately out of this free single-list scope.
57
+ * / kanban, nested DnD, auto-scroll at the edges, and virtualized lists are
58
+ * deliberately out of this single-list scope.
59
59
  */
60
60
  declare class SortableController extends Controller<HTMLElement> {
61
61
  #private;
@@ -118,7 +118,7 @@ var SortableController = class extends Controller {
118
118
  * Mirrors a step into the `status` live region. Copy is localizable through
119
119
  * `data-grabbed` / `data-moved` / `data-dropped` / `data-canceled` templates on
120
120
  * the status element (`%{name}` / `%{position}` / `%{total}` placeholders);
121
- * terse English is the fallback (same channel design as `stimeo--feed`).
121
+ * terse English is the fallback (the library's shared status-channel design).
122
122
  */
123
123
  #announce(key, item) {
124
124
  if (!this.hasStatusTarget) return;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/controllers/sortable_controller.ts"],"names":[],"mappings":";;;AAoEO,IAAM,kBAAA,GAAN,cAAiC,UAAA,CAAwB;AAAA,EAC9D,OAAgB,OAAA,GAAU,CAAC,MAAA,EAAQ,QAAQ,QAAQ,CAAA;AAAA,EACnD,OAAgB,MAAA,GAAS;AAAA,IACvB,WAAA,EAAa,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,UAAA;AAAW,GACnD;AAAA,EACA,OAAO,MAAA,GAAS,CAAC,SAAS,CAAA;AAAA,EAS1B,QAAA,GAA+B,IAAA;AAAA,EAEtB,OAAA,GAAgB;AAGvB,IAAA,IAAA,CAAK,OAAA,CAAQ,gBAAgB,wBAAwB,CAAA;AACrD,IAAA,IAAA,CAAK,OAAA,CAAQ,gBAAA,CAAiB,4BAAA,EAA8B,IAAA,CAAK,YAAY,CAAA;AAC7E,IAAA,IAAA,CAAK,OAAA,CAAQ,gBAAA,CAAiB,2BAAA,EAA6B,IAAA,CAAK,WAAW,CAAA;AAC3E,IAAA,IAAA,CAAK,OAAA,CAAQ,gBAAA,CAAiB,0BAAA,EAA4B,IAAA,CAAK,UAAU,CAAA;AACzE,IAAA,IAAA,CAAK,OAAA,CAAQ,gBAAA,CAAiB,6BAAA,EAA+B,IAAA,CAAK,aAAa,CAAA;AAAA,EACjF;AAAA,EAES,UAAA,GAAmB;AAC1B,IAAA,IAAA,CAAK,OAAA,CAAQ,mBAAA,CAAoB,4BAAA,EAA8B,IAAA,CAAK,YAAY,CAAA;AAChF,IAAA,IAAA,CAAK,OAAA,CAAQ,mBAAA,CAAoB,2BAAA,EAA6B,IAAA,CAAK,WAAW,CAAA;AAC9E,IAAA,IAAA,CAAK,OAAA,CAAQ,mBAA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AAA;AAAA,EAGA,QAAQ,IAAA,EAA2B;AACjC,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,YAAA,CAAa,4BAA4B,CAAA;AAC/D,IAAA,IAAI,UAAU,OAAO,QAAA;AACrB,IAAA,OAAA,CAAQ,KAAK,WAAA,IAAe,EAAA,EAAI,QAAQ,MAAA,EAAQ,GAAG,EAAE,IAAA,EAAK;AAAA,EAC5D;AAAA;AAAA,EAGA,SAAS,MAAA,EAAgD;AACvD,IAAA,MAAM,IAAA,GAAO,MAAA;AACb,IAAA,IAAI,CAAC,MAAM,OAAO,IAAA;AAClB,IAAA,OAAO,IAAA,CAAK,MAAA,EAAO,CAAE,IAAA,CAAK,CAAC,IAAA,KAAS,IAAA,KAAS,IAAA,IAAQ,IAAA,CAAK,QAAA,CAAS,IAAI,CAAC,CAAA,IAAK,IAAA;AAAA,EAC/E;AAAA;AAAA,EAGA,MAAA,GAAwB;AACtB,IAAA,OAAO,IAAA,CAAK,WAAA;AAAA,EACd;AAAA;AAAA,EAGA,IAAI,KAAA,GAAqB;AACvB,IAAA,OAAO,IAAA,CAAK,aAAA,GAAgB,IAAA,CAAK,UAAA,GAAa,IAAA,CAAK,OAAA;AAAA,EACrD;AAAA,EAEA,IAAI,WAAA,GAAuB;AACzB,IAAA,OAAO,KAAK,gBAAA,KAAqB,YAAA;AAAA,EACnC;AACF","file":"sortable_controller.js","sourcesContent":["import { Controller } from \"@hotwired/stimulus\";\n\n/** A reorder in flight: one item picked up by pointer or keyboard. */\ninterface SortSession {\n item: HTMLElement;\n /** Index at pickup, for the `reorder` detail and the cancel restore. */\n from: number;\n /** Last primary-axis cumulative delta consumed by keyboard stepping. */\n lastPrimary: number;\n}\n\n/**\n * Headless, accessible **sortable** (single-list reorder) — the a11y-first\n * drag-and-drop that is the flagship consumer of the\n * `stimeo--pointer-drag` primitive. The composition is markup-level and each\n * layer keeps its job: `pointer-drag` (on every item) emits the normalized drag\n * signal with its built-in keyboard alternative, `roving` (on the list) keeps\n * the handles a single Tab stop, and this controller interprets the signal —\n * live-reordering the DOM, announcing each step through a `status` live region,\n * and reporting the final `reorder`. No dedicated APG pattern exists for\n * drag-and-drop; the keyboard model (grab → arrows → drop / Escape) comes from\n * `pointer-drag` and the announcements make it non-visually trackable\n * (WCAG 2.1.1 / 2.5.7 / 4.1.3). Core (zero dependencies).\n *\n * Markup contract (identifier: `stimeo--sortable`):\n * <div data-controller=\"stimeo--sortable\">\n * <ul data-stimeo--sortable-target=\"list\" data-controller=\"stimeo--roving\"\n * data-stimeo--roving-orientation-value=\"vertical\">\n * <li data-stimeo--sortable-target=\"item\" data-stimeo--sortable-name=\"Card A\"\n * data-controller=\"stimeo--pointer-drag\"\n * data-stimeo--pointer-drag-axis-value=\"y\">\n * <span>Card A</span>\n * <button type=\"button\" aria-label=\"Reorder Card A\"\n * data-stimeo--pointer-drag-target=\"handle\"\n * data-stimeo--roving-target=\"item\">⠿</button>\n * </li>\n * …\n * </ul>\n * <span role=\"status\" data-stimeo--sortable-target=\"status\"></span>\n * </div>\n *\n * The composed values must follow the sort axis: roving's `orientation`\n * (which defaults to `horizontal`, so a vertical list has to author\n * `vertical`) and pointer-drag's `axis`. `stimeo check` enforces both\n * alignments as composition rules (`composition-mismatch`).\n *\n * Pointer flow: dragging an item live-moves it whenever the pointer crosses a\n * sibling's midpoint (per `orientation`). Keyboard flow: each synthetic\n * `pointer-drag` move steps the item one position. Dropping dispatches\n * `reorder` (`{ item, from, to }`, zero-based) when the position changed;\n * Escape / `pointercancel` restores the pickup position. Every step is mirrored\n * into the `status` live region (localizable via `data-grabbed` / `data-moved`\n * / `data-dropped` / `data-canceled` templates with `%{name}` / `%{position}` /\n * `%{total}` placeholders; terse English is the fallback).\n *\n * @remarks\n * Behavior only — the ghost/placeholder/drop-hint visuals are the consumer's\n * CSS, keyed off `pointer-drag`'s `data-dragging`/`data-grabbed` on the item\n * and this controller's `data-sortable-dragging` on the root. Persistence is\n * the consumer's `reorder` listener (post the new position; a Turbo Stream\n * broadcast makes the board collaborative). The DOM order is the single source\n * of truth: items are read live on every event, so rows appended by Turbo need\n * no rewiring, and a Turbo cache restore reconnects idempotently (`connect()`\n * clears the transient root hook; a drag cannot survive a navigation). Only the\n * event listeners are held, and they are removed on `disconnect()`. Multi-list\n * / kanban, nested DnD, auto-scroll at the edges, and virtualized lists are the\n * premium tier — deliberately out of this free single-list scope.\n */\nexport class SortableController extends Controller<HTMLElement> {\n static override targets = [\"list\", \"item\", \"status\"];\n static override values = {\n orientation: { type: String, default: \"vertical\" },\n };\n static events = [\"reorder\"] as const;\n\n declare readonly hasListTarget: boolean;\n declare readonly listTarget: HTMLElement;\n declare readonly itemTargets: HTMLElement[];\n declare readonly hasStatusTarget: boolean;\n declare readonly statusTarget: HTMLElement;\n declare orientationValue: string;\n\n #session: SortSession | null = null;\n\n override connect(): void {\n // A drag cannot survive a navigation: drop the hook a Turbo cache snapshot\n // may have preserved mid-drag (idempotent reconnect).\n this.element.removeAttribute(\"data-sortable-dragging\");\n this.element.addEventListener(\"stimeo--pointer-drag:start\", this.#onDragStart);\n this.element.addEventListener(\"stimeo--pointer-drag:move\", this.#onDragMove);\n this.element.addEventListener(\"stimeo--pointer-drag:end\", this.#onDragEnd);\n this.element.addEventListener(\"stimeo--pointer-drag:cancel\", this.#onDragCancel);\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"stimeo--pointer-drag:start\", this.#onDragStart);\n this.element.removeEventListener(\"stimeo--pointer-drag:move\", this.#onDragMove);\n this.element.removeEventListener(\"stimeo--pointer-drag:end\", this.#onDragEnd);\n this.element.removeEventListener(\"stimeo--pointer-drag:cancel\", this.#onDragCancel);\n this.#session = null;\n this.element.removeAttribute(\"data-sortable-dragging\");\n }\n\n /** Picks the item up: remembers its origin and announces the grab. */\n readonly #onDragStart = (event: Event): void => {\n // One reorder at a time: a start from another item (each item has its own\n // pointer-drag instance) must not clobber the live session — its from\n // index and cancel restore would be lost.\n if (this.#session) return;\n const item = this.#itemFor(event.target);\n if (!item) return;\n this.#session = { item, from: this.#items().indexOf(item), lastPrimary: 0 };\n this.element.setAttribute(\"data-sortable-dragging\", \"true\");\n this.#announce(\"grabbed\", item);\n };\n\n readonly #onDragMove = (event: Event): void => {\n const session = this.#session;\n const detail = (event as CustomEvent<Record<string, number | string>>).detail;\n if (!session || this.#itemFor(event.target) !== session.item) return;\n\n if (detail.pointerType === \"keyboard\") {\n this.#stepFromKeyboard(session, detail);\n } else {\n this.#followPointer(session, detail);\n }\n };\n\n /** Drops the item: announces, then reports `reorder` if the position changed. */\n readonly #onDragEnd = (event: Event): void => {\n const session = this.#session;\n if (!session || this.#itemFor(event.target) !== session.item) return;\n this.#session = null;\n this.element.removeAttribute(\"data-sortable-dragging\");\n this.#announce(\"dropped\", session.item);\n const to = this.#items().indexOf(session.item);\n if (to !== session.from) {\n this.dispatch(\"reorder\", { detail: { item: session.item, from: session.from, to } });\n }\n };\n\n /** Restores the pickup position (Escape / OS `pointercancel`). */\n readonly #onDragCancel = (event: Event): void => {\n const session = this.#session;\n if (!session || this.#itemFor(event.target) !== session.item) return;\n this.#session = null;\n this.element.removeAttribute(\"data-sortable-dragging\");\n this.#moveTo(session.item, session.from);\n this.#announce(\"canceled\", session.item);\n };\n\n /**\n * Keyboard stepping: `pointer-drag` reports *cumulative* synthetic deltas, so\n * the difference from the last consumed value is one arrow press — its sign is\n * the direction. Cross-axis arrows never change the primary delta (no move).\n */\n #stepFromKeyboard(session: SortSession, detail: Record<string, number | string>): void {\n const primary = Number(this.#isVertical ? detail.dy : detail.dx) || 0;\n const delta = primary - session.lastPrimary;\n session.lastPrimary = primary;\n if (delta === 0) return;\n\n const items = this.#items();\n const index = items.indexOf(session.item);\n const next = Math.max(0, Math.min(index + (delta > 0 ? 1 : -1), items.length - 1));\n if (next === index) return;\n this.#moveTo(session.item, next);\n this.#announce(\"moved\", session.item);\n }\n\n /**\n * Pointer following: the item moves to the slot whose siblings' midpoints the\n * pointer has passed (per `orientation`). Skipped when the list has no layout\n * geometry (every rect is zero — nothing meaningful to compare against).\n */\n #followPointer(session: SortSession, detail: Record<string, number | string>): void {\n const pointer = Number(this.#isVertical ? detail.y : detail.x) || 0;\n const others = this.#items().filter((item) => item !== session.item);\n if (others.length === 0) return;\n\n let laidOut = false;\n let target = 0;\n for (const other of others) {\n const rect = other.getBoundingClientRect();\n if (rect.width > 0 || rect.height > 0) laidOut = true;\n const midpoint = this.#isVertical ? rect.top + rect.height / 2 : rect.left + rect.width / 2;\n if (pointer > midpoint) target += 1;\n }\n if (!laidOut) return;\n\n // The item's index among all items equals the count of others before it,\n // so it doubles as the current insertion slot in others-space.\n const current = this.#items().indexOf(session.item);\n if (target !== current) {\n this.#moveTo(session.item, target);\n this.#announce(\"moved\", session.item);\n }\n }\n\n /** Reinserts `item` so it lands at `index` among the list's items. */\n #moveTo(item: HTMLElement, index: number): void {\n const others = this.#items().filter((candidate) => candidate !== item);\n const clamped = Math.max(0, Math.min(index, others.length));\n const reference = others[clamped] ?? null;\n // Real browsers drop focus when the focused node is re-inserted (the move\n // is a remove+insert), which would strand the keyboard grab after one\n // arrow press — restore it so focus rides the moved item.\n const active = document.activeElement;\n const hadFocus = active instanceof HTMLElement && item.contains(active);\n this.#list.insertBefore(item, reference);\n if (hadFocus) active.focus();\n }\n\n /**\n * Mirrors a step into the `status` live region. Copy is localizable through\n * `data-grabbed` / `data-moved` / `data-dropped` / `data-canceled` templates on\n * the status element (`%{name}` / `%{position}` / `%{total}` placeholders);\n * terse English is the fallback (same channel design as `stimeo--feed`).\n */\n #announce(key: \"grabbed\" | \"moved\" | \"dropped\" | \"canceled\", item: HTMLElement): void {\n if (!this.hasStatusTarget) return;\n const position = String(this.#items().indexOf(item) + 1);\n const total = String(this.#items().length);\n const name = this.#nameOf(item);\n const fallback = {\n grabbed: `Grabbed ${name}, position ${position} of ${total}`,\n moved: `${name}, position ${position} of ${total}`,\n dropped: `Dropped ${name} at position ${position} of ${total}`,\n canceled: `Reorder canceled, ${name} returned to position ${position} of ${total}`,\n } as const;\n // Single-pass function replacement keeps the substitution literal-safe:\n // `$`-sequences in the (author/content-derived) name never expand, and a\n // name that happens to contain a placeholder token is not re-substituted.\n const values: Record<string, string> = { name, position, total };\n const template = this.statusTarget.dataset[key];\n this.statusTarget.textContent = template\n ? template.replace(/%\\{(name|position|total)\\}/g, (match, token: string) => {\n return values[token] ?? match;\n })\n : fallback[key];\n }\n\n /** The announced item name: the authored override, else its collapsed text. */\n #nameOf(item: HTMLElement): string {\n const authored = item.getAttribute(\"data-stimeo--sortable-name\");\n if (authored) return authored;\n return (item.textContent ?? \"\").replace(/\\s+/g, \" \").trim();\n }\n\n /** Resolves the sortable item owning a bubbled `pointer-drag` event. */\n #itemFor(target: EventTarget | null): HTMLElement | null {\n const node = target as Node | null;\n if (!node) return null;\n return this.#items().find((item) => item === node || item.contains(node)) ?? null;\n }\n\n /** The items in live DOM order (targets re-query the DOM on every access). */\n #items(): HTMLElement[] {\n return this.itemTargets;\n }\n\n /** The reorder container: the `list` target when present, else the element. */\n get #list(): HTMLElement {\n return this.hasListTarget ? this.listTarget : this.element;\n }\n\n get #isVertical(): boolean {\n return this.orientationValue !== \"horizontal\";\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/controllers/sortable_controller.ts"],"names":[],"mappings":";;;AAoEO,IAAM,kBAAA,GAAN,cAAiC,UAAA,CAAwB;AAAA,EAC9D,OAAgB,OAAA,GAAU,CAAC,MAAA,EAAQ,QAAQ,QAAQ,CAAA;AAAA,EACnD,OAAgB,MAAA,GAAS;AAAA,IACvB,WAAA,EAAa,EAAE,IAAA,EAAM,MAAA,EAAQ,SAAS,UAAA;AAAW,GACnD;AAAA,EACA,OAAO,MAAA,GAAS,CAAC,SAAS,CAAA;AAAA,EAS1B,QAAA,GAA+B,IAAA;AAAA,EAEtB,OAAA,GAAgB;AAGvB,IAAA,IAAA,CAAK,OAAA,CAAQ,gBAAgB,wBAAwB,CAAA;AACrD,IAAA,IAAA,CAAK,OAAA,CAAQ,gBA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,GAAqB;AACvB,IAAA,OAAO,IAAA,CAAK,aAAA,GAAgB,IAAA,CAAK,UAAA,GAAa,IAAA,CAAK,OAAA;AAAA,EACrD;AAAA,EAEA,IAAI,WAAA,GAAuB;AACzB,IAAA,OAAO,KAAK,gBAAA,KAAqB,YAAA;AAAA,EACnC;AACF","file":"sortable_controller.js","sourcesContent":["import { Controller } from \"@hotwired/stimulus\";\n\n/** A reorder in flight: one item picked up by pointer or keyboard. */\ninterface SortSession {\n item: HTMLElement;\n /** Index at pickup, for the `reorder` detail and the cancel restore. */\n from: number;\n /** Last primary-axis cumulative delta consumed by keyboard stepping. */\n lastPrimary: number;\n}\n\n/**\n * Headless, accessible **sortable** (single-list reorder) — the a11y-first\n * drag-and-drop that is the flagship consumer of the\n * `stimeo--pointer-drag` primitive. The composition is markup-level and each\n * layer keeps its job: `pointer-drag` (on every item) emits the normalized drag\n * signal with its built-in keyboard alternative, `roving` (on the list) keeps\n * the handles a single Tab stop, and this controller interprets the signal —\n * live-reordering the DOM, announcing each step through a `status` live region,\n * and reporting the final `reorder`. No dedicated APG pattern exists for\n * drag-and-drop; the keyboard model (grab → arrows → drop / Escape) comes from\n * `pointer-drag` and the announcements make it non-visually trackable\n * (WCAG 2.1.1 / 2.5.7 / 4.1.3). Core (zero dependencies).\n *\n * Markup contract (identifier: `stimeo--sortable`):\n * <div data-controller=\"stimeo--sortable\">\n * <ul data-stimeo--sortable-target=\"list\" data-controller=\"stimeo--roving\"\n * data-stimeo--roving-orientation-value=\"vertical\">\n * <li data-stimeo--sortable-target=\"item\" data-stimeo--sortable-name=\"Card A\"\n * data-controller=\"stimeo--pointer-drag\"\n * data-stimeo--pointer-drag-axis-value=\"y\">\n * <span>Card A</span>\n * <button type=\"button\" aria-label=\"Reorder Card A\"\n * data-stimeo--pointer-drag-target=\"handle\"\n * data-stimeo--roving-target=\"item\">⠿</button>\n * </li>\n * …\n * </ul>\n * <span role=\"status\" data-stimeo--sortable-target=\"status\"></span>\n * </div>\n *\n * The composed values must follow the sort axis: roving's `orientation`\n * (which defaults to `horizontal`, so a vertical list has to author\n * `vertical`) and pointer-drag's `axis`. `stimeo check` enforces both\n * alignments as composition rules (`composition-mismatch`).\n *\n * Pointer flow: dragging an item live-moves it whenever the pointer crosses a\n * sibling's midpoint (per `orientation`). Keyboard flow: each synthetic\n * `pointer-drag` move steps the item one position. Dropping dispatches\n * `reorder` (`{ item, from, to }`, zero-based) when the position changed;\n * Escape / `pointercancel` restores the pickup position. Every step is mirrored\n * into the `status` live region (localizable via `data-grabbed` / `data-moved`\n * / `data-dropped` / `data-canceled` templates with `%{name}` / `%{position}` /\n * `%{total}` placeholders; terse English is the fallback).\n *\n * @remarks\n * Behavior only — the ghost/placeholder/drop-hint visuals are the consumer's\n * CSS, keyed off `pointer-drag`'s `data-dragging`/`data-grabbed` on the item\n * and this controller's `data-sortable-dragging` on the root. Persistence is\n * the consumer's `reorder` listener (post the new position; a Turbo Stream\n * broadcast makes the board collaborative). The DOM order is the single source\n * of truth: items are read live on every event, so rows appended by Turbo need\n * no rewiring, and a Turbo cache restore reconnects idempotently (`connect()`\n * clears the transient root hook; a drag cannot survive a navigation). Only the\n * event listeners are held, and they are removed on `disconnect()`. Multi-list\n * / kanban, nested DnD, auto-scroll at the edges, and virtualized lists are\n * deliberately out of this single-list scope.\n */\nexport class SortableController extends Controller<HTMLElement> {\n static override targets = [\"list\", \"item\", \"status\"];\n static override values = {\n orientation: { type: String, default: \"vertical\" },\n };\n static events = [\"reorder\"] as const;\n\n declare readonly hasListTarget: boolean;\n declare readonly listTarget: HTMLElement;\n declare readonly itemTargets: HTMLElement[];\n declare readonly hasStatusTarget: boolean;\n declare readonly statusTarget: HTMLElement;\n declare orientationValue: string;\n\n #session: SortSession | null = null;\n\n override connect(): void {\n // A drag cannot survive a navigation: drop the hook a Turbo cache snapshot\n // may have preserved mid-drag (idempotent reconnect).\n this.element.removeAttribute(\"data-sortable-dragging\");\n this.element.addEventListener(\"stimeo--pointer-drag:start\", this.#onDragStart);\n this.element.addEventListener(\"stimeo--pointer-drag:move\", this.#onDragMove);\n this.element.addEventListener(\"stimeo--pointer-drag:end\", this.#onDragEnd);\n this.element.addEventListener(\"stimeo--pointer-drag:cancel\", this.#onDragCancel);\n }\n\n override disconnect(): void {\n this.element.removeEventListener(\"stimeo--pointer-drag:start\", this.#onDragStart);\n this.element.removeEventListener(\"stimeo--pointer-drag:move\", this.#onDragMove);\n this.element.removeEventListener(\"stimeo--pointer-drag:end\", this.#onDragEnd);\n this.element.removeEventListener(\"stimeo--pointer-drag:cancel\", this.#onDragCancel);\n this.#session = null;\n this.element.removeAttribute(\"data-sortable-dragging\");\n }\n\n /** Picks the item up: remembers its origin and announces the grab. */\n readonly #onDragStart = (event: Event): void => {\n // One reorder at a time: a start from another item (each item has its own\n // pointer-drag instance) must not clobber the live session — its from\n // index and cancel restore would be lost.\n if (this.#session) return;\n const item = this.#itemFor(event.target);\n if (!item) return;\n this.#session = { item, from: this.#items().indexOf(item), lastPrimary: 0 };\n this.element.setAttribute(\"data-sortable-dragging\", \"true\");\n this.#announce(\"grabbed\", item);\n };\n\n readonly #onDragMove = (event: Event): void => {\n const session = this.#session;\n const detail = (event as CustomEvent<Record<string, number | string>>).detail;\n if (!session || this.#itemFor(event.target) !== session.item) return;\n\n if (detail.pointerType === \"keyboard\") {\n this.#stepFromKeyboard(session, detail);\n } else {\n this.#followPointer(session, detail);\n }\n };\n\n /** Drops the item: announces, then reports `reorder` if the position changed. */\n readonly #onDragEnd = (event: Event): void => {\n const session = this.#session;\n if (!session || this.#itemFor(event.target) !== session.item) return;\n this.#session = null;\n this.element.removeAttribute(\"data-sortable-dragging\");\n this.#announce(\"dropped\", session.item);\n const to = this.#items().indexOf(session.item);\n if (to !== session.from) {\n this.dispatch(\"reorder\", { detail: { item: session.item, from: session.from, to } });\n }\n };\n\n /** Restores the pickup position (Escape / OS `pointercancel`). */\n readonly #onDragCancel = (event: Event): void => {\n const session = this.#session;\n if (!session || this.#itemFor(event.target) !== session.item) return;\n this.#session = null;\n this.element.removeAttribute(\"data-sortable-dragging\");\n this.#moveTo(session.item, session.from);\n this.#announce(\"canceled\", session.item);\n };\n\n /**\n * Keyboard stepping: `pointer-drag` reports *cumulative* synthetic deltas, so\n * the difference from the last consumed value is one arrow press — its sign is\n * the direction. Cross-axis arrows never change the primary delta (no move).\n */\n #stepFromKeyboard(session: SortSession, detail: Record<string, number | string>): void {\n const primary = Number(this.#isVertical ? detail.dy : detail.dx) || 0;\n const delta = primary - session.lastPrimary;\n session.lastPrimary = primary;\n if (delta === 0) return;\n\n const items = this.#items();\n const index = items.indexOf(session.item);\n const next = Math.max(0, Math.min(index + (delta > 0 ? 1 : -1), items.length - 1));\n if (next === index) return;\n this.#moveTo(session.item, next);\n this.#announce(\"moved\", session.item);\n }\n\n /**\n * Pointer following: the item moves to the slot whose siblings' midpoints the\n * pointer has passed (per `orientation`). Skipped when the list has no layout\n * geometry (every rect is zero — nothing meaningful to compare against).\n */\n #followPointer(session: SortSession, detail: Record<string, number | string>): void {\n const pointer = Number(this.#isVertical ? detail.y : detail.x) || 0;\n const others = this.#items().filter((item) => item !== session.item);\n if (others.length === 0) return;\n\n let laidOut = false;\n let target = 0;\n for (const other of others) {\n const rect = other.getBoundingClientRect();\n if (rect.width > 0 || rect.height > 0) laidOut = true;\n const midpoint = this.#isVertical ? rect.top + rect.height / 2 : rect.left + rect.width / 2;\n if (pointer > midpoint) target += 1;\n }\n if (!laidOut) return;\n\n // The item's index among all items equals the count of others before it,\n // so it doubles as the current insertion slot in others-space.\n const current = this.#items().indexOf(session.item);\n if (target !== current) {\n this.#moveTo(session.item, target);\n this.#announce(\"moved\", session.item);\n }\n }\n\n /** Reinserts `item` so it lands at `index` among the list's items. */\n #moveTo(item: HTMLElement, index: number): void {\n const others = this.#items().filter((candidate) => candidate !== item);\n const clamped = Math.max(0, Math.min(index, others.length));\n const reference = others[clamped] ?? null;\n // Real browsers drop focus when the focused node is re-inserted (the move\n // is a remove+insert), which would strand the keyboard grab after one\n // arrow press — restore it so focus rides the moved item.\n const active = document.activeElement;\n const hadFocus = active instanceof HTMLElement && item.contains(active);\n this.#list.insertBefore(item, reference);\n if (hadFocus) active.focus();\n }\n\n /**\n * Mirrors a step into the `status` live region. Copy is localizable through\n * `data-grabbed` / `data-moved` / `data-dropped` / `data-canceled` templates on\n * the status element (`%{name}` / `%{position}` / `%{total}` placeholders);\n * terse English is the fallback (the library's shared status-channel design).\n */\n #announce(key: \"grabbed\" | \"moved\" | \"dropped\" | \"canceled\", item: HTMLElement): void {\n if (!this.hasStatusTarget) return;\n const position = String(this.#items().indexOf(item) + 1);\n const total = String(this.#items().length);\n const name = this.#nameOf(item);\n const fallback = {\n grabbed: `Grabbed ${name}, position ${position} of ${total}`,\n moved: `${name}, position ${position} of ${total}`,\n dropped: `Dropped ${name} at position ${position} of ${total}`,\n canceled: `Reorder canceled, ${name} returned to position ${position} of ${total}`,\n } as const;\n // Single-pass function replacement keeps the substitution literal-safe:\n // `$`-sequences in the (author/content-derived) name never expand, and a\n // name that happens to contain a placeholder token is not re-substituted.\n const values: Record<string, string> = { name, position, total };\n const template = this.statusTarget.dataset[key];\n this.statusTarget.textContent = template\n ? template.replace(/%\\{(name|position|total)\\}/g, (match, token: string) => {\n return values[token] ?? match;\n })\n : fallback[key];\n }\n\n /** The announced item name: the authored override, else its collapsed text. */\n #nameOf(item: HTMLElement): string {\n const authored = item.getAttribute(\"data-stimeo--sortable-name\");\n if (authored) return authored;\n return (item.textContent ?? \"\").replace(/\\s+/g, \" \").trim();\n }\n\n /** Resolves the sortable item owning a bubbled `pointer-drag` event. */\n #itemFor(target: EventTarget | null): HTMLElement | null {\n const node = target as Node | null;\n if (!node) return null;\n return this.#items().find((item) => item === node || item.contains(node)) ?? null;\n }\n\n /** The items in live DOM order (targets re-query the DOM on every access). */\n #items(): HTMLElement[] {\n return this.itemTargets;\n }\n\n /** The reorder container: the `list` target when present, else the element. */\n get #list(): HTMLElement {\n return this.hasListTarget ? this.listTarget : this.element;\n }\n\n get #isVertical(): boolean {\n return this.orientationValue !== \"horizontal\";\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/intersection_watcher.ts","../../src/controllers/sticky_observer_controller.ts"],"names":[],"mappings":";;;;;AA8BO,IAAM,sBAAN,MAA0B;AAAA,EACtB,UAAA;AAAA,EACT,SAAA,GAAyC,IAAA;AAAA,EACzC,OAAA,GAAU,KAAA;AAAA,EAEV,YAAY,SAAA,EAA2D;AACrE,IAAA,IAAA,CAAK,UAAA,GAAa,SAAA;AAAA,EACpB;AAAA;AAAA,EAGA,IAAI,MAAA,GAAkB;AACpB,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,KAAA,CAAM,OAAA,EAAuC,OAAA,GAAoC,EAAC,EAAY;AAC5F,IAAA,IAAA,CAAK,IAAA,EAAK;AACV,IAAA,IAAI,OAAO,oBAAA,KAAyB,WAAA,EAAa,OAAO,KAAA;AACxD,IAAA,MAAM,OAAO,KAAA,CAAM,OAAA,CAAQ,OAAO,CAAA,GAAK,OAAA,GAAiC,CAAC,OAAkB,CAAA;AAC3F,IAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,KAAA;AAE9B,IAAA,MAAM,IAAA,GACJ,MAAA,IAAU,OAAA,GACL,OAAA,CAAQ,IAAA,IAAQ,IAAA,GACjB,OAAA,CAAQ,YAAA,GACN,QAAA,CAAS,aAAA,CAAc,OAAA,CAAQ,YAAY,CAAA,GAC3C,IAAA;AAER,IAAA,IAAA,CAAK,OAAA,GAAU,IAAA;AACf,IAAA,IAAA,CAAK,YAAY,IAAI,oBAAA;AAAA,MACnB,CAAC,OAAA,KAAY;AACX,QAAA,IAAI,IAAA,CAAK,OAAA,EAAS,IAAA,CAAK,UAAA,CAAW,OAAO,CAAA;AAAA,MAC3C,CAAA;AAAA,MACA,EAAE,IAAA,EAAM,UAAA,E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;AAGZ,IAAA,IAAA,CAAK,SAAA,CAAU,CAAC,KAAA,CAAM,cAAc,CAAA;AAAA,EACtC;AAAA,EAES,OAAA,GAAgB;AACvB,IAAA,IAAI,CAAC,KAAK,iBAAA,EAAmB;AAC7B,IAAA,IAAA,CAAK,QAAA,CAAS,KAAA,CAAM,IAAA,CAAK,cAAA,EAAgB;AAAA,MACvC,cAAc,IAAA,CAAK,iBAAA;AAAA,MACnB,UAAA,EAAY,CAAA,CAAA,EAAI,IAAA,CAAK,WAAW,CAAA,cAAA,CAAA;AAAA,MAChC,SAAA,EAAW,CAAC,CAAC;AAAA,KACd,CAAA;AAAA,EACH;AAAA,EAES,UAAA,GAAmB;AAC1B,IAAA,IAAA,CAAK,SAAS,IAAA,EAAK;AACnB,IAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AAAA,EAChB;AAAA;AAAA,EAGA,UAAU,IAAA,EAAqB;AAC7B,IAAA,IAAI,IAAA,KAAS,KAAK,MAAA,EAAQ;AAC1B,IAAA,IAAA,CAAK,MAAA,GAAS,IAAA;AACd,IAAA,IAAI,KAAK,gBAAA,EAAkB;AACzB,MAAA,IAAA,CAAK,aAAA,CAAc,YAAA,CAAa,YAAA,EAAc,IAAA,GAAO,SAAS,OAAO,CAAA;AAAA,IACvE;AACA,IAAA,IAAA,CAAK,QAAA,CAAS,UAAU,EAAE,MAAA,EAAQ,EAAE,KAAA,EAAO,IAAA,IAAQ,CAAA;AAAA,EACrD;AACF","file":"sticky_observer_controller.js","sourcesContent":["/**\n * Shared `IntersectionObserver` plumbing for Stimeo's scroll-triggered\n * controllers (`intersection`, `scrollspy`, `sticky-observer`, `lazy-frame`).\n *\n * These controllers each grew a separate implementation of the same idea;\n * this util is that idea written once — the boilerplate every consumer\n * repeated: the `IntersectionObserver` support guard, root resolution from a\n * selector, observer creation/teardown, the **active guard** (the browser may\n * flush a final queued callback batch right after `disconnect()`, and a\n * detached controller must not mutate possibly-cached DOM), and the\n * unobserve→observe **re-arm** that re-delivers the current state (the\n * infinite-scroll \"sentinel never left the viewport\" fix).\n *\n * Like {@link RovingTabindex} and `FocusTrap`, this is a policy-free internal\n * util: what an intersection *means* (a spied link, a stuck header, a lazy\n * load) stays in each controller. The public `stimeo--intersection` controller\n * is its thin declarative face.\n */\nexport interface IntersectionWatchOptions {\n /**\n * The observation root. Pass an element (or `null` for the viewport) when\n * the caller already resolved it; omit to resolve from `rootSelector`.\n */\n root?: Element | null;\n /** Selector for the observation root; empty/omitted = viewport. */\n rootSelector?: string;\n rootMargin?: string;\n threshold?: number | number[];\n}\n\nexport class IntersectionWatcher {\n readonly #onEntries: (entries: IntersectionObserverEntry[]) => void;\n #observer: IntersectionObserver | null = null;\n #active = false;\n\n constructor(onEntries: (entries: IntersectionObserverEntry[]) => void) {\n this.#onEntries = onEntries;\n }\n\n /** Whether an observer is live (started, `IntersectionObserver` supported). */\n get active(): boolean {\n return this.#active;\n }\n\n /**\n * (Re)creates the observer and observes `targets`. Returns `false` — leaving\n * the watcher inert — without `IntersectionObserver` support (very old\n * browsers; the caller's no-JS fallback stays in charge) or with no targets.\n */\n start(targets: Element | readonly Element[], options: IntersectionWatchOptions = {}): boolean {\n this.stop();\n if (typeof IntersectionObserver === \"undefined\") return false;\n const list = Array.isArray(targets) ? (targets as readonly Element[]) : [targets as Element];\n if (list.length === 0) return false;\n\n const root =\n \"root\" in options\n ? (options.root ?? null)\n : options.rootSelector\n ? document.querySelector(options.rootSelector)\n : null;\n\n this.#active = true;\n this.#observer = new IntersectionObserver(\n (entries) => {\n if (this.#active) this.#onEntries(entries);\n },\n { root, rootMargin: options.rootMargin, threshold: options.threshold },\n );\n for (const target of list) this.#observer.observe(target);\n return true;\n }\n\n /**\n * Re-delivers `target`'s CURRENT intersection state: `IntersectionObserver`\n * only reports *changes*, but `observe()` always reports the present state,\n * so unobserve→observe turns \"still intersecting\" into a fresh callback.\n */\n rearm(target: Element): void {\n if (!this.#observer) return;\n this.#observer.unobserve(target);\n this.#observer.observe(target);\n }\n\n /** Severs the observer; late queued callbacks become no-ops via the guard. */\n stop(): void {\n this.#active = false;\n this.#observer?.disconnect();\n this.#observer = null;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { IntersectionWatcher } from \"../utils/intersection_watcher\";\n\n/**\n * Headless **Sticky State Observer**: detects whether a `position: sticky`\n * element is currently stuck and publishes it as `data-stuck`. No APG widget — a\n * pure state-detection utility. Detection uses an {@link IntersectionObserver}\n * and a sentinel placed just before the sticky element, avoiding per-frame scroll\n * math.\n *\n * Markup contract (identifier: `stimeo--sticky-observer`):\n * <div data-controller=\"stimeo--sticky-observer\">\n * <div data-stimeo--sticky-observer-target=\"sentinel\"\n * aria-hidden=\"true\" style=\"height: 1px;\"></div>\n * <header data-stimeo--sticky-observer-target=\"element\"\n * style=\"position: sticky; top: 0;\">Site heading</header>\n * <main>…</main>\n * </div>\n *\n * When the sentinel scrolls out past the top of the viewport (or `rootSelector`\n * container), the sticky element is considered stuck and `data-stuck=\"true\"` is\n * set; otherwise `false`. The `change` event fires on each transition.\n *\n * @remarks\n * Behavior only — `position: sticky`, shadows, and shrink effects are the\n * consumer's CSS (`[data-stuck=\"true\"] { … }`). `data-stuck` is a visual hook\n * only: it carries no ARIA role/state. `offset` feeds a negative top `rootMargin`\n * and must match the sticky element's CSS `top`. The observer is disconnected on\n * `disconnect()` (Turbo navigation included).\n */\nexport class StickyObserverController extends Controller<HTMLElement> {\n static override targets = [\"sentinel\", \"element\"];\n static override values = {\n rootSelector: { type: String, default: \"\" },\n offset: { type: Number, default: 0 },\n };\n static events = [\"change\"] as const;\n\n declare readonly sentinelTarget: HTMLElement;\n declare readonly elementTarget: HTMLElement;\n declare readonly hasSentinelTarget: boolean;\n declare readonly hasElementTarget: boolean;\n\n declare rootSelectorValue: string;\n declare offsetValue: number;\n\n /** Shared IO plumbing (support guard, root resolution, active guard). */\n readonly #watcher = new IntersectionWatcher((entries) => this.#onIntersect(entries));\n /** Last reported stuck state, so `change` fires only on transitions. */\n #stuck: boolean | null = null;\n\n #onIntersect(entries: IntersectionObserverEntry[]): void {\n const entry = entries[entries.length - 1];\n if (!entry) return;\n // The sentinel sits above the sticky element; once it is no longer\n // intersecting the (top-inset) root, the sticky element has stuck.\n this.#setStuck(!entry.isIntersecting);\n }\n\n override connect(): void {\n if (!this.hasSentinelTarget) return;\n this.#watcher.start(this.sentinelTarget, {\n rootSelector: this.rootSelectorValue,\n rootMargin: `-${this.offsetValue}px 0px 0px 0px`,\n threshold: [0],\n });\n }\n\n override disconnect(): void {\n this.#watcher.stop();\n this.#stuck = null;\n }\n\n /** Reflects the stuck state onto the sticky element and emits `change`. */\n #setStuck(next: boolean): void {\n if (next === this.#stuck) return;\n this.#stuck = next;\n if (this.hasElementTarget) {\n this.elementTarget.setAttribute(\"data-stuck\", next ? \"true\" : \"false\");\n }\n this.dispatch(\"change\", { detail: { stuck: next } });\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/intersection_watcher.ts","../../src/controllers/sticky_observer_controller.ts"],"names":[],"mappings":";;;;;AA4BO,IAAM,sBAAN,MAA0B;AAAA,EACtB,UAAA;AAAA,EACT,SAAA,GAAyC,IAAA;AAAA,EACzC,OAAA,GAAU,KAAA;AAAA,EAEV,YAAY,SAAA,EAA2D;AACrE,IAAA,IAAA,CAAK,UAAA,GAAa,SAAA;AAAA,EACpB;AAAA;AAAA,EAGA,IAAI,MAAA,GAAkB;AACpB,IAAA,OAAO,IAAA,CAAK,OAAA;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,KAAA,CAAM,OAAA,EAAuC,OAAA,GAAoC,EAAC,EAAY;AAC5F,IAAA,IAAA,CAAK,IAAA,EAAK;AACV,IAAA,IAAI,OAAO,oBAAA,KAAyB,WAAA,EAAa,OAAO,KAAA;AACxD,IAAA,MAAM,OAAO,KAAA,CAAM,OAAA,CAAQ,OAAO,CAAA,GAAK,OAAA,GAAiC,CAAC,OAAkB,CAAA;AAC3F,IAAA,IAAI,IA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AO,SAAS,OAAO,CAAA;AAAA,IACvE;AACA,IAAA,IAAA,CAAK,QAAA,CAAS,UAAU,EAAE,MAAA,EAAQ,EAAE,KAAA,EAAO,IAAA,IAAQ,CAAA;AAAA,EACrD;AACF","file":"sticky_observer_controller.js","sourcesContent":["/**\n * Shared `IntersectionObserver` plumbing for Stimeo's scroll-triggered\n * controllers (`intersection`, `scrollspy`, `sticky-observer`, `lazy-frame`).\n *\n * It centralizes the `IntersectionObserver` support guard, root resolution from\n * a selector, observer creation/teardown, the **active guard** (the browser may\n * flush a final queued callback batch right after `disconnect()`, and a\n * detached controller must not mutate possibly-cached DOM), and the\n * unobserve→observe **re-arm** that re-delivers the current state even when the\n * target never leaves the viewport.\n *\n * Like {@link RovingTabindex} and `FocusTrap`, this is a policy-free internal\n * util: what an intersection *means* (a spied link, a stuck header, a lazy\n * load) stays in each controller. The public `stimeo--intersection` controller\n * is its thin declarative face.\n */\nexport interface IntersectionWatchOptions {\n /**\n * The observation root. Pass an element (or `null` for the viewport) when\n * the caller already resolved it; omit to resolve from `rootSelector`.\n */\n root?: Element | null;\n /** Selector for the observation root; empty/omitted = viewport. */\n rootSelector?: string;\n rootMargin?: string;\n threshold?: number | number[];\n}\n\nexport class IntersectionWatcher {\n readonly #onEntries: (entries: IntersectionObserverEntry[]) => void;\n #observer: IntersectionObserver | null = null;\n #active = false;\n\n constructor(onEntries: (entries: IntersectionObserverEntry[]) => void) {\n this.#onEntries = onEntries;\n }\n\n /** Whether an observer is live (started, `IntersectionObserver` supported). */\n get active(): boolean {\n return this.#active;\n }\n\n /**\n * (Re)creates the observer and observes `targets`. Returns `false` — leaving\n * the watcher inert — without `IntersectionObserver` support (very old\n * browsers; the caller's no-JS fallback stays in charge) or with no targets.\n */\n start(targets: Element | readonly Element[], options: IntersectionWatchOptions = {}): boolean {\n this.stop();\n if (typeof IntersectionObserver === \"undefined\") return false;\n const list = Array.isArray(targets) ? (targets as readonly Element[]) : [targets as Element];\n if (list.length === 0) return false;\n\n const root =\n \"root\" in options\n ? (options.root ?? null)\n : options.rootSelector\n ? document.querySelector(options.rootSelector)\n : null;\n\n this.#active = true;\n this.#observer = new IntersectionObserver(\n (entries) => {\n if (this.#active) this.#onEntries(entries);\n },\n { root, rootMargin: options.rootMargin, threshold: options.threshold },\n );\n for (const target of list) this.#observer.observe(target);\n return true;\n }\n\n /**\n * Re-delivers `target`'s CURRENT intersection state: `IntersectionObserver`\n * only reports *changes*, but `observe()` always reports the present state,\n * so unobserve→observe turns \"still intersecting\" into a fresh callback.\n */\n rearm(target: Element): void {\n if (!this.#observer) return;\n this.#observer.unobserve(target);\n this.#observer.observe(target);\n }\n\n /** Severs the observer; late queued callbacks become no-ops via the guard. */\n stop(): void {\n this.#active = false;\n this.#observer?.disconnect();\n this.#observer = null;\n }\n}\n","import { Controller } from \"@hotwired/stimulus\";\nimport { IntersectionWatcher } from \"../utils/intersection_watcher\";\n\n/**\n * Headless **Sticky State Observer**: detects whether a `position: sticky`\n * element is currently stuck and publishes it as `data-stuck`. No APG widget — a\n * pure state-detection utility. Detection uses an {@link IntersectionObserver}\n * and a sentinel placed just before the sticky element, avoiding per-frame scroll\n * math.\n *\n * Markup contract (identifier: `stimeo--sticky-observer`):\n * <div data-controller=\"stimeo--sticky-observer\">\n * <div data-stimeo--sticky-observer-target=\"sentinel\"\n * aria-hidden=\"true\" style=\"height: 1px;\"></div>\n * <header data-stimeo--sticky-observer-target=\"element\"\n * style=\"position: sticky; top: 0;\">Site heading</header>\n * <main>…</main>\n * </div>\n *\n * When the sentinel scrolls out past the top of the viewport (or `rootSelector`\n * container), the sticky element is considered stuck and `data-stuck=\"true\"` is\n * set; otherwise `false`. The `change` event fires on each transition.\n *\n * @remarks\n * Behavior only — `position: sticky`, shadows, and shrink effects are the\n * consumer's CSS (`[data-stuck=\"true\"] { … }`). `data-stuck` is a visual hook\n * only: it carries no ARIA role/state. `offset` feeds a negative top `rootMargin`\n * and must match the sticky element's CSS `top`. The observer is disconnected on\n * `disconnect()` (Turbo navigation included).\n */\nexport class StickyObserverController extends Controller<HTMLElement> {\n static override targets = [\"sentinel\", \"element\"];\n static override values = {\n rootSelector: { type: String, default: \"\" },\n offset: { type: Number, default: 0 },\n };\n static events = [\"change\"] as const;\n\n declare readonly sentinelTarget: HTMLElement;\n declare readonly elementTarget: HTMLElement;\n declare readonly hasSentinelTarget: boolean;\n declare readonly hasElementTarget: boolean;\n\n declare rootSelectorValue: string;\n declare offsetValue: number;\n\n /** Shared IO plumbing (support guard, root resolution, active guard). */\n readonly #watcher = new IntersectionWatcher((entries) => this.#onIntersect(entries));\n /** Last reported stuck state, so `change` fires only on transitions. */\n #stuck: boolean | null = null;\n\n #onIntersect(entries: IntersectionObserverEntry[]): void {\n const entry = entries[entries.length - 1];\n if (!entry) return;\n // The sentinel sits above the sticky element; once it is no longer\n // intersecting the (top-inset) root, the sticky element has stuck.\n this.#setStuck(!entry.isIntersecting);\n }\n\n override connect(): void {\n if (!this.hasSentinelTarget) return;\n this.#watcher.start(this.sentinelTarget, {\n rootSelector: this.rootSelectorValue,\n rootMargin: `-${this.offsetValue}px 0px 0px 0px`,\n threshold: [0],\n });\n }\n\n override disconnect(): void {\n this.#watcher.stop();\n this.#stuck = null;\n }\n\n /** Reflects the stuck state onto the sticky element and emits `change`. */\n #setStuck(next: boolean): void {\n if (next === this.#stuck) return;\n this.#stuck = next;\n if (this.hasElementTarget) {\n this.elementTarget.setAttribute(\"data-stuck\", next ? \"true\" : \"false\");\n }\n this.dispatch(\"change\", { detail: { stuck: next } });\n }\n}\n"]}
@@ -26,8 +26,7 @@ import { Controller } from '@hotwired/stimulus';
26
26
  * (`0` for the active tab, `-1` for the rest), and the panel `hidden` attribute;
27
27
  * the consumer owns all styling. The optional `list` target marks the tablist
28
28
  * container as part of the semantic contract — the Inspector requires its
29
- * `role="tablist"` and future orientation support has an anchor; the controller
30
- * performs no runtime work on it.
29
+ * `role="tablist"`; the controller performs no runtime work on it.
31
30
  *
32
31
  * Behavior provided:
33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AAI,IAAA,CAAK,MAAA,IAAU,IAAA,CAAK,MAAA;AACpD,QAAA;AAAA,MACF,KAAK,MAAA;AACH,QAAA,SAAA,GAAY,CAAA;AACZ,QAAA;AAAA,MACF,KAAK,KAAA;AACH,QAAA,SAAA,GAAY,KAAK,MAAA,GAAS,CAAA;AAC1B,QAAA;AAAA,MACF;AACE,QAAA;AAAA;AAGJ,IAAA,KAAA,CAAM,cAAA,EAAe;AACrB,IAAA,IAAA,CAAK,YAAA,CAAa,SAAA,EAAW,EAAE,KAAA,EAAO,MAAM,CAAA;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,YAAA,CAAa,KAAA,EAAe,EAAE,KAAA,EAAM,EAA6B;AAC/D,IAAA,IAAA,CAAK,UAAA,CAAW,OAAA,CAAQ,CAAC,GAAA,EAAK,CAAA,KAAM;AAClC,MAAA,MAAM,WAAW,CAAA,KAAM,KAAA;AACvB,MAAA,GAAA,CAAI,YAAA,CAAa,eAAA,EAAiB,QAAA,GAAW,MAAA,GAAS,OAAO,CAAA;AAC7D,MAAA,GAAA,CAAI,QAAA,GAAW,WAAW,CAAA,GAAI,EAAA;AAAA,IAChC,CAAC,CAAA;AACD,IAAA,IAAA,CAAK,YAAA,CAAa,OAAA,CAAQ,CAAC,KAAA,EAAO,CAAA,KAAM;AACtC,MAAA,KAAA,CAAM,SAAS,CAAA,KAAM,KAAA;AAAA,IACvB,CAAC,CAAA;AACD,IAAA,IAAI,KAAA,EAAO,IAAA,CAAK,UAAA,CAAW,KAAK,GAAG,KAAA,EAAM;AAAA,EAC3C;AACF","file":"tabs_controller.js","sourcesContent":["import { Controller } from \"@hotwired/stimulus\";\n\n/**\n * Headless, accessible tabs behavior.\n *\n * Markup contract (identifier: `stimeo--tabs`):\n * <div data-controller=\"stimeo--tabs\">\n * <div role=\"tablist\" aria-label=\"…\" data-stimeo--tabs-target=\"list\">\n * <button role=\"tab\" id=\"tab-1\" aria-controls=\"panel-1\"\n * data-stimeo--tabs-target=\"tab\"\n * data-action=\"stimeo--tabs#select\n * keydown->stimeo--tabs#onKeydown\">Tab 1</button>\n * <!-- more tabs -->\n * </div>\n * <div role=\"tabpanel\" id=\"panel-1\" aria-labelledby=\"tab-1\"\n * data-stimeo--tabs-target=\"panel\">…</div>\n * <!-- more panels -->\n * </div>\n *\n * Implements the WAI-ARIA APG **Tabs** pattern with **automatic activation**:\n * moving focus with the arrow keys immediately selects the focused tab. Tabs are\n * paired to panels by index (the Nth tab controls the Nth panel).\n *\n * @remarks\n * Behavior only. State is exposed through `aria-selected`, roving `tabindex`\n * (`0` for the active tab, `-1` for the rest), and the panel `hidden` attribute;\n * the consumer owns all styling. The optional `list` target marks the tablist\n * container as part of the semantic contract — the Inspector requires its\n * `role=\"tablist\"` and future orientation support has an anchor; the controller\n * performs no runtime work on it.\n *\n * Behavior provided:\n * - Click a tab to select it.\n * - `ArrowRight`/`ArrowLeft` move to and select the next/previous tab (wrapping);\n * `Home`/`End` select the first/last tab.\n */\nexport class TabsController extends Controller<HTMLElement> {\n static override targets = [\"tab\", \"panel\", \"list\"];\n static actions = [\"onKeydown\", \"select\"] as const;\n\n declare readonly tabTargets: HTMLButtonElement[];\n declare readonly panelTargets: HTMLElement[];\n\n /** Selects the initially active tab (the pre-selected one, else the first). */\n override connect(): void {\n const preselected = this.tabTargets.findIndex(\n (tab) => tab.getAttribute(\"aria-selected\") === \"true\",\n );\n this.#selectIndex(preselected === -1 ? 0 : preselected, { focus: false });\n }\n\n /** Selects the clicked tab. Bound via `data-action` (click). */\n select(event: Event): void {\n const index = this.tabTargets.indexOf(event.currentTarget as HTMLButtonElement);\n if (index !== -1) this.#selectIndex(index, { focus: false });\n }\n\n /** Implements arrow/Home/End navigation with automatic activation. */\n onKeydown(event: KeyboardEvent): void {\n const tabs = this.tabTargets;\n const currentIndex = tabs.indexOf(event.currentTarget as HTMLButtonElement);\n if (currentIndex === -1) return;\n\n let nextIndex: number | null = null;\n switch (event.key) {\n case \"ArrowRight\":\n nextIndex = (currentIndex + 1) % tabs.length;\n break;\n case \"ArrowLeft\":\n nextIndex = (currentIndex - 1 + tabs.length) % tabs.length;\n break;\n case \"Home\":\n nextIndex = 0;\n break;\n case \"End\":\n nextIndex = tabs.length - 1;\n break;\n default:\n return;\n }\n\n event.preventDefault();\n this.#selectIndex(nextIndex, { focus: true });\n }\n\n /**\n * Activates the tab/panel pair at `index`: updates `aria-selected`, the roving\n * `tabindex`, and panel visibility. Optionally moves focus to the new tab.\n */\n #selectIndex(index: number, { focus }: { focus: boolean }): void {\n this.tabTargets.forEach((tab, i) => {\n const selected = i === index;\n tab.setAttribute(\"aria-selected\", selected ? \"true\" : \"false\");\n tab.tabIndex = selected ? 0 : -1;\n });\n this.panelTargets.forEach((panel, i) => {\n panel.hidden = i !== index;\n });\n if (focus) this.tabTargets[index]?.focus();\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/controllers/tabs_controller.ts"],"names":[],"mappings":";;;AAmCO,IAAM,cAAA,GAAN,cAA6B,UAAA,CAAwB;AAAA,EAC1D,OAAgB,OAAA,GAAU,CAAC,KAAA,EAAO,SAAS,MAAM,CAAA;AAAA,EACjD,OAAO,OAAA,GAAU,CAAC,WAAA,EAAa,QAAQ,CAAA;AAAA;AAAA,EAM9B,OAAA,GAAgB;AACvB,IAAA,MAAM,WAAA,GAAc,KAAK,UAAA,CAAW,SAAA;AAAA,MAClC,CAAC,GAAA,KAAQ,GAAA,CAAI,YAAA,CAAa,eAAe,CAAA,KAAM;AAAA,KACjD;AACA,IAAA,IAAA,CAAK,YAAA,CAAa,gBAAgB,EAAA,GAAK,CAAA,GAAI,aAAa,EAAE,KAAA,EAAO,OAAO,CAAA;AAAA,EAC1E;AAAA;AAAA,EAGA,OAAO,KAAA,EAAoB;AACzB,IAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,UAAA,CAAW,OAAA,CAAQ,MAAM,aAAkC,CAAA;AAC9E,IAAA,IAAI,KAAA,KAAU,IAAI,IAAA,CAAK,YA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AAC,CAAA;AACD,IAAA,IAAA,CAAK,YAAA,CAAa,OAAA,CAAQ,CAAC,KAAA,EAAO,CAAA,KAAM;AACtC,MAAA,KAAA,CAAM,SAAS,CAAA,KAAM,KAAA;AAAA,IACvB,CAAC,CAAA;AACD,IAAA,IAAI,KAAA,EAAO,IAAA,CAAK,UAAA,CAAW,KAAK,GAAG,KAAA,EAAM;AAAA,EAC3C;AACF","file":"tabs_controller.js","sourcesContent":["import { Controller } from \"@hotwired/stimulus\";\n\n/**\n * Headless, accessible tabs behavior.\n *\n * Markup contract (identifier: `stimeo--tabs`):\n * <div data-controller=\"stimeo--tabs\">\n * <div role=\"tablist\" aria-label=\"…\" data-stimeo--tabs-target=\"list\">\n * <button role=\"tab\" id=\"tab-1\" aria-controls=\"panel-1\"\n * data-stimeo--tabs-target=\"tab\"\n * data-action=\"stimeo--tabs#select\n * keydown->stimeo--tabs#onKeydown\">Tab 1</button>\n * <!-- more tabs -->\n * </div>\n * <div role=\"tabpanel\" id=\"panel-1\" aria-labelledby=\"tab-1\"\n * data-stimeo--tabs-target=\"panel\">…</div>\n * <!-- more panels -->\n * </div>\n *\n * Implements the WAI-ARIA APG **Tabs** pattern with **automatic activation**:\n * moving focus with the arrow keys immediately selects the focused tab. Tabs are\n * paired to panels by index (the Nth tab controls the Nth panel).\n *\n * @remarks\n * Behavior only. State is exposed through `aria-selected`, roving `tabindex`\n * (`0` for the active tab, `-1` for the rest), and the panel `hidden` attribute;\n * the consumer owns all styling. The optional `list` target marks the tablist\n * container as part of the semantic contract — the Inspector requires its\n * `role=\"tablist\"`; the controller performs no runtime work on it.\n *\n * Behavior provided:\n * - Click a tab to select it.\n * - `ArrowRight`/`ArrowLeft` move to and select the next/previous tab (wrapping);\n * `Home`/`End` select the first/last tab.\n */\nexport class TabsController extends Controller<HTMLElement> {\n static override targets = [\"tab\", \"panel\", \"list\"];\n static actions = [\"onKeydown\", \"select\"] as const;\n\n declare readonly tabTargets: HTMLButtonElement[];\n declare readonly panelTargets: HTMLElement[];\n\n /** Selects the initially active tab (the pre-selected one, else the first). */\n override connect(): void {\n const preselected = this.tabTargets.findIndex(\n (tab) => tab.getAttribute(\"aria-selected\") === \"true\",\n );\n this.#selectIndex(preselected === -1 ? 0 : preselected, { focus: false });\n }\n\n /** Selects the clicked tab. Bound via `data-action` (click). */\n select(event: Event): void {\n const index = this.tabTargets.indexOf(event.currentTarget as HTMLButtonElement);\n if (index !== -1) this.#selectIndex(index, { focus: false });\n }\n\n /** Implements arrow/Home/End navigation with automatic activation. */\n onKeydown(event: KeyboardEvent): void {\n const tabs = this.tabTargets;\n const currentIndex = tabs.indexOf(event.currentTarget as HTMLButtonElement);\n if (currentIndex === -1) return;\n\n let nextIndex: number | null = null;\n switch (event.key) {\n case \"ArrowRight\":\n nextIndex = (currentIndex + 1) % tabs.length;\n break;\n case \"ArrowLeft\":\n nextIndex = (currentIndex - 1 + tabs.length) % tabs.length;\n break;\n case \"Home\":\n nextIndex = 0;\n break;\n case \"End\":\n nextIndex = tabs.length - 1;\n break;\n default:\n return;\n }\n\n event.preventDefault();\n this.#selectIndex(nextIndex, { focus: true });\n }\n\n /**\n * Activates the tab/panel pair at `index`: updates `aria-selected`, the roving\n * `tabindex`, and panel visibility. Optionally moves focus to the new tab.\n */\n #selectIndex(index: number, { focus }: { focus: boolean }): void {\n this.tabTargets.forEach((tab, i) => {\n const selected = i === index;\n tab.setAttribute(\"aria-selected\", selected ? \"true\" : \"false\");\n tab.tabIndex = selected ? 0 : -1;\n });\n this.panelTargets.forEach((panel, i) => {\n panel.hidden = i !== index;\n });\n if (focus) this.tabTargets[index]?.focus();\n }\n}\n"]}
@@ -16,15 +16,9 @@ import { Controller } from '@hotwired/stimulus';
16
16
  * <div role="region" aria-label="Notifications">
17
17
  * <ol data-stimeo--toast-target="list"></ol>
18
18
  * <template data-stimeo--toast-target="template">
19
- * <li role="status" data-stimeo--toast-target="item"
20
- * data-action="mouseenter->stimeo--toast#pause
21
- * mouseleave->stimeo--toast#resume
22
- * focusin->stimeo--toast#pause
23
- * focusout->stimeo--toast#resume
24
- * keydown->stimeo--toast#onKeydown"
25
- * tabindex="0">
26
- * <span data-toast-slot="body"></span>
27
- * <button type="button" data-action="stimeo--toast#dismiss">Dismiss</button>
19
+ * <li data-stimeo--toast-target="item" tabindex="0">
20
+ * <span role="status" data-toast-slot="body"></span>
21
+ * <button type="button" data-toast-dismiss>Dismiss</button>
28
22
  * </li>
29
23
  * </template>
30
24
  * </div>
@@ -61,6 +55,10 @@ declare class ToastController extends Controller<HTMLElement> {
61
55
  maxValue: number;
62
56
  connect(): void;
63
57
  disconnect(): void;
58
+ /** Rebinds delegated interaction when Turbo replaces the list target in place. */
59
+ listTargetConnected(element: HTMLElement): void;
60
+ /** Releases delegation only when the removed target is its current owner. */
61
+ listTargetDisconnected(element: HTMLElement): void;
64
62
  durationValueChanged(): void;
65
63
  maxValueChanged(): void;
66
64
  /**