From 7c5f64f6a0d4bde503f1bb252f754a79654f76ee Mon Sep 17 00:00:00 2001 From: Warn Date: Mon, 23 Nov 2026 16:27:29 +0800 Subject: [PATCH 1/5] feat(core,web,worker): add shared i18n/locale foundation, AI locale support, and GEB docs --- GEMINI.md | 19 ++ apps/web/src/ai-organization.ts | 11 ++ apps/web/src/extension-distribution.ts | 8 +- apps/web/src/i18n.ts | 238 +++++++++++++++++++++++++ apps/web/src/theme.ts | 50 +++++- apps/web/worker/GEMINI.md | 31 ++++ apps/web/worker/ai-organization.ts | 31 +++- apps/web/worker/settings.ts | 13 ++ packages/core/GEMINI.md | 18 ++ packages/core/src/i18n.ts | 116 ++++++++++++ packages/core/src/index.ts | 7 + packages/core/src/settings.ts | 12 ++ 12 files changed, 543 insertions(+), 11 deletions(-) create mode 100644 GEMINI.md create mode 100644 apps/web/src/i18n.ts create mode 100644 apps/web/worker/GEMINI.md create mode 100644 packages/core/GEMINI.md create mode 100644 packages/core/src/i18n.ts diff --git a/GEMINI.md b/GEMINI.md new file mode 100644 index 0000000..adb1402 --- /dev/null +++ b/GEMINI.md @@ -0,0 +1,19 @@ +# Dockmark - Self-hosted personal bookmark, workspace, and browser command launcher + +TypeScript ^7.0.2 + React ^19.2.8 + Vite ^8.2.2 + Cloudflare Workers & D1 (Wrangler 4.131.1, @cloudflare/vite-plugin ^1.54.7) + WXT ^0.21.4 + + +apps/ - Deployable web app, Cloudflare Worker API, and browser extensions (2 subdirectories: web/, extension/) +packages/ - Shared domain contracts, settings normalization, i18n, search, and URL policy (1 subdirectory: core/) +scripts/ - Release packaging, Cloudflare deploy/migration helpers, and Chromium smoke suites (14 scripts) +docs/ - Architecture, API, security, roadmap, and Firefox validation specifications (1 subdirectory: brand/) + + + +package.json - npm workspace root scripts for dev, build, typecheck, extension packaging, D1 migrations, and smoke tests +tsconfig.base.json - Strict ES2022 bundler TypeScript configuration (strict, exactOptionalPropertyTypes, verbatimModuleSyntax, noUncheckedIndexedAccess) +wrangler.jsonc - Cloudflare Workers entry (apps/web/worker/router.ts), SPA asset serving, and D1 database binding (DB) +.editorconfig - Cross-editor indentation, charset, and newline formatting rules + + +[PROTOCOL]: Update this header on change, then check GEMINI.md diff --git a/apps/web/src/ai-organization.ts b/apps/web/src/ai-organization.ts index 178fbaa..b3bd27a 100644 --- a/apps/web/src/ai-organization.ts +++ b/apps/web/src/ai-organization.ts @@ -1,3 +1,12 @@ +/** + * [INPUT]: depends on ResolvedLocale from @dockmark/core and currentResolvedLocale from ./i18n; calls /api/ai/status, /api/ai/organize, and /api/ai/apply + * [OUTPUT]: exports AI provider settings storage helpers, timeout constants, status fetch, locale-aware suggestion generator, and patch applier + * [POS]: web client wrapper for AI-assisted bookmark organization in apps/web/src; consumed by AiOrganizationSettings.tsx and InboxPage.tsx + * [PROTOCOL]: Update this header on change, then check GEMINI.md + */ +import type { ResolvedLocale } from "@dockmark/core"; +import { currentResolvedLocale } from "./i18n"; + export interface AiProviderSettings { endpoint: string; model: string; @@ -90,6 +99,7 @@ export function getAiProviderStatus() { export async function generateAiOrganizationSuggestions( settings: AiProviderSettings, bookmarkIds: string[], + locale: ResolvedLocale = currentResolvedLocale(), ): Promise { if (!settings.endpoint.trim()) throw new Error("Choose an AI provider endpoint before generating suggestions."); if (!settings.model.trim()) throw new Error("Choose an AI model before generating suggestions."); @@ -106,6 +116,7 @@ export async function generateAiOrganizationSuggestions( model: settings.model.trim(), timeoutSeconds: settings.timeoutSeconds, bookmarkIds, + locale, }), }); return Array.isArray(response.suggestions) ? response.suggestions : []; diff --git a/apps/web/src/extension-distribution.ts b/apps/web/src/extension-distribution.ts index 49e94a6..cbebe95 100644 --- a/apps/web/src/extension-distribution.ts +++ b/apps/web/src/extension-distribution.ts @@ -1,4 +1,10 @@ -export const EXTENSION_RELEASE_VERSION = "1.5.5"; +/** + * [INPUT]: standalone release metadata with no runtime module dependencies + * [OUTPUT]: exports EXTENSION_RELEASE_VERSION, store/download URLs, and compareExtensionVersions + * [POS]: single source of truth for expected browser extension release version and download URLs in apps/web/src + * [PROTOCOL]: Update this header on change, then check GEMINI.md + */ +export const EXTENSION_RELEASE_VERSION = "1.6.0"; // Fill these when browser-store listings are public. The UI will promote the // store action while keeping manual downloads visible. diff --git a/apps/web/src/i18n.ts b/apps/web/src/i18n.ts new file mode 100644 index 0000000..ebabf0e --- /dev/null +++ b/apps/web/src/i18n.ts @@ -0,0 +1,238 @@ +/** + * [INPUT]: depends on useCallback, useEffect, useState from react; depends on LOCALE_STORAGE_KEY, normalizeLocalePreference, resolveLocale, tx, and settings/locale types from @dockmark/core; depends on applyLocalePreference, saveAppearanceAndLocale, and syncAppearanceFromCloud from ./theme + * [OUTPUT]: exports PUBLIC_LOCALE_STORAGE_KEY, localLocalePreference, currentResolvedLocale, applyLocalePreference, bindSystemLocaleListener, saveAppearanceAndLocale, syncAppearanceAndLocaleFromCloud, useI18n, and usePublicI18n + * [POS]: web i18n state, cloud sync, and React hooks for private app and public visitor routes in apps/web/src + * [PROTOCOL]: Update this header on change, then check GEMINI.md + */ +import { useCallback, useEffect, useState } from "react"; +import { + LOCALE_STORAGE_KEY, + normalizeLocalePreference, + resolveLocale, + tx as coreTx, + type AppearanceSettings, + type LocalePreference, + type ResolvedLocale, +} from "@dockmark/core"; +import { + applyLocalePreference, + saveAppearanceAndLocale, + syncAppearanceFromCloud, +} from "./theme"; + +export const PUBLIC_LOCALE_STORAGE_KEY = "dockmarkPublicLocaleV1"; + +export { applyLocalePreference, saveAppearanceAndLocale }; + +export function localLocalePreference(): LocalePreference { + if (typeof window === "undefined") return "system"; + try { + return normalizeLocalePreference(window.localStorage.getItem(LOCALE_STORAGE_KEY)); + } catch { + return "system"; + } +} + +export function currentResolvedLocale(): ResolvedLocale { + return resolveLocale(localLocalePreference()); +} + +export function bindSystemLocaleListener(): () => void { + const listener = () => { + if (localLocalePreference() === "system") { + applyLocalePreference("system", false); + } + }; + window.addEventListener("languagechange", listener); + return () => window.removeEventListener("languagechange", listener); +} + +export async function syncAppearanceAndLocaleFromCloud(): Promise { + return syncAppearanceFromCloud(); +} + +function localPublicLocalePreference(): LocalePreference { + if (typeof window === "undefined") return "system"; + try { + return normalizeLocalePreference(window.localStorage.getItem(PUBLIC_LOCALE_STORAGE_KEY)); + } catch { + return "system"; + } +} + +function applyPublicDocumentLocale(preference: LocalePreference, persist = false): ResolvedLocale { + const normalized = normalizeLocalePreference(preference); + const resolved = resolveLocale(normalized); + if (typeof document !== "undefined") { + document.documentElement.dataset.localePreference = normalized; + document.documentElement.dataset.locale = resolved; + document.documentElement.lang = resolved; + } + if (persist && typeof window !== "undefined") { + try { + window.localStorage.setItem(PUBLIC_LOCALE_STORAGE_KEY, normalized); + } catch { + // Ignore storage write failures in restricted browser contexts. + } + window.dispatchEvent(new CustomEvent("dockmark:public-locale", { detail: { preference: normalized, locale: resolved } })); + } + return resolved; +} + +export function useI18n(): { + locale: ResolvedLocale; + localePreference: LocalePreference; + isZh: boolean; + tx: (en: string, zh: string) => string; + setLocalePreference: (next: LocalePreference, options?: { syncCloud?: boolean }) => Promise; +} { + const [localePreference, setPreferenceState] = useState(() => localLocalePreference()); + const [locale, setLocaleState] = useState(() => resolveLocale(localLocalePreference())); + + useEffect(() => { + const syncFromLocal = () => { + const nextPref = localLocalePreference(); + setPreferenceState(nextPref); + setLocaleState(resolveLocale(nextPref)); + }; + + const onLocaleEvent = (event: Event) => { + const detail = (event as CustomEvent<{ preference?: LocalePreference; locale?: ResolvedLocale }>).detail; + if (detail?.preference) { + const nextPref = normalizeLocalePreference(detail.preference); + setPreferenceState(nextPref); + setLocaleState(detail.locale ?? resolveLocale(nextPref)); + } else { + syncFromLocal(); + } + }; + + const onStorage = (event: StorageEvent) => { + if (event.key !== null && event.key !== LOCALE_STORAGE_KEY) return; + const nextPref = localLocalePreference(); + applyLocalePreference(nextPref, false); + setPreferenceState(nextPref); + setLocaleState(resolveLocale(nextPref)); + }; + + const onLanguageChange = () => { + const nextPref = localLocalePreference(); + if (nextPref === "system") { + applyLocalePreference("system", false); + } + syncFromLocal(); + }; + + window.addEventListener("dockmark:locale", onLocaleEvent); + window.addEventListener("storage", onStorage); + window.addEventListener("languagechange", onLanguageChange); + return () => { + window.removeEventListener("dockmark:locale", onLocaleEvent); + window.removeEventListener("storage", onStorage); + window.removeEventListener("languagechange", onLanguageChange); + }; + }, []); + + const setLocalePreference = useCallback( + async (next: LocalePreference, options?: { syncCloud?: boolean }) => { + const normalized = normalizeLocalePreference(next); + const resolved = applyLocalePreference(normalized, true); + setPreferenceState(normalized); + setLocaleState(resolved); + + if (options?.syncCloud === false) return; + + try { + const saved = await saveAppearanceAndLocale({ locale: normalized }); + const savedResolved = applyLocalePreference(saved.locale, true); + setPreferenceState(saved.locale); + setLocaleState(savedResolved); + } catch (caught) { + const status = typeof caught === "object" && caught !== null && "status" in caught + ? (caught as { status?: unknown }).status + : undefined; + if (status === 401 || status === 403) return; + throw caught; + } + }, + [], + ); + + const tx = useCallback((en: string, zh: string) => coreTx(locale, en, zh), [locale]); + + return { + locale, + localePreference, + isZh: locale === "zh-CN", + tx, + setLocalePreference, + }; +} + +export function usePublicI18n(): { + locale: ResolvedLocale; + localePreference: LocalePreference; + isZh: boolean; + tx: (en: string, zh: string) => string; + setLocalePreference: (next: LocalePreference) => void; +} { + const [localePreference, setPreferenceState] = useState(() => localPublicLocalePreference()); + const [locale, setLocaleState] = useState(() => resolveLocale(localPublicLocalePreference())); + + useEffect(() => { + const syncPublic = () => { + const nextPref = localPublicLocalePreference(); + const nextLocale = applyPublicDocumentLocale(nextPref, false); + setPreferenceState(nextPref); + setLocaleState(nextLocale); + }; + + syncPublic(); + + const onPublicLocaleEvent = () => { + syncPublic(); + }; + + const onOwnerLocaleEvent = () => { + // Keep the visitor's public page language intact if cloud appearance sync finishes after mount. + applyPublicDocumentLocale(localPublicLocalePreference(), false); + }; + + const onStorage = (event: StorageEvent) => { + if (event.key !== null && event.key !== PUBLIC_LOCALE_STORAGE_KEY) return; + syncPublic(); + }; + + const onLanguageChange = () => { + syncPublic(); + }; + + window.addEventListener("dockmark:public-locale", onPublicLocaleEvent); + window.addEventListener("dockmark:locale", onOwnerLocaleEvent); + window.addEventListener("storage", onStorage); + window.addEventListener("languagechange", onLanguageChange); + return () => { + window.removeEventListener("dockmark:public-locale", onPublicLocaleEvent); + window.removeEventListener("dockmark:locale", onOwnerLocaleEvent); + window.removeEventListener("storage", onStorage); + window.removeEventListener("languagechange", onLanguageChange); + }; + }, []); + + const setLocalePreference = useCallback((next: LocalePreference) => { + const normalized = normalizeLocalePreference(next); + const resolved = applyPublicDocumentLocale(normalized, true); + setPreferenceState(normalized); + setLocaleState(resolved); + }, []); + + const tx = useCallback((en: string, zh: string) => coreTx(locale, en, zh), [locale]); + + return { + locale, + localePreference, + isZh: locale === "zh-CN", + tx, + setLocalePreference, + }; +} diff --git a/apps/web/src/theme.ts b/apps/web/src/theme.ts index 374378b..feba367 100644 --- a/apps/web/src/theme.ts +++ b/apps/web/src/theme.ts @@ -1,7 +1,19 @@ +/** + * [INPUT]: depends on LOCALE_STORAGE_KEY, normalizeAppearanceSettings, normalizeLocalePreference, resolveLocale, and appearance/locale types from @dockmark/core + * [OUTPUT]: exports APPEARANCE_STORAGE_KEY, applyAppearance, applyLocalePreference, localAppearance, fetchAppearanceSettings, saveAppearanceSettings, saveAppearanceAndLocale, syncAppearanceFromCloud, and bindSystemAppearanceListener + * [POS]: React-free DOM theme/locale application and /api/settings/appearance client in apps/web/src; consumed by main.tsx, AppearanceSettings.tsx, and i18n.ts + * [PROTOCOL]: Update this header on change, then check GEMINI.md + */ import { + LOCALE_STORAGE_KEY, normalizeAppearanceSettings, + normalizeLocalePreference, + resolveLocale, type AppearancePreference, type AppearanceSettings, + type LocalePreference, + type ResolvedLocale, + type UpdateAppearanceSettingsInput, } from "@dockmark/core"; export const APPEARANCE_STORAGE_KEY = "dockmarkAppearanceV1"; @@ -46,6 +58,27 @@ export function applyAppearance(preference: AppearancePreference, persist = true window.dispatchEvent(new CustomEvent("dockmark:appearance", { detail: { preference, theme } })); } +export function applyLocalePreference(preference: LocalePreference, persist = true): ResolvedLocale { + const normalized = normalizeLocalePreference(preference); + const resolved = resolveLocale(normalized); + if (typeof document !== "undefined") { + document.documentElement.dataset.localePreference = normalized; + document.documentElement.dataset.locale = resolved; + document.documentElement.lang = resolved; + } + if (persist && typeof window !== "undefined") { + try { + window.localStorage.setItem(LOCALE_STORAGE_KEY, normalized); + } catch { + // Ignore storage write failures in restricted browser contexts. + } + } + if (typeof window !== "undefined") { + window.dispatchEvent(new CustomEvent("dockmark:locale", { detail: { preference: normalized, locale: resolved } })); + } + return resolved; +} + export function localAppearance(): AppearancePreference { const stored = localStorage.getItem(APPEARANCE_STORAGE_KEY); return stored === "light" || stored === "dark" || stored === "system" ? stored : "system"; @@ -61,24 +94,33 @@ export async function fetchAppearanceSettings(): Promise { return normalizeAppearanceSettings(payload.settings); } -export async function saveAppearanceSettings(preference: AppearancePreference): Promise { +export async function saveAppearanceAndLocale(input: UpdateAppearanceSettingsInput): Promise { const response = await fetch("/api/settings/appearance", { method: "PATCH", headers: { "content-type": "application/json" }, - body: JSON.stringify({ preference }), + body: JSON.stringify(input), }); const payload = await response.json().catch(() => ({})) as { settings?: unknown; error?: { message?: string }; }; - if (!response.ok) throw new Error(payload.error?.message ?? `Appearance update failed (${response.status}).`); + if (!response.ok) { + const error = new Error(payload.error?.message ?? `Appearance update failed (${response.status}).`) as Error & { status?: number }; + error.status = response.status; + throw error; + } return normalizeAppearanceSettings(payload.settings); } -export async function syncAppearanceFromCloud() { +export async function saveAppearanceSettings(preference: AppearancePreference): Promise { + return saveAppearanceAndLocale({ preference }); +} + +export async function syncAppearanceFromCloud(): Promise { try { const settings = await fetchAppearanceSettings(); applyAppearance(settings.preference); + applyLocalePreference(settings.locale); return settings; } catch { return null; diff --git a/apps/web/worker/GEMINI.md b/apps/web/worker/GEMINI.md new file mode 100644 index 0000000..1bfa1cb --- /dev/null +++ b/apps/web/worker/GEMINI.md @@ -0,0 +1,31 @@ +# apps/web/worker/ +> L2 | Parent: /GEMINI.md + +Cloudflare Worker HTTP API layer backed by D1 (`DB`), mounted at `router.ts` and delegating core CRUD and SPA fallback to `index.ts`. + +## Member list +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/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` and `/api/settings/appearance` persistence in `app_settings` (theme `preference` + `locale`) 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 +capture-inbox.ts: `/api/capture/review`, `/api/inbox`, `/api/inbox/count`, and inbox triage/dismissal routes +capture-write.ts: `/api/capture/bookmark` and `/api/capture/batch` extension-authenticated capture write routes with duplicate handling +change-journal.ts: `/api/library/change-journal` audit log reader and journal entry recorder for reversible library mutations +duplicate-review.ts: `/api/library/duplicates` duplicate URL group detection and reviewed merge/archive actions +health-check.ts: Server-side bookmark reachability probing respecting `HealthPolicy` and recording `health_checks` rows +library-batch-maintenance.ts: Active/archived bookmark listing (`/api/bookmarks`, `/api/bookmarks/archived`) and `/api/bookmarks/batch-maintenance` bulk archive/restore/policy updates +library-batch-organize.ts: `/api/bookmarks/batch-organize` bulk category and tag assignment for selected bookmarks +local-health-result.ts: Extension-reported local-network bookmark health probe ingestion +metadata.ts: Safe public URL title/description/icon fetcher for bookmark metadata enrichment +public-bookmarks.ts: `/api/public/bookmarks` public curated listing and `/api/public/bookmarks/selection` owner curation controls +reorder.ts: `/api/categories/reorder` and `/api/bookmarks/reorder` position persistence +search-engines.ts: `/api/search-engines` CRUD and default engine selection backed by `@dockmark/core` keyword/template validation +sessions.ts: `/api/sessions` saved browser tab-window snapshots and item CRUD +smart-collections.ts: `/api/smart-collections` saved filter collection CRUD +tags.ts: `/api/bookmark-tags` and `/api/bookmarks/:id/tags` normalized tag association endpoints +workspaces.ts: `/api/workspaces` named workspace and workspace item CRUD with open-mode and URL policy normalization + +[PROTOCOL]: Update this header on change, then check GEMINI.md diff --git a/apps/web/worker/ai-organization.ts b/apps/web/worker/ai-organization.ts index 2cdd73a..c00f8eb 100644 --- a/apps/web/worker/ai-organization.ts +++ b/apps/web/worker/ai-organization.ts @@ -1,4 +1,10 @@ -import { inferHealthPolicy, normalizeBookmarkUrl, type HealthPolicy } from "@dockmark/core"; +/** + * [INPUT]: depends on inferHealthPolicy, normalizeBookmarkUrl, HealthPolicy, and ResolvedLocale from @dockmark/core; queries D1 bookmarks, categories, tags, and bookmark_tags + * [OUTPUT]: exports AiOrganizationEnv, AiOrganizationHttpError, and handleAiOrganizationApi + * [POS]: Worker HTTP handler for /api/ai/status and /api/ai/organize in apps/web/worker; proxies OpenAI-compatible suggestion calls with locale-aware prompts + * [PROTOCOL]: Update this header on change, then check GEMINI.md + */ +import { inferHealthPolicy, normalizeBookmarkUrl, type HealthPolicy, type ResolvedLocale } from "@dockmark/core"; type BindValue = string | number | null; @@ -282,8 +288,12 @@ async function loadOrganizationInput(db: D1DatabaseLike, ids: string[]) { }; } -function providerRequestBody(model: string, input: Awaited>) { - const system = [ +function providerRequestBody( + model: string, + input: Awaited>, + locale: ResolvedLocale, +) { + const instructions = [ "You organize a personal bookmark library.", "Return JSON only as an object with a suggestions array.", "Each suggestion must contain bookmarkId, title, description, categoryName, tags.", @@ -293,7 +303,14 @@ function providerRequestBody(model: string, input: Awaited>, timeoutSeconds: number, + locale: ResolvedLocale, ) { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), timeoutSeconds * 1000); - const body = providerRequestBody(model, input); + const body = providerRequestBody(model, input, locale); try { const response = await fetchProviderResponse(endpoint, apiKey, body, controller.signal); @@ -446,9 +464,10 @@ async function organize(request: Request, env: AiOrganizationEnv) { const endpoint = providerEndpoint(requiredString(body, "endpoint", 4096)); const model = requiredString(body, "model", 200); const timeoutSeconds = providerTimeoutSeconds(body.timeoutSeconds); + const locale: ResolvedLocale = body.locale === "zh-CN" ? "zh-CN" : "en"; const ids = bookmarkIds(body.bookmarkIds); const input = await loadOrganizationInput(env.DB, ids); - const payload = await callProvider(endpoint, model, apiKey, input, timeoutSeconds); + const payload = await callProvider(endpoint, model, apiKey, input, timeoutSeconds, locale); const text = extractText(payload); if (!text) { throw new AiOrganizationHttpError(502, "provider_missing_output", "AI provider response did not contain a supported text result."); diff --git a/apps/web/worker/settings.ts b/apps/web/worker/settings.ts index 8839e91..77daee2 100644 --- a/apps/web/worker/settings.ts +++ b/apps/web/worker/settings.ts @@ -1,3 +1,9 @@ +/** + * [INPUT]: depends on browser/appearance settings helpers and LocalePreference from @dockmark/core; queries D1 app_settings, bookmark_tags, smart_collections, and bookmarks tables + * [OUTPUT]: exports SettingsDbLike, SettingsHttpError, loadAppearanceSettings, and handleSettingsApi + * [POS]: Worker HTTP handler for /api/settings/browser and /api/settings/appearance in apps/web/worker + * [PROTOCOL]: Update this header on change, then check GEMINI.md + */ import { DEFAULT_APPEARANCE_SETTINGS, DEFAULT_BROWSER_SETTINGS, @@ -11,6 +17,7 @@ import { type BookmarkConflictPreference, type BrowserNewTabSettings, type BrowserSettings, + type LocalePreference, type UpdateAppearanceSettingsInput, type UpdateBrowserSettingsInput, } from "@dockmark/core"; @@ -96,6 +103,11 @@ function parseAppearancePreference(value: unknown): AppearancePreference { throw new SettingsHttpError(400, "invalid_field", "preference must be system, light or dark."); } +function parseLocalePreference(value: unknown): LocalePreference { + if (value === "system" || value === "en" || value === "zh-CN") return value; + throw new SettingsHttpError(400, "invalid_field", "locale must be system, en or zh-CN."); +} + function parseInteger(value: unknown, key: string, min: number, max: number) { if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) { throw new SettingsHttpError(400, "invalid_field", `${key} must be an integer between ${min} and ${max}.`); @@ -219,6 +231,7 @@ function parseBrowserUpdate(body: Record): UpdateBrowserSetting function parseAppearanceUpdate(body: Record): UpdateAppearanceSettingsInput { const update: UpdateAppearanceSettingsInput = {}; if (hasOwn(body, "preference")) update.preference = parseAppearancePreference(body.preference); + if (hasOwn(body, "locale")) update.locale = parseLocalePreference(body.locale); return update; } diff --git a/packages/core/GEMINI.md b/packages/core/GEMINI.md new file mode 100644 index 0000000..2635afa --- /dev/null +++ b/packages/core/GEMINI.md @@ -0,0 +1,18 @@ +# packages/core/ +> L2 | Parent: /GEMINI.md + +Shared zero-dependency domain layer consumed by `@dockmark/web`, `apps/web/worker`, and `@dockmark/extension`. + +## Member list +package.json: `@dockmark/core` workspace manifest exporting `./src/index.ts` and running `tsc -p tsconfig.json` +tsconfig.json: Package TypeScript config extending `../../tsconfig.base.json` +src/index.ts: Public barrel re-exporting models, settings, i18n, URL policy, bookmark URL normalization, 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` and `AppearanceSettings` (including `locale: LocalePreference`) 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 +src/command-rank.ts: Launcher source weights (`LAUNCHER_SOURCE_WEIGHT`), default labels, and `rankCommandResults` ordering +src/search.ts: Search engine keyword validation (`normalizeSearchKeyword`), `%s` template validation (`validateSearchTemplate`), and query URL builder + +[PROTOCOL]: Update this header on change, then check GEMINI.md diff --git a/packages/core/src/i18n.ts b/packages/core/src/i18n.ts new file mode 100644 index 0000000..d212a7e --- /dev/null +++ b/packages/core/src/i18n.ts @@ -0,0 +1,116 @@ +/** + * [INPUT]: depends on CommandSource, HealthPolicy, and HealthStatus types from ./models + * [OUTPUT]: provides locale types, LOCALE_STORAGE_KEY, normalizeLocalePreference, resolveLocale, tx, formatRelativeTime, SOURCE_LABELS, HEALTH_STATUS_LABELS, and HEALTH_POLICY_LABELS + * [POS]: shared i18n primitives and canonical bilingual dictionaries in packages/core/src; consumed by settings, web, worker, and extension + * [PROTOCOL]: Update this header on change, then check GEMINI.md + */ +import type { CommandSource, HealthPolicy, HealthStatus } from "./models"; + +export type LocalePreference = "system" | "en" | "zh-CN"; +export type ResolvedLocale = "en" | "zh-CN"; + +export const LOCALE_STORAGE_KEY = "dockmarkLocaleV1"; + +export function normalizeLocalePreference(value: unknown): LocalePreference { + if (typeof value !== "string") return "system"; + const normalized = value.trim().toLowerCase().replace(/_/g, "-"); + if (normalized === "en" || normalized.startsWith("en-")) return "en"; + if (normalized === "zh" || normalized.startsWith("zh-")) return "zh-CN"; + return "system"; +} + +export function resolveLocale(preference: LocalePreference, browserLanguage?: string): ResolvedLocale { + if (preference === "en" || preference === "zh-CN") return preference; + const candidate = (browserLanguage ?? (typeof navigator !== "undefined" ? navigator.language : "en")).trim().toLowerCase(); + return candidate.startsWith("zh") ? "zh-CN" : "en"; +} + +export function tx(locale: ResolvedLocale, en: string, zh: string): string { + return locale === "zh-CN" ? zh : en; +} + +export function formatRelativeTime(isoValue: string | null | undefined, locale: ResolvedLocale): string { + if (!isoValue) return tx(locale, "never", "从未"); + const timestamp = Date.parse(isoValue); + if (!Number.isFinite(timestamp)) return tx(locale, "never", "从未"); + + const diffMs = Math.max(0, Date.now() - timestamp); + const diffMinutes = Math.floor(diffMs / 60_000); + if (diffMinutes < 1) return tx(locale, "just now", "刚刚"); + if (diffMinutes < 60) return tx(locale, `${diffMinutes}m ago`, `${diffMinutes} 分钟前`); + + const diffHours = Math.floor(diffMinutes / 60); + if (diffHours < 24) return tx(locale, `${diffHours}h ago`, `${diffHours} 小时前`); + + const diffDays = Math.floor(diffHours / 24); + return tx(locale, `${diffDays}d ago`, `${diffDays} 天前`); +} + +export const SOURCE_LABELS: Record> = { + en: { + tab: "Open tab", + workspace: "Workspace", + session: "Session", + collection: "Collection", + bookmark: "Bookmark", + navigation: "Navigation", + search: "Search", + }, + "zh-CN": { + tab: "打开的标签页", + workspace: "工作区", + session: "会话", + collection: "智能合集", + bookmark: "书签", + navigation: "导航", + search: "搜索", + }, +}; + +export const HEALTH_STATUS_LABELS: Record> = { + en: { + unknown: "Unknown", + healthy: "Healthy", + redirected: "Redirected", + "auth-required": "Auth required", + forbidden: "Forbidden", + "rate-limited": "Rate limited", + timeout: "Timeout", + "dns-error": "DNS error", + "tls-error": "TLS error", + unavailable: "Unavailable", + "local-only": "Local-only", + ignored: "Ignored", + }, + "zh-CN": { + unknown: "未知", + healthy: "正常", + redirected: "已重定向", + "auth-required": "需要认证", + forbidden: "禁止访问", + "rate-limited": "触发限流", + timeout: "请求超时", + "dns-error": "DNS 错误", + "tls-error": "TLS 错误", + unavailable: "无法访问", + "local-only": "仅本地", + ignored: "已忽略", + }, +}; + +export const HEALTH_POLICY_LABELS: Record> = { + en: { + auto: "Auto", + normal: "Normal", + ignore: "Ignore", + "local-only": "Local-only", + manual: "Manual", + }, + "zh-CN": { + auto: "自动", + normal: "常规", + ignore: "忽略", + "local-only": "仅本地", + manual: "手动", + }, +}; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index b927a7c..8b815c4 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,5 +1,12 @@ +/** + * [INPUT]: depends on models, settings, i18n, url-policy, bookmark-url, command-rank, and search modules + * [OUTPUT]: re-exports the public @dockmark/core surface + * [POS]: package barrel entry point for packages/core/src + * [PROTOCOL]: Update this header on change, then check GEMINI.md + */ export * from "./models"; export * from "./settings"; +export * from "./i18n"; export * from "./url-policy"; export * from "./bookmark-url"; export * from "./command-rank"; diff --git a/packages/core/src/settings.ts b/packages/core/src/settings.ts index 92ecad7..b864f6e 100644 --- a/packages/core/src/settings.ts +++ b/packages/core/src/settings.ts @@ -1,4 +1,11 @@ +/** + * [INPUT]: depends on Id from ./models; depends on LocalePreference and normalizeLocalePreference from ./i18n + * [OUTPUT]: provides browser and appearance 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 + */ import type { Id } from "./models"; +import { normalizeLocalePreference, type LocalePreference } from "./i18n"; export const BROWSER_SETTINGS_VERSION = 1; export const APPEARANCE_SETTINGS_VERSION = 1; @@ -29,11 +36,13 @@ export interface UpdateBrowserSettingsInput { export interface AppearanceSettings { version: typeof APPEARANCE_SETTINGS_VERSION; preference: AppearancePreference; + locale: LocalePreference; updatedAt: string | null; } export interface UpdateAppearanceSettingsInput { preference?: AppearancePreference; + locale?: LocalePreference; } export const DEFAULT_BROWSER_SETTINGS: BrowserSettings = { @@ -52,6 +61,7 @@ export const DEFAULT_BROWSER_SETTINGS: BrowserSettings = { export const DEFAULT_APPEARANCE_SETTINGS: AppearanceSettings = { version: APPEARANCE_SETTINGS_VERSION, preference: "system", + locale: "system", updatedAt: null, }; @@ -118,6 +128,7 @@ export function normalizeAppearanceSettings(value: unknown): AppearanceSettings return { version: APPEARANCE_SETTINGS_VERSION, preference: normalizeAppearancePreference(record.preference), + locale: normalizeLocalePreference(record.locale), updatedAt: typeof record.updatedAt === "string" && record.updatedAt ? record.updatedAt : null, }; } @@ -146,6 +157,7 @@ export function mergeAppearanceSettings( return normalizeAppearanceSettings({ ...current, ...(input.preference === undefined ? {} : { preference: input.preference }), + ...(input.locale === undefined ? {} : { locale: input.locale }), updatedAt, }); } From c1e0141630a2dcc64562b008783820806f4c5392 Mon Sep 17 00:00:00 2001 From: Warn Date: Mon, 23 Nov 2026 16:34:38 +0800 Subject: [PATCH 2/5] feat(web): polish management views, extract subcomponents, and add EN/zh-CN i18n --- apps/web/src/AiOrganizationSettings.tsx | 342 +++++++-- apps/web/src/BookmarkCategorySidebar.tsx | 191 +++++ apps/web/src/BookmarkFavicon.tsx | 75 ++ apps/web/src/BookmarkFormFields.tsx | 157 +++++ apps/web/src/BookmarkMaintenance.tsx | 390 ++++++++--- apps/web/src/BookmarkManager.tsx | 41 +- apps/web/src/BookmarkManagerLegacy.tsx | 450 ++++++------ apps/web/src/ChangeJournal.tsx | 133 +++- apps/web/src/DuplicateReviewPage.tsx | 394 ++++++++--- apps/web/src/InboxPage.tsx | 529 ++++++++------ apps/web/src/InboxReviewCard.tsx | 359 ++++++++++ apps/web/src/LibraryBulkMaintenance.tsx | 263 +++++-- apps/web/src/LibraryBulkOrganizer.tsx | 166 +++-- apps/web/src/NativeBookmarkImport.tsx | 418 +++++------ apps/web/src/NativeBookmarkSyncPanels.tsx | 424 +++++++++++ apps/web/src/SearchEngineManager.tsx | 263 +++++-- apps/web/src/SessionManager.tsx | 314 +++++++-- apps/web/src/SmartCollectionsPage.tsx | 494 ++++++++++--- apps/web/src/TransferManager.tsx | 267 +++++-- apps/web/src/WorkspaceManager.tsx | 410 ++++++++--- apps/web/src/ai-organization.css | 62 +- apps/web/src/bookmark-tags.css | 89 ++- apps/web/src/change-journal.css | 67 +- apps/web/src/duplicate-review.css | 547 +++++++++++++-- apps/web/src/health.css | 15 +- apps/web/src/inbox.css | 813 +++++++++++++++++++--- apps/web/src/library-bulk.css | 169 +++-- apps/web/src/maintenance.css | 118 ++-- apps/web/src/reorder.css | 11 +- apps/web/src/search-engines.css | 419 ++++++++++- apps/web/src/session.css | 549 +++++++++++++-- apps/web/src/smart-collections.css | 544 +++++++++++++-- apps/web/src/transfer.css | 771 +++++++++++++++++--- apps/web/src/workspaces.css | 461 ++++++++++-- 34 files changed, 8560 insertions(+), 2155 deletions(-) create mode 100644 apps/web/src/BookmarkCategorySidebar.tsx create mode 100644 apps/web/src/BookmarkFavicon.tsx create mode 100644 apps/web/src/BookmarkFormFields.tsx create mode 100644 apps/web/src/InboxReviewCard.tsx create mode 100644 apps/web/src/NativeBookmarkSyncPanels.tsx diff --git a/apps/web/src/AiOrganizationSettings.tsx b/apps/web/src/AiOrganizationSettings.tsx index 2879f95..7688e55 100644 --- a/apps/web/src/AiOrganizationSettings.tsx +++ b/apps/web/src/AiOrganizationSettings.tsx @@ -1,5 +1,12 @@ +/** + * [INPUT]: depends on Bookmark, Category, HEALTH_POLICY_LABELS from @dockmark/core; AI APIs from ./ai-organization; listBookmarkTags from ./tag-api; useI18n from ./i18n + * [OUTPUT]: exports AiOrganizationSettings component + * [POS]: provider configuration, bookmark selection queue, and diff review workbench for AI-assisted organization inside the Organize tab + * [PROTOCOL]: Update this header on change, then check GEMINI.md + */ + import { useEffect, useMemo, useState } from "react"; -import type { Bookmark, Category } from "@dockmark/core"; +import { HEALTH_POLICY_LABELS, type Bookmark, type Category } from "@dockmark/core"; import { applyAiOrganizationPatches, generateAiOrganizationSuggestions, @@ -12,6 +19,7 @@ import { type AiOrganizationSuggestion, type AiProviderSettings, } from "./ai-organization"; +import { useI18n } from "./i18n"; import { listBookmarkTags } from "./tag-api"; import "./ai-organization.css"; @@ -23,8 +31,8 @@ interface Props { type QueueFilter = "pending" | "generated" | "all"; -function messageFrom(error: unknown) { - return error instanceof Error ? error.message : "Something went wrong."; +function messageFrom(error: unknown, fallback: string) { + return error instanceof Error ? error.message : fallback; } function sameTags(left: string[], right: string[]) { @@ -34,6 +42,10 @@ function sameTags(left: string[], right: string[]) { } export function AiOrganizationSettings({ bookmarks, categories, onChanged }: Props) { + const { locale, tx } = useI18n(); + const policyLabels = HEALTH_POLICY_LABELS[locale]; + const genericError = tx("Something went wrong.", "操作失败,请重试。"); + const [provider, setProvider] = useState(() => loadAiProviderSettings()); const [apiKeyConfigured, setApiKeyConfigured] = useState(null); const [bookmarkTags, setBookmarkTags] = useState>({}); @@ -59,7 +71,7 @@ export function AiOrganizationSettings({ bookmarks, categories, onChanged }: Pro setBookmarkTags(nextTags); setApiKeyConfigured(status.apiKeyConfigured); } catch (caught) { - if (!cancelled) setError(messageFrom(caught)); + if (!cancelled) setError(messageFrom(caught, genericError)); } finally { if (!cancelled) setLoadingTags(false); } @@ -123,11 +135,17 @@ export function AiOrganizationSettings({ bookmarks, categories, onChanged }: Pro setError(null); setMessage(null); if (!providerTimeoutValid()) { - setError(`Provider timeout must be between ${MIN_AI_TIMEOUT_SECONDS} and ${MAX_AI_TIMEOUT_SECONDS} seconds.`); + setError(tx( + `Provider timeout must be between ${MIN_AI_TIMEOUT_SECONDS} and ${MAX_AI_TIMEOUT_SECONDS} seconds.`, + `超时时间需在 ${MIN_AI_TIMEOUT_SECONDS} 到 ${MAX_AI_TIMEOUT_SECONDS} 秒之间。`, + )); return; } saveAiProviderSettings(provider); - setMessage("Provider endpoint, model and timeout saved in this browser. The API key stays in the Worker secret store."); + setMessage(tx( + "Provider endpoint, model, and timeout saved locally. The API key stays in the Worker secret store.", + "接口地址、模型与超时配置已保存到本地浏览器;API 密钥仅保存在 Worker 密钥库中。", + )); } async function refreshKeyStatus() { @@ -135,9 +153,11 @@ export function AiOrganizationSettings({ bookmarks, categories, onChanged }: Pro try { const status = await getAiProviderStatus(); setApiKeyConfigured(status.apiKeyConfigured); - setMessage(status.apiKeyConfigured ? "Worker AI secret is configured." : "Worker AI secret is still missing."); + setMessage(status.apiKeyConfigured + ? tx("Worker AI secret is configured.", "Worker AI 密钥已就绪。") + : tx("Worker AI secret is not configured yet.", "尚未配置 Worker AI 密钥。")); } catch (caught) { - setError(messageFrom(caught)); + setError(messageFrom(caught, genericError)); } } @@ -177,20 +197,29 @@ export function AiOrganizationSettings({ bookmarks, categories, onChanged }: Pro setGeneratedIds(new Set()); setQueueFilter("pending"); setSelectedIds(new Set()); - setMessage("AI generation progress reset for this page session. No bookmark data was changed."); + setMessage(tx( + "AI generation progress reset for this session. No bookmark data was changed.", + "已重置本次页面会话的生成进度,未修改任何书签数据。", + )); setError(null); } function discardPreview() { setSuggestions([]); setAcceptedIds(new Set()); - setMessage("Current AI preview discarded. Generated markers and the next queue selection were kept."); + setMessage(tx( + "Current AI preview discarded. Session markers and next queue selection were kept.", + "已放弃当前 AI 预览,保留已生成标记与下一批待选队列。", + )); setError(null); } async function generate() { if (suggestions.length) { - setError("Review, apply, or discard the current AI preview before generating another batch."); + setError(tx( + "Review, apply, or discard the current AI preview before generating another batch.", + "请先复核、应用或放弃当前 AI 建议,再生成下一批。", + )); return; } const selected = bookmarks.filter((bookmark) => selectedIds.has(bookmark.id) && bookmark.healthPolicy === "normal"); @@ -202,7 +231,11 @@ export function AiOrganizationSettings({ bookmarks, categories, onChanged }: Pro setAcceptedIds(new Set()); try { saveAiProviderSettings(provider); - const next = await generateAiOrganizationSuggestions(provider, selected.map((bookmark) => bookmark.id)); + const next = await generateAiOrganizationSuggestions( + provider, + selected.map((bookmark) => bookmark.id), + locale, + ); const generatedAfter = new Set(generatedIds); next.forEach((suggestion) => generatedAfter.add(suggestion.bookmarkId)); setGeneratedIds(generatedAfter); @@ -214,11 +247,17 @@ export function AiOrganizationSettings({ bookmarks, categories, onChanged }: Pro const remainingAfter = allEligible.filter((bookmark) => !generatedAfter.has(bookmark.id)).length; setMessage( next.length === selected.length - ? `Generated ${next.length} suggestions. ${remainingAfter} eligible bookmark${remainingAfter === 1 ? "" : "s"} remain; ${nextBatch.length} next queued for selection. Review the current preview before generating again.` - : `Generated ${next.length} of ${selected.length} requested suggestions. Missing rows remain pending and can be retried; ${nextBatch.length} bookmarks are queued next.`, + ? tx( + `Generated ${next.length} suggestions. ${remainingAfter} eligible bookmark${remainingAfter === 1 ? "" : "s"} remain; ${nextBatch.length} queued next.`, + `已生成 ${next.length} 条建议,剩余 ${remainingAfter} 个可整理书签,已自动预选下一批 ${nextBatch.length} 项。`, + ) + : tx( + `Generated ${next.length} of ${selected.length} requested suggestions. Missing rows stay pending; ${nextBatch.length} queued next.`, + `已生成 ${next.length}/${selected.length} 条建议,未返回项仍保留在待生成队列,已预选下一批 ${nextBatch.length} 项。`, + ), ); } catch (caught) { - setError(messageFrom(caught)); + setError(messageFrom(caught, genericError)); } finally { setGenerating(false); } @@ -254,7 +293,10 @@ export function AiOrganizationSettings({ bookmarks, categories, onChanged }: Pro if (suggestion.categoryName) { const mapped = categoryByName.get(suggestion.categoryName.toLocaleLowerCase()); if (!mapped) { - throw new Error(`Suggested category “${suggestion.categoryName}” no longer exists. Refresh and regenerate before applying.`); + throw new Error(tx( + `Suggested category “${suggestion.categoryName}” no longer exists. Refresh and regenerate before applying.`, + `建议的分类「${suggestion.categoryName}」已不存在,请刷新并重新生成后再应用。`, + )); } categoryId = mapped; } @@ -269,7 +311,10 @@ export function AiOrganizationSettings({ bookmarks, categories, onChanged }: Pro } if (!patches.length) { - setMessage(`No reviewed AI patches were applied${skipped ? `; ${skipped} bookmarks are no longer AI-eligible` : ""}.`); + setMessage(tx( + `No reviewed AI patches were applied${skipped ? `; ${skipped} bookmarks are no longer AI-eligible` : ""}.`, + `未应用任何 AI 建议${skipped ? `;${skipped} 个书签已不符合 AI 整理条件` : ""}。`, + )); return; } @@ -285,12 +330,12 @@ export function AiOrganizationSettings({ bookmarks, categories, onChanged }: Pro await onChanged(); setSuggestions((current) => current.filter((suggestion) => !appliedIds.has(suggestion.bookmarkId))); setAcceptedIds((current) => new Set(Array.from(current).filter((id) => !appliedIds.has(id)))); - setMessage( - `Applied ${result.applied} reviewed AI suggestion${result.applied === 1 ? "" : "s"} in one atomic batch` + - `${skipped ? `; ${skipped} skipped because the bookmark is no longer AI-eligible` : ""}. URLs and HealthPolicy were untouched.`, - ); + setMessage(tx( + `Applied ${result.applied} reviewed AI suggestion${result.applied === 1 ? "" : "s"} atomically${skipped ? `; ${skipped} skipped` : ""}. URLs and health policies were untouched.`, + `已一次性应用 ${result.applied} 条 AI 建议${skipped ? `(跳过 ${skipped} 项)` : ""},网址与健康策略未作修改。`, + )); } catch (caught) { - setError(messageFrom(caught)); + setError(messageFrom(caught, genericError)); } finally { setApplying(false); } @@ -298,33 +343,63 @@ export function AiOrganizationSettings({ bookmarks, categories, onChanged }: Pro return (
-
+
-

AI-ASSISTED ORGANIZATION

-

Suggest first.
Apply only after review.

-

Classify bookmarks into existing categories, clean titles, draft descriptions and suggest tags. Dockmark never sends a bookmark until you explicitly select it and click Generate, and it never applies a suggestion until you review the diff.

+

{tx("AI-assisted organization", "AI 辅助整理")}

+

+ {tx( + "Classify bookmarks into existing categories, clean titles, draft descriptions, and suggest tags. Nothing is sent or applied until you review.", + "按现有分类整理书签、优化标题、起草描述并推荐标签。仅在你手动生成并确认差异后才会写入。", + )} +

- {apiKeyConfigured === null ? "Checking AI secret" : apiKeyConfigured ? "Worker secret ready" : "Worker secret required"} - Max 20 bookmarks / request + + {apiKeyConfigured === null + ? tx("Checking AI secret", "检查 AI 密钥中") + : apiKeyConfigured + ? tx("Worker secret ready", "Worker 密钥就绪") + : tx("Worker secret required", "需配置 Worker 密钥")} + + {tx("Max 20 bookmarks / request", "单次最多 20 个书签")}
-

OpenAI-compatible provider

Endpoint, model and timeout are browser-local preferences. The API key is never stored in Web localStorage or D1; the Worker reads it from DOCKMARK_AI_API_KEY.

+
+

{tx("OpenAI-compatible provider", "OpenAI 兼容接口配置")}

+

+ {tx( + "Endpoint, model, and timeout are saved locally in this browser. The API key is read by the Worker from ", + "接口地址、模型与超时仅保存在当前浏览器;API 密钥由 Worker 从 ", + )} + DOCKMARK_AI_API_KEY + {tx(".", " 读取,绝不暴露给前端。")} +

+
- - + +

- Configure the secret in your self-hosted Worker with npx wrangler secret put DOCKMARK_AI_API_KEY or the Cloudflare dashboard. The provider endpoint must be public HTTPS. Selected bookmark content is loaded by the Worker and sent only after Generate; the key never enters the page. + {tx("Set the secret with ", "使用 ")} + npx wrangler secret put DOCKMARK_AI_API_KEY + {tx( + " or in the Cloudflare dashboard. The endpoint must be public HTTPS.", + " 或在 Cloudflare 控制台配置密钥;接口地址须为公网 HTTPS。", + )}

-

Select bookmarks

Generation progress is tracked only for this page session. Generated rows can be filtered out while the next ungenerated batch is queued automatically.

+
+

{tx("Select bookmarks", "选择待整理书签")}

+

+ {tx( + "Progress is tracked for this session so generated items can be filtered out while the next batch queues automatically.", + "进度仅在本次页面会话内跟踪,生成后会自动预选下一批待整理书签。", + )} +

+
{selectedIds.size}/20
- setQuery(event.target.value)} placeholder="Filter title or URL…" aria-label="Filter bookmarks for AI organization" /> + setQuery(event.target.value)} + placeholder={tx("Filter title or URL…", "按标题或网址筛选…")} + aria-label={tx("Filter bookmarks for AI organization", "筛选 AI 整理书签")} + />
-
- - - +
+ + +
- {generatedCount} generated this session · {remainingCount} eligible remaining + + {tx( + `${generatedCount} generated this session · ${remainingCount} remaining`, + `本次已生成 ${generatedCount} 项 · 剩余 ${remainingCount} 项`, + )} +
- - - - + + + +
{selectedGeneratedCount > 0 && ( -

{selectedGeneratedCount} selected bookmark{selectedGeneratedCount === 1 ? " was" : "s were"} already generated in this session. Generate will intentionally refresh those suggestions.

+

+ {tx( + `${selectedGeneratedCount} selected bookmark${selectedGeneratedCount === 1 ? " was" : "s were"} already generated in this session and will be refreshed.`, + `已选中有 ${selectedGeneratedCount} 个书签在本次会话已生成过,继续生成将刷新其建议。`, + )} +

)}
{filteredBookmarks.slice(0, 120).map((bookmark) => { const protectedPolicy = bookmark.healthPolicy !== "normal"; const generated = generatedIds.has(bookmark.id); - const category = categoryById.get(bookmark.categoryId ?? "") ?? "UNCATEGORIZED"; + const category = categoryById.get(bookmark.categoryId ?? "") ?? tx("Uncategorized", "未分类"); return ( ); })} - {!filteredBookmarks.length &&

No bookmarks match this queue view.

} + {!filteredBookmarks.length && ( +

{tx("No bookmarks match this queue view.", "当前队列视图下暂无匹配书签。")}

+ )}
-
@@ -408,13 +551,30 @@ export function AiOrganizationSettings({ bookmarks, categories, onChanged }: Pro {suggestions.length > 0 && (
-

AI PREVIEW · NOTHING APPLIED YET

Review proposed organization

+
+

{tx("Review proposed organization", "复核 AI 整理建议")}

+

+ {tx("Preview only — nothing has been written yet.", "仅预览,尚未写入任何更改。")} +

+
- - - + + +
@@ -422,35 +582,71 @@ export function AiOrganizationSettings({ bookmarks, categories, onChanged }: Pro {suggestions.map((suggestion) => { const bookmark = bookmarkById.get(suggestion.bookmarkId); if (!bookmark) return null; - const currentCategory = bookmark.categoryId ? categoryById.get(bookmark.categoryId) ?? "Unknown category" : "Uncategorized"; - const nextCategory = suggestion.categoryName ?? "Uncategorized"; + const currentCategory = bookmark.categoryId + ? categoryById.get(bookmark.categoryId) ?? tx("Unknown category", "未知分类") + : tx("Uncategorized", "未分类"); + const nextCategory = suggestion.categoryName ?? tx("Uncategorized", "未分类"); const currentTags = bookmarkTags[bookmark.id] ?? []; const titleChanged = suggestion.title !== bookmark.title; const descriptionChanged = suggestion.description !== (bookmark.description ?? ""); const categoryChanged = nextCategory !== currentCategory; const tagsChanged = !sameTags(suggestion.tags, currentTags); + const changedLabels = [ + titleChanged && tx("Title", "标题"), + descriptionChanged && tx("Description", "描述"), + categoryChanged && tx("Category", "分类"), + tagsChanged && tx("Tags", "标签"), + ].filter(Boolean).join(" · ") || tx("No field change", "无字段变动"); + return (
-
TitleCurrent{bookmark.title}Suggested{suggestion.title || bookmark.title}
-
CategoryCurrent{currentCategory}Suggested{nextCategory}
-
DescriptionCurrent{bookmark.description || "—"}Suggested{suggestion.description || "—"}
-
TagsCurrent{currentTags.join(", ") || "—"}Suggested{suggestion.tags.join(", ") || "—"}
+
+ {tx("Title", "标题")} + {tx("Current", "当前")}{bookmark.title} + {tx("Suggested", "建议")}{suggestion.title || bookmark.title} +
+
+ {tx("Category", "分类")} + {tx("Current", "当前")}{currentCategory} + {tx("Suggested", "建议")}{nextCategory} +
+
+ {tx("Description", "描述")} + {tx("Current", "当前")}{bookmark.description || "—"} + {tx("Suggested", "建议")}{suggestion.description || "—"} +
+
+ {tx("Tags", "标签")} + {tx("Current", "当前")}{currentTags.join(", ") || "—"} + {tx("Suggested", "建议")}{suggestion.tags.join(", ") || "—"} +
); })}
-

Apply sends the reviewed title, description, category and tags once and commits them as one D1 batch. URL, HealthPolicy, HealthStatus, browser mappings and health history remain outside the AI write surface.

+

+ {tx( + "Applying commits reviewed titles, descriptions, categories, and tags in one atomic batch. URLs, health policies, health history, and browser mappings remain untouched.", + "应用后会以单次原子事务写入确认过的标题、描述、分类与标签;网址、健康策略、健康历史与浏览器映射不受影响。", + )} +

)} - {loadingTags &&

Loading existing tags and AI secret status…

} + {loadingTags && ( +

{tx("Loading existing tags and AI secret status…", "正在加载已有标签与 AI 密钥状态…")}

+ )} ); } diff --git a/apps/web/src/BookmarkCategorySidebar.tsx b/apps/web/src/BookmarkCategorySidebar.tsx new file mode 100644 index 0000000..f5c8621 --- /dev/null +++ b/apps/web/src/BookmarkCategorySidebar.tsx @@ -0,0 +1,191 @@ +/** + * [INPUT]: depends on Category from @dockmark/core; useI18n from ./i18n + * [OUTPUT]: exports BookmarkCategorySidebar component + * [POS]: left sidebar of BookmarkManagerLegacy handling category CRUD/reordering and tag filter chips + * [PROTOCOL]: Update this header on change, then check GEMINI.md + */ + +import type { DragEvent, FormEvent } from "react"; +import type { Category } from "@dockmark/core"; +import { useI18n } from "./i18n"; + +export interface TagCountItem { + name: string; + count: number; +} + +interface Props { + categories: Category[]; + tagSummary: TagCountItem[]; + activeTag: string | null; + newCategory: string; + editingCategoryId: string | null; + editingCategoryName: string; + draggedCategoryId: string | null; + busy: boolean; + reordering: boolean; + onNewCategoryChange: (value: string) => void; + onSubmitCategory: (event: FormEvent) => void; + onStartEditCategory: (category: Category) => void; + onCancelEditCategory: () => void; + onEditingCategoryNameChange: (value: string) => void; + onSubmitCategoryEdit: (event: FormEvent, id: string) => void; + onDeleteCategory: (category: Category) => void; + onDragStartCategory: (id: string) => void; + onDragEndCategory: () => void; + onDropCategory: (event: DragEvent, targetId: string) => void; + onMoveCategory: (id: string, offset: -1 | 1) => void; + onSelectTag: (tag: string | null) => void; +} + +export function BookmarkCategorySidebar({ + categories, + tagSummary, + activeTag, + newCategory, + editingCategoryId, + editingCategoryName, + draggedCategoryId, + busy, + reordering, + onNewCategoryChange, + onSubmitCategory, + onStartEditCategory, + onCancelEditCategory, + onEditingCategoryNameChange, + onSubmitCategoryEdit, + onDeleteCategory, + onDragStartCategory, + onDragEndCategory, + onDropCategory, + onMoveCategory, + onSelectTag, +}: Props) { + const { tx } = useI18n(); + + return ( + + ); +} diff --git a/apps/web/src/BookmarkFavicon.tsx b/apps/web/src/BookmarkFavicon.tsx new file mode 100644 index 0000000..7a54bce --- /dev/null +++ b/apps/web/src/BookmarkFavicon.tsx @@ -0,0 +1,75 @@ +/** + * [INPUT]: depends on useEffect, useState from react + * [OUTPUT]: exports BookmarkFavicon component and safeDomainLabel helper + * [POS]: shared icon renderer for web management cards, showing valid HTTP/HTTPS favicons with a crisp monogram fallback + * [PROTOCOL]: Update this header on change, then check GEMINI.md + */ + +import { useEffect, useState } from "react"; + +interface Props { + iconUrl?: string | null | undefined; + title: string; + url?: string | undefined; + className?: string | undefined; +} + +function safeHttpUrl(value: string | null | undefined): string | null { + if (!value) return null; + const trimmed = value.trim(); + if (!trimmed) return null; + try { + const parsed = new URL(trimmed); + return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.toString() : null; + } catch { + return null; + } +} + +export function safeDomainLabel(url: string): string { + try { + return new URL(url).hostname.replace(/^www\./i, ""); + } catch { + return url; + } +} + +function monogramFor(title: string, url?: string): string { + const cleanedTitle = title.trim(); + if (cleanedTitle) return cleanedTitle.slice(0, 1).toUpperCase(); + if (url) { + const host = safeDomainLabel(url).trim(); + if (host) return host.slice(0, 1).toUpperCase(); + } + return "•"; +} + +export function BookmarkFavicon({ iconUrl, title, url, className = "bookmark-icon" }: Props) { + const safeSrc = safeHttpUrl(iconUrl); + const [failed, setFailed] = useState(false); + + useEffect(() => { + setFailed(false); + }, [safeSrc]); + + if (safeSrc && !failed) { + return ( + + ); + } + + return ( + + ); +} diff --git a/apps/web/src/BookmarkFormFields.tsx b/apps/web/src/BookmarkFormFields.tsx new file mode 100644 index 0000000..4c002e7 --- /dev/null +++ b/apps/web/src/BookmarkFormFields.tsx @@ -0,0 +1,157 @@ +/** + * [INPUT]: depends on Bookmark, Category, HealthPolicy, HealthStatus, HEALTH_POLICY_LABELS, HEALTH_STATUS_LABELS from @dockmark/core; useI18n from ./i18n + * [OUTPUT]: exports BookmarkDraft, DraftPolicy, emptyDraft, BookmarkFields, and HealthBadge + * [POS]: form field grid and health badge primitives extracted from BookmarkManagerLegacy to keep modules compact + * [PROTOCOL]: Update this header on change, then check GEMINI.md + */ + +import { + HEALTH_POLICY_LABELS, + HEALTH_STATUS_LABELS, + type Bookmark, + type Category, + type HealthPolicy, + type HealthStatus, +} from "@dockmark/core"; +import { useI18n } from "./i18n"; + +export type DraftPolicy = HealthPolicy | "auto"; + +export interface BookmarkDraft { + title: string; + url: string; + description: string; + categoryId: string; + healthPolicy: DraftPolicy; + tagsText: string; +} + +export const emptyDraft: BookmarkDraft = { + title: "", + url: "", + description: "", + categoryId: "", + healthPolicy: "auto", + tagsText: "", +}; + +export function HealthBadge({ bookmark }: { bookmark: Bookmark }) { + const { locale } = useI18n(); + const status: HealthStatus = bookmark.healthPolicy === "local-only" + ? "local-only" + : bookmark.healthPolicy === "ignore" + ? "ignored" + : bookmark.healthStatus; + + const label = bookmark.healthPolicy === "manual" && status === "unknown" + ? HEALTH_POLICY_LABELS[locale].manual + : HEALTH_STATUS_LABELS[locale][status]; + + return ( + + {label} + + ); +} + +interface BookmarkFieldsProps { + draft: BookmarkDraft; + categories: Category[]; + onChange: (draft: BookmarkDraft) => void; + allowAuto: boolean; + idPrefix: string; + urlError?: string | null; + tagsError?: string | null; +} + +export function BookmarkFields({ + draft, + categories, + onChange, + allowAuto, + idPrefix, + urlError, + tagsError, +}: BookmarkFieldsProps) { + const { locale, tx } = useI18n(); + const policyLabels = HEALTH_POLICY_LABELS[locale]; + const tagsHelpId = `${idPrefix}-tags-help`; + const tagsErrorId = `${idPrefix}-tags-error`; + const urlErrorId = `${idPrefix}-url-error`; + + return ( +
+ + + + +