Skip to content

Latest commit

 

History

61 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@keenmate/web-commandpalette

License: MIT

A framework-agnostic command palette web component — commands with multi-step wizards, scoped and global search, favorites and recents, full keyboard control, RTL and a phone sheet.

What is it

@keenmate/web-commandpalette is a custom element (<web-command-palette>) that holds the whole command-palette state machine — routing, wizards, search, keyboard, focus and scroll-lock — and talks to its host only through properties, events and async callbacks. Hosts (plain JS, Svelte, React, Blazor, Phoenix LiveView) stay thin adapters instead of re-implementing the palette.

Reads the shared --base-* variables from the page (pure-admin, or @keenmate/theme-designer), with its own --cp-* knobs on top; the CSS is the component's own (plain CSS in the shadow root).

Headline features:

  • / commands and : search contexts, plus global search that shows matching commands instantly.
  • Multi-step command wizards — fixed, loaded-once or live-searched steps, free text, branches.
  • Async search with debounce and AbortSignal cancellation; empty scoped queries never hit the server.
  • Favorites and recently used items (incl. completed runs, replayable with Tab / Enter), stored in localStorage or your backend.
  • A short feedback line of what ran, instead of the dialog just vanishing.
  • Full keyboard control, g <letter> hotkeys, RTL, i18n labels, a fullscreen sheet on phones.

What's New in v1.0.0-rc01

  • First release — one palette instead of three — <web-command-palette> replaces the three command palettes that had drifted apart in pure-admin vanilla, svelte-pure-admin and the keen-pure-admin LiveComponent. Each one re-implemented routing, search and keyboard handling, and each had its own bugs. The element now owns that whole logic, and hosts talk to it only through properties, cp-* events and async callbacks. Hosts (plain JS, Svelte, React, Blazor, Phoenix LiveView) become thin adapters, with no copy of the palette logic in each. commands plus a searchCallback is a complete setup. Every callback argument and event detail is plain JSON, so it can travel over a LiveView bridge.

  • Commands, contexts and global search — with the async rules built in — / lists commands and : lists search contexts, and anything else is a global search. Global search shows matching commands and contexts right away, then appends the server results. Static lists filter on the client. Provider calls are debounced (search-debounce) and cancelled with an AbortSignal when a newer query replaces them, and late answers are dropped. A context search with an empty query never calls the server. Keyboard navigation never waits for a request, so arrows stay instant while results load.

  • Multi-step wizards that can branch — A command can ask a series of steps, such as /deploy → environment → branch. Each step can use fixed options, a list loaded once, a live search: true lookup, freeText, or a conditional shouldShow. An option can carry its own steps, so one command can fork: /assign-admin John to group Finance and … to site Intranet ask different follow-up questions. Step.load and Context.search let you define a picker once and reuse it across commands. The central stepOptionsCallback / searchCallback keep working for server-driven hosts.

  • Favorites and recents, replayable in two keystrokes — Star any row with Ctrl/⌘+D. The Recent list (ranked by frequency and recency) remembers instant commands, finished runs with their answers, contexts and chosen results. Replaying a run offers each remembered answer first: Enter accepts the rest and runs it, Tab steps through one answer at a time, and typing replaces an answer. The home screen shows only a few rows (max-favorite-count / max-recent-count). Ctrl+F / R or g f opens the full lists, and all of these keys are configurable. Usage is stored per storage-key (core state store: localStorage, or your loadStateCallback / saveStateCallback), or in your backend one entry at a time through loadUsageCallback / saveUsageCallback.

  • A feedback line instead of a vanishing dialog — When a command runs, the dialog used to disappear at once, which left users unsure anything had happened. It now shrinks, with an animation, to a one-line summary like ✓ /deploy to Staging branch main Done for feedback-duration ms (default 1500). The cp-complete / cp-command event still fires immediately. Turn it off with show-feedback="false", or replace or skip it per run with renderFeedbackCallback.

  • Theming on the shared --base-* variables, plus its own --cp-* knobs — The CSS is the component's own plain CSS, inlined into the shadow root. It reads only the shared --base-* variables (@keenmate/base-css-variables 2.0) and the component's --cp-* knobs. Font sizes follow --base-font-size-* and the font follows --base-font-family. Sizing scales with --base-rem and size="sm|lg|xl". Icons (check, close, star) and the results scrollbar can be themed through --cp-icon-* and --cp-scrollbar-*. Shadow parts expose palette, container, input, results and footer. The examples site has a theme gallery with seven styles and size switches.

  • RTL, i18n and a phone sheet — dir="rtl" on the element or any ancestor mirrors the layout, which uses logical CSS throughout. It also swaps ←/→ paging and isolates mixed-direction text, so /deploy … keeps its order inside Hebrew or Arabic UI. Every visible and announced string comes from the labels map. On touch phones, mobile-presentation="auto" turns the dialog into a fullscreen sheet that stays above the on-screen keyboard.

Breaking change in the next release (2.0) — interaction model. The cp- prefix is gone (open, close, result-select, ready), and cp-command / cp-complete fold into one action event per command run (detail.id = the command id, detail.selections the wizard answers). on* twins receive the event detail. Commands are core action items (name → text, shortcut → trigger, hotkey → shortcut, plus isVisible / isDisabled / isDanger / onClick / get*Callback); options use text; every callback takes one ctx (searchCallback({ scope, term, signal }), getStepOptionsCallback(ctx)); beforeActionCallback / beforeResultSelectCallback can cancel; el.controller is the public facade. The full old → new table is in the CHANGELOG [Unreleased] section; the docs below already describe the new API.

Demos & docs

All guides are listed in docs/README.md.

Install

npm install @keenmate/web-commandpalette

Quick start

Minimal — commands, no server:

<web-command-palette></web-command-palette>

<script type="module">
  import '@keenmate/web-commandpalette';

  const palette = document.querySelector('web-command-palette');
  palette.commands = [
    { id: 'reload', trigger: '/reload', text: 'Reload data', shortcut: 'g r' },
    { id: 'go', trigger: '/go', text: 'Go to page',
      steps: [{ id: 'page', options: [{ text: 'Users', value: '/users' }, { text: 'Orders', value: '/orders' }] }] },
  ];

  // One `action` event per command: at once without steps, after the last answer with them.
  palette.addEventListener('action', (e) => {
    if (e.detail.id === 'reload') reload();
    if (e.detail.id === 'go') location.href = e.detail.selections[0].value;
  });
</script>

Ctrl/⌘+K opens it; type / for commands.

With search — contexts, a server callback and results:

palette.contexts = [{ id: 'products', trigger: ':products', aliases: [':p'], text: 'Products' }];

palette.searchCallback = async ({ scope, term, signal }) => {
  // scope: 'global' | { contextId: 'products' } — called only for non-empty, debounced terms
  const where = scope === 'global' ? 'global' : scope.contextId;
  const res = await fetch(`/api/search?scope=${where}&q=${encodeURIComponent(term)}`, { signal });
  return res.json(); // [{ id, title, subtitle?, icon?, href?, group? }]
};

palette.addEventListener('result-select', (e) => (location.href = e.detail.result.href));

The palette closes itself after result-select / action; the host performs the effect. Every callback takes one ctx, and every ctx and event detail carries controller (el.controller, the public facade) and element. See docs/usage.md for the full API and docs/examples.md for recipes (step pickers, branching wizards, favorites on the server, custom feedback line).

Responsive rules

Tune the palette per device class or window width without app-side viewport code — a map of partial configs, or a callback that computes one. Keys are configKeys; set them page-wide, per tag or per instance (the generic core mechanism, core SPEC §6.7):

// page-wide (every KeenMate component) and per tag — may be set before the script loads
window.components.responsive = { device: { mobile: { presentation: 'fullscreen' } } };
window.components['web-command-palette'].responsiveCallback = (ctx) =>
  ctx.deviceClass === 'desktop' ? undefined : { display: 'tokens', pageSize: 5 };

// per instance (property, or the JSON attribute responsive='{"breakpoint":{"mobile":{…}}}')
palette.responsive = { device: { tablet: { size: 'lg' } }, breakpoint: { mobile: { pageSize: 5 } } };
palette.responsiveCallback = (ctx) => (ctx.env.orientation === 'landscape' ? { pageSize: 4 } : undefined);

A map has two axes: device — the device class by capability (mobile / tablet = a touch phone / tablet, a mouse device is desktop at any width); breakpoint — the window width bucket (mobile < 768px ≤ tablet < 1024px ≤ desktop, so a narrowed desktop window is mobile). Both may be set; device wins on the same key. Own widths or combinations (device class AND width, orientation, …) go in a responsiveCallback.

Precedence (later wins, key by key): global map → global callback → per-tag map → per-tag callback → the instance's own attributes / properties → instance map → instance callback. An attribute written on an element is never overridden by a page rule; null from the instance callback ignores every page rule. Rules re-run when the device class / breakpoint / orientation changes and never reflect to attributes. Typed as CommandPaletteResponsiveMap / CommandPaletteResponsiveCallback.

Editor IntelliSense

The package ships editor metadata — autocomplete and hover docs for the element's attributes, events and --cp-* CSS variables — generated from the component's source on every build.

  • JetBrains (WebStorm / IntelliJ) — works automatically via the web-types field in package.json.

  • VS Code — point your workspace at the data files once in .vscode/settings.json:

    {
      "html.customData": ["./node_modules/@keenmate/web-commandpalette/vscode.html-custom-data.json"],
      "css.customData": ["./node_modules/@keenmate/web-commandpalette/vscode.css-custom-data.json"]
    }

    Reload the window after adding them.

Browser support

Modern evergreen browsers with native customElements, Shadow DOM, CSS color-mix(), light-dark() and dynamic viewport units (the @keenmate/base-css-variables themes also use relative color syntax):

  • Chrome / Edge 123+
  • Firefox 128+
  • Safari 17.5+

Dark mode follows the page signal (.dark, [data-theme], [data-bs-theme] on <html> / <body>, or a theme-source element), detected by @keenmate/web-components-core and mirrored onto the host as data-context-theme, so it works in every engine. To follow the OS, declare html { color-scheme: light dark } on the page.

No polyfills are shipped.

Development

make setup        # npm install
make dev          # examples hub on http://localhost:12400
make build        # cem analyze → library build (dist/) → check:vars
make test         # unit (Vitest) + e2e (Playwright: desktop + Pixel 7)
make              # list every target (publish-rc, image-build, kill-port, …)

Details — single tests, the CSS pipeline, publishing, the example-site image — are in BUILD.md.

Code structure

Layer File Role
Element src/web-component.ts CommandPaletteElement — the static inputs / static events tables (IDE metadata is generated from them), overlay, presentation, feedback line
Logic src/palette.ts PaletteEngine — DOM-free modes, wizard, filtering, async search, pagination
Logic src/usage.ts UsageStore — favorites + recents, frecency, pluggable persistence
Render src/render.ts builds the shadow DOM once and patches it
Service src/keyboard.ts global hotkeys + input key map
Side src/types.ts, src/logger.ts, src/helpers/, src/css/ public types, logging, pure helpers (filter.ts filtering, icons.ts icon rendering), shadow-root CSS

The palette CSS is plain CSS in src/css/ (main.css imports the layers: variables → component → overrides), inlined into the shadow root. It reads only --cp-* and --base-*.

About

Authored and maintained by Keenmate s.r.o.. The component ships standalone with sensible light/dark defaults; when mounted inside Pure Admin — or any host that publishes the --base-* taxonomy via @keenmate/theme-designer — it adopts the host's colors, typography, and sizing automatically. There is no runtime dependency on Pure Admin; the integration is opt-in via CSS variables.

Built with BlissFramework

Built on @keenmate/web-components-core (BlissElement) following the BlissFramework component guidelines for structure, theming and accessibility.

License

MIT © Keenmate s.r.o. — see LICENSE.

Releases

Packages

Contributors

Languages