diff --git a/.changeset/35891-record-page-no-stage-bar.md b/.changeset/35891-record-page-no-stage-bar.md new file mode 100644 index 00000000000..57d23c38549 --- /dev/null +++ b/.changeset/35891-record-page-no-stage-bar.md @@ -0,0 +1,23 @@ +--- +'@object-ui/plugin-detail': minor +'@object-ui/components': minor +'@object-ui/i18n': patch +'@objectstack/lint': minor +--- + +feat(plugin-detail): the default record page draws no stage bar and no key-field strip; the stage moves from the header's status tag + +Clause-②: yes (widening) +Metadata-protocol: semantic + +The default record page (`buildDefaultPageSchema`) no longer emits `record:highlights` or `record:path`. The stage is the status tag beside the record's name: a reader who may edit the stage field sees it with an arrow and opens a menu listing every stage in order, the current one checked; a stage the field's blocking `state_machine` cannot reach is disabled with its reason under the name. Picking a stage confirms, and a stage that makes other fields required (their `requiredWhen` holds once the record stands on it, such as a loss reason on a lost stage) asks for exactly those fields in the same dialog and writes them with the move. A refusal stays in the dialog, beside the field it names, and the stage does not move. A reader who may not edit the field, an approval lock or an open draft leaves the plain tag. A plain status field (no stage role) is read and moved the same way. + +The details body now draws every field its groups hold: the highlight fields and the stage field are no longer taken out of their groups, so a record reads in the same groups and order in view and in edit (objectstack#35849). `highlightFields` itself is unchanged and still drives the hover card, a related list's default columns and the record picker; nothing is picked when an object declares none. + +`buildDefaultHighlights` and both blocks are kept: an authored page, or a slotted page's `highlights` slot, still places a strip and a path where it wants them. + +- `@object-ui/components`: `RecordHeaderState` gains an optional `stage` renderer (with the exported `RecordHeaderStageParts`), which the header calls with the stage tag it would draw. Without a host bar (a phone) the header now draws the stage tag in the row under the record's name, beside the state's tags; before, a phone showed no stage at all. +- `@object-ui/plugin-detail`: exports `RecordStageMenu`, the menu a host hands the header as `RecordHeaderState.stage`. Its fields-a-stage-needs dialog comes from the package-internal `useStageChange` (`record:path` keeps its plain confirmation). +- `@object-ui/plugin-detail`: `BuildPageOptions.highlightFields`, `.statusField` and `.stages` are still accepted by `buildDefaultPageSchema` and `buildDefaultTabs` but no longer do anything there, since the default page draws no strip and no stage bar; `buildDefaultHighlights` still reads them. Retiring them is objectstack#35943. +- `@object-ui/i18n`: four `detail.stageMenu*` strings in every locale. +- `@objectstack/lint`: `field-group-shadowed` no longer counts the highlight strip as hiding fields from the detail body, since the default record page leaves them in their groups; a group whose only visible member is the record title still warns. diff --git a/content/docs/data-modeling/objects.mdx b/content/docs/data-modeling/objects.mdx index 16322cf57f7..32120259d2e 100644 --- a/content/docs/data-modeling/objects.mdx +++ b/content/docs/data-modeling/objects.mdx @@ -69,7 +69,7 @@ export const Account = ObjectSchema.create({ | `nameField` | `string` | optional | The stored field used as the record display name, e.g. `'name'` or `'title'` (ADR-0079). The deprecated alias `displayNameField` is still accepted. | | `titleFormat` | `string` | optional | Deprecated (ADR-0079 → `nameField`). Render-only title template (e.g. `'{{record.name}} - {{record.code}}'`); an explicit `nameField` takes precedence. An object definition that declares it is refused at save and by `os validate`; a stored object that carries it still loads | | `imageField` | `string` | optional | The record's picture: names a field of this object whose type is `image` or `avatar` — any other name is refused when the object is validated or published. It is the one object-level declaration the record page header draws beside the title; a record whose field is empty shows no picture. | -| `highlightFields` | `string[]` | optional | Most-important fields in priority order — default list columns, cards, previews, detail highlight strip (ADR-0085; formerly `compactLayout` — the old spelling was retired and is now rejected) | +| `highlightFields` | `string[]` | optional | Most-important fields in priority order — default list columns, cards, previews (ADR-0085; formerly `compactLayout` — the old spelling was retired and is now rejected) | | `stageField` | `string \| false` | optional | Linear lifecycle field; `false` declares the status field non-linear and suppresses stage heuristics (ADR-0085) | ### Capabilities (`enable`) diff --git a/content/docs/data-modeling/schema-design.mdx b/content/docs/data-modeling/schema-design.mdx index b05a54010b3..31f3f2984e0 100644 --- a/content/docs/data-modeling/schema-design.mdx +++ b/content/docs/data-modeling/schema-design.mdx @@ -57,7 +57,7 @@ export const MyObject = ObjectSchema.create({ | `description` | string | Help text | `'Companies...'` | | `nameField` | string | Canonical primary title field — the stored field used as the record display name (ADR-0079); the deprecated alias `displayNameField` is still accepted | `'name'` | | `titleFormat` | string | Deprecated (ADR-0079 → `nameField`). Render-only title template (`{{record.field}}` interpolation); an explicit `nameField` now takes precedence. Refused at save and by `os validate`; a stored object that carries it still loads | `'{{record.name}} - {{record.id}}'` | -| `highlightFields` | string[] | Most-important fields, in priority order (default columns, cards, previews, detail highlight strip; ADR-0085 — formerly `compactLayout`; the old spelling was retired and is now rejected) | `['name', 'status']` | +| `highlightFields` | string[] | Most-important fields, in priority order (default columns, cards, previews; ADR-0085 — formerly `compactLayout`; the old spelling was retired and is now rejected) | `['name', 'status']` | ### Enable Features diff --git a/content/docs/ui/forms.mdx b/content/docs/ui/forms.mdx index 41462f1edd4..6ef06073cfd 100644 --- a/content/docs/ui/forms.mdx +++ b/content/docs/ui/forms.mdx @@ -454,10 +454,10 @@ has been removed from `ObjectSchema`). Record-detail rendering is derived from the object's **cross-surface semantic roles** (ADR-0085): - `nameField` — which field is the record's display name. -- `highlightFields` — the most important fields (detail highlight strip, - default list columns, cards). -- `stageField` — the linear-lifecycle field behind the detail progress - stepper (`false` suppresses detection). +- `highlightFields` — the most important fields (hover cards, the record + picker, default list columns, cards). +- `stageField` — the linear-lifecycle field behind the stage tag in the + record header, a menu that moves it (`false` suppresses detection). - `fieldGroups` + `Field.group` — semantic grouping, rendered identically on forms, modals, and detail pages. diff --git a/content/docs/ui/pages.mdx b/content/docs/ui/pages.mdx index 923a89c942e..0851ac0d29b 100644 --- a/content/docs/ui/pages.mdx +++ b/content/docs/ui/pages.mdx @@ -180,7 +180,7 @@ replacement. ### The synthesized default A record page needs no authoring. With no page assigned, the Console synthesizes one from -the object: a header, the highlights strip, the record's **details**, and a right column of +the object: a header, the record's **details**, and a right column of panels: the related lists, then the attachments of an object with `enable: { files: true }`, then **Approvals** when the record has approval requests, and **动态** (Activity) last. On a narrow screen the same panels follow the details in one column, so **动态** ends the page. A @@ -226,7 +226,7 @@ synthesizer fills in the rest. A slotted page authors `slots`, not `regions`: | `header` | The `page:header` node | | `actions` | The action bar (`record:quick_actions`) | | `alerts` | The alert banners above the body | -| `highlights` | The highlights strip | +| `highlights` | Empty by default; a strip or stage bar placed here draws above the tabs | | `details` | The record's details; the rest of the page stays synthesized | | `discussion` | The discussion panel | diff --git a/docs/qa/platform-checklist/areas/studio-authoring.json b/docs/qa/platform-checklist/areas/studio-authoring.json index 2a4bca15d69..09271e9d743 100644 --- a/docs/qa/platform-checklist/areas/studio-authoring.json +++ b/docs/qa/platform-checklist/areas/studio-authoring.json @@ -315,13 +315,13 @@ "title": "Record-page authoring round-trip: created bound to its object, seeded from the default layout, block-edited, published, rendered", "since": "v16", "status": "active", - "revision": 16, + "revision": 17, "priority": "P1", "surface": "mixed", "personas": ["admin (authors)", "end user (opens the record). The viewer is the admin unless a member is used: every signed-in member reads showcase_account through the showcase's everyone baseline, showcase_member_default (allowRead; examples/app-showcase/src/security/permission-sets.ts MemberDefaultPermissionSet, which the dev CLI adds to every member per request). QA run #29893 (at 589049b0) drove the member leg as phone.demo@example.com and the authored page rendered; record which viewer each run used"], "fixtures": { "app": "showcase", - "requires": ["seeded showcase_account records to render the published page against (the stock showcase seed, examples/app-showcase/src/data/seed/index.ts). The object is chosen for two facts. It DECLARES highlightFields (status, industry, annual_revenue; examples/app-showcase/src/data/objects/account.object.ts), and since #28907 the synthesized default draws record:highlights only for declared highlightFields (deriveHighlightFields in ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts: an object that declares none gets no strip), so only such an object can show acceptance[0]'s record:highlights. And it ships NO record page (no page under examples/app-showcase/src/ui/pages names it), so the authored page is the one usePageAssignment serves. ⛔ Not showcase_contact: it declares no highlightFields, so its full create seeds no record:highlights by design (QA run #29672). ⛔ Not showcase_invoice: it ships the package default record page showcase_invoice_document (isDefault: true, examples/app-showcase/src/ui/pages/invoice-document.page.ts), which wins by design (objectui react usePageAssignment: the default record page, else the first), and authoring a second isDefault page answers 422 DEFAULT_RECORD_PAGE_CONFLICT. showcase_project, showcase_task and showcase_preference ship defaults too (QA runs #24571 and #24604)"], + "requires": ["seeded showcase_account records to render the published page against (the stock showcase seed, examples/app-showcase/src/data/seed/index.ts). The object is chosen because it ships NO record page (no page under examples/app-showcase/src/ui/pages names it), so the authored page is the one usePageAssignment serves. ⛔ Not showcase_invoice: it ships the package default record page showcase_invoice_document (isDefault: true, examples/app-showcase/src/ui/pages/invoice-document.page.ts), which wins by design (objectui react usePageAssignment: the default record page, else the first), and authoring a second isDefault page answers 422 DEFAULT_RECORD_PAGE_CONFLICT. showcase_project, showcase_task and showcase_preference ship defaults too (QA runs #24571 and #24604)"], "knownGaps": [ "AUTOMATION LIVES UNDER ui/ — `automated.ref` names objectui specs, and since objectui was imported into this repository they resolve at ui/PATH in this checkout. A jsdom unit pin runs from ui/, the objectui root, with its path written relative to ui/: `cd ui && pnpm exec vitest run --maxWorkers=1 packages/PKG/src/FILE`. ⛔ Not `pnpm --filter @object-ui/PKG exec vitest run FILE`: that runs in the package directory, and the ui vitest guard (ui/scripts/vitest-invocation-guard.mjs, which ui/vitest.config.mts calls) refuses any run whose Vitest root is not ui/ (its package-cwd verdict). a ui/e2e/live spec runs from ui/ with `pnpm test:e2e:live SPEC` against a live backend and the console dev server (the prerequisites are in ui/playwright.live.config.ts). Cite the output naming the commit, or drive the item by hand in the browser and score it as a manual run. ⛔ Never score it as covered on the strength of the `automated` field alone — an unrun pin is a claim, not evidence. Full protocol: RUNNER.md, the objectui-pinned-automation standing fact." ] @@ -329,7 +329,7 @@ "steps": [ "open /_console/studio/~all/metadata/page/new — Studio's All metadata area, where the retired Setup create URL (/_console/apps/showcase_app/metadata/page/new) lands in one hop since #28818 (setupMetadataStudioPath); the same create form (MetadataResourceEditPage in create mode), and with no ?package= the save binds no package, as before — and fill the create form: Label 'Invoice Page ' (slugifies into Name), set Page type = record (the create form defaults Page type to list — objectui metadata-admin anchors.ts, the page createSchema), Kind = full (a record page's Kind defaults to slotted, which saves regions [] and shows the object's synthesized default page by design; only an explicit full copies the default's regions into the draft, the page createSeed in ui/packages/app-shell/src/views/metadata-admin/anchors.ts), Object showcase_account (fixtures.requires[0]); Save", "capture the PUT /api/v1/meta/page/ request the save issues", - "assert the draft body: type:'record', object:'showcase_account', kind:'full', and regions seeded NON-empty from the object's synthesized default detail page (the page resource's createSeed hook) including a record:highlights block carrying the object's declared highlightFields (fixtures.requires[0]) — never a blank canvas (ADR-0034 / objectui#1541)", + "assert the draft body: type:'record', object:'showcase_account', kind:'full', and regions seeded NON-empty from the object's synthesized default detail page (the page resource's createSeed hook) including the record:details field sections, and no record:highlights or record:path block: since #35891 the synthesized default page draws neither, so the copy carries neither (an author adds them as blocks) — never a blank canvas (ADR-0034 / objectui#1541)", "open the page editor (/_console/studio/~all/metadata/page/, the All metadata item page — the generic editor, since the cross-package leg opens no pillar): the Basics, Data Context and Advanced panels render (the layout is edited on the canvas, not in a Layout section — see acceptance[1].verify), and 'Add block' opens the block-type picker", "add a block (e.g. Card); the draft autosaves (the block pick and each property edit PUT the draft, and the toolbar Save stays disabled), then Publish through the ResourceEditPage draft/publish chrome", "GET /api/v1/meta/page/: the published regions must include the added block", @@ -338,9 +338,9 @@ ], "acceptance": [ { - "clause": "a record page created Kind = full persists bound to its object with PRE-SEEDED regions — record:highlights present, regions non-empty, on an object that declares highlightFields (fixtures.requires[0])", + "clause": "a record page created Kind = full persists bound to its object with PRE-SEEDED regions — regions non-empty and the same blocks as the synthesized default page, which since #35891 places no key-field strip and no stage bar", "oracle": "network", - "verify": "the captured PUT body has type:'record', object:'showcase_account', kind:'full', Array.isArray(regions) with blocks including record:highlights, which carries the declared highlightFields (status, industry, annual_revenue)", + "verify": "the captured PUT body has type:'record', object:'showcase_account', kind:'full', Array.isArray(regions) non-empty, its blocks (those inside page:tabs included) holding record:details, and no record:highlights or record:path block anywhere in them (buildDefaultPageSchema in ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts places neither unless a highlights slot is authored)", "evidence": "the captured PUT payload" }, { @@ -430,7 +430,8 @@ }, { "revision": 14, "date": "2026-11-03", "change": "the item's record page moves from showcase_contact to showcase_account: fixtures.requires[0], personas[1], steps[0], steps[2], steps[6], acceptance[0] (clause and verify), acceptance[3].verify and automated.ref. Since #28907 (8bb2417a74) the synthesized default record page draws record:highlights only for an object's declared highlightFields (deriveHighlightFields, ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts), and showcase_contact declares none. So QA run #29672 read a full create on it with no record:highlights and scored acceptance[0] FAIL as stale spec; its control, a full create on showcase_account, carried the block. Read from source at base 339f63da30: showcase_account declares highlightFields status, industry and annual_revenue (examples/app-showcase/src/data/objects/account.object.ts), the page createSeed copies the synthesized regions on a full create (ui/packages/app-shell/src/views/metadata-admin/anchors.ts), no showcase page names the object, and the everyone baseline showcase_member_default reads it. The clause keeps its strength: a full create on the named object without record:highlights is still the FAIL. acceptance[1] to [3] passed on showcase_contact in the run and are not yet driven on showcase_account. Card #29679, from QA run #29672", "ref": "#29679" }, { "revision": 15, "date": "2026-11-04", "change": "steps[4] and personas[1] corrected from QA run #29893 (W5-STUDIO, at 589049b0): the record page draft autosaves (Save stays disabled), and the member leg has now been driven. Read at base f68b47ca", "ref": "#29906" }, - { "revision": 16, "date": "2026-11-08", "change": "acceptance[3].verify: a Card from the picker has no properties and renders an empty box, so its title is set before publish and the render is judged by that title. Checklist-accuracy finding of QA run #31486 (owed:weekly, at 0647dabb). Read at base 4894cfe1", "ref": "#31499" } + { "revision": 16, "date": "2026-11-08", "change": "acceptance[3].verify: a Card from the picker has no properties and renders an empty box, so its title is set before publish and the render is judged by that title. Checklist-accuracy finding of QA run #31486 (owed:weekly, at 0647dabb). Read at base 4894cfe1", "ref": "#31499" }, + { "revision": 17, "date": "2026-11-20", "change": "fixtures.requires[0], steps[2] and acceptance[0] (clause and verify) follow #35891 (epic #35590; maintainer 2026-11-20 17:16:59Z, 「把阶段条和关键字段条去掉,是的」): the synthesized default record page places no record:highlights and no record:path, so a full create copies neither, and acceptance[0] would read their absence as a FAIL. The clause now asks for the default page's blocks, record:details among them, and for neither strip nor bar. showcase_account stays the object because it ships no record page; its declared highlightFields no longer decide the seed. The showcase_contact exclusion is gone with that reason. Read from source on the #35891 branch at base 2f314ee6b9. No run made", "ref": "#35891" } ] }, { diff --git a/packages/lint/src/validate-semantic-roles.test.ts b/packages/lint/src/validate-semantic-roles.test.ts index 20f2834ee65..e25a7826a49 100644 --- a/packages/lint/src/validate-semantic-roles.test.ts +++ b/packages/lint/src/validate-semantic-roles.test.ts @@ -104,9 +104,11 @@ describe('validateSemanticRoles (ADR-0085)', () => { expect(control.map((f) => [f.rule, f.message.includes('"lines"')])).toEqual([[FIELD_GROUP_EMPTY, true]]); }); - it('flags a group fully shadowed by the highlight strip (rule d)', () => { - // `money`'s only member is also a highlight → detail bodies hide it, so - // the group never renders on detail pages. + // objectstack#35849 — the default record page draws no highlight strip and + // leaves every grouped field in its group (objectstack#35891), so a group + // whose members are all highlights IS drawn on the detail page. Rule (d) + // used to hide the first six highlights from the body and warn here. + it('rule d no longer counts highlights as hidden from the body (objectstack#35849)', () => { const findings = validateSemanticRoles(stack([{ name: 'zoo', highlightFields: ['name', 'status', 'amount'], @@ -117,94 +119,70 @@ describe('validateSemanticRoles (ADR-0085)', () => { fields: { name: { type: 'text' }, status: { type: 'select', group: 'basics' }, - code: { type: 'text', group: 'basics' }, // keeps basics visible + code: { type: 'text', group: 'basics' }, amount: { type: 'number', group: 'money' }, }, }])); - expect(findings).toHaveLength(1); - expect(findings[0]).toMatchObject({ - severity: 'warning', - rule: FIELD_GROUP_SHADOWED, - path: 'objects[0].fieldGroups', - }); - expect(findings[0].message).toContain('money'); - expect(findings[0].message).toContain('amount'); + expect(findings).toEqual([]); + + // Every one of the six strip positions: a group holding only that + // highlight is drawn, so nothing is flagged. + for (const position of [1, 2, 3, 4, 5, 6]) { + const strip = ['a', 'b', 'c', 'd', 'e', 'f']; + const owner = strip[position - 1]; + const clean = validateSemanticRoles(stack([{ + name: 'lead', + highlightFields: strip, + fieldGroups: [{ key: 'basics', label: 'Basics' }, { key: 'assignment', label: 'Assignment' }], + fields: { + name: { type: 'text', group: 'basics' }, notes: { type: 'textarea', group: 'basics' }, + ...Object.fromEntries(strip.map((n) => [n, { type: 'text', ...(n === owner ? { group: 'assignment' } : {}) }])), + }, + }])); + expect(clean, `position ${position}`).toEqual([]); + } }); - it('rule d counts the title field as hidden-from-body and respects the 6-entry strip cap', () => { - // A group holding only the record title never renders in the body even - // though the title is filtered OUT of the strip. + it('rule d still flags a group that holds only the record title', () => { + // A group holding only the record title never renders in the body: the + // title is the page heading. const titleOnly = validateSemanticRoles(stack([{ name: 'doc', highlightFields: ['title', 'status'], fieldGroups: [{ key: 'head', label: 'Head' }], fields: { title: { type: 'text', group: 'head' }, status: { type: 'select' } }, }])); - expect(titleOnly.map((f) => f.rule)).toEqual([FIELD_GROUP_SHADOWED]); - - // Entry #7 is beyond the strip (first 6 after the title filter), so a - // group containing it still renders → clean. - const beyondCap = validateSemanticRoles(stack([{ - name: 'wide', - highlightFields: ['name', 'a', 'b', 'c', 'd', 'e', 'f', 'g'], - fieldGroups: [{ key: 'tail', label: 'Tail' }], - fields: { - name: {}, a: {}, b: {}, c: {}, d: {}, e: {}, f: {}, - g: { type: 'text', group: 'tail' }, - }, - }])); - expect(beyondCap).toEqual([]); + expect(titleOnly).toHaveLength(1); + expect(titleOnly[0]).toMatchObject({ severity: 'warning', rule: FIELD_GROUP_SHADOWED, path: 'objects[0].fieldGroups' }); + expect(titleOnly[0]?.message).toContain('"head"'); // Hidden members don't keep a group "visible": a group whose only - // NON-hidden member is highlighted is still shadowed. + // NON-hidden member is the title is still shadowed. const hiddenMember = validateSemanticRoles(stack([{ name: 'mix', - highlightFields: ['name', 'amount'], - fieldGroups: [{ key: 'money', label: 'Money' }], + highlightFields: ['amount'], + fieldGroups: [{ key: 'head', label: 'Head' }], fields: { - name: {}, - amount: { type: 'number', group: 'money' }, - legacy: { type: 'text', group: 'money', hidden: true }, + name: { type: 'text', group: 'head' }, + amount: { type: 'number' }, + legacy: { type: 'text', group: 'head', hidden: true }, }, }])); - expect(hiddenMember.map((f) => f.rule)).toEqual([FIELD_GROUP_SHADOWED]); - }); + expect(hiddenMember).toHaveLength(1); + expect(hiddenMember[0]?.rule).toBe(FIELD_GROUP_SHADOWED); - // The record page hoists RECORD_HIGHLIGHTS_MAX (6) highlights and its body - // leaves them out. The rule used to cut at 4, so a group whose only member - // sat 5th or 6th was emptied on the page and passed the lint. - it('rule d judges the six highlights the record page hoists, not four', () => { - for (const position of [5, 6]) { - const strip = ['a', 'b', 'c', 'd', 'e', 'f']; - const owner = strip[position - 1]; - const findings = validateSemanticRoles(stack([{ - name: 'lead', - highlightFields: strip, - fieldGroups: [{ key: 'basics', label: 'Basics' }, { key: 'assignment', label: 'Assignment' }], - fields: { - name: { type: 'text', group: 'basics' }, notes: { type: 'textarea', group: 'basics' }, - ...Object.fromEntries(strip.map((n) => [n, { type: 'text', ...(n === owner ? { group: 'assignment' } : {}) }])), - }, - }])); - expect(findings, `position ${position}`).toHaveLength(1); - expect(findings[0]).toMatchObject({ severity: 'warning', rule: FIELD_GROUP_SHADOWED, path: 'objects[0].fieldGroups' }); - expect(findings[0]?.message).toContain('"assignment"'); - expect(findings[0]?.hint).toContain('first 6 highlightFields'); - } - - // Control: four highlights out of a six-slot strip, every group keeping - // a member the body draws → clean. - const fourOfSix = validateSemanticRoles(stack([{ - name: 'lead', - highlightFields: ['a', 'b', 'c', 'd'], - fieldGroups: [{ key: 'basics', label: 'Basics' }, { key: 'assignment', label: 'Assignment' }], + // Control: the same group with a second visible member is drawn. + const withSecond = validateSemanticRoles(stack([{ + name: 'mix', + highlightFields: ['amount'], + fieldGroups: [{ key: 'head', label: 'Head' }], fields: { - name: { type: 'text', group: 'basics' }, notes: { type: 'textarea', group: 'basics' }, - a: { type: 'text', group: 'basics' }, b: { type: 'text' }, c: { type: 'text' }, - d: { type: 'text', group: 'assignment' }, owner_id: { type: 'text', group: 'assignment' }, + name: { type: 'text', group: 'head' }, + code: { type: 'text', group: 'head' }, + amount: { type: 'number' }, }, }])); - expect(fourOfSix).toEqual([]); + expect(withSecond).toEqual([]); }); // #6326 — rule (d)'s title resolution used to read @@ -220,28 +198,24 @@ describe('validateSemanticRoles (ADR-0085)', () => { // key can physically reach it; the assertion is that it is IGNORED. Do not // make the fixture schema-valid: that deletes the coverage. // - // The pair below is the discriminating one. Title resolution matters here - // because the title is filtered OUT of the 6-entry strip, so whether - // `ref_no` counts as the title decides whether entry #7 (`f`) lands inside - // the strip. Read as the title → strip is [a,b,c,d,e,f], group "tail" - // (only member `f`) is fully hidden → SHADOWED. Not read → strip is - // [ref_no,a,b,c,d,e], `f` still renders → clean. No field here is one of the + // The pair below is the discriminating one: group "head" holds only + // `ref_no`. Read as the title → the group is shadowed. Not read → `ref_no` + // is an ordinary field the body draws → clean. No field here is one of the // conventional fallbacks (name/full_name/title/subject/display_name), and // none is an injected system column, so nothing else can supply a title. + // (Before objectstack#35849 the pair discriminated through the six-entry + // strip instead; the strip no longer hides anything.) it('ignores primaryField in title resolution; nameField still resolves (#6326)', () => { const withPhantomKey = validateSemanticRoles(stack([{ name: 'ledger_entry', primaryField: 'ref_no', - highlightFields: ['ref_no', 'a', 'b', 'c', 'd', 'e', 'f'], - fieldGroups: [{ key: 'tail', label: 'Tail' }], - fields: { - ref_no: { type: 'text' }, a: { type: 'text' }, b: { type: 'text' }, - c: { type: 'text' }, d: { type: 'text' }, e: { type: 'text' }, f: { type: 'text', group: 'tail' }, - }, + highlightFields: ['ref_no', 'a'], + fieldGroups: [{ key: 'head', label: 'Head' }], + fields: { ref_no: { type: 'text', group: 'head' }, a: { type: 'text' } }, }])); // Goes red the moment the `primaryField` entry returns to the chain: - // `ref_no` would become the title, `f` would fall inside the strip, and - // one FIELD_GROUP_SHADOWED finding would appear. + // `ref_no` would become the title and one FIELD_GROUP_SHADOWED finding + // would appear. expect(withPhantomKey).toEqual([]); // Paired positive — the SAME shape with the one declarable pointer. This @@ -250,12 +224,9 @@ describe('validateSemanticRoles (ADR-0085)', () => { const withNameField = validateSemanticRoles(stack([{ name: 'ledger_entry', nameField: 'ref_no', - highlightFields: ['ref_no', 'a', 'b', 'c', 'd', 'e', 'f'], - fieldGroups: [{ key: 'tail', label: 'Tail' }], - fields: { - ref_no: { type: 'text' }, a: { type: 'text' }, b: { type: 'text' }, - c: { type: 'text' }, d: { type: 'text' }, e: { type: 'text' }, f: { type: 'text', group: 'tail' }, - }, + highlightFields: ['ref_no', 'a'], + fieldGroups: [{ key: 'head', label: 'Head' }], + fields: { ref_no: { type: 'text', group: 'head' }, a: { type: 'text' } }, }])); // Indexed rather than `.map((f) => f.rule)` on purpose: this file's // relative import of the module under test omits the `.js` extension, so @@ -264,7 +235,7 @@ describe('validateSemanticRoles (ADR-0085)', () => { // Same assertion strength, no new ledger entry. expect(withNameField).toHaveLength(1); expect(withNameField[0]?.rule).toBe(FIELD_GROUP_SHADOWED); - expect(withNameField[0]?.message).toContain('tail'); + expect(withNameField[0]?.message).toContain('head'); }); it('flags stageField pointing at a missing field; false is fine', () => { @@ -324,12 +295,22 @@ describe('validateSemanticRoles — a group that lists its own fields', () => { fields: { name: { type: 'text' }, code: { type: 'text' } }, }])); expect(clean, JSON.stringify(clean)).toEqual([]); - const shadowed = validateSemanticRoles(stack([{ + // A highlighted member is drawn in the body (#35849), so highlighting + // `code` too leaves the group visible. + const highlighted = validateSemanticRoles(stack([{ name: 'quote', highlightFields: ['name', 'code'], fieldGroups: [{ key: 'basic', label: 'Basic', fields: ['code', 'name'] }], fields: { name: { type: 'text' }, code: { type: 'text' } }, }])); + expect(highlighted, JSON.stringify(highlighted)).toEqual([]); + // A list naming only the record title is shadowed: the title is the H1. + const shadowed = validateSemanticRoles(stack([{ + name: 'quote', + highlightFields: ['name'], + fieldGroups: [{ key: 'basic', label: 'Basic', fields: ['name'] }], + fields: { name: { type: 'text' }, code: { type: 'text' } }, + }])); expect(shadowed.map((f) => f.rule)).toEqual([FIELD_GROUP_SHADOWED]); }); @@ -430,7 +411,7 @@ describe('validateSemanticRoles — injected system columns (#5378)', () => { fieldGroups: [{ key: 'basic', label: 'Basic' }], fields: { name: { group: 'basic' }, notes: { group: 'basic' } }, }])); - // `basic` has two declared members, neither hoisted into the strip, so no + // `basic` has two declared members, neither the title, so no // FIELD_GROUP_SHADOWED — and no injected column is counted as its member. expect(findings).toEqual([]); }); diff --git a/packages/lint/src/validate-semantic-roles.ts b/packages/lint/src/validate-semantic-roles.ts index 4251797eabc..c4c9c9b6c15 100644 --- a/packages/lint/src/validate-semantic-roles.ts +++ b/packages/lint/src/validate-semantic-roles.ts @@ -28,7 +28,6 @@ * are different questions, and only one of them moved. */ -import { RECORD_HIGHLIGHTS_MAX } from '@objectstack/spec/ui'; import { readFieldGroupMembership } from '@objectstack/spec/data'; import { injectedColumnsFor, unprovisionedInjectedColumnsFor } from './system-fields.js'; import { recordsOf } from './object-graph.js'; @@ -252,17 +251,19 @@ export function validateSemanticRoles(stack: AnyRec): SemanticRoleFinding[] { if (unprovisioned.has(entry)) findings.push(unprovisionedPointer('highlightFields', entry)); } - // ── (d) declared group fully shadowed by the detail highlight strip ── - // Detail pages render the first RECORD_HIGHLIGHTS_MAX highlightFields - // (after the title leaves the list) as the top strip and HIDE those - // fields from the details body. The count is the spec constant the record - // page synthesizer cuts with, so the verdict and the screen cannot drift - // apart; a literal here once judged 4 while the page drew 6, so a group - // emptied by the 5th or 6th highlight passed. The record's title field is - // the page H1 and never renders in the body either. A group whose every - // visible member is covered by strip ∪ title therefore renders on FORMS - // but silently never on detail pages — legal, but almost never what the - // author pictured when they declared the group. + // ── (d) declared group fully shadowed on the detail page ── + // The record's title field is the page H1 and never renders in the + // details body. A group whose every visible member is the title therefore + // renders on FORMS but silently never on detail pages — legal, but almost + // never what the author pictured when they declared the group. + // + // The highlight strip no longer counts (objectstack#35849): the default + // record page draws no strip and leaves every grouped field in its group + // (objectstack#35891), so a highlighted field is drawn in the body like + // any other. The rule used to hide the first six (RECORD_HIGHLIGHTS_MAX) + // highlights from the body too, and judging that now would warn about + // groups the page draws. Its reach is unchanged: objects that declare + // `highlightFields`. const declaredStrings = highlights.filter( (h): h is string => typeof h === 'string' && h.length > 0, ); @@ -280,10 +281,7 @@ export function validateSemanticRoles(stack: AnyRec): SemanticRoleFinding[] { .find((v): v is string => typeof v === 'string' && v.length > 0 && fieldNames.has(v)); const titleField = declaredTitle ?? ['name', 'full_name', 'title', 'subject', 'display_name'].find((c) => fieldNames.has(c)); - const stripSet = new Set( - declaredStrings.filter((h) => h !== titleField).slice(0, RECORD_HIGHLIGHTS_MAX), - ); - const hiddenFromBody = new Set(stripSet); + const hiddenFromBody = new Set(); if (titleField) hiddenFromBody.add(titleField); for (const key of declaredGroups) { @@ -299,12 +297,10 @@ export function validateSemanticRoles(stack: AnyRec): SemanticRoleFinding[] { path: `${path}.fieldGroups`, message: `${objName}: every field in group "${key}" (${members.join(', ')}) is ` + - `hoisted into the detail highlight strip (or is the record title) — ` + - `the group renders on forms but never on detail pages`, + `the record title — the group renders on forms but never on detail pages`, hint: - `Keep at least one non-highlighted field in "${key}", or remove the ` + - `group if the strip already covers it. (Detail pages show the first ` + - `${RECORD_HIGHLIGHTS_MAX} highlightFields as the top strip and hide them from the body.)`, + `Add another field to "${key}", or remove the group. (Detail pages show ` + + `the record title as the page heading and leave it out of the body.)`, }); } } diff --git a/ui/e2e/record-tabs-rail-35595.spec.ts b/ui/e2e/record-tabs-rail-35595.spec.ts index 55ed67303b0..6433b50fac1 100644 --- a/ui/e2e/record-tabs-rail-35595.spec.ts +++ b/ui/e2e/record-tabs-rail-35595.spec.ts @@ -18,7 +18,9 @@ import { uiRoot } from '../scripts/ui-root.mjs'; * at the 1184 px a 1440 window leaves draws every tab. * - On 概览 the stage path and the key fields are at the top across the * whole width — both columns; CONTROL, the details column beside the rail - * is narrower than they are. + * is narrower than they are. Since objectstack#35891 the default page + * draws no strip, so the fixture places one in the `highlights` slot, as + * an authored page does. * - The rail is the 概览 tab's: another tab open draws no rail and no * strip; CONTROL, back on 概览 both are drawn again. * - A rail card's title opens its tab; CONTROL, the 概览 tab returns. @@ -168,7 +170,7 @@ import { I18nProvider } from ${JSON.stringify(I18N)}; import { RelatedCountStore } from ${JSON.stringify(COUNT_STORE)}; import { RecordPageColumns } from ${JSON.stringify(PAGE_COLUMNS)}; import { buildDefaultPageColumns, recordPageTierFor } from ${JSON.stringify(SYNTH_COLUMNS)}; -import { buildDefaultPageSchema } from ${JSON.stringify(SYNTH_PAGE)}; +import { buildDefaultHighlights, buildDefaultPageSchema } from ${JSON.stringify(SYNTH_PAGE)}; const h = React.createElement; const c = window.__case; @@ -196,16 +198,21 @@ const approvals = { requests: [{ id: 'req-1' }], pendingRequest: { id: 'req-1', step_label: '经理审批', pending_approvers: ['u2'], pending_approver_names: { u2: '王经理' } }, }; -const page = buildDefaultPageSchema( - { name: 'account', label: '客户', enable: { files: true }, fields: { name: { type: 'text' }, phone: { type: 'phone' }, rating: { type: 'select' } } }, - { - related: RELATED.map(([objectName, relationshipField, title]) => ({ objectName, relationshipField, title })), - highlightFields: ['phone'], - statusField: 'rating', - stages: [{ value: 'cold', label: '冷' }, { value: 'warm', label: '温' }, { value: 'hot', label: '热' }], - approvals: { count: 1, node: { approvals, currentUserId: 'u1' } }, - }, -); +const ACCOUNT = { name: 'account', label: '客户', enable: { files: true }, fields: { name: { type: 'text' }, phone: { type: 'phone' }, rating: { type: 'select' } } }; +const STRIP = { + highlightFields: ['phone'], + statusField: 'rating', + stages: [{ value: 'cold', label: '冷' }, { value: 'warm', label: '温' }, { value: 'hot', label: '热' }], +}; +// Since objectstack#35891 the default page draws no strip; the stage path and +// the key fields are placed the way an author places them, in the highlights +// slot, and the columns lay that strip out as before. +const page = buildDefaultPageSchema(ACCOUNT, { + related: RELATED.map(([objectName, relationshipField, title]) => ({ objectName, relationshipField, title })), + ...STRIP, + approvals: { count: 1, node: { approvals, currentUserId: 'u1' } }, + slots: { highlights: buildDefaultHighlights(ACCOUNT, STRIP) }, +}); const columns = buildDefaultPageColumns(page); function Host() { diff --git a/ui/packages/app-shell/src/views/RecordDetailView.lookupDependsOn-7190.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.lookupDependsOn-7190.test.tsx index 704d8fdff40..fb603080e83 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.lookupDependsOn-7190.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.lookupDependsOn-7190.test.tsx @@ -45,11 +45,12 @@ * * `InlineFieldInput` has exactly two non-test call sites — `DetailSection` (the * details body) and `HeaderHighlight` (the highlights strip). The canonical - * record page routes a field to exactly one of them: `buildDefaultTabs` hands - * the strip's field list to `buildDefaultDetails` as `hideFields`, so a - * highlight is hidden from the body. Declaring `highlightFields` therefore - * selects which call site renders the fields under test, with no classname - * coupling and no double render. + * record page routes a field to exactly one of them: a strip's fields are + * left out of the body (`HighlightFieldsContext`), so the field list the + * strip holds selects which call site renders the fields under test, with no + * classname coupling and no double render. Since objectstack#35891 the default + * page draws no strip, so every case places it through a slotted page's + * `highlights` slot (`stripPage`), holding the list it declares. * * The two call sites build the record differently, which is why both are pinned * rather than one: `DetailView` hands `DetailSection` the saved record already @@ -241,8 +242,7 @@ function makeDataSource(fields: Fields, record: Record = RECORD } as any; } -function makeMetadata() { - const pages: any[] = []; +function makeMetadata(pages: any[] = []) { return { objects: [], pages, loading: false, error: null, refresh: async () => {}, invalidate: () => {}, @@ -251,10 +251,22 @@ function makeMetadata() { } as any; } -function tree(ds: any, objects: any[]) { +/** + * The record page that draws the strip. Since objectstack#35891 the default + * page draws none, so the strip is placed the way an author places it: a + * slotted page whose `highlights` slot holds the declared list. + */ +function stripPage(highlightFields: string[]) { + return { + name: `${OBJECT}_strip`, type: 'record', object: OBJECT, kind: 'slotted', isDefault: true, regions: [], + slots: { highlights: { type: 'record:highlights', properties: { fields: highlightFields } } }, + }; +} + +function tree(ds: any, objects: any[], pages: any[] = []) { return ( - + = RECORD, ) { const ds = makeDataSource(fields, record); - const { container } = render(tree(ds, objectsWith(fields, highlightFields))); + const { container } = render(tree(ds, objectsWith(fields, highlightFields), [stripPage(highlightFields)])); await screen.findByText('Task one'); fireEvent.doubleClick(screen.getByText('emea')); await waitFor(() => { diff --git a/ui/packages/app-shell/src/views/RecordDetailView.phoneFace-27058.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.phoneFace-27058.test.tsx index 44d89b25271..9984ca519bc 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.phoneFace-27058.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.phoneFace-27058.test.tsx @@ -15,7 +15,8 @@ * knows its rows; no ⊟ (the stack has no right column), no ⤡ (no drawer * to collapse to); * - Target 4, the header: the subtitle from the first two declared text - * highlights, then at most four highlights; + * highlights (the strip of four that followed is gone since + * objectstack#35891); * - Target 7, the bottom bar: the header's actions drawn below the body, in * their bar face — the host's Edit, the primary and the `⋯`, however many * actions the page declares (objectstack#34595; this file pinned Edit @@ -301,7 +302,7 @@ describe('the record page on a phone (objectstack#27058)', () => { expect(pageBar()!.querySelector('[data-record-top-bar-position]')).toBeNull(); }); - it('the header: the subtitle from the first two declared text highlights, then at most four highlights', async () => { + it('the header: the subtitle from the first two declared text highlights; no strip under it (objectstack#35891)', async () => { mountPage([`/apps/${APP}/${LEAD}/record/r-1`]); const subtitle = await waitFor( () => { @@ -312,17 +313,12 @@ describe('the record page on a phone (objectstack#27058)', () => { { timeout: 5000 }, ); expect(subtitle.textContent).toBe('Atlas Construction · Director of Sales'); - const strip = document.querySelector('[data-highlights-face]') as HTMLElement; - expect(strip).toBeTruthy(); - const text = strip.textContent ?? ''; - // Email, Status, Phone, City: four, after the subtitle's two; the fifth - // declared one (Website) is in the sections. - expect(strip.children).toHaveLength(4); - expect(text).toContain('mira@atlas.test'); - expect(text).toContain('Austin'); - expect(text).not.toContain('Atlas Construction'); - expect(text).not.toContain('atlas.test/'); - expect(text).not.toContain('https://atlas.test'); + // Until objectstack#35891 a strip of four highlights (Email, Status, + // Phone, City) followed. The default page draws no strip now, on a phone + // as on a desktop; those fields read in their groups. + expect(document.querySelector('[data-highlights-face]')).toBeNull(); + await waitFor(() => expect(document.body.textContent).toContain('mira@atlas.test')); + expect(document.body.textContent).toContain('Austin'); }); it('the bottom bar: [Edit][Convert Lead][⋯] with the declared second action in the ⋯; the header draws no action row (objectstack#34595)', async () => { diff --git a/ui/packages/app-shell/src/views/RecordDetailView.phoneOwnerLine-28909.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.phoneOwnerLine-28909.test.tsx index 2e34c01f4c1..f0f85dbbb9f 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.phoneOwnerLine-28909.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.phoneOwnerLine-28909.test.tsx @@ -12,10 +12,11 @@ * harness), with `owner_id` declared 5th in `highlightFields`, behind four * non-text highlights (so the phone subtitle takes none of them): * - * - at 390 px the phone header draws four highlights after its subtitle, so - * the owner is not in the strip and the meta line names it; - * - at 1440 px the strip draws all five, the owner among them, and the meta - * line leaves it out (objectstack#28868, the owner once). + * - until objectstack#35891 the phone header drew four highlights (the + * owner past them, so the meta line named it) and the desktop strip all + * five (the strip named the owner, the meta line did not); + * - the default page draws no strip now, so at 390 px and at 1440 px the + * meta line names the owner. */ import * as React from 'react'; @@ -138,17 +139,15 @@ function mountPage() { ); } -/** The strip and the meta line, once both are drawn. */ -async function stripAndMetaLine(): Promise<{ strip: HTMLElement; metaLine: HTMLElement }> { +/** The meta line, once the record has loaded. */ +async function metaLineLoaded(): Promise { return waitFor( () => { - const strip = document.querySelector('[data-highlights-face]') as HTMLElement | null; const metaLine = document.querySelector('[data-testid="record-meta-footer"]') as HTMLElement | null; - expect(strip).toBeTruthy(); expect(metaLine).toBeTruthy(); - // The record has loaded: the strip shows its values. - expect(strip!.textContent).toContain('mira@atlas.test'); - return { strip: strip!, metaLine: metaLine! }; + // The record has loaded: its values are on the page. + expect(document.body.textContent).toContain('mira@atlas.test'); + return metaLine!; }, { timeout: 5000 }, ); @@ -180,24 +179,22 @@ afterEach(() => { }); describe('the owner at every width, once (objectstack#28909)', () => { - it('on a phone: owner_id declared 5th is past the header\'s four, so the meta line names the owner', async () => { + // Until objectstack#35891 the default page drew a strip of the declared + // highlights: four on a phone (the owner past them, so the meta line named + // it) and all five on a desktop (the strip named the owner, the meta line + // did not). The default page draws no strip now, at any width, so the meta + // line names the owner at both. + it.each([ + ['a phone', 390], + ['a desktop', 1440], + ])('on %s: no strip, and the meta line names the owner', async (_face, width) => { + setWidth(width); mountPage(); - const { strip, metaLine } = await stripAndMetaLine(); - // The phone header: four highlights, the owner not among them. - expect(strip.children).toHaveLength(4); - expect(strip.textContent).not.toContain('Ada Admin'); + const metaLine = await metaLineLoaded(); + expect(document.querySelector('[data-highlights-face]')).toBeNull(); const owner = ownerEntry(metaLine); expect(owner).toBeTruthy(); expect(owner!.textContent).toContain('Ada Admin'); - }); - - it('on a desktop: the strip names the owner and the meta line does not', async () => { - setWidth(1440); - mountPage(); - const { strip, metaLine } = await stripAndMetaLine(); - expect(strip.children).toHaveLength(5); - expect(strip.textContent).toContain('Ada Admin'); - expect(ownerEntry(metaLine)).toBeNull(); // The rest of the meta line is still drawn. expect(metaLine.querySelector('[data-record-meta-id]')!.textContent).toBe('r-1'); }); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 8b8b7af456a..a625095f9df 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -84,7 +84,7 @@ import type { ConsoleActionDispatch } from '../consoleActionDispatch.js'; import { useRecordApprovals, openApprovalOf, isSubmitterOf } from '../hooks/useRecordApprovals.js'; import { RecordAttachmentsPanel } from './RecordAttachmentsPanel.js'; import { RecordApprovalsPanel } from './RecordApprovalsPanel.js'; -import { ApprovalBandOnceScope } from '@object-ui/plugin-detail'; +import { ApprovalBandOnceScope, RecordStageMenu } from '@object-ui/plugin-detail'; import { DeclaredActionsBar } from './DeclaredActionsBar.js'; import { SYS_APPROVAL_REQUEST_OBJECT, @@ -5542,6 +5542,9 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri ) : undefined, + // objectstack#35891 — the stage tag is the stage's menu: the default + // page draws no stage bar, so the header is where the stage moves. + stage: (parts) => , }; const sharedChrome = ( <> diff --git a/ui/packages/app-shell/src/views/RecordDetailView.updateActionRefresh-29935.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.updateActionRefresh-29935.test.tsx index fd3385a23ef..5737ba0d22b 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.updateActionRefresh-29935.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.updateActionRefresh-29935.test.tsx @@ -222,12 +222,13 @@ function headerCtaLabels(): string[] { } /** - * The header path bar's current stage, as each rendering of it (wide and - * narrow) names it to assistive tech. + * The stage the header's stage tag reads, as each rendering of it names it. + * Until objectstack#35891 this read the path bar's current step; the default + * page draws no path bar now, and the stage is the tag beside the name. */ function currentStages(): string[] { - return Array.from(document.querySelectorAll('[role="listitem"][aria-current="step"]')) - .map((el) => el.getAttribute('aria-label') ?? ''); + return Array.from(document.querySelectorAll('[data-record-stage-tag]')) + .map((el) => (el.textContent ?? '').trim()); } function actionPosts(): string[] { @@ -283,10 +284,10 @@ afterEach(() => { }); describe('objectstack#29935 — a declared update action reflects its write on the record page', () => { - it('full page: after the 200 the page re-reads, the path bar reads Resolved and the Resolve button is gone', async () => { + it('full page: after the 200 the page re-reads, the stage tag reads Resolved and the Resolve button is gone', async () => { const dataSource = await mount([resolveTicket], 'page'); expect(headerCtaLabels()).toContain('Resolve'); - await waitFor(() => expect(currentStages()).toContain('Open, current stage')); + await waitFor(() => expect(currentStages()).toContain('Open')); const readsBefore = dataSource.findOne.mock.calls.length; await click('Resolve'); @@ -295,22 +296,22 @@ describe('objectstack#29935 — a declared update action reflects its write on t await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Ticket resolved.', expect.anything())); await waitFor(() => expect(dataSource.findOne.mock.calls.length).toBeGreaterThan(readsBefore)); await waitFor(() => expect(headerCtaLabels()).not.toContain('Resolve')); - await waitFor(() => expect(currentStages()).toContain('Resolved, current stage')); - expect(currentStages()).not.toContain('Open, current stage'); + await waitFor(() => expect(currentStages()).toContain('Resolved')); + expect(currentStages()).not.toContain('Open'); }); it('drawer: the same click re-reads the record and the Open list it came from drops it', async () => { const dataSource = await mount([resolveTicket], 'drawer'); const openList = () => Array.from(screen.getByTestId('open-list').querySelectorAll('li')).map((li) => li.textContent); await waitFor(() => expect(openList()).toEqual([RECORD_ID, OTHER_ID])); - await waitFor(() => expect(currentStages()).toContain('Open, current stage')); + await waitFor(() => expect(currentStages()).toContain('Open')); const readsBefore = dataSource.findOne.mock.calls.length; await click('Resolve'); await waitFor(() => expect(dataSource.findOne.mock.calls.length).toBeGreaterThan(readsBefore)); await waitFor(() => expect(headerCtaLabels()).not.toContain('Resolve')); - await waitFor(() => expect(currentStages()).toContain('Resolved, current stage')); + await waitFor(() => expect(currentStages()).toContain('Resolved')); await waitFor(() => expect(openList()).toEqual([OTHER_ID])); }); diff --git a/ui/packages/components/src/__tests__/page-header-stage-tag-35891.test.tsx b/ui/packages/components/src/__tests__/page-header-stage-tag-35891.test.tsx new file mode 100644 index 00000000000..c80b68f6e09 --- /dev/null +++ b/ui/packages/components/src/__tests__/page-header-stage-tag-35891.test.tsx @@ -0,0 +1,141 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35891 — the default record page draws no stage bar, so the + * header's stage tag is where the stage is read and moved: + * + * - a host's `RecordHeaderState.stage` gets the tag the header would draw (its + * field, its label, the tag itself) and draws what it returns in its place, + * in the host bar and in the header's own row; + * - without a host bar (a phone, a page with no top bar) the tag now sits in + * the row under the record's name, beside the state's tags — before, only + * the bar drew it, so a phone showed no stage at all; + * - without `stage` the tag is the plain readout. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, cleanup, waitFor } from '@testing-library/react'; +import { ComponentRegistry } from '@object-ui/core'; +import { ActionProvider, RecordContextProvider } from '@object-ui/react'; +import '../renderers'; +import '@object-ui/react-runtime'; +import { + RecordHeaderBarContext, + RecordHeaderStateContext, + type RecordHeaderStageParts, + type RecordHeaderState, +} from '../renderers/layout/record-header-bar-context'; + +afterEach(() => cleanup()); + +function PageHeader({ schema }: { schema: any }) { + const Component = ComponentRegistry.get('page:header'); + if (!Component) throw new Error('page:header not registered'); + // eslint-disable-next-line react-hooks/static-components -- ComponentRegistry.get returns a registered component (stable), not one created during render + return ; +} + +const DEAL = { id: 'opp-1', name: 'Wayne Enterprise License', stage: 'negotiation' }; +const DEAL_SCHEMA = { + name: 'crm_opportunity', + label: 'Opportunity', + stageField: 'stage', + fields: { + name: { type: 'text', label: 'Name' }, + stage: { + type: 'select', + label: 'Stage', + options: [ + { value: 'prospecting', label: 'Prospecting' }, + { value: 'negotiation', label: 'Negotiation' }, + ], + }, + }, +}; + +function BarHost({ children }: { children: React.ReactNode }) { + const [titleSlot, setTitleSlot] = React.useState(null); + const [actionSlot, setActionSlot] = React.useState(null); + const claim = React.useCallback(() => {}, []); + const bar = React.useMemo(() => ({ titleSlot, actionSlot, claim }), [titleSlot, actionSlot, claim]); + return ( + <> + + + {children} + + ); +} + +function renderHeader({ bar = false, state }: { bar?: boolean; state?: RecordHeaderState } = {}) { + const header = ( + + + + + + + + ); + return render(bar ? {header} : header); +} + +describe('the header stage tag (objectstack#35891)', () => { + it('without a host bar the stage tag sits under the record name, before the state tags', async () => { + renderHeader({ state: { tags: 审批中 } }); + await waitFor(() => expect(document.querySelector('[data-record-header-tags]')).toBeTruthy()); + const row = document.querySelector('[data-record-header-tags]')!; + expect(row.querySelector('[data-record-stage-tag="stage"]')?.textContent).toBe('Negotiation'); + expect(row.firstElementChild?.getAttribute('data-record-stage-tag')).toBe('stage'); + }); + + it('without a host bar and without state tags the stage tag still draws (a phone shows the stage)', async () => { + renderHeader(); + await waitFor(() => expect(document.querySelector('[data-record-header-tags] [data-record-stage-tag="stage"]')).toBeTruthy()); + }); + + it('a host stage gets the field, the label and the plain tag, and draws in its place (no bar)', async () => { + const seen: RecordHeaderStageParts[] = []; + const stage = vi.fn((parts: RecordHeaderStageParts) => { + seen.push(parts); + return ; + }); + renderHeader({ state: { stage } }); + await waitFor(() => expect(screen.getByTestId('stage-menu')).toBeTruthy()); + const last = seen[seen.length - 1]; + expect(last.field).toBe('stage'); + expect(last.label).toBe('Negotiation'); + expect(last.tag).toBeTruthy(); + // The plain tag is not drawn beside the host's control. + expect(document.querySelector('[data-record-header-tags] span[data-record-stage-tag]')).toBeNull(); + }); + + it('a host stage draws in the host bar\'s title slot too', async () => { + renderHeader({ bar: true, state: { stage: (parts) => } }); + const titleSlot = screen.getByTestId('title-slot'); + await waitFor(() => expect(titleSlot.querySelector('[data-testid="stage-menu"]')?.textContent).toBe('Negotiation')); + }); + + it('control: a record with no stage value draws no tag and never asks the host', async () => { + const stage = vi.fn(() => ); + render( + + + + + + + , + ); + await waitFor(() => expect(screen.getByText('Blank')).toBeTruthy()); + expect(document.querySelector('[data-record-stage-tag]')).toBeNull(); + expect(stage).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/components/src/index.ts b/ui/packages/components/src/index.ts index f029c6e5be5..eb080851399 100644 --- a/ui/packages/components/src/index.ts +++ b/ui/packages/components/src/index.ts @@ -124,7 +124,7 @@ export type { PageHeaderPhoneFace } from './renderers/layout/page-header-phone-c // The record's one-row header (objectstack#35593): the host bar's two slots the // record header draws into, and the record state's tags and button group. export { RecordHeaderBarContext, RecordHeaderStateContext } from './renderers/layout/record-header-bar-context'; -export type { RecordHeaderBar, RecordHeaderGroupParts, RecordHeaderState } from './renderers/layout/record-header-bar-context'; +export type { RecordHeaderBar, RecordHeaderGroupParts, RecordHeaderStageParts, RecordHeaderState } from './renderers/layout/record-header-bar-context'; export type { PageHeaderActionsProps } from './renderers/layout/containers'; // The form's host slots (objectstack#28104, objectstack#28106): the console's // create page names the fields an AI chat draft filled, and the form marks them diff --git a/ui/packages/components/src/renderers/layout/containers.tsx b/ui/packages/components/src/renderers/layout/containers.tsx index c542c310877..7f630a8e5cf 100644 --- a/ui/packages/components/src/renderers/layout/containers.tsx +++ b/ui/packages/components/src/renderers/layout/containers.tsx @@ -63,7 +63,7 @@ import { resolveFieldReadFace } from '../../lib/field-face'; import { PageDescriptionContext } from './page-description-context'; import { PageHeaderTrailingContext } from './page-header-trailing-context'; import { PageHeaderPhoneContext } from './page-header-phone-context'; -import { RecordHeaderBarContext, RecordHeaderStateContext } from './record-header-bar-context'; +import { RecordHeaderBarContext, RecordHeaderStateContext, type RecordHeaderState } from './record-header-bar-context'; import { renderBlockChildren } from './page-block-grid'; import { isFileIdToken } from '@objectstack/spec/data'; import { readActionEntryParamValues } from '../action/static-params'; @@ -3015,10 +3015,19 @@ function disableRecordChromeOf(schema: any): boolean { /** * The record's current stage as a short tag (objectstack#35593): the option * label of the object's stage field (`detectStatusField`, the field - * `record:path` steps through) on this record. A field with no options, or no - * value on the record, draws nothing. + * `record:path` steps through, or a plain status field) on this record. A + * field with no options, or no value on the record, draws nothing. + * + * The tag is where the stage is read and moved (objectstack#35891: the default + * record page draws no stage bar). A host that can move the stage hands + * `RecordHeaderState.stage`, which draws the tag as its menu; without one the + * tag is a readout. */ -function recordStageTag(objSchema: any, labelledData: any): React.ReactNode { +function recordStageTag( + objSchema: any, + labelledData: any, + stage: RecordHeaderState['stage'], +): React.ReactNode { const stageField = detectStatusField(objSchema); if (!stageField) return null; const options = (declaredFieldDef(objSchema, stageField) as any)?.options; @@ -3026,7 +3035,7 @@ function recordStageTag(objSchema: any, labelledData: any): React.ReactNode { const raw = labelledData?.[stageField]; const text = typeof raw === 'string' ? raw.trim() : typeof raw === 'number' ? String(raw) : ''; if (!text) return null; - return ( + const tag = ( ); + return stage ? stage({ field: stageField, label: text, tag }) : tag; } const PageHeaderRenderer: React.FC = ({ schema, className, ...props }) => { @@ -3080,7 +3090,8 @@ const PageHeaderRenderer: React.FC = ({ schema, className, ...props }) => { const phoneFace = React.useContext(PageHeaderPhoneContext); // The host's one-row bar (objectstack#35593) and the record state's tags. const headerBar = React.useContext(RecordHeaderBarContext); - const headerStateTags = React.useContext(RecordHeaderStateContext)?.tags; + const headerState = React.useContext(RecordHeaderStateContext); + const headerStateTags = headerState?.tags; const headerObjectSchema: any = (ctx as any)?.objectSchema; const headerObjectName: string | undefined = ctx?.objectName || headerObjectSchema?.name; const explicitTitle = interpolate( @@ -3248,6 +3259,7 @@ const PageHeaderRenderer: React.FC = ({ schema, className, ...props }) => { // (objectui#13103): a select `nameField` heads the page with its option // label, exactly as the same field does through the template. const labelledData = withOptionLabels(data, objSchema, fieldOptionLabel, rawObjectName); + const stageTag = recordStageTag(objSchema, labelledData, headerState?.stage); const interpolatedTitleFormat = formatTitleTemplate(objSchema?.titleFormat, labelledData); // Unified resolver (ADR-0079): honours the object's declared // `nameField`/`displayNameField` and falls back to type-aware field @@ -3483,7 +3495,7 @@ const PageHeaderRenderer: React.FC = ({ schema, className, ...props }) => { } className="text-foreground [&_h1]:text-sm [&_h1]:font-semibold [&_h1]:sm:text-sm [&>div]:flex-nowrap [&>div]:items-center" /> - {recordStageTag(objSchema, labelledData)} + {stageTag} {headerStateTags} , headerBar.titleSlot, @@ -3526,9 +3538,12 @@ const PageHeaderRenderer: React.FC = ({ schema, className, ...props }) => { } /> {/* objectstack#35593 — the record state's tags (an approval's - status) where no host bar takes the record's header. */} - {headerStateTags && ( + status) where no host bar takes the record's header; with them + the stage tag (objectstack#35891), which a phone otherwise never + showed once the default page stopped drawing the stage bar. */} + {(stageTag || headerStateTags) && (
+ {stageTag} {headerStateTags}
)} diff --git a/ui/packages/components/src/renderers/layout/record-header-bar-context.ts b/ui/packages/components/src/renderers/layout/record-header-bar-context.ts index 52195024835..c220fde2d2c 100644 --- a/ui/packages/components/src/renderers/layout/record-header-bar-context.ts +++ b/ui/packages/components/src/renderers/layout/record-header-bar-context.ts @@ -72,6 +72,25 @@ export interface RecordHeaderGroupParts { export interface RecordHeaderState { tags?: React.ReactNode; group?: (parts: RecordHeaderGroupParts) => React.ReactNode; + /** + * The record's stage tag (objectstack#35891): called with the tag the + * header draws for the object's stage field, it returns what the header + * draws in its place — the tag as a menu that moves the record to another + * stage, for a reader who may. Absent: the tag as it is. + */ + stage?: (parts: RecordHeaderStageParts) => React.ReactNode; +} + +/** + * What the header hands a host's `stage` (objectstack#35891). + */ +export interface RecordHeaderStageParts { + /** The stage field the tag reads (`detectStatusField`). */ + field: string; + /** The current stage's option label, as the tag shows it. */ + label: string; + /** The tag exactly as the header draws it without a host. */ + tag: React.ReactNode; } export const RecordHeaderStateContext = React.createContext(null); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 0e5533d0853..f1d8f9e0668 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1642,6 +1642,10 @@ const ar = { pathStageChangeConflict: 'قام شخص آخر بتغيير هذا السجل، ويتم الآن عرض أحدث إصدار. اضغط على المرحلة مرة أخرى إذا كان النقل لا يزال مطلوبًا.', pathStageChangeDenied: 'ليس لديك إذن لتغيير مرحلة هذا السجل.', pathStageChangeFailed: 'تعذر تغيير المرحلة.', + stageMenuTrigger: 'المرحلة: {{stage}}. تغيير المرحلة', + stageMenuCurrent: 'المرحلة الحالية', + stageMenuNotReachable: 'لا يمكن الانتقال إلى هنا من {{stage}}', + stageMenuFieldsDescription: 'لنقل هذا السجل إلى {{stage}}، املأ ما يلي:', linkCopied: "تم نسخ الرابط إلى الحافظة", commentFailed: "لم يُنشر تعليقك. لم يُحفظ أي شيء — يُرجى المحاولة مرة أخرى.", reactionFailed: "لم يُحفظ تفاعلك. يُرجى المحاولة مرة أخرى.", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 524e145960f..f7bcee4ecdb 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1468,6 +1468,10 @@ const de = { pathStageChangeConflict: 'Jemand anderes hat diesen Datensatz geändert; die aktuelle Version wird jetzt angezeigt. Klicken Sie erneut auf die Phase, wenn die Verschiebung weiterhin gilt.', pathStageChangeDenied: 'Sie sind nicht berechtigt, die Phase dieses Datensatzes zu ändern.', pathStageChangeFailed: 'Die Phase konnte nicht geändert werden.', + stageMenuTrigger: 'Phase: {{stage}}. Phase ändern', + stageMenuCurrent: 'aktuelle Phase', + stageMenuNotReachable: 'Von {{stage}} nicht hierher verschiebbar', + stageMenuFieldsDescription: 'Um diesen Datensatz zu {{stage}} zu verschieben, bitte ausfüllen:', linkCopied: "Link in die Zwischenablage kopiert", commentFailed: "Ihr Kommentar wurde nicht veröffentlicht. Es wurde nichts gespeichert – bitte versuchen Sie es erneut.", reactionFailed: "Ihre Reaktion wurde nicht gespeichert. Bitte versuchen Sie es erneut.", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index d849fe57db8..9f7ec580d44 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1607,6 +1607,10 @@ const en = { pathStageChangeConflict: 'Someone else changed this record, and the latest version is now shown. Press the stage again if the move still applies.', pathStageChangeDenied: "You don't have permission to change this record's stage.", pathStageChangeFailed: 'The stage could not be changed.', + stageMenuTrigger: 'Stage: {{stage}}. Change stage', + stageMenuCurrent: 'current stage', + stageMenuNotReachable: "Can't move here from {{stage}}", + stageMenuFieldsDescription: 'To move this record to {{stage}}, fill in:', linkCopied: 'Link copied to clipboard', commentFailed: 'Your comment was not posted. Nothing was saved — please try again.', reactionFailed: 'Your reaction was not saved. Please try again.', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 0501f14d953..bd8288d7ba7 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1513,6 +1513,10 @@ const es = { pathStageChangeConflict: 'Otra persona ha modificado este registro y ahora se muestra la versión más reciente. Vuelve a pulsar la etapa si el cambio sigue siendo válido.', pathStageChangeDenied: 'No tienes permiso para cambiar la etapa de este registro.', pathStageChangeFailed: 'No se ha podido cambiar la etapa.', + stageMenuTrigger: 'Etapa: {{stage}}. Cambiar etapa', + stageMenuCurrent: 'etapa actual', + stageMenuNotReachable: 'No se puede pasar aquí desde {{stage}}', + stageMenuFieldsDescription: 'Para mover este registro a {{stage}}, completa:', linkCopied: "Enlace copiado al portapapeles", commentFailed: "Tu comentario no se ha publicado. No se ha guardado nada; inténtalo de nuevo.", reactionFailed: "Tu reacción no se ha guardado. Inténtalo de nuevo.", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index d1c21ddfbfc..29a88044771 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1510,6 +1510,10 @@ const fr = { pathStageChangeConflict: "Quelqu'un d'autre a modifié cet enregistrement ; la dernière version est maintenant affichée. Cliquez à nouveau sur l'étape si le changement s'applique toujours.", pathStageChangeDenied: "Vous n'avez pas l'autorisation de modifier l'étape de cet enregistrement.", pathStageChangeFailed: "L'étape n'a pas pu être modifiée.", + stageMenuTrigger: "Étape : {{stage}}. Changer d'étape", + stageMenuCurrent: 'étape actuelle', + stageMenuNotReachable: 'Impossible de passer ici depuis {{stage}}', + stageMenuFieldsDescription: 'Pour faire passer cet enregistrement à {{stage}}, renseignez :', linkCopied: "Lien copié dans le presse-papiers", commentFailed: "Votre commentaire n'a pas été publié. Rien n'a été enregistré — veuillez réessayer.", reactionFailed: "Votre réaction n'a pas été enregistrée. Veuillez réessayer.", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index afb9452b692..2c6f03125cb 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1549,6 +1549,10 @@ const ja = { pathStageChangeConflict: '他のユーザーがこのレコードを変更したため、最新の内容を表示しています。移動が必要な場合は、もう一度ステージを押してください。', pathStageChangeDenied: 'このレコードのステージを変更する権限がありません。', pathStageChangeFailed: 'ステージを変更できませんでした。', + stageMenuTrigger: 'ステージ:{{stage}}。ステージを変更', + stageMenuCurrent: '現在のステージ', + stageMenuNotReachable: '{{stage}}からここへは移動できません', + stageMenuFieldsDescription: '{{stage}}に移動するには、次を入力してください:', linkCopied: "リンクをクリップボードにコピーしました", commentFailed: "コメントを投稿できませんでした。何も保存されていません。もう一度お試しください。", reactionFailed: "リアクションが保存されませんでした。もう一度お試しください。", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 5f81fd6a437..687e8bc5e78 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1468,6 +1468,10 @@ const ko = { pathStageChangeConflict: '다른 사용자가 이 레코드를 변경하여 최신 버전을 표시합니다. 이동이 여전히 필요하면 단계를 다시 누르세요.', pathStageChangeDenied: '이 레코드의 단계를 변경할 권한이 없습니다.', pathStageChangeFailed: '단계를 변경할 수 없습니다.', + stageMenuTrigger: '단계: {{stage}}. 단계 변경', + stageMenuCurrent: '현재 단계', + stageMenuNotReachable: '{{stage}}에서 여기로 이동할 수 없습니다', + stageMenuFieldsDescription: '{{stage}}(으)로 이동하려면 다음을 입력하세요:', linkCopied: "링크가 클립보드에 복사됨", commentFailed: "댓글이 게시되지 않았습니다. 아무것도 저장되지 않았습니다. 다시 시도해 주세요.", reactionFailed: "반응이 저장되지 않았습니다. 다시 시도해 주세요.", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 3b714b36e82..784338c74aa 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1510,6 +1510,10 @@ const pt = { pathStageChangeConflict: 'Outra pessoa alterou este registro, e a versão mais recente está sendo exibida. Pressione a etapa novamente se a mudança ainda se aplicar.', pathStageChangeDenied: 'Você não tem permissão para alterar a etapa deste registro.', pathStageChangeFailed: 'Não foi possível alterar a etapa.', + stageMenuTrigger: 'Etapa: {{stage}}. Alterar etapa', + stageMenuCurrent: 'etapa atual', + stageMenuNotReachable: 'Não é possível ir para cá a partir de {{stage}}', + stageMenuFieldsDescription: 'Para mover este registro para {{stage}}, preencha:', linkCopied: "Link copiado para a área de transferência", commentFailed: "Seu comentário não foi publicado. Nada foi salvo — tente novamente.", reactionFailed: "Sua reação não foi salva. Tente novamente.", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 4affd4f3167..307bcdb6ca3 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1654,6 +1654,10 @@ const ru = { pathStageChangeConflict: 'Запись изменил другой пользователь, теперь показана последняя версия. Нажмите на этап ещё раз, если перевод всё ещё нужен.', pathStageChangeDenied: 'У вас нет прав на смену этапа этой записи.', pathStageChangeFailed: 'Не удалось сменить этап.', + stageMenuTrigger: 'Этап: «{{stage}}». Сменить этап', + stageMenuCurrent: 'текущий этап', + stageMenuNotReachable: 'Сюда нельзя перейти с этапа «{{stage}}»', + stageMenuFieldsDescription: 'Чтобы перевести запись на этап «{{stage}}», заполните:', linkCopied: "Ссылка скопирована в буфер обмена", commentFailed: "Комментарий не опубликован. Ничего не сохранено — попробуйте ещё раз.", reactionFailed: "Реакция не сохранена. Попробуйте ещё раз.", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 20224f7d44e..38495339b18 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1334,6 +1334,10 @@ const zh = { pathStageChangeConflict: '其他人已修改此记录,现已显示最新版本。如仍需移动,请再次点击该阶段。', pathStageChangeDenied: '你没有更改此记录阶段的权限。', pathStageChangeFailed: '无法更改阶段。', + stageMenuTrigger: '阶段:{{stage}},更改阶段', + stageMenuCurrent: '当前阶段', + stageMenuNotReachable: '流转规则不允许从{{stage}}直接改到这里', + stageMenuFieldsDescription: '改为{{stage}}前,请先填写:', linkCopied: '链接已复制到剪贴板', commentFailed: '评论未发布,内容没有保存,请重试。', reactionFailed: '表情回应未保存,请重试。', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index abd7c3573ae..4fe445f0480 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1334,6 +1334,10 @@ const zhHant = { pathStageChangeConflict: '其他人已修改此記錄,現已顯示最新版本。如仍需移動,請再次點選該階段。', pathStageChangeDenied: '你沒有更改此記錄階段的權限。', pathStageChangeFailed: '無法更改階段。', + stageMenuTrigger: '階段:{{stage}},更改階段', + stageMenuCurrent: '當前階段', + stageMenuNotReachable: '流轉規則不允許從{{stage}}直接改到這裡', + stageMenuFieldsDescription: '改為{{stage}}前,請先填寫:', linkCopied: '連結已複製到剪貼簿', commentFailed: '評論未釋出,內容沒有儲存,請重試。', reactionFailed: '表情回應未儲存,請重試。', diff --git a/ui/packages/plugin-detail/src/RecordPageColumns.tsx b/ui/packages/plugin-detail/src/RecordPageColumns.tsx index 93e1fe9249b..091f8a3871c 100644 --- a/ui/packages/plugin-detail/src/RecordPageColumns.tsx +++ b/ui/packages/plugin-detail/src/RecordPageColumns.tsx @@ -318,8 +318,10 @@ const COLUMN_STACK = 'flex min-w-0 flex-col gap-4 [&>*:has(>[hidden]:only-child) * there at first paint, an empty list muted with no number, the width the * row's only fold), then the open tab's face. * - * 概览 draws the strip (`record:path`, `record:highlights`) across the whole - * width, then the details and the right rail — the summary of the other tabs + * 概览 draws a strip the page places (`record:path`, `record:highlights`, a + * slotted page's `highlights`; the default page places none since + * objectstack#35891) across the whole width, then the details and the right + * rail — the summary of the other tabs * (`RecordSummaryRail`, objectstack#35596: 审批, 附件, 最近动态, then the * lists with records; a card with nothing to show is not drawn, and a rail * known to have none folds away). Every other tab draws its block in full in diff --git a/ui/packages/plugin-detail/src/RecordStageMenu.tsx b/ui/packages/plugin-detail/src/RecordStageMenu.tsx new file mode 100644 index 00000000000..4d36ab0d8d3 --- /dev/null +++ b/ui/packages/plugin-detail/src/RecordStageMenu.tsx @@ -0,0 +1,147 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * The record header's stage tag as a menu (objectstack#35891). + * + * The default record page draws no stage bar (the maintainer, 2026-11-20: + * 「把阶段条和关键字段条去掉」): the stage is the status tag beside the record's + * name, and the tag is where it moves. A host hands this component to the + * header as `RecordHeaderState.stage`; the header calls it with the tag it + * would draw. + * + * - A reader who may move the stage sees the tag with a small arrow; it opens + * a menu listing every stage in order, the current one checked. A reader who + * may not (no edit right on the field, a read-only or computed field, an + * approval lock, an open draft) sees the tag alone: the same verdict + * `record:path`'s press asks (`useStageChange`). + * - A stage the field's blocking `state_machine` cannot reach from the stored + * value is drawn disabled, with the reason under its name. + * - Picking a stage opens the stage confirmation. A stage that needs other + * fields filled first asks for exactly those fields in the same dialog and + * writes them with the move; a refusal is shown in the dialog and the stage + * does not move (`collectFields`, see `recordPathStageChange.tsx`). + * - The menu is Radix's: Enter or Space on the focused tag opens it, the arrow + * keys move, Enter picks, Esc closes without a change. + * + * The stages are the ones `record:path` offers: the field's options, less + * those whose `visibleWhen` rules this record out (`stagesThisRecordWalks`). + * A plain status field (no stage role) is read and moved the same way. + */ + +import React from 'react'; +import { Check, ChevronDown } from 'lucide-react'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuTrigger, + cn, + type RecordHeaderStageParts, +} from '@object-ui/components'; +import { useRecordContext, useSafeFieldLabel } from '@object-ui/react'; +import { pickLocalized, useObjectTranslation } from '@object-ui/i18n'; +import { RecordFieldAccessForRecord } from './recordFieldAccess'; +import { useStageChange } from './renderers/recordPathStageChange'; +import { stagesThisRecordWalks, type PathStage } from './renderers/record-path'; +import { deriveStages } from './synth/buildDefaultPageSchema'; +import { useDetailTranslation } from './useDetailTranslation'; + +export type RecordStageMenuProps = RecordHeaderStageParts; + +/** + * The tag as a menu, inside the row-scoped field-access scope the record + * page's other in-place editors mount, so the field's edit right is asked of + * THIS stored row. + */ +export const RecordStageMenu: React.FC = (props) => { + const ctx = useRecordContext(); + return ( + + + + ); +}; + +const RecordStageMenuBody: React.FC = ({ field, label, tag }) => { + const ctx = useRecordContext(); + const { t } = useDetailTranslation(); + const { language } = useObjectTranslation(); + const { fieldOptionLabel } = useSafeFieldLabel(); + const change = useStageChange(true, field, { collectFields: true }); + + const record = ctx?.data as Record | undefined; + const current = record?.[field]; + const objectName = ctx?.objectName; + const objectSchema = ctx?.objectSchema as { fields?: Record } | undefined; + const stages: PathStage[] = React.useMemo(() => { + const derived = (deriveStages(objectSchema as any, field) ?? []) as PathStage[]; + const walked = stagesThisRecordWalks(derived, objectSchema?.fields?.[field]?.options, record, current); + return walked.map((stage) => { + const authored = pickLocalized(stage.label as any, language) ?? String(stage.value); + const text = objectName ? fieldOptionLabel(objectName, field, String(stage.value), String(authored)) : String(authored); + return { ...stage, label: text }; + }); + }, [objectSchema, field, record, current, language, objectName, fieldOptionLabel]); + + if (!change.pressable || stages.length === 0) return <>{tag}; + + return ( + <> + + + {label} + + + {stages.map((stage) => { + const isCurrent = current != null && String(stage.value) === String(current); + const reachable = isCurrent || change.admits(stage.value); + return ( + { + if (!isCurrent) change.request({ value: stage.value, label: stage.label }); + }} + className="items-start gap-2" + > + + + + {stage.label} + {isCurrent ? {`, ${t('detail.stageMenuCurrent')}`} : null} + + {!reachable ? ( + + {t('detail.stageMenuNotReachable', { stage: label })} + + ) : null} + + + ); + })} + + + {change.dialog} + + ); +}; diff --git a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx index cbb0ea41891..0404cceabba 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.test.tsx @@ -61,7 +61,7 @@ vi.mock('@object-ui/react', async (importOriginal) => { import { RecordPageColumns } from '../RecordPageColumns'; import { buildDefaultPageColumns } from '../synth/recordPageColumns'; -import { buildDefaultPageSchema } from '../synth/buildDefaultPageSchema'; +import { buildDefaultHighlights, buildDefaultPageSchema } from '../synth/buildDefaultPageSchema'; import { DetailView } from '../DetailView'; import { InlineEditProvider } from '@object-ui/react'; @@ -313,16 +313,20 @@ describe('RecordPageColumns — the rail: 审批, 附件, 最近动态, 其他 }); it('the rail is the 概览 tab\'s: another tab open draws none, and the strip leaves with it', async () => { + // A slotted page placing the strip: the default page draws none since + // objectstack#35891, and the columns still draw a placed one on 概览. + const lead = { name: 'lead', fields: { name: { type: 'text' }, email: { type: 'email' }, rating: { type: 'select' } } } as any; const cols = buildDefaultPageColumns( - buildDefaultPageSchema( - { name: 'lead', fields: { name: { type: 'text' }, email: { type: 'email' }, rating: { type: 'select' } } } as any, - { - related: relatedLists, - highlightFields: ['email'], - statusField: 'rating', - stages: [{ value: 'hot', label: 'Hot' }], + buildDefaultPageSchema(lead, { + related: relatedLists, + slots: { + highlights: buildDefaultHighlights(lead, { + highlightFields: ['email'], + statusField: 'rating', + stages: [{ value: 'hot', label: 'Hot' }], + }), }, - ), + }), )!; expect(cols.strip.length).toBeGreaterThan(0); const overview = drawPage('wide', cols, { onEnlargeRelated: vi.fn() }); diff --git a/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx new file mode 100644 index 00000000000..4d0be9ed54f --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx @@ -0,0 +1,334 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * objectstack#35891 — the record header's stage tag is the stage's menu. + * + * - A reader who may move the stage gets the tag with an arrow; it opens a + * menu of every stage in order, the current one checked. + * - A stage the field's blocking `state_machine` cannot reach is disabled and + * says why under its name. + * - Picking a stage confirms, then writes the stage through the record update. + * - A stage whose move makes another field required (`requiredWhen`) asks for + * just that field in the same dialog; the move and the value go in one + * write. A refusal is shown in the dialog and nothing else moves. + * - A reader who may not edit (no field grant, a page that may not edit, an + * approval lock) sees the plain tag. + * - The keyboard: Enter on the tag opens, arrows move, Enter picks, Esc closes. + * + * `@object-ui/*` resolves to source through the root vitest alias table. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { render, cleanup, fireEvent, screen, waitFor, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { InlineEditProvider, RecordContextProvider } from '@object-ui/react'; + +const { permsStub, perms } = vi.hoisted(() => { + const perms: { isLoaded: boolean; writeDenied: string[] } = { isLoaded: true, writeDenied: [] }; + return { + perms, + permsStub: { + get isLoaded() { return perms.isLoaded; }, + checkField: (_object: string, field: string, action: string) => + action === 'read' ? true : !perms.writeDenied.includes(field), + check: () => ({ allowed: true }), + getFieldPermissions: () => [], + getRowFilter: () => undefined, + getObjectApiOperations: () => undefined, + roles: [], + userId: null, + systemPermissions: undefined, + hasCapabilities: () => true, + can: () => true, + cannot: () => false, + }, + }; +}); + +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, usePermissions: () => permsStub as any }; +}); + +import { RecordStageMenu } from '../RecordStageMenu'; + +const VERSION = '2026-11-20T12:00:00.000Z'; + +const OPPORTUNITY = { + name: 'crm_opportunity', + fields: { + name: { type: 'text', label: 'Name' }, + stage: { + type: 'select', + label: 'Stage', + options: [ + { value: 'prospecting', label: 'Prospecting' }, + { value: 'negotiation', label: 'Negotiation' }, + { value: 'closed_won', label: 'Closed Won', kind: 'won' }, + { value: 'closed_lost', label: 'Closed Lost', kind: 'lost' }, + ], + }, + loss_reason: { + type: 'text', + label: 'Loss Reason', + requiredWhen: 'has(record.stage) && record.stage == "closed_lost"', + }, + }, + validations: [ + { + type: 'state_machine', + name: 'deal_flow', + field: 'stage', + message: 'A deal cannot skip negotiation.', + transitions: { + prospecting: ['negotiation', 'closed_lost'], + negotiation: ['closed_won', 'closed_lost'], + }, + }, + ], +}; + +function makeDataSource(update: (...args: any[]) => Promise = async () => ({})) { + return { update: vi.fn(update) }; +} + +interface MountOptions { + canEdit?: boolean; + dataSource?: ReturnType; + refresh?: () => Promise; + stage?: string; +} + +function mount(opts: MountOptions = {}) { + const dataSource = opts.dataSource ?? makeDataSource(); + const refresh = opts.refresh ?? vi.fn(async () => {}); + const stage = opts.stage ?? 'prospecting'; + const label = OPPORTUNITY.fields.stage.options.find((o) => o.value === stage)!.label; + const tag = {label}; + const r = render( + + + + + , + ); + return { ...r, dataSource, refresh }; +} + +const trigger = () => screen.getByRole('button', { name: /^Stage: / }); + +function openMenu() { + fireEvent.pointerDown(trigger(), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + return screen.getByRole('menu'); +} + +const item = (menu: HTMLElement, label: string) => + within(menu).getAllByRole('menuitem').find((el) => el.textContent?.startsWith(label))!; + +beforeEach(() => { + perms.isLoaded = true; + perms.writeDenied = []; +}); + +afterEach(() => cleanup()); + +describe('#35891 the stage tag opens a menu of every stage', () => { + it('lists every stage in order, the current one checked', () => { + mount(); + expect(trigger()).toHaveAttribute('data-record-stage-tag', 'stage'); + expect(trigger()).toHaveAttribute('aria-haspopup', 'menu'); + const menu = openMenu(); + const labels = within(menu).getAllByRole('menuitem').map((el) => el.getAttribute('data-stage-value')); + expect(labels).toEqual(['prospecting', 'negotiation', 'closed_won', 'closed_lost']); + expect(item(menu, 'Prospecting')).toHaveAttribute('aria-current', 'true'); + expect(item(menu, 'Negotiation')).not.toHaveAttribute('aria-current'); + }); + + it('a stage the state machine cannot reach is disabled and says why', () => { + mount(); + const menu = openMenu(); + const won = item(menu, 'Closed Won'); + expect(won).toHaveAttribute('aria-disabled', 'true'); + expect(within(won).getByText("Can't move here from Prospecting")).toBeInTheDocument(); + expect(item(menu, 'Negotiation')).not.toHaveAttribute('aria-disabled'); + }); + + it('picking a reachable stage confirms, then writes the stage with the record version and re-reads', async () => { + const { dataSource, refresh } = mount(); + fireEvent.click(item(openMenu(), 'Negotiation')); + const dialog = await screen.findByRole('alertdialog'); + expect(within(dialog).getByText('Move this record to Negotiation?')).toBeInTheDocument(); + fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); + await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1)); + expect(dataSource.update).toHaveBeenCalledWith('crm_opportunity', 'o1', { stage: 'negotiation' }, { ifMatch: VERSION }); + await waitFor(() => expect(refresh).toHaveBeenCalled()); + await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull()); + }); + + it('cancelling writes nothing', async () => { + const { dataSource } = mount(); + fireEvent.click(item(openMenu(), 'Negotiation')); + const dialog = await screen.findByRole('alertdialog'); + fireEvent.click(within(dialog).getByRole('button', { name: 'Cancel' })); + await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull()); + expect(dataSource.update).not.toHaveBeenCalled(); + }); +}); + +describe('#35891 a stage that needs more fields asks for them', () => { + const lossRefusal = () => Object.assign(new Error('VALIDATION_FAILED'), { + code: 'VALIDATION_FAILED', + fields: [{ field: 'loss_reason', code: 'required', message: 'Loss Reason is required to close as lost' }], + }); + + it('Closed Lost asks for the loss reason only, and writes it with the move', async () => { + const { dataSource } = mount(); + fireEvent.click(item(openMenu(), 'Closed Lost')); + const dialog = await screen.findByRole('alertdialog'); + expect(within(dialog).getByText('To move this record to Closed Lost, fill in:')).toBeInTheDocument(); + const fields = Array.from(dialog.querySelectorAll('[data-stage-change-field]')).map((el) => el.getAttribute('data-stage-change-field')); + expect(fields).toEqual(['loss_reason']); + fireEvent.change(within(dialog).getByRole('textbox'), { target: { value: 'Price' } }); + fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); + await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1)); + expect(dataSource.update).toHaveBeenCalledWith( + 'crm_opportunity', 'o1', { stage: 'closed_lost', loss_reason: 'Price' }, { ifMatch: VERSION }, + ); + await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull()); + }); + + it('left empty, the server refusal names the field in the dialog and the stage does not move', async () => { + const dataSource = makeDataSource(async () => { throw lossRefusal(); }); + const { refresh } = mount({ dataSource }); + fireEvent.click(item(openMenu(), 'Closed Lost')); + const dialog = await screen.findByRole('alertdialog'); + fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); + await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1)); + // Still open, the reason beside the field, nothing re-read. + const open = await screen.findByRole('alertdialog'); + expect(within(open).getByText('Loss Reason is required to close as lost')).toBeInTheDocument(); + expect(open.querySelector('[data-stage-change-field-error="loss_reason"]')).not.toBeNull(); + expect(refresh).not.toHaveBeenCalled(); + }); + + it('a refusal that names a field the menu did not know about adds it to the form', async () => { + const amountRefusal = Object.assign(new Error('VALIDATION_FAILED'), { + code: 'VALIDATION_FAILED', + fields: [{ field: 'name', code: 'required', message: 'Name is required to negotiate' }], + }); + const dataSource = makeDataSource(async () => { throw amountRefusal; }); + mount({ dataSource }); + fireEvent.click(item(openMenu(), 'Negotiation')); + let dialog = await screen.findByRole('alertdialog'); + expect(dialog.querySelector('[data-stage-change-field]')).toBeNull(); + fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); + await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1)); + dialog = await screen.findByRole('alertdialog'); + await waitFor(() => expect(dialog.querySelector('[data-stage-change-field="name"]')).not.toBeNull()); + expect(within(dialog).getByText('Name is required to negotiate')).toBeInTheDocument(); + }); + + it('a refusal that names no fillable field reads under the form, the dialog stays open', async () => { + const machineRefusal = Object.assign(new Error('VALIDATION_FAILED'), { + code: 'VALIDATION_FAILED', + fields: [{ field: 'stage', code: 'state_machine', message: 'A deal cannot skip negotiation.' }], + }); + const dataSource = makeDataSource(async () => { throw machineRefusal; }); + mount({ dataSource }); + fireEvent.click(item(openMenu(), 'Negotiation')); + const dialog = await screen.findByRole('alertdialog'); + fireEvent.click(within(dialog).getByRole('button', { name: 'Move' })); + await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1)); + const open = await screen.findByRole('alertdialog'); + await waitFor(() => expect(within(open).getByText('A deal cannot skip negotiation.')).toBeInTheDocument()); + }); +}); + +describe('#35891 who sees the plain tag', () => { + it('a reader the page may not let edit (an approval lock included) sees the tag, no arrow', () => { + mount({ canEdit: false }); + expect(screen.getByTestId('plain-tag')).toHaveTextContent('Prospecting'); + expect(screen.queryByRole('button', { name: /^Stage: / })).toBeNull(); + }); + + it('a reader without the edit grant on the stage field sees the tag', () => { + perms.writeDenied = ['stage']; + mount(); + expect(screen.getByTestId('plain-tag')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /^Stage: / })).toBeNull(); + }); + + it('control: with the grant, the arrowed menu replaces the tag', () => { + mount(); + expect(screen.queryByTestId('plain-tag')).toBeNull(); + expect(trigger()).toHaveTextContent('Prospecting'); + }); +}); + +describe('#35891 the keyboard', () => { + it('Enter opens the menu; Escape closes it without a write', async () => { + const { dataSource } = mount(); + trigger().focus(); + fireEvent.keyDown(trigger(), { key: 'Enter' }); + const menu = await screen.findByRole('menu'); + expect(menu).toBeInTheDocument(); + fireEvent.keyDown(menu, { key: 'Escape' }); + await waitFor(() => expect(screen.queryByRole('menu')).toBeNull()); + expect(dataSource.update).not.toHaveBeenCalled(); + }); + + it('the confirm dialog opens on Move, so Enter confirms the stage it names', async () => { + mount(); + fireEvent.click(item(openMenu(), 'Negotiation')); + const dialog = await screen.findByRole('alertdialog'); + await waitFor(() => expect(within(dialog).getByRole('button', { name: 'Move' })).toHaveFocus()); + }); + + it('a stage that needs a field opens with that field focused', async () => { + mount(); + fireEvent.click(item(openMenu(), 'Closed Lost')); + const dialog = await screen.findByRole('alertdialog'); + await waitFor(() => expect(within(dialog).getByRole('textbox')).toHaveFocus()); + }); + + it('control: the record:path dialog keeps the alert dialog default, Cancel first', async () => { + const { useStageChange } = await import('../renderers/recordPathStageChange'); + function PathHost() { + const change = useStageChange(true, 'stage'); + return ( + <> + + {change.dialog} + + ); + } + render( + + + + + , + ); + fireEvent.click(screen.getByRole('button', { name: 'go' })); + const dialog = await screen.findByRole('alertdialog'); + await waitFor(() => expect(within(dialog).getByRole('button', { name: 'Cancel' })).toHaveFocus()); + }); +}); diff --git a/ui/packages/plugin-detail/src/index.tsx b/ui/packages/plugin-detail/src/index.tsx index 151a862996c..7ec4a77c5e2 100644 --- a/ui/packages/plugin-detail/src/index.tsx +++ b/ui/packages/plugin-detail/src/index.tsx @@ -102,6 +102,10 @@ export type { SysActivityRow } from './renderers/recordActivityFeed'; export { RecordDetailDrawer, deriveRecordPageHref } from './RecordDetailDrawer'; export type { RecordDetailDrawerProps } from './RecordDetailDrawer'; +// objectstack#35891 — the record header's stage tag as a menu that moves the +// stage; a host hands it to the header as `RecordHeaderState.stage`. +export { RecordStageMenu } from './RecordStageMenu'; +export type { RecordStageMenuProps } from './RecordStageMenu'; /** * The record overlay PAYLOAD, with no shell of its own (objectui#9299). * diff --git a/ui/packages/plugin-detail/src/renderers/__tests__/record-highlights.groupGate-12720.test.tsx b/ui/packages/plugin-detail/src/renderers/__tests__/record-highlights.groupGate-12720.test.tsx index aa6cb626fe7..6da35d0513a 100644 --- a/ui/packages/plugin-detail/src/renderers/__tests__/record-highlights.groupGate-12720.test.tsx +++ b/ui/packages/plugin-detail/src/renderers/__tests__/record-highlights.groupGate-12720.test.tsx @@ -40,7 +40,7 @@ import * as React from 'react'; import { HighlightFieldsProvider, RecordContextProvider } from '@object-ui/react'; import { RecordDetailsRenderer } from '../record-details'; import { RecordHighlightsRenderer } from '../record-highlights'; -import { buildDefaultPageSchema } from '../../synth/buildDefaultPageSchema'; +import { buildDefaultHighlights, buildDefaultPageSchema } from '../../synth/buildDefaultPageSchema'; const OBJECT = 'recheck_gate'; const GATE = "record.kind == 'pro'"; @@ -95,7 +95,9 @@ function nodeOfType(node: any, type: string): any { function renderSynthesizedPage(objectSchema: any, data: Record) { const page = buildDefaultPageSchema(objectSchema); - const strip = nodeOfType(page, 'record:highlights'); + // The strip the sub-builder emits for a page that places one (the default + // page draws none since objectstack#35891). + const strip = nodeOfType(buildDefaultHighlights(objectSchema), 'record:highlights'); const details = nodeOfType(page, 'record:details'); if (!strip || !details) throw new Error('HARNESS DEAD: the synthesized page lost a node'); const dataSource = { getObjectSchema: async () => objectSchema }; diff --git a/ui/packages/plugin-detail/src/renderers/__tests__/record-path.stageChange-28199.test.tsx b/ui/packages/plugin-detail/src/renderers/__tests__/record-path.stageChange-28199.test.tsx index c91e35d628d..542ab1f0ecc 100644 --- a/ui/packages/plugin-detail/src/renderers/__tests__/record-path.stageChange-28199.test.tsx +++ b/ui/packages/plugin-detail/src/renderers/__tests__/record-path.stageChange-28199.test.tsx @@ -12,8 +12,9 @@ * field — and every path that does not opt in — keeps the readout. * * The last two groups pin objectstack#30075 (ruling: option A): the - * synthesized default record page's path carries the opt-in, mounted here as - * the JSON document `buildDefaultPageSchema` emits, through the real + * synthesized strip's path carries the opt-in (since objectstack#35891 the + * default page places no strip itself; a slotted page places this one), + * mounted here as the JSON document `buildDefaultPageSchema` emits, through the real * `SchemaRenderer`; an authored `highlights` slot keeps its declared value; * and a stage the field's blocking `state_machine` cannot reach from the * stored value is never offered as a press. @@ -56,7 +57,7 @@ vi.mock('@object-ui/permissions', async (importOriginal) => { }); import { RecordPathRenderer } from '../record-path'; -import { buildDefaultPageSchema } from '../../synth/buildDefaultPageSchema'; +import { buildDefaultHighlights, buildDefaultPageSchema } from '../../synth/buildDefaultPageSchema'; // Registers `record:path` for the `SchemaRenderer` mounts below. import '../../index'; @@ -307,6 +308,14 @@ const MACHINE = { transitions: { draft: ['in_review', 'declined'], in_review: ['accepted', 'declined'] }, }; +/** + * A slotted page placing the default strip (`buildDefaultHighlights` into the + * `highlights` slot). Since objectstack#35891 the default page draws no strip + * of its own; the sub-builder's path, which these pins read, is unchanged. + */ +const stripPage = (def: unknown): any => + buildDefaultPageSchema(def as never, { slots: { highlights: buildDefaultHighlights(def as never) } } as never); + /** Every `record:path` node among a synthesized page's top-level components. */ const pathNodesOf = (page: any): any[] => page.regions[0].components.filter((c: any) => c?.type === 'record:path'); @@ -334,14 +343,14 @@ function mountNode(node: unknown, opts: Omit = const buttonNames = (row: HTMLElement): (string | null)[] => within(row).queryAllByRole('button').map((b) => b.getAttribute('aria-label')); -describe('#30075 the default record page turns click-to-advance on', () => { - it('the synthesized page writes allowStageChange: true on its path node', () => { - const [path] = pathNodesOf(buildDefaultPageSchema(QUOTE_DEF as never)); +describe('#30075 the synthesized strip turns click-to-advance on', () => { + it('the synthesized strip writes allowStageChange: true on its path node', () => { + const [path] = pathNodesOf(stripPage(QUOTE_DEF)); expect(path.properties).toMatchObject({ statusField: 'status', allowStageChange: true }); }); it('a reader who may edit the stage field gets a press, with a confirmation, through the record update', async () => { - const [path] = pathNodesOf(buildDefaultPageSchema(QUOTE_DEF as never)); + const [path] = pathNodesOf(stripPage(QUOTE_DEF)); const { container, dataSource, refresh } = mountNode(path); expect(rows(container)).toHaveLength(2); for (const row of rows(container)) { @@ -358,7 +367,7 @@ describe('#30075 the default record page turns click-to-advance on', () => { }); it('a reader the page may not let edit this record keeps the read-only path', () => { - const [path] = pathNodesOf(buildDefaultPageSchema(QUOTE_DEF as never)); + const [path] = pathNodesOf(stripPage(QUOTE_DEF)); const { container } = mountNode(path, { canEdit: false }); expect(rows(container)).toHaveLength(2); for (const row of rows(container)) expect(row.querySelectorAll('button,[tabindex]')).toHaveLength(0); @@ -366,7 +375,7 @@ describe('#30075 the default record page turns click-to-advance on', () => { it('a reader without the edit grant on the stage field keeps the read-only path', () => { perms.writeDenied = ['status']; - const [path] = pathNodesOf(buildDefaultPageSchema(QUOTE_DEF as never)); + const [path] = pathNodesOf(stripPage(QUOTE_DEF)); const { container } = mountNode(path); expect(rows(container)).toHaveLength(2); for (const row of rows(container)) expect(row.querySelectorAll('button,[tabindex]')).toHaveLength(0); @@ -395,7 +404,7 @@ describe('#30075 the press offers only the moves the field\'s state machine admi const MACHINED = { ...QUOTE_DEF, validations: [MACHINE] }; it('a stage the machine cannot reach from the stored value is a readout, not a button', () => { - const [path] = pathNodesOf(buildDefaultPageSchema(MACHINED as never)); + const [path] = pathNodesOf(stripPage(MACHINED)); const { container } = mountNode(path, { objectSchema: MACHINED }); for (const row of rows(container)) { expect(buttonNames(row)).toEqual(['Move to In review', 'Move to Declined']); @@ -406,7 +415,7 @@ describe('#30075 the press offers only the moves the field\'s state machine admi it('control: a warning-severity machine does not narrow the press (the server would not refuse)', () => { const warned = { ...QUOTE_DEF, validations: [{ ...MACHINE, severity: 'warning' }] }; - const [path] = pathNodesOf(buildDefaultPageSchema(warned as never)); + const [path] = pathNodesOf(stripPage(warned)); const { container } = mountNode(path, { objectSchema: warned }); expect(buttonNames(rows(container)[0])).toEqual(['Move to In review', 'Move to Accepted', 'Move to Declined']); }); @@ -416,7 +425,7 @@ describe('#30075 the press offers only the moves the field\'s state machine admi code: 'VALIDATION_FAILED', fields: [{ field: 'amount', code: 'required', message: 'is required to send a quote for review' }], }); - const [path] = pathNodesOf(buildDefaultPageSchema(MACHINED as never)); + const [path] = pathNodesOf(stripPage(MACHINED)); const { container, refresh } = mountNode(path, { objectSchema: MACHINED, dataSource: makeDataSource(async () => { throw refusal; }), diff --git a/ui/packages/plugin-detail/src/renderers/record-path.tsx b/ui/packages/plugin-detail/src/renderers/record-path.tsx index f8facc48df8..2c4e2c89948 100644 --- a/ui/packages/plugin-detail/src/renderers/record-path.tsx +++ b/ui/packages/plugin-detail/src/renderers/record-path.tsx @@ -147,7 +147,7 @@ const PHONE_LIST_LABEL_CLASS = 'text-left [overflow-wrap:anywhere]'; type StageState = 'completed' | 'current' | 'upcoming'; -type PathStage = { value: unknown; label: string; terminal?: 'won' | 'lost' }; +export type PathStage = { value: unknown; label: string; terminal?: 'won' | 'lost' }; /** * `stages[].label` is an `I18nLabel` in the spec row @@ -226,8 +226,11 @@ function readsActingUser(pred: FieldRulePredicate): boolean { * * No read is added: the record and its object definition are the ones the * record context already holds. + * + * ⚠️ Package-internal: exported for `RecordStageMenu` (objectstack#35891), + * which offers the same stages; NOT re-exported from the package entry. */ -function stagesThisRecordWalks( +export function stagesThisRecordWalks( stages: PathStage[], options: unknown, record: Record | undefined, diff --git a/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx b/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx index 4837c96c3e0..a5c7d351e0f 100644 --- a/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx +++ b/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx @@ -37,6 +37,19 @@ * on (objectstack#30075), which is why an always-refused button would reach * every app with a machine on its stage field. A field without such a rule * offers every stage, and the server still judges each write. + * + * ## The fields a stage needs (`collectFields`, objectstack#35891) + * + * The header's stage menu (`RecordStageMenu`) asks for more than a yes: a + * stage that makes other fields required — a field whose `requiredWhen` holds + * once the record stands on it and is empty now, such as a loss reason on + * 「失败」 — opens the confirmation with just those fields, and the move and + * their values go in ONE write. Which fields to ask for is presentation; the + * server still judges the write (objectui#6868: it is the only validation + * authority on this surface). A refusal that names fields the reader may fill + * keeps the form open with those fields added and each one's reason beside + * it, and the stage does not move. `record:path` leaves the option off and + * keeps its plain confirmation. */ import React from 'react'; @@ -49,8 +62,14 @@ import { AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, + Button, } from '@object-ui/components'; -import { resolveFieldAffordance, stateMachineNextValues } from '@object-ui/core'; +import { + isMissingForRequired, + resolveFieldAffordance, + resolveFieldRuleState, + stateMachineNextValues, +} from '@object-ui/core'; import { usePermissions } from '@object-ui/permissions'; import { declaredUserMessage, @@ -67,6 +86,8 @@ import { pickLocalized, useObjectTranslation } from '@object-ui/i18n'; import { isComputedDetailField } from '../fieldEnrichment'; import { NON_EDITABLE_SYSTEM_FIELDS } from '../systemFields'; import { updateVia } from '../InlineEditSaveBar'; +import { InlineFieldInput } from '../InlineFieldInput'; +import { enrichDetailField } from '../fieldEnrichment'; import { isConcurrentUpdateError } from '../ConcurrentUpdateDialog'; import { useDetailTranslation } from '../useDetailTranslation'; @@ -114,7 +135,15 @@ export function stageRefusalLines( } /** The members of an object definition's field entry this module reads. */ -type FieldDef = { type?: unknown; readonly?: unknown; label?: unknown }; +type FieldDef = { + type?: unknown; + readonly?: unknown; + required?: unknown; + label?: unknown; + visibleWhen?: any; + readonlyWhen?: any; + requiredWhen?: any; +}; const fieldDefOf = (objectSchema: unknown, field: string): FieldDef | undefined => (objectSchema as { fields?: Record } | null | undefined)?.fields?.[field]; @@ -143,16 +172,37 @@ export interface StageChange { dialog: React.ReactNode; } -export function useStageChange(allowStageChange: boolean, statusField: string | undefined): StageChange { +export interface StageChangeOptions { + /** + * Ask, in the confirmation, for the fields the target stage needs filled + * (see "The fields a stage needs" above). Off for `record:path`. + */ + collectFields?: boolean; +} + +/** A pending move: the stage, and the fields its confirmation asks for. */ +type StageTarget = { value: unknown; label: string; fields: string[] }; + +export function useStageChange( + allowStageChange: boolean, + statusField: string | undefined, + options: StageChangeOptions = {}, +): StageChange { + const collectFields = options.collectFields === true; const ctx = useRecordContext(); const inline = useInlineEdit(); const perms = usePermissions(); const { t } = useDetailTranslation(); const { fieldLabel } = useSafeFieldLabel(); const { language } = useObjectTranslation(); - const [target, setTarget] = React.useState<{ value: unknown; label: string } | null>(null); + const [target, setTarget] = React.useState(null); const [busy, setBusy] = React.useState(false); const [refusal, setRefusal] = React.useState(null); + // The confirmation's own fields (`collectFields`): their values, and the + // server's reason for each one it refused on the last try. + const [values, setValues] = React.useState>({}); + const [fieldErrors, setFieldErrors] = React.useState>({}); + const [formLines, setFormLines] = React.useState(null); const objectName = ctx?.objectName; const recordId = ctx?.recordId; @@ -176,10 +226,51 @@ export function useStageChange(allowStageChange: boolean, statusField: string | const reachable = statusField ? stateMachineNextValues(ctx?.objectSchema, statusField, stored) : null; const admits = (value: unknown): boolean => reachable === null || reachable.has(String(value)); - const request = React.useCallback((stage: { value: unknown; label: string }) => { + // A field this reader may fill in the confirmation: the same question the + // record page's other in-place editors ask of a field. + const fillable = (field: string): boolean => { + const def = fieldDefOf(ctx?.objectSchema, field); + return !!def + && field !== statusField + && def.readonly !== true + && !isComputedDetailField(undefined, def) + && !NON_EDITABLE_SYSTEM_FIELDS.has(field) + && !!objectName + && resolveFieldAffordance('recordEdit', perms, objectName, field); + }; + + // The empty fields whose `requiredWhen` holds once the record stands on + // `value`, judged as the engine's transition gate judges them (the stored + // row is `previous`), and that are shown and writable there. + const fieldsNeededAt = (value: unknown): string[] => { + if (!collectFields || !statusField) return []; + const fields = (ctx?.objectSchema as { fields?: Record } | undefined)?.fields ?? {}; + const record = (ctx?.data ?? {}) as Record; + const moved = { ...record, [statusField]: value }; + const out: string[] = []; + for (const [name, def] of Object.entries(fields)) { + if (!def || def.requiredWhen == null || !fillable(name)) continue; + if (!isMissingForRequired(record[name])) continue; + const state = resolveFieldRuleState( + { visibleWhen: def.visibleWhen, readonlyWhen: def.readonlyWhen, requiredWhen: def.requiredWhen }, + moved, + { required: def.required === true, readonly: def.readonly === true, name }, + record, + undefined, + `field '${name}'`, + ); + if (state.visible && !state.readonly && state.required) out.push(name); + } + return out; + }; + + const request = (stage: { value: unknown; label: string }) => { setRefusal(null); - setTarget(stage); - }, []); + setValues({}); + setFieldErrors({}); + setFormLines(null); + setTarget({ value: stage.value, label: stage.label, fields: fieldsNeededAt(stage.value) }); + }; const labelOf = (field: string): string => { const declared = fieldDefOf(ctx?.objectSchema, field)?.label; @@ -189,6 +280,7 @@ export function useStageChange(allowStageChange: boolean, statusField: string | const confirm = async () => { const stage = target; + if (collectFields) return confirmWithFields(stage); setTarget(null); if (!stage || !pressable || !admits(stage.value)) return; setBusy(true); @@ -207,20 +299,136 @@ export function useStageChange(allowStageChange: boolean, statusField: string | } }; + // `collectFields`: the move and the asked-for fields in one write. The + // confirmation stays open until the write lands; a refusal is shown in it, + // never only after it closed, and the stage does not move. + const confirmWithFields = async (stage: StageTarget | null) => { + if (!stage || !pressable || !admits(stage.value) || busy) return; + setBusy(true); + setFieldErrors({}); + setFormLines(null); + const updatedAt = (ctx?.data as Record | undefined)?.updated_at; + const ifMatch = typeof updatedAt === 'string' ? updatedAt : undefined; + const payload: Record = { [statusField!]: stage.value }; + for (const field of stage.fields) { + if (Object.prototype.hasOwnProperty.call(values, field)) payload[field] = values[field]; + } + try { + await updateVia(dataSource, objectName!, recordId!, payload, ifMatch ? { ifMatch } : undefined); + setTarget(null); + await ctx?.refresh?.(); + } catch (err) { + // The fields the refusal names that this reader may fill join the + // form, each with its reason; every other line reads under the form. + const named = isConcurrentUpdateError(err) ? [] : (extractFieldErrors(err) ?? []); + const byField: Record = {}; + for (const e of named) { + if (e.message && fillable(e.field)) byField[e.field] = e.message; + } + const asked = Object.keys(byField); + if (asked.length > 0) { + setTarget({ ...stage, fields: [...stage.fields, ...asked.filter((f) => !stage.fields.includes(f))] }); + setFieldErrors(byField); + } + const rest = asked.length > 0 + ? named.filter((e) => e.message && !(e.field in byField)).map((e) => + e.field === statusField || e.field === RECORD_LEVEL_FIELD ? e.message : `${labelOf(e.field)}: ${e.message}`) + : stageRefusalLines(err, statusField!, labelOf, t); + setFormLines(rest.length > 0 ? rest : null); + if (isConcurrentUpdateError(err)) await ctx?.refresh?.(); + } finally { + setBusy(false); + } + }; + + const record = (ctx?.data ?? {}) as Record; + const staged = { ...record, ...values, ...(target && statusField ? { [statusField]: target.value } : {}) }; + const fieldsBody = collectFields && target && target.fields.length > 0 ? ( +
+ {target.fields.map((field) => { + const def = fieldDefOf(ctx?.objectSchema, field) as Record | undefined; + const enriched = enrichDetailField({ name: field, label: labelOf(field), type: def?.type ?? 'text' }, def); + const error = fieldErrors[field]; + const id = `stage-change-field-${field}`; + return ( +
+ +
+ setValues((prev) => ({ ...prev, [field]: v }))} + dataSource={dataSource} + autoFocus={field === target.fields[0]} + error={error} + dependentValues={staged} + /> +
+ {error && ( +

+ {error} +

+ )} +
+ ); + })} +
+ ) : null; + const dialog = ( - { if (!open) setTarget(null); }}> - + { if (!open && !(collectFields && busy)) setTarget(null); }} + > + { + // An alert dialog focuses Cancel on open. The stage menu's dialog is + // one the reader opened by picking a stage, so Enter confirms the + // move (objectstack#35891): focus the first field it asks for, or + // the confirm button when it asks for none. + const content = event.currentTarget as HTMLElement | null; + const first = content?.querySelector( + '[data-stage-change-fields] input, [data-stage-change-fields] textarea, [data-stage-change-fields] button, [data-stage-change-fields] [role="combobox"]', + ) ?? content?.querySelector('[data-stage-change-confirm]'); + if (first) { + event.preventDefault(); + first.focus(); + } + } : undefined} + > {t('detail.pathStageChangeTitle')} - {t('detail.pathStageChangeDescription', { stage: target?.label ?? '' })} + {fieldsBody + ? t('detail.stageMenuFieldsDescription', { stage: target?.label ?? '' }) + : t('detail.pathStageChangeDescription', { stage: target?.label ?? '' })} + {fieldsBody} + {collectFields && formLines && ( +
+ {formLines.map((line, i) =>

{line}

)} +
+ )} - {t('detail.cancel')} - { void confirm(); }}> - {t('detail.pathStageChangeConfirm')} - + {t('detail.cancel')} + {collectFields ? ( + + ) : ( + { void confirm(); }}> + {t('detail.pathStageChangeConfirm')} + + )}
diff --git a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.bodyTables-27055.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.bodyTables-27055.test.ts index a6b673a94d0..0e03f88bb02 100644 --- a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.bodyTables-27055.test.ts +++ b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.bodyTables-27055.test.ts @@ -25,7 +25,7 @@ */ import { describe, expect, it } from 'vitest'; -import { BODY_TABLE_PAGE_SIZE, buildDefaultPageSchema, buildDefaultTabs } from '../buildDefaultPageSchema'; +import { BODY_TABLE_PAGE_SIZE, buildDefaultHighlights, buildDefaultPageSchema, buildDefaultTabs } from '../buildDefaultPageSchema'; import { bodyTableIdsOf, buildDefaultPageColumns } from '../recordPageColumns'; const quoteDef = { @@ -208,13 +208,13 @@ describe("the record's own fields lead the Overview, its master-detail tables fo expect(shape(columns.details)).toEqual(['details(basic)', 'table(meeting_todo)']); }); - it('with a key-fields strip the order is strip, then the field groups, then the body table', () => { + it('declared key fields draw no strip (objectstack#35891): the field groups, then the body table', () => { const columns = columnsOf({ ...meetingDef, highlightFields: ['owner', 'meeting_date'] }, { related: [TODOS] }); - expect(stripShape(columns.strip)).toEqual(['record:highlights']); + expect(stripShape(columns.strip)).toEqual([]); expect(shape(columns.details)).toEqual(['details(basic)', 'table(meeting_todo)']); }); - it('with a stage bar and key fields the order is the strip (key fields, stage), the field groups, the body table', () => { + it('a slotted strip (key fields, stage) still leads: the strip, the field groups, the body table', () => { const staged = { ...meetingDef, highlightFields: ['owner'], @@ -228,7 +228,10 @@ describe("the record's own fields lead the Overview, its master-detail tables fo }, }, }; - const columns = columnsOf(staged, { statusField: 'status', related: [TODOS] }); + const columns = columnsOf(staged, { + related: [TODOS], + slots: { highlights: buildDefaultHighlights(staged, { statusField: 'status' }) }, + }); expect(stripShape(columns.strip)).toEqual(['record:highlights', 'record:path']); expect(shape(columns.details)).toEqual(['details(basic)', 'table(meeting_todo)']); }); diff --git a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.strictPayload.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.strictPayload.test.ts index f0194041a61..98a2226dda8 100644 --- a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.strictPayload.test.ts +++ b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.strictPayload.test.ts @@ -138,8 +138,9 @@ describe('ADR-0089 D3a — the Studio create payload parses server-side (objectu ], approvals: { node: { currentUserId: 'u_1' } }, }; - // A declared strip, so the `record:highlights` node is among them (the - // strip is the declared list only, objectstack#28868). + // Declared highlights and a stage field: since objectstack#35891 the page + // still emits neither `record:highlights` nor `record:path` (the strip + // sub-builder that emits them is parsed in the next case). const filesDef = { ...leadDef, highlightFields: ['email'], enable: { files: true } }; // One page: the synthesizer emits no reference rail any more // (objectstack#27055), so every branch it has co-occurs here. @@ -161,8 +162,6 @@ describe('ADR-0089 D3a — the Studio create payload parses server-side (objectu 'record:approvals', 'record:attachments', 'record:details', - 'record:highlights', - 'record:path', 'record:related_list', ]); for (const node of nodes) { diff --git a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.test.ts index 24c8f15064c..43c9af245b6 100644 --- a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.test.ts +++ b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.test.ts @@ -213,33 +213,20 @@ describe('buildDefaultPageSchema', () => { expect(page.regions[0].name).toBe('main'); }); - it('emits page:header, record:highlights, record:path, page:tabs — no discussion footer (objectstack#27055)', () => { + it('emits page:header, page:tabs — no strip, no discussion footer (objectstack#35891, objectstack#27055)', () => { + // A stage field and declared highlights: the default page still draws no + // stage bar and no highlight strip (the maintainer, 2026-11-20: + // 「把阶段条和关键字段条去掉」). The stage is the header's status tag. const types = buildDefaultPageSchema(declaredLeadDef).regions[0].components.map( (c: any) => c.type, ); // The discussion is part of the timeline stream, the Timeline tab. - expect(types).toEqual([ - 'page:header', - 'record:highlights', - 'record:path', - 'page:tabs', - ]); - }); - - it('omits record:path when no status field', () => { - const def: ObjectDefLike = { name: 'note', fields: { body: {} } }; - const types = buildDefaultPageSchema(def).regions[0].components.map( - (c: any) => c.type, - ); - expect(types).not.toContain('record:path'); + expect(types).toEqual(['page:header', 'page:tabs']); }); - it('omits record:highlights when no fields derivable', () => { - const def: ObjectDefLike = { name: 'empty', fields: {} }; - const types = buildDefaultPageSchema(def).regions[0].components.map( - (c: any) => c.type, - ); - expect(types).not.toContain('record:highlights'); + it('control: buildDefaultHighlights, for a page that places the strip itself, still emits both blocks', () => { + const types = buildDefaultHighlights(declaredLeadDef).map((c: any) => c.type); + expect(types).toEqual(['record:highlights', 'record:path']); }); it('hideDiscussion drops the timeline stream (objectstack#27055)', () => { @@ -248,14 +235,14 @@ describe('buildDefaultPageSchema', () => { expect(tabItems(tabs).map((t: any) => t.value)).toEqual(['details']); }); - it('options override auto-derivation', () => { - const page = buildDefaultPageSchema(leadDef, { + it('options override auto-derivation (the strip sub-builder)', () => { + const strip = buildDefaultHighlights(leadDef, { highlightFields: ['email'], statusField: 'rating', stages: [{ value: 'hot', label: 'Hot' }], }); - const hl = page.regions[0].components.find((c: any) => c.type === 'record:highlights'); - const path = page.regions[0].components.find((c: any) => c.type === 'record:path'); + const hl = strip.find((c: any) => c.type === 'record:highlights'); + const path = strip.find((c: any) => c.type === 'record:path'); expect(props(hl).fields).toEqual(['email']); expect(props(path).statusField).toBe('rating'); expect(props(path).stages).toEqual([{ value: 'hot', label: 'Hot' }]); @@ -471,7 +458,7 @@ describe('buildDefaultPageSchema', () => { expect(hasCustom).toBe(true); }); - it('highlights slot replaces the entire chips+path strip', () => { + it('highlights slot places the strip the page draws (the default page draws none, objectstack#35891)', () => { const page = buildDefaultPageSchema(leadDef, { slots: { highlights: { type: 'div', id: 'custom-strip' } }, }); @@ -533,11 +520,10 @@ describe('buildDefaultPageSchema', () => { const page = buildDefaultPageSchema(declaredLeadDef, { slots: { header: { type: 'div', id: 'h' } }, }); - // header replaced, but tabs (with the timeline stream) + highlights still default + // header replaced, tabs (with the timeline stream) still default; no + // strip is the default too (objectstack#35891) const types = page.regions[0].components.map((c: any) => c.type); - expect(types).toContain('record:highlights'); - expect(types).toContain('record:path'); - expect(types).toContain('page:tabs'); + expect(types).toEqual(['div', 'page:tabs']); const tabs = page.regions[0].components.find((c: any) => c.type === 'page:tabs'); expect(tabItems(tabs).some((t: any) => t.value === 'timeline')).toBe(true); }); diff --git a/ui/packages/plugin-detail/src/synth/__tests__/highlights-declaredOnly-28868.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/highlights-declaredOnly-28868.test.ts index 4b6b0fb741a..3976baf32e0 100644 --- a/ui/packages/plugin-detail/src/synth/__tests__/highlights-declaredOnly-28868.test.ts +++ b/ui/packages/plugin-detail/src/synth/__tests__/highlights-declaredOnly-28868.test.ts @@ -7,19 +7,25 @@ */ /** - * objectstack#28868 — the default record page draws each fact once. + * objectstack#28868, as objectstack#35849 / objectstack#35891 changed it — the + * default record page draws each field in its group. * - * 1. No guessed strip: an object that declares no `highlightFields` has no - * `record:highlights` node, and the body hides none of its fields. The - * maintainer's ruling: 「没声明就不挑」. - * 2. A declared strip is unchanged: the declared list minus the name field, - * at most six, and the body leaves out exactly the fields the strip draws. - * 3. The stage once: when the page draws `record:path`, its `statusField` - * joins the body's `hideFields`. + * 1. No guessed highlights: an object that declares no `highlightFields` has + * none, and nothing is picked from field names or types. The maintainer's + * ruling: 「没声明就不挑」 (objectstack#28868, kept by objectstack#35849: + * 「自动选择的关键字会让人误会」). + * 2. A declared list is still the author's — the hover card, the related + * lists and the record picker read it (`deriveHighlightFields`, minus the + * name field, at most six) — but the default page draws no strip for it + * (objectstack#35891) and the body takes none of its fields out of their + * groups (objectstack#35849: 「后台配的分组原样生效」). + * 3. The stage likewise: the default page draws no `record:path`; the stage + * field stays in its group, and the header's status tag moves it. * + * Until objectstack#35849 the body's `hideFields` left out the strip's fields + * and the path's stage field; those pins are migrated here to the new rule. * The owner rule (the meta line leaves the owner out when the strip carries - * it) and the one word for the owner are pinned beside the meta line, in - * `RecordMetaFooter.ownerOnce-28868.test.tsx`. + * it) is pinned beside the meta line, in `RecordMetaFooter.ownerOnce-28868.test.tsx`. */ import { describe, expect, it } from 'vitest'; @@ -98,69 +104,55 @@ describe('1. no declared highlightFields: no strip, and the body keeps every fie }); }); -describe('2. a declared strip: the declared list minus the name field, max 6', () => { - it('the strip draws exactly the declared list without the title, and the body leaves out exactly those', () => { +describe('2. a declared list: still the author\'s, but no strip and no field leaves its group', () => { + it('deriveHighlightFields still reads the declared list without the title, at most six', () => { const def = { ...account, highlightFields: ['name', 'industry', 'owner_id'] }; expect(deriveHighlightFields(def, null)).toEqual(['industry', 'owner_id']); - const page = buildDefaultPageSchema(def); - expect(nodesOfType(page, 'record:highlights').map((n) => n.properties.fields)).toEqual([['industry', 'owner_id']]); - expect(bodyHideFields(page)).toEqual([['industry', 'owner_id']]); - }); - - it('a declared entry past the sixth is drawn by the body, not dropped from both', () => { const names = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; - const wide: ObjectDefLike = { - name: 'wide', - fields: { name: { type: 'text' }, ...Object.fromEntries(names.map((n) => [n, { type: 'text' }])) }, - }; - // The record page passes its declared list in as `highlightFields` - // (RecordDetailView's synthesized parts): the strip cuts it at six, and so - // does the body's hide list. - const page = buildDefaultPageSchema(wide, { highlightFields: names }); - expect(nodesOfType(page, 'record:highlights').map((n) => n.properties.fields)).toEqual([names.slice(0, 6)]); - expect(bodyHideFields(page)).toEqual([names.slice(0, 6)]); + expect(deriveHighlightFields({ name: 'wide', fields: {}, highlightFields: names }, null)).toEqual(names.slice(0, 6)); }); -}); -describe('3. the stage once: the path\'s statusField leaves the body', () => { - it('an opportunity with a path has no stage field in the body', () => { - const page = buildDefaultPageSchema(opportunity()); - expect(nodesOfType(page, 'record:path').map((n) => n.properties.statusField)).toEqual(['stage']); - expect(bodyHideFields(page)).toEqual([['stage']]); + it('the default page has no record:highlights node and the body hides nothing', () => { + const def = { ...account, highlightFields: ['name', 'industry', 'owner_id'] }; + const page = buildDefaultPageSchema(def); + expect(nodesOfType(page, 'record:highlights')).toEqual([]); + expect(bodyHideFields(page)).toEqual([undefined]); }); - it('the stage joins a declared strip\'s hide list, once', () => { - const page = buildDefaultPageSchema(opportunity({ highlightFields: ['amount', 'stage'] })); - expect(bodyHideFields(page)).toEqual([['amount', 'stage']]); + it('a host passing its declared list in as highlightFields changes neither', () => { + // RecordDetailView passes the object's list in its synthesized parts. + const page = buildDefaultPageSchema(account, { highlightFields: ['industry', 'owner_id'] }); + expect(nodesOfType(page, 'record:highlights')).toEqual([]); + expect(bodyHideFields(page)).toEqual([undefined]); }); +}); - it('control: no path (stageField: false), so the stage stays in the body', () => { - const page = buildDefaultPageSchema(opportunity({ stageField: false })); +describe('3. the stage stays in its group; the default page draws no path', () => { + it('an opportunity with a stage field has no record:path, and the stage stays in the body', () => { + const page = buildDefaultPageSchema(opportunity()); expect(nodesOfType(page, 'record:path')).toEqual([]); expect(bodyHideFields(page)).toEqual([undefined]); }); - it('control: a status field with no stages to draw is no path, so it stays in the body', () => { - const def: ObjectDefLike = { name: 'note', fields: { body: { type: 'text' }, status: { type: 'text' } } }; - const page = buildDefaultPageSchema(def); - expect(nodesOfType(page, 'record:path')).toEqual([]); + it('a declared strip holding the stage hides neither', () => { + const page = buildDefaultPageSchema(opportunity({ highlightFields: ['amount', 'stage'] })); expect(bodyHideFields(page)).toEqual([undefined]); }); - it('an authored highlights slot decides: its record:path hides the stage, a slot without one does not', () => { + it('an authored highlights slot is drawn as written, and still takes nothing out of the body', () => { const withPath = buildDefaultPageSchema(opportunity({ stageField: false }), { slots: { highlights: { type: 'record:path', properties: { statusField: 'stage' } } }, }); - expect(bodyHideFields(withPath)).toEqual([['stage']]); + expect(nodesOfType(withPath, 'record:path').map((n) => n.properties.statusField)).toEqual(['stage']); + expect(bodyHideFields(withPath)).toEqual([undefined]); + }); - const withoutPath = buildDefaultPageSchema(opportunity(), { - slots: { highlights: { type: 'div', id: 'custom-strip' } }, - }); - expect(bodyHideFields(withoutPath)).toEqual([undefined]); + it('buildDefaultTabs on its own hides nothing either', () => { + expect(bodyHideFields(buildDefaultTabs(opportunity()))).toEqual([undefined]); + expect(bodyHideFields(buildDefaultTabs(opportunity({ highlightFields: ['amount'] })))).toEqual([undefined]); }); - it('buildDefaultTabs on its own hides what the default strip for the same options draws', () => { - expect(bodyHideFields(buildDefaultTabs(opportunity()))).toEqual([['stage']]); - expect(bodyHideFields(buildDefaultTabs(opportunity({ stageField: false })))).toEqual([undefined]); + it('control: the strip sub-builder still emits the path for a page that places it', () => { + expect(buildDefaultHighlights(opportunity()).map((n) => n.type)).toEqual(['record:path']); }); }); diff --git a/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts b/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts index a0218d674d3..c08c513d752 100644 --- a/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts +++ b/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts @@ -43,8 +43,10 @@ export interface ObjectDefLike { * linear flow — suppress stage detection entirely (#2065). */ stageField?: string | false; stages?: Array<{ value: any; label: string }>; - /** Semantic role (ADR-0085): the object's most important fields — - * drives the highlight strip (first {@link RECORD_HIGHLIGHTS_MAX}). */ + /** Semantic role (ADR-0085): the object's most important fields — the + * hover card, a related list's default columns, the record picker, and a + * strip a page places itself (first {@link RECORD_HIGHLIGHTS_MAX}). The + * default record page draws no strip (objectstack#35891). */ highlightFields?: string[]; /** * ACCEPTED BUT NEVER READ — do not "tidy" this away (objectui#7287). @@ -140,10 +142,22 @@ export interface ObjectDefFieldLike { } export interface BuildPageOptions { - /** Override the auto-derived highlight field list. */ + /** + * ACCEPTED BUT NEVER READ by {@link buildDefaultPageSchema} and + * {@link buildDefaultTabs} (objectstack#35891). The default page draws no + * highlight strip and no stage bar, and the Details body keeps every + * grouped field (objectstack#35849), so these three keys have nothing left + * to override there. Only {@link buildDefaultHighlights} reads them, for a + * page that places the strip itself. + * + * They stay declared because this interface ships in a published `.d.ts`, + * as `ObjectDefLike.primaryField` does (objectui#7287); removing them is + * objectstack#35943's change, not a rider here. + */ highlightFields?: string[]; - /** Override the auto-derived statusField / stages. */ + /** Accepted but never read by the default page — see `highlightFields`. */ statusField?: string; + /** Accepted but never read by the default page — see `highlightFields`. */ stages?: Array<{ value: any; label: string }>; /** Override the auto-derived section grouping. The heading rides `label` — * the one slot `@object-ui/types` declares (objectui#6190). */ @@ -265,9 +279,9 @@ export interface BuildPageOptions { * - `actions` — replaces `record:quick_actions`. The override fires * even when `headerActions` is empty (i.e. the override lets you * add a header bar where the synthesizer would have skipped one). - * - `highlights` — replaces the highlight strip (chips + chevron - * path). The override fires even when neither auto-emission - * condition is met. + * - `highlights` — places a highlight strip (chips, a chevron path) + * between the header and the tabs. The default page draws none + * (objectstack#35891), so this slot is the only way one appears there. * - `details` — replaces the Details tab body (the `record:details` * node). Other tabs (Timeline / Related / Approvals) are unaffected. * There is no `tabs` slot (objectstack#27053): the strip is composed @@ -475,10 +489,9 @@ export { RECORD_HIGHLIGHTS_MAX }; * and "what the H1 shows" cannot disagree (objectui#7287). Filtering before * the slice means the title never wastes a slot. * - * The three readers of the strip — the default page - * ({@link buildDefaultHighlights}, and the body's `hideFields` in - * {@link buildDefaultTabs}), the phone record header and the record hover - * card — all ask this one function. + * Its readers — {@link buildDefaultHighlights} (for a page that places the + * strip itself; the default page draws none, objectstack#35891), the phone + * record header and the record hover card — all ask this one function. * * `_statusField` is accepted and not read. It is part of the published * signature from when this function guessed and skipped the stage; a declared @@ -539,6 +552,10 @@ export function buildDefaultActions( * Sub-builder: the highlight strip — `record:highlights` chips plus * `record:path` chevron (when a status field is configured). * + * The default record page no longer calls it (objectstack#35891): the stage + * moves from the header's status tag, and the highlight fields stay in their + * groups. It is kept, unchanged, for a slotted page's `highlights` slot. + * * Returns an array because the strip is conceptually one region with * two adjacent nodes. * @@ -573,34 +590,6 @@ export function buildDefaultHighlights( return out; } -/** - * The stage field of the `record:path` among a page's strip nodes, or `null` - * when the strip draws no path. A node's props are read the way - * {@link bodyTablePlacement} reads a related-list node's: the ADR-0089 D3a - * `properties` bag over the node's own keys. - */ -function drawnPathField(nodes: readonly any[]): string | null { - for (const node of nodes) { - if (node?.type !== 'record:path') continue; - const props = { ...node, ...(node?.properties ?? {}) }; - if (typeof props.statusField === 'string' && props.statusField.length > 0) return props.statusField; - } - return null; -} - -/** - * The fields the Details body leaves out because the page's header already - * draws them (objectstack#28868): the highlight strip's fields, as many as - * the strip shows ({@link RECORD_HIGHLIGHTS_MAX} — a declared entry past the - * sixth is drawn by the body, not dropped from both), and the stage field - * when the page draws `record:path` for it, so the stage is shown once. - */ -function headerDrawnFields(highlightFields: readonly string[], pathField: string | null): string[] { - const out = highlightFields.slice(0, RECORD_HIGHLIGHTS_MAX); - if (pathField !== null && !out.includes(pathField)) out.push(pathField); - return out; -} - /** * One field group, resolved — the section a `record:details` `{ group }` * reference stands for — plus the group's own ADR-0089 `visibleWhen` @@ -977,24 +966,23 @@ export function buildDefaultTabs( timeline?: any[]; } = {}, ): any { - // The Details body leaves out what the default strip for these options - // draws: its highlights and the stage field of its `record:path`. - const highlightFields = options.highlightFields ?? deriveHighlightFields(def, null); - const strip = buildDefaultHighlights(def, { highlightFields, statusField: options.statusField }); - return synthTabs(def, options, headerDrawnFields(highlightFields, drawnPathField(strip))); + return synthTabs(def, options); } type DefaultTabsOptions = NonNullable[1]>; /** - * {@link buildDefaultTabs}' body, given the fields the Details body leaves - * out. `buildDefaultPageSchema` passes the ones the page it builds actually - * draws in its header (an authored `highlights` slot included). + * {@link buildDefaultTabs}' body. + * + * The Details body draws every field the object's groups hold, the highlight + * fields and the stage field included (objectstack#35849): the groups an + * author configured read the same in view and in edit, and nothing the page + * draws elsewhere is taken out of them. A builder who does not want a field + * twice leaves it out of `highlightFields` or out of the group. */ function synthTabs( def: ObjectDefLike | undefined, options: DefaultTabsOptions, - bodyHiddenFields: string[], ): any { // Every tab carries a STABLE, semantic `value` (objectui#2257): the active // tab is URL-addressable (`?tab=`, ADR-0054 C3), so values must @@ -1037,7 +1025,7 @@ function synthTabs( { label: 'Overview', value: 'details', - children: bodyTablePlacement(def, options.sections, bodyHiddenFields, bodies), + children: bodyTablePlacement(def, options.sections, undefined, bodies), }, ]; // objectstack#35595 — EVERY ordinary related list is a tab of its own, in @@ -1123,7 +1111,7 @@ export function buildDefaultAttachments(): any { * * Shape: * { type:'record', template:'default', regions:[ { name:'main', - * components: [page:header, record:highlights?, record:path?, + * components: [page:header, ?, * page:tabs, record:discussion?] } ] } * For `enable.files: true` objects the tabs node carries a peer * Attachments tab (`record:attachments` — objectstack#4358). @@ -1174,23 +1162,15 @@ export function buildDefaultPageSchema( components.push(...toNodeArray(slots.alerts)); } - // 3) Highlight strip (chips + chevron path). - const strip = - 'highlights' in slots && slots.highlights !== undefined - ? toNodeArray(slots.highlights) - : buildDefaultHighlights(def, { - highlightFields: options.highlightFields, - statusField: options.statusField, - stages: options.stages, - }); - components.push(...strip); - // What the Details body leaves out (objectstack#28868): the strip's - // highlights, and the stage field when THIS page draws `record:path` for it - // — the default strip's path, or one an authored `highlights` slot places. - const bodyHidden = headerDrawnFields( - options.highlightFields ?? deriveHighlightFields(def, null), - drawnPathField(strip), - ); + // 3) Highlights slot. The default page draws no strip (objectstack#35891, + // the maintainer's 2026-11-20 「把阶段条和关键字段条去掉」): the stage is + // the header's status tag, which opens a menu to move it, and the + // highlight fields stay in their groups (objectstack#35849). + // `buildDefaultHighlights` and the two blocks are kept, so an authored + // `highlights` slot, or an authored page, still places a strip and a path. + if ('highlights' in slots && slots.highlights !== undefined) { + components.push(...toNodeArray(slots.highlights)); + } // The timeline stream's content (objectstack#27055): an authored // `discussion` slot replaces it; `hideDiscussion` drops it. @@ -1210,12 +1190,10 @@ export function buildDefaultPageSchema( sections: options.sections, related: options.related, approvals: options.approvals, - highlightFields: options.highlightFields, - statusField: options.statusField, hideAttachments: options.hideAttachments, hideDiscussion: options.hideDiscussion, timeline, - }, bodyHidden); + }); // Replace the first tab's children (Details) with the override. The items // live in the node's `properties` bag — the canonical carrier per // ADR-0089 D3a (see `componentNode`). @@ -1229,12 +1207,10 @@ export function buildDefaultPageSchema( sections: options.sections, related: options.related, approvals: options.approvals, - highlightFields: options.highlightFields, - statusField: options.statusField, hideAttachments: options.hideAttachments, hideDiscussion: options.hideDiscussion, timeline, - }, bodyHidden)); + })); } // ADR-0085 (objectstack#27055): the synthesized page has ONE region. The diff --git a/ui/packages/plugin-detail/src/useDetailTranslation.ts b/ui/packages/plugin-detail/src/useDetailTranslation.ts index bf014d6c60d..bb9607fd6b9 100644 --- a/ui/packages/plugin-detail/src/useDetailTranslation.ts +++ b/ui/packages/plugin-detail/src/useDetailTranslation.ts @@ -328,6 +328,10 @@ export const DETAIL_DEFAULT_TRANSLATIONS: Record = { 'detail.pathStageChangeConflict': 'Someone else changed this record, and the latest version is now shown. Press the stage again if the move still applies.', 'detail.pathStageChangeDenied': "You don't have permission to change this record's stage.", 'detail.pathStageChangeFailed': 'The stage could not be changed.', + 'detail.stageMenuTrigger': 'Stage: {{stage}}. Change stage', + 'detail.stageMenuCurrent': 'current stage', + 'detail.stageMenuNotReachable': "Can't move here from {{stage}}", + 'detail.stageMenuFieldsDescription': 'To move this record to {{stage}}, fill in:', // objectui#9050 — RelatedList's malformed-filter state. Byte-identical to // the `en` pack (`defaults-maps-mirror-en-pack`), and present HERE as well // because a provider-less host mounting `RelatedList` directly is exactly