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
19 changes: 12 additions & 7 deletions apps/web/e2e/docs.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,19 @@ async function signIn(page: Page, email: string) {
async function seedDocs(workspaceId: string) {
const { db } = openSqlite("file:.data/e2e.sqlite");
const now = new Date();
const root = "R_docs:main:docs";
// The whole repo (decision 038): root "" and the repo's own folders.
const root = "R_docs:main:";
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(workspaceRepos).values({ workspaceId, repoNodeId: "R_docs", docsPath: "" }),
db.insert(ghDocRoots).values({ id: root, repoNodeId: "R_docs", branch: "main", path: "", 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: "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 },
]),
Expand Down Expand Up @@ -68,7 +69,7 @@ test("docs: tree, hide folder, rich-text editor, frontmatter panel", async ({ br

// The hide folder, set through the settings form.
await owner.goto(`/w/${workspaceId}/settings`);
await owner.getByLabel("Hide docs in this folder").fill("internal");
await owner.getByLabel("Hide docs in this folder").fill("docs/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;
Expand All @@ -88,9 +89,13 @@ test("docs: tree, hide folder, rich-text editor, frontmatter panel", async ({ br
// Owner: the whole tree, from the sidebar's Docs link.
await owner.goto(`/w/${workspaceId}`);
await owner.getByRole("link", { name: "Docs", exact: true }).click();
// The repo is the top folder, with the repo's own folders inside.
const tree = owner.getByRole("complementary", { name: "Docs" });
await expect(tree.getByRole("button", { name: "handbook" })).toBeVisible();
await expect(tree.getByRole("link", { name: "README" })).toBeVisible();
await expect(tree.getByRole("button", { name: "docs" })).toBeVisible();
await expect(tree.getByRole("button", { name: "internal" })).toBeVisible();
await expect(tree.getByRole("button", { name: "guide" })).toBeVisible();

// Read Only: no hidden folder in the tree, the API, or by URL.
await reader.goto(`/w/${workspaceId}/docs`);
Expand All @@ -99,11 +104,11 @@ test("docs: tree, hide folder, rich-text editor, frontmatter panel", async ({ br
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`);
const r = await reader.request.get(`/api/v1/workspaces/${workspaceId}/docs/file?repo=R_docs&path=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 reader.getByRole("complementary", { name: "Docs" }).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);
Expand Down
7 changes: 4 additions & 3 deletions apps/web/src/app/w/[workspaceId]/docs/doc-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { syntaxHighlighting } from "@codemirror/language";
import { searchKeymap } from "@codemirror/search";
import { Compartment, EditorState } from "@codemirror/state";
import { EditorView, drawSelection, dropCursor, keymap, placeholder } from "@codemirror/view";
import { MAX_EDITABLE_BYTES, type TextChange, lineSeparatorOf, relativeLink, resolveRelative, safeFileName } from "@gitwork/core";
import { MAX_EDITABLE_BYTES, type TextChange, folderOf, joinRoot, lineSeparatorOf, relativeLink, resolveRelative, safeFileName } from "@gitwork/core";
import type { DocView, Editor } from "@gitwork/server";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
Expand Down Expand Up @@ -107,7 +107,8 @@ export function DocEditor(props: { workspaceId: string; repoNodeId: string; path
const base = safeFileName(file.name || "image.png");
const dot = base.lastIndexOf(".");
const name = `${base.slice(0, dot > 0 ? dot : undefined)}-${Date.now().toString(36)}${dot > 0 ? base.slice(dot) : ".png"}`;
const abs = `${doc.root}/assets/${name}`;
// Next to the doc: <its folder>/assets/ (decision 038).
const abs = joinRoot(folderOf(path), `assets/${name}`);
const link = relativeLink(path, abs);
images.current.set(abs, { data: await toBase64(file), url: URL.createObjectURL(file), link });
const alt = (file.name || "image").replace(/\.[^.]+$/, "").replace(/[[\]]/g, "");
Expand Down Expand Up @@ -285,7 +286,7 @@ export function DocEditor(props: { workspaceId: string; repoNodeId: string; path
async function rename() {
if (!doc) return;
const clean = newName.trim().replace(/^\/+/, "");
const target = `${doc.root}/${/\.(md|markdown)$/i.test(clean) ? clean : `${clean}.md`}`;
const target = joinRoot(doc.root, /\.(md|markdown)$/i.test(clean) ? clean : `${clean}.md`);
try {
const out = await docs.rename({ repoNodeId, path, baseSha: baseSha.current, newPath: target });
setRenaming(false);
Expand Down
80 changes: 40 additions & 40 deletions apps/web/src/app/w/[workspaceId]/docs/docs-tree.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
"use client";
import type { DocFileView, DocRepoView } from "@gitwork/server";
import type { ReactNode } from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { joinRoot, relativeToRoot } from "@gitwork/core";
import { useEffect, useMemo, useRef, useState } from "react";
import { Button, ErrorText, Input } from "@/components/kit";
import { api } from "@/lib/api";
import { decodeSegment, docHref, rawHref } from "./links";
Expand All @@ -15,14 +17,15 @@ interface Folder {
}

function buildTree(repo: DocRepoView): Folder {
const root: Folder = { name: repo.root, path: repo.root, folders: new Map(), files: [] };
// The repo is the top folder; below it, the repo's own folders (decision 038).
const root: Folder = { name: repo.fullName.split("/")[1] ?? repo.fullName, path: repo.root, folders: new Map(), files: [] };
for (const file of repo.files) {
const parts = file.path.slice(repo.root.length + 1).split("/");
const parts = relativeToRoot(file.path, repo.root).split("/");
let folder = root;
for (const part of parts.slice(0, -1)) {
let next = folder.folders.get(part);
if (!next) {
next = { name: part, path: `${folder.path}/${part}`, folders: new Map(), files: [] };
next = { name: part, path: joinRoot(folder.path, part), folders: new Map(), files: [] };
folder.folders.set(part, next);
}
folder = next;
Expand All @@ -34,8 +37,8 @@ function buildTree(repo: DocRepoView): Folder {

const STATUS_TEXT: Record<DocRepoView["status"], string> = {
ok: "",
unsynced: "Not loaded from GitHub yet.",
missing: "This folder does not exist on the branch yet. Create a doc to start it.",
unsynced: "Loading from GitHub…",
missing: "Nothing on this branch yet. Create a doc to start it.",
unavailable: "The GitHub App cannot reach this repo right now.",
};

Expand All @@ -48,23 +51,21 @@ export function DocsTree(props: { workspaceId: string; linked: boolean; repos: D
const [creating, setCreating] = useState<string | null>(null);
const [name, setName] = useState("");

async function refresh() {
setBusy(true);
setError("");
try {
await api("POST", `/workspaces/${props.workspaceId}/docs/refresh`);
router.refresh();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
// Repos never read from GitHub load on their own: no button (decision 038). Once per page.
const loading = useRef(false);
const unsynced = props.repos.some((r) => r.status === "unsynced");
useEffect(() => {
if (!unsynced || loading.current) return;
loading.current = true;
api("POST", `/workspaces/${props.workspaceId}/docs/refresh`)
.then(() => router.refresh())
.catch((e: Error) => setError(e.message));
}, [unsynced, props.workspaceId, router]);

async function create(repo: DocRepoView) {
const clean = name.trim().replace(/^\/+/, "");
if (!clean) return;
const path = `${repo.root}/${/\.(md|markdown)$/i.test(clean) ? clean : `${clean}.md`}`;
const path = joinRoot(repo.root, /\.(md|markdown)$/i.test(clean) ? clean : `${clean}.md`);
setBusy(true);
setError("");
try {
Expand All @@ -85,10 +86,7 @@ export function DocsTree(props: { workspaceId: string; linked: boolean; repos: D
<aside aria-label="Docs" className="shrink-0 space-y-4 text-sm md:w-64">
{props.repos.map((repo) => (
<section key={repo.repoNodeId} className="space-y-1">
<div className="flex items-center justify-between gap-2">
<h2 className="truncate text-xs font-medium text-muted-foreground" title={`${repo.fullName} · ${repo.root}/ on ${repo.branch}`}>
{repo.fullName}
</h2>
<div className="flex items-center justify-end gap-2">
{props.canWrite && repo.status !== "unavailable" && (
<button type="button" className="text-xs text-muted-foreground hover:text-foreground" onClick={() => setCreating(creating === repo.repoNodeId ? null : repo.repoNodeId)}>
+ New doc
Expand All @@ -109,18 +107,10 @@ export function DocsTree(props: { workspaceId: string; linked: boolean; repos: D
</Button>
</form>
)}
{repo.status !== "ok" && (
<div className="space-y-1 text-xs text-muted-foreground">
<p>{STATUS_TEXT[repo.status]}</p>
{repo.status === "unsynced" && props.canWrite && (
<Button variant="secondary" className="h-7" disabled={busy} onClick={() => void refresh()}>
Load from GitHub
</Button>
)}
</div>
)}
{repo.status === "ok" && <FolderView workspaceId={props.workspaceId} repo={repo} folder={buildTree(repo)} current={current} depth={0} />}
{repo.status === "ok" && repo.files.length === 0 && <p className="text-xs text-muted-foreground">No files in {repo.root}/ yet.</p>}
<FolderView workspaceId={props.workspaceId} repo={repo} folder={buildTree(repo)} current={current} depth={0}>
{repo.status !== "ok" && <p className="px-2 py-1 text-xs text-muted-foreground">{STATUS_TEXT[repo.status]}</p>}
{repo.status === "ok" && repo.files.length === 0 && <p className="px-2 py-1 text-xs text-muted-foreground">No files yet.</p>}
</FolderView>
{repo.truncated && <p className="text-xs text-amber-600">This folder has more files than Gitwork lists.</p>}
</section>
))}
Expand All @@ -129,15 +119,15 @@ export function DocsTree(props: { workspaceId: string; linked: boolean; repos: D
);
}

function FolderView(props: { workspaceId: string; repo: DocRepoView; folder: Folder; current: string | null; depth: number }) {
function FolderView(props: { workspaceId: string; repo: DocRepoView; folder: Folder; current: string | null; depth: number; children?: ReactNode }) {
const { folder, repo, depth } = props;
const folders = useMemo(() => [...folder.folders.values()].sort((a, b) => a.name.localeCompare(b.name)), [folder]);
const [open, setOpen] = useState(true);
const body = (
<ul className="space-y-0.5">
{folders.map((f) => (
<li key={f.path}>
<FolderView {...props} folder={f} depth={depth + 1} />
<FolderView workspaceId={props.workspaceId} repo={repo} folder={f} current={props.current} depth={depth + 1} />
</li>
))}
{folder.files.map((file) => {
Expand Down Expand Up @@ -165,16 +155,26 @@ function FolderView(props: { workspaceId: string; repo: DocRepoView; folder: Fol
})}
</ul>
);
if (depth === 0) return body;
return (
<div>
<button type="button" aria-expanded={open} onClick={() => setOpen(!open)} className="flex w-full items-center gap-1 rounded-md px-2 py-1 text-left text-muted-foreground hover:bg-muted">
<button
type="button"
aria-expanded={open}
onClick={() => setOpen(!open)}
title={depth === 0 ? `${repo.fullName} · ${repo.root ? `${repo.root}/ ` : ""}on ${repo.branch}` : undefined}
className={`flex w-full items-center gap-1 rounded-md px-2 py-1 text-left hover:bg-muted ${depth === 0 ? "font-medium text-foreground" : "text-muted-foreground"}`}
>
<span aria-hidden className="w-3 text-xs">
{open ? "▾" : "▸"}
</span>
<span className="truncate">{folder.name}</span>
</button>
{open && <div className="ml-3 border-l border-border pl-1">{body}</div>}
{open && (
<div className="ml-3 border-l border-border pl-1">
{props.children}
{body}
</div>
)}
</div>
);
}
5 changes: 3 additions & 2 deletions apps/web/src/app/w/[workspaceId]/docs/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ export default async function DocsIndexPage({ params }: PageProps<"/w/[workspace
</Card>
);
}
// The first doc of the first repo, so the page is never empty when docs exist.
const first = docs.repos.flatMap((r) => r.files.filter((f) => f.kind === "doc").map((f) => ({ repo: r.repoNodeId, path: f.path })))[0];
// A README at the top of a repo first, else the first doc, so the page is never empty.
const all = docs.repos.flatMap((r) => r.files.filter((f) => f.kind === "doc").map((f) => ({ repo: r.repoNodeId, path: f.path, root: r.root })));
const first = all.find((d) => /^readme\.(md|markdown)$/i.test(d.root ? d.path.slice(d.root.length + 1) : d.path)) ?? all[0];
return (
<Card className="mx-auto max-w-2xl space-y-2">
<h1 className="text-lg font-semibold">Docs</h1>
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/app/w/[workspaceId]/settings/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export default async function WorkspaceSettingsPage({ params }: PageProps<"/w/[w
{data && github.ok && docRepos.length > 0 && (
<Card className="space-y-4">
<h2 className="font-medium">Docs folders</h2>
<p className="text-sm text-muted-foreground">Empty shows the whole repo. Enter a folder, such as docs, to show only that folder.</p>
<DocFoldersPanel
workspaceId={workspaceId}
repos={docRepos.map((r) => ({ nodeId: r.repoNodeId, fullName: r.fullName, path: r.path, branch: r.branch, defaultBranch: r.defaultBranch }))}
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/app/w/[workspaceId]/settings/settings-panels.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ export function VisibilityPanel(props: { workspaceId: string; hideLabel: string;
<Label htmlFor="hide-folder">Hide docs in this folder</Label>
<Input id="hide-folder" value={hideFolder} placeholder="e.g. internal" maxLength={200} onChange={(e) => setHideFolder(e.target.value)} />
<p className="mt-1 text-xs text-muted-foreground">
Inside each repo&apos;s docs folder: &ldquo;internal&rdquo; hides docs/internal/. Read Only members never see these files. Empty hides nothing.
From the top of each repo (or its docs folder, if one is set): &ldquo;internal&rdquo; hides internal/. Read Only members never see these files. Empty hides nothing.
</p>
</div>
<div className="flex items-center gap-2 text-sm">
Expand Down Expand Up @@ -303,7 +303,7 @@ function DocFolderRow(props: { workspaceId: string; repo: { nodeId: string; full
<p className="truncate text-sm font-medium sm:pb-2">{props.repo.fullName}</p>
<div>
<Label htmlFor={`docs-path-${id}`}>Docs folder</Label>
<Input id={`docs-path-${id}`} value={path} onChange={(e) => setPath(e.target.value)} placeholder="docs" />
<Input id={`docs-path-${id}`} value={path} onChange={(e) => setPath(e.target.value)} placeholder="Whole repo" />
</div>
<div>
<Label htmlFor={`docs-branch-${id}`}>Branch</Label>
Expand Down
3 changes: 2 additions & 1 deletion docs/INDEX.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
| 035 | [Docs cache: tree by folder oid, text by blob sha](decisions/035-docs-cache.md) |
| 036 | [Doc writes: one signed commit, conflict check, pull request fallback](decisions/036-doc-writes.md) |
| 037 | ["Rich text" is a live preview over the source, not WYSIWYG](decisions/037-rich-text-view.md) |
| 038 | [Docs show each repo's whole tree, loaded automatically](decisions/038-whole-repo-tree.md) |

## Features

Expand All @@ -60,4 +61,4 @@
| [features/speed.md](features/speed.md) | Client store, /sync with ETag, optimistic edits, side panel, measured budgets. |
| [features/keyboard.md](features/keyboard.md) | Shared keymap, command menu, pickers, bulk edit with undo, shortcut sheet. |
| [features/shell.md](features/shell.md) | Workspace layout and sidebar, grouped virtualized list, dense cards, write-path line, dark mode. |
| [features/docs.md](features/docs.md) | Doc tree, rich-text editor, frontmatter panel, images, commits, PR fallback, conflicts, presence. |
| [features/docs.md](features/docs.md) | Repo trees (whole repo by default), rich-text editor, frontmatter panel, images, commits, PR fallback, conflicts, presence. |
6 changes: 3 additions & 3 deletions docs/STATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ Last updated: 2026-11-19

## In Progress

Phase 4 — Docs on web: built on `feature/docs-web`, PR open, waiting for the owner's merge. The owner
said "start phase 4" on 2026-11-19, ahead of the live GitHub check and Track E.
Docs show each repo's whole tree, loaded automatically (decision 038): `feature/docs-repo-tree`, PR
open, waiting for the owner's merge. Production runs PR #16 (deployed 2026-11-19).

First Cloudflare deploy (blocked on the owner's account steps, above).

Expand All @@ -39,7 +39,7 @@ First Cloudflare deploy (blocked on the owner's account steps, above).
| Track C — Keyboard and command menu (PR #9) | 2026-11-10 | [features/keyboard.md](features/keyboard.md) |
| Track D — App shell and clear UI (PR #10) | 2026-11-10 | [features/shell.md](features/shell.md) |
| Timeline virtualization, roadmap B6 (PR #11) | 2026-11-10 | [features/shell.md](features/shell.md) |
| Phase 4 — Docs on web (decisions 035–037; PR awaiting merge) | 2026-11-19 | [features/docs.md](features/docs.md) |
| Phase 4 — Docs on web (decisions 035–037; PR #16) | 2026-11-19 | [features/docs.md](features/docs.md) |

## Backlog

Expand Down
Loading
Loading