From 86ad71b0a1afa12e15014b66e48ca424b23db994 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:37:25 +0000 Subject: [PATCH 01/22] feat(spec): an object pins its header buttons per page type, at most three (#36366) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `ObjectSchema.pinnedActions` (new, optional, no default): a `list` arm and a `record` arm, each the names of the actions that page's header draws as buttons, in order, at most three; every other action the header places goes to its More menu. An entry is an action name of the object or one of the page's `$` built-ins (`$import`, `$export` on the list page; none on the record page). The shape refuses more than three, an entry twice, a malformed entry and a built-in the page does not have, each with a named reason; the limit and the entry pattern are in the JSON Schema, uniqueness is the one dropped refinement (ledger rows added). `ObjectExtensionSchema.pinnedActions` carries the same leaf, so an installed object (ADR-0146 D10, extend-only) is pinned from its customization pair. The object form gains the `pinnedActions` composite (two string-tags rows), translated in every locale; the two echo-decision counts and the `/meta/types` object property count move with history lines. Clause-②: yes (widening) Metadata-protocol: added Claude-Session: https://claude.ai/code/session_01QsR2jSr8sNCnJrK6Q9kEF5 Co-authored-by: Claude --- content/docs/references/api/metadata.mdx | 1 + content/docs/references/data/object.mdx | 16 ++ content/docs/references/system/migration.mdx | 2 + .../src/object-schema-fls-references.ts | 2 +- .../ar.metadata-forms.generated.ts | 12 ++ .../de.metadata-forms.generated.ts | 12 ++ .../en.metadata-forms.generated.ts | 12 ++ .../es-ES.metadata-forms.generated.ts | 12 ++ .../fr.metadata-forms.generated.ts | 12 ++ .../ja-JP.metadata-forms.generated.ts | 12 ++ .../ko.metadata-forms.generated.ts | 12 ++ .../pt-BR.metadata-forms.generated.ts | 12 ++ .../ru.metadata-forms.generated.ts | 12 ++ .../zh-CN.metadata-forms.generated.ts | 12 ++ .../zh-Hant.metadata-forms.generated.ts | 12 ++ packages/spec/api-surface/data.json | 5 + packages/spec/authorable-surface/data.json | 2 + .../spec/dropped-refinements.baseline.json | 32 +++- packages/spec/export-origins/data.json | 5 + packages/spec/src/data/index.ts | 8 + .../src/data/object-pinned-actions.test.ts | 90 +++++++++++ .../spec/src/data/object-pinned-actions.ts | 141 ++++++++++++++++++ packages/spec/src/data/object.form.ts | 12 ++ packages/spec/src/data/object.zod.ts | 18 ++- 24 files changed, 456 insertions(+), 10 deletions(-) create mode 100644 packages/spec/src/data/object-pinned-actions.test.ts create mode 100644 packages/spec/src/data/object-pinned-actions.ts diff --git a/content/docs/references/api/metadata.mdx b/content/docs/references/api/metadata.mdx index 54df68fe613..d2418802082 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`. | +| **pinnedActions** | `{ list?: string[]; record?: string[] }` | optional | The actions each page header of the object shows as buttons, per page type (`list`, `record`), in order, at most 3 per page; every other action the header places goes to its 「More」 menu. Omit to keep the header'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 00d97ec787b..0e4937d571e 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`. | +| **pinnedActions** | `{ list?: string[]; record?: string[] }` | optional | The actions each page header of the object shows as buttons, per page type (`list`, `record`), in order, at most 3 per page; every other action the header places goes to its 「More」 menu. Omit to keep the header'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.pinnedActions` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **list** | `string[]` | optional | The list page header's buttons, in order: action names of the object placed at `list_toolbar`, or `$import` / `$export`. At most 3; every other action goes to 「More」. Omit to draw the header as before. | +| **record** | `string[]` | optional | The record page header's buttons, in order: action names of the object placed at `record_header` or `record_more`. At most 3; every other action goes to 「More」. Omit to draw the header 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 | +| **pinnedActions** | `{ list?: string[]; record?: string[] }` | optional | The actions each page header of the object shows as buttons, per page type (`list`, `record`), in order, at most 3 per page; every other action the header places goes to its 「More」 menu. Omit to keep the header's own choice (each action's `order`). | | **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.pinnedActions` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **list** | `string[]` | optional | The list page header's buttons, in order: action names of the object placed at `list_toolbar`, or `$import` / `$export`. At most 3; every other action goes to 「More」. Omit to draw the header as before. | +| **record** | `string[]` | optional | The record page header's buttons, in order: action names of the object placed at `record_header` or `record_more`. At most 3; every other action goes to 「More」. Omit to draw the header 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..3f5bdb8ebc4 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`. | +| **pinnedActions** | `{ list?: string[]; record?: string[] }` | optional | The actions each page header of the object shows as buttons, per page type (`list`, `record`), in order, at most 3 per page; every other action the header places goes to its 「More」 menu. Omit to keep the header'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`. | +| **pinnedActions** | `{ list?: string[]; record?: string[] }` | optional | The actions each page header of the object shows as buttons, per page type (`list`, `record`), in order, at most 3 per page; every other action the header places goes to its 「More」 menu. Omit to keep the header'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/packages/metadata-core/src/object-schema-fls-references.ts b/packages/metadata-core/src/object-schema-fls-references.ts index b23994b143d..745f9eff5f2 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, pinnedActions: 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/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 95cc16ad51b..78d9ab4f91b 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} المخزَّن مفتاحًا تلو الآخر؛ اكتب واحدًا في المصدر لتقييد الإجراء بكل سجل." }, + pinnedActions: { + label: "الإجراءات المثبتة", + helpText: "الإجراءات التي يعرضها رأس كل صفحة كأزرار بالترتيب، 3 على الأكثر لكل صفحة؛ وأي إجراء آخر يضعه الرأس يذهب إلى قائمة «المزيد». إن لم تُحدَّد: يختار كل رأس أزراره حسب ترتيب الإجراءات كما كان." + }, + "pinnedActions.list": { + label: "صفحة القائمة", + helpText: "أسماء الإجراءات الموضوعة في شريط أدوات القائمة، أو $import / $export، بترتيب العرض. 3 على الأكثر. يرفض os validate اسمًا ليس إجراءً لهذا الكائن أو غير موضوع في شريط القائمة؛ ولا يعرض مثل هذا الاسم أي زر." + }, + "pinnedActions.record": { + label: "صفحة السجل", + helpText: "أسماء الإجراءات الموضوعة في رأس السجل أو في قائمة «المزيد» الخاصة به، بترتيب العرض. 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 58fea25afcb..4300fc41b4d 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." }, + pinnedActions: { + label: "Angeheftete Aktionen", + helpText: "Welche Aktionen jeder Seitenkopf der Reihe nach als Schaltflächen zeigt, höchstens 3 pro Seite; jede andere Aktion des Kopfs kommt ins Menü „Mehr“. Nicht gesetzt: Jeder Kopf wählt seine Schaltflächen wie bisher nach der Reihenfolge der Aktionen." + }, + "pinnedActions.list": { + label: "Listenseite", + helpText: "Namen von Aktionen in der Listen-Symbolleiste oder $import / $export, in der Reihenfolge der Anzeige. Höchstens 3. os validate lehnt einen Namen ab, der keine Aktion dieses Objekts ist oder nicht in der Listen-Symbolleiste platziert ist; ein solcher Name zeigt keine Schaltfläche." + }, + "pinnedActions.record": { + label: "Datensatzseite", + helpText: "Namen von Aktionen im Datensatzkopf oder in dessen Menü „Mehr“, in der Reihenfolge der Anzeige. Höchstens 3. os validate lehnt einen Namen ab, der keine Aktion dieses Objekts ist oder nicht auf der Datensatzseite platziert ist; ein solcher Name zeigt keine Schaltfläche." + }, 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 97272cb84b0..0eeafc50a88 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." }, + pinnedActions: { + label: "Pinned Actions", + helpText: "Which actions each page header shows as buttons, in order, at most 3 per page; every other action the header places goes to its More menu. Unset: each header picks its buttons by the actions' order, as before." + }, + "pinnedActions.list": { + label: "List page", + helpText: "Action names placed on the list toolbar, or $import / $export, in the order they are drawn. At most 3. os validate refuses a name that is no action of this object or is not placed on the list toolbar; such a name draws no button." + }, + "pinnedActions.record": { + label: "Record page", + helpText: "Action names placed in the record header or its More menu, in the order they are drawn. At most 3. os validate refuses a name that is no action of this object or is not placed on the record page; such a name draws no button." + }, 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 c3083760454..c7fc2fb7ea0 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." }, + pinnedActions: { + label: "Acciones fijadas", + helpText: "Qué acciones muestra como botones cada cabecera de página, en orden, como máximo 3 por página; cualquier otra acción de la cabecera va a su menú Más. Sin definir: cada cabecera elige sus botones por el orden de las acciones, como antes." + }, + "pinnedActions.list": { + label: "Página de lista", + helpText: "Nombres de acciones situadas en la barra de herramientas de la lista, o $import / $export, en el orden en que se muestran. Como máximo 3. 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 muestra botón." + }, + "pinnedActions.record": { + label: "Página de registro", + helpText: "Nombres de acciones situadas en la cabecera del registro o en su menú Más, en el orden en que se muestran. Como máximo 3. os validate rechaza un nombre que no es una acción de este objeto o que no está en la página de registro; ese nombre no muestra botón." + }, 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 fba9518f002..31fe8671199 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." }, + pinnedActions: { + label: "Actions épinglées", + helpText: "Les actions que chaque en-tête de page affiche en boutons, dans l'ordre, 3 au plus par page ; toute autre action de l'en-tête va dans son menu Plus. Non défini : chaque en-tête choisit ses boutons selon l'ordre des actions, comme avant." + }, + "pinnedActions.list": { + label: "Page de liste", + helpText: "Noms d'actions placées dans la barre d'outils de la liste, ou $import / $export, dans l'ordre d'affichage. 3 au plus. 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 aucun bouton." + }, + "pinnedActions.record": { + label: "Page d'enregistrement", + helpText: "Noms d'actions placées dans l'en-tête de l'enregistrement ou dans son menu Plus, dans l'ordre d'affichage. 3 au plus. os validate refuse un nom qui n'est pas une action de cet objet ou qui n'est pas placé sur la page d'enregistrement ; un tel nom n'affiche aucun bouton." + }, 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 6f79d65dadc..c674b794b69 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} オブジェクトはキーごとに編集されます。各レコードでアクションを制御するにはソースに記述してください。" }, + pinnedActions: { + label: "固定アクション", + helpText: "各ページのヘッダーにボタンとして順に表示するアクション。1 ページ最大 3 個で、ヘッダーに配置されたその他のアクションは「その他」メニューに入ります。未設定の場合、各ヘッダーは従来どおりアクションの順序でボタンを選びます。" + }, + "pinnedActions.list": { + label: "一覧ページ", + helpText: "一覧ツールバーに配置されたアクション名、または $import / $export を表示順に指定します。最大 3 個。このオブジェクトのアクションでない名前や一覧ツールバーに配置されていない名前は os validate が拒否し、その名前のボタンは表示されません。" + }, + "pinnedActions.record": { + label: "レコードページ", + helpText: "レコードヘッダーまたはその「その他」メニューに配置されたアクション名を表示順に指定します。最大 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 b0a479c998e..10a652a8bc3 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} 개체는 키별로 편집됩니다. 레코드마다 작업을 제어하려면 소스에 작성하세요." }, + pinnedActions: { + label: "고정 작업", + helpText: "각 페이지 헤더에 버튼으로 순서대로 표시할 작업입니다. 페이지당 최대 3개이며, 헤더에 배치된 나머지 작업은 「더 보기」 메뉴로 갑니다. 설정하지 않으면 각 헤더는 이전처럼 작업 순서에 따라 버튼을 고릅니다." + }, + "pinnedActions.list": { + label: "목록 페이지", + helpText: "목록 도구 모음에 배치된 작업 이름 또는 $import / $export를 표시 순서대로 지정합니다. 최대 3개. 이 개체의 작업이 아니거나 목록 도구 모음에 배치되지 않은 이름은 os validate가 거부하며, 그런 이름은 버튼으로 표시되지 않습니다." + }, + "pinnedActions.record": { + label: "레코드 페이지", + helpText: "레코드 헤더 또는 그 「더 보기」 메뉴에 배치된 작업 이름을 표시 순서대로 지정합니다. 최대 3개. 이 개체의 작업이 아니거나 레코드 페이지에 배치되지 않은 이름은 os validate가 거부하며, 그런 이름은 버튼으로 표시되지 않습니다." + }, editMode: { label: "편집 모드", helpText: "이 객체 레코드의 편집 상호 작용 의도입니다. 없으면 렌더러가 자체 기본값을 고릅니다. 스타일이 아니라 렌더러 간 공통 의도입니다." 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 eb19cdc068e..ed38d48f6df 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." }, + pinnedActions: { + label: "Ações fixadas", + helpText: "Quais ações cada cabeçalho de página mostra como botões, em ordem, no máximo 3 por página; qualquer outra ação do cabeçalho vai para o menu Mais. Sem definir: cada cabeçalho escolhe os botões pela ordem das ações, como antes." + }, + "pinnedActions.list": { + label: "Página de lista", + helpText: "Nomes de ações colocadas na barra de ferramentas da lista, ou $import / $export, na ordem em que aparecem. No máximo 3. O os validate recusa um nome que não é ação deste objeto ou não está na barra da lista; esse nome não mostra botão." + }, + "pinnedActions.record": { + label: "Página de registro", + helpText: "Nomes de ações colocadas no cabeçalho do registro ou no menu Mais dele, na ordem em que aparecem. No máximo 3. O os validate recusa um nome que não é ação deste objeto ou não está na página de registro; esse nome não mostra botão." + }, 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 ad37a22f879..dc40146766c 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} редактируется по ключам; задайте его в исходном коде, чтобы управлять действием для каждой записи." }, + pinnedActions: { + label: "Закреплённые действия", + helpText: "Какие действия каждый заголовок страницы показывает кнопками, по порядку, не более 3 на страницу; остальные действия заголовка попадают в меню «Ещё». Не задано: каждый заголовок, как и раньше, выбирает кнопки по порядку действий." + }, + "pinnedActions.list": { + label: "Страница списка", + helpText: "Имена действий на панели инструментов списка или $import / $export, в порядке показа. Не более 3. os validate отклоняет имя, которое не является действием этого объекта или не размещено на панели списка; такое имя не показывает кнопку." + }, + "pinnedActions.record": { + label: "Страница записи", + helpText: "Имена действий в заголовке записи или в его меню «Ещё», в порядке показа. Не более 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 53c26b6c7cf..703c4e15465 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} 对象逐键编辑;在源码中写一个即可按每条记录控制该操作。" }, + pinnedActions: { + label: "固定按钮", + helpText: "每种页面的页头按顺序显示为按钮的动作,每页最多 3 个;页头放置的其他动作都进「更多」菜单。未设置时,各页头仍按动作的排序选按钮。" + }, + "pinnedActions.list": { + label: "列表页", + helpText: "放在列表工具栏上的动作名称,或 $import / $export,按显示顺序排列,最多 3 个。os validate 会拒绝不是本对象动作、或未放在列表工具栏上的名称;这样的名称不显示按钮。" + }, + "pinnedActions.record": { + label: "记录页", + helpText: "放在记录页头或其「更多」菜单中的动作名称,按显示顺序排列,最多 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 6a491c0640b..a86f835754a 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} 物件逐鍵編輯;在原始碼中寫一個即可按每筆記錄控制該操作。" }, + pinnedActions: { + label: "固定按鈕", + helpText: "每種頁面的頁首按順序顯示為按鈕的動作,每頁最多 3 個;頁首放置的其他動作都進「更多」選單。未設定時,各頁首仍按動作的排序選按鈕。" + }, + "pinnedActions.list": { + label: "清單頁", + helpText: "放在清單工具列上的動作名稱,或 $import / $export,按顯示順序排列,最多 3 個。os validate 會拒絕不是本物件動作、或未放在清單工具列上的名稱;這樣的名稱不顯示按鈕。" + }, + "pinnedActions.record": { + label: "記錄頁", + helpText: "放在記錄頁首或其「更多」選單中的動作名稱,按顯示順序排列,最多 3 個。os validate 會拒絕不是本物件動作、或未放在記錄頁上的名稱;這樣的名稱不顯示按鈕。" + }, editMode: { label: "編輯方式", helpText: "該物件記錄的編輯互動意圖。留空則由呈現端自行選擇預設方式。這是跨呈現端的意圖宣告,不是樣式。" diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index fa1e0431b47..49a092aee51 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -577,6 +577,9 @@ "NumericStringReading (type)", "OBJECT_COLORS (const)", "OBJECT_KEY_GUIDANCE (const)", + "OBJECT_PINNED_ACTION_LIMIT (const)", + "OBJECT_PINNED_ACTION_PAGES (const)", + "OBJECT_PINNED_BUILTIN_ACTIONS (const)", "ORACLE_DEFAULT_PORT (const)", "ORGANIZATION_UNIT_CODE_PATTERN (const)", "OWNER_FIELD_DEF (const)", @@ -622,6 +625,8 @@ "ObjectIndexParsed (type)", "ObjectOwnership (type)", "ObjectOwnershipEnum (const)", + "ObjectPinnedActionPage (type)", + "ObjectPinnedActions (type)", "ObjectRequiredPermissions (type)", "ObjectRequiredPermissionsSchema (const)", "ObjectSchema (const)", diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index ed0ebba883e..972edaa3aa1 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -705,6 +705,7 @@ "data/Object:name", "data/Object:nameField", "data/Object:ownership", + "data/Object:pinnedActions", "data/Object:pluralLabel", "data/Object:protection", "data/Object:publicSharing", @@ -745,6 +746,7 @@ "data/ObjectExtension:fields", "data/ObjectExtension:indexes", "data/ObjectExtension:label", + "data/ObjectExtension:pinnedActions", "data/ObjectExtension:place", "data/ObjectExtension:pluralLabel", "data/ObjectExtension:priority", diff --git a/packages/spec/dropped-refinements.baseline.json b/packages/spec/dropped-refinements.baseline.json index 70d70d03422..9b135e9cdee 100644 --- a/packages/spec/dropped-refinements.baseline.json +++ b/packages/spec/dropped-refinements.baseline.json @@ -162,6 +162,8 @@ "manifest.objects.element.lifecycle", "manifest.objects.element.membershipKeys", "manifest.objects.element.membershipKeys.valueType", + "manifest.objects.element.pinnedActions.list", + "manifest.objects.element.pinnedActions.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.pinnedActions.list", + "data.options[1].manifest.objects.element.pinnedActions.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.pinnedActions.list", + "options[1].manifest.objects.element.pinnedActions.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.pinnedActions.list", + "data.packages.element.options[1].manifest.objects.element.pinnedActions.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.pinnedActions.list", + "data.pinnedActions.record" ] }, "api/PackageInstallBody": { @@ -1197,7 +1207,9 @@ "listViews.valueType.kanban.groupByField", "listViews.valueType.timeline.groupByField", "membershipKeys", - "membershipKeys.valueType" + "membershipKeys.valueType", + "pinnedActions.list", + "pinnedActions.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", + "pinnedActions.list", + "pinnedActions.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.pinnedActions.list", + "operations.element.options[3].object.pinnedActions.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.pinnedActions.list", + "object.pinnedActions.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.pinnedActions.list", + "options[3].object.pinnedActions.record" ] }, "system/ObjectStorageConfig": { diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 10b7e6aa332..39bc54ac8e6 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -567,6 +567,9 @@ "NumericStringReading": "src/data/filter-number-comparand-declared-type.ts#NumericStringReading (type)", "OBJECT_COLORS": "src/data/object-icon.ts#OBJECT_COLORS (const)", "OBJECT_KEY_GUIDANCE": "src/data/authoring-key-lint.ts#OBJECT_KEY_GUIDANCE (const)", + "OBJECT_PINNED_ACTION_LIMIT": "src/data/object-pinned-actions.ts#OBJECT_PINNED_ACTION_LIMIT (const)", + "OBJECT_PINNED_ACTION_PAGES": "src/data/object-pinned-actions.ts#OBJECT_PINNED_ACTION_PAGES (const)", + "OBJECT_PINNED_BUILTIN_ACTIONS": "src/data/object-pinned-actions.ts#OBJECT_PINNED_BUILTIN_ACTIONS (const)", "ORACLE_DEFAULT_PORT": "src/data/driver/oracle.zod.ts#ORACLE_DEFAULT_PORT (const)", "ORGANIZATION_UNIT_CODE_PATTERN": "src/data/standard-units.ts#ORGANIZATION_UNIT_CODE_PATTERN (const)", "OWNER_FIELD_DEF": "src/data/injected-system-column-provenance.ts#OWNER_FIELD_DEF (const)", @@ -611,6 +614,8 @@ "ObjectIndexParsed": "src/data/object.zod.ts#ObjectIndexParsed (type)", "ObjectOwnership": "src/data/object.zod.ts#ObjectOwnership (type)", "ObjectOwnershipEnum": "src/data/object.zod.ts#ObjectOwnershipEnum (const)", + "ObjectPinnedActionPage": "src/data/object-pinned-actions.ts#ObjectPinnedActionPage (type)", + "ObjectPinnedActions": "src/data/object-pinned-actions.ts#ObjectPinnedActions (type)", "ObjectRequiredPermissions": "src/data/object.zod.ts#ObjectRequiredPermissions (type)", "ObjectRequiredPermissionsSchema": "src/data/object.zod.ts#ObjectRequiredPermissionsSchema (const)", "ObjectSchema": "src/data/object.zod.ts#ObjectSchema (const)", diff --git a/packages/spec/src/data/index.ts b/packages/spec/src/data/index.ts index 249fefd9ec6..bc3e5855de8 100644 --- a/packages/spec/src/data/index.ts +++ b/packages/spec/src/data/index.ts @@ -217,6 +217,14 @@ 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 header buttons per page type: the limit, the pages and their built-ins. +export { + OBJECT_PINNED_ACTION_LIMIT, + OBJECT_PINNED_ACTION_PAGES, + OBJECT_PINNED_BUILTIN_ACTIONS, + type ObjectPinnedActionPage, + type ObjectPinnedActions, +} from './object-pinned-actions'; // 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-pinned-actions.test.ts b/packages/spec/src/data/object-pinned-actions.test.ts new file mode 100644 index 00000000000..834a4c69071 --- /dev/null +++ b/packages/spec/src/data/object-pinned-actions.test.ts @@ -0,0 +1,90 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36366 — `pinnedActions`, the actions each page header of an + * object shows as buttons. Optional with no default; the shape refuses, with a + * named reason, more than three, an entry pinned twice, an entry that is + * neither an action name nor a `$` built-in, and a built-in the page does not + * have. The object extension carries the same shape. + */ + +import { describe, expect, it } from 'vitest'; +import { ObjectExtensionSchema, ObjectSchema } from './object.zod'; +import { + OBJECT_PINNED_ACTION_LIMIT, + OBJECT_PINNED_BUILTIN_ACTIONS, + OBJECT_PINNED_ACTIONS_SCHEMA, +} from './object-pinned-actions'; + +const object = (pinnedActions?: unknown) => ({ + name: 'crm_lead', + fields: { title: { type: 'text' } }, + ...(pinnedActions === undefined ? {} : { pinnedActions }), +}); + +function refusal(pinnedActions: unknown): string[] { + const r = ObjectSchema.safeParse(object(pinnedActions)); + if (r.success) return []; + return r.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`); +} + +describe('pinnedActions (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 && 'pinnedActions' in r.data).toBe(false); + }); + + it('takes a list arm and a record arm, each up to three, in order', () => { + const pins = { list: ['$export', 'convert_lead', '$import'], record: ['convert_lead', 'log_call', 'send_email'] }; + const r = ObjectSchema.safeParse(object(pins)); + expect(r.success).toBe(true); + expect(r.success && r.data.pinnedActions).toEqual(pins); + expect(ObjectSchema.safeParse(object({ record: [] })).success).toBe(true); + expect(ObjectSchema.safeParse(object({})).success).toBe(true); + }); + + it('refuses more than three, naming the limit', () => { + expect(OBJECT_PINNED_ACTION_LIMIT).toBe(3); + const [message] = refusal({ record: ['a_one', 'a_two', 'a_three', 'a_four'] }); + expect(message).toMatch(/^pinnedActions\.record: `pinnedActions\.record` pins 4 actions; a header draws at most 3/); + }); + + it('refuses an entry pinned twice, at its index', () => { + expect(refusal({ list: ['convert_lead', 'convert_lead'] })).toEqual([ + 'pinnedActions.list.1: `convert_lead` is pinned twice on the list page; a header draws an action once.', + ]); + }); + + it('refuses an entry that is neither an action name nor a built-in', () => { + for (const bad of ['Convert', 'convert-lead', 'x', '', 'crm.convert']) { + const [message] = refusal({ record: [bad] }); + expect(message, bad).toBe( + `pinnedActions.record.0: \`${bad}\` is not an action name (lowercase snake_case, as the action's \`name\`) ` + + 'nor a built-in (the record page has no built-in, pin an action name).', + ); + } + }); + + it('refuses a built-in the page does not have, naming the ones it has', () => { + expect(OBJECT_PINNED_BUILTIN_ACTIONS).toEqual({ list: ['$import', '$export'], record: [] }); + expect(refusal({ list: ['$print'] })).toEqual([ + "pinnedActions.list.0: `$print` is not a built-in of the list page: the list page's built-ins are `$import`, `$export`.", + ]); + expect(refusal({ record: ['$export'] })).toEqual([ + 'pinnedActions.record.0: `$export` is not a built-in of the record page: the record page has no built-in, pin an action name.', + ]); + }); + + it('is a closed shape: an unknown arm is refused, a near-miss pointed at its arm', () => { + expect(refusal({ detail: ['convert_lead'] }).join()).toMatch(/detail/); + expect(refusal({ recordPage: ['convert_lead'] }).join()).toMatch(/record/); + }); + + it('the object extension carries the same leaf', () => { + expect(ObjectExtensionSchema.safeParse({ extend: 'crm_lead', pinnedActions: { record: ['log_call'] } }).success).toBe(true); + const r = ObjectExtensionSchema.safeParse({ extend: 'crm_lead', pinnedActions: { record: ['a_one', 'a_two', 'a_three', 'a_four'] } }); + expect(r.success).toBe(false); + expect(OBJECT_PINNED_ACTIONS_SCHEMA.safeParse(undefined).success).toBe(true); + }); +}); diff --git a/packages/spec/src/data/object-pinned-actions.ts b/packages/spec/src/data/object-pinned-actions.ts new file mode 100644 index 00000000000..6629b41c9d6 --- /dev/null +++ b/packages/spec/src/data/object-pinned-actions.ts @@ -0,0 +1,141 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { z } from 'zod'; +import { strictObject } from '../shared/strict-object'; + +/** + * `ObjectSchema.pinnedActions` (objectstack#36366): which actions an object's + * page header shows as buttons, per page type, in order. + * + * A page header draws at most {@link OBJECT_PINNED_ACTION_LIMIT} actions as + * buttons and puts every other action it places in its 「More」 menu. Without + * this key that choice follows each action's `order` and declaration order, + * which is shared by every page an action is placed on. With it, an arm names + * the buttons of one page type: `list` for the object's list page header, + * `record` for its record page header. An arm names actions by `name`, at + * most three, in the order they are drawn; every other action the header + * places goes to 「More」. An object without the key (or without an arm) draws + * that header exactly as before. + * + * An entry is an action `name` of the object (lowercase snake_case, the + * action's own spelling), or one of the page's built-in buttons, spelled with + * a leading `$` so it can never collide with an action name: + * {@link OBJECT_PINNED_BUILTIN_ACTIONS}. The list page's built-ins are its + * import and export buttons; the record page has none (its Edit button is + * drawn outside the slots, and Share and Delete stay in 「More」). + * + * What the shape refuses here, at every door: more than three entries, an + * entry pinned twice, an entry that is neither an action name nor a `$` + * built-in, and a `$` built-in the page does not have. Whether an action name + * names an action of this object placed on that page is a reference, judged + * where the whole stack is visible (`@objectstack/lint`'s + * `validateObjectPinnedActions`). + * + * 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. + */ + +/** The most actions one page header draws as buttons. */ +export const OBJECT_PINNED_ACTION_LIMIT = 3; + +/** The page types an object's header actions are pinned on. */ +export const OBJECT_PINNED_ACTION_PAGES = ['list', 'record'] as const; +export type ObjectPinnedActionPage = (typeof OBJECT_PINNED_ACTION_PAGES)[number]; + +/** + * The built-in buttons a page header may pin beside the object's actions, per + * page type. The list page's import and export are the console's own buttons, + * not object actions; the record page has none. + */ +export const OBJECT_PINNED_BUILTIN_ACTIONS: Readonly> = { + list: ['$import', '$export'], + record: [], +}; + +/** + * The entries one page's arm accepts: an action name (the spelling + * `ActionSchema.name` accepts, `SnakeCaseIdentifierSchema`: lowercase snake + * case, two characters at least) or one of the page's built-ins. A pattern, + * so the JSON Schema states it too. + */ +function pinPattern(page: ObjectPinnedActionPage): RegExp { + const builtins = OBJECT_PINNED_BUILTIN_ACTIONS[page].map((b) => `|\\${b}`).join(''); + return new RegExp(`^(?:[a-z][a-z0-9_]+${builtins})$`); +} + +function builtinsSentence(page: ObjectPinnedActionPage): string { + const builtins = OBJECT_PINNED_BUILTIN_ACTIONS[page]; + return builtins.length > 0 + ? `the ${page} page's built-ins are ${builtins.map((b) => `\`${b}\``).join(', ')}` + : `the ${page} page has no built-in, pin an action name`; +} + +/** Why `pin` is no entry of the `page` arm. */ +function pinRefusal(page: ObjectPinnedActionPage, pin: unknown): string { + const text = String(pin); + return text.startsWith('$') + ? `\`${text}\` is not a built-in of the ${page} page: ${builtinsSentence(page)}.` + : `\`${text}\` is not an action name (lowercase snake_case, as the action's \`name\`) ` + + `nor a built-in (${builtinsSentence(page)}).`; +} + +function pinnedArm(page: ObjectPinnedActionPage) { + return z + .array(z.string().regex(pinPattern(page), { error: (issue) => pinRefusal(page, issue.input) })) + .max(OBJECT_PINNED_ACTION_LIMIT, { + error: (issue) => + `\`pinnedActions.${page}\` pins ${Array.isArray(issue.input) ? issue.input.length : 'more'} actions; ` + + `a header draws at most ${OBJECT_PINNED_ACTION_LIMIT} as buttons and puts every other action in 「More」. ` + + `Keep the first ${OBJECT_PINNED_ACTION_LIMIT}.`, + }) + .superRefine((pins, ctx) => { + // Uniqueness is the one rule JSON Schema is not given here. + const seen = new Set(); + pins.forEach((pin, index) => { + if (seen.has(pin)) { + ctx.addIssue({ + code: 'custom', + path: [index], + message: `\`${pin}\` is pinned twice on the ${page} page; a header draws an action once.`, + }); + } + seen.add(pin); + }); + }); +} + +/** + * The `pinnedActions` leaf, shared by `ObjectSchema` and `ObjectExtensionSchema`. + * Optional with no default: absent draws every header as before. + */ +export const OBJECT_PINNED_ACTIONS_SCHEMA = strictObject( + { + surface: "this object's `pinnedActions`", + history: 'Closed from its first release (objectstack#36366): no key here was ever dropped silently.', + aliases: { listPage: 'list', recordPage: 'record' }, + }, + { + list: pinnedArm('list') + .optional() + .describe( + "The list page header's buttons, in order: action names of the object placed at `list_toolbar`, " + + 'or `$import` / `$export`. At most 3; every other action goes to 「More」. Omit to draw the header as before.', + ), + record: pinnedArm('record') + .optional() + .describe( + "The record page header's buttons, in order: action names of the object placed at `record_header` " + + 'or `record_more`. At most 3; every other action goes to 「More」. Omit to draw the header as before.', + ), + }, +) + .optional() + .describe( + 'The actions each page header of the object shows as buttons, per page type (`list`, `record`), in order, ' + + 'at most 3 per page; every other action the header places goes to its 「More」 menu. Omit to keep the ' + + "header's own choice (each action's `order`).", + ); + +/** An object's pinned header actions, as authored. */ +export type ObjectPinnedActions = z.input; diff --git a/packages/spec/src/data/object.form.ts b/packages/spec/src/data/object.form.ts index b9d04d76b9a..d142c616941 100644 --- a/packages/spec/src/data/object.form.ts +++ b/packages/spec/src/data/object.form.ts @@ -755,6 +755,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 header buttons per page type. Each arm is a list of names + // (the `string-tags` face): action names of the object, or the list + // page's `$import` / `$export`. The design mode edits it on the page. + { + field: 'pinnedActions', + type: 'composite', + helpText: 'Which actions each page header shows as buttons, in order, at most 3 per page; every other action the header places goes to its More menu. Unset: each header picks its buttons by the actions\' order, as before.', + fields: [ + { field: 'list', label: 'List page', widget: 'string-tags', helpText: 'Action names placed on the list toolbar, or $import / $export, in the order they are drawn. At most 3. os validate refuses a name that is no action of this object or is not placed on the list toolbar; such a name draws no button.' }, + { field: 'record', label: 'Record page', widget: 'string-tags', helpText: 'Action names placed in the record header or its More menu, in the order they are drawn. At most 3. os validate refuses a name that is no action of this object or is not placed on the record page; such a name draws no button.' }, + ], + }, { 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 7639786fa97..d20482344b0 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 header buttons per page type, shared with the object extension. +import { OBJECT_PINNED_ACTIONS_SCHEMA } from './object-pinned-actions'; // 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. @@ -4047,6 +4049,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 actions each page header shows as buttons (list, record), at most 3 each. + pinnedActions: OBJECT_PINNED_ACTIONS_SCHEMA, /** * Taxonomy & Organization @@ -6920,12 +6924,12 @@ 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 + // pinnedActions / validations / indexes / priority) 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. ' + + '`fields`, `label`, `pluralLabel`, `description`, `pinnedActions`, `validations` and ' + + '`indexes`, and applies `fieldPatches`, and 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 ' + @@ -7034,6 +7038,14 @@ export const ObjectExtensionSchema = lazySchema(() => strictObject({ /** Override description */ description: z.string().optional().describe('Override description for the extended object'), + + /** + * [#36366] Override the extended object's pinned header actions, as on the + * object itself (`ObjectSchema.pinnedActions`). A fold scalar like `label`: + * the last extender by `priority` wins, and a value the tenant authored on + * the base stays (ADR-0029 D9.2a). + */ + pinnedActions: OBJECT_PINNED_ACTIONS_SCHEMA, /** Additional validation rules to add */ validations: z.array(ValidationRuleSchema).optional().describe('Additional validation rules to merge into the target object'), From b8b61fa58924a05cb0632c1480a517da249633d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:37:26 +0000 Subject: [PATCH 02/22] feat(objectql): the object fold carries an extension's pinned header actions (#36366) `pinnedActions` is a fourth `OBJECT_FOLD_SCALAR_KEYS` member: an extension's arm replaces the running arm, an arm it leaves out stays, the higher `priority` is written last, and pins the tenant authored on the base stay (ADR-0029 D9.2a). It is not a string, so the yield asks the shared question by structure (`foldScalarOverridesPackagedBase`), with the string predicate's three conservative edges. Claude-Session: https://claude.ai/code/session_01QsR2jSr8sNCnJrK6Q9kEF5 Co-authored-by: Claude --- .../registry-extension-pinned-actions.test.ts | 98 +++++++++++++++++++ .../src/registry-object-registration.ts | 13 +-- packages/objectql/src/registry-top-level.ts | 37 ++++++- packages/objectql/src/registry.ts | 13 ++- 4 files changed, 147 insertions(+), 14 deletions(-) create mode 100644 packages/objectql/src/registry-extension-pinned-actions.test.ts diff --git a/packages/objectql/src/registry-extension-pinned-actions.test.ts b/packages/objectql/src/registry-extension-pinned-actions.test.ts new file mode 100644 index 00000000000..37115740f77 --- /dev/null +++ b/packages/objectql/src/registry-extension-pinned-actions.test.ts @@ -0,0 +1,98 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36366 — `pinnedActions`, the header buttons per page type, is a + * fold scalar of the object extension (ADR-0146 D10: an installed object is + * extended, never replaced). The fold (`mergeObjectDefinitions`) carries it + * arm by arm: an arm the extension sets replaces the running arm, an arm it + * leaves out stays. Two extenders resolve by `priority` (the higher one is + * written last), and a value the tenant authored on the base stays (the + * ADR-0029 D9.2a yield the three string scalars take). + */ + +import { describe, it, expect } 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 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 pinned = (r: SchemaRegistry) => (r.getObject('crm_lead') as unknown as Record).pinnedActions; + +describe('#36366 — an object extension pins header actions', () => { + it('an extension-only pin: the base pins nothing, the object is served with the extension\'s pins', () => { + const r = registry(); + r.registerObjectExtension({ extend: 'crm_lead', pinnedActions: { record: ['convert_lead', 'log_call'] } }, PAIR); + expect(pinned(r)).toEqual({ record: ['convert_lead', 'log_call'] }); + }); + + it('a base plus extension pin: the arm the extension sets replaces the base\'s, the other arm stays', () => { + const r = registry({ ...LEAD, pinnedActions: { list: ['$export'], record: ['log_call'] } }); + r.registerObjectExtension({ extend: 'crm_lead', pinnedActions: { record: ['convert_lead'] } }, PAIR); + expect(pinned(r)).toEqual({ list: ['$export'], record: ['convert_lead'] }); + }); + + it('an empty arm is a pin too: nothing drawn as a button on that page', () => { + const r = registry({ ...LEAD, pinnedActions: { record: ['log_call'] } }); + r.registerObjectExtension({ extend: 'crm_lead', pinnedActions: { record: [] } }, PAIR); + expect(pinned(r)).toEqual({ record: [] }); + }); + + it('an extension that pins nothing leaves the base\'s pins, and the packaged base keeps its own', () => { + const r = registry({ ...LEAD, pinnedActions: { record: ['log_call'] } }); + r.registerObjectExtension({ extend: 'crm_lead', label: 'Prospect' }, PAIR); + expect(pinned(r)).toEqual({ record: ['log_call'] }); + r.registerObjectExtension({ extend: 'crm_lead', pinnedActions: { record: ['convert_lead'] }, priority: 300 }, PARTNER); + expect((r.getPackagedObjectBase('crm_lead') as unknown as Record).pinnedActions).toEqual({ record: ['log_call'] }); + }); + + it('two extenders resolve by priority: the higher one is written last', () => { + const r = registry(); + r.registerObjectExtension({ extend: 'crm_lead', pinnedActions: { record: ['a_partner'] }, priority: 250 }, PARTNER); + r.registerObjectExtension({ extend: 'crm_lead', pinnedActions: { record: ['a_custom'] }, priority: 150 }, PAIR); + expect(pinned(r)).toEqual({ record: ['a_partner'] }); + }); + + it('pins the tenant authored on the base stay over an extender\'s (ADR-0029 D9.2a)', () => { + const r = registry({ ...LEAD, pinnedActions: { record: ['log_call'] } }); + r.registerObject({ ...clone(LEAD), pinnedActions: { record: ['send_email'] }, _provenance: 'org' } as never, BASE, undefined, 'overlay'); + r.registerObjectExtension({ extend: 'crm_lead', pinnedActions: { record: ['convert_lead'] } }, PAIR); + expect(pinned(r)).toEqual({ record: ['send_email'] }); + }); + + it('a tenant overlay that repeats the packaged pins authored nothing: the extender applies', () => { + const r = registry({ ...LEAD, pinnedActions: { record: ['log_call'] } }); + r.registerObject({ ...clone(LEAD), pinnedActions: { record: ['log_call'] }, _provenance: 'org' } as never, BASE, undefined, 'overlay'); + r.registerObjectExtension({ extend: 'crm_lead', pinnedActions: { record: ['convert_lead'] } }, PAIR); + expect(pinned(r)).toEqual({ record: ['convert_lead'] }); + }); + + it('is idempotent over an already-folded base', () => { + const r = registry({ ...LEAD, pinnedActions: { list: ['$import'] } }); + r.registerObjectExtension({ extend: 'crm_lead', pinnedActions: { record: ['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.pinnedActions).toEqual(once.pinnedActions); + }); + + it('control: an object nothing pins is served without the key', () => { + const r = registry(); + r.registerObjectExtension({ extend: 'crm_lead', label: 'Prospect' }, PAIR); + expect('pinnedActions' in (r.getObject('crm_lead') as object)).toBe(false); + }); +}); diff --git a/packages/objectql/src/registry-object-registration.ts b/packages/objectql/src/registry-object-registration.ts index 3eaa3c2318b..df5b303fb62 100644 --- a/packages/objectql/src/registry-object-registration.ts +++ b/packages/objectql/src/registry-object-registration.ts @@ -49,7 +49,6 @@ import { BASE_FIELD_DISPLAY_WHITELIST, isInjectedColumnDefinition, materializeTr import type { ObjectOwnership, RelatedListsArrangement, ServiceObject } from '@objectstack/spec/data'; import { QUEUE_FIELD_DEF, applyAuditFieldGovernance, fieldPatchTargetMisses, installedManifestsOf, isCodeArtifactBody, isTenantAuthored, pairsOf } from '@objectstack/metadata-core'; import type { FieldPatchTargetMiss } from '@objectstack/metadata-core'; -import { scalarOverridesPackagedBase } from '@objectstack/spec/system'; import { SEARCH_COMPANION_FIELD, provisionSearchCompanion } from './search-companion.js'; import { applyExtensionPlacements, fieldGroupKeysOf, placementContributorsOf } from './registry-extension-placement.js'; import type { ExtensionPlacementNote } from './registry-extension-placement.js'; @@ -62,7 +61,7 @@ import type { RecordCurrencyFollowRefusedError } from './record-currency-aggrega import { DEFAULT_EXTENDER_PRIORITY, DEFAULT_OVERLAY_PRIORITY, DEFAULT_OWNER_PRIORITY, NO_PACKAGE_REFERRER, OBJECT_FOLD_SCALAR_KEYS, QUEUE_FIELD, admittedFieldPatches, changedPackagedRuleKeys, computeFQN, - displayKeyOverridesPackagedBase, fieldNamesOf, fieldPatchYieldKey, indexKeysOf, isLeftOutExtension, + displayKeyOverridesPackagedBase, fieldNamesOf, fieldPatchYieldKey, foldScalarOverridesPackagedBase, indexKeysOf, isLeftOutExtension, isPackagelessActionSlotKey, isPlainRecord, leavesExtensionsOut, mergeValidationsByName, optionByValue, ownFieldNamesOf, ownFieldsTarget, parseOverlaySlotKey, parsePackageObjectActions, picklistReferrerOf, reconcileManagedApiMethods, recordFieldOf, ruleNamesOf, sortActionsByOrder, stableStringify, storedRowPackageOf, @@ -1313,7 +1312,7 @@ export class ObjectRegistrationFacet { } /** - * [ADR-0029 D9.2a] Which of the three fold scalars the BASE layer carries a + * [ADR-0029 D9.2a] Which of the fold scalars the BASE layer carries a * TENANT-AUTHORED value for — i.e. one that no longer equals the packaged * owner's. * @@ -1323,8 +1322,10 @@ export class ObjectRegistrationFacet { * extender yields. This **amends ADR-0029 D9.2**, whose fold was * unconditionally last-writer-wins on the scalars, and it is deliberately the * SAME comparison-based mechanism the #8284 fix applies one layer up — the - * predicate is literally {@link scalarOverridesPackagedBase}, imported from - * `@objectstack/spec`, not a second copy of the shape. One sentence at both + * predicate is literally `scalarOverridesPackagedBase`, imported from + * `@objectstack/spec`, not a second copy of the shape ([#36366] the + * structured scalar `pinnedActions` asks the same question by its structure, + * `foldScalarOverridesPackagedBase`). One sentence at both * layers: *an explicit override beats a packaged default.* * * ⛔ No provenance flag is stamped on the document and no migration is @@ -1373,7 +1374,7 @@ export class ObjectRegistrationFacet { if (!owner || owner === baseDefinition) return undefined; let authored: Set | undefined; for (const key of OBJECT_FOLD_SCALAR_KEYS) { - if (scalarOverridesPackagedBase(owner, key, baseDefinition[key])) { + if (foldScalarOverridesPackagedBase(owner, key, baseDefinition[key])) { (authored ??= new Set()).add(key); } } diff --git a/packages/objectql/src/registry-top-level.ts b/packages/objectql/src/registry-top-level.ts index 5cffdd711f6..303c689dcbd 100644 --- a/packages/objectql/src/registry-top-level.ts +++ b/packages/objectql/src/registry-top-level.ts @@ -414,14 +414,41 @@ export function parseFQN(fqn: string): { namespace: string | undefined; shortNam } /** - * The three SCALAR props {@link mergeObjectDefinitions} resolves last-writer-wins - * — the exact set the #8284 ruling and ADR-0029 D9.2a both cover, and the same three - * {@link scalarOverridesPackagedBase} answers for. + * The SCALAR props {@link mergeObjectDefinitions} resolves last-writer-wins + * — the three string scalars the #8284 ruling and ADR-0029 D9.2a both cover, + * which {@link scalarOverridesPackagedBase} answers for, and [#36366] + * `pinnedActions`, the object's header buttons per page type, which + * {@link foldScalarOverridesPackagedBase} answers for by its structure. */ -const OBJECT_FOLD_SCALAR_KEYS = ['label', 'pluralLabel', 'description'] as const; +const OBJECT_FOLD_SCALAR_KEYS = ['label', 'pluralLabel', 'description', 'pinnedActions'] as const; type ObjectFoldScalarKey = (typeof OBJECT_FOLD_SCALAR_KEYS)[number]; +/** [#36366] A `pinnedActions` value as one comparable string (its two arms, in order), or `null` when it pins nothing. */ +function pinnedActionsKey(value: unknown): string | null { + if (!isPlainRecord(value)) return null; + const list = Array.isArray(value.list) ? value.list : null; + const record = Array.isArray(value.record) ? value.record : null; + return list === null && record === null ? null : JSON.stringify([list, record]); +} + +/** + * [ADR-0029 D9.2a] Whether the fold's base carries `value` for the scalar + * `key` authored away from the packaged owner's. The string scalars ask + * {@link scalarOverridesPackagedBase}, the one comparison both layers share. + * [#36366] `pinnedActions` is not a string, so that predicate answers `false` + * for it whatever the base holds; it asks the same question by structure, + * with the predicate's three conservative edges: no owner document → `false`, + * a value that pins nothing → `false`, and equality is exact (both arms, in + * order). + */ +function foldScalarOverridesPackagedBase(owner: unknown, key: ObjectFoldScalarKey, value: unknown): boolean { + if (key !== 'pinnedActions') return scalarOverridesPackagedBase(owner, key, value); + if (!isPlainRecord(owner)) return false; + const authored = pinnedActionsKey(value); + return authored !== null && authored !== pinnedActionsKey(owner.pinnedActions); +} + /** * [ADR-0146 D10, second rule] An object extension's per-field display patches: * the slot `ObjectExtensionSchema.fieldPatches` declares, carried onto the @@ -2249,7 +2276,7 @@ export { QUEUE_FIELD, RunRegisteredObject, SECURITY_CATALOG_NAME_RULE, ServedObjectLayer, TenantRuleSettings, WithheldExtensions, admittedFieldPatches, applyFieldPatches, bareNameConflictLine, bareNameReasonFor, bundleBaseKey, carriesTenantScopeColumn, changedPackagedRuleKeys, coldBootConflictMessage, collectBundle, declaredOwnedObjectNames, - declaresTenantIndex, displayKeyOverridesPackagedBase, entriesOfMember, fieldNamesOf, fieldPatchYieldKey, + declaresTenantIndex, displayKeyOverridesPackagedBase, entriesOfMember, fieldNamesOf, fieldPatchYieldKey, foldScalarOverridesPackagedBase, indexKeysOf, isLeftOutExtension, isPackagelessActionSlotKey, isPlainRecord, isStoredActionRow, leavesExtensionsOut, mergeValidationsByName, optionByValue, overlaySlotEntriesOf, overlaySlotKey, ownFieldNamesOf, ownFieldsTarget, packageBodySlot, packagedAddedFields, packagelessActionOwnerKey, packagelessActionSlotEntriesOf, diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index 1ecbe1aa56a..a7131d55c77 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -204,8 +204,9 @@ export { * [ADR-0029 D9.2a, 2026-10-30 note]): rules of different names add, and a * rule of a name already folded replaces it — with `tenantRules`, carrying * the tenant's `message` and `active`, never the tenant's condition. - * - The three {@link OBJECT_FOLD_SCALAR_KEYS} (`label`, `pluralLabel`, - * `description`) are overridden last-writer-wins, subject to the + * - The {@link OBJECT_FOLD_SCALAR_KEYS} (`label`, `pluralLabel`, + * `description`, and [#36366] `pinnedActions` arm by arm) are overridden + * last-writer-wins, subject to the * `tenantAuthored` yield rule below. [#30391] A `label` that renames the * object without a `pluralLabel` beside it also takes the running * `pluralLabel` off: the plural named the old label. @@ -232,7 +233,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` / `pinnedActions` / `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 @@ -309,6 +310,12 @@ function mergeObjectDefinitions( if (extension.description !== undefined && !yields('description')) { merged.description = extension.description; } + // [#36366] The header buttons per page type, a fold scalar like the three + // above, arm by arm: an arm the extension sets replaces the running arm, an + // arm it leaves out stays as folded. + if (extension.pinnedActions !== undefined && !yields('pinnedActions')) { + merged.pinnedActions = { ...merged.pinnedActions, ...extension.pinnedActions }; + } // [ADR-0146 D10, second rule] The extension's display patches of the // owner's own fields (`ownFields`) — never of a field an extension adds, From 30ce73490e6f7cec3c48c55feaaf6d1b9cb84b90 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:37:26 +0000 Subject: [PATCH 03/22] feat(lint): a pinned header action that names no placed action is refused (#36366) `validateObjectPinnedActions` (gating, os validate / build / lint): a name in an object's or an object extension's `pinnedActions` that is no action of the object (`object-pinned-action-unknown`), or one not placed on that page (`object-pinned-action-not-placed`: `list_toolbar` for the list arm, `record_header` / `record_more` for the record arm). An extension of an object the stack does not define is not judged. CLI only: the runtime snapshot carries no stack `actions` (RUNTIME_NEEDS_FULL_SNAPSHOT). Claude-Session: https://claude.ai/code/session_01QsR2jSr8sNCnJrK6Q9kEF5 Co-authored-by: Claude --- packages/lint/src/authoring-rules.ts | 18 ++ packages/lint/src/index.ts | 6 + .../validate-object-pinned-actions.test.ts | 81 +++++++++ .../src/validate-object-pinned-actions.ts | 156 ++++++++++++++++++ 4 files changed, 261 insertions(+) create mode 100644 packages/lint/src/validate-object-pinned-actions.test.ts create mode 100644 packages/lint/src/validate-object-pinned-actions.ts diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 47d69056a25..a621db4f0f3 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 { validateObjectPinnedActions } from './validate-object-pinned-actions.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 pinned header actions (`pinnedActions`, and an + // object extension's) that name no action of the object, or one not placed + // on the page the arm pins: the pin draws no button. Gating, because the + // author's pin 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: 'validateObjectPinnedActions', + tier: 'gating', + input: 'parsed', + commands: ALL, + source: 'packages/lint/src/validate-object-pinned-actions.ts', + surfaces: CLI_ONLY, + surfaceReason: RUNTIME_NEEDS_FULL_SNAPSHOT, + run: (stack) => validateObjectPinnedActions(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..08b657f8255 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 { + validateObjectPinnedActions, + OBJECT_PINNED_ACTION_UNKNOWN, + OBJECT_PINNED_ACTION_NOT_PLACED, +} from './validate-object-pinned-actions.js'; +export type { ObjectPinnedActionsFinding } from './validate-object-pinned-actions.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-pinned-actions.test.ts b/packages/lint/src/validate-object-pinned-actions.test.ts new file mode 100644 index 00000000000..9297dd1cbf0 --- /dev/null +++ b/packages/lint/src/validate-object-pinned-actions.test.ts @@ -0,0 +1,81 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36366 — `validateObjectPinnedActions`: a pinned header action + * that names no action of the object, or one not placed on the page its arm + * pins, is refused at `error` with the reason named. The object's own pins 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_PINNED_ACTION_NOT_PLACED, + OBJECT_PINNED_ACTION_UNKNOWN, + validateObjectPinnedActions, +} from './validate-object-pinned-actions.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 = {}, pinnedActions?: unknown) => ({ + objects: [{ ...LEAD, ...(pinnedActions ? { pinnedActions } : {}) }], + actions: [{ name: 'send_email', objectName: 'crm_lead', label: 'Send email', locations: ['record_header', 'list_toolbar'] }], + ...extra, +}); + +const rules = (s: Record) => validateObjectPinnedActions(s).map((f) => `${f.rule} ${f.path}`); + +describe('validateObjectPinnedActions (objectstack#36366)', () => { + it('passes pins of placed actions, own and stack-bound, and the $ built-ins', () => { + expect(rules(stack({}, { record: ['convert_lead', 'log_call', 'send_email'], list: ['$export', 'mass_assign', 'send_email'] }))).toEqual([]); + expect(rules(stack())).toEqual([]); + }); + + it('refuses a name no action of the object has, at error, naming it', () => { + const [finding] = validateObjectPinnedActions(stack({}, { record: ['convert_lead', 'close_lead'] })); + expect(finding).toMatchObject({ + severity: 'error', + rule: OBJECT_PINNED_ACTION_UNKNOWN, + where: 'object "crm_lead"', + path: 'objects[0].pinnedActions.record[1]', + }); + expect(finding.message).toContain('"close_lead"'); + }); + + it('refuses an action not placed on the page its arm pins', () => { + expect(rules(stack({}, { list: ['convert_lead'], record: ['mass_assign', 'headless'] }))).toEqual([ + `${OBJECT_PINNED_ACTION_NOT_PLACED} objects[0].pinnedActions.list[0]`, + `${OBJECT_PINNED_ACTION_NOT_PLACED} objects[0].pinnedActions.record[0]`, + `${OBJECT_PINNED_ACTION_NOT_PLACED} objects[0].pinnedActions.record[1]`, + ]); + }); + + 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', pinnedActions: { record: ['send_email', 'nope'] } }, + { extend: 'sys_user', pinnedActions: { record: ['anything'] } }, + ], + }); + expect(rules(s)).toEqual([`${OBJECT_PINNED_ACTION_UNKNOWN} objectExtensions[0].pinnedActions.record[1]`]); + }); + + 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 === 'validateObjectPinnedActions'); + expect(rule).toMatchObject({ tier: 'gating', surfaces: ['cli'] }); + expect(rule?.surfaceReason).toMatch(/snapshot/); + expect(barrel.OBJECT_PINNED_ACTION_UNKNOWN).toBe('object-pinned-action-unknown'); + expect(barrel.OBJECT_PINNED_ACTION_NOT_PLACED).toBe('object-pinned-action-not-placed'); + }); +}); diff --git a/packages/lint/src/validate-object-pinned-actions.ts b/packages/lint/src/validate-object-pinned-actions.ts new file mode 100644 index 00000000000..525534566cf --- /dev/null +++ b/packages/lint/src/validate-object-pinned-actions.ts @@ -0,0 +1,156 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { recordsOf } from './object-graph.js'; + +/** + * An object's pinned header actions (`pinnedActions`, objectstack#36366) that + * name no action the header can draw. + * + * `pinnedActions.list` / `.record` name, in order, the actions a page header + * draws as buttons; every other action it places goes to 「More」. The schema + * refuses the SHAPE at every door (more than three, an entry twice, a + * malformed entry, a `$` built-in the page 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 on the page the arm pins it on. A name that is not + * would draw no button at all, so the author's pin is lost without a word. + * This rule refuses it, at `error`, naming the reason: + * + * - `object-pinned-action-unknown`: no action of that name is declared on the + * object (its own `actions`, or a stack action whose `objectName` is it); + * - `object-pinned-action-not-placed`: the action is declared but not placed + * on that page: `list_toolbar` for the `list` arm, `record_header` or + * `record_more` for the `record` arm (the record header draws both). + * + * Both object positions are judged: an object's own `pinnedActions`, 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 pin that reaches the server another way names nothing the + * header draws, so it draws no button. + */ + +export const OBJECT_PINNED_ACTION_UNKNOWN = 'object-pinned-action-unknown'; +export const OBJECT_PINNED_ACTION_NOT_PLACED = 'object-pinned-action-not-placed'; + +export interface ObjectPinnedActionsFinding { + /** Always `error`: the pin 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].pinnedActions.record[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 pinned name that names no action of the object, or one not + * placed on the page its arm pins. Returns findings (empty = clean). + */ +export function validateObjectPinnedActions(stack: AnyRec): ObjectPinnedActionsFinding[] { + const findings: ObjectPinnedActionsFinding[] = []; + 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 = (pinned: unknown, objectName: string, object: AnyRec, at: string, where: string): void => { + if (!pinned || typeof pinned !== 'object' || Array.isArray(pinned)) return; + const actions = actionsOf(stack, object, objectName); + for (const arm of ['list', 'record'] as const) { + const pins = (pinned as AnyRec)[arm]; + if (!Array.isArray(pins)) continue; + const locations = ARM_LOCATIONS[arm]; + const page = arm === 'list' ? 'list page' : 'record page'; + pins.forEach((pin, index) => { + const name = strName(pin); + if (!name || name.startsWith('$')) return; + const path = `${at}.pinnedActions.${arm}[${index}]`; + const action = actions.get(name); + if (!action) { + findings.push({ + severity: 'error', + rule: OBJECT_PINNED_ACTION_UNKNOWN, + where, + path, + message: `"${objectName}" pins "${name}" on its ${page} header, and "${objectName}" declares no action of that name, so the pin draws no button`, + hint: + `Pin an action of "${objectName}" by its name (its own actions, or a stack action with objectName: ` + + `'${objectName}'), or remove "${name}" from pinnedActions.${arm}`, + }); + return; + } + const placed = Array.isArray(action.locations) && action.locations.some((l) => locations.includes(l as string)); + if (!placed) { + findings.push({ + severity: 'error', + rule: OBJECT_PINNED_ACTION_NOT_PLACED, + where, + path, + message: + `"${objectName}" pins "${name}" on its ${page} header, and that action is not placed there ` + + `(locations ${locations.map((l) => `'${l}'`).join(' or ')}), so the pin draws no button`, + hint: + `Add ${locations.map((l) => `'${l}'`).join(' or ')} to the locations of "${name}", or remove it ` + + `from pinnedActions.${arm}`, + }); + } + }); + } + }; + + objects.forEach((object, i) => { + const name = strName(object.name); + if (name) judge(object.pinnedActions, 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.pinnedActions, target, object, `objectExtensions[${i}]`, `object extension of "${target}"`); + } + }); + + return findings; +} From e2d345db1fc71a45075dbd0a5f480d6e715902ce Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 11:54:05 +0000 Subject: [PATCH 04/22] feat(console): the page headers draw an object's pinned actions, and the design mode sets them (#36366) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both record headers (the default page's and an authored page:header with placedActions: true) and the list header read pinnedActions through one reader, pinnedHeaderActions. In the design mode, 「Header buttons」 at the end of the header moves actions between 「Pinned to header」 (at most three, dragged into order) and 「Other」; the header shows the staged change, and Save writes it into the object's own package or, for an installed object, its customization package as an object_extension, refusing a name the header cannot draw. Liveness row, docs, skill note. Claude-Session: https://claude.ai/code/session_01QsR2jSr8sNCnJrK6Q9kEF5 Co-authored-by: Claude --- .../36366-object-pinned-header-actions.md | 25 ++ .../docs/data-modeling/object-extensions.mdx | 3 +- content/docs/ui/actions.mdx | 28 +++ packages/spec/liveness/object.json | 23 ++ .../src/layout/DesignModeHeaderPins.tsx | 56 +++++ .../src/layout/DesignModeHeaderPinsPanel.tsx | 232 ++++++++++++++++++ .../DesignModeHeaderPins-36366.test.tsx | 206 ++++++++++++++++ .../designModeHeaderPins-36366.test.ts | 90 +++++++ .../designModeHeaderPinsSave-36366.test.ts | 165 +++++++++++++ .../src/layout/designModeHeaderPins.ts | 175 +++++++++++++ .../src/layout/designModeHeaderPinsSave.ts | 146 +++++++++++ ...ordDetailView.pinnedActions-36366.test.tsx | 193 +++++++++++++++ .../app-shell/src/views/RecordDetailView.tsx | 63 ++++- ...iewPageHeader.pinnedActions-36366.test.tsx | 120 +++++++++ .../src/views/objectViewPageHeader.tsx | 154 ++++++++++-- .../src/renderers/layout/containers.tsx | 22 +- .../layout/record-header-bar-context.ts | 8 + ui/packages/i18n/src/locales/ar.ts | 15 ++ ui/packages/i18n/src/locales/de.ts | 15 ++ ui/packages/i18n/src/locales/en.ts | 15 ++ ui/packages/i18n/src/locales/es.ts | 15 ++ ui/packages/i18n/src/locales/fr.ts | 15 ++ ui/packages/i18n/src/locales/ja.ts | 15 ++ ui/packages/i18n/src/locales/ko.ts | 15 ++ ui/packages/i18n/src/locales/pt-BR.ts | 15 ++ ui/packages/i18n/src/locales/ru.ts | 15 ++ ui/packages/i18n/src/locales/zh-Hans.ts | 15 ++ ui/packages/i18n/src/locales/zh-Hant.ts | 15 ++ .../pinned-header-actions-36366.test.ts | 73 ++++++ ui/packages/types/src/index.ts | 1 + ui/packages/types/src/ui-action.ts | 61 +++++ 31 files changed, 1977 insertions(+), 32 deletions(-) create mode 100644 .changeset/36366-object-pinned-header-actions.md create mode 100644 ui/packages/app-shell/src/layout/DesignModeHeaderPins.tsx create mode 100644 ui/packages/app-shell/src/layout/DesignModeHeaderPinsPanel.tsx create mode 100644 ui/packages/app-shell/src/layout/__tests__/DesignModeHeaderPins-36366.test.tsx create mode 100644 ui/packages/app-shell/src/layout/__tests__/designModeHeaderPins-36366.test.ts create mode 100644 ui/packages/app-shell/src/layout/__tests__/designModeHeaderPinsSave-36366.test.ts create mode 100644 ui/packages/app-shell/src/layout/designModeHeaderPins.ts create mode 100644 ui/packages/app-shell/src/layout/designModeHeaderPinsSave.ts create mode 100644 ui/packages/app-shell/src/views/RecordDetailView.pinnedActions-36366.test.tsx create mode 100644 ui/packages/app-shell/src/views/objectViewPageHeader.pinnedActions-36366.test.tsx create mode 100644 ui/packages/types/src/__tests__/pinned-header-actions-36366.test.ts diff --git a/.changeset/36366-object-pinned-header-actions.md b/.changeset/36366-object-pinned-header-actions.md new file mode 100644 index 00000000000..bf10865a85a --- /dev/null +++ b/.changeset/36366-object-pinned-header-actions.md @@ -0,0 +1,25 @@ +--- +'@objectstack/spec': minor +'@objectstack/objectql': minor +'@objectstack/lint': minor +'@objectstack/metadata-core': 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 chooses its page headers' buttons (`pinnedActions`), and the design mode sets them + +Clause-②: yes (widening) +Metadata-protocol: added +Skills-docs: follow-up owed — skills/objectstack-ui/rules/actions.md (its token ceiling has no room: 3,711, and the paragraph costs ~170) + +A page header draws at most three of its actions as buttons and puts the rest in its 「More」 menu. An object now chooses which, per page type, with the new optional key `pinnedActions` on `ObjectSchema` and `ObjectExtensionSchema`: `{ list?: string[]; record?: string[] }`, each at most three names, in the order drawn. `list` names actions placed at `list_toolbar` and the list page's built-ins `$import` and `$export`; `record` names actions placed at `record_header` or `record_more`. Every other action the page places goes to 「More」. An arm left out (or the key left out) keeps the header's own choice, as before. + +- `@objectstack/spec`: the key and its shape refusals at every door (more than three, a name twice, a malformed name, a built-in the page does not have), each with its reason. New exports `OBJECT_PINNED_ACTION_LIMIT`, `OBJECT_PINNED_ACTION_PAGES`, `OBJECT_PINNED_BUILTIN_ACTIONS` and the types `ObjectPinnedActionPage`, `ObjectPinnedActions`. The object form offers it under Advanced. +- `@objectstack/objectql`: an `object_extension`'s `pinnedActions` folds onto the object arm by arm (the last extender by priority wins), and yields to a tenant's own pins as `label` does (ADR-0029 D9.2a). New export `foldScalarOverridesPackagedBase`. +- `@objectstack/lint`: `validateObjectPinnedActions` (`object-pinned-action-unknown`, `object-pinned-action-not-placed`, at `error`) refuses in `os validate`, `os build` and `os lint` a pinned name that is no action of the object, or one not placed on that page. +- `@object-ui/types`: `pinnedHeaderActions(actions, pins, page)`, the one reader both record headers and the list header apply. +- The console: both record headers (the default page's and an authored `page:header` with `placedActions: true`) and the list header draw the pins. In the design mode, 「Header buttons」 at the end of the page header lists the page's actions under 「Pinned to header」 (dragged into order) and 「Other」; 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 it: into the object's own package when it is writable, else into the installed object's customization package as an `object_extension`. 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..35d466b2110 100644 --- a/content/docs/data-modeling/object-extensions.mdx +++ b/content/docs/data-modeling/object-extensions.mdx @@ -69,6 +69,7 @@ check that spelling first. | `label` | Replaces the target's label — with one exception, [below](#extensions-and-tenant-customization). A new `label` with no `pluralLabel` beside it also takes the target's plural off, since that plural names the old label: the object is served as one that declares no plural, and lists title it by its label. Set `pluralLabel` too to serve one. A plural the tenant set stays. | | `pluralLabel` | Same as `label`. | | `description` | Same as `label`. | +| `pinnedActions` | **Applied arm by arm.** An extension's `list` or `record` list replaces the target's list for that page; an arm it leaves out keeps the target's. Yields to a tenant's own pins as `label` does. See [choosing the header's buttons](/docs/ui/actions#choose-the-headers-buttons). | | `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. | | `priority` | Not merged — it *orders* the merge. `0`–`999`, default `200`. | @@ -414,7 +415,7 @@ survive a customized object rather than being dropped by it. One deliberate asymmetry, ruled 2026-08-13: an extension's `label`, `pluralLabel` and - `description` apply only while the base still carries the **packaged owner's** value. + `description` (and, since objectstack#36366, `pinnedActions`) apply only while the base still carries the **packaged owner's** value. Once a tenant has renamed the object, the extension's packaged default yields and the tenant's name stands. A `fieldPatches` key yields the same way, one field (and option) at a time: a field label the tenant edited keeps the tenant's text. Fields, validations and indexes are unaffected — they merge diff --git a/content/docs/ui/actions.mdx b/content/docs/ui/actions.mdx index 237834068aa..3cfb88d2bb8 100644 --- a/content/docs/ui/actions.mdx +++ b/content/docs/ui/actions.mdx @@ -375,6 +375,34 @@ 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 +chooses them itself with `pinnedActions`, one list per page type, in the order drawn: + +```typescript +ObjectSchema.create({ + name: 'crm_opportunity', + // ... + pinnedActions: { + list: ['mass_assign', '$export'], // the list page: actions at list_toolbar + record: ['mark_won', 'mark_lost', 'clone'], // the record page: actions at record_header or record_more + }, +}); +``` + +- At most three per page, each named once. Every other action the page places goes to + 「More」, including one placed at `record_header`. +- The list page also pins its built-in Import and Export as `$import` and `$export`. + The record page has no built-ins. +- Leave a list out (or `pinnedActions` out) and that header keeps its own choice. +- `os validate`, `os build` and `os lint` refuse a name that is no action of the + object, or one not placed on that page. Such a name draws no button. +- An administrator sets the same lists in the running app: 「Edit app」, then + 「Header buttons」 at the end of the page header. For an installed object the + change is saved as this environment's customization (an `object_extension`). + Surfaces can also reference actions **by name**: ```typescript diff --git a/packages/spec/liveness/object.json b/packages/spec/liveness/object.json index 49c9ee471ea..ad09ed175f0 100644 --- a/packages/spec/liveness/object.json +++ b/packages/spec/liveness/object.json @@ -30,6 +30,29 @@ "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." }, + "pinnedActions": { + "status": "live", + "verifiedAt": "2026-11-22", + "evidenceScope": "in-repo", + "evidence": "ui/packages/types/src/ui-action.ts#pinnedHeaderActions (the ONE reader: pinned actions become the header's buttons in pin order, every other placed action goes to the overflow); ui/packages/app-shell/src/views/RecordDetailView.tsx#RecordDetailView (the synthesized record header reads `pinnedActions.record`, staged pins included); 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 `pinnedActions.list`, `$import` and `$export` among the actions); packages/objectql/src/registry.ts#mergeObjectDefinitions (an `object_extension`'s pins fold onto the object, arm by arm); ui/packages/app-shell/src/layout/DesignModeHeaderPins.tsx#DesignModeHeaderPins (the design mode writes it)", + "note": "objectstack#36366: the page header's buttons per page type, at most three in order; every other action the page places is in 「More」. Absent (or an arm absent): the header's own choice, as before. An installed object is pinned through its customization package's `object_extension`.", + "children": { + "list": { + "status": "live", + "verifiedAt": "2026-11-22", + "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#pinnedHeaderActions (the unpinned toolbar actions go to the bar's overflow)", + "note": "objectstack#36366: the list page header's buttons." + }, + "record": { + "status": "live", + "verifiedAt": "2026-11-22", + "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#pinnedHeaderActions (pinned actions placed at `record_header` in pin order, the rest at `record_more`)", + "note": "objectstack#36366: the record page header's buttons." + } + } + }, "displayNameField": { "status": "live", "note": "Deprecated alias of nameField (ADR-0079); still read by objectui RecordDetailView + resolveDisplayField back-compat." 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..941e65f9a6e --- /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 pins 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 pinnedActions?: unknown }; + +/** + * The object's pins as the page's header draws them: the change staged under + * the design mode, else the object's `pinnedActions` 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 `pinnedActions`. */ + readonly objectDef: ServedObject & { readonly actions?: unknown }; + /** The page type the header is: the object's list page or its record page. */ + 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..6553c650422 --- /dev/null +++ b/ui/packages/app-shell/src/layout/DesignModeHeaderPinsPanel.tsx @@ -0,0 +1,232 @@ +// 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 page's actions in two parts, 「Pinned to header」 (at most three, + * dragged into order) and 「Other」 (in the header's 「More」 menu). A dot + * beside each action moves it between the two; pinning a fourth is refused + * with a toast and changes nothing. + * + * The change is staged under the object's key (`pinsChangeKey`), both page + * types in one value, 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, + shownPins, + togglePin, + type ObjectPins, +} from './designModeHeaderPins.js'; +import { consoleObjectPinsDoors, saveObjectPins } from './designModeHeaderPinsSave.js'; +import type { DesignModeHeaderPinsProps } from './DesignModeHeaderPins.js'; + +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 shown = shownPins(current, page, actions as never); + const candidates = React.useMemo(() => pinCandidates(actions as never, page, builtins), [actions, page, builtins]); + const labelOf = React.useCallback( + (id: string) => candidates.find((c) => c.id === id)?.label ?? id, + [candidates], + ); + const pinned = shown.filter((id) => candidates.some((c) => c.id === id) || id.startsWith('$')); + const others = candidates.filter((c) => !shown.includes(c.id)); + + 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.', + }), + 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: string[]) => { + const next: ObjectPins = { ...current, [page]: nextShown }; + if (JSON.stringify(next) === JSON.stringify(served)) { + unstage(); + return; + } + stage(next, (value) => + saveObjectPins({ objectName, packageId, served: objectDef, pins: value }, texts, consoleObjectPinsDoors(client as never)), + ); + }, + [current, page, served, stage, unstage, objectName, packageId, objectDef, texts, client], + ); + + const toggle = (id: string) => { + const next = togglePin(pinned, 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 }), + ); + const onDragEnd = (event: DragEndEvent) => { + const from = pinned.indexOf(String(event.active.id)); + const to = event.over ? pinned.indexOf(String(event.over.id)) : -1; + if (from < 0 || to < 0 || from === to) return; + update(movePin(pinned, 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' })} +

+
    + {others.map((c) => ( +
  • + + {c.label} + +
  • + ))} +
+ {others.length === 0 && ( +

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

+ )} +
+
+
+ ); +} + +function PinnedRow({ + id, + label, + onToggle, + t, +}: { + id: string; + label: string; + 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..105b5101724 --- /dev/null +++ b/ui/packages/app-shell/src/layout/__tests__/DesignModeHeaderPins-36366.test.tsx @@ -0,0 +1,206 @@ +// 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 what the header pins (the object's arm, else the + * header's own first three), moves an action between 「Pinned to header」 and + * 「Other」, refuses a fourth with a toast, stages the change so the header + * draws it, and 「Save」 writes it. + * + * 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')); + 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, pinnedActions: { record: ['clone'] } }, false); + expect(screen.queryByTestId('design-header-pins')).toBeNull(); + expect(screen.getByTestId('header-pins').textContent).toBe('{"record":["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 object with the new pins', async () => { + start(); + await openPanel(); + toggle('mark_won'); + toggle('log_call'); + expect(listed('pinned')).toEqual(['convert', 'clone', 'log_call']); + expect(screen.getByTestId('header-pins').textContent).toBe('{"record":["convert","clone","log_call"]}'); + 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', pinnedActions: { record: ['convert', 'clone', 'log_call'] } }, + { 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, pinnedActions: { record: ['log_call'] } }); + await openPanel(); + expect(listed('pinned')).toEqual(['log_call']); + 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, pinnedActions: { record: ['log_call'] } }); + await openPanel(); + toggle('log_call'); + expect(screen.getByTestId('header-pins').textContent).toBe('{"record":[]}'); + fireEvent.click(screen.getByTestId('design-mode-cancel')); + await flush(); + expect(screen.getByTestId('header-pins').textContent).toBe('{"record":["log_call"]}'); + expect(written).toEqual([]); + }); +}); 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..eebf7e4197c --- /dev/null +++ b/ui/packages/app-shell/src/layout/__tests__/designModeHeaderPins-36366.test.ts @@ -0,0 +1,90 @@ +// 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 as pinned (the object's arm, else the header's own + * first three), what it offers, the toggle with its limit of three, the + * reorder, and the save's refusal of a name the header cannot draw. + */ + +import { describe, expect, it } from 'vitest'; +import { + PIN_LIMIT, + defaultPins, + movePin, + pinCandidates, + pinsChangeKey, + pinsRefusal, + servedPins, + shownPins, + 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 pages 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({ pinnedActions: { record: ['convert'] } })).toEqual({ record: ['convert'] }); + expect(servedPins({ pinnedActions: { list: [], record: ['a', 7] } })).toEqual({ list: [], record: ['a'] }); + expect(servedPins({})).toEqual({}); + expect(servedPins({ pinnedActions: ['convert'] })).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']); + expect(shownPins({}, 'record', ACTIONS)).toEqual(['convert', 'mark_won', 'clone']); + expect(shownPins({ record: ['share'] }, 'record', ACTIONS)).toEqual(['share']); + expect(shownPins({ record: [] }, 'record', ACTIONS)).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 in place; a fourth is refused (null)', () => { + expect(togglePin(['a', 'b'], 'c')).toEqual(['a', 'b', 'c']); + expect(togglePin(['a', 'b', 'c'], 'b')).toEqual(['a', 'c']); + expect(togglePin(['a', 'b', 'c'], 'd')).toBeNull(); + }); + + it('a reorder moves one pin; an index outside the pins 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 that is no action of the object, or one not placed on the arm's page", () => { + const served = { actions: ACTIONS }; + expect(pinsRefusal(served, { record: ['convert', 'log_call'], list: ['$export', 'mass_assign'] }, TEXTS)).toBeNull(); + expect(pinsRefusal(served, { record: ['ghost'] }, TEXTS)).toBe('unknown ghost'); + expect(pinsRefusal(served, { list: ['convert'] }, TEXTS)).toBe('not placed convert'); + }); +}); 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..028f60c8170 --- /dev/null +++ b/ui/packages/app-shell/src/layout/__tests__/designModeHeaderPinsSave-36366.test.ts @@ -0,0 +1,165 @@ +// 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'; + +const TEXTS = { + notListed: 'not listed', + pendingDraft: 'pending draft', + 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; + 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: true }; + }, + client: { + layered: async (...args) => { + calls.push(['layered', ...args]); + return opts.layers ?? null; + }, + get: async (...args) => { + calls.push(['get', ...args]); + if (opts.extension === undefined) throw Object.assign(new Error('not found'), { status: 404 }); + return 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: Record) => ({ 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: ['log_call', 'convert'] }), TEXTS, d); + expect(calls).toEqual([ + ['layered', 'object', 'crm_lead', { packageId: 'com.acme.crm' }], + [ + 'save', + 'object', + 'crm_lead', + { ...authored, pinnedActions: { record: ['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: ['$export', 'mass_assign'] }), TEXTS, d); + expect(calls).toEqual([ + ['ensure', 'com.acme.crm'], + ['get', 'object_extension', 'crm_lead', { packageId: 'com.acme.crm.custom' }], + [ + 'save', + 'object_extension', + 'crm_lead', + { extend: 'crm_lead', pinnedActions: { list: ['$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' } }, + pinnedActions: { record: ['convert'] }, + _packageId: 'com.acme.crm.custom', + }; + const { d, calls } = doors({ writable: false, extension }); + await saveObjectPins(input({ record: ['log_call'] }), TEXTS, d); + const save = calls.find((c) => c[0] === 'save'); + expect(save?.[3]).toEqual({ extend: 'crm_lead', fields: { score__c: { type: 'number' } }, pinnedActions: { record: ['log_call'] } }); + }); + + 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: ['ghost'] }), TEXTS, d)).rejects.toThrow('unknown ghost'); + await expect(saveObjectPins(input({ list: ['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: ['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: ['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: ['convert'] }), TEXTS, pair.d)).rejects.toThrow('pending draft'); + expect(pair.calls.map((c) => c[0])).toEqual(['ensure', 'get', '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: ['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..6a5bd38387d --- /dev/null +++ b/ui/packages/app-shell/src/layout/designModeHeaderPins.ts @@ -0,0 +1,175 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The page header's pinned actions under the design mode (objectstack#36366): + * which of a page's actions its header draws as buttons, at most three, in + * order, and which go to 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 `pinnedActions` (`@objectstack/spec`), one arm + * per page type: `list` for its list page, `record` for its record page. 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. + * + * @module + */ + +import { + OBJECT_PINNED_ACTION_LIMIT, + OBJECT_PINNED_BUILTIN_ACTIONS, + type ObjectPinnedActionPage, +} from '@objectstack/spec/data'; +import { actionRendersAt } from '@object-ui/types'; + +export type PinPage = ObjectPinnedActionPage; + +/** An object's pins for both pages: the `pinnedActions` value written. */ +export interface ObjectPins { + readonly list?: readonly string[]; + readonly record?: readonly string[]; +} + +/** One thing the panel can pin: an action of the object, or a page built-in (`$import`). */ +export interface PinCandidate { + readonly id: string; + readonly label: string; +} + +/** The most a header pins (`OBJECT_PINNED_ACTION_LIMIT`, 3). */ +export const PIN_LIMIT = OBJECT_PINNED_ACTION_LIMIT; + +/** The design mode's key for the pins of `objectName`: one staged change per object, both pages 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 page's header places. */ +const PAGE_LOCATIONS: Readonly> = { + list: ['list_toolbar'], + record: ['record_header', 'record_more'], +}; + +/** Whether `action` is placed on `page`'s header. */ +export function placedOnPage(action: PinnableAction, page: PinPage): boolean { + return PAGE_LOCATIONS[page].some((location) => actionRendersAt(action as never, location)); +} + +/** The object's `pinnedActions` as served (`{}` when it pins nothing). */ +export function servedPins(objectDef: unknown): ObjectPins { + const raw = (objectDef as { pinnedActions?: unknown } | null | undefined)?.pinnedActions; + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}; + const arm = (value: unknown) => + Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : undefined; + const list = arm((raw as ObjectPins).list); + const record = arm((raw as ObjectPins).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 + * page'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_PINNED_BUILTIN_ACTIONS[page]); + for (const builtin of builtins) if (allowed.has(builtin.id) && !seen.has(builtin.id)) out.push(builtin); + return out; +} + +/** The pins as the panel shows them: the arm set (staged or served), else the header's default. */ +export function shownPins(pins: ObjectPins, page: PinPage, actions: readonly PinnableAction[]): string[] { + const arm = pins[page]; + return arm ? [...arm] : defaultPins(actions, page); +} + +/** `pins` with `id` toggled on `page`: off when pinned, on at the end when not. `null` when the header is full. */ +export function togglePin(shown: readonly string[], id: string): string[] | null { + if (shown.includes(id)) return shown.filter((pin) => pin !== id); + if (shown.length >= PIN_LIMIT) return null; + return [...shown, id]; +} + +/** `shown` with the pin at `from` moved to `to`. */ +export function movePin(shown: readonly string[], from: number, to: number): string[] { + if (from === to || from < 0 || to < 0 || from >= shown.length || to >= shown.length) return [...shown]; + const next = [...shown]; + 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 that + * is no action of the object, or one not placed on the page its arm pins + * (`@objectstack/lint`'s `validateObjectPinnedActions`, 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) { + for (const pin of pins[page] ?? []) { + if (pin.startsWith('$')) continue; + const action = actions.find((a) => a.name === pin); + if (!action) return texts.unknown(pin); + if (!placedOnPage(action, page)) return texts.notPlaced(pin); + } + } + return null; +} 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..21cb3547336 --- /dev/null +++ b/ui/packages/app-shell/src/layout/designModeHeaderPinsSave.ts @@ -0,0 +1,146 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The write behind the design mode's 「Save」 for an object's pinned header + * actions (objectstack#36366): the object's `pinnedActions`, written into its + * customization layer and published at once, so everyone sees it. + * + * 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 `pinnedActions`; + * - else the base's paired customization package, asked of the ensure door + * (which creates it on first use and names it): the pair's + * `object_extension` of the object, as published there (or a new one), with + * the new `pinnedActions`. 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`): 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 pinned name is checked against the object + * as served (every package's actions): a name that is no action of the object, + * or one not placed on that page, is refused with its reason. + * + * @module + */ + +import { stripReadDecorations } from '@objectstack/spec/kernel'; +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 { OBJECT_EXTENSION_TYPE } from '../views/studio-design/StudioCustomizeControls.js'; +import { + ensureCustomizationPackage, + fetchListedPackageManifests, + type EnsuredCustomizationPackage, + type ListedPackageManifest, +} from '../views/studio-design/packages-io.js'; +import { pinsRefusal, type ObjectPins } 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; + /** `name` is no action of the object. */ + readonly unknown: (name: string) => string; + /** `name` is an action of the object not placed on that page. */ + readonly notPlaced: (name: string) => string; +} + +/** A document as stored, less what a read adds and what belongs to its package. */ +function documentOf(read: unknown): Record { + const body = stripReadDecorations((read ?? {}) as Record) as Record; + const doc: Record = {}; + for (const [key, value] of Object.entries(body)) if (!key.startsWith('_')) doc[key] = value; + return doc; +} + +/** `pins` as written: an arm the object sets, nothing for an arm it does not. */ +function pinnedActionsValue(pins: ObjectPins): ObjectPins { + return { ...(pins.list ? { list: [...pins.list] } : {}), ...(pins.record ? { record: [...pins.record] } : {}) }; +} + +/** Whether `err` says the item is not there (`404`). */ +function isNotFound(err: unknown): boolean { + return (err as { status?: unknown } | null | undefined)?.status === 404; +} + +/** Save `pins` as the pinned header actions 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 manifests = await doors.listPackages(); + const listed = manifests.get(packageId); + if (!listed) throw new Error(texts.notListed); + + let type = 'object'; + let target = packageId; + let body: Record; + if (listed.writable) { + const layers = (await doors.client.layered('object', objectName, { packageId })) as AuthoredLayers | null; + if (layers && 'draft' in layers && layers.draft) throw new Error(texts.pendingDraft); + body = { ...authoredPublished('object', layers), name: objectName, pinnedActions: pinnedActionsValue(pins) }; + } else { + const pair = await doors.ensureCustomization(packageId); + type = OBJECT_EXTENSION_TYPE; + target = pair.packageId; + let published: unknown = null; + try { + published = await doors.client.get(OBJECT_EXTENSION_TYPE, objectName, { packageId: target }); + } catch (err) { + if (!isNotFound(err)) throw err; + } + body = { ...documentOf(published), extend: objectName, pinnedActions: pinnedActionsValue(pins) }; + } + try { + await doors.client.save(type, objectName, body, { mode: 'draft', packageId: target, ifNoneMatch: '*' }); + } catch (err) { + if (isDraftVersionConflict(err)) throw Object.assign(new Error(texts.pendingDraft), { cause: err }); + throw err; + } + try { + await doors.client.publish(type, objectName, { packageId: target }); + } catch (err) { + try { + await doors.client.reset(type, objectName, { state: 'draft', packageId: target }); + } catch (discardErr) { + console.error('[design-mode] a refused publish left the pinned actions 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.pinnedActions-36366.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.pinnedActions-36366.test.tsx new file mode 100644 index 00000000000..ebfd49e575e --- /dev/null +++ b/ui/packages/app-shell/src/views/RecordDetailView.pinnedActions-36366.test.tsx @@ -0,0 +1,193 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36366 — the object's record-page pins (`pinnedActions.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). + * + * 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'; + +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 } }; + +function mount(pinnedActions: unknown, authoredHeader: boolean) { + const objects = [ + { + name: 'crm_deal', + label: 'Deal', + fields: { id: { type: 'text', label: 'Id' }, name: { type: 'text', label: 'Name' } }, + actions: ACTIONS, + ...(pinnedActions ? { pinnedActions } : {}), + }, + ]; + const pages = authoredHeader + ? [ + { + name: 'crm_deal_detail', + label: 'Detail', + type: 'record', + object: 'crm_deal', + kind: 'full', + isDefault: true, + regions: [{ name: 'main', width: 'full', components: [PLACED_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; + render( + + + + + + + + + , + ); +} + +/** 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([ + ['the synthesized default page', 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: ['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('a list-page arm alone leaves the record header as it was', async () => { + mount({ list: ['$export'] }, authored); + const { inline, menu } = await headerFaces(); + expect(inline).toEqual(['Convert', 'Mark Won', 'Share']); + expect(menu).toEqual(['Log Call']); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index fa30329b656..ef92371e9e0 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -73,6 +73,8 @@ 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 { 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'; @@ -85,7 +87,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 { pinnedHeaderActions, 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'; @@ -1066,6 +1068,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 header pins as the header draws them: + // 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 @@ -4651,8 +4659,14 @@ 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-page pins (`pinnedActions.record`) + // choose which of them are buttons, in order; the rest go to ⋯. No pins: + // the header's own choice, as before. + const base = pinnedHeaderActions( + 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 @@ -4798,7 +4812,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-page pins (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 @@ -5949,14 +5966,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) => ( <> @@ -5972,7 +5983,33 @@ 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). + 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' && ( + ((objectDef as any).actions).map((a: any) => localizeActionTexts(objectDef.name, a))} + /> + )} + + ) + : approvalGroup, + // objectstack#36366 — the record-page pins the header draws, staged ones + // included, for a page that places the object's actions itself. + pinnedActions: 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/objectViewPageHeader.pinnedActions-36366.test.tsx b/ui/packages/app-shell/src/views/objectViewPageHeader.pinnedActions-36366.test.tsx new file mode 100644 index 00000000000..2273ec5ffda --- /dev/null +++ b/ui/packages/app-shell/src/views/objectViewPageHeader.pinnedActions-36366.test.tsx @@ -0,0 +1,120 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36366 — the list header reads the object's list-page pins + * (`pinnedActions.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(pinnedActions?: unknown, extra: Record = {}) { + const objectDef = { name: 'crm_task', label: 'Task', actions: TOOLBAR, ...(pinnedActions ? { pinnedActions } : {}) }; + 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: ['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('a pinned Import is a button of its own and leaves the Import / Export menu', () => { + mount({ list: ['$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: ['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: ['convert'] }); + expect(drawn()).toEqual(['bar(new_task mass_assign export_csv)']); + }); + + it('an environment list never reads the pins', () => { + mount({ list: ['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 294d652a515..29c67b3aaa5 100644 --- a/ui/packages/app-shell/src/views/objectViewPageHeader.tsx +++ b/ui/packages/app-shell/src/views/objectViewPageHeader.tsx @@ -34,6 +34,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 { pinnedHeaderActions, type ActionBarSchema } 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'; @@ -107,19 +110,30 @@ export function ObjectViewPageBarActions({ barEnd, }: ObjectViewPageBarProps & { barEnd?: ObjectViewBarEnd }) { const description = objectDef.description ? objectDesc(objectDef) : undefined; - const exportDoor = barEnd?.exportDoor; + // objectstack#36366 — the object's list-page pins (`pinnedActions.list`): + // the header's buttons, in order, the page's Import and Export among them + // (`$import`, `$export`). Absent: the header's own choice, as before. + // Under the design mode the pins staged there are drawn (`useObjectPins`). + const objectPins = useObjectPins(objectDef); + const listPins = isEnvironmentList ? undefined : objectPins.list; + const importPinned = !!listPins?.includes('$import') && importShown; + const exportPinned = !!listPins?.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: the description (no longer a resident subtitle), Import and // the favorites entry — the page's once-in-a-while acts. - const moreShown = !!description || !!listFavorite || (ioInMore && (importShown || !!exportDoor)); + const moreShown = !!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 ? ( - - ) : ( - + {listPins ? ( + 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 ? ( + + ) : ( + + ) ) )} @@ -145,7 +199,7 @@ export function ObjectViewPageBarActions({ {moreShown && ( )} + {/* 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 pin order: each + * pinned action of the toolbar (`pinnedHeaderActions`), 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. A pin naming nothing this + * reader is offered draws nothing. + */ +function PinnedListHeaderActions({ + pins, + toolbarBar, + importButton, + exportButton, +}: { + pins: readonly string[]; + toolbarBar?: ActionBarSchema; + importButton: ReactNode; + exportButton: ReactNode; +}) { + const arranged = pinnedHeaderActions((toolbarBar?.actions ?? []) as any[], pins, '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 pins) { + 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 { /** The object's description, the menu's first line; absent ⇒ none. */ description?: string; diff --git a/ui/packages/components/src/renderers/layout/containers.tsx b/ui/packages/components/src/renderers/layout/containers.tsx index 2ae3baaa1d3..6b03fd906d9 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, pinnedHeaderActions, 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'; @@ -2094,10 +2094,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-page pins (the design mode's staged + // ones) over the object's own, keyed on content for the memo below. + const hostPinnedActions = recordHeaderState?.pinnedActions; + const hostPinsKey = hostPinnedActions ? JSON.stringify(hostPinnedActions) : ''; // 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 @@ -2226,8 +2231,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-page pins applied as it applies them (objectstack#36366). + if (drawsPlacedActions) { + return pinnedHeaderActions( + placedHeaderActions(registered), + hostPinnedActions ?? (headerActionsObjectMeta as any)?.pinnedActions?.record, + 'record', + ); + } const declared = resolveDeclaredActionIds(authoredHeaderActions, registered); if (declared.kind === 'refused') { reportRefusedHeaderActions(headerObjectName, declared); @@ -2257,6 +2269,7 @@ export const PageHeaderActions: React.FC = ({ } } return declared.actions; + // eslint-disable-next-line react-hooks/exhaustive-deps -- `hostPinnedActions` is keyed on content by `hostPinsKey` }, [ authoredHeaderActions, headerActionsObjectMeta, @@ -2265,6 +2278,7 @@ export const PageHeaderActions: React.FC = ({ headerObjectName, placedRefused, drawsPlacedActions, + hostPinsKey, ]); // ── 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..3f8c0be38d5 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-page pins the header draws (objectstack#36366), where the host + * holds them ahead of the object as served: the design mode's staged pins. + * A header that places the object's actions itself (`placedActions: true`) + * reads these over the object's `pinnedActions.record`. Absent: the + * object's own. + */ + pinnedActions?: readonly string[]; } /** diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index ac43f404220..abce499f44e 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -3882,6 +3882,21 @@ const ar = { noVersion: 'حزمة هذا التطبيق لا تذكر إصدارًا، لذا لا يمكن تخصيص قائمته.', notWritable: 'حزمة تخصيص هذا التطبيق غير قابلة للكتابة، لذا لا يمكن حفظ قائمته.', }, + pins: { + button: 'أزرار الترويسة', + pinned: 'مثبّتة في الترويسة', + other: 'أخرى', + nonePinned: 'لا يوجد زر مثبّت: كل الإجراءات في «المزيد».', + noneOther: 'كل الإجراءات مثبّتة.', + pin: 'تثبيت {{name}} في الترويسة', + unpin: 'نقل {{name}} إلى «المزيد»', + drag: 'اسحب {{name}} لإعادة الترتيب', + full: 'يُثبَّت في الترويسة {{cap}} أزرار على الأكثر. ألغِ تثبيت أحدها أولًا.', + notListed: 'حزمة هذا الكائن غير مدرجة، لذا لا يمكن حفظ أزرار ترويسته.', + pendingDraft: 'لهذا الكائن تغييرات غير منشورة في Studio. انشرها أو تجاهلها هناك، ثم احفظ مرة أخرى.', + unknown: 'لم يعد «{{name}}» إجراءً لهذا الكائن. ألغِ تثبيته ثم احفظ مرة أخرى.', + notPlaced: 'لم يعد «{{name}}» معروضًا في هذه الصفحة. ألغِ تثبيته ثم احفظ مرة أخرى.', + }, }, topbar: { openAssistant: "فتح مساعد {{name}}", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 8084ec8f42f..030a733986b 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -3559,6 +3559,21 @@ const de = { noVersion: 'Das Paket dieser App nennt keine Version, daher kann ihr Menü nicht angepasst werden.', notWritable: 'Das Anpassungspaket dieser App ist nicht beschreibbar, daher kann ihr Menü nicht gespeichert werden.', }, + 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.', + 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.', + }, }, topbar: { openAssistant: "Assistent {{name}} öffnen", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 3684e31dafe..0cca67b856e 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -4240,6 +4240,21 @@ const en = { noVersion: 'This app\'s package states no version, so its menu cannot be customized.', notWritable: 'This app\'s customization package cannot be written, so its menu cannot be saved.', }, + 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.', + 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.', + }, }, topbar: { aiAssistant: 'AI Assistant', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 10d50139536..047c35e23a5 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -3641,6 +3641,21 @@ const es = { noVersion: 'El paquete de esta aplicación no declara versión, así que su menú no se puede personalizar.', notWritable: 'El paquete de personalización de esta aplicación no se puede escribir, así que su menú no se puede guardar.', }, + 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.', + 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.', + }, }, topbar: { openAssistant: "Abrir el asistente {{name}}", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 6a9fb41ee93..e5da826f977 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -3637,6 +3637,21 @@ const fr = { noVersion: 'Le package de cette application ne déclare aucune version : son menu ne peut pas être personnalisé.', notWritable: 'Le package de personnalisation de cette application n’est pas modifiable : son menu ne peut pas être enregistré.', }, + 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.', + 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.', + }, }, topbar: { openAssistant: "Ouvrir l'assistant {{name}}", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 61180baad15..c716afb9042 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -3561,6 +3561,21 @@ const ja = { noVersion: 'このアプリのパッケージにはバージョンがないため、メニューをカスタマイズできません。', notWritable: 'このアプリのカスタマイズパッケージに書き込めないため、メニューを保存できません。', }, + pins: { + button: 'ヘッダーのボタン', + pinned: 'ヘッダーに固定', + other: 'その他', + nonePinned: '固定されたボタンはありません。すべての操作は「その他」にあります。', + noneOther: 'すべての操作が固定されています。', + pin: '{{name}} をヘッダーに固定', + unpin: '{{name}} を「その他」へ移動', + drag: '{{name}} をドラッグして並べ替え', + full: 'ヘッダーに固定できるボタンは最大 {{cap}} 個です。先にどれかの固定を外してください。', + notListed: 'このオブジェクトのパッケージが一覧にないため、ヘッダーのボタンを保存できません。', + pendingDraft: 'このオブジェクトには Studio に未公開の変更があります。そちらで公開または破棄してから、もう一度保存してください。', + unknown: '「{{name}}」はこのオブジェクトの操作ではなくなりました。固定を外してから保存してください。', + notPlaced: '「{{name}}」はこのページに表示されなくなりました。固定を外してから保存してください。', + }, }, topbar: { openAssistant: "{{name}} アシスタントを開く", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 5c13dde9655..c31c7be81ff 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -3559,6 +3559,21 @@ const ko = { noVersion: '이 앱의 패키지에 버전이 없어 메뉴를 사용자 지정할 수 없습니다.', notWritable: '이 앱의 사용자 지정 패키지에 쓸 수 없어 메뉴를 저장할 수 없습니다.', }, + pins: { + button: '헤더 버튼', + pinned: '헤더에 고정', + other: '기타', + nonePinned: '고정된 버튼이 없습니다. 모든 작업은 "더 보기"에 있습니다.', + noneOther: '모든 작업이 고정되어 있습니다.', + pin: '{{name}}을(를) 헤더에 고정', + unpin: '{{name}}을(를) "더 보기"로 이동', + drag: '{{name}}을(를) 끌어서 순서 변경', + full: '헤더에는 버튼을 최대 {{cap}}개까지 고정할 수 있습니다. 먼저 하나의 고정을 해제하세요.', + notListed: '이 개체의 패키지가 목록에 없어 헤더 버튼을 저장할 수 없습니다.', + pendingDraft: '이 개체에는 Studio에 게시되지 않은 변경 사항이 있습니다. 그곳에서 게시하거나 취소한 뒤 다시 저장하세요.', + unknown: '"{{name}}"은(는) 더 이상 이 개체의 작업이 아닙니다. 고정을 해제한 뒤 다시 저장하세요.', + notPlaced: '"{{name}}"은(는) 더 이상 이 페이지에 없습니다. 고정을 해제한 뒤 다시 저장하세요.', + }, }, topbar: { openAssistant: "{{name}} 어시스턴트 열기", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 0391db19ef5..9ffb30662a9 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -3636,6 +3636,21 @@ const pt = { noVersion: 'O pacote deste aplicativo não declara versão, então o menu não pode ser personalizado.', notWritable: 'O pacote de personalização deste aplicativo não pode ser gravado, então o menu não pode ser salvo.', }, + 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.', + 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.', + }, }, topbar: { openAssistant: "Abrir o assistente {{name}}", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 3b814bcf631..2239fe0abb0 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -3728,6 +3728,21 @@ const ru = { noVersion: 'Пакет этого приложения не указывает версию, поэтому меню нельзя настроить.', notWritable: 'Пакет настроек этого приложения недоступен для записи, поэтому меню нельзя сохранить.', }, + pins: { + button: 'Кнопки заголовка', + pinned: 'Закреплены в заголовке', + other: 'Прочее', + nonePinned: 'Нет закреплённых кнопок: все действия в меню «Ещё».', + noneOther: 'Все действия закреплены.', + pin: 'Закрепить {{name}} в заголовке', + unpin: 'Переместить {{name}} в «Ещё»', + drag: 'Перетащите {{name}}, чтобы изменить порядок', + full: 'В заголовке закрепляется не больше {{cap}} кнопок. Сначала открепите одну.', + notListed: 'Пакет этого объекта отсутствует в списке, поэтому кнопки заголовка нельзя сохранить.', + pendingDraft: 'В Studio есть неопубликованные изменения этого объекта. Опубликуйте или отмените их там и сохраните снова.', + unknown: '«{{name}}» больше не является действием этого объекта. Открепите его и сохраните снова.', + notPlaced: '«{{name}}» больше не предлагается на этой странице. Открепите его и сохраните снова.', + }, }, topbar: { openAssistant: "Открыть ассистента {{name}}", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 4c4e8822b9e..af6f784902d 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -3640,6 +3640,21 @@ const zh = { noVersion: '这个应用所在的包没有声明版本,菜单无法定制。', notWritable: '这个应用的定制包不可写,菜单无法保存。', }, + pins: { + button: '页头按钮', + pinned: '固定在页头', + other: '其他', + nonePinned: '没有固定的按钮:所有动作都在「更多」里。', + noneOther: '所有动作都已固定。', + pin: '把 {{name}} 固定到页头', + unpin: '把 {{name}} 移到「更多」', + drag: '拖动 {{name}} 调整顺序', + full: '页头最多固定 {{cap}} 个按钮,请先取消固定一个。', + notListed: '这个对象所在的包不在列表中,页头按钮无法保存。', + pendingDraft: '这个对象在 Studio 里有未发布的改动。请先在那里发布或丢弃,再保存。', + unknown: '「{{name}}」已不是这个对象的动作。请取消固定后再保存。', + notPlaced: '「{{name}}」已不在这个页面上。请取消固定后再保存。', + }, }, topbar: { aiAssistant: 'AI 助手', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index a064abb5cca..56f86acd8be 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -3640,6 +3640,21 @@ const zhHant = { noVersion: '這個應用所在的包沒有宣告版本,選單無法定製。', notWritable: '這個應用的定製包不可寫,選單無法儲存。', }, + pins: { + button: '頁頭按鈕', + pinned: '固定在頁頭', + other: '其他', + nonePinned: '沒有固定的按鈕:所有動作都在「更多」裡。', + noneOther: '所有動作都已固定。', + pin: '把 {{name}} 固定到頁頭', + unpin: '把 {{name}} 移到「更多」', + drag: '拖動 {{name}} 調整順序', + full: '頁頭最多固定 {{cap}} 個按鈕,請先取消固定一個。', + notListed: '這個物件所在的包不在列表中,頁頭按鈕無法儲存。', + pendingDraft: '這個物件在 Studio 裡有未釋出的改動。請先在那裡釋出或丟棄,再儲存。', + unknown: '「{{name}}」已不是這個物件的動作。請取消固定後再儲存。', + notPlaced: '「{{name}}」已不在這個頁面上。請取消固定後再儲存。', + }, }, topbar: { aiAssistant: 'AI 助手', diff --git a/ui/packages/types/src/__tests__/pinned-header-actions-36366.test.ts b/ui/packages/types/src/__tests__/pinned-header-actions-36366.test.ts new file mode 100644 index 00000000000..138bfd6ae1c --- /dev/null +++ b/ui/packages/types/src/__tests__/pinned-header-actions-36366.test.ts @@ -0,0 +1,73 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#36366 — `pinnedHeaderActions`: an object's pinned header actions + * applied to the actions one page header places. No pins answers the actions + * as they are (the header draws as before); pins make the named actions the + * header's buttons, in pin order, and send every other one to the overflow. + */ + +import { describe, expect, it } from 'vitest'; +import { pinnedHeaderActions } 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('pinnedHeaderActions (objectstack#36366)', () => { + it('no pins: the actions as they are, so the header draws as before', () => { + expect(pinnedHeaderActions(RECORD, undefined, 'record')).toEqual(RECORD); + expect(pinnedHeaderActions(LIST, null, 'list')).toEqual(LIST); + }); + + it('record: the pinned ones lead in pin order at record_header; the rest are record_more only', () => { + const out = pinnedHeaderActions(RECORD, ['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] = pinnedHeaderActions(RECORD, ['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 = pinnedHeaderActions(LIST, ['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 arm pins nothing: every action goes to the overflow', () => { + expect(pinnedHeaderActions(LIST, [], 'list').every((a) => a.component === 'action:menu')).toBe(true); + expect(pinnedHeaderActions(RECORD, [], 'record').every((a) => !a.locations?.includes('record_header'))).toBe(true); + }); + + it('a pin naming no placed action, or a `$` built-in, draws nothing; a pin named twice counts once', () => { + const out = pinnedHeaderActions(LIST, ['$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('does not change the actions it is given', () => { + const before = JSON.stringify(RECORD); + pinnedHeaderActions(RECORD, ['clone'], '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..df2e8aa5b10 100644 --- a/ui/packages/types/src/index.ts +++ b/ui/packages/types/src/index.ts @@ -1294,6 +1294,7 @@ export { ACTION_PARAM_FIELD_TYPES, actionRendersAt, placedHeaderActions, + pinnedHeaderActions, 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..3c0a123f12c 100644 --- a/ui/packages/types/src/ui-action.ts +++ b/ui/packages/types/src/ui-action.ts @@ -128,6 +128,67 @@ export function placedHeaderActions