From 1a1aef8078dfbf04bf68db118346cf11dc999d50 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 17:55:15 +0000 Subject: [PATCH 01/11] feat(plugin-detail): default record page drops the stage bar and key-field strip; stage moves from the header tag The default record page no longer emits record:highlights or record:path and the details body keeps every grouped field. The header's stage tag is a menu (RecordStageMenu via RecordHeaderState.stage) listing every stage, unreachable ones disabled with a reason; a stage that makes other fields required asks for them in the confirmation and writes them with the move. The phone header now shows the stage tag. field-group-shadowed stops counting the strip. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgTcbvQNTSr6ij3TMW7 --- .changeset/35891-record-page-no-stage-bar.md | 22 ++ .../lint/src/validate-semantic-roles.test.ts | 153 ++++----- packages/lint/src/validate-semantic-roles.ts | 38 +-- .../app-shell/src/views/RecordDetailView.tsx | 5 +- .../page-header-stage-tag-35891.test.tsx | 141 +++++++++ ui/packages/components/src/index.ts | 2 +- .../src/renderers/layout/containers.tsx | 33 +- .../layout/record-header-bar-context.ts | 19 ++ ui/packages/i18n/src/locales/ar.ts | 4 + ui/packages/i18n/src/locales/de.ts | 4 + ui/packages/i18n/src/locales/en.ts | 4 + ui/packages/i18n/src/locales/es.ts | 4 + ui/packages/i18n/src/locales/fr.ts | 4 + ui/packages/i18n/src/locales/ja.ts | 4 + ui/packages/i18n/src/locales/ko.ts | 4 + ui/packages/i18n/src/locales/pt-BR.ts | 4 + ui/packages/i18n/src/locales/ru.ts | 4 + ui/packages/i18n/src/locales/zh-Hans.ts | 4 + ui/packages/i18n/src/locales/zh-Hant.ts | 4 + .../plugin-detail/src/RecordPageColumns.tsx | 6 +- .../plugin-detail/src/RecordStageMenu.tsx | 147 +++++++++ .../src/__tests__/RecordPageColumns.test.tsx | 22 +- .../__tests__/RecordStageMenu-35891.test.tsx | 291 ++++++++++++++++++ ui/packages/plugin-detail/src/index.tsx | 4 + ...record-highlights.groupGate-12720.test.tsx | 6 +- .../record-path.stageChange-28199.test.tsx | 33 +- .../src/renderers/record-path.tsx | 7 +- .../src/renderers/recordPathStageChange.tsx | 220 ++++++++++++- ...DefaultPageSchema.bodyTables-27055.test.ts | 13 +- ...ildDefaultPageSchema.strictPayload.test.ts | 7 +- .../__tests__/buildDefaultPageSchema.test.ts | 46 +-- .../highlights-declaredOnly-28868.test.ts | 96 +++--- .../src/synth/buildDefaultPageSchema.ts | 102 +++--- .../plugin-detail/src/useDetailTranslation.ts | 4 + 34 files changed, 1140 insertions(+), 321 deletions(-) create mode 100644 .changeset/35891-record-page-no-stage-bar.md create mode 100644 ui/packages/components/src/__tests__/page-header-stage-tag-35891.test.tsx create mode 100644 ui/packages/plugin-detail/src/RecordStageMenu.tsx create mode 100644 ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx 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..2ccb383dab4 --- /dev/null +++ b/.changeset/35891-record-page-no-stage-bar.md @@ -0,0 +1,22 @@ +--- +'@object-ui/plugin-detail': minor +'@object-ui/components': minor +'@object-ui/i18n': patch +'@objectstack/lint': patch +--- + +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`; `useStageChange` takes `{ collectFields: true }` for the fields-a-stage-needs dialog (`record:path` keeps its plain confirmation). +- `@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/packages/lint/src/validate-semantic-roles.test.ts b/packages/lint/src/validate-semantic-roles.test.ts index 3684fd102d4..78be6fd4e7b 100644 --- a/packages/lint/src/validate-semantic-roles.test.ts +++ b/packages/lint/src/validate-semantic-roles.test.ts @@ -103,9 +103,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'], @@ -116,94 +118,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 @@ -219,28 +197,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 @@ -249,12 +223,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 @@ -263,7 +234,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', () => { @@ -378,7 +349,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 2b06ef801d7..64e3a395a4b 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 { injectedColumnsFor, unprovisionedInjectedColumnsFor } from './system-fields.js'; import { recordsOf } from './object-graph.js'; @@ -215,17 +214,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, ); @@ -243,10 +244,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) { @@ -263,12 +261,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/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/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 406c332d4fc..7a850933037 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 14b652d847d..42e442ecd63 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1635,6 +1635,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 58e70f7edbe..200d311f0c0 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1461,6 +1461,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 dff9e7910d5..00464400a65 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1600,6 +1600,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 e0c7e224bfd..f4afbc50647 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1506,6 +1506,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 82acd914de1..bf85e75c43f 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1503,6 +1503,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 6991ebb6490..aef07d530b7 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1542,6 +1542,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 13f7a980535..b3c3d20d89c 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1461,6 +1461,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 171f9615455..bf7d5fa4959 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1503,6 +1503,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 0629e208996..d3f19e379f8 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1647,6 +1647,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 3812641e6a2..3bc030f00b2 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1327,6 +1327,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 3ff3be4e69d..70f86861c11 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1327,6 +1327,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..70b84eb628d --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx @@ -0,0 +1,291 @@ +/** + * 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(); + }); +}); diff --git a/ui/packages/plugin-detail/src/index.tsx b/ui/packages/plugin-detail/src/index.tsx index 8f3888dc7f0..56335a28fe6 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..af3cff3aaf5 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,122 @@ 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); }} + > {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..68f32a9d413 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). @@ -265,9 +267,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 +477,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 +540,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 +578,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 +954,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 +1013,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 +1099,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 +1150,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. @@ -1215,7 +1183,7 @@ export function buildDefaultPageSchema( 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`). @@ -1234,7 +1202,7 @@ export function buildDefaultPageSchema( 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 From 9c1f3353d0e3a4d6096b4ccae557385280b49f66 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 18:07:54 +0000 Subject: [PATCH 02/11] chore(i18n): regenerate zh-Hant from zh-Hans for the stage menu strings Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgTcbvQNTSr6ij3TMW7 --- ui/packages/i18n/src/locales/zh-Hant.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 70f86861c11..138bcd812db 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1327,8 +1327,8 @@ const zhHant = { pathStageChangeConflict: '其他人已修改此記錄,現已顯示最新版本。如仍需移動,請再次點選該階段。', pathStageChangeDenied: '你沒有更改此記錄階段的權限。', pathStageChangeFailed: '無法更改階段。', - stageMenuTrigger: '階段:{{stage}},變更階段', - stageMenuCurrent: '目前階段', + stageMenuTrigger: '階段:{{stage}},更改階段', + stageMenuCurrent: '當前階段', stageMenuNotReachable: '流轉規則不允許從{{stage}}直接改到這裡', stageMenuFieldsDescription: '改為{{stage}}前,請先填寫:', linkCopied: '連結已複製到剪貼簿', From ea83c3e7216c880a197be8679dfbd141d11823d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 18:30:27 +0000 Subject: [PATCH 03/11] fix(plugin-detail): the stage menu's confirm dialog opens on Move, so Enter confirms An alert dialog focuses Cancel on open, so Enter after picking a stage from the header menu cancelled the move. The menu's dialog now focuses the first field it asks for, or Move when it asks for none. record:path keeps the alert dialog default. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgTcbvQNTSr6ij3TMW7 --- .../__tests__/RecordStageMenu-35891.test.tsx | 43 +++++++++++++++++++ .../src/renderers/recordPathStageChange.tsx | 18 +++++++- 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx index 70b84eb628d..4d0be9ed54f 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordStageMenu-35891.test.tsx @@ -288,4 +288,47 @@ describe('#35891 the keyboard', () => { 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/renderers/recordPathStageChange.tsx b/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx index af3cff3aaf5..a5c7d351e0f 100644 --- a/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx +++ b/ui/packages/plugin-detail/src/renderers/recordPathStageChange.tsx @@ -383,7 +383,22 @@ export function useStageChange( open={target !== null} onOpenChange={(open) => { 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')} @@ -404,7 +419,6 @@ export function useStageChange(