Skip to content

Commit e07456b

Browse files
committed
feat(ui): hoist stateMachineNextValues into @object-ui/core and narrow the edit form's state-machine select
Claude-Session: https://claude.ai/code/session_015Kzn5VKHAGKe251waHoUqj Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6a6ebff commit e07456b

14 files changed

Lines changed: 543 additions & 53 deletions
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
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+
import { describe, it, expect } from 'vitest';
10+
import { stateMachineNextValues } from '../validators/state-machine-next-values';
11+
import { stateMachineNextValues as fromPackageRoot } from '../../index';
12+
13+
// The showcase task's machine (examples/app-showcase task.object.ts).
14+
const transitions = {
15+
backlog: ['todo'],
16+
todo: ['in_progress', 'backlog'],
17+
in_progress: ['in_review', 'todo'],
18+
in_review: ['done', 'in_progress'],
19+
done: ['in_progress'],
20+
};
21+
22+
const withRule = (rule: Record<string, unknown>) => ({
23+
validations: [{ type: 'state_machine', field: 'status', transitions, ...rule }],
24+
});
25+
26+
const sorted = (s: Set<string> | null) => (s ? [...s].sort() : s);
27+
28+
describe('stateMachineNextValues', () => {
29+
it('is published from the package root', () => {
30+
expect(fromPackageRoot).toBe(stateMachineNextValues);
31+
});
32+
33+
it('offers the persisted value plus its declared next states', () => {
34+
expect(sorted(stateMachineNextValues(withRule({}), 'status', 'backlog'))).toEqual([
35+
'backlog',
36+
'todo',
37+
]);
38+
});
39+
40+
it('narrows on an explicit error-severity, active, update-event rule', () => {
41+
const rule = withRule({ severity: 'error', active: true, events: ['update'] });
42+
expect(sorted(stateMachineNextValues(rule, 'status', 'in_review'))).toEqual([
43+
'done',
44+
'in_progress',
45+
'in_review',
46+
]);
47+
});
48+
49+
it('does not narrow on a warning or info machine — the server never blocks it', () => {
50+
expect(stateMachineNextValues(withRule({ severity: 'warning' }), 'status', 'backlog')).toBeNull();
51+
expect(stateMachineNextValues(withRule({ severity: 'info' }), 'status', 'backlog')).toBeNull();
52+
});
53+
54+
it('does not narrow on an inactive rule', () => {
55+
expect(stateMachineNextValues(withRule({ active: false }), 'status', 'backlog')).toBeNull();
56+
});
57+
58+
it('does not narrow on a rule whose events leave out update', () => {
59+
expect(stateMachineNextValues(withRule({ events: ['insert'] }), 'status', 'backlog')).toBeNull();
60+
});
61+
62+
it('reads an empty events list as the spec default, which covers update', () => {
63+
expect(sorted(stateMachineNextValues(withRule({ events: [] }), 'status', 'done'))).toEqual([
64+
'done',
65+
'in_progress',
66+
]);
67+
});
68+
69+
it('leaves an undeclared from-state unconstrained', () => {
70+
expect(stateMachineNextValues(withRule({}), 'status', 'archived')).toBeNull();
71+
});
72+
73+
it('leaves an empty persisted value unconstrained', () => {
74+
expect(stateMachineNextValues(withRule({}), 'status', null)).toBeNull();
75+
expect(stateMachineNextValues(withRule({}), 'status', undefined)).toBeNull();
76+
});
77+
78+
it('intersects several blocking rules on the same field', () => {
79+
const schema = {
80+
validations: [
81+
{ type: 'state_machine', field: 'status', transitions },
82+
{ type: 'state_machine', field: 'status', transitions: { in_review: ['done'] } },
83+
],
84+
};
85+
expect(sorted(stateMachineNextValues(schema, 'status', 'in_review'))).toEqual([
86+
'done',
87+
'in_review',
88+
]);
89+
});
90+
91+
it('ignores a warning rule beside a blocking one', () => {
92+
const schema = {
93+
validations: [
94+
{ type: 'state_machine', field: 'status', transitions },
95+
{
96+
type: 'state_machine',
97+
field: 'status',
98+
severity: 'warning',
99+
transitions: { in_review: [] },
100+
},
101+
],
102+
};
103+
expect(sorted(stateMachineNextValues(schema, 'status', 'in_review'))).toEqual([
104+
'done',
105+
'in_progress',
106+
'in_review',
107+
]);
108+
});
109+
110+
it('ignores rules on other fields and rules of other types', () => {
111+
const schema = {
112+
validations: [
113+
{ type: 'state_machine', field: 'phase', transitions },
114+
{ type: 'script', field: 'status', condition: 'true' },
115+
],
116+
};
117+
expect(stateMachineNextValues(schema, 'status', 'backlog')).toBeNull();
118+
});
119+
});

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,8 @@ export {
2929
type ObjectValidationResult,
3030
type ValidationExpressionEvaluator,
3131
} from './object-validation-engine.js';
32+
33+
// Not part of the deprecated engine: a presentation read of a declared
34+
// `state_machine` transition map, so a choice control offers only the moves
35+
// the server would accept (#25933). It imports nothing from the engine.
36+
export { stateMachineNextValues } from './state-machine-next-values.js';
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
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+
* @object-ui/core - State-machine next values
11+
*
12+
* Which values a `state_machine`-governed field may move to from its persisted
13+
* value, read from the object's served `validations`. A choice control (the
14+
* grid's inline editor, the record form's select, the board's columns) offers
15+
* only these, so it does not stage a move the server is bound to refuse.
16+
*
17+
* This is a PRESENTATION read of the declared transition map, not a client-side
18+
* enforcement path: it never judges a write, and the server's rule validator
19+
* stays the one authority that refuses an invalid transition. The deprecated
20+
* object-level rule engine next door is a different thing and stays unwired
21+
* (#3110); this module neither imports nor mirrors it.
22+
*
23+
* It narrows exactly where the server would refuse, and nowhere else:
24+
*
25+
* - only `severity: 'error'` rules (the spec default) — a `warning` / `info`
26+
* machine never blocks the write, so every option stays offered;
27+
* - only rules that are `active` (default `true`) and whose `events` cover
28+
* `update` (default `['insert', 'update']`) — a move is an update;
29+
* - a from-state the transition map does not declare is unconstrained, as
30+
* the server is lenient there;
31+
* - several applicable rules on one field all have to pass, so their allowed
32+
* sets intersect.
33+
*
34+
* `active`, `events` and `severity` arrive ABSENT from `/meta` when the author
35+
* left them at the spec default, so an absent key reads as the default, never
36+
* as JavaScript falsiness.
37+
*
38+
* @module state-machine-next-values
39+
* @packageDocumentation
40+
*/
41+
42+
/** The spec's `events` default for a validation rule. */
43+
const DEFAULT_EVENTS: readonly string[] = ['insert', 'update'];
44+
45+
/** A `state_machine` rule that refuses an invalid move on update. */
46+
function isBlockingUpdateMachine(
47+
rule: unknown,
48+
fieldName: string,
49+
): rule is { transitions: Record<string, unknown> } {
50+
if (!rule || typeof rule !== 'object') return false;
51+
const r = rule as {
52+
type?: unknown;
53+
field?: unknown;
54+
transitions?: unknown;
55+
active?: unknown;
56+
events?: unknown;
57+
severity?: unknown;
58+
};
59+
if (r.type !== 'state_machine' || r.field !== fieldName) return false;
60+
if (!r.transitions || typeof r.transitions !== 'object') return false;
61+
if (r.active === false) return false;
62+
if ((r.severity ?? 'error') !== 'error') return false;
63+
const events = Array.isArray(r.events) && r.events.length > 0 ? r.events : DEFAULT_EVENTS;
64+
return events.includes('update');
65+
}
66+
67+
/**
68+
* For a field governed by a blocking `state_machine` validation, the set of
69+
* values reachable from `currentValue` — the current value itself plus its
70+
* declared allowed transitions.
71+
*
72+
* `currentValue` is the PERSISTED value (the row as the server last stored
73+
* it), because that is the from-state the server judges a move against — never
74+
* a value the user has staged but not saved.
75+
*
76+
* Returns `null` (= "don't constrain the options") when:
77+
* - the object has no applicable `state_machine` validation for the field
78+
* (none at all, or only warning / inactive / insert-only ones), or
79+
* - the current value is empty, or no applicable rule declares it as a
80+
* from-state.
81+
*/
82+
export function stateMachineNextValues(
83+
objectSchema: unknown,
84+
fieldName: string,
85+
currentValue: unknown,
86+
): Set<string> | null {
87+
const rules = (objectSchema as { validations?: unknown } | null | undefined)?.validations;
88+
if (!Array.isArray(rules)) return null;
89+
if (currentValue === undefined || currentValue === null) return null;
90+
const from = String(currentValue);
91+
92+
let reachable: Set<string> | null = null;
93+
for (const rule of rules) {
94+
if (!isBlockingUpdateMachine(rule, fieldName)) continue;
95+
const allowed = rule.transitions[from];
96+
// An undeclared from-state is not policed by this rule.
97+
if (!Array.isArray(allowed)) continue;
98+
const next = new Set<string>([from, ...allowed.map((s) => String(s))]);
99+
reachable = reachable === null ? next : new Set([...reachable].filter((v) => next.has(v)));
100+
}
101+
return reachable;
102+
}

‎ui/packages/plugin-form/src/DrawerForm.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,7 @@ export const DrawerForm: React.FC<DrawerFormProps> = ({
247247
const uploadGate = useUploadGate();
248248
const previewMode = usePreviewMode();
249249
const [objectSchema, setObjectSchema] = useState<any>(null);
250+
const [formData, setFormData] = useState<Record<string, any>>({});
250251
/**
251252
* The ONE field-gate step every layout draws through (`gateFormFields`,
252253
* objectui#10612): FLS drops non-readable fields and locks non-editable ones,
@@ -262,11 +263,12 @@ export const DrawerForm: React.FC<DrawerFormProps> = ({
262263
objectName: schema.objectName,
263264
mode: schema.mode,
264265
objectSchema,
266+
// The persisted record a `state_machine` select narrows by (#25933).
267+
previousValues: schema.mode === 'edit' && schema.recordId ? formData : undefined,
265268
}) as FormField[],
266-
[perms, schema.objectName, schema.mode, objectSchema],
269+
[perms, schema.objectName, schema.mode, schema.recordId, objectSchema, formData],
267270
);
268271
const [formFields, setFormFields] = useState<FormField[]>([]);
269-
const [formData, setFormData] = useState<Record<string, any>>({});
270272
const [loading, setLoading] = useState(true);
271273
// objectui#10682 — the load error, kept per read (the object schema and the
272274
// record), each written only by the current run of its read and cleared when

‎ui/packages/plugin-form/src/ModalForm.tsx‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,7 @@ export const ModalForm: React.FC<ModalFormProps> = ({
323323
const previewMode = usePreviewMode();
324324
const perms = usePermissions();
325325
const [objectSchema, setObjectSchema] = useState<any>(null);
326+
const [formData, setFormData] = useState<Record<string, any>>({});
326327
// The ONE field-gate step every layout draws through (`gateFormFields`,
327328
// objectui#10612): FLS drops non-readable fields and disables non-editable
328329
// ones (`80c54122e`; fail-open when no PermissionProvider is mounted), and
@@ -336,11 +337,12 @@ export const ModalForm: React.FC<ModalFormProps> = ({
336337
objectName: schema.objectName,
337338
mode: schema.mode,
338339
objectSchema,
340+
// The persisted record a `state_machine` select narrows by (#25933).
341+
previousValues: schema.mode === 'edit' && schema.recordId ? formData : undefined,
339342
}) as FormField[],
340-
[perms, schema.objectName, schema.mode, objectSchema],
343+
[perms, schema.objectName, schema.mode, schema.recordId, objectSchema, formData],
341344
);
342345
const [formFields, setFormFields] = useState<FormField[]>([]);
343-
const [formData, setFormData] = useState<Record<string, any>>({});
344346
const [loading, setLoading] = useState(true);
345347
// objectui#10682 — the load error, kept per read (the object schema and the
346348
// record), each written only by the current run of its read and cleared when

‎ui/packages/plugin-form/src/ObjectForm.tsx‎

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -670,6 +670,16 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource
670670
// `t`, is what its dependency list carries. It changes when the language, or
671671
// that language's late-arriving catalogue, does.
672672
const maxFileSizeSentence = t('form.maxFileSize', { size: '' });
673+
const [initialData, setInitialData] = useState<any>(null);
674+
// The persisted record, for `previous`-scoped field rules and the read-only
675+
// submit strip (objectui#3484). Edit mode only, and WITHOUT the schema
676+
// defaults folded in below: `previous` must be the row as the server last
677+
// stored it, not "the row plus what a blank column would default to". It is
678+
// also the from-state a `state_machine` select narrows by (#25933).
679+
const previousValues =
680+
schema.mode === 'edit' && schema.recordId && initialData && typeof initialData === 'object'
681+
? (initialData as Record<string, any>)
682+
: undefined;
673683
// The ONE field-gate step every layout draws through (objectui#10612):
674684
// field-level security plus the ADR-0092 D4 managed-object lock, which this
675685
// arm's field generator used to stamp on its own — see `gateFormFields`.
@@ -681,8 +691,9 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource
681691
mode: schema.mode,
682692
objectSchema,
683693
deniedDescription,
694+
previousValues,
684695
}) as FormField[],
685-
[perms, schema.objectName, schema.mode, objectSchema, deniedDescription],
696+
[perms, schema.objectName, schema.mode, objectSchema, deniedDescription, previousValues],
686697
);
687698
// objectui#11000 — why `gateFields` locked every field, when the lock is the
688699
// form-wide one: the affordance for the mode is closed. Rendered above the
@@ -701,7 +712,6 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource
701712
/>
702713
);
703714
const [formFields, setFormFields] = useState<FormField[]>([]);
704-
const [initialData, setInitialData] = useState<any>(null);
705715
const [loading, setLoading] = useState(true);
706716
// objectui#10682 — the load error, kept per read (the object schema and the
707717
// record), each written only by the current run of its read and cleared when
@@ -1524,15 +1534,6 @@ const SimpleObjectForm: React.FC<{ schema: LocalizedObjectFormSchema; dataSource
15241534
}, [schema]);
15251535

15261536

1527-
// The persisted record, for `previous`-scoped field rules and the read-only
1528-
// submit strip (objectui#3484). Edit mode only, and WITHOUT the schema
1529-
// defaults folded in above: `previous` must be the row as the server last
1530-
// stored it, not "the row plus what a blank column would default to".
1531-
const previousValues =
1532-
schema.mode === 'edit' && schema.recordId && initialData && typeof initialData === 'object'
1533-
? (initialData as Record<string, any>)
1534-
: undefined;
1535-
15361537
// Auto-layout parity with the flat path (which runs these inside
15371538
// applyAutoLayout): drop platform-managed system fields — and, in create
15381539
// mode, server-computed fields — BEFORE deriving field-group sections, so a

‎ui/packages/plugin-form/src/SplitForm.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -350,9 +350,11 @@ export const SplitForm: React.FC<SplitFormProps> = ({
350350
objectName: schema.objectName,
351351
mode: schema.mode,
352352
objectSchema,
353+
// The persisted record a `state_machine` select narrows by (#25933).
354+
previousValues: schema.mode === 'edit' && schema.recordId ? formData : undefined,
353355
}) ?? fields) as FormField[];
354356
},
355-
[objectSchema, schema.readOnly, schema.mode, schema.recordId, schema.objectName, schema.customFields, fieldLabel, perms],
357+
[objectSchema, schema.readOnly, schema.mode, schema.recordId, schema.objectName, schema.customFields, fieldLabel, perms, formData],
356358
);
357359

358360
// Handle form submission

‎ui/packages/plugin-form/src/TabbedForm.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -448,9 +448,11 @@ export const TabbedForm: React.FC<TabbedFormProps> = ({
448448
objectName: schema.objectName,
449449
mode: schema.mode,
450450
objectSchema,
451+
// The persisted record a `state_machine` select narrows by (#25933).
452+
previousValues: schema.mode === 'edit' && schema.recordId ? formData : undefined,
451453
}) ?? fields) as FormField[];
452454
},
453-
[objectSchema, schema.readOnly, schema.mode, schema.recordId, schema.objectName, schema.customFields, fieldLabel, perms],
455+
[objectSchema, schema.readOnly, schema.mode, schema.recordId, schema.objectName, schema.customFields, fieldLabel, perms, formData],
454456
);
455457

456458
// Handle form submission

‎ui/packages/plugin-form/src/WizardForm.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -724,9 +724,11 @@ export const WizardForm: React.FC<WizardFormProps> = ({
724724
objectName: schema.objectName,
725725
mode: schema.mode,
726726
objectSchema,
727+
// The persisted record a `state_machine` select narrows by (#25933).
728+
previousValues: schema.mode === 'edit' ? persistedRecord : undefined,
727729
}) ?? fields) as FormField[];
728730
},
729-
[objectSchema, schema.readOnly, schema.mode, schema.recordId, schema.objectName, schema.customFields, fieldLabel, perms],
731+
[objectSchema, schema.readOnly, schema.mode, schema.recordId, schema.objectName, schema.customFields, fieldLabel, perms, persistedRecord],
730732
);
731733

732734
// objectui#11000 — the affordance the lock above found CLOSED for this

0 commit comments

Comments
 (0)