An open source design system that's fully customizable and agent ready
TypeScript
[Component Audit] ChartTooltip: keep hover details above modal surfaces (#6394)
Cindy Zhangcb7a565c327b
diff --git a/.github/scripts/story-play-guard.js b/.github/scripts/story-play-guard.jsindex bf9df22e67..195f97943b 100644--- a/.github/scripts/story-play-guard.js+++ b/.github/scripts/story-play-guard.js@@ -38,6 +38,13 @@ const port = Number(getArg('port') || 6010);// Stories whose play assertions are load-bearing. Adding a story here is the// whole cost of promoting its play function into required CI.const TARGETS = [+ {+ component: 'ChartTooltip',+ story: 'charts-chrome-tooltip--modal-layering',+ guards:+ 'ChartTooltip stays continuously open across content-bearing points in ' ++ 'nested Theme/MediaTheme scope above a native modal with nonzero geometry',+ },{component: 'TabList',story: 'core-tablist--full-bleed-geometry',diff --git a/apps/docsite/src/__tests__/data-extraction.test.ts b/apps/docsite/src/__tests__/data-extraction.test.tsindex 42a9895c45..4f5e637780 100644--- a/apps/docsite/src/__tests__/data-extraction.test.ts+++ b/apps/docsite/src/__tests__/data-extraction.test.ts@@ -248,6 +248,7 @@ describe('componentRegistry', () => {'ChartGrid','ChartLegend','ChartSwatch',+ 'ChartTooltip',]);expect(components['@astryxdesign/richtext'].map(comp => comp.name)).toEqual(['RichTextEditor'],diff --git a/apps/storybook/stories/charts/Tooltip.stories.tsx b/apps/storybook/stories/charts/Tooltip.stories.tsxindex 7e4fb28351..cd7d1f658e 100644--- a/apps/storybook/stories/charts/Tooltip.stories.tsx+++ b/apps/storybook/stories/charts/Tooltip.stories.tsx@@ -1,6 +1,9 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+import {useEffect, useRef} from 'react';import type {Meta, StoryObj} from '@storybook/react';+import {expect, waitFor} from 'storybook/test';+import * as stylex from '@stylexjs/stylex';import {Chart,bar,@@ -9,8 +12,31 @@ import {ChartAxis,currency,} from '@astryxdesign/charts';+import {defineTheme, MediaTheme, Theme, useLocale} from '@astryxdesign/core';+import {+ colorVars,+ radiusVars,+ spacingVars,+} from '@astryxdesign/core/theme/tokens.stylex';import {monthlyData} from './_data';-import {useLocale} from '@astryxdesign/core';++const styles = stylex.create({+ modal: {+ inlineSize: 720,+ maxInlineSize: 'calc(100vw - 32px)',+ padding: spacingVars['--spacing-4'],+ borderWidth: 1,+ borderStyle: 'solid',+ borderColor: colorVars['--color-border'],+ borderRadius: radiusVars['--radius-container'],+ backgroundColor: colorVars['--color-background-surface'],+ },+});++const modalLayeringTheme = defineTheme({+ name: 'chart-tooltip-modal-test',+ tokens: {'--color-accent': '#7c3aed'},+});const meta: Meta<typeof Chart> = {title: 'Charts/Chrome/Tooltip',@@ -18,30 +44,156 @@ const meta: Meta<typeof Chart> = {};export default meta;+function TooltipChart({showLineDots = false}: {showLineDots?: boolean}) {+ const locale = useLocale();+ return (+ <Chart+ data={monthlyData}+ xKey="month"+ series={[+ bar('revenue', {color: '#3b82f6', label: 'Revenue', stack: 'x'}),+ bar('costs', {color: '#ef4444', label: 'Costs', stack: 'x'}),+ line('trend', {+ color: '#f59e0b',+ label: 'Trend',+ dots: showLineDots,+ }),+ ]}+ tooltip+ grid={<ChartGrid />}+ axes={+ <>+ <ChartAxis position="bottom" />+ <ChartAxis position="left" tickFormat={currency('$', locale)} />+ </>+ }+ height={320}+ />+ );+}+/** Hover the chart: a grouped tooltip shows every series value at that x, with a* column highlight for bars and hover dots on lines. */export const Default: StoryObj = {- render: () => {- const locale = useLocale();- return (- <Chart- data={monthlyData}- xKey="month"- series={[- bar('revenue', {color: '#3b82f6', label: 'Revenue', stack: 'x'}),- bar('costs', {color: '#ef4444', label: 'Costs', stack: 'x'}),- line('trend', {color: '#f59e0b', label: 'Trend'}),- ]}- tooltip- grid={<ChartGrid />}- axes={- <>- <ChartAxis position="bottom" />- <ChartAxis position="left" tickFormat={currency('$', locale)} />- </>- }- height={320}- />+ render: () => <TooltipChart />,+};++function ModalLayeringFixture() {+ const dialogRef = useRef<HTMLDialogElement>(null);++ useEffect(() => {+ const dialog = dialogRef.current;+ if (dialog && !dialog.open) {+ dialog.showModal();+ }+ return () => {+ if (dialog?.open) {+ dialog.close();+ }+ };+ }, []);++ return (+ <Theme theme={modalLayeringTheme} mode="light">+ <MediaTheme mode="dark">+ <dialog+ ref={dialogRef}+ aria-label="Chart tooltip layering test"+ {...stylex.props(styles.modal)}>+ <TooltipChart showLineDots />+ </dialog>+ </MediaTheme>+ </Theme>+ );+}++/**+ * Keeps the chart inside nested Theme/MediaTheme scopes and a native modal,+ * then opens its tooltip after the modal. The play assertions prove the host+ * stays in those scopes, remains continuously open across content-bearing+ * points, and becomes a later browser top-layer entry rather than a high-z-index+ * portal hidden behind the dialog.+ */+export const ModalLayering: StoryObj = {+ render: () => <ModalLayeringFixture />,+ play: async ({canvasElement}) => {+ const dialog = canvasElement.querySelector('dialog');+ await waitFor(() => expect(dialog?.matches(':modal')).toBe(true));++ const getEventSurface = () =>+ canvasElement.querySelector<SVGRectElement>(+ 'svg rect[fill="transparent"]',+ );+ const getTooltip = () =>+ document.querySelector<HTMLElement>('[role="tooltip"]');+ await waitFor(() => {+ expect(getEventSurface()).not.toBeNull();+ expect(getTooltip()).not.toBeNull();+ });+ const eventSurface = getEventSurface();+ const tooltip = getTooltip();+ if (!eventSurface || !tooltip) {+ throw new Error('Chart event surface or tooltip did not render');+ }++ const layer = tooltip.parentElement;+ if (!layer) {+ throw new Error('Chart tooltip Layer host did not render');+ }+ const toggleStates: string[] = [];+ const recordToggle = (event: Event) => {+ toggleStates.push((event as ToggleEvent).newState);+ };+ layer.addEventListener('beforetoggle', recordToggle);++ await waitFor(() => {+ expect(eventSurface.getBoundingClientRect().width).toBeGreaterThan(0);+ expect(+ canvasElement.querySelectorAll<SVGCircleElement>(+ 'svg g[clip-path] circle',+ ).length,+ ).toBeGreaterThanOrEqual(2);+ });+ const points = canvasElement.querySelectorAll<SVGCircleElement>(+ 'svg g[clip-path] circle',);+ const eventRect = eventSurface.getBoundingClientRect();+ const moveTo = (point: SVGCircleElement) => {+ const pointRect = point.getBoundingClientRect();+ eventSurface.dispatchEvent(+ new PointerEvent('pointermove', {+ bubbles: true,+ clientX: pointRect.left + pointRect.width / 2,+ clientY: eventRect.top + eventRect.height / 2,+ pointerType: 'mouse',+ }),+ );+ };++ moveTo(points[0]);+ await waitFor(() => {+ expect(tooltip.textContent).toContain('Jan');+ expect(layer.matches(':popover-open')).toBe(true);+ });+ expect(toggleStates).toEqual(['open']);++ moveTo(points[1]);+ await waitFor(() => {+ expect(tooltip.textContent).toContain('Feb');+ expect(layer.matches(':popover-open')).toBe(true);+ });+ await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));++ expect(toggleStates).toEqual(['open']);+ expect(dialog?.matches(':modal')).toBe(true);+ expect(+ layer.closest('[data-astryx-theme="chart-tooltip-modal-test"]'),+ ).not.toBeNull();+ expect(layer.closest('[data-astryx-media="dark"]')).not.toBeNull();+ expect(getComputedStyle(layer).zIndex).toBe('auto');+ const layerRect = layer.getBoundingClientRect();+ expect(layerRect.width).toBeGreaterThan(0);+ expect(layerRect.height).toBeGreaterThan(0);+ layer.removeEventListener('beforetoggle', recordToggle);},};diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex 32a95243e6..d78ef6a965 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -131,6 +131,11 @@"path": "components/charts/chart-swatch","aliases": []},+ {+ "name": "component-charts-chart-tooltip",+ "path": "components/charts/chart-tooltip",+ "aliases": []+ },{"name": "component-chat-composer","path": "components/chat-composer",diff --git a/packages/charts/src/ChartTooltip.doc.mjs b/packages/charts/src/ChartTooltip.doc.mjsnew file mode 100644index 0000000000..f11a573436--- /dev/null+++ b/packages/charts/src/ChartTooltip.doc.mjs@@ -0,0 +1,167 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */++export const docs = {+ name: 'ChartTooltip',+ displayName: 'Chart Tooltip',+ group: 'Charts',+ category: 'Data Visualization',+ isHiddenFromOverview: true,+ keywords: [+ 'chart',+ 'tooltip',+ 'hover',+ 'series',+ 'crosshair',+ 'data visualization',+ ],++ usage: {+ description:+ 'ChartTooltip shows grouped values for the chart position nearest the pointer. Use Chart’s tooltip prop or its configuration object for the standard integration; direct composition remains available when you need explicit child composition.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'Treat tooltip content as supplemental pointer detail. Give the parent Chart an accessible name and preserve its equivalent data table or another complete data view.',+ },+ {+ guidance: true,+ description:+ 'When composing ChartTooltip directly, pass the same series definitions used by Chart so rows, swatches, and hover dots stay aligned with the plotted marks.',+ },+ {+ guidance: false,+ description:+ 'Put information required to understand the chart only in the tooltip. The current interaction is pointer-driven and does not establish a focus trigger or aria-describedby relationship.',+ },+ {+ guidance: false,+ description:+ 'Render interactive controls inside the custom tooltip body. The surface is presentational and does not accept pointer input.',+ },+ ],+ accessibility: [+ {+ name: 'Supplemental detail',+ category: 'Content',+ criterion: '1.1.1 Non-text Content',+ requirement: 'Required on the parent Chart',+ states: ['All'],+ description:+ 'The tooltip supplements the parent Chart. It does not replace the Chart accessible name, hidden data table, summary, or another equivalent data view.',+ },+ {+ name: 'Tooltip semantics',+ category: 'Semantics',+ criterion: '1.3.1 Info and Relationships',+ requirement: 'Built in with a documented limitation',+ states: ['Hovered'],+ description:+ 'The visible card uses role tooltip. Chart does not currently expose a focusable data-point trigger or an aria-describedby relationship, so required information must remain available outside this pointer-only surface.',+ },+ ],+ anatomy: [+ {+ name: 'Layer host',+ required: true,+ description:+ 'Layer host mounted under the chart’s nearest HTML container so nested Theme and MediaTheme scopes remain inherited. It uses the browser top layer when the Popover API is available and otherwise keeps the card visible through Layer’s reduced fallback.',+ },+ {+ name: 'Tooltip card',+ required: true,+ description:+ 'Non-interactive surface containing the current x value and series values.',+ },+ {+ name: 'Series row',+ required: false,+ description:+ 'For multi-series charts, a decorative swatch, visible label, and value.',+ },+ {+ name: 'Hover indicator',+ required: false,+ description:+ 'Band highlight for bar series on a band scale, or a vertical crosshair otherwise.',+ },+ {+ name: 'Hover dot',+ required: false,+ description:+ 'Point marker for each eligible non-bar series at the hovered data index.',+ },+ ],+ },++ props: [+ {+ name: 'series',+ type: 'readonly SeriesDef[]',+ description:+ 'Series definitions used to derive tooltip rows and hover dots. Chart supplies this automatically through its tooltip prop; direct composition should pass the same array used by Chart.',+ default: '[]',+ },+ {+ name: 'render',+ type: '(xValue: unknown, seriesValues: TooltipSeriesValue[]) => ReactNode',+ description:+ 'Replaces the default card body. Return null to hide the card while preserving enabled hover indicators and dots.',+ default: 'Default grouped value content',+ },+ {+ name: 'hoverIndicator',+ type: 'boolean',+ description:+ 'Shows a band highlight for bar series on a band scale, or a vertical crosshair for other series.',+ default: 'true',+ },+ {+ name: 'showHoverDots',+ type: 'boolean',+ description:+ 'Shows a point marker for each eligible non-bar series at the hovered index.',+ default: 'true',+ },+ {+ name: 'placement',+ type: "'auto' | 'right' | 'left' | 'top'",+ description:+ 'Selects one of the shipped placement algorithms. The current implementation positions from the hovered x coordinate and the plot top; whether placement should instead be point-relative on both axes remains unresolved. Custom renderers own their content sizing.',+ default: "'auto'",+ },+ ],++ examples: [+ {+ label: 'Generated chart tooltip',+ code: `import {Chart, bar, line} from '@astryxdesign/charts';++<Chart+ data={monthlyRevenue}+ xKey="month"+ series={[+ bar('revenue', {label: 'Revenue'}),+ line('forecast', {label: 'Forecast'}),+ ]}+ tooltip+/>;`,+ },+ {+ label: 'Direct composition',+ code: `import {Chart, ChartTooltip, line} from '@astryxdesign/charts';++const series = [line('revenue', {label: 'Revenue'})];++<Chart data={monthlyRevenue} xKey="month" series={series}>+ <ChartTooltip+ series={series}+ placement="top"+ showHoverDots={false}+ />+</Chart>;`,+ },+ ],+};diff --git a/packages/charts/src/ChartTooltip.spec.md b/packages/charts/src/ChartTooltip.spec.mdnew file mode 100644index 0000000000..fdec5aa7f5--- /dev/null+++ b/packages/charts/src/ChartTooltip.spec.md@@ -0,0 +1,240 @@+---+schema_version: 3+template_version: 5+kind: component+id: component:ChartTooltip+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+owners: [cixzhang]+review_triggers: [public-api, behavior, layout, theming, accessibility]+verified_by:+ [+ packages/charts/src/ChartTooltip.test.tsx,+ apps/storybook/stories/charts/Tooltip.stories.tsx,+ ]+modules: []+families: []+design_specs: []+architecture:+ [+ architecture:component-test-sufficiency,+ architecture:component-theming-surface,+ architecture:theme-application,+ architecture:knowledge-contracts,+ architecture:layer-runtime,+ ]+contributing: []+system_specs:+ [spec:AST-002, spec:AST-003, spec:AST-013, spec:AST-027, spec:AST-029]+---++# ChartTooltip component contract++## Contract at a glance++| Area | Contract |+| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | No API shape or default changes. This draft records the shipped grouped-content, indicator, dot, custom-render, and placement surfaces. |+| Behavior | The nearest pointer x selects one datum; the card, enabled SVG indicator, and eligible dots update together. A visible Layer remains open when both the prior and next selections produce content. The card stays in the nearest chart HTML scope and uses Layer fixed mode. |+| End-user impact | Pointer users keep the chart's nested Theme/MediaTheme treatment; supported browsers also keep details above clipping or modal top-layer UI, while the reduced fallback preserves ordinary visibility. |+| Builder impact | None. `Chart tooltip`, tooltip configuration objects, and direct `ChartTooltip` composition continue to use the same props and defaults. |+| Compatibility/readiness | Canary-compatible behavioral repair. This observational draft is non-authoritative; placement meaning, focus association, and future theming targets remain unresolved owner choices. |+| Review checks | Reject a document-body host, premature custom-content open, changed API/default, lost pointer cleanup, duplicate custom-render invocation, invalid SVG coordinates, or any claim that open questions are settled. |+| Governing rules | `spec:AST-027/FR7–FR8`, `architecture:layer-runtime/INV1–INV3`, `architecture:theme-application/INV1–INV3`, `spec:AST-013/FR7–FR10`, `architecture:component-test-sufficiency/INV1–INV11`, and `spec:AST-029/DEC-4`. |++This table is a review projection; the body below is authoritative.++## Intent++ChartTooltip renders supplemental grouped values for the chart datum nearest the+pointer. It owns the pointer-selected card, its viewport positioning, optional+crosshair or band highlight, and eligible hover dots. Chart owns data, scales,+plot geometry, pointer dispatch, accessible naming, and its supported equivalent+data view.++## Compatibility and migration++- Released default preserved: yes at the canary surface; the package has no stable release.+- Compatibility class: no public API or default change; the card moves from a fixed body portal with a page-level z-index to the shared fixed Layer runtime.+- Controlled/uncontrolled behavior: not applicable; Chart's pointer stream owns the active index.+- Migration decision: none; `spec:AST-027/FR7–FR8` already requires the Layer migration.++Consumer migration instructions belong in consumer docs and release notes.++## Ownership boundary++**Owns**++- Selecting tooltip content from the nearest chart pointer event.+- Deriving ordered visible-series rows for the hovered datum.+- Rendering the default card or caller-supplied card content.+- Hosting the Layer under the nearest chart HTML container so nested Theme and MediaTheme scopes remain inherited.+- Positioning and viewport-clamping the card coordinates through Layer fixed mode; custom renderers own their content dimensions.+- Rendering the current crosshair or bar-band indicator and eligible hover dots.+- Unsubscribing from Chart's pointer stream when the component unmounts.++**Does not own / non-goals**++- Chart data, scales, plot geometry, or pointer-event generation — owned by `component:Chart`.+- Product-specific value formatting, series labels, and colors — owned by the product callsite and series definitions.+- The chart's accessible name, hidden data table, summary, or another equivalent non-pointer data view — owned by `component:Chart` and the product callsite.+- A new focusable data-point model or tooltip trigger relationship; those require an owner decision under `spec:AST-002` and `spec:AST-003`.++## Public concepts++| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |+| ---------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | ----------------------------------------- | ----------------------- | -------------------------------------------------------------- | ------------ | -------------------------------------------------------------------------------------------- |+| Series source | caller array or omitted | Supplies row labels, values, colors, mark types, and hover-dot eligibility. | Every ChartTooltip | empty array | product callsite | experimental | Utility and unresolved series are filtered; missing and non-finite row values are preserved. |+| Card content | default body; custom React node; custom `null` | Shows grouped details or suppresses only the card. | Hovered datum | default grouped content | `component:ChartTooltip` | experimental | A custom `null` never opens Layer and keeps enabled SVG indicators and dots. |+| Hover indicator | enabled or disabled; bar-band or vertical crosshair | Marks the active x position inside the plot. | Valid hovered datum | enabled | `component:ChartTooltip` | experimental | Invalid or non-finite chart coordinates suppress the mark. |+| Hover dots | enabled or disabled; one per eligible resolved non-bar series | Marks each eligible series point at the active index. | Valid finite resolved points | enabled | `component:ChartTooltip` | experimental | Missing and non-finite resolved points are skipped. |+| Card placement | `auto`, `right`, `left`, `top` | Selects horizontal placement from the hovered x coordinate and the current vertical rule. | Visible card | `auto` | `component:ChartTooltip` | experimental | Unknown values are rejected by TypeScript. |+| Layer host | nearest chart HTML container | Preserves the nearest Theme and MediaTheme CSS scopes while remaining valid HTML outside SVG. | Browser render | nearest chart container | `architecture:layer-runtime`; `architecture:theme-application` | settled | A document-body host loses nested CSS scope. |+| Layer visibility | closed; browser top-layer open; reduced-fallback visible | Uses native top-layer stacking when supported; otherwise preserves ordinary card visibility. | Browser render | closed | `architecture:layer-runtime` | settled | The reduced fallback does not claim top-layer stacking. |++## Behavioral and layout contract++Draft requirements identify their basis so observed code is not mistaken for an+intentional decision. A `current` contract contains no unresolved rows.++| ID | Candidate invariant | Basis | Draft review state |+| --- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ------------------ |+| FR1 | Chart's `tooltip` shorthand MUST inject the chart series; direct composition currently requires the caller to pass the same series array when rows and dots are wanted. | implementation, types, docs, and focused tests | verify |+| FR2 | The nearest pointer event MUST select one data index; a present-content-to-present-content change MUST replace content without closing an already-open Layer. Leaving the plot, selecting a stale index, or selecting content suppressed by custom `null` MUST keep Layer closed or hide an already-open card, and a later present-content index MUST be able to reveal it again. | `spec:AST-013/FR8–FR10`; `architecture:component-test-sufficiency/INV4–INV5`; implementation and focused/browser tests | verify |+| FR3 | The default card MUST show the x value and either one bare value or one labelled row per visible resolved series. A custom renderer MUST receive the x value and ordered rows once per render and MAY return `null` without opening Layer. | implementation and focused tests | verify |+| FR4 | Enabled indicators MUST render a band highlight for bar series on a band scale and a vertical crosshair otherwise. Enabled dots MUST exclude bars and non-finite or missing resolved points. | implementation and focused tests | verify |+| FR5 | `auto` currently starts to the right and flips left on inline overflow; explicit `right`, `left`, and `top` use the hovered x coordinate, while every mode currently uses the plot top as its vertical origin and clamps the resulting coordinates. Custom-rendered content keeps its caller-owned dimensions. | implementation and partial focused tests | human decision |+| FR6 | The host MUST remain under the nearest chart HTML container to preserve Theme and MediaTheme scope and MUST use `useLayer({mode: 'fixed'})`; supported browsers receive native top-layer promotion, while browsers without Popover API use Layer's reduced visibility fallback. A document-body host or numeric z-index is not a substitute. | `architecture:theme-application/INV1–INV3`; `spec:AST-027/FR7–FR8`; `architecture:layer-runtime/INV1–INV3`; `spec:AST-013/FR7–FR8` | settled |+| FR7 | The component MUST subscribe once per active callback identity and MUST release that subscription on unmount. | implementation and focused test | verify |+| FR8 | Server rendering MUST omit the browser-only layer without reading a portal target; SVG indicators remain render-derived. | `spec:AST-013/FR9–FR10`; implementation and focused server-render test | verify |++### Allowed variation++- **AV1 — Series content.** Callers may choose labels, colors, order, values, and custom rendered card content through existing public inputs.+- **AV2 — Chart geometry.** Chart may change plot dimensions and scale output; ChartTooltip follows the supplied pointer coordinates and clamps its card coordinates. Custom renderers own their content dimensions.+- **AV3 — Supplemental surface.** Products may omit the tooltip when the chart's non-pointer presentation already supplies sufficient detail.++### Representative states++| State | Required invariant | Allowed variation |+| ---------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------ |+| Present-content transition | Card content and position update while the same Layer host remains continuously open. | The selected values and resulting coordinates vary. |+| Initial / pointer leave | Card is closed and no stale card content is exposed. | SVG indicators are absent. |+| Stale index | Layer does not open for a pointer index absent from current data. | Prior valid content may already have been closed. |+| Single series | Card shows x value plus one value. | Caller label, color, and value vary. |+| Multiple series | Card preserves the derived visible-series order and labels each row. | Number and type of rows vary. |+| Custom content | Renderer receives the current x value and rows. | Any non-interactive React content may be returned. |+| Custom `null` | Layer never opens while enabled plot indicators remain. | Indicator and dot options remain independently configurable. |+| Bar on band scale | Band highlight replaces the crosshair; bars receive no hover dot. | Band geometry follows the scale. |+| Line, area, or dot | Crosshair and eligible finite hover dots follow the selected index. | Series paint and resolved coordinates vary. |+| Nested Theme / MediaTheme | Layer host remains a DOM descendant of the nearest active scopes. | Theme name and media mode vary. |+| Clipped or modal composition | Layer host is an open native popover above clipping and top-layer peers. | Surrounding clipping and modal geometry vary. |+| Reduced Popover fallback | Host starts hidden, opens on a valid hover, and hides again without a false visible state. | Native top-layer enhancement is unavailable. |+| Server render | No portal or browser layer is emitted. | Rendered SVG fragment may be empty without pointer state. |++### Transformation and precedence order++- **ORD1 — Pointer selection.** Receive Chart pointer event → resolve nearest data index → derive datum and rows → resolve custom or default card content → preserve an open Layer when the next selection also produces content, otherwise keep Layer closed for absent content or show it for present content → measure final card geometry and clamp its coordinates.+- **ORD2 — Indicator selection.** Check `hoverIndicator` → prefer bar-band representation when any bar uses a band scale → otherwise resolve the crosshair x → suppress non-finite output.+- **ORD3 — Dot selection.** Check `showHoverDots` → retain eligible non-bar series → find the current resolved point → suppress missing or non-finite points.++### Performance and resources++- **PR1 — Pointer render boundary.** Pointer movement within one resolved data index SHOULD NOT force a React commit when the computed card position is unchanged.+- **PR2 — Subscription ownership.** ChartTooltip owns exactly one current pointer subscription and MUST release it when the subscription identity changes or the component unmounts.+- **PR3 — Render callback.** A custom card renderer MUST NOT be invoked twice for one React render merely to decide visibility.++## Accessibility contract++- **AR1 — Supplemental information.** Tooltip-only content does not replace Chart's accessible name, supported hidden data table, summary, or another complete data view.+- **AR2 — Current semantics.** The card currently exposes `role="tooltip"` and remains non-interactive. This draft does not assert that the pointer-only trigger path completes the WAI-ARIA tooltip pattern.+- **AR3 — Association gap.** Keyboard exposure and an `aria-describedby` owner remain unresolved because Chart has no focusable data-point trigger. An audit MUST NOT invent that interaction or API without owner approval.++## Design relationships++| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |+| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | -------------- | ------------------ |+| Layer host | Stay under the nearest chart HTML scope; use native top-layer stacking when available and preserve ordinary visibility in the reduced fallback. | `architecture:theme-application/INV1–INV3`; `spec:AST-027/FR7–FR8`; `spec:AST-013/FR7–FR8` | overlay | FR6 |+| Tooltip card | Present grouped supplemental detail without accepting pointer interaction. | unsettled; no current design record is linked | supporting | FR3, AR1–AR3 |+| Series row | Associate one visible label and value with its decorative series swatch. | observed implementation | supporting | FR3 |+| Hover indicator | Mark the active x region without changing the chart's data or accessible name. | unsettled; no current design record is linked | supporting | FR4 |+| Hover dot | Echo an eligible series point at the selected index. | unsettled; no current design record is linked | supporting | FR4 |++### Theming anatomy++<!-- anatomy-theming:v1 -->++```json+{+ "Layer host": {+ "none": {+ "reason": "unsettled: the host paints the card with semantic tokens but no current contract decides whether ChartTooltip needs a public target."+ }+ },+ "Tooltip card": {+ "none": {+ "reason": "intentional: the semantic role-only child adds no component-owned paint; the Layer host owns the card chrome."+ }+ },+ "Series row": {+ "none": {+ "reason": "intentional: shared Layout, Text, and ChartSwatch components own the rendered row surfaces."+ }+ },+ "Hover indicator": {+ "none": {+ "reason": "unsettled: semantic tokens paint the current SVG mark but no current contract selects public theme reachability."+ }+ },+ "Hover dot": {+ "none": {+ "reason": "unsettled: series-owned paint and current fixed geometry have no approved public theme target."+ }+ }+}+```++## Family and system relationships++- No current family or design record governs ChartTooltip.+- `architecture:layer-runtime` and `spec:AST-027/FR7–FR8` require fixed Layer composition and browser top-layer promotion where supported.+- `architecture:theme-application/INV1–INV3` requires the host to remain in the nearest Theme and MediaTheme CSS scope rather than portal to the document body.+- `architecture:component-test-sufficiency` owns rational public-state partitions and observable assertions.+- `architecture:component-theming-surface` owns anatomy-to-target disposition; this draft records current absence without deciding future themeability.+- `architecture:knowledge-contracts` keeps consumer syntax in `ChartTooltip.doc.mjs` and observed behavior in this draft component record.+- `spec:AST-013/FR7–FR10` owns the reduced Popover fallback, server-render boundary, and real-browser evidence requirement.+- `spec:AST-002` owns any future public API or compatibility decision.+- `spec:AST-003` owns any future passive-overlay coordination model.+- `spec:AST-029/DEC-4` owns red-before-green behavior remediation; the broader Night Watch contract owns this observational backfill, finite evidence inventory, objective remediation, and fail-closed readiness report.++## Verification map++| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------ | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- |+| FR1, FR3–FR4 | `ChartTooltip.test.tsx`; Tooltip Storybook fixture | single, multi, custom, null, stale index, bar, line, missing values | A stale/custom-null state opens Layer, a public option changes output, or a missing/non-finite point leaks invalid SVG. | `audit:ChartTooltip/behavior` |+| FR2 | present-content continuity focused test; modal Storybook play assertion | initial open, present→present, leave→reopen, open→stale→valid, content→custom-null→content | A present-content change closes/reopens Layer, leaves old content, or prevents later present content after a closed state. | `audit:ChartTooltip/behavior` |+| FR5 | focused placement test; source review | right; other modes remain gaps | Positioning changes without an owner ruling or evidence for every public value. | `audit:ChartTooltip/api-behavior` |+| FR6 | red/green Layer host, nested-theme, and reduced-fallback tests; modal Storybook play assertion | nested Theme/MediaTheme, closed, fallback open/closed, native modal hover | A document-body host loses local theme scope, native top-layer state is absent, or fallback visibility is false. | `audit:ChartTooltip/layering` |+| FR7 | focused lifecycle test | mount and unmount | A pointer listener remains after unmount. | `audit:ChartTooltip/code-health` |+| FR8 | `renderToString` focused test | server render | Server evaluation reads `document` or emits the browser-only card. | `audit:ChartTooltip/runtime` |+| AR1–AR3 | Chart accessibility tests; focused axe; owner review pending | small-data alternative and hovered card | Tooltip content becomes the only data path or draft semantics are treated as policy. | `audit:ChartTooltip/accessibility` |++## Decision log++None. This draft records observed behavior plus the Layer and theme-locality corrections+already required by current shared authority; it does not approve new ChartTooltip+policy.++## Open questions++- **OQ1 — Placement meaning.** Should `top`, `left`, `right`, and `auto` be relative to the hovered point in both axes, or should the public description name the current plot-top vertical origin? (`human-api`)+- **OQ2 — Keyboard and tooltip association.** Should Chart expose a focusable data-point trigger and `aria-describedby` relationship, or should this surface use different semantics while the data table remains the keyboard/AT path? (`human-api`)+- **OQ3 — Theming reachability.** Should the Layer host or any SVG indicator become a stable public theme target? (`human-api`)++## Content boundary++This file does not duplicate consumer prop tables/examples, current audit results,+implementation steps, or shared system rules. It links to their owners.diff --git a/packages/charts/src/ChartTooltip.test.tsx b/packages/charts/src/ChartTooltip.test.tsxindex fe6c820ec3..3926b314c0 100644--- a/packages/charts/src/ChartTooltip.test.tsx+++ b/packages/charts/src/ChartTooltip.test.tsx@@ -14,7 +14,9 @@import {describe, it, expect, vi} from 'vitest';import {render, act} from '@testing-library/react';+import {renderToString} from 'react-dom/server';import {scaleLinear, scaleBand} from 'd3-scale';+import {MediaTheme, Theme, defineTheme} from '@astryxdesign/core';import {ChartTooltip} from './ChartTooltip';import {ChartProvider} from './ChartContext';import type {@@ -30,6 +32,15 @@ const DATA = [{month: 'Mar', sales: 5, profit: 4},];+const OUTER_THEME = defineTheme({+ name: 'chart-tooltip-outer-test',+ tokens: {'--color-accent': '#112233'},+});+const INNER_THEME = defineTheme({+ name: 'chart-tooltip-inner-test',+ tokens: {'--color-accent': '#445566'},+});+const SALES_POINTS: ResolvedPoint[] = [{px: 50, py: 120, py0: 200, dataIndex: 0},{px: 250, py: 40, py0: 200, dataIndex: 1},@@ -97,7 +108,7 @@ function renderTooltip() {return render(<ChartProvider value={harness.ctx}>- <svg>+ <svg ref={harness.ctx.svgRef}><g><ChartTooltip series={[makeSeries()]} {...props} /></g>@@ -113,6 +124,19 @@ const hoverAt = (index: number): ChartPointerEvent => ({active: false,});+const staleHover: ChartPointerEvent = {+ x: 0,+ y: 0,+ nearest: {+ px: 50,+ py: 120,+ py0: 200,+ dataIndex: 99,+ seriesKey: 'sales',+ },+ active: false,+};+const pointerLeave: ChartPointerEvent = {x: -1,y: -1,@@ -121,18 +145,50 @@ const pointerLeave: ChartPointerEvent = {};const card = () => document.querySelector('[role="tooltip"]') as HTMLElement;+const layerHost = () => card().parentElement as HTMLElement;describe('ChartTooltip card', () => {- it('portals an initially empty tooltip card into document.body', () => {+ it('portals the fixed Layer host to the nearest chart HTML container', () => {const harness = makeHarness();const {container} = renderTooltip(harness);+ const svg = container.querySelector('svg');+expect(card()).not.toBeNull();- expect(card().parentElement).toBe(document.body);- // The card lives outside the chart subtree.- expect(container.querySelector('[role="tooltip"]')).toBeNull();+ expect(layerHost()).toHaveAttribute('popover', 'manual');+ expect(layerHost().parentElement).toBe(svg?.parentElement);+ // The card keeps local CSS inheritance without becoming invalid SVG.+ expect(svg?.contains(card())).toBe(false);expect(card().textContent).toBe('');});+ it('keeps the Layer host inside nested Theme and MediaTheme scopes', () => {+ const harness = makeHarness();+ const {container} = render(+ <Theme theme={OUTER_THEME}>+ <Theme theme={INNER_THEME}>+ <MediaTheme mode="dark">+ <ChartProvider value={harness.ctx}>+ <svg ref={harness.ctx.svgRef}>+ <g>+ <ChartTooltip series={[makeSeries()]} />+ </g>+ </svg>+ </ChartProvider>+ </MediaTheme>+ </Theme>+ </Theme>,+ );++ const innerTheme = container.querySelector(+ '[data-astryx-theme="chart-tooltip-inner-test"]',+ );+ const mediaTheme = container.querySelector('[data-astryx-media="dark"]');+ expect(innerTheme).not.toBeNull();+ expect(mediaTheme).not.toBeNull();+ expect(innerTheme?.contains(layerHost())).toBe(true);+ expect(mediaTheme?.contains(layerHost())).toBe(true);+ });+it('shows the hovered x value and the bare value for a single series', () => {const harness = makeHarness();renderTooltip(harness);@@ -167,15 +223,162 @@ describe('ChartTooltip card', () => {});it('reveals the card on hover and hides it again when the pointer leaves', () => {+ const showSpy = vi.spyOn(HTMLElement.prototype, 'showPopover');+ const hideSpy = vi.spyOn(HTMLElement.prototype, 'hidePopover');const svgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');const harness = makeHarness({svgRef: {current: svgEl}});- renderTooltip(harness);- harness.dispatch(hoverAt(0));- expect(card().style.display).toBe('block');+ try {+ renderTooltip(harness);+ harness.dispatch(hoverAt(0));+ expect(showSpy).toHaveBeenCalledOnce();++ harness.dispatch(pointerLeave);+ expect(hideSpy).toHaveBeenCalledOnce();+ } finally {+ showSpy.mockRestore();+ hideSpy.mockRestore();+ }+ });++ it('keeps the Layer open while moving between valid data points', () => {+ const showSpy = vi.spyOn(HTMLElement.prototype, 'showPopover');+ const hideSpy = vi.spyOn(HTMLElement.prototype, 'hidePopover');+ const harness = makeHarness();++ try {+ renderTooltip(harness);+ harness.dispatch(hoverAt(0));+ const openHost = layerHost();+ expect(card().textContent).toContain('Jan');++ harness.dispatch(hoverAt(1));++ expect(layerHost()).toBe(openHost);+ expect(card().textContent).toContain('Feb');+ expect(showSpy).toHaveBeenCalledOnce();+ expect(hideSpy).not.toHaveBeenCalled();++ harness.dispatch(pointerLeave);+ expect(hideSpy).toHaveBeenCalledOnce();++ harness.dispatch(hoverAt(2));+ expect(layerHost()).toBe(openHost);+ expect(card().textContent).toContain('Mar');+ expect(showSpy).toHaveBeenCalledTimes(2);+ } finally {+ showSpy.mockRestore();+ hideSpy.mockRestore();+ }+ });++ it('measures native Popover geometry after revealing the first card', () => {+ const showSpy = vi.spyOn(HTMLElement.prototype, 'showPopover');+ const widthSpy = vi+ .spyOn(HTMLElement.prototype, 'offsetWidth', 'get')+ .mockImplementation(function (this: HTMLElement) {+ return this.hasAttribute('popover') && this.style.display !== 'none'+ ? 120+ : 0;+ });+ const heightSpy = vi+ .spyOn(HTMLElement.prototype, 'offsetHeight', 'get')+ .mockImplementation(function (this: HTMLElement) {+ return this.hasAttribute('popover') && this.style.display !== 'none'+ ? 40+ : 0;+ });+ const harness = makeHarness();++ try {+ renderTooltip(harness, {placement: 'left'});+ harness.dispatch(hoverAt(1));++ expect(showSpy).toHaveBeenCalledOnce();+ // svgLeft(0) + marginLeft(48) + px(250) - width(120) - gap(8)+ expect(layerHost().style.left).toBe('170px');+ } finally {+ showSpy.mockRestore();+ widthSpy.mockRestore();+ heightSpy.mockRestore();+ }+ });++ it('keeps the non-Popover fallback hidden until hover', async () => {+ const showDescriptor = Object.getOwnPropertyDescriptor(+ HTMLElement.prototype,+ 'showPopover',+ );+ const hideDescriptor = Object.getOwnPropertyDescriptor(+ HTMLElement.prototype,+ 'hidePopover',+ );+ Object.defineProperty(HTMLElement.prototype, 'showPopover', {+ configurable: true,+ value: undefined,+ writable: true,+ });+ Object.defineProperty(HTMLElement.prototype, 'hidePopover', {+ configurable: true,+ value: undefined,+ writable: true,+ });+ const svgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');+ const harness = makeHarness({svgRef: {current: svgEl}});++ try {+ renderTooltip(harness);+ expect(layerHost().style.display).toBe('none');++ harness.dispatch(hoverAt(0));+ const openHost = layerHost();+ expect(openHost.style.display).not.toBe('none');+ expect(card().textContent).toContain('Jan');++ const priorStyles: Array<string | null> = [];+ const observer = new MutationObserver(records => {+ for (const record of records) {+ priorStyles.push(record.oldValue);+ }+ });+ observer.observe(openHost, {+ attributeFilter: ['style'],+ attributeOldValue: true,+ attributes: true,+ });- harness.dispatch(pointerLeave);- expect(card().style.display).toBe('none');+ harness.dispatch(hoverAt(1));+ await Promise.resolve();+ observer.disconnect();+ expect(layerHost()).toBe(openHost);+ expect(card().textContent).toContain('Feb');+ expect(openHost.style.display).not.toBe('none');+ expect(priorStyles.some(style => style?.includes('display: none'))).toBe(+ false,+ );++ harness.dispatch(pointerLeave);+ expect(openHost.style.display).toBe('none');+ } finally {+ if (showDescriptor) {+ Object.defineProperty(+ HTMLElement.prototype,+ 'showPopover',+ showDescriptor,+ );+ } else {+ Reflect.deleteProperty(HTMLElement.prototype, 'showPopover');+ }+ if (hideDescriptor) {+ Object.defineProperty(+ HTMLElement.prototype,+ 'hidePopover',+ hideDescriptor,+ );+ } else {+ Reflect.deleteProperty(HTMLElement.prototype, 'hidePopover');+ }+ }});it('pins the card beside the hovered point for placement="right"', () => {@@ -185,22 +388,47 @@ describe('ChartTooltip card', () => {harness.dispatch(hoverAt(1));// jsdom rects are zero, so left = svgLeft(0) + margin.left(48) + px(250)// + the 8px gap.- expect(card().style.display).toBe('block');- expect(card().style.left).toBe('306px');+ expect(layerHost().style.left).toBe('306px');});- it('hides the card when the hovered index no longer exists in data', () => {- const svgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');- const harness = makeHarness({svgRef: {current: svgEl}});- renderTooltip(harness);- harness.dispatch({- x: 0,- y: 0,- nearest: {px: 50, py: 120, py0: 200, dataIndex: 99, seriesKey: 'sales'},- active: false,- });- expect(card().textContent).toBe('');- expect(card().style.display).toBe('none');+ it('does not open the card when the hovered index no longer exists in data', () => {+ const showSpy = vi.spyOn(HTMLElement.prototype, 'showPopover');+ const hideSpy = vi.spyOn(HTMLElement.prototype, 'hidePopover');+ const harness = makeHarness();++ try {+ renderTooltip(harness);+ harness.dispatch(staleHover);+ expect(card().textContent).toBe('');+ expect(showSpy).not.toHaveBeenCalled();+ expect(hideSpy).not.toHaveBeenCalled();+ } finally {+ showSpy.mockRestore();+ hideSpy.mockRestore();+ }+ });++ it('closes an open card for a stale index and reopens for later valid data', () => {+ const showSpy = vi.spyOn(HTMLElement.prototype, 'showPopover');+ const hideSpy = vi.spyOn(HTMLElement.prototype, 'hidePopover');+ const harness = makeHarness();++ try {+ renderTooltip(harness);+ harness.dispatch(hoverAt(0));+ expect(card().textContent).toContain('Jan');++ harness.dispatch(staleHover);+ expect(card().textContent).toBe('');+ expect(hideSpy).toHaveBeenCalledOnce();++ harness.dispatch(hoverAt(1));+ expect(card().textContent).toContain('Feb');+ expect(showSpy).toHaveBeenCalledTimes(2);+ } finally {+ showSpy.mockRestore();+ hideSpy.mockRestore();+ }});});@@ -260,13 +488,78 @@ describe('ChartTooltip custom render', () => {]);});- it('hides the card when the custom render opts out by returning null', () => {- const svgEl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');- const harness = makeHarness({svgRef: {current: svgEl}});- renderTooltip(harness, {render: () => null});- harness.dispatch(hoverAt(1));- expect(card().textContent).toBe('');- expect(card().style.display).toBe('none');+ it('never opens the card when the custom render opts out with null', () => {+ const showSpy = vi.spyOn(HTMLElement.prototype, 'showPopover');+ const hideSpy = vi.spyOn(HTMLElement.prototype, 'hidePopover');+ const harness = makeHarness();++ try {+ renderTooltip(harness, {render: () => null});+ harness.dispatch(hoverAt(1));+ expect(card().textContent).toBe('');+ expect(showSpy).not.toHaveBeenCalled();+ expect(hideSpy).not.toHaveBeenCalled();+ } finally {+ showSpy.mockRestore();+ hideSpy.mockRestore();+ }+ });++ it('closes for custom null content and reopens for later content', () => {+ const showSpy = vi.spyOn(HTMLElement.prototype, 'showPopover');+ const hideSpy = vi.spyOn(HTMLElement.prototype, 'hidePopover');+ const harness = makeHarness();++ try {+ renderTooltip(harness, {+ render: xValue =>+ xValue === 'Feb' ? null : <span>{String(xValue)}</span>,+ });+ harness.dispatch(hoverAt(0));+ expect(card().textContent).toBe('Jan');++ harness.dispatch(hoverAt(1));+ expect(card().textContent).toBe('');+ expect(hideSpy).toHaveBeenCalledOnce();++ harness.dispatch(hoverAt(2));+ expect(card().textContent).toBe('Mar');+ expect(showSpy).toHaveBeenCalledTimes(2);+ } finally {+ showSpy.mockRestore();+ hideSpy.mockRestore();+ }+ });+});++describe('ChartTooltip server rendering', () => {+ it('omits the browser-only layer without a document', () => {+ const harness = makeHarness();+ const documentDescriptor = Object.getOwnPropertyDescriptor(+ globalThis,+ 'document',+ );++ Object.defineProperty(globalThis, 'document', {+ configurable: true,+ value: undefined,+ });+ try {+ const markup = renderToString(+ <ChartProvider value={harness.ctx}>+ <svg>+ <g>+ <ChartTooltip series={[makeSeries()]} />+ </g>+ </svg>+ </ChartProvider>,+ );+ expect(markup).not.toContain('role="tooltip"');+ } finally {+ if (documentDescriptor) {+ Object.defineProperty(globalThis, 'document', documentDescriptor);+ }+ }});});diff --git a/packages/charts/src/ChartTooltip.tsx b/packages/charts/src/ChartTooltip.tsxindex 7ecf51cf1e..aff58d45ca 100644--- a/packages/charts/src/ChartTooltip.tsx+++ b/packages/charts/src/ChartTooltip.tsx@@ -17,7 +17,11 @@** // Composable — drop into the chart's children for full control* <Chart>- * <ChartTooltip hoverIndicator={false} placement="top" />+ * <ChartTooltip+ * series={series}+ * hoverIndicator={false}+ * placement="top"+ * />* </Chart>* ```*/@@ -41,8 +45,7 @@ import {shadowVars,spacingVars,} from '@astryxdesign/core/theme/tokens.stylex';-import {Text} from '@astryxdesign/core';-import {VStack, HStack} from '@astryxdesign/core';+import {HStack, Text, useLayer, VStack} from '@astryxdesign/core';import {useChart} from './ChartContext';import {ChartSwatch, swatchVariantForType} from './ChartSwatch';import {@@ -90,10 +93,9 @@ export interface ChartTooltipProps {}const styles = stylex.create({- // Card chrome — static visual styles. Position (left/top/display) is updated- // imperatively via ref to keep pointer-move cost free of React renders.+ // Visual card chrome is applied to the Layer host. useLayer owns its fixed+ // positioning and browser top-layer promotion.card: {- position: 'fixed',backgroundColor: colorVars['--color-background-popover'],border: `1px solid ${colorVars['--color-border']}`,borderRadius: radiusVars['--radius-container'],@@ -102,8 +104,6 @@ const styles = stylex.create({boxShadow: shadowVars['--shadow-med'],pointerEvents: 'none',whiteSpace: 'nowrap',- zIndex: 9999,- display: 'none',},crosshair: {stroke: colorVars['--color-text-primary'],@@ -150,8 +150,8 @@ const DefaultTooltipContent = memo(function DefaultTooltipContent({* Composable grouped tooltip for Chart.** Subscribes to the chart's pointer event stream and only re-renders when the- * hovered data index changes (not on every pointer move). Card position is- * updated imperatively via a ref to keep pointer-move cost ~free.+ * hovered data index changes (not on every pointer move). Card coordinates retain+ * their previous state when the resolved point and browser geometry are unchanged.*/export function ChartTooltip({series = [],@@ -172,20 +172,41 @@ export function ChartTooltip({height,} = useChart();const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);+ const [cardPosition, setCardPosition] = useState({x: 0, y: 0});+ const [portalTarget, setPortalTarget] = useState<HTMLElement | null>(null);const cardRef = useRef<HTMLDivElement>(null);+ const lastPointerEventRef = useRef<ChartPointerEvent | null>(null);+ const {+ hide: hideLayer,+ isOpen: isLayerOpen,+ render: renderLayer,+ show: showLayer,+ } = useLayer({+ mode: 'fixed',+ });// Whether the card is currently suppressed (no content, or a custom `render`- // opted out by returning null). positionCard reads this so a same-index- // pointer move — which repositions the card without a React commit — can't- // re-reveal a card the visibility effect below has hidden.- const cardHiddenRef = useRef(false);+ // opted out by returning null). Start closed; once present content opens the+ // Layer, a content-bearing index change keeps it open while React swaps the+ // content. positionCard also reads this so a same-index pointer move cannot+ // re-reveal a suppressed card before the visibility effect confirms content.+ const cardHiddenRef = useRef(true);++ // The Layer host must remain in the chart's nearest HTML subtree so nested+ // Theme and MediaTheme scopes keep applying. The portal crosses only the SVG+ // boundary; browser top-layer promotion remains Layer's responsibility.+ useEffect(() => {+ const nextTarget = svgRef.current?.parentElement ?? null;+ setPortalTarget(current => (current === nextTarget ? current : nextTarget));+ }, [svgRef, width]);// Stable Set of resolved series keys — used by deriveTooltipSeriesValues.// Recomputed only when the resolved map identity changes (per layout pass).const resolvedKeys = useMemo(() => new Set(resolved.keys()), [resolved]);// ─── Card positioning ──────────────────────────────────────────────────- // Imperative — the card is portaled, and we don't want pointer-move to- // trigger React renders.+ // Layer owns top-layer promotion. Pointer moves update coordinates only when+ // the hovered point or browser geometry changes, so moves within one point do+ // not force a React commit.const positionCard = useCallback((e: ChartPointerEvent) => {const card = cardRef.current;@@ -194,14 +215,21 @@ export function ChartTooltip({return;}if (!svg || !e.nearest || cardHiddenRef.current) {- card.style.display = 'none';+ hideLayer();+ return;+ }++ showLayer();+ const layerHost = card.parentElement;+ if (!layerHost) {return;}+const svgRect = svg.getBoundingClientRect();const screenX = svgRect.left + margin.left + e.nearest.px;const screenY = svgRect.top + margin.top;- const cardWidth = card.offsetWidth;- const cardHeight = card.offsetHeight;+ const cardWidth = layerHost.offsetWidth;+ const cardHeight = layerHost.offsetHeight;const viewportWidth = window.innerWidth;const viewportHeight = window.innerHeight;const gap = 8;@@ -229,30 +257,33 @@ export function ChartTooltip({}}- // Clamp to the viewport so the card never clips off-screen — it's- // portaled and position:fixed, so this keeps it fully visible for every- // placement (pinned placements and the near-edge `auto` flip alike).+ // Clamp the card coordinates to the viewport. Oversized custom content+ // keeps its caller-owned dimensions and may extend past the far edge.x = Math.max(gap, Math.min(x, viewportWidth - cardWidth - gap));y = Math.max(gap, Math.min(y, viewportHeight - cardHeight - gap));- card.style.left = `${x}px`;- card.style.top = `${y}px`;- card.style.display = 'block';+ setCardPosition(current =>+ current.x === x && current.y === y ? current : {x, y},+ );},- [svgRef, margin, placement],+ [svgRef, margin, placement, hideLayer, showLayer],);// ─── Subscribe to pointer events ───────────────────────────────────────useEffect(() => {let currentIndex: number | null = null;const unsub = onPointer((e: ChartPointerEvent) => {+ lastPointerEventRef.current = e;const newIndex = e.nearest?.dataIndex ?? null;if (newIndex !== currentIndex) {currentIndex = newIndex;- // Optimistically treat the new index as showable; the visibility effect- // re-hides it after commit if there's no content (e.g. custom `render`- // returned null). This keeps the card appearing on the first move.- cardHiddenRef.current = false;+ // Keep a closed/suppressed card closed until React resolves content.+ // Do not preemptively close an already-visible card for another index:+ // the visibility effect closes absent content after commit, while+ // content-bearing transitions keep the same Layer continuously open.+ if (newIndex == null) {+ cardHiddenRef.current = true;+ }setHoveredIndex(newIndex);}positionCard(e);@@ -372,27 +403,50 @@ export function ChartTooltip({margin.top,]);- // Single source of truth for whether the card has anything to show. It's- // hidden when there's no hover, when the hovered index is stale/out-of-range- // (e.g. `data` shrank while hovering, so `datum` is undefined), or when a- // custom `render` opts out by returning null — the documented contract, which- // still shows the band highlight + dots. The decision is stored in a ref so- // the imperative positionCard honors it on subsequent same-index moves- // (otherwise it would re-reveal an empty bordered box). Runs after commit, so- // `render` (which may return null, or throw) never executes on the SSR path.+ // Render props are ordinary React content. Resolve them once per commit so a+ // custom renderer is not invoked separately by the visibility synchronizer.+ // Keep it browser-only: the layer has no portal target during SSR.+ const cardContent =+ typeof document === 'undefined' ||+ hoveredIndex == null ||+ datum == null ? null : render ? (+ render(xValue, seriesValues)+ ) : (+ <DefaultTooltipContent xValue={xValue} rows={seriesValues} />+ );+ const isCardHidden =+ hoveredIndex == null ||+ datum == null ||+ (render != null && cardContent == null);+ const hasNativePopover =+ typeof HTMLElement !== 'undefined' &&+ typeof HTMLElement.prototype.showPopover === 'function';+ const shouldHideLayerHost =+ isCardHidden || (!hasNativePopover && !isLayerOpen);++ // Synchronize the shared Layer's native Popover state after React commits the+ // new card body. The second positioning pass measures that final body; later+ // moves within the same data point usually resolve to the existing state.useEffect(() => {- const hidden =- hoveredIndex == null ||- datum == null ||- (render != null && render(xValue, seriesValues) == null);- cardHiddenRef.current = hidden;- if (hidden) {- const card = cardRef.current;- if (card) {- card.style.display = 'none';- }+ cardHiddenRef.current = isCardHidden;+ if (isCardHidden) {+ hideLayer();+ return;+ }++ const pointerEvent = lastPointerEventRef.current;+ if (pointerEvent) {+ positionCard(pointerEvent);}- }, [render, hoveredIndex, datum, xValue, seriesValues]);+ }, [+ isCardHidden,+ hoveredIndex,+ xValue,+ seriesValues,+ render,+ hideLayer,+ positionCard,+ ]);// ─── Render ────────────────────────────────────────────────────────────if (typeof document === 'undefined') {@@ -405,26 +459,29 @@ export function ChartTooltip({);}- // Mirrors the visibility effect's first two conditions: no card when there's- // no hover or the hovered datum is stale/out-of-range (so `render` and the- // default body are never called with an undefined x-value + empty rows).- const cardContent =- hoveredIndex == null || datum == null ? null : render ? (- render(xValue, seriesValues)- ) : (- <DefaultTooltipContent xValue={xValue} rows={seriesValues} />- );-return (<>{hoverIndicatorElement}{dots}- {createPortal(- <div ref={cardRef} role="tooltip" {...stylex.props(styles.card)}>- {cardContent}- </div>,- document.body,- )}+ {portalTarget+ ? createPortal(+ renderLayer(+ <div ref={cardRef} role="tooltip">+ {cardContent}+ </div>,+ {+ x: cardPosition.x,+ y: cardPosition.y,+ // Native Popover keeps a closed host out of layout itself, so+ // remove our guard before showPopover() measures it. Layer's+ // reduced fallback needs the explicit closed display state.+ style: shouldHideLayerHost ? {display: 'none'} : undefined,+ xstyle: styles.card,+ },+ ),+ portalTarget,+ )+ : null}</>);}