Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/SYSTEM_SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)` |
Expand Down
4 changes: 4 additions & 0 deletions docs/UI_SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
92 changes: 92 additions & 0 deletions e2e/search.spec.ts
Original file line number Diff line number Diff line change
@@ -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();
});
19 changes: 19 additions & 0 deletions src/components/search/SearchButton.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<Button
variant="ghost"
size="icon"
className={className}
aria-label="Search"
title="Search (Ctrl/⌘ K)"
onClick={() => setSearchOpen(true)}
>
<Search className="size-4" />
</Button>
);
}
32 changes: 32 additions & 0 deletions src/components/search/SearchHost.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<Suspense fallback={null}>
<SearchPalette />
</Suspense>
);
}
155 changes: 155 additions & 0 deletions src/components/search/SearchPalette.tsx
Original file line number Diff line number Diff line change
@@ -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<typeof draftEntries>[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<Draft[]>([]);
const list = useRef<HTMLDivElement>(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 (
<Dialog open onOpenChange={(open) => !open && close()}>
<DialogContent className="top-4 max-h-[calc(100dvh-2rem)] translate-y-0 gap-0 overflow-hidden p-0 sm:top-[12vh] sm:max-w-xl [&>button:last-child]:hidden">
<DialogTitle className="sr-only">Search</DialogTitle>
<DialogDescription className="sr-only">
Find drafts, words in drafts, commands, settings and pages.
</DialogDescription>
<div className="flex items-center gap-2 border-b border-border px-3">
<Search className="size-4 shrink-0 text-muted-foreground" aria-hidden />
<input
autoFocus
role="combobox"
aria-expanded
aria-controls="search-results"
aria-activedescendant={current ? `search-${current.id}` : undefined}
aria-label="Search"
placeholder="Search drafts, commands, settings…"
className="h-12 w-full bg-transparent text-base outline-none placeholder:text-muted-foreground sm:text-sm"
value={query}
onChange={(e) => 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);
}
}}
/>
</div>
<div
ref={list}
id="search-results"
role="listbox"
aria-label="Results"
className="max-h-[60dvh] overflow-y-auto p-1"
>
{!flat.length && (
<p className="px-3 py-6 text-center text-sm text-muted-foreground">
{query.trim() ? "Nothing found." : "Type to search."}
</p>
)}
{groups.map((g) => (
<div key={g.group} role="group" aria-label={g.group}>
<p className="px-3 pt-2 pb-1 text-xs font-medium text-muted-foreground">
{query.trim() || g.group !== "Drafts" ? g.group : "Recent drafts"}
</p>
{g.items.map((e) => {
index += 1;
const i = index;
return (
<div
key={e.id}
id={`search-${e.id}`}
data-index={i}
role="option"
aria-selected={e === current}
className="cursor-pointer rounded-md px-3 py-2 text-sm aria-selected:bg-accent aria-selected:text-accent-foreground"
onMouseMove={() => setActive(i)}
onClick={() => choose(e)}
>
<span className="block truncate">{e.title}</span>
{e.hint && (
<span className="block truncate text-xs text-muted-foreground">{e.hint}</span>
)}
</div>
);
})}
</div>
))}
</div>
<p className="hidden border-t border-border px-3 py-2 text-xs text-muted-foreground sm:block">
↑ ↓ to move · Enter to open · Esc to close
</p>
</DialogContent>
</Dialog>
);
}
2 changes: 2 additions & 0 deletions src/components/settings/SettingsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -38,6 +39,7 @@ export function SettingsPage({ tab, onTab }: { tab: string; onTab: (tab: Setting
<Button asChild variant="ghost" size="sm">
<Link to="/editor">Back to the editor</Link>
</Button>
<SearchButton />
<ThemeToggle />
</div>
</div>
Expand Down
Loading
Loading