𝗜 𝗥𝗲𝗯𝘂𝗶𝗹𝘁 𝘁𝗵𝗲 𝗖𝗺𝗱-𝗞 𝗖𝗼𝗺𝗺𝗮𝗻𝗱 𝗣𝗮𝗹𝗲𝘁𝘁𝗲 𝗶𝗻 𝟲𝟬 𝗟𝗶𝗻𝗲𝘀

Apps like Linear, Raycast, and VS Code use a command palette. You press ⌘K, type a few letters, and hit Enter. It feels complex. It is actually only 60 lines of JavaScript.

Here is how you build it:

  1. The Keyboard Listener You need a global listener. Browsers use Ctrl+K for search. You must use preventDefault to stop this.

document.addEventListener("keydown", e => { if ((e.metaKey || e.ctrlKey) && e.key === "k") { e.preventDefault(); openPalette(); } });

  1. Command Data Store every action as an object. The UI stays simple. It lists these objects and runs the function you choose. Adding a new feature means adding one line to your list.

const COMMANDS = [ { icon: "🌙", label: "Toggle dark mode", group: "Theme", run: toggleDark }, { icon: "📄", label: "New file", group: "File", run: newFile }, ];

  1. Fuzzy Search Good palettes use subsequence matching. This means characters must appear in order, but they do not need to be next to each other. Typing "tgldk" should find "Toggle dark mode".

function fuzzy(q, text) { let i = 0; for (const ch of text.toLowerCase()) { if (ch === q[i]) i++; } return i === q.length; }

  1. Keyboard Navigation The goal is to stop using the mouse. Use Arrow keys to change a selection index. Use Enter to run the command. Use Escape to close the menu.

  2. The Instant Feel Focus the input field the moment the palette opens. This allows you to type without clicking.

A command palette needs four things:

Build this once to understand how modern power-user tools work.

Try it live: https://dev48v.infy.uk/design/day10-command-palette.html

Source: https://dev.to/dev48v/i-rebuilt-the-cmd-k-command-palette-in-60-lines-of-javascript-3a1l