feat(ui): Search, the dock bay, and the offline chip
UI-SPEC §4's Search screen. `useIndexStore`, `PdDockBay` and `PdOfflineBanner` — 16 of 16 components in §6's inventory now exist. Three things live in the store rather than the component, and all three are consequences of the < 50 ms budget rather than preferences: - **The previous result set stays rendered** while a new query is in flight. Blanking the list on every keystroke is what makes a fast search feel slow. - **Responses are sequenced.** Two searches can be in flight and can return out of order; without a sequence number the older one wins and the list contradicts the field. This is the kind of bug that shows up only under a fast typist on a slow day. - **A 16 ms debounce** — one frame. It is a coalescer, not a delay: the first keystroke after a pause searches immediately. Anything longer is felt on a budget this tight. Already-installed packages show `INSTALLED` or `UPDATE` instead of an [Add] button (DATA-FLOW §4), which is what stops the most common mistake — queueing something you already have. An empty version field in the dock bay means *latest*, which is exactly what a `PlanRequest` with no specifier means, so the common case needs no typing. The offline chip is deliberately not a blocking state: search is served from the local index and keeps working, so greying the app out would claim more than is true. `navigator.onLine` reports whether an interface is up, not whether PyPI is reachable, so it explains a failure rather than gating an attempt. `/` focuses Search (UI-SPEC §8), guarded against text fields — otherwise a slash could not be typed into a version specifier. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3d1e13bbbb
commit
30146b02d7
9 files changed
+631
-2
No files matched your search
+16
-1
@@ -3,11 +3,13 @@ import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { NAV_KEYS } from '@/components/nav'
|
||||
import { PdLegalGate } from '@/components/PdLegalGate'
|
||||
import { PdOfflineBanner } from '@/components/PdOfflineBanner'
|
||||
import { PdSidebar } from '@/components/PdSidebar'
|
||||
import { PdStatusLine } from '@/components/PdStatusLine'
|
||||
import type { NavKey } from '@/components/nav'
|
||||
import { PdEnvironments } from '@/screens/PdEnvironments'
|
||||
import { PdPackages } from '@/screens/PdPackages'
|
||||
import { PdSearch } from '@/screens/PdSearch'
|
||||
import { PdSettings } from '@/screens/PdSettings'
|
||||
import { useEnvStore, useLegalStore, useUiStore } from '@/stores'
|
||||
|
||||
@@ -20,6 +22,7 @@ const SCREENS: Partial<Record<NavKey, React.ReactNode>> = {
|
||||
environments: <PdEnvironments />,
|
||||
installed: <PdPackages mode="installed" />,
|
||||
updates: <PdPackages mode="updates" />,
|
||||
search: <PdSearch />,
|
||||
settings: <PdSettings />,
|
||||
}
|
||||
|
||||
@@ -44,6 +47,17 @@ export function App() {
|
||||
// UI-SPEC §8: Ctrl+1..8 select tabs, positionally over NAV_KEYS.
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
// 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
|
||||
const typing =
|
||||
target?.tagName === 'INPUT' || target?.tagName === 'TEXTAREA' || target?.isContentEditable
|
||||
if (e.key === '/' && !e.ctrlKey && !e.altKey && !e.metaKey && typing !== true) {
|
||||
e.preventDefault()
|
||||
setNav('search')
|
||||
return
|
||||
}
|
||||
|
||||
if (!e.ctrlKey || e.altKey || e.metaKey) return
|
||||
const index = Number.parseInt(e.key, 10) - 1
|
||||
const key = NAV_KEYS[index]
|
||||
@@ -69,7 +83,8 @@ export function App() {
|
||||
<div className="flex h-full flex-col bg-bg text-text">
|
||||
<header className="flex items-center justify-between border-b border-border px-4 py-2">
|
||||
<span className="font-mono text-accent">{t('app.name')}</span>
|
||||
<span className="font-mono text-data text-text-dim">
|
||||
<span className="flex items-center gap-2 font-mono text-data text-text-dim">
|
||||
<PdOfflineBanner />
|
||||
{selected ?? t('status.noEnvironment')}
|
||||
</span>
|
||||
</header>
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* The install queue — UI-SPEC §4's **dock bay**.
|
||||
*
|
||||
* "Docks along the right edge as a slim column of added packages with editable version fields and
|
||||
* `Install (n)`." It persists across searches on purpose: adding four packages should be four
|
||||
* searches and one install, not four installs.
|
||||
*
|
||||
* An empty version field means *latest*, which is exactly what a `PlanRequest` with no specifier
|
||||
* means — so the common case needs no typing, and the field is there for the case that does.
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import type { QueuedPackage } from '@/stores/index-search'
|
||||
|
||||
interface PdDockBayProps {
|
||||
queue: readonly QueuedPackage[]
|
||||
onVersionChange: (name: string, version: string) => void
|
||||
onRemove: (name: string) => void
|
||||
onInstall: () => void
|
||||
/** Disabled without a selected environment — there would be nowhere to install to. */
|
||||
canInstall: boolean
|
||||
}
|
||||
|
||||
export function PdDockBay({
|
||||
queue,
|
||||
onVersionChange,
|
||||
onRemove,
|
||||
onInstall,
|
||||
canInstall,
|
||||
}: PdDockBayProps) {
|
||||
const { t } = useTranslation()
|
||||
|
||||
if (queue.length === 0) return null
|
||||
|
||||
return (
|
||||
<aside
|
||||
aria-label={t('search.dockBay')}
|
||||
className="flex w-64 shrink-0 flex-col border-l border-border bg-surface"
|
||||
>
|
||||
<h2 className="shrink-0 border-b border-border px-3 py-2 text-data text-text-dim">
|
||||
{t('search.dockBay')}
|
||||
</h2>
|
||||
|
||||
<ul className="min-h-0 flex-1 space-y-1 overflow-auto p-2">
|
||||
{queue.map((item) => (
|
||||
<li key={item.name} data-queued={item.name} className="rounded-pd bg-surface-2 p-2">
|
||||
<div className="flex items-baseline justify-between gap-2">
|
||||
<code className="min-w-0 truncate font-mono text-data">{item.name}</code>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onRemove(item.name)
|
||||
}}
|
||||
aria-label={t('search.remove', { pkg: item.name })}
|
||||
className="shrink-0 text-data text-text-dim"
|
||||
>
|
||||
{'✕'}
|
||||
</button>
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
value={item.version}
|
||||
onChange={(e) => {
|
||||
onVersionChange(item.name, e.target.value)
|
||||
}}
|
||||
// Empty is the common case and already means latest, so the placeholder says so
|
||||
// rather than leaving the field looking unfinished.
|
||||
placeholder={t('search.latest')}
|
||||
aria-label={t('search.versionFor', { pkg: item.name })}
|
||||
className="mt-1 w-full rounded-pd border border-border bg-bg px-2 py-0.5 font-mono text-data"
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<div className="shrink-0 border-t border-border p-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onInstall}
|
||||
disabled={!canInstall}
|
||||
title={canInstall ? undefined : t('search.noEnvironment')}
|
||||
className="w-full rounded-pd border border-accent px-3 py-1 text-data text-accent disabled:border-border disabled:text-text-dim disabled:opacity-40"
|
||||
>
|
||||
{t('search.install', { count: queue.length })}
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* The offline chip — UI-SPEC §7: "banner chip in top bar; search works (local index), metadata
|
||||
* panel shows cached-at timestamp".
|
||||
*
|
||||
* Deliberately **not** a blocking state. Search is served from a local index and keeps working;
|
||||
* only the things that genuinely need the network stop. A banner that greyed the app out would be
|
||||
* claiming more than is true.
|
||||
*
|
||||
* `navigator.onLine` is the only signal available in a webview, and it is a weak one — it reports
|
||||
* whether an interface is up, not whether PyPI is reachable. So it is treated as a hint that
|
||||
* explains a failure the user is already seeing, never as a gate on trying.
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
/** True when the OS says there is no connection. Not exported: the banner is its only reader,
|
||||
* and exporting it from a component file breaks fast refresh. */
|
||||
function useOnline(): boolean {
|
||||
const [online, setOnline] = useState(() => navigator.onLine)
|
||||
|
||||
useEffect(() => {
|
||||
const up = () => {
|
||||
setOnline(true)
|
||||
}
|
||||
const down = () => {
|
||||
setOnline(false)
|
||||
}
|
||||
window.addEventListener('online', up)
|
||||
window.addEventListener('offline', down)
|
||||
return () => {
|
||||
window.removeEventListener('online', up)
|
||||
window.removeEventListener('offline', down)
|
||||
}
|
||||
}, [])
|
||||
|
||||
return online
|
||||
}
|
||||
|
||||
export function PdOfflineBanner() {
|
||||
const { t } = useTranslation()
|
||||
const online = useOnline()
|
||||
|
||||
if (online) return null
|
||||
|
||||
return (
|
||||
<span
|
||||
role="status"
|
||||
title={t('search.offlineDetail')}
|
||||
className="rounded-pd bg-warn/20 px-2 py-0.5 text-data text-warn"
|
||||
>
|
||||
{t('search.offline')}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { NAV_KEYS, type NavKey } from '@/components/nav'
|
||||
import { useEnvStore, useUiStore } from '@/stores'
|
||||
|
||||
/** Tabs whose screens land in a later milestone. Kept in place, not hidden. */
|
||||
const NOT_YET: readonly NavKey[] = ['search', 'pins', 'health', 'security']
|
||||
const NOT_YET: readonly NavKey[] = ['pins', 'health', 'security']
|
||||
|
||||
/**
|
||||
* The sidebar — UI-SPEC §3 and §8.
|
||||
|
||||
@@ -153,6 +153,35 @@
|
||||
"checkFinding": "{{pkg}} requires {{requirement}}",
|
||||
"done": "Back to packages"
|
||||
},
|
||||
"search": {
|
||||
"title": "Search",
|
||||
"placeholder": "Search PyPI…",
|
||||
"warming": "Preparing the package index…",
|
||||
"searching": "Searching…",
|
||||
"indexMissing": "The package index has not been downloaded yet.",
|
||||
"refreshIndex": "Download the index",
|
||||
"refreshing": "Downloading…",
|
||||
"noResults": "nothing matches “{{query}}”",
|
||||
"noResultsHint": "Check the spelling, or refresh the index if the package is new.",
|
||||
"installed": "INSTALLED",
|
||||
"add": "Add",
|
||||
"queued": "Queued",
|
||||
"dockBay": "To install",
|
||||
"latest": "latest",
|
||||
"versionFor": "Version for {{pkg}}",
|
||||
"remove": "Remove {{pkg}} from the queue",
|
||||
"install_one": "Install {{count}} package",
|
||||
"install_other": "Install {{count}} packages",
|
||||
"noEnvironment": "Pick an environment first.",
|
||||
"requiresPython": "Needs Python {{spec}}",
|
||||
"freshness": {
|
||||
"fresh": "just fetched",
|
||||
"cached": "cached",
|
||||
"stale": "cached — could not refresh"
|
||||
},
|
||||
"offline": "OFFLINE",
|
||||
"offlineDetail": "No connection. Search still works from the local index; installing and metadata do not."
|
||||
},
|
||||
"settings": {
|
||||
"title": "Settings",
|
||||
"engine": "Engine",
|
||||
|
||||
@@ -146,6 +146,34 @@
|
||||
"checkFinding": "{{pkg}} yêu cầu {{requirement}}",
|
||||
"done": "Quay lại danh sách gói"
|
||||
},
|
||||
"search": {
|
||||
"title": "Tìm kiếm",
|
||||
"placeholder": "Tìm trên PyPI…",
|
||||
"warming": "Đang chuẩn bị danh mục gói…",
|
||||
"searching": "Đang tìm…",
|
||||
"indexMissing": "Danh mục gói chưa được tải về.",
|
||||
"refreshIndex": "Tải danh mục",
|
||||
"refreshing": "Đang tải…",
|
||||
"noResults": "không có gì khớp “{{query}}”",
|
||||
"noResultsHint": "Hãy kiểm tra chính tả, hoặc tải lại danh mục nếu gói này mới.",
|
||||
"installed": "ĐÃ CÀI",
|
||||
"add": "Thêm",
|
||||
"queued": "Đã thêm",
|
||||
"dockBay": "Sẽ cài",
|
||||
"latest": "mới nhất",
|
||||
"versionFor": "Phiên bản cho {{pkg}}",
|
||||
"remove": "Bỏ {{pkg}} khỏi danh sách",
|
||||
"install_other": "Cài {{count}} gói",
|
||||
"noEnvironment": "Hãy chọn một môi trường trước.",
|
||||
"requiresPython": "Cần Python {{spec}}",
|
||||
"freshness": {
|
||||
"fresh": "vừa tải",
|
||||
"cached": "đã lưu",
|
||||
"stale": "đã lưu — không làm mới được"
|
||||
},
|
||||
"offline": "NGOẠI TUYẾN",
|
||||
"offlineDetail": "Không có kết nối. Tìm kiếm vẫn chạy từ danh mục cục bộ; cài đặt và metadata thì không."
|
||||
},
|
||||
"settings": {
|
||||
"title": "Cài đặt",
|
||||
"engine": "Bộ máy",
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
/**
|
||||
* Search — UI-SPEC §4, and the screen the < 50 ms keystroke budget belongs to.
|
||||
*
|
||||
* "Search field autofocused; results stream under 50 ms per keystroke from the local index. Result
|
||||
* row: name · summary · latest · `INSTALLED ✓`/`UPDATE` chip when applicable · **[Add]**."
|
||||
*
|
||||
* The already-installed chips are the reason this screen reads `useEnvStore`: DATA-FLOW §4 says a
|
||||
* package already present shows its state instead of an [Add] button, which stops the most common
|
||||
* mistake — queueing something you already have.
|
||||
*/
|
||||
|
||||
import { useEffect, useMemo, useRef } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { PdBadge } from '@/components/PdBadge'
|
||||
import { PdDockBay } from '@/components/PdDockBay'
|
||||
import { PdEmptyState } from '@/components/PdEmptyState'
|
||||
import { PdErrorRow } from '@/components/PdErrorRow'
|
||||
import { useEnvStore, usePlanStore } from '@/stores'
|
||||
import { queueSpecs, useIndexStore } from '@/stores/index-search'
|
||||
|
||||
export function PdSearch() {
|
||||
const { t } = useTranslation()
|
||||
const field = useRef<HTMLInputElement>(null)
|
||||
|
||||
const query = useIndexStore((s) => s.query)
|
||||
const hits = useIndexStore((s) => s.hits)
|
||||
const ready = useIndexStore((s) => s.ready)
|
||||
const unavailable = useIndexStore((s) => s.unavailable)
|
||||
const searching = useIndexStore((s) => s.searching)
|
||||
const error = useIndexStore((s) => s.error)
|
||||
const selected = useIndexStore((s) => s.selected)
|
||||
const meta = useIndexStore((s) => s.meta)
|
||||
const metaFreshness = useIndexStore((s) => s.metaFreshness)
|
||||
const queue = useIndexStore((s) => s.queue)
|
||||
const refreshing = useIndexStore((s) => s.refreshing)
|
||||
|
||||
const setQuery = useIndexStore((s) => s.setQuery)
|
||||
const select = useIndexStore((s) => s.select)
|
||||
const enqueue = useIndexStore((s) => s.enqueue)
|
||||
const setQueuedVersion = useIndexStore((s) => s.setQueuedVersion)
|
||||
const dequeue = useIndexStore((s) => s.dequeue)
|
||||
const clearQueue = useIndexStore((s) => s.clearQueue)
|
||||
const refreshIndex = useIndexStore((s) => s.refreshIndex)
|
||||
|
||||
const packages = useEnvStore((s) => s.packages)
|
||||
const rows = useEnvStore((s) => s.rows)
|
||||
const envSelected = useEnvStore((s) => s.selected)
|
||||
const planResolve = usePlanStore((s) => s.resolve)
|
||||
|
||||
const envRow = rows.find((r) => r.interpreter === envSelected)
|
||||
|
||||
// UI-SPEC §5: the Search flow's first click is spent arriving here, so the field must already
|
||||
// have focus — "Search (autofocus) → result [Add] → Install → Confirm" is 4, not 5.
|
||||
useEffect(() => {
|
||||
field.current?.focus()
|
||||
}, [])
|
||||
|
||||
// What is already installed, so a result can say so instead of offering [Add].
|
||||
const installed = useMemo(
|
||||
() => new Map(packages.map((p) => [p.name, p])),
|
||||
[packages],
|
||||
)
|
||||
|
||||
return (
|
||||
<section aria-labelledby="search-title" className="flex h-full min-h-0">
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col p-6">
|
||||
<h1 id="search-title" className="shrink-0 text-accent">
|
||||
{t('search.title')}
|
||||
</h1>
|
||||
|
||||
<input
|
||||
ref={field}
|
||||
type="search"
|
||||
value={query}
|
||||
onChange={(e) => {
|
||||
setQuery(e.target.value)
|
||||
}}
|
||||
placeholder={t('search.placeholder')}
|
||||
aria-label={t('search.title')}
|
||||
className="mt-3 shrink-0 rounded-pd border border-border bg-surface px-3 py-1.5 font-mono text-data"
|
||||
/>
|
||||
|
||||
<div className="mt-1 flex shrink-0 items-center gap-2 text-data text-text-dim">
|
||||
{/* Warming is a state, not a failure: the index is 858k names and takes ~613 ms to
|
||||
load, and saying so beats a field that silently returns nothing. */}
|
||||
{!ready && unavailable === null ? <span>{t('search.warming')}</span> : null}
|
||||
{searching ? <span>{t('search.searching')}</span> : null}
|
||||
</div>
|
||||
|
||||
{unavailable !== null ? (
|
||||
<div className="mt-3 shrink-0 rounded-pd border-l-2 border-warn p-2">
|
||||
<p className="text-data text-warn">{t('search.indexMissing')}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
void refreshIndex()
|
||||
}}
|
||||
disabled={refreshing}
|
||||
className="mt-2 rounded-pd border border-border px-3 py-1 text-data disabled:opacity-40"
|
||||
>
|
||||
{refreshing ? t('search.refreshing') : t('search.refreshIndex')}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error !== null ? (
|
||||
<div className="mt-3 shrink-0">
|
||||
<PdErrorRow error={error} />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{query.trim() !== '' && hits.length === 0 && ready && !searching ? (
|
||||
<PdEmptyState message={t('search.noResults', { query })} hint={t('search.noResultsHint')} />
|
||||
) : null}
|
||||
|
||||
<ul className="mt-3 min-h-0 flex-1 space-y-1 overflow-auto">
|
||||
{hits.map((hit) => {
|
||||
const have = installed.get(hit.name)
|
||||
const queued = queue.some((q) => q.name === hit.name)
|
||||
return (
|
||||
<li
|
||||
key={hit.name}
|
||||
data-hit={hit.name}
|
||||
data-match={hit.kind}
|
||||
className={`flex items-center gap-2 rounded-pd p-2 ${
|
||||
selected === hit.name ? 'bg-surface-2' : 'bg-surface'
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
void select(hit.name)
|
||||
}}
|
||||
className="min-w-0 flex-1 text-left"
|
||||
>
|
||||
{/* The display name as PyPI spells it — data, never localized (I18N §2). */}
|
||||
<code className="font-mono text-data">{hit.display}</code>
|
||||
</button>
|
||||
|
||||
{/* DATA-FLOW §4: an installed package shows its state rather than [Add]. */}
|
||||
{have === undefined ? null : (
|
||||
<PdBadge
|
||||
tone={have.latest === undefined ? 'accent' : 'warn'}
|
||||
label={
|
||||
have.latest === undefined
|
||||
? t('search.installed')
|
||||
: t('packages.badge.update')
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{have === undefined ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
enqueue(hit.name)
|
||||
}}
|
||||
disabled={queued}
|
||||
className="shrink-0 rounded-pd border border-border px-2 py-0.5 text-data disabled:opacity-40"
|
||||
>
|
||||
{queued ? t('search.queued') : t('search.add')}
|
||||
</button>
|
||||
) : null}
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
|
||||
{/* The detail panel. `stale` is not an error — ARCHITECTURE §5 keeps showing cached
|
||||
metadata offline rather than failing, and says which it is. */}
|
||||
{meta !== null ? (
|
||||
<div className="mt-3 shrink-0 rounded-pd border-t border-border pt-3">
|
||||
<div className="flex items-baseline gap-2">
|
||||
<code className="font-mono text-data">{meta.name}</code>
|
||||
{meta.version == null ? null : (
|
||||
<span className="font-mono text-data text-text-dim">{meta.version}</span>
|
||||
)}
|
||||
{metaFreshness === 'fresh' ? null : (
|
||||
<PdBadge tone="dim" label={t(`search.freshness.${metaFreshness ?? 'cached'}`)} />
|
||||
)}
|
||||
</div>
|
||||
{meta.summary == null ? null : <p className="mt-1 text-data">{meta.summary}</p>}
|
||||
<p className="mt-1 text-data text-text-dim">
|
||||
{meta.requiresPython == null
|
||||
? ''
|
||||
: t('search.requiresPython', { spec: meta.requiresPython })}
|
||||
{meta.license == null ? '' : ` · ${meta.license}`}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<PdDockBay
|
||||
queue={queue}
|
||||
onVersionChange={setQueuedVersion}
|
||||
onRemove={dequeue}
|
||||
canInstall={envRow?.env !== undefined}
|
||||
onInstall={() => {
|
||||
if (envRow?.env === undefined) return
|
||||
const specs = queueSpecs(queue)
|
||||
clearQueue()
|
||||
void planResolve(envRow.env, { intent: 'install', specs })
|
||||
}}
|
||||
/>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* Search and the dock bay — ARCHITECTURE §9's `useIndexStore`.
|
||||
*
|
||||
* The whole screen exists under one number: **< 50 ms per keystroke**, measured in the app. SP-3
|
||||
* measured 42.1 ms for the ranking alone, in memory, with no IPC round trip — this adds one, so
|
||||
* the design has to assume the budget is tight rather than discover it afterwards. Three things
|
||||
* follow, and all three are here rather than in the component:
|
||||
*
|
||||
* 1. **The previous result set stays rendered** while a new query is in flight. Blanking the list
|
||||
* on every keystroke is what makes a fast search *feel* slow.
|
||||
* 2. **Responses are sequenced.** Two searches can be in flight and they can return out of order;
|
||||
* without a sequence number the older one wins and the list contradicts the field.
|
||||
* 3. **A debounce, but a short one.** Long enough to skip work while a fast typist is mid-word,
|
||||
* short enough to be invisible — and it is a *coalescer*, not a delay: the first keystroke
|
||||
* after a pause searches immediately.
|
||||
*/
|
||||
|
||||
import { create } from 'zustand'
|
||||
|
||||
import {
|
||||
indexRefresh,
|
||||
indexSearch,
|
||||
isPdError,
|
||||
pkgMetadata,
|
||||
type Freshness,
|
||||
type Hit,
|
||||
type PackageMeta,
|
||||
type PdError,
|
||||
} from '@/ipc'
|
||||
|
||||
/**
|
||||
* Coalescing window, in ms.
|
||||
*
|
||||
* One frame. Anything longer is felt as lag on a budget this tight; anything shorter stops
|
||||
* coalescing anything at all. The debounce exists to avoid queueing work behind a fast typist,
|
||||
* not to wait for them to stop.
|
||||
*/
|
||||
export const SEARCH_DEBOUNCE_MS = 16
|
||||
|
||||
/** How many hits to ask for. The panel shows one screenful; ranking cost scales with this. */
|
||||
export const SEARCH_LIMIT = 50
|
||||
|
||||
/** One queued package — UI-SPEC §4's "dock bay". */
|
||||
export interface QueuedPackage {
|
||||
name: string
|
||||
/** Empty means "latest", which is what the resolver does with no version specifier. */
|
||||
version: string
|
||||
}
|
||||
|
||||
interface IndexState {
|
||||
query: string
|
||||
hits: Hit[]
|
||||
/** False while the 613 ms index load is still running. */
|
||||
ready: boolean
|
||||
/** Set when the index cannot be loaded at all — the screen offers a refresh. */
|
||||
unavailable: string | null
|
||||
/** True while a search is in flight, for a spinner that does not blank the list. */
|
||||
searching: boolean
|
||||
error: PdError | null
|
||||
|
||||
/** The details panel's subject. */
|
||||
selected: string | null
|
||||
meta: PackageMeta | null
|
||||
metaFreshness: Freshness | null
|
||||
metaError: PdError | null
|
||||
|
||||
/** The dock bay queue, in the order packages were added. */
|
||||
queue: QueuedPackage[]
|
||||
|
||||
refreshing: boolean
|
||||
lastRefresh: string | null
|
||||
|
||||
setQuery: (query: string) => void
|
||||
select: (name: string) => Promise<void>
|
||||
enqueue: (name: string) => void
|
||||
setQueuedVersion: (name: string, version: string) => void
|
||||
dequeue: (name: string) => void
|
||||
clearQueue: () => void
|
||||
refreshIndex: () => Promise<void>
|
||||
}
|
||||
|
||||
function asPdError(e: unknown): PdError {
|
||||
return isPdError(e) ? e : { code: 'PD-INT-001', message: String(e) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Sequence of the most recent search, and of the most recent one applied.
|
||||
*
|
||||
* Module-level rather than store state: they are bookkeeping no component renders, and putting
|
||||
* them in the store would wake every subscriber on each keystroke.
|
||||
*/
|
||||
let issued = 0
|
||||
let applied = 0
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
export const useIndexStore = create<IndexState>((set, get) => ({
|
||||
query: '',
|
||||
hits: [],
|
||||
ready: true,
|
||||
unavailable: null,
|
||||
searching: false,
|
||||
error: null,
|
||||
selected: null,
|
||||
meta: null,
|
||||
metaFreshness: null,
|
||||
metaError: null,
|
||||
queue: [],
|
||||
refreshing: false,
|
||||
lastRefresh: null,
|
||||
|
||||
setQuery: (query) => {
|
||||
set({ query })
|
||||
|
||||
if (timer !== undefined) clearTimeout(timer)
|
||||
if (query.trim() === '') {
|
||||
// Clearing the field clears the list immediately — there is nothing to keep showing.
|
||||
issued += 1
|
||||
applied = issued
|
||||
set({ hits: [], searching: false })
|
||||
return
|
||||
}
|
||||
|
||||
timer = setTimeout(() => {
|
||||
const seq = (issued += 1)
|
||||
set({ searching: true })
|
||||
indexSearch(query, SEARCH_LIMIT)
|
||||
.then((results) => {
|
||||
// Out-of-order arrival: a slower earlier search must not overwrite a later one.
|
||||
if (seq < applied) return
|
||||
applied = seq
|
||||
set({
|
||||
hits: results.hits,
|
||||
ready: results.ready,
|
||||
unavailable: results.unavailable ?? null,
|
||||
searching: false,
|
||||
error: null,
|
||||
})
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
if (seq < applied) return
|
||||
applied = seq
|
||||
set({ searching: false, error: asPdError(e) })
|
||||
})
|
||||
}, SEARCH_DEBOUNCE_MS)
|
||||
},
|
||||
|
||||
select: async (name) => {
|
||||
set({ selected: name, meta: null, metaFreshness: null, metaError: null })
|
||||
try {
|
||||
const [meta, freshness] = await pkgMetadata(name)
|
||||
// The user may have moved on while PyPI was answering.
|
||||
if (get().selected !== name) return
|
||||
set({ meta, metaFreshness: freshness })
|
||||
} catch (e) {
|
||||
if (get().selected !== name) return
|
||||
set({ metaError: asPdError(e) })
|
||||
}
|
||||
},
|
||||
|
||||
enqueue: (name) =>
|
||||
set((s) =>
|
||||
s.queue.some((q) => q.name === name) ? {} : { queue: [...s.queue, { name, version: '' }] },
|
||||
),
|
||||
|
||||
setQueuedVersion: (name, version) =>
|
||||
set((s) => ({
|
||||
queue: s.queue.map((q) => (q.name === name ? { ...q, version } : q)),
|
||||
})),
|
||||
|
||||
dequeue: (name) => set((s) => ({ queue: s.queue.filter((q) => q.name !== name) })),
|
||||
clearQueue: () => set({ queue: [] }),
|
||||
|
||||
refreshIndex: async () => {
|
||||
set({ refreshing: true, error: null })
|
||||
try {
|
||||
const report = await indexRefresh()
|
||||
set({
|
||||
refreshing: false,
|
||||
unavailable: null,
|
||||
ready: true,
|
||||
lastRefresh: String(report.projects),
|
||||
})
|
||||
// The in-memory index was invalidated on the Rust side, so re-run whatever is in the field.
|
||||
const { query, setQuery } = get()
|
||||
if (query.trim() !== '') setQuery(query)
|
||||
} catch (e) {
|
||||
set({ refreshing: false, error: asPdError(e) })
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
/** The `name==version` specs the dock bay would install, as `Intent::Install` wants them. */
|
||||
export function queueSpecs(queue: readonly QueuedPackage[]): string[] {
|
||||
return queue.map((q) => (q.version.trim() === '' ? q.name : `${q.name}==${q.version.trim()}`))
|
||||
}
|
||||
@@ -364,3 +364,12 @@ export const useUiStore = create<UiState>((set) => ({
|
||||
// The plan store lives in its own file: it is the largest of them and the only one holding a live
|
||||
// event subscription. Re-exported so `@/stores` stays the single import site.
|
||||
export { CONSOLE_LIMIT, apply, usePlanStore, type ConsoleLine, type PlanPhase } from '@/stores/plan'
|
||||
|
||||
// Search and the dock bay, in their own file for the same reason as the plan store.
|
||||
export {
|
||||
SEARCH_DEBOUNCE_MS,
|
||||
SEARCH_LIMIT,
|
||||
queueSpecs,
|
||||
useIndexStore,
|
||||
type QueuedPackage,
|
||||
} from '@/stores/index-search'
|
||||
Reference in new issue
Block a user