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 = { 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 onError: (title: string, e: unknown) => void } type ProgressMap = Record /** * 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 = ({ locale, safeMode, installed, refreshSignal, onBusyChange, onChanged, onError, }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const [query, setQuery] = useState('') const [kind, setKind] = useState('') const [result, setResult] = useState(null) const [syncing, setSyncing] = useState(false) const [refreshing, setRefreshing] = useState(false) const [visible, setVisible] = useState(PAGE_SIZE) const [progress, setProgress] = useState({}) const [prompt, setPrompt] = useState(null) const [promptReport, setPromptReport] = useState(null) const [promptChecked, setPromptChecked] = useState(false) const [enabling, setEnabling] = useState(false) const seq = useRef(0) const synced = useRef(false) const sentinel = useRef(null) const installingRef = useRef>(new Set()) const promptTargetIDRef = useRef('') const promptQueueRef = useRef([]) 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 (
{text}
) } 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 } if (!item.compatible) { return } if (item.installed && !item.update_available) { return } if (item.update_available) { return ( ) } return ( ) } // 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 (
{facets.length > 1 && (
{[{ kind: '', count: 0 }, ...facets].map((f) => ( ))}
)}
{!showLoader && result?.stale && result.fetch_error && (
)} {(result?.withdrawn_installed ?? []).map((w) => (
))} {showLoader ? ( ) : emptyAfterSync ? (
{query || kind ? tr('pluginSearchEmpty') : tr('pluginMarketEmpty')}
) : ( <>
{shown.map((item, i) => { const e = item.entry const desc = locText(e.description, locale, '') const muted = !!item.withdrawn || !item.compatible return (

{locText(e.name, locale, e.id)}

v{e.version}
{action(item)}

{desc}

) })}
{hasMore ?
) }