Skip to main content

createSelectableCollectionNavigation

Add accessible keyboard navigation (arrow keys, Home/End, RTL) for tabs, radio groups, and listboxes.

View as Markdown

createSelectableCollectionNavigation adds keyboard navigation (Arrow Up/Down/Left/Right, Home, End) and activation handling to a collection of selectable items such as Tabs, Radio Groups, and Listboxes.

Import#

import { createSelectableCollectionNavigation } from 'moraine/utils'

Signature#

function createSelectableCollectionNavigation<TItem, TValue extends NonNullable<unknown>>(
  options: CreateSelectableCollectionNavigationOptions<TItem, TValue>,
): {
  onNavigationKeyDown: (
    event: KeyboardEvent,
    currentValue: TValue | undefined,
    orientation: 'horizontal' | 'vertical',
  ) => void
  focusByOffset: (currentValue: TValue | undefined, offset: number) => void
  focusBoundary: (kind: 'first' | 'last') => void
  moveSelection: (currentValue: TValue, offset: number) => void
}

interface CreateSelectableCollectionNavigationOptions<TItem, TValue extends NonNullable<unknown>> {
  /** Items in the collection. */
  items: Accessor<TItem[]>
  /** Returns the stable, non-null value that identifies an item. */
  getValue: (item: TItem) => TValue
  /** Called when an item is selected. */
  onSelect: (value: TValue) => void
  /** Returns whether an item is disabled. Disabled items are skipped. */
  isDisabled?: (item: TItem) => boolean
  /**
   * Whether arrow-key navigation wraps from the ends.
   * @default false
   */
  loop?: Accessor<boolean>
  /**
   * `'automatic'` selects the item arrow keys move to. `'manual'` only focuses it.
   * @default 'automatic'
   */
  activationMode?: Accessor<'automatic' | 'manual'>
  /** Focuses an item by its value. */
  focusValue?: (value: TValue) => void
  /** Returns the text direction. Without it, the direction comes from the event target's computed style. */
  getDirection?: () => 'ltr' | 'rtl'
}

TValue can be a string, number, or any other non-null value. Items compare by ===.

Usage Example#

src/CustomTabs.tsx
import { For, createSignal } from 'solid-js'
import { createSelectableCollectionNavigation } from 'moraine/utils'

interface TabItem {
  id: string
  label: string
}

export function CustomTabs() {
  const tabs: TabItem[] = [
    { id: 'overview', label: 'Overview' },
    { id: 'settings', label: 'Settings' },
    { id: 'billing', label: 'Billing' },
  ]
  const [selectedId, setSelectedId] = createSignal('overview')
  const tabRefs = new Map<string, HTMLButtonElement>()

  const nav = createSelectableCollectionNavigation({
    items: () => tabs,
    getValue: (item) => item.id,
    onSelect: (id) => setSelectedId(id),
    focusValue: (id) => tabRefs.get(id)?.focus(),
    loop: () => true,
  })

  return (
    <div role="tablist" aria-label="Project sections" class="flex gap-2 border-b">
      <For each={tabs}>
        {(tab) => (
          <button
            ref={(element) => tabRefs.set(tab.id, element)}
            role="tab"
            aria-selected={selectedId() === tab.id}
            tabIndex={selectedId() === tab.id ? 0 : -1}
            onClick={() => setSelectedId(tab.id)}
            onKeyDown={(event) => nav.onNavigationKeyDown(event, tab.id, 'horizontal')}
            class="px-3 py-1.5 border-b-2"
          >
            {tab.label}
          </button>
        )}
      </For>
    </div>
  )
}

Key Bindings#

The orientation you pass to onNavigationKeyDown decides which arrow keys navigate.

  • ArrowLeft / ArrowRight: Move to the previous / next item in horizontal collections. The keys swap in RTL.
  • ArrowUp / ArrowDown: Move to the previous / next item in vertical collections.
  • Home / End: Jump to the first / last enabled item.
  • Enter / Space: Select the current item unless it is disabled, in both activation modes.
  • Automatic vs manual: In automatic mode, arrow keys, Home, and End move focus and select in one step. In manual mode, they only move focus.

Without a current item, the next key goes to the first enabled item and the previous key to the last. Disabled items are skipped. Without loop, navigation stops at the ends.