diff --git a/.changeset/36366-object-action-layout.md b/.changeset/36366-object-action-layout.md new file mode 100644 index 00000000000..eac1a147431 --- /dev/null +++ b/.changeset/36366-object-action-layout.md @@ -0,0 +1,33 @@ +--- +'@objectstack/spec': minor +'@objectstack/objectql': minor +'@objectstack/lint': minor +'@objectstack/metadata-core': patch +'@objectstack/metadata-protocol': patch +'@objectstack/platform-objects': patch +'@object-ui/types': minor +'@object-ui/components': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat: an object arranges its actions per scope (`actionLayout`: pinned buttons and the 「More」 order), and the design mode sets it + +Clause-②: yes (widening) +Metadata-protocol: added +Skills-docs: follow-up #36630 + +A page header draws at most three of its actions as buttons and puts the rest in its 「More」 menu. An object now arranges them itself with the new optional key `actionLayout` on `ObjectSchema` and `ObjectExtensionSchema`: `{ list?: Arm, record?: Arm }`, where `Arm = { pinned: string[], more?: string[] }`. `pinned` names the buttons in the order drawn, at most three (`[]` pins none); `more` orders the 「More」 menu; an action the scope places that neither part names goes to the end of 「More」 in its default order. A pinned action that is hidden leaves its button out, and no other action takes its place. + +- `list` arranges the actions placed at `list_toolbar` and the list page's built-ins `$import` and `$export`. A built-in is only ever pinned: one named in `more` is refused with its reason, since not pinned the list page draws it in its own Import / Export menu. +- `record` arranges the actions placed at `record_header` or `record_more`. It is a scope, not a page: the record page header, the side preview and a phone's bottom action bar all read it. A `page:header` that authors its own `actions` list keeps that list. +- An arm left out (or the key left out) draws that scope exactly as before. + +What each package gains: + +- `@objectstack/spec`: the key and its shape refusals at every door (more than three pinned, a name given twice in one part or in both, a malformed name, a built-in the scope does not have, a built-in in `more`, since a built-in is only ever pinned), each with its reason. New exports `OBJECT_ACTION_LAYOUT_PINNED_LIMIT`, `OBJECT_ACTION_LAYOUT_SCOPES`, `OBJECT_ACTION_LAYOUT_BUILTINS` and the types `ObjectActionLayoutScope`, `ObjectActionLayout`, `ObjectActionLayoutArm`. The object form offers it under Advanced, one JSON row per arm. +- `@objectstack/objectql`: `actionLayout` joins `fieldGroups` and `relatedLists` as a key only the base's paired `.custom` package writes on an `object_extension` (ADR-0146 D10). It is applied last, after every other layer, arm by arm: each arm it writes replaces the served arm for that scope whole, and an arm it leaves out stays. A manifest's `objectExtensions` entry now carries the key to the fold. +- `@objectstack/metadata-protocol`: the one judge refuses `actionLayout` from any other package, naming the action's own `locations` and `order` as the way to place an action the package brings. Each door says it its own way: publish, restore and draft promotion of an `object_extension` answer `VALIDATION_ERROR` / 400; marketplace install refuses the package body with `VALIDATION_ERROR` / 422; `os validate` and `os build` exit non-zero and print the row; the registry fold skips the key and leaves a note. +- `@objectstack/lint`: `validateObjectActionLayout` (`object-action-layout-unknown`, `object-action-layout-not-placed`, at `error`) refuses in `os validate`, `os build` and `os lint` a name, in either part, that is no action of the object or is not placed in the scope its arm arranges. +- `@object-ui/types`: `arrangedHeaderActions(actions, arm, scope)`, the one reader both record headers and the list header apply, and `readActionLayoutArm`. +- The console: both record headers (the default page's and an authored `page:header` with `placedActions: true`) and the list header draw the arrangement. In the design mode, 「Header buttons」 at the end of the page header lists the scope's actions under 「Pinned to header」 and 「Other」 (the 「More」 menu), each dragged into order; a dot moves an action between them, a fourth pin is refused with a toast, the header shows the change at once, and 「Save」 writes only the arms that changed: into the object's own package when it is writable, else into the installed object's customization package as an `object_extension`, through the one writer of an installed object's arrangement (`saveObjectExtensionArrangement`, whose patch type now takes the object-shaped `actionLayout`), which refuses a customization package the server does not list writable. A name the scope no longer offers is listed in the panel as left out. A name the header cannot draw is refused at save with its reason. New `@object-ui/i18n` keys under `designMode.pins`. diff --git a/content/docs/data-modeling/object-extensions.mdx b/content/docs/data-modeling/object-extensions.mdx index e01ed6a4bb4..9e34d7cafa9 100644 --- a/content/docs/data-modeling/object-extensions.mdx +++ b/content/docs/data-modeling/object-extensions.mdx @@ -71,6 +71,7 @@ check that spelling first. | `description` | Same as `label`. | | `place` | **Applied once, after every extension's fields are merged.** Says where the fields, groups and child lists this extension brings go on the target — [below](#placing-what-you-bring). | | `fieldGroups`, `relatedLists` | **Only in a base's paired `.custom` package. Each replaces, whole.** The complete field arrangement and the complete tab list of the target, applied last — [below](#arranging-the-whole-record-page). In any other package they are refused, and `place` is the key to use. | +| `actionLayout` | **Only in a base's paired `.custom` package. Applied arm by arm, last.** Each `list` or `record` arm it writes (`{ pinned, more }`) replaces the arm the target serves for that scope whole; an arm it leaves out stays. In any other package it is refused, and an action the package brings is placed by its own `locations` and `order`. See [choosing the header's buttons](/docs/ui/actions#choose-the-headers-buttons). | | `priority` | Not merged — it *orders* the merge. `0`–`999`, default `200`. | Added fields are ordinary fields, so everything on the @@ -276,7 +277,8 @@ D10). The object is extended, never replaced: - **An object takes no `overrides` declaration.** Declaring one on an object is refused, naming the extension as the route. - **The pair may arrange the whole record page.** Its extension, and no other package's, - writes `fieldGroups` and `relatedLists` — [below](#arranging-the-whole-record-page). + writes `fieldGroups` and `relatedLists` — [below](#arranging-the-whole-record-page) — + and `actionLayout`, the order of the object's actions and which are header buttons. {/* os:check */} ```typescript diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 725c766cf02..43cd68c17fe 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -937,7 +937,7 @@ os compile --json # JSON output for CI pipelines → Normalizing stack definition... → Lowering inline handlers... → Validating protocol compliance... - → Running author-time rules (76)... + → Running author-time rules (77)... → Checking that every required capability has a provider installable in this edition... → Collecting package docs (ADR-0046)... 0 collected → Writing artifact... diff --git a/content/docs/deployment/validating-metadata.mdx b/content/docs/deployment/validating-metadata.mdx index 69a62a824b8..b4e6b0a4fd5 100644 --- a/content/docs/deployment/validating-metadata.mdx +++ b/content/docs/deployment/validating-metadata.mdx @@ -867,7 +867,7 @@ A clean run walks the registry and reports timing: Config: /path/to/support-desk/objectstack.config.ts Load time: 21ms → Validating against ObjectStack Protocol... - → Running author-time rules (76)... + → Running author-time rules (77)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/content/docs/getting-started/build-with-claude-code.mdx b/content/docs/getting-started/build-with-claude-code.mdx index 593d23bfb29..5a253f68c8b 100644 --- a/content/docs/getting-started/build-with-claude-code.mdx +++ b/content/docs/getting-started/build-with-claude-code.mdx @@ -311,7 +311,7 @@ visible: 'status != "resolved"' ◆ Validate ──────────────────────────────────────── → Validating against ObjectStack Protocol... - → Running author-time rules (76)... + → Running author-time rules (77)... ✗ Author-time rules failed (1 issue) • stack · action 'resolve_ticket' visible: bare reference `status` — a diff --git a/content/docs/references/api/metadata.mdx b/content/docs/references/api/metadata.mdx index 54df68fe613..a24ce56c75a 100644 --- a/content/docs/references/api/metadata.mdx +++ b/content/docs/references/api/metadata.mdx @@ -939,6 +939,7 @@ Metadata query with filtering, sorting, and pagination | **description** | `string` | optional | Developer documentation / description | | **icon** | `string` | optional | Icon name (Lucide/Material) for UI representation | | **color** | `Enum<'gray' \| 'blue' \| 'teal' \| 'green' \| 'amber' \| 'orange' \| 'red' \| 'pink' \| 'purple'>` | optional | Object colour, one name from the fixed palette (gray, blue, teal, green, amber, orange, red, pink, purple). The console draws the object's icon as a white glyph on a rounded square of this colour, so one object looks the same wherever its icon appears. No free colour values. Omit to draw the neutral `gray`. | +| **actionLayout** | `{ list?: object; record?: object }` | optional | The order of the object's actions and which are buttons, per action scope (`list`, `record`): `pinned` (at most 3 buttons, in order) and `more` (the 「More」 menu order; unnamed actions follow in their default order). Omit to keep each surface's own choice (each action's `order`). | | **isSystem** | `boolean` | optional (default: `false`) | Is system object (protected from deletion; defaults its org-wide sharing to public when no sharingModel is set — plugin-sharing) | | **managedBy** | `Enum<'platform' \| 'config' \| 'system-data' \| 'engine-owned' \| 'append-only' \| …>` | optional | Lifecycle bucket — platform (user CRUD) \| config (admin authored) \| system-data (platform-defined schema, admin/user-writable data) \| engine-owned (engine owns the lifecycle, no user writes) \| append-only (audit) \| synced (rows copied by a pull from a connector or federated source; read-only to members, and userActions cannot open a write) \| better-auth (identity). UI clients honour the resolved affordance matrix. | | **ownership** | `Enum<'user' \| 'business_unit' \| 'org' \| 'none'>` | optional | Record-ownership model: user (default — injects reassignable owner_id plus owning_business_unit_id) \| business_unit (unit-owned: owning_business_unit_id only, no owner_id) \| org \| none (no per-record owner, neither anchor). Distinct from the package own/extend contribution kind. | diff --git a/content/docs/references/data/object.mdx b/content/docs/references/data/object.mdx index fadc710ceac..8140c219a8a 100644 --- a/content/docs/references/data/object.mdx +++ b/content/docs/references/data/object.mdx @@ -151,6 +151,7 @@ const result = ApiMethod.parse(data); | **description** | `string` | optional | Developer documentation / description | | **icon** | `string` | optional | Icon name (Lucide/Material) for UI representation | | **color** | `Enum<'gray' \| 'blue' \| 'teal' \| 'green' \| 'amber' \| 'orange' \| 'red' \| 'pink' \| 'purple'>` | optional | Object colour, one name from the fixed palette (gray, blue, teal, green, amber, orange, red, pink, purple). The console draws the object's icon as a white glyph on a rounded square of this colour, so one object looks the same wherever its icon appears. No free colour values. Omit to draw the neutral `gray`. | +| **actionLayout** | `{ list?: object; record?: object }` | optional | The order of the object's actions and which are buttons, per action scope (`list`, `record`): `pinned` (at most 3 buttons, in order) and `more` (the 「More」 menu order; unnamed actions follow in their default order). Omit to keep each surface's own choice (each action's `order`). | | **isSystem** | `boolean` | optional (default: `false`) | Is system object (protected from deletion; defaults its org-wide sharing to public when no sharingModel is set — plugin-sharing) | | **managedBy** | `Enum<'platform' \| 'config' \| 'system-data' \| 'engine-owned' \| 'append-only' \| 'synced' \| 'better-auth'>` | optional | Lifecycle bucket — platform (user CRUD) \| config (admin authored) \| system-data (platform-defined schema, admin/user-writable data) \| engine-owned (engine owns the lifecycle, no user writes) \| append-only (audit) \| synced (rows copied by a pull from a connector or federated source; read-only to members, and userActions cannot open a write) \| better-auth (identity). UI clients honour the resolved affordance matrix. | | **ownership** | `Enum<'user' \| 'business_unit' \| 'org' \| 'none'>` | optional | Record-ownership model: user (default — injects reassignable owner_id plus owning_business_unit_id) \| business_unit (unit-owned: owning_business_unit_id only, no owner_id) \| org \| none (no per-record owner, neither anchor). Distinct from the package own/extend contribution kind. | @@ -197,6 +198,13 @@ const result = ApiMethod.parse(data); | **_packageVersion** | `string` | optional | Owning package version. | | **_lockDocsUrl** | `string` | optional | Optional documentation link surfaced next to _lockReason. | +### Nested Shape: `Object.actionLayout` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **list** | `{ pinned: string[]; more?: string[] }` | optional | The list scope's arrangement: actions of the object placed at `list_toolbar`, as drawn on the list page toolbar, and `$import` / `$export` as pinned buttons (not pinned, they stay in the page's own Import / Export menu). Omit to draw it as before. | +| **record** | `{ pinned: string[]; more?: string[] }` | optional | The record scope's arrangement: actions of the object placed at `record_header` or `record_more`, as drawn in the record header (record page, side preview, a phone's bottom bar). Omit to draw it as before. | + ### Nested Shape: `Object.userActions` | Property | Type | Required | Description | @@ -616,6 +624,7 @@ const result = ApiMethod.parse(data); | **label** | `string` | optional | Override label for the extended object | | **pluralLabel** | `string` | optional | Override plural label for the extended object | | **description** | `string` | optional | Override description for the extended object | +| **actionLayout** | `{ list?: object; record?: object }` | optional | The arrangement of the extended object's actions, per scope (`list`, `record`), in the object's own shape. Written only by the object extension of the paired `.custom` package of the App the object belongs to (ADR-0146 D10). An extension in a package that is not a `.custom` package is refused at publish, by `os validate` / `os build` and at install, and the registry merge skips it with a warning; an action that package brings is placed by its own `locations` and `order`. A `.custom` package that is not this object's pair is not applied. Each arm written replaces the arm the object serves for that scope, whole, after every other layer; an arm not written stays as the object gives it, and removing the key, or uninstalling or disabling the package, restores it. | | **validations** | `any[]` | optional | Additional validation rules to merge into the target object | | **indexes** | `{ name?: string; fields: string[]; unique?: false \| 'global' \| 'organization' }[]` | optional | Additional indexes to merge into the target object | | **place** | `({ field: string; group: string; after?: string; before?: string } \| { list: string; after?: string; before?: string; label?: string; … } \| { group: object; after?: string; before?: string })[]` | optional | Where the fields, groups and child lists this extension brings go on the extended object. Each entry is one of: `{ field, group, after \| before }` — a field of this extension's own `fields`, into a field group (the extended object's, or one this extension adds), right after or before a member of that group; `{ group: { key, label, … }, after \| before }` — a field group of this extension's own (its `fields` may name only fields this extension adds, its `relatedList` only a child list of this package), right after or before a group of the extended object; `{ list, after \| before, label?, columns? }` — a child list of this package (a child object of the same package that points at the extended object, or object.field), right after or before a tab of the extended object (a relatedLists entry name, a built-in tab included), with that tab's own title and columns (each column a field of the child, judged as a relatedLists entry's columns are). Write `after` or `before`, or neither for the end. An anchor may be an item another placement brings, whatever order the two are written or registered in. An anchor nobody has puts the item at the end of its group, of the groups, or of the tabs (before the approvals and activity-stream tabs); a group that does not exist puts the field among the ungrouped fields. Nothing is dropped. Several items at one anchor follow ascending `priority`, then package name, so every build gives the same order. Placement arranges what the extended object declares: list placements apply when it declares `relatedLists`, group and field placements when it declares `fieldGroups`. Where it declares none, its automatic arrangement stays as it is and the item still shows there: the list in the automatic tab order, with this entry's `label` and `columns` not applied either (write them on the child's own lookup field as `relatedListTitle` / `relatedListColumns`, which apply on every parent), and the field among the fields in declaration order, its `after` / `before` not applied. The boot log names each placement that did not apply, with the object and the package; `os validate` names it too when the extended object is in the same stack. A child list another package brings shows even when the extended object's `relatedLists` does not name it: placed, at its place; unplaced, at the end of the tabs. An extension places only its own items: a field outside its own `fields` is refused here; a field the extended object declares (an owner field this extension redeclares for its display is still the owner's), a group key the extended object declares, and a list (or a group's `relatedList`) that is not a child object of its package are refused at `defineStack` where the objects are known; the merge skips each of them too, with a warning naming whose item it is. A group key another package's extension already adds is not refused: the merge adds it once and names the second. Applied once, by the registry merge, so the record page, the forms and Studio show one arrangement; uninstalling the package removes its items and leaves the extended object's own order as it was. Example: `place: [{ field: 'tax_id', group: 'basic', after: 'industry' }, { list: 'contract', after: 'opportunity', columns: ['name', 'amount'] }]`. | @@ -724,6 +733,13 @@ const result = ApiMethod.parse(data); | **placeholder** | `string` | optional | Placeholder text rendered inside the empty input (the HTML placeholder attribute); disappears once a value is entered. Distinct from `inlineHelpText` (always-visible help rendered beside/under the input) and `description` (tooltip/developer documentation). | | **options** | `Record` | optional | Display patches of the base field's options, keyed by each option's stored `value` (which stays the vendor's); each entry takes the option display keys of BASE_FIELD_DISPLAY_WHITELIST. | +### Nested Shape: `ObjectExtension.actionLayout` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **list** | `{ pinned: string[]; more?: string[] }` | optional | The list scope's arrangement: actions of the object placed at `list_toolbar`, as drawn on the list page toolbar, and `$import` / `$export` as pinned buttons (not pinned, they stay in the page's own Import / Export menu). Omit to draw it as before. | +| **record** | `{ pinned: string[]; more?: string[] }` | optional | The record scope's arrangement: actions of the object placed at `record_header` or `record_more`, as drawn in the record header (record page, side preview, a phone's bottom bar). Omit to draw it as before. | + ### Nested Shape: `ObjectExtension.indexes[number]` | Property | Type | Required | Description | diff --git a/content/docs/references/system/migration.mdx b/content/docs/references/system/migration.mdx index 7a984376b87..281772c5173 100644 --- a/content/docs/references/system/migration.mdx +++ b/content/docs/references/system/migration.mdx @@ -333,6 +333,7 @@ Create a new object | **description** | `string` | optional | Developer documentation / description | | **icon** | `string` | optional | Icon name (Lucide/Material) for UI representation | | **color** | `Enum<'gray' \| 'blue' \| 'teal' \| 'green' \| 'amber' \| 'orange' \| 'red' \| 'pink' \| 'purple'>` | optional | Object colour, one name from the fixed palette (gray, blue, teal, green, amber, orange, red, pink, purple). The console draws the object's icon as a white glyph on a rounded square of this colour, so one object looks the same wherever its icon appears. No free colour values. Omit to draw the neutral `gray`. | +| **actionLayout** | `{ list?: object; record?: object }` | optional | The order of the object's actions and which are buttons, per action scope (`list`, `record`): `pinned` (at most 3 buttons, in order) and `more` (the 「More」 menu order; unnamed actions follow in their default order). Omit to keep each surface's own choice (each action's `order`). | | **isSystem** | `boolean` | optional (default: `false`) | Is system object (protected from deletion; defaults its org-wide sharing to public when no sharingModel is set — plugin-sharing) | | **managedBy** | `Enum<'platform' \| 'config' \| 'system-data' \| 'engine-owned' \| 'append-only' \| …>` | optional | Lifecycle bucket — platform (user CRUD) \| config (admin authored) \| system-data (platform-defined schema, admin/user-writable data) \| engine-owned (engine owns the lifecycle, no user writes) \| append-only (audit) \| synced (rows copied by a pull from a connector or federated source; read-only to members, and userActions cannot open a write) \| better-auth (identity). UI clients honour the resolved affordance matrix. | | **ownership** | `Enum<'user' \| 'business_unit' \| 'org' \| 'none'>` | optional | Record-ownership model: user (default — injects reassignable owner_id plus owning_business_unit_id) \| business_unit (unit-owned: owning_business_unit_id only, no owner_id) \| org \| none (no per-record owner, neither anchor). Distinct from the package own/extend contribution kind. | @@ -638,6 +639,7 @@ Create a new object | **description** | `string` | optional | Developer documentation / description | | **icon** | `string` | optional | Icon name (Lucide/Material) for UI representation | | **color** | `Enum<'gray' \| 'blue' \| 'teal' \| 'green' \| 'amber' \| 'orange' \| 'red' \| 'pink' \| 'purple'>` | optional | Object colour, one name from the fixed palette (gray, blue, teal, green, amber, orange, red, pink, purple). The console draws the object's icon as a white glyph on a rounded square of this colour, so one object looks the same wherever its icon appears. No free colour values. Omit to draw the neutral `gray`. | +| **actionLayout** | `{ list?: object; record?: object }` | optional | The order of the object's actions and which are buttons, per action scope (`list`, `record`): `pinned` (at most 3 buttons, in order) and `more` (the 「More」 menu order; unnamed actions follow in their default order). Omit to keep each surface's own choice (each action's `order`). | | **isSystem** | `boolean` | optional (default: `false`) | Is system object (protected from deletion; defaults its org-wide sharing to public when no sharingModel is set — plugin-sharing) | | **managedBy** | `Enum<'platform' \| 'config' \| 'system-data' \| 'engine-owned' \| 'append-only' \| …>` | optional | Lifecycle bucket — platform (user CRUD) \| config (admin authored) \| system-data (platform-defined schema, admin/user-writable data) \| engine-owned (engine owns the lifecycle, no user writes) \| append-only (audit) \| synced (rows copied by a pull from a connector or federated source; read-only to members, and userActions cannot open a write) \| better-auth (identity). UI clients honour the resolved affordance matrix. | | **ownership** | `Enum<'user' \| 'business_unit' \| 'org' \| 'none'>` | optional | Record-ownership model: user (default — injects reassignable owner_id plus owning_business_unit_id) \| business_unit (unit-owned: owning_business_unit_id only, no owner_id) \| org \| none (no per-record owner, neither anchor). Distinct from the package own/extend contribution kind. | diff --git a/content/docs/ui/actions.mdx b/content/docs/ui/actions.mdx index 237834068aa..5eabedc2b5a 100644 --- a/content/docs/ui/actions.mdx +++ b/content/docs/ui/actions.mdx @@ -375,6 +375,53 @@ is collected, then the body runs with those values as its `input`. | `record_related` | Each row of a related list inside a parent record — there only, never on the object's own list views (unlike `list_item`). Declared, not yet placed: the console does not draw it on those rows yet | | `record_section` | Named action bars on record pages | +### Choose the header's buttons + +A page header draws at most three of its actions as buttons and puts the rest in its +「More」 menu. By default it picks the first three by each action's `order`. An object +arranges them itself with `actionLayout`, one arm per action scope. Each arm has two +parts: `pinned`, the buttons in the order drawn, and `more`, the order of 「More」: + +```typescript +ObjectSchema.create({ + name: 'crm_opportunity', + // ... + actionLayout: { + // the list scope: actions placed at list_toolbar, drawn on the list page toolbar + list: { pinned: ['mass_assign', '$export'], more: ['send_digest'] }, + // the record scope: actions placed at record_header or record_more + record: { pinned: ['mark_won', 'mark_lost'], more: ['clone', 'share'] }, + }, +}); +``` + +- `pinned` is required in an arm and names at most three; `pinned: []` pins none. + `more` is optional. A name appears once, in one part. +- An action the scope places that neither part names goes to the end of 「More」, in + its default order. A pinned action hidden by its `visible` predicate or its + permissions leaves its button out; no other action takes its place. +- The `record` arm is a scope, not a page: it orders the record header wherever it is + drawn, on the record page, in the side preview and in a phone's bottom action bar. + A record page whose `page:header` authors its own `actions` list keeps that list. +- The list scope can also pin its built-in Import and Export as `$import` and + `$export`. A built-in is only ever pinned: not pinned, the list page draws it in its + own Import / Export menu, as without the key (also with `pinned: []`), so `more` + names actions only. The record scope has no built-ins: New, Edit and Delete keep + their places. +- Leave an arm out (or `actionLayout` out) and that scope draws as before. +- The schema refuses more than three pinned, a name given twice, a malformed name, a + built-in the scope does not have and a built-in in `more`. `os validate`, `os build` and `os lint` also + refuse a name that is no action of the object, or one the scope does not place. +- An administrator sets the same arms in the running app: the app name at the top of + the sidebar, then 「Edit app」 in its menu, then 「Header buttons」 at the end of the + page header. Only the arm changed is saved. For + an installed object it is saved as this environment's customization, the + `object_extension` of the base's paired `.custom` package, whose arm replaces the + object's arm for that scope whole. Only that package writes `actionLayout` on an + extension: any other package's extension is refused it at publish, `os validate`, + `os build` and install, and places the actions it brings by their own `locations` + and `order`. + Surfaces can also reference actions **by name**: ```typescript diff --git a/content/docs/ui/react-pages.mdx b/content/docs/ui/react-pages.mdx index 0204769b764..52418ebaf38 100644 --- a/content/docs/ui/react-pages.mdx +++ b/content/docs/ui/react-pages.mdx @@ -404,7 +404,7 @@ objectstack validate ──────────────────────────────────────── → Loading configuration... → Validating against ObjectStack Protocol... - → Running author-time rules (76)... + → Running author-time rules (77)... → Checking that every required capability has a provider installable in this edition... → Checking package docs (ADR-0046)... diff --git a/packages/cli/src/utils/extension-arrangement.ts b/packages/cli/src/utils/extension-arrangement.ts index 518f3ee3bb7..2097c0d1b9a 100644 --- a/packages/cli/src/utils/extension-arrangement.ts +++ b/packages/cli/src/utils/extension-arrangement.ts @@ -6,9 +6,10 @@ * * The verdict is `@objectstack/metadata-protocol`'s `judgeExtensionArrangement`, * the one the save, restore, publish and install doors ask, so a green - * validate is an artifact those doors admit: `fieldGroups` and `relatedLists` - * on an `objectExtensions` entry only in a base's paired `.custom` package; - * any other package places what it brings with `place`. This module only + * validate is an artifact those doors admit: `fieldGroups`, `relatedLists` + * and `actionLayout` on an `objectExtensions` entry only in a base's paired + * `.custom` package; any other package places what it brings with `place`, + * and its actions by their own `locations` and `order`. This module only * hands it the artifact's packages, the reading * `findExtensionFieldSuffixRefusals` (`./extension-field-suffix.ts`) takes. A * stack naming no package id is not judged, as the judge skips a write bound @@ -25,7 +26,7 @@ export interface ExtensionArrangementRefusalRow { path: string; /** The code the active doors refuse the same key with. */ code: 'VALIDATION_ERROR'; - /** The key as written: `fieldGroups` or `relatedLists`. */ + /** The key as written: `fieldGroups`, `relatedLists` or `actionLayout`. */ key: string; /** The package the extension is declared in. */ packageId: string; diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 47d69056a25..ac06ebf40e8 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -154,6 +154,7 @@ import { validateActionBodyCompiles } from './validate-action-body-compiles.js'; import { validateHookAndJobBodyCompiles } from './validate-hook-body-compiles.js'; import { validateRuleSchemaFormats } from './validate-rule-schema-formats.js'; import { validateActionLocations } from './validate-action-locations.js'; +import { validateObjectActionLayout } from './validate-object-action-layout.js'; import { validateActionObjectBinding } from './validate-action-object-binding.js'; import { validateFlowNodeExecutors } from './validate-flow-node-executors.js'; import { validateInertObjectDeclarations } from './validate-inert-object-declarations.js'; @@ -1897,6 +1898,23 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ surfaceReason: RUNTIME_NEEDS_FULL_SNAPSHOT, run: (stack) => validateActionLocations(stack), }, + // [#36366] An object's action layout (`actionLayout`, and an object + // extension's) naming no action of the object, or one not placed in the + // scope its arm arranges: the name draws nothing. Gating, because the + // author's arrangement is lost without a word otherwise. CLI only: the runtime + // snapshot carries no stack `actions`, so an action bound by `objectName` + // would read as unknown there; the design mode's Save checks the names + // against the served object before it writes. + { + name: 'validateObjectActionLayout', + tier: 'gating', + input: 'parsed', + commands: ALL, + source: 'packages/lint/src/validate-object-action-layout.ts', + surfaces: CLI_ONLY, + surfaceReason: RUNTIME_NEEDS_FULL_SNAPSHOT, + run: (stack) => validateObjectActionLayout(stack), + }, // A standalone action that declares a location but no `objectName` binds to // no object, so the button it declares never renders (every location is an // object's surface). The handler still runs: an object-less action answers diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index 9f7f2367129..354abe4a324 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -711,6 +711,12 @@ export type { ActionNameRefFinding, ActionNameRefSeverity } from './validate-act export { validateActionLocations, ACTION_NO_PLACEMENT } from './validate-action-locations.js'; export type { ActionLocationsFinding, ActionLocationsSeverity } from './validate-action-locations.js'; +export { + validateObjectActionLayout, + OBJECT_ACTION_LAYOUT_UNKNOWN, + OBJECT_ACTION_LAYOUT_NOT_PLACED, +} from './validate-object-action-layout.js'; +export type { ObjectActionLayoutFinding } from './validate-object-action-layout.js'; export { validateActionObjectBinding, ACTION_NO_OBJECT_BINDING } from './validate-action-object-binding.js'; export type { ActionObjectBindingFinding } from './validate-action-object-binding.js'; export { validateFlowNodeExecutors, FLOW_NODE_TYPE_NO_EXECUTOR } from './validate-flow-node-executors.js'; diff --git a/packages/lint/src/validate-object-action-layout.test.ts b/packages/lint/src/validate-object-action-layout.test.ts new file mode 100644 index 00000000000..66945fab9ab --- /dev/null +++ b/packages/lint/src/validate-object-action-layout.test.ts @@ -0,0 +1,92 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36366 — `validateObjectActionLayout`: a name in an action layout + * arm (`pinned` or `more`) that names no action of the object, or one not + * placed in the scope its arm arranges, is refused at `error` with the reason + * named. The object's own layout and an extension's (against the object it + * extends) are judged; an extension of an object the stack does not define, + * and the `$` built-ins, are not. + */ + +import { describe, expect, it } from 'vitest'; +import { + OBJECT_ACTION_LAYOUT_NOT_PLACED, + OBJECT_ACTION_LAYOUT_UNKNOWN, + validateObjectActionLayout, +} from './validate-object-action-layout.js'; +import { AUTHORING_RULES } from './authoring-rules.js'; +import * as barrel from './index.js'; + +const LEAD = { + name: 'crm_lead', + fields: { title: { type: 'text' } }, + actions: [ + { name: 'convert_lead', label: 'Convert', locations: ['record_header'] }, + { name: 'log_call', label: 'Log call', locations: ['record_more'] }, + { name: 'mass_assign', label: 'Assign', locations: ['list_toolbar'] }, + { name: 'headless', label: 'Headless', locations: [] }, + ], +}; + +const stack = (extra: Record = {}, actionLayout?: unknown) => ({ + objects: [{ ...LEAD, ...(actionLayout ? { actionLayout } : {}) }], + actions: [{ name: 'send_email', objectName: 'crm_lead', label: 'Send email', locations: ['record_header', 'list_toolbar'] }], + ...extra, +}); + +const rules = (s: Record) => validateObjectActionLayout(s).map((f) => `${f.rule} ${f.path}`); + +describe('validateObjectActionLayout (objectstack#36366)', () => { + it('passes pins of placed actions, own and stack-bound, and the $ built-ins', () => { + expect(rules(stack({}, { record: { pinned: ['convert_lead', 'log_call'], more: ['send_email'] }, list: { pinned: ['$export', 'mass_assign'], more: ['send_email'] } }))).toEqual([]); + expect(rules(stack())).toEqual([]); + }); + + it('refuses a name no action of the object has, at error, naming it', () => { + const [finding] = validateObjectActionLayout(stack({}, { record: { pinned: ['convert_lead', 'close_lead'] } })); + expect(finding).toMatchObject({ + severity: 'error', + rule: OBJECT_ACTION_LAYOUT_UNKNOWN, + where: 'object "crm_lead"', + path: 'objects[0].actionLayout.record.pinned[1]', + }); + expect(finding.message).toContain('"close_lead"'); + }); + + it('refuses an action of the other scope, or one placed nowhere, in either part', () => { + expect( + rules(stack({}, { list: { pinned: ['convert_lead'] }, record: { pinned: ['mass_assign'], more: ['headless'] } })), + ).toEqual([ + `${OBJECT_ACTION_LAYOUT_NOT_PLACED} objects[0].actionLayout.list.pinned[0]`, + `${OBJECT_ACTION_LAYOUT_NOT_PLACED} objects[0].actionLayout.record.pinned[0]`, + `${OBJECT_ACTION_LAYOUT_NOT_PLACED} objects[0].actionLayout.record.more[0]`, + ]); + }); + + it('refuses an unknown name in `more` too, naming the 「More」 menu', () => { + const [finding] = validateObjectActionLayout(stack({}, { record: { pinned: [], more: ['gone_action'] } })); + expect(finding).toMatchObject({ rule: OBJECT_ACTION_LAYOUT_UNKNOWN, path: 'objects[0].actionLayout.record.more[0]' }); + expect(finding.message).toBe( + '"crm_lead" names "gone_action" for the record header\'s 「More」 menu, and "crm_lead" declares no action of that name, so it draws nothing', + ); + }); + + it('judges an extension against the object it extends, and skips one whose object the stack does not define', () => { + const s = stack({ + objectExtensions: [ + { extend: 'crm_lead', actionLayout: { record: { pinned: ['send_email'], more: ['nope'] } } }, + { extend: 'sys_user', actionLayout: { record: { pinned: ['anything'] } } }, + ], + }); + expect(rules(s)).toEqual([`${OBJECT_ACTION_LAYOUT_UNKNOWN} objectExtensions[0].actionLayout.record.more[0]`]); + }); + + it('is a gating rule on all three commands, CLI only with its reason, and its ids are on the barrel', () => { + const rule = AUTHORING_RULES.find((r) => r.name === 'validateObjectActionLayout'); + expect(rule).toMatchObject({ tier: 'gating', surfaces: ['cli'] }); + expect(rule?.surfaceReason).toMatch(/snapshot/); + expect(barrel.OBJECT_ACTION_LAYOUT_UNKNOWN).toBe('object-action-layout-unknown'); + expect(barrel.OBJECT_ACTION_LAYOUT_NOT_PLACED).toBe('object-action-layout-not-placed'); + }); +}); diff --git a/packages/lint/src/validate-object-action-layout.ts b/packages/lint/src/validate-object-action-layout.ts new file mode 100644 index 00000000000..d9ffc7e36f6 --- /dev/null +++ b/packages/lint/src/validate-object-action-layout.ts @@ -0,0 +1,162 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { recordsOf } from './object-graph.js'; + +/** + * An object's action layout (`actionLayout`, objectstack#36366) naming an + * action its scope cannot draw. + * + * `actionLayout.list` / `.record` arrange one action scope each: `pinned` + * names, in order, the actions drawn as buttons, `more` the order of the + * 「More」 menu. The schema refuses the SHAPE at every door (more than three + * pinned, an entry twice, a malformed entry, a `$` built-in the scope does not + * have). What it cannot see is the REFERENCE: whether a name is an action of + * the object, and whether that action is placed in the scope the arm arranges. + * A name that is not draws nothing, so the author's arrangement is lost + * without a word. This rule refuses it, at `error`, naming the reason: + * + * - `object-action-layout-unknown`: no action of that name is declared on the + * object (its own `actions`, or a stack action whose `objectName` is it); + * - `object-action-layout-not-placed`: the action is declared but not placed + * in that scope: `list_toolbar` for the `list` arm, `record_header` or + * `record_more` for the `record` arm (the record header draws both). A + * record action named in the `list` arm, or the reverse, is this. + * + * Both object positions are judged: an object's own `actionLayout`, and an + * `objectExtensions` entry's, against the object it extends. An extension of + * an object this stack does not define is not judged (its actions are in the + * other package, ADR-0072 D1: no finding the graph cannot back). `$` built-ins + * are the schema's; they are skipped here. + * + * Where it runs: `os validate`, `os build` and `os lint`, where the whole stack + * is visible. The runtime publish gate's per-write snapshot carries objects + * but not the stack's `actions` collection, so there an action bound by + * `objectName` would read as unknown; the design mode's 「Save」 checks the + * names against the object as served (every package's actions) before it + * writes, and a name that reaches the server another way names nothing the + * scope draws, so it draws nothing. + */ + +export const OBJECT_ACTION_LAYOUT_UNKNOWN = 'object-action-layout-unknown'; +export const OBJECT_ACTION_LAYOUT_NOT_PLACED = 'object-action-layout-not-placed'; + +export interface ObjectActionLayoutFinding { + /** Always `error`: the name draws nothing. */ + severity: 'error'; + /** Diagnostic rule id. */ + rule: string; + /** Human-readable location, e.g. `object "crm_lead"`. */ + where: string; + /** Config path, e.g. `objects[0].actionLayout.record.pinned[1]`. */ + path: string; + /** What is wrong. */ + message: string; + /** How to fix it. */ + hint: string; +} + +type AnyRec = Record; + +/** The locations an arm's actions are placed at: the page's header draws an action placed at one of them. */ +const ARM_LOCATIONS: Readonly> = { + list: ['list_toolbar'], + record: ['record_header', 'record_more'], +}; + +function strName(v: unknown): string | undefined { + return typeof v === 'string' && v.length > 0 ? v : undefined; +} + +/** The object's declared actions by name: its own `actions`, then the stack's bound to it by `objectName`. */ +function actionsOf(stack: AnyRec, object: AnyRec, objectName: string): Map { + const out = new Map(); + for (const action of recordsOf(object.actions)) { + const name = strName(action.name); + if (name && !out.has(name)) out.set(name, action); + } + for (const action of recordsOf(stack.actions)) { + const name = strName(action.name); + if (name && action.objectName === objectName && !out.has(name)) out.set(name, action); + } + return out; +} + +/** + * Refuse every name in an arm (`pinned` or `more`) that names no action of + * the object, or one not placed in the scope its arm arranges. Returns findings (empty = clean). + */ +export function validateObjectActionLayout(stack: AnyRec): ObjectActionLayoutFinding[] { + const findings: ObjectActionLayoutFinding[] = []; + if (!stack || typeof stack !== 'object') return findings; + + const objects = recordsOf(stack.objects); + const byName = new Map(); + for (const object of objects) { + const name = strName(object.name); + if (name && !byName.has(name)) byName.set(name, object); + } + + const judge = (layout: unknown, objectName: string, object: AnyRec, at: string, where: string): void => { + if (!layout || typeof layout !== 'object' || Array.isArray(layout)) return; + const actions = actionsOf(stack, object, objectName); + for (const arm of ['list', 'record'] as const) { + const value = (layout as AnyRec)[arm]; + if (!value || typeof value !== 'object' || Array.isArray(value)) continue; + const locations = ARM_LOCATIONS[arm]; + const scope = arm === 'list' ? 'list toolbar' : 'record header'; + for (const part of ['pinned', 'more'] as const) { + const names = (value as AnyRec)[part]; + if (!Array.isArray(names)) continue; + const role = part === 'pinned' ? `the ${scope}'s buttons` : `the ${scope}'s 「More」 menu`; + names.forEach((entry, index) => { + const name = strName(entry); + if (!name || name.startsWith('$')) return; + const path = `${at}.actionLayout.${arm}.${part}[${index}]`; + const action = actions.get(name); + if (!action) { + findings.push({ + severity: 'error', + rule: OBJECT_ACTION_LAYOUT_UNKNOWN, + where, + path, + message: `"${objectName}" names "${name}" for ${role}, and "${objectName}" declares no action of that name, so it draws nothing`, + hint: + `Name an action of "${objectName}" (its own actions, or a stack action with objectName: ` + + `'${objectName}'), or remove "${name}" from actionLayout.${arm}.${part}`, + }); + return; + } + const placed = Array.isArray(action.locations) && action.locations.some((l) => locations.includes(l as string)); + if (!placed) { + findings.push({ + severity: 'error', + rule: OBJECT_ACTION_LAYOUT_NOT_PLACED, + where, + path, + message: + `"${objectName}" names "${name}" for ${role}, and that action is not placed in the ${arm} scope ` + + `(locations ${locations.map((l) => `'${l}'`).join(' or ')}), so it draws nothing there`, + hint: + `Add ${locations.map((l) => `'${l}'`).join(' or ')} to the locations of "${name}", or remove it ` + + `from actionLayout.${arm}.${part}`, + }); + } + }); + } + } + }; + + objects.forEach((object, i) => { + const name = strName(object.name); + if (name) judge(object.actionLayout, name, object, `objects[${i}]`, `object "${name}"`); + }); + recordsOf(stack.objectExtensions).forEach((extension, i) => { + const target = strName(extension.extend); + const object = target ? byName.get(target) : undefined; + if (target && object) { + judge(extension.actionLayout, target, object, `objectExtensions[${i}]`, `object extension of "${target}"`); + } + }); + + return findings; +} diff --git a/packages/metadata-core/src/object-schema-fls-references.ts b/packages/metadata-core/src/object-schema-fls-references.ts index b23994b143d..fb594b9048a 100644 --- a/packages/metadata-core/src/object-schema-fls-references.ts +++ b/packages/metadata-core/src/object-schema-fls-references.ts @@ -774,7 +774,7 @@ const LIST_VIEW_NAME_LISTS: Readonly> = { */ export const OBJECT_REFERENCE_POSITIONS: Readonly> = { // Identity and posture — no field names. - name: keep, label: keep, pluralLabel: keep, description: keep, icon: keep, color: keep, isSystem: keep, + name: keep, label: keep, pluralLabel: keep, description: keep, icon: keep, color: keep, actionLayout: keep, isSystem: keep, managedBy: keep, ownership: keep, systemFields: keep, datasource: keep, access: keep, requiredPermissions: keep, fileAccessDelegate: keep, schemaReadDelegate: keep, editMode: keep, enable: keep, sharingModel: keep, externalSharingModel: keep, protection: keep, diff --git a/packages/metadata-protocol/src/protocol-extension-arrangement.test.ts b/packages/metadata-protocol/src/protocol-extension-arrangement.test.ts index 927674e771f..618b8d04854 100644 --- a/packages/metadata-protocol/src/protocol-extension-arrangement.test.ts +++ b/packages/metadata-protocol/src/protocol-extension-arrangement.test.ts @@ -20,6 +20,7 @@ const PARTNER = 'com.acme.partner'; const GROUPS = [{ key: 'basic', label: 'Basics', fields: ['name', 'region__c'] }]; const TABS = ['crm_contact', { list: 'crm_task', hidden: true }]; +const LAYOUT = { record: { pinned: ['convert_lead'], more: ['log_call'] } }; describe('judgeExtensionArrangement — the rule', () => { it('a plain package writing `fieldGroups` is refused once, at the key, prescribing `place`', () => { @@ -53,10 +54,29 @@ describe('judgeExtensionArrangement — the rule', () => { it('CONTROL: the same body in the base\'s paired `.custom` package is admitted', () => { expect(judgeExtensionArrangement({ packageId: PAIR, - objectExtensions: [{ extend: 'crm_lead', fieldGroups: GROUPS, relatedLists: TABS }], + objectExtensions: [{ extend: 'crm_lead', fieldGroups: GROUPS, relatedLists: TABS, actionLayout: LAYOUT }], })).toEqual([]); }); + it('[#36366] `actionLayout` is refused the same way, prescribing the action\'s own `locations` and `order`', () => { + const refusals = judgeExtensionArrangement({ + packageId: PARTNER, + objectExtensions: [{ extend: 'crm_lead', actionLayout: LAYOUT }], + }); + expect(refusals).toHaveLength(1); + expect(refusals[0]).toMatchObject({ + path: 'objectExtensions[0].actionLayout', object: 'crm_lead', key: 'actionLayout', packageId: PARTNER, + }); + expect(refusals[0]!.message).toContain('`.custom`'); + expect(refusals[0]!.message).toContain('`locations` and `order`'); + expect(refusals[0]!.message.length).toBeLessThanOrEqual(500); + const err = extensionArrangementRefusalError(refusals); + expect(err.code).toBe('VALIDATION_ERROR'); + expect(err.status).toBe(400); + // An empty arrangement is an arrangement written: refused too. + expect(judgeExtensionArrangement({ packageId: PARTNER, objectExtensions: [{ extend: 'crm_lead', actionLayout: {} }] })).toHaveLength(1); + }); + it('CONTROL: a plain package that writes neither key, and places with `place`, is admitted', () => { expect(judgeExtensionArrangement({ packageId: PARTNER, @@ -103,8 +123,16 @@ describe('objectExtensionItemRefusal — the save, publish and restore gate asks expect(err?.issues?.map((i) => i.path)).toEqual(['relatedLists']); }); + it('[#36366] …and with `actionLayout`, located at that key', () => { + const err = ask(PARTNER, item({ actionLayout: LAYOUT })); + expect(err?.code).toBe('VALIDATION_ERROR'); + expect(err?.status).toBe(400); + expect(err?.issues?.map((i) => i.path)).toEqual(['actionLayout']); + expect(err?.message).toContain('`locations` and `order`'); + }); + it('CONTROL: the same item written into the paired `.custom` package is admitted', () => { - expect(ask(PAIR, item({ fields: { region__c: { type: 'text' } }, fieldGroups: GROUPS, relatedLists: TABS }))).toBeUndefined(); + expect(ask(PAIR, item({ fields: { region__c: { type: 'text' } }, fieldGroups: GROUPS, relatedLists: TABS, actionLayout: LAYOUT }))).toBeUndefined(); }); it('CONTROL: the plain package\'s item without the keys is admitted', () => { diff --git a/packages/metadata-protocol/src/protocol-extension-arrangement.ts b/packages/metadata-protocol/src/protocol-extension-arrangement.ts index 9c3e1bad6a8..d347533ba14 100644 --- a/packages/metadata-protocol/src/protocol-extension-arrangement.ts +++ b/packages/metadata-protocol/src/protocol-extension-arrangement.ts @@ -6,9 +6,10 @@ * * Maintainer, verbatim: 「软件包字段、子表自定义分三种,原始软件包,继承软件包和环境管理员覆盖, * 继承软件包 我记得已经有一套标准,只能申明插入位置,原始软件包、环境管理员 应该可以申明完整的配置」. - * An object extension carries two keys for it, `fieldGroups` and - * `relatedLists` (`CUSTOM_ARRANGEMENT_KEYS`, `@objectstack/spec/data`), in the - * shape an object declares them in. Which package an extension belongs to is + * An object extension carries the keys for it, `fieldGroups`, + * `relatedLists` and [objectstack#36366] `actionLayout` + * (`CUSTOM_ARRANGEMENT_KEYS`, `@objectstack/spec/data`), in the shape an + * object declares them in. Which package an extension belongs to is * not in its body, so the schema cannot say who wrote them; this module is * the ONE judge and every door calls it, as the `__c` reservation's doors * call theirs (`protocol-extension-field-suffix.ts`): @@ -24,7 +25,8 @@ * In a package that is NOT a base's paired `.custom` * ({@link isCustomizationPackage}, the `__c` judge's predicate), every * arrangement key an `objectExtensions` entry writes is refused, with the - * prescription to place what the package brings with `place`. In a `.custom` + * prescription to place what the package brings with `place` (an action it + * brings, by the action's own `locations` and `order`). In a `.custom` * package nothing is refused. A body bound to no package is not judged: the * rule is about packages, as the `__c` reservation is. * @@ -70,17 +72,19 @@ export interface ExtensionArrangementSubject { const isRecord = (v: unknown): v is Record => v !== null && typeof v === 'object' && !Array.isArray(v); -/** What `place` writes instead, per key. */ -const PLACE_EXAMPLE: Readonly> = Object.freeze({ - fieldGroups: "`place: [{ field: 'tax_id', group: 'basic', after: 'industry' }]`", - relatedLists: "`place: [{ list: 'contract', after: 'opportunity' }]`", +/** What the package writes instead, per key: `place` for fields and lists, the action's own placement for actions. */ +const PRESCRIPTION: Readonly> = Object.freeze({ + fieldGroups: "place what this package brings with `place`, e.g. `place: [{ field: 'tax_id', group: 'basic', after: 'industry' }]`", + relatedLists: "place what this package brings with `place`, e.g. `place: [{ list: 'contract', after: 'opportunity' }]`", + actionLayout: "place an action this package brings by the action's own `locations` and `order`, e.g. " + + "`{ name: 'send_quote', objectName: 'crm_lead', locations: ['record_more'], order: 50 }`", }); /** The sentence. Prescription inside the first 500 characters: a 4xx message crosses the REST boundary capped there. */ function arrangementOutsidePairMessage(key: CustomArrangementKey, object: string, packageId: string): string { return `\`${key}\` in the extension of object '${object}' in package '${packageId}': only the object extension of a ` + 'base\'s paired `.custom` package declares an object\'s whole arrangement (ADR-0146 D10). Remove the key and ' - + `place what this package brings with \`place\`, e.g. ${PLACE_EXAMPLE[key]}.`; + + `${PRESCRIPTION[key]}.`; } /** diff --git a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts index af0c8800ded..935babaf796 100644 --- a/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts +++ b/packages/metadata-protocol/src/protocol.meta-types-degenerate-derivation.test.ts @@ -403,9 +403,11 @@ describe('#17501 — /meta/types serves a real schema for `action`, and moves no // when a record is created. // [#36290] `field` 85 → 86: `fieldHistory`, the field's own switch for // old → new values on the record activity timeline (false turns them off). + // [#36366] `object` 51 → 52: `actionLayout`, the order of the object's + // actions and which are buttons, per action scope (list, record). const CARD_PROPERTY_COUNTS: Record = { agent: 24, app: 24, dashboard: 21, dataset: 17, field: 86, flow: 24, - hook: 24, object: 51, page: 28, position: 14, report: 24, skill: 17, tool: 14, + hook: 24, object: 52, page: 28, position: 14, report: 24, skill: 17, tool: 14, }; it.each(Object.entries(CARD_PROPERTY_COUNTS))( diff --git a/packages/objectql/src/engine-registration.ts b/packages/objectql/src/engine-registration.ts index f89f669b362..e134da62a35 100644 --- a/packages/objectql/src/engine-registration.ts +++ b/packages/objectql/src/engine-registration.ts @@ -141,7 +141,7 @@ export function objectExtensionContribution(ext: any): { definition: { name: string; fields: unknown; fieldPatches: unknown; label: unknown; pluralLabel: unknown; description: unknown; validations: unknown; indexes: unknown; place: unknown; - fieldGroups: unknown; relatedLists: unknown; + fieldGroups: unknown; relatedLists: unknown; actionLayout: unknown; }; priority: number; } { @@ -169,6 +169,9 @@ export function objectExtensionContribution(ext: any): { // package's and names it. fieldGroups: ext.fieldGroups, relatedLists: ext.relatedLists, + // [objectstack#36366] …and the arrangement of its actions, the + // same rule's third key, applied there arm by arm. + actionLayout: ext.actionLayout, }, priority: ext.priority ?? 200, }; diff --git a/packages/objectql/src/protocol-custom-arrangement.test.ts b/packages/objectql/src/protocol-custom-arrangement.test.ts index 53583fdaf57..439c61af387 100644 --- a/packages/objectql/src/protocol-custom-arrangement.test.ts +++ b/packages/objectql/src/protocol-custom-arrangement.test.ts @@ -278,3 +278,36 @@ describe('ADR-0146 D10 — the paired `.custom` package arranges an installed ob expect(on._relatedListsArrangement).toEqual({ packageId: PAIR, hidden: ['crm_note'], unlisted: 'hidden' }); }); }); + +describe('objectstack#36366 — `actionLayout` is the pair\'s third arrangement key, through the protocol', () => { + const PAIR_LAYOUT = { actionLayout: { record: { pinned: ['convert_lead'], more: ['log_call'] } } }; + + it('the pair\'s extension is saved and its arm is served; a non-`.custom` writer is refused at the save door with code and status, and nothing is stored or served', async () => { + const { protocol, stores } = await boot(); + const refused = await outcome(() => saveExtension(protocol, ADDON, { actionLayout: { record: { pinned: ['log_call'] } } })); + expect(refused).toMatchObject({ ok: false, code: 'VALIDATION_ERROR', status: 400, issues: 1 }); + expect((refused as any).message).toContain('`actionLayout`'); + expect((refused as any).message, 'prescribes the action\'s own placement').toContain('`locations` and `order`'); + const rows = Array.from(stores.get('sys_metadata')?.values() ?? []).filter((r) => r.type === 'object_extension' && r.package_id === ADDON); + expect(rows, 'no row was written').toEqual([]); + expect('actionLayout' in (await servedObject(protocol))).toBe(false); + + // CONTROL: the same key in the object's pair is saved and served. + expect(await outcome(() => saveExtension(protocol, PAIR, PAIR_LAYOUT))).toEqual({ ok: true }); + expect((await servedObject(protocol)).actionLayout).toEqual(PAIR_LAYOUT.actionLayout); + }); + + it('a package body\'s `objectExtensions` entry carries the key to the fold: the pair\'s arm is served, another package\'s is not', async () => { + const { engine } = await boot(); + engine.registerApp({ + id: 'com.example.partner', name: 'partner', version: '1.0.0', namespace: 'crm', type: 'app', dependencies: { [BASE]: '^1.0.0' }, + objectExtensions: [{ extend: OBJ, actionLayout: { record: { pinned: ['a_partner'] }, list: { pinned: [] } }, priority: 900 }], + } as any); + expect('actionLayout' in (engine.registry.getObject(OBJ) as object), 'another package\'s arrangement is not applied').toBe(false); + engine.registerApp({ + id: PAIR, name: 'crm-custom', version: '0.1.0', namespace: 'crm_custom', type: 'app', dependencies: { [BASE]: '^1' }, + objectExtensions: [{ extend: OBJ, ...PAIR_LAYOUT }], + } as any); + expect((engine.registry.getObject(OBJ) as any).actionLayout).toEqual(PAIR_LAYOUT.actionLayout); + }); +}); diff --git a/packages/objectql/src/registry-custom-arrangement.ts b/packages/objectql/src/registry-custom-arrangement.ts index 0ce324d8158..67155de2c30 100644 --- a/packages/objectql/src/registry-custom-arrangement.ts +++ b/packages/objectql/src/registry-custom-arrangement.ts @@ -13,7 +13,9 @@ * 3. where the `.custom` extension writes `fieldGroups` or `relatedLists` * (`CUSTOM_ARRANGEMENT_KEYS`), that key REPLACES the result of 1–2, * whole. A key it does not write keeps that result. Nothing is merged - * entry by entry. + * entry by entry. [objectstack#36366] Where it writes `actionLayout`, + * each arm it writes (`list`, `record`) replaces the arm the result of + * 1–2 serves for that scope, whole; an arm it does not write stays. * * What the replacement leaves to the object's own rules: * @@ -62,6 +64,7 @@ */ import { + OBJECT_ACTION_LAYOUT_SCOPES, extensionArrangementKeys, relatedListEntryHidden, relatedListEntryName, @@ -180,7 +183,7 @@ export function applyCustomArrangement( note(writer, key, `declares \`${key}\`, which is not applied: only the object extension of a base's paired \`.custom\` ` + 'package declares the whole arrangement of an object. An extension places the fields, groups and ' + - 'child lists it brings with `place`.'); + 'child lists it brings with `place`, and the actions it brings by their own `locations` and `order`.'); continue; } if (!pairs.includes(packageId)) { @@ -190,8 +193,8 @@ export function applyCustomArrangement( '. Only the paired `.custom` package of the App an object belongs to declares its arrangement.'); continue; } - if (!Array.isArray(writer.body[key])) { - note(writer, key, `declares \`${key}\` that is not a list, so it is not applied.`); + if (key === 'actionLayout' ? !isRecord(writer.body[key]) : !Array.isArray(writer.body[key])) { + note(writer, key, `declares \`${key}\` that is not ${key === 'actionLayout' ? 'an object' : 'a list'}, so it is not applied.`); continue; } admitted.push({ ...writer, packageId }); @@ -310,6 +313,25 @@ export function applyCustomArrangement( }; } + // ── actionLayout ──────────────────────────────────────────────────────── + // [objectstack#36366] Arm by arm: each arm the pair writes replaces the + // arm steps 1–2 serve for that scope, whole (`pinned` and `more` + // together); an arm it does not write, or one that is no object, stays. + const layoutWriter = servedWriter('actionLayout'); + if (layoutWriter !== undefined) { + const written = layoutWriter.body.actionLayout as AnyRecord; + const running = isRecord(record.actionLayout) ? record.actionLayout : {}; + let layout: AnyRecord | undefined; + for (const scope of OBJECT_ACTION_LAYOUT_SCOPES) { + const arm = written[scope]; + if (isRecord(arm)) layout = { ...(layout ?? running), [scope]: { ...arm } }; + } + if (layout !== undefined) { + out.actionLayout = layout; + changed = true; + } + } + if (!changed) return { object, notes, relatedLists: undefined }; return { object: out as unknown as ServiceObject, notes, relatedLists }; } diff --git a/packages/objectql/src/registry-extension-action-layout.test.ts b/packages/objectql/src/registry-extension-action-layout.test.ts new file mode 100644 index 00000000000..fbd1542e85c --- /dev/null +++ b/packages/objectql/src/registry-extension-action-layout.test.ts @@ -0,0 +1,139 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36366 — `actionLayout`, the order of an object's actions and + * which are buttons per scope, is one of the paired `.custom` package's + * arrangement keys on an object extension (`CUSTOM_ARRANGEMENT_KEYS`, + * ADR-0146 D10), as `fieldGroups` and `relatedLists` are: + * + * - only the object's own pair is applied, by role, never by `priority` or + * fold order (ADR-0146 D2); any other package's `actionLayout` is skipped + * and named (the doors refuse it before it gets here); + * - it is applied LAST (`applyCustomArrangement`), arm by arm: each arm the + * pair writes replaces the arm the object serves for that scope, whole + * (`pinned` and `more` together), and an arm it does not write stays as + * the owner, or a tenant base, gives it. + */ + +import { afterEach, describe, it, expect, vi } from 'vitest'; +import { SchemaRegistry } from './registry.js'; + +const BASE = 'com.acme.crm'; +const PAIR = 'com.acme.crm.custom'; +const PARTNER = 'com.partner.crm-ext'; +const OTHER_PAIR = 'com.partner.crm-ext.custom'; + +const LEAD = { + name: 'crm_lead', + label: 'Lead', + fields: { title: { name: 'title', type: 'text', label: 'Title' } }, +}; + +const clone = (v: T): T => JSON.parse(JSON.stringify(v)) as T; + +function registry(base: Record = LEAD): SchemaRegistry { + const r = new SchemaRegistry({ multiTenant: false }); + r.logLevel = 'silent'; + r.registerObject(clone(base) as never, BASE, undefined, 'own'); + return r; +} + +const layout = (r: SchemaRegistry) => (r.getObject('crm_lead') as unknown as Record).actionLayout; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe('#36366 — the paired `.custom` extension arranges the object\'s actions', () => { + it('the pair\'s arm is served where the base arranges nothing', () => { + const r = registry(); + r.registerObjectExtension({ extend: 'crm_lead', actionLayout: { record: { pinned: ['convert_lead', 'log_call'] } } }, PAIR); + expect(layout(r)).toEqual({ record: { pinned: ['convert_lead', 'log_call'] } }); + }); + + it('arm by arm: the arm the pair writes replaces the base\'s, the arm it leaves out stays', () => { + const r = registry({ ...LEAD, actionLayout: { list: { pinned: ['$export'] }, record: { pinned: ['log_call'] } } }); + r.registerObjectExtension({ extend: 'crm_lead', actionLayout: { record: { pinned: ['convert_lead'] } } }, PAIR); + expect(layout(r)).toEqual({ list: { pinned: ['$export'] }, record: { pinned: ['convert_lead'] } }); + }); + + it('an arm is replaced whole: the base\'s `more` does not survive a pair arm that leaves it out', () => { + const r = registry({ ...LEAD, actionLayout: { record: { pinned: ['log_call'], more: ['clone_lead', 'send_email'] } } }); + r.registerObjectExtension({ extend: 'crm_lead', actionLayout: { record: { pinned: ['convert_lead'] } } }, PAIR); + expect(layout(r)).toEqual({ record: { pinned: ['convert_lead'] } }); + }); + + it('an empty `pinned` is an arrangement too: no action of that scope is a button', () => { + const r = registry({ ...LEAD, actionLayout: { record: { pinned: ['log_call'] } } }); + r.registerObjectExtension({ extend: 'crm_lead', actionLayout: { record: { pinned: [] } } }, PAIR); + expect(layout(r)).toEqual({ record: { pinned: [] } }); + }); + + it('M1: another package\'s `actionLayout` is not applied, whatever its priority; the pair\'s is, and the skip is named', () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const r = registry(); + r.registerObjectExtension({ extend: 'crm_lead', actionLayout: { record: { pinned: ['a_partner'] } }, priority: 250 }, PARTNER); + r.registerObjectExtension({ extend: 'crm_lead', actionLayout: { record: { pinned: ['a_custom'] } }, priority: 150 }, PAIR); + expect(layout(r)).toEqual({ record: { pinned: ['a_custom'] } }); + const lines = warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('is not applied')); + expect(lines.some((l) => l.includes(`from package "${PARTNER}"`) && l.includes('`actionLayout`'))).toBe(true); + }); + + it('M1: at the same default priority, a package registered after the pair does not win', () => { + const r = registry(); + r.registerObjectExtension({ extend: 'crm_lead', actionLayout: { record: { pinned: ['a_custom'] } } }, PAIR); + r.registerObjectExtension({ extend: 'crm_lead', actionLayout: { record: { pinned: ['a_partner'] } } }, PARTNER); + expect(layout(r)).toEqual({ record: { pinned: ['a_custom'] } }); + }); + + it('M1: alone, another package\'s `actionLayout` changes nothing, nor does a `.custom` package that is not the object\'s pair', () => { + for (const pkg of [PARTNER, OTHER_PAIR]) { + const r = registry({ ...LEAD, actionLayout: { record: { pinned: ['log_call'] } } }); + r.registerObjectExtension({ extend: 'crm_lead', actionLayout: { record: { pinned: ['a_other'] }, list: { pinned: [] } } }, pkg); + expect(layout(r), pkg).toEqual({ record: { pinned: ['log_call'] } }); + } + }); + + it('S2: a tenant base that arranged one scope keeps it, and the pair\'s other arm still applies', () => { + const r = registry(); + r.registerObject({ ...clone(LEAD), actionLayout: { list: { pinned: ['$import'] } }, _provenance: 'org' } as never, BASE, undefined, 'overlay'); + r.registerObjectExtension({ extend: 'crm_lead', actionLayout: { record: { pinned: ['convert_lead'] } } }, PAIR); + expect(layout(r)).toEqual({ list: { pinned: ['$import'] }, record: { pinned: ['convert_lead'] } }); + }); + + it('S2: where the pair and a tenant base arrange the same scope, the pair\'s arm is served (applied last, by role)', () => { + const r = registry(); + r.registerObject({ ...clone(LEAD), actionLayout: { record: { pinned: ['send_email'] } }, _provenance: 'org' } as never, BASE, undefined, 'overlay'); + r.registerObjectExtension({ extend: 'crm_lead', actionLayout: { record: { pinned: ['convert_lead'] } } }, PAIR); + expect(layout(r)).toEqual({ record: { pinned: ['convert_lead'] } }); + }); + + it('N2: a pair `actionLayout` that is no object, or an arm that is no object, is not applied', () => { + const r = registry({ ...LEAD, actionLayout: { record: { pinned: ['log_call'] } } }); + r.registerObjectExtension({ extend: 'crm_lead', actionLayout: [{ pinned: ['a_bad'] }] } as never, PAIR); + expect(layout(r)).toEqual({ record: { pinned: ['log_call'] } }); + const empty = registry({ ...LEAD, actionLayout: { record: { pinned: ['log_call'] } } }); + empty.registerObjectExtension({ extend: 'crm_lead', actionLayout: { record: 'log_call' } } as never, PAIR); + expect(layout(empty)).toEqual({ record: { pinned: ['log_call'] } }); + }); + + it('the packaged base keeps its own arrangement', () => { + const r = registry({ ...LEAD, actionLayout: { record: { pinned: ['log_call'] } } }); + r.registerObjectExtension({ extend: 'crm_lead', actionLayout: { record: { pinned: ['convert_lead'] } } }, PAIR); + expect((r.getPackagedObjectBase('crm_lead') as unknown as Record).actionLayout).toEqual({ record: { pinned: ['log_call'] } }); + }); + + it('is idempotent over an already-folded base', () => { + const r = registry({ ...LEAD, actionLayout: { list: { pinned: ['$import'] } } }); + r.registerObjectExtension({ extend: 'crm_lead', actionLayout: { record: { pinned: ['convert_lead'] } } }, PAIR); + const once = r.getObject('crm_lead') as unknown as Record; + const twice = r.foldObjectExtendersOnto('crm_lead', clone(once) as never) as unknown as Record; + expect(twice.actionLayout).toEqual(once.actionLayout); + }); + + it('control: an object nothing arranges is served without the key', () => { + const r = registry(); + r.registerObjectExtension({ extend: 'crm_lead', label: 'Prospect' }, PAIR); + expect('actionLayout' in (r.getObject('crm_lead') as object)).toBe(false); + }); +}); diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index e942804d510..6ecd528fd52 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -232,7 +232,7 @@ export { * Declarative authors never reach that silence, though: `ObjectExtensionSchema` * (`packages/spec/src/data/object.zod.ts`) is `.strict()` — its shape is * exactly `extend` / `fields` / `fieldPatches` / `label` / `pluralLabel` / - * `description` / `validations` / `indexes` / `place` / `fieldGroups` / `relatedLists` / `priority`, so an `objectExtensions` entry + * `description` / `actionLayout` / `validations` / `indexes` / `place` / `fieldGroups` / `relatedLists` / `priority`, so an `objectExtensions` entry * naming `tenancy`, `permissions`, or any other key outside that list fails * LOUDLY at authoring time with a prescription (#4001; the same rule is * documented at `content/docs/data-modeling/object-extensions.mdx`). This 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 0b6fe9aff23..5fba731bf7a 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 @@ -469,6 +469,18 @@ export const arMetadataForms: NonNullable = { label: "تغيير المالك", helpText: "إجراء تغيير المالك، فرديًا وجماعيًا: التشغيل يعرضه والإيقاف يخفيه. غير مُعيَّن: مُشغَّل، إلا أنه مُوقَف على كائن تفاصيل controlled_by_parent. يُعرض فقط على كائن لسجلاته مالك قابل لإعادة التعيين (ownership بقيمة user أو غير مُعيَّن، بلا managedBy، ليس كائن sys_، وowner_id ليس للقراءة فقط، وعلى كائن خارجي يكون owner_id مُعرَّفًا أو مربوطًا)؛ وتشغيله على أي كائن آخر مرفوض. يتحكم في الإجراء فقط، لا في التعديل العادي لـ owner_id. يُحرَّر كائن {enabled, visibleWhen, disabledWhen} المخزَّن مفتاحًا تلو الآخر؛ اكتب واحدًا في المصدر لتقييد الإجراء بكل سجل." }, + actionLayout: { + label: "ترتيب الإجراءات", + helpText: "ترتيب إجراءات هذا الكائن وأيّها يظهر أزرارًا، لكل نطاق: pinned (3 أزرار على الأكثر، بالترتيب) وmore (ترتيب قائمة «المزيد»؛ والإجراء غير المذكور في أيٍّ منهما يأتي بعدها بترتيبه الافتراضي). عند عدم التعيين: يختار كل سطح أزراره حسب ترتيب الإجراءات كما كان." + }, + "actionLayout.list": { + label: "القائمة", + helpText: "شريط أدوات صفحة القائمة، بالصيغة {\"pinned\": [...], \"more\": [...]}: أسماء الإجراءات الموضوعة في شريط أدوات القائمة؛ $import / $export في pinned فقط. 3 مثبتة على الأكثر. وإن لم تُثبَّت، تظل الصفحة ترسم قائمة الاستيراد / التصدير الخاصة بها. يرفض os validate الاسم الذي ليس إجراءً لهذا الكائن أو غير الموضوع في شريط أدوات القائمة؛ ومثل هذا الاسم لا يرسم شيئًا." + }, + "actionLayout.record": { + label: "السجل", + helpText: "رأس السجل (صفحة السجل، والمعاينة الجانبية، والشريط السفلي في الهاتف)، بالصيغة {\"pinned\": [...], \"more\": [...]}: أسماء الإجراءات الموضوعة في رأس السجل أو في قائمة «المزيد» الخاصة به. 3 مثبتة على الأكثر. يرفض os validate الاسم الذي ليس إجراءً لهذا الكائن أو غير الموضوع في صفحة السجل؛ ومثل هذا الاسم لا يرسم شيئًا." + }, editMode: { label: "وضع التحرير", helpText: "نية تفاعل التحرير لسجلات هذا الكائن. عند الغياب، يختار العارض إعداده الافتراضي. نية عابرة للعارضات، وليست تنسيقًا." 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 bb251b321a5..ce8731878ed 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 @@ -469,6 +469,18 @@ export const deMetadataForms: NonNullable = { label: "Inhaber ändern", helpText: "Die Aktion „Inhaber ändern“, einzeln und als Massenaktion: ein bietet sie an, aus blendet sie aus. Nicht gesetzt: ein, außer aus auf einem controlled_by_parent-Detailobjekt. Nur auf einem Objekt angeboten, dessen Datensätze einen neu zuweisbaren Inhaber haben (ownership user oder nicht gesetzt, kein managedBy, kein sys_-Objekt, owner_id nicht schreibgeschützt und auf einem externen Objekt deklariert oder zugeordnet); das Einschalten auf jedem anderen Objekt wird abgelehnt. Es steuert nur die Aktion, nicht eine einfache Bearbeitung von owner_id. Ein gespeichertes Objekt {enabled, visibleWhen, disabledWhen} wird Schlüssel für Schlüssel bearbeitet; schreiben Sie eines im Quelltext, um die Aktion von jedem Datensatz abhängig zu machen." }, + actionLayout: { + label: "Aktionsanordnung", + helpText: "Die Reihenfolge der Aktionen dieses Objekts und welche davon Schaltflächen sind, je Bereich: pinned (höchstens 3 Schaltflächen, in Reihenfolge) und more (die Reihenfolge des Menüs „Mehr“; eine in keinem von beiden genannte Aktion folgt in ihrer Standardreihenfolge). Nicht gesetzt: Jede Oberfläche wählt ihre Schaltflächen wie bisher nach der Reihenfolge der Aktionen." + }, + "actionLayout.list": { + label: "Liste", + helpText: "Die Symbolleiste der Listenseite, als {\"pinned\": [...], \"more\": [...]}: Namen von Aktionen in der Listen-Symbolleiste; $import / $export nur in pinned. Höchstens 3 angeheftet. Nicht angeheftet zeigt die Seite weiterhin ihr eigenes Import-/Export-Menü. os validate lehnt einen Namen ab, der keine Aktion dieses Objekts ist oder nicht in der Listen-Symbolleiste platziert ist; ein solcher Name zeichnet nichts." + }, + "actionLayout.record": { + label: "Datensatz", + helpText: "Die Datensatzkopfzeile (Datensatzseite, Seitenvorschau, Leiste unten auf dem Telefon), als {\"pinned\": [...], \"more\": [...]}: Namen von Aktionen in der Datensatzkopfzeile oder ihrem Menü „Mehr“. Höchstens 3 angeheftet. os validate lehnt einen Namen ab, der keine Aktion dieses Objekts ist oder nicht auf der Datensatzseite platziert ist; ein solcher Name zeichnet nichts." + }, editMode: { label: "Bearbeitungsmodus", helpText: "Absicht der Bearbeitungsinteraktion für Datensätze dieses Objekts. Fehlt sie, wählt der Renderer seinen eigenen Standard. Rendererübergreifende Absicht, keine Gestaltung." 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 bbe344b61b6..70a79b3ef83 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 @@ -469,6 +469,18 @@ export const enMetadataForms: NonNullable = { label: "Change Owner", helpText: "The Change Owner action, single and bulk: on offers it, off hides it. Unset: on, except off on a controlled_by_parent detail. Offered only on an object whose records have a reassignable owner (ownership user or unset, no managedBy, not a sys_ object, owner_id not readonly and, on an external object, declared or mapped); turning it on anywhere else is refused. It gates the action only, not a plain edit of owner_id. A stored {enabled, visibleWhen, disabledWhen} object is edited key by key; write one in source to gate the action on each record." }, + actionLayout: { + label: "Action Layout", + helpText: "The order of this object's actions and which are buttons, per scope: pinned (at most 3 buttons, in order) and more (the More menu's order; an action named in neither follows in its default order). Unset: each surface picks its buttons by the actions' order, as before." + }, + "actionLayout.list": { + label: "List", + helpText: "The list page toolbar, as {\"pinned\": [...], \"more\": [...]}: action names placed on the list toolbar; $import / $export only in pinned. At most 3 pinned. Not pinned, the page still draws its own Import / Export menu. os validate refuses a name that is no action of this object or is not placed on the list toolbar; such a name draws nothing." + }, + "actionLayout.record": { + label: "Record", + helpText: "The record header (record page, side preview, phone bar), as {\"pinned\": [...], \"more\": [...]}: action names placed in the record header or its More menu. At most 3 pinned. os validate refuses a name that is no action of this object or is not placed on the record page; such a name draws nothing." + }, editMode: { label: "Edit Mode", helpText: "Edit-interaction intent for records of this object. Absent, the renderer picks its own default. Cross-renderer intent, not styling." 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 2e5ae885f07..bea8879d92b 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 @@ -469,6 +469,18 @@ export const esESMetadataForms: NonNullable = label: "Cambiar propietario", helpText: "La acción Cambiar propietario, individual y masiva: activada la ofrece, desactivada la oculta. Sin definir: activada, salvo desactivada en un objeto de detalle controlled_by_parent. Solo se ofrece en un objeto cuyos registros tienen un propietario reasignable (ownership user o sin definir, sin managedBy, no es un objeto sys_, owner_id no es de solo lectura y, en un objeto externo, está declarado o mapeado); activarla en cualquier otro objeto se rechaza. Solo controla la acción, no una edición directa de owner_id. Un objeto {enabled, visibleWhen, disabledWhen} almacenado se edita clave por clave; escriba uno en el código fuente para condicionar la acción a cada registro." }, + actionLayout: { + label: "Disposición de acciones", + helpText: "El orden de las acciones de este objeto y cuáles son botones, por ámbito: pinned (como máximo 3 botones, en orden) y more (el orden del menú Más; una acción que no aparece en ninguno sigue en su orden predeterminado). Sin definir: cada superficie elige sus botones por el orden de las acciones, como antes." + }, + "actionLayout.list": { + label: "Lista", + helpText: "La barra de herramientas de la página de lista, como {\"pinned\": [...], \"more\": [...]}: nombres de acciones colocadas en la barra de la lista; $import / $export solo en pinned. Como máximo 3 fijadas. Sin fijar, la página sigue mostrando su propio menú Importar / Exportar. os validate rechaza un nombre que no es una acción de este objeto o que no está en la barra de la lista; ese nombre no dibuja nada." + }, + "actionLayout.record": { + label: "Registro", + helpText: "El encabezado del registro (página del registro, vista previa lateral, barra inferior del teléfono), como {\"pinned\": [...], \"more\": [...]}: nombres de acciones colocadas en el encabezado del registro o en su menú Más. Como máximo 3 fijadas. os validate rechaza un nombre que no es una acción de este objeto o que no está en la página del registro; ese nombre no dibuja nada." + }, editMode: { label: "Modo de edición", helpText: "Intención de interacción al editar registros de este objeto. Si se omite, el renderizador elige su propio valor predeterminado. Es una intención entre renderizadores, no un estilo." 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 61415dc3b2e..934f99206cf 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 @@ -469,6 +469,18 @@ export const frMetadataForms: NonNullable = { label: "Changer de propriétaire", helpText: "L’action Changer de propriétaire, unitaire et en masse : activée, elle est proposée ; désactivée, elle est masquée. Non défini : activée, sauf désactivée sur un objet de détail controlled_by_parent. Proposée uniquement sur un objet dont les enregistrements ont un propriétaire réattribuable (ownership user ou non défini, sans managedBy, pas un objet sys_, owner_id non en lecture seule et, sur un objet externe, déclaré ou mappé) ; l’activer sur tout autre objet est refusé. Elle ne contrôle que l’action, pas une simple modification de owner_id. Un objet {enabled, visibleWhen, disabledWhen} enregistré se modifie clé par clé ; écrivez-en un dans le source pour conditionner l’action à chaque enregistrement." }, + actionLayout: { + label: "Disposition des actions", + helpText: "L’ordre des actions de cet objet et celles qui sont des boutons, par portée : pinned (au plus 3 boutons, dans l’ordre) et more (l’ordre du menu Plus ; une action nommée dans aucun des deux suit dans son ordre par défaut). Non défini : chaque surface choisit ses boutons selon l’ordre des actions, comme avant." + }, + "actionLayout.list": { + label: "Liste", + helpText: "La barre d’outils de la page de liste, sous la forme {\"pinned\": [...], \"more\": [...]} : noms d’actions placées dans la barre de la liste ; $import / $export seulement dans pinned. Au plus 3 épinglées. Non épinglés, la page affiche toujours son propre menu Importer / Exporter. os validate refuse un nom qui n’est pas une action de cet objet ou qui n’est pas placé dans la barre de la liste ; un tel nom n’affiche rien." + }, + "actionLayout.record": { + label: "Enregistrement", + helpText: "L’en-tête de l’enregistrement (page de l’enregistrement, aperçu latéral, barre du bas sur téléphone), sous la forme {\"pinned\": [...], \"more\": [...]} : noms d’actions placées dans l’en-tête de l’enregistrement ou son menu Plus. Au plus 3 épinglées. os validate refuse un nom qui n’est pas une action de cet objet ou qui n’est pas placé sur la page de l’enregistrement ; un tel nom n’affiche rien." + }, editMode: { label: "Mode de modification", helpText: "Intention d’interaction de modification pour les enregistrements de cet objet. En l’absence de valeur, le moteur de rendu choisit sa propre valeur par défaut. Intention commune à tous les moteurs de rendu, et non un style." 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 e21fe7c39c9..a0730cc8b03 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 @@ -469,6 +469,18 @@ export const jaJPMetadataForms: NonNullable = label: "所有者の変更", helpText: "所有者の変更アクション(単一および一括)。オンで提供、オフで非表示。未設定の場合はオンですが、controlled_by_parent の詳細オブジェクトではオフです。レコードに再割り当て可能な所有者があるオブジェクト(ownership が user または未設定、managedBy なし、sys_ オブジェクトでない、owner_id が読み取り専用でなく、外部オブジェクトでは宣言またはマッピングされている)でのみ提供されます。それ以外のオブジェクトでオンにすると拒否されます。制御するのはアクションのみで、owner_id の通常の編集は対象外です。保存済みの {enabled, visibleWhen, disabledWhen} オブジェクトはキーごとに編集されます。各レコードでアクションを制御するにはソースに記述してください。" }, + actionLayout: { + label: "アクションの配置", + helpText: "このオブジェクトのアクションの順序と、どれをボタンにするかをスコープごとに指定します:pinned(ボタン最大 3 個、表示順)と more(「その他」メニューの順序。どちらにも書かれていないアクションは既定の順序で後ろに続きます)。未設定の場合、各画面は従来どおりアクションの order でボタンを選びます。" + }, + "actionLayout.list": { + label: "リスト", + helpText: "リストページのツールバー。{\"pinned\": [...], \"more\": [...]} の形で書きます:リストのツールバーに配置されたアクション名。$import / $export は pinned にのみ書けます。固定は最大 3 個。固定しない場合も、ページは独自のインポート / エクスポートメニューを表示します。os validate は、このオブジェクトのアクションでない名前やリストのツールバーに配置されていない名前を拒否します。そのような名前は何も表示しません。" + }, + "actionLayout.record": { + label: "レコード", + helpText: "レコードヘッダー(レコードページ、サイドプレビュー、スマートフォンの下部バー)。{\"pinned\": [...], \"more\": [...]} の形で書きます:レコードヘッダーまたはその「その他」メニューに配置されたアクション名。固定は最大 3 個。os validate は、このオブジェクトのアクションでない名前やレコードページに配置されていない名前を拒否します。そのような名前は何も表示しません。" + }, editMode: { label: "編集の開き方", helpText: "このオブジェクトのレコードを編集するときの操作意図。未設定ならレンダラー側の既定に従います。スタイルではなく、レンダラー横断の意図表明です。" 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 ca02b246e7b..2ab94a14e85 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 @@ -469,6 +469,18 @@ export const koMetadataForms: NonNullable = { label: "소유자 변경", helpText: "소유자 변경 작업(단건 및 일괄): 켜면 제공하고 끄면 숨깁니다. 설정하지 않으면 켜짐이며, controlled_by_parent 상세 개체에서는 꺼짐입니다. 레코드에 재할당 가능한 소유자가 있는 개체(ownership이 user이거나 미설정, managedBy 없음, sys_ 개체 아님, owner_id가 읽기 전용 아님, 외부 개체에서는 owner_id가 선언되거나 매핑됨)에서만 제공됩니다. 다른 개체에서 켜면 거부됩니다. 작업만 제어하며 owner_id의 일반 편집에는 영향을 주지 않습니다. 저장된 {enabled, visibleWhen, disabledWhen} 개체는 키별로 편집됩니다. 레코드마다 작업을 제어하려면 소스에 작성하세요." }, + actionLayout: { + label: "작업 배치", + helpText: "이 객체 작업의 순서와 버튼으로 표시할 작업을 범위별로 지정합니다: pinned(버튼 최대 3개, 순서대로)와 more(「더 보기」 메뉴의 순서. 둘 다에 없는 작업은 기본 순서로 뒤에 이어집니다). 설정하지 않으면 각 화면이 이전처럼 작업의 order로 버튼을 고릅니다." + }, + "actionLayout.list": { + label: "목록", + helpText: "목록 페이지 도구 모음, {\"pinned\": [...], \"more\": [...]} 형식: 목록 도구 모음에 배치된 작업 이름; $import / $export는 pinned에만 씁니다. 고정은 최대 3개. 고정하지 않아도 페이지는 자체 가져오기 / 내보내기 메뉴를 표시합니다. os validate는 이 객체의 작업이 아니거나 목록 도구 모음에 배치되지 않은 이름을 거부하며, 그런 이름은 아무것도 표시하지 않습니다." + }, + "actionLayout.record": { + label: "레코드", + helpText: "레코드 헤더(레코드 페이지, 측면 미리보기, 휴대폰 하단 바), {\"pinned\": [...], \"more\": [...]} 형식: 레코드 헤더나 그 「더 보기」 메뉴에 배치된 작업 이름. 고정은 최대 3개. os validate는 이 객체의 작업이 아니거나 레코드 페이지에 배치되지 않은 이름을 거부하며, 그런 이름은 아무것도 표시하지 않습니다." + }, editMode: { label: "편집 모드", helpText: "이 객체 레코드의 편집 상호 작용 의도입니다. 없으면 렌더러가 자체 기본값을 고릅니다. 스타일이 아니라 렌더러 간 공통 의도입니다." diff --git a/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts index a6d0b7ed1fa..11d0df87f38 100644 --- a/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-collapsed-sections-echo-decisions.test.ts @@ -963,10 +963,14 @@ describe('#19403 round 8 — the population, DERIVED from the form and a shape', // 119 since that card's L2 (S1) gave the `enable.fieldHistory` row a help // text saying what an unset switch means — one leaf, authored in every // locale. `capabilities` reads 12 → 13. - expect(PANEL_LEAVES.length).toBe(119); + // 125 since #36366 gave `advanced` the `actionLayout` composite (the + // action arrangement per scope) and its `list` / `record` rows — a label + // and a help text each, three rows and six leaves, all translated leaves + // authored by that card. `advanced` reads 106 → 112. + expect(PANEL_LEAVES.length).toBe(125); expect(PANEL_LEAVES.every((l) => l.prop === 'label' || l.prop === 'helpText')).toBe(true); expect(PANEL_LEAVES.filter((l) => l.section === 'capabilities').length).toBe(13); - expect(PANEL_LEAVES.filter((l) => l.section === 'advanced').length).toBe(106); + expect(PANEL_LEAVES.filter((l) => l.section === 'advanced').length).toBe(112); }); it('⭐ DARK, OUTWARD — the open sections are excluded, and `fields.placeholder` is the one that proves it', () => { diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index 0e0fab84379..2c60296e973 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1310,7 +1310,10 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // 760 since #36425: the field form offers the `showOnCreate` row (ask // for the field when a record is created) — one row label, authored in // all three locales. - expect(translated.length, `${locale} positive control`).toBe(760); + // 763 since #36366: `advanced` offers the `actionLayout` composite and + // its `list` / `record` rows — three row labels, authored in all three + // locales. + expect(translated.length, `${locale} positive control`).toBe(763); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index e14015c2477..2c8338af6d4 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 @@ -469,6 +469,18 @@ export const ptBRMetadataForms: NonNullable = label: "Alterar proprietário", helpText: "A ação Alterar proprietário, individual e em massa: ativada, é oferecida; desativada, fica oculta. Não definida: ativada, exceto desativada em um objeto de detalhe controlled_by_parent. Oferecida apenas em um objeto cujos registros têm um proprietário reatribuível (ownership user ou não definido, sem managedBy, não é um objeto sys_, owner_id não é somente leitura e, em um objeto externo, está declarado ou mapeado); ativá-la em qualquer outro objeto é recusado. Controla apenas a ação, não uma edição simples de owner_id. Um objeto {enabled, visibleWhen, disabledWhen} armazenado é editado chave por chave; escreva um no código-fonte para condicionar a ação a cada registro." }, + actionLayout: { + label: "Disposição das ações", + helpText: "A ordem das ações deste objeto e quais são botões, por escopo: pinned (no máximo 3 botões, em ordem) e more (a ordem do menu Mais; uma ação não nomeada em nenhum dos dois segue na sua ordem padrão). Sem definir: cada superfície escolhe seus botões pela ordem das ações, como antes." + }, + "actionLayout.list": { + label: "Lista", + helpText: "A barra de ferramentas da página de lista, como {\"pinned\": [...], \"more\": [...]}: nomes de ações colocadas na barra da lista; $import / $export apenas em pinned. No máximo 3 fixadas. Sem fixar, a página ainda mostra seu próprio menu Importar / Exportar. O os validate recusa um nome que não é uma ação deste objeto ou que não está na barra da lista; esse nome não desenha nada." + }, + "actionLayout.record": { + label: "Registro", + helpText: "O cabeçalho do registro (página do registro, pré-visualização lateral, barra inferior do celular), como {\"pinned\": [...], \"more\": [...]}: nomes de ações colocadas no cabeçalho do registro ou no seu menu Mais. No máximo 3 fixadas. O os validate recusa um nome que não é uma ação deste objeto ou que não está na página do registro; esse nome não desenha nada." + }, editMode: { label: "Modo de edição", helpText: "Intenção de interação de edição para os registros deste objeto. Ausente, o renderizador escolhe seu próprio padrão. Intenção entre renderizadores, não estilo." 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 e91861f9699..8bcf4a45f16 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 @@ -469,6 +469,18 @@ export const ruMetadataForms: NonNullable = { label: "Сменить владельца", helpText: "Действие «Сменить владельца», одиночное и массовое: включено — предлагается, выключено — скрыто. Не задано: включено, кроме объекта-детали controlled_by_parent, где выключено. Предлагается только на объекте, у записей которого есть переназначаемый владелец (ownership user или не задано, без managedBy, не объект sys_, owner_id не только для чтения, а на внешнем объекте объявлен или сопоставлен); включение на любом другом объекте отклоняется. Управляет только действием, а не обычным изменением owner_id. Сохранённый объект {enabled, visibleWhen, disabledWhen} редактируется по ключам; задайте его в исходном коде, чтобы управлять действием для каждой записи." }, + actionLayout: { + label: "Расположение действий", + helpText: "Порядок действий этого объекта и какие из них показаны кнопками, по области: pinned (не более 3 кнопок, по порядку) и more (порядок меню «Ещё»; действие, не названное ни там, ни там, идёт следом в порядке по умолчанию). Не задано: каждая поверхность выбирает кнопки по порядку действий, как раньше." + }, + "actionLayout.list": { + label: "Список", + helpText: "Панель инструментов страницы списка, в виде {\"pinned\": [...], \"more\": [...]}: имена действий на панели списка; $import / $export только в pinned. Не более 3 закреплённых. Без закрепления страница по-прежнему показывает своё меню импорта / экспорта. os validate отклоняет имя, которое не является действием этого объекта или не размещено на панели списка; такое имя ничего не показывает." + }, + "actionLayout.record": { + label: "Запись", + helpText: "Заголовок записи (страница записи, боковой просмотр, нижняя панель на телефоне), в виде {\"pinned\": [...], \"more\": [...]}: имена действий в заголовке записи или его меню «Ещё». Не более 3 закреплённых. os validate отклоняет имя, которое не является действием этого объекта или не размещено на странице записи; такое имя ничего не показывает." + }, editMode: { label: "Режим редактирования", helpText: "Намерение по взаимодействию при редактировании записей этого объекта. Если отсутствует, отрисовщик выбирает своё значение по умолчанию. Намерение для всех отрисовщиков, а не оформление." 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 ab3fb4c2f22..5018cc3116e 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 @@ -469,6 +469,18 @@ export const zhCNMetadataForms: NonNullable = label: "更改负责人", helpText: "更改负责人操作(单条与批量):开启即提供,关闭即隐藏。未设置时开启,但 controlled_by_parent 明细对象默认关闭。仅在记录有可重新分配负责人的对象上提供(ownership 为 user 或未设置、无 managedBy、不是 sys_ 对象、owner_id 未设为只读,外部对象上 owner_id 已声明或已映射);在其他对象上开启会被拒绝。它只控制该操作,不影响直接编辑 owner_id。已存储的 {enabled, visibleWhen, disabledWhen} 对象逐键编辑;在源码中写一个即可按每条记录控制该操作。" }, + actionLayout: { + label: "动作布局", + helpText: "本对象动作的顺序及哪些显示为按钮,按作用域分:pinned(最多 3 个按钮,按顺序)和 more(「更多」菜单的顺序;两者都没写的动作按默认顺序排在后面)。未设置时,各处仍按动作的排序选按钮。" + }, + "actionLayout.list": { + label: "列表", + helpText: "列表页工具栏,写作 {\"pinned\": [...], \"more\": [...]}:放在列表工具栏上的动作名称;$import / $export 只能放在 pinned。最多固定 3 个。未固定时,页面仍显示自己的导入 / 导出菜单。os validate 会拒绝不是本对象动作、或未放在列表工具栏上的名称;这样的名称什么也不显示。" + }, + "actionLayout.record": { + label: "记录", + helpText: "记录页头(记录页、侧边预览、手机底栏),写作 {\"pinned\": [...], \"more\": [...]}:放在记录页头或其「更多」菜单中的动作名称。最多固定 3 个。os validate 会拒绝不是本对象动作、或未放在记录页上的名称;这样的名称什么也不显示。" + }, editMode: { label: "编辑方式", helpText: "该对象记录的编辑交互意图。留空则由渲染端自行选择默认方式。这是跨渲染端的意图声明,不是样式。" 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 089db9691c5..e18c228ea33 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 @@ -469,6 +469,18 @@ export const zhHantMetadataForms: NonNullable label: "變更負責人", helpText: "變更負責人操作(單筆與批次):開啟即提供,關閉即隱藏。未設定時開啟,但 controlled_by_parent 明細物件預設關閉。僅在記錄有可重新指派負責人的物件上提供(ownership 為 user 或未設定、無 managedBy、不是 sys_ 物件、owner_id 未設為唯讀,外部物件上 owner_id 已宣告或已對應);在其他物件上開啟會被拒絕。它只控制該操作,不影響直接編輯 owner_id。已儲存的 {enabled, visibleWhen, disabledWhen} 物件逐鍵編輯;在原始碼中寫一個即可按每筆記錄控制該操作。" }, + actionLayout: { + label: "動作佈局", + helpText: "本物件動作的順序及哪些顯示為按鈕,按作用域分:pinned(最多 3 個按鈕,按順序)和 more(「更多」選單的順序;兩者都沒寫的動作按預設順序排在後面)。未設定時,各處仍按動作的排序選按鈕。" + }, + "actionLayout.list": { + label: "列表", + helpText: "列表頁工具列,寫作 {\"pinned\": [...], \"more\": [...]}:放在列表工具列上的動作名稱;$import / $export 只能放在 pinned。最多固定 3 個。未固定時,頁面仍顯示自己的匯入 / 匯出選單。os validate 會拒絕不是本物件動作、或未放在列表工具列上的名稱;這樣的名稱什麼也不顯示。" + }, + "actionLayout.record": { + label: "記錄", + helpText: "記錄頁頭(記錄頁、側邊預覽、手機底欄),寫作 {\"pinned\": [...], \"more\": [...]}:放在記錄頁頭或其「更多」選單中的動作名稱。最多固定 3 個。os validate 會拒絕不是本物件動作、或未放在記錄頁上的名稱;這樣的名稱什麼也不顯示。" + }, editMode: { label: "編輯方式", helpText: "該物件記錄的編輯互動意圖。留空則由呈現端自行選擇預設方式。這是跨呈現端的意圖宣告,不是樣式。" diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 790dc482a76..361141cd9b7 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -580,6 +580,9 @@ "NumericColumnRepresentation (type)", "NumericStringGrammarCase (type)", "NumericStringReading (type)", + "OBJECT_ACTION_LAYOUT_BUILTINS (const)", + "OBJECT_ACTION_LAYOUT_PINNED_LIMIT (const)", + "OBJECT_ACTION_LAYOUT_SCOPES (const)", "OBJECT_COLORS (const)", "OBJECT_KEY_GUIDANCE (const)", "ORACLE_DEFAULT_PORT (const)", @@ -589,6 +592,9 @@ "ObjectAccessConfig (type)", "ObjectAccessConfigParsed (type)", "ObjectAccessConfigSchema (const)", + "ObjectActionLayout (type)", + "ObjectActionLayoutArm (type)", + "ObjectActionLayoutScope (type)", "ObjectCapabilities (const)", "ObjectCapabilities (type)", "ObjectCapabilitiesParsed (type)", diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index ed0ebba883e..0118ccebfbb 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -677,6 +677,7 @@ "data/Object:_packageVersion", "data/Object:_provenance", "data/Object:access", + "data/Object:actionLayout", "data/Object:actions", "data/Object:activityMilestones", "data/Object:attachedOnRead", @@ -738,6 +739,7 @@ "data/ObjectDependencyNode:dependsOn", "data/ObjectDependencyNode:object", "data/ObjectDependencyNode:references", + "data/ObjectExtension:actionLayout", "data/ObjectExtension:description", "data/ObjectExtension:extend", "data/ObjectExtension:fieldGroups", diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index 70d70d03422..dfb4351621a 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -3,7 +3,7 @@ "measured": { "zod": "4.4.3", "publishedSchemasWithDroppedRefinements": 274, - "droppedRefinementSites": 1151, + "droppedRefinementSites": 1171, "refinementSitesThatDidProject": 728, "refinementSitesWithNoJsonFormToCompare": 0 }, @@ -162,6 +162,8 @@ "manifest.objects.element.lifecycle", "manifest.objects.element.membershipKeys", "manifest.objects.element.membershipKeys.valueType", + "manifest.objects.element.actionLayout.list", + "manifest.objects.element.actionLayout.record", "manifest.pages.element", "manifest.pages.element.apps", "manifest.pages.element.slots.header.options[0].type", @@ -351,6 +353,8 @@ "data.options[1].manifest.objects.element.lifecycle", "data.options[1].manifest.objects.element.membershipKeys", "data.options[1].manifest.objects.element.membershipKeys.valueType", + "data.options[1].manifest.objects.element.actionLayout.list", + "data.options[1].manifest.objects.element.actionLayout.record", "data.options[1].manifest.pages.element", "data.options[1].manifest.pages.element.apps", "data.options[1].manifest.pages.element.slots.header.options[0].type", @@ -506,6 +510,8 @@ "options[1].manifest.objects.element.lifecycle", "options[1].manifest.objects.element.membershipKeys", "options[1].manifest.objects.element.membershipKeys.valueType", + "options[1].manifest.objects.element.actionLayout.list", + "options[1].manifest.objects.element.actionLayout.record", "options[1].manifest.pages.element", "options[1].manifest.pages.element.apps", "options[1].manifest.pages.element.slots.header.options[0].type", @@ -605,6 +611,8 @@ "data.packages.element.options[1].manifest.objects.element.lifecycle", "data.packages.element.options[1].manifest.objects.element.membershipKeys", "data.packages.element.options[1].manifest.objects.element.membershipKeys.valueType", + "data.packages.element.options[1].manifest.objects.element.actionLayout.list", + "data.packages.element.options[1].manifest.objects.element.actionLayout.record", "data.packages.element.options[1].manifest.pages.element", "data.packages.element.options[1].manifest.pages.element.apps", "data.packages.element.options[1].manifest.pages.element.slots.header.options[0].type", @@ -684,7 +692,9 @@ "data.listViews.valueType.kanban.groupByField", "data.listViews.valueType.timeline.groupByField", "data.membershipKeys", - "data.membershipKeys.valueType" + "data.membershipKeys.valueType", + "data.actionLayout.list", + "data.actionLayout.record" ] }, "api/PackageInstallBody": { @@ -1197,7 +1207,9 @@ "listViews.valueType.kanban.groupByField", "listViews.valueType.timeline.groupByField", "membershipKeys", - "membershipKeys.valueType" + "membershipKeys.valueType", + "actionLayout.list", + "actionLayout.record" ] }, "data/ObjectExtension": { @@ -1208,7 +1220,9 @@ "fields.out.valueType.inlineColumns.element", "fields.out.valueType.lookupFilters.element", "fields.out.valueType.relatedListFilter.lazy", - "fields.out.valueType.summaryOperations" + "fields.out.valueType.summaryOperations", + "actionLayout.list", + "actionLayout.record" ] }, "data/OracleConfig": { @@ -1563,7 +1577,9 @@ "operations.element.options[3].object.listViews.valueType.kanban.groupByField", "operations.element.options[3].object.listViews.valueType.timeline.groupByField", "operations.element.options[3].object.membershipKeys", - "operations.element.options[3].object.membershipKeys.valueType" + "operations.element.options[3].object.membershipKeys.valueType", + "operations.element.options[3].object.actionLayout.list", + "operations.element.options[3].object.actionLayout.record" ] }, "system/CreateObjectOperation": { @@ -1596,7 +1612,9 @@ "object.listViews.valueType.kanban.groupByField", "object.listViews.valueType.timeline.groupByField", "object.membershipKeys", - "object.membershipKeys.valueType" + "object.membershipKeys.valueType", + "object.actionLayout.list", + "object.actionLayout.record" ] }, "system/CronSchedule": { @@ -1651,7 +1669,9 @@ "options[3].object.listViews.valueType.kanban.groupByField", "options[3].object.listViews.valueType.timeline.groupByField", "options[3].object.membershipKeys", - "options[3].object.membershipKeys.valueType" + "options[3].object.membershipKeys.valueType", + "options[3].object.actionLayout.list", + "options[3].object.actionLayout.record" ] }, "system/ObjectStorageConfig": { diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 55df42e31e0..8c7299c08e4 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -570,6 +570,9 @@ "NumericColumnRepresentation": "src/data/numeric-column-representation.ts#NumericColumnRepresentation (type)", "NumericStringGrammarCase": "src/data/filter-number-comparand-declared-type.ts#NumericStringGrammarCase (type)", "NumericStringReading": "src/data/filter-number-comparand-declared-type.ts#NumericStringReading (type)", + "OBJECT_ACTION_LAYOUT_BUILTINS": "src/data/object-action-layout.ts#OBJECT_ACTION_LAYOUT_BUILTINS (const)", + "OBJECT_ACTION_LAYOUT_PINNED_LIMIT": "src/data/object-action-layout.ts#OBJECT_ACTION_LAYOUT_PINNED_LIMIT (const)", + "OBJECT_ACTION_LAYOUT_SCOPES": "src/data/object-action-layout.ts#OBJECT_ACTION_LAYOUT_SCOPES (const)", "OBJECT_COLORS": "src/data/object-icon.ts#OBJECT_COLORS (const)", "OBJECT_KEY_GUIDANCE": "src/data/authoring-key-lint.ts#OBJECT_KEY_GUIDANCE (const)", "ORACLE_DEFAULT_PORT": "src/data/driver/oracle.zod.ts#ORACLE_DEFAULT_PORT (const)", @@ -579,6 +582,9 @@ "ObjectAccessConfig": "src/data/object.zod.ts#ObjectAccessConfig (type)", "ObjectAccessConfigParsed": "src/data/object.zod.ts#ObjectAccessConfigParsed (type)", "ObjectAccessConfigSchema": "src/data/object.zod.ts#ObjectAccessConfigSchema (const)", + "ObjectActionLayout": "src/data/object-action-layout.ts#ObjectActionLayout (type)", + "ObjectActionLayoutArm": "src/data/object-action-layout.ts#ObjectActionLayoutArm (type)", + "ObjectActionLayoutScope": "src/data/object-action-layout.ts#ObjectActionLayoutScope (type)", "ObjectCapabilities": "src/data/object.zod.ts#ObjectCapabilities (type)", "ObjectCapabilitiesParsed": "src/data/object.zod.ts#ObjectCapabilitiesParsed (type)", "ObjectColor": "src/data/object-icon.ts#ObjectColor (type)", diff --git a/packages/spec/liveness/object.json b/packages/spec/liveness/object.json index 49c9ee471ea..73794e2e8a0 100644 --- a/packages/spec/liveness/object.json +++ b/packages/spec/liveness/object.json @@ -30,6 +30,61 @@ "evidence": "ui/packages/layout/src/NavigationRenderer.tsx#NavigationItemRenderer (an `object` navigation entry draws an ObjectIconTile coloured by `resolveTargetColor`); ui/packages/app-shell/src/hooks/useNavTargetIcon.ts#useNavTargetColor (reads the object's `color` from the metadata cache for the sidebar and the app-home menu); ui/packages/components/src/custom/object-icon-tile.tsx#ObjectIconTile (maps the palette name to the square's colour); ui/packages/app-shell/src/views/metadata-admin/inspectors/ObjectDefaultInspector.tsx#ObjectDefaultInspector (the designer writes it)", "note": "objectstack#35985: the colour of the rounded square the object's icon is drawn on, from the closed palette `OBJECT_COLORS`. Unset draws the neutral gray. The navigation (sidebar, app-home menu, phone menu) reads it; the other places that draw an object icon follow in the card's second PR." }, + "actionLayout": { + "status": "live", + "verifiedAt": "2026-11-23", + "evidenceScope": "in-repo", + "evidence": "ui/packages/types/src/ui-action.ts#arrangedHeaderActions (the ONE reader: an arm's `pinned` actions become the header's buttons in pin order, the ones `more` names lead the overflow in that order, every other placed action follows in its default order); ui/packages/app-shell/src/views/RecordDetailView.tsx#RecordDetailView (the record header reads `actionLayout.record`, staged arrangement included; the side preview and the phone's bottom bar draw the same header); ui/packages/components/src/renderers/layout/containers.tsx#PageHeaderActions (an authored `page:header` with `placedActions: true` reads the same arm); ui/packages/app-shell/src/views/objectViewPageHeader.tsx#PinnedListHeaderActions (the list header reads `actionLayout.list`, `$import` and `$export` among the actions); packages/objectql/src/registry-custom-arrangement.ts#applyCustomArrangement (only the base's paired `.custom` extension writes it, applied last, each arm it writes replaced whole; any other package's is refused at publish, os validate, os build and install); ui/packages/app-shell/src/layout/DesignModeHeaderPins.tsx#DesignModeHeaderPins (the design mode writes it)", + "note": "objectstack#36366: the order of the object's actions and which are buttons, per action scope (`list`, `record`): `pinned` is at most three buttons in order, `more` orders the 「More」 menu, and an action named in neither follows at the end of 「More」 in its default order. Absent (or an arm absent): the scope draws as before. An installed object is arranged through its customization package's `object_extension`.", + "children": { + "list": { + "status": "live", + "verifiedAt": "2026-11-23", + "evidenceScope": "in-repo", + "evidence": "ui/packages/app-shell/src/views/objectViewPageHeader.tsx#PinnedListHeaderActions (the list header draws the pinned toolbar actions and `$import` / `$export` as its buttons, in pin order); ui/packages/types/src/ui-action.ts#arrangedHeaderActions (the unpinned toolbar actions go to the bar's overflow)", + "note": "objectstack#36366: the list scope, drawn on the list page toolbar.", + "children": { + "pinned": { + "status": "live", + "verifiedAt": "2026-11-23", + "evidenceScope": "in-repo", + "evidence": "ui/packages/app-shell/src/views/objectViewPageHeader.tsx#PinnedListHeaderActions (the list header draws the pinned toolbar actions and a pinned `$import` / `$export` as its buttons, in pin order); ui/packages/types/src/ui-action.ts#arrangedHeaderActions (a pinned toolbar action leads the bar's sort)", + "note": "objectstack#36366: the list toolbar's buttons, at most three, in order." + }, + "more": { + "status": "live", + "verifiedAt": "2026-11-23", + "evidenceScope": "in-repo", + "evidence": "ui/packages/types/src/ui-action.ts#arrangedHeaderActions (the toolbar actions `more` names lead the toolbar's ⋯ in that order, unnamed ones after); ui/packages/app-shell/src/views/objectViewPageHeader.tsx#PinnedListHeaderActions (draws them in the toolbar's ⋯)", + "note": "objectstack#36366: the order of the list toolbar's ⋯ menu." + } + } + }, + "record": { + "status": "live", + "verifiedAt": "2026-11-23", + "evidenceScope": "in-repo", + "evidence": "ui/packages/app-shell/src/views/RecordDetailView.tsx#RecordDetailView (the synthesized record header reads the arm); ui/packages/components/src/renderers/layout/containers.tsx#PageHeaderActions (an authored `page:header` with `placedActions: true` reads it); ui/packages/types/src/ui-action.ts#arrangedHeaderActions (pinned actions placed at `record_header` in pin order, the rest at `record_more`)", + "note": "objectstack#36366: the record scope, drawn in the record header: the record page, the side preview and the phone's bottom bar.", + "children": { + "pinned": { + "status": "live", + "verifiedAt": "2026-11-23", + "evidenceScope": "in-repo", + "evidence": "ui/packages/types/src/ui-action.ts#arrangedHeaderActions (a pinned action is placed at `record_header` and leads the sort, in pin order); ui/packages/app-shell/src/views/RecordDetailView.tsx#RecordDetailView (the record header, side preview and phone bar draw them as buttons); ui/packages/components/src/renderers/layout/containers.tsx#PageHeaderActions (an authored `placedActions: true` header too)", + "note": "objectstack#36366: the record header's buttons, at most three, in order." + }, + "more": { + "status": "live", + "verifiedAt": "2026-11-23", + "evidenceScope": "in-repo", + "evidence": "ui/packages/types/src/ui-action.ts#arrangedHeaderActions (an unpinned action is placed at `record_more`, the ones `more` names first in that order); ui/packages/app-shell/src/views/RecordDetailView.tsx#RecordDetailView (the record header's ⋯ draws them)", + "note": "objectstack#36366: the order of the record header's ⋯ menu." + } + } + } + } + }, "displayNameField": { "status": "live", "note": "Deprecated alias of nameField (ADR-0079); still read by objectui RecordDetailView + resolveDisplayField back-compat." diff --git a/packages/spec/liveness/state-counts/object.md b/packages/spec/liveness/state-counts/object.md index dc2c107bc04..bd9976320f9 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` | 90 | 0 | 0 | 1 | 1 | 92 | +| `object` | 94 | 0 | 0 | 1 | 1 | 96 | diff --git a/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts b/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts index 354477bf568..0c01604f479 100644 --- a/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts +++ b/packages/spec/src/compose-stacks-merge-collection-refusal.test.ts @@ -80,6 +80,8 @@ const COLLECTION_KEYS_IN_SHAPE_ORDER = [ * in `compose-stacks-merge-config-object-refusal.test.ts`. */ const CONFIG_OBJECT_KEYS_IN_SHAPE_ORDER = [ + // [#36366] `actionLayout` — the object's action arrangement per scope (pinned, more). + 'actionLayout', 'userActions', 'external', 'tenancy', diff --git a/packages/spec/src/compose-stacks-merge-config-object-refusal.test.ts b/packages/spec/src/compose-stacks-merge-config-object-refusal.test.ts index 330cb878589..6aa0b372b9a 100644 --- a/packages/spec/src/compose-stacks-merge-config-object-refusal.test.ts +++ b/packages/spec/src/compose-stacks-merge-config-object-refusal.test.ts @@ -78,6 +78,8 @@ const shared = (out: ObjectStackDefinition) => * `'merge'` by the unedited composer, which is the ARRIVAL leg below in production. */ const CONFIG_OBJECT_KEYS_IN_SHAPE_ORDER = [ + // [#36366] `actionLayout` — the object's action arrangement per scope (pinned, more). + 'actionLayout', 'userActions', 'external', 'tenancy', diff --git a/packages/spec/src/data/field-customization.ts b/packages/spec/src/data/field-customization.ts index f3d73e0fbca..486aa8e3a74 100644 --- a/packages/spec/src/data/field-customization.ts +++ b/packages/spec/src/data/field-customization.ts @@ -19,7 +19,7 @@ * 3. **Only the paired `.custom` package arranges the whole record page** * (maintainer, verbatim: 「软件包字段、子表自定义分三种,原始软件包,继承软件包和环境管理员覆盖, * 继承软件包 我记得已经有一套标准,只能申明插入位置,原始软件包、环境管理员 应该可以申明完整的配置」). - * {@link CUSTOM_ARRANGEMENT_KEYS} are the two keys its object extension + * {@link CUSTOM_ARRANGEMENT_KEYS} are the keys its object extension * writes, in an object's own shape; any other package's extension places * what it brings with `place`, and outside a `.custom` package is refused * these keys at publish, at `os validate` and at the install door. The @@ -113,15 +113,19 @@ export type BaseFieldOptionDisplayProperty = (typeof BASE_FIELD_DISPLAY_WHITELIS * [ADR-0146 D10] The keys of an object extension only a base's paired * `.custom` package writes: the whole field arrangement and the whole tab * list of the extended object, each in the shape an object declares it in - * (`ObjectExtensionSchema.fieldGroups` / `.relatedLists`). Written, a key - * replaces what the owner declares and the other extensions' `place` entries - * add to, whole; not written, that arrangement stays. + * (`ObjectExtensionSchema.fieldGroups` / `.relatedLists`), and + * [objectstack#36366] the arrangement of its actions + * (`ObjectExtensionSchema.actionLayout`). Written, a list key replaces what + * the owner declares and the other extensions' `place` entries add to, + * whole; `actionLayout` replaces the owner's arm for each scope it writes + * (`list`, `record`), and an arm it does not write stays. Not written, that + * arrangement stays. * * The ONE list: the registry fold that applies the keys, and the judge that * refuses them outside `.custom` (publish, `os validate` / `os build`, the * install door), read it through {@link extensionArrangementKeys}. */ -export const CUSTOM_ARRANGEMENT_KEYS = Object.freeze(['fieldGroups', 'relatedLists'] as const); +export const CUSTOM_ARRANGEMENT_KEYS = Object.freeze(['fieldGroups', 'relatedLists', 'actionLayout'] as const); /** One of {@link CUSTOM_ARRANGEMENT_KEYS}. */ export type CustomArrangementKey = (typeof CUSTOM_ARRANGEMENT_KEYS)[number]; @@ -129,8 +133,8 @@ export type CustomArrangementKey = (typeof CUSTOM_ARRANGEMENT_KEYS)[number]; /** * [ADR-0146 D10] The {@link CUSTOM_ARRANGEMENT_KEYS} an object extension body * writes, in the list's order. A key counts as written when the body carries - * any value under it (an empty array included: it declares an arrangement - * with nothing in it); `undefined` and `null` do not. Tolerant of an unparsed + * any value under it (an empty array or object included: it declares an + * arrangement with nothing in it); `undefined` and `null` do not. Tolerant of an unparsed * body, so every door and the fold share one reading. */ export function extensionArrangementKeys(extension: unknown): CustomArrangementKey[] { diff --git a/packages/spec/src/data/index.ts b/packages/spec/src/data/index.ts index 1641fe0e4b2..93d23cd0e33 100644 --- a/packages/spec/src/data/index.ts +++ b/packages/spec/src/data/index.ts @@ -217,6 +217,15 @@ export * from './object.zod'; // [#35985] The object colour palette, named once so a renderer draws exactly // the names the spec accepts. The `icon` / `color` leaves stay unexported. export { OBJECT_COLORS, type ObjectColor } from './object-icon'; +// [#36366] The action layout per scope: the pinned limit, the scopes and their built-ins. +export { + OBJECT_ACTION_LAYOUT_PINNED_LIMIT, + OBJECT_ACTION_LAYOUT_SCOPES, + OBJECT_ACTION_LAYOUT_BUILTINS, + type ObjectActionLayoutScope, + type ObjectActionLayout, + type ObjectActionLayoutArm, +} from './object-action-layout'; // API-method derivation — the single source of truth turning an object's // `enable.apiMethods` whitelist into its effective operation set (#3391). export * from './api-derivation'; diff --git a/packages/spec/src/data/object-action-layout.test.ts b/packages/spec/src/data/object-action-layout.test.ts new file mode 100644 index 00000000000..24a5bc30283 --- /dev/null +++ b/packages/spec/src/data/object-action-layout.test.ts @@ -0,0 +1,133 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36366 — `actionLayout`, the order of an object's actions and + * which are buttons, per action scope. Optional with no default; each arm is + * `{ pinned, more }`. The shape refuses, with a named reason, more than three + * pinned, an entry named twice (in one part or in both), an entry that is + * neither an action name nor a `$` built-in, and a built-in the scope does not + * have. The object extension carries the same shape. + */ + +import { describe, expect, it } from 'vitest'; +import { ObjectExtensionSchema, ObjectSchema } from './object.zod'; +import { + OBJECT_ACTION_LAYOUT_BUILTINS, + OBJECT_ACTION_LAYOUT_PINNED_LIMIT, + OBJECT_ACTION_LAYOUT_SCHEMA, +} from './object-action-layout'; + +const object = (actionLayout?: unknown) => ({ + name: 'crm_lead', + fields: { title: { type: 'text' } }, + ...(actionLayout === undefined ? {} : { actionLayout }), +}); + +function refusal(actionLayout: unknown): string[] { + const r = ObjectSchema.safeParse(object(actionLayout)); + if (r.success) return []; + return r.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`); +} + +describe('actionLayout (objectstack#36366)', () => { + it('is optional with no default: an object without it parses without it', () => { + const r = ObjectSchema.safeParse(object()); + expect(r.success).toBe(true); + expect(r.success && 'actionLayout' in r.data).toBe(false); + }); + + it('takes a list arm and a record arm, each pinned (up to three) and more, in order', () => { + const layout = { + list: { pinned: ['$export', 'convert_lead', '$import'], more: ['mass_update'] }, + record: { pinned: ['convert_lead', 'log_call', 'send_email'], more: ['clone_lead', 'archive_lead'] }, + }; + const r = ObjectSchema.safeParse(object(layout)); + expect(r.success).toBe(true); + expect(r.success && r.data.actionLayout).toEqual(layout); + expect(ObjectSchema.safeParse(object({ record: { pinned: [] } })).success).toBe(true); + expect(ObjectSchema.safeParse(object({ record: { pinned: ['log_call'] } })).success).toBe(true); + expect(ObjectSchema.safeParse(object({})).success).toBe(true); + }); + + it('an arm states its pinned list: `more` alone is refused', () => { + expect(refusal({ record: { more: ['log_call'] } }).join()).toMatch(/^actionLayout\.record\.pinned: /); + }); + + it('refuses more than three pinned, naming the limit and where the rest go', () => { + expect(OBJECT_ACTION_LAYOUT_PINNED_LIMIT).toBe(3); + const [message] = refusal({ record: { pinned: ['a_one', 'a_two', 'a_three', 'a_four'] } }); + expect(message).toMatch( + /^actionLayout\.record\.pinned: `actionLayout\.record\.pinned` names 4 actions; at most 3 are drawn as buttons/, + ); + expect(message).toMatch(/move the rest to `more`\.$/); + }); + + it('refuses an entry named twice in one part, at its index', () => { + expect(refusal({ list: { pinned: ['convert_lead', 'convert_lead'] } })).toEqual([ + 'actionLayout.list.pinned.1: `convert_lead` is named twice in `list.pinned`; an action is drawn once.', + ]); + expect(refusal({ record: { pinned: [], more: ['log_call', 'log_call'] } })).toEqual([ + 'actionLayout.record.more.1: `log_call` is named twice in `record.more`; an action is drawn once.', + ]); + }); + + it('refuses an entry named in both parts, at its place in `more`', () => { + expect(refusal({ record: { pinned: ['close_won'], more: ['clone_deal', 'close_won'] } })).toEqual([ + 'actionLayout.record.more.1: `close_won` is named in both `record.pinned` and `record.more`; an action is either a button or in 「More」.', + ]); + }); + + it('refuses an entry that is neither an action name nor a built-in, in either part', () => { + for (const bad of ['Convert', 'convert-lead', 'x', '', 'crm.convert']) { + for (const part of ['pinned', 'more'] as const) { + const arm = part === 'pinned' ? { pinned: [bad] } : { pinned: [], more: [bad] }; + const [message] = refusal({ record: arm }); + expect(message, `${part} ${bad}`).toBe( + `actionLayout.record.${part}.0: \`${bad}\` is not an action name (lowercase snake_case, as the action's \`name\`) ` + + 'nor a built-in (the record scope has no built-in, name an action).', + ); + } + } + }); + + it('refuses a built-in the scope does not have, naming the ones it has', () => { + expect(OBJECT_ACTION_LAYOUT_BUILTINS).toEqual({ list: ['$import', '$export'], record: [] }); + expect(refusal({ list: { pinned: ['$print'] } })).toEqual([ + "actionLayout.list.pinned.0: `$print` is not a built-in of the list scope: the list scope's built-ins are `$import`, `$export`.", + ]); + expect(refusal({ record: { pinned: [], more: ['$export'] } })).toEqual([ + 'actionLayout.record.more.0: `$export` is not a built-in of the record scope: the record scope has no built-in, name an action.', + ]); + }); + + it('refuses a built-in in `more`: a built-in is only ever pinned, not pinned it keeps the page\'s own menu', () => { + expect(refusal({ list: { pinned: [], more: ['mass_assign', '$import'] } })).toEqual([ + 'actionLayout.list.more.1: `$import` cannot be ordered in `list.more`: a built-in is only ever pinned. Not pinned, ' + + 'the list page draws it in its own Import / Export menu, so remove it from `more`, or move it to `pinned`.', + ]); + expect(refusal({ list: { pinned: ['$import'], more: ['$export'] } })).toHaveLength(1); + // CONTROL: the same built-in pinned, and an action in `more`, are accepted. + expect(refusal({ list: { pinned: ['$import', '$export'], more: ['mass_assign'] } })).toEqual([]); + }); + + it('is a closed shape at both levels: an unknown arm or part is refused, a near-miss pointed at its key', () => { + expect(refusal({ detail: { pinned: ['convert_lead'] } }).join()).toMatch(/record/); + expect(refusal({ recordPage: { pinned: ['convert_lead'] } }).join()).toMatch(/record/); + expect(refusal({ record: { pinned: [], overflow: ['log_call'] } }).join()).toMatch(/more/); + expect(refusal({ record: { buttons: ['log_call'] } }).join()).toMatch(/pinned/); + // The old per-page array is no arm. + expect(refusal({ record: ['log_call'] }).length).toBeGreaterThan(0); + }); + + it('the object extension carries the same leaf', () => { + expect( + ObjectExtensionSchema.safeParse({ extend: 'crm_lead', actionLayout: { record: { pinned: ['log_call'] } } }).success, + ).toBe(true); + const r = ObjectExtensionSchema.safeParse({ + extend: 'crm_lead', + actionLayout: { record: { pinned: ['a_one', 'a_two', 'a_three', 'a_four'] } }, + }); + expect(r.success).toBe(false); + expect(OBJECT_ACTION_LAYOUT_SCHEMA.safeParse(undefined).success).toBe(true); + }); +}); diff --git a/packages/spec/src/data/object-action-layout.ts b/packages/spec/src/data/object-action-layout.ts new file mode 100644 index 00000000000..44a4590bf8d --- /dev/null +++ b/packages/spec/src/data/object-action-layout.ts @@ -0,0 +1,220 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { z } from 'zod'; +import { strictObject } from '../shared/strict-object'; + +/** + * `ObjectSchema.actionLayout` (objectstack#36366): the order of an object's + * actions, and which of them are shown as buttons, per action scope. + * + * Without this key, a surface that draws an object's actions orders them by + * each action's `order` and declaration order, and draws the first ones as + * buttons and the rest in its 「More」 menu. That order is shared by every + * surface an action is placed on. With it, an arm states the arrangement of + * one scope: + * + * - `list`: the actions that act on no record, drawn on the object's list + * page toolbar (placed at `list_toolbar`), with the list page's built-ins + * `$import` and `$export`. + * - `record`: the actions that act on one record, drawn in the record page's + * header (placed at `record_header` or `record_more`). The same arm orders + * every surface that draws that header: the record page, the side preview + * and a phone's bottom action bar. + * + * An arm is a scope, not a page: one arm arranges one set of actions wherever + * that set is drawn. The key only re-arranges, so it sits on the object as a + * ruled exception to ADR-0085 §2's re-arrange sentence, the second after + * `relatedLists` (the maintainer's ruling on #36635; the dated ADR note is + * carried by #36086). The `list` arm has one reader today, the list page + * toolbar. + * + * Each arm has two parts. `pinned` names the buttons, at most + * {@link OBJECT_ACTION_LAYOUT_PINNED_LIMIT}, in the order they are drawn; + * `pinned: []` pins none. `more` names the order of the 「More」 menu; an + * action the scope places that neither part names goes to the end of 「More」, + * in its default order (`order`, then declaration). A pinned action hidden by + * its `visible` predicate or its permissions leaves its button out; no other + * action takes its place. An object without the key, or without an arm, draws + * that scope exactly as before. + * + * An entry is an action `name` of the object (lowercase snake_case, the + * action's own spelling), or one of the scope's built-ins, spelled with a + * leading `$` so it can never collide with an action name: + * {@link OBJECT_ACTION_LAYOUT_BUILTINS}. A built-in is only ever pinned: not + * pinned, the list page draws it in its own Import / Export menu, as without + * the key, so `more` names actions only. The record scope has none: New, Edit + * and Delete keep their fixed places. + * + * What the shape refuses here, at every door: more than three pinned, an + * entry named twice (in one part or in both), an entry that is neither an + * action name nor a `$` built-in, a `$` built-in the scope does not have, and + * a `$` built-in in `more`. + * Whether an action name names an action of this object placed in that scope + * is a reference, judged where the whole stack is visible + * (`@objectstack/lint`'s `validateObjectActionLayout`). + * + * Declared in its own module so the object extension (`ObjectExtensionSchema`, + * an installed object's customization, ADR-0146 D10) carries exactly the shape + * the object does. Only the base's paired `.custom` package writes it there + * (`CUSTOM_ARRANGEMENT_KEYS`); each arm it writes replaces the object's arm + * for that scope whole, applied last. + */ + +/** The most actions one arm pins as buttons. */ +export const OBJECT_ACTION_LAYOUT_PINNED_LIMIT = 3; + +/** The action scopes an object's actions are arranged in. */ +export const OBJECT_ACTION_LAYOUT_SCOPES = ['list', 'record'] as const; +export type ObjectActionLayoutScope = (typeof OBJECT_ACTION_LAYOUT_SCOPES)[number]; + +/** + * The built-in buttons an arm may name beside the object's actions, per scope. + * The list page's import and export are the console's own buttons, not object + * actions; the record scope has none. + */ +export const OBJECT_ACTION_LAYOUT_BUILTINS: Readonly> = { + list: ['$import', '$export'], + record: [], +}; + +/** + * The entries one scope's arm accepts: an action name (the spelling + * `ActionSchema.name` accepts, `SnakeCaseIdentifierSchema`: lowercase snake + * case, two characters at least) or one of the scope's built-ins. A pattern, + * so the JSON Schema states it too. + */ +function entryPattern(scope: ObjectActionLayoutScope): RegExp { + const builtins = OBJECT_ACTION_LAYOUT_BUILTINS[scope].map((b) => `|\\${b}`).join(''); + return new RegExp(`^(?:[a-z][a-z0-9_]+${builtins})$`); +} + +function builtinsSentence(scope: ObjectActionLayoutScope): string { + const builtins = OBJECT_ACTION_LAYOUT_BUILTINS[scope]; + return builtins.length > 0 + ? `the ${scope} scope's built-ins are ${builtins.map((b) => `\`${b}\``).join(', ')}` + : `the ${scope} scope has no built-in, name an action`; +} + +/** Why `entry` is no entry of the `scope` arm. */ +function entryRefusal(scope: ObjectActionLayoutScope, entry: unknown): string { + const text = String(entry); + return text.startsWith('$') + ? `\`${text}\` is not a built-in of the ${scope} scope: ${builtinsSentence(scope)}.` + : `\`${text}\` is not an action name (lowercase snake_case, as the action's \`name\`) ` + + `nor a built-in (${builtinsSentence(scope)}).`; +} + +function entries(scope: ObjectActionLayoutScope) { + return z.array(z.string().regex(entryPattern(scope), { error: (issue) => entryRefusal(scope, issue.input) })); +} + +/** An action name: what `more` accepts, a built-in being only ever pinned. */ +const ACTION_NAME_PATTERN = /^[a-z][a-z0-9_]+$/; + +/** Why `entry` is no entry of the `scope` arm's `more`. */ +function moreEntryRefusal(scope: ObjectActionLayoutScope, entry: unknown): string { + const text = String(entry); + if (OBJECT_ACTION_LAYOUT_BUILTINS[scope].includes(text)) { + return `\`${text}\` cannot be ordered in \`${scope}.more\`: a built-in is only ever pinned. Not pinned, the ` + + `${scope} page draws it in its own Import / Export menu, so remove it from \`more\`, or move it to \`pinned\`.`; + } + return entryRefusal(scope, entry); +} + +function moreEntries(scope: ObjectActionLayoutScope) { + return z.array(z.string().regex(ACTION_NAME_PATTERN, { error: (issue) => moreEntryRefusal(scope, issue.input) })); +} + +/** What `pinned: []` leaves drawn, per scope. */ +const PINNED_NONE: Readonly> = { + list: '`[]` pins none: every action goes to 「More」, and the list page still draws its own Import / Export menu.', + record: '`[]` pins none: every action goes to 「More」; New, Edit and Delete keep their fixed places.', +}; + +function layoutArm(scope: ObjectActionLayoutScope) { + return strictObject( + { + surface: `this object's \`actionLayout.${scope}\``, + // Closed from its first release (objectstack#36366). + history: 'Closed from its first release: no key here was ever dropped silently.', + aliases: { buttons: 'pinned', inline: 'pinned', overflow: 'more', menu: 'more' }, + }, + { + pinned: entries(scope) + .max(OBJECT_ACTION_LAYOUT_PINNED_LIMIT, { + error: (issue) => + `\`actionLayout.${scope}.pinned\` names ${Array.isArray(issue.input) ? issue.input.length : 'more'} actions; ` + + `at most ${OBJECT_ACTION_LAYOUT_PINNED_LIMIT} are drawn as buttons, and every other action goes to 「More」. ` + + `Keep the first ${OBJECT_ACTION_LAYOUT_PINNED_LIMIT} and move the rest to \`more\`.`, + }) + .describe( + `The ${scope} scope's buttons, in order, at most ${OBJECT_ACTION_LAYOUT_PINNED_LIMIT}. ${PINNED_NONE[scope]}`, + ), + more: moreEntries(scope) + .optional() + .describe( + "The order of the scope's 「More」 menu: action names only (a built-in is only ever pinned). An action " + + 'named in neither part goes to the end of 「More」, in its default order.', + ), + }, + ).superRefine((arm, ctx) => { + // Uniqueness, across both parts, is the one rule JSON Schema is not given here. + const seen = new Map(); + for (const part of ['pinned', 'more'] as const) { + (arm[part] ?? []).forEach((entry, index) => { + const first = seen.get(entry); + if (first) { + ctx.addIssue({ + code: 'custom', + path: [part, index], + message: + first === part + ? `\`${entry}\` is named twice in \`${scope}.${part}\`; an action is drawn once.` + : `\`${entry}\` is named in both \`${scope}.pinned\` and \`${scope}.more\`; an action is either a button or in 「More」.`, + }); + return; + } + seen.set(entry, part); + }); + } + }); +} + +/** + * The `actionLayout` leaf, shared by `ObjectSchema` and `ObjectExtensionSchema`. + * Optional with no default: absent draws every scope as before. + */ +export const OBJECT_ACTION_LAYOUT_SCHEMA = strictObject( + { + surface: "this object's `actionLayout`", + // Closed from its first release (objectstack#36366). + history: 'Closed from its first release: no key here was ever dropped silently.', + aliases: { listPage: 'list', recordPage: 'record', detail: 'record' }, + }, + { + list: layoutArm('list') + .optional() + .describe( + "The list scope's arrangement: actions of the object placed at `list_toolbar`, as drawn on the list page " + + 'toolbar, and `$import` / `$export` as pinned buttons (not pinned, they stay in the page\'s own Import / ' + + 'Export menu). Omit to draw it as before.', + ), + record: layoutArm('record') + .optional() + .describe( + "The record scope's arrangement: actions of the object placed at `record_header` or `record_more`, as " + + "drawn in the record header (record page, side preview, a phone's bottom bar). Omit to draw it as before.", + ), + }, +) + .optional() + .describe( + "The order of the object's actions and which are buttons, per action scope (`list`, `record`): `pinned` " + + '(at most 3 buttons, in order) and `more` (the 「More」 menu order; unnamed actions follow in their default ' + + "order). Omit to keep each surface's own choice (each action's `order`).", + ); + +/** An object's action layout, as authored. */ +export type ObjectActionLayout = z.input; +/** One scope's arm of an object's action layout, as authored. */ +export type ObjectActionLayoutArm = NonNullable['record']>; diff --git a/packages/spec/src/data/object-extension-arrangement.test.ts b/packages/spec/src/data/object-extension-arrangement.test.ts index 81e50f4d484..3385f0e3e3e 100644 --- a/packages/spec/src/data/object-extension-arrangement.test.ts +++ b/packages/spec/src/data/object-extension-arrangement.test.ts @@ -35,8 +35,8 @@ const issues = (input: unknown) => { }; describe('the arrangement keys', () => { - it('are fieldGroups and relatedLists, frozen', () => { - expect([...CUSTOM_ARRANGEMENT_KEYS]).toEqual(['fieldGroups', 'relatedLists']); + it('are fieldGroups, relatedLists and [#36366] actionLayout, frozen', () => { + expect([...CUSTOM_ARRANGEMENT_KEYS]).toEqual(['fieldGroups', 'relatedLists', 'actionLayout']); expect(Object.isFrozen(CUSTOM_ARRANGEMENT_KEYS)).toBe(true); }); @@ -46,6 +46,9 @@ describe('the arrangement keys', () => { [{ extend: 'a', relatedLists: ['task'] }, ['relatedLists']], [{ extend: 'a', relatedLists: [], fieldGroups: [{ key: 'b', label: 'B' }] }, ['fieldGroups', 'relatedLists']], [{ extend: 'a', fieldGroups: undefined, relatedLists: null }, []], + [{ extend: 'a', actionLayout: { record: { pinned: [] } } }, ['actionLayout']], + [{ extend: 'a', actionLayout: {}, relatedLists: [] }, ['relatedLists', 'actionLayout']], + [{ extend: 'a', actionLayout: null }, []], [undefined, []], [['fieldGroups'], []], ])('extensionArrangementKeys(%j) → %j', (body, keys) => { diff --git a/packages/spec/src/data/object.form.ts b/packages/spec/src/data/object.form.ts index e64ed26d7eb..9ddd8d6e974 100644 --- a/packages/spec/src/data/object.form.ts +++ b/packages/spec/src/data/object.form.ts @@ -756,6 +756,18 @@ export const objectForm = defineForm({ { field: 'transfer', label: 'Change Owner', widget: 'json', helpText: 'The Change Owner action, single and bulk: on offers it, off hides it. Unset: on, except off on a controlled_by_parent detail. Offered only on an object whose records have a reassignable owner (ownership user or unset, no managedBy, not a sys_ object, owner_id not readonly and, on an external object, declared or mapped); turning it on anywhere else is refused. It gates the action only, not a plain edit of owner_id. A stored {enabled, visibleWhen, disabledWhen} object is edited key by key; write one in source to gate the action on each record.' }, ], }, + // [#36366] The action layout per scope. Each arm is an object of two + // name lists (`pinned`, `more`), edited as JSON; the design mode edits + // it on the page. + { + field: 'actionLayout', + type: 'composite', + helpText: 'The order of this object\'s actions and which are buttons, per scope: pinned (at most 3 buttons, in order) and more (the More menu\'s order; an action named in neither follows in its default order). Unset: each surface picks its buttons by the actions\' order, as before.', + fields: [ + { field: 'list', label: 'List', widget: 'json', helpText: 'The list page toolbar, as {"pinned": [...], "more": [...]}: action names placed on the list toolbar; $import / $export only in pinned. At most 3 pinned. Not pinned, the page still draws its own Import / Export menu. os validate refuses a name that is no action of this object or is not placed on the list toolbar; such a name draws nothing.' }, + { field: 'record', label: 'Record', widget: 'json', helpText: 'The record header (record page, side preview, phone bar), as {"pinned": [...], "more": [...]}: action names placed in the record header or its More menu. At most 3 pinned. os validate refuses a name that is no action of this object or is not placed on the record page; such a name draws nothing.' }, + ], + }, { field: 'editMode', type: 'select', helpText: "Edit-interaction intent for records of this object. Absent, the renderer picks its own default. Cross-renderer intent, not styling.", options: [ { label: 'Modal — edit form as a dialog over the current view', value: 'modal' }, { label: 'Page — navigate to a dedicated full-page edit route', value: 'page' }, diff --git a/packages/spec/src/data/object.zod.ts b/packages/spec/src/data/object.zod.ts index c432582742d..123c3cba2ba 100644 --- a/packages/spec/src/data/object.zod.ts +++ b/packages/spec/src/data/object.zod.ts @@ -33,6 +33,8 @@ import { RECORD_PAGE_BUILTIN_TABS, relatedListEntryHidden, relatedListEntryName, import { refuseStageFieldWithoutKinds } from './stage-field-kinds'; // [#32763] The `icon` leaf, shared with the AI blueprint object. import { OBJECT_COLOR_SCHEMA, OBJECT_ICON_SCHEMA } from './object-icon'; +// [#36366] The action arrangement per scope (pinned, more), shared with the object extension. +import { OBJECT_ACTION_LAYOUT_SCHEMA } from './object-action-layout'; // The masked-on-read declaration (#20141); `warnGenericPasswordFields` reads its // `password` exemption rather than restating it. No runtime cycle: that module's // only imports are type-only. @@ -4060,6 +4062,8 @@ const ObjectSchemaBase = strictObject( icon: OBJECT_ICON_SCHEMA, // [#35985] The colour of the square the icon is drawn on, from a closed palette. color: OBJECT_COLOR_SCHEMA, + // [#36366] The order of the object's actions and which are buttons, per scope (list, record). + actionLayout: OBJECT_ACTION_LAYOUT_SCHEMA, /** * Taxonomy & Organization @@ -6846,6 +6850,20 @@ const CUSTOM_ARRANGEMENT_WRITER = 'refused at those doors: the registry merge does not apply what it writes here, alone or beside the pair, ' + 'and the boot log names it.'; +/** [#36366, ADR-0146 D10] The extension's `actionLayout` description. */ +function objectExtensionActionLayoutDescription(): string { + return ( + 'The arrangement of the extended object\'s actions, per scope (`list`, `record`), in the object\'s own shape. ' + + 'Written only by the object extension of the paired `.custom` package of the App the object belongs to ' + + '(ADR-0146 D10). An extension in a package that is not a `.custom` package is refused at publish, by ' + + '`os validate` / `os build` and at install, and the registry merge skips it with a warning; an action that ' + + 'package brings is placed by its own `locations` and `order`. A `.custom` package that is not this object\'s ' + + 'pair is not applied. Each arm written replaces the arm the object serves for that scope, whole, after ' + + 'every other layer; an arm not written stays as the object gives it, and removing the key, or uninstalling ' + + 'or disabling the package, restores it.' + ); +} + /** [ADR-0146 D10] The extension's `fieldGroups` description. */ function objectExtensionFieldGroupsDescription(): string { return ( @@ -6933,12 +6951,16 @@ export const ObjectExtensionSchema = lazySchema(() => strictObject({ guidance: { // The merge in `objectql/src/engine.ts` copies EXACTLY the declared keys // (extend / fields / fieldPatches / label / pluralLabel / description / - // validations / indexes / priority) onto the extension def. Anything else - // is not "unsupported yet" — there is no slot for it to arrive through. + // validations / indexes / priority, and the paired `.custom` package's + // fieldGroups / relatedLists / actionLayout) onto the extension def. + // Anything else is not "unsupported yet" — there is no slot for it to + // arrive through. actions: '`actions` cannot be contributed through an object extension — the merge carries ' + '`fields`, `label`, `pluralLabel`, `description`, `validations` and `indexes`, and ' + - 'applies `fieldPatches`, and nothing else. ' + + 'applies `fieldPatches`; only the base\'s paired `.custom` package also writes ' + + '`fieldGroups`, `relatedLists` and `actionLayout` (the order of the object\'s actions, ' + + 'never a new one); nothing else. ' + "Declare a top-level action with `objectName: ''` in the same stack: " + '`defineStack()` accepts it because the stack extends the target, keeps it in the ' + 'top-level `actions`, and the engine\'s schema registry attaches it to the target ' + @@ -6960,9 +6982,9 @@ export const ObjectExtensionSchema = lazySchema(() => strictObject({ 'carry them. Declare the views as a top-level `view` in the stack that defines the ' + 'target object. `defineStack()` refuses a top-level `view` whose `list` or `form` data ' + 'source is an object the stack does not define, an extended one included.', - // [#35901, ADR-0146 D10] `fieldGroups` and `relatedLists` are KEYS of this - // schema, not guidance: the paired `.custom` package's extension writes - // them, and which package an extension belongs to is not in its body, so + // [#35901, #36366, ADR-0146 D10] `fieldGroups`, `relatedLists` and + // `actionLayout` are KEYS of this schema, not guidance: the paired + // `.custom` package's extension writes them, and which package an extension belongs to is not in its body, so // the refusal of any other writer is the server's (`CUSTOM_ARRANGEMENT_KEYS` // and its judge, at publish, `os validate` / `os build` and install). // A membership key belongs to the package that owns the roster object, so a @@ -7047,6 +7069,17 @@ export const ObjectExtensionSchema = lazySchema(() => strictObject({ /** Override description */ description: z.string().optional().describe('Override description for the extended object'), + + /** + * [#36366, ADR-0146 D10] The arrangement of the extended object's actions, + * as on the object itself (`ObjectSchema.actionLayout`), written by the + * object extension of the base's paired `.custom` package and by no other + * (`CUSTOM_ARRANGEMENT_KEYS`). Applied by role, last, arm by arm: each arm + * it writes replaces the arm the object serves for that scope, whole; an + * arm it leaves out stays. Refused for any other writer where `fieldGroups` + * is. See {@link objectExtensionActionLayoutDescription}. + */ + actionLayout: OBJECT_ACTION_LAYOUT_SCHEMA.describe(objectExtensionActionLayoutDescription()), /** Additional validation rules to add */ validations: z.array(ValidationRuleSchema).optional().describe('Additional validation rules to merge into the target object'), diff --git a/ui/packages/app-shell/src/layout/DesignModeHeaderPins.tsx b/ui/packages/app-shell/src/layout/DesignModeHeaderPins.tsx new file mode 100644 index 00000000000..1fc649c9f49 --- /dev/null +++ b/ui/packages/app-shell/src/layout/DesignModeHeaderPins.tsx @@ -0,0 +1,56 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * 「Header buttons」, the design mode's control at the right end of a page + * header's button group (objectstack#36366), and the action arrangement a + * page header draws. + * + * The control is drawn only while the mode is on, and its panel + * (`DesignModeHeaderPinsPanel.tsx`: the drag-and-drop list and the save + * behind it) is loaded then, so a page header outside the mode loads none of + * it. While a change is staged the page's header draws it + * ({@link useObjectPins}), so the administrator sees the header they are + * making. + * + * @module + */ + +import * as React from 'react'; +import { useDesignModeActive, useDesignModeChange } from './designMode.js'; +import { pinsChangeKey, servedPins, type ObjectPins, type PinCandidate, type PinPage } from './designModeHeaderPins.js'; + +const HeaderPinsPanel = React.lazy(() => import('./DesignModeHeaderPinsPanel.js')); + +type ServedObject = { readonly name?: unknown; readonly _packageId?: unknown; readonly actionLayout?: unknown }; + +/** + * The object's action arrangement as the page's header draws it: the change + * staged under the design mode, else the object's `actionLayout` as served. + * `undefined` for an arm neither sets (the header's own choice). + */ +export function useObjectPins(objectDef: ServedObject | null | undefined): ObjectPins { + const name = typeof objectDef?.name === 'string' ? objectDef.name : ''; + const staged = useDesignModeChange(pinsChangeKey(name)).value; + return React.useMemo(() => staged ?? servedPins(objectDef), [staged, objectDef]); +} + +export interface DesignModeHeaderPinsProps { + /** The object as served: its name, package, actions and `actionLayout`. */ + readonly objectDef: ServedObject & { readonly actions?: unknown }; + /** The action scope the header draws: the object's list page toolbar or its record header. */ + readonly page: PinPage; + /** The page's actions as its header has them (labels localized), in any order. */ + readonly actions: readonly Record[]; + /** The page's built-in buttons this reader is offered (`$import`, `$export`). */ + readonly builtins?: readonly PinCandidate[]; +} + +export function DesignModeHeaderPins(props: DesignModeHeaderPinsProps) { + const active = useDesignModeActive(); + if (!active) return null; + return ( + + + + ); +} diff --git a/ui/packages/app-shell/src/layout/DesignModeHeaderPinsPanel.tsx b/ui/packages/app-shell/src/layout/DesignModeHeaderPinsPanel.tsx new file mode 100644 index 00000000000..5d5a715d36e --- /dev/null +++ b/ui/packages/app-shell/src/layout/DesignModeHeaderPinsPanel.tsx @@ -0,0 +1,255 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The panel behind the design mode's 「Header buttons」 (objectstack#36366), + * loaded only once the mode is on (`DesignModeHeaderPins.tsx` loads it + * lazily): a scope's actions in two parts, 「Pinned to header」 (at most + * three) and 「Other」 (the header's 「More」 menu), each dragged into order. + * A dot beside each action moves it between the two; pinning a fourth is + * refused with a toast and changes nothing. A name the object's arrangement + * sets that the scope no longer offers is listed as left out. + * + * The change is staged under the object's key (`pinsChangeKey`), both scopes + * in one value, each arm written whole (`{ pinned, more }`), and the mode's + * 「Save」 writes it (`designModeHeaderPinsSave.ts`); 「Cancel」 drops it. + * + * @module + */ + +import * as React from 'react'; +import { + DndContext, + KeyboardSensor, + PointerSensor, + closestCenter, + useSensor, + useSensors, + type DragEndEvent, +} from '@dnd-kit/core'; +import { SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from '@dnd-kit/sortable'; +import { CSS } from '@dnd-kit/utilities'; +import { Circle, CircleDot, GripVertical, PanelTop } from 'lucide-react'; +import { toast } from 'sonner'; +import { Button, Popover, PopoverContent, PopoverTrigger, cn } from '@object-ui/components'; +import { useObjectTranslation } from '@object-ui/i18n'; +import { useMetadataClient } from '../views/metadata-admin/useMetadata.js'; +import { useDesignModeChange } from './designMode.js'; +import { + PIN_LIMIT, + movePin, + pinCandidates, + pinsChangeKey, + servedPins, + shownArrangement, + staleNames, + togglePin, + type ObjectPins, + type ShownArrangement, +} from './designModeHeaderPins.js'; +import { consoleObjectPinsDoors, saveObjectPins } from './designModeHeaderPinsSave.js'; +import type { DesignModeHeaderPinsProps } from './DesignModeHeaderPins.js'; + +/** Both scopes of `pins` as one comparable string, whatever order its keys were set in. */ +function pinsKey(pins: ObjectPins): string { + return JSON.stringify([pins.list ?? null, pins.record ?? null]); +} + +export default function HeaderPinsPanel({ objectDef, page, actions, builtins = [] }: DesignModeHeaderPinsProps) { + const { t } = useObjectTranslation(); + const client = useMetadataClient(); + const objectName = typeof objectDef.name === 'string' ? objectDef.name : ''; + const packageId = typeof objectDef._packageId === 'string' ? objectDef._packageId : ''; + const change = useDesignModeChange(pinsChangeKey(objectName)); + const served = React.useMemo(() => servedPins(objectDef), [objectDef]); + const current = change.value ?? served; + const candidates = React.useMemo(() => pinCandidates(actions as never, page, builtins), [actions, page, builtins]); + const shown = shownArrangement(current, page, actions as never, candidates); + const stale = staleNames(current, page, candidates); + const labelOf = React.useCallback( + (id: string) => candidates.find((c) => c.id === id)?.label ?? id, + [candidates], + ); + const { pinned, more } = shown; + + const texts = React.useMemo( + () => ({ + notListed: t('designMode.pins.notListed', { + defaultValue: "This object's package is not listed, so its header buttons cannot be saved.", + }), + pendingDraft: t('designMode.pins.pendingDraft', { + defaultValue: 'This object has unpublished changes in Studio. Publish or discard them there, then save again.', + }), + pairNotWritable: t('designMode.pins.pairNotWritable', { + defaultValue: "This app's customization package cannot be written, so its header buttons cannot be saved.", + }), + unknown: (name: string) => + t('designMode.pins.unknown', { name, defaultValue: '"{{name}}" is no longer an action of this object. Unpin it, then save again.' }), + notPlaced: (name: string) => + t('designMode.pins.notPlaced', { name, defaultValue: '"{{name}}" is no longer offered on this page. Unpin it, then save again.' }), + }), + [t], + ); + const stage = change.stage; + const unstage = change.unstage; + const update = React.useCallback( + (nextShown: ShownArrangement) => { + // An arrangement that draws as the served one does is the served arm + // (or none), so moving back stages nothing. + const servedShown = shownArrangement(served, page, actions as never, candidates); + const asServed = JSON.stringify(servedShown) === JSON.stringify(nextShown); + const { [page]: _dropped, ...otherScope } = current; + const next: ObjectPins = asServed + ? { ...otherScope, ...(served[page] ? { [page]: served[page] } : {}) } + : { ...current, [page]: { pinned: nextShown.pinned, more: nextShown.more } }; + if (pinsKey(next) === pinsKey(served)) { + unstage(); + return; + } + stage(next, (value) => + saveObjectPins({ objectName, packageId, served: objectDef, pins: value }, texts, consoleObjectPinsDoors(client as never)), + ); + }, + [current, page, served, actions, candidates, stage, unstage, objectName, packageId, objectDef, texts, client], + ); + + const toggle = (id: string) => { + const next = togglePin(shown, id); + if (next === null) { + toast.info( + t('designMode.pins.full', { + cap: PIN_LIMIT, + defaultValue: 'At most {{cap}} buttons are pinned to the header. Unpin one first.', + }), + ); + return; + } + update(next); + }; + + const sensors = useSensors( + useSensor(PointerSensor, { activationConstraint: { distance: 5 } }), + useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }), + ); + // One list per part: a drag reorders within its own part; the dot moves + // between them. + const onDragEnd = (part: 'pinned' | 'more') => (event: DragEndEvent) => { + const list = shown[part]; + const from = list.indexOf(String(event.active.id)); + const to = event.over ? list.indexOf(String(event.over.id)) : -1; + if (from < 0 || to < 0 || from === to) return; + update({ ...shown, [part]: movePin(list, from, to) }); + }; + + return ( + + + + + +
+

+ {t('designMode.pins.pinned', { defaultValue: 'Pinned to header' })} + {`${pinned.length}/${PIN_LIMIT}`} +

+ + +
    + {pinned.map((id) => ( + toggle(id)} t={t} /> + ))} +
+
+
+ {pinned.length === 0 && ( +

+ {t('designMode.pins.nonePinned', { defaultValue: 'No button is pinned: every action is in More.' })} +

+ )} +
+
+

+ {t('designMode.pins.other', { defaultValue: 'Other' })} +

+ + +
    + {more.map((id) => ( + toggle(id)} t={t} /> + ))} +
+
+
+ {more.length === 0 && ( +

+ {t('designMode.pins.noneOther', { defaultValue: 'Every action is pinned.' })} +

+ )} +
+ {stale.length > 0 && ( +

+ {t('designMode.pins.stale', { + names: stale.join(', '), + defaultValue: 'No longer offered here, left out when you save: {{names}}', + })} +

+ )} +
+
+ ); +} + +function ArrangedRow({ + id, + label, + pinned, + onToggle, + t, +}: { + id: string; + label: string; + pinned: boolean; + onToggle: () => void; + t: ReturnType['t']; +}) { + const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id }); + return ( +
  • + + {label} + +
  • + ); +} diff --git a/ui/packages/app-shell/src/layout/__tests__/DesignModeHeaderPins-36366.test.tsx b/ui/packages/app-shell/src/layout/__tests__/DesignModeHeaderPins-36366.test.tsx new file mode 100644 index 00000000000..dd2b878ee3b --- /dev/null +++ b/ui/packages/app-shell/src/layout/__tests__/DesignModeHeaderPins-36366.test.tsx @@ -0,0 +1,245 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The design mode's 「Header buttons」 (objectstack#36366): drawn only while + * the mode is on; it shows the scope's arrangement (the object's arm, else the + * header's own first three pinned and the rest in their default order), moves + * an action between 「Pinned to header」 and 「Other」, refuses a fourth with a + * toast, lists a name the scope no longer offers, stages the change so the + * header draws it, and 「Save」 writes the arm whole (`{ pinned, more }`). + * + * Real subjects: `DesignModeHeaderPins` (and the panel it loads), `useObjectPins`, + * `useDesignModeController`, `DesignModeProvider`, `DesignModeBar`, + * `saveObjectPins`. The metadata client and the package doors are fakes that + * record what is written. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; + +vi.mock('@object-ui/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useObjectTranslation: () => ({ + t: (k: string, o?: Record) => + String(o?.defaultValue ?? k).replace(/\{\{(\w+)\}\}/g, (_hole, name: string) => String(o?.[name] ?? '')), + language: 'en', + }), +})); + +const toastInfo = vi.hoisted(() => vi.fn()); +const toastError = vi.hoisted(() => vi.fn()); +vi.mock('sonner', async (importOriginal) => ({ + ...(await importOriginal>()), + toast: { info: toastInfo, error: toastError, success: vi.fn() }, +})); + +const written = vi.hoisted(() => [] as Array<[string, ...unknown[]]>); +const client = vi.hoisted(() => ({ + layered: async () => ({ code: { name: 'crm_lead', label: 'Lead' } }), + get: async () => ({}), + save: async (...args: unknown[]) => { + written.push(['save', ...args]); + return {}; + }, + publish: async (...args: unknown[]) => { + written.push(['publish', ...args]); + return {}; + }, + reset: async () => ({}), +})); +vi.mock('../../views/metadata-admin/useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => client, +})); +vi.mock('../../views/studio-design/packages-io', async (importOriginal) => ({ + ...(await importOriginal>()), + fetchListedPackageManifests: async () => + new Map([['com.acme.crm', { id: 'com.acme.crm', name: 'CRM', writable: true, manifest: { version: '1.0.0' } }]]), + ensureCustomizationPackage: async () => { + throw new Error('not expected'); + }, +})); + +import { DesignModeProvider, useDesignMode, useDesignModeController } from '../designMode'; +import { DesignModeBar } from '../DesignModeBar'; +import { DesignModeHeaderPins, useObjectPins } from '../DesignModeHeaderPins'; + +const ACTIONS = [ + { name: 'convert', label: 'Convert', locations: ['record_header'], order: 1 }, + { name: 'mark_won', label: 'Mark won', locations: ['record_header'], order: 2 }, + { name: 'clone', label: 'Clone', locations: ['record_header'], order: 3 }, + { name: 'log_call', label: 'Log call', locations: ['record_more'], order: 4 }, +]; + +function Harness({ objectDef }: { objectDef: Record }) { + const mode = useDesignModeController({ appName: 'crm', appBasePath: '/apps/crm', enabled: true }); + return ( + + {mode.active && } + + + + + ); +} + +/** What the page header would draw: the pins `useObjectPins` answers. */ +function HeaderReadout({ objectDef }: { objectDef: Record }) { + const pins = useObjectPins(objectDef); + return {JSON.stringify(pins)}; +} + +function Enter() { + const mode = useDesignMode(); + return ( + + ); +} + +const flush = () => act(async () => { await new Promise((r) => setTimeout(r, 0)); }); +const SERVED = { name: 'crm_lead', _packageId: 'com.acme.crm', actions: ACTIONS }; + +function start(objectDef: Record = SERVED, enter = true) { + render( + + + , + ); + if (enter) fireEvent.click(screen.getByText('enter')); +} + +async function openPanel() { + // The panel is loaded once the mode is on. + fireEvent.click(await screen.findByTestId('design-header-pins', {}, { timeout: 5000 })); + await flush(); + return screen.getByTestId('design-header-pins-panel'); +} + +/** The ids listed in a section of the panel, in order. */ +function listed(section: 'pinned' | 'other'): string[] { + return [...screen.getByTestId(`design-header-pins-${section}`).querySelectorAll('li')].map((li) => + (li.getAttribute('data-testid') ?? '').slice('design-header-pin-'.length), + ); +} + +const toggle = (id: string) => fireEvent.click(within(screen.getByTestId(`design-header-pin-${id}`)).getByTestId('design-header-pin-toggle')); + +beforeEach(() => { + written.length = 0; + toastInfo.mockReset(); + toastError.mockReset(); +}); +afterEach(cleanup); + +describe('「Header buttons」 under the design mode (objectstack#36366)', () => { + it('is not drawn outside the mode, and the header draws the object as served', () => { + start({ ...SERVED, actionLayout: { record: { pinned: ['clone'] } } }, false); + expect(screen.queryByTestId('design-header-pins')).toBeNull(); + expect(screen.getByTestId('header-pins').textContent).toBe('{"record":{"pinned":["clone"]}}'); + }); + + it("with no pins set it shows the header's own first three as pinned, the rest under Other, 3/3", async () => { + start(); + await openPanel(); + expect(listed('pinned')).toEqual(['convert', 'mark_won', 'clone']); + expect(listed('other')).toEqual(['log_call']); + expect(screen.getByTestId('design-header-pins-pinned')).toHaveTextContent('3/3'); + }); + + it('a fourth pin is refused with a toast and changes nothing', async () => { + start(); + await openPanel(); + toggle('log_call'); + expect(toastInfo).toHaveBeenCalledWith('At most 3 buttons are pinned to the header. Unpin one first.'); + expect(listed('pinned')).toEqual(['convert', 'mark_won', 'clone']); + expect(screen.getByTestId('design-mode-save')).toBeDisabled(); + }); + + it('moving an action is staged, the header draws it at once, and 「Save」 writes the arm whole', async () => { + start(); + await openPanel(); + toggle('mark_won'); + expect(listed('other')).toEqual(['mark_won', 'log_call']); + toggle('log_call'); + expect(listed('pinned')).toEqual(['convert', 'clone', 'log_call']); + expect(listed('other')).toEqual(['mark_won']); + expect(screen.getByTestId('header-pins').textContent).toBe( + '{"record":{"pinned":["convert","clone","log_call"],"more":["mark_won"]}}', + ); + expect(written).toEqual([]); + + fireEvent.click(screen.getByTestId('design-mode-save')); + await flush(); + await flush(); + const [save, publish] = written; + expect(save).toEqual([ + 'save', + 'object', + 'crm_lead', + { name: 'crm_lead', label: 'Lead', actionLayout: { record: { pinned: ['convert', 'clone', 'log_call'], more: ['mark_won'] } } }, + { mode: 'draft', packageId: 'com.acme.crm', ifNoneMatch: '*' }, + ]); + expect(publish).toEqual(['publish', 'object', 'crm_lead', { packageId: 'com.acme.crm' }]); + }); + + it("an object's own pins are what the panel starts from; unpinning back to them stages nothing", async () => { + start({ ...SERVED, actionLayout: { record: { pinned: ['log_call'] } } }); + await openPanel(); + expect(listed('pinned')).toEqual(['log_call']); + expect(listed('other')).toEqual(['convert', 'mark_won', 'clone']); + expect(screen.getByTestId('design-header-pins-pinned')).toHaveTextContent('1/3'); + toggle('convert'); + expect(screen.getByTestId('design-mode-save')).toBeEnabled(); + toggle('convert'); + expect(screen.getByTestId('design-mode-save')).toBeDisabled(); + }); + + it('「Cancel」 drops the change: the header draws the object as served again', async () => { + start({ ...SERVED, actionLayout: { record: { pinned: ['log_call'] } } }); + await openPanel(); + toggle('log_call'); + expect(screen.getByTestId('header-pins').textContent).toBe( + '{"record":{"pinned":[],"more":["log_call","convert","mark_won","clone"]}}', + ); + fireEvent.click(screen.getByTestId('design-mode-cancel')); + await flush(); + expect(screen.getByTestId('header-pins').textContent).toBe('{"record":{"pinned":["log_call"]}}'); + expect(written).toEqual([]); + }); + + it("「Other」 starts from the object's `more`, in its order, then the rest in the default order", async () => { + start({ ...SERVED, actionLayout: { record: { pinned: ['convert'], more: ['log_call', 'clone'] } } }); + await openPanel(); + expect(listed('pinned')).toEqual(['convert']); + expect(listed('other')).toEqual(['log_call', 'clone', 'mark_won']); + }); + + it('a name the arrangement sets that the scope no longer offers is listed as left out, and a save writes without it', async () => { + start({ ...SERVED, actionLayout: { record: { pinned: ['gone_action', 'convert'], more: ['clone'] } } }); + await openPanel(); + expect(screen.getByTestId('design-header-pins-stale')).toHaveTextContent( + 'No longer offered here, left out when you save: gone_action', + ); + expect(listed('pinned')).toEqual(['convert']); + toggle('mark_won'); + fireEvent.click(screen.getByTestId('design-mode-save')); + await flush(); + await flush(); + expect(written[0]?.[3]).toEqual({ + name: 'crm_lead', + label: 'Lead', + actionLayout: { record: { pinned: ['convert', 'mark_won'], more: ['clone', 'log_call'] } }, + }); + }); + + it('control: an arrangement every name of which is offered lists nothing as left out', async () => { + start({ ...SERVED, actionLayout: { record: { pinned: ['convert'] } } }); + await openPanel(); + expect(screen.queryByTestId('design-header-pins-stale')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/designModeHeaderPins-36366.test.ts b/ui/packages/app-shell/src/layout/__tests__/designModeHeaderPins-36366.test.ts new file mode 100644 index 00000000000..f3061ab5ce1 --- /dev/null +++ b/ui/packages/app-shell/src/layout/__tests__/designModeHeaderPins-36366.test.ts @@ -0,0 +1,140 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36366 — the pure half of the design mode's 「Header buttons」: + * what the panel shows (the object's arm, else the header's own first three + * pinned and the rest in their default order), what it offers, the names an + * arm sets that the scope no longer offers, the toggle with its limit of + * three, the reorder, and the save's refusal of a name the scope cannot draw. + */ + +import { describe, expect, it } from 'vitest'; +import { + PIN_LIMIT, + defaultPins, + headerReadsPins, + movePin, + pinCandidates, + pinsChangeKey, + pinsRefusal, + servedPins, + shownArrangement, + staleNames, + togglePin, +} from '../designModeHeaderPins'; + +const ACTIONS = [ + { name: 'log_call', label: 'Log call', locations: ['record_more'] }, + { name: 'mark_won', label: 'Mark won', locations: ['record_header'], order: 2 }, + { name: 'convert', label: 'Convert', locations: ['record_header'], order: 1 }, + { name: 'clone', label: 'Clone', locations: ['record_header'], order: 3 }, + { name: 'share', label: 'Share', locations: ['record_header'], order: 4 }, + { name: 'archive', label: 'Archive', locations: ['record_header'], component: 'action:menu' }, + { name: 'mass_assign', label: 'Assign', locations: ['list_toolbar'] }, + { name: 'new_task', label: 'New task', locations: ['list_toolbar'], variant: 'primary' }, +]; + +const TEXTS = { unknown: (n: string) => `unknown ${n}`, notPlaced: (n: string) => `not placed ${n}` }; + +describe('the header pins under the design mode (objectstack#36366)', () => { + it('one staged change per object, both scopes in it', () => { + expect(pinsChangeKey('crm_lead')).toBe('object-pins:crm_lead'); + expect(PIN_LIMIT).toBe(3); + }); + + it('reads the served arms, and nothing for an arm the object does not set', () => { + expect(servedPins({ actionLayout: { record: { pinned: ['convert'] } } })).toEqual({ record: { pinned: ['convert'] } }); + expect(servedPins({ actionLayout: { list: { pinned: [] }, record: { pinned: ['a', 7], more: ['b'] } } })).toEqual({ + list: { pinned: [] }, + record: { pinned: ['a'], more: ['b'] }, + }); + expect(servedPins({})).toEqual({}); + expect(servedPins({ actionLayout: ['convert'] })).toEqual({}); + // The old per-page array, or an arm without `pinned`, is no arm. + expect(servedPins({ actionLayout: { record: ['convert'], list: { more: ['x'] } } })).toEqual({}); + }); + + it("with no arm set the panel shows the header's own first three: by order, record_header only, never an action:menu", () => { + expect(defaultPins(ACTIONS, 'record')).toEqual(['convert', 'mark_won', 'clone']); + expect(defaultPins(ACTIONS, 'list')).toEqual(['new_task', 'mass_assign']); + const candidates = pinCandidates(ACTIONS, 'record', []); + expect(shownArrangement({}, 'record', ACTIONS, candidates)).toEqual({ + pinned: ['convert', 'mark_won', 'clone'], + more: ['log_call', 'archive', 'share'], + }); + expect(shownArrangement({ record: { pinned: ['share'] } }, 'record', ACTIONS, candidates)).toEqual({ + pinned: ['share'], + more: ['log_call', 'archive', 'convert', 'mark_won', 'clone'], + }); + expect(shownArrangement({ record: { pinned: [] } }, 'record', ACTIONS, candidates).pinned).toEqual([]); + }); + + it("「More」 shows the arm's `more` first, in its order, then every other candidate in the default order", () => { + const candidates = pinCandidates(ACTIONS, 'record', []); + expect( + shownArrangement({ record: { pinned: ['convert'], more: ['share', 'log_call', 'convert'] } }, 'record', ACTIONS, candidates), + ).toEqual({ pinned: ['convert'], more: ['share', 'log_call', 'archive', 'mark_won', 'clone'] }); + }); + + it('a name the arm sets that the scope no longer offers is left out, and listed', () => { + const candidates = pinCandidates(ACTIONS, 'record', []); + const pins = { record: { pinned: ['gone_action', 'convert'], more: ['mass_assign', 'clone'] } }; + expect(shownArrangement(pins, 'record', ACTIONS, candidates).pinned).toEqual(['convert']); + expect(shownArrangement(pins, 'record', ACTIONS, candidates).more).not.toContain('mass_assign'); + expect(staleNames(pins, 'record', candidates)).toEqual(['gone_action', 'mass_assign']); + expect(staleNames({ list: { pinned: ['$import'] } }, 'list', pinCandidates(ACTIONS, 'list', []))).toEqual([]); + expect(staleNames({}, 'record', candidates)).toEqual([]); + }); + + it("offers the page's placed actions in the header's order, then the built-ins the page has", () => { + const builtins = [ + { id: '$import', label: 'Import' }, + { id: '$export', label: 'Export' }, + ]; + expect(pinCandidates(ACTIONS, 'record', builtins).map((c) => c.id)).toEqual([ + 'log_call', + 'archive', + 'convert', + 'mark_won', + 'clone', + 'share', + ]); + expect(pinCandidates(ACTIONS, 'list', builtins).map((c) => c.id)).toEqual(['new_task', 'mass_assign', '$import', '$export']); + }); + + it('a toggle pins at the end, and unpins to the top of 「More」; a fourth is refused (null)', () => { + expect(togglePin({ pinned: ['a', 'b'], more: ['c', 'd'] }, 'c')).toEqual({ pinned: ['a', 'b', 'c'], more: ['d'] }); + expect(togglePin({ pinned: ['a', 'b', 'c'], more: ['d'] }, 'b')).toEqual({ pinned: ['a', 'c'], more: ['b', 'd'] }); + expect(togglePin({ pinned: ['a', 'b', 'c'], more: ['d'] }, 'd')).toBeNull(); + }); + + it('a reorder moves one entry of a part; an index outside it changes nothing', () => { + expect(movePin(['a', 'b', 'c'], 2, 0)).toEqual(['c', 'a', 'b']); + expect(movePin(['a', 'b', 'c'], 0, 5)).toEqual(['a', 'b', 'c']); + }); + + it("the save refuses a name, in either part, that is no action of the object or one of the other scope", () => { + const served = { actions: ACTIONS }; + expect( + pinsRefusal( + served, + { record: { pinned: ['convert'], more: ['log_call'] }, list: { pinned: ['$export'], more: ['mass_assign', '$import'] } }, + TEXTS, + ), + ).toBeNull(); + expect(pinsRefusal(served, { record: { pinned: ['ghost'] } }, TEXTS)).toBe('unknown ghost'); + expect(pinsRefusal(served, { record: { pinned: [], more: ['ghost'] } }, TEXTS)).toBe('unknown ghost'); + expect(pinsRefusal(served, { list: { pinned: ['convert'] } }, TEXTS)).toBe('not placed convert'); + expect(pinsRefusal(served, { record: { pinned: [], more: ['mass_assign'] } }, TEXTS)).toBe('not placed mass_assign'); + }); + + it('the synthesized header and placedActions read the pins; a header with its own list, or none, does not', () => { + const page = (header: Record) => ({ regions: [{ name: 'main', components: [{ type: 'page:header', properties: header }] }] }); + expect(headerReadsPins(null)).toBe(true); + expect(headerReadsPins({ regions: [{ name: 'main', components: [{ type: 'record:details' }] }] })).toBe(true); + expect(headerReadsPins(page({ placedActions: true }))).toBe(true); + expect(headerReadsPins(page({ actions: ['convert', 'clone'] }))).toBe(false); + expect(headerReadsPins(page({ subtitle: 'no actions' }))).toBe(false); + expect(headerReadsPins({ header: { type: 'page:header', actions: [] } })).toBe(false); + }); +}); diff --git a/ui/packages/app-shell/src/layout/__tests__/designModeHeaderPinsSave-36366.test.ts b/ui/packages/app-shell/src/layout/__tests__/designModeHeaderPinsSave-36366.test.ts new file mode 100644 index 00000000000..12cf464cd87 --- /dev/null +++ b/ui/packages/app-shell/src/layout/__tests__/designModeHeaderPinsSave-36366.test.ts @@ -0,0 +1,236 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36366 — the write behind the design mode's 「Save」 for an + * object's pinned header actions: the object's own package when it is + * writable, else the installed object's customization (`object_extension`), + * published at once, never over a pending draft, and never with a name the + * header cannot draw. + */ + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const emitMetadataRefresh = vi.hoisted(() => vi.fn()); +vi.mock('../../assistant/assistantBus', async (importOriginal) => ({ + ...(await importOriginal>()), + emitMetadataRefresh, +})); + +import { saveObjectPins, type ObjectPinsSaveDoors } from '../designModeHeaderPinsSave'; +import type { ObjectPins } from '../designModeHeaderPins'; + +const TEXTS = { + notListed: 'not listed', + pendingDraft: 'pending draft', + pairNotWritable: 'pair not writable', + unknown: (n: string) => `unknown ${n}`, + notPlaced: (n: string) => `not placed ${n}`, +}; + +/** The object as served: every package's actions folded in. */ +const SERVED = { + name: 'crm_lead', + label: 'Lead', + _packageId: 'com.acme.crm', + actions: [ + { name: 'convert', locations: ['record_header'] }, + { name: 'log_call', locations: ['record_more'] }, + { name: 'mass_assign', locations: ['list_toolbar'] }, + ], +}; + +function doors(opts: { + writable: boolean; + layers?: unknown; + extension?: unknown; + pairWritable?: boolean; + save?: () => Promise; + publish?: () => Promise; +}) { + const calls: Array<[string, ...unknown[]]> = []; + const d: ObjectPinsSaveDoors = { + listPackages: async () => + new Map([['com.acme.crm', { id: 'com.acme.crm', name: 'CRM', writable: opts.writable, manifest: { version: '1.0.0' } }]]), + ensureCustomization: async (base) => { + calls.push(['ensure', base]); + return { basePackageId: base, packageId: `${base}.custom`, namespace: 'crm_custom', created: false, writable: opts.pairWritable ?? true }; + }, + client: { + layered: async (...args) => { + calls.push(['layered', ...args]); + return opts.layers ?? null; + }, + get: async (...args) => { + calls.push(['get', ...args]); + // The console's client answers `null` for an item that is not there. + return opts.extension === undefined ? null : opts.extension; + }, + save: async (...args) => { + calls.push(['save', ...args]); + return opts.save ? opts.save() : {}; + }, + publish: async (...args) => { + calls.push(['publish', ...args]); + return opts.publish ? opts.publish() : {}; + }, + reset: async (...args) => { + calls.push(['reset', ...args]); + return {}; + }, + }, + }; + return { d, calls }; +} + +const input = (pins: ObjectPins) => ({ objectName: 'crm_lead', packageId: 'com.acme.crm', served: SERVED, pins }); + +beforeEach(() => emitMetadataRefresh.mockReset()); + +describe('saving the header pins (objectstack#36366)', () => { + it('a writable package: the object as its author wrote it, with the new pins, saved as a draft and published', async () => { + const authored = { name: 'crm_lead', label: 'Lead', actions: [{ name: 'convert', locations: ['record_header'] }] }; + const { d, calls } = doors({ writable: true, layers: { code: authored } }); + await saveObjectPins(input({ record: { pinned: ['log_call', 'convert'] } }), TEXTS, d); + expect(calls).toEqual([ + ['layered', 'object', 'crm_lead', { packageId: 'com.acme.crm' }], + [ + 'save', + 'object', + 'crm_lead', + { ...authored, actionLayout: { record: { pinned: ['log_call', 'convert'] } } }, + { mode: 'draft', packageId: 'com.acme.crm', ifNoneMatch: '*' }, + ], + ['publish', 'object', 'crm_lead', { packageId: 'com.acme.crm' }], + ]); + expect(emitMetadataRefresh).toHaveBeenCalledTimes(1); + }); + + it("an installed (read-only) package: a new object_extension in its customization package, carrying no `name`", async () => { + const { d, calls } = doors({ writable: false }); + await saveObjectPins(input({ list: { pinned: ['$export', 'mass_assign'] } }), TEXTS, d); + expect(calls).toEqual([ + ['ensure', 'com.acme.crm'], + ['get', 'object_extension', 'crm_lead', { packageId: 'com.acme.crm.custom' }], + ['layered', 'object', 'crm_lead', { packageId: 'com.acme.crm' }], + [ + 'save', + 'object_extension', + 'crm_lead', + { extend: 'crm_lead', actionLayout: { list: { pinned: ['$export', 'mass_assign'] } } }, + { mode: 'draft', packageId: 'com.acme.crm.custom', ifNoneMatch: '*' }, + ], + ['publish', 'object_extension', 'crm_lead', { packageId: 'com.acme.crm.custom' }], + ]); + }); + + it('an installed package whose extension is already published keeps what it holds, and replaces only the pins', async () => { + const extension = { + extend: 'crm_lead', + fields: { score__c: { type: 'number' } }, + actionLayout: { record: { pinned: ['convert'] } }, + _packageId: 'com.acme.crm.custom', + }; + const { d, calls } = doors({ writable: false, extension }); + await saveObjectPins(input({ record: { pinned: ['log_call'] } }), TEXTS, d); + const save = calls.find((c) => c[0] === 'save'); + expect(save?.[3]).toEqual({ extend: 'crm_lead', fields: { score__c: { type: 'number' } }, actionLayout: { record: { pinned: ['log_call'] } } }); + }); + + it('S3: only the arm the administrator changed is written: the served arm of another scope is not copied in', async () => { + const served = { ...SERVED, actionLayout: { list: { pinned: ['mass_assign'] }, record: { pinned: ['log_call'] } } }; + const { d, calls } = doors({ writable: false }); + await saveObjectPins( + { ...input({ list: { pinned: ['mass_assign'] }, record: { pinned: ['convert'] } }), served }, + TEXTS, + d, + ); + const save = calls.find((c) => c[0] === 'save'); + expect(save?.[3]).toEqual({ extend: 'crm_lead', actionLayout: { record: { pinned: ['convert'] } } }); + }); + + it('S3: an arm the target document already holds for an unchanged scope stays as it holds it', async () => { + const served = { ...SERVED, actionLayout: { list: { pinned: ['mass_assign'] }, record: { pinned: ['log_call'] } } }; + const extension = { extend: 'crm_lead', actionLayout: { list: { pinned: ['mass_assign'] } } }; + const { d, calls } = doors({ writable: false, extension }); + await saveObjectPins( + { ...input({ list: { pinned: ['mass_assign'] }, record: { pinned: [], more: ['convert'] } }), served }, + TEXTS, + d, + ); + const save = calls.find((c) => c[0] === 'save'); + expect(save?.[3]).toEqual({ + extend: 'crm_lead', + actionLayout: { list: { pinned: ['mass_assign'] }, record: { pinned: [], more: ['convert'] } }, + }); + }); + + it('S3: a staged value that arranges as the object is served writes nothing', async () => { + const served = { ...SERVED, actionLayout: { record: { pinned: ['log_call'] } } }; + const { d, calls } = doors({ writable: true }); + await saveObjectPins({ ...input({ record: { pinned: ['log_call'] } }), served }, TEXTS, d); + expect(calls).toEqual([]); + }); + + it('S4: a built-in is only ever pinned: `more` is written with action names only', async () => { + const { d, calls } = doors({ writable: false }); + await saveObjectPins(input({ list: { pinned: ['mass_assign'], more: ['$import', '$export'] } }), TEXTS, d); + const save = calls.find((c) => c[0] === 'save'); + expect(save?.[3]).toEqual({ extend: 'crm_lead', actionLayout: { list: { pinned: ['mass_assign'], more: [] } } }); + }); + + it('S5: an installed object is written through the one writer of its arrangement: a pair the server answers not writable is refused before anything is read or written to it', async () => { + const { d, calls } = doors({ writable: false, pairWritable: false }); + await expect(saveObjectPins(input({ record: { pinned: ['convert'] } }), TEXTS, d)).rejects.toThrow('pair not writable'); + expect(calls).toEqual([['ensure', 'com.acme.crm']]); + expect(emitMetadataRefresh).not.toHaveBeenCalled(); + }); + + it('S5: through the one writer, every key the stored extension holds is kept, and a landed publish announces itself', async () => { + const extension = { + extend: 'crm_lead', + relatedLists: [{ objectName: 'crm_task', relationshipField: 'lead' }], + fieldGroups: [{ key: 'main', fields: ['name'] }], + actionLayout: { list: { pinned: ['mass_assign'] } }, + }; + const { d, calls } = doors({ writable: false, extension }); + await saveObjectPins(input({ record: { pinned: ['convert'] } }), TEXTS, d); + const save = calls.find((c) => c[0] === 'save'); + expect(save?.[3]).toEqual({ + ...extension, + actionLayout: { list: { pinned: ['mass_assign'] }, record: { pinned: ['convert'] } }, + }); + expect(calls.at(-1)).toEqual(['publish', 'object_extension', 'crm_lead', { packageId: 'com.acme.crm.custom' }]); + expect(emitMetadataRefresh).toHaveBeenCalledTimes(1); + }); + + it('a name the header cannot draw is refused before anything is read or written, with its reason', async () => { + const { d, calls } = doors({ writable: true }); + await expect(saveObjectPins(input({ record: { pinned: ['ghost'] } }), TEXTS, d)).rejects.toThrow('unknown ghost'); + await expect(saveObjectPins(input({ list: { pinned: ['convert'] } }), TEXTS, d)).rejects.toThrow('not placed convert'); + expect(calls).toEqual([]); + }); + + it('a package the server does not list is refused', async () => { + const { d } = doors({ writable: true }); + await expect(saveObjectPins({ ...input({ record: { pinned: ['convert'] } }), packageId: 'com.other' }, TEXTS, d)).rejects.toThrow('not listed'); + }); + + it("a draft already pending (the object's, or the extension's) is not overwritten nor published: the save says so", async () => { + const own = doors({ writable: true, layers: { code: { name: 'crm_lead' }, draft: { name: 'crm_lead' } } }); + await expect(saveObjectPins(input({ record: { pinned: ['convert'] } }), TEXTS, own.d)).rejects.toThrow('pending draft'); + expect(own.calls.map((c) => c[0])).toEqual(['layered']); + + const conflict = Object.assign(new Error('conflict'), { status: 409, code: 'METADATA_CONFLICT' }); + const pair = doors({ writable: false, save: () => Promise.reject(conflict) }); + await expect(saveObjectPins(input({ record: { pinned: ['convert'] } }), TEXTS, pair.d)).rejects.toThrow('pending draft'); + expect(pair.calls.map((c) => c[0])).toEqual(['ensure', 'get', 'layered', 'save']); + expect(emitMetadataRefresh).not.toHaveBeenCalled(); + }); + + it('a refused publish discards the draft this save wrote, and the refusal is passed on', async () => { + const refusal = new Error('refused'); + const { d, calls } = doors({ writable: true, layers: { code: { name: 'crm_lead' } }, publish: () => Promise.reject(refusal) }); + await expect(saveObjectPins(input({ record: { pinned: ['convert'] } }), TEXTS, d)).rejects.toBe(refusal); + expect(calls.at(-1)).toEqual(['reset', 'object', 'crm_lead', { state: 'draft', packageId: 'com.acme.crm' }]); + }); +}); diff --git a/ui/packages/app-shell/src/layout/designModeHeaderPins.ts b/ui/packages/app-shell/src/layout/designModeHeaderPins.ts new file mode 100644 index 00000000000..5b16ed6579d --- /dev/null +++ b/ui/packages/app-shell/src/layout/designModeHeaderPins.ts @@ -0,0 +1,256 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The header's action arrangement under the design mode (objectstack#36366): + * which of a scope's actions its header draws as buttons, at most three, in + * order, and the order of the rest in its 「More」 menu. Pure functions of the + * object as served; the panel (`DesignModeHeaderPins.tsx`) draws them and the + * save (`designModeHeaderPinsSave.ts`) writes them. + * + * The setting is the object's `actionLayout` (`@objectstack/spec`), one arm + * per action scope, `{ pinned, more }`: `list` for the list page toolbar, + * `record` for the record header (record page, side preview, phone bar). An + * arm the object does not set leaves that header's own choice: the first three + * of its buttons by each action's `order`, which is what the panel shows as + * pinned until the administrator changes it, and the rest in that order. + * + * @module + */ + +import { + OBJECT_ACTION_LAYOUT_BUILTINS, + OBJECT_ACTION_LAYOUT_PINNED_LIMIT, + type ObjectActionLayoutScope, +} from '@objectstack/spec/data'; +import { actionRendersAt, readActionLayoutArm, type ActionLayoutArm } from '@object-ui/types'; + +export type PinPage = ObjectActionLayoutScope; + +/** One scope's arrangement: the buttons, then the 「More」 menu's order. */ +export type PinArm = ActionLayoutArm; + +/** An object's arrangement for both scopes: the `actionLayout` value written. */ +export interface ObjectPins { + readonly list?: PinArm; + readonly record?: PinArm; +} + +/** One scope's arrangement as the panel shows it: every candidate, either pinned or in 「More」. */ +export interface ShownArrangement { + readonly pinned: string[]; + readonly more: string[]; +} + +/** One thing the panel can arrange: an action of the object, or a scope built-in (`$import`). */ +export interface PinCandidate { + readonly id: string; + readonly label: string; +} + +/** The most a header pins (`OBJECT_ACTION_LAYOUT_PINNED_LIMIT`, 3). */ +export const PIN_LIMIT = OBJECT_ACTION_LAYOUT_PINNED_LIMIT; + +/** The design mode's key for the arrangement of `objectName`: one staged change per object, both scopes in it. */ +export function pinsChangeKey(objectName: string): string { + return `object-pins:${objectName}`; +} + +type PinnableAction = { + readonly name?: unknown; + readonly label?: unknown; + readonly locations?: readonly string[]; + readonly order?: unknown; + readonly variant?: unknown; + readonly component?: unknown; +}; + +/** The locations whose actions a scope's header places. */ +const PAGE_LOCATIONS: Readonly> = { + list: ['list_toolbar'], + record: ['record_header', 'record_more'], +}; + +/** Whether `action` is placed in `page`'s scope. */ +export function placedOnPage(action: PinnableAction, page: PinPage): boolean { + return PAGE_LOCATIONS[page].some((location) => actionRendersAt(action as never, location)); +} + +/** The object's `actionLayout` as served (`{}` when it arranges nothing). */ +export function servedPins(objectDef: unknown): ObjectPins { + const raw = (objectDef as { actionLayout?: unknown } | null | undefined)?.actionLayout; + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}; + const list = readActionLayoutArm((raw as Record).list); + const record = readActionLayoutArm((raw as Record).record); + return { ...(list ? { list } : {}), ...(record ? { record } : {}) }; +} + +/** The header's own sort: `order` ascending (unset 0), `variant: 'primary'` first among equals, then incoming order. */ +function headerSort(actions: readonly T[]): T[] { + const rank = (a: PinnableAction) => (typeof a.order === 'number' ? a.order : 0); + return [...actions].sort((a, b) => { + const byOrder = rank(a) - rank(b); + if (byOrder !== 0) return byOrder; + return (a.variant === 'primary' ? 0 : 1) - (b.variant === 'primary' ? 0 : 1); + }); +} + +/** + * What the header draws as buttons while the object sets no arm for `page`: + * the first three of its row's actions by the header's own sort. On the record + * page the row's actions are those placed at `record_header` (one placed at + * `record_more` only is in ⋯ already); an action authored into ⋯ + * (`component: 'action:menu'`) is never a button. + */ +export function defaultPins(actions: readonly PinnableAction[], page: PinPage): string[] { + const row = actions.filter( + (a) => + typeof a.name === 'string' && + a.component !== 'action:menu' && + (page === 'list' ? actionRendersAt(a as never, 'list_toolbar') : actionRendersAt(a as never, 'record_header')), + ); + return headerSort(row) + .slice(0, PIN_LIMIT) + .map((a) => a.name as string); +} + +/** + * Everything the panel offers for `page`, in the header's own order (the + * default order of 「More」): the scope's placed actions, then its built-ins + * that this reader is offered. + */ +export function pinCandidates( + actions: readonly PinnableAction[], + page: PinPage, + builtins: readonly PinCandidate[], +): PinCandidate[] { + const seen = new Set(); + const out: PinCandidate[] = []; + for (const action of headerSort(actions.filter((a) => placedOnPage(a, page)))) { + const name = typeof action.name === 'string' ? action.name : ''; + if (!name || seen.has(name)) continue; + seen.add(name); + out.push({ id: name, label: typeof action.label === 'string' && action.label ? action.label : name }); + } + const allowed = new Set(OBJECT_ACTION_LAYOUT_BUILTINS[page]); + for (const builtin of builtins) if (allowed.has(builtin.id) && !seen.has(builtin.id)) out.push(builtin); + return out; +} + +/** + * The arrangement as the panel shows it, over `candidates` (in their default + * order): the arm set (staged or served), else the header's default. Pinned + * are the arm's `pinned` this reader is offered; 「More」 is every other + * candidate, the ones the arm's `more` names first, in that order, then the + * rest in the default order. + */ +export function shownArrangement( + pins: ObjectPins, + page: PinPage, + actions: readonly PinnableAction[], + candidates: readonly PinCandidate[], +): ShownArrangement { + const ids = new Set(candidates.map((c) => c.id)); + const arm = pins[page]; + const pinned = (arm ? [...arm.pinned] : defaultPins(actions, page)).filter((id) => ids.has(id)); + const taken = new Set(pinned); + const more: string[] = []; + for (const id of [...(arm?.more ?? []), ...candidates.map((c) => c.id)]) { + if (!ids.has(id) || taken.has(id)) continue; + taken.add(id); + more.push(id); + } + return { pinned: [...new Set(pinned)], more }; +} + +/** + * The names the arm for `page` sets that this scope no longer offers (an + * action the package removed, or one no longer placed here): the panel says + * they are left out, and a save writes the arrangement without them. The + * `$` built-ins are not judged: one this reader is not offered (no import + * permission) is still the scope's. + */ +export function staleNames(pins: ObjectPins, page: PinPage, candidates: readonly PinCandidate[]): string[] { + const arm = pins[page]; + if (!arm) return []; + const ids = new Set(candidates.map((c) => c.id)); + return [...new Set([...arm.pinned, ...(arm.more ?? [])])].filter((name) => !name.startsWith('$') && !ids.has(name)); +} + +/** + * `shown` with `id` moved between its two parts: a pinned one to the top of + * 「More」, one in 「More」 to the end of the pinned ones. `null` when the + * header is full. + */ +export function togglePin(shown: ShownArrangement, id: string): ShownArrangement | null { + if (shown.pinned.includes(id)) { + return { pinned: shown.pinned.filter((pin) => pin !== id), more: [id, ...shown.more.filter((m) => m !== id)] }; + } + if (shown.pinned.length >= PIN_LIMIT) return null; + return { pinned: [...shown.pinned, id], more: shown.more.filter((m) => m !== id) }; +} + +/** `list` with the entry at `from` moved to `to`. */ +export function movePin(list: readonly string[], from: number, to: number): string[] { + if (from === to || from < 0 || to < 0 || from >= list.length || to >= list.length) return [...list]; + const next = [...list]; + const [moved] = next.splice(from, 1); + next.splice(to, 0, moved); + return next; +} + +/** + * Why `pins` cannot be saved on `objectDef` as served, or `null`: a name, in + * either part of an arm, that is no action of the object, or one not placed + * in the scope its arm arranges (`@objectstack/lint`'s + * `validateObjectActionLayout`, asked of the object as served, every + * package's actions included). `$` built-ins are the schema's. + */ +export function pinsRefusal( + objectDef: unknown, + pins: ObjectPins, + texts: { unknown: (name: string) => string; notPlaced: (name: string) => string }, +): string | null { + const actions = Array.isArray((objectDef as { actions?: unknown } | null)?.actions) + ? ((objectDef as { actions: PinnableAction[] }).actions) + : []; + for (const page of ['list', 'record'] as const) { + const arm = pins[page]; + for (const name of [...(arm?.pinned ?? []), ...(arm?.more ?? [])]) { + if (name.startsWith('$')) continue; + const action = actions.find((a) => a.name === name); + if (!action) return texts.unknown(name); + if (!placedOnPage(action, page)) return texts.notPlaced(name); + } + } + return null; +} + +/** + * Whether a record page's header reads the object's pins: the synthesized + * header (no authored page, or one with no `page:header` node of its own, as + * a slotted page that leaves its header slot alone), or an authored + * `page:header` with `placedActions: true`. A `page:header` authored with its + * own `actions` list keeps that list, and one with neither draws none of the + * object's actions: neither reads pins, so the design mode offers no + * 「Header buttons」 on them. + */ +export function headerReadsPins(page: unknown): boolean { + const headers: Record[] = []; + const seen = new Set(); + const walk = (node: unknown): void => { + if (node === null || typeof node !== 'object' || seen.has(node)) return; + seen.add(node); + if (Array.isArray(node)) { + node.forEach(walk); + return; + } + const rec = node as Record; + if (rec.type === 'page:header') headers.push(rec); + Object.values(rec).forEach(walk); + }; + walk(page); + return headers.every((h) => { + const props = (h.properties ?? {}) as Record; + return (h.placedActions ?? props.placedActions) === true && (h.actions ?? props.actions) === undefined; + }); +} diff --git a/ui/packages/app-shell/src/layout/designModeHeaderPinsSave.ts b/ui/packages/app-shell/src/layout/designModeHeaderPinsSave.ts new file mode 100644 index 00000000000..ac3e580ae78 --- /dev/null +++ b/ui/packages/app-shell/src/layout/designModeHeaderPinsSave.ts @@ -0,0 +1,187 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The write behind the design mode's 「Save」 for an object's action + * arrangement (objectstack#36366): the object's `actionLayout`, written into + * its customization layer and published at once, so everyone sees it. Only + * the arms the administrator changed are written, each whole + * (`{ pinned, more }`): an arm the staged value carries as the object serves + * it is left as the target document holds it (or absent), so the served arm + * of the base or of another layer is never copied in, where it would mask a + * later change of its owner. The pair's arm replaces the object's arm whole + * in the fold, and removing it restores the package's own. A built-in + * (`$import`) is only ever pinned, so `more` is written with action names + * only. + * + * Where it is written follows ADR-0146 D10 (objects are extended, never + * replaced), as Studio's object editing does: + * + * - the object's own package when the server lists it writable: the object as + * its author wrote it (`overlay ?? code` of its layered read, never the + * served object, which folds other packages' actions and fields in), with + * the new `actionLayout`; + * - else the base's paired customization package: `actionLayout` is one of + * the keys `CUSTOM_ARRANGEMENT_KEYS` names, so this save is a caller of the + * one writer of an installed object's arrangement + * (`saveObjectExtensionArrangement`, `../views/objectExtensionArrangementSave.ts`), + * never a second writer: it asks the ensure door for the pair, refuses a pair + * the server does not list writable, and keeps every key the pair's stored + * extension holds. This module only composes the `actionLayout` it hands + * over, from the one the stored extension holds. The fold carries it onto + * the object. + * + * How it is written is the runtime's confirmed-save rule, as the app menu's + * save (`designModeMenuSave.ts`) and the one writer: the draft is written with + * the first-write pin, so a draft somebody left pending is refused, never + * overwritten nor published on its saver's behalf, and the refusal is said; a + * publish the server refuses discards the draft this save wrote. A landed + * publish announces itself (`emitMetadataRefresh`), and the console re-reads + * the object. + * + * Before anything is written, every name of both parts is checked against the + * object as served (every package's actions): a name that is no action of the + * object, or one not placed in that arm's scope, is refused with its reason. + * (More than three pinned, and a name in both parts, the schema refuses at + * the server's door, with its own reason.) + * + * @module + */ + +import type { ObjectActionLayout } from '@objectstack/spec/data'; +import { emitMetadataRefresh } from '../assistant/assistantBus.js'; +import { isDraftVersionConflict } from '../views/metadata-admin/DraftConflictDialog.js'; +import { authoredPublished, type AuthoredLayers } from '../views/metadata-admin/authoredObjectBuffer.js'; +import { saveObjectExtensionArrangement } from '../views/objectExtensionArrangementSave.js'; +import { + ensureCustomizationPackage, + fetchListedPackageManifests, + type EnsuredCustomizationPackage, + type ListedPackageManifest, +} from '../views/studio-design/packages-io.js'; +import { pinsRefusal, servedPins, type ObjectPins, type PinPage } from './designModeHeaderPins.js'; + +/** The doors the save goes through; the defaults are the console's own. */ +export interface ObjectPinsSaveDoors { + readonly listPackages: () => Promise>; + readonly ensureCustomization: (basePackageId: string) => Promise; + readonly client: { + layered: (type: string, name: string, options: { packageId?: string }) => Promise; + get: (type: string, name: string, options?: Record) => Promise; + save: (type: string, name: string, body: unknown, options: Record) => Promise; + publish: (type: string, name: string, options: { packageId?: string }) => Promise; + reset: (type: string, name: string, options: Record) => Promise; + }; +} + +/** The sentences a refused save is said with, in the viewer's language. */ +export interface ObjectPinsSaveTexts { + /** The object's package is not one the server lists. */ + readonly notListed: string; + /** A draft of the object (or of its extension) is already pending. */ + readonly pendingDraft: string; + /** The customization package the server answered for an installed object is not writable. */ + readonly pairNotWritable: string; + /** `name` is no action of the object. */ + readonly unknown: (name: string) => string; + /** `name` is an action of the object not placed in that arm's scope. */ + readonly notPlaced: (name: string) => string; +} + +/** One arm as written: its `pinned`, and its `more` (action names only, a built-in being only ever pinned) when it has one. */ +function armValue(arm: NonNullable): NonNullable { + const more = arm.more?.filter((name) => !name.startsWith('$')); + return more ? { pinned: [...arm.pinned], more } : { pinned: [...arm.pinned] }; +} + +const SCOPES: readonly PinPage[] = ['list', 'record']; + +/** One arm as compared: absent and a value are different arrangements. */ +function armKey(arm: ObjectPins['list']): string { + return arm ? JSON.stringify(armValue(arm)) : ''; +} + +/** The scopes whose arm `pins` stages differently from the arm the object is served with. */ +export function changedScopes(pins: ObjectPins, served: unknown): PinPage[] { + const before = servedPins(served); + return SCOPES.filter((scope) => armKey(pins[scope]) !== armKey(before[scope])); +} + +/** + * The `actionLayout` the target document is written with: the one it holds, + * with each changed scope's arm as staged (taken off where the staged value + * has none). `undefined` when it then arranges nothing. + */ +function actionLayoutValue(held: unknown, pins: ObjectPins, changed: readonly PinPage[]): ObjectActionLayout | undefined { + const out: Record = + held && typeof held === 'object' && !Array.isArray(held) ? { ...(held as Record) } : {}; + for (const scope of changed) { + const arm = pins[scope]; + if (arm) out[scope] = armValue(arm); + else delete out[scope]; + } + return Object.keys(out).length > 0 ? (out as ObjectActionLayout) : undefined; +} + +/** `body` with its `actionLayout` set to `layout`, or without the key when `layout` is `undefined`. */ +function withActionLayout(body: Record, layout: ObjectActionLayout | undefined): Record { + const { actionLayout: _held, ...rest } = body; + return layout ? { ...rest, actionLayout: layout } : rest; +} + +/** Save `pins` as the action layout of the object `objectName` of the package `packageId`, and publish them. */ +export async function saveObjectPins( + input: { objectName: string; packageId: string; served: unknown; pins: ObjectPins }, + texts: ObjectPinsSaveTexts, + doors: ObjectPinsSaveDoors, +): Promise { + const { objectName, packageId, served, pins } = input; + const refusal = pinsRefusal(served, pins, texts); + if (refusal) throw new Error(refusal); + const changed = changedScopes(pins, served); + if (changed.length === 0) return; + const manifests = await doors.listPackages(); + const listed = manifests.get(packageId); + if (!listed) throw new Error(texts.notListed); + + if (!listed.writable) { + // An installed object: the one writer of its arrangement writes the pair. + await saveObjectExtensionArrangement( + { + objectName, + basePackageId: packageId, + arrange: ({ extension }) => ({ actionLayout: actionLayoutValue(extension?.actionLayout, pins, changed) }), + }, + { notListed: texts.notListed, pendingDraft: texts.pendingDraft, notWritable: texts.pairNotWritable }, + { ...doors, listPackages: async () => manifests, refreshed: emitMetadataRefresh }, + ); + return; + } + + const layers = (await doors.client.layered('object', objectName, { packageId })) as AuthoredLayers | null; + if (layers && 'draft' in layers && layers.draft) throw new Error(texts.pendingDraft); + const authored = authoredPublished('object', layers) as Record; + const body = withActionLayout({ ...authored, name: objectName }, actionLayoutValue(authored.actionLayout, pins, changed)); + try { + await doors.client.save('object', objectName, body, { mode: 'draft', packageId, ifNoneMatch: '*' }); + } catch (err) { + if (isDraftVersionConflict(err)) throw Object.assign(new Error(texts.pendingDraft), { cause: err }); + throw err; + } + try { + await doors.client.publish('object', objectName, { packageId }); + } catch (err) { + try { + await doors.client.reset('object', objectName, { state: 'draft', packageId }); + } catch (discardErr) { + console.error('[design-mode] a refused publish left the action layout draft pending:', discardErr); + } + emitMetadataRefresh(); + throw err; + } + emitMetadataRefresh(); +} + +/** The console's doors, around `client` (`useMetadataClient()`). */ +export function consoleObjectPinsDoors(client: ObjectPinsSaveDoors['client']): ObjectPinsSaveDoors { + return { listPackages: fetchListedPackageManifests, ensureCustomization: ensureCustomizationPackage, client }; +} diff --git a/ui/packages/app-shell/src/views/RecordDetailView.actionLayout-36366.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.actionLayout-36366.test.tsx new file mode 100644 index 00000000000..adc3e869fcc --- /dev/null +++ b/ui/packages/app-shell/src/views/RecordDetailView.actionLayout-36366.test.tsx @@ -0,0 +1,248 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36366 — the object's record-page pins (`actionLayout.record`) + * choose the record header's buttons, in order; every other placed action is + * in the header's ⋯. Both record headers read them: the synthesized default + * page's (`RecordDetailView`'s header list) and an authored `page:header` with + * `placedActions: true` (`PageHeaderActions`). No pins: each header draws as + * before (the control). A header authored with its own `actions` list keeps + * that list, and the design mode offers it no 「Header buttons」. + * + * Read through the real `RecordDetailView` → `page:header` renderer → + * `PageHeaderActions`, embedded as `ObjectView`'s drawer mounts it (the drawer + * keeps three inline buttons, so inline and ⋯ are told apart). + */ + +import * as React from 'react'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import type { MockInstance } from 'vitest'; +import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { MemoryRouter } from 'react-router-dom'; + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: null, activeOrganization: null }), + createAuthenticatedFetch: () => vi.fn(), +})); +vi.mock('@object-ui/collaboration', async (importOriginal) => ({ + ...(await importOriginal>()), + useRecordPresence: () => [], + PresenceAvatars: () => null, +})); +vi.mock('sonner', () => ({ + toast: Object.assign(vi.fn(), { + success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn(), loading: vi.fn(), dismiss: vi.fn(), + }), +})); +vi.mock('./ActionParamDialog', () => ({ ActionParamDialog: () => null })); +vi.mock('./ActionResultDialog', () => ({ ActionResultDialog: () => null })); +vi.mock('./FlowRunner', () => ({ FlowRunner: () => null })); +vi.mock('./MetadataInspector', () => ({ + MetadataPanel: () => null, + useMetadataInspector: () => ({ showDebug: false, toggle: () => {} }), +})); + +import { I18nProvider } from '@object-ui/i18n'; +import { MetadataCtx } from '@object-ui/react'; +import { RecordDetailView } from './RecordDetailView'; +import { FavoritesProvider } from '../context/FavoritesProvider'; +import { DesignModeProvider } from '../layout/designMode'; + +const RECORD_ID = 'rec-1'; + +const CONVERT = { name: 'convert', label: 'Convert', type: 'url', target: 'https://example.com/c', locations: ['record_header'], order: 1 }; +const MARK_WON = { name: 'mark_won', label: 'Mark Won', type: 'url', target: 'https://example.com/w', locations: ['record_header'], order: 2 }; +const SHARE = { name: 'share', label: 'Share', type: 'url', target: 'https://example.com/s', locations: ['record_header'], order: 3 }; +const LOG_CALL = { name: 'log_call', label: 'Log Call', type: 'url', target: 'https://example.com/l', locations: ['record_more'], order: 4 }; +const ACTIONS = [CONVERT, MARK_WON, SHARE, LOG_CALL]; +const LABELS = ACTIONS.map((a) => a.label); + +const PLACED_HEADER = { type: 'page:header', properties: { placedActions: true } }; +const OWN_LIST_HEADER = { type: 'page:header', properties: { actions: ['convert', 'share', 'log_call'] } }; + +type HeaderKind = 'synthesized' | 'placed' | 'own'; + +/** The design mode, on, with nothing staged: the store's surface the header reads. */ +const DESIGN_MODE_ON = { active: true, changes: new Map(), stage: () => {}, unstage: () => {} } as any; + +function mount(actionLayout: unknown, header: HeaderKind | boolean, designMode = false) { + const kind: HeaderKind = header === true ? 'placed' : header === false ? 'synthesized' : header; + const objects = [ + { + name: 'crm_deal', + label: 'Deal', + fields: { id: { type: 'text', label: 'Id' }, name: { type: 'text', label: 'Name' } }, + actions: ACTIONS, + ...(actionLayout ? { actionLayout } : {}), + }, + ]; + const pages = kind !== 'synthesized' + ? [ + { + name: 'crm_deal_detail', + label: 'Detail', + type: 'record', + object: 'crm_deal', + kind: 'full', + isDefault: true, + regions: [{ name: 'main', width: 'full', components: [kind === 'placed' ? PLACED_HEADER : OWN_LIST_HEADER, { type: 'record:details', properties: {} }] }], + }, + ] + : []; + const metadata = { + objects, + pages, + apps: [], + loading: false, + error: null, + refresh: async () => {}, + invalidate: () => {}, + ensureType: async () => [], + getItem: async (type: string, name: string) => (type === 'object' ? objects.find((o) => o.name === name) ?? null : null), + getItemsByType: () => [], + } as any; + const dataSource = { + find: vi.fn(async () => ({ data: [] })), + findOne: vi.fn(async () => ({ id: RECORD_ID, name: 'Big deal' })), + create: vi.fn(async () => ({})), + update: vi.fn(async () => ({})), + delete: vi.fn(async () => ({})), + } as any; + const view = ( + + ); + render( + + + + + {designMode ? {view} : view} + + + + , + ); +} + +/** The object's actions among the header's inline buttons, then those only in its ⋯ menu. */ +async function headerFaces(): Promise<{ inline: string[]; menu: string[] }> { + await waitFor(() => expect(document.querySelector('[role="toolbar"]')).toBeTruthy()); + await waitFor(() => + expect( + Array.from(document.querySelector('[role="toolbar"]')!.querySelectorAll('button')).some((b) => + LABELS.includes((b.textContent ?? '').trim()), + ), + ).toBe(true), + ); + const bar = document.querySelector('[role="toolbar"]') as HTMLElement; + const inline = Array.from(bar.querySelectorAll('button')) + .map((b) => b.getAttribute('aria-label') ?? (b.textContent ?? '').trim()) + .filter((l) => LABELS.includes(l)); + const trigger = screen.queryByRole('button', { name: 'More actions' }); + if (!trigger) return { inline, menu: [] }; + fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false, pointerType: 'mouse' }); + await waitFor(() => expect(screen.getByRole('menu')).toBeInTheDocument()); + const menu = Array.from(screen.getByRole('menu').querySelectorAll('[role="menuitem"]')) + .map((e) => (e.textContent ?? '').trim()) + // The ⋯ also lists, for a narrow row, the buttons that may fold into it: + // the menu's own actions are the ones drawn nowhere inline. + .filter((l) => LABELS.includes(l) && !inline.includes(l)); + return { inline, menu }; +} + +let consoleError: MockInstance; + +beforeEach(() => { + cleanup(); + localStorage.clear(); + consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response(JSON.stringify({ data: [] }), { status: 200, headers: { 'content-type': 'application/json' } })), + ); +}); + +afterEach(() => { + consoleError.mockRestore(); + vi.unstubAllGlobals(); + vi.clearAllMocks(); +}); + +describe.each([ + // Mounted `embedded`, as the side preview (`objectViewRecordOverlay`) mounts it. + ['the synthesized default page, in the side preview', false], + ['an authored page:header with placedActions: true', true], +] as const)('#36366 record header pins: %s', (_face, authored) => { + it('CONTROL — no pins: the header draws as before (record_header inline by order, record_more in ⋯)', async () => { + mount(undefined, authored); + const { inline, menu } = await headerFaces(); + expect(inline).toEqual(['Convert', 'Mark Won', 'Share']); + expect(menu).toEqual(['Log Call']); + }); + + it('the pinned actions are the buttons, in pin order (a record_more one too); the rest are in ⋯', async () => { + mount({ record: { pinned: ['log_call', 'share'] } }, authored); + const { inline, menu } = await headerFaces(); + expect(inline).toEqual(['Log Call', 'Share']); + expect(menu).toEqual(expect.arrayContaining(['Convert', 'Mark Won'])); + expect(menu).toHaveLength(2); + }); + + it('`more` orders the ⋯: the names it gives first, in its order, then the rest in their own order', async () => { + mount({ record: { pinned: ['convert'], more: ['log_call', 'share'] } }, authored); + const { inline, menu } = await headerFaces(); + expect(inline).toEqual(['Convert']); + // The host's own 「Share」 entry follows the object's actions in the ⋯ and + // reads the same label as the fixture's `share`: the object's three come first. + expect(menu.slice(0, 3)).toEqual(['Log Call', 'Share', 'Mark Won']); + }); + + it('CONTROL — the same pins without `more`: the ⋯ keeps the actions\' own order', async () => { + mount({ record: { pinned: ['convert'] } }, authored); + const { inline, menu } = await headerFaces(); + expect(inline).toEqual(['Convert']); + expect(menu.slice(0, 3)).toEqual(['Mark Won', 'Share', 'Log Call']); + }); + + it('a list-page arm alone leaves the record header as it was', async () => { + mount({ list: { pinned: ['$export'] } }, authored); + const { inline, menu } = await headerFaces(); + expect(inline).toEqual(['Convert', 'Mark Won', 'Share']); + expect(menu).toEqual(['Log Call']); + }); +}); + +describe('#36366 a record header authored with its own actions list', () => { + it('keeps its list: the pins do not choose its buttons', async () => { + mount({ record: { pinned: ['mark_won'] } }, 'own'); + const { inline } = await headerFaces(); + expect(inline).toEqual(['Convert', 'Share']); + expect(inline).not.toContain('Mark Won'); + }); + + it('is offered no 「Header buttons」 under the design mode; the headers that read pins are', async () => { + // The control is loaded lazily: the headers that offer it load it first, + // so its absence below is asked once it would have drawn. + mount(undefined, 'placed', true); + expect(await screen.findByTestId('design-header-pins', {}, { timeout: 5000 })).toBeInTheDocument(); + cleanup(); + mount(undefined, 'synthesized', true); + expect(await screen.findByTestId('design-header-pins', {}, { timeout: 5000 })).toBeInTheDocument(); + cleanup(); + mount(undefined, 'own', true); + await headerFaces(); + await new Promise((r) => setTimeout(r, 50)); + expect(screen.queryByTestId('design-header-pins')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.phoneFace-27058.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.phoneFace-27058.test.tsx index 8ca7af68a7e..bea28659ebe 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.phoneFace-27058.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.phoneFace-27058.test.tsx @@ -834,3 +834,34 @@ describe('a disabledWhen-greyed Edit or Delete says why (objectstack#35135)', () expect(screen.queryByText(PREDICATE_REASON)).toBeNull(); }); }); + +describe('the phone bottom bar reads the object\'s record scope arrangement (objectstack#36366)', () => { + /** The three-action lead, with `actionLayout` on the lead object. */ + function arranged(actionLayout: unknown) { + const [lead, ...rest] = objectsWith([ + action('convert', 'Convert Lead'), + action('assign', 'Assign'), + action('call', 'Log Call'), + ]) as unknown as Array>; + return [{ ...lead, actionLayout }, ...rest] as never; + } + + it('the pinned actions are the bar\'s buttons, in pin order; `more` leads the top bar\'s ⋯ in its order, before Edit', async () => { + mountPage([`/apps/${APP}/${LEAD}/record/r-1`], arranged({ record: { pinned: ['call', 'convert'], more: ['assign'] } })); + const toolbar = await barDrawn(); + expect(toolbar.getAttribute('data-page-header-actions-face')).toBe('bar'); + expect(barButtons()).toEqual(['Log Call', 'Convert Lead']); + const items = await moreItems(); + expect(items).not.toContain('Log Call'); + expect(items).not.toContain('Convert Lead'); + expect(items.indexOf('Assign')).toBeGreaterThanOrEqual(0); + expect(items.indexOf('Assign')).toBeLessThan(items.indexOf('Edit')); + }); + + it('`pinned: []` draws no bar button: every action is in the top bar\'s ⋯', async () => { + mountPage([`/apps/${APP}/${LEAD}/record/r-1`], arranged({ record: { pinned: [] } })); + const items = await moreItems(); + expect(items).toEqual(expect.arrayContaining(['Convert Lead', 'Assign', 'Log Call', 'Edit'])); + expect(actionBar()?.querySelectorAll('[role="toolbar"] > button').length ?? 0).toBe(0); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 94604d68093..410bd1c473b 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -74,6 +74,9 @@ import { editFormLockedByState } from '../utils/editFormLockedByState.js'; import { matchAppBySegment, resolveHostAppSegment } from '../utils/appRoute.js'; import { hostInConsolePath } from '../utils/hostInConsolePath.js'; import { useShellPageActionsSlot, useShellSidebarExpandSlot } from '../layout/shellPageActionsSlot.js'; +import { DesignModeHeaderPins, useObjectPins } from '../layout/DesignModeHeaderPins.js'; +import { headerReadsPins } from '../layout/designModeHeaderPins.js'; +import { useDesignModeActive } from '../layout/designMode.js'; import { recycleBinRefusalLabelsOf, recycleBinRestoreOf } from '../utils/recycleBinRestore.js'; import { launchConsoleFlow } from '../utils/flowLaunch.js'; import type { TranslateFn } from '@object-ui/i18n'; @@ -86,7 +89,7 @@ import { useNavigationContext, useRecordBreadcrumbTitle } from '../context/Navig // Both sets are derived, not restated — see record-detail-system-fields.ts. import { deriveRecordDetailSections } from './recordDetailSections.js'; import type { DataSource, FeedItem, Reaction, RecordPageOperation, RecordPagePayload } from '@object-ui/types'; -import { placedHeaderActions } from '@object-ui/types'; +import { arrangedHeaderActions, placedHeaderActions } from '@object-ui/types'; import type { ActionDef, ActionParamDef, ActionResult, ConfirmationHandler, ParamCollectionHandler } from '@object-ui/core'; import type { ConsoleActionDispatch } from '../consoleActionDispatch.js'; import { useRecordApprovals, openApprovalOf, isSubmitterOf } from '../hooks/useRecordApprovals.js'; @@ -1070,6 +1073,12 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri const [heldRecordTitle, setHeldRecordTitle] = useState<{ record: string; title: string } | undefined>(); const recordTitle = heldRecordTitle?.record === routeRecordKey ? heldRecordTitle.title : undefined; const objectDef = objects.find((o: any) => o.name === objectName); + // objectstack#36366 — the object's action arrangement as the header draws + // it: staged under the design mode, else as served. Keyed on content for the + // synthesized page's memo below. + const objectPins = useObjectPins(objectDef as any); + const recordPinsKey = JSON.stringify(objectPins.record ?? null); + const designModeOn = useDesignModeActive(); // objectui#13385 (maintainer ruling, option B) — a record page inside the // Setup app draws no floating `ManagedByBadge`; the header's object-label // chip carries the badge's note instead. Read off the route's `:appName`, so @@ -4675,8 +4684,16 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // (objectstack#29951), so the synthesized header and such a page draw the // same actions, an action another package places on the object included. const recordHeaderActions = (() => { - const base = placedHeaderActions(objectDef.actions as any[] | undefined) - .map((a: any) => localizeActionTexts(objectDef.name, a)); + // objectstack#36366 — the object's record scope arrangement + // (`actionLayout.record`): `pinned` chooses which of them are buttons, in + // order, and `more` orders the rest in ⋯. The same list feeds the side + // preview (an embedded mount) and the phone's bottom bar (the header's + // `bar` face). No arm: the header's own choice, as before. + const base = arrangedHeaderActions( + placedHeaderActions(objectDef.actions as any[] | undefined), + objectPins.record, + 'record', + ).map((a: any) => localizeActionTexts(objectDef.name, a)); // ⛔ No approval actions are injected here any more (objectui#3055). // They used to be two hand-written buttons (approve/reject only, no @@ -4822,7 +4839,10 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // the panel's headline is the pending one. (The decision actions no longer // ride this list at all — objectui#3055 moved them to the declared-action // bar, which reads the pending row directly.) - }, [objectDef?.name, childRelations, t, objectPluralLabel, language, objects, approvals.available, approvals.pendingRequest, approvals.requests, user?.id]); + // `recordPinsKey`: the record scope arrangement (objectstack#36366), staged under + // the design mode without `objects` changing. + // eslint-disable-next-line react-hooks/exhaustive-deps -- `objectPins` is keyed on content by `recordPinsKey` + }, [objectDef?.name, childRelations, t, objectPluralLabel, language, objects, approvals.available, approvals.pendingRequest, approvals.requests, user?.id, recordPinsKey]); // objectstack#30344 — whether this record page shows the record's field // history: the history gate, AND this reader's audit read answered. A read // the server refuses (or that fails) answers nothing, so the stream offers @@ -5988,14 +6008,8 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // any (`DeclaredActionsBar`'s header face says which) and the record's own // row otherwise. Remind is the submitter's 「催办」 here, so it is not // excluded as it was from the band (the approvals panel keeps its own). - const recordHeaderState: RecordHeaderState = { - tags: approvalTag || (headerBarForRecord ? stateLockChip : null) ? ( - <> - {approvalTag} - {headerBarForRecord ? stateLockChip : null} - - ) : undefined, - group: approvalBarMounted + // The pending request's levers, when the viewer has any. + const approvalGroup = approvalBarMounted ? (parts: RecordHeaderGroupParts) => ( <> @@ -6011,7 +6025,36 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri /> ) - : undefined, + : undefined; + // objectstack#36366 — under the design mode the group ends with + // 「Header buttons」 (the record row, or the approval's levers, unchanged), + // on a header that reads the pins: not on one authored with its own + // `actions` list, nor on one that draws none of the object's actions. + const headerTakesPins = headerReadsPins(assignedPage ?? assignedSlots); + const recordHeaderState: RecordHeaderState = { + tags: approvalTag || (headerBarForRecord ? stateLockChip : null) ? ( + <> + {approvalTag} + {headerBarForRecord ? stateLockChip : null} + + ) : undefined, + group: designModeOn && objectDef + ? (parts: RecordHeaderGroupParts) => ( + <> + {approvalGroup ? approvalGroup(parts) : parts.recordRow} + {parts.face === 'row' && headerTakesPins && ( + ((objectDef as any).actions).map((a: any) => localizeActionTexts(objectDef.name, a))} + /> + )} + + ) + : approvalGroup, + // objectstack#36366 — the record scope arrangement the header draws, a staged one + // included, for a page that places the object's actions itself. + actionLayout: objectPins.record, // objectstack#35891 — the stage tag is the stage's menu: the default // page draws no stage bar, so the header is where the stage moves. stage: (parts) => , diff --git a/ui/packages/app-shell/src/views/objectExtensionArrangementSave.ts b/ui/packages/app-shell/src/views/objectExtensionArrangementSave.ts index d0b27016c7c..674bff23c2c 100644 --- a/ui/packages/app-shell/src/views/objectExtensionArrangementSave.ts +++ b/ui/packages/app-shell/src/views/objectExtensionArrangementSave.ts @@ -2,13 +2,15 @@ /** * The ONE write of an installed object's arrangement (ADR-0146 D2/D3/D10): the - * keys `CUSTOM_ARRANGEMENT_KEYS` names (`fieldGroups`, `relatedLists`), written + * keys `CUSTOM_ARRANGEMENT_KEYS` names (`fieldGroups`, `relatedLists`, + * `actionLayout`), written * into the object extension of the base's paired `.custom` package and * published at once, so everyone sees it. * * Every arrangement editor of an installed object is a caller of this one * writer, never a second writer: the record page's 「Configure tabs」 hands it - * `relatedLists` (objectstack#36499); a field-layout editor hands it + * `relatedLists` (objectstack#36499); the design mode's 「Header buttons」 + * hands it `actionLayout` (objectstack#36366); a field-layout editor hands it * `fieldGroups` the same way. * * - Where: the pair the ensure door answers for the object's package @@ -36,7 +38,7 @@ */ import { stripReadDecorations } from '@objectstack/spec/kernel'; -import type { CustomArrangementKey } from '@objectstack/spec/data'; +import type { CustomArrangementKey, ObjectActionLayout } from '@objectstack/spec/data'; import { isDraftVersionConflict } from './metadata-admin/DraftConflictDialog.js'; import { OBJECT_EXTENSION_TYPE, objectExtensionBodyOf, type ObjectExtensionBody } from './studio-design/StudioCustomizeControls.js'; import type { EnsuredCustomizationPackage, ListedPackageManifest } from './studio-design/packages-io.js'; @@ -74,8 +76,16 @@ export interface StoredArrangement { readonly object: Record; } +/** + * The value an arrangement key is written with: a list for `fieldGroups` and + * `relatedLists`, an object of arms for `actionLayout`. + */ +export type ExtensionArrangementValue = K extends 'actionLayout' + ? ObjectActionLayout + : unknown[]; + /** The arrangement keys to write: a key present replaces the stored one; `undefined` takes it off. */ -export type ExtensionArrangementPatch = Partial>; +export type ExtensionArrangementPatch = { [K in CustomArrangementKey]?: ExtensionArrangementValue | undefined }; /** A document as stored, less what a read adds and what belongs to its package. */ function documentOf(read: unknown): Record { diff --git a/ui/packages/app-shell/src/views/objectViewPageHeader.actionLayout-36366.test.tsx b/ui/packages/app-shell/src/views/objectViewPageHeader.actionLayout-36366.test.tsx new file mode 100644 index 00000000000..9390812aebf --- /dev/null +++ b/ui/packages/app-shell/src/views/objectViewPageHeader.actionLayout-36366.test.tsx @@ -0,0 +1,129 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36366 — the list header reads the object's list-page pins + * (`actionLayout.list`): the pinned toolbar actions and the page's pinned + * Import (`$import`) and Export (`$export`) are its buttons, in pin order, + * and every other toolbar action is in the toolbar's own ⋯. No pins: the + * header draws as before (the control). An environment list never reads them. + * + * The real subject is `ObjectViewPageBarActions`; the `action:bar` node is + * stood in by a readout of what it is handed (its actions as buttons or menu + * entries, and its inline budget), which is the part this change arranges. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render, screen } from '@testing-library/react'; + +vi.mock('./objectViewHeaderLaunchGate', async (importOriginal) => ({ + ...(await importOriginal>()), + ListHeaderActionBar: ({ schema }: { schema: { actions: Array<{ name: string; component?: string }>; maxVisible?: number } }) => ( + + {schema.actions.map((a) => `${a.component === 'action:menu' ? '⋯' : ''}${a.name}`).join(' ')} + + ), +})); +vi.mock('../environment/EnvironmentListToolbar', () => ({ + EnvironmentListToolbar: () => , +})); + +import { ObjectViewPageBarActions } from './objectViewPageHeader'; + +const TOOLBAR = [ + { name: 'new_task', label: 'New task', locations: ['list_toolbar'] }, + { name: 'mass_assign', label: 'Assign', locations: ['list_toolbar'] }, + { name: 'export_csv', label: 'CSV', locations: ['list_toolbar'] }, +]; + +const t = ((k: string, o?: { defaultValue?: string }) => o?.defaultValue ?? k) as never; + +function mount(actionLayout?: unknown, extra: Record = {}) { + const objectDef = { name: 'crm_task', label: 'Task', actions: TOOLBAR, ...(actionLayout ? { actionLayout } : {}) }; + render( +
    + '', + createButton: , + importShown: true, + setShowImport: () => {}, + importDisabled: false, + t, + listActions: TOOLBAR, + isEnvironmentList: false, + headerToolbarActions: TOOLBAR, + environmentEntitlements: undefined, + toolbarBar: { type: 'action:bar', actions: TOOLBAR }, + listFavorite: null, + foldedHeaderActions: [], + barEnd: { exportDoor: {}, folded: false }, + ...extra, + } as unknown as React.ComponentProps)} + /> +
    , + ); +} + +/** What the header draws, in order: each bar's readout, and the pinned built-ins by their test id. */ +function drawn(): string[] { + const kept = ['bar', 'object-view-import-pinned', 'object-view-export-pinned']; + return [...screen.getByTestId('header').querySelectorAll('[data-testid]')] + .filter((el) => kept.includes(el.getAttribute('data-testid') ?? '')) + .map((el) => (el.getAttribute('data-testid') === 'bar' ? `bar(${el.textContent})` : el.getAttribute('data-testid')!)); +} + +afterEach(cleanup); + +describe('the list header reads the list-page pins (objectstack#36366)', () => { + it('CONTROL — no pins: one toolbar bar with every action, as before; Import and Export in their menu', () => { + mount(); + expect(drawn()).toEqual(['bar(new_task mass_assign export_csv)']); + expect(screen.getByTestId('bar')).toHaveAttribute('data-max', ''); + }); + + it('pins draw in pin order, the built-ins between the actions; the rest go to the toolbar ⋯', () => { + mount({ list: { pinned: ['mass_assign', '$export', 'new_task'] } }); + expect(drawn()).toEqual([ + 'bar(mass_assign)', + 'object-view-export-pinned', + 'bar(new_task)', + 'bar(⋯export_csv)', + ]); + // Each pinned run is a bar whose budget is its own length: nothing folds. + expect(screen.getAllByTestId('bar')[0]).toHaveAttribute('data-max', '1'); + }); + + it('`more` orders the toolbar ⋯: the names it gives first, in its order, then the rest in their own order', () => { + mount({ list: { pinned: ['new_task'], more: ['export_csv'] } }); + expect(drawn()).toEqual(['bar(new_task)', 'bar(⋯export_csv ⋯mass_assign)']); + cleanup(); + // CONTROL — the same pins without `more`: the ⋯ keeps the toolbar's own order. + mount({ list: { pinned: ['new_task'] } }); + expect(drawn()).toEqual(['bar(new_task)', 'bar(⋯mass_assign ⋯export_csv)']); + }); + + it('a pinned Import is a button of its own and leaves the Import / Export menu', () => { + mount({ list: { pinned: ['$import'] } }); + expect(drawn()).toEqual(['object-view-import-pinned', 'bar(⋯new_task ⋯mass_assign ⋯export_csv)']); + }); + + it('a pin naming nothing this reader is offered draws nothing', () => { + mount({ list: { pinned: ['ghost', '$import'] } }, { importShown: false }); + expect(drawn()).toEqual(['bar(⋯new_task ⋯mass_assign ⋯export_csv)']); + }); + + it('a record-page arm alone leaves the list header as it was', () => { + mount({ record: { pinned: ['convert'] } }); + expect(drawn()).toEqual(['bar(new_task mass_assign export_csv)']); + }); + + it('an environment list never reads the pins', () => { + mount({ list: { pinned: ['mass_assign'] } }, { isEnvironmentList: true }); + expect(screen.getByTestId('environment-toolbar')).toBeInTheDocument(); + expect(screen.queryByTestId('bar')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/objectViewPageHeader.tsx b/ui/packages/app-shell/src/views/objectViewPageHeader.tsx index b3d6a422d72..6d2a2c17005 100644 --- a/ui/packages/app-shell/src/views/objectViewPageHeader.tsx +++ b/ui/packages/app-shell/src/views/objectViewPageHeader.tsx @@ -40,6 +40,9 @@ import { PageHeader } from '../layout/PageHeader.js'; import { ManagedByBadge } from '../components/ManagedByBadge.js'; import { EnvironmentListToolbar } from '../environment/EnvironmentListToolbar.js'; import { ListHeaderActionBar } from './objectViewHeaderLaunchGate.js'; +import { arrangedHeaderActions, readActionLayoutArm, type ActionBarSchema, type ActionLayoutArm } from '@object-ui/types'; +import { DesignModeHeaderPins, useObjectPins } from '../layout/DesignModeHeaderPins.js'; +import type { PinCandidate } from '../layout/designModeHeaderPins.js'; import type { useObjectViewToolbarAffordances } from './objectViewToolbarAffordances.js'; import type { useObjectViewHeaderToolbar } from './objectViewHeaderToolbar.js'; import type { useObjectViewHeaderChrome } from './objectViewHeaderChrome.js'; @@ -121,20 +124,32 @@ export function ObjectViewPageBarActions({ const objectSettingsPath = useObjectSettingsGate( useObjectSettingsPath({ appSegment: appName, objectName: objectDef?.name }), ); - const exportDoor = barEnd?.exportDoor; + // objectstack#36366 — the object's list scope arrangement + // (`actionLayout.list`): `pinned` is the header's buttons, in order, the + // page's Import and Export among them (`$import`, `$export`), and `more` + // orders the toolbar's ⋯. Absent: the header's own choice, as before. + // Under the design mode the arrangement staged there is drawn (`useObjectPins`). + const objectPins = useObjectPins(objectDef); + const listArm = isEnvironmentList ? undefined : readActionLayoutArm(objectPins.list); + const importPinned = !!listArm?.pinned.includes('$import') && importShown; + const exportPinned = !!listArm?.pinned.includes('$export') && !!barEnd?.exportDoor; + // A pinned Import or Export is a button of its own, out of the menus. + const importInMenus = importShown && !importPinned; + const exportDoor = exportPinned ? undefined : barEnd?.exportDoor; // 「Import / Export」 is drawn at the view bar's end while it fits; folded, // and on the page bar, its entries are ⋮ More's. - const ioAtEnd = !!barEnd && !barEnd.folded && (importShown || !!exportDoor); + const ioAtEnd = !!barEnd && !barEnd.folded && (importInMenus || !!exportDoor); const ioInMore = !ioAtEnd; // The ⋮ menu: Object settings, the description (no longer a resident // subtitle), Import and the favorites entry — the page's once-in-a-while // acts. - const moreShown = !!objectSettingsPath || !!description || !!listFavorite || (ioInMore && (importShown || !!exportDoor)); + const moreShown = !!objectSettingsPath || !!description || !!listFavorite || (ioInMore && (importInMenus || !!exportDoor)); + const drawsToolbar = !!listActions?.some((a: any) => a.locations?.includes('list_toolbar')); return ( <> {ioAtEnd && ( )} - {/* Schema-driven toolbar actions */} - {listActions?.some((a: any) => a.locations?.includes('list_toolbar')) && ( - isEnvironmentList ? ( - - ) : ( - + {listArm ? ( + setShowImport(true)} + disabled={importDisabled} + title={t('console.objectView.importTitle')} + data-testid="object-view-import-pinned" + > + + {t('console.objectView.import')} + + ) : null} + exportButton={exportPinned && barEnd?.exportDoor ? ( + + + + + + + + + ) : null} + /> + ) : ( + /* Schema-driven toolbar actions */ + drawsToolbar && ( + isEnvironmentList ? ( + + ) : ( + + ) ) )} @@ -161,7 +216,7 @@ export function ObjectViewPageBarActions({ )} + {/* objectstack#36366 — the design mode's 「Header buttons」, last. */} + {!isEnvironmentList && ( + []} + builtins={listPinBuiltins(importShown, !!barEnd?.exportDoor, t)} + /> + )} ); } +/** The list page's built-ins this reader is offered to pin: its Import and its Export, where the page draws them. */ +function listPinBuiltins(importShown: boolean, exportShown: boolean, t: ObjectViewPageBarProps['t']): PinCandidate[] { + return [ + ...(importShown ? [{ id: '$import', label: String(t('console.objectView.import')) }] : []), + ...(exportShown ? [{ id: '$export', label: String(t('list.export', { defaultValue: 'Export' })) }] : []), + ]; +} + +/** + * objectstack#36366 — the list header's pinned buttons, in `pinned` order: + * each pinned action of the toolbar (`arrangedHeaderActions`), and the page's + * pinned Import and Export where they are offered. Every other toolbar action + * is in the toolbar's own ⋯ menu, drawn after them, the ones `more` names + * first, in that order. A `$import` / `$export` is only ever pinned (the + * schema refuses one in `more`); not pinned, it stays in the page's Import / + * Export entries. A name naming nothing this reader is offered draws nothing. + */ +function PinnedListHeaderActions({ + arm, + toolbarBar, + importButton, + exportButton, +}: { + arm: ActionLayoutArm; + toolbarBar?: ActionBarSchema; + importButton: ReactNode; + exportButton: ReactNode; +}) { + const arranged = arrangedHeaderActions((toolbarBar?.actions ?? []) as any[], arm, 'list'); + const byName = new Map(); + for (const action of arranged) { + if (action?.component !== 'action:menu' && typeof action?.name === 'string') byName.set(action.name, action); + } + const rest = arranged.filter((action) => action?.component === 'action:menu'); + // Runs of adjacent pinned actions share one bar, so a built-in pinned + // between two actions sits between their buttons. + const parts: ReactNode[] = []; + let run: any[] = []; + const flush = () => { + if (run.length === 0 || !toolbarBar) return; + parts.push( + , + ); + run = []; + }; + for (const pin of arm.pinned) { + if (pin === '$import' || pin === '$export') { + flush(); + const button = pin === '$import' ? importButton : exportButton; + if (button) parts.push({button}); + continue; + } + const action = byName.get(pin); + if (action) run.push(action); + } + flush(); + if (rest.length > 0 && toolbarBar) { + parts.push(); + } + return <>{parts}; +} + export interface ObjectViewMoreMenuProps extends Pick { /** * objectstack#36487 — where Object settings goes, already passed by the diff --git a/ui/packages/components/src/renderers/layout/containers.tsx b/ui/packages/components/src/renderers/layout/containers.tsx index 31fdfa9a1e7..ae7ddbb7d93 100644 --- a/ui/packages/components/src/renderers/layout/containers.tsx +++ b/ui/packages/components/src/renderers/layout/containers.tsx @@ -22,7 +22,7 @@ import React from 'react'; import { createPortal } from 'react-dom'; import { ComponentRegistry, ExpressionEvaluator, declaredNameField, isElementDataSourceConfig, evalRowPredicate, formatTitleTemplate, hasDeclaredPredicate, getRecordDisplayName, isActionSwitchedOff, recordDisplayValueAt, resolveNameField, toPredicateRecord } from '@object-ui/core'; import type { ComponentInput } from '@object-ui/core'; -import { actionRendersAt, detectStatusField, placedHeaderActions, resolveDeclaredActionIds } from '@object-ui/types'; +import { actionRendersAt, detectStatusField, arrangedHeaderActions, placedHeaderActions, resolveDeclaredActionIds } from '@object-ui/types'; import type { DeclaredActionsRefusal } from '@object-ui/types'; import { useRecordContext, useAction, useCapabilityGate, usePredicateScope, usePageVariables, useInlineEdit, useActionTextLocalizer, useMetadataItem, reportUnresolvableVisibilityPredicate, resolveInlineAriaProps, buildNodeEvaluationScope } from '@object-ui/react'; import { renderChildren, renderNodeSlot, cn } from '../../lib/utils'; @@ -2095,10 +2095,15 @@ export const PageHeaderActions: React.FC = ({ // The record's state (objectstack#35593): when the host hands a `group`, // the row is what that group draws — the record's row unchanged, or the // state's own levers with the record's actions in their `⋯`. - const stateGroup = React.useContext(RecordHeaderStateContext)?.group; + const recordHeaderState = React.useContext(RecordHeaderStateContext); + const stateGroup = recordHeaderState?.group; // objectstack#36151 — the phone host's top-bar slot for the `⋯`: handed, the // bottom bar keeps the action buttons alone. `undefined` = no such slot. const phoneMoreSlot = React.useContext(PageHeaderPhoneContext)?.more; + // objectstack#36366 — the host's record scope arrangement (the design mode's + // staged one) over the object's own, keyed on content for the memo below. + const hostActionLayout = recordHeaderState?.actionLayout; + const hostLayoutKey = hostActionLayout ? JSON.stringify(hostActionLayout) : ''; // Record-level inline-edit session (objectui#2572 item 4): while a shared // inline draft is active, header actions flagged `disableDuringInlineEdit` // (the host's Edit CTA) grey out so the classic form-edit surface can't be @@ -2227,8 +2232,15 @@ export const PageHeaderActions: React.FC = ({ reportRefusedPlacedActions(headerObjectName); return []; } - // The ONE placed-header reader the synthesized header reads too. - if (drawsPlacedActions) return placedHeaderActions(registered); + // The ONE placed-header reader the synthesized header reads too, with the + // object's record scope arrangement applied as it applies it (objectstack#36366). + if (drawsPlacedActions) { + return arrangedHeaderActions( + placedHeaderActions(registered), + hostActionLayout ?? (headerActionsObjectMeta as any)?.actionLayout?.record, + 'record', + ); + } const declared = resolveDeclaredActionIds(authoredHeaderActions, registered); if (declared.kind === 'refused') { reportRefusedHeaderActions(headerObjectName, declared); @@ -2258,6 +2270,7 @@ export const PageHeaderActions: React.FC = ({ } } return declared.actions; + // eslint-disable-next-line react-hooks/exhaustive-deps -- `hostActionLayout` is keyed on content by `hostLayoutKey` }, [ authoredHeaderActions, headerActionsObjectMeta, @@ -2266,6 +2279,7 @@ export const PageHeaderActions: React.FC = ({ headerObjectName, placedRefused, drawsPlacedActions, + hostLayoutKey, ]); // ── Action predicates: ONE dialect, ONE entry (objectui#3521) ────────────── diff --git a/ui/packages/components/src/renderers/layout/record-header-bar-context.ts b/ui/packages/components/src/renderers/layout/record-header-bar-context.ts index 66e8961637c..efa38799e85 100644 --- a/ui/packages/components/src/renderers/layout/record-header-bar-context.ts +++ b/ui/packages/components/src/renderers/layout/record-header-bar-context.ts @@ -101,6 +101,14 @@ export interface RecordHeaderState { * declaration, unchanged. */ title?: RecordHeaderTitle; + /** + * The record scope arrangement the header draws (objectstack#36366), where + * the host holds it ahead of the object as served: the design mode's staged + * one. A header that places the object's actions itself (`placedActions: + * true`) reads it over the object's `actionLayout.record`. Absent: the + * object's own. + */ + actionLayout?: { readonly pinned: readonly string[]; readonly more?: readonly string[] }; } /** diff --git a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts index 057754f93b9..b1371a451c3 100644 --- a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts +++ b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts @@ -474,7 +474,10 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // 129 once objectstack-ai/objectstack#36364's report half added // `designMode.menu.newReportLeft`, the same sentence for a new report // („{{name}}“) — one interpolated span. - expect(okSpans, 'correctly paired spans').toBe(129); + // 133 once objectstack-ai/objectstack#36366 added `designMode.pins`: the + // header-buttons panel naming the 「More」 menu („Mehr“, twice) and the + // arranged action a save refuses („{{name}}“, twice), four spans. + expect(okSpans, 'correctly paired spans').toBe(133); }); it('keeps the count identity that replaces the card’s count(„) === count(“)', () => { @@ -607,7 +610,9 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // `designMode.menu.newItemLeft`, one more matched pair. // 129 / 129 / 0 after its report half added `designMode.menu.newReportLeft`, // one more matched pair. - expect({ open, close, rdq }).toEqual({ open: 129, close: 129, rdq: 0 }); + // 133 / 133 / 0 after objectstack-ai/objectstack#36366 added + // `designMode.pins`, four more matched pairs. + expect({ open, close, rdq }).toEqual({ open: 133, close: 133, rdq: 0 }); // The durable shape: every „ closed by a “, every surplus “ an English // opener answered by a ”. Survived translating the two English values. expect(close).toBe(open + rdq); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index cd9cf33fea8..c5472a46f9c 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3948,6 +3948,23 @@ const ar = { newItemLeft: 'تعذّرت إزالة لوحة المعلومات الجديدة "{{name}}"؛ أزلها في Studio.', newReportLeft: 'تعذّرت إزالة التقرير الجديد "{{name}}"؛ أزله في Studio.', }, + pins: { + button: 'أزرار الترويسة', + pinned: 'مثبّتة في الترويسة', + other: 'أخرى', + nonePinned: 'لا يوجد زر مثبّت: كل الإجراءات في «المزيد».', + noneOther: 'كل الإجراءات مثبّتة.', + pin: 'تثبيت {{name}} في الترويسة', + unpin: 'نقل {{name}} إلى «المزيد»', + drag: 'اسحب {{name}} لإعادة الترتيب', + full: 'يُثبَّت في الترويسة {{cap}} أزرار على الأكثر. ألغِ تثبيت أحدها أولًا.', + notListed: 'حزمة هذا الكائن غير مدرجة، لذا لا يمكن حفظ أزرار ترويسته.', + pendingDraft: 'لهذا الكائن تغييرات غير منشورة في Studio. انشرها أو تجاهلها هناك، ثم احفظ مرة أخرى.', + pairNotWritable: 'لا يمكن الكتابة في حزمة التخصيص لهذا التطبيق، لذا لا يمكن حفظ أزرار ترويسته.', + unknown: 'لم يعد «{{name}}» إجراءً لهذا الكائن. ألغِ تثبيته ثم احفظ مرة أخرى.', + notPlaced: 'لم يعد «{{name}}» معروضًا في هذه الصفحة. ألغِ تثبيته ثم احفظ مرة أخرى.', + stale: 'لم يعد معروضًا هنا، ويُحذف عند الحفظ: {{names}}', + }, recordTabs: { entry: 'تكوين علامات التبويب', title: 'تكوين علامات التبويب', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 91b5c53ce16..2ab22b9c54b 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -3625,6 +3625,23 @@ const de = { newItemLeft: 'Das neue Dashboard „{{name}}“ konnte nicht wieder entfernt werden; entfernen Sie es in Studio.', newReportLeft: 'Der neue Bericht „{{name}}“ konnte nicht wieder entfernt werden; entfernen Sie ihn in Studio.', }, + pins: { + button: 'Kopfzeilen-Schaltflächen', + pinned: 'In der Kopfzeile angeheftet', + other: 'Weitere', + nonePinned: 'Keine Schaltfläche angeheftet: Alle Aktionen sind unter „Mehr“.', + noneOther: 'Alle Aktionen sind angeheftet.', + pin: '{{name}} in der Kopfzeile anheften', + unpin: '{{name}} nach „Mehr“ verschieben', + drag: '{{name}} ziehen, um die Reihenfolge zu ändern', + full: 'Höchstens {{cap}} Schaltflächen sind in der Kopfzeile angeheftet. Lösen Sie zuerst eine.', + notListed: 'Das Paket dieses Objekts ist nicht gelistet, daher können seine Kopfzeilen-Schaltflächen nicht gespeichert werden.', + pendingDraft: 'Dieses Objekt hat unveröffentlichte Änderungen in Studio. Veröffentlichen oder verwerfen Sie sie dort und speichern Sie dann erneut.', + pairNotWritable: 'Das Anpassungspaket dieser App ist nicht beschreibbar, daher können die Kopfzeilen-Schaltflächen nicht gespeichert werden.', + unknown: '„{{name}}“ ist keine Aktion dieses Objekts mehr. Lösen Sie sie und speichern Sie erneut.', + notPlaced: '„{{name}}“ wird auf dieser Seite nicht mehr angeboten. Lösen Sie sie und speichern Sie erneut.', + stale: 'Hier nicht mehr angeboten, beim Speichern weggelassen: {{names}}', + }, recordTabs: { entry: 'Tabs konfigurieren', title: 'Tabs konfigurieren', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 0cbbeb821d4..e8218cd1567 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -4369,6 +4369,23 @@ const en = { newItemLeft: 'The new dashboard "{{name}}" could not be removed again; remove it in Studio.', newReportLeft: 'The new report "{{name}}" could not be removed again; remove it in Studio.', }, + pins: { + button: 'Header buttons', + pinned: 'Pinned to header', + other: 'Other', + nonePinned: 'No button is pinned: every action is in More.', + noneOther: 'Every action is pinned.', + pin: 'Pin {{name}} to the header', + unpin: 'Move {{name}} to More', + drag: 'Drag {{name}} to reorder', + full: 'At most {{cap}} buttons are pinned to the header. Unpin one first.', + notListed: 'This object\'s package is not listed, so its header buttons cannot be saved.', + pendingDraft: 'This object has unpublished changes in Studio. Publish or discard them there, then save again.', + pairNotWritable: 'This app\'s customization package cannot be written, so its header buttons cannot be saved.', + unknown: '"{{name}}" is no longer an action of this object. Unpin it, then save again.', + notPlaced: '"{{name}}" is no longer offered on this page. Unpin it, then save again.', + stale: 'No longer offered here, left out when you save: {{names}}', + }, recordTabs: { entry: 'Configure tabs', title: 'Configure tabs', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 725f303d69e..abe9ce1c6f5 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -3707,6 +3707,23 @@ const es = { newItemLeft: 'No se pudo eliminar el nuevo panel "{{name}}"; elimínalo en Studio.', newReportLeft: 'No se pudo eliminar el nuevo informe "{{name}}"; elimínalo en Studio.', }, + pins: { + button: 'Botones del encabezado', + pinned: 'Fijados en el encabezado', + other: 'Otros', + nonePinned: 'No hay botones fijados: todas las acciones están en Más.', + noneOther: 'Todas las acciones están fijadas.', + pin: 'Fijar {{name}} en el encabezado', + unpin: 'Mover {{name}} a Más', + drag: 'Arrastra {{name}} para reordenar', + full: 'Se fijan como máximo {{cap}} botones en el encabezado. Desfija uno primero.', + notListed: 'El paquete de este objeto no está en la lista, así que sus botones del encabezado no se pueden guardar.', + pendingDraft: 'Este objeto tiene cambios sin publicar en Studio. Publícalos o descártalos allí y vuelve a guardar.', + pairNotWritable: 'No se puede escribir en el paquete de personalización de esta app, así que sus botones del encabezado no se pueden guardar.', + unknown: '"{{name}}" ya no es una acción de este objeto. Desfíjala y vuelve a guardar.', + notPlaced: '"{{name}}" ya no se ofrece en esta página. Desfíjala y vuelve a guardar.', + stale: 'Ya no se ofrece aquí; se omite al guardar: {{names}}', + }, recordTabs: { entry: 'Configurar pestañas', title: 'Configurar pestañas', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index fbe97040726..f422a9fa515 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -3703,6 +3703,23 @@ const fr = { newItemLeft: 'Le nouveau tableau de bord « {{name}} » n’a pas pu être supprimé ; supprimez-le dans Studio.', newReportLeft: 'Le nouveau rapport « {{name}} » n\'a pas pu être retiré ; retirez-le dans Studio.', }, + pins: { + button: 'Boutons de l’en-tête', + pinned: 'Épinglés dans l’en-tête', + other: 'Autres', + nonePinned: 'Aucun bouton épinglé : toutes les actions sont dans Plus.', + noneOther: 'Toutes les actions sont épinglées.', + pin: 'Épingler {{name}} dans l’en-tête', + unpin: 'Déplacer {{name}} dans Plus', + drag: 'Faites glisser {{name}} pour réordonner', + full: 'Au plus {{cap}} boutons sont épinglés dans l’en-tête. Désépinglez-en un d’abord.', + notListed: 'Le package de cet objet n’est pas listé : ses boutons d’en-tête ne peuvent pas être enregistrés.', + pendingDraft: 'Cet objet a des modifications non publiées dans Studio. Publiez-les ou annulez-les là-bas, puis enregistrez à nouveau.', + pairNotWritable: 'Le package de personnalisation de cette app n\'est pas modifiable : ses boutons d’en-tête ne peuvent pas être enregistrés.', + unknown: '« {{name}} » n’est plus une action de cet objet. Désépinglez-la, puis enregistrez à nouveau.', + notPlaced: '« {{name}} » n’est plus proposée sur cette page. Désépinglez-la, puis enregistrez à nouveau.', + stale: 'N’est plus proposé ici, omis à l’enregistrement : {{names}}', + }, recordTabs: { entry: 'Configurer les onglets', title: 'Configurer les onglets', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index d1e20011d69..2737c1f7585 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -3627,6 +3627,23 @@ const ja = { newItemLeft: '新しいダッシュボード「{{name}}」を削除できませんでした。Studio で削除してください。', newReportLeft: '新しいレポート「{{name}}」を削除できませんでした。Studio で削除してください。', }, + pins: { + button: 'ヘッダーのボタン', + pinned: 'ヘッダーに固定', + other: 'その他', + nonePinned: '固定されたボタンはありません。すべての操作は「その他」にあります。', + noneOther: 'すべての操作が固定されています。', + pin: '{{name}} をヘッダーに固定', + unpin: '{{name}} を「その他」へ移動', + drag: '{{name}} をドラッグして並べ替え', + full: 'ヘッダーに固定できるボタンは最大 {{cap}} 個です。先にどれかの固定を外してください。', + notListed: 'このオブジェクトのパッケージが一覧にないため、ヘッダーのボタンを保存できません。', + pendingDraft: 'このオブジェクトには Studio に未公開の変更があります。そちらで公開または破棄してから、もう一度保存してください。', + pairNotWritable: 'このアプリのカスタマイズパッケージは書き込めないため、ヘッダーのボタンを保存できません。', + unknown: '「{{name}}」はこのオブジェクトの操作ではなくなりました。固定を外してから保存してください。', + notPlaced: '「{{name}}」はこのページに表示されなくなりました。固定を外してから保存してください。', + stale: 'ここには表示されなくなったため、保存時に除外されます: {{names}}', + }, recordTabs: { entry: 'タブを設定', title: 'タブを設定', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index d8dd3aece6b..b1321a6b296 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -3625,6 +3625,23 @@ const ko = { newItemLeft: '새 대시보드 "{{name}}"을(를) 삭제하지 못했습니다. Studio에서 삭제하세요.', newReportLeft: '새 보고서 "{{name}}"을(를) 삭제하지 못했습니다. Studio에서 삭제하세요.', }, + pins: { + button: '헤더 버튼', + pinned: '헤더에 고정', + other: '기타', + nonePinned: '고정된 버튼이 없습니다. 모든 작업은 "더 보기"에 있습니다.', + noneOther: '모든 작업이 고정되어 있습니다.', + pin: '{{name}}을(를) 헤더에 고정', + unpin: '{{name}}을(를) "더 보기"로 이동', + drag: '{{name}}을(를) 끌어서 순서 변경', + full: '헤더에는 버튼을 최대 {{cap}}개까지 고정할 수 있습니다. 먼저 하나의 고정을 해제하세요.', + notListed: '이 개체의 패키지가 목록에 없어 헤더 버튼을 저장할 수 없습니다.', + pendingDraft: '이 개체에는 Studio에 게시되지 않은 변경 사항이 있습니다. 그곳에서 게시하거나 취소한 뒤 다시 저장하세요.', + pairNotWritable: '이 앱의 사용자 지정 패키지에 쓸 수 없어 헤더 버튼을 저장할 수 없습니다.', + unknown: '"{{name}}"은(는) 더 이상 이 개체의 작업이 아닙니다. 고정을 해제한 뒤 다시 저장하세요.', + notPlaced: '"{{name}}"은(는) 더 이상 이 페이지에 없습니다. 고정을 해제한 뒤 다시 저장하세요.', + stale: '이 페이지에 더 이상 없으며, 저장할 때 제외됩니다: {{names}}', + }, recordTabs: { entry: '탭 구성', title: '탭 구성', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 9e62fbd8bdb..6bcf30bf629 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -3702,6 +3702,23 @@ const pt = { newItemLeft: 'Não foi possível remover o novo painel "{{name}}"; remova-o no Studio.', newReportLeft: 'Não foi possível remover o novo relatório "{{name}}"; remova-o no Studio.', }, + pins: { + button: 'Botões do cabeçalho', + pinned: 'Fixados no cabeçalho', + other: 'Outros', + nonePinned: 'Nenhum botão fixado: todas as ações estão em Mais.', + noneOther: 'Todas as ações estão fixadas.', + pin: 'Fixar {{name}} no cabeçalho', + unpin: 'Mover {{name}} para Mais', + drag: 'Arraste {{name}} para reordenar', + full: 'No máximo {{cap}} botões ficam fixados no cabeçalho. Desafixe um primeiro.', + notListed: 'O pacote deste objeto não está listado, então os botões do cabeçalho não podem ser salvos.', + pendingDraft: 'Este objeto tem alterações não publicadas no Studio. Publique ou descarte-as lá e salve novamente.', + pairNotWritable: 'O pacote de personalização deste app não pode ser gravado, então os botões do cabeçalho não podem ser salvos.', + unknown: '"{{name}}" não é mais uma ação deste objeto. Desafixe-a e salve novamente.', + notPlaced: '"{{name}}" não é mais oferecida nesta página. Desafixe-a e salve novamente.', + stale: 'Não é mais oferecido aqui; fica de fora ao salvar: {{names}}', + }, recordTabs: { entry: 'Configurar abas', title: 'Configurar abas', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index a2646fae840..db29ef6729a 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -3794,6 +3794,23 @@ const ru = { newItemLeft: 'Не удалось удалить новую панель «{{name}}»; удалите её в Studio.', newReportLeft: 'Не удалось удалить новый отчёт «{{name}}»; удалите его в Studio.', }, + pins: { + button: 'Кнопки заголовка', + pinned: 'Закреплены в заголовке', + other: 'Прочее', + nonePinned: 'Нет закреплённых кнопок: все действия в меню «Ещё».', + noneOther: 'Все действия закреплены.', + pin: 'Закрепить {{name}} в заголовке', + unpin: 'Переместить {{name}} в «Ещё»', + drag: 'Перетащите {{name}}, чтобы изменить порядок', + full: 'В заголовке закрепляется не больше {{cap}} кнопок. Сначала открепите одну.', + notListed: 'Пакет этого объекта отсутствует в списке, поэтому кнопки заголовка нельзя сохранить.', + pendingDraft: 'В Studio есть неопубликованные изменения этого объекта. Опубликуйте или отмените их там и сохраните снова.', + pairNotWritable: 'Пакет настроек этого приложения недоступен для записи, поэтому кнопки заголовка нельзя сохранить.', + unknown: '«{{name}}» больше не является действием этого объекта. Открепите его и сохраните снова.', + notPlaced: '«{{name}}» больше не предлагается на этой странице. Открепите его и сохраните снова.', + stale: 'Здесь больше не предлагается, при сохранении будет опущено: {{names}}', + }, recordTabs: { entry: 'Настроить вкладки', title: 'Настроить вкладки', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 2ed86939a1d..409282af881 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3763,6 +3763,23 @@ const zh = { newItemLeft: '新建的仪表盘「{{name}}」没能删除,请在 Studio 里删除它。', newReportLeft: '新建的报表「{{name}}」没能删除,请在 Studio 里删除它。', }, + pins: { + button: '页头按钮', + pinned: '固定在页头', + other: '其他', + nonePinned: '没有固定的按钮:所有动作都在「更多」里。', + noneOther: '所有动作都已固定。', + pin: '把 {{name}} 固定到页头', + unpin: '把 {{name}} 移到「更多」', + drag: '拖动 {{name}} 调整顺序', + full: '页头最多固定 {{cap}} 个按钮,请先取消固定一个。', + notListed: '这个对象所在的包不在列表中,页头按钮无法保存。', + pendingDraft: '这个对象在 Studio 里有未发布的改动。请先在那里发布或丢弃,再保存。', + pairNotWritable: '这个应用的定制包不可写,页头按钮无法保存。', + unknown: '「{{name}}」已不是这个对象的动作。请取消固定后再保存。', + notPlaced: '「{{name}}」已不在这个页面上。请取消固定后再保存。', + stale: '已不在这个页面上,保存时会去掉:{{names}}', + }, recordTabs: { entry: '配置页签', title: '配置页签', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 66fff5f55de..e0e8cc10a19 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3763,6 +3763,23 @@ const zhHant = { newItemLeft: '新建的儀表盤「{{name}}」沒能刪除,請在 Studio 裡刪除它。', newReportLeft: '新建的報表「{{name}}」沒能刪除,請在 Studio 裡刪除它。', }, + pins: { + button: '頁頭按鈕', + pinned: '固定在頁頭', + other: '其他', + nonePinned: '沒有固定的按鈕:所有動作都在「更多」裡。', + noneOther: '所有動作都已固定。', + pin: '把 {{name}} 固定到頁頭', + unpin: '把 {{name}} 移到「更多」', + drag: '拖動 {{name}} 調整順序', + full: '頁頭最多固定 {{cap}} 個按鈕,請先取消固定一個。', + notListed: '這個物件所在的包不在列表中,頁頭按鈕無法儲存。', + pendingDraft: '這個物件在 Studio 裡有未釋出的改動。請先在那裡釋出或丟棄,再儲存。', + pairNotWritable: '這個應用的定製包不可寫,頁頭按鈕無法儲存。', + unknown: '「{{name}}」已不是這個物件的動作。請取消固定後再儲存。', + notPlaced: '「{{name}}」已不在這個頁面上。請取消固定後再儲存。', + stale: '已不在這個頁面上,儲存時會去掉:{{names}}', + }, recordTabs: { entry: '配置頁籤', title: '配置頁籤', diff --git a/ui/packages/types/src/__tests__/arranged-header-actions-36366.test.ts b/ui/packages/types/src/__tests__/arranged-header-actions-36366.test.ts new file mode 100644 index 00000000000..ab2bf58c508 --- /dev/null +++ b/ui/packages/types/src/__tests__/arranged-header-actions-36366.test.ts @@ -0,0 +1,101 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36366 — `arrangedHeaderActions`: an object's action layout arm + * applied to the actions one header of its scope places. No arm answers the + * actions as they are (the header draws as before); an arm makes its `pinned` + * actions the header's buttons, in order, and sends every other one to the + * overflow, the ones `more` names first, in that order, then the rest in + * their own order. + */ + +import { describe, expect, it } from 'vitest'; +import { arrangedHeaderActions } from '../ui-action'; + +const RECORD = [ + { name: 'edit', locations: ['record_header'], order: 1 }, + { name: 'clone', locations: ['record_more'] }, + { name: 'mark_won', locations: ['record_header'], order: 5 }, + { name: 'archive', locations: ['record_header', 'record_more'], component: 'action:menu' }, +]; + +const LIST = [ + { name: 'new_lead', locations: ['list_toolbar'] }, + { name: 'mass_assign', locations: ['list_toolbar'], order: 3 }, + { name: 'import_csv', locations: ['list_toolbar'], component: 'action:menu' }, +]; + +const names = (actions: readonly { name?: unknown }[]) => actions.map((a) => a.name); + +describe('arrangedHeaderActions (objectstack#36366)', () => { + it('no arm: the actions as they are, so the header draws as before', () => { + expect(arrangedHeaderActions(RECORD, undefined, 'record')).toEqual(RECORD); + expect(arrangedHeaderActions(LIST, null, 'list')).toEqual(LIST); + // A value that is no arm (the old per-page array, an arm without `pinned`) is none. + expect(arrangedHeaderActions(RECORD, ['clone'], 'record')).toEqual(RECORD); + expect(arrangedHeaderActions(RECORD, { more: ['clone'] }, 'record')).toEqual(RECORD); + }); + + it('record: the pinned ones lead in pin order at record_header; the rest are record_more only', () => { + const out = arrangedHeaderActions(RECORD, { pinned: ['clone', 'mark_won'] }, 'record'); + expect(names(out)).toEqual(['clone', 'mark_won', 'edit', 'archive']); + const [clone, markWon, edit, archive] = out; + expect(clone.locations).toEqual(['record_more', 'record_header']); + expect((clone.order as number) < (markWon.order as number)).toBe(true); + expect(edit.locations).toEqual(['record_more']); + expect(archive.locations).toEqual(['record_more']); + }); + + it('record: a pinned action authored into the overflow (`action:menu`) becomes a button', () => { + const [archive] = arrangedHeaderActions(RECORD, { pinned: ['archive'] }, 'record'); + expect(archive).toMatchObject({ name: 'archive', component: undefined }); + expect(archive.locations).toContain('record_header'); + }); + + it('list: the pinned ones lead in pin order; the rest are `action:menu`, the bar overflow', () => { + const out = arrangedHeaderActions(LIST, { pinned: ['import_csv', 'new_lead'] }, 'list'); + expect(names(out)).toEqual(['import_csv', 'new_lead', 'mass_assign']); + expect(out[0].component).toBeUndefined(); + expect(out[2].component).toBe('action:menu'); + }); + + it('an empty `pinned` draws no button: every action goes to the overflow', () => { + expect(arrangedHeaderActions(LIST, { pinned: [] }, 'list').every((a) => a.component === 'action:menu')).toBe(true); + expect(arrangedHeaderActions(RECORD, { pinned: [] }, 'record').every((a) => !a.locations?.includes('record_header'))).toBe(true); + }); + + it('a name naming no placed action, or a `$` built-in, draws nothing; a name twice counts once', () => { + const out = arrangedHeaderActions(LIST, { pinned: ['$export', 'ghost', 'mass_assign', 'mass_assign'] }, 'list'); + expect(names(out)).toEqual(['mass_assign', 'new_lead', 'import_csv']); + expect(out.filter((a) => a.component !== 'action:menu').map((a) => a.name)).toEqual(['mass_assign']); + }); + + it('record: `more` orders the overflow, ahead of the actions it does not name, which keep their own order', () => { + const out = arrangedHeaderActions(RECORD, { pinned: ['mark_won'], more: ['archive', 'clone'] }, 'record'); + expect(names(out)).toEqual(['mark_won', 'archive', 'clone', 'edit']); + const [markWon, archive, clone, edit] = out; + expect((markWon.order as number) < (archive.order as number)).toBe(true); + expect((archive.order as number) < (clone.order as number)).toBe(true); + expect((clone.order as number) < (edit.order as number)).toBe(true); + expect([archive, clone, edit].every((a) => !a.locations?.includes('record_header'))).toBe(true); + }); + + it('list: `more` orders the bar overflow the same way', () => { + const out = arrangedHeaderActions(LIST, { pinned: [], more: ['mass_assign', '$export', 'import_csv'] }, 'list'); + expect(names(out)).toEqual(['mass_assign', 'import_csv', 'new_lead']); + expect(out.every((a) => a.component === 'action:menu')).toBe(true); + expect((out[0].order as number) < (out[1].order as number)).toBe(true); + }); + + it('a name in both parts is a button: `pinned` wins', () => { + const out = arrangedHeaderActions(LIST, { pinned: ['new_lead'], more: ['new_lead', 'mass_assign'] }, 'list'); + expect(names(out)).toEqual(['new_lead', 'mass_assign', 'import_csv']); + expect(out[0].component).toBeUndefined(); + }); + + it('does not change the actions it is given', () => { + const before = JSON.stringify(RECORD); + arrangedHeaderActions(RECORD, { pinned: ['clone'], more: ['edit'] }, 'record'); + expect(JSON.stringify(RECORD)).toBe(before); + }); +}); diff --git a/ui/packages/types/src/index.ts b/ui/packages/types/src/index.ts index c6c3a2207ad..2939783687e 100644 --- a/ui/packages/types/src/index.ts +++ b/ui/packages/types/src/index.ts @@ -1294,6 +1294,9 @@ export { ACTION_PARAM_FIELD_TYPES, actionRendersAt, placedHeaderActions, + arrangedHeaderActions, + readActionLayoutArm, + type ActionLayoutArm, resolveDeclaredActionIds, } from './ui-action.js'; diff --git a/ui/packages/types/src/ui-action.ts b/ui/packages/types/src/ui-action.ts index d778d59f78d..33d1f1de663 100644 --- a/ui/packages/types/src/ui-action.ts +++ b/ui/packages/types/src/ui-action.ts @@ -128,6 +128,101 @@ export function placedHeaderActions list.filter((v): v is string => typeof v === 'string' && v !== ''); + return Array.isArray(more) ? { pinned: names(pinned), more: names(more) } : { pinned: names(pinned) }; +} + +/** + * An object's action layout arm (`actionLayout.list` / `.record`, + * objectstack#36366) applied to the actions one header of that scope places, + * for the header's own sort and inline/overflow split to draw. + * + * `arm.pinned` names, in order, the actions the header draws as buttons; + * every other action it places goes to its overflow menu, the ones + * `arm.more` names first, in that order, then the rest in their own order. + * No arm (`undefined`, or a value that is no arm) answers `actions` itself: + * the header draws exactly as before. A name naming none of `actions` (an + * action not placed there, one hidden from this reader, or a built-in such as + * `$export`, which the host draws itself) is skipped: it draws nothing, and + * no other action takes a pinned one's place. + * + * - `record`: a pinned action is placed at `record_header` and leads the sort; + * an unpinned one is placed at `record_more` only, the header's + * overflow-only placement (`page:header`'s `isMoreOnly`). + * - `list`: a pinned action leads the `action:bar`'s sort; an unpinned one is + * `component: 'action:menu'`, which the bar places in its overflow without + * spending an inline slot. + */ +export function arrangedHeaderActions< + T extends { name?: unknown; locations?: readonly string[]; order?: unknown; component?: unknown }, +>(actions: readonly T[], layoutArm: unknown, scope: 'list' | 'record'): T[] { + const arm = readActionLayoutArm(layoutArm); + if (!arm) return [...actions]; + const rankOf = (names: readonly string[]) => { + const rank = new Map(); + names.forEach((name, index) => { + if (!rank.has(name)) rank.set(name, index); + }); + return rank; + }; + const pinRank = rankOf(arm.pinned); + const moreRank = rankOf((arm.more ?? []).filter((name) => !pinRank.has(name))); + const pinned: T[] = []; + const named: T[] = []; + const rest: T[] = []; + const seen = new Set(); + for (const action of actions) { + const name = typeof action?.name === 'string' ? action.name : ''; + const at = name && !seen.has(name) ? pinRank.get(name) : undefined; + if (at !== undefined) { + seen.add(name); + const component = action.component === 'action:menu' ? undefined : action.component; + const locations = + scope === 'record' && !(action.locations ?? []).includes('record_header') + ? [...(action.locations ?? []), 'record_header'] + : action.locations; + pinned.push({ ...action, locations, order: PINNED_HEADER_ACTION_ORDER + at, component } as T); + continue; + } + let overflow: T; + if (scope === 'list') { + overflow = { ...action, component: 'action:menu' }; + } else { + const locations = (action.locations ?? []).filter((l) => l !== 'record_header'); + overflow = { ...action, locations: locations.includes('record_more') ? locations : [...locations, 'record_more'] }; + } + const moreAt = name && !seen.has(name) ? moreRank.get(name) : undefined; + if (moreAt !== undefined) { + seen.add(name); + named.push({ ...overflow, order: MORE_HEADER_ACTION_ORDER + moreAt } as T); + } else { + rest.push(overflow); + } + } + const byOrder = (a: T, b: T) => (a.order as number) - (b.order as number); + return [...pinned.sort(byOrder), ...named.sort(byOrder), ...rest]; +} + // ============================================================================ // Declared action arrays — ONE rule for every surface that authors a list of // actions by id (objectui#7182)