app-shiki-diff-view.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import { RGBA, StyledText, type TextChunk } from "@mbears/opentui-core";
  2. import React from "react";
  3. import type { ToolResultDisplayHunk, ToolResultDisplayLine } from "./app-model.js";
  4. import {
  5. highlightShikiCodeLines,
  6. type ShikiHighlightSegment,
  7. } from "./app-shiki-highlighter.js";
  8. import { activeTuiTheme, type TuiThemeTokens } from "./theme/index.js";
  9. const SPLIT_DIFF_WIDTH_BREAKPOINT = 120;
  10. const LINE_NUMBER_WIDTH = 4;
  11. const GUTTER_TRAILING_SPACE = " ";
  12. const UNIFIED_EMPTY_MARKER = " ";
  13. const EMPTY_LINE_NUMBER = "";
  14. const SHIKI_FONT_STYLE_ITALIC = 1;
  15. const SHIKI_FONT_STYLE_BOLD = 2;
  16. const SHIKI_FONT_STYLE_UNDERLINE = 4;
  17. const SHIKI_FONT_STYLE_STRIKETHROUGH = 8;
  18. const OPENTUI_BOLD_ATTRIBUTE = 1;
  19. const OPENTUI_ITALIC_ATTRIBUTE = 4;
  20. const OPENTUI_UNDERLINE_ATTRIBUTE = 8;
  21. const OPENTUI_STRIKETHROUGH_ATTRIBUTE = 128;
  22. const rgbaCache = new Map<string, RGBA>();
  23. type DiffMarker = "+" | "-" | " ";
  24. type DiffTone = ToolResultDisplayLine["tone"];
  25. type ShikiDiffViewMode = "split" | "unified";
  26. type DiffDisplayRow = {
  27. content: string;
  28. id: string;
  29. marker: DiffMarker;
  30. newLine?: number;
  31. oldLine?: number;
  32. tone: DiffTone;
  33. };
  34. type SplitDiffRow = {
  35. id: string;
  36. left?: DiffDisplayRow;
  37. right?: DiffDisplayRow;
  38. };
  39. type HighlightState = {
  40. cacheKey: string;
  41. segmentsByRow: ShikiHighlightSegment[][];
  42. };
  43. export function ShikiDiffView(props: {
  44. filePath?: string;
  45. structuredPatch: ToolResultDisplayHunk[];
  46. terminalWidth: number;
  47. truncated?: boolean;
  48. view?: ShikiDiffViewMode;
  49. }): React.ReactElement {
  50. const theme = activeTuiTheme();
  51. const rows = React.useMemo(() => buildDiffRows(props.structuredPatch), [props.structuredPatch]);
  52. const cacheKey = React.useMemo(() => diffRowsCacheKey(rows), [rows]);
  53. const [highlightState, setHighlightState] = React.useState<HighlightState | undefined>();
  54. const view = props.view ?? diffViewForWidth(props.terminalWidth);
  55. React.useEffect(() => {
  56. let disposed = false;
  57. setHighlightState(undefined);
  58. void highlightShikiCodeLines({
  59. filePath: props.filePath,
  60. lines: rows.map((row) => row.content),
  61. mode: theme.mode,
  62. }).then((segmentsByRow) => {
  63. if (disposed || !segmentsByRow) return;
  64. setHighlightState({ cacheKey, segmentsByRow });
  65. });
  66. return () => {
  67. disposed = true;
  68. };
  69. }, [cacheKey, props.filePath, rows, theme.mode]);
  70. const segmentsByRow =
  71. highlightState?.cacheKey === cacheKey ? highlightState.segmentsByRow : undefined;
  72. return h(
  73. "box",
  74. {
  75. style: {
  76. flexDirection: "column",
  77. paddingLeft: 2,
  78. width: "100%",
  79. },
  80. },
  81. ...(view === "split"
  82. ? splitRowsToNodes(buildSplitDiffRows(rows), rows, segmentsByRow, theme)
  83. : unifiedRowsToNodes(rows, segmentsByRow, theme)),
  84. ...(props.truncated ? [truncatedNode(theme)] : []),
  85. );
  86. }
  87. export function diffViewForWidth(terminalWidth: number): ShikiDiffViewMode {
  88. return terminalWidth > SPLIT_DIFF_WIDTH_BREAKPOINT ? "split" : "unified";
  89. }
  90. export function buildDiffRows(hunks: ToolResultDisplayHunk[]): DiffDisplayRow[] {
  91. const rows: DiffDisplayRow[] = [];
  92. hunks.forEach((hunk, hunkIndex) => {
  93. let oldLine = hunk.oldStart;
  94. let newLine = hunk.newStart;
  95. hunk.lines.forEach((rawLine, lineIndex) => {
  96. const marker = diffMarker(rawLine);
  97. rows.push({
  98. content: diffContent(rawLine, marker),
  99. id: `${hunkIndex}:${lineIndex}`,
  100. marker,
  101. newLine: marker === "-" ? undefined : newLine,
  102. oldLine: marker === "+" ? undefined : oldLine,
  103. tone: toneForMarker(marker),
  104. });
  105. if (marker !== "+") oldLine += 1;
  106. if (marker !== "-") newLine += 1;
  107. });
  108. });
  109. return rows;
  110. }
  111. export function buildSplitDiffRows(rows: DiffDisplayRow[]): SplitDiffRow[] {
  112. const splitRows: SplitDiffRow[] = [];
  113. let index = 0;
  114. while (index < rows.length) {
  115. const current = rows[index];
  116. if (!current) break;
  117. if (current.marker === " ") {
  118. splitRows.push({ id: current.id, left: current, right: current });
  119. index += 1;
  120. continue;
  121. }
  122. const deleted: DiffDisplayRow[] = [];
  123. const added: DiffDisplayRow[] = [];
  124. while (index < rows.length && rows[index]?.marker !== " ") {
  125. const changed = rows[index];
  126. if (changed?.marker === "-") deleted.push(changed);
  127. if (changed?.marker === "+") added.push(changed);
  128. index += 1;
  129. }
  130. const pairCount = Math.max(deleted.length, added.length);
  131. for (let pairIndex = 0; pairIndex < pairCount; pairIndex += 1) {
  132. const left = deleted[pairIndex];
  133. const right = added[pairIndex];
  134. splitRows.push({
  135. id: `${left?.id ?? "empty"}:${right?.id ?? "empty"}`,
  136. left,
  137. right,
  138. });
  139. }
  140. }
  141. return splitRows;
  142. }
  143. function unifiedRowsToNodes(
  144. rows: DiffDisplayRow[],
  145. segmentsByRow: ShikiHighlightSegment[][] | undefined,
  146. theme: TuiThemeTokens,
  147. ): React.ReactElement[] {
  148. return rows.map((row, index) =>
  149. h("text", {
  150. content: rowToStyledText({
  151. row,
  152. segments: segmentsByRow?.[index],
  153. side: "unified",
  154. theme,
  155. }),
  156. key: `unified-${row.id}`,
  157. style: {
  158. bg: backgroundForTone(row.tone, theme),
  159. width: "100%",
  160. },
  161. wrapMode: "word",
  162. }),
  163. );
  164. }
  165. function splitRowsToNodes(
  166. rows: SplitDiffRow[],
  167. sourceRows: DiffDisplayRow[],
  168. segmentsByRow: ShikiHighlightSegment[][] | undefined,
  169. theme: TuiThemeTokens,
  170. ): React.ReactElement[] {
  171. const indexById = new Map<string, number>();
  172. for (const [index, row] of sourceRows.entries()) {
  173. indexById.set(row.id, index);
  174. }
  175. return rows.map((row) =>
  176. h(
  177. "box",
  178. {
  179. key: `split-${row.id}`,
  180. style: {
  181. flexDirection: "row",
  182. width: "100%",
  183. },
  184. },
  185. splitCellNode({
  186. key: `left-${row.id}`,
  187. row: row.left,
  188. segments: row.left ? segmentsByRow?.[indexById.get(row.left.id) ?? -1] : undefined,
  189. side: "left",
  190. theme,
  191. }),
  192. splitCellNode({
  193. key: `right-${row.id}`,
  194. row: row.right,
  195. segments: row.right ? segmentsByRow?.[indexById.get(row.right.id) ?? -1] : undefined,
  196. side: "right",
  197. theme,
  198. }),
  199. ),
  200. );
  201. }
  202. function splitCellNode(input: {
  203. key: string;
  204. row?: DiffDisplayRow;
  205. segments?: ShikiHighlightSegment[];
  206. side: "left" | "right";
  207. theme: TuiThemeTokens;
  208. }): React.ReactElement {
  209. const tone = input.row?.tone ?? "context";
  210. return h("text", {
  211. content: rowToStyledText({
  212. row: input.row,
  213. segments: input.segments,
  214. side: input.side,
  215. theme: input.theme,
  216. }),
  217. key: input.key,
  218. style: {
  219. bg: backgroundForTone(tone, input.theme),
  220. width: "50%",
  221. },
  222. truncate: true,
  223. wrapMode: "none",
  224. });
  225. }
  226. function rowToStyledText(input: {
  227. row?: DiffDisplayRow;
  228. segments?: ShikiHighlightSegment[];
  229. side: "left" | "right" | "unified";
  230. theme: TuiThemeTokens;
  231. }): StyledText {
  232. const tone = input.row?.tone ?? "context";
  233. const rowBackground = backgroundForTone(tone, input.theme);
  234. const gutterBackground = gutterBackgroundForTone(tone, input.theme);
  235. const fallbackText = input.row?.content ?? "";
  236. return new StyledText([
  237. styledChunk(gutterText(input.row, input.side), input.theme.diffLineNumber, gutterBackground),
  238. ...highlightChunks(input.segments, fallbackText, input.theme.text, rowBackground),
  239. ]);
  240. }
  241. function highlightChunks(
  242. segments: ShikiHighlightSegment[] | undefined,
  243. fallbackText: string,
  244. fallbackColor: string,
  245. background: string,
  246. ): TextChunk[] {
  247. if (!segments?.length) return [styledChunk(fallbackText, fallbackColor, background)];
  248. return segments.map((segment) =>
  249. styledChunk(
  250. segment.text,
  251. segment.color ?? fallbackColor,
  252. background,
  253. opentuiAttributesFromShiki(segment.fontStyle),
  254. ),
  255. );
  256. }
  257. function truncatedNode(theme: TuiThemeTokens): React.ReactElement {
  258. return h("text", {
  259. key: "diff-truncated",
  260. style: {
  261. fg: theme.diffLineNumber,
  262. width: "100%",
  263. },
  264. }, " ... diff truncated");
  265. }
  266. function gutterText(row: DiffDisplayRow | undefined, side: "left" | "right" | "unified"): string {
  267. if (!row) return `${EMPTY_LINE_NUMBER.padStart(LINE_NUMBER_WIDTH)} `;
  268. const lineNumber = side === "left" ? row.oldLine : side === "right" ? row.newLine : displayLine(row);
  269. const marker = side === "unified" ? row.marker : markerForSplitSide(row, side);
  270. return `${String(lineNumber ?? "").padStart(LINE_NUMBER_WIDTH)} ${marker}${GUTTER_TRAILING_SPACE}`;
  271. }
  272. function markerForSplitSide(row: DiffDisplayRow, side: "left" | "right"): string {
  273. if (row.marker === " ") return UNIFIED_EMPTY_MARKER;
  274. if (side === "left") return row.marker === "-" ? "-" : UNIFIED_EMPTY_MARKER;
  275. return row.marker === "+" ? "+" : UNIFIED_EMPTY_MARKER;
  276. }
  277. function displayLine(row: DiffDisplayRow): number | undefined {
  278. return row.marker === "+" ? row.newLine : row.oldLine;
  279. }
  280. function diffRowsCacheKey(rows: DiffDisplayRow[]): string {
  281. return rows.map((row) => `${row.id}\0${row.content}`).join("\n");
  282. }
  283. function diffMarker(rawLine: string): DiffMarker {
  284. if (rawLine.startsWith("+")) return "+";
  285. if (rawLine.startsWith("-")) return "-";
  286. return " ";
  287. }
  288. function diffContent(rawLine: string, marker: DiffMarker): string {
  289. if (marker === "+" || marker === "-") return rawLine.slice(1);
  290. return rawLine.startsWith(" ") ? rawLine.slice(1) : rawLine;
  291. }
  292. function toneForMarker(marker: DiffMarker): DiffTone {
  293. if (marker === "+") return "addition";
  294. if (marker === "-") return "deletion";
  295. return "context";
  296. }
  297. function backgroundForTone(tone: DiffTone, theme: TuiThemeTokens): string {
  298. if (tone === "addition") return theme.diffAddedBg;
  299. if (tone === "deletion") return theme.diffRemovedBg;
  300. return theme.diffContextBg;
  301. }
  302. function gutterBackgroundForTone(tone: DiffTone, theme: TuiThemeTokens): string {
  303. if (tone === "addition") return theme.diffAddedLineNumberBg;
  304. if (tone === "deletion") return theme.diffRemovedLineNumberBg;
  305. return theme.diffContextBg;
  306. }
  307. function styledChunk(text: string, fg: string, bg: string, attributes = 0): TextChunk {
  308. return {
  309. __isChunk: true,
  310. attributes,
  311. bg: rgba(bg),
  312. fg: rgba(fg),
  313. text,
  314. };
  315. }
  316. function rgba(color: string): RGBA {
  317. const cached = rgbaCache.get(color);
  318. if (cached) return cached;
  319. const parsed = RGBA.fromHex(color);
  320. rgbaCache.set(color, parsed);
  321. return parsed;
  322. }
  323. function opentuiAttributesFromShiki(fontStyle: number | undefined): number {
  324. if (!fontStyle) return 0;
  325. let attributes = 0;
  326. if ((fontStyle & SHIKI_FONT_STYLE_BOLD) !== 0) attributes |= OPENTUI_BOLD_ATTRIBUTE;
  327. if ((fontStyle & SHIKI_FONT_STYLE_ITALIC) !== 0) attributes |= OPENTUI_ITALIC_ATTRIBUTE;
  328. if ((fontStyle & SHIKI_FONT_STYLE_UNDERLINE) !== 0) attributes |= OPENTUI_UNDERLINE_ATTRIBUTE;
  329. if ((fontStyle & SHIKI_FONT_STYLE_STRIKETHROUGH) !== 0) {
  330. attributes |= OPENTUI_STRIKETHROUGH_ATTRIBUTE;
  331. }
  332. return attributes;
  333. }
  334. const h = React.createElement as (
  335. type: React.ElementType | string,
  336. props?: Record<string, unknown> | null,
  337. ...children: React.ReactNode[]
  338. ) => React.ReactElement;