diff --git a/.changeset/36167-cel-list-membership.md b/.changeset/36167-cel-list-membership.md new file mode 100644 index 00000000000..401a7e6d7de --- /dev/null +++ b/.changeset/36167-cel-list-membership.md @@ -0,0 +1,16 @@ +--- +'@object-ui/app-shell': patch +'@object-ui/console': patch +'@object-ui/i18n': patch +--- + +fix(studio): the CEL condition builder offers membership, not equals, on a list field + +Clause-②: no +Metadata-protocol: none + +On a field that holds a list (a `multiselect`, `checkboxes` or `tags` field, or a `select` / `lookup` / `user` field declared `multiple: true`), Studio's condition builder (hook, validation-rule, action-visibility, page-block and flow entry conditions) offered equals / not equals and the ordering operators. CEL compares the whole list with one value there, so `record.labels == 'frontend'` was false for every record (and `!=` true for every record), and the author got no signal. + +Such a field is now offered what the list toolbar's filter builder offers it: contains, does not contain, is empty and is not empty. Contains writes `S != null && V in S` and does not contain writes `S == null || !(V in S)`, the same spelling a flow edge's condition rows write; both are null-safe. A row moved onto a list field leaves equals for contains, and a row moved off one leaves membership for equals. A stored condition that compares a list field with `==` / `!=` now opens in the expression editor exactly as stored, never rewritten. A single-value field is offered what it was before. + +New locale key: `engine.inspector.condition.op.notContains` in the studio catalogue (en, zh). No props or exports change. diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ConditionBuilder.listSubject-36167.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ConditionBuilder.listSubject-36167.test.tsx new file mode 100644 index 00000000000..0983c0c3c71 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ConditionBuilder.listSubject-36167.test.tsx @@ -0,0 +1,252 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36167 — `ConditionBuilder` on a LIST subject (a `multiselect` / + * `checkboxes` / `tags`, or a `select` / `lookup` / `user` declared + * `multiple: true`). + * + * Under `@objectstack/formula`'s `celEngine`, `S == V` compares the whole list + * with one value, so it answers a constant. The builder therefore offers a + * list subject what the shared filter builder offers it (membership and the + * empty checks), writes membership in the one spelling the flow edge's rows + * write (`cel-list-membership.ts`), and opens a stored `==` on a list in the + * raw editor unchanged. Every emitted condition is evaluated by the engine + * beside its spelling, and a single-value field keeps `==`. + */ + +// The builder reaches a dynamic `import()` of each module below: its first load +// is paid here, at collection, never inside a case's clocked window +// (`check:test-source-alias`). +import '@objectstack/lint'; +import '@object-ui/core'; +import * as React from 'react'; +import { describe, it, expect, afterEach, beforeAll, vi } from 'vitest'; +import { render, screen, cleanup, fireEvent } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { celEngine } from '@objectstack/formula'; +import { jsonColumnFilterOperators } from '@object-ui/components'; + +// ConditionBuilder calls useObjectFields(objectName) even when `fields` is +// supplied; stub the shared client so the mount-time fetch stays off the network. +const state = vi.hoisted(() => ({ + metadataClient: { + get: vi.fn(async (): Promise => undefined), + list: vi.fn(async () => [] as unknown[]), + withPreviewDrafts() { return this; }, + }, +})); +vi.mock('../useMetadata', () => ({ + useMetadataClient: () => state.metadataClient, +})); + +import { ConditionBuilder } from './ConditionBuilder'; +import { listSubjectOperators } from './cel-list-membership'; +import { rowsToCel } from './flow-edge-condition-rows'; + +afterEach(() => cleanup()); + +beforeAll(() => { + // Radix Select probes pointer-capture APIs the test DOM lacks. + for (const m of ['hasPointerCapture', 'setPointerCapture', 'releasePointerCapture'] as const) { + if (!Element.prototype[m]) { + // @ts-expect-error test shim + Element.prototype[m] = m === 'hasPointerCapture' ? () => false : () => {}; + } + } +}); + +type CatalogRow = { name: string; label?: string; type?: string; multiple?: boolean }; + +const FIELDS: CatalogRow[] = [ + { name: 'labels', label: 'Labels', type: 'multiselect' }, + { name: 'tags', label: 'Tags', type: 'tags' }, + { name: 'channels', label: 'Channels', type: 'checkboxes' }, + { name: 'regions', label: 'Regions', type: 'select', multiple: true }, + { name: 'watchers', label: 'Watchers', type: 'lookup', multiple: true }, + { name: 'reviewers', label: 'Reviewers', type: 'user', multiple: true }, + { name: 'status', label: 'Status', type: 'select' }, + { name: 'owner', label: 'Owner', type: 'lookup' }, + { name: 'address', label: 'Address', type: 'address' }, +]; +const LIST_FIELDS = FIELDS.slice(0, 6); +const SCALAR_FIELDS = FIELDS.slice(6); + +/** The words the builder shows for the shared builder's list operators. */ +const LIST_OP_WORDS: Record = { + contains: 'contains', + not_contains: 'does not contain', + is_empty: 'is empty', + is_not_empty: 'is not empty', +}; + +function Harness({ initial }: { initial: string }) { + const [v, setV] = React.useState(initial); + return ( +
+ +
{v}
+
+ ); +} + +const committed = () => screen.getByTestId('committed').textContent ?? ''; +const comboboxes = (c: HTMLElement) => Array.from(c.querySelectorAll('[role="combobox"]')) as HTMLElement[]; +const lastOpTrigger = (c: HTMLElement) => comboboxes(c).at(-1)!; +const rawEditor = (c: HTMLElement) => c.querySelector('textarea'); + +async function offeredOps(c: HTMLElement): Promise { + await userEvent.click(lastOpTrigger(c)); + const ops = (await screen.findAllByRole('option')).map((o) => o.textContent ?? ''); + await userEvent.keyboard('{Escape}'); + return ops; +} + +async function pickOp(c: HTMLElement, label: string) { + await userEvent.click(lastOpTrigger(c)); + await userEvent.click(await screen.findByRole('option', { name: label })); +} + +/** Add a row and pick `field` as its subject. */ +async function addRowOn(c: HTMLElement, field: CatalogRow) { + fireEvent.click(screen.getByText('Add condition')); + const subjects = comboboxes(c); + await userEvent.click(subjects[subjects.length - 2]); + await userEvent.click(await screen.findByRole('option', { name: `${field.label} record.${field.name}` })); +} + +const typeValue = (c: HTMLElement, value: string) => { + const boxes = c.querySelectorAll('input'); + fireEvent.change(boxes[boxes.length - 1], { target: { value } }); +}; + +const evaluate = (cel: string, record: Record) => { + const r = celEngine.evaluate({ dialect: 'cel', source: cel }, { record }); + if (!r.ok) throw new Error(JSON.stringify(r.error)); + return r.value; +}; + +describe('a list subject is offered the shared builder’s list operators, and nothing else', () => { + it.each(LIST_FIELDS)('$label ($type) offers membership and the empty checks — never == / != / ordering', async (field) => { + const shared = jsonColumnFilterOperators({ type: field.type, multiple: field.multiple === true })!; + expect(listSubjectOperators(field)).toEqual(shared); + const { container } = render(); + await addRowOn(container, field); + expect(await offeredOps(container)).toEqual(shared.map((op) => LIST_OP_WORDS[op])); + }); + + it.each(SCALAR_FIELDS)('CONTROL — $label ($type) keeps equals / not equals and is offered no membership', async (field) => { + expect(listSubjectOperators(field)).toBeUndefined(); + const { container } = render(); + await addRowOn(container, field); + const ops = await offeredOps(container); + expect(ops).toEqual(expect.arrayContaining(['equals', 'not equals', 'is empty', 'is not empty'])); + expect(ops).not.toContain('contains'); + expect(ops).not.toContain('does not contain'); + }); +}); + +describe('membership is written null-safe, in the flow edge’s spelling, and the engine answers it as membership', () => { + it('picking a list subject moves a new row off `equals` onto `contains`', async () => { + const { container } = render(); + await addRowOn(container, FIELDS[0]); + expect(lastOpTrigger(container).textContent).toBe('contains'); + typeValue(container, 'frontend'); + expect(committed()).toBe("record.labels != null && 'frontend' in record.labels"); + }); + + it.each(LIST_FIELDS)('$label: contains / does not contain', async (field) => { + const s = `record.${field.name}`; + const { container } = render(); + await addRowOn(container, field); + typeValue(container, 'u1'); + const contains = committed(); + await pickOp(container, 'does not contain'); + const notContains = committed(); + + expect(contains).toBe(`${s} != null && 'u1' in ${s}`); + expect(notContains).toBe(`${s} == null || !('u1' in ${s})`); + // The same row through the flow edge's writer: one spelling. + const edgeField = { value: s, label: field.label!, type: field.type, multiple: field.multiple }; + expect(rowsToCel({ logic: 'and', conditions: [{ field: s, operator: 'contains', value: 'u1' }] }, [edgeField])) + .toEqual({ ok: true, cel: contains }); + expect(rowsToCel({ logic: 'and', conditions: [{ field: s, operator: 'not_contains', value: 'u1' }] }, [edgeField])) + .toEqual({ ok: true, cel: notContains }); + + expect(evaluate(contains, { [field.name]: ['u1', 'u2'] })).toBe(true); + expect(evaluate(contains, { [field.name]: ['u2'] })).toBe(false); + expect(evaluate(contains, { [field.name]: [] })).toBe(false); + expect(evaluate(contains, { [field.name]: null })).toBe(false); + expect(evaluate(notContains, { [field.name]: ['u2'] })).toBe(true); + expect(evaluate(notContains, { [field.name]: ['u1', 'u2'] })).toBe(false); + expect(evaluate(notContains, { [field.name]: [] })).toBe(true); + expect(evaluate(notContains, { [field.name]: null })).toBe(true); + }); + + it('the empty checks on a list keep their null-or-empty-list spelling', async () => { + const { container } = render(); + await addRowOn(container, FIELDS[0]); + await pickOp(container, 'is empty'); + const cel = committed(); + expect(cel).toBe('record.labels == null || size(record.labels) == 0'); + expect(evaluate(cel, { labels: [] })).toBe(true); + expect(evaluate(cel, { labels: null })).toBe(true); + expect(evaluate(cel, { labels: ['qa'] })).toBe(false); + }); + + it('INSTRUMENT CONTROL — the equality this replaces answers a constant on a list', () => { + expect(evaluate("record.labels == 'frontend'", { labels: ['frontend', 'qa'] })).toBe(false); + expect(evaluate("record.labels == 'frontend'", { labels: ['qa'] })).toBe(false); + expect(evaluate("record.labels != 'frontend'", { labels: ['frontend', 'qa'] })).toBe(true); + expect(evaluate("record.labels != 'frontend'", { labels: ['qa'] })).toBe(true); + }); +}); + +describe('a stored condition on a list reads back exactly, or opens in the raw editor unchanged', () => { + it.each([ + ['contains, alone', "record.labels != null && 'frontend' in record.labels"], + ['does not contain, alone', "record.labels == null || !('frontend' in record.labels)"], + ['contains, joined', "record.status == 'done' && (record.watchers != null && 'u1' in record.watchers)"], + ])('%s: reopens as rows, and an edit re-emits it unchanged', (_name, cel) => { + const { container } = render(); + expect(rawEditor(container), 'opened in the raw editor — it did not round-trip').toBeNull(); + if (cel.startsWith("record.status == 'done'")) { + fireEvent.change(container.querySelector('input')!, { target: { value: 'closed' } }); + expect(committed()).toBe(cel.replace("'done'", "'closed'")); + } + }); + + it.each([ + ['== on a list', "record.labels == 'frontend'"], + ['!= on a list, joined', "record.status == 'done' && record.regions != 'emea'"], + ['membership on a single-value field', "record.owner != null && 'u1' in record.owner"], + ])('%s: opens in the raw editor verbatim, and nothing is emitted', (_name, stored) => { + const { container } = render(); + expect(rawEditor(container), 'expected the raw CEL editor').not.toBeNull(); + expect(rawEditor(container)!.value).toBe(stored); + expect(committed()).toBe(stored); + }); + + it('CONTROL — equality on a single-value field still opens as rows', () => { + const { container } = render(); + expect(rawEditor(container)).toBeNull(); + expect(lastOpTrigger(container).textContent).toBe('equals'); + }); +}); + +describe('moving a row between a list and a single-value field keeps an offered operator', () => { + it('list → single value: membership becomes equals, the value kept', async () => { + const { container } = render(); + await userEvent.click(comboboxes(container)[0]); + await userEvent.click(await screen.findByRole('option', { name: 'Status record.status' })); + expect(lastOpTrigger(container).textContent).toBe('equals'); + expect(committed()).toBe("record.status == 'frontend'"); + }); + + it('an empty check survives the move, re-spelled for the new field', async () => { + const { container } = render(); + await userEvent.click(comboboxes(container)[0]); + await userEvent.click(await screen.findByRole('option', { name: 'Owner record.owner' })); + expect(lastOpTrigger(container).textContent).toBe('is empty'); + expect(committed()).toBe('record.owner == null'); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ConditionBuilder.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ConditionBuilder.tsx index 918ea2ff6d3..3039de70b02 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ConditionBuilder.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ConditionBuilder.tsx @@ -33,8 +33,9 @@ import { CelPredicateField } from '../CelPredicateField.js'; import type { CelLintIssue } from '../celAuthoring.js'; import { useServerHoldAt } from '../draftVerdict.js'; import { t, tFormat, useMetadataLocale } from '../i18n.js'; +import { listMembershipCel, listSubjectOperators, readListMembership } from './cel-list-membership.js'; -type Op = '==' | '!=' | '>' | '<' | '>=' | '<=' | 'truthy' | 'falsy'; +type Op = '==' | '!=' | '>' | '<' | '>=' | '<=' | 'truthy' | 'falsy' | 'contains' | 'notContains'; /** The quote character a string literal was authored with. Remembered per row * so the builder re-emits the author's own spelling instead of normalising it @@ -110,9 +111,30 @@ const VALUELESS_OP_KEYS: Readonly { +/** + * This builder's operator for each operator the shared filter builder offers + * on a LIST subject (objectstack#36167). A translation, not a list: WHICH + * operators a list takes is `listSubjectOperators`' answer. + */ +const LIST_OP_CHOICES: Readonly> = { + contains: { value: 'contains', labelKey: 'engine.inspector.condition.op.contains' }, + not_contains: { value: 'notContains', labelKey: 'engine.inspector.condition.op.notContains' }, + is_empty: { value: 'falsy', labelKey: VALUELESS_OP_KEYS.emptiable.falsy }, + is_not_empty: { value: 'truthy', labelKey: VALUELESS_OP_KEYS.emptiable.truthy }, +}; + +/** The shared builder's operators for a list subject, or `undefined` when the subject is not one. */ +type ListOpsOf = (subject: string) => readonly string[] | undefined; +const NO_LIST_SUBJECTS: ListOpsOf = () => undefined; + +/** + * The operator list one row offers. A list subject (objectstack#36167) takes + * membership and the empty checks — never `==` / `!=` / ordering, which CEL + * answers as a constant on a list. Every other subject takes the compare + * operators, then the value-less pair worded for it (objectui#11894). + */ +function opChoicesFor(declared: SubjectValue | undefined, listOps?: readonly string[]): ReadonlyArray { + if (listOps) return listOps.flatMap((op) => (LIST_OP_CHOICES[op] ? [LIST_OP_CHOICES[op]] : [])); const keys = VALUELESS_OP_KEYS[ declared === undefined ? 'undeclared' : declared === 'boolean' ? 'boolean' : 'emptiable' ]; @@ -179,6 +201,28 @@ function declaredSubjectValues( return out; } +/** + * Every LIST subject the catalog declares (objectstack#36167), keyed like + * {@link declaredSubjectValues}, with the operators the shared builder offers + * it. A field is a list exactly when its 「is empty」 row is `multi_value` — + * both read the spec's `isMultiValueField` — so this map moves only when that + * one does. + */ +function listSubjectOps( + fields: ReadonlyArray, + fieldPrefix: string, + includePrevious: boolean, +): Map { + const out = new Map(); + for (const f of fields) { + const ops = listSubjectOperators(f); + if (!ops) continue; + out.set(`${fieldPrefix}${f.name}`, ops); + if (includePrevious) out.set(`previous.${f.name}`, ops); + } + return out; +} + /** * The context subjects a record-scoped mount site binds. This is the DEFAULT * vocabulary — a caller that binds something else declares it via @@ -675,7 +719,12 @@ function compileRow(r: Row, valueOf: SubjectValueOf): { cel: string; compound: b const clauses = emptyCheckClauses(r.subject, declared, empty); return { cel: clauses.join(empty ? ' || ' : ' && '), compound: clauses.length > 1 }; } - const cmp = `${r.subject} ${r.op} ${fmtValue(r.value, r.quote)}`; + if (r.op === 'contains' || r.op === 'notContains') { + // objectstack#36167 — list membership, in the one spelling the flow edge's + // rows write too; null-safe, as CEL's `in` faults on a `null` list. + return { cel: listMembershipCel(r.subject, fmtValue(r.value, r.quote), r.op === 'contains'), compound: true }; + } + const cmp =`${r.subject} ${r.op} ${fmtValue(r.value, r.quote)}`; // objectstack#27513 — an ordering comparison on a field faults on a `null` // value and the server refuses it at publish; behind `!= null` it is well // typed for every value. The same guard the "can't be negative" preset @@ -790,10 +839,23 @@ function parseGuardedCompare(text: string): Row | null { return compileRow(row, NOTHING_DECLARED).cel === text ? row : null; } +/** + * Read `text` back as a list membership row (objectstack#36167), or `null`. + * Accepts exactly the text {@link compileRow} emits for such a row; whether + * its subject is a list is {@link initFrom}'s question. + */ +function parseMembership(text: string): Row | null { + const m = readListMembership(text); + if (!m) return null; + const v = unfmtValue(m.member); + const row: Row = { subject: m.subject, op: m.contains ? 'contains' : 'notContains', value: v.value, quote: v.quote }; + return compileRow(row, NOTHING_DECLARED).cel === text ? row : null; +} + /** Read one AND/OR term back as a row, or `null` when it is not a row's shape. */ function parseTerm(p: string, valueOf: SubjectValueOf): Row | null { const group = enclosedGroup(p); - if (group !== null) return parseEmptyCheck(group, valueOf) ?? parseGuardedCompare(group); + if (group !== null) return parseEmptyCheck(group, valueOf) ?? parseGuardedCompare(group) ?? parseMembership(group); const check = parseEmptyCheck(p, valueOf); if (check) return check; const cmp = /^([a-zA-Z_][\w.]*)\s*(==|!=|>=|<=|>|<)\s*(.+)$/.exec(p); @@ -817,7 +879,7 @@ function parse( if (!s) return { rows: [], join: '&&' }; // A lone row whose check is several clauses compiles without parentheses, // so the whole text is tried as that one row before it is split. - const whole = parseEmptyCheck(s, valueOf) ?? parseGuardedCompare(s); + const whole = parseEmptyCheck(s, valueOf) ?? parseGuardedCompare(s) ?? parseMembership(s); if (whole) return { rows: [whole], join: '&&' }; const split = splitTopLevel(s); if (!split) return null; @@ -837,10 +899,19 @@ function parse( * author stored, so it opens in the raw editor verbatim rather than being * rewritten on their next edit (objectui#11894) — the rule this component's * header states for every expression it cannot reproduce. + * + * A row whose operator its subject is not offered opens in the raw editor too + * (objectstack#36167): a stored `record.tags == 'x'` on a list is a predicate + * CEL answers as a constant, and the rows have no operator to show it with. */ -function initFrom(value: string, valueOf: SubjectValueOf): { rows: Row[]; join: '&&' | '||'; raw: boolean } { +function initFrom( + value: string, + valueOf: SubjectValueOf, + listOpsOf: ListOpsOf = NO_LIST_SUBJECTS, +): { rows: Row[]; join: '&&' | '||'; raw: boolean } { const p = parse(value || '', valueOf); - if (p && norm(compile(p.rows, p.join, valueOf)) === norm(value || '')) { + const offered = (r: Row) => opChoicesFor(valueOf(r.subject), listOpsOf(r.subject)).some((o) => o.value === r.op); + if (p && p.rows.every(offered) && norm(compile(p.rows, p.join, valueOf)) === norm(value || '')) { return { rows: p.rows, join: p.join, raw: false }; } return { rows: [], join: '&&', raw: !!value }; @@ -1010,6 +1081,24 @@ export function ConditionBuilder({ label, value, onCommit, objectName, fields: f [fields, fieldPrefix, includePrevious], ); const valueOf: SubjectValueOf = (subject) => subjectValues.get(subject); + /** The list subjects and their operators (objectstack#36167). It moves only + * with `declaredKey` — see {@link listSubjectOps}. */ + const listOps = React.useMemo( + () => listSubjectOps(fields, fieldPrefix, includePrevious), + [fields, fieldPrefix, includePrevious], + ); + const listOpsOf: ListOpsOf = (subject) => listOps.get(subject); + /** The operators the row's subject is offered. */ + const opsFor = (subject: string) => opChoicesFor(valueOf(subject), listOpsOf(subject)); + /** + * A row whose new subject is not offered its operator takes the subject's + * first one (objectstack#36167): a list subject is never left on `==`, and a + * row moved off a list onto a single-value field is never left on membership. + */ + const withOfferedOp = (r: Row): Row => { + const ops = opsFor(r.subject); + return ops.some((o) => o.value === r.op) ? r : { ...r, op: ops[0].value }; + }; /** Every subject spelling that names a catalog field, hidden and untyped * ones included — what an ordering row is guarded on (objectstack#27513). */ const fieldSubjects = React.useMemo(() => { @@ -1024,11 +1113,13 @@ export function ConditionBuilder({ label, value, onCommit, objectName, fields: f // Held in a ref so the effects below read this render's catalog without // listing a function that is new every render. const valueOfRef = React.useRef(valueOf); + const listOpsOfRef = React.useRef(listOpsOf); React.useEffect(() => { valueOfRef.current = valueOf; + listOpsOfRef.current = listOpsOf; }); - const init = React.useMemo(() => initFrom(value, valueOf), []); // first mount only + const init = React.useMemo(() => initFrom(value, valueOf, listOpsOf), []); // first mount only const [rows, setRowsState] = React.useState(init.rows); const [join, setJoin] = React.useState<'&&' | '||'>(init.join); const [raw, setRaw] = React.useState(init.raw); @@ -1043,7 +1134,7 @@ export function ConditionBuilder({ label, value, onCommit, objectName, fields: f if (v === lastEmitted.current) return; lastEmitted.current = v; editedSinceRead.current = false; - const next = initFrom(v, valueOfRef.current); + const next = initFrom(v, valueOfRef.current, listOpsOfRef.current); setRowsState(next.rows); setJoin(next.join); setRaw(next.raw); @@ -1063,7 +1154,7 @@ export function ConditionBuilder({ label, value, onCommit, objectName, fields: f if (readDeclaredKey.current === declaredKey) return; readDeclaredKey.current = declaredKey; if (editedSinceRead.current) return; - const next = initFrom(lastEmitted.current, valueOfRef.current); + const next = initFrom(lastEmitted.current, valueOfRef.current, listOpsOfRef.current); setRowsState(next.rows); setJoin(next.join); setRaw(next.raw); @@ -1128,7 +1219,7 @@ export function ConditionBuilder({ label, value, onCommit, objectName, fields: f
{label ? : } @@ -1200,7 +1291,7 @@ export function ConditionBuilder({ label, value, onCommit, objectName, fields: f )}
- update(rows.map((x, j) => j === i ? withOfferedOp({ ...x, subject: v }) : x))} disabled={disabled}> {subjectOptions.map((o) => ( @@ -1225,7 +1316,7 @@ export function ConditionBuilder({ label, value, onCommit, objectName, fields: f
diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ConditionBuilder.typedEmptyOps-11894.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ConditionBuilder.typedEmptyOps-11894.test.tsx index fae60a0d5f2..542d9011077 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ConditionBuilder.typedEmptyOps-11894.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ConditionBuilder.typedEmptyOps-11894.test.tsx @@ -118,6 +118,12 @@ function mountBenchmark(subject: string, fields: ReadonlyArray = TYP return render(); } +/** The same on a LIST subject, whose stored second row is membership: a list is + * not offered `==`, so `S == 'x'` would open in the raw editor (objectstack#36167). */ +function mountListBenchmark(subject: string) { + return render(); +} + describe('the benchmark rule on a DATE field evaluates both ways (objectui#11894)', () => { it('"is empty" compiles to a null check, true with no due date and false with one', async () => { const { container } = mountBenchmark('record.due_date'); @@ -170,7 +176,7 @@ describe('a TEXT field: "is empty" is null or the empty string', () => { describe('a MULTI-VALUE field: "is empty" is null or the empty list', () => { it('`tags`: true for null and for [], false for a member', async () => { - const { container } = mountBenchmark('record.tags'); + const { container } = mountListBenchmark('record.tags'); await pickOp(container, 'is empty'); const cel = committed(); expect(cel).toBe("record.status == 'done' && (record.tags == null || size(record.tags) == 0)"); @@ -180,7 +186,7 @@ describe('a MULTI-VALUE field: "is empty" is null or the empty list', () => { }); it('a lookup is multi-value only when declared `multiple: true` — the spec reads both keys', async () => { - const multi = mountBenchmark('record.watchers'); + const multi = mountListBenchmark('record.watchers'); await pickOp(multi.container, 'is not empty'); const multiCel = committed(); expect(multiCel).toBe("record.status == 'done' && (record.watchers != null && size(record.watchers) != 0)"); diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/cel-list-membership.ts b/ui/packages/app-shell/src/views/metadata-admin/inspectors/cel-list-membership.ts new file mode 100644 index 00000000000..44325793b0d --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/cel-list-membership.ts @@ -0,0 +1,69 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * cel-list-membership — list membership in CEL, ONE spelling for every builder + * that writes a condition on a list subject (objectstack#36167): the flow + * edge's rows (`flow-edge-condition-rows.ts`, objectstack#35992) and the + * `ConditionBuilder`. + * + * A list subject is a field whose stored value is a list: a `multiselect` / + * `checkboxes` / `tags`, or a multi-capable type declared `multiple: true`. + * Under `@objectstack/formula`'s `celEngine`, `S == V` compares the whole list + * with one value, so it is false for every record (and `S != V` true for every + * record); `S.contains(V)` faults ("no matching overload"); and `V in S` is + * membership. So a list subject is offered membership and the empty checks, + * and membership is written null-safe: + * + * - contains → `S != null && V in S`; + * - does not contain → `S == null || !(V in S)`. + * + * Which operators a list subject takes is the shared filter builder's answer + * (`jsonColumnFilterOperators`), read here rather than restated, so the + * builders and the list toolbar's `FilterBuilder` cannot disagree. + */ + +import { jsonColumnFilterOperators, type FilterBuilderOperator } from '@object-ui/components'; + +/** The two facts that decide whether a field holds a list. */ +export interface ListSubjectFacts { + type?: string; + multiple?: boolean; +} + +/** + * The operators the shared builder offers on a LIST subject — membership and + * the empty checks — or `undefined` for every other field. A structured-JSON + * field (`json`, `address`, …) takes the empty checks only and is not a list: + * its value is an object, so it answers `undefined` here. + */ +export function listSubjectOperators(field: ListSubjectFacts): readonly FilterBuilderOperator[] | undefined { + const ops = jsonColumnFilterOperators({ type: field.type, multiple: field.multiple === true }); + return ops?.includes('contains') ? ops : undefined; +} + +/** + * Membership of `member` (already a CEL literal or reference) in the list + * `subject`: `contains` ⇒ `S != null && V in S`, else its complement + * `S == null || !(V in S)`. Both are two clauses, so a caller parenthesises + * the result when it joins it with other terms. + */ +export function listMembershipCel(subject: string, member: string, contains: boolean): string { + return contains ? `${subject} != null && ${member} in ${subject}` : `${subject} == null || !(${member} in ${subject})`; +} + +const SUBJECT = '[A-Za-z_][A-Za-z0-9_]*(?:\\.[A-Za-z_][A-Za-z0-9_]*)*'; +const CONTAINS_RE = new RegExp(`^(${SUBJECT}) != null && (.+) in \\1$`); +const NOT_CONTAINS_RE = new RegExp(`^(${SUBJECT}) == null \\|\\| !\\((.+) in \\1\\)$`); + +/** + * Read `text` back as the membership {@link listMembershipCel} writes, or + * `null`. Accepts exactly what the writer emits for the parts it reads — the + * member's own text is the caller's to read as a value. + */ +export function readListMembership(text: string): { subject: string; member: string; contains: boolean } | null { + for (const [re, contains] of [[CONTAINS_RE, true], [NOT_CONTAINS_RE, false]] as const) { + const m = re.exec(text); + if (m && listMembershipCel(m[1], m[2], contains) === text) return { subject: m[1], member: m[2], contains }; + } + return null; +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-edge-condition-rows.ts b/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-edge-condition-rows.ts index a4cd78ff1f2..8f806da4032 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-edge-condition-rows.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-edge-condition-rows.ts @@ -40,7 +40,8 @@ * list membership, `S != null && V in S`, and `not_contains` its complement, * `S == null || !(V in S)`. CEL has no `contains` method on a list (it * faults with "no matching overload"), and `S == V` compares the whole list - * with one value, so it is false for every record. + * with one value, so it is false for every record. The spelling is the one + * `ConditionBuilder` writes too (`cel-list-membership.ts`). * - `in` / `not_in` → `S in [A, B]` / `!(S in [A, B])`. * - `is_empty` / `is_not_empty` → the spec's ruled 「is empty」 table * (`expandEmptyOperator`), in the clauses `ConditionBuilder` writes: @@ -68,9 +69,10 @@ * that writes more than one clause is parenthesised when it is joined. */ -import { operatorsForField, jsonColumnFilterOperators, isFilterValueComplete } from '@object-ui/components'; +import { operatorsForField, isFilterValueComplete } from '@object-ui/components'; import { expandEmptyOperator, type EmptyOperatorArm } from '@objectstack/spec/data'; import { FILTER_DATE_LIKE_TYPES, FILTER_LOOKUP_LIKE_TYPES, FILTER_NUMBER_LIKE_TYPES, FILTER_SELECT_LIKE_TYPES } from '@object-ui/types'; +import { listMembershipCel, listSubjectOperators } from './cel-list-membership.js'; /** One column the rows may name: `value` is its CEL subject (`record.meeting_date`). */ export interface EdgeConditionField { @@ -184,12 +186,11 @@ function offered(field: EdgeConditionField, operator: string): boolean { /** * Whether the column holds a list — the columns the shared builder offers - * membership on (`jsonColumnFilterOperators` answers the multi-value set, whose - * `contains` is one member). A structured-JSON column gets the empty checks - * only, so its `contains` never reaches the writer. + * membership on (`listSubjectOperators`, objectstack#36167). A structured-JSON + * column gets the empty checks only, so its `contains` never reaches the writer. */ function isListColumn(field: EdgeConditionField): boolean { - return jsonColumnFilterOperators({ type: field.type, multiple: field.multiple === true })?.includes('contains') === true; + return listSubjectOperators(field) !== undefined; } const ORDERING: Readonly> = { @@ -212,9 +213,7 @@ function rowCel(row: EdgeConditionRow, field: EdgeConditionField): { cel: string // List membership: one member per row, as the builder's value control picks. const v = typeof row.value === 'string' ? literalOf(row.value, kind) : undefined; if (v === undefined) return null; - return op === 'contains' - ? { cel: `${s} != null && ${v} in ${s}`, compound: true } - : { cel: `${s} == null || !(${v} in ${s})`, compound: true }; + return { cel: listMembershipCel(s, v, op === 'contains'), compound: true }; } switch (op) { case 'is_empty': diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectValidationsPanel.typedEmptyOps-11894.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectValidationsPanel.typedEmptyOps-11894.test.tsx index 2cf424c945e..d32817f37b7 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectValidationsPanel.typedEmptyOps-11894.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectValidationsPanel.typedEmptyOps-11894.test.tsx @@ -19,6 +19,11 @@ * with `{ record, previous }` as objectql's `checkPredicate` calls it. */ +// The builder reaches a dynamic `import()` of each module below: its first load +// is paid here, at collection, never inside a case's clocked window +// (`check:test-source-alias`). +import '@objectstack/lint'; +import '@object-ui/core'; import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest'; @@ -113,7 +118,9 @@ describe('the Rules tab types the condition builder (objectui#11894)', () => { it('a lookup declared `multiple` builds "is empty" as null or an empty list — the flag reaches the builder', async () => { const onPatch = vi.fn(); - render(); + // A list is offered membership, not `==` (objectstack#36167): a stored + // `record.watchers == 'x'` would open in the raw editor. + render(); await pickOp('record.watchers', 'is empty'); const cel = writtenCondition(onPatch) as string; expect(cel).toBe("record.status == 'done' && (record.watchers == null || size(record.watchers) == 0)"); diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 267e8a870aa..ad03b30cbbd 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -1509,6 +1509,8 @@ const STUDIO_EN: Record = { 'engine.inspector.condition.op.atLeast': 'at least', 'engine.inspector.condition.op.atMost': 'at most', 'engine.inspector.condition.op.contains': 'contains', + // objectstack#36167 — membership's complement on a list subject. + 'engine.inspector.condition.op.notContains': 'does not contain', 'engine.inspector.condition.op.inAnyOf': 'in (any of)', 'engine.inspector.condition.op.notIn': 'not in', 'engine.inspector.view.type.grid': 'Table / List', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index d244373187f..701b046cfc6 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -1340,6 +1340,7 @@ const STUDIO_ZH: Record = { 'engine.inspector.condition.op.atLeast': '至少', 'engine.inspector.condition.op.atMost': '至多', 'engine.inspector.condition.op.contains': '包含', + 'engine.inspector.condition.op.notContains': '不包含', 'engine.inspector.condition.op.inAnyOf': '属于(任一)', 'engine.inspector.condition.op.notIn': '不属于', 'engine.inspector.view.type.grid': '表格 / 列表',