Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | 12x 12x 12x 12x 12x 12x 52x 70x 70x 12x 12x 40x 12x 7x 7x 6x 6x 6x 12x 12x 10x 10x 8x 8x 8x 12x 12x 12x 9x 9x 9x 2x 1x 7x 8x 8x 7x 7x 12x 12x 12x 12x 12x 21x 20x 20x 20x 20x 12x 20x 10x 20x 20x 20x 7x 5x 5x 5x 3x 3x 5x 5x 3x 5x 9x 8x 5x 4x 3x 2x 1x 1x 1x 1x 6x 6x | import { createRuntimeId } from '../accessibility/ids';
import { createCollection, type CollectionItem } from '../collections/collection';
import { createControllerHost } from '../core/host';
import type {
ChangeDetails,
ControllableValueOptions,
RuntimeController,
RuntimeEventSource,
} from '../core/types';
import { focusById } from '../focus/focus';
import { createControllableValue } from '../state/controllable';
import { createDisclosureSnapshot } from './disclosure';
/** Accordion expansion modes. @public */
export type AccordionType = 'single' | 'multiple';
/** Causes of accordion expansion and focus changes. @public */
export type AccordionChangeReason = 'programmatic' | 'trigger' | 'keyboard';
/** Dynamic accordion item registration. @public */
export interface AccordionItem extends CollectionItem {
/** Optional consumer-provided trigger ID. */
readonly triggerId?: string;
/** Optional consumer-provided panel ID. */
readonly panelId?: string;
}
/** Immutable per-item ARIA and state metadata. @public */
export interface AccordionItemSnapshot {
/** Stable item ID. */
readonly id: string;
/** Trigger DOM ID. */
readonly triggerId: string;
/** Panel DOM ID. */
readonly panelId: string;
/** Current expansion state. */
readonly expanded: boolean;
/** Current disabled state. */
readonly disabled: boolean;
/** Roving tabindex value for the trigger. */
readonly tabIndex: 0 | -1;
}
/** Immutable Accordion snapshot. @public */
export interface AccordionSnapshot {
/** Single or multiple expansion mode. */
readonly type: AccordionType;
/** Ordered expanded item IDs. */
readonly expandedIds: readonly string[];
/** Keyboard-focused trigger ID. */
readonly focusedId: string | null;
/** Whether expansion state is consumer-owned. */
readonly controlled: boolean;
/** Ordered registered item metadata. */
readonly items: readonly AccordionItemSnapshot[];
}
/** Accordion expansion event payload. @public */
export interface AccordionChangeEvent {
/** Ordered next expanded IDs. */
readonly expandedIds: readonly string[];
/** Item that initiated the transition. */
readonly itemId: string;
/** Typed cause and optional native event. */
readonly details: ChangeDetails<AccordionChangeReason>;
}
/** Accordion event map with cancellable expansion. @public */
export interface AccordionEvents {
/** Cancellable event emitted before expansion state changes. */
readonly beforeChange: AccordionChangeEvent;
/** Event emitted after expansion state changes. */
readonly stateChange: AccordionChangeEvent;
}
/** Accordion options using the shared controllable state contract. @public */
export interface AccordionOptions extends Partial<
ControllableValueOptions<readonly string[], AccordionChangeReason>
> {
/** Single or multiple expansion mode. @defaultValue `single` */
readonly type?: AccordionType;
/** Allows the single open item to collapse. @defaultValue `false` */
readonly collapsible?: boolean;
/** Wraps trigger focus at collection edges. @defaultValue `true` */
readonly loop?: boolean;
/** Stable ID prefix for item relationships. */
readonly id?: string;
}
/** Headless Accordion controller. @public */
export interface AccordionController
extends RuntimeController<AccordionSnapshot>, RuntimeEventSource<AccordionEvents> {
/** Registers an item and optional trigger element for roving focus. */
registerItem(item: AccordionItem, trigger?: HTMLElement): () => void;
/** Toggles an item according to single/multiple and collapsible rules. */
toggle(itemId: string, details?: ChangeDetails<AccordionChangeReason>): void;
/** Handles Arrow, Home, End, Enter, and Space on an item trigger. */
handleTriggerKeyDown(itemId: string, event: KeyboardEvent): void;
/** Focuses a registered enabled trigger by ID. */
focus(itemId: string): void;
}
/** Creates an Accordion that reuses the shared collection and controllable-state layers. @public */
export function createAccordion(options: AccordionOptions = {}): AccordionController {
const type = options.type ?? 'single';
const prefix = options.id ?? createRuntimeId('accordion');
const collection = createCollection<AccordionItem>();
const triggers = new Map<string, HTMLElement>();
const registrations = new Map<string, symbol>();
let focusedId: string | null = null;
const build = (expandedIds: readonly string[], controlled: boolean): AccordionSnapshot => ({
type,
expandedIds: Object.freeze([...expandedIds]),
focusedId,
controlled,
items: collection.items().map((item) => {
const relationship = createDisclosureSnapshot(
`${prefix}-${item.id}`,
expandedIds.includes(item.id),
controlled,
item.disabled ?? false,
item.triggerId,
item.panelId,
);
return {
id: item.id,
triggerId: relationship.trigger.id,
panelId: relationship.panel.id,
expanded: relationship.expanded,
disabled: relationship.disabled,
tabIndex: focusedId === item.id ? 0 : -1,
};
}),
});
const host = createControllerHost<AccordionSnapshot, AccordionEvents>(
build(options.getValue?.() ?? options.defaultValue ?? [], options.getValue !== undefined),
);
const sync = (): void => {
host.update(build(state.get(), state.controlled));
};
let pendingChange: AccordionChangeEvent | undefined;
const commit = (
expandedIds: readonly string[],
changeDetails?: ChangeDetails<AccordionChangeReason>,
): void => {
sync();
if (!changeDetails || !pendingChange) return;
const payload = { ...pendingChange, expandedIds, details: changeDetails };
pendingChange = undefined;
host.emit('stateChange', payload);
};
const state = createControllableValue<readonly string[], AccordionChangeReason>(
{
defaultValue: options.defaultValue ?? [],
...(options.getValue ? { getValue: options.getValue } : {}),
...(options.onValueChange ? { onValueChange: options.onValueChange } : {}),
...(options.subscribeValue ? { subscribeValue: options.subscribeValue } : {}),
},
commit,
);
const focus = (id: string): void => {
const item = collection.get(id);
if (!item || item.disabled) return;
focusedId = id;
sync();
focusById(triggers, id);
};
const toggle = (
itemId: string,
changeDetails: ChangeDetails<AccordionChangeReason> = { reason: 'programmatic' },
): void => {
const item = collection.get(itemId);
if (!item || item.disabled) return;
const current = [...state.get()];
const expanded = current.includes(itemId);
let next: readonly string[];
if (expanded) {
if (type === 'single' && !options.collapsible) return;
next = current.filter((id) => id !== itemId);
} else next = type === 'single' ? [itemId] : [...current, itemId];
const payload = { expandedIds: next, itemId, details: changeDetails };
if (!host.emit('beforeChange', payload)) return;
pendingChange = payload;
if (state.set(next, changeDetails)) commit(next, changeDetails);
};
host.resources.add(() => state.destroy());
host.resources.add(() => collection.clear());
host.resources.add(() => triggers.clear());
host.resources.add(() => registrations.clear());
return {
getSnapshot: host.getSnapshot,
subscribe: host.subscribe,
on: host.on,
off: host.off,
once: host.once,
registerItem(item, trigger) {
if (!host.alive()) return () => undefined;
const token = Symbol(item.id);
registrations.set(item.id, token);
const unregister = collection.register(item);
if (trigger) triggers.set(item.id, trigger);
else triggers.delete(item.id);
if (!focusedId && !item.disabled) focusedId = item.id;
else if (focusedId === item.id && item.disabled) focusedId = collection.edge('first') ?? null;
sync();
let active = true;
return () => {
if (!active) return;
active = false;
unregister();
if (registrations.get(item.id) === token) {
registrations.delete(item.id);
triggers.delete(item.id);
}
const current = collection.get(item.id);
if (focusedId === item.id && (!current || current.disabled))
focusedId = collection.edge('first') ?? null;
sync();
};
},
toggle,
handleTriggerKeyDown(itemId, event) {
if (!host.alive()) return;
let target: string | undefined;
if (event.key === 'ArrowDown') target = collection.move(itemId, 1, options.loop ?? true);
else if (event.key === 'ArrowUp') target = collection.move(itemId, -1, options.loop ?? true);
else if (event.key === 'Home') target = collection.edge('first');
else if (event.key === 'End') target = collection.edge('last');
else if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
toggle(itemId, { reason: 'keyboard', event });
return;
} else return;
event.preventDefault();
if (target) focus(target);
},
focus,
destroy: host.destroy,
};
}
|