Skip to content
Myr

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.

authored by oscabriel · committed by oscabriel · parent f63aa3b · Browse files · 18 files+297 added−100 removed
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

18 files+297 added−100 removed

modified:apps/web/src/features/code/commit-view.tsx+8 added-3 removed
17 unmodified lines
18import type { ProjectName } from "@repo/protocol/ids";19import { Option } from "effect";20import type { DateTime } from "effect";21import { Columns2, FoldVertical, Rows3, UnfoldVertical } from "lucide-react";22import { useMemo } from "react";23import type { ReactNode } from "react";2425import { Button } from "@/components/ui/button";26
6 unmodified lines
33import { GUTTER, MEASURE, Workspace } from "../shared/shell/workspace.tsx";34import { When } from "../shared/time.tsx";35import { askOf } from "../why/rows.ts";36import { drawnFiles, statsOf } from "./diff-model.ts";36import type { DiffStats } from "./diff-model.ts";37import type { DiffStats, DrawnFile } from "./diff-model.ts";38import { DiffPane, PANE_SCROLLER } from "./diff-pane.tsx";39import { commitHref, shortSha, treeHref } from "./paths.ts";40import { ChangeCounts, PlainDiff } from "./plain-diff.tsx";41
324 unmodified lines
366 /** 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}373374export const CommitView = ({375 diff,376 drawing,377 drawn: parsed,378 files: filesButton,379 folded,380 now,381 onFold,
4 unmodified lines
386 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]);392393 const allFolded = drawn.every((file) =>394 folded === undefined ? file.folded : folded.has(file.file.path)395 );
54 unmodified lines
450 <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 lines
modified:apps/web/src/features/code/diff-view.tsx+12 added-3 removed
186 unmodified lines
187 );188189 const slotOf = (path: string) => slots.find((slot) => slot.path === path);190191 // 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 });195196 useEffect(() => {197 folds.current = { folded, onFold };198 });199200 // An address naming a file scrolls to it, and its lines are selected.201 useEffect(() => {202 const named = parseDiffHash(hash);203
2 unmodified lines
206 }207208 const { lines, path } = named.value;209201 if (folded?.has(path) === true) {202 onFold?.(path, false);210 if (folds.current.folded?.has(path) === true) {211 folds.current.onFold?.(path, false);212 }213214 reveal(handle.current, container.current, path);215
13 unmodified lines
229 side: lines.value.side,230 type: "line",231 });232 }224 }, [byPath, folded, hash, onFold]);233 }, [byPath, hash]);234235 const options = useMemo(236 (): CodeViewReactOptions<DiffAnnotation, undefined> => ({237 ...diffsOptions,
118 unmodified lines
modified:apps/web/src/features/code/file-header.tsx+29 added-7 removed
16 unmodified lines
1718import { buttonVariants } from "@/components/ui/button";1920import { useCopy } from "../shared/copy-action.tsx";21import { useKeys } from "../shared/keys.tsx";22import type { KeyPress } from "../shared/keys.tsx";23import { AppLink } from "../shared/link.tsx";24import { CopyButton } from "./copy.tsx";25import {26 ancestorsOf,
51 unmodified lines
78 ...(file.binary ? ["binary"] : []),79 ...(languageOf(file.path) === undefined ? [] : [languageOf(file.path) ?? ""]),80];8182/**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 */87export const permalinkPress = (press: KeyPress, on: boolean) =>88 on &&89 press.key === "y" &&90 !press.inField &&91 !press.altKey &&92 !press.ctrlKey &&93 !press.metaKey;9495/** `y` rewrites the address to the page at its commit, keeping the line anchor. */96export const PermalinkKey = ({ href }: { readonly href: string }) => {97 const on = useKeys()?.on ?? true;9899 useEffect(() => {100 const onKey = (event: KeyboardEvent) => {101 const [target] = event.composedPath();10286 const typing =103 const inField =104 target instanceof HTMLElement &&105 (target.isContentEditable ||106 target.closest("input, select, textarea, [role=combobox]") !== null);107108 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 lines
129130 return () => {131 globalThis.removeEventListener("keydown", onKey);132 };111 }, [href]);133 }, [href, on]);134135 return null;136};137
214 unmodified lines
modified:apps/web/src/features/code/log-view.tsx+4 added-2 removed
219 unmodified lines
220 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 lines
288 )}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 line
modified:apps/web/src/features/code/not-found.tsx+10 added-1 removed
modified:apps/web/src/features/code/paths.ts+14 added-1 removed
modified:apps/web/src/features/code/plain-diff.tsx+40 added-32 removed
16 unmodified lines
17import type { ChangedFile } from "@repo/protocol/domain/code";18import { Option } from "effect";19import { ChevronDown, SquareDot, SquareMinus, SquarePlus } from "lucide-react";20import type { LucideIcon } from "lucide-react";21import { useMemo } from "react";22import type { ReactNode } from "react";2324import { drawnFiles, splitRows, unifiedRows } from "./diff-model.ts";25import type { DrawnFile, PlainRow, SplitRow } from "./diff-model.ts";
242 unmodified lines
268 /** 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}275276/**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 */281export 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]);289288 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;294291 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);297298 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 lines
62/** A changed file's `+n −m`, each part in the diff's own tint. */63const 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 lines
modified:apps/web/src/routes/$project/blob/$rev/$.tsx+5 added-2 removed
148 unmodified lines
149 }150151 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 lines
14import { CodeNotFound } from "../../../features/code/not-found.tsx";15import { PlainDiff } from "../../../features/code/plain-diff.tsx";16import { pageHead } from "../../../features/shared/head.ts";17import { notFoundFor } from "../../../features/shared/refusals.ts";18import { immutablePage } from "../../../server/cache-headers.ts";18import { serverClient } from "../../../server/client.ts";19import { CommitRail } from "../tree/-code-rail.tsx";20import { CommitPageData } from "../tree/-commit-files.ts";21import { FilesButton } from "../tree/-files-button.tsx";22import { codePageHeaders } from "../tree/-headers.ts";2324// 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.3031interface CommitParams {32 readonly project: string;33 readonly sha: string;
43 unmodified lines
77 )78 );7980const CommitPage = () => {81 const { diff, now, project, territory } = Schema.decodeSync(CommitPageData)(82 Route.useLoaderData()81 const loaded = Route.useLoaderData();8283 // 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 );8990 const router = useRouter();91 const asked = Route.useSearch().style === "split";
1 unmodified line
93 const roomy = useMedia(SPLIT_QUERY);94 // Split only where the screen has room for two sides.95 const split = chosen && roomy;9697 // 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]);100101 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 );108109 const [folded, setFolded] = useState<ReadonlySet<string>>(defaults);110
41 unmodified lines
152 <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 lines
167 split={split}168 />169 )170 }171 drawn={drawn}172 files={<FilesButton commit />}173 folded={folded}174 now={now}175 onFold={onFold}
15 unmodified lines
191 }),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 line
modified:apps/web/src/routes/$project/commits/$rev.tsx+2 added-1 removed
114 unmodified lines
115 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 line
modified:apps/web/src/routes/$project/tree/$rev/$.tsx+5 added-2 removed
117 unmodified lines
118119export 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 */11import { isCommitId } from "../../../features/code/headers.ts";12import { branchPage, immutablePage } from "../../../server/cache-headers.ts";1311/** A code page's headers at `rev`. */14/** A code page's headers at `rev`, given whether its loader found what it names. */15export 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 lines
20 useRouter,21} from "@tanstack/react-router";22import { Option, Schema } from "effect";23import { AsyncResult } from "effect/reactivity";24import { useMemo } from "react";2526import { pathsAtom, refsAtom } from "../../../client/code.ts";27import { ClientTree } from "../../../features/code/client-tree.tsx";28import { drawnFiles, treeOrder } from "../../../features/code/diff-model.ts";
22 unmodified lines
51 select: (match) => match.loaderData,52 shouldThrow: false,53 });5455 // 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};6566/** Which page of a file the address is: its folder, its code, or why. */67type Kind = "blob" | "tree" | "why";
90 unmodified lines
158 hrefFor(project, kind === "tree" ? "blob" : kind, rev, file)159 );160 };161156 useCodeFileKeys((paths ?? []).toSorted(treeOrder), path, open);162 const ordered = useMemo(() => (paths ?? []).toSorted(treeOrder), [paths]);163164 useCodeFileKeys(ordered, path, open);165166 return shown && paths !== undefined ? (167 <ClientTree168 current={path}169 key={`${project}@${rev}`}
44 unmodified lines
214 const current = Option.getOrUndefined(215 Option.map(parseDiffHash(hash), ({ path }) => path)216 );217210 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]);220221 const counts = useMemo(222 () => new Map(drawn.map(({ counts: each, file }) => [file.path, each])),223 [drawn]224 );225226 const status = useMemo(227 () => drawn.map(({ file }) => ({ path: file.path, status: file.status })),228 [drawn]229 );230231 const open = (path: string) => {232 const { pathname, searchStr } = router.state.location;233234 router.history.replace(`${pathname}${searchStr}#${diffAnchor(path)}`);
3 unmodified lines
238239 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 lines
modified: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 lines
modified:apps/web/src/routes/$project/why/$rev/$.tsx+5 added-2 removed
144 unmodified lines
145};146147export 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 lines
19 statsOf,20 treeOrder,21 unifiedRows,22} from "../src/features/code/diff-model.ts";23import { permalinkPress } from "../src/features/code/file-header.tsx";24import { stepFrom } from "../src/features/code/file-keys.ts";2526const decode = Schema.decodeSync(ChangedFile);27
177 unmodified lines
205 expect(stepFrom(paths, undefined, -1)).toBe("c.ts");206 expect(stepFrom([], undefined, 1)).toBeUndefined();207 });208});209210describe("the permalink key", () => {211 const press = {212 altKey: false,213 ctrlKey: false,214 inField: false,215 key: "y",216 metaKey: false,217 };218219 it("takes y to the page at its commit while the single keys are on", () => {220 expect(permalinkPress(press, true)).toBeTruthy();221 });222223 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 lines
51import { RefsView, TAGS_PAGE } from "../src/features/code/refs-view.tsx";52import { SoftLanding } from "../src/features/code/soft-landing.ts";53import { TreeView } from "../src/features/code/tree-view.tsx";54import { Refusals } from "../src/features/shared/refusals.ts";55import {56 readBlobPage,57 Route as BlobRoute,55import { readBlobPage } from "../src/routes/$project/blob/$rev/$.tsx";58} from "../src/routes/$project/blob/$rev/$.tsx";59import { readCommitPage } from "../src/routes/$project/commit/$sha.tsx";60import { readLogPage } from "../src/routes/$project/commits/$rev.tsx";61import { readRefsPage } from "../src/routes/$project/refs.tsx";62import {63 readTreePage,64 Route as TreeRoute,59import { readTreePage } from "../src/routes/$project/tree/$rev/$.tsx";65} from "../src/routes/$project/tree/$rev/$.tsx";66import { codePageHeaders } from "../src/routes/$project/tree/-headers.ts";67import { Route as WhyRoute } from "../src/routes/$project/why/$rev/$.tsx";68import { branchPage, immutablePage } from "../src/server/cache-headers.ts";69import { reachingTransport } from "./transport.ts";7071const markupOf = (element: ReactElement) => renderToStaticMarkup(element);
729 unmodified lines
801 "/datekit/commits/main?path=src%2Fparse.ts&from=60",802 ]);803 });804805 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 );820821 expect(hrefsOf(pager)).toStrictEqual([822 "/datekit/commits/main?show=answers",823 "/datekit/commits/main?from=60&show=answers",824 ]);825 });826827 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 lines
1637 markup.indexOf('data-entry="src/format/locale/en.ts"')1638 );1639 });16401641 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 });16491650 const pages = [1651 ["tree", TreeRoute],1652 ["blob", BlobRoute],1653 ["why", WhyRoute],1654 ] as const;16551656 const withoutFiles = pages.flatMap(([page, route]) => {1657 const Landing = route.options.notFoundComponent;16581659 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 });16661667 expect(withoutFiles).toStrictEqual([]);1668 });16691670 it("keeps any other refusal verbatim, with a way onward", () => {1671 const refusal = new UnknownRevision({ rev: "v9" });16721673 const element = (
6 unmodified lines
1680});16811682/** The line a code page's route answers its headers with. */1683const 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)`;16871688describe("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 });16941695 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 });17001701 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 lines
17131714 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