From 4f7bf9f4ad4da64db064ec3ef70df42d61f7e9bb Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 08:58:17 +0000 Subject: [PATCH 01/15] wip(#36373): business wording in the report and widget panels --- .../inspectors/DashboardWidgetInspector.tsx | 81 ++++++++++--- .../inspectors/InspectorComboField.tsx | 11 +- .../inspectors/ReportDefaultInspector.tsx | 104 ++++++++++++---- .../metadata-admin/inspectors/_shared.tsx | 17 ++- .../inspectors/dataset-picker-options.ts | 12 ++ .../metadata-admin/inspectors/servedLabel.ts | 112 ++++++++++++++++++ .../previews/ViewColumnPanes.tsx | 15 ++- .../previews/useDatasetCatalog.ts | 7 ++ .../views/studio-design/servedReportText.ts | 54 +++++++++ ui/packages/i18n/src/namespaces/studio/en.ts | 54 +++++---- ui/packages/i18n/src/namespaces/studio/zh.ts | 53 +++++---- 11 files changed, 430 insertions(+), 90 deletions(-) create mode 100644 ui/packages/app-shell/src/views/metadata-admin/inspectors/servedLabel.ts create mode 100644 ui/packages/app-shell/src/views/studio-design/servedReportText.ts diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardWidgetInspector.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardWidgetInspector.tsx index 6d372a66f27..cc7b9b5fa72 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardWidgetInspector.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardWidgetInspector.tsx @@ -31,7 +31,12 @@ import { } from '@object-ui/components'; import type { DashboardWidgetSchema, DashboardWidgetTypeName } from '@object-ui/types'; import { completeWidgetLayout, defaultWidgetPlacement } from '@object-ui/types'; -import { resolveDashboardFilterDefs, type DashboardFilterDef, type RegistryComponentMeta } from '@object-ui/core'; +import { + DATE_RANGE_FILTER_NAME, + resolveDashboardFilterDefs, + type DashboardFilterDef, + type RegistryComponentMeta, +} from '@object-ui/core'; import type { MetadataInspectorProps } from '../inspector-registry.js'; import { t, tFormat } from '../i18n.js'; // The spec's `I18nLabel` resolver (new in @objectstack/spec 17.0.0-rc.6), @@ -45,10 +50,11 @@ import { DatasetNamesEditor, datasetDimensionOptions, datasetMeasureOptions, - datasetPickerOptions, } from './ReportDefaultInspector.js'; -import { useDatasetCatalog, useDatasetSemantics } from '../previews/useDatasetCatalog.js'; -import { packageDatasetsFirst } from './dataset-picker-options.js'; +import { useDatasetCatalog, useDatasetSemantics, type DatasetDimensionInfo } from '../previews/useDatasetCatalog.js'; +import { datasetLabelOptions, packageDatasetsFirst } from './dataset-picker-options.js'; +import { shownLabel, writtenLabel, useLabelLanguage } from './servedLabel.js'; +import { useServedWidgetText } from '../../studio-design/servedDashboardText.js'; import { DatasetCreateEntry, useStudioDatasetAuthoring } from '../../studio-design/datasetCreate.js'; import type { ObjectFieldInfo } from '../previews/useObjectFields.js'; import { widgetMissingInputs } from '../../studio-design/metadataError.js'; @@ -139,8 +145,11 @@ export function DashboardWidgetInspector({ // Report inspector's pickers share (see `datasetPickerOptions` and its // siblings): a dataset's declared `description` rides as the combo's muted // `hint`, a member's `label` beside its name. The stored value is the name. + // objectstack#36373 — business wording: a data source reads as its label, + // a field as its label; the machine names stay the stored values, reachable + // on hover (`nameOnHover` on each combo below). const datasetComboOptions: InspectorComboOption[] = React.useMemo(() => { - const opts: InspectorComboOption[] = datasetPickerOptions( + const opts: InspectorComboOption[] = datasetLabelOptions( packageDatasetsFirst(catalog.datasets, datasetAuthoring?.packageId), ); if (datasetName && !opts.some((o) => o.value === datasetName)) { @@ -149,8 +158,8 @@ export function DashboardWidgetInspector({ return opts; }, [catalog.datasets, datasetName, datasetAuthoring?.packageId]); const measureOptions: ObjectFieldInfo[] = React.useMemo( - () => datasetMeasureOptions(semantics.measures), - [semantics.measures], + () => datasetMeasureOptions(semantics.measures, locale), + [semantics.measures, locale], ); const dimensionOptions: ObjectFieldInfo[] = React.useMemo( () => datasetDimensionOptions(semantics.dimensions), @@ -161,7 +170,7 @@ export function DashboardWidgetInspector({ // object-field source. The combo prints the value (the dimension name) // itself, so the label is the author's text alone. const fieldComboOptions: InspectorComboOption[] = React.useMemo( - () => semantics.dimensions.map((d) => ({ value: d.name, label: d.label ?? d.name, hint: d.type })), + () => semantics.dimensions.map((d) => ({ value: d.name, label: d.label ?? d.name })), [semantics.dimensions], ); @@ -169,6 +178,11 @@ export function DashboardWidgetInspector({ // The dashboard's own dateRange + globalFilters declarations, normalized // to the same flat def list the runtime broadcasts from — so the editor // offers exactly the filters the renderer will apply. + // The language the widget's own title is shown and edited in, and the + // served (translated) titles the Studio pairs with the published layer. + const language = useLabelLanguage(locale); + const servedWidgets = useServedWidgetText(); + const filterDefs: DashboardFilterDef[] = React.useMemo( () => resolveDashboardFilterDefs({ @@ -178,6 +192,24 @@ export function DashboardWidgetInspector({ [draft], ); + // objectstack#36373 — a filter is named by its label: the author's, else the + // built-in date filter's own name, else the label of the dimension that + // reads its field. Its machine name is the last resort, never the first. + const dimensionLabelForField = (field: string): string | undefined => + dimensionLabelOf(semantics.dimensions, field); + const filterName = (def: DashboardFilterDef): string => + resolveInlineI18nLabel(def.label, language) || + (def.name === DATE_RANGE_FILTER_NAME ? t('engine.inspector.widget.filterBindingDateRange', locale) : '') || + dimensionLabelForField(def.field) || + def.name; + // The field picker's empty face names the filter's own field by its label. + const filterDefaultPlaceholder = (def: DashboardFilterDef): string => { + const label = dimensionLabelForField(def.field); + return label + ? tFormat('engine.inspector.widget.filterBindingDefault', locale, { field: label }) + : t('engine.inspector.widget.filterBindingDefaultField', locale); + }; + if (selection.kind !== 'widget') { return (
- {resolveInlineI18nLabel(widget.title, locale) || + {shownLabel(widget.title, widgetServedTitle, language) || selection.label || tFormat('engine.inspector.widget.untitledN', locale, { n: index + 1 })}
@@ -302,7 +336,11 @@ export function DashboardWidgetInspector({ patchWidget({ // Never `{ title: e.target.value }` — that is the flattening @@ -311,7 +349,9 @@ export function DashboardWidgetInspector({ // so its map limb is `Record`, while a stored // title that parses as `I18nLabel` has string entries only and the // entry written here is `e.target.value`. - title: setLocalized(widget.title, locale, e.target.value) as DashboardWidgetSchema['title'], + title: (e.target.value === '' + ? setLocalized(widget.title, language, '') + : writtenLabel(widget.title, widgetServedTitle, language, e.target.value, '')) as DashboardWidgetSchema['title'], }) } disabled={readOnly} @@ -367,7 +407,7 @@ export function DashboardWidgetInspector({ placeholder={t('engine.inspector.widget.datasetPlaceholder', locale)} searchPlaceholder={t('engine.inspector.widget.datasetPlaceholder', locale)} disabled={readOnly} - mono + nameOnHover /> {heldHint('dataset')}

@@ -453,7 +493,7 @@ export function DashboardWidgetInspector({ `||` also fixes the truthiness gate: an object is always truthy, so a map that resolves to nothing never reached `def.name`. */} - {resolveInlineI18nLabel(def.label, locale) || def.name} + {filterName(def)} setBinding(v ? v : undefined)} options={fieldComboOptions} - placeholder={tFormat('engine.inspector.widget.filterBindingDefault', locale, { field: def.field })} + placeholder={filterDefaultPlaceholder(def)} searchPlaceholder={t('engine.form.searchFields', locale)} disabled={readOnly} - mono + nameOnHover /> {override && !readOnly && ( @@ -583,6 +623,15 @@ export function DashboardWidgetInspector({ ); } +/** + * The label of the dataset dimension a dashboard filter's field names: the one + * named `field`, else the one reading the object field `field`. + */ +function dimensionLabelOf(dimensions: DatasetDimensionInfo[], field: string): string | undefined { + const hit = dimensions.find((d) => d.name === field) ?? dimensions.find((d) => d.field === field); + return hit?.label || undefined; +} + /** * The id a `labelling="group"` field's `

@@ -285,8 +315,9 @@ export function DatasetNamesEditor({ onCommit(appendArray(names, f.name))} /> )} @@ -336,6 +368,10 @@ export function ReportDefaultInspector({ onInlineIssueFieldsChange, }: ReportDefaultInspectorProps) { const tr = React.useCallback((key: string) => t(key, locale), [locale]); + // The language the report's own text (its name, its chart title) is shown + // and edited in: the session's, the one the page beside the panel reads. + const language = useLabelLanguage(locale); + const servedText = useServedReportText(); // In create mode the host passes an empty `name` (the PK is assigned on // first save). Mirror ObjectDefaultInspector: expose an editable Name that @@ -355,7 +391,9 @@ export function ReportDefaultInspector({ // string arm painted an EMPTY Label box over a report that has a label, and // the empty box is what invites the retype that flattens the map // (objectui#9274). READ through the repo's one resolver for the union. - const labelValue = pickLocalized(draft.label, locale); + // The Name box shows the current language's text: the served translation + // while the buffer still holds the authored source (`servedLabel.ts`). + const labelValue = shownLabel(draft.label, servedText?.label, language); // objectui#12680 — whether the author has edited the name is read off the // DRAFT, not kept in this component: the name still follows the label while // it is empty or equals the identifier the label as it stands derives. A ref @@ -400,8 +438,10 @@ export function ReportDefaultInspector({ // // objectui#11161 — a select item renders text only, so a declared // description follows the label after ` — `. + // objectstack#36373 — the report panel speaks business wording: a dataset + // reads as its label alone (the machine name stays the stored value). const datasetOptions = React.useMemo( - () => datasetSelectOptions(catalog.datasets), + () => datasetLabelOptions(catalog.datasets), [catalog.datasets], ); @@ -428,8 +468,8 @@ export function ReportDefaultInspector({ ); const measureOptions: ObjectFieldInfo[] = React.useMemo( - () => datasetMeasureOptions(semantics.measures), - [semantics.measures], + () => datasetMeasureOptions(semantics.measures, locale), + [semantics.measures, locale], ); const dimensionOptions: ObjectFieldInfo[] = React.useMemo( () => datasetDimensionOptions(semantics.dimensions), @@ -448,7 +488,7 @@ export function ReportDefaultInspector({ const chartType = typeof chart.type === 'string' ? (chart.type as string) : ''; const chartX = typeof chart.xAxis === 'string' ? (chart.xAxis as string) : ''; const chartY = typeof chart.yAxis === 'string' ? (chart.yAxis as string) : ''; - const chartTitle = pickLocalized(chart.title, locale); + const chartTitle = pickLocalized(chart.title, language); const commitChart = (patch: Record) => { const next = { ...chart, ...patch }; onPatch({ chart: next.type ? next : undefined }); @@ -456,19 +496,36 @@ export function ReportDefaultInspector({ // Both axis rosters used to append an out-of-catalog axis unflagged // (objectui#8488): visible, but indistinguishable from a dimension the // dataset actually offers. The flag is `InspectorSelectField`'s job now. - // objectui#11161 — a select item renders text only, so each axis reads - // `LABEL (name)`; the stored axis is the name. + // objectstack#36373 — each axis reads as the author's label (a measure with + // its aggregate in the designer locale); the stored axis is the name. const chartXOptions = React.useMemo( - () => semantics.dimensions.map((d) => ({ value: d.name, label: labelBesideName(d.name, d.label) })), + () => semantics.dimensions.map((d) => ({ value: d.name, label: d.label || d.name })), [semantics.dimensions], ); const chartYOptions = React.useMemo( () => semantics.measures.map((m) => ({ value: m.name, - label: withAggregate(labelBesideName(m.name, m.label), m.aggregate), + label: withAggregate(m.label || m.name, aggregateText(m.aggregate, locale)), })), - [semantics.measures], + [semantics.measures, locale], + ); + // The chart-type roster: each family by its name in the designer locale and + // its glyph — the widget-type registry the dashboard pickers read. + const chartTypeOptions = React.useMemo( + () => [ + { value: '', label: t('engine.inspector.report.chartNone', locale) }, + ...REPORT_CHART_TYPES.map((tp) => { + const meta = WIDGET_TYPE_META[tp]; + const Icon = meta?.icon; + return { + value: tp, + label: meta ? t(meta.selectLabelKey, locale) : tp, + ...(Icon ? { icon: } : {}), + }; + }), + ], + [locale], ); // A `joined` report carries its data on dataset-bound `blocks` (edited via @@ -540,8 +597,11 @@ export function ReportDefaultInspector({ // report, so it is the more reachable of the two. A required key // spells "empty" as `''`, not as an absent key, so the clear arm's // `undefined` (nothing localized left) is mapped back onto it. + // objectstack#36373 — the edit lands in the session language's + // entry; a plain-string source the box showed translated becomes + // `{ default: SOURCE, LANG: EDIT }` (`servedLabel.ts`). const patch: Record = { - label: v ? setLocalized(draft.label, locale, v) : (clearLocalized(draft.label, locale) ?? ''), + label: writtenLabel(draft.label, servedText?.label, language, v, ''), }; // Live-derive the snake_case name from the label until the author // edits the Name field directly (create mode only). `v` is the plain @@ -593,6 +653,9 @@ export function ReportDefaultInspector({ mono /> )} +

+ {tr('engine.inspector.report.datasetHint')} +

({ value: tp, label: tp })), - ]} + options={chartTypeOptions} onCommit={(v) => commitChart({ type: v || undefined })} disabled={readOnly} /> @@ -655,8 +715,8 @@ export function ReportDefaultInspector({ // clearing a plain-string title has always done). commitChart({ title: v - ? setLocalized(chart.title, locale, v) - : clearLocalized(chart.title, locale), + ? setLocalized(chart.title, language, v) + : clearLocalized(chart.title, language), }) } disabled={readOnly} diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/_shared.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/_shared.tsx index ce7abd08dcd..adc6f3697be 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/_shared.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/_shared.tsx @@ -464,7 +464,11 @@ export function InspectorSelectField({ }: { label: string; value: string | undefined; - options: Array<{ value: string; label: string }>; + /** + * The roster. An option's `icon`, when given, is drawn before its label in + * the list and on the trigger (the chart-type pickers' glyphs). + */ + options: Array<{ value: string; label: string; icon?: React.ReactNode }>; onCommit: (v: string) => void; placeholder?: string; /** @@ -666,7 +670,16 @@ export function InspectorSelectField({ {shownOptions.map((o) => ( - {o.label} + + {'icon' in o && o.icon ? ( + + {o.icon} + {o.label} + + ) : ( + o.label + )} + ))} diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/dataset-picker-options.ts b/ui/packages/app-shell/src/views/metadata-admin/inspectors/dataset-picker-options.ts index 86b8249f8c4..1786735b0c1 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/dataset-picker-options.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/dataset-picker-options.ts @@ -45,6 +45,18 @@ export function datasetSelectOptions( })); } +/** + * The options of the report and dashboard-widget "data source" pickers: the + * author's label alone (the machine name when none is declared). Those panels + * speak business wording — a builder reads which data the chart counts, never + * its machine name, which stays the option's VALUE. + */ +export function datasetLabelOptions( + datasets: DatasetCatalogEntry[], +): Array<{ value: string; label: string }> { + return datasets.map((d) => ({ value: d.name, label: d.label || d.name })); +} + /** * objectstack#27518 — the catalog with `packageId`'s own datasets first, each * group in the order served. With no package, the catalog as it is. diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/servedLabel.ts b/ui/packages/app-shell/src/views/metadata-admin/inspectors/servedLabel.ts new file mode 100644 index 00000000000..b46d1daf977 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/servedLabel.ts @@ -0,0 +1,112 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The authoring box of a translatable label — a report's name, a dashboard + * widget's title — read and written in the CURRENT language. + * + * The editors edit the authored buffer, which the server does not translate: + * a plain-string label is the package's default-language literal, and its + * other languages live in the translation bundle the server applies where it + * serves the document (`translateReport`, `translateDashboard`). So a box that + * shows the buffer shows a zh-CN admin the English source, while the page + * beside it reads in Chinese. + * + * A {@link ServedLabelPair} carries the two readings of one label: as the + * published layer authors it and as the server serves it in this session's + * language. The rules: + * + * - SHOW the served text while the buffer still holds the authored value the + * server translated (the same comparison `servedDashboardText.ts` makes); + * otherwise show the buffer in the session language. + * - WRITE an edit to the session language only. When the box was showing a + * translation of a plain-string label, the label becomes the inline locale + * map `{ default: SOURCE, LANG: EDIT }`: the source text stays byte-identical + * for every other language, and the server's resolver lets the map's entry + * for the requested language beat the bundle (`translateReport`). A map + * label, or a box that showed the source itself, writes through + * `setLocalized` as before. + * + * ⛔ The served text is never written back as the source: an untouched box + * commits nothing, and an edit lands in its own language's entry. + */ + +import type { I18nLabel } from '@objectstack/spec/ui'; +import { pickLocalized, setLocalized, clearLocalized, useObjectTranslation } from '@object-ui/i18n'; +import { sameLabel } from '../../studio-design/servedNavText.js'; +import { designerLocaleOf, type SupportedLocale } from '../i18n.js'; + +/** + * The language a label box reads and writes in: the session's own tag + * (`ja-JP`, `zh-CN`), the one the served text beside the panel is in. The + * designer locale only names the chrome's catalogue (`en-US` for a ja-JP + * session), so it is the answer only where the session's tag does not map + * onto it — a host with no i18n instance, which hands a locale in directly. + */ +export function useLabelLanguage(locale: SupportedLocale | string | undefined): string { + const { language } = useObjectTranslation(); + const designer = locale ?? 'en-US'; + return language && designerLocaleOf(language) === designer ? language : designer; +} + +/** One label as the published layer authors it, and as the server serves it now. */ +export interface ServedLabelPair { + authored: I18nLabel | undefined; + served: I18nLabel | undefined; +} + +function asLabel(value: unknown): I18nLabel | undefined { + if (typeof value === 'string') return value; + if (value && typeof value === 'object' && !Array.isArray(value)) return value as I18nLabel; + return undefined; +} + +/** + * The served text the box should show for `current`, or `undefined` when the + * buffer's own text is what it shows: no pair, an edited buffer, or a served + * text that is the source itself. + */ +function servedTranslation( + current: unknown, + pair: ServedLabelPair | null | undefined, + language: string, +): string | undefined { + if (!pair || pair.served === undefined) return undefined; + if (!sameLabel(asLabel(current), pair.authored)) return undefined; + const served = pickLocalized(pair.served, language); + if (!served) return undefined; + return served === pickLocalized(current, language) ? undefined : served; +} + +/** The text a label's authoring box shows in `language`. */ +export function shownLabel( + current: unknown, + pair: ServedLabelPair | null | undefined, + language: string, +): string { + return servedTranslation(current, pair, language) ?? pickLocalized(current, language); +} + +/** + * The label an edit typed into that box stores. `next === ''` is the clear: + * it removes this language's entry where one exists, and otherwise leaves the + * label as it is (a translation borrowed from the bundle has no entry to + * clear). `emptyAs` is how the caller's key spells "nothing left" — `''` for a + * required label, `undefined` for an optional one. + */ +export function writtenLabel( + current: unknown, + pair: ServedLabelPair | null | undefined, + language: string, + next: string, + emptyAs: '' | undefined, +): I18nLabel | undefined { + const translated = servedTranslation(current, pair, language) !== undefined; + if (next === '') { + if (translated) return asLabel(current); + return clearLocalized(current, language) ?? emptyAs; + } + if (translated && typeof current === 'string') { + return setLocalized({ default: current }, language, next) as I18nLabel; + } + return setLocalized(current, language, next) as I18nLabel; +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/ViewColumnPanes.tsx b/ui/packages/app-shell/src/views/metadata-admin/previews/ViewColumnPanes.tsx index fe31c53d3e0..ff6eeaac1c8 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/ViewColumnPanes.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/ViewColumnPanes.tsx @@ -308,12 +308,18 @@ export function AddFieldPopover({ loading, error, onAdd, + nameOnHover = false, }: { fields: ObjectFieldInfo[]; usedNames: Set; loading: boolean; error: string | null; onAdd: (field: ObjectFieldInfo) => void; + /** + * Keep each option's machine name off the list, reachable on hover only (the + * option's title) — for the panels that speak business wording. + */ + nameOnHover?: boolean; }) { const locale = useMetadataLocale(); const [open, setOpen] = React.useState(false); @@ -374,8 +380,13 @@ export function AddFieldPopover({ className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs hover:bg-accent" > - {f.label} - {f.name !== f.label && ( + + {f.label} + + {f.name !== f.label && !nameOnHover && ( {f.name} diff --git a/ui/packages/app-shell/src/views/metadata-admin/previews/useDatasetCatalog.ts b/ui/packages/app-shell/src/views/metadata-admin/previews/useDatasetCatalog.ts index 7fe099fe6fb..4d60c8b18b9 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/previews/useDatasetCatalog.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/previews/useDatasetCatalog.ts @@ -58,6 +58,12 @@ export interface DatasetDimensionInfo { label?: string; /** Raw field type id when declared (e.g. 'text', 'date'). */ type?: string; + /** + * The object field the dimension reads (`owner_id` for `owner`), when + * declared — how a dashboard filter's default field finds the dimension + * label a panel names it by. + */ + field?: string; } export interface DatasetMeasureInfo { @@ -154,6 +160,7 @@ export function toCatalogEntry(doc: Record, locale: string): Da name: d.name as string, label: authoredText(d.label, locale), type: typeof d.type === 'string' ? (d.type as string) : undefined, + ...(typeof d.field === 'string' && d.field ? { field: d.field } : {}), })) : []; const measures: DatasetMeasureInfo[] = Array.isArray(doc.measures) diff --git a/ui/packages/app-shell/src/views/studio-design/servedReportText.ts b/ui/packages/app-shell/src/views/studio-design/servedReportText.ts new file mode 100644 index 00000000000..6f5150ab354 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/servedReportText.ts @@ -0,0 +1,54 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The served (current-language) text of a report's name and description, + * paired with the published layer it was translated from — the report's half + * of `servedDashboardText.ts`, read by the report inspector's Name box + * (`servedLabel.ts`). + * + * The runtime report page and the Studio both edit a report through its + * authored buffer, which the server does not translate; the `/meta` report + * list the console's metadata store holds is translated for this session's + * language (`translateReport`). A host that holds both provides them through + * {@link ServedReportTextContext}; outside a provider the inspector reads the + * buffer alone, as it always has. Internal to app-shell. + */ + +import * as React from 'react'; +import type { ServedLabelPair } from '../metadata-admin/inspectors/servedLabel.js'; +import { isLabel } from './servedNavText.js'; + +/** The served text of one report's translatable slots. */ +export interface ServedReportText { + label?: ServedLabelPair; + description?: ServedLabelPair; +} + +/** + * Pair the served report (`served`, a row of the `/meta` report list) with the + * published layer it was translated from (`published`). `null` when either is + * missing or the two are not the same report. + */ +export function servedReportTextOf( + published: Record | null | undefined, + served: Record | null | undefined, +): ServedReportText | null { + if (!published || !served) return null; + if (typeof published.name !== 'string' || published.name !== served.name) return null; + const out: ServedReportText = {}; + for (const slot of ['label', 'description'] as const) { + const s = served[slot]; + const a = published[slot]; + if (!isLabel(s)) continue; + out[slot] = { authored: isLabel(a) ? a : undefined, served: s }; + } + return out; +} + +/** `null` (the default) is "no served text": the inspector reads the buffer alone. */ +export const ServedReportTextContext = React.createContext(null); + +/** The served report text the nearest host provides, or `null`. */ +export function useServedReportText(): ServedReportText | null { + return React.useContext(ServedReportTextContext); +} diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 5b8f83b24d9..0014f881eac 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -627,24 +627,23 @@ const STUDIO_EN: Record = { 'engine.inspector.widget.height': 'Height', 'engine.inspector.widget.remove': 'Remove widget', // Dataset binding (ADR-0021) — governed cross-object semantic layer. - 'engine.inspector.widget.datasetSection': 'Dataset binding', - 'engine.inspector.widget.dataset': 'Dataset', - 'engine.inspector.widget.datasetPlaceholder': 'e.g. sales_pipeline', - 'engine.inspector.widget.datasetHint': - 'Pick the governed dataset this widget draws from, then choose its dimensions and measures below. Dataset numbers stay consistent across objects, and row-level security applies.', - 'engine.inspector.widget.dimensions': 'Dimensions', + 'engine.inspector.widget.datasetSection': 'Data source', + 'engine.inspector.widget.dataset': 'Data source', + 'engine.inspector.widget.datasetPlaceholder': 'Choose a data source…', + 'engine.inspector.widget.datasetHint': 'The widget reads its numbers from here; everyone sees only the records they have access to.', + 'engine.inspector.widget.dimensions': 'Group by', 'engine.inspector.widget.dimensionsPlaceholder': 'e.g. stage, region (comma-separated)', - 'engine.inspector.widget.dimensionsHint': - 'Dataset dimension names to group by. Leave empty for a single-value KPI metric.', - 'engine.inspector.widget.values': 'Values (measures)', + 'engine.inspector.widget.dimensionsHint': 'The field to group by. Leave it empty to show a single number.', + 'engine.inspector.widget.values': 'Metrics', 'engine.inspector.widget.valuesPlaceholder': 'e.g. revenue, deal_count (comma-separated)', - 'engine.inspector.widget.valuesHint': 'Dataset measure names to show.', + 'engine.inspector.widget.valuesHint': 'What to total or count, such as the sum of amounts or the number of records.', // Dashboard filter bindings (framework#2501) - 'engine.inspector.widget.filterBindingsSection': 'Dashboard filter bindings', - 'engine.inspector.widget.filterBindingsHint': - 'Map each dashboard-level filter to one of this widget’s own fields, or untick Apply to opt the widget out. Empty = the filter’s own field.', + 'engine.inspector.widget.filterBindingsSection': 'Follows the filters at the top of the page', + 'engine.inspector.widget.filterBindingsHint': 'A ticked filter applies to this widget; you can also point it at another field of this widget.', 'engine.inspector.widget.filterBindingApply': 'Apply', 'engine.inspector.widget.filterBindingDefault': 'Default ({field})', + 'engine.inspector.widget.filterBindingDefaultField': 'Default field', + 'engine.inspector.widget.filterBindingDateRange': 'Date', 'engine.inspector.widget.filterBindingField': 'Bound field for {filter}', 'engine.inspector.widget.filterBindingReset': 'Reset', // objectui#10748 — the widget-type select's options (keyed by the stored @@ -1536,20 +1535,27 @@ const STUDIO_EN: Record = { 'engine.inspector.report.type.summary': 'Summary', 'engine.inspector.report.type.matrix': 'Matrix', 'engine.inspector.report.type.joined': 'Joined', - 'engine.inspector.report.dataset': 'Dataset', - 'engine.inspector.report.datasetPlaceholder': 'e.g. sales_metrics', - 'engine.inspector.report.values': 'Values (measures)', - 'engine.inspector.report.valuesEmpty': 'No measures yet. Add one from the dataset below.', - 'engine.inspector.report.rows': 'Rows (dimensions)', - 'engine.inspector.report.rowsEmpty': 'No dimensions yet. Add one from the dataset below.', - 'engine.inspector.report.columnsAcross': 'Columns (across dimensions)', - 'engine.inspector.report.columnsAcrossEmpty': 'No across dimensions yet — the matrix pivots rows × columns.', + 'engine.inspector.report.dataset': 'Data source', + 'engine.inspector.report.datasetPlaceholder': 'Choose a data source…', + 'engine.inspector.report.datasetHint': 'The report reads its numbers from here; everyone sees only the records they have access to.', + 'engine.inspector.report.aggregate.sum': 'Sum', + 'engine.inspector.report.aggregate.avg': 'Average', + 'engine.inspector.report.aggregate.count': 'Count', + 'engine.inspector.report.aggregate.count_distinct': 'Distinct count', + 'engine.inspector.report.aggregate.min': 'Minimum', + 'engine.inspector.report.aggregate.max': 'Maximum', + 'engine.inspector.report.values': 'Metrics', + 'engine.inspector.report.valuesEmpty': 'No metrics yet. Add one below.', + 'engine.inspector.report.rows': 'Group by', + 'engine.inspector.report.rowsEmpty': 'No grouping yet. Add one below.', + 'engine.inspector.report.columnsAcross': 'Group columns by', + 'engine.inspector.report.columnsAcrossEmpty': 'No column grouping yet — the matrix crosses its groups with these.', 'engine.inspector.report.chart': 'Chart', 'engine.inspector.report.chartType': 'Chart type', - 'engine.inspector.report.chartNone': 'None (table only)', + 'engine.inspector.report.chartNone': 'No chart (table only)', 'engine.inspector.report.chartTitle': 'Chart title', - 'engine.inspector.report.chartX': 'X-Axis (dimension)', - 'engine.inspector.report.chartY': 'Y-Axis (measure)', + 'engine.inspector.report.chartX': 'Horizontal axis (group)', + 'engine.inspector.report.chartY': 'Vertical axis (metric)', 'engine.inspector.report.noSchema': 'Spec schema unavailable — basic properties only.', // Trailing section for fields the live server has but the bundled spec lacks. 'engine.inspector.moreFields': 'More fields', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index 47e899a49c6..193cff6b7d0 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -541,23 +541,23 @@ const STUDIO_ZH: Record = { 'engine.inspector.widget.height': '高度', 'engine.inspector.widget.remove': '删除组件', // Dataset binding (ADR-0021) — governed cross-object semantic layer. - 'engine.inspector.widget.datasetSection': '数据集绑定', - 'engine.inspector.widget.dataset': '数据集', - 'engine.inspector.widget.datasetPlaceholder': '例如:sales_pipeline', - 'engine.inspector.widget.datasetHint': - '选择本组件取数的受治理数据集,再在下方选择它的维度和度量。数据集口径一致、可跨对象,并强制行级安全(RLS)。', - 'engine.inspector.widget.dimensions': '维度', + 'engine.inspector.widget.datasetSection': '数据来源', + 'engine.inspector.widget.dataset': '数据来源', + 'engine.inspector.widget.datasetPlaceholder': '选择数据来源…', + 'engine.inspector.widget.datasetHint': '卡片从这里取数;每个人只能看到自己有权限的记录。', + 'engine.inspector.widget.dimensions': '分组', 'engine.inspector.widget.dimensionsPlaceholder': '例如:stage, region(逗号分隔)', - 'engine.inspector.widget.dimensionsHint': '用于分组的数据集维度名。留空则渲染为单值 KPI。', - 'engine.inspector.widget.values': '值(度量)', + 'engine.inspector.widget.dimensionsHint': '按哪个字段分组。不选则只显示一个数字。', + 'engine.inspector.widget.values': '指标', 'engine.inspector.widget.valuesPlaceholder': '例如:revenue, deal_count(逗号分隔)', - 'engine.inspector.widget.valuesHint': '要展示的数据集度量名。', + 'engine.inspector.widget.valuesHint': '要统计的指标,例如金额合计、记录数。', // Dashboard filter bindings (framework#2501) - 'engine.inspector.widget.filterBindingsSection': '仪表盘过滤器绑定', - 'engine.inspector.widget.filterBindingsHint': - '把每个仪表盘级过滤器映射到本组件自己的字段;取消勾选「应用」可让本组件不受该过滤器影响。留空表示使用过滤器自身的字段。', + 'engine.inspector.widget.filterBindingsSection': '跟着页面顶部的筛选变', + 'engine.inspector.widget.filterBindingsHint': '勾选「应用」的筛选会作用到这张卡片;也可以改成按卡片里的另一个字段来筛。', 'engine.inspector.widget.filterBindingApply': '应用', 'engine.inspector.widget.filterBindingDefault': '默认({field})', + 'engine.inspector.widget.filterBindingDefaultField': '默认字段', + 'engine.inspector.widget.filterBindingDateRange': '时间', 'engine.inspector.widget.filterBindingField': '{filter} 绑定的字段', 'engine.inspector.widget.filterBindingReset': '恢复默认', 'engine.inspector.widget.type.metric': 'KPI 指标', @@ -1366,20 +1366,27 @@ const STUDIO_ZH: Record = { 'engine.inspector.report.type.summary': '汇总', 'engine.inspector.report.type.matrix': '矩阵', 'engine.inspector.report.type.joined': '联合', - 'engine.inspector.report.dataset': '数据集', - 'engine.inspector.report.datasetPlaceholder': '例如:sales_metrics', - 'engine.inspector.report.values': '值(度量)', - 'engine.inspector.report.valuesEmpty': '还没有度量。从下方数据集中添加。', - 'engine.inspector.report.rows': '行(维度)', - 'engine.inspector.report.rowsEmpty': '还没有维度。从下方数据集中添加。', - 'engine.inspector.report.columnsAcross': '列(横向维度)', - 'engine.inspector.report.columnsAcrossEmpty': '还没有横向维度——矩阵按 行 × 列 透视。', + 'engine.inspector.report.dataset': '数据来源', + 'engine.inspector.report.datasetPlaceholder': '选择数据来源…', + 'engine.inspector.report.datasetHint': '报表从这里取数;每个人只能看到自己有权限的记录。', + 'engine.inspector.report.aggregate.sum': '合计', + 'engine.inspector.report.aggregate.avg': '平均', + 'engine.inspector.report.aggregate.count': '计数', + 'engine.inspector.report.aggregate.count_distinct': '去重计数', + 'engine.inspector.report.aggregate.min': '最小', + 'engine.inspector.report.aggregate.max': '最大', + 'engine.inspector.report.values': '指标', + 'engine.inspector.report.valuesEmpty': '还没有指标,从下方添加一个。', + 'engine.inspector.report.rows': '分组', + 'engine.inspector.report.rowsEmpty': '还没有分组,从下方添加一个。', + 'engine.inspector.report.columnsAcross': '列分组', + 'engine.inspector.report.columnsAcrossEmpty': '还没有列分组——矩阵按 分组 × 列分组 交叉统计。', 'engine.inspector.report.chart': '图表', 'engine.inspector.report.chartType': '图表类型', - 'engine.inspector.report.chartNone': '无(仅表格)', + 'engine.inspector.report.chartNone': '不显示图表(只看表格)', 'engine.inspector.report.chartTitle': '图表标题', - 'engine.inspector.report.chartX': 'X 轴(维度)', - 'engine.inspector.report.chartY': 'Y 轴(度量)', + 'engine.inspector.report.chartX': '横轴(分组)', + 'engine.inspector.report.chartY': '纵轴(指标)', 'engine.inspector.report.noSchema': '规格 schema 不可用 —— 仅显示基础属性。', // Trailing section for fields the live server has but the bundled spec lacks. 'engine.inspector.moreFields': '更多字段', From 67132dd77055c698998cccc87fb9a665ef64034a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 09:04:57 +0000 Subject: [PATCH 02/15] wip(#36373): current-language titles, served text in the panels, inline-entry precedence --- packages/spec/src/system/i18n-report.test.ts | 90 +++++++++++++++++++ packages/spec/src/system/i18n-resolver.ts | 80 ++++++++++++++--- .../app-shell/src/views/ReportView.tsx | 56 +++++++++++- .../metadata-admin/inspectors/servedLabel.ts | 2 +- .../studio-design/StudioDesignSurface.tsx | 28 +++++- 5 files changed, 241 insertions(+), 15 deletions(-) diff --git a/packages/spec/src/system/i18n-report.test.ts b/packages/spec/src/system/i18n-report.test.ts index fa539514410..b6e08181b53 100644 --- a/packages/spec/src/system/i18n-report.test.ts +++ b/packages/spec/src/system/i18n-report.test.ts @@ -19,6 +19,8 @@ import { import { translateMetadataDocument, translateReport, + translateDashboard, + translateDataset, TRANSLATABLE_METADATA_TYPES, } from './i18n-resolver'; // The fixture is PARSED by the authoring schema rather than hand-shaped, so a @@ -178,3 +180,91 @@ describe('translateReport', () => { }); }); }); + +/** + * objectstack#36373 — the console's report and dashboard panels edit a name or + * a widget title in the CURRENT language: an edit made while the box showed a + * bundle translation of a plain-string source stores the inline locale map + * `{ default: SOURCE, LANG: EDIT }`. These pins hold the precedence that makes + * that edit visible without moving any other locale. + */ +describe('an inline locale map entry for the requested locale beats the catalog (objectstack#36373)', () => { + const multi: TranslationBundle = { + 'zh-CN': { reports: { opps_by_stage: { label: '各阶段商机', description: '按阶段汇总的商机' } } }, + 'ja-JP': { reports: { opps_by_stage: { label: 'ステージ別商談' } } }, + }; + const packagedBase = () => report(); + // The shape the panel writes for a zh-CN edit of the plain-string source. + const editedInZh = () => ({ + ...report(), + label: { default: 'Opportunities by Stage', 'zh-CN': '各阶段商机(本公司)' }, + }); + + it('serves the zh-CN entry to a zh-CN reader, not the bundle translation', () => { + const out = translateReport(editedInZh(), multi, { locale: 'zh-CN', packagedBase: packagedBase() }) as any; + expect(out.label).toEqual({ default: 'Opportunities by Stage', 'zh-CN': '各阶段商机(本公司)' }); + // The description, untouched by the edit, still reads its translation. + expect(out.description).toBe('按阶段汇总的商机'); + }); + + it('keeps the English source byte-identical for a reader in the source language', () => { + const out = translateReport(editedInZh(), multi, { locale: 'en', packagedBase: packagedBase() }) as any; + expect(out.label.default).toBe(packagedBase().label); + }); + + it('a third locale still reads its own bundle translation, never the zh-CN entry or `default`', () => { + const out = translateReport(editedInZh(), multi, { locale: 'ja-JP', packagedBase: packagedBase() }) as any; + expect(out.label).toBe('ステージ別商談'); + }); + + it('a base-language entry answers a regional request (`zh` for `zh-CN`)', () => { + const edited = { ...report(), label: { default: 'Opportunities by Stage', zh: '各阶段(本公司)' } }; + const out = translateReport(edited, multi, { locale: 'zh-CN', packagedBase: packagedBase() }) as any; + expect(out.label).toEqual(edited.label); + }); + + it('control: a map equal to the package\'s own map changes nothing — the bundle still answers', () => { + const shipped = { default: 'Opportunities by Stage', 'zh-CN': '旧的内联译文' }; + const base = { ...report(), label: shipped }; + const served = { ...report(), label: { ...shipped } }; + const out = translateReport(served, multi, { locale: 'zh-CN', packagedBase: base }) as any; + expect(out.label).toBe('各阶段商机'); + }); + + it('control: with no packaged base the catalog answers, as the string rule does', () => { + const out = translateReport(editedInZh(), multi, { locale: 'zh-CN' }) as any; + expect(out.label).toBe('各阶段商机'); + }); + + it('a dashboard widget title follows the same rule', () => { + const bundle: TranslationBundle = { + 'zh-CN': { dashboards: { exec: { widgets: { rev: { title: '按行业收入' } } } } }, + 'ja-JP': { dashboards: { exec: { widgets: { rev: { title: '業種別売上' } } } } }, + }; + const base = { name: 'exec', label: 'Executive', widgets: [{ id: 'rev', title: 'Revenue by Industry' }] }; + const edited = { + ...base, + widgets: [{ id: 'rev', title: { default: 'Revenue by Industry', 'zh-CN': '各行业收入(本公司)' } }], + }; + const zh = translateDashboard(edited as any, bundle, { locale: 'zh-CN', packagedBase: base }) as any; + expect(zh.widgets[0].title).toEqual(edited.widgets[0].title); + const ja = translateDashboard(edited as any, bundle, { locale: 'ja-JP', packagedBase: base }) as any; + expect(ja.widgets[0].title).toBe('業種別売上'); + // Unedited: the bundle answers, as before. + const plain = translateDashboard(base as any, bundle, { locale: 'zh-CN', packagedBase: base }) as any; + expect(plain.widgets[0].title).toBe('按行业收入'); + }); + + it('scope control: a dataset member\'s inline map still loses to the bundle (ADR-0149)', () => { + const bundle: TranslationBundle = { + 'zh-CN': { datasets: { pipeline: { dimensions: { stage: { label: '阶段' } } } } }, + }; + const base = { name: 'pipeline', object: 'opp', dimensions: [{ name: 'stage', label: 'Stage' }], measures: [] }; + const edited = { + ...base, + dimensions: [{ name: 'stage', label: { default: 'Stage', 'zh-CN': '销售阶段(本公司)' } }], + }; + const out = translateDataset(edited as any, bundle, { locale: 'zh-CN', packagedBase: base }) as any; + expect(out.dimensions[0].label).toBe('阶段'); + }); +}); diff --git a/packages/spec/src/system/i18n-resolver.ts b/packages/spec/src/system/i18n-resolver.ts index f1a66a17c2d..dd69f2333a2 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -2578,10 +2578,14 @@ export function translateDashboard( if (!w || typeof w !== 'object' || typeof w.id !== 'string') return w; const next: WidgetLike = { ...w }; const packagedWidget = packagedPart(base, 'widgets', (candidate) => candidate.id === w.id); - const title = lookupWidgetAttr( - catalogFor(catalogs, valueOverridesPackagedBase(packagedWidget, 'title', w.title)), - name, w.id, 'title', opts, - ); + // A widget title's inline entry for the requested locale, where it is + // the customer's text, beats the catalog (`translateReport`'s rule). + const title = inlineEntryOverridesPackagedBase(packagedWidget, 'title', w.title, opts?.locale) + ? undefined + : lookupWidgetAttr( + catalogFor(catalogs, valueOverridesPackagedBase(packagedWidget, 'title', w.title)), + name, w.id, 'title', opts, + ); if (title) next.title = title; const desc = lookupWidgetAttr( catalogFor(catalogs, valueOverridesPackagedBase(packagedWidget, 'description', w.description)), @@ -3178,12 +3182,19 @@ export function translateReport( if (typeof name !== 'string' || name.length === 0 || !catalogs.unchanged) return doc; const base = asRecord(opts?.packagedBase); - const label = lookupReportAttr( - catalogFor(catalogs, valueOverridesPackagedBase(base, 'label', doc.label)), name, 'label', opts, - ); - const description = lookupReportAttr( - catalogFor(catalogs, valueOverridesPackagedBase(base, 'description', doc.description)), name, 'description', opts, - ); + // An inline map's own entry for the requested locale, where it is the + // customer's text, beats the catalog: the slot is served as authored and the + // reader picks that entry ({@link inlineEntryOverridesPackagedBase}). + const label = inlineEntryOverridesPackagedBase(base, 'label', doc.label, opts?.locale) + ? undefined + : lookupReportAttr( + catalogFor(catalogs, valueOverridesPackagedBase(base, 'label', doc.label)), name, 'label', opts, + ); + const description = inlineEntryOverridesPackagedBase(base, 'description', doc.description, opts?.locale) + ? undefined + : lookupReportAttr( + catalogFor(catalogs, valueOverridesPackagedBase(base, 'description', doc.description)), name, 'description', opts, + ); const blocks = translateReportBlocks(doc.blocks, catalogs, name, base, opts); if (label === undefined && description === undefined && blocks === undefined) return doc; return { @@ -4948,6 +4959,55 @@ function valueOverridesPackagedBase(base: unknown, key: string, value: unknown): return (base as Record)[key] !== value; } +/** + * An inline locale map's entry for the REQUESTED locale — the exact tag, then + * the base language's tag (`zh` for `zh-CN`). ⛔ Never `default` and never a + * sibling region: those are display fallbacks for a locale the map has no + * entry for, and are no statement about the requested locale. + */ +function inlineEntryFor(value: unknown, locale: string | undefined): string | undefined { + if (!value || typeof value !== 'object' || Array.isArray(value) || !locale) return undefined; + const map = value as Record; + const read = (key: string): string | undefined => { + if (!Object.prototype.hasOwnProperty.call(map, key)) return undefined; + const entry = map[key]; + return typeof entry === 'string' && entry.length > 0 ? entry : undefined; + }; + const baseTag = locale.split('-')[0]; + return read(locale) ?? (baseTag !== locale ? read(baseTag) : undefined); +} + +/** + * Whether an inline locale map's entry for the requested locale is a + * customer's own text that beats the catalog's translation for that locale — + * the map-valued twin of {@link valueOverridesPackagedBase}, which answers the + * same question for a plain string (`false` for any map) and exists so that a + * customer's value beats the package's translation. + * + * `true` only when the map carries an entry for the requested locale + * ({@link inlineEntryFor}) AND that entry differs from the packaged base's own + * entry for the locale: a map equal to the package's own map changes nothing, + * so a package that ships inline maps keeps reading its bundle exactly as + * before. No packaged base supplied: `false`, as the string rule answers. A + * locale the map has no entry for keeps reading the catalog, so a third + * language still reads its bundle translation, never another locale's entry. + * + * Read by {@link translateReport} (name, description) and + * {@link translateDashboard} (a widget's title), the label slots the + * console's report and dashboard panels edit in the current language. + */ +function inlineEntryOverridesPackagedBase( + base: unknown, + key: string, + value: unknown, + locale: string | undefined, +): boolean { + if (!base || typeof base !== 'object') return false; + const entry = inlineEntryFor(value, locale); + if (entry === undefined) return false; + return inlineEntryFor((base as Record)[key], locale) !== entry; +} + /** * Whether a field authors help text on `inlineHelpText` — a non-empty string, * as the i18n extractor and the console's `inlineHelpText || description` diff --git a/ui/packages/app-shell/src/views/ReportView.tsx b/ui/packages/app-shell/src/views/ReportView.tsx index cea581b7a76..660ff87f3f5 100644 --- a/ui/packages/app-shell/src/views/ReportView.tsx +++ b/ui/packages/app-shell/src/views/ReportView.tsx @@ -28,6 +28,40 @@ import { DrillDownDrawer } from '@object-ui/plugin-dashboard'; import { DrillNavigationProvider } from '@object-ui/react'; import { useRecordListDrillNavigation } from './useOpenRecordList.js'; import { metadataText } from '../hooks/useNavTargetLabel.js'; +import { + ServedReportTextContext, + servedReportTextOf, + type ServedReportText, +} from './studio-design/servedReportText.js'; + +/** + * The report keys whose text the server translates where it serves the report + * (`translateReport`: the name, the description, a joined report's block + * labels) plus the `title` the page header reads first. + */ +const SERVED_TEXT_KEYS = ['title', 'label', 'description', 'blocks'] as const; + +/** + * objectstack#36373 — the report the page DRAWS while the editor is open: the + * edited buffer, except that each translated key the edit has not touched is + * the served copy's. The buffer is the untranslated authored document + * (objectstack#35008), so drawing it whole flipped the page heading and the + * subtitle to the source language the moment the editor opened; a key the + * author did change is drawn as edited. + */ +export function previewWithServedText( + served: Record | null | undefined, + authoredAtOpen: Record | null | undefined, + edited: Record, +): Record { + if (!served || !authoredAtOpen) return edited; + const out: Record = { ...edited }; + for (const key of SERVED_TEXT_KEYS) { + if (JSON.stringify(edited[key]) !== JSON.stringify(authoredAtOpen[key])) continue; + if (key in served) out[key] = served[key]; + } + return out; +} // Fallback fields when no schema is available const FALLBACK_FIELDS = [ @@ -251,11 +285,19 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { // no display copy for this locale. const savedSinceOpenRef = useRef(false); const [openingEditor, setOpeningEditor] = useState(false); + // The authored buffer as the editor opened on it, and the served text of + // the report's name and description paired with the published layer — the + // page draws the served text for every key the edit leaves alone + // (`previewWithServedText`), and the editor's Name box reads it + // (`ServedReportTextContext`). + const [authoredAtOpen, setAuthoredAtOpen] = useState | null>(null); + const [servedText, setServedText] = useState(null); const handleOpenConfigPanel = useCallback(async () => { if (!metadataClient || !reportName) return; const packageId = servedPackageId(reportData); setOpeningEditor(true); let body: Record | null = null; + let published: Record | null = null; let failure: string | null = null; try { const at = packageId ? { packageId } : {}; @@ -264,6 +306,8 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { metadataClient.getDraft('report', reportName, at), ]); const authored = authoredBuffer('report', layers as AuthoredLayers, extractDraftBody(servedDraft)); + const lay = layers as { effective?: unknown; code?: unknown } | null; + published = ((lay?.effective ?? lay?.code ?? null) as Record | null) ?? null; if (authored.kind === 'unserved') failure = tStudio('engine.studio.refusal.draftUnreadable', metadataLocale); else if (Object.keys(authored.body).length > 0) body = authored.body; else failure = tStudio('engine.form.notFound', metadataLocale); @@ -283,6 +327,8 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { return; } savedSinceOpenRef.current = false; + setAuthoredAtOpen(body); + setServedText(servedReportTextOf(published, reportData)); setEditSchema(body); setConfigPanelOpen(true); setConfigVersion((v) => v + 1); @@ -468,8 +514,12 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { ); } - // Use live-edited schema for preview (persists after closing panel until metadata refreshes) - const previewReport = editSchema || reportData; + // Use live-edited schema for preview (persists after closing panel until + // metadata refreshes), with the served text of every translated key the + // edit has not touched (objectstack#36373). + const previewReport = editSchema + ? previewWithServedText(reportData, authoredAtOpen, editSchema) + : reportData; // `label` and `description` are the spec's `string | I18nLabel`, so an // inline locale map (`{ en, 'zh-CN' }`) is valid metadata and is served // unchanged. Drawn raw, React refused the object and the page went blank @@ -531,6 +581,7 @@ export function ReportView({ dataSource }: { dataSource?: DataSource }) { {/* Right-side config panel — studio's spec-driven report inspector, hosted locally in app-shell (see ReportConfigPanel). */} + refresh().catch(() => {})} /> + | null; @@ -3305,11 +3306,21 @@ export function InterfacesPillar({ currentType === 'dashboard' && currentName ? ((findByName(metadata.dashboards, currentName) as Record | undefined) ?? null) : null; + // objectstack#36373 — the report leaf's half: its served name and + // description, paired with the same published layer, for the report + // inspector's Name box (`servedReportText.ts`). + const servedReport = + currentType === 'report' && currentName + ? ((findByName(metadata.reports, currentName) as Record | undefined) ?? null) + : null; // A dashboard leaf with a pending draft reads its published layer once, to // pair the served titles with: only when the server serves that dashboard, // so a never-published draft asks no `/layers` (objectui#11799). const publishedPending = - currentType === 'dashboard' && leafPublished.key === leafKey && !leafPublished.read && !!servedDashboard; + (currentType === 'dashboard' || currentType === 'report') && + leafPublished.key === leafKey && + !leafPublished.read && + !!(servedDashboard ?? servedReport); React.useEffect(() => { if (!publishedPending || !currentType || !currentName) return; const key = leafKey; @@ -3339,6 +3350,13 @@ export function InterfacesPillar({ : null, [currentType, leafPublished, leafKey, servedDashboard], ); + const servedReportText = React.useMemo( + () => + currentType === 'report' && leafPublished.key === leafKey && leafPublished.read + ? servedReportTextOf(leafPublished.doc, servedReport) + : null, + [currentType, leafPublished, leafKey, servedReport], + ); // objectui#5813 — a local dirty flag so auto-save only arms after a real // edit, never on the load-effect's own setDraft. @@ -4893,6 +4911,9 @@ export function InterfacesPillar({
) : selection && Inspector && current ? (
+ {/* objectstack#36373 — a selected dashboard widget's Title box reads + the served (current-language) title; `null` for any other leaf. */} + +
) : isSourcePage ? ( // objectui#12725 — no 源码 tab: the properties say what the page IS @@ -4934,6 +4956,7 @@ export function InterfacesPillar({ {/* objectui#12688 — a dashboard's component list draws the served widget titles (display only); `null` for any other leaf. */} + +
) : designersUnregistered ? ( From 04c7459b4ff52f55b5cff0b0d24ab6e059d9dcd1 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 09:18:59 +0000 Subject: [PATCH 03/15] test(app-shell): move the panel tests to the business wording (#36373) Claude-Session: https://claude.ai/code/session_01QsR2jUP9hxdL4RzdzTs9eK Co-authored-by: Claude --- .../DashboardWidgetInspector.test.tsx | 32 ++--- .../ReportDefaultInspector.test.tsx | 35 +++--- .../datasetPickers.authorText-11161.test.tsx | 112 +++++++++--------- ...r.componentListServedTitles-12688.test.tsx | 15 ++- ...InterfacesPillar.heldWidget-11910.test.tsx | 18 +-- ...InterfacesPillar.reportHeld-27785.test.tsx | 8 +- ...gnSurface.heldWidgetPublish-11910.test.tsx | 2 +- ui/packages/i18n/src/namespaces/studio/en.ts | 2 +- ui/packages/i18n/src/namespaces/studio/zh.ts | 2 +- 9 files changed, 124 insertions(+), 102 deletions(-) diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardWidgetInspector.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardWidgetInspector.test.tsx index a1bf7b0f79f..a73cf06b2b3 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardWidgetInspector.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardWidgetInspector.test.tsx @@ -65,10 +65,10 @@ function renderWidget(extra: Record = {}, props: Record { it('shows the Dataset picker; dimensions/values appear only once a dataset is bound', () => { const { rerender } = renderWidget(); - expect(screen.getByText('Dataset')).toBeInTheDocument(); + expect(screen.getByText('Data source')).toBeInTheDocument(); // Dimensions/Values sections are gated behind a bound dataset. - expect(screen.queryByText('Dimensions')).not.toBeInTheDocument(); - expect(screen.queryByText('Values (measures)')).not.toBeInTheDocument(); + expect(screen.queryByText('Group by')).not.toBeInTheDocument(); + expect(screen.queryByText('Metrics')).not.toBeInTheDocument(); rerender( { />, ); // Sections now present, and the bound members render in the lists. - expect(screen.getByText('Dimensions')).toBeInTheDocument(); - expect(screen.getByText('Values (measures)')).toBeInTheDocument(); + expect(screen.getByText('Group by')).toBeInTheDocument(); + expect(screen.getByText('Metrics')).toBeInTheDocument(); expect(screen.getByText('stage')).toBeInTheDocument(); - expect(screen.getByText('revenue')).toBeInTheDocument(); + expect(screen.getByText('revenue · Sum')).toBeInTheDocument(); }); it('no longer renders the removed inline object query fields', () => { @@ -96,8 +96,8 @@ describe('DashboardWidgetInspector — dataset binding', () => { it('renders Chinese labels under zh-CN', () => { renderWidget({ dataset: 'sales_pipeline' }, { locale: 'zh-CN' }); - expect(screen.getByText('数据集绑定')).toBeInTheDocument(); - expect(screen.getByText('维度')).toBeInTheDocument(); + expect(screen.getByText('数据来源')).toBeInTheDocument(); + expect(screen.getByText('分组')).toBeInTheDocument(); }); it('the Dataset label resolves to the combo trigger, not to nothing (#3997)', () => { @@ -110,15 +110,15 @@ describe('DashboardWidgetInspector — dataset binding', () => { // the atom's own pins live in `_shared.labels.test.tsx`. renderWidget({ dataset: 'sales_pipeline' }); - const label = screen.getByText('Dataset'); + const label = screen.getByText('Data source'); const forId = label.getAttribute('for'); expect(forId).toBeTruthy(); - const trigger = screen.getByLabelText('Dataset'); + const trigger = screen.getByLabelText('Data source'); expect(trigger).toBe(document.getElementById(forId!)); expect(trigger.tagName).toBe('BUTTON'); expect(trigger).toHaveAttribute('role', 'combobox'); - expect(trigger).toHaveAccessibleName('Dataset'); + expect(trigger).toHaveAccessibleName('Data source'); // Exactly one element answers that id — the trigger, not a wrapper. expect(document.querySelectorAll(`[id="${forId}"]`)).toHaveLength(1); @@ -230,17 +230,19 @@ describe('DashboardWidgetInspector — dashboard filter bindings (framework#2501 it('hides the section when the dashboard declares no filters', () => { renderWidget(); - expect(screen.queryByText('Dashboard filter bindings')).not.toBeInTheDocument(); + expect(screen.queryByText('Follows the filters at the top of the page')).not.toBeInTheDocument(); }); it('renders one row per dashboard filter (dateRange + each globalFilter)', () => { renderFiltered(); - expect(screen.getByText('Dashboard filter bindings')).toBeInTheDocument(); + expect(screen.getByText('Follows the filters at the top of the page')).toBeInTheDocument(); expect(screen.getByTestId('widget-filter-binding-dateRange')).toBeInTheDocument(); const region = screen.getByTestId('widget-filter-binding-region'); expect(within(region).getByText('Region')).toBeInTheDocument(); - // Default placeholder names the filter's own field. - expect(within(region).getByText('Default (region)')).toBeInTheDocument(); + // The bound dataset declares no `region` dimension, so the empty face + // reads "Default field" — never the machine name (objectstack#36373). + expect(within(region).getByText('Default field')).toBeInTheDocument(); + expect(within(region).queryByText('Default (region)')).not.toBeInTheDocument(); }); it('unticking Apply patches filterBindings[name] = false; re-ticking removes the entry', () => { diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ReportDefaultInspector.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ReportDefaultInspector.test.tsx index 89ec6f77766..9f3e43bf403 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ReportDefaultInspector.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ReportDefaultInspector.test.tsx @@ -75,11 +75,13 @@ describe('ReportDefaultInspector — dataset binding (9.0 single form)', () => { />, ); expect(labelledInput('Label').value).toBe('Pipeline'); - expect(screen.getByText('Dataset')).toBeInTheDocument(); + expect(screen.getByText('Data source')).toBeInTheDocument(); // The bound measure and dimension rows show. - expect(screen.getByText('Values (measures)')).toBeInTheDocument(); - expect(screen.getByText('total_amount')).toBeInTheDocument(); - expect(screen.getByText('Rows (dimensions)')).toBeInTheDocument(); + expect(screen.getByText('Metrics')).toBeInTheDocument(); + // A bound measure row reads `LABEL · AGGREGATE` in words; with no label + // declared the label is the name (objectstack#36373). + expect(screen.getByText('total_amount · Sum')).toBeInTheDocument(); + expect(screen.getByText('Group by')).toBeInTheDocument(); expect(screen.getByText('stage')).toBeInTheDocument(); }); @@ -110,8 +112,9 @@ describe('ReportDefaultInspector — dataset binding (9.0 single form)', () => { // Two add-popovers (values + rows) — open the first (values). const addButtons = screen.getAllByText(/add field/i); fireEvent.click(addButtons[0]); - // The popover item shows the measure's label ('deal_count · count'). - fireEvent.click(screen.getByText('deal_count · count')); + // The popover item shows the measure's label and its aggregate in the + // designer locale ('deal_count · Count'). + fireEvent.click(screen.getByText('deal_count · Count')); expect(onPatch).toHaveBeenCalledWith({ values: ['total_amount', 'deal_count'] }); }); @@ -139,7 +142,7 @@ describe('ReportDefaultInspector — dataset binding (9.0 single form)', () => { readOnly={false} />, ); - expect(screen.getByText('Columns (across dimensions)')).toBeInTheDocument(); + expect(screen.getByText('Group columns by')).toBeInTheDocument(); expect(screen.getByText('close_quarter')).toBeInTheDocument(); fireEvent.click(screen.getByRole('button', { name: 'Remove close_quarter' })); expect(onPatch).toHaveBeenCalledWith({ columns: [] }); @@ -154,7 +157,7 @@ describe('ReportDefaultInspector — dataset binding (9.0 single form)', () => { readOnly={false} />, ); - expect(screen.queryByText('Columns (across dimensions)')).not.toBeInTheDocument(); + expect(screen.queryByText('Group columns by')).not.toBeInTheDocument(); }); it('falls back to a manual dataset input when the catalog is empty', () => { @@ -167,7 +170,7 @@ describe('ReportDefaultInspector — dataset binding (9.0 single form)', () => { readOnly={false} />, ); - const input = labelledInput('Dataset'); + const input = labelledInput('Data source'); expect(input).toBeInTheDocument(); expect(input.tagName).toBe('INPUT'); }); @@ -181,8 +184,8 @@ describe('ReportDefaultInspector — dataset binding (9.0 single form)', () => { readOnly={false} />, ); - expect(screen.queryByText('Dataset')).not.toBeInTheDocument(); - expect(screen.queryByText('Values (measures)')).not.toBeInTheDocument(); + expect(screen.queryByText('Data source')).not.toBeInTheDocument(); + expect(screen.queryByText('Metrics')).not.toBeInTheDocument(); }); it('renders Chinese labels under zh-CN', () => { @@ -196,7 +199,7 @@ describe('ReportDefaultInspector — dataset binding (9.0 single form)', () => { />, ); expect(screen.getByText('报表类型')).toBeInTheDocument(); - expect(screen.getByText('数据集')).toBeInTheDocument(); + expect(screen.getByText('数据来源')).toBeInTheDocument(); }); it('disables inputs when readOnly', () => { @@ -224,7 +227,7 @@ describe('ReportDefaultInspector — dataset binding (9.0 single form)', () => { * was a correct `value` prop that reached no pixels. */ describe('ReportDefaultInspector — a dataset the catalog no longer lists (objectui#8488)', () => { - const datasetTrigger = () => screen.getByRole('combobox', { name: 'Dataset' }); + const datasetTrigger = () => screen.getByRole('combobox', { name: 'Data source' }); it('shows the stored dataset name, flagged, instead of a blank binding', () => { render( @@ -250,9 +253,9 @@ describe('ReportDefaultInspector — a dataset the catalog no longer lists (obje readOnly={false} />, ); - // `datasetOptions` labels a catalogued dataset `LABEL (NAME)`; the point of - // the case is the absence of the flag, not the label's own spelling. - expect(datasetTrigger().textContent).toBe('Sales metrics (sales_metrics)'); + // objectstack#36373 — a catalogued dataset reads as its label alone; the + // point of the case is the absence of the flag, not the label's spelling. + expect(datasetTrigger().textContent).toBe('Sales metrics'); expect(screen.queryByText(/not found/), 'nothing is flagged').toBeNull(); }); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/datasetPickers.authorText-11161.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/datasetPickers.authorText-11161.test.tsx index a88626b5ef7..caee11f3024 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/datasetPickers.authorText-11161.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/datasetPickers.authorText-11161.test.tsx @@ -1,14 +1,18 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * objectui#11161 — the report inspector and the dashboard-widget inspector - * show the author's text a dataset declares, beside the machine names. + * objectui#11161, as objectstack#36373 restates it — the report inspector and + * the dashboard-widget inspector show the author's text a dataset declares, + * and NOT the machine names beside it. * - * - Measure and dimension options show the member's `label` beside its name - * (the add-member list prints the name in its own code chip; a select item - * writes `LABEL (name)`; a measure keeps its ` · aggregate` hint). - * - Dataset options show the dataset's `description`. - * - Each falls back to the name when nothing is declared. + * - Measure and dimension options show the member's `label` alone; the + * machine name is the row's hover text (`title`), never a visible chip or a + * `(name)` suffix. A measure reads `LABEL · AGGREGATE` with the aggregate in + * the panel's language (「收入 · 合计」). + * - Dataset options show the dataset's label alone: no `(name)`, and no + * description (the card's 「只显示它的名称」). + * - Each falls back to the name when nothing is declared — the author's own + * word for an untranslated, unlabelled member. * - A map-valued label resolves in the designer locale, under en and under zh. * - What a pick stores is the machine name, never the label. * @@ -50,7 +54,7 @@ vi.stubGlobal( vi.fn(async () => new Response('null', { status: 404, headers: { 'content-type': 'application/json' } })), ); -import { t } from '../i18n'; +import { t, tFormat } from '../i18n'; import { ReportDefaultInspector } from './ReportDefaultInspector'; import { DashboardWidgetInspector } from './DashboardWidgetInspector'; @@ -83,6 +87,8 @@ const TEXT = { en: { pipeline: 'Sales pipeline', description: 'Open deals by stage', stage: 'Stage', revenue: 'Revenue' }, zh: { pipeline: '销售管道', description: '按阶段统计的在途商机', stage: '阶段', revenue: '收入' }, } as const; +/** An aggregate as the panel names it in the case language. */ +const agg = (lang: Lang, aggregate: string) => t(`engine.inspector.report.aggregate.${aggregate}`, LOCALE[lang]); let switchLanguage: ((lang: string) => Promise) | null = null; function LanguageProbe() { @@ -116,7 +122,8 @@ const norm = (s: string | null | undefined) => (s ?? '').replace(/\s+/g, ' ').tr /** * Open the Nth add-member popover and read each offered row as - * `[label, name chip or null]` — the two slots `AddFieldPopover` renders. + * `[label, hover text]` — the visible label and the machine name in `title`. + * A visible code chip fails the read outright: these panels print no names. */ async function openAddMember(lang: Lang, nth: number): Promise> { const addText = t('engine.form.addFieldPlain', LOCALE[lang]); @@ -127,10 +134,11 @@ async function openAddMember(lang: Lang, nth: number): Promise [ - norm(row.querySelector('span.font-medium')?.textContent), - row.querySelector('code') ? norm(row.querySelector('code')!.textContent) : null, - ]); + .map((row) => { + expect(row.querySelector('code'), 'no machine-name chip').toBeNull(); + const label = row.querySelector('span.font-medium'); + return [norm(label?.textContent), label?.getAttribute('title') ?? null]; + }); } /** Open a Radix select and read its items. */ @@ -167,29 +175,26 @@ function mountReport(lang: Lang, draft: Record, onPatch = vi.fn ); } -describe('the report inspector shows the dataset text beside the names (objectui#11161)', () => { +describe('the report inspector shows the dataset text, not the names (objectui#11161, objectstack#36373)', () => { for (const lang of LANGS) { const x = TEXT[lang]; - it(`${lang}: the dataset options show the description; one without it reads as before`, async () => { + it(`${lang}: the dataset options read the dataset's label alone`, async () => { await mountReport(lang, {}); const items = await selectItems(t('engine.inspector.report.dataset', LOCALE[lang])); - expect(items).toEqual([ - `${x.pipeline} (sales_pipeline) — ${x.description}`, - 'Bare metrics (bare_metrics)', - ]); + expect(items).toEqual([x.pipeline, 'Bare metrics']); }); - it(`${lang}: the measure options show the label beside the name, the aggregate kept`, async () => { + it(`${lang}: the measure options show the label and the aggregate in words, the name on hover`, async () => { await mountReport(lang, { dataset: 'sales_pipeline' }); expect(await openAddMember(lang, 0)).toEqual([ - [`${x.revenue} · sum`, 'revenue'], - // Nothing declared: the name, exactly as the option always read. - ['deal_count · count', 'deal_count'], + [`${x.revenue} · ${agg(lang, 'sum')}`, 'revenue'], + // Nothing declared: the name is the only word there is. + [`deal_count · ${agg(lang, 'count')}`, 'deal_count'], ]); }); - it(`${lang}: the dimension options show the label beside the name`, async () => { + it(`${lang}: the dimension options show the label, the name on hover`, async () => { await mountReport(lang, { dataset: 'sales_pipeline' }); expect(await openAddMember(lang, 1)).toEqual([ [x.stage, 'stage'], @@ -197,17 +202,14 @@ describe('the report inspector shows the dataset text beside the names (objectui ]); }); - it(`${lang}: the chart axis selects read LABEL (name), and the name alone when none is declared`, async () => { + it(`${lang}: the chart axis selects read the label alone, the name only when none is declared`, async () => { await mountReport(lang, { dataset: 'sales_pipeline', chart: { type: 'bar' } }); - expect(await selectItems(t('engine.inspector.report.chartX', LOCALE[lang]))).toEqual([ - `${x.stage} (stage)`, - 'region', - ]); + expect(await selectItems(t('engine.inspector.report.chartX', LOCALE[lang]))).toEqual([x.stage, 'region']); await userEvent.keyboard('{Escape}'); await flush(); expect(await selectItems(t('engine.inspector.report.chartY', LOCALE[lang]))).toEqual([ - `${x.revenue} (revenue) · sum`, - 'deal_count · count', + `${x.revenue} · ${agg(lang, 'sum')}`, + `deal_count · ${agg(lang, 'count')}`, ]); }); } @@ -216,14 +218,14 @@ describe('the report inspector shows the dataset text beside the names (objectui const onPatch = vi.fn(); await mountReport('en', { dataset: 'sales_pipeline', values: ['deal_count'] }, onPatch); await openAddMember('en', 0); - fireEvent.click(screen.getByText('Revenue · sum')); + fireEvent.click(screen.getByText('Revenue · Sum')); expect(onPatch).toHaveBeenCalledWith({ values: ['deal_count', 'revenue'] }); cleanup(); const onPick = vi.fn(); await mountReport('en', {}, onPick); - await selectItems('Dataset'); - await userEvent.click(screen.getByRole('option', { name: 'Sales pipeline (sales_pipeline) — Open deals by stage' })); + await selectItems('Data source'); + await userEvent.click(screen.getByRole('option', { name: 'Sales pipeline' })); expect(onPick).toHaveBeenCalledWith({ dataset: 'sales_pipeline' }); }); }); @@ -261,24 +263,23 @@ function mountWidget(lang: Lang, widget: Record, onPatch = vi.f ); } -describe('the dashboard-widget inspector shows the dataset text beside the names (objectui#11161)', () => { +describe('the dashboard-widget inspector shows the dataset text, not the names (objectui#11161, objectstack#36373)', () => { for (const lang of LANGS) { const x = TEXT[lang]; - it(`${lang}: the dataset options show the description as the option's hint`, async () => { + it(`${lang}: the dataset options read the label alone, the name on hover`, async () => { await mountWidget(lang, {}); fireEvent.click(screen.getByRole('combobox', { name: t('engine.inspector.widget.dataset', LOCALE[lang]) })); await flush(); const [pipeline, bare] = screen.getAllByRole('option'); - expect(within(pipeline).getByText('sales_pipeline')).toBeInTheDocument(); - expect(within(pipeline).getByText(`${x.pipeline} (sales_pipeline)`)).toBeInTheDocument(); - expect(within(pipeline).getByText(x.description)).toBeInTheDocument(); - // No description declared: no hint. The combo leads with the option's - // label and puts the machine name after it (objectui#12303). - expect(norm(bare.textContent)).toBe('Bare metrics (bare_metrics) bare_metrics'); + // objectui#12303's trailing machine name is gone from these panels. + expect(norm(pipeline.textContent)).toBe(x.pipeline); + expect(within(pipeline).getByText(x.pipeline)).toHaveAttribute('title', 'sales_pipeline'); + expect(norm(bare.textContent)).toBe('Bare metrics'); + expect(within(bare).getByText('Bare metrics')).toHaveAttribute('title', 'bare_metrics'); }); - it(`${lang}: the measure and dimension options show the label beside the name`, async () => { + it(`${lang}: the measure and dimension options show the label, the name on hover`, async () => { await mountWidget(lang, { dataset: 'sales_pipeline' }); expect(state.get).toHaveBeenCalledWith('dataset', 'sales_pipeline'); expect(await openAddMember(lang, 0)).toEqual([ @@ -288,21 +289,26 @@ describe('the dashboard-widget inspector shows the dataset text beside the names await userEvent.keyboard('{Escape}'); await flush(); expect(await openAddMember(lang, 1)).toEqual([ - [`${x.revenue} · sum`, 'revenue'], - ['deal_count · count', 'deal_count'], + [`${x.revenue} · ${agg(lang, 'sum')}`, 'revenue'], + [`deal_count · ${agg(lang, 'count')}`, 'deal_count'], ]); }); - it(`${lang}: the filter-binding field options show the dimension label beside its name`, async () => { + it(`${lang}: the filter-binding field options show the dimension label, the name on hover`, async () => { await mountWidget(lang, { dataset: 'sales_pipeline' }); const row = screen.getByTestId('widget-filter-binding-stage_filter'); fireEvent.click(within(row).getByRole('combobox')); await flush(); const [stage, region] = screen.getAllByRole('option'); - expect(within(stage).getByText('stage')).toBeInTheDocument(); - expect(within(stage).getByText(x.stage)).toBeInTheDocument(); - // No label declared: the name, and the type hint, as before. - expect(norm(region.textContent)).toBe('regiontext'); + expect(norm(stage.textContent)).toBe(x.stage); + expect(within(stage).getByText(x.stage)).toHaveAttribute('title', 'stage'); + // No label declared: the name alone — no type hint beside it. + expect(norm(region.textContent)).toBe('region'); + // The row names the filter by its label, and the empty face by the + // dimension's label — 「默认(阶段)」, never `stage`. + expect( + within(row).getByText(tFormat('engine.inspector.widget.filterBindingDefault', LOCALE[lang], { field: x.stage })), + ).toBeInTheDocument(); }); } @@ -310,7 +316,7 @@ describe('the dashboard-widget inspector shows the dataset text beside the names const onPatch = vi.fn(); await mountWidget('en', { dataset: 'sales_pipeline' }, onPatch); await openAddMember('en', 1); - fireEvent.click(screen.getByText('Revenue · sum')); + fireEvent.click(screen.getByText('Revenue · Sum')); expect(onPatch).toHaveBeenCalledWith({ widgets: [expect.objectContaining({ id: 'w1', values: ['revenue'] })], }); @@ -321,13 +327,13 @@ describe('the dashboard-widget inspector shows the dataset text beside the names // The trigger shows the bound option's label. Read by its id: the host's // `locale` prop is not what switches here, the app language is. const trigger = () => document.getElementById('widget-dataset'); - expect(norm(trigger()?.textContent)).toBe('Sales pipeline (sales_pipeline)'); + expect(norm(trigger()?.textContent)).toBe('Sales pipeline'); expect(switchLanguage, 'the provider handed its language switch over').toBeTruthy(); await act(async () => { await switchLanguage!('zh'); }); await flush(); - expect(norm(trigger()?.textContent)).toBe('销售管道 (sales_pipeline)'); + expect(norm(trigger()?.textContent)).toBe('销售管道'); expect(state.list, 'one read of the catalog, not one per language').toHaveBeenCalledTimes(1); expect(state.get, 'one hydration of the bound dataset, not one per language').toHaveBeenCalledTimes(1); }); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.componentListServedTitles-12688.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.componentListServedTitles-12688.test.tsx index f6f94d116f1..9861139c700 100644 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.componentListServedTitles-12688.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.componentListServedTitles-12688.test.tsx @@ -220,17 +220,24 @@ describe('objectui#12688 — a widget changed or added in the draft draws its au }); }); -describe('objectui#12688 — every editor keeps the authored widget title on the same zh-CN session', () => { - it("the widget inspector's Title input reads the authored title", async () => { +/** + * objectstack#36373 restates this case: the inspector's Title box reads the + * title in the session's language, as the canvas and the list beside it do. + * objectui#12688 kept the authored English here because an edit then wrote + * the source; an edit now writes the session language's entry + * (`servedLabel.ts`), so the box can show what the page shows. + */ +describe('objectstack#36373 — the widget inspector reads the served title on the same zh-CN session', () => { + it("the widget inspector's Title input reads the served title, not the English source", async () => { const inspector = await componentList('zh', '任务数与平均进度'); fireEvent.click(within(inspector).getByRole('button', { name: '任务数与平均进度' })); - expect(await screen.findByDisplayValue('Task Count vs Avg Progress', undefined, { timeout: 8000 })).toHaveAttribute( + expect(await screen.findByDisplayValue('任务数与平均进度', undefined, { timeout: 8000 })).toHaveAttribute( 'id', 'widget-title', ); - expect(screen.queryByDisplayValue('任务数与平均进度')).toBeNull(); + expect(screen.queryByDisplayValue('Task Count vs Avg Progress')).toBeNull(); }); }); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.heldWidget-11910.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.heldWidget-11910.test.tsx index 59dd999d662..9cbe9354dfc 100644 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.heldWidget-11910.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.heldWidget-11910.test.tsx @@ -171,7 +171,7 @@ async function addMetric(): Promise { async function bindDataset(): Promise { await userEvent.click(within(rail()).getByRole('combobox', { name: t('engine.inspector.widget.dataset', 'en') })); - await userEvent.click(await screen.findByRole('option', { name: /sales_ds/ })); + await userEvent.click(await screen.findByRole('option', { name: 'Sales' })); await flush(); } @@ -341,10 +341,13 @@ describe('a bound widget whose binding the author empties is held, not sent refu await within(rail()).findByDisplayValue(title, undefined, { timeout: 8000 }); } - /** The inspector's own remove button on the member `name` of a binding list. */ - function remove(name: string): void { + /** + * The inspector's own remove button on a member of a binding list, named by + * the row's label — a measure's reads `LABEL · AGGREGATE` (objectstack#36373). + */ + function remove(label: string): void { fireEvent.click( - within(rail()).getByRole('button', { name: tFormat('engine.viewColumnPanes.remove', 'en', { label: name }) }), + within(rail()).getByRole('button', { name: tFormat('engine.viewColumnPanes.remove', 'en', { label }) }), ); } @@ -357,7 +360,7 @@ describe('a bound widget whose binding the author empties is held, not sent refu mountPillar(report); await ready(); await selectWidget('pipeline', 'Pipeline'); - remove('revenue'); + remove('Revenue · Sum'); await outlastDebounce(); expect(dashboardSaves(), 'the emptied measure list is not sent').toEqual([]); @@ -390,7 +393,7 @@ describe('a bound widget whose binding the author empties is held, not sent refu mountPillar(); await ready(); await selectWidget('by_stage', 'By stage'); - remove('stage'); + remove('Stage'); await waitFor(() => expect(dashboardSaves()).toHaveLength(1), { timeout: 4000 }); const [sent] = dashboardSaves(); expect((sent.widgets as unknown[])[1]).toMatchObject({ id: 'by_stage', dimensions: [], values: ['revenue'] }); @@ -404,7 +407,7 @@ describe('a bound widget whose binding the author empties is held, not sent refu mountPillar(); await ready(); await selectWidget('spread', 'Spread'); - remove('stage'); + remove('Stage'); await outlastDebounce(); expect(dashboardSaves(), 'a scatter the spec refuses for want of a dimension is not sent').toEqual([]); @@ -432,6 +435,7 @@ describe('a bound widget whose binding the author empties is held, not sent refu mountPillar(); await ready(); await selectWidget('pipeline', 'Pipeline'); + // No such dataset, so no member text: the row reads the name. remove('revenue'); await waitFor(() => expect(dashboardSaves()).toHaveLength(1), { timeout: 4000 }); expect((dashboardSaves()[0].widgets as unknown[])[0]).toMatchObject({ dataset: 'Sales Pipeline', values: [] }); diff --git a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.reportHeld-27785.test.tsx b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.reportHeld-27785.test.tsx index e082d8a6bf4..c87c0c2e151 100644 --- a/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.reportHeld-27785.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/InterfacesPillar.reportHeld-27785.test.tsx @@ -254,7 +254,7 @@ describe('a chart type picked before its axes is held until both axes are picked const report = vi.fn(); mountPillar(report); const inspector = await ready('Order'); - await pick(inspector, L('engine.inspector.report.chartType'), 'bar'); + await pick(inspector, L('engine.inspector.report.chartType'), L('engine.inspector.widget.type.bar')); await outlastDebounce(); const clauseX = tFormat('engine.studio.held.reportChartNeedsInput', 'en', { input: x }); @@ -267,7 +267,7 @@ describe('a chart type picked before its axes is held until both axes are picked fireEvent.click(within(screen.getByTestId('studio-held')).getByRole('button', { name: L('engine.studio.refusal.show') })); await waitFor(() => expect(document.activeElement).toBe(within(inspector).getByRole('combobox', { name: x }))); - await pick(inspector, x, 'Stage (stage)'); + await pick(inspector, x, 'Stage'); await outlastDebounce(); expect(reportSaves(), 'one axis is not enough').toEqual([]); expect(screen.getByTestId('studio-held-message')).toHaveTextContent( @@ -279,8 +279,8 @@ describe('a chart type picked before its axes is held until both axes are picked const report = vi.fn(); mountPillar(report); const inspector = await ready('Order'); - await pick(inspector, L('engine.inspector.report.chartType'), 'bar'); - await pick(inspector, x, 'Stage (stage)'); + await pick(inspector, L('engine.inspector.report.chartType'), L('engine.inspector.widget.type.bar')); + await pick(inspector, x, 'Stage'); await pick(inspector, y, /^Revenue/); await waitFor(() => expect(reportSaves()).toHaveLength(1), { timeout: 4000 }); const [sent] = reportSaves(); diff --git a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldWidgetPublish-11910.test.tsx b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldWidgetPublish-11910.test.tsx index 2b5a723eb54..7479c8ed635 100644 --- a/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldWidgetPublish-11910.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/StudioDesignSurface.heldWidgetPublish-11910.test.tsx @@ -242,7 +242,7 @@ describe('Publish refuses while a new widget is held, naming it (objectui#11910) // The surface folds the inspector beside its chat dock, so the widget's // inspector is read from the page rather than from an aside. await userEvent.click(screen.getByRole('combobox', { name: t('engine.inspector.widget.dataset', 'en') })); - await userEvent.click(await screen.findByRole('option', { name: /sales_ds/ })); + await userEvent.click(await screen.findByRole('option', { name: 'Sales' })); const adds = await screen.findAllByRole('button', { name: t('engine.form.addFieldPlain', 'en') }); expect(adds.length, 'the dimensions and measures editors').toBe(2); fireEvent.click(adds[1]); diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 0014f881eac..bfe4b4bf880 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -627,7 +627,7 @@ const STUDIO_EN: Record = { 'engine.inspector.widget.height': 'Height', 'engine.inspector.widget.remove': 'Remove widget', // Dataset binding (ADR-0021) — governed cross-object semantic layer. - 'engine.inspector.widget.datasetSection': 'Data source', + 'engine.inspector.widget.datasetSection': 'Data', 'engine.inspector.widget.dataset': 'Data source', 'engine.inspector.widget.datasetPlaceholder': 'Choose a data source…', 'engine.inspector.widget.datasetHint': 'The widget reads its numbers from here; everyone sees only the records they have access to.', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index 193cff6b7d0..ef5f4852ba5 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -541,7 +541,7 @@ const STUDIO_ZH: Record = { 'engine.inspector.widget.height': '高度', 'engine.inspector.widget.remove': '删除组件', // Dataset binding (ADR-0021) — governed cross-object semantic layer. - 'engine.inspector.widget.datasetSection': '数据来源', + 'engine.inspector.widget.datasetSection': '数据', 'engine.inspector.widget.dataset': '数据来源', 'engine.inspector.widget.datasetPlaceholder': '选择数据来源…', 'engine.inspector.widget.datasetHint': '卡片从这里取数;每个人只能看到自己有权限的记录。', From 20bb0d84b3fba56e0f092dad5cefbc9f455899ea Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 09:24:49 +0000 Subject: [PATCH 04/15] test(app-shell): pin the business wording, the served heading and the label box (#36373) Claude-Session: https://claude.ai/code/session_01QsR2jUP9hxdL4RzdzTs9eK Co-authored-by: Claude --- ...portView.headingStaysServed-36373.test.tsx | 213 +++++++++++++++ .../panelBusinessWording-36373.test.tsx | 254 ++++++++++++++++++ .../inspectors/servedLabel.test.ts | 94 +++++++ .../metadata-admin/metadata-form-zh-cn.ts | 51 ++-- 4 files changed, 594 insertions(+), 18 deletions(-) create mode 100644 ui/packages/app-shell/src/views/ReportView.headingStaysServed-36373.test.tsx create mode 100644 ui/packages/app-shell/src/views/metadata-admin/inspectors/panelBusinessWording-36373.test.tsx create mode 100644 ui/packages/app-shell/src/views/metadata-admin/inspectors/servedLabel.test.ts diff --git a/ui/packages/app-shell/src/views/ReportView.headingStaysServed-36373.test.tsx b/ui/packages/app-shell/src/views/ReportView.headingStaysServed-36373.test.tsx new file mode 100644 index 00000000000..0661e96e4ad --- /dev/null +++ b/ui/packages/app-shell/src/views/ReportView.headingStaysServed-36373.test.tsx @@ -0,0 +1,213 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36373 — opening the report's editor keeps the page in the + * session's language. + * + * ## The defect this pins + * + * objectstack#35008 seeded the editor with the AUTHORED report, so a quick + * edit stores the source. `ReportView` also drew that buffer as the page: the + * heading and subtitle above the open panel turned from the served 「任务概览 + * (联合)」 to the English source the moment 「编辑」 was pressed. The page + * now draws the served text for every translated key the edit has not + * touched (`previewWithServedText`), and hands the panel the served text of + * the name, so its box reads the same language (`ServedReportTextContext`). + * + * Ablation (run): with `previewReport = editSchema ?? reportData`, the tree + * before this change, the first two cases go RED on the heading; the third, + * the context the panel reads, is a separate seam and stays GREEN. + * + * Harness: `ReportView.authoredEditBuffer-35008.test.tsx`'s, unchanged but for + * the stub inspector. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, waitFor, fireEvent, act, cleanup } from '@testing-library/react'; + +vi.mock('sonner', () => ({ + toast: Object.assign(vi.fn(), { + success: vi.fn(), error: vi.fn(), info: vi.fn(), + warning: vi.fn(), loading: vi.fn(), dismiss: vi.fn(), + }), +})); + +vi.mock('@object-ui/plugin-report', async (importOriginal) => ({ + ...(await importOriginal>()), + ReportRenderer: () => null, +})); +vi.mock('@object-ui/plugin-dashboard', async (importOriginal) => ({ + ...(await importOriginal>()), + DrillDownDrawer: () => null, +})); +// The panel's spec inspector, reduced to one edit of `description`, showing +// the served-text pair its host provides. +vi.mock('./metadata-admin/inspectors/ReportDefaultInspector', async () => { + const { useServedReportText } = await import('./studio-design/servedReportText'); + return { + ReportDefaultInspector: ({ onPatch, draft }: any) => { + const served = useServedReportText(); + return ( + + ); + }, + }; +}); + +const meta = vi.hoisted(() => ({ value: null as any })); +vi.mock('../providers/MetadataProvider', () => ({ useMetadata: () => meta.value })); + +vi.mock('react-router-dom', () => ({ + useParams: () => ({ reportName: 'task_overview' }), + useNavigate: () => vi.fn(), + useLocation: () => ({ pathname: '/apps/com.qa.tr/report/task_overview', search: '' }), +})); + +vi.mock('./useOpenRecordList', () => ({ + useRecordListDrillNavigation: () => ({ openRecordList: vi.fn(), canOpenRecordList: () => true }), +})); +vi.mock('./MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false }), +})); +const client = vi.hoisted(() => ({ value: null as any })); +vi.mock('./metadata-admin/useMetadata', () => ({ useMetadataClient: () => client.value })); +vi.mock('../providers/AdapterProvider', () => ({ useAdapter: () => ({}) })); +vi.mock('../providers/ExpressionProvider', () => ({ useExpressionContext: () => ({ app: undefined }) })); +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useWorkspaceAdminStatus: () => ({ isAdmin: true, isResolved: true }), +})); + +// `ReportView` reaches a dynamic `import('@objectstack/lint')` (through the panel's +// inspector): pay its load at collection, never inside a case's clocked window +// (`check:test-source-alias`). +import '@objectstack/lint'; +import { ReportView } from './ReportView'; + +const PKG = 'com.qa.tr'; + +/** The report as its author stored it (en source). */ +const SOURCE = { + name: 'task_overview', + label: 'Task Overview (Joined)', + description: 'Multiple task sub-reports stacked into one joined view.', + type: 'joined', + blocks: [ + { name: 'open_block', label: 'Open Tasks', type: 'summary', dataset: 'task_metrics', rows: ['status'], values: ['est_hours'] }, + { name: 'done_block', label: 'Completed Tasks', type: 'summary', dataset: 'task_metrics', rows: ['status'], values: ['task_count'] }, + ], +}; + +/** The same report as the zh-CN read serves it: translated, with the read's decorations. */ +function served(doc: typeof SOURCE) { + return { + ...doc, + label: '任务概览(联合)', + description: '将多个任务子报表堆叠在一个联合视图中。', + blocks: [ + { ...doc.blocks[0], label: '未完成任务' }, + { ...doc.blocks[1], label: '已完成任务' }, + ], + _packageId: PKG, + }; +} + +const refresh = vi.fn(async () => {}); + +function mountReport() { + meta.value = { + apps: [], + objects: [], + dashboards: [], + reports: [served(SOURCE)], + pages: [], + loading: false, + error: null, + refresh, + invalidate: () => {}, + ensureType: async () => [], + getItem: vi.fn(async () => null), + getItemsByType: () => [], + getTypeStatus: () => 'ready', + }; + render( ({ data: [] })) } as any} />); +} + +/** A client whose served reads translate and whose layered read is the stored row. */ +function makeClient({ draft }: { draft: typeof SOURCE | null }) { + return { + // The served draft read (`RuntimeDraftBar`): translated, like every served read. + get: vi.fn(async () => (draft ? served(draft) : null)), + // The served draft read the editor hands `authoredBuffer` (objectstack#35054): the envelope, translated. + getDraft: vi.fn(async () => (draft ? { type: 'report', name: draft.name, item: served(draft) } : null)), + layered: vi.fn(async () => ({ code: null, overlay: null, overlayScope: null, effective: SOURCE, draft })), + save: vi.fn(async () => ({})), + publish: vi.fn(async () => ({})), + reset: vi.fn(async () => ({})), + }; +} + +async function openEditor() { + fireEvent.click(await screen.findByTestId('report-edit-button')); + await screen.findByTestId('report-config-panel'); + await waitFor(() => expect(client.value.get).toHaveBeenCalled()); + await act(async () => {}); +} + +beforeEach(() => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'error').mockImplementation(() => {}); +}); + +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); + vi.clearAllMocks(); +}); + +describe('opening the report editor keeps the page in the session language (objectstack#36373)', () => { + it('the heading and subtitle stay as served once the editor is open', async () => { + client.value = makeClient({ draft: null }); + mountReport(); + expect(await screen.findByText('任务概览(联合)')).toBeInTheDocument(); + await openEditor(); + + // The editor holds the source (objectstack#35008) … + expect(screen.getByTestId('stub-report-edit')).toHaveAttribute('data-label', SOURCE.label); + // … and the page above it still reads as served. + expect(screen.getByText('任务概览(联合)')).toBeInTheDocument(); + expect(screen.getByText('将多个任务子报表堆叠在一个联合视图中。')).toBeInTheDocument(); + expect(screen.queryByText(SOURCE.label)).toBeNull(); + expect(screen.queryByText(SOURCE.description)).toBeNull(); + }); + + it('an edited key draws the edit; the keys left alone stay served', async () => { + client.value = makeClient({ draft: null }); + mountReport(); + await openEditor(); + fireEvent.click(screen.getByTestId('stub-report-edit')); + + expect(await screen.findByText('Edited description')).toBeInTheDocument(); + expect(screen.getByText('任务概览(联合)')).toBeInTheDocument(); + }); + + it('the panel is handed the served name beside the authored one it was translated from', async () => { + client.value = makeClient({ draft: null }); + mountReport(); + await openEditor(); + + const served = JSON.parse(screen.getByTestId('stub-report-edit').getAttribute('data-served')!); + expect(served.label).toEqual({ authored: SOURCE.label, served: '任务概览(联合)' }); + expect(served.description).toEqual({ authored: SOURCE.description, served: '将多个任务子报表堆叠在一个联合视图中。' }); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/panelBusinessWording-36373.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/panelBusinessWording-36373.test.tsx new file mode 100644 index 00000000000..332abc83082 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/panelBusinessWording-36373.test.tsx @@ -0,0 +1,254 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36373 — the report panel and the dashboard-widget panel speak + * business wording: labels, not machine names. + * + * The card's acceptance, as a sweep over the rendered panel: + * + * - The panel reads 「数据来源:商机指标」「指标:金额 · 合计、平均赢单概率 · + * 平均」「分组:阶段」「图表:柱状图」, and the name box reads the served + * 「各阶段商机」, not the English source. + * - No machine name, chart-type token or old term is anywhere in the panel's + * text: `total_amount`, `stage`, `bar`, `opportunity_metrics`, `RLS`, + * 「维度」「度量」「受治理」. A machine name lives in a `title` only. + * - The chart-type options are Chinese names, each with its icon. + * - In English the panel reads English labels, still with no machine name. + * - A filter binding names the filter: 「时间」 for the date range, the + * dimension label for a filter with no label of its own. + * - An edit of the name box lands in zh-CN: `{ default: SOURCE, 'zh-CN': EDIT }`. + * + * The fixture mirrors the HotCRM report the card measured + * (`opportunity_metrics`), with its labels already resolved — the catalog + * hook's job, pinned in `datasetPickers.authorText-11161.test.tsx`. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, cleanup, fireEvent, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { loadStudioCatalogue } from '@object-ui/i18n/namespaces/studio'; +import type { DatasetCatalogEntry } from '../previews/useDatasetCatalog'; +await loadStudioCatalogue('zh'); + +vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('null', { status: 404, headers: { 'content-type': 'application/json' } })), +); + +const LABELS = { + 'zh-CN': { + dataset: '商机指标', + total_amount: '金额', + avg_probability: '平均赢单概率', + stage: '阶段', + account_industry: '行业', + owner_id: '负责人', + }, + 'en-US': { + dataset: 'Opportunity metrics', + total_amount: 'Amount', + avg_probability: 'Win probability', + stage: 'Stage', + account_industry: 'Industry', + owner_id: 'Owner', + }, +} as const; +type Locale = keyof typeof LABELS; + +function catalogIn(locale: Locale): DatasetCatalogEntry[] { + const l = LABELS[locale]; + return [ + { + name: 'opportunity_metrics', + label: l.dataset, + description: 'Governed opportunity facts with RLS enforced', + dimensions: [ + { name: 'stage', label: l.stage, type: 'text' }, + { name: 'account_industry', label: l.account_industry, type: 'text' }, + { name: 'owner', field: 'owner_id', label: l.owner_id, type: 'lookup' }, + ], + measures: [ + { name: 'total_amount', label: l.total_amount, aggregate: 'sum' }, + { name: 'avg_probability', label: l.avg_probability, aggregate: 'avg' }, + ], + }, + ]; +} + +const semantics = vi.hoisted(() => ({ locale: 'zh-CN' as 'zh-CN' | 'en-US' })); +// The hooks run at render, after the module body: `catalogIn` is in scope. +vi.mock('../previews/useDatasetCatalog', async (importOriginal) => { + const real = await importOriginal>(); + return { + ...real, + // The widget inspector reads its members through `useDatasetSemantics`. + useDatasetSemantics: () => { + const [entry] = catalogIn(semantics.locale); + return { dimensions: entry.dimensions, measures: entry.measures, loading: false, error: null }; + }, + useDatasetCatalog: (override?: DatasetCatalogEntry[]) => ({ + datasets: override ?? catalogIn(semantics.locale), + loading: false, + error: null, + }), + }; +}); + +import { ReportDefaultInspector } from './ReportDefaultInspector'; +import { DashboardWidgetInspector } from './DashboardWidgetInspector'; +import { ServedReportTextContext } from '../../studio-design/servedReportText'; +import { t } from '../i18n'; + +afterEach(cleanup); + +const SOURCE = 'Opportunities by Stage'; +const SERVED = '各阶段商机'; + +const REPORT = { + name: 'opportunities_by_stage', + label: SOURCE, + type: 'summary', + dataset: 'opportunity_metrics', + rows: ['stage'], + values: ['total_amount', 'avg_probability'], + chart: { type: 'bar', xAxis: 'stage', yAxis: 'total_amount' }, +}; + +/** The words no panel may print: machine names, a chart token, the old terms. */ +const FORBIDDEN = ['total_amount', 'avg_probability', 'account_industry', 'opportunity_metrics', 'stage', 'bar', 'RLS', '维度', '度量', '受治理']; + +function visibleText(el: HTMLElement): string { + // A Radix select keeps a hidden native