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

Design: a repository tree's rows and total use §5's row, and tree-row/tree-total leave §5d #4072

Parked opened this
Closed without merging

scout/forge:scout/3840-design-a-repository-tree-s-rows-and-tota → main 12 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +5 −1323
docs/DESIGN.md +1 −1
@@ -394,7 +394,7 @@ gone, so this list only shrinks.
394394 A `.field` directly inside a `.bar` drops its bottom margin and the bar aligns to the end, so a labelled input and its button share a baseline
395395 - **`style/components.ts`** — parts of the §5 components that the table does not spell out — the palette's list, the menu's items, a dialog's head and foot, comments, the theme picker — and a few small helpers beside them: `.cat` `.clone` `.clone-text` `.comment` `.comment-body` `.comment-form` `.dash` `.dialog-body` `.dialog-foot` `.dialog-head` `.empty-title` `.error-note` `.field-row` `.form-actions` `.hex` `.ico` `.ico-loader` `.list` `.live-status` `.menu-item` `.menu-panel` `.menu-sep` `.menu-title` `.palette-empty` `.palette-foot` `.palette-group` `.palette-heading` `.palette-input` `.palette-item` `.palette-list` `.passkey` `.passkey-lead` `.passkey-note` `.passkey-off` `.passkey-on` `.preview` `.sep` `.split` `.sprite` `.swatch` `.table-scroll` `.tell-here` `.theme-apply` `.theme-option` `.tick` `.timeline` `.tl-dot` `.toast-body` `.topbar-search`
396396 - **`style/components.ts`, settings rows** — a list whose rows are settings (limits, capacity): the `<ul class="list setting-list">` lets title and meta wrap instead of ellipsizing, and a row's controls take their own line under 640px. `.row-fields` is the form in that row's trail (input, Save, Default): always visible, never hover-gated, wrapping under the text before it would clip. Use both for any page whose rows show a name, a current value, and a control to change it; use `.row-actions` only for secondary actions (delete, wake, pin, revoke). Flags, telemetry, cloud, people, crew roles and subscription headroom/budget use `.row-fields`. Classes: `.row-fields` `.setting-list`
397 - **`style/content.ts`, page furniture** — what frames a page's content: page and repo heads, the merge box, the front page and its tiles, explore, backups, boards, the fleet chart's series colours, following, lineage: `.act` `.app-shelf` `.app-tile` `.app-tile-body` `.app-tile-desc` `.app-tile-look` `.app-tile-name` `.backups-drill` `.backups-error` `.backups-now` `.backups-restore` `.bform` `.bgrid` `.big` `.bmanage` `.boards-result` `.bp-h2` `.bp-h3` `.bp-w2` `.bp-w3` `.break` `.bt-bar` `.bt-grid` `.bt-group` `.bt-hist` `.bt-name` `.bt-procs` `.bt-row` `.bt-val` `.chart` `.chart-box` `.commit-body` `.commit-head` `.connect-more` `.connect-path` `.domain-records` `.explore-filters` `.explore-line` `.explore-main` `.explore-name` `.explore-row` `.fg-s0` `.fg-s1` `.fg-s2` `.fg-s3` `.fg-s4` `.fg-s5` `.fg-s6` `.fg-s7` `.filters` `.flag-form` `.following` `.following-actions` `.following-eyebrow` `.following-foot` `.following-head` `.following-sentence` `.fork-bar` `.front-admin` `.front-controls` `.front-crew` `.front-featured` `.front-featured-body` `.front-featured-look` `.front-issues` `.front-live` `.front-more` `.front-pick` `.front-pin-any` `.front-weights` `.frozen` `.frozen-form` `.frozen-sentence` `.handoff` `.handoff-links` `.headroom` `.issue-head` `.issue-meta` `.merge-box` `.merge-form` `.merge-headline` `.merge-sub` `.mirror-form` `.number` `.origin-link` `.origin-mark` `.origin-name` `.origin-row` `.owner` `.page-head` `.path-head` `.policy-line` `.qf` `.repo-actions` `.repo-audience` `.repo-desc` `.repo-layout` `.repo-lineage` `.repo-title` `.search` `.slash` `.stage-detail` `.stage-dot` `.steps` `.sub` `.sys-pair` `.table-wrap` `.terminal-line` `.tok` `.tree-row` `.tree-total` `.wall-cells` `.where-sep`
397 - **`style/content.ts`, page furniture** — what frames a page's content: page and repo heads, the merge box, the front page and its tiles, explore, backups, boards, the fleet chart's series colours, following, lineage: `.act` `.app-shelf` `.app-tile` `.app-tile-body` `.app-tile-desc` `.app-tile-look` `.app-tile-name` `.backups-drill` `.backups-error` `.backups-now` `.backups-restore` `.bform` `.bgrid` `.big` `.bmanage` `.boards-result` `.bp-h2` `.bp-h3` `.bp-w2` `.bp-w3` `.break` `.bt-bar` `.bt-grid` `.bt-group` `.bt-hist` `.bt-name` `.bt-procs` `.bt-row` `.bt-val` `.chart` `.chart-box` `.commit-body` `.commit-head` `.connect-more` `.connect-path` `.domain-records` `.explore-filters` `.explore-line` `.explore-main` `.explore-name` `.explore-row` `.fg-s0` `.fg-s1` `.fg-s2` `.fg-s3` `.fg-s4` `.fg-s5` `.fg-s6` `.fg-s7` `.filters` `.flag-form` `.following` `.following-actions` `.following-eyebrow` `.following-foot` `.following-head` `.following-sentence` `.fork-bar` `.front-admin` `.front-controls` `.front-crew` `.front-featured` `.front-featured-body` `.front-featured-look` `.front-issues` `.front-live` `.front-more` `.front-pick` `.front-pin-any` `.front-weights` `.frozen` `.frozen-form` `.frozen-sentence` `.handoff` `.handoff-links` `.headroom` `.issue-head` `.issue-meta` `.merge-box` `.merge-form` `.merge-headline` `.merge-sub` `.mirror-form` `.number` `.origin-link` `.origin-mark` `.origin-name` `.origin-row` `.owner` `.page-head` `.path-head` `.policy-line` `.qf` `.repo-actions` `.repo-audience` `.repo-desc` `.repo-layout` `.repo-lineage` `.repo-title` `.search` `.slash` `.stage-detail` `.stage-dot` `.steps` `.sub` `.sys-pair` `.table-wrap` `.terminal-line` `.tok` `.wall-cells` `.where-sep`
398398 - **`style/content.ts`, code view** — the source view and the syntax-highlight token classes `highlight-html.ts` builds as `tok-${kind}`: `.blob-view` `.ln` `.tok-attribute` `.tok-comment` `.tok-constant` `.tok-decorator` `.tok-deleted` `.tok-emphasis` `.tok-function` `.tok-heading` `.tok-inserted` `.tok-keyword` `.tok-link` `.tok-meta` `.tok-number` `.tok-operator` `.tok-plain` `.tok-property` `.tok-punctuation` `.tok-regex` `.tok-string` `.tok-tag` `.tok-type` `.tok-variable`
399399 - **`style/content.ts`, prose (markdown)** — table cell alignment, built by `markdown.ts` as `ta-${align}`: `.ta-c` `.ta-r`
400400 - **`style/content.ts`, diff viewer** — the diff table: its gutters, line kinds, file head and inline review comments: `.add` `.del` `.dh` `.diff` `.diff-body` `.diff-head` `.diff-note` `.diff-path` `.diff-stat` `.diff-stub` `.diff-summary` `.diff-table` `.dl` `.dl-review` `.dn` `.dn-comment` `.nonl` `.rc-hidden` `.rc-resolve` `.rc-resolved` `.wd`
src/web/pages/repo.ts −1318
@@ -1,1318 +0,0 @@
1 /**
2 * Repository pages: the code at a ref, one file, and the raw bytes.
3 * Everything is URL-addressable and renders without JavaScript; reads go
4 * straight to git, so nothing shown here is stored anywhere else.
5 *
6 * Every ref reaching git passes `isSafeRef` first, and every ref *leaving*
7 * here in a URL is percent-encoded, so a branch called `feature/a` stays one
8 * path segment and can never smuggle a path of its own.
9 */
10
11 import { followingLine } from "./upstream-follow.ts";
12 import { NOT_A_MEMBER } from "../../core/roles.ts";
13 import { storageLimitMessage } from "../../core/storage.ts";
14 import { canRead, listForks, type Repo } from "../../core/repos.ts";
15 import { FORKS_PER_DAY, forkRepo, repositoryLimitMessage } from "../../actions/repos.ts";
16 import { forkDrift, takeUpdates, type ForkDrift } from "../../actions/forks.ts";
17 import { lineageOf } from "../../core/following.ts";
18 import {
19 followingCard,
20 followingOf,
21 lineageCard,
22 nothingNew,
23 } from "./following.ts";
24 import { frozenBlock } from "./frozen.ts";
25 import { pinRepo, syncRepoNow, unpinRepo } from "../../actions/origins.ts";
26 import {
27 canAdmin,
28 canWrite,
29 forkParentFor,
30 visibleForks,
31 } from "../../core/repos.ts";
32 import { isSafeRef, isSafeTreePath } from "../../git/guard.ts";
33 import { blobForRender, type TreeEntry } from "../../git/read.ts";
34 import { repoDir } from "../../git/repos.ts";
35 import { estimateTokens } from "../../kernel/tokens-format.ts";
36 import { safeBack, type Ctx } from "../../http/context.ts";
37 import { json, notFound } from "../../http/respond.ts";
38 import type { Blob, RepoSource } from "../../view/source.ts";
39 import {
40 crumbsFor,
41 loadRepo,
42 notFoundPage,
43 repoBase,
44 repoHeader,
45 scopeHeader,
46 signInFirst,
47 } from "../chrome.ts";
48 import { codeJs } from "../client.ts";
49 import { highlightBlob } from "../code.ts";
50 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
51 import { liveClientJs, liveMount } from "../live.ts";
52 import { appStrip } from "./apps.ts";
53 import { studioApp } from "../studio/app.ts";
54 import { getAppByRepo } from "../../core/apps.ts";
55 import { field, readForm } from "../form.ts";
56 import { html, when, type Html } from "../html.ts";
57 import { flashTo, fragment, page, redirect } from "../layout.ts";
58 import { renderMarkdown } from "../markdown.ts";
59 import { browseBase, localScope, type RepoScope } from "../scope.ts";
60 import { repoForkOf } from "../../core/origins.ts";
61 import {
62 badge,
63 btn,
64 card,
65 empty,
66 fileSize,
67 sizeWithTokens,
68 tokenCount,
69 icon,
70 iconBtn,
71 listCard,
72 row,
73 seg,
74 time,
75 } from "../ui.ts";
76
77 const MAX_RENDER_BYTES = 1_000_000;
78 // A blob under the byte cap can still be pathological (a megabyte of newlines
79 // is ~490k lines). Bounding rendered lines bounds the response independently.
80 const MAX_RENDER_LINES = 5_000;
81
82 import { pathCrumbs, refMenu, refSetFrom, type RefSet } from "./refs.ts";
83 import {
84 codeLayout,
85 codeMount,
86 explorerColumn,
87 explorerFragment,
88 finderButton,
89 finderDialog,
90 loadExplorer,
91 } from "./explorer.ts";
92
93 export { crumbsFor, loadRepo, repoBase };
94 export { pathCrumbs, refMenu, refSet, refSetFrom } from "./refs.ts";
95
96 // ---- fork ----
97
98 /** The parent and the forks this viewer may see, from the request. */
99 const forkParent = (ctx: Ctx, repo: Repo): Repo | undefined =>
100 forkParentFor(ctx.app.db, repo, ctx.auth.user);
101 const forksFor = (ctx: Ctx, repo: Repo): Repo[] =>
102 visibleForks(ctx.app.db, repo.id, ctx.auth.user);
103
104 /**
105 * How far the fork has slipped from its parent, in a phrase. A fork with
106 * commits of its own says so: an update would be refused, so the sentence
107 * has to explain the missing button.
108 */
109 function driftNote(drift: ForkDrift | undefined): string | undefined {
110 if (drift === undefined || drift.ahead === null || drift.behind === null)
111 return undefined;
112 const commits = (n: number) => `${n} commit${n === 1 ? "" : "s"}`;
113 const { ahead, behind } = drift;
114 if (ahead === 0)
115 return behind === 0 ? "up to date" : `${commits(behind)} behind`;
116 if (behind === 0) return `${commits(ahead)} of its own`;
117 return `${commits(ahead)} of its own, ${behind} behind — merge by hand`;
118 }
119
120 /**
121 * Offer the update only when it would fast-forward: something to take, and
122 * nothing of the fork's own in the way. Unknown drift keeps the button, since
123 * the action itself is the thing that decides.
124 */
125 function updatable(drift: ForkDrift | undefined): boolean {
126 if (drift === undefined || drift.ahead === null || drift.behind === null)
127 return true;
128 return drift.behind > 0 && drift.ahead === 0;
129 }
130
131 /**
132 * GET /:owner/:name/forks — every fork of this repository the viewer may
133 * see, newest first. The count on the repository page is the way in.
134 */
135 export async function forksPage(ctx: Ctx): Promise<Response> {
136 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
137 let t = performance.now();
138 const repo = loadRepo(ctx);
139 notePhase(ctx.request, "repository", performance.now() - t);
140 if (!repo) return notFoundPage(ctx);
141 t = performance.now();
142 const forks = listForks(ctx.app.db, repo.id).filter((fork) =>
143 canRead(ctx.app.db, fork, ctx.auth.user),
144 );
145 notePhase(ctx.request, "forks", performance.now() - t);
146 t = performance.now();
147 // The whole family, from the oldest ancestor this viewer may see: who
148 // follows whom, and where each stands against the one it follows.
149 const lineage = await lineageOf(ctx.app, repo, (r) =>
150 canRead(ctx.app.db, r, ctx.auth.user),
151 );
152 notePhase(ctx.request, "lineage", performance.now() - t);
153 t = performance.now();
154 const body = html`${repoHeader(ctx, repo, "forks")}
155 <div class="page-head mt">
156 <h2>${forks.length} fork${forks.length === 1 ? "" : "s"}</h2>
157 </div>
158 ${lineage.size === 1
159 ? empty({
160 icon: "fork",
161 title: "No forks yet",
162 note: "A fork is a copy under another name that can propose changes back here, and follows this one until it has work of its own.",
163 })
164 : lineageCard(lineage, repo.id)}`;
165 const res = page({
166 ctx,
167 title: `Forks · ${repo.ownerName}/${repo.name}`,
168 body,
169 });
170 notePhase(ctx.request, "render", performance.now() - t);
171 return res;
172 }
173
174 /** The "forked from …" lineage line and a Fork button, for the repo home. */
175 function forkBar(ctx: Ctx, repo: Repo): Html {
176 const canFork =
177 ctx.auth.user !== undefined && ctx.auth.user.id !== repo.ownerId;
178 const forkCount = forksFor(ctx, repo).length;
179 if (!canFork && forkCount === 0) return html``;
180 return html`<div class="mt">
181 ${listCard([
182 row({
183 lead: icon("fork"),
184 title:
185 forkCount > 0
186 ? html`<a href="${repoBase(repo)}/forks"
187 >${badge(`${forkCount} fork${forkCount === 1 ? "" : "s"}`)}</a
188 >`
189 : "Forks",
190 trail: canFork
191 ? html`<form method="post" action="${repoBase(repo)}/fork">
192 ${btn("Fork", { size: "sm", icon: "fork" })}
193 </form>`
194 : html``,
195 }),
196 ])}
197 </div>`;
198 }
199
200 // POST /:owner/:name/fork
201 export async function forkSubmit(ctx: Ctx): Promise<Response> {
202 const repo = loadRepo(ctx);
203 if (!repo) return notFoundPage(ctx);
204 if (!ctx.auth.user) return signInFirst(ctx);
205 const form = await readForm(ctx, "rw");
206 if (form instanceof Response) return form;
207
208 const forked = await forkRepo(
209 ctx.app,
210 ctx.auth.user,
211 repo,
212 field(form, "name") || undefined,
213 );
214 if (!forked.ok) {
215 const reason =
216 forked.error === "name_taken"
217 ? "You already have a repository by that name."
218 : forked.error === "not_member"
219 ? `Not made: ${NOT_A_MEMBER}.`
220 : forked.error === "repository_limit"
221 ? `Not made: ${repositoryLimitMessage(ctx.app, ctx.auth.user)}.`
222 : forked.error === "storage_limit"
223 ? `Not made: ${storageLimitMessage(ctx.app, ctx.auth.user.id)}.`
224 : forked.error === "limit"
225 ? `That is today's forks made (${FORKS_PER_DAY} a day). Try again tomorrow.`
226 : "That fork could not be created.";
227 return flashTo(ctx, repoBase(repo), { tone: "danger", message: reason });
228 }
229 return flashTo(ctx, repoBase(forked.value), {
230 message: `Forked to ${forked.value.ownerName}/${forked.value.name}.`,
231 });
232 }
233
234 // ---- mirrors and pins ----
235
236 // POST /:owner/:name/sync — pull this mirror now. Any writer may ask: it only
237 // fetches, so it borrows nobody's identity and grants nobody anything.
238 export async function repoSyncSubmit(ctx: Ctx): Promise<Response> {
239 const repo = loadRepo(ctx);
240 if (!repo) return notFoundPage(ctx);
241 if (!ctx.auth.user) return signInFirst(ctx);
242 const form = await readForm(ctx, "rw");
243 if (form instanceof Response) return form;
244
245 // A native fork takes from its parent; a mirror from its origin.
246 if (repo.origin === null && repo.forkParentId !== null) {
247 const took = await takeUpdates(ctx.app, ctx.auth.user, repo);
248 if (!took.ok) {
249 const e = took.error;
250 return flashTo(ctx, repoBase(repo), {
251 tone: "danger",
252 message:
253 typeof e === "string"
254 ? e === "not_a_fork"
255 ? "This repository has no parent to follow."
256 : "You need write access to update this fork."
257 : e.kind === "conflict"
258 ? `${repo.defaultBranch} and the parent both changed ${e.files.join(", ")}; the crew can converge it.`
259 : e.kind === "moved"
260 ? "Something moved while this was read; try again."
261 : `Git could not take the updates: ${e.message}`,
262 });
263 }
264 const parent = forkParent(ctx, repo);
265 return flashTo(ctx, repoBase(repo), {
266 message: took.value.updated
267 ? `${took.value.merged ? "Merged" : "Updated"} ${repo.defaultBranch} to ${took.value.to.slice(0, 7)}.`
268 : parent === undefined
269 ? "Already up to date with the parent."
270 : nothingNew(parent),
271 });
272 }
273 const synced = await syncRepoNow(ctx.app, ctx.auth.user, repo);
274 if (!synced.ok)
275 return flashTo(ctx, repoBase(repo), {
276 tone: "danger",
277 message:
278 synced.error !== "not_found"
279 ? "You need write access to sync this mirror."
280 : repo.detached !== null
281 ? "This mirror is frozen: its origin was disconnected. Reconnect it first."
282 : "This repository does not mirror an origin.",
283 });
284 return flashTo(ctx, repoBase(repo), {
285 ...(synced.value.error === ""
286 ? { message: "Synced from the origin." }
287 : { tone: "danger" as const, message: synced.value.error }),
288 });
289 }
290
291 /**
292 * POST /:owner/:name/pin — "keep this on my machine", toggled.
293 *
294 * The state being asked for travels in the form rather than being read back
295 * out of the database, so a double submit is idempotent instead of a
296 * flip-flop.
297 */
298 export async function pinSubmit(ctx: Ctx): Promise<Response> {
299 const repo = loadRepo(ctx);
300 if (!repo) return notFoundPage(ctx);
301 if (!ctx.auth.user) return signInFirst(ctx);
302 const form = await readForm(ctx, "rw");
303 if (form instanceof Response) return form;
304
305 const wanted = field(form, "pinned") !== "0";
306 const done = wanted
307 ? pinRepo(ctx.app, ctx.auth.user, repo)
308 : unpinRepo(ctx.app, ctx.auth.user, repo);
309 const back = safeBack(ctx) ?? repoBase(repo);
310 if (!done.ok && wanted)
311 return flashTo(ctx, back, {
312 tone: "danger",
313 message: "That could not be pinned.",
314 });
315 return flashTo(ctx, back, {
316 message: wanted
317 ? "Pinned. The local client keeps it cloned on your machine."
318 : "Unpinned.",
319 });
320 }
321
322 // ---- shared pieces ----
323
324 /**
325 * One directory level. Takes a URL base rather than a repository, so the same
326 * listing renders for a repo we hold and for one we are reading live off
327 * another forge — the rows differ only in where they point.
328 */
329 export function treeListing(
330 base: string,
331 ref: string,
332 path: string,
333 entries: readonly TreeEntry[],
334 ): Html {
335 const encoded = encodeURIComponent(ref);
336 const parent = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
337 const rows: Html[] = [];
338 if (path !== "") {
339 rows.push(
340 row({
341 href: `${base}/tree/${encoded}${parent === "" ? "" : `/${parent}`}`,
342 lead: icon("up"),
343 title: html`<span class="muted">..</span>`,
344 nav: true,
345 }),
346 );
347 }
348 for (const entry of entries) {
349 const target = path === "" ? entry.name : `${path}/${entry.name}`;
350 const isTree = entry.type === "tree";
351 rows.push(
352 row({
353 href: `${base}/${isTree ? "tree" : "blob"}/${encoded}/${target}`,
354 lead: icon(isTree ? "folder" : "file"),
355 title: entry.name,
356 trail:
357 entry.size >= 0
358 ? html`<span class="muted small num"
359 >${sizeWithTokens(entry.size, target)}</span
360 >`
361 : html``,
362 nav: true,
363 data: { kind: entry.type },
364 }),
365 );
366 }
367 const total = directoryTotal(entries);
368 return listCard(rows, total.text.trim() === "" ? {} : { foot: total });
369 }
370
371 /**
372 * What the files at this level weigh together: bytes and estimated tokens,
373 * the two summed over the same files. Subdirectories carry no size in a
374 * tree listing (`git ls-tree -l` gives `-`), so they are not in it — the
375 * line says "here" and the tooltip says why. Binary files add bytes but no
376 * tokens. Nothing when there are no files.
377 */
378 export function directoryTotal(entries: readonly TreeEntry[]): Html {
379 let files = 0;
380 let bytes = 0;
381 let tokens = 0;
382 for (const entry of entries) {
383 if (entry.type !== "blob" || entry.size < 0) continue;
384 files += 1;
385 bytes += entry.size;
386 tokens += estimateTokens(entry.size, entry.name) ?? 0;
387 }
388 if (files === 0) return html``;
389 return html`<span
390 class="muted small num"
391 title="Files at this level only; subdirectories are not counted"
392 >
393 ${files.toLocaleString("en-US")} file${files === 1 ? "" : "s"} here ·
394 ${fileSize(bytes)} · ${tokenCount(tokens, "estimated")}
395 </span>`;
396 }
397
398 /**
399 * The README under a directory listing, read through whichever source is
400 * answering. It is found in the entries we already have rather than by asking
401 * for the tree again — `RepoSource.readme` only knows the root, and a README
402 * two directories down is exactly as worth rendering.
403 */
404 export async function readmeFor(
405 source: RepoSource,
406 ref: string,
407 entries: readonly TreeEntry[],
408 prefix: string,
409 ): Promise<Html> {
410 const readme = entries.find(
411 (e) =>
412 e.type === "blob" && /^readme(\.md|\.markdown|\.txt)?$/i.test(e.name),
413 );
414 if (!readme) return html``;
415 const at = prefix === "" ? readme.name : `${prefix}/${readme.name}`;
416 const blob = await source.blob(ref, at);
417 if (!blob.ok || blob.value.kind !== "text") return html``;
418 if (blob.value.size > MAX_RENDER_BYTES) return html``;
419 const text = new TextDecoder().decode(blob.value.body);
420 const rendered = /\.(md|markdown)$/i.test(readme.name)
421 ? renderMarkdown(text)
422 : html`<pre>${text}</pre>`;
423 return card(html`<div class="prose">${rendered}</div>`, {
424 pad: false,
425 head: html`${icon("file")}
426 <h2>${readme.name}</h2>`,
427 });
428 }
429
430 /**
431 * A Markdown file has two right answers — the prose it becomes and the text
432 * you would edit — so the page offers both and defaults to the one people
433 * came for. `?view=source` is a plain link, so both halves work with no
434 * JavaScript, are addressable, and survive being sent to somebody.
435 */
436 export type BlobView = "source" | "rendered";
437
438 export const isMarkdownPath = (path: string): boolean =>
439 /\.(md|markdown|mdx)$/i.test(path);
440
441 export function blobView(value: string | null): BlobView {
442 return value === "source" ? "source" : "rendered";
443 }
444
445 /** One file, in each of the three states a source can hand one back in. */
446 export function blobBody(
447 base: string,
448 ref: string,
449 path: string,
450 blob: Blob,
451 highlighted?: (ms: number) => void,
452 ): { content: Html; lines: number } {
453 const encoded = encodeURIComponent(ref);
454 if (blob.kind === "binary") {
455 return {
456 lines: 0,
457 content: empty({
458 icon: "file",
459 title: "Binary file",
460 note: `${fileSize(blob.size)} — not shown, but you can download it.`,
461 action: btn("Download", {
462 href: `${base}/raw/${encoded}/${path}`,
463 variant: "primary",
464 icon: "download",
465 }),
466 }),
467 };
468 }
469 if (blob.kind === "too_large") {
470 return {
471 lines: 0,
472 content: empty({
473 icon: "alert",
474 title: "Too large to render",
475 note: `${fileSize(blob.size)} — over the render cap. Fetch the raw bytes instead.`,
476 action: btn("View raw", {
477 href: `${base}/raw/${encoded}/${path}`,
478 variant: "primary",
479 }),
480 }),
481 };
482 }
483 const text = new TextDecoder().decode(blob.body).replace(/\n$/, "");
484 // Highlight the whole file (multi-line constructs need full context),
485 // then take the first N lines for rendering.
486 const began = performance.now();
487 const highlight = highlightBlob(text, path);
488 highlighted?.(performance.now() - began);
489 const lines = highlight.slice(0, MAX_RENDER_LINES);
490 const truncated = highlight.length > MAX_RENDER_LINES;
491 return {
492 lines: highlight.length,
493 content: html`<div class="card code">
494 <table>
495 ${lines.map(
496 (line, i) =>
497 html`<tr id="L${i + 1}">
498 <td class="ln"><a href="#L${i + 1}">${i + 1}</a></td>
499 <td><pre>${line}</pre></td>
500 </tr>`,
501 )}
502 </table>
503 </div>
504 ${when(truncated, () =>
505 empty({
506 icon: "alert",
507 title: "Showing the first 5,000 lines",
508 note: `This file has ${highlight.length.toLocaleString()} lines. Fetch the raw bytes for all of them.`,
509 action: btn("View raw", { href: `${base}/raw/${encoded}/${path}` }),
510 }),
511 )}`,
512 };
513 }
514
515 /** The ref switcher and the History link every code page carries. */
516 export function codeBar(
517 refs: RefSet,
518 ref: string,
519 hrefFor: (r: string) => string,
520 historyHref: string,
521 menu: { base?: string; canWrite?: boolean } = {},
522 ): Html {
523 return html`${refMenu(refs, ref, hrefFor, menu)}
524 ${btn("History", {
525 href: historyHref,
526 size: "sm",
527 variant: "outline",
528 icon: "history",
529 })}`;
530 }
531
532 /**
533 * The About rail: what this repo is, in one glance, plus how to clone it.
534 *
535 * On a mirror, everything about the origin sits in one "Where it lives"
536 * block — where it comes from, when it last came, the button that fetches it
537 * now, and where a push actually lands. Those four facts used to be spread
538 * across three parts of the card, which is how someone ends up pushing to a
539 * mirror without knowing the origin gets the last word.
540 *
541 * `drift` is how far the fork has slipped from its parent, read by the caller
542 * (git, so asynchronous); `undefined` on anything that is not a native fork.
543 */
544 function aboutCard(
545 ctx: Ctx,
546 repo: Repo,
547 refs: RefSet,
548 drift?: ForkDrift,
549 ): Html {
550 const cloneUrl = `${ctx.url.origin}/${repo.ownerName}/${repo.name}.git`;
551 // An SSH listener is not built yet; when a deployment configures one, the
552 // second clone line appears with no further change here.
553 const sshPort = (ctx.app.config as { sshPort?: number }).sshPort;
554 const parent = forkParent(ctx, repo);
555 const origin = repo.origin;
556 // A fork made at the origin has no `forkParentId` — its parent is a
557 // repository on another forge — so the lineage row reads it off the link
558 // the fork flow wrote, and points at the live browse of the upstream.
559 const upstream = repoForkOf(ctx.app.db, repo.id);
560 const upstreamHref =
561 upstream === null || origin === null
562 ? undefined
563 : browseBase(origin.originId, upstream);
564 const admin = canAdmin(ctx.app.db, repo, ctx.auth.user);
565 const whereItLives = when(
566 origin,
567 (o) =>
568 html`<div class="where-block">
569 <h3>Where it lives</h3>
570 <ul class="list setting-list">
571 ${row({
572 title: "Origin",
573 trail:
574 o.htmlUrl === ""
575 ? html`${o.fullName}`
576 : html`<a href="${o.htmlUrl}" rel="noreferrer noopener"
577 >${o.fullName}</a
578 >`,
579 })}
580 ${row({
581 title: "Last fetch",
582 trail: html`${o.lastFetchAt === null ? "never" : time(o.lastFetchAt)}`,
583 })}
584 </ul>
585 ${when(
586 o.fetchError !== "",
587 () => html`<p class="error-note mt">${o.fetchError}</p>`,
588 )}
589 ${when(
590 admin,
591 () =>
592 html`<form method="post" action="${repoBase(repo)}/sync" class="mt">
593 ${btn("Sync now", { size: "sm", icon: "sync" })}
594 </form>`,
595 )}
596 <p class="mt small muted">
597 Pushes here go through to
598 <span class="mono">${o.fullName}</span> first — if the origin refuses
599 one, nothing lands locally either.
600 </p>
601 </div>`,
602 );
603 return html`${card(
604 html`${when(
605 repo.description !== "",
606 () => html`<p class="mb">${repo.description}</p>`,
607 )}
608 <ul class="list setting-list">
609 ${row({ title: "Visibility", trail: html`${repo.visibility}` })}
610 ${row({
611 title: "Default",
612 trail: html`<span class="mono">${repo.defaultBranch}</span>`,
613 })}
614 ${row({ title: "Protection", trail: html`${repo.protectDefault ? "on" : "off"}` })}
615 ${row({
616 title: "Branches",
617 trail: html`<span class="num">${refs.branches.length}</span>`,
618 })}
619 ${when(
620 refs.tags.length > 0,
621 () =>
622 row({
623 title: "Tags",
624 trail: html`<span class="num">${refs.tags.length}</span>`,
625 }),
626 )}
627 ${when(
628 parent,
629 (p) =>
630 // The standing and the one thing to do about it live in the
631 // Following card above the code; the rail only names the parent.
632 row({
633 title: "Fork of",
634 trail: html`<a href="/${p.ownerName}/${p.name}"
635 >${p.ownerName}/${p.name}</a
636 >`,
637 }),
638 )}
639 ${when(
640 upstream,
641 (up) =>
642 row({
643 title: "Fork of",
644 trail:
645 upstreamHref === undefined
646 ? html`<span class="mono">${up}</span>`
647 : html`<a href="${upstreamHref}">${up}</a>`,
648 }),
649 )}
650 </ul>
651 ${followingLine(ctx, repo)}
652 ${whereItLives}
653 ${when(
654 repo.visibility === "public" && repo.origin === null,
655 () =>
656 html`<p class="mt small muted">
657 ${icon("lock")} Found a security problem?
658 <a href="${repoBase(repo)}/issues/new?sealed=1"
659 >Report it sealed</a
660 >: only the people who keep this repository and its crew see it
661 until the fix is released.
662 </p>`,
663 )}
664 <p class="mt small muted">Clone over HTTPS</p>
665 <span class="clone"
666 ><span class="clone-text" id="clone-https">${cloneUrl}</span>
667 ${iconBtn("copy", "Copy clone URL", {
668 size: "sm",
669 type: "button",
670 copy: "clone-https",
671 })}</span
672 >
673 ${when(
674 sshPort !== undefined,
675 () =>
676 html`<p class="mt small muted">Clone over SSH</p>
677 <span class="clone"
678 ><span class="clone-text" id="clone-ssh"
679 >ssh://git@${ctx.app.config.host ??
680 ctx.url
681 .hostname}:${sshPort}/${repo.ownerName}/${repo.name}.git</span
682 ></span
683 >`,
684 )}`,
685 { head: html`<h2>About</h2>` },
686 )}`;
687 }
688
689 // ---- pages ----
690
691 /**
692 * Studio's own word for a repository it otherwise has nothing to say about:
693 * no app record, so no head card, no box, no Now — just the code underneath,
694 * same as it always rendered. One line says so, and the one door out —
695 * `/settings/app`, the same "Run as an app" form Settings already carries —
696 * opens only for whoever could actually submit it, so a reader never sees a
697 * button that would just come back refused.
698 */
699 function noAppCard(ctx: Ctx, repo: Repo): Html {
700 const admin = canAdmin(ctx.app.db, repo, ctx.auth.user);
701 return empty({
702 icon: "rocket",
703 title: "This repository has no app yet.",
704 ...(admin
705 ? {
706 action: btn("Run as an app", {
707 href: `${repoBase(repo)}/settings/app`,
708 variant: "primary",
709 icon: "rocket",
710 }),
711 }
712 : {}),
713 });
714 }
715
716 /** The tree, the README under it, and the ref switcher above both. */
717 export async function renderCode(
718 scope: RepoScope,
719 o: {
720 refs: RefSet;
721 ref: string;
722 path: string;
723 entries: readonly TreeEntry[];
724 extra?: Html;
725 rail?: Html;
726 /** The README, when the caller has already read it (and timed the read). */
727 readme?: Html;
728 },
729 ): Promise<Html> {
730 const base = scope.base;
731 const { ref, path } = o;
732 const readme = o.readme ?? (await readmeFor(scope.source, ref, o.entries, path));
733 const historyParams = new URLSearchParams({ ref });
734 if (path !== "") historyParams.set("path", path);
735 const bar =
736 path === ""
737 ? html`<div class="bar mb">
738 ${codeBar(
739 o.refs,
740 ref,
741 (r) => `${base}?ref=${encodeURIComponent(r)}`,
742 `${base}/commits?${historyParams.toString()}`,
743 { base, canWrite: scope.caps.write },
744 )}
745 <span class="spacer"></span>
746 ${finderButton()}
747 </div>`
748 : html`<div class="path-head">
749 ${refMenu(
750 o.refs,
751 ref,
752 (r) => `${base}/tree/${encodeURIComponent(r)}/${path}`,
753 { base, canWrite: scope.caps.write },
754 )}
755 ${pathCrumbs(base, scope.facts.name, ref, path, false)}
756 <span class="spacer"></span>
757 ${btn("History", {
758 href: `${base}/commits?${historyParams.toString()}`,
759 size: "sm",
760 variant: "outline",
761 icon: "history",
762 })}
763 </div>`;
764 const main = html`${bar} ${o.extra ?? null}
765 ${treeListing(base, ref, path, o.entries)}
766 <div class="mt">${readme}</div>`;
767 return o.rail === undefined
768 ? main
769 : html`<div class="repo-layout">
770 <div>${main}</div>
771 <aside aria-label="About">${o.rail}</aside>
772 </div>`;
773 }
774
775 /**
776 * What a file page offers besides reading it.
777 *
778 * Three situations, one button. On a repository we hold and may push, it is
779 * Edit. On one whose origin says we may not — a live browse, or a mirror of
780 * somebody else's repository — it is **Propose a change**, which is the same
781 * editor with a fork and a pull request behind the button. Nothing
782 * disappears, because "you cannot change this" is never the whole truth: you
783 * can always propose it.
784 */
785 export function editAction(scope: RepoScope, ref: string, path: string): Html {
786 const encoded = encodeURIComponent(ref);
787 if (scope.propose !== undefined) {
788 return btn("Propose a change", {
789 href: `${scope.base}/edit/${encoded}/${path}`,
790 size: "sm",
791 variant: "outline",
792 icon: "fork",
793 shortcut: "e",
794 title: `You cannot push to ${scope.propose.upstream} — this lands on your fork and opens a pull there`,
795 });
796 }
797 if (scope.kind === "origin") {
798 const mirror = scope.mirror;
799 return btn("Mirror to edit", {
800 href:
801 mirror === undefined
802 ? scope.base
803 : `/${mirror.ownerName}/${mirror.name}/edit/${encoded}/${path}`,
804 size: "sm",
805 variant: "outline",
806 icon: mirror === undefined ? "download" : "pencil",
807 title:
808 mirror === undefined
809 ? "This repository is read-only here. Mirror it into your workbench to edit it."
810 : "Edit this file in the mirror",
811 });
812 }
813 if (!scope.caps.write) return html``;
814 return btn("Edit", {
815 href: `${scope.base}/edit/${encoded}/${path}`,
816 size: "sm",
817 variant: "outline",
818 icon: "pencil",
819 shortcut: "e",
820 });
821 }
822
823 /**
824 * One file, framed by the same path header the tree uses. The header is
825 * sticky and the whole pane is one element, because a script swapping a
826 * preview in replaces exactly this.
827 */
828 export function renderBlob(
829 scope: RepoScope,
830 o: {
831 refs: RefSet;
832 ref: string;
833 path: string;
834 blob: Blob;
835 view?: BlobView;
836 /** Told how long highlighting took, for Server-Timing. */
837 highlighted?: (ms: number) => void;
838 },
839 ): Html {
840 const base = scope.base;
841 const encoded = encodeURIComponent(o.ref);
842 const markdown = o.blob.kind === "text" && isMarkdownPath(o.path);
843 const view: BlobView = markdown ? (o.view ?? "rendered") : "source";
844 const { content, lines } =
845 view === "rendered" && o.blob.kind === "text"
846 ? renderedMarkdown(o.blob)
847 : blobBody(base, o.ref, o.path, o.blob, o.highlighted);
848 const sizeText =
849 o.blob.kind === "too_large" ? "" : sizeWithTokens(o.blob.size, o.path);
850 const fileHref = `${base}/blob/${encoded}/${o.path}`;
851 return html`<div class="code-pane" id="code-pane" data-path="${o.path}">
852 <div class="path-head">
853 ${refMenu(
854 o.refs,
855 o.ref,
856 (r) => `${base}/blob/${encodeURIComponent(r)}/${o.path}`,
857 { base, canWrite: scope.caps.write },
858 )}
859 ${pathCrumbs(base, scope.facts.name, o.ref, o.path, true)}
860 <span class="spacer"></span>
861 ${when(
862 lines > 0,
863 () =>
864 html`<span class="muted small num"
865 >${lines.toLocaleString()} lines · ${sizeText}</span
866 >`,
867 )}
868 ${when(
869 markdown,
870 () =>
871 html`<span class="blob-view"
872 >${seg([
873 {
874 label: "Source",
875 href: `${fileHref}?view=source`,
876 current: view === "source",
877 },
878 {
879 label: "Rendered",
880 href: fileHref,
881 current: view === "rendered",
882 },
883 ])}</span
884 >`,
885 )}
886 ${btn("Raw", {
887 href: `${base}/raw/${encoded}/${o.path}`,
888 size: "sm",
889 variant: "outline",
890 })}
891 ${btn("History", {
892 href: `${base}/commits?ref=${encoded}&path=${encodeURIComponent(o.path)}`,
893 size: "sm",
894 variant: "outline",
895 icon: "history",
896 })}
897 ${editAction(scope, o.ref, o.path)}
898 </div>
899 ${content}
900 </div>`;
901 }
902
903 /** A Markdown file as prose, framed exactly the way a README is. */
904 function renderedMarkdown(blob: Blob & { kind: "text" }): {
905 content: Html;
906 lines: number;
907 } {
908 const text = new TextDecoder().decode(blob.body);
909 return {
910 lines: text === "" ? 0 : text.replace(/\n$/, "").split("\n").length,
911 content: html`<div class="card prose">${renderMarkdown(text)}</div>`,
912 };
913 }
914
915 /** The bytes, with the headers that stop them ever executing as a page. */
916 export function rawResponse(blob: Blob): Response {
917 if (blob.kind === "too_large") return new Response("", { status: 404 });
918 return new Response(blob.body, {
919 headers: {
920 "content-type":
921 blob.kind === "text"
922 ? "text/plain; charset=utf-8"
923 : "application/octet-stream",
924 "x-content-type-options": "nosniff",
925 "content-security-policy": "default-src 'none'; sandbox",
926 "cache-control": "private, max-age=0",
927 },
928 });
929 }
930
931 // GET /:owner/:name — the repo home. An app's home is the app, for every
932 // viewer: what it serves, who is on it, what it asks; its code is one tab
933 // deeper, at /files. Any other repository's home is its code. An older
934 // `?ref=` link to the code of an app is handed on to its Files step.
935 export async function repoHome(ctx: Ctx): Promise<Response> {
936 const repo = loadRepo(ctx);
937 if (!repo) return notFoundPage(ctx);
938 const record = getAppByRepo(ctx.app.db, repo.id);
939 if (record === undefined) return await codeHome(ctx, repo);
940 if (ctx.url.searchParams.has("ref"))
941 return redirect(`${repoBase(repo)}/files${ctx.url.search}`);
942 return await studioApp(ctx, repo, record);
943 }
944
945 // GET /:owner/:name/files — an app's Files step: its code, exactly the page
946 // any other repository's home is. A repository that is not an app has no
947 // step under a home that is already its code, so it is sent there.
948 export async function repoFiles(ctx: Ctx): Promise<Response> {
949 const repo = loadRepo(ctx);
950 if (!repo) return notFoundPage(ctx);
951 if (getAppByRepo(ctx.app.db, repo.id) === undefined)
952 return redirect(`${repoBase(repo)}${ctx.url.search}`);
953 return await codeHome(ctx, repo);
954 }
955
956 /**
957 * "Archived on <date>" with, for an admin, the Wake button. A repository put
958 * away still clones, pushes and links as before; this only says so.
959 */
960 function archivedLine(ctx: Ctx, repo: Repo): Html | null {
961 if (repo.archivedAt === null) return null;
962 return html`<div class="mt archived">
963 <p>
964 Archived on
965 <time datetime="${repo.archivedAt}">${repo.archivedAt.slice(0, 10)}</time>
966 </p>
967 ${when(
968 canAdmin(ctx.app.db, repo, ctx.auth.user),
969 () => html`<form method="post" action="${repoBase(repo)}/settings/archive">
970 <input type="hidden" name="archived" value="0" />
971 <input type="hidden" name="to" value="repo" />
972 ${btn("Wake", { size: "sm" })}
973 </form>`,
974 )}
975 </div>`;
976 }
977
978 /** The code at a ref: the tree, the README and the About rail — with, in
979 * the studio, the offer to make a repository that is not an app one. */
980 async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
981 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
982 const isApp = timePhase(ctx.request, "appof", () => getAppByRepo(ctx.app.db, repo.id) !== undefined);
983 const noApp = isApp ? null : noAppCard(ctx, repo);
984 const scope = localScope(ctx, repo);
985 const cloneUrl = `${ctx.url.origin}/${repo.ownerName}/${repo.name}.git`;
986 const refs = await timePhaseAsync(ctx.request, "refs", () => refSetFrom(scope.source));
987
988 if (refs.branches.length === 0) {
989 const body = html`${scopeHeader(ctx, scope, "code")}${archivedLine(ctx, repo)}${noApp}
990 <div class="mt">
991 ${empty({
992 icon: "repo",
993 title: "An empty repository, ready for its first push",
994 note: "Point a local repository at it and push — the first branch you push becomes the code you see here.",
995 })}
996 ${card(
997 html`<span class="clone"
998 ><span class="clone-text" id="clone-https"
999 >git remote add origin ${cloneUrl} &amp;&amp; git push -u origin
1000 ${repo.defaultBranch}</span
1001 >
1002 ${iconBtn("copy", "Copy", {
1003 size: "sm",
1004 type: "button",
1005 copy: "clone-https",
1006 })}</span
1007 >`,
1008 {
1009 head: html`${icon("command")}
1010 <h2>Get started</h2>`,
1011 },
1012 )}
1013 </div>`;
1014 return page({
1015 ctx,
1016 title: repo.name,
1017 description: repo.description,
1018 ogImage: `/og/repo/${repo.ownerName}~${repo.name}.png`,
1019 feed: {
1020 href: `${repoBase(repo)}/activity.atom`,
1021 title: `${repo.ownerName}/${repo.name} activity`,
1022 },
1023 crumbs: scope.crumbs,
1024 palette: scope.palette,
1025 body,
1026 });
1027 }
1028
1029 const wanted = ctx.url.searchParams.get("ref");
1030 const ref =
1031 wanted !== null && isSafeRef(wanted) && knownRef(refs, wanted)
1032 ? wanted
1033 : knownRef(refs, repo.defaultBranch)
1034 ? repo.defaultBranch
1035 : refs.branches[0]!;
1036 // A fork's rail says how far its default branch is from its parent's; the
1037 // count is git's, so it is read here rather than inside the card — beside
1038 // the tree read, not after it, because neither waits on the other.
1039 const parent = forkParent(ctx, repo);
1040 const [entries, drift] = await Promise.all([
1041 timePhaseAsync(ctx.request, "tree", () => scope.source.tree(ref, "")),
1042 parent === undefined ? undefined : forkDrift(ctx.app, repo, parent),
1043 ]);
1044 const tree = entries.ok ? entries.value : [];
1045
1046 const readme = await timePhaseAsync(ctx.request, "readme", () =>
1047 readmeFor(scope.source, ref, tree, ""),
1048 );
1049 const following = await timePhaseAsync(ctx.request, "following", () => followingOf(ctx, repo));
1050 const rendering = performance.now();
1051 const body = html`${scopeHeader(ctx, scope, "code", {
1052 branchCount: refs.branches.length,
1053 })}${archivedLine(ctx, repo)}${noApp}
1054 ${frozenBlock(ctx, repo)} ${appStrip(ctx, repo)}
1055 ${following === undefined
1056 ? forkBar(ctx, repo)
1057 : followingCard(ctx, repo, following)}
1058 ${await renderCode(scope, {
1059 refs,
1060 ref,
1061 path: "",
1062 entries: tree,
1063 readme,
1064 rail: aboutCard(ctx, repo, refs, drift),
1065 })}
1066 ${codeMount(scope, ref)} ${finderDialog()} ${liveMount({ repo: scope.base })}`;
1067 const response = page({
1068 ctx,
1069 title: repo.name,
1070 description: repo.description,
1071 ogImage: `/og/repo/${repo.ownerName}~${repo.name}.png`,
1072 feed: {
1073 href: `${repoBase(repo)}/activity.atom`,
1074 title: `${repo.ownerName}/${repo.name} activity`,
1075 },
1076 crumbs: scope.crumbs,
1077 palette: scope.palette,
1078 body,
1079 scriptJs: `${codeJs}\n${liveClientJs}`,
1080 });
1081 notePhase(ctx.request, "render", performance.now() - rendering);
1082 return response;
1083 }
1084
1085 function knownRef(refs: RefSet, name: string): boolean {
1086 return refs.branches.includes(name) || refs.tags.includes(name);
1087 }
1088
1089 /**
1090 * The explorer's "New file" affordance, for a writer standing in a folder —
1091 * or, where the origin says you cannot push, its propose twin.
1092 */
1093 export function newFileAction(
1094 scope: RepoScope,
1095 ref: string,
1096 dir: string,
1097 ): Html {
1098 const encoded = encodeURIComponent(ref);
1099 const href = `${scope.base}/new/${encoded}${dir === "" ? "" : `/${dir}`}`;
1100 if (scope.propose !== undefined)
1101 return btn("Propose a new file", {
1102 href,
1103 size: "sm",
1104 variant: "ghost",
1105 icon: "fork",
1106 });
1107 if (!scope.caps.write || scope.kind !== "local") return html``;
1108 return btn("New file", {
1109 href,
1110 size: "sm",
1111 variant: "ghost",
1112 icon: "filePlus",
1113 });
1114 }
1115
1116 /**
1117 * The code browser's frame: the explorer column, the content beside it, and
1118 * the finder dialog that both the button and `t` open. Every code page —
1119 * ours and a live browse — goes through here, so the two can never drift.
1120 */
1121 export function codePage(
1122 ctx: Ctx,
1123 scope: RepoScope,
1124 o: {
1125 title: string;
1126 ref: string;
1127 explorer: Html;
1128 content: Html;
1129 header?: Html;
1130 before?: Html;
1131 },
1132 ): Response {
1133 return page({
1134 ctx,
1135 title: o.title,
1136 crumbs: scope.crumbs,
1137 palette: scope.palette,
1138 body: html`${o.header ?? scopeHeader(ctx, scope, "code", { compact: true })}
1139 ${o.before ?? null} ${codeLayout(o.explorer, o.content)}
1140 ${codeMount(scope, o.ref)} ${finderDialog()}`,
1141 scriptJs: codeJs,
1142 wide: true,
1143 });
1144 }
1145
1146 /**
1147 * The object reads of one request, summed: Server-Timing names `git` once,
1148 * however many reads the page made.
1149 */
1150 function gitClock(request: Request): {
1151 read: <T>(work: () => Promise<T>) => Promise<T>;
1152 done: () => void;
1153 } {
1154 let total = 0;
1155 return {
1156 read: async (work) => {
1157 const began = performance.now();
1158 try {
1159 return await work();
1160 } finally {
1161 total += performance.now() - began;
1162 }
1163 },
1164 done: () => notePhase(request, "git", total),
1165 };
1166 }
1167
1168 // GET /:owner/:name/tree/:ref[/*path]
1169 export async function treePage(ctx: Ctx): Promise<Response> {
1170 const repo = loadRepo(ctx);
1171 if (!repo) return notFoundPage(ctx);
1172 const scope = localScope(ctx, repo);
1173 const ref = ctx.params.ref ?? "";
1174 const path = ctx.params.path ?? "";
1175 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
1176 const git = gitClock(ctx.request);
1177 const entries = await git.read(() => scope.source.tree(ref, path));
1178 if (!entries.ok) return notFoundPage(ctx);
1179
1180 // The explorer's lazy expansion asks for exactly one directory.
1181 if (ctx.url.searchParams.get("fragment") === "explorer") {
1182 git.done();
1183 return fragment(explorerFragment(scope.base, ref, path, entries.value), {
1184 request: ctx.request,
1185 });
1186 }
1187
1188 const [refs, explorer] = await git.read(() =>
1189 Promise.all([
1190 refSetFrom(scope.source),
1191 loadExplorer(scope.source, ref, path, false),
1192 ]),
1193 );
1194 git.done();
1195 // `render` includes the README read: it is fetched while the page is built.
1196 const began = performance.now();
1197 const response = codePage(ctx, scope, {
1198 title: `${path || ref} · ${repo.name}`,
1199 ref,
1200 explorer: explorerColumn(scope, explorer, {
1201 finder: true,
1202 actions: newFileAction(scope, ref, path),
1203 }),
1204 content: await renderCode(scope, {
1205 refs,
1206 ref,
1207 path,
1208 entries: entries.value,
1209 }),
1210 });
1211 notePhase(ctx.request, "render", performance.now() - began);
1212 return response;
1213 }
1214
1215 // GET /:owner/:name/blob/:ref/*path
1216 export async function blobPage(ctx: Ctx): Promise<Response> {
1217 const repo = loadRepo(ctx);
1218 if (!repo) return notFoundPage(ctx);
1219 const scope = localScope(ctx, repo);
1220 const ref = ctx.params.ref ?? "";
1221 const path = ctx.params.path ?? "";
1222 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
1223 const git = gitClock(ctx.request);
1224 const blob = await git.read(() => scope.source.blob(ref, path));
1225 if (!blob.ok) return notFoundPage(ctx);
1226 const refs = await git.read(() => refSetFrom(scope.source));
1227 let highlightMs: number | undefined;
1228 const renderStart = performance.now();
1229 const pane = renderBlob(scope, {
1230 refs,
1231 ref,
1232 path,
1233 blob: capped(blob.value),
1234 view: blobView(ctx.url.searchParams.get("view")),
1235 highlighted: (ms) => (highlightMs = (highlightMs ?? 0) + ms),
1236 });
1237 if (highlightMs !== undefined) notePhase(ctx.request, "highlight", highlightMs);
1238 const paneMs = performance.now() - renderStart - (highlightMs ?? 0);
1239
1240 // The preview a script drops into the pane beside the explorer. Same
1241 // renderer, same markup — a preview and a real page load are the same file.
1242 if (ctx.url.searchParams.get("fragment") === "1") {
1243 git.done();
1244 notePhase(ctx.request, "render", paneMs);
1245 return fragment(pane, { request: ctx.request });
1246 }
1247
1248 const explorer = await git.read(() =>
1249 loadExplorer(scope.source, ref, path, true),
1250 );
1251 git.done();
1252 const filename = path.split("/").pop() ?? path;
1253 const pageStart = performance.now();
1254 const response = await codePage(ctx, scope, {
1255 title: `${filename} · ${repo.name}`,
1256 ref,
1257 explorer: explorerColumn(scope, explorer, {
1258 finder: true,
1259 actions: newFileAction(
1260 scope,
1261 ref,
1262 path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "",
1263 ),
1264 }),
1265 content: pane,
1266 });
1267 notePhase(ctx.request, "render", paneMs + performance.now() - pageStart);
1268 return response;
1269 }
1270
1271 /**
1272 * GET /:owner/:name/paths/:ref — every file path at a ref, as JSON, for the
1273 * fuzzy finder. It is the same read `RepoSource.paths` already bounds and
1274 * caches, behind the same `canRead` every other repo route asks: a repository
1275 * you cannot see does not have a path list either.
1276 */
1277 export async function pathsJson(ctx: Ctx): Promise<Response> {
1278 const repo = loadRepo(ctx);
1279 if (!repo) return notFound();
1280 const scope = localScope(ctx, repo);
1281 const listed = await scope.source.paths(ctx.params.ref ?? "");
1282 if (!listed.ok) return notFound();
1283 return json(
1284 {
1285 ref: ctx.params.ref ?? "",
1286 paths: listed.value.paths,
1287 truncated: listed.value.truncated,
1288 },
1289 200,
1290 { "cache-control": "private, max-age=30" },
1291 );
1292 }
1293
1294 /** The page's own render ceiling, under the source's fetch ceiling. */
1295 function capped(blob: Blob): Blob {
1296 return blob.kind !== "too_large" && blob.size > MAX_RENDER_BYTES
1297 ? { kind: "too_large", size: blob.size }
1298 : blob;
1299 }
1300
1301 /**
1302 * GET /:owner/:name/raw/:ref/*path — the bytes, nothing else. Served as plain
1303 * text (or an opaque stream for binary) with `nosniff` and a `sandbox` CSP, so
1304 * a file in a repository can never execute as a page on this origin.
1305 */
1306 export async function rawBlob(ctx: Ctx): Promise<Response> {
1307 const repo = loadRepo(ctx);
1308 if (!repo) return notFoundPage(ctx);
1309 const ref = ctx.params.ref ?? "";
1310 const path = ctx.params.path ?? "";
1311 if (!isSafeRef(ref) || !isSafeTreePath(path)) return notFoundPage(ctx);
1312
1313 const dir = repoDir(ctx.app.reposRoot, repo.ownerName, repo.name);
1314 const blob = await blobForRender(dir, ref, path, 25_000_000);
1315 if (blob.kind === "missing" || blob.kind === "too_large")
1316 return notFoundPage(ctx);
1317 return rawResponse(blob);
1318 }
src/web/style/content.ts −4
@@ -237,10 +237,6 @@ a.origin-chip:hover { border-color: var(--border-strong); color: var(--fg); }
237237 margin-top: 8px; font-size: 13px; color: var(--muted-fg);
238238 }
239239
240 .tree-row { padding: 8px 14px; min-height: 36px; }
241 .tree-row .ico { color: var(--faint); }
242 .tree-row[data-kind="tree"] .ico { color: var(--accent); }
243 .tree-total { margin: 6px 2px 0; text-align: right; }
244240 .tok { white-space: nowrap; }
245241
246242 /* The file's location stays on screen while its contents scroll past. Opaque
test/tokens.test.ts +4
@@ -193,6 +193,10 @@ describe("token counts on the pages", () => {
193193 // Files here: 4000 + 3000 + 8 = 7008 B = 6.8 KB; 1000 + 1000 + 0 tokens.
194194 expect(page).toMatch(/3 files here ·\s+6\.8 KB ·\s+<span[^>]*>~2\.0k tok</);
195195 expect(page).toContain("subdirectories are not counted");
196 // Rows and total are §5's: no page-local tree classes.
197 expect(page).not.toContain("tree-row");
198 expect(page).not.toContain("tree-total");
199 expect(page).toContain('class="card-foot"');
196200 });
197201
198202 test("a file shows its tokens beside its size, with the estimate said", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs