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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,10 @@ docs/ INDEX.md → STATE.md → spec.md, decisions/
- UI: shadcn/ui files in `apps/web/src/components/ui/` stay as the CLI writes them; app wrappers
live in `components/kit.tsx`.
- New `/api/v1` routes go in `packages/server/src/api/routes.ts`, with tests in
`packages/server/test/api.test.ts` or, for task and link routes, `api-tasks.test.ts`
(success, 401, 403, 400).
`packages/server/test/api.test.ts` or, for task and link routes, `api-tasks.test.ts`, or, for
doc routes, `api-docs.test.ts` (success, 401, 403, 400).
- Docs: every path passes `normalizeDocPath()` and `isDocVisible()` (packages/core). Read the
editor's text with `docText()` (`sliceDoc`), never `doc.toString()`.
- DB tests run on both drivers: `describe.each(await allTestDrivers())` from `@gitwork/db/testing`.
- Pages read the request (`getSession()`/`connection()`) before any config, or `next build` fails.
- Webhook handlers verify the signature and are idempotent on the delivery ID.
Expand Down
152 changes: 152 additions & 0 deletions apps/web/e2e/docs.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
/**
* Phase 4 (docs/spec.md): the doc tree and the editor in a real browser.
*
* GitHub is not reachable in E2E, so the test writes the cache rows a synced docs folder would
* have, and checks what a page can do from the cache: the tree, the hide folder for Read Only, the
* rich-text view, formatting, the frontmatter panel, and that single-key shortcuts stay out of the
* editor. Commits are covered against a fake GitHub in packages/server/test/docs.test.ts.
*/
import { type BrowserContext, type Page, expect, test } from "@playwright/test";
import { ghDocBlobs, ghDocFiles, ghDocRoots, ghProjects, ghRepos, workspaceGithub, workspaceRepos } from "@gitwork/db";
import { openSqlite } from "@gitwork/db/node";
import { lastEmail, signInCode } from "./outbox";

const README = "---\ntitle: Welcome\ntags: [a, b]\n---\n# Handbook\n\nSome **bold** words.\n\n- [ ] Write docs\n";
const SECRET = "# Secret plan\n\nInternal only.\n";

async function signIn(page: Page, email: string) {
await page.goto("/sign-in");
await page.getByLabel("Email").fill(email);
await page.getByRole("button", { name: "Email me a sign-in code" }).click();
await page.getByLabel("Code").fill(await signInCode(email));
await page.getByRole("button", { name: "Sign in" }).click();
await expect(page.getByRole("button", { name: "Sign out" })).toBeVisible();
}

async function seedDocs(workspaceId: string) {
const { db } = openSqlite("file:.data/e2e.sqlite");
const now = new Date();
const root = "R_docs:main:docs";
await db.batch([
db
.insert(ghRepos)
.values({ nodeId: "R_docs", githubId: 50, installationId: 99, owner: "acme", name: "handbook", fullName: "acme/handbook", private: true, defaultBranch: "main", htmlUrl: "https://github.com/acme/handbook", syncedAt: now })
.onConflictDoNothing(),
db.insert(ghProjects).values({ nodeId: "PVT_docs", installationId: 99, ownerLogin: "acme", number: 7, title: "Handbook", url: "https://github.com/orgs/acme/projects/7", syncedAt: now }).onConflictDoNothing(),
db.insert(workspaceGithub).values({ workspaceId, installationId: 99, projectNodeId: "PVT_docs", linkedAt: now }),
db.insert(workspaceRepos).values({ workspaceId, repoNodeId: "R_docs" }),
db.insert(ghDocRoots).values({ id: root, repoNodeId: "R_docs", branch: "main", path: "docs", headOid: "c0ffee", treeOid: "7ree", syncedAt: now }),
db.insert(ghDocFiles).values([
{ rootId: root, path: "docs/README.md", blobSha: "a".repeat(40), size: README.length },
{ rootId: root, path: "docs/internal/plan.md", blobSha: "b".repeat(40), size: SECRET.length },
{ rootId: root, path: "docs/guide/setup.md", blobSha: "c".repeat(40), size: 9 },
]),
db.insert(ghDocBlobs).values([
{ sha: "a".repeat(40), text: README, size: README.length, fetchedAt: now },
{ sha: "b".repeat(40), text: SECRET, size: SECRET.length, fetchedAt: now },
{ sha: "c".repeat(40), text: "# Setup\n", size: 9, fetchedAt: now },
]),
]);
}

test("docs: tree, hide folder, rich-text editor, frontmatter panel", async ({ browser }) => {
const contexts: BrowserContext[] = [];
const page = async () => {
const ctx = await browser.newContext();
contexts.push(ctx);
return ctx.newPage();
};

const owner = await page();
await signIn(owner, "docs-owner@example.com");
await owner.getByLabel("Account name").fill("Docs Agency");
await owner.getByLabel("First workspace").fill("Docs Website");
await owner.getByRole("button", { name: "Create" }).click();
await expect(owner.getByRole("heading", { name: "Docs Website" })).toBeVisible();
const workspaceId = /\/w\/([^/?#]+)/.exec(owner.url())![1]!;
await seedDocs(workspaceId);

// The hide folder, set through the settings form.
await owner.goto(`/w/${workspaceId}/settings`);
await owner.getByLabel("Hide docs in this folder").fill("internal");
const saved = owner.waitForResponse((r) => r.url().endsWith(`/workspaces/${workspaceId}/settings`) && r.status() === 204);
await owner.getByRole("button", { name: "Save", exact: true }).click();
await saved;

// A Read Only client.
await owner.getByRole("link", { name: "Members" }).click();
await owner.getByLabel("Email").fill("docs-reader@example.com");
await owner.getByLabel("Role").selectOption("read_only");
await owner.getByRole("button", { name: "Send invite" }).click();
const [, invitePath] = await lastEmail("docs-reader@example.com", /http:\/\/localhost:\d+(\/invite\/[A-Za-z0-9_-]+)/);
const reader = await page();
await signIn(reader, "docs-reader@example.com");
await reader.goto(invitePath!);
await reader.getByRole("button", { name: "Accept invite" }).click();
await expect(reader.getByText("Your role: Read Only")).toBeVisible();

// Owner: the whole tree, from the sidebar's Docs link.
await owner.goto(`/w/${workspaceId}`);
await owner.getByRole("link", { name: "Docs", exact: true }).click();
const tree = owner.getByRole("complementary", { name: "Docs" });
await expect(tree.getByRole("link", { name: "README" })).toBeVisible();
await expect(tree.getByRole("button", { name: "internal" })).toBeVisible();

// Read Only: no hidden folder in the tree, the API, or by URL.
await reader.goto(`/w/${workspaceId}/docs`);
await expect(reader.getByRole("complementary", { name: "Docs" }).getByRole("link", { name: "README" })).toBeVisible();
expect(await reader.content()).not.toContain("internal");
const list = await (await reader.request.get(`/api/v1/workspaces/${workspaceId}/docs`)).text();
expect(list).not.toContain("internal");
expect((await reader.request.get(`/api/v1/workspaces/${workspaceId}/docs/file?repo=R_docs&path=docs/internal/plan.md`)).status()).toBe(404);
const r = await reader.request.get(`/api/v1/workspaces/${workspaceId}/docs/file?repo=R_docs&path=docs/README.md`);
expect(await r.json()).toMatchObject({ doc: { text: README, editable: false } });

// Read Only sees the doc rendered, with no toolbar or save.
await reader.getByRole("link", { name: "README" }).click();
await expect(reader.locator(".cm-lp-h1")).toHaveText("Handbook");
await expect(reader.getByRole("toolbar", { name: "Formatting" })).toHaveCount(0);
await expect(reader.getByRole("button", { name: "Save" })).toHaveCount(0);

// Owner: the rich-text view hides marks; the cursor's line shows the source.
await owner.getByRole("complementary", { name: "Docs" }).getByRole("link", { name: "README" }).click();
const editor = owner.getByTestId("doc-editor");
await expect(editor.locator(".cm-lp-h1")).toHaveText("Handbook");
await expect(editor.locator(".cm-lp-strong")).toHaveText("bold");
await expect(editor.locator("input.cm-lp-task")).toHaveCount(1);
// Frontmatter lives in the properties panel; the parser would draw it as a rule and a heading.
await expect(editor.getByText("title: Welcome")).toHaveCount(0);
await expect(editor.locator("hr")).toHaveCount(0);
await editor.locator(".cm-lp-h1").click();
await expect(editor.locator(".cm-lp-h1")).toHaveText("# Handbook");

// Single-key shortcuts never fire inside the editor (roadmap C4): "c" types a "c".
await owner.keyboard.press("End");
await owner.keyboard.type(" c");
await expect(editor.locator(".cm-lp-h1")).toHaveText("# Handbook c");
await expect(owner.getByRole("dialog")).toHaveCount(0);
await expect(owner.getByTestId("doc-status")).toHaveText("Unsaved changes");

// Formatting: select a word and make it italic.
await editor.locator(".cm-line", { hasText: "Some" }).click();
await owner.keyboard.press("Home");
for (let i = 0; i < 4; i++) await owner.keyboard.press("Shift+ArrowRight");
await owner.getByRole("button", { name: "Italic (⌘I)" }).click();
await owner.getByRole("group", { name: "View" }).getByRole("button", { name: "Markdown" }).click();
await expect(editor.locator(".cm-line", { hasText: "bold" })).toHaveText("*Some* **bold** words.");

// The frontmatter panel edits one line; the list stays read-only.
const panel = owner.getByRole("region", { name: "Properties" });
await expect(panel.getByText("[a, b]")).toBeVisible();
await panel.getByLabel("Property title").fill("Welcome aboard");
await panel.getByLabel("Property title").press("Enter");
await expect(editor.locator(".cm-line").nth(1)).toHaveText("title: Welcome aboard");
await expect(editor.locator(".cm-line").nth(2)).toHaveText("tags: [a, b]");

// A save needs GitHub; without the App the editor says so and keeps the text.
await owner.getByRole("button", { name: "Save", exact: true }).click();
await expect(owner.getByTestId("doc-status")).toContainText("GitHub App is not set up");
await expect(editor.locator(".cm-line").nth(1)).toHaveText("title: Welcome aboard");

for (const ctx of contexts) await ctx.close();
});
9 changes: 9 additions & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,18 @@
"test:e2e": "playwright test"
},
"dependencies": {
"@codemirror/commands": "6.11.1",
"@codemirror/lang-markdown": "6.5.2",
"@codemirror/language": "6.13.1",
"@codemirror/merge": "6.12.3",
"@codemirror/search": "6.7.2",
"@codemirror/state": "6.7.6",
"@codemirror/view": "6.43.15",
"@gitwork/core": "workspace:*",
"@gitwork/db": "workspace:*",
"@gitwork/server": "workspace:*",
"@lezer/highlight": "1.2.5",
"@lezer/markdown": "1.8.1",
"@opennextjs/cloudflare": "1.20.11",
"better-auth": "1.7.8",
"class-variance-authority": "0.7.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { requireWorkspacePage } from "@/server/pages";
import { decodeSegment } from "../../links";
import { DocEditor } from "../../doc-editor";

/** The editor loads the doc through /api/v1 in the browser: this render never calls GitHub. */
export default async function DocPage({ params }: PageProps<"/w/[workspaceId]/docs/[repoNodeId]/[...path]">) {
const { workspaceId, repoNodeId, path } = await params;
await requireWorkspacePage(workspaceId, `/w/${workspaceId}/docs`);
const docPath = path.map(decodeSegment).join("/");
const repo = decodeSegment(repoNodeId);
return <DocEditor key={`${repo}:${docPath}`} workspaceId={workspaceId} repoNodeId={repo} path={docPath} />;
}
59 changes: 59 additions & 0 deletions apps/web/src/app/w/[workspaceId]/docs/conflict-view.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"use client";
import { MergeView } from "@codemirror/merge";
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { useEffect, useRef } from "react";
import { Button } from "@/components/kit";
import { docExtensions, docText } from "@/lib/doc-editor";

/**
* Someone changed the doc on GitHub since it was opened (decision 011). Left: GitHub's version.
* Right: this person's version, editable. They keep editing the right side, then save it on top
* of GitHub's version, or drop theirs.
*/
export function ConflictView(props: {
theirs: string;
mine: string;
busy: boolean;
onSave: (merged: string) => void;
onKeepEditing: (merged: string) => void;
onUseTheirs: () => void;
}) {
const host = useRef<HTMLDivElement>(null);
const view = useRef<MergeView | null>(null);
useEffect(() => {
const merge = new MergeView({
a: { doc: props.theirs, extensions: [...docExtensions(props.theirs), EditorState.readOnly.of(true), EditorView.lineWrapping] },
b: { doc: props.mine, extensions: [...docExtensions(props.mine), EditorView.lineWrapping] },
parent: host.current!,
collapseUnchanged: { margin: 3, minSize: 6 },
});
view.current = merge;
return () => merge.destroy();
}, [props.theirs, props.mine]);
const merged = () => (view.current ? docText(view.current.b.state) : props.mine);

return (
<section aria-label="Resolve changes" className="space-y-3">
<div className="rounded-lg border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-900 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-100">
Someone changed this doc on GitHub since you opened it. Left: the version on GitHub. Right: your version. Edit the right side, then save it.
</div>
<div className="grid grid-cols-2 text-xs font-medium text-muted-foreground">
<span>On GitHub</span>
<span>Yours</span>
</div>
<div ref={host} className="overflow-hidden rounded-lg border border-border text-sm" />
<div className="flex flex-wrap gap-2">
<Button disabled={props.busy} onClick={() => props.onSave(merged())}>
Save my version
</Button>
<Button variant="secondary" disabled={props.busy} onClick={() => props.onKeepEditing(merged())}>
Keep editing
</Button>
<Button variant="ghost" disabled={props.busy} onClick={props.onUseTheirs}>
Discard mine, use GitHub&apos;s
</Button>
</div>
</section>
);
}
Loading
Loading