Start MenuMOL
The menu a Start Button opens - a native popover, so light dismiss, Escape and the top layer come from the browser. The runtime adds what a start menu needs: the focus goes into the search and typing searches every item, a folder's items too, in one list; a folder opens its own popover beside its item (hover, Right arrow), the arrows walk what shows, Enter picks; Ctrl+Esc opens it from anywhere on the desktop. A pick fires start-select with the item's value and closes the menu - the page decides what it opens. The parts are all optional: a classic menu is a list with folders and a foot, a modern one leads with the search and a grid of pinned apps.
On this page (5)
Open it from the Start Button or with Ctrl+Esc, in any look. Type to search (try 'med' - Media Player is two folders deep); hover or press Right on a folder to open it beside its item. A pick closes the menu and fires start-select - the line under the desktop names it.
§States
Named states via the shared State API, bound on each .start-menu:
default- closedopen- open;{ query }searches
The first example carries data-state-demo; bun run screenshots drives it via el.api.setState(name) and captures screenshots/{mode}/start-menu-{state}.png.
Machine contract - verified against start-menu.schema.json by bun run verify:
| State | Type | Values | Default | Description |
|---|---|---|---|---|
open | boolean | true, false | false | The menu is open (data-state-name). |
§API
Generated from start-menu.ts and the shared State API - the descriptions are their JSDoc, the types are checked by the compiler.
States
type StartMenuState = 'default' | 'open' - setState(name, config) takes the config of the state it names.
| State | Description | ||||||
|---|---|---|---|---|---|---|---|
default | Closed. No config. | ||||||
open | Open.
|
Every element
| Member | Description | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
el.api.setState<S extends StartMenuState>(name: S, config?: StartMenuStateConfigs[S]): unknown | Enter a state: the DOM work runs (also when it is the current state), the store records it.
Returns | |||||||||
el.api.getState(): { name: StartMenuState; config: StartMenuStateConfigs[StartMenuState]; model?: ElementModel } | The state the element shows now - read back from the DOM, so it includes what the user changed. Returns | |||||||||
el.api.render(state?: { name: StartMenuState; config: StartMenuStateConfigs[StartMenuState]; model?: ElementModel }): string | The element's markup in a state - the authored markup with that state applied; a pure function of the state.
Returns | |||||||||
el.api.settled(): Promise<void> | Wait for the last state's DOM work (async states: a diagram rendering, a chart mounting). Returns | |||||||||
el.store: Store<{ name: StartMenuState; config: StartMenuStateConfigs[StartMenuState] }> | A defuss-store store of the element's state - subscribe to follow every change (also the user's), set it to drive the component. |
Registry
| Member | Description | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
df$.shadcn.startMenuApi.setState<S extends StartMenuState>(el: HTMLElement, name: S, config?: StartMenuStateConfigs[S]): unknown | Enter a state: the DOM work runs (also when it is the current state), the store records it.
Returns | ||||||||||||
df$.shadcn.startMenuApi.getState(el: HTMLElement): { name: StartMenuState; config: StartMenuStateConfigs[StartMenuState]; model?: ElementModel } | The state the element shows now - read back from the DOM, so it includes what the user changed.
Returns | ||||||||||||
df$.shadcn.startMenuApi.render(state: { name: StartMenuState; config: StartMenuStateConfigs[StartMenuState]; model?: ElementModel }): string | The element's markup in a state - the authored markup with that state applied; a pure function of the state.
Returns | ||||||||||||
df$.shadcn.startMenuApi.store(el: HTMLElement): Store<{ name: StartMenuState; config: StartMenuStateConfigs[StartMenuState] }> | The element's store (bindComponent made it).
Returns | ||||||||||||
df$.shadcn.startMenuApi.commit<S extends StartMenuState>(el: HTMLElement, name: S, config?: StartMenuStateConfigs[S]): void | Record a state the element reached on its own (no DOM work) - for a component's own handlers.
| ||||||||||||
df$.shadcn.startMenuStates: StartMenuState[] | The declared states, 'default' first: default, open. |
df$.shadcn.startMenu
| Member | Description | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
open(target: string | HTMLElement, query: string = ''): HTMLElement | null | Open the menu (with a search text).
Returns | |||||||||
close(target: string | HTMLElement): HTMLElement | null | Close the menu.
Returns | |||||||||
toggle(target: string | HTMLElement): boolean | Open it when closed, close it when open.
Returns |
Events
| Event | Description | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
start-select | Fires when an item is picked - its value and label; the menu closes.
|
Types
| Type | Description | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
StartSelectDetail | What start-select carries.
|
§CSS view file
/* -- Start Menu component ----------------------------------------- A popover anchored to its Start Button (above it, flipped below when there is no room): a head with the user, a search field, pinned items in a grid, all items in a list - a folder opens its own popover beside it - and the power buttons at the foot. While searching, the matches of every list and folder show in one list. A look restyles it; the markup stays. */@layer components { .start-menu { position: fixed; inset: auto; margin: 0; position-area: top span-right; position-try-fallbacks: flip-block, flip-inline; box-sizing: border-box; width: min(22rem, calc(100vw - 1rem)); max-height: min(32rem, 80vh); padding: 0.75rem; display: none; flex-direction: column; gap: 0.625rem; overflow: auto; border: 1px solid var(--border); border-radius: var(--radius-lg); background: var(--popover); color: var(--popover-foreground); font-family: var(--font-sans); font-size: 0.875rem; box-shadow: var(--shadow-xl); &:popover-open { display: flex; } } .start-menu-head { display: flex; align-items: center; gap: 0.625rem; font-weight: 600; } .start-menu-search { display: flex; align-items: center; gap: 0.5rem; padding: 0.375rem 0.625rem; border: 1px solid var(--input); border-radius: var(--radius-md); background: var(--background); color: var(--muted-foreground); & svg { width: 1rem; height: 1rem; flex: none; } & input { flex: 1; min-width: 0; border: 0; outline: none; background: none; color: var(--foreground); font: inherit; } &:focus-within { border-color: var(--ring); } } .start-menu-heading { margin: 0.25rem 0.25rem 0; color: var(--muted-foreground); font-size: 0.75rem; font-weight: 600; } .start-menu-pinned { display: grid; grid-template-columns: repeat(auto-fill, minmax(4.75rem, 1fr)); gap: 0.25rem; & .start-menu-item { flex-direction: column; gap: 0.375rem; padding-block: 0.625rem; text-align: center; font-size: 0.75rem; } & .start-menu-icon { width: 2rem; height: 2rem; } } .start-menu-list { display: flex; flex-direction: column; } .start-menu-item { display: flex; align-items: center; gap: 0.625rem; width: 100%; padding: 0.4375rem 0.625rem; border: 0; border-radius: var(--radius-md); background: none; color: inherit; font: inherit; text-align: start; cursor: default; outline: none; &:is(:hover, :focus-visible, [aria-expanded="true"]) { background: var(--accent); color: var(--accent-foreground); } &:focus-visible { outline: 2px solid var(--ring); outline-offset: -2px; } &[disabled] { opacity: 0.5; } /* a folder: an arrow at the end */ &[aria-haspopup]::after { content: ""; margin-inline-start: auto; width: 0.375rem; height: 0.375rem; border-block-start: 1.5px solid currentColor; border-inline-end: 1.5px solid currentColor; rotate: 45deg; } } .start-menu-icon { display: grid; place-items: center; width: 1.25rem; height: 1.25rem; flex: none; & > :is(svg, img, .desktop-glyph) { width: 100%; height: 100%; } } .start-menu-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } /* a folder's popover, beside its item */ .start-menu-sub { position: fixed; inset: auto; margin: 0; position-area: right span-bottom; position-try-fallbacks: flip-inline, flip-block; box-sizing: border-box; min-width: 12rem; max-height: 70vh; padding: 0.375rem; display: none; flex-direction: column; overflow: auto; border: 1px solid var(--border); border-radius: var(--radius-md); background: var(--popover); color: var(--popover-foreground); font-family: var(--font-sans); font-size: 0.875rem; box-shadow: var(--shadow-lg); &:popover-open { display: flex; } } .start-menu-foot { display: flex; align-items: center; gap: 0.25rem; margin-block-start: auto; padding-block-start: 0.5rem; border-block-start: 1px solid var(--border); & .start-menu-item { width: auto; } & .start-menu-item:first-child { margin-inline-end: auto; } } .start-menu-empty { margin: 0; padding: 0.75rem; color: var(--muted-foreground); text-align: center; } /* searching: every list's matches in one list; folders, pinned items and the rest step aside */ .start-menu[data-searching] { & .start-menu-pinned, & .start-menu-heading, & .start-menu-item[aria-haspopup], & .start-menu-list .start-menu-item:not([data-match]) { display: none; } & .start-menu-sub { display: contents; } } @media (prefers-reduced-motion: reduce) { .start-menu, .start-menu-sub { transition: none; } } @media (forced-colors: active) { .start-menu-item:is(:hover, :focus-visible, [aria-expanded="true"]) { background: Highlight; color: HighlightText; } }}§JavaScript view file
The popovers open and close natively; the script adds the search, the folders, the keys and start-select.
// -- Start Menu ---------------------------------------------------// A desktop's start menu on a popover: a search field that filters every item// as you type, pinned items and a list of all items (a folder opens its own// popover beside it, the classic cascading menu), the user and the power// buttons. Arrows move through what shows (Right / Left open and close a// folder), Enter picks; a pick fires start-select with the item's value and// closes the menu - the page decides what it opens. A Start Button opens it.// VERIFIED: (start-menu.e2e) a close clears the search even when the page emptied the field first - the Desktop// scaffold's handler did, and the next opening showed nothing but an empty result list.// Shared preamble (AGENTS.md "State API"); the implementation lives in core.js —// build.ts rewrites this import into a df$.shadcn.shared binding in dist/.import { defussGlobals, defussQuery, componentState, bindComponent } from '../../../shared/state-api.js';const df$ = defussGlobals();const dfDollar = defussQuery();/** An element by id, through df$ (null when none has it). */const byId = (id: string | null | undefined): HTMLElement | null => (id ? (dfDollar('#' + CSS.escape(id)).get(0) as HTMLElement | undefined) : undefined) ?? null;/** What start-select carries. */interface StartSelectDetail { /** the picked item's data-value (else its label) */ value: string; /** the picked item's label */ label: string;}const startMenuStates = ['default', 'open'];/** setState() configs per state. */export interface StartMenuStateConfigs { /** Closed. */ default: {}; /** Open. */ open: { /** the search text (the items that match show) */ query?: string; };}const ITEM = '.start-menu-item';const resolve = (target) => typeof target === 'string' ? (dfDollar('#' + CSS.escape(target)).get(0) ?? dfDollar(target).get(0)) : target;const labelOf = (i: Element): string => (dfDollar(i).find('.start-menu-label').get(0)?.textContent ?? i.textContent ?? '').replace(/\s+/g, ' ').trim();const valueOf = (i: HTMLElement): string => i.dataset.value ?? labelOf(i);/** The items the reader can reach now: in the open menu or an open folder, shown, not a folder of the results. */const reachable = (menu: HTMLElement): HTMLElement[] => dfDollar(menu) .find<HTMLElement>(ITEM) .toArray() .filter((i) => i.checkVisibility());/** The markup of a state: the search text. 'open' itself lives in the top layer (:popover-open). */function applyMarkup(menu, _stateName, query = '') { dfDollar(menu) .find('.start-menu-search input') .attr('value', query || null);}/** Filters every item (folders' contents too) by the search text; folders close while it searches. */function filter(menu: HTMLElement, q: string) { const query = q.trim().toLowerCase(); menu.toggleAttribute('data-searching', !!query); const all = dfDollar(menu).find<HTMLElement>(ITEM).toArray(); for (const i of all) { if (i.hasAttribute('aria-haspopup')) continue; i.toggleAttribute('data-match', !!query && labelOf(i).toLowerCase().includes(query)); } if (query) for (const sub of dfDollar(menu).find<HTMLElement>('.start-menu-sub').toArray()) if (sub.matches(':popover-open')) sub.hidePopover(); const empty = dfDollar(menu).find('.start-menu-empty').get(0) as HTMLElement | undefined; if (empty) empty.hidden = !query || all.some((i) => i.hasAttribute('data-match'));}function triggerStateChange(menu, stateName, config) { const input = dfDollar(menu).find('.start-menu-search input').get(0) as HTMLInputElement | undefined; if (stateName === 'open') { if (!menu.matches(':popover-open')) menu.showPopover(); if (input && config.query !== undefined && input.value !== config.query) { input.value = config.query; filter(menu, config.query); } } else if (menu.matches(':popover-open')) menu.hidePopover(); applyMarkup(menu, stateName, input?.value ?? '');}/** Registry-level API; pass the .start-menu element explicitly. Unknown names throw. */export const startMenuApi = componentState({ component: 'start-menu', states: startMenuStates, events: ['toggle', 'input'], apply: (menu, state) => triggerStateChange(menu, state.name, state.config), read: (menu) => { const q = (dfDollar(menu).find('.start-menu-search input').get(0) as HTMLInputElement | undefined)?.value ?? ''; return menu.matches(':popover-open') ? { name: 'open', config: q ? { query: q } : {} } : { name: 'default', config: {} }; }, markup: (el, state) => applyMarkup(el, state.name, (state.config.query as string | undefined) ?? ''),});df$.startMenuApi = startMenuApi;df$.startMenuStates = startMenuStates;/** The folder popover an item opens (aria-controls), anchored beside it. */function openFolder(item: HTMLElement, focusFirst: boolean) { const sub = byId(item.getAttribute('aria-controls') ?? ''); if (!sub) return; // close the folders open beside this one (same level) const level = item.closest('.start-menu-sub, .start-menu'); for (const other of dfDollar(level).find<HTMLElement>(':scope [aria-haspopup][aria-expanded="true"]').toArray()) if (other !== item && other.closest('.start-menu-sub, .start-menu') === level) closeFolder(other); const name = `--start-menu-${item.getAttribute('aria-controls')}`; item.style.setProperty('anchor-name', name); sub.style.setProperty('position-anchor', name); if (!sub.matches(':popover-open')) sub.showPopover(); item.setAttribute('aria-expanded', 'true'); if (focusFirst) reachable(sub)[0]?.focus();}function closeFolder(item: HTMLElement) { const sub = byId(item.getAttribute('aria-controls') ?? ''); if (sub?.matches(':popover-open')) sub.hidePopover(); item.setAttribute('aria-expanded', 'false');}function pick(menu: HTMLElement, item: HTMLElement) { if (item.hasAttribute('aria-haspopup')) return openFolder(item, true); // Fires when an item is picked - its value and label; the menu closes. menu.dispatchEvent( new CustomEvent<StartSelectDetail>('start-select', { bubbles: true, detail: { value: valueOf(item), label: labelOf(item) }, }), ); startMenuApi.setState(menu, 'default', {});}function bind(menu: HTMLElement) { const input = dfDollar(menu).find('.start-menu-search input').get(0) as HTMLInputElement | undefined; menu.addEventListener('toggle', (e: Event) => { const open = (e as ToggleEvent).newState === 'open'; for (const b of dfDollar(`[popovertarget="${CSS.escape(menu.id)}"]`).toArray()) b.setAttribute('aria-expanded', String(open)); if (open) { if (input?.checkVisibility()) input.focus(); else reachable(menu)[0]?.focus(); } else { for (const f of dfDollar(menu).find<HTMLElement>('[aria-haspopup][aria-expanded="true"]').toArray()) closeFolder(f); // the search ends with the menu - also when the page cleared the field first if (input) { input.value = ''; filter(menu, ''); } } }); input?.addEventListener('input', () => filter(menu, input.value)); menu.addEventListener('click', (e) => { const item = (e.target as Element).closest(ITEM) as HTMLElement | null; if (item && !item.hasAttribute('disabled')) pick(menu, item); }); // folders open on hover too, like the classic menu menu.addEventListener('pointerover', (e) => { if ((e as PointerEvent).pointerType !== 'mouse') return; const item = (e.target as Element).closest(ITEM) as HTMLElement | null; if (!item) return; if (item.hasAttribute('aria-haspopup')) openFolder(item, false); else { const level = item.closest('.start-menu-sub, .start-menu'); for (const f of dfDollar(level).find<HTMLElement>('[aria-haspopup][aria-expanded="true"]').toArray()) if (f.closest('.start-menu-sub, .start-menu') === level) closeFolder(f); } }); menu.addEventListener('keydown', (e) => { const items = reachable(menu); const cur = (e.target as Element).closest(ITEM) as HTMLElement | null; if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); // within the level the focus is on (a folder's own items), else the whole menu const level = cur?.closest('.start-menu-sub') ?? null; const list = level ? items.filter((i) => i.closest('.start-menu-sub') === level) : items.filter((i) => !i.closest('.start-menu-sub')); const k = cur ? list.indexOf(cur) : -1; const next = list[(k + (e.key === 'ArrowDown' ? 1 : -1) + list.length) % list.length]; next?.focus(); return; } if (e.key === 'ArrowRight' && cur?.hasAttribute('aria-haspopup')) { e.preventDefault(); openFolder(cur, true); return; } if (e.key === 'ArrowLeft' && cur?.closest('.start-menu-sub')) { e.preventDefault(); const sub = cur.closest('.start-menu-sub') as HTMLElement; const opener = dfDollar(menu) .find<HTMLElement>(`[aria-controls="${CSS.escape(sub.id)}"]`) .get(0); if (opener) { closeFolder(opener); opener.focus(); } return; } if (e.key === 'Enter' && e.target === input) { e.preventDefault(); const first = items.find((i) => i.hasAttribute('data-match')); if (first) pick(menu, first); return; } if (e.key === 'Escape' && cur?.closest('.start-menu-sub')) { e.preventDefault(); e.stopPropagation(); const sub = cur.closest('.start-menu-sub') as HTMLElement; const opener = dfDollar(menu) .find<HTMLElement>(`[aria-controls="${CSS.escape(sub.id)}"]`) .get(0); if (opener) { closeFolder(opener); opener.focus(); } return; } // typing anywhere in the menu searches if (input?.checkVisibility() && e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey && e.target !== input) { input.focus(); } });}/** * Open the menu (with a search text). * @param target - the .start-menu element, its id or a selector * @param query - the text to search for ('' shows everything) * @returns the menu, null when the target matches none */const openMenu = (target: string | HTMLElement, query: string = ''): HTMLElement | null => { const m = resolve(target); if (m) startMenuApi.setState(m, 'open', { query }); return m;};/** * Close the menu. * @param target - the .start-menu element, its id or a selector * @returns the menu, null when the target matches none */const closeMenu = (target: string | HTMLElement): HTMLElement | null => { const m = resolve(target); if (m) startMenuApi.setState(m, 'default', {}); return m;};/** * Open it when closed, close it when open. * @param target - the .start-menu element, its id or a selector * @returns whether it is open now */const toggleMenu = (target: string | HTMLElement): boolean => { const m = resolve(target); if (!m) return false; const opening = !m.matches(':popover-open'); startMenuApi.setState(m, opening ? 'open' : 'default', opening ? { query: '' } : {}); return opening;};/** df$.shadcn.startMenu - open, close and toggle a start menu. */export const startMenuActions = { open: openMenu, close: closeMenu, toggle: toggleMenu };df$.startMenu = startMenuActions;function init() { dfDollar('.start-menu[popover]:not([data-init])') .toArray() .forEach((menu) => { menu.dataset.init = ''; for (const f of dfDollar(menu).find<HTMLElement>(`${ITEM}[aria-controls]`).toArray()) { f.setAttribute('aria-haspopup', 'menu'); if (!f.hasAttribute('aria-expanded')) f.setAttribute('aria-expanded', 'false'); } // the menu opens at its Start Button (any [popovertarget] naming it) const name = `--start-menu-${menu.id}`; menu.style.setProperty('position-anchor', name); for (const b of dfDollar(`[popovertarget="${CSS.escape(menu.id)}"]`).toArray()) { b.style.setProperty('anchor-name', name); b.setAttribute('aria-expanded', 'false'); } bind(menu); // el.store + el.api (AGENTS.md "State through stores") bindComponent(menu, startMenuApi); });}// Ctrl+Esc opens the start menu of the desktop the focus is in (else the first on the page), like the Windows keyif (!document.__startMenuInit) { document.__startMenuInit = true; document.addEventListener('keydown', (e) => { if (e.key !== 'Escape' || !e.ctrlKey) return; // the nearest menu around the focus: the desktop the reader is in let menu: HTMLElement | undefined; for (let p = document.activeElement as Element | null; p && !menu; p = p.parentElement) menu = dfDollar(p).find<HTMLElement>('.start-menu[popover]').get(0); menu ??= dfDollar<HTMLElement>('.start-menu[popover]').get(0); if (!menu) return; e.preventDefault(); toggleMenu(menu); });}init();new MutationObserver(init).observe(document, { childList: true, subtree: true });Comments, ideas or improvements? Edit this page's source on GitHub