All files / components listbox.ts

99.02% Statements 102/103
98.18% Branches 108/110
100% Functions 16/16
100% Lines 83/83

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 242 243 244 245 246 247 248 249 250 251                                                                                                                                                                                                                          21x 21x 21x 21x 21x 21x 120x             129x                 21x     21x 99x     21x       14x 14x 2x 2x   12x 12x 12x 12x 12x 12x 12x   21x                 21x 14x 13x 12x 12x   10x 7x 7x   21x       19x 19x 16x 19x   19x     2x   19x 1x 15x 15x 13x 13x   21x 23x   21x 21x 21x 21x 21x             40x 39x 39x 11x 2x 39x 39x 39x 29x 27x 27x 27x 27x 22x 27x           20x   18x 18x 11x 2x 9x 8x 7x 2x 5x 4x 4x 4x 1x 17x 17x          
import {
  createCollection,
  findTypeaheadMatch,
  type CollectionItem,
} from '../collections/collection';
import { createRuntimeId } from '../accessibility/ids';
import { createControllerHost } from '../core/host';
import { createTimeoutManager } from '../core/timers';
import type {
  ChangeDetails,
  ControllableValueOptions,
  RuntimeController,
  RuntimeEventSource,
} from '../core/types';
import { createControllableValue } from '../state/controllable';
 
/** Listbox selection mode. @public */
export type ListboxSelectionMode = 'single' | 'multiple';
 
/** Causes of listbox selection changes. @public */
export type ListboxChangeReason = 'programmatic' | 'pointer' | 'keyboard' | 'typeahead';
 
/** Dynamic Listbox option registration. @public */
export interface ListboxOption extends CollectionItem {
  /** Consumer value; defaults to the stable option ID. */
  readonly value?: string;
}
 
/** Immutable per-option semantic metadata. @public */
export interface ListboxOptionSnapshot {
  /** Stable option ID. */
  readonly id: string;
  /** Consumer selection value. */
  readonly value: string;
  /** Human-readable typeahead text. */
  readonly text: string;
  /** Value for `aria-selected`. */
  readonly selected: boolean;
  /** Value for `aria-disabled`. */
  readonly disabled: boolean;
  /** Option role for consumer markup. */
  readonly role: 'option';
}
 
/** Immutable Listbox snapshot. @public */
export interface ListboxSnapshot {
  /** Stable listbox ID used by `aria-controls`. */
  readonly id: string;
  /** Listbox role for consumer markup. */
  readonly role: 'listbox';
  /** Whether multiple values may be selected. */
  readonly ariaMultiselectable: boolean;
  /** ID exposed through `aria-activedescendant`. */
  readonly activeId: string | null;
  /** Ordered selected consumer values. */
  readonly selectedValues: readonly string[];
  /** Whether selection is consumer-owned. */
  readonly controlled: boolean;
  /** Ordered option semantics. */
  readonly options: readonly ListboxOptionSnapshot[];
}
 
/** Listbox selection lifecycle payload. @public */
export interface ListboxSelectEvent {
  /** Option that initiated the transition. */
  readonly option: Readonly<ListboxOption>;
  /** Ordered next selected values. */
  readonly selectedValues: readonly string[];
  /** Typed cause and optional native event. */
  readonly details: ChangeDetails<ListboxChangeReason>;
}
 
/** Listbox event map. @public */
export interface ListboxEvents {
  /** Cancellable event emitted before selection changes. */
  readonly beforeSelect: ListboxSelectEvent;
  /** Event emitted after selection changes. */
  readonly select: ListboxSelectEvent;
  /** Event emitted with the published selection snapshot. */
  readonly stateChange: ListboxSelectEvent;
}
 
/** Listbox options for state ownership and keyboard behavior. @public */
export interface ListboxOptions extends Partial<
  ControllableValueOptions<readonly string[], ListboxChangeReason>
> {
  /** Single or multiple selection. @defaultValue `single` */
  readonly selectionMode?: ListboxSelectionMode;
  /** Wraps Arrow navigation at collection edges. @defaultValue `true` */
  readonly loop?: boolean;
  /** Deterministic listbox ID. */
  readonly id?: string;
}
 
/** Headless Listbox controller using active-descendant focus. @public */
export interface ListboxController
  extends RuntimeController<ListboxSnapshot>, RuntimeEventSource<ListboxEvents> {
  /** Registers a dynamic option and returns cleanup scoped to that registration. */
  registerOption(option: ListboxOption): () => void;
  /** Sets the keyboard-active enabled option. */
  setActive(id: string | null): void;
  /** Selects or toggles an enabled option. */
  select(id: string, details?: ChangeDetails<ListboxChangeReason>): void;
  /** Handles Arrow keys, Home/End, typeahead, Enter, and Space. */
  handleKeyDown(event: KeyboardEvent): void;
}
 
/** Creates an accessible single- or multi-select Listbox with dynamic options. @public */
export function createListbox(options: ListboxOptions = {}): ListboxController {
  const id = options.id ?? createRuntimeId('listbox');
  const mode = options.selectionMode ?? 'single';
  const collection = createCollection<ListboxOption>();
  let activeId: string | null = null;
  let typeahead = '';
  const typeaheadTimer = createTimeoutManager();
  const build = (values: readonly string[], controlled: boolean): ListboxSnapshot => ({
    id,
    role: 'listbox',
    ariaMultiselectable: mode === 'multiple',
    activeId,
    selectedValues: Object.freeze([...values]),
    controlled,
    options: collection.items().map((option) => ({
      id: option.id,
      value: option.value ?? option.id,
      text: option.text,
      selected: values.includes(option.value ?? option.id),
      disabled: option.disabled ?? false,
      role: 'option',
    })),
  });
  const host = createControllerHost<ListboxSnapshot, ListboxEvents>(
    build(options.getValue?.() ?? options.defaultValue ?? [], options.getValue !== undefined),
  );
  const sync = (): void => {
    host.update(build(state.get(), state.controlled));
  };
  let pendingSelection: ListboxSelectEvent | undefined;
  const commit = (
    selectedValues: readonly string[],
    changeDetails?: ChangeDetails<ListboxChangeReason>,
  ): void => {
    sync();
    if (!changeDetails) {
      pendingSelection = undefined;
      return;
    }
    Iif (!pendingSelection) return;
    activeId = pendingSelection.option.id;
    const payload = { ...pendingSelection, selectedValues, details: changeDetails };
    pendingSelection = undefined;
    sync();
    host.emit('select', payload);
    host.emit('stateChange', payload);
  };
  const state = createControllableValue<readonly string[], ListboxChangeReason>(
    {
      defaultValue: options.defaultValue ?? [],
      ...(options.getValue ? { getValue: options.getValue } : {}),
      ...(options.onValueChange ? { onValueChange: options.onValueChange } : {}),
      ...(options.subscribeValue ? { subscribeValue: options.subscribeValue } : {}),
    },
    commit,
  );
  const setActive = (nextId: string | null): void => {
    if (!host.alive()) return;
    if (nextId) {
      const option = collection.get(nextId);
      if (!option || option.disabled) return;
    }
    if (activeId === nextId) return;
    activeId = nextId;
    sync();
  };
  const select = (
    optionId: string,
    changeDetails: ChangeDetails<ListboxChangeReason> = { reason: 'programmatic' },
  ): void => {
    const option = collection.get(optionId);
    if (!option || option.disabled) return;
    const value = option.value ?? option.id;
    const current = [...state.get()];
    const next =
      mode === 'single'
        ? [value]
        : current.includes(value)
          ? current.filter((item) => item !== value)
          : [...current, value];
    if (current.length === next.length && current.every((item, index) => item === next[index]))
      return;
    const payload = { option, selectedValues: next, details: changeDetails };
    if (!host.emit('beforeSelect', payload)) return;
    pendingSelection = payload;
    if (state.set(next, changeDetails)) commit(next, changeDetails);
  };
  const resetTypeahead = (): void => {
    typeahead = '';
  };
  host.resources.add(resetTypeahead);
  host.resources.add(typeaheadTimer.clear);
  host.resources.add(() => state.destroy());
  host.resources.add(() => collection.clear());
  return {
    getSnapshot: host.getSnapshot,
    subscribe: host.subscribe,
    on: host.on,
    off: host.off,
    once: host.once,
    registerOption(option) {
      if (!host.alive()) return () => undefined;
      const unregister = collection.register(option);
      if (!activeId && !option.disabled) activeId = option.id;
      else if (activeId === option.id && option.disabled)
        activeId = collection.edge('first') ?? null;
      sync();
      let active = true;
      return () => {
        if (!active) return;
        active = false;
        unregister();
        const current = collection.get(option.id);
        if (activeId === option.id && (!current || current.disabled))
          activeId = collection.edge('first') ?? null;
        sync();
      };
    },
    setActive,
    select,
    handleKeyDown(event) {
      if (!host.alive()) return;
      let next: string | undefined;
      if (event.key === 'ArrowDown')
        next = collection.move(activeId ?? undefined, 1, options.loop ?? true);
      else if (event.key === 'ArrowUp')
        next = collection.move(activeId ?? undefined, -1, options.loop ?? true);
      else if (event.key === 'Home') next = collection.edge('first');
      else if (event.key === 'End') next = collection.edge('last');
      else if (event.key === 'Enter' || event.key === ' ') {
        if (activeId) select(activeId, { reason: 'keyboard', event });
      } else if (event.key.length === 1 && !event.altKey && !event.ctrlKey && !event.metaKey) {
        typeahead += event.key;
        next = findTypeaheadMatch(collection.items(), typeahead, activeId ?? undefined);
        typeaheadTimer.schedule(resetTypeahead, 500);
      } else return;
      event.preventDefault();
      if (next) setActive(next);
    },
    destroy: host.destroy,
  };
}