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
32 changes: 26 additions & 6 deletions web/src/components/site-icon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { faviconCandidates, hashColor, initialOf } from "@/lib/icons";
import { cn } from "@/lib/utils";

/**
* 站点图标:真实 favicon 优先(icon_url → Google s2 → 目标站 /favicon.ico),
* 全部失败时回退「按域名哈希着色的首字圆」(MASTER.md §1.4)。
* 站点图标:手动指定的图标优先,其次是本站 `/api/icon` 解析出的 favicon,
* 两者都失败时回退「按域名哈希着色的首字圆」(MASTER.md §1.4)。
*/
export function SiteIcon({
title,
Expand All @@ -23,9 +23,19 @@ export function SiteIcon({
() => faviconCandidates(url, iconUrl),
[url, iconUrl],
);
const [index, setIndex] = React.useState(0);

if (index >= candidates.length) {
// 回退进度绑定在当前候选清单上:url/iconUrl 变化(如切换搜索引擎,组件实例被复用)
// 时从第一候选重试,旧候选上的失败不会让新候选被跳过。渲染期按 React「props 变化时
// 调整 state」的官方模式复位,A→B→A 来回切换也不会取回旧进度。
const signature = candidates.join("\n");
const [cursor, setCursor] = React.useState({ signature, index: 0 });
if (cursor.signature !== signature) {
setCursor({ signature, index: 0 });
}
const index = cursor.signature === signature ? cursor.index : 0;
const src = candidates[index];

if (!src) {
return (
<span
aria-hidden="true"
Expand All @@ -47,13 +57,23 @@ export function SiteIcon({

return (
<img
src={candidates[index]}
// src 变化时换元素:被中止的旧请求的 error 不会落到新候选头上
key={src}
src={src}
alt=""
width={size}
height={size}
loading="lazy"
decoding="async"
onError={() => setIndex((i) => i + 1)}
onError={(event) => {
// 兜底校验:只认当前元素上的当前 src
if (event.currentTarget.getAttribute("src") !== src) return;
// 函数式更新:不读本次 render 的过期闭包
setCursor((current) => ({
signature,
index: (current.signature === signature ? current.index : 0) + 1,
}));
}}
className={cn("shrink-0 rounded-md object-contain", className)}
style={{ width: size, height: size }}
/>
Expand Down
18 changes: 13 additions & 5 deletions web/src/lib/icons.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
/** 图标策略(design-system/nav/MASTER.md §1.4):真实 favicon 优先,失败回退按域名哈希着色的首字圆。 */
/**
* 图标策略(design-system/nav/MASTER.md §1.4):手动指定的图标优先,其次本站图标端点
* `/api/icon`(worker 端解析目标站图标并缓存),两档都失败回退按域名哈希着色的首字圆。
*/

/** favicon 优先级:手动 icon_url > Google s2 服务 > 目标站 /favicon.ico(由 <SiteIcon> 依次回退) */
/** 本站图标端点(契约:`GET /api/icon?url=<encodeURIComponent 后的绝对 http(s) URL>`) */
const SITE_ICON_ENDPOINT = "/api/icon";

/** 图标候选优先级:手动 icon_url > 本站 /api/icon(由 <SiteIcon> 依次回退) */
export function faviconCandidates(
url: string,
iconUrl?: string | null,
): string[] {
const out: string[] = [];
if (iconUrl) out.push(iconUrl);
try {
const host = new URL(url).hostname;
out.push(`https://www.google.com/s2/favicons?domain=${host}&sz=64`);
out.push(`https://${host}/favicon.ico`);
const { protocol } = new URL(url);
// 端点只接受绝对 http(s) URL:畸形值与非 http(s) 不发请求,直接走首字圆
if (protocol === "http:" || protocol === "https:") {
out.push(`${SITE_ICON_ENDPOINT}?url=${encodeURIComponent(url)}`);
}
} catch {
/* malformed url → 首字圆 */
}
Expand Down
142 changes: 142 additions & 0 deletions web/test/site-icon.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { SiteIcon } from "@/components/site-icon";
import { faviconCandidates } from "@/lib/icons";

/**
* 图标来源契约(docs/api-contract.md § GET /api/icon):
* 候选为 `[iconUrl, "/api/icon?url=" + encodeURIComponent(url)]`,两档都失败回退首字圆;
* 不再有 Google s2 与目标站裸 `/favicon.ico` 两个直连候选。
*/

const endpoint = (url: string) => `/api/icon?url=${encodeURIComponent(url)}`;

describe("faviconCandidates", () => {
it("无手动图标时只走本站端点", () => {
const url = "https://github.com/workerhub/nav";
expect(faviconCandidates(url)).toEqual([endpoint(url)]);
});

it("手动图标排第一,其次本站端点", () => {
const url = "https://example.com/";
expect(faviconCandidates(url, "/assets/assets/icon/a.png")).toEqual([
"/assets/assets/icon/a.png",
endpoint(url),
]);
});

it("不再出现 Google s2 与目标站裸 /favicon.ico", () => {
const candidates = faviconCandidates("https://example.com/");
expect(candidates).toHaveLength(1);
expect(candidates[0]).not.toContain("google.com");
expect(candidates[0]).not.toContain("example.com/favicon.ico");
});

it("畸形 URL 与非 http(s) 不请求端点,直接首字圆", () => {
expect(faviconCandidates("not a url")).toEqual([]);
expect(faviconCandidates("ftp://example.com/a")).toEqual([]);
expect(faviconCandidates("/relative")).toEqual([]);
// 手动图标不受 url 畸形影响
expect(faviconCandidates("not a url", "/assets/x.png")).toEqual([
"/assets/x.png",
]);
});
});

describe("SiteIcon", () => {
/** 取当前图片元素;没有就显式失败(不用非空断言)。 */
function currentImg(container: HTMLElement): HTMLImageElement {
const img = container.querySelector("img");
if (!img) throw new Error("expected an <img> in container");
return img;
}

it("无手动图标:img 指向本站 /api/icon", () => {
const url = "https://example.com/";
const { container } = render(<SiteIcon title="示例" url={url} />);
expect(currentImg(container).getAttribute("src")).toBe(endpoint(url));
});

it("手动图标优先,失败后才回退端点", () => {
const url = "https://example.com/";
const iconUrl = "/assets/assets/icon/a.png";
const { container } = render(
<SiteIcon title="示例" url={url} iconUrl={iconUrl} />,
);
expect(currentImg(container).getAttribute("src")).toBe(iconUrl);

fireEvent.error(currentImg(container));
expect(currentImg(container).getAttribute("src")).toBe(endpoint(url));
});

it("两档都失败回退首字圆", () => {
const url = "https://example.com/";
const { container } = render(
<SiteIcon title="示例" url={url} iconUrl="/assets/assets/icon/a.png" />,
);
fireEvent.error(currentImg(container));
fireEvent.error(currentImg(container));

expect(container.querySelector("img")).toBeNull();
expect(screen.getByText("示")).toBeInTheDocument();
});

it("畸形 URL 不发图请求,直接首字圆", () => {
const { container } = render(<SiteIcon title="示例" url="not a url" />);
expect(container.querySelector("img")).toBeNull();
expect(screen.getByText("示")).toBeInTheDocument();
});

it("url 变化(切换搜索引擎)后从第一候选重试", () => {
const urlA = "https://a.example.com/";
const urlB = "https://b.example.com/";
const { container, rerender } = render(<SiteIcon title="A" url={urlA} />);
fireEvent.error(currentImg(container));
expect(container.querySelector("img")).toBeNull();

rerender(<SiteIcon title="B" url={urlB} />);
expect(currentImg(container).getAttribute("src")).toBe(endpoint(urlB));
});

it("A→B→A 来回切换:切回 A 仍从第一候选重试", () => {
const urlA = "https://a.example.com/";
const urlB = "https://b.example.com/";
const { container, rerender } = render(<SiteIcon title="A" url={urlA} />);
fireEvent.error(currentImg(container));
expect(container.querySelector("img")).toBeNull();

rerender(<SiteIcon title="B" url={urlB} />);
expect(currentImg(container).getAttribute("src")).toBe(endpoint(urlB));

rerender(<SiteIcon title="A" url={urlA} />);
expect(currentImg(container).getAttribute("src")).toBe(endpoint(urlA));
});

it("手动图标换成另一个后重试新值,不被旧失败跳过", () => {
const url = "https://example.com/";
const { container, rerender } = render(
<SiteIcon title="示例" url={url} iconUrl="/assets/a.png" />,
);
fireEvent.error(currentImg(container));
expect(currentImg(container).getAttribute("src")).toBe(endpoint(url));

rerender(<SiteIcon title="示例" url={url} iconUrl="/assets/b.png" />);
expect(currentImg(container).getAttribute("src")).toBe("/assets/b.png");
});

it("旧 src 的 error 不推进新候选(候选变化时换元素)", () => {
const urlA = "https://a.example.com/";
const urlB = "https://b.example.com/";
const { container, rerender } = render(<SiteIcon title="A" url={urlA} />);
const oldImg = currentImg(container);

rerender(<SiteIcon title="B" url={urlB} />);
const newImg = currentImg(container);
expect(newImg).not.toBe(oldImg);
expect(newImg.getAttribute("src")).toBe(endpoint(urlB));

// 模拟被中止的旧请求补发的 error:旧元素已不在文档里,不得影响新候选
fireEvent.error(oldImg);
expect(currentImg(container).getAttribute("src")).toBe(endpoint(urlB));
});
});
Loading