Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/mosaic-chart-fluid-tooltip.md
Original file line number Diff line number Diff line change
@@ -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.
14 changes: 12 additions & 2 deletions packages/mosaic/src/components/chart/chart-parts.styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
Expand Down
2 changes: 2 additions & 0 deletions packages/mosaic/src/primitives/chart/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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<void>(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;
Expand Down Expand Up @@ -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(
<Profiler
id='chart'
onRender={() => {
commits++;
}}
>
<Chart onSelectionChange={onSelectionChange} />
</Profiler>,
);
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(<Chart onSelectionChange={onSelectionChange} />);
Expand Down Expand Up @@ -606,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(
<BoundedChart
width={800}
chartWidth={800}
/>,
);
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(
<div
data-testid='scroller'
style={{ height: 300, overflow: 'auto' }}
>
<BoundedChart
width={800}
chartWidth={800}
/>
<div style={{ height: 2000 }} />
</div>,
);
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(
<BoundedChart
Expand Down
26 changes: 24 additions & 2 deletions packages/mosaic/src/primitives/chart/chart-tooltip.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client';

import { autoUpdate, flip, offset, shift, size, useFloating } from '@floating-ui/react';
import { autoUpdate, flip, hide, offset, shift, size, useFloating } from '@floating-ui/react';
import React from 'react';

import { useTransition } from '../hooks/use-transition';
Expand Down Expand Up @@ -35,6 +35,22 @@ export type ChartTooltipProps<TActive extends ChartActive = ChartActive> = Omit<

type BoundaryRef = React.RefObject<HTMLElement | null>;

function useMoving(open: boolean, datumIndex: number | undefined) {
const [openedAt, setOpenedAt] = React.useState<number | undefined>(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;
Expand All @@ -61,6 +77,7 @@ function tooltipMiddleware(
elements.floating.style.maxWidth = `${Math.max(0, right - left)}px`;
},
})),
hide(),
];
}

Expand Down Expand Up @@ -103,6 +120,7 @@ export const ChartTooltip = React.forwardRef<HTMLDivElement, ChartTooltipProps>(
floatingStyles,
placement: resolvedPlacement,
isPositioned,
middlewareData,
} = useFloating({
open,
strategy: 'fixed',
Expand Down Expand Up @@ -135,14 +153,18 @@ export const ChartTooltip = React.forwardRef<HTMLDivElement, ChartTooltipProps>(
}, [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: <Freeze frozen={!open}>{open ? content : null}</Freeze>,
Expand Down
19 changes: 16 additions & 3 deletions packages/mosaic/src/primitives/chart/internal/selection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,22 @@ export function selectionReducer<TSelection extends ChartSelection>(
): SelectionState<TSelection> {
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',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
5 changes: 3 additions & 2 deletions packages/swingset/src/stories/chart.component.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.

<Story
name='Highlight'
Expand Down
18 changes: 12 additions & 6 deletions packages/swingset/src/stories/chart.component.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
'use client';

import { Button } from '@clerk/mosaic/components/button';
import { Chart, type ChartSeries } from '@clerk/mosaic/components/chart';
import { useRef } from 'react';
import { type BarSelection, Chart, type ChartSeries } from '@clerk/mosaic/components/chart';
import { useRef, useState } from 'react';

import type { StoryMeta } from '@/lib/types';

Expand Down Expand Up @@ -288,15 +288,21 @@ export function Palette() {
);
}

const busiestDay = { category: '2026-11-24' };

export function Highlight() {
const chart = Chart.useBarChart({ data: dailyAgents, series: agentsByDay, index: getDay, highlight: busiestDay });
const [highlight, setHighlight] = useState<BarSelection | null>(null);
const chart = Chart.useBarChart({
data: growth,
series: growthSeries,
index: getWeek,
onSelectionChange: setHighlight,
highlight,
});
return (
<Chart.Root
chart={chart}
aria-label='Active agents by day'
aria-label='Weekly active users'
>
<Chart.Legend />
<Chart.Grid />
<Chart.Bars />
<Chart.YAxis />
Expand Down
Loading