App.tsx imported a one-line helper from SchemaForm, which pulled both text domains into the startup bundle. The i18n test now follows the real import graph instead of a hand-kept file list, so it catches this. npm test runs every test file. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
432 lines
16 KiB
TypeScript
432 lines
16 KiB
TypeScript
import { AlertTriangle, Check, Download, ShieldAlert } from 'lucide-react'
|
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
|
import '../i18n/domains/plugins.gen'
|
|
import { I18nKey, locText, t } from '../i18n'
|
|
import { Locale, MarketBrowseResult, MarketCatalogItem, PluginInfo, ScanReport } from '../types'
|
|
import { Button, Tip } from '../ui/controls'
|
|
import { Modal } from '../ui/dialog'
|
|
import { api, events, MarketInstallProgress } from '../wails'
|
|
import { PluginAppIcon, PluginApprovalBody, PluginSearchInput, PluginTrustBadge, RiskList } from './PluginParts'
|
|
import { WordmarkLoader } from './WordmarkLoader'
|
|
|
|
// Cards are revealed in pages as the feed scrolls into view.
|
|
const PAGE_SIZE = 24
|
|
// A manual refresh keeps the loader up at least this long, so it reads as a
|
|
// response instead of a flicker.
|
|
const MIN_REFRESH_MS = 900
|
|
const QUERY_DEBOUNCE_MS = 180
|
|
|
|
const KIND_LABELS: Record<string, I18nKey> = {
|
|
theme: 'pluginMarketKindTheme',
|
|
locale: 'pluginMarketKindLocale',
|
|
driver: 'pluginMarketKindDriver',
|
|
tool: 'pluginMarketKindTool',
|
|
template: 'pluginMarketKindTemplate',
|
|
runtime: 'pluginMarketKindRuntime',
|
|
}
|
|
|
|
interface Props {
|
|
locale: Locale
|
|
safeMode?: boolean
|
|
/** Installed plugins; a change re-reads install state from the cache. */
|
|
installed: PluginInfo[]
|
|
/** Bumped by the page's refresh button to force a network fetch. */
|
|
refreshSignal: number
|
|
onBusyChange: (busy: boolean) => void
|
|
/** Called after an install or enable so the page reloads its plugin list. */
|
|
onChanged: (opts: { enabled?: PluginInfo }) => Promise<void> | void
|
|
onError: (title: string, e: unknown) => void
|
|
}
|
|
|
|
type ProgressMap = Record<string, MarketInstallProgress>
|
|
|
|
/**
|
|
* Plugin market feed: a multi-column card grid that paints from the local
|
|
* cache first, revalidates over the network, and reveals cards page by page.
|
|
*/
|
|
export const PluginMarket: React.FC<Props> = ({
|
|
locale, safeMode, installed, refreshSignal, onBusyChange, onChanged, onError,
|
|
}) => {
|
|
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
|
const [query, setQuery] = useState('')
|
|
const [kind, setKind] = useState('')
|
|
const [result, setResult] = useState<MarketBrowseResult | null>(null)
|
|
const [syncing, setSyncing] = useState(false)
|
|
const [refreshing, setRefreshing] = useState(false)
|
|
const [visible, setVisible] = useState(PAGE_SIZE)
|
|
const [progress, setProgress] = useState<ProgressMap>({})
|
|
const [prompt, setPrompt] = useState<PluginInfo | null>(null)
|
|
const [promptReport, setPromptReport] = useState<ScanReport | null>(null)
|
|
const [promptChecked, setPromptChecked] = useState(false)
|
|
const [enabling, setEnabling] = useState(false)
|
|
|
|
const seq = useRef(0)
|
|
const synced = useRef(false)
|
|
const sentinel = useRef<HTMLDivElement>(null)
|
|
const installingRef = useRef<Set<string>>(new Set())
|
|
const promptTargetIDRef = useRef('')
|
|
const promptQueueRef = useRef<PluginInfo[]>([])
|
|
const params = useRef({ query, kind })
|
|
params.current = { query, kind }
|
|
|
|
useEffect(() => { onBusyChange(syncing) }, [syncing])
|
|
|
|
// Network load. Stale responses (an older query) are dropped.
|
|
const sync = useCallback(async (force: boolean) => {
|
|
const id = ++seq.current
|
|
const { query: q, kind: k } = params.current
|
|
setSyncing(true)
|
|
const started = Date.now()
|
|
if (force) setRefreshing(true)
|
|
try {
|
|
const res = await api.BrowsePluginMarket(q, k, false, force)
|
|
if (force) {
|
|
const wait = MIN_REFRESH_MS - (Date.now() - started)
|
|
if (wait > 0) await new Promise((r) => window.setTimeout(r, wait))
|
|
}
|
|
if (id !== seq.current) return
|
|
setResult(res)
|
|
synced.current = true
|
|
} catch (e) {
|
|
if (id === seq.current) onError(tr('pluginFailMarketLoad'), e)
|
|
} finally {
|
|
if (id === seq.current) {
|
|
setSyncing(false)
|
|
setRefreshing(false)
|
|
}
|
|
}
|
|
}, [])
|
|
|
|
// Cache-only read: instant, no network.
|
|
const peek = useCallback(async (keepNetworkState: boolean) => {
|
|
const { query: q, kind: k } = params.current
|
|
try {
|
|
const res = await api.PeekPluginMarket(q, k)
|
|
setResult((prev) => {
|
|
if (keepNetworkState && prev) {
|
|
res.stale = prev.stale
|
|
res.fetch_error = prev.fetch_error
|
|
}
|
|
return res
|
|
})
|
|
} catch (e) {
|
|
// the network load reports errors
|
|
console.warn('[market] PeekPluginMarket failed:', e)
|
|
}
|
|
}, [])
|
|
|
|
// First open: paint from cache, then revalidate.
|
|
useEffect(() => {
|
|
void peek(false).then(() => sync(false))
|
|
}, [])
|
|
|
|
// Query and category changes; the first render is handled above.
|
|
const firstFilter = useRef(true)
|
|
useEffect(() => {
|
|
if (firstFilter.current) { firstFilter.current = false; return }
|
|
setVisible(PAGE_SIZE)
|
|
const timer = window.setTimeout(() => { void sync(false) }, query ? QUERY_DEBOUNCE_MS : 0)
|
|
return () => window.clearTimeout(timer)
|
|
}, [query, kind])
|
|
|
|
const firstRefresh = useRef(true)
|
|
useEffect(() => {
|
|
if (firstRefresh.current) { firstRefresh.current = false; return }
|
|
void sync(true)
|
|
}, [refreshSignal])
|
|
|
|
// Install state lives in the plugin list; re-read it without the network.
|
|
const firstInstalled = useRef(true)
|
|
useEffect(() => {
|
|
if (firstInstalled.current) { firstInstalled.current = false; return }
|
|
if (synced.current) void peek(true)
|
|
}, [installed])
|
|
|
|
useEffect(() => events.onPluginInstall((p) => {
|
|
setProgress((prev) => prev[p.id] ? { ...prev, [p.id]: p } : prev)
|
|
}), [])
|
|
|
|
const items = result?.items ?? []
|
|
const shown = items.slice(0, visible)
|
|
const hasMore = items.length > visible
|
|
|
|
// Reveal the next page as the sentinel nears the viewport.
|
|
useEffect(() => {
|
|
const el = sentinel.current
|
|
if (!el || !hasMore || typeof IntersectionObserver === 'undefined') return
|
|
const io = new IntersectionObserver((entries) => {
|
|
if (entries.some((e) => e.isIntersecting)) setVisible((v) => v + PAGE_SIZE)
|
|
}, { rootMargin: '240px 0px' })
|
|
io.observe(el)
|
|
return () => io.disconnect()
|
|
}, [hasMore, visible, items.length])
|
|
|
|
const openPrompt = (info: PluginInfo) => {
|
|
promptTargetIDRef.current = info.id
|
|
setPromptChecked(false)
|
|
setPromptReport(null)
|
|
setPrompt(info)
|
|
if (info.needs_approval) {
|
|
void api.ScanInstalledPlugin(info.id)
|
|
.then((rep) => {
|
|
if (promptTargetIDRef.current === info.id) setPromptReport(rep)
|
|
})
|
|
.catch((e) => console.warn('[market] ScanInstalledPlugin failed:', info.id, e))
|
|
}
|
|
}
|
|
|
|
const advancePrompt = () => {
|
|
const next = promptQueueRef.current.shift()
|
|
if (next) {
|
|
openPrompt(next)
|
|
return
|
|
}
|
|
promptTargetIDRef.current = ''
|
|
setPrompt(null)
|
|
setPromptReport(null)
|
|
}
|
|
|
|
const closePrompt = () => {
|
|
if (enabling) return
|
|
advancePrompt()
|
|
}
|
|
|
|
const install = async (item: MarketCatalogItem) => {
|
|
const id = item.entry.id
|
|
if (installingRef.current.has(id)) return
|
|
installingRef.current.add(id)
|
|
setProgress((prev) => ({ ...prev, [id]: { id, phase: 'download', done: 0, total: item.entry.size_bytes ?? 0 } }))
|
|
try {
|
|
const info = await api.InstallMarketPlugin(id, false)
|
|
await onChanged({})
|
|
if (info && !info.enabled) {
|
|
if (promptTargetIDRef.current) {
|
|
if (promptTargetIDRef.current !== info.id && !promptQueueRef.current.some((p) => p.id === info.id)) {
|
|
promptQueueRef.current.push(info)
|
|
}
|
|
} else {
|
|
openPrompt(info)
|
|
}
|
|
}
|
|
} catch (e) {
|
|
onError(tr('pluginFailMarketInstall'), e)
|
|
} finally {
|
|
installingRef.current.delete(id)
|
|
setProgress((prev) => {
|
|
const next = { ...prev }
|
|
delete next[id]
|
|
return next
|
|
})
|
|
}
|
|
}
|
|
|
|
const enablePrompted = async () => {
|
|
if (!prompt) return
|
|
setEnabling(true)
|
|
try {
|
|
const target = prompt
|
|
await api.EnablePlugin(target.id, target.needs_approval)
|
|
advancePrompt()
|
|
await onChanged({ enabled: target })
|
|
} catch (e) {
|
|
onError(tr('pluginFailEnable'), e)
|
|
} finally {
|
|
setEnabling(false)
|
|
}
|
|
}
|
|
|
|
const facets = useMemo(() => {
|
|
const list = [...(result?.kinds ?? [])]
|
|
if (kind && !list.some((f) => f.kind === kind)) list.push({ kind, count: 0 })
|
|
return list
|
|
}, [result, kind])
|
|
const kindLabel = (k: string) => KIND_LABELS[k] ? tr(KIND_LABELS[k]) : k.charAt(0).toUpperCase() + k.slice(1)
|
|
|
|
const action = (item: MarketCatalogItem) => {
|
|
const e = item.entry
|
|
const p = progress[e.id]
|
|
if (p) {
|
|
const pct = p.phase === 'download' && p.total > 0 ? Math.min(100, Math.round((p.done / p.total) * 100)) : null
|
|
const text = p.phase === 'install' ? tr('pluginMarketInstalling') : pct === null ? tr('pluginMarketDownloading') : `${pct}%`
|
|
return (
|
|
<div
|
|
className={`market-progress rg-p-progress${pct === null ? ' is-indeterminate' : ''}`}
|
|
role="progressbar"
|
|
aria-label={tr('pluginMarketDownloading')}
|
|
aria-valuemin={0}
|
|
aria-valuemax={100}
|
|
aria-valuenow={pct ?? undefined}
|
|
>
|
|
<span className="market-progress-fill" style={pct === null ? undefined : { transform: `scaleX(${pct / 100})` }} />
|
|
<span className="market-progress-text">{text}</span>
|
|
</div>
|
|
)
|
|
}
|
|
if (item.withdrawn) {
|
|
const why = locText(item.withdrawn.reason, locale, '')
|
|
+ (item.withdrawn.instead_id ? ` · ${tr('pluginMarketWithdrawnInstead', { target: item.withdrawn.instead_name || item.withdrawn.instead_id })}` : '')
|
|
return <Tip label={why || tr('pluginMarketWithdrawn')}><span tabIndex={0}><Button className="market-btn" disabled>{tr('pluginMarketWithdrawn')}</Button></span></Tip>
|
|
}
|
|
if (!item.compatible) {
|
|
return <Tip label={item.incompatible_reason || tr('pluginMarketIncompatible')}><span tabIndex={0}><Button className="market-btn" disabled>{tr('pluginMarketIncompatible')}</Button></span></Tip>
|
|
}
|
|
if (item.installed && !item.update_available) {
|
|
return <Button className="market-btn" disabled icon={<Check size={13} aria-hidden="true" />}>{tr('pluginMarketInstalled')}</Button>
|
|
}
|
|
if (item.update_available) {
|
|
return (
|
|
<Tip label={tr('pluginMarketVersionTip', { installed: item.installed_version ?? '', version: e.version })}>
|
|
<span>
|
|
<Button className="market-btn" variant="primary" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => void install(item)}>
|
|
{tr('pluginMarketUpdateShort')}
|
|
</Button>
|
|
</span>
|
|
</Tip>
|
|
)
|
|
}
|
|
return (
|
|
<Button className="market-btn" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => void install(item)}>
|
|
{tr('pluginMarketInstall')}
|
|
</Button>
|
|
)
|
|
}
|
|
|
|
// The loader covers the feed when there is nothing to show yet, or when the
|
|
// user asked for a refresh and should see it happen.
|
|
const showLoader = refreshing || (syncing && items.length === 0) || (!result && !synced.current)
|
|
const emptyAfterSync = !showLoader && items.length === 0
|
|
|
|
return (
|
|
<section className="section plugin-market">
|
|
<div className="market-toolbar">
|
|
<PluginSearchInput
|
|
value={query}
|
|
onChange={setQuery}
|
|
placeholder={tr('pluginMarketSearchPlaceholder')}
|
|
wide
|
|
/>
|
|
{facets.length > 1 && (
|
|
<div className="market-kinds" role="radiogroup" aria-label={tr('pluginMarketKindAll')}>
|
|
{[{ kind: '', count: 0 }, ...facets].map((f) => (
|
|
<button
|
|
key={f.kind || 'all'}
|
|
type="button"
|
|
role="radio"
|
|
aria-checked={kind === f.kind}
|
|
className={`plugin-pill${kind === f.kind ? ' is-active' : ''}`}
|
|
onClick={() => setKind(f.kind)}
|
|
>
|
|
{f.kind ? kindLabel(f.kind) : tr('pluginMarketKindAll')}
|
|
{f.kind && f.count > 0 && <span className="plugin-pill-count">{f.count}</span>}
|
|
</button>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
{!showLoader && result?.stale && result.fetch_error && (
|
|
<div className="notice notice-warn">
|
|
<span className="notice-main">
|
|
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
|
|
<span>{tr('pluginMarketStaleBanner')}</span>
|
|
</span>
|
|
</div>
|
|
)}
|
|
|
|
{(result?.withdrawn_installed ?? []).map((w) => (
|
|
<div className="notice notice-warn" key={w.id}>
|
|
<span className="notice-main">
|
|
<ShieldAlert size={15} className="notice-icon" aria-hidden="true" />
|
|
<span>
|
|
{tr('pluginMarketWithdrawnInstalledWarn', { id: w.id, reason: locText(w.reason, locale, '') })}
|
|
{w.instead_id ? ` · ${tr('pluginMarketWithdrawnInstead', { target: w.instead_name || w.instead_id })}` : ''}
|
|
</span>
|
|
</span>
|
|
</div>
|
|
))}
|
|
|
|
{showLoader ? (
|
|
<WordmarkLoader className="market-loader" label={tr(refreshing || result ? 'pluginMarketSyncing' : 'pluginMarketLoading')} />
|
|
) : emptyAfterSync ? (
|
|
<div className="plugins-empty">{query || kind ? tr('pluginSearchEmpty') : tr('pluginMarketEmpty')}</div>
|
|
) : (
|
|
<>
|
|
<div className="market-grid">
|
|
{shown.map((item, i) => {
|
|
const e = item.entry
|
|
const desc = locText(e.description, locale, '')
|
|
const muted = !!item.withdrawn || !item.compatible
|
|
return (
|
|
<article
|
|
className={`market-card rg-p-card${muted ? ' is-muted' : ''}`}
|
|
key={e.id}
|
|
style={{ '--i': i % PAGE_SIZE } as React.CSSProperties}
|
|
>
|
|
<div className="market-card-head">
|
|
<PluginAppIcon plugin={e} size="lg" />
|
|
<div className="market-card-titles">
|
|
<h3 className="market-card-name" title={locText(e.name, locale, e.id)}>{locText(e.name, locale, e.id)}</h3>
|
|
<div className="market-card-byline">
|
|
<PluginTrustBadge locale={locale} trust={e.trust} publisher={e.publisher} />
|
|
<span className="market-card-dot" aria-hidden="true">·</span>
|
|
<span className="market-card-version">v{e.version}</span>
|
|
</div>
|
|
</div>
|
|
<div className="market-card-action">{action(item)}</div>
|
|
</div>
|
|
<p className="market-card-desc" title={desc}>{desc}</p>
|
|
</article>
|
|
)
|
|
})}
|
|
</div>
|
|
{hasMore
|
|
? <div ref={sentinel} className="market-sentinel" aria-hidden="true" />
|
|
: items.length > PAGE_SIZE && <div className="market-feed-end">{tr('pluginMarketFeedEnd', { count: items.length })}</div>}
|
|
</>
|
|
)}
|
|
|
|
{prompt && (
|
|
<Modal
|
|
title={tr('pluginEnablePromptTitle', { name: locText(prompt.name, locale, prompt.id) })}
|
|
subtitle={`${prompt.publisher || tr('pluginTrustCommunity')} · v${prompt.version}`}
|
|
closeLabel={tr('close')}
|
|
dismissable={!enabling}
|
|
onClose={closePrompt}
|
|
>
|
|
<div className="dialog-body">
|
|
{prompt.needs_approval ? (
|
|
<>
|
|
<PluginApprovalBody locale={locale} plugin={prompt} report={promptReport} />
|
|
<label className="choice">
|
|
<input type="checkbox" checked={promptChecked} onChange={(e) => setPromptChecked(e.target.checked)} />
|
|
<span>{tr('pluginApproveCheckbox')}</span>
|
|
</label>
|
|
</>
|
|
) : (prompt.risks?.length ?? 0) > 0 ? (
|
|
<>
|
|
<p className="plugin-enable-lead">{tr('pluginEnablePromptBody')}</p>
|
|
<RiskList locale={locale} risks={prompt.risks} />
|
|
</>
|
|
) : (
|
|
<p className="plugin-enable-lead">{tr('pluginEnablePromptNoRisk')}</p>
|
|
)}
|
|
</div>
|
|
<div className="dialog-foot">
|
|
<span />
|
|
<span className="hstack">
|
|
<Button variant="ghost" disabled={enabling} onClick={closePrompt}>{tr('pluginEnableLater')}</Button>
|
|
<Button
|
|
variant="primary"
|
|
disabled={enabling || !!safeMode || (prompt.needs_approval && !promptChecked)}
|
|
onClick={() => void enablePrompted()}
|
|
>
|
|
{tr(prompt.needs_approval ? 'pluginApproveConfirm' : 'pluginEnableNow')}
|
|
</Button>
|
|
</span>
|
|
</div>
|
|
</Modal>
|
|
)}
|
|
</section>
|
|
)
|
|
}
|