diff --git a/.changeset/36373-report-panel-business-wording.md b/.changeset/36373-report-panel-business-wording.md new file mode 100644 index 00000000000..25c453dcfaf --- /dev/null +++ b/.changeset/36373-report-panel-business-wording.md @@ -0,0 +1,24 @@ +--- +'@objectstack/spec': minor +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(app-shell): the report and dashboard-widget panels speak business wording, and opening the report editor keeps the page in the session's language + +Clause-②: yes (widening) — the report and widget panels accept an edit of a translated name or title in the session's language, stored as the inline locale map `{ default: SOURCE, LANG: EDIT }` the spec's `I18nLabel` already allows; nothing is removed or renamed +Metadata-protocol: semantic — `translateReport` and `translateDashboard` now treat a report `label`/`description` or a widget `title` as changed when its inline locale-map entry for the requested locale (the entry the panel writes: exact tag, then the locale's own script, else base tag or a sibling region; never `default`) differs from the packaged base's own, so the base's translation no longer replaces it; a translation the paired `.custom` package ships still answers first (ruling record 6631250894), and with none the entry is served; dataset members (`translateDataset`, ADR-0149) are unchanged + +The report editor beside a report (runtime 「编辑」 and Studio) and the dashboard widget property bar (Studio, and the dashboard page's edit state) now name things the way a business reader does: + +- Fields, measures and data sources show their labels in the current language; the machine name is on hover only (`title`), never printed. A measure reads `LABEL · AGGREGATE` with the aggregate in words (「金额 · 合计」, "Amount · Sum"). +- 「行(维度)」「维度」 read 「分组」, 「值(度量)」 reads 「指标」, 「数据集」 reads 「数据来源」 (its label alone, no `(name)` and no description), and the filter-binding section reads 「跟着页面顶部的筛选变」 with each filter by its name (「时间」 for the date range, the dimension's label for a filter with none). +- The chart-type list is Chinese names with their icons (柱状图, 折线图, …), not `bar`. +- The line under the data source is plain words: 「报表从这里取数;每个人只能看到自己有权限的记录。」 — no 「受治理」 or 「RLS」. +- The report form rows below the curated fields (section headings and hints in zh-CN) use the same wording. + +The report's name box and a widget's title box show the served (current-language) text while it is untouched, and an edit lands in the session language only: a plain-string source shown translated becomes `{ default: SOURCE, LANG: EDIT }`, so every other language reads exactly what it read before. For a report or dashboard installed from a package (one with a packaged base), the server serves that entry ahead of the package's translation (a translation the paired customization package ships still comes first), so the edit is what the page shows after save. A report with no packaged base keeps the bundle first: where the bundle has an entry for that language, the stored edit does not show. + +Fixed: opening the report editor no longer turns the page heading and subtitle from the served 「各阶段商机」 to the English source. The page draws the served text for every translated key the edit has not touched. + +This supersedes objectui#11161's `LABEL (name)` and objectui#12303's trailing machine name on these two panels only; other dataset pickers are unchanged. diff --git a/content/docs/protocol/kernel/i18n-standard.mdx b/content/docs/protocol/kernel/i18n-standard.mdx index 4d042a8fb50..a174b0bca6e 100644 --- a/content/docs/protocol/kernel/i18n-standard.mdx +++ b/content/docs/protocol/kernel/i18n-standard.mdx @@ -287,6 +287,26 @@ its own raw dotted key on screen, in every locale. For the props that have no bundle key at all, the map is the **only** localisation route — a document localised that way is fully localised. +**A report's `label` and `description` and a dashboard widget's `title` keep +their map entry over the bundle at the `/meta` boundary** (objectstack#36373). +These props have a bundle key too, so `translateReport` and +`translateDashboard` decide between the two. The map's entry for the requested +locale is the one the panel writes for that locale — the exact tag, then an +entry of the locale's own script where the language splits by script (a +`zh-TW` reader never takes a Simplified `zh` entry), otherwise its base +language or a sibling region; never `default`. When the item has a packaged +base and that entry differs from the base's own, the slot counts as changed, +exactly as a re-authored string does: a translation the paired `.custom` +package ships still answers first, the base's translation never does, and with +no pair translation the entry is served. Otherwise (no packaged base, no +entry, or the same entry) the bundle entry is served as before. A map that repeats the package's own map +therefore still takes a package's translation updates, and a map an admin +edited in one language serves that edit while every other language reads its +bundle text. This is how the report and widget panels store an edit made in a +non-default language: `{ default: SOURCE, 'zh-CN': EDIT }`, the source text +untouched. Dataset members are not covered: `translateDataset` keeps ADR-0149's +bundle-first order. + **A map is never extracted, and no bundle key is synthesised for one.** `os i18n extract` scaffolds no row for a map and no key family exists for one; in particular **no key is derived from a node's position in the component diff --git a/content/docs/ui/dashboards.mdx b/content/docs/ui/dashboards.mdx index 72b1e9ce06c..ae1a804a5f3 100644 --- a/content/docs/ui/dashboards.mdx +++ b/content/docs/ui/dashboards.mdx @@ -743,9 +743,11 @@ or re-target. `os validate` and the publish door refuse such a key with absent). A dashboard embedded in a page that declares its own `variables` merges the two scopes: a filter shadows only an outer variable of the same name, and a write goes to the scope that defines the variable. -- **Bindings in Studio.** The dashboard widget inspector has a **Dashboard filter bindings** - section, one row per declared filter, with an apply toggle (the `false` opt-out) and a - field picker for the override. +- **Bindings in Studio.** The dashboard widget inspector has a **Follows the filters at the + top of the page** section, one row per declared filter, named by the filter's label (the + date range reads **Date**; a filter with no label reads its dimension's label), with an + apply toggle (the `false` opt-out) and a field picker for the override. The panel names + fields, metrics and data sources by their labels; a machine name shows on hover only. - **Refresh.** The page header has a **Refresh All** button, and `refreshIntervalSeconds` re-reads the widgets every that many seconds (`0` or unset: no automatic refresh). Widgets re-read in place rather than remounting, single-value tiles included. diff --git a/content/docs/ui/reports.mdx b/content/docs/ui/reports.mdx index 8c867bfba45..87b5479848c 100644 --- a/content/docs/ui/reports.mdx +++ b/content/docs/ui/reports.mdx @@ -305,6 +305,25 @@ A `report` entry **without** `reportName` opens the app's report index open. The console adds no index entry by itself: declare `{ id: 'nav_reports', type: 'report' }` where the menu should carry it. +## Editing a report beside it + +An admin opens a report's **Edit** panel from the report page (and the same panel in Studio). +The panel speaks the reader's language rather than the schema's: + +- **Data source** is the bound `dataset`, shown by its label; **Metrics** are its `values`, + each read as `LABEL · AGGREGATE` (*Amount · Sum*); **Group by** is its `rows`; a matrix adds + **Group columns by** (`columns`). Fields show their labels; the machine name is on hover only. +- The chart type list shows each type by name with its icon. +- The name box shows the report's name in the current language. An edit made in a + non-default language is stored for that language only, as the inline locale map + `{ default: SOURCE, 'zh-CN': EDIT }`, so every other language reads what it read before. + For a report installed from a package, the server serves that entry ahead of the + package's translation bundle; a report with no packaged base keeps the bundle first, so + where the bundle has an entry for that language the edit does not show + ([inline locale maps](/docs/protocol/kernel/i18n-standard#form-2-is-several-locales-text-at-once)). +- The page heading and subtitle stay in the current language while the panel is open; a key + the edit changes shows the edit. + ## Permissions and protection The report schema carries exactly **one** access-shaped block, and it is not about diff --git a/packages/spec/src/system/i18n-report.test.ts b/packages/spec/src/system/i18n-report.test.ts index fa539514410..b3361a08401 100644 --- a/packages/spec/src/system/i18n-report.test.ts +++ b/packages/spec/src/system/i18n-report.test.ts @@ -19,11 +19,14 @@ 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 // translator reading a member the schema does not carry cannot pass here. import { ReportSchema } from '../ui/report.zod'; +import { resolveI18nLabel } from '../ui/i18n-label-resolver'; const report = () => ReportSchema.parse({ name: 'opps_by_stage', @@ -178,3 +181,200 @@ 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 — the panel\'s edit is not served (owed: L2 7078881267 S2)', () => { + 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('按行业收入'); + }); + + // ─── L2 7078881267 M1: rank 1 of ruling record 6631250894 holds ────────── + it('a translation the paired `.custom` package ships still answers first (ruling 6631250894 rank 1)', () => { + const pairBundle: TranslationBundle = { 'zh-CN': { reports: { opps_by_stage: { label: '成对包的译文' } } } }; + const out = translateReport(editedInZh(), multi, { locale: 'zh-CN', packagedBase: packagedBase(), pairBundle }) as any; + expect(out.label).toBe('成对包的译文'); + }); + + it('a pair with no entry for the slot leaves the map, and the base\'s translation never answers', () => { + const pairBundle: TranslationBundle = { 'zh-CN': { reports: { opps_by_stage: { description: '成对包的说明' } } } }; + const out = translateReport(editedInZh(), multi, { locale: 'zh-CN', packagedBase: packagedBase(), pairBundle }) as any; + expect(out.label).toEqual(editedInZh().label); + expect(resolveI18nLabel(out.label, 'zh-CN')).toBe('各阶段商机(本公司)'); + }); + + it('a widget title: the pair answers first, then the entry, never the base\'s translation', () => { + const bundle: TranslationBundle = { 'zh-CN': { 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 pairBundle: TranslationBundle = { 'zh-CN': { dashboards: { exec: { widgets: { rev: { title: '成对包的标题' } } } } } }; + const withPair = translateDashboard(edited as any, bundle, { locale: 'zh-CN', packagedBase: base, pairBundle }) as any; + expect(withPair.widgets[0].title).toBe('成对包的标题'); + const emptyPair: TranslationBundle = { 'zh-CN': { dashboards: { exec: { label: '高管' } } } }; + const noEntry = translateDashboard(edited as any, bundle, { locale: 'zh-CN', packagedBase: base, pairBundle: emptyPair }) as any; + expect(noEntry.widgets[0].title).toEqual(edited.widgets[0].title); + }); + + // ─── L2 7079950960 S3: the pair speaks for the requested locale only ───── + it('a pair translation for a fallback locale does not outrank the map\'s own entry', () => { + const pairBundle: TranslationBundle = { en: { reports: { opps_by_stage: { label: 'Pipeline by stage (pair)' } } } }; + const out = translateReport(editedInZh(), multi, { + locale: 'zh-CN', fallbackChain: ['en'], packagedBase: packagedBase(), pairBundle, + }) as any; + expect(out.label).toEqual(editedInZh().label); + expect(resolveI18nLabel(out.label, 'zh-CN')).toBe('各阶段商机(本公司)'); + }); + + it('a pair translation for a sibling region (zh-TW) does not answer a zh-CN request over the zh-CN entry', () => { + const pairBundle: TranslationBundle = { 'zh-TW': { reports: { opps_by_stage: { label: '各階段商機(成對包)' } } } }; + const out = translateReport(editedInZh(), multi, { locale: 'zh-CN', packagedBase: packagedBase(), pairBundle }) as any; + expect(out.label).toEqual(editedInZh().label); + }); + + it('L2 7080413623 S4: a pair row stored under another spelling of the same language (zh-Hans) still answers a zh-CN request first', () => { + const pairBundle: TranslationBundle = { 'zh-Hans': { reports: { opps_by_stage: { label: '成对包的译文(zh-Hans)' } } } }; + const out = translateReport(editedInZh(), multi, { locale: 'zh-CN', packagedBase: packagedBase(), pairBundle }) as any; + expect(out.label).toBe('成对包的译文(zh-Hans)'); + // The mirror: a zh-Hans request over a row stored under zh-CN. + const edited = { ...report(), label: { default: 'Opportunities by Stage', 'zh-Hans': '各阶段商机(本公司)' } }; + const mirror: TranslationBundle = { 'zh-CN': { reports: { opps_by_stage: { label: '成对包的译文(zh-CN)' } } } }; + const back = translateReport(edited, multi, { locale: 'zh-Hans', packagedBase: packagedBase(), pairBundle: mirror }) as any; + expect(back.label).toBe('成对包的译文(zh-CN)'); + // A ja-JP request over a row stored under the table tag `ja`. + const editedJa = { ...report(), label: { default: 'Opportunities by Stage', 'ja-JP': 'ステージ別(当社)' } }; + const ja: TranslationBundle = { ja: { reports: { opps_by_stage: { label: 'ステージ別(ペア)' } } } }; + const jaOut = translateReport(editedJa, multi, { locale: 'ja-JP', packagedBase: packagedBase(), pairBundle: ja }) as any; + expect(jaOut.label).toBe('ステージ別(ペア)'); + }); + + it('a widget title: a fallback-locale pair translation leaves the zh-CN entry', () => { + const bundle: TranslationBundle = { 'zh-CN': { 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 pairBundle: TranslationBundle = { en: { dashboards: { exec: { widgets: { rev: { title: 'Revenue (pair)' } } } } } }; + const out = translateDashboard(edited as any, bundle, { locale: 'zh-CN', fallbackChain: ['en'], packagedBase: base, pairBundle }) as any; + expect(out.widgets[0].title).toEqual(edited.widgets[0].title); + }); + + it('control: a re-authored plain string still reads the pair along the chain, as before', () => { + const pairBundle: TranslationBundle = { en: { reports: { opps_by_stage: { label: 'Pipeline by stage (pair)' } } } }; + const edited = { ...report(), label: 'Pipeline by stage (ours)' }; + const out = translateReport(edited, multi, { locale: 'zh-CN', fallbackChain: ['en'], packagedBase: packagedBase(), pairBundle }) as any; + expect(out.label).toBe('Pipeline by stage (pair)'); + }); + + // ─── L2 7078881267 S1: the gate picks the entry the writer and reader pick ─ + describe('the entry for a locale is the one the panel writes and the reader shows', () => { + const scripts: TranslationBundle = { + ...multi, + 'zh-TW': { reports: { opps_by_stage: { label: '各階段商機' } } }, + }; + + it('a zh-TW request over { default, zh } reads its Traditional bundle text, never the Simplified entry', () => { + const edited = { ...report(), label: { default: 'Opportunities by Stage', zh: '各阶段(本公司)' } }; + const out = translateReport(edited, scripts, { locale: 'zh-TW', packagedBase: packagedBase() }) as any; + expect(out.label).toBe('各階段商機'); + }); + + it('a zh-TW request over { default, zh, zh-HK } gates on the zh-HK entry the reader shows', () => { + const edited = { + ...report(), + label: { default: 'Opportunities by Stage', zh: '各阶段(本公司)', 'zh-HK': '各階段(本公司)' }, + }; + const out = translateReport(edited, scripts, { locale: 'zh-TW', packagedBase: packagedBase() }) as any; + expect(out.label).toEqual(edited.label); + expect(resolveI18nLabel(out.label, 'zh-TW')).toBe('各階段(本公司)'); + // The Simplified entry alone, equal to the base's own, is no statement about zh-TW. + const sameHk = { ...report(), label: { ...edited.label } }; + const base = { ...report(), label: { ...edited.label } }; + expect((translateReport(sameHk, scripts, { locale: 'zh-TW', packagedBase: base }) as any).label).toBe('各階段商機'); + }); + + it('a bare-zh session reads the zh-CN entry its own edit replaced', () => { + const edited = { ...report(), label: { default: 'Opportunities by Stage', 'zh-CN': '各阶段商机(本公司)' } }; + const out = translateReport(edited, multi, { locale: 'zh', packagedBase: packagedBase() }) as any; + expect(out.label).toEqual(edited.label); + expect(resolveI18nLabel(out.label, 'zh')).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..d375ab44781 100644 --- a/packages/spec/src/system/i18n-resolver.ts +++ b/packages/spec/src/system/i18n-resolver.ts @@ -87,7 +87,7 @@ import { mapFlowNodeList } from '../conversions/walk.js'; import { flowScreenFieldOptionKey } from '../automation/flow-screen-option-key.js'; import { pageComponentSlotPositions } from '../ui/component.zod.js'; import { templateSlotSource } from '../automation/flow-text-slot-template.js'; -import { platformLocaleTagOf } from './platform-locales.js'; +import { PLATFORM_LOCALE_TAGS, platformLocaleTagOf } from './platform-locales.js'; import type { PlatformTranslationBundle, @@ -520,6 +520,10 @@ interface LabelCatalogs { * empty, which is exactly what every translator did * before the option existed: a changed string keeps its text, an unchanged * one reads `bundle`. With no `packagedBase` nothing counts as changed. + * + * [#36373] For a report `label` / `description` and a widget `title`, an + * inline locale map whose entry for the requested locale differs from the + * base's also counts as changed ({@link slotRead}). */ function labelCatalogs( bundle: TranslationBundle | undefined, @@ -2536,6 +2540,10 @@ function lookupWidgetAttr( * does not carry was authored after the fact and counts as diverged (the * object rule's "a base that declares no such scalar"). No base supplied is * the pre-#20680 behaviour, unchanged: the catalog applies. + * + * [#36373] A widget `title` written as an inline locale map whose entry for + * the requested locale differs from the base's counts as changed too + * ({@link slotRead}), so the base's translation never replaces it. */ export function translateDashboard( doc: T, @@ -2578,10 +2586,12 @@ 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, counts as changed (`translateReport`'s rule): + // the pair's translation for that locale still answers first, the + // base's never. + const titleRead = slotRead(catalogs, packagedWidget, 'title', w.title, opts); + const title = lookupWidgetAttr(titleRead.bundle, name, w.id, 'title', titleRead.opts); if (title) next.title = title; const desc = lookupWidgetAttr( catalogFor(catalogs, valueOverridesPackagedBase(packagedWidget, 'description', w.description)), @@ -3165,7 +3175,12 @@ function translateReportBlocks( * * `label` and `description` are `I18nLabelSchema` at the authoring site, so * either may be an inline locale map; a key the bundle does not carry leaves - * that map intact rather than flattening it to one language. + * that map intact rather than flattening it to one language. [#36373] A map + * whose entry for the requested locale differs from the base's counts as + * changed, as a re-authored string does ({@link slotRead}): the pair's + * translation for that locale still answers first, the base's translation + * never, and with neither the reader shows that entry. With no packaged base nothing counts + * as changed, so the bundle answers ahead of the entry. */ export function translateReport( doc: T, @@ -3178,12 +3193,16 @@ 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, counts as changed ({@link slotRead}): the slot reads the + // pair's translation for that locale only, so a translation the paired + // `.custom` package ships for it still answers first (ruling record + // 6631250894, rank 1) and the base's translation never does. No pair answer + // for that locale leaves the map as served, and the reader picks that entry. + const labelRead = slotRead(catalogs, base, 'label', doc.label, opts); + const label = lookupReportAttr(labelRead.bundle, name, 'label', labelRead.opts); + const descriptionRead = slotRead(catalogs, base, 'description', doc.description, opts); + const description = lookupReportAttr(descriptionRead.bundle, name, 'description', descriptionRead.opts); const blocks = translateReportBlocks(doc.blocks, catalogs, name, base, opts); if (label === undefined && description === undefined && blocks === undefined) return doc; return { @@ -4948,6 +4967,142 @@ function valueOverridesPackagedBase(base: unknown, key: string, value: unknown): return (base as Record)[key] !== value; } +/** + * The entry of an inline locale map that belongs to the REQUESTED locale: the + * entry the console's writer (`localeWriteKey` beside `pickLocalized` in + * `ui/packages/i18n/src/pickLocalized.ts`) replaces for an edit made in that + * locale, so the entry an edit lands in is the entry this gate asks about. + * + * 1. the exact tag; + * 2. where the platform table splits the base language by script (`zh` into + * `zh-Hans` and `zh-Hant`): the bare base, then the first sibling, that + * mean the locale's own script ({@link platformLocaleTagOf}), and nothing + * else, so a `zh-TW` request never takes a Simplified `zh` or `zh-CN` + * entry for its own; + * 3. otherwise the bare base (`pt` for `pt-BR`), then the first sibling + * sharing it, in key order. + * + * Own string properties only, and never an empty one. ⛔ Never `default` and + * never an entry of another script: 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)) return undefined; + const lang = (locale ?? '').trim(); + if (!lang) return undefined; + const map = value as Record; + const usable = (key: string): boolean => + Object.prototype.hasOwnProperty.call(map, key) && typeof map[key] === 'string' && (map[key] as string).length > 0; + const key = inlineEntryKeyFor(lang, usable, Object.keys(map)); + return key === undefined ? undefined : (map[key] as string); +} + +/** {@link inlineEntryFor}'s selection, as a key. */ +function inlineEntryKeyFor( + lang: string, + usable: (key: string) => boolean, + keys: readonly string[], +): string | undefined { + if (usable(lang)) return lang; + const base = lang.split('-')[0]; + const siblings = keys.filter((k) => k.split('-')[0] === base && usable(k)); + const script = platformLocaleTagOf(lang); + const splitsByScript = + script !== undefined && PLATFORM_LOCALE_TAGS.filter((t) => t.split('-')[0] === script.split('-')[0]).length > 1; + if (splitsByScript) { + if (usable(base) && platformLocaleTagOf(base) === script) return base; + return siblings.find((k) => platformLocaleTagOf(k) === script); + } + if (usable(base)) return base; + return siblings[0]; +} + +/** + * Whether an inline locale map's entry for the requested locale is a + * customer's own text that the BASE's translation must not replace — the + * map-valued twin of {@link valueOverridesPackagedBase}, which answers the + * same question for a plain string (`false` for any map). A separate function, + * not a second limb of that one: the exported {@link scalarOverridesPackagedBase} + * and the object fold that imports it compare strings only, and stay so. + * + * `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 through {@link slotRead} 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; +} + +/** + * [#36373] What a report `label` / `description` or a widget `title` is read + * from, and along which locales: + * + * - a plain string the override changed ({@link valueOverridesPackagedBase}): + * the pair's own translations along the whole locale chain, as every + * changed string reads ({@link catalogFor}); the override's text has no + * locale, so any translation of it is a better answer; + * - an inline map whose entry for the requested locale is the customer's own + * ({@link inlineEntryOverridesPackagedBase}): the pair's translation for + * the REQUESTED language only (the same tag, case aside, or another + * spelling of the same platform-table tag), with no fallback chain and no + * regional variant of another script. The map states its text for that locale, + * so a pair translation for another one (`en` down the chain, `zh-TW` for + * a `zh-CN` request) is no better answer than it. Rank 1 of ruling record + * 6631250894 is kept for the locale it speaks about; the base's + * translation never answers; + * - otherwise: the unchanged catalog, as before. + */ +function slotRead( + catalogs: LabelCatalogs, + base: unknown, + key: string, + value: unknown, + opts: TranslateDocumentOptions | undefined, +): { bundle: TranslationBundle | undefined; opts: TranslateDocumentOptions | undefined } { + if (valueOverridesPackagedBase(base, key, value)) return { bundle: catalogs.changed, opts }; + if (!inlineEntryOverridesPackagedBase(base, key, value, opts?.locale)) return { bundle: catalogs.unchanged, opts }; + const locale = (opts?.locale ?? '').trim(); + const pair = catalogs.changed; + const own = pair && locale ? samelanguagePairKey(Object.keys(pair), locale) : undefined; + return { + bundle: own === undefined ? undefined : ({ [locale]: pair![own] } as TranslationBundle), + opts: { ...opts, locale, fallbackChain: [] }, + }; +} + +/** + * The key of a pair bundle that holds the REQUESTED language, for + * {@link slotRead}: the same tag (case aside), else a key that names the same + * platform-table tag ({@link platformLocaleTagOf}: a `zh-CN` request reads a + * row stored under `zh-Hans`, `ja-JP` one under `ja`). It stops there, before + * the base-language and regional-variant steps of `pickData`, so a `zh-TW` + * key never answers a `zh-CN` request. + */ +function samelanguagePairKey(keys: readonly string[], locale: string): string | undefined { + const folded = locale.toLowerCase(); + const exact = keys.find((code) => code.toLowerCase() === folded); + if (exact !== undefined) return exact; + const tag = platformLocaleTagOf(locale); + return tag === undefined ? undefined : keys.find((code) => platformLocaleTagOf(code) === tag); +} + /** * 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/DashboardInPageEditor.tsx b/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx index 0a27b679ebb..7133377da52 100644 --- a/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx +++ b/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx @@ -50,6 +50,7 @@ import { appendArray, uniqueId } from './metadata-admin/inspectors/_shared.js'; import { getDashboardForm } from './metadata-admin/dashboard-schema.js'; import { useMetadataLocale, type SupportedLocale } from './metadata-admin/i18n.js'; import type { MetadataSelection } from './metadata-admin/preview-registry.js'; +import { ServedWidgetTextContext, servedWidgetTextOf } from './studio-design/servedDashboardText.js'; /** Where the editor would save, as read at open (nothing is written to open). */ export type WritableDashboardEditTarget = Exclude; @@ -259,6 +260,12 @@ export function DashboardEditActions({ * The right panel while editing: Studio's card panel for the selected card, * its dashboard panel (label, cards, filters, layout) otherwise. `revealFilters` * opens and scrolls to the filters section, the "Add filter" path. + * + * objectstack#36373: the panels read a card title in the session's language + * through {@link ServedWidgetTextContext}, as in Studio: `served` is the page's + * served dashboard, `published` the stored document the edit opened, paired + * widget by widget ({@link servedWidgetTextOf}). Without the pair the title box + * shows the stored source and an edit there replaces it. */ export function DashboardEditPanel({ name, @@ -268,9 +275,15 @@ export function DashboardEditPanel({ onSelectionChange, revealFilters, onFiltersRevealed, + served, + published, }: { name: string; draft: Record; + /** The dashboard as the page serves it, in the session's language. */ + served?: Record | null; + /** The stored document the edit state opened, before any change. */ + published?: Record | null; selection: MetadataSelection | null; onPatch: (patch: Record) => void; onSelectionChange: (next: MetadataSelection | null) => void; @@ -280,6 +293,7 @@ export function DashboardEditPanel({ const locale = useMetadataLocale(); const tt = useSafeTranslate(); const ref = React.useRef(null); + const servedWidgets = React.useMemo(() => servedWidgetTextOf(published, served), [published, served]); React.useEffect(() => { if (!revealFilters || selection) return; @@ -303,6 +317,7 @@ export function DashboardEditPanel({ className="w-full shrink-0 overflow-auto border-t bg-background p-3 sm:w-80 sm:border-l sm:border-t-0" data-testid="dashboard-edit-panel" > + {selection?.kind === 'widget' ? ( )} + ); } @@ -341,6 +357,8 @@ export type DashboardEditClient = DashboardEditReader & { export interface DashboardInPageEdit { /** The document being edited, `null` outside the edit state. */ draft: Record | null; + /** The stored document as the edit state opened it, before any change; `null` outside it. */ + published: Record | null; opening: boolean; saving: boolean; dirty: boolean; @@ -380,6 +398,7 @@ export function useDashboardInPageEdit({ const [session, setSession] = React.useState<{ target: WritableDashboardEditTarget; draft: Record; + published: Record; dirty: boolean; } | null>(null); const [opening, setOpening] = React.useState(false); @@ -402,7 +421,7 @@ export function useDashboardInPageEdit({ try { const opened = await openDashboardForEdit(name, ownerPackageId, client, { doors, walled }); if (opened.kind === 'refused') return opened; - setSession({ target: opened.target, draft: opened.doc, dirty: false }); + setSession({ target: opened.target, draft: opened.doc, published: opened.doc, dirty: false }); setSelection(null); return null; } finally { @@ -450,6 +469,7 @@ export function useDashboardInPageEdit({ return { draft: session?.draft ?? null, + published: session?.published ?? null, opening, saving, dirty: session?.dirty ?? false, diff --git a/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx index 9fbd6cec533..a89eec415bc 100644 --- a/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx +++ b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx @@ -88,9 +88,21 @@ vi.mock('sonner', () => ({ info: vi.fn(), }, })); -vi.mock('./metadata-admin/inspectors/DashboardWidgetInspector', () => ({ - DashboardWidgetInspector: (p: any) =>
{p.selection.id}
, -})); +vi.mock('./metadata-admin/inspectors/DashboardWidgetInspector', async () => { + // objectstack#36373: the stub reads the served title the real panel reads. + const { useServedWidgetText } = await import('./studio-design/servedDashboardText'); + return { + DashboardWidgetInspector: (p: any) => { + const pair = useServedWidgetText()?.widgets.get(p.selection.id); + return ( +
+ {p.selection.id} + {pair ? `${pair.served} ← ${pair.authored}` : 'none'} +
+ ); + }, + }; +}); vi.mock('./metadata-admin/inspectors/DashboardDefaultInspector', () => ({ DashboardDefaultInspector: (p: any) => (
@@ -235,6 +247,14 @@ describe('DashboardView in-page edit (objectstack#36372)', () => { expect(queryDataset.mock.calls.every((c: unknown[]) => (c[2] as { callerPackage?: string })?.callerPackage === 'crm')).toBe(true); }); + it('the card panel reads the served title beside the stored one (objectstack#36373)', async () => { + mount(); + await openEdit(); + fireEvent.click(screen.getByTestId('dashboard-preview-widget-widget_total')); + // The pair the title box shows and writes by: served for the session, authored as stored. + expect(screen.getByTestId('stub-widget-served-title')).toHaveTextContent('Total (served) ← Total (stored)'); + }); + it('Add card appends a card and selects it', async () => { mount(); await openEdit(); diff --git a/ui/packages/app-shell/src/views/DashboardView.tsx b/ui/packages/app-shell/src/views/DashboardView.tsx index 0da66322cf3..692315c07d1 100644 --- a/ui/packages/app-shell/src/views/DashboardView.tsx +++ b/ui/packages/app-shell/src/views/DashboardView.tsx @@ -511,6 +511,8 @@ export function DashboardView({ dataSource }: { dataSource?: any }) { onSelectionChange={edit.select} revealFilters={edit.revealFilters} onFiltersRevealed={edit.filtersRevealed} + served={dashboard as Record | undefined} + published={edit.published} /> )} 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/ReportView.tsx b/ui/packages/app-shell/src/views/ReportView.tsx index cea581b7a76..b82635d55b6 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; 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(() => {})} /> + ({ }), })); +// Pay the dynamic `@objectstack/formula` / `@objectstack/lint` load at collection, never inside a case's +// clocked window (`check:test-source-alias`). +import '@objectstack/formula'; +import '@objectstack/lint'; import { DashboardWidgetInspector } from './DashboardWidgetInspector'; // The inspector's `engine.inspector.*` rows live in `@object-ui/i18n`'s `studio` // namespace, whose `zh` catalogue is fetched on demand (objectstack#25922). @@ -65,10 +69,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 +100,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 +114,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 +234,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/DashboardWidgetInspector.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardWidgetInspector.tsx index 6d372a66f27..e3eb7374432 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,13 @@ 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, + columnIdentity, + 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 +51,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 +146,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 +159,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 +171,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 +179,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 +193,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 +337,11 @@ export function DashboardWidgetInspector({ patchWidget({ // Never `{ title: e.target.value }` — that is the flattening @@ -311,7 +350,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 +408,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 +494,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 +624,15 @@ export function DashboardWidgetInspector({ ); } +/** + * The label of the dataset dimension that reads the object field a dashboard + * filter names. A dimension's column is `columnIdentity()`'s answer — its + * declared `field`, else its `name` — the same column the filter applies to. + */ +function dimensionLabelOf(dimensions: DatasetDimensionInfo[], field: string): string | undefined { + return dimensions.find((d) => columnIdentity(d) === field)?.label || undefined; +} + /** * The id a `labelling="group"` field's `