diff --git a/.changeset/37802-object-field-tabs.md b/.changeset/37802-object-field-tabs.md new file mode 100644 index 00000000000..f36eedc69ad --- /dev/null +++ b/.changeset/37802-object-field-tabs.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': minor +'@object-ui/plugin-detail': minor +'@object-ui/app-shell': minor +'@object-ui/types': minor +'@objectstack/platform-objects': minor +'@objectstack/metadata-core': minor +'@objectstack/lint': minor +--- + +feat: an object can draw field groups as tabs of its record page, with `fieldTabs` + +Clause-②: yes (widening) — `ObjectSchema` gains the optional `fieldTabs: [{ key, groups }]`; `@object-ui/plugin-detail` exports `fieldTabIdOfField` and the type `RecordPageFieldTab`, and `DefaultPageColumns` gains the optional `fieldTabs` +Metadata-protocol: added + +`fieldTabs: [{ key: 'content', groups: ['content', 'import'] }]` takes the named field groups out of the standard record page's overview and draws them as a tab right after it (`?related=fields:content`), before the related lists and the built-in tabs, in declared order; on a pinned page the first field tab is the one open beside the overview. The tab's title and icon are its first group's, and a one-group tab draws no second heading. The overview keeps the groups no tab names, the ungrouped fields, the body tables and the approval band. Each tab has its own "show empty fields" row; a tab whose groups are all hidden (`visibleWhen`) or missing on the served object is not drawn; the reader cannot move or hide these tabs; a cited `?section=` inside a tab opens that tab first. The entry form, print pages and authored pages are unchanged. + +The parse refuses a group the object does not declare, a group two tabs name, a group with `relatedList`, a repeated `key`, and the form-level keys (`fields`, `label`, `icon`, `visibleWhen`); the undeclared-group refusal and the `fields` refusal name the form-level `FormSchema.fieldTabs`, which lists field names. `FormSchema.fieldTabs` in `@object-ui/types` refuses a missing `fields` with a message naming `ObjectSchema.fieldTabs`. An object extension cannot write the key. `composeStacks` with `objectConflict: 'merge'` refuses two declarations of one object whose `fieldTabs` differ, as it does every other object-level collection. The object metadata form offers it as a repeater. `os lint` warns (`object/field-tabs-empty-overview`) when the tabs take every field out of the overview. + +Absent: unchanged. Nothing to migrate. diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 3c0533dbcbb..98014d1f7f0 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -1,7 +1,7 @@ --- title: Object schema — Data Protocol reference navTitle: Object -description: "Object schemas of the ObjectStack Data Protocol: ApiMethod, ApiOperation, Index and 21 more — each property with its type, default and a TypeScript example." +description: "Object schemas of the ObjectStack Data Protocol: ApiMethod, ApiOperation, Index and 22 more — each property with its type, default and a TypeScript example." --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -13,8 +13,8 @@ description: "Object schemas of the ObjectStack Data Protocol: ApiMethod, ApiOpe ## TypeScript Usage ```typescript -import { ApiMethod, ApiOperationSchema, IndexSchema, LifecycleSchema, LifecycleClassSchema, ObjectSchema, ObjectAccessConfigSchema, ObjectCapabilities, ObjectExtensionSchema, ObjectExtensionFieldPlacementSchema, ObjectExtensionGroupPlacementSchema, ObjectExtensionListPlacementSchema, ObjectExtensionPlacementSchema, ObjectExtensionRelatedListEntrySchema, ObjectExtensionRelatedListEntryObjectSchema, ObjectExternalBindingSchema, ObjectFieldGroupSchema, ObjectOwnershipEnum, ObjectRequiredPermissionsSchema, PerOperationRequiredPermissionsSchema, RelatedListEntrySchema, RelatedListEntryObjectSchema, RowCrudActionOverrideSchema, TenancyConfigSchema } from '@objectstack/spec/data'; -import type { ApiMethod, ApiOperation, Lifecycle, LifecycleClass, ObjectAccessConfig, ObjectCapabilities, ObjectExtension, ObjectExtensionFieldPlacement, ObjectExtensionGroupPlacement, ObjectExtensionListPlacement, ObjectExtensionPlacement, ObjectExtensionRelatedListEntry, ObjectExtensionRelatedListEntryObject, ObjectExternalBinding, ObjectFieldGroup, ObjectRequiredPermissions, PerOperationRequiredPermissions, RelatedListEntry, RelatedListEntryObject, RowCrudActionOverride, TenancyConfig } from '@objectstack/spec/data'; +import { ApiMethod, ApiOperationSchema, IndexSchema, LifecycleSchema, LifecycleClassSchema, ObjectSchema, ObjectAccessConfigSchema, ObjectCapabilities, ObjectExtensionSchema, ObjectExtensionFieldPlacementSchema, ObjectExtensionGroupPlacementSchema, ObjectExtensionListPlacementSchema, ObjectExtensionPlacementSchema, ObjectExtensionRelatedListEntrySchema, ObjectExtensionRelatedListEntryObjectSchema, ObjectExternalBindingSchema, ObjectFieldGroupSchema, ObjectFieldTabSchema, ObjectOwnershipEnum, ObjectRequiredPermissionsSchema, PerOperationRequiredPermissionsSchema, RelatedListEntrySchema, RelatedListEntryObjectSchema, RowCrudActionOverrideSchema, TenancyConfigSchema } from '@objectstack/spec/data'; +import type { ApiMethod, ApiOperation, Lifecycle, LifecycleClass, ObjectAccessConfig, ObjectCapabilities, ObjectExtension, ObjectExtensionFieldPlacement, ObjectExtensionGroupPlacement, ObjectExtensionListPlacement, ObjectExtensionPlacement, ObjectExtensionRelatedListEntry, ObjectExtensionRelatedListEntryObject, ObjectExternalBinding, ObjectFieldGroup, ObjectFieldTab, ObjectRequiredPermissions, PerOperationRequiredPermissions, RelatedListEntry, RelatedListEntryObject, RowCrudActionOverride, TenancyConfig } from '@objectstack/spec/data'; // Validate data const result = ApiMethod.parse(data); @@ -179,6 +179,7 @@ const result = ApiMethod.parse(data); | **highlightFields** | `string[]` | optional | [ADR-0085] Ordered most-important fields; first entry wins where only one fits. Drives default list and related-list columns, cards, hover cards, previews and the record picker; the default record page draws no strip from it. Renamed from compactLayout. | | **relatedLists** | `(string \| { list: string; label?: string; columns?: string[] })[]` | optional | The record page's tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. A child list another package brings is not hidden by it: that package places the list with its object extension's place entry (an `{ list, after \| before }` entry), and an unplaced one shows at the end of the tabs, before approvals and the activity stream; this object may also name it, which a build accepts only when that package is in the stack, and then its own position wins. Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be `{ list, label?, columns? }` to give that list its own title and child-field columns (wins over the child FK's relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused by os validate / os build (which leave a sys_ / cloud_ / ai_ name to the runtime) and by a metadata write that names no package; a write into a package stores it and the record page places nothing for it. A columns name that resolves to no field of the child (a dotted name is walked through the child's relationships, as relatedListColumns is) is refused. | | **pinOverview** | `boolean` | optional | Whether the desktop full standard record page pins the overview (the record's own fields) to a left column beside its other tabs. Absent or true: derived as before (a full page wide enough for both columns, with another tab and no related table among the fields, pins). false: the desktop full page never pins, at any width; the overview is its first tab, open by default, and its fields lay out by width in up to three columns, also when the overview holds a related table. Read by the desktop full standard record page alone: the side preview and a phone draw the same either way, and print pages and authored kind: full \| html \| react pages do not read it. Not accepted on an object extension. | +| **fieldTabs** | `{ key: string; groups: string[] }[]` | optional | Field groups the standard record page draws as tabs of their own, right after the overview and before the related-list tabs, in this order. Each entry is `{ key, groups }`: key names the tab (snake_case; its page address is fields:``), groups lists keys of this object's fieldGroups, drawn in that order and taken out of the overview. The tab's title and icon are its first group's. The reader cannot move or hide these tabs. Refused: a group the object does not declare, a group two tabs name, a group with relatedList (body tables stay in the overview), a repeated key. Absent: unchanged. The entry form, print pages and authored kind: full \| html \| react pages are not affected. Not accepted on an object extension. Not the form-level FormSchema.fieldTabs, which lists field names. | | **stageField** | `string \| false` | optional | [ADR-0085] Lifecycle stage field (linear/ordered), or false to declare the status field non-linear and suppress stage heuristics. Absent = heuristic detection allowed. When the named field carries options, it must be a single-value `select` / `radio` with inline `options`, each declaring its `kind` ('open' / 'won' / 'lost'); a picklist-backed or multi-value stage field is refused. A name that resolves to no declared field, or a field with no options, is not judged at parse. | | **editMode** | `Enum<'modal' \| 'page'>` | optional | Edit-interaction intent for records of this object: 'modal' opens the edit form as a dialog over the current view; 'page' navigates to a dedicated full-page edit route. Absent = the renderer picks its own default (objectui defaults to modal). Cross-renderer intent, not pixel styling (family). | | **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047) | @@ -407,6 +408,13 @@ const result = ApiMethod.parse(data); | **label** | `string` | optional | This list's title on the record page (its tab and its table heading). Wins over the child FK's relatedListTitle; absent = that key, else the child object's plural label. | | **columns** | `string[]` | optional | This list's columns, as field names of the child object (e.g. ['product', 'quantity', 'amount']). Wins over the child FK's relatedListColumns; absent = that key, else the child object's derived columns. Used wherever this list is drawn: its tab, and the body table a field group places. A name that is no field of the child is refused where the child is known. | +### Nested Shape: `Object.fieldTabs[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **key** | `string` | ✅ | The tab's key (snake_case). The record page addresses the tab as fields:``. | +| **groups** | `string[]` | ✅ | The field groups this tab holds: keys of this object's fieldGroups, in the order the tab draws them. The first one's label and icon title the tab. | + ### Nested Shape: `Object.listViews[string]` | Property | Type | Required | Description | @@ -1036,6 +1044,18 @@ External datasource binding (ADR-0015) * `developerEditionCreate` +--- + +## ObjectFieldTab + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **key** | `string` | ✅ | The tab's key (snake_case). The record page addresses the tab as fields:``. | +| **groups** | `string[]` | ✅ | The field groups this tab holds: keys of this object's fieldGroups, in the order the tab draws them. The first one's label and icon title the tab. | + + --- ## ObjectOwnershipEnum diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index c3b14606ade..c9e2b5de14e 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1749 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1750 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -25,7 +25,7 @@ counts are sums of the rows they head. Regenerate with | [AI Protocol](/docs/references/ai) | 18 | 108 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 37 | 528 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | -| [Data Protocol](/docs/references/data) | 35 | 197 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | +| [Data Protocol](/docs/references/data) | 35 | 198 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | | [Integration Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/integration) | 1 | 23 | The single connector protocol (ADR-0097) — catalog descriptors and provider-bound instances. | | [Kernel Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/kernel) | 30 | 153 | Plugin lifecycle and manifests, capabilities and security, metadata loading, service registry. | @@ -36,7 +36,7 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 17 | 188 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **224** | **1749** | 14 protocol modules | +| **Total** | **224** | **1750** | 14 protocol modules | --- @@ -146,7 +146,7 @@ Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execu ## Data Protocol -**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 197 schemas** +**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 198 schemas** Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. @@ -179,7 +179,7 @@ Objects, fields, queries, filters, datasources and drivers — the ObjectQL laye | [`hook-body.zod.ts`](/docs/references/data/hook-body) | `ExpressionBody`, `HookBody`, `HookBodyCapability`, `ScriptBody` | | [`hook-body-doors.zod.ts`](/docs/references/data/hook-body-doors) | `BodyActivityAppendInput`, `BodyDoorRecordRef`, `BodyMailSendInput` | | [`mapping.zod.ts`](/docs/references/data/mapping) | `ImportFieldMapping`, `Mapping`, `TransformType` | -| [`object.zod.ts`](/docs/references/data/object) | `ApiMethod`, `ApiOperation`, `Index`, `Lifecycle`, `LifecycleClass`, `Object`, `ObjectAccessConfig`, `ObjectCapabilities`, `ObjectExtension`, `ObjectExtensionFieldPlacement`, `ObjectExtensionGroupPlacement`, `ObjectExtensionListPlacement`, `ObjectExtensionPlacement`, `ObjectExtensionRelatedListEntry`, `ObjectExtensionRelatedListEntryObject`, `ObjectExternalBinding`, `ObjectFieldGroup`, `ObjectOwnershipEnum`, `ObjectRequiredPermissions`, `PerOperationRequiredPermissions`, `RelatedListEntry`, `RelatedListEntryObject`, `RowCrudActionOverride`, `TenancyConfig` | +| [`object.zod.ts`](/docs/references/data/object) | `ApiMethod`, `ApiOperation`, `Index`, `Lifecycle`, `LifecycleClass`, `Object`, `ObjectAccessConfig`, `ObjectCapabilities`, `ObjectExtension`, `ObjectExtensionFieldPlacement`, `ObjectExtensionGroupPlacement`, `ObjectExtensionListPlacement`, `ObjectExtensionPlacement`, `ObjectExtensionRelatedListEntry`, `ObjectExtensionRelatedListEntryObject`, `ObjectExternalBinding`, `ObjectFieldGroup`, `ObjectFieldTab`, `ObjectOwnershipEnum`, `ObjectRequiredPermissions`, `PerOperationRequiredPermissions`, `RelatedListEntry`, `RelatedListEntryObject`, `RowCrudActionOverride`, `TenancyConfig` | | [`picklist.zod.ts`](/docs/references/data/picklist) | `Picklist`, `PicklistExtension`, `PicklistServedField` | | [`query.zod.ts`](/docs/references/data/query) | `AggregationFunction`, `AggregationNode`, `DateGranularity`, `FieldNode`, `FullTextSearch`, `GroupByNode`, `Query`, `SortNode` | | [`recycle-bin.zod.ts`](/docs/references/data/recycle-bin) | `RecycleBinClearedReference`, `RecycleBinEntry`, `RecycleBinRetentionDays`, `RecycleBinRetentionDaysEnv`, `RecycleBinSnapshot`, `RecycleBinSnapshotRow` | diff --git a/content/docs/ui/pages.mdx b/content/docs/ui/pages.mdx index cf4534baeee..2dc5859f33b 100644 --- a/content/docs/ui/pages.mdx +++ b/content/docs/ui/pages.mdx @@ -318,6 +318,40 @@ export const Policy = ObjectSchema.create({ }); ``` +An object can also move some of its field groups out of the details into tabs of their own with +`fieldTabs`. Each entry names a tab `key` and the `groups` it draws, in order; the tabs sit right +after **Details**, in the order they are declared, before the related lists, and on a pinned page +the first of them is the tab open beside the details. A tab takes its title and icon from its +first group, and a tab with one group draws no second heading under the title. **Details** keeps +the groups no tab names, the fields in no group, the related tables and the approval band. +Each tab counts its own empty fields. A tab whose groups are all hidden (their `visibleWhen`) is +not drawn, and a link to a cited section inside a tab opens that tab first. The reader cannot +move or hide these tabs. Only the standard record page reads the key: the entry form, print pages +and authored pages draw every group as before. + +```ts +export const Policy = ObjectSchema.create({ + name: 'policy', + label: 'Policy', + fieldGroups: [ + { key: 'basic', label: 'Basic' }, + { key: 'content', label: 'Content' }, + { key: 'import', label: 'Original' }, + ], + fieldTabs: [{ key: 'content', groups: ['content', 'import'] }], + fields: { + title: Field.text({ label: 'Title', group: 'basic' }), + body: Field.markdown({ label: 'Body', group: 'content' }), + source_file: Field.text({ label: 'Source file', group: 'import' }), + }, +}); +``` + +The parse refuses a group the object does not declare, a group two tabs name, a group that holds +a related list (body tables stay in **Details**), and a repeated `key`; an object extension cannot +write the key. This is not the form-level `fieldTabs` of a form view, which lists field names. +`os lint` warns when the tabs take every field out of **Details**. + The related lists load in steps, and the details never wait for them. The page asks every list's count in one request set, sent beside the record read, and draws each list's tab before those counts land; a list counted at 0 reads no rows, and its tab is muted, with no diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md index 16f509d22ee..66ff6fbb0f8 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/data.md @@ -21,7 +21,7 @@ The `strict` column is the one the campaign schedules against; it counts both th | Dir | Sites | strict | passthrough | catchall | strip | |---|---|---|---|---|---| -| `data/` | 184 | 115 | 2 | 0 | 67 | +| `data/` | 185 | 116 | 2 | 0 | 67 | ## `data/` — sites @@ -54,7 +54,7 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `hook-body.zod.ts` | 2 | | `hook.zod.ts` | 7 | | `mapping.zod.ts` | 8 | -| `object.zod.ts` | 31 | +| `object.zod.ts` | 32 | | `picklist.zod.ts` | 3 | | `query.zod.ts` | 5 | | `recycle-bin.zod.ts` | 4 | @@ -62,7 +62,7 @@ classify and is not listed (it becomes reportable the day it grows its first sit | `seed-loader.zod.ts` | 12 | | `seed.zod.ts` | 2 | | `validation.zod.ts` | 6 | -| **total** | **184** | +| **total** | **185** | ## `data/` — open @@ -70,7 +70,7 @@ Per file, how many of its sites still silently discard unknown keys. The `Class` column that decides the bucket split is hand-written in the ledger; the arithmetic over it is here. -**67 strip of 184**, in 11 file(s). +**67 strip of 185**, in 11 file(s). | File | Strip | Sites | |---|---|---| @@ -85,7 +85,7 @@ over it is here. | `query.zod.ts` | 3 | 5 | | `recycle-bin.zod.ts` | 4 | 4 | | `seed-loader.zod.ts` | 12 | 12 | -| **total** | **67** | **184** | +| **total** | **67** | **185** | | Bucket | Sites | |---|---| diff --git a/packages/lint/src/data-model-rules.field-tabs-37802.test.ts b/packages/lint/src/data-model-rules.field-tabs-37802.test.ts new file mode 100644 index 00000000000..017aca6718c --- /dev/null +++ b/packages/lint/src/data-model-rules.field-tabs-37802.test.ts @@ -0,0 +1,74 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37802 — `object/field-tabs-empty-overview`: an object whose + * `fieldTabs` move every field out of the record page's overview is warned + * (the overview stays its first tab, with no field). CONTROL: the same object + * with one group, or one ungrouped field, left in the overview is silent, and + * so is an object without `fieldTabs`. Membership is the page's: a group's own + * `fields` list first, then a field's `group`; hidden fields and ungrouped + * system fields are not drawn, so they do not count. + */ + +import { describe, expect, it } from 'vitest'; +import { lintDataModel } from './data-model-rules.js'; + +const RULE = 'object/field-tabs-empty-overview'; + +const policy = (fieldTabs: unknown, extraFields: Record = {}) => ({ + name: 'policy', + nameField: 'title', + fieldGroups: [ + { key: 'basic', label: 'Basic' }, + { key: 'content', label: 'Content' }, + ], + fields: { + title: { type: 'text', group: 'basic' }, + body: { type: 'textarea', group: 'content' }, + ...extraFields, + }, + ...(fieldTabs === undefined ? {} : { fieldTabs }), +}); + +const findings = (obj: unknown) => lintDataModel([obj]).filter((i) => i.rule === RULE); + +describe(`${RULE} (objectstack#37802)`, () => { + it('warns when every field is moved into a field tab, at the object\'s fieldTabs', () => { + const [finding, ...rest] = findings(policy([{ key: 'all', groups: ['basic', 'content'] }])); + expect(rest).toEqual([]); + expect(finding.severity).toBe('warning'); + expect(finding.path).toBe('objects[0].fieldTabs'); + expect(finding.message).toContain('"policy"'); + }); + + it('two tabs that together take every group warn too', () => { + expect(findings(policy([{ key: 'a', groups: ['basic'] }, { key: 'b', groups: ['content'] }]))).toHaveLength(1); + }); + + it('membership spelled by the groups\' own `fields` lists is read as the page reads it', () => { + const listed = { + name: 'policy', + nameField: 'title', + fieldGroups: [ + { key: 'basic', label: 'Basic', fields: ['title'] }, + { key: 'content', label: 'Content', fields: ['body'] }, + ], + fields: { title: { type: 'text' }, body: { type: 'textarea' } }, + }; + expect(findings({ ...listed, fieldTabs: [{ key: 'all', groups: ['basic', 'content'] }] })).toHaveLength(1); + // CONTROL: the same lists with one group left in the overview. + expect(findings({ ...listed, fieldTabs: [{ key: 'content', groups: ['content'] }] })).toEqual([]); + }); + + it('a field the overview would not draw does not keep it from being empty: hidden, or an ungrouped system field', () => { + const all = [{ key: 'all', groups: ['basic', 'content'] }]; + expect(findings(policy(all, { secret: { type: 'text', hidden: true } }))).toHaveLength(1); + expect(findings(policy(all, { created_at: { type: 'datetime' } }))).toHaveLength(1); + }); + + it('CONTROL: a group left in the overview, an ungrouped field, or no fieldTabs is silent', () => { + expect(findings(policy([{ key: 'content', groups: ['content'] }]))).toEqual([]); + expect(findings(policy([{ key: 'all', groups: ['basic', 'content'] }], { status: { type: 'text' } }))).toEqual([]); + expect(findings(policy(undefined))).toEqual([]); + }); +}); diff --git a/packages/lint/src/data-model-rules.ts b/packages/lint/src/data-model-rules.ts index 4a1b325cc1b..8895de88b28 100644 --- a/packages/lint/src/data-model-rules.ts +++ b/packages/lint/src/data-model-rules.ts @@ -23,7 +23,9 @@ import { REFERENCE_VALUE_TYPES, isAggregateCompatibleWithFieldType, isApiOperationAllowed, + FIELD_GROUP_SYSTEM_FIELDS, fieldGroupsPlaceRelationship, + readFieldGroupMembership, isGroupPlaceableRelationship, masterDetailRequiredOmitted, referenceCarrierOf, @@ -1455,6 +1457,40 @@ export function lintDataModel(objects: any[]): LintIssue[] { }); } + // objectstack#37802 — `fieldTabs` (ADR-0085's Note of 2026-11-27) moves + // field groups out of the record page's overview into tabs of their own. + // The overview always exists (the body tables, the approval band and the + // meta line stay there), so a declaration that moves out every field + // leaves it a tab with no field: legal, and almost never meant. + const fieldTabGroups = new Set(); + for (const tab of Array.isArray(obj.fieldTabs) ? obj.fieldTabs : []) { + for (const group of Array.isArray(tab?.groups) ? tab.groups : []) { + if (typeof group === 'string') fieldTabGroups.add(group); + } + } + // Membership is read the way the page reads it — a group's own `fields` + // list first, then a field's `group` (`readFieldGroupMembership`) — and + // only a field the overview would draw counts: not hidden, and, when + // ungrouped, not one of the system fields the layout never lists. + const membership = fieldTabGroups.size > 0 ? readFieldGroupMembership(obj) : undefined; + const drawn = fields.filter(({ name, def }) => + def?.hidden !== true && (membership?.groupOf.has(name) || !FIELD_GROUP_SYSTEM_FIELDS.has(name))); + if ( + membership !== undefined + && drawn.length > 0 + && drawn.every(({ name }) => fieldTabGroups.has(membership.groupOf.get(name) ?? '')) + ) { + issues.push({ + severity: 'warning', + rule: 'object/field-tabs-empty-overview', + message: + `Object "${obj.name}" moves every field into its \`fieldTabs\` — the record page's overview, still its ` + + 'first tab, draws no field', + path: `${objPath}.fieldTabs`, + fix: 'Leave at least one field group out of `fieldTabs` (the overview draws the groups no tab names and the ungrouped fields).', + }); + } + for (const { name: fieldName, def } of fields) { if (!def || typeof def !== 'object') continue; const fieldPath = `${objPath}.fields.${fieldName}`; diff --git a/packages/metadata-core/src/object-schema-fls-references.ts b/packages/metadata-core/src/object-schema-fls-references.ts index bdc115e1eb3..082a2298ee0 100644 --- a/packages/metadata-core/src/object-schema-fls-references.ts +++ b/packages/metadata-core/src/object-schema-fls-references.ts @@ -824,6 +824,8 @@ export const OBJECT_REFERENCE_POSITIONS: Readonly> = { requiredPermissions: keep, fileAccessDelegate: keep, schemaReadDelegate: keep, editMode: keep, enable: keep, // The record page layout switch (ADR-0085's Note of 2026-11-27): a boolean, no field name. pinOverview: keep, + // The record page's field tabs (the same Note): tab keys and field GROUP keys, no field name. + fieldTabs: keep, sharingModel: keep, externalSharingModel: keep, protection: keep, // [#25760] The per-object sharing opt-ins (`sharing.controlledByParent.ownerMayEdit`, // ADR-0055 §3 amendment): a block of booleans that names no field. diff --git a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts index 4ee2d7ad23e..26ab331ba26 100644 --- a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts +++ b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts @@ -418,9 +418,11 @@ describe('#17501 — /meta/types serves a real schema for `action`, and moves no // (no person edits a field of the record at the console; writes keep it). // [#37792] `object` 53 → 54: `pinOverview`, the record page layout switch // (ADR-0085's Note of 2026-11-27). + // [#37802] `object` 54 → 55: `fieldTabs`, the record page's field tabs + // (the same Note). const CARD_PROPERTY_COUNTS: Record = { agent: 24, app: 24, dashboard: 21, dataset: 17, field: 89, flow: 24, - hook: 24, object: 54, page: 28, position: 14, report: 24, skill: 18, tool: 14, + hook: 24, object: 55, page: 28, position: 14, report: 24, skill: 18, tool: 14, }; it.each(Object.entries(CARD_PROPERTY_COUNTS))( diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index ec7dfb99aa9..459ff57f73a 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const arMetadataForms: NonNullable = { label: "Pin Overview", helpText: "Whether the wide desktop record page pins the overview (the record's own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way." }, + fieldTabs: { + label: "Field Tabs", + helpText: "Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused." + }, + "fieldTabs.key": { + label: "المفتاح", + helpText: "Machine key in snake_case, unique among this object's field tabs; the tab's address on the record page (fields:key)." + }, + "fieldTabs.groups": { + label: "المجموعات", + helpText: "The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here." + }, searchableFields: { label: "الحقول القابلة للبحث", helpText: "أسماء الحقول التي يطابقها استعلام $search ‏(ADR-0061): القيمة الافتراضية لمنتقي السجلات والبحث السريع في القوائم والبحث العام؛ ويمكن لطريقة العرض تضييقها. عند عدم تعيينها، يستخدم البحث حقل الاسم/العنوان إضافة إلى الحقول النصية القصيرة. يجب أن يسمّي كل إدخال حقلًا مخزَّنًا من هذا الكائن — ويُرفض عند النشر الاسم المجهول أو حقل الصيغة الافتراضي." diff --git a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts index 589663e6467..bb02c8c8d54 100644 --- a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts @@ -96,6 +96,10 @@ export const arGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.sections.refresh.label": "1b63ae2e002930a6", "metadataForms.object.fields.actionLayout.selection.helpText": "3647854e40367b07", "metadataForms.object.fields.actionLayout.selection.label": "68d28c84b59e72b3", + "metadataForms.object.fields.fieldTabs.groups.helpText": "0c98d15573eccade", + "metadataForms.object.fields.fieldTabs.helpText": "81a1a0076b489db7", + "metadataForms.object.fields.fieldTabs.key.helpText": "21ab5c572c405819", + "metadataForms.object.fields.fieldTabs.label": "5493ff02a20f00bd", "metadataForms.object.fields.pinOverview.helpText": "768f0157c04d4ee2", "metadataForms.object.fields.pinOverview.label": "901b14e51cd49243", "metadataForms.permission.fields.fields.helpText": "887a0bae04a950e2", diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index 259dfca9885..c99cdb444bc 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const deMetadataForms: NonNullable = { label: "Pin Overview", helpText: "Whether the wide desktop record page pins the overview (the record's own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way." }, + fieldTabs: { + label: "Field Tabs", + helpText: "Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused." + }, + "fieldTabs.key": { + label: "Schlüssel", + helpText: "Machine key in snake_case, unique among this object's field tabs; the tab's address on the record page (fields:key)." + }, + "fieldTabs.groups": { + label: "Gruppen", + helpText: "The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here." + }, searchableFields: { label: "Durchsuchbare Felder", helpText: "Feldnamen, auf die die Abfrage $search passt (ADR-0061): der Standard für die Datensatzauswahl, die Schnellsuche der Liste und die globale Suche; eine Ansicht kann ihn einschränken. Nicht gesetzt, sucht die Suche im Namens-/Titelfeld und in kurzen Textfeldern. Jeder Eintrag muss ein gespeichertes Feld dieses Objekts benennen – ein unbekannter Name oder ein virtuelles Formelfeld wird bei der Veröffentlichung abgelehnt." diff --git a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts index 0b99263831e..3e76081d8de 100644 --- a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts @@ -133,6 +133,10 @@ export const deGeneratedSourceHashes: Readonly> = { "metadataForms.object.fields.actionLayout.selection.helpText": "3647854e40367b07", "metadataForms.object.fields.actionLayout.selection.label": "68d28c84b59e72b3", "metadataForms.object.fields.enable.feeds.label": "669c64671f632139", + "metadataForms.object.fields.fieldTabs.groups.helpText": "0c98d15573eccade", + "metadataForms.object.fields.fieldTabs.helpText": "81a1a0076b489db7", + "metadataForms.object.fields.fieldTabs.key.helpText": "21ab5c572c405819", + "metadataForms.object.fields.fieldTabs.label": "5493ff02a20f00bd", "metadataForms.object.fields.lifecycle.storage.shards.label": "739988affb36b2e0", "metadataForms.object.fields.name.label": "5274417ff1ccaf01", "metadataForms.object.fields.pinOverview.helpText": "768f0157c04d4ee2", diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index 7780031c80e..a0590352051 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const enMetadataForms: NonNullable = { label: "Pin Overview", helpText: "Whether the wide desktop record page pins the overview (the record's own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way." }, + fieldTabs: { + label: "Field Tabs", + helpText: "Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused." + }, + "fieldTabs.key": { + label: "Key", + helpText: "Machine key in snake_case, unique among this object's field tabs; the tab's address on the record page (fields:key)." + }, + "fieldTabs.groups": { + label: "Groups", + helpText: "The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here." + }, searchableFields: { label: "Searchable Fields", helpText: "Field names the $search query matches (ADR-0061): the default for the record picker, list quick-search and global search; a view may narrow it. Unset, search uses the name/title field plus short-text fields. Each entry must name a stored field of this object — an unknown name or a virtual formula field is refused at publish." diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index f80ab0fe699..3d06b37476c 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const esESMetadataForms: NonNullable = label: "Fijar resumen", helpText: "Si la página de registro de escritorio ancha fija el resumen (los campos propios del registro) en una columna izquierda junto a las demás pestañas. Sin definir: se fija como antes siempre que la página sea lo bastante ancha y tenga otras pestañas; un interruptor sin tocar no escribe nada, por lo que aparece desactivado mientras la página sigue fijada. Desactivado una vez definido: la página completa de escritorio nunca se fija, en ningún ancho, y el resumen es su primera pestaña, abierta por defecto, con los campos dispuestos según el ancho en hasta tres columnas, también cuando el resumen contiene una tabla relacionada. La vista previa lateral y un teléfono se ven igual en ambos casos." }, + fieldTabs: { + label: "Pestañas de campos", + helpText: "Grupos de campos que la página de registro estándar muestra como pestañas, justo después del resumen, en este orden, antes de las listas relacionadas. Cada pestaña nombra los grupos que muestra, en orden; el resumen conserva los grupos que ninguna pestaña nombra y los campos sin grupo. La pestaña toma su título e icono de su primer grupo. El formulario de entrada, las páginas de impresión y las páginas propias no cambian. Se rechazan un grupo nombrado dos veces, un grupo que Grupos de campos no declara y un grupo de lista relacionada." + }, + "fieldTabs.key": { + label: "Clave", + helpText: "Clave técnica en snake_case, única entre las pestañas de campos de este objeto; es la dirección de la pestaña en la página de registro (fields:clave)." + }, + "fieldTabs.groups": { + label: "Grupos", + helpText: "Las claves de los grupos de campos que muestra esta pestaña, en orden (al menos una). Un grupo que llena una lista relacionada se queda en el resumen y aquí se rechaza." + }, searchableFields: { label: "Campos buscables", helpText: "Nombres de campo con los que coincide la consulta $search (ADR-0061): el valor predeterminado del selector de registros, la búsqueda rápida de listas y la búsqueda global; una vista puede acotarlo. Sin definir, la búsqueda usa el campo de nombre/título más los campos de texto corto. Cada entrada debe nombrar un campo almacenado de este objeto: un nombre desconocido o un campo formula virtual se rechaza al publicar." diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index 8c220dac697..636947ba180 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const frMetadataForms: NonNullable = { label: "Pin Overview", helpText: "Whether the wide desktop record page pins the overview (the record's own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way." }, + fieldTabs: { + label: "Field Tabs", + helpText: "Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused." + }, + "fieldTabs.key": { + label: "Clé", + helpText: "Machine key in snake_case, unique among this object's field tabs; the tab's address on the record page (fields:key)." + }, + "fieldTabs.groups": { + label: "Groupes", + helpText: "The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here." + }, searchableFields: { label: "Champs de recherche", helpText: "Noms des champs auxquels correspond la requête $search (ADR-0061) : la valeur par défaut pour le sélecteur d’enregistrements, la recherche rapide dans les listes et la recherche globale ; une vue peut la restreindre. Si elle n’est pas définie, la recherche utilise le champ de nom/titre ainsi que les champs de texte court. Chaque entrée doit désigner un champ stocké de cet objet — un nom inconnu ou un champ de formule virtuel est refusé à la publication." diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index 9e979940dd3..3f73a5b853d 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -154,6 +154,10 @@ export const frGeneratedSourceHashes: Readonly> = { "metadataForms.object.fields.actionLayout.selection.helpText": "3647854e40367b07", "metadataForms.object.fields.actionLayout.selection.label": "68d28c84b59e72b3", "metadataForms.object.fields.description.label": "779a4342c8eb6707", + "metadataForms.object.fields.fieldTabs.groups.helpText": "0c98d15573eccade", + "metadataForms.object.fields.fieldTabs.helpText": "81a1a0076b489db7", + "metadataForms.object.fields.fieldTabs.key.helpText": "21ab5c572c405819", + "metadataForms.object.fields.fieldTabs.label": "5493ff02a20f00bd", "metadataForms.object.fields.fields.description.label": "779a4342c8eb6707", "metadataForms.object.fields.fields.expression.label": "cd1b52ad1588075e", "metadataForms.object.fields.fields.max.label": "8081d808ef64ff91", diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index 946b3a5a6cb..83dd9038879 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const jaJPMetadataForms: NonNullable = label: "概要を固定", helpText: "デスクトップの広いレコードページで、概要(レコード自身の項目)を左の列に固定し、他のタブをその横に並べるかどうか。未設定:ページが十分に広く他のタブがあれば、これまでどおり固定されます。触れていないスイッチは何も書き込まないため、オフと表示されていてもページは固定されたままです。一度オフに設定すると:デスクトップの全画面ページはどの幅でも固定されず、概要が最初のタブとして既定で開き、項目は幅に合わせて最大 3 列で並びます。概要に関連テーブルがある場合も同じです。サイドプレビューとスマートフォンはどちらでも同じ表示です。" }, + fieldTabs: { + label: "フィールドタブ", + helpText: "標準レコードページで、概要のすぐ後に、この順序で関連リストより前にタブとして表示するフィールドグループ。各タブは表示するグループを順番に指定します。概要には、どのタブにも指定されていないグループと、どのグループにも属さないフィールドが残ります。タブのタイトルとアイコンは最初のグループのものを使います。入力フォーム、印刷ページ、独自に作成したページは変わりません。2 回指定されたグループ、フィールドグループで宣言されていないグループ、関連リストのグループは拒否されます。" + }, + "fieldTabs.key": { + label: "キー", + helpText: "snake_case の機械キー。このオブジェクトのフィールドタブ内で一意で、レコードページ上のタブのアドレス(fields:キー)になります。" + }, + "fieldTabs.groups": { + label: "グループ", + helpText: "このタブが表示するフィールドグループのキーを順番に指定します(1 つ以上)。関連リストで埋まるグループは概要に残り、ここでは拒否されます。" + }, searchableFields: { label: "検索対象項目", helpText: "$search クエリが照合する項目名(ADR-0061)。レコードピッカー、一覧のクイック検索、グローバル検索の既定値で、ビューで絞り込めます。未設定の場合は名前/タイトル項目と短いテキスト項目で検索します。各項目はこのオブジェクトの保存済みの項目を指す必要があり、不明な名前や仮想の formula 項目は公開時に拒否されます。" diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 4c871bccdf7..7f7aa548caa 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const koMetadataForms: NonNullable = { label: "Pin Overview", helpText: "Whether the wide desktop record page pins the overview (the record's own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way." }, + fieldTabs: { + label: "Field Tabs", + helpText: "Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused." + }, + "fieldTabs.key": { + label: "키", + helpText: "Machine key in snake_case, unique among this object's field tabs; the tab's address on the record page (fields:key)." + }, + "fieldTabs.groups": { + label: "그룹", + helpText: "The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here." + }, searchableFields: { label: "검색 가능 필드", helpText: "$search 쿼리가 일치시키는 필드 이름입니다(ADR-0061). 레코드 선택기, 목록 빠른 검색, 전역 검색의 기본값이며 뷰에서 좁힐 수 있습니다. 설정하지 않으면 이름/제목 필드와 짧은 텍스트 필드로 검색합니다. 각 항목은 이 객체의 저장된 필드를 지정해야 하며, 알 수 없는 이름이나 가상 수식 필드는 게시할 때 거부됩니다." diff --git a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts index 3c060cfb5a3..1fc0cb999be 100644 --- a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts @@ -96,6 +96,10 @@ export const koGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.sections.refresh.label": "1b63ae2e002930a6", "metadataForms.object.fields.actionLayout.selection.helpText": "3647854e40367b07", "metadataForms.object.fields.actionLayout.selection.label": "68d28c84b59e72b3", + "metadataForms.object.fields.fieldTabs.groups.helpText": "0c98d15573eccade", + "metadataForms.object.fields.fieldTabs.helpText": "81a1a0076b489db7", + "metadataForms.object.fields.fieldTabs.key.helpText": "21ab5c572c405819", + "metadataForms.object.fields.fieldTabs.label": "5493ff02a20f00bd", "metadataForms.object.fields.pinOverview.helpText": "768f0157c04d4ee2", "metadataForms.object.fields.pinOverview.label": "901b14e51cd49243", "metadataForms.permission.fields.fields.helpText": "887a0bae04a950e2", diff --git a/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts index 5f9f01f3546..ba12af10577 100644 --- a/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts @@ -1022,7 +1022,11 @@ describe('#19403 round 8 — the population, DERIVED from the form and a shape', // 134 since #37792 gave `basics` the `pinOverview` row (the record page // layout switch) — label and help text, authored in every translated // locale, so `openEchoes` stays at zero. - expect(OPEN_LEAVES.length).toBe(134); + // 140 since #37802 gave `basics` the `fieldTabs` repeater (the record + // page's field tabs) — the row and its `key` and `groups` sub-rows, six + // leaves (three labels, three help texts), authored in every translated + // locale, so `openEchoes` stays at zero. + expect(OPEN_LEAVES.length).toBe(140); expect(PANEL_LEAVES.some((l) => l.path === 'fields.placeholder')).toBe(false); expect(OPEN_LEAVES.some((l) => l.path === 'fields.placeholder')).toBe(true); for (const path of ['name', 'label', 'fields', 'fields.valueDomain', 'fields.deleteBehavior', 'fields.expression']) { diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index 6b94b1d16b8..c5a78fcaad8 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1366,7 +1366,10 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // 872 since #38692: the `knowledge_source` form's `source.retrieval` // group and its `mode` row (the retrieval mode) — two row labels, // authored in every locale. - expect(translated.length, `${locale} positive control`).toBe(872); + // 875 since #37802: the object form's `fieldTabs` repeater (the record + // page's field tabs) — the row and its `key` and `groups` sub-rows, + // three labels, authored in all three locales. + expect(translated.length, `${locale} positive control`).toBe(875); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index c99ccbfb967..85188b9f2b1 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const ptBRMetadataForms: NonNullable = label: "Pin Overview", helpText: "Whether the wide desktop record page pins the overview (the record's own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way." }, + fieldTabs: { + label: "Field Tabs", + helpText: "Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused." + }, + "fieldTabs.key": { + label: "Chave", + helpText: "Machine key in snake_case, unique among this object's field tabs; the tab's address on the record page (fields:key)." + }, + "fieldTabs.groups": { + label: "Grupos", + helpText: "The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here." + }, searchableFields: { label: "Campos pesquisáveis", helpText: "Nomes de campos que a consulta $search compara (ADR-0061): o padrão para o seletor de registros, a busca rápida da lista e a busca global; uma visualização pode restringi-lo. Quando não definido, a busca usa o campo de nome/título mais os campos de texto curto. Cada entrada deve nomear um campo armazenado deste objeto — um nome desconhecido ou um campo de fórmula virtual é recusado na publicação." diff --git a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts index f8e7135ce8c..51b6c9b7c94 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts @@ -109,6 +109,10 @@ export const ptBRGeneratedSourceHashes: Readonly> = { "metadataForms.object.fields.actionLayout.selection.helpText": "3647854e40367b07", "metadataForms.object.fields.actionLayout.selection.label": "68d28c84b59e72b3", "metadataForms.object.fields.enable.feeds.label": "669c64671f632139", + "metadataForms.object.fields.fieldTabs.groups.helpText": "0c98d15573eccade", + "metadataForms.object.fields.fieldTabs.helpText": "81a1a0076b489db7", + "metadataForms.object.fields.fieldTabs.key.helpText": "21ab5c572c405819", + "metadataForms.object.fields.fieldTabs.label": "5493ff02a20f00bd", "metadataForms.object.fields.lifecycle.storage.shards.label": "739988affb36b2e0", "metadataForms.object.fields.pinOverview.helpText": "768f0157c04d4ee2", "metadataForms.object.fields.pinOverview.label": "901b14e51cd49243", diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index ade11e38373..0dfbad5ec73 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const ruMetadataForms: NonNullable = { label: "Pin Overview", helpText: "Whether the wide desktop record page pins the overview (the record's own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way." }, + fieldTabs: { + label: "Field Tabs", + helpText: "Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused." + }, + "fieldTabs.key": { + label: "Ключ", + helpText: "Machine key in snake_case, unique among this object's field tabs; the tab's address on the record page (fields:key)." + }, + "fieldTabs.groups": { + label: "Группы", + helpText: "The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here." + }, searchableFields: { label: "Поля поиска", helpText: "Имена полей, по которым ищет запрос $search (ADR-0061): значение по умолчанию для выбора записей, быстрого поиска в списке и глобального поиска; представление может его сузить. Если не задано, поиск использует поле названия/заголовка и короткие текстовые поля. Каждая запись должна указывать хранимое поле этого объекта — неизвестное имя или виртуальное поле формулы отклоняется при публикации." diff --git a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts index f270a7b9ac9..94dc7169b72 100644 --- a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts @@ -96,6 +96,10 @@ export const ruGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.sections.refresh.label": "1b63ae2e002930a6", "metadataForms.object.fields.actionLayout.selection.helpText": "3647854e40367b07", "metadataForms.object.fields.actionLayout.selection.label": "68d28c84b59e72b3", + "metadataForms.object.fields.fieldTabs.groups.helpText": "0c98d15573eccade", + "metadataForms.object.fields.fieldTabs.helpText": "81a1a0076b489db7", + "metadataForms.object.fields.fieldTabs.key.helpText": "21ab5c572c405819", + "metadataForms.object.fields.fieldTabs.label": "5493ff02a20f00bd", "metadataForms.object.fields.pinOverview.helpText": "768f0157c04d4ee2", "metadataForms.object.fields.pinOverview.label": "901b14e51cd49243", "metadataForms.permission.fields.fields.helpText": "887a0bae04a950e2", diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index 0a51c8d7b32..37900d8e32d 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const zhCNMetadataForms: NonNullable = label: "固定概览", helpText: "桌面宽屏记录页是否把概览(记录自己的字段)固定在左栏、其他页签排在旁边。未设置:只要页面够宽且有其他页签,就照旧固定;没动过的开关不写任何值,所以它显示为关闭,页面却仍然固定。设置为关闭后:桌面整页在任何宽度下都不再固定,概览是第一个页签并默认打开,字段按页面宽度最多排三列,概览里有子表时也一样。侧边预览和手机无论设不设都一样。" }, + fieldTabs: { + label: "字段页签", + helpText: "在标准记录页上作为页签绘制的字段分组,紧跟在概览之后,按此顺序排在相关列表之前。每个页签列出它绘制的分组及顺序;概览保留没有页签认领的分组和不属于任何分组的字段。页签的标题和图标取自它的第一个分组。录入表单、打印页和自定义页面不受影响。同一分组被命名两次、字段分组里没有声明的分组,以及相关列表分组,都会被拒绝。" + }, + "fieldTabs.key": { + label: "键", + helpText: "snake_case 格式的机器键,在本对象的字段页签中唯一;也是该页签在记录页上的地址(fields:键)。" + }, + "fieldTabs.groups": { + label: "分组", + helpText: "此页签绘制的字段分组键,按顺序排列(至少一个)。由相关列表填充的分组留在概览中,在这里会被拒绝。" + }, searchableFields: { label: "可搜索字段", helpText: "$search 查询匹配的字段名(ADR-0061):记录选择器、列表快速搜索和全局搜索的默认范围,视图可以再收窄。未设置时,搜索使用名称/标题字段加上短文本字段。每一项都必须是本对象已存储的字段——未知的名称或虚拟的 formula 字段会在发布时被拒绝。" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index 7027c4a2dc4..0092f8e835e 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -84,6 +84,18 @@ export const zhHantMetadataForms: NonNullable label: "Pin Overview", helpText: "Whether the wide desktop record page pins the overview (the record's own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way." }, + fieldTabs: { + label: "Field Tabs", + helpText: "Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused." + }, + "fieldTabs.key": { + label: "鍵", + helpText: "Machine key in snake_case, unique among this object's field tabs; the tab's address on the record page (fields:key)." + }, + "fieldTabs.groups": { + label: "分組", + helpText: "The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here." + }, searchableFields: { label: "可搜尋欄位", helpText: "$search 查詢比對的欄位名(ADR-0061):記錄選擇器、清單快速搜尋和全域搜尋的預設範圍,檢視可以再收窄。未設定時,搜尋使用名稱/標題欄位加上短文字欄位。每一項都必須是本物件已儲存的欄位——未知的名稱或虛擬的 formula 欄位會在發布時被拒絕。" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts index 356460549be..55d55f4e207 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts @@ -94,6 +94,10 @@ export const zhHantGeneratedSourceHashes: Readonly> = { "metadataForms.knowledge_source.sections.refresh.label": "1b63ae2e002930a6", "metadataForms.object.fields.actionLayout.selection.helpText": "3647854e40367b07", "metadataForms.object.fields.actionLayout.selection.label": "68d28c84b59e72b3", + "metadataForms.object.fields.fieldTabs.groups.helpText": "0c98d15573eccade", + "metadataForms.object.fields.fieldTabs.helpText": "81a1a0076b489db7", + "metadataForms.object.fields.fieldTabs.key.helpText": "21ab5c572c405819", + "metadataForms.object.fields.fieldTabs.label": "5493ff02a20f00bd", "metadataForms.object.fields.pinOverview.helpText": "768f0157c04d4ee2", "metadataForms.object.fields.pinOverview.label": "901b14e51cd49243", "metadataForms.report.fields.dateRange.allowCustomRange.helpText": "eb95a6b1536e22fd", diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index b587763393f..f27f1619f48 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -630,6 +630,9 @@ "ObjectFieldGroup (type)", "ObjectFieldGroupParsed (type)", "ObjectFieldGroupSchema (const)", + "ObjectFieldTab (type)", + "ObjectFieldTabParsed (type)", + "ObjectFieldTabSchema (const)", "ObjectIndex (type)", "ObjectIndexParsed (type)", "ObjectOwnership (type)", diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index 14a97189fb6..4b272e5eca0 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -694,6 +694,7 @@ "data/Object:external", "data/Object:externalSharingModel [RETIRED]", "data/Object:fieldGroups", + "data/Object:fieldTabs", "data/Object:fields", "data/Object:fileAccessDelegate", "data/Object:highlightFields", @@ -791,6 +792,8 @@ "data/ObjectFieldGroup:relatedList", "data/ObjectFieldGroup:requiresFeature", "data/ObjectFieldGroup:visibleWhen", + "data/ObjectFieldTab:groups", + "data/ObjectFieldTab:key", "data/OracleConfig:connectString", "data/OracleConfig:host", "data/OracleConfig:password [RETIRED]", diff --git a/packages/spec/declaration-map/data.json b/packages/spec/declaration-map/data.json index a1fe37afb61..27ba55ab2c0 100644 --- a/packages/spec/declaration-map/data.json +++ b/packages/spec/declaration-map/data.json @@ -244,6 +244,8 @@ "ObjectExternalBindingSchema": "data/ObjectExternalBinding", "ObjectFieldGroup": "data/ObjectFieldGroup", "ObjectFieldGroupSchema": "data/ObjectFieldGroup", + "ObjectFieldTab": "data/ObjectFieldTab", + "ObjectFieldTabSchema": "data/ObjectFieldTab", "ObjectOwnershipEnum": "data/ObjectOwnershipEnum", "ObjectRequiredPermissions": "data/ObjectRequiredPermissions", "ObjectRequiredPermissionsSchema": "data/ObjectRequiredPermissions", diff --git a/packages/spec/docs/references/api/metadata.md b/packages/spec/docs/references/api/metadata.md index f35fb4bf046..eb6af874aaf 100644 --- a/packages/spec/docs/references/api/metadata.md +++ b/packages/spec/docs/references/api/metadata.md @@ -964,6 +964,7 @@ Metadata query with filtering, sorting, and pagination | **highlightFields** | `string[]` | optional | [ADR-0085] Ordered most-important fields; first entry wins where only one fits. Drives default list and related-list columns, cards, hover cards, previews and the record picker; the default record page draws no strip from it. Renamed from compactLayout. | | **relatedLists** | `(string \| { list: string; label?: string; columns?: string[] })[]` | optional | The record page's tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. A child list another package brings is not hidden by it: that package places the list with its object extension's place entry (an `{ list, after \| before }` entry), and an unplaced one shows at the end of the tabs, before approvals and the activity stream; this object may also name it, which a build accepts only when that package is in the stack, and then its own position wins. Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be `{ list, label?, columns? }` to give that list its own title and child-field columns (wins over the child FK's relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused by os validate / os build (which leave a sys_ / cloud_ / ai_ name to the runtime) and by a metadata write that names no package; a write into a package stores it and the record page places nothing for it. A columns name that resolves to no field of the child (a dotted name is walked through the child's relationships, as relatedListColumns is) is refused. | | **pinOverview** | `boolean` | optional | Whether the desktop full standard record page pins the overview (the record's own fields) to a left column beside its other tabs. Absent or true: derived as before (a full page wide enough for both columns, with another tab and no related table among the fields, pins). false: the desktop full page never pins, at any width; the overview is its first tab, open by default, and its fields lay out by width in up to three columns, also when the overview holds a related table. Read by the desktop full standard record page alone: the side preview and a phone draw the same either way, and print pages and authored kind: full \| html \| react pages do not read it. Not accepted on an object extension. | +| **fieldTabs** | `{ key: string; groups: string[] }[]` | optional | Field groups the standard record page draws as tabs of their own, right after the overview and before the related-list tabs, in this order. Each entry is `{ key, groups }`: key names the tab (snake_case; its page address is fields:``), groups lists keys of this object's fieldGroups, drawn in that order and taken out of the overview. The tab's title and icon are its first group's. The reader cannot move or hide these tabs. Refused: a group the object does not declare, a group two tabs name, a group with relatedList (body tables stay in the overview), a repeated key. Absent: unchanged. The entry form, print pages and authored kind: full \| html \| react pages are not affected. Not accepted on an object extension. Not the form-level FormSchema.fieldTabs, which lists field names. | | **stageField** | `string \| false` | optional | [ADR-0085] Lifecycle stage field (linear/ordered), or false to declare the status field non-linear and suppress stage heuristics. Absent = heuristic detection allowed. When the named field carries options, it must be a single-value `select` / `radio` with inline `options`, each declaring its `kind` ('open' / 'won' / 'lost'); a picklist-backed or multi-value stage field is refused. A name that resolves to no declared field, or a field with no options, is not judged at parse. | | **editMode** | `Enum<'modal' \| 'page'>` | optional | Edit-interaction intent for records of this object: 'modal' opens the edit form as a dialog over the current view; 'page' navigates to a dedicated full-page edit route. Absent = the renderer picks its own default (objectui defaults to modal). Cross-renderer intent, not pixel styling (family). | | **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047) | diff --git a/packages/spec/docs/references/system/migration.md b/packages/spec/docs/references/system/migration.md index 1dfea2c5735..dd5dd494e6c 100644 --- a/packages/spec/docs/references/system/migration.md +++ b/packages/spec/docs/references/system/migration.md @@ -363,6 +363,7 @@ Create a new object | **highlightFields** | `string[]` | optional | [ADR-0085] Ordered most-important fields; first entry wins where only one fits. Drives default list and related-list columns, cards, hover cards, previews and the record picker; the default record page draws no strip from it. Renamed from compactLayout. | | **relatedLists** | `(string \| { list: string; label?: string; columns?: string[] })[]` | optional | The record page's tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. A child list another package brings is not hidden by it: that package places the list with its object extension's place entry (an `{ list, after \| before }` entry), and an unplaced one shows at the end of the tabs, before approvals and the activity stream; this object may also name it, which a build accepts only when that package is in the stack, and then its own position wins. Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be `{ list, label?, columns? }` to give that list its own title and child-field columns (wins over the child FK's relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused by os validate / os build (which leave a sys_ / cloud_ / ai_ name to the runtime) and by a metadata write that names no package; a write into a package stores it and the record page places nothing for it. A columns name that resolves to no field of the child (a dotted name is walked through the child's relationships, as relatedListColumns is) is refused. | | **pinOverview** | `boolean` | optional | Whether the desktop full standard record page pins the overview (the record's own fields) to a left column beside its other tabs. Absent or true: derived as before (a full page wide enough for both columns, with another tab and no related table among the fields, pins). false: the desktop full page never pins, at any width; the overview is its first tab, open by default, and its fields lay out by width in up to three columns, also when the overview holds a related table. Read by the desktop full standard record page alone: the side preview and a phone draw the same either way, and print pages and authored kind: full \| html \| react pages do not read it. Not accepted on an object extension. | +| **fieldTabs** | `{ key: string; groups: string[] }[]` | optional | Field groups the standard record page draws as tabs of their own, right after the overview and before the related-list tabs, in this order. Each entry is `{ key, groups }`: key names the tab (snake_case; its page address is fields:``), groups lists keys of this object's fieldGroups, drawn in that order and taken out of the overview. The tab's title and icon are its first group's. The reader cannot move or hide these tabs. Refused: a group the object does not declare, a group two tabs name, a group with relatedList (body tables stay in the overview), a repeated key. Absent: unchanged. The entry form, print pages and authored kind: full \| html \| react pages are not affected. Not accepted on an object extension. Not the form-level FormSchema.fieldTabs, which lists field names. | | **stageField** | `string \| false` | optional | [ADR-0085] Lifecycle stage field (linear/ordered), or false to declare the status field non-linear and suppress stage heuristics. Absent = heuristic detection allowed. When the named field carries options, it must be a single-value `select` / `radio` with inline `options`, each declaring its `kind` ('open' / 'won' / 'lost'); a picklist-backed or multi-value stage field is refused. A name that resolves to no declared field, or a field with no options, is not judged at parse. | | **editMode** | `Enum<'modal' \| 'page'>` | optional | Edit-interaction intent for records of this object: 'modal' opens the edit form as a dialog over the current view; 'page' navigates to a dedicated full-page edit route. Absent = the renderer picks its own default (objectui defaults to modal). Cross-renderer intent, not pixel styling (family). | | **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047) | diff --git a/packages/spec/docs/references/system/migration.part-2.md b/packages/spec/docs/references/system/migration.part-2.md index b3656778ffb..8ab56a69140 100644 --- a/packages/spec/docs/references/system/migration.part-2.md +++ b/packages/spec/docs/references/system/migration.part-2.md @@ -207,6 +207,7 @@ Create a new object | **highlightFields** | `string[]` | optional | [ADR-0085] Ordered most-important fields; first entry wins where only one fits. Drives default list and related-list columns, cards, hover cards, previews and the record picker; the default record page draws no strip from it. Renamed from compactLayout. | | **relatedLists** | `(string \| { list: string; label?: string; columns?: string[] })[]` | optional | The record page's tabs beside the overview, in order. Absent: every related list shows (owned master_detail children, then lookup children), then attachments, approvals and the activity stream, as before. Declared: only the lists named here show, in this order; leaving one out hides its tab. A child list another package brings is not hidden by it: that package places the list with its object extension's place entry (an `{ list, after \| before }` entry), and an unplaced one shows at the end of the tabs, before approvals and the activity stream; this object may also name it, which a build accepts only when that package is in the stack, and then its own position wins. Each entry is a child object name (e.g. "task"), object.field when that child has more than one relationship to this object (e.g. "event.related_to"), or a built-in tab: "sys_attachment" (attachments, still only when enable.files is on; not shown when unlisted), "sys_approval_request" (approvals, still only when the record has requests; when unlisted it follows the listed tabs), "sys_activity" (the activity stream of activities, discussion and changes; when unlisted it comes last). An entry may instead be `{ list, label?, columns? }` to give that list its own title and child-field columns (wins over the child FK's relatedListTitle / relatedListColumns, used wherever the list is drawn); a built-in tab is written only as its bare name. relatedList: false on the FK still hides a list; body tables placed by fieldGroups are not hidden by this list. A name whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere; one whose child exists nowhere is refused by os validate / os build (which leave a sys_ / cloud_ / ai_ name to the runtime) and by a metadata write that names no package; a write into a package stores it and the record page places nothing for it. A columns name that resolves to no field of the child (a dotted name is walked through the child's relationships, as relatedListColumns is) is refused. | | **pinOverview** | `boolean` | optional | Whether the desktop full standard record page pins the overview (the record's own fields) to a left column beside its other tabs. Absent or true: derived as before (a full page wide enough for both columns, with another tab and no related table among the fields, pins). false: the desktop full page never pins, at any width; the overview is its first tab, open by default, and its fields lay out by width in up to three columns, also when the overview holds a related table. Read by the desktop full standard record page alone: the side preview and a phone draw the same either way, and print pages and authored kind: full \| html \| react pages do not read it. Not accepted on an object extension. | +| **fieldTabs** | `{ key: string; groups: string[] }[]` | optional | Field groups the standard record page draws as tabs of their own, right after the overview and before the related-list tabs, in this order. Each entry is `{ key, groups }`: key names the tab (snake_case; its page address is fields:``), groups lists keys of this object's fieldGroups, drawn in that order and taken out of the overview. The tab's title and icon are its first group's. The reader cannot move or hide these tabs. Refused: a group the object does not declare, a group two tabs name, a group with relatedList (body tables stay in the overview), a repeated key. Absent: unchanged. The entry form, print pages and authored kind: full \| html \| react pages are not affected. Not accepted on an object extension. Not the form-level FormSchema.fieldTabs, which lists field names. | | **stageField** | `string \| false` | optional | [ADR-0085] Lifecycle stage field (linear/ordered), or false to declare the status field non-linear and suppress stage heuristics. Absent = heuristic detection allowed. When the named field carries options, it must be a single-value `select` / `radio` with inline `options`, each declaring its `kind` ('open' / 'won' / 'lost'); a picklist-backed or multi-value stage field is refused. A name that resolves to no declared field, or a field with no options, is not judged at parse. | | **editMode** | `Enum<'modal' \| 'page'>` | optional | Edit-interaction intent for records of this object: 'modal' opens the edit form as a dialog over the current view; 'page' navigates to a dedicated full-page edit route. Absent = the renderer picks its own default (objectui defaults to modal). Cross-renderer intent, not pixel styling (family). | | **listViews** | `Record; type?: Enum<'grid' \| 'kanban' \| 'gallery' \| 'calendar' \| 'timeline' \| 'gantt' \| 'map' \| …>; data?: object \| object \| object; … }>` | optional | Built-in named list views (segmented tabs) shipped with the object schema — "views" mode, dropdown userFilters allowed, no page-only tabs (ADR-0047) | diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 04a164f2e3f..0c1597cc347 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -619,6 +619,9 @@ "ObjectFieldGroup": "src/data/object.zod.ts#ObjectFieldGroup (type)", "ObjectFieldGroupParsed": "src/data/object.zod.ts#ObjectFieldGroupParsed (type)", "ObjectFieldGroupSchema": "src/data/object.zod.ts#ObjectFieldGroupSchema (const)", + "ObjectFieldTab": "src/data/object.zod.ts#ObjectFieldTab (type)", + "ObjectFieldTabParsed": "src/data/object.zod.ts#ObjectFieldTabParsed (type)", + "ObjectFieldTabSchema": "src/data/object.zod.ts#ObjectFieldTabSchema (const)", "ObjectIndex": "src/data/object.zod.ts#ObjectIndex (type)", "ObjectIndexParsed": "src/data/object.zod.ts#ObjectIndexParsed (type)", "ObjectOwnership": "src/data/object.zod.ts#ObjectOwnership (type)", diff --git a/packages/spec/json-schema.manifest/data.json b/packages/spec/json-schema.manifest/data.json index 0b931c87222..a5518b3debc 100644 --- a/packages/spec/json-schema.manifest/data.json +++ b/packages/spec/json-schema.manifest/data.json @@ -131,6 +131,7 @@ "data/ObjectExtensionRelatedListEntryObject", "data/ObjectExternalBinding", "data/ObjectFieldGroup", + "data/ObjectFieldTab", "data/ObjectOwnershipEnum", "data/ObjectRequiredPermissions", "data/OracleConfig", diff --git a/packages/spec/liveness/object.json b/packages/spec/liveness/object.json index 5f2d02efc21..14429b382e9 100644 --- a/packages/spec/liveness/object.json +++ b/packages/spec/liveness/object.json @@ -170,6 +170,30 @@ "producer": "ui/packages/app-shell/src/views/RecordDetailView.tsx#RecordDetailView (threads the served object's `pinOverview` into `RecordPageColumns` on the desktop full record page; not on a phone)", "note": "ADR-0085 Note of 2026-11-27: a ruled exception (an object key that only re-arranges the synthesized record page). Not an object-extension key and not in CUSTOM_ARRANGEMENT_KEYS." }, + "fieldTabs": { + "status": "live", + "verifiedAt": "2026-11-30", + "evidenceScope": "in-repo", + "evidence": "ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts#fieldTabPlacement (each entry's groups come out of the overview's sections, in its order; a group the object does not declare or another tab took is skipped, a tab left with none is not placed); ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts#buildDefaultTabs (a `fields:` tab per entry right after the overview, before every related and built-in tab, its title and icon its first group's); ui/packages/plugin-detail/src/RecordPageColumns.tsx#RecordPageColumns (the laid-out page draws each tab whose groups are drawn, with its own empty-field row; the reader's arrangement neither moves nor hides it); ui/packages/app-shell/src/views/RecordDetailView.tsx#RecordDetailView (a `?section=` cited inside a field tab opens that tab first); packages/lint/src/data-model-rules.ts#lintDataModel (`object/field-tabs-empty-overview` warns when every field is moved out)", + "producer": "ui/packages/app-shell/src/views/RecordDetailView.tsx#RecordDetailView (synthesizes the standard record page from the served object, its `fieldTabs` included)", + "note": "ADR-0085 Note of 2026-11-27: a ruled exception (an object key that only re-arranges the synthesized record page), the second key of that ruling beside pinOverview. Not an object-extension key and not in CUSTOM_ARRANGEMENT_KEYS. Not the form-level FormSchema.fieldTabs.", + "children": { + "key": { + "status": "live", + "verifiedAt": "2026-11-30", + "evidenceScope": "in-repo", + "evidence": "ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts#buildDefaultTabs (the tab's value `fields:`, the `?related=` address); ui/packages/plugin-detail/src/synth/recordPageColumns.ts#recordPageColumnOfTab (`fields:` lays out as a field tab)", + "note": "The tab's address on the record page; unique within the object." + }, + "groups": { + "status": "live", + "verifiedAt": "2026-11-30", + "evidenceScope": "in-repo", + "evidence": "ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts#fieldTabPlacement (the named groups' sections, in this order, are the tab's body and leave the overview); packages/spec/src/data/object.zod.ts#refuseDishonestFieldTabs (an undeclared group, a group two tabs name and a related-list group are refused)", + "note": "Keys of the object's own fieldGroups." + } + } + }, "stageField": { "status": "live", "proof": "packages/qa/dogfood/test/semantic-roles.dogfood.test.ts#semantic-roles-served", diff --git a/packages/spec/liveness/state-counts/object.md b/packages/spec/liveness/state-counts/object.md index 89a58bc8ede..9b5400d17eb 100644 --- a/packages/spec/liveness/state-counts/object.md +++ b/packages/spec/liveness/state-counts/object.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `object` | 98 | 0 | 0 | 1 | 1 | 100 | +| `object` | 100 | 0 | 0 | 1 | 1 | 102 | diff --git a/packages/spec/src/compose-stacks-collection-pipe-arm.test.ts b/packages/spec/src/compose-stacks-collection-pipe-arm.test.ts index dff46d04225..7959ab3ef03 100644 --- a/packages/spec/src/compose-stacks-collection-pipe-arm.test.ts +++ b/packages/spec/src/compose-stacks-collection-pipe-arm.test.ts @@ -255,6 +255,7 @@ describe('MAIN — the preprocess-wrapped collection key is IN the refusal set', 'activityMilestones', 'highlightFields', 'relatedLists', + 'fieldTabs', 'listViews', 'searchableFields', 'membershipKeys', @@ -313,6 +314,7 @@ describe("TODAY-INVARIANCE — the fix moves no key on today's ObjectSchema", () 'activityMilestones', 'highlightFields', 'relatedLists', + 'fieldTabs', 'listViews', 'searchableFields', 'membershipKeys', diff --git a/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts b/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts index 0c01604f479..e30a4df1642 100644 --- a/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts +++ b/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts @@ -68,6 +68,7 @@ const COLLECTION_KEYS_IN_SHAPE_ORDER = [ 'activityMilestones', 'highlightFields', 'relatedLists', + 'fieldTabs', 'listViews', 'searchableFields', 'membershipKeys', @@ -142,6 +143,7 @@ describe("composeStacks objectConflict: 'merge' — a collection both objects de ['searchableFields', ['title'], ['title', 'body']], ['highlightFields', ['title'], ['body']], ['relatedLists', ['task'], ['event']], + ['fieldTabs', [{ key: 'content', groups: ['content'] }], [{ key: 'content', groups: ['content', 'import'] }]], ['activityMilestones', [{ name: 'm_a' }], [{ name: 'm_b' }]], ['requiredPermissions', ['crm.read'], ['billing.read']], ['attachedOnRead', { viewer: { can_act: 'boolean' } }, { viewer: { can_act: 'boolean', is_submitter: 'boolean' } }], diff --git a/packages/spec/src/data/object.metadata-form.ts b/packages/spec/src/data/object.metadata-form.ts index 9457f797e02..529d106111b 100644 --- a/packages/spec/src/data/object.metadata-form.ts +++ b/packages/spec/src/data/object.metadata-form.ts @@ -85,6 +85,21 @@ export const objectForm = defineMetadataForm({ // the tab list it lays out. A boolean row: an untouched switch writes // nothing, so an object keeps the derived pin until an author sets it. { field: 'pinOverview', type: 'boolean', colSpan: 1, helpText: 'Whether the wide desktop record page pins the overview (the record\'s own fields) to a left column beside the other tabs. Unset: it pins as before wherever the page is wide enough and has other tabs; an untouched switch writes nothing, so it reads off while the page still pins. Off once set: the desktop full page never pins, at any width, and the overview is its first tab, open by default, its fields laid out by width in up to three columns, also when the overview holds a related table. The side preview and a phone draw the same either way.' }, + // ADR-0085 (Note of 2026-11-27, objectstack#37802) — the field tabs, + // the second key of that ruling, beside the layout switch: a repeater + // over the entry's two keys, as `fieldGroups` below. `groups` is a list + // of the object's own group keys, a `tags` row as a group's `fields` + // is; the parse refuses a key no group declares. + { + field: 'fieldTabs', + type: 'repeater', + colSpan: 2, + helpText: 'Field groups drawn as tabs of the standard record page, right after the overview, in this order, before the related lists. Each tab names the groups it draws, in order; the overview keeps the groups no tab names and the fields in no group. The tab takes its title and icon from its first group. The entry form, print pages and authored pages are unchanged. A group named twice, a group no Field Groups entry declares, and a related-list group are refused.', + fields: [ + { field: 'key', label: 'Key', type: 'text', required: true, helpText: 'Machine key in snake_case, unique among this object\'s field tabs; the tab\'s address on the record page (fields:key).' }, + { field: 'groups', label: 'Groups', type: 'tags', required: true, helpText: 'The field group keys this tab draws, in order (at least one). A group a related list fills stays in the overview and is refused here.' }, + ], + }, { field: 'searchableFields', widget: 'string-tags', colSpan: 2, helpText: 'Field names the $search query matches (ADR-0061): the default for the record picker, list quick-search and global search; a view may narrow it. Unset, search uses the name/title field plus short-text fields. Each entry must name a stored field of this object — an unknown name or a virtual formula field is refused at publish.' }, // #19332 (flight G2a of ruling record 5861442317) — the object's field // groups, the ADR-0085 layout role beside `nameField` / `highlightFields`. diff --git a/packages/spec/src/data/object.test.ts b/packages/spec/src/data/object.test.ts index febbfe99305..4fb2ed589bd 100644 --- a/packages/spec/src/data/object.test.ts +++ b/packages/spec/src/data/object.test.ts @@ -2042,6 +2042,105 @@ describe('ObjectSchema.pinOverview — the record page layout switch', () => { }); }); +describe('ObjectSchema.fieldTabs — field groups drawn as record page tabs', () => { + const policy = (extra: Record) => ({ + name: 'policy', + fields: { + title: { type: 'text', group: 'basic' }, + body: { type: 'textarea', group: 'content' }, + source_file: { type: 'text', group: 'import' }, + }, + fieldGroups: [ + { key: 'basic', label: 'Basic' }, + { key: 'content', label: 'Content' }, + { key: 'import', label: 'Original' }, + { key: 'lines', label: 'Lines', relatedList: 'policy_line' }, + ], + ...extra, + }); + const issuesOf = (input: unknown) => { + const result = ObjectSchema.safeParse(input); + expect(result.success).toBe(false); + return result.success ? [] : result.error.issues; + }; + + it('parses absent, and a valid two-tab declaration end to end, keeping order', () => { + expect(ObjectSchema.parse(policy({})).fieldTabs).toBeUndefined(); + const tabs = [ + { key: 'content', groups: ['content', 'import'] }, + { key: 'basics', groups: ['basic'] }, + ]; + expect(ObjectSchema.parse(policy({ fieldTabs: tabs })).fieldTabs).toEqual(tabs); + expect(ObjectSchema.create(policy({ fieldTabs: tabs }) as never).fieldTabs).toEqual(tabs); + }); + + it('refuses a group the object does not declare, at the groups entry', () => { + const issues = issuesOf(policy({ fieldTabs: [{ key: 'content', groups: ['content', 'terms'] }] })); + expect(issues).toHaveLength(1); + expect(issues[0].path).toEqual(['fieldTabs', 0, 'groups', 1]); + expect(issues[0].message).toContain("'terms'"); + expect(issues[0].message).toContain('FormSchema.fieldTabs'); + }); + + it('refuses every group on an object that declares no fieldGroups', () => { + const issues = issuesOf({ name: 'policy', fields: {}, fieldTabs: [{ key: 'content', groups: ['content'] }] }); + expect(issues.map((i) => i.path)).toEqual([['fieldTabs', 0, 'groups', 0]]); + }); + + it('refuses a group two tabs name, naming the first tab', () => { + const issues = issuesOf(policy({ + fieldTabs: [ + { key: 'content', groups: ['content'] }, + { key: 'more', groups: ['import', 'content'] }, + ], + })); + expect(issues).toHaveLength(1); + expect(issues[0].path).toEqual(['fieldTabs', 1, 'groups', 1]); + expect(issues[0].message).toContain("'content' and 'more'"); + }); + + it('refuses a group that places a related table', () => { + const issues = issuesOf(policy({ fieldTabs: [{ key: 'lines', groups: ['lines'] }] })); + expect(issues).toHaveLength(1); + expect(issues[0].path).toEqual(['fieldTabs', 0, 'groups', 0]); + expect(issues[0].message).toContain('policy_line'); + }); + + it('refuses a repeated key', () => { + const issues = issuesOf(policy({ + fieldTabs: [ + { key: 'content', groups: ['content'] }, + { key: 'content', groups: ['import'] }, + ], + })); + expect(issues).toHaveLength(1); + expect(issues[0].path).toEqual(['fieldTabs', 1, 'key']); + expect(issues[0].message).toContain("'content' is already a field tab's key"); + }); + + it('refuses an entry with no group, a non-snake_case key, and the form-level shape by name', () => { + expect(issuesOf(policy({ fieldTabs: [{ key: 'content', groups: [] }] }))[0].path).toEqual(['fieldTabs', 0, 'groups']); + expect(issuesOf(policy({ fieldTabs: [{ key: 'Content', groups: ['content'] }] }))[0].path).toEqual(['fieldTabs', 0, 'key']); + const formShape = issuesOf(policy({ fieldTabs: [{ key: 'content', groups: ['content'], fields: ['body'] }] })); + const unknown = formShape.find((i) => i.code === 'unrecognized_keys'); + expect(unknown).toBeDefined(); + expect(unknown!.message).toContain('FormSchema.fieldTabs'); + const labelled = issuesOf(policy({ fieldTabs: [{ key: 'content', groups: ['content'], label: 'Body' }] })); + expect(labelled.find((i) => i.code === 'unrecognized_keys')!.message).toContain('first group'); + }); + + it('an object extension refuses it, naming the object key and the form-level one', () => { + const result = ObjectExtensionSchema.safeParse({ extend: 'crm_account', fieldTabs: [{ key: 'content', groups: ['content'] }] }); + expect(result.success).toBe(false); + if (!result.success) { + const issue = result.error.issues.find((i) => i.code === 'unrecognized_keys'); + expect(issue).toBeDefined(); + expect(issue!.message).toContain('ObjectSchema.fieldTabs'); + expect(issue!.message).toContain('FormSchema.fieldTabs'); + } + }); +}); + describe('ObjectSchema.fieldGroups', () => { it('should accept an object without fieldGroups (fully optional)', () => { const result = ObjectSchema.safeParse({ diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index 78e0b0085ea..fb03dd2559b 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -1653,9 +1653,59 @@ export const ObjectFieldGroupSchema = lazySchema(() => strictObject({ // group's slot name; the key never reaches the output. }).transform((group, ctx) => lowerRequiresFeature(group, ctx, 'visibleWhen'))); +/** + * [ADR-0085, Note of 2026-11-27] One `ObjectSchema.fieldTabs` entry: a tab of + * the standard record page holding some of this object's field groups. + * + * Deliberately not the form-level `FormSchema.fieldTabs` entry + * (`@object-ui/types`), which shares the key name and claims FIELD names: + * a record-page field tab claims GROUPS, so a field keeps its group on every + * surface and only where the group is drawn changes. Each shape's refusal + * names the other key. No `label` or `icon` (v1): the tab's title and icon + * are its first group's, whose `label` is already translated. + */ +export const ObjectFieldTabSchema = lazySchema(() => strictObject({ + surface: 'this fieldTabs entry', + history: + 'An unknown key here would be dropped silently: the tab would still draw, so the author would believe ' + + 'the setting they wrote had been applied.', + aliases: { + name: 'key', + id: 'key', + fieldGroups: 'groups', + }, + guidance: { + fields: + '`fields` is the form-level `FormSchema.fieldTabs` shape (`@object-ui/types`), which claims field names. ' + + 'An object\'s `fieldTabs` entry (`ObjectSchema.fieldTabs`, the record page\'s field tabs) names field ' + + 'GROUPS: write `groups: [, …]`, and put the fields in those groups.', + label: + '`label` is not a fieldTabs entry key: a record-page field tab takes its title from its first group\'s ' + + '`label`. Order `groups` so the group whose label should title the tab comes first.', + icon: + '`icon` is not a fieldTabs entry key: a record-page field tab takes its icon from its first group\'s `icon`.', + visibleWhen: + '`visibleWhen` is not a fieldTabs entry key: a field tab is drawn when at least one of its groups is, so ' + + 'gate the groups (`fieldGroups[].visibleWhen`).', + }, +}, { + key: z.string().regex(FIELD_GROUP_KEY_PATTERN, { + message: 'A fieldTabs key must be lowercase snake_case (e.g., "content", "terms")', + }).describe('The tab\'s key (snake_case). The record page addresses the tab as fields:.').meta({ title: 'Key' }), + groups: z.array(z.string().regex(FIELD_GROUP_KEY_PATTERN, { + message: 'A fieldTabs groups entry is a fieldGroups key of this object, in snake_case (e.g., "content")', + })).min(1, { + message: 'A fieldTabs entry names at least one field group in `groups`', + }).describe('The field groups this tab holds: keys of this object\'s fieldGroups, in the order the tab draws them. The first one\'s label and icon title the tab.').meta({ title: 'Groups' }), +})); + export type ObjectFieldGroup = z.input; /** Post-parse shape of {@link ObjectFieldGroup} — defaults applied, transforms run (ADR-0122). */ export type ObjectFieldGroupParsed = z.infer; +/** One `ObjectSchema.fieldTabs` entry (objectstack#37802): a record-page field tab, `{ key, groups }`. */ +export type ObjectFieldTab = z.input; +/** Post-parse shape of {@link ObjectFieldTab} (ADR-0122). */ +export type ObjectFieldTabParsed = z.infer; /** * Base Object Schema Definition @@ -3582,6 +3632,95 @@ function refuseFieldsInRelatedListGroups(fieldGroups: unknown, fields: unknown, } } +/** + * [ADR-0085, Note of 2026-11-27] Each `fieldTabs` entry names field groups this + * object declares, each group at most once across the tabs, and none that + * places a related table. One located issue per offending `groups` entry, at + * `['fieldTabs', i, 'groups', j]`: + * + * - a key `fieldGroups` does not declare (an object with no `fieldGroups` + * declares none); + * - a group an earlier tab (or an earlier position of the same tab) already + * names, naming where it was first named; + * - a group carrying `relatedList`: a body table stays in the overview in v1. + * + * Judged here, in the object's `superRefine`, for the reason + * {@link refuseFieldsInRelatedListGroups} gives: only the object holds both + * lists. A repeated tab `key` is refused here too, at the second entry's `key` + * (`['fieldTabs', i, 'key']`): one place judges the whole list, and a + * refinement on the array itself would be one more rule the published JSON + * Schema drops. + */ +function refuseDishonestFieldTabs(fieldTabs: unknown, fieldGroups: unknown, ctx: z.RefinementCtx): void { + if (!Array.isArray(fieldTabs)) return; + const declared = new Map(); + if (Array.isArray(fieldGroups)) { + for (const group of fieldGroups) { + if (group !== null && typeof group === 'object' && typeof (group as { key?: unknown }).key === 'string') { + const key = (group as { key: string }).key; + if (!declared.has(key)) declared.set(key, group as { relatedList?: unknown }); + } + } + } + const namedBy = new Map(); + const tabKeys = new Set(); + fieldTabs.forEach((tab: unknown, index: number) => { + if (tab === null || typeof tab !== 'object') return; + const { key, groups } = tab as { key?: unknown; groups?: unknown }; + if (typeof key === 'string') { + if (tabKeys.has(key)) { + ctx.addIssue({ + code: 'custom', + path: ['fieldTabs', index, 'key'], + message: `fieldTabs[].key must be unique within an object: '${key}' is already a field tab's key, and each record-page field tab has its own`, + }); + } + tabKeys.add(key); + } + if (!Array.isArray(groups)) return; + const tabName = typeof key === 'string' ? `'${key}'` : `#${index + 1}`; + groups.forEach((group: unknown, at: number) => { + if (typeof group !== 'string') return; + const path = ['fieldTabs', index, 'groups', at]; + const declaration = declared.get(group); + if (!declaration) { + ctx.addIssue({ + code: 'custom', + path, + message: + `Field tab ${tabName} names the field group '${group}', which this object's \`fieldGroups\` does not declare. ` + + 'A fieldTabs entry (`ObjectSchema.fieldTabs`) names keys of the object\'s own `fieldGroups`: declare the ' + + 'group, or name a declared one. (A form\'s tabbed field layout lists field names; that is the form-level ' + + '`FormSchema.fieldTabs`.)', + }); + return; + } + const first = namedBy.get(group); + if (first !== undefined) { + ctx.addIssue({ + code: 'custom', + path, + message: + `The field group '${group}' is named by two field tabs, ${first} and ${tabName}. A group is drawn in one ` + + 'place: remove it from one of the two `groups` lists.', + }); + return; + } + namedBy.set(group, tabName); + if (typeof declaration.relatedList === 'string') { + ctx.addIssue({ + code: 'custom', + path, + message: + `Field tab ${tabName} names the field group '${group}', which places the related list ` + + `'${declaration.relatedList}' (its \`relatedList\`). A body table stays in the overview: name only ` + + 'groups of fields in `fieldTabs`.', + }); + } + }); + }); +} + /** * A field group's `fields` list and a field's own `group` are two spellings of * one membership (`ObjectFieldGroupSchema.fields`), so where both speak they @@ -4950,6 +5089,29 @@ const ObjectSchemaBase = strictObject( * object it is the base package's to write. */ pinOverview: z.boolean().optional().describe('Whether the desktop full standard record page pins the overview (the record\'s own fields) to a left column beside its other tabs. Absent or true: derived as before (a full page wide enough for both columns, with another tab and no related table among the fields, pins). false: the desktop full page never pins, at any width; the overview is its first tab, open by default, and its fields lay out by width in up to three columns, also when the overview holds a related table. Read by the desktop full standard record page alone: the side preview and a phone draw the same either way, and print pages and authored kind: full | html | react pages do not read it. Not accepted on an object extension.'), + /** + * [ADR-0085, Note of 2026-11-27, a ruled exception] Field groups the + * standard record page draws as tabs of their own instead of in the + * overview. Each entry names one tab (`key`, the `fields:` tab id in + * the page address) and the field groups it holds (`groups`, keys of this + * object's `fieldGroups`, drawn in that order). + * + * The tabs come right after the overview, in declared order, before every + * related-list and built-in tab; the reader cannot move or hide them. A tab + * takes its title and icon from its first group. The overview keeps every + * group no tab names, the ungrouped fields, the approval band and the + * record's meta line. On a pinned page (`pinOverview`) the first field tab + * is the tab open beside the overview. + * + * Refused at parse: a group this object does not declare, a group two tabs + * name, a group that places a related table (`relatedList`; body tables stay + * in the overview), and a repeated `key`. Absent: the page is unchanged. + * Read by the standard record page alone: the entry form, print pages and + * authored `kind: 'full' | 'html' | 'react'` pages lay out every group as + * before. Not an object-extension key, and not the form-level + * `FormSchema.fieldTabs` (`@object-ui/types`), which lists field names. + */ + fieldTabs: z.array(ObjectFieldTabSchema).optional().describe('Field groups the standard record page draws as tabs of their own, right after the overview and before the related-list tabs, in this order. Each entry is { key, groups }: key names the tab (snake_case; its page address is fields:), groups lists keys of this object\'s fieldGroups, drawn in that order and taken out of the overview. The tab\'s title and icon are its first group\'s. The reader cannot move or hide these tabs. Refused: a group the object does not declare, a group two tabs name, a group with relatedList (body tables stay in the overview), a repeated key. Absent: unchanged. The entry form, print pages and authored kind: full | html | react pages are not affected. Not accepted on an object extension. Not the form-level FormSchema.fieldTabs, which lists field names.'), /** * [ADR-0085] Semantic role: the field that represents the record's LINEAR * lifecycle (an ordered pipeline / stage progression). A string names the @@ -5439,6 +5601,9 @@ const ObjectSchemaBase = strictObject( // A group's `fields` list and a field's own `group` agree where both speak. // See the helper's docblock. refuseFieldGroupMembershipConflicts(object.fieldGroups, object.fields, ctx); + // [ADR-0085, Note of 2026-11-27] Each field tab names declared groups of + // fields, each once. See the helper's docblock. + refuseDishonestFieldTabs(object.fieldTabs, object.fieldGroups, ctx); // [ADR-0055 §1 · #23100 ruling B, as amended by #30905 ruling A] Exactly one // master `master_detail` under `controlled_by_parent` (the required one, or // the only one declared `required: false`) — the one master relation the @@ -7122,6 +7287,12 @@ export const ObjectExtensionSchema = lazySchema(() => strictObject({ '`pinOverview` cannot be contributed through an object extension: whether the record page pins ' + 'the overview is declared on the object itself (`ObjectSchema.pinOverview`) by the package that ' + 'defines it.', + // [ADR-0085, Note of 2026-11-27] The record page's field tabs are the + // object's own, like `pinOverview`: not in `CUSTOM_ARRANGEMENT_KEYS`. + fieldTabs: + '`fieldTabs` cannot be contributed through an object extension: which field groups the record page ' + + 'draws as tabs is declared on the object itself (`ObjectSchema.fieldTabs`) by the package that ' + + 'defines it. (A form\'s tabbed field layout is a different key, the form-level `FormSchema.fieldTabs`.)', membershipKeys: '`membershipKeys` cannot be contributed through an object extension: a membership key is ' + 'declared by the package that owns the roster object whose rows define it. Declare the key on ' + diff --git a/ui/packages/app-shell/src/views/RecordDetailView.citedSectionFieldTab-37802.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.citedSectionFieldTab-37802.test.tsx new file mode 100644 index 00000000000..7bd8a205109 --- /dev/null +++ b/ui/packages/app-shell/src/views/RecordDetailView.citedSectionFieldTab-37802.test.tsx @@ -0,0 +1,218 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37802 — a cited section (`?section=ANCHOR`, ADR-0160 D9) whose + * field sits in one of the object's field tabs (`ObjectSchema.fieldTabs`) + * opens that tab first, then scrolls to and marks the heading, through the + * REAL `RecordDetailView` (the harness is objectstack#37365's): + * + * - the `body` group drawn as the tab `fields:body`: `?section=scope` opens + * that tab (`?related=fields:body` beside `?section=` in the address) + * and marks `Scope` in it; + * - CONTROL: the same object without `fieldTabs` marks the heading in the + * overview and opens no tab; + * - a cited field the overview draws (`notes`, the `basic` group) opens no tab + * beside the field tab. + */ + +import * as React from 'react'; +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, cleanup, within, act, waitFor } from '@testing-library/react'; +import { MemoryRouter, useLocation } from 'react-router-dom'; + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: { id: 'u-ada', name: 'Ada', image: null }, activeOrganization: null }), + createAuthenticatedFetch: () => vi.fn(), +})); +vi.mock('@object-ui/collaboration', async (importOriginal) => ({ + ...(await importOriginal>()), + useRecordPresence: () => [], + PresenceAvatars: () => null, +})); +vi.mock('sonner', () => ({ + toast: Object.assign(vi.fn(), { + success: vi.fn(), + error: vi.fn(), + info: vi.fn(), + warning: vi.fn(), + loading: vi.fn(), + dismiss: vi.fn(), + }), +})); +vi.mock('./ActionParamDialog', () => ({ ActionParamDialog: () => null })); +vi.mock('./ActionResultDialog', () => ({ ActionResultDialog: () => null })); +vi.mock('./FlowRunner', () => ({ FlowRunner: () => null })); +vi.mock('./MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }), +})); + +// The markdown face is lazily loaded by the cell renderer; importing it here +// moves its load into the import phase (ui/AGENTS.md, flaky-test discipline). +import '../../../fields/src/widgets/MarkdownContent'; +import { I18nProvider } from '@object-ui/i18n'; +import { MetadataCtx } from '@object-ui/react'; +import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; +import { RecordDetailView } from './RecordDetailView'; +import { RECORD_SECTION_TARGET_ATTR } from './recordSectionAnchor'; + +const OBJECT_NAME = 'policy'; +const RECORD_ID = 'pol_7'; + +const BODY = ['# Intro', '', 'Hello.', '', '## Scope', '', 'Everyone.'].join('\n'); +const NOTES = ['# Steps', '', 'Sign the sheet.'].join('\n'); + +const FIELDS = { + id: { type: 'text', label: 'Id' }, + title: { type: 'text', label: 'Title', group: 'basic' }, + content: { type: 'markdown', label: 'Content', group: 'body' }, + notes: { type: 'textarea', label: 'Notes', group: 'basic' }, +}; +const FIELD_GROUPS = [ + { key: 'basic', label: 'Basic' }, + { key: 'body', label: 'Body' }, +]; +/** The policy as served: its body group drawn as a field tab, or (CONTROL) in the overview. */ +const objectsWith = (fieldTabs?: unknown) => [ + { name: OBJECT_NAME, label: 'Policy', fields: FIELDS, fieldGroups: FIELD_GROUPS, enable: { feeds: false }, ...(fieldTabs ? { fieldTabs } : {}) }, +]; +let OBJECTS = objectsWith(); + +function makeDataSource(content = BODY) { + return { + find: vi.fn(async () => ({ data: [] })), + findOne: vi.fn(async (_o: string, id: string) => ({ id, title: `Policy ${id}`, content, notes: NOTES })), + create: vi.fn(async (_o: string, data: any) => ({ id: 'x', ...data })), + update: vi.fn(async (_o: string, id: string, patch: any) => ({ id, ...patch })), + delete: vi.fn(async () => true), + } as any; +} + +function metadata() { + return { + objects: OBJECTS, + pages: [], + loading: false, + error: null, + refresh: async () => {}, + invalidate: () => {}, + ensureType: async () => [], + getItem: async () => null, + getItemsByType: (type: string) => (type === 'object' ? OBJECTS : []), + getTypeStatus: () => 'ready', + } as any; +} + +const FULL = { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true }; +const PERMS = { + authenticated: true, + userId: 'u-ada', + tenantId: null, + positions: ['member'], + hasAnyQueue: false, + objectsUsingQueues: [], + permissionSets: ['member'], + objects: { [OBJECT_NAME]: FULL }, + fields: {}, +} as MePermissionsAuthenticatedResponse; + +/** The router's current search, written after each render the probe makes. */ +const probe = { search: '' }; +function LocationProbe() { + const location = useLocation(); + React.useEffect(() => { + probe.search = location.search; + }); + return null; +} + +async function mount(search: string) { + // The page opens a tab off the window's address (`openEnlargedRelated`), as + // the browser router keeps it: the memory router's entry is mirrored there. + window.history.replaceState(null, '', `/apps/compliance/${OBJECT_NAME}/record/${RECORD_ID}${search}`); + const rendered = render( + + + + + + {}} + objectNameOverride={OBJECT_NAME} + recordIdOverride={RECORD_ID} + /> + + + + , + ); + await within(rendered.container) + .findAllByText(`Policy ${RECORD_ID}`, undefined, { timeout: 4000 }) + .catch(() => undefined); + await act(async () => {}); + return rendered; +} + +let scrolled: HTMLElement[] = []; +const originalScroll = HTMLElement.prototype.scrollIntoView; + +beforeEach(() => { + scrolled = []; + probe.search = ''; + HTMLElement.prototype.scrollIntoView = function (this: HTMLElement) { + scrolled.push(this); + }; + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } })), + ); +}); + +afterEach(async () => { + cleanup(); + // The page forgets the section it opened once it has stayed unmounted (objectstack#37487 S5). + await new Promise((resolve) => setTimeout(resolve, 0)); + HTMLElement.prototype.scrollIntoView = originalScroll; + vi.unstubAllGlobals(); + vi.clearAllMocks(); + OBJECTS = objectsWith(); + window.history.replaceState(null, '', '/'); +}); + +const marked = (root: HTMLElement) => Array.from(root.querySelectorAll(`[${RECORD_SECTION_TARGET_ATTR}]`)); +const openTab = () => new URLSearchParams(probe.search).get('related'); +const citedSection = () => new URLSearchParams(probe.search).get('section'); + +describe('a cited section inside a field tab (objectstack#37802)', () => { + it('opens the field tab first, then marks the heading in it', async () => { + OBJECTS = objectsWith([{ key: 'body', groups: ['body'] }]); + const { container } = await mount('?section=scope'); + await waitFor(() => expect(openTab()).toBe('fields:body'), { timeout: 4000 }); + // The citation stays in the address beside the open tab. + expect(citedSection()).toBe('scope'); + await waitFor(() => expect(marked(container)).toHaveLength(1), { timeout: 4000 }); + const heading = marked(container)[0]; + expect(heading.textContent).toBe('Scope'); + expect(heading.closest('[data-record-field-tab="fields:body"]')).not.toBeNull(); + expect(scrolled).toEqual([heading]); + }); + + it('CONTROL: without fieldTabs the heading is marked in the overview and no tab opens', async () => { + const { container } = await mount('?section=scope'); + await waitFor(() => expect(marked(container)).toHaveLength(1), { timeout: 4000 }); + expect(marked(container)[0].closest('[data-record-field-tab]')).toBeNull(); + expect(openTab()).toBeNull(); + }); + + it('a cited field the overview draws opens no tab beside the field tab', async () => { + OBJECTS = objectsWith([{ key: 'body', groups: ['body'] }]); + await mount('?section=steps'); + await waitFor(() => expect(scrolled).toHaveLength(1), { timeout: 4000 }); + expect(scrolled[0].getAttribute('data-detail-field')).toBe('notes'); + expect(openTab()).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index eafcaf7c495..494590a6ffa 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -10,7 +10,7 @@ import { useState, useEffect, useLayoutEffect, useCallback, useContext, useMemo, useRef, type ReactElement } from 'react'; import { useParams, useNavigate, useLocation, useSearchParams, Link } from 'react-router-dom'; -import { activityRowToFeedItem, buildCommentThreads, CommentsButton, CommentsPage, RecordCommentsInPanelContext, composeImpersonatedActor, IMPERSONATED_ACTOR_FALLBACK, auditEntriesToFeedItems, bodyTableIdsOf, claimQueuedRecord, RECORD_PAGE_TIMELINE_PANEL, RECORD_TIMELINE_PANEL_MAX_ENTRIES, RecordFieldChangesContext, RecordFieldHistoryContext, RecordTimelineTotalContext, RecordViewApprovalsContext, DefaultRecordPageContext, EMPTY_RELATED_ARRANGEMENT, InlineEditSaveBar, RECORD_PAGE_DETAILS_WIDTH, RecordBodyTablesContext, RecordMetaFooter, RecordPageColumns, buildDefaultPageColumns, buildDefaultPageSchema, extractMentions, recordSitsInQueue, resolveTitleField, useQueueClaimOffered, useRecordEditable, useRecordPageTier } from '@object-ui/plugin-detail'; +import { activityRowToFeedItem, buildCommentThreads, CommentsButton, CommentsPage, RecordCommentsInPanelContext, composeImpersonatedActor, IMPERSONATED_ACTOR_FALLBACK, auditEntriesToFeedItems, bodyTableIdsOf, claimQueuedRecord, RECORD_PAGE_TIMELINE_PANEL, RECORD_TIMELINE_PANEL_MAX_ENTRIES, RecordFieldChangesContext, RecordFieldHistoryContext, RecordTimelineTotalContext, RecordViewApprovalsContext, DefaultRecordPageContext, EMPTY_RELATED_ARRANGEMENT, InlineEditSaveBar, RECORD_PAGE_DETAILS_WIDTH, RecordBodyTablesContext, RecordMetaFooter, RecordPageColumns, buildDefaultPageColumns, buildDefaultPageSchema, extractMentions, fieldTabIdOfField, recordSitsInQueue, resolveTitleField, useQueueClaimOffered, useRecordEditable, useRecordPageTier } from '@object-ui/plugin-detail'; import { isRefusedFeedRead } from '@object-ui/plugin-detail/core'; // objectstack#36075 — the comment panel's unresolved count and the moderator's verdict. import { unresolvedThreadCount, useRecordVerdict } from '@object-ui/plugin-detail'; @@ -925,6 +925,29 @@ const ignoreArrangementChange = (): void => {}; let lastCitedSectionOpen: { target: string; opened: string } | null = null; let mountedRecordPages = 0; +/** + * objectstack#37802 — opens the field tab a cited section sits in, once per + * citation (`citation` spells the record, anchor and chip click, as the + * section effect's key does), in place of the entry: a tab switch afterwards + * keeps the citation and opens nothing. Draws nothing. + */ +function OpenCitedFieldTab({ + tab, + citation, + open, +}: { + tab: string; + citation: string; + open: (id: string, options?: { replace?: boolean }) => void; +}): null { + useEffect(() => { + open(tab, { replace: true }); + // Once per citation: `open` is re-made on every navigation. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [tab, citation]); + return null; +} + /** Whether a cited-section open is a new one, and record it when it is. */ function claimCitedSectionOpen(target: string, opened: string): boolean { const last = lastCitedSectionOpen; @@ -5835,6 +5858,16 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // page and for a page whose strip the partition cannot read, which is drawn // as written, tabs and all. const pageColumns = pageColumnsEligible ? buildDefaultPageColumns(renderedPage) : null; + // objectstack#37802 — a cited section (`?section=`) whose field sits in one + // of the object's field tabs (`fieldTabs`): that tab opens first + // (`OpenCitedFieldTab`, drawn beside the laid-out page), and the section + // effect above finds the heading once the tab draws it. A cited field the + // overview draws opens nothing. + const citedFieldTab = + pageColumns && citedSectionCandidates.length > 0 + && citedSectionCandidates.every((c) => fieldTabIdOfField(pageColumns, objectDef, c.field) !== null) + ? fieldTabIdOfField(pageColumns, objectDef, citedSectionCandidates[0].field) + : null; // The child objects' field definitions this view already holds, for the // related counts asked up front (objectstack#27056): the relationship's // arity is read off them instead of a schema read first. @@ -6581,6 +6614,9 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri + {citedFieldTab && citedSectionKey && ( + + )} ` tab per entry right after it, before +every related and built-in tab (`fieldTabPlacement`), and +`buildDefaultPageColumns` hands them to `RecordPageColumns` as +`columns.fieldTabs`. The laid-out page draws a tab whose groups are drawn on +this record (a group's `visibleWhen` is judged where the tab row is built), +gives each tab its own empty-field row, draws a one-group tab without its +group's heading, and offers no move or hide on it. They count as other tabs +for the pin. `fieldTabIdOfField` names the tab a field sits in, which the host +opens for a cited `?section=`. + On a pinned page the left column narrows on its own to leave the tabs 400 px, never below 320 px; under that the page is no longer pinned and the details become its first tab again. The divider between the column and the tabs is a diff --git a/ui/packages/plugin-detail/src/RecordPageColumns.tsx b/ui/packages/plugin-detail/src/RecordPageColumns.tsx index ac5eb7ac617..89386edae43 100644 --- a/ui/packages/plugin-detail/src/RecordPageColumns.tsx +++ b/ui/packages/plugin-detail/src/RecordPageColumns.tsx @@ -9,7 +9,9 @@ import * as React from 'react'; import { cn } from '@object-ui/components'; import type { FieldContainerLike } from '@object-ui/core'; -import { SchemaRenderer, toRenderableSchema, useRecordContext, useRecordPagePreferences } from '@object-ui/react'; +import { SchemaRenderer, toRenderableSchema, usePredicateScope, useRecordContext, useRecordPagePreferences, useSafeFieldLabel } from '@object-ui/react'; +import { pickLocalized, useObjectTranslation } from '@object-ui/i18n'; +import type { FieldRulePredicate } from '@object-ui/core'; import { RECORD_PAGE_DETAILS_MIN_WIDTH, RECORD_PAGE_DETAILS_WIDTH, @@ -20,11 +22,14 @@ import { recordPagePinsDetails, relatedListIdsIn, type DefaultPageColumns, + type RecordPageFieldTab, type RecordPageTier, } from './synth/recordPageColumns'; +import { deriveFieldGroupDetailEntries } from './synth/buildDefaultPageSchema'; +import { fieldGroupPredicateVisible, lazyPredicateRecord } from './fieldPredicateVisibility'; import { useDetailTranslation } from './useDetailTranslation'; import { RecordBodyTablesContext, RelatedEnlargeContext, RelatedListEnlargedContext } from './relatedListCompact'; -import { ApprovalBandOnceScope, DefaultRecordPageContext, DetailsColumnCapContext } from './defaultRecordPage'; +import { ApprovalBandOnceScope, DefaultRecordPageContext, DetailsColumnCapContext, FieldTabTitledGroupContext } from './defaultRecordPage'; import { RECORD_TAB_OVERVIEW, RecordTabRow, type RecordTab, type RecordTabArrangeEdit } from './RecordTabRow'; import { RECORD_TAB_APPROVALS, @@ -275,6 +280,68 @@ function drawDetailsNodes(nodes: any[]): React.ReactNode { return {drawNodes(nodes)}; } +/** + * The field groups of the object's field tabs (objectstack#37802) the record + * page draws: a tab is drawn when at least one of its groups is — declared on + * the object the page reads, holding a field (the shared derivation drops an + * empty group) and admitted by its `visibleWhen` on this record, judged by the + * call `record:details` makes for the same group (fail-closed). The verdict is + * lifted here, where the tab row is built, so a tab whose groups are all + * hidden or missing (a `.custom` package's `fieldGroups` replaced them) draws + * no tab at all. Without an object definition on the record context (nothing + * to judge against) every tab is kept, as its body is. + */ +function useDrawnFieldTabs(tabs: readonly RecordPageFieldTab[]): RecordPageFieldTab[] { + const ctx = useRecordContext(); + const scope = usePredicateScope(); + if (tabs.length === 0) return []; + const objSchema = (ctx as { objectSchema?: any } | null)?.objectSchema; + if (!objSchema) return [...tabs]; + const entries = new Map(); + for (const entry of deriveFieldGroupDetailEntries(objSchema) ?? []) { + if (typeof entry.key === 'string') entries.set(entry.key, entry); + } + const record = lazyPredicateRecord((ctx as { data?: Record } | null)?.data, objSchema?.fields); + const objectName = typeof ctx?.objectName === 'string' ? ctx.objectName : ''; + const drawn = (group: string): boolean => { + const entry = entries.get(group); + if (!entry) return false; + if (entry.visibleWhen == null) return true; + return fieldGroupPredicateVisible( + entry.visibleWhen as FieldRulePredicate, + record(), + scope, + `group '${group}' of the field tab on object '${objectName}'`, + ); + }; + return tabs.filter((tab) => tab.groups.some(drawn)); +} + +/** + * A field tab's body (objectstack#37802): its `record:details` nodes as a + * field list of their own — its empty fields counted by its own 「显示 N 个空字段」 + * row at its foot, shown or not by the reader's one per-object choice the + * overview's row reads too — and, for a tab of one group, that group drawn + * without the heading the tab's title already is. + */ +const FieldTabBody: React.FC<{ tab: RecordPageFieldTab; fieldList: Omit }> = ({ + tab, + fieldList, +}) => { + const [emptyFields] = React.useState(createEmptyFieldTally); + const list = React.useMemo(() => ({ ...fieldList, emptyFields }), [fieldList, emptyFields]); + return ( + + +
+ {drawDetailsNodes(tab.children)} + +
+
+
+ ); +}; + const LINE_BUTTON = 'rounded-sm font-medium text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring'; @@ -604,7 +671,23 @@ export const RecordPageColumns: React.FC = ({ enlargedRelated && !panelNodes.has(enlargedRelated) ? columns.details.find((n) => relatedNodeId(n) === enlargedRelated) : undefined; - const otherTabs: RecordTab[] = resolved.order.map(arrangedTab); + // objectstack#37802 — the object's field tabs, right after the overview, in + // declared order, before every related and built-in tab. Fixed: the reader's + // arrangement neither moves nor hides them (they carry no `arrange`). + const fieldTabs = useDrawnFieldTabs(columns.fieldTabs ?? []); + const { sectionLabel } = useSafeFieldLabel(); + const { language } = useObjectTranslation(); + const fieldTabTitle = (tab: RecordPageFieldTab): string => { + const raw = tab.label != null ? pickLocalized(tab.label as any, language) : undefined; + const fallback = typeof raw === 'string' && raw ? raw : tab.groups[0] ?? tab.id; + return preferenceObject && tab.groups[0] ? sectionLabel(preferenceObject, tab.groups[0], fallback) : fallback; + }; + const otherTabs: RecordTab[] = fieldTabs.map((tab) => ({ + id: tab.id, + label: fieldTabTitle(tab), + ...(tab.icon ? { icon: tab.icon } : {}), + })); + otherTabs.push(...resolved.order.map(arrangedTab)); if (bodyTableNode) otherTabs.push({ id: enlargedRelated!, label: relatedNodeTitle(bodyTableNode) }); if (attachmentsNode) otherTabs.push({ id: RECORD_TAB_ATTACHMENTS, label: attachmentsTitle, count: attachmentCount }); if (approvalsNode) otherTabs.push({ id: RECORD_TAB_APPROVALS, label: approvalsTitle, dot: approvalPending }); @@ -660,6 +743,13 @@ export const RecordPageColumns: React.FC = ({ ); + } else if (openTab && fieldTabs.some((tab) => tab.id === openTab)) { + const tab = fieldTabs.find((t) => t.id === openTab)!; + face = ( + + + + ); } else if (openTab === RECORD_TAB_ATTACHMENTS && attachmentsNode) { face = blockFace(RECORD_TAB_ATTACHMENTS, attachmentsTitle, attachmentsNode); } else if (openTab === RECORD_TAB_APPROVALS && approvalsNode) { diff --git a/ui/packages/plugin-detail/src/RecordTabRow.tsx b/ui/packages/plugin-detail/src/RecordTabRow.tsx index fb8f2529c50..f91108e3434 100644 --- a/ui/packages/plugin-detail/src/RecordTabRow.tsx +++ b/ui/packages/plugin-detail/src/RecordTabRow.tsx @@ -14,6 +14,7 @@ import { DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger, + LazyIcon, cn, } from '@object-ui/components'; import { ArrowLeft, ArrowRight, ChevronDown, EyeOff, RotateCcw } from 'lucide-react'; @@ -48,6 +49,11 @@ export interface RecordTab { * Absent: a fixed tab (概览, 附件, 审批, 动态, an open body table). */ arrange?: { before: boolean; after: boolean }; + /** + * A Lucide icon name drawn before the label — a field tab's, its first + * group's `icon` (objectstack#37802). Absent: no icon, as on every other tab. + */ + icon?: string; } /** What a related tab's menu asks of the reader's arrangement (objectstack#35783). */ @@ -99,12 +105,25 @@ const hasCount = (tab: RecordTab): tab is RecordTab & { count: number } => /** Whether a tab's list is known to be empty: a count of `0`. */ export const isEmptyRecordTab = (tab: RecordTab): boolean => tab.count === 0; +/** + * A tab's icon (objectstack#37802): a Lucide name draws the real icon, as a + * field group's section header does (`DetailSection`'s `SectionIcon`); any + * other text (an emoji from hand-authored metadata) is drawn as text. + */ +const TabIcon: React.FC<{ name: string }> = ({ name }) => ( + + {/^[a-z0-9][a-z0-9-]*$/i.test(name) ? : name} + +); + /** * A tab's face, shared by the row's button, the dropdown's items and the - * measuring copy: the label, then the count chip (above 0) or the dot. + * measuring copy: the icon (a field tab's), the label, then the count chip + * (above 0) or the dot. */ const TabFace: React.FC<{ tab: RecordTab; muted?: boolean; menu?: boolean }> = ({ tab, muted, menu }) => ( <> + {tab.icon && } {tab.label} @@ -159,7 +178,7 @@ export const RecordTabRow: React.FC = ({ // What the tabs draw, as a value: re-measure when a label or a count moves. const facesKey = JSON.stringify([ - tabs.map((tab) => [tab.id, tab.label, tab.count ?? null, tab.dot === true]), + tabs.map((tab) => [tab.id, tab.label, tab.count ?? null, tab.dot === true, tab.icon ?? null]), hiddenTabs.length, activeId, !!onArrange, diff --git a/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.fieldTabs-37802.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.fieldTabs-37802.test.tsx new file mode 100644 index 00000000000..f53415ee226 --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/RecordPageColumns.fieldTabs-37802.test.tsx @@ -0,0 +1,318 @@ +/** + * 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#37802 — the object's `fieldTabs` (`ObjectSchema.fieldTabs`, + * ADR-0085's Note of 2026-11-27) on the laid-out record page. + * + * The page is the REAL synthesized one (`buildDefaultPageSchema` → + * `buildDefaultPageColumns`) drawn through the REAL registry, so each + * `record:details` node resolves its `{ group }` sections the way the running + * app does. What it pins, each beside its control (the same object without + * `fieldTabs`, or the same tab without the condition): + * + * - a two-group tab draws its groups in its order, and the overview no longer + * draws them; the related lists and attachments keep their tabs; + * - the tab row runs overview → field tabs → the rest, and the reader's + * arrangement offers no move or hide on a field tab; + * - a tab whose every group is hidden by `visibleWhen`, or missing from the + * object the page reads, draws no tab; + * - each field tab counts its own empty fields in its own row; + * - a one-group tab draws no second heading under its title; + * - a tab carries its first group's icon before its title (none without one); + * - inline edit is the page's one session: a draft made on a field tab's field + * survives switching to the overview and back, and is what Save writes; a + * server refusal naming a field in a tab not open is still listed by the + * save bar. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, cleanup, within, fireEvent, waitFor } from '@testing-library/react'; +import { InlineEditProvider, RecordContextProvider, useInlineEdit } from '@object-ui/react'; +// The registry must hold the record renderers and the field widgets before the +// first render (AGENTS.md 测试纪律). +import '@object-ui/components'; +import '@object-ui/fields'; +import '../index'; +import { RecordPageColumns } from '../RecordPageColumns'; +import { InlineEditSaveBar } from '../InlineEditSaveBar'; +import { buildDefaultPageSchema, type ObjectDefLike } from '../synth/buildDefaultPageSchema'; +import { buildDefaultPageColumns } from '../synth/recordPageColumns'; + +/** `useRecordEditable`'s explain probe, answered with its fail-open 501 (the binding suites do the same). */ +vi.stubGlobal('fetch', (async () => new Response(null, { status: 501 })) as unknown as typeof globalThis.fetch); + +let width = 0; +beforeEach(() => { + width = 0; + vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(() => width); +}); +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +const policy = { + name: 'policy', + label: 'Policy', + enable: { files: true }, + fieldGroups: [ + { key: 'basic', label: 'Basic' }, + { key: 'content', label: 'Content' }, + { key: 'import', label: 'Original' }, + { key: 'review', label: 'Review', visibleWhen: "record.status == 'in_review'" }, + ], + fields: { + name: { name: 'name', label: 'Name', type: 'text' }, + owner: { name: 'owner', label: 'Owner', type: 'text', group: 'basic' }, + body: { name: 'body', label: 'Body text', type: 'textarea', group: 'content' }, + summary: { name: 'summary', label: 'Summary', type: 'text', group: 'content' }, + source_file: { name: 'source_file', label: 'Source file', type: 'text', group: 'import' }, + checksum: { name: 'checksum', label: 'Checksum', type: 'text', group: 'import' }, + imported_by: { name: 'imported_by', label: 'Imported by', type: 'text', group: 'import' }, + reviewer: { name: 'reviewer', label: 'Reviewer', type: 'text', group: 'review' }, + status: { name: 'status', label: 'Status', type: 'text' }, + }, +}; + +/** A policy with its body and source written; `summary`, `checksum`, `imported_by` left empty. */ +const RECORD = { id: 'p1', name: 'Travel policy', owner: 'Ada', body: 'Long body text', source_file: 'travel.pdf', status: 'active', reviewer: 'Lin' }; + +const related = [{ objectName: 'task', relationshipField: 'policy_id', title: 'Tasks' }]; + +function draw( + def: Record, + { + open, + schema = def, + data = RECORD, + }: { open?: string; schema?: Record; data?: Record } = {}, +) { + const page = buildDefaultPageSchema(def as ObjectDefLike, { related, hideDiscussion: true }); + const columns = buildDefaultPageColumns(page)!; + expect(columns, 'the synthesized page lays out').not.toBeNull(); + const onEnlargeRelated = vi.fn(); + const utils = render( + + + , + ); + return { ...utils, onEnlargeRelated }; +} + +const tabIds = () => screen.queryAllByRole('tab').map((tab) => tab.getAttribute('data-record-tab')); +const detailsColumn = (container: HTMLElement) => + container.querySelector('[data-record-column="details"]') as HTMLElement | null; +const fieldTab = (container: HTMLElement, id: string) => + container.querySelector(`[data-record-field-tab="${id}"]`) as HTMLElement | null; +const labelsIn = (el: HTMLElement | null) => (el?.textContent ?? ''); +const order = (text: string, ...words: string[]) => words.map((w) => text.indexOf(w)); + +const withTabs = (fieldTabs: unknown) => ({ ...policy, fieldTabs }); + +describe('RecordPageColumns — the object\'s field tabs (objectstack#37802)', () => { + it('CONTROL: without fieldTabs the overview draws every group; the tabs are the related ones', () => { + const { container } = draw(policy); + expect(tabIds()).toEqual(['overview', 'task.policy_id', 'attachments']); + const overview = labelsIn(detailsColumn(container)); + expect(overview).toContain('Body text'); + expect(overview).toContain('Source file'); + }); + + it('a two-group tab draws its groups in its order; the overview no longer draws them; related and attachments keep their tabs', () => { + const def = withTabs([{ key: 'content', groups: ['import', 'content'] }]); + const first = draw(def); + expect(tabIds()).toEqual(['overview', 'fields:content', 'task.policy_id', 'attachments']); + const overview = labelsIn(detailsColumn(first.container)); + expect(overview).toContain('Owner'); + expect(overview).not.toContain('Body text'); + expect(overview).not.toContain('Source file'); + first.unmount(); + + const { container } = draw(def, { open: 'fields:content' }); + const body = fieldTab(container, 'fields:content'); + expect(body).not.toBeNull(); + const text = labelsIn(body); + const [original, content, source, bodyText] = order(text, 'Original', 'Content', 'Source file', 'Body text'); + expect(original).toBeGreaterThanOrEqual(0); + expect(content).toBeGreaterThan(original); + expect(source).toBeGreaterThan(original); + expect(bodyText).toBeGreaterThan(content); + expect(text).not.toContain('Owner'); + // The tab's title is its first group's label. + expect(screen.getByRole('tab', { name: /Original/ }).getAttribute('data-record-tab')).toBe('fields:content'); + }); + + it("the tab draws its first group's icon before its title; a group with no icon draws none", () => { + const iconed = { ...policy, fieldGroups: policy.fieldGroups.map((g) => (g.key === 'content' ? { ...g, icon: 'file-text' } : g)) }; + const { container } = draw({ ...iconed, fieldTabs: [{ key: 'content', groups: ['content'] }, { key: 'original', groups: ['import'] }] }); + const contentTab = container.querySelector('[data-record-tab="fields:content"]')!; + const icon = contentTab.querySelector('[data-record-tab-icon]'); + expect(icon?.getAttribute('data-record-tab-icon')).toBe('file-text'); + // The icon comes before the title on the tab's face. + expect(icon!.compareDocumentPosition(contentTab.querySelector('[data-record-tab-label]')!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + // CONTROL: `import` declares no icon, and no other tab draws one. + expect(container.querySelector('[data-record-tab="fields:original"] [data-record-tab-icon]')).toBeNull(); + expect(screen.getAllByRole('tab').filter((tab) => tab.querySelector('[data-record-tab-icon]'))).toHaveLength(1); + }); + + it("the reader's arrangement offers no move or hide on a field tab; a related tab carries it", () => { + const { container } = draw(withTabs([{ key: 'content', groups: ['content'] }]), { open: 'fields:content' }); + // The open field tab is no menu trigger (no chevron); the related tab, opened, is. + const fieldTabButton = container.querySelector('[data-record-tab="fields:content"]')!; + expect(fieldTabButton.getAttribute('aria-selected')).toBe('true'); + expect(fieldTabButton.querySelector('[data-record-tab-menu-chevron]')).toBeNull(); + cleanup(); + const control = draw(withTabs([{ key: 'content', groups: ['content'] }]), { open: 'task.policy_id' }); + const relatedButton = control.container.querySelector('[data-record-tab="task.policy_id"]')!; + expect(relatedButton.querySelector('[data-record-tab-menu-chevron]')).not.toBeNull(); + }); + + it('a tab whose every group visibleWhen hides draws no tab; shown, it does', () => { + const def = withTabs([{ key: 'review', groups: ['review'] }]); + draw(def); + expect(tabIds()).not.toContain('fields:review'); + cleanup(); + draw(def, { data: { ...RECORD, status: 'in_review' } }); + expect(tabIds()).toContain('fields:review'); + }); + + it('a group missing from the object the page reads is skipped; a tab left with none draws no tab', () => { + const def = withTabs([{ key: 'content', groups: ['content'] }, { key: 'original', groups: ['import'] }]); + // The served object lost `import` (a `.custom` package replaced `fieldGroups`). + const served = { ...policy, fieldGroups: policy.fieldGroups.filter((g) => g.key !== 'import') }; + draw(def, { schema: served }); + expect(tabIds()).toEqual(['overview', 'fields:content', 'task.policy_id', 'attachments']); + cleanup(); + // CONTROL: the object as declared draws both. + draw(def); + expect(tabIds()).toEqual(['overview', 'fields:content', 'fields:original', 'task.policy_id', 'attachments']); + }); + + it('each field tab counts its own empty fields in its own row', () => { + const def = withTabs([{ key: 'content', groups: ['content'] }, { key: 'original', groups: ['import'] }]); + const content = draw(def, { open: 'fields:content' }); + const row = fieldTab(content.container, 'fields:content')!.querySelector('[data-empty-fields-row]'); + expect(row?.getAttribute('data-empty-fields-count')).toBe('1'); + content.unmount(); + const original = draw(def, { open: 'fields:original' }); + const row2 = fieldTab(original.container, 'fields:original')!.querySelector('[data-empty-fields-row]'); + expect(row2?.getAttribute('data-empty-fields-count')).toBe('2'); + }); + + it('pinned beside the overview, the tab and the overview each count only their own empty fields', () => { + width = 1600; + const def = { + ...withTabs([{ key: 'content', groups: ['content'] }]), + fields: { ...policy.fields, phone: { name: 'phone', label: 'Phone', type: 'text', group: 'basic' } }, + }; + const { container } = draw(def, { open: 'fields:content' }); + expect(container.querySelector('[data-record-page-pinned]')).not.toBeNull(); + const overviewRow = detailsColumn(container)!.querySelector('[data-empty-fields-row]'); + const tabRow = fieldTab(container, 'fields:content')!.querySelector('[data-empty-fields-row]'); + // The overview's empty fields are `phone`, `checksum` and `imported_by`; the tab's is `summary`. + expect(overviewRow?.getAttribute('data-empty-fields-count')).toBe('3'); + expect(tabRow?.getAttribute('data-empty-fields-count')).toBe('1'); + }); + + it('a one-group tab draws no second heading under its title; a two-group tab keeps both headings', () => { + const one = draw(withTabs([{ key: 'original', groups: ['import'] }]), { open: 'fields:original' }); + const body = fieldTab(one.container, 'fields:original')!; + expect(within(body).queryByText('Original')).toBeNull(); + expect(labelsIn(body)).toContain('Source file'); + one.unmount(); + const two = draw(withTabs([{ key: 'content', groups: ['import', 'content'] }]), { open: 'fields:content' }); + const both = fieldTab(two.container, 'fields:content')!; + expect(within(both).queryByText('Original')).not.toBeNull(); + expect(within(both).queryByText('Content')).not.toBeNull(); + }); +}); + +describe('RecordPageColumns — field tabs and the page\'s one inline-edit session (objectstack#37802)', () => { + const def = withTabs([{ key: 'content', groups: ['content'] }]); + const LABELS: Record = { body: 'Body text', owner: 'Owner' }; + + function Edits() { + const inline = useInlineEdit()!; + return ( + <> + + + + ); + } + + function page(open: string | undefined, update: ReturnType) { + const columns = buildDefaultPageColumns(buildDefaultPageSchema(def as ObjectDefLike, { related, hideDiscussion: true }))!; + return ( + + + + + LABELS[n]} + /> + + + ); + } + + it('a draft on a field tab survives switching to the overview and back, and Save writes it', async () => { + const update = vi.fn(async (_o: string, _id: string, patch: Record) => ({ ...RECORD, ...patch })); + const { rerender } = render(page('fields:content', update)); + fireEvent.click(screen.getByText('edit-enter')); + fireEvent.click(screen.getByText('edit-body')); + // To the overview: the tab's body is gone from the page, the session is not. + rerender(page(undefined, update)); + expect(document.querySelector('[data-record-field-tab="fields:content"]')).toBeNull(); + expect(screen.getByRole('button', { name: 'Save' })).toBeTruthy(); + // Back on the tab: the field draws the draft. + rerender(page('fields:content', update)); + const tabBody = document.querySelector('[data-record-field-tab="fields:content"]') as HTMLElement; + expect((within(tabBody).getByDisplayValue('Rewritten body') as HTMLTextAreaElement).value).toBe('Rewritten body'); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(update).toHaveBeenCalledTimes(1)); + expect(update.mock.calls[0][2]).toMatchObject({ body: 'Rewritten body' }); + }); + + it('a server refusal naming a field in a tab not open is still listed by the save bar', async () => { + const update = vi.fn().mockRejectedValue({ + code: 'VALIDATION_FAILED', + message: 'VALIDATION_FAILED: Validation failed for policy', + details: { error: 'Validation failed', code: 'VALIDATION_FAILED', fields: [{ field: 'body', code: 'max', message: 'Body is too long' }] }, + }); + const { rerender } = render(page('fields:content', update)); + fireEvent.click(screen.getByText('edit-enter')); + fireEvent.click(screen.getByText('edit-body')); + // The reader went back to the overview before saving: the field's tab is not open. + rerender(page(undefined, update)); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(update).toHaveBeenCalledTimes(1)); + await waitFor(() => + expect( + Array.from(document.querySelectorAll('[data-inline-field-error]')).map((li) => [ + li.getAttribute('data-inline-field-error'), + li.textContent, + ]), + ).toEqual([['body', 'Body text: Body is too long']]), + ); + expect(document.querySelector('[data-record-field-tab="fields:content"]')).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-detail/src/defaultRecordPage.ts b/ui/packages/plugin-detail/src/defaultRecordPage.ts index c930b89e62d..268c5d010fd 100644 --- a/ui/packages/plugin-detail/src/defaultRecordPage.ts +++ b/ui/packages/plugin-detail/src/defaultRecordPage.ts @@ -147,3 +147,15 @@ export function framelessSectionColumns(visibleFieldCount: number, cap: 1 | 2 | if (visibleFieldCount <= 5 || cap === 2) return 2; return 3; } + +/** + * objectstack#37802 — the field group whose heading a field tab already draws + * as its title: a tab of the object's `fieldTabs` that holds ONE group is + * titled by that group (`RecordPageColumns`), so `record:details` draws the + * group's fields under the tab without its heading, its card or its fold. + * `null` (the default) everywhere else: every group keeps its heading. + * + * Module-internal, like `DetailsColumnCapContext`: neither a prop nor a + * schema key. + */ +export const FieldTabTitledGroupContext = React.createContext(null); diff --git a/ui/packages/plugin-detail/src/fieldPredicateVisibility.ts b/ui/packages/plugin-detail/src/fieldPredicateVisibility.ts index 9e5f3813a9d..699cb83a3ab 100644 --- a/ui/packages/plugin-detail/src/fieldPredicateVisibility.ts +++ b/ui/packages/plugin-detail/src/fieldPredicateVisibility.ts @@ -16,6 +16,7 @@ import { columnIdentity, + evalFieldPredicate, resolveFieldRuleState, toPredicateRecord, type FieldRulePredicate, @@ -52,6 +53,24 @@ export function assemblePredicateRecord( return out; } +/** + * Does a field GROUP's `visibleWhen` admit the group on this record? The one + * call `record:details` makes for a `{ group }` section (its + * `sectionPredicateVisible` docblock says why: the form's engine, the form's + * three inputs, fail-CLOSED), and the one the laid-out record page makes for + * a field tab's groups before it draws the tab (objectstack#37802). + */ +export function fieldGroupPredicateVisible( + visibleWhen: FieldRulePredicate, + record: Record, + scope: Record, + where: string, +): boolean { + return evalFieldPredicate(visibleWhen, record, false, record, scope, { + context: `visibleWhen of ${where} — fail-closed, the group is hidden`, + }); +} + /** * {@link assemblePredicateRecord}, assembled on first use and then reused — so * a surface whose fields declare no predicate does no extra work. diff --git a/ui/packages/plugin-detail/src/index.tsx b/ui/packages/plugin-detail/src/index.tsx index 4d8bcdb9be4..4fdbd5a09f4 100644 --- a/ui/packages/plugin-detail/src/index.tsx +++ b/ui/packages/plugin-detail/src/index.tsx @@ -247,12 +247,15 @@ export { buildDefaultPageColumns, bodyTableIdsOf, RECORD_PAGE_TIMELINE_PANEL, + // objectstack#37802 — the field tab a cited field sits in. + fieldTabIdOfField, } from './synth/recordPageColumns'; // objectstack#27069 — the one reading of a related-list entry. export { relatedListEntryNames } from './synth/relatedListEntry'; export type { RecordPageTier, DefaultPageColumns, + RecordPageFieldTab, } from './synth/recordPageColumns'; export { useRecordPageTier } from './useRecordPageTier'; export type { UseRecordPageTierOptions } from './useRecordPageTier'; diff --git a/ui/packages/plugin-detail/src/renderers/record-details.tsx b/ui/packages/plugin-detail/src/renderers/record-details.tsx index ccf0aeffa65..614ba6b4c0e 100644 --- a/ui/packages/plugin-detail/src/renderers/record-details.tsx +++ b/ui/packages/plugin-detail/src/renderers/record-details.tsx @@ -27,19 +27,18 @@ import { resolveAffordance, type FieldRulePredicate, recordDisplayValueAt, - evalFieldPredicate, resolveNameField, withoutDeniedFields, } from '@object-ui/core'; import { DetailView } from '../DetailView'; import { hasCellValue } from '../emptiness'; -import { EmptySectionsLineContext } from '../defaultRecordPage'; +import { EmptySectionsLineContext, FieldTabTitledGroupContext } from '../defaultRecordPage'; import { RecordPageProvenanceContext } from '../recordPageProvenance'; import { RecordFieldAccessForRecord } from '../recordFieldAccess'; import { deriveFieldGroupDetailEntries, type FieldGroupDetailEntry } from '../synth/buildDefaultPageSchema'; import { useRecordAriaProps } from './recordComponentAria'; import { recordBindingBlock } from './recordBinding'; -import { dropFieldPredicateHidden, lazyPredicateRecord } from '../fieldPredicateVisibility'; +import { dropFieldPredicateHidden, fieldGroupPredicateVisible, lazyPredicateRecord } from '../fieldPredicateVisibility'; /** Normalize a field entry (string | {field} | {name}) to its machine name. */ const fieldName = (entry: any): string | null => columnIdentity(entry) ?? null; @@ -225,9 +224,7 @@ function sectionPredicateVisible( scope: Record, where: string, ): boolean { - return evalFieldPredicate(visibleWhen, record, false, record, scope, { - context: `visibleWhen of ${where} — fail-closed, the group is hidden`, - }); + return fieldGroupPredicateVisible(visibleWhen, record, scope, where); } /** @@ -365,6 +362,9 @@ const RecordDetailsBody: React.FC = ({ // same predicate (objectui#11630). Called here with the other hooks because // the returns below are conditional. const predicateScope = usePredicateScope(); + // objectstack#37802 — the group a one-group field tab is titled by: drawn + // without its own heading (`FieldTabTitledGroupContext`). + const tabTitledGroup = React.useContext(FieldTabTitledGroupContext); // Phase N.4b: field names registered live by a mounted `record:highlights` // instance via HighlightFieldsContext (used to dedupe them out of the grid). @@ -1090,7 +1090,12 @@ const RecordDetailsBody: React.FC = ({ hideEmpty: s.hideEmpty ?? true, fields: dropPredicateHidden(dropHidden(normaliseList(filterList(s.fields)))), }); - }) + }).map((s) => + // objectstack#37802 — the tab's title is this group's heading already: + // no second heading, card or fold under it. + tabTitledGroup !== null && s.name === tabTitledGroup + ? { ...s, title: undefined, showBorder: false, collapsible: false, defaultCollapsed: false } + : s) : schema.sections; // A pointer pair's type half is drawn by its id half's card, not as a row diff --git a/ui/packages/plugin-detail/src/synth/__tests__/fieldTabs-37802.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/fieldTabs-37802.test.ts new file mode 100644 index 00000000000..bdb3d5b5d65 --- /dev/null +++ b/ui/packages/plugin-detail/src/synth/__tests__/fieldTabs-37802.test.ts @@ -0,0 +1,153 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#37802 — the object's `fieldTabs` (`ObjectSchema.fieldTabs`, + * ADR-0085's Note of 2026-11-27), as the synthesized record page places them. + * + * Pure and read off `buildDefaultPageSchema`'s real output: a field tab takes + * its groups' sections out of the overview and sits right after it, in + * declared order, before every related and built-in tab; its `fields:` + * id lays out as a column of its own; a group the object does not declare is + * skipped, and a tab left with none is not placed. Each fact sits beside its + * control: the same object without `fieldTabs`. + */ + +import { describe, it, expect } from 'vitest'; +import { buildDefaultPageSchema, fieldTabPlacement, type ObjectDefLike } from '../buildDefaultPageSchema'; +import { + buildDefaultPageColumns, + fieldTabIdOfField, + recordPageColumnOfTab, + recordPagePinsDetails, +} from '../recordPageColumns'; + +const policy: ObjectDefLike = { + name: 'policy', + label: 'Policy', + fieldGroups: [ + { key: 'basic', label: 'Basic' }, + { key: 'content', label: 'Content', icon: 'file-text' }, + { key: 'import', label: 'Original' }, + ], + fields: { + name: { name: 'name', label: 'Name', type: 'text' }, + owner: { name: 'owner', label: 'Owner', type: 'text', group: 'basic' }, + body: { name: 'body', label: 'Body', type: 'textarea', group: 'content' }, + source_file: { name: 'source_file', label: 'Source file', type: 'text', group: 'import' }, + }, +} as ObjectDefLike; + +const related = [{ objectName: 'task', relationshipField: 'policy_id', title: 'Tasks' }]; + +const itemsOf = (page: any): any[] => page.regions[0].components.find((n: any) => n.type === 'page:tabs').properties.items; +const values = (page: any): string[] => itemsOf(page).map((item: any) => item.value); +const groupsOf = (node: any): string[] => + (node?.properties?.sections ?? []).map((s: any) => s.group ?? (s.fields ? `[${s.fields.join(',')}]` : s.name)); +const overviewGroups = (page: any): string[] => + itemsOf(page)[0].children.filter((n: any) => n.type === 'record:details').flatMap(groupsOf); + +describe('fieldTabs — the synthesized page places the field tabs (objectstack#37802)', () => { + it('CONTROL: without fieldTabs the overview holds every group and the tabs are the related ones', () => { + const page = buildDefaultPageSchema(policy, { related, hideDiscussion: true }); + expect(values(page)).toEqual(['details', 'related:task.policy_id']); + expect(overviewGroups(page)).toEqual(['basic', 'content', 'import', '[name]']); + }); + + it('a two-group tab takes both groups, in its order, out of the overview, right after it', () => { + const def = { ...policy, fieldTabs: [{ key: 'content', groups: ['import', 'content'] }] }; + const page = buildDefaultPageSchema(def, { related, hideDiscussion: true }); + expect(values(page)).toEqual(['details', 'fields:content', 'related:task.policy_id']); + // The overview keeps the groups no tab names and the ungrouped fields. + expect(overviewGroups(page)).toEqual(['basic', '[name]']); + const tab = itemsOf(page)[1]; + expect(tab.children.map((n: any) => n.type)).toEqual(['record:details']); + expect(groupsOf(tab.children[0])).toEqual(['import', 'content']); + // Its title and icon are its first group's (no label/icon of its own in v1). + expect(tab.label).toBe('Original'); + expect(tab.icon).toBeUndefined(); + }); + + it('two tabs keep their declared order, before the related lists, attachments and the stream', () => { + const def = { + ...policy, + enable: { files: true }, + fieldTabs: [ + { key: 'original', groups: ['import'] }, + { key: 'content', groups: ['content'] }, + ], + }; + const page = buildDefaultPageSchema(def, { related }); + expect(values(page)).toEqual(['details', 'fields:original', 'fields:content', 'related:task.policy_id', 'attachments', 'timeline']); + expect(itemsOf(page)[2].icon).toBe('file-text'); + // A declared `relatedLists` places the related tabs only: no entry moves a field tab. + const declared = buildDefaultPageSchema({ ...def, relatedLists: [{ list: 'task' }] } as ObjectDefLike, { related }); + expect(values(declared).slice(0, 4)).toEqual(['details', 'fields:original', 'fields:content', 'related:task.policy_id']); + }); + + it('a group the object does not declare is skipped; a tab left with none is not placed', () => { + const def = { + ...policy, + fieldTabs: [ + { key: 'gone', groups: ['no_such_group'] }, + { key: 'content', groups: ['no_such_group', 'content'] }, + ], + }; + const page = buildDefaultPageSchema(def, { related, hideDiscussion: true }); + expect(values(page)).toEqual(['details', 'fields:content', 'related:task.policy_id']); + expect(groupsOf(itemsOf(page)[1].children[0])).toEqual(['content']); + expect(overviewGroups(page)).toEqual(['basic', 'import', '[name]']); + }); + + it('a group named by two tabs is drawn once, in the first', () => { + const placed = fieldTabPlacement( + { ...policy, fieldTabs: [{ key: 'a', groups: ['content'] }, { key: 'b', groups: ['content', 'import'] }] }, + // The `{ group }` reference form `resolveDetailSections` hands it. + [{ group: 'basic' }, { group: 'content' }, { group: 'import' }], + )!; + expect(placed.tabs.map((t) => [t.key, t.sections.map((s) => s.group)])).toEqual([ + ['a', ['content']], + ['b', ['import']], + ]); + expect(placed.overview).toEqual([{ group: 'basic' }]); + }); + + it('every group moved out leaves the overview an empty field body, still the first tab', () => { + const def = { ...policy, fields: { ...policy.fields, name: { ...policy.fields!.name, group: 'basic' } }, fieldTabs: [{ key: 'all', groups: ['basic', 'content', 'import'] }] }; + const page = buildDefaultPageSchema(def as ObjectDefLike, { related, hideDiscussion: true }); + expect(values(page)).toEqual(['details', 'fields:all', 'related:task.policy_id']); + const overview = itemsOf(page)[0].children; + expect(overview.map((n: any) => n.type)).toEqual(['record:details']); + expect(overview[0].properties.sections).toEqual([]); + }); + + it('the layout reads the field tabs as their own column; they count as other tabs for the pin', () => { + expect(recordPageColumnOfTab('fields:content')).toBe('fields'); + expect(recordPageColumnOfTab('fields:')).toBeNull(); + const def = { ...policy, fieldTabs: [{ key: 'content', groups: ['content', 'import'] }] }; + const columns = buildDefaultPageColumns(buildDefaultPageSchema(def, { hideDiscussion: true }))!; + expect(columns).not.toBeNull(); + expect(columns.related).toEqual([]); + expect(columns.fieldTabs!.map((t) => [t.id, t.groups])).toEqual([['fields:content', ['content', 'import']]]); + // A field tab alone is an "other tab": the wide full page pins… + expect(recordPagePinsDetails(1600, columns, true)).toBe(true); + // …CONTROL: the same page without the tab has nothing to pin beside. + const bare = buildDefaultPageColumns(buildDefaultPageSchema(policy, { hideDiscussion: true }))!; + expect(recordPagePinsDetails(1600, bare, true)).toBe(false); + }); + + it('a cited field opens the field tab that holds its group; an overview field opens none', () => { + const def = { ...policy, fieldTabs: [{ key: 'content', groups: ['content', 'import'] }] }; + const columns = buildDefaultPageColumns(buildDefaultPageSchema(def, { hideDiscussion: true }))!; + expect(fieldTabIdOfField(columns, def, 'source_file')).toBe('fields:content'); + expect(fieldTabIdOfField(columns, def, 'body')).toBe('fields:content'); + expect(fieldTabIdOfField(columns, def, 'owner')).toBeNull(); + expect(fieldTabIdOfField(columns, def, 'name')).toBeNull(); + expect(fieldTabIdOfField(columns, def, 'no_such_field')).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts b/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts index 891afc4b11f..443045840ba 100644 --- a/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts +++ b/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts @@ -123,6 +123,13 @@ export interface ObjectDefLike { * whether an empty `relatedLists` is a declared list with every tab hidden). */ _relatedListsArrangement?: unknown; + /** + * The spec's `fieldTabs` (`ObjectSchema.fieldTabs`, ADR-0085's Note of + * 2026-11-27): field groups the record page draws as tabs of their own, + * right after the overview. Each entry names its tab's `key` and its + * `groups` (keys of `fieldGroups`). See {@link fieldTabPlacement}. + */ + fieldTabs?: ReadonlyArray<{ key?: unknown; groups?: unknown }>; // NOTE: the per-surface `detail` hints block was REMOVED from the spec by // ADR-0085 — presentation intent is declared via the top-level semantic // roles above (stageField / highlightFields / fieldGroups). Per-page @@ -842,6 +849,89 @@ function sectionDrawnClosed(def: ObjectDefLike | undefined): (section: Record`. */ +export const RECORD_PAGE_FIELD_TAB_PREFIX = 'fields:'; + +/** One field tab the synthesized page draws (see {@link fieldTabPlacement}). */ +export interface FieldTabPlacement { + /** The entry's `key`; the tab's value is `fields:`. */ + key: string; + /** The first drawn group's label, as the object declares it (translated where drawn). */ + label: unknown; + /** The first drawn group's icon, when it declares one. */ + icon?: string; + /** The sections the tab draws, in the entry's `groups` order. */ + sections: Array>; +} + +/** + * The object's `fieldTabs` (`ObjectSchema.fieldTabs`, ADR-0085's Note of + * 2026-11-27, objectstack#37802) laid over the Details sections the page + * draws: each tab takes the sections of the groups it names, in its `groups` + * order, out of the overview. `null` when the object declares no field tab + * that draws anything, so the page is exactly what it was without the key. + * + * A section belongs to a group by `group` (the spec's reference form, which the + * host and the synthesizer write) or by `name` (a resolved section a caller + * passes). Read at runtime, not judged (the object's parse refuses an + * unknown group, a group two tabs name and a body-table group): a group no + * section draws — undeclared, empty, or replaced by a `.custom` package's + * `fieldGroups` — is skipped, a group an earlier tab took is not drawn twice, + * and a tab left with no section is not drawn. A body-table group is never a + * section, so it stays where `bodyTablePlacement` puts it, in the overview. + */ +export function fieldTabPlacement( + def: ObjectDefLike | undefined, + // The Details body's sections: `{ group }` references, enumerated ones, or both. + sections: ReadonlyArray> | undefined, +): { overview: Array>; tabs: FieldTabPlacement[] } | null { + const declared = Array.isArray(def?.fieldTabs) ? def!.fieldTabs : []; + if (declared.length === 0 || !Array.isArray(sections) || sections.length === 0) return null; + const groups = new Map>(); + for (const group of Array.isArray(def?.fieldGroups) ? def!.fieldGroups : []) { + if (group && typeof group.key === 'string' && !groups.has(group.key)) groups.set(group.key, group as Record); + } + const groupOf = (section: Record): string | undefined => { + const key = typeof section?.group === 'string' ? section.group : typeof section?.name === 'string' ? section.name : undefined; + return key !== undefined && groups.has(key) ? key : undefined; + }; + const sectionOfGroup = new Map>(); + for (const section of sections as Array>) { + const key = groupOf(section); + if (key !== undefined && !sectionOfGroup.has(key)) sectionOfGroup.set(key, section); + } + const taken = new Set(); + const tabKeys = new Set(); + const tabs: FieldTabPlacement[] = []; + for (const entry of declared) { + const key = entry?.key; + if (typeof key !== 'string' || key.length === 0 || tabKeys.has(key) || !Array.isArray(entry?.groups)) continue; + const drawn: string[] = []; + for (const group of entry.groups as unknown[]) { + if (typeof group !== 'string' || taken.has(group) || !sectionOfGroup.has(group)) continue; + taken.add(group); + drawn.push(group); + } + if (drawn.length === 0) continue; + tabKeys.add(key); + const first = groups.get(drawn[0])!; + tabs.push({ + key, + label: first.label ?? drawn[0], + ...(typeof first.icon === 'string' && first.icon ? { icon: first.icon } : {}), + sections: drawn.map((group) => sectionOfGroup.get(group)!), + }); + } + if (tabs.length === 0) return null; + return { + overview: (sections as Array>).filter((section) => { + const key = groupOf(section); + return key === undefined || !taken.has(key); + }), + tabs, + }; +} + /** Rows on the first page of a body table (objectstack#27055, Target 8). */ export const BODY_TABLE_PAGE_SIZE = 10; @@ -1059,13 +1149,34 @@ function synthTabs( // objectstack#35595 — the first tab is 「概览」 (the token the tab strip // localizes as `detail.recordTabOverview`); its value stays `details`, the // URL token a `?tab=` link already names. + // objectstack#37802 — the object's field tabs (`fieldTabs`, ADR-0085's Note + // of 2026-11-27) take their groups' sections out of the overview, and sit + // right after it, in declared order, before every related and built-in tab. + // The overview keeps the rest: the groups no tab names, the ungrouped + // fields, the body tables (the host draws the approval band and the meta + // line there). Every group moved out leaves an overview of its tables and + // an empty field body (`@objectstack/lint` warns of that declaration). + const fieldTabs = fieldTabPlacement(def, resolveDetailSections(def, options.sections)); + const overviewChildren = !fieldTabs + ? bodyTablePlacement(def, options.sections, undefined, bodies) + : fieldTabs.overview.length > 0 + ? bodyTablePlacement(def, fieldTabs.overview, undefined, bodies) + : [componentNode('record:details', { sections: [] }), ...bodies]; const items: any[] = [ { label: 'Overview', value: 'details', - children: bodyTablePlacement(def, options.sections, undefined, bodies), + children: overviewChildren, }, ]; + for (const tab of fieldTabs?.tabs ?? []) { + items.push({ + label: tab.label, + value: `${RECORD_PAGE_FIELD_TAB_PREFIX}${tab.key}`, + ...(tab.icon ? { icon: tab.icon } : {}), + children: [componentNode('record:details', { sections: tab.sections })], + }); + } // objectstack#35595 — EVERY ordinary related list is a tab of its own, in // the order the host passed (the object's `relatedLists`, then the derived // order), whether or not it has records: one table, one tab, one count. The @@ -1163,6 +1274,9 @@ function arrangeDeclaredTabs(declared: readonly unknown[] | undefined, items: an const unlistedRelated = tail < names.length ? tail - 0.5 : unlisted; const rank = (tab: any): number | null => { const value = typeof tab?.value === 'string' ? tab.value : ''; + // objectstack#37802 — a field tab is not a related list: no entry places + // it, and it stays right after the overview, in declared order. + if (value.startsWith(RECORD_PAGE_FIELD_TAB_PREFIX)) return -1; const builtin = (Object.keys(BUILTIN_TAB_VALUES) as RecordPageBuiltinTab[]) .find((name) => BUILTIN_TAB_VALUES[name] === value); if (builtin) { diff --git a/ui/packages/plugin-detail/src/synth/recordPageColumns.ts b/ui/packages/plugin-detail/src/synth/recordPageColumns.ts index ad09e5f0870..716ffca3125 100644 --- a/ui/packages/plugin-detail/src/synth/recordPageColumns.ts +++ b/ui/packages/plugin-detail/src/synth/recordPageColumns.ts @@ -37,18 +37,21 @@ * ## Why the layout is derived, with one declared exception * * The tiers are the renderer's. No page template and no node type says - * "columns", and one object key alone steers the layout: `pinOverview` - * (`ObjectSchema.pinOverview`, a ruled exception recorded by ADR-0085's Note - * of 2026-11-27), which keeps the wide full page from pinning the details - * when it is `false` ({@link recordPagePinsDetails}). Everything else is - * derived. The spec's page vocabulary is closed inside its own + * "columns", and two object keys alone steer the layout, both ruled + * exceptions recorded by ADR-0085's Note of 2026-11-27: `pinOverview` + * (`ObjectSchema.pinOverview`), which keeps the wide full page from pinning + * the details when it is `false` ({@link recordPagePinsDetails}), and + * `fieldTabs` (`ObjectSchema.fieldTabs`, objectstack#37802), which draws + * named field groups as tabs of their own right after the overview (their + * `fields:` items). Everything else is derived. The spec's page vocabulary is closed inside its own * namespaces (`record:*`, `page:*`), so a columns node would be a type an * author — or an AI — could write and the spec could not judge, and a Studio * seed carrying it would be refused at save. The layout is therefore read off * the synthesized page itself, by the stable semantic `value` every tab item * carries (`buildDefaultTabs`, objectui#2257): `details` is the 概览 tab * (its path and highlights are the strip, the rest the details column), - * `timeline` (the one stream, objectstack#27055) is the 动态 tab, and each + * `timeline` (the one stream, objectstack#27055) is the 动态 tab, each + * `fields:` is a field tab (objectstack#37802), and each * `related:object.field`, `approvals` and `attachments` is a tab of its own * (objectstack#35595; 动态 last, objectstack#34590). The synthesized page has one region (`main`); a page with * any other region is not the synthesized page (objectstack#27055 removed the @@ -59,6 +62,12 @@ * and the host draws the page as written, tabs and all. */ +import { + RECORD_PAGE_FIELD_TAB_PREFIX, + deriveFieldGroupDetailEntries, + type ObjectDefLike, +} from './buildDefaultPageSchema'; + /** * The console sidebar's width when it is expanded: `SIDEBAR_WIDTH` (16rem) of * the sidebar primitive in `@object-ui/components`. Measured on the console @@ -187,13 +196,14 @@ export const RECORD_PAGE_PIN_MIN_WIDTH = */ export function recordPagePinsDetails( contentWidth: number, - columns: Pick | null | undefined, + columns: (Pick & Pick, 'fieldTabs'>) | null | undefined, fullPage: boolean, pinOverview?: boolean, ): boolean { if (pinOverview === false) return false; if (!fullPage || !columns || !(contentWidth >= RECORD_PAGE_PIN_MIN_WIDTH)) return false; - if (columns.timeline.length === 0 && columns.related.length === 0) return false; + // A field tab (objectstack#37802) is another tab to put beside the details. + if (columns.timeline.length === 0 && columns.related.length === 0 && !(columns.fieldTabs?.length)) return false; return relatedListIdsIn(columns.details).length === 0; } @@ -224,10 +234,11 @@ export const RECORD_PAGE_TIMELINE_PANEL = 'timeline'; /** * Where a synthesized tab's blocks land: the details column, the 动态 panel - * (`timeline`, the last panel of the right column, objectstack#34590) or the - * related panels before it. + * (`timeline`, the last panel of the right column, objectstack#34590), the + * related panels before it, or a field tab of its own (`fields`, + * objectstack#37802). */ -export type RecordPageColumn = 'details' | 'timeline' | 'related'; +export type RecordPageColumn = 'details' | 'timeline' | 'related' | 'fields'; /** * The column a synthesized tab lands in, by the tab's stable `value`; `null` @@ -246,9 +257,25 @@ export function recordPageColumnOfTab(value: unknown): RecordPageColumn | null { if (value === 'timeline' || value === 'activity' || value === 'history') return 'timeline'; if (value === 'related' || value.startsWith('related:')) return 'related'; if (value === 'approvals' || value === 'attachments') return 'related'; + // objectstack#37802 — `fields:`, a tab of the object's `fieldTabs`. + if (value.startsWith(RECORD_PAGE_FIELD_TAB_PREFIX) && value.length > RECORD_PAGE_FIELD_TAB_PREFIX.length) return 'fields'; return null; } +/** + * One field tab of the synthesized page (objectstack#37802, the object's + * `fieldTabs`): its `fields:` id, its title and icon (its first group's, + * as the page item carries them, untranslated), the field groups its sections + * name in order, and its body (`record:details` nodes). + */ +export interface RecordPageFieldTab { + id: string; + label: unknown; + icon?: string; + groups: string[]; + children: any[]; +} + /** The synthesized record page, partitioned for its layout. */ export interface DefaultPageColumns { /** @@ -273,6 +300,12 @@ export interface DefaultPageColumns { timeline: any[]; /** Related lists in the strip's order, then Approvals and Attachments. */ related: any[]; + /** + * The field tabs (objectstack#37802), in the strip's order: right after the + * overview, before the related tabs. Absent on a hand-built partition, read + * as none. + */ + fieldTabs?: RecordPageFieldTab[]; } type PageNode = Record; @@ -320,6 +353,7 @@ export function buildDefaultPageColumns(page: unknown): DefaultPageColumns | nul // declared `relatedLists` may place attachments or approvals among its lists; // undeclared, the tabs already run lists, then attachments, then approvals). const related: any[] = []; + const fieldTabs: RecordPageFieldTab[] = []; for (const rawItem of items) { const item = asNode(rawItem); if (!item) return null; @@ -329,7 +363,15 @@ export function buildDefaultPageColumns(page: unknown): DefaultPageColumns | nul const children = nodeList(item.children); if (column === 'details') details.push(...children); else if (column === 'timeline') timelineTabs.push(...children); - else related.push(...children); + else if (column === 'fields') { + fieldTabs.push({ + id: item.value, + label: item.label, + ...(typeof item.icon === 'string' && item.icon ? { icon: item.icon } : {}), + groups: fieldGroupsIn(children), + children, + }); + } else related.push(...children); } const before = components.slice(0, tabIndex); @@ -339,9 +381,53 @@ export function buildDefaultPageColumns(page: unknown): DefaultPageColumns | nul details, timeline: [...components.slice(tabIndex + 1), ...timelineTabs], related, + fieldTabs, }; } +/** + * The field groups the `record:details` nodes among `nodes` draw, in order: + * each section's `group` (the reference form) or `name` (a resolved section). + */ +export function fieldGroupsIn(nodes: any[]): string[] { + const out: string[] = []; + for (const raw of nodes) { + const node = asNode(raw); + if (node?.type !== 'record:details') continue; + const props = { ...node, ...(asNode(node.properties) ?? {}) }; + for (const section of nodeList(props.sections)) { + const s = asNode(section); + const key = typeof s?.group === 'string' ? s.group : typeof s?.name === 'string' ? s.name : undefined; + if (key !== undefined && !out.includes(key)) out.push(key); + } + } + return out; +} + +/** + * The field tab (`fields:`, objectstack#37802) whose groups hold the + * field `fieldName`, or `null` when the field is drawn in the overview or not + * at all. Read against the object's `fieldGroups` the way `record:details` + * resolves a group's members (`deriveFieldGroupDetailEntries`), so a cited + * section (`?section=`) inside a field tab opens that tab first. + */ +export function fieldTabIdOfField( + columns: Pick, 'fieldTabs'> | null | undefined, + def: ObjectDefLike | undefined, + fieldName: string, +): string | null { + const tabs = columns?.fieldTabs ?? []; + if (tabs.length === 0) return null; + const groupOfField = new Map(); + for (const entry of deriveFieldGroupDetailEntries(def) ?? []) { + if (typeof entry.key !== 'string') continue; + for (const field of entry.section.fields as Array<{ name: string }>) groupOfField.set(field.name, entry.key); + } + const group = groupOfField.get(fieldName); + if (group === undefined) return null; + return tabs.find((tab) => tab.groups.includes(group))?.id ?? null; +} + /** * The relationship ids (`object.field`) of the body tables a synthesized * record page draws (objectstack#27055, Target 8): every `record:related_list` diff --git a/ui/packages/plugin-form/src/fieldTabs.entryForm-37802.test.tsx b/ui/packages/plugin-form/src/fieldTabs.entryForm-37802.test.tsx new file mode 100644 index 00000000000..db851162801 --- /dev/null +++ b/ui/packages/plugin-form/src/fieldTabs.entryForm-37802.test.tsx @@ -0,0 +1,74 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#37802 — the object's `fieldTabs` (`ObjectSchema.fieldTabs`) + * places field groups as tabs of the standard record PAGE only: the entry + * form still draws every group, in one form, the tab's groups included. + * CONTROL: the same object without `fieldTabs` draws the same form. + */ + +import React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, waitFor, cleanup } from '@testing-library/react'; +import { registerAllFields } from '@object-ui/fields'; +import { ModalForm } from './ModalForm'; + +registerAllFields(); + +const SCHEMA = { + name: 'ticket', + fieldGroups: [ + { key: 'basic', label: 'Basic Info' }, + { key: 'tracking', label: 'Tracking Info' }, + ], + fields: { + title: { type: 'text', label: 'Title', group: 'basic' }, + assignee: { type: 'text', label: 'Assignee', group: 'basic' }, + status_note: { type: 'text', label: 'Status Note', group: 'tracking' }, + channel: { type: 'text', label: 'Channel', group: 'tracking' }, + }, +}; + +const makeDS = (objectSchema: any) => + ({ + getObjectSchema: vi.fn().mockResolvedValue(objectSchema), + create: vi.fn().mockResolvedValue({ id: 't1' }), + update: vi.fn().mockResolvedValue({ id: 't1' }), + findOne: vi.fn().mockResolvedValue({ id: 't1' }), + }) as any; + +afterEach(() => cleanup()); + +async function drawnForm(objectSchema: any) { + render( + , + ); + await waitFor(() => expect(document.body.textContent).toContain('Tracking Info')); + const forms = document.body.querySelectorAll('form'); + expect(forms.length).toBe(1); + return { + text: forms[0].textContent ?? '', + inputs: Array.from(forms[0].querySelectorAll('input')).map((i) => i.getAttribute('name')), + }; +} + +describe('fieldTabs leaves the entry form alone (objectstack#37802)', () => { + it("draws every group, the tab's group included, as the same object without fieldTabs does", async () => { + const control = await drawnForm(SCHEMA); + cleanup(); + const withTabs = await drawnForm({ ...SCHEMA, fieldTabs: [{ key: 'tracking', groups: ['tracking'] }] }); + expect(withTabs.text).toContain('Basic Info'); + expect(withTabs.text).toContain('Tracking Info'); + expect(withTabs.inputs).toEqual(['title', 'assignee', 'status_note', 'channel']); + expect(withTabs.inputs).toEqual(control.inputs); + }); +}); diff --git a/ui/packages/types/src/__tests__/form-field-tabs-object-shape.test.ts b/ui/packages/types/src/__tests__/form-field-tabs-object-shape.test.ts new file mode 100644 index 00000000000..059bacfa400 --- /dev/null +++ b/ui/packages/types/src/__tests__/form-field-tabs-object-shape.test.ts @@ -0,0 +1,42 @@ +/** + * 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#37802 — `FormSchema.fieldTabs` and the object-level + * `ObjectSchema.fieldTabs` (`@objectstack/spec`, ADR-0085's Note of + * 2026-11-27) share a key name and differ in shape: a form tab claims field + * names in `fields`, a record-page field tab names field groups in `groups`. + * An entry written in the other shape here is refused with a message that + * names the object-level key (the spec's refusal names this one). + */ + +import { describe, expect, it } from 'vitest'; +import { FormSchema } from '../zod/form.zod'; + +const form = (fieldTabs: unknown) => ({ + type: 'form', + fields: [{ name: 'body', label: 'Body', type: 'textarea' }], + fieldTabs, +}); + +describe('FormSchema.fieldTabs — the object-level shape is refused by name', () => { + it('still parses a form tab that lists fields', () => { + expect(FormSchema.safeParse(form([{ key: 'content', fields: ['body'] }])).success).toBe(true); + }); + + it('refuses an entry that names groups instead of fields, naming ObjectSchema.fieldTabs', () => { + const result = FormSchema.safeParse(form([{ key: 'content', groups: ['content'] }])); + expect(result.success).toBe(false); + if (!result.success) { + // The missing `fields` is the one issue, and it names the object-level + // key. (A `groups` list beside `fields` passes through the loose entry, + // as it did before: refusing it would narrow this published parse.) + expect(result.error.issues).toHaveLength(1); + expect(result.error.issues[0].path).toEqual(['fieldTabs', 0, 'fields']); + expect(result.error.issues[0].message).toContain('ObjectSchema.fieldTabs'); + } + }); +}); diff --git a/ui/packages/types/src/zod/form.zod.ts b/ui/packages/types/src/zod/form.zod.ts index 4a0c95eb5e8..131b7291d47 100644 --- a/ui/packages/types/src/zod/form.zod.ts +++ b/ui/packages/types/src/zod/form.zod.ts @@ -1287,7 +1287,16 @@ const FormFieldTabEntrySchema = z.looseObject({ key: z.string().describe('Stable tab key (the Radix Tabs value)'), label: z.string().optional().describe('Tab trigger text; falls back to key'), description: z.string().optional().describe('Blurb rendered above the tab fields'), - fields: z.array(z.string()).describe('Names of the fields (from FormSchema.fields) this tab renders, in order'), + fields: z.array(z.string(), { + // ADR-0085's Note of 2026-11-27 — the object-level `ObjectSchema.fieldTabs` + // (`@objectstack/spec`) shares this key name and names field GROUPS; an + // entry written in that shape here lacks `fields`, so the refusal names it. + error: (issue) => issue.input === undefined + ? 'A form\'s fieldTabs entry lists the fields it renders in `fields` (field names from FormSchema.fields). ' + + 'Naming field groups in `groups` is the object-level `ObjectSchema.fieldTabs` (the record page\'s field tabs), ' + + 'declared on the object, not on a form.' + : undefined, + }).describe('Names of the fields (from FormSchema.fields) this tab renders, in order'), containerClass: z.string().optional().describe('Field-grid classes for this tab panel'), visibleWhen: ExpressionWireSchema.optional() .describe('Predicate gating the tab: a bare string or the { dialect?, source } envelope; a hidden tab still submits'),