Skip to content

Commit 7a6dc7a

Browse files
committed
test(ui): pin percentDisplay on the percent cell and every relay site
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibvqwtTGSkCm75Nci1s
1 parent 7b7880e commit 7a6dc7a

4 files changed

Lines changed: 399 additions & 0 deletions

File tree

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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#28255: the percent cell reads the field's `percentDisplay`
11+
* (`FieldSchema.percentDisplay` in `@objectstack/spec`).
12+
*
13+
* `plain` is a rate or a probability rather than progress, so the cell prints
14+
* the percentage alone, with no `progressbar`. Absent or `bar` keeps the bar
15+
* beside the number. Every read-only host (grid cell, detail field, header
16+
* chip) draws this one renderer; the relay sites that carry the key to it are
17+
* pinned in their own packages.
18+
*
19+
* ── Directions with the read removed (the ablation this file exists for) ──
20+
* `plain`: no progressbar RED (the bar is drawn)
21+
* `plain`: the number is the text GREEN (the bar's text is the same number)
22+
* `bar` / absent: a progressbar GREEN (the default face either way)
23+
*/
24+
25+
import React from 'react';
26+
import { describe, it, expect, afterEach } from 'vitest';
27+
import { render, screen, cleanup } from '@testing-library/react';
28+
import '@testing-library/jest-dom';
29+
import { PercentCellRenderer } from '../index';
30+
31+
afterEach(cleanup);
32+
33+
function renderCell(value: unknown, field: Record<string, unknown>) {
34+
return render(<PercentCellRenderer value={value as any} field={{ type: 'percent', name: 'probability', ...field } as any} />);
35+
}
36+
37+
describe('PercentCellRenderer reads percentDisplay (objectstack#28255)', () => {
38+
it('`plain` prints the percentage alone, with no progress bar', () => {
39+
const { container } = renderCell(0.25, { percentDisplay: 'plain' });
40+
expect(screen.queryByRole('progressbar')).toBeNull();
41+
expect(container.textContent).toBe('25%');
42+
});
43+
44+
it('`plain` keeps the declared width and storage: a whole-stored value at scale 1', () => {
45+
const { container } = renderCell(33.3, { percentDisplay: 'plain', max: 100, scale: 1 });
46+
expect(screen.queryByRole('progressbar')).toBeNull();
47+
expect(container.textContent).toBe('33.3%');
48+
});
49+
50+
it('`bar` pins the progress bar', () => {
51+
renderCell(0.25, { percentDisplay: 'bar' });
52+
expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '25');
53+
});
54+
55+
it('CONTROL: an absent key keeps the renderer default, the bar', () => {
56+
const { container } = renderCell(0.25, {});
57+
expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '25');
58+
expect(container.textContent).toBe('25%');
59+
});
60+
61+
it('a blank value is still the empty face under `plain`', () => {
62+
const { container } = renderCell(null, { percentDisplay: 'plain' });
63+
expect(screen.queryByRole('progressbar')).toBeNull();
64+
expect(container.textContent).not.toContain('%');
65+
});
66+
});
Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
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#28255: a percent field's authored `percentDisplay` reaches the
11+
* DETAIL cells, through each place this package hand-copies field metadata
12+
* beside `useGrouping`:
13+
*
14+
* - `ENRICHED_FIELD_METADATA_KEYS` (`enrichDetailField`), which `DetailSection`
15+
* and `HeaderHighlight` share;
16+
* - `buildRecordDetailFields` (`RecordDetailPanel`), rendered with NO data
17+
* source, so the panel's own copy is the only road;
18+
* - `RelatedList`'s cell bag.
19+
*
20+
* `PercentCellRenderer` reads the key; a site that drops it hands the cell a
21+
* field without it, and a `plain` probability draws its bar again. Each case
22+
* has a same-shape control field with no key, which must keep its bar.
23+
*
24+
* The viewport is pinned to desktop: `RelatedList` swaps its table for a
25+
* gallery under `useIsMobile()` (objectui#8399).
26+
*/
27+
28+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
29+
import { render, cleanup, waitFor } from '@testing-library/react';
30+
import '@testing-library/jest-dom';
31+
import * as React from 'react';
32+
33+
import '@object-ui/components';
34+
import type { DetailViewSection, HighlightField } from '@object-ui/types';
35+
import { DetailSection } from '../DetailSection';
36+
import { HeaderHighlight } from '../HeaderHighlight';
37+
import { RecordDetailPanel } from '../RecordDetailPanel';
38+
import { RelatedList } from '../RelatedList';
39+
40+
// `RecordDetailPanel` mounts `DetailView`, whose `useRecordEditable` probes
41+
// `POST /api/v1/security/explain`; one double at module scope (objectui#7439).
42+
vi.stubGlobal(
43+
'fetch',
44+
vi.fn(async () => ({ ok: true, json: async () => ({ record: { visible: true } }) })),
45+
);
46+
47+
beforeEach(() => {
48+
Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1280 });
49+
});
50+
afterEach(cleanup);
51+
52+
const FIELDS = {
53+
// A probability, not progress: the author asks for the plain face.
54+
probability: { type: 'percent', label: 'Probability', percentDisplay: 'plain' },
55+
// The control: no key, so the bar stays.
56+
completion: { type: 'percent', label: 'Completion' },
57+
};
58+
59+
const RECORD = { id: 'r1', probability: 0.25, completion: 0.6 };
60+
61+
/** Exactly one bar on the surface, and it is the control's 60. */
62+
function expectDeclaredFaces(container: HTMLElement) {
63+
const text = container.textContent ?? '';
64+
expect(text, 'the plain value is drawn').toContain('25%');
65+
expect(text, 'CONTROL: the barred value is drawn').toContain('60%');
66+
const bars = Array.from(container.querySelectorAll('[role="progressbar"]'));
67+
expect(bars.map((b) => b.getAttribute('aria-valuenow')), '`plain` draws no bar; the control keeps its bar').toEqual(['60']);
68+
}
69+
70+
describe('the authored percentDisplay reaches the detail cells (objectstack#28255)', () => {
71+
it('DetailSection: through the enrichment key list, from the object schema', () => {
72+
const section = {
73+
title: 'S',
74+
fields: [{ name: 'probability' }, { name: 'completion' }],
75+
} as unknown as DetailViewSection;
76+
const { container } = render(
77+
<DetailSection section={section} data={RECORD} objectSchema={{ fields: FIELDS }} />,
78+
);
79+
expectDeclaredFaces(container);
80+
});
81+
82+
it('HeaderHighlight: the header chips share the enrichment key list', () => {
83+
const fields: HighlightField[] = [
84+
{ name: 'probability', label: 'Probability' },
85+
{ name: 'completion', label: 'Completion' },
86+
];
87+
const { container } = render(
88+
<HeaderHighlight fields={fields} data={RECORD} objectSchema={{ fields: FIELDS }} />,
89+
);
90+
expectDeclaredFaces(container);
91+
});
92+
93+
it('RecordDetailPanel: through the panel\'s own field build', async () => {
94+
const { container } = render(
95+
<RecordDetailPanel
96+
record={RECORD}
97+
objectName="deal"
98+
recordId="r1"
99+
objectSchema={{ fields: FIELDS }}
100+
/>,
101+
);
102+
await waitFor(() => expect(container.textContent).toContain('60%'));
103+
expectDeclaredFaces(container);
104+
});
105+
106+
it('RelatedList: through the related table\'s cell bag', async () => {
107+
const dataSource = {
108+
getObjectSchema: vi.fn(async () => ({ name: 'deal', fields: { name: { type: 'text', label: 'Name' }, ...FIELDS } })),
109+
find: vi.fn(async () => ({ data: [{ ...RECORD, name: 'Tower' }], total: 1 })),
110+
};
111+
const { container } = render(
112+
<RelatedList
113+
title="Deals"
114+
type="table"
115+
api="deal"
116+
objectName="deal"
117+
referenceField="parent"
118+
parentId="P-1"
119+
dataSource={dataSource as any}
120+
/>,
121+
);
122+
await waitFor(() => expect(container.querySelector('table')).not.toBeNull());
123+
await waitFor(() => expect(container.textContent).toContain('Tower'));
124+
expectDeclaredFaces(container.querySelector('tbody') as HTMLElement);
125+
});
126+
});
Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
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#28255: a percent field's authored `percentDisplay` reaches the
11+
* grid cell on every configured-column path.
12+
*
13+
* `PercentCellRenderer` reads `field.percentDisplay`, but the three
14+
* configured-column paths (ListColumn objects, a string array, inline rows
15+
* with a `fields` projection) each build a `fieldMeta` bag key by key, the
16+
* way `useGrouping` rides (objectui#11026). So each path is driven here.
17+
*
18+
* ── Directions with the cell's read in place and the grid's relay removed ──
19+
* `plain` probability, each configured path RED (two bars per row)
20+
* the control field (no key) GREEN (one bar either way)
21+
* auto-generated columns (whole def, no bag) GREEN (the reference face)
22+
*/
23+
24+
import React from 'react';
25+
import { describe, it, expect, beforeAll, afterEach, vi } from 'vitest';
26+
import { render, screen, waitFor, cleanup } from '@testing-library/react';
27+
import '@testing-library/jest-dom';
28+
import { I18nProvider, LocalizationProvider } from '@object-ui/i18n';
29+
import { registerAllFields } from '@object-ui/fields';
30+
import { ActionProvider, SchemaRendererProvider } from '@object-ui/react';
31+
import { ObjectGrid } from '../ObjectGrid';
32+
33+
registerAllFields();
34+
35+
beforeAll(() => {
36+
if (!Element.prototype.scrollIntoView) {
37+
Element.prototype.scrollIntoView = vi.fn() as unknown as Element['scrollIntoView'];
38+
}
39+
});
40+
41+
afterEach(cleanup);
42+
43+
const OBJECT = 'os_28255_deal';
44+
45+
const FIELDS: Record<string, Record<string, unknown>> = {
46+
id: { type: 'text' },
47+
name: { type: 'text', label: 'Deal Name' },
48+
// A probability, not progress: the author asks for the plain face.
49+
probability: { type: 'percent', label: 'Win Chance', percentDisplay: 'plain' },
50+
// The control: no key, so the bar stays.
51+
completion: { type: 'percent', label: 'Completion' },
52+
};
53+
54+
const ROW = { id: 'd1', name: 'Tower', probability: 0.25, completion: 0.6 };
55+
const PERCENT_FIELDS = ['probability', 'completion'] as const;
56+
57+
function Providers({ children }: { children: React.ReactNode }) {
58+
return (
59+
<I18nProvider config={{ defaultLanguage: 'en', detectBrowserLanguage: false }} persistLanguage={false}>
60+
<LocalizationProvider value={{ locale: 'en-US' }}>{children}</LocalizationProvider>
61+
</I18nProvider>
62+
);
63+
}
64+
65+
function makeDataSource() {
66+
return {
67+
find: vi.fn(async () => ({ data: [ROW], total: 1, hasMore: false, pageSize: 50 })),
68+
getObjectSchema: async (name: string) => ({ name, fields: structuredClone(FIELDS) }),
69+
} as never;
70+
}
71+
72+
/**
73+
* Render the grid and wait for the ENRICHED columns: until the object schema
74+
* arrives a column with no type is drawn withheld (masked). The def's label,
75+
* which differs from the humanized field name, arrives in the same pass.
76+
*/
77+
async function renderGrid(schemaExtra: Record<string, unknown>) {
78+
const ds = makeDataSource();
79+
const utils = render(
80+
<Providers>
81+
<ActionProvider>
82+
<SchemaRendererProvider dataSource={ds}>
83+
<ObjectGrid
84+
schema={{
85+
type: 'object-grid',
86+
objectName: OBJECT,
87+
data: { provider: 'value', items: [ROW] },
88+
pagination: { pageSize: 50 },
89+
...schemaExtra,
90+
} as never}
91+
dataSource={ds}
92+
/>
93+
</SchemaRendererProvider>
94+
</ActionProvider>
95+
</Providers>,
96+
);
97+
await waitFor(() => expect(screen.getAllByText('Win Chance').length).toBeGreaterThan(0));
98+
return utils;
99+
}
100+
101+
/** Each body cell's text and whether it draws a progress bar. */
102+
function cells(container: HTMLElement): Array<{ text: string; bar: boolean }> {
103+
return Array.from(container.querySelectorAll('tbody td')).map((td) => ({
104+
text: (td.textContent ?? '').trim(),
105+
bar: td.querySelector('[role="progressbar"]') !== null,
106+
}));
107+
}
108+
109+
function expectDeclaredFaces(container: HTMLElement) {
110+
const all = cells(container);
111+
const probability = all.find((c) => c.text === '25%');
112+
const completion = all.find((c) => c.text === '60%');
113+
expect(probability, `cells: ${JSON.stringify(all)}`).toBeDefined();
114+
expect(completion, `cells: ${JSON.stringify(all)}`).toBeDefined();
115+
expect(probability!.bar, '`plain` draws no bar').toBe(false);
116+
expect(completion!.bar, 'CONTROL: no key keeps the bar').toBe(true);
117+
}
118+
119+
/** The three configured-column paths that build a `fieldMeta` bag. */
120+
const PATHS: Array<[string, Record<string, unknown>]> = [
121+
['ListColumn objects', { columns: [{ field: 'name' }, ...PERCENT_FIELDS.map((field) => ({ field }))] }],
122+
['string columns', { columns: ['name', ...PERCENT_FIELDS] }],
123+
['inline rows + fields projection', { fields: ['name', ...PERCENT_FIELDS] }],
124+
];
125+
126+
describe('a percent field\'s authored percentDisplay reaches the grid cell (objectstack#28255)', () => {
127+
it.each(PATHS)('%s: `plain` prints the percentage with no bar', async (_path, schemaExtra) => {
128+
const { container } = await renderGrid(schemaExtra);
129+
expectDeclaredFaces(container);
130+
});
131+
132+
it('auto-generated columns (the whole def, no bag): the reference face', async () => {
133+
const { container } = await renderGrid({});
134+
expectDeclaredFaces(container);
135+
});
136+
});

0 commit comments

Comments
 (0)