From 6abb9a443fc91089d743ecc5ed0476a6afe2fac8 Mon Sep 17 00:00:00 2001 From: Alex Carpenter Date: Wed, 25 Nov 2026 09:42:05 -0500 Subject: [PATCH 1/2] perf(mosaic): skip chart rerenders while the pointer stays on one bar --- .../chart/__tests__/chart.browser.test.tsx | 38 ++++++++++++++++++- .../primitives/chart/internal/selection.ts | 19 ++++++++-- .../chart/internal/use-chart-instance.ts | 3 ++ 3 files changed, 56 insertions(+), 4 deletions(-) diff --git a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx index d357fa10d05..6e32972b06b 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx @@ -1,7 +1,7 @@ import { cleanup, render as renderComponent, screen } from '@testing-library/react'; import type {} from '@vitest/browser-playwright'; import type { ReactElement } from 'react'; -import { useRef } from 'react'; +import { Profiler, useRef } from 'react'; import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; import { cdp, page, userEvent } from 'vitest/browser'; @@ -85,6 +85,13 @@ function pointer(type: string, target: Element, clientX: number, clientY: number target.dispatchEvent(new PointerEvent(type, { bubbles: true, clientX, clientY, pointerType })); } +function nextFrames(count: number) { + return new Promise(resolve => { + const step = (left: number) => (left === 0 ? resolve() : requestAnimationFrame(() => step(left - 1))); + step(count); + }); +} + function centerOfCategory(categoryIndex: number) { const plot = surface().getBoundingClientRect(); const step = plot.width / months.length; @@ -434,6 +441,35 @@ describe('choosing a period with a pointer', () => { expect(screen.queryByTestId('cursor')).toBeNull(); }); + it('does not rerender while the mouse moves within the selected period', async () => { + let commits = 0; + const onSelectionChange = vi.fn<(selection: BarSelection | null) => void>(); + await render( + { + commits++; + }} + > + + , + ); + const { x, y } = centerOfCategory(3); + pointer('pointermove', surface(), x, y); + await expect.poll(() => onSelectionChange.mock.lastCall?.[0]).toMatchObject({ category: 'Apr' }); + await nextFrames(3); + const settled = commits; + + for (const dx of [-6, -3, 3, 6]) { + pointer('pointermove', surface(), x + dx, y + dx); + await nextFrames(1); + } + await nextFrames(2); + + expect(onSelectionChange).toHaveBeenCalledTimes(1); + expect(commits).toBe(settled); + }); + it('selects on touch contact, keeps it after the finger lifts, and dismisses on a touch elsewhere', async () => { const onSelectionChange = vi.fn<(selection: BarSelection | null) => void>(); await render(); diff --git a/packages/mosaic/src/primitives/chart/internal/selection.ts b/packages/mosaic/src/primitives/chart/internal/selection.ts index 572670a5b73..2f2ee626607 100644 --- a/packages/mosaic/src/primitives/chart/internal/selection.ts +++ b/packages/mosaic/src/primitives/chart/internal/selection.ts @@ -73,9 +73,22 @@ export function selectionReducer( ): SelectionState { switch (action.type) { case 'pointer': - return action.selection - ? { status: 'selected', source: 'pointer', category: action.selection.category, selection: action.selection } - : NO_SELECTION; + if (!action.selection) { + return NO_SELECTION; + } + if ( + state.status === 'selected' && + state.source === 'pointer' && + sameSelection(state.selection, action.selection) + ) { + return state; + } + return { + status: 'selected', + source: 'pointer', + category: action.selection.category, + selection: action.selection, + }; case 'select': return { status: 'selected', diff --git a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts index 90c7843e409..f3430d48a49 100644 --- a/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts +++ b/packages/mosaic/src/primitives/chart/internal/use-chart-instance.ts @@ -205,6 +205,9 @@ export function useChartInstance< } const previous = stateRef.current; const next = selectionReducer(previous, action); + if (next === previous) { + return next; + } stateRef.current = next; setStored(next); const nextValue = toPublicSelection(next); From a9f2a3f8525b575d1a405e4454c5ee46543ec4c1 Mon Sep 17 00:00:00 2001 From: Alex Carpenter Date: Wed, 25 Nov 2026 09:42:07 -0500 Subject: [PATCH 2/2] feat(mosaic): slide the chart tooltip between bars and hide it off screen --- .changeset/mosaic-chart-fluid-tooltip.md | 7 +++ .../components/chart/chart-parts.styles.ts | 14 ++++- .../mosaic/src/primitives/chart/README.md | 2 + .../chart/__tests__/chart.browser.test.tsx | 51 +++++++++++++++++++ .../src/primitives/chart/chart-tooltip.tsx | 26 +++++++++- .../swingset/src/stories/chart.component.mdx | 5 +- .../src/stories/chart.component.stories.tsx | 18 ++++--- 7 files changed, 111 insertions(+), 12 deletions(-) create mode 100644 .changeset/mosaic-chart-fluid-tooltip.md diff --git a/.changeset/mosaic-chart-fluid-tooltip.md b/.changeset/mosaic-chart-fluid-tooltip.md new file mode 100644 index 00000000000..2e13d952e2a --- /dev/null +++ b/.changeset/mosaic-chart-fluid-tooltip.md @@ -0,0 +1,7 @@ +--- +'@clerk/mosaic': minor +--- + +The chart tooltip now slides between bars instead of jumping, and stays put when it first opens. With reduced motion it only fades. While the selected bar is scrolled out of view the tooltip hides, and it comes back when the bar does. Moving the pointer within one bar no longer rerenders the chart. + +`Chart.Tooltip` carries two new attributes for styling: `data-moving`, from the first change of bar until it closes, and `data-anchor-hidden`, while the selected bar is out of view. diff --git a/packages/mosaic/src/components/chart/chart-parts.styles.ts b/packages/mosaic/src/components/chart/chart-parts.styles.ts index 7d3041f3b37..1f5a6989402 100644 --- a/packages/mosaic/src/components/chart/chart-parts.styles.ts +++ b/packages/mosaic/src/components/chart/chart-parts.styles.ts @@ -64,8 +64,18 @@ export const partStyles = stylex.create({ default: 1, ':where([data-starting-style], [data-ending-style])': 0, }, - transitionDuration: durationVars['--cl-duration-fast'], - transitionProperty: 'opacity', + transitionDuration: { + default: durationVars['--cl-duration-fast'], + ':where([data-moving])': `${durationVars['--cl-duration-fast']}, ${durationVars['--cl-duration-slow']}, ${durationVars['--cl-duration-slow']}`, + }, + transitionProperty: { + default: 'opacity', + ':where([data-moving])': 'opacity, top, left', + '@media (prefers-reduced-motion: reduce)': { + default: 'opacity', + ':where([data-moving])': 'opacity', + }, + }, transitionTimingFunction: { default: easingVars['--cl-ease-enter'], ':where([data-ending-style])': easingVars['--cl-ease-exit'], diff --git a/packages/mosaic/src/primitives/chart/README.md b/packages/mosaic/src/primitives/chart/README.md index 0008d7e3aa8..43e08407bc8 100644 --- a/packages/mosaic/src/primitives/chart/README.md +++ b/packages/mosaic/src/primitives/chart/README.md @@ -284,6 +284,8 @@ Painting the bars is the one thing the chart object does not do, because their c | `data-focus-visible` | `Chart.Cursor` | Present while the keyboard selected the category. Ring the cursor then, not the whole chart | | `data-side` | `Chart.Tooltip` | `left` or `right` of the selected period, or `bottom` when pinned to the top of a narrow chart | | `data-open` / `data-closed` | `Chart.Tooltip` | The tooltip's open state, with `data-starting-style` and `data-ending-style` during transitions | +| `data-moving` | `Chart.Tooltip` | Present from the first change of category while open until it closes, so a position transition skips the first open | +| `data-anchor-hidden` | `Chart.Tooltip` | Present while the selected point is scrolled out of view. The tooltip is hidden | The interaction surface also carries the chart type's state, such as `data-active-section` for bars. `Chart.Bar` takes its own attributes before each paint, listed under [Styling](#styling). diff --git a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx index 6e32972b06b..8157c198750 100644 --- a/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx +++ b/packages/mosaic/src/primitives/chart/__tests__/chart.browser.test.tsx @@ -642,6 +642,57 @@ describe('the tooltip', () => { expect(contains(boundary, tooltip)).toBe(true); }); + it('marks the tooltip as moving from the first change of period until it closes', async () => { + await render( + , + ); + const tooltip = await focusPeriod(0); + expect(tooltip).toHaveTextContent('Jan: 10'); + expect(tooltip).not.toHaveAttribute('data-moving'); + + await userEvent.keyboard('{ArrowRight}'); + await expect.poll(() => tooltip.textContent).toBe('Feb: 20'); + expect(tooltip).toHaveAttribute('data-moving'); + + await userEvent.keyboard('{ArrowLeft}'); + await expect.poll(() => tooltip.textContent).toBe('Jan: 10'); + expect(tooltip).toHaveAttribute('data-moving'); + + surface().blur(); + await expect.poll(() => screen.queryByTestId('tooltip')).toBeNull(); + const reopened = await focusPeriod(0); + expect(reopened).not.toHaveAttribute('data-moving'); + }); + + it('hides the tooltip while its chart is scrolled out of view and shows it again once it is back', async () => { + await render( +
+ +
+
, + ); + const tooltip = await focusPeriod(1); + expect(tooltip).not.toHaveAttribute('data-anchor-hidden'); + + const scroller = screen.getByTestId('scroller'); + scroller.scrollTop = 1000; + await expect.poll(() => tooltip.hasAttribute('data-anchor-hidden')).toBe(true); + expect(tooltip.style.visibility).toBe('hidden'); + + scroller.scrollTop = 0; + await expect.poll(() => tooltip.hasAttribute('data-anchor-hidden')).toBe(false); + expect(tooltip.style.visibility).toBe(''); + }); + it('closes when the selection is dismissed', async () => { await render( = Omit< type BoundaryRef = React.RefObject; +function useMoving(open: boolean, datumIndex: number | undefined) { + const [openedAt, setOpenedAt] = React.useState(undefined); + const [moved, setMoved] = React.useState(false); + if (!open) { + if (openedAt !== undefined || moved) { + setOpenedAt(undefined); + setMoved(false); + } + } else if (openedAt === undefined) { + setOpenedAt(datumIndex); + } else if (!moved && datumIndex !== openedAt) { + setMoved(true); + } + return open && moved; +} + /** Reads the boundary when floating-ui computes a position, not during render. */ function boundaryReader(collisionBoundary: BoundaryRef | undefined, chartBoxRef: BoundaryRef) { return () => collisionBoundary?.current ?? chartBoxRef.current ?? undefined; @@ -61,6 +77,7 @@ function tooltipMiddleware( elements.floating.style.maxWidth = `${Math.max(0, right - left)}px`; }, })), + hide(), ]; } @@ -103,6 +120,7 @@ export const ChartTooltip = React.forwardRef( floatingStyles, placement: resolvedPlacement, isPositioned, + middlewareData, } = useFloating({ open, strategy: 'fixed', @@ -135,14 +153,18 @@ export const ChartTooltip = React.forwardRef( }, [anchorX, anchorY, chartBoxRef, chartWidth, collisionBoundary, collisionPadding, pinned, refs]); const { mounted, transitionProps } = useTransition({ open, ref: popupRef }); + const moving = useMoving(open, active?.datumIndex); + const anchorHidden = middlewareData.hide?.referenceHidden === true; const ownProps = { ...transitionProps, 'data-side': resolvedSide, + ...(moving ? { 'data-moving': '' } : null), + ...(anchorHidden ? { 'data-anchor-hidden': '' } : null), style: { ...floatingStyles, pointerEvents: 'none', - ...(isPositioned ? null : { visibility: 'hidden' }), + ...(isPositioned && !anchorHidden ? null : { visibility: 'hidden' }), ...transitionProps.style, }, children: {open ? content : null}, diff --git a/packages/swingset/src/stories/chart.component.mdx b/packages/swingset/src/stories/chart.component.mdx index ea374167343..f8a3750faed 100644 --- a/packages/swingset/src/stories/chart.component.mdx +++ b/packages/swingset/src/stories/chart.component.mdx @@ -123,8 +123,9 @@ in one stack. ### Highlight `highlight` keeps the matching bars at full strength and dims the rest with an opaque mix toward -`--cl-color-surface`, so grid lines never show through. It is separate from the selection, so the -tooltip still opens and closes as the pointer moves. Without `highlight`, nothing is dimmed. +`--cl-color-surface`, so grid lines never show through. Here the selection drives it: hover a bar, +or move to one with the keyboard, to dim the rest, and leave to clear it. Without `highlight`, +hovering shows the band and tooltip and dims nothing. (null); + const chart = Chart.useBarChart({ + data: growth, + series: growthSeries, + index: getWeek, + onSelectionChange: setHighlight, + highlight, + }); return ( +