From 976e3bf65b9e996aee29e26ae5ce6ac2a84cfe03 Mon Sep 17 00:00:00 2001 From: Warn Date: Mon, 23 Nov 2026 18:50:11 +0800 Subject: [PATCH 1/4] feat(core,worker): add pinnedBookmarkIds to PublicPageSettings and /api/settings/public-page validation --- apps/web/worker/GEMINI.md | 2 +- apps/web/worker/settings.ts | 42 ++++++++++++++++++++++++++++++++++- packages/core/GEMINI.md | 2 +- packages/core/src/settings.ts | 23 ++++++++++++++++++- 4 files changed, 65 insertions(+), 4 deletions(-) diff --git a/apps/web/worker/GEMINI.md b/apps/web/worker/GEMINI.md index 6acf1ed..2833fbb 100644 --- a/apps/web/worker/GEMINI.md +++ b/apps/web/worker/GEMINI.md @@ -7,7 +7,7 @@ Cloudflare Worker HTTP API layer backed by D1 (`DB`), mounted at `router.ts` and router.ts: Top-level Worker `fetch` dispatcher enforcing auth/device access, CSRF same-origin checks, public route exemptions (`/api/health`, `GET /api/settings/appearance`, `GET /api/settings/public-page`, `GET /api/public/bookmarks`), and domain handler routing index.ts: Base Worker handling `/api/health`, `/api/categories`, `/api/bookmarks`, workspace delegation, health checks, and static asset fallback auth.ts: Session cookie and paired-device bearer token authentication, PBKDF2 password hashing, device pairing exchange, and `/api/auth/*` endpoints -settings.ts: `/api/settings/browser` (including launcher shortcuts), `/api/settings/appearance`, `/api/settings/public-page`, and non-secret `/api/settings/ai` persistence in `app_settings` plus browser bootstrap payloads +settings.ts: `/api/settings/browser` (including launcher shortcuts), `/api/settings/appearance`, `/api/settings/public-page` (including `pinnedBookmarkIds` validation up to `MAX_PUBLIC_PINNED_BOOKMARKS`), and non-secret `/api/settings/ai` persistence in `app_settings` plus browser bootstrap payloads ai-organization.ts: `/api/ai/status` and `/api/ai/organize` OpenAI-compatible proxy with SSRF/redirect guards, `HealthPolicy === "normal"` gating, and locale-aware (`en` / `zh-CN`) prompt instructions ai-batch-apply.ts: `/api/ai/apply` transactional D1 batch updater applying reviewed AI title, description, category, and tag suggestions bookmark-details.ts: `/api/bookmarks/with-tags` and `/api/bookmarks/:id/with-tags` composite bookmark + tag create/update endpoints diff --git a/apps/web/worker/settings.ts b/apps/web/worker/settings.ts index 9be6f15..c96979a 100644 --- a/apps/web/worker/settings.ts +++ b/apps/web/worker/settings.ts @@ -1,5 +1,5 @@ /** - * [INPUT]: depends on browser, appearance, public-page, and AI settings helpers plus URL policy checks from @dockmark/core; queries D1 app_settings, bookmark_tags, smart_collections, and bookmarks tables + * [INPUT]: depends on browser, appearance, public-page (including MAX_PUBLIC_PINNED_BOOKMARKS), and AI settings helpers plus URL policy checks from @dockmark/core; queries D1 app_settings, bookmark_tags, smart_collections, and bookmarks tables * [OUTPUT]: exports SettingsDbLike, SettingsHttpError, loadAppearanceSettings, loadPublicPageSettings, loadAiSettings, and handleSettingsApi * [POS]: Worker HTTP handler for /api/settings/browser, /api/settings/appearance, /api/settings/public-page, and /api/settings/ai in apps/web/worker * [PROTOCOL]: Update this header on change, then check GEMINI.md @@ -9,6 +9,7 @@ import { DEFAULT_APPEARANCE_SETTINGS, DEFAULT_BROWSER_SETTINGS, DEFAULT_PUBLIC_PAGE_SETTINGS, + MAX_PUBLIC_PINNED_BOOKMARKS, inferHealthPolicy, mergeAiSettings, mergeAppearanceSettings, @@ -26,6 +27,7 @@ import { type BookmarkConflictPreference, type BrowserNewTabSettings, type BrowserSettings, + type Id, type LauncherShortcutKey, type LocalePreference, type PublicPageLayout, @@ -132,6 +134,43 @@ function parsePublicPageLayout(value: unknown): PublicPageLayout { throw new SettingsHttpError(400, "invalid_field", "defaultLayout must be grid, compact or list."); } +function parsePinnedBookmarkIds(value: unknown): Id[] { + if (!Array.isArray(value)) { + throw new SettingsHttpError(400, "invalid_field", "pinnedBookmarkIds must be an array."); + } + if (value.length > MAX_PUBLIC_PINNED_BOOKMARKS) { + throw new SettingsHttpError( + 400, + "invalid_field", + `pinnedBookmarkIds must contain at most ${MAX_PUBLIC_PINNED_BOOKMARKS} items.`, + ); + } + const seen = new Set(); + const ids: Id[] = []; + for (const item of value) { + if (typeof item !== "string") { + throw new SettingsHttpError( + 400, + "invalid_field", + "pinnedBookmarkIds items must be non-empty strings of at most 120 characters.", + ); + } + const trimmed = item.trim(); + if (!trimmed || trimmed.length > 120) { + throw new SettingsHttpError( + 400, + "invalid_field", + "pinnedBookmarkIds items must be non-empty strings of at most 120 characters.", + ); + } + if (!seen.has(trimmed)) { + seen.add(trimmed); + ids.push(trimmed); + } + } + return ids; +} + function parseBoolean(value: unknown, key: string): boolean { if (typeof value !== "boolean") { throw new SettingsHttpError(400, "invalid_field", `${key} must be a boolean.`); @@ -324,6 +363,7 @@ function parsePublicPageUpdate(body: Record): UpdatePublicPageS if (hasOwn(body, "showWebSearch")) update.showWebSearch = parseBoolean(body.showWebSearch, "showWebSearch"); if (hasOwn(body, "showCategoryNav")) update.showCategoryNav = parseBoolean(body.showCategoryNav, "showCategoryNav"); if (hasOwn(body, "openInNewTab")) update.openInNewTab = parseBoolean(body.openInNewTab, "openInNewTab"); + if (hasOwn(body, "pinnedBookmarkIds")) update.pinnedBookmarkIds = parsePinnedBookmarkIds(body.pinnedBookmarkIds); return update; } diff --git a/packages/core/GEMINI.md b/packages/core/GEMINI.md index 9fbba3b..85ce4f1 100644 --- a/packages/core/GEMINI.md +++ b/packages/core/GEMINI.md @@ -8,7 +8,7 @@ package.json: `@dockmark/core` workspace manifest exporting `./src/index.ts` and tsconfig.json: Package TypeScript config extending `../../tsconfig.base.json` src/index.ts: Public barrel re-exporting models, settings, i18n, URL policy, bookmark URL normalization, Pinyin initials, command ranking, and search utilities src/models.ts: Core entity types and CRUD input contracts (`Bookmark`, `Category`, `Workspace`, `Session`, `SearchEngine`, `HealthCheck`, `HealthPolicy`, `HealthStatus`, `CommandSource`, `CommandResult`) -src/settings.ts: `BrowserSettings` (including `launcherShortcut` and `slashFocus`), `AppearanceSettings`, `PublicPageSettings`, and non-secret `AiSettings` schemas, version constants, defaults, normalizers, and merge helpers +src/settings.ts: `BrowserSettings` (including `launcherShortcut` and `slashFocus`), `AppearanceSettings`, `PublicPageSettings` (including `pinnedBookmarkIds` and `MAX_PUBLIC_PINNED_BOOKMARKS`), and non-secret `AiSettings` schemas, version constants, defaults, normalizers, and merge helpers src/i18n.ts: Shared `LocalePreference` (`"system" | "en" | "zh-CN"`), `ResolvedLocale`, `LOCALE_STORAGE_KEY`, locale normalization/resolution, `tx`, `formatRelativeTime`, and canonical `SOURCE_LABELS`, `HEALTH_STATUS_LABELS`, `HEALTH_POLICY_LABELS` dictionaries src/url-policy.ts: Hostname/IPv4/IPv6 inspection (`inferHealthPolicy`) classifying localhost, private LAN, link-local, and non-HTTP URLs as `local-only` src/bookmark-url.ts: Input URL normalization (`normalizeBookmarkUrl`) prepending `http://` for local bare hosts and `https://` for public hosts diff --git a/packages/core/src/settings.ts b/packages/core/src/settings.ts index 5381f3b..accd2c8 100644 --- a/packages/core/src/settings.ts +++ b/packages/core/src/settings.ts @@ -1,6 +1,6 @@ /** * [INPUT]: depends on Id from ./models; depends on LocalePreference and normalizeLocalePreference from ./i18n - * [OUTPUT]: provides browser (with launcher shortcuts), appearance, public-page, and non-secret AI settings contracts, defaults, normalizers, and merge helpers + * [OUTPUT]: provides browser (with launcher shortcuts), appearance, public-page (with MAX_PUBLIC_PINNED_BOOKMARKS and pinnedBookmarkIds), and non-secret AI settings contracts, defaults, normalizers, and merge helpers * [POS]: schema and normalization boundary for persisted app_settings payloads in packages/core/src * [PROTOCOL]: Update this header on change, then check GEMINI.md */ @@ -10,6 +10,7 @@ import { normalizeLocalePreference, type LocalePreference } from "./i18n"; export const BROWSER_SETTINGS_VERSION = 1; export const APPEARANCE_SETTINGS_VERSION = 1; export const PUBLIC_PAGE_SETTINGS_VERSION = 1; +export const MAX_PUBLIC_PINNED_BOOKMARKS = 24; export const AI_SETTINGS_VERSION = 1; export type BookmarkConflictPreference = "ask" | "browser" | "dockmark"; @@ -62,6 +63,7 @@ export interface PublicPageSettings { showWebSearch: boolean; showCategoryNav: boolean; openInNewTab: boolean; + pinnedBookmarkIds: Id[]; updatedAt: string | null; } @@ -73,6 +75,7 @@ export interface UpdatePublicPageSettingsInput { showWebSearch?: boolean; showCategoryNav?: boolean; openInNewTab?: boolean; + pinnedBookmarkIds?: Id[]; } export interface AiSettings { @@ -120,6 +123,7 @@ export const DEFAULT_PUBLIC_PAGE_SETTINGS: PublicPageSettings = { showWebSearch: true, showCategoryNav: true, openInNewTab: true, + pinnedBookmarkIds: [], updatedAt: null, }; @@ -156,6 +160,21 @@ function trimmedCappedString(value: unknown, maxLength: number) { return typeof value === "string" ? value.trim().slice(0, maxLength) : ""; } +function normalizePinnedBookmarkIds(value: unknown): Id[] { + if (!Array.isArray(value)) return []; + const seen = new Set(); + const normalized: Id[] = []; + for (const item of value) { + if (typeof item !== "string") continue; + const trimmed = item.trim(); + if (!trimmed || trimmed.length > 120 || seen.has(trimmed)) continue; + seen.add(trimmed); + normalized.push(trimmed); + if (normalized.length >= MAX_PUBLIC_PINNED_BOOKMARKS) break; + } + return normalized; +} + export function normalizeBrowserSettings(value: unknown): BrowserSettings { if (!value || typeof value !== "object" || Array.isArray(value)) { return structuredClone(DEFAULT_BROWSER_SETTINGS); @@ -237,6 +256,7 @@ export function normalizePublicPageSettings(value: unknown): PublicPageSettings openInNewTab: typeof record.openInNewTab === "boolean" ? record.openInNewTab : DEFAULT_PUBLIC_PAGE_SETTINGS.openInNewTab, + pinnedBookmarkIds: normalizePinnedBookmarkIds(record.pinnedBookmarkIds), updatedAt: typeof record.updatedAt === "string" && record.updatedAt ? record.updatedAt : null, }; } @@ -306,6 +326,7 @@ export function mergePublicPageSettings( ...(input.showWebSearch === undefined ? {} : { showWebSearch: input.showWebSearch }), ...(input.showCategoryNav === undefined ? {} : { showCategoryNav: input.showCategoryNav }), ...(input.openInNewTab === undefined ? {} : { openInNewTab: input.openInNewTab }), + ...(input.pinnedBookmarkIds === undefined ? {} : { pinnedBookmarkIds: input.pinnedBookmarkIds }), updatedAt, }); } From e4cae6d6f915141d8c612d3ddbbe0c32ebf501dd Mon Sep 17 00:00:00 2001 From: Warn Date: Mon, 23 Nov 2026 18:52:17 +0800 Subject: [PATCH 2/4] feat(web): support tag and description merge with undo in duplicate review --- apps/web/src/DuplicateCandidateCard.tsx | 443 ++++++++++++++++++++++++ apps/web/src/DuplicateReviewPage.tsx | 400 +++++++-------------- apps/web/src/duplicate-review-api.ts | 22 +- apps/web/src/duplicate-review.css | 137 +++++++- apps/web/worker/duplicate-review.ts | 98 ++++-- 5 files changed, 783 insertions(+), 317 deletions(-) create mode 100644 apps/web/src/DuplicateCandidateCard.tsx 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} + )} +
+ +
+ +
+ + + +
+ +
+ {showMergeBar && ( +
+ +
+ + +
+
+ )} + +
+
+ + +
+
+ + + {tx("Open A ↗", "打开 A ↗")} + + + {tx("Open B ↗", "打开 B ↗")} + +
+
+
+
+ ); +} 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)}
) : ( - visible.map((candidate) => { - const archiving = busyCandidateId === candidate.id; - return ( -
-
-
-
- {kindLabel(candidate.kind, tx)} - {kindDescription(candidate.kind, tx)} -
-

{localizedReason(candidate, isZh)}

- {candidate.evidenceUrl && ( - {candidate.evidenceUrl} - )} -
- -
- -
- - - -
- -
-
- - -
-
- - - {tx("Open A ↗", "打开 A ↗")} - - - {tx("Open B ↗", "打开 B ↗")} - -
-
-
- ); - }) + visible.map((candidate) => ( + { + void archiveDuplicate(target, keepSide, mergeEnabled); + }} + onLocate={locateInLibrary} + /> + )) )} {!loading && result && visible.length === 0 && ( diff --git a/apps/web/src/duplicate-review-api.ts b/apps/web/src/duplicate-review-api.ts index 0866b81..4c99c01 100644 --- a/apps/web/src/duplicate-review-api.ts +++ b/apps/web/src/duplicate-review-api.ts @@ -1,7 +1,7 @@ /** * [INPUT]: calls GET /api/library/duplicates via fetch - * [OUTPUT]: exports getDuplicateReview and duplicate review response/member types - * [POS]: Web API client for DuplicateReviewPage in apps/web/src + * [OUTPUT]: exports getDuplicateReview and normalized duplicate review response/member types (including bookmark tags) + * [POS]: Web API client for DuplicateReviewPage and DuplicateCandidateCard in apps/web/src * [PROTOCOL]: Update this header on change, then check GEMINI.md */ @@ -17,6 +17,7 @@ export interface DuplicateReviewMember { categoryName?: string; healthPolicy: string; healthStatus: string; + tags: string[]; createdAt?: string; updatedAt?: string; canonicalUrl?: string; @@ -57,6 +58,14 @@ interface ErrorEnvelope { }; } +function normalizeMember(member: DuplicateReviewMember): DuplicateReviewMember { + const rawTags = (member as { tags?: unknown }).tags; + const tags = Array.isArray(rawTags) + ? rawTags.filter((tag): tag is string => typeof tag === "string" && tag.trim().length > 0) + : []; + return { ...member, tags }; +} + export async function getDuplicateReview(): Promise { const response = await fetch("/api/library/duplicates", { headers: { accept: "application/json" }, @@ -65,5 +74,12 @@ export async function getDuplicateReview(): Promise { if (!response.ok) { throw new Error(payload.error?.message ?? `Duplicate review failed with status ${response.status}.`); } - return payload; + return { + ...payload, + candidates: (payload.candidates ?? []).map((candidate) => ({ + ...candidate, + left: normalizeMember(candidate.left), + right: normalizeMember(candidate.right), + })), + }; } diff --git a/apps/web/src/duplicate-review.css b/apps/web/src/duplicate-review.css index 6d5d705..c560e4d 100644 --- a/apps/web/src/duplicate-review.css +++ b/apps/web/src/duplicate-review.css @@ -518,6 +518,34 @@ html[data-theme="light"] .duplicate-url-diff { line-height: 1.5; } +.duplicate-member-tags { + display: flex; + flex-wrap: wrap; + gap: 5px; + margin-top: 9px; +} + +.duplicate-tag-chip { + display: inline-flex; + align-items: center; + min-height: 21px; + padding: 0 8px; + border: 1px solid var(--dm-border); + border-radius: 999px; + background: var(--dm-bg-soft); + color: var(--dm-text-muted); + font-size: 11px; + line-height: 1.2; + white-space: nowrap; +} + +.duplicate-tag-chip.is-unique { + border-color: color-mix(in srgb, var(--dm-accent) 46%, var(--dm-border)); + background: var(--dm-accent-bg); + color: var(--dm-accent-strong); + font-weight: 560; +} + .duplicate-member-evidence { display: grid; gap: 6px; @@ -551,14 +579,112 @@ html[data-theme="light"] .duplicate-url-diff { } .duplicate-candidate-footer { + display: grid; + gap: 10px; + padding: 11px 18px; + border-top: 1px solid var(--dm-border); + background: var(--dm-bg-soft); +} + +.duplicate-footer-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; - padding: 11px 18px; - border-top: 1px solid var(--dm-border); - background: var(--dm-bg-soft); +} + +.duplicate-merge-bar { + display: grid; + gap: 7px; + padding: 9px 12px; + border: 1px solid color-mix(in srgb, var(--dm-accent) 30%, var(--dm-border)); + border-radius: 11px; + background: color-mix(in srgb, var(--dm-selected-bg) 52%, var(--dm-bg-card)); + transition: opacity .14s ease, border-color .14s ease; +} + +.duplicate-merge-bar.is-disabled { + border-color: var(--dm-border); + background: var(--dm-bg-card); +} + +.duplicate-merge-bar.is-disabled .duplicate-merge-previews { + opacity: .55; +} + +.duplicate-merge-toggle { + display: inline-flex; + align-items: center; + gap: 8px; + color: var(--dm-text); + font-size: 12px; + font-weight: 560; + line-height: 1.4; + cursor: pointer; +} + +.duplicate-merge-toggle input[type="checkbox"] { + width: 14px; + height: 14px; + margin: 0; + accent-color: var(--dm-accent); + cursor: pointer; + flex: 0 0 auto; +} + +.duplicate-merge-previews { + display: flex; + flex-wrap: wrap; + gap: 6px 14px; + padding-left: 22px; +} + +.duplicate-merge-preview-row { + display: inline-flex; + align-items: center; + flex-wrap: wrap; + gap: 5px; +} + +.duplicate-merge-side { + color: var(--dm-text-muted); + font-size: 11px; + font-weight: 620; + white-space: nowrap; +} + +.duplicate-merge-chips { + display: inline-flex; + align-items: center; + flex-wrap: wrap; + gap: 4px; +} + +.duplicate-merge-chip { + display: inline-flex; + align-items: center; + min-height: 19px; + padding: 0 7px; + border: 1px solid color-mix(in srgb, var(--dm-accent) 44%, var(--dm-border)); + border-radius: 999px; + background: var(--dm-accent-bg); + color: var(--dm-accent-strong); + font-size: 10.5px; + font-weight: 560; + white-space: nowrap; +} + +.duplicate-merge-chip.is-description { + border-color: var(--dm-border-strong); + background: var(--dm-bg-card); + color: var(--dm-text-soft); +} + +.duplicate-merge-cap { + color: var(--dm-text-muted); + font-size: 10.5px; + white-space: nowrap; } .duplicate-review-actions, @@ -660,8 +786,11 @@ html[data-theme="light"] .duplicate-url-diff { margin: -12px auto; } .duplicate-candidate-heading, - .duplicate-candidate-footer { + .duplicate-footer-row { align-items: stretch; flex-direction: column; } + .duplicate-merge-previews { + padding-left: 0; + } } diff --git a/apps/web/worker/duplicate-review.ts b/apps/web/worker/duplicate-review.ts index 603973e..e7f0eab 100644 --- a/apps/web/worker/duplicate-review.ts +++ b/apps/web/worker/duplicate-review.ts @@ -1,7 +1,7 @@ /** - * [INPUT]: depends on D1 bookmarks, categories, and bookmark_metadata tables via DuplicateReviewDatabase + * [INPUT]: depends on D1 bookmarks, categories, bookmark_metadata, bookmark_tags, and tags tables via DuplicateReviewDatabase * [OUTPUT]: exports handleDuplicateReviewApi, reviewFingerprint, DuplicateReviewHttpError, and DuplicateReview types - * [POS]: Worker handler for GET /api/library/duplicates; detects canonical, resolved, and normalized URL duplicates while preserving SPA hash routes + * [POS]: Worker handler for GET /api/library/duplicates; detects canonical, resolved, and normalized URL duplicates with active bookmark tags while preserving SPA hash routes * [PROTOCOL]: Update this header on change, then check GEMINI.md */ @@ -33,6 +33,11 @@ interface DuplicateRow { fetched_at: string | null; } +interface BookmarkTagRow { + bookmark_id: string; + name: string; +} + export type DuplicateCandidateKind = "canonical" | "resolved" | "normalized"; export interface DuplicateReviewMember { @@ -45,6 +50,7 @@ export interface DuplicateReviewMember { categoryName?: string; healthPolicy: string; healthStatus: string; + tags: string[]; createdAt?: string; updatedAt?: string; canonicalUrl?: string; @@ -141,7 +147,7 @@ function displayEvidenceUrl(raw: string | null | undefined) { } } -function member(row: DuplicateRow): DuplicateReviewMember { +function member(row: DuplicateRow, tagsByBookmarkId: Map): DuplicateReviewMember { return { id: row.id, title: row.title, @@ -152,6 +158,7 @@ function member(row: DuplicateRow): DuplicateReviewMember { ...(row.category_name ? { categoryName: row.category_name } : {}), healthPolicy: row.health_policy, healthStatus: row.health_status, + tags: tagsByBookmarkId.get(row.id) ?? [], ...(row.created_at ? { createdAt: row.created_at } : {}), ...(row.updated_at ? { updatedAt: row.updated_at } : {}), ...(row.canonical_url ? { canonicalUrl: row.canonical_url } : {}), @@ -170,6 +177,7 @@ function addCandidate( rightRow: DuplicateRow, kind: DuplicateCandidateKind, reason: string, + tagsByBookmarkId: Map, evidenceUrl?: string, ) { if (leftRow.id === rightRow.id) return; @@ -183,8 +191,8 @@ function addCandidate( kind, reason, ...(evidenceUrl ? { evidenceUrl } : {}), - left: member(left), - right: member(right), + left: member(left, tagsByBookmarkId), + right: member(right, tagsByBookmarkId), }); } @@ -199,6 +207,7 @@ function addMetadataPairs( candidates: Map, rows: DuplicateRow[], kind: "canonical" | "resolved", + tagsByBookmarkId: Map, ) { const originals = new Map(); const evidence = new Map(); @@ -233,6 +242,7 @@ function addMetadataPairs( kind === "canonical" ? "Saved page metadata points these bookmarks at the same canonical target." : "Saved metadata shows these bookmarks resolving to the same final target.", + tagsByBookmarkId, displayEvidenceUrl(rawEvidence), ); } @@ -240,7 +250,11 @@ function addMetadataPairs( } } -function addNormalizedPairs(candidates: Map, rows: DuplicateRow[]) { +function addNormalizedPairs( + candidates: Map, + rows: DuplicateRow[], + tagsByBookmarkId: Map, +) { const groups = new Map(); for (const row of rows) pushBucket(groups, reviewFingerprint(row.url), row); for (const group of groups.values()) { @@ -257,6 +271,7 @@ function addNormalizedPairs(candidates: Map, r rightRow, "normalized", "The URLs become equivalent after ignoring protocol/www, fragments, trailing slashes and known tracking parameters.", + tagsByBookmarkId, ); } } @@ -264,32 +279,53 @@ function addNormalizedPairs(candidates: Map, r } async function duplicateReview(db: DuplicateReviewDatabase) { - const result = await db.prepare( - `SELECT b.id, - b.title, - b.url, - b.description, - b.icon_url, - b.category_id, - c.name AS category_name, - b.health_status, - b.health_policy, - b.created_at, - b.updated_at, - m.canonical_url, - m.final_url, - m.fetched_at - FROM bookmarks b - LEFT JOIN categories c ON c.id = b.category_id - LEFT JOIN bookmark_metadata m ON m.bookmark_id = b.id - WHERE b.archived_at IS NULL - ORDER BY b.updated_at DESC, b.id ASC`, - ).all(); - const rows = result.results ?? []; + const [result, tagResult] = await Promise.all([ + db.prepare( + `SELECT b.id, + b.title, + b.url, + b.description, + b.icon_url, + b.category_id, + c.name AS category_name, + b.health_status, + b.health_policy, + b.created_at, + b.updated_at, + m.canonical_url, + m.final_url, + m.fetched_at + FROM bookmarks b + LEFT JOIN categories c ON c.id = b.category_id + LEFT JOIN bookmark_metadata m ON m.bookmark_id = b.id + WHERE b.archived_at IS NULL + ORDER BY b.updated_at DESC, b.id ASC`, + ).all(), + db.prepare( + `SELECT bt.bookmark_id, t.name + FROM bookmark_tags bt + JOIN bookmarks b ON b.id = bt.bookmark_id + JOIN tags t ON t.id = bt.tag_id + WHERE b.archived_at IS NULL + ORDER BY bt.bookmark_id ASC, t.name COLLATE NOCASE ASC`, + ).all(), + ]); + + const rows = result?.results ?? []; + const tagsByBookmarkId = new Map(); + for (const tagRow of tagResult?.results ?? []) { + if (typeof tagRow?.bookmark_id !== "string" || typeof tagRow?.name !== "string") continue; + const trimmed = tagRow.name.trim(); + if (!trimmed) continue; + const list = tagsByBookmarkId.get(tagRow.bookmark_id); + if (list) list.push(trimmed); + else tagsByBookmarkId.set(tagRow.bookmark_id, [trimmed]); + } + const candidates = new Map(); - addMetadataPairs(candidates, rows, "canonical"); - addMetadataPairs(candidates, rows, "resolved"); - addNormalizedPairs(candidates, rows); + addMetadataPairs(candidates, rows, "canonical", tagsByBookmarkId); + addMetadataPairs(candidates, rows, "resolved", tagsByBookmarkId); + addNormalizedPairs(candidates, rows, tagsByBookmarkId); const rank: Record = { canonical: 3, resolved: 2, normalized: 1 }; const allCandidates = Array.from(candidates.values()).sort((left, right) => { From 84b89d169b3e0684763f760dd0e39b6504d337c5 Mon Sep 17 00:00:00 2001 From: Warn Date: Mon, 23 Nov 2026 18:55:28 +0800 Subject: [PATCH 3/4] feat(web): fix AI secret card overflow and add public pinned favorites + collapsible groups --- apps/web/src/AiProviderSettingsPage.tsx | 45 +-- apps/web/src/PublicPage.tsx | 268 ++++++++++++----- apps/web/src/PublicPageSettings.tsx | 369 ++++++++++++++---------- apps/web/src/PublicSiteConfigCard.tsx | 140 +++++++++ apps/web/src/public-page.css | 112 ++++++- apps/web/src/settings.css | 150 +++++++++- 6 files changed, 823 insertions(+), 261 deletions(-) create mode 100644 apps/web/src/PublicSiteConfigCard.tsx 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 + + +
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 (
@@ -387,7 +513,7 @@ export function PublicPage() { × )} - {activeWebEngine && query.trim() ? ( + {activeWebEngine && trimmedQuery ? ( - ))} + )} + +
+ {([ + ["grid", tx("Grid", "网格")], + ["compact", tx("Compact", "紧凑")], + ["list", tx("List", "列表")], + ] as const).map(([mode, label]) => ( + + ))} +
)} @@ -457,71 +596,58 @@ export function PublicPage() { {error &&
{error}
} {!error && loading &&
{tx("Loading curated links…", "正在加载公开书签…")}
} + {showPinnedSection && ( +
+
+ +

{tx("Pinned", "置顶常用")}

+ {pinnedItems.length} +
+
+ {pinnedItems.map((bookmark) => renderBookmarkCard(bookmark, { keyPrefix: "pin-" }))} +
+
+ )} + {!loading && !error && groups.length > 0 && (
- {groups.map((group) => ( -
-
- {group.icon ?? "#"} -

{group.name}

- {group.items.length} -
-
- {group.items.map((bookmark) => { - 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"; - return ( - - - - {bookmark.title} - {effectiveLayout !== "compact" && ( - {bookmark.description || host} - )} - - {effectiveLayout === "list" && ( - {host} - )} - {effectiveLayout !== "compact" && ( - - )} - - ); - })} -
-
- ))} + {groups.map((group) => { + const isCollapsed = !isFilterOverride && collapsedKeys.has(group.key); + return ( +
+ + {!isCollapsed && ( +
+ {group.items.map((bookmark) => renderBookmarkCard(bookmark, { showPinIndicator: true }))} +
+ )} +
+ ); + })}
)} {!loading && !error && !groups.length && (
- {query.trim() ? tx("No public links match that filter.", "没有匹配的公开链接。") : tx("Nothing is public yet.", "暂未发布公开链接。")} + {trimmedQuery ? tx("No public links match that filter.", "没有匹配的公开链接。") : tx("Nothing is public yet.", "暂未发布公开链接。")} - {query.trim() + {trimmedQuery ? siteSettings.showWebSearch ? tx("Press Enter to search Google, or pick a web search engine below.", "按 Enter 使用 Google 搜索,或直接选择下方外网引擎。") : tx("Try another keyword or switch category.", "请尝试其他关键词或切换分类。") : tx("The owner can publish selected bookmarks from Settings.", "站点所有者可在「设置 → 公开主页」中选择发布书签。")} - {query.trim() && siteSettings.showWebSearch && ( + {trimmedQuery && siteSettings.showWebSearch && (
{WEB_SEARCH_ENGINES.slice(0, 4).map((engine) => ( - ))} -
- - -
- - - - -
- -
- - {tx( - "Visitors can still switch Grid / Compact / List locally in their browser without changing your D1 defaults.", - "访客仍可在自己浏览器中本地切换网格 / 紧凑 / 列表视图,不会覆盖你的 D1 默认配置。", - )} - - -
- + void saveSiteConfig(event)} + />

{tx("Public layout", "公开列表预览与排序")}

-

{tx("Reorder published categories and links directly here.", "直接上下调整已公开分类与链接顺序。")}

+

{tx("Pin top favorites and reorder published categories and links directly here.", "置顶高频常用链接,并直接调整已公开分类与书签顺序。")}

{tx(`${groups.length} groups`, `${groups.length} 个分组`)}
+
+
+
+ + + {tx("Pinned Favorites", "置顶常用区")} + + {tx("Featured above all category groups on /", "固定展示在公开主页顶部分类区上方")} +
+ + {pinnedBookmarks.length} / {MAX_PUBLIC_PINNED_BOOKMARKS} + +
+ + {pinnedBookmarks.length > 0 ? ( +
+ {pinnedBookmarks.map((bookmark, index) => ( +
+ + + {bookmark.title} + {bookmark.url} + +
+ + + +
+
+ ))} +
+ ) : ( +

+ {tx( + "Click “★ Pin” on any published bookmark below to pin it to the top favorites bar.", + "点击下方已公开书签右侧的「★ 置顶」即可固定到公开主页顶部常用区。", + )} +

+ )} +
+
{groups.map((group, groupIndex) => (
@@ -508,43 +544,60 @@ export function PublicPageSettings({ bookmarks, categories, onChanged }: Props)
- {group.bookmarks.map((bookmark, index) => ( -
- - - {bookmark.title} - {bookmark.url} - -
- - - + {group.bookmarks.map((bookmark, index) => { + const isPinned = pinnedIdSet.has(bookmark.id); + const pinDisabled = pinSaving || (!isPinned && pinLimitReached); + return ( +
+ + + {bookmark.title} + {bookmark.url} + +
+ + + + +
-
- ))} + ); + })}
))} diff --git a/apps/web/src/PublicSiteConfigCard.tsx b/apps/web/src/PublicSiteConfigCard.tsx new file mode 100644 index 0000000..0e56ce5 --- /dev/null +++ b/apps/web/src/PublicSiteConfigCard.tsx @@ -0,0 +1,140 @@ +/** + * [INPUT]: depends on PublicPageLayout and PublicPageSettings from @dockmark/core; useI18n from ./i18n + * [OUTPUT]: exports PublicSiteConfigCard form component for editing public root page (/) branding, default layout, search bar, category nav, and link opening behavior + * [POS]: Extracted top configuration card rendered by PublicPageSettings.tsx under /app/settings/public to keep both modules cohesive and well below the 800-line limit. + * [PROTOCOL]: Update this header on change, then check GEMINI.md + */ +import type { FormEvent } from "react"; +import type { PublicPageLayout, PublicPageSettings } from "@dockmark/core"; +import { useI18n } from "./i18n"; + +interface Props { + siteConfig: PublicPageSettings; + saving: boolean; + onChange: (updater: (current: PublicPageSettings) => PublicPageSettings) => void; + onSubmit: (event: FormEvent) => void; +} + +export function PublicSiteConfigCard({ siteConfig, saving, onChange, onSubmit }: Props) { + const { tx } = useI18n(); + + return ( +
+
+
+

{tx("Navigation Station Appearance & Behavior", "导航站外观与交互配置")}

+

+ {tx( + "Customize the public root page (/) title, default density, search engines, and link opening behavior.", + "自定义公开主页(/)的站点标题、默认视图密度、外网搜索引擎栏与链接打开方式。", + )} +

+
+ {tx("Applies to /", "生效于 /")} +
+ +
+ + +
+ +
+ {tx("Default layout", "默认布局")} +
+ {([ + ["grid", tx("Standard Grid", "标准卡片 Grid")], + ["compact", tx("Compact Nav", "紧凑导航 Compact")], + ["list", tx("Detailed List", "详情列表 List")], + ] as Array<[PublicPageLayout, string]>).map(([layoutValue, label]) => ( + + ))} +
+
+ +
+ + + + +
+ +
+ + {tx( + "Visitors can still switch Grid / Compact / List locally in their browser without changing your D1 defaults.", + "访客仍可在自己浏览器中本地切换网格 / 紧凑 / 列表视图,不会覆盖你的 D1 默认配置。", + )} + + +
+
+ ); +} diff --git a/apps/web/src/public-page.css b/apps/web/src/public-page.css index e2c4bb7..e633ad4 100644 --- a/apps/web/src/public-page.css +++ b/apps/web/src/public-page.css @@ -161,12 +161,40 @@ } .public-category-pill.active em { color: var(--dm-accent-strong); } +.public-toolbar-controls { + display: inline-flex; + align-items: center; + gap: 8px; + flex: 0 0 auto; + margin-left: auto; +} +.public-collapse-all-btn { + display: inline-flex; + align-items: center; + gap: 5px; + height: 32px; + padding: 0 10px; + border: 1px solid var(--dm-border); + border-radius: 10px; + background: var(--dm-bg-soft); + color: var(--dm-text-soft); + font-size: 11px; + font-weight: 550; + cursor: pointer; + white-space: nowrap; + transition: border-color 140ms ease, background-color 140ms ease, color 140ms ease; +} +.public-collapse-all-btn:hover { + border-color: color-mix(in srgb, var(--dm-accent) 44%, var(--dm-border)); + background: var(--dm-hover-bg); + color: var(--dm-text); +} + .public-layout-switcher { display: inline-flex; align-items: center; gap: 3px; flex: 0 0 auto; - margin-left: auto; padding: 3px; border: 1px solid var(--dm-border); border-radius: 10px; @@ -192,12 +220,78 @@ box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--dm-accent) 42%, var(--dm-border)); } -.public-groups { display: grid; gap: 26px; } +/* Pinned Favorites section above category groups */ +.public-pinned-section { + display: grid; + gap: 10px; + margin-bottom: 24px; + padding: 12px; + border: 1px solid color-mix(in srgb, var(--dm-accent) 34%, var(--dm-border)); + border-radius: 16px; + background: color-mix(in srgb, var(--dm-accent-bg) 30%, transparent); +} +.public-pinned-heading { + padding: 2px 4px; +} +.public-pinned-star { + color: var(--dm-accent-strong); + font-size: 13px; + line-height: 1; +} +.public-pinned-heading small { + padding: 2px 8px; + border: 1px solid color-mix(in srgb, var(--dm-accent) 38%, var(--dm-border)); + border-radius: 999px; + background: var(--dm-selected-bg); + color: var(--dm-accent-strong); +} + +.public-groups { display: grid; gap: 22px; } .public-group { display: grid; gap: 10px; } .public-group-heading { display: flex; align-items: center; gap: 8px; color: var(--dm-text-soft); } .public-group-heading > span { color: var(--dm-accent); font: 11px ui-monospace, SFMono-Regular, Menlo, monospace; } .public-group-heading h2 { margin: 0; color: var(--dm-text); font-size: 13px; font-weight: 640; letter-spacing: .02em; } .public-group-heading small { margin-left: auto; color: var(--dm-text-muted); font-size: 11px; font-variant-numeric: tabular-nums; } +.public-group-toggle { + width: 100%; + min-height: 34px; + padding: 6px 10px; + border: 1px solid transparent; + border-radius: 10px; + background: transparent; + cursor: pointer; + text-align: left; + transition: border-color 140ms ease, background-color 140ms ease; +} +.public-group-toggle:hover { + border-color: var(--dm-border); + background: color-mix(in srgb, var(--dm-bg-soft) 72%, transparent); +} +.public-group-toggle:focus-visible { + outline: 0; + border-color: var(--dm-accent); + box-shadow: 0 0 0 3px var(--dm-focus-ring); +} +.public-group-toggle.is-collapsed { + border-color: var(--dm-border); + background: color-mix(in srgb, var(--dm-bg-card) 68%, transparent); +} +.public-group-chevron { + display: inline-grid; + place-items: center; + width: 14px; + color: var(--dm-text-muted); + font-size: 11px; + line-height: 1; +} +.public-group-icon { color: var(--dm-accent); } +.public-card-pin-mark { + flex: 0 0 auto; + color: var(--dm-accent-strong); + font-size: 11px; + line-height: 1; + opacity: .85; +} /* Mode 1: Grid (refined 3-col cards) */ .public-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 9px; } @@ -316,6 +410,17 @@ html[data-theme="light"] .public-domain-badge { color: var(--dm-text-soft); } +html[data-theme="light"] .public-pinned-section { + border-color: #a8cbb5; + background: color-mix(in srgb, var(--dm-selected-bg) 48%, #ffffff); +} +html[data-theme="light"] .public-collapse-all-btn { + background: rgba(255, 255, 255, .9); +} +html[data-theme="light"] .public-group-toggle.is-collapsed { + background: rgba(255, 255, 255, .88); +} + @media (max-width: 900px) { .public-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } } @@ -327,7 +432,8 @@ html[data-theme="light"] .public-domain-badge { .public-hero { padding-top: 22px; } .public-hero-head { align-items: flex-start; flex-direction: column; gap: 8px; } .public-toolbar { align-items: stretch; flex-direction: column; gap: 10px; } - .public-layout-switcher { margin-left: 0; align-self: flex-start; } + .public-toolbar-controls { margin-left: 0; justify-content: space-between; width: 100%; flex-wrap: wrap; } + .public-layout-switcher { margin-left: 0; } .public-grid { grid-template-columns: 1fr; } .public-grid-compact { grid-template-columns: repeat(2, minmax(0, 1fr)); } .public-search-kbd { display: none; } diff --git a/apps/web/src/settings.css b/apps/web/src/settings.css index b395eed..689931a 100644 --- a/apps/web/src/settings.css +++ b/apps/web/src/settings.css @@ -88,8 +88,73 @@ .public-layout-item strong, .public-layout-item small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .public-layout-item strong { font-size: 12px; } .public-layout-item small { color: var(--dm-text-muted); font-size: 10px; } -.public-order-actions { display: flex; align-items: center; gap: 9px; white-space: nowrap; } +.public-order-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; white-space: nowrap; } .public-order-actions button:disabled { opacity: .35; cursor: default; } +.public-pinned-panel { + margin-bottom: 12px; + overflow: hidden; + border: 1px solid color-mix(in srgb, var(--dm-accent) 44%, var(--dm-border)); + border-radius: 13px; + background: color-mix(in srgb, var(--dm-accent-bg) 38%, var(--dm-bg-soft)); +} +.public-pinned-panel-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 10px 12px; + border-bottom: 1px solid color-mix(in srgb, var(--dm-accent) 26%, var(--dm-border)); +} +.public-pinned-panel-head > div { display: grid; gap: 2px; min-width: 0; } +.public-pinned-panel-head strong { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--dm-text); } +.public-pinned-panel-head span { color: var(--dm-text-muted); font-size: 10.5px; } +.public-pinned-quota { + flex: 0 0 auto; + padding: 2px 8px; + border: 1px solid color-mix(in srgb, var(--dm-accent) 42%, var(--dm-border)); + border-radius: 999px; + background: var(--dm-selected-bg); + color: var(--dm-accent-strong); + font-style: normal; + font-size: 11px; + font-weight: 600; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} +.public-pin-star { color: var(--dm-accent-strong); font-size: 12px; line-height: 1; } +.public-pinned-empty { margin: 0; padding: 11px 12px; color: var(--dm-text-muted); font-size: 11.5px; line-height: 1.45; } +.public-pin-btn { + display: inline-flex; + align-items: center; + gap: 3px; + height: 24px; + padding: 0 8px; + border: 1px solid var(--dm-border); + border-radius: 999px; + background: var(--dm-bg-card); + color: var(--dm-text-soft); + font-size: 11px; + font-weight: 560; + cursor: pointer; + white-space: nowrap; + transition: border-color 140ms ease, background-color 140ms ease, color 140ms ease; +} +.public-pin-btn:hover:not(:disabled) { + border-color: color-mix(in srgb, var(--dm-accent) 52%, var(--dm-border)); + background: var(--dm-hover-bg); + color: var(--dm-text); +} +.public-pin-btn.is-pinned { + border-color: color-mix(in srgb, var(--dm-accent) 58%, var(--dm-border)); + background: var(--dm-selected-bg); + color: var(--dm-accent-strong); +} +html[data-theme="light"] .public-pinned-panel { + border-color: #a8cbb5; + background: color-mix(in srgb, var(--dm-selected-bg) 52%, #ffffff); +} +html[data-theme="light"] .public-pin-btn { background: #fff; } +html[data-theme="light"] .public-pin-btn.is-pinned { background: var(--dm-selected-bg); } .public-publish-card .public-bookmark-picker { max-height: 640px; } .public-bookmark-add { grid-template-columns: minmax(0, 1fr) auto; width: 100%; text-align: left; } .public-bookmark-add:disabled { opacity: .55; cursor: default; } @@ -227,7 +292,8 @@ html[data-theme="light"] .public-bookmark-row.public-bookmark-manage.is-publishe /* Settings -> AI Service (/app/settings/ai) */ .ai-service-section { display: grid; gap: 16px; } -.ai-service-grid { display: grid; grid-template-columns: minmax(0, 1.35fr) minmax(280px, .65fr); gap: 14px; align-items: start; } +.ai-service-grid { display: grid; grid-template-columns: minmax(0, 1.25fr) minmax(0, 0.95fr); gap: 14px; align-items: start; } +.ai-service-grid > * { min-width: 0; max-width: 100%; } .ai-preset-block { display: grid; gap: 8px; margin-bottom: 14px; } .ai-preset-label { color: var(--dm-text-muted); font-size: 11px; text-transform: uppercase; letter-spacing: .07em; } .ai-preset-chips { display: flex; flex-wrap: wrap; gap: 7px; } @@ -261,12 +327,48 @@ html[data-theme="light"] .public-bookmark-row.public-bookmark-manage.is-publishe border-top: 1px solid var(--dm-border); } .ai-service-form-actions > div { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } -.ai-secret-card { display: grid; gap: 12px; } -.ai-status-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; } +.ai-secret-card { display: grid; grid-template-columns: minmax(0, 1fr); gap: 12px; min-width: 0; overflow: hidden; } +.ai-secret-card > * { min-width: 0; max-width: 100%; } +.ai-secret-card .card-heading, +.ai-secret-card .card-heading > div { min-width: 0; } +.ai-status-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + flex-wrap: wrap; + min-width: 0; + max-width: 100%; +} +.ai-status-meta { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + min-width: 0; + max-width: 100%; +} +.ai-secret-name { + min-width: 0; + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + padding: 3px 7px; + border: 1px solid var(--dm-border); + border-radius: 7px; + background: var(--dm-bg-soft); + color: var(--dm-text); + font: 600 11.5px/1.3 ui-monospace, SFMono-Regular, Menlo, monospace; +} .ai-status-badge { display: inline-flex; align-items: center; gap: 6px; + min-width: 0; + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; padding: 4px 10px; border: 1px solid var(--dm-border); border-radius: 999px; @@ -274,34 +376,55 @@ html[data-theme="light"] .public-bookmark-row.public-bookmark-manage.is-publishe font-weight: 600; white-space: nowrap; } -.ai-status-badge .status-dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; } +.ai-status-badge .status-dot { flex: 0 0 auto; width: 7px; height: 7px; border-radius: 50%; background: currentColor; } .ai-status-badge.is-ready { border-color: color-mix(in srgb, var(--dm-accent) 55%, var(--dm-border)); background: var(--dm-success-bg); color: var(--dm-accent-strong); } .ai-status-badge.is-missing { border-color: #6b582e; background: var(--dm-warning-bg); color: #d8bb76; } html[data-theme="light"] .ai-status-badge.is-missing { border-color: #dfc995; color: #7a6328; } +.ai-status-row button, +.ai-recheck-btn { + flex: 0 0 auto; + min-height: 30px; + padding: 0 10px; + font-size: 12px; + white-space: nowrap; +} .ai-secret-cmd { - display: flex; + display: grid; + grid-template-columns: minmax(0, 1fr) auto; align-items: center; - justify-content: space-between; - gap: 10px; - padding: 9px 11px; + gap: 8px; + min-width: 0; + max-width: 100%; + padding: 8px 10px; border: 1px solid var(--dm-border); border-radius: 10px; background: var(--dm-bg-soft); } .ai-secret-cmd code { + display: block; min-width: 0; overflow-x: auto; color: var(--dm-accent-strong); font: 12px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; white-space: nowrap; + scrollbar-width: thin; +} +.ai-secret-cmd button { + flex: 0 0 auto; + min-height: 30px; + padding: 0 10px; + font-size: 11px; + white-space: nowrap; } -.ai-quick-links { display: grid; gap: 8px; padding-top: 10px; border-top: 1px solid var(--dm-border); } +.ai-quick-links { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; min-width: 0; padding-top: 10px; border-top: 1px solid var(--dm-border); } .ai-quick-link { display: flex; align-items: center; justify-content: space-between; gap: 10px; width: 100%; + min-width: 0; + max-width: 100%; min-height: 38px; padding: 8px 12px; border: 1px solid var(--dm-border); @@ -314,6 +437,8 @@ html[data-theme="light"] .ai-status-badge.is-missing { border-color: #dfc995; co text-align: left; transition: border-color 140ms ease, background-color 140ms ease, color 140ms ease; } +.ai-quick-link > span:first-child { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.ai-quick-link > span:last-child { flex: 0 0 auto; } .ai-quick-link:hover { border-color: color-mix(in srgb, var(--dm-accent) 46%, var(--dm-border)); background: var(--dm-hover-bg); color: var(--dm-text); } /* BrowserSettings shortcut stack */ @@ -336,8 +461,11 @@ html[data-theme="light"] .ai-status-badge.is-missing { border-color: #dfc995; co font-size: 11px; } +@media (max-width: 960px) { + .ai-service-grid { grid-template-columns: 1fr; } +} @media (max-width: 860px) { - .ai-service-grid, .public-site-config-grid { grid-template-columns: 1fr; } + .public-site-config-grid { grid-template-columns: 1fr; } } @media (max-width: 640px) { .ai-service-form-row { grid-template-columns: 1fr; } From 62fa7631cd8ea53f04e59909f0af9b1f02f89b4e Mon Sep 17 00:00:00 2001 From: Warn Date: Mon, 23 Nov 2026 19:03:11 +0800 Subject: [PATCH 4/4] test,docs: verify AI secret card zero-overflow, sync GEB index, and document public pins & duplicate merge --- README.md | 4 +- apps/web/GEMINI.md | 16 ++-- scripts/chromium-web-shell-smoke.mjs | 133 ++++++++++++++++++++++++++- 3 files changed, 143 insertions(+), 10 deletions(-) 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, 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/scripts/chromium-web-shell-smoke.mjs b/scripts/chromium-web-shell-smoke.mjs index 54a9999..9fd3ed5 100644 --- a/scripts/chromium-web-shell-smoke.mjs +++ b/scripts/chromium-web-shell-smoke.mjs @@ -1,6 +1,6 @@ /** * [INPUT]: depends on apps/web/src shell, settings, and ui-polish stylesheets and playwright Chromium - * [OUTPUT]: verifies zero horizontal overflow, sticky 46px/64px/128px geometry, zero inner focus-outline on composite search boxes, 5-tab Settings subnav fit, and responsive nav behavior at 1280/900/720/390px in both English and Simplified Chinese + * [OUTPUT]: verifies zero horizontal overflow, sticky 46px/64px/128px geometry, zero inner focus-outline on composite search boxes, 5-tab Settings subnav fit, AI Service Worker Secret Status card zero-overflow geometry, and responsive nav behavior at 1280/900/720/390px in both English and Simplified Chinese * [POS]: Chromium responsive shell layout smoke test in scripts/ * [PROTOCOL]: Update this header on change, then check GEMINI.md */ @@ -41,6 +41,18 @@ const LOCALE_FIXTURES = [ resultHeading: "Command results", bridgeMeta: "Browser bridge · 20 open tabs", resultPill: "Open tab", + aiCard: { + providerTitle: "Provider Endpoint & Model", + providerDesc: "Pick a 1-click preset or enter any HTTPS OpenAI-compatible Chat Completions URL.", + secretTitle: "Worker Secret Status", + secretDesc: "Bound server-side via Cloudflare Workers secrets.", + readyLabel: "Ready", + recheckLabel: "Recheck", + copyLabel: "Copy", + footnote: "Run the Wrangler command above in your Dockmark deployment directory. Your API key stays encrypted inside Cloudflare Workers and never leaves the server.", + quickLink1: "Open Capture Inbox AI Triage", + quickLink2: "Open Bookmarks → Bulk & AI Organize", + }, expectPhoneSectionOverflow: true, }, { @@ -61,6 +73,18 @@ const LOCALE_FIXTURES = [ resultHeading: "命令结果", bridgeMeta: "浏览器桥接 · 20 个打开的标签页", resultPill: "打开的标签页", + aiCard: { + providerTitle: "服务商接口与模型", + providerDesc: "可一键填入常用服务商预设,或手动填写任意 HTTPS OpenAI 兼容接口地址。", + secretTitle: "Worker 密钥状态", + secretDesc: "由 Cloudflare Workers 服务端密钥安全注入。", + readyLabel: "已就绪", + recheckLabel: "重新检测", + copyLabel: "复制", + footnote: "在部署目录执行上方 Wrangler 命令即可写入密钥。密钥全程加密保存在 Cloudflare Workers 运行时内,不会暴露给前端或浏览器。", + quickLink1: "前往「收件箱 AI 分拣」", + quickLink2: "前往「书签库 → 批量与 AI 整理」", + }, expectPhoneSectionOverflow: false, }, ]; @@ -106,6 +130,65 @@ function fixture(copy) { ${copy.settingsTabs.map((tab, index) => ``).join("")} +
+
+
+
+
+

${copy.aiCard.providerTitle}

+

${copy.aiCard.providerDesc}

+
+
+
+
+ + + + + + +
+
+
+ +
+ + +
+
+
+
+
+
+

${copy.aiCard.secretTitle}

+

${copy.aiCard.secretDesc}

+
+
+
+
+ DOCKMARK_AI_API_KEY + + + ${copy.aiCard.readyLabel} + +
+ +
+
+ npx wrangler secret put DOCKMARK_AI_API_KEY + +
+

${copy.aiCard.footnote}

+ +
+
+
@@ -184,6 +267,53 @@ try { assert.equal(settingsSubnav.overflowing, false, `[${copy.locale}] ${width}px Settings subnav should fit without horizontal overflow.`); assert.equal(settingsSubnav.allInsideViewport, true, `[${copy.locale}] ${width}px all 5 Settings tabs should remain within the viewport.`); + const aiSecretLayout = await page.evaluate(() => { + const grid = document.querySelector(".ai-service-grid"); + const secretCard = document.querySelector(".ai-secret-card"); + if (!(grid instanceof HTMLElement) || !(secretCard instanceof HTMLElement)) { + throw new Error("AI Service Worker Secret Status fixture is missing."); + } + const cardRect = secretCard.getBoundingClientRect(); + const overflowingChildren = [...secretCard.querySelectorAll("*")] + .map((child) => { + const rect = child.getBoundingClientRect(); + return { + tag: child.tagName.toLowerCase(), + className: child.className, + right: rect.right, + cardRight: cardRect.right, + delta: rect.right - cardRect.right, + }; + }) + .filter((item) => item.delta > 1); + return { + gridScrollWidth: grid.scrollWidth, + gridClientWidth: grid.clientWidth, + secretScrollWidth: secretCard.scrollWidth, + secretClientWidth: secretCard.clientWidth, + secretRight: cardRect.right, + viewportWidth: window.innerWidth, + overflowingChildren, + }; + }); + assert.ok( + aiSecretLayout.gridScrollWidth <= aiSecretLayout.gridClientWidth + 1, + `[${copy.locale}] ${width}px .ai-service-grid should not overflow horizontally (${aiSecretLayout.gridScrollWidth} > ${aiSecretLayout.gridClientWidth}).`, + ); + assert.ok( + aiSecretLayout.secretScrollWidth <= aiSecretLayout.secretClientWidth + 1, + `[${copy.locale}] ${width}px .ai-secret-card should not overflow horizontally (${aiSecretLayout.secretScrollWidth} > ${aiSecretLayout.secretClientWidth}).`, + ); + assert.ok( + aiSecretLayout.secretRight <= aiSecretLayout.viewportWidth + 1, + `[${copy.locale}] ${width}px .ai-secret-card right edge should remain inside viewport (${aiSecretLayout.secretRight} > ${aiSecretLayout.viewportWidth}).`, + ); + assert.deepEqual( + aiSecretLayout.overflowingChildren, + [], + `[${copy.locale}] ${width}px all descendants of .ai-secret-card must stay inside card bounds.`, + ); + // Verify zero inner focus-outline bug on .command input while .command outer container highlights cleanly. const commandBefore = await page.evaluate(() => { const wrapper = document.querySelector(".command"); @@ -249,6 +379,7 @@ try { console.log("✓ Web shell has no document-level horizontal overflow at 1280/900/720/390px in both EN and zh-CN"); console.log("✓ Utility and workspace navigation remain stacked, single-line, and sticky while scrolling"); console.log("✓ All 5 Settings subnav tabs (including AI Service) fit cleanly across 1280/900/720/390px without overflow"); + console.log("✓ Settings → AI Service (.ai-service-grid + .ai-secret-card) has zero horizontal overflow and all descendants stay within card bounds across 1280/900/720/390px in EN and zh-CN"); console.log("✓ Focused .command input has zero inner outline while the outer .command wrapper highlights cleanly"); console.log("✓ Tablet and phone breakpoints reclaim nav space without clipping the page"); console.log("✓ Internal sticky sidebars offset below both navigation bars");