@@ -1411,6 +1452,66 @@ export function Studio({ docId }: { docId: string }) {
setMobilePanel(null);
setTimeout(() => editor.current?.goToLine(line), 100);
};
+
+ /* ---------- search ---------- */
+ searchEntries.current = () => {
+ const cmd = (title: string, run: () => void, keywords = ""): SearchEntry => ({
+ id: `studio:${title}`,
+ group: "Commands",
+ title,
+ keywords,
+ run,
+ });
+ const open = (p: NonNullable
) => (overlay ? setMobilePanel(p) : setPanel(p));
+ const cloudDraft = !!doc && inCloud && !doc.shared;
+ return [
+ cmd("New draft", () => void newDoc(), "create add"),
+ cmd("Import files…", () => fileInput.current?.click(), "open upload markdown zip"),
+ cmd("Import a folder…", () => folderInput.current?.click(), "open upload directory"),
+ cmd("Download .md", downloadMd, "export markdown file save"),
+ cmd("Copy Markdown", copyMd, "export clipboard"),
+ cmd("Copy rendered HTML", copyHtml, "export clipboard"),
+ cmd("Download standalone .html", downloadHtml, "export html file"),
+ cmd("Download all drafts (.zip)", () => exportAsync(exportAll), "export archive backup"),
+ cmd("Show the editor only", () => setView("editor"), "view source"),
+ cmd("Show editor and preview", () => setView("split"), "view split side by side"),
+ cmd("Show the preview only", () => setView("preview"), "view rendered"),
+ cmd("Checks", () => open("checks"), "panel portability issues lint"),
+ cmd("Outline", () => open("outline"), "panel headings contents"),
+ cmd("Front matter", () => open("meta"), "panel metadata yaml"),
+ cmd("History", () => open("history"), "panel versions revisions"),
+ cmd(
+ "Drafts list",
+ () => (compact || focus ? setMobileLibrary(true) : setLibrary((v) => !v)),
+ "library sidebar folders",
+ ),
+ cmd("Focus mode", () => setFocus((f) => !f), "distraction free zen"),
+ cmd("Insert link", openLink, "url"),
+ cmd("Insert image", () => setImageDialog({ open: true, initialAlt: "" }), "picture"),
+ cmd("Insert table", () => setTableDialog(true), "grid"),
+ cmd("Save a version", () => void saveVersion(), "history snapshot"),
+ cmd("Writing check rules", () => setRulesOpen(true), "checker settings standards"),
+ cmd("AI integrations", () => setAiIntegrations(true), "provider model key"),
+ cmd("Keyboard shortcuts", () => setShortcuts(true), "keys hotkeys"),
+ ...(cloudDraft && doc
+ ? [
+ cmd("Share…", () => setShareTarget(doc), "link review publish"),
+ cmd("Edit together…", () => setCollabTarget(doc), "collaborate invite live"),
+ ...(githubPublish
+ ? [cmd("Publish to GitHub…", () => setPublishTarget(doc), "commit gist")]
+ : []),
+ ]
+ : []),
+ ...outline.map((h): SearchEntry => ({
+ id: `heading:${h.line}`,
+ group: "Headings",
+ title: h.text || "(empty heading)",
+ hint: `Line ${h.line}`,
+ run: () => goToLine(h.line),
+ })),
+ ];
+ };
+ jumpTo.current = goToLine;
const ownShare = doc ? shares.byDraft.get(doc.id) : undefined;
const startCompose = (kind: Composing["kind"]) => {
const snap = editor.current?.getSnapshot();
@@ -1677,20 +1778,10 @@ export function Studio({ docId }: { docId: string }) {
Markdown
- {
- warnLocalImages();
- download(`${fileBase()}.md`, out(), "text/markdown;charset=utf-8");
- }}
- >
+
Download .md
- {
- warnLocalImages();
- void copy(out(), "Markdown");
- }}
- >
+
Copy Markdown
HTML
-
- exportAsync(async () => {
- const { html } = await renderExportBody(out(true), profile, {});
- await copy(html, "HTML");
- })
- }
- >
+
Copy rendered HTML
-
- exportAsync(async () =>
- download(
- `${fileBase()}.html`,
- await standaloneDocument(doc?.title ?? "", out(true), profile, {}),
- "text/html;charset=utf-8",
- ),
- )
- }
- >
+
Download standalone .html
@@ -1786,6 +1860,7 @@ export function Studio({ docId }: { docId: string }) {
Publish
)}
+
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