Files
NapCatQQ/packages/napcat-webui-frontend/src/components/display_card/plugin_card.tsx
T
手瓜一十雪 48ffd5597a Add plugin icon support and caching
Introduce support for plugin icons across backend and frontend. Updates include:

- napcat-onebot: add optional `icon` field to PluginPackageJson.
- Backend (api/Plugin, PluginStore, router): add handlers/utilities to locate and serve plugin icons (`GetPluginIconHandler`, getPluginIconUrl, findPluginIconPath) and wire the route `/api/Plugin/Icon/:pluginId`.
- Cache logic: implement `cachePluginIcon` to fetch GitHub user avatars and store as `data/icon.png` when package.json lacks an icon; invoked after plugin install (regular and SSE flows).
- Frontend: add `icon` to PluginItem, prefer backend-provided icon URL in plugin card (via new getPluginIconUrl util that appends webui_token query param), and add the util to handle token-based image requests.
- Plugin store UI: add a Random category (shuffled), client-side pagination, and reset page on tab/search changes.

These changes let the UI display plugin icons (falling back to author/avatar or Vercel avatars) and cache icons for better UX, while handling auth by passing the token as a query parameter for img src requests.
2026-02-20 23:32:57 +08:00

221 lines
6.9 KiB
TypeScript

import { Avatar } from '@heroui/avatar';
import { Button } from '@heroui/button';
import { Card, CardBody, CardFooter } from '@heroui/card';
import { Chip } from '@heroui/chip';
import { Switch } from '@heroui/switch';
import { Tooltip } from '@heroui/tooltip';
import { MdDeleteForever, MdSettings } from 'react-icons/md';
import clsx from 'clsx';
import { useLocalStorage } from '@uidotdev/usehooks';
import { useState } from 'react';
import key from '@/const/key';
import { PluginItem } from '@/controllers/plugin_manager';
import { getPluginIconUrl } from '@/utils/plugin_icon';
/** 提取作者头像 URL */
function getAuthorAvatar (homepage?: string, repository?: string): string | undefined {
// 1. 尝试从 repository 提取 GitHub 用户名
if (repository) {
try {
// 处理 git+https://github.com/... 或 https://github.com/...
const repoUrl = repository.replace(/^git\+/, '').replace(/\.git$/, '');
const url = new URL(repoUrl);
if (url.hostname === 'github.com' || url.hostname === 'www.github.com') {
const parts = url.pathname.split('/').filter(Boolean);
if (parts.length >= 1) {
return `https://github.com/${parts[0]}.png`;
}
}
} catch {
// 忽略解析错误
}
}
// 2. 尝试从 homepage 提取
if (homepage) {
try {
const url = new URL(homepage);
if (url.hostname === 'github.com' || url.hostname === 'www.github.com') {
const parts = url.pathname.split('/').filter(Boolean);
if (parts.length >= 1) {
return `https://github.com/${parts[0]}.png`;
}
} else {
// 如果是自定义域名,尝试获取 favicon
return `https://api.iowen.cn/favicon/${url.hostname}.png`;
}
} catch {
// 忽略解析错误
}
}
return undefined;
}
export interface PluginDisplayCardProps {
data: PluginItem;
onToggleStatus: () => Promise<void>;
onUninstall: () => Promise<void>;
onConfig?: () => void;
hasConfig?: boolean;
}
const PluginDisplayCard: React.FC<PluginDisplayCardProps> = ({
data,
onToggleStatus,
onUninstall,
onConfig,
hasConfig = false,
}) => {
const { name, version, author, description, status, homepage, repository, icon } = data;
const isEnabled = status === 'active';
const [processing, setProcessing] = useState(false);
const [isExpanded, setIsExpanded] = useState(false);
const [backgroundImage] = useLocalStorage<string>(key.backgroundImage, '');
const hasBackground = !!backgroundImage;
// 优先使用后端返回的 icon URL(需要携带 token),否则尝试提取作者头像,最后兜底 Vercel 风格头像
const avatarUrl = getPluginIconUrl(icon) || getAuthorAvatar(homepage, repository) || `https://avatar.vercel.sh/${encodeURIComponent(name)}`;
const handleToggle = () => {
setProcessing(true);
onToggleStatus().finally(() => setProcessing(false));
};
const handleUninstall = () => {
setProcessing(true);
onUninstall().finally(() => setProcessing(false));
};
return (
<Card
className={clsx(
'group w-full backdrop-blur-md rounded-2xl overflow-hidden transition-all duration-300',
'hover:shadow-xl hover:-translate-y-1',
'border border-white/50 dark:border-white/10 hover:border-primary/50 dark:hover:border-primary/50',
hasBackground ? 'bg-white/20 dark:bg-black/10' : 'bg-white/60 dark:bg-black/30'
)}
shadow='sm'
>
<CardBody className='p-4 flex flex-col gap-3'>
{/* Header */}
<div className='flex items-start justify-between gap-3'>
<div className='flex items-center gap-3 min-w-0'>
<Avatar
src={avatarUrl}
name={author || '?'}
className='flex-shrink-0'
size='md'
isBordered
radius='full'
color='default'
/>
<div className='min-w-0'>
<h3 className='text-base font-bold text-default-900 truncate' title={name}>
{name}
</h3>
<p className='text-xs text-default-500 mt-0.5 truncate'>
by <span className='font-medium'>{author || '未知'}</span>
</p>
</div>
</div>
<Chip
size='sm'
variant='flat'
color={status === 'active' ? 'success' : status === 'stopped' ? 'warning' : 'default'}
className='flex-shrink-0 font-medium h-6 px-1'
>
{status === 'active' ? '运行中' : status === 'stopped' ? '已停止' : '已禁用'}
</Chip>
</div>
{/* Description */}
<div
className='relative min-h-[2.5rem] cursor-pointer group/desc'
onClick={() => setIsExpanded(!isExpanded)}
>
<Tooltip
content={description}
isDisabled={!description || description.length < 50 || isExpanded}
placement='bottom'
className='max-w-[280px]'
delay={500}
>
<p className={clsx(
'text-sm text-default-600 dark:text-default-400 leading-relaxed transition-all duration-300',
isExpanded ? 'line-clamp-none' : 'line-clamp-2'
)}
>
{description || '暂无描述'}
</p>
</Tooltip>
</div>
{/* Version Badge */}
<div>
<Chip
size='sm'
variant='flat'
color='primary'
className='h-5 text-xs font-semibold px-0.5'
classNames={{ content: 'px-1' }}
>
v{version}
</Chip>
</div>
</CardBody>
<CardFooter className='px-4 pb-4 pt-0 gap-3'>
<Switch
isDisabled={processing}
isSelected={isEnabled}
onValueChange={handleToggle}
size='sm'
color='success'
classNames={{
wrapper: 'group-data-[selected=true]:bg-success',
}}
>
<span className='text-xs font-medium text-default-600'>
{isEnabled ? '已启用' : '已禁用'}
</span>
</Switch>
<div className='flex-1' />
{hasConfig && (
<Tooltip content='插件配置'>
<Button
isIconOnly
radius='full'
size='sm'
variant='light'
color='primary'
onPress={onConfig}
>
<MdSettings size={20} />
</Button>
</Tooltip>
)}
<Tooltip content='卸载插件' color='danger'>
<Button
isIconOnly
radius='full'
size='sm'
variant='light'
color='danger'
onPress={handleUninstall}
isDisabled={processing}
>
<MdDeleteForever size={20} />
</Button>
</Tooltip>
</CardFooter>
</Card>
);
};
export default PluginDisplayCard;