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
16 changes: 14 additions & 2 deletions docs/api-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"settings": {
"siteTitle": "nav",
"backgroundUrl": "",
"wallpaperSource": "bing",
"logoUrl": "",
"theme": "system",
"columns": 0,
Expand All @@ -50,6 +51,15 @@
}
```

`wallpaperSource`:首页壁纸来源,`bing`(默认,Bing 每日壁纸)| `custom`(用 `backgroundUrl` 自定义图)。存量库无此键时按 `bing` 返回。

### GET /api/wallpaper/today

同源代理 Bing 每日壁纸(无鉴权,公共页未登录也要取图)。
- 200:图片二进制,`Content-Type: image/*`;`Cache-Control: public, max-age=<到下一个北京时间零点的秒数>`。
- 回源失败时回退到昨日缓存图(同样 200);连昨日缓存也无 → `502 {"error":"wallpaper unavailable"}`。
- 服务端按北京时间自然日缓存当天图(内部缓存条目多保留一天以支持次日回退);不向上游透传 `content-length` / `x-msedge-ref` / `nel` / `report-to` 等头。

## 私有

### GET /api/private
Expand Down Expand Up @@ -113,11 +123,13 @@ Passkey(WebAuthn,/api/auth/passkey/*,@simplewebauthn/server v14):

### 站点设置

- `GET /api/admin/settings` → `{siteTitle, backgroundUrl, logoUrl, theme, columns, searchNewTab}`
- `PUT /api/admin/settings` body 可含 `{siteTitle, backgroundUrl, logoUrl, theme(light|dark|system), columns(0–12), searchNewTab(boolean)}` → 更新后对象
- `GET /api/admin/settings` → `{siteTitle, backgroundUrl, wallpaperSource, logoUrl, theme, columns, searchNewTab}`
- `PUT /api/admin/settings` body 可含 `{siteTitle, backgroundUrl, wallpaperSource(bing|custom), logoUrl, theme(light|dark|system), columns(0–12), searchNewTab(boolean)}` → 更新后对象

`searchNewTab`:搜索是否在新标签页打开。存储键 `search_new_tab`,值 `"1"`/`"0"`(同 `totp_enabled` 的 KV 布尔惯例);库中**无此键**(存量库)时按 `true` 返回。写入只接受布尔值,非布尔返回 400 `searchNewTab must be a boolean`。

`wallpaperSource`:首页壁纸来源。存储键 `wallpaper_source`,值 `"bing"`/`"custom"`;库中**无此键**(存量库)时按 `bing` 返回。写入只接受 `bing`/`custom`,其他值返回 400 `wallpaperSource must be 'bing' or 'custom'`。

`columns` 允许 `0–12`,其中 `0` 表示**未配置**(用默认值):`0` 原样存入并原样返回,不会被替换成默认列数。`GET /api/admin/settings` 对未配置的库返回 `columns: 0`,所以 `0–12` 都能往返提交;超出范围返回 400 `columns must be between 0 and 12`。

`backgroundUrl` / `logoUrl` 的值可以是外链 URL,也可以是本地上传路径(`/assets/…`,见下节)。`/assets/…` 被替换成**任何**其他值时,旧 R2 对象自动删除;外链旧值一律不删。
Expand Down
26 changes: 26 additions & 0 deletions web/src/components/admin/settings-panels.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,8 @@ export function SettingsPanel({
const [form, setForm] = React.useState<SiteSettings>({
...settings,
logoUrl: settings.logoUrl ?? "",
// 旧数据 / 旧 mock 可能没有该字段:契约默认 Bing
wallpaperSource: settings.wallpaperSource ?? "bing",
// 旧数据 / 旧 mock 可能没有该字段:契约默认开
searchNewTab: settings.searchNewTab ?? true,
});
Expand Down Expand Up @@ -278,6 +280,30 @@ export function SettingsPanel({
onChange={(e) => setForm({ ...form, siteTitle: e.target.value })}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="set-wallpaper-source">壁纸来源</Label>
<Select
value={form.wallpaperSource}
onValueChange={(v) =>
setForm({
...form,
wallpaperSource: v as SiteSettings["wallpaperSource"],
})
}
>
<SelectTrigger id="set-wallpaper-source" aria-label="选择壁纸来源">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="bing">Bing 每日壁纸</SelectItem>
<SelectItem value="custom">自定义壁纸</SelectItem>
</SelectContent>
</Select>
<p className="text-sm text-muted-foreground">
选「自定义壁纸」时使用下方背景图;选「Bing
每日壁纸」时忽略背景图地址。
</p>
</div>
<AssetUploadField
id="set-bg"
label="背景图"
Expand Down
29 changes: 28 additions & 1 deletion web/src/components/public-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,33 @@ export function PublicPage({ onOpenAdmin }: { onOpenAdmin: () => void }) {
const settings = siteData?.settings;
const categories = siteData?.categories ?? [];

// 壁纸来源(SPEC:缺省 bing)。custom 且填了 backgroundUrl 才用自定义图,
// 否则(bing / custom 但 backgroundUrl 为空)都走 Bing 每日壁纸端点。
// 站点设置未到达(settings 为 undefined)时先不解析来源、也不发探针,
// 以免设置还没回就提前拉取整张大图;此时先显示纯色底。
const settingsReady = settings !== undefined;
const wallpaperSource = settings?.wallpaperSource ?? "bing";
const customBackgroundUrl = settings?.backgroundUrl ?? "";
const useBing =
settingsReady && (wallpaperSource !== "custom" || !customBackgroundUrl);

// bing 取图失败时回落:先试 backgroundUrl(非空),再落到纯色底(url 层去掉)。
const [bingFailed, setBingFailed] = React.useState(false);
React.useEffect(() => {
setBingFailed(false);
if (!useBing) return;
const img = new Image();
img.onload = () => setBingFailed(false);
img.onerror = () => setBingFailed(true);
img.src = "/api/wallpaper/today";
}, [useBing]);

const backgroundUrl = !settingsReady
? ""
: useBing && !bingFailed
? "/api/wallpaper/today"
: customBackgroundUrl;

// 私有标识:/api/private 的分类 DTO 不含 visibility,用「全量里有、公开列表里没有」推导私有分类。
const publicIds = new Set(publicData?.categories.map((c) => c.id) ?? []);
const privateIds = new Set(
Expand All @@ -59,7 +86,7 @@ export function PublicPage({ onOpenAdmin }: { onOpenAdmin: () => void }) {
className="fixed inset-0 -z-10 bg-cover bg-center bg-no-repeat"
style={{
backgroundImage: `linear-gradient(rgba(15,23,42,0.55), rgba(15,23,42,0.35)), url(${JSON.stringify(
settings?.backgroundUrl ?? "",
backgroundUrl,
)})`,
backgroundColor: "#0f172a",
}}
Expand Down
9 changes: 7 additions & 2 deletions web/src/lib/mockDb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ function seed(): MockState {
siteTitle: "我的导航",
backgroundUrl:
"https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=2400&q=80",
wallpaperSource: "bing",
logoUrl: "",
theme: "system",
columns: 8,
Expand All @@ -160,11 +161,15 @@ function load(): MockState {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) {
// 旧 mock 库没有 searchNewTab:按契约默认开补齐,避免界面读到 undefined
// 旧 mock 库没有 searchNewTab / wallpaperSource:按契约默认补齐,避免界面读到 undefined
const state = JSON.parse(raw) as Omit<MockState, "settings"> & {
settings: Partial<SiteSettings>;
};
state.settings = { searchNewTab: true, ...state.settings };
state.settings = {
searchNewTab: true,
wallpaperSource: "bing",
...state.settings,
};
return state as MockState;
}
} catch {
Expand Down
2 changes: 2 additions & 0 deletions web/src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ export interface SearchEngine {
export interface SiteSettings {
siteTitle: string;
backgroundUrl: string;
/** 壁纸来源(后端 KV `wallpaper_source`,无此键时为 bing):`bing` 每日壁纸 / `custom` 用 backgroundUrl */
wallpaperSource: "bing" | "custom";
/** 站点 Logo 图片地址(外链 URL 或上传后的 `/assets/...` 路径,空串表示无) */
logoUrl: string;
theme: "system" | "light" | "dark";
Expand Down
127 changes: 125 additions & 2 deletions web/test/public-page.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { render, screen, within } from "@testing-library/react";
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { PublicPage } from "@/components/public-page";
import { useNavStore } from "@/lib/nav-store";
import type { SearchEngine, SiteSettings } from "@/lib/types";
Expand All @@ -12,6 +12,7 @@ vi.mock("sonner", () => ({
const baseSettings: SiteSettings = {
siteTitle: "我的导航",
backgroundUrl: "",
wallpaperSource: "bing",
logoUrl: "",
theme: "system",
columns: 6,
Expand Down Expand Up @@ -120,3 +121,125 @@ describe("PublicPage:搜索跳转方式跟随站点设置 searchNewTab", () =>
expect(location.href).toBe("http://localhost/start");
});
});

describe("PublicPage:壁纸来源解析(缺省 bing)", () => {
/** 背景层是唯一的 aria-hidden 且带 backgroundImage 的 div。 */
function backgroundLayer(container: HTMLElement): HTMLElement {
const el = Array.from(
container.querySelectorAll<HTMLElement>('div[aria-hidden="true"]'),
).find((d) => d.style.backgroundImage);
if (!el) throw new Error("背景层未找到");
return el;
}

afterEach(() => {
vi.unstubAllGlobals();
});

it("站点设置未到达(publicData 为 null):不发起探针,背景层不指向端点", () => {
useNavStore.setState({
publicData: null,
privateData: null,
authStatus: "anonymous",
loginPromptOpen: false,
loadPublic: async () => {},
loadPrivate: async () => {},
});
const imageSpy = vi.fn();
vi.stubGlobal("Image", imageSpy);

const { container } = render(<PublicPage onOpenAdmin={vi.fn()} />);

// 设置没回之前不应提前拉取整张大图。
expect(imageSpy).not.toHaveBeenCalled();
expect(backgroundLayer(container).style.backgroundImage).not.toContain(
"/api/wallpaper/today",
);
});

it("wallpaperSource=bing(缺省)+ 无 backgroundUrl:背景层指向 /api/wallpaper/today", () => {
seed(baseSettings);
const { container } = render(<PublicPage onOpenAdmin={vi.fn()} />);
expect(backgroundLayer(container).style.backgroundImage).toContain(
"/api/wallpaper/today",
);
});

it("wallpaperSource=custom + backgroundUrl 非空:背景层用 backgroundUrl", () => {
seed({
...baseSettings,
wallpaperSource: "custom",
backgroundUrl: "https://cdn.example.com/bg.jpg",
});
const { container } = render(<PublicPage onOpenAdmin={vi.fn()} />);
const bg = backgroundLayer(container).style.backgroundImage;
expect(bg).toContain("https://cdn.example.com/bg.jpg");
expect(bg).not.toContain("/api/wallpaper/today");
});

it("wallpaperSource=custom 但 backgroundUrl 为空:回落 /api/wallpaper/today", () => {
seed({ ...baseSettings, wallpaperSource: "custom", backgroundUrl: "" });
const { container } = render(<PublicPage onOpenAdmin={vi.fn()} />);
expect(backgroundLayer(container).style.backgroundImage).toContain(
"/api/wallpaper/today",
);
});

it("wallpaperSource=bing 但 backgroundUrl 非空:仍用 Bing(忽略自定义图)", () => {
seed({
...baseSettings,
wallpaperSource: "bing",
backgroundUrl: "https://cdn.example.com/bg.jpg",
});
const { container } = render(<PublicPage onOpenAdmin={vi.fn()} />);
expect(backgroundLayer(container).style.backgroundImage).toContain(
"/api/wallpaper/today",
);
});

it("bing 图加载失败:回落 backgroundUrl(非空)", async () => {
seed({
...baseSettings,
wallpaperSource: "bing",
backgroundUrl: "https://cdn.example.com/bg.jpg",
});

class FailingImage {
onload: (() => void) | null = null;
onerror: (() => void) | null = null;
set src(_v: string) {
queueMicrotask(() => this.onerror?.());
}
}
vi.stubGlobal("Image", FailingImage);

const { container } = render(<PublicPage onOpenAdmin={vi.fn()} />);

await waitFor(() =>
expect(backgroundLayer(container).style.backgroundImage).toContain(
"https://cdn.example.com/bg.jpg",
),
);
});

it("bing 图加载失败且无 backgroundUrl:去掉 url 层(纯色底)", async () => {
seed({ ...baseSettings, wallpaperSource: "bing", backgroundUrl: "" });

class FailingImage {
onload: (() => void) | null = null;
onerror: (() => void) | null = null;
set src(_v: string) {
queueMicrotask(() => this.onerror?.());
}
}
vi.stubGlobal("Image", FailingImage);

const { container } = render(<PublicPage onOpenAdmin={vi.fn()} />);

await waitFor(() => {
const bg = backgroundLayer(container).style.backgroundImage;
expect(bg).not.toContain("/api/wallpaper/today");
expect(bg).not.toContain("cdn.example.com");
});
});
});
54 changes: 54 additions & 0 deletions web/test/settings-panels.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const updateSettingsMock = vi.mocked(adminUpdateSettings);
const baseSettings: SiteSettings = {
siteTitle: "我的导航",
backgroundUrl: "",
wallpaperSource: "bing",
logoUrl: "",
theme: "system",
columns: 6,
Expand Down Expand Up @@ -199,3 +200,56 @@ describe("SettingsPanel:搜索在新标签页打开开关(默认开)", ()
expect(screen.getByLabelText("搜索在新标签页打开")).toBeChecked();
});
});

describe("SettingsPanel:壁纸来源切换(默认 Bing)", () => {
beforeEach(() => {
uploadMock.mockReset();
updateSettingsMock.mockReset();
updateSettingsMock.mockImplementation(async (input) => ({
...baseSettings,
...input,
}));
});

it("默认渲染「Bing 每日壁纸」,保存时提交 wallpaperSource=bing", async () => {
const user = userEvent.setup();

render(<SettingsPanel settings={baseSettings} onChanged={vi.fn()} />);

expect(screen.getByText("壁纸来源")).toBeInTheDocument();
expect(screen.getByText("Bing 每日壁纸")).toBeInTheDocument();

await user.click(screen.getByRole("button", { name: "保存设置" }));

await waitFor(() => expect(updateSettingsMock).toHaveBeenCalledTimes(1));
expect(updateSettingsMock.mock.calls[0][0]).toMatchObject({
wallpaperSource: "bing",
});
});

it("旧数据缺 wallpaperSource 时按默认 bing 显示", () => {
render(
<SettingsPanel
settings={{ ...baseSettings, wallpaperSource: undefined as never }}
onChanged={vi.fn()}
/>,
);
expect(screen.getByText("Bing 每日壁纸")).toBeInTheDocument();
});

it("切换到「自定义壁纸」并保存:提交 wallpaperSource=custom", async () => {
const user = userEvent.setup();

render(<SettingsPanel settings={baseSettings} onChanged={vi.fn()} />);

await user.click(screen.getByRole("combobox", { name: "选择壁纸来源" }));
await user.click(screen.getByRole("option", { name: "自定义壁纸" }));

await user.click(screen.getByRole("button", { name: "保存设置" }));

await waitFor(() => expect(updateSettingsMock).toHaveBeenCalledTimes(1));
expect(updateSettingsMock.mock.calls[0][0]).toMatchObject({
wallpaperSource: "custom",
});
});
});
1 change: 1 addition & 0 deletions web/test/theme-toggle.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import type { SiteSettings } from "@/lib/types";
const baseSettings: SiteSettings = {
siteTitle: "我的导航",
backgroundUrl: "",
wallpaperSource: "bing",
logoUrl: "",
theme: "system",
columns: 6,
Expand Down
2 changes: 2 additions & 0 deletions worker/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { publicRoutes } from "./routes/public";
import { privateRoutes } from "./routes/private";
import { adminRoutes } from "./routes/admin";
import { setupRoutes } from "./routes/setup";
import { wallpaperRoutes } from "./routes/wallpaper";
import { assetPublicRoutes } from "./routes/assets";
import { getSetting } from "./db/queries/settings";
import { deleteExpiredSessions } from "./db/queries/users";
Expand Down Expand Up @@ -49,6 +50,7 @@ app.route("/api/auth/passkey", webauthnRoutes);
app.route("/api/public", publicRoutes);
app.route("/api/private", privateRoutes);
app.route("/api/admin", adminRoutes);
app.route("/api/wallpaper", wallpaperRoutes);
// Setup surface: GET /api/setup/state (canonical), GET /api/setup/status
// (legacy alias), POST /api/setup (secret-gated upgrade — SETUP-PAGE-SPEC §3).
app.route("/api", setupRoutes);
Expand Down
Loading
Loading