feat(ui): the Ctrl+K command palette — P1-D
UI-SPEC §1 called this a signature move and PRD P1-5 has listed it since the start.
Frontend only: every action already exists as a store action, so no IPC command, no
Rust, no capability change.
`Ctrl+K` collided with nothing and was a **silent no-op** — `App.tsx` parses `e.key`
as a number, so `'k'` became NaN and `NAV_KEYS[NaN]` was undefined. The branch sits
*after* the guard-and-panel bail, which makes both refusals structural rather than
remembered: the palette cannot open while a plan owns the content area, while the
guard dialog is up, or behind the legal gate including About's review mode. A palette
that could navigate during an execution is the defect S3 shipped, through a different
door. Verified in the browser: behind a re-opened gate, Ctrl+K and Ctrl+3 both do
nothing, and the palette works again once it closes.
**Its own matcher, twenty lines, not `index_search`.** That command searches 864,000
PyPI package names over IPC — the wrong corpus and the wrong cost for nineteen
actions. What is taken from `index/mod.rs` is the ranking philosophy SP-3 paid for:
tiered, not score-ordered, because a raw fuzzy score rewards density and puts
`requests-ntlm` above `requests`.
**A ranking flaw the tests caught.** Matching one flat `"${group} ${label}"` string
ranked *Download the index* — group "Search", so a prefix match — above the Search
tab itself, whose label matched only as a subsequence of `go to search`. Someone
typing a screen's name wants the screen. Primary and secondary text now score
separately, with a gap wider than any tier, so every label match beats every group
match. Confirmed in the running app.
Not built on `PdDialog` — it hardcodes a heading and a Cancel-first row for
destructive confirms, the opposite of a filter list — but its `showModal()` pattern
is lifted whole, including the `if (!el.open)` guard that exists for StrictMode. It
*does* dismiss on backdrop click, which `PdDialog` argues against and is right to for
a confirm; nothing here is destructive on its own.
A listbox with `aria-activedescendant` rather than tab stops, so the input keeps
focus while the arrows move the selection — which is what lets someone keep typing to
narrow. `aria-selected` is also what survives Windows high-contrast mode, where the
tint is erased and `styles.css` outlines the selected row instead.
20 tests across the matcher and the palette.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0b02bbde1e
commit
ef9f4f5016
7 files changed
+587
-1
No files matched your search
+28
-1
@@ -1,9 +1,10 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { NAV_KEYS } from '@/components/nav'
|
||||
import { PdLegalGate } from '@/components/PdLegalGate'
|
||||
import { PdOfflineBanner } from '@/components/PdOfflineBanner'
|
||||
import { PdPalette } from '@/components/PdPalette'
|
||||
import { PdSidebar } from '@/components/PdSidebar'
|
||||
import { PdStatusLine } from '@/components/PdStatusLine'
|
||||
import { PdUninstallDialog } from '@/components/PdUninstallDialog'
|
||||
@@ -65,6 +66,8 @@ export function App() {
|
||||
const resetPlan = usePlanStore((s) => s.reset)
|
||||
const guardOpen = planPhase === 'guard' && guard !== null
|
||||
const mainRef = useRef<HTMLElement>(null)
|
||||
// Shell state, like `nav` — but local, because nothing outside this component reads it.
|
||||
const [paletteOpen, setPaletteOpen] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
void checkConsent()
|
||||
@@ -99,6 +102,20 @@ export function App() {
|
||||
// guarded neither. The sidebar was disabled and the panel kept rendering, so nothing looked
|
||||
// wrong until the plan finished and dropped the user on a tab they never chose.
|
||||
if (guardOpen || PANEL_PHASES.has(planPhase)) return
|
||||
|
||||
// UI-SPEC §1's Ctrl+K palette. Before the Ctrl+digit branch below, which parses `e.key` as a
|
||||
// number — `'k'` becomes NaN and `NAV_KEYS[NaN]` is undefined, so this was a silent no-op
|
||||
// rather than a collision. `toLowerCase`, because Shift+Ctrl+K reports `'K'`.
|
||||
//
|
||||
// It inherits both refusals above by construction: this line is unreachable while the legal
|
||||
// gate is up, while the guard dialog is open, or while a plan owns the content area — which
|
||||
// is the point. A palette that can navigate during an execution is the defect S3 shipped,
|
||||
// reached through a different door.
|
||||
if (e.ctrlKey && !e.altKey && !e.metaKey && e.key.toLowerCase() === 'k') {
|
||||
e.preventDefault()
|
||||
setPaletteOpen((open) => !open)
|
||||
return
|
||||
}
|
||||
// UI-SPEC §8: `/` focuses search. Guarded against text fields, or it would be impossible to
|
||||
// type a slash into a version specifier.
|
||||
const target = e.target as HTMLElement | null
|
||||
@@ -174,6 +191,16 @@ export function App() {
|
||||
|
||||
<PdStatusLine />
|
||||
|
||||
{/* Outside <main> for `PdUninstallDialog`'s reason: it opens over whatever screen is
|
||||
showing, and mounting it inside one would tie it to that screen's lifetime. */}
|
||||
{paletteOpen ? (
|
||||
<PdPalette
|
||||
onClose={() => {
|
||||
setPaletteOpen(false)
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{/* Outside <main>, because the dialog opens *over* the table the user selected from — they
|
||||
need to still see what they picked while deciding. Mounted here rather than in the row
|
||||
that opened it: `PdPackageTable` renders a ~25-row window, so scrolling would unmount
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* The command palette.
|
||||
*
|
||||
* `setup.ts` stubs `showModal` by setting `open` and nothing else — no top layer, no focus
|
||||
* containment, no native `cancel` on Escape. So modality is **not** under test here; what is
|
||||
* tested is the policy on top: what filtering shows, what Enter dispatches, and that dispatching
|
||||
* closes before it acts.
|
||||
*/
|
||||
|
||||
import { fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { PdPalette } from '@/components/PdPalette'
|
||||
import { useEnvStore, useLegalStore, useUiStore } from '@/stores'
|
||||
import { resetStore } from '@/test/stores'
|
||||
|
||||
vi.mock('@/ipc', async () => {
|
||||
const { ipcMock } = await import('@/test/ipc')
|
||||
return ipcMock()
|
||||
})
|
||||
|
||||
function open() {
|
||||
const onClose = vi.fn()
|
||||
render(<PdPalette onClose={onClose} />)
|
||||
return { onClose, input: screen.getByRole('combobox') }
|
||||
}
|
||||
|
||||
const options = () => within(screen.getByRole('listbox')).getAllByRole('option')
|
||||
|
||||
describe('PdPalette', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
resetStore(useUiStore)
|
||||
resetStore(useEnvStore)
|
||||
resetStore(useLegalStore)
|
||||
})
|
||||
|
||||
it('opens showing every action rather than an empty list', () => {
|
||||
open()
|
||||
// Nine tabs plus the rest. The exact number is not the point; that it is not zero is.
|
||||
expect(options().length).toBeGreaterThan(9)
|
||||
})
|
||||
|
||||
it('filters as you type, and ranks the exact match first', () => {
|
||||
const { input } = open()
|
||||
fireEvent.change(input, { target: { value: 'pins' } })
|
||||
expect(options()[0]).toHaveTextContent('Pins')
|
||||
})
|
||||
|
||||
it('navigates with the arrows while the input keeps focus', () => {
|
||||
// The reason this is a listbox with aria-activedescendant rather than a set of tab stops: the
|
||||
// user must be able to keep typing to narrow while moving through what is left.
|
||||
const { input } = open()
|
||||
expect(options()[0]).toHaveAttribute('aria-selected', 'true')
|
||||
|
||||
fireEvent.keyDown(input, { key: 'ArrowDown' })
|
||||
expect(options()[0]).toHaveAttribute('aria-selected', 'false')
|
||||
expect(options()[1]).toHaveAttribute('aria-selected', 'true')
|
||||
expect(input).toHaveFocus()
|
||||
|
||||
fireEvent.keyDown(input, { key: 'ArrowUp' })
|
||||
expect(options()[0]).toHaveAttribute('aria-selected', 'true')
|
||||
})
|
||||
|
||||
it('will not run off either end of the list', () => {
|
||||
const { input } = open()
|
||||
fireEvent.keyDown(input, { key: 'ArrowUp' })
|
||||
expect(options()[0]).toHaveAttribute('aria-selected', 'true')
|
||||
})
|
||||
|
||||
it('dispatches the highlighted action on Enter, and closes first', () => {
|
||||
const { input, onClose } = open()
|
||||
fireEvent.change(input, { target: { value: 'health' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
// Closing before running is what stops an action that changes `nav` fighting the dialog for
|
||||
// focus — App moves focus to the new screen's <h1> on every nav change.
|
||||
expect(useUiStore.getState().nav).toBe('health')
|
||||
})
|
||||
|
||||
it('dispatches on click too', () => {
|
||||
const { input } = open()
|
||||
fireEvent.change(input, { target: { value: 'search' } })
|
||||
fireEvent.click(options()[0] as HTMLElement)
|
||||
expect(useUiStore.getState().nav).toBe('search')
|
||||
})
|
||||
|
||||
it('reaches an action that is not a tab', () => {
|
||||
// The palette is only worth having if it does more than the sidebar already does.
|
||||
const { input } = open()
|
||||
fireEvent.change(input, { target: { value: 'documents' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
expect(useLegalStore.getState().review).toBe(true)
|
||||
})
|
||||
|
||||
it('says so when nothing matches, rather than showing an empty box', () => {
|
||||
const { input } = open()
|
||||
fireEvent.change(input, { target: { value: 'zzzzz' } })
|
||||
expect(screen.queryByRole('option')).toBeNull()
|
||||
expect(screen.getByText(/nothing matches/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('closes on Escape through its own handler', () => {
|
||||
const { onClose } = open()
|
||||
// jsdom does not synthesize the native `cancel` event, so this fires it directly — the same
|
||||
// path a real Escape takes.
|
||||
fireEvent(screen.getByRole('dialog'), new Event('cancel', { cancelable: true }))
|
||||
expect(onClose).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,248 @@
|
||||
/**
|
||||
* The command palette — `Ctrl+K`, PRD P1-5 and UI-SPEC §1's "signature move".
|
||||
*
|
||||
* Frontend only: every action it dispatches already exists as a store action, so there is no new
|
||||
* IPC command, no Rust and no capability change.
|
||||
*
|
||||
* **Not built on `PdDialog`**, which hardcodes a heading and a Cancel-first button row for
|
||||
* destructive confirms — the opposite of what a filter list wants. What is lifted from it is the
|
||||
* part worth reusing: a native `<dialog>` with `showModal()`, which brings the top layer, the
|
||||
* inert backdrop, real focus containment and `Esc` for free, plus the `if (!el.open)` guard that
|
||||
* exists because StrictMode double-invokes the mount effect.
|
||||
*
|
||||
* **It dismisses on backdrop click**, unlike `PdDialog`. That component argues the opposite and is
|
||||
* right to: a mis-click beside a dialog about to delete things must not read as consent. Nothing
|
||||
* here is destructive on its own — every action either navigates or opens something that has its
|
||||
* own confirm — so the convention wins.
|
||||
*
|
||||
* The list is a `listbox` with `aria-activedescendant`, not a set of tab stops: the input keeps
|
||||
* focus while `↑`/`↓` move the selection, which is what lets someone keep typing to narrow.
|
||||
* `aria-selected` is what makes the highlight survive Windows high-contrast mode, where the
|
||||
* `bg-surface-2` tint is erased and `styles.css`'s forced-colors block outlines the selected row
|
||||
* instead.
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { NAV_KEYS } from '@/components/nav'
|
||||
import { rank } from '@/components/match'
|
||||
import { useEnvStore, useHealthStore, useIndexStore, useLegalStore, useUiStore } from '@/stores'
|
||||
|
||||
/** One thing the palette can do. */
|
||||
interface Action {
|
||||
/** Stable, and the React key. */
|
||||
id: string
|
||||
/** Already localized. */
|
||||
label: string
|
||||
/** Shown dimmed on the right — which screen or area it belongs to. */
|
||||
group: string
|
||||
run: () => void
|
||||
}
|
||||
|
||||
export function PdPalette({ onClose }: { onClose: () => void }) {
|
||||
const { t } = useTranslation()
|
||||
const ref = useRef<HTMLDialogElement>(null)
|
||||
const [query, setQuery] = useState('')
|
||||
const [at, setAt] = useState(0)
|
||||
|
||||
const setNav = useUiStore((s) => s.setNav)
|
||||
const scan = useEnvStore((s) => s.scan)
|
||||
const loadPackages = useEnvStore((s) => s.loadPackages)
|
||||
const loadOutdated = useEnvStore((s) => s.loadOutdated)
|
||||
const takeSnapshot = useEnvStore((s) => s.takeSnapshot)
|
||||
const clearSelection = useEnvStore((s) => s.clearSelection)
|
||||
const refreshIndex = useIndexStore((s) => s.refreshIndex)
|
||||
const clearQueue = useIndexStore((s) => s.clearQueue)
|
||||
const setTab = useHealthStore((s) => s.setTab)
|
||||
const openReview = useLegalStore((s) => s.openReview)
|
||||
|
||||
const actions: Action[] = useMemo(
|
||||
() => [
|
||||
// The nine tabs. `security` has no screen and renders a placeholder, which is honest — the
|
||||
// sidebar shows it for the same reason.
|
||||
...NAV_KEYS.map((key) => ({
|
||||
id: `nav:${key}`,
|
||||
label: t(`nav.${key}`),
|
||||
group: t('palette.groups.go'),
|
||||
run: () => {
|
||||
setNav(key)
|
||||
},
|
||||
})),
|
||||
{
|
||||
id: 'env:rescan',
|
||||
label: t('actions.rescan'),
|
||||
group: t('nav.environments'),
|
||||
run: () => {
|
||||
setNav('environments')
|
||||
void scan()
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'pkg:refresh',
|
||||
label: t('palette.refreshPackages'),
|
||||
group: t('nav.installed'),
|
||||
run: () => {
|
||||
void loadPackages()
|
||||
void loadOutdated()
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'pkg:clear-selection',
|
||||
label: t('palette.clearSelection'),
|
||||
group: t('nav.installed'),
|
||||
run: clearSelection,
|
||||
},
|
||||
{
|
||||
id: 'snapshot:take',
|
||||
label: t('snapshots.take'),
|
||||
group: t('snapshots.title'),
|
||||
run: () => {
|
||||
void takeSnapshot()
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'index:refresh',
|
||||
label: t('search.refreshIndex'),
|
||||
group: t('nav.search'),
|
||||
run: () => {
|
||||
void refreshIndex()
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'index:clear-queue',
|
||||
label: t('palette.clearQueue'),
|
||||
group: t('nav.search'),
|
||||
run: clearQueue,
|
||||
},
|
||||
...(['deptry', 'vulture', 'ruff'] as const).map((tool) => ({
|
||||
id: `health:${tool}`,
|
||||
// The tool's own name, which is data and never translated (I18N §2).
|
||||
label: `${t('nav.health')}: ${tool}`,
|
||||
group: t('nav.health'),
|
||||
run: () => {
|
||||
setNav('health')
|
||||
setTab(tool)
|
||||
},
|
||||
})),
|
||||
{
|
||||
id: 'legal:review',
|
||||
label: t('about.reopen'),
|
||||
group: t('nav.about'),
|
||||
run: openReview,
|
||||
},
|
||||
],
|
||||
[
|
||||
t,
|
||||
setNav,
|
||||
scan,
|
||||
loadPackages,
|
||||
loadOutdated,
|
||||
clearSelection,
|
||||
takeSnapshot,
|
||||
refreshIndex,
|
||||
clearQueue,
|
||||
setTab,
|
||||
openReview,
|
||||
],
|
||||
)
|
||||
|
||||
const shown = useMemo(() => rank(actions, query, (a) => [a.label, a.group]), [actions, query])
|
||||
// Clamped rather than reset: narrowing the list must not silently move the selection to
|
||||
// something the user was not looking at.
|
||||
const active = Math.min(at, Math.max(0, shown.length - 1))
|
||||
|
||||
useEffect(() => {
|
||||
const el = ref.current
|
||||
// `showModal` throws when the dialog is already open, which React's double-invoked effects in
|
||||
// development make a real case rather than a theoretical one.
|
||||
if (el !== null && !el.open) el.showModal()
|
||||
return () => {
|
||||
if (el !== null && el.open) el.close()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const dispatch = (action: Action | undefined) => {
|
||||
if (action === undefined) return
|
||||
// Closed *before* running, so an action that changes `nav` does not fight the dialog for
|
||||
// focus — `App.tsx` moves focus to the new screen's `<h1>` on every nav change.
|
||||
onClose()
|
||||
action.run()
|
||||
}
|
||||
|
||||
return (
|
||||
<dialog
|
||||
ref={ref}
|
||||
aria-label={t('palette.title')}
|
||||
onCancel={(e) => {
|
||||
e.preventDefault()
|
||||
onClose()
|
||||
}}
|
||||
onClick={(e) => {
|
||||
// Backdrop only: clicks inside the panel below stop here first.
|
||||
if (e.target === ref.current) onClose()
|
||||
}}
|
||||
className="mt-24 w-full max-w-xl rounded-pd border border-border bg-surface p-0 text-text backdrop:bg-bg/80"
|
||||
>
|
||||
<div className="p-3">
|
||||
<input
|
||||
autoFocus
|
||||
type="text"
|
||||
role="combobox"
|
||||
aria-expanded="true"
|
||||
aria-controls="palette-list"
|
||||
aria-activedescendant={shown[active] === undefined ? undefined : `palette-${shown[active].id}`}
|
||||
aria-label={t('palette.title')}
|
||||
placeholder={t('palette.placeholder')}
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value)
|
||||
setAt(0)
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
setAt((i) => Math.min(i + 1, shown.length - 1))
|
||||
}
|
||||
if (e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
setAt((i) => Math.max(i - 1, 0))
|
||||
}
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
dispatch(shown[active])
|
||||
}
|
||||
}}
|
||||
className="w-full rounded-pd border border-border bg-bg px-3 py-1.5 font-mono text-data"
|
||||
/>
|
||||
|
||||
<ul id="palette-list" role="listbox" aria-label={t('palette.title')} className="mt-2 max-h-80 overflow-auto">
|
||||
{shown.map((action, i) => (
|
||||
<li
|
||||
key={action.id}
|
||||
id={`palette-${action.id}`}
|
||||
role="option"
|
||||
aria-selected={i === active}
|
||||
data-action-id={action.id}
|
||||
onClick={() => {
|
||||
dispatch(action)
|
||||
}}
|
||||
className={`flex cursor-pointer items-baseline justify-between gap-3 rounded-pd px-3 py-1.5 text-data ${
|
||||
i === active ? 'bg-surface-2 text-accent' : 'text-text'
|
||||
}`}
|
||||
>
|
||||
<span className="min-w-0 truncate">{action.label}</span>
|
||||
<span className="shrink-0 text-text-dim">{action.group}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
{shown.length === 0 ? (
|
||||
<p className="px-3 py-2 font-mono text-data text-text-dim">
|
||||
{`▸ ${t('palette.noMatch', { query })}`}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* The palette's matcher.
|
||||
*
|
||||
* The ranking rules are SP-3's, learned from nucleo putting `requests-ntlm` above `requests`: a
|
||||
* raw fuzzy score rewards density, so tiers come first and length breaks ties. These cases are
|
||||
* that finding restated over action labels.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { isSubsequence, rank } from '@/components/match'
|
||||
|
||||
const label = (s: string) => [s] as const
|
||||
|
||||
describe('isSubsequence', () => {
|
||||
it('requires order, not merely presence', () => {
|
||||
// The whole reason this is a two-pointer walk. `[...needle].every(c => hay.includes(c))` is
|
||||
// the obvious wrong implementation and would say true here.
|
||||
expect(isSubsequence('slot', 'tools')).toBe(false)
|
||||
expect(isSubsequence('tls', 'tools')).toBe(true)
|
||||
})
|
||||
|
||||
it('matches a prefix, a scattered run and the whole string', () => {
|
||||
expect(isSubsequence('too', 'tools')).toBe(true)
|
||||
expect(isSubsequence('tos', 'tools')).toBe(true)
|
||||
expect(isSubsequence('tools', 'tools')).toBe(true)
|
||||
expect(isSubsequence('toolss', 'tools')).toBe(false)
|
||||
})
|
||||
|
||||
it('is true for an empty needle', () => {
|
||||
expect(isSubsequence('', 'anything')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('rank', () => {
|
||||
it('keeps everything, in order, for an empty query', () => {
|
||||
// A palette that opens showing nothing has to be taught before it can be used.
|
||||
const items = ['Updates', 'Search', 'Pins']
|
||||
expect(rank(items, ' ', label)).toEqual(items)
|
||||
})
|
||||
|
||||
it('puts the exact match first, then the prefix, then the subsequence', () => {
|
||||
const got = rank(['Pins and things', 'Pin', 'Pins', 'Preferences in'], 'pin', label)
|
||||
expect(got.slice(0, 3)).toEqual(['Pin', 'Pins', 'Pins and things'])
|
||||
})
|
||||
|
||||
it('prefers the shorter label within a tier', () => {
|
||||
// SP-3's finding in miniature: the short thing containing the query is nearly always the
|
||||
// thing itself, and the longer ones are its variants.
|
||||
expect(rank(['Search settings', 'Search'], 'search', label)).toEqual([
|
||||
'Search',
|
||||
'Search settings',
|
||||
])
|
||||
})
|
||||
|
||||
it('is alphabetical on a full tie, so two identical queries never reorder', () => {
|
||||
expect(rank(['beta', 'alpha'], 'a', label)).toEqual(['alpha', 'beta'])
|
||||
})
|
||||
|
||||
it('drops what does not match at all', () => {
|
||||
expect(rank(['Updates', 'Health'], 'zzz', label)).toEqual([])
|
||||
})
|
||||
|
||||
it('is case-insensitive in both directions', () => {
|
||||
expect(rank(['Health'], 'HEALTH', label)).toEqual(['Health'])
|
||||
expect(rank(['HEALTH'], 'health', label)).toEqual(['HEALTH'])
|
||||
})
|
||||
|
||||
it('puts every label match above every group match', () => {
|
||||
// Found by a failing palette test. With one flat `${group} ${label}` string, typing `search`
|
||||
// ranked *Download the index* — group "Search", a prefix match — above the Search tab, whose
|
||||
// label matched only as a subsequence of `go to search`. Someone typing a screen's name wants
|
||||
// the screen, however weakly the label matched.
|
||||
const items = [
|
||||
{ label: 'Download the index', group: 'Search' },
|
||||
{ label: 'Search', group: 'Go to' },
|
||||
]
|
||||
const got = rank(items, 'search', (i) => [i.label, i.group])
|
||||
expect(got[0]?.label).toBe('Search')
|
||||
})
|
||||
|
||||
it('still finds an item by its group when no label matches', () => {
|
||||
const items = [{ label: 'Download the index', group: 'Search' }]
|
||||
expect(rank(items, 'search', (i) => [i.label, i.group])).toEqual(items)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* Ranking a short list of actions against what the user typed — the command palette's matcher.
|
||||
*
|
||||
* **Deliberately not `index_search`.** That command searches 864,000 PyPI *package names* over
|
||||
* IPC, which is the wrong corpus and the wrong cost for thirty actions; a palette that made a
|
||||
* round trip per keystroke would be slower than the thing it exists to speed up. `nucleo` is a
|
||||
* `pipdock-core` dependency and there is no JS fuzzy library, so this is twenty lines instead.
|
||||
*
|
||||
* What it *does* take from `crates/pipdock-core/src/index/mod.rs` is the ranking philosophy, which
|
||||
* was learned the hard way in SP-3: **tiered, not score-ordered.** A raw fuzzy score rewards
|
||||
* density, so a longer name containing the query densely beats the name the user actually typed —
|
||||
* nucleo ranks `requests-ntlm` above `requests`. Exact, then prefix, then subsequence; within a
|
||||
* tier, the shorter label; then alphabetical, so two identical queries never reorder.
|
||||
*/
|
||||
|
||||
/** How a candidate matched, in ranking order. Lower sorts first. */
|
||||
export const enum MatchKind {
|
||||
Exact = 0,
|
||||
Prefix = 1,
|
||||
Subsequence = 2,
|
||||
}
|
||||
|
||||
/**
|
||||
* Is `needle` a subsequence of `haystack`?
|
||||
*
|
||||
* A two-pointer walk, which is the part that is easy to get wrong: `[...needle].every(c =>
|
||||
* haystack.includes(c))` tests *presence*, not order, and would match `slot` against `tools`.
|
||||
* Both are lower-cased by the caller.
|
||||
*/
|
||||
export function isSubsequence(needle: string, haystack: string): boolean {
|
||||
let at = 0
|
||||
for (const c of haystack) {
|
||||
if (c === needle[at]) at += 1
|
||||
if (at === needle.length) return true
|
||||
}
|
||||
return at === needle.length
|
||||
}
|
||||
|
||||
/** How `haystack` matched `needle`, or null when it did not. */
|
||||
export function matchKind(needle: string, haystack: string): MatchKind | null {
|
||||
if (haystack === needle) return MatchKind.Exact
|
||||
if (haystack.startsWith(needle)) return MatchKind.Prefix
|
||||
return isSubsequence(needle, haystack) ? MatchKind.Subsequence : null
|
||||
}
|
||||
|
||||
/**
|
||||
* How much worse a match on the secondary text is than any match on the primary.
|
||||
*
|
||||
* Larger than the widest tier gap, so **every** label match outranks **every** group match. Found
|
||||
* by a test: with one flat text of `"${group} ${label}"`, typing `search` put *Download the index*
|
||||
* — group "Search", so a prefix match — above the Search tab itself, whose label matched only as a
|
||||
* subsequence of `go to search`. Someone typing a screen's name wants the screen.
|
||||
*/
|
||||
const SECONDARY = 10
|
||||
|
||||
/**
|
||||
* Rank `items` against `query`, keeping only what matches.
|
||||
*
|
||||
* `text` returns the primary label and, optionally, a secondary the item may also be found by —
|
||||
* its group. A match on the primary always beats a match on the secondary, whatever the tiers.
|
||||
*
|
||||
* An empty query keeps everything in its original order — a palette that opens showing nothing is
|
||||
* a palette that has to be taught before it can be used.
|
||||
*/
|
||||
export function rank<T>(
|
||||
items: readonly T[],
|
||||
query: string,
|
||||
text: (item: T) => readonly [primary: string, secondary?: string],
|
||||
): T[] {
|
||||
const needle = query.trim().toLowerCase()
|
||||
if (needle === '') return [...items]
|
||||
|
||||
return items
|
||||
.map((item) => {
|
||||
const [primary, secondary] = text(item)
|
||||
const label = primary.toLowerCase()
|
||||
const direct = matchKind(needle, label)
|
||||
if (direct !== null) return { item, label, score: direct }
|
||||
const via = secondary === undefined ? null : matchKind(needle, secondary.toLowerCase())
|
||||
return via === null ? null : { item, label, score: via + SECONDARY }
|
||||
})
|
||||
.filter((r): r is { item: T; label: string; score: number } => r !== null)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
a.score - b.score ||
|
||||
// The shorter label, because a short one containing the query is nearly always the thing
|
||||
// itself and the longer ones are its variants.
|
||||
a.label.length - b.label.length ||
|
||||
a.label.localeCompare(b.label),
|
||||
)
|
||||
.map((r) => r.item)
|
||||
}
|
||||
@@ -165,6 +165,17 @@
|
||||
"checkFinding": "{{pkg}} requires {{requirement}}",
|
||||
"done": "Back to packages"
|
||||
},
|
||||
"palette": {
|
||||
"title": "Commands",
|
||||
"placeholder": "Type a command…",
|
||||
"noMatch": "nothing matches “{{query}}”",
|
||||
"refreshPackages": "Refresh the package list",
|
||||
"clearSelection": "Clear the selection",
|
||||
"clearQueue": "Empty the install queue",
|
||||
"groups": {
|
||||
"go": "Go to"
|
||||
}
|
||||
},
|
||||
"pins": {
|
||||
"empty": "no pins in this environment",
|
||||
"emptyHint": "Pin a package from the Installed table to keep bulk updates away from it.",
|
||||
|
||||
@@ -158,6 +158,17 @@
|
||||
"checkFinding": "{{pkg}} yêu cầu {{requirement}}",
|
||||
"done": "Quay lại danh sách gói"
|
||||
},
|
||||
"palette": {
|
||||
"title": "Lệnh",
|
||||
"placeholder": "Gõ tên một lệnh…",
|
||||
"noMatch": "không có lệnh nào khớp “{{query}}”",
|
||||
"refreshPackages": "Tải lại danh sách gói",
|
||||
"clearSelection": "Bỏ chọn tất cả",
|
||||
"clearQueue": "Xoá hàng đợi cài đặt",
|
||||
"groups": {
|
||||
"go": "Đi tới"
|
||||
}
|
||||
},
|
||||
"pins": {
|
||||
"empty": "môi trường này chưa có gói nào được ghim",
|
||||
"emptyHint": "Ghim một gói từ bảng Đã cài để các lần cập nhật hàng loạt bỏ qua nó.",
|
||||
|
||||
Reference in new issue
Block a user