All files / components command-palette.ts

98.23% Statements 111/113
95.95% Branches 95/99
96.77% Functions 30/31
100% Lines 85/85

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 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293                                                                                                                                                                                                                                                              6x 6x 6x 6x   6x 28x   6x 38x     44x 44x 2x 28x   6x                 6x 38x 38x 16x   38x 38x         26x         6x       3x 3x 3x 3x 3x   6x                 6x 6x               6x 36x   25x       8x 6x       5x 3x   6x       7x 6x 6x 4x 4x 3x 3x 3x 3x 3x         6x 6x 6x 6x 6x             7x 6x 6x 6x 1x 1x         4x 3x 4x   8x 8x 8x 7x       2x 5x 3x 3x       3x 1x     17x 16x 16x 16x 3x 13x 3x 10x 7x 4x 3x 2x 14x 14x            
import { createCollection, fuzzyScore, type CollectionItem } from '../collections/collection';
import { createControllerHost } from '../core/host';
import type { ChangeDetails, RuntimeController, RuntimeEventSource } from '../core/types';
import { listen } from '../dom/dom';
import { createControllableValue } from '../state/controllable';
import { createDialog, type DialogOptions } from './dialog';
import type {
  OpenChangeEvent,
  OpenChangeReason,
  OpenLifecycleEvents,
  OverlayElements,
} from './openable';
 
/** Registered command metadata and action. @public */
export interface CommandItem extends CollectionItem {
  /** Optional visual grouping label. */
  readonly group?: string;
  /** Additional searchable terms. */
  readonly keywords?: readonly string[];
  /** Action invoked after a non-cancelled selection. */
  readonly perform: () => void | Promise<void>;
}
 
/** Configurable global command-palette shortcut. @public */
export interface CommandShortcut {
  /** KeyboardEvent key value. @defaultValue `k` */
  readonly key?: string;
  /** Requires Control on Windows/Linux or Meta on macOS. @defaultValue `true` */
  readonly ctrlOrMeta?: boolean;
  /** Requires Alt when true. */
  readonly alt?: boolean;
  /** Requires Shift when true. */
  readonly shift?: boolean;
}
 
/** Causes of Command Palette query and selection changes. @public */
export type CommandPaletteReason = 'programmatic' | 'input' | 'keyboard' | 'pointer';
 
/** Immutable Command Palette snapshot. @public */
export interface CommandPaletteSnapshot {
  /** Modal dialog open state. */
  readonly open: boolean;
  /** Current search query. */
  readonly query: string;
  /** Keyboard-active command ID. */
  readonly activeId: string | null;
  /** Score-ordered matching commands. */
  readonly commands: readonly Readonly<CommandItem>[];
  /** Whether no enabled command matches the query. */
  readonly empty: boolean;
  /** Whether query state is consumer-owned. */
  readonly queryControlled: boolean;
  /** Whether open state is consumer-owned. */
  readonly openControlled: boolean;
}
 
/** Command Palette selection payload. @public */
export interface CommandPaletteSelectEvent {
  /** Selected command. */
  readonly command: Readonly<CommandItem>;
  /** Typed cause and optional native event. */
  readonly details: ChangeDetails<CommandPaletteReason>;
}
 
/** Command Palette query payload. @public */
export interface CommandPaletteQueryEvent {
  /** Next query. */
  readonly query: string;
  /** Typed cause and optional native event. */
  readonly details: ChangeDetails<CommandPaletteReason>;
}
 
/** Command Palette event map. @public */
export interface CommandPaletteEvents extends Omit<OpenLifecycleEvents, 'stateChange'> {
  /** Cancellable event emitted before command invocation. */
  readonly beforeSelect: CommandPaletteSelectEvent;
  /** Event emitted after command invocation is started. */
  readonly select: CommandPaletteSelectEvent;
  /** Event emitted after query changes. */
  readonly queryChange: CommandPaletteQueryEvent;
  /** Event emitted for accepted open, query, or selection changes. */
  readonly stateChange: OpenChangeEvent | CommandPaletteSelectEvent | CommandPaletteQueryEvent;
}
 
/** Command Palette configuration. @public */
export interface CommandPaletteOptions {
  /** Dialog state and focus configuration. */
  readonly dialog?: DialogOptions;
  /** Global shortcut configuration. */
  readonly shortcut?: CommandShortcut;
  /** Initial query in uncontrolled mode. */
  readonly defaultQuery?: string;
  /** Reads consumer-owned query. */
  readonly getQuery?: () => string;
  /** Receives query change requests. */
  readonly onQueryChange?: (query: string, details: ChangeDetails<CommandPaletteReason>) => void;
  /** Subscribes to external query changes. */
  readonly subscribeQuery?: (listener: () => void) => () => void;
  /** Replaces the default ordered fuzzy score. */
  readonly matcher?: (command: Readonly<CommandItem>, query: string) => number;
}
 
/** Headless Command Palette controller. @public */
export interface CommandPaletteController
  extends RuntimeController<CommandPaletteSnapshot>, RuntimeEventSource<CommandPaletteEvents> {
  /** Registers a dynamic command and returns scoped cleanup. */
  registerCommand(command: CommandItem): () => void;
  /** Binds consumer-rendered modal dialog DOM. */
  bind(elements: OverlayElements): () => void;
  /** Registers the configured global shortcut on an explicit owner document. */
  bindShortcut(ownerDocument: Document): () => void;
  /** Opens the palette. */
  open(details?: ChangeDetails<OpenChangeReason>): void;
  /** Closes the palette. */
  close(details?: ChangeDetails<OpenChangeReason>): void;
  /** Updates query and active command. */
  setQuery(query: string, details?: ChangeDetails<CommandPaletteReason>): void;
  /** Handles navigation, activation, and Escape. */
  handleKeyDown(event: KeyboardEvent): void;
  /** Invokes an enabled command and closes after successful dispatch. */
  select(id: string, details?: ChangeDetails<CommandPaletteReason>): void;
}
 
/** Creates a modal Command Palette using the shared Dialog, collection, and fuzzy-search layers. @public */
export function createCommandPalette(
  options: CommandPaletteOptions = {},
): CommandPaletteController {
  const collection = createCollection<CommandItem>();
  const dialog = createDialog({ modal: true, ...(options.dialog ?? {}) });
  let activeId: string | null = null;
  let commands: readonly CommandItem[] = [];
  const matcher =
    options.matcher ??
    ((command: Readonly<CommandItem>, query: string) =>
      fuzzyScore(`${command.text} ${(command.keywords ?? []).join(' ')}`, query));
  const filter = (query: string): readonly CommandItem[] =>
    Object.freeze(
      collection
        .items()
        .map((command) => ({ command, score: matcher(command, query) }))
        .filter(({ score }) => score > Number.NEGATIVE_INFINITY)
        .sort((a, b) => b.score - a.score)
        .map(({ command }) => command),
    );
  const host = createControllerHost<CommandPaletteSnapshot, CommandPaletteEvents>({
    open: dialog.getSnapshot().open,
    query: options.defaultQuery ?? '',
    activeId,
    commands,
    empty: true,
    queryControlled: options.getQuery !== undefined,
    openControlled: dialog.getSnapshot().controlled,
  });
  const sync = (): void => {
    commands = filter(queryState.get());
    if (!commands.some((command) => command.id === activeId && !command.disabled)) {
      activeId = commands.find((command) => !command.disabled)?.id ?? null;
    }
    const dialogSnapshot = dialog.getSnapshot();
    host.update({
      open: dialogSnapshot.open,
      query: queryState.get(),
      activeId,
      commands,
      empty: commands.every((command) => command.disabled),
      queryControlled: queryState.controlled,
      openControlled: dialogSnapshot.controlled,
    });
  };
  const commitQuery = (
    query: string,
    changeDetails?: ChangeDetails<CommandPaletteReason>,
  ): void => {
    sync();
    Iif (!changeDetails) return;
    const payload = { query, details: changeDetails };
    host.emit('queryChange', payload);
    host.emit('stateChange', payload);
  };
  const queryState = createControllableValue<string, CommandPaletteReason>(
    {
      defaultValue: options.defaultQuery ?? '',
      ...(options.getQuery ? { getValue: options.getQuery } : {}),
      ...(options.onQueryChange ? { onValueChange: options.onQueryChange } : {}),
      ...(options.subscribeQuery ? { subscribeValue: options.subscribeQuery } : {}),
    },
    commitQuery,
  );
  host.resources.add(dialog.subscribe(sync));
  const openEvents = [
    'beforeOpen',
    'open',
    'afterOpen',
    'beforeClose',
    'close',
    'afterClose',
  ] as const;
  for (const name of openEvents) {
    host.resources.add(
      dialog.on(name, (event) => {
        if (!host.emit(name, event.detail)) event.preventDefault();
      }),
    );
  }
  host.resources.add(dialog.on('stateChange', (event) => host.emit('stateChange', event.detail)));
  const setQuery = (
    query: string,
    changeDetails: ChangeDetails<CommandPaletteReason> = { reason: 'programmatic' },
  ): void => {
    if (!host.alive() || queryState.get() === query) return;
    Eif (queryState.set(query, changeDetails)) commitQuery(query, changeDetails);
  };
  const select = (
    id: string,
    changeDetails: ChangeDetails<CommandPaletteReason> = { reason: 'programmatic' },
  ): void => {
    if (!host.alive()) return;
    const command = collection.get(id);
    if (!command || command.disabled) return;
    const payload = { command, details: changeDetails };
    if (!host.emit('beforeSelect', payload)) return;
    const result = command.perform();
    if (result instanceof Promise) void result.catch(() => undefined);
    host.emit('select', payload);
    host.emit('stateChange', payload);
    dialog.close({
      reason: 'selection',
      ...(changeDetails.event ? { event: changeDetails.event } : {}),
    });
  };
  host.resources.add(() => queryState.destroy());
  host.resources.add(() => collection.clear());
  host.resources.add(() => dialog.destroy());
  sync();
  return {
    getSnapshot: host.getSnapshot,
    subscribe: host.subscribe,
    on: host.on,
    off: host.off,
    once: host.once,
    registerCommand(command) {
      if (!host.alive()) return () => undefined;
      const unregister = collection.register(Object.freeze({ ...command }));
      sync();
      return () => {
        unregister();
        sync();
      };
    },
    bind: dialog.bind,
    bindShortcut(ownerDocument) {
      if (!host.alive()) return () => undefined;
      const shortcut = options.shortcut ?? {};
      return host.resources.add(
        listen<KeyboardEvent>(ownerDocument, 'keydown', (event) => {
          const platform = ownerDocument.defaultView?.navigator.platform ?? '';
          const primary = /mac/iu.test(platform) ? event.metaKey : event.ctrlKey;
          if ((shortcut.ctrlOrMeta ?? true) !== primary) return;
          if (
            (shortcut.alt ?? false) !== event.altKey ||
            (shortcut.shift ?? false) !== event.shiftKey
          )
            return;
          if (event.key.toLocaleLowerCase() !== (shortcut.key ?? 'k').toLocaleLowerCase()) return;
          event.preventDefault();
          dialog.toggle({ reason: 'keyboard', event });
        }),
      );
    },
    open: (changeDetails = { reason: 'programmatic' }) => dialog.open(changeDetails),
    close: (changeDetails = { reason: 'programmatic' }) => dialog.close(changeDetails),
    setQuery,
    handleKeyDown(event) {
      if (!host.alive()) return;
      const enabled = commands.filter((command) => !command.disabled);
      const index = enabled.findIndex((command) => command.id === activeId);
      if (event.key === 'ArrowDown')
        activeId = enabled[(index + 1 + enabled.length) % enabled.length]?.id ?? null;
      else if (event.key === 'ArrowUp')
        activeId = enabled[(index - 1 + enabled.length) % enabled.length]?.id ?? null;
      else if (event.key === 'Home') activeId = enabled[0]?.id ?? null;
      else if (event.key === 'End') activeId = enabled.at(-1)?.id ?? null;
      else if (event.key === 'Enter' && activeId) select(activeId, { reason: 'keyboard', event });
      else if (event.key === 'Escape') dialog.close({ reason: 'escape-key', event });
      else return;
      event.preventDefault();
      sync();
    },
    select,
    destroy: host.destroy,
  };
}