From 6201b7cf7da0a2e1c6b5d76948b5e94481d44aba Mon Sep 17 00:00:00 2001 From: wsp Date: Thu, 29 Oct 2026 10:50:55 +0800 Subject: [PATCH] fix(flow-chat): align virtualized code highlights Measure native line boxes in pixels and invalidate virtualizer estimates so highlighted rows stay aligned with the source text.\n\nKeep the native text node available for selection while rendering one visible decoration layer, and exclude the split item introduced by a trailing newline. Add regression coverage for unitless line heights, selection rendering, and trailing-newline line counts. --- .../components/WindowedCodeContent.test.tsx | 18 ++- .../components/WindowedCodeContent.tsx | 103 ++++++++++++++---- 2 files changed, 101 insertions(+), 20 deletions(-) diff --git a/src/web-ui/src/flow_chat/components/WindowedCodeContent.test.tsx b/src/web-ui/src/flow_chat/components/WindowedCodeContent.test.tsx index 686fc3803c..6d10350100 100644 --- a/src/web-ui/src/flow_chat/components/WindowedCodeContent.test.tsx +++ b/src/web-ui/src/flow_chat/components/WindowedCodeContent.test.tsx @@ -2,7 +2,7 @@ import React, { act } from 'react'; import { createRoot } from 'react-dom/client'; import { expect, it, vi } from 'vitest'; -import { WindowedCodeContent } from './WindowedCodeContent'; +import { getVisibleCodeLineCount, readLineHeight, WindowedCodeContent } from './WindowedCodeContent'; const highlights = vi.hoisted(() => ({ ready: false })); vi.mock('../timeline/highlightResources', () => ({ useHighlightedLines: (content: string) => content.split('\n').map(line => @@ -31,7 +31,23 @@ it('keeps complete native text and a live range while token decorations change', expect(source.firstChild).toBe(text); expect(selection.toString()).toBe(content); expect(host.querySelector('.code-preview__decorations')?.getAttribute('aria-hidden')).toBe('true'); + expect((host.querySelector('.code-preview__decorations') as HTMLElement).style.opacity).not.toBe('0'); } finally { window.getSelection()?.removeAllRanges(); act(() => root.unmount()); host.remove(); vi.unstubAllGlobals(); } }); + +it('converts unitless line-height tokens to pixel virtualizer offsets', () => { + vi.stubGlobal('getComputedStyle', () => ({ lineHeight: '1.5', fontSize: '16px' })); + try { + expect(readLineHeight(document.createElement('code'))).toBe(24); + } finally { + vi.unstubAllGlobals(); + } +}); + +it('does not virtualize the split item after a trailing newline', () => { + expect(getVisibleCodeLineCount(3, true)).toBe(2); + expect(getVisibleCodeLineCount(2, false)).toBe(2); + expect(getVisibleCodeLineCount(1, false)).toBe(1); +}); diff --git a/src/web-ui/src/flow_chat/components/WindowedCodeContent.tsx b/src/web-ui/src/flow_chat/components/WindowedCodeContent.tsx index dae2363b62..2f8fe045e0 100644 --- a/src/web-ui/src/flow_chat/components/WindowedCodeContent.tsx +++ b/src/web-ui/src/flow_chat/components/WindowedCodeContent.tsx @@ -1,4 +1,4 @@ -import React, { useEffect, useLayoutEffect, useMemo, useRef, useState, type RefObject } from 'react'; +import React, { useLayoutEffect, useMemo, useRef, useState, type RefObject } from 'react'; import { useVirtualizer } from '@tanstack/react-virtual'; import { useHighlightedLines } from '../timeline/highlightResources'; import { getInlineDiffTokenStyle } from './inlineDiffPrismTheme'; @@ -11,6 +11,59 @@ function tokenNode(token: PrismToken, key: number): React.ReactNode { : typeof token.content === 'string' ? token.content : tokenNode(token.content, 0)}; } +/** + * Resolve the source line box to pixels before feeding it to the virtualizer. + * + * `line-height` is a unitless design token (`1.52` in the code role). The + * computed style keeps that value unitless, while the virtualizer's offsets + * are pixels. Treating the result of `parseFloat` as pixels makes every later + * decoration row drift farther from the native text row. + */ +export function readLineHeight(source: HTMLElement): number | null { + const computed = getComputedStyle(source); + const rawLineHeight = computed.lineHeight.trim(); + const value = Number.parseFloat(rawLineHeight); + if (!Number.isFinite(value) || value <= 0) return null; + + if (rawLineHeight.endsWith('px')) return value; + + const fontSize = Number.parseFloat(computed.fontSize); + return Number.isFinite(fontSize) && fontSize > 0 ? value * fontSize : null; +} + +export function getVisibleCodeLineCount(splitLineCount: number, hasTrailingNewline: boolean): number { + return Math.max(1, splitLineCount - (hasTrailingNewline ? 1 : 0)); +} + +function readNativeLineRect(source: HTMLElement, lineIndex: number): { top: number; height: number } | null { + const text = source.firstChild; + if (!text || text.nodeType !== Node.TEXT_NODE) return null; + const value = text.textContent ?? ''; + let start = 0; + for (let index = 0; index < lineIndex; index += 1) { + const newline = value.indexOf('\n', start); + if (newline < 0) return null; + start = newline + 1; + } + const newline = value.indexOf('\n', start); + const end = newline < 0 ? value.length : newline; + const range = document.createRange(); + range.setStart(text, Math.min(start, value.length)); + range.setEnd(text, Math.min(Math.max(start + (end - start), start + 1), value.length)); + const rect = typeof range.getClientRects === 'function' ? range.getClientRects()[0] : null; + return rect ? { top: rect.top, height: rect.height } : null; +} + +function readActualLineHeight(source: HTMLElement, lineCount: number): number | null { + if (lineCount < 2) return null; + const sampleLine = Math.min(lineCount - 1, 32); + const first = readNativeLineRect(source, 0); + const sample = readNativeLineRect(source, sampleLine); + if (!first || !sample || sample.top <= first.top) return null; + const lineHeight = (sample.top - first.top) / sampleLine; + return Number.isFinite(lineHeight) && lineHeight > 0 ? lineHeight : null; +} + /** Keep one native text node for selection/copy/accessibility. Only the expensive * syntax-token and line-number decorations are virtualized in the existing pane. */ export function WindowedCodeContent({ content, language, scrollerRef, startingLineNumber, showLineNumbers, highlightedLine, onLineClick }: { @@ -19,43 +72,55 @@ export function WindowedCodeContent({ content, language, scrollerRef, startingLi onLineClick: (line: number) => void; }) { const lines = useHighlightedLines(content, language); - const plain = useMemo(() => content.split('\n'), [content]); + const { plain, visibleLineCount } = useMemo(() => { + const plain = content.split('\n'); + return { + plain, + visibleLineCount: getVisibleCodeLineCount(plain.length, content.endsWith('\n')), + }; + }, [content]); const [lineHeight, setLineHeight] = useState(22); const rootRef = useRef(null); const sourceRef = useRef(null); - const [selected, setSelected] = useState(false); - const virtualizer = useVirtualizer({ count: plain.length, getScrollElement: () => scrollerRef.current, + const virtualizer = useVirtualizer({ count: visibleLineCount, getScrollElement: () => scrollerRef.current, estimateSize: () => lineHeight, overscan: 5 }); - useEffect(() => { - const update = () => { - const selection = window.getSelection(); - setSelected(Boolean(sourceRef.current && selection?.rangeCount && !selection.isCollapsed - && selection.getRangeAt(0).intersectsNode(sourceRef.current))); - }; - document.addEventListener('selectionchange', update); - return () => document.removeEventListener('selectionchange', update); - }, []); useLayoutEffect(() => { const source = sourceRef.current; if (!source) return; const measure = () => { - const next = Number.parseFloat(getComputedStyle(source).lineHeight); - if (Number.isFinite(next) && next > 0) setLineHeight(next); + const cssLineHeight = readLineHeight(source); + const actualLineHeight = readActualLineHeight(source, visibleLineCount); + const next = actualLineHeight ?? cssLineHeight; + if (next !== null) setLineHeight(next); }; const observer = new ResizeObserver(measure); observer.observe(source); measure(); return () => observer.disconnect(); - }, [scrollerRef]); + }, [content.length, visibleLineCount, scrollerRef]); + + // The first virtualizer pass uses the fallback 22px estimate. Once the + // source line box is measured, invalidate TanStack Virtualizer's cached + // estimates so every row is projected with the resolved line height. + const previousLineHeightRef = useRef(lineHeight); + useLayoutEffect(() => { + if (previousLineHeightRef.current === lineHeight) return; + previousLineHeightRef.current = lineHeight; + virtualizer.measure(); + }, [lineHeight, virtualizer]); + return
 {
       if (!window.getSelection()?.isCollapsed) return;
       const index = Math.floor((event.clientY - event.currentTarget.getBoundingClientRect().top) / lineHeight);
-      if (index >= 0 && index < plain.length) onLineClick(startingLineNumber + index);
+      if (index >= 0 && index < visibleLineCount) onLineClick(startingLineNumber + index);
     }}>
-    {content}
+    {content}