code-view.tsx
This file
Path
apps/web/src/features/code/code-view.tsx
136 lines · 4.1 KiB · TypeScript
Last changed by
Draw text, controls, prose and code from one set of tokensoscabrielbefore adoption60f862e
History of this fileTake it
Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
lines 1–21why, one step back1/**2 * One file, drawn by `@pierre/diffs`: highlighted (Shiki's JavaScript3 * engine, never its WASM one), its lines selectable, the selection kept in4 * the address as `#L10` or `#L10-L20` (`line-hash.ts`) and scrolled to on5 * load. Its lines live in a shadow root, where a native `#L` fragment6 * cannot reach, so the drawing scrolls to the anchored line itself.7 *8 * It is Pierre's `File`, not its virtualized `CodeView`, which draws9 * nothing until it mounts; a file is capped at 1 MiB, and past10 * `HIGHLIGHT_LIMIT` characters it is drawn without highlighting.11 *12 * The library and Shiki's grammars are megabytes, so only the browser13 * loads this module (`client-code.tsx`); the Worker never bundles it.14 */15import { File } from "@pierre/diffs/react";16import type { FileOptions, SelectedLineRange } from "@pierre/diffs/react";17import { Option } from "effect";18import { useEffect, useMemo, useRef, useState } from "react";1920import { lineHash, parseLineHash } from "./line-hash.ts";21import type { LineRange } from "./line-hash.ts";Draw text, controls, prose and code from one set of tokensoscabrielbefore adoption60f862e
line 22why, one step back22import { diffsOptions, registerCodeTheme } from "./pierre.ts";Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
line 23why, one step back23Draw text, controls, prose and code from one set of tokensoscabrielbefore adoption60f862e
lines 24–25why, one step back24registerCodeTheme();25Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
lines 26–96why, one step back26/** Past this many characters a file is drawn without highlighting. */27const HIGHLIGHT_LIMIT = 300_000;2829export interface FileCodeProps {30 readonly path: string;31 /** The blob's id: the drawing's cache key. */32 readonly sha: string;33 readonly text: string;34}3536/** The lines the address names now, if any. */37const fromAddress = (): LineRange | null =>38 Option.getOrNull(parseLineHash(globalThis.location.hash));3940/** The drawing once it has rendered, and the line to bring into view in it. */41interface Pending {42 line?: number | undefined;43 node?: HTMLElement;44}4546/**47 * Scrolls the drawing to the pending line, once: the line clears when it48 * is found, so later renders leave the reader where they are.49 */50const reveal = (pending: Pending) => {51 const { line, node } = pending;5253 const row =54 line === undefined55 ? null56 : node?.shadowRoot?.querySelector(`[data-line="${line}"]`);5758 if (row !== null && row !== undefined) {59 // The page scrolls, not the drawing, and only up or down:60 // `scrollIntoView` would also slide a wide line sideways under the61 // line numbers.62 globalThis.scrollBy({63 top: row.getBoundingClientRect().top - globalThis.innerHeight / 2,64 });65 pending.line = undefined;66 }67};6869export const FileCode = ({ path, sha, text }: FileCodeProps) => {70 const [selected, setSelected] = useState<LineRange | null>(null);71 const pending = useRef<Pending>({});7273 useEffect(() => {74 const read = () => {75 const range = fromAddress();7677 setSelected(range);78 pending.current.line = range?.start;79 reveal(pending.current);80 };8182 read();83 globalThis.addEventListener("hashchange", read);8485 return () => {86 globalThis.removeEventListener("hashchange", read);87 };88 }, []);8990 const file = useMemo(91 () => ({ cacheKey: sha, contents: text, name: path }),92 [path, sha, text]93 );9495 const options = useMemo(96 (): FileOptions<undefined, undefined> => ({Draw text, controls, prose and code from one set of tokensoscabrielbefore adoption60f862e
line 97why, one step back97 ...diffsOptions,Merge branch 'build/904-web-code-browser'oscabrielbefore adoption06e2229
lines 98–136why, one step back98 enableLineSelection: true,99 lineHoverHighlight: "number",100 onLineSelected: (range: SelectedLineRange | null) => {101 const lines =102 range === null103 ? null104 : {105 end: Math.max(range.start, range.end),106 start: Math.min(range.start, range.end),107 };108109 setSelected(lines);110 globalThis.history.replaceState(111 globalThis.history.state,112 "",113 lines === null114 ? `${globalThis.location.pathname}${globalThis.location.search}`115 : lineHash(lines)116 );117 },118 onPostRender: (node: HTMLElement) => {119 pending.current.node = node;120 reveal(pending.current);121 },122 overflow: "scroll",123 tokenizeMaxLength: HIGHLIGHT_LIMIT,124 }),125 []126 );127128 return (129 <div className="border-rule min-w-0 border" data-code="pierre">130 <File file={file} options={options} selectedLines={selected} />131 </div>132 );133};134135// `React.lazy` takes a module's default export.136export default FileCode;