Subtlyv0.1.1
Menus & navigation

typeahead()

Find a menu item by typing. Keyboard prefix search.

Available in v0.1.1navigation.jsNavigation

Try it

Focus a destination, then type “p” to jump to Poland. Press “p” again to cycle to Portugal. Type “net” quickly to reach Netherlands. Arrow keys also work.

Live example

Focus a destination, then type its name.

<div id="your-component">
<div class="destination-list" role="toolbar" aria-label="Choose a destination"><button>Belgium</button><button>France</button><button>Netherlands</button><button>Poland</button><button>Portugal</button><button>Spain</button></div><p class="demo-status" role="status">Focus a destination, then type its name.</p>
</div>
import * as kit from 'subtly';

const el = document.querySelector('#your-component');
const listeners = new AbortController();
const { signal } = listeners;
const status = text => {
  el.querySelector('.demo-status').textContent = text;
};
// Local simulation only. Replace with your real data operation.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

function setup() {
  const list = el.querySelector('[role="toolbar"]');
          const focus = kit.rovingFocus(list, { selector: 'button', orientation: 'vertical' });
          const stop = kit.typeahead(list, { items: () => list.querySelectorAll('button') });
          list.addEventListener('focusin', event => status(event.target.textContent + ' focused'), { signal });
          list.addEventListener('click', event => {
            if (event.target.matches('button')) status(event.target.textContent + ' selected (demo)');
          }, { signal });
          return () => { stop(); focus.destroy(); };
}
const stop = setup();

// Call when this component is removed.
function cleanup() {
  listeners.abort();
  stop?.();
}

Add it to your project

  1. Copy the HTML. Use the HTML tab above and place the markup inside a dedicated component root. Layout classes belong to this documentation website; use your own styles.
  2. Connect the behavior. Copy the JavaScript tab, update #your-component and initialize it after the elements exist. Replace simulated operations with your own data.
  3. Clean up on unmount. Call the example’s cleanup() when the component is removed. It aborts application listeners and releases the utility’s timers or observers.

The preview and JavaScript tab use the same utility wiring. status() writes plain text into the example’s status element. wait() is a simulated local delay. For examples with data-ix attributes, start the declarative runtime once at application level, as shown in the code. Use your framework guide to place setup and cleanup correctly.

API and lifecycle

Provide a root plus items() returning enabled visible options. Typed characters match item-label prefixes; repeated letters cycle matches. The default buffer timeout is 600 ms. label(item) can customize the searchable text.

Interface
root, items(), label, timeout; returns cleanup.
Lifecycle
The return value is a cleanup function for the keydown listener. Update items() when options change; the helper does not manage selection or ARIA roles.

Accessibility and safety

Implementation notes

Initialize after the DOM is available. Keep native controls and keyboard interactions intact; release listeners and timers on unmount.

Use on a custom menu or listbox, not a text input. The helper skips composition and editable targets; combine it with the widget's own arrow-key navigation.

What to check

Type a full prefix, repeat a letter to cycle and wait for the buffer to reset. Check disabled options and text-entry fields are not intercepted.

View documented module source
/** Typeahead for a custom menu/listbox. Pass visible enabled items only.
 * Repeated letters cycle matching items; multi-letter input matches prefixes.
 * Does not assign ARIA roles or selection; your widget owns those semantics. */
export function typeahead(root, { items, label = e => e.textContent.trim(), timeout = 600 } = {}) {
    let buffer = '', last = 0;
    function key(e) {
        if (e.defaultPrevented || e.isComposing || e.ctrlKey || e.metaKey || e.altKey || e.key.length !== 1 || e.key === ' ' || e.target.closest('input,textarea,[contenteditable]')) return;
        const now = Date.now(), char = e.key.toLocaleLowerCase();
        buffer = now - last > timeout ? char : buffer + char; last = now;
        const repeated = [...buffer].every(c => c === char);
        const query = repeated ? char : buffer;
        const list = [...items()]; if (!list.length) return;
        const index = list.indexOf(document.activeElement);
        const start = repeated ? index + 1 : Math.max(0,index);
        for (let n = 0; n < list.length; n++) {
            const item = list[(start+n)%list.length];
            if (label(item).toLocaleLowerCase().startsWith(query)) { e.preventDefault(); item.focus(); break; }
        }
    }
    root.addEventListener('keydown', key);
    return () => root.removeEventListener('keydown', key);
}

/** Dismiss an overlay when pointer starts AND ends outside it.
 * Include trigger and portalled descendants in `inside()`.
 * Keyboard Escape is intentionally separate: only the topmost overlay
 * should handle it. Use your framework's overlay stack if available. */
export function outsidePress(inside, dismiss, doc = document) {
    let outside = false, pointer = null;
    const isOutside = e => !inside().some(el => e.composedPath().includes(el));
    function down(e) { if (!e.isPrimary || e.button !== 0) return; pointer = e.pointerId; outside = isOutside(e); }
    function up(e) { if (pointer !== e.pointerId) return; const close = outside && isOutside(e); pointer = null; outside = false; if (close) dismiss(e); }
    function cancel() { pointer = null; outside = false; }
    doc.addEventListener('pointerdown',down,true); doc.addEventListener('pointerup',up,true); doc.addEventListener('pointercancel',cancel,true);
    return () => { doc.removeEventListener('pointerdown',down,true); doc.removeEventListener('pointerup',up,true); doc.removeEventListener('pointercancel',cancel,true); };
}

/** Save/restore list scroll position and optional filter state.
 * Call restore AFTER content is rendered; key by route and list identity.
 * Memory-only by default: no sensitive search terms persisted to storage. */
export function navigationMemory({ max = 30 } = {}) {
    const cache = new Map();
    return {
        save(key, element, state = {}) { cache.delete(key); cache.set(key,{ top:element.scrollTop,left:element.scrollLeft,state:structuredClone(state) }); while(cache.size>max) cache.delete(cache.keys().next().value); },
        read(key) { const value=cache.get(key); return value ? structuredClone(value.state) : null; },
        restore(key,element) { const value=cache.get(key); if(value) element.scrollTo({top:value.top,left:value.left,behavior:'instant'}); return Boolean(value); },
        clear() { cache.clear(); }
    };
}

Search Subtly documentation

Popular pages
↑↓ to navigate↵ to openESC to close