Skip to content

Commit b317942

Browse files
fix(plugin-charts): a dataset object-chart draws a select dimension in declared option order (objectui#13403) (#13426)
Closes #13403 Clause-②: no ## What changed A page-level `object-chart` bound to a `dataset` now draws a select dimension in its field's declared option order, as the dashboard's `DatasetWidget` already does for the same dataset (objectui#11809). The showcase command center's priority panel read 高, 低, 中, 紧急 (the GROUP BY order of `high, low, medium, urgent`) and now reads 低 → 中 → 高 → 紧急. `packages/plugin-charts/src/ObjectChart.tsx` is the only source file touched: - The memo that already derives the option colours and dimension labels from the first dimension's localized options now also derives `categoryOrder` with `@object-ui/core`'s `buildCategoryOrder`. This applies on the dataset path only, and only when the chart names a dimension. A field with no options gives `null`, so nothing changes for it. - The rows are sorted by that order before `buildChartSeries`: declared options first, then values the options do not declare, then the empty bucket. The sort is stable. The order is put on the rows because `AdvancedChartImpl` reads `categoryOrder` only in its funnel branch. A bar, line or pie draws its rows in the order it receives them, which is also why the dashboard sorts its `plotRows` itself. - The schema handed to `ChartRenderer` carries `categoryOrder`, the same key the dashboard hands it, which the funnel orders its stages by. ## Judgment calls (premise check) - **No helper move.** `buildCategoryOrder` and `buildCategoryRank` already live in `@object-ui/core`, which `plugin-charts` depends on. `DatasetWidget.tsx` is untouched. - **Passing `categoryOrder` alone would not have fixed the card.** The card's mechanism is that "`AdvancedChartImpl` honours it through `buildCategoryRank(categoryOrder)`". On `main` that holds only for the funnel. The card's own panels are bars, so the rows had to be ordered as well. `AdvancedChartImpl.tsx` is untouched (another agent is editing it). - **One local helper, `declaredOptionPosition`.** It applies the same rule as the private function of the same name in `DatasetWidget`. `DatasetReportRenderer` has a third private copy. Moving it to `@object-ui/core` would add a core file to this card's declared surface, so this PR does not do it. It is recorded below as a possible follow-up. - **Gate is "the field declares options", not "the field type is select".** This matches the dashboard: `DimensionFieldMeta` carries no field type, and `buildCategoryOrder` returns `null` for a field without options. ## Tests New file `packages/plugin-charts/src/ObjectChart.categoryOrder-13403.test.tsx`, 3 tests: - The card's shape. Answered rows `high, low, medium, urgent` reach the renderer as 低, 中, 高, 紧急, with their measures `[2, 7, 5, 1]`, and `categoryOrder` equals `buildCategoryOrder(options)`, which is `['low','低','medium','中','high','高','urgent','紧急']`. - A value the options do not declare (`blocked`) comes after the declared ones, and the null bucket comes last. - Control: a dimension whose field declares no options gets no `categoryOrder` key and keeps the dataset's answered order. Results at head `2fa5702bc3`: - New file: 3/3 passed. - `pnpm exec vitest run --maxWorkers=2 packages/plugin-charts/`: 98 files, 1268 passed, 9 skipped. - Dashboard #11809 controls, unchanged: `DatasetWidget.selectOptionOrder-11809.test.tsx` and `DatasetWidget.optionLabelI18n.test.tsx`, 2 files, 15/15 passed. - `turbo run type-check --filter=@object-ui/plugin-charts...`: 19/19 tasks successful. `plugin-dashboard` was not touched. - `eslint` on the two touched files: 0 errors and 35 warnings. The same file at base also gives 35 warnings, so none are new. - `node scripts/check-changeset-presence.mjs`: passes (one patch changeset for `@object-ui/plugin-charts`). - `pnpm check:new-line-citations`: 0 new. Ablation was run on the committed fix, restored with `git checkout HEAD`, and the restored blob hash matches HEAD: - Leg A, row sort disabled: 2 failed, 1 passed (the two ordering tests fail; the control passes). - Leg B, `categoryOrder` hand-off removed: 2 failed, 1 passed. ## Acceptance notes - The second dimension's series order is not applied on this path. The dashboard also orders a pivoted second select dimension's legend (`seriesOrder`, objectui#11809). The card names the category axis only, so this PR leaves the series as they are. - `ChartRenderer`'s doc comment on `categoryOrder` still says it is "Set by DatasetWidget". `ObjectChart` now sets it too. `ChartRenderer.tsx` is outside this card's surface. - `declaredOptionPosition` now has three private copies: `DatasetWidget`, `DatasetReportRenderer` and `ObjectChart`. A single home in `@object-ui/core` is a possible follow-up. - [x] Adds no product-specific widget, dialog, hook or string (see AGENTS.md › Product-neutral renderer) Session: `https://claude.ai/code/session_01WJozybDmRH8z2c5SD7vJkj` --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WJozybDmRH8z2c5SD7vJkj Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2c3dc72 commit b317942

3 files changed

Lines changed: 277 additions & 6 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@object-ui/plugin-charts': patch
3+
---
4+
5+
A page-level `object-chart` bound to a `dataset` now draws a select dimension in the order its field declares its options, the order the dashboard's dataset widget already uses for the same dataset (objectui#11809). Before, the page block drew the dataset's GROUP BY order (the stored values, alphabetically), so a priority axis read High, Low, Medium, Urgent instead of Low, Medium, High, Urgent (objectui#13403). The rows are charted in declared order, values the options do not declare follow, and the empty bucket comes last; the schema handed to the renderer also carries the `categoryOrder` from `@object-ui/core`'s `buildCategoryOrder`, which a funnel orders its stages by. A dimension whose field declares no options keeps the dataset's order.
Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
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+
* objectui#13403 — a page-level `object-chart` bound to a `dataset` draws a
9+
* select dimension in the order its field DECLARES its options, the order the
10+
* dashboard's `DatasetWidget` already draws the same dataset in (objectui#11809).
11+
*
12+
* The dataset answers its buckets in GROUP BY order, the stored values'
13+
* alphabetical order, so the showcase command center's priority panel read
14+
* 高, 低, 中, 紧急 (`high, low, medium, urgent`) while the dashboards read
15+
* 低 → 中 → 高 → 紧急. Two halves are pinned, because the renderer reads them
16+
* on different chart families:
17+
* - the rows handed to `ChartRenderer` are in declared order (a bar, line or
18+
* pie draws its rows as handed);
19+
* - the schema carries `categoryOrder` from core's `buildCategoryOrder`, the
20+
* key `AdvancedChartImpl` orders a funnel by.
21+
*
22+
* Controls: a dimension whose field declares no options gets no
23+
* `categoryOrder` and keeps the dataset's answered order.
24+
*/
25+
26+
import type { DataSource } from '@object-ui/types';
27+
import React from 'react';
28+
import { describe, it, expect, vi, afterEach } from 'vitest';
29+
import { render, cleanup, waitFor } from '@testing-library/react';
30+
import { buildCategoryOrder } from '@object-ui/core';
31+
32+
type CapturedSchema = {
33+
data?: Array<Record<string, unknown>>;
34+
xAxisKey?: string;
35+
series?: Array<{ dataKey: string; label?: string }>;
36+
categoryOrder?: string[];
37+
};
38+
39+
let lastSchema: CapturedSchema | null = null;
40+
41+
vi.mock('./ChartRenderer', () => ({
42+
ChartRenderer: (props: { schema: CapturedSchema }) => {
43+
lastSchema = props.schema;
44+
return null;
45+
},
46+
}));
47+
48+
import { ObjectChart } from './ObjectChart';
49+
50+
const PRIORITY_OPTIONS = [
51+
{ value: 'low', label: '低' },
52+
{ value: 'medium', label: '中' },
53+
{ value: 'high', label: '高' },
54+
{ value: 'urgent', label: '紧急' },
55+
];
56+
57+
/** Answers only the documents it is given; anything else is an empty doc. */
58+
function installMetaFetchDouble(routes: Record<string, unknown>) {
59+
vi.stubGlobal(
60+
'fetch',
61+
vi.fn(async (input: unknown) => {
62+
const url = String(input);
63+
return { ok: true, json: async () => routes[url] ?? {} };
64+
}),
65+
);
66+
}
67+
68+
function metaRoutes(dimensions: Array<{ name: string; field: string }>) {
69+
return {
70+
'/api/v1/meta/dataset/showcase_task_metrics': {
71+
item: { name: 'showcase_task_metrics', object: 'task', dimensions },
72+
},
73+
'/api/v1/meta/object/task': {
74+
item: {
75+
name: 'task',
76+
fields: {
77+
priority: { type: 'select', options: PRIORITY_OPTIONS },
78+
assignee: { type: 'text' },
79+
},
80+
},
81+
},
82+
};
83+
}
84+
85+
/**
86+
* A partial data source carrying only `queryDataset`, the one member the
87+
* dataset path calls — crossed into the published contract explicitly
88+
* (objectui#7912), as the sibling ObjectChart suites do.
89+
*/
90+
function datasetSource(rows: Array<Record<string, unknown>>, fields: Array<{ name: string; label: string }>) {
91+
return { queryDataset: vi.fn().mockResolvedValue({ rows, fields }) } as unknown as DataSource;
92+
}
93+
94+
const categoriesOf = (schema: CapturedSchema | null) =>
95+
(schema?.data ?? []).map((row) => row[schema!.xAxisKey!]);
96+
97+
afterEach(() => {
98+
vi.unstubAllGlobals();
99+
cleanup();
100+
lastSchema = null;
101+
});
102+
103+
describe('ObjectChart — a dataset chart draws a select dimension in declared option order (objectui#13403)', () => {
104+
it('orders the categories 低 → 中 → 高 → 紧急 and hands the declared `categoryOrder`', async () => {
105+
installMetaFetchDouble(metaRoutes([{ name: 'priority', field: 'priority' }]));
106+
107+
render(
108+
<ObjectChart
109+
schema={{
110+
type: 'object-chart' as const,
111+
chartType: 'bar' as const,
112+
dataset: 'showcase_task_metrics',
113+
dimensions: ['priority'],
114+
values: ['task_count'],
115+
}}
116+
// GROUP BY order: the stored values, alphabetically.
117+
dataSource={datasetSource(
118+
[
119+
{ priority: 'high', task_count: 5 },
120+
{ priority: 'low', task_count: 2 },
121+
{ priority: 'medium', task_count: 7 },
122+
{ priority: 'urgent', task_count: 1 },
123+
],
124+
[
125+
{ name: 'priority', label: 'Priority' },
126+
{ name: 'task_count', label: 'Tasks' },
127+
],
128+
)}
129+
/>,
130+
);
131+
132+
await waitFor(() => expect(lastSchema?.categoryOrder).toBeDefined());
133+
// Core's own reading of the field's options — reused, not re-derived.
134+
expect(lastSchema!.categoryOrder).toEqual(buildCategoryOrder(PRIORITY_OPTIONS));
135+
expect(lastSchema!.categoryOrder).toEqual(['low', '低', 'medium', '中', 'high', '高', 'urgent', '紧急']);
136+
expect(categoriesOf(lastSchema)).toEqual(['低', '中', '高', '紧急']);
137+
// The measure travels with its category.
138+
expect(lastSchema!.data!.map((row) => row.task_count)).toEqual([2, 7, 5, 1]);
139+
});
140+
141+
it('puts a value the options do not declare after the declared ones, and the empty bucket last', async () => {
142+
installMetaFetchDouble(metaRoutes([{ name: 'priority', field: 'priority' }]));
143+
144+
render(
145+
<ObjectChart
146+
schema={{
147+
type: 'object-chart' as const,
148+
chartType: 'bar' as const,
149+
dataset: 'showcase_task_metrics',
150+
dimensions: ['priority'],
151+
values: ['task_count'],
152+
}}
153+
dataSource={datasetSource(
154+
[
155+
{ priority: null, task_count: 4 },
156+
{ priority: 'blocked', task_count: 3 },
157+
{ priority: 'high', task_count: 5 },
158+
{ priority: 'low', task_count: 2 },
159+
],
160+
[
161+
{ name: 'priority', label: 'Priority' },
162+
{ name: 'task_count', label: 'Tasks' },
163+
],
164+
)}
165+
/>,
166+
);
167+
168+
await waitFor(() => expect(lastSchema?.categoryOrder).toBeDefined());
169+
expect(lastSchema!.data!.map((row) => row.task_count)).toEqual([2, 5, 3, 4]);
170+
expect(categoriesOf(lastSchema).slice(0, 3)).toEqual(['低', '高', 'blocked']);
171+
});
172+
173+
it('control: a dimension whose field declares no options gets no `categoryOrder` and keeps the answered order', async () => {
174+
// The second dimension is the select one, so its relabel (高 in the series
175+
// labels) is the observable sign that the field metadata has landed — the
176+
// point after which a `categoryOrder` would have appeared.
177+
installMetaFetchDouble(
178+
metaRoutes([
179+
{ name: 'assignee', field: 'assignee' },
180+
{ name: 'priority', field: 'priority' },
181+
]),
182+
);
183+
184+
render(
185+
<ObjectChart
186+
schema={{
187+
type: 'object-chart' as const,
188+
chartType: 'bar' as const,
189+
dataset: 'showcase_task_metrics',
190+
dimensions: ['assignee', 'priority'],
191+
values: ['task_count'],
192+
}}
193+
dataSource={datasetSource(
194+
[
195+
{ assignee: 'zoe', priority: 'high', task_count: 5 },
196+
{ assignee: 'amy', priority: 'low', task_count: 2 },
197+
],
198+
[
199+
{ name: 'assignee', label: 'Assignee' },
200+
{ name: 'priority', label: 'Priority' },
201+
{ name: 'task_count', label: 'Tasks' },
202+
],
203+
)}
204+
/>,
205+
);
206+
207+
await waitFor(() =>
208+
expect((lastSchema?.series ?? []).map((s) => s.label)).toContain('高'),
209+
);
210+
expect(lastSchema).not.toHaveProperty('categoryOrder');
211+
expect(categoriesOf(lastSchema)).toEqual(['zoe', 'amy']);
212+
});
213+
});

‎packages/plugin-charts/src/ObjectChart.tsx‎

Lines changed: 59 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import React, { useState, useEffect, useContext, useCallback, useMemo } from 're
33
import { useDataScope, SchemaRendererContext, SchemaRenderer, useDrillNavigation, useFilterScope, ElementDataSourceGate, useDataInvalidation, type ElementDataSourceMapping } from '@object-ui/react';
44
import { ChartRenderer } from './ChartRenderer';
55
import { normalizeChartSchema } from './normalizeChartSchema';
6-
import { ComponentRegistry, chartMeasureKey, isStructuredGroupBy, objectAggregateSpecQuery, humanizeLabel, extractRecords, computeDrillFilter, composeDrillFilter, FilterOperatorError, isDrillEnabled, resolveDrillTitle, resolveFilterPlaceholders, resolveContextTokens, shiftFilterByCompareTo, compareToTrendLabelKey, chartTypeIgnoresCompareTo, buildChartSeries, buildOptionColorMap, deriveDimensionLabelMaps, dimensionOptionTranslator, loadDimensionFieldMeta, relabelDimensions, localizeFieldOptions, elementDataSourceBlock, type DimensionFieldMeta, type CompareToConfig, type DrillEvent, type ChartResultField, type ChartSegmentClickEvent } from '@object-ui/core';
6+
import { ComponentRegistry, chartMeasureKey, isStructuredGroupBy, objectAggregateSpecQuery, humanizeLabel, extractRecords, computeDrillFilter, composeDrillFilter, FilterOperatorError, isDrillEnabled, resolveDrillTitle, resolveFilterPlaceholders, resolveContextTokens, shiftFilterByCompareTo, compareToTrendLabelKey, chartTypeIgnoresCompareTo, buildChartSeries, buildOptionColorMap, buildCategoryOrder, buildCategoryRank, deriveDimensionLabelMaps, dimensionOptionTranslator, loadDimensionFieldMeta, relabelDimensions, localizeFieldOptions, elementDataSourceBlock, type DimensionFieldMeta, type CompareToConfig, type DrillEvent, type ChartResultField, type ChartSegmentClickEvent } from '@object-ui/core';
77
import { Sheet, SheetContent, SheetHeader, SheetTitle, Dialog, DialogContent, DialogHeader, DialogTitle, RefreshIndicator, Button, ChartSkeleton, DataEmptyState } from '@object-ui/components';
88
import { AlertCircle, ArrowUpRight, Inbox } from 'lucide-react';
99
import { builtinAggregateLabels, useSafeFieldLabel, useSafeTranslate, useObjectTranslation, pickLocalized } from '@object-ui/i18n';
@@ -168,6 +168,25 @@ function aggregateGroupByKey(
168168
return typeof gb === 'string' ? gb : undefined;
169169
}
170170

171+
/**
172+
* Where a dataset chart's category sits in the order its dimension field
173+
* DECLARES its options (objectui#13403), read off a `buildCategoryRank` map,
174+
* which keys the stored value and the display label alike: a declared option
175+
* at its declared position, then any value the options do not declare, then
176+
* the empty bucket. The caller sorts STABLY on it, so undeclared values keep
177+
* the dataset's order among themselves.
178+
*
179+
* The same reading as `declaredOptionPosition` in the dashboard's
180+
* `DatasetWidget` (objectui#11809), which charts the same dataset rows, so a
181+
* page block and a dashboard widget over one dimension draw one order.
182+
*/
183+
function declaredOptionPosition(value: unknown, rank: ReadonlyMap<string, number>): number {
184+
const declared = value == null ? undefined : rank.get(String(value));
185+
if (declared !== undefined) return declared;
186+
if (value == null || value === '') return Number.MAX_SAFE_INTEGER;
187+
return Number.MAX_SAFE_INTEGER - 1;
188+
}
189+
171190
/**
172191
* Client-side aggregation for fetched records.
173192
* Groups records by `groupBy` field and applies the aggregation function
@@ -704,8 +723,8 @@ export const ObjectChart = (props: ObjectChartProps) => {
704723
// surface, through `fieldOptionLabel` — the resolver list and form surfaces
705724
// already translate select options with
706725
// (`fieldOptions.<object>.<field>.<value>`).
707-
const { fieldOptionColors, dimensionLabels } = useMemo(() => {
708-
if (!optionMeta) return { fieldOptionColors: null, dimensionLabels: null };
726+
const { fieldOptionColors, dimensionLabels, categoryOrder } = useMemo(() => {
727+
if (!optionMeta) return { fieldOptionColors: null, dimensionLabels: null, categoryOrder: null };
709728
const { metaByPath, colorPath, fieldByDim } = optionMeta;
710729
// Colours read `option.label`, so they are fed the LOCALIZED options and
711730
// stay keyed by the string the rendered category actually carries — on the
@@ -730,8 +749,19 @@ export const ObjectChart = (props: ObjectChartProps) => {
730749
fieldByDim ? Object.entries(fieldByDim).map(([dim, path]) => ({ dim, path })) : null,
731750
fieldOptionLabel,
732751
);
733-
return { fieldOptionColors: buildOptionColorMap(colorOptions), dimensionLabels: labels };
734-
}, [optionMeta, fieldOptionLabel]);
752+
// objectui#13403 — the first dimension's DECLARED option order, the reading
753+
// the dashboard's `DatasetWidget` takes for the same dataset (objectui#11809):
754+
// core's `buildCategoryOrder` over the same localized options the colours
755+
// read, so it keys the stored value and the display label alike. Dataset
756+
// path only (`fieldByDim` is null on the aggregate path), and only when the
757+
// chart names a dimension: with none, `colorPath` falls back to the
758+
// dataset's own first dimension, which this chart does not draw. A field
759+
// with no options yields null, so such a chart keeps its answered order.
760+
const order = fieldByDim && Array.isArray(schema.dimensions) && schema.dimensions.length > 0
761+
? buildCategoryOrder(colorOptions)
762+
: null;
763+
return { fieldOptionColors: buildOptionColorMap(colorOptions), dimensionLabels: labels, categoryOrder: order };
764+
}, [optionMeta, fieldOptionLabel, schema.dimensions]);
735765

736766
// Run a single aggregate query (used for both the current and comparison
737767
// windows). Extracted so the two queries share identical logic.
@@ -1273,9 +1303,28 @@ export const ObjectChart = (props: ObjectChartProps) => {
12731303
// text from the locale bundle here instead of the server's English `label`;
12741304
// an author-declared measure carries no discriminator and keeps its label
12751305
// verbatim (objectui#4106).
1306+
//
1307+
// objectui#13403 — the rows are charted in the first dimension's DECLARED
1308+
// option order, as the dashboard's `DatasetWidget` charts them
1309+
// (objectui#11809). The dataset answers its buckets in GROUP BY order, the
1310+
// stored values' alphabetical order, so a priority axis read High, Low,
1311+
// Medium, Urgent on a page block and Low, Medium, High, Urgent on a
1312+
// dashboard. `categoryOrder` below reaches only the funnel inside the
1313+
// renderer; a bar, line or pie draws its rows in the order it is handed
1314+
// them, so the order is applied to the rows here, before they are charted.
1315+
const categoryRank = schema.dataset ? buildCategoryRank(categoryOrder) : null;
1316+
const datasetRows = schema.dataset ? relabelDimensions(finalData, dimensionLabels) : finalData;
1317+
const firstDimension = Array.isArray(schema.dimensions) ? schema.dimensions[0] : undefined;
1318+
const plotRows = categoryRank && firstDimension
1319+
? [...datasetRows].sort(
1320+
(a, b) =>
1321+
declaredOptionPosition(a?.[firstDimension], categoryRank) -
1322+
declaredOptionPosition(b?.[firstDimension], categoryRank),
1323+
)
1324+
: datasetRows;
12761325
const datasetChart = schema.dataset
12771326
? buildChartSeries(
1278-
relabelDimensions(finalData, dimensionLabels),
1327+
plotRows,
12791328
schema.dimensions,
12801329
schema.values,
12811330
datasetFields,
@@ -1369,6 +1418,10 @@ export const ObjectChart = (props: ObjectChartProps) => {
13691418
...finalSchema,
13701419
colors: paletteColors,
13711420
...(mergedCategoryColors ? { categoryColors: mergedCategoryColors } : {}),
1421+
// objectui#13403 — the declared order, for the funnel the renderer orders
1422+
// itself (the dashboard hands it the same key). Absent for a dimension
1423+
// whose field declares no options, so that chart is untouched.
1424+
...(datasetChart && categoryOrder ? { categoryOrder } : {}),
13721425
};
13731426

13741427
/**

0 commit comments

Comments
 (0)