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
9 changes: 6 additions & 3 deletions docs/api-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@
"backgroundUrl": "",
"logoUrl": "",
"theme": "system",
"columns": 0
"columns": 0,
"searchNewTab": true
}
}
```
Expand Down Expand Up @@ -112,8 +113,10 @@ Passkey(WebAuthn,/api/auth/passkey/*,@simplewebauthn/server v14):

### 站点设置

- `GET /api/admin/settings` → `{siteTitle, backgroundUrl, logoUrl, theme, columns}`
- `PUT /api/admin/settings` body 可含 `{siteTitle, backgroundUrl, logoUrl, theme(light|dark|system), columns(0–12)}` → 更新后对象
- `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)}` → 更新后对象

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

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

Expand Down
17 changes: 17 additions & 0 deletions web/src/components/admin/settings-panels.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,8 @@ export function SettingsPanel({
const [form, setForm] = React.useState<SiteSettings>({
...settings,
logoUrl: settings.logoUrl ?? "",
// 旧数据 / 旧 mock 可能没有该字段:契约默认开
searchNewTab: settings.searchNewTab ?? true,
});

const save = async () => {
Expand Down Expand Up @@ -321,6 +323,21 @@ export function SettingsPanel({
</Select>
</div>
</div>
<div className="flex items-start justify-between gap-4 rounded-lg border p-3">
<div className="grid gap-1">
<Label htmlFor="set-search-new-tab">搜索在新标签页打开</Label>
<p className="text-sm text-muted-foreground">
开启时搜索结果在新标签页打开,当前起始页与已展开的分类不会丢;关闭则沿用当前页跳转。
</p>
</div>
<Switch
id="set-search-new-tab"
checked={form.searchNewTab}
onCheckedChange={(searchNewTab) =>
setForm({ ...form, searchNewTab })
}
/>
</div>
</div>
<Button onClick={() => void save()} className="w-fit">
保存设置
Expand Down
7 changes: 6 additions & 1 deletion web/src/components/public-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,12 @@ export function PublicPage({ onOpenAdmin }: { onOpenAdmin: () => void }) {
(settings?.siteTitle ?? "我的导航")
)}
</h1>
{siteData && <SearchBar engines={siteData.searchEngines} />}
{siteData && (
<SearchBar
engines={siteData.searchEngines}
openInNewTab={siteData.settings.searchNewTab ?? true}
/>
)}
</FadeIn>

{/* 导航区:登录后为全量分类(公开+私有),私有分类带「私有」标识 */}
Expand Down
21 changes: 16 additions & 5 deletions web/src/components/search-bar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,17 @@ import type { SearchEngine } from "@/lib/types";

/**
* 顶部多引擎搜索框:引擎切换(下拉)、`/` 键全局聚焦、Enter 按 {q} 模板跳转。
*
* `openInNewTab`(站点设置 `searchNewTab`,默认开):开时结果在新标签页打开,
* 起始页与会话保留;关时沿用当前页跳转。两种方式对所有引擎(含自定义)一致生效。
*/
export function SearchBar({ engines }: { engines: SearchEngine[] }) {
export function SearchBar({
engines,
openInNewTab = true,
}: {
engines: SearchEngine[];
openInNewTab?: boolean;
}) {
const inputRef = React.useRef<HTMLInputElement>(null);
const [engineId, setEngineId] = React.useState<string | null>(null);
const [query, setQuery] = React.useState("");
Expand Down Expand Up @@ -47,10 +56,12 @@ export function SearchBar({ engines }: { engines: SearchEngine[] }) {
e.preventDefault();
const q = query.trim();
if (!q || !engine) return;
window.location.href = engine.urlTemplate.replace(
"{q}",
encodeURIComponent(q),
);
const url = engine.urlTemplate.replace("{q}", encodeURIComponent(q));
if (openInNewTab) {
window.open(url, "_blank", "noopener,noreferrer");
return;
}
window.location.href = url;
};

return (
Expand Down
10 changes: 9 additions & 1 deletion web/src/lib/mockDb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,14 +151,22 @@ function seed(): MockState {
logoUrl: "",
theme: "system",
columns: 8,
searchNewTab: true,
},
};
}

function load(): MockState {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) return JSON.parse(raw) as MockState;
if (raw) {
// 旧 mock 库没有 searchNewTab:按契约默认开补齐,避免界面读到 undefined
const state = JSON.parse(raw) as Omit<MockState, "settings"> & {
settings: Partial<SiteSettings>;
};
state.settings = { searchNewTab: true, ...state.settings };
return state as MockState;
}
} catch {
/* fall through to seed */
}
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 @@ -46,6 +46,8 @@ export interface SiteSettings {
theme: "system" | "light" | "dark";
/** 0–12(后端接受并原样存储),0 表示未配置(用默认值) */
columns: number;
/** 搜索在新标签页打开(后端 KV `search_new_tab`,无此键时为 true) */
searchNewTab: boolean;
}

export interface SiteData {
Expand Down
71 changes: 70 additions & 1 deletion web/test/public-page.test.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { PublicPage } from "@/components/public-page";
import { useNavStore } from "@/lib/nav-store";
import type { SiteSettings } from "@/lib/types";
import type { SearchEngine, SiteSettings } from "@/lib/types";

vi.mock("sonner", () => ({
toast: { success: vi.fn(), error: vi.fn() },
Expand All @@ -14,6 +15,7 @@ const baseSettings: SiteSettings = {
logoUrl: "",
theme: "system",
columns: 6,
searchNewTab: true,
};

function seed(settings: SiteSettings) {
Expand Down Expand Up @@ -51,3 +53,70 @@ describe("PublicPage 头部:有 Logo 显示 Logo,无 Logo 显示标题文字
expect(within(heading).queryByRole("img")).toBeNull();
});
});

describe("PublicPage:搜索跳转方式跟随站点设置 searchNewTab", () => {
const engines: SearchEngine[] = [
{
id: "eng-google",
name: "Google",
urlTemplate: "https://www.google.com/search?q={q}",
icon: null,
sortOrder: 0,
isDefault: true,
},
];

function seedWithEngines(settings: SiteSettings) {
useNavStore.setState({
publicData: { categories: [], searchEngines: engines, settings },
privateData: null,
authStatus: "anonymous",
loginPromptOpen: false,
loadPublic: async () => {},
loadPrivate: async () => {},
});
}

async function submitSearch() {
const user = userEvent.setup();
await user.type(screen.getByLabelText("搜索关键词"), "nav{enter}");
}

it("searchNewTab=false:搜索在当前页跳转(不新开标签)", async () => {
seedWithEngines({ ...baseSettings, searchNewTab: false });
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
const location = { href: "http://localhost/start" };
Object.defineProperty(window, "location", {
configurable: true,
writable: true,
value: location as unknown as Location,
});

render(<PublicPage onOpenAdmin={vi.fn()} />);
await submitSearch();

expect(openSpy).not.toHaveBeenCalled();
expect(location.href).toBe("https://www.google.com/search?q=nav");
});

it("设置缺该字段(存量库)时按默认开:新标签打开", async () => {
seedWithEngines({ ...baseSettings, searchNewTab: undefined as never });
const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
const location = { href: "http://localhost/start" };
Object.defineProperty(window, "location", {
configurable: true,
writable: true,
value: location as unknown as Location,
});

render(<PublicPage onOpenAdmin={vi.fn()} />);
await submitSearch();

expect(openSpy).toHaveBeenCalledWith(
"https://www.google.com/search?q=nav",
"_blank",
"noopener,noreferrer",
);
expect(location.href).toBe("http://localhost/start");
});
});
138 changes: 138 additions & 0 deletions web/test/search-bar.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { SearchBar } from "@/components/search-bar";
import type { SearchEngine } from "@/lib/types";

/**
* 搜索跳转方式(站点设置 `searchNewTab`,默认开):
* - 开:`window.open(url, "_blank", "noopener,noreferrer")`,起始页与会话保留;
* - 关:沿用 `window.location.href` 当前页跳转。
* 两种方式都在 submit 的公共分支里,切换引擎(含自定义引擎)后行为一致。
*/

const google: SearchEngine = {
id: "eng-google",
name: "Google",
urlTemplate: "https://www.google.com/search?q={q}",
icon: null,
sortOrder: 0,
isDefault: true,
};

const custom: SearchEngine = {
id: "eng-custom",
name: "自建搜索",
urlTemplate: "https://search.example.com/?wd={q}&lang=zh",
icon: null,
sortOrder: 1,
isDefault: false,
};

const engines = [google, custom];

/** jsdom 不实现真实导航:把 location 换成可读 href 的桩,断言跳转目标。 */
function stubLocation() {
const location = { href: "http://localhost/start" };
Object.defineProperty(window, "location", {
configurable: true,
writable: true,
value: location as unknown as Location,
});
return location;
}

let openSpy: ReturnType<typeof vi.spyOn>;
let location: { href: string };

beforeEach(() => {
location = stubLocation();
openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
});

async function search(query: string) {
const user = userEvent.setup();
await user.type(screen.getByLabelText("搜索关键词"), `${query}{enter}`);
}

async function switchEngine(name: string) {
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: /当前搜索引擎/ }));
await user.click(await screen.findByRole("menuitem", { name }));
}

describe("SearchBar 跳转方式:默认新标签打开", () => {
it("回车在新标签页打开,当前页不动(noopener,noreferrer)", async () => {
render(<SearchBar engines={engines} />);

await search("react hooks");

expect(openSpy).toHaveBeenCalledWith(
"https://www.google.com/search?q=react%20hooks",
"_blank",
"noopener,noreferrer",
);
expect(location.href).toBe("http://localhost/start");
});

it("显式 openInNewTab={true} 同为新标签打开", async () => {
render(<SearchBar engines={engines} openInNewTab />);

await search("nav");

expect(openSpy).toHaveBeenCalledWith(
"https://www.google.com/search?q=nav",
"_blank",
"noopener,noreferrer",
);
expect(location.href).toBe("http://localhost/start");
});

it("切换引擎后仍是新标签打开,且用该引擎的模板", async () => {
render(<SearchBar engines={engines} />);

await switchEngine("自建搜索");
await search("nav 导航");

expect(openSpy).toHaveBeenCalledWith(
"https://search.example.com/?wd=nav%20%E5%AF%BC%E8%88%AA&lang=zh",
"_blank",
"noopener,noreferrer",
);
expect(location.href).toBe("http://localhost/start");
});
});

describe("SearchBar 跳转方式:关闭开关后当前页跳转", () => {
it("回车在当前页跳转,不新开标签", async () => {
render(<SearchBar engines={engines} openInNewTab={false} />);

await search("react hooks");

expect(openSpy).not.toHaveBeenCalled();
expect(location.href).toBe("https://www.google.com/search?q=react%20hooks");
});

it("切换引擎后仍是当前页跳转,且用该引擎的模板", async () => {
render(<SearchBar engines={engines} openInNewTab={false} />);

await switchEngine("自建搜索");
await search("nav 导航");

expect(openSpy).not.toHaveBeenCalled();
expect(location.href).toBe(
"https://search.example.com/?wd=nav%20%E5%AF%BC%E8%88%AA&lang=zh",
);
});
});

describe("SearchBar 边界:空查询", () => {
it("空查询 / 纯空格不跳转、不新开标签", async () => {
render(<SearchBar engines={engines} />);

await search(" ");

expect(openSpy).not.toHaveBeenCalled();
expect(location.href).toBe("http://localhost/start");
});
});
Loading
Loading