file-header.tsx
This file
Path
apps/web/src/features/code/file-header.tsx
352 lines · 10.3 KiB · TypeScript
Last changed by
Fix the finish review's findings: drafted code draws, counts agree, commands hangoscabrielbefore adoptionf7f6e49
History of this fileTake it
Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 1–315why, one step back1/**2 * The code pages' file header: the toolbar that stays under the context3 * bar while the code scrolls. Left to right: the Files button (below the4 * shell's width, where the tree is not in a rail), the path as a trail of5 * links with a button that copies it, the file's size in words ("12 lines6 * · 493 bytes · TypeScript"), the Code | Why toggle (one page, two modes,7 * each its own address), then Raw, Permalink (`y`) and Copy.8 *9 * Also here: the `y` key, which rewrites the address to the page at its10 * commit, and the words a file's facts are said in.11 */12import type { FileView } from "@repo/protocol/domain/code";13import type { ProjectName } from "@repo/protocol/ids";14import { Check, Copy, Link2 } from "lucide-react";15import { Fragment, useEffect } from "react";16import type { ReactNode } from "react";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,27 blobHref,28 rawHref,29 sizeInWords,30 treeHref,31 whyHref,32} from "./paths.ts";3334/** A text's lines, without the empty one after its last newline. */35export const linesOf = (text: string): readonly string[] => {36 const lines = text.split("\n");3738 return lines.at(-1) === "" ? lines.slice(0, -1) : lines;39};4041/** The language a file is written in, by its name; none for one this list does not know. */42const LANGUAGES: readonly (readonly [RegExp, string])[] = [43 [/\.(?:c|m)?tsx?$/u, "TypeScript"],44 [/\.(?:c|m)?jsx?$/u, "JavaScript"],45 [/\.json$/u, "JSON"],46 [/\.(?:md|markdown|mdown)$/u, "Markdown"],47 [/\.ya?ml$/u, "YAML"],48 [/\.toml$/u, "TOML"],49 [/\.css$/u, "CSS"],50 [/\.html?$/u, "HTML"],51 [/\.rs$/u, "Rust"],52 [/\.go$/u, "Go"],53 [/\.py$/u, "Python"],54 [/\.(?:sh|bash|zsh)$/u, "Shell"],55 [/(?:^|\/)Dockerfile$/u, "Dockerfile"],56 [/\.sql$/u, "SQL"],57 [/\.rb$/u, "Ruby"],58 [/\.java$/u, "Java"],59 [/\.kt$/u, "Kotlin"],60 [/\.swift$/u, "Swift"],61 [/\.c$|\.h$/u, "C"],62 [/\.(?:cc|cpp|hpp)$/u, "C++"],63];6465export const languageOf = (path: string) =>66 LANGUAGES.find(([pattern]) => pattern.test(path))?.[1];6768/** A file in words: its lines, its size, its language. */69export const fileWords = (file: FileView): readonly string[] => [70 ...(file.text === undefined71 ? []72 : [73 `${linesOf(file.text).length.toLocaleString("en")} ${74 linesOf(file.text).length === 1 ? "line" : "lines"75 }`,76 ]),77 sizeInWords(file.size),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();102103 const inField =104 target instanceof HTMLElement &&105 (target.isContentEditable ||106 target.closest("input, select, textarea, [role=combobox]") !== null);107108 if (109 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 "",123 `${href}${globalThis.location.search}${globalThis.location.hash}`124 );125 }126 };127128 globalThis.addEventListener("keydown", onKey);129130 return () => {131 globalThis.removeEventListener("keydown", onKey);132 };133 }, [href, on]);134135 return null;136};137138const CRUMB =139 "text-muted-foreground hover:text-foreground min-w-0 truncate no-underline transition-colors duration-[120ms]";140141/** A button that copies `text` with only its mark showing; its name says what it copies. */142const CopyMark = ({143 label,144 text,145}: {146 readonly label: string;147 readonly text: string;148}) => {149 const { copied, copy } = useCopy(text);150151 return (152 <button153 aria-label={154 copied ? `Copied ${label.toLowerCase().replace(/^copy /u, "")}` : label155 }156 className="text-muted-foreground hover:text-foreground hover:bg-surface flex size-7 shrink-0 cursor-pointer items-center justify-center"157 onClick={copy}158 title={label}159 type="button"160 >161 {copied ? (162 <Check aria-hidden="true" className="size-3.5" strokeWidth={1.75} />163 ) : (164 <Copy aria-hidden="true" className="size-3.5" strokeWidth={1.75} />165 )}166 </button>167 );168};169170/** The path as links: the project, each folder at `rev`, then the name itself. */171export const PathTrail = ({172 path,173 project,174 rev,175}: {176 readonly path: string | undefined;177 readonly project: ProjectName;178 readonly rev: string;179}) => {180 const here = path === undefined || path === "" ? undefined : path;181 const name = here?.split("/").at(-1);182183 return (184 <nav185 aria-label="Path"186 className="flex min-w-0 items-center gap-1"187 data-slot="breadcrumb"188 >189 <ol className="text-mono flex min-w-0 items-center gap-1 font-mono">190 {/* On a phone the toolbar has room for the name alone: the folders191 above it are the Files sheet's. */}192 <li193 className={`${here === undefined ? "flex" : "tablet:flex hidden"} min-w-0 shrink-0 items-center`}194 >195 {here === undefined ? (196 <span aria-current="page" className="text-foreground font-medium">197 {project}198 </span>199 ) : (200 <AppLink className={CRUMB} to={treeHref(project, rev)}>201 {project}202 </AppLink>203 )}204 </li>205 {here === undefined206 ? null207 : ancestorsOf(here).map((folder) => (208 <Fragment key={folder}>209 <li210 aria-hidden="true"211 className="text-muted-foreground tablet:block hidden"212 >213 /214 </li>215 <li className="tablet:flex hidden min-w-0 items-center">216 <AppLink217 className={CRUMB}218 to={treeHref(project, rev, folder)}219 >220 {folder.split("/").at(-1)}221 </AppLink>222 </li>223 </Fragment>224 ))}225 {name === undefined ? null : (226 <>227 <li228 aria-hidden="true"229 className="text-muted-foreground tablet:block hidden"230 >231 /232 </li>233 <li className="flex min-w-0 items-center">234 <span235 aria-current="page"236 className="text-foreground min-w-0 truncate font-medium"237 title={here}238 >239 {name}240 </span>241 </li>242 </>243 )}244 </ol>245 {here === undefined ? null : <CopyMark label="Copy path" text={here} />}246 </nav>247 );248};249250const SEGMENT =251 "text-ui hover:bg-surface aria-[current]:bg-foreground aria-[current]:text-background aria-[current]:hover:bg-foreground flex h-7 items-center px-2.5 font-medium no-underline transition-colors duration-150";252253/** Code | Why: the file, or why each of its lines is there; one page, two addresses. */254export const ModeToggle = ({255 mode,256 path,257 project,258 rev,259}: {260 readonly mode: "code" | "why";261 readonly path: string;262 readonly project: ProjectName;263 readonly rev: string;264}) => (265 <nav aria-label="Mode" className="border-input flex shrink-0 border">266 <AppLink267 aria-current={mode === "code" ? "page" : undefined}268 className={SEGMENT}269 to={blobHref(project, rev, path)}270 >271 Code272 </AppLink>273 <AppLink274 aria-current={mode === "why" ? "page" : undefined}275 className={SEGMENT}276 to={whyHref(project, rev, path)}277 >278 Why279 </AppLink>280 </nav>281);282283const TOOL = buttonVariants({284 className: "no-underline",285 size: "sm",286 variant: "ghost",287});288289/** The file header, as the page's toolbar. */290export const FileHeader = ({291 file,292 files,293 mode,294 path,295 project,296 rev,297}: {298 readonly project: ProjectName;299 readonly rev: string;300 /** The folder or file the page is about; the root when absent. */301 readonly path?: string | undefined;302 /** Code or Why, on a file's page; nothing on a folder's. */303 readonly mode?: "code" | "why";304 /** The file, read: its size in words, its bytes and its text to copy. */305 readonly file?: FileView;306 /** The Files button, below the shell's width. */307 readonly files?: ReactNode;308}) => (309 <>310 {files === undefined ? null : (311 <div className="shell:hidden flex shrink-0">{files}</div>312 )}313 <div className="flex min-w-0 flex-1 items-center gap-3">314 <PathTrail path={path} project={project} rev={rev} />315 {file === undefined ? null : (Fix the finish review's findings: drafted code draws, counts agree, commands hangoscabrielbefore adoptionf7f6e49
lines 316–317why, one step back316 // From 1440 px the inspector says the same, beside the path.317 <p className="text-ui text-muted-foreground diffsplit:block codefacts:hidden hidden min-w-0 truncate tabular-nums">Merge build/1211-code-browseroscabrielbefore adoptiona6808d3
lines 318–352why, one step back318 {fileWords(file).join(" · ")}319 </p>320 )}321 </div>322 {mode === undefined || path === undefined ? null : (323 <ModeToggle mode={mode} path={path} project={project} rev={rev} />324 )}325 {file === undefined ? null : (326 <nav327 aria-label="File"328 className="shell:flex hidden shrink-0 items-center gap-0.5"329 data-toolbar="file"330 >331 <a className={TOOL} href={rawHref(project, file.at, file.path)}>332 Raw333 </a>334 <AppLink335 className={TOOL}336 title="Permalink (y)"337 to={(mode === "why" ? whyHref : blobHref)(338 project,339 file.at,340 file.path341 )}342 >343 <Link2 aria-hidden="true" strokeWidth={1.75} />344 Permalink345 </AppLink>346 {file.text === undefined ? null : (347 <CopyButton label="Copy" text={file.text} />348 )}349 </nav>350 )}351 </>352);