diff --git a/README.md b/README.md
index 23d26c4..d3ad93f 100644
--- a/README.md
+++ b/README.md
@@ -20,9 +20,9 @@ The Web app resolves the favicon dynamically so it follows the active System / L
## What's New in v1.6.1
-- **Personal Navigation Station (Public Page)**: Customize your public homepage (`/`) from **Settings → Public Page** (`/api/settings/public-page`) with a custom site title/subtitle, default layout (`grid`, `compact`, or `list`), search bar + external web search engine switcher (`Filter`, `Google`, `Bing`, `GitHub`, `DuckDuckGo`, `百度`), category navigation pills, and new-tab behavior. Visitors can switch layout, theme, and language locally without mutating owner data.
+- **Personal Navigation Station (Public Page)**: Customize your public homepage (`/`) from **Settings → Public Page** (`/api/settings/public-page`) with a custom site title/subtitle, default layout (`grid`, `compact`, or `list`), search bar + external web search engine switcher (`Filter`, `Google`, `Bing`, `GitHub`, `DuckDuckGo`, `百度`), category navigation pills, new-tab behavior, and up to 24 ordered **Pinned Favorites** (`pinnedBookmarkIds`). Visitors can switch layout, theme, language, and per-category collapse state (`dockmarkPublicCollapsedV1`, with **Collapse/Expand all** and automatic expansion while searching) locally without mutating owner data.
- **Dedicated Settings → AI Service (`/app/settings/ai`)**: Configure OpenAI-compatible AI providers in one central panel with 6 one-click presets (`OpenAI`, `DeepSeek`, `OpenRouter`, `SiliconFlow`, `Gemini`, `Groq`), D1-synced non-secret endpoint/model/timeout settings (`/api/settings/ai`), live `DOCKMARK_AI_API_KEY` Worker secret diagnostics, and quick links to Inbox AI Triage and Bookmarks Organize.
-- **Duplicate Review Archive/Undo & SPA Hash-Route Safety**: Duplicate detection preserves distinct SPA hash routes (e.g. `#/login` vs `#/monitoring`) while collapsing plain document anchors (`#section-1` vs `#section-2`). Compare pairs side-by-side with URL diff highlighting, filter by evidence type or Pinyin search, jump directly to **Locate in Library** (`/app/bookmarks?q=...`), and run 1-click **Keep A · Archive B** / **Keep B · Archive A** with inline Change Journal undo.
+- **Duplicate Review Tag/Description Merge, Archive/Undo & SPA Hash-Route Safety**: Duplicate detection preserves distinct SPA hash routes (e.g. `#/login` vs `#/monitoring`) while collapsing plain document anchors (`#section-1` vs `#section-2`). Compare pairs side-by-side with URL diff highlighting and `#tag` chips (highlighting tags unique to each side), filter by evidence type or Pinyin search, jump directly to **Locate in Library** (`/app/bookmarks?q=...`), and run 1-click **Keep A · Archive B** / **Keep B · Archive A** with optional pre-archive merging of unique tags (up to 12) and missing descriptions plus full inline **Undo** (restoring the archived bookmark and reverting any merged metadata).
- **Zero-Dependency Pinyin Initial Search**: Match Chinese bookmark, workspace, collection, tab, and `#tag` titles by Hanzi initials (e.g. typing `zhzl` finds `知乎专栏`) consistently across Web Launcher, Bookmark Library, Public Page, New Tab, and Extension Popup Open Tabs.
- **Modular WXT TypeScript New Tab & UI Polish**: Replaced the 7 legacy hand-patched New Tab scripts with a single WXT-compiled TypeScript bundle (`newtab-app.js` from `apps/extension/entrypoints/newtab-app.ts` + `lib/newtab/*.ts`) sharing `@dockmark/core`, paired with customizable launcher shortcuts (`⌘K` / `⌘J` / `Alt+K` + `/` focus), outer-only `:focus-within` composite search bars (zero inner focus outline), and unified custom `` styling.
diff --git a/apps/web/GEMINI.md b/apps/web/GEMINI.md
index 0879ed6..2f3a49f 100644
--- a/apps/web/GEMINI.md
+++ b/apps/web/GEMINI.md
@@ -19,13 +19,14 @@ src/main.tsx: SPA bootstrapper applying local appearance/locale before paint, bi
src/PrivateRoot.tsx: Session auth gate (`LoginCard`, `SetupRequired`) and sticky 46px private utility bar with inbox badge and 1-click theme/locale quick-toggles
src/App.tsx: Authenticated workspace shell with sticky 64px topbar, Raycast-style command bar (`!bang`, `@collection`, `#tag`, Pinyin initials, customizable `launcherShortcut`/`slashFocus`), keyboard-navigable results, and section router
src/LauncherDashboard.tsx: Command ranking (`buildLauncherResults`), keyboard-navigable `LauncherCommandPanel`, empty-query dashboard (open tabs, workspaces, filterable bookmarks), and `SafeFavicon`
-src/PublicPage.tsx: Read-only Personal Navigation Station (`/`) loading `/api/settings/public-page` + `/api/public/bookmarks` with customizable site title/subtitle, Pinyin search + web engine switcher, category nav pills, visitor-local 3-way layout (`grid`/`compact`/`list`), `usePublicI18n()`, and local theme toggle
+src/PublicPage.tsx: Read-only Personal Navigation Station (`/`) loading `/api/settings/public-page` + `/api/public/bookmarks` with customizable site title/subtitle, ordered `★ Pinned Favorites` section, collapsible category headers persisted in visitor-local `dockmarkPublicCollapsedV1` (with Collapse/Expand all and search auto-expand), Pinyin search + web engine switcher, category nav pills, visitor-local 3-way layout (`grid`/`compact`/`list`), `usePublicI18n()`, and local theme toggle
src/SettingsPage.tsx: Client-side `/app/settings/*` router coordinating 5 tabs: Appearance & Language, Browser, AI Service, Security, and Public Page
src/AppearanceSettings.tsx: Theme (`System / Light / Dark`) and Language (`System / English / 简体中文`) selector cards synced via `PATCH /api/settings/appearance`
src/BrowserSettingsManager.tsx: Local-first and D1-synced New Tab launcher limits, default engine, launcher shortcut (`⌘K`/`⌘J`/`Alt+K` + `/` focus), and bookmark conflict policy settings
-src/AiProviderSettingsPage.tsx: Dedicated `/app/settings/ai` panel with 6 OpenAI-compatible provider presets, D1-synced non-secret endpoint/model/timeout form (`saveCloudAiSettings`), `DOCKMARK_AI_API_KEY` Worker secret status check, and Inbox/Organize quick links
+src/AiProviderSettingsPage.tsx: Dedicated `/app/settings/ai` panel with 6 OpenAI-compatible provider presets, D1-synced non-secret endpoint/model/timeout form (`saveCloudAiSettings`), `Default / Local` vs `Cloud synced` state badge, wrapped `DOCKMARK_AI_API_KEY` Worker secret status check, and Inbox/Organize quick links
src/SecuritySettings.tsx: One-time extension pairing code generator and active/revoked paired-device management
-src/PublicPageSettings.tsx: Personal Navigation Station appearance/behavior editor (`/api/settings/public-page`), single and bulk bookmark publication manager, and canonical category/bookmark public ordering
+src/PublicPageSettings.tsx: Personal Navigation Station settings view orchestrating `PublicSiteConfigCard`, ordered `★ Pinned Favorites` curation (up to `MAX_PUBLIC_PINNED_BOOKMARKS = 24`), single and bulk bookmark publication, and canonical category/bookmark public ordering
+src/PublicSiteConfigCard.tsx: Extracted top configuration card for `PublicPageSettings` editing public root (`/`) site title/subtitle, default layout, search bar, web search, category nav, and new-tab behavior
src/BrowserExtensionManager.tsx: Extension hub (`/app/extension`) with Chromium New Tab, Chromium Standard, and Firefox MV3 profiles, install guide, and live bridge diagnostics
## `src/` — Library, Workspace & Triage Managers
@@ -48,7 +49,8 @@ src/NativeBookmarkSyncPanels.tsx: Extracted mapping preview (`NativeMappingPrevi
src/InboxPage.tsx: Capture Inbox triage view with cloud-hydrated AI provider status, `/app/settings/ai` quick link, metadata review, and filing/archiving actions
src/InboxReviewCard.tsx: Single-bookmark Inbox review card handling filing, AI triage selection, and opt-in metadata suggestions
src/SmartCollectionsPage.tsx: Saved dynamic filter collection builder, live preview, and bulk handoff
-src/DuplicateReviewPage.tsx: Duplicate URL group detector with Pinyin search, segmented evidence filters, side-by-side URL diff highlighting, 1-click Keep & Archive with Change Journal undo, and Locate in Library handoff
+src/DuplicateReviewPage.tsx: Duplicate URL group review workbench with Pinyin search, segmented evidence filters, atomic-style tag/description merge + Keep & Archive execution, full Undo (restoring archived bookmark and reverting merged metadata), and Locate in Library handoff
+src/DuplicateCandidateCard.tsx: Extracted duplicate pair comparison card (`computeDuplicateMerge`) displaying side-by-side URL diff highlighting, unique `#tag` chips, contextual merge preview toggle, and Keep/Archive actions
## `src/` — Client Data, Bridge, Theme & i18n Modules
src/i18n.ts: Web locale state (`dockmarkLocaleV1`, `dockmarkPublicLocaleV1`), cloud sync, `useI18n()`, and visitor-only `usePublicI18n()`
@@ -63,7 +65,7 @@ src/bookmark-details-api.ts: Composite bookmark + tag mutation API client
src/bookmark-search.ts: Tokenized bookmark, `#tag`, and Hanzi Pinyin initial client-side search predicates
src/bookmark-transfer.ts: Netscape HTML and Dockmark JSON bookmark parsers and serializers
src/change-journal-api.ts: Change journal listing API client
-src/duplicate-review-api.ts: Duplicate group listing (`iconUrl`, timestamps) and resolution API client
+src/duplicate-review-api.ts: Duplicate group listing (`iconUrl`, `tags`, timestamps) and resolution API client
src/inbox-api.ts: Capture Inbox listing, count, filing, and `INBOX_CHANGED_EVENT` broadcaster
src/library-batch-api.ts: Bulk library category/tag batch API client
src/library-maintenance-api.ts: Archived bookmark listing and bulk maintenance API client
@@ -80,10 +82,10 @@ src/theme.css: Dark (`#0a0f0c`) and light (`#f4f7f5`) semantic `--dm-*` design t
src/ui-polish.css: Outer-only `:focus-within` rings for composite search boxes (zero inner outline), custom SVG-chevron `` styling, reusable `.dm-search-box`, and light-theme surface alignment
src/light-theme-consistency.css: Light-theme overrides for Extension, Transfer, Auth, and Public Page curation cards
src/responsive-shell.css: Sticky 46px utility bar, sticky 64px topbar (`top: 46px`), 128px sticky sidebar offset, and 900/720/520px responsive nav rules
-src/settings.css: 5-tab Settings subnav, preference cards, AI provider preset grid, segmented controls, and public curation layout styles
+src/settings.css: 5-tab Settings subnav, preference cards, overflow-safe AI provider/secret grid, segmented controls, and public pinning/curation layout styles
src/security.css: Private utility bar, quick theme/locale pills, auth screens, and paired-device list styles
src/extension.css: Extension hub hero, profile cards, installation guide, diagnostics, and compact launcher nudge strip
-src/public-page.css: Personal Navigation Station topbar, visitor controls, Pinyin/web search bar, category nav pills, and `grid`/`compact`/`list` layouts
+src/public-page.css: Personal Navigation Station topbar, visitor controls, Pinyin/web search bar, category nav pills, `★ Pinned Favorites` section, collapsible group headers, and `grid`/`compact`/`list` layouts
src/*.css (feature sheets): Scoped styles for `ai-organization`, `bookmark-tags`, `bridge`, `change-journal`, `duplicate-review`, `health`, `inbox`, `library-bulk`, `maintenance`, `reorder`, `search-engines`, `session`, `smart-collections`, `transfer`, and `workspaces`
[PROTOCOL]: Update this header on change, then check GEMINI.md
diff --git a/apps/web/src/AiProviderSettingsPage.tsx b/apps/web/src/AiProviderSettingsPage.tsx
index 4e482dd..fb66ffe 100644
--- a/apps/web/src/AiProviderSettingsPage.tsx
+++ b/apps/web/src/AiProviderSettingsPage.tsx
@@ -223,7 +223,13 @@ export function AiProviderSettingsPage() {
- {isDirty ? tx("Unsaved edits", "有未保存修改") : tx("Cloud synced", "云端已同步")}
+
+ {isDirty
+ ? tx("Unsaved edits", "有未保存修改")
+ : settings.updatedAt
+ ? tx("Cloud synced", "云端已同步")
+ : tx("Default / Local", "默认配置")}
+
{loading ? tx("Loading AI settings…", "正在加载配置…") : formatSyncTime(settings.updatedAt, locale, tx)}
@@ -333,29 +339,32 @@ export function AiProviderSettingsPage() {
-
+ DOCKMARK_AI_API_KEY
+
+
+ {apiKeyConfigured === true
+ ? tx("Ready", "已就绪")
: apiKeyConfigured === false
- ? "is-missing"
- : ""
- }`}
- >
-
- {apiKeyConfigured === true
- ? tx("DOCKMARK_AI_API_KEY · Ready", "DOCKMARK_AI_API_KEY · 已配置 Ready")
- : apiKeyConfigured === false
- ? tx("DOCKMARK_AI_API_KEY · Missing", "DOCKMARK_AI_API_KEY · 未配置 Missing")
- : tx("Checking status…", "正在检测状态…")}
-
+ ? tx("Not set", "未配置")
+ : tx("Checking…", "检测中…")}
+
+
void recheckStatus()}
>
- {checkingKey ? tx("Checking…", "检测中…") : tx("Recheck status", "重新检测状态")}
+ {checkingKey ? tx("Checking…", "检测中…") : tx("Recheck", "重新检测")}
diff --git a/apps/web/src/DuplicateCandidateCard.tsx b/apps/web/src/DuplicateCandidateCard.tsx
new file mode 100644
index 0000000..0cb2c7b
--- /dev/null
+++ b/apps/web/src/DuplicateCandidateCard.tsx
@@ -0,0 +1,443 @@
+/**
+ * [INPUT]: depends on useMemo, useState, type ReactNode from react; formatRelativeTime, HEALTH_POLICY_LABELS, HEALTH_STATUS_LABELS, type ResolvedLocale from @dockmark/core; BookmarkFavicon, safeDomainLabel from ./BookmarkFavicon; MAX_BOOKMARK_TAGS from ./bookmark-details-api; type DuplicateCandidateKind, DuplicateReviewCandidate, DuplicateReviewMember from ./duplicate-review-api
+ * [OUTPUT]: exports computeDuplicateMerge, DuplicateMergePlan, and DuplicateCandidateCard component
+ * [POS]: Per-pair duplicate candidate card with URL diff highlighting, unique-tag chips, contextual merge toggle/preview, and keep/archive controls for DuplicateReviewPage
+ * [PROTOCOL]: Update this header on change, then check GEMINI.md
+ */
+
+import { useMemo, useState, type ReactNode } from "react";
+import {
+ formatRelativeTime,
+ HEALTH_POLICY_LABELS,
+ HEALTH_STATUS_LABELS,
+ type ResolvedLocale,
+} from "@dockmark/core";
+import { BookmarkFavicon, safeDomainLabel } from "./BookmarkFavicon";
+import { MAX_BOOKMARK_TAGS } from "./bookmark-details-api";
+import type {
+ DuplicateCandidateKind,
+ DuplicateReviewCandidate,
+ DuplicateReviewMember,
+} from "./duplicate-review-api";
+
+type TxFn = (en: string, zh: string) => string;
+
+export interface DuplicateMergePlan {
+ tagsToAdd: string[];
+ droppedTagCount: number;
+ adoptDescription: string | null;
+ hasMergeableData: boolean;
+}
+
+export function computeDuplicateMerge(
+ keeper: DuplicateReviewMember,
+ archived: DuplicateReviewMember,
+): DuplicateMergePlan {
+ const keeperTags = keeper.tags ?? [];
+ const archivedTags = archived.tags ?? [];
+ const seenLower = new Set(keeperTags.map((tag) => tag.toLocaleLowerCase()));
+ const uniqueFromArchived: string[] = [];
+
+ for (const tag of archivedTags) {
+ const trimmed = tag.trim();
+ if (!trimmed) continue;
+ const key = trimmed.toLocaleLowerCase();
+ if (seenLower.has(key)) continue;
+ seenLower.add(key);
+ uniqueFromArchived.push(trimmed);
+ }
+
+ const availableSlots = Math.max(0, MAX_BOOKMARK_TAGS - keeperTags.length);
+ const tagsToAdd = uniqueFromArchived.slice(0, availableSlots);
+ const droppedTagCount = uniqueFromArchived.length - tagsToAdd.length;
+ const trimmedArchivedDesc = archived.description?.trim() ?? "";
+ const adoptDescription = !(keeper.description?.trim()) && trimmedArchivedDesc
+ ? trimmedArchivedDesc
+ : null;
+ const hasMergeableData = tagsToAdd.length > 0 || adoptDescription !== null;
+
+ return { tagsToAdd, droppedTagCount, adoptDescription, hasMergeableData };
+}
+
+const KNOWN_REASON_ZH: Record = {
+ "Saved page metadata points these bookmarks at the same canonical target.":
+ "已保存的页面元数据显示这两条书签指向同一个规范链接目标。",
+ "Saved metadata shows these bookmarks resolving to the same final target.":
+ "已保存的页面元数据显示这两条书签最终跳转到同一个目标地址。",
+ "The URLs become equivalent after ignoring protocol/www, fragments, trailing slashes and known tracking parameters.":
+ "忽略协议/www、文档锚点、末尾斜杠及常见追踪参数后,两条链接等价。",
+};
+
+function kindLabel(kind: DuplicateCandidateKind, tx: TxFn): string {
+ switch (kind) {
+ case "canonical":
+ return tx("Canonical target", "规范链接");
+ case "resolved":
+ return tx("Resolved target", "跳转目标");
+ case "normalized":
+ return tx("URL variant", "URL 变体");
+ }
+}
+
+function kindDescription(kind: DuplicateCandidateKind, tx: TxFn): string {
+ switch (kind) {
+ case "canonical":
+ return tx("Strong metadata evidence", "强元数据依据");
+ case "resolved":
+ return tx("Redirect / final-URL evidence", "重定向 / 最终地址依据");
+ case "normalized":
+ return tx("Conservative URL normalization", "保守 URL 归一化");
+ }
+}
+
+function localizedReason(candidate: DuplicateReviewCandidate, isZh: boolean): string {
+ if (!isZh) return candidate.reason;
+ return KNOWN_REASON_ZH[candidate.reason] ?? candidate.reason;
+}
+
+function healthPolicyLabel(policy: string, locale: ResolvedLocale): string {
+ const labels = HEALTH_POLICY_LABELS[locale] as Record;
+ return labels[policy] ?? policy;
+}
+
+function healthStatusLabel(status: string, locale: ResolvedLocale): string {
+ const labels = HEALTH_STATUS_LABELS[locale] as Record;
+ return labels[status] ?? status;
+}
+
+function formatFullDate(value: string, locale: ResolvedLocale): string {
+ const date = new Date(value);
+ if (Number.isNaN(date.getTime())) return value;
+ return new Intl.DateTimeFormat(locale, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ hour: "2-digit",
+ minute: "2-digit",
+ }).format(date);
+}
+
+function renderUrlWithDiff(url: string, otherUrl: string): ReactNode {
+ const leftChars = Array.from(url);
+ const rightChars = Array.from(otherUrl);
+ let prefixLen = 0;
+ while (
+ prefixLen < leftChars.length &&
+ prefixLen < rightChars.length &&
+ leftChars[prefixLen] === rightChars[prefixLen]
+ ) {
+ prefixLen += 1;
+ }
+
+ let suffixLen = 0;
+ while (
+ suffixLen < leftChars.length - prefixLen &&
+ suffixLen < rightChars.length - prefixLen &&
+ leftChars[leftChars.length - 1 - suffixLen] === rightChars[rightChars.length - 1 - suffixLen]
+ ) {
+ suffixLen += 1;
+ }
+
+ const diff = leftChars.slice(prefixLen, leftChars.length - suffixLen).join("");
+ if (!diff) return url;
+ const prefix = leftChars.slice(0, prefixLen).join("");
+ const suffix = suffixLen > 0 ? leftChars.slice(leftChars.length - suffixLen).join("") : "";
+
+ return (
+ <>
+ {prefix}
+ {diff}
+ {suffix}
+ >
+ );
+}
+
+function MemberCard({
+ side,
+ bookmark,
+ otherBookmark,
+ locale,
+ tx,
+}: {
+ side: "left" | "right";
+ bookmark: DuplicateReviewMember;
+ otherBookmark: DuplicateReviewMember;
+ locale: ResolvedLocale;
+ tx: TxFn;
+}) {
+ const timestamp = bookmark.updatedAt ?? bookmark.createdAt ?? null;
+ const relativeUpdated = timestamp ? formatRelativeTime(timestamp, locale) : null;
+ const tags = bookmark.tags ?? [];
+ const otherTagSet = useMemo(
+ () => new Set((otherBookmark.tags ?? []).map((tag) => tag.toLocaleLowerCase())),
+ [otherBookmark.tags],
+ );
+
+ return (
+
+
+
+
+
+ {side === "left" ? "A" : "B"}
+ {bookmark.title}
+
+
+ {safeDomainLabel(bookmark.url)}
+
+ {bookmark.categoryName ?? tx("Uncategorized", "未分类")}
+
+
+ {healthPolicyLabel(bookmark.healthPolicy, locale)} · {healthStatusLabel(bookmark.healthStatus, locale)}
+
+ {relativeUpdated && timestamp && (
+
+ {tx(`Updated ${relativeUpdated}`, `更新于 ${relativeUpdated}`)}
+
+ )}
+
+
+
+
+
+ {renderUrlWithDiff(bookmark.url, otherBookmark.url)}
+
+ {bookmark.description && {bookmark.description}
}
+
+ {tags.length > 0 && (
+
+ {tags.map((tag) => {
+ const isUnique = !otherTagSet.has(tag.toLocaleLowerCase());
+ return (
+
+ #{tag}
+
+ );
+ })}
+
+ )}
+
+ {(bookmark.canonicalUrl || bookmark.finalUrl || bookmark.metadataFetchedAt) && (
+
+ {bookmark.canonicalUrl && (
+
+ {tx("Canonical", "规范链接")}
+ {bookmark.canonicalUrl}
+
+ )}
+ {bookmark.finalUrl && (
+
+ {tx("Resolved", "最终跳转")}
+ {bookmark.finalUrl}
+
+ )}
+ {bookmark.metadataFetchedAt && (
+
+ {tx(
+ `Metadata fetched ${formatFullDate(bookmark.metadataFetchedAt, locale)}`,
+ `元数据抓取于 ${formatFullDate(bookmark.metadataFetchedAt, locale)}`,
+ )}
+
+ )}
+
+ )}
+
+ );
+}
+
+function MergePreviewRow({
+ sideLabel,
+ plan,
+ tx,
+}: {
+ sideLabel: string;
+ plan: DuplicateMergePlan;
+ tx: TxFn;
+}) {
+ if (!plan.hasMergeableData && plan.droppedTagCount === 0) return null;
+
+ return (
+
+
{sideLabel}
+
+ {plan.tagsToAdd.map((tag) => (
+
+ +#{tag}
+
+ ))}
+ {plan.adoptDescription !== null && (
+
+ {tx("+description", "+补充描述")}
+
+ )}
+ {plan.droppedTagCount > 0 && (
+
+ {tx(
+ `+${plan.droppedTagCount} skipped (max ${MAX_BOOKMARK_TAGS} tags)`,
+ `上限 ${MAX_BOOKMARK_TAGS} 个标签(跳过 ${plan.droppedTagCount} 个)`,
+ )}
+
+ )}
+
+
+ );
+}
+
+export interface DuplicateCandidateCardProps {
+ candidate: DuplicateReviewCandidate;
+ locale: ResolvedLocale;
+ isZh: boolean;
+ tx: TxFn;
+ archiving: boolean;
+ actionsDisabled: boolean;
+ onHide: (id: string) => void;
+ onArchive: (candidate: DuplicateReviewCandidate, keepSide: "left" | "right", mergeEnabled: boolean) => void;
+ onLocate: (title: string) => void;
+}
+
+export function DuplicateCandidateCard({
+ candidate,
+ locale,
+ isZh,
+ tx,
+ archiving,
+ actionsDisabled,
+ onHide,
+ onArchive,
+ onLocate,
+}: DuplicateCandidateCardProps) {
+ const [mergeEnabled, setMergeEnabled] = useState(true);
+ const keepLeftPlan = useMemo(
+ () => computeDuplicateMerge(candidate.left, candidate.right),
+ [candidate.left, candidate.right],
+ );
+ const keepRightPlan = useMemo(
+ () => computeDuplicateMerge(candidate.right, candidate.left),
+ [candidate.left, candidate.right],
+ );
+ const showMergeBar = keepLeftPlan.hasMergeableData || keepRightPlan.hasMergeableData;
+
+ return (
+
+
+
+
+ {kindLabel(candidate.kind, tx)}
+ {kindDescription(candidate.kind, tx)}
+
+
{localizedReason(candidate, isZh)}
+ {candidate.evidenceUrl && (
+
{candidate.evidenceUrl}
+ )}
+
+ onHide(candidate.id)}
+ >
+ {tx("Hide for now", "暂时隐藏")}
+
+
+
+
+
+ ≈
+
+
+
+
+ {showMergeBar && (
+
+
+ setMergeEnabled(event.target.checked)}
+ />
+
+ {tx(
+ "Merge unique tags & missing description into kept bookmark",
+ "归档前将对方独有标签与缺失描述合并至保留项",
+ )}
+
+
+
+
+
+
+
+ )}
+
+
+
+ onArchive(candidate, "left", mergeEnabled)}
+ >
+ {archiving ? tx("Archiving…", "归档中…") : tx("Keep A · Archive B", "保留 A · 归档 B")}
+
+ onArchive(candidate, "right", mergeEnabled)}
+ >
+ {archiving ? tx("Archiving…", "归档中…") : tx("Keep B · Archive A", "保留 B · 归档 A")}
+
+
+
+
+
+
+ );
+}
diff --git a/apps/web/src/DuplicateReviewPage.tsx b/apps/web/src/DuplicateReviewPage.tsx
index c702380..f210f5e 100644
--- a/apps/web/src/DuplicateReviewPage.tsx
+++ b/apps/web/src/DuplicateReviewPage.tsx
@@ -1,24 +1,19 @@
/**
- * [INPUT]: depends on useEffect, useMemo, useState from react; formatRelativeTime, HEALTH_POLICY_LABELS, HEALTH_STATUS_LABELS, ResolvedLocale from @dockmark/core; textMatchesQuery from ./bookmark-search; maintainLibraryBatch from ./library-maintenance-api; getDuplicateReview and DuplicateReview types from ./duplicate-review-api; useI18n from ./i18n; BookmarkFavicon, safeDomainLabel from ./BookmarkFavicon; ./duplicate-review.css
- * [OUTPUT]: exports DuplicateReviewPage component for side-by-side duplicate bookmark inspection, URL diff highlighting, safe reviewed archive/undo, and Library deep-linking
- * [POS]: top-level /app/duplicates workspace; never auto-mutates bookmarks and records explicit archive/restore actions in the Change Journal
+ * [INPUT]: depends on useEffect, useMemo, useState from react; type HealthPolicy from @dockmark/core; updateBookmarkWithTags from ./bookmark-details-api; textMatchesQuery from ./bookmark-search; computeDuplicateMerge, DuplicateCandidateCard from ./DuplicateCandidateCard; getDuplicateReview and DuplicateReview types from ./duplicate-review-api; useI18n from ./i18n; maintainLibraryBatch from ./library-maintenance-api; ./duplicate-review.css
+ * [OUTPUT]: exports DuplicateReviewPage component for side-by-side duplicate bookmark inspection, optional tag/description merging before archive, atomic-style undo, and Library deep-linking
+ * [POS]: top-level /app/duplicates workspace; never auto-mutates bookmarks and supports reversible tag/description merge + archive with Change Journal tracking
* [PROTOCOL]: Update this header on change, then check GEMINI.md
*/
-import { useEffect, useMemo, useState, type ReactNode } from "react";
-import {
- formatRelativeTime,
- HEALTH_POLICY_LABELS,
- HEALTH_STATUS_LABELS,
- type ResolvedLocale,
-} from "@dockmark/core";
-import { BookmarkFavicon, safeDomainLabel } from "./BookmarkFavicon";
+import { useEffect, useMemo, useState } from "react";
+import type { HealthPolicy } from "@dockmark/core";
+import { updateBookmarkWithTags } from "./bookmark-details-api";
import { textMatchesQuery } from "./bookmark-search";
+import { computeDuplicateMerge, DuplicateCandidateCard } from "./DuplicateCandidateCard";
import {
getDuplicateReview,
type DuplicateCandidateKind,
type DuplicateReviewCandidate,
- type DuplicateReviewMember,
type DuplicateReviewResult,
} from "./duplicate-review-api";
import { useI18n } from "./i18n";
@@ -27,103 +22,23 @@ import "./duplicate-review.css";
type TxFn = (en: string, zh: string) => string;
+interface KeeperSnapshot {
+ id: string;
+ title: string;
+ url: string;
+ description: string | null;
+ categoryId: string | null;
+ healthPolicy: HealthPolicy;
+ tags: string[];
+}
+
interface ArchiveNotice {
archivedId: string;
archivedTitle: string;
keptTitle: string;
-}
-
-const KNOWN_REASON_ZH: Record = {
- "Saved page metadata points these bookmarks at the same canonical target.":
- "已保存的页面元数据显示这两条书签指向同一个规范链接目标。",
- "Saved metadata shows these bookmarks resolving to the same final target.":
- "已保存的页面元数据显示这两条书签最终跳转到同一个目标地址。",
- "The URLs become equivalent after ignoring protocol/www, fragments, trailing slashes and known tracking parameters.":
- "忽略协议/www、文档锚点、末尾斜杠及常见追踪参数后,两条链接等价。",
-};
-
-function kindLabel(kind: DuplicateCandidateKind, tx: TxFn): string {
- switch (kind) {
- case "canonical":
- return tx("Canonical target", "规范链接");
- case "resolved":
- return tx("Resolved target", "跳转目标");
- case "normalized":
- return tx("URL variant", "URL 变体");
- }
-}
-
-function kindDescription(kind: DuplicateCandidateKind, tx: TxFn): string {
- switch (kind) {
- case "canonical":
- return tx("Strong metadata evidence", "强元数据依据");
- case "resolved":
- return tx("Redirect / final-URL evidence", "重定向 / 最终地址依据");
- case "normalized":
- return tx("Conservative URL normalization", "保守 URL 归一化");
- }
-}
-
-function localizedReason(candidate: DuplicateReviewCandidate, isZh: boolean): string {
- if (!isZh) return candidate.reason;
- return KNOWN_REASON_ZH[candidate.reason] ?? candidate.reason;
-}
-
-function healthPolicyLabel(policy: string, locale: ResolvedLocale): string {
- const labels = HEALTH_POLICY_LABELS[locale] as Record;
- return labels[policy] ?? policy;
-}
-
-function healthStatusLabel(status: string, locale: ResolvedLocale): string {
- const labels = HEALTH_STATUS_LABELS[locale] as Record;
- return labels[status] ?? status;
-}
-
-function formatFullDate(value: string, locale: ResolvedLocale): string {
- const date = new Date(value);
- if (Number.isNaN(date.getTime())) return value;
- return new Intl.DateTimeFormat(locale, {
- year: "numeric",
- month: "short",
- day: "numeric",
- hour: "2-digit",
- minute: "2-digit",
- }).format(date);
-}
-
-function renderUrlWithDiff(url: string, otherUrl: string): ReactNode {
- const leftChars = Array.from(url);
- const rightChars = Array.from(otherUrl);
- let prefixLen = 0;
- while (
- prefixLen < leftChars.length &&
- prefixLen < rightChars.length &&
- leftChars[prefixLen] === rightChars[prefixLen]
- ) {
- prefixLen += 1;
- }
-
- let suffixLen = 0;
- while (
- suffixLen < leftChars.length - prefixLen &&
- suffixLen < rightChars.length - prefixLen &&
- leftChars[leftChars.length - 1 - suffixLen] === rightChars[rightChars.length - 1 - suffixLen]
- ) {
- suffixLen += 1;
- }
-
- const diff = leftChars.slice(prefixLen, leftChars.length - suffixLen).join("");
- if (!diff) return url;
- const prefix = leftChars.slice(0, prefixLen).join("");
- const suffix = suffixLen > 0 ? leftChars.slice(leftChars.length - suffixLen).join("") : "";
-
- return (
- <>
- {prefix}
- {diff}
- {suffix}
- >
- );
+ mergedTagCount: number;
+ mergedDescription: boolean;
+ keeperSnapshot: KeeperSnapshot | null;
}
function matches(candidate: DuplicateReviewCandidate, query: string): boolean {
@@ -131,9 +46,11 @@ function matches(candidate: DuplicateReviewCandidate, query: string): boolean {
candidate.left.title,
candidate.left.url,
candidate.left.categoryName ?? "",
+ ...(candidate.left.tags ?? []),
candidate.right.title,
candidate.right.url,
candidate.right.categoryName ?? "",
+ ...(candidate.right.tags ?? []),
candidate.evidenceUrl ?? "",
]);
}
@@ -143,83 +60,31 @@ function locateInLibrary(title: string) {
window.dispatchEvent(new PopStateEvent("popstate"));
}
-function MemberCard({
- side,
- bookmark,
- otherUrl,
- locale,
- tx,
-}: {
- side: "left" | "right";
- bookmark: DuplicateReviewMember;
- otherUrl: string;
- locale: ResolvedLocale;
- tx: TxFn;
-}) {
- const timestamp = bookmark.updatedAt ?? bookmark.createdAt ?? null;
- const relativeUpdated = timestamp ? formatRelativeTime(timestamp, locale) : null;
-
- return (
-
-
-
-
-
- {side === "left" ? "A" : "B"}
- {bookmark.title}
-
-
- {safeDomainLabel(bookmark.url)}
-
- {bookmark.categoryName ?? tx("Uncategorized", "未分类")}
-
-
- {healthPolicyLabel(bookmark.healthPolicy, locale)} · {healthStatusLabel(bookmark.healthStatus, locale)}
-
- {relativeUpdated && timestamp && (
-
- {tx(`Updated ${relativeUpdated}`, `更新于 ${relativeUpdated}`)}
-
- )}
-
-
-
-
-
- {renderUrlWithDiff(bookmark.url, otherUrl)}
-
- {bookmark.description && {bookmark.description}
}
-
- {(bookmark.canonicalUrl || bookmark.finalUrl || bookmark.metadataFetchedAt) && (
-
- {bookmark.canonicalUrl && (
-
- {tx("Canonical", "规范链接")}
- {bookmark.canonicalUrl}
-
- )}
- {bookmark.finalUrl && (
-
- {tx("Resolved", "最终跳转")}
- {bookmark.finalUrl}
-
- )}
- {bookmark.metadataFetchedAt && (
-
- {tx(
- `Metadata fetched ${formatFullDate(bookmark.metadataFetchedAt, locale)}`,
- `元数据抓取于 ${formatFullDate(bookmark.metadataFetchedAt, locale)}`,
- )}
-
- )}
-
- )}
-
+function formatArchiveNotice(notice: ArchiveNotice, tx: TxFn): string {
+ const { archivedTitle, keptTitle, mergedTagCount, mergedDescription } = notice;
+ if (mergedTagCount > 0 && mergedDescription) {
+ const tagWord = mergedTagCount === 1 ? "tag" : "tags";
+ return tx(
+ `Kept “${keptTitle}” and archived “${archivedTitle}” (merged ${mergedTagCount} unique ${tagWord} and description).`,
+ `已保留“${keptTitle}”并归档“${archivedTitle}”(已合并 ${mergedTagCount} 个独有标签与描述)。`,
+ );
+ }
+ if (mergedTagCount > 0) {
+ const tagWord = mergedTagCount === 1 ? "tag" : "tags";
+ return tx(
+ `Kept “${keptTitle}” and archived “${archivedTitle}” (merged ${mergedTagCount} unique ${tagWord}).`,
+ `已保留“${keptTitle}”并归档“${archivedTitle}”(已合并 ${mergedTagCount} 个独有标签)。`,
+ );
+ }
+ if (mergedDescription) {
+ return tx(
+ `Kept “${keptTitle}” and archived “${archivedTitle}” (merged missing description).`,
+ `已保留“${keptTitle}”并归档“${archivedTitle}”(已合并缺失描述)。`,
+ );
+ }
+ return tx(
+ `Archived “${archivedTitle}” (kept “${keptTitle}”). Recorded in Change Journal.`,
+ `已归档“${archivedTitle}”(保留“${keptTitle}”),记录已写入变更日志。`,
);
}
@@ -276,21 +141,58 @@ export function DuplicateReviewPage() {
setHiddenIds((current) => new Set(current).add(id));
}
- async function archiveDuplicate(candidate: DuplicateReviewCandidate, keepSide: "left" | "right") {
- const kept = candidate[keepSide];
+ async function archiveDuplicate(
+ candidate: DuplicateReviewCandidate,
+ keepSide: "left" | "right",
+ mergeEnabled: boolean,
+ ) {
+ const keeper = candidate[keepSide];
const archived = keepSide === "left" ? candidate.right : candidate.left;
+ const mergePlan = computeDuplicateMerge(keeper, archived);
+ const shouldMerge = mergeEnabled && mergePlan.hasMergeableData;
+ let keeperSnapshot: KeeperSnapshot | null = null;
+ let keeperMutated = false;
+
setBusyCandidateId(candidate.id);
setError(null);
setRestoreNotice(null);
try {
+ if (shouldMerge) {
+ keeperSnapshot = {
+ id: keeper.id,
+ title: keeper.title,
+ url: keeper.url,
+ description: keeper.description ?? null,
+ categoryId: keeper.categoryId,
+ healthPolicy: keeper.healthPolicy as HealthPolicy,
+ tags: [...(keeper.tags ?? [])],
+ };
+ await updateBookmarkWithTags(keeper.id, {
+ title: keeper.title,
+ url: keeper.url,
+ description: mergePlan.adoptDescription ?? keeper.description ?? null,
+ categoryId: keeper.categoryId,
+ healthPolicy: keeper.healthPolicy as HealthPolicy,
+ tags: [...(keeper.tags ?? []), ...mergePlan.tagsToAdd],
+ });
+ keeperMutated = true;
+ }
+
await maintainLibraryBatch({ bookmarkIds: [archived.id], action: "archive" });
setArchiveNotice({
archivedId: archived.id,
archivedTitle: archived.title,
- keptTitle: kept.title,
+ keptTitle: keeper.title,
+ mergedTagCount: shouldMerge ? mergePlan.tagsToAdd.length : 0,
+ mergedDescription: shouldMerge ? mergePlan.adoptDescription !== null : false,
+ keeperSnapshot,
});
await refresh({ keepHidden: true, keepNotices: true });
} catch (caught) {
+ if (keeperMutated && keeperSnapshot) {
+ const { id, ...revertInput } = keeperSnapshot;
+ await updateBookmarkWithTags(id, revertInput).catch(() => {});
+ }
setError(
caught instanceof Error
? caught.message
@@ -308,12 +210,21 @@ export function DuplicateReviewPage() {
setError(null);
try {
await maintainLibraryBatch({ bookmarkIds: [target.archivedId], action: "restore" });
+ if (target.keeperSnapshot) {
+ const { id, ...revertInput } = target.keeperSnapshot;
+ await updateBookmarkWithTags(id, revertInput);
+ }
setArchiveNotice(null);
setRestoreNotice(
- tx(
- `Restored “${target.archivedTitle}” back to your library.`,
- `已将「${target.archivedTitle}」恢复至书签库。`,
- ),
+ target.keeperSnapshot
+ ? tx(
+ `Restored “${target.archivedTitle}” and reverted merged metadata on “${target.keptTitle}”.`,
+ `已恢复“${target.archivedTitle}”,并撤销对“${target.keptTitle}”的合并改动。`,
+ )
+ : tx(
+ `Restored “${target.archivedTitle}” back to your library.`,
+ `已将“${target.archivedTitle}”恢复至书签库。`,
+ ),
);
await refresh({ keepHidden: true, keepNotices: true });
} catch (caught) {
@@ -342,8 +253,8 @@ export function DuplicateReviewPage() {
{tx("Duplicate Review", "重复项审查")}
{tx(
- "Compare saved URLs with canonical and resolved metadata evidence. Nothing mutates automatically — keep one side to safely archive the duplicate with instant undo and Change Journal tracking.",
- "结合规范链接与跳转目标元数据识别候选重复书签。不会自动修改数据,可手动保留一侧并安全归档另一侧,支持一键撤销与变更日志追踪。",
+ "Compare saved URLs with canonical and resolved metadata evidence. Nothing mutates automatically — keep one side to optionally merge unique tags and missing description before safely archiving the duplicate with instant undo.",
+ "结合规范链接与跳转目标元数据识别候选重复书签。不会自动修改数据,可手动保留一侧并在归档前合并独有标签与缺失描述,支持一键完整撤销。",
)}
@@ -367,12 +278,7 @@ export function DuplicateReviewPage() {
{archiveNotice && (
-
- {tx(
- `Archived “${archiveNotice.archivedTitle}” (kept “${archiveNotice.keptTitle}”). Recorded in Change Journal.`,
- `已归档“${archiveNotice.archivedTitle}”(保留“${archiveNotice.keptTitle}”),记录已写入变更日志。`,
- )}
-
+
{formatArchiveNotice(archiveNotice, tx)}
void undoArchive()}
>
- {undoBusy ? tx("Restoring…", "撤销中…") : tx("Undo", "撤销归档")}
+ {undoBusy ? tx("Undoing…", "撤销中…") : tx("Undo", "撤销")}
setQuery(event.target.value)}
- placeholder={tx("Search title, URL, category, or Pinyin…", "搜索标题、链接、分类或拼音首字母…")}
+ placeholder={tx("Search title, URL, category, tag, or Pinyin…", "搜索标题、链接、分类、标签或拼音首字母…")}
aria-label={tx("Search review queue", "搜索审查列表")}
/>
{query && (
@@ -511,86 +417,22 @@ export function DuplicateReviewPage() {
{tx("Analyzing saved bookmark and metadata evidence…", "正在分析书签与页面元数据依据…")}
) : (
- visible.map((candidate) => {
- const archiving = busyCandidateId === candidate.id;
- return (
-
-
-
-
- {kindLabel(candidate.kind, tx)}
- {kindDescription(candidate.kind, tx)}
-
-
{localizedReason(candidate, isZh)}
- {candidate.evidenceUrl && (
-
{candidate.evidenceUrl}
- )}
-
- hide(candidate.id)}
- >
- {tx("Hide for now", "暂时隐藏")}
-
-
-
-
-
- ≈
-
-
-
-
-
- void archiveDuplicate(candidate, "left")}
- >
- {archiving ? tx("Archiving…", "归档中…") : tx("Keep A · Archive B", "保留 A · 归档 B")}
-
- void archiveDuplicate(candidate, "right")}
- >
- {archiving ? tx("Archiving…", "归档中…") : tx("Keep B · Archive A", "保留 B · 归档 A")}
-
-
-
-
-
- );
- })
+ visible.map((candidate) => (
+
{
+ void archiveDuplicate(target, keepSide, mergeEnabled);
+ }}
+ onLocate={locateInLibrary}
+ />
+ ))
)}
{!loading && result && visible.length === 0 && (
diff --git a/apps/web/src/PublicPage.tsx b/apps/web/src/PublicPage.tsx
index b731793..c146fab 100644
--- a/apps/web/src/PublicPage.tsx
+++ b/apps/web/src/PublicPage.tsx
@@ -1,7 +1,7 @@
/**
* [INPUT]: depends on AppearancePreference, PublicPageLayout, PublicPageSettings from @dockmark/core; textMatchesQuery from ./bookmark-search; usePublicI18n from ./i18n; hostLabel, SafeFavicon, safeHttpUrl from ./LauncherDashboard; public settings API/cache helpers from ./public-settings-api; theme helpers from ./theme; and ./public-page.css
- * [OUTPUT]: exports PublicPage Personal Navigation Station with custom branding, Pinyin-aware filter & web search engines, category jump pills, and visitor-local 3-mode layout switcher
- * [POS]: Public root route (/) rendered by main.tsx for visitors. Reads /api/public/bookmarks and /api/settings/public-page in parallel and never mutates owner D1 preferences.
+ * [OUTPUT]: exports PublicPage Personal Navigation Station with custom branding, Pinyin-aware filter & web search engines, pinned favorites section, collapsible category groups with visitor-local storage (dockmarkPublicCollapsedV1), category jump pills, and visitor-local 3-mode layout switcher
+ * [POS]: Public root route (/) rendered by main.tsx for visitors. Reads /api/public/bookmarks and /api/settings/public-page in parallel and keeps visitor layout and collapsed-group memory strictly local without mutating owner D1 preferences.
* [PROTOCOL]: Update this header on change, then check GEMINI.md
*/
import { useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from "react";
@@ -49,12 +49,34 @@ const WEB_SEARCH_ENGINES: WebSearchEngineOption[] = [
];
const THEME_CYCLE: AppearancePreference[] = ["system", "light", "dark"];
+const PUBLIC_COLLAPSED_STORAGE_KEY = "dockmarkPublicCollapsedV1";
+
+function readCollapsedGroups(): Set {
+ try {
+ const raw = window.localStorage.getItem(PUBLIC_COLLAPSED_STORAGE_KEY);
+ if (!raw) return new Set();
+ const parsed: unknown = JSON.parse(raw);
+ if (!Array.isArray(parsed)) return new Set();
+ return new Set(parsed.filter((item): item is string => typeof item === "string" && item.length > 0));
+ } catch {
+ return new Set();
+ }
+}
+
+function writeCollapsedGroups(keys: Set) {
+ try {
+ window.localStorage.setItem(PUBLIC_COLLAPSED_STORAGE_KEY, JSON.stringify([...keys]));
+ } catch {
+ // Ignore storage quota or private-browsing failures.
+ }
+}
export function PublicPage() {
const { isZh, tx, setLocalePreference } = usePublicI18n();
const [appearance, setAppearance] = useState(() => localAppearance());
const [siteSettings, setSiteSettings] = useState(() => readLocalPublicPageSettings());
const [visitorLayout, setVisitorLayout] = useState(() => readVisitorPublicLayout());
+ const [collapsedKeys, setCollapsedKeys] = useState>(() => readCollapsedGroups());
const [bookmarks, setBookmarks] = useState([]);
const [query, setQuery] = useState("");
const [searchMode, setSearchMode] = useState("filter");
@@ -100,6 +122,7 @@ export function PublicPage() {
const onStorage = (event: StorageEvent) => {
if (event.key === APPEARANCE_STORAGE_KEY) syncAppearance();
if (event.key === PUBLIC_SITE_CONFIG_STORAGE_KEY) setSiteSettings(readLocalPublicPageSettings());
+ if (event.key === PUBLIC_COLLAPSED_STORAGE_KEY) setCollapsedKeys(readCollapsedGroups());
};
window.addEventListener("dockmark:appearance", onAppearance);
window.addEventListener(PUBLIC_SITE_CONFIG_EVENT, onSiteConfig);
@@ -165,6 +188,11 @@ export function PublicPage() {
};
}, [tx]);
+ const bookmarksById = useMemo(
+ () => new Map(bookmarks.map((bookmark) => [bookmark.id, bookmark])),
+ [bookmarks],
+ );
+
const categories = useMemo(() => {
const map = new Map();
for (const bookmark of bookmarks) {
@@ -187,21 +215,41 @@ export function PublicPage() {
}
}, [categories, selectedCategoryKey]);
+ const trimmedQuery = query.trim();
+
const filtered = useMemo(() => {
const byCategory = selectedCategoryKey === "all"
? bookmarks
: bookmarks.filter((bookmark) => (bookmark.category?.id ?? "uncategorized") === selectedCategoryKey);
- const trimmed = query.trim();
- if (!trimmed || searchMode !== "filter") return byCategory;
+ if (!trimmedQuery || searchMode !== "filter") return byCategory;
return byCategory.filter((bookmark) =>
- textMatchesQuery(trimmed, [
+ textMatchesQuery(trimmedQuery, [
bookmark.title,
bookmark.url,
bookmark.description ?? "",
bookmark.category?.name ?? "",
]),
);
- }, [bookmarks, query, searchMode, selectedCategoryKey]);
+ }, [bookmarks, searchMode, selectedCategoryKey, trimmedQuery]);
+
+ const pinnedIdSet = useMemo(
+ () => new Set(siteSettings.pinnedBookmarkIds),
+ [siteSettings.pinnedBookmarkIds],
+ );
+
+ const pinnedItems = useMemo(() => {
+ const matchingIds = trimmedQuery && searchMode === "filter"
+ ? new Set(filtered.map((bookmark) => bookmark.id))
+ : null;
+ const resolved: PublicBookmark[] = [];
+ for (const id of siteSettings.pinnedBookmarkIds) {
+ const bookmark = bookmarksById.get(id);
+ if (!bookmark) continue;
+ if (matchingIds && !matchingIds.has(id)) continue;
+ resolved.push(bookmark);
+ }
+ return resolved;
+ }, [bookmarksById, filtered, searchMode, siteSettings.pinnedBookmarkIds, trimmedQuery]);
const groups = useMemo(() => {
const map = new Map();
@@ -219,6 +267,11 @@ export function PublicPage() {
return Array.from(map.values());
}, [filtered, tx]);
+ const isFilterOverride = Boolean(trimmedQuery) || selectedCategoryKey !== "all";
+ const showCollapseAllControl = groups.length >= 2 && selectedCategoryKey === "all" && !trimmedQuery;
+ const allGroupsCollapsed = groups.length > 0 && groups.every((group) => collapsedKeys.has(group.key));
+ const showPinnedSection = !loading && !error && selectedCategoryKey === "all" && pinnedItems.length > 0;
+
const nextAppearance = THEME_CYCLE[(THEME_CYCLE.indexOf(appearance) + 1) % THEME_CYCLE.length] ?? "system";
const themeIcon = appearance === "light" ? "☀" : appearance === "dark" ? "☾" : "◐";
const themeLabel = appearance === "light"
@@ -237,6 +290,30 @@ export function PublicPage() {
writeVisitorPublicLayout(layout);
}
+ function toggleGroup(key: string) {
+ if (isFilterOverride) return;
+ setCollapsedKeys((current) => {
+ const next = new Set(current);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ writeCollapsedGroups(next);
+ return next;
+ });
+ }
+
+ function toggleAllGroups() {
+ setCollapsedKeys((current) => {
+ const next = new Set(current);
+ if (allGroupsCollapsed) {
+ groups.forEach((group) => next.delete(group.key));
+ } else {
+ groups.forEach((group) => next.add(group.key));
+ }
+ writeCollapsedGroups(next);
+ return next;
+ });
+ }
+
function openExternalUrl(url: string) {
if (siteSettings.openInNewTab) {
const opened = window.open(url, "_blank", "noopener,noreferrer");
@@ -286,6 +363,55 @@ export function PublicPage() {
? "public-grid-list"
: "public-grid";
+ function renderBookmarkCard(bookmark: PublicBookmark, options?: { keyPrefix?: string; showPinIndicator?: boolean }) {
+ const host = hostLabel(bookmark.url);
+ const href = safeHttpUrl(bookmark.url) ?? "#";
+ const cardClass = effectiveLayout === "compact"
+ ? "public-card public-card-compact"
+ : effectiveLayout === "list"
+ ? "public-card public-card-list"
+ : "public-card";
+ const isPinned = options?.showPinIndicator && pinnedIdSet.has(bookmark.id);
+ return (
+
+
+
+ {bookmark.title}
+ {effectiveLayout !== "compact" && (
+ {bookmark.description || host}
+ )}
+
+ {isPinned && (
+
+ ★
+
+ )}
+ {effectiveLayout === "list" && (
+ {host}
+ )}
+ {effectiveLayout !== "compact" && (
+ ↗
+ )}
+
+ );
+ }
+
return (