Skip to content

Commit 66b10ee

Browse files
committed
fix(app-shell): hold a new field validation rule until it has a field and a message
A new state_machine / format / json_schema rule was written to the object draft at once, on the object's first listed field and with no message. It now waits in the Validations panel, the hold guarded rules already take, with no field picked for the author. "Add transition" keeps its blank row local until it has a from-state instead of writing the key "". A conditional rule's `when` gets its own caption (en, zh) instead of the script rule's fail-condition one. Claude-Session: https://claude.ai/code/session_01JQwxbaA4X9WGDi4ZgwZ4PZ Co-authored-by: Claude <noreply@anthropic.com>
1 parent f79ec28 commit 66b10ee

7 files changed

Lines changed: 481 additions & 91 deletions

‎ui/packages/app-shell/src/views/metadata-admin/i18n.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2063,6 +2063,8 @@ const ENGINE_STRINGS_EN: Record<string, string> = {
20632063
'engine.studio.held.needsInput': '{input} on the step “{step}” needs a value',
20642064
'engine.studio.held.needsCondition': 'the rule “{rule}” needs a condition',
20652065
'engine.studio.held.needsThenCondition': 'the “Then” rule of “{rule}” needs a condition',
2066+
'engine.studio.held.needsRuleField': 'the rule “{rule}” needs a field',
2067+
'engine.studio.held.needsRuleMessage': 'the rule “{rule}” needs an error message',
20662068
// objectui#11910 — a dashboard widget held until it is bound; `input` is the
20672069
// widget inspector's own label for it (Dataset, Values (measures)).
20682070
'engine.studio.held.widgetNeedsInput': '{input} on the widget “{widget}” needs a value',
@@ -2305,6 +2307,8 @@ const ENGINE_STRINGS_EN: Record<string, string> = {
23052307
'engine.studio.rules.newButton': 'New validation rule',
23062308
'engine.studio.rules.noMessage': '(no message)',
23072309
'engine.studio.rules.notSaved': 'Not saved — needs a condition',
2310+
'engine.studio.rules.notSavedField': 'Not saved — needs a field',
2311+
'engine.studio.rules.notSavedMessage': 'Not saved — needs a message',
23082312
'engine.studio.rules.structured': '“{type}” rules carry structured configuration (state-machine transitions / format constraints etc.) and cannot be edited here yet — maintain them in the code package. Message: {message}',
23092313
'engine.studio.rules.none2': '(none)',
23102314
'engine.studio.rules.deleteRule': 'Delete rule',
@@ -2314,6 +2318,9 @@ const ENGINE_STRINGS_EN: Record<string, string> = {
23142318
'engine.studio.rules.celPre': 'Fail condition (CEL) — when the condition is ',
23152319
'engine.studio.rules.celTrue': 'true',
23162320
'engine.studio.rules.celMid': ', the save is rejected with the message above.',
2321+
// A conditional rule's `when`: it says when the `then` rule applies.
2322+
'engine.studio.rules.whenPre': 'Guard (CEL) — when the condition is ',
2323+
'engine.studio.rules.whenMid': ', the “Then” rule below applies; otherwise the “Otherwise” rule, if one is set.',
23172324
'engine.studio.rules.severity': 'Severity',
23182325
'engine.studio.rules.severityError': 'error (rejects the save)',
23192326
'engine.studio.rules.enabled': 'Enabled',
@@ -4685,6 +4692,8 @@ const ENGINE_STRINGS_ZH: Record<string, string> = {
46854692
'engine.studio.held.needsInput': '步骤「{step}」的「{input}」需要填写',
46864693
'engine.studio.held.needsCondition': '规则「{rule}」需要一个条件',
46874694
'engine.studio.held.needsThenCondition': '规则「{rule}」的「Then」规则需要一个条件',
4695+
'engine.studio.held.needsRuleField': '规则「{rule}」需要选择一个字段',
4696+
'engine.studio.held.needsRuleMessage': '规则「{rule}」需要一条错误消息',
46884697
'engine.studio.held.widgetNeedsInput': '组件「{widget}」的「{input}」需要填写',
46894698
'engine.studio.held.line': '尚未保存:{clause}。更改已保留在此处,补全后会自动保存。',
46904699
'engine.studio.held.publish': '未发布:{clause},该更改尚未保存。请先补全,再发布。',
@@ -4906,6 +4915,8 @@ const ENGINE_STRINGS_ZH: Record<string, string> = {
49064915
'engine.studio.rules.newButton': '新建验证规则',
49074916
'engine.studio.rules.noMessage': '(无消息)',
49084917
'engine.studio.rules.notSaved': '未保存 —— 需要条件',
4918+
'engine.studio.rules.notSavedField': '未保存 —— 需要字段',
4919+
'engine.studio.rules.notSavedMessage': '未保存 —— 需要消息',
49094920
'engine.studio.rules.structured': '「{type}」类型的规则带有结构化配置(状态机转移表 / 格式约束等),暂不支持在此编辑 —— 请在代码包中维护。消息:{message}',
49104921
'engine.studio.rules.none2': '(无)',
49114922
'engine.studio.rules.deleteRule': '删除规则',
@@ -4915,6 +4926,8 @@ const ENGINE_STRINGS_ZH: Record<string, string> = {
49154926
'engine.studio.rules.celPre': '失败条件(CEL)—— 条件为 ',
49164927
'engine.studio.rules.celTrue': '真',
49174928
'engine.studio.rules.celMid': ' 时,拒绝保存并显示上面的消息。',
4929+
'engine.studio.rules.whenPre': '前提条件(CEL)—— 条件为 ',
4930+
'engine.studio.rules.whenMid': ' 时,应用下面的「Then」规则;否则应用「Otherwise」规则(如已设置)。',
49184931
'engine.studio.rules.severity': '严重度',
49194932
'engine.studio.rules.severityError': 'error(拒绝保存)',
49204933
'engine.studio.rules.enabled': '启用',
Lines changed: 267 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,267 @@
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#26731 — a new field rule is held until it is complete, an empty
11+
* transition row is never stored, and a conditional's `when` is captioned as
12+
* what it is.
13+
*
14+
* Choosing State machine, Format or JSON schema in the New menu used to write
15+
* the rule to the object draft at once, on the object's first listed field
16+
* (`created_at` on a served object) and with no message, and the Data pillar's
17+
* autosave stored it. Now the new rule waits in the panel, as a guarded one
18+
* waits for its condition (objectui#11820): no field is picked for the author,
19+
* and the rule is written once, when it has a field and an error message.
20+
*
21+
* "Add transition" used to write the key `""` straight into the rule; the
22+
* blank row now stays in the editor until it has a from-state.
23+
*
24+
* The `conditional` rule's `when` input carried the script rule's caption
25+
* ("Fail condition … the save is rejected"), the opposite of what `when` does:
26+
* it says when the `then` rule applies.
27+
*
28+
* The harness feeds every `onPatch` back into `draft`, as the Data pillar does.
29+
*/
30+
31+
import '@testing-library/jest-dom/vitest';
32+
import * as React from 'react';
33+
import { describe, it, expect, vi, afterEach } from 'vitest';
34+
import { render, screen, fireEvent, cleanup, within } from '@testing-library/react';
35+
import { I18nProvider, createI18n } from '@object-ui/i18n';
36+
import { ObjectSchema } from '@objectstack/spec/data';
37+
38+
import { ObjectValidationsPanel } from './ObjectValidationsPanel';
39+
import { t } from '../metadata-admin/i18n';
40+
41+
afterEach(() => cleanup());
42+
43+
// The served object's audit column first, as the card measured it: the field a
44+
// new rule must not be seeded with.
45+
const baseDraft: Record<string, unknown> = {
46+
name: 'invoice',
47+
label: 'Invoice',
48+
fields: {
49+
created_at: { type: 'datetime', label: 'Created At', system: true },
50+
status: { type: 'select', label: 'Status' },
51+
payload: { type: 'json', label: 'Payload' },
52+
},
53+
validations: [
54+
{ type: 'script', name: 'no_negative', message: 'no', condition: 'record.amount < 0', severity: 'error' },
55+
],
56+
};
57+
58+
const MESSAGE_BOX = 'e.g. Completion date is required when status is Done';
59+
60+
function Harness({ onPatch, initial = baseDraft }: { onPatch: (p: Record<string, unknown>) => void; initial?: Record<string, unknown> }) {
61+
const [draft, setDraft] = React.useState(initial);
62+
return (
63+
<ObjectValidationsPanel
64+
draft={draft}
65+
onPatch={(p) => {
66+
onPatch(p);
67+
setDraft((d) => ({ ...d, ...p }));
68+
}}
69+
/>
70+
);
71+
}
72+
73+
function addFromMenu(label: string) {
74+
fireEvent.click(screen.getByText('New'));
75+
fireEvent.click(screen.getByRole('button', { name: 'Advanced' }));
76+
fireEvent.click(screen.getByRole('button', { name: label }));
77+
}
78+
79+
/** Pick `label` in the open rule's field picker, the shared `Select` (objectui#11865). */
80+
async function pickField(label: string): Promise<void> {
81+
fireEvent.keyDown(screen.getByTestId('rule-field'), { key: 'ArrowDown' });
82+
fireEvent.click(within(await screen.findByRole('listbox')).getByRole('option', { name: label }));
83+
}
84+
85+
function lastValidations(onPatch: ReturnType<typeof vi.fn>): Array<Record<string, unknown>> {
86+
const calls = onPatch.mock.calls;
87+
return calls[calls.length - 1][0].validations as Array<Record<string, unknown>>;
88+
}
89+
90+
const FIELD_TYPES: ReadonlyArray<[type: string, menu: string, field: string]> = [
91+
['state_machine', 'State machine — allowed transitions', 'Status (status)'],
92+
['format', 'Format — regex / built-in format', 'Status (status)'],
93+
['json_schema', 'JSON schema — validate a JSON field', 'Payload (payload)'],
94+
];
95+
96+
describe('a new field rule waits for its field and message (objectstack#26731)', () => {
97+
it.each(FIELD_TYPES)('a new %s rule is held with no field until it has a field and a message, then written once', async (type, menu, fieldLabel) => {
98+
const onPatch = vi.fn();
99+
render(<Harness onPatch={onPatch} />);
100+
addFromMenu(menu);
101+
102+
// Held: listed, open, marked, and no field picked for the author.
103+
expect(onPatch).not.toHaveBeenCalled();
104+
expect(screen.getByText('validation_2')).toBeInTheDocument();
105+
expect(screen.getByTestId('rule-unsaved')).toHaveTextContent('Not saved — needs a field');
106+
expect(screen.getByTestId('rule-held')).toHaveTextContent(
107+
'Not saved yet: the rule “validation_2” needs a field. Your changes are kept here and saved once it is filled in.',
108+
);
109+
expect(screen.getByTestId('rule-field')).toHaveTextContent('— pick a field —');
110+
expect(screen.getByTestId('rule-held-hint')).toBeInTheDocument();
111+
112+
await pickField(fieldLabel);
113+
// A field alone is not enough: the rule still has nothing to tell the user.
114+
expect(onPatch).not.toHaveBeenCalled();
115+
expect(screen.getByTestId('rule-unsaved')).toHaveTextContent('Not saved — needs a message');
116+
expect(screen.getByTestId('rule-held')).toHaveTextContent('the rule “validation_2” needs an error message');
117+
expect(screen.getAllByTestId('rule-held-hint')).toHaveLength(1);
118+
119+
fireEvent.change(screen.getByPlaceholderText(MESSAGE_BOX), { target: { value: 'Bad value' } });
120+
expect(onPatch).toHaveBeenCalledTimes(1);
121+
const written = lastValidations(onPatch);
122+
expect(written).toHaveLength(2);
123+
expect(written[0]).toEqual((baseDraft.validations as unknown[])[0]);
124+
const fieldName = /\((\w+)\)$/.exec(fieldLabel)![1];
125+
expect(written[1]).toMatchObject({
126+
type,
127+
name: 'validation_2',
128+
field: fieldName,
129+
message: 'Bad value',
130+
events: ['insert', 'update'],
131+
});
132+
expect(written[1].field).not.toBe('created_at');
133+
expect(ObjectSchema.safeParse({ ...baseDraft, validations: written }).success).toBe(true);
134+
135+
// Written, it is an ordinary rule.
136+
expect(screen.queryByTestId('rule-unsaved')).toBeNull();
137+
expect(screen.queryByTestId('rule-held')).toBeNull();
138+
expect(screen.queryByTestId('rule-held-hint')).toBeNull();
139+
});
140+
141+
it('a message typed first waits for the field, and the field writes it', async () => {
142+
const onPatch = vi.fn();
143+
render(<Harness onPatch={onPatch} />);
144+
addFromMenu('Format — regex / built-in format');
145+
fireEvent.change(screen.getByPlaceholderText(MESSAGE_BOX), { target: { value: 'Bad code' } });
146+
expect(onPatch).not.toHaveBeenCalled();
147+
expect(screen.getByTestId('rule-held')).toHaveTextContent('needs a field');
148+
149+
await pickField('Status (status)');
150+
expect(onPatch).toHaveBeenCalledTimes(1);
151+
expect(lastValidations(onPatch)[1]).toMatchObject({ type: 'format', field: 'status', message: 'Bad code' });
152+
});
153+
154+
it('a blank message does not complete the rule', async () => {
155+
const onPatch = vi.fn();
156+
render(<Harness onPatch={onPatch} />);
157+
addFromMenu('JSON schema — validate a JSON field');
158+
await pickField('Payload (payload)');
159+
fireEvent.change(screen.getByPlaceholderText(MESSAGE_BOX), { target: { value: ' ' } });
160+
expect(onPatch).not.toHaveBeenCalled();
161+
expect(screen.getByTestId('rule-held')).toHaveTextContent('needs an error message');
162+
});
163+
164+
it('control — an existing rule switched to a field type keeps the valid first-field skeleton', async () => {
165+
const onPatch = vi.fn();
166+
render(<Harness onPatch={onPatch} />);
167+
fireEvent.keyDown(screen.getByTestId('rule-type'), { key: 'ArrowDown' });
168+
fireEvent.click(
169+
within(await screen.findByRole('listbox')).getByRole('option', { name: 'Format — regex / built-in format' }),
170+
);
171+
expect(onPatch).toHaveBeenCalledTimes(1);
172+
expect(lastValidations(onPatch)[0]).toMatchObject({ type: 'format', name: 'no_negative', field: 'created_at' });
173+
expect(screen.queryByTestId('rule-unsaved')).toBeNull();
174+
});
175+
});
176+
177+
describe('an empty transition row is not stored (objectstack#26731)', () => {
178+
const machine = {
179+
...baseDraft,
180+
validations: [
181+
{ type: 'state_machine', name: 'status_flow', message: 'Bad move', field: 'status', transitions: { open: ['closed'] } },
182+
],
183+
};
184+
185+
it('“Add transition” shows a blank row and writes nothing until it has a from-state', () => {
186+
const onPatch = vi.fn();
187+
render(<Harness onPatch={onPatch} initial={machine} />);
188+
fireEvent.click(screen.getByRole('button', { name: 'Add transition' }));
189+
expect(onPatch).not.toHaveBeenCalled();
190+
const froms = screen.getAllByPlaceholderText(t('engine.studio.rules.transitionFrom', 'en-US'));
191+
expect(froms).toHaveLength(2);
192+
expect(froms[1]).toHaveValue('');
193+
194+
// Next states typed first stay in the row, unsent.
195+
const tos = screen.getAllByPlaceholderText(t('engine.studio.rules.transitionTo', 'en-US'));
196+
fireEvent.change(tos[1], { target: { value: 'open' } });
197+
expect(onPatch).not.toHaveBeenCalled();
198+
199+
fireEvent.change(froms[1], { target: { value: 'closed' } });
200+
expect(onPatch).toHaveBeenCalledTimes(1);
201+
const written = lastValidations(onPatch)[0];
202+
expect(written.transitions).toEqual({ open: ['closed'], closed: ['open'] });
203+
expect(written.transitions).not.toHaveProperty('');
204+
// The row it became is the one the author is typing in.
205+
expect(screen.getAllByPlaceholderText(t('engine.studio.rules.transitionFrom', 'en-US'))[1]).toHaveValue('closed');
206+
});
207+
208+
it('deleting the blank row writes nothing', () => {
209+
const onPatch = vi.fn();
210+
render(<Harness onPatch={onPatch} initial={machine} />);
211+
fireEvent.click(screen.getByRole('button', { name: 'Add transition' }));
212+
const deletes = screen.getAllByRole('button', { name: 'Delete' });
213+
// The row's own delete, not the rule's.
214+
fireEvent.click(deletes.filter((b) => b.getAttribute('data-testid') !== 'rule-delete')[1]);
215+
expect(onPatch).not.toHaveBeenCalled();
216+
expect(screen.getAllByPlaceholderText(t('engine.studio.rules.transitionFrom', 'en-US'))).toHaveLength(1);
217+
});
218+
});
219+
220+
describe('the conditional rule’s `when` has its own caption (objectstack#26731)', () => {
221+
const both = {
222+
...baseDraft,
223+
validations: [
224+
{ type: 'script', name: 'no_negative', message: 'no', condition: 'record.amount < 0', severity: 'error' },
225+
{
226+
type: 'conditional',
227+
name: 'enterprise_only',
228+
message: 'x',
229+
when: "record.status == 'open'",
230+
then: { type: 'script', name: 'enterprise_only_then', message: 'y', condition: 'record.amount > 1' },
231+
},
232+
],
233+
};
234+
235+
function captionOf(ruleName: string, lang: 'en' | 'zh'): string {
236+
const panel = <ObjectValidationsPanel draft={both} onPatch={() => {}} />;
237+
if (lang === 'en') render(panel);
238+
else {
239+
const zh = createI18n({ defaultLanguage: 'zh', detectBrowserLanguage: false, resources: { zh: {} } });
240+
render(<I18nProvider instance={zh}>{panel}</I18nProvider>);
241+
}
242+
fireEvent.click(screen.getByText(ruleName));
243+
const group = screen.getAllByRole('group').find((g) => g.hasAttribute('aria-labelledby') && g.tabIndex === -1)!;
244+
const text = document.getElementById(group.getAttribute('aria-labelledby')!)!.textContent ?? '';
245+
cleanup();
246+
return text;
247+
}
248+
249+
it.each([
250+
['en', 'en-US'],
251+
['zh', 'zh-CN'],
252+
] as const)('in %s the conditional caption is not the script one, and says the Then rule applies', (lang, locale) => {
253+
const script = captionOf('no_negative', lang);
254+
const conditional = captionOf('enterprise_only', lang);
255+
expect(script).toBe(
256+
t('engine.studio.rules.celPre', locale) + t('engine.studio.rules.celTrue', locale) + t('engine.studio.rules.celMid', locale),
257+
);
258+
expect(conditional).toBe(
259+
t('engine.studio.rules.whenPre', locale) + t('engine.studio.rules.celTrue', locale) + t('engine.studio.rules.whenMid', locale),
260+
);
261+
expect(conditional).not.toBe(script);
262+
// Real rows, not the key echoed back.
263+
expect(t('engine.studio.rules.whenPre', locale)).not.toBe('engine.studio.rules.whenPre');
264+
expect(t('engine.studio.rules.whenMid', locale)).not.toBe('engine.studio.rules.whenMid');
265+
expect(conditional).toContain('Then');
266+
});
267+
});

‎ui/packages/app-shell/src/views/studio-design/ObjectValidationsPanel.newRuleWaits-11820.test.tsx‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@
2323
*
2424
* Controls: an existing rule is edited exactly as before (a type switch still
2525
* seeds the valid `'false'` placeholder, since that rule is already in the
26-
* draft), and a type with no guard is written at once.
26+
* draft), and a type with no guard waits for no condition — only for its field
27+
* and message (objectstack#26731, pinned in `newRuleComplete-26731`).
2728
*
2829
* The harness feeds every `onPatch` back into `draft`, as the Data pillar does,
2930
* so what the panel shows after a write is what the pillar would show.
@@ -181,10 +182,18 @@ describe('a new validation rule waits for its condition (objectui#11820)', () =>
181182
expect(screen.queryByText('validation_2')).toBeNull();
182183
});
183184

184-
it('control — a type with no guard is written at once, on Create + Update', () => {
185+
it('control — a type with no guard waits for no condition: its field and message write it, on Create + Update', async () => {
185186
const onPatch = vi.fn();
186187
render(<Harness onPatch={onPatch} />);
187188
addFromMenu('Format — regex / built-in format');
189+
// objectstack#26731 — held until it has a field and a message, never a condition.
190+
expect(onPatch).not.toHaveBeenCalled();
191+
expect(screen.queryByRole('button', { name: /Expression/ })).toBeNull();
192+
fireEvent.keyDown(screen.getByTestId('rule-field'), { key: 'ArrowDown' });
193+
fireEvent.click(within(await screen.findByRole('listbox')).getByRole('option', { name: 'Name (name)' }));
194+
fireEvent.change(screen.getByPlaceholderText('e.g. Completion date is required when status is Done'), {
195+
target: { value: 'Bad name' },
196+
});
188197
expect(onPatch).toHaveBeenCalledTimes(1);
189198
const written = lastValidations(onPatch)[1];
190199
expect(written).toMatchObject({ type: 'format', name: 'validation_2', events: ['insert', 'update'] });

‎ui/packages/app-shell/src/views/studio-design/ObjectValidationsPanel.runsOn-11923.test.tsx‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -218,16 +218,21 @@ describe('the "Runs on" row reads the spec\'s events contract (objectui#11923)',
218218
});
219219
});
220220

221-
it('a new rule starts on the spec\'s default (objectui#11820)', () => {
221+
it('a new rule starts on the spec\'s default (objectui#11820)', async () => {
222222
const onPatch = vi.fn();
223223
render(<Harness onPatch={onPatch} initial={draftWith(RULE)} />);
224224
fireEvent.click(screen.getByText('New'));
225225
// The per-type list sits under Advanced since objectui#11861; this pin is
226226
// about where a new rule starts, not about the menu's layout.
227227
const advanced = screen.queryByRole('button', { name: 'Advanced' });
228228
if (advanced) fireEvent.click(advanced);
229-
// A type with no guard is written at once.
230229
fireEvent.click(screen.getByRole('button', { name: t('engine.studio.rules.typeFormat', EN) }));
230+
// Written once it has a field and a message (objectstack#26731).
231+
fireEvent.keyDown(screen.getByTestId('rule-field'), { key: 'ArrowDown' });
232+
fireEvent.click(within(await screen.findByRole('listbox')).getByRole('option', { name: 'Name (name)' }));
233+
fireEvent.change(screen.getByPlaceholderText(t('engine.studio.rules.messagePlaceholder', EN)), {
234+
target: { value: 'Bad name' },
235+
});
231236
const rule = lastRule(onPatch);
232237
expect(rule.type).toBe('format');
233238
expect(rule.events).toEqual(SPEC_DEFAULT);

0 commit comments

Comments
 (0)