Skip to content

About

Production-ready, keyboard-driven Command Palette (Cmd+K / Ctrl+K) React component with fuzzy search, dynamic action registration, and framework support for Inertia.js, Next.js, and Vite.

Topics

Resources

Code of conduct

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

@manggala31/react-spotlight

Production-ready, keyboard-driven Command Palette (Cmd+K / Ctrl+K) React component with fuzzy search, grouped actions, custom theme support, and seamless framework integrations.

npm version license


Table of Contents


Overview

@manggala/react-spotlight is a lightweight, headless-compatible Command Palette component engineered for modern web applications. Inspired by Spotlight on macOS and command palettes in tools like Raycast, Linear, and VS Code, it gives users instant access to navigation routes, quick actions, application settings, and search results via global keyboard shortcuts.


Key Features

  • Lightning Fast Search: Performs instantaneous fuzzy filtering over labels, descriptions, and custom keywords.
  • Keyboard First Design: Complete keyboard control using Cmd+K / Ctrl+K to open, arrow keys to navigate, Enter to execute, and Esc to dismiss.
  • Grouped Action Structure: Organize commands cleanly into logical sections such as Navigation, Actions, and Preferences.
  • Framework Agnostic Integration: Designed to work out of the box with React 18, React 19, Next.js, Remix, and Laravel Inertia.js.
  • Zero Heavy Dependencies: Built with zero external UI framework dependencies to keep bundle sizes minimal.
  • Context Driven API: Access, open, close, or mutate available commands dynamically from any nested component via useSpotlight().
  • Extensible Styling: Includes a clean default dark/light theme driven by CSS custom properties, easily overridden or restyled with Tailwind CSS.

Installation

Install @manggala/react-spotlight using your package manager of choice:

# Using npm
npm install @manggala31/react-spotlight

# Using yarn
yarn add @manggala31/react-spotlight

# Using pnpm
pnpm add @manggala31/react-spotlight

# Using bun
bun add @manggala31/react-spotlight

Quick Start

1. Wrap Application with Provider & Import Styles

Import the default CSS stylesheet and place SpotlightProvider and <Spotlight /> near the root of your application component tree.

import React from 'react';
import { SpotlightProvider, Spotlight, SpotlightActionGroup } from '@manggala/react-spotlight';
import '@manggala/react-spotlight/styles.css';

const actions: SpotlightActionGroup[] = [
  {
    group: 'Navigation',
    actions: [
      {
        id: 'nav-dashboard',
        label: 'Go to Dashboard',
        description: 'View primary analytics and system overview',
        shortcut: ['g', 'd'],
        onSelect: () => {
          window.location.href = '/dashboard';
        },
      },
      {
        id: 'nav-users',
        label: 'User Management',
        description: 'Manage registered accounts and role permissions',
        shortcut: ['g', 'u'],
        onSelect: () => {
          window.location.href = '/users';
        },
      },
    ],
  },
  {
    group: 'Quick Actions',
    actions: [
      {
        id: 'action-new-project',
        label: 'Create New Project',
        description: 'Initialize a new project workspace',
        shortcut: ['c', 'p'],
        onSelect: () => {
          console.log('Project creation modal opened');
        },
      },
      {
        id: 'action-toggle-theme',
        label: 'Toggle Dark Mode',
        description: 'Switch between light and dark visual themes',
        onSelect: () => {
          console.log('Theme mode toggled');
        },
      },
    ],
  },
];

export default function App() {
  return (
    <SpotlightProvider actions={actions}>
      <YourLayout>
        <Header />
        <Content />
      </YourLayout>
      <Spotlight placeholder="Search pages, commands, or settings..." />
    </SpotlightProvider>
  );
}

2. Trigger Spotlight Programmatically

Use the useSpotlight hook inside any descendant component to trigger or control the Spotlight dialog:

import React from 'react';
import { useSpotlight } from '@manggala/react-spotlight';

export function Header() {
  const { openSpotlight } = useSpotlight();

  return (
    <header className="header">
      <button onClick={openSpotlight} className="search-button" type="button">
        <span>Search commands...</span>
        <kbd>Cmd + K</kbd>
      </button>
    </header>
  );
}

Framework Integrations

Laravel Inertia.js (React)

Integrate Spotlight into your Inertia layout (e.g., AuthenticatedLayout.tsx):

import React from 'react';
import { router } from '@inertiajs/react';
import { SpotlightProvider, Spotlight, SpotlightActionGroup } from '@manggala/react-spotlight';
import '@manggala/react-spotlight/styles.css';

interface Props {
  children: React.ReactNode;
}

export default function AuthenticatedLayout({ children }: Props) {
  const actions: SpotlightActionGroup[] = [
    {
      group: 'Navigation',
      actions: [
        {
          id: 'inertia-dashboard',
          label: 'Dashboard',
          shortcut: ['g', 'd'],
          onSelect: () => router.visit(route('dashboard')),
        },
        {
          id: 'inertia-profile',
          label: 'Profile Settings',
          shortcut: ['g', 'p'],
          onSelect: () => router.visit(route('profile.edit')),
        },
      ],
    },
  ];

  return (
    <SpotlightProvider actions={actions}>
      <div className="min-h-screen bg-gray-100">
        <main>{children}</main>
      </div>
      <Spotlight placeholder="Type a command or search..." />
    </SpotlightProvider>
  );
}

Next.js (App Router)

Place SpotlightProvider inside a client component wrapper:

'use client';

import React from 'react';
import { SpotlightProvider, Spotlight, SpotlightActionGroup } from '@manggala/react-spotlight';
import '@manggala/react-spotlight/styles.css';

export function Providers({ children }: { children: React.ReactNode }) {
  const actions: SpotlightActionGroup[] = [
    {
      group: 'General',
      actions: [
        {
          id: 'next-home',
          label: 'Home Page',
          onSelect: () => window.location.href = '/',
        },
      ],
    },
  ];

  return (
    <SpotlightProvider actions={actions}>
      {children}
      <Spotlight />
    </SpotlightProvider>
  );
}

Vite + React

Include in main.tsx or App.tsx:

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { SpotlightProvider, Spotlight } from '@manggala/react-spotlight';
import '@manggala/react-spotlight/styles.css';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <SpotlightProvider actions={[]}>
      <App />
      <Spotlight />
    </SpotlightProvider>
  </React.StrictMode>
);

API Reference

<SpotlightProvider>

The context provider component that manages Spotlight state and global keyboard listeners.

Prop Type Default Description
actions SpotlightActionGroup[] [] Initial array of grouped actions.
shortcut string 'k' Key identifier combined with Cmd / Ctrl to toggle modal.
children React.ReactNode undefined Children elements wrapped by provider.

<Spotlight>

The UI dialog component that renders the input field and search results overlay.

Prop Type Default Description
placeholder string 'Type a command or search...' Input placeholder text.
emptyMessage string 'No results found.' Text rendered when no items match search query.
maxResults number 10 Maximum visible items rendered in search list.
className string '' Optional custom CSS class for overlay container.
onClose () => void undefined Callback function executed when modal closes.

useSpotlight() Hook

A custom hook providing access to Spotlight context controls:

const {
  isOpen,            // boolean: current visibility state
  openSpotlight,     // () => void: opens modal
  closeSpotlight,    // () => void: closes modal
  toggleSpotlight,   // () => void: toggles modal
  actions,           // SpotlightActionGroup[]: active actions list
  setActions,        // State setter to update actions dynamically
} = useSpotlight();

TypeScript Interfaces

SpotlightAction

export interface SpotlightAction {
  id: string;
  label: string;
  description?: string;
  icon?: React.ReactNode;
  shortcut?: string[];
  keywords?: string[];
  onSelect: (action: SpotlightAction) => void;
}

SpotlightActionGroup

export interface SpotlightActionGroup {
  group: string;
  actions: SpotlightAction[];
}

Keyboard Shortcuts

Key Combination Action
Cmd + K / Ctrl + K Toggle Spotlight modal visibility
Down Arrow (↓) Select next result item
Up Arrow (↑) Select previous result item
Enter Execute currently selected action
Escape (Esc) Dismiss / Close Spotlight modal

Styling & Custom Themes

CSS Variables

Customize colors, borders, typography, and shadows by modifying the default CSS custom properties:

:root {
  --spotlight-bg: #1e1e2e;
  --spotlight-border: #313244;
  --spotlight-text: #cdd6f4;
  --spotlight-muted: #a6adc8;
  --spotlight-active-bg: #313244;
  --spotlight-accent: #cba6f7;
  --spotlight-radius: 12px;
  --spotlight-shadow: 0 20px 50px rgba(0, 0, 0, 0.4);
}

Tailwind CSS Customization

Target Spotlight CSS class names directly within your Tailwind stylesheet:

.spotlight-container {
  @apply bg-slate-900 border-slate-800 text-slate-100 rounded-xl shadow-2xl;
}

.spotlight-item-selected {
  @apply bg-slate-800 text-indigo-400;
}

Accessibility (a11y)

  • Focus Management: Focus automatically moves to search input when modal opens.
  • Scroll Containment: Keyboard arrow key navigation automatically keeps active items in viewport.
  • ARIA Semantics: Standard list semantics ensure compatibility with screen readers.

Performance & Footprint

  • Bundle Size: Under 4 KB minified + gzipped.
  • Zero Heavy Dependencies: No external UI frameworks or utility libraries required.
  • Tree-shakeable: Built with tsup delivering clean ES Modules and CommonJS outputs.

License

MIT License © Ilham Hatta Manggala

About

Production-ready, keyboard-driven Command Palette (Cmd+K / Ctrl+K) React component with fuzzy search, dynamic action registration, and framework support for Inertia.js, Next.js, and Vite.

Topics

Resources

Code of conduct

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages