diff --git a/docs/SYSTEM_SPEC.md b/docs/SYSTEM_SPEC.md index 4dee9b9..70d33d1 100644 --- a/docs/SYSTEM_SPEC.md +++ b/docs/SYSTEM_SPEC.md @@ -153,6 +153,7 @@ | `src/lib/checker/config.ts` | Checker rule settings: the zod schema, defaults, the list of built-in rule ids, JSON export and import, and `applyOverrides` for a draft's `checks:` front matter. | `CheckConfig`, `DEFAULT_CONFIG`, `parseConfig`, `exportConfig`, `importConfig`, `applyOverrides` | | `src/lib/checker/{standards,custom,run,storage}.ts` | The publication standards, the writer's own pattern rules (with limits and a guard against runaway patterns), the runner that merges all issues for the Checks panel, and the localStorage load and save. | `runStandards`, `runCustomRules`, `validateCustomRule`, `runChecks`, `loadConfig`, `saveConfig` | | `src/lib/storage/zip.ts` | Dependency-free ZIP reader and writer (deflate through `CompressionStream`; no encryption or ZIP64). Limits: 5,000 files, 256 MB unpacked. | `createZip(entries)`, `readZip(bytes, limits?)`, `ZIP_LIMITS` | +| `src/lib/search/` | Search palette logic: `rank.ts` (every word must match; titles that start with them first; a draft's matching line), `entries.ts` (pages, guides, settings rows from `src/lib/settings/catalog.ts`, theme, drafts by name and text), `registry.ts` (entries a mounted page adds, open state, line to jump to). UI in `src/components/search/`, loaded on first open. | `rankEntries`, `draftEntries`, `siteEntries` | | `src/lib/settings/` | The Settings page's pure parts: `tabs.ts` (which sections a signed-in or signed-out visitor sees, parsed from `?tab=`) and `prefs.ts` (the target platform and Normalize choices in `localStorage`, the keys Studio reads). The page is `src/routes/settings.tsx` with `src/components/settings/`. | `visibleTabs`, `parseSettingsTab`, `loadPrefs`, `savePrefs` | | `src/lib/storage/archive.ts` | Drafts to and from archive files: `Folder/title.md`, images under `images/`, library folders as directories. | `buildArchive(docs)`, `parseArchive(files)`, `mapImageSrc`, `dataUriToBytes` | | `src/lib/editor/diff.ts` | Dependency-free line diff (longest common subsequence, large inputs shown whole) producing side-by-side rows. | `diffLines(a, b)`, `diffStats(rows)` | diff --git a/docs/UI_SPEC.md b/docs/UI_SPEC.md index 6f6909d..b0197d3 100644 --- a/docs/UI_SPEC.md +++ b/docs/UI_SPEC.md @@ -122,6 +122,10 @@ Only for an admin; anyone else sees the site's 404. Reached from "Admin dashboar Opened from the Account menu (**Account** opens the Account tab, **Settings** the Editor tab), from a gear button beside Sign in in the editor's top bar when signed out, and from the header and footer of the public pages. Tabs, with the open one in the address (`?tab=`): **Account** (signed in only: picture, name and address; Display name, Email and Password rows, each with an Edit button that opens a dialog: the name field, the new address with the current password (a link is emailed to it and the address changes when it is opened; disabled for an account with no password, which sets one first), or the current and the new password (an account that signs in with GitHub or Google has no current one and sees Set password); changing the password signs the other devices out), then **Sign in with GitHub** and **Sign in with Google** rows (when the server has them) with Link, which leaves for the provider and comes back with a toast, or Unlink, disabled with an explanation while it is the only way to sign in). The content is one centred column., **Editor** (theme, target platform, Normalize on export, a button for the writing-check rules and one for keyboard shortcuts; all kept on this device), **AI** (opens the AI integrations dialog) and **Connections** (cloud drafts, hosted images when the server has them, and GitHub publishing with Connect or Disconnect; signed in only). A signed-out visitor sees only Editor and AI and cannot reach the others by address. The rules, shortcuts, AI, cloud-drafts and images dialogs are the same ones the editor opens, so they stay where they are used mid-task. noindex. +## 6c. Search palette + +A dialog for finding anything, on every page: Ctrl/⌘ Shift P anywhere, Ctrl/⌘ K anywhere except in the editor's text (where it stays Link), or the Search button in the editor's top bar, the Settings header and the public pages' header (not on the home page, which keeps its header for the call to open the editor; the shortcuts work there). One field and grouped results: **Drafts** (by name, title or folder), **In drafts** (drafts whose text holds every word, with the matching line; choosing one opens the draft at that line), **Headings** of the open draft, **Commands** (in the editor: new draft, import, the exports, views, panels, focus, insert link, image or table, save a version, the rules, AI and shortcuts dialogs, and share, edit together and publish for a cloud draft; everywhere: theme), **Settings** (each row of the Settings page, opening its tab) and **Pages** (editor, settings, guides and each guide, privacy, terms, and the admin dashboard for an admin). Arrow keys move, Enter opens, Esc closes; with nothing typed it lists the recent drafts and the first commands. Its code loads the first time it opens. + ## 7. Small screens — `06_mobile_editor_view.png`, `07_mobile_preview_view.png` - **Below 768px** the studio is a single pane: the view toggle offers Editor and Preview only, and the panel buttons move to a bottom navigation bar. diff --git a/e2e/search.spec.ts b/e2e/search.spec.ts new file mode 100644 index 0000000..da8dba6 --- /dev/null +++ b/e2e/search.spec.ts @@ -0,0 +1,92 @@ +import { expect, test, type Page } from "@playwright/test"; +import { replaceText, startDraft } from "./draft"; + +const palette = (page: Page) => page.getByRole("dialog", { name: "Search" }); +const search = async (page: Page, text: string) => { + await palette(page).getByRole("combobox", { name: "Search" }).fill(text); +}; + +/** Two drafts: the second open, the first holding a rare word on its line 9. */ +async function twoDrafts(page: Page) { + await startDraft(page); + const body = [ + "# Mission log", + "", + "Day one.", + "", + "Day two.", + "", + "Day three.", + "", + "The zebrafish swam past.", + ]; + await replaceText(page, body.join("\n")); + const first = new URL(page.url()).pathname; + await page.getByRole("button", { name: "New draft" }).first().click(); + await expect(page).not.toHaveURL(first); + await replaceText(page, "# Shopping\n\nmilk"); + return first; +} + +test("finds a word inside another draft and opens it at that line", async ({ page }) => { + const first = await twoDrafts(page); + await page.locator("body").click({ position: { x: 5, y: 5 } }); // out of the editor text + await page.keyboard.press("ControlOrMeta+k"); + await expect(palette(page)).toBeVisible(); + await search(page, "zebrafish"); + const option = palette(page).getByRole("option", { name: /Mission log/ }); + await expect(option).toContainText("The zebrafish swam past."); + await page.keyboard.press("Enter"); + await expect(palette(page)).toBeHidden(); + await expect(page).toHaveURL(first); + await expect(page.locator(".cm-activeLine")).toContainText("zebrafish"); +}); + +test("Ctrl/⌘ K inside the editor text stays Link; Ctrl/⌘ Shift P opens search there", async ({ + page, +}) => { + await startDraft(page); + await page.locator(".cm-content").click(); + await page.keyboard.press("ControlOrMeta+k"); + await expect(palette(page)).toBeHidden(); + await page.keyboard.press("Escape"); + await page.locator(".cm-content").click(); + await page.keyboard.press("ControlOrMeta+Shift+p"); + await expect(palette(page)).toBeVisible(); +}); + +test("runs an editor command and goes to a setting", async ({ page }) => { + await startDraft(page); + await page.getByRole("button", { name: "Search", exact: true }).click(); + await search(page, "insert table"); + await page.keyboard.press("Enter"); + await expect(page.getByRole("dialog", { name: /table/i })).toBeVisible(); + await page.keyboard.press("Escape"); + + await page.getByRole("button", { name: "Search", exact: true }).click(); + await search(page, "target platform"); + await palette(page) + .getByRole("option", { name: /Target platform/ }) + .click(); + await expect(page).toHaveURL(/\/settings\?tab=editor/); +}); + +test("works on other pages, and on the home page by shortcut only", async ({ page }) => { + await page.goto("/guides"); + // a server-rendered page: the button works once the page has hydrated + await expect(async () => { + await page.getByRole("button", { name: "Search", exact: true }).click(); + await expect(palette(page)).toBeVisible({ timeout: 1000 }); + }).toPass(); + await search(page, "privacy"); + await page.keyboard.press("Enter"); + await expect(page).toHaveURL(/\/privacy/); + + // the home page has the shortcut but no button + await page.goto("/"); + await expect(page.getByRole("button", { name: "Search", exact: true })).toHaveCount(0); + await expect(async () => { + await page.keyboard.press("ControlOrMeta+k"); + await expect(palette(page)).toBeVisible({ timeout: 1000 }); + }).toPass(); +}); diff --git a/src/components/search/SearchButton.tsx b/src/components/search/SearchButton.tsx new file mode 100644 index 0000000..89dc809 --- /dev/null +++ b/src/components/search/SearchButton.tsx @@ -0,0 +1,19 @@ +import { Search } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { setSearchOpen } from "@/lib/search/registry"; + +/** Opens the search palette (also Ctrl/⌘ K). */ +export function SearchButton({ className }: { className?: string }) { + return ( + + ); +} diff --git a/src/components/search/SearchHost.tsx b/src/components/search/SearchHost.tsx new file mode 100644 index 0000000..bb6a92a --- /dev/null +++ b/src/components/search/SearchHost.tsx @@ -0,0 +1,32 @@ +import { Suspense, lazy, useEffect } from "react"; +import { setSearchOpen, useSearchOpen } from "@/lib/search/registry"; + +// The palette's code loads the first time it opens, so pages pay nothing until then. +const SearchPalette = lazy(() => import("./SearchPalette")); + +/** + * Opens search on Ctrl/⌘ Shift P anywhere, and on Ctrl/⌘ K outside the editor's text (where it + * stays "Link"). Every page has the shortcuts; the home page has no button for it (SiteHeader). + */ +export function SearchHost() { + const open = useSearchOpen(); + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (!(e.metaKey || e.ctrlKey) || e.altKey) return; + const key = e.key.toLowerCase(); + const inEditor = e.target instanceof Element && !!e.target.closest(".cm-editor"); + if ((key === "p" && e.shiftKey) || (key === "k" && !e.shiftKey && !inEditor)) { + e.preventDefault(); + setSearchOpen(true); + } + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, []); + if (!open) return null; + return ( + + + + ); +} diff --git a/src/components/search/SearchPalette.tsx b/src/components/search/SearchPalette.tsx new file mode 100644 index 0000000..75ff5bd --- /dev/null +++ b/src/components/search/SearchPalette.tsx @@ -0,0 +1,155 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import { useNavigate, useRouterState } from "@tanstack/react-router"; +import { Search } from "lucide-react"; +import { Dialog, DialogContent, DialogDescription, DialogTitle } from "@/components/ui/dialog"; +import { useAccount } from "@/lib/account/store"; +import { documentStore, indexedDbStore } from "@/lib/storage/documentStore"; +import { cloudOwners, isVisibleDoc } from "@/lib/sync/meta"; +import { setTheme } from "@/lib/ui/theme"; +import { draftEntries, siteEntries, type SearchNav } from "@/lib/search/entries"; +import { type SearchEntry, groupResults, rankEntries } from "@/lib/search/rank"; +import { registeredEntries, requestJump, setSearchOpen } from "@/lib/search/registry"; + +type Draft = Parameters[0][number]; + +/** The search palette: drafts and their text, the page's commands, settings and pages. */ +export default function SearchPalette() { + const navigate = useNavigate(); + const path = useRouterState({ select: (s) => s.location.pathname }); + const account = useAccount(); + const [query, setQuery] = useState(""); + const [active, setActive] = useState(0); + const [drafts, setDrafts] = useState([]); + const list = useRef(null); + + useEffect(() => { + let live = true; + void Promise.all([documentStore.list(), cloudOwners(indexedDbStore)]).then(([all, owners]) => { + if (live) setDrafts(all.filter((d) => isVisibleDoc(owners, d, account.user?.id))); + }); + return () => { + live = false; + }; + }, [account.user?.id]); + + const close = () => setSearchOpen(false); + const nav: SearchNav = useMemo( + () => ({ + go: (to) => void navigate({ to }), + openDraft: (id, line) => { + if (line) requestJump(id, line); + if (path !== `/editor/${id}`) + void navigate({ to: "/editor/$docId", params: { docId: id } }); + }, + setTheme, + }), + [navigate, path], + ); + + const groups = useMemo(() => { + const who = { signedIn: !!account.user, isAdmin: !!account.user?.isAdmin }; + const fixed = [...registeredEntries(), ...siteEntries(nav, who)]; + if (!query.trim()) + return groupResults( + [...draftEntries(drafts, "", nav).slice(0, 5), ...registeredEntries().slice(0, 5)], + 5, + ); + return groupResults([...draftEntries(drafts, query, nav), ...rankEntries(query, fixed)]); + }, [query, drafts, nav, account.user]); + const flat = groups.flatMap((g) => g.items); + const current = flat[Math.min(active, flat.length - 1)]; + + useEffect(() => setActive(0), [query]); + useEffect(() => { + list.current?.querySelector(`[data-index="${active}"]`)?.scrollIntoView({ block: "nearest" }); + }, [active]); + + const choose = (e: SearchEntry | undefined) => { + if (!e) return; + close(); + e.run(); + }; + + let index = -1; + return ( + !open && close()}> + + Search + + Find drafts, words in drafts, commands, settings and pages. + +
+ + setQuery(e.target.value)} + onKeyDown={(e) => { + if (e.key === "ArrowDown") { + e.preventDefault(); + setActive((a) => Math.min(a + 1, flat.length - 1)); + } else if (e.key === "ArrowUp") { + e.preventDefault(); + setActive((a) => Math.max(a - 1, 0)); + } else if (e.key === "Enter") { + e.preventDefault(); + choose(current); + } + }} + /> +
+
+ {!flat.length && ( +

+ {query.trim() ? "Nothing found." : "Type to search."} +

+ )} + {groups.map((g) => ( +
+

+ {query.trim() || g.group !== "Drafts" ? g.group : "Recent drafts"} +

+ {g.items.map((e) => { + index += 1; + const i = index; + return ( +
setActive(i)} + onClick={() => choose(e)} + > + {e.title} + {e.hint && ( + {e.hint} + )} +
+ ); + })} +
+ ))} +
+

+ ↑ ↓ to move · Enter to open · Esc to close +

+
+
+ ); +} diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx index 20229de..9f20798 100644 --- a/src/components/settings/SettingsPage.tsx +++ b/src/components/settings/SettingsPage.tsx @@ -2,6 +2,7 @@ import { useEffect } from "react"; import { Link } from "@tanstack/react-router"; import { Logo } from "@/components/Logo"; import { ThemeToggle } from "@/components/ThemeToggle"; +import { SearchButton } from "@/components/search/SearchButton"; import { Button } from "@/components/ui/button"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { accountStore, useAccount } from "@/lib/account/store"; @@ -38,6 +39,7 @@ export function SettingsPage({ tab, onTab }: { tab: string; onTab: (tab: Setting + diff --git a/src/components/site/SiteHeader.tsx b/src/components/site/SiteHeader.tsx index 724ae3d..51cd5f9 100644 --- a/src/components/site/SiteHeader.tsx +++ b/src/components/site/SiteHeader.tsx @@ -1,4 +1,5 @@ -import { Link } from "@tanstack/react-router"; +import { Link, useRouterState } from "@tanstack/react-router"; +import { SearchButton } from "@/components/search/SearchButton"; import { ArrowUpRight, Github, Settings } from "lucide-react"; import { Logo } from "@/components/Logo"; import { ThemeToggle } from "@/components/ThemeToggle"; @@ -7,6 +8,8 @@ import { SITE } from "@/lib/site/seo"; /** Header for the public pages: logo (home), theme toggle and the GitHub link. */ export function SiteHeader() { + // the home page keeps its own navigation, without search + const home = useRouterState({ select: (s) => s.location.pathname === "/" }); return (
+ {!home && } )} +
diff --git a/src/lib/search/entries.test.ts b/src/lib/search/entries.test.ts new file mode 100644 index 0000000..7ad21f7 --- /dev/null +++ b/src/lib/search/entries.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it, vi } from "vitest"; +import { SETTINGS_TABS } from "@/lib/settings/tabs"; +import { SETTING_ROWS } from "@/lib/settings/catalog"; +import { draftEntries, siteEntries } from "./entries"; +import { rankEntries } from "./rank"; + +const nav = () => ({ go: vi.fn(), openDraft: vi.fn(), setTheme: vi.fn() }); + +describe("siteEntries", () => { + it("offers only the settings and pages a visitor can reach", () => { + const out = siteEntries(nav(), { signedIn: false, isAdmin: false }); + const titles = out.map((e) => e.title); + expect(titles).toContain("Target platform"); + expect(titles).not.toContain("Password"); + expect(titles).not.toContain("Admin dashboard"); + const admin = siteEntries(nav(), { signedIn: true, isAdmin: true }).map((e) => e.title); + expect(admin).toEqual(expect.arrayContaining(["Password", "Admin dashboard"])); + }); + it("a setting goes to its tab, and a theme is applied at once", () => { + const n = nav(); + const out = siteEntries(n, { signedIn: true, isAdmin: false }); + rankEntries("password", out)[0]!.run(); + expect(n.go).toHaveBeenCalledWith("/settings?tab=account"); + rankEntries("theme dark", out)[0]!.run(); + expect(n.setTheme).toHaveBeenCalledWith("dark"); + }); + it("finds a guide by its title", () => { + const out = siteEntries(nav(), { signedIn: false, isAdmin: false }); + expect(rankEntries("portable markdown", out)[0]).toMatchObject({ group: "Pages" }); + }); + it("names a real tab in every settings row", () => { + for (const row of SETTING_ROWS) expect(SETTINGS_TABS).toContain(row.tab); + }); +}); + +describe("draftEntries", () => { + const docs = [ + { + id: "a", + title: "Launch plan", + content: "# Launch plan\n\nThe rocket goes up.", + folder: "Work", + }, + { id: "b", title: "Notes", name: "Groceries", content: "eggs\nmilk and rocket salad" }, + { id: "c", title: "Empty", content: "" }, + ]; + it("matches drafts by name, title or folder, and by words in the text with the line", () => { + const n = nav(); + const out = draftEntries(docs, "rocket", n); + expect(out.map((e) => [e.group, e.title])).toEqual([ + ["In drafts", "Launch plan"], + ["In drafts", "Groceries"], + ]); + expect(out[1]!.hint).toBe("milk and rocket salad"); + out[1]!.run(); + expect(n.openDraft).toHaveBeenCalledWith("b", 2); + expect(draftEntries(docs, "work", n).map((e) => [e.group, e.title])).toEqual([ + ["Drafts", "Launch plan"], + ]); + }); + it("lists a draft once: a title match is not repeated as a text match", () => { + const out = draftEntries(docs, "launch", nav()); + expect(out.map((e) => e.group)).toEqual(["Drafts"]); + }); + it("with no words, lists the drafts as given (most recent first)", () => { + expect(draftEntries(docs, "", nav()).map((e) => e.title)).toEqual([ + "Launch plan", + "Groceries", + "Empty", + ]); + }); +}); diff --git a/src/lib/search/entries.ts b/src/lib/search/entries.ts new file mode 100644 index 0000000..3ba746f --- /dev/null +++ b/src/lib/search/entries.ts @@ -0,0 +1,95 @@ +// The entries every page can search: pages, guides, settings rows, theme, and the drafts in this +// browser. The editor adds its own commands through registry.ts. +import { GUIDES, guidePath } from "@/lib/site/guides"; +import { SETTING_ROWS } from "@/lib/settings/catalog"; +import { visibleTabs } from "@/lib/settings/tabs"; +import type { Theme } from "@/lib/ui/theme"; +import { type SearchEntry, matchLine, rankEntries, termsOf } from "./rank"; + +export type SearchNav = { + go: (to: string) => void; + openDraft: (id: string, line?: number) => void; + setTheme: (theme: Theme) => void; +}; + +export function siteEntries( + nav: SearchNav, + who: { signedIn: boolean; isAdmin: boolean }, +): SearchEntry[] { + const tabs = visibleTabs(who.signedIn); + const page = (title: string, to: string, keywords = ""): SearchEntry => ({ + id: `page:${to}`, + group: "Pages", + title, + keywords, + run: () => nav.go(to), + }); + return [ + page("Editor", "/editor", "drafts write library"), + page("Settings", "/settings", "preferences options"), + ...(who.isAdmin ? [page("Admin dashboard", "/admin", "accounts plans server")] : []), + page("Guides", "/guides", "help docs learn"), + ...GUIDES.map((g) => ({ ...page(g.title, guidePath(g.slug), "guide"), hint: "Guide" })), + page("Privacy", "/privacy", "policy data"), + page("Terms", "/terms", "terms of use"), + ...SETTING_ROWS.filter((r) => tabs.includes(r.tab)).map((r): SearchEntry => ({ + id: `setting:${r.title}`, + group: "Settings", + title: r.title, + hint: `Settings, ${r.tab[0]!.toUpperCase()}${r.tab.slice(1)}`, + keywords: r.keywords, + run: () => nav.go(`/settings?tab=${r.tab}`), + })), + ...(["light", "dark", "system"] as const).map((t): SearchEntry => ({ + id: `theme:${t}`, + group: "Commands", + title: `Theme: ${t[0]!.toUpperCase()}${t.slice(1)}`, + keywords: "appearance mode", + run: () => nav.setTheme(t), + })), + ]; +} + +type Draft = { + id: string; + title: string; + name?: string | undefined; + content: string; + folder?: string | undefined; +}; + +/** + * Drafts whose name, title or folder match ("Drafts"), then drafts whose text holds every word + * ("In drafts", with the line). With no words: every draft, in the order given. + */ +export function draftEntries(docs: Draft[], query: string, nav: SearchNav): SearchEntry[] { + const label = (d: Draft) => d.name?.trim() || d.title || "Untitled"; + const byTitle = docs.map((d): SearchEntry => ({ + id: `draft:${d.id}`, + group: "Drafts", + title: label(d), + ...(d.folder && { hint: d.folder }), + keywords: `${d.title} ${d.folder ?? ""}`, + run: () => nav.openDraft(d.id), + })); + const terms = termsOf(query); + if (!terms.length) return byTitle; + const titled = rankEntries(query, byTitle); + const seen = new Set(titled.map((e) => e.id)); + const inText: SearchEntry[] = []; + for (const d of docs) { + if (seen.has(`draft:${d.id}`)) continue; + const lower = d.content.toLowerCase(); + if (!terms.every((t) => lower.includes(t))) continue; + const m = matchLine(d.content, terms); + if (!m) continue; + inText.push({ + id: `text:${d.id}`, + group: "In drafts", + title: label(d), + hint: m.text, + run: () => nav.openDraft(d.id, m.line), + }); + } + return [...titled, ...inText]; +} diff --git a/src/lib/search/rank.test.ts b/src/lib/search/rank.test.ts new file mode 100644 index 0000000..f3a39a2 --- /dev/null +++ b/src/lib/search/rank.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from "vitest"; +import { type SearchEntry, groupResults, matchLine, rankEntries } from "./rank"; + +const entry = (title: string, extra: Partial = {}): SearchEntry => ({ + id: title, + group: "Commands", + title, + run: () => {}, + ...extra, +}); + +describe("rankEntries", () => { + const entries = [ + entry("Download all drafts (.zip)", { keywords: "export archive backup" }), + entry("Download .md", { keywords: "export markdown file" }), + entry("Insert table"), + entry("Theme: Dark", { keywords: "appearance night" }), + ]; + const titles = (q: string) => rankEntries(q, entries).map((e) => e.title); + + it("needs every word, from the title or the keywords, in any case", () => { + expect(titles("DOWNLOAD zip")).toEqual(["Download all drafts (.zip)"]); + expect(titles("export markdown")).toEqual(["Download .md"]); + expect(titles("dark night")).toEqual(["Theme: Dark"]); + expect(titles("table zip")).toEqual([]); + }); + it("puts a title that starts with the words before one that only contains them", () => { + const list = [ + entry("Copy rendered HTML"), + entry("HTML export"), + entry("Show HTML", { keywords: "x" }), + ]; + expect(rankEntries("html", list).map((e) => e.title)).toEqual([ + "HTML export", + "Copy rendered HTML", + "Show HTML", + ]); + }); + it("ranks a title match above a keyword-only match", () => { + expect(titles("export")).toEqual(["Download all drafts (.zip)", "Download .md"]); + const list = [entry("Backup", { keywords: "zip" }), entry("Zip it")]; + expect(rankEntries("zip", list).map((e) => e.title)).toEqual(["Zip it", "Backup"]); + }); + it("returns nothing for an empty query", () => expect(titles(" ")).toEqual([])); +}); + +describe("matchLine", () => { + const text = "---\ntitle: X\n---\n# Intro\n\nSome words here.\nThe rocket launches at dawn.\n"; + it("finds the 1-based line with the most of the words, outside the front matter", () => { + expect(matchLine(text, ["rocket", "dawn"])).toEqual({ + line: 7, + text: "The rocket launches at dawn.", + }); + expect(matchLine(text, ["title"])).toBeNull(); + expect(matchLine(text, ["missing"])).toBeNull(); + }); + it("shortens a long line around the match", () => { + const long = `${"a ".repeat(100)}needle${" b".repeat(100)}`; + const m = matchLine(long, ["needle"])!; + expect(m.text.length).toBeLessThan(120); + expect(m.text).toContain("needle"); + expect(m.text.startsWith("…")).toBe(true); + }); +}); + +describe("groupResults", () => { + it("keeps the groups in a fixed order and caps each one", () => { + const list = [ + entry("c1"), + entry("d1", { group: "Drafts" }), + ...Array.from({ length: 12 }, (_, i) => entry(`s${i}`, { group: "Settings" })), + ]; + const groups = groupResults(list, 5); + expect(groups.map((g) => g.group)).toEqual(["Drafts", "Commands", "Settings"]); + expect(groups[2]!.items).toHaveLength(5); + }); +}); diff --git a/src/lib/search/rank.ts b/src/lib/search/rank.ts new file mode 100644 index 0000000..d07fcc6 --- /dev/null +++ b/src/lib/search/rank.ts @@ -0,0 +1,83 @@ +// Ranking for the search palette: every word typed must be in an entry's title or keywords; a +// title that starts with them beats one that contains them, which beats keywords alone. Pure, so +// the palette, its tests and any page share one behaviour. + +export const GROUPS = ["Drafts", "In drafts", "Headings", "Commands", "Settings", "Pages"] as const; +export type Group = (typeof GROUPS)[number]; + +export type SearchEntry = { + id: string; + group: Group; + title: string; + /** A second line: where it is, or the matching words of a draft. */ + hint?: string; + /** Other words it should be found by (not shown). */ + keywords?: string; + run: () => void; +}; + +// The front matter block, as markdown.ts finds it; matched here so the palette does not load the +// Markdown engine on pages that have no editor. +const FRONT_MATTER = /^---\r?\n[\s\S]*?\r?\n---\r?\n?/; + +export const termsOf = (query: string) => query.toLowerCase().split(/\s+/).filter(Boolean); + +function score(terms: string[], e: SearchEntry): number | null { + const title = e.title.toLowerCase(); + const rest = `${e.keywords ?? ""} ${e.hint ?? ""}`.toLowerCase(); + let total = 0; + for (const t of terms) { + if (title.startsWith(t)) total += 3; + else if (new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`).test(title)) total += 2; + else if (title.includes(t)) total += 1.5; + else if (rest.includes(t)) total += 1; + else return null; + } + return total; +} + +/** The entries that match every word, best first (ties keep their order). */ +export function rankEntries(query: string, entries: SearchEntry[]): SearchEntry[] { + const terms = termsOf(query); + if (!terms.length) return []; + return entries + .map((e, i) => ({ e, i, s: score(terms, e) })) + .filter((r): r is { e: SearchEntry; i: number; s: number } => r.s !== null) + .sort((a, b) => b.s - a.s || a.i - b.i) + .map((r) => r.e); +} + +const LINE_CHARS = 100; + +/** The line of a draft's text with the most of the words (1-based, front matter skipped). */ +export function matchLine(content: string, terms: string[]): { line: number; text: string } | null { + const head = content.match(FRONT_MATTER)?.[0] ?? ""; + const body = content.slice(head.length); + const offset = head.split("\n").length - 1; + let best: { line: number; text: string; hits: number; at: number } | null = null; + body.split(/\r?\n/).forEach((raw, i) => { + const lower = raw.toLowerCase(); + const at = terms.map((t) => lower.indexOf(t)).filter((n) => n >= 0); + if (at.length && (!best || at.length > best.hits)) + best = { line: offset + i + 1, text: raw, hits: at.length, at: Math.min(...at) }; + }); + if (!best) return null; + const { line, text: raw, at } = best as { line: number; text: string; at: number }; + const text = raw.trim(); + if (text.length <= LINE_CHARS) return { line, text }; + const lead = raw.length - raw.trimStart().length; + const start = Math.max(0, Math.min(at - lead - 30, text.length - LINE_CHARS)); + const end = start + LINE_CHARS; + return { + line, + text: `${start > 0 ? "…" : ""}${text.slice(start, end)}${end < text.length ? "…" : ""}`, + }; +} + +/** Results in the fixed group order, at most `perGroup` each. */ +export function groupResults(entries: SearchEntry[], perGroup = 6) { + return GROUPS.map((group) => ({ + group, + items: entries.filter((e) => e.group === group).slice(0, perGroup), + })).filter((g) => g.items.length); +} diff --git a/src/lib/search/registry.test.ts b/src/lib/search/registry.test.ts new file mode 100644 index 0000000..9c5eba1 --- /dev/null +++ b/src/lib/search/registry.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it, vi } from "vitest"; +import { onJump, registerSearchSource, registeredEntries, requestJump, takeJump } from "./registry"; + +const entry = (title: string) => ({ id: title, group: "Commands" as const, title, run: () => {} }); + +describe("search sources", () => { + it("reads every registered source at search time, and forgets one when removed", () => { + let n = 1; + const off = registerSearchSource("a", () => [entry(`a${n}`)]); + const offB = registerSearchSource("b", () => [entry("b")]); + n = 2; + expect(registeredEntries().map((e) => e.title)).toEqual(["a2", "b"]); + off(); + expect(registeredEntries().map((e) => e.title)).toEqual(["b"]); + offB(); + }); + it("a stale removal does not drop a newer source under the same key", () => { + const old = registerSearchSource("k", () => [entry("old")]); + const off = registerSearchSource("k", () => [entry("new")]); + old(); + expect(registeredEntries().map((e) => e.title)).toEqual(["new"]); + off(); + }); +}); + +describe("jumping to a line", () => { + it("is taken once, and only by the draft it was for", () => { + const heard = vi.fn(); + const off = onJump(heard); + requestJump("d1", 12); + expect(heard).toHaveBeenCalledOnce(); + expect(takeJump("d2")).toBeNull(); + expect(takeJump("d1")).toBe(12); + expect(takeJump("d1")).toBeNull(); + off(); + }); +}); diff --git a/src/lib/search/registry.ts b/src/lib/search/registry.ts new file mode 100644 index 0000000..a7058f8 --- /dev/null +++ b/src/lib/search/registry.ts @@ -0,0 +1,52 @@ +// What the search palette can find beyond drafts and pages: a page that is showing (the editor) +// adds its own commands while it is mounted. Also whether the palette is open, and a line to jump +// to once a draft opened from a text match is loaded. Module state: there is one palette. +import { useSyncExternalStore } from "react"; +import type { SearchEntry } from "./rank"; + +const sources = new Map SearchEntry[]>(); + +/** Adds a source of entries, read each time the palette searches; returns its removal. */ +export function registerSearchSource(key: string, read: () => SearchEntry[]) { + sources.set(key, read); + return () => { + if (sources.get(key) === read) sources.delete(key); + }; +} +export const registeredEntries = () => [...sources.values()].flatMap((read) => read()); + +let open = false; +const openListeners = new Set<() => void>(); +export function setSearchOpen(next: boolean) { + if (open === next) return; + open = next; + for (const l of openListeners) l(); +} +export const useSearchOpen = () => + useSyncExternalStore( + (l) => { + openListeners.add(l); + return () => void openListeners.delete(l); + }, + () => open, + () => false, + ); + +let jump: { id: string; line: number } | null = null; +const jumpListeners = new Set<() => void>(); +/** Asks the editor to go to a line of a draft once that draft is open. */ +export function requestJump(id: string, line: number) { + jump = { id, line }; + for (const l of jumpListeners) l(); +} +/** The line asked for this draft, once: it is cleared when taken. */ +export function takeJump(id: string): number | null { + if (jump?.id !== id) return null; + const { line } = jump; + jump = null; + return line; +} +export function onJump(listener: () => void) { + jumpListeners.add(listener); + return () => void jumpListeners.delete(listener); +} diff --git a/src/lib/settings/catalog.ts b/src/lib/settings/catalog.ts new file mode 100644 index 0000000..8d617dd --- /dev/null +++ b/src/lib/settings/catalog.ts @@ -0,0 +1,22 @@ +// Every row of the Settings page, for search: where it is and the words it is found by. Kept next +// to tabs.ts; the test checks each row names a real tab. +import type { SettingsTab } from "./tabs"; + +export type SettingRow = { tab: SettingsTab; title: string; keywords: string }; + +export const SETTING_ROWS: SettingRow[] = [ + { tab: "account", title: "Display name", keywords: "profile name account" }, + { tab: "account", title: "Email", keywords: "address change account" }, + { tab: "account", title: "Password", keywords: "change set security account" }, + { tab: "account", title: "Sign in with GitHub", keywords: "link unlink connected accounts" }, + { tab: "account", title: "Sign in with Google", keywords: "link unlink connected accounts" }, + { tab: "editor", title: "Theme", keywords: "appearance dark light system mode" }, + { tab: "editor", title: "Target platform", keywords: "profile commonmark gfm wiki" }, + { tab: "editor", title: "Normalize on export", keywords: "bullets fences emphasis" }, + { tab: "editor", title: "Writing checks", keywords: "rules checker lint standards" }, + { tab: "editor", title: "Keyboard shortcuts", keywords: "keys hotkeys" }, + { tab: "ai", title: "AI integrations", keywords: "provider model key openai anthropic ollama" }, + { tab: "connections", title: "Cloud drafts", keywords: "sync account storage" }, + { tab: "connections", title: "Hosted images", keywords: "uploads files" }, + { tab: "connections", title: "GitHub publishing", keywords: "connect disconnect repository" }, +]; diff --git a/src/routes/__root.tsx b/src/routes/__root.tsx index 010fd97..4e86825 100644 --- a/src/routes/__root.tsx +++ b/src/routes/__root.tsx @@ -13,6 +13,7 @@ import { useEffect, type ReactNode } from "react"; import appCss from "../styles.css?url"; import { AiCloudSession } from "@/components/AiCloudSession"; import { AuthNotices } from "@/components/AuthNotices"; +import { SearchHost } from "@/components/search/SearchHost"; import { Toaster } from "@/components/ui/sonner"; import { jsonLd, jsonLdScript, pageHead, SITE } from "@/lib/site/seo"; import { registerServiceWorker } from "@/lib/pwa/register"; @@ -141,6 +142,7 @@ function RootComponent() { + ); }