204 lines · 11.5 KBRaw
| 1 | import { Badge, Button, Shimmer, cn } from "@refs/design-system"; |
| 2 | import { ChatCircleIcon, XIcon } from "@refs/design-system/icons"; |
| 3 | import { Fragment, memo, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react"; |
| 4 | import type { CodeToken } from "../highlight"; |
| 5 | import type { CardLine, CodeModel } from "./model"; |
| 6 | import { useFileHighlight, type FileSources } from "./sources"; |
| 7 | |
| 8 | const NAME = /(#?[A-Za-z_$][\w$]*)/; |
| 9 | |
| 10 | export interface CardProps { |
| 11 | readonly model: CodeModel; |
| 12 | readonly index: number; |
| 13 | readonly id: string; |
| 14 | /** The head line that leads to the next card, when the reader chose it. */ |
| 15 | readonly via: number | null; |
| 16 | readonly next: string | null; |
| 17 | readonly active: boolean; |
| 18 | readonly sources: FileSources; |
| 19 | readonly commit: string; |
| 20 | readonly fold: boolean; |
| 21 | readonly onFollow: (index: number, line: number, to: string) => void; |
| 22 | readonly onSelect: (index: number, locate: boolean) => void; |
| 23 | readonly onCaller: (index: number, caller: string) => void; |
| 24 | readonly onScroll: () => void; |
| 25 | readonly onClose: (index: number) => void; |
| 26 | readonly notes?: CardNotes; |
| 27 | } |
| 28 | |
| 29 | /** Review comments in cards: the threads under a head line, and the form to start one. */ |
| 30 | export interface CardNotes { |
| 31 | threadsAt(path: string, line: number): readonly ReactNode[]; |
| 32 | composer(path: string, line: number, close: () => void): ReactNode; |
| 33 | } |
| 34 | |
| 35 | /** One step of a trace: a declaration's code or a whole file, with each name it can follow as a link to the next step. */ |
| 36 | export const CodeCard = memo(function CodeCard({ model, index, id, via, next, active, sources, commit, fold, onFollow, onSelect, onCaller, onScroll, onClose, notes }: CardProps) { |
| 37 | const [composing, setComposing] = useState<number | null>(null); |
| 38 | useEffect(() => setComposing(null), [notes]); |
| 39 | const reviewable = notes && model.span(id) && model.change(model.span(id)!.file)?.status !== "deleted" && model.change(model.span(id)!.file) ? notes : undefined; |
| 40 | const symbol = model.span(id)!; |
| 41 | const source = sources.lines(symbol.file); |
| 42 | const request = sources.request; |
| 43 | useEffect(() => request([symbol.file]), [request, symbol.file]); |
| 44 | const tokens = useFileHighlight(commit, symbol.file, source); |
| 45 | const lines = useMemo(() => model.cardLines(id, source, fold), [model, id, source, fold]); |
| 46 | const follow = useMemo(() => model.followable(id), [model, id]); |
| 47 | const nextName = next ? model.symbol(next)?.name : undefined; |
| 48 | const lead = via ?? (nextName ? firstMention(lines, nextName) : null); |
| 49 | const body = useRef<HTMLDivElement>(null); |
| 50 | const diff = model.diff(id); |
| 51 | const status = model.status(id); |
| 52 | const callers = useMemo(() => model.callers(id).slice(0, 6), [model, id]); |
| 53 | |
| 54 | useLayoutEffect(() => { |
| 55 | const element = body.current; |
| 56 | if (!element) return; |
| 57 | const target = element.querySelector<HTMLElement>(lead !== null ? `[data-line="${lead}"]` : "[data-change]"); |
| 58 | if (target) element.scrollTop = Math.max(0, target.offsetTop - element.clientHeight * 0.35); |
| 59 | }, [lead, lines.length]); |
| 60 | |
| 61 | const path = symbol.file.split("/"); |
| 62 | const name = path.pop(); |
| 63 | return ( |
| 64 | <article data-card={index} aria-current={active ? "step" : undefined} className={cn("flex h-full min-w-0 flex-1 basis-0 flex-col overflow-hidden rounded-panel bg-panel shadow-card", active && "shadow-[0_0_0_1px_var(--line),0_0_0_4px_color-mix(in_oklab,var(--porcelain)_14%,transparent)]")} onClick={() => !active && onSelect(index, false)}> |
| 65 | <div className="flex h-10 shrink-0 items-center shadow-[inset_0_-1px_0_var(--hairline)]"> |
| 66 | <button type="button" className="flex h-full min-w-0 flex-1 cursor-pointer items-center gap-2 pl-3 text-left hover:bg-hover" onClick={(event) => (event.stopPropagation(), onSelect(index, true))} aria-label={`Step ${index + 1}: ${model.qualifiedName(id)}. Show it on the map.`}> |
| 67 | <span aria-hidden className={cn("grid size-5 shrink-0 place-items-center rounded-full text-xs font-semibold tabular-nums", active ? "shadow-[inset_0_0_0_3.5px_var(--porcelain)]" : "shadow-[inset_0_0_0_2px_var(--porcelain)]")}> |
| 68 | {index + 1} |
| 69 | </span> |
| 70 | <Badge>{model.kind(id)}</Badge> |
| 71 | <span className="shrink-0 font-mono text-compact font-medium text-ink">{model.qualifiedName(id)}</span> |
| 72 | <span className="min-w-0 truncate font-mono text-xs text-faint"> |
| 73 | {path.length ? `${path.join("/")}/` : ""} |
| 74 | {name} |
| 75 | </span> |
| 76 | <span className="ml-auto flex shrink-0 items-center gap-1.5"> |
| 77 | {status === "added" && <Badge>New</Badge>} |
| 78 | {status === "changed" && <Badge>Changed</Badge>} |
| 79 | {(diff.added > 0 || diff.removed > 0) && ( |
| 80 | <span className="font-mono text-xs tabular-nums"> |
| 81 | {diff.added > 0 && <span className="text-success">+{diff.added}</span>} {diff.removed > 0 && <span className="text-danger">−{diff.removed}</span>} |
| 82 | </span> |
| 83 | )} |
| 84 | </span> |
| 85 | </button> |
| 86 | <Button size="sm" variant="ghost" shape="square" className="hit-area mx-1.5" aria-label={`Close ${model.qualifiedName(id)}`} title="Close this card" icon={<XIcon />} onClick={(event) => (event.stopPropagation(), onClose(index))} /> |
| 87 | </div> |
| 88 | <div |
| 89 | ref={body} |
| 90 | className="code-view min-h-0 flex-1 overflow-auto py-2" |
| 91 | onScroll={onScroll} |
| 92 | onPointerOver={(event) => { |
| 93 | const to = (event.target as HTMLElement).closest<HTMLElement>(".code-map-ref")?.dataset.to; |
| 94 | const file = to && model.symbol(to)?.file; |
| 95 | if (file) sources.request([file]); |
| 96 | }} |
| 97 | > |
| 98 | {!source && !sources.failed(symbol.file) && ( |
| 99 | <div className="flex flex-col gap-2 px-4 py-2"> |
| 100 | {["w-3/4", "w-1/2", "w-5/6", "w-2/5", "w-2/3"].map((width) => ( |
| 101 | <Shimmer key={width} className={cn("h-3", width)} /> |
| 102 | ))} |
| 103 | </div> |
| 104 | )} |
| 105 | {sources.failed(symbol.file) && <p className="px-4 py-2 text-compact text-muted">This file could not be read. Open it from the Code tab.</p>} |
| 106 | {lines.map((line, row) => ( |
| 107 | <Fragment key={row}> |
| 108 | <Line line={line} tokens={line.kind === "line" ? tokens?.[line.number - 1] : undefined} follow={follow} lead={line.kind === "line" && line.number === lead} nextName={nextName} onFollow={(to) => line.kind === "line" && onFollow(index, line.number, to)} onComment={reviewable && line.kind === "line" ? () => setComposing(line.number) : undefined} /> |
| 109 | {reviewable && line.kind === "line" && <LineNotes notes={reviewable} path={symbol.file} line={line.number} composing={composing === line.number} onClose={() => setComposing(null)} />} |
| 110 | </Fragment> |
| 111 | ))} |
| 112 | </div> |
| 113 | {callers.length > 0 && ( |
| 114 | <div className="flex shrink-0 flex-wrap items-center gap-1.5 px-3 py-2 text-xs text-faint shadow-[inset_0_1px_0_var(--hairline)]"> |
| 115 | <span className="caption">Used by</span> |
| 116 | {callers.map((caller) => ( |
| 117 | <button key={caller} type="button" className="h-5 cursor-pointer rounded-chip bg-hover px-1.5 font-mono text-xs text-muted hover:bg-control-hover hover:text-ink" onClick={(event) => (event.stopPropagation(), onCaller(index, caller))} title={`Trace from ${model.qualifiedName(caller)} in ${model.symbol(caller)?.file}`}> |
| 118 | {callerLabel(model, caller, callers)} |
| 119 | </button> |
| 120 | ))} |
| 121 | </div> |
| 122 | )} |
| 123 | </article> |
| 124 | ); |
| 125 | }); |
| 126 | |
| 127 | function callerLabel(model: CodeModel, caller: string, all: readonly string[]): string { |
| 128 | const name = model.qualifiedName(caller); |
| 129 | if (all.filter((other) => model.qualifiedName(other) === name).length < 2) return name; |
| 130 | return `${name} · ${model.symbol(caller)?.file.split("/").pop()}`; |
| 131 | } |
| 132 | |
| 133 | function firstMention(lines: readonly CardLine[], name: string): number | null { |
| 134 | const pattern = new RegExp(`(^|[^\\w$#])${name.replace(/[$#]/g, "\\$&")}([^\\w$]|$)`); |
| 135 | const found = lines.slice(1).find((line) => line.kind === "line" && pattern.test(line.text)) ?? lines.find((line) => line.kind === "line" && pattern.test(line.text)); |
| 136 | return found && found.kind === "line" ? found.number : null; |
| 137 | } |
| 138 | |
| 139 | function LineNotes({ notes, path, line, composing, onClose }: { notes: CardNotes; path: string; line: number; composing: boolean; onClose: () => void }) { |
| 140 | const threads = notes.threadsAt(path, line); |
| 141 | if (!threads.length && !composing) return null; |
| 142 | return ( |
| 143 | <div className="sticky left-0 flex w-[min(100%,40rem)] flex-col gap-3 bg-raised px-3 py-3 font-sans whitespace-normal shadow-[inset_0_1px_0_var(--hairline),inset_0_-1px_0_var(--hairline)]"> |
| 144 | {threads} |
| 145 | {composing && notes.composer(path, line, onClose)} |
| 146 | </div> |
| 147 | ); |
| 148 | } |
| 149 | |
| 150 | interface LineProps { |
| 151 | readonly line: CardLine; |
| 152 | readonly tokens: readonly CodeToken[] | undefined; |
| 153 | readonly follow: ReadonlyMap<string, string>; |
| 154 | readonly lead: boolean; |
| 155 | readonly nextName: string | undefined; |
| 156 | readonly onFollow: (to: string) => void; |
| 157 | readonly onComment?: () => void; |
| 158 | } |
| 159 | |
| 160 | function Line({ line, tokens, follow, lead, nextName, onFollow, onComment }: LineProps) { |
| 161 | if (line.kind === "fold") { |
| 162 | return ( |
| 163 | <div className="caption flex h-7 items-center bg-sunken px-4 text-faint shadow-[inset_0_1px_0_var(--hairline),inset_0_-1px_0_var(--hairline)]"> |
| 164 | {line.count} unchanged {line.count === 1 ? "line" : "lines"} |
| 165 | </div> |
| 166 | ); |
| 167 | } |
| 168 | const removed = line.kind === "removed"; |
| 169 | const added = line.kind === "line" && line.added; |
| 170 | return ( |
| 171 | <div data-line={line.kind === "line" ? line.number : undefined} data-change={removed || added || undefined} className={cn("flex min-w-max", added && "bg-success-tint", removed && "bg-danger-tint", lead && "bg-hover shadow-[inset_2px_0_0_var(--porcelain)]")}> |
| 172 | {onComment && line.kind === "line" ? ( |
| 173 | <button type="button" className="line-number group/number relative shrink-0 cursor-pointer select-none hover:text-ink" title={`Comment on line ${line.number}`} aria-label={`Comment on line ${line.number}`} onClick={(event) => (event.stopPropagation(), onComment())}> |
| 174 | <ChatCircleIcon size={12} className="absolute top-1/2 left-1.5 hidden -translate-y-1/2 text-accent-text group-hover/number:block" aria-hidden /> |
| 175 | {line.number} |
| 176 | </button> |
| 177 | ) : ( |
| 178 | <span className="line-number shrink-0 select-none">{line.kind === "line" ? line.number : ""}</span> |
| 179 | )} |
| 180 | <span aria-hidden className={cn("w-4 shrink-0 select-none", added ? "text-success" : removed ? "text-danger" : "text-faint")}> |
| 181 | {added ? "+" : removed ? "−" : ""} |
| 182 | </span> |
| 183 | <span className={cn("line pl-0", removed && "line-through decoration-[color-mix(in_oklab,var(--danger)_55%,transparent)]")}>{removed ? line.text || " " : code(line.text, tokens, follow, lead ? nextName : undefined, onFollow)}</span> |
| 184 | </div> |
| 185 | ); |
| 186 | } |
| 187 | |
| 188 | /** A line's text in its token colours, with every name the card can follow made into a link. */ |
| 189 | function code(text: string, tokens: readonly CodeToken[] | undefined, follow: ReadonlyMap<string, string>, next: string | undefined, onFollow: (to: string) => void): ReactNode { |
| 190 | const runs = tokens ?? [{ text }]; |
| 191 | return runs.map((token, tokenIndex) => |
| 192 | token.text.split(NAME).map((part, partIndex) => { |
| 193 | const key = `${tokenIndex}:${partIndex}`; |
| 194 | const target = partIndex % 2 === 1 ? follow.get(part) : undefined; |
| 195 | const style = token.light || token.dark ? { ["--token-light" as string]: token.light, ["--token-dark" as string]: token.dark } : undefined; |
| 196 | if (!target) return part ? <span key={key} style={style}>{part}</span> : null; |
| 197 | return ( |
| 198 | <button key={key} type="button" style={style} data-next={part === next || undefined} data-to={target} className="code-map-ref" onClick={(event) => (event.stopPropagation(), onFollow(target))}> |
| 199 | {part} |
| 200 | </button> |
| 201 | ); |
| 202 | }), |
| 203 | ); |
| 204 | } |