diff --git a/AGENTS.md b/AGENTS.md index 9814b8c..e866143 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -133,9 +133,9 @@ No CI is configured; no rustfmt.toml/clippy.toml — default `cargo fmt`/`clippy no restart; `resolve_js_runtime()` returns an owned `Option`. Never cache a resolved path across operations. Never spawn bare yt-dlp — build every command with `yt_dlp_command()` so the resolver-chosen binary *and* `--js-runtimes` args are applied. -- **LLM summaries by env var**: `ARCHIVR_ANTHROPIC_API_KEY` / `ARCHIVR_ANTHROPIC_URL` / `ARCHIVR_ANTHROPIC_MODEL`, `ARCHIVR_OPENAI_API_KEY` / `ARCHIVR_OPENAI_URL` / `ARCHIVR_OPENAI_MODEL`, `ARCHIVR_CLAUDE_CLI` / `ARCHIVR_CLAUDE_MODEL`, `ARCHIVR_CODEX_CLI` / `ARCHIVR_CODEX_MODEL`, plus `ARCHIVR_SUMMARY_HTTP_TIMEOUT` (default 120s) and `ARCHIVR_SUMMARY_CLI_TIMEOUT` (default 300s). Thread titles use `ARCHIVR_ANTHROPIC_TITLE_MODEL` (default `claude-haiku-4-5`), `ARCHIVR_OPENAI_TITLE_MODEL` (`gpt-4o-mini`), `ARCHIVR_CLAUDE_TITLE_MODEL` (`haiku`), `ARCHIVR_CODEX_TITLE_MODEL` (`gpt-6-luna`, override if unavailable) — never the summary model; `thread_title.rs` reuses provider transports via `summarizer::complete_plain`. The one exception to env-only config: admins may override the title model per provider in the auth DB (`instance_settings.title_model_{anthropic_http,openai_compatible,claude_cli,codex_cli}`; PATCH `/api/admin/instance-settings` trims, blank clears, rejects overlong or whitespace/control chars; GET returns `title_models.` with `model`/`source`/`fallback`). Precedence instance > `ARCHIVR_*_TITLE_MODEL` > default; the server passes the instance value to core as an `Option<&str>` override — core never reads the auth DB. Same convention as above — never TOML, which also keeps API keys out of anything the archive persists. Summaries are manual-only: nothing in `capture.rs` triggers them. The two CLI vars are optional overrides: unset, `resolve_cli()` auto-discovers well-known absolute installs first (`/opt/homebrew/bin/claude`, `/usr/local/bin/claude`; `/Applications/ChatGPT.app/Contents/Resources/codex`, `/opt/homebrew/bin/codex`, `/usr/local/bin/codex`), then `$HOME/.local/bin/`, then the bare name on PATH — the absolute defaults matter because the ChatGPT desktop app ships `codex` off PATH. Frontend static output is generated; never hand-edit `crates/archivr-server/static/`. +- **LLM summaries by env var**: `ARCHIVR_ANTHROPIC_API_KEY` / `ARCHIVR_ANTHROPIC_URL` / `ARCHIVR_ANTHROPIC_MODEL`, `ARCHIVR_OPENAI_API_KEY` / `ARCHIVR_OPENAI_URL` / `ARCHIVR_OPENAI_MODEL`, `ARCHIVR_CLAUDE_CLI` / `ARCHIVR_CLAUDE_MODEL`, `ARCHIVR_CODEX_CLI` / `ARCHIVR_CODEX_MODEL`, plus `ARCHIVR_SUMMARY_HTTP_TIMEOUT` (default 120s) and `ARCHIVR_SUMMARY_CLI_TIMEOUT` (default 300s). Thread titles use `ARCHIVR_ANTHROPIC_TITLE_MODEL` (default `claude-haiku-4-5`), `ARCHIVR_OPENAI_TITLE_MODEL` (`gpt-4o-mini`), `ARCHIVR_CLAUDE_TITLE_MODEL` (`haiku`), `ARCHIVR_CODEX_TITLE_MODEL` (`gpt-6-luna`, override if unavailable) — never the summary model; `thread_title.rs` reuses provider transports via `summarizer::complete_plain`. The exceptions to env-only config: admins may override the title model per provider (`instance_settings.title_model_{anthropic_http,openai_compatible,claude_cli,codex_cli}`) and the OpenAI-compatible endpoint, API key, and model (`instance_settings.openai_{base_url,api_key,model}`; PATCH `/api/admin/instance-settings` trims, blank clears, rejects overlong or whitespace/control chars; GET returns `title_models.` and `openai_api_key_set` without exposing keys; `POST /api/admin/openai-models` lists remote models). Precedence instance > `ARCHIVR_*` env > default; the server passes instance values to core as overrides — core never reads the auth DB. Users may persist their preferred summary provider across devices via `users.summary_provider` (`PATCH /api/auth/me`). Same convention as above — never TOML, which also keeps API keys out of anything the archive persists. Summaries are manual-only: nothing in `capture.rs` triggers them. The two CLI vars are optional overrides: unset, `resolve_cli()` auto-discovers well-known absolute installs first (`/opt/homebrew/bin/claude`, `/usr/local/bin/claude`; `/Applications/ChatGPT.app/Contents/Resources/codex`, `/opt/homebrew/bin/codex`, `/usr/local/bin/codex`), then `$HOME/.local/bin/`, then the bare name on PATH — the absolute defaults matter because the ChatGPT desktop app ships `codex` off PATH. Frontend static output is generated; never hand-edit `crates/archivr-server/static/`. - **Frontend**: JSX (no TypeScript), PascalCase components in `frontend/src/components/`, kebab-case CSS classes, plain CSS with custom properties in `styles.css` (no Tailwind/CSS-in-JS). No router — `App.jsx` parses `window.location.pathname` + `history.pushState`. State = `useState` + one `AuthContext`; `sessionStorage` for refresh-resilient dialog state (see `CaptureDialog.jsx` job polling, 500ms). All API calls through `frontend/src/api.js` with relative `/api/*` URLs — add new endpoints there, not inline `fetch`. Summary polling and generate callbacks must remain scoped to the currently selected entry; image-inclusion behavior is unchanged. In-progress captures render through `SkeletonEntryRow.jsx`, which is a compact spinner + locator + "Archiving…" line (with a playlist/channel hint), **not** a grey skeleton block — don't reintroduce placeholder shimmer. Layout comes from semantic classes (e.g. `.capture-text-row` in `styles.css`), never from fallthrough on a generic row class; give a new row shape its own class. -- **CLI providers parse a file, not stdout**: `codex` is invoked as `codex exec --output-last-message -` (prompt on stdin) and the reply is read back from that file — raw stdout carries a runtime header, an echo of the user prompt, and a `tokens used` footer that the JSON extractor will happily mistake for the answer. There is a positional-prompt fallback for older builds that reject `-`. Keep any new CLI provider on the same "give me only the final message" contract. +- **CLI providers parse a file, not stdout**: `codex` is invoked as `codex exec --skip-git-repo-check --sandbox read-only --output-last-message -` (prompt on stdin) and the reply is read back from that file — raw stdout carries a runtime header, an echo of the user prompt, and a `tokens used` footer that the JSON extractor will happily mistake for the answer. `--skip-git-repo-check` permits execution outside a trusted git repository and `--sandbox read-only` enforces safety. There is a positional-prompt fallback for older builds that reject `-`. Keep any new CLI provider on the same "give me only the final message" contract. - **Transcription engines follow the same rule**: whisper.cpp writes `-ovtt`; script engines (Whisper `script`, Parakeet) are run as ` - + + +
diff --git a/docs/README.md b/docs/README.md index 5b71b2c..f29af48 100644 --- a/docs/README.md +++ b/docs/README.md @@ -56,6 +56,8 @@ Contributing? See the [contributor guide](../CONTRIBUTING.md) and its ecosystem - **LLM summaries** — regenerable per-entry summary via the Anthropic HTTP API, an OpenAI-compatible HTTP API, a local `claude` CLI, or a local `codex` CLI; triggered manually from the entry rail, never automatically on capture; text-only by default, with an explicit `Include attached images` option; YouTube videos are summarized from their subtitles - **Text notes** — capture a plain-text or Markdown note with a title and no URL; the byte-preserving note is stored as a normal deduplicated blob and opens in the usual entry-rail preview - **In-progress capture indicator** — running captures appear as a compact spinner row in the entries list until they finish, replacing the earlier grey skeleton block +- **Dark mode** — toggle light/dark from the topbar or auth screen, or configure System/Light/Dark under **Settings › Profile** +- **Cookie rules** — global, wildcard, or regex rules under **Settings › Cookies** inject custom cookies into capture network requests (yt-dlp, HTTP downloads, web snapshots). The input accepts native JSON, browser extension exports (Cookie-Editor, EditThisCookie), Netscape `cookies.txt`, or `Cookie:` header strings with automatic formatting and collision-safe merge on paste ## Quick Start @@ -393,11 +395,13 @@ replacement succeeds, and public readers receive completed content only—never | `ARCHIVR_CODEX_MODEL` | *(the CLI's own default)* | Optional model override for the local Codex CLI | | `ARCHIVR_SUMMARY_HTTP_TIMEOUT` | `120` | Seconds before an HTTP-provider summary is killed | | `ARCHIVR_SUMMARY_CLI_TIMEOUT` | `300` | Seconds before a CLI-provider summary is killed; also bounds each summary-time yt-dlp subtitle fetch call | +OpenAI-compatible endpoints can also be configured directly in the web UI under **Settings › Instance › OpenAI-compatible endpoint** (Base URL, optional API key, and model, with a **Fetch models** helper). Instance settings take precedence over the `ARCHIVR_OPENAI_*` environment variables. + +Users can also choose and save their preferred summary provider across sessions and devices in **Settings › Profile › Preferred summary provider** or directly via the Summary section in the sidebar. Thread-title generation uses the same provider but never its summary model (`ARCHIVR_*_MODEL`); it uses a cheap title model instead. Admins can set a per-provider title model in **Settings › Instance › Thread title models**. Precedence: that instance setting (blank = unset) > the env var below > the built-in default. - | Variable | Default | Description | |---|---|---| | `ARCHIVR_ANTHROPIC_TITLE_MODEL` | `claude-haiku-4-5` | Model used only for thread-title generation | diff --git a/frontend/index.html b/frontend/index.html index 093b9c6..6d5b2cf 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -6,6 +6,7 @@ Archivr +
diff --git a/frontend/public/theme-init.js b/frontend/public/theme-init.js new file mode 100644 index 0000000..10835c7 --- /dev/null +++ b/frontend/public/theme-init.js @@ -0,0 +1,9 @@ +(function () { + try { + var stored = localStorage.getItem('archivr-theme'); + var isDark = stored === 'dark' || (stored !== 'light' && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches); + document.documentElement.dataset.theme = isDark ? 'dark' : 'light'; + } catch (e) { + /* ignore storage access error */ + } +})(); diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 31a8291..e09870e 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -207,7 +207,7 @@ export default function App() { poll() const timer = setInterval(poll, 3000) return () => { clearInterval(timer); setForeignCaptures([]) } - }, [archiveId, currentUser]) + }, [archiveId, !currentUser]) const [ublockWarningIgnored, setUblockWarningIgnored] = useState( () => sessionStorage.getItem('ublockWarningIgnored') === 'true' @@ -317,7 +317,7 @@ export default function App() { tasks.push(fetchTags(archiveId).then(setTagNodes)) } Promise.all(tasks) - }, [archiveId, currentUser]) // currentUser distinguishes guest vs authenticated + }, [archiveId, !currentUser]) // distinguishes guest vs authenticated without firing on preference changes // Debounced search — scoped to active collection useEffect(() => { diff --git a/frontend/src/api.js b/frontend/src/api.js index d602c09..f7f656a 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -484,6 +484,22 @@ export async function updateInstanceSettings(patch) { if (!res.ok) { const b = await res.json().catch(() => ({})); throw new Error(b.error || `HTTP ${res.status}`); } } +export async function fetchOpenAiModels(options = {}) { + const res = await fetch('/api/admin/openai-models', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + base_url: options.baseUrl || undefined, + api_key: options.apiKey || undefined, + }), + }); + if (!res.ok) { + const b = await res.json().catch(() => ({})); + throw new Error(b.error || `HTTP ${res.status}`); + } + return res.json(); +} + export async function getYtDlpStatus({ signal } = {}) { return getJson('/api/admin/yt-dlp', { signal }); } diff --git a/frontend/src/components/ContextRail.jsx b/frontend/src/components/ContextRail.jsx index b481106..83383aa 100644 --- a/frontend/src/components/ContextRail.jsx +++ b/frontend/src/components/ContextRail.jsx @@ -1,5 +1,6 @@ -import { useState, useEffect, useLayoutEffect, useRef } from 'react' -import { fetchEntryTags, assignTag, removeTag, listEntryCollections, listCollections, addEntryToCollection, updateEntryTitle, generateThreadTitle, deleteEntry, rearchiveEntry, pollCaptureJob, fetchEntrySummary, requestEntrySummary, saveEntrySummary, fetchTranscriptionEngines } from '../api' +import { useState, useEffect, useLayoutEffect, useRef, useContext } from 'react' +import { fetchEntryTags, assignTag, removeTag, listEntryCollections, listCollections, addEntryToCollection, updateEntryTitle, generateThreadTitle, deleteEntry, rearchiveEntry, pollCaptureJob, fetchEntrySummary, requestEntrySummary, saveEntrySummary, fetchTranscriptionEngines, patchMe } from '../api' +import { AuthContext } from '../App.jsx' import ExportDialog from './ExportDialog' import { formatTimestamp, formatBytes, valueText, sourceIconSvg, displayPath } from '../utils' @@ -66,6 +67,7 @@ function orderedSelection(rows, selectedUids) { } export default function ContextRail({ archiveId, selectedEntry, selectedUids, selectedEntries, detail, onTagFilterSet, tagNodes, onTagsRefresh, onEntryTitleChange, onEntryDeleted, onBulkDeleted, humanizeTags, onDetailRefresh, onOpenPreview, onPlay, isPublicSession }) { + const { currentUser, setCurrentUser } = useContext(AuthContext) ?? {} const [tags, setTags] = useState([]) const [exportOpen, setExportOpen] = useState(false) const [assignInput, setAssignInput] = useState('') @@ -91,10 +93,18 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se const [summaryError, setSummaryError] = useState('') const [summaryBusy, setSummaryBusy] = useState(false) const [summaryProvider, setSummaryProvider] = useState(() => { + if (currentUser?.summary_provider) return currentUser.summary_provider try { return sessionStorage.getItem(SUMMARY_PROVIDER_KEY) || SUMMARY_PROVIDERS[0].value } catch { return SUMMARY_PROVIDERS[0].value } }) + + useEffect(() => { + if (currentUser?.summary_provider) { + setSummaryProvider(currentUser.summary_provider) + try { sessionStorage.setItem(SUMMARY_PROVIDER_KEY, currentUser.summary_provider) } catch {} + } + }, [currentUser?.summary_provider]) const [includeSummaryImages, setIncludeSummaryImages] = useState(false) // Local transcription engines offered by the server ([] = feature off) and // the one picked for YouTube videos without subtitles ('' = none). @@ -361,6 +371,13 @@ export default function ContextRail({ archiveId, selectedEntry, selectedUids, se setSummaryProvider(value) if (value === 'claude_cli') setIncludeSummaryImages(false) try { sessionStorage.setItem(SUMMARY_PROVIDER_KEY, value) } catch { /* private mode */ } + if (currentUser && currentUser.summary_provider !== value) { + patchMe({ summary_provider: value }) + .then(() => { + setCurrentUser?.(prev => prev ? { ...prev, summary_provider: value } : prev) + }) + .catch(() => {}) + } } function handleTranscribeEngineChange(value) { diff --git a/frontend/src/components/LoginPage.jsx b/frontend/src/components/LoginPage.jsx index ff6bf30..bb93bcb 100644 --- a/frontend/src/components/LoginPage.jsx +++ b/frontend/src/components/LoginPage.jsx @@ -1,5 +1,6 @@ import { useState } from 'react'; import { login } from '../api.js'; +import ThemeToggle from './ThemeToggle.jsx'; export default function LoginPage({ onLogin }) { const [username, setUsername] = useState(''); @@ -23,6 +24,7 @@ export default function LoginPage({ onLogin }) { return (
+

Archivr

Sign in to your archive

diff --git a/frontend/src/components/SettingsView.jsx b/frontend/src/components/SettingsView.jsx index 560733c..f6cf740 100644 --- a/frontend/src/components/SettingsView.jsx +++ b/frontend/src/components/SettingsView.jsx @@ -8,9 +8,11 @@ import { scanOrphanBlobs, deleteOrphanBlobs, listCookieRules, createCookieRule, updateCookieRule, deleteCookieRule, listRoles, fetchMe, - getYtDlpStatus, updateYtDlp, + getYtDlpStatus, updateYtDlp, fetchOpenAiModels, } from '../api.js' import { describeExpiry, formatTimestamp } from '../utils.js' +import { useTheme } from '../useTheme.js' +import { normalizeCookiesInput, pasteCookies } from '../cookieImport.js' const ROLE_ADMIN = 4 const ROLE_OWNER = 8 @@ -54,6 +56,7 @@ export default function SettingsView({ tab, onTabChange, archiveId }) { function ProfileTab({ currentUser, setCurrentUser }) { const [displayName, setDisplayName] = useState(currentUser?.display_name ?? '') + const { preference, resolved, setPreference } = useTheme() const [saving, setSaving] = useState(false) const [saveMsg, setSaveMsg] = useState(null) @@ -133,6 +136,48 @@ function ProfileTab({ currentUser, setCurrentUser }) {

When on, tag paths show as "X / Articles" instead of "x/articles".

+
+ + +

+ Default provider used for summaries and thread title generation across all your devices. +

+
+
+ + +

+ Choose light, dark, or follow your operating system settings. +

+
@@ -379,6 +424,36 @@ function InstanceTab({ isOwner, setCurrentUser }) { const [permSaving, setPermSaving] = useState(false) const [permMsg, setPermMsg] = useState(null) + const [fetchingModels, setFetchingModels] = useState(false) + const [modelFetchMsg, setModelFetchMsg] = useState(null) + const [fetchedModels, setFetchedModels] = useState([]) + const [apiKeyInput, setApiKeyInput] = useState('') + const [clearingKey, setClearingKey] = useState(false) + + async function handleFetchModels() { + setFetchingModels(true) + setModelFetchMsg(null) + try { + const res = await fetchOpenAiModels({ + baseUrl: settings.openai_base_url, + apiKey: apiKeyInput || undefined, + }) + const list = res.models || [] + setFetchedModels(list) + if (list.length > 0) { + setModelFetchMsg({ ok: true, text: `Fetched ${list.length} model${list.length === 1 ? '' : 's'}.` }) + if (!settings.openai_model) { + setSettings(s => ({ ...s, openai_model: list[0] })) + } + } else { + setModelFetchMsg({ ok: true, text: 'No models returned from endpoint.' }) + } + } catch (e) { + setModelFetchMsg({ ok: false, text: e.message || 'Failed to fetch models' }) + } finally { + setFetchingModels(false) + } + } useEffect(() => { (async () => { try { @@ -416,8 +491,23 @@ function InstanceTab({ isOwner, setCurrentUser }) { e.preventDefault() setSaving(true); setSaveMsg(null) try { - const { reorder_children_role_bits: _mask, title_models: _models, ...rest } = settings - await updateInstanceSettings(rest) + const { + reorder_children_role_bits: _mask, + title_models: _models, + openai_api_key_set: _ks, + ublock_ext_available: _ub, + cookie_ext_available: _ck, + ...rest + } = settings + const payload = { ...rest } + if (apiKeyInput.trim()) { + payload.openai_api_key = apiKeyInput.trim() + } else if (clearingKey) { + payload.openai_api_key = '' + } + await updateInstanceSettings(payload) + setApiKeyInput('') + setClearingKey(false) setSettings(await getInstanceSettings()) // server-trimmed models + effective sources setSaveMsg({ ok: true, text: 'Saved.' }) } catch (err) { @@ -461,11 +551,16 @@ function InstanceTab({ isOwner, setCurrentUser }) { {TITLE_MODEL_PROVIDERS.map(([kind, label]) => { const key = `title_model_${kind}` const info = settings.title_models?.[kind] - const placeholder = info ? `${info.fallback_model} (${info.fallback_source})` : '' + const isOai = kind === 'openai_compatible' + const sourceLabel = info?.fallback_source === 'instance' && isOai + ? 'endpoint model' + : info?.fallback_source + const placeholder = info ? `${info.fallback_model} (${sourceLabel})` : '' return (
setSettings(s => ({ ...s, [key]: e.target.value }))} />
@@ -473,6 +568,99 @@ function InstanceTab({ isOwner, setCurrentUser }) { })}

Cheap model used for Generate title. Leave blank to use the default.

+
+ +
+ + setSettings(s => ({ ...s, openai_base_url: e.target.value }))} + /> +

Endpoint for OpenAI-compatible LLMs (e.g. Handy STT post-processing, Ollama, LocalAI).

+
+ +
+ + { + setApiKeyInput(e.target.value) + if (clearingKey) setClearingKey(false) + }} + /> + {settings.openai_api_key_set && !clearingKey && !apiKeyInput && ( + + )} + {clearingKey && ( + + Key will be removed on save.{' '} + + + )} +
+ +
+ +
+ setSettings(s => ({ ...s, openai_model: e.target.value }))} + style={{ flex: 1 }} + /> + +
+ + {fetchedModels.map(m => ( + + {modelFetchMsg && ( +
+ {modelFetchMsg.text} +
+ )} +
+
{saveMsg &&
{saveMsg.text}
} + ) +} diff --git a/frontend/src/components/Topbar.jsx b/frontend/src/components/Topbar.jsx index f191d75..e582ce2 100644 --- a/frontend/src/components/Topbar.jsx +++ b/frontend/src/components/Topbar.jsx @@ -1,6 +1,7 @@ import { useContext, useState } from 'react'; import { AuthContext } from '../App.jsx'; import { logout as apiLogout } from '../api.js'; +import ThemeToggle from './ThemeToggle.jsx'; export default function Topbar({ archives, archiveId, onArchiveChange, view, onViewChange, onCaptureClick, collections, selectedCollectionUid, onCollectionChange, isPublicSession, onSignInClick }) { const { currentUser, setCurrentUser } = useContext(AuthContext) ?? {}; @@ -51,6 +52,9 @@ export default function Topbar({ archives, archiveId, onArchiveChange, view, onV <> +
+ +
) : ( <> @@ -63,14 +67,17 @@ export default function Topbar({ archives, archiveId, onArchiveChange, view, onV ))} - {currentUser && ( -
- {currentUser.display_name || currentUser.username} - -
- )} +
+ + {currentUser && ( + <> + {currentUser.display_name || currentUser.username} + + + )} +
)} diff --git a/frontend/src/cookieImport.js b/frontend/src/cookieImport.js new file mode 100644 index 0000000..d9def6e --- /dev/null +++ b/frontend/src/cookieImport.js @@ -0,0 +1,233 @@ +/** + * Converts cookies pasted into Settings › Cookies into the cookie-rule format + * the server accepts: a JSON object whose values are all strings + * ({"name": "value"}). + * + * Recognised inputs: + * - archivr JSON: {"session": "abc"} + * - extension JSON: [{"name": "session", "value": "abc", "domain": …}, …] + * (Cookie-Editor / EditThisCookie export; a single such object also works) + * - Netscape: cookies.txt lines, including `#HttpOnly_` prefixed ones + * - header string: session=abc; theme=dark (optional `Cookie:` prefix) + * + * Rules are scoped by URL pattern, so domain/path/expiry/flags are dropped. + */ + +const FORMAT_LABELS = { + archivr: 'archivr JSON', + extension: 'extension JSON', + netscape: 'Netscape', + header: 'header string', +} + +// Same character rules as the extension session cookies (browserData.js). +const INVALID_NAME = /[\x00-\x1f\x7f ;=]/ +const INVALID_VALUE = /[\x00-\x1f\x7f;]/ + +const NETSCAPE_HEADER = /^#\s*Netscape HTTP Cookie File/i +const HTTP_ONLY_PREFIX = '#HttpOnly_' +const BOOL_FIELD = /^(TRUE|FALSE)$/i + +function fail(error) { + return { ok: false, error } +} + +function checkPair(name, value) { + if (!name || INVALID_NAME.test(name)) { + return `Invalid cookie name ${JSON.stringify(name)}: names cannot be empty or contain spaces, ';' or '='.` + } + if (INVALID_VALUE.test(value)) { + return `Invalid value for cookie ${JSON.stringify(name)}: values cannot contain ';' or control characters.` + } + return null +} + +function converted(format, entries) { + for (const [name, value] of entries) { + const err = checkPair(name, value) + if (err) return fail(err) + } + if (entries.length === 0) return fail(`No cookies found in ${FORMAT_LABELS[format]}.`) + return { ok: true, format, cookies: entries } +} + +function isPlainObject(v) { + return v !== null && typeof v === 'object' && !Array.isArray(v) +} + +function extensionCookie(item, index) { + if (!isPlainObject(item) || typeof item.name !== 'string' || typeof item.value !== 'string') { + return { error: `Cookie #${index + 1} needs string "name" and "value" fields.` } + } + return { entry: [item.name, item.value] } +} + +function parseJson(text) { + let data + try { data = JSON.parse(text) } catch { + return fail('Invalid JSON.') + } + if (Array.isArray(data)) { + const entries = [] + for (let i = 0; i < data.length; i++) { + const { entry, error } = extensionCookie(data[i], i) + if (error) return fail(error) + entries.push(entry) + } + return converted('extension', entries) + } + if (!isPlainObject(data)) { + return fail('Cookies JSON must be an object like {"session": "abc"} or an extension export array.') + } + const values = Object.values(data) + if (values.every(v => typeof v === 'string')) { + // Native format: passed through as-is (the server is the authority on it). + return { ok: true, format: 'archivr', cookies: Object.entries(data) } + } + // One cookie copied out of an extension export ({"name", "value", "domain", …}). + if (typeof data.name === 'string' && typeof data.value === 'string') { + return converted('extension', [[data.name, data.value]]) + } + return fail('Cookie values must all be strings, e.g. {"session": "abc"}.') +} + +function netscapeFields(line) { + const tabbed = line.split('\t') + if (tabbed.length >= 7) return tabbed + // Copies out of a terminal or chat often turn tabs into spaces. + return line.trim().split(/\s+/) +} + +function looksLikeNetscapeLine(line) { + const fields = netscapeFields(line) + return fields.length >= 6 && BOOL_FIELD.test(fields[1]) && BOOL_FIELD.test(fields[3]) +} + +function cookieLines(text) { + return text.split(/\r?\n/) + .map(line => line.trimEnd()) + .filter(line => line.trim() !== '') + .map(line => line.startsWith(HTTP_ONLY_PREFIX) ? line.slice(HTTP_ONLY_PREFIX.length) : line) + .filter(line => !line.startsWith('#')) +} + +function parseNetscape(text) { + const entries = [] + for (const line of cookieLines(text)) { + if (!looksLikeNetscapeLine(line)) { + return fail(`Not a Netscape cookie line: ${line.slice(0, 80)}`) + } + const fields = netscapeFields(line) + const sep = fields.length === line.split('\t').length ? '\t' : ' ' + entries.push([fields[5], fields.slice(6).join(sep)]) + } + return converted('netscape', entries) +} + +function parseHeader(text) { + const body = text.trim().replace(/^cookie:\s*/i, '') + const entries = [] + for (const part of body.split(/;|\r?\n/)) { + const pair = part.trim() + if (pair === '') continue + const eq = pair.indexOf('=') + if (eq <= 0) return fail(`Expected name=value, got ${JSON.stringify(pair.slice(0, 80))}.`) + entries.push([pair.slice(0, eq).trim(), pair.slice(eq + 1).trim()]) + } + return converted('header', entries) +} + +/** + * Parses cookies in any supported format. + * @param {string} text + * @returns {{ok: true, format: string, cookies: Array<[string, string]>} | {ok: false, error: string}} + */ +export function parseCookies(text) { + const trimmed = (text ?? '').trim() + if (trimmed === '') return fail('No cookies found.') + if (trimmed.startsWith('{') || trimmed.startsWith('[')) return parseJson(trimmed) + const firstLine = cookieLines(trimmed)[0] + if (NETSCAPE_HEADER.test(trimmed) || (firstLine !== undefined && looksLikeNetscapeLine(firstLine))) { + return parseNetscape(trimmed) + } + return parseHeader(trimmed) +} + +/** + * Merges cookie lists; `incoming` wins on a name collision. + * @returns {{cookies: Object, added: number, replaced: number}} + */ +export function mergeCookies(base, incoming) { + const merged = new Map(base) + let added = 0 + let replaced = 0 + for (const [name, value] of incoming) { + if (!merged.has(name)) added++ + else if (merged.get(name) !== value) replaced++ + merged.set(name, value) + } + // Object.fromEntries keeps names such as "__proto__" as own properties. + return { cookies: Object.fromEntries(merged), added, replaced } +} + +export function formatCookies(cookies) { + return JSON.stringify(cookies, null, 2) +} + +function plural(n, word) { + return `${n} ${word}${n === 1 ? '' : 's'}` +} + +/** + * Normalises a cookie-rule textarea before it is sent to the server. + * Native JSON is sent unchanged; other formats are converted. + * @returns {{ok: true, json: string} | {ok: false, error: string}} + */ +export function normalizeCookiesInput(text) { + const parsed = parseCookies(text) + if (!parsed.ok) return parsed + if (parsed.format === 'archivr') return { ok: true, json: text } + return { ok: true, json: formatCookies(Object.fromEntries(parsed.cookies)) } +} + +/** + * Decides what pasting `clip` over the selection [start, end) of `current` does. + * + * Returns null when the browser's normal paste should run: the result is + * already a valid cookie object (ordinary JSON editing), or the clipboard is + * not cookies at all. Otherwise the caller prevents the paste and either + * replaces the textarea with `text` or shows `error`. + * + * @returns {null | {text: string, message: string} | {error: string}} + */ +export function pasteCookies(current, start, end, clip) { + const before = current.slice(0, start) + const after = current.slice(end) + const combined = parseCookies(before + clip + after) + if (combined.ok && combined.format === 'archivr') return null + + const incoming = parseCookies(clip) + if (!incoming.ok) return null + + const label = FORMAT_LABELS[incoming.format] + const count = plural(incoming.cookies.length, 'cookie') + const rest = before + after + if (rest.trim() === '') { + return { + text: formatCookies(Object.fromEntries(incoming.cookies)), + message: `Converted ${count} from ${label}.`, + } + } + + const existing = parseCookies(rest) + if (!existing.ok) { + return { + error: `Clipboard has ${count} (${label}), but the existing content isn't valid cookies (${existing.error}) — fix or clear it, then paste again.`, + } + } + const { cookies, added, replaced } = mergeCookies(existing.cookies, incoming.cookies) + const message = existing.cookies.length === 0 + ? `Converted ${count} from ${label}.` + : `Merged ${count} from ${label}: ${added} added, ${replaced} replaced.` + return { text: formatCookies(cookies), message } +} diff --git a/frontend/src/cookieImport.test.js b/frontend/src/cookieImport.test.js new file mode 100644 index 0000000..4d3645b --- /dev/null +++ b/frontend/src/cookieImport.test.js @@ -0,0 +1,289 @@ +import { describe, expect, test } from 'bun:test' +import { + parseCookies, + mergeCookies, + formatCookies, + normalizeCookiesInput, + pasteCookies, +} from './cookieImport.js' + +// User's exact prompt sample: extension JSON +const EXTENSION_JSON_SAMPLE = `[ + { + "domain": "127.0.0.1", + "expirationDate": 1794836374, + "hostOnly": true, + "httpOnly": true, + "name": "session", + "path": "/", + "sameSite": "strict", + "secure": false, + "session": false, + "storeId": null, + "value": "sess_2242ce38c8c54a49b80fab32e8556b82" + } +]` + +// User's exact prompt sample: Netscape format +const NETSCAPE_SAMPLE = `# Netscape HTTP Cookie File +# http://curl.haxx.se/rfc/cookie_spec.html +# This file was generated by Cookie-Editor +#HttpOnly_127.0.0.1 FALSE / FALSE 1794836374 session sess_2242ce38c8c54a49b80fab32e8556b82` + +// User's exact prompt sample: header string +const HEADER_SAMPLE = 'session=sess_2242ce38c8c54a49b80fab32e8556b82' + +describe('parseCookies', () => { + test('parses extension JSON array', () => { + const res = parseCookies(EXTENSION_JSON_SAMPLE) + expect(res.ok).toBe(true) + expect(res.format).toBe('extension') + expect(res.cookies).toEqual([ + ['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'], + ]) + }) + + test('parses single extension cookie object', () => { + const single = JSON.parse(EXTENSION_JSON_SAMPLE)[0] + const res = parseCookies(JSON.stringify(single)) + expect(res.ok).toBe(true) + expect(res.format).toBe('extension') + expect(res.cookies).toEqual([ + ['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'], + ]) + }) + + test('parses Netscape cookie file with #HttpOnly_ and whitespace-separated fields', () => { + const res = parseCookies(NETSCAPE_SAMPLE) + expect(res.ok).toBe(true) + expect(res.format).toBe('netscape') + expect(res.cookies).toEqual([ + ['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'], + ]) + }) + + test('parses standard tab-separated Netscape file', () => { + const tabbed = [ + '# Netscape HTTP Cookie File', + '.example.com\tTRUE\t/\tFALSE\t1794836374\tsession\tsess_123', + '#HttpOnly_.example.com\tTRUE\t/\tTRUE\t1794836374\tcsrf\ttoken_456', + ].join('\n') + const res = parseCookies(tabbed) + expect(res.ok).toBe(true) + expect(res.format).toBe('netscape') + expect(res.cookies).toEqual([ + ['session', 'sess_123'], + ['csrf', 'token_456'], + ]) + }) + + test('handles CRLF line endings in Netscape file', () => { + const crlf = NETSCAPE_SAMPLE.replace(/\n/g, '\r\n') + const res = parseCookies(crlf) + expect(res.ok).toBe(true) + expect(res.cookies).toEqual([ + ['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'], + ]) + }) + + test('parses header string', () => { + const res = parseCookies(HEADER_SAMPLE) + expect(res.ok).toBe(true) + expect(res.format).toBe('header') + expect(res.cookies).toEqual([ + ['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'], + ]) + }) + + test('parses header string with Cookie: prefix and multiple pairs', () => { + const res = parseCookies('Cookie: a=1; b=2=3; c="quoted"') + expect(res.ok).toBe(true) + expect(res.format).toBe('header') + expect(res.cookies).toEqual([ + ['a', '1'], + ['b', '2=3'], // value preserves subsequent '=' + ['c', '"quoted"'], + ]) + }) + + test('parses multiline header strings (newline separated)', () => { + const res = parseCookies('a=1\nb=2\r\nc=3') + expect(res.ok).toBe(true) + expect(res.cookies).toEqual([['a', '1'], ['b', '2'], ['c', '3']]) + }) + + test('identifies native archivr JSON', () => { + const res = parseCookies('{"session": "sess_2242ce38c8c54a49b80fab32e8556b82"}') + expect(res.ok).toBe(true) + expect(res.format).toBe('archivr') + expect(res.cookies).toEqual([ + ['session', 'sess_2242ce38c8c54a49b80fab32e8556b82'], + ]) + }) + + test('parses empty object as native archivr JSON', () => { + const res = parseCookies('{}') + expect(res.ok).toBe(true) + expect(res.format).toBe('archivr') + expect(res.cookies).toEqual([]) + }) + + test('rejects empty string', () => { + expect(parseCookies('').ok).toBe(false) + expect(parseCookies(' ').ok).toBe(false) + }) + + test('rejects cookie name with space or semicolon', () => { + expect(parseCookies('bad name=val').ok).toBe(false) + expect(parseCookies('bad;name=val').ok).toBe(false) + }) + + test('rejects cookie value with control chars', () => { + expect(parseCookies('name=val\x00x').ok).toBe(false) + }) + + test('rejects malformed extension entry missing value', () => { + const res = parseCookies('[{"name": "foo"}]') + expect(res.ok).toBe(false) + expect(res.error).toMatch(/needs string "name" and "value"/) + }) +}) + +describe('mergeCookies', () => { + test('merges base and incoming; incoming overwrites collision', () => { + const base = [['a', '1'], ['b', '2']] + const incoming = [['b', 'overwritten'], ['c', '3']] + const res = mergeCookies(base, incoming) + expect(res.cookies).toEqual({ + a: '1', + b: 'overwritten', + c: '3', + }) + expect(res.added).toBe(1) + expect(res.replaced).toBe(1) + }) + + test('detects unchanged values as not replaced', () => { + const base = [['a', '1']] + const incoming = [['a', '1']] + const res = mergeCookies(base, incoming) + expect(res.added).toBe(0) + expect(res.replaced).toBe(0) + }) + + test('preserves reserved property names like __proto__', () => { + const res = mergeCookies([], [['__proto__', 'safe']]) + expect(Object.hasOwn(res.cookies, '__proto__')).toBe(true) + expect(res.cookies['__proto__']).toBe('safe') + }) +}) + +describe('normalizeCookiesInput', () => { + test('passes native JSON string through verbatim', () => { + const native = '{\n "session": "abc"\n}' + expect(normalizeCookiesInput(native)).toEqual({ ok: true, json: native }) + }) + + test('converts extension JSON to pretty JSON', () => { + const res = normalizeCookiesInput(EXTENSION_JSON_SAMPLE) + expect(res.ok).toBe(true) + expect(JSON.parse(res.json)).toEqual({ + session: 'sess_2242ce38c8c54a49b80fab32e8556b82', + }) + }) + + test('converts Netscape to pretty JSON', () => { + const res = normalizeCookiesInput(NETSCAPE_SAMPLE) + expect(res.ok).toBe(true) + expect(JSON.parse(res.json)).toEqual({ + session: 'sess_2242ce38c8c54a49b80fab32e8556b82', + }) + }) + + test('converts header string to pretty JSON', () => { + const res = normalizeCookiesInput(HEADER_SAMPLE) + expect(res.ok).toBe(true) + expect(JSON.parse(res.json)).toEqual({ + session: 'sess_2242ce38c8c54a49b80fab32e8556b82', + }) + }) + + test('returns error for invalid input', () => { + const res = normalizeCookiesInput('not a valid cookie string') + expect(res.ok).toBe(false) + }) +}) + +describe('pasteCookies', () => { + test('returns null if entire pasted result is already valid native JSON', () => { + // Normal JSON typing/editing: pasting `"abc"` into `{"a": }` + const current = '{"a": }' + // Cursor right after the space: start = 6, end = 6 + const res = pasteCookies(current, 6, 6, '"abc"') + expect(res).toBeNull() + }) + + test('returns null if clipboard is not cookies at all', () => { + const res = pasteCookies('{}', 0, 2, 'hello world') + expect(res).toBeNull() + }) + + test('converts clipboard when textarea is default empty object and selected entirely', () => { + const res = pasteCookies('{}', 0, 2, EXTENSION_JSON_SAMPLE) + expect(res).not.toBeNull() + expect(res.error).toBeUndefined() + expect(JSON.parse(res.text)).toEqual({ + session: 'sess_2242ce38c8c54a49b80fab32e8556b82', + }) + expect(res.message).toMatch(/Converted 1 cookie from extension JSON/) + }) + + test('converts clipboard when textarea is completely empty', () => { + const res = pasteCookies('', 0, 0, HEADER_SAMPLE) + expect(res).not.toBeNull() + expect(JSON.parse(res.text)).toEqual({ + session: 'sess_2242ce38c8c54a49b80fab32e8556b82', + }) + expect(res.message).toMatch(/Converted 1 cookie from header string/) + }) + + test('merges into existing native JSON', () => { + const current = '{\n "existing": "val"\n}' + const res = pasteCookies(current, current.length, current.length, NETSCAPE_SAMPLE) + expect(res).not.toBeNull() + expect(res.error).toBeUndefined() + expect(JSON.parse(res.text)).toEqual({ + existing: 'val', + session: 'sess_2242ce38c8c54a49b80fab32e8556b82', + }) + expect(res.message).toMatch(/Merged 1 cookie from Netscape: 1 added, 0 replaced/) + }) + + test('overwrites existing keys when pasting newer values', () => { + const current = '{\n "session": "old_value"\n}' + const res = pasteCookies(current, current.length, current.length, HEADER_SAMPLE) + expect(res).not.toBeNull() + expect(JSON.parse(res.text)).toEqual({ + session: 'sess_2242ce38c8c54a49b80fab32e8556b82', + }) + expect(res.message).toMatch(/Merged 1 cookie from header string: 0 added, 1 replaced/) + }) + + test('merges into existing Netscape content (if user already had that in textarea)', () => { + const current = NETSCAPE_SAMPLE + const clip = 'extra=value_123' + const res = pasteCookies(current, current.length, current.length, clip) + expect(res).not.toBeNull() + expect(JSON.parse(res.text)).toEqual({ + session: 'sess_2242ce38c8c54a49b80fab32e8556b82', + extra: 'value_123', + }) + }) + + test('returns error when clipboard has cookies but remaining textarea is invalid', () => { + const current = '{"broken json: ' + const res = pasteCookies(current, current.length, current.length, HEADER_SAMPLE) + expect(res).not.toBeNull() + expect(res.error).toMatch(/existing content isn't valid cookies/) + }) +}) diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 73cb8f6..834116a 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -15,6 +15,36 @@ --link: #245f72; --top: #141d18; --field: #fffdf7; + --lift: #fff; + --row-alt: #f2ede5; + --row-selected: #eee2d2; + --child-row-a: #fafaf8; + --child-row-b: #f2f0ec; + --url-ink: #555b55; + --pill-bg: #d8e3df; + --pill-ink: #275a5f; + --pill-line: #bfd0ca; + --ok-bg: #d8eddf; + --ok-ink: #235c35; + --ok-line: #b4d9be; + --err-bg: #f5ddd8; + --err-ink: #8d3f30; + --err-line: #e0b8b0; + --err-row: #fdf0ed; + --warn-bg: #fdefd8; + --warn-ink: #8a4f10; + --warn-line: #f0cfa0; + --conflict-ink: #c07000; + --conflict-bg: #fff3cd; + --conflict-line: #e0a000; + --alert: #c05000; + --disabled-bg: #ede8e0; + --ink-hover: #2c332b; + /* Primary buttons: dark-on-light page, light-on-dark page. */ + --strong: var(--top); + --on-strong: #f5f0e7; + /* Text on --accent fills; stays light in both themes. */ + --on-accent: #f5f0e7; --r: 3px; --r2: 6px; --r3: 10px; @@ -23,6 +53,52 @@ --display: "Cormorant Garamond", Georgia, serif; } +/* data-theme is always resolved to light|dark by /theme-init.js before first + paint and kept in sync by src/theme.js. */ +:root[data-theme="dark"] { + color-scheme: dark; + --ink: #e6dfd1; + --muted: #a29d91; + --muted-2: #858074; + --paper: #171916; + --paper-2: #23261f; + --paper-3: #1d201b; + --line: #3a3e35; + --line-soft: #2b2e27; + --accent: #b85d46; + --accent-2: #c9944f; + --link: #79b4c6; + --top: #0e110f; + --field: #1a1d18; + --lift: #33372f; + --row-alt: #191c17; + --row-selected: #352d25; + --child-row-a: #1b1e19; + --child-row-b: #181b16; + --url-ink: #9b9e94; + --pill-bg: #1d3236; + --pill-ink: #9ccdd6; + --pill-line: #2f4c51; + --ok-bg: #1b3223; + --ok-ink: #8fd0a2; + --ok-line: #2d5038; + --err-bg: #3b211b; + --err-ink: #f0a08e; + --err-line: #5c3329; + --err-row: #2a1b17; + --warn-bg: #382a15; + --warn-ink: #e6b169; + --warn-line: #5a4321; + --conflict-ink: #e9a646; + --conflict-bg: #352a11; + --conflict-line: #7d5c12; + --alert: #f08b4f; + --disabled-bg: #262922; + --ink-hover: #d3ccbe; + --strong: var(--ink); + --on-strong: var(--paper); +} + * { box-sizing: border-box; } @@ -216,7 +292,7 @@ select { align-items: center; gap: 16px; padding: 12px 22px; - background: color-mix(in srgb, var(--paper) 88%, white); + background: color-mix(in srgb, var(--paper) 88%, var(--lift)); border-bottom: 1px solid var(--line-soft); } .search-field { @@ -286,7 +362,7 @@ select { position: sticky; top: 67px; z-index: 2; - background: color-mix(in srgb, var(--paper) 92%, white); + background: color-mix(in srgb, var(--paper) 92%, var(--lift)); border-bottom: 1px solid var(--line-soft); color: var(--muted); font-size: 10.5px; @@ -303,17 +379,17 @@ select { } #entries-body > div > div { padding: 7px 10px; flex-shrink: 0; overflow: hidden; } /* Pending capture rows (no index class) fall back to nth-child; real rows use explicit classes. */ -#entries-body > div:not(.entry-row-outer):nth-child(even) { background: #f2ede5; } +#entries-body > div:not(.entry-row-outer):nth-child(even) { background: var(--row-alt); } #entries-body > div:not(.entry-row-outer):nth-child(odd) { background: var(--paper-3); } /* Index-based stripes for real entry rows — immune to pending-capture sibling count. */ #entries-body > .entry-row-outer--light { background: var(--paper-3); } -#entries-body > .entry-row-outer--dark { background: #f2ede5; } +#entries-body > .entry-row-outer--dark { background: var(--row-alt); } #entries-body > div.is-selected { - background: #eee2d2; + background: var(--row-selected); box-shadow: inset 0 0 0 2px var(--accent); } #entries-body > div.is-multi-selected { - background: #eee2d2; + background: var(--row-selected); box-shadow: inset 0 0 0 2px var(--accent); } @@ -340,12 +416,33 @@ select { .entry-title { color: var(--link); font-weight: 700; min-width: 0; } .entry-header-row > div { padding: 9px 10px; flex-shrink: 0; font-weight: 600; } -.source-icon { display: flex; align-items: center; justify-content: center; width: 1.05em; height: 1.05em; flex-shrink: 0; } +.source-icon { + display: flex; + align-items: center; + justify-content: center; + width: 1.05em; + height: 1.05em; + flex-shrink: 0; + color: var(--ink); + opacity: 0.88; +} +.source-icon:hover, +#entries-body > div:hover .source-icon, +#entries-body > div.is-selected .source-icon, +.child-entry-row:hover .source-icon, +.child-entry-row.is-selected .source-icon { + opacity: 1; +} .source-icon > * { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; } .source-icon svg { width: 100%; height: 100%; } -.url-cell { color: #555b55; white-space: nowrap; text-overflow: ellipsis; word-break: break-all; } +.source-icon svg path:not([fill]) { fill: currentColor; } +:root[data-theme="dark"] .favicon-img { + background: rgba(255, 255, 255, 0.08); + border-radius: 3px; +} +.url-cell { color: var(--url-ink); white-space: nowrap; text-overflow: ellipsis; word-break: break-all; } #entries-body .url-cell:hover { overflow: visible; white-space: normal; } -.type-pill { display: inline-block; padding: 2px 6px; background: #d8e3df; color: #275a5f; border: 1px solid #bfd0ca; border-radius: var(--r); } +.type-pill { display: inline-block; padding: 2px 6px; background: var(--pill-bg); color: var(--pill-ink); border: 1px solid var(--pill-line); border-radius: var(--r); } /* ── Multi-select checkbox column ───────────────────────────────────────── */ /* Hidden on desktop (pointer:fine); always visible on touch/mobile */ @@ -408,7 +505,7 @@ select { z-index: 1; text-align: left; padding: 10px; - background: color-mix(in srgb, var(--paper) 92%, white); + background: color-mix(in srgb, var(--paper) 92%, var(--lift)); color: var(--muted); border-bottom: 1px solid var(--line-soft); font-size: 10.5px; @@ -420,7 +517,7 @@ select { border-bottom: 1px solid var(--line-soft); vertical-align: top; } -#runs-view .entry-table tr:nth-child(even) td { background: #f2ede5; } +#runs-view .entry-table tr:nth-child(even) td { background: var(--row-alt); } #runs-view .entry-table tr:nth-child(odd) td { background: var(--paper-3); } /* ── Context rail ────────────────────────────────────────────────────────── */ @@ -578,7 +675,7 @@ select { text-transform: uppercase; border-radius: var(--r); cursor: pointer; white-space: nowrap; } -.tag-add-btn:hover { background: #2c332b; } +.tag-add-btn:hover { background: var(--ink-hover); } /* collections in rail */ .coll-row { @@ -1046,7 +1143,7 @@ select { color: var(--muted); font-style: italic; } -.capture-quality-hint--error { color: #c05000; font-style: normal; } +.capture-quality-hint--error { color: var(--alert); font-style: normal; } /* Status dot */ .cap-dot { @@ -1061,9 +1158,9 @@ select { line-height: 1; } .cap-dot--idle { background: var(--paper-2); } -.cap-dot--running { background: #fdefd8; color: #8a4f10; } -.cap-dot--ok { background: #d8eddf; color: #235c35; } -.cap-dot--err { background: #f5ddd8; color: #8d3f30; } +.cap-dot--running { background: var(--warn-bg); color: var(--warn-ink); } +.cap-dot--ok { background: var(--ok-bg); color: var(--ok-ink); } +.cap-dot--err { background: var(--err-bg); color: var(--err-ink); } /* Spinner inside the running dot */ .cap-spinner { @@ -1317,12 +1414,12 @@ select { line-height: 1; } .capture-file-badge--done { - background: #d8eddf; - color: #235c35; + background: var(--ok-bg); + color: var(--ok-ink); } .capture-file-badge--error { - background: #f5ddd8; - color: #8d3f30; + background: var(--err-bg); + color: var(--err-ink); } /* ── Toast stack ─────────────────────────────────────────────────────────── */ @@ -1877,7 +1974,7 @@ select { cursor: pointer; border-radius: var(--r); } -.coll-delete-btn:hover { background: var(--accent); color: var(--paper); } +.coll-delete-btn:hover { background: var(--accent); color: var(--on-accent); } .coll-detail-vis { display: flex; align-items: center; @@ -2042,8 +2139,32 @@ select { white-space: nowrap; transition: background 0.15s, color 0.15s; } -.logout-btn:hover { background: rgba(255,255,255,0.1); color: var(--paper); } +.logout-btn:hover { background: rgba(255,255,255,0.1); color: #f5f0e7; } .logout-btn:disabled { opacity: 0.5; cursor: default; } +.theme-toggle-btn { + display: inline-flex; + align-items: center; + justify-content: center; + width: 26px; + height: 26px; + padding: 0; + border: 1px solid rgba(255,255,255,0.18); + background: transparent; + color: #c8bfb0; + border-radius: var(--r); + cursor: pointer; + transition: background 0.15s, color 0.15s, border-color 0.15s; +} +.theme-toggle-btn:hover { + background: rgba(255,255,255,0.1); + color: #f5f0e7; + border-color: rgba(255,255,255,0.32); +} +.theme-toggle-btn svg { + width: 14px; + height: 14px; + display: block; +} /* ── Login / Setup pages ─────────────────────────────────────────────────── */ .login-page, @@ -2054,6 +2175,7 @@ select { align-items: center; justify-content: center; background: var(--paper); + position: relative; } .login-card, .setup-card { @@ -2065,6 +2187,32 @@ select { border-radius: var(--r3); box-shadow: 0 2px 20px rgba(20,29,24,0.07); } +.auth-page-theme-toggle { + position: absolute; + top: 18px; + right: 18px; + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0; + border: 1px solid var(--line); + background: var(--paper-2); + color: var(--ink); + border-radius: var(--r2); + cursor: pointer; + transition: background 0.15s, border-color 0.15s; +} +.auth-page-theme-toggle:hover { + background: var(--field); + border-color: var(--accent); +} +.auth-page-theme-toggle svg { + width: 16px; + height: 16px; + display: block; +} .login-brand, .setup-brand { font-family: var(--display); @@ -2120,8 +2268,8 @@ select { width: 100%; margin-top: 8px; border: none; - background: var(--top); - color: var(--paper); + background: var(--strong); + color: var(--on-strong); font-size: 14px; font-weight: 600; padding: 11px 16px; @@ -2204,8 +2352,8 @@ select { .form-msg--err { color: var(--accent); } .btn-primary { border: none; - background: var(--top); - color: var(--paper); + background: var(--strong); + color: var(--on-strong); font-size: 13px; font-weight: 600; padding: 8px 16px; @@ -2234,7 +2382,7 @@ select { border-radius: var(--r); cursor: pointer; } -.btn-danger:hover { background: var(--accent); color: var(--paper); } +.btn-danger:hover { background: var(--accent); color: var(--on-accent); } /* ── Admin view overrides ────────────────────────────────────────────────── */ .admin-view h1 { font-family: var(--display); font-weight: 600; font-size: 26px; margin: 0 0 20px; } @@ -2324,8 +2472,8 @@ select { text-transform: uppercase; letter-spacing: 0.04em; } -.status-active { background: #d8eddf; color: #235c35; border: 1px solid #b4d9be; } -.status-disabled { background: #ede8e0; color: var(--muted); border: 1px solid var(--line); } +.status-active { background: var(--ok-bg); color: var(--ok-ink); border: 1px solid var(--ok-line); } +.status-disabled { background: var(--disabled-bg); color: var(--muted); border: 1px solid var(--line); } /* ── Runs view improvements ──────────────────────────────────────────────── */ .run-status { @@ -2337,13 +2485,13 @@ select { text-transform: uppercase; letter-spacing: 0.04em; } -.run-status--completed { background: #d8eddf; color: #235c35; border: 1px solid #b4d9be; } -.run-status--failed { background: #f5ddd8; color: #8d3f30; border: 1px solid #e0b8b0; } -.run-status--in-progress { background: #fdefd8; color: #8a4f10; border: 1px solid #f0cfa0; } +.run-status--completed { background: var(--ok-bg); color: var(--ok-ink); border: 1px solid var(--ok-line); } +.run-status--failed { background: var(--err-bg); color: var(--err-ink); border: 1px solid var(--err-line); } +.run-status--in-progress { background: var(--warn-bg); color: var(--warn-ink); border: 1px solid var(--warn-line); } /* Clickable failed run rows and expandable error detail */ .run-row--failed { cursor: pointer; } -.run-row--failed:hover td { background: #fdf0ed !important; } +.run-row--failed:hover td { background: var(--err-row) !important; } .run-expand-hint { margin-left: 6px; font-size: 10px; @@ -2369,8 +2517,8 @@ select { /* ── Token created banner ────────────────────────────────────────────────── */ .token-banner { - background: #d8eddf; - border: 1px solid #b4d9be; + background: var(--ok-bg); + border: 1px solid var(--ok-line); padding: 12px 14px; margin-bottom: 16px; font-size: 13px; @@ -2425,7 +2573,7 @@ select { color: var(--muted); background: var(--paper-2); } -.session-badge { background: #d8eddf; color: #235c35; border-color: #b4d9be; } +.session-badge { background: var(--ok-bg); color: var(--ok-ink); border-color: var(--ok-line); } .token-expiry { font-size: 12px; color: var(--muted); margin-top: 2px; } .token-expiry--expired { color: var(--accent); } .session-row { @@ -2440,7 +2588,7 @@ select { } .session-row .muted { font-size: 12px; margin-top: 2px; } .admin-action-btn--danger { color: var(--accent); border-color: var(--accent); } -.admin-action-btn--danger:hover { background: #f5ddd8; } +.admin-action-btn--danger:hover { background: var(--err-bg); } /* ── Instance settings checkboxes ───────────────────────────────────────── */ .checkbox-row { @@ -3079,7 +3227,7 @@ google-cast-launcher.video-tv-btn { height: 38px; border-radius: 50%; background: var(--accent); - color: var(--paper); + color: var(--on-accent); border: none; cursor: pointer; display: flex; @@ -3235,7 +3383,7 @@ google-cast-launcher.video-tv-btn { padding: 8px 12px; margin-bottom: 16px; background: var(--accent); - color: var(--paper); + color: var(--on-accent); border: none; border-radius: var(--r3); font-size: 13px; @@ -3340,11 +3488,11 @@ body.has-audio-bar { padding-bottom: 56px; } #entries-body > .entry-row-outer.is-selected { background: unset; outline: none; box-shadow: none; } #entries-body > .entry-row-outer.is-multi-selected { background: unset; outline: none; box-shadow: none; } #entries-body > .entry-row-outer.is-selected > .entry-row-main { - background: #eee2d2; + background: var(--row-selected); box-shadow: inset 0 0 0 2px var(--accent); } #entries-body > .entry-row-outer.is-multi-selected > .entry-row-main { - background: #eee2d2; + background: var(--row-selected); box-shadow: inset 0 0 0 2px var(--accent); } @@ -3371,15 +3519,15 @@ body.has-audio-bar { padding-bottom: 56px; } } .child-entry-row:hover { opacity: 1; } .child-entry-row:last-child { border-bottom: none; } -.child-entry-row--light { background: #fafaf8; } -.child-entry-row--dark { background: #f2f0ec; } +.child-entry-row--light { background: var(--child-row-a); } +.child-entry-row--dark { background: var(--child-row-b); } .child-entry-row.is-selected { - background: #eee2d2; + background: var(--row-selected); box-shadow: inset 0 0 0 2px var(--accent); opacity: 1; } .child-entry-row.is-multi-selected { - background: #eee2d2; + background: var(--row-selected); box-shadow: inset 0 0 0 2px var(--accent); opacity: 1; } @@ -3515,9 +3663,9 @@ body.has-audio-bar { padding-bottom: 56px; } .capture-conflict-badge { font-size: 0.7rem; - color: #c07000; - background: #fff3cd; - border: 1px solid #e0a000; + color: var(--conflict-ink); + background: var(--conflict-bg); + border: 1px solid var(--conflict-line); border-radius: 4px; padding: 1px 6px; margin-left: 6px; @@ -3542,8 +3690,8 @@ body.has-audio-bar { padding-bottom: 56px; } } .capture-playlist-item:last-of-type { border-bottom: none; } .capture-playlist-item--conflict { - border-left-color: #c07000; - background: color-mix(in srgb, #c07000 6%, transparent); + border-left-color: var(--conflict-ink); + background: color-mix(in srgb, var(--conflict-ink) 6%, transparent); } .capture-playlist-item-title { flex: 1; @@ -3566,7 +3714,7 @@ body.has-audio-bar { padding-bottom: 56px; } .capture-playlist-conflict-badge { font-size: 0.68rem; font-weight: 600; - color: #c07000; + color: var(--conflict-ink); white-space: nowrap; flex-shrink: 0; } @@ -3588,7 +3736,7 @@ body.has-audio-bar { padding-bottom: 56px; } } .capture-playlist-item:hover .capture-playlist-item-remove, .capture-playlist-item-remove:focus-visible { opacity: 1; } -.capture-playlist-item-remove:hover { color: #c04000; opacity: 1; } +.capture-playlist-item-remove:hover { color: var(--alert); opacity: 1; } @media (pointer: coarse) { .capture-playlist-item-remove { opacity: 1; } } .capture-playlist-item-remove { font-size: 0.75rem; line-height: 1; } diff --git a/frontend/src/theme.js b/frontend/src/theme.js new file mode 100644 index 0000000..9c0c841 --- /dev/null +++ b/frontend/src/theme.js @@ -0,0 +1,113 @@ +export const THEME_KEY = 'archivr-theme' +export const THEMES = ['system', 'light', 'dark'] + +export function parseThemePreference(val) { + return val === 'light' || val === 'dark' ? val : 'system' +} + +export function getStoredThemePreference() { + if (typeof window === 'undefined' || !window.localStorage) return 'system' + try { + return parseThemePreference(window.localStorage.getItem(THEME_KEY)) + } catch { + return 'system' + } +} + +export function systemPrefersDark() { + if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false + try { + return window.matchMedia('(prefers-color-scheme: dark)').matches + } catch { + return false + } +} + +export function resolveTheme(preference, isDark) { + const pref = parseThemePreference(preference) + if (pref === 'system') return isDark ? 'dark' : 'light' + return pref +} + +export function applyTheme(preference) { + if (typeof document === 'undefined') return 'light' + const isDark = systemPrefersDark() + const resolved = resolveTheme(preference, isDark) + document.documentElement.dataset.theme = resolved + return resolved +} + +const listeners = new Set() + +function notify() { + for (const cb of listeners) { + try { cb() } catch { /* ignore subscriber error */ } + } +} + +export function setThemePreference(preference) { + const valid = parseThemePreference(preference) + if (typeof window !== 'undefined' && window.localStorage) { + try { + if (valid === 'system') { + window.localStorage.removeItem(THEME_KEY) + } else { + window.localStorage.setItem(THEME_KEY, valid) + } + } catch { + // storage unavailable / quota exceeded + } + } + applyTheme(valid) + notify() + return valid +} + +// Attach listeners once in browser environments +let mediaQueryList = null +if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') { + try { + mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)') + const onMediaChange = () => { + const currentPref = getStoredThemePreference() + if (currentPref === 'system') { + applyTheme('system') + notify() + } + } + if (typeof mediaQueryList.addEventListener === 'function') { + mediaQueryList.addEventListener('change', onMediaChange) + } else if (typeof mediaQueryList.addListener === 'function') { + mediaQueryList.addListener(onMediaChange) + } + } catch { + // ignore matchMedia setup failures + } + + window.addEventListener('storage', (e) => { + if (e.key === THEME_KEY) { + applyTheme(getStoredThemePreference()) + notify() + } + }) +} + +export function subscribeTheme(callback) { + listeners.add(callback) + return () => { + listeners.delete(callback) + } +} + +export function getThemeSnapshot() { + const preference = getStoredThemePreference() + const resolved = resolveTheme(preference, systemPrefersDark()) + return `${preference}:${resolved}` +} +if (typeof document !== 'undefined') { + try { + applyTheme(getStoredThemePreference()) + } catch { + /* ignore in environments with partial DOM mocks */ + } +} diff --git a/frontend/src/theme.test.js b/frontend/src/theme.test.js new file mode 100644 index 0000000..5ff1f6c --- /dev/null +++ b/frontend/src/theme.test.js @@ -0,0 +1,116 @@ +import { describe, it, expect, beforeEach, afterAll } from 'bun:test' + +function makeStorage() { + const store = new Map() + return { + getItem: (k) => (store.has(k) ? store.get(k) : null), + setItem: (k, v) => store.set(k, String(v)), + removeItem: (k) => store.delete(k), + clear: () => store.clear(), + } +} + +const originalWindow = globalThis.window +const mockStorage = makeStorage() +globalThis.window = { + localStorage: mockStorage, + matchMedia: (query) => ({ + matches: false, + media: query, + addEventListener: () => {}, + removeEventListener: () => {}, + }), + addEventListener: () => {}, + removeEventListener: () => {}, +} + +const { + THEME_KEY, + parseThemePreference, + resolveTheme, + getStoredThemePreference, + setThemePreference, + subscribeTheme, + applyTheme, +} = await import('./theme.js') + +describe('theme preference and resolution', () => { + beforeEach(() => { + mockStorage.clear() + }) + + afterAll(() => { + globalThis.window = originalWindow + }) + + it('parses valid and invalid preference strings', () => { + expect(parseThemePreference('light')).toBe('light') + expect(parseThemePreference('dark')).toBe('dark') + expect(parseThemePreference('system')).toBe('system') + expect(parseThemePreference('auto')).toBe('system') + expect(parseThemePreference('')).toBe('system') + expect(parseThemePreference(null)).toBe('system') + expect(parseThemePreference(undefined)).toBe('system') + expect(parseThemePreference('DARK')).toBe('system') + }) + + it('resolves explicit preference over system state', () => { + expect(resolveTheme('light', true)).toBe('light') + expect(resolveTheme('light', false)).toBe('light') + expect(resolveTheme('dark', true)).toBe('dark') + expect(resolveTheme('dark', false)).toBe('dark') + }) + + it('resolves system preference according to system state', () => { + expect(resolveTheme('system', true)).toBe('dark') + expect(resolveTheme('system', false)).toBe('light') + expect(resolveTheme('unknown', true)).toBe('dark') + expect(resolveTheme('unknown', false)).toBe('light') + }) + + it('stores explicit preference and removes item for system', () => { + setThemePreference('dark') + expect(mockStorage.getItem(THEME_KEY)).toBe('dark') + expect(getStoredThemePreference()).toBe('dark') + + setThemePreference('light') + expect(mockStorage.getItem(THEME_KEY)).toBe('light') + expect(getStoredThemePreference()).toBe('light') + + setThemePreference('system') + expect(mockStorage.getItem(THEME_KEY)).toBeNull() + expect(getStoredThemePreference()).toBe('system') + }) + + it('notifies subscribers when preference changes', () => { + let callCount = 0 + const unsubscribe = subscribeTheme(() => { + callCount += 1 + }) + + setThemePreference('dark') + expect(callCount).toBe(1) + + setThemePreference('light') + expect(callCount).toBe(2) + + unsubscribe() + setThemePreference('system') + expect(callCount).toBe(2) + }) + + it('applies theme to document element dataset when document exists', () => { + const originalDoc = globalThis.document + const htmlEl = { dataset: {} } + globalThis.document = { documentElement: htmlEl } + + try { + applyTheme('dark') + expect(htmlEl.dataset.theme).toBe('dark') + applyTheme('light') + expect(htmlEl.dataset.theme).toBe('light') + } finally { + globalThis.document = originalDoc + } + }) +}) diff --git a/frontend/src/useTheme.js b/frontend/src/useTheme.js new file mode 100644 index 0000000..b5b5360 --- /dev/null +++ b/frontend/src/useTheme.js @@ -0,0 +1,32 @@ +import { useSyncExternalStore, useCallback } from 'react' +import { + getStoredThemePreference, + systemPrefersDark, + resolveTheme, + setThemePreference, + subscribeTheme, + getThemeSnapshot, +} from './theme.js' + +export function useTheme() { + const snapshot = useSyncExternalStore(subscribeTheme, getThemeSnapshot, () => 'system:light') + const [preference, resolved] = snapshot.split(':') + + const setPreference = useCallback((next) => { + setThemePreference(next) + }, []) + + const toggleTheme = useCallback(() => { + // If currently resolving to dark -> switch to light. Otherwise -> switch to dark. + const currentResolved = resolveTheme(getStoredThemePreference(), systemPrefersDark()) + const next = currentResolved === 'dark' ? 'light' : 'dark' + setThemePreference(next) + }, []) + + return { + preference, + resolved, + setPreference, + toggleTheme, + } +} diff --git a/frontend/src/utils.js b/frontend/src/utils.js index f325dd5..3cd5363 100644 --- a/frontend/src/utils.js +++ b/frontend/src/utils.js @@ -49,15 +49,15 @@ export const SOURCE_ICONS = { youtube: ``, youtube_music: ``, spotify: ``, - x: ``, + x: ``, instagram: ``, facebook: ``, - tiktok: ``, + tiktok: ``, reddit: ``, snapchat: ``, - local: ``, - web: ``, - other: `?`, + local: ``, + web: ``, + other: `?`, }; export function sourceIconSvg(kind) {