Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/34339-formula-label-multi-select.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/formula': minor
---

fix(formula): `label()` over a multi-select reads each selected option's label, joined with `, `

Clause-②: no
Metadata-protocol: semantic

A formula `label(record.<field>)` over a `multiple: true` select used to fault on every non-empty selection, so the formula field read null in every view (the engine logged "renders ONE option value … holds a list of values"), while `os validate` and `os lint --strict` passed it.

It now reads the label of each selected value in the reader's language, in the order the record stores the values, joined with `, `: a record holding `['no_sales_price', 'no_customer']` reads `无销售价, 无客户` to a `zh-CN` reader and `No sales price, No customer` to an `en-US` one. A one-value selection reads that one label. An empty selection or an empty field reads `''`, as before. A listed value no option declares reads as stored, as a single value does.

This is the rule a mail template's `option` hole already prints a multi-select by; both now go through one shared helper, so the two cannot drift. A single select reads exactly as before. Nothing to migrate: a formula that read null now reads text.
7 changes: 6 additions & 1 deletion content/docs/data-modeling/formulas.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,12 @@ page title, related lists and lookups all follow it.
(`os validate`, `os build`, the object save door), with the field named,
because it has no label to read and the formula would read null on every row.
An empty value reads `''`; a stored value no option declares reads as itself.
A multi-value select is refused.
- On a multi-value select (`multiple: true`), `label()` reads the label of each
selected value, in the order the record stores them, joined with `, `: a
record holding `['no_sales_price', 'no_customer']` reads `无销售价, 无客户` to a
`zh-CN` reader and `No sales price, No customer` to an `en-US` one. An empty
selection reads `''`. A mail template's `option` hole prints the same list
the same way.
- A read with no locale (a script, a scheduled job) reads the declared labels.
- A **stored** computed field (a `text` field with an `expression`) is computed
once, on the write, so it stores the declared label whatever the writer's
Expand Down
88 changes: 81 additions & 7 deletions packages/formula/src/option-label.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';

import { celEngine } from './cel-engine';
import { formatValue } from './template-engine';
import { inferExpressionType } from './validate';
import type { EvalOptionLabels } from './types';
import type { Expression } from '@objectstack/spec';
Expand Down Expand Up @@ -58,7 +59,7 @@ describe('label(record.<field>) — option labels in the reader\'s locale (#2660
}
});

it('refuses a field that declares no options, on every row, and a list value', () => {
it('refuses a field that declares no options, on every row', () => {
const plain = celEngine.evaluate(cel('label(record.title)'), { record, optionLabels: zhCN });
expect(plain.ok).toBe(false);
if (!plain.ok) {
Expand All @@ -69,12 +70,12 @@ describe('label(record.<field>) — option labels in the reader\'s locale (#2660
const empty = celEngine.evaluate(cel('label(record.title)'), { record: { ...record, title: null }, optionLabels: zhCN });
expect(empty.ok).toBe(false);
if (!empty.ok) expect(empty.error.message).toContain('`title` declares no options');
const list = celEngine.evaluate(cel('label(record.tags)'), {
record,
optionLabels: { ...zhCN, tags: { a: 'A' } },
});
expect(list.ok).toBe(false);
if (!list.ok) expect(list.error.message).toContain('renders ONE option value');
});

it('refuses an object value at run time — it is no option value', () => {
const r = celEngine.evaluate(cel('label(record.kind)'), { record: { kind: { v: 'clean' } }, optionLabels: zhCN });
expect(r.ok).toBe(false);
if (!r.ok) expect(r.error.kind).toBe('runtime');
});

it('compiles the one argument shape and refuses every other at the type check', () => {
Expand All @@ -100,3 +101,76 @@ describe('label(record.<field>) — option labels in the reader\'s locale (#2660
expect(inferExpressionType('label(record.kind)')).toBe('text');
});
});

/**
* `label(record.<field>)` over a `multiple: true` select — a list of stored
* values — prints the label of each value, in the order the record stores
* them, joined with `, `: the rule the mail template's `option` hole applies
* to the same list (`OPTION_ARGUMENT_RULE`), through one shared helper.
*/
describe('label(record.<field>) over a multi-select — each selected label, joined', () => {
const GAPS = 'label(record.gaps)';
const zh: EvalOptionLabels = {
gaps: { no_sales_price: '无销售价', no_customer: '无客户', no_freight_region: '无运费区域' },
one: { no_customer: '无客户' },
};
const en: EvalOptionLabels = {
gaps: { no_sales_price: 'No sales price', no_customer: 'No customer', no_freight_region: 'No freight region' },
one: { no_customer: 'No customer' },
};
const evalIn = (labels: EvalOptionLabels, rec: Record<string, unknown>, source = GAPS) =>
celEngine.evaluate(cel(source), { record: rec, optionLabels: labels });

it('reads each selected value\'s label in the reader\'s language, joined with `, `', () => {
const rec = { gaps: ['no_sales_price', 'no_customer'] };
expect(evalIn(zh, rec)).toEqual({ ok: true, value: '无销售价, 无客户' });
expect(evalIn(en, rec)).toEqual({ ok: true, value: 'No sales price, No customer' });
});

it('reads a one-element list as that one label', () => {
expect(evalIn(zh, { gaps: ['no_freight_region'] })).toEqual({ ok: true, value: '无运费区域' });
expect(evalIn(en, { gaps: ['no_freight_region'] })).toEqual({ ok: true, value: 'No freight region' });
});

it('keeps the order the record stores, not the order the options are declared in', () => {
expect(evalIn(en, { gaps: ['no_freight_region', 'no_sales_price'] }))
.toEqual({ ok: true, value: 'No freight region, No sales price' });
});

it('reads an empty list and an empty field as \'\', as a single select reads empty', () => {
expect(evalIn(zh, { gaps: [] })).toEqual({ ok: true, value: '' });
expect(evalIn(zh, { gaps: null })).toEqual({ ok: true, value: '' });
});

it('reads a listed value no option declares as itself, as the single-value path does', () => {
expect(evalIn(en, { one: 'retired' }, 'label(record.one)')).toEqual({ ok: true, value: 'retired' });
expect(evalIn(en, { gaps: ['no_customer', 'retired'] })).toEqual({ ok: true, value: 'No customer, retired' });
});

it('composes into a sentence like any string', () => {
const r = evalIn(zh, { gaps: ['no_customer'] }, "'缺: ' + label(record.gaps)");
expect(r).toEqual({ ok: true, value: '缺: 无客户' });
});

it('a field that declares no options still faults on a list, as on every other value', () => {
const r = celEngine.evaluate(cel('label(record.tags)'), { record: { tags: ['a'] }, optionLabels: zh });
expect(r.ok).toBe(false);
if (!r.ok) expect(r.error.kind).toBe('runtime');
});

it('a list holding an object faults — an object is no option value', () => {
const r = evalIn(zh, { gaps: ['no_customer', { v: 'x' }] });
expect(r.ok).toBe(false);
if (!r.ok) expect(r.error.kind).toBe('runtime');
});

it('⭐ prints what the mail template\'s `option` hole prints for the same list — one rule', () => {
const list = ['no_freight_region', 'retired', 'no_customer'];
const viaLabel = evalIn(en, { gaps: list });
const viaHole = formatValue('option', list, 'quote_line.gaps', {
optionLabels: { 'quote_line.gaps': en.gaps },
});
expect(viaLabel).toEqual({ ok: true, value: viaHole });
expect(viaHole).toBe('No freight region, retired, No customer');
});
});
40 changes: 35 additions & 5 deletions packages/formula/src/stdlib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -490,14 +490,32 @@ export function optionlessLabelSentence(field: string): string {
);
}

/**
* A list of stored option values — a multi-select's value — as the label of
* each, in the order the list holds them, joined with `, `.
*
* The ONE spelling of that rule: `label(record.<field>)` ({@link optionLabelOf})
* and the mail template's `option` hole (`template-engine.ts`,
* `OPTION_ARGUMENT_RULE`) both print a multi-select through it, each with its
* own single-value lookup as `labelOf`, so the two agree on the order and the
* separator by construction.
*
* Package-internal (NOT re-exported from `index.ts`).
*/
export function labelEachOption(values: readonly unknown[], labelOf: (value: unknown) => string): string {
return values.map((value) => labelOf(value)).join(', ');
}

/**
* The label a reader reads for `value` of `field`, from the pinned map.
*
* `null` / absent is `''`, so a name composes cleanly over an empty select
* (`trim()` answers `''` for the same reason). A value no option declares reads
* as itself — the select control shows such a value the same way. Everything
* else that cannot be answered THROWS, which the engine reports as
* `{ ok: false, kind: 'runtime' }`.
* as itself — the select control shows such a value the same way. A list — a
* `multiple: true` select's value — reads the label of each of its values, in
* stored order, joined with `, ` ({@link labelEachOption}); an empty list is
* `''`. Everything else that cannot be answered THROWS, which the engine
* reports as `{ ok: false, kind: 'runtime' }`.
*/
function optionLabelOf(field: string, value: unknown, labels: EvalOptionLabels | undefined): string {
if (labels === undefined) {
Expand All @@ -513,11 +531,23 @@ function optionLabelOf(field: string, value: unknown, labels: EvalOptionLabels |
// row, not only on the rows where it happens to hold a value.
const options = Object.prototype.hasOwnProperty.call(labels, field) ? labels[field] : undefined;
if (options === undefined) throw new Error(optionlessLabelSentence(field));
if (Array.isArray(value)) return labelEachOption(value, (item) => oneOptionLabel(field, item, options, true));
return oneOptionLabel(field, value, options, false);
}

/** One stored option value of `field` as its label from `options`, or as stored when no option declares it. */
function oneOptionLabel(
field: string,
value: unknown,
options: Readonly<Record<string, string>>,
listed: boolean,
): string {
if (value === null || value === undefined) return '';
if (typeof value === 'object') {
throw new Error(
`label(record.${field}) renders ONE option value, and \`${field}\` holds ` +
`${Array.isArray(value) ? 'a list of values' : 'an object'} on this record.`,
`label(record.${field}) reads a select field's option values, and \`${field}\` holds ` +
`${listed ? 'a list with a non-option entry' : 'an object'} on this record: an option value is ` +
'text or a number.',
);
}
const stored = String(value);
Expand Down
7 changes: 4 additions & 3 deletions packages/formula/src/template-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

import type { Expression } from '@objectstack/spec';

import { buildScope } from './stdlib';
import { buildScope, labelEachOption } from './stdlib';
import type { DialectEngine, EvalContext, EvalResult } from './types';

/**
Expand Down Expand Up @@ -165,13 +165,14 @@ const FORMATTERS: Record<string, Formatter> = {
// field it throws, whatever the value (`optionTableRefusal`): the hole
// promises a label, so the stored value is never printed in its place, as
// `currency` never picks a currency. A multi-select value labels each
// element, joined with `, `.
// element, in stored order, joined with `, ` — `labelEachOption`, the rule
// `label(record.<field>)` prints a multi-select by too.
option: (v, arg, _locale, _timeZone, _currency, optionLabels) => {
const objectField = arg ?? '';
const refusal = optionTableRefusal(`option:${objectField}`, objectField, optionLabels);
if (refusal) throw new RangeError(refusal);
const labels = optionLabels![objectField];
if (Array.isArray(v)) return v.map((item) => optionLabelOf(item, labels)).join(', ');
if (Array.isArray(v)) return labelEachOption(v, (item) => optionLabelOf(item, labels));
return optionLabelOf(v, labels);
},
};
Expand Down
78 changes: 78 additions & 0 deletions packages/objectql/src/engine-formula-option-label.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -215,3 +215,81 @@ describe('#33634 — the declared sourceLocale, not defaultLocale, is the author
expect(a.display_name).toBe('v2 · 清稿');
});
});

describe('label() over a multi-select reads each selected label, joined, in the reader\'s locale', () => {
// The card's quote-line shape: a multi-select of gap kinds named by a
// formula, beside a CONTROL single select named the same way.
const LINE = {
name: 'ol_quote_line',
label: 'Quote Line',
fields: {
id: { name: 'id', label: 'ID', type: 'text' as const, primaryKey: true },
gaps: {
name: 'gaps', label: 'Gaps', type: 'select' as const, multiple: true,
options: [
{ label: 'No sales price', value: 'no_sales_price' },
{ label: 'No customer', value: 'no_customer' },
{ label: 'No freight region', value: 'no_freight_region' },
],
},
gaps_note: {
name: 'gaps_note', label: 'Gaps Note', type: 'formula' as const,
expression: { dialect: 'cel', source: 'label(record.gaps)' },
},
one: {
name: 'one', label: 'One Gap', type: 'select' as const,
options: [{ label: 'No sales price', value: 'no_sales_price' }, { label: 'No customer', value: 'no_customer' }],
},
one_note: {
name: 'one_note', label: 'One Note', type: 'formula' as const,
expression: { dialect: 'cel', source: 'label(record.one)' },
},
},
};
const GAP_LABELS = { no_sales_price: '无销售价', no_customer: '无客户', no_freight_region: '无运费区域' };

async function makeLineEngine() {
const engine = new ObjectQL();
const rig = makeStubDriver();
engine.registerDriver(rig.driver as never, true);
await engine.init();
engine.registry.registerObject(LINE as never, 'test');
engine.setI18nService(makeI18n({
getTranslations: (locale: string) => (locale === 'zh-CN'
? { objects: { ol_quote_line: { fields: { gaps: { options: GAP_LABELS }, one: { options: GAP_LABELS } } } } }
: {}),
}));
return { engine, ...rig };
}

const readIn = (engine: ObjectQL, id: unknown, context: unknown) =>
engine.findOne('ol_quote_line', { where: { id }, context } as never) as Promise<Rec>;

it('a record read answers the joined labels in zh-CN and en-US, beside the single-select control', async () => {
const { engine } = await makeLineEngine();
const created = await engine.insert(
'ol_quote_line', { gaps: ['no_sales_price', 'no_customer'], one: 'no_customer' }, { context: enUS },
) as Rec;
const zh = await readIn(engine, created.id, zhCN);
expect(zh.gaps_note).toBe('无销售价, 无客户');
expect(zh.one_note).toBe('无客户');
const en = await readIn(engine, created.id, enUS);
expect(en.gaps_note).toBe('No sales price, No customer');
expect(en.one_note).toBe('No customer');
});

it('a one-element selection reads that one label; the write response reads the writer\'s locale', async () => {
const { engine } = await makeLineEngine();
const created = await engine.insert('ol_quote_line', { gaps: ['no_freight_region'] }, { context: zhCN }) as Rec;
expect(created.gaps_note).toBe('无运费区域');
expect((await readIn(engine, created.id, enUS)).gaps_note).toBe('No freight region');
});

it('an empty selection and an empty field read \'\'', async () => {
const { engine } = await makeLineEngine();
const empty = await engine.insert('ol_quote_line', { gaps: [] }, { context: zhCN }) as Rec;
expect((await readIn(engine, empty.id, zhCN)).gaps_note).toBe('');
const none = await engine.insert('ol_quote_line', { gaps: null }, { context: enUS }) as Rec;
expect((await readIn(engine, none.id, enUS)).gaps_note).toBe('');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { defineStack } from '@objectstack/spec';

const OBJECT = 'fol_version';
const NAME = "'v' + string(record.version_no) + ' · ' + label(record.kind)";
const GAPS = 'label(record.gaps)';

const fixtureStack = defineStack({
manifest: {
Expand Down Expand Up @@ -50,13 +51,35 @@ const fixtureStack = defineStack({
],
},
display_name: { type: 'formula', label: 'Name', expression: { dialect: 'cel', source: NAME }, returnType: 'text' },
// A multi-select read through `label()`: each selected label, joined
// with `, `. `kind` + `display_name` above is its single-select CONTROL.
gaps: {
type: 'select',
label: 'Gaps',
multiple: true,
options: [
{ label: 'No sales price', value: 'no_sales_price' },
{ label: 'No customer', value: 'no_customer' },
{ label: 'No freight region', value: 'no_freight_region' },
],
},
gaps_note: {
type: 'formula', label: 'Gaps Note', expression: { dialect: 'cel', source: GAPS }, returnType: 'text',
},
},
},
],
translations: [
{
'zh-CN': {
objects: { [OBJECT]: { fields: { kind: { options: { clean: '清稿', redline: '修订稿' } } } } },
objects: {
[OBJECT]: {
fields: {
kind: { options: { clean: '清稿', redline: '修订稿' } },
gaps: { options: { no_sales_price: '无销售价', no_customer: '无客户', no_freight_region: '无运费区域' } },
},
},
},
},
},
],
Expand Down Expand Up @@ -142,4 +165,23 @@ describe('dogfood: a formula name reads its select option label in the reader\'s
expect((await readOne(locale, created.id)).display_name, locale).toBe(`v7 · ${shown}`);
}
});

it('label() over a multi-select reads each selected label, joined, in each reader\'s locale', async () => {
const created = await create('en-US', { version_no: 8, kind: 'clean', gaps: ['no_sales_price', 'no_customer'] });
const zh = await readOne('zh-CN', created.id);
expect(zh.gaps_note).toBe('无销售价, 无客户');
expect(zh.display_name).toBe('v8 · 清稿'); // CONTROL: the single select on the same record
const en = await readOne('en-US', created.id);
expect(en.gaps_note).toBe('No sales price, No customer');
expect(en.display_name).toBe('v8 · Clean');

const one = await create('zh-CN', { version_no: 9, kind: 'clean', gaps: ['no_freight_region'] });
expect(one.gaps_note).toBe('无运费区域');
expect((await readOne('en-US', one.id)).gaps_note).toBe('No freight region');

const empty = await create('en-US', { version_no: 10, kind: 'clean', gaps: [] });
expect((await readOne('zh-CN', empty.id)).gaps_note).toBe('');
const none = await create('en-US', { version_no: 11, kind: 'clean' });
expect((await readOne('en-US', none.id)).gaps_note).toBe('');
});
});
Loading