@tangible/ui 0.2.52 → 0.2.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/styles/index.scss CHANGED
@@ -124,6 +124,20 @@ $layers: true !default;
124
124
  color: var(--#{sys.$prefix}color-fg);
125
125
  }
126
126
 
127
+ // `hidden` means hidden. Component display rules (`.tui-interface
128
+ // .tui-button { display: inline-flex }`, Tabs, …) out-rank the UA's
129
+ // `[hidden] { display: none }`, so without this a consumer's `hidden` on a
130
+ // TUI element did nothing (#254). `!important` because the attribute's
131
+ // meaning is absolute: in the layered build an important declaration in
132
+ // `resets` beats every later layer, and in the unlayered build it beats
133
+ // both the components and a host's own display rules.
134
+ // `until-found` is left to the UA: it renders as content-visibility, and
135
+ // display: none would stop find-in-page revealing it.
136
+ &[hidden]:not([hidden="until-found" i]),
137
+ [hidden]:not([hidden="until-found" i]) {
138
+ display: none !important;
139
+ }
140
+
127
141
  // Universal border-box — all TUI elements use border-box sizing.
128
142
  &,
129
143
  *,
package/tui-manifest.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
- "version": "0.2.52",
3
- "generated": "2026-11-26T18:11:30.888Z",
2
+ "version": "0.2.53",
3
+ "generated": "2026-11-26T19:55:17.116Z",
4
4
  "components": {
5
5
  "Accordion": {
6
6
  "props": {
@@ -2034,7 +2034,8 @@
2034
2034
  "--tui-move-handle-fg",
2035
2035
  "--tui-move-handle-bg",
2036
2036
  "--tui-move-handle-fg-interact",
2037
- "--tui-move-handle-bg-interact"
2037
+ "--tui-move-handle-bg-interact",
2038
+ "--tui-move-handle-fg-disabled"
2038
2039
  ],
2039
2040
  "story": {
2040
2041
  "title": "Components/MoveHandle",
@@ -0,0 +1,49 @@
1
+ /**
2
+ * How page numbers are shown.
3
+ * - `simple`: prev/next only, no numbers
4
+ * - `ends`: first, last, current and its neighbours, no ellipses
5
+ * - `full`: every page
6
+ * - `smart`: a stable-width window with ellipses (default)
7
+ */
8
+ export type PagerMode = 'simple' | 'ends' | 'full' | 'smart';
9
+ /** Slots `smart` mode fills, numbers and ellipses together. */
10
+ export declare const DEFAULT_PAGER_SLOTS = 7;
11
+ /**
12
+ * `first`/`last` share the nav shape rather than the page shape: they are
13
+ * jump affordances like prev/next, not members of the numbered group, so they
14
+ * take the same variant treatment (outline in flush, ghost in detached).
15
+ */
16
+ export type PagerNavKind = 'first' | 'prev' | 'next' | 'last';
17
+ /**
18
+ * One button (or the ellipsis) in a pager, in reading order.
19
+ * Nav items carry the page they go to; a disabled one points at the page it
20
+ * would go to if it could (clamped to 1…total).
21
+ */
22
+ export type PagerItem = {
23
+ kind: PagerNavKind;
24
+ disabled: boolean;
25
+ page: number;
26
+ } | {
27
+ kind: 'page';
28
+ page: number;
29
+ current: boolean;
30
+ } | {
31
+ kind: 'ellipsis';
32
+ };
33
+ export type PagerItemsOptions = {
34
+ /** 1-based. Clamped to 1…totalPages. */
35
+ currentPage: number;
36
+ /** Values below 1 are treated as 1. */
37
+ totalPages: number;
38
+ /** @default 'smart' */
39
+ mode?: PagerMode;
40
+ /** Slots `smart` mode fills, numbers and ellipses together. @default 7 */
41
+ maxNumbers?: number;
42
+ /** Add first/last buttons outside prev/next. @default false */
43
+ showFirstLast?: boolean;
44
+ };
45
+ /**
46
+ * The pager's items in reading order: « ‹ 1 … 4 5 6 … 20 › ».
47
+ * Inputs are normalised the way <Pager> normalises its props.
48
+ */
49
+ export declare function getPagerItems({ currentPage, totalPages, mode, maxNumbers, showFirstLast, }: PagerItemsOptions): PagerItem[];
package/utils/pager.js ADDED
@@ -0,0 +1,129 @@
1
+ // =============================================================================
2
+ // Pager items: which buttons a pager shows, framework-free
3
+ // =============================================================================
4
+ //
5
+ // The page-numbering logic behind <Pager>, exported on its own
6
+ // (`@tangible/ui/utils/pager`) so a renderer without React draws exactly the
7
+ // same sequence: a PHP-printed or vanilla-JS pager on a WordPress front end
8
+ // (SearchSync, #256). No React, no DOM.
9
+ //
10
+ // =============================================================================
11
+ /** Slots `smart` mode fills, numbers and ellipses together. */
12
+ export const DEFAULT_PAGER_SLOTS = 7;
13
+ /**
14
+ * Build a stable-width list of page tokens (numbers + ellipses).
15
+ *
16
+ * Always shows: first, last, current, current±1
17
+ * Single-page gaps are filled in (no "1 ... 3" silliness)
18
+ * Expands symmetrically from current, biased toward center
19
+ */
20
+ function buildNumberTokens(total, current, maxSlots = DEFAULT_PAGER_SLOTS) {
21
+ if (total <= 1)
22
+ return [1];
23
+ if (total <= maxSlots)
24
+ return Array.from({ length: total }, (_, i) => i + 1);
25
+ const inRange = (n) => n >= 1 && n <= total;
26
+ // Start with anchors: first, last, current and neighbors
27
+ const chosen = new Set([1, total]);
28
+ if (inRange(current))
29
+ chosen.add(current);
30
+ if (inRange(current - 1))
31
+ chosen.add(current - 1);
32
+ if (inRange(current + 1))
33
+ chosen.add(current + 1);
34
+ /**
35
+ * Convert chosen pages to tokens, inserting ellipses for gaps.
36
+ * Single-page gaps get filled in rather than showing an ellipsis.
37
+ */
38
+ const materialize = () => {
39
+ const pages = [...chosen].sort((a, b) => a - b);
40
+ const tokens = [];
41
+ for (let i = 0; i < pages.length; i++) {
42
+ tokens.push(pages[i]);
43
+ const next = pages[i + 1];
44
+ if (next == null)
45
+ break;
46
+ const gap = next - pages[i];
47
+ if (gap === 2)
48
+ tokens.push(pages[i] + 1);
49
+ else if (gap > 2)
50
+ tokens.push('...');
51
+ }
52
+ return tokens;
53
+ };
54
+ /** Try adding a page. Returns true if it fit within maxSlots. */
55
+ const tryAdd = (p) => {
56
+ if (!inRange(p) || chosen.has(p))
57
+ return false;
58
+ chosen.add(p);
59
+ if (materialize().length > maxSlots) {
60
+ chosen.delete(p);
61
+ return false;
62
+ }
63
+ return true;
64
+ };
65
+ // Expand symmetrically from current until we fill available slots
66
+ let offset = 2;
67
+ while (materialize().length < maxSlots) {
68
+ const left = current - offset;
69
+ const right = current + offset;
70
+ // Bias toward center: if past halfway, try right first
71
+ const preferRight = current > total / 2;
72
+ const [first, second] = preferRight ? [right, left] : [left, right];
73
+ // Try preferred side, then other side
74
+ const added = tryAdd(first) || tryAdd(second);
75
+ // If neither side worked, try both explicitly (handles edge cases)
76
+ if (!added && !tryAdd(left) && !tryAdd(right))
77
+ break;
78
+ offset++;
79
+ }
80
+ return materialize();
81
+ }
82
+ /**
83
+ * The pager's items in reading order: « ‹ 1 … 4 5 6 … 20 › ».
84
+ * Inputs are normalised the way <Pager> normalises its props.
85
+ */
86
+ export function getPagerItems({ currentPage, totalPages, mode = 'smart', maxNumbers = DEFAULT_PAGER_SLOTS, showFirstLast = false, }) {
87
+ const total = Math.max(1, totalPages);
88
+ const current = Math.min(total, Math.max(1, currentPage));
89
+ const items = [];
90
+ // Outside prev/next, not inside: the reading order is
91
+ // « ‹ 1 2 3 › » in every pager that has them.
92
+ if (showFirstLast) {
93
+ items.push({ kind: 'first', disabled: current <= 1, page: 1 });
94
+ }
95
+ items.push({
96
+ kind: 'prev',
97
+ disabled: current <= 1,
98
+ page: Math.max(1, current - 1),
99
+ });
100
+ if (mode === 'full') {
101
+ for (let p = 1; p <= total; p++) {
102
+ items.push({ kind: 'page', page: p, current: p === current });
103
+ }
104
+ }
105
+ else if (mode === 'ends') {
106
+ const set = new Set([1, current - 1, current, current + 1, total].filter((n) => n >= 1 && n <= total));
107
+ const pages = Array.from(set).sort((a, b) => a - b);
108
+ pages.forEach((p) => items.push({ kind: 'page', page: p, current: p === current }));
109
+ }
110
+ else if (mode === 'smart') {
111
+ const tokens = buildNumberTokens(total, current, maxNumbers);
112
+ tokens.forEach((tok) => {
113
+ if (tok === '...')
114
+ items.push({ kind: 'ellipsis' });
115
+ else
116
+ items.push({ kind: 'page', page: tok, current: tok === current });
117
+ });
118
+ }
119
+ // mode === 'simple' => no page numbers
120
+ items.push({
121
+ kind: 'next',
122
+ disabled: current >= total,
123
+ page: Math.min(total, current + 1),
124
+ });
125
+ if (showFirstLast) {
126
+ items.push({ kind: 'last', disabled: current >= total, page: total });
127
+ }
128
+ return items;
129
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Marks a component whose `label` prop names the control itself (Checkbox,
3
+ * Switch). Field.Control reads it to warn when a Field.Label would replace
4
+ * that name (#259). A `Symbol.for` key so two copies of TUI on one page agree.
5
+ *
6
+ * @internal
7
+ */
8
+ export declare const SELF_LABELLING: unique symbol;
9
+ /** @internal */
10
+ export declare function markSelfLabelling(component: object): void;
11
+ /** @internal */
12
+ export declare function isSelfLabelling(type: unknown): boolean;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Marks a component whose `label` prop names the control itself (Checkbox,
3
+ * Switch). Field.Control reads it to warn when a Field.Label would replace
4
+ * that name (#259). A `Symbol.for` key so two copies of TUI on one page agree.
5
+ *
6
+ * @internal
7
+ */
8
+ export const SELF_LABELLING = Symbol.for('tangible-ui/self-labelling');
9
+ /** @internal */
10
+ export function markSelfLabelling(component) {
11
+ component[SELF_LABELLING] = true;
12
+ }
13
+ /** @internal */
14
+ export function isSelfLabelling(type) {
15
+ return ((typeof type === 'object' || typeof type === 'function') &&
16
+ type !== null &&
17
+ type[SELF_LABELLING] === true);
18
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Vanilla accordion: TUI's Accordion for markup with no React behind it
3
+ * (Tangible Blocks, L&L templates, plain PHP). Behaviour hangs off
4
+ * `data-tui-accordion-*` attributes, not classes, so the reference markup can
5
+ * wear the React Accordion's classes and tokens while a consumer with its own
6
+ * look (SearchSync's filter panels) adds only the attributes.
7
+ *
8
+ * What it owns, so server markup can't get it wrong:
9
+ *
10
+ * - `aria-expanded` on the trigger and `data-state` (`open` | `closed`) on the
11
+ * item, trigger and panel, kept in step
12
+ * - a closed panel is `inert` and `aria-hidden`, so Tab and screen readers
13
+ * skip what can't be seen (a grid-row collapse alone hides nothing, #255)
14
+ * - `id` and `aria-controls` filled in when the markup leaves them out
15
+ * - single mode closes the other items; `data-tui-accordion-collapsible` lets
16
+ * the open one close too (multiple mode always can), as in React
17
+ * - closing a panel that holds focus moves focus to its trigger
18
+ * - in single, non-collapsible mode the open header is `aria-disabled` (APG),
19
+ * still focusable and not painted disabled; an author's own `aria-disabled`
20
+ * is left alone
21
+ *
22
+ * Markup:
23
+ *
24
+ * <div class="tui-accordion" data-tui-accordion="single" data-tui-accordion-collapsible>
25
+ * <div class="tui-accordion__item" data-tui-accordion-item data-state="open">
26
+ * <h3 class="tui-accordion__heading">
27
+ * <button type="button" class="tui-accordion__trigger" data-tui-accordion-trigger>
28
+ * <span class="tui-accordion__trigger-content">Brand</span>
29
+ * <span class="tui-accordion__indicator" aria-hidden="true">…chevron…</span>
30
+ * </button>
31
+ * </h3>
32
+ * <div class="tui-accordion__panel" data-tui-accordion-panel>
33
+ * <div class="tui-accordion__panel-content">…</div>
34
+ * </div>
35
+ * </div>
36
+ * </div>
37
+ *
38
+ * `data-tui-accordion` is `single` (default) or `multiple`. An item starts open
39
+ * with `data-state="open"` on the item or `aria-expanded="true"` on its
40
+ * trigger. The trigger must be a <button>: Enter and Space come from the
41
+ * platform, and nothing here adds key handling. Put it in a heading at the
42
+ * level the page needs. A disabled trigger (`disabled` or
43
+ * `aria-disabled="true"`) doesn't toggle.
44
+ *
45
+ * The React Accordion puts `data-tui-accordion-trigger` on its triggers too, as
46
+ * a styling hook. Without `data-tui-accordion` and `data-tui-accordion-item`
47
+ * around them, this script ignores them, so the two can share a page.
48
+ *
49
+ * Each toggle fires `tui-accordion-toggle` on the item (bubbles), with
50
+ * `{ open, trigger, panel }`. State lives in the DOM, so two copies of the
51
+ * script on one page agree.
52
+ */
53
+ /** Fired on the item after it opens or closes. Bubbles. */
54
+ export declare const ACCORDION_TOGGLE_EVENT = "tui-accordion-toggle";
55
+ export type AccordionToggleEventDetail = {
56
+ open: boolean;
57
+ trigger: HTMLElement;
58
+ panel: HTMLElement;
59
+ };
60
+ /** An item, its trigger or its panel, or the id of any of them. */
61
+ export type AccordionTarget = string | Element;
62
+ /**
63
+ * Brings markup in line with its state: ids, `aria-controls`, `inert` on
64
+ * closed panels, and one open item in single mode. The standalone script runs
65
+ * it on the whole page at load; call it for markup added later. Toggling an
66
+ * item syncs it anyway, so this is about first paint.
67
+ */
68
+ export declare function sync(scope?: ParentNode): void;
69
+ /**
70
+ * Opens an item (closing its siblings in single mode). Returns false only
71
+ * when the target isn't an accordion item. Closing a sibling that holds focus
72
+ * moves focus to that sibling's trigger.
73
+ */
74
+ export declare function open(target: AccordionTarget): boolean;
75
+ /**
76
+ * Closes an item. Programmatic closes ignore `collapsible`, as React's
77
+ * controlled value does. Returns false only when the target isn't an item.
78
+ */
79
+ export declare function close(target: AccordionTarget): boolean;
80
+ /**
81
+ * Toggles an item the way a click on its trigger would (so a disabled or
82
+ * non-collapsible open item stays put). Returns the item's open state
83
+ * afterwards, or null when the target isn't an item.
84
+ */
85
+ export declare function toggle(target: AccordionTarget): boolean | null;
86
+ /**
87
+ * Wires every `data-tui-accordion` on the page through one delegated click
88
+ * listener, so markup added later works without another call (run `sync()` on
89
+ * it to fix its first paint). Calls are counted: the listener comes off when
90
+ * every caller has run its teardown.
91
+ *
92
+ * The standalone script (`vanilla/accordion.min.js`) calls this itself.
93
+ */
94
+ export declare function init(): () => void;
@@ -0,0 +1,317 @@
1
+ /**
2
+ * Vanilla accordion: TUI's Accordion for markup with no React behind it
3
+ * (Tangible Blocks, L&L templates, plain PHP). Behaviour hangs off
4
+ * `data-tui-accordion-*` attributes, not classes, so the reference markup can
5
+ * wear the React Accordion's classes and tokens while a consumer with its own
6
+ * look (SearchSync's filter panels) adds only the attributes.
7
+ *
8
+ * What it owns, so server markup can't get it wrong:
9
+ *
10
+ * - `aria-expanded` on the trigger and `data-state` (`open` | `closed`) on the
11
+ * item, trigger and panel, kept in step
12
+ * - a closed panel is `inert` and `aria-hidden`, so Tab and screen readers
13
+ * skip what can't be seen (a grid-row collapse alone hides nothing, #255)
14
+ * - `id` and `aria-controls` filled in when the markup leaves them out
15
+ * - single mode closes the other items; `data-tui-accordion-collapsible` lets
16
+ * the open one close too (multiple mode always can), as in React
17
+ * - closing a panel that holds focus moves focus to its trigger
18
+ * - in single, non-collapsible mode the open header is `aria-disabled` (APG),
19
+ * still focusable and not painted disabled; an author's own `aria-disabled`
20
+ * is left alone
21
+ *
22
+ * Markup:
23
+ *
24
+ * <div class="tui-accordion" data-tui-accordion="single" data-tui-accordion-collapsible>
25
+ * <div class="tui-accordion__item" data-tui-accordion-item data-state="open">
26
+ * <h3 class="tui-accordion__heading">
27
+ * <button type="button" class="tui-accordion__trigger" data-tui-accordion-trigger>
28
+ * <span class="tui-accordion__trigger-content">Brand</span>
29
+ * <span class="tui-accordion__indicator" aria-hidden="true">…chevron…</span>
30
+ * </button>
31
+ * </h3>
32
+ * <div class="tui-accordion__panel" data-tui-accordion-panel>
33
+ * <div class="tui-accordion__panel-content">…</div>
34
+ * </div>
35
+ * </div>
36
+ * </div>
37
+ *
38
+ * `data-tui-accordion` is `single` (default) or `multiple`. An item starts open
39
+ * with `data-state="open"` on the item or `aria-expanded="true"` on its
40
+ * trigger. The trigger must be a <button>: Enter and Space come from the
41
+ * platform, and nothing here adds key handling. Put it in a heading at the
42
+ * level the page needs. A disabled trigger (`disabled` or
43
+ * `aria-disabled="true"`) doesn't toggle.
44
+ *
45
+ * The React Accordion puts `data-tui-accordion-trigger` on its triggers too, as
46
+ * a styling hook. Without `data-tui-accordion` and `data-tui-accordion-item`
47
+ * around them, this script ignores them, so the two can share a page.
48
+ *
49
+ * Each toggle fires `tui-accordion-toggle` on the item (bubbles), with
50
+ * `{ open, trigger, panel }`. State lives in the DOM, so two copies of the
51
+ * script on one page agree.
52
+ */
53
+ const ROOT_ATTR = 'data-tui-accordion';
54
+ const COLLAPSIBLE_ATTR = 'data-tui-accordion-collapsible';
55
+ const ITEM_ATTR = 'data-tui-accordion-item';
56
+ const TRIGGER_ATTR = 'data-tui-accordion-trigger';
57
+ const PANEL_ATTR = 'data-tui-accordion-panel';
58
+ // Marks an aria-disabled this script set on a locked open header, so it can
59
+ // tell its own from an author's and take it off again.
60
+ const LOCKED_ATTR = 'data-tui-accordion-locked';
61
+ /** Fired on the item after it opens or closes. Bubbles. */
62
+ export const ACCORDION_TOGGLE_EVENT = 'tui-accordion-toggle';
63
+ const warned = new WeakSet();
64
+ let bindings = 0;
65
+ let uid = 0;
66
+ function warn(el, message) {
67
+ // Always on, as in the vanilla Modal: template authors have no dev build.
68
+ if (warned.has(el))
69
+ return;
70
+ warned.add(el);
71
+ console.warn(`[TUI accordion] ${message}`, el);
72
+ }
73
+ function ensureId(el, prefix) {
74
+ // Two copies of the module (an ESM import and the standalone script) each
75
+ // count from 0, so check the page rather than trusting the counter.
76
+ while (!el.id) {
77
+ const id = `tui-accordion-${prefix}-${++uid}`;
78
+ if (!document.getElementById(id))
79
+ el.id = id;
80
+ }
81
+ return el.id;
82
+ }
83
+ function directOf(item, attr) {
84
+ // The item's own part, not one from an accordion nested in its panel.
85
+ for (const el of item.querySelectorAll(`[${attr}]`)) {
86
+ if (el.closest(`[${ITEM_ATTR}]`) === item)
87
+ return el;
88
+ }
89
+ return null;
90
+ }
91
+ function partsOf(el) {
92
+ const item = el.closest(`[${ITEM_ATTR}]`);
93
+ if (!item) {
94
+ warn(el, `No [${ITEM_ATTR}] around this element. Each trigger and panel pair needs an item.`);
95
+ return null;
96
+ }
97
+ const trigger = directOf(item, TRIGGER_ATTR);
98
+ const panel = directOf(item, PANEL_ATTR);
99
+ if (!trigger || !panel) {
100
+ warn(item, `This item needs one [${TRIGGER_ATTR}] and one [${PANEL_ATTR}].`);
101
+ return null;
102
+ }
103
+ return { root: item.closest(`[${ROOT_ATTR}]`), item, trigger, panel };
104
+ }
105
+ /** Disabled by the author: a locked open header isn't. */
106
+ function isDisabled(trigger) {
107
+ return (trigger.matches(':disabled') ||
108
+ (trigger.getAttribute('aria-disabled') === 'true' && !trigger.hasAttribute(LOCKED_ATTR)));
109
+ }
110
+ function isOpen(parts) {
111
+ return parts.item.getAttribute('data-state') === 'open';
112
+ }
113
+ function isMultiple(root) {
114
+ return root?.getAttribute(ROOT_ATTR) === 'multiple';
115
+ }
116
+ /** Writes one item's state to every attribute that carries it. */
117
+ function apply({ root, item, trigger, panel }, open) {
118
+ const state = open ? 'open' : 'closed';
119
+ // APG: an open header whose panel can't collapse (single, not collapsible)
120
+ // is aria-disabled. Still focusable and unpainted; activating it does nothing.
121
+ const locked = open && !!root && !isMultiple(root) && !root.hasAttribute(COLLAPSIBLE_ATTR);
122
+ if (locked && !isDisabled(trigger)) {
123
+ trigger.setAttribute('aria-disabled', 'true');
124
+ trigger.setAttribute(LOCKED_ATTR, '');
125
+ }
126
+ else if (!locked && trigger.hasAttribute(LOCKED_ATTR)) {
127
+ trigger.removeAttribute('aria-disabled');
128
+ trigger.removeAttribute(LOCKED_ATTR);
129
+ }
130
+ // Focus inside a panel that's about to go inert would be stranded.
131
+ if (!open && panel.contains(document.activeElement))
132
+ trigger.focus();
133
+ item.setAttribute('data-state', state);
134
+ trigger.setAttribute('data-state', state);
135
+ // The Accordion styles paint disabled off :disabled or [data-disabled];
136
+ // mirror aria-disabled so an inert trigger doesn't look live.
137
+ trigger.toggleAttribute('data-disabled', isDisabled(trigger));
138
+ trigger.setAttribute('aria-expanded', String(open));
139
+ panel.setAttribute('data-state', state);
140
+ panel.inert = !open;
141
+ if (open)
142
+ panel.removeAttribute('aria-hidden');
143
+ else
144
+ panel.setAttribute('aria-hidden', 'true');
145
+ }
146
+ function wire(parts) {
147
+ const { trigger, panel } = parts;
148
+ if (!(trigger instanceof HTMLButtonElement)) {
149
+ warn(trigger, `[${TRIGGER_ATTR}] should be a <button>: anything else gets no keyboard activation.`);
150
+ }
151
+ else if (!trigger.hasAttribute('type')) {
152
+ // Inside a form, a type-less button submits it.
153
+ trigger.type = 'button';
154
+ }
155
+ trigger.setAttribute('aria-controls', ensureId(panel, 'panel'));
156
+ ensureId(trigger, 'trigger');
157
+ }
158
+ function itemsOf(root) {
159
+ return [...root.querySelectorAll(`[${ITEM_ATTR}]`)].filter((item) => item.closest(`[${ROOT_ATTR}]`) === root);
160
+ }
161
+ /**
162
+ * Brings markup in line with its state: ids, `aria-controls`, `inert` on
163
+ * closed panels, and one open item in single mode. The standalone script runs
164
+ * it on the whole page at load; call it for markup added later. Toggling an
165
+ * item syncs it anyway, so this is about first paint.
166
+ */
167
+ export function sync(scope = document) {
168
+ // A scope inside an accordion (a newly appended item) re-syncs its root,
169
+ // which is idempotent; roots below the scope sync too.
170
+ const outer = scope instanceof Element ? scope.closest(`[${ROOT_ATTR}]`) : null;
171
+ const roots = new Set([...(outer ? [outer] : []), ...scope.querySelectorAll(`[${ROOT_ATTR}]`)]);
172
+ for (const root of roots) {
173
+ let seenOpen = false;
174
+ for (const item of itemsOf(root)) {
175
+ const parts = partsOf(item);
176
+ if (!parts)
177
+ continue;
178
+ wire(parts);
179
+ let open = isOpen(parts) || parts.trigger.getAttribute('aria-expanded') === 'true';
180
+ if (open && !isMultiple(root)) {
181
+ if (seenOpen) {
182
+ warn(root, 'More than one item starts open in a single accordion; keeping the first.');
183
+ open = false;
184
+ }
185
+ seenOpen = true;
186
+ }
187
+ apply(parts, open);
188
+ }
189
+ }
190
+ }
191
+ function set(parts, open) {
192
+ if (isOpen(parts) === open)
193
+ return;
194
+ if (open && !isMultiple(parts.root) && parts.root) {
195
+ for (const item of itemsOf(parts.root)) {
196
+ if (item === parts.item)
197
+ continue;
198
+ const other = partsOf(item);
199
+ if (other && isOpen(other))
200
+ set(other, false);
201
+ }
202
+ }
203
+ wire(parts);
204
+ apply(parts, open);
205
+ const detail = { open, trigger: parts.trigger, panel: parts.panel };
206
+ parts.item.dispatchEvent(new CustomEvent(ACCORDION_TOGGLE_EVENT, { bubbles: true, detail }));
207
+ }
208
+ function resolve(target) {
209
+ const el = typeof target === 'string' ? document.getElementById(target) : target;
210
+ if (!el) {
211
+ console.warn(`[TUI accordion] No element with id "${String(target)}".`);
212
+ return null;
213
+ }
214
+ // A root isn't an item: resolving it would walk up to an outer accordion's item.
215
+ if (!el.matches(`[${ITEM_ATTR}], [${TRIGGER_ATTR}], [${PANEL_ATTR}]`)) {
216
+ console.warn('[TUI accordion] Pass an item, trigger or panel (or its id), not', el);
217
+ return null;
218
+ }
219
+ return partsOf(el);
220
+ }
221
+ /**
222
+ * Opens an item (closing its siblings in single mode). Returns false only
223
+ * when the target isn't an accordion item. Closing a sibling that holds focus
224
+ * moves focus to that sibling's trigger.
225
+ */
226
+ export function open(target) {
227
+ const parts = resolve(target);
228
+ if (!parts)
229
+ return false;
230
+ set(parts, true);
231
+ return true;
232
+ }
233
+ /**
234
+ * Closes an item. Programmatic closes ignore `collapsible`, as React's
235
+ * controlled value does. Returns false only when the target isn't an item.
236
+ */
237
+ export function close(target) {
238
+ const parts = resolve(target);
239
+ if (!parts)
240
+ return false;
241
+ set(parts, false);
242
+ return true;
243
+ }
244
+ /**
245
+ * Toggles an item the way a click on its trigger would (so a disabled or
246
+ * non-collapsible open item stays put). Returns the item's open state
247
+ * afterwards, or null when the target isn't an item.
248
+ */
249
+ export function toggle(target) {
250
+ const parts = resolve(target);
251
+ if (!parts)
252
+ return null;
253
+ activate(parts);
254
+ return isOpen(parts);
255
+ }
256
+ function activate(parts) {
257
+ if (isDisabled(parts.trigger))
258
+ return;
259
+ if (!isOpen(parts)) {
260
+ set(parts, true);
261
+ return;
262
+ }
263
+ // In single mode the open item stays open unless the accordion is collapsible.
264
+ const collapsible = isMultiple(parts.root) || parts.root?.hasAttribute(COLLAPSIBLE_ATTR);
265
+ if (collapsible || !parts.root)
266
+ set(parts, false);
267
+ }
268
+ // Marks a click as handled across copies of the module. The Symbol.for guard
269
+ // stops a second standalone script installing, but an ESM import plus the
270
+ // script still means two listeners, and a toggle isn't idempotent: the second
271
+ // would undo the first.
272
+ const HANDLED = Symbol.for('tangible-ui/vanilla/accordion/handled');
273
+ function onClick(event) {
274
+ if (event.defaultPrevented || !(event.target instanceof Element))
275
+ return;
276
+ const marked = event;
277
+ if (marked[HANDLED])
278
+ return;
279
+ const trigger = event.target.closest(`[${TRIGGER_ATTR}]`);
280
+ // The React Accordion stamps the same trigger attribute as a styling hook
281
+ // but has no item or root attributes: leave its triggers alone, silently.
282
+ if (!trigger || !trigger.closest(`[${ITEM_ATTR}]`) || !trigger.closest(`[${ROOT_ATTR}]`))
283
+ return;
284
+ const parts = partsOf(trigger);
285
+ if (!parts || parts.trigger !== trigger)
286
+ return;
287
+ marked[HANDLED] = true;
288
+ activate(parts);
289
+ }
290
+ /**
291
+ * Wires every `data-tui-accordion` on the page through one delegated click
292
+ * listener, so markup added later works without another call (run `sync()` on
293
+ * it to fix its first paint). Calls are counted: the listener comes off when
294
+ * every caller has run its teardown.
295
+ *
296
+ * The standalone script (`vanilla/accordion.min.js`) calls this itself.
297
+ */
298
+ export function init() {
299
+ if (bindings++ === 0) {
300
+ document.addEventListener('click', onClick);
301
+ if (document.readyState === 'loading') {
302
+ document.addEventListener('DOMContentLoaded', () => sync(), { once: true });
303
+ }
304
+ else {
305
+ sync();
306
+ }
307
+ }
308
+ let released = false;
309
+ return () => {
310
+ if (released)
311
+ return;
312
+ released = true;
313
+ if (--bindings > 0)
314
+ return;
315
+ document.removeEventListener('click', onClick);
316
+ };
317
+ }
@@ -0,0 +1 @@
1
+ (()=>{var _=Object.defineProperty;var C=(t,e)=>{for(var n in e)_(t,n,{get:e[n],enumerable:!0})};var $={};C($,{ACCORDION_TOGGLE_EVENT:()=>S,close:()=>G,init:()=>h,open:()=>B,sync:()=>M,toggle:()=>q});var l="data-tui-accordion",x="data-tui-accordion-collapsible",a="data-tui-accordion-item",u="data-tui-accordion-trigger",A="data-tui-accordion-panel",m="data-tui-accordion-locked",S="tui-accordion-toggle",y=new WeakSet,v=0,U=0;function T(t,e){y.has(t)||(y.add(t),console.warn(`[TUI accordion] ${e}`,t))}function I(t,e){for(;!t.id;){let n=`tui-accordion-${e}-${++U}`;document.getElementById(n)||(t.id=n)}return t.id}function O(t,e){for(let n of t.querySelectorAll(`[${e}]`))if(n.closest(`[${a}]`)===t)return n;return null}function b(t){let e=t.closest(`[${a}]`);if(!e)return T(t,`No [${a}] around this element. Each trigger and panel pair needs an item.`),null;let n=O(e,u),o=O(e,A);return!n||!o?(T(e,`This item needs one [${u}] and one [${A}].`),null):{root:e.closest(`[${l}]`),item:e,trigger:n,panel:o}}function L(t){return t.matches(":disabled")||t.getAttribute("aria-disabled")==="true"&&!t.hasAttribute(m)}function d(t){return t.item.getAttribute("data-state")==="open"}function E(t){return t?.getAttribute(l)==="multiple"}function k({root:t,item:e,trigger:n,panel:o},i){let s=i?"open":"closed",r=i&&!!t&&!E(t)&&!t.hasAttribute(x);r&&!L(n)?(n.setAttribute("aria-disabled","true"),n.setAttribute(m,"")):!r&&n.hasAttribute(m)&&(n.removeAttribute("aria-disabled"),n.removeAttribute(m)),!i&&o.contains(document.activeElement)&&n.focus(),e.setAttribute("data-state",s),n.setAttribute("data-state",s),n.toggleAttribute("data-disabled",L(n)),n.setAttribute("aria-expanded",String(i)),o.setAttribute("data-state",s),o.inert=!i,i?o.removeAttribute("aria-hidden"):o.setAttribute("aria-hidden","true")}function D(t){let{trigger:e,panel:n}=t;e instanceof HTMLButtonElement?e.hasAttribute("type")||(e.type="button"):T(e,`[${u}] should be a <button>: anything else gets no keyboard activation.`),e.setAttribute("aria-controls",I(n,"panel")),I(e,"trigger")}function R(t){return[...t.querySelectorAll(`[${a}]`)].filter(e=>e.closest(`[${l}]`)===t)}function M(t=document){let e=t instanceof Element?t.closest(`[${l}]`):null,n=new Set([...e?[e]:[],...t.querySelectorAll(`[${l}]`)]);for(let o of n){let i=!1;for(let s of R(o)){let r=b(s);if(!r)continue;D(r);let g=d(r)||r.trigger.getAttribute("aria-expanded")==="true";g&&!E(o)&&(i&&(T(o,"More than one item starts open in a single accordion; keeping the first."),g=!1),i=!0),k(r,g)}}}function f(t,e){if(d(t)===e)return;if(e&&!E(t.root)&&t.root)for(let o of R(t.root)){if(o===t.item)continue;let i=b(o);i&&d(i)&&f(i,!1)}D(t),k(t,e);let n={open:e,trigger:t.trigger,panel:t.panel};t.item.dispatchEvent(new CustomEvent(S,{bubbles:!0,detail:n}))}function p(t){let e=typeof t=="string"?document.getElementById(t):t;return e?e.matches(`[${a}], [${u}], [${A}]`)?b(e):(console.warn("[TUI accordion] Pass an item, trigger or panel (or its id), not",e),null):(console.warn(`[TUI accordion] No element with id "${String(t)}".`),null)}function B(t){let e=p(t);return e?(f(e,!0),!0):!1}function G(t){let e=p(t);return e?(f(e,!1),!0):!1}function q(t){let e=p(t);return e?(N(e),d(e)):null}function N(t){if(L(t.trigger))return;if(!d(t)){f(t,!0);return}(E(t.root)||t.root?.hasAttribute(x)||!t.root)&&f(t,!1)}var P=Symbol.for("tangible-ui/vanilla/accordion/handled");function w(t){if(t.defaultPrevented||!(t.target instanceof Element))return;let e=t;if(e[P])return;let n=t.target.closest(`[${u}]`);if(!n||!n.closest(`[${a}]`)||!n.closest(`[${l}]`))return;let o=b(n);!o||o.trigger!==n||(e[P]=!0,N(o))}function h(){v++===0&&(document.addEventListener("click",w),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>M(),{once:!0}):M());let t=!1;return()=>{t||(t=!0,!(--v>0)&&document.removeEventListener("click",w))}}var H=Symbol.for("tangible-ui/vanilla/accordion"),c=globalThis;c[H]||(c[H]=$,h());c.TangibleUI=c.TangibleUI||{};c.TangibleUI.accordion=c[H];})();