Skip to content

Commit e56af92

Browse files
committed
wip(ui): tests and changeset for dashboard readability
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibzKuj2HUUN2wUhZ9Go
1 parent b434e78 commit e56af92

5 files changed

Lines changed: 367 additions & 6 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@object-ui/core': patch
3+
'@object-ui/plugin-charts': patch
4+
'@object-ui/plugin-dashboard': patch
5+
---
6+
7+
Clause-②: yes (widening: @object-ui/core gains the public export formatMonthBucketLabel; no accept set moves)
8+
Metadata-protocol: none
9+
10+
Dashboard numbers and chart labels stay readable on a phone:
11+
12+
- **KPI value.** A dataset-bound KPI tile's value now shrinks to fit its tile, the way the plain metric tiles already did, instead of being cut with an ellipsis (`$1,090,00...` on a phone). Past the smallest size it keeps the ellipsis and shows the full figure as a tooltip. A short value looks as before.
13+
- **Month axis.** A chart over a month-bucketed date dimension labels its axis `Oct 2025` in the reader's locale, not the raw bucket key `2025-10`. The key itself is unchanged in the data, so drill-through and ordering are unaffected. `@object-ui/core` adds `formatMonthBucketLabel(value, locale)`, which answers that label for a `YYYY-MM` key and `undefined` for anything else.
14+
- **Legend swatches.** A bar or area chart's legend draws a colour swatch for every series; it drew none, because those marks fill from a gradient. A comparison (`compareTo`) series' swatch is drawn hollow, so it reads apart from the solid swatch of the series it overlays in the same colour.
15+
- **Horizontal bar labels.** A horizontal bar chart's category labels are drawn in full on a phone, wrapped to at most two lines inside the axis, instead of cut to eight characters (`In Progr…`). A label still too long ends in an ellipsis and shows the full text as a tooltip.
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* The month bucket key's display face (objectstack#27520 row 15): a
11+
* `month`-granularity date dimension answers `2025-10`, and an axis reads
12+
* `Oct 2025`.
13+
*/
14+
15+
import { describe, it, expect } from 'vitest';
16+
import { formatMonthBucketLabel } from '../date-bucket-label';
17+
18+
describe('formatMonthBucketLabel', () => {
19+
it('reads a month bucket key as the short month and the year, in the locale', () => {
20+
expect(formatMonthBucketLabel('2025-10', 'en-US')).toBe('Oct 2025');
21+
expect(formatMonthBucketLabel('2026-01', 'en-US')).toBe('Jan 2026');
22+
expect(formatMonthBucketLabel('2025-10', 'zh-CN')).toBe(new Date(Date.UTC(2025, 9, 1)).toLocaleDateString('zh-CN', { month: 'short', year: 'numeric', timeZone: 'UTC' }));
23+
});
24+
25+
it('names the month the key names whatever the time zone (formatted in UTC)', () => {
26+
// The first of the month at UTC midnight is the previous day west of UTC;
27+
// a local-zone face would print September for `2025-10` there.
28+
expect(formatMonthBucketLabel('2025-10', 'en-US')).not.toMatch(/Sep/);
29+
expect(formatMonthBucketLabel('2025-12', 'en-US')).toBe('Dec 2025');
30+
});
31+
32+
it('keeps a year below 100 as written', () => {
33+
expect(formatMonthBucketLabel('0050-06', 'en-US')).toMatch(/50/);
34+
expect(formatMonthBucketLabel('0050-06', 'en-US')).not.toMatch(/1950/);
35+
});
36+
37+
it('answers undefined for every other shape, so the caller keeps the value as written', () => {
38+
for (const v of ['2025-10-01', '2025-Q4', '2025', '2025-13', '2025-00', '2025-1', 'In Progress', '', null, undefined, 202510]) {
39+
expect(formatMonthBucketLabel(v, 'en-US'), String(v)).toBeUndefined();
40+
}
41+
});
42+
43+
it('answers undefined for a locale Intl refuses', () => {
44+
expect(formatMonthBucketLabel('2025-10', 'not a locale!')).toBeUndefined();
45+
});
46+
});

‎ui/packages/core/src/utils/date-bucket-label.ts‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,13 @@
2525

2626
const MONTH_BUCKET_KEY_RE = /^(\d{4})-(0[1-9]|1[0-2])$/;
2727

28-
/** Whether `value` is a month bucket key (`YYYY-MM`). */
29-
export function isMonthBucketKey(value: unknown): value is string {
30-
return typeof value === 'string' && MONTH_BUCKET_KEY_RE.test(value);
31-
}
32-
3328
/**
3429
* `Oct 2025` for the month bucket key `2025-10`, in `locale`; `undefined` for
3530
* any other value, or when `Intl` refuses the locale, so the caller keeps the
3631
* key as written.
3732
*/
3833
export function formatMonthBucketLabel(value: unknown, locale?: string): string | undefined {
39-
if (!isMonthBucketKey(value)) return undefined;
34+
if (typeof value !== 'string' || !MONTH_BUCKET_KEY_RE.test(value)) return undefined;
4035
const [year, month] = value.split('-').map(Number);
4136
const date = new Date(0);
4237
// `setUTCFullYear`, not `Date.UTC(year, …)`: the latter maps years 0-99 onto 1900+y.
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* Dashboard chart readability (objectstack#27520 rows 15 and 18).
11+
*
12+
* - A month bucket key (`2025-10`) reads `Oct 2025` on the category axis.
13+
* - The legend draws a swatch for a bar series (whose mark fills from a
14+
* gradient, so recharts hands the legend a `url(#…)` it cannot draw), and a
15+
* comparison series' swatch is hollow, apart from the primary's solid one.
16+
* - A horizontal bar's category label is drawn in full on a phone, wrapped
17+
* into the axis width, instead of cut to eight characters; a label that
18+
* still has to be cut carries the full text as its tooltip.
19+
*/
20+
21+
import React from 'react';
22+
import { describe, it, expect, vi, afterEach } from 'vitest';
23+
import { render, cleanup, act } from '@testing-library/react';
24+
25+
vi.mock('recharts', async () => {
26+
const actual = await vi.importActual<any>('recharts');
27+
return {
28+
...actual,
29+
ResponsiveContainer: ({ children }: any) =>
30+
React.cloneElement(children, { width: 360, height: 320 }),
31+
};
32+
});
33+
34+
import AdvancedChartImpl from './AdvancedChartImpl';
35+
36+
const DESKTOP_WIDTH = window.innerWidth;
37+
38+
afterEach(() => {
39+
cleanup();
40+
(window as any).innerWidth = DESKTOP_WIDTH;
41+
});
42+
43+
// The legend payload registers from a layout effect; read it after a tick.
44+
const settle = () => act(async () => { await new Promise((r) => setTimeout(r, 60)); });
45+
46+
const swatches = (c: HTMLElement) =>
47+
Array.from(c.querySelectorAll<HTMLElement>('.recharts-legend-wrapper .rounded-\\[2px\\]'));
48+
49+
const categoryTicks = (c: HTMLElement) =>
50+
Array.from(c.querySelectorAll<SVGTextElement>('.recharts-yAxis .recharts-cartesian-axis-tick-value, .recharts-cartesian-axis-tick-labels text'));
51+
52+
describe('month bucket keys on the category axis (row 15)', () => {
53+
it('reads `2025-10` as `Oct 2025`', () => {
54+
const { container } = render(
55+
<AdvancedChartImpl
56+
chartType="line"
57+
data={[{ month: '2025-10', n: 3 }, { month: '2025-11', n: 5 }, { month: '2025-12', n: 4 }]}
58+
xAxisKey="month"
59+
series={[{ dataKey: 'n', label: 'Count' }]}
60+
isAnimationActive={false}
61+
/>,
62+
);
63+
const text = container.textContent ?? '';
64+
expect(text).toContain('Oct 2025');
65+
expect(text).toContain('Dec 2025');
66+
expect(text).not.toContain('2025-10');
67+
});
68+
69+
it('CONTROL: a category that only looks partly like a date is drawn as written', () => {
70+
const { container } = render(
71+
<AdvancedChartImpl
72+
chartType="bar"
73+
data={[{ q: '2025-Q4', n: 3 }, { q: '2026-Q1', n: 5 }]}
74+
xAxisKey="q"
75+
series={[{ dataKey: 'n', label: 'Count' }]}
76+
isAnimationActive={false}
77+
/>,
78+
);
79+
expect(container.textContent).toContain('2025-Q4');
80+
});
81+
});
82+
83+
describe('legend swatches (row 15)', () => {
84+
const compared = [
85+
{ dataKey: 'n', label: 'Count', variant: 'current' },
86+
{ dataKey: 'n__compare', label: 'Count · vs last quarter', variant: 'comparison' },
87+
];
88+
const rows = [{ stage: 'Prospecting', n: 3, n__compare: 2 }, { stage: 'Proposal', n: 5, n__compare: 4 }];
89+
90+
it('a bar chart draws a colour on every swatch, never a gradient reference', async () => {
91+
const { container } = render(
92+
<AdvancedChartImpl chartType="bar" data={rows} xAxisKey="stage" series={compared} isAnimationActive={false} />,
93+
);
94+
await settle();
95+
const drawn = swatches(container);
96+
expect(drawn).toHaveLength(2);
97+
for (const swatch of drawn) {
98+
const color = swatch.style.getPropertyValue('--color-bg');
99+
expect(color).not.toBe('');
100+
expect(color).not.toMatch(/^url\(/);
101+
}
102+
});
103+
104+
it.each(['bar', 'line', 'area'])('%s: the comparison swatch is hollow and the primary one solid, in the same colour', async (chartType) => {
105+
const { container } = render(
106+
<AdvancedChartImpl chartType={chartType} data={rows} xAxisKey="stage" series={compared} isAnimationActive={false} />,
107+
);
108+
await settle();
109+
const [primary, comparison] = swatches(container);
110+
expect(primary.classList.contains('bg-(--color-bg)')).toBe(true);
111+
expect(primary.getAttribute('data-swatch')).toBeNull();
112+
expect(comparison.getAttribute('data-swatch')).toBe('comparison');
113+
expect(comparison.classList.contains('bg-transparent')).toBe(true);
114+
expect(comparison.classList.contains('border-(--color-bg)')).toBe(true);
115+
// The overlay mirrors its primary's colour; the swatch shape tells them apart.
116+
expect(comparison.style.getPropertyValue('--color-bg')).toBe(primary.style.getPropertyValue('--color-bg'));
117+
});
118+
});
119+
120+
describe('horizontal bar category labels on a phone (row 18)', () => {
121+
const asPhone = () => {
122+
(window as any).innerWidth = 390;
123+
window.dispatchEvent(new Event('resize'));
124+
};
125+
const statuses = [
126+
{ status: 'In Progress', n: 4 },
127+
{ status: 'Backlog', n: 2 },
128+
{ status: 'Waiting on the customer to confirm the delivery window', n: 1 },
129+
];
130+
131+
it('draws "In Progress" whole, not cut to "In Progr…"', () => {
132+
asPhone();
133+
const { container } = render(
134+
<AdvancedChartImpl chartType="horizontal-bar" data={statuses} xAxisKey="status" series={[{ dataKey: 'n', label: 'Tasks' }]} isAnimationActive={false} />,
135+
);
136+
const texts = categoryTicks(container).map((t) => Array.from(t.querySelectorAll('tspan')).map((s) => s.textContent).join(' '));
137+
expect(texts).toContain('In Progress');
138+
expect(container.textContent).not.toContain('In Progr…');
139+
});
140+
141+
it('wraps a long label to at most two lines and carries the full label as its tooltip', () => {
142+
asPhone();
143+
const { container } = render(
144+
<AdvancedChartImpl chartType="horizontal-bar" data={statuses} xAxisKey="status" series={[{ dataKey: 'n', label: 'Tasks' }]} isAnimationActive={false} />,
145+
);
146+
const long = categoryTicks(container).find((t) => t.querySelector('title'));
147+
expect(long).toBeDefined();
148+
expect(long!.querySelector('title')!.textContent).toBe('Waiting on the customer to confirm the delivery window');
149+
const lines = Array.from(long!.querySelectorAll('tspan')).map((s) => s.textContent ?? '');
150+
expect(lines).toHaveLength(2);
151+
expect(lines[1].endsWith('…')).toBe(true);
152+
// A label that fits carries no tooltip.
153+
const backlog = categoryTicks(container).find((t) => t.textContent === 'Backlog');
154+
expect(backlog?.querySelector('title')).toBeNull();
155+
});
156+
});
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#27520 row 3 — the dataset-bound KPI tile's value scales before
11+
* it would clip.
12+
*
13+
* On a phone the Delivery Operations dashboard draws its KPI tiles two to a
14+
* row, and the Total Budget tile cut `$1,090,000.00` to `$1,090,00...`: the
15+
* dataset-bound tile drew every value at the short face (20 px, 24 px from a
16+
* 160 px tile), while the plain tiles already took the size ladder
17+
* (objectui#12942). Now it takes a ladder of its own, measured against its own
18+
* box, which has no Card inset.
19+
*
20+
* jsdom has no layout, so this file pins the CONTRACT: every step starts where
21+
* the formula in `../metricTile` says, which rung a value takes, and that the
22+
* tile's value node carries it. The measured widths are in the pull request,
23+
* from a browser.
24+
*/
25+
26+
import * as React from 'react';
27+
import { describe, it, expect, vi, afterEach } from 'vitest';
28+
import { render, screen, cleanup } from '@testing-library/react';
29+
import { I18nProvider } from '@object-ui/i18n';
30+
import type { DashboardComponentSchema } from '@object-ui/types';
31+
// Module scope (AGENTS.md 测试纪律): the barrel registers the dashboard blocks.
32+
import '@object-ui/components';
33+
import '../index';
34+
import { DashboardRenderer } from '../DashboardRenderer';
35+
import {
36+
METRIC_TILE_DATASET_VALUE_LADDER,
37+
METRIC_TILE_VALUE_CLASS,
38+
METRIC_TILE_VALUE_FINAL_SIZES,
39+
METRIC_TILE_VALUE_LADDER,
40+
metricTileValueClass,
41+
metricTileValueEm,
42+
} from '../metricTile';
43+
44+
afterEach(cleanup);
45+
46+
const classesOf = (el: Element) => (el.getAttribute('class') ?? '').split(/\s+/).filter(Boolean);
47+
48+
/** Tailwind's type scale, in px, for the sizes the ladder uses. */
49+
const PX: Record<string, number> = { 'text-sm': 14, 'text-base': 16, 'text-lg': 18, 'text-xl': 20, 'text-2xl': 24 };
50+
51+
/** The size a class list draws at in a container `width` px wide. */
52+
function sizeAt(classes: string[], width: number): number {
53+
let px = 0;
54+
let from = -1;
55+
for (const c of classes) {
56+
const step = /^@\[(\d+)px\]:(text-[a-z0-9]+)$/.exec(c);
57+
if (step && PX[step[2]] !== undefined) {
58+
const at = Number(step[1]);
59+
if (width >= at && at > from) { from = at; px = PX[step[2]]; }
60+
} else if (PX[c] !== undefined && from < 0) {
61+
px = PX[c];
62+
}
63+
}
64+
return px;
65+
}
66+
67+
/** The short rung's own step for a size: 20 px from 0, 24 px from 160 px. */
68+
const SHORT_FACE_STEP: Record<string, number> = { 'text-xl': 0, 'text-2xl': 160 };
69+
70+
const BUDGET = '$1,090,000.00';
71+
72+
describe('the dataset tile value ladder (objectstack#27520)', () => {
73+
it('has the plain ladder\'s rungs and its short face', () => {
74+
expect(METRIC_TILE_DATASET_VALUE_LADDER.map((r) => r.maxEm)).toEqual(METRIC_TILE_VALUE_LADDER.map((r) => r.maxEm));
75+
expect(METRIC_TILE_DATASET_VALUE_LADDER[0].sizes).toBe(METRIC_TILE_VALUE_LADDER[0].sizes);
76+
});
77+
78+
it('starts every step where its size fits the rung\'s widest value, never before the short face\'s own step', () => {
79+
for (const { maxEm, sizes } of METRIC_TILE_DATASET_VALUE_LADDER.slice(1)) {
80+
const cls = sizes.split(' ');
81+
expect(cls[0]).toBe('text-sm');
82+
for (const c of cls.slice(1)) {
83+
const step = /^@\[(\d+)px\]:(text-[a-z0-9]+)$/.exec(c);
84+
expect(step, c).not.toBeNull();
85+
const need = Math.max(Math.ceil(maxEm * PX[step![2]]), SHORT_FACE_STEP[step![2]] ?? 0);
86+
expect(Number(step![1]), `${c} on the ${maxEm} em rung`).toBe(need);
87+
}
88+
}
89+
expect(METRIC_TILE_VALUE_FINAL_SIZES).toBe('text-sm');
90+
});
91+
92+
it('never draws a longer value larger than a shorter one in the same tile', () => {
93+
const rungs = METRIC_TILE_DATASET_VALUE_LADDER.map((r) => r.sizes.split(' '));
94+
for (let width = 60; width <= 400; width += 1) {
95+
const px = rungs.map((cls) => sizeAt(cls, width));
96+
expect(px, `at ${width} px`).toEqual([...px].sort((a, b) => b - a));
97+
}
98+
});
99+
100+
it('fits the Total Budget figure at every width from where 14 px holds it', () => {
101+
const em = metricTileValueEm(BUDGET);
102+
const cls = metricTileValueClass(BUDGET, METRIC_TILE_DATASET_VALUE_LADDER).split(' ');
103+
for (let width = Math.ceil(em * 14); width <= 400; width += 1) {
104+
expect(em * sizeAt(cls, width), `at a ${width} px tile`).toBeLessThanOrEqual(width);
105+
}
106+
// The short face did not: 20 px in a 140 px tile, 24 px in a 170 px one.
107+
const short = METRIC_TILE_VALUE_CLASS.split(' ');
108+
expect(em * sizeAt(short, 140)).toBeGreaterThan(140);
109+
expect(em * sizeAt(short, 170)).toBeGreaterThan(170);
110+
});
111+
});
112+
113+
describe('the rendered dataset tile (objectstack#27520)', () => {
114+
const renderTile = (value: number) =>
115+
render(
116+
<I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }}>
117+
<DashboardRenderer
118+
schema={{
119+
type: 'dashboard',
120+
name: 'ops',
121+
widgets: [{ id: 'kpi_total_budget', type: 'metric', title: 'Total Budget', dataset: 'project_metrics', values: ['budget_sum'] }],
122+
} as unknown as DashboardComponentSchema}
123+
dataSource={{
124+
queryDataset: vi.fn(async () => ({
125+
rows: [{ budget_sum: value }],
126+
fields: [{ name: 'budget_sum', label: 'Total Budget', type: 'currency', format: '$0,0.00' }],
127+
})),
128+
}}
129+
/>
130+
</I18nProvider>,
131+
);
132+
133+
it('draws a long money figure on its ladder rung, whole, with the figure as its tooltip', async () => {
134+
renderTile(1090000);
135+
const value = await screen.findByText(BUDGET);
136+
const cls = classesOf(value);
137+
expect(cls).toEqual(expect.arrayContaining(metricTileValueClass(BUDGET, METRIC_TILE_DATASET_VALUE_LADDER).split(' ')));
138+
expect(cls).not.toContain('text-xl');
139+
expect(value.textContent).toBe(BUDGET);
140+
expect(value).toHaveAttribute('title', BUDGET);
141+
});
142+
143+
it('CONTROL: a short figure keeps the short face and no tooltip', async () => {
144+
renderTile(42);
145+
const value = await screen.findByText('$42.00');
146+
expect(classesOf(value)).toEqual(expect.arrayContaining(METRIC_TILE_VALUE_CLASS.split(' ')));
147+
expect(value).not.toHaveAttribute('title');
148+
});
149+
});

0 commit comments

Comments
 (0)