Skip to content

Commit b434e78

Browse files
committed
wip(ui): dashboard numbers and chart labels readable on a phone
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibzKuj2HUUN2wUhZ9Go
1 parent 9f13ee8 commit b434e78

6 files changed

Lines changed: 248 additions & 29 deletions

File tree

‎ui/packages/core/src/index.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,9 @@ export * from './utils/number-display.js';
164164
// below could not import, so a date-valued measure rendered its raw ISO
165165
// string. `@object-ui/fields` re-exports these names unchanged.
166166
export * from './utils/date-display.js';
167+
// The display face of a `YYYY-MM` month bucket key (`Oct 2025`) — read by the
168+
// chart axis, which keeps the key itself as the bucket's identity.
169+
export * from './utils/date-bucket-label.js';
167170
// The native date/time control adapters (objectui#3127), moved down from
168171
// `@object-ui/fields` so `@object-ui/components`' data table can share them
169172
// instead of keeping private copies (objectui#10625). `@object-ui/fields`
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
* date-bucket-label — the display face of a month bucket key.
11+
*
12+
* The analytics executor answers a `month`-granularity date dimension with a
13+
* sort-stable bucket KEY, `YYYY-MM` (`2025-10`). The key is the row's identity:
14+
* a drill-through filters by it and the chart orders by it, so it stays as the
15+
* executor wrote it. What a reader sees on an axis is this face instead,
16+
* `Oct 2025` in the display locale.
17+
*
18+
* Only the key shape is recognised: four digits, a dash, a month 01..12, and
19+
* nothing else. A day (`YYYY-MM-DD`) is the date-display path's, and a quarter
20+
* (`2025-Q4`) or a year (`2025`) already reads as written.
21+
*
22+
* The month is formatted in UTC from a UTC date, so no display or browser
23+
* time zone can move it to the neighbouring month.
24+
*/
25+
26+
const MONTH_BUCKET_KEY_RE = /^(\d{4})-(0[1-9]|1[0-2])$/;
27+
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+
33+
/**
34+
* `Oct 2025` for the month bucket key `2025-10`, in `locale`; `undefined` for
35+
* any other value, or when `Intl` refuses the locale, so the caller keeps the
36+
* key as written.
37+
*/
38+
export function formatMonthBucketLabel(value: unknown, locale?: string): string | undefined {
39+
if (!isMonthBucketKey(value)) return undefined;
40+
const [year, month] = value.split('-').map(Number);
41+
const date = new Date(0);
42+
// `setUTCFullYear`, not `Date.UTC(year, …)`: the latter maps years 0-99 onto 1900+y.
43+
date.setUTCFullYear(year, month - 1, 1);
44+
try {
45+
return date.toLocaleDateString(locale, { month: 'short', year: 'numeric', timeZone: 'UTC' });
46+
} catch {
47+
return undefined;
48+
}
49+
}

‎ui/packages/plugin-charts/src/AdvancedChartImpl.tsx‎

Lines changed: 135 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -47,11 +47,12 @@ import {
4747
ChartTooltipContent,
4848
ChartLegend,
4949
ChartLegendContent,
50+
type LegendSwatch,
5051
ChartContainerConfig
5152
} from './ChartContainerImpl';
5253
import { mapScatterClick, mapTreemapClick, mapSankeyClick } from './chartDrillEvents';
5354
import { formatterFor, domainFor, ticksFor, plotsWholeNumbers, RENDERABLE, SINGLE_VALUE_CHART_TYPES, TABULAR_CHART_TYPES, effectiveChartFamily, comboBaseFamily, placeYAxes, type DeclaredChartFamily, type NormalizedAxis, type NormalizedSeries, type ValueAxisSlot, type YAxisPlacement } from './normalizeChartSchema';
54-
import { buildCategoryRank, chartRowBucketId, isRealCalendarDate, toDateInputValue, toDisplayDate, type ChartSegmentClickEvent } from '@object-ui/core';
55+
import { buildCategoryRank, chartRowBucketId, formatMonthBucketLabel, isRealCalendarDate, toDateInputValue, toDisplayDate, type ChartSegmentClickEvent } from '@object-ui/core';
5556
import { createSafeTranslation, useDisplayLocale, useSafeTranslate } from '@object-ui/i18n';
5657

5758
// Default color fallback for chart series
@@ -479,6 +480,87 @@ function estimateLabelWidthPx(label: string): number {
479480
return ems * AXIS_TICK_FONT_PX;
480481
}
481482

483+
/**
484+
* The most lines a horizontal-bar category label wraps to before it is cut.
485+
* Two keep a bar's label beside its own bar at the row heights a dashboard
486+
* tile draws.
487+
*/
488+
const CATEGORY_LABEL_MAX_LINES = 2;
489+
490+
/**
491+
* A horizontal-bar category label broken into lines that fit `maxWidthPx`,
492+
* by the same upper estimate the x axis sizes its bands from
493+
* ({@link estimateLabelWidthPx}). Words wrap whole; a word wider than a line
494+
* is cut by glyph. Past {@link CATEGORY_LABEL_MAX_LINES} the last line ends in
495+
* an ellipsis and `truncated` is set, so the tick carries the full label as
496+
* its tooltip.
497+
*/
498+
function wrapCategoryLabel(label: string, maxWidthPx: number): { lines: string[]; truncated: boolean } {
499+
const fits = (text: string) => estimateLabelWidthPx(text) <= maxWidthPx;
500+
if (label === '' || fits(label)) return { lines: [label], truncated: false };
501+
const lines: string[] = [];
502+
let current = '';
503+
const pushGlyphs = (word: string) => {
504+
for (const glyph of word) {
505+
if (current !== '' && !fits(current + glyph)) {
506+
lines.push(current);
507+
current = '';
508+
}
509+
current += glyph;
510+
}
511+
};
512+
for (const word of label.split(/\s+/u).filter(Boolean)) {
513+
const candidate = current === '' ? word : `${current} ${word}`;
514+
if (fits(candidate)) {
515+
current = candidate;
516+
} else {
517+
if (current !== '') lines.push(current);
518+
current = '';
519+
if (fits(word)) current = word;
520+
else pushGlyphs(word);
521+
}
522+
}
523+
if (current !== '') lines.push(current);
524+
if (lines.length <= CATEGORY_LABEL_MAX_LINES) return { lines, truncated: false };
525+
const kept = lines.slice(0, CATEGORY_LABEL_MAX_LINES);
526+
let last = kept[kept.length - 1];
527+
while (last.length > 0 && !fits(`${last}…`)) last = Array.from(last).slice(0, -1).join('');
528+
kept[kept.length - 1] = `${last.trimEnd()}…`;
529+
return { lines: kept, truncated: true };
530+
}
531+
532+
/**
533+
* What a left category axis keeps between its edge and the label's end:
534+
* recharts' `tickSize` plus its default `tickMargin` of 2.
535+
*/
536+
const CATEGORY_TICK_INSET_PX = RECHARTS_TICK_SIZE + 2;
537+
538+
/** The line advance of a wrapped category label, in em. */
539+
const CATEGORY_LABEL_LINE_EM = 1.1;
540+
541+
/**
542+
* The horizontal-bar CATEGORY axis tick: the full label, wrapped into the
543+
* axis width ({@link wrapCategoryLabel}) and centred on its bar, with the full
544+
* label as a tooltip when it had to be cut. It replaces the phone cut to eight
545+
* characters, which left a bar named only by its first letters ("In Progr…").
546+
*/
547+
function WrappedCategoryTick(props: any) {
548+
const { x, y, payload, textAnchor, maxWidthPx, formatLabel } = props;
549+
const full = String(formatLabel(payload?.value) ?? '');
550+
const { lines, truncated } = wrapCategoryLabel(full, maxWidthPx);
551+
// Centre the block on the tick: the first line rises half the extra lines,
552+
// and 0.355em puts a line's middle (not its baseline) on `y`.
553+
const firstDy = `${0.355 - ((lines.length - 1) * CATEGORY_LABEL_LINE_EM) / 2}em`;
554+
return (
555+
<text x={x} y={y} textAnchor={textAnchor ?? 'end'} fill={AXIS_TICK_STYLE.fill} className="recharts-text recharts-cartesian-axis-tick-value">
556+
{truncated ? <title>{full}</title> : null}
557+
{lines.map((line, i) => (
558+
<tspan key={i} x={x} dy={i === 0 ? firstDy : `${CATEGORY_LABEL_LINE_EM}em`}>{line}</tspan>
559+
))}
560+
</text>
561+
);
562+
}
563+
482564
/** recharts' default chart margin, left plus right (5px each side). */
483565
const CHART_MARGIN_X_PX = 10;
484566

@@ -2281,8 +2363,10 @@ function AdvancedChartImplInner({
22812363
}, []);
22822364

22832365
// Format ISO date strings into compact "MMM D" / "MMM YYYY" labels for X-axis ticks.
2284-
// Falls back to the raw value when not parseable as a date.
2285-
const formatTick = React.useCallback((value: any): string => {
2366+
// Falls back to the raw value when not parseable as a date. The full label:
2367+
// `formatTick` below adds the phone cut, which the horizontal-bar category
2368+
// axis does not take (it wraps instead, see `WrappedCategoryTick`).
2369+
const formatCategoryLabel = React.useCallback((value: any): string => {
22862370
if (value == null || value === '') return '';
22872371
// A resolved display label for this exact category value — the same
22882372
// `config[key]?.label` convention already used for series names (below)
@@ -2292,6 +2376,10 @@ function AdvancedChartImplInner({
22922376
const resolved = config?.[String(value)]?.label;
22932377
if (resolved != null) return String(resolved);
22942378
const str = typeof value === 'string' ? value : String(value);
2379+
// A month bucket key (`2025-10`, a `month`-granularity date dimension) reads
2380+
// as `Oct 2025`; the key itself stays the bucket's identity in the row.
2381+
const month = formatMonthBucketLabel(str, displayLocale);
2382+
if (month !== undefined) return month;
22952383
// Detect ISO 8601 date / datetime strings (YYYY-MM-DD or with time component)
22962384
const isoLike = /^\d{4}-\d{2}-\d{2}/.test(str);
22972385
if (isoLike) {
@@ -2327,9 +2415,13 @@ function AdvancedChartImplInner({
23272415
}
23282416
}
23292417
}
2418+
return str;
2419+
}, [data, xAxisKey, config, displayLocale]);
2420+
const formatTick = React.useCallback((value: any): string => {
2421+
const str = formatCategoryLabel(value);
23302422
if (isMobile && str.length > 8) return str.slice(0, 8) + '…';
23312423
return str;
2332-
}, [data, xAxisKey, isMobile, config, displayLocale]);
2424+
}, [formatCategoryLabel, isMobile]);
23332425

23342426
// Memoize whether any X-axis label is long enough to warrant angle rotation
23352427
const hasLongLabels = React.useMemo(
@@ -3477,6 +3569,12 @@ function AdvancedChartImplInner({
34773569

34783570
// Horizontal bar — swap X/Y axis types and orientation.
34793571
const isHorizontal = chartType === 'horizontal-bar';
3572+
// Its category axis draws each label in full (no phone cut), wrapped into
3573+
// this width by `WrappedCategoryTick`.
3574+
const categoryTickFormatter = formatterFor(xAxisSpec?.format, displayLocale) ?? formatCategoryLabel;
3575+
const categoryAxisWidth = isHorizontal
3576+
? Math.min(140, Math.max(60, Math.ceil(Math.max(0, ...data.map((d) => estimateLabelWidthPx(String(categoryTickFormatter(d?.[xAxisKey]) ?? ''))))) + CATEGORY_TICK_INSET_PX))
3577+
: 0;
34803578

34813579
// Build vertical fill gradients (bar + area) for every colour in play, so
34823580
// fills read as a polished ramp instead of flat blocks (大屏 look). Inline
@@ -3492,6 +3590,30 @@ function AdvancedChartImplInner({
34923590
]));
34933591
const gslug = (c: string) => 'g' + c.replace(/[^a-zA-Z0-9]/g, '');
34943592

3593+
// A series' colour. A comparison series mirrors the colour of the primary
3594+
// series it overlays rather than taking a fresh palette slot: the first
3595+
// non-comparison series above it.
3596+
const seriesColorAt = (sIdx: number): string => {
3597+
const s = series[sIdx];
3598+
const isComparison = s?.variant === 'comparison';
3599+
const baseSeries = isComparison
3600+
? (series.slice(0, sIdx).find((p: any) => p.variant !== 'comparison') || series[0])
3601+
: s;
3602+
const baseIdx = isComparison ? series.indexOf(baseSeries) : sIdx;
3603+
return resolveColor(config[baseSeries.dataKey]?.color || _gpal[baseIdx % _gpal.length] || DEFAULT_CHART_COLOR);
3604+
};
3605+
// The legend's swatch per series. A bar or area mark fills from a gradient,
3606+
// so the colour recharts hands the legend is a paint-server reference no
3607+
// swatch can draw; the swatch takes the series colour instead. A comparison
3608+
// swatch is drawn hollow, the way its mark is muted, so it reads apart from
3609+
// the primary series it shares a colour with.
3610+
const legendSwatches: Record<string, LegendSwatch> = Object.fromEntries(
3611+
series.map((s: any, sIdx: number) => [
3612+
String(s.dataKey),
3613+
{ color: seriesColorAt(sIdx), comparison: s.variant === 'comparison' },
3614+
]),
3615+
);
3616+
34953617
return (
34963618
<ChartFrame title={title} subtitle={subtitle}>
34973619
<ChartFootnote note={joinNotes(xPositionNote, yPositionNote)}>
@@ -3543,14 +3665,18 @@ function AdvancedChartImplInner({
35433665
`position` included: `left` / `right` are its sides here
35443666
(objectui#10587, see `placeXAxis`). Its `title` follows them too,
35453667
laid out for an axis running down the plot (objectui#10654). */}
3668+
{/* The category labels wrap inside the axis width and carry the
3669+
full label as a tooltip when cut (`WrappedCategoryTick`); the
3670+
width is sized from the widest label, between 60 and 140 px. */}
35463671
<YAxis
35473672
type="category"
35483673
dataKey={xAxisKey}
3549-
tick={AXIS_TICK_STYLE}
3674+
tick={(tickProps: any) => (
3675+
<WrappedCategoryTick {...tickProps} maxWidthPx={categoryAxisWidth - CATEGORY_TICK_INSET_PX} formatLabel={categoryTickFormatter} />
3676+
)}
35503677
tickLine={false}
35513678
axisLine={false}
3552-
width={Math.min(140, Math.max(60, Math.max(...data.map(d => String(d[xAxisKey] ?? '').length)) * 7))}
3553-
tickFormatter={xTickFormatter}
3679+
width={categoryAxisWidth}
35543680
{...(xAxisDown ? { orientation: xAxisDown } : {})}
35553681
{...(xAxisSpec?.title ? { label: { value: xAxisSpec.title, ...yAxisTitleLayoutFor(xAxisDown) } } : {})}
35563682
/>
@@ -3608,23 +3734,15 @@ function AdvancedChartImplInner({
36083734
{tooltipsEnabled ? <ChartTooltip content={<ChartTooltipContent />} /> : null}
36093735
{legendVisible ? (
36103736
<ChartLegend
3611-
content={<ChartLegendContent />}
3737+
content={<ChartLegendContent swatches={legendSwatches} />}
36123738
{...(isMobile && { verticalAlign: "bottom", wrapperStyle: { fontSize: '11px', paddingTop: '8px' } })}
36133739
/>
36143740
) : null}
36153741
{annotationEls}
36163742
{brushEl}
36173743
{series.map((s: any, sIdx: number) => {
3618-
const palette = getPalette();
3619-
// Comparison series should mirror the color of the primary series
3620-
// they overlay, not be assigned a fresh palette color. Find the
3621-
// first non-comparison series above this one and reuse its color.
36223744
const isComparison = s.variant === 'comparison';
3623-
const baseSeries = isComparison
3624-
? (series.slice(0, sIdx).find((p: any) => p.variant !== 'comparison') || series[0])
3625-
: s;
3626-
const baseIdx = isComparison ? series.indexOf(baseSeries) : sIdx;
3627-
const seriesColor = resolveColor(config[baseSeries.dataKey]?.color || palette[baseIdx % palette.length] || DEFAULT_CHART_COLOR);
3745+
const seriesColor = seriesColorAt(sIdx);
36283746

36293747
// Spec `series[].yAxis` binds this series to a value-axis slot. Only
36303748
// meaningful once a second axis is declared, and bound to the id the

‎ui/packages/plugin-charts/src/ChartContainerImpl.tsx‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -445,12 +445,22 @@ function ChartTooltipContent({
445445

446446
const ChartLegend = Legend
447447

448+
/**
449+
* The swatch a legend item draws for a series, keyed by its `dataKey`, when
450+
* the chart knows better than the colour recharts hands the legend: a mark
451+
* filled from a gradient hands it a paint-server reference (`url(#…)`), which
452+
* no swatch can draw. A `comparison` series draws its swatch hollow, the way
453+
* its mark is muted.
454+
*/
455+
export type LegendSwatch = { color: string; comparison?: boolean }
456+
448457
function ChartLegendContent({
449458
className,
450459
hideIcon = false,
451460
payload,
452461
verticalAlign = "bottom",
453462
nameKey,
463+
swatches,
454464
}: any) {
455465
const { config } = useChart()
456466

@@ -471,6 +481,7 @@ function ChartLegendContent({
471481
.map((item: any) => {
472482
const key = `${nameKey || item.dataKey || "value"}`
473483
const itemConfig = getPayloadConfigFromPayload(config, item, key)
484+
const swatch: LegendSwatch | undefined = (swatches as Record<string, LegendSwatch> | undefined)?.[String(item.dataKey)]
474485

475486
return (
476487
<div
@@ -487,10 +498,16 @@ function ChartLegendContent({
487498
// same shape as the tooltip indicator above (AGENTS.md styling
488499
// carve-out; objectui#10021).
489500
<div
490-
className="h-2 w-2 shrink-0 rounded-[2px] bg-(--color-bg)"
501+
className={cn(
502+
"h-2 w-2 shrink-0 rounded-[2px]",
503+
swatch?.comparison
504+
? "border-[1.5px] border-(--color-bg) bg-transparent"
505+
: "bg-(--color-bg)"
506+
)}
507+
data-swatch={swatch?.comparison ? "comparison" : undefined}
491508
style={
492509
{
493-
"--color-bg": item.color,
510+
"--color-bg": swatch?.color ?? item.color,
494511
} as React.CSSProperties
495512
}
496513
/>

‎ui/packages/plugin-dashboard/src/DatasetWidget.tsx‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,10 @@ import {
9999
METRIC_TILE_CONTAINER_CLASS,
100100
METRIC_TILE_TITLE_CLASS,
101101
METRIC_TILE_MEASURE_LABEL_CLASS,
102-
METRIC_TILE_VALUE_CLASS,
102+
METRIC_TILE_DATASET_VALUE_LADDER,
103103
metricTileTooltip,
104+
metricTileValueClass,
105+
metricTileValueTitle,
104106
} from './metricTile';
105107
import { DrillDownDrawer } from './DrillDownDrawer';
106108
import { specDefaultWidgetType } from './widgetDispatch';
@@ -1389,6 +1391,7 @@ export function DatasetWidget({ widget, dataSource, heading, onForbidden }: {
13891391
// under the value, in place of the measure label, which then rides only in
13901392
// the title's tooltip (objectstack#27430).
13911393
const caption = heading?.description || measureLabel;
1394+
const shownValue = formatMeasure(value, f?.format, f?.currency, f?.percentScale, displayLocale);
13921395
return (
13931396
// Positioned only while a re-read is in flight, for the refresh bar: the
13941397
// idle tile's markup is pinned byte-for-byte (`DatasetWidget.colorVariant`,
@@ -1401,7 +1404,10 @@ export function DatasetWidget({ widget, dataSource, heading, onForbidden }: {
14011404
`./metricTile`). Without one, the tile's markup is unchanged: the
14021405
label is then the only text naming the value. */}
14031406
{heading && <MetricHeadingRow heading={heading} label={measureLabel} />}
1404-
<span className={cn(heading ? cn('font-semibold', METRIC_TILE_VALUE_CLASS) : 'text-2xl font-semibold tabular-nums', accentClass)}>{formatMeasure(value, f?.format, f?.currency, f?.percentScale, displayLocale)}</span>
1407+
{/* With a heading the value scales before it would clip: a long
1408+
money figure takes the dataset tile's ladder, and past its last
1409+
rung keeps the ellipsis with the full figure as its tooltip. */}
1410+
<span className={cn(heading ? cn('font-semibold', metricTileValueClass(shownValue, METRIC_TILE_DATASET_VALUE_LADDER)) : 'text-2xl font-semibold tabular-nums', accentClass)} title={heading ? metricTileValueTitle(shownValue) : undefined}>{shownValue}</span>
14051411
{heading && caption && (
14061412
<span className={METRIC_TILE_MEASURE_LABEL_CLASS} data-testid="dataset-metric-label">{caption}</span>
14071413
)}

0 commit comments

Comments
 (0)