/** * options.ts — settings page. * * The form edits a draft copy of the settings. Saving validates everything * first (topics, site rules, CSS selectors); invalid input is reported next * to the field and nothing is written until it is fixed. */ import { describeEngine, type UiStatusReply } from "../shared/protocol.ts"; import { describeVision } from "../shared/vision.ts"; import { ENGINE_PREFERENCES, FILTER_MODES, LIMITS, MIGRATION_NOTES_KEY, SETTINGS_KEY, STORAGE_KEYS, migrateSettings, newTopicId, normalizeTopicText, normalizeExcludedPhrases, parseLines, validateSelector, validateTopicText, type EnginePreference, type FilterMode, type Settings, type Topic, } from "../shared/settings.ts"; import { parseSiteRules } from "../shared/sites.ts"; import { FEEDBACK_KEY, type FeedbackRecord } from "../shared/feedback.ts"; import { browserMajor, formatDiagnostics } from "./diagnostics.ts"; const $ = (id: string) => document.getElementById(id) as T; const form = $("settings-form"); const enabledInput = $("enabled"); const topicList = $("topic-list"); const topicEmpty = $("topic-empty"); const newTopicInput = $("new-topic"); const newTopicError = $("new-topic-error"); const sitesInput = $("excluded-sites"); const sitesError = $("sites-error"); const selectorsInput = $("protected-selectors"); const selectorsError = $("selectors-error"); const engineSelect = $("engine"); const imagesInput = $("images"); const imageDownloadsInput = $("image-downloads"); const saveStatus = $("save-status"); const dirtyNote = $("dirty-note"); const engineStatusEl = $("engine-status"); const diagnostics = $("diagnostics"); let saved: Settings; let topics: Topic[] = []; function setStatus(text: string, kind: "ok" | "error" | "" = ""): void { saveStatus.textContent = text; saveStatus.dataset.kind = kind; } function markDirty(): void { dirtyNote.hidden = false; setStatus(""); } function fillErrors(list: HTMLUListElement, field: HTMLElement, errors: string[]): void { list.replaceChildren(...errors.map((e) => Object.assign(document.createElement("li"), { textContent: e }))); field.setAttribute("aria-invalid", errors.length ? "true" : "false"); } // ── Topics ──────────────────────────────────────────────────────────────── function renderTopics(): void { topicList.replaceChildren( ...topics.map((topic) => { const li = document.createElement("li"); li.className = "topic-row"; li.dataset.enabled = String(topic.enabled); li.dataset.topicId = topic.id; const toggle = document.createElement("input"); toggle.type = "checkbox"; toggle.checked = topic.enabled; toggle.setAttribute("aria-label", `Enable topic “${topic.text}”`); toggle.addEventListener("change", () => { topic.enabled = toggle.checked; li.dataset.enabled = String(topic.enabled); markDirty(); }); const text = document.createElement("input"); text.type = "text"; text.value = topic.text; text.maxLength = LIMITS.maxTopicChars; text.setAttribute("aria-label", "Topic text"); const err = document.createElement("p"); err.className = "error-text row-error"; err.id = `err-${topic.id}`; text.setAttribute("aria-describedby", err.id); text.addEventListener("input", () => { topic.text = text.value; err.textContent = ""; text.removeAttribute("aria-invalid"); markDirty(); }); const remove = document.createElement("button"); remove.type = "button"; remove.className = "btn btn-quiet"; remove.textContent = "Remove"; remove.setAttribute("aria-label", `Remove topic “${topic.text}”`); remove.addEventListener("click", () => { topics = topics.filter((t) => t !== topic); renderTopics(); markDirty(); newTopicInput.focus(); }); const scope = document.createElement("details"); scope.className = "topic-scope"; const summary = document.createElement("summary"); summary.textContent = "Text exclusions (optional)"; const label = document.createElement("label"); label.textContent = "Leave this topic visible when the text contains any of these phrases (one per line)"; const exclusions = document.createElement("textarea"); exclusions.rows = 3; exclusions.value = (topic.excludedPhrases ?? []).join("\n"); exclusions.setAttribute("aria-label", `Text exclusions for “${topic.text}”`); const help = document.createElement("p"); help.className = "hint"; help.id = `scope-help-${topic.id}`; help.textContent = "Exact whole phrases, ignoring case and accents. For example, exclude ‘car review’ from ‘jaguar’. No meaning is inferred from negative wording. Mixed text containing an exclusion is also left visible for this topic. Other topics or a matching parent card can still blur it. Images are unaffected. Up to 10 phrases, 120 characters each."; exclusions.setAttribute("aria-describedby", help.id); exclusions.addEventListener("input", () => { topic.excludedPhrases = parseLines(exclusions.value); markDirty(); }); label.append(exclusions); scope.append(summary, label, help); li.append(toggle, text, remove, err, scope); return li; }) ); topicEmpty.hidden = topics.length > 0; } /** Returns false (and shows why) when the pending text cannot be added. */ function addTopic(): boolean { const text = normalizeTopicText(newTopicInput.value); const error = topics.length >= LIMITS.maxTopics ? `At most ${LIMITS.maxTopics} topics.` : validateTopicText(text, topics); newTopicError.textContent = error ?? ""; newTopicInput.setAttribute("aria-invalid", error ? "true" : "false"); if (error) return false; topics.push({ id: newTopicId(), text, enabled: true }); newTopicInput.value = ""; renderTopics(); markDirty(); return true; } $("add-topic").addEventListener("click", addTopic); newTopicInput.addEventListener("keydown", (e) => { if (e.key === "Enter") { e.preventDefault(); addTopic(); } }); // ── Load / save ─────────────────────────────────────────────────────────── function applyToForm(s: Settings): void { saved = s; topics = s.topics.map((t) => ({ ...t })); enabledInput.checked = s.enabled; form.querySelectorAll('input[name="mode"]').forEach((r) => (r.checked = r.value === s.mode)); sitesInput.value = s.excludedSites.join("\n"); selectorsInput.value = s.protectedSelectors.join("\n"); engineSelect.value = s.engine; imagesInput.checked = s.images; imageDownloadsInput.checked = s.imageDownloads; syncImageControls(); renderTopics(); dirtyNote.hidden = true; } /** Validate the whole form; returns settings or null (errors are shown). */ function readForm(): Settings | null { let ok = true; const seen: Topic[] = []; const cleanTopics: Topic[] = []; for (const t of topics) { const row = topicList.querySelector(`[data-topic-id="${CSS.escape(t.id)}"]`); const phraseError = (t.excludedPhrases?.length ?? 0) > LIMITS.maxExcludedPhrases ? "At most 10 text exclusions." : t.excludedPhrases?.some(p => p.length > LIMITS.maxExcludedPhraseChars) ? "Text exclusions must be at most 120 characters each." : null; const err = validateTopicText(t.text, seen) ?? phraseError; if (row) { row.querySelector(".row-error")!.textContent = err ?? ""; row.querySelector('input[type="text"]')!.setAttribute("aria-invalid", err ? "true" : "false"); } if (err) ok = false; const clean = { ...t, text: normalizeTopicText(t.text) }; const phrases = normalizeExcludedPhrases(t.excludedPhrases); if (phrases.length) clean.excludedPhrases = phrases; else delete clean.excludedPhrases; seen.push(clean); cleanTopics.push(clean); } const siteLines = parseLines(sitesInput.value); const sites = parseSiteRules(siteLines); const siteErrors = sites.errors.map((e) => `“${e.input}”: ${e.error}`); if (sites.hosts.length > LIMITS.maxSites) siteErrors.push(`At most ${LIMITS.maxSites} sites.`); fillErrors(sitesError, sitesInput, siteErrors); if (siteErrors.length) ok = false; const selectors = [...new Set(parseLines(selectorsInput.value))]; const selectorErrors = selectors.flatMap((s) => { const e = validateSelector(s, document); return e ? [`“${s}”: ${e}`] : []; }); if (selectors.length > LIMITS.maxSelectors) selectorErrors.push(`At most ${LIMITS.maxSelectors} selectors.`); fillErrors(selectorsError, selectorsInput, selectorErrors); if (selectorErrors.length) { ok = false; (selectorsInput.closest("details") as HTMLDetailsElement).open = true; } if (!ok) return null; const mode = (form.querySelector('input[name="mode"]:checked')?.value ?? "precision") as FilterMode; const engine = engineSelect.value as EnginePreference; return { schema: 2, enabled: enabledInput.checked, mode: FILTER_MODES.includes(mode) ? mode : "precision", engine: ENGINE_PREFERENCES.includes(engine) ? engine : "auto", topics: cleanTopics, excludedSites: sites.hosts, protectedSelectors: selectors, images: imagesInput.checked, imageDownloads: imageDownloadsInput.checked, }; } /** Downloads only mean something with image filtering on. */ function syncImageControls(): void { imageDownloadsInput.disabled = !imagesInput.checked; } imagesInput.addEventListener("change", syncImageControls); form.addEventListener("submit", async (e) => { e.preventDefault(); // A topic typed but not yet added must not be silently discarded. if (normalizeTopicText(newTopicInput.value) && !addTopic()) { setStatus("Not saved — the new topic is not valid (see the message under it).", "error"); newTopicInput.focus(); return; } const next = readForm(); if (!next) { setStatus("Not saved — please fix the highlighted fields.", "error"); (form.querySelector('[aria-invalid="true"]') as HTMLElement | null)?.focus(); return; } try { await chrome.storage.local.set({ [SETTINGS_KEY]: next }); applyToForm(next); const n = next.topics.filter((t) => t.enabled).length; setStatus( !next.enabled ? "Saved. Filtering is turned off." : n === 0 ? "Saved. Add a topic to start filtering." : `Saved. ${n} topic${n === 1 ? "" : "s"} configured. Pages may take time to be checked.`, "ok" ); } catch (err) { setStatus(`Could not save: ${String(err)}`, "error"); } }); form.addEventListener("input", () => { markDirty(); }); chrome.storage.onChanged.addListener((changes, area) => { // Reflect changes made elsewhere (e.g. the popup) unless the user is editing. if (area === "local" && changes[SETTINGS_KEY] && dirtyNote.hidden) { applyToForm(migrateSettings({ [SETTINGS_KEY]: changes[SETTINGS_KEY].newValue }).settings); } }); // ── Engine status ───────────────────────────────────────────────────────── let lastStatus: UiStatusReply | null = null; async function refreshStatus(): Promise { try { const status = (await chrome.runtime.sendMessage({ type: "ui:status" })) as UiStatusReply; lastStatus = status; engineStatusEl.dataset.state = status.engine.state; engineStatusEl.textContent = !saved?.enabled ? "Filtering off" : describeEngine(status.engine); const rows: [string, string][] = [ ["Engine", status.engine.state], ["Backend", status.engine.backend ?? "—"], ["Model", status.engine.model], ["Load time", status.engine.loadMs === null ? "—" : `${status.engine.loadMs} ms`], ["Detail", status.engine.detail ?? "—"], ["Content script", status.registration.registered ? "registered" : "not registered"], ["Registration error", status.registration.error ?? "—"], ["Image model", saved?.images ? `${status.vision.model}: ${describeVision(status.vision, true)}` : "off"], ["Image model load time", status.vision.loadMs === null ? "—" : `${status.vision.loadMs} ms`], ["Image model detail", status.vision.detail ?? "—"], ]; diagnostics.replaceChildren( ...rows.flatMap(([k, v]) => [ Object.assign(document.createElement("dt"), { textContent: k }), Object.assign(document.createElement("dd"), { textContent: v }), ]) ); } catch { engineStatusEl.textContent = "Status unavailable"; } } // ── Copy diagnostics (explicit click only; see diagnostics.ts) ──────────── const copyStatus = $("copy-status"); $("copy-diagnostics").addEventListener("click", async () => { if (!saved || !lastStatus) { copyStatus.textContent = "Status not available yet — try again in a moment."; return; } const text = formatDiagnostics({ version: chrome.runtime.getManifest().version, browser: browserMajor(navigator.userAgent), settings: saved, engine: lastStatus.engine, vision: lastStatus.vision, registered: lastStatus.registration.registered, includeTopics: $("diag-topics").checked, }); try { await navigator.clipboard.writeText(text); copyStatus.textContent = "Copied to the clipboard."; } catch { copyStatus.textContent = "Could not copy to the clipboard."; } }); // ── Migration notes ─────────────────────────────────────────────────────── const migrationBox = $("migration-notes"); chrome.storage.local.get(MIGRATION_NOTES_KEY).then((r) => { const notes = r[MIGRATION_NOTES_KEY] as { droppedSites?: { input: string; error: string }[] } | undefined; const dropped = Array.isArray(notes?.droppedSites) ? notes!.droppedSites : []; if (!dropped.length) return; $("migration-list").replaceChildren( ...dropped.map((d) => Object.assign(document.createElement("li"), { textContent: `${String(d.input)} — ${String(d.error)}` })) ); migrationBox.hidden = false; }); $("dismiss-migration").addEventListener("click", async () => { await chrome.storage.local.remove(MIGRATION_NOTES_KEY); migrationBox.hidden = true; }); chrome.storage.local.get([...STORAGE_KEYS]).then((stored) => { applyToForm(migrateSettings(stored).settings); void refreshStatus(); }); setInterval(refreshStatus, 3000); // Explicit local export, without clipboard or network transmission. async function refreshFeedback(): Promise { try { const reply = await chrome.runtime.sendMessage({ type: "feedback:list" }); if (!reply?.ok) throw Error("unavailable"); const feedback: FeedbackRecord[] = reply.records; $("feedback-summary").textContent = `${feedback.length} local report${feedback.length === 1 ? "" : "s"}. Unreviewed user observations, not confirmed accuracy labels.`; $("export-feedback").disabled = feedback.length === 0; $("delete-feedback").disabled = feedback.length === 0; $("feedback-list").replaceChildren(...feedback.slice(-10).reverse().map(r => Object.assign(document.createElement("li"), { textContent: `${new Date(r.createdAt).toLocaleDateString()} — ${r.kind === "wrongly-hidden" ? "Wrongly hidden" : "Should be hidden"}: ${r.topic} (${r.target.tag} ${r.target.ordinal})${r.diagnostics ? "; diagnostics included" : ""}`, }))); return feedback; } catch { $("feedback-summary").textContent = "Could not read local feedback. Reload Settings to try again."; return []; } } $("export-feedback").addEventListener("click", async () => { const feedback = await refreshFeedback(); if (!feedback.length) return; const blob = new Blob([JSON.stringify({ schema: 1, exportedAt: new Date().toISOString(), records: feedback }, null, 2)], { type: "application/json" }); const url = URL.createObjectURL(blob); const a = Object.assign(document.createElement("a"), { href: url, download: "clearscroll-local-feedback.json" }); a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); }); $("delete-feedback").addEventListener("click", async () => { try { const reply = await chrome.runtime.sendMessage({ type: "feedback:clear" }); if (!reply?.ok) throw Error("unavailable"); await refreshFeedback(); } catch { $("feedback-summary").textContent = "Could not delete feedback. Try again."; } }); chrome.storage.onChanged.addListener((changes, area) => { if (area === "local" && changes[FEEDBACK_KEY]) void refreshFeedback(); }); void refreshFeedback();