Skip to content

Commit 7f9627d

Browse files
committed
fix(formula): the template formatter locale rides a reserved context channel, never a root
A template's roots are author-visible values: a bulk action's params, a flow's variables. The engine read its formatter locale from extra.locale, so a root named locale set the locale of every formatted value in the sentence, and no viewer locale was ever passed. EvalContext gains a reserved locale field the engine reads instead, the console filler takes the display locale from its caller, and both React runner owners install useDisplayLocale() on the runner. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XbF1LGGBRTWwTfLay1d51s
1 parent 9598405 commit 7f9627d

12 files changed

Lines changed: 240 additions & 18 deletions

File tree

‎packages/formula/src/template-engine.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,3 +69,38 @@ describe('templateEngine', () => {
6969
expect(r).toEqual({ ok: true, value: 'hot' });
7070
});
7171
});
72+
73+
// The formatter locale rides the context's reserved `locale` channel, never a
74+
// root (#26232). Expected strings come from `Intl` itself, so a newer ICU in CI
75+
// cannot drift them.
76+
describe('templateEngine — formatter locale channel', () => {
77+
const source = '{{ amount | number:2 }} · {{ due | date:long }} · {{ locale }}';
78+
const roots = { amount: 1234567.5, due: '2031-05-06T12:00:00Z' };
79+
const due = new Date('2031-05-06T12:00:00Z');
80+
const expected = (tag: string, printed = '') =>
81+
`${new Intl.NumberFormat(tag, { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(1234567.5)} · ` +
82+
`${new Intl.DateTimeFormat(tag, { dateStyle: 'long' }).format(due)} · ${printed}`;
83+
const render = (ctx: Parameters<typeof templateEngine.evaluate>[1]) =>
84+
templateEngine.evaluate<string>({ dialect: 'template', source }, ctx);
85+
86+
it('formats in the locale the context names', () => {
87+
expect(render({ extra: roots, locale: 'de-DE' })).toEqual({ ok: true, value: expected('de-DE') });
88+
expect(expected('de-DE')).not.toBe(expected('en-US'));
89+
});
90+
91+
it('a root named `locale` is a value a hole prints, not the formatter locale', () => {
92+
expect(render({ extra: { ...roots, locale: 'de-DE' } })).toEqual({
93+
ok: true,
94+
value: expected('en-US', 'de-DE'),
95+
});
96+
expect(render({ extra: { ...roots, locale: 'de-DE' }, locale: 'fr-FR' })).toEqual({
97+
ok: true,
98+
value: expected('fr-FR', 'de-DE'),
99+
});
100+
});
101+
102+
it('no locale, or an empty one, renders en-US as before', () => {
103+
expect(render({ extra: roots })).toEqual({ ok: true, value: expected('en-US') });
104+
expect(render({ extra: roots, locale: '' })).toEqual({ ok: true, value: expected('en-US') });
105+
});
106+
});

‎packages/formula/src/template-engine.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -272,10 +272,9 @@ export const templateEngine: DialectEngine = {
272272
if (!check.ok) return check as EvalResult<T>;
273273

274274
const scope = buildScope(ctx);
275-
const locale =
276-
(ctx.extra && typeof ctx.extra.locale === 'string' && ctx.extra.locale) ||
277-
(typeof (ctx as { locale?: string }).locale === 'string' && (ctx as { locale?: string }).locale) ||
278-
'en-US';
275+
// Formatter locale: the context's reserved `locale` channel only, never a
276+
// root — a root named `locale` is a value like any other (#26232).
277+
const locale = typeof ctx.locale === 'string' && ctx.locale !== '' ? ctx.locale : 'en-US';
279278
// Reference timezone for `datetime` rendering (ADR-0053 Phase 2). Unset →
280279
// Intl uses the runtime zone, matching pre-Phase-2 behavior.
281280
const timeZone = typeof ctx.timezone === 'string' ? ctx.timezone : undefined;
@@ -285,7 +284,7 @@ export const templateEngine: DialectEngine = {
285284
if (!parsed) return _match; // compile already validated; defensive
286285
const value = resolvePath(scope, parsed.path);
287286
if (parsed.filter) {
288-
return FORMATTERS[parsed.filter.name](value, parsed.filter.arg, locale as string, timeZone);
287+
return FORMATTERS[parsed.filter.name](value, parsed.filter.arg, locale, timeZone);
289288
}
290289
return baseString(value);
291290
});

‎packages/formula/src/template-formatters.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { templateEngine, TEMPLATE_FORMATTERS, formatValue } from './template-eng
44
function render(source: string, record: Record<string, unknown>, timezone?: string): string {
55
const r = templateEngine.evaluate<string>(
66
{ dialect: 'template', source },
7-
{ record, extra: { locale: 'en-US' }, ...(timezone ? { timezone } : {}) },
7+
{ record, locale: 'en-US', ...(timezone ? { timezone } : {}) },
88
);
99
if (!r.ok) throw new Error(r.error.message);
1010
return r.value;

‎packages/formula/src/types.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,19 @@ export interface EvalContext {
8282
* Defaults to `UTC` when unset. Calendar-day `date` rendering stays tz-naive.
8383
*/
8484
timezone?: string;
85+
/**
86+
* Locale (BCP-47 tag, e.g. `zh-CN`) the `template` dialect's formatters
87+
* render numbers, money, percents and dates in. Defaults to `en-US` when
88+
* unset or empty.
89+
*
90+
* A reserved channel, like {@link timezone}: it is NOT bound as a variable,
91+
* and nothing in {@link extra} or any other root sets it. A template's roots
92+
* are author-visible values (a bulk action's params, a flow's variables), so
93+
* a root named `locale` is just a value a hole can print — it used to also
94+
* set the formatter locale of the whole sentence (objectstack#26232). The
95+
* caller that knows the viewer's display locale passes it here.
96+
*/
97+
locale?: string;
8598
/**
8699
* Current authenticated subject (hook / action / view contexts).
87100
*

‎packages/services/service-automation/src/builtin/template.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,10 @@ export function textTemplateScope(variables: VariableMap): Record<string, unknow
102102
* Value→string is the engine's, defined per value (ADR-0032 §3): `null` /
103103
* absent renders nothing, an object or array renders as JSON, a `Date` as its
104104
* ISO text, and a formatter makes the rest explicit (`{{ amount | currency }}`,
105-
* `{{ due | date:iso }}`). A flow variable named `locale` is also the
106-
* formatters' locale — the engine reads its scope's `locale` for that.
105+
* `{{ due | date:iso }}`). The formatters render in the engine's default
106+
* `en-US`: a flow variable named `locale` is a value like any other, never the
107+
* formatters' locale (#26232 — the engine reads that from its own reserved
108+
* channel, not from a root).
107109
*
108110
* Absent in, absent out: a slot the author left unset — or one that renders
109111
* no text at all — returns `undefined`, so a screen falls back to its node

‎packages/services/service-automation/src/builtin/text-slot-template.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,13 @@ describe('#22110 — renderTextSlot, the one text renderer', () => {
267267
it('leaves a single-brace token as literal text — the doors refuse it before a run, so the renderer never reads it', () => {
268268
expect(renderTextSlot('Hello {record.name}', vars({ record: ACME }))).toBe('Hello {record.name}');
269269
});
270+
271+
it('a flow variable named `locale` is a value a hole prints, not the formatters\' locale (#26232)', () => {
272+
// Expected text from `Intl` itself, so a newer ICU in CI cannot drift it.
273+
const amount = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(1234567.5);
274+
expect(renderTextSlot('{{ amount | number:2 }} ({{ locale }})', vars({ amount: 1234567.5, locale: 'de-DE' })))
275+
.toBe(`${amount} (de-DE)`);
276+
});
270277
});
271278

272279
/** This package's `src` — the runtime whose `$` variables the spec judge lists. */

‎ui/packages/core/src/actions/ActionRunner.ts‎

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1283,6 +1283,7 @@ export class ActionRunner {
12831283
private paramCollectionHandler: ParamCollectionHandler | null;
12841284
private resultDialogHandler: ResultDialogHandler | null;
12851285
private translate: ((key: string, options: { defaultValue: string }) => string) | null;
1286+
private displayLocale: (() => string | undefined) | null;
12861287

12871288
/**
12881289
* Built-in dispatch, one entry per runnable action type.
@@ -1322,6 +1323,7 @@ export class ActionRunner {
13221323
this.paramCollectionHandler = null;
13231324
this.resultDialogHandler = null;
13241325
this.translate = null;
1326+
this.displayLocale = null;
13251327
}
13261328

13271329
/**
@@ -1341,6 +1343,20 @@ export class ActionRunner {
13411343
this.translate = translate;
13421344
}
13431345

1346+
/**
1347+
* Set where the runner reads the viewer's display locale (a BCP-47 tag) —
1348+
* the host's own, injected so this package resolves none. It is read when a
1349+
* copy template is filled, so a language switch reaches a runner built
1350+
* before it. The `template` formatters in `confirmText` and
1351+
* `successMessage` render in it (`{{ amount | currency }}`,
1352+
* `{{ due | date:long }}`), through the engine's reserved locale channel, so
1353+
* a root named `locale` never sets it (objectstack#26232). With none
1354+
* installed they format in `en-US`.
1355+
*/
1356+
setDisplayLocale(displayLocale: () => string | undefined): void {
1357+
this.displayLocale = displayLocale;
1358+
}
1359+
13441360
/**
13451361
* Set a custom confirmation handler (e.g., Shadcn AlertDialog).
13461362
*/
@@ -1811,7 +1827,11 @@ export class ActionRunner {
18111827
const successCopy = actionCopySource(action.successMessage);
18121828
if (successCopy !== undefined && successCopy.trim() !== '') {
18131829
return hasTemplateHoles(successCopy)
1814-
? fillTemplateHoles(successCopy, { result: payload, record: this.dispatchRecord(action) })
1830+
? fillTemplateHoles(
1831+
successCopy,
1832+
{ result: payload, record: this.dispatchRecord(action) },
1833+
this.displayLocale?.(),
1834+
)
18151835
: successCopy;
18161836
}
18171837
return this.runnerText(RUNNER_TEXT.completedSuccessfully);
@@ -1846,7 +1866,11 @@ export class ActionRunner {
18461866
const staticParams = params && typeof params === 'object' && !Array.isArray(params)
18471867
? Object.fromEntries(Object.entries(params).filter(([key]) => key !== '_rowRecord'))
18481868
: undefined;
1849-
return fillTemplateHoles(text, { record: this.dispatchRecord(action), params: staticParams });
1869+
return fillTemplateHoles(
1870+
text,
1871+
{ record: this.dispatchRecord(action), params: staticParams },
1872+
this.displayLocale?.(),
1873+
);
18501874
}
18511875

18521876
/**
@@ -2909,9 +2933,9 @@ export class ActionRunner {
29092933
/**
29102934
* A one-shot runner for {@link ActionRunner.execute}'s `callContext`
29112935
* (objectui#13063): this runner's context with `callContext` merged over it,
2912-
* and this runner's handlers, translator and registries, shared rather than
2913-
* copied, so the dispatch confirms, collects params, toasts and navigates
2914-
* exactly as this runner does.
2936+
* and this runner's handlers, translator, display locale and registries,
2937+
* shared rather than copied, so the dispatch confirms, collects params,
2938+
* toasts and navigates exactly as this runner does.
29152939
*
29162940
* Two keys follow the merge rather than the base:
29172941
*
@@ -2953,6 +2977,7 @@ export class ActionRunner {
29532977
scoped.paramCollectionHandler = this.paramCollectionHandler;
29542978
scoped.resultDialogHandler = this.resultDialogHandler;
29552979
scoped.translate = this.translate;
2980+
scoped.displayLocale = this.displayLocale;
29562981
return scoped;
29572982
}
29582983

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
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#26232 — a copy template's formatters render in the viewer's
11+
* display locale, and a root named `locale` never sets it.
12+
*
13+
* Measured before this card: `fillTemplateHoles` passed its roots as the
14+
* template engine's `extra`, and the engine read its formatter locale from
15+
* `extra.locale`. So a param named `locale` set the locale of every formatted
16+
* value in the sentence, and with no such param every viewer read `en-US`.
17+
* The locale now rides the engine's reserved channel: the host installs its
18+
* display locale on the runner (`setDisplayLocale`), and the filler passes it
19+
* apart from the roots.
20+
*
21+
* Expected strings come from `Intl` itself, so a newer ICU cannot drift them.
22+
*/
23+
import { describe, it, expect, vi } from 'vitest';
24+
import { ActionRunner, type ActionDef } from '../ActionRunner';
25+
import { fillTemplateHoles } from '../actionCopyTemplate';
26+
27+
const AMOUNT = 1234567.5;
28+
const money = (tag: string) => new Intl.NumberFormat(tag, { style: 'currency', currency: 'EUR' }).format(AMOUNT);
29+
30+
async function confirmTextFor(runner: ActionRunner, def: ActionDef, callContext?: object): Promise<unknown> {
31+
const confirm = vi.fn().mockResolvedValue(false);
32+
runner.setConfirmHandler(confirm);
33+
await runner.execute(def, callContext);
34+
expect(confirm).toHaveBeenCalledTimes(1);
35+
return confirm.mock.calls[0][0];
36+
}
37+
38+
describe('fillTemplateHoles keeps the formatter locale apart from the roots (objectstack#26232)', () => {
39+
it('a root named `locale` is a value a hole prints, not the formatter locale', () => {
40+
expect(money('de-DE')).not.toBe(money('en-US'));
41+
expect(fillTemplateHoles('{{ amount | currency:EUR }} ({{ locale }})', { amount: AMOUNT, locale: 'de-DE' }))
42+
.toBe(`${money('en-US')} (de-DE)`);
43+
});
44+
45+
it('formats in the locale the caller passes', () => {
46+
expect(fillTemplateHoles('{{ amount | currency:EUR }}', { amount: AMOUNT }, 'de-DE')).toBe(money('de-DE'));
47+
});
48+
});
49+
50+
describe('the runner fills its copy templates in the display locale it was given (objectstack#26232)', () => {
51+
const CONFIRM: ActionDef = {
52+
name: 'reprice',
53+
onClick: () => {},
54+
confirmText: 'Set {{ record.amount | currency:EUR }} ({{ params.locale }})?',
55+
params: { locale: 'fr-FR' },
56+
};
57+
const runner = () => new ActionRunner({ objectName: 'crm_deal', record: { amount: AMOUNT } });
58+
59+
it('CONTROL: with no display locale installed, the formatters render en-US as before', async () => {
60+
expect(await confirmTextFor(runner(), CONFIRM)).toBe(`Set ${money('en-US')} (fr-FR)?`);
61+
});
62+
63+
it('confirmText: the installed display locale is the formatter locale', async () => {
64+
const r = runner();
65+
r.setDisplayLocale(() => 'de-DE');
66+
expect(await confirmTextFor(r, CONFIRM)).toBe(`Set ${money('de-DE')} (fr-FR)?`);
67+
});
68+
69+
it('the display locale is read per fill, so a switch reaches a runner built before it', async () => {
70+
const r = runner();
71+
let current = 'de-DE';
72+
r.setDisplayLocale(() => current);
73+
expect(await confirmTextFor(r, CONFIRM)).toBe(`Set ${money('de-DE')} (fr-FR)?`);
74+
current = 'ja-JP';
75+
expect(await confirmTextFor(r, CONFIRM)).toBe(`Set ${money('ja-JP')} (fr-FR)?`);
76+
});
77+
78+
it('a dispatch with a callContext keeps the display locale', async () => {
79+
const r = new ActionRunner({ objectName: 'crm_deal' });
80+
r.setDisplayLocale(() => 'de-DE');
81+
expect(await confirmTextFor(r, CONFIRM, { record: { amount: AMOUNT } })).toBe(`Set ${money('de-DE')} (fr-FR)?`);
82+
});
83+
84+
it('successMessage: formats `result` in the display locale', async () => {
85+
const r = runner();
86+
const toast = vi.fn();
87+
r.setToastHandler(toast);
88+
r.setDisplayLocale(() => 'de-DE');
89+
r.registerHandler('script', async () => ({ success: true, data: { total: AMOUNT, locale: 'fr-FR' } }));
90+
await r.execute({
91+
type: 'script',
92+
name: 'reprice',
93+
successMessage: { dialect: 'template', source: 'Total {{ result.total | currency:EUR }} ({{ result.locale }})' },
94+
});
95+
expect(toast.mock.calls[0][0]).toBe(`Total ${money('de-DE')} (fr-FR)`);
96+
});
97+
});

‎ui/packages/core/src/actions/actionCopyTemplate.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,8 +77,19 @@ export function hasTemplateHoles(text: string): boolean {
7777
* unbalanced delimiter, logic inside a hole) is returned as written: the
7878
* publish gate refuses it on the server side, and the user still reads the
7979
* author's sentence rather than nothing.
80+
*
81+
* `locale` is the viewer's display locale (a BCP-47 tag) the formatters render
82+
* in, passed by the caller that already has it — ⛔ never resolved here. It
83+
* rides the engine's reserved `locale` channel, apart from `roots`, so a root
84+
* named `locale` (a param of that name) is a value a hole prints, not the
85+
* locale of the whole sentence (objectstack#26232). Omitted, the engine
86+
* formats in `en-US`.
8087
*/
81-
export function fillTemplateHoles(source: string, roots: Record<string, unknown>): string {
82-
const filled = templateEngine.evaluate<string>({ dialect: 'template', source }, { extra: roots });
88+
export function fillTemplateHoles(
89+
source: string,
90+
roots: Record<string, unknown>,
91+
locale?: string,
92+
): string {
93+
const filled = templateEngine.evaluate<string>({ dialect: 'template', source }, { extra: roots, locale });
8394
return filled.ok && typeof filled.value === 'string' ? filled.value : source;
8495
}

‎ui/packages/react/src/context/ActionContext.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ import {
2727
type ParamCollectionHandler,
2828
type ResultDialogHandler,
2929
} from '@object-ui/core';
30-
import { useActionRunnerTranslator } from './actionRunnerTranslator.js';
30+
import { useActionRunnerDisplayLocale, useActionRunnerTranslator } from './actionRunnerTranslator.js';
3131
import { usePredicateScope } from '../hooks/useExpression.js';
3232

3333
export interface ActionProviderProps {
@@ -100,6 +100,8 @@ export const ActionProvider: React.FC<ActionProviderProps> = ({
100100
const [result, setResult] = useState<ActionResult | null>(null);
101101
// The runner's own copy (the generic success toast) in the session's language.
102102
const translate = useActionRunnerTranslator();
103+
// Its copy templates' formatters in the viewer's display locale (#26232).
104+
const displayLocale = useActionRunnerDisplayLocale();
103105

104106
const runner = useMemo(() => {
105107
// Normalize the evaluator scope so predicates can use *either* flat
@@ -117,6 +119,7 @@ export const ActionProvider: React.FC<ActionProviderProps> = ({
117119
} as ActionCtx;
118120
const r = new ActionRunner(normalizedContext);
119121
r.setTranslator(translate);
122+
r.setDisplayLocale(displayLocale);
120123
if (onConfirm) r.setConfirmHandler(onConfirm);
121124
if (onToast) r.setToastHandler(onToast);
122125
if (onModal) r.setModalHandler(onModal);

0 commit comments

Comments
 (0)