Public: anyone can read this; the crew can change it.

A fork's page links its upstream and its siblings count, and the tree page opens at the visitor's own fork #13705

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/13670-a-fork-s-page-links-its-upstream-and-its → main 11 commits fork 3 threads · 3 unresolved

  • Merged. scout/13670-a-fork-s-page-links-its-upstream-and-its was merged into main as 21acbb8.

Review

Sign in to review this change.
10 files changed +226 −8
docs/features/README.md +1
@@ -20,6 +20,7 @@ Read with the guide page [What a forge is](../guide-what-a-forge-is.md).
2020 - [First week: three steps on a new forge's home](first-week.md)
2121 - [How long the last forge from a template took, at /templates/<name>](template-timing.md)
2222 - [A look in the feed](feed-look.md)
23 - [A fork's page finds its place in the tree](fork-tree-here.md)
2324 - [Open pulls red for over a day are named in one issue](red-pulls.md)
2425 - [Empty lists](empty-words.md)
2526 - [An app with no description says its README](readme-description.md)
docs/features/fork-tree-here.md added +22
@@ -0,0 +1,22 @@
1 # A fork's page finds its place in the tree
2
3 A fork's page links its upstream and counts the other forks in the tree. The
4 forks page (`/owner/name/forks`) marks the visitor's own node.
5
6 - On a fork's page, the upstream is one link away, and the other forks are
7 counted beside it.
8 - A visitor who owns a node anywhere in the tree (a direct fork, a deeper
9 one, or a sibling's) follows the fork count, or the "N other forks" link on
10 a fork's page, to `/owner/name/forks#your-fork`. The page scrolls to their
11 first node and `:target` marks it. Every node of theirs says "you" on a
12 muted row; only the first carries the anchor.
13 - The terminal needs no new key: its fork tree screen
14 (`src/tui/screens/fork_tree.ts`) draws the same tree in one scroll and
15 already ends the viewer's nodes with `(you)`:
16
17 * alice/widgets
18 bob/widgets (you)
19 cy/widgets
20
21 Try it: sign in as someone with a fork, open the repository, then follow its
22 fork count.
src/.mcp.json added
No content changes.
src/core/following.ts +23
@@ -666,6 +666,29 @@ export interface Lineage {
666666 readonly truncated: boolean;
667667 }
668668
669 /**
670 * The id of the viewer's own node on the forks page; the links that lead there end in `#` + this.
671 */
672 export const MINE_ANCHOR = "your-fork";
673
674 /**
675 * Whether `viewerId` owns a repository in `repo`'s tree other than `repo`
676 * itself, anywhere up or down, a deeper fork or a sibling included: the
677 * forks page then has a node of theirs for the anchor to scroll to.
678 */
679 export function ownsInTree(
680 forge: Pick<Following, "db">,
681 repo: Repo,
682 viewerId: string | undefined,
683 mayRead: (r: Repo) => boolean,
684 ): boolean {
685 if (viewerId === undefined) return false;
686 const up = listAncestors(forge.db, repo.id, LINEAGE_MAX_DEPTH);
687 const top = up.length === 0 ? repo : (up[up.length - 1] as Repo);
688 const family = [...up, ...listDescendants(forge.db, top.id, LINEAGE_MAX_DEPTH + 1)];
689 return family.some((r) => r.id !== repo.id && r.ownerId === viewerId && mayRead(r));
690 }
691
669692 const LINEAGE_MAX_NODES = 60;
670693 const LINEAGE_MAX_RELATIONS = 30;
671694 const LINEAGE_MAX_DEPTH = 6;
src/web/.mcp.json added
No content changes.
src/web/chrome.ts +31 −4
@@ -18,14 +18,14 @@ import {
1818 getRepo,
1919 } from "../core/repos.ts";
2020 import { nearRepos as nearTo } from "../core/near_repos.ts";
21 import { type Repo } from "../core/repos.ts";
21 import { type Repo, visibleForks } from "../core/repos.ts";
2222 import { parentUrl, shownTrail, sourceLabel } from "../core/provenance.ts";
2323 import type { App } from "../app.ts";
2424 import type { Ctx } from "../http/context.ts";
2525 import { apiError, prefersJson } from "../http/respond.ts";
2626 import { FOLLOW_WORD } from "../actions/follow_words.ts";
2727 import { forkFollowMode } from "../core/fork_follow.ts";
28 import { keptBehind } from "../core/following.ts";
28 import { keptBehind, MINE_ANCHOR, ownsInTree } from "../core/following.ts";
2929 import { html, raw, when, type Html } from "./html.ts";
3030 import { icon } from "./icons.ts";
3131 import { nearPages } from "./near_pages.ts";
@@ -304,6 +304,7 @@ export function scopeHeader(
304304 ? html`<span class="repo-actions">${actions}</span>`
305305 : null}`;
306306
307 const family = repo === undefined || parent === undefined ? undefined : familyOf(ctx, repo, parent);
307308 return html`<header class="repo-head">
308309 ${options.ownTitle
309310 ? html`<div class="repo-title">${title}</div>`
@@ -313,7 +314,7 @@ export function scopeHeader(
313314 !options.compact && facts.description !== "",
314315 () => html`<p class="muted small">${facts.description}</p>`,
315316 )}
316 ${repo === undefined ? null : lineageLine(ctx.app, repo, parent)}
317 ${repo === undefined ? null : lineageLine(ctx.app, repo, parent, family)}
outdated

A very long inline call; compute the sibling count in a local first.

317318 ${when(
318319 scope.upstream !== undefined && upstreamHref(scope) === undefined,
319320 // The where strip carries "fork of octo/widgets" and links it, which
@@ -331,6 +332,23 @@ export function scopeHeader(
331332 </header>`;
332333 }
333334
335 /** The siblings the viewer may read, and whether they own a node in `parent`'s tree to land on. */
336 function familyOf(ctx: Ctx, repo: Repo, parent: Repo): Family {
337 const { db } = ctx.app;
338 const viewer = ctx.auth.user;
339 const siblings = visibleForks(db, parent.id, viewer).filter((f) => f.id !== repo.id).length;
340 return { siblings, mine: ownsInTree(ctx.app, parent, viewer?.id, (r) => canRead(db, r, viewer)) };
341 }
342
343 /**
344 * What the lineage line says of the family: the other forks of the parent, and a way to the
345 * viewer's own.
346 */
347 export interface Family {
348 readonly siblings: number;
349 readonly mine: boolean;
350 }
351
334352 /**
335353 * The trail up, as one quiet line however it was built (#3293): "forked
336354 * from alice/arm" for a fork made here, "Migrated from github.com/a/arm ·
@@ -343,19 +361,28 @@ export function lineageLine(
343361 app: Pick<App, "db" | "reposRoot">,
344362 repo: Repo,
345363 parent: Repo | undefined,
364 /** The other forks of `parent` (`familyOf`); absent says none. */
365 family?: Family,
346366 ): Html | null {
347367 const db = app.db;
348368 const shown = shownTrail(db, repo, parent);
349369 if (parent === undefined && shown === undefined) return null;
350370 const out = (href: string, text: string): Html =>
351371 html`<a href="${href}" rel="noopener noreferrer">${text}</a>`;
372 // The siblings the viewer may read, counted: the way into the family.
373 const siblings = family?.siblings ?? 0;
374 const anchor = family?.mine === true ? `#${MINE_ANCHOR}` : "";
375 const others =
376 parent === undefined || siblings === 0
377 ? null
378 : html` · <a href="/${parent.ownerName}/${parent.name}/forks${anchor}" data-siblings>${siblings} other fork${siblings === 1 ? "" : "s"}</a>`;
352379 const segments: Html[] = [];
353380 if (parent !== undefined)
354381 segments.push(
355382 html`forked from
356383 <a href="/${parent.ownerName}/${parent.name}"
357384 >${parent.ownerName}/${parent.name}</a
358 > · ${followWord(app, repo, parent)}`,
385 > · ${followWord(app, repo, parent)}${others}`,
359386 );
360387 if (shown !== undefined) {
361388 segments.push(
src/web/pages/following.ts +16 −1
@@ -29,7 +29,7 @@ import {
2929 convergeState,
3030 type Converge,
3131 } from "../../crew/converge.ts";
32 import type { Lineage, LineageNode } from "../../core/following.ts";
32 import { MINE_ANCHOR, type Lineage, type LineageNode } from "../../core/following.ts";
3333 import {
3434 parentReleases,
3535 parentForgeOf,
@@ -52,6 +52,16 @@ import { flashOrJson } from "../layout.ts";
5252 import { badge, btn, icon, row, timeAgo, type Tone } from "../ui.ts";
5353 import { disconnectedOn } from "./frozen.ts";
5454
55 /** The first node (parents before children) the viewer owns and is not looking at. */
56 function firstOwn(n: LineageNode, hereId: string, viewerId: string): string | undefined {
57 if (n.repo.id !== hereId && n.repo.ownerId === viewerId) return n.repo.id;
58 for (const c of n.children) {
59 const found = firstOwn(c, hereId, viewerId);
60 if (found !== undefined) return found;
61 }
62 return undefined;
outdated

The doc comment above now attaches to MINE_ANCHOR instead of lineageCard. Move the constant above the comment.

63 }
64
5565 /**
5666 * The family as a tree: nested lists, so the nesting a sighted reader sees
5767 * as indentation is the nesting a screen reader announces, and a phone
@@ -60,6 +70,9 @@ import { disconnectedOn } from "./frozen.ts";
6070 * fork carries its standing against its own parent.
6171 */
6272 export function lineageCard(lineage: Lineage, hereId: string, viewerId?: string): Html {
73 // The viewer's own node carries the page's one anchor, so `#your-fork` scrolls to it and
74 // `:target` marks it; rows of theirs beyond the first say "you" without the id.
75 const mineId = viewerId === undefined ? undefined : firstOwn(lineage.root, hereId, viewerId);
6376 const node = (n: LineageNode, depth: number): Html => {
6477 const here = n.repo.id === hereId;
6578 const trail = [
@@ -75,6 +88,8 @@ export function lineageCard(lineage: Lineage, hereId: string, viewerId?: string)
7588 href: `/${n.repo.ownerName}/${n.repo.name}`,
7689 nav: true,
7790 current: here,
91 ...(n.repo.id === mineId ? { id: MINE_ANCHOR } : {}),
92 ...(n.repo.id !== hereId && viewerId !== undefined && n.repo.ownerId === viewerId ? { data: { mine: "" } } : {}),
7893 lead: icon(depth === 0 ? "repo" : "fork"),
7994 title: `${n.repo.ownerName}/${n.repo.name}`,
8095 ...(n.repo.description === "" ? {} : { meta: html`${n.repo.description}` }),
src/web/pages/repo.ts +6 −3
@@ -43,7 +43,7 @@ import {
4343 } from "../../actions/forks.ts";
4444 import { FORK_DEFAULT_MODE, forkFollowModes, type ForkFollowMode } from "../../core/fork_follow.ts";
4545 import { FOLLOW_PHRASE, isSevered } from "../../actions/follow_words.ts";
46 import { lineageOf } from "../../core/following.ts";
46 import { lineageOf, MINE_ANCHOR, ownsInTree } from "../../core/following.ts";
4747 import {
4848 archivedParentLine,
4949 followingCard,
@@ -313,13 +313,16 @@ function forkBar(ctx: Ctx, repo: Repo): Html {
313313 user !== undefined && user.id !== repo.ownerId && (!guest || repo.visibility === "public");
314314 // Forge it is for any signed-in person, the owner too: it makes a forge, not a copy in this one.
315315 const canForge = ctx.auth.user?.kind === "user";
316 const forkCount = forksFor(ctx, repo).length;
316 const visible = forksFor(ctx, repo);
317 const forkCount = visible.length;
318 // A visitor with a node anywhere in the tree lands on it: the forks page scrolls there.
319 const mine = ownsInTree(ctx.app, repo, user?.id, (r) => canRead(ctx.app.db, r, user));
317320 if (!canFork && !canForge && forkCount === 0) return html``;
318321 const forks = row({
319322 lead: icon("fork"),
320323 title:
321324 forkCount > 0
322 ? html`<a href="${repoBase(repo)}/forks"
325 ? html`<a href="${repoBase(repo)}/forks${mine ? `#${MINE_ANCHOR}` : ""}"
323326 >${badge(`${forkCount} fork${forkCount === 1 ? "" : "s"}`)}</a
324327 >`
325328 : "Forks",
src/web/style/components.ts +1
@@ -486,6 +486,7 @@ a.flow-row { min-height: 44px; }
486486 a.row:hover, .row[data-nav]:hover { background: var(--muted); color: inherit; }
487487 .list li[aria-current="true"] > .row { background: var(--muted); }
488488 /* A tree: the rows under a row hang from a rule, a step in. */
489 .list li[data-mine] > .row, .list li[data-mine]:target > .row { background: var(--muted); }
outdated

Principle 5: --accent is for interaction alone; this paints ownership. Use a muted background and the 'you' word instead.

489490 .row-children { list-style: none; margin: 0 0 0 22px; padding: 0; border-left: 1px solid var(--border); }
490491 .row-children > li[data-fold] > details > summary { display: flex; align-items: center; min-height: 44px; padding: 0 12px; cursor: pointer; color: var(--muted-fg, inherit); }
491492 .row-children > li[data-fold] > details > summary:hover { background: var(--muted); }
test/fork-tree-here.test.ts added +126
@@ -0,0 +1,126 @@
1 /**
2 * #13670: a fork's page names its upstream and counts its siblings; the forks page marks the
3 * visitor's own node and gives it the anchor the repository's fork link points at.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
10 import { setRole } from "../src/actions/roles.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { getRepo } from "../src/core/repos.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18
19 let dataDir: string;
20 let app: App;
21 let servers: Servers;
22
23 const must = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
24 if (!r.ok) throw new Error(JSON.stringify(r.error));
25 return r.value;
26 };
27 const mk = async (username: string, first: boolean): Promise<User> =>
28 must(
29 await createUser(app.db, {
30 origin: "seed",
31 trusted: true,
32 username,
33 email: `${username}@forge.local`,
34 password: "a-good-passphrase",
35 adminIfFirst: first,
36 }),
37 );
38 const signIn = async (username: string): Promise<string> =>
39 (
40 (
41 await fetch(`${servers.url}/signin`, {
42 method: "POST",
43 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
44 redirect: "manual",
45 })
46 ).headers.get("set-cookie") ?? ""
47 ).split(";")[0]!;
48 const get = async (path: string, cookie = ""): Promise<string> =>
49 (await fetch(`${servers.url}${path}`, { headers: { cookie } })).text();
50
51 beforeAll(async () => {
52 dataDir = await mkdtemp(join(tmpdir(), "forge-fork-tree-here-"));
53 app = createApp({ dataDir, port: 0 });
54 servers = await serve(app);
55 const ann = await mk("ann", true);
56 const bea = await mk("bea", false);
57 const cal = await mk("cal", false);
58 await mk("eve", false);
59 const dee = await mk("dee", false);
60 for (const n of ["bea", "cal", "eve", "dee"]) must(setRole(app, ann, n, "member"));
61 const root = must(await createRepo(app, ann, { name: "yard", visibility: "public" }));
62 must(await commitToBranch(app, ann, root, { message: "first", files: [{ path: "a.txt", content: "a\n" }] }));
63 must(await forkRepo(app, bea, root));
64 must(await forkRepo(app, cal, root));
65 // A deeper fork: dee forks bea's fork, so dee has no direct fork of yard.
66 must(await forkRepo(app, dee, getRepo(app.db, "bea", "yard")!));
67 // A family with one fork only.
68 const pond = must(await createRepo(app, ann, { name: "pond", visibility: "public" }));
69 must(await commitToBranch(app, ann, pond, { message: "first", files: [{ path: "a.txt", content: "a\n" }] }));
70 must(await forkRepo(app, bea, pond));
71 }, 60_000);
72
73 afterAll(async () => {
74 servers?.stop();
75 app?.close();
76 await rm(dataDir, { recursive: true, force: true });
77 });
78
79 test("a fork's page links its upstream and counts the other forks", async () => {
80 const body = await get("/bea/yard");
81 expect(body).toContain('<a href="/ann/yard">ann/yard</a>');
82 expect(body).toMatch(/<a href="\/ann\/yard\/forks" data-siblings>1 other fork<\/a>/);
83 });
84
85 test("a sole fork shows no sibling count", async () => {
86 const body = await get("/bea/pond");
87 expect(body).toContain('<a href="/ann/pond">ann/pond</a>');
88 expect(body).not.toContain("data-siblings");
89 });
90
91 test("a non-fork says nothing of an upstream or siblings", async () => {
92 // ann's repository is no fork.
93 expect(await get("/ann/yard")).not.toContain("data-siblings");
94 expect(await get("/ann/yard")).not.toContain("forked from");
95 });
96
97 test("the visitor's own node carries the anchor and the mark; the fork link points at it", async () => {
98 const cookie = await signIn("cal");
99 const tree = await get("/ann/yard/forks", cookie);
100 expect(tree.match(/id="your-fork"/g)?.length).toBe(1);
101 const li = tree.slice(tree.lastIndexOf("<li", tree.indexOf('id="your-fork"')), tree.indexOf("</a>", tree.indexOf('id="your-fork"')));
102 expect(li).toContain("data-mine");
103 expect(li).toContain("/cal/yard");
104 expect(await get("/ann/yard", cookie)).toContain('href="/ann/yard/forks#your-fork"');
105 });
106
107 test("a visitor without a fork gets no anchor and a plain link", async () => {
108 const cookie = await signIn("eve");
109 expect(await get("/ann/yard/forks", cookie)).not.toContain('id="your-fork"');
110 const home = await get("/ann/yard", cookie);
111 expect(home).not.toContain("#your-fork");
112 expect(home).toContain('href="/ann/yard/forks"');
113 expect(await get("/ann/yard/forks")).not.toContain('id="your-fork"');
114 });
115
116 test("a deeper fork is anchored from the root's fork link and from a sibling link", async () => {
117 const cookie = await signIn("dee");
118 expect(await get("/ann/yard", cookie)).toContain('href="/ann/yard/forks#your-fork"');
119 // cal's page: bea's fork and dee's below it are siblings' tree; the link carries the anchor.
120 expect(await get("/cal/yard", cookie)).toMatch(/href="\/ann\/yard\/forks#your-fork" data-siblings/);
121 const tree = await get("/ann/yard/forks", cookie);
122 const at = tree.indexOf('id="your-fork"');
123 expect(tree.slice(tree.lastIndexOf("<li", at), tree.indexOf("</a>", at))).toContain("/dee/yard");
124 // A visitor with no node keeps the plain sibling link.
125 expect(await get("/cal/yard", await signIn("eve"))).toMatch(/href="\/ann\/yard\/forks" data-siblings/);
126 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs