Skip to content

Checkpoint: A Command Palette

The Course
•
20 min study

Close the earlier lessons and build this from the brief. Dialog.jsx and Combobox.jsx from this day's lessons are included, with a list of commands.

The brief

  • An Open command palette button, and Ctrl+K (or ⌘K) anywhere on the page, open a dialog titled Command palette.
  • Inside, a combobox labelled Command lists the commands. Choosing one, with the keyboard or the mouse, closes the dialog and shows Ran: Take a break in a status message that screen readers announce.
  • Escape closes the palette, and focus returns to wherever it was.
  • Each time the palette opens, the combobox starts empty.

Acceptance checks:

  • With the keyboard only: Ctrl+K, type br, Down, Enter. The status says Ran: Take a break, and the dialog is closed.
  • After Escape, focus is back on the button that opened it.
  • The status message is a live region that exists before anything is run.
Your workspace React · 6 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // Build the command palette here. Dialog.jsx and Combobox.jsx from this day's // lessons are included. See the brief. export default function App() { return ( <main> <h1>Study Hub</h1> </main> ); } import { useId, useState } from "react"; // A text box with a list of suggestions. Focus stays in the input; the // highlighted option is announced through aria-activedescendant. export default function Combobox({ label, options, onSelect }) { const [query, setQuery] = useState(""); const [open, setOpen] = useState(false); const [activeIndex, setActiveIndex] = useState(-1); const id = useId(); const listId = `${id}-list`; const matches = options.filter((o) => o.toLowerCase().includes(query.trim().toLowerCase())); const optionId = (index) => `${id}-option-${index}`; function choose(option) { setQuery(option); setOpen(false); setActiveIndex(-1); onSelect(option); } function handleKeyDown(event) { if (event.key === "ArrowDown") { event.preventDefault(); setOpen(true); setActiveIndex((i) => Math.min(i + 1, matches.length - 1)); } else if (event.key === "ArrowUp") { event.preventDefault(); setActiveIndex((i) => Math.max(i - 1, 0)); } else if (event.key === "Enter" && open && activeIndex >= 0) { event.preventDefault(); choose(matches[activeIndex]); } else if (event.key === "Escape") { setOpen(false); setActiveIndex(-1); } } return ( <div> <label htmlFor={`${id}-input`}>{label}</label>{" "} <input id={`${id}-input`} role="combobox" aria-expanded={open} aria-controls={listId} aria-autocomplete="list" aria-activedescendant={open && activeIndex >= 0 ? optionId(activeIndex) : undefined} value={query} onChange={(e) => { setQuery(e.target.value); setOpen(true); setActiveIndex(-1); }} onKeyDown={handleKeyDown} /> {open && matches.length > 0 && ( <ul role="listbox" id={listId} aria-label={label}> {matches.map((option, index) => ( <li key={option} id={optionId(index)} role="option" aria-selected={index === activeIndex} data-active={index === activeIndex} onMouseDown={(e) => e.preventDefault()} onClick={() => choose(option)} > {option} </li> ))} </ul> )} </div> ); } export const commands = ["Start focus session", "Take a break", "Open today's cards", "Show stats", "Switch theme"]; import { useEffect, useRef } from "react"; // The browser's own modal dialog: it moves focus inside, blocks the page // behind it, closes on Escape, and returns focus to whatever opened it. export default function Dialog({ open, onClose, title, children }) { const ref = useRef(null); // Keep the real <dialog> in step with the open prop. useEffect(() => { const dialog = ref.current; if (open && !dialog.open) dialog.showModal(); if (!open && dialog.open) dialog.close(); }, [open]); return ( <dialog ref={ref} onClose={onClose} aria-labelledby="dialog-title"> <h2 id="dialog-title">{title}</h2> {children} </dialog> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; } dialog { border: 1px solid #d6dde6; border-radius: 12px; padding: 1rem 1.25rem; width: min(28rem, 90vw); } dialog::backdrop { background: rgb(22 35 45 / 0.45); } [role="listbox"] { list-style: none; margin: 0.25rem 0 0; padding: 0.25rem; border: 1px solid #d6dde6; border-radius: 8px; max-height: 12rem; overflow-y: auto; } [role="option"] { padding: 0.3rem 0.5rem; border-radius: 6px; cursor: pointer; } [role="option"][data-active="true"] { background: #e6f7fc; outline: 2px solid #087ea4; } [role="toolbar"] { display: flex; gap: 0.25rem; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the shortcut

An effect that listens for keydown on window, checks event.key.toLowerCase() === "k" && (event.ctrlKey || event.metaKey), and calls preventDefault so the browser's own shortcut doesn't run.

Hint 2: starting empty

Render the combobox only while the palette is open: {open && <Combobox ... />}. Closing unmounts it, so its state starts fresh next time.

Show one solution
One solution React · 6 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useEffect, useState } from "react"; import Combobox from "./Combobox.jsx"; import Dialog from "./Dialog.jsx"; import { commands } from "./commands.js"; export default function App() { const [open, setOpen] = useState(false); const [status, setStatus] = useState(""); // Ctrl+K or ⌘K opens the palette from anywhere on the page. useEffect(() => { function handleKeyDown(event) { if (event.key.toLowerCase() === "k" && (event.ctrlKey || event.metaKey)) { event.preventDefault(); setOpen(true); } } window.addEventListener("keydown", handleKeyDown); return () => window.removeEventListener("keydown", handleKeyDown); }, []); function run(command) { setOpen(false); setStatus(`Ran: ${command}`); } return ( <main> <h1>Study Hub</h1> <button onClick={() => setOpen(true)}>Open command palette</button> <p className="muted" role="status">{status}</p> <Dialog open={open} onClose={() => setOpen(false)} title="Command palette"> {open && <Combobox label="Command" options={commands} onSelect={run} />} </Dialog> </main> ); } import { useId, useState } from "react"; // A text box with a list of suggestions. Focus stays in the input; the // highlighted option is announced through aria-activedescendant. export default function Combobox({ label, options, onSelect }) { const [query, setQuery] = useState(""); const [open, setOpen] = useState(false); const [activeIndex, setActiveIndex] = useState(-1); const id = useId(); const listId = `${id}-list`; const matches = options.filter((o) => o.toLowerCase().includes(query.trim().toLowerCase())); const optionId = (index) => `${id}-option-${index}`; function choose(option) { setQuery(option); setOpen(false); setActiveIndex(-1); onSelect(option); } function handleKeyDown(event) { if (event.key === "ArrowDown") { event.preventDefault(); setOpen(true); setActiveIndex((i) => Math.min(i + 1, matches.length - 1)); } else if (event.key === "ArrowUp") { event.preventDefault(); setActiveIndex((i) => Math.max(i - 1, 0)); } else if (event.key === "Enter" && open && activeIndex >= 0) { event.preventDefault(); choose(matches[activeIndex]); } else if (event.key === "Escape") { setOpen(false); setActiveIndex(-1); } } return ( <div> <label htmlFor={`${id}-input`}>{label}</label>{" "} <input id={`${id}-input`} role="combobox" aria-expanded={open} aria-controls={listId} aria-autocomplete="list" aria-activedescendant={open && activeIndex >= 0 ? optionId(activeIndex) : undefined} value={query} onChange={(e) => { setQuery(e.target.value); setOpen(true); setActiveIndex(-1); }} onKeyDown={handleKeyDown} /> {open && matches.length > 0 && ( <ul role="listbox" id={listId} aria-label={label}> {matches.map((option, index) => ( <li key={option} id={optionId(index)} role="option" aria-selected={index === activeIndex} data-active={index === activeIndex} onMouseDown={(e) => e.preventDefault()} onClick={() => choose(option)} > {option} </li> ))} </ul> )} </div> ); } export const commands = ["Start focus session", "Take a break", "Open today's cards", "Show stats", "Switch theme"]; import { useEffect, useRef } from "react"; // The browser's own modal dialog: it moves focus inside, blocks the page // behind it, closes on Escape, and returns focus to whatever opened it. export default function Dialog({ open, onClose, title, children }) { const ref = useRef(null); // Keep the real <dialog> in step with the open prop. useEffect(() => { const dialog = ref.current; if (open && !dialog.open) dialog.showModal(); if (!open && dialog.open) dialog.close(); }, [open]); return ( <dialog ref={ref} onClose={onClose} aria-labelledby="dialog-title"> <h2 id="dialog-title">{title}</h2> {children} </dialog> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; } dialog { border: 1px solid #d6dde6; border-radius: 12px; padding: 1rem 1.25rem; width: min(28rem, 90vw); } dialog::backdrop { background: rgb(22 35 45 / 0.45); } [role="listbox"] { list-style: none; margin: 0.25rem 0 0; padding: 0.25rem; border: 1px solid #d6dde6; border-radius: 8px; max-height: 12rem; overflow-y: auto; } [role="option"] { padding: 0.3rem 0.5rem; border-radius: 6px; cursor: pointer; } [role="option"][data-active="true"] { background: #e6f7fc; outline: 2px solid #087ea4; } [role="toolbar"] { display: flex; gap: 0.25rem; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Check yourself

  1. What does showModal() do that rendering a <div> on top doesn't?
  2. In a roving tabindex, which element has tabIndex={0}?
  3. Why does a combobox keep focus in the input and use aria-activedescendant?

Was this article helpful?

Your response is saved on this device.