From f0ad6eb2919f2075edb852f509c8d9b39ca3672e Mon Sep 17 00:00:00 2001 From: Chizoba Jude Ojini Date: Sat, 14 Nov 2026 14:03:34 +0000 Subject: [PATCH 01/12] fix(library): remove a folder when its last draft is deleted --- docs/SYSTEM_SPEC.md | 2 +- docs/UI_SPEC.md | 2 +- src/lib/storage/documentStore.test.ts | 26 ++++++++++++++++++++++++++ src/lib/storage/documentStore.ts | 4 ++++ 4 files changed, 32 insertions(+), 2 deletions(-) diff --git a/docs/SYSTEM_SPEC.md b/docs/SYSTEM_SPEC.md index 8b51d74..9232068 100644 --- a/docs/SYSTEM_SPEC.md +++ b/docs/SYSTEM_SPEC.md @@ -53,7 +53,7 @@ | **Writing Aids** | Word count, character count, estimated reading time, live heading outline/TOC with click-to-line | Done (M1) | | **AI Writing** | BYOK direct browser streaming (OpenAI, Anthropic, Google Gemini, OpenAI-compatible); title/description/tag suggestions; draft topic into new document | Done (M1) | | **PWA & Offline** | Installable manifest (standalone, maskable icons, a New draft shortcut) and an offline service worker (`public/sw.js`, see PWA and offline below). No app icon badge | Done | -| **Advanced Library** | Full-text draft search, tag filters (from front matter `tags`), one-level folders (a library label, created, dragged into and deleted from the sidebar; names live under the `meta:folders` key so an empty folder persists), bulk import and export as ZIP (see Import and export below) | Done | +| **Advanced Library** | Full-text draft search, tag filters (from front matter `tags`), one-level folders (a library label, created, dragged into and deleted from the sidebar; names live under the `meta:folders` key so an empty folder persists until its last draft is deleted, whichever device deletes it; moving a draft out leaves the folder), bulk import and export as ZIP (see Import and export below) | Done | | **Local History** | Automatic snapshots of each draft in IndexedDB (at most one every 5 minutes, up to 50 per draft, automatic ones dropped first), a manual "Save a version now", a side-by-side line diff against the current text, and one-click restore that first keeps the text it replaces | Done | | **Accounts** | Email + password / magic link, GitHub and Google OAuth | Milestone 3 | | **Cloud Sync** | Multi-device synchronization with versioned last-write-wins and automatic conflict forks | Milestone 3 | diff --git a/docs/UI_SPEC.md b/docs/UI_SPEC.md index a3d0147..a834574 100644 --- a/docs/UI_SPEC.md +++ b/docs/UI_SPEC.md @@ -67,7 +67,7 @@ For a draft in the cloud, on a server that can publish (`githubPublish` in `/api - **Top bar, row 1:** drafts toggle · wordmark link with the release (`v0.2.0`, from package.json; hidden below 640px) and current title · Import dropdown (files or a ZIP, or a folder) · Install (only when the browser offers to install the app) · AI writer · Export dropdown (including Download all drafts as a ZIP) · Account (sign in or create an account, with "Forgot your password?" when the server sends mail and a `/reset-password` page for the emailed link; optional; "Continue with Google" and "Continue with GitHub" when the server has them). Signed in, the menu has "Choose drafts for the cloud…" and "Manage images…" (when this server hosts images) and "Sign out"; the drafts list shows "Cloud: n of 5 drafts", a cloud icon on drafts stored in the account, and "Save to cloud" / "Remove from cloud" in each draft's menu. - **Top bar, row 2:** target-profile Select (GFM extended, Strict CommonMark, GFM without HTML, Wiki notes; remembered per device) · view toggle (Editor / Split / Preview) · panel buttons on mid-size screens. - **Export dropdown:** Download .md, Copy Markdown, Download self-contained .md and Copy self-contained Markdown (both enabled only when the draft has local images), Copy rendered HTML, Download standalone .html, and the "Normalize on export" switch. -- **Drafts sidebar:** New folder and New draft buttons, a search box, tag chips, and a folder tree. Search matches every word in a draft's title or text (a matching line is shown under the title); tag chips come from each draft's front matter `tags` and narrow the list when selected. Folders are labels kept in the library, not in the text: they list first (A to Z, collapsible, drafts indented beneath them with a guide line) and unfiled drafts follow. A draft moves by dragging it onto a folder, or onto the empty part of the list to take it out, and also from its three-dot menu (Rename, Move to folder, Duplicate, Delete), which is the route on touch screens. A folder's menu has Rename folder (an inline field with save and cancel; the drafts follow, and a name another folder already has is refused) and Delete folder: an empty one goes at once, one with drafts asks first because the drafts inside are deleted too. Delete opens a confirmation Dialog. +- **Drafts sidebar:** New folder and New draft buttons, a search box, tag chips, and a folder tree. Search matches every word in a draft's title or text (a matching line is shown under the title); tag chips come from each draft's front matter `tags` and narrow the list when selected. Folders are labels kept in the library, not in the text: they list first (A to Z, collapsible, drafts indented beneath them with a guide line) and unfiled drafts follow. A draft moves by dragging it onto a folder, or onto the empty part of the list to take it out, and also from its three-dot menu (Rename, Move to folder, Duplicate, Delete), which is the route on touch screens. A folder's menu has Rename folder (an inline field with save and cancel; the drafts follow, and a name another folder already has is refused) and Delete folder: an empty one goes at once, one with drafts asks first because the drafts inside are deleted too. A folder also goes when its last draft is deleted (here or on another device); moving the last draft out leaves it. Delete opens a confirmation Dialog. - **Formatting toolbar** (`role="toolbar"`, one tab stop, arrow keys / Home / End to move, Alt+F10 from the editor to enter it and Esc to leave; 17 buttons that wrap onto an extra row when the space runs out, never scroll: one row from 768px up (36px buttons), two rows on phones (40px touch targets)): undo, redo, **focus mode** (hides the side panels; `aria-pressed` while on; the drafts button in the top bar then opens the list as a panel from the left, closed by choosing a draft or Esc, with the cursor returned to the editor; the right-hand panel buttons stay too and open their panel from the right the same way, while the panel docked beside the editor is hidden and comes back as it was when focus mode ends; on phones the bottom panel bar stays as well) · heading style menu (Paragraph, H1-H6), bold, italic, strikethrough, inline code · link, image · quote, bulleted, numbered and task lists · code block menu, table menu, **Insert** menu. - Toggle tools show their state at the cursor (`aria-pressed`), and pressing one twice undoes it. diff --git a/src/lib/storage/documentStore.test.ts b/src/lib/storage/documentStore.test.ts index 04b9cea..d6245b5 100644 --- a/src/lib/storage/documentStore.test.ts +++ b/src/lib/storage/documentStore.test.ts @@ -87,6 +87,32 @@ describe("folders", () => { expect(await store.folders.list()).toEqual(["Notes"]); expect((await store.get(d.id))?.folder).toBe("Notes"); }); + it("drops a folder when its last draft is removed, and keeps it while others remain", async () => { + const store = createDocumentStore(memoryStore()); + await store.folders.add("Blog"); + const a = await store.create({ content: "a", folder: "Blog" }); + const b = await store.create({ content: "b", folder: "blog" }); + await store.remove(a.id); + expect(await store.folders.list()).toEqual(["Blog"]); + await store.remove(b.id); + expect(await store.folders.list()).toEqual([]); + }); + it("leaves other folders, loose drafts and never-filled folders alone", async () => { + const store = createDocumentStore(memoryStore()); + await store.folders.add("Empty"); + await store.folders.add("Other"); + await store.create({ content: "o", folder: "Other" }); + const loose = await store.create({ content: "l" }); + await store.remove(loose.id); + expect(await store.folders.list()).toEqual(["Empty", "Other"]); + }); + it("does not drop the folder when a draft is only moved out of it", async () => { + const store = createDocumentStore(memoryStore()); + await store.folders.add("Blog"); + const d = await store.create({ content: "a", folder: "Blog" }); + await store.save({ ...d, folder: undefined }); + expect(await store.folders.list()).toEqual(["Blog"]); + }); it("does not show up among the documents", async () => { const store = createDocumentStore(memoryStore()); await store.folders.add("Blog"); diff --git a/src/lib/storage/documentStore.ts b/src/lib/storage/documentStore.ts index a44bd43..5afb883 100644 --- a/src/lib/storage/documentStore.ts +++ b/src/lib/storage/documentStore.ts @@ -155,8 +155,12 @@ export function createDocumentStore(kv: KeyValueStore) { notify(opts.quiet); return doc; }, + /** Removing a folder's last draft removes the folder too (also when sync removes it). */ async remove(id: string, opts: { quiet?: boolean } = {}) { + const folder = (await kv.get(PREFIX + id))?.folder; await kv.del(PREFIX + id); + if (folder && !(await store.list()).some((d) => d.folder && byName(d.folder, folder) === 0)) + await store.folders.remove(folder); notify(opts.quiet); }, async create(partial: Partial = {}): Promise { From 3df8162ed30685304b99a4cb22ac61aacc841506 Mon Sep 17 00:00:00 2001 From: Chizoba Jude Ojini Date: Sat, 14 Nov 2026 15:24:51 +0000 Subject: [PATCH 02/12] feat(settings): add a settings page for the editor, AI and connections --- docs/SYSTEM_SPEC.md | 1 + docs/UI_SPEC.md | 4 + e2e/settings.spec.ts | 64 ++++++++++ src/components/settings/AccountSection.tsx | 25 ++++ src/components/settings/AiSection.tsx | 22 ++++ .../settings/ConnectionsSection.tsx | 77 ++++++++++++ src/components/settings/EditorSection.tsx | 115 ++++++++++++++++++ src/components/settings/SettingsPage.tsx | 75 ++++++++++++ src/components/settings/SettingsRow.tsx | 22 ++++ src/components/site/SiteFooter.tsx | 3 + src/components/site/SiteHeader.tsx | 8 +- src/components/studio/AccountMenu.tsx | 18 ++- src/lib/settings/prefs.test.ts | 29 +++++ src/lib/settings/prefs.ts | 15 +++ src/lib/settings/tabs.test.ts | 19 +++ src/lib/settings/tabs.ts | 14 +++ src/routeTree.gen.ts | 21 ++++ src/routes/settings.tsx | 23 ++++ 18 files changed, 553 insertions(+), 2 deletions(-) create mode 100644 e2e/settings.spec.ts create mode 100644 src/components/settings/AccountSection.tsx create mode 100644 src/components/settings/AiSection.tsx create mode 100644 src/components/settings/ConnectionsSection.tsx create mode 100644 src/components/settings/EditorSection.tsx create mode 100644 src/components/settings/SettingsPage.tsx create mode 100644 src/components/settings/SettingsRow.tsx create mode 100644 src/lib/settings/prefs.test.ts create mode 100644 src/lib/settings/prefs.ts create mode 100644 src/lib/settings/tabs.test.ts create mode 100644 src/lib/settings/tabs.ts create mode 100644 src/routes/settings.tsx diff --git a/docs/SYSTEM_SPEC.md b/docs/SYSTEM_SPEC.md index 9232068..8832d32 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/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)` | | `src/lib/editor/images.ts` | Client-side image handling, resizing, and compression. | `compressImage(file, maxDimension, quality)`, `safeImageName()`, `kb()` | diff --git a/docs/UI_SPEC.md b/docs/UI_SPEC.md index a834574..96db54f 100644 --- a/docs/UI_SPEC.md +++ b/docs/UI_SPEC.md @@ -118,6 +118,10 @@ Fields: title, slug, date, cover image URL, description, tags (comma separated). Only for an admin; anyone else sees the site's 404. Reached from "Admin dashboard" in the account menu. A header with the logo, "Back to the editor" and the theme button, and tabs (kept in the address, so a link opens one): **Overview** (cards of site totals), **Accounts** (a search box, a table of accounts with plan, cloud drafts, status badges and join date; opening one shows a dialog with Account controls (role, plan, suspended, email confirmed, Save account, Sign out everywhere, Delete account, each destructive one asking for a second press), Usage, "Limits for this account" (a number field or switch per limit, grouped as Storage and counts, Sharing and publishing, Rate limits, each saying where its value comes from, with Reset and Save limits) and Content (cloud drafts, share links and images by title and size, each with a two-press Remove)), **Plans** (list, New plan form with name, label and the same limit controls), **Server** (a switch for new accounts, a site notice, and default limits for every account), **Audit log** (who did what to whom, newest first). The site notice, when set, shows as a banner above the editor. +## 6b. Settings: `/settings` + +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** (who is signed in: picture, name, address and whether it is confirmed; signed in only), **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. + ## 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/settings.spec.ts b/e2e/settings.spec.ts new file mode 100644 index 0000000..d507dfd --- /dev/null +++ b/e2e/settings.spec.ts @@ -0,0 +1,64 @@ +import { expect, test } from "@playwright/test"; +import { startDraft } from "./draft"; +import { account, skipPicker } from "./sync-helpers"; + +const unique = () => `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; + +test("signed out, the settings page offers the editor and AI sections and keeps a choice", async ({ + page, +}) => { + await page.goto("/settings"); + await expect(page.getByRole("tab", { name: "Editor" })).toBeVisible(); + await expect(page.getByRole("tab", { name: "AI" })).toBeVisible(); + await expect(page.getByRole("tab", { name: "Account" })).toHaveCount(0); + + await page.getByLabel("Target platform").selectOption("commonmark"); + await page.getByRole("switch", { name: "Normalize on export" }).click(); + await page.reload(); + await expect(page.getByLabel("Target platform")).toHaveValue("commonmark"); + await expect(page.getByRole("switch", { name: "Normalize on export" })).toBeChecked(); + + // a signed-in section is not reachable by address either + await page.goto("/settings?tab=account"); + await expect(page.getByRole("tab", { name: "Editor", selected: true })).toBeVisible(); +}); + +test("the account menu opens settings, which show the account and its connections", async ({ + page, +}) => { + const address = `settings-${unique()}@example.com`; + await account(page, "Create account", address); + await skipPicker(page); + await page.getByRole("button", { name: /^Account:/ }).click(); + await page.getByRole("menuitem", { name: "Account", exact: true }).click(); + + await expect(page).toHaveURL(/\/settings\?tab=account/); + await expect(page.getByRole("tab", { name: "Account", selected: true })).toBeVisible(); + await expect(page.getByRole("region", { name: "Account" })).toContainText(address); + + await page.getByRole("tab", { name: "Connections" }).click(); + await expect(page).toHaveURL(/tab=connections/); + await page.getByRole("button", { name: "Choose drafts…" }).click(); + await expect(page.getByRole("dialog")).toBeVisible(); +}); + +test("the settings page is reachable from the editor and the public pages without signing in", async ({ + page, +}) => { + await startDraft(page); + await page.getByRole("link", { name: "Settings", exact: true }).click(); + await expect(page).toHaveURL(/\/settings/); + await expect(page.getByRole("tab", { name: "Editor", selected: true })).toBeVisible(); + + await page.goto("/guides"); + await page.getByRole("link", { name: "Settings", exact: true }).first().click(); + await expect(page).toHaveURL(/\/settings/); +}); + +test("the account menu has a Settings item that opens the editor section", async ({ page }) => { + await account(page, "Create account", `settings-${unique()}@example.com`); + await skipPicker(page); + await page.getByRole("button", { name: /^Account:/ }).click(); + await page.getByRole("menuitem", { name: "Settings", exact: true }).click(); + await expect(page.getByRole("tab", { name: "Editor", selected: true })).toBeVisible(); +}); diff --git a/src/components/settings/AccountSection.tsx b/src/components/settings/AccountSection.tsx new file mode 100644 index 0000000..42d7ddf --- /dev/null +++ b/src/components/settings/AccountSection.tsx @@ -0,0 +1,25 @@ +import { Avatar } from "@/components/ui/avatar"; +import type { AccountUser } from "@/lib/account/client"; +import { SettingsRow } from "./SettingsRow"; + +/** Who is signed in. Changing the name, password, sign-ins and address comes with the account API. */ +export function AccountSection({ user }: { user: AccountUser }) { + const label = user.displayName || user.email; + return ( +
+
+ +
+

{label}

+

{user.email}

+
+
+ + {user.email} + +
+ ); +} diff --git a/src/components/settings/AiSection.tsx b/src/components/settings/AiSection.tsx new file mode 100644 index 0000000..5074acb --- /dev/null +++ b/src/components/settings/AiSection.tsx @@ -0,0 +1,22 @@ +import { useState } from "react"; +import { Button } from "@/components/ui/button"; +import { AiIntegrationsDialog } from "@/components/studio/AiIntegrationsDialog"; +import { SettingsRow } from "./SettingsRow"; + +/** The AI providers the writer uses. Keys stay in this browser's session, never on a server. */ +export function AiSection() { + const [open, setOpen] = useState(false); + return ( +
+ + + + +
+ ); +} diff --git a/src/components/settings/ConnectionsSection.tsx b/src/components/settings/ConnectionsSection.tsx new file mode 100644 index 0000000..87a6aa1 --- /dev/null +++ b/src/components/settings/ConnectionsSection.tsx @@ -0,0 +1,77 @@ +import { useEffect, useState } from "react"; +import { toast } from "sonner"; +import { Button } from "@/components/ui/button"; +import { ChooseCloudDrafts } from "@/components/studio/CloudDialogs"; +import { ManageImages } from "@/components/studio/ManageImages"; +import { useAccount } from "@/lib/account/store"; +import { type GithubStatus, connectUrl, githubApi } from "@/lib/github/api"; +import { useCloud } from "@/lib/sync/hooks"; +import { SettingsRow } from "./SettingsRow"; + +/** What the account reaches beyond this device: cloud drafts, hosted images, GitHub. */ +export function ConnectionsSection({ userId }: { userId: string }) { + const account = useAccount(); + const cloud = useCloud(); + const [picker, setPicker] = useState(false); + const [images, setImages] = useState(false); + const [github, setGithub] = useState(null); + useEffect(() => { + if (account.githubPublish) githubApi.status().then(setGithub, () => setGithub(null)); + }, [account.githubPublish]); + + return ( +
+ + + + {account.images && ( + + + + )} + {account.githubPublish && ( + + {github?.connected ? ( + + ) : ( + github?.available && ( + + ) + )} + + )} + + +
+ ); +} diff --git a/src/components/settings/EditorSection.tsx b/src/components/settings/EditorSection.tsx new file mode 100644 index 0000000..7cef636 --- /dev/null +++ b/src/components/settings/EditorSection.tsx @@ -0,0 +1,115 @@ +import { useEffect, useRef, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Switch } from "@/components/ui/switch"; +import { PROFILES, type Profile } from "@/lib/markdown/profiles"; +import { DEFAULT_CONFIG } from "@/lib/checker/config"; +import { loadConfig, saveConfig } from "@/lib/checker/storage"; +import { type Theme, setTheme } from "@/lib/ui/theme"; +import { useThemeChoice } from "@/lib/ui/useThemeChoice"; +import { loadPrefs, savePrefs } from "@/lib/settings/prefs"; +import { RulesDialog } from "@/components/studio/RulesDialog"; +import { ShortcutsDialog } from "@/components/studio/ShortcutsDialog"; +import { SettingsRow } from "./SettingsRow"; + +const THEMES: { id: Theme; label: string }[] = [ + { id: "system", label: "System" }, + { id: "light", label: "Light" }, + { id: "dark", label: "Dark" }, +]; + +/** Looks and writing choices. All of it is kept on this device, so it works without an account. */ +export function EditorSection() { + const theme = useThemeChoice(); + const [prefs, setPrefs] = useState(() => ({ + profile: "gfm-extended" as Profile, + normalize: false, + })); + const [config, setConfig] = useState(DEFAULT_CONFIG); + const [rules, setRules] = useState(false); + const [keys, setKeys] = useState(false); + const back = useRef(null); + // read after mount: the server render has no localStorage + useEffect(() => { + setPrefs(loadPrefs()); + setConfig(loadConfig()); + }, []); + const change = (next: Partial) => { + const merged = { ...prefs, ...next }; + setPrefs(merged); + savePrefs(merged); + }; + + return ( +
+ +
+ {THEMES.map((t) => ( + + ))} +
+
+ p.id === prefs.profile)?.hint} + > + + + + change({ normalize: on })} + /> + + + + + + + + { + setConfig(next); + saveConfig(next); + }} + /> + back.current?.focus()} + /> +
+ ); +} diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx new file mode 100644 index 0000000..e9270e0 --- /dev/null +++ b/src/components/settings/SettingsPage.tsx @@ -0,0 +1,75 @@ +import { useEffect } from "react"; +import { Link } from "@tanstack/react-router"; +import { Logo } from "@/components/Logo"; +import { ThemeToggle } from "@/components/ThemeToggle"; +import { Button } from "@/components/ui/button"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { accountStore, useAccount } from "@/lib/account/store"; +import { type SettingsTab, parseSettingsTab, visibleTabs } from "@/lib/settings/tabs"; +import { AccountSection } from "./AccountSection"; +import { AiSection } from "./AiSection"; +import { ConnectionsSection } from "./ConnectionsSection"; +import { EditorSection } from "./EditorSection"; + +const LABEL: Record = { + account: "Account", + editor: "Editor", + ai: "AI", + connections: "Connections", +}; + +/** Everything that can be set, in one place. Sections that need an account only show with one. */ +export function SettingsPage({ tab, onTab }: { tab: string; onTab: (tab: SettingsTab) => void }) { + const account = useAccount(); + // this page asks who is signed in itself, like the dashboard + useEffect(() => void accountStore.refresh(), []); + if (!account.loaded) return
Loading…
; + const user = account.user; + const current = parseSettingsTab(tab, !!user); + return ( +
+
+
+ + + + Settings +
+ + +
+
+
+
+

Settings

+ onTab(v as SettingsTab)}> + + {visibleTabs(!!user).map((t) => ( + + {LABEL[t]} + + ))} + + {user && ( + + + + )} + + + + + + + {user && ( + + + + )} + +
+
+ ); +} diff --git a/src/components/settings/SettingsRow.tsx b/src/components/settings/SettingsRow.tsx new file mode 100644 index 0000000..184efc3 --- /dev/null +++ b/src/components/settings/SettingsRow.tsx @@ -0,0 +1,22 @@ +import type { ReactNode } from "react"; + +/** One setting: what it is on the left, its control on the right. */ +export function SettingsRow({ + title, + description, + children, +}: { + title: string; + description?: ReactNode; + children: ReactNode; +}) { + return ( +
+
+

{title}

+ {description &&

{description}

} +
+
{children}
+
+ ); +} diff --git a/src/components/site/SiteFooter.tsx b/src/components/site/SiteFooter.tsx index c023553..c0b6365 100644 --- a/src/components/site/SiteFooter.tsx +++ b/src/components/site/SiteFooter.tsx @@ -15,6 +15,9 @@ export function SiteFooter() { Guides + + Settings + Privacy diff --git a/src/components/site/SiteHeader.tsx b/src/components/site/SiteHeader.tsx index 15c13d8..724ae3d 100644 --- a/src/components/site/SiteHeader.tsx +++ b/src/components/site/SiteHeader.tsx @@ -1,4 +1,5 @@ -import { ArrowUpRight, Github } from "lucide-react"; +import { Link } from "@tanstack/react-router"; +import { ArrowUpRight, Github, Settings } from "lucide-react"; import { Logo } from "@/components/Logo"; import { ThemeToggle } from "@/components/ThemeToggle"; import { Button } from "@/components/ui/button"; @@ -15,6 +16,11 @@ export function SiteHeader() { />
+
+ {user.email} + ); } + +function NameForm({ name }: { name: string }) { + const [value, setValue] = useState(name); + const [busy, setBusy] = useState(false); + async function save(e: FormEvent) { + e.preventDefault(); + setBusy(true); + const r = await updateDisplayName(value); + setBusy(false); + if ("error" in r) return void toast.error(r.error); + await accountStore.refresh(); + toast.success("Name saved"); + } + return ( +
+ +

+ Shown to people you edit with and in comments. Leave empty to show your email address. +

+
+ setValue(e.target.value)} + /> + +
+
+ ); +} + +function PasswordForm({ hasPassword }: { hasPassword: boolean }) { + const [current, setCurrent] = useState(""); + const [next, setNext] = useState(""); + const [busy, setBusy] = useState(false); + async function save(e: FormEvent) { + e.preventDefault(); + setBusy(true); + const r = await changePassword(next, hasPassword ? current : undefined); + setBusy(false); + if ("error" in r) return void toast.error(r.error); + setCurrent(""); + setNext(""); + await accountStore.refresh(); + toast.success(hasPassword ? "Password changed" : "Password set", { + description: "Your other devices were signed out.", + }); + } + return ( +
+

{hasPassword ? "Change password" : "Set a password"}

+

+ {hasPassword + ? "Your other devices are signed out when it changes." + : "You sign in with GitHub or Google. A password lets you sign in with your email too."} +

+
+ {hasPassword && ( + <> + + setCurrent(e.target.value)} + /> + + )} + + setNext(e.target.value)} + /> + +
+
+ ); +} diff --git a/src/lib/account/client.ts b/src/lib/account/client.ts index 9df8801..a759590 100644 --- a/src/lib/account/client.ts +++ b/src/lib/account/client.ts @@ -10,6 +10,8 @@ export type AccountUser = { isAdmin?: boolean; /** The picture of a Google or GitHub account, when there is one. */ avatarUrl?: string | null; + /** False for an account that signs in only with GitHub or Google (it may set a password). */ + hasPassword?: boolean; }; export type Account = { user: AccountUser | null; @@ -49,6 +51,9 @@ const MESSAGES: Record = { no_verified_email: "That account has no verified email address, so it can't be used to sign in.", email_in_use: "That email is already being used by another sign-in. Try again.", suspended: "This account has been suspended.", + wrong_password: "That isn't your current password.", + same: "Choose a password different from the current one.", + unauthorized: "You were signed out. Sign in again.", signups_closed: "New accounts aren't being created right now.", }; @@ -208,3 +213,34 @@ export async function submitPasswordReset( return { error: "Can't reach the server. Check your connection and try again." }; } } + +const send = async (path: string, method: string, data: unknown) => { + try { + const res = await fetch(path, { + method, + headers: { "content-type": "application/json" }, + body: JSON.stringify(data), + }); + const body = (await res.json()) as { error?: string; retryAfter?: number } & Record< + string, + unknown + >; + if (res.ok) return body; + const wait = body.retryAfter ? ` Try again in ${Math.ceil(body.retryAfter / 60)} min.` : ""; + return { error: authMessage(body.error ?? "") + (body.error === "rate_limited" ? wait : "") }; + } catch { + return { error: "Can't reach the server. Check your connection and try again." }; + } +}; + +/** Changes the name other people see; an empty name goes back to showing the address. */ +export async function updateDisplayName(displayName: string) { + const r = await send("/api/auth/profile", "PATCH", { displayName }); + return "error" in r ? { error: String(r.error) } : { ok: true as const }; +} + +/** Changes the password, or sets one for an account that has none. Other devices are signed out. */ +export async function changePassword(next: string, current?: string) { + const r = await send("/api/auth/password", "POST", { next, ...(current && { current }) }); + return "error" in r ? { error: String(r.error) } : { ok: true as const }; +} diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.ts index f8c42d8..3787729 100644 --- a/src/routeTree.gen.ts +++ b/src/routeTree.gen.ts @@ -41,6 +41,8 @@ import { Route as ApiAuthGoogleRouteImport } from './routes/api/auth/google' import { Route as ApiAuthLoginRouteImport } from './routes/api/auth/login' import { Route as ApiAuthLogoutRouteImport } from './routes/api/auth/logout' import { Route as ApiAuthMeRouteImport } from './routes/api/auth/me' +import { Route as ApiAuthPasswordRouteImport } from './routes/api/auth/password' +import { Route as ApiAuthProfileRouteImport } from './routes/api/auth/profile' import { Route as ApiAuthResetRouteImport } from './routes/api/auth/reset' import { Route as ApiAuthSignupRouteImport } from './routes/api/auth/signup' import { Route as ApiAuthVerifyRouteImport } from './routes/api/auth/verify' @@ -237,6 +239,16 @@ const ApiAuthMeRoute = ApiAuthMeRouteImport.update({ path: '/api/auth/me', getParentRoute: () => rootRouteImport, } as any) +const ApiAuthPasswordRoute = ApiAuthPasswordRouteImport.update({ + id: '/api/auth/password', + path: '/api/auth/password', + getParentRoute: () => rootRouteImport, +} as any) +const ApiAuthProfileRoute = ApiAuthProfileRouteImport.update({ + id: '/api/auth/profile', + path: '/api/auth/profile', + getParentRoute: () => rootRouteImport, +} as any) const ApiAuthResetRoute = ApiAuthResetRouteImport.update({ id: '/api/auth/reset', path: '/api/auth/reset', @@ -453,6 +465,8 @@ export interface FileRoutesByFullPath { '/api/auth/login': typeof ApiAuthLoginRoute '/api/auth/logout': typeof ApiAuthLogoutRoute '/api/auth/me': typeof ApiAuthMeRoute + '/api/auth/password': typeof ApiAuthPasswordRoute + '/api/auth/profile': typeof ApiAuthProfileRoute '/api/auth/reset': typeof ApiAuthResetRoute '/api/auth/signup': typeof ApiAuthSignupRoute '/api/auth/verify': typeof ApiAuthVerifyRouteWithChildren @@ -522,6 +536,8 @@ export interface FileRoutesByTo { '/api/auth/login': typeof ApiAuthLoginRoute '/api/auth/logout': typeof ApiAuthLogoutRoute '/api/auth/me': typeof ApiAuthMeRoute + '/api/auth/password': typeof ApiAuthPasswordRoute + '/api/auth/profile': typeof ApiAuthProfileRoute '/api/auth/reset': typeof ApiAuthResetRoute '/api/auth/signup': typeof ApiAuthSignupRoute '/api/auth/verify': typeof ApiAuthVerifyRouteWithChildren @@ -592,6 +608,8 @@ export interface FileRoutesById { '/api/auth/login': typeof ApiAuthLoginRoute '/api/auth/logout': typeof ApiAuthLogoutRoute '/api/auth/me': typeof ApiAuthMeRoute + '/api/auth/password': typeof ApiAuthPasswordRoute + '/api/auth/profile': typeof ApiAuthProfileRoute '/api/auth/reset': typeof ApiAuthResetRoute '/api/auth/signup': typeof ApiAuthSignupRoute '/api/auth/verify': typeof ApiAuthVerifyRouteWithChildren @@ -663,6 +681,8 @@ export interface FileRouteTypes { | '/api/auth/login' | '/api/auth/logout' | '/api/auth/me' + | '/api/auth/password' + | '/api/auth/profile' | '/api/auth/reset' | '/api/auth/signup' | '/api/auth/verify' @@ -732,6 +752,8 @@ export interface FileRouteTypes { | '/api/auth/login' | '/api/auth/logout' | '/api/auth/me' + | '/api/auth/password' + | '/api/auth/profile' | '/api/auth/reset' | '/api/auth/signup' | '/api/auth/verify' @@ -801,6 +823,8 @@ export interface FileRouteTypes { | '/api/auth/login' | '/api/auth/logout' | '/api/auth/me' + | '/api/auth/password' + | '/api/auth/profile' | '/api/auth/reset' | '/api/auth/signup' | '/api/auth/verify' @@ -870,6 +894,8 @@ export interface RootRouteChildren { ApiAuthLoginRoute: typeof ApiAuthLoginRoute ApiAuthLogoutRoute: typeof ApiAuthLogoutRoute ApiAuthMeRoute: typeof ApiAuthMeRoute + ApiAuthPasswordRoute: typeof ApiAuthPasswordRoute + ApiAuthProfileRoute: typeof ApiAuthProfileRoute ApiAuthResetRoute: typeof ApiAuthResetRoute ApiAuthSignupRoute: typeof ApiAuthSignupRoute ApiAuthVerifyRoute: typeof ApiAuthVerifyRouteWithChildren @@ -1110,6 +1136,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiAuthMeRouteImport parentRoute: typeof rootRouteImport } + '/api/auth/password': { + id: '/api/auth/password' + path: '/api/auth/password' + fullPath: '/api/auth/password' + preLoaderRoute: typeof ApiAuthPasswordRouteImport + parentRoute: typeof rootRouteImport + } + '/api/auth/profile': { + id: '/api/auth/profile' + path: '/api/auth/profile' + fullPath: '/api/auth/profile' + preLoaderRoute: typeof ApiAuthProfileRouteImport + parentRoute: typeof rootRouteImport + } '/api/auth/reset': { id: '/api/auth/reset' path: '/api/auth/reset' @@ -1625,6 +1665,8 @@ const rootRouteChildren: RootRouteChildren = { ApiAuthLoginRoute: ApiAuthLoginRoute, ApiAuthLogoutRoute: ApiAuthLogoutRoute, ApiAuthMeRoute: ApiAuthMeRoute, + ApiAuthPasswordRoute: ApiAuthPasswordRoute, + ApiAuthProfileRoute: ApiAuthProfileRoute, ApiAuthResetRoute: ApiAuthResetRoute, ApiAuthSignupRoute: ApiAuthSignupRoute, ApiAuthVerifyRoute: ApiAuthVerifyRouteWithChildren, diff --git a/src/routes/api/auth/password.ts b/src/routes/api/auth/password.ts new file mode 100644 index 0000000..ff9eeda --- /dev/null +++ b/src/routes/api/auth/password.ts @@ -0,0 +1,9 @@ +import { createFileRoute } from "@tanstack/react-router"; + +export const Route = createFileRoute("/api/auth/password")({ + server: { + handlers: { + POST: async ({ request }) => (await import("@/server/auth/routes")).passwordHandler(request), + }, + }, +}); diff --git a/src/routes/api/auth/profile.ts b/src/routes/api/auth/profile.ts new file mode 100644 index 0000000..d0413f2 --- /dev/null +++ b/src/routes/api/auth/profile.ts @@ -0,0 +1,9 @@ +import { createFileRoute } from "@tanstack/react-router"; + +export const Route = createFileRoute("/api/auth/profile")({ + server: { + handlers: { + PATCH: async ({ request }) => (await import("@/server/auth/routes")).profileHandler(request), + }, + }, +}); diff --git a/src/server/auth/profile.test.ts b/src/server/auth/profile.test.ts new file mode 100644 index 0000000..7c70311 --- /dev/null +++ b/src/server/auth/profile.test.ts @@ -0,0 +1,88 @@ +// @vitest-environment node +import { eq } from "drizzle-orm"; +import { beforeEach, describe, expect, it } from "vitest"; +import { createNodeDb } from "../../../infra/db/node"; +import { emailTokens, sessions, users } from "../../../infra/db/schema"; +import type { Db } from "../db"; +import { changePassword, updateProfile } from "./profile"; +import { issueReset } from "./reset"; +import { login, signup, startSession, userForToken } from "./service"; + +let db: Db; +let user: { id: string; email: string }; +let token: string; +const now = 1_700_000_000_000; +const creds = { email: "ada@example.com", password: "the first long password" }; +const next = "a brand new long password"; + +beforeEach(async () => { + db = createNodeDb(":memory:") as unknown as Db; + const r = await signup(db, creds, now, { verifyByEmail: false }); + if ("error" in r) throw new Error(r.error); + user = r.user; + token = r.token; +}); + +describe("updateProfile", () => { + it("sets the display name, trimmed, and shows it in the session's user", async () => { + const r = await updateProfile(db, user.id, { displayName: " Ada L. " }, now); + expect(r).toMatchObject({ ok: true, user: { displayName: "Ada L." } }); + expect((await userForToken(db, token, now))?.user.displayName).toBe("Ada L."); + }); + it("clears the name when it is empty, and refuses a name that is too long", async () => { + await updateProfile(db, user.id, { displayName: "Ada" }, now); + expect(await updateProfile(db, user.id, { displayName: " " }, now)).toMatchObject({ + ok: true, + user: { displayName: null }, + }); + expect(await updateProfile(db, user.id, { displayName: "x".repeat(61) }, now)).toEqual({ + ok: false, + error: "invalid", + }); + expect(await updateProfile(db, user.id, {}, now)).toEqual({ ok: false, error: "invalid" }); + }); +}); + +describe("changePassword", () => { + it("needs the current password, then signs in with the new one only", async () => { + expect(await changePassword(db, user.id, token, { current: "wrong password!!", next })).toEqual( + { ok: false, error: "wrong_password" }, + ); + expect(await changePassword(db, user.id, token, { next })).toEqual({ + ok: false, + error: "wrong_password", + }); + expect( + await changePassword(db, user.id, token, { current: creds.password, next }, now), + ).toEqual({ ok: true }); + expect(await login(db, { email: creds.email, password: next }, now)).toHaveProperty("token"); + expect(await login(db, creds, now)).toEqual({ error: "invalid_credentials" }); + }); + it("keeps this session and ends the account's others, and its reset links", async () => { + const other = await startSession(db, { ...(await userForToken(db, token, now))!.user }, now); + await issueReset(db, user, now); + await changePassword(db, user.id, token, { current: creds.password, next }, now); + expect(await userForToken(db, token, now)).not.toBeNull(); + expect(await userForToken(db, other.token, now)).toBeNull(); + expect(await db.select().from(emailTokens).where(eq(emailTokens.userId, user.id))).toEqual([]); + }); + it("turns away a weak or unchanged password without touching anything", async () => { + const same = { current: creds.password, next: creds.password }; + expect(await changePassword(db, user.id, token, same)).toEqual({ ok: false, error: "same" }); + expect( + await changePassword(db, user.id, token, { current: creds.password, next: "short" }), + ).toEqual({ ok: false, error: "invalid" }); + expect(await login(db, creds, now)).toHaveProperty("token"); + }); + it("lets an account with no password (a social sign-in) set one without a current one", async () => { + await db.update(users).set({ passwordHash: null }).where(eq(users.id, user.id)); + expect(await changePassword(db, user.id, token, { next }, now)).toEqual({ ok: true }); + expect(await login(db, { email: creds.email, password: next }, now)).toHaveProperty("token"); + expect((await db.select().from(sessions)).length).toBeGreaterThan(0); + }); + it("says whether the account has a password", async () => { + expect((await userForToken(db, token, now))?.user.hasPassword).toBe(true); + await db.update(users).set({ passwordHash: null }).where(eq(users.id, user.id)); + expect((await userForToken(db, token, now))?.user.hasPassword).toBe(false); + }); +}); diff --git a/src/server/auth/profile.ts b/src/server/auth/profile.ts new file mode 100644 index 0000000..f7c08e5 --- /dev/null +++ b/src/server/auth/profile.ts @@ -0,0 +1,64 @@ +// What a signed-in person changes about their own account: the name shown to others, and the +// password. (The address and the linked sign-ins have their own files.) +import { and, eq, ne } from "drizzle-orm"; +import { z } from "zod"; +import { emailTokens, sessions, users } from "../../../infra/db/schema"; +import type { Db } from "../db"; +import { hashPassword, verifyPassword } from "./password"; +import type { PublicUser } from "./service"; +import { sha256Hex } from "./tokens"; + +const Profile = z.object({ displayName: z.string().trim().max(60) }); +const NewPassword = z.string().min(10).max(200); + +export async function updateProfile( + db: Db, + userId: string, + input: unknown, + now = Date.now(), +): Promise<{ ok: true; user: Pick } | { ok: false; error: "invalid" }> { + const parsed = Profile.safeParse(input); + if (!parsed.success) return { ok: false, error: "invalid" }; + const displayName = parsed.data.displayName || null; + await db.update(users).set({ displayName, updatedAt: now }).where(eq(users.id, userId)); + return { ok: true, user: { displayName } }; +} + +/** + * Sets a new password. An account that has one must give the current one (a stolen session alone + * cannot change it); one that signs in only with GitHub or Google has none and may just set one. + * Every other session of the account ends and its reset links stop working; this one stays. + */ +export async function changePassword( + db: Db, + userId: string, + sessionToken: string, + input: { current?: string; next: string }, + now = Date.now(), +): Promise<{ ok: true } | { ok: false; error: "wrong_password" | "invalid" | "same" }> { + const [row] = await db.select().from(users).where(eq(users.id, userId)); + if (!row) return { ok: false, error: "invalid" }; + if (row.passwordHash) { + if (!input.current || !(await verifyPassword(input.current, row.passwordHash))) + return { ok: false, error: "wrong_password" }; + if (input.current === input.next) return { ok: false, error: "same" }; + } + const parsed = NewPassword.safeParse(input.next); + if (!parsed.success) return { ok: false, error: "invalid" }; + await db + .update(users) + .set({ passwordHash: await hashPassword(parsed.data), updatedAt: now }) + .where(eq(users.id, userId)); + + await Promise.all([ + db + .delete(emailTokens) + .where(and(eq(emailTokens.userId, userId), eq(emailTokens.purpose, "reset"))), + db + .delete(sessions) + .where( + and(eq(sessions.userId, userId), ne(sessions.tokenHash, await sha256Hex(sessionToken))), + ), + ]); + return { ok: true }; +} diff --git a/src/server/auth/routes.ts b/src/server/auth/routes.ts index 74cc4c7..c4e1b7b 100644 --- a/src/server/auth/routes.ts +++ b/src/server/auth/routes.ts @@ -23,6 +23,7 @@ import { SESSION_MS, login, logout, signup, userForToken } from "./service"; import { verifyTurnstile } from "./turnstile"; import { confirmVerification, hasLiveVerification, sendVerification } from "./verify"; import { withUser } from "./guard"; +import { changePassword, updateProfile } from "./profile"; const json = (body: unknown, status = 200, headers?: HeadersInit) => Response.json(body, { status, headers: { "cache-control": "no-store", ...headers } }); @@ -221,6 +222,43 @@ export const resendHandler = (request: Request) => return json({ ok: true, sent: true }); }); +/** `PATCH { displayName }`: the name other people see (cursors, comments, who shared a draft). */ +export const profileHandler = (request: Request) => + withUser(request, async (user, db) => { + if (!sameOrigin(request)) return json({ error: "forbidden" }, 403); + const result = await updateProfile(db, user.id, await body(request)); + return result.ok ? json({ user: result.user }) : json({ error: result.error }, 400); + }); + +/** + * `POST { current?, next }`: changes the password, or sets one for an account that signs in only + * with GitHub or Google. Wrong guesses of the current one are limited per account (a stolen + * session cannot be used to try passwords). Other devices are signed out; this one stays. + */ +export const passwordHandler = (request: Request) => + withUser(request, async (user, db) => { + if (!sameOrigin(request)) return json({ error: "forbidden" }, 403); + const token = readToken(request); + const input = (await body(request)) as { current?: unknown; next?: unknown } | null; + if (!token || typeof input?.next !== "string") return json({ error: "invalid" }, 400); + const key = `password:${user.id}`; + const max = limit(request, "LOGIN_FAIL_LIMIT", 10); + const wait = await lockedOut(db, key, max); + if (wait !== null) return tooMany(wait); + const result = await changePassword(db, user.id, token, { + next: input.next, + ...(typeof input.current === "string" && { current: input.current }), + }); + if (!result.ok) { + if (result.error === "wrong_password") await hit(db, key, max, FAIL_WINDOW); + return json({ error: result.error }, result.error === "wrong_password" ? 401 : 400); + } + await clearLimit(db, key); + // the other devices' sockets close with their sessions; this browser's reconnects at once + await endSessions(request, user.id, "signed_out"); + return json({ ok: true }); + }); + export async function logoutHandler(request: Request) { if (!sameOrigin(request)) return json({ error: "forbidden" }, 403); const token = readToken(request); diff --git a/src/server/auth/service.ts b/src/server/auth/service.ts index 5f16a8c..babb98d 100644 --- a/src/server/auth/service.ts +++ b/src/server/auth/service.ts @@ -26,6 +26,8 @@ export type PublicUser = { isAdmin: boolean; /** The picture a social sign-in brought, shown in the account menu. */ avatarUrl?: string | null; + /** False for an account that only signs in with GitHub or Google (it may set a password). */ + hasPassword?: boolean; }; type Signed = { user: PublicUser; token: string }; @@ -47,6 +49,7 @@ const publicUser = (u: { emailVerifiedAt: number | null; role?: string; avatarUrl?: string | null; + passwordHash?: string | null; }): PublicUser => ({ id: u.id, email: u.email, @@ -54,6 +57,7 @@ const publicUser = (u: { emailVerified: u.emailVerifiedAt !== null, isAdmin: u.role === "admin", avatarUrl: u.avatarUrl ?? null, + ...(u.passwordHash !== undefined && { hasPassword: u.passwordHash !== null }), }); /** The role a new account gets: admin when it is the very first account, in one statement so two sign-ups cannot both win. */ @@ -106,7 +110,7 @@ export async function signup( return { error: "email_taken" }; } const [made] = await db.select({ role: users.role }).from(users).where(eq(users.id, user.id)); - return startSession(db, publicUser({ ...user, role: made?.role ?? "user" }), now); + return startSession(db, publicUser({ ...user, passwordHash, role: made?.role ?? "user" }), now); } // Verified against this when the email is unknown, so both failures take the same time. @@ -165,6 +169,7 @@ export async function userForToken( email: users.email, displayName: users.displayName, avatarUrl: users.avatarUrl, + passwordHash: users.passwordHash, emailVerifiedAt: users.emailVerifiedAt, role: users.role, suspendedAt: users.suspendedAt, From cbc51fd01a8a9935eabce5e2a6901ea4172590d3 Mon Sep 17 00:00:00 2001 From: Chizoba Jude Ojini Date: Sat, 14 Nov 2026 16:13:22 +0000 Subject: [PATCH 04/12] feat(settings): edit the name and password in dialogs and centre the page --- docs/UI_SPEC.md | 2 +- e2e/settings.spec.ts | 37 ++- src/components/settings/AccountSection.tsx | 228 ++++++++++++------ src/components/settings/AiSection.tsx | 2 +- .../settings/ConnectionsSection.tsx | 2 +- src/components/settings/EditorSection.tsx | 2 +- src/components/settings/SettingsPage.tsx | 2 +- 7 files changed, 189 insertions(+), 86 deletions(-) diff --git a/docs/UI_SPEC.md b/docs/UI_SPEC.md index eb728f4..aae4d1e 100644 --- a/docs/UI_SPEC.md +++ b/docs/UI_SPEC.md @@ -120,7 +120,7 @@ Only for an admin; anyone else sees the site's 404. Reached from "Admin dashboar ## 6b. Settings: `/settings` -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; a Display name field; Change password with the current one, or Set a password for an account that signs in with GitHub or Google; changing it signs the other devices out), **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. +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 and Password rows, each with an Edit button that opens a dialog: the name field, 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). 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. ## 7. Small screens — `06_mobile_editor_view.png`, `07_mobile_preview_view.png` diff --git a/e2e/settings.spec.ts b/e2e/settings.spec.ts index 0d93ea6..cadf76e 100644 --- a/e2e/settings.spec.ts +++ b/e2e/settings.spec.ts @@ -78,19 +78,35 @@ test("the account tab changes the name and the password, and signs other devices expect(login.status()).toBe(200); await page.goto("/settings?tab=account"); - await page.getByLabel("Display name").fill("Ada L."); - await page.getByRole("button", { name: "Save", exact: true }).click(); + await page + .getByText("Display name", { exact: true }) + .locator("xpath=ancestor::div[contains(@class,'justify-between')][1]") + .getByRole("button", { name: "Edit" }) + .click(); + const nameDialog = page.getByRole("dialog", { name: "Display name" }); + await nameDialog.getByLabel("Display name").fill("Ada L."); + await nameDialog.getByRole("button", { name: "Save" }).click(); await expect(page.getByRole("region", { name: "Account" })).toContainText("Ada L."); const next = "a brand new long password"; - await page.getByLabel("Current password").fill("not the password at all"); - await page.getByLabel("New password").fill(next); - await page.getByRole("button", { name: "Change password" }).click(); + const openPassword = async () => { + await page + .getByText("Password", { exact: true }) + .locator("xpath=ancestor::div[contains(@class,'justify-between')][1]") + .getByRole("button", { name: "Edit" }) + .click(); + return page.getByRole("dialog", { name: "Change password" }); + }; + let dialog = await openPassword(); + await dialog.getByLabel("Current password").fill("not the password at all"); + await dialog.getByLabel("New password").fill(next); + await dialog.getByRole("button", { name: "Change password" }).click(); await expect(page.getByText("That isn't your current password.")).toBeVisible(); - await page.getByLabel("Current password").fill(password); - await page.getByRole("button", { name: "Change password" }).click(); + await dialog.getByLabel("Current password").fill(password); + await dialog.getByRole("button", { name: "Change password" }).click(); await expect(page.getByText("Your other devices were signed out.")).toBeVisible(); + await expect(dialog).toBeHidden(); // this browser stays signed in; the other device does not await page.reload(); @@ -100,3 +116,10 @@ test("the account tab changes the name and the password, and signs other devices ).toBeNull(); await otherContext.close(); }); + +test("the settings content sits in the middle of the page", async ({ page }) => { + await page.setViewportSize({ width: 1280, height: 800 }); + await page.goto("/settings"); + const box = (await page.getByRole("region", { name: "Editor" }).boundingBox())!; + expect(Math.abs(box.x + box.width / 2 - 640)).toBeLessThan(8); +}); diff --git a/src/components/settings/AccountSection.tsx b/src/components/settings/AccountSection.tsx index 77cab9d..6ba6a01 100644 --- a/src/components/settings/AccountSection.tsx +++ b/src/components/settings/AccountSection.tsx @@ -1,18 +1,28 @@ -import { type FormEvent, useState } from "react"; +import { type FormEvent, type ReactNode, useState } from "react"; import { toast } from "sonner"; import { Avatar } from "@/components/ui/avatar"; import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { type AccountUser, changePassword, updateDisplayName } from "@/lib/account/client"; import { accountStore } from "@/lib/account/store"; import { SettingsRow } from "./SettingsRow"; -/** Who is signed in, and what they can change about themselves. */ +/** Who is signed in, and what they can change about themselves (each change in its own dialog). */ export function AccountSection({ user }: { user: AccountUser }) { const label = user.displayName || user.email; + const [editing, setEditing] = useState<"name" | "password" | null>(null); + const hasPassword = user.hasPassword !== false; return ( -
+
@@ -20,115 +30,185 @@ export function AccountSection({ user }: { user: AccountUser }) {

{user.email}

- + + + {user.email} - + + + + {/* mounted only while open, so each opening starts empty or from what is saved */} + {editing === "name" && ( + setEditing(null)} name={user.displayName ?? ""} /> + )} + {editing === "password" && ( + setEditing(null)} hasPassword={hasPassword} /> + )}
); } -function NameForm({ name }: { name: string }) { +function FormDialog({ + onClose, + title, + description, + submit, + busy, + disabled, + onSubmit, + children, +}: { + onClose: () => void; + title: string; + description: string; + submit: string; + busy: boolean; + disabled: boolean; + onSubmit: () => void; + children: ReactNode; +}) { + return ( + !open && onClose()}> + +
{ + e.preventDefault(); + onSubmit(); + }} + > + + {title} + {description} + + {children} + + + + +
+
+
+ ); +} + +function NameDialog({ onClose, name }: { onClose: () => void; name: string }) { const [value, setValue] = useState(name); const [busy, setBusy] = useState(false); - async function save(e: FormEvent) { - e.preventDefault(); + async function save() { setBusy(true); const r = await updateDisplayName(value); setBusy(false); if ("error" in r) return void toast.error(r.error); await accountStore.refresh(); toast.success("Name saved"); + onClose(); } return ( -
-
+
+
+
{THEMES.map((t) => ( diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx index e9270e0..20229de 100644 --- a/src/components/settings/SettingsPage.tsx +++ b/src/components/settings/SettingsPage.tsx @@ -42,7 +42,7 @@ export function SettingsPage({ tab, onTab }: { tab: string; onTab: (tab: Setting
-
+

Settings

onTab(v as SettingsTab)}> From f6ea2313caf5a63cfb3ee882be2ddd36c544f571 Mon Sep 17 00:00:00 2001 From: Chizoba Jude Ojini Date: Sat, 14 Nov 2026 16:13:46 +0000 Subject: [PATCH 05/12] test(settings): use const for the password dialog --- e2e/settings.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/e2e/settings.spec.ts b/e2e/settings.spec.ts index cadf76e..dfe3e3b 100644 --- a/e2e/settings.spec.ts +++ b/e2e/settings.spec.ts @@ -97,7 +97,7 @@ test("the account tab changes the name and the password, and signs other devices .click(); return page.getByRole("dialog", { name: "Change password" }); }; - let dialog = await openPassword(); + const dialog = await openPassword(); await dialog.getByLabel("Current password").fill("not the password at all"); await dialog.getByLabel("New password").fill(next); await dialog.getByRole("button", { name: "Change password" }).click(); From ae2c8e5c09166f500014546cf3ec558f370a360e Mon Sep 17 00:00:00 2001 From: Chizoba Jude Ojini Date: Sat, 14 Nov 2026 16:54:13 +0000 Subject: [PATCH 06/12] feat(account): change the email address with a link to the new one --- docs/SYSTEM_SPEC.md | 3 + docs/UI_SPEC.md | 2 +- e2e/email-change.spec.ts | 90 ++++++++ src/components/AuthNotices.tsx | 4 +- src/components/settings/AccountSection.tsx | 76 ++++++- src/lib/account/client.ts | 9 + src/routeTree.gen.ts | 52 +++++ src/routes/api/auth/email.confirm.ts | 10 + src/routes/api/auth/email.ts | 10 + src/server/auth/email-change.test.ts | 230 +++++++++++++++++++++ src/server/auth/email-change.ts | 166 +++++++++++++++ src/server/auth/routes.ts | 67 ++++++ src/server/auth/tokens.ts | 2 +- 13 files changed, 714 insertions(+), 7 deletions(-) create mode 100644 e2e/email-change.spec.ts create mode 100644 src/routes/api/auth/email.confirm.ts create mode 100644 src/routes/api/auth/email.ts create mode 100644 src/server/auth/email-change.test.ts create mode 100644 src/server/auth/email-change.ts diff --git a/docs/SYSTEM_SPEC.md b/docs/SYSTEM_SPEC.md index ebadf5f..eae11bf 100644 --- a/docs/SYSTEM_SPEC.md +++ b/docs/SYSTEM_SPEC.md @@ -603,6 +603,8 @@ CREATE TABLE share_comments ( -- plain text, one level of replies | `POST` | `/api/auth/verify/resend` | Session | Sends another confirmation email (3 an hour per account). | | `POST` | `/api/auth/forgot` | None | Emails a password reset link when the address has an account, and answers the same either way (5 an hour per address, 3 an hour per inbox, CAPTCHA when set). | | `POST` | `/api/auth/reset` | None | Sets a new password with the link's token (one hour, single use), ends every session, and counts as confirming the address. | +| `POST` | `/api/auth/email` | Session | `{ email, current }`. Emails a confirmation link to the new address; the address changes when it is opened. Needs the current password and a server that sends mail; `409 email_taken`, `same_email`, `password_required`. 3 links an hour. | +| `GET` | `/api/auth/email/confirm?token=` | Link | Makes the new address the account's, re-keys invitations, ends other sessions, notifies the old address, then redirects to `/settings?tab=account`. | | `PATCH` | `/api/auth/profile` | Session | `{ displayName }` (up to 60 characters; empty clears it). The name other people see in cursors, comments and invitations. | | `POST` | `/api/auth/password` | Session | `{ current?, next }`. Changes the password; an account with none (GitHub or Google only) may set one without `current`. Wrong guesses are limited per account like sign-in failures. Ends the account's other sessions and reset links; the session making the request stays. | | `GET` | `/api/auth/github` | None | Initiates GitHub OAuth flow with PKCE state challenge. | @@ -667,6 +669,7 @@ CREATE TABLE share_comments ( -- plain text, one level of replies - _Email confirmation:_ when the server can send mail, a password account starts unconfirmed and **nothing is sent at sign-up**: the first time the account tries the cloud (a draft's "Save to cloud" or the account menu's "Choose drafts for the cloud…") the app opens a "Confirm your email" dialog that sends the link, and opening it again sends nothing while that link is still good ("Send it again" forces one). People who only write locally never cost a message. Until the link is used the cloud (sync and image hosting) answers 403 `email_unverified`. The one-time link (hash stored, 24 hours, single use, valid only for the address it was sent to) is used. GitHub and Google accounts count as confirmed. A server that sends no mail confirms nothing and blocks nothing. A failed send shows in the dialog, which offers to try again. - _Email design and retries:_ confirmation and reset mail are sent as plain text plus a designed HTML version (`src/server/mail/template.ts`): the warm paper palette as hex with a dark version for clients that follow the reader's setting, the link also written out under the button, and nothing loaded from the network (no images, fonts or trackers). If sending a confirmation fails, its link is removed again, so the next request tries a second time; once a send succeeds, later requests answer "already sent" until the link is used or expires. - _Password reset:_ "Forgot your password?" in the sign-in dialog (shown only when the server can send mail) asks for the address and always answers "if an account exists, we sent a link", so it cannot reveal who has one: unknown addresses and inboxes already sent 3 links in the hour are answered identically, the mail is sent after the response goes out (`waitUntil` on Workers), and the same sign-up CAPTCHA applies. The link points to a page (`/reset-password`, noindex), not to a state-changing GET, so mail scanners that open links cannot use it up; the page takes the token out of the address bar. A link lasts an hour, works once, is stored only as a hash, is tied to the address it was sent to and to its purpose (a confirmation link cannot reset a password, nor the reverse), and a new request replaces the older one. A weak password is refused without using the link up. Resetting sets the password (so a GitHub-only account can also gain one), deletes every session of the account and its other pending links, sets the address as confirmed (the person just read mail sent to it) and lifts a sign-in lockout. It does not sign anyone in. +- _Changing the address:_ Settings, Account, Email, Edit asks for the new address and the current password and emails a link to the NEW address (purpose `email_change`, 24 hours, once, stored as a hash like the others, a newer request replaces the older one, 3 an hour per account). Nothing changes until the link is opened, so a mistyped address cannot lock anyone out, and the old address keeps working meanwhile. The current password is required so a stolen session cannot move the account to another inbox; an account with no password (GitHub or Google only) sets one first, and wrong guesses share the password limit. It needs a server that sends mail, since the new address must be proven. Opening the link (`GET /api/auth/email/confirm`, which redirects to the Account tab) sets `users.email` and `email_key` (the unique key decides if someone took the address meanwhile), marks it confirmed, ends the account's other sessions (the browser that opened the link stays signed in when it holds one of them), re-keys invitations held under the old inbox (`document_editors`, `share_people`; a row that would duplicate one already under the new address is dropped) so shared and live drafts keep opening, and emails a notice to the old address. - _CAPTCHA:_ with `TURNSTILE_SECRET` set, sign-up needs a Cloudflare Turnstile token, verified server-side (anything but a clear success fails); the CSP allows Cloudflare's challenge script and frame for it. 1. **HTML Sanitization:** Raw user input is parsed and sanitized using a strict `rehype-sanitize` schema allowing only standard formatting elements, safe attributes, and `data:image/*` or `https://` sources. diff --git a/docs/UI_SPEC.md b/docs/UI_SPEC.md index aae4d1e..0e11449 100644 --- a/docs/UI_SPEC.md +++ b/docs/UI_SPEC.md @@ -120,7 +120,7 @@ Only for an admin; anyone else sees the site's 404. Reached from "Admin dashboar ## 6b. Settings: `/settings` -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 and Password rows, each with an Edit button that opens a dialog: the name field, 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). 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. +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). 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. ## 7. Small screens — `06_mobile_editor_view.png`, `07_mobile_preview_view.png` diff --git a/e2e/email-change.spec.ts b/e2e/email-change.spec.ts new file mode 100644 index 0000000..32ed16d --- /dev/null +++ b/e2e/email-change.spec.ts @@ -0,0 +1,90 @@ +import { expect, test, type APIRequestContext } from "@playwright/test"; +import { SITE, asVisitor, linkIn, mailTo, password, sentTo, signUp, unique } from "./mail-server"; + +// These specs run against the server that sends mail (see playwright.config.ts). +test.use({ baseURL: SITE }); + +const CONFIRM = /confirm your new email/i; +const NOTICE = /email was changed/i; +const ask = (request: APIRequestContext, email: string, current = password) => + request.post("/api/auth/email", { data: { email, current } }); +const login = (request: APIRequestContext, email: string) => + request.post("/api/auth/login", { data: { email, password }, headers: asVisitor() }); + +test("a link to the new address changes it, tells the old one, and ends other devices", async ({ + request, + playwright, +}) => { + const old = `old-${unique()}@example.com`; + const fresh = `fresh-${unique()}@example.com`; + await signUp(request, old); + const other = await playwright.request.newContext({ baseURL: SITE }); + expect((await login(other, old)).status()).toBe(200); + + // the password is checked, and nothing is sent for a wrong one + const wrong = await ask(request, fresh, "not the password at all"); + expect(wrong.status()).toBe(401); + expect((await wrong.json()).error).toBe("wrong_password"); + expect(await sentTo(fresh, CONFIRM)).toBe(0); + + expect((await ask(request, fresh)).status()).toBe(200); + const link = linkIn(await mailTo(fresh, CONFIRM)); + expect(link.pathname).toBe("/api/auth/email/confirm"); + // nothing has changed yet + expect((await login(other, old)).status()).toBe(200); + + const opened = await request.get(link.pathname + link.search, { maxRedirects: 0 }); + expect(opened.status()).toBe(302); + expect(opened.headers()["location"]).toContain("email_changed=1"); + await mailTo(old, NOTICE); + + expect((await login(request, old)).status()).toBe(401); + expect((await login(request, fresh)).status()).toBe(200); + // this browser (which opened the link) stays signed in; the other device was signed out + const me = await (await request.get("/api/auth/me")).json(); + expect(me.user.email).toBe(fresh); + expect((await (await other.get("/api/auth/me")).json()).user).toBeNull(); + + const again = await request.get(link.pathname + link.search, { maxRedirects: 0 }); + expect(again.headers()["location"]).toContain("auth_error=email_change_failed"); + await other.dispose(); +}); + +test("an address another account has, or one's own, is refused", async ({ request }) => { + const mine = `mine-${unique()}@example.com`; + const theirs = `theirs-${unique()}@example.com`; + await signUp(request, theirs); + await request.post("/api/auth/logout"); + await signUp(request, mine); + const taken = await ask(request, theirs); + expect(taken.status()).toBe(409); + expect((await taken.json()).error).toBe("email_taken"); + const same = await ask(request, mine.toUpperCase()); + expect((await same.json()).error).toBe("same_email"); + expect(await sentTo(theirs, CONFIRM)).toBe(0); +}); + +test("in the app: the Email row sends the link, and opening it shows the new address", async ({ + page, +}) => { + const old = `app-old-${unique()}@example.com`; + const fresh = `app-fresh-${unique()}@example.com`; + await page.setExtraHTTPHeaders(asVisitor()); + await signUp(page.request, old); + await page.goto("/settings?tab=account"); + await page + .getByText("Email", { exact: true }) + .locator("xpath=ancestor::div[contains(@class,'justify-between')][1]") + .getByRole("button", { name: "Edit" }) + .click(); + const dialog = page.getByRole("dialog", { name: "Change email" }); + await dialog.getByLabel("New email address").fill(fresh); + await dialog.getByLabel("Current password").fill(password); + await dialog.getByRole("button", { name: "Send link" }).click(); + await expect(page.getByText("Check your new inbox")).toBeVisible(); + + await page.goto(linkIn(await mailTo(fresh, CONFIRM)).toString()); + await expect(page).toHaveURL(/\/settings/); + await expect(page.getByText("Email changed")).toBeVisible(); + await expect(page.getByRole("region", { name: "Account" })).toContainText(fresh); +}); diff --git a/src/components/AuthNotices.tsx b/src/components/AuthNotices.tsx index abbb7f2..7559aef 100644 --- a/src/components/AuthNotices.tsx +++ b/src/components/AuthNotices.tsx @@ -25,10 +25,12 @@ export function AuthNotices() { if (code) toast.error(authMessage(code)); if (url.searchParams.get("verified")) toast.success("Email confirmed", { description: "You can now store drafts in your cloud." }); + if (url.searchParams.get("email_changed")) + toast.success("Email changed", { description: "Sign in with the new address from now on." }); const github = url.searchParams.get("github_error"); if (github) toast.error(GITHUB_ERRORS[github] ?? GITHUB_ERRORS["github_failed"]!); if (url.searchParams.get("github") === "connected") toast.success("GitHub connected"); - const names = ["auth_error", "verified", "github_error", "github"]; + const names = ["auth_error", "verified", "email_changed", "github_error", "github"]; if (names.some((n) => url.searchParams.has(n))) { for (const n of names) url.searchParams.delete(n); window.history.replaceState(null, "", url); diff --git a/src/components/settings/AccountSection.tsx b/src/components/settings/AccountSection.tsx index 6ba6a01..d5fdc64 100644 --- a/src/components/settings/AccountSection.tsx +++ b/src/components/settings/AccountSection.tsx @@ -12,14 +12,19 @@ import { } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; -import { type AccountUser, changePassword, updateDisplayName } from "@/lib/account/client"; +import { + type AccountUser, + changePassword, + requestEmailChange, + updateDisplayName, +} from "@/lib/account/client"; import { accountStore } from "@/lib/account/store"; import { SettingsRow } from "./SettingsRow"; /** Who is signed in, and what they can change about themselves (each change in its own dialog). */ export function AccountSection({ user }: { user: AccountUser }) { const label = user.displayName || user.email; - const [editing, setEditing] = useState<"name" | "password" | null>(null); + const [editing, setEditing] = useState<"name" | "email" | "password" | null>(null); const hasPassword = user.hasPassword !== false; return (
@@ -42,9 +47,20 @@ export function AccountSection({ user }: { user: AccountUser }) { - {user.email} + setEditing(null)} name={user.displayName ?? ""} /> )} + {editing === "email" && setEditing(null)} />} {editing === "password" && ( setEditing(null)} hasPassword={hasPassword} /> )} @@ -153,6 +170,57 @@ function NameDialog({ onClose, name }: { onClose: () => void; name: string }) { ); } +function EmailDialog({ onClose }: { onClose: () => void }) { + const [email, setEmail] = useState(""); + const [current, setCurrent] = useState(""); + const [busy, setBusy] = useState(false); + async function save() { + setBusy(true); + const r = await requestEmailChange(email, current); + setBusy(false); + if ("error" in r) return void toast.error(r.error); + toast.success("Check your new inbox", { + description: `We sent a link to ${r.to}. Your address changes when you open it.`, + }); + onClose(); + } + return ( + + + setEmail(e.target.value)} + /> + + setCurrent(e.target.value)} + /> + + ); +} + function PasswordDialog({ onClose, hasPassword }: { onClose: () => void; hasPassword: boolean }) { const [current, setCurrent] = useState(""); const [next, setNext] = useState(""); diff --git a/src/lib/account/client.ts b/src/lib/account/client.ts index a759590..8579452 100644 --- a/src/lib/account/client.ts +++ b/src/lib/account/client.ts @@ -53,6 +53,9 @@ const MESSAGES: Record = { suspended: "This account has been suspended.", wrong_password: "That isn't your current password.", same: "Choose a password different from the current one.", + same_email: "That is the address this account already uses.", + password_required: "Set a password first (under Password), then change your email.", + email_change_failed: "That link is invalid or has expired. Ask for a new one in Settings.", unauthorized: "You were signed out. Sign in again.", signups_closed: "New accounts aren't being created right now.", }; @@ -244,3 +247,9 @@ export async function changePassword(next: string, current?: string) { const r = await send("/api/auth/password", "POST", { next, ...(current && { current }) }); return "error" in r ? { error: String(r.error) } : { ok: true as const }; } + +/** Emails a confirmation link to the new address; the address changes when the link is opened. */ +export async function requestEmailChange(email: string, current: string) { + const r = await send("/api/auth/email", "POST", { email, current }); + return "error" in r ? { error: String(r.error) } : { ok: true as const, to: String(r["to"]) }; +} diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.ts index 3787729..c40fd6d 100644 --- a/src/routeTree.gen.ts +++ b/src/routeTree.gen.ts @@ -35,6 +35,7 @@ import { Route as ApiAdminSettingsRouteImport } from './routes/api/admin.setting import { Route as ApiAdminUsersRouteImport } from './routes/api/admin.users' import { Route as ApiAiIntegrationsRouteImport } from './routes/api/ai.integrations' import { Route as ApiAssetsIdRouteImport } from './routes/api/assets.$id' +import { Route as ApiAuthEmailRouteImport } from './routes/api/auth/email' import { Route as ApiAuthForgotRouteImport } from './routes/api/auth/forgot' import { Route as ApiAuthGithubRouteImport } from './routes/api/auth/github' import { Route as ApiAuthGoogleRouteImport } from './routes/api/auth/google' @@ -57,6 +58,7 @@ import { Route as ApiSyncPushRouteImport } from './routes/api/sync/push' import { Route as ApiAdminPlansNameRouteImport } from './routes/api/admin.plans.$name' import { Route as ApiAdminUsersIdRouteImport } from './routes/api/admin.users.$id' import { Route as ApiAiIntegrationsIdRouteImport } from './routes/api/ai.integrations.$id' +import { Route as ApiAuthEmailConfirmRouteImport } from './routes/api/auth/email.confirm' import { Route as ApiAuthGithubCallbackRouteImport } from './routes/api/auth/github.callback' import { Route as ApiAuthGoogleCallbackRouteImport } from './routes/api/auth/google.callback' import { Route as ApiAuthVerifyResendRouteImport } from './routes/api/auth/verify.resend' @@ -209,6 +211,11 @@ const ApiAssetsIdRoute = ApiAssetsIdRouteImport.update({ path: '/$id', getParentRoute: () => ApiAssetsRoute, } as any) +const ApiAuthEmailRoute = ApiAuthEmailRouteImport.update({ + id: '/api/auth/email', + path: '/api/auth/email', + getParentRoute: () => rootRouteImport, +} as any) const ApiAuthForgotRoute = ApiAuthForgotRouteImport.update({ id: '/api/auth/forgot', path: '/api/auth/forgot', @@ -319,6 +326,11 @@ const ApiAiIntegrationsIdRoute = ApiAiIntegrationsIdRouteImport.update({ path: '/$id', getParentRoute: () => ApiAiIntegrationsRoute, } as any) +const ApiAuthEmailConfirmRoute = ApiAuthEmailConfirmRouteImport.update({ + id: '/confirm', + path: '/confirm', + getParentRoute: () => ApiAuthEmailRoute, +} as any) const ApiAuthGithubCallbackRoute = ApiAuthGithubCallbackRouteImport.update({ id: '/callback', path: '/callback', @@ -459,6 +471,7 @@ export interface FileRoutesByFullPath { '/api/admin/users': typeof ApiAdminUsersRouteWithChildren '/api/ai/integrations': typeof ApiAiIntegrationsRouteWithChildren '/api/assets/$id': typeof ApiAssetsIdRoute + '/api/auth/email': typeof ApiAuthEmailRouteWithChildren '/api/auth/forgot': typeof ApiAuthForgotRoute '/api/auth/github': typeof ApiAuthGithubRouteWithChildren '/api/auth/google': typeof ApiAuthGoogleRouteWithChildren @@ -481,6 +494,7 @@ export interface FileRoutesByFullPath { '/api/admin/plans/$name': typeof ApiAdminPlansNameRoute '/api/admin/users/$id': typeof ApiAdminUsersIdRouteWithChildren '/api/ai/integrations/$id': typeof ApiAiIntegrationsIdRoute + '/api/auth/email/confirm': typeof ApiAuthEmailConfirmRoute '/api/auth/github/callback': typeof ApiAuthGithubCallbackRoute '/api/auth/google/callback': typeof ApiAuthGoogleCallbackRoute '/api/auth/verify/resend': typeof ApiAuthVerifyResendRoute @@ -530,6 +544,7 @@ export interface FileRoutesByTo { '/api/admin/users': typeof ApiAdminUsersRouteWithChildren '/api/ai/integrations': typeof ApiAiIntegrationsRouteWithChildren '/api/assets/$id': typeof ApiAssetsIdRoute + '/api/auth/email': typeof ApiAuthEmailRouteWithChildren '/api/auth/forgot': typeof ApiAuthForgotRoute '/api/auth/github': typeof ApiAuthGithubRouteWithChildren '/api/auth/google': typeof ApiAuthGoogleRouteWithChildren @@ -552,6 +567,7 @@ export interface FileRoutesByTo { '/api/admin/plans/$name': typeof ApiAdminPlansNameRoute '/api/admin/users/$id': typeof ApiAdminUsersIdRouteWithChildren '/api/ai/integrations/$id': typeof ApiAiIntegrationsIdRoute + '/api/auth/email/confirm': typeof ApiAuthEmailConfirmRoute '/api/auth/github/callback': typeof ApiAuthGithubCallbackRoute '/api/auth/google/callback': typeof ApiAuthGoogleCallbackRoute '/api/auth/verify/resend': typeof ApiAuthVerifyResendRoute @@ -602,6 +618,7 @@ export interface FileRoutesById { '/api/admin/users': typeof ApiAdminUsersRouteWithChildren '/api/ai/integrations': typeof ApiAiIntegrationsRouteWithChildren '/api/assets/$id': typeof ApiAssetsIdRoute + '/api/auth/email': typeof ApiAuthEmailRouteWithChildren '/api/auth/forgot': typeof ApiAuthForgotRoute '/api/auth/github': typeof ApiAuthGithubRouteWithChildren '/api/auth/google': typeof ApiAuthGoogleRouteWithChildren @@ -624,6 +641,7 @@ export interface FileRoutesById { '/api/admin/plans/$name': typeof ApiAdminPlansNameRoute '/api/admin/users/$id': typeof ApiAdminUsersIdRouteWithChildren '/api/ai/integrations/$id': typeof ApiAiIntegrationsIdRoute + '/api/auth/email/confirm': typeof ApiAuthEmailConfirmRoute '/api/auth/github/callback': typeof ApiAuthGithubCallbackRoute '/api/auth/google/callback': typeof ApiAuthGoogleCallbackRoute '/api/auth/verify/resend': typeof ApiAuthVerifyResendRoute @@ -675,6 +693,7 @@ export interface FileRouteTypes { | '/api/admin/users' | '/api/ai/integrations' | '/api/assets/$id' + | '/api/auth/email' | '/api/auth/forgot' | '/api/auth/github' | '/api/auth/google' @@ -697,6 +716,7 @@ export interface FileRouteTypes { | '/api/admin/plans/$name' | '/api/admin/users/$id' | '/api/ai/integrations/$id' + | '/api/auth/email/confirm' | '/api/auth/github/callback' | '/api/auth/google/callback' | '/api/auth/verify/resend' @@ -746,6 +766,7 @@ export interface FileRouteTypes { | '/api/admin/users' | '/api/ai/integrations' | '/api/assets/$id' + | '/api/auth/email' | '/api/auth/forgot' | '/api/auth/github' | '/api/auth/google' @@ -768,6 +789,7 @@ export interface FileRouteTypes { | '/api/admin/plans/$name' | '/api/admin/users/$id' | '/api/ai/integrations/$id' + | '/api/auth/email/confirm' | '/api/auth/github/callback' | '/api/auth/google/callback' | '/api/auth/verify/resend' @@ -817,6 +839,7 @@ export interface FileRouteTypes { | '/api/admin/users' | '/api/ai/integrations' | '/api/assets/$id' + | '/api/auth/email' | '/api/auth/forgot' | '/api/auth/github' | '/api/auth/google' @@ -839,6 +862,7 @@ export interface FileRouteTypes { | '/api/admin/plans/$name' | '/api/admin/users/$id' | '/api/ai/integrations/$id' + | '/api/auth/email/confirm' | '/api/auth/github/callback' | '/api/auth/google/callback' | '/api/auth/verify/resend' @@ -888,6 +912,7 @@ export interface RootRouteChildren { ApiAdminSettingsRoute: typeof ApiAdminSettingsRoute ApiAdminUsersRoute: typeof ApiAdminUsersRouteWithChildren ApiAiIntegrationsRoute: typeof ApiAiIntegrationsRouteWithChildren + ApiAuthEmailRoute: typeof ApiAuthEmailRouteWithChildren ApiAuthForgotRoute: typeof ApiAuthForgotRoute ApiAuthGithubRoute: typeof ApiAuthGithubRouteWithChildren ApiAuthGoogleRoute: typeof ApiAuthGoogleRouteWithChildren @@ -1094,6 +1119,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiAssetsIdRouteImport parentRoute: typeof ApiAssetsRoute } + '/api/auth/email': { + id: '/api/auth/email' + path: '/api/auth/email' + fullPath: '/api/auth/email' + preLoaderRoute: typeof ApiAuthEmailRouteImport + parentRoute: typeof rootRouteImport + } '/api/auth/forgot': { id: '/api/auth/forgot' path: '/api/auth/forgot' @@ -1248,6 +1280,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiAiIntegrationsIdRouteImport parentRoute: typeof ApiAiIntegrationsRoute } + '/api/auth/email/confirm': { + id: '/api/auth/email/confirm' + path: '/confirm' + fullPath: '/api/auth/email/confirm' + preLoaderRoute: typeof ApiAuthEmailConfirmRouteImport + parentRoute: typeof ApiAuthEmailRoute + } '/api/auth/github/callback': { id: '/api/auth/github/callback' path: '/callback' @@ -1559,6 +1598,18 @@ const ApiAiIntegrationsRouteChildren: ApiAiIntegrationsRouteChildren = { const ApiAiIntegrationsRouteWithChildren = ApiAiIntegrationsRoute._addFileChildren(ApiAiIntegrationsRouteChildren) +interface ApiAuthEmailRouteChildren { + ApiAuthEmailConfirmRoute: typeof ApiAuthEmailConfirmRoute +} + +const ApiAuthEmailRouteChildren: ApiAuthEmailRouteChildren = { + ApiAuthEmailConfirmRoute: ApiAuthEmailConfirmRoute, +} + +const ApiAuthEmailRouteWithChildren = ApiAuthEmailRoute._addFileChildren( + ApiAuthEmailRouteChildren, +) + interface ApiAuthGithubRouteChildren { ApiAuthGithubCallbackRoute: typeof ApiAuthGithubCallbackRoute } @@ -1659,6 +1710,7 @@ const rootRouteChildren: RootRouteChildren = { ApiAdminSettingsRoute: ApiAdminSettingsRoute, ApiAdminUsersRoute: ApiAdminUsersRouteWithChildren, ApiAiIntegrationsRoute: ApiAiIntegrationsRouteWithChildren, + ApiAuthEmailRoute: ApiAuthEmailRouteWithChildren, ApiAuthForgotRoute: ApiAuthForgotRoute, ApiAuthGithubRoute: ApiAuthGithubRouteWithChildren, ApiAuthGoogleRoute: ApiAuthGoogleRouteWithChildren, diff --git a/src/routes/api/auth/email.confirm.ts b/src/routes/api/auth/email.confirm.ts new file mode 100644 index 0000000..7d7b55c --- /dev/null +++ b/src/routes/api/auth/email.confirm.ts @@ -0,0 +1,10 @@ +import { createFileRoute } from "@tanstack/react-router"; + +export const Route = createFileRoute("/api/auth/email/confirm")({ + server: { + handlers: { + GET: async ({ request }) => + (await import("@/server/auth/routes")).emailConfirmHandler(request), + }, + }, +}); diff --git a/src/routes/api/auth/email.ts b/src/routes/api/auth/email.ts new file mode 100644 index 0000000..51cca0c --- /dev/null +++ b/src/routes/api/auth/email.ts @@ -0,0 +1,10 @@ +import { createFileRoute } from "@tanstack/react-router"; + +export const Route = createFileRoute("/api/auth/email")({ + server: { + handlers: { + POST: async ({ request }) => + (await import("@/server/auth/routes")).emailChangeHandler(request), + }, + }, +}); diff --git a/src/server/auth/email-change.test.ts b/src/server/auth/email-change.test.ts new file mode 100644 index 0000000..67d5117 --- /dev/null +++ b/src/server/auth/email-change.test.ts @@ -0,0 +1,230 @@ +// @vitest-environment node +import { eq } from "drizzle-orm"; +import { beforeEach, describe, expect, it } from "vitest"; +import { createNodeDb } from "../../../infra/db/node"; +import { + documentEditors, + documents, + emailTokens, + sharePeople, + shareLinks, + users, +} from "../../../infra/db/schema"; +import type { Db } from "../db"; +import { + confirmEmailChange, + emailChangeMail, + emailChangedNotice, + requestEmailChange, +} from "./email-change"; +import { login, signup, userForToken } from "./service"; +import { confirmVerification, issueVerification } from "./verify"; + +let db: Db; +let user: { id: string; email: string }; +const now = 1_700_000_000_000; +const password = "the first long password"; +const ask = (input: { email: string; current?: string }, at = now) => + requestEmailChange(db, user.id, input, at); + +beforeEach(async () => { + db = createNodeDb(":memory:") as unknown as Db; + const r = await signup(db, { email: "ada@example.com", password }, now, { verifyByEmail: true }); + if ("error" in r) throw new Error(r.error); + user = r.user; +}); + +describe("requestEmailChange", () => { + it("needs the current password, and an account with none must set one first", async () => { + expect(await ask({ email: "ada@new.example" })).toEqual({ + ok: false, + error: "wrong_password", + }); + expect(await ask({ email: "ada@new.example", current: "not it, not at all" })).toEqual({ + ok: false, + error: "wrong_password", + }); + await db.update(users).set({ passwordHash: null }).where(eq(users.id, user.id)); + expect(await ask({ email: "ada@new.example", current: password })).toEqual({ + ok: false, + error: "password_required", + }); + }); + it("turns away a bad address, the same inbox, and an address another account has", async () => { + expect(await ask({ email: "nope", current: password })).toEqual({ + ok: false, + error: "invalid", + }); + expect(await ask({ email: "ADA+news@example.com", current: password })).toEqual({ + ok: false, + error: "same_email", + }); + await signup(db, { email: "bob@example.com", password }, now, { verifyByEmail: true }); + expect(await ask({ email: "Bob@Example.com", current: password })).toEqual({ + ok: false, + error: "email_taken", + }); + }); + it("issues a link for the new address and changes nothing yet", async () => { + const r = await ask({ email: " Ada@New.example ", current: password }); + expect(r).toMatchObject({ ok: true, to: "ada@new.example" }); + const [row] = await db.select().from(users).where(eq(users.id, user.id)); + expect(row?.email).toBe("ada@example.com"); + expect(await login(db, { email: "ada@example.com", password }, now)).toHaveProperty("token"); + expect(await login(db, { email: "ada@new.example", password }, now)).toEqual({ + error: "invalid_credentials", + }); + }); + it("replaces an earlier pending link", async () => { + const first = await ask({ email: "one@new.example", current: password }); + const second = await ask({ email: "two@new.example", current: password }); + if (!first.ok || !second.ok) throw new Error("expected links"); + expect(await confirmEmailChange(db, first.token, now + 1)).toEqual({ + ok: false, + error: "invalid_token", + }); + expect(await confirmEmailChange(db, second.token, now + 1)).toMatchObject({ ok: true }); + }); +}); + +describe("confirmEmailChange", () => { + async function pending(email = "ada@new.example", at = now) { + const r = await ask({ email, current: password }, at); + if (!r.ok) throw new Error(r.error); + return r.token; + } + + it("switches the address, confirms it, and signs in with the new one only", async () => { + const token = await pending(); + expect(await confirmEmailChange(db, token, now + 1000)).toEqual({ + ok: true, + userId: user.id, + oldEmail: "ada@example.com", + newEmail: "ada@new.example", + }); + expect(await login(db, { email: "ada@new.example", password }, now)).toHaveProperty("token"); + expect(await login(db, { email: "ada@example.com", password }, now)).toEqual({ + error: "invalid_credentials", + }); + const [row] = await db.select().from(users).where(eq(users.id, user.id)); + expect(row).toMatchObject({ email: "ada@new.example", emailKey: "ada@new.example" }); + expect(row?.emailVerifiedAt).toBe(now + 1000); + }); + it("works once, and not after a day", async () => { + const token = await pending(); + expect(await confirmEmailChange(db, token, now + 1000)).toMatchObject({ ok: true }); + expect(await confirmEmailChange(db, token, now + 2000)).toEqual({ + ok: false, + error: "invalid_token", + }); + const late = await pending("ada@later.example", now); + expect(await confirmEmailChange(db, late, now + 25 * 60 * 60 * 1000)).toEqual({ + ok: false, + error: "invalid_token", + }); + }); + it("is refused when someone took the address meanwhile, and keeps the old one", async () => { + const token = await pending(); + await signup(db, { email: "ada@new.example", password }, now, { verifyByEmail: true }); + expect(await confirmEmailChange(db, token, now + 1000)).toEqual({ + ok: false, + error: "email_taken", + }); + const [row] = await db.select().from(users).where(eq(users.id, user.id)); + expect(row?.email).toBe("ada@example.com"); + }); + it("does not mix up with the confirmation and reset links", async () => { + const token = await pending(); + const verify = await issueVerification(db, user, now); + expect(await confirmEmailChange(db, verify, now + 1)).toEqual({ + ok: false, + error: "invalid_token", + }); + expect(await confirmVerification(db, token, now + 1)).toEqual({ ok: false }); + expect(await confirmEmailChange(db, token, now + 1)).toMatchObject({ ok: true }); + }); + it("keeps invitations to the old address working under the new one", async () => { + const owner = await signup(db, { email: "owner@example.com", password }, now, { + verifyByEmail: true, + }); + if ("error" in owner) throw new Error(owner.error); + const doc = (id: string) => ({ + id, + userId: owner.user.id, + contentHash: "h", + createdAt: now, + updatedAt: now, + }); + await db.insert(documents).values([doc("d1"), doc("d2")]); + await db.insert(documentEditors).values([ + { + id: "e1", + documentId: "d1", + email: "ada@example.com", + emailKey: "ada@example.com", + invitedBy: owner.user.id, + createdAt: now, + }, + // also invited under the new address: the two collapse into one + { + id: "e2", + documentId: "d2", + email: "ada@example.com", + emailKey: "ada@example.com", + invitedBy: owner.user.id, + createdAt: now, + }, + { + id: "e3", + documentId: "d2", + email: "ada@new.example", + emailKey: "ada@new.example", + invitedBy: owner.user.id, + createdAt: now, + }, + ]); + await db.insert(shareLinks).values({ id: "s1", documentId: "d1", slug: "abc", createdAt: now }); + await db.insert(sharePeople).values({ + id: "p1", + shareId: "s1", + email: "ada@example.com", + emailKey: "ada@example.com", + createdAt: now, + }); + + await confirmEmailChange(db, await pending(), now + 1000); + + const editors = await db.select().from(documentEditors); + expect(editors.map((e) => [e.documentId, e.emailKey]).sort()).toEqual([ + ["d1", "ada@new.example"], + ["d2", "ada@new.example"], + ]); + expect(editors.find((e) => e.documentId === "d1")?.email).toBe("ada@new.example"); + expect((await db.select().from(sharePeople))[0]).toMatchObject({ + email: "ada@new.example", + emailKey: "ada@new.example", + }); + }); + it("ends the account's sessions except the ones asked to stay", async () => { + const other = await login(db, { email: "ada@example.com", password }, now); + if ("error" in other) throw new Error(other.error); + const keep = await login(db, { email: "ada@example.com", password }, now); + if ("error" in keep) throw new Error(keep.error); + await confirmEmailChange(db, await pending(), now + 1000, keep.token); + expect(await userForToken(db, keep.token, now + 2000)).toMatchObject({ + user: { email: "ada@new.example" }, + }); + expect(await userForToken(db, other.token, now + 2000)).toBeNull(); + }); +}); + +describe("the emails", () => { + it("send the link to the new address and the notice to the old one", () => { + const link = emailChangeMail("https://x.test", "tok", "ada@new.example"); + expect(link.to).toBe("ada@new.example"); + expect(link.text).toContain("https://x.test/api/auth/email/confirm?token=tok"); + const note = emailChangedNotice("https://x.test", "ada@example.com", "ada@new.example"); + expect(note.to).toBe("ada@example.com"); + expect(note.text).toContain("ada@new.example"); + }); +}); diff --git a/src/server/auth/email-change.ts b/src/server/auth/email-change.ts new file mode 100644 index 0000000..f834bcf --- /dev/null +++ b/src/server/auth/email-change.ts @@ -0,0 +1,166 @@ +// Changing the address an account signs in with. The link goes to the NEW address and works once +// for a day; until it is opened nothing changes, so a mistyped address cannot lock anyone out. +// Asking needs the current password, so a stolen session alone cannot move the account to another +// inbox (an account with no password sets one first). Opening it makes the new address the +// account's, counts it as confirmed (the person just read mail sent to it) and ends the other +// sessions. Invitations to the old address follow the person to the new one. +import { and, eq, inArray, ne } from "drizzle-orm"; +import { z } from "zod"; +import { + documentEditors, + emailTokens, + sessions, + sharePeople, + users, +} from "../../../infra/db/schema"; +import type { Db } from "../db"; +import type { Mail } from "../mail"; +import { renderMail } from "../mail/template"; +import { canonicalEmail } from "./email"; +import { verifyPassword } from "./password"; +import { findToken, issueToken, sha256Hex } from "./tokens"; + +export const EMAIL_CHANGE_TTL_MS = 24 * 60 * 60 * 1000; + +const Address = z.string().trim().toLowerCase().email().max(254); + +export async function requestEmailChange( + db: Db, + userId: string, + input: { email: string; current?: string }, + now = Date.now(), +): Promise< + | { ok: true; token: string; to: string } + | { + ok: false; + error: "wrong_password" | "password_required" | "invalid" | "same_email" | "email_taken"; + } +> { + const [row] = await db.select().from(users).where(eq(users.id, userId)); + if (!row) return { ok: false, error: "invalid" }; + if (!row.passwordHash) return { ok: false, error: "password_required" }; + if (!input.current || !(await verifyPassword(input.current, row.passwordHash))) + return { ok: false, error: "wrong_password" }; + + const parsed = Address.safeParse(input.email); + const key = parsed.success ? canonicalEmail(parsed.data) : null; + if (!parsed.success || !key) return { ok: false, error: "invalid" }; + if (key === (row.emailKey ?? canonicalEmail(row.email))) + return { ok: false, error: "same_email" }; + const [taken] = await db.select({ id: users.id }).from(users).where(eq(users.emailKey, key)); + if (taken) return { ok: false, error: "email_taken" }; + + const token = await issueToken( + db, + { id: userId, email: parsed.data }, + "email_change", + EMAIL_CHANGE_TTL_MS, + now, + ); + return { ok: true, token, to: parsed.data }; +} + +/** `keepToken` is the session of the browser that opened the link, when it is this account's. */ +export async function confirmEmailChange( + db: Db, + token: string, + now = Date.now(), + keepToken?: string, +): Promise< + | { ok: true; userId: string; oldEmail: string; newEmail: string } + | { ok: false; error: "invalid_token" | "email_taken" } +> { + const link = await findToken(db, token, "email_change", now); + if (!link) return { ok: false, error: "invalid_token" }; + const [user] = await db.select().from(users).where(eq(users.id, link.userId)); + if (!user) return { ok: false, error: "invalid_token" }; + const newEmail = link.email; + const key = canonicalEmail(newEmail); + if (!key) return { ok: false, error: "invalid_token" }; + const oldKey = user.emailKey ?? canonicalEmail(user.email); + + try { + // the unique index on the key decides if someone else took the address since the link was sent + await db + .update(users) + .set({ email: newEmail, emailKey: key, emailVerifiedAt: now, updatedAt: now }) + .where(eq(users.id, user.id)); + } catch { + return { ok: false, error: "email_taken" }; + } + if (oldKey) await moveInvitations(db, oldKey, newEmail, key); + await db.delete(emailTokens).where(eq(emailTokens.userId, user.id)); + await db + .delete(sessions) + .where( + keepToken + ? and(eq(sessions.userId, user.id), ne(sessions.tokenHash, await sha256Hex(keepToken))) + : eq(sessions.userId, user.id), + ); + return { ok: true, userId: user.id, oldEmail: user.email, newEmail }; +} + +/** Invitations (to edit, to a private link) held under the old inbox now name the new one. */ +async function moveInvitations(db: Db, oldKey: string, email: string, key: string) { + const editors = await db + .select() + .from(documentEditors) + .where(eq(documentEditors.emailKey, oldKey)); + if (editors.length) { + const has = await db + .select({ documentId: documentEditors.documentId }) + .from(documentEditors) + .where(eq(documentEditors.emailKey, key)); + const duplicate = new Set(has.map((h) => h.documentId)); + const drop = editors.filter((e) => duplicate.has(e.documentId)).map((e) => e.id); + if (drop.length) await db.delete(documentEditors).where(inArray(documentEditors.id, drop)); + await db + .update(documentEditors) + .set({ email, emailKey: key }) + .where(eq(documentEditors.emailKey, oldKey)); + } + const people = await db.select().from(sharePeople).where(eq(sharePeople.emailKey, oldKey)); + if (people.length) { + const has = await db + .select({ shareId: sharePeople.shareId }) + .from(sharePeople) + .where(eq(sharePeople.emailKey, key)); + const duplicate = new Set(has.map((h) => h.shareId)); + const drop = people.filter((p) => duplicate.has(p.shareId)).map((p) => p.id); + if (drop.length) await db.delete(sharePeople).where(inArray(sharePeople.id, drop)); + await db + .update(sharePeople) + .set({ email, emailKey: key }) + .where(eq(sharePeople.emailKey, oldKey)); + } +} + +export const emailChangeMail = (origin: string, token: string, to: string): Mail => + renderMail({ + to, + subject: "Confirm your new email for mdstudio", + preheader: "Use this address to sign in to mdstudio.", + heading: "Confirm your new email", + intro: [ + "Someone asked to use this address for an mdstudio account. Until you confirm, the account keeps its current address.", + ], + action: { label: "Confirm new email", url: `${origin}/api/auth/email/confirm?token=${token}` }, + outro: [ + "The link works once and expires in 24 hours. If you didn't ask for this, ignore this message: nothing changes.", + ], + }); + +/** To the address the account had, once it no longer does. */ +export const emailChangedNotice = (origin: string, to: string, newEmail: string): Mail => + renderMail({ + to, + subject: "Your mdstudio email was changed", + preheader: `This account now signs in with ${newEmail}.`, + heading: "Your email was changed", + intro: [ + `The mdstudio account that used this address now signs in with ${newEmail}. Your other devices were signed out.`, + "If you did this, there is nothing more to do. If you didn't, sign in with the new address and change your password, or ask whoever runs this server for help.", + ], + action: { label: "Open mdstudio", url: `${origin}/settings?tab=account` }, + outro: ["You are getting this because this address used to belong to the account."], + }); diff --git a/src/server/auth/routes.ts b/src/server/auth/routes.ts index c4e1b7b..b374164 100644 --- a/src/server/auth/routes.ts +++ b/src/server/auth/routes.ts @@ -23,6 +23,12 @@ import { SESSION_MS, login, logout, signup, userForToken } from "./service"; import { verifyTurnstile } from "./turnstile"; import { confirmVerification, hasLiveVerification, sendVerification } from "./verify"; import { withUser } from "./guard"; +import { + confirmEmailChange, + emailChangeMail, + emailChangedNotice, + requestEmailChange, +} from "./email-change"; import { changePassword, updateProfile } from "./profile"; const json = (body: unknown, status = 200, headers?: HeadersInit) => @@ -259,6 +265,67 @@ export const passwordHandler = (request: Request) => return json({ ok: true }); }); +/** + * `POST { email, current }`: emails a link to the NEW address; nothing changes until it is opened. + * Needs the current password (wrong guesses share the password limit) and a server that sends mail, + * since the new address must be proven. Three links an hour per account. + */ +export const emailChangeHandler = (request: Request) => + withUser(request, async (user, db) => { + if (!sameOrigin(request)) return json({ error: "forbidden" }, 403); + const mailer = await getMailer(request); + if (!mailer) return json({ error: "email_unavailable" }, 503); + const input = (await body(request)) as { email?: unknown; current?: unknown } | null; + if (typeof input?.email !== "string") return json({ error: "invalid" }, 400); + const guesses = `password:${user.id}`; + const max = limit(request, "LOGIN_FAIL_LIMIT", 10); + const wait = await lockedOut(db, guesses, max); + if (wait !== null) return tooMany(wait); + const result = await requestEmailChange(db, user.id, { + email: input.email, + ...(typeof input.current === "string" && { current: input.current }), + }); + if (!result.ok) { + if (result.error === "wrong_password") await hit(db, guesses, max, FAIL_WINDOW); + const status = { wrong_password: 401, email_taken: 409 }[result.error as string] ?? 400; + return json({ error: result.error }, status); + } + await clearLimit(db, guesses); + const sends = await hit( + db, + `email-change:${user.id}`, + limit(request, "VERIFY_EMAIL_LIMIT", 3), + HOUR, + ); + if (!sends.allowed) return tooMany(sends.retryAfter); + try { + await mailer(emailChangeMail(siteOrigin(request), result.token, result.to)); + } catch (error) { + console.error("Couldn't send the email-change link", error); + return json({ error: "email_failed" }, 502); + } + return json({ ok: true, to: result.to }); + }); + +/** The link in that email: makes the new address the account's, then goes to the settings. */ +export async function emailConfirmHandler(request: Request) { + const token = new URL(request.url).searchParams.get("token") ?? ""; + const db = await getDb(request); + const done = await confirmEmailChange(db, token, Date.now(), readToken(request) ?? undefined); + if (!done.ok) + return redirect( + `/settings?tab=account&auth_error=${done.error === "email_taken" ? "email_taken" : "email_change_failed"}`, + ); + await endSessions(request, done.userId, "signed_out"); + const mailer = await getMailer(request); + if (mailer) + await afterResponse( + request, + mailer(emailChangedNotice(siteOrigin(request), done.oldEmail, done.newEmail)), + ); + return redirect("/settings?tab=account&email_changed=1"); +} + export async function logoutHandler(request: Request) { if (!sameOrigin(request)) return json({ error: "forbidden" }, 403); const token = readToken(request); diff --git a/src/server/auth/tokens.ts b/src/server/auth/tokens.ts index 164ac4e..2e58b9c 100644 --- a/src/server/auth/tokens.ts +++ b/src/server/auth/tokens.ts @@ -6,7 +6,7 @@ import { and, eq, gt } from "drizzle-orm"; import { emailTokens } from "../../../infra/db/schema"; import type { Db } from "../db"; -export type Purpose = "verify" | "reset"; +export type Purpose = "verify" | "reset" | "email_change"; const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)) From 0156af75e0a77dc008b8bb14179b2db19dfe4df4 Mon Sep 17 00:00:00 2001 From: Chizoba Jude Ojini Date: Sat, 14 Nov 2026 17:34:00 +0000 Subject: [PATCH 07/12] feat(account): link and unlink GitHub and Google sign-ins --- docs/SYSTEM_SPEC.md | 3 + docs/UI_SPEC.md | 2 +- e2e/linked-sign-ins.spec.ts | 99 ++++++++++++++++++++++ src/components/AuthNotices.tsx | 7 +- src/components/settings/AccountSection.tsx | 61 ++++++++++++- src/lib/account/client.ts | 11 +++ src/routeTree.gen.ts | 21 +++++ src/routes/api/auth/links.$provider.ts | 10 +++ src/server/auth/github.test.ts | 39 ++++++++- src/server/auth/github.ts | 60 ++++++++----- src/server/auth/google.ts | 62 +++++++++----- src/server/auth/links.test.ts | 89 +++++++++++++++++++ src/server/auth/links.ts | 80 +++++++++++++++++ src/server/auth/routes.ts | 95 ++++++++++++++++++--- 14 files changed, 586 insertions(+), 53 deletions(-) create mode 100644 e2e/linked-sign-ins.spec.ts create mode 100644 src/routes/api/auth/links.$provider.ts create mode 100644 src/server/auth/links.test.ts create mode 100644 src/server/auth/links.ts diff --git a/docs/SYSTEM_SPEC.md b/docs/SYSTEM_SPEC.md index eae11bf..4dee9b9 100644 --- a/docs/SYSTEM_SPEC.md +++ b/docs/SYSTEM_SPEC.md @@ -605,6 +605,8 @@ CREATE TABLE share_comments ( -- plain text, one level of replies | `POST` | `/api/auth/reset` | None | Sets a new password with the link's token (one hour, single use), ends every session, and counts as confirming the address. | | `POST` | `/api/auth/email` | Session | `{ email, current }`. Emails a confirmation link to the new address; the address changes when it is opened. Needs the current password and a server that sends mail; `409 email_taken`, `same_email`, `password_required`. 3 links an hour. | | `GET` | `/api/auth/email/confirm?token=` | Link | Makes the new address the account's, re-keys invitations, ends other sessions, notifies the old address, then redirects to `/settings?tab=account`. | +| `GET` | `/api/auth/{github,google}?link=1` | Session | Starts linking that provider to the signed-in account; its callback links it and redirects to `/settings?tab=account`. | +| `DELETE` | `/api/auth/links/:provider` | Session | Unlinks `github` or `google`; `409 last_method` if it is the only way to sign in. | | `PATCH` | `/api/auth/profile` | Session | `{ displayName }` (up to 60 characters; empty clears it). The name other people see in cursors, comments and invitations. | | `POST` | `/api/auth/password` | Session | `{ current?, next }`. Changes the password; an account with none (GitHub or Google only) may set one without `current`. Wrong guesses are limited per account like sign-in failures. Ends the account's other sessions and reset links; the session making the request stays. | | `GET` | `/api/auth/github` | None | Initiates GitHub OAuth flow with PKCE state challenge. | @@ -670,6 +672,7 @@ CREATE TABLE share_comments ( -- plain text, one level of replies - _Email design and retries:_ confirmation and reset mail are sent as plain text plus a designed HTML version (`src/server/mail/template.ts`): the warm paper palette as hex with a dark version for clients that follow the reader's setting, the link also written out under the button, and nothing loaded from the network (no images, fonts or trackers). If sending a confirmation fails, its link is removed again, so the next request tries a second time; once a send succeeds, later requests answer "already sent" until the link is used or expires. - _Password reset:_ "Forgot your password?" in the sign-in dialog (shown only when the server can send mail) asks for the address and always answers "if an account exists, we sent a link", so it cannot reveal who has one: unknown addresses and inboxes already sent 3 links in the hour are answered identically, the mail is sent after the response goes out (`waitUntil` on Workers), and the same sign-up CAPTCHA applies. The link points to a page (`/reset-password`, noindex), not to a state-changing GET, so mail scanners that open links cannot use it up; the page takes the token out of the address bar. A link lasts an hour, works once, is stored only as a hash, is tied to the address it was sent to and to its purpose (a confirmation link cannot reset a password, nor the reverse), and a new request replaces the older one. A weak password is refused without using the link up. Resetting sets the password (so a GitHub-only account can also gain one), deletes every session of the account and its other pending links, sets the address as confirmed (the person just read mail sent to it) and lifts a sign-in lockout. It does not sign anyone in. - _Changing the address:_ Settings, Account, Email, Edit asks for the new address and the current password and emails a link to the NEW address (purpose `email_change`, 24 hours, once, stored as a hash like the others, a newer request replaces the older one, 3 an hour per account). Nothing changes until the link is opened, so a mistyped address cannot lock anyone out, and the old address keeps working meanwhile. The current password is required so a stolen session cannot move the account to another inbox; an account with no password (GitHub or Google only) sets one first, and wrong guesses share the password limit. It needs a server that sends mail, since the new address must be proven. Opening the link (`GET /api/auth/email/confirm`, which redirects to the Account tab) sets `users.email` and `email_key` (the unique key decides if someone took the address meanwhile), marks it confirmed, ends the account's other sessions (the browser that opened the link stays signed in when it holds one of them), re-keys invitations held under the old inbox (`document_editors`, `share_people`; a row that would duplicate one already under the new address is dropped) so shared and live drafts keep opening, and emails a notice to the old address. +- _Linked sign-ins:_ Settings, Account lists GitHub and Google (those the server has, plus any already linked) with **Link** or **Unlink**. Linking is the same OAuth flow with `?link=1` on the start address: it needs a signed-in session, the state cookie carries a `.link` marker, and the callback attaches the provider's identity to the signed-in account (`links.ts`) instead of signing anyone in, so the provider's email may differ from the account's. The state check is what stops a forged callback from linking someone else's identity to a victim. An identity belongs to one account (`already_linked`) and an account has one per provider (`provider_taken`; unlink the first to use another). A name or picture the account lacks is filled in, never replaced. `DELETE /api/auth/links/:provider` unlinks, refused (`409 last_method`) when it is the account's only way to sign in, which a password counts as. `/api/auth/me` returns `linked`. Flows end on `/settings?tab=account` with `linked=` or `auth_error=`. - _CAPTCHA:_ with `TURNSTILE_SECRET` set, sign-up needs a Cloudflare Turnstile token, verified server-side (anything but a clear success fails); the CSP allows Cloudflare's challenge script and frame for it. 1. **HTML Sanitization:** Raw user input is parsed and sanitized using a strict `rehype-sanitize` schema allowing only standard formatting elements, safe attributes, and `data:image/*` or `https://` sources. diff --git a/docs/UI_SPEC.md b/docs/UI_SPEC.md index 0e11449..6f6909d 100644 --- a/docs/UI_SPEC.md +++ b/docs/UI_SPEC.md @@ -120,7 +120,7 @@ Only for an admin; anyone else sees the site's 404. Reached from "Admin dashboar ## 6b. Settings: `/settings` -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). 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. +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. ## 7. Small screens — `06_mobile_editor_view.png`, `07_mobile_preview_view.png` diff --git a/e2e/linked-sign-ins.spec.ts b/e2e/linked-sign-ins.spec.ts new file mode 100644 index 0000000..ffc26d1 --- /dev/null +++ b/e2e/linked-sign-ins.spec.ts @@ -0,0 +1,99 @@ +import { expect, test, type APIRequestContext } from "@playwright/test"; +import { SITE, password, signUp, unique } from "./mail-server"; + +// The mail server is set up for Google against e2e/fake-google.ts: the "code" is the profile the +// fake answers with. A callback is made by hand, after a start that gives this browser its state. +test.use({ baseURL: SITE }); + +const profile = (email: string, sub = `g-${unique()}`) => + Buffer.from(JSON.stringify({ sub, email, email_verified: true, name: "Ada" })).toString( + "base64url", + ); + +async function viaGoogle(request: APIRequestContext, code: string, link: boolean) { + const start = await request.get(`/api/auth/google${link ? "?link=1" : ""}`, { maxRedirects: 0 }); + const location = start.headers()["location"]!; + if (!location.includes("code_challenge")) return start; // refused before leaving the app + const state = new URL(location).searchParams.get("state")!; + return request.get(`/api/auth/google/callback?${new URLSearchParams({ code, state })}`, { + maxRedirects: 0, + }); +} +const me = async (request: APIRequestContext) => + (await (await request.get("/api/auth/me")).json()).user; + +test("links Google to a password account, whatever its email, and signs in with it", async ({ + request, + playwright, +}) => { + await signUp(request, `link-${unique()}@example.com`); + const id = (await me(request)).id; + const sub = `sub-${unique()}`; + const code = profile(`other-${unique()}@example.org`, sub); + + const linked = await viaGoogle(request, code, true); + expect(linked.headers()["location"]).toBe("/settings?tab=account&linked=google"); + expect(await me(request)).toMatchObject({ id, linked: ["google"] }); + + // a fresh browser signing in with that Google account reaches the same account + const other = await playwright.request.newContext({ baseURL: SITE }); + expect((await viaGoogle(other, code, false)).headers()["location"]).toBe("/editor"); + expect(await me(other)).toMatchObject({ id }); + await other.dispose(); +}); + +test("a link needs a signed-in browser, and an identity belongs to one account", async ({ + request, + playwright, +}) => { + const signedOut = await viaGoogle( + await playwright.request.newContext({ baseURL: SITE }), + "x", + true, + ); + expect(signedOut.headers()["location"]).toContain("auth_error=unauthorized"); + + const code = profile(`shared-${unique()}@example.org`); + await signUp(request, `first-${unique()}@example.com`); + expect((await viaGoogle(request, code, true)).headers()["location"]).toContain("linked=google"); + const second = await playwright.request.newContext({ baseURL: SITE }); + await signUp(second, `second-${unique()}@example.com`); + expect((await viaGoogle(second, code, true)).headers()["location"]).toContain( + "auth_error=already_linked", + ); + expect(await me(second)).toMatchObject({ linked: [] }); + await second.dispose(); +}); + +test("unlinking keeps the last way to sign in, until a password is set", async ({ playwright }) => { + const request = await playwright.request.newContext({ baseURL: SITE }); + // an account made with Google alone has no password + await viaGoogle(request, profile(`only-${unique()}@example.com`), false); + expect(await me(request)).toMatchObject({ hasPassword: false, linked: ["google"] }); + + const refused = await request.delete("/api/auth/links/google"); + expect(refused.status()).toBe(409); + expect((await refused.json()).error).toBe("last_method"); + + const set = await request.post("/api/auth/password", { data: { next: password } }); + expect(set.status()).toBe(200); + expect((await request.delete("/api/auth/links/google")).status()).toBe(200); + expect(await me(request)).toMatchObject({ linked: [] }); + expect((await request.delete("/api/auth/links/google")).status()).toBe(404); + await request.dispose(); +}); + +test("in the app: the Account tab links and unlinks Google", async ({ page }) => { + await signUp(page.request, `ui-${unique()}@example.com`); + await page.goto("/settings?tab=account"); + const row = page + .getByText("Sign in with Google", { exact: true }) + .locator("xpath=ancestor::div[contains(@class,'justify-between')][1]"); + await expect(row.getByRole("link", { name: "Link" })).toBeVisible(); + + await viaGoogle(page.request, profile(`ui-other-${unique()}@example.org`), true); + await page.reload(); + await row.getByRole("button", { name: "Unlink" }).click(); + await expect(page.getByText("Google unlinked")).toBeVisible(); + await expect(row.getByRole("link", { name: "Link" })).toBeVisible(); +}); diff --git a/src/components/AuthNotices.tsx b/src/components/AuthNotices.tsx index 7559aef..8fd64a0 100644 --- a/src/components/AuthNotices.tsx +++ b/src/components/AuthNotices.tsx @@ -27,10 +27,15 @@ export function AuthNotices() { toast.success("Email confirmed", { description: "You can now store drafts in your cloud." }); if (url.searchParams.get("email_changed")) toast.success("Email changed", { description: "Sign in with the new address from now on." }); + const linked = url.searchParams.get("linked"); + if (linked === "github" || linked === "google") + toast.success(`${linked === "github" ? "GitHub" : "Google"} linked`, { + description: "You can sign in with it from now on.", + }); const github = url.searchParams.get("github_error"); if (github) toast.error(GITHUB_ERRORS[github] ?? GITHUB_ERRORS["github_failed"]!); if (url.searchParams.get("github") === "connected") toast.success("GitHub connected"); - const names = ["auth_error", "verified", "email_changed", "github_error", "github"]; + const names = ["auth_error", "verified", "email_changed", "linked", "github_error", "github"]; if (names.some((n) => url.searchParams.has(n))) { for (const n of names) url.searchParams.delete(n); window.history.replaceState(null, "", url); diff --git a/src/components/settings/AccountSection.tsx b/src/components/settings/AccountSection.tsx index d5fdc64..e10fa93 100644 --- a/src/components/settings/AccountSection.tsx +++ b/src/components/settings/AccountSection.tsx @@ -16,9 +16,10 @@ import { type AccountUser, changePassword, requestEmailChange, + unlinkProvider, updateDisplayName, } from "@/lib/account/client"; -import { accountStore } from "@/lib/account/store"; +import { accountStore, useAccount } from "@/lib/account/store"; import { SettingsRow } from "./SettingsRow"; /** Who is signed in, and what they can change about themselves (each change in its own dialog). */ @@ -74,6 +75,7 @@ export function AccountSection({ user }: { user: AccountUser }) { {hasPassword ? "Edit" : "Set password"} + {/* mounted only while open, so each opening starts empty or from what is saved */} {editing === "name" && ( setEditing(null)} name={user.displayName ?? ""} /> @@ -86,6 +88,63 @@ export function AccountSection({ user }: { user: AccountUser }) { ); } +const PROVIDERS = [ + { id: "github", name: "GitHub" }, + { id: "google", name: "Google" }, +] as const; + +/** GitHub and Google sign-ins: link another one, or unlink one while another way remains. */ +function SignInMethods({ user }: { user: AccountUser }) { + const account = useAccount(); + const linked = user.linked ?? []; + const [busy, setBusy] = useState(false); + const lastMethod = user.hasPassword === false && linked.length < 2; + const shown = PROVIDERS.filter((p) => linked.includes(p.id) || account[p.id]); + if (!shown.length) return null; + return ( + <> + {shown.map((p) => { + const isLinked = linked.includes(p.id); + return ( + + {isLinked ? ( + + ) : ( + + )} + + ); + })} + + ); +} + function FormDialog({ onClose, title, diff --git a/src/lib/account/client.ts b/src/lib/account/client.ts index 8579452..46b9e8b 100644 --- a/src/lib/account/client.ts +++ b/src/lib/account/client.ts @@ -12,6 +12,8 @@ export type AccountUser = { avatarUrl?: string | null; /** False for an account that signs in only with GitHub or Google (it may set a password). */ hasPassword?: boolean; + /** The GitHub and Google identities linked to the account. */ + linked?: ("github" | "google")[]; }; export type Account = { user: AccountUser | null; @@ -53,6 +55,9 @@ const MESSAGES: Record = { suspended: "This account has been suspended.", wrong_password: "That isn't your current password.", same: "Choose a password different from the current one.", + already_linked: "That account is already linked to a different mdstudio account.", + provider_taken: "This account already has one linked. Unlink it first to link another.", + last_method: "Set a password first: it would be your only way to sign in.", same_email: "That is the address this account already uses.", password_required: "Set a password first (under Password), then change your email.", email_change_failed: "That link is invalid or has expired. Ask for a new one in Settings.", @@ -253,3 +258,9 @@ export async function requestEmailChange(email: string, current: string) { const r = await send("/api/auth/email", "POST", { email, current }); return "error" in r ? { error: String(r.error) } : { ok: true as const, to: String(r["to"]) }; } + +/** Unlinks GitHub or Google, unless it is the account's last way to sign in. */ +export async function unlinkProvider(provider: "github" | "google") { + const r = await send(`/api/auth/links/${provider}`, "DELETE", {}); + return "error" in r ? { error: String(r.error) } : { ok: true as const }; +} diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.ts index c40fd6d..16c95a5 100644 --- a/src/routeTree.gen.ts +++ b/src/routeTree.gen.ts @@ -61,6 +61,7 @@ import { Route as ApiAiIntegrationsIdRouteImport } from './routes/api/ai.integra import { Route as ApiAuthEmailConfirmRouteImport } from './routes/api/auth/email.confirm' import { Route as ApiAuthGithubCallbackRouteImport } from './routes/api/auth/github.callback' import { Route as ApiAuthGoogleCallbackRouteImport } from './routes/api/auth/google.callback' +import { Route as ApiAuthLinksProviderRouteImport } from './routes/api/auth/links.$provider' import { Route as ApiAuthVerifyResendRouteImport } from './routes/api/auth/verify.resend' import { Route as ApiCollabIdEditorsRouteImport } from './routes/api/collab.$id.editors' import { Route as ApiCollabLinkSlugRouteImport } from './routes/api/collab.link.$slug' @@ -341,6 +342,11 @@ const ApiAuthGoogleCallbackRoute = ApiAuthGoogleCallbackRouteImport.update({ path: '/callback', getParentRoute: () => ApiAuthGoogleRoute, } as any) +const ApiAuthLinksProviderRoute = ApiAuthLinksProviderRouteImport.update({ + id: '/api/auth/links/$provider', + path: '/api/auth/links/$provider', + getParentRoute: () => rootRouteImport, +} as any) const ApiAuthVerifyResendRoute = ApiAuthVerifyResendRouteImport.update({ id: '/resend', path: '/resend', @@ -497,6 +503,7 @@ export interface FileRoutesByFullPath { '/api/auth/email/confirm': typeof ApiAuthEmailConfirmRoute '/api/auth/github/callback': typeof ApiAuthGithubCallbackRoute '/api/auth/google/callback': typeof ApiAuthGoogleCallbackRoute + '/api/auth/links/$provider': typeof ApiAuthLinksProviderRoute '/api/auth/verify/resend': typeof ApiAuthVerifyResendRoute '/api/collab/$id/editors': typeof ApiCollabIdEditorsRouteWithChildren '/api/collab/link/$slug': typeof ApiCollabLinkSlugRoute @@ -570,6 +577,7 @@ export interface FileRoutesByTo { '/api/auth/email/confirm': typeof ApiAuthEmailConfirmRoute '/api/auth/github/callback': typeof ApiAuthGithubCallbackRoute '/api/auth/google/callback': typeof ApiAuthGoogleCallbackRoute + '/api/auth/links/$provider': typeof ApiAuthLinksProviderRoute '/api/auth/verify/resend': typeof ApiAuthVerifyResendRoute '/api/collab/$id/editors': typeof ApiCollabIdEditorsRouteWithChildren '/api/collab/link/$slug': typeof ApiCollabLinkSlugRoute @@ -644,6 +652,7 @@ export interface FileRoutesById { '/api/auth/email/confirm': typeof ApiAuthEmailConfirmRoute '/api/auth/github/callback': typeof ApiAuthGithubCallbackRoute '/api/auth/google/callback': typeof ApiAuthGoogleCallbackRoute + '/api/auth/links/$provider': typeof ApiAuthLinksProviderRoute '/api/auth/verify/resend': typeof ApiAuthVerifyResendRoute '/api/collab/$id/editors': typeof ApiCollabIdEditorsRouteWithChildren '/api/collab/link/$slug': typeof ApiCollabLinkSlugRoute @@ -719,6 +728,7 @@ export interface FileRouteTypes { | '/api/auth/email/confirm' | '/api/auth/github/callback' | '/api/auth/google/callback' + | '/api/auth/links/$provider' | '/api/auth/verify/resend' | '/api/collab/$id/editors' | '/api/collab/link/$slug' @@ -792,6 +802,7 @@ export interface FileRouteTypes { | '/api/auth/email/confirm' | '/api/auth/github/callback' | '/api/auth/google/callback' + | '/api/auth/links/$provider' | '/api/auth/verify/resend' | '/api/collab/$id/editors' | '/api/collab/link/$slug' @@ -865,6 +876,7 @@ export interface FileRouteTypes { | '/api/auth/email/confirm' | '/api/auth/github/callback' | '/api/auth/google/callback' + | '/api/auth/links/$provider' | '/api/auth/verify/resend' | '/api/collab/$id/editors' | '/api/collab/link/$slug' @@ -930,6 +942,7 @@ export interface RootRouteChildren { ApiGithubReposRoute: typeof ApiGithubReposRouteWithChildren ApiSyncPullRoute: typeof ApiSyncPullRoute ApiSyncPushRoute: typeof ApiSyncPushRoute + ApiAuthLinksProviderRoute: typeof ApiAuthLinksProviderRoute ApiDocumentsIdRevisionsRoute: typeof ApiDocumentsIdRevisionsRouteWithChildren ApiGithubPublicationsIdRoute: typeof ApiGithubPublicationsIdRoute ApiSSlugCommentsRoute: typeof ApiSSlugCommentsRouteWithChildren @@ -1301,6 +1314,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiAuthGoogleCallbackRouteImport parentRoute: typeof ApiAuthGoogleRoute } + '/api/auth/links/$provider': { + id: '/api/auth/links/$provider' + path: '/api/auth/links/$provider' + fullPath: '/api/auth/links/$provider' + preLoaderRoute: typeof ApiAuthLinksProviderRouteImport + parentRoute: typeof rootRouteImport + } '/api/auth/verify/resend': { id: '/api/auth/verify/resend' path: '/resend' @@ -1728,6 +1748,7 @@ const rootRouteChildren: RootRouteChildren = { ApiGithubReposRoute: ApiGithubReposRouteWithChildren, ApiSyncPullRoute: ApiSyncPullRoute, ApiSyncPushRoute: ApiSyncPushRoute, + ApiAuthLinksProviderRoute: ApiAuthLinksProviderRoute, ApiDocumentsIdRevisionsRoute: ApiDocumentsIdRevisionsRouteWithChildren, ApiGithubPublicationsIdRoute: ApiGithubPublicationsIdRoute, ApiSSlugCommentsRoute: ApiSSlugCommentsRouteWithChildren, diff --git a/src/routes/api/auth/links.$provider.ts b/src/routes/api/auth/links.$provider.ts new file mode 100644 index 0000000..a7b243c --- /dev/null +++ b/src/routes/api/auth/links.$provider.ts @@ -0,0 +1,10 @@ +import { createFileRoute } from "@tanstack/react-router"; + +export const Route = createFileRoute("/api/auth/links/$provider")({ + server: { + handlers: { + DELETE: async ({ request, params }) => + (await import("@/server/auth/routes")).unlinkHandler(request, params.provider), + }, + }, +}); diff --git a/src/server/auth/github.test.ts b/src/server/auth/github.test.ts index 2f46dcb..36e4671 100644 --- a/src/server/auth/github.test.ts +++ b/src/server/auth/github.test.ts @@ -3,7 +3,8 @@ import { beforeEach, describe, expect, it } from "vitest"; import { createNodeDb } from "../../../infra/db/node"; import { oauthAccounts, users } from "../../../infra/db/schema"; import type { Db } from "../db"; -import { authorizeUrl, githubSignIn, pkcePair } from "./github"; +import { authorizeUrl, githubLink, githubSignIn, pkcePair } from "./github"; +import { linkedProviders } from "./links"; import { signup, userForToken } from "./service"; const cfg = { clientId: "cid", clientSecret: "secret" }; @@ -124,3 +125,39 @@ describe("githubSignIn", () => { }); }); }); + +describe("githubLink", () => { + it("adds the GitHub identity to the signed-in account whatever its email, and signs nobody in", async () => { + const made = await signup( + db, + { email: "me@example.com", password: "a long enough password" }, + now, + ); + if ("error" in made) throw new Error(made.error); + const other = github({ + emails: [{ email: "else@example.org", primary: true, verified: true }], + }); + expect(await githubLink(db, cfg, input, made.user.id, other, now)).toEqual({ ok: true }); + expect(await linkedProviders(db, made.user.id)).toEqual(["github"]); + expect(await db.select().from(users)).toHaveLength(1); + }); + it("reports a failed exchange without linking anything", async () => { + const made = await signup( + db, + { email: "me@example.com", password: "a long enough password" }, + now, + ); + if ("error" in made) throw new Error(made.error); + expect( + await githubLink( + db, + cfg, + input, + made.user.id, + github({ token: { error: "bad_verification_code" } }), + now, + ), + ).toEqual({ ok: false, error: "github_failed" }); + expect(await linkedProviders(db, made.user.id)).toEqual([]); + }); +}); diff --git a/src/server/auth/github.ts b/src/server/auth/github.ts index 0d32b6e..30234cd 100644 --- a/src/server/auth/github.ts +++ b/src/server/auth/github.ts @@ -2,7 +2,8 @@ // are used; the access token is never stored, it lives for the two calls made in the callback. import type { Db } from "../db"; import type { PublicUser } from "./service"; -import { type SocialFailure, socialSignIn } from "./social"; +import { linkSocial } from "./links"; +import { type SocialFailure, type SocialProfile, socialSignIn } from "./social"; export type GithubConfig = { clientId: string; clientSecret: string }; type Failure = { error: "github_failed" } | SocialFailure; @@ -47,13 +48,14 @@ const api = (token: string) => ({ }, }); -export async function githubSignIn( - db: Db, +type Input = { code: string; verifier: string; redirectUri: string }; + +/** Who GitHub says the person is, after the code was exchanged; nothing is stored. */ +async function githubProfile( cfg: GithubConfig, - input: { code: string; verifier: string; redirectUri: string }, - fetchFn: typeof fetch = fetch, - now = Date.now(), -): Promise<{ user: PublicUser; token: string } | Failure> { + input: Input, + fetchFn: typeof fetch, +): Promise { const tokenRes = await fetchFn("https://github.com/login/oauth/access_token", { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, @@ -90,16 +92,36 @@ export async function githubSignIn( const verified = emails.filter((e) => e.verified); const email = (verified.find((e) => e.primary) ?? verified[0])?.email ?? null; - return socialSignIn( - db, - "github", - { - id: String(profile.id), - email, - verified: email !== null, // GitHub only lists addresses it has verified - name: profile.name ?? profile.login ?? null, - avatar: profile.avatar_url ?? null, - }, - now, - ); + return { + id: String(profile.id), + email, + verified: email !== null, // GitHub only lists addresses it has verified + name: profile.name ?? profile.login ?? null, + avatar: profile.avatar_url ?? null, + }; +} + +export async function githubSignIn( + db: Db, + cfg: GithubConfig, + input: Input, + fetchFn: typeof fetch = fetch, + now = Date.now(), +): Promise<{ user: PublicUser; token: string } | Failure> { + const profile = await githubProfile(cfg, input, fetchFn); + return "error" in profile ? profile : socialSignIn(db, "github", profile, now); +} + +/** Adds the person's GitHub identity to the signed-in account (see links.ts). */ +export async function githubLink( + db: Db, + cfg: GithubConfig, + input: Input, + userId: string, + fetchFn: typeof fetch = fetch, + now = Date.now(), +) { + const profile = await githubProfile(cfg, input, fetchFn); + if ("error" in profile) return { ok: false as const, error: profile.error }; + return linkSocial(db, "github", profile, userId, now); } diff --git a/src/server/auth/google.ts b/src/server/auth/google.ts index 22954ba..27d6741 100644 --- a/src/server/auth/google.ts +++ b/src/server/auth/google.ts @@ -3,7 +3,8 @@ // the one call made in the callback. import type { Db } from "../db"; import type { PublicUser } from "./service"; -import { type SocialFailure, socialSignIn } from "./social"; +import { linkSocial } from "./links"; +import { type SocialFailure, type SocialProfile, socialSignIn } from "./social"; export type GoogleConfig = { clientId: string; clientSecret: string }; @@ -37,14 +38,15 @@ export const googleAuthorizeUrl = ( code_challenge_method: "S256", }); -export async function googleSignIn( - db: Db, +type Input = { code: string; verifier: string; redirectUri: string }; + +/** Who Google says the person is, after the code was exchanged; nothing is stored. */ +async function googleProfile( cfg: GoogleConfig, - input: { code: string; verifier: string; redirectUri: string }, - fetchFn: typeof fetch = fetch, - now = Date.now(), + input: Input, + fetchFn: typeof fetch, base?: string, -): Promise<{ user: PublicUser; token: string } | { error: "google_failed" } | SocialFailure> { +): Promise { const urls = googleUrls(base); const failed = { error: "google_failed" } as const; try { @@ -78,19 +80,41 @@ export async function googleSignIn( }; if (typeof profile.sub !== "string" || !profile.sub) return failed; const text = (v: unknown) => (typeof v === "string" && v ? v : null); - return socialSignIn( - db, - "google", - { - id: profile.sub, - email: text(profile.email), - verified: profile.email_verified === true || profile.email_verified === "true", - name: text(profile.name), - avatar: text(profile.picture), - }, - now, - ); + return { + id: profile.sub, + email: text(profile.email), + verified: profile.email_verified === true || profile.email_verified === "true", + name: text(profile.name), + avatar: text(profile.picture), + }; } catch { return failed; // Google unreachable, or an answer that was not JSON } } + +export async function googleSignIn( + db: Db, + cfg: GoogleConfig, + input: Input, + fetchFn: typeof fetch = fetch, + now = Date.now(), + base?: string, +): Promise<{ user: PublicUser; token: string } | { error: "google_failed" } | SocialFailure> { + const profile = await googleProfile(cfg, input, fetchFn, base); + return "error" in profile ? profile : socialSignIn(db, "google", profile, now); +} + +/** Adds the person's Google identity to the signed-in account (see links.ts). */ +export async function googleLink( + db: Db, + cfg: GoogleConfig, + input: Input, + userId: string, + fetchFn: typeof fetch = fetch, + now = Date.now(), + base?: string, +) { + const profile = await googleProfile(cfg, input, fetchFn, base); + if ("error" in profile) return { ok: false as const, error: profile.error }; + return linkSocial(db, "google", profile, userId, now); +} diff --git a/src/server/auth/links.test.ts b/src/server/auth/links.test.ts new file mode 100644 index 0000000..4445d65 --- /dev/null +++ b/src/server/auth/links.test.ts @@ -0,0 +1,89 @@ +// @vitest-environment node +import { eq } from "drizzle-orm"; +import { beforeEach, describe, expect, it } from "vitest"; +import { createNodeDb } from "../../../infra/db/node"; +import { oauthAccounts, users } from "../../../infra/db/schema"; +import type { Db } from "../db"; +import { linkSocial, linkedProviders, unlinkSocial } from "./links"; +import { signup } from "./service"; +import { socialSignIn } from "./social"; + +let db: Db; +let ada: { id: string; email: string }; +const now = 1_700_000_000_000; +const password = "the first long password"; +const profile = (id: string, extra: object = {}) => ({ + id, + email: "someone@elsewhere.example", + verified: true, + name: "Someone", + avatar: "https://img.example/a.png", + ...extra, +}); + +beforeEach(async () => { + db = createNodeDb(":memory:") as unknown as Db; + const r = await signup(db, { email: "ada@example.com", password }, now, { verifyByEmail: false }); + if ("error" in r) throw new Error(r.error); + ada = r.user; +}); + +describe("linkSocial", () => { + it("adds a provider identity even when its email is not the account's", async () => { + expect(await linkSocial(db, "github", profile("gh-1"), ada.id, now)).toEqual({ ok: true }); + expect(await linkedProviders(db, ada.id)).toEqual(["github"]); + // and signing in with it now reaches this account, not a new one + const signed = await socialSignIn(db, "github", profile("gh-1"), now); + if ("error" in signed) throw new Error(signed.error); + expect(signed.user.id).toBe(ada.id); + }); + it("is harmless to repeat, and fills in a name or picture the account lacks, never replacing one", async () => { + await linkSocial(db, "github", profile("gh-1"), ada.id, now); + expect(await linkSocial(db, "github", profile("gh-1"), ada.id, now)).toEqual({ ok: true }); + expect(await db.select().from(oauthAccounts)).toHaveLength(1); + const [row] = await db.select().from(users).where(eq(users.id, ada.id)); + expect(row).toMatchObject({ displayName: "Someone", avatarUrl: "https://img.example/a.png" }); + await db.update(users).set({ displayName: "Ada" }).where(eq(users.id, ada.id)); + await linkSocial(db, "google", profile("g-1", { name: "Other" }), ada.id, now); + expect((await db.select().from(users).where(eq(users.id, ada.id)))[0]?.displayName).toBe("Ada"); + }); + it("refuses an identity that belongs to another account", async () => { + const bob = await signup(db, { email: "bob@example.com", password }, now, { + verifyByEmail: false, + }); + if ("error" in bob) throw new Error(bob.error); + await linkSocial(db, "github", profile("gh-1"), bob.user.id, now); + expect(await linkSocial(db, "github", profile("gh-1"), ada.id, now)).toEqual({ + ok: false, + error: "already_linked", + }); + expect(await linkedProviders(db, ada.id)).toEqual([]); + }); + it("allows one identity per provider: unlink the first to use another", async () => { + await linkSocial(db, "github", profile("gh-1"), ada.id, now); + expect(await linkSocial(db, "github", profile("gh-2"), ada.id, now)).toEqual({ + ok: false, + error: "provider_taken", + }); + }); +}); + +describe("unlinkSocial", () => { + it("removes a provider while the account can still sign in another way", async () => { + await linkSocial(db, "github", profile("gh-1"), ada.id, now); + await linkSocial(db, "google", profile("g-1"), ada.id, now); + expect(await unlinkSocial(db, "github", ada.id)).toEqual({ ok: true }); + expect(await linkedProviders(db, ada.id)).toEqual(["google"]); + }); + it("keeps the last way to sign in", async () => { + await db.update(users).set({ passwordHash: null }).where(eq(users.id, ada.id)); + await linkSocial(db, "github", profile("gh-1"), ada.id, now); + expect(await unlinkSocial(db, "github", ada.id)).toEqual({ ok: false, error: "last_method" }); + await linkSocial(db, "google", profile("g-1"), ada.id, now); + expect(await unlinkSocial(db, "github", ada.id)).toEqual({ ok: true }); + expect(await unlinkSocial(db, "google", ada.id)).toEqual({ ok: false, error: "last_method" }); + }); + it("says so when the provider was not linked", async () => { + expect(await unlinkSocial(db, "github", ada.id)).toEqual({ ok: false, error: "not_linked" }); + }); +}); diff --git a/src/server/auth/links.ts b/src/server/auth/links.ts new file mode 100644 index 0000000..784530a --- /dev/null +++ b/src/server/auth/links.ts @@ -0,0 +1,80 @@ +// The GitHub and Google identities of an account: which are linked, linking another (from a +// signed-in session, whatever email the provider has) and unlinking one. Signing in with a +// provider is in social.ts. +import { and, eq } from "drizzle-orm"; +import { oauthAccounts, users } from "../../../infra/db/schema"; +import type { Db } from "../db"; +import type { SocialProfile, SocialProvider } from "./social"; + +export async function linkedProviders(db: Db, userId: string): Promise { + const rows = await db + .select({ provider: oauthAccounts.provider }) + .from(oauthAccounts) + .where(eq(oauthAccounts.userId, userId)); + return rows.map((r) => r.provider as SocialProvider).sort(); +} + +/** + * Adds the identity to the account. The person is proven twice: signed in here, and signed in at + * the provider just now. An identity belongs to one account, and an account has one per provider. + */ +export async function linkSocial( + db: Db, + provider: SocialProvider, + profile: SocialProfile, + userId: string, + now = Date.now(), +): Promise<{ ok: true } | { ok: false; error: "already_linked" | "provider_taken" }> { + const [known] = await db + .select({ userId: oauthAccounts.userId }) + .from(oauthAccounts) + .where(and(eq(oauthAccounts.provider, provider), eq(oauthAccounts.providerUserId, profile.id))); + if (known) return known.userId === userId ? { ok: true } : { ok: false, error: "already_linked" }; + const [mine] = await db + .select({ id: oauthAccounts.id }) + .from(oauthAccounts) + .where(and(eq(oauthAccounts.userId, userId), eq(oauthAccounts.provider, provider))); + if (mine) return { ok: false, error: "provider_taken" }; + try { + await db.insert(oauthAccounts).values({ + id: crypto.randomUUID(), + userId, + provider, + providerUserId: profile.id, + createdAt: now, + }); + } catch { + return { ok: false, error: "already_linked" }; // two links of one identity raced + } + // a name or picture the account lacks is filled in; one it has is kept + const [row] = await db.select().from(users).where(eq(users.id, userId)); + if (row && (!row.displayName || !row.avatarUrl)) + await db + .update(users) + .set({ + displayName: row.displayName ?? profile.name, + avatarUrl: row.avatarUrl ?? profile.avatar, + updatedAt: now, + }) + .where(eq(users.id, userId)); + return { ok: true }; +} + +/** Removes a provider, unless it is the account's last way to sign in. */ +export async function unlinkSocial( + db: Db, + provider: SocialProvider, + userId: string, +): Promise<{ ok: true } | { ok: false; error: "not_linked" | "last_method" }> { + const linked = await linkedProviders(db, userId); + if (!linked.includes(provider)) return { ok: false, error: "not_linked" }; + const [row] = await db + .select({ passwordHash: users.passwordHash }) + .from(users) + .where(eq(users.id, userId)); + if (!row?.passwordHash && linked.length < 2) return { ok: false, error: "last_method" }; + await db + .delete(oauthAccounts) + .where(and(eq(oauthAccounts.userId, userId), eq(oauthAccounts.provider, provider))); + return { ok: true }; +} diff --git a/src/server/auth/routes.ts b/src/server/auth/routes.ts index b374164..035a11e 100644 --- a/src/server/auth/routes.ts +++ b/src/server/auth/routes.ts @@ -6,8 +6,9 @@ import { endSessions } from "../realtime/publish"; import { getPublicSettings } from "../settings/service"; import { canonicalEmail } from "./email"; import { findForReset, issueReset, resetMail, resetPassword } from "./reset"; -import { authorizeUrl, githubSignIn, pkcePair, randomState } from "./github"; -import { googleAuthorizeUrl, googleSignIn } from "./google"; +import { authorizeUrl, githubLink, githubSignIn, pkcePair, randomState } from "./github"; +import { googleAuthorizeUrl, googleLink, googleSignIn } from "./google"; +import { linkedProviders, unlinkSocial } from "./links"; import { CONNECT_COOKIE, OAUTH_COOKIE, @@ -326,6 +327,16 @@ export async function emailConfirmHandler(request: Request) { return redirect("/settings?tab=account&email_changed=1"); } +/** `DELETE /api/auth/links/github|google`: unlinks a provider, never the last way to sign in. */ +export const unlinkHandler = (request: Request, provider: string) => + withUser(request, async (user, db) => { + if (!sameOrigin(request)) return json({ error: "forbidden" }, 403); + if (provider !== "github" && provider !== "google") return json({ error: "invalid" }, 400); + const result = await unlinkSocial(db, provider, user.id); + if (result.ok) return json({ ok: true }); + return json({ error: result.error }, result.error === "not_linked" ? 404 : 409); + }); + export async function logoutHandler(request: Request) { if (!sameOrigin(request)) return json({ error: "forbidden" }, 403); const token = readToken(request); @@ -359,7 +370,8 @@ export async function meHandler(request: Request) { }; if (!session || !token) return json({ user: null, providers }); // Re-issue the cookie so the browser keeps it exactly as long as the (sliding) session lives. - return json({ user: session.user, providers }, 200, { + const linked = await linkedProviders(await getDb(request), session.user.id); + return json({ user: { ...session.user, linked }, providers }, 200, { "set-cookie": sessionCookie(token, protocol(request), session.expiresAt - Date.now()), }); } @@ -382,14 +394,30 @@ const redirect = (to: string, ...cookies: string[]) => { return new Response(null, { status: 302, headers }); }; +/** Where a social flow ends: the editor to sign in, the account settings to link (`.link` mode). */ +const LINK_BACK = "/settings?tab=account"; + +/** A link flow starts only from a signed-in session; this answers who, or null. */ +async function linkingUser(request: Request) { + const token = readToken(request); + const session = token ? await userForToken(await getDb(request), token) : null; + return session?.user ?? null; +} + export async function githubStartHandler(request: Request) { + const link = new URL(request.url).searchParams.get("link") === "1"; const cfg = githubConfig(request); - if (!cfg) return redirect("/editor?auth_error=github_unavailable"); + if (!cfg) + return redirect( + link ? `${LINK_BACK}&auth_error=github_unavailable` : "/editor?auth_error=github_unavailable", + ); + if (link && !(await linkingUser(request))) + return redirect(`${LINK_BACK}&auth_error=unauthorized`); const { verifier, challenge } = await pkcePair(); const state = randomState(); return redirect( authorizeUrl(cfg, redirectUri(request), state, challenge), - oauthCookie(`${state}.${verifier}`, protocol(request), 10 * 60 * 1000), + oauthCookie(`${state}.${verifier}${link ? ".link" : ""}`, protocol(request), 10 * 60 * 1000), ); } @@ -403,11 +431,27 @@ export async function githubCallbackHandler(request: Request) { const connecting = readCookie(request, CONNECT_COOKIE); if (connecting && connecting.split(".")[0] === params.get("state")) return (await import("../github/routes")).connectCallbackHandler(request); - const [state, verifier] = readCookie(request, OAUTH_COOKIE)?.split(".") ?? []; + const [state, verifier, mode] = readCookie(request, OAUTH_COOKIE)?.split(".") ?? []; const code = params.get("code"); // The state in the URL must be the one this browser was given, or the callback was forged. if (!cfg || !state || !verifier || !code || params.get("state") !== state) - return fail("github_failed"); + return mode === "link" + ? redirect(`${LINK_BACK}&auth_error=github_failed`, clear) + : fail("github_failed"); + if (mode === "link") { + const user = await linkingUser(request); + if (!user) return redirect(`${LINK_BACK}&auth_error=unauthorized`, clear); + const linked = await githubLink( + await getDb(request), + cfg, + { code, verifier, redirectUri: redirectUri(request) }, + user.id, + ); + return redirect( + linked.ok ? `${LINK_BACK}&linked=github` : `${LINK_BACK}&auth_error=${linked.error}`, + clear, + ); + } const result = await githubSignIn(await getDb(request), cfg, { code, verifier, @@ -429,8 +473,14 @@ const googleRedirectUri = (request: Request) => `${getEnv(request, "PUBLIC_URL")?.replace(/\/$/, "") ?? new URL(request.url).origin}/api/auth/google/callback`; export async function googleStartHandler(request: Request) { + const link = new URL(request.url).searchParams.get("link") === "1"; const cfg = googleConfig(request); - if (!cfg) return redirect("/editor?auth_error=google_unavailable"); + if (!cfg) + return redirect( + link ? `${LINK_BACK}&auth_error=google_unavailable` : "/editor?auth_error=google_unavailable", + ); + if (link && !(await linkingUser(request))) + return redirect(`${LINK_BACK}&auth_error=unauthorized`); const { verifier, challenge } = await pkcePair(); const state = randomState(); return redirect( @@ -441,21 +491,44 @@ export async function googleStartHandler(request: Request) { challenge, getEnv(request, "GOOGLE_URL"), ), - oauthCookie(`${state}.${verifier}`, protocol(request), 10 * 60 * 1000, "google"), + oauthCookie( + `${state}.${verifier}${link ? ".link" : ""}`, + protocol(request), + 10 * 60 * 1000, + "google", + ), ); } export async function googleCallbackHandler(request: Request) { const cfg = googleConfig(request); const clear = oauthCookie("", protocol(request), 0, "google"); - const fail = (code: string) => redirect(`/editor?auth_error=${code}`, clear); const params = new URL(request.url).searchParams; - const [state, verifier] = readCookie(request, OAUTH_COOKIE)?.split(".") ?? []; + const [state, verifier, mode] = readCookie(request, OAUTH_COOKIE)?.split(".") ?? []; + const fail = (code: string) => + redirect( + mode === "link" ? `${LINK_BACK}&auth_error=${code}` : `/editor?auth_error=${code}`, + clear, + ); // The state in the URL must be the one this browser was given, or the callback was forged. if (!cfg || !state || !verifier || params.get("state") !== state) return fail("google_failed"); const code = params.get("code"); if (params.get("error") === "access_denied") return fail("google_denied"); if (!code) return fail("google_failed"); + if (mode === "link") { + const user = await linkingUser(request); + if (!user) return fail("unauthorized"); + const linked = await googleLink( + await getDb(request), + cfg, + { code, verifier, redirectUri: googleRedirectUri(request) }, + user.id, + fetch, + Date.now(), + getEnv(request, "GOOGLE_URL"), + ); + return linked.ok ? redirect(`${LINK_BACK}&linked=google`, clear) : fail(linked.error); + } const result = await googleSignIn( await getDb(request), cfg, From e6fc13cbe03e302e077bdbb1c45bccaf9e4db25a Mon Sep 17 00:00:00 2001 From: Chizoba Jude Ojini Date: Sat, 14 Nov 2026 19:36:27 +0000 Subject: [PATCH 08/12] feat(search): add a search palette for drafts, commands, settings and pages (#111) * feat(search): add a search palette for drafts, commands, settings and pages * feat(search): open search by shortcut on the home page too --- docs/SYSTEM_SPEC.md | 1 + docs/UI_SPEC.md | 4 + e2e/search.spec.ts | 92 +++++++++++++ src/components/search/SearchButton.tsx | 19 +++ src/components/search/SearchHost.tsx | 32 +++++ src/components/search/SearchPalette.tsx | 155 ++++++++++++++++++++++ src/components/settings/SettingsPage.tsx | 2 + src/components/site/SiteHeader.tsx | 6 +- src/components/studio/ShortcutsDialog.tsx | 3 +- src/components/studio/Studio.tsx | 137 ++++++++++++++----- src/lib/search/entries.test.ts | 72 ++++++++++ src/lib/search/entries.ts | 95 +++++++++++++ src/lib/search/rank.test.ts | 77 +++++++++++ src/lib/search/rank.ts | 83 ++++++++++++ src/lib/search/registry.test.ts | 37 ++++++ src/lib/search/registry.ts | 52 ++++++++ src/lib/settings/catalog.ts | 22 +++ src/routes/__root.tsx | 2 + 18 files changed, 858 insertions(+), 33 deletions(-) create mode 100644 e2e/search.spec.ts create mode 100644 src/components/search/SearchButton.tsx create mode 100644 src/components/search/SearchHost.tsx create mode 100644 src/components/search/SearchPalette.tsx create mode 100644 src/lib/search/entries.test.ts create mode 100644 src/lib/search/entries.ts create mode 100644 src/lib/search/rank.test.ts create mode 100644 src/lib/search/rank.ts create mode 100644 src/lib/search/registry.test.ts create mode 100644 src/lib/search/registry.ts create mode 100644 src/lib/settings/catalog.ts 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() { + ); } From 63968ea6c765dffc80b0cd13dc727b894a5318bd Mon Sep 17 00:00:00 2001 From: Chizoba Jude Ojini Date: Sun, 15 Nov 2026 19:00:51 +0000 Subject: [PATCH 09/12] feat(ui): polish the app frames, left panel strip and loading states - Studio: panel, drafts, search, theme, settings and account buttons move to a left strip; one docked left pane; Export/Publish and Share choosers merged; profile selector and view switch in the header; trimmed draft menu - Shared frames for Settings and Admin (left menu), standalone sign-in, reset and error screens, guides and legal pages with a scrolling contents list, new public header and footer - Review page: bar, text and footer share one width, centred until comments are showing, delete-comment indicator - Every action button shows a loading state (pressed) or pending (siblings); guard test added - Shared Select for every dropdown, new Switch, no ellipsis in action labels - Docs and e2e updated --- docs/DESIGN_SYSTEM.md | 11 +- docs/SYSTEM_SPEC.md | 2 +- docs/UI_SPEC.md | 45 ++-- e2e/admin.spec.ts | 2 +- e2e/ai-edit.spec.ts | 10 +- e2e/collab-comments.spec.ts | 2 + e2e/collab-people.ts | 6 +- e2e/draft.ts | 8 +- e2e/github-ui.spec.ts | 4 +- e2e/guides.spec.ts | 44 ++++ e2e/home.spec.ts | 17 +- e2e/images-ui.spec.ts | 2 +- e2e/protection.spec.ts | 4 +- e2e/reset.spec.ts | 2 +- e2e/review-page.spec.ts | 83 +++++++ e2e/search.spec.ts | 9 +- e2e/settings.spec.ts | 20 +- e2e/share-ui.spec.ts | 20 +- e2e/studio.spec.ts | 93 ++++++-- src/components/admin/AdminPage.tsx | 97 +++------ src/components/admin/AuditTab.tsx | 2 +- src/components/admin/LimitsEditor.tsx | 2 +- src/components/admin/OverviewTab.tsx | 4 +- src/components/admin/PlansTab.tsx | 14 +- src/components/admin/SettingsTab.tsx | 3 +- src/components/admin/UserDialog.tsx | 39 ++-- src/components/admin/UsersTab.tsx | 11 +- src/components/admin/bits.tsx | 18 +- src/components/settings/AccountSection.tsx | 171 ++++++++------- src/components/settings/AiSection.tsx | 19 +- .../settings/ConnectionsSection.tsx | 98 +++++---- src/components/settings/EditorSection.tsx | 126 ++++++----- src/components/settings/SettingsPage.tsx | 84 +++----- src/components/settings/SettingsRow.tsx | 6 +- src/components/share/Comments.tsx | 67 ++++-- src/components/share/OpenInvite.tsx | 52 +++-- src/components/site/AppShell.tsx | 125 +++++++++++ src/components/site/DocLayout.tsx | 99 +++++++++ src/components/site/LegalPage.tsx | 44 +++- src/components/site/SiteFooter.tsx | 38 ++-- src/components/site/SiteHeader.tsx | 85 +++++--- src/components/site/SitePieces.tsx | 47 ++++ src/components/site/Standalone.tsx | 69 ++++++ src/components/studio/AccountMenu.tsx | 27 ++- src/components/studio/AiEditDialog.tsx | 5 +- .../studio/AiIntegrationsDialog.tsx | 5 +- src/components/studio/AiMenuItems.tsx | 2 +- src/components/studio/AiPicker.tsx | 9 +- src/components/studio/AiWriter.tsx | 9 +- src/components/studio/CollabDialog.tsx | 15 +- src/components/studio/EditorToolbar.tsx | 2 +- src/components/studio/HistoryPanel.tsx | 28 ++- src/components/studio/Library.tsx | 16 +- src/components/studio/ManageImages.tsx | 15 +- src/components/studio/MarkdownEditor.tsx | 1 + src/components/studio/ReviewComments.tsx | 22 +- src/components/studio/RulesDialog.tsx | 31 +-- src/components/studio/ShareChooser.tsx | 73 +++++++ src/components/studio/ShareDialog.tsx | 19 +- src/components/studio/Studio.tsx | 204 ++++++++++++------ src/components/ui/loading-rules.test.ts | 55 +++++ src/components/ui/switch.test.tsx | 38 ++++ src/components/ui/switch.tsx | 9 +- src/lib/ai/actions.ts | 4 +- src/lib/site/render-toc.ts | 13 ++ src/lib/ui/layout.ts | 3 - src/routes/README.md | 20 +- src/routes/__root.tsx | 51 ++--- src/routes/guides.$slug.tsx | 103 ++++----- src/routes/guides.index.tsx | 34 +-- src/routes/index.tsx | 6 +- src/routes/privacy.tsx | 7 +- src/routes/reset-password.tsx | 19 +- src/routes/s.$slug.tsx | 124 ++++++----- src/routes/terms.tsx | 7 +- src/styles.css | 5 +- 76 files changed, 1826 insertions(+), 859 deletions(-) create mode 100644 src/components/site/AppShell.tsx create mode 100644 src/components/site/DocLayout.tsx create mode 100644 src/components/site/SitePieces.tsx create mode 100644 src/components/site/Standalone.tsx create mode 100644 src/components/studio/ShareChooser.tsx create mode 100644 src/components/ui/loading-rules.test.ts create mode 100644 src/components/ui/switch.test.tsx create mode 100644 src/lib/site/render-toc.ts diff --git a/docs/DESIGN_SYSTEM.md b/docs/DESIGN_SYSTEM.md index 42fd582..512a69e 100644 --- a/docs/DESIGN_SYSTEM.md +++ b/docs/DESIGN_SYSTEM.md @@ -35,16 +35,21 @@ Radius: `--radius: 0.5rem` (sm/md/lg/xl derived). Shadows: minimal, soft; prefer ## Components (shadcn variants) - Button: `default` (primary), `secondary` (active toggle), `ghost` (toolbar icons, 40×40 touch targets on mobile), `outline`, `destructive`. -- Dialog (AI writer, delete confirmation), Sheet (library and panels below 1280px), DropdownMenu (export), Select (profile, provider), Tabs, Tooltip, Input/Textarea/Label, Switch (normalize), Sonner toasts. Only these shadcn components are kept in `src/components/ui/`; add new ones when a feature needs them. +- Dialog (AI writer, delete confirmation), Sheet (library and panels below 1280px), DropdownMenu (export), Select (profile, provider), Tabs, Tooltip, Input/Textarea/Label, Switch (normalize; 44×24px, the accent track when on and a muted track when off, a knob in its own colours that never takes the page background), Sonner toasts. Only these shadcn components are kept in `src/components/ui/`; add new ones when a feature needs them. - Icons: lucide-react, 16px in toolbars. +## Page frames +- **Public pages** (`SiteHeader`, `SiteFooter`, `SitePieces`): content up to 1200px; tiles are `border bg-muted`, chips are small labels (`accent`, `line`, `warn`), a call to action is a band on `bg-accent`. Reading pages (guides, legal) use `DocLayout`: a sticky contents column on the left from 1280px. +- **App pages** (`AppShell`: Settings, Admin): a top bar on the page background with the same hairline as the public header (its contents the width of the page's content; **Back to the editor** is the primary button, the account a ghost icon), a menu of sections on the left (the active one on `bg-accent` with the primary along its left edge; chips on phones), a title with a line under it, and rows grouped in bordered cards on `bg-card` (a light lift off the page; the controls inside are outlines on the card's own colour, not darker wells). +- **Standalone screens** (`Standalone`: private-link gate, invitation, password reset, 404, load error): a bar like the app pages' (page background, primary Open the editor), and a centred bordered `bg-card` box. + ## Preview styling (`.md-preview`) GitHub-like prose on `bg-paper`: max-width ~72ch, headings in Fraunces, links primary with underline, blockquote left border `border`, tables bordered with zebra `muted`, code `code-bg` + mono, task-list checkboxes, images max-width 100%. ## Layout & breakpoints - `< 768px` phone: single pane (Editor / Preview toggle), horizontally scrollable toolbar, panel buttons in a bottom nav, library and panels in sheets, condensed status bar. -- `768-1279px`: split view with scroll sync; the library opens as a left sheet and the panels as a right sheet. -- `>= 1280px` desktop: docked library sidebar (about 240px, collapsible) | editor | preview (scroll-synced) | docked side panel (about 288px, Checks/Outline/Front matter). +- `768-1279px`: split view with scroll sync; the library and the panels open as a sheet from the left. +- `>= 1280px` desktop: panel buttons (48px) | one docked pane (288px, resizable; the library or the chosen panel) | editor | preview (scroll-synced). Nothing docks on the right. - Focus mode: hides chrome, centers the editor. - Touch targets >= 40px on phones (toolbar buttons shrink to 36px from 768px up, where a pointer is the norm); dialogs scroll within the viewport. diff --git a/docs/SYSTEM_SPEC.md b/docs/SYSTEM_SPEC.md index 70d33d1..f228335 100644 --- a/docs/SYSTEM_SPEC.md +++ b/docs/SYSTEM_SPEC.md @@ -669,7 +669,7 @@ CREATE TABLE share_comments ( -- plain text, one level of replies - _Linking social sign-ins_ (`src/server/auth/social.ts`, shared by GitHub and Google): the provider's own id (`oauth_accounts`, unique per provider) is the identity, never the email. A known identity signs in (a suspended account is refused). Otherwise the provider must report the email as verified (`no_verified_email`). An account with that inbox (`emailKey`) gets the identity added and is signed in, so Google plus GitHub with one email, or a password account plus either, is one account; a suspended account is refused and nothing is linked. When that account's address was never confirmed, its password, sessions and pending links are removed first (whoever pre-registered it may not own the address), and the address counts as confirmed. With no such account a new confirmed, password-less one is made unless sign-ups are closed (`signups_closed`); the user row and its identity are removed together if the second insert fails. Different emails make different accounts. Password sign-up with an existing email answers `email_taken`, whose message points to the social buttons and "Forgot password" without saying which method the account uses. - _Limits_ (table `rate_limits`, fixed windows, the same SQL on D1 and SQLite): 5 sign-ups per hour per address, 10 failed sign-ins per 15 minutes per email and per address (locked out until the window ends, before any password work, and a success clears the email's count), 3 confirmation emails per hour per account. The address is `cf-connecting-ip`, or `X-Forwarded-For` only when `TRUST_PROXY` is set, since any client can send that header; with neither, only the per-email limits apply. - _Mail providers:_ `src/server/mail/` sends through a chain of providers (Resend and Mailtrap over HTTP anywhere; SMTP or a folder of JSON files on Node). Each has its free-tier limits (per UTC day and month) in a registry (`providers.ts`; adding one is one entry plus a small sender), counted in `rate_limits` only for sends that succeeded. A send goes to the provider with the most room left, skips any that is full, and falls through to the next on a failure; a provider that fails is left alone for 5 minutes, and a 429 marks it full for the day. `MAIL_PROVIDERS` orders or limits them, `MAIL__DAILY`/`_MONTHLY` override the limits. No provider configured means no mail. -- _Email confirmation:_ when the server can send mail, a password account starts unconfirmed and **nothing is sent at sign-up**: the first time the account tries the cloud (a draft's "Save to cloud" or the account menu's "Choose drafts for the cloud…") the app opens a "Confirm your email" dialog that sends the link, and opening it again sends nothing while that link is still good ("Send it again" forces one). People who only write locally never cost a message. Until the link is used the cloud (sync and image hosting) answers 403 `email_unverified`. The one-time link (hash stored, 24 hours, single use, valid only for the address it was sent to) is used. GitHub and Google accounts count as confirmed. A server that sends no mail confirms nothing and blocks nothing. A failed send shows in the dialog, which offers to try again. +- _Email confirmation:_ when the server can send mail, a password account starts unconfirmed and **nothing is sent at sign-up**: the first time the account tries the cloud (a draft's "Save to cloud" or the account menu's "Choose drafts for the cloud") the app opens a "Confirm your email" dialog that sends the link, and opening it again sends nothing while that link is still good ("Send it again" forces one). People who only write locally never cost a message. Until the link is used the cloud (sync and image hosting) answers 403 `email_unverified`. The one-time link (hash stored, 24 hours, single use, valid only for the address it was sent to) is used. GitHub and Google accounts count as confirmed. A server that sends no mail confirms nothing and blocks nothing. A failed send shows in the dialog, which offers to try again. - _Email design and retries:_ confirmation and reset mail are sent as plain text plus a designed HTML version (`src/server/mail/template.ts`): the warm paper palette as hex with a dark version for clients that follow the reader's setting, the link also written out under the button, and nothing loaded from the network (no images, fonts or trackers). If sending a confirmation fails, its link is removed again, so the next request tries a second time; once a send succeeds, later requests answer "already sent" until the link is used or expires. - _Password reset:_ "Forgot your password?" in the sign-in dialog (shown only when the server can send mail) asks for the address and always answers "if an account exists, we sent a link", so it cannot reveal who has one: unknown addresses and inboxes already sent 3 links in the hour are answered identically, the mail is sent after the response goes out (`waitUntil` on Workers), and the same sign-up CAPTCHA applies. The link points to a page (`/reset-password`, noindex), not to a state-changing GET, so mail scanners that open links cannot use it up; the page takes the token out of the address bar. A link lasts an hour, works once, is stored only as a hash, is tied to the address it was sent to and to its purpose (a confirmation link cannot reset a password, nor the reverse), and a new request replaces the older one. A weak password is refused without using the link up. Resetting sets the password (so a GitHub-only account can also gain one), deletes every session of the account and its other pending links, sets the address as confirmed (the person just read mail sent to it) and lifts a sign-in lockout. It does not sign anyone in. - _Changing the address:_ Settings, Account, Email, Edit asks for the new address and the current password and emails a link to the NEW address (purpose `email_change`, 24 hours, once, stored as a hash like the others, a newer request replaces the older one, 3 an hour per account). Nothing changes until the link is opened, so a mistyped address cannot lock anyone out, and the old address keeps working meanwhile. The current password is required so a stolen session cannot move the account to another inbox; an account with no password (GitHub or Google only) sets one first, and wrong guesses share the password limit. It needs a server that sends mail, since the new address must be proven. Opening the link (`GET /api/auth/email/confirm`, which redirects to the Account tab) sets `users.email` and `email_key` (the unique key decides if someone took the address meanwhile), marks it confirmed, ends the account's other sessions (the browser that opened the link stays signed in when it holds one of them), re-keys invitations held under the old inbox (`document_editors`, `share_people`; a row that would duplicate one already under the new address is dropped) so shared and live drafts keep opening, and emails a notice to the old address. diff --git a/docs/UI_SPEC.md b/docs/UI_SPEC.md index b0197d3..f2b920f 100644 --- a/docs/UI_SPEC.md +++ b/docs/UI_SPEC.md @@ -5,30 +5,30 @@ Items marked **(planned)** are specified but not built yet. ## 1. Landing `/` — `01_home_page.png`, `08_home_checker_demo.png` -Header: the `Logo` (two-pages mark plus the **md**studio wordmark, linking home), a theme button (each click goes Light, Dark, System and round again; its icon and label show the current choice) and a GitHub link (opens the repository in a new tab). Sections, top to bottom: +Header (`SiteHeader`, shared by the public pages, content up to 1200px wide): the `Logo` (two-pages mark plus the **md**studio wordmark, linking home), the links Features (`/#features`) and Guides (marked while on the guides), then a Settings icon and **Open the editor** (no search, theme or repository links here). (The theme is chosen in Settings, or with the button in the editor's side strip: each click goes Light, Dark, System and round again.) Below 768px the links fold into a Menu button. The changelog (on GitHub) is linked from the footer; self-hosting is in the README. Sections, top to bottom: - **Hero:** "Write once. Render the same everywhere.", a short description, a primary "Start writing" button to `/editor`, a "Try the checker" anchor, and a decorative (`aria-hidden`) editor/preview mock. The page has exactly one `h1`. - **How it works:** Write, Check, Export. - **Live checker demo** (`#try-it`): the real portability engine, lazy-loaded behind `ClientOnly`. An editable sample, four target pills with live issue counts, and a clickable report that selects the offending line. -- **Features** (six cards), **target profiles** (four cards), **About** and **Who it's for**, an eight-question **FAQ** (native `details`, mirrored in FAQPage JSON-LD), a closing call to action, and a footer (copyright and author on the left, GitHub and Changelog on the right). +- **Features** (six cards), **target profiles** (four cards), **About** and **Who it's for**, an eight-question **FAQ** (native `details`, mirrored in FAQPage JSON-LD), a closing call to action, and the footer (`SiteFooter`, in two groups: "mdstudio · version · MIT" on the left; Guides, Privacy, Terms and Changelog on the right). - **Theme:** an inline head script applies the saved or OS theme before first paint; the theme button also lives in the studio header. "System" forgets any saved choice and follows the OS, including when it switches while the page is open; Light and Dark are remembered on this device and ignore the OS. ## 1a. Privacy and Terms `/privacy`, `/terms` -Plain text pages in the site layout (header, footer), with the title and "Last updated" date, linked from the footer. Public and indexable. +Text pages in the site layout (header, footer), in the same reading layout as a guide (`DocLayout`): the page's sections listed in a sticky column on the left (from 1024px; below that there is no room beside the text and it is hidden, and the text is centred), with the section being read marked as the page scrolls, and beside it a Privacy | Terms switch, the title and "Last updated" date. Linked from the footer. Public and indexable. ## 1b. Guides `/guides` and `/guides/$slug` -Shared `SiteHeader` and `SiteFooter` (the footer links to Guides, the source and the changelog). The index lists every guide with its description and update date. A guide page has breadcrumbs, the title as the single `h1`, an "Updated … · N min read" line, an "On this page" list of section links, the article (`.md-preview`), a call to action to open the editor, and three related guides. Unknown slugs return a real 404. The home page links to the first three guides. +Shared `SiteHeader` and `SiteFooter` (the footer has "mdstudio · version · MIT" on the left and Guides, Privacy, Terms and Changelog on the right). The index has a large "Markdown guides" heading and every guide as a tile (update date chip, title, description; the whole tile is the link). A guide page (`DocLayout`) has the "On this page" list in a sticky column on the left (from 1024px, hidden below, where the text is centred; the section being read is marked as the page scrolls), breadcrumbs, the title as the single `h1`, an "Updated … · N min read" line, the article (`.md-preview`), a call to action to open the editor on a tinted band, and three related guides as tiles. Unknown slugs return a real 404. The home page links to the first three guides. ## 1c. Sharing from the editor — `14_share_dialog.png`, `15_comments_panel.png` -For a draft in the cloud (verified accounts only), the draft's menu has **Share…** and the header has a **Share** button (an icon on small screens). A small globe next to the cloud icon marks drafts that have a live link (a lock when only named people can open it). The Share dialog (`ShareDialog.tsx`) has two states: +For a draft in the cloud (verified accounts only), the draft's menu has **Share** and the header has a **Share** button (an icon below 1024px); both open the "Share this draft" choice described in the top bar, and its **Share for review** leads to the dialog below. A small globe next to the cloud icon marks drafts that have a live link (a lock when only named people can open it). The Share dialog (`ShareDialog.tsx`) has two states: - **Not shared:** "Who can open it" (Anyone with the link, or Only people I invite, which is off where the server turns private links off), a "Let reviewers comment" switch (both are chosen before publishing, so a private link is never public first), a "Link lasts" choice (1 to 7 days, 4 by default), a note that the page shows the text as it is in the cloud when published and that later edits stay private until an update, a note about images stored only on this device when the draft has any, and **Publish**. - **Shared:** the link ("Public link" or "Private link") in a read-only field with **Copy**, "Who can open it" and "Let reviewers comment" (a change is saved at once), for a private link a **People who can open it** list (invite by email with **Invite**, up to 10, remove with the ✕ beside an address; adding an address emails it once), the publish and expiry dates, "Link lasts" (changing it sets the expiry that many days from now), a warning "Your draft has changes that are not published" when the draft differs from the published copy, **Publish update** (enabled only then) and **Stop sharing**. Publishing saves the draft and runs a sync first, so the copy is the latest text. Buttons show the loading state while a request runs; errors (not in the cloud yet, too many changes, offline, a full or unusable invite) appear in the dialog. -**Editing together.** A cloud draft's menu also has **Edit together…** (`CollabDialog.tsx`). Before it is on, the dialog says what it does and has **Start editing together** (it saves the draft and runs a sync first, so the room starts from the latest text); where the server or the account does not allow it, it says so. Once on, it has **People who can edit** (invite by email with **Invite**, up to the account's limit counting the owner, remove with the ✕ beside an address) and **Stop editing together** (the draft keeps its latest text, everyone invited is let go). While it is on, the dialog also shows the **Draft link** (read-only, with **Copy**) that the invitation emails carry. A draft being edited together has a people icon in the list. The footer of such a draft (`CollabStatus.tsx`) says **Live**, **Offline: your edits are kept here and will merge** or **Opening the shared draft…**, with a small avatar for each other person in it (their cursor colour, name on hover). +**Editing together.** **Edit together** is the second choice of **Share** (`CollabDialog.tsx`). Before it is on, the dialog says what it does and has **Start editing together** (it saves the draft and runs a sync first, so the room starts from the latest text); where the server or the account does not allow it, it says so. Once on, it has **People who can edit** (invite by email with **Invite**, up to the account's limit counting the owner, remove with the ✕ beside an address) and **Stop editing together** (the draft keeps its latest text, everyone invited is let go). While it is on, the dialog also shows the **Draft link** (read-only, with **Copy**) that the invitation emails carry. A draft being edited together has a people icon in the list. The footer of such a draft (`CollabStatus.tsx`) says **Live**, **Offline: your edits are kept here and will merge** or **Opening the shared draft…**, with a small avatar for each other person in it (their cursor colour, name on hover). The invitation email's **Open the draft** button leads to `/c/
`: a page that asks for a sign-in if needed (with the invited address, creating an account is offered), then opens the draft; anyone not invited sees "You can't open this draft". Invitations and removals show up in **Shared with you** at once, without a reload. An invited person finds the draft under **Shared with you** at the bottom of their library (read when the studio opens and when the window returns; it shows who owns each draft). Opening one makes a local copy and opens it in the live editor; **Leave** (the exit icon, with a confirmation) removes it. These drafts are not in the person's own list, do not count against their cloud limit, are never uploaded, and leave the device at sign-out with what the browser kept of them. When the owner removes the person, stops editing together or deletes the draft, the open draft says so ("You can no longer edit …", with a line that changes made while offline stay on this device only; while the studio checks, because the room keeps turning the browser away, the footer says "Can't reach the room. Checking your access…") and stays on the device as an ordinary draft with its latest text. In the admin dashboard, the Overview shows how many drafts are edited together and how many people are invited, and the Server tab has the switch **Editing together is open**. @@ -40,15 +40,15 @@ A draft in the cloud also gets a **Comments** panel (speech-bubble button beside ## 1d. Shared page `/s/$slug` — `16_shared_page_comments.png`, `17_shared_page_phone.png`, `18_private_link_gate.png` -A public, read-only page for one published copy of a draft. The site header, a one-line notice ("A copy shared with mdstudio on . Available until . Report this page"), the text in `.md-preview` (single column, up to `max-w-3xl`, readable at 360px with no sideways scroll) and the site footer. Math and Mermaid diagrams are drawn in the browser after load, in the colors of the theme in use. An unknown, expired or revoked link is the site's 404 page. +A public, read-only page for one published copy of a draft. Its own top bar (logo, a "Shared for review" or "Shared copy" chip, the theme button and **Open the editor**), the text and the footer all in one width: wide enough for the comments column while it shows beside the text with something in it, and just the text, centred, when the comments are hidden, there are none yet, or they sit below it (the bar and the footer narrow with it; the page starts narrow and widens when the first comment or notice appears), a meta line ("A copy shared with mdstudio on . Available until ."), the text in `.md-preview` (readable at 360px with no sideways scroll; the comments sit in a column beside it when the writer takes them and the window is wide, below it on narrow screens), "Made with mdstudio · Report this page" under the text, and the site footer. Math and Mermaid diagrams are drawn in the browser after load, in the colors of the theme in use. An unknown, expired or revoked link is the site's 404 page. -**Private links.** A signed-out reader of a link limited to named people sees a lock, "This document is private" and a **Sign in** button, and none of the text; the page is `noindex`, `no-store`. The small sign-in dialog (`ReaderSignIn`: sign in or create an account, with a show/hide password button and the sign-up CAPTCHA when the server has one) leaves them on the page, which reloads for them. Someone signed in who was not invited gets the 404 page. An open private page adds "Only the people the writer named can open this." +**Private links.** A signed-out reader of a link limited to named people sees a standalone screen (logo and **Open the editor** above, a centred box): a "Private review link" chip, "This document is private" and a **Sign in** button, and none of the text; the page is `noindex`, `no-store`. The small sign-in dialog (`ReaderSignIn`: sign in or create an account, with a show/hide password button and the sign-up CAPTCHA when the server has one) leaves them on the page, which reloads for them. Someone signed in who was not invited gets the 404 page. An open private page adds "Only the people the writer named can open this." -**Comments** (when the writer turned them on), as in a document review. A reader selects words on the page and a **Comment** button appears beside the selection; pressing it opens a box in the column beside the page (a bottom sheet under 1024px) with the selected words quoted. The words stay highlighted, and each comment card sits level with its words, pushed down so cards never overlap. Clicking a highlight shows its comment and clicking a card scrolls to its words. **Hide comments** (a floating button, or the ✕ on the sheet) hides the column and **Comments (n)** shows it again, as does a click on any highlight. A signed-out reader is told "The writer is taking comments" with **Sign in to read and write comments**; a signed-in reader whose email is not confirmed is asked to confirm it. Cards show the author's name, the date, an "Earlier version" tag for comments written on an older copy, a "Resolved" tag, **Reply**, and **Delete** (with a confirmation) on the reader's own comments. A comment whose words or block are gone from the current copy stays in the column, marked as being on an earlier version, without a highlight. Text is shown as plain text. The locked private-link page keeps the footer at the bottom of the window. +**Comments** (when the writer turned them on), as in a document review. A reader selects words on the page and a **Comment** button appears beside the selection; pressing it opens a box in the column beside the page (a bottom sheet under 1024px) with the selected words quoted. The words stay highlighted, and each comment card sits level with its words, pushed down so cards never overlap. Clicking a highlight shows its comment and clicking a card scrolls to its words. **Hide comments** (a floating button, or the ✕ on the sheet) hides the column and **Comments (n)** shows it again, as does a click on any highlight. A signed-out reader is told "The writer is taking comments" with **Sign in to read and write comments**; a signed-in reader whose email is not confirmed is asked to confirm it. Cards show the author's name, the date, an "Earlier version" tag for comments written on an older copy, a "Resolved" tag, **Reply**, and **Delete** (with a confirmation) on the reader's own comments; while one is being deleted it is dimmed and its "Deleting" button shows a spinner. A comment whose words or block are gone from the current copy stays in the column, marked as being on an earlier version, without a highlight. Text is shown as plain text. The locked private-link page keeps the footer at the bottom of the window. ## 1e. Publishing to GitHub — `19_publish_connect.png`, `20_publish_github.png` -For a draft in the cloud, on a server that can publish (`githubPublish` in `/api/auth/me`), the draft's menu has **Publish to GitHub…** and the header has a **Publish** button (the GitHub icon alone below the xl breakpoint). The dialog (`PublishDialog.tsx`) reads from the server only when it opens or a choice needs it: the connection, what was published before, and the repositories. Nothing is requested in the background. +For a draft in the cloud, on a server that can publish (`githubPublish` in `/api/auth/me`), the draft's menu has **Publish** and the header's **Export** button becomes **Publish** (its menu starts with Publish to GitHub). The dialog (`PublishDialog.tsx`) reads from the server only when it opens or a choice needs it: the connection, what was published before, and the repositories. Nothing is requested in the background. - **Not connected:** an explanation, **Also allow private repositories** (off by default: only public repositories and gists are reachable), a note that an organization may need to approve mdstudio, and **Connect GitHub**. It leaves for GitHub and returns to the editor, which reopens this dialog on the same draft. - **Connected:** "Connected as ", **Allow private repositories** (when they were not allowed) and **Disconnect**, then two tabs. @@ -62,14 +62,17 @@ For a draft in the cloud, on a server that can publish (`githubPublish` in `/api **First visit and empty library.** `/editor` opens the first draft on the machine (or in the signed-in account). With none, it opens `/editor/new`, held in memory only and saved, under its own address, when the writer first types. On a first visit that is the example text; once this browser has ever stored a draft (a flag kept beside the drafts), it is a completely blank editor, so deleting the last draft, or reloading after it, never brings the example back. Until something is typed nothing is stored, so signing in with drafts in the cloud replaces either with those drafts. "New draft" always starts empty. -**Buttons.** Every enabled button, tab, menu item and switch shows a pointer cursor (a base rule in `src/styles.css`). `Button` has two busy states: `pending` (disabled, `aria-busy`) and `loading` (the same plus a spinner, which replaces the icon on an icon button). Sign-in and sign-up, the reset links, the confirmation email and the cloud picker use `loading`. +**Buttons.** Every enabled button, tab, menu item and switch shows a pointer cursor (a base rule in `src/styles.css`). `Button` has two busy states: `pending` (disabled, `aria-busy`) and `loading` (the same plus a spinner, which replaces the icon on an icon button). A button that starts a request shows it: the button that was pressed uses `loading` (disabled, with a spinner; on an icon button the spinner replaces the icon) for as long as its action runs, whether it is the main action of a form or dialog or a small action in a row (sign-in and sign-up, the reset links, the confirmation email, the cloud picker, publishing, saving a plan, account, limits or server settings, testing an AI connection, refreshing models, opening a generated draft, the account search, unlinking a sign-in, disconnecting GitHub, deleting a hosted image, resolving or deleting a comment, removing a person, saving or restoring a version, and the two-press admin buttons). The other buttons of the same dialog use `pending` (disabled, no spinner) while it runs, so nothing can be pressed twice. `disabled` alone is for a button that cannot be used yet (an empty field, a limit reached), never for one that is working; a test (`loading-rules.test.ts`) fails on a button disabled by a busy state without `loading` or `pending`, and on a hand-made spinner. The label of a button, menu item or command never ends in an ellipsis ("Edit rules", not "Edit rules…"); the ellipsis is kept only for text that says something is in progress ("Loading…", "Saving…"). Every dropdown choice uses the shared `Select` component (the target platform in the top bar and in Settings, a rule's severity, the AI provider and integration), never a native ` change({ profile: e.target.value as Profile })} + + +
+ {THEMES.map((t) => ( + + ))} +
+
+ p.id === prefs.profile)?.hint} > - {PROFILES.map((p) => ( - - ))} - - - - change({ normalize: on })} - /> - - - - - - - + + + + change({ normalize: on })} + /> + +
+ Writing checks + + + + + + + + -
-
- - - - Settings -
- - - -
-
-
-
-

Settings

- onTab(v as SettingsTab)}> - - {visibleTabs(!!user).map((t) => ( - - {LABEL[t]} - - ))} - - {user && ( - - - - )} - - - - - - - {user && ( - - - - )} - -
- + / Settings} + sections={visibleTabs(!!user).map((id) => ({ id, label: LABEL[id] }))} + current={current} + onSection={onTab} + menuLabel="Settings sections" + > + {user && ( + + + + + )} + + + + + + + + + {user && ( + + + + + )} + ); } diff --git a/src/components/settings/SettingsRow.tsx b/src/components/settings/SettingsRow.tsx index 184efc3..3e00d8a 100644 --- a/src/components/settings/SettingsRow.tsx +++ b/src/components/settings/SettingsRow.tsx @@ -11,10 +11,10 @@ export function SettingsRow({ children: ReactNode; }) { return ( -
+
-

{title}

- {description &&

{description}

} +

{title}

+ {description &&

{description}

}
{children}
diff --git a/src/components/share/Comments.tsx b/src/components/share/Comments.tsx index 2d3097e..82da401 100644 --- a/src/components/share/Comments.tsx +++ b/src/components/share/Comments.tsx @@ -101,12 +101,26 @@ function One({ className = "", }: { comment: ShareComment; - onDelete: (c: ShareComment) => void; + onDelete: (c: ShareComment) => unknown; className?: string; }) { const [confirming, setConfirming] = useState(false); + const [deleting, setDeleting] = useState(false); + const remove = async () => { + setDeleting(true); + try { + await onDelete(comment); + } finally { + setDeleting(false); + setConfirming(false); + } + }; return ( -
  • + // while it is being deleted the comment is dimmed, and its button shows the work +
  • {comment.author} {when(comment.createdAt)} @@ -119,20 +133,24 @@ function One({ {comment.mine && (confirming ? ( <> - - + ) : ( -

    Confirm your email first

    -

    +

    Confirm your email first

    +

    Editing together needs a confirmed email address. Open the link we sent you, then try again.

    @@ -108,8 +115,8 @@ export function OpenInvite({ link }: { link: string }) { )} {step === "denied" && ( <> -

    You can't open this draft

    -

    +

    You can't open this draft

    +

    The link may have stopped working, or this account isn't the address that was invited. Sign in with the invited address, or ask the owner to invite you again.

    @@ -117,15 +124,14 @@ export function OpenInvite({ link }: { link: string }) { )} {step === "failed" && ( <> -

    Couldn't reach the server

    -

    Check your connection and try again.

    - )} -
  • - - + + ); } diff --git a/src/components/site/AppShell.tsx b/src/components/site/AppShell.tsx new file mode 100644 index 0000000..774713f --- /dev/null +++ b/src/components/site/AppShell.tsx @@ -0,0 +1,125 @@ +import type { ReactNode } from "react"; +import { Link } from "@tanstack/react-router"; +import { Logo } from "@/components/Logo"; +import { AccountMenu } from "@/components/studio/AccountMenu"; +import { Button } from "@/components/ui/button"; +import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"; +import { cn } from "@/lib/utils"; + +/** + * The frame of the app's own pages (Settings, Admin): a top bar with the logo and a label, and a + * menu of sections on the left (a row of chips on phones). Each section is a Radix tab, so the menu + * keeps tab semantics and arrow-key movement. + */ +export function AppShell({ + label, + sections, + current, + onSection, + menuLabel, + wide, + children, +}: { + label: ReactNode; + sections: readonly { id: T; label: string }[]; + current: T; + onSection: (id: T) => void; + menuLabel: string; + wide?: boolean; + children: ReactNode; +}) { + return ( +
    + + onSection(v as T)} + orientation="vertical" + className={cn( + "mx-auto flex flex-col gap-4 p-4 md:flex-row md:items-start md:gap-10 md:px-6 md:py-8", + wide ? "max-w-310" : "max-w-280", + )} + > + + {sections.map((s) => ( + + {s.label} + + ))} + +
    {children}
    +
    +
    + ); +} + +/** The top bar of the app's own pages, and of the screens that stand on their own. */ +export function AppTopBar({ + label, + editor = true, + wide = false, +}: { + label?: ReactNode; + editor?: boolean; + wide?: boolean; +}) { + return ( +
    + {/* the same width and side padding as the page's content below, so the two line up */} +
    + + {label} +
    + {editor && ( + + )} + +
    +
    +
    + ); +} + +/** A page's heading, with the line under it. */ +export function PageTitle({ title, sub }: { title: string; sub?: ReactNode }) { + return ( +
    +

    {title}

    + {sub &&

    {sub}

    } +
    + ); +} + +/** A bordered group of rows. */ +export function Card({ children, className }: { children: ReactNode; className?: string }) { + return ( +
    + {children} +
    + ); +} + +/** A heading between two cards. */ +export function CardHeading({ children }: { children: ReactNode }) { + return

    {children}

    ; +} diff --git a/src/components/site/DocLayout.tsx b/src/components/site/DocLayout.tsx new file mode 100644 index 0000000..40ba989 --- /dev/null +++ b/src/components/site/DocLayout.tsx @@ -0,0 +1,99 @@ +import { useEffect, useState, type ReactNode } from "react"; +import { SITE_WIDTH } from "./SitePieces"; +import { cn } from "@/lib/utils"; + +/** How far below the top of the window a heading counts as "being read". */ +const READING_LINE = 120; + +/** The id of the section being read: the last one whose heading has reached the reading line. */ +function useActiveSection(ids: string[]) { + const [active, setActive] = useState(ids[0] ?? ""); + const key = ids.join("|"); + useEffect(() => { + if (ids.length === 0) return; + let frame = 0; + const update = () => { + frame = 0; + const doc = document.documentElement; + // at the very bottom the last section is the one being read, even if it is too short to reach the line + if (window.innerHeight + window.scrollY >= doc.scrollHeight - 2) + return setActive(ids.at(-1)!); + let current = ids[0]!; + for (const id of ids) { + const el = document.getElementById(id); + if (el && el.getBoundingClientRect().top <= READING_LINE) current = id; + } + setActive(current); + }; + const onScroll = () => { + if (!frame) frame = requestAnimationFrame(update); + }; + update(); + window.addEventListener("scroll", onScroll, { passive: true }); + window.addEventListener("resize", onScroll); + return () => { + window.removeEventListener("scroll", onScroll); + window.removeEventListener("resize", onScroll); + if (frame) cancelAnimationFrame(frame); + }; + // the ids, joined: the array itself is new on every render + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [key]); + return active; +} + +/** + * A page of reading (a guide, a legal page): its sections listed in a sticky column on the left, + * with the one being read marked, and the text beside it. The list is shown for as long as the + * window has room for it beside the text (from 1024px) and hidden below that. + */ +export function DocLayout({ + toc, + tocTitle, + children, +}: { + toc: { text: string; id: string }[]; + tocTitle: string; + children: ReactNode; +}) { + const active = useActiveSection(toc.map((t) => t.id)); + return ( +
    + {toc.length > 0 && ( + + )} + {/* centred when the list is hidden (or there is none); beside the list otherwise */} +
    0 && "lg:mx-0")}> + {children} +
    +
    + ); +} diff --git a/src/components/site/LegalPage.tsx b/src/components/site/LegalPage.tsx index 84f3639..5697033 100644 --- a/src/components/site/LegalPage.tsx +++ b/src/components/site/LegalPage.tsx @@ -1,24 +1,54 @@ +import { Link } from "@tanstack/react-router"; +import { DocLayout } from "@/components/site/DocLayout"; import { SiteFooter } from "@/components/site/SiteFooter"; import { SiteHeader } from "@/components/site/SiteHeader"; import { formatDate } from "@/lib/site/guides-content"; -import type { LegalPage as Legal } from "@/lib/site/legal"; +import { LEGAL_PAGES, legalPath, type LegalPage as Legal } from "@/lib/site/legal"; +import { cn } from "@/lib/utils"; /** A legal page: the title and date here, the text rendered (and sanitized) from content/legal. */ -export function LegalPage({ page, html }: { page: Legal; html: string }) { +export function LegalPage({ + page, + html, + toc, +}: { + page: Legal; + html: string; + toc: { text: string; id: string }[]; +}) { return (
    -
    +
    -

    + +

    {page.title}

    -

    +

    Last updated {formatDate(page.updated)}

    -
    + {/* sanitized by renderMarkdown (rehype-sanitize) */} +
    -
    +
    ); diff --git a/src/components/site/SiteFooter.tsx b/src/components/site/SiteFooter.tsx index c0b6365..586e914 100644 --- a/src/components/site/SiteFooter.tsx +++ b/src/components/site/SiteFooter.tsx @@ -1,35 +1,35 @@ import { Link } from "@tanstack/react-router"; import { SITE } from "@/lib/site/seo"; +import { cn } from "@/lib/utils"; -export function SiteFooter() { +const VERSION = import.meta.env.VITE_APP_VERSION; +const link = "hover:text-foreground"; + +/** Two groups: what this is on the left, where to read more on the right. */ +export function SiteFooter({ widthClass = "max-w-300" }: { widthClass?: string } = {}) { return (
    -
    - - © {new Date().getFullYear()} - - {SITE.author} - - -
    diff --git a/src/components/studio/AiIntegrationsDialog.tsx b/src/components/studio/AiIntegrationsDialog.tsx index 911d65c..5142f49 100644 --- a/src/components/studio/AiIntegrationsDialog.tsx +++ b/src/components/studio/AiIntegrationsDialog.tsx @@ -310,10 +310,11 @@ function IntegrationForm({ )} {revisions.length ? ( @@ -159,9 +170,16 @@ export function HistoryPanel({ Close + ); +} + +/** The one Share button's first step: send the draft out to be read, or open it up to be written. */ +export function ShareChooser({ + open, + onOpenChange, + onReview, + onEdit, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; + onReview: () => void; + onEdit: () => void; +}) { + return ( + + + + Share this draft + Choose how the other people take part. + +
    + } + title="Share for review" + body="A read-only copy at a link, to anyone or to people you name. Readers can comment on the words." + onClick={onReview} + /> + } + title="Edit together" + body="Invite people by email to type in this draft with you, at the same time." + onClick={onEdit} + /> +
    +
    +
    + ); +} diff --git a/src/components/studio/ShareDialog.tsx b/src/components/studio/ShareDialog.tsx index b39bd02..8a14dc5 100644 --- a/src/components/studio/ShareDialog.tsx +++ b/src/components/studio/ShareDialog.tsx @@ -74,9 +74,11 @@ export function ShareDialog({ const { byDraft, defaultDays, maxDays, privateLinks, loaded } = useShares(); const share = draft ? byDraft.get(draft.id) : undefined; const [days, setDays] = useState(String(defaultDays)); - const [busy, setBusy] = useState<"publish" | "extend" | "stop" | "settings" | "invite" | null>( - null, - ); + const [busy, setBusy] = useState< + "publish" | "extend" | "stop" | "settings" | "invite" | "remove" | null + >(null); + // the person being removed, so only their button shows it + const [removing, setRemoving] = useState(null); // what a link not yet published will be made with const [chosenAccess, setChosenAccess] = useState("public"); const [chosenComments, setChosenComments] = useState(false); @@ -214,15 +216,17 @@ export function ShareDialog({ "person", ); }; - const uninvite = (person: SharePerson) => + const uninvite = (person: SharePerson) => { + setRemoving(person.id); void run( - "invite", + "remove", async () => { await peopleApi.remove(draft.id, person.id); setPeople((list) => list.filter((p) => p.id !== person.id)); }, "person", - ); + ).finally(() => setRemoving(null)); + }; const stop = () => run("stop", async () => { await shareApi.revoke(draft.id); @@ -364,7 +368,8 @@ export function ShareDialog({ size="icon" className="size-7 shrink-0" aria-label={`Remove ${p.email}`} - pending={busy !== null} + loading={removing === p.id} + pending={busy !== null && removing !== p.id} onClick={() => uninvite(p)} > diff --git a/src/components/studio/Studio.tsx b/src/components/studio/Studio.tsx index a471ffd..9cb8317 100644 --- a/src/components/studio/Studio.tsx +++ b/src/components/studio/Studio.tsx @@ -32,6 +32,7 @@ import { sortLocalImages, warnLocalImages as noteLocalImages } from "@/lib/colla import { detachShared, openShared, removeShared } from "@/lib/collab/shared"; import { useSharedWithMe } from "@/lib/collab/sharedHooks"; import { ShareDialog } from "@/components/studio/ShareDialog"; +import { ShareChooser } from "@/components/studio/ShareChooser"; import { clearShares, useShares } from "@/lib/share/hooks"; import { addToCloud, @@ -53,6 +54,7 @@ import { SlidersHorizontal, FolderUp, Share2, + Send, Github, FileUp, MonitorDown, @@ -60,6 +62,8 @@ import { Copy, Columns2, PanelLeft, + Files, + Settings, FileText, Eye, AlertTriangle, @@ -97,7 +101,7 @@ import { import { TooltipProvider } from "@/components/ui/tooltip"; import { SiteNotice } from "@/components/SiteNotice"; import { cn } from "@/lib/utils"; -import { CHECKS_OPEN_MIN_WIDTH, clampLibraryWidth, LIBRARY_WIDTH } from "@/lib/ui/layout"; +import { clampLibraryWidth, LIBRARY_WIDTH } from "@/lib/ui/layout"; import { HistoryPanel } from "@/components/studio/HistoryPanel"; import { Library } from "@/components/studio/Library"; import { historyStore, type Revision } from "@/lib/storage/history"; @@ -340,8 +344,6 @@ export function Studio({ docId }: { docId: string }) { if (p) setProfile(p); setNormalize(localStorage.getItem("md:normalize") === "1"); setCheckConfig(loadConfig()); - // Checks start open only on wide screens; below that the editor keeps the room until asked. - if (window.matchMedia(`(min-width: ${CHECKS_OPEN_MIN_WIDTH}px)`).matches) setPanel("checks"); const w = localStorage.getItem("md:library-width"); if (w) setLibraryWidth(clampLibraryWidth(w)); }, []); @@ -1293,6 +1295,7 @@ export function Studio({ docId }: { docId: string }) { if (account) await syncNow(account.id); }; // the draft whose share dialog is open + const [shareChoice, setShareChoice] = useState(null); const [shareTarget, setShareTarget] = useState(null); const [collabTarget, setCollabTarget] = useState(null); // the draft whose publish-to-GitHub dialog is open @@ -1444,9 +1447,19 @@ export function Studio({ docId }: { docId: string }) { }; const errCount = issues.filter((i) => i.severity !== "info").length; - const showLibrary = library && !focus && !compact; - const showPanel = panel && !focus && !compact; const activePanel = overlay ? mobilePanel : panel; + // The drafts and every panel share one pane on the left (on phones and in focus mode they open + // as a panel over the page instead). A panel takes the pane; closing it gives the pane back to + // the drafts if they were showing. + const toggleSide = (p: "drafts" | NonNullable) => { + if (overlay) return p === "drafts" ? setMobileLibrary(true) : setMobilePanel(p); + if (p !== "drafts") return setPanel(panel === p ? null : p); + if (panel) { + setPanel(null); + setLibrary(true); + } else setLibrary((v) => !v); + }; + const sideOpen = !overlay && (panel !== null || library); const goToLine = (line: number) => { setView("editor"); setMobilePanel(null); @@ -1466,8 +1479,8 @@ export function Studio({ docId }: { docId: string }) { 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("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"), @@ -1480,11 +1493,7 @@ export function Studio({ docId }: { docId: string }) { 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("Drafts list", () => toggleSide("drafts"), "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"), @@ -1495,10 +1504,10 @@ export function Studio({ docId }: { docId: string }) { cmd("Keyboard shortcuts", () => setShortcuts(true), "keys hotkeys"), ...(cloudDraft && doc ? [ - cmd("Share…", () => setShareTarget(doc), "link review publish"), - cmd("Edit together…", () => setCollabTarget(doc), "collaborate invite live"), + cmd("Share", () => setShareTarget(doc), "link review publish"), + cmd("Edit together", () => setCollabTarget(doc), "collaborate invite live"), ...(githubPublish - ? [cmd("Publish to GitHub…", () => setPublishTarget(doc), "commit gist")] + ? [cmd("Publish to GitHub", () => setPublishTarget(doc), "commit gist")] : []), ] : []), @@ -1532,6 +1541,8 @@ export function Studio({ docId }: { docId: string }) { setActiveThread(r.id); return undefined; }; + // one menu for what leaves the studio: publishing too, once the draft is in the cloud + const canPublish = inCloud && githubPublish; const panelButtons = ( [ ["checks", errCount ? AlertTriangle : CheckCircle2, "Checks"], @@ -1550,8 +1561,9 @@ export function Studio({ docId }: { docId: string }) { variant={activePanel === p ? "secondary" : "ghost"} size="icon" className="relative size-10 shrink-0" - onClick={() => (overlay ? setMobilePanel(p) : setPanel(panel === p ? null : p))} + onClick={() => toggleSide(p)} aria-label={label} + aria-pressed={activePanel === p} title={label} > @@ -1586,10 +1598,9 @@ export function Studio({ docId }: { docId: string }) { cloudOn ? void addToCloud(account.id, [d.id]) : askToConfirmEmail(), onRemove: (d: MdDocument) => void removeFromCloud(account.id, d.id), ...(cloudOn && { - onShare: (d: MdDocument) => setShareTarget(d), + onShare: (d: MdDocument) => setShareChoice(d), shared: sharedIds, sharedPrivately: privateIds, - onCollab: (d: MdDocument) => setCollabTarget(d), live: cloudDrafts.live, }), ...(cloudOn && githubPublish && { onPublish: (d: MdDocument) => setPublishTarget(d) }), @@ -1691,25 +1702,31 @@ export function Studio({ docId }: { docId: string }) {
    {/* Top bar */} -
    -
    +
    +
    - + + {/* the page's heading for assistive tech; the preview's own headings follow it */} +

    {doc?.title ?? "Editor"}

    / {doc?.title ?? "…"}
    -
    +
    {install && ( fileInput.current?.click()}>
    - Files or a ZIP… + Files or a ZIP Markdown, text, or an exported archive @@ -1756,7 +1773,7 @@ export function Studio({ docId }: { docId: string }) { folderInput.current?.click()}>
    - A folder… + A folder Folders become library folders @@ -1770,13 +1787,28 @@ export function Studio({ docId }: { docId: string }) { variant="default" size="sm" className="h-8 px-2 sm:px-3" - aria-label="Export" + aria-label={canPublish ? "Publish" : "Export"} > - - Export + {canPublish ? : } + {canPublish ? "Publish" : "Export"} + {canPublish && doc && ( + <> + Publish + setPublishTarget(doc)}> + +
    + Publish to GitHub + + A commit, a pull request or a gist + +
    +
    + + + )} Markdown Download .md @@ -1836,33 +1868,23 @@ export function Studio({ docId }: { docId: string }) {
    - {cloudOn && doc && cloudDrafts.linked.has(doc.id) && ( + {inCloud && doc && ( - )} - {cloudOn && githubPublish && doc && cloudDrafts.linked.has(doc.id) && ( - )} - - - + {/* from 1280px these live in the side strip */} + + + {/* from 1280px the account sits in the side strip */} + {compact && }
    -
    + {/* on a phone this is a second row; from 640px its two parts join the first */} +
    -
    +
    {( [ @@ -1916,7 +1939,10 @@ export function Studio({ docId }: { docId: string }) { key={v} variant={effectiveView === v ? "secondary" : "ghost"} size="icon" - className={cn("size-10 shrink-0", v === "split" && "hidden md:inline-flex")} + className={cn( + "size-10 shrink-0 sm:size-8", + v === "split" && "hidden md:inline-flex", + )} onClick={() => setView(v)} aria-label={`${v} view`} aria-pressed={effectiveView === v} @@ -1932,10 +1958,51 @@ export function Studio({ docId }: { docId: string }) {
    - {/* Library */} - {showLibrary && ( + {/* Panel buttons, on the left beside the pane they open */} + {!compact && ( + + )} + {/* The left pane: the drafts, or the panel chosen beside it */} + {sideOpen && (
    - {libraryContent} + {panel ? ( + + ) : ( + libraryContent + )}
    - - {/* Side panel */} - {!compact && ( -
    - {showPanel && ( - - )} -
    {panelButtons}
    -
    - )} + !open && setShareChoice(null)} + onReview={() => { + if (shareChoice) setShareTarget(shareChoice); + setShareChoice(null); + }} + onEdit={() => { + if (shareChoice) setCollabTarget(shareChoice); + setShareChoice(null); + }} + /> ; + +/** The ` - - Go home - + + - + ); } diff --git a/src/routes/guides.$slug.tsx b/src/routes/guides.$slug.tsx index 80ab010..bf59275 100644 --- a/src/routes/guides.$slug.tsx +++ b/src/routes/guides.$slug.tsx @@ -3,15 +3,12 @@ import { ArrowRight } from "lucide-react"; import { SiteFooter } from "@/components/site/SiteFooter"; import { SiteHeader } from "@/components/site/SiteHeader"; import { Button } from "@/components/ui/button"; +import { DocLayout } from "@/components/site/DocLayout"; +import { Band, TILE } from "@/components/site/SitePieces"; +import { cn } from "@/lib/utils"; import { GUIDES, guideBySlug, readingMinutes } from "@/lib/site/guides"; -import { - formatDate, - headingIds, - loadGuideMarkdown, - relatedGuides, - withHeadingIds, -} from "@/lib/site/guides-content"; -import { getOutline, renderMarkdown } from "@/lib/markdown/markdown"; +import { formatDate, loadGuideMarkdown, relatedGuides } from "@/lib/site/guides-content"; +import { renderWithToc } from "@/lib/site/render-toc"; import { articleJsonLd, breadcrumbJsonLd, jsonLdScript, pageHead } from "@/lib/site/seo"; export const Route = createFileRoute("/guides/$slug")({ @@ -20,14 +17,7 @@ export const Route = createFileRoute("/guides/$slug")({ const guide = guideBySlug(params.slug); const md = guide ? await loadGuideMarkdown(guide.slug) : null; if (!guide || md === null) throw notFound(); - const sections = getOutline(md).filter((h) => h.depth === 2); - const ids = headingIds(sections.map((s) => s.text)); - return { - guide, - html: withHeadingIds(renderMarkdown(md, "gfm-extended"), ids), - minutes: readingMinutes(md), - toc: sections.map((s, i) => ({ text: s.text, id: ids[i]! })), - }; + return { guide, minutes: readingMinutes(md), ...renderWithToc(md) }; }, head: ({ loaderData, params }) => { const guide = loaderData?.guide ?? guideBySlug(params.slug); @@ -58,7 +48,7 @@ function GuidePage() { return (
    -
    + -
    -

    +
    +

    {guide.title}

    -

    - Updated {formatDate(guide.updated)} · {minutes} min read +

    + Updated {formatDate(guide.updated)} + {minutes} min read

    - {/* sanitized by renderMarkdown (rehype-sanitize) */} -
    +
    -
    -

    - Check your own Markdown -

    -

    - Open source and private. Pick a target platform and see what won’t travel. -

    -
    - + +
    +

    Check your own Markdown

    +

    + Open source and private. Pick a target platform and see what won’t travel. +

    -
    + +
    -
      +
      {relatedGuides(GUIDES, guide.slug).map((g) => ( -
    • - - {g.title} - -

      {g.description}

      -
    • + +

      {g.title}

      +

      {g.description}

      + ))} -
    +

    - + ); diff --git a/src/routes/guides.index.tsx b/src/routes/guides.index.tsx index 6c2e294..467373c 100644 --- a/src/routes/guides.index.tsx +++ b/src/routes/guides.index.tsx @@ -1,6 +1,8 @@ import { createFileRoute, Link } from "@tanstack/react-router"; import { SiteFooter } from "@/components/site/SiteFooter"; import { SiteHeader } from "@/components/site/SiteHeader"; +import { Chip, SITE_WIDTH, TILE } from "@/components/site/SitePieces"; +import { cn } from "@/lib/utils"; import { formatDate } from "@/lib/site/guides-content"; import { GUIDES, guidePath } from "@/lib/site/guides"; import { breadcrumbJsonLd, jsonLdScript, pageHead } from "@/lib/site/seo"; @@ -28,30 +30,32 @@ function GuidesIndex() { return (
    -
    -

    - Markdown guides -

    -

    - Practical, platform-aware guides to writing Markdown that renders the same on GitHub, - dev.to, Obsidian and any CommonMark tool. Each one explains what differs and how to avoid - surprises. -

    -
      +
      +
      +

      + Markdown guides +

      +

      + Practical, platform-aware guides to writing Markdown that renders the same on GitHub, + dev.to, Obsidian and any CommonMark tool. Each one explains what differs and how to + avoid surprises. +

      +
      +
        {GUIDES.map((g) => ( -
      • -

        +
      • + Updated {formatDate(g.updated)} +

        {g.title}

        -

        {g.description}

        -

        Updated {formatDate(g.updated)}

        +

        {g.description}

      • ))}

      diff --git a/src/routes/index.tsx b/src/routes/index.tsx index 567aa36..d666ef5 100644 --- a/src/routes/index.tsx +++ b/src/routes/index.tsx @@ -210,7 +210,11 @@ on two lines.
    -
    +

    Everything a Markdown writer needs

    diff --git a/src/routes/privacy.tsx b/src/routes/privacy.tsx index 4917011..61a7d1d 100644 --- a/src/routes/privacy.tsx +++ b/src/routes/privacy.tsx @@ -1,8 +1,8 @@ import { createFileRoute, notFound } from "@tanstack/react-router"; import { LegalPage } from "@/components/site/LegalPage"; -import { renderMarkdown } from "@/lib/markdown/markdown"; import { legalBySlug, legalPath } from "@/lib/site/legal"; import { loadLegalMarkdown } from "@/lib/site/legal-content"; +import { renderWithToc } from "@/lib/site/render-toc"; import { pageHead } from "@/lib/site/seo"; const page = legalBySlug("privacy")!; @@ -11,7 +11,7 @@ export const Route = createFileRoute("/privacy")({ loader: async () => { const md = await loadLegalMarkdown(page.slug); if (md === null) throw notFound(); - return { html: renderMarkdown(md, "gfm-extended") }; + return renderWithToc(md); }, head: () => pageHead({ @@ -23,5 +23,6 @@ export const Route = createFileRoute("/privacy")({ }); function Page() { - return ; + const { html, toc } = Route.useLoaderData(); + return ; } diff --git a/src/routes/reset-password.tsx b/src/routes/reset-password.tsx index fc2df36..26f5ffe 100644 --- a/src/routes/reset-password.tsx +++ b/src/routes/reset-password.tsx @@ -2,7 +2,7 @@ import { Link, createFileRoute } from "@tanstack/react-router"; import { Eye, EyeOff } from "lucide-react"; import { useEffect, useState } from "react"; -import { Logo } from "@/components/Logo"; +import { Standalone, StandaloneBox } from "@/components/site/Standalone"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -47,12 +47,11 @@ function ResetPassword() { } return ( -
    -
    - + + {done ? (
    -

    Password changed

    +

    Password changed

    Every device was signed out. Sign in with your new password.

    @@ -62,7 +61,7 @@ function ResetPassword() {
    ) : !held ? (
    -

    This link doesn't work

    +

    This link doesn't work

    It's missing its code. Open the link from the email again, or ask for a new one from the sign-in dialog. @@ -79,7 +78,7 @@ function ResetPassword() { void submit(); }} > -

    Choose a new password

    +

    Choose a new password

    @@ -115,12 +114,12 @@ function ResetPassword() { {error}

    )} - )} -
    -
    + + ); } diff --git a/src/routes/s.$slug.tsx b/src/routes/s.$slug.tsx index 5ed5d38..b0d25a9 100644 --- a/src/routes/s.$slug.tsx +++ b/src/routes/s.$slug.tsx @@ -1,10 +1,14 @@ -import { createFileRoute, notFound, useRouter } from "@tanstack/react-router"; +import { createFileRoute, Link, notFound, useRouter } from "@tanstack/react-router"; import { Lock } from "lucide-react"; import { useEffect, useMemo, useRef, useState } from "react"; import { ReaderSignIn } from "@/components/share/ReaderSignIn"; import { ShareComments } from "@/components/share/Comments"; import { SiteFooter } from "@/components/site/SiteFooter"; -import { SiteHeader } from "@/components/site/SiteHeader"; +import { Logo } from "@/components/Logo"; +import { ThemeToggle } from "@/components/ThemeToggle"; +import { Chip, SITE_WIDTH } from "@/components/site/SitePieces"; +import { Standalone, StandaloneBox } from "@/components/site/Standalone"; +import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/button"; import { accountStore } from "@/lib/account/store"; import { hydrateDiagrams, renderDiagramFor } from "@/lib/markdown/diagrams"; @@ -57,27 +61,30 @@ function SharedPage() { if (data.kind === "sign_in") return ( -
    - -
    -
    - +

    + You come straight back here after signing in. +

    + -
    + ); return ; } @@ -113,54 +120,73 @@ function Document({ hydrateDiagrams(body.current, renderDiagramFor(theme)).catch((e) => console.error(e)); }, [html, theme]); + const report = `${SITE.repo}/issues/new?title=${encodeURIComponent("Report a shared page")}&body=${encodeURIComponent(`/s/${slug}`)}`; + // The bar, the text and the footer share one width: wide enough for the comments column while it + // shows, and just the text (centred) when it does not. + const [side, setSide] = useState(false); + const width = side ? "max-w-310" : "max-w-230"; return (
    - -
    -

    - {data.kind === "private" && ( - <> -

    -
    -
    +
    +
    + + + {data.comments ? "Shared for review" : "Shared copy"} + +
    + + +
    +
    +
    +
    +
    +
    +

    + {data.kind === "private" && ( + + + )} + A copy shared with mdstudio on {shareDate(data.publishedAt)}. + Available until {shareDate(data.expiresAt)}. +

    {!/]/.test(html) &&

    {title}

    }
    +

    + Made with mdstudio + + Report this page + +

    - data.kind === "private" && onSignedIn()} - /> + {/* the comments column, while it shows */} +
    + data.kind === "private" && onSignedIn()} + onSideChange={setSide} + /> +
    - +
    ); } diff --git a/src/routes/terms.tsx b/src/routes/terms.tsx index 637d7e4..7af1a3a 100644 --- a/src/routes/terms.tsx +++ b/src/routes/terms.tsx @@ -1,8 +1,8 @@ import { createFileRoute, notFound } from "@tanstack/react-router"; import { LegalPage } from "@/components/site/LegalPage"; -import { renderMarkdown } from "@/lib/markdown/markdown"; import { legalBySlug, legalPath } from "@/lib/site/legal"; import { loadLegalMarkdown } from "@/lib/site/legal-content"; +import { renderWithToc } from "@/lib/site/render-toc"; import { pageHead } from "@/lib/site/seo"; const page = legalBySlug("terms")!; @@ -11,7 +11,7 @@ export const Route = createFileRoute("/terms")({ loader: async () => { const md = await loadLegalMarkdown(page.slug); if (md === null) throw notFound(); - return { html: renderMarkdown(md, "gfm-extended") }; + return renderWithToc(md); }, head: () => pageHead({ @@ -23,5 +23,6 @@ export const Route = createFileRoute("/terms")({ }); function Page() { - return ; + const { html, toc } = Route.useLoaderData(); + return ; } diff --git a/src/styles.css b/src/styles.css index e5db659..6c3c94b 100644 --- a/src/styles.css +++ b/src/styles.css @@ -480,8 +480,9 @@ .cm-editor.cm-focused { outline: none; } -.cm-scroller { - font-family: var(--font-mono); +/* !important: CodeMirror's base theme sets "monospace" on the scroller with a selector that wins otherwise. */ +.cm-editor .cm-scroller { + font-family: var(--font-mono) !important; line-height: 1.7; } .cm-content { From d6fadebaf17ff729068cb47485cf8fa90ac87b78 Mon Sep 17 00:00:00 2001 From: Chizoba Jude Ojini Date: Sun, 15 Nov 2026 20:44:41 +0000 Subject: [PATCH 10/12] feat(ui): list AI integrations in settings, add a page loader, keep the side strip on tablets - Settings > AI lists each integration with Update and Remove, and Add integration opens the dialog - PageLoader (the animated logo) replaces the small loading lines on Settings, Admin and the editor's first load, and is the router's default pending screen - The editor's side strip stays from 768px (only phones lose it); the top bar's drafts toggle is phone only; the layout switches use CSS --- docs/UI_SPEC.md | 8 +-- e2e/collab-comments.spec.ts | 5 +- e2e/settings.spec.ts | 31 ++++++++++ e2e/studio.spec.ts | 27 +++++++-- src/components/PageLoader.tsx | 60 +++++++++++++++++++ src/components/admin/AdminPage.tsx | 3 +- src/components/settings/AiSection.tsx | 75 ++++++++++++++++++++++-- src/components/settings/SettingsPage.tsx | 3 +- src/components/studio/Studio.tsx | 72 ++++++++++------------- src/router.tsx | 2 + src/routes/editor.index.tsx | 7 +-- src/styles.css | 34 +++++++++++ 12 files changed, 264 insertions(+), 63 deletions(-) create mode 100644 src/components/PageLoader.tsx diff --git a/docs/UI_SPEC.md b/docs/UI_SPEC.md index f2b920f..6d6a12f 100644 --- a/docs/UI_SPEC.md +++ b/docs/UI_SPEC.md @@ -67,7 +67,7 @@ For a draft in the cloud, on a server that can publish (`githubPublish` in `/api - **Top bar:** one row from 640px (it wraps onto a second row only when the window is too narrow for everything). Left to right: drafts toggle (phones) · wordmark link with the release (`v0.2.0`, from package.json; hidden below 640px) and current title · target-profile Select (GFM extended, Strict CommonMark, GFM without HTML, Wiki notes; remembered per device) · view switch (Editor, Split, Preview as three icon buttons; Split hidden on phones) · panel buttons (768 to 1279px only) · Install (only when the browser offers to install the app) · AI writer · Import dropdown (files or a ZIP, or a folder) · **Export** · **Share**. On a phone the Select and the view switch form a second row. - **Export / Publish:** one button. For a draft that is not in the cloud (or on a server that cannot publish) it is **Export**; for a cloud draft on a server that can publish to GitHub it is **Publish**, and its menu starts with a **Publish** section (Publish to GitHub) above the same Markdown, HTML and All drafts sections and the "Normalize on export" switch. Labels show from 1024px; below that only the icons. - **Share:** one button, for cloud drafts only. It opens a "Share this draft" dialog with two choices: **Share for review** (the Share dialog below: a link readers can comment on) and **Edit together** (the invitation dialog below). The drafts menu keeps both as separate items. -- **Account:** the avatar (signed in: the menu with "Choose drafts for the cloud", "Manage images", Account, Settings, Admin dashboard and "Sign out"; signed out: Sign in and create an account, with "Forgot your password?" when the server sends mail and a `/reset-password` page for the emailed link; optional; "Continue with Google" and "Continue with GitHub" when the server has them) sits at the foot of the side strip from 1280px, and at the end of the top bar below that. The drafts list shows "Cloud: n of 5 drafts", a cloud icon on drafts stored in the account, and "Save to cloud" / "Remove from cloud" in each draft's menu. +- **Account:** the avatar (signed in: the menu with "Choose drafts for the cloud", "Manage images", Account, Settings, Admin dashboard and "Sign out"; signed out: Sign in and create an account, with "Forgot your password?" when the server sends mail and a `/reset-password` page for the emailed link; optional; "Continue with Google" and "Continue with GitHub" when the server has them) sits at the foot of the side strip from 768px, and at the end of the top bar on phones. The drafts list shows "Cloud: n of 5 drafts", a cloud icon on drafts stored in the account, and "Save to cloud" / "Remove from cloud" in each draft's menu. - **Top bar, row 2:** target-profile Select (GFM extended, Strict CommonMark, GFM without HTML, Wiki notes; remembered per device) · view toggle (Editor / Split / Preview) · panel buttons on mid-size screens. - **Export dropdown:** Download .md, Copy Markdown, Download self-contained .md and Copy self-contained Markdown (both enabled only when the draft has local images), Copy rendered HTML, Download standalone .html, and the "Normalize on export" switch. - **Drafts sidebar:** New folder and New draft buttons, a search box, tag chips, and a folder tree. Search matches every word in a draft's title or text (a matching line is shown under the title); tag chips come from each draft's front matter `tags` and narrow the list when selected. Folders are labels kept in the library, not in the text: they list first (A to Z, collapsible, drafts indented beneath them with a guide line) and unfiled drafts follow. A draft moves by dragging it onto a folder, or onto the empty part of the list to take it out, and also from its three-dot menu (Rename, Move to folder, Save to cloud or Remove from cloud, then for a cloud draft Share, Publish (where the server can publish to GitHub) and Host images (where the server hosts them and the draft has local images), Duplicate, Delete; no item ends in an ellipsis), which is the route on touch screens. A folder's menu has Rename folder (an inline field with save and cancel; the drafts follow, and a name another folder already has is refused) and Delete folder: an empty one goes at once, one with drafts asks first because the drafts inside are deleted too. A folder also goes when its last draft is deleted (here or on another device); moving the last draft out leaves it. Delete opens a confirmation Dialog. @@ -123,7 +123,7 @@ Only for an admin; anyone else sees the site's 404. Reached from "Admin dashboar ## 6b. Settings: `/settings` -Opened from the Account menu (**Account** opens the Account tab, **Settings** the Editor tab), from the gear in the editor's side strip (and in its top bar below 1280px), and from the gear in the header of the public pages. The app frame (`AppShell`, as the dashboard): a top bar (on the page background, like the public header) with the logo, "/ Settings", a primary "Back to the editor" button and the account menu (its contents line up with the page's content below it), and the sections in a menu on the left (a row of chips on phones), with the open one in the address (`?tab=`). Each section has its title and a line under it, and its rows are grouped in bordered cards: **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 profile sits in its own card, the sign-ins under a "Sign-in methods" heading., **Editor** (theme as a System | Light | Dark switch, 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. +Opened from the Account menu (**Account** opens the Account tab, **Settings** the Editor tab), from the gear in the editor's side strip (and in its top bar on phones), and from the gear in the header of the public pages. The app frame (`AppShell`, as the dashboard): a top bar (on the page background, like the public header) with the logo, "/ Settings", a primary "Back to the editor" button and the account menu (its contents line up with the page's content below it), and the sections in a menu on the left (a row of chips on phones), with the open one in the address (`?tab=`). Each section has its title and a line under it, and its rows are grouped in bordered cards: **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 profile sits in its own card, the sign-ins under a "Sign-in methods" heading., **Editor** (theme as a System | Light | Dark switch, target platform, Normalize on export, a button for the writing-check rules and one for keyboard shortcuts; all kept on this device), **AI** (the integrations listed in the card, each with its provider, Ready or Key needed, an Update button that opens the dialog on its form and a Remove button; an Add integration button opens the dialog on a blank form; the dialog closes after saving) 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. ## 6b-2. Standalone screens and 404 @@ -136,8 +136,8 @@ A dialog for finding anything, on every page: Ctrl/⌘ Shift P anywhere, Ctrl/ ## 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. -- **Below 1280px** the drafts list and Checks, Outline, Front matter, History and Comments open as a sheet from the left, sharing the same components as the docked pane. -- **At 1280px and above** a Drafts button and the panel buttons (Checks, Outline, Front matter, History, Comments) sit in a 48px column at the left edge, with Search, the theme button and Settings at its foot (below 1280px they stay in the top bar), and beside them one docked pane that the drafts and the panels share: a panel takes the pane, pressing its button again closes it and gives the pane back to the drafts, and the Drafts button there (or the one in the top bar) shows or hides the list. There is no panel column on the right. The pane defaults to 288px and can be dragged (or resized with the arrow keys, Home and End; double-click resets) between 240px and 480px; the width is remembered. The drafts show first; Checks opens from its button. +- **Below 1280px** the drafts list and Checks, Outline, Front matter, History and Comments open as a sheet from the left (from the side strip, or on phones from the top bar's drafts button and the bottom bar), sharing the same components as the docked pane. +- **From 768px** (everything but phones) a Drafts button and the panel buttons (Checks, Outline, Front matter, History, Comments) sit in a 48px column at the left edge, with Search, the theme button, Settings and the account at its foot. **At 1280px and above**, beside them, one docked pane that the drafts and the panels share: a panel takes the pane, pressing its button again closes it and gives the pane back to the drafts, and the Drafts button there shows or hides the list (the top bar's drafts toggle exists only on phones). There is no panel column on the right. The pane defaults to 288px and can be dragged (or resized with the arrow keys, Home and End; double-click resets) between 240px and 480px; the width is remembered. The drafts show first; Checks opens from its button. ## Interactions diff --git a/e2e/collab-comments.spec.ts b/e2e/collab-comments.spec.ts index 69c046a..70a8c3b 100644 --- a/e2e/collab-comments.spec.ts +++ b/e2e/collab-comments.spec.ts @@ -106,7 +106,10 @@ test("stopping editing together keeps the open comments in the draft's History", await expect(panel(a).getByText("Please expand this")).toBeVisible(); // the panel shares the left pane with the drafts, whose menu has Share - await a.getByRole("banner").getByRole("button", { name: "Toggle drafts" }).click(); + await a + .getByRole("navigation", { name: "Panels" }) + .getByRole("button", { name: "Drafts" }) + .click(); const dialog = await openDialog(a); await expect( dialog.getByText(/Comments and suggestions end with editing together/), diff --git a/e2e/settings.spec.ts b/e2e/settings.spec.ts index 1f8c093..4239a20 100644 --- a/e2e/settings.spec.ts +++ b/e2e/settings.spec.ts @@ -129,3 +129,34 @@ test("the settings menu and content sit together in the middle of the page", asy expect(content.x).toBeGreaterThan(menu.x + menu.width); expect(Math.abs(menu.x - (1440 - (content.x + content.width)))).toBeLessThan(8); }); + +test("the AI tab lists the integrations, adds one from a dialog, and updates or removes it", async ({ + page, +}) => { + await page.goto("/settings?tab=ai"); + const section = page.getByRole("region", { name: "AI" }); + await expect(section.getByText("No integrations yet")).toBeVisible(); + await expect(section.getByRole("button", { name: "Manage" })).toHaveCount(0); + + // add one: the dialog opens on a blank form and closes once it is saved + await section.getByRole("button", { name: "Add integration" }).click(); + const dialog = page.getByRole("dialog", { name: "AI integrations" }); + await dialog.getByLabel("AI provider").click(); + await page.getByRole("option", { name: /Ollama/ }).click(); + await dialog.getByLabel("Model IDs").fill("llama3.2"); + await dialog.getByRole("button", { name: "Add integration" }).click(); + await expect(dialog).toBeHidden(); + await expect(section.getByText("No integrations yet")).toBeHidden(); + await expect(section.getByRole("listitem")).toHaveCount(1); + await expect(section.getByRole("listitem")).toContainText("Ollama"); + + // update it: straight to its form, and back to the page after saving + await section.getByRole("button", { name: "Update Ollama" }).click(); + await dialog.getByLabel("Name (optional)").fill("My local"); + await dialog.getByRole("button", { name: "Save" }).click(); + await expect(dialog).toBeHidden(); + await expect(section.getByRole("listitem")).toContainText("My local"); + + await section.getByRole("button", { name: "Remove My local" }).click(); + await expect(section.getByText("No integrations yet")).toBeVisible(); +}); diff --git a/e2e/studio.spec.ts b/e2e/studio.spec.ts index 61ceee7..c7a2260 100644 --- a/e2e/studio.spec.ts +++ b/e2e/studio.spec.ts @@ -196,7 +196,9 @@ test("the drafts and the panels share the pane on the left", async ({ page }) => await open(page); const panels = page.getByRole("navigation", { name: "Panels" }); const drafts = page.getByRole("complementary").getByRole("navigation", { name: "Drafts" }); - const toggle = page.getByRole("banner").getByRole("button", { name: "Toggle drafts" }); + const toggle = page + .getByRole("navigation", { name: "Panels" }) + .getByRole("button", { name: "Drafts" }); // the drafts show first, with the panel buttons to their left await expect(drafts).toBeVisible(); await expect(checks).toBeHidden(); @@ -1135,7 +1137,9 @@ test("in focus mode the drafts button opens the list as a panel and focus mode s }) => { await open(page); const focus = page.getByRole("toolbar").getByRole("button", { name: "Focus mode" }); - const toggle = page.getByRole("banner").getByRole("button", { name: "Toggle drafts" }); + const toggle = page + .getByRole("navigation", { name: "Panels" }) + .getByRole("button", { name: "Drafts" }); const sidebar = page.getByRole("complementary").getByRole("navigation", { name: "Drafts" }); // normal mode: the button still opens and closes the sidebar in place @@ -1242,14 +1246,25 @@ test("one button for what leaves the studio: Export for a local draft, with the await expect(bar.getByRole("button", { name: "preview view" })).toBeVisible(); }); -test("the account sits in the side strip from 1280px, and in the top bar below it", async ({ +test("the account sits in the side strip from 768px, and in the top bar on a phone", async ({ page, }) => { await page.setViewportSize({ width: 1440, height: 900 }); await open(page); - const strip = page.getByRole("navigation", { name: "Panels" }); + const strip = page.getByRole("navigation", { name: "Panels", exact: true }); + const bar = page.getByRole("banner"); await expect(strip.getByRole("button", { name: "Sign in" })).toBeVisible(); - await expect(page.getByRole("banner").getByRole("button", { name: "Sign in" })).toHaveCount(0); + await expect(bar.getByRole("button", { name: "Sign in" })).toHaveCount(0); + await expect(bar.getByRole("button", { name: "Toggle drafts" })).toHaveCount(0); + // a narrower window keeps the strip, with the search, theme and account in it await page.setViewportSize({ width: 1000, height: 800 }); - await expect(page.getByRole("banner").getByRole("button", { name: "Sign in" })).toBeVisible(); + await expect(strip.getByRole("button", { name: "Sign in" })).toBeVisible(); + await expect(strip.getByRole("button", { name: "Drafts" })).toBeVisible(); + await expect(bar.getByRole("button", { name: "Sign in" })).toHaveCount(0); + await expect(bar.getByRole("button", { name: "Toggle drafts" })).toHaveCount(0); + // only a phone drops the strip, and then the top bar has the account and the drafts toggle + await page.setViewportSize({ width: 600, height: 800 }); + await expect(strip).toBeHidden(); + await expect(bar.getByRole("button", { name: "Sign in" })).toBeVisible(); + await expect(bar.getByRole("button", { name: "Toggle drafts" })).toBeVisible(); }); diff --git a/src/components/PageLoader.tsx b/src/components/PageLoader.tsx new file mode 100644 index 0000000..8fe44b7 --- /dev/null +++ b/src/components/PageLoader.tsx @@ -0,0 +1,60 @@ +import { cn } from "@/lib/utils"; +import { Wordmark } from "@/components/Logo"; + +/** + * What a page shows while it loads: the mark, drawn stroke by stroke (the source page, the rendered + * page, then its lines) on a loop, with the name under it. Fills the space it is given. + */ +export function PageLoader({ + label = "Loading", + className, +}: { + label?: string; + className?: string; +}) { + return ( +
    + + + {label} +
    + ); +} diff --git a/src/components/admin/AdminPage.tsx b/src/components/admin/AdminPage.tsx index a43d94a..e7b13a5 100644 --- a/src/components/admin/AdminPage.tsx +++ b/src/components/admin/AdminPage.tsx @@ -1,3 +1,4 @@ +import { PageLoader } from "@/components/PageLoader"; import { useEffect } from "react"; import { TabsContent } from "@/components/ui/tabs"; import { AppShell, PageTitle } from "@/components/site/AppShell"; @@ -41,7 +42,7 @@ export function AdminPage({ const account = useAccount(); // the dashboard is the one page that asks who is signed in itself useEffect(() => void accountStore.refresh(), []); - if (!account.loaded) return
    Loading…
    ; + if (!account.loaded) return ; if (!account.user?.isAdmin) return ; return ( (null); + const full = + state.cloud === "on" && state.cloudLimit !== null && state.items.length >= state.cloudLimit; return (
    + The services you use (OpenAI, Anthropic, Gemini, Ollama or any compatible gateway), + with their model and key. Keys are not saved to disk or sent to mdstudio. + {full && ` Your account keeps up to ${state.cloudLimit}. Remove one to add another.`} + + } > - + {state.items.length === 0 ? ( +

    + {state.cloud === "loading" ? "Loading your integrations" : "No integrations yet."} +

    + ) : ( +
      + {state.items.map((i) => ( +
    • +
      +
      {i.name}
      +
      + {PROVIDER_LABELS[i.provider]} · {needsKey(state, i.id) ? "Key needed" : "Ready"} +
      +
      + + +
    • + ))} +
    + )}
    - + !o && setEditing(null)} + editId={editing} + returnOnSave + />
    ); } diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx index e1603ac..9ca93c3 100644 --- a/src/components/settings/SettingsPage.tsx +++ b/src/components/settings/SettingsPage.tsx @@ -1,3 +1,4 @@ +import { PageLoader } from "@/components/PageLoader"; import { useEffect } from "react"; import { TabsContent } from "@/components/ui/tabs"; import { AppShell, PageTitle } from "@/components/site/AppShell"; @@ -20,7 +21,7 @@ export function SettingsPage({ tab, onTab }: { tab: string; onTab: (tab: Setting const account = useAccount(); // this page asks who is signed in itself, like the dashboard useEffect(() => void accountStore.refresh(), []); - if (!account.loaded) return
    Loading…
    ; + if (!account.loaded) return ; const user = account.user; const current = parseSettingsTab(tab, !!user); return ( diff --git a/src/components/studio/Studio.tsx b/src/components/studio/Studio.tsx index 9cb8317..32d7711 100644 --- a/src/components/studio/Studio.tsx +++ b/src/components/studio/Studio.tsx @@ -1707,18 +1707,13 @@ export function Studio({ docId }: { docId: string }) { - + {/* the page's heading for assistive tech; the preview's own headings follow it */}

    {doc?.title ?? "Editor"}

    @@ -1880,11 +1875,11 @@ export function Studio({ docId }: { docId: string }) { Share )} - {/* from 1280px these live in the side strip */} - - - {/* from 1280px the account sits in the side strip */} - {compact && } + {/* from 768px these live in the side strip */} + + + {/* mounted once: it owns its dialogs, so a hidden twin would open them twice */} + {phone && }
    ))} -
    {panelButtons}
    {/* Panel buttons, on the left beside the pane they open */} - {!compact && ( - - )} + + + {panelButtons} +
    + + + + {!phone && } + {/* The left pane: the drafts, or the panel chosen beside it */} {sideOpen && (
    diff --git a/src/router.tsx b/src/router.tsx index 8fce71e..e0294bf 100644 --- a/src/router.tsx +++ b/src/router.tsx @@ -3,6 +3,7 @@ import { createRouter } from "@tanstack/react-router"; import { createIsomorphicFn } from "@tanstack/react-start"; import { getRequest } from "@tanstack/react-start/server"; import { getRequestNonce } from "./lib/server/csp"; +import { PageLoader } from "./components/PageLoader"; import { routeTree } from "./routeTree.gen"; // Undefined in dev and in the browser; set by the security-headers middleware in production. @@ -18,6 +19,7 @@ export const getRouter = () => { routeTree, context: { queryClient }, scrollRestoration: true, + defaultPendingComponent: PageLoader, defaultPreloadStaleTime: 0, ...(nonce && { ssr: { nonce } }), }); diff --git a/src/routes/editor.index.tsx b/src/routes/editor.index.tsx index 20b25c1..2f2575b 100644 --- a/src/routes/editor.index.tsx +++ b/src/routes/editor.index.tsx @@ -1,5 +1,6 @@ import { createFileRoute, useNavigate } from "@tanstack/react-router"; import { useEffect } from "react"; +import { PageLoader } from "@/components/PageLoader"; import { fetchAccount } from "@/lib/account/client"; import { documentStore, indexedDbStore, NEW_DOC_ID } from "@/lib/storage/documentStore"; import { cloudOwners, isVisibleDoc } from "@/lib/sync/meta"; @@ -31,9 +32,5 @@ function EditorIndex() { navigate({ to: "/editor/$docId", params: { docId }, replace: true }); })(); }, [navigate]); - return ( -
    - Opening your drafts… -
    - ); + return ; } diff --git a/src/styles.css b/src/styles.css index 6c3c94b..2440e4b 100644 --- a/src/styles.css +++ b/src/styles.css @@ -605,3 +605,37 @@ mark.share-hl[data-active] { color: var(--muted-foreground); font-size: 0.85em; } + +/* The page loader: the logo drawn in four beats, repeating. Still when motion is reduced. */ +@keyframes page-loader-draw { + 0% { stroke-dashoffset: 1; } + 35%, 85% { stroke-dashoffset: 0; } + 100% { stroke-dashoffset: -1; } +} +@keyframes page-loader-page { + 0%, 20% { opacity: 0; transform: translateX(-8px); } + 45%, 85% { opacity: 1; transform: translateX(0); } + 100% { opacity: 0; transform: translateX(0); } +} +.page-loader-source, +.page-loader-lines, +.page-loader-prompt { + stroke-dasharray: 1; + animation: page-loader-draw 2.2s ease-in-out infinite; +} +.page-loader-prompt { animation-delay: 0.15s; } +.page-loader-lines { animation-delay: 0.6s; } +.page-loader-page { + animation: page-loader-page 2.2s ease-in-out infinite; +} +@media (prefers-reduced-motion: reduce) { + .page-loader-source, + .page-loader-lines, + .page-loader-prompt, + .page-loader-page { + animation: none; + stroke-dashoffset: 0; + opacity: 1; + transform: none; + } +} From bada9689beb06200586538698b812884c98333f2 Mon Sep 17 00:00:00 2001 From: Chizoba Jude Ojini Date: Mon, 16 Nov 2026 16:09:43 +0000 Subject: [PATCH 11/12] docs: rewrite the home page and guides, consolidate the docs (#114) * feat(guides): keep each guide's details and dates in its own front matter - slug, title, description, order, published and updated live in content/guides/.md, read at build time, so a new guide needs no code change - published and updated are UTC moments; the page shows the time when both fall on one day - site constants move to a plain module so the e2e runner can read them * docs(home): rewrite the home page around write, check, collaborate, review and publish - new hero with a real editor screenshot, the live checker second, a five-step flow with the real limits, three principles, a combined "Also in the box" and "Who it's for", a two-column FAQ of nine questions - site description, feature list and llms.txt follow the new copy; the SEO claims test now reflects that editing together, review and GitHub publishing are built * docs(guides): fix the guides, add three on review, GitHub and writing together, redesign the index - drop dev.to and Hashnode for blogging platforms in general; the guide is now markdown-for-blogging-platforms with a test-post checklist instead of per-platform claims - fix profile names, remove the repeated product paragraph, and tailor each closing - new guides: share for review, publish to GitHub, write together online or offline - published and updated carry realistic UTC times, shown on the guide page; the catalogue carries each guide's reading time - the index leads with the newest guide in a featured card, then lists the rest one per row with publish date and reading time * docs(legal): cover editing together, take legal details from front matter, relative guide links - Privacy and terms: editing together, the live connection, changing the email address, on-device search; updated date - Privacy and terms carry their own front matter (read like the guides'), and the page shows "Last updated" with its time - Guides link to the editor and each other by path, so local and preview builds stay on themselves * docs: consolidate the docs, generate llms.txt, retake screenshots - Updated existing UI screenshots to reflect recent changes in the application. - Added new screenshots for settings AI, search palette, guides index, and admin dashboard. - Enhanced README documentation to include new features such as accounts, sync, uploads, sharing, GitHub publishing, and real-time collaboration. - Introduced a new script to generate the llms.txt file from the site's content. - Improved the AI writing actions and added tests to ensure consistency. - Removed the outdated roadmap.md file and cleaned up the routes documentation. --- AGENTS.md | 8 +- README.md | 41 +-- .../commonmark-vs-github-flavored-markdown.md | 13 +- .../guides/markdown-for-blogging-platforms.md | 68 +++++ .../guides/markdown-for-devto-and-hashnode.md | 55 ---- content/guides/markdown-images.md | 13 +- content/guides/markdown-line-breaks.md | 11 +- content/guides/markdown-math-and-diagrams.md | 15 +- content/guides/markdown-portability.md | 25 +- content/guides/obsidian-to-github-markdown.md | 15 +- content/guides/publish-markdown-to-github.md | 46 +++ content/guides/share-markdown-for-review.md | 45 +++ content/guides/write-markdown-together.md | 42 +++ content/legal/privacy.md | 31 +- content/legal/terms.md | 19 +- docs/ARCHITECTURE.md | 62 ---- docs/DESIGN_SYSTEM.md | 63 +++-- docs/FEATURES_ROADMAP.md | 58 ---- docs/PRODUCT_SPEC.md | 50 ---- docs/SYSTEM_SPEC.md | 149 ++++++---- docs/UI_SPEC.md | 24 +- docs/ui-screenshots/01_home_page.png | Bin 86247 -> 123692 bytes docs/ui-screenshots/02_editor_split_view.png | Bin 147022 -> 149816 bytes .../ui-screenshots/03_editor_checks_panel.png | Bin 168480 -> 165233 bytes .../04_editor_frontmatter_panel.png | Bin 177084 -> 175874 bytes .../04_editor_outline_panel.png | Bin 146205 -> 142718 bytes docs/ui-screenshots/05_ai_writer_dialog.png | Bin 112770 -> 131519 bytes docs/ui-screenshots/06_mobile_editor_view.png | Bin 149289 -> 121360 bytes .../ui-screenshots/07_mobile_preview_view.png | Bin 128683 -> 127642 bytes docs/ui-screenshots/08_home_checker_demo.png | Bin 90668 -> 93649 bytes docs/ui-screenshots/09_editor_dark.png | Bin 146635 -> 149310 bytes docs/ui-screenshots/10_checker_rules.png | Bin 141957 -> 153610 bytes docs/ui-screenshots/11_export_menu.png | Bin 179717 -> 186171 bytes docs/ui-screenshots/12_history_compare.png | Bin 119952 -> 128457 bytes docs/ui-screenshots/13_library.png | Bin 79669 -> 82649 bytes docs/ui-screenshots/14_share_dialog.png | Bin 117220 -> 117931 bytes docs/ui-screenshots/15_comments_panel.png | Bin 141193 -> 123806 bytes .../16_shared_page_comments.png | Bin 87868 -> 92203 bytes docs/ui-screenshots/17_shared_page_phone.png | Bin 149923 -> 147461 bytes docs/ui-screenshots/18_private_link_gate.png | Bin 35088 -> 32740 bytes docs/ui-screenshots/19_publish_connect.png | Bin 115074 -> 115931 bytes docs/ui-screenshots/20_publish_github.png | Bin 109589 -> 111521 bytes docs/ui-screenshots/21_settings_ai.png | Bin 0 -> 45341 bytes docs/ui-screenshots/22_search_palette.png | Bin 0 -> 78794 bytes docs/ui-screenshots/23_guides_index.png | Bin 0 -> 111618 bytes docs/ui-screenshots/24_admin_dashboard.png | Bin 0 -> 40348 bytes e2e/guides.spec.ts | 33 ++- e2e/legal.spec.ts | 6 +- infra/README.md | 2 +- infra/guide-catalogue-plugin.ts | 38 +++ infra/guide-catalogue.ts | 52 ++++ infra/legal-catalogue.ts | 33 +++ package.json | 1 + public/home-editor-dark.png | Bin 0 -> 122415 bytes public/home-editor-light.png | Bin 0 -> 122825 bytes public/llms.txt | 70 +++-- roadmap.md | 87 ------ scripts/llms.ts | 7 + scripts/screenshots.mjs | 52 +++- src/components/site/LegalPage.tsx | 4 +- src/env.d.ts | 12 + src/lib/ai/actions.test.ts | 2 +- src/lib/site/guides-content.test.ts | 15 + src/lib/site/guides-content.ts | 21 +- src/lib/site/guides.test.ts | 35 ++- src/lib/site/guides.ts | 78 +----- src/lib/site/legal-content.ts | 5 +- src/lib/site/legal.test.ts | 32 ++- src/lib/site/legal.ts | 32 +-- src/lib/site/llms.test.ts | 19 ++ src/lib/site/llms.ts | 44 +++ src/lib/site/seo-content.ts | 103 +++---- src/lib/site/seo.test.ts | 19 +- src/lib/site/seo.ts | 16 +- src/lib/site/site.ts | 18 ++ src/routes/README.md | 21 -- src/routes/guides.$slug.tsx | 20 +- src/routes/guides.index.tsx | 89 ++++-- src/routes/index.tsx | 264 ++++++++---------- vite.config.ts | 3 + vitest.config.ts | 3 +- 81 files changed, 1210 insertions(+), 879 deletions(-) create mode 100644 content/guides/markdown-for-blogging-platforms.md delete mode 100644 content/guides/markdown-for-devto-and-hashnode.md create mode 100644 content/guides/publish-markdown-to-github.md create mode 100644 content/guides/share-markdown-for-review.md create mode 100644 content/guides/write-markdown-together.md delete mode 100644 docs/ARCHITECTURE.md delete mode 100644 docs/FEATURES_ROADMAP.md delete mode 100644 docs/PRODUCT_SPEC.md create mode 100644 docs/ui-screenshots/21_settings_ai.png create mode 100644 docs/ui-screenshots/22_search_palette.png create mode 100644 docs/ui-screenshots/23_guides_index.png create mode 100644 docs/ui-screenshots/24_admin_dashboard.png create mode 100644 infra/guide-catalogue-plugin.ts create mode 100644 infra/guide-catalogue.ts create mode 100644 infra/legal-catalogue.ts create mode 100644 public/home-editor-dark.png create mode 100644 public/home-editor-light.png delete mode 100644 roadmap.md create mode 100644 scripts/llms.ts create mode 100644 src/lib/site/llms.test.ts create mode 100644 src/lib/site/llms.ts create mode 100644 src/lib/site/site.ts delete mode 100644 src/routes/README.md diff --git a/AGENTS.md b/AGENTS.md index a5c465b..c5e7aec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,10 +14,9 @@ mdstudio is built for writers, developers, technical bloggers, and documentation Before proposing or making changes, read: -1. `docs/SYSTEM_SPEC.md`: the master source of truth (product, architecture, schema, decisions). The end-to-end use cases are in `docs/PRODUCT_SPEC.md`. +1. `docs/SYSTEM_SPEC.md`: the master source of truth (product, architecture, schema, decisions). The end-to-end use cases are in its section 1, and what is planned or not built yet is in its section 12. 2. This file: the non-negotiable invariants. -3. `roadmap.md`: milestones and pending work. -4. As needed: `docs/UI_SPEC.md` and `docs/DESIGN_SYSTEM.md` (screens and tokens), `infra/README.md` (backend blueprints), `docs/RELEASING.md` (releases and secrets). +3. As needed: `docs/UI_SPEC.md` and `docs/DESIGN_SYSTEM.md` (screens and tokens), `infra/README.md` (backend blueprints), `docs/RELEASING.md` (releases and secrets). --- @@ -77,6 +76,9 @@ All backend code lives in or is scaffolded via `infra/` (see `infra/README.md`): - **Compatibility:** Do not use Node.js standard library modules (`fs`, `path`, `crypto`, ...) in client-side code; client code must run in all browsers and on Cloudflare Workers. Node APIs are fine in `scripts/` and the Node-only `infra/` drivers. - **Types:** Prefer clean types and deterministic state machines. The TypeScript config is strict (`exactOptionalPropertyTypes`, `noUncheckedIndexedAccess`). - **Tailwind classes:** write them in the form Tailwind recommends (`size-4` not `h-4 w-4`, `shrink-0` not `flex-shrink-0`, `data-disabled:` not `data-[disabled]:`, `wrap-break-word` not `break-words`). `bun run tailwind:check` lists anything that is not, CI runs it, and `bun run tailwind:fix` rewrites it using Tailwind's own rules. +- **UI conventions:** every button that starts an action shows `loading` (the one pressed) or `pending` (its siblings), never a bare `disabled`; every dropdown uses the shared `Select`; action labels never end in an ellipsis. The rules and the reasons are in `docs/DESIGN_SYSTEM.md`, and a test (`loading-rules.test.ts`) enforces the first. +- **Public pages:** a guide (`content/guides/.md`) and a legal page (`content/legal/.md`) say what they are in their own front matter (slug, title, description, and `published` and `updated` as UTC moments); adding one needs no code change. Set `updated` when you change one. +- **Docs:** a change that alters what the app does, how it looks or how it is built updates `docs/SYSTEM_SPEC.md` and `docs/UI_SPEC.md` in the same change; the home copy and the FAQ live in `src/lib/site/seo-content.ts`, and `public/llms.txt` is generated from it (`bun run llms`). - **Accessibility:** Build accessible UX by default (Radix primitives, roving focus on toolbars, labelled controls). --- diff --git a/README.md b/README.md index 2ea2752..a9b7e20 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@

    Write Markdown once. See exactly how it renders everywhere.
    - An open-source, local-first Markdown editor with a faithful live preview and a portability checker for GitHub, dev.to and Obsidian. + An open-source, local-first Markdown editor with a faithful live preview and a portability checker for GitHub, blogging platforms and Obsidian.

    @@ -30,17 +30,20 @@ mdstudio keeps your **raw Markdown as the single source of truth**. The preview - **Faithful live preview.** Strict CommonMark and GitHub Flavored Markdown, sanitized, with syntax-highlighted code. Scrolling stays aligned line by line, and clicking a block in the preview puts the editor cursor on its source line. - **Portability checker.** Raw HTML, local images and links, base64 images, wiki-links, `==highlights==`, math, Mermaid, trailing-space line breaks, missing alt text, unclosed tags and more. Every issue is clickable. Turn rules on or off, add publication standards (title and description length, required front matter, heading structure) and your own text or regex rules, and share them as a JSON file. - **Target profiles.** Strict CommonMark, GFM extended, GFM without HTML, and Wiki notes. The preview, the checks and the toolbar warnings follow your choice. +- **Edit together.** Invite people by email and edit one draft at the same time, online or offline: live cursors, per-person undo, and offline edits merge when the network returns (Yjs). Up to 3 people per draft by default. +- **Review links.** Share an expiring read-only copy (1 to 7 days), public or for named people only. Signed-in readers comment on the words they select, and you resolve the comments from the editor. +- **Publish to GitHub.** Commit or open a pull request to a repository, or post a gist, with the images committed beside the file. - **Complete formatting toolbar.** Marks, headings, lists, task lists, links, images, footnotes, rules, code blocks, tables with cell navigation, GitHub alerts, math, diagrams and HTML helpers. Fully keyboard accessible. - **Math and diagrams.** KaTeX and Mermaid, rendered on demand, themed for light and dark. -- **Local-first and private.** Drafts autosave to your browser's IndexedDB. No account, no uploads. -- **A library that scales.** Search every draft, filter by tag, organise drafts in folders (drag and drop), and rename them without touching the text. +- **Local-first.** Drafts autosave to your browser's IndexedDB and everything works offline with no account. Anything that leaves your device (cloud drafts, share links, publishing) is a choice you make per draft. +- **A library that scales.** Search every draft and the words inside them, filter by tag, organise drafts in folders (drag and drop), and rename them without touching the text. One search (Ctrl/⌘ K) also finds commands, settings and pages. - **Version history.** Versions are kept automatically as you write; compare any of them side by side with the current draft and restore it. - **Works offline.** The studio keeps working with no connection and can be installed as an app. - **Import and export.** Open `.md` files, a ZIP or a whole folder, or paste from Google Docs, Notion and the web. Export clean UTF-8 Markdown (LF endings), self-contained Markdown with embedded images, standalone HTML, or every draft at once as a ZIP. -- **Optional AI writer and inline AI actions, bring your own key.** OpenAI, Anthropic, Gemini or any OpenAI-compatible endpoint (Ollama, OpenRouter, Groq). Keys stay in session memory and requests go straight from your browser to the provider. +- **AI on your own key.** A writer for titles, descriptions and drafts, inline actions on the selection (rewrite, shorten, translate, proofread), and Fix with AI on a flagged check, always shown as a diff you accept or reject. OpenAI, Anthropic, Gemini, Ollama or any OpenAI-compatible endpoint. Keys stay in session memory and requests go straight from your browser to the provider. - **Responsive and themed.** Split view on desktop, single pane with drawers on phones, light and dark mode. -- **Self-hostable.** One Docker container with SQLite, or Cloudflare Workers. -- **Guides.** Seven practical [guides to portable Markdown](https://mdstudio.deityhub.com/guides), written in Markdown and rendered by mdstudio itself. +- **Self-hostable.** One Docker container with SQLite, or Cloudflare Workers (D1, R2 and Durable Objects). The hosted site is the same code. An admin dashboard manages accounts, plans, limits and server settings. +- **Guides.** Practical [guides](https://mdstudio.deityhub.com/guides) on portable Markdown, reviewing, writing together and publishing, written in Markdown and rendered by mdstudio itself.

    The drafts library with search, tags and folders @@ -52,6 +55,11 @@ mdstudio keeps your **raw Markdown as the single source of truth**. The preview Publishing a draft to a GitHub repository

    +

    + Settings: the AI tab listing its integrations + The search palette finding a command and a guide +

    +

    mdstudio in dark mode mdstudio on a phone @@ -96,9 +104,9 @@ The app is served on with data in the `mdstudio-data` vo - **Engine.** [unified](https://unifiedjs.com): remark-parse, GFM, front matter, math, remark-rehype, rehype-sanitize, then highlighting. The output is always sanitized. All Markdown logic lives in [`src/lib/markdown/markdown.ts`](src/lib/markdown/markdown.ts). - **Editor.** CodeMirror 6, loaded only in the browser. Editing commands are pure functions with their own tests. - **Storage.** Raw IndexedDB behind a small `documentStore` interface. -- **Security.** Nonce-based Content-Security-Policy in production, sanitized preview, no server in the writing path. +- **Security.** Nonce-based Content-Security-Policy in production, a sanitized preview, and no server in the writing path unless you choose a cloud feature. - **Stack.** TanStack Start, React 19, Vite, Tailwind CSS v4, Radix UI. -- **Backend blueprints.** One Drizzle SQLite schema shared by Cloudflare D1 and `better-sqlite3`, with R2 or disk storage. See [`infra/`](infra/README.md); it is activated in milestone 3. +- **Backend.** One Drizzle SQLite schema shared by Cloudflare D1 and `better-sqlite3`, with R2 or disk storage, cookie sessions, a WebSocket channel on Durable Objects (in process when self-hosted) and a Yjs room per live draft. See [`infra/`](infra/README.md). ## Development @@ -112,23 +120,22 @@ The app is served on with data in the `mdstudio-data` vo | `bun run licenses` | Audits dependency licenses against the policy | | `bun run screenshots` | Regenerates the UI screenshots in `docs/ui-screenshots` | | `bun run brand` | Regenerates the icons and social card | +| `bun run llms` | Regenerates `public/llms.txt` from the site copy | Read [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request: branch from `dev`, write the test first, and use Conventional Commits. ## Documentation -| Document | Contents | -| ------------------------------------------------------------------------------------- | --------------------------------------------------------- | -| [docs/SYSTEM_SPEC.md](docs/SYSTEM_SPEC.md) | Source of truth: product, architecture, schema, decisions | -| [docs/PRODUCT_SPEC.md](docs/PRODUCT_SPEC.md) | The end-to-end use cases | -| [docs/UI_SPEC.md](docs/UI_SPEC.md) and [docs/DESIGN_SYSTEM.md](docs/DESIGN_SYSTEM.md) | Screens and design tokens | -| [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) | Modules and routes | -| [docs/RELEASING.md](docs/RELEASING.md) | Cutting a release and the required secrets | -| [roadmap.md](roadmap.md) | What is done and what is next | +| Document | Contents | +| ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| [docs/SYSTEM_SPEC.md](docs/SYSTEM_SPEC.md) | Source of truth: product and use cases, architecture, schema, API, decisions | +| [docs/UI_SPEC.md](docs/UI_SPEC.md) and [docs/DESIGN_SYSTEM.md](docs/DESIGN_SYSTEM.md) | Every screen, and the design tokens and conventions | +| [docs/RELEASING.md](docs/RELEASING.md) | Cutting a release and the required secrets | +| [infra/README.md](infra/README.md) | The backend blueprints and how to run them | ## Roadmap -Next up: v0.1.0, then accounts with sync, hosted images and share links. Details in [roadmap.md](roadmap.md). +What is planned and what is not built yet is in the [system spec](docs/SYSTEM_SPEC.md), and what is released is in the [changelog](CHANGELOG.md). ## Contributing, security and license diff --git a/content/guides/commonmark-vs-github-flavored-markdown.md b/content/guides/commonmark-vs-github-flavored-markdown.md index 3007927..cb656d4 100644 --- a/content/guides/commonmark-vs-github-flavored-markdown.md +++ b/content/guides/commonmark-vs-github-flavored-markdown.md @@ -1,3 +1,12 @@ +--- +slug: commonmark-vs-github-flavored-markdown +title: "CommonMark vs GitHub Flavored Markdown: What Differs" +description: "A clear comparison of CommonMark and GitHub Flavored Markdown: tables, task lists, strikethrough, footnotes, autolinks and alerts, and when each one matters." +order: 2 +published: 2026-11-02T09:57:00Z +updated: 2026-11-16T09:41:00Z +--- + CommonMark and GitHub Flavored Markdown (GFM) are the two Markdown standards you will meet most often. GFM is a strict superset of CommonMark, which means every valid CommonMark document is also valid GFM, but not the other way round. Knowing exactly what GFM adds tells you when your text stops being universally portable. ## What CommonMark is @@ -53,6 +62,6 @@ Other platforms may support some of these, all of them or none. That is why a do - Footnotes and alerts are not CommonMark and not part of the GFM specification, so check each target. - Raw HTML is allowed by CommonMark, but GFM filters a small set of dangerous tags and most platforms sanitize far more. -## Check which flavor you are using +## See which flavor your text uses -It is easy to use a GFM feature without noticing. [mdstudio](https://mdstudio.deityhub.com/editor) lets you switch the target profile between Strict CommonMark, GitHub (GFM extended), GFM without HTML or Wiki notes. On Strict CommonMark, the checker flags every table, task list, strikethrough and footnote as a GFM extension, so you can see exactly where your text depends on one. The editor is open source and keeps your drafts in your browser. Read more in the [portable Markdown guide](https://mdstudio.deityhub.com/guides/markdown-portability). +It is easy to use a GFM feature without noticing. Open the text in [mdstudio](/editor) and switch the target to Strict CommonMark: the checker flags every table, task list, strikethrough and footnote as a GFM extension, so you can see exactly where your text depends on one. The [portable Markdown guide](/guides/markdown-portability) has the wider checklist. diff --git a/content/guides/markdown-for-blogging-platforms.md b/content/guides/markdown-for-blogging-platforms.md new file mode 100644 index 0000000..0c306d2 --- /dev/null +++ b/content/guides/markdown-for-blogging-platforms.md @@ -0,0 +1,68 @@ +--- +slug: markdown-for-blogging-platforms +title: Writing Markdown for Blogging Platforms +description: "Write Markdown that publishes cleanly to blogging platforms and site tools: front matter, images, raw HTML and a test post before you rely on an extra feature." +order: 4 +published: 2026-11-02T13:08:00Z +updated: 2026-11-16T10:52:00Z +--- + +Most blogging platforms, publishing tools and static site generators let you write in Markdown, which makes it tempting to draft in your own editor and paste the result. That works well, as long as you know where each tool differs from the Markdown you write locally. This guide covers the habits that make a post publish cleanly the first time, without claiming to know the rules of any one platform: those change, and the platform's own documentation is the authority. + +## They all read Markdown, and then add their own rules + +Headings, lists, links, images, block quotes, tables and fenced code blocks are common ground. Beyond that, each tool adds its own features, such as embed tags for videos and social posts, shortcodes, or a plugin system, and each processes your text before showing it to readers. Some sanitize HTML, some rewrite links, some turn single newlines into line breaks. The same file can come out differently in each. + +## Start with front matter + +Many tools read a YAML block at the top of the file for the title, a description, tags, a date and a draft flag. The field names differ from tool to tool, so check the ones your target reads, and keep the block valid YAML: + +```md +--- +title: Writing portable Markdown +description: A short summary for previews and search. +tags: markdown, writing +draft: true +--- +``` + +Keep the number of tags within what the platform allows, and keep the post marked as a draft until you have previewed it there. A tool that does not understand a field usually ignores it, but one that is strict about unknown fields may refuse the post. + +## Do not rely on raw HTML + +Platforms sanitize HTML, and what survives can change. Alignment wrappers, custom styles, iframes and scripts are the usual casualties. If you can express something in Markdown, do. Use a Markdown table instead of an HTML one, bold instead of a styled span, and the platform's own embed syntax for videos and social posts. + +## Images need public URLs + +A relative path such as an `images` folder only exists on your computer, unless the tool publishes from a repository that contains it. Upload each image through the platform's editor and use the URL it returns, or host the images somewhere stable. Add alt text to every image: it helps screen readers, and it is what readers see if the image fails to load. Avoid embedding large base64 images in the text, since they bloat the post and are often rejected. + +```md +![A flow chart of the publishing process](https://example.com/images/publish-flow.png) +``` + +## Code blocks and highlighting + +Always put a language after the opening fence. It enables syntax highlighting, and it keeps your code readable if the post is copied to another site. + +````md +```ts +export const greet = (name: string) => `Hello, ${name}`; +``` +```` + +## Test post: what to try before you rely on it + +The features most likely to behave differently are the ones outside CommonMark. Before you build a post around one, publish a private or draft test post that uses each of these once, and look at the result: + +- Math written with dollar signs. +- A Mermaid diagram in a fenced block. +- A footnote, a task list and a table. +- A GitHub-style alert (a block quote starting with a marker such as NOTE). +- An Obsidian wiki-link, which prints as literal brackets almost everywhere. +- Raw HTML with an alignment attribute. + +Write down what works for that platform. It takes ten minutes once and saves you from finding out in front of readers. For a diagram you cannot afford to lose, use an image. See the guide to [math and Mermaid in Markdown](/guides/markdown-math-and-diagrams). + +## Preview before you publish + +[mdstudio](/editor) can hold the text to the stricter rules while you write. Choose the GFM without HTML target: raw HTML is reported as an error there, and the checker also catches local images, wiki-links, math, Mermaid and trailing-space line breaks, each with a click to jump to the line. If your tool builds pages from a Git repository, you can also publish the draft straight to it as a commit or a pull request. For a wider checklist, read the [portable Markdown guide](/guides/markdown-portability). diff --git a/content/guides/markdown-for-devto-and-hashnode.md b/content/guides/markdown-for-devto-and-hashnode.md deleted file mode 100644 index 12a2fb9..0000000 --- a/content/guides/markdown-for-devto-and-hashnode.md +++ /dev/null @@ -1,55 +0,0 @@ -dev.to and Hashnode both let you write posts in Markdown, which makes it tempting to draft in your own editor and paste the result. That works well, as long as you know where each platform differs from the Markdown you write locally. This guide covers the habits that make a post publish cleanly the first time. - -## Both are Markdown, with their own rules - -dev.to and Hashnode follow common Markdown conventions: headings, lists, links, images, block quotes, tables and fenced code blocks. Each adds its own features on top, such as embed tags for videos and social posts, and each processes your text before showing it to readers. The details change over time, so treat the points below as habits rather than guarantees, and check the platform's current editor guide for anything unusual. - -## Start with front matter - -dev.to reads a YAML block at the top of the post, which sets the title, tags and publishing state: - -```md ---- -title: Writing portable Markdown -published: false -description: A short summary for previews and search. -tags: markdown, writing ---- -``` - -Keep the block valid YAML, keep tags to the number the platform allows, and set `published: false` until you have previewed the post. Hashnode takes much of this from its editor settings instead, so check how it handles imported metadata. - -## Do not rely on raw HTML - -Both platforms sanitize HTML, and what survives can change. Alignment wrappers, custom styles, iframes and scripts are the usual casualties. If you can express something in Markdown, do. Use a Markdown table instead of an HTML one, bold instead of a styled span, and the platform's own embed syntax for videos and tweets. - -## Images need public URLs - -A relative path such as an `images` folder only exists on your computer. Upload each image through the platform's editor and use the URL it returns, or host the images somewhere stable. Add alt text to every image: it helps screen readers, and it is what readers see if the image fails to load. Avoid embedding large base64 images in the text, since they bloat the post and are often rejected. - -```md -![A flow chart of the publishing process](https://example.com/images/publish-flow.png) -``` - -## Code blocks and highlighting - -Always put a language after the opening fence. It enables syntax highlighting, and it keeps your code readable if the post is copied to another site. - -````md -```ts -export const greet = (name: string) => `Hello, ${name}`; -``` -```` - -## Things that often do not render - -- Math written with dollar signs may show as plain text. -- Mermaid diagrams written in a fenced block may show as code rather than a diagram. -- Obsidian wiki-links print as literal brackets. -- Footnotes and GitHub-style alerts may not be supported. - -Check each against the platform before you rely on it, and prefer an image for diagrams you cannot afford to lose. See the guide to [math and Mermaid in Markdown](https://mdstudio.deityhub.com/guides/markdown-math-and-diagrams). - -## Preview before you publish - -The fastest safeguard is to check the post against the rules of your target before you paste it. In [mdstudio](https://mdstudio.deityhub.com/editor), choose the GFM without HTML profile. Raw HTML is reported as an error there, and the checker also catches local images, wiki-links, math, Mermaid and trailing-space line breaks, each with a click to jump to the line. The editor is open source and keeps drafts in your browser. For a wider checklist, read the [portable Markdown guide](https://mdstudio.deityhub.com/guides/markdown-portability). diff --git a/content/guides/markdown-images.md b/content/guides/markdown-images.md index d695d0f..4404621 100644 --- a/content/guides/markdown-images.md +++ b/content/guides/markdown-images.md @@ -1,3 +1,12 @@ +--- +slug: markdown-images +title: "Markdown Images: Paths, Alt Text and Portability" +description: "How to add images in Markdown so they show up everywhere: relative paths, hosted URLs, base64 data URIs, alt text and the mistakes that break previews." +order: 6 +published: 2026-11-02T15:49:00Z +updated: 2026-11-16T11:46:00Z +--- + Images are the most common reason a Markdown post looks broken after publishing. The text copies perfectly, and then every picture shows as a missing icon. The cause is almost always the path, and the fix is to understand where each kind of image link actually works. ## The basic syntax @@ -14,7 +23,7 @@ You can add an optional title in quotes after the address. It usually shows as a 1. **A hosted URL.** An absolute web address works anywhere the image is reachable. This is the most portable choice. 2. **A relative path.** A path such as `images/chart.png` only works when the Markdown file and the image sit in the same place the renderer expects. It works in a repository README and in many static site generators. It fails when you paste the text into another site. -3. **A platform upload.** On sites like dev.to, you upload through the editor and it gives you a hosted URL. Use that URL in the text. +3. **A platform upload.** Many publishing tools let you upload through their own editor and give you a hosted URL. Use that URL in the text. 4. **A base64 data URI.** The image data is embedded in the text itself. It is self-contained, but it makes the file huge and many platforms reject or strip it. ## Why local paths fail @@ -40,4 +49,4 @@ Alt text is the description shown when an image fails to load, and what screen r ## Find broken image links before you publish -[mdstudio](https://mdstudio.deityhub.com/editor) flags local image paths, embedded base64 images and images with missing alt text, with a click to jump to each one. When you insert an image, the dialog requires alt text. You can also export a self-contained Markdown or HTML file that embeds your local images, so the document works on its own. The editor is open source and keeps your drafts in your browser. For the wider picture, read the [portable Markdown guide](https://mdstudio.deityhub.com/guides/markdown-portability). +[mdstudio](/editor) flags local image paths, embedded base64 images and images with missing alt text, with a click to jump to each one, and its insert-image dialog will not accept an empty alt text. When a draft has to travel as one file, export a self-contained Markdown or HTML file that embeds the local images. When you publish to GitHub, the images are committed beside the file. On a self-hosted install it can also host the images for you and rewrite the paths. For the wider picture, read the [portable Markdown guide](/guides/markdown-portability). diff --git a/content/guides/markdown-line-breaks.md b/content/guides/markdown-line-breaks.md index 9164483..24d5cc0 100644 --- a/content/guides/markdown-line-breaks.md +++ b/content/guides/markdown-line-breaks.md @@ -1,3 +1,12 @@ +--- +slug: markdown-line-breaks +title: Markdown Line Breaks and Paragraphs Explained +description: "How line breaks work in Markdown: paragraphs, soft breaks and hard breaks, why trailing spaces are fragile, and which method renders the same everywhere." +order: 5 +published: 2026-11-02T14:31:00Z +updated: 2026-11-16T11:17:00Z +--- + Line breaks are one of the most confusing parts of Markdown. You press Enter, and nothing happens in the preview, or everything runs together, or it works on one site and not another. The behavior is actually well defined, and once you know the rules you can pick the method that survives every platform. ## Paragraphs, soft breaks and hard breaks @@ -49,4 +58,4 @@ Some editors turn every newline into a break to feel friendlier. That makes the ## Catch fragile breaks automatically -[mdstudio](https://mdstudio.deityhub.com/editor) renders soft breaks the way CommonMark defines them, so single newlines do not turn into breaks in the preview. Its portability checker also flags trailing-space line breaks, so you can replace them before an editor strips them. The editor is open source and keeps your drafts in your browser, unless you want to sync it to the cloud. For related pitfalls, read the [portable Markdown guide](https://mdstudio.deityhub.com/guides/markdown-portability). +[mdstudio](/editor) renders soft breaks the way CommonMark defines them, so a single newline does not turn into a break in the preview. Its checker also flags trailing-space line breaks, so you can replace them with a backslash before an editor strips them. For related pitfalls, read the [portable Markdown guide](/guides/markdown-portability). diff --git a/content/guides/markdown-math-and-diagrams.md b/content/guides/markdown-math-and-diagrams.md index 66fa199..ad62588 100644 --- a/content/guides/markdown-math-and-diagrams.md +++ b/content/guides/markdown-math-and-diagrams.md @@ -1,3 +1,12 @@ +--- +slug: markdown-math-and-diagrams +title: "Math and Mermaid Diagrams in Markdown: Where They Work" +description: "Where LaTeX math and Mermaid diagrams render in Markdown: GitHub and Obsidian support them, other platforms do not. How to write them and what to do instead." +order: 7 +published: 2026-11-02T16:36:00Z +updated: 2026-11-16T12:09:00Z +--- + LaTeX math and Mermaid diagrams are two of the most useful extensions to Markdown, and two of the least portable. They render beautifully on some platforms and show up as raw source on others. This guide shows how to write them and where they work, so you can decide when to use them. ## Math in Markdown @@ -40,9 +49,9 @@ Mermaid supports flowcharts, sequence diagrams, class diagrams, state diagrams, | GitHub | Yes | Yes | | Obsidian | Yes | Yes | | Strict CommonMark | No | No | -| dev.to and Hashnode | Not from plain syntax | Not from plain syntax | +| Blogging platforms and site generators | Depends on the platform | Depends on the platform | -Some platforms offer their own non-standard embed tags for math or diagrams. Those do not work anywhere else, which is the trade-off to weigh. +Some platforms offer their own non-standard embed tags for math or diagrams, and others need a plugin or a setting. Check the one you publish to with a test post before you rely on it. Embed tags do not work anywhere else, which is the trade-off to weigh. ## What to do when the target does not support them @@ -59,4 +68,4 @@ Rendering user-provided math and diagrams carries some risk, since both are pars ## Preview them against your target -[mdstudio](https://mdstudio.deityhub.com/editor) renders math with KaTeX and diagrams with Mermaid in strict mode, in light and dark themes, and shows them only for the profiles whose platforms support them. On the GFM without HTML or Strict CommonMark profile, the checker warns that math and Mermaid are not portable, and the toolbar marks the tools that the target will not render. The editor is open source and keeps your drafts in your browser. For more on compatibility, read the [portable Markdown guide](https://mdstudio.deityhub.com/guides/markdown-portability). +[mdstudio](/editor) renders math with KaTeX and diagrams with Mermaid in strict mode, in light and dark themes, and only for the targets that support them. On GFM without HTML or Strict CommonMark the checker warns that math and Mermaid are not portable, and the toolbar marks the tools that target will not render. For more on compatibility, read the [portable Markdown guide](/guides/markdown-portability). diff --git a/content/guides/markdown-portability.md b/content/guides/markdown-portability.md index f2dc8bf..230e964 100644 --- a/content/guides/markdown-portability.md +++ b/content/guides/markdown-portability.md @@ -1,4 +1,13 @@ -Markdown looks like one language, but it is really a family of dialects. The same file can render perfectly on GitHub, lose a diagram on dev.to and print raw brackets in a static site generator. This guide explains why that happens and gives you a checklist for writing Markdown that renders the same everywhere. +--- +slug: markdown-portability +title: "Portable Markdown: Why It Renders Differently Everywhere" +description: Why the same Markdown looks different on GitHub, blogging platforms and Obsidian, and a checklist for making your writing render the same on every platform. +order: 1 +published: 2026-11-02T08:42:00Z +updated: 2026-11-16T09:14:00Z +--- + +Markdown looks like one language, but it is really a family of dialects. The same file can render perfectly on GitHub, lose a diagram on a blogging platform and print raw brackets in a static site generator. This guide explains why that happens and gives you a checklist for writing Markdown that renders the same everywhere. ## Why the same Markdown renders differently @@ -6,7 +15,7 @@ The original Markdown description left many details open, so every tool made its - GitHub adds alerts, math, Mermaid diagrams and footnotes. - Obsidian adds wiki-links, embeds, highlights and callouts. -- dev.to and Hashnode add their own front matter, embed tags and sanitizing rules. +- Blogging platforms add their own front matter, embed tags and sanitizing rules. - Static site generators each add shortcodes, plugins or MDX. Your text is only portable if every platform you care about understands every construct in it. @@ -14,10 +23,10 @@ Your text is only portable if every platform you care about understands every co ## The six things that break most often 1. **Raw HTML.** Platforms sanitize HTML differently. A `div` with an alignment attribute may survive on GitHub and be stripped elsewhere. Prefer Markdown for everything Markdown can express. -2. **Local images.** An image link like `images/diagram.png` works on your machine and nowhere else. Use a hosted URL or upload the image to the platform. See the [guide to Markdown images](https://mdstudio.deityhub.com/guides/markdown-images). +2. **Local images.** An image link like `images/diagram.png` works on your machine and nowhere else. Use a hosted URL or upload the image to the platform. See the [guide to Markdown images](/guides/markdown-images). 3. **Wiki-links.** Obsidian links such as the double-bracket form below are meaningless outside Obsidian and print as literal text. -4. **Math and diagrams.** LaTeX math and Mermaid diagrams render on GitHub and Obsidian, but many other places show the raw source. See [math and Mermaid in Markdown](https://mdstudio.deityhub.com/guides/markdown-math-and-diagrams). -5. **Line breaks.** Whether a single newline becomes a visible break depends on the platform. See [Markdown line breaks](https://mdstudio.deityhub.com/guides/markdown-line-breaks). +4. **Math and diagrams.** LaTeX math and Mermaid diagrams render on GitHub and Obsidian, but many other places show the raw source. See [math and Mermaid in Markdown](/guides/markdown-math-and-diagrams). +5. **Line breaks.** Whether a single newline becomes a visible break depends on the platform. See [Markdown line breaks](/guides/markdown-line-breaks). 6. **Extensions.** Tables, task lists, footnotes, strikethrough and alerts are not part of strict CommonMark. ```md @@ -37,8 +46,6 @@ Before you publish, run through this list: - Avoid trailing-space line breaks, which editors often strip. A backslash at the end of the line is clearer. - Open the result on the target platform, or in a preview that follows its rules, before you hit publish. -## Check it automatically - -Reading a checklist is slow and easy to forget. [mdstudio](https://mdstudio.deityhub.com/editor) is an open-source Markdown editor built around this problem. Choose a target profile (Strict CommonMark, GitHub (GFM extended), GFM without HTML or Wiki notes), and its portability checker flags raw HTML, local images, wiki-links, math, Mermaid, trailing-space breaks and more, with a click to jump to each one. The preview shows what that platform renders, with no preview-only tricks, so what you see is what ships. +## Let the editor do the checking -Your drafts stay in your browser, there is no account requirement unless you want to use the cloud features, and the project is open source under the MIT license. [Open the editor](https://mdstudio.deityhub.com/editor) and paste in a post to see what it finds. +Run the checklist against your own text in [mdstudio](/editor). Pick a target (Strict CommonMark, GFM extended, GFM without HTML or Wiki notes) and the Checks panel lists each problem with its line number: raw HTML, local images, wiki-links, math, Mermaid and trailing-space breaks. The preview follows the same rules, so you see the result before you publish. Paste a post in to try it. diff --git a/content/guides/obsidian-to-github-markdown.md b/content/guides/obsidian-to-github-markdown.md index cc150a2..9e6bce5 100644 --- a/content/guides/obsidian-to-github-markdown.md +++ b/content/guides/obsidian-to-github-markdown.md @@ -1,4 +1,13 @@ -Obsidian stores notes as plain Markdown files, which makes them easy to share, but Obsidian adds syntax that other tools do not understand. If you copy a note straight into a GitHub README, a dev.to post or a static site, some of it will break. This guide lists what to convert and how. +--- +slug: obsidian-to-github-markdown +title: "Obsidian to GitHub Markdown: Wiki-links, Callouts & More" +description: "How to share Obsidian notes outside Obsidian: convert wiki-links, highlights, callouts and embeds so they render on GitHub, blogging platforms and static sites." +order: 3 +published: 2026-11-02T11:23:00Z +updated: 2026-11-16T10:08:00Z +--- + +Obsidian stores notes as plain Markdown files, which makes them easy to share, but Obsidian adds syntax that other tools do not understand. If you copy a note straight into a GitHub README, a blog post or a static site, some of it will break. This guide lists what to convert and how. ## What Obsidian adds to Markdown @@ -58,8 +67,8 @@ Obsidian callouts look like a block quote that starts with a type in square brac ## What does carry over -Headings, emphasis, lists, task lists, tables, footnotes, code blocks, math and Mermaid diagrams are all standard on GitHub too, so these usually need no changes. Math and Mermaid still fail on platforms that do not render them. See [math and Mermaid in Markdown](https://mdstudio.deityhub.com/guides/markdown-math-and-diagrams). +Headings, emphasis, lists, task lists, tables, footnotes, code blocks, math and Mermaid diagrams are all standard on GitHub too, so these usually need no changes. Math and Mermaid still fail on platforms that do not render them. See [math and Mermaid in Markdown](/guides/markdown-math-and-diagrams). ## Let a checker find them -Doing this by eye across a long note is error prone. Paste the note into [mdstudio](https://mdstudio.deityhub.com/editor) and switch the target profile to Strict CommonMark, GitHub (GFM extended), GFM without HTML or Wiki notes. The portability checker lists every wiki-link, highlight, local image and other non-portable construct with a clickable line number. Switch to the Obsidian profile and the wiki-link and highlight warnings disappear, which shows exactly what is Obsidian-only. The editor is open source and local-first. For the bigger picture, read the [portable Markdown guide](https://mdstudio.deityhub.com/guides/markdown-portability). +Doing this by eye across a long note is error prone. Paste the note into [mdstudio](/editor) and choose GFM extended: the checker lists every wiki-link, highlight and local image with a clickable line number. Then choose Wiki notes and the wiki-link and highlight warnings go away, which shows exactly what is Obsidian-only. For the bigger picture, read the [portable Markdown guide](/guides/markdown-portability). diff --git a/content/guides/publish-markdown-to-github.md b/content/guides/publish-markdown-to-github.md new file mode 100644 index 0000000..fdf56bf --- /dev/null +++ b/content/guides/publish-markdown-to-github.md @@ -0,0 +1,46 @@ +--- +slug: publish-markdown-to-github +title: Publish Markdown to GitHub from an Editor +description: "Send a Markdown draft to a GitHub repository as a commit, a pull request or a gist, with its images, and what to know about connecting and republishing." +order: 9 +published: 2026-11-16T11:03:00Z +updated: 2026-11-16T11:03:00Z +--- + +For a README, a documentation page or a blog kept in a repository, the last step is copying the text into a file, committing it, and fixing the image paths. It is easy to get one of those wrong. Publishing straight from the editor removes the copying, and puts the image files where the text already points. This guide explains what mdstudio does when you publish a draft to GitHub, and what it does not do. + +## Connecting GitHub is a separate step + +Signing in with GitHub only identifies you. It asks for no access to your repositories and keeps no token. To publish, you connect GitHub explicitly, from the Publish dialog or from Settings, and GitHub asks you to approve it. mdstudio asks for access to public repositories and gists, or to private repositories when you choose that option. The token is stored encrypted on the server and never sent to your browser. You can disconnect at any time. + +Publishing is available for a draft kept in your cloud, with a confirmed email address. + +## Commit, pull request or gist + +Pick a repository, a branch and a path, including any folders, such as `posts/my-post.md`. Then choose how it goes in: + +- **Commit** puts the file on the branch you chose. If the branch moved while you were publishing, mdstudio stops and tells you, instead of overwriting anything. +- **Pull request** puts the commit on a new branch named after the draft and the time, and opens a pull request against the branch you chose. Use it when someone has to approve a change. +- **Gist** publishes the text as a secret gist unless you make it public. Publishing again updates the same gist, and it is created again if you deleted it. + +## Images come with the file + +A draft often points at images such as `images/diagram.png`. Publishing commits those files into an `images` folder beside the Markdown file, which is where the text already points, so the links work in the repository without edits. Images pasted into the text as base64 data are taken out and committed as files, so no base64 ends up in the repository. There is a limit of 20 images and about 4.5 MB in one publish. + +## Publishing again, and not overwriting by accident + +Publishing the same draft again updates the same file. If a file already exists at that path and this draft did not put it there, or someone changed it since, mdstudio will not replace it unless you confirm that you want to. This protects work that does not belong to the draft. + +## Write for the repository + +Because the text goes to GitHub, write for GitHub: + +- Use the GFM extended target, so tables, task lists, alerts and footnotes are expected. +- Use relative links between files in the repository, and hosted URLs for everything else. +- Give code fences a language, and keep one blank line between paragraphs. + +The checker warns about links to local files, because they break once the text leaves its folder. Inside a repository a relative link to another file is correct, so read those warnings with the repository's layout in mind. + +## When something else is the destination + +Not everything is published through a repository. If you are sending the text to a platform that takes pasted Markdown, export clean Markdown with the target set to the one that matches, and read [writing Markdown for blogging platforms](/guides/markdown-for-blogging-platforms). To get a second opinion before you commit, see [sharing a draft for review](/guides/share-markdown-for-review). To try publishing, [open the editor](/editor). diff --git a/content/guides/share-markdown-for-review.md b/content/guides/share-markdown-for-review.md new file mode 100644 index 0000000..1310129 --- /dev/null +++ b/content/guides/share-markdown-for-review.md @@ -0,0 +1,45 @@ +--- +slug: share-markdown-for-review +title: Share a Markdown Draft for Review Before You Publish +description: "Get feedback on a Markdown draft before it goes live: an expiring read-only copy, who can open it, comments on selected words, and what happens as you edit." +order: 8 +published: 2026-11-16T10:27:00Z +updated: 2026-11-16T10:27:00Z +--- + +Sending someone a Markdown file for feedback is awkward. They need an editor that renders it, they reply in a chat thread with line numbers you have to hunt for, and by the time you have fixed the first round, the file they hold is out of date. A read-only page with comments on the exact words solves most of that. This guide explains how review links in mdstudio work, and the choices you make when you create one. + +## What a review link is + +A review link is a copy of a draft, published at its own web address. It is not the draft itself. The page shows the text rendered the way the editor's preview shows it, with math and diagrams drawn in the reader's browser, and it has no controls for editing. Readers need no editor and no account to read a public link. + +Only a draft that is kept in your cloud can be shared, and your email address has to be confirmed first. Choose **Share** on the draft, then **Share for review**. + +## It expires, on purpose + +Every link has a lifetime of 1 to 7 days, 4 by default. You can lengthen or shorten it while it is live, and you can stop sharing at any moment, after which the address stops working. A link that has run out can be published again under a new address. The expiry is there so that a draft you meant to show for a week does not sit on the web forever. + +## Public, or only for named people + +A **public** link opens for anyone who has the address, and because it is a public web page, search engines can index it. Treat it like publishing. Do not use it for anything you would not put on a website. + +A link limited to **named people** lists the email addresses you invite. A reader has to sign in with a confirmed account on one of those addresses. Anyone else, including a signed-out visitor who guesses the address, gets a plain "not found", so the page does not reveal that it exists. Private pages are never indexed and are never cached publicly. Each invited address gets one email with who shared it, the title, the expiry date and a button. + +## Comments on the exact words + +When you turn comments on, signed-in readers with a confirmed email can select text on the page and comment on it. A comment is plain text, shown with the reader's display name and never their address, and anyone can reply in the thread. You see the comments in the editor, next to the draft, and you can resolve or delete them. You get at most one email an hour per link saying that something was said, and never what was said. + +## When you keep writing + +The page does not change when you edit the draft. It keeps the text you published until you choose to publish an update. That is deliberate: reviewers always comment on a fixed copy, and you can keep working without readers seeing half-finished sentences. + +When you do publish an update, comments written on the earlier copy are found again by the words they were attached to, and marked as being on an earlier version, so you can tell what still applies. Open pages show that an update has arrived and offer to reload. + +## A short review routine + +1. Finish a draft you would be willing to show, and check it in the editor first. +2. Share it for review, with the people you want to hear from, and a lifetime that fits the deadline. +3. Resolve each comment as you deal with it, and publish an update when you want a second look. +4. When you are done, stop sharing. Your draft is unchanged, and an expired link and its comments stay available to you for 30 days. + +Review is one step in a longer flow. For editing the same draft at the same time as someone else, read [writing a Markdown draft together](/guides/write-markdown-together). To send the finished text on, see [publishing Markdown to GitHub](/guides/publish-markdown-to-github). To try it, [open the editor](/editor). diff --git a/content/guides/write-markdown-together.md b/content/guides/write-markdown-together.md new file mode 100644 index 0000000..9da8c99 --- /dev/null +++ b/content/guides/write-markdown-together.md @@ -0,0 +1,42 @@ +--- +slug: write-markdown-together +title: Write a Markdown Draft Together, Online or Offline +description: "How several people edit one Markdown draft at once: inviting people, cursors and undo, what happens when someone goes offline, and the limits to know first." +order: 10 +published: 2026-11-16T11:36:00Z +updated: 2026-11-16T11:36:00Z +--- + +Two people editing one file usually means taking turns, or merging by hand. For a document you both want to move quickly, such as a README, a proposal or a post with a deadline, that is slow. Editing the same draft at the same time removes the turn-taking. This guide explains how it works in mdstudio, what is merged for you, and where it stops. + +## Starting a shared draft + +Open the draft's menu and choose **Share**, then **Edit together**, and invite people by email address. The draft has to be kept in your cloud, and the people you invite need a confirmed account on that address. Invited people find the draft under "Shared with you" in their library and open it from there. + +By default up to 3 people, including you, can edit one draft, and an account can have 2 of these live at a time. A server's admin can change both limits, and can switch the feature off. You can stop editing together at any time, which returns the draft to normal syncing. + +## What you see while you write + +Everyone's cursor and selection appear in the text with a name and a colour, and an avatar stack in the header shows who is in the draft. Undo is personal: pressing it reverts your own last edit, never someone else's. A small indicator tells you whether you are live, reconnecting or offline. + +## Offline edits merge + +This is the part that is hard with files and easy here. If you lose the connection, you can keep writing. Your edits are kept on your device, and when the network returns they are sent and merged with what everyone else did in the meantime. Nobody has to resolve a conflict by choosing one version. + +If two people change the same spot while apart, both keep their text, and the order of the two pieces is decided consistently for everyone, so the result is the same on every device. It can read oddly, since two people wrote the same sentence differently, but nothing is lost. Reread the passage after a reconnect. + +## What happens to the saved copy + +The text people edit together is the live draft. A copy of it is kept up to date in the owner's cloud draft within a short time after anyone stops typing, so history, sharing and publishing work from current text. If the owner restores an older version, it is applied as an ordinary edit that everyone sees. + +## Limits worth knowing + +- Only the text is shared live. The name and folder of the draft are not synced between people while it is live. +- Images pasted into the text as local data are not shared. Use hosted images, or a link, so everyone sees them. +- People you invite can edit, but cannot reshare the draft, publish it to GitHub or delete it. Those stay with the owner. +- Removing a person, or deleting the draft, ends their access straight away. They keep a plain local copy of what they had, and nothing is destroyed. +- There are no comments or suggestions inside the live editor. For feedback from people who should not edit, use a [review link](/guides/share-markdown-for-review). + +## When to use it + +Edit together when two or three people are producing the same text. Use a review link when you want feedback on a finished copy from many readers. And write the final text for the place it is going: read [portable Markdown](/guides/markdown-portability) before you publish. To try it, [open the editor](/editor). diff --git a/content/legal/privacy.md b/content/legal/privacy.md index 8edaec9..050fdde 100644 --- a/content/legal/privacy.md +++ b/content/legal/privacy.md @@ -1,3 +1,12 @@ +--- +slug: privacy +title: "Privacy Policy" +description: "What mdstudio stores and shares: nothing without an account, and only what each feature needs with one, including editing together. No ads, no analytics." +order: 1 +published: 2026-11-11T16:55:00Z +updated: 2026-11-16T13:28:00Z +--- + This policy covers the hosted mdstudio at {{site}}, run by the mdstudio maintainers ("we", "us"). If you self-host mdstudio, whoever runs your copy is responsible for your data, and this policy does not apply to it. The short version: mdstudio is local-first. You can write, preview, check and export without an account, and then nothing you write leaves your browser. An account is optional and adds features that need a server. There is no advertising, no analytics and no tracking. @@ -8,6 +17,7 @@ Without an account, everything is stored on your device: - Your drafts and their saved versions (IndexedDB). - Your settings: theme, checker rules, library folders and similar (localStorage). +- The search index: searching your drafts, commands and settings (the search dialog) happens on your device, and what you type is never sent anywhere. - A copy of the app's files, so it works offline (the browser cache). We never receive these. Clearing your browser's site data deletes them. @@ -20,12 +30,13 @@ If you are signed in, the name, provider, address and model of your AI setups ar ## What we store when you have an account -- **Account details:** your email address, a hash of your password (never the password itself), your display name, and the time the account was created. +- **Account details:** your email address, a hash of your password (never the password itself), your display name, and the time the account was created. When you change your email address, a link goes to the new address, and the address changes only once that link is opened; we also tell the old address that it changed. - **Sign-in with Google or GitHub:** see the next section. We store the provider's ID for you, your profile picture's address, and your name. - **Sessions:** a hash of your session token and its expiry. No IP address or device details are stored with it. - **Email links:** hashes of the one-time links for confirming your email and resetting your password, until they expire or are used. - **Cloud drafts:** only drafts you choose to put in the cloud. The text, the title and a limited number of earlier versions are stored. Drafts are not end-to-end encrypted: they are stored in a database that we administer, and the admin tools we use show titles and sizes, not text. - **Share links and comments:** see below. +- **Drafts edited together:** see "Editing together" below. - **GitHub publishing:** only if you connect it. See below. - **Account limits and admin records:** your plan and limits, whether the account is suspended, and a log of admin actions (who did what to which account). @@ -54,13 +65,24 @@ A share link publishes a copy of a cloud draft at a public address. Understand w - You can make a link private to invited email addresses. Readers must then sign in with one of those addresses. Invitations are sent by email. - If comments are on, signed-in readers can comment. Comments show the commenter's display name, never their email address. If your display name came from Google or GitHub, that is the name shown. +## Editing together + +You can switch a cloud draft to live editing and invite people by email address, up to 3 people on a draft including you. Understand what that means before you use it: + +- The people you invite can read the whole draft, edit it at the same time as you, and see each other's display name, picture and cursor while they are in it. They need an account with a confirmed email address that matches the invitation. Removing a person, or stopping live editing, ends their access to the live draft. +- While a draft is edited live, its text, and the comments and suggestions made in it, are kept in a live room: on the hosted service, storage belonging to a Cloudflare Durable Object, separate from the main database. A copy of the text is also written to your cloud draft so that versions, share links and publishing keep working. The room is deleted when you stop live editing or delete the draft. +- Each invited person's browser keeps a copy on their device while they work, so it can keep working offline and merge afterwards. Taking access away does not delete a copy that is already on their device, because we cannot reach into someone's browser. Only invite people you would trust with the text. +- Live drafts are not end-to-end encrypted, like other cloud drafts. The admin tools we use show titles and sizes, not text. +- The live connection (a WebSocket to Cloudflare) knows which account is on it, so that only invited people can join. It also carries other live updates, such as your drafts reaching your other devices and new comments on a share link. Nothing about it is stored beyond the connection. +- An invitation is an email to the address you give, with a link to the draft. + ## Email -We send email for confirming your address, password resets, share invitations and notices that someone commented on your shared draft (at most one an hour per link, and never the comment itself). These go through an email provider (currently Resend or Mailtrap), which receives the recipient address and the message. +We send email for confirming your address, changing it, password resets, share invitations, invitations to edit together and notices that someone commented on your shared draft (at most one an hour per link, and never the comment itself). These go through an email provider (currently Resend or Mailtrap), which receives the recipient address and the message. ## Technical data -- **Hosting:** the site runs on Cloudflare (Workers, D1 database, and its network). Cloudflare processes IP addresses and request details to deliver and protect the site, and may keep logs under [its own privacy policy](https://www.cloudflare.com/privacypolicy/). +- **Hosting:** the site runs on Cloudflare (Workers, the D1 database, Durable Objects for live updates and editing, and its network). Cloudflare processes IP addresses and request details to deliver and protect the site, and may keep logs under [its own privacy policy](https://www.cloudflare.com/privacypolicy/). - **Abuse limits:** to limit sign-up and sign-in abuse, we keep short-lived counters tied to your IP address (and to the email address being tried). They exist only for the length of the limit, at most about an hour, and are then deleted. - **Sign-up check:** sign-up may use Cloudflare Turnstile to tell people from bots. Turnstile runs in your browser and sends information about it to Cloudflare. - **Errors:** if a server error occurs, the error and where it happened are logged so we can fix it. Request contents, such as your draft text, are not logged. @@ -82,7 +104,8 @@ We do not sell personal data. Data goes only to the services needed to run mdstu - Account data and cloud drafts: until you delete them or the account is deleted. - Sessions: 24 hours, renewed while you use the site, and never more than 5 days after you signed in. - Email confirmation links: 24 hours. Password reset links: 1 hour. -- When an account is deleted, its drafts, versions, share links, comments, GitHub connection and sessions are deleted with it. Cloudflare keeps short-lived database backups, so deleted data can remain in them for a limited time (up to 30 days). +- Live editing rooms: until you stop live editing or delete the draft. +- When an account is deleted, its drafts, versions, share links, comments, live editing rooms, GitHub connection and sessions are deleted with it. Cloudflare keeps short-lived database backups, so deleted data can remain in them for a limited time (up to 30 days). ## Your choices and rights diff --git a/content/legal/terms.md b/content/legal/terms.md index d8ac04d..8a9cd70 100644 --- a/content/legal/terms.md +++ b/content/legal/terms.md @@ -1,8 +1,17 @@ +--- +slug: terms +title: "Terms of Service" +description: "The rules for using the hosted mdstudio: your content, acceptable use, limits and the service's lack of guarantees." +order: 2 +published: 2026-11-11T16:55:00Z +updated: 2026-11-16T13:28:00Z +--- + These terms cover your use of the hosted mdstudio at {{site}}, run by the mdstudio maintainers ("we", "us"). By using it, you agree to them. If you do not agree, do not use it. How we handle personal data is in the [Privacy Policy](/privacy). ## What mdstudio is -mdstudio is a Markdown editor and portability checker. You can use the editor without an account, and it stores your drafts in your browser. An account is optional and adds cloud drafts, share links with comments, saved AI setups and publishing to GitHub. The service is free. +mdstudio is a Markdown editor and portability checker. You can use the editor without an account, and it stores your drafts in your browser. An account is optional and adds cloud drafts, share links with comments, editing a draft together with people you invite, saved AI setups and publishing to GitHub. The service is free. ## Your account @@ -12,10 +21,16 @@ mdstudio is a Markdown editor and portability checker. You can use the editor wi ## Your content -You own what you write. You give us permission to store, process and show it only as needed to run the features you use: to keep your cloud drafts, sync them between your devices, serve a share link you publish, send your draft to GitHub when you publish, and send your text to an AI provider when you run an AI helper. That permission ends when you delete the content or the account, apart from short-lived backups. +You own what you write. You give us permission to store, process and show it only as needed to run the features you use: to keep your cloud drafts, sync them between your devices, serve a share link you publish, show a draft to the people you invite to edit it, send your draft to GitHub when you publish, and send your text to an AI provider when you run an AI helper. That permission ends when you delete the content or the account, apart from short-lived backups. You are responsible for your content and for having the right to use it. A share link is public unless you make it private. Do not publish anything there that you would not want read by anyone. +## Editing together + +You can invite other people, by email address, to edit a cloud draft with you. Invite only people you want to have the whole text, because they can read it, change it and keep a copy on their device. You are responsible for who you invite and for what they can see. People you invite can edit anything in the draft, including your text. + +Only you can invite and remove people, stop live editing or delete the draft. When you remove someone or stop, their access ends, but a copy already on their device stays there. People you are invited by can use the draft only to work on it with you: they may not share it, publish it or use it for anything else. A draft allows up to 3 people, and an account up to 2 live drafts, for now. + ## What you may not do - Break the law, or post content that is illegal, infringes someone's rights, or is meant to deceive, harass or harm people (including malware and phishing). diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md deleted file mode 100644 index 3f4c807..0000000 --- a/docs/ARCHITECTURE.md +++ /dev/null @@ -1,62 +0,0 @@ -# Architecture - -## Stack -| Layer | Choice | -|---|---| -| Framework | TanStack Start v1, React 19, TypeScript, Vite | -| Routing | TanStack Router file routes (`src/routes`) | -| Styling | Tailwind CSS v4 via `src/styles.css` (`@theme inline`, OKLCH tokens) | -| UI kit | shadcn/ui (Radix) in `src/components/ui`, Vaul drawers, Sonner toasts, lucide-react icons | -| Editor | CodeMirror 6 (`@codemirror/lang-markdown`, language-data, search, history) | -| Markdown | unified: remark-parse, remark-gfm, remark-frontmatter, remark-rehype, rehype-highlight, rehype-sanitize, rehype-stringify; rehype-parse + rehype-remark + remark-stringify for HTML→MD; `yaml` for front matter | -| Storage | IndexedDB (raw, no wrapper library) | -| Tests | Vitest + Testing Library + jsdom | - -## Routes -| Path | File | Purpose | -|---|---|---| -| `/` | `src/routes/index.tsx` | Landing page | -| `/editor` | `src/routes/editor.index.tsx` | Opens most recent draft, or creates one from the sample | -| `/editor/$docId` | `src/routes/editor.$docId.tsx` | Renders `` | -| root | `src/routes/__root.tsx` | Head/meta, fonts (Fraunces, IBM Plex Sans, JetBrains Mono), `` | - -## Modules -### `src/lib/markdown/markdown.ts` (single home of all Markdown logic) -- `PROFILES`: `commonmark | gfm-extended | gfm-no-html | wiki-notes` — controls which features are considered portable. -- `renderMarkdown(text, profile, images)` → sanitized HTML string. Local `images/x.png` refs resolve to stored data URIs for preview only. -- `checkPortability(text, profile)` → `Issue[] {rule, severity, line, message, fix?}`. Rules: raw-html, data-image, local-image, mermaid, highlight (`==x==`), wiki-link (`[[x]]`), math (`$`/`$$`), container (`:::`), trailing-break (two spaces), mixed-bullets, gfm-table/task/strike (on commonmark), fence-lang (missing language). -- `getOutline`, `getStats` (words, chars, reading time), `deriveTitle`, `slugify`. -- `splitFrontMatter` / `joinFrontMatter` (YAML). -- `finalizeText` (LF endings, trailing newline), `normalizeMarkdown` (remark-stringify with consistent bullets/fences/emphasis). -- `embedImages(text, images)` → self-contained export. -- `htmlToMarkdown(html)` — paste conversion. -- `standaloneHtml(title, html)` — full HTML document with inline CSS. - -### `src/lib/storage/documentStore.ts` -```ts -interface MdDocument { id: string; title: string; content: string; images: Record; createdAt: number; updatedAt: number } -``` -`list / get / save / create / remove / duplicate` + `SAMPLE`. Treat as an interface: a future sync backend implements the same API. - -### `src/lib/editor/images.ts` -`compressImage(file)` (canvas, max 1600px, JPEG/WebP), `safeImageName`, `kb`. - -### `src/lib/ai/provider.ts` / `src/lib/ai/writing.ts` -- Providers: `openai` (`/v1/chat/completions`), `anthropic` (`/v1/messages`, header `anthropic-dangerous-direct-browser-access: true`), `gemini` (`:streamGenerateContent?alt=sse`), `custom` (OpenAI-compatible base URL, HTTPS required). -- `buildProviderRequest`, `generateWithProvider` — streaming SSE parse, AbortSignal, refusal/length handling, no retry on 402/403. -- Modes: `metadata` (returns JSON `{title, description, tags[]}`) and `write` (streams Markdown). -- Keys: React state only. Never persisted. - -### Components (`src/components/studio`) -- `Studio.tsx` — page orchestration: top bar, library, toolbar, editor/preview, side panel, status bar, autosave (400 ms debounce), import, paste, export, compact (<1024px) layout with drawers. -- `MarkdownEditor.tsx` — CodeMirror wrapper; `EditorHandle { wrap, linePrefix, insert, goToLine, scrollToRatio, focus }`; paste & drop handlers; Mod-B/I/K. -- `AiWriter.tsx` — provider connection + two tabs (Metadata, Write a topic). - -## Invariants -See `AGENTS.md`. Key: no preview-only transforms; sanitize always; storage via documentStore only; CodeMirror client-only; AI BYOK and review-before-apply; tokens only. - -## Tests (31 passing) -`src/lib/markdown/markdown.test.ts` (render: no `
    ` on single newline, no smart quotes, GFM, sanitizer strips `