Skip to content

Commit 0a67177

Browse files
committed
wip: object-metric polarity colours the trend badge; tests, changeset, skills line
Claude-Session: https://claude.ai/code/session_01JQwxbWhSYPUK8z26ntsh8g Co-authored-by: Claude <noreply@anthropic.com>
1 parent e4c8a1a commit 0a67177

11 files changed

Lines changed: 300 additions & 34 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@object-ui/plugin-dashboard': minor
4+
'@objectstack/skills': patch
5+
---
6+
7+
feat(spec): an inline `object-metric` tile declares `polarity`, so a lower-is-better KPI draws a rise red
8+
9+
Clause-②: yes (widening)
10+
Metadata-protocol: added (object-metric polarity)
11+
12+
A dataset measure has declared `polarity` since the dataset-bound KPI tile learned to colour its delta by it, but a page-level `object-metric` tile aggregates a field, not a dataset measure, so it had nothing to attach to and coloured its trend badge by direction alone: an average turnaround that rose 23% was drawn green.
13+
14+
- **Spec.** `ObjectMetricPropsSchema` (`ComponentPropsMap['object-metric']`) declares an optional top-level `polarity`, the dataset measure's own `DatasetMeasurePolarity` by reference: `higher`, `lower` or `neutral`. Any other value is refused at the key. `betterWhen`, `goodDirection` and `trendDirection` are pointed at `polarity`; a top-level `direction` is answered with both keys it could mean (`trend.direction` for the static badge's arrow, `polarity` for good news); `higherIsBetter` / `lowerIsBetter` get the three values.
15+
- **Renderer.** `ObjectMetricWidget` forwards `polarity` to `MetricWidget`, which colours the badge it draws, the `compareTo`-derived one or the static `trend`, by the same rule the dataset-bound tile uses (`deltaToneClass`, now one shared helper): `lower` draws a rise red and a fall green, `neutral` draws it muted. The arrow always shows which way the number moved. The `object-metric` registration publishes the input.
16+
- **Undeclared keeps today's colours exactly**: a rise green, a fall red. Nothing infers a polarity from the aggregated field's name.
17+
- **Skills.** `objectstack-ui` `rules/dashboards.md` says an inline `object-metric` declares its own `polarity`.
18+
19+
Nothing to do for existing tiles. To use it, add `polarity: 'lower'` to an `object-metric` node whose number is better when it falls.

‎packages/spec/authorable-surface/ui.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -985,6 +985,7 @@
985985
"ui/ObjectMetricProps:invert",
986986
"ui/ObjectMetricProps:label",
987987
"ui/ObjectMetricProps:objectName",
988+
"ui/ObjectMetricProps:polarity",
988989
"ui/ObjectMetricProps:prefix",
989990
"ui/ObjectMetricProps:suffix",
990991
"ui/ObjectMetricProps:title",

‎packages/spec/liveness/page.json‎

Lines changed: 1 addition & 1 deletion
Large diffs are not rendered by default.
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* `object-metric.polarity` — which direction of change is good news for an
5+
* inline KPI tile, so a "lower is better" tile colours a rising delta as bad
6+
* (#27347).
7+
*
8+
* The tile aggregates a field, not a dataset measure, so the measure's own
9+
* `polarity` (#26602) had nothing to attach to. The tile now declares the SAME
10+
* key, by reference to `DatasetMeasurePolarity`: the three peer values parse
11+
* and keep their value, an absent key parses exactly as before (no default is
12+
* materialized, so the renderer's undeclared arm keeps today's colours), any
13+
* other value is refused at the key, and the near-miss spellings are pointed
14+
* at it — except the bare `direction`, which on this tile is the static
15+
* `trend` badge's arrow and gets a prescription naming both keys.
16+
*/
17+
18+
import { describe, it, expect } from 'vitest';
19+
import { ObjectMetricPropsSchema, type ObjectMetricProps } from './component.zod';
20+
import { DatasetMeasurePolarity } from './dataset.zod';
21+
22+
const tile = {
23+
objectName: 'approval',
24+
label: 'Avg. turnaround',
25+
aggregate: { field: 'turnaround_days', function: 'avg' as const },
26+
compareTo: { kind: 'previousPeriod' as const },
27+
};
28+
29+
describe('ObjectMetricPropsSchema.polarity', () => {
30+
it.each(['higher', 'lower', 'neutral'] as const)('accepts %s and keeps the value', (polarity) => {
31+
const parsed = ObjectMetricPropsSchema.safeParse({ ...tile, polarity });
32+
expect(parsed.success).toBe(true);
33+
expect(parsed.data?.polarity).toBe(polarity);
34+
});
35+
36+
it('is the dataset measure\'s vocabulary, by reference — not a second spelling', () => {
37+
expect(ObjectMetricPropsSchema.shape.polarity.unwrap()).toBe(DatasetMeasurePolarity);
38+
});
39+
40+
it('an absent polarity parses exactly as before: no key is materialized', () => {
41+
const parsed = ObjectMetricPropsSchema.safeParse(tile);
42+
expect(parsed.success).toBe(true);
43+
expect(Object.prototype.hasOwnProperty.call(parsed.data, 'polarity')).toBe(false);
44+
});
45+
46+
it.each(['up', 'down', 'good', 'inverse', true])('refuses %j at the key', (polarity) => {
47+
const parsed = ObjectMetricPropsSchema.safeParse({ ...tile, polarity });
48+
expect(parsed.success).toBe(false);
49+
expect(parsed.error?.issues.map((i) => [i.code, i.path])).toEqual([['invalid_value', ['polarity']]]);
50+
});
51+
52+
it.each(['betterWhen', 'goodDirection', 'trendDirection'])('points the near-miss `%s` at `polarity`', (key) => {
53+
const parsed = ObjectMetricPropsSchema.safeParse({ ...tile, [key]: 'lower' });
54+
expect(parsed.success).toBe(false);
55+
const issue = parsed.error?.issues.find((i) => i.code === 'unrecognized_keys');
56+
expect(issue).toBeDefined();
57+
expect(issue?.message).toContain('`polarity`');
58+
});
59+
60+
it('answers a top-level `direction` with BOTH keys it could mean', () => {
61+
const parsed = ObjectMetricPropsSchema.safeParse({ ...tile, direction: 'lower' });
62+
expect(parsed.success).toBe(false);
63+
const issue = parsed.error?.issues.find((i) => i.code === 'unrecognized_keys');
64+
expect(issue?.message).toContain('`trend`');
65+
expect(issue?.message).toContain('`polarity`');
66+
});
67+
68+
it.each(['lowerIsBetter', 'higherIsBetter'])('answers the boolean-flag spelling `%s` with the three values', (key) => {
69+
const parsed = ObjectMetricPropsSchema.safeParse({ ...tile, [key]: true });
70+
expect(parsed.success).toBe(false);
71+
const issue = parsed.error?.issues.find((i) => i.code === 'unrecognized_keys');
72+
expect(issue?.message).toContain("polarity: 'lower'");
73+
expect(issue?.message).toContain("polarity: 'neutral'");
74+
});
75+
76+
it('the authored type admits the three values and refuses any other', () => {
77+
const lower: ObjectMetricProps = { ...tile, polarity: 'lower' };
78+
// @ts-expect-error — `up` is a trend direction, not a polarity.
79+
const wrong: ObjectMetricProps = { ...tile, polarity: 'up' };
80+
expect([lower.polarity, wrong.polarity]).toEqual(['lower', 'up']);
81+
});
82+
});

‎skills/objectstack-ui/rules/dashboards.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -246,9 +246,9 @@ compareTo: { kind: 'previousYear', dimension: 'close_date' } // several —
246246
```
247247

248248
* **Metric widgets** — a delta arrow plus a trend label from the kind (`vs
249-
previous period`). Its colour follows the measure's `polarity`: `'lower'`
250-
(turnaround, cost) draws a rise red, `'neutral'` uncoloured; undeclared =
251-
rise green. `options.trend` reaches no renderer; `compareTo` is the trend.
249+
previous period`). Its colour follows `polarity` (the measure's; an inline
250+
`object-metric` declares its own): `'lower'` (turnaround, cost) draws a rise
251+
red, `'neutral'` uncoloured; undeclared = rise green. `compareTo` is the trend.
252252
* **Cartesian charts** (`line` / `area` / `bar` / `horizontal-bar` /
253253
`scatter`) — the comparison series is appended after the primary series
254254
with `variant: 'comparison'`, muted per family (dashed `'4 4'` on

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

Lines changed: 4 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ import { AlertTriangle, ShieldAlert, Download, ArrowUpIcon, ArrowDownIcon, Minus
9292
// surface (see that component's header for why it is dashboard-local).
9393
import { WidgetEmptyState } from './WidgetEmptyState';
9494
import { useFilterScope } from '@object-ui/react';
95-
import { resolveFilterPlaceholders, computeMetricDelta, formatMetricDeltaPercent, type MetricDelta } from './utils';
95+
import { resolveFilterPlaceholders, computeMetricDelta, formatMetricDeltaPercent, deltaToneClass } from './utils';
9696
import { metricAccentTextClass } from './colorVariants';
9797
import {
9898
METRIC_TILE_CONTAINER_CLASS,
@@ -265,31 +265,9 @@ const COMPARE_KIND_TREND_KEY = {
265265
previousYear: 'vsLastYear',
266266
} as const satisfies Record<CompareToConfig['kind'], string>;
267267

268-
/**
269-
* The good/bad colour of a period-over-period delta, judged by the measure's
270-
* declared polarity (objectstack#26602). The dataset measure's `polarity`
271-
* reaches this widget on the answer's column descriptor (`fields[].polarity`),
272-
* relayed by the server like `format` and `currency`.
273-
*
274-
* - `lower`: a fall is good news (green) and a rise is bad (red). Turnaround
275-
* days, overdue counts, cost: a slower approval no longer reads as a win.
276-
* - `neutral`: neither direction is good or bad, so no tone at all.
277-
* - `higher`, and an UNDECLARED polarity: a rise green, a fall red, the
278-
* colours every delta had before the key existed. Nothing here guesses a
279-
* polarity from the measure's name or unit.
280-
*
281-
* The arrow is not this function's business: it always shows which way the
282-
* number moved. A flat delta (`direction: 'neutral'`) takes no tone under any
283-
* polarity, as before.
284-
*/
285-
function deltaToneClass(
286-
direction: MetricDelta['direction'],
287-
polarity: DatasetResultField['polarity'],
288-
): string | undefined {
289-
if (direction === 'neutral' || polarity === 'neutral') return undefined;
290-
const good = polarity === 'lower' ? direction === 'down' : direction === 'up';
291-
return good ? 'text-emerald-600 dark:text-emerald-400' : 'text-rose-600 dark:text-rose-400';
292-
}
268+
// The good/bad colour of a delta by the measure's declared polarity is
269+
// `deltaToneClass` in `./utils` (objectstack#26602): one rule shared with the
270+
// inline `object-metric` tile's badge (objectstack#27347).
293271

294272
/**
295273
* ISO calendar date, optionally carrying a time part — `2026-01-15`,

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

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,12 @@ import {
1616
type DisplayNumberFormatOptions,
1717
} from '@object-ui/i18n';
1818
import type { I18nLabel } from '@object-ui/types';
19+
import type { ObjectMetricProps } from '@objectstack/spec/ui';
1920
import { ArrowDownIcon, ArrowUpIcon, MinusIcon, AlertCircle, Loader2 } from 'lucide-react';
2021
import { VARIANT_ICON_CLASSES, VARIANT_TEXT_CLASSES, type MetricColorVariant } from './colorVariants';
2122
import { hostDomProps, type SchemaHostProps } from './schemaHostProps';
2223
import { METRIC_TILE_CONTAINER_CLASS, METRIC_TILE_TITLE_CLASS, metricTileValueClass, metricTileValueTitle } from './metricTile';
23-
import { formatMetricDeltaPercent, type MetricDelta } from './utils';
24+
import { formatMetricDeltaPercent, deltaToneClass, type MetricDelta } from './utils';
2425

2526
const TREND_LABEL_DEFAULTS: Record<string, string> = {
2627
'dashboard.trend.vsLastQuarter': 'vs last quarter',
@@ -280,6 +281,16 @@ export interface MetricWidgetProps extends React.HTMLAttributes<HTMLDivElement>
280281
* `trend.value` stays the number the spec declares.
281282
*/
282283
derivedTrend?: MetricDelta & { label?: string };
284+
/**
285+
* Which direction of change is good news for this number, BY REFERENCE to
286+
* the `object-metric` row's own key (`ObjectMetricProps['polarity']` in
287+
* `@objectstack/spec/ui`, the dataset measure's vocabulary). It colours the
288+
* badge drawn, `derivedTrend ?? trend`, by the rule the dataset-bound tile
289+
* applies (`deltaToneClass` in `./utils`): `lower` draws a rise red and a
290+
* fall green, `neutral` draws both muted. Undeclared keeps rise green, fall
291+
* red. The arrow always follows the number (objectstack#27347).
292+
*/
293+
polarity?: ObjectMetricProps['polarity'];
283294
icon?: React.ReactNode | string;
284295
className?: string;
285296
description?: string | I18nLabel;
@@ -328,6 +339,7 @@ export const MetricWidget = ({
328339
value,
329340
trend,
330341
derivedTrend,
342+
polarity,
331343
icon,
332344
className,
333345
description,
@@ -486,9 +498,8 @@ export const MetricWidget = ({
486498
{shownTrend && (
487499
<span className={cn(
488500
"flex items-center shrink-0 font-medium",
489-
shownTrend.direction === 'up' && "text-emerald-600 dark:text-emerald-400",
490-
shownTrend.direction === 'down' && "text-rose-600 dark:text-rose-400",
491-
shownTrend.direction === 'neutral' && "text-muted-foreground"
501+
deltaToneClass(shownTrend.direction, polarity),
502+
(shownTrend.direction === 'neutral' || polarity === 'neutral') && "text-muted-foreground"
492503
)}>
493504
{shownTrend.direction === 'up' && <ArrowUpIcon className="h-3 w-3 mr-1" />}
494505
{shownTrend.direction === 'down' && <ArrowDownIcon className="h-3 w-3 mr-1" />}

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import React, { useState, useEffect, useContext, useCallback, useMemo } from 're
1010
import { SchemaRendererContext, useFilterScope, useDataInvalidation } from '@object-ui/react';
1111
import { isDrillEnabled, resolveDrillTitle, isStructuredGroupBy, objectAggregateSpecQuery, toFilterNode } from '@object-ui/core';
1212
import type { I18nLabel, ObjectChartSchema, ObjectMetricDrillDownConfig } from '@object-ui/types';
13+
import type { ObjectMetricProps } from '@objectstack/spec/ui';
1314
import {
1415
useLocalization,
1516
useDisplayLocale,
@@ -288,6 +289,16 @@ export interface ObjectMetricWidgetProps {
288289
* comparison window.
289290
*/
290291
compareTo?: CompareToConfig;
292+
/**
293+
* Which direction of change is good news for this tile's number — the
294+
* `object-metric` row's own key, BY REFERENCE (`ObjectMetricProps['polarity']`
295+
* in `@objectstack/spec/ui`, the dataset measure's `higher | lower | neutral`
296+
* vocabulary). Forwarded to `MetricWidget`, which colours the badge it draws,
297+
* the `compareTo`-derived one or the static `trend`, by it. Undeclared keeps
298+
* rise green, fall red; nothing infers it from the aggregated field's name
299+
* (objectstack#27347).
300+
*/
301+
polarity?: ObjectMetricProps['polarity'];
291302
/** Optional i18n translator used to localize the trend label. */
292303
t?: (key: string, defaultValue: string) => string;
293304
/** Layout variant forwarded to MetricWidget: 'card' (default) or 'bare'. */
@@ -314,6 +325,7 @@ export const ObjectMetricWidget: React.FC<ObjectMetricWidgetProps> = ({
314325
drillDown,
315326
title,
316327
compareTo,
328+
polarity,
317329
t: tProp,
318330
variant,
319331
}) => {
@@ -752,6 +764,7 @@ export const ObjectMetricWidget: React.FC<ObjectMetricWidgetProps> = ({
752764
value={tileValue}
753765
trend={trend}
754766
derivedTrend={derivedTrend}
767+
polarity={polarity}
755768
icon={icon}
756769
className={className}
757770
description={description}
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#27347 — an inline `object-metric` tile colours its trend badge by
5+
* its declared `polarity`.
6+
*
7+
* The dataset-bound tile has coloured its delta by the measure's `polarity`
8+
* since objectstack#26602, but a page-level `object-metric` node aggregates a
9+
* field, not a dataset measure, so it coloured by direction alone: an average
10+
* turnaround that rose 20% was drawn green. The node now declares `polarity`
11+
* itself, in the measure's vocabulary, and `MetricWidget` colours the badge it
12+
* draws (`derivedTrend ?? trend`) by the one shared rule, `deltaToneClass`:
13+
* - `lower`: a rise is red, a fall is green;
14+
* - `neutral`: no good/bad colour, the muted text colour;
15+
* - `higher`: a rise is green, a fall is red;
16+
* - undeclared: exactly today's class string, with no guess from the field's
17+
* name — the fixture aggregates a field literally named `turnaround_days`.
18+
*
19+
* The arrow is the number's direction under every polarity. The `compareTo`
20+
* rows mount the REGISTERED block through `SchemaRenderer` (its
21+
* `ElementDataSourceGate` shell forwards every authored key but `objectName`
22+
* and `filter` untouched), so the pin covers the path an author reaches. The
23+
* static `trend` badge is the same badge, so one top-level key covers it too.
24+
*/
25+
26+
import { describe, it, expect, vi, afterEach } from 'vitest';
27+
import { render, screen, cleanup } from '@testing-library/react';
28+
import { SchemaRenderer, SchemaRendererProvider } from '@object-ui/react';
29+
// Registers `object-metric` at MODULE scope, never inside a hook
30+
// (object-ui/no-dynamic-import-in-test-hook).
31+
import '../index';
32+
33+
afterEach(cleanup);
34+
35+
const GOOD = /text-emerald-600/;
36+
const BAD = /text-rose-600/;
37+
const MUTED = /text-muted-foreground/;
38+
39+
type Polarity = 'higher' | 'lower' | 'neutral' | undefined;
40+
41+
const quarterStart = (d: Date) => new Date(d.getFullYear(), Math.floor(d.getMonth() / 3) * 3, 1);
42+
const iso = (d: Date) =>
43+
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
44+
const CURRENT_FROM = iso(quarterStart(new Date()));
45+
46+
/** The current window answers `current`; every shifted window answers `previous`. */
47+
const comparingAdapter = (current: number, previous: number) => ({
48+
aggregate: vi.fn(async (_object: string, q: { filter?: { submitted_on?: { $gte?: string } } }) => [
49+
{ turnaround_days_avg: String(q?.filter?.submitted_on?.$gte) === CURRENT_FROM ? current : previous },
50+
]),
51+
});
52+
53+
const mount = (schema: Record<string, unknown>, adapter?: unknown) =>
54+
render(
55+
<SchemaRendererProvider dataSource={adapter as never}>
56+
<SchemaRenderer
57+
schema={{ type: 'object-metric', objectName: 'approval', label: 'Avg. turnaround', ...schema } as never}
58+
/>
59+
</SchemaRendererProvider>,
60+
);
61+
62+
/** The `compareTo`-derived badge of an `object-metric` node declaring `polarity`. */
63+
async function derivedBadge(current: number, previous: number, polarity: Polarity) {
64+
mount(
65+
{
66+
aggregate: { field: 'turnaround_days', function: 'avg' },
67+
filter: { submitted_on: { $gte: '{current_quarter_start}', $lte: '{current_quarter_end}' } },
68+
compareTo: { kind: 'previousPeriod' },
69+
...(polarity ? { polarity } : {}),
70+
},
71+
comparingAdapter(current, previous),
72+
);
73+
return screen.findByText('20%');
74+
}
75+
76+
const arrow = (badge: HTMLElement) => badge.querySelector('svg')?.getAttribute('class') ?? '';
77+
78+
describe('object-metric — trend badge colour by declared `polarity` (objectstack#27347)', () => {
79+
it('lower: a rise is drawn bad, with the up arrow kept', async () => {
80+
const badge = await derivedBadge(120, 100, 'lower');
81+
expect(badge.className).toMatch(BAD);
82+
expect(badge.className).not.toMatch(GOOD);
83+
expect(arrow(badge)).toMatch(/arrow-up/);
84+
});
85+
86+
it('lower: a fall is drawn good, with the down arrow kept', async () => {
87+
const badge = await derivedBadge(80, 100, 'lower');
88+
expect(badge.className).toMatch(GOOD);
89+
expect(badge.className).not.toMatch(BAD);
90+
expect(arrow(badge)).toMatch(/arrow-down/);
91+
});
92+
93+
it('higher: a rise is drawn good, as before', async () => {
94+
const badge = await derivedBadge(120, 100, 'higher');
95+
expect(badge.className).toMatch(GOOD);
96+
expect(badge.className).not.toMatch(BAD);
97+
});
98+
99+
it('neutral: neither a rise nor a fall takes a good/bad colour', async () => {
100+
for (const [current, direction] of [[120, /arrow-up/], [80, /arrow-down/]] as const) {
101+
const badge = await derivedBadge(current, 100, 'neutral');
102+
expect(badge.className).not.toMatch(GOOD);
103+
expect(badge.className).not.toMatch(BAD);
104+
expect(badge.className).toMatch(MUTED);
105+
expect(arrow(badge)).toMatch(direction);
106+
cleanup();
107+
}
108+
});
109+
110+
it('CONTROL — undeclared draws today\'s class string byte for byte, never guessed from the field name', async () => {
111+
const rise = await derivedBadge(120, 100, undefined);
112+
expect(rise.className).toBe('flex items-center shrink-0 font-medium text-emerald-600 dark:text-emerald-400');
113+
cleanup();
114+
const fall = await derivedBadge(80, 100, undefined);
115+
expect(fall.className).toBe('flex items-center shrink-0 font-medium text-rose-600 dark:text-rose-400');
116+
});
117+
118+
it('colours the static `trend` badge by the same key', () => {
119+
mount({ fallbackValue: 4.2, trend: { value: 12, direction: 'up' }, polarity: 'lower' });
120+
const badge = screen.getByText('12%');
121+
expect(badge.className).toMatch(BAD);
122+
expect(arrow(badge)).toMatch(/arrow-up/);
123+
});
124+
125+
it('CONTROL — a static badge with no `direction` takes no tone under any polarity', () => {
126+
mount({ fallbackValue: 4.2, trend: { value: 12 }, polarity: 'lower' });
127+
const badge = screen.getByText('12%');
128+
expect(badge.className).toBe('flex items-center shrink-0 font-medium');
129+
});
130+
});

0 commit comments

Comments
 (0)