Fix the code browser's review findings: 404 caching, folds against the address, the landings filter across pages
Before adoption: this commit came in with the history the project adopted, so no landing records it.
- A code page that found nothing answers the brief cache even at a whole commit id: route headers run for a 404 too, so a missing commit or a project imported later was kept by browsers for a year as `immutable`. `codePageHeaders(rev, found)` now serves all five code routes, the commit page included (found = the loader read data). - The diff follows the address only when the address moves: the hash effect re-ran on every fold, so the file the address named could not be folded and folding any other file scrolled back to it. The commit page also decodes its loader data once per read (a fresh `diff.files` each render re-parsed every file in `DiffCode` on every fold). - Each commit's files are parsed once per page (`drawn`, optional on `CommitView` and `PlainDiff`), the rail's changed files and the tree's key order are memoised, so `J`/`K` and folds parse nothing again. - The landings pager keeps `?show=` (`commitsHref` takes `show`): Older and Newer no longer drop the Answers or Ask openings filter. - The soft landing keeps the Files button (each code route's `notFoundComponent` passes it), so a phone reaches the tree from a missing path. - `y` (Permalink) honours the single-keys switch (`permalinkPress`), as the shell's other single keys do. - The tree's `+n −m` decoration keeps its space (a no-break space; a plain one collapsed between the row's boxes), and a rival forge's name left a doc comment. - Tests: headers for a 404 at a commit id; the pager keeping the filter; the Files button on every soft landing; the permalink key off with the switch. The fold fix is checked by hand (CodeView draws nothing in vitest): folding the named file now stays folded.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
18 files+297 added−100 removed
- tests:+99 added−11 removed
- other:+198 added−89 removed
Provenance
- Commit
4592d84- Tree
d7eaf97- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent
f63aa3b
18 files changed+297 added−100 removed
modified:apps/web/src/features/code/commit-view.tsx+8 added-3 removed
17 unmodified lines18 import type { ProjectName } from "@repo/protocol/ids";19 import { Option } from "effect";20 import type { DateTime } from "effect";21 import { Columns2, FoldVertical, Rows3, UnfoldVertical } from "lucide-react";22+import { useMemo } from "react";23 import type { ReactNode } from "react";24 25 import { Button } from "@/components/ui/button";26 6 unmodified lines33 import { GUTTER, MEASURE, Workspace } from "../shared/shell/workspace.tsx";34 import { When } from "../shared/time.tsx";35 import { askOf } from "../why/rows.ts";36 import { drawnFiles, statsOf } from "./diff-model.ts";36-import type { DiffStats } from "./diff-model.ts";37+import type { DiffStats, DrawnFile } from "./diff-model.ts";38 import { DiffPane, PANE_SCROLLER } from "./diff-pane.tsx";39 import { commitHref, shortSha, treeHref } from "./paths.ts";40 import { ChangeCounts, PlainDiff } from "./plain-diff.tsx";41 324 unmodified lines366 /** The browser's drawing of the diff, holding `PlainDiff` as its fallback. */367 readonly drawing?: ReactNode;368 /** The Files button, below the shell's width. */369 readonly files?: ReactNode;370+ /** The diff's files already parsed (`drawnFiles`), so a page parses each once. */371+ readonly drawn?: readonly DrawnFile[] | undefined;372 }373 374 export const CommitView = ({375 diff,376 drawing,377+ drawn: parsed,378 files: filesButton,379 folded,380 now,381 onFold,4 unmodified lines386 territory,387 }: CommitViewProps) => {388 const { commit, files, truncated } = diff;389 const body = bodyWithoutTrailers(commit);386- const drawn = drawnFiles(files);387- const stats = statsOf(drawn, territory);390+ const drawn = useMemo(() => parsed ?? drawnFiles(files), [files, parsed]);391+ const stats = useMemo(() => statsOf(drawn, territory), [drawn, territory]);392 393 const allFolded = drawn.every((file) =>394 folded === undefined ? file.folded : folded.has(file.file.path)395 );54 unmodified lines450 <DiffPane>451 {drawing ?? (452 <div className={PANE_SCROLLER}>453 <PlainDiff454+ drawn={drawn}455 files={files}456 folded={folded}457 onFold={onFold}458 split={split}7 unmodified linesmodified:apps/web/src/features/code/diff-view.tsx+12 added-3 removed
186 unmodified lines187 );188 189 const slotOf = (path: string) => slots.find((slot) => slot.path === path);190 191+ // The folds as they are now, read when the address moves: a fold the192+ // reader makes later must neither unfold the named file again nor193+ // scroll back to it.194+ const folds = useRef({ folded, onFold });195+196+ useEffect(() => {197+ folds.current = { folded, onFold };198+ });199+200 // An address naming a file scrolls to it, and its lines are selected.201 useEffect(() => {202 const named = parseDiffHash(hash);203 2 unmodified lines206 }207 208 const { lines, path } = named.value;209 201- if (folded?.has(path) === true) {202- onFold?.(path, false);210+ if (folds.current.folded?.has(path) === true) {211+ folds.current.onFold?.(path, false);212 }213 214 reveal(handle.current, container.current, path);215 13 unmodified lines229 side: lines.value.side,230 type: "line",231 });232 }224- }, [byPath, folded, hash, onFold]);233+ }, [byPath, hash]);234 235 const options = useMemo(236 (): CodeViewReactOptions<DiffAnnotation, undefined> => ({237 ...diffsOptions,118 unmodified linesmodified:apps/web/src/features/code/file-header.tsx+29 added-7 removed
16 unmodified lines17 18 import { buttonVariants } from "@/components/ui/button";19 20 import { useCopy } from "../shared/copy-action.tsx";21+import { useKeys } from "../shared/keys.tsx";22+import type { KeyPress } from "../shared/keys.tsx";23 import { AppLink } from "../shared/link.tsx";24 import { CopyButton } from "./copy.tsx";25 import {26 ancestorsOf,51 unmodified lines78 ...(file.binary ? ["binary"] : []),79 ...(languageOf(file.path) === undefined ? [] : [languageOf(file.path) ?? ""]),80 ];81 82+/**83+ * Whether `press` asks for the permalink: `y`, with no modifier, outside a84+ * field, and only while the single keys are on (the switch in the keys85+ * dialog turns this one off too).86+ */87+export const permalinkPress = (press: KeyPress, on: boolean) =>88+ on &&89+ press.key === "y" &&90+ !press.inField &&91+ !press.altKey &&92+ !press.ctrlKey &&93+ !press.metaKey;94+95 /** `y` rewrites the address to the page at its commit, keeping the line anchor. */96 export const PermalinkKey = ({ href }: { readonly href: string }) => {97+ const on = useKeys()?.on ?? true;98+99 useEffect(() => {100 const onKey = (event: KeyboardEvent) => {101 const [target] = event.composedPath();102 86- const typing =103+ const inField =104 target instanceof HTMLElement &&105 (target.isContentEditable ||106 target.closest("input, select, textarea, [role=combobox]") !== null);107 108 if (92- event.key === "y" &&93- !typing &&94- !event.metaKey &&95- !event.ctrlKey &&96- !event.altKey109+ permalinkPress(110+ {111+ altKey: event.altKey,112+ ctrlKey: event.ctrlKey,113+ inField,114+ key: event.key,115+ metaKey: event.metaKey,116+ },117+ on118+ )119 ) {120 globalThis.history.replaceState(121 globalThis.history.state,122 "",6 unmodified lines129 130 return () => {131 globalThis.removeEventListener("keydown", onKey);132 };111- }, [href]);133+ }, [href, on]);134 135 return null;136 };137 214 unmodified linesmodified:apps/web/src/features/code/log-view.tsx+4 added-2 removed
219 unmodified lines220 rev,221 show = "all",222 }: LogViewProps) => {223 const filter = path === undefined ? {} : { path };224+ // The pager keeps the kind the page shows.225+ const kind = show === "all" ? {} : { show };226 const shown = commits.filter((commit) => shows(show, commit));227 const base = commitsHref(project, rev, filter);228 const [to, query = ""] = base.split("?");229 58 unmodified lines288 )}289 <Pager290 newer={291 from > 0290- ? commitsHref(project, rev, newerPage(from, path))292+ ? commitsHref(project, rev, { ...newerPage(from, path), ...kind })293 : undefined294 }295 older={296 next === undefined297 ? undefined296- : commitsHref(project, rev, { ...filter, from: next })298+ : commitsHref(project, rev, { ...filter, ...kind, from: next })299 }300 />301 </Workspace>302 );1 unmodified linemodified:apps/web/src/features/code/not-found.tsx+10 added-1 removed
7 unmodified lines891011121314151630 unmodified lines4748495050515253545556575859606162636465666768694 unmodified lines7 unmodified lines * says why in a sentence. */import { Option, Schema } from "effect";import type { Array } from "effect";import type { ReactNode } from "react";
import { EmptyState } from "../shared/empty.tsx";import { AppLink } from "../shared/link.tsx";import { RefusalView } from "../shared/refusal.tsx";30 unmodified lines </p> </Workspace>);
export const CodeNotFound = ({ data }: { readonly data?: unknown }) =>export const CodeNotFound = ({ data, files,}: { readonly data?: unknown; /** The Files button, below the shell's width, on the folder a missing path lands on. */ readonly files?: ReactNode;}) => Option.match(decodeLanding(data), { onNone: () => ( <Refused refusals={Option.getOrUndefined(decodeRefusals(data))} /> ), onSome: (landing) => ( <TreeView files={files} listing={landing.nearest} notice={<RefusalView refusals={landing.refusals} />} now={landing.now} project={landing.project}4 unmodified linesmodified:apps/web/src/features/code/paths.ts+14 added-1 removed
36 unmodified lines373839404141424344454647484950515253543 unmodified lines58596061626364656667686950 unmodified lines36 unmodified lines/** The log from `rev`: only the commits that changed `path` when given, from the `from`th. */export const commitsHref = ( project: ProjectName, rev: string, { from, path }: { readonly from?: number; readonly path?: string } = {} { from, path, show, }: { readonly from?: number; readonly path?: string; /** Only the answers or the asks' openings; every commit when absent. */ readonly show?: "answers" | "openings"; } = {}) => { const query = new URLSearchParams();
if (path !== undefined) {3 unmodified lines if (from !== undefined && from > 0) { query.set("from", String(from)); }
if (show !== undefined) { query.set("show", show); }
const search = query.toString();
return `/${project}/commits/${revSegment(rev)}${search === "" ? "" : `?${search}`}`;};50 unmodified linesmodified:apps/web/src/features/code/plain-diff.tsx+40 added-32 removed
16 unmodified lines17 import type { ChangedFile } from "@repo/protocol/domain/code";18 import { Option } from "effect";19 import { ChevronDown, SquareDot, SquareMinus, SquarePlus } from "lucide-react";20 import type { LucideIcon } from "lucide-react";21+import { useMemo } from "react";22 import type { ReactNode } from "react";23 24 import { drawnFiles, splitRows, unifiedRows } from "./diff-model.ts";25 import type { DrawnFile, PlainRow, SplitRow } from "./diff-model.ts";242 unmodified lines268 /** The files folded now; each file's own default (`folded`) when absent. */269 readonly folded?: ReadonlySet<string> | undefined;270 /** A header's fold was pressed. */271 readonly onFold?: ((path: string, folded: boolean) => void) | undefined;272+ /** `files` already parsed (`drawnFiles`), so a page parses each once. */273+ readonly drawn?: readonly DrawnFile[] | undefined;274 }275 276 /**277 * The diff of `files`, plain, in the order a tree lists them. Server278 * markup: one `section[data-file]` per file, its header sticky at the top279 * of the pane that scrolls it.280 */281 export const PlainDiff = ({282+ drawn: parsed,283 files,284 folded,285 onFold,286 split = false,283-}: PlainDiffProps) => (284- <div className="text-mono leading-code font-mono" data-diff="plain">285- {drawnFiles(files).map((drawn) => {286- const { file } = drawn;287+}: PlainDiffProps) => {288+ const drawnList = useMemo(() => parsed ?? drawnFiles(files), [files, parsed]);289 288- const closed =289- folded === undefined ? drawn.folded : folded.has(file.path);290+ return (291+ <div className="text-mono leading-code font-mono" data-diff="plain">292+ {drawnList.map((drawn) => {293+ const { file } = drawn;294 291- return (292- <section293- aria-label={file.path}294- data-file={file.path}295- data-folded={closed}296- id={diffAnchor(file.path)}297- key={file.path}298- >299- <details300- className="group/file"301- onToggle={(event) => {302- onFold?.(file.path, !event.currentTarget.open);303- }}304- open={!closed}295+ const closed =296+ folded === undefined ? drawn.folded : folded.has(file.path);297+298+ return (299+ <section300+ aria-label={file.path}301+ data-file={file.path}302+ data-folded={closed}303+ id={diffAnchor(file.path)}304+ key={file.path}305 >306- <summary307- className="border-rule bg-background text-mono hover:bg-surface sticky top-0 z-[1] flex h-11 cursor-pointer list-none items-center gap-2 border-y px-4 font-sans [&::-webkit-details-marker]:hidden"308- data-diffs-header=""306+ <details307+ className="group/file"308+ onToggle={(event) => {309+ onFold?.(file.path, !event.currentTarget.open);310+ }}311+ open={!closed}312 >313+ <summary314+ className="border-rule bg-background text-mono hover:bg-surface sticky top-0 z-[1] flex h-11 cursor-pointer list-none items-center gap-2 border-y px-4 font-sans [&::-webkit-details-marker]:hidden"315+ data-diffs-header=""316+ >310- <FileHeaderLine file={drawn} />311- </summary>312- <FileBody file={drawn} split={split} />313- </details>314- </section>315- );316- })}317- </div>318-);317+ <FileHeaderLine file={drawn} />318+ </summary>319+ <FileBody file={drawn} split={split} />320+ </details>321+ </section>322+ );323+ })}324+ </div>325+ );326+};modified:apps/web/src/features/code/repo-tree.tsx+3 added-1 removed
61 unmodified lines62 /** A changed file's `+n −m`, each part in the diff's own tint. */63 const decorationOf = (counts: Counts): FileTreeRowDecoration => ({64 parts: [65 { color: "var(--diff-add-sign)", text: `+${counts.additions}` },66+ // A no-break space: the row lays its parts out as boxes, where a67+ // plain space between them collapses to nothing.66- { text: " " },68+ { text: "\u00A0" },69 { color: "var(--diff-del-sign)", text: `−${counts.deletions}` },70 ],71 text: `+${counts.additions} −${counts.deletions}`,72 title: `${counts.additions} added, ${counts.deletions} removed`,111 unmodified linesmodified:apps/web/src/routes/$project/blob/$rev/$.tsx+5 added-2 removed
148 unmodified lines149 }150 151 return page;152 },153- headers: ({ params }) => codePageHeaders(params.rev),153+ headers: ({ loaderData, params }) =>154+ codePageHeaders(params.rev, loaderData !== undefined),155 head: ({ params: { _splat, project, rev } }) =>156 pageHead({ title: `${_splat ?? project} at ${rev}` }),157 component: BlobPage,157- notFoundComponent: CodeNotFound,158+ notFoundComponent: ({ data }) => (159+ <CodeNotFound data={data} files={<FilesButton />} />160+ ),161 });modified:apps/web/src/routes/$project/commit/$sha.tsx+20 added-10 removed
13 unmodified lines14 import { CodeNotFound } from "../../../features/code/not-found.tsx";15 import { PlainDiff } from "../../../features/code/plain-diff.tsx";16 import { pageHead } from "../../../features/shared/head.ts";17 import { notFoundFor } from "../../../features/shared/refusals.ts";18-import { immutablePage } from "../../../server/cache-headers.ts";18 import { serverClient } from "../../../server/client.ts";19 import { CommitRail } from "../tree/-code-rail.tsx";20 import { CommitPageData } from "../tree/-commit-files.ts";21 import { FilesButton } from "../tree/-files-button.tsx";22+import { codePageHeaders } from "../tree/-headers.ts";23 24 // One commit and what it changed, read on the server, with the territory25 // of the ask it answered (the diff's stats split by it): the page arrives26 // with the landing and the diff as plain text, and the browser draws the27 // diff over it, the changed files as a tree in the rail. A commit never28-// changes, so neither does its page: it is kept for good, and the router29-// never reads it again.28+// changes, so neither does its page: it is kept for good (a 404 only29+// briefly), and the router never reads it again.30 31 interface CommitParams {32 readonly project: string;33 readonly sha: string;43 unmodified lines77 )78 );79 80 const CommitPage = () => {81- const { diff, now, project, territory } = Schema.decodeSync(CommitPageData)(82- Route.useLoaderData()81+ const loaded = Route.useLoaderData();82+83+ // Decoded once per read: the diff's files keep one identity while the84+ // reader folds, splits and moves, so nothing is parsed or drawn again.85+ const { diff, now, project, territory } = useMemo(86+ () => Schema.decodeSync(CommitPageData)(loaded),87+ [loaded]88 );89 90 const router = useRouter();91 const asked = Route.useSearch().style === "split";1 unmodified line93 const roomy = useMedia(SPLIT_QUERY);94 // Split only where the screen has room for two sides.95 const split = chosen && roomy;96 97+ // Each file parsed once for the page: the head's stats, the plain text98+ // and the folds all read this.99+ const drawn = useMemo(() => drawnFiles(diff.files), [diff.files]);100+101 const defaults = useMemo(102 () =>103 new Set(95- drawnFiles(diff.files)96- .filter(({ folded }) => folded)97- .map(({ file }) => file.path)104+ drawn.filter(({ folded }) => folded).map(({ file }) => file.path)105 ),99- [diff.files]106+ [drawn]107 );108 109 const [folded, setFolded] = useState<ReadonlySet<string>>(defaults);110 41 unmodified lines152 <ClientDiffs153 fallback={154 <div className={PANE_SCROLLER}>155 <PlainDiff156+ drawn={drawn}157 files={diff.files}158 folded={folded}159 onFold={onFold}160 split={split}6 unmodified lines167 split={split}168 />169 )170 }171+ drawn={drawn}172 files={<FilesButton commit />}173 folded={folded}174 now={now}175 onFold={onFold}15 unmodified lines191 }),192 loader: ({ params }) => commitPage({ data: params }),193 // A commit never changes: what was read stays fresh for good.194 staleTime: Number.POSITIVE_INFINITY,186- headers: () => immutablePage,195+ headers: ({ loaderData, params }) =>196+ codePageHeaders(params.sha, loaderData !== undefined),197 head: ({ params: { project, sha } }) =>198 pageHead({ title: `${project}: commit ${sha.slice(0, 7)}` }),199 component: CommitPage,200 notFoundComponent: CodeNotFound,1 unmodified linemodified:apps/web/src/routes/$project/commits/$rev.tsx+2 added-1 removed
114 unmodified lines115 show: SHOWS.find((each) => each === search.show),116 }),117 loaderDeps: ({ search }) => ({ from: search.from, path: search.path }),118 loader: ({ deps, params }) => logPage({ data: { ...params, ...deps } }),119- headers: ({ params }) => codePageHeaders(params.rev),119+ headers: ({ loaderData, params }) =>120+ codePageHeaders(params.rev, loaderData !== undefined),121 head: ({ params: { project, rev } }) =>122 pageHead({ title: `${project}: landings on ${rev}` }),123 component: LogPage,124 notFoundComponent: CodeNotFound,1 unmodified linemodified:apps/web/src/routes/$project/tree/$rev/$.tsx+5 added-2 removed
117 unmodified lines118 119 export const Route = createFileRoute("/$project/tree/$rev/$")({120 staticData: { rail: CodeRail },121 loader: ({ params }) => treePage({ data: params }),122- headers: ({ params }) => codePageHeaders(params.rev),122+ headers: ({ loaderData, params }) =>123+ codePageHeaders(params.rev, loaderData !== undefined),124 head: ({ params: { _splat, project, rev } }) =>125 pageHead({126 title: `${_splat === undefined || _splat === "" ? project : _splat} at ${rev}`,127 }),128 component: TreePage,128- notFoundComponent: CodeNotFound,129+ notFoundComponent: ({ data }) => (130+ <CodeNotFound data={data} files={<FilesButton />} />131+ ),132 });modified:apps/web/src/routes/$project/tree/-headers.ts+12 added-8 removed
1 /**2- * The `Cache-Control` a code page answers with, by what its address names:3- * a page at a whole commit id shows what can never change, so a browser4- * keeps it for good; a page at `main` or a tag moves with the next5- * landing, so it is kept briefly and read again behind it. Not a route:6- * the `-` prefix keeps the router from reading it as one.2+ * The `Cache-Control` a code page answers with, by what its address names3+ * and whether it found anything: a page at a whole commit id shows what4+ * can never change, so a browser keeps it for good; a page at `main` or a5+ * tag moves with the next landing, so it is kept briefly and read again6+ * behind it. A page that found nothing (no such project, commit or path:7+ * its loader read no data) is kept briefly too, even at a whole commit8+ * id: a landing or an import may bring what it named. Not a route: the9+ * `-` prefix keeps the router from reading it as one.10 */11 import { isCommitId } from "../../../features/code/headers.ts";12 import { branchPage, immutablePage } from "../../../server/cache-headers.ts";13 11-/** A code page's headers at `rev`. */14+/** A code page's headers at `rev`, given whether its loader found what it names. */15 export const codePageHeaders = (13- rev: string16+ rev: string,17+ found: boolean18 ): Readonly<Record<string, string>> =>15- isCommitId(rev) ? immutablePage : branchPage;19+ found && isCommitId(rev) ? immutablePage : branchPage;modified:apps/web/src/routes/$project/tree/-rail-body.tsx+27 added-12 removed
19 unmodified lines20 useRouter,21 } from "@tanstack/react-router";22 import { Option, Schema } from "effect";23 import { AsyncResult } from "effect/reactivity";24+import { useMemo } from "react";25 26 import { pathsAtom, refsAtom } from "../../../client/code.ts";27 import { ClientTree } from "../../../features/code/client-tree.tsx";28 import { drawnFiles, treeOrder } from "../../../features/code/diff-model.ts";22 unmodified lines51 select: (match) => match.loaderData,52 shouldThrow: false,53 });54 55+ // Decoded once per read, not on every move between files.56+ return useMemo(57+ () =>54- return Option.match(decode(data), {55- onNone: () => NONE,56- onSome: ({ diff }) => diff.files,57- });58+ Option.match(decode(data), {59+ onNone: () => NONE,60+ onSome: ({ diff }) => diff.files,61+ }),62+ [data]63+ );64 };65 66 /** Which page of a file the address is: its folder, its code, or why. */67 type Kind = "blob" | "tree" | "why";90 unmodified lines158 hrefFor(project, kind === "tree" ? "blob" : kind, rev, file)159 );160 };161 156- useCodeFileKeys((paths ?? []).toSorted(treeOrder), path, open);162+ const ordered = useMemo(() => (paths ?? []).toSorted(treeOrder), [paths]);163 164+ useCodeFileKeys(ordered, path, open);165+166 return shown && paths !== undefined ? (167 <ClientTree168 current={path}169 key={`${project}@${rev}`}44 unmodified lines214 const current = Option.getOrUndefined(215 Option.map(parseDiffHash(hash), ({ path }) => path)216 );217 210- const drawn = drawnFiles(files);211- const paths = drawn.map(({ file }) => file.path);218+ const drawn = useMemo(() => drawnFiles(files), [files]);219+ const paths = useMemo(() => drawn.map(({ file }) => file.path), [drawn]);220 221+ const counts = useMemo(222+ () => new Map(drawn.map(({ counts: each, file }) => [file.path, each])),223+ [drawn]224+ );225+226+ const status = useMemo(227+ () => drawn.map(({ file }) => ({ path: file.path, status: file.status })),228+ [drawn]229+ );230+231 const open = (path: string) => {232 const { pathname, searchStr } = router.state.location;233 234 router.history.replace(`${pathname}${searchStr}#${diffAnchor(path)}`);3 unmodified lines238 239 return always || wide ? (240 <div className="min-h-0 flex-1 pt-1">241 <ClientTree224- counts={new Map(drawn.map(({ counts, file }) => [file.path, counts]))}242+ counts={counts}243 current={current}244 key={paths.join("\n")}245 onOpen={open}246 open247 paths={paths}230- status={drawn.map(({ file }) => ({231- path: file.path,232- status: file.status,233- }))}248+ status={status}249 />250 </div>251 ) : null;252 };7 unmodified linesmodified:apps/web/src/routes/$project/tree/-soft-landing.ts+2 added-2 removed
1 /**2- * The soft landing for a missing path (GitLab's: the nearest folder, with3- * the refusal above it): when a code page's path is not at a revision2+ * The soft landing for a missing path (the nearest folder, with the3+ * refusal above it): when a code page's path is not at a revision4 * that exists, the folders above it are read, nearest first, and the5 * first that exists travels in the 404 with the platform's `UnknownPath`,6 * so the page shows that folder with the refusal's own words as its7 * notice. The root always exists where the revision does. Not a route:67 unmodified linesmodified:apps/web/src/routes/$project/why/$rev/$.tsx+5 added-2 removed
144 unmodified lines145 };146 147 export const Route = createFileRoute("/$project/why/$rev/$")({148 staticData: { rail: CodeRail },149- headers: ({ params }) => codePageHeaders(params.rev),149+ headers: ({ loaderData, params }) =>150+ codePageHeaders(params.rev, loaderData !== undefined),151 loader: ({ params }) => whyPage({ data: params }),152 head: ({ params: { _splat, project, rev } }) =>153 pageHead({ title: `Why ${_splat ?? project} at ${rev}` }),154 component: WhyPage,154- notFoundComponent: CodeNotFound,155+ notFoundComponent: ({ data }) => (156+ <CodeNotFound data={data} files={<FilesButton />} />157+ ),158 });modified:apps/web/test/code-diff.test.ts+24 added
18 unmodified lines19 statsOf,20 treeOrder,21 unifiedRows,22 } from "../src/features/code/diff-model.ts";23+import { permalinkPress } from "../src/features/code/file-header.tsx";24 import { stepFrom } from "../src/features/code/file-keys.ts";25 26 const decode = Schema.decodeSync(ChangedFile);27 177 unmodified lines205 expect(stepFrom(paths, undefined, -1)).toBe("c.ts");206 expect(stepFrom([], undefined, 1)).toBeUndefined();207 });208 });209+210+describe("the permalink key", () => {211+ const press = {212+ altKey: false,213+ ctrlKey: false,214+ inField: false,215+ key: "y",216+ metaKey: false,217+ };218+219+ it("takes y to the page at its commit while the single keys are on", () => {220+ expect(permalinkPress(press, true)).toBeTruthy();221+ });222+223+ it("does nothing once the single keys are switched off, in a field, or with a modifier", () => {224+ expect([225+ permalinkPress(press, false),226+ permalinkPress({ ...press, inField: true }, true),227+ permalinkPress({ ...press, ctrlKey: true }, true),228+ permalinkPress({ ...press, key: "Y" }, true),229+ ]).toStrictEqual([false, false, false, false]);230+ });231+});modified:apps/web/test/code.test.tsx+75 added-11 removed
50 unmodified lines51 import { RefsView, TAGS_PAGE } from "../src/features/code/refs-view.tsx";52 import { SoftLanding } from "../src/features/code/soft-landing.ts";53 import { TreeView } from "../src/features/code/tree-view.tsx";54 import { Refusals } from "../src/features/shared/refusals.ts";55+import {56+ readBlobPage,57+ Route as BlobRoute,55-import { readBlobPage } from "../src/routes/$project/blob/$rev/$.tsx";58+} from "../src/routes/$project/blob/$rev/$.tsx";59 import { readCommitPage } from "../src/routes/$project/commit/$sha.tsx";60 import { readLogPage } from "../src/routes/$project/commits/$rev.tsx";61 import { readRefsPage } from "../src/routes/$project/refs.tsx";62+import {63+ readTreePage,64+ Route as TreeRoute,59-import { readTreePage } from "../src/routes/$project/tree/$rev/$.tsx";65+} from "../src/routes/$project/tree/$rev/$.tsx";66 import { codePageHeaders } from "../src/routes/$project/tree/-headers.ts";67+import { Route as WhyRoute } from "../src/routes/$project/why/$rev/$.tsx";68 import { branchPage, immutablePage } from "../src/server/cache-headers.ts";69 import { reachingTransport } from "./transport.ts";70 71 const markupOf = (element: ReactElement) => renderToStaticMarkup(element);729 unmodified lines801 "/datekit/commits/main?path=src%2Fparse.ts&from=60",802 ]);803 });804 805+ it("keeps the filter on both pages: Older and Newer show the same kind", () => {806+ const pager = navOf(807+ markupOf(808+ <LogView809+ commits={commits}810+ from={30}811+ next={60}812+ now={now}813+ project={datekit}814+ rev="main"815+ show="answers"816+ />817+ ),818+ 'data-slot="pagination"'819+ );820+821+ expect(hrefsOf(pager)).toStrictEqual([822+ "/datekit/commits/main?show=answers",823+ "/datekit/commits/main?from=60&show=answers",824+ ]);825+ });826+827 it("goes back to a path's newest commits from a later page, since a path's `from` counts commits scanned, not shown", () => {828 // The platform scans 200 commits a call for a path, so the page that829 // starts at 230 may follow one that started at 30 or at 0: only the830 // first page is known to be newer.806 unmodified lines1637 markup.indexOf('data-entry="src/format/locale/en.ts"')1638 );1639 });1640 1641+ it("keeps the Files button on the folder it lands on, so a phone still reaches the tree", () => {1642+ const data = Schema.encodeSync(SoftLanding)({1643+ nearest: nested,1644+ now,1645+ project: datekit,1646+ refusals: [noPath(RepoPath.make("src/format/locale/gone/x.ts"))],1647+ rev: "main",1648+ });1649+1650+ const pages = [1651+ ["tree", TreeRoute],1652+ ["blob", BlobRoute],1653+ ["why", WhyRoute],1654+ ] as const;1655+1656+ const withoutFiles = pages.flatMap(([page, route]) => {1657+ const Landing = route.options.notFoundComponent;1658+1659+ return Landing !== undefined &&1660+ /aria-haspopup="dialog"[^>]*>[\s\S]*?Files<\/button>/u.test(1661+ markupOf(<Landing data={data} isNotFound routeId={route.id} />)1662+ )1663+ ? []1664+ : [page];1665+ });1666+1667+ expect(withoutFiles).toStrictEqual([]);1668+ });1669+1670 it("keeps any other refusal verbatim, with a way onward", () => {1671 const refusal = new UnknownRevision({ rev: "v9" });1672 1673 const element = (6 unmodified lines1680 });1681 1682 /** The line a code page's route answers its headers with. */1683 const headersLine = (path: string) =>1626- path.includes("/commit/")1627- ? "headers: () => immutablePage"1628- : "headers: ({ params }) => codePageHeaders(params.rev)";1684+ `headers: ({ loaderData, params }) => codePageHeaders(params.${1685+ path.includes("/commit/") ? "sha" : "rev"1686+ }, loaderData !== undefined)`;1687 1688 describe("a code page's caching", () => {1689 it("keeps a page at a whole commit id for good, and a page at main or a tag briefly", () => {1632- expect([AT, "main", TAG].map((rev) => codePageHeaders(rev))).toStrictEqual([1633- immutablePage,1634- branchPage,1635- branchPage,1636- ]);1690+ expect(1691+ [AT, "main", TAG].map((rev) => codePageHeaders(rev, true))1692+ ).toStrictEqual([immutablePage, branchPage, branchPage]);1693 });1694 1695+ it("keeps a page that found nothing only briefly, even at a whole commit id, since a later landing or import may fill it", () => {1696+ expect(1697+ [AT, "main"].map((rev) => codePageHeaders(rev, false))1698+ ).toStrictEqual([branchPage, branchPage]);1699+ });1700+1701 const routes: Readonly<Record<string, string>> = import.meta.glob(1702 "../src/routes/$project/{tree,blob,why}/$rev/$.tsx",1703 { eager: true, import: "default", query: "?raw" }1704 );8 unmodified lines1713 1714 expect(Object.keys(pages)).toHaveLength(5);1715 expect(1716 Object.entries(pages).flatMap(([path, source]) =>1655- source.includes(headersLine(path)) ? [] : [path]1717+ source.replaceAll(/\s+/gu, " ").includes(headersLine(path))1718+ ? []1719+ : [path]1720 )1721 ).toStrictEqual([]);1722 });1723 });12 unmodified lines