πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(web): expand timeline rows to show labels without shrinking time (#16977)
Nikita Kabardinea9191dc5056
diff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsxindex 31432ad3d0..4d8e927241 100644--- a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx@@ -1787,7 +1787,7 @@ export const HoverDoesNotRecolourTheBar = meta.story({/** A control that can do nothing should say so rather than look broken. */export const FitIsDisabledWhenItWouldDoNothing = meta.story({name: "(Test) Fit Is Disabled When It Would Do Nothing",- args: { ...READABLE, roots: manySpans(40), onSelect: fn(), onHover: fn() },+ args: { ...READABLE, roots: manySpans(12), onSelect: fn(), onHover: fn() },play: async ({ canvasElement }) => {const fit = () =>canvasElement.querySelector<HTMLButtonElement>(@@ -1807,6 +1807,389 @@ export const FitIsDisabledWhenItWouldDoNothing = meta.story({},});+/**+ * A long trace fits as 1px rows β the whole clock, no names. The spent fit+ * control used to sit there disabled, so there was no obvious way to get the+ * labels back without also shrinking the duration. "Show labels" grows only+ * the rows; Fit then takes you back to the overview.+ */+export const ShowLabelsKeepsTheWholeClock = meta.story({+ name: "(Test) Show Labels Keeps The Whole Clock",+ args: {+ roots: manySpans(150),+ box: DESKTOP,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const readout = () =>+ canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-readout"]',+ )?.textContent ?? "";+ const toolbar = () =>+ canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-toolbar"]',+ );+ const labels = () =>+ canvasElement.querySelectorAll('[data-testid="timeline-dense-metrics"]')+ .length;++ await expect(readout()).toContain("fitted");+ await expect(readout()).toContain("4.0px rows");+ await expect(labels()).toBe(0);++ const show = canvasElement.querySelector<HTMLButtonElement>(+ 'button[aria-label="Show labels"]',+ );+ if (!show) throw new Error("no show-labels button");+ await expect(show.disabled).toBe(false);+ await expect(show.innerText.toLowerCase()).toContain("show labels");+ const caption = [...(toolbar()?.querySelectorAll("span") ?? [])].find(+ (el) => el.textContent?.trim().toLowerCase() === "show labels",+ );+ if (!caption) throw new Error("Show labels text is not on the button");+ await expect(show.contains(caption)).toBe(true);+ await userEvent.click(caption);++ await waitFor(() => expect(readout()).toContain("26.0px rows (labelled)"));+ await expect(readout()).toContain("zoomed");+ await expect(labels()).toBeGreaterThan(0);++ const fit = canvasElement.querySelector<HTMLButtonElement>(+ 'button[aria-label="Fit whole trace"]',+ );+ if (!fit) throw new Error("no fit button after expanding");+ await expect(fit.disabled).toBe(false);+ await userEvent.click(fit);++ await waitFor(() => expect(readout()).toContain("fitted"));+ await expect(readout()).toContain("4.0px rows");+ await expect(labels()).toBe(0);+ },+});++/**+ * A box that only slices time must not hide Fit behind Show labels. Growing+ * the rows would keep that narrow clock; Fit is the way back to the overview.+ */+export const FitStaysAfterATimeOnlyBox = meta.story({+ name: "(Test) Fit Stays After A Time Only Box",+ args: {+ roots: manySpans(150),+ box: DESKTOP,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const surface = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-surface"]',+ );+ if (!surface) throw new Error("dense surface not found");+ surface.setPointerCapture = () => undefined;+ surface.releasePointerCapture = () => undefined;+ const readout = () =>+ canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-readout"]',+ )?.textContent ?? "";++ await expect(+ canvasElement.querySelector('button[aria-label="Show labels"]'),+ ).not.toBeNull();++ const rect = surface.getBoundingClientRect();+ const drag = (type: string, x: number, y: number) =>+ surface.dispatchEvent(+ new PointerEvent(type, {+ bubbles: true,+ cancelable: true,+ pointerId: 1,+ pointerType: "mouse",+ buttons: type === "pointerup" ? 0 : 1,+ clientX: x,+ clientY: y,+ }),+ );+ // Full height, half the clock: rows stay hairline, time narrows.+ drag("pointerdown", rect.left + rect.width * 0.25, rect.top + 2);+ drag("pointermove", rect.left + rect.width * 0.75, rect.bottom - 2);+ drag("pointerup", rect.left + rect.width * 0.75, rect.bottom - 2);+ await waitFor(() => expect(readout()).toContain("zoomed"));+ await expect(readout()).toMatch(/[1-4]\.\dpx rows/);++ await expect(+ canvasElement.querySelector('button[aria-label="Show labels"]'),+ ).toBeNull();+ const fit = canvasElement.querySelector<HTMLButtonElement>(+ 'button[aria-label="Fit whole trace"]',+ );+ if (!fit) throw new Error("Fit disappeared after a time-only box");+ await expect(fit.disabled).toBe(false);+ },+});++/**+ * A short trace on a narrow pane already has readable rows, but auto will not+ * spend the lane on names. Show labels is still the ask: take the gutter,+ * even if the bars get thinner.+ */+export const ShowLabelsOpensTheGutterOnANarrowPane = meta.story({+ name: "(Test) Show Labels Opens The Gutter On A Narrow Pane",+ args: {+ roots: manySpans(12),+ box: PHONE,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const names = () =>+ canvasElement.querySelectorAll(+ '[data-testid="timeline-dense-peek"] span[title], [data-testid="timeline-dense-content"] > div span[title]',+ ).length;+ const barLeft = () => {+ const bar = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-bar"]',+ );+ return bar?.getBoundingClientRect().left ?? 0;+ };++ await expect(names()).toBe(0);+ const show = canvasElement.querySelector<HTMLButtonElement>(+ 'button[aria-label="Show labels"]',+ );+ if (!show) throw new Error("no show-labels button on a squeezed pane");+ await expect(show.innerText.toLowerCase()).toContain("show labels");+ const caption = [...show.querySelectorAll("span")].find(+ (el) => el.textContent?.trim().toLowerCase() === "show labels",+ );+ if (!caption) throw new Error("Show labels text is not on the button");+ const leftBefore = barLeft();++ await userEvent.click(caption);+ await waitFor(() => expect(names()).toBeGreaterThan(0));+ await expect(barLeft()).toBeGreaterThan(leftBefore + 40);+ },+});++/**+ * A pane too narrow to ever commit the gutter still offers Show labels, but+ * names float as a peek overlay. A second rail tap must be able to dismiss+ * that peek: committedOpen never becomes true, so the toggle has to look at+ * the held-open pin, not the committed lane.+ */+const TOO_NARROW_TO_COMMIT = { width: 220, height: 400 };++export const ShowLabelsPeekTogglesOffOnATooNarrowPane = meta.story({+ name: "(Test) Show Labels Peek Toggles Off On A Too Narrow Pane",+ args: {+ roots: manySpans(12),+ box: TOO_NARROW_TO_COMMIT,+ gutter: "auto",+ pointer: "coarse",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const surface = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-surface"]',+ );+ if (!surface) throw new Error("dense surface not found");+ surface.setPointerCapture = () => undefined;+ surface.releasePointerCapture = () => undefined;+ const peekNames = () =>+ canvasElement.querySelectorAll(+ '[data-testid="timeline-dense-peek"] span[title]',+ ).length;+ const gutterNames = () =>+ canvasElement.querySelectorAll(+ '[data-testid="timeline-dense-content"] > div span[title]',+ ).length;+ const barLeft = () => {+ const bar = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-bar"]',+ );+ return bar?.getBoundingClientRect().left ?? 0;+ };+ const tapRail = () => {+ const rect = surface.getBoundingClientRect();+ touch(surface, "pointerdown", 1, rect.left + 2, rect.top + 80);+ touch(surface, "pointerup", 1, rect.left + 2, rect.top + 80);+ };++ const show = canvasElement.querySelector<HTMLButtonElement>(+ 'button[aria-label="Show labels"]',+ );+ if (!show) throw new Error("no show-labels button on a peek-only pane");+ const leftBefore = barLeft();++ await userEvent.click(show);+ await waitFor(() => expect(peekNames()).toBeGreaterThan(0));+ await expect(gutterNames()).toBe(0);+ await expect(Math.abs(barLeft() - leftBefore)).toBeLessThan(20);++ tapRail();+ await waitFor(() => expect(peekNames()).toBe(0));+ await expect(gutterNames()).toBe(0);++ tapRail();+ await waitFor(() => expect(peekNames()).toBeGreaterThan(0));+ await expect(gutterNames()).toBe(0);+ },+});++/**+ * After a coarse rail tap collapses a committed gutter, Show labels must+ * clear that leftover override and take the lane again. A stale+ * override==="collapsed" used to leave names as a peek overlay.+ */+export const ShowLabelsRecommitsAfterARailCollapse = meta.story({+ name: "(Test) Show Labels Recommits After A Rail Collapse",+ args: {+ roots: manySpans(12),+ box: PHONE,+ gutter: "auto",+ pointer: "coarse",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const surface = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-surface"]',+ );+ if (!surface) throw new Error("dense surface not found");+ surface.setPointerCapture = () => undefined;+ surface.releasePointerCapture = () => undefined;+ const peekNames = () =>+ canvasElement.querySelectorAll(+ '[data-testid="timeline-dense-peek"] span[title]',+ ).length;+ const gutterNames = () =>+ canvasElement.querySelectorAll(+ '[data-testid="timeline-dense-content"] > div span[title]',+ ).length;+ const barLeft = () => {+ const bar = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-bar"]',+ );+ return bar?.getBoundingClientRect().left ?? 0;+ };+ const tapRail = () => {+ const rect = surface.getBoundingClientRect();+ touch(surface, "pointerdown", 1, rect.left + 2, rect.top + 80);+ touch(surface, "pointerup", 1, rect.left + 2, rect.top + 80);+ };+ const clickShowLabels = async () => {+ const show = canvasElement.querySelector<HTMLButtonElement>(+ 'button[aria-label="Show labels"]',+ );+ if (!show) throw new Error("no show-labels button");+ await userEvent.click(show);+ };++ const leftClosed = barLeft();+ await expect(gutterNames()).toBe(0);++ await clickShowLabels();+ await waitFor(() => expect(gutterNames()).toBeGreaterThan(0));+ await expect(peekNames()).toBe(0);+ await expect(barLeft()).toBeGreaterThan(leftClosed + 40);++ tapRail();+ await waitFor(() => expect(gutterNames()).toBe(0));+ await expect(peekNames()).toBe(0);++ await clickShowLabels();+ await waitFor(() => expect(gutterNames()).toBeGreaterThan(0));+ await expect(peekNames()).toBe(0);+ await expect(barLeft()).toBeGreaterThan(leftClosed + 40);+ },+});++/**+ * Panning a hairline overview is not a time zoom. Show labels must stay, or+ * Fit would snap the window back to the top of the tree instead of naming+ * the rows you just scrolled to.+ */+export const ShowLabelsSurvivesAVerticalPan = meta.story({+ name: "(Test) Show Labels Survives A Vertical Pan",+ args: {+ roots: manySpans(800),+ box: DESKTOP,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ },+ play: async ({ canvasElement }) => {+ const surface = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-surface"]',+ );+ if (!surface) throw new Error("dense surface not found");+ const readout = () =>+ canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-readout"]',+ )?.textContent ?? "";+ const show = () =>+ canvasElement.querySelector<HTMLButtonElement>(+ 'button[aria-label="Show labels"]',+ );++ await expect(readout()).toContain("fitted");+ await expect(show()).not.toBeNull();++ const rect = surface.getBoundingClientRect();+ surface.dispatchEvent(+ new WheelEvent("wheel", {+ bubbles: true,+ cancelable: true,+ clientX: rect.left + rect.width / 2,+ clientY: rect.top + rect.height / 2,+ deltaY: 240,+ }),+ );+ await waitFor(() => expect(readout()).toContain("zoomed"));+ await expect(readout()).toMatch(/1\.0px rows/);+ await expect(show()).not.toBeNull();+ await expect(+ canvasElement.querySelector('button[aria-label="Fit whole trace"]'),+ ).toBeNull();++ if (!show()) throw new Error("Show labels vanished after a vertical pan");+ await userEvent.click(show()!);+ await waitFor(() => expect(readout()).toContain("26.0px rows (labelled)"));+ await expect(readout()).toContain("zoomed");+ },+});+/** Collapse in the tree means collapse here: the same set, honoured. */export const CollapsedRowsAreNotDrawn = meta.story({name: "(Test) Collapsed Rows Are Not Drawn",@@ -2017,7 +2400,7 @@ export const TheCursorMatchesTheGesture = meta.story({*/export const TheToolbarDoesNotExplainItself = meta.story({name: "(Test) The Toolbar Does Not Explain Itself",- args: { ...READABLE, roots: manySpans(40), onSelect: fn(), onHover: fn() },+ args: { ...READABLE, roots: manySpans(12), onSelect: fn(), onHover: fn() },play: async ({ canvasElement }) => {const toolbar = canvasElement.querySelector<HTMLElement>('[data-testid="timeline-dense-toolbar"]',diff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsxindex 5226ef86f2..c59682406b 100644--- a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx@@ -21,9 +21,11 @@* phone or a peek panel, where there is not, the colour rail becomes the* affordance and a hover or a tap floats the names over the chart.* - Any wheel or two-finger scroll pans both axes; pinch and β/ctrl + wheel zoom- * BOTH axes about the cursor, so the time window narrows and the rows grow- * together. Zoom is exponential in a zoom level and deltas accumulate per- * frame, as in mapping libraries β see the rate constants below.+ * about the cursor. While rows are still too short to hold a label, that zoom+ * grows only the rows β the whole duration stays on screen until the names+ * come back β and after that both axes move together. Zoom is exponential in+ * a zoom level and deltas accumulate per frame, as in mapping libraries β see+ * the rate constants below.* - Drag pans both axes too, and drag draws a box to zoom into β the one* gesture where the user has stated the window on both axes, so it goes* straight there. There are no scrollbars by design: a map has none, and the@@ -56,7 +58,7 @@ import {type ReactNode,} from "react";import { useTheme } from "next-themes";-import { Scan, Minus, Plus } from "lucide-react";+import { Scan, Minus, Plus, UnfoldVertical } from "lucide-react";import { ItemBadge, type LangfuseItemType } from "@/src/components/ItemBadge";import {tooltipPlacement,@@ -81,6 +83,8 @@ import { traceSpaceOf, type Box } from "../../fns/timeline/viewTransform";import {HUMAN_ROW_HEIGHT,anchorTimeToRows,+ canExpandRowsToReadable,+ expandRowsToReadable,interpolateViewport,rowCountBounds,viewportsEqual,@@ -95,7 +99,7 @@ import {rowIndexAtOffset,visibleRowRange,zoomToBox,- zoomViewport,+ zoomViewportRevealLabels,type RowExtent,type Viewport,} from "../../fns/timeline/viewport";@@ -388,6 +392,10 @@ export function TimelineDense({// A manual override lives until you touch the chart again, which is what// "expand to look, then get out of my way" means in practice.const [override, setOverride] = useState<GutterMode | null>(null);+ // An explicit "Show labels" is the other ask: keep the names on screen even+ // when a gesture would have handed the gutter back, and even when auto would+ // rather keep the lane. Fit or a rail collapse lets go.+ const [labelsPinned, setLabelsPinned] = useState(false);// Desktop peek: hovering the left edge opens it, moving into the chart closes// it again. No click to look, no click to get out of the way.const [peeking, setPeeking] = useState(false);@@ -437,9 +445,16 @@ export function TimelineDense({*/const canShowNames = liveRowHeight >= NAME_MIN_ROW_HEIGHT;const wantedGutter = Math.min(Math.max(contentWidth * 0.38, 96), 168);- const asked = override === "expanded" || gutterMode === "expanded";- const wantsOpen =- override === "collapsed" ? false : asked || gutterMode === "auto";+ const asked =+ labelsPinned || override === "expanded" || gutterMode === "expanded";+ // An explicit "Show labels" pin wins over a leftover rail-collapse+ // override; otherwise the names stay a peek overlay and never take+ // the gutter the user just asked for.+ const wantsOpen = labelsPinned+ ? true+ : override === "collapsed"+ ? false+ : asked || gutterMode === "auto";const gutterFits =contentWidth - wantedGutter >=(asked ? MIN_LANE_WIDTH : AUTO_OPEN_MIN_LANE_WIDTH);@@ -486,11 +501,22 @@ export function TimelineDense({// an explicit ask still gets the names where they could not fit beside the// chart.const peekWidth =- canShowNames && !committedOpen && (peeking || override === "expanded")+ canShowNames &&+ !committedOpen &&+ (peeking || labelsPinned || override === "expanded")? wantedGutter: 0;const presentation = presentationForRowHeight(rowHeight);const fitted = isViewportFitted(current, limits);+ const canShowLabels = canExpandRowsToReadable(current, limits);+ const labelsShowing = committedOpen || (labelsPinned && peekWidth > 0);+ // Replace Fit only while the whole clock is still on screen AND names are+ // missing. Rows can be too short, or the pane too narrow to volunteer a+ // gutter β both are the same ask. A time-zoomed hairline keeps Fit.+ const clockFits = current.time.duration >= limits.traceSpace.duration - 0.5;+ const offerShowLabels =+ clockFits && !labelsShowing && (canShowLabels || canShowNames);+ const fitSpent = fitted && !labelsPinned;const barHeight = Math.max(Math.min(rowHeight - 1, MAX_BAR_HEIGHT), 1);/**@@ -666,7 +692,7 @@ export function TimelineDense({options: { factor: number; xRatio: number; yRatio: number },) => {const { limits: live, extentOf: extent } = layoutRef.current;- const zoomed = zoomViewport(+ const zoomed = zoomViewportRevealLabels(from ? clampViewport(from, live) : fitViewport(live),live,options,@@ -816,6 +842,19 @@ export function TimelineDense({[cancelTween],);+ const showLabels = () => {+ const { limits: live, extentOf } = layoutRef.current;+ setLabelsPinned(true);+ setOverride(null);+ flyTo(+ anchorTimeToRows(+ expandRowsToReadable(viewportRef.current, live),+ live,+ extentOf,+ ),+ );+ };+const scheduleGesture = useCallback(() => {// Any gesture on the chart hands the space back: an expanded gutter is for// looking, and the moment you work in the chart it gets out of the way. It@@ -828,8 +867,9 @@ export function TimelineDense({/*** Wheel and trackpad pinch on a non-passive listener, so the page never takes- * the gesture. Both zoom, like a map: a Mac pinch arrives as wheel + ctrlKey- * and needs no special case; shift or a horizontal wheel pans instead.+ * the gesture. A Mac pinch arrives as wheel + ctrlKey and needs no special+ * case; shift or a horizontal wheel pans instead. Pinch-zoom grows only the+ * rows while labels are hidden, then both axes once they fit.*/const attachSurface = useCallback((element: HTMLDivElement | null) => {@@ -923,7 +963,14 @@ export function TimelineDense({canShowNames &&offsetX <= Math.max(railWidth, peekWidth) + PEEK_MARGIN_PX) {- setOverride(isOpen ? "collapsed" : "expanded");+ // Peek overlays never become committedOpen (the pane is too narrow+ // to give the gutter a lane). Toggle on the held-open state so a+ // second tap can dismiss a peek the first tap β or Show labels β+ // just opened.+ const namesHeldOpen =+ committedOpen || labelsPinned || override === "expanded";+ setLabelsPinned(!namesHeldOpen);+ setOverride(namesHeldOpen ? "collapsed" : "expanded");// This tap is spent on the toggle, so it is not half of a double-tap:// opening and closing the names inside the double-tap window otherwise read// as one, and flew the viewport to whatever row the second tap landed on.@@ -1307,31 +1354,48 @@ export function TimelineDense({</ToolbarButton><ToolbarButtonlabel="Zoom in"- onClick={() => zoomBy(2 ** BUTTON_ZOOM_LEVELS, 0.5, 0.5)}+ onClick={() =>+ offerShowLabels+ ? showLabels()+ : zoomBy(2 ** BUTTON_ZOOM_LEVELS, 0.5, 0.5)+ }><Plus className="h-3 w-3" /></ToolbarButton>- <ToolbarButton- label={fitted ? "Whole trace already fits" : "Fit whole trace"}- onClick={() => flyTo(fitViewport(limits))}- disabled={fitted}- >- {/* A viewfinder, not the diagonal arrows this used to wear: those read- as "fullscreen", so a control that was merely spent looked broken. */}- <Scan className="h-3 w-3" />- </ToolbarButton>+ {offerShowLabels ? (+ <ToolbarButton label="Show labels" onClick={showLabels}>+ <UnfoldVertical className="h-3 w-3" />+ <span className="pr-0.5" style={{ fontSize: "10px" }}>+ Show labels+ </span>+ </ToolbarButton>+ ) : (+ <ToolbarButton+ label={fitSpent ? "Whole trace already fits" : "Fit whole trace"}+ onClick={() => {+ setLabelsPinned(false);+ setOverride(null);+ flyTo(fitViewport(limits));+ }}+ disabled={fitSpent}+ >+ {/* A viewfinder, not the diagonal arrows this used to wear: those+ read as "fullscreen", so a control that was merely spent looked+ broken. */}+ <Scan className="h-3 w-3" />+ </ToolbarButton>+ )}{/* Where you are, when you are somewhere β and nothing at all when the- whole trace is in view. This carried a list of gestures once. Every- way of interacting with this surface is one you would have tried:- drag, scroll, pinch, double-click, click. A caption explaining them- is a caption nobody reads, taking the room a state readout earns. */}- <span- className="text-muted-foreground truncate"- style={{ fontSize: "10px" }}- title={fitted ? undefined : windowHint}- >- {fitted ? null : windowHint}- </span>+ whole trace is in view. */}+ {!offerShowLabels && !fitted ? (+ <span+ className="text-muted-foreground truncate"+ style={{ fontSize: "10px" }}+ title={windowHint}+ >+ {windowHint}+ </span>+ ) : null}</div>{/* The axis doubles as the scrub track: press to place the playhead, drag@@ -1911,7 +1975,7 @@ function ToolbarButton({title={label}onClick={onClick}disabled={disabled}- className="hover:bg-muted flex h-4 w-4 shrink-0 items-center justify-center rounded disabled:pointer-events-none disabled:opacity-40"+ className="hover:bg-muted flex h-4 min-w-4 shrink-0 items-center justify-center gap-0.5 rounded px-0.5 disabled:pointer-events-none disabled:opacity-40">{children}</button>diff --git a/web/src/features/traces/fns/timeline/viewport.clienttest.ts b/web/src/features/traces/fns/timeline/viewport.clienttest.tsindex c8cfce2c6b..5f339a8cff 100644--- a/web/src/features/traces/fns/timeline/viewport.clienttest.ts+++ b/web/src/features/traces/fns/timeline/viewport.clienttest.ts@@ -2,7 +2,10 @@ import { describe, expect, it } from "vitest";import { traceSpaceOf } from "./viewTransform";import {HUMAN_ROW_HEIGHT,+ LABELLED_ROW_HEIGHT,anchorTimeToRows,+ canExpandRowsToReadable,+ expandRowsToReadable,MAX_ROW_HEIGHT,MIN_ROW_HEIGHT,clampViewport,@@ -10,6 +13,7 @@ import {focusViewport,isViewportFitted,panViewport,+ presentationForRowHeight,revealViewport,rowHeightOf,viewportsEqual,@@ -17,6 +21,7 @@ import {visibleRowRange,zoomToBox,zoomViewport,+ zoomViewportRevealLabels,type Viewport,} from "./viewport";@@ -66,6 +71,110 @@ describe("viewport", () => {expect(rowHeightOf(zoomedIn, 600)).toBeCloseTo(MAX_ROW_HEIGHT, 6);});+ it("expands rows to a readable height without narrowing the clock", () => {+ const fitted = fitViewport(limits);+ expect(rowHeightOf(fitted, limits.boxHeight)).toBe(MIN_ROW_HEIGHT);+ expect(canExpandRowsToReadable(fitted, limits)).toBe(true);+ expect(presentationForRowHeight(MIN_ROW_HEIGHT)).toBe("hairline");++ const expanded = expandRowsToReadable(fitted, limits);+ expect(rowHeightOf(expanded, limits.boxHeight)).toBeCloseTo(+ HUMAN_ROW_HEIGHT,+ 6,+ );+ expect(expanded.time).toEqual(limits.traceSpace);+ expect(expanded.rows.start).toBe(0);+ expect(isViewportFitted(expanded, limits)).toBe(false);+ expect(canExpandRowsToReadable(expanded, limits)).toBe(false);+ expect(+ presentationForRowHeight(rowHeightOf(expanded, limits.boxHeight)),+ ).toBe("labelled");++ // A window that has been panned keeps that slice at the top.+ const panned = {+ ...fitted,+ rows: { start: 800, count: fitted.rows.count },+ };+ const fromThere = expandRowsToReadable(panned, limits);+ expect(fromThere.rows.start).toBeCloseTo(800, 6);+ expect(fromThere.time).toEqual(panned.time);++ // A clock that has already been sliced stays sliced; only the rows grow.+ const narrowed = zoomViewport(fitted, limits, {+ factor: 2,+ xRatio: 0.5,+ yRatio: 0.5,+ axes: "x",+ });+ expect(canExpandRowsToReadable(narrowed, limits)).toBe(true);+ const expandedClock = expandRowsToReadable(narrowed, limits);+ expect(expandedClock.time).toEqual(narrowed.time);+ expect(rowHeightOf(expandedClock, limits.boxHeight)).toBeCloseTo(+ HUMAN_ROW_HEIGHT,+ 6,+ );++ // A short trace already sits at the human height β nothing to grow.+ const short = { ...limits, rowCount: 12 };+ const shortFit = fitViewport(short);+ expect(canExpandRowsToReadable(shortFit, short)).toBe(false);+ expect(expandRowsToReadable(shortFit, short)).toEqual(shortFit);+ });++ it("zooms only the rows when labels are still hidden", () => {+ const fitted = fitViewport(limits);+ const yOnly = zoomViewport(fitted, limits, {+ factor: 2,+ xRatio: 0.5,+ yRatio: 0.5,+ axes: "y",+ });+ expect(yOnly.time).toEqual(fitted.time);+ expect(yOnly.rows.count).toBeCloseTo(300, 6);+ expect(rowHeightOf(yOnly, limits.boxHeight)).toBeCloseTo(2, 6);++ // Incremental zoom-in stays on Y until a label would fit.+ const reveal = zoomViewportRevealLabels(fitted, limits, {+ factor: 2,+ xRatio: 0.5,+ yRatio: 0.5,+ });+ expect(reveal.time).toEqual(fitted.time);+ expect(rowHeightOf(reveal, limits.boxHeight)).toBeCloseTo(2, 6);++ // A factor large enough to cross the labelled threshold spends the rest+ // on both axes β otherwise a batched pinch would leave the clock full.+ const crossing = zoomViewportRevealLabels(fitted, limits, {+ factor: LABELLED_ROW_HEIGHT * 1.2,+ xRatio: 0.5,+ yRatio: 0.5,+ });+ expect(rowHeightOf(crossing, limits.boxHeight)).toBeGreaterThanOrEqual(+ LABELLED_ROW_HEIGHT,+ );+ expect(crossing.time.duration).toBeCloseTo(fitted.time.duration / 1.2, 6);++ const labelled = expandRowsToReadable(fitted, limits);+ const both = zoomViewportRevealLabels(labelled, limits, {+ factor: 1.2,+ xRatio: 0.5,+ yRatio: 0.5,+ });+ expect(both.time.duration).toBeCloseTo(labelled.time.duration / 1.2, 6);+ expect(both.rows.count).toBeCloseTo(labelled.rows.count / 1.2, 6);++ // Zooming out from the hairline is a no-op on time (already full) and+ // cannot shrink the rows below the floor.+ const out = zoomViewportRevealLabels(fitted, limits, {+ factor: 0.5,+ xRatio: 0.5,+ yRatio: 0.5,+ });+ expect(out.time).toEqual(fitted.time);+ expect(rowHeightOf(out, limits.boxHeight)).toBeCloseTo(MIN_ROW_HEIGHT, 6);+ expect(LABELLED_ROW_HEIGHT).toBe(20);+ });+it("zooms both axes about the anchor and holds the content under it", () => {const zoomed = zoomViewport(fitViewport(limits), limits, {factor: 2,diff --git a/web/src/features/traces/fns/timeline/viewport.ts b/web/src/features/traces/fns/timeline/viewport.tsindex 32bf20c520..22062b99e0 100644--- a/web/src/features/traces/fns/timeline/viewport.ts+++ b/web/src/features/traces/fns/timeline/viewport.ts@@ -13,8 +13,11 @@* `boxHeight / rows.count` β vertical zoom IS the visible row count, which is* what makes "zoom until the rows are readable" a single number.*- * Both axes clamp to content, so the viewport can never leave the trace, and a- * single `factor` drives both β a map does not zoom one axis at a time.+ * Both axes clamp to content, so the viewport can never leave the trace.+ * Gesture zoom is usually one `factor` on both axes β a map does not zoom one+ * axis at a time β except while rows are still too short to hold a label: then+ * zooming in grows only the rows, so the whole duration stays on screen until+ * the names come back.*/import { clampView, type TimeSpan } from "./viewTransform";@@ -33,6 +36,8 @@ export const MIN_ROW_HEIGHT = 1;export const MAX_ROW_HEIGHT = 40;/** The row height a human reads comfortably β what double-click aims for. */export const HUMAN_ROW_HEIGHT = 26;+/** Shortest row that can hold a duration label and a name. */+export const LABELLED_ROW_HEIGHT = 20;export type RowPresentation =/** Bar, duration label and name. */@@ -45,7 +50,7 @@ export type RowPresentation =/** What a row can show follows from how tall it is, never the other way round. */export function presentationForRowHeight(rowHeight: number): RowPresentation {const height = Number.isFinite(rowHeight) ? rowHeight : 0;- if (height >= 20) return "labelled";+ if (height >= LABELLED_ROW_HEIGHT) return "labelled";if (height >= 10) return "compact";return "hairline";}@@ -65,8 +70,8 @@ export type ViewportLimits = {boxHeight: number;};-const finite = (value: number, fallback: number) =>- Number.isFinite(value) ? value : fallback;+const finite = (value: number | undefined, fallback: number) =>+ typeof value === "number" && Number.isFinite(value) ? value : fallback;const clamp = (value: number, min: number, max: number) =>Math.min(Math.max(value, min), max);@@ -143,39 +148,136 @@ export function clampViewport(};}+export type ZoomAxes = "both" | "x" | "y";+/**- * Zoom both axes about a point in the box, given as ratios of its width and- * height. `factor > 1` zooms in. The content under the anchor stays under it.+ * Zoom about a point in the box, given as ratios of its width and height.+ * `factor > 1` zooms in. The content under the anchor stays under it.+ *+ * `axes` defaults to both. `"y"` grows or shrinks only the rows, which is how+ * a long trace can keep its full duration on screen while the labels return.*/export function zoomViewport(viewport: Viewport,limits: ViewportLimits,- options: { factor: number; xRatio: number; yRatio: number },+ options: {+ factor: number;+ xRatio: number;+ yRatio: number;+ axes?: ZoomAxes;+ },): Viewport {const factor = finite(options.factor, 1);if (factor <= 0) return clampViewport(viewport, limits);+ const axes = options.axes ?? "both";+ const zoomX = axes !== "y";+ const zoomY = axes !== "x";const xRatio = clamp(finite(options.xRatio, 0.5), 0, 1);const yRatio = clamp(finite(options.yRatio, 0.5), 0, 1);const anchorMs = viewport.time.start + viewport.time.duration * xRatio;- const timeDuration = viewport.time.duration / factor;+ const timeDuration = zoomX+ ? viewport.time.duration / factor+ : viewport.time.duration;const anchorRow = viewport.rows.start + viewport.rows.count * yRatio;- const rowsCount = viewport.rows.count / factor;+ const rowsCount = zoomY ? viewport.rows.count / factor : viewport.rows.count;return clampViewport({time: {- start: anchorMs - timeDuration * xRatio,+ start: zoomX ? anchorMs - timeDuration * xRatio : viewport.time.start,duration: timeDuration,},- rows: { start: anchorRow - rowsCount * yRatio, count: rowsCount },+ rows: {+ start: zoomY ? anchorRow - rowsCount * yRatio : viewport.rows.start,+ count: rowsCount,+ },},limits,);}+/**+ * Grow rows until they can hold labels, without narrowing the time window.+ *+ * The resting fit of a long trace is 1px rows β the whole shape, no text. This+ * is the other rest: the same clock, rows tall enough to name themselves, the+ * rest of the tree panned to.+ */+export function expandRowsToReadable(+ viewport: Viewport,+ limits: ViewportLimits,+ options: { yRatio?: number; targetRowHeight?: number } = {},+): Viewport {+ const from = clampViewport(viewport, limits);+ const target = Math.max(+ finite(options.targetRowHeight, HUMAN_ROW_HEIGHT),+ LABELLED_ROW_HEIGHT,+ );+ const yRatio = clamp(finite(options.yRatio, 0), 0, 1);+ const bounds = rowCountBounds(limits);+ const boxHeight = Math.max(finite(limits.boxHeight, 0), 0);+ const count = clamp(+ boxHeight > 0 ? boxHeight / target : bounds.min,+ bounds.min,+ bounds.max,+ );+ const anchorRow = from.rows.start + from.rows.count * yRatio;+ return clampViewport(+ {+ time: from.time,+ rows: { start: anchorRow - count * yRatio, count },+ },+ limits,+ );+}++/** Whether growing the rows (and keeping the clock) would reveal labels. */+export function canExpandRowsToReadable(+ viewport: Viewport,+ limits: ViewportLimits,+): boolean {+ const height = rowHeightOf(viewport, limits.boxHeight);+ if (height >= LABELLED_ROW_HEIGHT) return false;+ const expanded = expandRowsToReadable(viewport, limits);+ return rowHeightOf(expanded, limits.boxHeight) > height + 0.05;+}++/**+ * Zoom in: grow rows first until labels fit, then apply whatever factor is+ * left to both axes. Zoom out: both axes (a full-width window only shrinks+ * the rows).+ */+export function zoomViewportRevealLabels(+ viewport: Viewport,+ limits: ViewportLimits,+ options: { factor: number; xRatio: number; yRatio: number },+): Viewport {+ const factor = finite(options.factor, 1);+ if (factor <= 1) {+ return zoomViewport(viewport, limits, options);+ }+ const height = rowHeightOf(viewport, limits.boxHeight);+ if (!(height > 0) || height >= LABELLED_ROW_HEIGHT) {+ return zoomViewport(viewport, limits, options);+ }+ const yFactorNeeded = LABELLED_ROW_HEIGHT / height;+ if (factor <= yFactorNeeded) {+ return zoomViewport(viewport, limits, { ...options, axes: "y" });+ }+ const labelled = zoomViewport(viewport, limits, {+ ...options,+ factor: yFactorNeeded,+ axes: "y",+ });+ return zoomViewport(labelled, limits, {+ ...options,+ factor: factor / yFactorNeeded,+ });+}+/*** Zoom to a box drawn on the surface β "show me exactly this region".*