From a672729ae3b34270e8e6eede6f3988c5a67c411d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 04:10:55 +0000 Subject: [PATCH 01/13] feat(fields): show a quantity with its unit label and display decimals (#35490) A number field declaring unitConfig draws its unit beside the number in grid, list, form and detail, through one resolver in @object-ui/core and one formatter in @object-ui/fields. Standard codes take the platform's per-locale label and their organization's sys_standard_unit_setting row; organization codes take their sys_unit label and decimal places. The field's scale is the ceiling (ADR-0158 L4). A retired or unreadable unit shows the bare code. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXM7nqtiQ3M9JqGAqL --- .changeset/35490-quantity-unit-display.md | 22 ++ .../form-quantity-record-35490.test.tsx | 51 ++++ .../components/src/renderers/form/form.tsx | 10 + ui/packages/core/src/index.ts | 3 + .../__tests__/unit-display-35490.test.ts | 153 ++++++++++++ ui/packages/core/src/utils/unit-display.ts | 231 ++++++++++++++++++ .../__tests__/quantityDisplay-35490.test.tsx | 184 ++++++++++++++ ui/packages/fields/src/index.tsx | 18 +- .../fields/src/widgets/NumberField.tsx | 100 +++++--- .../fields/src/widgets/QuantityText.tsx | 74 ++++++ .../fields/src/widgets/quantity-format.ts | 122 +++++++++ .../fields/src/widgets/useQuantityUnit.ts | 130 ++++++++++ ui/packages/i18n/src/locales/ar.ts | 47 ++++ ui/packages/i18n/src/locales/de.ts | 47 ++++ ui/packages/i18n/src/locales/en.ts | 47 ++++ ui/packages/i18n/src/locales/es.ts | 47 ++++ ui/packages/i18n/src/locales/fr.ts | 47 ++++ ui/packages/i18n/src/locales/ja.ts | 47 ++++ ui/packages/i18n/src/locales/ko.ts | 47 ++++ ui/packages/i18n/src/locales/pt-BR.ts | 47 ++++ ui/packages/i18n/src/locales/ru.ts | 47 ++++ ui/packages/i18n/src/locales/zh-Hans.ts | 47 ++++ ui/packages/i18n/src/locales/zh-Hant.ts | 47 ++++ .../plugin-detail/src/RecordDetailPanel.tsx | 3 + ui/packages/plugin-detail/src/RelatedList.tsx | 18 ++ .../quantityUnitRelay-35490.test.tsx | 118 +++++++++ .../plugin-detail/src/fieldEnrichment.ts | 4 + .../__tests__/gridQuantityUnit-35490.test.tsx | 94 +++++++ .../src/objectGridGenerateColumns.tsx | 8 + .../plugin-grid/src/objectGridRowLoad.ts | 14 +- ui/packages/plugin-list/src/ListView.tsx | 11 +- .../ListView.quantityUnit-35490.test.tsx | 82 +++++++ ui/packages/types/src/field-types.ts | 15 ++ 33 files changed, 1940 insertions(+), 42 deletions(-) create mode 100644 .changeset/35490-quantity-unit-display.md create mode 100644 ui/packages/components/src/renderers/form/__tests__/form-quantity-record-35490.test.tsx create mode 100644 ui/packages/core/src/utils/__tests__/unit-display-35490.test.ts create mode 100644 ui/packages/core/src/utils/unit-display.ts create mode 100644 ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx create mode 100644 ui/packages/fields/src/widgets/QuantityText.tsx create mode 100644 ui/packages/fields/src/widgets/quantity-format.ts create mode 100644 ui/packages/fields/src/widgets/useQuantityUnit.ts create mode 100644 ui/packages/plugin-detail/src/__tests__/quantityUnitRelay-35490.test.tsx create mode 100644 ui/packages/plugin-grid/src/__tests__/gridQuantityUnit-35490.test.tsx create mode 100644 ui/packages/plugin-list/src/__tests__/ListView.quantityUnit-35490.test.tsx diff --git a/.changeset/35490-quantity-unit-display.md b/.changeset/35490-quantity-unit-display.md new file mode 100644 index 00000000000..7392d998fef --- /dev/null +++ b/.changeset/35490-quantity-unit-display.md @@ -0,0 +1,22 @@ +--- +'@object-ui/core': patch +'@object-ui/fields': patch +'@object-ui/types': patch +'@object-ui/i18n': patch +'@object-ui/components': patch +'@object-ui/plugin-grid': patch +'@object-ui/plugin-list': patch +'@object-ui/plugin-detail': patch +--- + +feat(fields): a quantity displays with its unit's label and display decimal places in grid, form and detail (ADR-0158 R1 display) + +Clause-②: no +Metadata-protocol: none + +A `number` field that declares `unitConfig` now draws its unit beside the number on every face: grid and list cells, the record page (sections, highlights, the quick-look panel, related lists), and the form, both read-only and beside the edited box. A `fixed` quantity shows its one unit; a `record` quantity shows the unit its row's code field holds, and the list, grid and related-list reads fetch that field (and the row's organization) even when no column shows it. A `text` field declaring `unitConfig: { unitMode: 'code' }` shows the code's label. + +- A standard code (`KGM`, `H87`, …) shows the platform's label in the reader's locale, from a new `units.standard` table in every language pack; an organization code shows its `sys_unit` label. +- Decimal places: a standard code takes its organization's `sys_standard_unit_setting` row, an organization code its `sys_unit.decimal_places`. The row is the record's own organization's, never merely the first one returned. The field's `scale` is the ceiling (ADR-0158 L4), and nothing is rounded at write: footers, exports and the API keep the exact value. +- A retired organization unit, and a unit whose row the reader may not read (an external member holds no `sys_unit` read), show the bare code, never an error. +- One resolver (`resolveQuantityUnit` in `@object-ui/core`) and one formatter (`formatQuantity` in `@object-ui/fields`) serve every face. diff --git a/ui/packages/components/src/renderers/form/__tests__/form-quantity-record-35490.test.tsx b/ui/packages/components/src/renderers/form/__tests__/form-quantity-record-35490.test.tsx new file mode 100644 index 00000000000..7ea8407f3c9 --- /dev/null +++ b/ui/packages/components/src/renderers/form/__tests__/form-quantity-record-35490.test.tsx @@ -0,0 +1,51 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35490 (ADR-0158 R1 display): a `record`-mode quantity in a form + * shows the unit its record's code field holds, so the number widget is handed + * the live form record (`dependentValues`), as a record-mode amount is. + */ + +import { describe, it, expect, beforeAll } from 'vitest'; +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import { ComponentRegistry } from '@object-ui/core'; +import '../../../renderers'; + +function NumberProbe(props: any) { + return
{JSON.stringify(props.dependentValues ?? null)}
; +} + +beforeAll(() => { + ComponentRegistry.register('field:number', NumberProbe, { namespace: 'test' }); +}, 30000); + +describe('form renderer — a quantity gets the live record (objectstack#35490)', () => { + it("feeds the number widget the record, so it follows the unit field's edits", async () => { + const Form = ComponentRegistry.get('form')!; + render( +
, + ); + // The record itself, not `null`: the widget is on the channel before any edit. + expect(JSON.parse(screen.getByTestId('number-probe').textContent!)).toHaveProperty('unit_code'); + fireEvent.change(screen.getByLabelText(/unit/i), { target: { value: 'GRM' } }); + await waitFor(() => { + expect(JSON.parse(screen.getByTestId('number-probe').textContent!)).toMatchObject({ unit_code: 'GRM' }); + }); + }); +}); diff --git a/ui/packages/components/src/renderers/form/form.tsx b/ui/packages/components/src/renderers/form/form.tsx index 00f6a5df323..41832589aae 100644 --- a/ui/packages/components/src/renderers/form/form.tsx +++ b/ui/packages/components/src/renderers/form/form.tsx @@ -1387,6 +1387,14 @@ function renderFieldDescription( */ const RECORD_CURRENCY_WIDGET_TYPES = new Set(['currency', 'formula', 'summary']); +/** + * Widget keys whose display reads a sibling field's value for a quantity's + * unit (ADR-0158): a `record`-mode quantity shows the unit its record's code + * field holds, and its organization picks the unit's display decimal places. + * `NumberField` takes `dependentValues` by name, so it never reaches the DOM. + */ +const QUANTITY_WIDGET_TYPES = new Set(['number']); + function stripRegisteredFieldProps(type: string, props: RenderFieldProps): RenderFieldProps { const { dataSource, @@ -1438,6 +1446,8 @@ function stripRegisteredFieldProps(type: string, props: RenderFieldProps): Rende // A record-mode amount's symbol and decimals follow the code the user picks // in its sibling select, so the amount box needs the live record too. ...(RECORD_CURRENCY_WIDGET_TYPES.has(normalizedType) ? { dependentValues } : {}), + // A record-mode quantity's unit follows the code in its sibling field. + ...(QUANTITY_WIDGET_TYPES.has(normalizedType) ? { dependentValues } : {}), // Only the widgets that report unparseable text read it; every other one // would spread an unknown handler onto its DOM (objectstack#27483). ...(INVALID_INPUT_REPORTING_WIDGET_TYPES.has(normalizedType) ? { onInvalidInputChange } : {}), diff --git a/ui/packages/core/src/index.ts b/ui/packages/core/src/index.ts index 15e0b079b0a..2f9a4571208 100644 --- a/ui/packages/core/src/index.ts +++ b/ui/packages/core/src/index.ts @@ -383,6 +383,9 @@ export * from './utils/parent-scope.js'; // The other half of a view's field appetite: the fields its PREDICATES read, // which the column-derived `$select` never asked the server for. export * from './utils/predicate-fields.js'; +// Which unit a quantity is in and what it displays as (ADR-0158): the ONE +// resolution every quantity face shares. +export * from './utils/unit-display.js'; export * from './utils/withheld-fields.js'; // The THIRD source of a view's field appetite: the fields it GROUPS BY. The // spec's `grouping` block is a sibling of `columns`, not a subset, so a grid diff --git a/ui/packages/core/src/utils/__tests__/unit-display-35490.test.ts b/ui/packages/core/src/utils/__tests__/unit-display-35490.test.ts new file mode 100644 index 00000000000..c73713775c7 --- /dev/null +++ b/ui/packages/core/src/utils/__tests__/unit-display-35490.test.ts @@ -0,0 +1,153 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35490 (ADR-0158 R1 display): which unit a quantity is in and + * what it displays as, resolved once for every face. + */ + +import { describe, it, expect } from 'vitest'; +import { + declaresQuantityUnit, + pickRowForOrganization, + quantityUnitCode, + quantityUnitReadField, + resolveQuantityUnit, + shownQuantityUnitReads, +} from '../unit-display'; + +const FIXED = { type: 'number', unitConfig: { unitMode: 'fixed', unit: 'KGM' } }; +const RECORD = { type: 'number', unitConfig: { unitMode: 'record', unitField: 'unit_code' } }; +const CODE = { type: 'text', unitConfig: { unitMode: 'code' } }; + +describe('quantityUnitCode — which code a value is in', () => { + it('reads a fixed unit from the field, whatever the record', () => { + expect(quantityUnitCode(FIXED, { unit_code: 'GRM' })).toBe('KGM'); + expect(quantityUnitCode(FIXED)).toBe('KGM'); + }); + + it("reads a record-mode unit from the record's unit field, exactly as stored", () => { + expect(quantityUnitCode(RECORD, { unit_code: 'BOX_12' })).toBe('BOX_12'); + expect(quantityUnitCode(RECORD, { unit_code: 'kgm' })).toBe('kgm'); + }); + + it('answers none for a blank code, or a caller with no record', () => { + expect(quantityUnitCode(RECORD, { unit_code: '' })).toBeUndefined(); + expect(quantityUnitCode(RECORD, { unit_code: ' ' })).toBeUndefined(); + expect(quantityUnitCode(RECORD, { unit_code: null })).toBeUndefined(); + expect(quantityUnitCode(RECORD)).toBeUndefined(); + }); + + it("reads a unit-code field's own value (Open item 8)", () => { + expect(quantityUnitCode(CODE, {}, 'H87')).toBe('H87'); + }); + + it('answers none for a field with no unit, or a declaration on another type', () => { + expect(quantityUnitCode({ type: 'number' }, { unit_code: 'KGM' })).toBeUndefined(); + expect(quantityUnitCode({ type: 'currency', unitConfig: { unitMode: 'fixed', unit: 'KGM' } })).toBeUndefined(); + expect(quantityUnitCode({ type: 'text', unitConfig: { unitMode: 'fixed', unit: 'KGM' } })).toBeUndefined(); + }); + + it('names the sibling a projection must fetch, under record mode only', () => { + expect(quantityUnitReadField(RECORD)).toBe('unit_code'); + expect(quantityUnitReadField(FIXED)).toBeUndefined(); + expect(quantityUnitReadField(CODE)).toBeUndefined(); + expect(declaresQuantityUnit(FIXED) && declaresQuantityUnit(RECORD) && declaresQuantityUnit(CODE)).toBe(true); + expect(declaresQuantityUnit({ type: 'number' })).toBe(false); + }); +}); + +describe("pickRowForOrganization — the record's organization's row, never the first one returned", () => { + const rows = [ + { code: 'KGM', decimal_places: 3, organization_id: 'org_a' }, + { code: 'KGM', decimal_places: 0, organization_id: 'org_b' }, + ]; + + it("picks the record's organization under the group posture, wherever its row sits", () => { + expect(pickRowForOrganization(rows, 'KGM', { organization_id: 'org_b' })?.decimal_places).toBe(0); + expect(pickRowForOrganization(rows, 'KGM', { organization_id: 'org_a' })?.decimal_places).toBe(3); + expect(pickRowForOrganization([...rows].reverse(), 'KGM', { organization_id: 'org_a' })?.decimal_places).toBe(3); + }); + + it("answers none for an organization with no row, rather than another organization's", () => { + expect(pickRowForOrganization(rows, 'KGM', { organization_id: 'org_c' })).toBeUndefined(); + }); + + it('answers none when the organization is unknown and two organizations have a row', () => { + expect(pickRowForOrganization(rows, 'KGM', {})).toBeUndefined(); + expect(pickRowForOrganization(rows, 'KGM')).toBeUndefined(); + }); + + it('answers the only row when the organization is unknown (the isolated posture reads one)', () => { + expect(pickRowForOrganization([rows[0]], 'KGM', {})?.decimal_places).toBe(3); + }); + + it('matches a record and a row that both carry no organization (the single posture)', () => { + const single = [{ code: 'KGM', decimal_places: 2, organization_id: null }]; + expect(pickRowForOrganization(single, 'KGM', { organization_id: null })?.decimal_places).toBe(2); + expect(pickRowForOrganization(single, 'KGM', { organization_id: 'org_a' })).toBeUndefined(); + }); +}); + +describe('resolveQuantityUnit — label and decimal places, in the order of lookup', () => { + const catalog = { + organizationUnits: [ + { code: 'BOX_12', label: 'Box of 12', decimal_places: 0, retired: false, organization_id: 'org_a' }, + { code: 'JIN1', label: 'Jin', decimal_places: 2, retired: true, organization_id: 'org_a' }, + ], + standardUnitSettings: [{ code: 'GRM', decimal_places: 3, organization_id: 'org_a' }], + }; + const rec = { organization_id: 'org_a' }; + + it("gives a standard code the platform label and its organization's setting", () => { + expect(resolveQuantityUnit('GRM', catalog, rec, 'g')).toEqual({ code: 'GRM', standard: true, label: 'g', decimals: 3 }); + }); + + it('gives a standard code with no setting no decimal places of its own', () => { + expect(resolveQuantityUnit('KGM', catalog, rec, 'kg')).toEqual({ code: 'KGM', standard: true, label: 'kg' }); + }); + + it("gives an organization code its own row's label and decimal places", () => { + expect(resolveQuantityUnit('BOX_12', catalog, rec)).toEqual({ code: 'BOX_12', standard: false, label: 'Box of 12', decimals: 0 }); + }); + + it('shows a deleted (retired) organization unit as the bare code (L1)', () => { + expect(resolveQuantityUnit('JIN1', catalog, rec)).toEqual({ code: 'JIN1', standard: false }); + }); + + it('shows an organization unit the reader cannot read as the bare code (an external member)', () => { + const { organizationUnits: _withheld, ...unread } = catalog; + expect(resolveQuantityUnit('BOX_12', unread, rec)).toEqual({ code: 'BOX_12', standard: false }); + }); + + it("does not take another organization's unit row", () => { + expect(resolveQuantityUnit('BOX_12', catalog, { organization_id: 'org_b' })).toEqual({ code: 'BOX_12', standard: false }); + }); + + it('ignores a decimal-places value outside 0..12', () => { + const odd = { standardUnitSettings: [{ code: 'GRM', decimal_places: 13, organization_id: 'org_a' }] }; + expect(resolveQuantityUnit('GRM', odd, rec, 'g')).toEqual({ code: 'GRM', standard: true, label: 'g' }); + }); +}); + +describe('shownQuantityUnitReads — what a projection fetches for shown quantity columns', () => { + const fields = { qty: RECORD, weight: FIXED, unit_code: { type: 'text' }, name: { type: 'text' } }; + + it("asks for a record-mode quantity's code field and the row's organization", () => { + expect(shownQuantityUnitReads(['name', 'qty'], fields)).toEqual(['unit_code', 'organization_id']); + }); + + it('asks for the organization alone for a fixed-unit quantity', () => { + expect(shownQuantityUnitReads([{ field: 'weight' }], fields)).toEqual(['organization_id']); + }); + + it('asks for nothing when no shown column draws a unit, or the quantity is hidden', () => { + expect(shownQuantityUnitReads(['name'], fields)).toEqual([]); + expect(shownQuantityUnitReads([{ field: 'qty', hidden: true }], fields)).toEqual([]); + }); +}); diff --git a/ui/packages/core/src/utils/unit-display.ts b/ui/packages/core/src/utils/unit-display.ts new file mode 100644 index 00000000000..8616dee9c2c --- /dev/null +++ b/ui/packages/core/src/utils/unit-display.ts @@ -0,0 +1,231 @@ +/** + * ObjectUI — quantity unit display resolution + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * Which unit a quantity is in, and what that unit displays as: its label and + * its display decimal places (ADR-0158 U4, U6, L1, L4, Open item 10). + * + * Pure, with no React and no I/O, so every face that draws a quantity — a + * grid cell, a read-only form field, a detail row — resolves it through the + * same functions and cannot drift. The rows it resolves against are read by + * the caller (`@object-ui/fields`' `useQuantityUnit`), which owns the data + * source and the refusal classification. + * + * The order of lookup for a code: + * - a standard code (`STANDARD_UNITS`, U1) takes the platform's label for it + * and the decimal places of its `sys_standard_unit_setting` row (Open item + * 10, ruled A), when the organization has set one; + * - an organization code takes the label and `decimal_places` of its + * `sys_unit` row (U3, L2); + * - anything else — a retired or deleted organization unit (L1), a unit row + * the reader may not read, or a code no row names — is the bare code, with + * no label and no decimal places of its own. + */ + +import { standardUnitOf } from '@objectstack/spec/data'; +import { columnIdentity } from './column-identity.js'; + +/** The part of a field definition the resolution reads. */ +export interface UnitBearingField { + type?: string; + unitConfig?: unknown; +} + +/** One `sys_unit` row, as far as the display reads it. */ +export interface OrganizationUnitRow { + code?: unknown; + label?: unknown; + decimal_places?: unknown; + retired?: unknown; + organization_id?: unknown; +} + +/** One `sys_standard_unit_setting` row, as far as the display reads it. */ +export interface StandardUnitSettingRow { + code?: unknown; + decimal_places?: unknown; + organization_id?: unknown; +} + +/** + * The rows a reader could see. `undefined` for a table means it was not read + * (still in flight, refused, or no data source): its codes then resolve as if + * no row named them. + */ +export interface UnitCatalog { + organizationUnits?: readonly OrganizationUnitRow[]; + standardUnitSettings?: readonly StandardUnitSettingRow[]; +} + +/** What a quantity's unit displays as. */ +export interface ResolvedUnit { + /** The stored code, exactly as stored. */ + code: string; + /** The label to show beside the number; absent ⇒ the bare code is shown. */ + label?: string; + /** The unit's display decimal places (U6); absent ⇒ the field's own width. */ + decimals?: number; + /** Whether the code is one of the standard table's (U1). */ + standard: boolean; +} + +const isBlank = (v: unknown): boolean => v == null || (typeof v === 'string' && v.trim() === ''); + +/** + * The unit code a value of `field` is in, read off `record` where the field + * points at a sibling, or `undefined` when there is none to show. + * + * - `number` with `unitConfig: { unitMode: 'fixed', unit }` → `unit`; + * - `number` with `unitConfig: { unitMode: 'record', unitField }` → the + * record's `unitField` value, or `undefined` when the record holds none (a + * caller with no record, such as a footer over many rows, gets none); + * - `text` with `unitConfig: { unitMode: 'code' }` → the field's own `value`. + * + * The code is returned exactly as stored (U4: exact uppercase); it is never + * trimmed or case-folded into a code the record does not hold. + */ +export function quantityUnitCode( + field: UnitBearingField | null | undefined, + record?: Readonly> | null, + value?: unknown, +): string | undefined { + const config = field?.unitConfig; + if (config === null || typeof config !== 'object') return undefined; + const { unitMode, unit, unitField } = config as { unitMode?: unknown; unit?: unknown; unitField?: unknown }; + let code: unknown; + if (field?.type === 'number' && unitMode === 'fixed') code = unit; + else if (field?.type === 'number' && unitMode === 'record' && typeof unitField === 'string' && unitField !== '') { + code = record?.[unitField]; + } else if (field?.type === 'text' && unitMode === 'code') code = value; + return typeof code === 'string' && !isBlank(code) ? code : undefined; +} + +/** + * The sibling field a quantity's code is read from, for a host that builds a + * projection (`$select`) and must fetch it with the row: `unitField` under + * `record` mode, `undefined` otherwise. + */ +export function quantityUnitReadField(field: UnitBearingField | null | undefined): string | undefined { + const config = field?.unitConfig; + if (field?.type !== 'number' || config === null || typeof config !== 'object') return undefined; + const { unitMode, unitField } = config as { unitMode?: unknown; unitField?: unknown }; + return unitMode === 'record' && typeof unitField === 'string' && unitField !== '' ? unitField : undefined; +} + +/** Whether `field` declares a unit the display draws (a quantity, or a unit-code field). */ +export function declaresQuantityUnit(field: UnitBearingField | null | undefined): boolean { + const config = field?.unitConfig; + if (config === null || typeof config !== 'object') return false; + const mode = (config as { unitMode?: unknown }).unitMode; + return field?.type === 'number' ? mode === 'fixed' || mode === 'record' : field?.type === 'text' && mode === 'code'; +} + +/** + * The organization a row belongs to, normalised so that "no stamp" is one + * value: under the `single` tenancy posture rows carry no organization, and a + * record and a setting that both carry none belong together. + */ +const organizationOf = (row: { organization_id?: unknown } | null | undefined): string | null => + typeof row?.organization_id === 'string' && row.organization_id !== '' ? row.organization_id : null; + +/** + * The row of `code` that belongs to the record's organization, never merely + * the first row returned (note 7180167601 on objectstack#35490): under the + * `group` posture a member reads one row per organization they belong to. + * + * `record` decides. When it carries `organization_id` (a stamp, or an explicit + * `null` under `single`), only the row of that organization answers. When it + * does not carry the key at all, the organization is unknown, and only a code + * with exactly one readable row answers: guessing between two organizations' + * rows would show one organization's setting on another's record. + */ +export function pickRowForOrganization( + rows: readonly R[] | undefined, + code: string, + record?: Readonly> | null, +): R | undefined { + if (!rows) return undefined; + const candidates = rows.filter((row) => row?.code === code); + if (candidates.length === 0) return undefined; + if (record && Object.prototype.hasOwnProperty.call(record, 'organization_id')) { + const organization = organizationOf(record as { organization_id?: unknown }); + return candidates.find((row) => organizationOf(row) === organization); + } + return candidates.length === 1 ? candidates[0] : undefined; +} + +/** A whole number of decimal places from 0 to 12 (`UNIT_DECIMAL_PLACES_MAX`), or `undefined`. */ +function decimalPlaces(value: unknown): number | undefined { + const n = typeof value === 'string' && value.trim() !== '' ? Number(value) : value; + return typeof n === 'number' && Number.isInteger(n) && n >= 0 && n <= 12 ? n : undefined; +} + +/** + * What `code` displays as on `record`, read against the rows in `catalog`. + * + * `standardLabel` is the platform's label for a standard code in the reader's + * locale (2A); a caller with none passes `undefined` and the code is shown. + * + * A retired organization unit resolves to the bare code with no decimal + * places (L1: "show the code without a label"), and so does a unit whose row + * the reader cannot see — an external member holds no `sys_unit` read + * (comment 7030066814 on objectstack#35490). + */ +export function resolveQuantityUnit( + code: string, + catalog: UnitCatalog, + record?: Readonly> | null, + standardLabel?: string, +): ResolvedUnit { + if (standardUnitOf(code)) { + const setting = pickRowForOrganization(catalog.standardUnitSettings, code, record); + const decimals = decimalPlaces(setting?.decimal_places); + return { + code, + standard: true, + ...(standardLabel ? { label: standardLabel } : {}), + ...(decimals !== undefined ? { decimals } : {}), + }; + } + const row = pickRowForOrganization(catalog.organizationUnits, code, record); + if (!row || row.retired === true) return { code, standard: false }; + const label = typeof row.label === 'string' && row.label.trim() !== '' ? row.label : undefined; + const decimals = decimalPlaces(row.decimal_places); + return { + code, + standard: false, + ...(label ? { label } : {}), + ...(decimals !== undefined ? { decimals } : {}), + }; +} + +/** + * What the shown quantity columns need on their rows (ADR-0158), for a host + * that builds a projection: each `record`-mode quantity's `unitField`, and + * `organization_id` once when any shown column draws a unit, since the + * organization picks a unit's setting row ({@link pickRowForOrganization}). + * A column authored `hidden: true` pulls nothing. The host still applies its + * own gates (a declared field, one the principal may read) to the output. + */ +export function shownQuantityUnitReads( + columns: unknown, + fields: Readonly> | null | undefined, +): string[] { + if (!Array.isArray(columns) || !fields || typeof fields !== 'object') return []; + const out = new Set(); + for (const entry of columns) { + if (entry && typeof entry === 'object' && (entry as { hidden?: unknown }).hidden === true) continue; + const name = columnIdentity(entry); + const def = name ? (fields[name] as UnitBearingField | undefined) : undefined; + if (!declaresQuantityUnit(def)) continue; + const read = quantityUnitReadField(def); + if (read) out.add(read); + out.add('organization_id'); + } + return [...out]; +} diff --git a/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx b/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx new file mode 100644 index 00000000000..a930c23f7f5 --- /dev/null +++ b/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx @@ -0,0 +1,184 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35490 (ADR-0158 R1 display): a quantity renders with its unit's + * label and display decimal places on every face. The grid cell and the + * detail row are `getCellRenderer('number')` handed the row + * (`dependentValues`, as `generateColumns` and `DetailSection` hand it); the + * form is `NumberField`, read-only and edited, handed the form's record. + * + * Covers the card's named cases: record mode and fixed mode on all three + * faces; a deleted org unit and an external member's org unit show the bare + * code; the setting row is the record's organization's; and L4's clamp (the + * field's `scale` is the ceiling). + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import React from 'react'; +import { render, cleanup, screen, waitFor } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { SchemaRendererContext } from '@object-ui/react'; +import { I18nProvider } from '@object-ui/i18n'; +import { getCellRenderer } from '../index'; +import { NumberField } from '../widgets/NumberField'; +import { formatQuantity, quantityDisplayPlaces } from '../widgets/quantity-format'; + +afterEach(cleanup); + +const text = (s: string | null | undefined) => (s ?? '').replace(/ /g, ' '); + +const ORG_UNITS = [ + { code: 'BOX_12', label: 'Box of 12', decimal_places: 1, retired: false, organization_id: 'org_a' }, + { code: 'JIN1', label: 'Jin', decimal_places: 2, retired: true, organization_id: 'org_a' }, +]; +const SETTINGS = [ + { code: 'GRM', decimal_places: 3, organization_id: 'org_a' }, + { code: 'GRM', decimal_places: 0, organization_id: 'org_b' }, + { code: 'KGM', decimal_places: 0, organization_id: 'org_a' }, +]; + +/** A data source answering the two unit tables; `refuse` names tables it answers 403 for. */ +function unitSource(refuse: string[] = []) { + const calls: string[] = []; + return { + calls, + async find(resource: string) { + calls.push(resource); + if (refuse.includes(resource)) throw Object.assign(new Error('Forbidden'), { status: 403 }); + if (resource === 'sys_unit') return { data: ORG_UNITS }; + if (resource === 'sys_standard_unit_setting') return { data: SETTINGS }; + return { data: [] }; + }, + }; +} + +const RECORD_QTY = { name: 'qty', type: 'number', unitConfig: { unitMode: 'record', unitField: 'unit_code' } } as any; +const FIXED_QTY = { name: 'weight', type: 'number', unitConfig: { unitMode: 'fixed', unit: 'KGM' } } as any; + +type Face = 'grid' | 'detail' | 'form'; + +function draw(face: Face, field: any, value: number, record: Record, ds: unknown) { + const Cell = getCellRenderer('number'); + const body = + face === 'form' ? ( + {}} field={field} dependentValues={record} readonly /> + ) : ( + + ); + return render( + +
{body}
+
, + ); +} +const faceText = () => text(screen.getByTestId('face').textContent); + +describe.each(['grid', 'detail', 'form'])('the %s face', (face) => { + it("draws a record-mode quantity with its row's org unit label and decimal places", async () => { + draw(face, RECORD_QTY, 4, { unit_code: 'BOX_12', organization_id: 'org_a' }, unitSource()); + await waitFor(() => expect(faceText()).toBe('4.0 Box of 12')); + }); + + it("draws a fixed-mode quantity with the standard label and its organization's setting", async () => { + draw(face, FIXED_QTY, 1234.5, { organization_id: 'org_a' }, unitSource()); + await waitFor(() => expect(faceText()).toBe('1,235 kg')); + }); + + it('draws a deleted (retired) org unit as the bare code, at the field width', async () => { + const ds = unitSource(); + draw(face, RECORD_QTY, 2.5, { unit_code: 'JIN1', organization_id: 'org_a' }, ds); + await waitFor(() => expect(ds.calls).toContain('sys_unit')); + await waitFor(() => expect(faceText()).toBe('2.5 JIN1')); + }); + + it('draws an org unit as the bare code for an external member, who may not read sys_unit', async () => { + const ds = unitSource(['sys_unit']); + draw(face, RECORD_QTY, 4, { unit_code: 'BOX_12', organization_id: 'org_a' }, ds); + await waitFor(() => expect(ds.calls).toContain('sys_unit')); + expect(faceText()).toBe('4 BOX_12'); + expect(screen.queryByRole('alert')).toBeNull(); + }); + + it("takes the decimal places of the record's own organization's row", async () => { + draw(face, RECORD_QTY, 1.5, { unit_code: 'GRM', organization_id: 'org_b' }, unitSource()); + await waitFor(() => expect(faceText()).toBe('2 g')); + cleanup(); + draw(face, RECORD_QTY, 1.5, { unit_code: 'GRM', organization_id: 'org_a' }, unitSource()); + await waitFor(() => expect(faceText()).toBe('1.500 g')); + }); + + it("never shows more places than the field's scale (L4)", async () => { + draw(face, { ...RECORD_QTY, scale: 2 }, 1.5, { unit_code: 'GRM', organization_id: 'org_a' }, unitSource()); + await waitFor(() => expect(faceText()).toBe('1.50 g')); + }); + + it('draws a bare number when the row names no unit', async () => { + draw(face, RECORD_QTY, 7, { unit_code: '', organization_id: 'org_a' }, unitSource()); + expect(faceText()).toBe('7'); + }); +}); + +describe('the edited form box', () => { + it('names the unit beside the input', async () => { + render( + + {}} field={RECORD_QTY} dependentValues={{ unit_code: 'BOX_12', organization_id: 'org_a' }} /> + , + ); + await waitFor(() => expect(screen.getByText('Box of 12')).toBeInTheDocument()); + expect(screen.getByRole('spinbutton')).toHaveValue(3); + }); +}); + +describe('the per-locale standard label (ADR-0158 L2, 2A)', () => { + it("reads the reader's locale", async () => { + render( + + +
{React.createElement(getCellRenderer('number'), { value: 2, field: FIXED_QTY, dependentValues: { organization_id: 'org_a' } })}
+
+
, + ); + await waitFor(() => expect(faceText()).toBe('2 千克')); + }); +}); + +describe('a unit-code field (Open item 8)', () => { + it("draws the code's label, and a retired code bare", async () => { + const CODE = { name: 'base_unit', type: 'text', unitConfig: { unitMode: 'code' } } as any; + const Cell = getCellRenderer('text'); + render( + +
+
+
, + ); + await waitFor(() => expect(text(screen.getByTestId('a').textContent)).toBe('pc')); + expect(text(screen.getByTestId('b').textContent)).toBe('JIN1'); + }); +}); + +describe('formatQuantity — the one formatter', () => { + const field = { name: 'qty', type: 'number' } as any; + + it('marks a stored value with more places than shown, and changes nothing stored', () => { + const value = 1.5; + const out = formatQuantity(value, field, { code: 'H87', standard: true, label: 'pc', decimals: 0 }, 'en-US'); + expect(out).toEqual({ text: '2 pc', number: '2', unit: 'pc', hidden: true }); + expect(value).toBe(1.5); + expect(formatQuantity(1.5, field, { code: 'GRM', standard: true, label: 'g', decimals: 3 }, 'en-US').hidden).toBe(false); + }); + + it('keeps the field width when the unit has no decimal places of its own', () => { + expect(formatQuantity(1.25, { ...field, scale: 2 }, { code: 'KGM', standard: true, label: 'kg' }, 'en-US').text).toBe('1.25 kg'); + expect(quantityDisplayPlaces(undefined, field)).toBeUndefined(); + expect(quantityDisplayPlaces(5, { ...field, scale: 2 })).toBe(2); + expect(quantityDisplayPlaces(1, { ...field, scale: 2 })).toBe(1); + }); +}); diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index 8020f2ae7b4..1c507502a14 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -8,7 +8,7 @@ import React from 'react'; import type { DateFieldMetadata, DateTimeFieldMetadata, FieldMetadata, SelectOptionMetadata } from '@object-ui/types'; -import { ComponentRegistry, percentDisplayValue, type PercentScale, getRecordDisplayName, humanizeLabel, isEmptyValue, optionDisplayLabel, isMissingForRequired, formatDate, formatDateTime, formatDateTimeCompactParts, formatRelativeDate, toDisplayDate, extractRecords, withoutDeniedFields, type RegistryComponentMeta, type DateDisplayOptions } from '@object-ui/core'; +import { ComponentRegistry, declaresQuantityUnit, percentDisplayValue, type PercentScale, getRecordDisplayName, humanizeLabel, isEmptyValue, optionDisplayLabel, isMissingForRequired, formatDate, formatDateTime, formatDateTimeCompactParts, formatRelativeDate, toDisplayDate, extractRecords, withoutDeniedFields, type RegistryComponentMeta, type DateDisplayOptions } from '@object-ui/core'; // The platform's own value-shape contract, asked rather than restated // (objectui#6744). See `locationStoredValueSchemaFor` below for why this is a // runtime import in the barrel and not a hand-written coordinate range. @@ -35,6 +35,7 @@ import { deriveHexBadgePalette } from './hexBadgePalette.js'; // `NumberField`'s read-only branch (objectui#11431), and likewise for currency // (`CurrencyField`) and percent (`PercentField`) (objectui#11444). import { formatNumberFieldValue, formatCurrency, formatPercentPoints, percentCellScale } from './widgets/number-format.js'; +import { QuantityText, UnitCodeText } from './widgets/QuantityText.js'; import { useFieldTranslation } from './widgets/useFieldTranslation.js'; import { useBooleanValueLabel } from './widgets/booleanValueLabel.js'; import { GridField } from './widgets/GridField.js'; @@ -833,13 +834,18 @@ function findDeclaredOption( * reads too. Only a scalar stored value is matched; an array or an expanded * record keeps the coerced text, since neither is one option's code. */ -export function TextCellRenderer({ value, field }: CellRendererProps): React.ReactElement { +export function TextCellRenderer({ value, field, dependentValues }: CellRendererProps): React.ReactElement { const safe = coerceToSafeValue(value); // THE FLOOR by name and nothing more (objectui#8496), on the coerced text. // ⛔ Deliberately NOT `isBlankCellText`: a stored `' '` is a value of a text // cell and keeps its spaces — the trim belongs to the renderers that go on to // coerce the text into a number, a date or an `href`. if (isEmptyValue(safe)) return ; + // A unit-code field (ADR-0158 Open item 8): the code's label, or the bare + // code when the unit has none to show. + if (typeof value === 'string' && declaresQuantityUnit(field)) { + return ; + } // `options` is a spec key on every field (`FieldSchema.options`), but the // per-type metadata of the types this cell draws does not name it, so it is // read structurally, as `LookupCellRenderer` reads its static options. @@ -854,7 +860,7 @@ export function TextCellRenderer({ value, field }: CellRendererProps): React.Rea /** * Number field cell renderer */ -export function NumberCellRenderer({ value, field }: CellRendererProps): React.ReactElement { +export function NumberCellRenderer({ value, field, dependentValues }: CellRendererProps): React.ReactElement { // Hook before the empty-value early return — a value flipping between null // and set must not change the hook count between renders (same rule as // CurrencyCellRenderer below). @@ -866,6 +872,12 @@ export function NumberCellRenderer({ value, field }: CellRendererProps): React.R if (isBlankCellText(safe)) return ; const num = Number(safe); + // A quantity (ADR-0158): its unit's label and display width, through the + // face `NumberField`'s read-only branch draws too. The row is the record a + // `record`-mode quantity reads its code from. + if (!isNaN(num) && declaresQuantityUnit(field)) { + return ; + } // The width (`scale` through `resolveFieldScale`), the grouping policy // (`scale` / `useGrouping`) and the two fraction-digit arms are assembled in // `formatNumberFieldValue`, the one call `NumberField`'s read-only branch diff --git a/ui/packages/fields/src/widgets/NumberField.tsx b/ui/packages/fields/src/widgets/NumberField.tsx index 1d35e269db6..881b5dcd522 100644 --- a/ui/packages/fields/src/widgets/NumberField.tsx +++ b/ui/packages/fields/src/widgets/NumberField.tsx @@ -8,18 +8,29 @@ import { InCellTextInput } from './InCellTextInput.js'; import { PHONE_TOUCH_HEIGHT } from './touchTarget.js'; import { useBadInputRefusal, BadInputMessage, BAD_INPUT_BORDER } from './numberBadInput.js'; import { formatNumberFieldValue } from './number-format.js'; +import { declaresQuantityUnit } from '@object-ui/core'; +import { QuantityText } from './QuantityText.js'; +import { useQuantityUnit } from './useQuantityUnit.js'; /** * NumberField - Numeric input with optional decimal precision * Supports min/max/step constraints and configurable decimal precision */ -export function NumberField({ value, onChange, field, readonly, error, inCell, onCommit: _onCommit, ...props }: FieldWidgetComponentProps) { +export function NumberField({ value, onChange, field, readonly, error, inCell, onCommit: _onCommit, dependentValues, ...props }: FieldWidgetComponentProps) { // Before the readonly return: hooks are unconditional (objectui#6780). const { refusal, readBadInput } = useBadInputRefusal('1234'); const locale = useDisplayLocale(); + // The unit an edited quantity is entered in (ADR-0158), shown beside the box. + // Resolved for the read-only face inside `QuantityText` instead. + const editUnit = useQuantityUnit(readonly ? undefined : field, dependentValues); if (readonly) { if (value == null) return ; + // A quantity (ADR-0158): the face `NumberCellRenderer` draws, with the + // form's live record for a `record`-mode quantity's code. + if (typeof value === 'number' && declaresQuantityUnit(field)) { + return ; + } // The text `NumberCellRenderer` shows for the same field and value: both // make the one `formatNumberFieldValue` call, with the width // `resolveFieldScale` answers, the field's grouping policy and the display @@ -92,43 +103,60 @@ export function NumberField({ value, onChange, field, readonly, error, inCell, o ); } + const box = ( + { + // objectui#6780: ask the browser whether it can READ the box before + // trusting `.value`. The emission below is deliberately unchanged — + // see `numberBadInput.tsx` for why refusing would wipe the very text + // the diagnostic points at. + readBadInput(e.target); + const val = e.target.value; + onChange(val === '' ? (null as any) : Number(val)); + }} + onBlur={handleBlur} + placeholder={numberField?.placeholder} + disabled={readonly || domProps.disabled} + className={cn(PHONE_TOUCH_HEIGHT, refusal ? BAD_INPUT_BORDER : '', domProps.className)} + // Surface the field's declared range so the browser's spinner/keyboard + // affordances respect it (server-side validation still owns enforcement). + min={typeof numberField?.min === 'number' ? numberField.min : undefined} + max={typeof numberField?.max === 'number' ? numberField.max : undefined} + step={step} + // `refusal` is this widget's OWN reading and no host can produce it; + // `error` keeps its single author (objectui#3222 / objectui#6716) — + // the same two-name split `CurrencyField` and `PercentField` use. + // + // This was a CONDITIONAL spread (written only while `refusal` was + // active) for as long as the widget did not read `error`: an + // unconditional attribute computed from a prop it never consumed would + // have stamped `"false"` over the correct value ``'s Radix + // Slot hands down — the overwrite objectui#3222's e2e pins call out. + // Reading `error` here is what retires that hazard, so the two halves + // landed together (objectui#6803); neither is safe alone. + aria-invalid={!!error || !!refusal} + /> + ); + return (
- { - // objectui#6780: ask the browser whether it can READ the box before - // trusting `.value`. The emission below is deliberately unchanged — - // see `numberBadInput.tsx` for why refusing would wipe the very text - // the diagnostic points at. - readBadInput(e.target); - const val = e.target.value; - onChange(val === '' ? (null as any) : Number(val)); - }} - onBlur={handleBlur} - placeholder={numberField?.placeholder} - disabled={readonly || domProps.disabled} - className={cn(PHONE_TOUCH_HEIGHT, refusal ? BAD_INPUT_BORDER : '', domProps.className)} - // Surface the field's declared range so the browser's spinner/keyboard - // affordances respect it (server-side validation still owns enforcement). - min={typeof numberField?.min === 'number' ? numberField.min : undefined} - max={typeof numberField?.max === 'number' ? numberField.max : undefined} - step={step} - // `refusal` is this widget's OWN reading and no host can produce it; - // `error` keeps its single author (objectui#3222 / objectui#6716) — - // the same two-name split `CurrencyField` and `PercentField` use. - // - // This was a CONDITIONAL spread (written only while `refusal` was - // active) for as long as the widget did not read `error`: an - // unconditional attribute computed from a prop it never consumed would - // have stamped `"false"` over the correct value ``'s Radix - // Slot hands down — the overwrite objectui#3222's e2e pins call out. - // Reading `error` here is what retires that hazard, so the two halves - // landed together (objectui#6803); neither is safe alone. - aria-invalid={!!error || !!refusal} - /> + {editUnit ? ( +
+ {box} + + {editUnit.label ?? editUnit.code} + +
+ ) : ( + box + )}
); diff --git a/ui/packages/fields/src/widgets/QuantityText.tsx b/ui/packages/fields/src/widgets/QuantityText.tsx new file mode 100644 index 00000000000..3aa1e09e2fe --- /dev/null +++ b/ui/packages/fields/src/widgets/QuantityText.tsx @@ -0,0 +1,74 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import React from 'react'; +import type { FieldMetadata } from '@object-ui/types'; +import { useDisplayLocale } from '@object-ui/i18n'; +import { useQuantityUnit } from './useQuantityUnit.js'; +import { formatQuantity } from './quantity-format.js'; + +/** + * A quantity with its unit (ADR-0158 R1 display): the face `NumberCellRenderer` + * draws in a grid or detail row and `NumberField`'s read-only branch draws in + * a form, so the three surfaces show one quantity identically. + * + * `record` is the row or form values the quantity sits in: a `record`-mode + * quantity reads its code from it, and its organization picks the setting row. + */ +export function QuantityText({ + value, + field, + record, + className, +}: { + value: number; + field: FieldMetadata; + record?: Readonly> | null; + className?: string; +}): React.ReactElement { + const locale = useDisplayLocale(); + const unit = useQuantityUnit(field, record); + const display = formatQuantity(value, field, unit, locale); + return ( + + {display.number} + {display.unit ? ( + <> + {'\u00a0'} + + {display.unit} + + + ) : null} + + ); +} + +/** + * A unit-code field (`text` with `unitConfig: { unitMode: 'code' }`, ADR-0158 + * Open item 8 ruled A): the code's label, with the code itself as its title, + * or the bare code when the unit has no label to show. + */ +export function UnitCodeText({ + value, + field, + record, + className, +}: { + value: string; + field: FieldMetadata; + record?: Readonly> | null; + className?: string; +}): React.ReactElement { + const unit = useQuantityUnit(field, record, value); + return ( + + {unit?.label ?? value} + + ); +} diff --git a/ui/packages/fields/src/widgets/quantity-format.ts b/ui/packages/fields/src/widgets/quantity-format.ts new file mode 100644 index 00000000000..9031fd67610 --- /dev/null +++ b/ui/packages/fields/src/widgets/quantity-format.ts @@ -0,0 +1,122 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The ONE formatting call every display face of a quantity makes (ADR-0158): + * `NumberCellRenderer` in a grid or detail row, and `NumberField`'s read-only + * branch in a form. Pure, for the reason `number-format.ts` gives: the eager + * barrel and the lazily loaded widget both call it and neither may import the + * other. + * + * What it draws: the number at the unit's display width, then the unit's + * label, or its bare code when the unit has no label to show (L1). The stored + * value is never changed: nothing here rounds at write (L4), and a footer, + * an export, the API and MCP all read the exact stored value. + */ + +import type { FieldMetadata } from '@object-ui/types'; +import type { ResolvedUnit } from '@object-ui/core'; +import { resolveFieldScale } from '@objectstack/spec/data'; +import { formatDisplayNumber } from '@object-ui/i18n'; +import { formatNumberFieldValue } from './number-format.js'; + +/** What a quantity displays as. */ +export interface QuantityDisplay { + /** The whole text: the number, then the unit's label or code when there is one. */ + text: string; + /** The number alone, as `text` writes it. */ + number: string; + /** The label or code drawn after the number; absent when the quantity has no unit to show. */ + unit?: string; + /** + * Whether the stored value has more decimal places than the number shows. + * Computed for every quantity; nothing renders from it yet (ADR-0158 Open + * item 6's second half decides whether a marker does). + */ + hidden: boolean; +} + +/** + * The display decimal places of a quantity whose unit declares `unitDecimals` + * (ADR-0158 U6), under L4: the field's declared `scale` is the ceiling, so the + * unit never shows more places than the field stores. A field that declares no + * `scale` takes the unit's places as they are (Open item 6, first half: a + * quantity needs no `scale`). `undefined` when the unit declares none, and the + * field's own width then applies. + */ +export function quantityDisplayPlaces(unitDecimals: number | undefined, field: FieldMetadata): number | undefined { + if (unitDecimals === undefined) return undefined; + const scale = resolveFieldScale({ type: field.type, scale: 'scale' in field ? field.scale : undefined }); + return scale === undefined ? unitDecimals : Math.min(unitDecimals, scale); +} + +/** The number of decimal places `value` carries in its shortest decimal form. */ +function placesOf(value: number): number { + if (!Number.isFinite(value)) return 0; + const text = Math.abs(value).toString(); + const exp = /e([+-]\d+)$/.exec(text); + const mantissa = exp ? text.slice(0, exp.index) : text; + const dot = mantissa.indexOf('.'); + const fraction = dot === -1 ? 0 : mantissa.length - dot - 1; + return Math.max(0, fraction - (exp ? Number(exp[1]) : 0)); +} + +/** + * The fraction-digit bounds a quantity is drawn at, given its display places. + * + * ⭐ The rounding rule lives here and nowhere else: ADR-0158 Open item 6's + * second half (what a unit's display default does with a stored value that + * has more places) is answered by this function. Today it is a fixed width, + * as a currency amount is drawn at its currency's digits: a unit of 3 places + * shows 1.5 as `1.500`, and a unit of 0 places shows 1.5 rounded, the way + * `Intl` rounds. + */ +function quantityFractionDigits(places: number): { minimumFractionDigits: number; maximumFractionDigits: number } { + return { minimumFractionDigits: places, maximumFractionDigits: places }; +} + +/** + * Format a quantity of `field` in `unit` for display. + * + * @param value the stored number; callers decide what is empty first. + * @param field the field metadata (`type`, `scale`, `useGrouping` are read). + * @param unit the resolved unit (`resolveQuantityUnit`), or `undefined` when + * the quantity has no unit to show (a blank code on its row). + * @param locale the display locale tag. + */ +export function formatQuantity( + value: number, + field: FieldMetadata, + unit: ResolvedUnit | undefined, + locale?: string, +): QuantityDisplay { + const places = quantityDisplayPlaces(unit?.decimals, field); + let number: string; + let hidden = false; + if (places === undefined) { + // No display default of the unit's own: the field's own width, as a bare + // number of this field is drawn. + number = formatNumberFieldValue(value, field, locale); + } else { + const declaredScale = resolveFieldScale({ type: field.type, scale: 'scale' in field ? field.scale : undefined }); + const useGrouping = + 'useGrouping' in field && typeof field.useGrouping === 'boolean' ? field.useGrouping : undefined; + const digits = quantityFractionDigits(places); + // The grouping policy keeps reading the FIELD's declaration, so a quantity + // groups exactly as the same field's bare number does. + number = formatDisplayNumber(value, { locale, scale: declaredScale, useGrouping, ...digits }); + hidden = placesOf(value) > digits.maximumFractionDigits; + } + const label = unit ? (unit.label ?? unit.code) : undefined; + return { + text: label ? `${number}\u00a0${label}` : number, + number, + ...(label ? { unit: label } : {}), + hidden, + }; +} diff --git a/ui/packages/fields/src/widgets/useQuantityUnit.ts b/ui/packages/fields/src/widgets/useQuantityUnit.ts new file mode 100644 index 00000000000..22ea2c18cf1 --- /dev/null +++ b/ui/packages/fields/src/widgets/useQuantityUnit.ts @@ -0,0 +1,130 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The unit a quantity displays in, for the faces that draw one (ADR-0158 R1 + * display): which code, its label, and its display decimal places. + * + * The rows come from the two places the platform keeps them: the + * organization's own units (`sys_unit`, U3) and its decimal places for + * standard codes (`sys_standard_unit_setting`, Open item 10). Both are read + * through the data source the surfaces already use (`SchemaRendererContext`), + * once per adapter for the session, the way `homeAmountPreview` reads rates. + * A read the caller may not make (an external member holds no `sys_unit` + * read) or one that fails leaves that table unread, and its codes show bare: + * never an error. + */ + +import { useContext, useEffect, useState } from 'react'; +import { SchemaRendererContext } from '@object-ui/react'; +import { en } from '@object-ui/i18n'; +import { + quantityUnitCode, + resolveQuantityUnit, + type OrganizationUnitRow, + type ResolvedUnit, + type StandardUnitSettingRow, + type UnitBearingField, + type UnitCatalog, +} from '@object-ui/core'; +import { useFieldTranslation } from './useFieldTranslation.js'; + +/** The organization-unit table (ADR-0158 U3). */ +export const ORGANIZATION_UNIT_OBJECT = 'sys_unit'; +/** The standard-unit decimal-places table (ADR-0158 Open item 10). */ +export const STANDARD_UNIT_SETTING_OBJECT = 'sys_standard_unit_setting'; + +/** + * How many rows one read asks for. A setting row exists per standard code an + * organization has set (at most the table's size per organization), and an + * organization's own units are a short reference list; a member of several + * organizations reads each one's rows. + */ +const UNIT_READ_TOP = 2000; + +interface UnitSource { + find(resource: string, params?: Record): Promise; +} + +const rowsOf = (answer: unknown): readonly Record[] => { + const rows = Array.isArray(answer) ? answer : (answer as { data?: unknown } | null)?.data; + return Array.isArray(rows) ? (rows as Record[]) : []; +}; + +/** One read per adapter, kept for the session; a read that fails resolves to "unread". */ +const CATALOG_READS = new WeakMap>(); + +/** + * Read both unit tables through `source`, once per adapter. Each table is read + * on its own, so a refusal of one (an external member and `sys_unit`) leaves + * the other readable. + */ +export function readUnitCatalog(source: UnitSource): Promise { + const held = CATALOG_READS.get(source); + if (held) return held; + const read = (object: string, select: string[]): Promise => + source + .find(object, { $select: select, $top: UNIT_READ_TOP }) + .then((answer) => rowsOf(answer) as unknown as readonly R[], () => undefined); + const catalog = Promise.all([ + read(ORGANIZATION_UNIT_OBJECT, ['code', 'label', 'decimal_places', 'retired', 'organization_id']), + read(STANDARD_UNIT_SETTING_OBJECT, ['code', 'decimal_places', 'organization_id']), + ]).then(([organizationUnits, standardUnitSettings]): UnitCatalog => ({ + ...(organizationUnits ? { organizationUnits } : {}), + ...(standardUnitSettings ? { standardUnitSettings } : {}), + })); + CATALOG_READS.set(source, catalog); + return catalog; +} + +/** + * The platform's label for a standard code in the reader's locale (ADR-0158 + * L2, 2A), or `undefined` for a code with none. One function, so where the + * per-locale names live can move without any caller changing. + */ +export function useStandardUnitLabel(): (code: string) => string | undefined { + const { t } = useFieldTranslation(); + return (code: string) => { + const base = (en.units.standard as Readonly>)[code]; + if (base === undefined) return undefined; + const label = t(`units.standard.${code}`, { defaultValue: base }); + return typeof label === 'string' && label !== '' && label !== `units.standard.${code}` ? label : base; + }; +} + +/** + * The unit a value of `field` displays in, on `record`: `undefined` when the + * field declares no unit or the record names none. Until the unit tables are + * read the code resolves with its label but no decimal places of its own. + */ +export function useQuantityUnit( + field: UnitBearingField | null | undefined, + record?: Readonly> | null, + value?: unknown, + dataSource?: unknown, +): ResolvedUnit | undefined { + const ctx = useContext(SchemaRendererContext); + const source = (dataSource ?? ctx?.dataSource) as UnitSource | null | undefined; + const code = quantityUnitCode(field, record, value); + const standardLabel = useStandardUnitLabel(); + const canRead = code !== undefined && typeof source?.find === 'function'; + const [catalog, setCatalog] = useState<{ source: object; catalog: UnitCatalog } | undefined>(undefined); + useEffect(() => { + if (!canRead || !source) return; + let current = true; + readUnitCatalog(source).then((read) => { + if (current) setCatalog({ source, catalog: read }); + }); + return () => { + current = false; + }; + }, [canRead, source]); + if (code === undefined) return undefined; + const rows = catalog && catalog.source === source ? catalog.catalog : {}; + return resolveQuantityUnit(code, rows, record, standardLabel(code)); +} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 040ffe0ca80..d9e4fb49510 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -289,6 +289,53 @@ const ar = { textFallback: "النص", }, }, + // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), + // drawn beside a quantity; keyed by the code in exact uppercase. + units: { + standard: { + KGM: 'كغ', + GRM: 'غ', + MGM: 'مغ', + TNE: 'طن', + LBR: 'رطل', + ONZ: 'أونصة', + MTR: 'م', + MMT: 'مم', + CMT: 'سم', + KMT: 'كم', + INH: 'بوصة', + FOT: 'قدم', + YRD: 'ياردة', + MTK: 'م²', + CMK: 'سم²', + MMK: 'مم²', + FTK: 'قدم²', + MTQ: 'م³', + LTR: 'لتر', + MLT: 'مل', + GLL: 'غالون', + SEC: 'ثانية', + MIN: 'دقيقة', + HUR: 'ساعة', + DAY: 'يوم', + WEE: 'أسبوع', + H87: 'قطعة', + PR: 'زوج', + DZN: 'دزينة', + XBG: 'كيس', + XBE: 'حزمة', + XBO: 'زجاجة', + XBX: 'علبة', + XCT: 'كرتونة', + XCS: 'صندوق', + XCR: 'قفص', + XDR: 'برميل', + XPK: 'طرد', + XPX: 'منصة', + XRO: 'لفة', + XSA: 'جوال', + }, + }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index b581fe53706..a8e4472174d 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -271,6 +271,53 @@ const de = { textFallback: "Text", }, }, + // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), + // drawn beside a quantity; keyed by the code in exact uppercase. + units: { + standard: { + KGM: 'kg', + GRM: 'g', + MGM: 'mg', + TNE: 't', + LBR: 'lb', + ONZ: 'oz', + MTR: 'm', + MMT: 'mm', + CMT: 'cm', + KMT: 'km', + INH: 'in', + FOT: 'ft', + YRD: 'yd', + MTK: 'm²', + CMK: 'cm²', + MMK: 'mm²', + FTK: 'ft²', + MTQ: 'm³', + LTR: 'l', + MLT: 'ml', + GLL: 'gal', + SEC: 's', + MIN: 'min', + HUR: 'h', + DAY: 'd', + WEE: 'Wo.', + H87: 'Stk.', + PR: 'Paar', + DZN: 'Dtzd.', + XBG: 'Beutel', + XBE: 'Bündel', + XBO: 'Flasche', + XBX: 'Schachtel', + XCT: 'Karton', + XCS: 'Kiste', + XCR: 'Lattenkiste', + XDR: 'Fass', + XPK: 'Pkg.', + XPX: 'Palette', + XRO: 'Rolle', + XSA: 'Sack', + }, + }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index e4a76084830..318e4bcd9ad 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -429,6 +429,53 @@ const en = { textFallback: 'text', }, }, + // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), + // drawn beside a quantity; keyed by the code in exact uppercase. + units: { + standard: { + KGM: 'kg', + GRM: 'g', + MGM: 'mg', + TNE: 't', + LBR: 'lb', + ONZ: 'oz', + MTR: 'm', + MMT: 'mm', + CMT: 'cm', + KMT: 'km', + INH: 'in', + FOT: 'ft', + YRD: 'yd', + MTK: 'm²', + CMK: 'cm²', + MMK: 'mm²', + FTK: 'ft²', + MTQ: 'm³', + LTR: 'L', + MLT: 'mL', + GLL: 'gal', + SEC: 's', + MIN: 'min', + HUR: 'h', + DAY: 'd', + WEE: 'wk', + H87: 'pc', + PR: 'pr', + DZN: 'doz', + XBG: 'bag', + XBE: 'bundle', + XBO: 'bottle', + XBX: 'box', + XCT: 'carton', + XCS: 'case', + XCR: 'crate', + XDR: 'drum', + XPK: 'pkg', + XPX: 'pallet', + XRO: 'roll', + XSA: 'sack', + }, + }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index c879e9508ec..b56d34ea514 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -279,6 +279,53 @@ const es = { textFallback: "texto", }, }, + // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), + // drawn beside a quantity; keyed by the code in exact uppercase. + units: { + standard: { + KGM: 'kg', + GRM: 'g', + MGM: 'mg', + TNE: 't', + LBR: 'lb', + ONZ: 'oz', + MTR: 'm', + MMT: 'mm', + CMT: 'cm', + KMT: 'km', + INH: 'pulg.', + FOT: 'pie', + YRD: 'yd', + MTK: 'm²', + CMK: 'cm²', + MMK: 'mm²', + FTK: 'pie²', + MTQ: 'm³', + LTR: 'L', + MLT: 'mL', + GLL: 'gal', + SEC: 's', + MIN: 'min', + HUR: 'h', + DAY: 'd', + WEE: 'sem.', + H87: 'pza', + PR: 'par', + DZN: 'doc.', + XBG: 'bolsa', + XBE: 'fardo', + XBO: 'botella', + XBX: 'caja', + XCT: 'cartón', + XCS: 'estuche', + XCR: 'cajón', + XDR: 'bidón', + XPK: 'paquete', + XPX: 'palé', + XRO: 'rollo', + XSA: 'saco', + }, + }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 5bf4039eab7..f9ae15505ab 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -274,6 +274,53 @@ const fr = { textFallback: "le texte", }, }, + // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), + // drawn beside a quantity; keyed by the code in exact uppercase. + units: { + standard: { + KGM: 'kg', + GRM: 'g', + MGM: 'mg', + TNE: 't', + LBR: 'lb', + ONZ: 'oz', + MTR: 'm', + MMT: 'mm', + CMT: 'cm', + KMT: 'km', + INH: 'po', + FOT: 'pi', + YRD: 'vg', + MTK: 'm²', + CMK: 'cm²', + MMK: 'mm²', + FTK: 'pi²', + MTQ: 'm³', + LTR: 'L', + MLT: 'mL', + GLL: 'gal', + SEC: 's', + MIN: 'min', + HUR: 'h', + DAY: 'j', + WEE: 'sem.', + H87: 'pce', + PR: 'paire', + DZN: 'douz.', + XBG: 'sachet', + XBE: 'lot', + XBO: 'bouteille', + XBX: 'boîte', + XCT: 'carton', + XCS: 'caisse', + XCR: 'cageot', + XDR: 'fût', + XPK: 'colis', + XPX: 'palette', + XRO: 'rouleau', + XSA: 'sac', + }, + }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 5b689d2ef4e..41e28e64dcb 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -271,6 +271,53 @@ const ja = { textFallback: "テキスト", }, }, + // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), + // drawn beside a quantity; keyed by the code in exact uppercase. + units: { + standard: { + KGM: 'kg', + GRM: 'g', + MGM: 'mg', + TNE: 't', + LBR: 'lb', + ONZ: 'oz', + MTR: 'm', + MMT: 'mm', + CMT: 'cm', + KMT: 'km', + INH: 'in', + FOT: 'ft', + YRD: 'yd', + MTK: 'm²', + CMK: 'cm²', + MMK: 'mm²', + FTK: 'ft²', + MTQ: 'm³', + LTR: 'L', + MLT: 'mL', + GLL: 'gal', + SEC: '秒', + MIN: '分', + HUR: '時間', + DAY: '日', + WEE: '週', + H87: '個', + PR: '組', + DZN: 'ダース', + XBG: '袋', + XBE: '束', + XBO: '本', + XBX: '箱', + XCT: 'カートン', + XCS: 'ケース', + XCR: 'クレート', + XDR: 'ドラム', + XPK: '包', + XPX: 'パレット', + XRO: '巻', + XSA: '大袋', + }, + }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 6d159da8f17..86121deb0d5 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -271,6 +271,53 @@ const ko = { textFallback: "텍스트", }, }, + // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), + // drawn beside a quantity; keyed by the code in exact uppercase. + units: { + standard: { + KGM: 'kg', + GRM: 'g', + MGM: 'mg', + TNE: 't', + LBR: 'lb', + ONZ: 'oz', + MTR: 'm', + MMT: 'mm', + CMT: 'cm', + KMT: 'km', + INH: 'in', + FOT: 'ft', + YRD: 'yd', + MTK: 'm²', + CMK: 'cm²', + MMK: 'mm²', + FTK: 'ft²', + MTQ: 'm³', + LTR: 'L', + MLT: 'mL', + GLL: 'gal', + SEC: '초', + MIN: '분', + HUR: '시간', + DAY: '일', + WEE: '주', + H87: '개', + PR: '쌍', + DZN: '다스', + XBG: '봉지', + XBE: '묶음', + XBO: '병', + XBX: '상자', + XCT: '카톤', + XCS: '케이스', + XCR: '크레이트', + XDR: '드럼', + XPK: '포장', + XPX: '팔레트', + XRO: '롤', + XSA: '포대', + }, + }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 09c1cc0730a..5f8124daa8b 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -274,6 +274,53 @@ const pt = { textFallback: "texto", }, }, + // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), + // drawn beside a quantity; keyed by the code in exact uppercase. + units: { + standard: { + KGM: 'kg', + GRM: 'g', + MGM: 'mg', + TNE: 't', + LBR: 'lb', + ONZ: 'oz', + MTR: 'm', + MMT: 'mm', + CMT: 'cm', + KMT: 'km', + INH: 'pol', + FOT: 'pé', + YRD: 'jd', + MTK: 'm²', + CMK: 'cm²', + MMK: 'mm²', + FTK: 'pé²', + MTQ: 'm³', + LTR: 'L', + MLT: 'mL', + GLL: 'gal', + SEC: 's', + MIN: 'min', + HUR: 'h', + DAY: 'd', + WEE: 'sem.', + H87: 'pç', + PR: 'par', + DZN: 'dz', + XBG: 'sacola', + XBE: 'fardo', + XBO: 'garrafa', + XBX: 'caixa', + XCT: 'caixa de papelão', + XCS: 'estojo', + XCR: 'engradado', + XDR: 'tambor', + XPK: 'pacote', + XPX: 'palete', + XRO: 'rolo', + XSA: 'saco', + }, + }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index c1281b7a05c..7f1d2a7d7e5 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -280,6 +280,53 @@ const ru = { textFallback: "текст", }, }, + // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), + // drawn beside a quantity; keyed by the code in exact uppercase. + units: { + standard: { + KGM: 'кг', + GRM: 'г', + MGM: 'мг', + TNE: 'т', + LBR: 'фнт', + ONZ: 'унц', + MTR: 'м', + MMT: 'мм', + CMT: 'см', + KMT: 'км', + INH: 'дюйм', + FOT: 'фут', + YRD: 'ярд', + MTK: 'м²', + CMK: 'см²', + MMK: 'мм²', + FTK: 'фут²', + MTQ: 'м³', + LTR: 'л', + MLT: 'мл', + GLL: 'гал', + SEC: 'с', + MIN: 'мин', + HUR: 'ч', + DAY: 'сут', + WEE: 'нед', + H87: 'шт', + PR: 'пар', + DZN: 'дюж', + XBG: 'пакет', + XBE: 'связка', + XBO: 'бутылка', + XBX: 'коробка', + XCT: 'картон', + XCS: 'ящик', + XCR: 'клеть', + XDR: 'бочка', + XPK: 'упак', + XPX: 'поддон', + XRO: 'рул', + XSA: 'мешок', + }, + }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 832015de466..7f7461cd65c 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -281,6 +281,53 @@ const zh = { textFallback: '文本', }, }, + // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), + // drawn beside a quantity; keyed by the code in exact uppercase. + units: { + standard: { + KGM: '千克', + GRM: '克', + MGM: '毫克', + TNE: '吨', + LBR: '磅', + ONZ: '盎司', + MTR: '米', + MMT: '毫米', + CMT: '厘米', + KMT: '千米', + INH: '英寸', + FOT: '英尺', + YRD: '码', + MTK: '平方米', + CMK: '平方厘米', + MMK: '平方毫米', + FTK: '平方英尺', + MTQ: '立方米', + LTR: '升', + MLT: '毫升', + GLL: '加仑', + SEC: '秒', + MIN: '分钟', + HUR: '小时', + DAY: '天', + WEE: '周', + H87: '件', + PR: '双', + DZN: '打', + XBG: '袋', + XBE: '捆', + XBO: '瓶', + XBX: '盒', + XCT: '纸箱', + XCS: '箱', + XCR: '板条箱', + XDR: '桶', + XPK: '包', + XPX: '托盘', + XRO: '卷', + XSA: '麻袋', + }, + }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index d397fc1bf28..f344bc2a648 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -281,6 +281,53 @@ const zhHant = { textFallback: '文本', }, }, + // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), + // drawn beside a quantity; keyed by the code in exact uppercase. + units: { + standard: { + KGM: '公斤', + GRM: '克', + MGM: '毫克', + TNE: '公噸', + LBR: '磅', + ONZ: '盎司', + MTR: '公尺', + MMT: '毫米', + CMT: '公分', + KMT: '公里', + INH: '英寸', + FOT: '英尺', + YRD: '碼', + MTK: '平方公尺', + CMK: '平方公分', + MMK: '平方毫米', + FTK: '平方英尺', + MTQ: '立方公尺', + LTR: '公升', + MLT: '毫升', + GLL: '加侖', + SEC: '秒', + MIN: '分鐘', + HUR: '小時', + DAY: '天', + WEE: '週', + H87: '件', + PR: '雙', + DZN: '打', + XBG: '袋', + XBE: '捆', + XBO: '瓶', + XBX: '盒', + XCT: '紙箱', + XCS: '箱', + XCR: '板條箱', + XDR: '桶', + XPK: '包', + XPX: '棧板', + XRO: '卷', + XSA: '麻袋', + }, + }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/plugin-detail/src/RecordDetailPanel.tsx b/ui/packages/plugin-detail/src/RecordDetailPanel.tsx index 0ba2726f9ea..3f6e703b8d0 100644 --- a/ui/packages/plugin-detail/src/RecordDetailPanel.tsx +++ b/ui/packages/plugin-detail/src/RecordDetailPanel.tsx @@ -188,6 +188,9 @@ export function buildRecordDetailFields( // refuses a field-level `currency`, so without this a fixed-EUR amount // read in the tenant's currency here (objectui#12242). currencyConfig: def.currencyConfig, + // A quantity's unit (ADR-0158): the number cell draws its label and + // display decimal places from it. + unitConfig: (def as { unitConfig?: unknown }).unitConfig, // A formula's declared result type, which picks its face in the formula // cell: `currency` draws through the currency cell with the // `currencyConfig` above. Without it a money formula read as a bare diff --git a/ui/packages/plugin-detail/src/RelatedList.tsx b/ui/packages/plugin-detail/src/RelatedList.tsx index e20109b9201..09b2f987d3b 100644 --- a/ui/packages/plugin-detail/src/RelatedList.tsx +++ b/ui/packages/plugin-detail/src/RelatedList.tsx @@ -70,6 +70,8 @@ import { listViewPredicates, parentRelationshipFieldDef, PLATFORM_RECORD_COLUMNS, + shownQuantityUnitReads, + declaresQuantityUnit, recordDisplayValueAt, resolveNameField, composeParentScopeFilter, @@ -1972,6 +1974,17 @@ export const RelatedList: React.FC = ({ if (declared && !readable(field)) continue; projection.add(field); } + // [ADR-0158] A drawn quantity's unit: a `record`-mode quantity's code + // field and the row's organization, which the number cell reads off the + // row. The code field passes the same declared and FLS gates; + // `organization_id` is a platform column every object carries. + const drawnDefs = Object.fromEntries(drawnKeys.map((key) => [key, parentRelationshipFieldDef(fields, key)])); + for (const field of shownQuantityUnitReads(drawnKeys, drawnDefs)) { + const declared = parentRelationshipFieldDef(fields, field) !== undefined; + if (!declared && !PLATFORM_RECORD_COLUMNS.has(field)) continue; + if (declared && !readable(field)) continue; + projection.add(field); + } // The mobile card gallery's cover: no column shows it, but the gallery // reads it off every row. Asked for when the child DECLARES it (either // container shape) and FLS allows it — on every viewport, not only on @@ -3037,6 +3050,9 @@ export const RelatedList: React.FC = ({ // refuses a field-level `currency`, so without this a fixed-EUR amount // read in the tenant's currency in this list (objectui#12242). ...(def.currencyConfig && { currencyConfig: def.currencyConfig }), + // A quantity's unit (ADR-0158): the number cell draws its label and + // display decimal places from it. + ...((def as { unitConfig?: unknown }).unitConfig ? { unitConfig: (def as { unitConfig?: unknown }).unitConfig } : {}), // A formula's declared result type, which picks its face in the formula // cell: `currency` draws through the currency cell with the // `currencyConfig` above. Without it a money formula read as a bare @@ -3091,6 +3107,8 @@ export const RelatedList: React.FC = ({ // its sibling code field, or, when it follows the parent, the record // this list hangs under, laid on the row by `withFollowedParent`. ...(recordCurrencyField(def) !== undefined && { dependentValues: withFollowedParent(row, def, parentRecord) ?? undefined }), + // A quantity reads its unit code and organization off the ROW (ADR-0158). + ...(recordCurrencyField(def) === undefined && declaresQuantityUnit(def as { type?: string; unitConfig?: unknown }) && { dependentValues: row }), }); }; }; diff --git a/ui/packages/plugin-detail/src/__tests__/quantityUnitRelay-35490.test.tsx b/ui/packages/plugin-detail/src/__tests__/quantityUnitRelay-35490.test.tsx new file mode 100644 index 00000000000..b41ec509bce --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/quantityUnitRelay-35490.test.tsx @@ -0,0 +1,118 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35490 (ADR-0158 R1 display): a quantity's `unitConfig` reaches + * the DETAIL cells through each place this package hand-copies field metadata + * for them, and the row they read the unit off carries its code: + * + * - `ENRICHED_FIELD_METADATA_KEYS` (`enrichDetailField`), which `DetailSection` + * and `HeaderHighlight` share; + * - `buildRecordDetailFields` (`RecordDetailPanel`), the quick-look overlay; + * - `RelatedList`'s cell bag and its `$select`, for a code column not shown. + * + * The unit rows come from the host's data source, as the console provides it. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, cleanup, waitFor } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import * as React from 'react'; +import { SchemaRendererProvider } from '@object-ui/react'; +import '@object-ui/components'; +import type { DetailViewSection } from '@object-ui/types'; +import { DetailSection } from '../DetailSection'; +import { RecordDetailPanel } from '../RecordDetailPanel'; +import { RelatedList } from '../RelatedList'; + +vi.stubGlobal( + 'fetch', + vi.fn(async () => ({ ok: true, json: async () => ({ record: { visible: true } }) })), +); + +beforeEach(() => { + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1280 }); +}); +afterEach(cleanup); + +const FIELDS = { + name: { type: 'text', label: 'Name' }, + qty: { type: 'number', label: 'Qty', unitConfig: { unitMode: 'record', unitField: 'unit_code' } }, + weight: { type: 'number', label: 'Weight', unitConfig: { unitMode: 'fixed', unit: 'KGM' } }, + unit_code: { type: 'text', label: 'Unit' }, +}; +const RECORD = { id: 'r1', name: 'Tower', qty: 4, weight: 1.25, unit_code: 'BOX_12', organization_id: 'org_a' }; + +function unitSource(rows: Record[] = [RECORD]) { + const calls: Array<{ object: string; params: Record }> = []; + return { + calls, + getObjectSchema: vi.fn(async () => ({ name: 'line', fields: FIELDS })), + find: vi.fn(async (object: string, params: Record) => { + calls.push({ object, params }); + if (object === 'sys_unit') return { data: [{ code: 'BOX_12', label: 'Box of 12', decimal_places: 1, retired: false, organization_id: 'org_a' }] }; + if (object === 'sys_standard_unit_setting') return { data: [{ code: 'KGM', decimal_places: 1, organization_id: 'org_a' }] }; + const sel = Array.isArray(params?.$select) ? (params.$select as string[]) : undefined; + const data = rows.map((r) => (sel ? Object.fromEntries(Object.entries(r).filter(([k]) => k === 'id' || sel.includes(k))) : r)); + return { data, total: data.length }; + }), + }; +} + +const flat = (s: string | null | undefined) => (s ?? '').replace(/ /g, ' '); + +describe('the declared unitConfig reaches the detail cells (objectstack#35490)', () => { + it('DetailSection: a record-mode and a fixed-mode quantity, with their unit labels', async () => { + const ds = unitSource(); + const section = { title: 'S', fields: [{ name: 'qty' }, { name: 'weight' }] } as unknown as DetailViewSection; + const { container } = render( + + + , + ); + await waitFor(() => { + expect(flat(container.textContent)).toContain('4.0 Box of 12'); + expect(flat(container.textContent)).toContain('1.3 kg'); + }); + }); + + it("RecordDetailPanel: through the panel's own field build", async () => { + const ds = unitSource(); + const { container } = render( + + + , + ); + await waitFor(() => expect(flat(container.textContent)).toContain('4.0 Box of 12')); + }); + + it("RelatedList: through the cell bag, with the unit column not shown, so the read carries it", async () => { + const ds = unitSource(); + const { container } = render( + + + , + ); + await waitFor(() => expect(container.textContent).toContain('Tower')); + await waitFor(() => { + const cells = Array.from(container.querySelectorAll('tbody td')).map((td) => flat(td.textContent).trim()); + expect(cells, `cells: ${JSON.stringify(cells)}`).toContain('4.0 Box of 12'); + }); + const read = ds.calls.find((c) => c.object === 'line'); + expect(read?.params.$select).toEqual(expect.arrayContaining(['unit_code', 'organization_id'])); + }); +}); diff --git a/ui/packages/plugin-detail/src/fieldEnrichment.ts b/ui/packages/plugin-detail/src/fieldEnrichment.ts index 2647d161b75..0a382eb57aa 100644 --- a/ui/packages/plugin-detail/src/fieldEnrichment.ts +++ b/ui/packages/plugin-detail/src/fieldEnrichment.ts @@ -237,6 +237,10 @@ export const ENRICHED_FIELD_METADATA_KEYS = [ // cell: `currency` draws through the currency cell with the // `currencyConfig` above. Without it a money formula read as a bare number. 'returnType', + // A quantity's unit (ADR-0158 U4): the number cell draws the unit's label + // and display decimal places from it. Without it a quantity read as a bare + // number on the record page. + 'unitConfig', 'precision', 'scale', // The author's digit-grouping hint, which overrides `scale`'s scale-0 diff --git a/ui/packages/plugin-grid/src/__tests__/gridQuantityUnit-35490.test.tsx b/ui/packages/plugin-grid/src/__tests__/gridQuantityUnit-35490.test.tsx new file mode 100644 index 00000000000..4f4fa18f878 --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/gridQuantityUnit-35490.test.tsx @@ -0,0 +1,94 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35490 (ADR-0158 R1 display), in the object grid: a quantity + * draws with its unit's label and display decimal places, and a `record`-mode + * quantity reads its row's code even when the code column is not shown, so + * the grid's read carries the code field and the row's organization. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import * as React from 'react'; +import { render, screen, waitFor, cleanup } from '@testing-library/react'; +import { LocalizationProvider } from '@object-ui/i18n'; +import { registerAllFields } from '@object-ui/fields'; +import { ActionProvider, SchemaRendererProvider } from '@object-ui/react'; +import { ObjectGrid } from '../ObjectGrid'; + +registerAllFields(); +afterEach(cleanup); + +const FIELDS = { + name: { name: 'name', type: 'text', label: 'Line' }, + qty: { name: 'qty', type: 'number', label: 'Qty', unitConfig: { unitMode: 'record', unitField: 'unit_code' } }, + weight: { name: 'weight', type: 'number', label: 'Weight', unitConfig: { unitMode: 'fixed', unit: 'KGM' } }, + unit_code: { name: 'unit_code', type: 'text', label: 'Unit' }, +}; +const RAW = [ + { id: 'l1', name: 'L1', qty: 4, weight: 1.25, unit_code: 'BOX_12', organization_id: 'org_a' }, + { id: 'l2', name: 'L2', qty: 1.5, weight: 2, unit_code: 'GRM', organization_id: 'org_a' }, + { id: 'l3', name: 'L3', qty: 2, weight: 3, unit_code: 'JIN1', organization_id: 'org_a' }, +]; +const UNITS = [ + { code: 'BOX_12', label: 'Box of 12', decimal_places: 1, retired: false, organization_id: 'org_a' }, + { code: 'JIN1', label: 'Jin', decimal_places: 2, retired: true, organization_id: 'org_a' }, +]; +const SETTINGS = [ + { code: 'GRM', decimal_places: 3, organization_id: 'org_a' }, + { code: 'KGM', decimal_places: 1, organization_id: 'org_a' }, +]; + +/** A source that honours `$select`, as the server does, and answers the unit tables. */ +function source() { + const calls: Array<{ object: string; params: Record }> = []; + const ds = { + find: async (object: string, p: Record) => { + calls.push({ object, params: p }); + if (object === 'sys_unit') return { data: UNITS }; + if (object === 'sys_standard_unit_setting') return { data: SETTINGS }; + const sel = Array.isArray(p?.$select) ? (p.$select as string[]) : undefined; + const data = RAW.map((r) => (sel ? Object.fromEntries(Object.entries(r).filter(([k]) => k === 'id' || sel.includes(k))) : r)); + return { data, total: data.length }; + }, + findOne: async () => null, + create: async () => ({}), + update: async () => ({}), + delete: async () => true, + getObjectSchema: async () => ({ name: 'line', fields: FIELDS }), + }; + return { ds, calls }; +} + +const rowTexts = () => [...document.querySelectorAll('tbody tr')].map((tr) => (tr.textContent ?? '').replace(/ /g, ' ')); + +describe('object grid: a quantity with its unit (objectstack#35490)', () => { + it("draws each row in its own unit, with the unit column not shown", async () => { + const { ds, calls } = source(); + render( + + {/* The host's data source, as the console provides it to every cell. */} + + + + + + , + ); + await waitFor(() => expect(screen.getByText('L1')).toBeInTheDocument()); + await waitFor(() => { + const rows = rowTexts(); + expect(rows[0]).toContain('4.0 Box of 12'); + expect(rows[0]).toContain('1.3 kg'); + expect(rows[1]).toContain('1.500 g'); + expect(rows[2]).toContain('2 JIN1'); + }); + const read = calls.find((c) => c.object === 'line')!; + expect(read.params.$select).toEqual(expect.arrayContaining(['unit_code', 'organization_id'])); + }); +}); diff --git a/ui/packages/plugin-grid/src/objectGridGenerateColumns.tsx b/ui/packages/plugin-grid/src/objectGridGenerateColumns.tsx index d89d31e3d89..b32b539f018 100644 --- a/ui/packages/plugin-grid/src/objectGridGenerateColumns.tsx +++ b/ui/packages/plugin-grid/src/objectGridGenerateColumns.tsx @@ -364,6 +364,10 @@ export function useObjectGridGenerateColumns({ // Dropped, the cell fell through to the tenant currency while the // metric tile and every whole-def cell read the field's own. if (objectDefField.currencyConfig) fieldMeta.currencyConfig = objectDefField.currencyConfig; + // A quantity's unit (ADR-0158), verbatim for the same reason: the + // cell's `useQuantityUnit` owns what it means. Dropped, a quantity + // drew as a bare number. + if ((objectDefField as { unitConfig?: unknown }).unitConfig) fieldMeta.unitConfig = (objectDefField as { unitConfig?: unknown }).unitConfig; // A formula's declared `returnType` picks its face in the // formula cell (`FormulaCellRenderer`): `currency` draws through // the currency cell with the `currencyConfig` above. Dropped @@ -646,6 +650,8 @@ export function useObjectGridGenerateColumns({ if (fieldDef.currency) fieldMeta.currency = fieldDef.currency; // Verbatim, as the ListColumn path copies it (objectui#10354). if (fieldDef.currencyConfig) fieldMeta.currencyConfig = fieldDef.currencyConfig; + // A quantity's unit (ADR-0158), as path A copies it. + if ((fieldDef as { unitConfig?: unknown }).unitConfig) fieldMeta.unitConfig = (fieldDef as { unitConfig?: unknown }).unitConfig; // The formula's face, as path A copies it. if (fieldDef.returnType !== undefined) fieldMeta.returnType = fieldDef.returnType; if (fieldDef.precision !== undefined) fieldMeta.precision = fieldDef.precision; @@ -840,6 +846,8 @@ export function useObjectGridGenerateColumns({ if (fieldDef.currency) fieldMeta.currency = fieldDef.currency; // Verbatim, as the ListColumn path copies it (objectui#10354). if (fieldDef.currencyConfig) fieldMeta.currencyConfig = fieldDef.currencyConfig; + // A quantity's unit (ADR-0158), as path A copies it. + if ((fieldDef as { unitConfig?: unknown }).unitConfig) fieldMeta.unitConfig = (fieldDef as { unitConfig?: unknown }).unitConfig; // The formula's face, as path A copies it. if (fieldDef.returnType !== undefined) fieldMeta.returnType = fieldDef.returnType; if (fieldDef.precision !== undefined) fieldMeta.precision = fieldDef.precision; diff --git a/ui/packages/plugin-grid/src/objectGridRowLoad.ts b/ui/packages/plugin-grid/src/objectGridRowLoad.ts index 190b528f4aa..049e0080b83 100644 --- a/ui/packages/plugin-grid/src/objectGridRowLoad.ts +++ b/ui/packages/plugin-grid/src/objectGridRowLoad.ts @@ -12,7 +12,7 @@ import React, { useEffect } from 'react'; import type { ObjectGridSchema, DataSource, DependsOnInput, ViewData } from '@object-ui/types'; import { useDataInvalidation, type OwnWrites } from '@object-ui/react'; import { recordCurrencyReadField } from '@object-ui/i18n'; -import { resolveDependsOnFields, declaredNameField, buildExpandFields, columnIdentity, collectPredicateFieldRefs, collectGroupingFieldRefs, listViewPredicates, isProjectableField, convertSortToQueryParams, normalizeSortEntries, readWithheldFieldNames, refersToWithheldField, type QuerySortEntry } from '@object-ui/core'; +import { resolveDependsOnFields, shownQuantityUnitReads, declaredNameField, buildExpandFields, columnIdentity, collectPredicateFieldRefs, collectGroupingFieldRefs, listViewPredicates, isProjectableField, convertSortToQueryParams, normalizeSortEntries, readWithheldFieldNames, refersToWithheldField, type QuerySortEntry } from '@object-ui/core'; import type { usePermissions } from '@object-ui/permissions'; import { findParamsSignature } from './objectGridQuery'; import { normalizeColumns } from './objectGridColumns'; @@ -499,6 +499,16 @@ export function useObjectGridRowLoad({ .filter((f) => isProjectableField(f, declared as Record)) .filter((f) => passesProjectionGate(f)) : []; + // [ADR-0158] A shown QUANTITY's unit: a `record`-mode quantity's + // code field, and the row's organization, which picks the unit's + // display decimal places. The cell reads both off the ROW + // (`useQuantityUnit`), so a grid not showing the code drew the + // number with no unit. The same two gates as the harvests above. + const quantityUnitFields = declared + ? shownQuantityUnitReads(shownColumns.filter(passesProjectionGate), declared as Record) + .filter((f) => isProjectableField(f, declared as Record)) + .filter((f) => passesProjectionGate(f)) + : []; // [objectui#13107] The object's DECLARED name field. The bulk // confirm step names each affected record from the row this // projection fetched (`getRecordDisplayName`, ADR-0079), so a @@ -515,7 +525,7 @@ export function useObjectGridRowLoad({ : []; // A UNION, never an append: a grouping field that IS also a column // must not produce a duplicate `$select` entry. - const extraFields = [...predicateFields, ...groupingFields, ...concurrencyFields, ...rowColorFields, ...deadlineFields, ...referenceViaFields, ...dependsOnFields, ...nameFields, ...recordCurrencyFields]; + const extraFields = [...predicateFields, ...groupingFields, ...concurrencyFields, ...rowColorFields, ...deadlineFields, ...referenceViaFields, ...dependsOnFields, ...nameFields, ...recordCurrencyFields, ...quantityUnitFields]; const withHarvestedFields = (list: any[]): any[] => { if (extraFields.length === 0) return list; const names = new Set(list.map((f: any) => columnIdentity(f))); diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 36e5278a329..a7d9000a1f2 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -64,7 +64,7 @@ import { useDensityMode, resolveInlineAriaProps } from '@object-ui/react'; import type { DataTableSchema, DependsOnInput, ListViewSchema, ObjectMapConfig } from '@object-ui/types'; import { AUDIT_FIELD_NAMES, detectStatusField, isSystemManagedField } from '@object-ui/types'; import { usePullToRefresh } from '@object-ui/mobile'; -import { type ListViewVisualization, resolveConditionalFormatting, buildExpandFields, buildExportFileName, resolveAffordance, isObjectExportOffered, type SchemaLike, partitionRowsByPredicate, normalizeListViewSchema, isListViewVisualization, rowHeightToDensityMode, mergeFilterNodes, toFilterNodeSafely, FilterOperatorError, columnIdentity, collectPredicateFieldRefs, collectGroupingFieldRefs, listViewPredicates, PLATFORM_RECORD_COLUMNS, EXPANDABLE_FIELD_TYPES, UNMATERIALIZED_FIELD_TYPES, readObjectSortability, isPlatformSortableField, leadWithNameField, filterPlatformSortableSort, applyNonGridRowCeiling, type NonGridCeilingResult, resolveNameField, declaredNameField, resolveDependsOnFields, GANTT_CONFIG_SPELLING, kanbanDeclaredLanes, csvBlob, readWithheldFieldNames, refersToWithheldField, withHeaderSortPick } from '@object-ui/core'; +import { type ListViewVisualization, resolveConditionalFormatting, buildExpandFields, buildExportFileName, resolveAffordance, isObjectExportOffered, type SchemaLike, partitionRowsByPredicate, normalizeListViewSchema, isListViewVisualization, rowHeightToDensityMode, mergeFilterNodes, toFilterNodeSafely, FilterOperatorError, columnIdentity, collectPredicateFieldRefs, collectGroupingFieldRefs, listViewPredicates, PLATFORM_RECORD_COLUMNS, EXPANDABLE_FIELD_TYPES, UNMATERIALIZED_FIELD_TYPES, readObjectSortability, isPlatformSortableField, leadWithNameField, filterPlatformSortableSort, applyNonGridRowCeiling, type NonGridCeilingResult, resolveNameField, declaredNameField, resolveDependsOnFields, GANTT_CONFIG_SPELLING, kanbanDeclaredLanes, csvBlob, readWithheldFieldNames, refersToWithheldField, withHeaderSortPick, shownQuantityUnitReads } from '@object-ui/core'; import { useObjectLabel, useSafeFieldLabel, createSafeTranslation, useDisplayLocale, pickLocalized, recordCurrencyField, recordCurrencyReadField } from '@object-ui/i18n'; // Two resolvers, two vocabularies — the repo spells the distinction into the // NAMES (objectui#4167). `resolveInlineI18nLabel` is the spec's own @@ -4377,6 +4377,15 @@ export const ListView = React.forwardRef(({ if (!read.expand) addSpeculative(read.field); } + // [ADR-0158] A shown quantity's unit: a `record`-mode quantity's code + // field, and the row's organization, which picks the unit's display + // decimal places (`useQuantityUnit` reads both off the row). The + // code field through the speculative gate; `organization_id` is a + // platform column every object carries but none declares. + for (const f of shownQuantityUnitReads(schema.columns, objectDef?.fields)) { + addPredicateField(f); + } + // View-specific runtime fields. Each non-grid view binds to one // or more record fields (groupBy for kanban, dates for calendar/ // timeline/gantt, image/title for gallery). Without these in the diff --git a/ui/packages/plugin-list/src/__tests__/ListView.quantityUnit-35490.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.quantityUnit-35490.test.tsx new file mode 100644 index 00000000000..6ec41c96134 --- /dev/null +++ b/ui/packages/plugin-list/src/__tests__/ListView.quantityUnit-35490.test.tsx @@ -0,0 +1,82 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35490 (ADR-0158 R1 display), in the list view (the console's + * list host): a `record`-mode quantity reads its row's code even when the code + * column is not shown, so the list's own read carries the code field and the + * row's organization. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import * as React from 'react'; +import { render, screen, waitFor, cleanup } from '@testing-library/react'; +import { LocalizationProvider } from '@object-ui/i18n'; +import { registerAllFields } from '@object-ui/fields'; +import { ActionProvider, SchemaRendererProvider } from '@object-ui/react'; +import '@object-ui/plugin-grid'; +import { ListView } from '../ListView'; + +registerAllFields(); +afterEach(cleanup); + +const FIELDS = { + name: { name: 'name', type: 'text', label: 'Line' }, + qty: { name: 'qty', type: 'number', label: 'Qty', unitConfig: { unitMode: 'record', unitField: 'unit_code' } }, + unit_code: { name: 'unit_code', type: 'text', label: 'Unit' }, +}; +const RAW = [ + { id: 'l1', name: 'L1', qty: 4, unit_code: 'BOX_12', organization_id: 'org_a' }, + { id: 'l2', name: 'L2', qty: 1.5, unit_code: 'GRM', organization_id: 'org_b' }, +]; + +function source() { + const calls: Array<{ object: string; params: Record }> = []; + const ds = { + find: async (object: string, p: Record) => { + calls.push({ object, params: p }); + if (object === 'sys_unit') return { data: [{ code: 'BOX_12', label: 'Box of 12', decimal_places: 1, retired: false, organization_id: 'org_a' }] }; + if (object === 'sys_standard_unit_setting') { + return { data: [{ code: 'GRM', decimal_places: 3, organization_id: 'org_a' }, { code: 'GRM', decimal_places: 0, organization_id: 'org_b' }] }; + } + const sel = Array.isArray(p?.$select) ? (p.$select as string[]) : undefined; + const data = RAW.map((r) => (sel ? Object.fromEntries(Object.entries(r).filter(([k]) => k === 'id' || sel.includes(k))) : r)); + return { data, total: data.length }; + }, + findOne: async () => null, + create: async () => ({}), + update: async () => ({}), + delete: async () => true, + getObjectSchema: async () => ({ name: 'line', fields: FIELDS }), + }; + return { ds, calls }; +} + +describe('list view: a quantity with its unit column not shown (objectstack#35490)', () => { + it("reads each row's own unit and organization, so the read carries both", async () => { + const { ds, calls } = source(); + render( + + + + + + + , + ); + await waitFor(() => expect(screen.getByText('L1')).toBeInTheDocument(), { timeout: 8000 }); + await waitFor(() => { + const rows = [...document.querySelectorAll('tbody tr')].map((tr) => (tr.textContent ?? '').replace(/ /g, ' ')); + expect(rows[0]).toContain('4.0 Box of 12'); + // The row of organization B: B's setting of 0 places, not A's of 3. + expect(rows[1]).toContain('2 g'); + }); + const read = calls.find((c) => c.object === 'line')!; + expect(read.params.$select).toEqual(expect.arrayContaining(['unit_code', 'organization_id'])); + }); +}); diff --git a/ui/packages/types/src/field-types.ts b/ui/packages/types/src/field-types.ts index 65dec22ef54..8a66209c6ee 100644 --- a/ui/packages/types/src/field-types.ts +++ b/ui/packages/types/src/field-types.ts @@ -256,6 +256,13 @@ export type FieldConstraints = { */ export interface TextFieldMetadata extends BaseFieldMetadata { type: 'text'; + /** + * A unit-code field's declaration — `@objectstack/spec`'s + * `FieldSchema.unitConfig`, typed BY REFERENCE (ADR-0158 Open item 8): + * `{ unitMode: 'code' }` on a `text` field that holds a unit code with no + * quantity beside it. Its display draws the code's label. + */ + unitConfig?: SpecField['unitConfig']; /** * Minimum character length — `@objectstack/spec`'s `FieldSchema.minLength`, * typed BY REFERENCE (objectui#11070). The form's validation rules @@ -472,6 +479,14 @@ export interface RichtextFieldMetadata extends BaseFieldMetadata { */ export interface NumberFieldMetadata extends BaseFieldMetadata { type: 'number'; + /** + * The quantity's unit — `@objectstack/spec`'s `FieldSchema.unitConfig`, + * typed BY REFERENCE (ADR-0158 U4): `{ unitMode: 'fixed', unit }` or + * `{ unitMode: 'record', unitField }`. The display faces draw the number with + * its unit's label and display decimal places through `QuantityText` + * (`@object-ui/fields`); the stored value stays a bare number. + */ + unitConfig?: SpecField['unitConfig']; min?: number; max?: number; /** Total number of digits (the `p` in a `decimal(p, s)` column). Not a display setting. */ From c0f137c609b0a779fdb6d6a4f1673f530834c02b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 04:21:17 +0000 Subject: [PATCH 02/13] docs(fields): document quantity display; export its pieces; regenerate zh-Hant (#35490) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXM7nqtiQ3M9JqGAqL --- content/docs/frontend/fields.mdx | 27 +++++++++++++++++++++++++ ui/packages/fields/README.md | 19 +++++++++++++++++ ui/packages/fields/src/index.tsx | 10 +++++++++ ui/packages/i18n/src/locales/zh-Hant.ts | 22 ++++++++++---------- 4 files changed, 67 insertions(+), 11 deletions(-) diff --git a/content/docs/frontend/fields.mdx b/content/docs/frontend/fields.mdx index ea8d2de30ed..375547e253e 100644 --- a/content/docs/frontend/fields.mdx +++ b/content/docs/frontend/fields.mdx @@ -84,6 +84,33 @@ ObjectUI comes with built-in support for the standard [ObjectStack Protocol](htt | `user` | Person picker — searches the `sys_user` object (a lookup specialized to users) | | `owner` | Record owner — a `user` field, typically read-only and stamped with the current user | +## Quantities with a unit + +A `number` field that declares `unitConfig` is a quantity, and every face draws it with its unit: grid and +list cells, the record page, the quick-look panel, related lists, and the form (read-only, and beside the +edited box). + +```json +{ "name": "qty", "type": "number", "unitConfig": { "unitMode": "record", "unitField": "unit_code" } } +``` + +- **Which unit.** `unitMode: 'fixed'` shows its one `unit`. `unitMode: 'record'` shows the code the row's + `unitField` holds; the list, grid and related-list reads fetch that field, and the row's + `organization_id`, even when no column shows them. A `text` field declaring `unitMode: 'code'` shows the + code's label. +- **Which label.** A standard code (`KGM`, `H87`, …) shows the platform's label in the reader's language, + from the `units.standard` table of each language pack. An organization's own code shows its `sys_unit` + label. +- **How many decimal places.** A standard code takes the organization's `sys_standard_unit_setting` row, + and an organization code its `sys_unit.decimal_places`, always the row of the record's own + organization. The field's `scale` is the ceiling. With no unit setting, the field's own width applies. + Nothing is rounded when the record is saved. +- **The bare code.** A retired organization unit, or one whose row the reader may not read, shows its code + with no label. + +The unit rows are read through the data source of the surrounding `SchemaRendererProvider`, once per +session. + ## How the Console draws field metadata What a field's metadata makes the Console draw (number inputs, polymorphic record pointers, diff --git a/ui/packages/fields/README.md b/ui/packages/fields/README.md index 5c4ac4ff5da..74a31eebfc0 100644 --- a/ui/packages/fields/README.md +++ b/ui/packages/fields/README.md @@ -106,6 +106,25 @@ correct". User-facing wording lives in [the fields guide](https://objectstack.ai/docs/frontend/fields). The measured browser vs happy-dom matrix is in `src/__tests__/numberInputBrowserReadings.ts`. +### Quantities with a unit (`unitConfig`) + +A `number` field declaring `unitConfig` (ADR-0158) is drawn as a quantity by `NumberCellRenderer` and by +`NumberField`'s read-only branch, through one component, `QuantityText`, so a cell and a read-only form show +one quantity identically. The pieces: + +- `useQuantityUnit(field, record, value?)` resolves the unit: the code (`fixed`, the row's `unitField`, or a + `code`-mode field's own value), its label and its display decimal places, reading `sys_unit` and + `sys_standard_unit_setting` through the `SchemaRendererContext` data source once per adapter. A refused + read leaves the code bare. +- `formatQuantity(value, field, unit, locale)` is the one formatter. It returns `{ text, number, unit, + hidden }`; `hidden` says the stored value has more places than are shown. The field's `scale` caps the + unit's places. +- The resolution itself (`resolveQuantityUnit`, `pickRowForOrganization`, `shownQuantityUnitReads`) is + pure and lives in `@object-ui/core`. + +A cell or widget only sees a `record`-mode quantity's code when its host hands it the row +(`dependentValues`). The grid, list, detail and form hosts do. + ### Rendering form field widgets outside the form The full widget surface is exported for consumers that render field widgets diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index 1c507502a14..cefc6eaa7d0 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -624,6 +624,16 @@ export { formatCurrency }; */ export { formatNumberFieldValue }; +/** + * A quantity with its unit (ADR-0158): the face `NumberCellRenderer` and + * `NumberField`'s read-only branch share, the hook that resolves the unit, and + * the one formatter. Exported so a host face that draws a quantity outside a + * cell makes the same calls. + */ +export { QuantityText, UnitCodeText }; +export { formatQuantity, quantityDisplayPlaces, type QuantityDisplay } from './widgets/quantity-format.js'; +export { useQuantityUnit, useStandardUnitLabel, readUnitCatalog } from './widgets/useQuantityUnit.js'; + /** * Format currency value in compact form for mobile display. * E.g., $150,000 → $150K, $1,200,000 → $1.2M diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index f344bc2a648..8a71b096e75 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -285,32 +285,32 @@ const zhHant = { // drawn beside a quantity; keyed by the code in exact uppercase. units: { standard: { - KGM: '公斤', + KGM: '千克', GRM: '克', MGM: '毫克', - TNE: '公噸', + TNE: '噸', LBR: '磅', ONZ: '盎司', - MTR: '公尺', + MTR: '米', MMT: '毫米', - CMT: '公分', - KMT: '公里', + CMT: '釐米', + KMT: '千米', INH: '英寸', FOT: '英尺', YRD: '碼', - MTK: '平方公尺', - CMK: '平方公分', + MTK: '平方米', + CMK: '平方釐米', MMK: '平方毫米', FTK: '平方英尺', - MTQ: '立方公尺', - LTR: '公升', + MTQ: '立方米', + LTR: '升', MLT: '毫升', GLL: '加侖', SEC: '秒', MIN: '分鐘', HUR: '小時', DAY: '天', - WEE: '週', + WEE: '周', H87: '件', PR: '雙', DZN: '打', @@ -323,7 +323,7 @@ const zhHant = { XCR: '板條箱', XDR: '桶', XPK: '包', - XPX: '棧板', + XPX: '托盤', XRO: '卷', XSA: '麻袋', }, From 440390b1e67c4c3514573c956a04cc719c6b2ac8 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 04:40:38 +0000 Subject: [PATCH 03/13] test(plugin-grid): pin the standalone grid's degraded quantity shape (#35490) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXM7nqtiQ3M9JqGAqL --- .../__tests__/gridQuantityUnit-35490.test.tsx | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/ui/packages/plugin-grid/src/__tests__/gridQuantityUnit-35490.test.tsx b/ui/packages/plugin-grid/src/__tests__/gridQuantityUnit-35490.test.tsx index 4f4fa18f878..ccab4162355 100644 --- a/ui/packages/plugin-grid/src/__tests__/gridQuantityUnit-35490.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/gridQuantityUnit-35490.test.tsx @@ -92,3 +92,23 @@ describe('object grid: a quantity with its unit (objectstack#35490)', () => { expect(read.params.$select).toEqual(expect.arrayContaining(['unit_code', 'organization_id'])); }); }); + +describe('object grid with no SchemaRendererProvider: the known degraded shape (objectstack#35490)', () => { + it('reads no unit rows, so a standard unit keeps its label at the field width and an org unit shows its code, with no error', async () => { + const { ds, calls } = source(); + render( + + + + + , + ); + await waitFor(() => expect(screen.getByText('L1')).toBeInTheDocument()); + const rows = rowTexts(); + expect(rows[0]).toContain('4 BOX_12'); + expect(rows[0]).toContain('1.25 kg'); + expect(rows[1]).toContain('1.5 g'); + expect(calls.some((c) => c.object === 'sys_unit' || c.object === 'sys_standard_unit_setting')).toBe(false); + expect(screen.queryByRole('alert')).toBeNull(); + }); +}); From d14d38c0524703ee43ee9320f588198b0fb12a5a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:41:43 +0000 Subject: [PATCH 04/13] feat(units): serve standard unit names, round quantities at render (#35490) Apply the rulings on ADR-0158 Open item 6 and L2: - @objectstack/spec gains STANDARD_UNIT_NAMES, the English base name of every standard code, and standardUnitName (own-property, exact case). - platform-objects bundles serve each code's name per locale as messages.standardUnit; English is copied from the spec base. - The UI reads app.messages.standardUnit and falls back to the spec base; its own per-locale tables are removed. - A quantity rounds at render, half away from zero, at fixed width min(unit places, field scale); stored values, totals, exports, API and MCP stay exact. No marker. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXM7nqtiQ3M9JqGAqL --- .changeset/35490-quantity-unit-display.md | 9 +- content/docs/frontend/fields.mdx | 12 +- .../src/apps/translations/ar.ts | 3 + .../src/apps/translations/de.ts | 3 + .../src/apps/translations/en.ts | 3 + .../src/apps/translations/es-ES.ts | 3 + .../src/apps/translations/fr.ts | 3 + .../src/apps/translations/ja-JP.ts | 3 + .../src/apps/translations/ko.ts | 3 + .../src/apps/translations/pt-BR.ts | 3 + .../src/apps/translations/ru.ts | 3 + .../translations/standard-unit-names.test.ts | 39 ++ .../apps/translations/standard-unit-names.ts | 471 ++++++++++++++++++ .../src/apps/translations/zh-CN.ts | 3 + .../src/apps/translations/zh-Hant.ts | 3 + packages/spec/api-surface/data.json | 2 + packages/spec/src/data/standard-units.test.ts | 31 ++ packages/spec/src/data/standard-units.ts | 65 +++ .../__tests__/quantityDisplay-35490.test.tsx | 19 +- .../fields/src/widgets/quantity-format.ts | 17 +- .../fields/src/widgets/useQuantityUnit.ts | 21 +- ui/packages/i18n/src/locales/ar.ts | 47 -- ui/packages/i18n/src/locales/de.ts | 47 -- ui/packages/i18n/src/locales/en.ts | 47 -- ui/packages/i18n/src/locales/es.ts | 47 -- ui/packages/i18n/src/locales/fr.ts | 47 -- ui/packages/i18n/src/locales/ja.ts | 47 -- ui/packages/i18n/src/locales/ko.ts | 47 -- ui/packages/i18n/src/locales/pt-BR.ts | 47 -- ui/packages/i18n/src/locales/ru.ts | 47 -- ui/packages/i18n/src/locales/zh-Hans.ts | 47 -- ui/packages/i18n/src/locales/zh-Hant.ts | 47 -- .../quantityUnitRelay-35490.test.tsx | 2 +- .../__tests__/gridQuantityUnit-35490.test.tsx | 8 +- .../ListView.quantityUnit-35490.test.tsx | 2 +- 35 files changed, 694 insertions(+), 554 deletions(-) create mode 100644 packages/platform-objects/src/apps/translations/standard-unit-names.test.ts create mode 100644 packages/platform-objects/src/apps/translations/standard-unit-names.ts diff --git a/.changeset/35490-quantity-unit-display.md b/.changeset/35490-quantity-unit-display.md index 7392d998fef..bdcb9885d12 100644 --- a/.changeset/35490-quantity-unit-display.md +++ b/.changeset/35490-quantity-unit-display.md @@ -1,8 +1,9 @@ --- +'@objectstack/spec': patch +'@objectstack/platform-objects': patch '@object-ui/core': patch '@object-ui/fields': patch '@object-ui/types': patch -'@object-ui/i18n': patch '@object-ui/components': patch '@object-ui/plugin-grid': patch '@object-ui/plugin-list': patch @@ -11,12 +12,12 @@ feat(fields): a quantity displays with its unit's label and display decimal places in grid, form and detail (ADR-0158 R1 display) -Clause-②: no +Clause-②: yes (widening) Metadata-protocol: none A `number` field that declares `unitConfig` now draws its unit beside the number on every face: grid and list cells, the record page (sections, highlights, the quick-look panel, related lists), and the form, both read-only and beside the edited box. A `fixed` quantity shows its one unit; a `record` quantity shows the unit its row's code field holds, and the list, grid and related-list reads fetch that field (and the row's organization) even when no column shows it. A `text` field declaring `unitConfig: { unitMode: 'code' }` shows the code's label. -- A standard code (`KGM`, `H87`, …) shows the platform's label in the reader's locale, from a new `units.standard` table in every language pack; an organization code shows its `sys_unit` label. -- Decimal places: a standard code takes its organization's `sys_standard_unit_setting` row, an organization code its `sys_unit.decimal_places`. The row is the record's own organization's, never merely the first one returned. The field's `scale` is the ceiling (ADR-0158 L4), and nothing is rounded at write: footers, exports and the API keep the exact value. +- A standard code (`KGM`, `H87`, …) shows the platform's name for it in the reader's locale; an organization code shows its `sys_unit` label. `@objectstack/spec` now exports the English base name of every standard code, `STANDARD_UNIT_NAMES` and `standardUnitName(code)`, beside `STANDARD_UNITS`. `@objectstack/platform-objects` serves each locale's names through the i18n service, as `messages.standardUnit` in every platform bundle, and a reader without a translation falls back to the English base. +- Decimal places: a standard code takes its organization's `sys_standard_unit_setting` row, an organization code its `sys_unit.decimal_places`. The row is the record's own organization's, never merely the first one returned. The field's `scale` is the ceiling (ADR-0158 L4). The number is drawn at that fixed width, rounded half away from zero (ADR-0158 Open item 6, ruled A): `1.5` beside a unit of 0 places reads `2`. Only the display rounds; nothing is rounded at write, and footers, exports and the API keep the exact value. - A retired organization unit, and a unit whose row the reader may not read (an external member holds no `sys_unit` read), show the bare code, never an error. - One resolver (`resolveQuantityUnit` in `@object-ui/core`) and one formatter (`formatQuantity` in `@object-ui/fields`) serve every face. diff --git a/content/docs/frontend/fields.mdx b/content/docs/frontend/fields.mdx index 375547e253e..2e235f25857 100644 --- a/content/docs/frontend/fields.mdx +++ b/content/docs/frontend/fields.mdx @@ -98,13 +98,15 @@ edited box). `unitField` holds; the list, grid and related-list reads fetch that field, and the row's `organization_id`, even when no column shows them. A `text` field declaring `unitMode: 'code'` shows the code's label. -- **Which label.** A standard code (`KGM`, `H87`, …) shows the platform's label in the reader's language, - from the `units.standard` table of each language pack. An organization's own code shows its `sys_unit` - label. +- **Which label.** A standard code (`KGM`, `H87`, …) shows the platform's name for it in the reader's + language, served by the platform's i18n service (`messages.standardUnit`), falling back to the + English name in `@objectstack/spec` (`STANDARD_UNIT_NAMES`). An organization's own code shows its + `sys_unit` label. - **How many decimal places.** A standard code takes the organization's `sys_standard_unit_setting` row, and an organization code its `sys_unit.decimal_places`, always the row of the record's own - organization. The field's `scale` is the ceiling. With no unit setting, the field's own width applies. - Nothing is rounded when the record is saved. + organization. The field's `scale` is the ceiling. The number is drawn at that fixed width, rounded half + away from zero (`1.5` beside a unit of 0 places reads `2`). With no unit setting, the field's own width + applies. Only the display rounds: the stored value, totals, exports and the API keep the exact value. - **The bare code.** A retired organization unit, or one whose row the reader may not read, shows its code with no label. diff --git a/packages/platform-objects/src/apps/translations/ar.ts b/packages/platform-objects/src/apps/translations/ar.ts index 910ef092d23..d7a834c8d21 100644 --- a/packages/platform-objects/src/apps/translations/ar.ts +++ b/packages/platform-objects/src/apps/translations/ar.ts @@ -2,12 +2,15 @@ import type { TranslationData } from '@objectstack/spec/system'; import { arObjects } from './ar.objects.generated.js'; +import { standardUnitMessages } from './standard-unit-names.js'; /** * العربية (ar) — Setup App Translations */ export const ar: TranslationData = { objects: arObjects, + // ADR-0158 L2 (2A): each standard unit code's name (`standard-unit-names.ts`). + messages: standardUnitMessages('ar'), apps: { account: { label: 'الحساب', diff --git a/packages/platform-objects/src/apps/translations/de.ts b/packages/platform-objects/src/apps/translations/de.ts index da7ea408f15..045eb6894bd 100644 --- a/packages/platform-objects/src/apps/translations/de.ts +++ b/packages/platform-objects/src/apps/translations/de.ts @@ -2,12 +2,15 @@ import type { TranslationData } from '@objectstack/spec/system'; import { deObjects } from './de.objects.generated.js'; +import { standardUnitMessages } from './standard-unit-names.js'; /** * Deutsch (de) — Setup App Translations */ export const de: TranslationData = { objects: deObjects, + // ADR-0158 L2 (2A): each standard unit code's name (`standard-unit-names.ts`). + messages: standardUnitMessages('de'), apps: { account: { label: 'Konto', diff --git a/packages/platform-objects/src/apps/translations/en.ts b/packages/platform-objects/src/apps/translations/en.ts index 22a8e541aea..be6aae9cf7f 100644 --- a/packages/platform-objects/src/apps/translations/en.ts +++ b/packages/platform-objects/src/apps/translations/en.ts @@ -2,6 +2,7 @@ import type { TranslationData } from '@objectstack/spec/system'; import { enObjects } from './en.objects.generated.js'; +import { standardUnitMessages } from './standard-unit-names.js'; /** * English (en) — Setup App Translations @@ -23,6 +24,8 @@ import { enObjects } from './en.objects.generated.js'; */ export const en: TranslationData = { objects: enObjects, + // ADR-0158 L2 (2A): each standard unit code's name (`standard-unit-names.ts`). + messages: standardUnitMessages('en'), apps: { account: { label: 'Account', diff --git a/packages/platform-objects/src/apps/translations/es-ES.ts b/packages/platform-objects/src/apps/translations/es-ES.ts index 2afc7302f88..8d0ad4921df 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.ts @@ -2,12 +2,15 @@ import type { TranslationData } from '@objectstack/spec/system'; import { esESObjects } from './es-ES.objects.generated.js'; +import { standardUnitMessages } from './standard-unit-names.js'; /** * Español (es-ES) — Setup App Translations */ export const esES: TranslationData = { objects: esESObjects, + // ADR-0158 L2 (2A): each standard unit code's name (`standard-unit-names.ts`). + messages: standardUnitMessages('es-ES'), apps: { account: { label: 'Cuenta', diff --git a/packages/platform-objects/src/apps/translations/fr.ts b/packages/platform-objects/src/apps/translations/fr.ts index 6fbb39c94b9..a3b8832a586 100644 --- a/packages/platform-objects/src/apps/translations/fr.ts +++ b/packages/platform-objects/src/apps/translations/fr.ts @@ -2,12 +2,15 @@ import type { TranslationData } from '@objectstack/spec/system'; import { frObjects } from './fr.objects.generated.js'; +import { standardUnitMessages } from './standard-unit-names.js'; /** * Français (fr) — Setup App Translations */ export const fr: TranslationData = { objects: frObjects, + // ADR-0158 L2 (2A): each standard unit code's name (`standard-unit-names.ts`). + messages: standardUnitMessages('fr'), apps: { account: { label: 'Compte', diff --git a/packages/platform-objects/src/apps/translations/ja-JP.ts b/packages/platform-objects/src/apps/translations/ja-JP.ts index 73c71595823..abd13efc8ad 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.ts @@ -2,12 +2,15 @@ import type { TranslationData } from '@objectstack/spec/system'; import { jaJPObjects } from './ja-JP.objects.generated.js'; +import { standardUnitMessages } from './standard-unit-names.js'; /** * 日本語 (ja-JP) — Setup App Translations */ export const jaJP: TranslationData = { objects: jaJPObjects, + // ADR-0158 L2 (2A): each standard unit code's name (`standard-unit-names.ts`). + messages: standardUnitMessages('ja-JP'), apps: { account: { label: 'アカウント', diff --git a/packages/platform-objects/src/apps/translations/ko.ts b/packages/platform-objects/src/apps/translations/ko.ts index bfa011991f9..4422134badf 100644 --- a/packages/platform-objects/src/apps/translations/ko.ts +++ b/packages/platform-objects/src/apps/translations/ko.ts @@ -2,12 +2,15 @@ import type { TranslationData } from '@objectstack/spec/system'; import { koObjects } from './ko.objects.generated.js'; +import { standardUnitMessages } from './standard-unit-names.js'; /** * 한국어 (ko) — Setup App Translations */ export const ko: TranslationData = { objects: koObjects, + // ADR-0158 L2 (2A): each standard unit code's name (`standard-unit-names.ts`). + messages: standardUnitMessages('ko'), apps: { account: { label: '계정', diff --git a/packages/platform-objects/src/apps/translations/pt-BR.ts b/packages/platform-objects/src/apps/translations/pt-BR.ts index 7013ba22562..904add3f7e0 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.ts @@ -2,12 +2,15 @@ import type { TranslationData } from '@objectstack/spec/system'; import { ptBRObjects } from './pt-BR.objects.generated.js'; +import { standardUnitMessages } from './standard-unit-names.js'; /** * Português do Brasil (pt-BR) — Setup App Translations */ export const ptBR: TranslationData = { objects: ptBRObjects, + // ADR-0158 L2 (2A): each standard unit code's name (`standard-unit-names.ts`). + messages: standardUnitMessages('pt-BR'), apps: { account: { label: 'Conta', diff --git a/packages/platform-objects/src/apps/translations/ru.ts b/packages/platform-objects/src/apps/translations/ru.ts index bcf1f070c53..eb2b6588a1e 100644 --- a/packages/platform-objects/src/apps/translations/ru.ts +++ b/packages/platform-objects/src/apps/translations/ru.ts @@ -2,12 +2,15 @@ import type { TranslationData } from '@objectstack/spec/system'; import { ruObjects } from './ru.objects.generated.js'; +import { standardUnitMessages } from './standard-unit-names.js'; /** * Русский (ru) — Setup App Translations */ export const ru: TranslationData = { objects: ruObjects, + // ADR-0158 L2 (2A): each standard unit code's name (`standard-unit-names.ts`). + messages: standardUnitMessages('ru'), apps: { account: { label: 'Учётная запись', diff --git a/packages/platform-objects/src/apps/translations/standard-unit-names.test.ts b/packages/platform-objects/src/apps/translations/standard-unit-names.test.ts new file mode 100644 index 00000000000..87b5c7121a2 --- /dev/null +++ b/packages/platform-objects/src/apps/translations/standard-unit-names.test.ts @@ -0,0 +1,39 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, it, expect } from 'vitest'; +import { STANDARD_UNITS, STANDARD_UNIT_NAMES } from '@objectstack/spec/data'; +import { STANDARD_UNIT_NAME_TRANSLATIONS, standardUnitMessageKey, standardUnitMessages } from './standard-unit-names'; +import { en, zhCN, jaJP, esES, zhHant, ar, fr, ptBR, ru, de, ko } from './index'; + +/** + * ADR-0158 L2 (2A): the platform serves a name for every standard unit code in + * every bundle locale (objectstack#35490), as `messages.standardUnit`. + */ +const BUNDLES = { en, 'zh-CN': zhCN, 'ja-JP': jaJP, 'es-ES': esES, 'zh-Hant': zhHant, ar, fr, 'pt-BR': ptBR, ru, de, ko }; +const codes = Object.keys(STANDARD_UNITS); + +describe('standard unit names in the platform bundles (ADR-0158 L2, objectstack#35490)', () => { + it('translates exactly the codes of STANDARD_UNITS in every non-English locale', () => { + for (const [locale, names] of Object.entries(STANDARD_UNIT_NAME_TRANSLATIONS)) { + expect(Object.keys(names), locale).toEqual(codes); + for (const [code, name] of Object.entries(names)) expect(name.trim(), `${locale} ${code}`).not.toBe(''); + } + expect(Object.keys(STANDARD_UNIT_NAME_TRANSLATIONS).sort()).toEqual(Object.keys(BUNDLES).filter((l) => l !== 'en').sort()); + }); + + it('serves every code in every bundle, under a single-segment message key', () => { + for (const [locale, bundle] of Object.entries(BUNDLES)) { + const messages = bundle.messages ?? {}; + for (const code of codes) { + const key = standardUnitMessageKey(code); + expect(key).not.toContain('.'); + expect(messages[key], `${locale} ${code}`).toBeTruthy(); + } + } + }); + + it('copies the English bundle from the spec base, never re-typed', () => { + for (const code of codes) expect(en.messages?.[standardUnitMessageKey(code)]).toBe(STANDARD_UNIT_NAMES[code]); + expect(standardUnitMessages('zh-CN')[standardUnitMessageKey('KGM')]).toBe('千克'); + }); +}); diff --git a/packages/platform-objects/src/apps/translations/standard-unit-names.ts b/packages/platform-objects/src/apps/translations/standard-unit-names.ts new file mode 100644 index 00000000000..c7386a6410e --- /dev/null +++ b/packages/platform-objects/src/apps/translations/standard-unit-names.ts @@ -0,0 +1,471 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The platform's per-locale name of every standard unit code (ADR-0158 L2, + * 2A: "Standard U1 codes get a platform-shipped per-locale label table"), + * served by the i18n service in each platform bundle's `messages` group. + * + * - The English base is `STANDARD_UNIT_NAMES` in `@objectstack/spec`, read + * here and never re-typed, so the `en` bundle is a copy of the source. + * - Each message key is single-segment (`standardUnitKGM`). Both i18n + * implementations resolve a dotted key by walking nested objects, so a flat + * `messages` key holding a dot would never resolve; the same rule as + * plugin-audit's `messages.ts`. + * - A reader asks `messages.standardUnit` and falls back to the spec's + * English name: the UI's quantity display (`useStandardUnitLabel` in + * `@object-ui/fields`), an export, an MCP tool. + * + * A pin test holds every locale below to exactly the codes of + * `STANDARD_UNITS`. + */ + +import { STANDARD_UNIT_NAMES } from '@objectstack/spec/data'; + +/** The `messages` key of a standard unit code's name. */ +export function standardUnitMessageKey(code: string): string { + return `standardUnit${code}`; +} + +/** The translated names, per platform bundle locale, keyed by code. */ +export const STANDARD_UNIT_NAME_TRANSLATIONS: Readonly>>> = { + 'zh-CN': { + KGM: "千克", + GRM: "克", + MGM: "毫克", + TNE: "吨", + LBR: "磅", + ONZ: "盎司", + MTR: "米", + MMT: "毫米", + CMT: "厘米", + KMT: "千米", + INH: "英寸", + FOT: "英尺", + YRD: "码", + MTK: "平方米", + CMK: "平方厘米", + MMK: "平方毫米", + FTK: "平方英尺", + MTQ: "立方米", + LTR: "升", + MLT: "毫升", + GLL: "美制加仑", + SEC: "秒", + MIN: "分钟", + HUR: "小时", + DAY: "天", + WEE: "周", + H87: "件", + PR: "双", + DZN: "打", + XBG: "袋", + XBE: "捆", + XBO: "瓶", + XBX: "盒", + XCT: "纸箱", + XCS: "箱", + XCR: "板条箱", + XDR: "桶", + XPK: "包", + XPX: "托盘", + XRO: "卷", + XSA: "麻袋", + }, + 'zh-Hant': { + KGM: "公斤", + GRM: "公克", + MGM: "毫克", + TNE: "公噸", + LBR: "磅", + ONZ: "盎司", + MTR: "公尺", + MMT: "公釐", + CMT: "公分", + KMT: "公里", + INH: "英寸", + FOT: "英尺", + YRD: "碼", + MTK: "平方公尺", + CMK: "平方公分", + MMK: "平方公釐", + FTK: "平方英尺", + MTQ: "立方公尺", + LTR: "公升", + MLT: "毫升", + GLL: "美制加侖", + SEC: "秒", + MIN: "分鐘", + HUR: "小時", + DAY: "天", + WEE: "週", + H87: "件", + PR: "雙", + DZN: "打", + XBG: "袋", + XBE: "捆", + XBO: "瓶", + XBX: "盒", + XCT: "紙箱", + XCS: "箱", + XCR: "板條箱", + XDR: "桶", + XPK: "包", + XPX: "棧板", + XRO: "卷", + XSA: "麻袋", + }, + 'ja-JP': { + KGM: "キログラム", + GRM: "グラム", + MGM: "ミリグラム", + TNE: "トン", + LBR: "ポンド", + ONZ: "オンス", + MTR: "メートル", + MMT: "ミリメートル", + CMT: "センチメートル", + KMT: "キロメートル", + INH: "インチ", + FOT: "フィート", + YRD: "ヤード", + MTK: "平方メートル", + CMK: "平方センチメートル", + MMK: "平方ミリメートル", + FTK: "平方フィート", + MTQ: "立方メートル", + LTR: "リットル", + MLT: "ミリリットル", + GLL: "米ガロン", + SEC: "秒", + MIN: "分", + HUR: "時間", + DAY: "日", + WEE: "週", + H87: "個", + PR: "組", + DZN: "ダース", + XBG: "袋", + XBE: "束", + XBO: "本", + XBX: "箱", + XCT: "カートン", + XCS: "ケース", + XCR: "クレート", + XDR: "ドラム", + XPK: "包", + XPX: "パレット", + XRO: "巻", + XSA: "大袋", + }, + 'ko': { + KGM: "킬로그램", + GRM: "그램", + MGM: "밀리그램", + TNE: "톤", + LBR: "파운드", + ONZ: "온스", + MTR: "미터", + MMT: "밀리미터", + CMT: "센티미터", + KMT: "킬로미터", + INH: "인치", + FOT: "피트", + YRD: "야드", + MTK: "제곱미터", + CMK: "제곱센티미터", + MMK: "제곱밀리미터", + FTK: "제곱피트", + MTQ: "세제곱미터", + LTR: "리터", + MLT: "밀리리터", + GLL: "미국 갤런", + SEC: "초", + MIN: "분", + HUR: "시간", + DAY: "일", + WEE: "주", + H87: "개", + PR: "쌍", + DZN: "다스", + XBG: "봉지", + XBE: "묶음", + XBO: "병", + XBX: "상자", + XCT: "카톤", + XCS: "케이스", + XCR: "크레이트", + XDR: "드럼", + XPK: "포장", + XPX: "팔레트", + XRO: "롤", + XSA: "포대", + }, + 'de': { + KGM: "Kilogramm", + GRM: "Gramm", + MGM: "Milligramm", + TNE: "Tonne", + LBR: "Pfund", + ONZ: "Unze", + MTR: "Meter", + MMT: "Millimeter", + CMT: "Zentimeter", + KMT: "Kilometer", + INH: "Zoll", + FOT: "Fuß", + YRD: "Yard", + MTK: "Quadratmeter", + CMK: "Quadratzentimeter", + MMK: "Quadratmillimeter", + FTK: "Quadratfuß", + MTQ: "Kubikmeter", + LTR: "Liter", + MLT: "Milliliter", + GLL: "US-Gallone", + SEC: "Sekunde", + MIN: "Minute", + HUR: "Stunde", + DAY: "Tag", + WEE: "Woche", + H87: "Stück", + PR: "Paar", + DZN: "Dutzend", + XBG: "Beutel", + XBE: "Bündel", + XBO: "Flasche", + XBX: "Schachtel", + XCT: "Karton", + XCS: "Kiste", + XCR: "Lattenkiste", + XDR: "Fass", + XPK: "Paket", + XPX: "Palette", + XRO: "Rolle", + XSA: "Sack", + }, + 'fr': { + KGM: "kilogramme", + GRM: "gramme", + MGM: "milligramme", + TNE: "tonne", + LBR: "livre", + ONZ: "once", + MTR: "mètre", + MMT: "millimètre", + CMT: "centimètre", + KMT: "kilomètre", + INH: "pouce", + FOT: "pied", + YRD: "yard", + MTK: "mètre carré", + CMK: "centimètre carré", + MMK: "millimètre carré", + FTK: "pied carré", + MTQ: "mètre cube", + LTR: "litre", + MLT: "millilitre", + GLL: "gallon US", + SEC: "seconde", + MIN: "minute", + HUR: "heure", + DAY: "jour", + WEE: "semaine", + H87: "pièce", + PR: "paire", + DZN: "douzaine", + XBG: "sachet", + XBE: "lot", + XBO: "bouteille", + XBX: "boîte", + XCT: "carton", + XCS: "caisse", + XCR: "cageot", + XDR: "fût", + XPK: "colis", + XPX: "palette", + XRO: "rouleau", + XSA: "sac", + }, + 'es-ES': { + KGM: "kilogramo", + GRM: "gramo", + MGM: "miligramo", + TNE: "tonelada", + LBR: "libra", + ONZ: "onza", + MTR: "metro", + MMT: "milímetro", + CMT: "centímetro", + KMT: "kilómetro", + INH: "pulgada", + FOT: "pie", + YRD: "yarda", + MTK: "metro cuadrado", + CMK: "centímetro cuadrado", + MMK: "milímetro cuadrado", + FTK: "pie cuadrado", + MTQ: "metro cúbico", + LTR: "litro", + MLT: "mililitro", + GLL: "galón estadounidense", + SEC: "segundo", + MIN: "minuto", + HUR: "hora", + DAY: "día", + WEE: "semana", + H87: "pieza", + PR: "par", + DZN: "docena", + XBG: "bolsa", + XBE: "fardo", + XBO: "botella", + XBX: "caja", + XCT: "cartón", + XCS: "estuche", + XCR: "cajón", + XDR: "bidón", + XPK: "paquete", + XPX: "palé", + XRO: "rollo", + XSA: "saco", + }, + 'pt-BR': { + KGM: "quilograma", + GRM: "grama", + MGM: "miligrama", + TNE: "tonelada", + LBR: "libra", + ONZ: "onça", + MTR: "metro", + MMT: "milímetro", + CMT: "centímetro", + KMT: "quilômetro", + INH: "polegada", + FOT: "pé", + YRD: "jarda", + MTK: "metro quadrado", + CMK: "centímetro quadrado", + MMK: "milímetro quadrado", + FTK: "pé quadrado", + MTQ: "metro cúbico", + LTR: "litro", + MLT: "mililitro", + GLL: "galão americano", + SEC: "segundo", + MIN: "minuto", + HUR: "hora", + DAY: "dia", + WEE: "semana", + H87: "peça", + PR: "par", + DZN: "dúzia", + XBG: "sacola", + XBE: "fardo", + XBO: "garrafa", + XBX: "caixa", + XCT: "caixa de papelão", + XCS: "estojo", + XCR: "engradado", + XDR: "tambor", + XPK: "pacote", + XPX: "palete", + XRO: "rolo", + XSA: "saco", + }, + 'ru': { + KGM: "килограмм", + GRM: "грамм", + MGM: "миллиграмм", + TNE: "тонна", + LBR: "фунт", + ONZ: "унция", + MTR: "метр", + MMT: "миллиметр", + CMT: "сантиметр", + KMT: "километр", + INH: "дюйм", + FOT: "фут", + YRD: "ярд", + MTK: "квадратный метр", + CMK: "квадратный сантиметр", + MMK: "квадратный миллиметр", + FTK: "квадратный фут", + MTQ: "кубический метр", + LTR: "литр", + MLT: "миллилитр", + GLL: "галлон США", + SEC: "секунда", + MIN: "минута", + HUR: "час", + DAY: "день", + WEE: "неделя", + H87: "штука", + PR: "пара", + DZN: "дюжина", + XBG: "пакет", + XBE: "связка", + XBO: "бутылка", + XBX: "коробка", + XCT: "картон", + XCS: "ящик", + XCR: "клеть", + XDR: "бочка", + XPK: "упаковка", + XPX: "поддон", + XRO: "рулон", + XSA: "мешок", + }, + 'ar': { + KGM: "كيلوغرام", + GRM: "غرام", + MGM: "ملليغرام", + TNE: "طن", + LBR: "رطل", + ONZ: "أونصة", + MTR: "متر", + MMT: "ملليمتر", + CMT: "سنتيمتر", + KMT: "كيلومتر", + INH: "بوصة", + FOT: "قدم", + YRD: "ياردة", + MTK: "متر مربع", + CMK: "سنتيمتر مربع", + MMK: "ملليمتر مربع", + FTK: "قدم مربع", + MTQ: "متر مكعب", + LTR: "لتر", + MLT: "مليلتر", + GLL: "غالون أمريكي", + SEC: "ثانية", + MIN: "دقيقة", + HUR: "ساعة", + DAY: "يوم", + WEE: "أسبوع", + H87: "قطعة", + PR: "زوج", + DZN: "دزينة", + XBG: "كيس", + XBE: "حزمة", + XBO: "زجاجة", + XBX: "علبة", + XCT: "كرتونة", + XCS: "صندوق", + XCR: "قفص", + XDR: "برميل", + XPK: "طرد", + XPX: "منصة", + XRO: "لفة", + XSA: "جوال", + }, +}; + +/** + * The `messages` entries of one platform bundle locale: the English base for + * `en`, the translated names otherwise. + */ +export function standardUnitMessages(locale: string): Record { + const names = locale === 'en' ? STANDARD_UNIT_NAMES : STANDARD_UNIT_NAME_TRANSLATIONS[locale]; + if (!names) throw new Error(`No standard unit names for locale ${locale}`); + return Object.fromEntries(Object.entries(names).map(([code, name]) => [standardUnitMessageKey(code), name])); +} diff --git a/packages/platform-objects/src/apps/translations/zh-CN.ts b/packages/platform-objects/src/apps/translations/zh-CN.ts index 89fbf78cad5..55f348c2a26 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.ts @@ -2,12 +2,15 @@ import type { TranslationData } from '@objectstack/spec/system'; import { zhCNObjects } from './zh-CN.objects.generated.js'; +import { standardUnitMessages } from './standard-unit-names.js'; /** * 简体中文 (zh-CN) — Setup App Translations */ export const zhCN: TranslationData = { objects: zhCNObjects, + // ADR-0158 L2 (2A): each standard unit code's name (`standard-unit-names.ts`). + messages: standardUnitMessages('zh-CN'), apps: { account: { label: '账户', diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.ts b/packages/platform-objects/src/apps/translations/zh-Hant.ts index fcc8f450c0c..c9bd7f21525 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.ts @@ -2,12 +2,15 @@ import type { TranslationData } from '@objectstack/spec/system'; import { zhHantObjects } from './zh-Hant.objects.generated.js'; +import { standardUnitMessages } from './standard-unit-names.js'; /** * 繁體中文 (zh-Hant) — Setup App Translations */ export const zhHant: TranslationData = { objects: zhHantObjects, + // ADR-0158 L2 (2A): each standard unit code's name (`standard-unit-names.ts`). + messages: standardUnitMessages('zh-Hant'), apps: { account: { label: '帳戶', diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 0c9a47c042e..be04bf52ac9 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -826,6 +826,7 @@ "STACK_KEY_GUIDANCE (const)", "STACK_RUNTIME_MEMBERS (const)", "STANDARD_UNITS (const)", + "STANDARD_UNIT_NAMES (const)", "STRING_STORED_COMPARAND_DOOR_FAMILIES (const)", "STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS (const)", "STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS (const)", @@ -1233,6 +1234,7 @@ "resolveUserActionTransfer (function)", "seedFile (function)", "sequenceWidth (function)", + "standardUnitName (function)", "standardUnitOf (function)", "storedHomeAmountSourceOf (function)", "stringStoredComparandDoorVerdict (function)", diff --git a/packages/spec/src/data/standard-units.test.ts b/packages/spec/src/data/standard-units.test.ts index cd9ddba2887..362d80a0dfc 100644 --- a/packages/spec/src/data/standard-units.test.ts +++ b/packages/spec/src/data/standard-units.test.ts @@ -4,6 +4,8 @@ import { describe, it, expect } from 'vitest'; import { ORGANIZATION_UNIT_CODE_PATTERN, STANDARD_UNITS, + STANDARD_UNIT_NAMES, + standardUnitName, UNIT_DIMENSIONS, UNIT_DIMENSION_BASE_CODES, type StandardUnit, @@ -123,3 +125,32 @@ describe('ORGANIZATION_UNIT_CODE_PATTERN — the organization code namespace (AD for (const code of Object.keys(STANDARD_UNITS)) expect(orgCode.test(code), code).toBe(false); }); }); + +describe('STANDARD_UNIT_NAMES — the English base name of every standard code (ADR-0158 L2, 2A)', () => { + it('names exactly the codes of STANDARD_UNITS, in the same order', () => { + expect(Object.keys(STANDARD_UNIT_NAMES)).toEqual(Object.keys(STANDARD_UNITS)); + }); + + it('gives every code a non-empty, trimmed, lowercase English name, and no two codes one name', () => { + const names = Object.values(STANDARD_UNIT_NAMES); + for (const [code, name] of Object.entries(STANDARD_UNIT_NAMES)) { + expect(name, code).toMatch(/^\S(?:.*\S)?$/); + expect(name, code).toBe(name.replace(/^US /, 'US ').toLowerCase().replace(/^us /, 'US ')); + } + expect(new Set(names).size).toBe(names.length); + }); + + it('is frozen, so no reader can rename a unit at runtime', () => { + expect(Object.isFrozen(STANDARD_UNIT_NAMES)).toBe(true); + }); + + it('answers by own property in exact uppercase, as standardUnitOf does', () => { + expect(standardUnitName('KGM')).toBe('kilogram'); + expect(standardUnitName('H87')).toBe('piece'); + expect(standardUnitName('kgm')).toBeUndefined(); + expect(standardUnitName(' KGM')).toBeUndefined(); + expect(standardUnitName('toString')).toBeUndefined(); + expect(standardUnitName('BOX_12')).toBeUndefined(); + expect(standardUnitName(undefined)).toBeUndefined(); + }); +}); diff --git a/packages/spec/src/data/standard-units.ts b/packages/spec/src/data/standard-units.ts index 852f0869aee..dd1b70d0a66 100644 --- a/packages/spec/src/data/standard-units.ts +++ b/packages/spec/src/data/standard-units.ts @@ -179,6 +179,71 @@ export const STANDARD_UNITS: Readonly> = Object.fre XSA: { dimension: 'package' }, // Sack }); +/** + * The English base name of every standard code (ADR-0158 L2, 2A: "Standard U1 + * codes get a platform-shipped per-locale label table"), keyed exactly as + * {@link STANDARD_UNITS} is. Each locale's name is served by the platform's + * i18n service (the platform translation bundles' `messages`, keyed + * `units.standard.`) and falls back to this name; a reader with no + * translation (an export, an MCP tool) names a unit from here. A pin test + * holds this table to exactly the keys of {@link STANDARD_UNITS}, so a code + * added there without a name here goes red. + */ +export const STANDARD_UNIT_NAMES: Readonly> = Object.freeze({ + KGM: 'kilogram', + GRM: 'gram', + MGM: 'milligram', + TNE: 'tonne', + LBR: 'pound', + ONZ: 'ounce', + MTR: 'metre', + MMT: 'millimetre', + CMT: 'centimetre', + KMT: 'kilometre', + INH: 'inch', + FOT: 'foot', + YRD: 'yard', + MTK: 'square metre', + CMK: 'square centimetre', + MMK: 'square millimetre', + FTK: 'square foot', + MTQ: 'cubic metre', + LTR: 'litre', + MLT: 'millilitre', + GLL: 'US gallon', + SEC: 'second', + MIN: 'minute', + HUR: 'hour', + DAY: 'day', + WEE: 'week', + H87: 'piece', + PR: 'pair', + DZN: 'dozen', + XBG: 'bag', + XBE: 'bundle', + XBO: 'bottle', + XBX: 'box', + XCT: 'carton', + XCS: 'case', + XCR: 'crate', + XDR: 'drum', + XPK: 'package', + XPX: 'pallet', + XRO: 'roll', + XSA: 'sack', +}); + +/** + * The English base name of a standard code ({@link STANDARD_UNIT_NAMES}), or + * `undefined` for a code that is not one: an own-property lookup in exact + * uppercase, as {@link standardUnitOf} reads the table. + */ +export function standardUnitName(code: unknown): string | undefined { + return typeof code === 'string' && Object.prototype.hasOwnProperty.call(STANDARD_UNIT_NAMES, code) + ? STANDARD_UNIT_NAMES[code] + : undefined; +} + /** * The ONE membership lookup of the standard unit table (ADR-0158 U1): the * entry {@link STANDARD_UNITS} holds for `code` as an OWN property, or diff --git a/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx b/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx index a930c23f7f5..c8835e3ee11 100644 --- a/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx +++ b/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx @@ -87,7 +87,7 @@ describe.each(['grid', 'detail', 'form'])('the %s face', (face) => { it("draws a fixed-mode quantity with the standard label and its organization's setting", async () => { draw(face, FIXED_QTY, 1234.5, { organization_id: 'org_a' }, unitSource()); - await waitFor(() => expect(faceText()).toBe('1,235 kg')); + await waitFor(() => expect(faceText()).toBe('1,235 kilogram')); }); it('draws a deleted (retired) org unit as the bare code, at the field width', async () => { @@ -107,15 +107,15 @@ describe.each(['grid', 'detail', 'form'])('the %s face', (face) => { it("takes the decimal places of the record's own organization's row", async () => { draw(face, RECORD_QTY, 1.5, { unit_code: 'GRM', organization_id: 'org_b' }, unitSource()); - await waitFor(() => expect(faceText()).toBe('2 g')); + await waitFor(() => expect(faceText()).toBe('2 gram')); cleanup(); draw(face, RECORD_QTY, 1.5, { unit_code: 'GRM', organization_id: 'org_a' }, unitSource()); - await waitFor(() => expect(faceText()).toBe('1.500 g')); + await waitFor(() => expect(faceText()).toBe('1.500 gram')); }); it("never shows more places than the field's scale (L4)", async () => { draw(face, { ...RECORD_QTY, scale: 2 }, 1.5, { unit_code: 'GRM', organization_id: 'org_a' }, unitSource()); - await waitFor(() => expect(faceText()).toBe('1.50 g')); + await waitFor(() => expect(faceText()).toBe('1.50 gram')); }); it('draws a bare number when the row names no unit', async () => { @@ -136,10 +136,13 @@ describe('the edited form box', () => { }); }); -describe('the per-locale standard label (ADR-0158 L2, 2A)', () => { - it("reads the reader's locale", async () => { +describe('the per-locale standard name (ADR-0158 L2, 2A)', () => { + it("reads the name the server serves for the reader's locale (`app.messages.standardUnit`)", async () => { + // The served translation document lays the platform bundles under `app`, + // as the console's loader does (`transformSpecTranslations`). + const resources = { zh: { app: { messages: { standardUnitKGM: '千克' } } } }; render( - +
{React.createElement(getCellRenderer('number'), { value: 2, field: FIXED_QTY, dependentValues: { organization_id: 'org_a' } })}
@@ -159,7 +162,7 @@ describe('a unit-code field (Open item 8)', () => {
, ); - await waitFor(() => expect(text(screen.getByTestId('a').textContent)).toBe('pc')); + await waitFor(() => expect(text(screen.getByTestId('a').textContent)).toBe('piece')); expect(text(screen.getByTestId('b').textContent)).toBe('JIN1'); }); }); diff --git a/ui/packages/fields/src/widgets/quantity-format.ts b/ui/packages/fields/src/widgets/quantity-format.ts index 9031fd67610..c14220374b4 100644 --- a/ui/packages/fields/src/widgets/quantity-format.ts +++ b/ui/packages/fields/src/widgets/quantity-format.ts @@ -35,8 +35,8 @@ export interface QuantityDisplay { unit?: string; /** * Whether the stored value has more decimal places than the number shows. - * Computed for every quantity; nothing renders from it yet (ADR-0158 Open - * item 6's second half decides whether a marker does). + * Computed for every quantity; nothing renders from it (ADR-0158 Open item + * 6 was ruled A, with no marker). */ hidden: boolean; } @@ -69,12 +69,15 @@ function placesOf(value: number): number { /** * The fraction-digit bounds a quantity is drawn at, given its display places. * - * ⭐ The rounding rule lives here and nowhere else: ADR-0158 Open item 6's + * ⭐ The rounding rule lives here and nowhere else. ADR-0158 Open item 6's * second half (what a unit's display default does with a stored value that - * has more places) is answered by this function. Today it is a fixed width, - * as a currency amount is drawn at its currency's digits: a unit of 3 places - * shows 1.5 as `1.500`, and a unit of 0 places shows 1.5 rounded, the way - * `Intl` rounds. + * has more places) was ruled A on objectstack#35490: round at render, half + * away from zero, at a fixed width, as a currency amount is drawn at its + * currency's digits. A unit of 3 places shows 1.5 as `1.500`, and a unit of + * 0 places shows 1.5 as `2`. `Intl.NumberFormat`'s default rounding mode, + * `halfExpand`, is that rule. Only the display rounds: the stored value, a + * footer's total (summed exact, then formatted), an export, the API and MCP + * keep the exact value. */ function quantityFractionDigits(places: number): { minimumFractionDigits: number; maximumFractionDigits: number } { return { minimumFractionDigits: places, maximumFractionDigits: places }; diff --git a/ui/packages/fields/src/widgets/useQuantityUnit.ts b/ui/packages/fields/src/widgets/useQuantityUnit.ts index 22ea2c18cf1..74aeadf23c7 100644 --- a/ui/packages/fields/src/widgets/useQuantityUnit.ts +++ b/ui/packages/fields/src/widgets/useQuantityUnit.ts @@ -22,7 +22,7 @@ import { useContext, useEffect, useState } from 'react'; import { SchemaRendererContext } from '@object-ui/react'; -import { en } from '@object-ui/i18n'; +import { standardUnitName } from '@objectstack/spec/data'; import { quantityUnitCode, resolveQuantityUnit, @@ -83,17 +83,24 @@ export function readUnitCatalog(source: UnitSource): Promise { } /** - * The platform's label for a standard code in the reader's locale (ADR-0158 - * L2, 2A), or `undefined` for a code with none. One function, so where the - * per-locale names live can move without any caller changing. + * The platform's name for a standard code in the reader's locale (ADR-0158 + * L2, 2A), or `undefined` for a code that is not one. + * + * The per-locale names are served by the platform's i18n service: each + * platform bundle's `messages.standardUnit`, which the console's served + * translation document lays under the `app` namespace. Absent a served name + * (no provider, or a locale the server does not translate), the English base + * name `STANDARD_UNIT_NAMES` in `@objectstack/spec` answers. One function, so + * where the names live can move without any caller changing. */ export function useStandardUnitLabel(): (code: string) => string | undefined { const { t } = useFieldTranslation(); return (code: string) => { - const base = (en.units.standard as Readonly>)[code]; + const base = standardUnitName(code); if (base === undefined) return undefined; - const label = t(`units.standard.${code}`, { defaultValue: base }); - return typeof label === 'string' && label !== '' && label !== `units.standard.${code}` ? label : base; + const key = `app.messages.standardUnit${code}`; + const served = t(key, { defaultValue: base }); + return typeof served === 'string' && served !== '' && served !== key ? served : base; }; } diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index d9e4fb49510..040ffe0ca80 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -289,53 +289,6 @@ const ar = { textFallback: "النص", }, }, - // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), - // drawn beside a quantity; keyed by the code in exact uppercase. - units: { - standard: { - KGM: 'كغ', - GRM: 'غ', - MGM: 'مغ', - TNE: 'طن', - LBR: 'رطل', - ONZ: 'أونصة', - MTR: 'م', - MMT: 'مم', - CMT: 'سم', - KMT: 'كم', - INH: 'بوصة', - FOT: 'قدم', - YRD: 'ياردة', - MTK: 'م²', - CMK: 'سم²', - MMK: 'مم²', - FTK: 'قدم²', - MTQ: 'م³', - LTR: 'لتر', - MLT: 'مل', - GLL: 'غالون', - SEC: 'ثانية', - MIN: 'دقيقة', - HUR: 'ساعة', - DAY: 'يوم', - WEE: 'أسبوع', - H87: 'قطعة', - PR: 'زوج', - DZN: 'دزينة', - XBG: 'كيس', - XBE: 'حزمة', - XBO: 'زجاجة', - XBX: 'علبة', - XCT: 'كرتونة', - XCS: 'صندوق', - XCR: 'قفص', - XDR: 'برميل', - XPK: 'طرد', - XPX: 'منصة', - XRO: 'لفة', - XSA: 'جوال', - }, - }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index a8e4472174d..b581fe53706 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -271,53 +271,6 @@ const de = { textFallback: "Text", }, }, - // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), - // drawn beside a quantity; keyed by the code in exact uppercase. - units: { - standard: { - KGM: 'kg', - GRM: 'g', - MGM: 'mg', - TNE: 't', - LBR: 'lb', - ONZ: 'oz', - MTR: 'm', - MMT: 'mm', - CMT: 'cm', - KMT: 'km', - INH: 'in', - FOT: 'ft', - YRD: 'yd', - MTK: 'm²', - CMK: 'cm²', - MMK: 'mm²', - FTK: 'ft²', - MTQ: 'm³', - LTR: 'l', - MLT: 'ml', - GLL: 'gal', - SEC: 's', - MIN: 'min', - HUR: 'h', - DAY: 'd', - WEE: 'Wo.', - H87: 'Stk.', - PR: 'Paar', - DZN: 'Dtzd.', - XBG: 'Beutel', - XBE: 'Bündel', - XBO: 'Flasche', - XBX: 'Schachtel', - XCT: 'Karton', - XCS: 'Kiste', - XCR: 'Lattenkiste', - XDR: 'Fass', - XPK: 'Pkg.', - XPX: 'Palette', - XRO: 'Rolle', - XSA: 'Sack', - }, - }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 318e4bcd9ad..e4a76084830 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -429,53 +429,6 @@ const en = { textFallback: 'text', }, }, - // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), - // drawn beside a quantity; keyed by the code in exact uppercase. - units: { - standard: { - KGM: 'kg', - GRM: 'g', - MGM: 'mg', - TNE: 't', - LBR: 'lb', - ONZ: 'oz', - MTR: 'm', - MMT: 'mm', - CMT: 'cm', - KMT: 'km', - INH: 'in', - FOT: 'ft', - YRD: 'yd', - MTK: 'm²', - CMK: 'cm²', - MMK: 'mm²', - FTK: 'ft²', - MTQ: 'm³', - LTR: 'L', - MLT: 'mL', - GLL: 'gal', - SEC: 's', - MIN: 'min', - HUR: 'h', - DAY: 'd', - WEE: 'wk', - H87: 'pc', - PR: 'pr', - DZN: 'doz', - XBG: 'bag', - XBE: 'bundle', - XBO: 'bottle', - XBX: 'box', - XCT: 'carton', - XCS: 'case', - XCR: 'crate', - XDR: 'drum', - XPK: 'pkg', - XPX: 'pallet', - XRO: 'roll', - XSA: 'sack', - }, - }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index b56d34ea514..c879e9508ec 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -279,53 +279,6 @@ const es = { textFallback: "texto", }, }, - // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), - // drawn beside a quantity; keyed by the code in exact uppercase. - units: { - standard: { - KGM: 'kg', - GRM: 'g', - MGM: 'mg', - TNE: 't', - LBR: 'lb', - ONZ: 'oz', - MTR: 'm', - MMT: 'mm', - CMT: 'cm', - KMT: 'km', - INH: 'pulg.', - FOT: 'pie', - YRD: 'yd', - MTK: 'm²', - CMK: 'cm²', - MMK: 'mm²', - FTK: 'pie²', - MTQ: 'm³', - LTR: 'L', - MLT: 'mL', - GLL: 'gal', - SEC: 's', - MIN: 'min', - HUR: 'h', - DAY: 'd', - WEE: 'sem.', - H87: 'pza', - PR: 'par', - DZN: 'doc.', - XBG: 'bolsa', - XBE: 'fardo', - XBO: 'botella', - XBX: 'caja', - XCT: 'cartón', - XCS: 'estuche', - XCR: 'cajón', - XDR: 'bidón', - XPK: 'paquete', - XPX: 'palé', - XRO: 'rollo', - XSA: 'saco', - }, - }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index f9ae15505ab..5bf4039eab7 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -274,53 +274,6 @@ const fr = { textFallback: "le texte", }, }, - // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), - // drawn beside a quantity; keyed by the code in exact uppercase. - units: { - standard: { - KGM: 'kg', - GRM: 'g', - MGM: 'mg', - TNE: 't', - LBR: 'lb', - ONZ: 'oz', - MTR: 'm', - MMT: 'mm', - CMT: 'cm', - KMT: 'km', - INH: 'po', - FOT: 'pi', - YRD: 'vg', - MTK: 'm²', - CMK: 'cm²', - MMK: 'mm²', - FTK: 'pi²', - MTQ: 'm³', - LTR: 'L', - MLT: 'mL', - GLL: 'gal', - SEC: 's', - MIN: 'min', - HUR: 'h', - DAY: 'j', - WEE: 'sem.', - H87: 'pce', - PR: 'paire', - DZN: 'douz.', - XBG: 'sachet', - XBE: 'lot', - XBO: 'bouteille', - XBX: 'boîte', - XCT: 'carton', - XCS: 'caisse', - XCR: 'cageot', - XDR: 'fût', - XPK: 'colis', - XPX: 'palette', - XRO: 'rouleau', - XSA: 'sac', - }, - }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 41e28e64dcb..5b689d2ef4e 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -271,53 +271,6 @@ const ja = { textFallback: "テキスト", }, }, - // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), - // drawn beside a quantity; keyed by the code in exact uppercase. - units: { - standard: { - KGM: 'kg', - GRM: 'g', - MGM: 'mg', - TNE: 't', - LBR: 'lb', - ONZ: 'oz', - MTR: 'm', - MMT: 'mm', - CMT: 'cm', - KMT: 'km', - INH: 'in', - FOT: 'ft', - YRD: 'yd', - MTK: 'm²', - CMK: 'cm²', - MMK: 'mm²', - FTK: 'ft²', - MTQ: 'm³', - LTR: 'L', - MLT: 'mL', - GLL: 'gal', - SEC: '秒', - MIN: '分', - HUR: '時間', - DAY: '日', - WEE: '週', - H87: '個', - PR: '組', - DZN: 'ダース', - XBG: '袋', - XBE: '束', - XBO: '本', - XBX: '箱', - XCT: 'カートン', - XCS: 'ケース', - XCR: 'クレート', - XDR: 'ドラム', - XPK: '包', - XPX: 'パレット', - XRO: '巻', - XSA: '大袋', - }, - }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 86121deb0d5..6d159da8f17 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -271,53 +271,6 @@ const ko = { textFallback: "텍스트", }, }, - // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), - // drawn beside a quantity; keyed by the code in exact uppercase. - units: { - standard: { - KGM: 'kg', - GRM: 'g', - MGM: 'mg', - TNE: 't', - LBR: 'lb', - ONZ: 'oz', - MTR: 'm', - MMT: 'mm', - CMT: 'cm', - KMT: 'km', - INH: 'in', - FOT: 'ft', - YRD: 'yd', - MTK: 'm²', - CMK: 'cm²', - MMK: 'mm²', - FTK: 'ft²', - MTQ: 'm³', - LTR: 'L', - MLT: 'mL', - GLL: 'gal', - SEC: '초', - MIN: '분', - HUR: '시간', - DAY: '일', - WEE: '주', - H87: '개', - PR: '쌍', - DZN: '다스', - XBG: '봉지', - XBE: '묶음', - XBO: '병', - XBX: '상자', - XCT: '카톤', - XCS: '케이스', - XCR: '크레이트', - XDR: '드럼', - XPK: '포장', - XPX: '팔레트', - XRO: '롤', - XSA: '포대', - }, - }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 5f8124daa8b..09c1cc0730a 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -274,53 +274,6 @@ const pt = { textFallback: "texto", }, }, - // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), - // drawn beside a quantity; keyed by the code in exact uppercase. - units: { - standard: { - KGM: 'kg', - GRM: 'g', - MGM: 'mg', - TNE: 't', - LBR: 'lb', - ONZ: 'oz', - MTR: 'm', - MMT: 'mm', - CMT: 'cm', - KMT: 'km', - INH: 'pol', - FOT: 'pé', - YRD: 'jd', - MTK: 'm²', - CMK: 'cm²', - MMK: 'mm²', - FTK: 'pé²', - MTQ: 'm³', - LTR: 'L', - MLT: 'mL', - GLL: 'gal', - SEC: 's', - MIN: 'min', - HUR: 'h', - DAY: 'd', - WEE: 'sem.', - H87: 'pç', - PR: 'par', - DZN: 'dz', - XBG: 'sacola', - XBE: 'fardo', - XBO: 'garrafa', - XBX: 'caixa', - XCT: 'caixa de papelão', - XCS: 'estojo', - XCR: 'engradado', - XDR: 'tambor', - XPK: 'pacote', - XPX: 'palete', - XRO: 'rolo', - XSA: 'saco', - }, - }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 7f1d2a7d7e5..c1281b7a05c 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -280,53 +280,6 @@ const ru = { textFallback: "текст", }, }, - // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), - // drawn beside a quantity; keyed by the code in exact uppercase. - units: { - standard: { - KGM: 'кг', - GRM: 'г', - MGM: 'мг', - TNE: 'т', - LBR: 'фнт', - ONZ: 'унц', - MTR: 'м', - MMT: 'мм', - CMT: 'см', - KMT: 'км', - INH: 'дюйм', - FOT: 'фут', - YRD: 'ярд', - MTK: 'м²', - CMK: 'см²', - MMK: 'мм²', - FTK: 'фут²', - MTQ: 'м³', - LTR: 'л', - MLT: 'мл', - GLL: 'гал', - SEC: 'с', - MIN: 'мин', - HUR: 'ч', - DAY: 'сут', - WEE: 'нед', - H87: 'шт', - PR: 'пар', - DZN: 'дюж', - XBG: 'пакет', - XBE: 'связка', - XBO: 'бутылка', - XBX: 'коробка', - XCT: 'картон', - XCS: 'ящик', - XCR: 'клеть', - XDR: 'бочка', - XPK: 'упак', - XPX: 'поддон', - XRO: 'рул', - XSA: 'мешок', - }, - }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 7f7461cd65c..832015de466 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -281,53 +281,6 @@ const zh = { textFallback: '文本', }, }, - // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), - // drawn beside a quantity; keyed by the code in exact uppercase. - units: { - standard: { - KGM: '千克', - GRM: '克', - MGM: '毫克', - TNE: '吨', - LBR: '磅', - ONZ: '盎司', - MTR: '米', - MMT: '毫米', - CMT: '厘米', - KMT: '千米', - INH: '英寸', - FOT: '英尺', - YRD: '码', - MTK: '平方米', - CMK: '平方厘米', - MMK: '平方毫米', - FTK: '平方英尺', - MTQ: '立方米', - LTR: '升', - MLT: '毫升', - GLL: '加仑', - SEC: '秒', - MIN: '分钟', - HUR: '小时', - DAY: '天', - WEE: '周', - H87: '件', - PR: '双', - DZN: '打', - XBG: '袋', - XBE: '捆', - XBO: '瓶', - XBX: '盒', - XCT: '纸箱', - XCS: '箱', - XCR: '板条箱', - XDR: '桶', - XPK: '包', - XPX: '托盘', - XRO: '卷', - XSA: '麻袋', - }, - }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 8a71b096e75..d397fc1bf28 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -281,53 +281,6 @@ const zhHant = { textFallback: '文本', }, }, - // ADR-0158 L2 (2A) — the platform's label for each standard unit code (U1), - // drawn beside a quantity; keyed by the code in exact uppercase. - units: { - standard: { - KGM: '千克', - GRM: '克', - MGM: '毫克', - TNE: '噸', - LBR: '磅', - ONZ: '盎司', - MTR: '米', - MMT: '毫米', - CMT: '釐米', - KMT: '千米', - INH: '英寸', - FOT: '英尺', - YRD: '碼', - MTK: '平方米', - CMK: '平方釐米', - MMK: '平方毫米', - FTK: '平方英尺', - MTQ: '立方米', - LTR: '升', - MLT: '毫升', - GLL: '加侖', - SEC: '秒', - MIN: '分鐘', - HUR: '小時', - DAY: '天', - WEE: '周', - H87: '件', - PR: '雙', - DZN: '打', - XBG: '袋', - XBE: '捆', - XBO: '瓶', - XBX: '盒', - XCT: '紙箱', - XCS: '箱', - XCR: '板條箱', - XDR: '桶', - XPK: '包', - XPX: '托盤', - XRO: '卷', - XSA: '麻袋', - }, - }, fields: { // objectstack#35956 — the in-place fill-in a change opens when it makes // other fields required (`RequiredFieldsDialog`). diff --git a/ui/packages/plugin-detail/src/__tests__/quantityUnitRelay-35490.test.tsx b/ui/packages/plugin-detail/src/__tests__/quantityUnitRelay-35490.test.tsx index b41ec509bce..9a3b35e7c88 100644 --- a/ui/packages/plugin-detail/src/__tests__/quantityUnitRelay-35490.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/quantityUnitRelay-35490.test.tsx @@ -77,7 +77,7 @@ describe('the declared unitConfig reaches the detail cells (objectstack#35490)', ); await waitFor(() => { expect(flat(container.textContent)).toContain('4.0 Box of 12'); - expect(flat(container.textContent)).toContain('1.3 kg'); + expect(flat(container.textContent)).toContain('1.3 kilogram'); }); }); diff --git a/ui/packages/plugin-grid/src/__tests__/gridQuantityUnit-35490.test.tsx b/ui/packages/plugin-grid/src/__tests__/gridQuantityUnit-35490.test.tsx index ccab4162355..0817c2c450e 100644 --- a/ui/packages/plugin-grid/src/__tests__/gridQuantityUnit-35490.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/gridQuantityUnit-35490.test.tsx @@ -84,8 +84,8 @@ describe('object grid: a quantity with its unit (objectstack#35490)', () => { await waitFor(() => { const rows = rowTexts(); expect(rows[0]).toContain('4.0 Box of 12'); - expect(rows[0]).toContain('1.3 kg'); - expect(rows[1]).toContain('1.500 g'); + expect(rows[0]).toContain('1.3 kilogram'); + expect(rows[1]).toContain('1.500 gram'); expect(rows[2]).toContain('2 JIN1'); }); const read = calls.find((c) => c.object === 'line')!; @@ -106,8 +106,8 @@ describe('object grid with no SchemaRendererProvider: the known degraded shape ( await waitFor(() => expect(screen.getByText('L1')).toBeInTheDocument()); const rows = rowTexts(); expect(rows[0]).toContain('4 BOX_12'); - expect(rows[0]).toContain('1.25 kg'); - expect(rows[1]).toContain('1.5 g'); + expect(rows[0]).toContain('1.25 kilogram'); + expect(rows[1]).toContain('1.5 gram'); expect(calls.some((c) => c.object === 'sys_unit' || c.object === 'sys_standard_unit_setting')).toBe(false); expect(screen.queryByRole('alert')).toBeNull(); }); diff --git a/ui/packages/plugin-list/src/__tests__/ListView.quantityUnit-35490.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.quantityUnit-35490.test.tsx index 6ec41c96134..4381c7b20a1 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.quantityUnit-35490.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.quantityUnit-35490.test.tsx @@ -74,7 +74,7 @@ describe('list view: a quantity with its unit column not shown (objectstack#3549 const rows = [...document.querySelectorAll('tbody tr')].map((tr) => (tr.textContent ?? '').replace(/ /g, ' ')); expect(rows[0]).toContain('4.0 Box of 12'); // The row of organization B: B's setting of 0 places, not A's of 3. - expect(rows[1]).toContain('2 g'); + expect(rows[1]).toContain('2 gram'); }); const read = calls.find((c) => c.object === 'line')!; expect(read.params.$select).toEqual(expect.arrayContaining(['unit_code', 'organization_id'])); From 235a2dcd93d1f706ccc6db6ee7bef690d1cf2e92 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:44:12 +0000 Subject: [PATCH 05/13] chore(spec): regenerate api-surface after merging main (#35490) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXM7nqtiQ3M9JqGAqL --- packages/spec/api-surface/data.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index be04bf52ac9..270425bb1cf 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -438,6 +438,7 @@ "HookQuery (type)", "HookRefusal (type)", "HookRefusalSchema (const)", + "HookRefusalThrownReason (interface)", "HookSchema (const)", "HookText (type)", "HookTextReader (type)", @@ -778,6 +779,7 @@ "ReferenceResolutionErrorSchema (const)", "ReferenceResolutionParsed (type)", "ReferenceResolutionSchema (const)", + "RefusalListProblem (type)", "RelatedListEntry (type)", "RelatedListEntryInput (type)", "RelatedListEntryObject (interface)", @@ -1155,6 +1157,7 @@ "isTitleEligible (function)", "isTransferEligible (function)", "isUnboundedAbove (function)", + "isUndeclaredThrownReason (function)", "isUniqueDeclared (function)", "isVirtualSearchField (function)", "judgeImportMappingTarget (function)", @@ -1262,6 +1265,8 @@ "uniqueNullDistinctDivergence (function)", "unknownImportMappingTargets (function)", "unprovisionedInjectedColumns (function)", + "unreadableActionRefusalListAtRun (function)", + "unreadableHookRefusalListAtRun (function)", "urlCredentialQueryParams (function)", "urlUserinfoPassword (function)", "urlUserinfoUsername (function)", From 77f01361fd24c72a740558952732b64ef2abc8e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 05:51:49 +0000 Subject: [PATCH 06/13] chore(spec): record the two new standard-unit exports in export-origins (#35490) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXM7nqtiQ3M9JqGAqL --- packages/spec/export-origins/data.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 057c96e7857..2d7631653b5 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -816,6 +816,7 @@ "STACK_KEY_GUIDANCE": "src/data/authoring-key-lint.ts#STACK_KEY_GUIDANCE (const)", "STACK_RUNTIME_MEMBERS": "src/data/authoring-key-lint.ts#STACK_RUNTIME_MEMBERS (const)", "STANDARD_UNITS": "src/data/standard-units.ts#STANDARD_UNITS (const)", + "STANDARD_UNIT_NAMES": "src/data/standard-units.ts#STANDARD_UNIT_NAMES (const)", "STRING_STORED_COMPARAND_DOOR_FAMILIES": "src/data/filter-string-stored-comparand-declared-type.ts#STRING_STORED_COMPARAND_DOOR_FAMILIES (const)", "STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS": "src/data/filter-string-stored-comparand-declared-type.ts#STRING_STORED_COMPARAND_DOOR_LIST_OPERATORS (const)", "STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS": "src/data/filter-string-stored-comparand-declared-type.ts#STRING_STORED_COMPARAND_DOOR_SCALAR_OPERATORS (const)", @@ -1221,6 +1222,7 @@ "resolveUserActionTransfer": "src/data/user-action-transfer.ts#resolveUserActionTransfer (function)", "seedFile": "src/data/seed-file.zod.ts#seedFile (function)", "sequenceWidth": "src/data/autonumber-format.ts#sequenceWidth (function)", + "standardUnitName": "src/data/standard-units.ts#standardUnitName (function)", "standardUnitOf": "src/data/standard-units.ts#standardUnitOf (function)", "storedHomeAmountSourceOf": "src/data/record-currency-path.ts#storedHomeAmountSourceOf (function)", "stringStoredComparandDoorVerdict": "src/data/filter-string-stored-comparand-declared-type.ts#stringStoredComparandDoorVerdict (function)", From 02d7c9759af94b8fdc1efc9be37fc36d77b440fe Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 06:03:28 +0000 Subject: [PATCH 07/13] test(components): load react-runtime at collection in the quantity form test (#35490) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXM7nqtiQ3M9JqGAqL --- .../form/__tests__/form-quantity-record-35490.test.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ui/packages/components/src/renderers/form/__tests__/form-quantity-record-35490.test.tsx b/ui/packages/components/src/renderers/form/__tests__/form-quantity-record-35490.test.tsx index 7ea8407f3c9..20355d75899 100644 --- a/ui/packages/components/src/renderers/form/__tests__/form-quantity-record-35490.test.tsx +++ b/ui/packages/components/src/renderers/form/__tests__/form-quantity-record-35490.test.tsx @@ -16,6 +16,8 @@ import { describe, it, expect, beforeAll } from 'vitest'; import { render, screen, fireEvent, waitFor } from '@testing-library/react'; import { ComponentRegistry } from '@object-ui/core'; import '../../../renderers'; +// Paid at collection, not inside a clocked case (check-test-source-alias). +import '@object-ui/react-runtime'; function NumberProbe(props: any) { return
{JSON.stringify(props.dependentValues ?? null)}
; From c7630bfb778eca86080d45dac4432e9d49b10aa7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 06:14:44 +0000 Subject: [PATCH 08/13] fix(units): escape NBSPs in quantity tests, keep the docs example off the component-type gate (#35490) Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXM7nqtiQ3M9JqGAqL --- content/docs/frontend/fields.mdx | 7 ++----- .../fields/src/__tests__/quantityDisplay-35490.test.tsx | 6 +++--- .../src/__tests__/quantityUnitRelay-35490.test.tsx | 2 +- .../src/__tests__/gridQuantityUnit-35490.test.tsx | 2 +- .../src/__tests__/ListView.quantityUnit-35490.test.tsx | 2 +- 5 files changed, 8 insertions(+), 11 deletions(-) diff --git a/content/docs/frontend/fields.mdx b/content/docs/frontend/fields.mdx index 2e235f25857..e20ee1678b0 100644 --- a/content/docs/frontend/fields.mdx +++ b/content/docs/frontend/fields.mdx @@ -88,11 +88,8 @@ ObjectUI comes with built-in support for the standard [ObjectStack Protocol](htt A `number` field that declares `unitConfig` is a quantity, and every face draws it with its unit: grid and list cells, the record page, the quick-look panel, related lists, and the form (read-only, and beside the -edited box). - -```json -{ "name": "qty", "type": "number", "unitConfig": { "unitMode": "record", "unitField": "unit_code" } } -``` +edited box). A record-mode quantity, for example, declares +`unitConfig: { unitMode: 'record', unitField: 'unit_code' }` on its `number` field. - **Which unit.** `unitMode: 'fixed'` shows its one `unit`. `unitMode: 'record'` shows the code the row's `unitField` holds; the list, grid and related-list reads fetch that field, and the row's diff --git a/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx b/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx index c8835e3ee11..1600d824d26 100644 --- a/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx +++ b/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx @@ -31,7 +31,7 @@ import { formatQuantity, quantityDisplayPlaces } from '../widgets/quantity-forma afterEach(cleanup); -const text = (s: string | null | undefined) => (s ?? '').replace(/ /g, ' '); +const text = (s: string | null | undefined) => (s ?? '').replace(/\u00a0/g, ' '); const ORG_UNITS = [ { code: 'BOX_12', label: 'Box of 12', decimal_places: 1, retired: false, organization_id: 'org_a' }, @@ -173,13 +173,13 @@ describe('formatQuantity — the one formatter', () => { it('marks a stored value with more places than shown, and changes nothing stored', () => { const value = 1.5; const out = formatQuantity(value, field, { code: 'H87', standard: true, label: 'pc', decimals: 0 }, 'en-US'); - expect(out).toEqual({ text: '2 pc', number: '2', unit: 'pc', hidden: true }); + expect(out).toEqual({ text: '2\u00a0pc', number: '2', unit: 'pc', hidden: true }); expect(value).toBe(1.5); expect(formatQuantity(1.5, field, { code: 'GRM', standard: true, label: 'g', decimals: 3 }, 'en-US').hidden).toBe(false); }); it('keeps the field width when the unit has no decimal places of its own', () => { - expect(formatQuantity(1.25, { ...field, scale: 2 }, { code: 'KGM', standard: true, label: 'kg' }, 'en-US').text).toBe('1.25 kg'); + expect(formatQuantity(1.25, { ...field, scale: 2 }, { code: 'KGM', standard: true, label: 'kg' }, 'en-US').text).toBe('1.25\u00a0kg'); expect(quantityDisplayPlaces(undefined, field)).toBeUndefined(); expect(quantityDisplayPlaces(5, { ...field, scale: 2 })).toBe(2); expect(quantityDisplayPlaces(1, { ...field, scale: 2 })).toBe(1); diff --git a/ui/packages/plugin-detail/src/__tests__/quantityUnitRelay-35490.test.tsx b/ui/packages/plugin-detail/src/__tests__/quantityUnitRelay-35490.test.tsx index 9a3b35e7c88..a0a41ba2631 100644 --- a/ui/packages/plugin-detail/src/__tests__/quantityUnitRelay-35490.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/quantityUnitRelay-35490.test.tsx @@ -64,7 +64,7 @@ function unitSource(rows: Record[] = [RECORD]) { }; } -const flat = (s: string | null | undefined) => (s ?? '').replace(/ /g, ' '); +const flat = (s: string | null | undefined) => (s ?? '').replace(/\u00a0/g, ' '); describe('the declared unitConfig reaches the detail cells (objectstack#35490)', () => { it('DetailSection: a record-mode and a fixed-mode quantity, with their unit labels', async () => { diff --git a/ui/packages/plugin-grid/src/__tests__/gridQuantityUnit-35490.test.tsx b/ui/packages/plugin-grid/src/__tests__/gridQuantityUnit-35490.test.tsx index 0817c2c450e..8c1ea84d1be 100644 --- a/ui/packages/plugin-grid/src/__tests__/gridQuantityUnit-35490.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/gridQuantityUnit-35490.test.tsx @@ -65,7 +65,7 @@ function source() { return { ds, calls }; } -const rowTexts = () => [...document.querySelectorAll('tbody tr')].map((tr) => (tr.textContent ?? '').replace(/ /g, ' ')); +const rowTexts = () => [...document.querySelectorAll('tbody tr')].map((tr) => (tr.textContent ?? '').replace(/\u00a0/g, ' ')); describe('object grid: a quantity with its unit (objectstack#35490)', () => { it("draws each row in its own unit, with the unit column not shown", async () => { diff --git a/ui/packages/plugin-list/src/__tests__/ListView.quantityUnit-35490.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.quantityUnit-35490.test.tsx index 4381c7b20a1..2c8d7cee5c3 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.quantityUnit-35490.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.quantityUnit-35490.test.tsx @@ -71,7 +71,7 @@ describe('list view: a quantity with its unit column not shown (objectstack#3549 ); await waitFor(() => expect(screen.getByText('L1')).toBeInTheDocument(), { timeout: 8000 }); await waitFor(() => { - const rows = [...document.querySelectorAll('tbody tr')].map((tr) => (tr.textContent ?? '').replace(/ /g, ' ')); + const rows = [...document.querySelectorAll('tbody tr')].map((tr) => (tr.textContent ?? '').replace(/\u00a0/g, ' ')); expect(rows[0]).toContain('4.0 Box of 12'); // The row of organization B: B's setting of 0 places, not A's of 3. expect(rows[1]).toContain('2 gram'); From 7b7017e7be095a8b64cd73bbe0273cf94105c147 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 06:28:09 +0000 Subject: [PATCH 09/13] feat(types): declare unitConfig on the form field face (#35490) The number widget reads it, as it reads currencyConfig; the form-field channel census requires every key it reads to be declared. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXM7nqtiQ3M9JqGAqL --- .../types/src/__tests__/form-field-zod-coverage.test.ts | 2 ++ ui/packages/types/src/form.ts | 9 +++++++++ ui/packages/types/src/zod/form.zod.ts | 4 ++++ 3 files changed, 15 insertions(+) diff --git a/ui/packages/types/src/__tests__/form-field-zod-coverage.test.ts b/ui/packages/types/src/__tests__/form-field-zod-coverage.test.ts index 189e978647e..094a357e17b 100644 --- a/ui/packages/types/src/__tests__/form-field-zod-coverage.test.ts +++ b/ui/packages/types/src/__tests__/form-field-zod-coverage.test.ts @@ -93,6 +93,8 @@ const DECLARED_KEYS = [ // read, and the currency widget's fixed-currency declaration, by reference. 'scale', 'currencyConfig', + // objectstack#35490 — the unit a quantity is drawn with, by reference. + 'unitConfig', 'minLength', 'maxLength', 'pattern', diff --git a/ui/packages/types/src/form.ts b/ui/packages/types/src/form.ts index c88feb4cedd..264da0d1930 100644 --- a/ui/packages/types/src/form.ts +++ b/ui/packages/types/src/form.ts @@ -2092,6 +2092,15 @@ export interface FormField { * (objectui#11070). */ currencyConfig?: SpecField['currencyConfig']; + /** + * The unit a quantity is drawn with (ADR-0158, objectstack#35490). On a + * `number` field, `{ unitMode: 'fixed', unit: 'KGM' }` gives every value one + * unit and `{ unitMode: 'record', unitField: 'unit_code' }` reads it off the + * record's own unit field. On a `text` field, `{ unitMode: 'code' }` marks + * the value itself as a unit code. The `number` widget shows the unit's + * name beside the value, at the unit's display decimal places. + */ + unitConfig?: SpecField['unitConfig']; /** * Minimum character length. The built-in `input` and `textarea` branches * put it on the native control as `minlength`, which the browser enforces diff --git a/ui/packages/types/src/zod/form.zod.ts b/ui/packages/types/src/zod/form.zod.ts index a0f8507f925..a5bdd4a64df 100644 --- a/ui/packages/types/src/zod/form.zod.ts +++ b/ui/packages/types/src/zod/form.zod.ts @@ -1159,6 +1159,10 @@ export const FormFieldSchema = z.looseObject({ // below carries that one rule (`CURRENCY_FIELD_SCALE_REFUSAL`). scale: stripImportedDefaults(SpecFieldSchema).shape.scale, currencyConfig: stripImportedDefaults(SpecFieldSchema).shape.currencyConfig, + // objectstack#35490 — the unit a `number` quantity (or a unit-code `text` + // field) is drawn with: `NumberField` and the text and number cells read it + // (ADR-0158 R1 display). + unitConfig: stripImportedDefaults(SpecFieldSchema).shape.unitConfig, minLength: stripImportedDefaults(SpecFieldSchema).shape.minLength, maxLength: stripImportedDefaults(SpecFieldSchema).shape.maxLength, pattern: z.string().optional() From 58f5398f6ee38f17c40bd532449ad32e590777af Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:20:41 +0000 Subject: [PATCH 10/13] fix(units): name the served key in the spec jsdoc, declare the form-field key in the changeset (#35490) Contract review S1 and S3: STANDARD_UNIT_NAMES' jsdoc names the single-segment key standardUnit; the changeset ships @object-ui/types as minor with Metadata-protocol: added and names unitConfig on FormField/FormFieldSchema. The form-face comments say nothing there reads unitMode 'code' yet. Adds a negative half-rounding pin. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXM7nqtiQ3M9JqGAqL --- .changeset/35490-quantity-unit-display.md | 5 +++-- packages/spec/src/data/standard-units.ts | 4 +++- .../fields/src/__tests__/quantityDisplay-35490.test.tsx | 7 +++++++ ui/packages/types/src/form.ts | 6 ++++-- ui/packages/types/src/zod/form.zod.ts | 7 ++++--- 5 files changed, 21 insertions(+), 8 deletions(-) diff --git a/.changeset/35490-quantity-unit-display.md b/.changeset/35490-quantity-unit-display.md index bdcb9885d12..d618040d022 100644 --- a/.changeset/35490-quantity-unit-display.md +++ b/.changeset/35490-quantity-unit-display.md @@ -3,7 +3,7 @@ '@objectstack/platform-objects': patch '@object-ui/core': patch '@object-ui/fields': patch -'@object-ui/types': patch +'@object-ui/types': minor '@object-ui/components': patch '@object-ui/plugin-grid': patch '@object-ui/plugin-list': patch @@ -13,7 +13,7 @@ feat(fields): a quantity displays with its unit's label and display decimal places in grid, form and detail (ADR-0158 R1 display) Clause-②: yes (widening) -Metadata-protocol: none +Metadata-protocol: added A `number` field that declares `unitConfig` now draws its unit beside the number on every face: grid and list cells, the record page (sections, highlights, the quick-look panel, related lists), and the form, both read-only and beside the edited box. A `fixed` quantity shows its one unit; a `record` quantity shows the unit its row's code field holds, and the list, grid and related-list reads fetch that field (and the row's organization) even when no column shows it. A `text` field declaring `unitConfig: { unitMode: 'code' }` shows the code's label. @@ -21,3 +21,4 @@ A `number` field that declares `unitConfig` now draws its unit beside the number - Decimal places: a standard code takes its organization's `sys_standard_unit_setting` row, an organization code its `sys_unit.decimal_places`. The row is the record's own organization's, never merely the first one returned. The field's `scale` is the ceiling (ADR-0158 L4). The number is drawn at that fixed width, rounded half away from zero (ADR-0158 Open item 6, ruled A): `1.5` beside a unit of 0 places reads `2`. Only the display rounds; nothing is rounded at write, and footers, exports and the API keep the exact value. - A retired organization unit, and a unit whose row the reader may not read (an external member holds no `sys_unit` read), show the bare code, never an error. - One resolver (`resolveQuantityUnit` in `@object-ui/core`) and one formatter (`formatQuantity` in `@object-ui/fields`) serve every face. +- `@object-ui/types`: `unitConfig` is now an authorable key on `FormField` and `FormFieldSchema` (by reference to the spec's `FieldSchema.unitConfig`, beside `currencyConfig`), so `objectui validate` accepts it on a hand-authored form field. The tolerant face now checks its value against the spec's `UnitConfigSchema`, where before it passed as an unknown key. On the form face only the `number` widget reads it; a `text` field's `unitMode: 'code'` is drawn by the grid and detail cells. diff --git a/packages/spec/src/data/standard-units.ts b/packages/spec/src/data/standard-units.ts index dd1b70d0a66..529aa10d732 100644 --- a/packages/spec/src/data/standard-units.ts +++ b/packages/spec/src/data/standard-units.ts @@ -184,7 +184,9 @@ export const STANDARD_UNITS: Readonly> = Object.fre * codes get a platform-shipped per-locale label table"), keyed exactly as * {@link STANDARD_UNITS} is. Each locale's name is served by the platform's * i18n service (the platform translation bundles' `messages`, keyed - * `units.standard.`) and falls back to this name; a reader with no + * `standardUnit` followed by the code, e.g. `standardUnitKGM`: one segment, + * because the i18n adapter walks a dotted key as nesting) and falls back to + * this name; a reader with no * translation (an export, an MCP tool) names a unit from here. A pin test * holds this table to exactly the keys of {@link STANDARD_UNITS}, so a code * added there without a name here goes red. diff --git a/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx b/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx index 1600d824d26..aa0da9160db 100644 --- a/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx +++ b/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx @@ -178,6 +178,13 @@ describe('formatQuantity — the one formatter', () => { expect(formatQuantity(1.5, field, { code: 'GRM', standard: true, label: 'g', decimals: 3 }, 'en-US').hidden).toBe(false); }); + it('rounds half away from zero, on both signs (OI6, ruled A)', () => { + const pc = { code: 'H87', standard: true, label: 'pc', decimals: 0 }; + expect(formatQuantity(-1.5, field, pc, 'en-US').number).toBe('-2'); + expect(formatQuantity(2.5, field, pc, 'en-US').number).toBe('3'); + expect(formatQuantity(-2.5, field, pc, 'en-US').number).toBe('-3'); + }); + it('keeps the field width when the unit has no decimal places of its own', () => { expect(formatQuantity(1.25, { ...field, scale: 2 }, { code: 'KGM', standard: true, label: 'kg' }, 'en-US').text).toBe('1.25\u00a0kg'); expect(quantityDisplayPlaces(undefined, field)).toBeUndefined(); diff --git a/ui/packages/types/src/form.ts b/ui/packages/types/src/form.ts index 264da0d1930..28632876ff0 100644 --- a/ui/packages/types/src/form.ts +++ b/ui/packages/types/src/form.ts @@ -2097,8 +2097,10 @@ export interface FormField { * `number` field, `{ unitMode: 'fixed', unit: 'KGM' }` gives every value one * unit and `{ unitMode: 'record', unitField: 'unit_code' }` reads it off the * record's own unit field. On a `text` field, `{ unitMode: 'code' }` marks - * the value itself as a unit code. The `number` widget shows the unit's - * name beside the value, at the unit's display decimal places. + * the value itself as a unit code; the grid and detail cells show its name, + * but on this form face nothing reads that mode yet (the text widget draws + * the bare code, and no unit picker exists). The `number` widget shows the + * unit's name beside the value, at the unit's display decimal places. */ unitConfig?: SpecField['unitConfig']; /** diff --git a/ui/packages/types/src/zod/form.zod.ts b/ui/packages/types/src/zod/form.zod.ts index a5bdd4a64df..f32c8af1ac5 100644 --- a/ui/packages/types/src/zod/form.zod.ts +++ b/ui/packages/types/src/zod/form.zod.ts @@ -1159,9 +1159,10 @@ export const FormFieldSchema = z.looseObject({ // below carries that one rule (`CURRENCY_FIELD_SCALE_REFUSAL`). scale: stripImportedDefaults(SpecFieldSchema).shape.scale, currencyConfig: stripImportedDefaults(SpecFieldSchema).shape.currencyConfig, - // objectstack#35490 — the unit a `number` quantity (or a unit-code `text` - // field) is drawn with: `NumberField` and the text and number cells read it - // (ADR-0158 R1 display). + // objectstack#35490 — the unit a `number` quantity is drawn with: + // `NumberField` and the number cell read it (ADR-0158 R1 display). A + // unit-code `text` field's `unitMode: 'code'` is read by the text cell + // only; on this form face the text widget does not read it yet. unitConfig: stripImportedDefaults(SpecFieldSchema).shape.unitConfig, minLength: stripImportedDefaults(SpecFieldSchema).shape.minLength, maxLength: stripImportedDefaults(SpecFieldSchema).shape.maxLength, From 5feaffb885b144d56455dfece62b5a0a3885e215 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:27:59 +0000 Subject: [PATCH 11/13] feat(fields): the unit picker for a unit code field (#35490, #37471) ADR-0158 Open item 8 (ruled A): a text field declaring unitMode 'code', and the unitField a record-mode quantity on the same form points at, draw UnitCodeField, a searchable picker of the organization's non-retired units and the standard codes, by name and limited to the declared unitDimension. It stores the code; read-only it shows the unit's name. @object-ui/core adds unitPickerOptions and the pointer helpers; the form stamps the pointer and hands the field its record. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXM7nqtiQ3M9JqGAqL --- .changeset/35490-quantity-unit-display.md | 3 +- content/docs/frontend/fields.mdx | 4 + .../form-quantity-record-35490.test.tsx | 34 +++++ .../components/src/renderers/form/form.tsx | 13 +- .../__tests__/unit-display-35490.test.ts | 58 ++++++++ ui/packages/core/src/utils/unit-display.ts | 92 ++++++++++++- ui/packages/fields/README.md | 6 + .../__tests__/quantityDisplay-35490.test.tsx | 49 ++++++- ui/packages/fields/src/index.tsx | 3 +- ui/packages/fields/src/widgets/TextField.tsx | 9 ++ .../fields/src/widgets/UnitCodeField.tsx | 124 ++++++++++++++++++ .../fields/src/widgets/useQuantityUnit.ts | 36 +++-- ui/packages/types/src/form.ts | 9 +- ui/packages/types/src/zod/form.zod.ts | 6 +- 14 files changed, 416 insertions(+), 30 deletions(-) create mode 100644 ui/packages/fields/src/widgets/UnitCodeField.tsx diff --git a/.changeset/35490-quantity-unit-display.md b/.changeset/35490-quantity-unit-display.md index d618040d022..b521a211f36 100644 --- a/.changeset/35490-quantity-unit-display.md +++ b/.changeset/35490-quantity-unit-display.md @@ -21,4 +21,5 @@ A `number` field that declares `unitConfig` now draws its unit beside the number - Decimal places: a standard code takes its organization's `sys_standard_unit_setting` row, an organization code its `sys_unit.decimal_places`. The row is the record's own organization's, never merely the first one returned. The field's `scale` is the ceiling (ADR-0158 L4). The number is drawn at that fixed width, rounded half away from zero (ADR-0158 Open item 6, ruled A): `1.5` beside a unit of 0 places reads `2`. Only the display rounds; nothing is rounded at write, and footers, exports and the API keep the exact value. - A retired organization unit, and a unit whose row the reader may not read (an external member holds no `sys_unit` read), show the bare code, never an error. - One resolver (`resolveQuantityUnit` in `@object-ui/core`) and one formatter (`formatQuantity` in `@object-ui/fields`) serve every face. -- `@object-ui/types`: `unitConfig` is now an authorable key on `FormField` and `FormFieldSchema` (by reference to the spec's `FieldSchema.unitConfig`, beside `currencyConfig`), so `objectui validate` accepts it on a hand-authored form field. The tolerant face now checks its value against the spec's `UnitConfigSchema`, where before it passed as an unknown key. On the form face only the `number` widget reads it; a `text` field's `unitMode: 'code'` is drawn by the grid and detail cells. +- `@object-ui/types`: `unitConfig` is now an authorable key on `FormField` and `FormFieldSchema` (by reference to the spec's `FieldSchema.unitConfig`, beside `currencyConfig`), so `objectui validate` accepts it on a hand-authored form field. The tolerant face now checks its value against the spec's `UnitConfigSchema`, where before it passed as an unknown key. On the form face the `number` widget reads it, and on a `text` field `unitMode: 'code'` makes the text widget the unit picker. +- A unit code field is chosen, never typed (ADR-0158 Open item 8): a `text` field declaring `unitMode: 'code'`, and the `unitField` a `record` quantity on the same form points at, draw a searchable picker (`UnitCodeField`) of the organization's non-retired units and the standard codes, each by name and restricted to the declared `unitDimension`. It stores the code; read-only, it shows the unit's name. `@object-ui/core` exports the option list (`unitPickerOptions`) and the pointer helpers (`quantityUnitCodePointers`, `withUnitCodePointer`, `declaresUnitCode`). diff --git a/content/docs/frontend/fields.mdx b/content/docs/frontend/fields.mdx index e20ee1678b0..6be7c80fc37 100644 --- a/content/docs/frontend/fields.mdx +++ b/content/docs/frontend/fields.mdx @@ -95,6 +95,10 @@ edited box). A record-mode quantity, for example, declares `unitField` holds; the list, grid and related-list reads fetch that field, and the row's `organization_id`, even when no column shows them. A `text` field declaring `unitMode: 'code'` shows the code's label. +- **Choosing a unit.** In a form, a `text` field declaring `unitMode: 'code'`, and the `unitField` a + `record` quantity on the same form points at, are a searchable unit picker, never a typed box: the + organization's non-retired units, then the standard codes, each by name and limited to the declared + `unitDimension`. The picker stores the code. Read-only, the field shows the unit's name. - **Which label.** A standard code (`KGM`, `H87`, …) shows the platform's name for it in the reader's language, served by the platform's i18n service (`messages.standardUnit`), falling back to the English name in `@objectstack/spec` (`STANDARD_UNIT_NAMES`). An organization's own code shows its diff --git a/ui/packages/components/src/renderers/form/__tests__/form-quantity-record-35490.test.tsx b/ui/packages/components/src/renderers/form/__tests__/form-quantity-record-35490.test.tsx index 20355d75899..c93d48671d9 100644 --- a/ui/packages/components/src/renderers/form/__tests__/form-quantity-record-35490.test.tsx +++ b/ui/packages/components/src/renderers/form/__tests__/form-quantity-record-35490.test.tsx @@ -23,8 +23,17 @@ function NumberProbe(props: any) { return
{JSON.stringify(props.dependentValues ?? null)}
; } +function TextProbe(props: any) { + return ( +
+ {JSON.stringify({ unitConfig: props.field?.unitConfig ?? null, record: props.dependentValues ?? null })} +
+ ); +} + beforeAll(() => { ComponentRegistry.register('field:number', NumberProbe, { namespace: 'test' }); + ComponentRegistry.register('field:text', TextProbe, { namespace: 'test' }); }, 30000); describe('form renderer — a quantity gets the live record (objectstack#35490)', () => { @@ -51,3 +60,28 @@ describe('form renderer — a quantity gets the live record (objectstack#35490)' }); }); }); + +describe("form renderer — a quantity's unit field is a unit code field (objectstack#37471)", () => { + it('stamps the pointer on the field the quantity names, and hands it the record', () => { + const Form = ComponentRegistry.get('form')!; + render( + , + ); + const unit = JSON.parse(screen.getByTestId('text-probe-unit_code').textContent!); + expect(unit.unitConfig).toEqual({ unitMode: 'code', unitDimension: 'mass' }); + expect(unit.record).toHaveProperty('unit_code'); + // A text field no quantity names is untouched, and gets no record. + expect(JSON.parse(screen.getByTestId('text-probe-note').textContent!)).toEqual({ unitConfig: null, record: null }); + }); +}); diff --git a/ui/packages/components/src/renderers/form/form.tsx b/ui/packages/components/src/renderers/form/form.tsx index 41832589aae..001128151ad 100644 --- a/ui/packages/components/src/renderers/form/form.tsx +++ b/ui/packages/components/src/renderers/form/form.tsx @@ -6,7 +6,7 @@ * LICENSE file in the root directory of this source tree. */ -import { ComponentRegistry, resolveFieldRuleState, evalFieldPredicate, resolveCascadingOptions, resolveDependsOnFields, CASCADE_OPTION_WIDGET_TYPES, EXPANDABLE_FIELD_TYPES, isValueStillOffered, isMissingForRequired, isServerOwnedValue, isActionSwitchedOff, type FieldRulePredicate } from '@object-ui/core'; +import { ComponentRegistry, resolveFieldRuleState, evalFieldPredicate, resolveCascadingOptions, resolveDependsOnFields, CASCADE_OPTION_WIDGET_TYPES, EXPANDABLE_FIELD_TYPES, isValueStillOffered, isMissingForRequired, isServerOwnedValue, isActionSwitchedOff, declaresUnitCode, quantityUnitCodePointers, withUnitCodePointer, type FieldRulePredicate } from '@object-ui/core'; import type { FormSchema, FormField as FormFieldConfig, FormFieldTab, FormFieldPane, FieldCondition, SelectOption } from '@object-ui/types'; import { useForm, type RefCallBack } from 'react-hook-form'; import { Form, FormField, FormItem, FormLabel, FormControl, FormMessage, FormDescription } from '../../ui/form'; @@ -1446,8 +1446,9 @@ function stripRegisteredFieldProps(type: string, props: RenderFieldProps): Rende // A record-mode amount's symbol and decimals follow the code the user picks // in its sibling select, so the amount box needs the live record too. ...(RECORD_CURRENCY_WIDGET_TYPES.has(normalizedType) ? { dependentValues } : {}), - // A record-mode quantity's unit follows the code in its sibling field. - ...(QUANTITY_WIDGET_TYPES.has(normalizedType) ? { dependentValues } : {}), + // A record-mode quantity's unit follows the code in its sibling field, and + // a unit code field offers its record's organization's units. + ...(QUANTITY_WIDGET_TYPES.has(normalizedType) || declaresUnitCode(fieldProps.field as never) ? { dependentValues } : {}), // Only the widgets that report unparseable text read it; every other one // would spread an unknown handler onto its DOM (objectstack#27483). ...(INVALID_INPUT_REPORTING_WIDGET_TYPES.has(normalizedType) ? { onInvalidInputChange } : {}), @@ -2576,6 +2577,9 @@ ComponentRegistry.register('form', // Read once per object and handed down on the field's own metadata. const codeFieldNames = React.useMemo(() => currencyCodeFieldNames(fields as unknown[]), [fields]); const usedCurrencyCodes = useUsedCurrencyCodes(contextDataSource, schema.objectName, codeFieldNames); + // The unit code fields a quantity on this form points at (ADR-0158 Open + // item 8): each is drawn as the unit picker (`withUnitCodePointer`). + const unitCodePointers = React.useMemo(() => quantityUnitCodePointers(fields as unknown[]), [fields]); // The record as each visible update action would leave it // (objectstack#28382). A declarative update action writes its static @@ -4289,7 +4293,8 @@ ComponentRegistry.register('form', // metadata was stashed (standalone forms). // A record-currency code field also carries the codes its // object's records already hold (`usedCurrencyCodes`). - field: withUsedCurrencyCodes(field.field || field, usedCurrencyCodes[name]), + // A unit code field a quantity points at carries that pointer. + field: withUnitCodePointer(withUsedCurrencyCodes(field.field || field, usedCurrencyCodes[name]), unitCodePointers.get(name)), ...formField, inputType: fieldProps.inputType, // The field's label, forwarded explicitly because the diff --git a/ui/packages/core/src/utils/__tests__/unit-display-35490.test.ts b/ui/packages/core/src/utils/__tests__/unit-display-35490.test.ts index c73713775c7..6f608e59ae7 100644 --- a/ui/packages/core/src/utils/__tests__/unit-display-35490.test.ts +++ b/ui/packages/core/src/utils/__tests__/unit-display-35490.test.ts @@ -19,6 +19,10 @@ import { quantityUnitReadField, resolveQuantityUnit, shownQuantityUnitReads, + declaresUnitCode, + quantityUnitCodePointers, + unitPickerOptions, + withUnitCodePointer, } from '../unit-display'; const FIXED = { type: 'number', unitConfig: { unitMode: 'fixed', unit: 'KGM' } }; @@ -151,3 +155,57 @@ describe('shownQuantityUnitReads — what a projection fetches for shown quantit expect(shownQuantityUnitReads([{ field: 'qty', hidden: true }], fields)).toEqual([]); }); }); + +describe('the unit picker (ADR-0158 Open item 8, objectstack#37471)', () => { + const catalog = { + organizationUnits: [ + { code: 'BOX_12', label: 'Box of 12', dimension: 'package', retired: false, organization_id: 'org_a' }, + { code: 'JIN1', label: 'Jin', dimension: 'mass', retired: false, organization_id: 'org_a' }, + { code: 'OLD1', label: 'Old', dimension: 'mass', retired: true, organization_id: 'org_a' }, + { code: 'BAG_B', label: 'Bag', dimension: 'package', retired: false, organization_id: 'org_b' }, + ], + }; + const names: Record = { KGM: 'kilogram', GRM: 'gram' }; + const label = (code: string) => names[code]; + + it("offers the record's organization's non-retired units first, then every standard code, storing codes", () => { + const options = unitPickerOptions(catalog, { organization_id: 'org_a' }, label); + const own = options.filter((o) => !o.standard).map((o) => `${o.code}=${o.label}`); + expect(own).toEqual(['BOX_12=Box of 12', 'JIN1=Jin']); + expect(options.findIndex((o) => o.standard)).toBe(2); + expect(options).toContainEqual({ code: 'KGM', label: 'kilogram', standard: true }); + // A standard code with no name in the reader's language shows its code. + expect(options).toContainEqual({ code: 'H87', label: 'H87', standard: true }); + }); + + it("restricts every unit to the field's unitDimension", () => { + const options = unitPickerOptions(catalog, { organization_id: 'org_a' }, label, { unitMode: 'code', unitDimension: 'mass' }); + expect(options.filter((o) => !o.standard).map((o) => o.code)).toEqual(['JIN1']); + expect(options.map((o) => o.code)).toContain('GRM'); + expect(options.map((o) => o.code)).not.toContain('H87'); + }); + + it('offers every readable organization unit when the record names no organization', () => { + expect(unitPickerOptions(catalog, {}, label).filter((o) => !o.standard).map((o) => o.code)).toEqual(['BOX_12', 'JIN1', 'BAG_B']); + }); + + it("names the unit field a record-mode quantity points at, with the quantity's dimension", () => { + const pointers = quantityUnitCodePointers([ + { name: 'qty', type: 'number', unitConfig: { unitMode: 'record', unitField: 'unit_code', unitDimension: 'mass' } }, + { name: 'w', field: { type: 'number', unitConfig: { unitMode: 'record', unitField: 'w_unit' } } }, + { name: 'kg', type: 'number', unitConfig: { unitMode: 'fixed', unit: 'KGM' } }, + ]); + expect([...pointers]).toEqual([['unit_code', { unitDimension: 'mass' }], ['w_unit', {}]]); + }); + + it('stamps the pointer on a copy, and never over a declared unitConfig', () => { + const field = { name: 'unit_code', type: 'text' }; + const stamped = withUnitCodePointer(field, { unitDimension: 'mass' }); + expect(stamped).toEqual({ name: 'unit_code', type: 'text', unitConfig: { unitMode: 'code', unitDimension: 'mass' } }); + expect(field).not.toHaveProperty('unitConfig'); + expect(declaresUnitCode(stamped)).toBe(true); + const declared = { type: 'text', unitConfig: { unitMode: 'code' } }; + expect(withUnitCodePointer(declared, { unitDimension: 'mass' })).toBe(declared); + expect(withUnitCodePointer(field, undefined)).toBe(field); + }); +}); diff --git a/ui/packages/core/src/utils/unit-display.ts b/ui/packages/core/src/utils/unit-display.ts index 8616dee9c2c..f718ecc3076 100644 --- a/ui/packages/core/src/utils/unit-display.ts +++ b/ui/packages/core/src/utils/unit-display.ts @@ -27,7 +27,7 @@ * no label and no decimal places of its own. */ -import { standardUnitOf } from '@objectstack/spec/data'; +import { STANDARD_UNITS, standardUnitOf } from '@objectstack/spec/data'; import { columnIdentity } from './column-identity.js'; /** The part of a field definition the resolution reads. */ @@ -42,6 +42,8 @@ export interface OrganizationUnitRow { label?: unknown; decimal_places?: unknown; retired?: unknown; + /** The unit's dimension (`mass`, …, `package`), read by the picker's `unitDimension` filter. */ + dimension?: unknown; organization_id?: unknown; } @@ -229,3 +231,91 @@ export function shownQuantityUnitReads( } return [...out]; } + +/* ── the unit picker (ADR-0158 Open item 8, objectstack#37471) ─────────── */ + +/** Whether `field` is a `text` field that holds a unit code (`unitMode: 'code'`). */ +export function declaresUnitCode(field: UnitBearingField | null | undefined): boolean { + return field?.type === 'text' && declaresQuantityUnit(field); +} + +/** The `unitDimension` a `unitConfig` restricts its units to, if any. */ +function unitDimensionOf(config: unknown): string | undefined { + const dimension = (config as { unitDimension?: unknown } | null | undefined)?.unitDimension; + return typeof dimension === 'string' && dimension !== '' ? dimension : undefined; +} + +/** + * The unit code fields a set of form fields declares by POINTER: the + * `unitField` of every `record`-mode quantity among them, mapped to the + * quantity's `unitDimension` (ADR-0158: "the field a `record` quantity's + * `unitField` names is a unit code field by that pointer, so it declares + * nothing itself"). Each entry is a form field config, which carries its + * metadata flat or on `.field`. + */ +export function quantityUnitCodePointers(fields: readonly unknown[] | null | undefined): Map { + const pointers = new Map(); + for (const entry of fields ?? []) { + const meta = ((entry as { field?: unknown })?.field ?? entry) as UnitBearingField | null; + const config = meta?.unitConfig as { unitMode?: unknown; unitField?: unknown } | undefined; + if (meta?.type !== 'number' || config?.unitMode !== 'record' || typeof config.unitField !== 'string') continue; + const dimension = unitDimensionOf(config); + pointers.set(config.unitField, dimension ? { unitDimension: dimension } : {}); + } + return pointers; +} + +/** + * `field` as a unit code field when a quantity points at it: a copy carrying + * `unitConfig: { unitMode: 'code' }` (and the quantity's `unitDimension`), so + * the text widget draws the unit picker. A field that declares its own + * `unitConfig`, or that nothing points at, comes back unchanged. + */ +export function withUnitCodePointer(field: F, pointer: { unitDimension?: string } | undefined): F { + if (!pointer || field === null || typeof field !== 'object') return field; + if ((field as UnitBearingField).unitConfig !== undefined) return field; + return { ...field, unitConfig: { unitMode: 'code', ...pointer } }; +} + +/** One choice the unit picker offers. */ +export interface UnitPickerOption { + /** The code the field stores. */ + code: string; + /** The name shown: the unit's label, or its code when it has none. */ + label: string; + /** A standard (U1) code, as opposed to one of the organization's own. */ + standard: boolean; +} + +/** + * The units a unit code field may hold, as the server's write check accepts + * them: the organization's non-retired `sys_unit` rows, then every standard + * code, each restricted to `unitDimension` when the field declares one. The + * organization's rows are the record's own organization's when the record + * carries one (as `pickRowForOrganization` chooses), else every readable row. + * `standardLabel` names a standard code in the reader's language. + */ +export function unitPickerOptions( + catalog: UnitCatalog, + record: Readonly> | null | undefined, + standardLabel: (code: string) => string | undefined, + unitConfig?: unknown, +): UnitPickerOption[] { + const dimension = unitDimensionOf(unitConfig); + const scoped = record && Object.prototype.hasOwnProperty.call(record, 'organization_id'); + const organization = scoped ? organizationOf(record as { organization_id?: unknown }) : undefined; + const own: UnitPickerOption[] = []; + const seen = new Set(); + for (const row of catalog.organizationUnits ?? []) { + const code = row?.code; + if (typeof code !== 'string' || code === '' || row.retired === true || seen.has(code)) continue; + if (scoped && organizationOf(row) !== organization) continue; + if (dimension && row.dimension !== dimension) continue; + seen.add(code); + own.push({ code, label: typeof row.label === 'string' && row.label !== '' ? row.label : code, standard: false }); + } + const standard = Object.entries(STANDARD_UNITS) + .filter(([, unit]) => !dimension || unit.dimension === dimension) + .map(([code]) => ({ code, label: standardLabel(code) ?? code, standard: true })); + return [...own, ...standard]; +} diff --git a/ui/packages/fields/README.md b/ui/packages/fields/README.md index 74a31eebfc0..a01aa98290b 100644 --- a/ui/packages/fields/README.md +++ b/ui/packages/fields/README.md @@ -125,6 +125,12 @@ one quantity identically. The pieces: A cell or widget only sees a `record`-mode quantity's code when its host hands it the row (`dependentValues`). The grid, list, detail and form hosts do. +A unit code field is chosen, not typed: `TextField` draws `UnitCodeField`, a searchable picker over +`unitPickerOptions` (the organization's non-retired units, then the standard codes, by name and limited to +the `unitDimension`), for a `text` field declaring `unitMode: 'code'` and for the `unitField` a quantity on +the same form points at (the form stamps that pointer with `withUnitCodePointer`). It stores the code; read-only, +it shows the unit's name. + ### Rendering form field widgets outside the form The full widget surface is exported for consumers that render field widgets diff --git a/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx b/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx index aa0da9160db..cb687884e4f 100644 --- a/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx +++ b/ui/packages/fields/src/__tests__/quantityDisplay-35490.test.tsx @@ -21,12 +21,13 @@ import { describe, it, expect, afterEach } from 'vitest'; import React from 'react'; -import { render, cleanup, screen, waitFor } from '@testing-library/react'; +import { render, cleanup, screen, waitFor, fireEvent } from '@testing-library/react'; import '@testing-library/jest-dom'; import { SchemaRendererContext } from '@object-ui/react'; import { I18nProvider } from '@object-ui/i18n'; import { getCellRenderer } from '../index'; import { NumberField } from '../widgets/NumberField'; +import { TextField } from '../widgets/TextField'; import { formatQuantity, quantityDisplayPlaces } from '../widgets/quantity-format'; afterEach(cleanup); @@ -34,8 +35,8 @@ afterEach(cleanup); const text = (s: string | null | undefined) => (s ?? '').replace(/\u00a0/g, ' '); const ORG_UNITS = [ - { code: 'BOX_12', label: 'Box of 12', decimal_places: 1, retired: false, organization_id: 'org_a' }, - { code: 'JIN1', label: 'Jin', decimal_places: 2, retired: true, organization_id: 'org_a' }, + { code: 'BOX_12', label: 'Box of 12', decimal_places: 1, dimension: 'package', retired: false, organization_id: 'org_a' }, + { code: 'JIN1', label: 'Jin', decimal_places: 2, dimension: 'mass', retired: true, organization_id: 'org_a' }, ]; const SETTINGS = [ { code: 'GRM', decimal_places: 3, organization_id: 'org_a' }, @@ -170,11 +171,9 @@ describe('a unit-code field (Open item 8)', () => { describe('formatQuantity — the one formatter', () => { const field = { name: 'qty', type: 'number' } as any; - it('marks a stored value with more places than shown, and changes nothing stored', () => { - const value = 1.5; - const out = formatQuantity(value, field, { code: 'H87', standard: true, label: 'pc', decimals: 0 }, 'en-US'); + it('marks a stored value with more places than shown', () => { + const out = formatQuantity(1.5, field, { code: 'H87', standard: true, label: 'pc', decimals: 0 }, 'en-US'); expect(out).toEqual({ text: '2\u00a0pc', number: '2', unit: 'pc', hidden: true }); - expect(value).toBe(1.5); expect(formatQuantity(1.5, field, { code: 'GRM', standard: true, label: 'g', decimals: 3 }, 'en-US').hidden).toBe(false); }); @@ -192,3 +191,39 @@ describe('formatQuantity — the one formatter', () => { expect(quantityDisplayPlaces(1, { ...field, scale: 2 })).toBe(1); }); }); + +describe('the unit picker on the form face (ADR-0158 Open item 8, objectstack#37471)', () => { + const CODE = { name: 'unit_code', type: 'text', unitConfig: { unitMode: 'code' } } as any; + const drawText = (props: Record) => + render( + +
+ {}} field={CODE} dependentValues={{ organization_id: 'org_a' }} {...(props as any)} /> +
+
, + ); + + it("read-only, shows the unit's name, not the bare code", async () => { + drawText({ value: 'BOX_12', readonly: true }); + await waitFor(() => expect(faceText()).toBe('Box of 12')); + cleanup(); + drawText({ value: 'H87', readonly: true }); + expect(faceText()).toBe('piece'); + }); + + it("lists the organization's live units and the standard codes by name, and stores the code picked", async () => { + const picked: string[] = []; + drawText({ onChange: (code: string) => picked.push(code) }); + fireEvent.click(screen.getByRole('combobox')); + await waitFor(() => expect(screen.getByRole('option', { name: /Box of 12/ })).toBeInTheDocument()); + // The retired unit is not offered. + expect(screen.queryByRole('option', { name: /Jin/ })).toBeNull(); + fireEvent.click(screen.getByRole('option', { name: /kilogram/ })); + expect(picked).toEqual(['KGM']); + }); + + it('shows the stored unit by name on the closed picker', async () => { + drawText({ value: 'BOX_12' }); + await waitFor(() => expect(screen.getByRole('combobox')).toHaveTextContent('Box of 12')); + }); +}); diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index cefc6eaa7d0..70df849bed1 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -632,7 +632,8 @@ export { formatNumberFieldValue }; */ export { QuantityText, UnitCodeText }; export { formatQuantity, quantityDisplayPlaces, type QuantityDisplay } from './widgets/quantity-format.js'; -export { useQuantityUnit, useStandardUnitLabel, readUnitCatalog } from './widgets/useQuantityUnit.js'; +export { useQuantityUnit, useStandardUnitLabel, useUnitCatalog, readUnitCatalog } from './widgets/useQuantityUnit.js'; +export { UnitCodeField } from './widgets/UnitCodeField.js'; /** * Format currency value in compact form for mobile display. diff --git a/ui/packages/fields/src/widgets/TextField.tsx b/ui/packages/fields/src/widgets/TextField.tsx index 61eb6a86ebc..e970f999210 100644 --- a/ui/packages/fields/src/widgets/TextField.tsx +++ b/ui/packages/fields/src/widgets/TextField.tsx @@ -7,6 +7,8 @@ import { PHONE_TOUCH_HEIGHT } from './touchTarget.js'; import { CurrencyCodeField, isCurrencyCodeField } from './CurrencyCodeField.js'; import { ScanFieldButton, useFieldScanOffered } from './ScanFieldButton.js'; import { InCellTextInput } from './InCellTextInput.js'; +import { declaresUnitCode } from '@object-ui/core'; +import { UnitCodeField } from './UnitCodeField.js'; /** * TextField - Standard single-line or multi-line text input @@ -25,6 +27,13 @@ export function TextField({ value, onChange, field, readonly, error, inCell, onC return ; } + // A unit code field (ADR-0158 Open item 8): declared `unitMode: 'code'`, or + // the `unitField` a quantity points at (stamped by the form). Chosen from + // the units the server accepts and shown by name, never typed. + if (declaresUnitCode(fieldData as { type?: string; unitConfig?: unknown })) { + return ; + } + if (readonly) { return {value || }; } diff --git a/ui/packages/fields/src/widgets/UnitCodeField.tsx b/ui/packages/fields/src/widgets/UnitCodeField.tsx new file mode 100644 index 00000000000..edc9249c177 --- /dev/null +++ b/ui/packages/fields/src/widgets/UnitCodeField.tsx @@ -0,0 +1,124 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import React from 'react'; +import { Check, ChevronsUpDown } from 'lucide-react'; +import { + Button, + Command, + CommandEmpty, + CommandGroup, + CommandInput, + CommandItem, + CommandList, + CommandSeparator, + EmptyValue, + Popover, + PopoverContent, + PopoverTrigger, + cn, +} from '@object-ui/components'; +import { unitPickerOptions, type UnitPickerOption } from '@object-ui/core'; +import type { FieldWidgetComponentProps } from './types.js'; +import { toDomProps } from './toDomProps.js'; +import { useFieldTranslation } from './useFieldTranslation.js'; +import { useQuantityUnit, useStandardUnitLabel, useUnitCatalog } from './useQuantityUnit.js'; + +/** + * UnitCodeField — the control a unit code field renders (ADR-0158 Open item 8, + * ruled A, objectstack#37471): a `text` field declaring `unitMode: 'code'`, or + * the `unitField` a `record`-mode quantity points at (the form stamps that + * pointer, `withUnitCodePointer`). A searchable list of the units the server's + * write check accepts: the organization's own non-retired units, then the + * standard codes, each by its name in the reader's language and restricted to + * the field's `unitDimension`. It stores the code. + * + * Read-only, it shows the unit's name, the face the grid and detail cells + * draw (a retired or unreadable unit shows its bare code). A stored code the + * list no longer offers (a unit retired since) stays selected and is shown; + * nothing rewrites it until the user picks another. + */ +export function UnitCodeField({ + value, + onChange, + field, + readonly, + error, + className, + dependentValues, + ...props +}: FieldWidgetComponentProps & { dependentValues?: Record }) { + const { t } = useFieldTranslation(); + const current = typeof value === 'string' && value !== '' ? value : undefined; + const shown = useQuantityUnit(field, dependentValues, current); + const standardLabel = useStandardUnitLabel(); + const catalog = useUnitCatalog(!readonly); + const [open, setOpen] = React.useState(false); + + if (readonly) { + return current ? ( + + {shown?.label ?? current} + + ) : ( + + ); + } + + const options = unitPickerOptions(catalog, dependentValues, standardLabel, (field as { unitConfig?: unknown } | undefined)?.unitConfig); + const own = options.filter((o) => !o.standard); + const standard = options.filter((o) => o.standard); + const item = (option: UnitPickerOption) => ( + { + onChange(option.code); + setOpen(false); + }} + > + + {option.label} + {option.label !== option.code && {option.code}} + + ); + const domProps = toDomProps(props); + + return ( + + + + + + + + + {t('common.noResults')} + {own.length > 0 && {own.map(item)}} + {own.length > 0 && standard.length > 0 && } + {standard.length > 0 && {standard.map(item)}} + + + + + ); +} diff --git a/ui/packages/fields/src/widgets/useQuantityUnit.ts b/ui/packages/fields/src/widgets/useQuantityUnit.ts index 74aeadf23c7..e0203da2c10 100644 --- a/ui/packages/fields/src/widgets/useQuantityUnit.ts +++ b/ui/packages/fields/src/widgets/useQuantityUnit.ts @@ -56,7 +56,12 @@ const rowsOf = (answer: unknown): readonly Record[] => { return Array.isArray(rows) ? (rows as Record[]) : []; }; -/** One read per adapter, kept for the session; a read that fails resolves to "unread". */ +/** + * One read per adapter, kept for the session; a read that fails resolves to + * "unread" and stays so until a reload. Kept on purpose: an external member's + * `sys_unit` refusal is permanent, and re-reading it per mount would cost one + * request per cell of a grid. + */ const CATALOG_READS = new WeakMap>(); /** @@ -67,12 +72,14 @@ const CATALOG_READS = new WeakMap>(); export function readUnitCatalog(source: UnitSource): Promise { const held = CATALOG_READS.get(source); if (held) return held; + // `$count: false`: no face draws a count of units, so the server need not + // count the table (the adapter's opt-out, `countOptOut.test.ts`). const read = (object: string, select: string[]): Promise => source - .find(object, { $select: select, $top: UNIT_READ_TOP }) + .find(object, { $select: select, $top: UNIT_READ_TOP, $count: false }) .then((answer) => rowsOf(answer) as unknown as readonly R[], () => undefined); const catalog = Promise.all([ - read(ORGANIZATION_UNIT_OBJECT, ['code', 'label', 'decimal_places', 'retired', 'organization_id']), + read(ORGANIZATION_UNIT_OBJECT, ['code', 'label', 'decimal_places', 'retired', 'dimension', 'organization_id']), read(STANDARD_UNIT_SETTING_OBJECT, ['code', 'decimal_places', 'organization_id']), ]).then(([organizationUnits, standardUnitSettings]): UnitCatalog => ({ ...(organizationUnits ? { organizationUnits } : {}), @@ -115,11 +122,22 @@ export function useQuantityUnit( value?: unknown, dataSource?: unknown, ): ResolvedUnit | undefined { - const ctx = useContext(SchemaRendererContext); - const source = (dataSource ?? ctx?.dataSource) as UnitSource | null | undefined; const code = quantityUnitCode(field, record, value); const standardLabel = useStandardUnitLabel(); - const canRead = code !== undefined && typeof source?.find === 'function'; + const rows = useUnitCatalog(code !== undefined, dataSource); + if (code === undefined) return undefined; + return resolveQuantityUnit(code, rows, record, standardLabel(code)); +} + +/** + * The unit rows (`readUnitCatalog`) through the data source the surfaces use, + * or `dataSource` when given; empty until they are read, or when `enabled` is + * false or there is no source to read through. + */ +export function useUnitCatalog(enabled: boolean, dataSource?: unknown): UnitCatalog { + const ctx = useContext(SchemaRendererContext); + const source = (dataSource ?? ctx?.dataSource) as UnitSource | null | undefined; + const canRead = enabled && typeof source?.find === 'function'; const [catalog, setCatalog] = useState<{ source: object; catalog: UnitCatalog } | undefined>(undefined); useEffect(() => { if (!canRead || !source) return; @@ -131,7 +149,7 @@ export function useQuantityUnit( current = false; }; }, [canRead, source]); - if (code === undefined) return undefined; - const rows = catalog && catalog.source === source ? catalog.catalog : {}; - return resolveQuantityUnit(code, rows, record, standardLabel(code)); + return catalog && catalog.source === source ? catalog.catalog : EMPTY_CATALOG; } + +const EMPTY_CATALOG: UnitCatalog = Object.freeze({}); diff --git a/ui/packages/types/src/form.ts b/ui/packages/types/src/form.ts index 28632876ff0..83ddc9ddfbf 100644 --- a/ui/packages/types/src/form.ts +++ b/ui/packages/types/src/form.ts @@ -2097,10 +2097,11 @@ export interface FormField { * `number` field, `{ unitMode: 'fixed', unit: 'KGM' }` gives every value one * unit and `{ unitMode: 'record', unitField: 'unit_code' }` reads it off the * record's own unit field. On a `text` field, `{ unitMode: 'code' }` marks - * the value itself as a unit code; the grid and detail cells show its name, - * but on this form face nothing reads that mode yet (the text widget draws - * the bare code, and no unit picker exists). The `number` widget shows the - * unit's name beside the value, at the unit's display decimal places. + * the value itself as a unit code: the text widget draws the unit picker + * (the organization's units and the standard codes, by name; read-only, the + * unit's name), as it does for the `unitField` a quantity on the same form + * points at. The `number` widget shows the unit's name beside the value, at + * the unit's display decimal places. */ unitConfig?: SpecField['unitConfig']; /** diff --git a/ui/packages/types/src/zod/form.zod.ts b/ui/packages/types/src/zod/form.zod.ts index f32c8af1ac5..c082a7d12ba 100644 --- a/ui/packages/types/src/zod/form.zod.ts +++ b/ui/packages/types/src/zod/form.zod.ts @@ -1160,9 +1160,9 @@ export const FormFieldSchema = z.looseObject({ scale: stripImportedDefaults(SpecFieldSchema).shape.scale, currencyConfig: stripImportedDefaults(SpecFieldSchema).shape.currencyConfig, // objectstack#35490 — the unit a `number` quantity is drawn with: - // `NumberField` and the number cell read it (ADR-0158 R1 display). A - // unit-code `text` field's `unitMode: 'code'` is read by the text cell - // only; on this form face the text widget does not read it yet. + // `NumberField` and the number cell read it (ADR-0158 R1 display). On a + // `text` field, `unitMode: 'code'` makes the text widget the unit picker + // (Open item 8, objectstack#37471), and the text cell draws the unit's name. unitConfig: stripImportedDefaults(SpecFieldSchema).shape.unitConfig, minLength: stripImportedDefaults(SpecFieldSchema).shape.minLength, maxLength: stripImportedDefaults(SpecFieldSchema).shape.maxLength, From a71abb845881f53923449a5749ab07e91f8c1930 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:46:13 +0000 Subject: [PATCH 12/13] fix(units): read the unit pointers off field metadata the form hands over (#37471) The form already reads its configs' .field stash (a ledgered reader); the core helper now takes the metadata alone, so the form-field channel census keeps one reader of that key per module. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXM7nqtiQ3M9JqGAqL --- ui/packages/components/src/renderers/form/form.tsx | 5 ++++- .../core/src/utils/__tests__/unit-display-35490.test.ts | 2 +- ui/packages/core/src/utils/unit-display.ts | 6 +++--- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/ui/packages/components/src/renderers/form/form.tsx b/ui/packages/components/src/renderers/form/form.tsx index 001128151ad..86efc7bb2e0 100644 --- a/ui/packages/components/src/renderers/form/form.tsx +++ b/ui/packages/components/src/renderers/form/form.tsx @@ -2579,7 +2579,10 @@ ComponentRegistry.register('form', const usedCurrencyCodes = useUsedCurrencyCodes(contextDataSource, schema.objectName, codeFieldNames); // The unit code fields a quantity on this form points at (ADR-0158 Open // item 8): each is drawn as the unit picker (`withUnitCodePointer`). - const unitCodePointers = React.useMemo(() => quantityUnitCodePointers(fields as unknown[]), [fields]); + const unitCodePointers = React.useMemo( + () => quantityUnitCodePointers((fields as Array<{ field?: unknown }>).map((f) => f?.field || f)), + [fields], + ); // The record as each visible update action would leave it // (objectstack#28382). A declarative update action writes its static diff --git a/ui/packages/core/src/utils/__tests__/unit-display-35490.test.ts b/ui/packages/core/src/utils/__tests__/unit-display-35490.test.ts index 6f608e59ae7..8e464eb98fe 100644 --- a/ui/packages/core/src/utils/__tests__/unit-display-35490.test.ts +++ b/ui/packages/core/src/utils/__tests__/unit-display-35490.test.ts @@ -192,7 +192,7 @@ describe('the unit picker (ADR-0158 Open item 8, objectstack#37471)', () => { it("names the unit field a record-mode quantity points at, with the quantity's dimension", () => { const pointers = quantityUnitCodePointers([ { name: 'qty', type: 'number', unitConfig: { unitMode: 'record', unitField: 'unit_code', unitDimension: 'mass' } }, - { name: 'w', field: { type: 'number', unitConfig: { unitMode: 'record', unitField: 'w_unit' } } }, + { name: 'w', type: 'number', unitConfig: { unitMode: 'record', unitField: 'w_unit' } }, { name: 'kg', type: 'number', unitConfig: { unitMode: 'fixed', unit: 'KGM' } }, ]); expect([...pointers]).toEqual([['unit_code', { unitDimension: 'mass' }], ['w_unit', {}]]); diff --git a/ui/packages/core/src/utils/unit-display.ts b/ui/packages/core/src/utils/unit-display.ts index f718ecc3076..136a1c852ba 100644 --- a/ui/packages/core/src/utils/unit-display.ts +++ b/ui/packages/core/src/utils/unit-display.ts @@ -250,13 +250,13 @@ function unitDimensionOf(config: unknown): string | undefined { * `unitField` of every `record`-mode quantity among them, mapped to the * quantity's `unitDimension` (ADR-0158: "the field a `record` quantity's * `unitField` names is a unit code field by that pointer, so it declares - * nothing itself"). Each entry is a form field config, which carries its - * metadata flat or on `.field`. + * nothing itself"). Each entry is a field's metadata (a form hands its + * fields' metadata, read off the config's `.field` stash where it has one). */ export function quantityUnitCodePointers(fields: readonly unknown[] | null | undefined): Map { const pointers = new Map(); for (const entry of fields ?? []) { - const meta = ((entry as { field?: unknown })?.field ?? entry) as UnitBearingField | null; + const meta = entry as UnitBearingField | null; const config = meta?.unitConfig as { unitMode?: unknown; unitField?: unknown } | undefined; if (meta?.type !== 'number' || config?.unitMode !== 'record' || typeof config.unitField !== 'string') continue; const dimension = unitDimensionOf(config); From 37fca77eee7be2df4c6073dac7c5d9a628ca6552 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:50:50 +0000 Subject: [PATCH 13/13] chore(changeset): grade @objectstack/spec minor for the new standard-unit name exports (#35490) The PR declares Metadata-protocol: added. The level gate reads only packages/**/src, and spec's public surface grew by STANDARD_UNIT_NAMES and standardUnitName, so spec carries the minor beside @object-ui/types. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CXM7nqtiQ3M9JqGAqL --- .changeset/35490-quantity-unit-display.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/35490-quantity-unit-display.md b/.changeset/35490-quantity-unit-display.md index b521a211f36..795c709e40a 100644 --- a/.changeset/35490-quantity-unit-display.md +++ b/.changeset/35490-quantity-unit-display.md @@ -1,5 +1,5 @@ --- -'@objectstack/spec': patch +'@objectstack/spec': minor '@objectstack/platform-objects': patch '@object-ui/core': patch '@object-ui/fields': patch