Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions scripts/generate-icon-index.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
#!/usr/bin/env node
/**
* 构建期图标索引生成:从三源(Dashboard Icons / selfh.st / Simple Icons)拉取
* 索引,压成精简条目 { slug, name, aliases[], source, url } 写入
* web/public/icon-index.json,作为静态资产随站点发布(前端本地搜索)。
*
* 任一一源拉取/解析失败:不覆盖已提交的旧索引、打印告警、以退出码 0 结束,
* 让构建继续用上一次成功生成的索引(web/public/icon-index.json 已提交进仓库)。
* 三源全成功才整体覆盖。
*/
import { writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";

const here = dirname(fileURLToPath(import.meta.url));
const OUT_PATH = resolve(here, "../web/public/icon-index.json");

const FETCH_TIMEOUT_MS = 30_000;

// 任一源解析出少于该条数视为「成功但退化」(如远端返回 200 + 空 JSON),
// 同样按失败处理:保留旧索引、告警、退出码 0,避免把已提交的索引覆盖成空集。
const MIN_ENTRIES_PER_SOURCE = 500;

async function fetchJson(url) {
const res = await fetch(url, {
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}

/** 三个来源:拉取地址 + 各自解析成精简条目(url 在此把 svg > png > webp 落定)。 */
const SOURCES = [
{
name: "dashboard-icons",
url: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/metadata.json",
parse(metadata) {
const out = [];
for (const [slug, meta] of Object.entries(metadata)) {
const ext = meta.base === "png" ? "png" : "svg";
out.push({
slug,
name: slug,
aliases: meta.aliases ?? [],
source: "dashboard",
url: `https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/${ext}/${slug}.${ext}`,
format: ext,
});
}
return out;
},
},
{
name: "selfh.st",
url: "https://cdn.jsdelivr.net/gh/selfhst/icons/index.json",
parse(index) {
const out = [];
for (const item of index) {
const slug = item.Reference;
const ext =
item.SVG === "Yes" ? "svg" : item.PNG === "Yes" ? "png" : "webp";
out.push({
slug,
name: item.Name ?? slug,
aliases: (item.Tags ?? "")
.split(",")
.map((s) => s.trim())
.filter(Boolean),
source: "selfhst",
url: `https://cdn.jsdelivr.net/gh/selfhst/icons/${ext}/${slug}.${ext}`,
format: ext,
});
}
return out;
},
},
{
name: "simple-icons",
url: "https://cdn.jsdelivr.net/npm/simple-icons@16/data/simple-icons.json",
parse(data) {
return data.map((item) => ({
slug: item.slug,
name: item.title ?? item.slug,
aliases: item.aliases?.aka ?? [],
source: "simple",
url: `https://cdn.simpleicons.org/${item.slug}`,
format: "svg",
}));
},
},
];

const entries = [];
for (const source of SOURCES) {
try {
const raw = await fetchJson(source.url);
const parsed = source.parse(raw);
if (!Array.isArray(parsed) || parsed.length < MIN_ENTRIES_PER_SOURCE) {
throw new Error(
`解析结果退化(${Array.isArray(parsed) ? parsed.length : 0} 条 < ${MIN_ENTRIES_PER_SOURCE})`,
);
}
entries.push(...parsed);
console.log(`[icon-index] ${source.name}: ${parsed.length} 条`);
} catch (err) {
console.error(
`[icon-index] ${source.name} 拉取/解析失败:${err?.message ?? err};保留上一次成功生成的索引`,
);
process.exit(0);
}
}

// 按 source + slug 稳定排序,减小每次重生成的 diff 噪音。
entries.sort(
(a, b) => a.source.localeCompare(b.source) || a.slug.localeCompare(b.slug),
);

writeFileSync(OUT_PATH, JSON.stringify(entries));
console.log(`[icon-index] 共 ${entries.length} 条 → ${OUT_PATH}`);
2 changes: 1 addition & 1 deletion web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"build": "node ../scripts/generate-icon-index.mjs && tsc --noEmit && vite build",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
Expand Down
1 change: 1 addition & 0 deletions web/public/icon-index.json

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions web/src/components/admin/crud-panels.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
deleteReplacedAsset,
useAssetDraftCleanup,
} from "@/components/admin/asset-upload";
import { IconPickerField } from "@/components/admin/icon-picker";
import { SiteIcon } from "@/components/site-icon";
import {
adminCreateCategory,
Expand Down Expand Up @@ -397,14 +398,14 @@ export function LinkPanel({
onChange={(e) => setForm({ ...form, url: e.target.value })}
/>
</div>
<AssetUploadField
<IconPickerField
id="link-icon"
label="链接图标"
purpose="icon"
value={form.iconUrl}
onChange={(iconUrl) => setForm({ ...form, iconUrl })}
onUploaded={draft.track}
hint="支持 PNG / JPEG / WebP / GIF / SVG / ICO,≤ 1MB;留空则自动抓 favicon"
title={form.title}
url={form.url}
/>
<div className="grid gap-2">
<Label htmlFor="link-desc">描述</Label>
Expand Down
172 changes: 172 additions & 0 deletions web/src/components/admin/icon-picker.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import * as React from "react";
import { Library } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Command,
CommandEmpty,
CommandInput,
CommandItem,
CommandList,
} from "@/components/ui/command";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { AssetUploadField } from "@/components/admin/asset-upload";
import {
loadIconIndex,
searchIcons,
type IconIndexEntry,
type IconSource,
} from "@/lib/icon-search";

const DEBOUNCE_MS = 300;
const RESULT_LIMIT = 50;

const SOURCE_LABEL: Record<IconSource, string> = {
dashboard: "Dashboard",
selfhst: "selfh.st",
simple: "Simple",
};

/** 初始查询词:标题非空用标题,否则由 URL 主机名首标签推导(github.com → github)。 */
function initialQuery(title: string, url: string): string {
const trimmed = title.trim();
if (trimmed) return trimmed;
try {
// 裸主机名(无 scheme)如 github.com 会令 new URL 抛错,补 https:// 兜底。
const host = new URL(
/^[a-z][a-z0-9+.-]*:\/\//i.test(url) ? url : `https://${url}`,
).hostname.replace(/^www\./, "");
return host.split(".")[0] ?? "";
} catch {
return "";
}
}

/** 输入防抖:值变化 delayMs 后才更新(用于候选搜索)。 */
function useDebouncedValue<T>(value: T, delayMs: number): T {
const [debounced, setDebounced] = React.useState(value);
React.useEffect(() => {
const id = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(id);
}, [value, delayMs]);
return debounced;
}

/**
* 链接图标选择器:在现有上传/URL 输入控件之上加「从图标库选择」入口。
* 只对链接图标使用(分类/搜索引擎图标仍用 AssetUploadField)。
* 选中结果只写一个 CDN URL 进 icon_url,保存时不会静默改写。
*/
export function IconPickerField({
id,
label,
value,
onChange,
onUploaded,
title,
url,
}: {
id: string;
label: string;
value: string;
onChange: (next: string) => void;
onUploaded?: (path: string) => void;
title: string;
url: string;
}) {
const [open, setOpen] = React.useState(false);
const [query, setQuery] = React.useState("");
const [index, setIndex] = React.useState<IconIndexEntry[] | null>(null);
const [error, setError] = React.useState<string | null>(null);

const debouncedQuery = useDebouncedValue(query, DEBOUNCE_MS);
const results = React.useMemo(
() => (index ? searchIcons(index, debouncedQuery, RESULT_LIMIT) : []),
[index, debouncedQuery],
);

const handleOpenChange = (next: boolean) => {
setOpen(next);
if (next) {
setQuery(initialQuery(title, url));
if (!index) {
loadIconIndex()
.then((idx) => {
setIndex(idx);
setError(null);
})
.catch((err) => setError((err as Error).message));
}
}
};

return (
<div className="grid gap-2">
<AssetUploadField
id={id}
label={label}
purpose="icon"
value={value}
onChange={onChange}
onUploaded={onUploaded}
hint="支持 PNG / JPEG / WebP / GIF / SVG / ICO,≤ 1MB;留空则自动抓 favicon"
/>
<Popover open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>
<Button type="button" variant="outline" className="w-fit">
<Library aria-hidden="true" />
从图标库选择
</Button>
</PopoverTrigger>
<PopoverContent align="start" className="w-80 p-0">
<Command shouldFilter={false} label="搜索图标">
<CommandInput
value={query}
onValueChange={setQuery}
placeholder="搜索图标名称…"
/>
<CommandList>
<CommandEmpty>
{error
? `索引加载失败:${error}`
: index
? "没有匹配的图标"
: "加载中…"}
</CommandEmpty>
{results.map((entry) => (
<CommandItem
key={`${entry.source}:${entry.slug}`}
value={`${entry.source}:${entry.slug}`}
onSelect={() => {
onChange(entry.url);
setOpen(false);
}}
>
<img
src={entry.url}
alt=""
loading="lazy"
className="size-5 shrink-0 object-contain"
/>
<span className="truncate">{entry.name}</span>
<Badge variant="secondary" className="ml-auto shrink-0">
{SOURCE_LABEL[entry.source]}
</Badge>
{entry.format === "svg" ? (
<Badge variant="outline" className="shrink-0">
SVG
</Badge>
) : null}
</CommandItem>
))}
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
);
}
Loading
Loading