diff --git a/.changeset/35897-related-lists-tab-list.md b/.changeset/35897-related-lists-tab-list.md new file mode 100644 index 00000000000..493887e365c --- /dev/null +++ b/.changeset/35897-related-lists-tab-list.md @@ -0,0 +1,36 @@ +--- +'@objectstack/spec': minor +'@objectstack/lint': minor +'@object-ui/plugin-detail': minor +'@object-ui/app-shell': minor +'@object-ui/i18n': minor +'@objectstack/platform-objects': patch +--- + +feat(spec): an object's `relatedLists` is its record page's tab list — only the listed related lists show, in order, the attachments, approvals and activity-stream tabs are placed by object name, and an entry can carry its list's title and columns + +Clause-②: yes (widening) +Metadata-protocol: semantic + +A record page's tabs are now declared on the parent object, in one place: + +```ts +relatedLists: [ + { list: 'quote_line', label: 'Line items', columns: ['product', 'quantity', 'unit_price', 'amount'] }, + 'task', + 'sys_attachment', + 'sys_approval_request', + 'sys_activity', +], +``` + +- **No `relatedLists` (or an empty one): nothing changes.** Every related list shows, in the derived order, then attachments, approvals and the activity stream. +- **A declared `relatedLists` now decides which tabs show**, not only their order. A related list no entry names shows no tab; before, it still followed the listed ones. Removing an entry removes its tab. Body tables a field group places in the overview (`fieldGroups[].relatedList`) stay at their group, and the tab such a `master_detail` table also keeps on an undeclared page shows only when an entry names it, and `relatedList: false` on the child's FK still hides a list. +- **This narrows the #35889 note** ("Its tab stays on the tab row too, with its count"): the tab of a `master_detail` child that a field group places in the overview stays only while the parent declares no `relatedLists`; once it declares one, that tab shows only if an entry names the child. +- **The three built-in tabs by object name**: `'sys_attachment'` (attachments; shown only when listed, and still only when the object enables files), `'sys_approval_request'` (approvals; still only on a record with requests, and when unlisted it follows the listed tabs), `'sys_activity'` (the one activity stream; when unlisted it closes the strip). A built-in is written only as its bare name: `{ list: 'sys_attachment', … }` is refused at parse. `'sys_comment'` and `'sys_audit_log'` are parts of the stream, not tabs: `os validate` warns (`related-list-stream-part`) and prescribes `'sys_activity'`. `'sys_attachment'` on an object without files warns (`related-list-attachments-off`). +- **An entry's own title and columns**: `{ list, label?, columns? }` wins over the child FK's `relatedListTitle` / `relatedListColumns`, which keep working unchanged. The columns are child field names, used wherever the list is drawn (its tab, and the body table a field group places); a dotted column (`account.industry`) walks the child's relationships, as `relatedListColumns` does, and a name that resolves to no field of the child is refused (`related-list-column-unknown`) by `os validate`, `os build` and the metadata write door. + +- **The generic object form** (metadata admin) edits `relatedLists` with its own chip input: a bare name and an object entry both show and both survive add and remove (the entry's title and columns beside its name; they are edited in Studio). Its help text states the tab-list meaning in every translated locale. +- **Studio** (object settings, Record page tabs): the editor lists the entries in order, the built-in tabs among them, and offers the built-ins not yet listed (attachments only when the object enables files). A relationship row's edit sets its own title and columns, and clearing both writes the bare name again. The relationships not listed are shown below as having no tab. A move, a removal or an add keeps every entry's object form and every built-in name. + +What to check in an app: an object that already declares `relatedLists` and leaves some related lists out now shows only the listed ones, and shows no attachments tab unless `'sys_attachment'` is listed. List every tab the page should keep, or remove `relatedLists` to show them all. A child list another package adds is hidden too until the parent names it, which a build accepts only when that package is in the parent's stack; letting a package place its own list is a later change. ADR-0087 semantic entry `related-lists-declared-is-tab-list`. diff --git a/content/docs/references/api/metadata.mdx b/content/docs/references/api/metadata.mdx index 4e4fbb8fe4c..a14aa3feba7 100644 --- a/content/docs/references/api/metadata.mdx +++ b/content/docs/references/api/metadata.mdx @@ -963,7 +963,7 @@ Metadata query with filtering, sorting, and pagination | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | | **imageField** | `string` | optional | The record's picture: names the field the record page header (record chrome) draws beside the title — one object-level declaration every record detail page reads, not a per-page header prop. Must name a field of this object whose type is `image` or `avatar`; any other name is refused. A record whose field is empty shows no picture (no initials or placeholder). | | **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[]` | optional | Business order of this object's related lists on its record page, most important first. Each entry is a child object name (e.g. "task"), or object.field when that child has more than one relationship to this object (e.g. "event.related_to"). Listed relationships come first in this order; unlisted ones follow in the derived order (owned master_detail children, then lookup children). An entry whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere. An entry 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, since a child outside the package may be a downstream package's object that points here, and the record page places nothing for it. It orders only: relatedList: false on the relationship still hides a list, and relatedList: 'primary' still places a list in the record's body, so the order applies among the body tables and among the side cards. | +| **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. That includes a child list another package adds: it is hidden until this object names it, which a build accepts only when that package is in the stack (letting a package place its own list is a later change). 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. | | **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/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index 543e017a1ce..7e6ea414ee1 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 13 more — each property with its type, default and a TypeScript example." +description: "Object schemas of the ObjectStack Data Protocol: ApiMethod, ApiOperation, Index and 15 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, ObjectExternalBindingSchema, ObjectFieldGroupSchema, ObjectOwnershipEnum, ObjectRequiredPermissionsSchema, PerOperationRequiredPermissionsSchema, RowCrudActionOverrideSchema, TenancyConfigSchema } from '@objectstack/spec/data'; -import type { ApiMethod, ApiOperation, Lifecycle, LifecycleClass, ObjectAccessConfig, ObjectCapabilities, ObjectExtension, ObjectExternalBinding, ObjectFieldGroup, ObjectRequiredPermissions, PerOperationRequiredPermissions, RowCrudActionOverride, TenancyConfig } from '@objectstack/spec/data'; +import { ApiMethod, ApiOperationSchema, IndexSchema, LifecycleSchema, LifecycleClassSchema, ObjectSchema, ObjectAccessConfigSchema, ObjectCapabilities, ObjectExtensionSchema, ObjectExternalBindingSchema, ObjectFieldGroupSchema, ObjectOwnershipEnum, ObjectRequiredPermissionsSchema, PerOperationRequiredPermissionsSchema, RelatedListEntrySchema, RelatedListEntryObjectSchema, RowCrudActionOverrideSchema, TenancyConfigSchema } from '@objectstack/spec/data'; +import type { ApiMethod, ApiOperation, Lifecycle, LifecycleClass, ObjectAccessConfig, ObjectCapabilities, ObjectExtension, ObjectExternalBinding, ObjectFieldGroup, ObjectRequiredPermissions, PerOperationRequiredPermissions, RelatedListEntry, RelatedListEntryObject, RowCrudActionOverride, TenancyConfig } from '@objectstack/spec/data'; // Validate data const result = ApiMethod.parse(data); @@ -175,7 +175,7 @@ const result = ApiMethod.parse(data); | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | | **imageField** | `string` | optional | The record's picture: names the field the record page header (record chrome) draws beside the title — one object-level declaration every record detail page reads, not a per-page header prop. Must name a field of this object whose type is `image` or `avatar`; any other name is refused. A record whose field is empty shows no picture (no initials or placeholder). | | **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[]` | optional | Business order of this object's related lists on its record page, most important first. Each entry is a child object name (e.g. "task"), or object.field when that child has more than one relationship to this object (e.g. "event.related_to"). Listed relationships come first in this order; unlisted ones follow in the derived order (owned master_detail children, then lookup children). An entry whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere. An entry 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, since a child outside the package may be a downstream package's object that points here, and the record page places nothing for it. It orders only: relatedList: false on the relationship still hides a list, and relatedList: 'primary' still places a list in the record's body, so the order applies among the body tables and among the side cards. | +| **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. That includes a child list another package adds: it is hidden until this object names it, which a build accepts only when that package is in the stack (letting a package place its own list is a later change). 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. | | **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) | @@ -383,6 +383,14 @@ const result = ApiMethod.parse(data); | **summary** | `string` | ✅ | Activity summary template; `{field}` tokens interpolate the record value. e.g. "Deal won: `{name}`". | | **type** | `string` | optional | Activity type for the emitted row — left unset, it keeps the update row's kind, "updated" (a milestone only fires on an update). | +### Nested Shape: `Object.relatedLists[number]` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **list** | `string` | ✅ | The relationship this entry names: a child object name (e.g. "quote_line"), or object.field when that child has more than one relationship to this object. | +| **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.listViews[string]` | Property | Type | Required | Description | @@ -827,6 +835,46 @@ Type: `string[]` | **delete** | `string[]` | optional | Capabilities required to delete (delete/purge). | +--- + +## RelatedListEntry + +### Union Options + +This schema accepts one of the following structures: + +#### Option 1 + +Type: `string` + +--- + +#### Option 2 + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **list** | `string` | ✅ | The relationship this entry names: a child object name (e.g. "quote_line"), or object.field when that child has more than one relationship to this object. | +| **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. | + +--- + + +--- + +## RelatedListEntryObject + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **list** | `string` | ✅ | The relationship this entry names: a child object name (e.g. "quote_line"), or object.field when that child has more than one relationship to this object. | +| **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. | + + --- ## RowCrudActionOverride diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index eaaeb17ba7a..9e4d718f8e7 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 — 1701 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1703 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/. */} @@ -23,7 +23,7 @@ counts are sums of the rows they head. Regenerate with | [AI Protocol](/docs/references/ai) | 14 | 84 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](/docs/references/api) | 37 | 521 | 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 | 189 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | +| [Data Protocol](/docs/references/data) | 35 | 191 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | | [Identity Protocol](/docs/references/identity) | 5 | 27 | Users and accounts, organizations, positions, SCIM provisioning. | | [Integration Protocol](/docs/references/integration) | 1 | 23 | The single connector protocol (ADR-0097) — catalog descriptors and provider-bound instances. | | [Kernel Protocol](/docs/references/kernel) | 30 | 153 | Plugin lifecycle and manifests, capabilities and security, metadata loading, service registry. | @@ -34,7 +34,7 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](/docs/references/system) | 40 | 297 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 16 | 180 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **219** | **1701** | 14 protocol modules | +| **Total** | **219** | **1703** | 14 protocol modules | --- @@ -140,7 +140,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, 189 schemas** +**Source:** `packages/spec/src/data/` · **Import:** `@objectstack/spec/data` · **35 pages, 191 schemas** Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. @@ -173,7 +173,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`, `ObjectExternalBinding`, `ObjectFieldGroup`, `ObjectOwnershipEnum`, `ObjectRequiredPermissions`, `PerOperationRequiredPermissions`, `RowCrudActionOverride`, `TenancyConfig` | +| [`object.zod.ts`](/docs/references/data/object) | `ApiMethod`, `ApiOperation`, `Index`, `Lifecycle`, `LifecycleClass`, `Object`, `ObjectAccessConfig`, `ObjectCapabilities`, `ObjectExtension`, `ObjectExternalBinding`, `ObjectFieldGroup`, `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/references/system/migration.mdx b/content/docs/references/system/migration.mdx index 6721981500d..f617abfe6f0 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -355,7 +355,7 @@ Create a new object | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | | **imageField** | `string` | optional | The record's picture: names the field the record page header (record chrome) draws beside the title — one object-level declaration every record detail page reads, not a per-page header prop. Must name a field of this object whose type is `image` or `avatar`; any other name is refused. A record whose field is empty shows no picture (no initials or placeholder). | | **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[]` | optional | Business order of this object's related lists on its record page, most important first. Each entry is a child object name (e.g. "task"), or object.field when that child has more than one relationship to this object (e.g. "event.related_to"). Listed relationships come first in this order; unlisted ones follow in the derived order (owned master_detail children, then lookup children). An entry whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere. An entry 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, since a child outside the package may be a downstream package's object that points here, and the record page places nothing for it. It orders only: relatedList: false on the relationship still hides a list, and relatedList: 'primary' still places a list in the record's body, so the order applies among the body tables and among the side cards. | +| **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. That includes a child list another package adds: it is hidden until this object names it, which a build accepts only when that package is in the stack (letting a package place its own list is a later change). 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. | | **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) | @@ -658,7 +658,7 @@ Create a new object | **titleFormat** | `string \| { dialect: 'template'; source?: string; ast?: any; meta?: object }` | optional | [DEPRECATED → nameField (ADR-0079)] Render-only title template; the server cannot return or query it, and an explicit nameField now takes precedence. An object definition that declares it is refused at the metadata save gate and by os validate; a stored object that carries it still parses and reads. Migrate a single-field title to nameField; a composite title that import, sort or search must match to a stored computed field (a non-formula field with an expression, computed and stored on every write) designated as nameField — a text formula designated as nameField stays legal for a title shown for display only. Placeholders may be written `{{field}}` or `{field}` — the title renderers treat the two as equivalent, normalizing `{{field}}` to `{field}` before substituting; neither spelling is judged at parse time. | | **imageField** | `string` | optional | The record's picture: names the field the record page header (record chrome) draws beside the title — one object-level declaration every record detail page reads, not a per-page header prop. Must name a field of this object whose type is `image` or `avatar`; any other name is refused. A record whose field is empty shows no picture (no initials or placeholder). | | **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[]` | optional | Business order of this object's related lists on its record page, most important first. Each entry is a child object name (e.g. "task"), or object.field when that child has more than one relationship to this object (e.g. "event.related_to"). Listed relationships come first in this order; unlisted ones follow in the derived order (owned master_detail children, then lookup children). An entry whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere. An entry 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, since a child outside the package may be a downstream package's object that points here, and the record page places nothing for it. It orders only: relatedList: false on the relationship still hides a list, and relatedList: 'primary' still places a list in the record's body, so the order applies among the body tables and among the side cards. | +| **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. That includes a child list another package adds: it is hidden until this object names it, which a build accepts only when that package is in the stack (letting a package place its own list is a later change). 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. | | **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/content/docs/ui/pages.mdx b/content/docs/ui/pages.mdx index 0ebf271eb8b..a64d234caea 100644 --- a/content/docs/ui/pages.mdx +++ b/content/docs/ui/pages.mdx @@ -232,9 +232,10 @@ synthesizer fills in the rest. A slotted page authors `slots`, not `regions`: Each slot takes one component or an array of them, and replaces its part whole: there is no deep merge. There is no `tabs` slot: the page's panels are composed from the object's fields -and relationship flags. To change which related lists appear or their order, set `relatedList` / -`relatedList: 'primary'` on the child's reference field; a page that needs its own strip is -`kind: 'full'`, drawn as authored. `slots.tabs`, `slots.related` and `slots.relatedLists` are +and relationship flags. To choose which related lists and built-in tabs appear and in what +order, list them in the object's `relatedLists` (the built-ins by object name: `sys_attachment`, +`sys_approval_request`, `sys_activity`); `relatedList: false` on the child's reference field +still hides a list. A page that needs its own strip is `kind: 'full'`, drawn as authored. `slots.tabs`, `slots.related` and `slots.relatedLists` are refused by name, and `os migrate meta --from 17` drops a stored `slots.tabs`. {/* os:check */} diff --git a/docs/adr/0035-config-driven-master-detail.md b/docs/adr/0035-config-driven-master-detail.md index c6f65f22780..f4ba9250c52 100644 --- a/docs/adr/0035-config-driven-master-detail.md +++ b/docs/adr/0035-config-driven-master-detail.md @@ -1,6 +1,6 @@ # ADR-0035: Config-driven master-detail (declare on the relationship, forms derive) -**Status**: Accepted · **Amended** (2026-10-28, [#27069](https://github.com/objectstack-ai/objectstack/issues/27069), maintainer rulings on that card: 「A」, an ordered list on the parent, and 「明细行的子表放在右侧合适嘛?」 / 「他如果做到放在基本信息下面,而条款和备注在后面」, line items in the record body) — `relatedList: 'primary'` is a **placement** (the record body, as a full-width table), no longer a prominence hint that orders lists; the order is the parent object's `relatedLists`; and an omitted `relatedList` on a `master_detail` FK that sets `inlineEdit` is now `'primary'` by default. See the note under the read-side table. · **Amended** (2026-11-19, [#35597](https://github.com/objectstack-ai/objectstack/issues/35597), under the record-page epic [#35590](https://github.com/objectstack-ai/objectstack/issues/35590), maintainer's words on that card: 「就是master-detail表类型的子表」 / 「主从的子表是否应该默认出现在概览的左侧区域?关键字段下面。」) — an omitted `relatedList` on ANY `master_detail` FK is `'primary'` (a body table) by default, `inlineEdit` or not; its totals are server-owned. See the second note under the read-side table. · **Amended** (2026-11-20, [#35889](https://github.com/objectstack-ai/objectstack/issues/35889), same epic, maintainer's words on that card: 「主从子表我认为不应该自动申明放在概览中,除非我通过 fieldGroup 强制指定」) — that default is withdrawn: an omitted `relatedList` on a `master_detail` FK is a tab, and the list is a body table (in the record page, the parent's forms and its edit state) only where a parent field group names it, and `inlineEdit` no longer inlines a child in the form by itself. See the third note under the read-side table. +**Status**: Accepted · **Amended** (2026-10-28, [#27069](https://github.com/objectstack-ai/objectstack/issues/27069), maintainer rulings on that card: 「A」, an ordered list on the parent, and 「明细行的子表放在右侧合适嘛?」 / 「他如果做到放在基本信息下面,而条款和备注在后面」, line items in the record body) — `relatedList: 'primary'` is a **placement** (the record body, as a full-width table), no longer a prominence hint that orders lists; the order is the parent object's `relatedLists`; and an omitted `relatedList` on a `master_detail` FK that sets `inlineEdit` is now `'primary'` by default. See the note under the read-side table. · **Amended** (2026-11-19, [#35597](https://github.com/objectstack-ai/objectstack/issues/35597), under the record-page epic [#35590](https://github.com/objectstack-ai/objectstack/issues/35590), maintainer's words on that card: 「就是master-detail表类型的子表」 / 「主从的子表是否应该默认出现在概览的左侧区域?关键字段下面。」) — an omitted `relatedList` on ANY `master_detail` FK is `'primary'` (a body table) by default, `inlineEdit` or not; its totals are server-owned. See the second note under the read-side table. · **Amended** (2026-11-20, [#35889](https://github.com/objectstack-ai/objectstack/issues/35889), same epic, maintainer's words on that card: 「主从子表我认为不应该自动申明放在概览中,除非我通过 fieldGroup 强制指定」) — that default is withdrawn: an omitted `relatedList` on a `master_detail` FK is a tab, and the list is a body table (in the record page, the parent's forms and its edit state) only where a parent field group names it, and `inlineEdit` no longer inlines a child in the form by itself. See the third note under the read-side table. · **Amended** (2026-11-20, [#35897](https://github.com/objectstack-ai/objectstack/issues/35897) and [#35899](https://github.com/objectstack-ai/objectstack/issues/35899), epic [#35896](https://github.com/objectstack-ai/objectstack/issues/35896), maintainer's words: 「其实除了 overview,我们直接用 relatedLists 是不是就可以。」 / 「三个内置项,是不是可以直接用对应的对象名」) — a declared `relatedLists` is the record page's tab list (unlisted side lists show no tab), with the attachments, approvals and activity-stream tabs placed by object name and an entry's own title and columns. See the fourth note under the read-side table. **Author**: surfaced while making master-detail (parent + child line-item) entry a first-class, low-config capability **Affects**: `@objectstack/spec` (field schema), `@object-ui/plugin-form`, `@object-ui/plugin-view`, `@object-ui/app-shell`; builds on ADR-0034 (atomic multi-write) and the cross-object batch endpoint (#1604) @@ -149,7 +149,9 @@ a self-referential FK surfaces a "children" list. > child object name or `object.field`): the record page draws it at that > group's position, the parent's create and edit forms inline it, and the > record page's Edit saves the record fields and its rows in one batch -> (#35599); its tab stays on the tab row. `relatedList: 'primary'` on the FK +> (#35599); its tab stays on the tab row (on a record page whose object +> declares no `relatedLists`: a declared one decides the tabs, see the next +> note). `relatedList: 'primary'` on the FK > still makes a body table with no group (and no tab, positioned by a group or not), `true` keeps a tab that no group can > place, and `false` hides it. The set a field group may name is unchanged > (`isGroupPlaceableRelationship`, read by the refusal at `defineStack` and at @@ -169,6 +171,33 @@ a self-referential FK surfaces a "children" list. > group (a `master_detail` FK may instead drop `relatedList: true`); a group > naming a list its FK hides (`false`) is refused. +> **Amended (2026-11-20, #35897 and #35899; epic #35896).** The sentence +> "unlisted lists follow in the derived order described above (owned first)" +> of the 2026-10-28 note no longer holds for a DECLARED `relatedLists`: that +> list is now the record page's tab list (the maintainer on the epic: +> 「删除tab就是不现实」, meaning removing a tab is not showing it; 「其实除了 +> overview,我们直接用 relatedLists 是不是就可以」). A side list no entry names +> shows no tab; the listed ones show in the listed order. That includes a child +> list another package adds: it is hidden until the parent names it, and a build +> accepts that name only when the package is in the parent's stack (an extension +> package placing its own list is the epic's child card #35901). The record page's +> three built-in tabs are entries too, by the platform object each draws +> (「三个内置项,是不是可以直接用对应的对象名」): `sys_attachment` (shown only +> when listed, and still only with `enable.files`), `sys_approval_request` +> (when unlisted it follows the listed tabs, and still only on a record with +> requests) and `sys_activity` (the one stream; when unlisted it closes the +> strip). An entry may be `{ list, label, columns }`, giving that list its +> title and columns on the parent; they win over the FK's `relatedListTitle` / +> `relatedListColumns` wherever the list is drawn. Unchanged: an undeclared or +> empty `relatedLists` shows every list in the derived order; `false` still +> suppresses a list whatever `relatedLists` says; body tables are placed by +> the field groups, not hidden by this list. A `master_detail` list that a +> field group places keeps its tab (the note above) only while `relatedLists` +> is undeclared: once it is declared, that list shows a tab only if an entry +> names it, and its body table stays at its group. See +> [ADR-0085](./0085-object-semantic-roles-over-surface-hint-blocks.md)'s note +> of the same date. + > **Note (2026-11-21, #35889, second slice).** The entry form now draws a > placed child where the record page does, so "placed in the form below the > record's fields until the form places it at the group" above is superseded. diff --git a/docs/adr/0085-object-semantic-roles-over-surface-hint-blocks.md b/docs/adr/0085-object-semantic-roles-over-surface-hint-blocks.md index e282d746aff..523faa5e21d 100644 --- a/docs/adr/0085-object-semantic-roles-over-surface-hint-blocks.md +++ b/docs/adr/0085-object-semantic-roles-over-surface-hint-blocks.md @@ -80,6 +80,30 @@ Keys that merely hide/re-arrange correct information (`hideRelatedTab`, `showRef > ([ADR-0035](./0035-config-driven-master-detail.md)'s amendment of the same > date). +> **Note (2026-11-20, [#35897](https://github.com/objectstack-ai/objectstack/issues/35897) and +> [#35899](https://github.com/objectstack-ai/objectstack/issues/35899), epic +> [#35896](https://github.com/objectstack-ai/objectstack/issues/35896)).** The maintainer's +> words on the epic: 「但是你看右侧,他显示哪些子表都是通过tab配置出来的。删除tab就是不现实。」 +> (that is, removing a tab means not showing it), 「其实除了 overview,我们直接用 relatedLists +> 是不是就可以。」 and 「三个内置项,是不是可以直接用对应的对象名」, then 「按对象名这版,立专题」. +> So a **declared** `relatedLists` is now the object's record-page TAB LIST, not only an order: +> the related lists it names show, in its order, and a side list it leaves out shows no tab. +> The attachments, approvals and activity-stream tabs are placed in it by the platform object +> each draws (`sys_attachment`, `sys_approval_request`, `sys_activity`), and an entry may give +> its list a title and columns on the parent (`{ list, label, columns }`). This is the one +> place §2's "keys that merely hide/re-arrange correct information are rejected at this +> layer" yields, by that ruling: the key still passes both admission tests as the 2026-10-28 +> note reads them (which relationships matter on this object is business intent; it binds +> every record surface and names no page), and showing is now part of that intent rather +> than a page toggle. The guard keeps its force for every other key: no per-page show/hide +> switch (`hideRelatedTab`, `showReferenceRail`) returns, and an undeclared `relatedLists` +> shows every list as before. Body tables stay the field groups' to place (`fieldGroups[] +> .relatedList`); the FK's `relatedList: false` still hides a list everywhere. A child list +> another package adds is no exception: once `relatedLists` is declared it shows no tab until +> the parent names it, and a build accepts that name only when the package is in the parent's +> stack. Letting an extension package place its own list is the epic's child card +> [#35901](https://github.com/objectstack-ai/objectstack/issues/35901). + ### 3. Deletions (all evidenced zero-author) - **`detail` block removed from `ObjectSchema`** — all three typed keys. `renderViaSchema` retires *together with* the legacy monolith renderer path in objectui (separate execution PR; the key is only that path's steering wheel, deleting it alone saves nothing). `hideReferenceRail`/`hideRelatedTab` are removed outright (the former is a proven no-op for spec authors; the latter's raison d'être — overriding rail/tab dedup — died with the rail). 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 93df1055baf..f6854312c89 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/` | 179 | 110 | 2 | 0 | 67 | +| `data/` | 180 | 111 | 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` | 26 | +| `object.zod.ts` | 27 | | `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** | **179** | +| **total** | **180** | ## `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 179**, in 11 file(s). +**67 strip of 180**, 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** | **179** | +| **total** | **67** | **180** | | Bucket | Sites | |---|---| diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 6187c889800..bb437de7c7a 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -660,11 +660,17 @@ export type { // `relatedList` must match an inbound lookup / master_detail relationship. // `error`, the verdict `defineStack` gives, and on the runtime publish door, // which runs no `defineStack`. [#27478] A field group's `relatedList` must -// name body tables only (`related-list-group-not-body`). +// name body tables only (`related-list-group-not-body`). [#35897 · #35899] A +// `relatedLists` object entry's columns must be child fields +// (`related-list-column-unknown`, error); a built-in tab entry that draws +// nothing warns (`related-list-attachments-off`, `related-list-stream-part`). export { validateRelatedListRefs, RELATED_LIST_REF_UNKNOWN, RELATED_LIST_GROUP_NOT_BODY, + RELATED_LIST_COLUMN_UNKNOWN, + RELATED_LIST_ATTACHMENTS_OFF, + RELATED_LIST_STREAM_PART, } from './validate-related-list-refs.js'; export type { RelatedListRefFinding, diff --git a/packages/lint/src/rule-explanations.ts b/packages/lint/src/rule-explanations.ts index 94f23356a2d..0789d815581 100644 --- a/packages/lint/src/rule-explanations.ts +++ b/packages/lint/src/rule-explanations.ts @@ -4745,6 +4745,45 @@ const RELATED_LIST_GROUP_NOT_BODY_EXPLANATION: RuleExplanation = { ], }; +const RELATED_LIST_COLUMN_UNKNOWN_EXPLANATION: RuleExplanation = { + rule: 'related-list-column-unknown', + covers: "the columns a relatedLists entry may name", + paragraphs: [ + 'A `relatedLists` entry may be written `{ list, label, columns }` to give that related list its own ' + + 'title and columns on the parent object. The columns are field names of the CHILD object, the one ' + + 'whose rows the list shows, exactly as the child FK\'s `relatedListColumns` names them; they win over ' + + 'that key wherever the list is drawn.', + 'A column that is no field of the child draws an empty column, silently, so it is an error on ' + + '`os validate`, `os build` and at the runtime publish gate. Judged against every child the entry ' + + 'names whose fields this rule can see (the authored fields and the registry-injected columns); a ' + + 'child outside the stack is not judged here.', + ], +}; + +const RELATED_LIST_ATTACHMENTS_OFF_EXPLANATION: RuleExplanation = { + rule: 'related-list-attachments-off', + covers: "'sys_attachment' in relatedLists without files enabled", + paragraphs: [ + "`'sys_attachment'` in `relatedLists` places the record page's attachments tab. The tab is drawn only " + + 'for an object that enables files (`enable.files: true`), the same gate the server enforces on ' + + 'attachment rows, so on an object without files the entry places nothing.', + 'A warning, not an error: the entry is not wrong in itself and becomes live the moment the object ' + + "turns files on. Enable files to show the tab, or remove `'sys_attachment'`.", + ], +}; + +const RELATED_LIST_STREAM_PART_EXPLANATION: RuleExplanation = { + rule: 'related-list-stream-part', + covers: 'a relatedLists entry naming a part of the activity stream', + paragraphs: [ + "The record page draws activities, the discussion and field changes as ONE stream, whose tab " + + "`relatedLists` names `'sys_activity'`. `'sys_comment'` and `'sys_audit_log'` are parts of that " + + 'stream, not tabs of their own, so an entry naming one places nothing.', + "A warning, prescribing `'sys_activity'`. Which parts the stream shows is still the object's own " + + 'switches (`enable.feeds`, `enable.activities`, `trackHistory`).', + ], +}; + // ── Object-name references (`validate-object-references.ts`) ──────────────── /** The sites judged — both object-reference ids. */ @@ -6602,6 +6641,9 @@ export const RULE_EXPLANATIONS: Readonly> = Obje [OBJECT_FIELD_REF_UNKNOWN_EXPLANATION.rule]: OBJECT_FIELD_REF_UNKNOWN_EXPLANATION, [RELATED_LIST_REF_UNKNOWN_EXPLANATION.rule]: RELATED_LIST_REF_UNKNOWN_EXPLANATION, [RELATED_LIST_GROUP_NOT_BODY_EXPLANATION.rule]: RELATED_LIST_GROUP_NOT_BODY_EXPLANATION, + [RELATED_LIST_COLUMN_UNKNOWN_EXPLANATION.rule]: RELATED_LIST_COLUMN_UNKNOWN_EXPLANATION, + [RELATED_LIST_ATTACHMENTS_OFF_EXPLANATION.rule]: RELATED_LIST_ATTACHMENTS_OFF_EXPLANATION, + [RELATED_LIST_STREAM_PART_EXPLANATION.rule]: RELATED_LIST_STREAM_PART_EXPLANATION, [OBJECT_REFERENCE_UNKNOWN_EXPLANATION.rule]: OBJECT_REFERENCE_UNKNOWN_EXPLANATION, [OBJECT_REFERENCE_UNREGISTERED_PLATFORM_EXPLANATION.rule]: OBJECT_REFERENCE_UNREGISTERED_PLATFORM_EXPLANATION, [CAPABILITY_REFERENCE_UNKNOWN_EXPLANATION.rule]: CAPABILITY_REFERENCE_UNKNOWN_EXPLANATION, diff --git a/packages/lint/src/validate-related-list-refs.test.ts b/packages/lint/src/validate-related-list-refs.test.ts index 5f472b9ba19..c244491786b 100644 --- a/packages/lint/src/validate-related-list-refs.test.ts +++ b/packages/lint/src/validate-related-list-refs.test.ts @@ -10,8 +10,11 @@ import { describe, expect, it } from 'vitest'; import { defineStack } from '@objectstack/spec'; import { + RELATED_LIST_ATTACHMENTS_OFF, + RELATED_LIST_COLUMN_UNKNOWN, RELATED_LIST_GROUP_NOT_BODY, RELATED_LIST_REF_UNKNOWN, + RELATED_LIST_STREAM_PART, validateRelatedListRefs, } from './validate-related-list-refs.js'; @@ -133,3 +136,73 @@ describe('validateRelatedListRefs', () => { expect(issues).toEqual(messages); }); }); + +/** + * [#35897 · #35899] The built-in tab names and an object entry's own columns. + * Each finding row's control differs from it by one key or one entry. + */ +describe('validateRelatedListRefs — built-in tabs and an entry\'s columns', () => { + const findings = (stack: Record, wholeCollection?: boolean) => + validateRelatedListRefs(stack, wholeCollection ? { wholeCollection } : undefined).map((f) => [f.severity, f.rule, f.path]); + // The platform objects as the runtime door's whole collection holds them: none points at the parent. + const platform = [ + { name: 'sys_attachment', label: 'Attachment', fields: { file_name: { type: 'text', label: 'File' } } }, + { name: 'sys_comment', label: 'Comment', fields: { body: { type: 'text', label: 'Body' } } }, + { name: 'sys_activity', label: 'Activity', fields: { subject: { type: 'text', label: 'Subject' } } }, + ]; + const withPlatform = (parent: Record) => ({ objects: [parent, task, event, note, ...platform] }); + + it('never judges the three built-in tab names as children, even on the whole collection (control)', () => { + const parent = lead({ enable: { files: true }, relatedLists: ['sys_attachment', 'sys_approval_request', 'sys_activity', 'rlo_task'] }); + expect(findings(withPlatform(parent), true)).toEqual([]); + expect(findings(stackOf(parent))).toEqual([]); + }); + + it("warns on 'sys_attachment' when the object does not enable files; enabling them is the control", () => { + expect(findings(stackOf(lead({ relatedLists: ['rlo_task', 'sys_attachment'] })))).toEqual([ + ['warning', RELATED_LIST_ATTACHMENTS_OFF, 'objects[0].relatedLists[1]'], + ]); + expect(findings(stackOf(lead({ enable: { files: true }, relatedLists: ['rlo_task', 'sys_attachment'] })))).toEqual([]); + }); + + it("warns on a part of the activity stream and prescribes 'sys_activity', in place of the unknown-name error", () => { + const stack = withPlatform(lead({ relatedLists: ['sys_comment', 'sys_audit_log'] })); + expect(findings(stack, true)).toEqual([ + ['warning', RELATED_LIST_STREAM_PART, 'objects[0].relatedLists[0]'], + ['warning', RELATED_LIST_STREAM_PART, 'objects[0].relatedLists[1]'], + ]); + const [first] = validateRelatedListRefs(stack, { wholeCollection: true }); + expect(first.hint).toContain("'sys_activity'"); + }); + + it('judges an object entry by its list, as a bare entry is', () => { + expect(findings(stackOf(lead({ relatedLists: [{ list: 'rlo_note', label: 'Notes' }] })))).toEqual([ + ['error', RELATED_LIST_REF_UNKNOWN, 'objects[0].relatedLists[0]'], + ]); + expect(findings(stackOf(lead({ relatedLists: [{ list: 'rlo_task', label: 'Tasks' }] })))).toEqual([]); + }); + + it("refuses an entry column that is no field of the child, naming the column; a child field and an injected column are the control", () => { + expect(findings(stackOf(lead({ relatedLists: [{ list: 'rlo_task', columns: ['lead_id', 'nope', 'created_at'] }] })))).toEqual([ + ['error', RELATED_LIST_COLUMN_UNKNOWN, 'objects[0].relatedLists[0].columns[1]'], + ]); + const [finding] = validateRelatedListRefs(stackOf(lead({ relatedLists: [{ list: 'rlo_task', columns: ['nope'] }] }))); + expect(finding.message).toContain("'nope' is not a field of 'rlo_task'"); + }); + + it("walks a dotted column as a relationship path, as the FK's relatedListColumns is walked (#35923 review S1)", () => { + // `lead_id.name` resolves through the task's lookup to the lead; the same spelling on the FK passes too. + expect(findings(stackOf(lead({ relatedLists: [{ list: 'rlo_task', columns: ['lead_id.name'] }] })))).toEqual([]); + expect(findings(stackOf(lead({ relatedLists: [{ list: 'rlo_task', columns: ['lead_id.nope', 'nope_id.name'] }] })))).toEqual([ + ['error', RELATED_LIST_COLUMN_UNKNOWN, 'objects[0].relatedLists[0].columns[0]'], + ['error', RELATED_LIST_COLUMN_UNKNOWN, 'objects[0].relatedLists[0].columns[1]'], + ]); + const [leaf] = validateRelatedListRefs(stackOf(lead({ relatedLists: [{ list: 'rlo_task', columns: ['lead_id.nope'] }] }))); + expect(leaf.message).toContain('"lead_id.nope" is not a field on object "rlo_lead"'); + }); + + it('judges the columns against every child a bare child name names, and leaves a child outside the stack unjudged', () => { + expect(findings(stackOf(lead({ relatedLists: [{ list: 'rlo_event', columns: ['who_id'] }] })))).toEqual([]); + expect(findings(stackOf(lead({ relatedLists: [{ list: 'rlo_elsewhere', columns: ['nope'] }] })))).toEqual([]); + }); +}); diff --git a/packages/lint/src/validate-related-list-refs.ts b/packages/lint/src/validate-related-list-refs.ts index 876c0755bcd..46abcf29992 100644 --- a/packages/lint/src/validate-related-list-refs.ts +++ b/packages/lint/src/validate-related-list-refs.ts @@ -62,10 +62,52 @@ * the sentence is `fieldGroupBodyTableRefusal`'s, the one `defineStack` writes. * `relatedLists` entries are not judged this way: they order body tables and * side cards alike. + * + * ## The built-in tabs and an entry's own columns (#35897, #35899) + * + * A `relatedLists` entry is a bare name or `{ list, label?, columns? }`; the + * name is read through `relatedListEntryName` (`@objectstack/spec/data`). + * + * - The three built-in tab names (`RECORD_PAGE_BUILTIN_TABS`: + * `sys_attachment`, `sys_approval_request`, `sys_activity`) name the record + * page's own tabs, never a child, so they are not judged as one. + * `sys_attachment` on an object that does not enable files draws nothing: + * `related-list-attachments-off` at `warning`, since turning files on + * later makes the entry live, and the entry is not wrong in itself. + * - `sys_comment` and `sys_audit_log` are parts of the activity stream + * (`RELATED_LIST_BUILTIN_PART_OF`), not tabs: `related-list-stream-part` + * at `warning`, prescribing `sys_activity`, in place of the unknown-name + * verdict such a name would otherwise earn where the platform object is + * in view. + * - An object entry's `columns` are fields of the child it names: each is + * judged against every child that entry names whose fields are known (the + * authored fields and the registry-injected columns, as + * `relatedListColumns` is judged in `validate-object-field-refs`), and a + * miss is `related-list-column-unknown` at `error`: the list would draw an + * empty column. A child left unjudged above is left unjudged here. A + * dotted column (`account.industry`) keeps that family's path resolution + * (`resolveFieldPath`, relationship hops from the child), so a column the + * FK's `relatedListColumns` accepts is accepted here too; a path the graph + * cannot answer is left unjudged, as there. */ -import { fieldGroupBodyTableRefusal, type NamedInboundRelationship } from '@objectstack/spec/data'; -import { objectsAsServed, recordsOf } from './object-graph.js'; +import { + fieldGroupBodyTableRefusal, + isRecordPageBuiltinTab, + relatedListEntryName, + RELATED_LIST_BUILTIN_PART_OF, + type NamedInboundRelationship, +} from '@objectstack/spec/data'; +import { + describeFieldPathVerdict, + indexServedObjectGraph, + isUnjudgeable, + objectsAsServed, + recordsOf, + resolveFieldPath, + type ObjectGraph, +} from './object-graph.js'; +import { injectedColumnsFor } from './system-fields.js'; /** A related-list entry that matches no inbound relationship of its object. */ export const RELATED_LIST_REF_UNKNOWN = 'related-list-ref-unknown'; @@ -73,9 +115,23 @@ export const RELATED_LIST_REF_UNKNOWN = 'related-list-ref-unknown'; /** A field group's `relatedList` naming a relationship that is not a body table. */ export const RELATED_LIST_GROUP_NOT_BODY = 'related-list-group-not-body'; +/** A `relatedLists` object entry's `columns` naming no field of the child it names. */ +export const RELATED_LIST_COLUMN_UNKNOWN = 'related-list-column-unknown'; + +/** `relatedLists` names `sys_attachment` on an object that does not enable files. */ +export const RELATED_LIST_ATTACHMENTS_OFF = 'related-list-attachments-off'; + +/** `relatedLists` names a part of the activity stream (`sys_comment`, `sys_audit_log`) as a tab. */ +export const RELATED_LIST_STREAM_PART = 'related-list-stream-part'; + export interface RelatedListRefFinding { - /** Always `error`: the same verdict `defineStack` gives. */ - severity: 'error'; + /** + * `error` for a name or column that places nothing (the verdict `defineStack` + * gives for a name); `warning` for a built-in tab entry that draws nothing + * on this object today (`related-list-attachments-off`, + * `related-list-stream-part`). + */ + severity: 'error' | 'warning'; /** Diagnostic rule id. */ rule: string; /** Human-readable location, e.g. `object "crm_lead" › relatedLists`. */ @@ -132,13 +188,19 @@ export function validateRelatedListRefs(stack: AnyRec, options?: RelatedListRefO // Child object name → its fields by name, as served (see the header). const fieldsByObject = new Map>(); + // Child object name → the registry-injected columns it carries (#35899: an entry's `columns`). + const injectedByObject = new Map>(); const merge = (child: string, fields: AnyRec[]): void => { const byName = fieldsByObject.get(child) ?? new Map(); for (const f of fields) if (typeof f.name === 'string') byName.set(f.name, f); fieldsByObject.set(child, byName); }; + // The graph a dotted column's relationship hops are walked on (built on first need). + let graph: ObjectGraph | undefined; for (const obj of objectsAsServed(stack).objects) { - if (typeof obj.name === 'string') merge(obj.name, recordsOf(obj.fields)); + if (typeof obj.name !== 'string') continue; + merge(obj.name, recordsOf(obj.fields)); + injectedByObject.set(obj.name, injectedColumnsFor(obj)); } // Parent name → its inbound relationships, in child then field order. @@ -193,8 +255,75 @@ export function validateRelatedListRefs(stack: AnyRec, options?: RelatedListRefO }; if (Array.isArray(obj.relatedLists)) { - obj.relatedLists.forEach((entry, i) => - judge(entry, `relatedLists[${i}]`, 'relatedLists', `${objPath}.relatedLists[${i}]`)); + obj.relatedLists.forEach((entry, i) => { + const path = `${objPath}.relatedLists[${i}]`; + const name = relatedListEntryName(entry); + if (name === undefined) return; + if (isRecordPageBuiltinTab(name)) { + const enable = isRec(obj.enable) ? obj.enable : undefined; + if (name === 'sys_attachment' && enable?.files !== true) { + findings.push({ + severity: 'warning', + rule: RELATED_LIST_ATTACHMENTS_OFF, + where: `object "${parentName}" › relatedLists`, + path, + message: + `Object '${parentName}' relatedLists[${i}] 'sys_attachment' places the attachments tab, but ` + + `'${parentName}' does not enable files (enable.files), so the record page draws no attachments tab.`, + hint: "Set enable: { files: true } on the object to show attachments, or remove 'sys_attachment'.", + }); + } + return; + } + const partOf = RELATED_LIST_BUILTIN_PART_OF[name]; + if (partOf !== undefined) { + findings.push({ + severity: 'warning', + rule: RELATED_LIST_STREAM_PART, + where: `object "${parentName}" › relatedLists`, + path, + message: + `Object '${parentName}' relatedLists[${i}] '${name}' is part of the record page's activity stream, ` + + `not a tab of its own, so it places nothing; the stream's tab is '${partOf}'.`, + hint: `Write '${partOf}' to place the activity stream tab (activities, discussion and field changes in one stream).`, + }); + return; + } + judge(name, `relatedLists[${i}]`, 'relatedLists', path); + if (!isRec(entry) || !Array.isArray(entry.columns)) return; + // [#35899] The entry's own columns: fields of every child it names whose fields are known. + const children = [...new Set(namedBy(name).map((r) => r.child))]; + for (const child of children) { + const fields = fieldsByObject.get(child); + if (!fields) continue; + const injected = injectedByObject.get(child) ?? new Set(); + entry.columns.forEach((column, c) => { + if (typeof column !== 'string' || fields.has(column) || injected.has(column)) return; + let message = + `Object '${parentName}' relatedLists[${i}].columns[${c}] '${column}' is not a field of '${child}', ` + + `the child whose rows the list '${name}' shows, so the column would draw empty.`; + if (column.includes('.')) { + // A relationship path from the child, judged as `relatedListColumns` judges one. + graph ??= indexServedObjectGraph(stack); + const verdict = resolveFieldPath(graph, child, column); + if (!verdict || isUnjudgeable(verdict)) return; + const account = describeFieldPathVerdict(verdict, column, `Object '${parentName}' relatedLists[${i}].columns[${c}]`); + if (!account) return; // the path resolves + message = `${account.message} The path is walked from '${child}', the child whose rows the list '${name}' shows, so the column would draw empty.`; + } + findings.push({ + severity: 'error', + rule: RELATED_LIST_COLUMN_UNKNOWN, + where: `object "${parentName}" › relatedLists`, + path: `${path}.columns[${c}]`, + message, + hint: + `Name a field of '${child}' (a related-list column is a field of the child object), ` + + 'or drop the entry\'s columns and let them derive.', + }); + }); + } + }); } if (Array.isArray(obj.fieldGroups)) { obj.fieldGroups.forEach((group, i) => { diff --git a/packages/metadata-core/src/object-schema-fls-references.test.ts b/packages/metadata-core/src/object-schema-fls-references.test.ts index 173716fe76e..79d9a63bcb5 100644 --- a/packages/metadata-core/src/object-schema-fls-references.test.ts +++ b/packages/metadata-core/src/object-schema-fls-references.test.ts @@ -328,6 +328,15 @@ describe('[ADR-0106 D1] references to a denied field — object level', () => { expect(served.fieldGroups).toEqual([{ key: 'lines', label: 'Lines', relatedList: 'secret_score.thing_id' }]); }); + it('[#35899] serves a relatedLists object entry whose columns share the denied field\'s name', () => { + // The columns are fields of the CHILD, governed by the child's own + // projection; filtering them against THIS object's denied set would + // drop an unrelated child column. + const entries = [{ list: 'task', label: 'Open tasks', columns: ['subject', 'secret_score'] }, 'sys_activity']; + const served = mask({ name: 'thing', fields: fieldsWith({}), relatedLists: entries }); + expect(served.relatedLists).toEqual(entries); + }); + it('deletes an UNCLASSIFIED key that mentions the denied field — fail-safe, never a leak', () => { const served = mask({ name: 'thing', fields: fieldsWith(), futureKey: { pick: 'record.secret_score' }, otherKey: 'title' }); expect(served).not.toHaveProperty('futureKey'); diff --git a/packages/metadata-core/src/object-schema-fls-references.ts b/packages/metadata-core/src/object-schema-fls-references.ts index 0d6b682ef32..6cd4b804ab4 100644 --- a/packages/metadata-core/src/object-schema-fls-references.ts +++ b/packages/metadata-core/src/object-schema-fls-references.ts @@ -789,7 +789,10 @@ export const OBJECT_REFERENCE_POSITIONS: Readonly> = { // `object.field` for one of that child's FKs to this object, never a field // of this object, so nothing here is this object's to deny. Read as // unclassified it would over-mask an entry whose child shares a denied - // field's name. + // field's name. [#35899] An object entry's `columns` name fields of that + // CHILD, so they are kept like `lookupColumns`: the child's own projection + // governs them, and the list's rows are read through it. Its `label` is + // author text, and the built-in tab names (`sys_attachment`, …) name objects. relatedLists: keep, // Expressions. titleFormat: expression, 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 553510bf50e..60a29c2346a 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 @@ -77,8 +77,8 @@ export const arMetadataForms: NonNullable = { helpText: "أسماء حقول هذا الكائن، الأهم أولًا — يفوز الإدخال الأول حيث لا يتسع إلا لواحد (ADR-0085). تحدد الأعمدة الافتراضية للقوائم والقوائم المرتبطة والبطاقات ومعاينات السجلات الفرعية وبطاقة التمرير للسجل ومنتقي السجلات. يُرفض عند النشر أي اسم ليس حقلًا من هذا الكائن." }, relatedLists: { - label: "القوائم المرتبطة", - helpText: "ترتيب العمل للقوائم المرتبطة بهذا الكائن في صفحة سجله، الأهم أولًا. كل إدخال اسم كائن فرعي (مثل task)، أو object.field عندما يكون لذلك الكائن الفرعي أكثر من علاقة بهذا الكائن. تأتي القوائم المُدرجة أولًا؛ ويتبعها الباقي بالترتيب المشتق. الاسم الذي لا يطابق أي علاقة تشير إلى هذا الكائن لا يضع شيئًا، لذا يرفضه حفظ الكائن أو التحقق منه." + label: "علامات تبويب صفحة السجل", + helpText: "علامات تبويب صفحة السجل بعد النظرة العامة، بالترتيب. كل إدخال اسم كائن فرعي (مثل task)، أو object.field عندما تكون لذلك الكائن الفرعي أكثر من علاقة بهذا الكائن، أو علامة تبويب مدمجة (sys_attachment وsys_approval_request وsys_activity)، أو إدخال بعنوانه وأعمدته الخاصة يُضبط في إعدادات الكائن في Studio. بمجرد إدراج أي شيء، لا تظهر علامة تبويب لقائمة مرتبطة لا يسمّيها أي إدخال، بما في ذلك قائمة تضيفها حزمة أخرى، إلى أن يسمّيها هذا الكائن؛ ولا تظهر المرفقات إلا عند إدراجها. فارغ: تظهر كل القوائم بالترتيب الافتراضي. يُرفض عند حفظ الكائن أي اسم لا يطابق علاقة تشير إلى هذا الكائن." }, searchableFields: { label: "الحقول القابلة للبحث", 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 61069f296ad..bd6d72ceaa0 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 @@ -77,8 +77,8 @@ export const deMetadataForms: NonNullable = { helpText: "Feldnamen dieses Objekts, das wichtigste zuerst – der erste Eintrag gewinnt, wo nur einer Platz hat (ADR-0085). Steuert die Standardspalten von Listen und Bezugslisten, Karten, Vorschauen untergeordneter Datensätze, die Hover-Karte des Datensatzes und die Datensatzauswahl. Ein Name, der kein Feld dieses Objekts ist, wird bei der Veröffentlichung abgelehnt." }, relatedLists: { - label: "Verknüpfte Listen", - helpText: "Fachliche Reihenfolge der verknüpften Listen dieses Objekts auf seiner Datensatzseite, die wichtigste zuerst. Jeder Eintrag ist ein Name eines untergeordneten Objekts (z. B. task) oder object.field, wenn dieses untergeordnete Objekt mehr als eine Beziehung zu diesem Objekt hat. Aufgeführte Listen kommen zuerst; die übrigen folgen in der abgeleiteten Reihenfolge. Ein Name, der keiner auf dieses Objekt zeigenden Beziehung entspricht, platziert nichts, daher lehnt das Speichern oder Validieren des Objekts ihn ab." + label: "Tabs der Datensatzseite", + helpText: "Die Tabs der Datensatzseite nach der Übersicht, in Reihenfolge. Jeder Eintrag ist der Name eines untergeordneten Objekts (z. B. task), object.field, wenn dieses Objekt mehr als eine Beziehung zu diesem Objekt hat, ein integrierter Tab (sys_attachment, sys_approval_request, sys_activity) oder ein Eintrag mit eigenem Titel und eigenen Spalten, festgelegt in den Objekteinstellungen von Studio. Sobald etwas aufgeführt ist, zeigt eine verknüpfte Liste, die kein Eintrag nennt, keinen Tab, auch eine Liste, die ein anderes Paket hinzufügt, bis dieses Objekt sie nennt; Anhänge erscheinen nur, wenn sie aufgeführt sind. Leer: Alle Listen erscheinen in der Standardreihenfolge. Ein Name, der keiner auf dieses Objekt zeigenden Beziehung entspricht, wird beim Speichern des Objekts abgelehnt." }, searchableFields: { label: "Durchsuchbare Felder", 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 64a90b9f383..f63156a3690 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 @@ -78,7 +78,7 @@ export const enMetadataForms: NonNullable = { }, relatedLists: { label: "Related Lists", - helpText: "Business order of this object's related lists on its record page, most important first. Each entry is a child object name (e.g. task), or object.field when that child has more than one relationship to this object. Listed lists come first; the rest follow in the derived order. A name that matches no relationship pointing at this object places nothing, so saving or validating the object refuses it." + helpText: "The record page tabs after the overview, in order. Each entry is a child object name (e.g. task), object.field when that child has more than one relationship to this object, a built-in tab (sys_attachment, sys_approval_request, sys_activity), or an entry with its own title and columns, set in Studio's object settings. Once anything is listed, a related list no entry names shows no tab, a list another package adds included, until this object names it; attachments show only when listed. Empty: every list shows in the default order. A name that matches no relationship pointing at this object is refused when the object is saved." }, searchableFields: { label: "Searchable Fields", 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 de3be128cbd..e34ef46fd4f 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 @@ -77,8 +77,8 @@ export const esESMetadataForms: NonNullable = helpText: "Nombres de campo de este objeto, del más importante al menos; donde solo cabe uno, gana la primera entrada (ADR-0085). Determinan las columnas predeterminadas de las listas y de las listas relacionadas, las tarjetas, las vistas previas de registros hijos, la tarjeta flotante del registro y el selector de registros. Un nombre que no sea un campo de este objeto se rechaza al publicar." }, relatedLists: { - label: "Orden de listas relacionadas", - helpText: "Orden de negocio de las listas relacionadas de este objeto en su página de registro, de la más importante a la menos. Cada entrada es el nombre de un objeto hijo (p. ej., task), u objeto.campo cuando ese hijo tiene más de una relación con este objeto. Las listas indicadas van primero; el resto sigue en el orden derivado. Un nombre que no coincide con ninguna relación que apunte a este objeto no coloca nada, y se rechaza al guardar o validar el objeto." + label: "Pestañas de la página de registro", + helpText: "Las pestañas de la página de registro después del resumen, en orden. Cada entrada es el nombre de un objeto hijo (p. ej., task), object.field cuando ese hijo tiene más de una relación con este objeto, una pestaña integrada (sys_attachment, sys_approval_request, sys_activity) o una entrada con su propio título y columnas, definida en la configuración del objeto en Studio. En cuanto se enumera algo, una lista relacionada que ninguna entrada nombra no muestra pestaña, incluida una lista que añade otro paquete, hasta que este objeto la nombre; los adjuntos solo se muestran si se enumeran. Vacío: todas las listas se muestran en el orden predeterminado. Un nombre que no coincide con ninguna relación que apunte a este objeto se rechaza al guardar el objeto." }, searchableFields: { label: "Campos buscables", 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 7c82160776f..373b5cf1bd9 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 @@ -77,8 +77,8 @@ export const frMetadataForms: NonNullable = { helpText: "Noms des champs de cet objet, du plus important au moins important — la première entrée l’emporte là où une seule peut figurer (ADR-0085). Détermine les colonnes par défaut des listes et des listes associées, les cartes, les aperçus d’enregistrements enfants, la carte de survol de l’enregistrement et le sélecteur d’enregistrements. Un nom qui n’est pas un champ de cet objet est refusé à la publication." }, relatedLists: { - label: "Listes associées", - helpText: "Ordre métier des listes associées de cet objet sur sa page d’enregistrement, de la plus importante à la moins importante. Chaque entrée est un nom d’objet enfant (par ex. task), ou object.field lorsque cet enfant a plusieurs relations avec cet objet. Les listes indiquées viennent en premier ; les autres suivent dans l’ordre dérivé. Un nom qui ne correspond à aucune relation pointant vers cet objet ne place rien : l’enregistrement ou la validation de l’objet le refuse donc." + label: "Onglets de la page d’enregistrement", + helpText: "Les onglets de la page d’enregistrement après la vue d’ensemble, dans l’ordre. Chaque entrée est un nom d’objet enfant (par ex. task), object.field lorsque cet enfant a plus d’une relation avec cet objet, un onglet intégré (sys_attachment, sys_approval_request, sys_activity) ou une entrée avec son propre titre et ses propres colonnes, définie dans les paramètres de l’objet de Studio. Dès qu’un élément est listé, une liste associée qu’aucune entrée ne nomme n’affiche aucun onglet, y compris une liste ajoutée par un autre paquet, jusqu’à ce que cet objet la nomme ; les pièces jointes ne s’affichent que si elles sont listées. Vide : toutes les listes s’affichent dans l’ordre par défaut. Un nom qui ne correspond à aucune relation pointant vers cet objet est refusé à l’enregistrement de l’objet." }, searchableFields: { label: "Champs de recherche", 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 083b27ff083..ec59b0067fa 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 @@ -77,8 +77,8 @@ export const jaJPMetadataForms: NonNullable = helpText: "このオブジェクトの項目名を重要な順に並べます。1 つしか表示できない場所では先頭の項目が使われます(ADR-0085)。既定の一覧列と関連リストの列、カード、子レコードのプレビュー、レコードのホバーカード、レコードの選択画面を決めます。このオブジェクトの項目でない名前は公開時に拒否されます。" }, relatedLists: { - label: "関連リストの順序", - helpText: "レコードページに表示するこのオブジェクトの関連リストの業務上の順序を、重要な順に並べます。各項目は子オブジェクト名(例:task)で、その子オブジェクトがこのオブジェクトと複数の関係を持つ場合は object.field と書きます。指定したリストが先に並び、残りは派生順で続きます。このオブジェクトを指す関係に一致しない名前は何も配置せず、オブジェクトの保存時や検証時に拒否されます。" + label: "レコードページのタブ", + helpText: "概要の後に表示するレコードページのタブを順番に並べます。各項目は子オブジェクト名(例: task)、その子オブジェクトがこのオブジェクトと複数の関係を持つ場合は object.field、組み込みタブ(sys_attachment、sys_approval_request、sys_activity)、または Studio のオブジェクト設定で独自のタイトルと列を設定した項目です。何か一つでも列挙すると、どの項目にも挙がっていない関連リストにはタブが表示されません(他のパッケージが追加したリストも同様)。このオブジェクトがそれを列挙するまで表示されません。添付ファイルは列挙した場合にのみ表示されます。空の場合は、すべてのリストが既定の順序で表示されます。このオブジェクトを指す関係に一致しない名前は、オブジェクトの保存時に拒否されます。" }, searchableFields: { label: "検索対象項目", 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 84109b545a9..9306d8d0758 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 @@ -77,8 +77,8 @@ export const koMetadataForms: NonNullable = { helpText: "이 객체의 필드 이름을 중요한 순서대로 나열합니다. 하나만 들어갈 자리에서는 첫 항목이 우선합니다(ADR-0085). 기본 목록 열과 관련 목록 열, 카드, 하위 레코드 미리보기, 레코드 호버 카드, 레코드 선택기를 결정합니다. 이 객체의 필드가 아닌 이름은 게시할 때 거부됩니다." }, relatedLists: { - label: "관련 목록", - helpText: "레코드 페이지에서 이 객체의 관련 목록이 표시되는 업무 순서로, 중요한 것부터 나열합니다. 각 항목은 하위 객체 이름(예: task)이며, 그 하위 객체가 이 객체와 관계를 둘 이상 가지면 object.field입니다. 나열된 목록이 먼저 오고 나머지는 도출된 순서로 이어집니다. 이 객체를 가리키는 관계와 일치하지 않는 이름은 아무것도 배치하지 않으므로, 객체를 저장하거나 검증할 때 거부됩니다." + label: "레코드 페이지 탭", + helpText: "개요 뒤에 표시되는 레코드 페이지 탭을 순서대로 나열합니다. 각 항목은 하위 객체 이름(예: task), 그 하위 객체가 이 객체와 관계가 둘 이상이면 object.field, 기본 제공 탭(sys_attachment, sys_approval_request, sys_activity), 또는 Studio의 객체 설정에서 자체 제목과 열을 지정한 항목입니다. 하나라도 나열하면 어떤 항목에도 없는 관련 목록은 탭이 표시되지 않으며(다른 패키지가 추가한 목록 포함), 이 객체가 그것을 나열할 때까지 표시되지 않습니다. 첨부 파일은 나열된 경우에만 표시됩니다. 비어 있으면 모든 목록이 기본 순서로 표시됩니다. 이 객체를 가리키는 관계와 일치하지 않는 이름은 객체를 저장할 때 거부됩니다." }, searchableFields: { label: "검색 가능 필드", 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 3f5a24bfe94..56ac501dcbc 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 @@ -77,8 +77,8 @@ export const ptBRMetadataForms: NonNullable = helpText: "Nomes de campos deste objeto, os mais importantes primeiro — a primeira entrada vence onde só cabe uma (ADR-0085). Define as colunas padrão das listas e das listas relacionadas, os cartões, as pré-visualizações de registros filhos, o cartão flutuante do registro e o seletor de registros. Um nome que não seja um campo deste objeto é recusado na publicação." }, relatedLists: { - label: "Listas relacionadas", - helpText: "Ordem de negócio das listas relacionadas deste objeto na página do registro, as mais importantes primeiro. Cada entrada é o nome de um objeto filho (por exemplo task), ou objeto.campo quando esse filho tem mais de um relacionamento com este objeto. As listas indicadas vêm primeiro; as demais seguem na ordem derivada. Um nome que não corresponde a nenhum relacionamento que aponte para este objeto não posiciona nada, por isso salvar ou validar o objeto o recusa." + label: "Abas da página do registro", + helpText: "As abas da página do registro depois da visão geral, em ordem. Cada entrada é o nome de um objeto filho (por exemplo task), object.field quando esse filho tem mais de uma relação com este objeto, uma aba integrada (sys_attachment, sys_approval_request, sys_activity) ou uma entrada com título e colunas próprios, definida nas configurações do objeto no Studio. Assim que algo é listado, uma lista relacionada que nenhuma entrada nomeia não mostra aba, inclusive uma lista que outro pacote adiciona, até que este objeto a nomeie; os anexos só aparecem quando listados. Vazio: todas as listas aparecem na ordem padrão. Um nome que não corresponde a nenhuma relação que aponte para este objeto é recusado ao salvar o objeto." }, searchableFields: { label: "Campos pesquisáveis", 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 91d53f113c7..f7e2db9fa17 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 @@ -77,8 +77,8 @@ export const ruMetadataForms: NonNullable = { helpText: "Имена полей этого объекта, самые важные первыми — там, где помещается только одно, побеждает первое (ADR-0085). Определяют столбцы по умолчанию для списков и связанных списков, карточки, предпросмотр дочерних записей, всплывающую карточку записи и выбор записи. Имя, не являющееся полем этого объекта, отклоняется при публикации." }, relatedLists: { - label: "Связанные списки", - helpText: "Бизнес-порядок связанных списков этого объекта на странице его записи, самые важные первыми. Каждая запись — имя дочернего объекта (например, task) или object.field, если у дочернего объекта несколько связей с этим. Перечисленные списки идут первыми; остальные следуют в выведенном порядке. Имя, не совпадающее ни с одной связью, указывающей на этот объект, ничего не размещает, поэтому при сохранении или проверке объекта оно отклоняется." + label: "Вкладки страницы записи", + helpText: "Вкладки страницы записи после обзора, по порядку. Каждый элемент — имя дочернего объекта (например, task), object.field, если у этого дочернего объекта больше одной связи с этим объектом, встроенная вкладка (sys_attachment, sys_approval_request, sys_activity) или элемент с собственным заголовком и столбцами, заданными в настройках объекта в Studio. Как только что-либо перечислено, связанный список, который не назван ни одним элементом, не показывает вкладку — в том числе список, добавленный другим пакетом, — пока этот объект его не назовёт; вложения показываются, только если они перечислены. Пусто: все списки показываются в порядке по умолчанию. Имя, не соответствующее ни одной связи, указывающей на этот объект, отклоняется при сохранении объекта." }, searchableFields: { label: "Поля поиска", 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 2dadd950016..f1ce4b6dbe8 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 @@ -77,8 +77,8 @@ export const zhCNMetadataForms: NonNullable = helpText: "本对象的字段名,按重要性从高到低排列——只能放下一个时取第一项(ADR-0085)。决定默认列表列和相关列表列、卡片、子记录预览、记录悬停卡片和记录选择器。不是本对象字段的名称会在发布时被拒绝。" }, relatedLists: { - label: "相关列表顺序", - helpText: "本对象记录页上相关列表的业务顺序,按重要性从高到低排列。每一项是子对象名称(例如 task),当该子对象与本对象有多个关系时写 object.field。列出的列表排在前面,其余按派生顺序排在后面。不对应任何指向本对象的关系的名称不起作用,保存或校验对象时会被拒绝。" + label: "记录页页签", + helpText: "记录页在概览之后显示的页签,按顺序排列。每一项是子对象名称(例如 task);当该子对象与本对象有多个关系时写 object.field;也可以是内置页签(sys_attachment、sys_approval_request、sys_activity),或带自己标题和列的一项(在 Studio 的对象设置里设置)。一旦列出任何一项,没有列出的相关列表就不显示页签(其他包添加的列表也一样),直到本对象列出它;附件只有列出时才显示。为空时,所有列表按默认顺序显示。不对应任何指向本对象的关系的名称,在保存对象时会被拒绝。" }, searchableFields: { label: "可搜索字段", 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 295c6f73d5c..12f38b43be9 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 @@ -77,8 +77,8 @@ export const zhHantMetadataForms: NonNullable helpText: "本物件的欄位名,依重要性從高到低排列——只能放下一個時取第一項(ADR-0085)。決定預設清單欄和相關清單欄、卡片、子記錄預覽、記錄懸停卡片和記錄選擇器。不是本物件欄位的名稱會在發布時被拒絕。" }, relatedLists: { - label: "相關清單順序", - helpText: "本物件記錄頁上相關清單的業務順序,依重要性從高到低排列。每一項是子物件名稱(例如 task),當該子物件與本物件有多個關係時寫 object.field。列出的清單排在前面,其餘依派生順序排在後面。不對應任何指向本物件的關係的名稱不起作用,儲存或驗證物件時會被拒絕。" + label: "記錄頁頁籤", + helpText: "記錄頁在概覽之後顯示的頁籤,依順序排列。每一項是子物件名稱(例如 task);當該子物件與本物件有多個關係時寫 object.field;也可以是內建頁籤(sys_attachment、sys_approval_request、sys_activity),或帶自己標題和欄位的一項(在 Studio 的物件設定裡設定)。一旦列出任何一項,未列出的相關清單就不顯示頁籤(其他套件新增的清單也一樣),直到本物件列出它;附件只有列出時才顯示。為空時,所有清單依預設順序顯示。不對應任何指向本物件之關係的名稱,在儲存物件時會被拒絕。" }, searchableFields: { label: "可搜尋欄位", diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 7c6a5737267..27b78134a76 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -685,6 +685,7 @@ "READABLE_IDS_REFUSAL (const)", "READ_ONLY_BELONGS_ON_DATASOURCE (const)", "RECORD_CONTEXT_TOKENS (const)", + "RECORD_PAGE_BUILTIN_TABS (const)", "RECORD_RESTORED_EVENT (const)", "RECORD_SURFACE_PAGE_THRESHOLD (const)", "RECYCLE_BIN_DEFAULT_RETENTION_DAYS (const)", @@ -695,6 +696,7 @@ "RECYCLE_BIN_RESTORE_REFUSAL_STATUS (const)", "RECYCLE_BIN_RETENTION_DAYS_ENV (const)", "REFERENCE_VALUE_TYPES (const)", + "RELATED_LIST_BUILTIN_PART_OF (const)", "RETIRED_DRIVER_ID_GUIDANCE (const)", "RETIRED_FILTER_OPERATORS (const)", "RETIRED_SEED_MODE_VALUES (const)", @@ -718,6 +720,7 @@ "RecordFlow (type)", "RecordFlowContainer (type)", "RecordFlowSurface (interface)", + "RecordPageBuiltinTab (type)", "RecordSurface (type)", "RecordSurfaceOptions (interface)", "RecordSurfaceViewport (type)", @@ -746,6 +749,12 @@ "ReferenceResolutionErrorSchema (const)", "ReferenceResolutionParsed (type)", "ReferenceResolutionSchema (const)", + "RelatedListEntry (type)", + "RelatedListEntryInput (type)", + "RelatedListEntryObject (interface)", + "RelatedListEntryObjectSchema (const)", + "RelatedListEntryParsed (type)", + "RelatedListEntrySchema (const)", "RelatedListRelationshipFields (interface)", "RenderAutonumberInput (interface)", "RenderedAutonumber (interface)", @@ -1097,6 +1106,7 @@ "isReadableIds (function)", "isRecordContextToken (function)", "isRecordCurrencyCodeField (function)", + "isRecordPageBuiltinTab (function)", "isRefusedTextComparand (function)", "isRuntimeDefaultToken (function)", "isSeedFilePath (function)", @@ -1164,6 +1174,7 @@ "refusedCredentialPathsOfSchema (function)", "refusedInlineCredentialKey (function)", "refusedPassthroughSecretPaths (function)", + "relatedListEntryName (function)", "renderAutonumber (function)", "resolveAutonumberFormat (function)", "resolveBulkPerRowHookBudget (function)", diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index f8b14bebc70..7d98d9e3d75 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -902,6 +902,9 @@ "data/ReferenceResolutionError:sourceObject", "data/ReferenceResolutionError:targetField", "data/ReferenceResolutionError:targetObject", + "data/RelatedListEntryObject:columns", + "data/RelatedListEntryObject:label", + "data/RelatedListEntryObject:list", "data/ReplicationConfig:enabled", "data/ReplicationConfig:readPreference", "data/ReplicationConfig:replicaSetName", diff --git a/packages/spec/declaration-map/data.json b/packages/spec/declaration-map/data.json index 4e958aa65e9..9c4f0511641 100644 --- a/packages/spec/declaration-map/data.json +++ b/packages/spec/declaration-map/data.json @@ -285,6 +285,10 @@ "ReferenceResolutionError": "data/ReferenceResolutionError", "ReferenceResolutionErrorSchema": "data/ReferenceResolutionError", "ReferenceResolutionSchema": "data/ReferenceResolution", + "RelatedListEntry": "data/RelatedListEntry", + "RelatedListEntryObject": "data/RelatedListEntryObject", + "RelatedListEntryObjectSchema": "data/RelatedListEntryObject", + "RelatedListEntrySchema": "data/RelatedListEntry", "ReplicationConfig": "data/ReplicationConfig", "ReplicationConfigSchema": "data/ReplicationConfig", "RowCrudActionOverride": "data/RowCrudActionOverride", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index f83f4e79ce2..14d47f34402 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -674,6 +674,7 @@ "READABLE_IDS_REFUSAL": "src/data/readable-ids-conformance.ts#READABLE_IDS_REFUSAL (const)", "READ_ONLY_BELONGS_ON_DATASOURCE": "src/data/driver/common.zod.ts#READ_ONLY_BELONGS_ON_DATASOURCE (const)", "RECORD_CONTEXT_TOKENS": "src/data/context-tokens.zod.ts#RECORD_CONTEXT_TOKENS (const)", + "RECORD_PAGE_BUILTIN_TABS": "src/data/related-list-entry.ts#RECORD_PAGE_BUILTIN_TABS (const)", "RECORD_RESTORED_EVENT": "src/data/recycle-bin.zod.ts#RECORD_RESTORED_EVENT (const)", "RECORD_SURFACE_PAGE_THRESHOLD": "src/data/record-surface.ts#RECORD_SURFACE_PAGE_THRESHOLD (const)", "RECYCLE_BIN_DEFAULT_RETENTION_DAYS": "src/data/recycle-bin.zod.ts#RECYCLE_BIN_DEFAULT_RETENTION_DAYS (const)", @@ -684,6 +685,7 @@ "RECYCLE_BIN_RESTORE_REFUSAL_STATUS": "src/data/recycle-bin.zod.ts#RECYCLE_BIN_RESTORE_REFUSAL_STATUS (const)", "RECYCLE_BIN_RETENTION_DAYS_ENV": "src/data/recycle-bin.zod.ts#RECYCLE_BIN_RETENTION_DAYS_ENV (const)", "REFERENCE_VALUE_TYPES": "src/data/field-value.zod.ts#REFERENCE_VALUE_TYPES (const)", + "RELATED_LIST_BUILTIN_PART_OF": "src/data/related-list-entry.ts#RELATED_LIST_BUILTIN_PART_OF (const)", "RETIRED_DRIVER_ID_GUIDANCE": "src/data/driver/config-registry.zod.ts#RETIRED_DRIVER_ID_GUIDANCE (const)", "RETIRED_FILTER_OPERATORS": "src/data/filter.zod.ts#RETIRED_FILTER_OPERATORS (const)", "RETIRED_SEED_MODE_VALUES": "src/data/seed.zod.ts#RETIRED_SEED_MODE_VALUES (const)", @@ -706,6 +708,7 @@ "RecordFlow": "src/data/record-surface.ts#RecordFlow (type)", "RecordFlowContainer": "src/data/record-surface.ts#RecordFlowContainer (type)", "RecordFlowSurface": "src/data/record-surface.ts#RecordFlowSurface (interface)", + "RecordPageBuiltinTab": "src/data/related-list-entry.ts#RecordPageBuiltinTab (type)", "RecordSurface": "src/data/record-surface.ts#RecordSurface (type)", "RecordSurfaceOptions": "src/data/record-surface.ts#RecordSurfaceOptions (interface)", "RecordSurfaceViewport": "src/data/record-surface.ts#RecordSurfaceViewport (type)", @@ -734,6 +737,12 @@ "ReferenceResolutionErrorSchema": "src/data/seed-loader.zod.ts#ReferenceResolutionErrorSchema (const)", "ReferenceResolutionParsed": "src/data/seed-loader.zod.ts#ReferenceResolutionParsed (type)", "ReferenceResolutionSchema": "src/data/seed-loader.zod.ts#ReferenceResolutionSchema (const)", + "RelatedListEntry": "src/data/object.zod.ts#RelatedListEntry (type)", + "RelatedListEntryInput": "src/data/related-list-entry.ts#RelatedListEntryInput (type)", + "RelatedListEntryObject": "src/data/related-list-entry.ts#RelatedListEntryObject (interface)", + "RelatedListEntryObjectSchema": "src/data/object.zod.ts#RelatedListEntryObjectSchema (const)", + "RelatedListEntryParsed": "src/data/object.zod.ts#RelatedListEntryParsed (type)", + "RelatedListEntrySchema": "src/data/object.zod.ts#RelatedListEntrySchema (const)", "RelatedListRelationshipFields": "src/data/related-list-body-table.ts#RelatedListRelationshipFields (interface)", "RenderAutonumberInput": "src/data/autonumber-format.ts#RenderAutonumberInput (interface)", "RenderedAutonumber": "src/data/autonumber-format.ts#RenderedAutonumber (interface)", @@ -1082,6 +1091,7 @@ "isReadableIds": "src/data/readable-ids.ts#isReadableIds (function)", "isRecordContextToken": "src/data/context-tokens.zod.ts#isRecordContextToken (function)", "isRecordCurrencyCodeField": "src/data/record-currency-path.ts#isRecordCurrencyCodeField (function)", + "isRecordPageBuiltinTab": "src/data/related-list-entry.ts#isRecordPageBuiltinTab (function)", "isRefusedTextComparand": "src/data/filter-text-comparand.ts#isRefusedTextComparand (function)", "isRuntimeDefaultToken": "src/data/default-value-tokens.ts#isRuntimeDefaultToken (function)", "isSeedFilePath": "src/data/seed-file.zod.ts#isSeedFilePath (function)", @@ -1149,6 +1159,7 @@ "refusedCredentialPathsOfSchema": "src/data/datasource-credential-redaction.ts#refusedCredentialPathsOfSchema (function)", "refusedInlineCredentialKey": "src/data/driver/common.zod.ts#refusedInlineCredentialKey (function)", "refusedPassthroughSecretPaths": "src/data/datasource-credential-redaction.ts#refusedPassthroughSecretPaths (function)", + "relatedListEntryName": "src/data/related-list-entry.ts#relatedListEntryName (function)", "renderAutonumber": "src/data/autonumber-format.ts#renderAutonumber (function)", "resolveAutonumberFormat": "src/data/autonumber-format.ts#resolveAutonumberFormat (function)", "resolveBulkPerRowHookBudget": "src/data/bulk-write-hook-conformance.ts#resolveBulkPerRowHookBudget (function)", diff --git a/packages/spec/json-schema.manifest/data.json b/packages/spec/json-schema.manifest/data.json index b14c260e220..6076e84d9df 100644 --- a/packages/spec/json-schema.manifest/data.json +++ b/packages/spec/json-schema.manifest/data.json @@ -152,6 +152,8 @@ "data/ReferenceNameOnlyValue", "data/ReferenceResolution", "data/ReferenceResolutionError", + "data/RelatedListEntry", + "data/RelatedListEntryObject", "data/ReplicationConfig", "data/RowCrudActionOverride", "data/SQLDialect", diff --git a/packages/spec/liveness/object.json b/packages/spec/liveness/object.json index f51bbc90222..c56a315b458 100644 --- a/packages/spec/liveness/object.json +++ b/packages/spec/liveness/object.json @@ -58,8 +58,31 @@ "status": "live", "verifiedAt": "2026-10-28", "evidenceScope": "in-repo", - "evidence": "ui/packages/app-shell/src/utils/deriveRelatedLists.ts#resolveRelatedListOrder (the one resolution: the parent's declared entries first, in order — a child object takes all of its lists, `object.field` one FK — then every unlisted list in the derived owned → lookup order); ui/packages/app-shell/src/utils/deriveRelatedLists.ts#deriveRelatedLists (hands `objectDef.relatedLists` to it); packages/spec/src/stack.zod.ts#collectRelatedListNameErrors (the AUTHORING judgement: an entry that matches no inbound lookup / master_detail field is refused at defineStack, naming the entry and the relationships that exist); packages/lint/src/validate-related-list-refs.ts#validateRelatedListRefs (the same judgement at the runtime object publish door, `related-list-ref-unknown` at error, against the children the live registry and stored rows hold)", - "note": "#27069, maintainer ruling A (an ordered list on the parent object). The record page reads it through deriveRelatedLists, whose output RecordDetailView renders in order (the tabbed page's own tabs and its Related tab keep this order within each). `relatedList: false` on the FK still hides a listed relationship, and `relatedList: 'primary'` places a list rather than ordering it. The cross-object strict-name check runs where the children's fields are known: `defineStack` (so `os validate` / `os build`), and the object publish door, whose snapshot carries the registry's objects and the stored rows. `fieldGroups[].relatedList` has its own row under the drilled `fieldGroups` (live since the record page v3 body layout, #27055, draws it; it names body tables only, #27478)." + "evidence": "ui/packages/app-shell/src/utils/deriveRelatedLists.ts#resolveRelatedListOrder (the one resolution: the parent's declared entries first, in order — a child object takes all of its lists, `object.field` one FK — then every unlisted list in the derived owned → lookup order); ui/packages/app-shell/src/utils/deriveRelatedLists.ts#deriveRelatedLists (hands `objectDef.relatedLists` to it); packages/spec/src/stack.zod.ts#collectRelatedListNameErrors (the AUTHORING judgement: an entry that matches no inbound lookup / master_detail field is refused at defineStack, naming the entry and the relationships that exist); packages/lint/src/validate-related-list-refs.ts#validateRelatedListRefs (the same judgement at the runtime object publish door, `related-list-ref-unknown` at error, against the children the live registry and stored rows hold); ui/packages/app-shell/src/utils/deriveRelatedLists.ts#deriveRelatedLists (#35897: a declared non-empty list derives only the side lists it names, body tables kept; #35899: an object entry's label / columns win over the FK's relatedListTitle / relatedListColumns); ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts#arrangeDeclaredTabs (#35897: the tabs sit at their entries, the built-ins sys_attachment / sys_approval_request / sys_activity by name); packages/lint/src/validate-related-list-refs.ts#validateRelatedListRefs (#35899: related-list-column-unknown at error; related-list-attachments-off and related-list-stream-part at warning)", + "note": "#27069, maintainer ruling A (an ordered list on the parent object). The record page reads it through deriveRelatedLists, whose output RecordDetailView renders in order (the tabbed page's own tabs and its Related tab keep this order within each). `relatedList: false` on the FK still hides a listed relationship, and `relatedList: 'primary'` places a list rather than ordering it. The cross-object strict-name check runs where the children's fields are known: `defineStack` (so `os validate` / `os build`), and the object publish door, whose snapshot carries the registry's objects and the stored rows. `fieldGroups[].relatedList` has its own row under the drilled `fieldGroups` (live since the record page v3 body layout, #27055, draws it; it names body tables only, #27478). #35897 / #35899 (epic #35896, maintainer's 「三个内置项,是不是可以直接用对应的对象名」): a DECLARED non-empty relatedLists is the record page's tab list — unlisted side lists show no tab; the built-in tabs are entries by object name (attachments only when listed and enable.files; approvals unlisted follow the listed tabs; the stream unlisted closes the strip); an entry may be { list, label, columns }, whose columns are judged against the child's fields. D3 entry `related-lists-declared-is-tab-list`.", + "children": { + "list": { + "status": "live", + "verifiedAt": "2026-11-20", + "evidenceScope": "in-repo", + "evidence": "packages/spec/src/data/related-list-entry.ts#relatedListEntryName (the one reading of an entry's name, bare or object form); ui/packages/app-shell/src/utils/deriveRelatedLists.ts#deriveRelatedLists (places and shows the lists the entry names); packages/spec/src/stack.zod.ts#collectRelatedListNameErrors (judged as a bare entry is)", + "note": "#35899. The relationship an object entry names, spelled as a bare entry; a built-in tab name is refused here at parse (written bare only)." + }, + "label": { + "status": "live", + "verifiedAt": "2026-11-20", + "evidenceScope": "in-repo", + "evidence": "ui/packages/app-shell/src/utils/deriveRelatedLists.ts#deriveRelatedLists (an object entry's label becomes the list's title, over the FK's relatedListTitle); ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts#buildDefaultTabs (the tab label and the table title read that title)", + "note": "#35899. The list's title on the record page: its tab and its table heading." + }, + "columns": { + "status": "live", + "verifiedAt": "2026-11-20", + "evidenceScope": "in-repo", + "evidence": "ui/packages/app-shell/src/utils/deriveRelatedLists.ts#deriveRelatedLists (an object entry's columns become the list's columns, over the FK's relatedListColumns); packages/lint/src/validate-related-list-refs.ts#validateRelatedListRefs (related-list-column-unknown at error, against the child's fields)", + "note": "#35899. Child field names; one set for every place the list is drawn (its tab, and the body table a field group places)." + } + } }, "stageField": { "status": "live", diff --git a/packages/spec/liveness/state-counts/object.md b/packages/spec/liveness/state-counts/object.md index 424d308d9f7..870164c5c01 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` | 87 | 0 | 0 | 1 | 1 | 89 | +| `object` | 89 | 0 | 0 | 1 | 1 | 91 | diff --git a/packages/spec/src/data/index.ts b/packages/spec/src/data/index.ts index 26ced7c8132..249fefd9ec6 100644 --- a/packages/spec/src/data/index.ts +++ b/packages/spec/src/data/index.ts @@ -482,6 +482,7 @@ export * from './record-currency-path'; // is not. Read by `defineStack`, `@objectstack/lint` and the objectui record page // and Studio, so the four cannot drift. export * from './related-list-body-table'; +export * from './related-list-entry'; // Feed & Activity Protocol — retains only the UI activity-timeline config enums // (FeedItemType / FeedFilterMode); the feed backend contracts were retired (ADR-0052 §5). diff --git a/packages/spec/src/data/object.form.ts b/packages/spec/src/data/object.form.ts index b177b0807ee..997cdd5e833 100644 --- a/packages/spec/src/data/object.form.ts +++ b/packages/spec/src/data/object.form.ts @@ -71,12 +71,16 @@ export const objectForm = defineForm({ // the publish door refuses it (`object-field-ref-unknown`, // `searchable-field-unknown`, both at `error`), and so does `os validate`. { field: 'highlightFields', widget: 'string-tags', colSpan: 2, helpText: 'Field names of this object, most important first — the first entry wins where only one fits (ADR-0085). Drives the default list and related-list columns, cards, child-record previews, the record hover card and the record picker. A name that is not a field of this object is refused at publish.' }, - // #27069 — the business order of the record page's related lists: a - // list of inbound relationship names (child object, or `object.field`) - // on the `highlightFields` row's face. A dangling name is refused at - // the publish door (`related-list-ref-unknown`, `error`, judged against - // the registry's children) and by `os validate` / `os build`. - { field: 'relatedLists', widget: 'string-tags', colSpan: 2, helpText: 'Business order of this object\'s related lists on its record page, most important first. Each entry is a child object name (e.g. task), or object.field when that child has more than one relationship to this object. Listed lists come first; the rest follow in the derived order. A name that matches no relationship pointing at this object places nothing, so saving or validating the object refuses it.' }, + // #27069 / #35897 / #35899 — the record page's tab list: inbound + // relationship names (child object, or `object.field`), the three + // built-in tabs by object name, or an entry's object form + // `{ list, label?, columns? }`. Its own widget, not `string-tags`: that + // chip input casts the value to `string[]`, and an object entry (which + // Studio's Record page tabs editor writes once a title or columns are + // set) cannot render as a chip there (#35923 review M1). A dangling name + // is refused at the publish door (`related-list-ref-unknown`, `error`, + // judged against the registry's children) and by `os validate` / `os build`. + { field: 'relatedLists', widget: 'related-list-entries', colSpan: 2, helpText: 'The record page tabs after the overview, in order. Each entry is a child object name (e.g. task), object.field when that child has more than one relationship to this object, a built-in tab (sys_attachment, sys_approval_request, sys_activity), or an entry with its own title and columns, set in Studio\'s object settings. Once anything is listed, a related list no entry names shows no tab, a list another package adds included, until this object names it; attachments show only when listed. Empty: every list shows in the default order. A name that matches no relationship pointing at this object is refused when the object is saved.' }, { 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.zod.ts b/packages/spec/src/data/object.zod.ts index 1808138c4cd..93200a9e3a9 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -27,6 +27,7 @@ import { suggestRename } from '../shared/rename-guess'; import { refuseRecordProtoKey } from '../shared/record-proto-key-guard'; import { bannedKeys } from '../shared/refinement-projection'; import { FIELD_GROUP_KEY_PATTERN } from './field-group-layout'; +import { RECORD_PAGE_BUILTIN_TABS } from './related-list-entry'; // [#23809] The stage-field option-kind rule, in its own module so the AI // blueprint object (`ai/solution-blueprint.zod.ts`) runs this same refinement. import { refuseStageFieldWithoutKinds } from './stage-field-kinds'; @@ -1269,6 +1270,93 @@ export const LifecycleSchema = lazySchema(() => strictObject({ */ const RELATED_LIST_ENTRY_PATTERN = /^[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)?$/; +/** + * The object form's `list`: any entry name but a built-in tab's + * (`RECORD_PAGE_BUILTIN_TABS`), which is written only bare. A pattern rather + * than a refinement, so the published JSON Schema refuses it too. + */ +const RELATED_LIST_OBJECT_ENTRY_NAME_PATTERN = new RegExp(`^(?!(?:${RECORD_PAGE_BUILTIN_TABS.join('|')})$)`); + +const RELATED_LIST_ENTRY_NAME_MESSAGE = + 'A relatedLists entry is a child object name (e.g. "task") or object.field (e.g. "event.related_to"), in snake_case'; + +/** + * [#35899] The OBJECT form of one `ObjectSchema.relatedLists` entry: the + * relationship it names (`list`, spelled as the bare entry is), and that + * list's own title and columns, declared on the PARENT so an author arranging + * the account page need not edit the task object. + * + * - `label` — the tab's title and the table's heading. Wins over the child + * FK's `relatedListTitle`, which wins over the child object's plural label. + * - `columns` — child FIELD NAMES, as the FK's `relatedListColumns` spells + * them. Win over that key, which wins over the child object's derived + * columns (`highlightFields`, then the field walk). One set of columns + * serves every place this list is drawn: its tab, and the body table a + * field group places (a group names no columns of its own). A name that is + * no field of the child is refused where the child's fields are known + * (`@objectstack/lint` `validate-related-list-refs`, the CLI and the runtime + * metadata write door). + * + * The record page's three built-in tabs (`sys_attachment`, + * `sys_approval_request`, `sys_activity`, `RECORD_PAGE_BUILTIN_TABS`) are + * written only as their bare names: an object entry naming one is refused, + * since their renderers read no title or columns from here. + * + * No filter, width, totals or row order here: the FK's `relatedListFilter` + * keeps the list's scope, and rows keep the child's default list-view sort. + */ +export const RelatedListEntryObjectSchema = lazySchema(() => strictObject({ + surface: 'this relatedLists entry', + history: + 'An unknown key here would be dropped silently: the tab would still draw, with the title and columns ' + + 'the child declares, so the author would believe the setting they wrote had been applied.', + aliases: { + name: 'list', + object: 'list', + objectName: 'list', + relationship: 'list', + title: 'label', + fields: 'columns', + }, + guidance: { + filter: + '`filter` is not a relatedLists entry key: a related list\'s scope is the child FK\'s `relatedListFilter`.', + sort: + '`sort` is not a relatedLists entry key: a related list orders its rows the way the child object\'s default list view sorts.', + }, +}, { + list: z.string().regex(RELATED_LIST_ENTRY_PATTERN, { message: RELATED_LIST_ENTRY_NAME_MESSAGE }) + .regex(RELATED_LIST_OBJECT_ENTRY_NAME_PATTERN, { + message: + `${RECORD_PAGE_BUILTIN_TABS.map((n) => `'${n}'`).join(', ')} are built-in record-page tabs, drawn by their own ` + + 'renderers: write one as its bare name (e.g. \'sys_attachment\'), never as { list }. A built-in tab takes no label or columns.', + }) + .describe('The relationship this entry names: a child object name (e.g. "quote_line"), or object.field when that child has more than one relationship to this object.'), + label: z.string().min(1).optional() + .describe("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: z.array(z.string({ + error: (issue) => issue.code === 'invalid_type' + ? "A relatedLists entry's columns are child FIELD-NAME strings (e.g. ['product', 'amount']): labels, cell types and formatting come from the child object's field definitions." + : undefined, + }).min(1)).min(1).optional() + .describe("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."), +})); + +/** + * [#27069 · #35897 · #35899] One `ObjectSchema.relatedLists` entry: the bare + * name (`'task'`, `'event.related_to'`, or a built-in tab such as + * `'sys_attachment'`), or {@link RelatedListEntryObjectSchema}'s object form + * carrying the list's own title and columns. The two mix freely. + */ +export const RelatedListEntrySchema = lazySchema(() => z.union([ + z.string().regex(RELATED_LIST_ENTRY_PATTERN, { message: RELATED_LIST_ENTRY_NAME_MESSAGE }), + RelatedListEntryObjectSchema, +])); +/** One `relatedLists` entry as an author writes it. */ +export type RelatedListEntry = z.input; +/** One `relatedLists` entry after parse. */ +export type RelatedListEntryParsed = z.infer; + /** * Object Field Group Schema — MVP (data-layer protocol) * @@ -4625,14 +4713,49 @@ const ObjectSchemaBase = strictObject( // (framework#2536): authoring it is rejected by `create()` like any unknown // key. All first-party consumers read `highlightFields` since objectui#2168. /** - * [#27069] The business order of this object's RELATED LISTS on its record - * page — what `highlightFields` is to fields, for child relationships. Each - * entry names one inbound relationship: the child object (`'task'`), or - * `object.field` when that child points here through more than one FK - * (`'event.related_to'`); a bare child name orders all of that child's lists - * together. Listed relationships come first, in this order; every unlisted - * one follows in the derived order (owned `master_detail` children, then - * `lookup` children, each in declaration order). + * [#27069 · #35897 · #35899] This object's record-page TABS beside its + * overview: which related lists show, in what order, with what title and + * columns, and where the three built-in tabs sit — what `highlightFields` + * is to fields, for child relationships. + * + * Absent (or empty): every inbound relationship shows, in the derived order + * (owned `master_detail` children, then `lookup` children, each in + * declaration order), then the attachments, approvals and activity-stream + * tabs — exactly as before this key existed. + * + * Declared: ONLY the lists it names show, in its order; removing an entry + * removes that tab. Each entry names one inbound relationship — the child + * object (`'task'`, every list of that child), or `object.field` when that + * child points here through more than one FK (`'event.related_to'`) — or a + * built-in tab by the platform object it draws (`RECORD_PAGE_BUILTIN_TABS`): + * + * - `'sys_attachment'` — attachments; still drawn only when the object + * enables files (`enable.files`), and not drawn when unlisted; + * - `'sys_approval_request'` — approvals; still drawn only when the record + * has approval requests. Unlisted, it follows the listed tabs: an + * approval is never hidden by leaving it out; + * - `'sys_activity'` — the one activity stream (activities, discussion and + * field changes, each still switched by the object's own keys). Unlisted, + * it closes the strip. + * + * `sys_comment` and `sys_audit_log` are parts of that stream, not tabs; + * `@objectstack/lint` warns on them and prescribes `'sys_activity'`. + * + * An entry is the bare name, or the object form + * {@link RelatedListEntryObjectSchema} (`{ list, label?, columns? }`) giving + * that list its own title and columns on the parent; the two forms mix. A + * built-in takes only the bare name. + * + * A child list another package adds is no exception: once this list is + * declared, it shows no tab until an entry names it, and `defineStack` + * accepts that name only when the package is in the stack. Letting an + * extension package place its own list is epic #35896's child card #35901. + * + * The FK's `relatedList: false` still hides a list whatever this says. Body + * tables a field group places in the overview (`fieldGroups[].relatedList`) + * are the field groups' to place and are not hidden by this list; it orders + * the body tables it names, and its `label` / `columns` apply wherever the + * list is drawn. * * Names are judged where the children are known (the shape alone is judged * at parse), and each refusal names the entry and the inbound relationships @@ -4652,21 +4775,14 @@ const ObjectSchemaBase = strictObject( * package's object that points in, so the entry is stored, and the * record page places nothing for it. The boundary is deliberate: the * `validate-related-list-refs` rule's header in `@objectstack/lint` - * carries the reasoning. - * - * It orders; it does not show or hide. `relatedList: false` on the FK still - * hides a listed relationship, and a FK's `relatedList: 'primary'` still - * decides where its list is drawn (the record's body rather than a side - * card): this order applies among the body tables and among the side cards. + * carries the reasoning; + * - the three built-in names are never judged as children. * * Reader: objectui's record page, through `deriveRelatedLists` - * (`ui/packages/app-shell/src/utils/deriveRelatedLists.ts`). + * (`ui/packages/app-shell/src/utils/deriveRelatedLists.ts`) and the + * synthesized page's tab list (`buildDefaultTabs`). */ - relatedLists: z.array( - z.string().regex(RELATED_LIST_ENTRY_PATTERN, { - message: 'A relatedLists entry is a child object name (e.g. "task") or object.field (e.g. "event.related_to"), in snake_case', - }), - ).optional().describe('Business order of this object\'s related lists on its record page, most important first. Each entry is a child object name (e.g. "task"), or object.field when that child has more than one relationship to this object (e.g. "event.related_to"). Listed relationships come first in this order; unlisted ones follow in the derived order (owned master_detail children, then lookup children). An entry whose child is in the stack but has no inbound lookup / master_detail field to this object is refused everywhere. An entry 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, since a child outside the package may be a downstream package\'s object that points here, and the record page places nothing for it. It orders only: relatedList: false on the relationship still hides a list, and relatedList: \'primary\' still places a list in the record\'s body, so the order applies among the body tables and among the side cards.'), + relatedLists: z.array(RelatedListEntrySchema).optional().describe('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. That includes a child list another package adds: it is hidden until this object names it, which a build accepts only when that package is in the stack (letting a package place its own list is a later change). 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.'), /** * [ADR-0085] Semantic role: the field that represents the record's LINEAR * lifecycle (an ordered pipeline / stage progression). A string names the diff --git a/packages/spec/src/data/related-list-entry.test.ts b/packages/spec/src/data/related-list-entry.test.ts new file mode 100644 index 00000000000..51319ef4065 --- /dev/null +++ b/packages/spec/src/data/related-list-entry.test.ts @@ -0,0 +1,42 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35897 · #35899] The one reading of a `relatedLists` entry's name and the + * built-in tab vocabulary every reader shares. + */ +import { describe, expect, it } from 'vitest'; +import { + RECORD_PAGE_BUILTIN_TABS, + RELATED_LIST_BUILTIN_PART_OF, + isRecordPageBuiltinTab, + relatedListEntryName, +} from './related-list-entry'; + +describe('relatedListEntryName', () => { + it('reads a bare name and the object form alike', () => { + expect(relatedListEntryName('task')).toBe('task'); + expect(relatedListEntryName('event.related_to')).toBe('event.related_to'); + expect(relatedListEntryName({ list: 'quote_line', columns: ['product'] })).toBe('quote_line'); + }); + + it('names nothing for any other value', () => { + for (const value of [undefined, null, 1, ['task'], {}, { list: 1 }]) { + expect(relatedListEntryName(value)).toBeUndefined(); + } + }); +}); + +describe('the built-in tab vocabulary', () => { + it('is the three platform objects the record page draws as its own tabs, in their default order', () => { + expect(RECORD_PAGE_BUILTIN_TABS).toEqual(['sys_attachment', 'sys_approval_request', 'sys_activity']); + for (const name of RECORD_PAGE_BUILTIN_TABS) expect(isRecordPageBuiltinTab(name)).toBe(true); + expect(isRecordPageBuiltinTab('sys_comment')).toBe(false); + expect(isRecordPageBuiltinTab({ list: 'sys_attachment' })).toBe(false); + }); + + it('maps the parts of the activity stream to the stream tab, and names no tab as a part', () => { + expect(RELATED_LIST_BUILTIN_PART_OF).toEqual({ sys_comment: 'sys_activity', sys_audit_log: 'sys_activity' }); + for (const tab of Object.values(RELATED_LIST_BUILTIN_PART_OF)) expect(isRecordPageBuiltinTab(tab)).toBe(true); + for (const part of Object.keys(RELATED_LIST_BUILTIN_PART_OF)) expect(isRecordPageBuiltinTab(part)).toBe(false); + }); +}); diff --git a/packages/spec/src/data/related-list-entry.ts b/packages/spec/src/data/related-list-entry.ts new file mode 100644 index 00000000000..c159d59ca82 --- /dev/null +++ b/packages/spec/src/data/related-list-entry.ts @@ -0,0 +1,77 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35897 · #35899] The words an `ObjectSchema.relatedLists` entry may say, + * and the one reading of an entry's name. + * + * Since #35897 a declared `relatedLists` is the record page's TAB LIST: only + * the relationships it names are shown as tabs, in its order. Three of its + * words are not relationships but the record page's three BUILT-IN tabs, + * named by the platform object each one draws: + * + * - `sys_attachment` — the attachments tab (file rows), drawn only when the + * object enables files (`enable.files`); + * - `sys_approval_request` — the approvals tab (approval steps), drawn only + * when the record has approval requests; + * - `sys_activity` — the activity stream tab: ONE stream merging the + * activities, the discussion and the field changes (each part still + * switched by the object's own `enable` keys and `trackHistory`). + * + * A built-in is drawn by its own renderer, never queried as a child table, so + * it is written only as its bare name: an object entry naming one is refused + * at parse (it would carry a label or columns no built-in renderer reads). + * + * `sys_comment` and `sys_audit_log` are parts of the activity stream, not tabs + * of their own; an entry naming one draws nothing, so `@objectstack/lint` + * (`validate-related-list-refs`) warns and prescribes `sys_activity`. + * + * Readers: the record page (objectui `deriveRelatedLists` and the synthesized + * page's tab list), Studio's related-list editor, `defineStack`'s name check + * and the lint rule, each through these exports, so no second list exists. + */ + +/** The record page's three built-in tabs, by the platform object each draws, in their default order. */ +export const RECORD_PAGE_BUILTIN_TABS = ['sys_attachment', 'sys_approval_request', 'sys_activity'] as const; + +/** One of the record page's built-in tab names. */ +export type RecordPageBuiltinTab = (typeof RECORD_PAGE_BUILTIN_TABS)[number]; + +const BUILTIN_TAB_SET: ReadonlySet = new Set(RECORD_PAGE_BUILTIN_TABS); + +/** Is `name` one of the record page's built-in tabs (`sys_attachment`, `sys_approval_request`, `sys_activity`)? */ +export function isRecordPageBuiltinTab(name: unknown): name is RecordPageBuiltinTab { + return typeof name === 'string' && BUILTIN_TAB_SET.has(name); +} + +/** + * The platform objects that are PARTS of a built-in tab rather than tabs of + * their own, each mapped to the built-in that draws it. + */ +export const RELATED_LIST_BUILTIN_PART_OF: Readonly> = Object.freeze({ + sys_comment: 'sys_activity', + sys_audit_log: 'sys_activity', +}); + +/** One `relatedLists` entry in its object form: the relationship named, with its own title and columns. */ +export interface RelatedListEntryObject { + readonly list: string; + readonly label?: string; + readonly columns?: readonly string[]; +} + +/** One `relatedLists` entry: the bare name, or the object form. */ +export type RelatedListEntryInput = string | RelatedListEntryObject; + +/** + * The name one `relatedLists` entry gives: the bare string itself, or the + * object form's `list`. `undefined` for anything else (a value the parse + * refuses; a reader of a stored row places nothing for it). + */ +export function relatedListEntryName(entry: unknown): string | undefined { + if (typeof entry === 'string') return entry; + if (typeof entry === 'object' && entry !== null && !Array.isArray(entry)) { + const list = (entry as { list?: unknown }).list; + if (typeof list === 'string') return list; + } + return undefined; +} diff --git a/packages/spec/src/migrations/entries/semantic/18.master-detail-related-list-tab-by-default.ts b/packages/spec/src/migrations/entries/semantic/18.master-detail-related-list-tab-by-default.ts index 21ee63d321f..bca670694b6 100644 --- a/packages/spec/src/migrations/entries/semantic/18.master-detail-related-list-tab-by-default.ts +++ b/packages/spec/src/migrations/entries/semantic/18.master-detail-related-list-tab-by-default.ts @@ -68,8 +68,9 @@ export const entry: SemanticMigration = { + 'draws no table for the child and the tab row carries the child\'s tab with its count; the create and ' + 'edit forms do not inline it. After adding a field group that names the ' + 'child, second in fieldGroups: the overview draws the child\'s table in the second group\'s place, the ' - + 'tab is still there, the create and edit forms inline the table at the same place (a tab of its own in a ' - + 'tabbed form), and the record page\'s Edit saves the ' + + 'tab is still there (on a parent that declares no relatedLists; a declared relatedLists decides the tabs, ' + + 'so there the tab shows only if an entry names the child), the create and edit forms inline the table ' + + 'at the same place (a tab of its own in a tabbed form), and the record page\'s Edit saves the ' + 'record fields and the rows in one save. A child whose FK sets inlineEdit and that no group names is not ' + 'inlined in the parent\'s forms. A child whose FK declares relatedList \'primary\' is drawn on the ' + 'record page as before: a body table with no tab of its own, whether or not a group positions it. Where ' diff --git a/packages/spec/src/migrations/entries/semantic/18.related-lists-declared-is-tab-list.ts b/packages/spec/src/migrations/entries/semantic/18.related-lists-declared-is-tab-list.ts new file mode 100644 index 00000000000..90b80d359e6 --- /dev/null +++ b/packages/spec/src/migrations/entries/semantic/18.related-lists-declared-is-tab-list.ts @@ -0,0 +1,45 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { SemanticMigration } from '../../types.js'; + +// #35897 (epic #35896) — an object's declared `relatedLists` changes meaning +// from "order only" to "the record page's tab list": the lists it names show, +// in its order, and a side list it leaves out shows no tab. The three built-in +// tabs (attachments, approvals, activity stream) are placed by object name. +// Semantic only, with no D2 conversion: which unlisted lists the author still +// wants is not recorded anywhere. +export const entry: SemanticMigration = { + id: 'related-lists-declared-is-tab-list', + surface: + 'objects[].relatedLists (data.ObjectSchema.relatedLists) when DECLARED and non-empty — an object ' + + 'that lists some of its inbound relationships and leaves others out', + replacement: + 'list every related list the record page should show, in the order it should show them; add ' + + "'sys_attachment' to keep the attachments tab of an object with enable.files, and optionally " + + "'sys_approval_request' and 'sys_activity' to place the approvals and activity-stream tabs. An object " + + 'that should keep every list declares no relatedLists at all', + reason: + 'The maintainer ruled that the record page\'s tabs are declared on the parent object in ' + + 'one place: removing an entry removes its tab (「删除tab就是不现实」, meaning not shown), with relatedLists as that ' + + 'list (「其实除了 overview,我们直接用 relatedLists 是不是就可以」) and the three built-in tabs named by ' + + 'their objects (「三个内置项,是不是可以直接用对应的对象名」). Until now a declared relatedLists only ' + + 'ordered: listed lists came first and every unlisted one still followed, and the attachments, ' + + 'approvals and stream tabs always closed the strip in a fixed order. Now, on a declared non-empty ' + + 'relatedLists, a side list no entry names shows no tab, a child list another package adds included: ' + + 'it is hidden until the parent names it, which a build accepts only when that package is in the ' + + 'parent\'s stack (letting a package place its own list is a later change); the attachments tab shows only when ' + + "'sys_attachment' is listed (and the object enables files, as before); the approvals tab, when " + + 'unlisted, follows the listed tabs and still shows whenever the record has requests; the stream ' + + 'tab, when unlisted, still closes the strip. Body tables a field group places stay at their group; ' + + 'the tab such a master_detail table also keeps on an undeclared page shows only when an entry names it, ' + + 'and relatedList: false on the FK still hides a list. An undeclared or empty relatedLists draws ' + + 'exactly what it drew before. A STORED object row is not rewritten: its record page changes at ' + + 'the next read. In-repo census before the change: no example, platform object, dogfood fixture ' + + 'or HotCRM object declared relatedLists; deployed metadata was NOT measured. ADR-0035 / ADR-0085 / ' + + 'ADR-0087', + acceptanceCriteria: + 'On the record page of each object that declares relatedLists, the tabs after the overview are the ' + + 'listed related lists and built-in tabs in the listed order, then (if unlisted) approvals when the ' + + 'record has requests and the activity stream last; an object that declares no relatedLists shows ' + + 'the same tabs as before.', +}; diff --git a/packages/spec/src/stack-related-lists-order.test.ts b/packages/spec/src/stack-related-lists-order.test.ts index 22ab1b74f23..909fda5c208 100644 --- a/packages/spec/src/stack-related-lists-order.test.ts +++ b/packages/spec/src/stack-related-lists-order.test.ts @@ -247,3 +247,71 @@ describe('defineStack — a field group relatedList names body tables only', () expect(refusal?.issues?.[0]).toContain('matches no inbound relationship'); }); }); + +/** + * [#35897 · #35899] A declared `relatedLists` is the record page's tab list, + * and an entry may be the object form `{ list, label?, columns? }`. The three + * built-in tab names (`sys_attachment`, `sys_approval_request`, + * `sys_activity`) name the page's own tabs: bare only, and never judged as a + * child. Each refusal row's control differs from it by one key or one entry. + */ +describe('ObjectSchema.relatedLists — entries with a title and columns, and the built-in tabs', () => { + it('accepts bare names, object entries and the built-in tab names, mixed (control)', () => { + const parsed = ObjectSchema.safeParse(lead({ + relatedLists: [ + { list: 'rlo_line', label: 'Line items', columns: ['product', 'amount'] }, + 'rlo_task', + { list: 'rlo_event.related_to' }, + 'sys_attachment', + 'sys_approval_request', + 'sys_activity', + ], + })); + expect(parsed.success).toBe(true); + expect(parsed.data?.relatedLists?.[0]).toEqual({ list: 'rlo_line', label: 'Line items', columns: ['product', 'amount'] }); + }); + + it.each(['sys_attachment', 'sys_approval_request', 'sys_activity'])( + "refuses the object form of the built-in tab '%s', prescribing the bare name", + (builtin) => { + const parsed = ObjectSchema.safeParse(lead({ relatedLists: [{ list: builtin, columns: ['name'] }] })); + expect(parsed.success).toBe(false); + const messages = JSON.stringify(parsed.error!.issues); + expect(messages).toContain('built-in record-page tabs'); + expect(ObjectSchema.safeParse(lead({ relatedLists: [builtin] })).success).toBe(true); + }, + ); + + it.each([ + ['an unknown key', { list: 'rlo_task', filter: { done: false } }], + ['the wrong word for the title', { list: 'rlo_task', title: 'Tasks' }], + ['column objects', { list: 'rlo_task', columns: [{ field: 'name' }] }], + ['an empty column list', { list: 'rlo_task', columns: [] }], + ['an empty label', { list: 'rlo_task', label: '' }], + ['no list', { label: 'Tasks' }], + ['a non-snake list', { list: 'Task' }], + ])('refuses %s in an object entry', (_label, entry) => { + expect(ObjectSchema.safeParse(lead({ relatedLists: [entry] })).success).toBe(false); + }); + + it('suggests label for title', () => { + const parsed = ObjectSchema.safeParse(lead({ relatedLists: [{ list: 'rlo_task', title: 'Tasks' }] })); + expect(JSON.stringify(parsed.error!.issues)).toContain('`title` → `label`'); + }); +}); + +describe('defineStack — relatedLists object entries and built-in tab names', () => { + it('leaves the built-in tab names unjudged, and judges an object entry by its list (control)', () => { + expect(() => defineStack(stackOf(lead({ + relatedLists: ['sys_attachment', { list: 'rlo_task', label: 'Tasks' }, 'sys_approval_request', 'sys_activity'], + })))).not.toThrow(); + }); + + it("refuses an object entry whose list matches no inbound relationship, at the entry's index", () => { + const refusal = refusalOf(() => defineStack(stackOf(lead({ relatedLists: ['sys_activity', { list: 'rlo_note', columns: ['title'] }] })))); + expect(refusal?.code).toBe('STACK_CROSS_REFERENCE_INVALID'); + expect(typeof refusal?.status).toBe('number'); + expect(refusal?.issues).toHaveLength(1); + expect(refusal?.issues?.[0]).toContain("Object 'rlo_lead' relatedLists[1] 'rlo_note' matches no inbound relationship"); + }); +}); diff --git a/packages/spec/src/stack.zod.ts b/packages/spec/src/stack.zod.ts index 5fcb37a76ae..38ac64d7812 100644 --- a/packages/spec/src/stack.zod.ts +++ b/packages/spec/src/stack.zod.ts @@ -15,6 +15,7 @@ import { findNamespaceObjectNameClashes, namespacedHoldersMeet, validateObjectNa import { validateNamespaceNotAddressLiteral } from './kernel/address-grammar'; import { PLATFORM_CAPABILITY_TOKENS, RETIRED_PLATFORM_CAPABILITY_GUIDANCE } from './kernel/platform-capabilities'; import { DatasourceSchema } from './data/datasource.zod'; +import { isRecordPageBuiltinTab, relatedListEntryName } from './data/related-list-entry'; import { TranslationBundleSchema, TranslationConfigSchema } from './system/translation.zod'; import { StackServerConfigSchema } from './system/stack-server.zod'; import { StackEmailConfigSchema } from './system/email-config.zod'; @@ -4604,7 +4605,13 @@ function collectRelatedListNameErrors( ); }; if (Array.isArray(parent.relatedLists)) { - parent.relatedLists.forEach((entry: unknown, i: number) => judge(entry, `relatedLists[${i}]`)); + // [#35897 · #35899] An entry is a bare name or `{ list, … }`; the three + // built-in tab names name the record page's own tabs, not a child. + parent.relatedLists.forEach((entry: unknown, i: number) => { + const name = relatedListEntryName(entry); + if (isRecordPageBuiltinTab(name)) return; + judge(name, `relatedLists[${i}]`); + }); } if (Array.isArray(parent.fieldGroups)) { parent.fieldGroups.forEach((group: unknown, i: number) => { diff --git a/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.relatedListsOrder-27069.test.ts b/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.relatedListsOrder-27069.test.ts index 5a004659562..2af00338c24 100644 --- a/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.relatedListsOrder-27069.test.ts +++ b/ui/packages/app-shell/src/utils/__tests__/deriveRelatedLists.relatedListsOrder-27069.test.ts @@ -41,23 +41,26 @@ describe('relatedLists — the declared business order (objectstack#27069)', () ]); }); - it('listed relationships come first in the declared order; the rest keep the derived order', () => { + it('listed relationships come first in the declared order; of the rest only the body tables stay, in the derived order (objectstack#35897)', () => { + // Since objectstack#35889 an owned child no group places is a tab, so an + // unlisted one goes; one a group of the lead places is a body table and stays. expect(order({ ...lead, relatedLists: ['task', 'campaign_member'] })).toEqual([ 'task.lead_id', 'campaign_member.lead_id', + ]); + const placing = { ...lead, fieldGroups: [{ key: 'notes', relatedList: 'note' }] }; + expect(order({ ...placing, relatedLists: ['task', 'campaign_member'] })).toEqual([ + 'task.lead_id', + 'campaign_member.lead_id', 'note.lead', - 'attachment.lead', - 'event.who_id', - 'event.related_to', ]); }); it('object.field names one FK of a child with several; a bare child name takes all of them', () => { - expect(order({ ...lead, relatedLists: ['event.related_to'] }).slice(0, 2)).toEqual([ + expect(order({ ...lead, relatedLists: ['event.related_to'] })).toEqual([ 'event.related_to', - 'note.lead', ]); - expect(order({ ...lead, relatedLists: ['event'] }).slice(0, 2)).toEqual([ + expect(order({ ...lead, relatedLists: ['event'] })).toEqual([ 'event.who_id', 'event.related_to', ]); @@ -68,15 +71,12 @@ describe('relatedLists — the declared business order (objectstack#27069)', () 'event.related_to', 'event.who_id', 'task.lead_id', - 'note.lead', - 'attachment.lead', - 'campaign_member.lead_id', ]); }); it('relatedList: false still hides a listed relationship', () => { const hiddenTask = { ...task, fields: { lead_id: { type: 'lookup', reference: 'lead', relatedList: false } } }; - const out = deriveRelatedLists({ ...lead, relatedLists: ['task'] }, [lead, hiddenTask, note]); + const out = deriveRelatedLists({ ...lead, relatedLists: ['task', 'note'] }, [lead, hiddenTask, note]); expect(out.map((r) => r.childObject)).toEqual(['note']); }); @@ -87,10 +87,10 @@ describe('relatedLists — the declared business order (objectstack#27069)', () }; const out = deriveRelatedLists({ ...lead, relatedLists: ['task'] }, [lead, note, task, primaryCampaign]); // `note` is an owned child with no relatedList: a tab since - // objectstack#35889 (no group of the lead places it), in its derived position. + // objectstack#35889 (no group of the lead places it), and unlisted, so it + // shows none (objectstack#35897); the unlisted primary list stays. expect(out.map((r) => [r.childObject, r.isPrimary])).toEqual([ ['task', false], - ['note', false], ['campaign_member', true], ]); }); @@ -157,3 +157,91 @@ describe("relatedList: 'primary' as body placement (objectstack#27069)", () => { expect(deriveRelatedLists(quote, [quote, line])[0].isPrimary).toBe(false); }); }); + +/** + * objectstack#35897 — a DECLARED `relatedLists` is the tab list: a side list + * no entry names is not derived (the authoring surface keeps it flagged); + * a body table stays, being the field groups' to place. objectstack#35899 — + * the object form's `label` / `columns` win over the FK's keys. + */ +describe('relatedLists — which lists show, and an entry\'s title and columns (objectstack#35897, objectstack#35899)', () => { + it('undeclared or empty: every list, as before (control)', () => { + const all = order(lead); + expect(all).toHaveLength(6); + expect(order({ ...lead, relatedLists: [] })).toEqual(all); + }); + + it('the built-in tab names name no child list, even one that points here', () => { + const sysActivity = { name: 'sys_activity', label: 'Activity', fields: { lead_id: { type: 'lookup', reference: 'lead' } } }; + const lists = deriveRelatedLists({ ...lead, relatedLists: ['sys_activity', 'task'] }, [...registry, sysActivity]) + .map((r) => `${r.childObject}.${r.referenceField}`); + expect(lists).toEqual(['task.lead_id']); + }); + + it('a group-placed master_detail table keeps its tab undeclared or listed, and loses only the tab when unlisted (objectstack#35889 item 4)', () => { + const order_ = { + name: 'order', + label: 'Order', + fields: { name: { type: 'text' } }, + fieldGroups: [{ key: 'lines', relatedList: 'order_line' }], + }; + const line = { name: 'order_line', label: 'Order Line', fields: { order: { type: 'master_detail', reference: 'order' } } }; + const note = { name: 'order_note', label: 'Order Note', fields: { order_id: { type: 'lookup', reference: 'order' } } }; + const catalog = [order_, line, note]; + const lineOf = (relatedLists?: unknown[]) => + deriveRelatedLists({ ...order_, ...(relatedLists ? { relatedLists } : {}) }, catalog).find((r) => r.childObject === 'order_line'); + // The default page (no relatedLists): a body table at its group AND a tab. + expect(lineOf()).toMatchObject({ isPrimary: true, keepsTab: true }); + // Declared and naming it: the same. + expect(lineOf(['order_note', 'order_line'])).toMatchObject({ isPrimary: true, keepsTab: true }); + // Declared without it: the body table stays at its group, with no tab. + const unlisted = lineOf(['order_note']); + expect(unlisted).toMatchObject({ isPrimary: true }); + expect(unlisted?.keepsTab).toBeUndefined(); + }); + + it('the authoring surface keeps an unlisted side list, flagged isUnlisted', () => { + const lists = deriveRelatedLists({ ...lead, relatedLists: ['task'] }, registry, { includeHidden: true }); + expect(lists.filter((r) => r.isUnlisted).map((r) => `${r.childObject}.${r.referenceField}`)).toEqual([ + 'note.lead', + 'attachment.lead', + 'event.who_id', + 'event.related_to', + 'campaign_member.lead_id', + ]); + expect(lists.find((r) => r.childObject === 'task')?.isUnlisted).toBeUndefined(); + }); + + it("the object form's label and columns win over the FK's; the bare form keeps the FK's (control)", () => { + const quoteLine = { + name: 'quote_line', + label: 'Quote Line', + fields: { + lead: { + type: 'lookup', + reference: 'lead', + relatedListTitle: 'FK title', + relatedListColumns: ['product', 'quantity', 'unit_price', 'amount'], + }, + }, + }; + const reg = [...registry, quoteLine]; + const [entry] = deriveRelatedLists({ ...lead, relatedLists: [{ list: 'quote_line', label: 'Line items', columns: ['product', 'amount'] }] }, reg); + expect(entry).toMatchObject({ childObject: 'quote_line', title: 'Line items', columns: ['product', 'amount'] }); + const [bare] = deriveRelatedLists({ ...lead, relatedLists: ['quote_line'] }, reg); + expect(bare).toMatchObject({ childObject: 'quote_line', title: 'FK title', columns: ['product', 'quantity', 'unit_price', 'amount'] }); + const [labelOnly] = deriveRelatedLists({ ...lead, relatedLists: [{ list: 'quote_line', label: 'Line items' }] }, reg); + expect(labelOnly.columns).toEqual(['product', 'quantity', 'unit_price', 'amount']); + }); + + it("an object entry's label names every list it names first; a later entry for the same list changes nothing", () => { + const lists = deriveRelatedLists( + { ...lead, relatedLists: [{ list: 'event.related_to', label: 'Regarding' }, { list: 'event', label: 'Events' }] }, + registry, + ); + expect(lists.slice(0, 2).map((r) => [r.referenceField, r.title])).toEqual([ + ['related_to', 'Regarding'], + ['who_id', 'Events'], + ]); + }); +}); diff --git a/ui/packages/app-shell/src/utils/deriveRelatedLists.ts b/ui/packages/app-shell/src/utils/deriveRelatedLists.ts index 970860683d9..15f3a647a91 100644 --- a/ui/packages/app-shell/src/utils/deriveRelatedLists.ts +++ b/ui/packages/app-shell/src/utils/deriveRelatedLists.ts @@ -57,11 +57,24 @@ * - ORDER is the parent's declared business order first: the parent object's * `relatedLists` (objectstack#27069) names inbound relationships — a child * object, or `object.field` for one FK — and those lists come first, in - * that order ({@link resolveRelatedListOrder}). Every unlisted list follows - * in the derived order: owned (`master_detail`) children before plain - * `lookup` children, preserving discovery order within each group. The - * primary flag places a list and no longer orders it; consumers that split - * body tables from side cards keep this order within each half. + * that order ({@link resolveRelatedListOrder}). Undeclared, every list + * follows in the derived order: owned (`master_detail`) children before + * plain `lookup` children, preserving discovery order within each group. + * The primary flag places a list and no longer orders it; consumers that + * split body tables from side cards keep this order within each half. + * - VISIBILITY (objectstack#35897): a DECLARED `relatedLists` is the record + * page's tab list, so a side list no entry names is not derived at all + * (the authoring surface, `includeHidden`, keeps it flagged + * `isUnlisted`). A body table (`isPrimary`) is the field groups' to place + * and is kept, after the listed ones, with no tab of its own (no + * `keepsTab`) unless an entry names it. Undeclared or empty: every list, as + * before. The three built-in tab names (`RECORD_PAGE_BUILTIN_TABS` in + * `@objectstack/spec/data`) name the page's own tabs, never a child list; + * the synthesized page places those (`buildDefaultTabs`). + * - An entry's own TITLE and COLUMNS (objectstack#35899): the object form + * `{ list, label, columns }` wins over the FK's `relatedListTitle` / + * `relatedListColumns`, for every list that entry names first, wherever + * the list is drawn (its tab, or the body table a field group places). * - A child object the data API does not expose (`enable.apiEnabled: * false`, e.g. a credential or device table) yields no record-page list: * every read of its records answers `404 OBJECT_API_DISABLED`. The @@ -75,7 +88,13 @@ * server-side; this closes the UI/DX gap. */ -import { fieldGroupsPlaceRelationship, isBodyTableRelationship, isGroupPlaceableRelationship } from '@objectstack/spec/data'; +import { + fieldGroupsPlaceRelationship, + isBodyTableRelationship, + isGroupPlaceableRelationship, + isRecordPageBuiltinTab, + relatedListEntryName, +} from '@objectstack/spec/data'; import { convertSortToQueryParams } from '@object-ui/core'; import { relatedListEntryNames } from '@object-ui/plugin-detail'; @@ -141,7 +160,10 @@ export interface DerivedRelatedList { /** * Present (true) on a body table that a parent field group MAKES one: a * `master_detail` FK declaring no `relatedList` that a group names. Such a - * table keeps its tab on the record page too (objectstack#35889 item 4). A + * table keeps its tab on the record page too (objectstack#35889 item 4), + * unless the parent DECLARES `relatedLists` and no entry names it: a declared + * list decides the tabs (objectstack#35897), so the table stays at its group + * with no tab. A * `'primary'` table is a body table without a group and keeps no tab, as * before, whether or not a group positions it. */ @@ -171,6 +193,13 @@ export interface DerivedRelatedList { * The record page never asks, so a hidden list never reaches it. */ isHidden?: true; + /** + * True when the parent DECLARES `relatedLists` and no entry names this side + * list (objectstack#35897), so the record page shows no tab for it — present + * only when the caller asked for hidden relationships + * ({@link DeriveRelatedListsOptions.includeHidden}), as `isHidden` is. + */ + isUnlisted?: true; } /** @@ -199,11 +228,12 @@ interface MergedObjectLike { name?: string; label?: string; /** - * The spec's optional `relatedLists` (objectstack#27069): the business order - * of THIS object's related lists, read when it is the parent. Each entry is - * a child object name or `object.field`; see {@link resolveRelatedListOrder}. + * The spec's optional `relatedLists` (objectstack#27069, objectstack#35897, + * objectstack#35899): THIS object's record-page tabs, read when it is the + * parent. Each entry is a child object name, `object.field`, a built-in tab + * name, or `{ list, label?, columns? }`; see {@link resolveRelatedListOrder}. */ - relatedLists?: string[]; + relatedLists?: unknown[]; /** * The spec's optional `fieldGroups`, read when this object is the parent: a * group's `relatedList` names the related list it places (objectstack#35889). @@ -290,18 +320,47 @@ export function resolveRelatedListOrder(); - const head: T[] = []; + const naming = relatedListNamingEntries(lists, declared); + if (!naming) return [...lists]; + const head = [...naming.keys()]; + return [...head, ...lists.filter((list) => !naming.has(list))]; +} + +/** The object form of one `relatedLists` entry, as a reader of a stored row sees it. */ +interface RelatedListEntryObjectLike { + list: string; + label?: unknown; + columns?: unknown; +} + +/** + * Each list a declared `relatedLists` names, mapped to the FIRST entry naming + * it, in the declared order (a Map keeps insertion order). `null` when nothing + * is declared (absent, or empty). An entry is read through the spec's + * `relatedListEntryName` (a bare name, or the object form's `list`); a + * built-in tab name names no list here. + */ +function relatedListNamingEntries( + lists: readonly T[], + declared: readonly unknown[] | null | undefined, +): Map | null { + if (!Array.isArray(declared) || declared.length === 0) return null; + const naming = new Map(); for (const entry of declared) { - if (typeof entry !== 'string') continue; + const name = relatedListEntryName(entry); + if (name === undefined || isRecordPageBuiltinTab(name)) continue; for (const list of lists) { - if (placed.has(list) || !relatedListEntryNames(entry, list)) continue; - placed.add(list); - head.push(list); + if (naming.has(list) || !relatedListEntryNames(name, list)) continue; + naming.set(list, entry); } } - return [...head, ...lists.filter((list) => !placed.has(list))]; + return naming; +} + +/** Is `entry` the object form of a `relatedLists` entry (objectstack#35899)? */ +function isEntryObject(entry: unknown): entry is RelatedListEntryObjectLike { + return typeof entry === 'object' && entry !== null && !Array.isArray(entry) + && typeof (entry as { list?: unknown }).list === 'string'; } /** @@ -356,7 +415,8 @@ export interface DeriveRelatedListsOptions { * Derive the detail-page related lists for `objectDef` from the full object * registry. Returns the lists `objectDef.relatedLists` names first, in that * order, then the rest: owned (`master_detail`) children, then `lookup` - * children; deterministic and side-effect free (safe to memoize). + * children — of which, when `relatedLists` is declared, only the body tables + * (objectstack#35897); deterministic and side-effect free (safe to memoize). */ export function deriveRelatedLists( objectDef: MergedObjectLike | null | undefined, @@ -454,7 +514,42 @@ export function deriveRelatedLists( } } - const all = resolveRelatedListOrder([...owned, ...referenced], objectDef.relatedLists); + // objectstack#35897 — a declared `relatedLists` is the tab list: the lists it + // names come first, in its order, and a side list it does not name is not + // derived (the authoring surface keeps it, flagged). A body table is the + // field groups' to place, so it stays, after the listed ones. + // objectstack#35899 — the naming entry's own `label` / `columns` win over + // the FK's `relatedListTitle` / `relatedListColumns`. + const derived = [...owned, ...referenced]; + const naming = relatedListNamingEntries(derived, objectDef.relatedLists); + const all: Working[] = []; + for (const list of resolveRelatedListOrder(derived, objectDef.relatedLists)) { + if (!naming) { + all.push(list); + continue; + } + const entry = naming.get(list); + if (!naming.has(list)) { + // A body table no entry names stays at its group, with no tab: a + // declared `relatedLists` decides the tabs, so the tab a group-placed + // `master_detail` table keeps on the default page goes (the seat's + // reading of objectstack#35897 against #35889 item 4). + if (list.isPrimary) { + const { keepsTab: _unlistedTab, ...bodyOnly } = list; + all.push(bodyOnly); + } else if (options?.includeHidden) all.push({ ...list, isUnlisted: true }); + continue; + } + if (!isEntryObject(entry)) { + all.push(list); + continue; + } + all.push({ + ...list, + ...(typeof entry.label === 'string' && entry.label ? { title: entry.label } : {}), + ...(Array.isArray(entry.columns) && entry.columns.length > 0 ? { columns: entry.columns } : {}), + }); + } // Multi-FK disambiguation: when a child object points here through more than // one relationship and gave no explicit title, suffix the FK label so the two // lists are distinguishable (e.g. "Opportunities · Partner Account"; the list diff --git a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx index 5f4196ca864..f26ef426b0f 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx @@ -1955,8 +1955,14 @@ describe('RecordDetailView.relatedListsOrder-27241', () => { expect(cardOrder(container)).toEqual(['showcase_task.project', 'showcase_note.project', 'showcase_call.project']); }); - it('with relatedLists: the declared lists first in that order, the rest after them in the derived order', async () => { + it('with relatedLists: only the declared lists, in that order; an unlisted side list draws nothing (objectstack#35897)', async () => { const { container } = renderPage(objectsWith(['showcase_call', 'showcase_note.project'])); + await waitFor(() => expect(cardOrder(container)).toHaveLength(2), { timeout: 5000 }); + expect(cardOrder(container)).toEqual(['showcase_call.project', 'showcase_note.project']); + }); + + it('with relatedLists listing every list: the declared order, nothing dropped (control)', async () => { + const { container } = renderPage(objectsWith(['showcase_call', 'showcase_note.project', 'showcase_task'])); await waitFor(() => expect(cardOrder(container)).toHaveLength(3), { timeout: 5000 }); expect(cardOrder(container)).toEqual(['showcase_call.project', 'showcase_note.project', 'showcase_task.project']); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/RelatedListEntriesWidget-35923.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/RelatedListEntriesWidget-35923.test.tsx new file mode 100644 index 00000000000..935851d101f --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/RelatedListEntriesWidget-35923.test.tsx @@ -0,0 +1,78 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#35923 (review M1): the generic object form's `relatedLists` + * row. An entry is a bare name or `{ list, label?, columns? }` (#35897, + * #35899); the row used `string-tags`, which renders each element as a React + * child, so an object entry written by Studio's Record page tabs editor broke + * the form. The row now names `related-list-entries`, which keeps every + * entry's stored form. + */ + +// The source under test reaches these through dynamic imports: their first load is paid at collection. +import '@objectstack/formula'; +import '@objectstack/lint'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, fireEvent, cleanup } from '@testing-library/react'; +import { objectForm } from '@objectstack/spec/data'; +import { WIDGETS } from './widgets'; + +afterEach(cleanup); + +const Entries = WIDGETS['related-list-entries']; +const objectEntry = { list: 'quote_line', label: 'Line items', columns: ['product', 'amount'] }; + +/** The `relatedLists` row of the published object form, wherever its section puts it. */ +function relatedListsRow(): { widget?: string; helpText?: string } | undefined { + const rows: Array<{ field?: string; widget?: string; helpText?: string }> = []; + for (const section of (objectForm as { sections?: Array<{ fields?: unknown[] }> }).sections ?? []) { + for (const f of section.fields ?? []) if (f && typeof f === 'object') rows.push(f as never); + } + return rows.find((r) => r.field === 'relatedLists'); +} + +describe('relatedLists on the generic object form (objectstack#35923 M1)', () => { + it('the published row names the entries widget, and its help text states the tab-list meaning', () => { + const row = relatedListsRow(); + expect(row?.widget).toBe('related-list-entries'); + expect(row?.helpText).toContain('shows no tab'); + expect(row?.helpText).not.toContain('the rest follow'); + }); + + it('renders an object entry beside a bare one, with its title and columns', () => { + render( {}} schema={{}} />); + expect(screen.getByTestId('related-list-entry-task')).toHaveTextContent('task'); + const chip = screen.getByTestId('related-list-entry-quote_line'); + expect(chip).toHaveTextContent('quote_line'); + expect(chip).toHaveTextContent('Line items'); + expect(chip).toHaveTextContent('product, amount'); + }); + + it('removing a bare entry keeps the object entry as stored; adding appends a bare name', () => { + const onChange = vi.fn(); + render(); + fireEvent.click(screen.getAllByRole('button')[0]); + expect(onChange).toHaveBeenLastCalledWith([objectEntry]); + + const input = screen.getByRole('textbox'); + fireEvent.change(input, { target: { value: 'sys_activity' } }); + fireEvent.keyDown(input, { key: 'Enter' }); + expect(onChange).toHaveBeenLastCalledWith(['task', objectEntry, 'sys_activity']); + }); + + it('does not add a second entry for a name an object entry already places', () => { + const onChange = vi.fn(); + render(); + const input = screen.getByRole('textbox'); + fireEvent.change(input, { target: { value: 'quote_line' } }); + fireEvent.keyDown(input, { key: 'Enter' }); + expect(onChange).toHaveBeenLastCalledWith([objectEntry]); + }); + + it('removing the last entry removes the key', () => { + const onChange = vi.fn(); + render(); + fireEvent.click(screen.getByRole('button')); + expect(onChange).toHaveBeenLastCalledWith(undefined); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.controlWidgetGridNaming-9889.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.controlWidgetGridNaming-9889.test.tsx index 99d2a98670b..3484e1c73a3 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.controlWidgetGridNaming-9889.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.controlWidgetGridNaming-9889.test.tsx @@ -52,6 +52,9 @@ * column name. */ +// The source under test reaches these through dynamic imports: their first load is paid at collection. +import '@objectstack/formula'; +import '@objectstack/lint'; import { describe, it, expect, afterEach } from 'vitest'; import { render, cleanup, fireEvent, screen } from '@testing-library/react'; import { SchemaForm } from './SchemaForm'; @@ -104,6 +107,7 @@ const CONTROL_CASES: WidgetCase[] = [ { widget: 'icon', control: (c) => c.querySelector('[aria-haspopup="dialog"]'), faceName: 'the icon picker trigger' }, { widget: 'color-input', control: (c) => c.querySelector('input[type="color"]'), faceName: 'the native colour input' }, { widget: 'string-tags', control: (c) => c.querySelector('input[type="text"]'), faceName: 'the tag entry box' }, + { widget: 'related-list-entries', control: (c) => c.querySelector('input[type="text"]'), faceName: 'the related-list entry box' }, { widget: 'secret', control: (c) => c.querySelector('input[type="password"]'), faceName: 'the masked credential box' }, ]; diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx index 408e9503a1e..af98c0d5d5e 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx @@ -51,6 +51,9 @@ * that renders nothing, and that green would mean nothing. */ +// The source under test reaches these through dynamic imports: their first load is paid at collection. +import '@objectstack/formula'; +import '@objectstack/lint'; import { describe, it, expect, afterEach, vi } from 'vitest'; import { render, screen, cleanup, within } from '@testing-library/react'; @@ -169,6 +172,7 @@ const CASES: Case[] = [ { key: 'master-detail', schema: { type: 'array', title: TITLE, items: { type: 'object', properties: { name: { type: 'string' } } } }, value: [{ name: 'a' }] }, { key: 'master-detail', variant: 'untyped-items', schema: { type: 'array', title: TITLE, items: {} }, value: [] }, { key: 'string-tags', schema: { type: 'array', title: TITLE, items: { type: 'string' } }, value: ['a'] }, + { key: 'related-list-entries', schema: { type: 'array', title: TITLE }, value: ['task', { list: 'quote_line', label: 'Lines', columns: ['product'] }] }, { key: 'multiselect', schema: { type: 'array', title: TITLE, items: { type: 'string', enum: ['grid', 'kanban'] } }, value: ['grid'] }, { key: 'multiselect', variant: 'no-options', schema: { type: 'array', title: TITLE, items: { type: 'string' } }, value: ['a'] }, { key: 'code', schema: { type: 'string', title: TITLE }, spec: { language: 'javascript' }, value: 'x = 1' }, diff --git a/ui/packages/app-shell/src/views/metadata-admin/__tests__/SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/__tests__/SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx index 83a8efb97b1..c4d143610e0 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/__tests__/SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/__tests__/SchemaForm.controlWidgetFailureArmNaming-9931.test.tsx @@ -55,6 +55,9 @@ */ import '@testing-library/jest-dom/vitest'; +// The source under test reaches these through dynamic imports: their first load is paid at collection. +import '@objectstack/formula'; +import '@objectstack/lint'; import { describe, it, expect, afterEach, vi } from 'vitest'; import { render, screen, cleanup, waitFor } from '@testing-library/react'; import { SchemaForm, type FormFieldSpec } from '../SchemaForm'; @@ -163,6 +166,7 @@ const CASES: ControlCase[] = [ { key: 'icon', schema: { type: 'string' }, value: 'check', banner: null }, { key: 'color-input', schema: { type: 'string' }, value: '#112233', banner: null }, { key: 'string-tags', schema: { type: 'array', items: { type: 'string' } }, value: ['a'], banner: null }, + { key: 'related-list-entries', schema: { type: 'array' }, value: ['task'], banner: null }, { key: 'secret', schema: { type: 'string' }, value: 's3cr3t', banner: null }, ]; diff --git a/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts b/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts index 65933535805..459e8de6329 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts @@ -52,7 +52,7 @@ export const ZH_CN_SPEC_FORMS: NonNullable = { imageField: { label: '记录图片字段' }, isSystem: { label: '系统内置' }, highlightFields: { label: '重点字段' }, - relatedLists: { label: '相关列表顺序' }, + relatedLists: { label: '记录页页签' }, searchableFields: { label: '可搜索字段' }, fieldGroups: { label: '字段分组' }, 'fieldGroups.key': { label: '键' }, diff --git a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx index 1371ba68905..f9be79d5d31 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx @@ -1737,6 +1737,117 @@ function StringTagsWidget({ ); } +/* -------------------------------------------------------------------------- */ +/* related-list-entries — chip input for an object's `relatedLists` */ +/* -------------------------------------------------------------------------- */ + +/** + * The name an object's `relatedLists` entry places: the bare string, or the + * object form's `list` (objectstack#35897 / #35899). The spec's own reader is + * `relatedListEntryName`; this one also answers a half-typed draft value. + */ +function relatedListEntryChipName(entry: unknown): string | undefined { + if (typeof entry === 'string') return entry; + if (entry && typeof entry === 'object' && typeof (entry as { list?: unknown }).list === 'string') { + return (entry as { list: string }).list; + } + return undefined; +} + +/** + * `relatedLists` on the generic object form (objectstack#35923 review M1): + * the `string-tags` face, over a list whose entries are a bare name OR the + * object form `{ list, label?, columns? }`. `string-tags` casts its value to + * `string[]` and renders each element as a React child, so an object entry + * (which Studio's record-page tabs editor writes as soon as a title or + * columns are set) broke the form. Here every entry keeps its stored form: + * add appends a bare name, remove drops one entry, and an object entry's + * chip shows its title and columns beside the name. Those are edited in + * Studio's object settings (Record page tabs), which reads the relationships. + */ +function RelatedListEntriesWidget({ + id, + ariaLabelledBy, + required, + value, + onChange, + readOnly, +}: WidgetProps) { + const locale = useMetadataLocale(); + const entries = Array.isArray(value) ? (value as unknown[]) : []; + const [draft, setDraft] = React.useState(''); + const names = entries.map(relatedListEntryChipName); + + function add(raw: string) { + const parts = raw + .split(/[,\n]/) + .map((s) => s.trim()) + .filter(Boolean); + if (parts.length === 0) return; + const next = [...entries]; + for (const p of parts) if (!names.includes(p) && !next.includes(p)) next.push(p); + onChange(next); + setDraft(''); + } + function remove(idx: number) { + const next = entries.slice(); + next.splice(idx, 1); + onChange(next.length > 0 ? next : undefined); + } + + return ( +
+
+ {entries.map((entry, i) => { + const name = names[i] ?? '?'; + const details = entry && typeof entry === 'object' ? (entry as { label?: unknown; columns?: unknown }) : undefined; + const label = typeof details?.label === 'string' ? details.label : undefined; + const columns = Array.isArray(details?.columns) ? details.columns.filter((c): c is string => typeof c === 'string') : []; + return ( + + {name} + {label && {label}} + {columns.length > 0 && [{columns.join(', ')}]} + {!readOnly && ( + + )} + + ); + })} + setDraft(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter' || e.key === ',') { + e.preventDefault(); + add(draft); + } else if (e.key === 'Backspace' && !draft && entries.length > 0) { + remove(entries.length - 1); + } + }} + onBlur={() => draft && add(draft)} + className="min-w-[8rem] flex-1 bg-transparent text-sm outline-none" + /> +
+
+ ); +} + /* -------------------------------------------------------------------------- */ /* multiselect — pick from a fixed option set (array of enum) */ /* -------------------------------------------------------------------------- */ @@ -3467,6 +3578,7 @@ export const WIDGETS = { 'condition': ConditionWidget, 'master-detail': MasterDetailWidget, 'string-tags': StringTagsWidget, + 'related-list-entries': RelatedListEntriesWidget, 'multiselect': MultiSelectWidget, 'code': CodeWidget, 'secret': SecretWidget, @@ -3579,6 +3691,7 @@ export const WIDGET_LABELLING: Record = { 'condition': 'group', 'master-detail': 'group', 'string-tags': 'control', + 'related-list-entries': 'control', 'multiselect': 'group', 'code': 'group', 'secret': 'control', diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectSettingsPanel.relatedListsOrder-27054.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectSettingsPanel.relatedListsOrder-27054.test.tsx index 54dad7eeba2..51b3ec214ac 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectSettingsPanel.relatedListsOrder-27054.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectSettingsPanel.relatedListsOrder-27054.test.tsx @@ -129,8 +129,10 @@ describe('ObjectSettingsPanel — relatedLists is an ordered list of the inbound expect(rowOrder()).toEqual(['event.related_to', 'task']); const after = pageOrder(lastLists(writes)); expect(after).not.toEqual(before); - // The listed relationships lead, in the written order; the rest keep the derived order. - expect(after).toEqual(['event.related_to', 'task.lead_id', 'note.lead', 'event.who_id']); + // Only the listed relationships show, in the written order: an unlisted + // side list shows no tab (objectstack#35897), and the owned `note` is a tab + // too since no group of the lead places it (objectstack#35889). + expect(after).toEqual(['event.related_to', 'task.lead_id']); // The keyboard path writes the same kind of order. fireEvent.click(within(screen.getByTestId('related-lists-row-task')).getByRole('button', { name: 'Move up' })); @@ -168,14 +170,18 @@ describe('ObjectSettingsPanel — relatedLists is an ordered list of the inbound expect(screen.getByTestId('related-lists-tail-row-campaign_member.lead_id')).toHaveTextContent( t('engine.studio.settings.relatedListsHidden', 'en-US'), ); - // The record page agrees: the listed one leads, the rest trail in the derived order. - expect(pageOrder(['event.related_to'])).toEqual(['event.related_to', 'note.lead', 'task.lead_id', 'event.who_id']); + // The record page: only the listed one; an unlisted list shows no tab + // (objectstack#35897), and no group of the lead places `note` as a table. + expect(pageOrder(['event.related_to'])).toEqual(['event.related_to']); - // The add picker offers exactly the tail, spelled as entries. + // The add picker offers the built-in tabs not listed (no attachments: the + // lead does not enable files), then exactly the tail, spelled as entries. fireEvent.keyDown(screen.getByTestId('related-lists-add-select'), { key: 'ArrowDown' }); const options = within(await screen.findByRole('listbox')).getAllByRole('option').map((o) => o.textContent); expect(options).toEqual([ t('engine.studio.settings.relatedListsAdd', 'en-US'), + 'Approvals (sys_approval_request)', + 'Activity (sys_activity)', 'Note (note)', 'Task (task)', 'Event · Who (event.who_id)', diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectSettingsPanel.relatedListsTabList-35897.test.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectSettingsPanel.relatedListsTabList-35897.test.tsx new file mode 100644 index 00000000000..d526108b334 --- /dev/null +++ b/ui/packages/app-shell/src/views/studio-design/ObjectSettingsPanel.relatedListsTabList-35897.test.tsx @@ -0,0 +1,180 @@ +/** + * 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#35897 · #35899 — the object settings panel authors `relatedLists` + * as the record page's TAB LIST: + * - an entry's object form (`{ list, label, columns }`) and the built-in tab + * names survive every write (a move, a removal, an add); + * - the built-in tabs are offered by object name, attachments only when the + * object enables files, and a listed attachments tab on an object without + * files says it does not show; + * - a relationship row edits its own title and columns: a title or a column + * writes the object form, clearing both writes the bare name again; + * - the preview draws the tabs in order, built-ins included. + */ + +import '@testing-library/jest-dom/vitest'; +import React from 'react'; +import { describe, it, expect, afterEach } from 'vitest'; +import { render, screen, fireEvent, within, cleanup } from '@testing-library/react'; +import { MetadataCtx, type MetadataContextValue } from '@object-ui/react'; +import { t } from '../metadata-admin/i18n'; +import { ObjectSettingsPanel } from './ObjectSettingsPanel'; + +afterEach(cleanup); + +type Row = Record; + +const quote: Row = { name: 'quote', label: 'Quote', fields: { name: { type: 'text', label: 'Name' } } }; +const line: Row = { + name: 'quote_line', + label: 'Quote Line', + fields: { + quote_id: { type: 'lookup', reference: 'quote', label: 'Quote' }, + product: { type: 'text', label: 'Product' }, + quantity: { type: 'number', label: 'Quantity' }, + amount: { type: 'currency', label: 'Amount' }, + }, +}; +const task: Row = { + name: 'task', + label: 'Task', + fields: { quote_id: { type: 'lookup', reference: 'quote', label: 'Quote' }, subject: { type: 'text', label: 'Subject' } }, +}; +const REGISTRY = [quote, line, task]; + +function store(): MetadataContextValue { + return { + apps: [], + objects: REGISTRY, + dashboards: [], + reports: [], + pages: [], + loading: false, + error: null, + refresh: async () => {}, + invalidate: () => {}, + ensureType: async () => [], + getItem: async () => null, + getItemsByType: () => [], + getTypeStatus: () => 'ready', + }; +} + +function Host({ initial, writes }: { initial: Row; writes: Row[] }) { + const [draft, setDraft] = React.useState(initial); + const value = React.useMemo(() => store(), []); + return ( + + setDraft((d) => { + const next = { ...d, ...patch }; + writes.push(next); + return next; + })} + locale="en-US" + /> + + ); +} + +const rowOrder = () => + screen.getAllByTestId(/^related-lists-row-/).map((el) => el.getAttribute('data-testid')!.replace('related-lists-row-', '')); +const lastLists = (writes: Row[]) => writes.at(-1)!.relatedLists; +const LINE_ENTRY = { list: 'quote_line', label: 'Line items', columns: ['product', 'amount'] }; + +describe('ObjectSettingsPanel — relatedLists is the record page tab list (objectstack#35897)', () => { + it('a move keeps an entry\'s object form and the built-in names', () => { + const writes: Row[] = []; + render(); + expect(rowOrder()).toEqual(['quote_line', 'sys_activity', 'task']); + // The entry's own title names its row; the built-in is named and tagged. + expect(screen.getByTestId('related-lists-row-quote_line')).toHaveTextContent('Line items'); + const stream = screen.getByTestId('related-lists-row-sys_activity'); + expect(stream).toHaveTextContent(t('engine.studio.settings.relatedListsBuiltin.sys_activity', 'en-US')); + expect(stream).toHaveTextContent(t('engine.studio.settings.relatedListsBuiltin', 'en-US')); + expect(screen.queryByTestId('related-lists-unmatched')).toBeNull(); + + fireEvent.click(within(screen.getByTestId('related-lists-row-task')).getByRole('button', { name: 'Move up' })); + expect(lastLists(writes)).toEqual([LINE_ENTRY, 'task', 'sys_activity']); + + fireEvent.click(screen.getByRole('button', { name: 'Remove task' })); + expect(lastLists(writes)).toEqual([LINE_ENTRY, 'sys_activity']); + }); + + it('offers the built-ins by object name, attachments only with files on', async () => { + const writes: Row[] = []; + render(); + fireEvent.keyDown(screen.getByTestId('related-lists-add-select'), { key: 'ArrowDown' }); + const options = within(await screen.findByRole('listbox')).getAllByRole('option').map((o) => o.textContent); + expect(options).toEqual([ + t('engine.studio.settings.relatedListsAdd', 'en-US'), + 'Attachments (sys_attachment)', + 'Approvals (sys_approval_request)', + 'Activity (sys_activity)', + 'Quote Line (quote_line)', + ]); + fireEvent.click(screen.getByRole('option', { name: 'Attachments (sys_attachment)' })); + expect(lastLists(writes)).toEqual(['task', 'sys_attachment']); + // A relationship not listed shows no tab. + expect(screen.getByTestId('related-lists-tail')).toHaveTextContent(t('engine.studio.settings.relatedListsTail', 'en-US')); + // The preview draws the tabs in order, then the unlisted approvals and stream. + expect(screen.getByTestId('related-lists-preview-side')).toHaveTextContent('Task · Attachments · Approvals · Activity'); + }); + + it('a listed attachments tab on an object without files says it does not show', () => { + render(); + expect(screen.getByTestId('related-lists-attachments-off')).toHaveTextContent( + t('engine.studio.settings.relatedListsAttachmentsOff', 'en-US'), + ); + expect(screen.getByTestId('related-lists-preview-side')).toHaveTextContent('Task · Approvals · Activity'); + expect(screen.getByTestId('related-lists-preview-side')).not.toHaveTextContent('Attachments'); + }); + + it('edits an entry\'s own title and columns, and clearing both writes the bare name', async () => { + const writes: Row[] = []; + render(); + // A built-in has no edit; a relationship has. + fireEvent.click(screen.getByTestId('related-lists-edit-quote_line')); + const details = screen.getByTestId('related-lists-details-quote_line'); + + fireEvent.change(within(details).getByTestId('related-lists-title-quote_line'), { target: { value: 'Line items' } }); + expect(lastLists(writes)).toEqual([{ list: 'quote_line', label: 'Line items' }, 'task']); + + // The column picker offers the child's own fields. + fireEvent.keyDown(within(details).getByTestId('related-lists-column-add-quote_line'), { key: 'ArrowDown' }); + const options = within(await screen.findByRole('listbox')).getAllByRole('option').map((o) => o.textContent); + expect(options).toEqual([ + t('engine.studio.settings.relatedListsColumnAdd', 'en-US'), + 'Quote (quote_id)', + 'Product (product)', + 'Quantity (quantity)', + 'Amount (amount)', + ]); + fireEvent.click(screen.getByRole('option', { name: 'Amount (amount)' })); + expect(lastLists(writes)).toEqual([{ list: 'quote_line', label: 'Line items', columns: ['amount'] }, 'task']); + + // A move elsewhere in the list keeps the details. + fireEvent.click(within(screen.getByTestId('related-lists-row-task')).getByRole('button', { name: 'Move up' })); + expect(lastLists(writes)).toEqual(['task', { list: 'quote_line', label: 'Line items', columns: ['amount'] }]); + + // Clearing the title and the last column writes the bare name again. + fireEvent.change(screen.getByTestId('related-lists-title-quote_line'), { target: { value: '' } }); + fireEvent.click(within(screen.getByTestId('related-lists-details-quote_line')).getByRole('button', { name: 'Remove amount' })); + expect(lastLists(writes)).toEqual(['task', 'quote_line']); + }); + + it('a built-in row has no edit', () => { + render(); + expect(screen.queryByTestId('related-lists-edit-sys_approval_request')).toBeNull(); + expect(screen.getByTestId('related-lists-edit-task')).toBeInTheDocument(); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/ObjectSettingsPanel.tsx b/ui/packages/app-shell/src/views/studio-design/ObjectSettingsPanel.tsx index ce92f5a54e2..e2effcbc23b 100644 --- a/ui/packages/app-shell/src/views/studio-design/ObjectSettingsPanel.tsx +++ b/ui/packages/app-shell/src/views/studio-design/ObjectSettingsPanel.tsx @@ -94,6 +94,7 @@ function SettingsPicker({ disabled, className, testId, + ariaLabel, }: { value: string; options: ReadonlyArray<{ value: string; label: string }>; @@ -101,6 +102,8 @@ function SettingsPicker({ disabled?: boolean; className: string; testId: string; + /** The trigger's accessible name, when nothing around it gives one. */ + ariaLabel?: string; }) { const at = options.findIndex((o) => o.value === value); return ( @@ -113,7 +116,7 @@ function SettingsPicker({ }} disabled={disabled} > - + @@ -407,6 +410,7 @@ export function ObjectSettingsPanel({ renderAdd={(options, add) => ( { if (v) add(v); diff --git a/ui/packages/app-shell/src/views/studio-design/RelatedListsEditor.tsx b/ui/packages/app-shell/src/views/studio-design/RelatedListsEditor.tsx index c79db9079c4..26f41609d88 100644 --- a/ui/packages/app-shell/src/views/studio-design/RelatedListsEditor.tsx +++ b/ui/packages/app-shell/src/views/studio-design/RelatedListsEditor.tsx @@ -7,30 +7,43 @@ */ /** - * The object's `relatedLists` (objectstack#27069) as an ORDERED list of its - * inbound relationships — what `highlightFields` is to fields, for the lists of - * child records on the record page. + * The object's `relatedLists` as its record page's TAB LIST (objectstack#27069, + * #35897, #35899): the inbound relationships and the built-in tabs the record + * page shows after the overview, in order — what `highlightFields` is to + * fields, for the tabs. * * - The rows are the declared entries, in order: drag one to a new place, or * move it with its up / down buttons (the shared `OrderedRowList`, the * rows `HighlightFieldsEditor` draws). - * - Every relationship no entry names follows, greyed and not draggable, in - * the derived order the record page gives it (owned `master_detail` - * children, then `lookup` children); the add picker lists exactly those. - * - It orders; it does not show or hide. A relationship hidden by - * `relatedList: false` on its FK is listed (an entry may name it) and - * marked hidden; the switch itself stays on the field. - * - Every write is checked first ({@link acceptRelatedListEntries}): an entry - * that names no inbound relationship never enters the value, since the - * spec's `defineStack` check and the publish door's lint both refuse it. A - * stored one keeps its row, marked, and the next write leaves it out. + * - A row is a relationship (the child, or `child.field`) or one of the three + * built-in tabs, named by the platform object each draws: attachments + * (`sys_attachment`), approvals (`sys_approval_request`) and the activity + * stream (`sys_activity`). The add picker offers the built-ins not yet + * listed (attachments only when the object enables files) and every + * relationship no entry names. + * - Once anything is listed, a relationship no entry names shows no tab: it + * is listed below, greyed, as not shown (a table a field group places in + * the overview stays there). With nothing listed every list shows in the + * default order. + * - A relationship row's Edit opens its own title and columns (the entry's + * object form, `{ list, label?, columns? }`), which win over the child FK's + * `relatedListTitle` / `relatedListColumns`; clearing both writes the bare + * name again. A built-in takes neither. + * - Every write is checked first ({@link acceptTabListEntries}): an entry + * that names no inbound relationship and no built-in never enters the + * value, since the spec's `defineStack` check and the publish door's lint + * both refuse it. A stored one keeps its row, marked, and the next write + * leaves it out. An entry's object form and a built-in name survive every + * write. * - Removing the last entry removes the key. - * - A preview draws the order the record page will use, through the record - * page's own derivation, split into body tables and side cards (the order - * applies within each). + * - A preview draws what the record page will use, through the record page's + * own derivation: the body tables, and the tabs in order. */ import React from 'react'; +import { Pencil } from 'lucide-react'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@object-ui/components'; +import { isRecordPageBuiltinTab, relatedListEntryName, type RecordPageBuiltinTab, type RelatedListEntryInput } from '@objectstack/spec/data'; import { deriveRelatedLists, type DerivedRelatedList, @@ -39,7 +52,12 @@ import { moveArray } from '../metadata-admin/inspectors/_shared.js'; import { t, tFormat, type SupportedLocale } from '../metadata-admin/i18n.js'; import { OrderedRowList } from './OrderedRowList.js'; import { - acceptRelatedListEntries, + acceptTabListEntries, + BUILTIN_TABS, + builtinTabLabelKey, + childColumnChoices, + entryDetails, + entryWithDetails, relationshipEntry, relationshipLabel, relationshipsNamedBy, @@ -57,6 +75,10 @@ function Badges({ named, locale }: { named: readonly DerivedRelatedList[]; local ); } +function Tag({ children }: { children: React.ReactNode }) { + return {children}; +} + /** A row's label; none for an entry that names no relationship (its spelling is all it has). */ function entryLabel(entry: string, named: readonly DerivedRelatedList[]): string { if (named.length === 0) return ''; @@ -64,6 +86,86 @@ function entryLabel(entry: string, named: readonly DerivedRelatedList[]): string return entry.includes('.') ? relationshipLabel(named[0]) : named[0].childLabel; } +/** One relationship entry's own title and columns. */ +function EntryDetailsEditor({ + name, + entry, + named, + choices, + onChange, + locale, +}: { + name: string; + entry: unknown; + named: readonly DerivedRelatedList[]; + choices: Array<{ name: string; label: string }> | undefined; + onChange: (next: RelatedListEntryInput) => void; + locale?: SupportedLocale; +}) { + const details = entryDetails(entry); + const columns = details.columns ?? []; + const write = (patch: { label?: string; columns?: readonly string[] }) => + onChange(entryWithDetails(name, { label: details.label, columns, ...patch })); + const known = new Set((choices ?? []).map((c) => c.name)); + const labelOf = (col: string) => choices?.find((c) => c.name === col)?.label ?? col; + const remaining = (choices ?? []).filter((c) => !columns.includes(c.name)); + // The title the record page draws when the entry sets none. + const fallback = named[0] ? (named[0].title || named[0].childLabel) : name; + return ( +
+ +
+ + {t(columns.length > 0 ? 'engine.studio.settings.relatedListsColumns' : 'engine.studio.settings.relatedListsColumnsDefault', locale)} + + `related-lists-column-${name}-${col}`} + renderRow={(col) => ( + + {labelOf(col)} + {col} + + )} + onMove={(from, to) => write({ columns: moveArray(columns, from, to) })} + onRemove={(col) => write({ columns: columns.filter((c) => c !== col) })} + removeLabel={(col) => tFormat('engine.studio.settings.removeField', locale, { field: col })} + /> + {remaining.length > 0 && ( + + )} +
+
+ ); +} + export function RelatedListsEditor({ name, draft, @@ -77,43 +179,83 @@ export function RelatedListsEditor({ /** The object draft (reads `relatedLists`; its own fields may add a self-reference). */ draft: Record; /** The next list; `undefined` removes the key. */ - onChange: (next: string[] | undefined) => void; + onChange: (next: RelatedListEntryInput[] | undefined) => void; disabled?: boolean; locale?: SupportedLocale; /** - * The host's "add relationship" picker over `options` (the unlisted - * relationships); `add` appends one, through the same pre-write check. + * The host's "add" picker over `options` (the built-in tabs and the + * relationships not listed); `add` appends one, through the same pre-write + * check. */ renderAdd?: (options: Array<{ value: string; label: string }>, add: (entry: string) => void) => React.ReactNode; }) { const { catalog, relationships, ready } = useRelatedListCatalog(name, draft); - const stored = Array.isArray(draft.relatedLists) - ? (draft.relatedLists as unknown[]).filter((e): e is string => typeof e === 'string') - : []; - // The rows: the stored entries, in order, once each. An entry that names no - // inbound relationship keeps its row (marked) until a write leaves it out. - const rows = [...new Set(stored)]; - const listed = acceptRelatedListEntries(rows, relationships); - const unmatched = ready ? rows.filter((e) => !listed.includes(e)) : []; + const [editing, setEditing] = React.useState(null); + const storedEntries = Array.isArray(draft.relatedLists) ? (draft.relatedLists as unknown[]) : []; + // The rows: the stored entries, in order, once per name. An entry that names + // no inbound relationship keeps its row (marked) until a write leaves it out. + const entryByName = new Map(); + for (const entry of storedEntries) { + const entryName = relatedListEntryName(entry); + if (entryName !== undefined && !entryByName.has(entryName)) entryByName.set(entryName, entry); + } + const rows = [...entryByName.keys()]; + const listed = acceptTabListEntries(storedEntries, relationships); + const listedNames = listed.map((e) => relatedListEntryName(e)!); + const unmatched = ready ? rows.filter((e) => !listedNames.includes(e)) : []; const locked = !!disabled || !ready; + const filesOn = (draft.enable as { files?: unknown } | undefined)?.files === true; - // The pre-write check: nothing that names no inbound relationship is written. - const write = (next: readonly string[]) => { - const accepted = acceptRelatedListEntries(next, relationships); + // The pre-write check: nothing that names no inbound relationship and no + // built-in tab is written. + const write = (next: readonly unknown[]) => { + const accepted = acceptTabListEntries(next, relationships); onChange(accepted.length > 0 ? accepted : undefined); }; + const entriesFor = (names: readonly string[]) => names.map((n) => entryByName.get(n) ?? n); const named = (entry: string) => relationshipsNamedBy(entry, relationships); - const tail = relationships.filter((r) => !listed.some((entry) => named(entry).includes(r))); - const addOptions = tail.map((r) => { - const entry = relationshipEntry(r, relationships); - return { value: entry, label: `${relationshipLabel(r)} (${entry})` }; - }); + const builtinLabel = (tab: RecordPageBuiltinTab) => t(builtinTabLabelKey(tab), locale); + const tail = relationships.filter((r) => !listedNames.some((entry) => named(entry).includes(r))); + const addOptions = [ + ...BUILTIN_TABS + .filter((tab) => !rows.includes(tab) && (tab !== 'sys_attachment' || filesOn)) + .map((tab) => ({ value: tab, label: `${builtinLabel(tab)} (${tab})` })), + ...tail.map((r) => { + const entry = relationshipEntry(r, relationships); + return { value: entry, label: `${relationshipLabel(r)} (${entry})` }; + }), + ]; // What the record page will draw: its own derivation, over what a write keeps. const preview = deriveRelatedLists({ ...draft, name, relatedLists: listed }, catalog as never[]); const body = preview.filter((r) => r.isPrimary); const side = preview.filter((r) => !r.isPrimary); + // The tab strip after the overview: the listed tabs in order, then + // approvals and the activity stream when they are not listed. Attachments + // show only when listed and the object enables files. + const tabs: string[] = []; + const placedSide = new Set(); + for (const entry of listedNames) { + if (isRecordPageBuiltinTab(entry)) { + if (entry !== 'sys_attachment' || filesOn) tabs.push(builtinLabel(entry)); + continue; + } + for (const r of side) { + if (placedSide.has(r) || !named(entry).some((n) => n.childObject === r.childObject && n.referenceField === r.referenceField)) continue; + placedSide.add(r); + tabs.push(relationshipLabel(r)); + } + } + for (const r of side) if (!placedSide.has(r)) tabs.push(relationshipLabel(r)); + if (listedNames.length === 0 && filesOn) tabs.push(builtinLabel('sys_attachment')); + for (const tab of ['sys_approval_request', 'sys_activity'] as const) { + if (!listedNames.includes(tab)) tabs.push(builtinLabel(tab)); + } + + const editingEntry = editing !== null && rows.includes(editing) && !unmatched.includes(editing) && !isRecordPageBuiltinTab(editing) + ? editing + : null; return (
@@ -126,18 +268,63 @@ export function RelatedListsEditor({ items={rows} ariaLabel={t('engine.studio.settings.relatedLists', locale)} rowTestId={(entry) => `related-lists-row-${entry}`} - renderRow={(entry) => ( - - {entryLabel(entry, named(entry))} - {entry} - - - )} - onMove={(from, to) => write(moveArray(rows, from, to))} - onRemove={(entry) => write(rows.filter((x) => x !== entry))} + renderRow={(entry) => { + if (isRecordPageBuiltinTab(entry)) { + return ( + + {builtinLabel(entry)} + {entry} + {t('engine.studio.settings.relatedListsBuiltin', locale)} + + ); + } + const isUnmatched = unmatched.includes(entry); + const own = entryDetails(entryByName.get(entry)); + return ( + + + {own.label || entryLabel(entry, named(entry))} + {entry} + + {own.columns && own.columns.length > 0 && ( + {tFormat('engine.studio.settings.relatedListsColumnCount', locale, { count: String(own.columns.length) })} + )} + + {!locked && !isUnmatched && ( + + )} + + ); + }} + onMove={(from, to) => write(entriesFor(moveArray(rows, from, to)))} + onRemove={(entry) => write(entriesFor(rows.filter((x) => x !== entry)))} removeLabel={(entry) => tFormat('engine.studio.settings.removeField', locale, { field: entry })} disabled={locked} /> + {editingEntry !== null && ( + write(rows.map((n) => (n === editingEntry ? next : entryByName.get(n) ?? n)))} + locale={locale} + /> + )} + {rows.includes('sys_attachment') && !filesOn && ( +

+ {t('engine.studio.settings.relatedListsAttachmentsOff', locale)} +

+ )} {unmatched.length > 0 && (
{unmatched.map((entry) => ( @@ -179,9 +366,9 @@ export function RelatedListsEditor({
)} {!locked && addOptions.length > 0 && ( -
{renderAdd?.(addOptions, (entry) => write([...rows, entry]))}
+
{renderAdd?.(addOptions, (entry) => write([...entriesFor(rows), entry]))}
)} - {ready && preview.length > 0 && ( + {ready && (preview.length > 0 || tabs.length > 0) && (
{t('engine.studio.settings.relatedListsPreview', locale)}
@@ -191,10 +378,10 @@ export function RelatedListsEditor({ {body.map(relationshipLabel).join(' · ')}
)} - {side.length > 0 && ( + {tabs.length > 0 && (
{t('engine.studio.settings.relatedListsPreviewSide', locale)}: - {side.map(relationshipLabel).join(' · ')} + {tabs.join(' · ')}
)}
diff --git a/ui/packages/app-shell/src/views/studio-design/relatedListVocabulary.ts b/ui/packages/app-shell/src/views/studio-design/relatedListVocabulary.ts index 6e89ea7c1f1..4e76a172311 100644 --- a/ui/packages/app-shell/src/views/studio-design/relatedListVocabulary.ts +++ b/ui/packages/app-shell/src/views/studio-design/relatedListVocabulary.ts @@ -28,6 +28,13 @@ import React from 'react'; import { useMetadata } from '@object-ui/react'; +import { + isRecordPageBuiltinTab, + relatedListEntryName, + RECORD_PAGE_BUILTIN_TABS, + type RecordPageBuiltinTab, + type RelatedListEntryInput, +} from '@objectstack/spec/data'; import { deriveRelatedLists, relatedListEntryNames, @@ -99,6 +106,91 @@ export function acceptRelatedListEntries( return out; } +/** + * [#35897 · #35899] The pre-write check of the object's TAB LIST + * (`relatedLists`): keep, in order and once per name, each entry that is one + * of the record page's built-in tabs (`sys_attachment`, `sys_approval_request`, + * `sys_activity`) or names at least one inbound relationship. A relationship + * entry keeps its object form (`{ list, label?, columns? }`); a built-in is + * written as its bare name, the only spelling the spec admits. A field + * group's `relatedList` takes no built-in, so it keeps + * {@link acceptRelatedListEntries}. + */ +export function acceptTabListEntries( + entries: readonly unknown[], + all: readonly DerivedRelatedList[], +): RelatedListEntryInput[] { + const out: RelatedListEntryInput[] = []; + const seen = new Set(); + for (const entry of entries) { + const name = relatedListEntryName(entry); + if (name === undefined || seen.has(name)) continue; + if (isRecordPageBuiltinTab(name)) { + seen.add(name); + out.push(name); + continue; + } + if (relationshipsNamedBy(name, all).length === 0) continue; + seen.add(name); + out.push(entry as RelatedListEntryInput); + } + return out; +} + +/** The record page's built-in tabs, in their default order. */ +export const BUILTIN_TABS: readonly RecordPageBuiltinTab[] = RECORD_PAGE_BUILTIN_TABS; + +/** The i18n key naming one built-in tab. */ +export function builtinTabLabelKey(name: RecordPageBuiltinTab): string { + return `engine.studio.settings.relatedListsBuiltin.${name}`; +} + +/** + * One entry with its own title and columns: the bare name when it carries + * neither (the spelling an entry without details is written in), else the + * object form with only the keys that carry something. + */ +export function entryWithDetails( + name: string, + details: { label?: string; columns?: readonly string[] }, +): RelatedListEntryInput { + const label = details.label?.trim() ? details.label : undefined; + const columns = details.columns && details.columns.length > 0 ? [...details.columns] : undefined; + if (label === undefined && columns === undefined) return name; + return { list: name, ...(label !== undefined ? { label } : {}), ...(columns !== undefined ? { columns } : {}) }; +} + +/** An entry's own title and columns (none for a bare name). */ +export function entryDetails(entry: unknown): { label?: string; columns?: string[] } { + if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return {}; + const { label, columns } = entry as { label?: unknown; columns?: unknown }; + return { + ...(typeof label === 'string' ? { label } : {}), + ...(Array.isArray(columns) ? { columns: columns.filter((c): c is string => typeof c === 'string') } : {}), + }; +} + +/** + * The fields of the child objects one entry names, as column choices: name and + * label, in the child's declared order (one child, or the first child when an + * entry somehow names two). `undefined` when the catalog does not serve the + * child's fields, so an editor cannot tell a real column from a misspelling. + */ +export function childColumnChoices( + named: readonly DerivedRelatedList[], + catalog: readonly ObjectDoc[], +): Array<{ name: string; label: string }> | undefined { + const child = named[0]?.childObject; + if (!child) return undefined; + const doc = catalog.find((o) => o.name === child); + const fields = doc?.fields; + if (!fields || typeof fields !== 'object' || Array.isArray(fields)) return undefined; + return Object.entries(fields as Record).map(([name, def]) => { + const label = def && typeof def === 'object' ? (def as { label?: unknown }).label : undefined; + return { name, label: typeof label === 'string' && label ? label : name }; + }); +} + /** What a related list is called in an editor row: its title, else the child's label. */ export function relationshipLabel(list: DerivedRelatedList): string { return list.title || list.childLabel; diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 267e8a870aa..625327de463 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -2362,10 +2362,10 @@ const STUDIO_EN: Record = { 'engine.studio.settings.addFieldOption': '+ Add field…', 'engine.studio.settings.undeclared': '(not declared — surfaces pick heuristically)', 'engine.studio.settings.highlightMax': 'Up to {max} highlight fields — remove one to add another.', - 'engine.studio.settings.relatedLists': 'Related list order (relatedLists) — the order of the lists of child records on this object\'s record page, most important first; it orders only, and showing or hiding a list stays on its relationship field', - 'engine.studio.settings.relatedListsAdd': '+ Add relationship…', - 'engine.studio.settings.relatedListsTail': 'Not listed — shown after these, in the default order', - 'engine.studio.settings.relatedListsUndeclared': 'Not declared — every list shows in the default order: owned children first, then lookups', + 'engine.studio.settings.relatedLists': 'Record page tabs (relatedLists) — the lists of child records and the built-in tabs this object\'s record page shows after the overview, in order; once anything is listed, a relationship not listed shows no tab', + 'engine.studio.settings.relatedListsAdd': '+ Add a list or tab…', + 'engine.studio.settings.relatedListsTail': 'Not listed — no tab on the record page (a table a field group places in the overview stays there)', + 'engine.studio.settings.relatedListsUndeclared': 'Not declared — every list shows in the default order: owned children first, then lookups, then attachments, approvals and the activity stream', 'engine.studio.settings.relatedListsNone': 'No object points at this one through a lookup or master-detail field yet.', 'engine.studio.settings.relatedListsLoading': 'Loading the objects that point at this one…', 'engine.studio.settings.relatedListsUnmatched': '“{entry}” names no relationship that points at this object, so the next change to this list leaves it out.', @@ -2373,7 +2373,18 @@ const STUDIO_EN: Record = { 'engine.studio.settings.relatedListsPrimary': 'in body', 'engine.studio.settings.relatedListsPreview': 'Record page order', 'engine.studio.settings.relatedListsPreviewBody': 'In the body', - 'engine.studio.settings.relatedListsPreviewSide': 'Side cards', + 'engine.studio.settings.relatedListsPreviewSide': 'Tabs', + 'engine.studio.settings.relatedListsBuiltin': 'built-in', + 'engine.studio.settings.relatedListsBuiltin.sys_attachment': 'Attachments', + 'engine.studio.settings.relatedListsBuiltin.sys_approval_request': 'Approvals', + 'engine.studio.settings.relatedListsBuiltin.sys_activity': 'Activity', + 'engine.studio.settings.relatedListsAttachmentsOff': 'Files are off for this object, so the attachments tab does not show.', + 'engine.studio.settings.relatedListsEdit': 'Edit the title and columns of {entry}', + 'engine.studio.settings.relatedListsTitle': 'Title', + 'engine.studio.settings.relatedListsColumns': 'Columns', + 'engine.studio.settings.relatedListsColumnsDefault': 'Columns — none chosen, so the list\'s default columns show', + 'engine.studio.settings.relatedListsColumnAdd': '+ Add column…', + 'engine.studio.settings.relatedListsColumnCount': '{count} columns', 'engine.studio.settings.sharing': 'Who can see which records', 'engine.studio.settings.sharingHint': 'Baseline record visibility applied before positions and sharing rules (ADR-0056/0090)', 'engine.studio.settings.sharingModel': 'Sharing model (sharingModel) — who can see and edit records another user owns', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index d244373187f..3f189c1a084 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -2148,10 +2148,10 @@ const STUDIO_ZH: Record = { 'engine.studio.settings.addFieldOption': '+ 添加字段…', 'engine.studio.settings.undeclared': '(未声明 —— 各处按启发式自动挑选)', 'engine.studio.settings.highlightMax': '最多 {max} 个重点字段——移除一个才能再添加。', - 'engine.studio.settings.relatedLists': '关联列表顺序(relatedLists)—— 本对象记录页上各子记录列表的顺序,最重要的在前;只管排序,显示与否仍在关系字段上设置', - 'engine.studio.settings.relatedListsAdd': '+ 添加关系…', - 'engine.studio.settings.relatedListsTail': '未列出 —— 排在以上之后,按默认顺序', - 'engine.studio.settings.relatedListsUndeclared': '未声明 —— 所有列表按默认顺序:先主从子对象,再查找关系', + 'engine.studio.settings.relatedLists': '记录页页签(relatedLists)—— 本对象记录页在概览之后显示的子记录列表和内置页签,按顺序;一旦列出任何一项,未列出的关系就不显示页签', + 'engine.studio.settings.relatedListsAdd': '+ 添加列表或页签…', + 'engine.studio.settings.relatedListsTail': '未列出 —— 记录页上不显示其页签(字段分组放进概览的表格仍在概览中)', + 'engine.studio.settings.relatedListsUndeclared': '未声明 —— 所有列表按默认顺序显示:先主从子对象,再查找关系,然后是附件、审批和活动流', 'engine.studio.settings.relatedListsNone': '还没有对象通过查找或主从字段指向本对象。', 'engine.studio.settings.relatedListsLoading': '正在加载指向本对象的对象…', 'engine.studio.settings.relatedListsUnmatched': '“{entry}”不对应任何指向本对象的关系,下次修改此列表时会被去掉。', @@ -2159,7 +2159,18 @@ const STUDIO_ZH: Record = { 'engine.studio.settings.relatedListsPrimary': '正文', 'engine.studio.settings.relatedListsPreview': '记录页顺序', 'engine.studio.settings.relatedListsPreviewBody': '正文', - 'engine.studio.settings.relatedListsPreviewSide': '侧栏卡片', + 'engine.studio.settings.relatedListsPreviewSide': '页签', + 'engine.studio.settings.relatedListsBuiltin': '内置', + 'engine.studio.settings.relatedListsBuiltin.sys_attachment': '附件', + 'engine.studio.settings.relatedListsBuiltin.sys_approval_request': '审批', + 'engine.studio.settings.relatedListsBuiltin.sys_activity': '活动', + 'engine.studio.settings.relatedListsAttachmentsOff': '本对象未启用文件,附件页签不会显示。', + 'engine.studio.settings.relatedListsEdit': '编辑 {entry} 的标题和列', + 'engine.studio.settings.relatedListsTitle': '标题', + 'engine.studio.settings.relatedListsColumns': '列', + 'engine.studio.settings.relatedListsColumnsDefault': '列 —— 未选择,显示该列表的默认列', + 'engine.studio.settings.relatedListsColumnAdd': '+ 添加列…', + 'engine.studio.settings.relatedListsColumnCount': '{count} 列', 'engine.studio.settings.sharing': '谁能看到哪些记录', 'engine.studio.settings.sharingHint': '在岗位与共享规则之前生效的记录可见性基线(ADR-0056/0090)', 'engine.studio.settings.sharingModel': '共享模型(sharingModel)—— 谁能查看和编辑他人拥有的记录', diff --git a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.test.ts b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.test.ts index 43c9af245b6..861893ef18b 100644 --- a/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.test.ts +++ b/ui/packages/plugin-detail/src/synth/__tests__/buildDefaultPageSchema.test.ts @@ -987,3 +987,68 @@ describe('buildDefaultTabs — stable tab values (objectui#2257)', () => { ]); }); }); + +/** + * objectstack#35897 — a declared `relatedLists` arranges the tabs after the + * overview, the three built-in tabs placed by object name. The host's + * `related` is what exists (`deriveRelatedLists` drops unlisted side lists); + * this pins the arrangement. Each row's control differs by one entry. + */ +describe('declared relatedLists arranges the tabs (objectstack#35897)', () => { + const def = (relatedLists?: unknown[], files = true): ObjectDefLike => ({ + name: 'account', + label: 'Account', + fields: { name: { type: 'text', label: 'Name' } }, + ...(files ? { enable: { files: true } } : {}), + ...(relatedLists ? { relatedLists } : {}), + }); + const related = [ + { objectName: 'task', relationshipField: 'account_id' }, + { objectName: 'contact', relationshipField: 'account_id' }, + ]; + const values = (d: ObjectDefLike, approvals = true) => + tabItems(buildDefaultTabs(d, { related, ...(approvals ? { approvals: { count: 1 } } : {}) })).map((t: any) => t.value); + + it('undeclared or empty: the lists, then attachments, approvals and the stream, as before (control)', () => { + const before = ['details', 'related:task.account_id', 'related:contact.account_id', 'attachments', 'approvals', 'timeline']; + expect(values(def())).toEqual(before); + expect(values(def([]))).toEqual(before); + }); + + it("['task', 'sys_attachment', 'contact']: task, attachments, contact, then the unlisted approvals and the stream last", () => { + expect(values(def(['task', 'sys_attachment', 'contact']))).toEqual([ + 'details', 'related:task.account_id', 'attachments', 'related:contact.account_id', 'approvals', 'timeline', + ]); + }); + + it("leaving 'sys_attachment' out removes the attachments tab", () => { + expect(values(def(['task', 'contact']))).toEqual([ + 'details', 'related:task.account_id', 'related:contact.account_id', 'approvals', 'timeline', + ]); + }); + + it("'sys_attachment' listed on an object without files draws no attachments tab", () => { + expect(values(def(['sys_attachment', 'task', 'contact'], false))).not.toContain('attachments'); + }); + + it('places the approvals and stream tabs where they are listed; approvals still need requests', () => { + expect(values(def(['sys_activity', 'contact', 'sys_approval_request', 'task']))).toEqual([ + 'details', 'timeline', 'related:contact.account_id', 'approvals', 'related:task.account_id', + ]); + expect(values(def(['sys_activity', 'contact', 'sys_approval_request', 'task']), false)).toEqual([ + 'details', 'timeline', 'related:contact.account_id', 'related:task.account_id', + ]); + }); + + it('reads the object form by its list, object.field by its one FK, and the attachments tab stays the file-rows node', () => { + const tabs = buildDefaultTabs(def([{ list: 'contact.account_id', label: 'People' }, 'sys_attachment', 'task']), { related }); + expect(tabItems(tabs).map((t: any) => t.value)).toEqual([ + 'details', 'related:contact.account_id', 'attachments', 'related:task.account_id', 'timeline', + ]); + expect(tabItems(tabs).find((t: any) => t.value === 'attachments').children).toEqual([{ type: 'record:attachments' }]); + }); + + it('a related tab the host passed but no entry names follows the listed tabs, in the order passed', () => { + expect(values(def(['contact']))).toEqual(['details', 'related:contact.account_id', 'related:task.account_id', 'approvals', 'timeline']); + }); +}); diff --git a/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts b/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts index 1e4e3646846..d2865751016 100644 --- a/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts +++ b/ui/packages/plugin-detail/src/synth/buildDefaultPageSchema.ts @@ -23,7 +23,7 @@ * the existing DetailView output. */ -import { deriveFieldGroupLayout } from '@objectstack/spec/data'; +import { deriveFieldGroupLayout, isRecordPageBuiltinTab, relatedListEntryName, type RecordPageBuiltinTab } from '@objectstack/spec/data'; import { RECORD_HIGHLIGHTS_MAX } from '@objectstack/spec/ui'; import type { SelectOptionKind, ServiceObject } from '@objectstack/spec/data'; import { detectStatusField } from '@object-ui/types'; @@ -103,6 +103,14 @@ export interface ObjectDefLike { * Attachments tab beside Details/Related (objectstack#4358). */ enable?: { files?: boolean; [key: string]: any }; + /** + * The spec's `relatedLists` (objectstack#35897): the record page's tabs + * beside the overview, in order. Read here for the three built-in tab names + * (`RECORD_PAGE_BUILTIN_TABS`) and to place each related tab at its + * entry's position; which related lists exist (and their titles and + * columns) is the host's `related` option. See {@link buildDefaultTabs}. + */ + relatedLists?: readonly 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 @@ -1084,7 +1092,63 @@ function synthTabs( } // objectstack#34590 — the 动态 tab closes the strip. if (timeline.length > 0) items.push({ label: 'Activity stream', value: 'timeline', children: timeline }); - return componentNode('page:tabs', { items }); + return componentNode('page:tabs', { items: arrangeDeclaredTabs(def?.relatedLists, items) }); +} + +/** The tab value each built-in tab name draws (objectstack#35897). */ +const BUILTIN_TAB_VALUES: Readonly> = { + sys_attachment: 'attachments', + sys_approval_request: 'approvals', + sys_activity: 'timeline', +}; + +/** + * objectstack#35897 — the object's declared `relatedLists` arranges the tabs + * after the overview. Absent or empty: `items` exactly as built (every list, + * then attachments, approvals, the stream). Declared: + * + * - each tab sits at the first entry naming it: a related tab at the entry + * naming its relationship (`related:.`), a built-in at its + * object name (`sys_attachment`, `sys_approval_request`, `sys_activity`); + * - the attachments tab is drawn only when listed (it still needs + * `enable.files`, decided above); + * - an unlisted approvals tab follows every listed tab, and an unlisted + * stream closes the strip, so leaving either out never hides it; + * - a related tab no entry names (a host that did not filter it) follows + * the listed tabs, in the order passed. + * + * Which related lists exist is the host's: `deriveRelatedLists` drops the + * unlisted side lists. A pure, stable reorder of the tabs already built. + */ +function arrangeDeclaredTabs(declared: readonly unknown[] | undefined, items: any[]): any[] { + if (!Array.isArray(declared) || declared.length === 0) return items; + const [overview, ...tabs] = items; + const names = declared.map((entry) => relatedListEntryName(entry)); + const unlisted = names.length; + const rank = (tab: any): number | null => { + const value = typeof tab?.value === 'string' ? tab.value : ''; + const builtin = (Object.keys(BUILTIN_TAB_VALUES) as RecordPageBuiltinTab[]) + .find((name) => BUILTIN_TAB_VALUES[name] === value); + if (builtin) { + const at = names.indexOf(builtin); + if (at !== -1) return at; + if (builtin === 'sys_attachment') return null; + return builtin === 'sys_activity' ? unlisted + 1 : unlisted; + } + if (value.startsWith('related:')) { + const id = value.slice('related:'.length); + const dot = id.indexOf('.'); + const list = { childObject: id.slice(0, dot), referenceField: id.slice(dot + 1) }; + const at = names.findIndex((name) => name !== undefined && !isRecordPageBuiltinTab(name) && relatedListEntryNames(name, list)); + return at === -1 ? unlisted : at; + } + return unlisted; + }; + const ranked = tabs + .map((tab, index) => ({ tab, index, rank: rank(tab) })) + .filter((entry): entry is { tab: any; index: number; rank: number } => entry.rank !== null) + .sort((a, b) => a.rank - b.rank || a.index - b.index); + return [overview, ...ranked.map((entry) => entry.tab)]; } /** diff --git a/ui/packages/plugin-detail/src/synth/recordPageColumns.ts b/ui/packages/plugin-detail/src/synth/recordPageColumns.ts index 832c10e4090..d1a2f1e5371 100644 --- a/ui/packages/plugin-detail/src/synth/recordPageColumns.ts +++ b/ui/packages/plugin-detail/src/synth/recordPageColumns.ts @@ -233,8 +233,10 @@ export function buildDefaultPageColumns(page: unknown): DefaultPageColumns | nul const details: any[] = []; const timelineTabs: any[] = []; - const relatedLists: any[] = []; - const relatedPanels: any[] = []; + // The related column keeps the tab order (objectstack#35897: an object's + // declared `relatedLists` may place attachments or approvals among its lists; + // undeclared, the tabs already run lists, then attachments, then approvals). + const related: any[] = []; for (const rawItem of items) { const item = asNode(rawItem); if (!item) return null; @@ -244,8 +246,7 @@ 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 if (item.value === 'approvals' || item.value === 'attachments') relatedPanels.push(...children); - else relatedLists.push(...children); + else related.push(...children); } const before = components.slice(0, tabIndex); @@ -254,7 +255,7 @@ export function buildDefaultPageColumns(page: unknown): DefaultPageColumns | nul strip: before.filter(isStripNode), details, timeline: [...components.slice(tabIndex + 1), ...timelineTabs], - related: [...relatedLists, ...relatedPanels], + related, }; }