Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

[Component Audit] ChartAxis: preserve complete truncated labels (#6346)

Cindy Zhang2b2113d7f95a
diff --git a/apps/docsite/src/__tests__/data-extraction.test.ts b/apps/docsite/src/__tests__/data-extraction.test.ts
index 90633fc1fc..96b8aa5840 100644
--- a/apps/docsite/src/__tests__/data-extraction.test.ts
+++ b/apps/docsite/src/__tests__/data-extraction.test.ts
@@ -244,6 +244,7 @@ describe('componentRegistry', () => {
expect(components['@astryxdesign/lab'].length).toBeGreaterThan(30);
expect(components['@astryxdesign/charts'].map(comp => comp.name)).toEqual([
'Chart',
+ 'ChartAxis',
'ChartSwatch',
]);
expect(components['@astryxdesign/richtext'].map(comp => comp.name)).toEqual(
diff --git a/apps/storybook/stories/charts/ChartAxis.stories.tsx b/apps/storybook/stories/charts/ChartAxis.stories.tsx
new file mode 100644
index 0000000000..19d29b1a80
--- /dev/null
+++ b/apps/storybook/stories/charts/ChartAxis.stories.tsx
@@ -0,0 +1,83 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {Chart, ChartAxis, bar} from '@astryxdesign/charts';
+
+const DATA = [
+ {month: 'January', value: 18},
+ {month: 'February', value: 31},
+ {month: 'March', value: 24},
+ {month: 'April', value: 42},
+];
+
+const GRAPHEME_DATA = [
+ {month: 'πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦ Family', value: 18},
+ {month: 'πŸ‘©πŸ½β€πŸš€ Space', value: 31},
+ {month: 'πŸ‡―πŸ‡΅ Japan', value: 24},
+ {month: 'éclair', value: 42},
+];
+
+const meta = {
+ title: 'Charts/Chrome/ChartAxis',
+ component: ChartAxis,
+ tags: ['autodocs'],
+ args: {
+ position: 'bottom',
+ },
+ argTypes: {
+ tickFormat: {control: false},
+ },
+ render: args => (
+ <Chart
+ data={DATA}
+ xKey="month"
+ series={[bar('value')]}
+ axes={<ChartAxis {...args} />}
+ height={300}
+ />
+ ),
+} satisfies Meta<typeof ChartAxis>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+/** Drive every ChartAxis prop against one stable categorical/linear chart. */
+export const Playground: Story = {};
+
+/** Compare all four physical plot-edge placements in one chart. */
+export const AllPositions: Story = {
+ render: () => (
+ <Chart
+ data={DATA}
+ xKey="month"
+ series={[bar('value')]}
+ axes={
+ <>
+ <ChartAxis position="top" showAxisLine showTicks />
+ <ChartAxis position="right" showAxisLine showTicks />
+ <ChartAxis position="bottom" showAxisLine showTicks />
+ <ChartAxis position="left" showAxisLine showTicks />
+ </>
+ }
+ height={300}
+ />
+ ),
+};
+
+/** Truncation keeps each user-perceived character intact before the ellipsis. */
+export const GraphemeTruncation: Story = {
+ args: {
+ position: 'bottom',
+ truncate: 1,
+ animated: false,
+ },
+ render: args => (
+ <Chart
+ data={GRAPHEME_DATA}
+ xKey="month"
+ series={[bar('value')]}
+ axes={<ChartAxis {...args} />}
+ height={300}
+ />
+ ),
+};
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index a111568174..55106acc04 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -111,6 +111,11 @@
"path": "components/charts/chart",
"aliases": []
},
+ {
+ "name": "component-charts-chart-axis",
+ "path": "components/charts/chart-axis",
+ "aliases": []
+ },
{
"name": "component-charts-chart-swatch",
"path": "components/charts/chart-swatch",
diff --git a/packages/charts/src/ChartAxis.doc.mjs b/packages/charts/src/ChartAxis.doc.mjs
new file mode 100644
index 0000000000..c5250461d0
--- /dev/null
+++ b/packages/charts/src/ChartAxis.doc.mjs
@@ -0,0 +1,162 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+
+export const docs = {
+ name: 'ChartAxis',
+ displayName: 'Chart Axis',
+ group: 'Charts',
+ category: 'Data Visualization',
+ isHiddenFromOverview: true,
+ keywords: ['chart', 'axis', 'ticks', 'labels', 'scale', 'data visualization'],
+
+ usage: {
+ description:
+ 'ChartAxis renders tick labels and optional edge and tick lines from the scales owned by a parent Chart. Use it in the Chart axes slot for physical top, right, bottom, or left plot edges.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Use ChartAxis inside Chart so its labels, ticks, and edge line share the same scales and plot dimensions as the marks.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Use tickFormat for product-specific units or locale formatting, and maxTicks or truncate when dense category labels need a bounded presentation.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Use axis labels or a pointer tooltip as the only way to obtain important values. Give Chart an accessible name and preserve an equivalent data view or summary.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Hide the edge line while showing tick marks. showTicks intentionally keeps the line visible so each mark has a grounded edge.',
+ },
+ ],
+ accessibility: [
+ {
+ name: 'Chart alternative',
+ category: 'Content',
+ criterion: '1.1.1 Non-text Content',
+ requirement: 'Required on the parent Chart',
+ states: ['All'],
+ description:
+ 'Chart owns the accessible image name and supported small-data table. Tick labels supplement that chart-level alternative rather than replacing it.',
+ },
+ {
+ name: 'Label text integrity',
+ category: 'Content',
+ criterion: 'Unicode grapheme clusters',
+ requirement: 'Required when truncate is set',
+ states: ['Truncated labels'],
+ description:
+ 'Truncation keeps emoji, joined emoji sequences, flags, and combining marks intact before appending the ellipsis.',
+ },
+ ],
+ anatomy: [
+ {
+ name: 'Axis edge line',
+ required: false,
+ description:
+ 'Line along the selected plot edge. It is shown by default only on the bottom edge and whenever tick marks are shown.',
+ },
+ {
+ name: 'Tick marks',
+ required: false,
+ description:
+ 'Short lines extending outward from each retained tick position.',
+ },
+ {
+ name: 'Tick labels',
+ required: true,
+ description:
+ 'Formatted scale values or categories positioned outside the selected plot edge.',
+ },
+ ],
+ },
+
+ props: [
+ {
+ name: 'position',
+ type: "'top' | 'right' | 'bottom' | 'left'",
+ description: 'Physical plot edge on which to render the axis.',
+ required: true,
+ },
+ {
+ name: 'tickCount',
+ type: 'number',
+ description:
+ 'Approximate continuous-scale tick count. d3 chooses the final values.',
+ default: '5',
+ },
+ {
+ name: 'maxTicks',
+ type: 'number',
+ description:
+ 'Maximum displayed label count. Labels are evenly skipped when the generated set is larger.',
+ },
+ {
+ name: 'tickFormat',
+ type: '(value: unknown) => string',
+ description:
+ 'Formats each retained tick. When omitted, continuous scales use d3 formatting and band scales use their category strings.',
+ },
+ {
+ name: 'truncate',
+ type: 'number',
+ description:
+ 'Maximum content characters retained before an ellipsis is appended. User-perceived characters remain intact.',
+ },
+ {
+ name: 'animated',
+ type: 'boolean',
+ description:
+ 'Whether tick position and visibility changes use the built-in transition.',
+ default: 'true',
+ },
+ {
+ name: 'showAxisLine',
+ type: 'boolean',
+ description:
+ 'Whether to draw the edge line. Tick marks force the line on so they remain grounded.',
+ default: 'true for bottom; false for top, right, and left',
+ },
+ {
+ name: 'showTicks',
+ type: 'boolean',
+ description: 'Whether to draw an outward mark at each retained tick.',
+ default: 'false',
+ },
+ ],
+
+ examples: [
+ {
+ label: 'Bottom and left axes',
+ code: `import {Chart, ChartAxis, ChartGrid, bar} from '@astryxdesign/charts';
+
+<Chart
+ data={monthlyRevenue}
+ xKey="month"
+ series={[bar('revenue')]}
+ grid={<ChartGrid horizontal />}
+ axes={
+ <>
+ <ChartAxis position="bottom" />
+ <ChartAxis position="left" tickFormat={value => String(value)} />
+ </>
+ }
+/>;`,
+ },
+ {
+ label: 'Dense category labels',
+ code: `<ChartAxis
+ position="bottom"
+ maxTicks={8}
+ truncate={12}
+ showTicks
+/>;`,
+ },
+ ],
+};
diff --git a/packages/charts/src/ChartAxis.spec.md b/packages/charts/src/ChartAxis.spec.md
new file mode 100644
index 0000000000..5edbd258c0
--- /dev/null
+++ b/packages/charts/src/ChartAxis.spec.md
@@ -0,0 +1,211 @@
+---
+schema_version: 3
+template_version: 5
+kind: component
+id: component:ChartAxis
+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/ChartAxis.test.tsx,
+ apps/storybook/stories/charts/ChartAxis.stories.tsx,
+ ]
+modules: []
+families: []
+design_specs: []
+architecture:
+ [
+ architecture:component-test-sufficiency,
+ architecture:component-theming-surface,
+ ]
+contributing: []
+system_specs: [spec:AST-002, spec:AST-029]
+---
+
+# ChartAxis component contract
+
+## Contract at a glance
+
+| Area | Contract |
+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | No API shape or default changes. Truncation and automatic horizontal density now count complete grapheme clusters under the objective Unicode text-segmentation standard. |
+| Behavior | The selected physical plot edge determines scale, placement, label direction, and the default edge line; explicit formatting and density inputs refine labels. |
+| End-user impact | Chart readers keep complete tick-label characters, and equally short Unicode labels are no longer thinned more aggressively than ASCII labels. |
+| Builder impact | None. Existing callsites remain valid and receive direct CLI documentation for the current surface. |
+| Compatibility/readiness | The canary API and defaults are preserved. This record is draft observational evidence; rendered and accessibility-tree evidence remains incomplete. |
+| Review checks | Reject a changed public shape/default, an axis using the wrong Chart scale, broken physical-edge placement, split grapheme labels, or hidden line/tick precedence. |
+| Governing rules | `spec:AST-029/FR3–FR7`, `architecture:component-test-sufficiency/INV1–INV9`, and [Unicode Text Segmentation](https://www.unicode.org/reports/tr29/). |
+
+This table is a review projection; the body below is authoritative.
+
+## Intent
+
+ChartAxis renders labelled Cartesian x or y scale output inside a Chart. It owns
+physical-edge placement, tick selection and formatting, optional tick marks, and the
+optional axis edge line while Chart owns the scale domains and plot geometry.
+
+## Compatibility and migration
+
+- Released default preserved: yes; the package is canary-only and has no stable release.
+- Compatibility class: no public API or default changes; Unicode truncation and automatic thinning intentionally change only labels containing multi-code-unit graphemes, while representative ASCII behavior is preserved.
+- Controlled/uncontrolled behavior: not applicable.
+- Migration decision: none; this draft does not authorize a public API change.
+
+Consumer migration instructions belong in consumer docs and release notes.
+
+## Ownership boundary
+
+**Owns**
+
+- Selecting the Chart-provided x or y scale for one physical plot edge.
+- Generating, formatting, thinning, truncating, positioning, and hiding tick labels.
+- Rendering its optional edge line and optional outward tick marks.
+- Applying optional transition styling to tick position and visibility changes.
+
+**Does not own / non-goals**
+
+- Data, domains, scale construction, or plot dimensions β€” owned by `component:Chart`.
+- Grid lines β€” owned by `component:ChartGrid`.
+- Product-specific units, locale choices, or label wording supplied through `tickFormat` β€” owned by the product callsite.
+- A standalone chart data alternative β€” owned by `component:Chart` and its surrounding product content.
+
+## Public concepts
+
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ---------------- | -------------------------------------- | --------------------------------------------------------------------- | ----------------------------------------------------------- | ------------------------------------ | --------------------- | ------------ | ------------------------------------------------------------------------------- |
+| Physical edge | `top`, `right`, `bottom`, `left` | Chooses the plot edge, scale axis, transform, and outward label side. | Required for every axis. | none | `component:ChartAxis` | experimental | Unknown values are rejected by TypeScript. |
+| Tick target | finite number | Requests an approximate continuous-scale tick count from d3. | Continuous scales; also configures the automatic formatter. | `5` | `component:ChartAxis` | experimental | Negative/non-finite values fall back to 5; fractions floor; values cap at 1000. |
+| Label cap | number or absent | Evenly skips labels when the generated set exceeds the requested cap. | Every scale. | automatic from available space | `component:ChartAxis` | experimental | Values outside the intended positive-count domain are not specified. |
+| Label formatter | `(value: unknown) => string` or absent | Replaces the band string or d3 continuous-scale formatter. | Every tick. | scale-appropriate built-in formatter | `component:ChartAxis` | experimental | Exceptions from consumer formatters propagate. |
+| Label truncation | positive character count or absent | Keeps that many user-perceived characters, then appends an ellipsis. | Every formatted label. | absent | `component:ChartAxis` | experimental | Zero/omitted disables truncation; other invalid values are not specified. |
+| Edge line | shown or hidden | Renders a line along the selected axis edge. | Every edge; tick marks force it on. | shown only for `bottom` | `component:ChartAxis` | experimental | Not applicable. |
+| Tick marks | shown or hidden | Renders an outward perpendicular mark beside each visible tick label. | Every edge. | hidden | `component:ChartAxis` | experimental | Not applicable. |
+| Tick transition | animated or immediate | Animates tick transform and opacity during scale changes. | Generated ticks. | animated | `component:ChartAxis` | experimental | Not applicable. |
+
+## Behavioral and layout contract
+
+Draft requirements identify their basis so observed code is not mistaken for an
+intentional decision.
+
+| ID | Candidate invariant | Basis | Draft review state |
+| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | ------------------ |
+| FR1 | A top or bottom axis MUST consume Chart's x scale; a left or right axis MUST consume the categorical y scale when present and the linear y scale otherwise. | implementation, types, and focused tests | verify |
+| FR2 | Continuous tick generation MUST use one sanitized count for both d3 tick generation and its default formatter; band scales MUST use their complete domain before thinning. | implementation | verify |
+| FR3 | A supplied `tickFormat` MUST win; otherwise continuous scales use d3 formatting and band values use `String`. | implementation and focused tests | verify |
+| FR4 | Explicit `maxTicks` MUST win over the size-derived cap. | implementation and focused tests | verify |
+| FR5 | Truncation MUST keep complete Unicode grapheme clusters while preserving the documented content-count-plus-ellipsis output. | focused red/green test and Unicode Standard Annex #29 | settled |
+| FR6 | Automatic horizontal density MUST estimate formatted label length in user-perceived characters rather than UTF-16 storage units. | focused red/green equivalence test and Unicode segmentation | settled |
+| FR7 | Bottom MUST show an edge line by default and the other edges MUST hide it by default. `showTicks` MUST force the edge line on and render one mark per surviving tick. | implementation, JSDoc, focused tests, and Storybook | verify |
+| FR8 | Bottom and right axes MUST translate to the corresponding plot edge. Top and left remain at the plot origin. Labels and tick marks extend outwards from that physical edge. | implementation and focused tests | verify |
+| FR9 | On a mixed-sign linear y domain, the bottom edge line MUST align with y=0; categorical y leaves it on the plot edge. | implementation | verify |
+| FR10 | Tick movement and visibility MAY transition when `animated` is true and MUST be immediate when false. Out-of-range ticks remain mounted with zero opacity during updates. | implementation and streaming examples; motion intent unsettled | human decision |
+
+### Allowed variation
+
+- **AV1 β€” Tick count.** d3 may choose a nearby continuous tick count rather than the requested number.
+- **AV2 β€” Label set.** Automatic and explicit density limits may omit evenly spaced labels while preserving their scale order.
+- **AV3 β€” Supplied text.** Product callsites may format values in their own units and locale through `tickFormat`.
+
+### Representative states
+
+| State | Required invariant | Allowed variation |
+| --------------------------- | ------------------------------------------------------------------- | ----------------------------------------------------- |
+| Bottom categorical | Band labels are centered; the edge line is shown by default. | Automatic density may omit labels. |
+| Top categorical | Band labels render outside the top edge. | Edge line remains hidden unless requested. |
+| Left continuous | d3 labels render outside the left edge. | d3 chooses exact tick values. |
+| Right continuous | Axis translates to the right edge and labels render outside it. | d3 chooses exact tick values. |
+| Vertical categorical | Row labels use `yBandScale` and align with band centers. | Automatic density may omit labels. |
+| Explicit formatting | Every retained label uses the supplied formatter. | Consumer-owned wording and units. |
+| Truncated label | Complete grapheme clusters precede the appended ellipsis. | The caller chooses the content-character limit. |
+| Tick marks shown | Every retained label has an outward mark and an edge line. | Edge-line visibility input is subsumed in this state. |
+| Mixed-sign linear y data | Bottom line represents y=0 rather than the plot boundary. | Exact pixel position follows the supplied domain. |
+| Streaming / changing domain | Tick positions and visibility update; animation follows `animated`. | Tick identity follows the raw value. |
+
+### Transformation and precedence order
+
+- **ORD1 β€” Scale.** Resolve physical orientation β†’ choose Chart scale β†’ generate and format each tick once β†’ derive the grapheme-aware density cap β†’ evenly filter labels.
+- **ORD2 β€” Label.** Apply the supplied formatter or the scale default β†’ preserve complete grapheme clusters when truncating β†’ render the result.
+- **ORD3 β€” Edge.** Resolve the position default β†’ apply `showAxisLine` β†’ force the line on when `showTicks` is true.
+
+### Performance and resources
+
+- **PR1 β€” Bounded continuous ticks.** Sanitization caps the d3 request at 1000 so a consumer value cannot allocate an unbounded tick array.
+- **PR2 β€” Derived tick state.** Tick generation and formatting remain render-derived and memoized; each generated label is formatted once and shared by density and rendering, and ChartAxis owns no listener, observer, timer, or persistent resource.
+
+## Accessibility contract
+
+- **AR1 β€” Visible text integrity.** A truncated tick label MUST preserve complete user-perceived characters under Unicode grapheme-cluster boundaries.
+- **AR2 β€” Chart-level alternative.** ChartAxis renders inside Chart's named image. Chart owns the accessible chart name and supported small-data table; axis labels and pointer content do not replace that alternative.
+- **AR3 β€” Nested axis semantics gap.** The implementation currently emits a position-labelled `role="group"`. Whether that group should be independently exposed and localized beneath Chart's `role="img"` remains unverified and requires owner review.
+
+## Design relationships
+
+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
+| ---------------- | ------------------------------------------------------ | ------------------------------------------------- | -------------- | ------------------ |
+| Axis edge line | Grounds the physical plot edge when present. | unsettled; no current design record is linked | supporting | FR7, FR9 |
+| Tick marks | Associate retained labels with positions on the scale. | unsettled; no current design record is linked | supporting | FR7 |
+| Tick labels | Preserve readable value/category text around the plot. | Unicode grapheme boundaries settle text integrity | supporting | FR3, FR5, FR6, AR1 |
+| Tick transition | Shows continuity during scale changes. | unsettled; `design:motion` remains draft | supporting | FR10 |
+
+### Theming anatomy
+
+<!-- anatomy-theming:v1 -->
+
+```json
+{
+ "Axis edge line": {
+ "none": {
+ "reason": "unsettled: ChartAxis consumes semantic color tokens but no current component or family contract decides whether the line is a public theme target."
+ }
+ },
+ "Tick marks": {
+ "none": {
+ "reason": "unsettled: ChartAxis consumes semantic color tokens but no current component or family contract decides whether tick marks are a public theme target."
+ }
+ },
+ "Tick labels": {
+ "none": {
+ "reason": "unsettled: ChartAxis consumes semantic color tokens but no current component or family contract decides whether labels are a public theme target."
+ }
+ }
+}
+```
+
+## Family and system relationships
+
+- No current family or design record governs ChartAxis.
+- `architecture:component-test-sufficiency` owns rational public-state partitions, observable assertions, and red-before-green audit remediation.
+- `architecture:component-theming-surface` owns anatomy-to-target disposition; token consumption alone does not enroll ChartAxis in public component theming.
+- `spec:AST-002` owns public API admission and forbids an audit from smuggling a new public choice into a repair.
+- `spec:AST-029` owns this observational backfill, closed evidence receipt, safe remediation, and fail-closed eligibility report.
+
+## Verification map
+
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------- | ------------------------------------------------------------------- | --------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | --------------------------------- |
+| FR1, FR8 | `ChartAxis.test.tsx`; `ChartAxis.stories.tsx` | top, right, bottom, left; band and linear | An edge uses the wrong scale, transform, or outward label side. | `audit:ChartAxis/behavior-layout` |
+| FR2, FR3 | `ChartAxis.test.tsx` | default count; band, linear, and custom formatting | Generation and formatting disagree or a supplied formatter is ignored. | `audit:ChartAxis/behavior` |
+| FR4 | `ChartAxis.test.tsx` | automatic cap and explicit `maxTicks` | Explicit capping stops winning over size-derived thinning. | `audit:ChartAxis/behavior` |
+| FR5, FR6, AR1 | red-before-green grapheme regressions; density tests; browser story | ASCII, emoji, flag, and ZWJ labels; truncated wide/narrow plots | A visible label splits a grapheme or equal perceived-width labels retain different ticks. | `audit:ChartAxis/i18n-testing` |
+| FR7 | `ChartAxis.test.tsx`; Axes & Grids Storybook fixture | defaults; line requested; ticks requested | Tick marks lose their edge line or line defaults change. | `audit:ChartAxis/behavior` |
+| FR9 | source review; browser evidence remains pending | positive-only, negative-only, mixed-sign, y-band | The mixed-sign zero line moves to the edge or a categorical axis crosses the plot. | `audit:ChartAxis/behavior-design` |
+| FR10 | streaming stories; exact-head browser evidence remains pending | animated, immediate, entering/leaving tick | Disabling animation retains a transition or a moving label jumps to stale geometry. | `audit:ChartAxis/design-testing` |
+| AR2, AR3 | Chart accessibility tests; package axe; accessibility-tree review | title/subtitle, small-data table, nested axis groups | Chart loses its alternative or an unreviewed nested semantic claim is treated as fact. | `audit:ChartAxis/accessibility` |
+
+## Decision log
+
+None. This draft records observed behavior and one objective Unicode correction; it does not approve new ChartAxis policy.
+
+## Open questions
+
+- **OQ1 β€” Axis semantics.** Should ChartAxis remain purely visual content within Chart's single named image, or expose each axis as an independently localized accessibility group? (`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/ChartAxis.test.tsx b/packages/charts/src/ChartAxis.test.tsx
index d298f54848..851e368755 100644
--- a/packages/charts/src/ChartAxis.test.tsx
+++ b/packages/charts/src/ChartAxis.test.tsx
@@ -4,8 +4,8 @@
* @file ChartAxis.test.tsx
* @input Uses vitest, @testing-library/react, Chart, ChartAxis, bar mark
* @output Functional tests for axis rendering β€” group semantics, band/linear
- * tick labels, default edge-line rules, custom formatting, truncation,
- * and label capping
+ * tick labels, physical edge placement, default edge-line rules,
+ * custom formatting, grapheme-safe truncation and density, and label capping
* @position Colocated test for ChartAxis.tsx (issue #4295 viz coverage)
*/
@@ -88,6 +88,52 @@ describe('ChartAxis bottom (band scale)', () => {
expect(within(axis).queryByText('Feb')).not.toBeInTheDocument();
});
+ it('automatically reduces categorical labels as the plot narrows', () => {
+ const denseData = Array.from({length: 20}, (_, index) => ({
+ month: `Period ${index + 1}`,
+ sales: index,
+ }));
+ renderChart(<ChartAxis position="bottom" />, denseData);
+ const axis = screen.getByRole('group', {name: 'bottom axis'});
+ const wideLabelCount = axis.querySelectorAll('text').length;
+
+ reportWidth(120);
+
+ const narrowLabelCount = axis.querySelectorAll('text').length;
+ expect(narrowLabelCount).toBeGreaterThan(0);
+ expect(narrowLabelCount).toBeLessThan(wideLabelCount);
+ });
+
+ it('keeps the same auto-thinned labels after ASCII and Unicode truncation', () => {
+ const asciiData = Array.from({length: 9}, (_, index) => ({
+ month: `${index + 1}AB`,
+ sales: index,
+ }));
+ const clusters = ['πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦', 'πŸ‡―πŸ‡΅', 'πŸ‘©πŸ½β€πŸš€'];
+ const unicodeData = Array.from({length: 9}, (_, index) => ({
+ month: `${index + 1}${clusters[index % clusters.length]}X`,
+ sales: index,
+ }));
+
+ const retainedIndexes = (data: typeof asciiData) => {
+ const {unmount} = renderChart(
+ <ChartAxis position="bottom" truncate={2} />,
+ data,
+ );
+ reportWidth(300);
+ const indexes = Array.from(
+ screen
+ .getByRole('group', {name: 'bottom axis'})
+ .querySelectorAll('text'),
+ label => Number(label.textContent?.match(/^(\d+)/)?.[1]),
+ );
+ unmount();
+ return indexes;
+ };
+
+ expect(retainedIndexes(unicodeData)).toEqual(retainedIndexes(asciiData));
+ });
+
it('truncates long category labels with an ellipsis', () => {
renderChart(<ChartAxis position="bottom" truncate={4} />, [
{month: 'January', sales: 4},
@@ -98,6 +144,15 @@ describe('ChartAxis bottom (band scale)', () => {
// Short labels are left alone.
expect(within(axis).getByText('Feb')).toBeInTheDocument();
});
+
+ it('preserves whole grapheme clusters when truncating labels', () => {
+ const family = 'πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦';
+ renderChart(<ChartAxis position="bottom" truncate={1} />, [
+ {month: `${family}Q`, sales: 4},
+ ]);
+ const axis = screen.getByRole('group', {name: 'bottom axis'});
+ expect(within(axis).getByText(`${family}…`)).toBeInTheDocument();
+ });
});
describe('ChartAxis left (linear scale)', () => {
@@ -129,3 +184,26 @@ describe('ChartAxis left (linear scale)', () => {
expect(lines).toHaveLength(7);
});
});
+
+describe('ChartAxis top and right positions', () => {
+ it('places both axes on their physical plot edges with outward labels', () => {
+ renderChart(
+ <>
+ <ChartAxis position="top" showTicks />
+ <ChartAxis position="right" showTicks />
+ </>,
+ );
+
+ const top = screen.getByRole('group', {name: 'top axis'});
+ expect(top).not.toHaveAttribute('transform');
+ expect(within(top).getByText('Jan')).toHaveAttribute('y', '-10');
+
+ const right = screen.getByRole('group', {name: 'right axis'});
+ expect(right).toHaveAttribute('transform', 'translate(528,0)');
+ expect(within(right).getByText('0')).toHaveAttribute('x', '10');
+ expect(within(right).getByText('0')).toHaveAttribute(
+ 'text-anchor',
+ 'start',
+ );
+ });
+});
diff --git a/packages/charts/src/ChartAxis.tsx b/packages/charts/src/ChartAxis.tsx
index 6e412beee7..8c90a0290a 100644
--- a/packages/charts/src/ChartAxis.tsx
+++ b/packages/charts/src/ChartAxis.tsx
@@ -2,6 +2,7 @@
/**
* @file ChartAxis.tsx (v2)
+ * @input Chart context scales, axis presentation props, and grapheme-safe text utilities
* @output Renders an axis (top, right, bottom, left) using the chart's scales
* @position Child of Chart v2; reads scales from chart context
*
@@ -19,6 +20,7 @@
import {useCallback, useMemo} from 'react';
import * as stylex from '@stylexjs/stylex';
+import {characterCount, truncateCharacters} from '@astryxdesign/core/utils';
import {colorVars} from '@astryxdesign/core/theme/tokens.stylex';
import {useChart} from './ChartContext';
import {isBandScale} from './utils';
@@ -33,7 +35,7 @@ export interface ChartAxisProps {
maxTicks?: number;
/** Custom tick formatter */
tickFormat?: (value: unknown) => string;
- /** Truncate labels to this many characters (appends "\u2026"). */
+ /** Truncate labels to this many user-perceived characters (appends "\u2026"). */
truncate?: number;
/** Enable smooth transitions for streaming (default: true) */
animated?: boolean;
@@ -121,19 +123,24 @@ export function ChartAxis({
const format = useCallback(
(value: unknown): string => {
const str = (tickFormat ?? autoFormat ?? String)(value);
- return truncate && str.length > truncate
- ? str.slice(0, truncate) + '\u2026'
- : str;
+ if (!truncate) {
+ return str;
+ }
+ const shortened = truncateCharacters(str, truncate, '');
+ return shortened === str ? str : shortened + '\u2026';
},
[tickFormat, autoFormat, truncate],
);
const ticks = useMemo(() => {
- let allTicks: {value: unknown; offset: number}[];
+ // Format each generated tick once so density and rendering share the same
+ // grapheme-safe label instead of repeating consumer formatting/segmentation.
+ let allTicks: {value: unknown; offset: number; label: string}[];
if (isBandScale(scale)) {
allTicks = scale.domain().map(d => ({
value: d,
offset: (scale(d) ?? 0) + scale.bandwidth() / 2,
+ label: format(d),
}));
} else {
const linearScale = scale as
@@ -141,6 +148,7 @@ export function ChartAxis({
allTicks = linearScale.ticks(safeTickCount).map(d => ({
value: d,
offset: linearScale(d as number & Date),
+ label: format(d),
}));
}
@@ -154,7 +162,7 @@ export function ChartAxis({
if (cap == null && allTicks.length > 1) {
if (isHorizontal && width > 0) {
const widestChars = allTicks.reduce(
- (m, t) => Math.max(m, format(t.value).length),
+ (m, tick) => Math.max(m, characterCount(tick.label)),
1,
);
const approxLabelPx = widestChars * 7 + 16;
@@ -210,8 +218,7 @@ export function ChartAxis({
{...stylex.props(styles.axisLine)}
/>
)}
- {ticks.map(({value, offset}) => {
- const label = format(value);
+ {ticks.map(({value, offset, label}) => {
// Key off the raw tick value, not the formatted label: distinct ticks
// can format (or truncate) to the same string and would collide as keys.
const key = String(value);