From a7ed93d6324cf6798967a8b0feffc81cd211d004 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 09:34:45 +0000 Subject: [PATCH 1/5] feat(app-shell): who sees this view, picked from the known capabilities, with the positions it reaches MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The view switcher's create card offers 「Who sees this view」 for a shared view, and Studio's view panel and dashboard settings render the audience row (`requiredPermissions`) as the new `ref-multi:capability` picker: the capabilities the environment knows, each with the permission sets granting it, and a read-only preview of the positions whose sets grant every pick. The card starts from the open view's gate and its pick replaces it. The shared hint no longer says every shared view is seen by everyone. The view hint's lockout sentence now says only what holds on every carrier. The administrator recipe lands in capabilities.mdx. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibxDBbvf7dEeutsepbm --- .changeset/34908-view-audience-picker.md | 20 ++ content/docs/permissions/capabilities.mdx | 40 +++ .../ar.metadata-forms.generated.ts | 2 +- .../ar.source-hashes.generated.ts | 2 +- .../de.metadata-forms.generated.ts | 2 +- .../de.source-hashes.generated.ts | 2 +- .../en.metadata-forms.generated.ts | 2 +- .../es-ES.metadata-forms.generated.ts | 2 +- .../fr.metadata-forms.generated.ts | 2 +- .../fr.source-hashes.generated.ts | 2 +- .../ja-JP.metadata-forms.generated.ts | 2 +- .../ko.metadata-forms.generated.ts | 2 +- .../ko.source-hashes.generated.ts | 2 +- .../pt-BR.metadata-forms.generated.ts | 2 +- .../pt-BR.source-hashes.generated.ts | 2 +- .../ru.metadata-forms.generated.ts | 2 +- .../ru.source-hashes.generated.ts | 2 +- .../zh-CN.metadata-forms.generated.ts | 2 +- .../zh-Hant.metadata-forms.generated.ts | 2 +- .../zh-Hant.source-hashes.generated.ts | 2 +- .../spec/src/ui/dashboard.metadata-form.ts | 5 +- packages/spec/src/ui/view.metadata-form.ts | 13 +- .../app-shell/src/views/CreateViewDialog.tsx | 42 ++- .../app-shell/src/views/ObjectView.tsx | 7 + .../src/views/ViewAudiencePicker.tsx | 144 ++++++++ .../app-shell/src/views/capabilityAudience.ts | 162 +++++++++ .../views/metadata-admin/ResourceEditPage.tsx | 14 +- .../SchemaForm.widgetLabelling.test.tsx | 3 + .../inspectors/DashboardDefaultInspector.tsx | 22 ++ .../inspectors/ViewVariantInspector.tsx | 20 +- .../metadata-admin/metadata-form-zh-cn.ts | 2 +- .../useCapabilityAudienceLoad.ts | 32 ++ .../src/views/metadata-admin/widgets.tsx | 73 ++++ .../src/views/objectViewTitleSwitcher.tsx | 15 + .../src/views/objectViewViewCrud.tsx | 10 +- .../src/views/viewAudience-34908.test.tsx | 322 ++++++++++++++++++ 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 +- ui/packages/i18n/src/namespaces/studio/en.ts | 9 + ui/packages/i18n/src/namespaces/studio/zh.ts | 7 + 49 files changed, 1123 insertions(+), 40 deletions(-) create mode 100644 .changeset/34908-view-audience-picker.md create mode 100644 ui/packages/app-shell/src/views/ViewAudiencePicker.tsx create mode 100644 ui/packages/app-shell/src/views/capabilityAudience.ts create mode 100644 ui/packages/app-shell/src/views/metadata-admin/useCapabilityAudienceLoad.ts create mode 100644 ui/packages/app-shell/src/views/viewAudience-34908.test.tsx diff --git a/.changeset/34908-view-audience-picker.md b/.changeset/34908-view-audience-picker.md new file mode 100644 index 00000000000..a6217140c75 --- /dev/null +++ b/.changeset/34908-view-audience-picker.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': patch +'@objectstack/platform-objects': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(app-shell): 「Who sees this view」 — pick a shared view's or a dashboard's audience from the known capabilities, and see which positions will see it + +Clause-②: no +Metadata-protocol: none + +The audience gate is the existing, server-enforced `requiredPermissions` (all of the capabilities listed are required). The console now sets it from a closed list and shows who it reaches; no key, value or gate changes, and nothing is granted from the view (granting stays in Setup). + +- **`@object-ui/app-shell`.** The view switcher's in-place create card offers 「Who sees this view」 for a shared view: the capabilities the environment knows (declared, or granted by a permission set), each with the permission sets granting it, and a read-only preview of the positions whose permission sets grant every capability picked. It starts from the open view's gate, which a new shared view used to inherit silently, and the pick replaces it; an empty pick writes no gate. A failed catalog read offers nothing to type. The shared hint no longer says every shared view is seen by everyone who can see the list. In Studio, the view panel's and the dashboard settings' audience row is the new `ref-multi:capability` picker with the same preview under it. +- **`@objectstack/spec`.** The view and dashboard forms' `requiredPermissions` rows declare `widget: 'ref-multi:capability'` (a host with no catalog keeps the typed-name box). The view hint's last sentence now says only what holds on every carrier: the person setting the gate no longer sees the view in the list either. +- **`@objectstack/platform-objects`.** The `metadataForms` bundles carry the narrowed view hint (zh-CN, ja-JP and es-ES translated; the other locales the English source). +- **`@object-ui/i18n`.** The create card's new strings and the corrected shared hint, in all eleven console locales. + +Nothing to migrate. diff --git a/content/docs/permissions/capabilities.mdx b/content/docs/permissions/capabilities.mdx index 24ca2d9f60a..33c0f4d966c 100644 --- a/content/docs/permissions/capabilities.mdx +++ b/content/docs/permissions/capabilities.mdx @@ -197,6 +197,45 @@ the same way; a user who may edit the object still reads all of its list views, so a save of what they loaded keeps them. +## Showing a list view to some positions, without code + +An administrator can decide who sees a shared list view or a dashboard in the +console, with no source file. The gate is the same `requiredPermissions` as +above, and the console only sets it; it grants nothing. Granting stays in +Setup. + +1. **Have a capability for the audience.** Use one your app declares, or + declare one in the environment + ([below](#declaring-a-capability-in-the-environment)). One capability per + audience, for example `crm_deal.view_sales` for "the sales team's deal + view". +2. **Grant it in Setup.** Add the name to the `systemPermissions` of a + permission set, and give that set to the positions that should see the + view. A position carries no capability of its own: it passes on what its + permission sets grant. To show the view to two groups, grant the one + capability to both groups' sets. +3. **Pick it on the view.** In the view switcher, **Add view → Shared** offers + **Who sees this view**. For an existing view, Studio's view panel has + **Required permissions** under **Navigation & sharing**, and a dashboard's + settings have it under **Access**. Both list only the capabilities the + environment knows, that is the ones declared and the ones a permission set + grants, with the sets granting each. You cannot type a name that matches + nothing there. + +Under the pick, the console previews the positions that will see the view: the +positions whose permission sets grant **every** capability picked. The preview +is advice, and the server stays the authority. It does not account for a +deactivated permission set, and it cannot name people who hold a set directly +rather than through a position. + + +**The gate applies to you too.** Pick a capability you do not hold, and the view +leaves your own view switcher as well. A view or a dashboard saved on its own +is then refused to you on every door, Studio included, until someone grants +you the capability. Grant it to your own permission set first if you still need +to open the view. + + ## One holder per name Each capability name has exactly one holder in the registry. When a package @@ -303,6 +342,7 @@ copy and the two would share one gate. Prefix your capability names. - [ ] The declaration is reachable from the stack (`capabilities: [...]`) or a `*.capability.ts` file - [ ] No other installed package declares the same name — the registry refuses a second holder at boot - [ ] Something actually **requires** the name (`requiredPermissions`), and something **grants** it (`systemPermissions`) +- [ ] A list view or dashboard gated from the console: its capability is granted to the positions' permission sets, and to your own if you still need to open it ## See also 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 77aa571ceb3..14e8aec4167 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 @@ -1661,7 +1661,7 @@ export const arMetadataForms: NonNullable = { }, requiredPermissions: { label: "Required Permissions", - helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you can no longer open this view either." + helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you no longer see this view in the list either." }, object: { label: "الكائن" diff --git a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts index 1aa6247cb11..425cd5e3b85 100644 --- a/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.source-hashes.generated.ts @@ -67,7 +67,7 @@ export const arGeneratedSourceHashes: Readonly> = { "metadataForms.report.fields.exportOptions.formats.label": "193cd91818d64ef7", "metadataForms.report.fields.exportOptions.includeHeaders.helpText": "44cbc80015ff051d", "metadataForms.report.fields.exportOptions.includeHeaders.label": "f114a4778c9727ae", - "metadataForms.view.fields.requiredPermissions.helpText": "c4599be2ffa06c02", + "metadataForms.view.fields.requiredPermissions.helpText": "824ea3479e2e607a", "metadataForms.view.fields.requiredPermissions.label": "a47b2168b71f5e68", "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", "objects.sys_email_template.fields.package_id.help": "e1f8cc4d0105cedc", 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 1918baa469d..8684c74ca38 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 @@ -1661,7 +1661,7 @@ export const deMetadataForms: NonNullable = { }, requiredPermissions: { label: "Required Permissions", - helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you can no longer open this view either." + helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you no longer see this view in the list either." }, object: { label: "Objekt" diff --git a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts index 16eebeb04a9..0a35ec33d1c 100644 --- a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts @@ -128,7 +128,7 @@ export const deGeneratedSourceHashes: Readonly> = { "metadataForms.view.fields.kanban.label": "dd95c452aa71459e", "metadataForms.view.fields.name.label": "5274417ff1ccaf01", "metadataForms.view.fields.navigation.label": "51cd9fc784a9643f", - "metadataForms.view.fields.requiredPermissions.helpText": "c4599be2ffa06c02", + "metadataForms.view.fields.requiredPermissions.helpText": "824ea3479e2e607a", "metadataForms.view.fields.requiredPermissions.label": "a47b2168b71f5e68", "metadataForms.view.fields.userActions.filter.label": "802895ec427fc6af", "metadataForms.view.fields.userFilters.element.label": "e480e4fe57239c98", 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 25f673b19c7..d67367073e1 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 @@ -1661,7 +1661,7 @@ export const enMetadataForms: NonNullable = { }, requiredPermissions: { label: "Required Permissions", - helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you can no longer open this view either." + helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you no longer see this view in the list either." }, object: { label: "Object" 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 ca94e15f7bd..7cb179a9236 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 @@ -1661,7 +1661,7 @@ export const esESMetadataForms: NonNullable = }, requiredPermissions: { label: "Permisos requeridos", - helpText: "Quién ve esta vista: las capacidades que una persona debe tener, todas las indicadas. Los conjuntos de permisos otorgan capacidades, y un puesto transmite las que otorgan sus conjuntos de permisos. Si se deja vacío, todos los que pueden ver la lista ven esta vista. Para mostrarla a varios grupos, elija una capacidad y otórguela al conjunto de permisos de cada grupo. El servidor lo aplica: los demás no encuentran la vista en la lista y se les deniega si la abren directamente. Esto también se aplica a usted: si indica una capacidad que no tiene, o la escribe mal, usted tampoco podrá volver a abrir esta vista." + helpText: "Quién ve esta vista: las capacidades que una persona debe tener, todas las indicadas. Los conjuntos de permisos otorgan capacidades, y un puesto transmite las que otorgan sus conjuntos de permisos. Si se deja vacío, todos los que pueden ver la lista ven esta vista. Para mostrarla a varios grupos, elija una capacidad y otórguela al conjunto de permisos de cada grupo. El servidor lo aplica: los demás no encuentran la vista en la lista y se les deniega si la abren directamente. Esto también se aplica a usted: si indica una capacidad que no tiene, o la escribe mal, usted tampoco verá esta vista en la lista." }, object: { label: "Objeto" 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 afa5dd31ca6..e2633b32210 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 @@ -1661,7 +1661,7 @@ export const frMetadataForms: NonNullable = { }, requiredPermissions: { label: "Required Permissions", - helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you can no longer open this view either." + helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you no longer see this view in the list either." }, object: { label: "Objet" diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index ebd32ddebcd..5edcd428bcb 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -164,7 +164,7 @@ export const frGeneratedSourceHashes: Readonly> = { "metadataForms.view.fields.navigation.label": "51cd9fc784a9643f", "metadataForms.view.fields.navigation.mode.label": "74dde5013435abdc", "metadataForms.view.fields.pagination.label": "309131fbaca258df", - "metadataForms.view.fields.requiredPermissions.helpText": "c4599be2ffa06c02", + "metadataForms.view.fields.requiredPermissions.helpText": "824ea3479e2e607a", "metadataForms.view.fields.requiredPermissions.label": "a47b2168b71f5e68", "metadataForms.view.fields.selection.type.label": "901bb552898b2cab", "metadataForms.view.fields.type.label": "901bb552898b2cab", 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 921d9a48fef..3c03010502a 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 @@ -1661,7 +1661,7 @@ export const jaJPMetadataForms: NonNullable = }, requiredPermissions: { label: "必要な権限", - helpText: "このビューを見られる人:閲覧者が保持する必要のあるケイパビリティで、列挙したものはすべて必要です。ケイパビリティは権限セットが付与し、ポジションはその権限セットが付与するものを引き継ぎます。空にすると、リストを見られる全員がこのビューを見られます。複数のグループに見せるには、ケイパビリティを 1 つ選び、各グループの権限セットに付与してください。サーバーが強制します:それ以外の人にはリストにこのビューが表示されず、直接開いても拒否されます。これはあなた自身にも適用されます:保持していないケイパビリティや綴りを誤ったケイパビリティを指定すると、あなたもこのビューを開けなくなります。" + helpText: "このビューを見られる人:閲覧者が保持する必要のあるケイパビリティで、列挙したものはすべて必要です。ケイパビリティは権限セットが付与し、ポジションはその権限セットが付与するものを引き継ぎます。空にすると、リストを見られる全員がこのビューを見られます。複数のグループに見せるには、ケイパビリティを 1 つ選び、各グループの権限セットに付与してください。サーバーが強制します:それ以外の人にはリストにこのビューが表示されず、直接開いても拒否されます。これはあなた自身にも適用されます:保持していないケイパビリティや綴りを誤ったケイパビリティを指定すると、あなたのリストにもこのビューは表示されなくなります。" }, object: { label: "オブジェクト" diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 671ad38fc06..f8f4e16e934 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 @@ -1661,7 +1661,7 @@ export const koMetadataForms: NonNullable = { }, requiredPermissions: { label: "Required Permissions", - helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you can no longer open this view either." + helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you no longer see this view in the list either." }, object: { label: "객체" diff --git a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts index b440ec908a1..8de3bbc85df 100644 --- a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts @@ -67,7 +67,7 @@ export const koGeneratedSourceHashes: Readonly> = { "metadataForms.report.fields.exportOptions.formats.label": "193cd91818d64ef7", "metadataForms.report.fields.exportOptions.includeHeaders.helpText": "44cbc80015ff051d", "metadataForms.report.fields.exportOptions.includeHeaders.label": "f114a4778c9727ae", - "metadataForms.view.fields.requiredPermissions.helpText": "c4599be2ffa06c02", + "metadataForms.view.fields.requiredPermissions.helpText": "824ea3479e2e607a", "metadataForms.view.fields.requiredPermissions.label": "a47b2168b71f5e68", "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", "objects.sys_email_template.fields.id.label": "00b0385c9c152888", 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 a9c2c2e0944..2149b6f7354 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 @@ -1661,7 +1661,7 @@ export const ptBRMetadataForms: NonNullable = }, requiredPermissions: { label: "Required Permissions", - helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you can no longer open this view either." + helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you no longer see this view in the list either." }, object: { label: "Objeto" diff --git a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts index 9a8c8163394..5eca386c3e6 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts @@ -84,7 +84,7 @@ export const ptBRGeneratedSourceHashes: Readonly> = { "metadataForms.report.fields.exportOptions.includeHeaders.label": "f114a4778c9727ae", "metadataForms.view.fields.gantt.label": "57ffc6ef520edfc5", "metadataForms.view.fields.kanban.label": "dd95c452aa71459e", - "metadataForms.view.fields.requiredPermissions.helpText": "c4599be2ffa06c02", + "metadataForms.view.fields.requiredPermissions.helpText": "824ea3479e2e607a", "metadataForms.view.fields.requiredPermissions.label": "a47b2168b71f5e68", "metadataForms.view.sections.gantt.label": "57ffc6ef520edfc5", "metadataForms.view.sections.kanban.label": "dd95c452aa71459e", 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 bd40396d57d..d538390d9d0 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 @@ -1661,7 +1661,7 @@ export const ruMetadataForms: NonNullable = { }, requiredPermissions: { label: "Required Permissions", - helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you can no longer open this view either." + helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you no longer see this view in the list either." }, object: { label: "Объект" diff --git a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts index 1a970de4508..2ecfaaa7130 100644 --- a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts @@ -67,7 +67,7 @@ export const ruGeneratedSourceHashes: Readonly> = { "metadataForms.report.fields.exportOptions.formats.label": "193cd91818d64ef7", "metadataForms.report.fields.exportOptions.includeHeaders.helpText": "44cbc80015ff051d", "metadataForms.report.fields.exportOptions.includeHeaders.label": "f114a4778c9727ae", - "metadataForms.view.fields.requiredPermissions.helpText": "c4599be2ffa06c02", + "metadataForms.view.fields.requiredPermissions.helpText": "824ea3479e2e607a", "metadataForms.view.fields.requiredPermissions.label": "a47b2168b71f5e68", "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", "objects.sys_email_template.fields.id.label": "00b0385c9c152888", 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 c711030e0ba..f3587d2b26f 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 @@ -1661,7 +1661,7 @@ export const zhCNMetadataForms: NonNullable = }, requiredPermissions: { label: "所需权限", - helpText: "谁能看此视图:查看者必须持有的能力,列出的每一项都要具备。能力由权限集授予,岗位通过其权限集获得这些能力。留空则所有能看到该列表的人都能看到此视图。要给多类人看,请选一个能力并授予每类人的权限集。由服务器强制执行:其他人在列表中看不到此视图,直接打开也会被拒绝。这也适用于你自己:列出你未持有或拼错的能力后,你也将无法再打开此视图。" + helpText: "谁能看此视图:查看者必须持有的能力,列出的每一项都要具备。能力由权限集授予,岗位通过其权限集获得这些能力。留空则所有能看到该列表的人都能看到此视图。要给多类人看,请选一个能力并授予每类人的权限集。由服务器强制执行:其他人在列表中看不到此视图,直接打开也会被拒绝。这也适用于你自己:列出你未持有或拼错的能力后,你在列表中也将看不到此视图。" }, object: { label: "对象" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index 34af280d9f6..123b80915bb 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 @@ -1661,7 +1661,7 @@ export const zhHantMetadataForms: NonNullable }, requiredPermissions: { label: "Required Permissions", - helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you can no longer open this view either." + helpText: "Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone who can see the list sees this view. To show it to several groups, pick one capability and grant it to each group's permission set. The server enforces it: anyone else does not find the view in the list and is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or misspell one, and you no longer see this view in the list either." }, object: { label: "物件" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts index dc54a98d4f4..de71721e4db 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts @@ -61,7 +61,7 @@ export const zhHantGeneratedSourceHashes: Readonly> = { "metadataForms.report.fields.exportOptions.formats.label": "193cd91818d64ef7", "metadataForms.report.fields.exportOptions.includeHeaders.helpText": "44cbc80015ff051d", "metadataForms.report.fields.exportOptions.includeHeaders.label": "f114a4778c9727ae", - "metadataForms.view.fields.requiredPermissions.helpText": "c4599be2ffa06c02", + "metadataForms.view.fields.requiredPermissions.helpText": "824ea3479e2e607a", "metadataForms.view.fields.requiredPermissions.label": "a47b2168b71f5e68", "objects.sys_email.fields.message_id.label": "14cd089a4062f4b1", "objects.sys_email_template.fields.id.label": "00b0385c9c152888", diff --git a/packages/spec/src/ui/dashboard.metadata-form.ts b/packages/spec/src/ui/dashboard.metadata-form.ts index 91cb5891458..c3360881d98 100644 --- a/packages/spec/src/ui/dashboard.metadata-form.ts +++ b/packages/spec/src/ui/dashboard.metadata-form.ts @@ -148,7 +148,8 @@ export const dashboardForm = defineMetadataForm({ { // The audience gate (#34908, ruling 7103739693 letter B): the existing, // server-enforced `requiredPermissions`, given an authoring row — the - // list view's row in `view.metadata-form.ts`, worded for a dashboard. + // list view's row in `view.metadata-form.ts` (the same `ref-multi:capability` + // picker and position preview), worded for a dashboard. label: 'Access', description: 'Who can see this dashboard.', collapsible: true, @@ -156,7 +157,7 @@ export const dashboardForm = defineMetadataForm({ fields: [ { field: 'requiredPermissions', - widget: 'string-tags', + widget: 'ref-multi:capability', helpText: 'Who sees this dashboard: the capabilities a person must hold, every one listed. Permission sets ' + 'grant capabilities, and a position passes on the ones its permission sets grant. Leave it empty and ' + 'everyone sees this dashboard. To show it to several groups, pick one capability and grant it to each ' diff --git a/packages/spec/src/ui/view.metadata-form.ts b/packages/spec/src/ui/view.metadata-form.ts index b6a4450d816..f1b016552a6 100644 --- a/packages/spec/src/ui/view.metadata-form.ts +++ b/packages/spec/src/ui/view.metadata-form.ts @@ -320,15 +320,24 @@ export const viewForm = defineMetadataForm({ // second audience key. The hint restates the clauses of // `AUDIENCE_REQUIRED_PERMISSIONS_DESCRIPTION` (all of them, no any-of // form, enforced by the server) for the administrator who sets it. + // `ref-multi:capability` offers only the capabilities the environment + // knows (declared, or granted by a permission set) and previews which + // positions the picked set reaches; a host that feeds no catalog gets + // the typed-name box. It writes the names only — granting stays in Setup. + // The last sentence says what holds for the person setting the gate on + // every carrier: the switcher drops the view for them too. It does not + // promise the designer refuses it: a view item is refused on every door, + // but an entry kept in its object's view set stays open to that set's + // editors there. { field: 'requiredPermissions', - widget: 'string-tags', + widget: 'ref-multi:capability', helpText: 'Who sees this view: the capabilities a person must hold, every one listed. Permission sets grant ' + 'capabilities, and a position passes on the ones its permission sets grant. Leave it empty and everyone ' + 'who can see the list sees this view. To show it to several groups, pick one capability and grant it to ' + 'each group\'s permission set. The server enforces it: anyone else does not find the view in the list and ' + 'is refused if they open it directly. The gate applies to you too: list a capability you do not hold, or ' - + 'misspell one, and you can no longer open this view either.', + + 'misspell one, and you no longer see this view in the list either.', }, ], }, diff --git a/ui/packages/app-shell/src/views/CreateViewDialog.tsx b/ui/packages/app-shell/src/views/CreateViewDialog.tsx index 01876e3f11e..2cdd6fee390 100644 --- a/ui/packages/app-shell/src/views/CreateViewDialog.tsx +++ b/ui/packages/app-shell/src/views/CreateViewDialog.tsx @@ -52,6 +52,9 @@ import type { ListViewVisualization } from '@object-ui/core'; import { slugify } from './metadata-admin/createDerive.js'; import { romanizeHan, useHanRomanizer } from './metadata-admin/romanizeHan.js'; import { datasetOptionLabel, useObjectDatasetBinding } from './studio-design/objectDatasets.js'; +import { usePickerLoad } from './metadata-admin/loadState.js'; +import type { CapabilityAudience } from './capabilityAudience.js'; +import { ViewAudiencePicker } from './ViewAudiencePicker.js'; import { deriveFieldOptions, isImageLikeField, @@ -1082,6 +1085,14 @@ export interface InPlaceViewRequest { scope: 'personal' | 'shared'; /** Carry the list's unsaved filters and sort into the new view. */ includeCurrent: boolean; + /** + * objectstack#34908 — a shared view's audience gate as the card's picker + * left it: the capabilities a reader must all hold (`[]` = no gate). Present + * only when the card offered the picker, and then it is authoritative over + * any gate the new view would otherwise inherit from the open one; absent, + * the host builds the body as before. + */ + requiredPermissions?: string[]; } export interface CreateViewCardProps { @@ -1112,6 +1123,15 @@ export interface CreateViewCardProps { onCreate: (request: InPlaceViewRequest) => boolean | Promise; /** Back to the view list. */ onBack: () => void; + /** + * objectstack#34908 — read the audience catalog (the capabilities the + * environment knows, the permission sets granting each, the positions + * holding them). Given ⇒ the shared scope offers 「Who sees this view」; + * read once the reader picks Shared. Absent ⇒ no picker. + */ + loadAudience?: () => Promise; + /** The open view's gate, the picker's starting value (the new view starts from the open one). */ + initialRequiredPermissions?: readonly string[]; } /** @@ -1138,6 +1158,8 @@ export function CreateViewCard({ shownFields, onCreate, onBack, + loadAudience, + initialRequiredPermissions, }: CreateViewCardProps) { const { t } = useObjectTranslation(); const allTypes = useMemo(() => buildViewTypeMeta(t), [t]); @@ -1159,6 +1181,12 @@ export function CreateViewCard({ const [includeCurrent, setIncludeCurrent] = useState(true); const [scope, setScope] = useState<'personal' | 'shared'>(canCreatePersonal ? 'personal' : 'shared'); const [submitting, setSubmitting] = useState(false); + const [requiredPermissions, setRequiredPermissions] = useState(() => [...(initialRequiredPermissions ?? [])]); + const offersAudience = scope === 'shared' && !!loadAudience; + const audience = usePickerLoad(useMemo( + () => (offersAudience ? loadAudience! : null), + [offersAudience, loadAudience], + )); const submittingRef = useRef(false); const baseId = useId(); // Loads the pinyin dictionary for a Chinese name, so the key reads as it. @@ -1202,7 +1230,12 @@ export function CreateViewCard({ submittingRef.current = true; setSubmitting(true); try { - await onCreate({ config, scope, includeCurrent: hasUnsavedConditions && includeCurrent }); + await onCreate({ + config, + scope, + includeCurrent: hasUnsavedConditions && includeCurrent, + ...(offersAudience ? { requiredPermissions } : {}), + }); } finally { submittingRef.current = false; setSubmitting(false); @@ -1335,9 +1368,14 @@ export function CreateViewCard({ )} {scope === 'shared' && (

- {t('view.switcher.scopeHint', { defaultValue: 'Shared views are seen by everyone who can see this list' })} + {t('view.switcher.scopeHint', { + defaultValue: 'Shared views are seen by everyone who can see this list, unless the view is limited to the holders of a capability', + })}

)} + {offersAudience && ( + + )} + )} + + ); + })} + + )} + {audience.status === 'error' ? ( +

+ {t('view.switcher.audienceLoadFailed', { + defaultValue: 'The capabilities could not be loaded, so the view can only be shared with everyone: {{message}}', + message: audience.message, + })} +

+ ) : loaded && options.length === 0 ? ( +

+ {t('view.switcher.audienceNone', { + defaultValue: 'No capability is defined yet. Capabilities are granted on permission sets, in Setup.', + })} +

+ ) : ( + + )} + {preview && ( +

+ {preview} +

+ )} + + ); +} diff --git a/ui/packages/app-shell/src/views/capabilityAudience.ts b/ui/packages/app-shell/src/views/capabilityAudience.ts new file mode 100644 index 00000000000..d2f87ae03bc --- /dev/null +++ b/ui/packages/app-shell/src/views/capabilityAudience.ts @@ -0,0 +1,162 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Who a list view's (or a dashboard's) audience gate reaches — the catalog the + * "Who sees this view" pickers offer and the positions they preview + * (objectstack#34908, ruling 7103739693 letter B). + * + * The gate is the existing `requiredPermissions` (ruling 6095014058): a list of + * capabilities, every one required, enforced by the server's `/meta` read gate. + * A capability reaches a person through a permission set's `systemPermissions`, + * and a position passes on the capabilities of the permission sets it names in + * `permissionSets` (ADR-0131 D3/D4) — it carries none of its own. So this + * module reads three registries and joins them; it writes nothing, and the + * view surface never grants (granting stays in Setup). + * + * The catalog is CLOSED: the names offered are the capabilities the registry + * declares (`defineCapability`) and every name a permission set grants — the + * same "known capability" set `validateCapabilityReferences` in + * `@objectstack/lint` resolves against — so an administrator, or an AI driving + * the console, cannot pick a name that matches nothing (a misspelled gate hides + * the view from everyone but the object's editors). + * + * The position preview is advisory and states only what the catalog says: a + * position is listed when the permission sets it names grant EVERY picked + * capability between them. It does not read the activation ledger (a + * deactivated set confers nothing at runtime) and it cannot list people who + * hold a set directly rather than through a position; the server's gate stays + * the authority. + */ + +/** One capability the environment knows, as the pickers offer it. */ +export interface CapabilityOption { + /** The capability name — what `requiredPermissions` stores. */ + name: string; + /** The declaration's label, when the registry declares one. */ + label?: string; + /** The permission sets granting it, by name, sorted. */ + grantedBy: string[]; +} + +/** One position, with the capabilities its permission sets grant. */ +export interface PositionReach { + name: string; + label?: string; + /** Every capability the position's named permission sets grant. */ + capabilities: string[]; +} + +/** The joined catalog: what may be picked, and which positions hold what. */ +export interface CapabilityAudience { + capabilities: CapabilityOption[]; + /** `null` when the position registry could not be read: the preview then says so. */ + positions: PositionReach[] | null; +} + +type Row = Record; + +/** A list row as the metadata list read answers it: the item, or an envelope around it. */ +function unwrap(raw: unknown): Row | null { + const item = raw && typeof raw === 'object' && 'item' in (raw as Row) ? (raw as Row).item : raw; + return item && typeof item === 'object' ? (item as Row) : null; +} + +const nameOf = (row: Row): string | undefined => + typeof row.name === 'string' && row.name.trim() ? row.name : undefined; +const labelOf = (row: Row): string | undefined => + typeof row.label === 'string' && row.label.trim() ? row.label : undefined; +const stringsOf = (value: unknown): string[] => + Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string' && v.trim() !== '') : []; + +/** + * Join the three registries' rows into the pickers' catalog. Pure: the rows + * are what `list('capability')`, `list('permission')` and `list('position')` + * answered (`positions: null` when that read failed). + */ +export function buildCapabilityAudience( + capabilityRows: readonly unknown[], + permissionSetRows: readonly unknown[], + positionRows: readonly unknown[] | null, +): CapabilityAudience { + const labels = new Map(); + for (const raw of capabilityRows) { + const row = unwrap(raw); + const name = row && nameOf(row); + if (row && name) labels.set(name, labelOf(row)); + } + const grantedBy = new Map>(); + const setGrants = new Map(); + for (const raw of permissionSetRows) { + const row = unwrap(raw); + const set = row && nameOf(row); + if (!row || !set) continue; + const caps = stringsOf(row.systemPermissions); + setGrants.set(set, caps); + for (const cap of caps) { + if (!grantedBy.has(cap)) grantedBy.set(cap, new Set()); + grantedBy.get(cap)!.add(set); + } + } + const names = new Set([...labels.keys(), ...grantedBy.keys()]); + const capabilities = [...names] + .sort((a, b) => a.localeCompare(b)) + .map((name) => ({ + name, + ...(labels.get(name) ? { label: labels.get(name) } : {}), + grantedBy: [...(grantedBy.get(name) ?? [])].sort((a, b) => a.localeCompare(b)), + })); + + const positions = positionRows === null + ? null + : positionRows + .map(unwrap) + .filter((row): row is Row => !!row && !!nameOf(row)) + .map((row) => { + const caps = new Set(); + for (const set of stringsOf(row.permissionSets)) for (const cap of setGrants.get(set) ?? []) caps.add(cap); + return { + name: nameOf(row)!, + ...(labelOf(row) ? { label: labelOf(row) } : {}), + capabilities: [...caps].sort((a, b) => a.localeCompare(b)), + }; + }) + .sort((a, b) => a.name.localeCompare(b.name)); + + return { capabilities, positions }; +} + +/** + * The positions whose permission sets grant EVERY picked capability — who the + * gate lets in through a position. Empty `picked` is no gate: `null`, which a + * preview reads as "everyone who can see the list". + */ +export function positionsReached( + picked: readonly string[], + positions: readonly PositionReach[], +): PositionReach[] | null { + if (picked.length === 0) return null; + return positions.filter((p) => picked.every((cap) => p.capabilities.includes(cap))); +} + +/** The metadata reads {@link loadCapabilityAudience} makes — the console `MetadataClient`'s `list`. */ +export interface CapabilityAudienceSource { + list: (type: string) => Promise; +} + +/** + * Read the three registries and join them. A failed capability or permission + * set read fails the load (the pickers then say so and keep a text box); a + * failed position read keeps the catalog and leaves `positions` `null`. + */ +export async function loadCapabilityAudience(source: CapabilityAudienceSource): Promise { + const [capabilities, permissionSets, positions] = await Promise.all([ + source.list('capability'), + source.list('permission'), + source.list('position').catch(() => null), + ]); + return buildCapabilityAudience( + Array.isArray(capabilities) ? capabilities : [], + Array.isArray(permissionSets) ? permissionSets : [], + positions === null ? null : Array.isArray(positions) ? positions : [], + ); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx index 685b5b1251e..081d03c605e 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx @@ -111,6 +111,7 @@ import { conditionSubjectsForMetadataType, } from './conditionScope.js'; import { mapLoaded, usePickerLoad } from './loadState.js'; +import { useCapabilityAudienceLoad } from './useCapabilityAudienceLoad.js'; import { useMetadataClient, useMetadataTypes, @@ -1398,6 +1399,16 @@ function MetadataResourceEditPageImpl({ ), ); + // objectstack#34908 — the audience catalog for the `ref-multi:capability` + // picker (a list view's or a dashboard's `requiredPermissions`): the + // capabilities the environment knows, the permission sets granting each and + // the positions holding them. Loaded only when the form on screen declares + // that widget, as the permission-set catalog above is. + const capabilityAudienceState = useCapabilityAudienceLoad( + client, + formDeclaresWidget(createMode && config.createSchema ? undefined : entry?.form, 'ref-multi:capability'), + ); + // Component ids placed on the page being edited — fuels the `ref:component` // picker so a page variable's `source` (the component that writes it) is // chosen from the real canvas components, not a free-text id. Derived from @@ -1456,8 +1467,9 @@ function MetadataResourceEditPageImpl({ objectViews: objectViewsState, componentIds, permissionSets: permissionSetsState, + capabilityAudience: capabilityAudienceState, }), - [type, objectsState, objectCatalogState, objectViewsState, componentIds, permissionSetsState], + [type, objectsState, objectCatalogState, objectViewsState, componentIds, permissionSetsState, capabilityAudienceState], ); // Load layered view + initial draft. diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx index 9e3506b3921..126a0484026 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx @@ -156,6 +156,9 @@ const CASES: Case[] = [ { key: 'ref-multi:permission', schema: { type: 'array', title: TITLE, items: { type: 'string' } }, ctx: { permissionSets: loaded([{ name: 'sales_rep' }, { name: 'support_agent' }]) }, value: ['sales_rep'] }, // No `ctx` at all: the hosts that feed no catalog get the typed-name box inside the same named list (objectui#12126). { key: 'ref-multi:permission', variant: 'no-catalog', schema: { type: 'array', title: TITLE, items: { type: 'string' } }, value: ['sales_rep'] }, + { key: 'ref-multi:capability', schema: { type: 'array', title: TITLE, items: { type: 'string' } }, ctx: { capabilityAudience: loaded({ capabilities: [{ name: 'view_deal_sales', grantedBy: ['sales_rep_set'] }], positions: [] }) }, value: ['view_deal_sales'] }, + // No `ctx` at all: the hosts that feed no catalog get the typed-name box inside the same named list (objectstack#34908). + { key: 'ref-multi:capability', variant: 'no-catalog', schema: { type: 'array', title: TITLE, items: { type: 'string' } }, value: ['view_deal_sales'] }, { key: 'filter-mode', schema: { type: 'object', title: TITLE }, ctx: { objectFields: loaded([{ name: 'status' }]) }, value: { element: 'dropdown' } }, { key: 'object-selector', schema: { type: 'string', title: TITLE }, ctx: { objectNames: loaded(['account']) }, value: 'account' }, { key: 'object-selector', variant: 'multiple', schema: { type: 'array', title: TITLE }, spec: { multiple: true }, ctx: { objectNames: loaded(['account', 'contact']) }, value: ['account'] }, diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardDefaultInspector.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardDefaultInspector.tsx index f054cf4e57d..8083493a4a0 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardDefaultInspector.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardDefaultInspector.tsx @@ -42,6 +42,10 @@ import { AddWidgetPicker } from '../previews/AddWidgetPicker.js'; import { WIDGET_TYPE_META, UnknownWidgetIcon } from '../previews/widget-types.js'; import type { MetadataDefaultInspectorProps } from '../default-inspector-registry.js'; import { SchemaForm } from '../SchemaForm.js'; +import { formDeclaresWidget, type WidgetContext } from '../widgets.js'; +import { conditionScopeForMetadataType } from '../conditionScope.js'; +import { useMetadataClient } from '../useMetadata.js'; +import { useCapabilityAudienceLoad } from '../useCapabilityAudienceLoad.js'; import { fallbackFormPatch } from './fallbackFormPatch.js'; import type { FormViewSpec } from '../SchemaForm.js'; import { getDashboardForm, getDashboardSchema } from '../dashboard-schema.js'; @@ -187,6 +191,23 @@ export function DashboardDefaultInspector({ return { schema: merged.schema, form: stackSectionsForNarrowPanel(merged.form) }; }, [serverSchema, locale]); + // objectstack#34908 — the Access section's audience row is the + // `ref-multi:capability` picker; feed it the capability catalog and the + // positions preview. This host handed down no `WidgetContext` before, so it + // now states the verdict the scope table rules for its type + // (`conditionScopeForMetadataType('dashboard')`) rather than inventing one; + // the dashboard form declares no `condition` row, so nothing renders + // differently for it. + const metadataClient = useMetadataClient(); + const capabilityAudience = useCapabilityAudienceLoad( + metadataClient, + formDeclaresWidget(form, 'ref-multi:capability'), + ); + const widgetContext = React.useMemo( + () => ({ conditionScope: conditionScopeForMetadataType('dashboard'), capabilityAudience }), + [capabilityAudience], + ); + return ( ( + () => ({ ...widgetContext, capabilityAudience }), + [widgetContext, capabilityAudience], + ); + /** Shallow-write a curated patch onto the variant. */ const writeVariant = (patch: Record) => { onPatch({ [variantKey]: { ...variant, ...patch } }); @@ -572,7 +588,7 @@ export function ViewVariantInspector({ value={variant} hiddenFields={['type', 'object', 'label']} readOnly={readOnly} - widgetContext={widgetContext} + widgetContext={formWidgetContext} issues={variantIssues} revealIssues={revealIssues} onInlineIssueFieldsChange={setFormIssueRows} diff --git a/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts b/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts index 6ccafe214f1..3c3c900d092 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/metadata-form-zh-cn.ts @@ -501,7 +501,7 @@ export const ZH_CN_SPEC_FORMS: NonNullable = { 'navigation.width': { label: '宽度', helpText: '[已弃用 → size] 抽屉的像素 / 百分比宽度(如 "600px")。编写时无法预知客户端视口,因此选不出合适的像素宽度——请使用 `size` 档位。' }, sharing: { label: '共享', helpText: '视图共享配置:谁锁定了视图配置' }, 'sharing.lockedBy': { label: '锁定者', helpText: '锁定该视图配置的用户' }, - requiredPermissions: { label: '所需权限', helpText: '谁能看此视图:查看者必须持有的能力,列出的每一项都要具备。能力由权限集授予,岗位通过其权限集获得这些能力。留空则所有能看到该列表的人都能看到此视图。要给多类人看,请选一个能力并授予每类人的权限集。由服务器强制执行:其他人在列表中看不到此视图,直接打开也会被拒绝。这也适用于你自己:列出你未持有或拼错的能力后,你也将无法再打开此视图。' }, + requiredPermissions: { label: '所需权限', helpText: '谁能看此视图:查看者必须持有的能力,列出的每一项都要具备。能力由权限集授予,岗位通过其权限集获得这些能力。留空则所有能看到该列表的人都能看到此视图。要给多类人看,请选一个能力并授予每类人的权限集。由服务器强制执行:其他人在列表中看不到此视图,直接打开也会被拒绝。这也适用于你自己:列出你未持有或拼错的能力后,你在列表中也将看不到此视图。' }, }, }, app: { diff --git a/ui/packages/app-shell/src/views/metadata-admin/useCapabilityAudienceLoad.ts b/ui/packages/app-shell/src/views/metadata-admin/useCapabilityAudienceLoad.ts new file mode 100644 index 00000000000..a8bbd8ebf83 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/useCapabilityAudienceLoad.ts @@ -0,0 +1,32 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Load the audience catalog the `ref-multi:capability` picker offers — the + * capabilities the environment knows, the permission sets granting each and + * the positions holding them (objectstack#34908) — as a {@link LoadState}, so + * a failed read reaches the picker as a failure, not as an empty catalog. + * + * `enabled` false sends no request and answers `idle`: a host passes + * `formDeclaresWidget(form, 'ref-multi:capability')`, so only an editor whose + * form carries the audience row reads the three registries. + */ + +import * as React from 'react'; +import { + loadCapabilityAudience, + type CapabilityAudience, + type CapabilityAudienceSource, +} from '../capabilityAudience.js'; +import { usePickerLoad, type LoadState } from './loadState.js'; + +export function useCapabilityAudienceLoad( + source: CapabilityAudienceSource | null | undefined, + enabled: boolean, +): LoadState { + return usePickerLoad( + React.useMemo( + () => (enabled && source ? () => loadCapabilityAudience(source) : null), + [enabled, source], + ), + ); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx index dc8da0f5929..83cdb67b965 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx @@ -54,9 +54,11 @@ import { toast } from 'sonner'; import { useObjectTranslation } from '@object-ui/i18n'; import { createAuthenticatedFetch } from '@object-ui/auth'; import { useMetadataLocale, t, tFormat } from './i18n.js'; +import type { SupportedLocale } from './i18n.js'; import { fieldHistoryChoiceOf, fieldHistoryOptions, fieldHistoryValueOf } from './fieldHistoryChoice.js'; import { isKnownViewType, viewTypeLabel } from './viewTypeLabels.js'; import type { FormFieldSpec, FormViewSpec, VisibilityPredicate } from './form-spec.js'; +import { positionsReached, type CapabilityAudience } from '../capabilityAudience.js'; import { usePredicateScope } from '@object-ui/react'; import { buildPredicateCtx, visibleOptions, type PredicateCtx } from './predicate.js'; import { foldFilterGroupToSpecRules, FILTER_FOLD_REFUSAL_KEYS } from '../viewFilterFold.js'; @@ -75,6 +77,7 @@ import { isLoading, loadErrorOf, loadedData, + mapLoaded, NOT_ASKED, offeredOptions, usePickerLoad, @@ -320,6 +323,13 @@ export interface WidgetContext { * does for a completed load that found no permission sets. */ permissionSets?: LoadState; + /** + * The capabilities the environment knows, joined with the permission sets + * granting each and the positions holding them — fuels the + * `ref-multi:capability` picker of an audience gate (`requiredPermissions` + * on a list view or a dashboard). Absent reads as {@link NOT_ASKED}. + */ + capabilityAudience?: LoadState; } /* Stable empties for the arms that have no catalog to offer yet — `idle` and @@ -842,6 +852,8 @@ interface RefMultiRegistry { addPlaceholderKey: string; /** The add picker's placeholder once every declared item is picked. */ allAddedKey: string; + /** What the picked names mean, drawn under the list (the capability picker's position preview). */ + footer?: (selected: readonly string[], context: WidgetContext | undefined, locale: SupportedLocale) => React.ReactNode; } /** @@ -988,6 +1000,7 @@ function RefMultiWidget({ ) : ( freeform ))} + {registry.footer?.(selected, context, locale)} ); } @@ -1005,6 +1018,64 @@ function RefMultiPermissionWidget(props: WidgetProps) { return ; } +/** + * Who an audience gate lets in through a position: the positions whose + * permission sets grant every picked capability, read off the same catalog + * the picker offers. Advisory — the server's read gate is the authority. + */ +function CapabilityAudienceFooter({ + selected, + context, + locale, +}: { + selected: readonly string[]; + context: WidgetContext | undefined; + locale: SupportedLocale; +}) { + const state = context?.capabilityAudience ?? NOT_ASKED; + if (state.status !== 'loaded') return null; + const positions = state.data.positions; + let text: string; + if (selected.length === 0) text = t('engine.form.audienceEveryone', locale); + else if (positions === null) text = t('engine.form.audiencePositionsUnread', locale); + else { + const reached = positionsReached(selected, positions) ?? []; + text = reached.length === 0 + ? t('engine.form.audienceNoPosition', locale) + : tFormat('engine.form.audiencePositions', locale, { positions: reached.map((p) => p.label ?? p.name).join(', ') }); + } + return ( +

+ {text} +

+ ); +} + +/** + * The `ref-multi:capability` registration: the capabilities the environment + * knows (declared, or granted by a permission set), each offered with the + * permission sets granting it, and the positions the picked set reaches. + */ +const CAPABILITY_REGISTRY: RefMultiRegistry = { + type: 'capability', + catalog: (context) => + context?.capabilityAudience + ? mapLoaded(context.capabilityAudience, (audience) => + audience.capabilities.map((c) => ({ name: c.name, label: c.label })), + ) + : undefined, + addLabelKey: 'engine.form.addCapabilityPlain', + addPlaceholderKey: 'engine.form.addCapability', + allAddedKey: 'engine.form.allCapabilitiesAdded', + footer: (selected, context, locale) => ( + + ), +}; + +function RefMultiCapabilityWidget(props: WidgetProps) { + return ; +} + /* -------------------------------------------------------------------------- */ /* object-selector — multi-select object picker */ /* -------------------------------------------------------------------------- */ @@ -3665,6 +3736,7 @@ export const WIDGETS = { 'ref:component': RefComponentWidget, 'ref:dataset': RefDatasetWidget, 'ref-multi:permission': RefMultiPermissionWidget, + 'ref-multi:capability': RefMultiCapabilityWidget, 'filter-mode': FilterModeWidget, 'object-selector': ObjectSelectorWidget, 'field-selector': FieldSelectorWidget, @@ -3779,6 +3851,7 @@ export const WIDGET_LABELLING: Record = { 'ref:component': 'control', 'ref:dataset': 'control', 'ref-multi:permission': 'group', + 'ref-multi:capability': 'group', 'filter-mode': 'group', 'object-selector': 'control', 'field-selector': 'control', diff --git a/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx b/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx index 7c5e54d1428..16ef0df1e24 100644 --- a/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx +++ b/ui/packages/app-shell/src/views/objectViewTitleSwitcher.tsx @@ -57,6 +57,7 @@ import type { buildViewTabs } from './objectViewTabs.js'; import type { ConsoleObjectViewProps } from './ObjectView.js'; import { FOOTER_ITEM, ObjectViewSwitcherMenu, type SwitcherCreateOptions } from './objectViewSwitcherMenu.js'; import { useCreateViewInPlace } from './objectViewViewCrud.js'; +import type { CapabilityAudience } from './capabilityAudience.js'; type TFn = ReturnType['t']; @@ -301,6 +302,16 @@ export function ObjectViewTitleSwitcher({ ); } +/** + * objectstack#34908 — the open view's audience gate, the create card's + * starting pick: a new shared view starts from the open one, gate included. + * Read where a view carries it — its body, or a view item's `config`. + */ +function requiredPermissionsOf(view: Record | undefined): string[] { + const own = view?.requiredPermissions ?? view?.config?.requiredPermissions; + return Array.isArray(own) ? own.filter((p: unknown): p is string => typeof p === 'string' && p.trim() !== '') : []; +} + /** The field names an open view's columns list (a name, or `{ field }`). */ function shownFieldsOf(view: Record | undefined): string[] { const columns = Array.isArray(view?.columns) ? view.columns : []; @@ -380,6 +391,8 @@ export function useObjectViewTitleSwitcher({ canCreatePersonal: boolean; canCreateShared: boolean; hasUnsavedConditions: boolean; + /** objectstack#34908 — the audience catalog for a shared view's 「Who sees this view」. Absent ⇒ no picker. */ + loadAudience?: () => Promise; }; onRenamePersonalView?: (viewId: string) => void; onDeletePersonalView?: (viewId: string) => void; @@ -402,6 +415,8 @@ export function useObjectViewTitleSwitcher({ hasUnsavedConditions: create.hasUnsavedConditions, shownFields: shownFieldsOf(create.activeView), onCreate: createInPlace, + loadAudience: create.canCreateShared ? create.loadAudience : undefined, + initialRequiredPermissions: requiredPermissionsOf(create.activeView), } : undefined; // objectui#12528 — the view's description is shown once. It rides on the diff --git a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx index 6fb1a46fe7d..992001acf36 100644 --- a/ui/packages/app-shell/src/views/objectViewViewCrud.tsx +++ b/ui/packages/app-shell/src/views/objectViewViewCrud.tsx @@ -606,7 +606,7 @@ export function useCreateViewInPlace({ clearSourceListState?: (viewId: string) => void; t: ReturnType['t']; }) { - return useCallback(async ({ config, scope, includeCurrent }: InPlaceViewRequest): Promise => { + return useCallback(async ({ config, scope, includeCurrent, requiredPermissions }: InPlaceViewRequest): Promise => { const { type, label, name } = config; const block = config[type]; const listState = readListState(); @@ -625,6 +625,14 @@ export function useCreateViewInPlace({ // the name and key the card gave it. const body: Record = { ...built.config, type, label, name }; delete body.id; + // objectstack#34908 — the card's 「Who sees this view」, when it + // offered one, decides the gate: the open view's own gate (copied + // over with its other keys) is replaced, and an empty pick is no + // gate, so no key is written. + if (requiredPermissions) { + delete body.requiredPermissions; + if (requiredPermissions.length > 0) body.requiredPermissions = [...requiredPermissions]; + } return createShared(body); } try { diff --git a/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx b/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx new file mode 100644 index 00000000000..e27dc8d57f3 --- /dev/null +++ b/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx @@ -0,0 +1,322 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#34908 (ruling 7103739693, letter B) — 「Who sees this view」. + * + * What is pinned: + * - the catalog: the capabilities offered are the ones the registry declares + * and every name a permission set grants (a closed list), each with the + * sets granting it; a position holds what its named sets grant; a failed + * position read keeps the catalog and says the positions are unknown; + * - the preview: a position is listed when its sets grant EVERY picked + * capability (the gate is all-of); nothing picked is no gate; + * - the create card's shared scope: the corrected hint, the picker offered + * only for a shared view and only from the catalog, its position preview, + * the open view's gate as the starting pick, and the pick on the request; + * a failed catalog read adds nothing (no free text); + * - the host: the picked gate replaces the one the open view would hand on, + * an empty pick writes no key, and no picker leaves the body as before; + * - the Studio form widget `ref-multi:capability`: the closed list and the + * same preview under it. + */ + +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +// The source under test reaches these through dynamic imports (the capability +// lint, the CEL authoring helpers); pay their first load during collection, not +// inside a case's clocked window. +import '@objectstack/lint'; +import '@objectstack/formula'; +import { render, cleanup, fireEvent, waitFor, screen, within, act, renderHook } from '@testing-library/react'; + +vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } })); +// One client for every render: a fresh object per call would re-run every +// effect keyed on the client (the card's dataset binding), render after render. +const client = { list: async () => [] }; +vi.mock('./metadata-admin/useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => client, +})); + +import { + buildCapabilityAudience, + loadCapabilityAudience, + positionsReached, + type CapabilityAudience, +} from './capabilityAudience'; +import { CreateViewCard, type InPlaceViewRequest } from './CreateViewDialog'; +import { useCreateViewInPlace } from './objectViewViewCrud'; +import { SchemaForm } from './metadata-admin/SchemaForm'; +import { formDeclaresWidget } from './metadata-admin/widgets'; +import { getViewForm } from './metadata-admin/view-schema'; + +afterEach(cleanup); + +const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 30))); + +const CAPABILITIES = [{ name: 'view_deal_sales', label: '客户视图·业务员' }, { item: { name: 'view_deal_finance' } }]; +const PERMISSION_SETS = [ + { name: 'sales_rep_set', systemPermissions: ['view_deal_sales', 'export_reports'] }, + { name: 'sales_lead_set', systemPermissions: ['view_deal_sales', 'view_deal_finance'] }, + { name: 'finance_set', systemPermissions: ['view_deal_finance'] }, +]; +const POSITIONS = [ + { name: 'sales_rep', label: '业务员', permissionSets: ['sales_rep_set'] }, + { name: 'sales_lead', label: '销售主管', permissionSets: ['sales_lead_set'] }, + { name: 'accountant', permissionSets: ['finance_set', 'missing_set'] }, +]; + +const AUDIENCE = buildCapabilityAudience(CAPABILITIES, PERMISSION_SETS, POSITIONS); + +describe('the audience catalog', () => { + it('offers the declared capabilities and every one a permission set grants, each with the sets granting it', () => { + expect(AUDIENCE.capabilities).toEqual([ + { name: 'export_reports', grantedBy: ['sales_rep_set'] }, + { name: 'view_deal_finance', grantedBy: ['finance_set', 'sales_lead_set'] }, + { name: 'view_deal_sales', label: '客户视图·业务员', grantedBy: ['sales_lead_set', 'sales_rep_set'] }, + ]); + }); + + it('a position holds what its named permission sets grant, and nothing of its own', () => { + expect(AUDIENCE.positions).toEqual([ + { name: 'accountant', capabilities: ['view_deal_finance'] }, + { name: 'sales_lead', label: '销售主管', capabilities: ['view_deal_finance', 'view_deal_sales'] }, + { name: 'sales_rep', label: '业务员', capabilities: ['export_reports', 'view_deal_sales'] }, + ]); + }); + + it('the preview lists a position only when its sets grant EVERY picked capability; nothing picked is no gate', () => { + const positions = AUDIENCE.positions!; + expect(positionsReached([], positions)).toBeNull(); + expect(positionsReached(['view_deal_sales'], positions)!.map((p) => p.name)).toEqual(['sales_lead', 'sales_rep']); + expect(positionsReached(['view_deal_sales', 'view_deal_finance'], positions)!.map((p) => p.name)).toEqual(['sales_lead']); + expect(positionsReached(['nobody_has_this'], positions)).toEqual([]); + }); + + it('a failed position read keeps the catalog and leaves the positions unknown; a failed capability read fails the load', async () => { + const fine = await loadCapabilityAudience({ + list: async (type) => { + if (type === 'position') throw new Error('403'); + return type === 'capability' ? CAPABILITIES : PERMISSION_SETS; + }, + }); + expect(fine.capabilities.map((c) => c.name)).toContain('view_deal_sales'); + expect(fine.positions).toBeNull(); + await expect(loadCapabilityAudience({ + list: async (type) => { + if (type === 'capability') throw new Error('boom'); + return []; + }, + })).rejects.toThrow('boom'); + }); +}); + +// --------------------------------------------------------------------------- +// The create card's shared scope +// --------------------------------------------------------------------------- + +function mountCard(props: Partial> = {}) { + const onCreate = vi.fn(async (_request: InPlaceViewRequest) => true); + render( + {}} + {...props} + />, + ); + return { onCreate }; +} + +const submit = () => screen.getByTestId('create-view-card-submit'); +const toShared = () => fireEvent.click(screen.getByTestId('create-view-card-scope-shared')); + +async function addCapability(name: string) { + fireEvent.keyDown(screen.getByTestId('view-audience-add'), { key: 'ArrowDown' }); + const listbox = await screen.findByRole('listbox'); + fireEvent.click(within(listbox).getByTestId(`view-audience-option-${name}`)); + await waitFor(() => expect(screen.queryByRole('listbox')).not.toBeInTheDocument()); +} + +describe('the create card: who sees a shared view', () => { + it('the shared hint no longer claims everyone sees every shared view', () => { + mountCard(); + toShared(); + expect(screen.getByTestId('create-view-card-shared-hint').textContent).toMatch(/unless the view is limited to the holders of a capability/); + }); + + it('the picker is offered for a shared view only, and the catalog is read only then', async () => { + const loadAudience = vi.fn(async () => AUDIENCE); + mountCard({ loadAudience }); + await settle(); + expect(screen.queryByTestId('view-audience-picker')).toBeNull(); + expect(loadAudience).not.toHaveBeenCalled(); + toShared(); + expect(screen.getByTestId('view-audience-picker')).toBeInTheDocument(); + await waitFor(() => expect(loadAudience).toHaveBeenCalledTimes(1)); + expect(screen.getByTestId('view-audience-preview').textContent).toBe('Everyone who can see this list'); + }); + + it('offers only the known capabilities, with their sets, and previews the positions that will see the view', async () => { + const { onCreate } = mountCard({ loadAudience: async () => AUDIENCE }); + toShared(); + await settle(); + fireEvent.keyDown(screen.getByTestId('view-audience-add'), { key: 'ArrowDown' }); + const listbox = await screen.findByRole('listbox'); + expect(within(listbox).getAllByRole('option').map((o) => o.getAttribute('data-testid'))).toEqual([ + 'view-audience-option-export_reports', + 'view-audience-option-view_deal_finance', + 'view-audience-option-view_deal_sales', + ]); + expect(within(listbox).getByTestId('view-audience-option-view_deal_sales').textContent).toContain('Granted by sales_lead_set, sales_rep_set'); + fireEvent.click(within(listbox).getByTestId('view-audience-option-view_deal_sales')); + await waitFor(() => expect(screen.queryByRole('listbox')).not.toBeInTheDocument()); + expect(screen.getByTestId('view-audience-preview').textContent).toBe('销售主管, 业务员 will see this view'); + await addCapability('view_deal_finance'); + expect(screen.getByTestId('view-audience-preview').textContent).toBe('销售主管 will see this view'); + fireEvent.click(submit()); + await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1)); + expect(onCreate.mock.calls[0][0]).toMatchObject({ scope: 'shared', requiredPermissions: ['view_deal_sales', 'view_deal_finance'] }); + }); + + it('a pick no position holds says who is left', async () => { + mountCard({ loadAudience: async () => AUDIENCE, initialRequiredPermissions: ['export_reports', 'view_deal_finance'] }); + toShared(); + await settle(); + expect(screen.getByTestId('view-audience-preview').textContent).toMatch(/^No position holds every picked capability/); + }); + + it('starts from the open view\'s gate, which can be removed: the request then carries an empty gate', async () => { + const { onCreate } = mountCard({ loadAudience: async () => AUDIENCE, initialRequiredPermissions: ['view_deal_sales'] }); + toShared(); + await settle(); + expect(screen.getByTestId('view-audience-picked-view_deal_sales')).toBeInTheDocument(); + fireEvent.click(within(screen.getByTestId('view-audience-picked-view_deal_sales')).getByRole('button')); + fireEvent.click(submit()); + await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1)); + expect(onCreate.mock.calls[0][0].requiredPermissions).toEqual([]); + }); + + it('a failed catalog read says so and offers nothing to type or pick', async () => { + mountCard({ loadAudience: async () => { throw new Error('denied'); } }); + toShared(); + await settle(); + expect(screen.getByTestId('view-audience-load-failed').textContent).toContain('denied'); + expect(screen.queryByTestId('view-audience-add')).toBeNull(); + expect(within(screen.getByTestId('view-audience-picker')).queryByRole('textbox')).toBeNull(); + }); + + it('CONTROL: a personal view, or a host with no catalog, sends no gate', async () => { + const first = mountCard({ loadAudience: async () => AUDIENCE }); + fireEvent.click(submit()); + await waitFor(() => expect(first.onCreate).toHaveBeenCalledTimes(1)); + expect(first.onCreate.mock.calls[0][0]).not.toHaveProperty('requiredPermissions'); + cleanup(); + const second = mountCard(); + toShared(); + expect(screen.queryByTestId('view-audience-picker')).toBeNull(); + fireEvent.click(submit()); + await waitFor(() => expect(second.onCreate).toHaveBeenCalledTimes(1)); + expect(second.onCreate.mock.calls[0][0]).not.toHaveProperty('requiredPermissions'); + }); +}); + +// --------------------------------------------------------------------------- +// The host: the picked gate decides the new shared view's body +// --------------------------------------------------------------------------- + +describe('useCreateViewInPlace: the picked gate', () => { + const GATED = { id: 'crm_deal.mine', name: 'mine', label: 'Mine', type: 'grid', columns: ['name'], requiredPermissions: ['view_deal_finance'] }; + const t = ((key: string) => key) as never; + + function setup() { + const createShared = vi.fn(async (_body: Record) => true); + const { result } = renderHook(() => useCreateViewInPlace({ + objectName: 'crm_deal', + activeView: GATED, + readListState: () => ({ url: {} }), + savePersonal: vi.fn(async () => 'pv'), + openPersonal: vi.fn(), + createShared, + t, + })); + return { create: result.current, createShared }; + } + const request = (requiredPermissions?: string[]): InPlaceViewRequest => ({ + config: { type: 'grid', label: 'Sales', name: 'sales' }, + scope: 'shared', + includeCurrent: false, + ...(requiredPermissions ? { requiredPermissions } : {}), + }); + + it('a pick replaces the gate the open view would hand on', async () => { + const { create, createShared } = setup(); + await create(request(['view_deal_sales'])); + expect(createShared.mock.calls[0][0].requiredPermissions).toEqual(['view_deal_sales']); + }); + + it('an empty pick writes no gate at all', async () => { + const { create, createShared } = setup(); + await create(request([])); + expect(createShared.mock.calls[0][0]).not.toHaveProperty('requiredPermissions'); + }); + + it('CONTROL: with no picker the body is built as before, the open view\'s gate included', async () => { + const { create, createShared } = setup(); + await create(request()); + expect(createShared.mock.calls[0][0].requiredPermissions).toEqual(['view_deal_finance']); + }); +}); + +// --------------------------------------------------------------------------- +// The Studio form widget +// --------------------------------------------------------------------------- + +describe('the view form\'s audience row in Studio', () => { + it('the view form declares the capability picker, so its hosts read the catalog', () => { + expect(formDeclaresWidget(getViewForm('en'), 'ref-multi:capability')).toBe(true); + }); + + function mountRow(audience: CapabilityAudience | null, value: string[]) { + render( + {}} + widgetContext={{ + conditionScope: 'none', + ...(audience ? { capabilityAudience: { status: 'loaded', data: audience } } : {}), + }} + />, + ); + } + + it('lists the picked names and previews the positions that will see the view', () => { + mountRow(AUDIENCE, ['view_deal_sales']); + expect(screen.getByTestId('ref-multi-capability')).toHaveTextContent('view_deal_sales'); + expect(screen.getByTestId('ref-multi-capability-audience').textContent).toContain('销售主管, 业务员'); + }); + + it('a stored name the catalog does not know is flagged, not dropped', () => { + mountRow(AUDIENCE, ['view_deal_sale']); + expect(screen.getByTestId('ref-multi-capability').querySelector('[data-not-found]')).not.toBeNull(); + }); + + it('nothing picked: everyone who can see the list sees it', () => { + mountRow(AUDIENCE, []); + expect(screen.getByTestId('ref-multi-capability-audience').textContent).toMatch(/everyone who can see the list/i); + }); + + it('CONTROL: no catalog fed, no preview', () => { + mountRow(null, ['view_deal_sales']); + expect(screen.queryByTestId('ref-multi-capability-audience')).toBeNull(); + }); +}); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 432120bad48..c793bb020fa 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1485,7 +1485,20 @@ const ar = { typeLabel: 'نوع العرض', includeCurrent: 'تضمين عوامل التصفية والفرز الحالية', scopeShared: 'مشترك', - scopeHint: 'العروض المشتركة يراها كل من يمكنه رؤية هذه القائمة', + scopeHint: 'العروض المشتركة يراها كل من يمكنه رؤية هذه القائمة، ما لم يُقصر العرض على حاملي صلاحية', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: 'من يرى هذا العرض', + audienceEveryone: 'كل من يمكنه رؤية هذه القائمة', + audienceAdd: 'قصر العرض على صلاحية…', + audienceAllAdded: 'تمت إضافة كل الصلاحيات', + audienceLoading: 'جارٍ تحميل الصلاحيات…', + audienceLoadFailed: 'تعذر تحميل الصلاحيات، لذا لا يمكن مشاركة العرض إلا مع الجميع: {{message}}', + audienceNone: 'لم تُعرَّف أي صلاحية بعد. تُمنح الصلاحيات في الإعداد عبر مجموعات الأذونات.', + audienceGrantedBy: 'تمنحها {{sets}}', + audienceRemove: 'إزالة {{name}}', + audiencePositions: 'سيرى هذا العرض: {{positions}}', + audienceNoPosition: 'لا يوجد منصب يحمل كل الصلاحيات المختارة: لن يرى هذا العرض إلا من مُنحت لهم مباشرة ومحررو الكائن', + audiencePositionsUnread: 'تعذرت قراءة المناصب، لذا لا يظهر من سيرى هذا العرض', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'توجد مسودة غير منشورة تستخدم اسم هذا العرض بالفعل، لذلك لم تتم المشاركة. غيّر اسم العرض وحاول مرة أخرى.', viewGone: 'العرض الذي فتحته لم يعد متاحًا، لذا تعرض القائمة العرض الافتراضي.', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index bddfbcf2439..04db438da78 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1348,7 +1348,20 @@ const de = { typeLabel: 'Ansichtstyp', includeCurrent: 'Aktuelle Filter und Sortierung übernehmen', scopeShared: 'Geteilt', - scopeHint: 'Geteilte Ansichten sieht jeder, der diese Liste sehen kann', + scopeHint: 'Geteilte Ansichten sieht jeder, der diese Liste sehen kann, außer die Ansicht ist auf die Inhaber einer Berechtigung beschränkt', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: 'Wer diese Ansicht sieht', + audienceEveryone: 'Jeder, der diese Liste sehen kann', + audienceAdd: 'Auf eine Berechtigung beschränken…', + audienceAllAdded: 'Alle Berechtigungen hinzugefügt', + audienceLoading: 'Berechtigungen werden geladen…', + audienceLoadFailed: 'Die Berechtigungen konnten nicht geladen werden, daher kann die Ansicht nur mit allen geteilt werden: {{message}}', + audienceNone: 'Noch keine Berechtigung definiert. Berechtigungen werden im Setup über Berechtigungssätze vergeben.', + audienceGrantedBy: 'Vergeben durch {{sets}}', + audienceRemove: '{{name}} entfernen', + audiencePositions: '{{positions}} sehen diese Ansicht', + audienceNoPosition: 'Keine Position hat alle gewählten Berechtigungen: Nur direkt Berechtigte und die Bearbeiter des Objekts sehen diese Ansicht', + audiencePositionsUnread: 'Die Positionen konnten nicht gelesen werden, daher wird nicht angezeigt, wer diese Ansicht sieht', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Ein unveröffentlichter Entwurf verwendet bereits den Namen dieser Ansicht, daher wurde nichts geteilt. Geben Sie der Ansicht einen anderen Namen und versuchen Sie es erneut.', viewGone: 'Die geöffnete Ansicht ist nicht mehr verfügbar, daher zeigt die Liste ihre Standardansicht.', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index cb216001c7b..4d3005813fe 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1660,7 +1660,20 @@ const en = { typeLabel: 'View type', includeCurrent: 'Include the current filters and sort', scopeShared: 'Shared', - scopeHint: 'Shared views are seen by everyone who can see this list', + scopeHint: 'Shared views are seen by everyone who can see this list, unless the view is limited to the holders of a capability', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: 'Who sees this view', + audienceEveryone: 'Everyone who can see this list', + audienceAdd: 'Limit to a capability…', + audienceAllAdded: 'All capabilities added', + audienceLoading: 'Loading capabilities…', + audienceLoadFailed: 'The capabilities could not be loaded, so the view can only be shared with everyone: {{message}}', + audienceNone: 'No capability is defined yet. Capabilities are granted on permission sets, in Setup.', + audienceGrantedBy: 'Granted by {{sets}}', + audienceRemove: 'Remove {{name}}', + audiencePositions: '{{positions}} will see this view', + audienceNoPosition: 'No position holds every picked capability: only people granted them directly, and the object’s editors, will see this view', + audiencePositionsUnread: 'The positions could not be read, so who will see this view is not shown', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'An unpublished draft already uses this view’s name, so nothing was shared. Give the view another name and try again.', viewGone: 'The view you opened is no longer available, so the list shows its default view.', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 75eff829d9b..ef47366caa8 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1385,7 +1385,20 @@ const es = { typeLabel: 'Tipo de vista', includeCurrent: 'Incluir los filtros y el orden actuales', scopeShared: 'Compartida', - scopeHint: 'Las vistas compartidas las ve cualquiera que pueda ver esta lista', + scopeHint: 'Las vistas compartidas las ve cualquiera que pueda ver esta lista, salvo que la vista se limite a quienes tengan un permiso', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: 'Quién ve esta vista', + audienceEveryone: 'Cualquiera que pueda ver esta lista', + audienceAdd: 'Limitar a un permiso…', + audienceAllAdded: 'Todos los permisos añadidos', + audienceLoading: 'Cargando permisos…', + audienceLoadFailed: 'No se pudieron cargar los permisos, así que la vista solo puede compartirse con todos: {{message}}', + audienceNone: 'Aún no hay permisos definidos. Los permisos se conceden en Configuración, en los conjuntos de permisos.', + audienceGrantedBy: 'Concedido por {{sets}}', + audienceRemove: 'Quitar {{name}}', + audiencePositions: '{{positions}} verán esta vista', + audienceNoPosition: 'Ningún puesto tiene todos los permisos elegidos: solo quienes los tengan concedidos directamente y los editores del objeto verán esta vista', + audiencePositionsUnread: 'No se pudieron leer los puestos, así que no se muestra quién verá esta vista', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Un borrador sin publicar ya usa el nombre de esta vista, así que no se compartió nada. Ponle otro nombre a la vista e inténtalo de nuevo.', viewGone: 'La vista que abriste ya no está disponible, así que la lista muestra su vista predeterminada.', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 46a334ba5fd..891cff5e301 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1380,7 +1380,20 @@ const fr = { typeLabel: 'Type de vue', includeCurrent: 'Inclure les filtres et le tri actuels', scopeShared: 'Partagée', - scopeHint: 'Les vues partagées sont visibles par tous ceux qui voient cette liste', + scopeHint: 'Les vues partagées sont visibles par tous ceux qui voient cette liste, sauf si la vue est limitée aux détenteurs d’une autorisation', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: 'Qui voit cette vue', + audienceEveryone: 'Tous ceux qui voient cette liste', + audienceAdd: 'Limiter à une autorisation…', + audienceAllAdded: 'Toutes les autorisations ajoutées', + audienceLoading: 'Chargement des autorisations…', + audienceLoadFailed: 'Les autorisations n’ont pas pu être chargées, la vue ne peut donc être partagée qu’avec tout le monde : {{message}}', + audienceNone: 'Aucune autorisation n’est encore définie. Les autorisations s’accordent dans Configuration, sur les ensembles d’autorisations.', + audienceGrantedBy: 'Accordée par {{sets}}', + audienceRemove: 'Retirer {{name}}', + audiencePositions: '{{positions}} verront cette vue', + audienceNoPosition: 'Aucun poste ne détient toutes les autorisations choisies : seules les personnes qui les ont reçues directement et les éditeurs de l’objet verront cette vue', + audiencePositionsUnread: 'Les postes n’ont pas pu être lus, qui verra cette vue n’est donc pas affiché', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Un brouillon non publié utilise déjà le nom de cette vue, donc rien n’a été partagé. Donnez un autre nom à la vue et réessayez.', viewGone: 'La vue ouverte n’est plus disponible, la liste affiche donc sa vue par défaut.', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 84676a167a6..7daa08bd517 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1348,7 +1348,20 @@ const ja = { typeLabel: 'ビューの種類', includeCurrent: '現在のフィルターと並べ替えを含める', scopeShared: '共有', - scopeHint: '共有ビューはこのリストを見られる全員に表示されます', + scopeHint: '共有ビューはこのリストを見られる全員に表示されます。ただし、ある権限の保有者に限定した場合を除きます', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: 'このビューを見られる人', + audienceEveryone: 'このリストを見られる全員', + audienceAdd: '権限の保有者に限定…', + audienceAllAdded: 'すべての権限を追加済み', + audienceLoading: '権限を読み込み中…', + audienceLoadFailed: '権限を読み込めないため、このビューは全員にのみ共有できます:{{message}}', + audienceNone: '権限はまだ定義されていません。権限はセットアップで権限セットに付与します。', + audienceGrantedBy: '付与元:{{sets}}', + audienceRemove: '{{name}} を削除', + audiencePositions: '{{positions}} がこのビューを見られます', + audienceNoPosition: '選択したすべての権限を持つ役職はありません。直接付与された人とオブジェクトの編集者だけがこのビューを見られます', + audiencePositionsUnread: '役職を読み込めないため、このビューを見られる人は表示されません', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: '未公開の下書きがすでにこのビューの名前を使っているため、共有しませんでした。ビューの名前を変えてもう一度お試しください。', viewGone: '開いたビューはもう存在しないため、リストは既定のビューを表示しています。', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index a47943f0187..63d2ec87598 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1348,7 +1348,20 @@ const ko = { typeLabel: '보기 유형', includeCurrent: '현재 필터와 정렬 포함', scopeShared: '공유', - scopeHint: '공유 보기는 이 목록을 볼 수 있는 모든 사람에게 표시됩니다', + scopeHint: '공유 보기는 이 목록을 볼 수 있는 모든 사람에게 표시됩니다. 단, 특정 권한 보유자로 제한한 경우는 예외입니다', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: '이 보기를 볼 수 있는 사람', + audienceEveryone: '이 목록을 볼 수 있는 모든 사람', + audienceAdd: '권한 보유자로 제한…', + audienceAllAdded: '모든 권한이 추가됨', + audienceLoading: '권한을 불러오는 중…', + audienceLoadFailed: '권한을 불러올 수 없어 이 보기는 모든 사람에게만 공유할 수 있습니다: {{message}}', + audienceNone: '아직 정의된 권한이 없습니다. 권한은 설정에서 권한 집합에 부여합니다.', + audienceGrantedBy: '{{sets}}에서 부여', + audienceRemove: '{{name}} 제거', + audiencePositions: '{{positions}}이(가) 이 보기를 봅니다', + audienceNoPosition: '선택한 모든 권한을 가진 직위가 없습니다. 직접 부여받은 사람과 개체 편집자만 이 보기를 봅니다', + audiencePositionsUnread: '직위를 읽을 수 없어 이 보기를 볼 사람이 표시되지 않습니다', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: '게시되지 않은 초안이 이미 이 보기의 이름을 사용하고 있어 공유하지 않았습니다. 보기 이름을 바꾸고 다시 시도하세요.', viewGone: '연 보기가 더 이상 없으므로 목록에 기본 보기가 표시됩니다.', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 5a925e1705c..b082687c618 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1380,7 +1380,20 @@ const pt = { typeLabel: 'Tipo de visualização', includeCurrent: 'Incluir os filtros e a ordenação atuais', scopeShared: 'Compartilhada', - scopeHint: 'Visualizações compartilhadas são vistas por todos que podem ver esta lista', + scopeHint: 'Visualizações compartilhadas são vistas por todos que podem ver esta lista, a menos que a visualização seja limitada a quem tem uma permissão', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: 'Quem vê esta visualização', + audienceEveryone: 'Todos que podem ver esta lista', + audienceAdd: 'Limitar a uma permissão…', + audienceAllAdded: 'Todas as permissões adicionadas', + audienceLoading: 'Carregando permissões…', + audienceLoadFailed: 'Não foi possível carregar as permissões, então a visualização só pode ser compartilhada com todos: {{message}}', + audienceNone: 'Nenhuma permissão definida ainda. As permissões são concedidas em Configuração, nos conjuntos de permissões.', + audienceGrantedBy: 'Concedida por {{sets}}', + audienceRemove: 'Remover {{name}}', + audiencePositions: '{{positions}} verão esta visualização', + audienceNoPosition: 'Nenhum cargo tem todas as permissões escolhidas: só quem as recebeu diretamente e os editores do objeto verão esta visualização', + audiencePositionsUnread: 'Não foi possível ler os cargos, então não é mostrado quem verá esta visualização', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Um rascunho não publicado já usa o nome desta visualização, então nada foi compartilhado. Dê outro nome à visualização e tente novamente.', viewGone: 'A visualização que você abriu não está mais disponível, então a lista mostra a visualização padrão.', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 77d9eca1ccd..a48961cbc61 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1418,7 +1418,20 @@ const ru = { typeLabel: 'Тип представления', includeCurrent: 'Включить текущие фильтры и сортировку', scopeShared: 'Общее', - scopeHint: 'Общие представления видны всем, кто видит этот список', + scopeHint: 'Общие представления видны всем, кто видит этот список, если представление не ограничено владельцами разрешения', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: 'Кто видит это представление', + audienceEveryone: 'Все, кто видит этот список', + audienceAdd: 'Ограничить разрешением…', + audienceAllAdded: 'Все разрешения добавлены', + audienceLoading: 'Загрузка разрешений…', + audienceLoadFailed: 'Не удалось загрузить разрешения, поэтому представление можно открыть только для всех: {{message}}', + audienceNone: 'Разрешения ещё не определены. Разрешения выдаются в настройках через наборы разрешений.', + audienceGrantedBy: 'Выдаётся набором {{sets}}', + audienceRemove: 'Удалить {{name}}', + audiencePositions: 'Это представление увидят: {{positions}}', + audienceNoPosition: 'Ни одна должность не имеет всех выбранных разрешений: представление увидят только те, кому они выданы напрямую, и редакторы объекта', + audiencePositionsUnread: 'Не удалось прочитать должности, поэтому не показано, кто увидит это представление', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Неопубликованный черновик уже использует имя этого представления, поэтому ничего не открыто для всех. Переименуйте представление и попробуйте снова.', viewGone: 'Открытое представление больше недоступно, поэтому список показывает представление по умолчанию.', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index a6ffde7ff72..900435fe95b 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1375,7 +1375,20 @@ const zh = { typeLabel: '视图类型', includeCurrent: '包含当前的筛选和排序', scopeShared: '共享', - scopeHint: '共享视图对能看到此列表的所有人可见', + scopeHint: '共享视图对能看到此列表的所有人可见,除非限定为持有某项能力的人', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: '谁能看此视图', + audienceEveryone: '能看到此列表的所有人', + audienceAdd: '限定为持有某项能力的人…', + audienceAllAdded: '已添加全部能力', + audienceLoading: '正在加载能力…', + audienceLoadFailed: '无法加载能力,此视图只能共享给所有人:{{message}}', + audienceNone: '尚未定义任何能力。能力在设置中通过权限集授予。', + audienceGrantedBy: '由 {{sets}} 授予', + audienceRemove: '移除 {{name}}', + audiencePositions: '{{positions}} 会看到此视图', + audienceNoPosition: '没有岗位同时持有所选的全部能力:只有被直接授予这些能力的人和该对象的编辑者能看到此视图', + audiencePositionsUnread: '无法读取岗位,因此不显示谁会看到此视图', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: '一个尚未发布的草稿已经用了这个视图的名称,所以没有共享。请换个名称再试。', viewGone: '你打开的视图已不存在,列表显示的是默认视图。', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index c69973ef4b9..227dead95c4 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1375,7 +1375,20 @@ const zhHant = { typeLabel: '檢視型別', includeCurrent: '包含當前的篩選和排序', scopeShared: '共享', - scopeHint: '共享檢視對能看到此列表的所有人可見', + scopeHint: '共享檢視對能看到此列表的所有人可見,除非限定為持有某項能力的人', + // objectstack#34908 — who a shared view reaches: the capability picker and its position preview. + audienceLabel: '誰能看此檢視', + audienceEveryone: '能看到此列表的所有人', + audienceAdd: '限定為持有某項能力的人…', + audienceAllAdded: '已新增全部能力', + audienceLoading: '正在載入能力…', + audienceLoadFailed: '無法載入能力,此檢視只能共享給所有人:{{message}}', + audienceNone: '尚未定義任何能力。能力在設定中透過權限集授予。', + audienceGrantedBy: '由 {{sets}} 授予', + audienceRemove: '移除 {{name}}', + audiencePositions: '{{positions}} 會看到此檢視', + audienceNoPosition: '沒有職位同時持有所選的全部能力:只有被直接授予這些能力的人和該物件的編輯者能看到此檢視', + audiencePositionsUnread: '無法讀取職位,因此不顯示誰會看到此檢視', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: '一個尚未釋出的草稿已經用了這個檢視的名稱,所以沒有共享。請換個名稱再試。', viewGone: '你開啟的檢視已不存在,列表顯示的是預設檢視。', diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 9e54fa03a70..0e419609ad3 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -1855,6 +1855,15 @@ const STUDIO_EN: Record = { 'engine.form.addPermissionSetPlain': 'Add permission set', 'engine.form.addPermissionSet': 'Add permission set…', 'engine.form.allPermissionSetsAdded': 'All permission sets added', + // The `ref-multi:capability` picker of an audience gate (`requiredPermissions` + // on a list view or a dashboard) and its position preview. + 'engine.form.addCapabilityPlain': 'Add capability', + 'engine.form.addCapability': 'Add capability…', + 'engine.form.allCapabilitiesAdded': 'All capabilities added', + 'engine.form.audienceEveryone': 'No capability picked: everyone who can see the list sees it.', + 'engine.form.audiencePositions': 'Positions that will see it: {positions}.', + 'engine.form.audienceNoPosition': 'No position holds every picked capability: only people granted them directly, and the object\'s editors, will see it.', + 'engine.form.audiencePositionsUnread': 'The positions could not be read, so who will see it is not shown.', 'engine.form.noObjectFields': 'No object fields ({error}).', // objectui#10862, slice 4 — the not-found `error` the field and dataset // catalogue hooks (`useObjectFields`, `useDatasetSemantics`) publish, read diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index 41488bbe6a0..f161cceefd3 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -1644,6 +1644,13 @@ const STUDIO_ZH: Record = { 'engine.form.addPermissionSetPlain': '添加权限集', 'engine.form.addPermissionSet': '添加权限集…', 'engine.form.allPermissionSetsAdded': '已添加全部权限集', + 'engine.form.addCapabilityPlain': '添加能力', + 'engine.form.addCapability': '添加能力…', + 'engine.form.allCapabilitiesAdded': '已添加全部能力', + 'engine.form.audienceEveryone': '未选能力:能看到该列表的人都能看到。', + 'engine.form.audiencePositions': '会看到的岗位:{positions}。', + 'engine.form.audienceNoPosition': '没有岗位同时持有所选的全部能力:只有被直接授予这些能力的人和对象编辑者能看到。', + 'engine.form.audiencePositionsUnread': '读取不到岗位,无法显示谁会看到。', 'engine.form.noObjectFields': '没有对象字段({error})。', // objectui#10862, slice 4. 'engine.form.objectNotFound': '未找到对象', From f67c1e60c570f06ae6e0fda62cf6a1a079fc7ecd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 10:32:06 +0000 Subject: [PATCH 2/5] fix(app-shell): the audience preview reads the served position grants, and the picker stays closed L1 rework on the who-sees-this-view picker: - The "no position" preview no longer says the object's editors still see the view: the carriers these surfaces write, a view item and a dashboard, are refused whole to their author too (11 console locales, studio en/zh, capabilityAudience.ts's header). - The create card says, while a gate is picked, that it applies to the creator too. - The position preview reads each position's sets in force from `GET /meta/position?include=grants` instead of joining a position's raw `permissionSets` in the browser; a list served without them leaves the positions unknown. - The Studio `ref-multi:capability` picker shows each option's granting sets and offers no typed-name box when the catalog is unread, empty or failed. - zh-Hant regenerated from zh-Hans with the pack's generator. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibxDBbvf7dEeutsepbm --- .changeset/34908-view-audience-picker.md | 2 +- content/docs/permissions/capabilities.mdx | 9 +- .../src/views/ViewAudiencePicker.tsx | 16 +++- .../app-shell/src/views/capabilityAudience.ts | 60 ++++++++---- .../SchemaForm.widgetLabelling.test.tsx | 2 +- .../src/views/metadata-admin/widgets.tsx | 53 ++++++++++- .../src/views/viewAudience-34908.test.tsx | 91 +++++++++++++++++-- ui/packages/i18n/src/locales/ar.ts | 3 +- ui/packages/i18n/src/locales/de.ts | 3 +- ui/packages/i18n/src/locales/en.ts | 3 +- ui/packages/i18n/src/locales/es.ts | 3 +- ui/packages/i18n/src/locales/fr.ts | 3 +- ui/packages/i18n/src/locales/ja.ts | 3 +- ui/packages/i18n/src/locales/ko.ts | 3 +- ui/packages/i18n/src/locales/pt-BR.ts | 3 +- ui/packages/i18n/src/locales/ru.ts | 3 +- ui/packages/i18n/src/locales/zh-Hans.ts | 3 +- ui/packages/i18n/src/locales/zh-Hant.ts | 7 +- ui/packages/i18n/src/namespaces/studio/en.ts | 5 +- ui/packages/i18n/src/namespaces/studio/zh.ts | 5 +- 20 files changed, 222 insertions(+), 58 deletions(-) diff --git a/.changeset/34908-view-audience-picker.md b/.changeset/34908-view-audience-picker.md index a6217140c75..076571af107 100644 --- a/.changeset/34908-view-audience-picker.md +++ b/.changeset/34908-view-audience-picker.md @@ -12,7 +12,7 @@ Metadata-protocol: none The audience gate is the existing, server-enforced `requiredPermissions` (all of the capabilities listed are required). The console now sets it from a closed list and shows who it reaches; no key, value or gate changes, and nothing is granted from the view (granting stays in Setup). -- **`@object-ui/app-shell`.** The view switcher's in-place create card offers 「Who sees this view」 for a shared view: the capabilities the environment knows (declared, or granted by a permission set), each with the permission sets granting it, and a read-only preview of the positions whose permission sets grant every capability picked. It starts from the open view's gate, which a new shared view used to inherit silently, and the pick replaces it; an empty pick writes no gate. A failed catalog read offers nothing to type. The shared hint no longer says every shared view is seen by everyone who can see the list. In Studio, the view panel's and the dashboard settings' audience row is the new `ref-multi:capability` picker with the same preview under it. +- **`@object-ui/app-shell`.** The view switcher's in-place create card offers 「Who sees this view」 for a shared view: the capabilities the environment knows (declared, or granted by a permission set), each with the permission sets granting it, and a read-only preview of the positions whose permission sets grant every capability picked. The preview reads each position's sets from the server (`GET /meta/position?include=grants`, the sets the resolver grants its holders), never from a position's raw definition; a list served without them leaves the positions unknown. While a gate is picked, the card says it applies to its creator too. It starts from the open view's gate, which a new shared view used to inherit silently, and the pick replaces it; an empty pick writes no gate. A failed catalog read offers nothing to type. The shared hint no longer says every shared view is seen by everyone who can see the list. In Studio, the view panel's and the dashboard settings' audience row is the new `ref-multi:capability` picker: a closed list (no typed-name box when the catalog is unread, empty or failed), each option with its granting sets, and the same preview under it. - **`@objectstack/spec`.** The view and dashboard forms' `requiredPermissions` rows declare `widget: 'ref-multi:capability'` (a host with no catalog keeps the typed-name box). The view hint's last sentence now says only what holds on every carrier: the person setting the gate no longer sees the view in the list either. - **`@objectstack/platform-objects`.** The `metadataForms` bundles carry the narrowed view hint (zh-CN, ja-JP and es-ES translated; the other locales the English source). - **`@object-ui/i18n`.** The create card's new strings and the corrected shared hint, in all eleven console locales. diff --git a/content/docs/permissions/capabilities.mdx b/content/docs/permissions/capabilities.mdx index 33c0f4d966c..3c05b11c8ad 100644 --- a/content/docs/permissions/capabilities.mdx +++ b/content/docs/permissions/capabilities.mdx @@ -223,10 +223,11 @@ Setup. nothing there. Under the pick, the console previews the positions that will see the view: the -positions whose permission sets grant **every** capability picked. The preview -is advice, and the server stays the authority. It does not account for a -deactivated permission set, and it cannot name people who hold a set directly -rather than through a position. +positions whose permission sets grant **every** capability picked. It reads +which sets each position grants from the server, the sets the resolver grants +its holders, so a position that has been switched off reaches no one. The preview is +still advice, and the server stays the authority: it cannot name people who +hold a set directly rather than through a position. **The gate applies to you too.** Pick a capability you do not hold, and the view diff --git a/ui/packages/app-shell/src/views/ViewAudiencePicker.tsx b/ui/packages/app-shell/src/views/ViewAudiencePicker.tsx index ee89fbbfff2..93766c62510 100644 --- a/ui/packages/app-shell/src/views/ViewAudiencePicker.tsx +++ b/ui/packages/app-shell/src/views/ViewAudiencePicker.tsx @@ -11,8 +11,9 @@ * matches nothing. There is no free-text fallback: when the catalog cannot be * read, nothing can be added and the view is shared with everyone (a name * already picked can still be removed). Under the list it previews, read-only, - * which positions the picked set reaches. It grants nothing: granting stays in - * Setup. + * which positions the picked set reaches (the sets each position grants in + * force, as the server serves them), and says the gate applies to the creator + * too. It grants nothing: granting stays in Setup. */ import { useId } from 'react'; @@ -51,7 +52,7 @@ export function ViewAudiencePicker({ audience, value, onChange, disabled }: View const reached = positionsReached(value, loaded.positions) ?? []; preview = reached.length === 0 ? t('view.switcher.audienceNoPosition', { - defaultValue: 'No position holds every picked capability: only people granted them directly, and the object’s editors, will see this view', + defaultValue: 'No position holds every picked capability: only people granted them directly will see this view', }) : t('view.switcher.audiencePositions', { defaultValue: '{{positions}} will see this view', @@ -139,6 +140,15 @@ export function ViewAudiencePicker({ audience, value, onChange, disabled }: View {preview}

)} + {/* The gate refuses a view item whole, its creator included, and the card + opens the view once it is created: say so while a gate is picked. */} + {value.length > 0 && ( +

+ {t('view.switcher.audienceSelf', { + defaultValue: 'This applies to you too: if you do not hold every capability picked, the view leaves your own list once it is created', + })} +

+ )} ); } diff --git a/ui/packages/app-shell/src/views/capabilityAudience.ts b/ui/packages/app-shell/src/views/capabilityAudience.ts index d2f87ae03bc..cdb2b336d40 100644 --- a/ui/packages/app-shell/src/views/capabilityAudience.ts +++ b/ui/packages/app-shell/src/views/capabilityAudience.ts @@ -8,8 +8,8 @@ * The gate is the existing `requiredPermissions` (ruling 6095014058): a list of * capabilities, every one required, enforced by the server's `/meta` read gate. * A capability reaches a person through a permission set's `systemPermissions`, - * and a position passes on the capabilities of the permission sets it names in - * `permissionSets` (ADR-0131 D3/D4) — it carries none of its own. So this + * and a position passes on the capabilities of the permission sets it grants + * (ADR-0131 D3/D4) — it carries none of its own. So this * module reads three registries and joins them; it writes nothing, and the * view surface never grants (granting stays in Setup). * @@ -18,14 +18,17 @@ * same "known capability" set `validateCapabilityReferences` in * `@objectstack/lint` resolves against — so an administrator, or an AI driving * the console, cannot pick a name that matches nothing (a misspelled gate hides - * the view from everyone but the object's editors). + * the view, or the dashboard, from everyone, its author included). * - * The position preview is advisory and states only what the catalog says: a - * position is listed when the permission sets it names grant EVERY picked - * capability between them. It does not read the activation ledger (a - * deactivated set confers nothing at runtime) and it cannot list people who - * hold a set directly rather than through a position; the server's gate stays - * the authority. + * The position preview reads which sets each position grants from the server: + * `GET /meta/position?include=grants` serves `_grantedPermissionSets`, the sets + * in force as the authorization resolver reads them (`describePositionGrants`), + * so the browser never joins a position's raw `permissionSets` itself. A + * position is listed when those sets grant EVERY picked capability between + * them. A list served without that decoration (no security service, a caller + * it is not described for) leaves the positions unknown, never guessed. The + * preview still cannot list people who hold a set directly rather than through + * a position; the server's gate stays the authority. */ /** One capability the environment knows, as the pickers offer it. */ @@ -42,14 +45,14 @@ export interface CapabilityOption { export interface PositionReach { name: string; label?: string; - /** Every capability the position's named permission sets grant. */ + /** Every capability granted by the sets the position grants in force, as served. */ capabilities: string[]; } /** The joined catalog: what may be picked, and which positions hold what. */ export interface CapabilityAudience { capabilities: CapabilityOption[]; - /** `null` when the position registry could not be read: the preview then says so. */ + /** `null` when the positions' grants could not be read, or were not served: the preview then says so. */ positions: PositionReach[] | null; } @@ -68,10 +71,26 @@ const labelOf = (row: Row): string | undefined => const stringsOf = (value: unknown): string[] => Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string' && v.trim() !== '') : []; +/** + * The sets a position grants in force, as `?include=grants` serves them + * (`_grantedPermissionSets: [{ name, via }]`); `undefined` when the row carries + * no such decoration. + */ +function grantedSetsOf(row: Row): string[] | undefined { + const served = row._grantedPermissionSets; + if (!Array.isArray(served)) return undefined; + return served + .map((entry) => (entry && typeof entry === 'object' ? (entry as Row).name : undefined)) + .filter((name): name is string => typeof name === 'string' && name.trim() !== ''); +} + /** * Join the three registries' rows into the pickers' catalog. Pure: the rows - * are what `list('capability')`, `list('permission')` and `list('position')` - * answered (`positions: null` when that read failed). + * are what `list('capability')`, `list('permission')` and + * `list('position', { include: 'grants' })` answered (`positions: null` when + * that read failed). A position row without the served grants makes the + * positions unknown (`null`): the preview is never computed from the raw + * `permissionSets` a position names. */ export function buildCapabilityAudience( capabilityRows: readonly unknown[], @@ -106,14 +125,15 @@ export function buildCapabilityAudience( grantedBy: [...(grantedBy.get(name) ?? [])].sort((a, b) => a.localeCompare(b)), })); - const positions = positionRows === null + const rows = positionRows === null + ? null + : positionRows.map(unwrap).filter((row): row is Row => !!row && !!nameOf(row)); + const positions = rows === null || rows.some((row) => grantedSetsOf(row) === undefined) ? null - : positionRows - .map(unwrap) - .filter((row): row is Row => !!row && !!nameOf(row)) + : rows .map((row) => { const caps = new Set(); - for (const set of stringsOf(row.permissionSets)) for (const cap of setGrants.get(set) ?? []) caps.add(cap); + for (const set of grantedSetsOf(row)!) for (const cap of setGrants.get(set) ?? []) caps.add(cap); return { name: nameOf(row)!, ...(labelOf(row) ? { label: labelOf(row) } : {}), @@ -140,7 +160,7 @@ export function positionsReached( /** The metadata reads {@link loadCapabilityAudience} makes — the console `MetadataClient`'s `list`. */ export interface CapabilityAudienceSource { - list: (type: string) => Promise; + list: (type: string, options?: { include?: 'grants' }) => Promise; } /** @@ -152,7 +172,7 @@ export async function loadCapabilityAudience(source: CapabilityAudienceSource): const [capabilities, permissionSets, positions] = await Promise.all([ source.list('capability'), source.list('permission'), - source.list('position').catch(() => null), + source.list('position', { include: 'grants' }).catch(() => null), ]); return buildCapabilityAudience( Array.isArray(capabilities) ? capabilities : [], diff --git a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx index 126a0484026..d344ccc1f26 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/SchemaForm.widgetLabelling.test.tsx @@ -157,7 +157,7 @@ const CASES: Case[] = [ // No `ctx` at all: the hosts that feed no catalog get the typed-name box inside the same named list (objectui#12126). { key: 'ref-multi:permission', variant: 'no-catalog', schema: { type: 'array', title: TITLE, items: { type: 'string' } }, value: ['sales_rep'] }, { key: 'ref-multi:capability', schema: { type: 'array', title: TITLE, items: { type: 'string' } }, ctx: { capabilityAudience: loaded({ capabilities: [{ name: 'view_deal_sales', grantedBy: ['sales_rep_set'] }], positions: [] }) }, value: ['view_deal_sales'] }, - // No `ctx` at all: the hosts that feed no catalog get the typed-name box inside the same named list (objectstack#34908). + // No `ctx` at all: a closed list says the capabilities are not available here, inside the same named list (objectstack#34908). { key: 'ref-multi:capability', variant: 'no-catalog', schema: { type: 'array', title: TITLE, items: { type: 'string' } }, value: ['view_deal_sales'] }, { key: 'filter-mode', schema: { type: 'object', title: TITLE }, ctx: { objectFields: loaded([{ name: 'status' }]) }, value: { element: 'dropdown' } }, { key: 'object-selector', schema: { type: 'string', title: TITLE }, ctx: { objectNames: loaded(['account']) }, value: 'account' }, diff --git a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx index 83cdb67b965..8d08f248ebe 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx @@ -854,6 +854,16 @@ interface RefMultiRegistry { allAddedKey: string; /** What the picked names mean, drawn under the list (the capability picker's position preview). */ footer?: (selected: readonly string[], context: WidgetContext | undefined, locale: SupportedLocale) => React.ReactNode; + /** A second line under an offered item (the capability picker: the permission sets granting it). */ + detail?: (name: string, context: WidgetContext | undefined, locale: SupportedLocale) => string | undefined; + /** + * A CLOSED list (objectstack#34908): no typed-name box on any arm. A catalog + * nobody fed says `unreadKey`, a completed read that found nothing says + * `noneKey`, a failed read shows only the failure notice — so a name that + * matches nothing can never be added. Names already stored stay listed and + * removable on every arm. + */ + closed?: { unreadKey: string; noneKey: string }; } /** @@ -872,6 +882,11 @@ interface RefMultiRegistry { * unregistered hint falls back to; * - LOADED — an add picker offering the declared items not yet picked. * + * A registry declared `closed` (the capability picker, objectstack#34908) + * offers no text box on any arm: FAILED shows only its notice, `idle` and an + * empty load each say why nothing can be added, LOADING shows a disabled + * picker. + * * A stored name the LOADED catalog does not declare stays in the list, flagged * `(not found)`, so it is neither dropped nor read as a declared item * (objectui#8488). The flag is a claim about the registry's answer, so it is @@ -989,14 +1004,35 @@ function RefMultiWidget({ {remaining.map((o) => ( - - {o.label && o.label !== o.name && {o.label}} - {o.name} + + + {o.label && o.label !== o.name && {o.label}} + {o.name} + + {registry.detail?.(o.name, context, locale) && ( + + {registry.detail(o.name, context, locale)} + + )} ))} + ) : registry.closed ? ( + // A closed list offers no typed-name box: say why nothing can be + // added (a failed read already shows its notice above). + loadError ? null : loading ? ( + + ) : ( +

+ {t(declared ? registry.closed.noneKey : registry.closed.unreadKey, locale)} +

+ ) ) : ( freeform ))} @@ -1054,10 +1090,19 @@ function CapabilityAudienceFooter({ /** * The `ref-multi:capability` registration: the capabilities the environment * knows (declared, or granted by a permission set), each offered with the - * permission sets granting it, and the positions the picked set reaches. + * permission sets granting it, and the positions the picked set reaches. The + * list is CLOSED: no arm offers a typed-name box, so a gate cannot name a + * capability nothing declares or grants (objectstack#34908). */ const CAPABILITY_REGISTRY: RefMultiRegistry = { type: 'capability', + closed: { unreadKey: 'engine.form.capabilitiesUnread', noneKey: 'engine.form.capabilitiesNone' }, + detail: (name, context, locale) => { + const state = context?.capabilityAudience; + if (state?.status !== 'loaded') return undefined; + const sets = state.data.capabilities.find((c) => c.name === name)?.grantedBy ?? []; + return sets.length > 0 ? tFormat('engine.form.capabilityGrantedBy', locale, { sets: sets.join(', ') }) : undefined; + }, catalog: (context) => context?.capabilityAudience ? mapLoaded(context.capabilityAudience, (audience) => diff --git a/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx b/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx index e27dc8d57f3..928eff436a0 100644 --- a/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx +++ b/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx @@ -6,17 +6,20 @@ * What is pinned: * - the catalog: the capabilities offered are the ones the registry declares * and every name a permission set grants (a closed list), each with the - * sets granting it; a position holds what its named sets grant; a failed - * position read keeps the catalog and says the positions are unknown; + * sets granting it; a position holds what the sets it grants IN FORCE + * grant, as `?include=grants` serves them (never its raw `permissionSets`); + * an undecorated or failed position read leaves the positions unknown; * - the preview: a position is listed when its sets grant EVERY picked * capability (the gate is all-of); nothing picked is no gate; * - the create card's shared scope: the corrected hint, the picker offered * only for a shared view and only from the catalog, its position preview, * the open view's gate as the starting pick, and the pick on the request; - * a failed catalog read adds nothing (no free text); + * a failed catalog read adds nothing (no free text); a picked gate says it + * applies to the creator too; * - the host: the picked gate replaces the one the open view would hand on, * an empty pick writes no key, and no picker leaves the body as before; - * - the Studio form widget `ref-multi:capability`: the closed list and the + * - the Studio form widget `ref-multi:capability`: the closed list (no + * typed-name box on any arm), each option with its granting sets, and the * same preview under it. */ @@ -61,10 +64,16 @@ const PERMISSION_SETS = [ { name: 'sales_lead_set', systemPermissions: ['view_deal_sales', 'view_deal_finance'] }, { name: 'finance_set', systemPermissions: ['view_deal_finance'] }, ]; +// As `GET /meta/position?include=grants` serves them: `_grantedPermissionSets` +// is the server's answer (the sets in force); the raw `permissionSets` a +// position names is NOT what the preview reads — `paused_lead` names a set +// but grants none (switched off), and `accountant` names one that is not served. +const grants = (...sets: string[]) => sets.map((name) => ({ name, via: 'definition' })); const POSITIONS = [ - { name: 'sales_rep', label: '业务员', permissionSets: ['sales_rep_set'] }, - { name: 'sales_lead', label: '销售主管', permissionSets: ['sales_lead_set'] }, - { name: 'accountant', permissionSets: ['finance_set', 'missing_set'] }, + { name: 'sales_rep', label: '业务员', permissionSets: ['sales_rep_set'], _grantedPermissionSets: grants('sales_rep_set') }, + { name: 'sales_lead', label: '销售主管', permissionSets: ['sales_lead_set'], _grantedPermissionSets: grants('sales_lead_set') }, + { name: 'accountant', permissionSets: ['finance_set', 'missing_set'], _grantedPermissionSets: grants('finance_set') }, + { name: 'paused_lead', permissionSets: ['sales_lead_set'], _grantedPermissionSets: [] }, ]; const AUDIENCE = buildCapabilityAudience(CAPABILITIES, PERMISSION_SETS, POSITIONS); @@ -78,14 +87,20 @@ describe('the audience catalog', () => { ]); }); - it('a position holds what its named permission sets grant, and nothing of its own', () => { + it('a position holds what the sets it grants IN FORCE (as served) grant, never what its raw definition names', () => { expect(AUDIENCE.positions).toEqual([ { name: 'accountant', capabilities: ['view_deal_finance'] }, + { name: 'paused_lead', capabilities: [] }, { name: 'sales_lead', label: '销售主管', capabilities: ['view_deal_finance', 'view_deal_sales'] }, { name: 'sales_rep', label: '业务员', capabilities: ['export_reports', 'view_deal_sales'] }, ]); }); + it('a position list served without its grants leaves the positions unknown, never joined in the browser', () => { + const undecorated = POSITIONS.map(({ _grantedPermissionSets: _served, ...raw }) => raw); + expect(buildCapabilityAudience(CAPABILITIES, PERMISSION_SETS, undecorated).positions).toBeNull(); + }); + it('the preview lists a position only when its sets grant EVERY picked capability; nothing picked is no gate', () => { const positions = AUDIENCE.positions!; expect(positionsReached([], positions)).toBeNull(); @@ -94,6 +109,14 @@ describe('the audience catalog', () => { expect(positionsReached(['nobody_has_this'], positions)).toEqual([]); }); + it('reads the positions with their served grants', async () => { + const list = vi.fn(async (type: string, _options?: { include?: 'grants' }) => + (type === 'capability' ? CAPABILITIES : type === 'permission' ? PERMISSION_SETS : POSITIONS) as unknown[]); + const audience = await loadCapabilityAudience({ list }); + expect(list).toHaveBeenCalledWith('position', { include: 'grants' }); + expect(positionsReached(['view_deal_sales'], audience.positions!)!.map((p) => p.name)).toEqual(['sales_lead', 'sales_rep']); + }); + it('a failed position read keeps the catalog and leaves the positions unknown; a failed capability read fails the load', async () => { const fine = await loadCapabilityAudience({ list: async (type) => { @@ -190,7 +213,18 @@ describe('the create card: who sees a shared view', () => { mountCard({ loadAudience: async () => AUDIENCE, initialRequiredPermissions: ['export_reports', 'view_deal_finance'] }); toShared(); await settle(); - expect(screen.getByTestId('view-audience-preview').textContent).toMatch(/^No position holds every picked capability/); + expect(screen.getByTestId('view-audience-preview').textContent).toBe( + 'No position holds every picked capability: only people granted them directly will see this view', + ); + }); + + it('while a gate is picked, it says the gate applies to the creator too; with none picked it says nothing of the kind', async () => { + mountCard({ loadAudience: async () => AUDIENCE }); + toShared(); + await settle(); + expect(screen.queryByTestId('view-audience-self')).toBeNull(); + await addCapability('view_deal_sales'); + expect(screen.getByTestId('view-audience-self').textContent).toMatch(/^This applies to you too/); }); it('starts from the open view\'s gate, which can be removed: the request then carries an empty gate', async () => { @@ -315,8 +349,45 @@ describe('the view form\'s audience row in Studio', () => { expect(screen.getByTestId('ref-multi-capability-audience').textContent).toMatch(/everyone who can see the list/i); }); - it('CONTROL: no catalog fed, no preview', () => { + it('offers each capability with the permission sets granting it', async () => { + mountRow(AUDIENCE, []); + fireEvent.keyDown(screen.getByTestId('ref-multi-capability-add'), { key: 'ArrowDown' }); + const listbox = await screen.findByRole('listbox'); + expect(within(listbox).getAllByTestId('ref-multi-capability-detail').map((d) => d.textContent)).toEqual([ + 'Granted by sales_rep_set', + 'Granted by finance_set, sales_lead_set', + 'Granted by sales_lead_set, sales_rep_set', + ]); + }); + + it('is a closed list: no catalog fed, an empty one, or a failed read offers no box to type a name in', () => { mountRow(null, ['view_deal_sales']); expect(screen.queryByTestId('ref-multi-capability-audience')).toBeNull(); + expect(screen.queryByTestId('ref-multi-capability-freeform')).toBeNull(); + expect(screen.getByTestId('ref-multi-capability-closed').textContent).toBe('The capability list is not available here, so none can be added.'); + cleanup(); + mountRow({ capabilities: [], positions: [] }, []); + expect(screen.queryByTestId('ref-multi-capability-freeform')).toBeNull(); + expect(screen.getByTestId('ref-multi-capability-closed').textContent).toMatch(/^No capability is defined yet/); + cleanup(); + render( + {}} + widgetContext={{ conditionScope: 'none', capabilityAudience: { status: 'error', message: 'denied' } }} + />, + ); + expect(screen.getByTestId('ref-multi-capability-load-failed')).toBeInTheDocument(); + expect(screen.queryByTestId('ref-multi-capability-freeform')).toBeNull(); + expect(screen.getByTestId('ref-multi-capability')).toHaveTextContent('view_deal_sales'); + }); + + it('nothing reachable: the preview no longer promises the object\'s editors', () => { + mountRow(AUDIENCE, ['export_reports', 'view_deal_finance']); + expect(screen.getByTestId('ref-multi-capability-audience').textContent).toBe( + 'No position holds every picked capability: only people granted them directly will see it.', + ); }); }); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index c793bb020fa..773ccc224e7 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1497,7 +1497,8 @@ const ar = { audienceGrantedBy: 'تمنحها {{sets}}', audienceRemove: 'إزالة {{name}}', audiencePositions: 'سيرى هذا العرض: {{positions}}', - audienceNoPosition: 'لا يوجد منصب يحمل كل الصلاحيات المختارة: لن يرى هذا العرض إلا من مُنحت لهم مباشرة ومحررو الكائن', + audienceNoPosition: 'لا يوجد منصب يحمل كل الصلاحيات المختارة: لن يرى هذا العرض إلا من مُنحت لهم مباشرة', + audienceSelf: 'ينطبق هذا عليك أيضًا: إذا لم تكن تحمل كل الصلاحيات المختارة، فسيختفي العرض من قائمتك أنت أيضًا بعد إنشائه', audiencePositionsUnread: 'تعذرت قراءة المناصب، لذا لا يظهر من سيرى هذا العرض', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'توجد مسودة غير منشورة تستخدم اسم هذا العرض بالفعل، لذلك لم تتم المشاركة. غيّر اسم العرض وحاول مرة أخرى.', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 04db438da78..013a2fd4af4 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1360,7 +1360,8 @@ const de = { audienceGrantedBy: 'Vergeben durch {{sets}}', audienceRemove: '{{name}} entfernen', audiencePositions: '{{positions}} sehen diese Ansicht', - audienceNoPosition: 'Keine Position hat alle gewählten Berechtigungen: Nur direkt Berechtigte und die Bearbeiter des Objekts sehen diese Ansicht', + audienceNoPosition: 'Keine Position hat alle gewählten Berechtigungen: Nur direkt Berechtigte sehen diese Ansicht', + audienceSelf: 'Das gilt auch für Sie: Haben Sie nicht alle gewählten Berechtigungen, verschwindet die Ansicht nach dem Erstellen auch aus Ihrer eigenen Liste', audiencePositionsUnread: 'Die Positionen konnten nicht gelesen werden, daher wird nicht angezeigt, wer diese Ansicht sieht', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Ein unveröffentlichter Entwurf verwendet bereits den Namen dieser Ansicht, daher wurde nichts geteilt. Geben Sie der Ansicht einen anderen Namen und versuchen Sie es erneut.', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 4d3005813fe..10f1414cef8 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1672,7 +1672,8 @@ const en = { audienceGrantedBy: 'Granted by {{sets}}', audienceRemove: 'Remove {{name}}', audiencePositions: '{{positions}} will see this view', - audienceNoPosition: 'No position holds every picked capability: only people granted them directly, and the object’s editors, will see this view', + audienceNoPosition: 'No position holds every picked capability: only people granted them directly will see this view', + audienceSelf: 'This applies to you too: if you do not hold every capability picked, the view leaves your own list once it is created', audiencePositionsUnread: 'The positions could not be read, so who will see this view is not shown', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'An unpublished draft already uses this view’s name, so nothing was shared. Give the view another name and try again.', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index ef47366caa8..25ea95bf486 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1397,7 +1397,8 @@ const es = { audienceGrantedBy: 'Concedido por {{sets}}', audienceRemove: 'Quitar {{name}}', audiencePositions: '{{positions}} verán esta vista', - audienceNoPosition: 'Ningún puesto tiene todos los permisos elegidos: solo quienes los tengan concedidos directamente y los editores del objeto verán esta vista', + audienceNoPosition: 'Ningún puesto tiene todos los permisos elegidos: solo quienes los tengan concedidos directamente verán esta vista', + audienceSelf: 'Esto también le afecta: si no tiene todos los permisos elegidos, la vista desaparecerá de su propia lista una vez creada', audiencePositionsUnread: 'No se pudieron leer los puestos, así que no se muestra quién verá esta vista', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Un borrador sin publicar ya usa el nombre de esta vista, así que no se compartió nada. Ponle otro nombre a la vista e inténtalo de nuevo.', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 891cff5e301..754a50cf66e 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1392,7 +1392,8 @@ const fr = { audienceGrantedBy: 'Accordée par {{sets}}', audienceRemove: 'Retirer {{name}}', audiencePositions: '{{positions}} verront cette vue', - audienceNoPosition: 'Aucun poste ne détient toutes les autorisations choisies : seules les personnes qui les ont reçues directement et les éditeurs de l’objet verront cette vue', + audienceNoPosition: 'Aucun poste ne détient toutes les autorisations choisies : seules les personnes qui les ont reçues directement verront cette vue', + audienceSelf: 'Cela vous concerne aussi : si vous ne détenez pas toutes les autorisations choisies, la vue quitte votre propre liste une fois créée', audiencePositionsUnread: 'Les postes n’ont pas pu être lus, qui verra cette vue n’est donc pas affiché', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Un brouillon non publié utilise déjà le nom de cette vue, donc rien n’a été partagé. Donnez un autre nom à la vue et réessayez.', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 7daa08bd517..40eb8430db0 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1360,7 +1360,8 @@ const ja = { audienceGrantedBy: '付与元:{{sets}}', audienceRemove: '{{name}} を削除', audiencePositions: '{{positions}} がこのビューを見られます', - audienceNoPosition: '選択したすべての権限を持つ役職はありません。直接付与された人とオブジェクトの編集者だけがこのビューを見られます', + audienceNoPosition: '選択したすべての権限を持つ役職はありません。直接付与された人だけがこのビューを見られます', + audienceSelf: 'これはあなた自身にも適用されます。選択したすべての権限を持っていない場合、作成後このビューはあなたのリストからも消えます', audiencePositionsUnread: '役職を読み込めないため、このビューを見られる人は表示されません', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: '未公開の下書きがすでにこのビューの名前を使っているため、共有しませんでした。ビューの名前を変えてもう一度お試しください。', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 63d2ec87598..a2dd23d27af 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1360,7 +1360,8 @@ const ko = { audienceGrantedBy: '{{sets}}에서 부여', audienceRemove: '{{name}} 제거', audiencePositions: '{{positions}}이(가) 이 보기를 봅니다', - audienceNoPosition: '선택한 모든 권한을 가진 직위가 없습니다. 직접 부여받은 사람과 개체 편집자만 이 보기를 봅니다', + audienceNoPosition: '선택한 모든 권한을 가진 직위가 없습니다. 직접 부여받은 사람만 이 보기를 봅니다', + audienceSelf: '이는 본인에게도 적용됩니다. 선택한 모든 권한을 갖고 있지 않으면 생성 후 이 보기는 본인 목록에서도 사라집니다', audiencePositionsUnread: '직위를 읽을 수 없어 이 보기를 볼 사람이 표시되지 않습니다', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: '게시되지 않은 초안이 이미 이 보기의 이름을 사용하고 있어 공유하지 않았습니다. 보기 이름을 바꾸고 다시 시도하세요.', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index b082687c618..381320cee51 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1392,7 +1392,8 @@ const pt = { audienceGrantedBy: 'Concedida por {{sets}}', audienceRemove: 'Remover {{name}}', audiencePositions: '{{positions}} verão esta visualização', - audienceNoPosition: 'Nenhum cargo tem todas as permissões escolhidas: só quem as recebeu diretamente e os editores do objeto verão esta visualização', + audienceNoPosition: 'Nenhum cargo tem todas as permissões escolhidas: só quem as recebeu diretamente verá esta visualização', + audienceSelf: 'Isso também vale para você: se você não tiver todas as permissões escolhidas, a visualização sai da sua própria lista depois de criada', audiencePositionsUnread: 'Não foi possível ler os cargos, então não é mostrado quem verá esta visualização', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Um rascunho não publicado já usa o nome desta visualização, então nada foi compartilhado. Dê outro nome à visualização e tente novamente.', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index a48961cbc61..6b65ee22b6c 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1430,7 +1430,8 @@ const ru = { audienceGrantedBy: 'Выдаётся набором {{sets}}', audienceRemove: 'Удалить {{name}}', audiencePositions: 'Это представление увидят: {{positions}}', - audienceNoPosition: 'Ни одна должность не имеет всех выбранных разрешений: представление увидят только те, кому они выданы напрямую, и редакторы объекта', + audienceNoPosition: 'Ни одна должность не имеет всех выбранных разрешений: представление увидят только те, кому они выданы напрямую', + audienceSelf: 'Это касается и вас: если у вас нет всех выбранных разрешений, после создания представление исчезнет и из вашего списка', audiencePositionsUnread: 'Не удалось прочитать должности, поэтому не показано, кто увидит это представление', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: 'Неопубликованный черновик уже использует имя этого представления, поэтому ничего не открыто для всех. Переименуйте представление и попробуйте снова.', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 900435fe95b..11ed11179b2 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1387,7 +1387,8 @@ const zh = { audienceGrantedBy: '由 {{sets}} 授予', audienceRemove: '移除 {{name}}', audiencePositions: '{{positions}} 会看到此视图', - audienceNoPosition: '没有岗位同时持有所选的全部能力:只有被直接授予这些能力的人和该对象的编辑者能看到此视图', + audienceNoPosition: '没有岗位同时持有所选的全部能力:只有被直接授予这些能力的人能看到此视图', + audienceSelf: '这对你自己同样生效:如果你没有持有所选的全部能力,视图创建后也会从你自己的列表中消失', audiencePositionsUnread: '无法读取岗位,因此不显示谁会看到此视图', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: '一个尚未发布的草稿已经用了这个视图的名称,所以没有共享。请换个名称再试。', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 227dead95c4..124dc7da13f 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1383,12 +1383,13 @@ const zhHant = { audienceAllAdded: '已新增全部能力', audienceLoading: '正在載入能力…', audienceLoadFailed: '無法載入能力,此檢視只能共享給所有人:{{message}}', - audienceNone: '尚未定義任何能力。能力在設定中透過權限集授予。', + audienceNone: '尚未定義任何能力。能力在設定中通過權限集授予。', audienceGrantedBy: '由 {{sets}} 授予', audienceRemove: '移除 {{name}}', audiencePositions: '{{positions}} 會看到此檢視', - audienceNoPosition: '沒有職位同時持有所選的全部能力:只有被直接授予這些能力的人和該物件的編輯者能看到此檢視', - audiencePositionsUnread: '無法讀取職位,因此不顯示誰會看到此檢視', + audienceNoPosition: '沒有崗位同時持有所選的全部能力:只有被直接授予這些能力的人能看到此檢視', + audienceSelf: '這對你自己同樣生效:如果你沒有持有所選的全部能力,檢視建立後也會從你自己的列表中消失', + audiencePositionsUnread: '無法讀取崗位,因此不顯示誰會看到此檢視', // objectstack#36409 — a shared view's name already taken, and a view that is gone. shareNameTaken: '一個尚未釋出的草稿已經用了這個檢視的名稱,所以沒有共享。請換個名稱再試。', viewGone: '你開啟的檢視已不存在,列表顯示的是預設檢視。', diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 0e419609ad3..50718465788 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -1862,7 +1862,10 @@ const STUDIO_EN: Record = { 'engine.form.allCapabilitiesAdded': 'All capabilities added', 'engine.form.audienceEveryone': 'No capability picked: everyone who can see the list sees it.', 'engine.form.audiencePositions': 'Positions that will see it: {positions}.', - 'engine.form.audienceNoPosition': 'No position holds every picked capability: only people granted them directly, and the object\'s editors, will see it.', + 'engine.form.audienceNoPosition': 'No position holds every picked capability: only people granted them directly will see it.', + 'engine.form.capabilityGrantedBy': 'Granted by {sets}', + 'engine.form.capabilitiesUnread': 'The capability list is not available here, so none can be added.', + 'engine.form.capabilitiesNone': 'No capability is defined yet. Capabilities are granted on permission sets, in Setup.', 'engine.form.audiencePositionsUnread': 'The positions could not be read, so who will see it is not shown.', 'engine.form.noObjectFields': 'No object fields ({error}).', // objectui#10862, slice 4 — the not-found `error` the field and dataset diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index f161cceefd3..e95d9c6cbcd 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -1649,7 +1649,10 @@ const STUDIO_ZH: Record = { 'engine.form.allCapabilitiesAdded': '已添加全部能力', 'engine.form.audienceEveryone': '未选能力:能看到该列表的人都能看到。', 'engine.form.audiencePositions': '会看到的岗位:{positions}。', - 'engine.form.audienceNoPosition': '没有岗位同时持有所选的全部能力:只有被直接授予这些能力的人和对象编辑者能看到。', + 'engine.form.audienceNoPosition': '没有岗位同时持有所选的全部能力:只有被直接授予这些能力的人能看到。', + 'engine.form.capabilityGrantedBy': '由 {sets} 授予', + 'engine.form.capabilitiesUnread': '此处读取不到能力列表,无法添加。', + 'engine.form.capabilitiesNone': '尚未定义任何能力。能力在设置中通过权限集授予。', 'engine.form.audiencePositionsUnread': '读取不到岗位,无法显示谁会看到。', 'engine.form.noObjectFields': '没有对象字段({error})。', // objectui#10862, slice 4. From 2156f1acc842ef4aba9a45532bfa93897809e9ec Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 10:41:24 +0000 Subject: [PATCH 3/5] fix(app-shell): read the capability catalog only once the audience row is on screen The Studio hosts (the view panel, the dashboard settings, the resource editor) loaded the three registries on mount, so tests that never open the Access section reached the network. Hosts now hand a stable loader down on WidgetContext; the ref-multi:capability picker reads it when it mounts, so a closed section sends no request. A catalog the host already holds still wins. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibxDBbvf7dEeutsepbm --- packages/spec/src/ui/view.metadata-form.ts | 5 ++- .../views/metadata-admin/ResourceEditPage.tsx | 16 +++---- .../inspectors/DashboardDefaultInspector.tsx | 18 ++++---- .../inspectors/ViewVariantInspector.tsx | 17 +++----- .../useCapabilityAudienceLoad.ts | 32 -------------- .../useCapabilityAudienceLoader.ts | 26 +++++++++++ .../src/views/metadata-admin/widgets.tsx | 26 ++++++++++- .../src/views/viewAudience-34908.test.tsx | 43 ++++++++++++++++++- 8 files changed, 116 insertions(+), 67 deletions(-) delete mode 100644 ui/packages/app-shell/src/views/metadata-admin/useCapabilityAudienceLoad.ts create mode 100644 ui/packages/app-shell/src/views/metadata-admin/useCapabilityAudienceLoader.ts diff --git a/packages/spec/src/ui/view.metadata-form.ts b/packages/spec/src/ui/view.metadata-form.ts index f1b016552a6..b8aea7e18ac 100644 --- a/packages/spec/src/ui/view.metadata-form.ts +++ b/packages/spec/src/ui/view.metadata-form.ts @@ -322,8 +322,9 @@ export const viewForm = defineMetadataForm({ // form, enforced by the server) for the administrator who sets it. // `ref-multi:capability` offers only the capabilities the environment // knows (declared, or granted by a permission set) and previews which - // positions the picked set reaches; a host that feeds no catalog gets - // the typed-name box. It writes the names only — granting stays in Setup. + // positions the picked set reaches; the list is closed, so a host that + // feeds no catalog offers nothing to add. It writes the names only — + // granting stays in Setup. // The last sentence says what holds for the person setting the gate on // every carrier: the switcher drops the view for them too. It does not // promise the designer refuses it: a view item is refused on every door, diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx index 081d03c605e..6ec0447caef 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceEditPage.tsx @@ -111,7 +111,7 @@ import { conditionSubjectsForMetadataType, } from './conditionScope.js'; import { mapLoaded, usePickerLoad } from './loadState.js'; -import { useCapabilityAudienceLoad } from './useCapabilityAudienceLoad.js'; +import { useCapabilityAudienceLoader } from './useCapabilityAudienceLoader.js'; import { useMetadataClient, useMetadataTypes, @@ -1402,12 +1402,10 @@ function MetadataResourceEditPageImpl({ // objectstack#34908 — the audience catalog for the `ref-multi:capability` // picker (a list view's or a dashboard's `requiredPermissions`): the // capabilities the environment knows, the permission sets granting each and - // the positions holding them. Loaded only when the form on screen declares - // that widget, as the permission-set catalog above is. - const capabilityAudienceState = useCapabilityAudienceLoad( - client, - formDeclaresWidget(createMode && config.createSchema ? undefined : entry?.form, 'ref-multi:capability'), - ); + // the positions holding them. The picker reads it through this loader once + // it is on screen, so a form without that row, or with it in a closed + // section, sends no request. + const loadCapabilityAudience = useCapabilityAudienceLoader(client); // Component ids placed on the page being edited — fuels the `ref:component` // picker so a page variable's `source` (the component that writes it) is @@ -1467,9 +1465,9 @@ function MetadataResourceEditPageImpl({ objectViews: objectViewsState, componentIds, permissionSets: permissionSetsState, - capabilityAudience: capabilityAudienceState, + loadCapabilityAudience, }), - [type, objectsState, objectCatalogState, objectViewsState, componentIds, permissionSetsState, capabilityAudienceState], + [type, objectsState, objectCatalogState, objectViewsState, componentIds, permissionSetsState, loadCapabilityAudience], ); // Load layered view + initial draft. diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardDefaultInspector.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardDefaultInspector.tsx index 8083493a4a0..0ff0a98458e 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardDefaultInspector.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardDefaultInspector.tsx @@ -42,10 +42,10 @@ import { AddWidgetPicker } from '../previews/AddWidgetPicker.js'; import { WIDGET_TYPE_META, UnknownWidgetIcon } from '../previews/widget-types.js'; import type { MetadataDefaultInspectorProps } from '../default-inspector-registry.js'; import { SchemaForm } from '../SchemaForm.js'; -import { formDeclaresWidget, type WidgetContext } from '../widgets.js'; +import type { WidgetContext } from '../widgets.js'; import { conditionScopeForMetadataType } from '../conditionScope.js'; import { useMetadataClient } from '../useMetadata.js'; -import { useCapabilityAudienceLoad } from '../useCapabilityAudienceLoad.js'; +import { useCapabilityAudienceLoader } from '../useCapabilityAudienceLoader.js'; import { fallbackFormPatch } from './fallbackFormPatch.js'; import type { FormViewSpec } from '../SchemaForm.js'; import { getDashboardForm, getDashboardSchema } from '../dashboard-schema.js'; @@ -192,20 +192,18 @@ export function DashboardDefaultInspector({ }, [serverSchema, locale]); // objectstack#34908 — the Access section's audience row is the - // `ref-multi:capability` picker; feed it the capability catalog and the - // positions preview. This host handed down no `WidgetContext` before, so it + // `ref-multi:capability` picker; hand it the loader of the capability + // catalog and the positions preview, which it reads once the collapsed + // section is opened. This host handed down no `WidgetContext` before, so it // now states the verdict the scope table rules for its type // (`conditionScopeForMetadataType('dashboard')`) rather than inventing one; // the dashboard form declares no `condition` row, so nothing renders // differently for it. const metadataClient = useMetadataClient(); - const capabilityAudience = useCapabilityAudienceLoad( - metadataClient, - formDeclaresWidget(form, 'ref-multi:capability'), - ); + const loadCapabilityAudience = useCapabilityAudienceLoader(metadataClient); const widgetContext = React.useMemo( - () => ({ conditionScope: conditionScopeForMetadataType('dashboard'), capabilityAudience }), - [capabilityAudience], + () => ({ conditionScope: conditionScopeForMetadataType('dashboard'), loadCapabilityAudience }), + [loadCapabilityAudience], ); return ( diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ViewVariantInspector.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ViewVariantInspector.tsx index 8b62f4060bf..b8c0c7a68b9 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/ViewVariantInspector.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/ViewVariantInspector.tsx @@ -42,9 +42,9 @@ import { SchemaForm } from '../SchemaForm.js'; import { IssuePrefixLines, issuesUnderPrefix, useIssuePrefixRegister, useSliceFormIssueRows } from '../issuePath.js'; import { useObjectFields, type ObjectFieldInfo } from '../previews/useObjectFields.js'; import { failed, loaded, type LoadState } from '../loadState.js'; -import { formDeclaresWidget, type ObjectFieldOption, type WidgetContext } from '../widgets.js'; +import type { ObjectFieldOption, WidgetContext } from '../widgets.js'; import { useMetadataClient } from '../useMetadata.js'; -import { useCapabilityAudienceLoad } from '../useCapabilityAudienceLoad.js'; +import { useCapabilityAudienceLoader } from '../useCapabilityAudienceLoader.js'; /** * Object picker for the view's binding — a searchable dropdown over the live @@ -421,16 +421,13 @@ export function ViewVariantInspector({ // objectstack#34908 — the audience row (`requiredPermissions`) is the // `ref-multi:capability` picker: it offers the capabilities the environment - // knows and previews the positions the picked set reaches. The three - // registries are read only when the form on screen declares that row. + // knows and previews the positions the picked set reaches. The picker reads + // the three registries through this loader once it is on screen. const metadataClient = useMetadataClient(); - const capabilityAudience = useCapabilityAudienceLoad( - metadataClient, - formDeclaresWidget(form, 'ref-multi:capability'), - ); + const loadCapabilityAudience = useCapabilityAudienceLoader(metadataClient); const formWidgetContext = React.useMemo( - () => ({ ...widgetContext, capabilityAudience }), - [widgetContext, capabilityAudience], + () => ({ ...widgetContext, loadCapabilityAudience }), + [widgetContext, loadCapabilityAudience], ); /** Shallow-write a curated patch onto the variant. */ diff --git a/ui/packages/app-shell/src/views/metadata-admin/useCapabilityAudienceLoad.ts b/ui/packages/app-shell/src/views/metadata-admin/useCapabilityAudienceLoad.ts deleted file mode 100644 index a8bbd8ebf83..00000000000 --- a/ui/packages/app-shell/src/views/metadata-admin/useCapabilityAudienceLoad.ts +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * Load the audience catalog the `ref-multi:capability` picker offers — the - * capabilities the environment knows, the permission sets granting each and - * the positions holding them (objectstack#34908) — as a {@link LoadState}, so - * a failed read reaches the picker as a failure, not as an empty catalog. - * - * `enabled` false sends no request and answers `idle`: a host passes - * `formDeclaresWidget(form, 'ref-multi:capability')`, so only an editor whose - * form carries the audience row reads the three registries. - */ - -import * as React from 'react'; -import { - loadCapabilityAudience, - type CapabilityAudience, - type CapabilityAudienceSource, -} from '../capabilityAudience.js'; -import { usePickerLoad, type LoadState } from './loadState.js'; - -export function useCapabilityAudienceLoad( - source: CapabilityAudienceSource | null | undefined, - enabled: boolean, -): LoadState { - return usePickerLoad( - React.useMemo( - () => (enabled && source ? () => loadCapabilityAudience(source) : null), - [enabled, source], - ), - ); -} diff --git a/ui/packages/app-shell/src/views/metadata-admin/useCapabilityAudienceLoader.ts b/ui/packages/app-shell/src/views/metadata-admin/useCapabilityAudienceLoader.ts new file mode 100644 index 00000000000..ec1b760c95b --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/useCapabilityAudienceLoader.ts @@ -0,0 +1,26 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The loader of the audience catalog the `ref-multi:capability` picker offers + * — the capabilities the environment knows, the permission sets granting each + * and the positions holding them (objectstack#34908). + * + * A host hands the loader down on {@link WidgetContext}; it does not call it. + * The picker itself reads the three registries, once it is on screen, so an + * editor whose audience row sits in a closed section, or whose form declares + * no such row, sends no request. The loader is stable per source, so the + * picker's read runs once per mount, not once per render. + */ + +import * as React from 'react'; +import { + loadCapabilityAudience, + type CapabilityAudience, + type CapabilityAudienceSource, +} from '../capabilityAudience.js'; + +export function useCapabilityAudienceLoader( + source: CapabilityAudienceSource | null | undefined, +): (() => Promise) | undefined { + return React.useMemo(() => (source ? () => loadCapabilityAudience(source) : undefined), [source]); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx index 8d08f248ebe..e44f0b514c1 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/widgets.tsx @@ -327,9 +327,18 @@ export interface WidgetContext { * The capabilities the environment knows, joined with the permission sets * granting each and the positions holding them — fuels the * `ref-multi:capability` picker of an audience gate (`requiredPermissions` - * on a list view or a dashboard). Absent reads as {@link NOT_ASKED}. + * on a list view or a dashboard). Absent reads as {@link NOT_ASKED}, unless + * {@link WidgetContext.loadCapabilityAudience} is given. */ capabilityAudience?: LoadState; + /** + * Reads {@link WidgetContext.capabilityAudience} when it is not given: the + * `ref-multi:capability` picker calls it once it is on screen, so a host + * whose audience row sits in a closed section sends no request. Keep it + * stable (`useCapabilityAudienceLoader`), or the picker reads again on + * every render. + */ + loadCapabilityAudience?: () => Promise; } /* Stable empties for the arms that have no catalog to offer yet — `idle` and @@ -1118,7 +1127,20 @@ const CAPABILITY_REGISTRY: RefMultiRegistry = { }; function RefMultiCapabilityWidget(props: WidgetProps) { - return ; + const { context } = props; + // The host hands down a loader, not a catalog: read it here, once the row is + // on screen. A catalog the host already holds wins. + const read = usePickerLoad( + context?.capabilityAudience ? null : context?.loadCapabilityAudience ?? null, + ); + const effective = React.useMemo( + () => + context?.capabilityAudience || !context?.loadCapabilityAudience + ? context + : { ...context, capabilityAudience: read }, + [context, read], + ); + return ; } /* -------------------------------------------------------------------------- */ diff --git a/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx b/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx index 928eff436a0..03ffa4f7085 100644 --- a/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx +++ b/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx @@ -20,7 +20,8 @@ * an empty pick writes no key, and no picker leaves the body as before; * - the Studio form widget `ref-multi:capability`: the closed list (no * typed-name box on any arm), each option with its granting sets, and the - * same preview under it. + * same preview under it; it reads the catalog through the host's loader + * once it is on screen, so a closed section sends no request. */ import '@testing-library/jest-dom/vitest'; @@ -314,7 +315,7 @@ describe('useCreateViewInPlace: the picked gate', () => { // --------------------------------------------------------------------------- describe('the view form\'s audience row in Studio', () => { - it('the view form declares the capability picker, so its hosts read the catalog', () => { + it('the view form declares the capability picker', () => { expect(formDeclaresWidget(getViewForm('en'), 'ref-multi:capability')).toBe(true); }); @@ -384,6 +385,44 @@ describe('the view form\'s audience row in Studio', () => { expect(screen.getByTestId('ref-multi-capability')).toHaveTextContent('view_deal_sales'); }); + it('reads the catalog through the host\'s loader only once the row is on screen', async () => { + const load = vi.fn(async () => AUDIENCE); + render( + {}} + widgetContext={{ conditionScope: 'none', loadCapabilityAudience: load }} + />, + ); + await settle(); + // The section is closed: no request. + expect(load).not.toHaveBeenCalled(); + expect(screen.queryByTestId('ref-multi-capability')).toBeNull(); + fireEvent.click(screen.getByText('Access')); + await waitFor(() => + expect(screen.getByTestId('ref-multi-capability-audience').textContent).toContain('销售主管, 业务员'), + ); + expect(load).toHaveBeenCalledTimes(1); + }); + + it('control: a catalog the host already holds is used as given, and the loader is not called', async () => { + const load = vi.fn(async () => AUDIENCE); + render( + {}} + widgetContext={{ conditionScope: 'none', capabilityAudience: { status: 'loaded', data: AUDIENCE }, loadCapabilityAudience: load }} + />, + ); + await settle(); + expect(load).not.toHaveBeenCalled(); + expect(screen.getByTestId('ref-multi-capability-audience').textContent).toContain('销售主管, 业务员'); + }); + it('nothing reachable: the preview no longer promises the object\'s editors', () => { mountRow(AUDIENCE, ['export_reports', 'view_deal_finance']); expect(screen.getByTestId('ref-multi-capability-audience').textContent).toBe( From 9731b21d769043d6b399a68a8089c750376f7b79 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 11:57:33 +0000 Subject: [PATCH 4/5] docs(changeset): the Studio audience row is a closed list, read once it is on screen Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibxDBbvf7dEeutsepbm --- .changeset/34908-view-audience-picker.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/34908-view-audience-picker.md b/.changeset/34908-view-audience-picker.md index 076571af107..de90ca4e0ff 100644 --- a/.changeset/34908-view-audience-picker.md +++ b/.changeset/34908-view-audience-picker.md @@ -12,8 +12,8 @@ Metadata-protocol: none The audience gate is the existing, server-enforced `requiredPermissions` (all of the capabilities listed are required). The console now sets it from a closed list and shows who it reaches; no key, value or gate changes, and nothing is granted from the view (granting stays in Setup). -- **`@object-ui/app-shell`.** The view switcher's in-place create card offers 「Who sees this view」 for a shared view: the capabilities the environment knows (declared, or granted by a permission set), each with the permission sets granting it, and a read-only preview of the positions whose permission sets grant every capability picked. The preview reads each position's sets from the server (`GET /meta/position?include=grants`, the sets the resolver grants its holders), never from a position's raw definition; a list served without them leaves the positions unknown. While a gate is picked, the card says it applies to its creator too. It starts from the open view's gate, which a new shared view used to inherit silently, and the pick replaces it; an empty pick writes no gate. A failed catalog read offers nothing to type. The shared hint no longer says every shared view is seen by everyone who can see the list. In Studio, the view panel's and the dashboard settings' audience row is the new `ref-multi:capability` picker: a closed list (no typed-name box when the catalog is unread, empty or failed), each option with its granting sets, and the same preview under it. -- **`@objectstack/spec`.** The view and dashboard forms' `requiredPermissions` rows declare `widget: 'ref-multi:capability'` (a host with no catalog keeps the typed-name box). The view hint's last sentence now says only what holds on every carrier: the person setting the gate no longer sees the view in the list either. +- **`@object-ui/app-shell`.** The view switcher's in-place create card offers 「Who sees this view」 for a shared view: the capabilities the environment knows (declared, or granted by a permission set), each with the permission sets granting it, and a read-only preview of the positions whose permission sets grant every capability picked. The preview reads each position's sets from the server (`GET /meta/position?include=grants`, the sets the resolver grants its holders), never from a position's raw definition; a list served without them leaves the positions unknown. While a gate is picked, the card says it applies to its creator too. It starts from the open view's gate, which a new shared view used to inherit silently, and the pick replaces it; an empty pick writes no gate. A failed catalog read offers nothing to type. The shared hint no longer says every shared view is seen by everyone who can see the list. In Studio, the view panel's and the dashboard settings' audience row is the new `ref-multi:capability` picker: a closed list (no typed-name box when the catalog is unread, empty or failed), each option with its granting sets, and the same preview under it. The picker reads the catalog once its row is on screen, so an editor whose audience section stays closed sends no request. +- **`@objectstack/spec`.** The view and dashboard forms' `requiredPermissions` rows declare `widget: 'ref-multi:capability'` (the list is closed: a host with no catalog offers nothing to add). The view hint's last sentence now says only what holds on every carrier: the person setting the gate no longer sees the view in the list either. - **`@objectstack/platform-objects`.** The `metadataForms` bundles carry the narrowed view hint (zh-CN, ja-JP and es-ES translated; the other locales the English source). - **`@object-ui/i18n`.** The create card's new strings and the corrected shared hint, in all eleven console locales. From 1782a6175b0091d213cbb1ea27c65a19b6c8b8e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 12:14:33 +0000 Subject: [PATCH 5/5] fix(app-shell): the no-position preview claims no exclusive audience A person holds the union of what each of their positions grants, so a pick no single position grants still lets in the holders of several positions. The preview line (11 console locales, Studio en/zh) now says so, as do the positionsReached docblock and the capabilities recipe; a case pins the two-position union. The failed-catalog line no longer says the view can only be shared with everyone (an inherited gate stays picked), and the loader's docblock no longer mentions a text box. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L9qibxDBbvf7dEeutsepbm --- content/docs/permissions/capabilities.mdx | 5 ++++- .../app-shell/src/views/ViewAudiencePicker.tsx | 8 ++++---- .../app-shell/src/views/capabilityAudience.ts | 9 ++++++--- .../src/views/viewAudience-34908.test.tsx | 14 +++++++++++--- ui/packages/i18n/src/locales/ar.ts | 4 ++-- ui/packages/i18n/src/locales/de.ts | 4 ++-- ui/packages/i18n/src/locales/en.ts | 4 ++-- ui/packages/i18n/src/locales/es.ts | 4 ++-- ui/packages/i18n/src/locales/fr.ts | 4 ++-- ui/packages/i18n/src/locales/ja.ts | 4 ++-- ui/packages/i18n/src/locales/ko.ts | 4 ++-- ui/packages/i18n/src/locales/pt-BR.ts | 4 ++-- ui/packages/i18n/src/locales/ru.ts | 4 ++-- ui/packages/i18n/src/locales/zh-Hans.ts | 4 ++-- ui/packages/i18n/src/locales/zh-Hant.ts | 4 ++-- ui/packages/i18n/src/namespaces/studio/en.ts | 2 +- ui/packages/i18n/src/namespaces/studio/zh.ts | 2 +- 17 files changed, 49 insertions(+), 35 deletions(-) diff --git a/content/docs/permissions/capabilities.mdx b/content/docs/permissions/capabilities.mdx index 3c05b11c8ad..6f555a74631 100644 --- a/content/docs/permissions/capabilities.mdx +++ b/content/docs/permissions/capabilities.mdx @@ -227,7 +227,10 @@ positions whose permission sets grant **every** capability picked. It reads which sets each position grants from the server, the sets the resolver grants its holders, so a position that has been switched off reaches no one. The preview is still advice, and the server stays the authority: it cannot name people who -hold a set directly rather than through a position. +hold a set directly rather than through a position, nor people who hold the +picked capabilities between several positions. A person holds everything each +of their positions grants, so two positions that each grant part of the pick +let their joint holders through. **The gate applies to you too.** Pick a capability you do not hold, and the view diff --git a/ui/packages/app-shell/src/views/ViewAudiencePicker.tsx b/ui/packages/app-shell/src/views/ViewAudiencePicker.tsx index 93766c62510..495fb095026 100644 --- a/ui/packages/app-shell/src/views/ViewAudiencePicker.tsx +++ b/ui/packages/app-shell/src/views/ViewAudiencePicker.tsx @@ -9,8 +9,8 @@ * capabilities the environment knows ({@link CapabilityAudience}), each shown * with the permission sets granting it — so a reader cannot type a name that * matches nothing. There is no free-text fallback: when the catalog cannot be - * read, nothing can be added and the view is shared with everyone (a name - * already picked can still be removed). Under the list it previews, read-only, + * read, nothing can be added (a name already picked, such as the open view's + * gate, stays and can be removed). Under the list it previews, read-only, * which positions the picked set reaches (the sets each position grants in * force, as the server serves them), and says the gate applies to the creator * too. It grants nothing: granting stays in Setup. @@ -52,7 +52,7 @@ export function ViewAudiencePicker({ audience, value, onChange, disabled }: View const reached = positionsReached(value, loaded.positions) ?? []; preview = reached.length === 0 ? t('view.switcher.audienceNoPosition', { - defaultValue: 'No position holds every picked capability: only people granted them directly will see this view', + defaultValue: 'No single position holds every picked capability: only people who hold all of them, directly or through several positions, will see this view', }) : t('view.switcher.audiencePositions', { defaultValue: '{{positions}} will see this view', @@ -95,7 +95,7 @@ export function ViewAudiencePicker({ audience, value, onChange, disabled }: View {audience.status === 'error' ? (

{t('view.switcher.audienceLoadFailed', { - defaultValue: 'The capabilities could not be loaded, so the view can only be shared with everyone: {{message}}', + defaultValue: 'The capabilities could not be loaded, so none can be added: {{message}}', message: audience.message, })}

diff --git a/ui/packages/app-shell/src/views/capabilityAudience.ts b/ui/packages/app-shell/src/views/capabilityAudience.ts index cdb2b336d40..f492ca3e24d 100644 --- a/ui/packages/app-shell/src/views/capabilityAudience.ts +++ b/ui/packages/app-shell/src/views/capabilityAudience.ts @@ -147,8 +147,11 @@ export function buildCapabilityAudience( /** * The positions whose permission sets grant EVERY picked capability — who the - * gate lets in through a position. Empty `picked` is no gate: `null`, which a - * preview reads as "everyone who can see the list". + * gate lets in through one position alone. It is not the whole audience: a + * person's capabilities are the union over every position they hold (and any + * set granted to them directly), so a holder of two positions that each grant + * part of the pick passes the gate too. Empty `picked` is no gate: `null`, + * which a preview reads as "everyone who can see the list". */ export function positionsReached( picked: readonly string[], @@ -165,7 +168,7 @@ export interface CapabilityAudienceSource { /** * Read the three registries and join them. A failed capability or permission - * set read fails the load (the pickers then say so and keep a text box); a + * set read fails the load (the pickers then say so, and offer nothing to add); a * failed position read keeps the catalog and leaves `positions` `null`. */ export async function loadCapabilityAudience(source: CapabilityAudienceSource): Promise { diff --git a/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx b/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx index 03ffa4f7085..3f086d92085 100644 --- a/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx +++ b/ui/packages/app-shell/src/views/viewAudience-34908.test.tsx @@ -210,12 +210,20 @@ describe('the create card: who sees a shared view', () => { expect(onCreate.mock.calls[0][0]).toMatchObject({ scope: 'shared', requiredPermissions: ['view_deal_sales', 'view_deal_finance'] }); }); - it('a pick no position holds says who is left', async () => { + it('a pick no single position holds claims no exclusive audience: two positions together can pass the gate', async () => { + // No one position grants both, but the gate reads the UNION of a person's + // positions: a holder of sales_rep (export_reports) and accountant + // (view_deal_finance) passes with no direct grant at all. + expect(positionsReached(['export_reports', 'view_deal_finance'], AUDIENCE.positions!)).toEqual([]); + const held = new Set( + AUDIENCE.positions!.filter((p) => p.name === 'sales_rep' || p.name === 'accountant').flatMap((p) => p.capabilities), + ); + expect(['export_reports', 'view_deal_finance'].every((c) => held.has(c))).toBe(true); mountCard({ loadAudience: async () => AUDIENCE, initialRequiredPermissions: ['export_reports', 'view_deal_finance'] }); toShared(); await settle(); expect(screen.getByTestId('view-audience-preview').textContent).toBe( - 'No position holds every picked capability: only people granted them directly will see this view', + 'No single position holds every picked capability: only people who hold all of them, directly or through several positions, will see this view', ); }); @@ -426,7 +434,7 @@ describe('the view form\'s audience row in Studio', () => { it('nothing reachable: the preview no longer promises the object\'s editors', () => { mountRow(AUDIENCE, ['export_reports', 'view_deal_finance']); expect(screen.getByTestId('ref-multi-capability-audience').textContent).toBe( - 'No position holds every picked capability: only people granted them directly will see it.', + 'No single position holds every picked capability: only people who hold all of them, directly or through several positions, will see it.', ); }); }); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 773ccc224e7..54d36bd6aee 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1492,12 +1492,12 @@ const ar = { audienceAdd: 'قصر العرض على صلاحية…', audienceAllAdded: 'تمت إضافة كل الصلاحيات', audienceLoading: 'جارٍ تحميل الصلاحيات…', - audienceLoadFailed: 'تعذر تحميل الصلاحيات، لذا لا يمكن مشاركة العرض إلا مع الجميع: {{message}}', + audienceLoadFailed: 'تعذر تحميل الصلاحيات، لذا لا يمكن إضافة أي منها: {{message}}', audienceNone: 'لم تُعرَّف أي صلاحية بعد. تُمنح الصلاحيات في الإعداد عبر مجموعات الأذونات.', audienceGrantedBy: 'تمنحها {{sets}}', audienceRemove: 'إزالة {{name}}', audiencePositions: 'سيرى هذا العرض: {{positions}}', - audienceNoPosition: 'لا يوجد منصب يحمل كل الصلاحيات المختارة: لن يرى هذا العرض إلا من مُنحت لهم مباشرة', + audienceNoPosition: 'لا يوجد منصب واحد يحمل كل الصلاحيات المختارة: لن يرى هذا العرض إلا من يحملها كلها، مباشرة أو عبر عدة مناصب', audienceSelf: 'ينطبق هذا عليك أيضًا: إذا لم تكن تحمل كل الصلاحيات المختارة، فسيختفي العرض من قائمتك أنت أيضًا بعد إنشائه', audiencePositionsUnread: 'تعذرت قراءة المناصب، لذا لا يظهر من سيرى هذا العرض', // objectstack#36409 — a shared view's name already taken, and a view that is gone. diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 013a2fd4af4..c187e481dfb 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1355,12 +1355,12 @@ const de = { audienceAdd: 'Auf eine Berechtigung beschränken…', audienceAllAdded: 'Alle Berechtigungen hinzugefügt', audienceLoading: 'Berechtigungen werden geladen…', - audienceLoadFailed: 'Die Berechtigungen konnten nicht geladen werden, daher kann die Ansicht nur mit allen geteilt werden: {{message}}', + audienceLoadFailed: 'Die Berechtigungen konnten nicht geladen werden, daher kann keine hinzugefügt werden: {{message}}', audienceNone: 'Noch keine Berechtigung definiert. Berechtigungen werden im Setup über Berechtigungssätze vergeben.', audienceGrantedBy: 'Vergeben durch {{sets}}', audienceRemove: '{{name}} entfernen', audiencePositions: '{{positions}} sehen diese Ansicht', - audienceNoPosition: 'Keine Position hat alle gewählten Berechtigungen: Nur direkt Berechtigte sehen diese Ansicht', + audienceNoPosition: 'Keine einzelne Position hat alle gewählten Berechtigungen: Nur wer alle hat, direkt oder über mehrere Positionen, sieht diese Ansicht', audienceSelf: 'Das gilt auch für Sie: Haben Sie nicht alle gewählten Berechtigungen, verschwindet die Ansicht nach dem Erstellen auch aus Ihrer eigenen Liste', audiencePositionsUnread: 'Die Positionen konnten nicht gelesen werden, daher wird nicht angezeigt, wer diese Ansicht sieht', // objectstack#36409 — a shared view's name already taken, and a view that is gone. diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 10f1414cef8..a16318e78b9 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1667,12 +1667,12 @@ const en = { audienceAdd: 'Limit to a capability…', audienceAllAdded: 'All capabilities added', audienceLoading: 'Loading capabilities…', - audienceLoadFailed: 'The capabilities could not be loaded, so the view can only be shared with everyone: {{message}}', + audienceLoadFailed: 'The capabilities could not be loaded, so none can be added: {{message}}', audienceNone: 'No capability is defined yet. Capabilities are granted on permission sets, in Setup.', audienceGrantedBy: 'Granted by {{sets}}', audienceRemove: 'Remove {{name}}', audiencePositions: '{{positions}} will see this view', - audienceNoPosition: 'No position holds every picked capability: only people granted them directly will see this view', + audienceNoPosition: 'No single position holds every picked capability: only people who hold all of them, directly or through several positions, will see this view', audienceSelf: 'This applies to you too: if you do not hold every capability picked, the view leaves your own list once it is created', audiencePositionsUnread: 'The positions could not be read, so who will see this view is not shown', // objectstack#36409 — a shared view's name already taken, and a view that is gone. diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 25ea95bf486..fadc22aa746 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1392,12 +1392,12 @@ const es = { audienceAdd: 'Limitar a un permiso…', audienceAllAdded: 'Todos los permisos añadidos', audienceLoading: 'Cargando permisos…', - audienceLoadFailed: 'No se pudieron cargar los permisos, así que la vista solo puede compartirse con todos: {{message}}', + audienceLoadFailed: 'No se pudieron cargar los permisos, así que no se puede añadir ninguno: {{message}}', audienceNone: 'Aún no hay permisos definidos. Los permisos se conceden en Configuración, en los conjuntos de permisos.', audienceGrantedBy: 'Concedido por {{sets}}', audienceRemove: 'Quitar {{name}}', audiencePositions: '{{positions}} verán esta vista', - audienceNoPosition: 'Ningún puesto tiene todos los permisos elegidos: solo quienes los tengan concedidos directamente verán esta vista', + audienceNoPosition: 'Ningún puesto por sí solo tiene todos los permisos elegidos: solo quienes los tengan todos, directamente o a través de varios puestos, verán esta vista', audienceSelf: 'Esto también le afecta: si no tiene todos los permisos elegidos, la vista desaparecerá de su propia lista una vez creada', audiencePositionsUnread: 'No se pudieron leer los puestos, así que no se muestra quién verá esta vista', // objectstack#36409 — a shared view's name already taken, and a view that is gone. diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 754a50cf66e..21296c8f1e3 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1387,12 +1387,12 @@ const fr = { audienceAdd: 'Limiter à une autorisation…', audienceAllAdded: 'Toutes les autorisations ajoutées', audienceLoading: 'Chargement des autorisations…', - audienceLoadFailed: 'Les autorisations n’ont pas pu être chargées, la vue ne peut donc être partagée qu’avec tout le monde : {{message}}', + audienceLoadFailed: 'Les autorisations n’ont pas pu être chargées, aucune ne peut donc être ajoutée : {{message}}', audienceNone: 'Aucune autorisation n’est encore définie. Les autorisations s’accordent dans Configuration, sur les ensembles d’autorisations.', audienceGrantedBy: 'Accordée par {{sets}}', audienceRemove: 'Retirer {{name}}', audiencePositions: '{{positions}} verront cette vue', - audienceNoPosition: 'Aucun poste ne détient toutes les autorisations choisies : seules les personnes qui les ont reçues directement verront cette vue', + audienceNoPosition: 'Aucun poste ne détient à lui seul toutes les autorisations choisies : seules les personnes qui les détiennent toutes, directement ou via plusieurs postes, verront cette vue', audienceSelf: 'Cela vous concerne aussi : si vous ne détenez pas toutes les autorisations choisies, la vue quitte votre propre liste une fois créée', audiencePositionsUnread: 'Les postes n’ont pas pu être lus, qui verra cette vue n’est donc pas affiché', // objectstack#36409 — a shared view's name already taken, and a view that is gone. diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 40eb8430db0..34b7e0cfe26 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1355,12 +1355,12 @@ const ja = { audienceAdd: '権限の保有者に限定…', audienceAllAdded: 'すべての権限を追加済み', audienceLoading: '権限を読み込み中…', - audienceLoadFailed: '権限を読み込めないため、このビューは全員にのみ共有できます:{{message}}', + audienceLoadFailed: '権限を読み込めないため、追加できません:{{message}}', audienceNone: '権限はまだ定義されていません。権限はセットアップで権限セットに付与します。', audienceGrantedBy: '付与元:{{sets}}', audienceRemove: '{{name}} を削除', audiencePositions: '{{positions}} がこのビューを見られます', - audienceNoPosition: '選択したすべての権限を持つ役職はありません。直接付与された人だけがこのビューを見られます', + audienceNoPosition: '選択したすべての権限を単独で持つ役職はありません。直接、または複数の役職を通じてすべてを持つ人だけがこのビューを見られます', audienceSelf: 'これはあなた自身にも適用されます。選択したすべての権限を持っていない場合、作成後このビューはあなたのリストからも消えます', audiencePositionsUnread: '役職を読み込めないため、このビューを見られる人は表示されません', // objectstack#36409 — a shared view's name already taken, and a view that is gone. diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index a2dd23d27af..b53defa22e0 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1355,12 +1355,12 @@ const ko = { audienceAdd: '권한 보유자로 제한…', audienceAllAdded: '모든 권한이 추가됨', audienceLoading: '권한을 불러오는 중…', - audienceLoadFailed: '권한을 불러올 수 없어 이 보기는 모든 사람에게만 공유할 수 있습니다: {{message}}', + audienceLoadFailed: '권한을 불러올 수 없어 추가할 수 없습니다: {{message}}', audienceNone: '아직 정의된 권한이 없습니다. 권한은 설정에서 권한 집합에 부여합니다.', audienceGrantedBy: '{{sets}}에서 부여', audienceRemove: '{{name}} 제거', audiencePositions: '{{positions}}이(가) 이 보기를 봅니다', - audienceNoPosition: '선택한 모든 권한을 가진 직위가 없습니다. 직접 부여받은 사람만 이 보기를 봅니다', + audienceNoPosition: '선택한 모든 권한을 단독으로 가진 직위가 없습니다. 직접 또는 여러 직위를 통해 모두 가진 사람만 이 보기를 봅니다', audienceSelf: '이는 본인에게도 적용됩니다. 선택한 모든 권한을 갖고 있지 않으면 생성 후 이 보기는 본인 목록에서도 사라집니다', audiencePositionsUnread: '직위를 읽을 수 없어 이 보기를 볼 사람이 표시되지 않습니다', // objectstack#36409 — a shared view's name already taken, and a view that is gone. diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 381320cee51..63658167e53 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1387,12 +1387,12 @@ const pt = { audienceAdd: 'Limitar a uma permissão…', audienceAllAdded: 'Todas as permissões adicionadas', audienceLoading: 'Carregando permissões…', - audienceLoadFailed: 'Não foi possível carregar as permissões, então a visualização só pode ser compartilhada com todos: {{message}}', + audienceLoadFailed: 'Não foi possível carregar as permissões, então nenhuma pode ser adicionada: {{message}}', audienceNone: 'Nenhuma permissão definida ainda. As permissões são concedidas em Configuração, nos conjuntos de permissões.', audienceGrantedBy: 'Concedida por {{sets}}', audienceRemove: 'Remover {{name}}', audiencePositions: '{{positions}} verão esta visualização', - audienceNoPosition: 'Nenhum cargo tem todas as permissões escolhidas: só quem as recebeu diretamente verá esta visualização', + audienceNoPosition: 'Nenhum cargo sozinho tem todas as permissões escolhidas: só quem tiver todas, diretamente ou por vários cargos, verá esta visualização', audienceSelf: 'Isso também vale para você: se você não tiver todas as permissões escolhidas, a visualização sai da sua própria lista depois de criada', audiencePositionsUnread: 'Não foi possível ler os cargos, então não é mostrado quem verá esta visualização', // objectstack#36409 — a shared view's name already taken, and a view that is gone. diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 6b65ee22b6c..5713c283caa 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1425,12 +1425,12 @@ const ru = { audienceAdd: 'Ограничить разрешением…', audienceAllAdded: 'Все разрешения добавлены', audienceLoading: 'Загрузка разрешений…', - audienceLoadFailed: 'Не удалось загрузить разрешения, поэтому представление можно открыть только для всех: {{message}}', + audienceLoadFailed: 'Не удалось загрузить разрешения, поэтому добавить их нельзя: {{message}}', audienceNone: 'Разрешения ещё не определены. Разрешения выдаются в настройках через наборы разрешений.', audienceGrantedBy: 'Выдаётся набором {{sets}}', audienceRemove: 'Удалить {{name}}', audiencePositions: 'Это представление увидят: {{positions}}', - audienceNoPosition: 'Ни одна должность не имеет всех выбранных разрешений: представление увидят только те, кому они выданы напрямую', + audienceNoPosition: 'Ни одна должность сама по себе не имеет всех выбранных разрешений: представление увидят только те, у кого есть все они — напрямую или через несколько должностей', audienceSelf: 'Это касается и вас: если у вас нет всех выбранных разрешений, после создания представление исчезнет и из вашего списка', audiencePositionsUnread: 'Не удалось прочитать должности, поэтому не показано, кто увидит это представление', // objectstack#36409 — a shared view's name already taken, and a view that is gone. diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 11ed11179b2..8641a299123 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1382,12 +1382,12 @@ const zh = { audienceAdd: '限定为持有某项能力的人…', audienceAllAdded: '已添加全部能力', audienceLoading: '正在加载能力…', - audienceLoadFailed: '无法加载能力,此视图只能共享给所有人:{{message}}', + audienceLoadFailed: '无法加载能力,因此无法添加:{{message}}', audienceNone: '尚未定义任何能力。能力在设置中通过权限集授予。', audienceGrantedBy: '由 {{sets}} 授予', audienceRemove: '移除 {{name}}', audiencePositions: '{{positions}} 会看到此视图', - audienceNoPosition: '没有岗位同时持有所选的全部能力:只有被直接授予这些能力的人能看到此视图', + audienceNoPosition: '没有哪个岗位单独持有所选的全部能力:只有直接或通过多个岗位合计持有全部这些能力的人能看到此视图', audienceSelf: '这对你自己同样生效:如果你没有持有所选的全部能力,视图创建后也会从你自己的列表中消失', audiencePositionsUnread: '无法读取岗位,因此不显示谁会看到此视图', // objectstack#36409 — a shared view's name already taken, and a view that is gone. diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 124dc7da13f..84d8f46d812 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1382,12 +1382,12 @@ const zhHant = { audienceAdd: '限定為持有某項能力的人…', audienceAllAdded: '已新增全部能力', audienceLoading: '正在載入能力…', - audienceLoadFailed: '無法載入能力,此檢視只能共享給所有人:{{message}}', + audienceLoadFailed: '無法載入能力,因此無法新增:{{message}}', audienceNone: '尚未定義任何能力。能力在設定中通過權限集授予。', audienceGrantedBy: '由 {{sets}} 授予', audienceRemove: '移除 {{name}}', audiencePositions: '{{positions}} 會看到此檢視', - audienceNoPosition: '沒有崗位同時持有所選的全部能力:只有被直接授予這些能力的人能看到此檢視', + audienceNoPosition: '沒有哪個崗位單獨持有所選的全部能力:只有直接或通過多個崗位合計持有全部這些能力的人能看到此檢視', audienceSelf: '這對你自己同樣生效:如果你沒有持有所選的全部能力,檢視建立後也會從你自己的列表中消失', audiencePositionsUnread: '無法讀取崗位,因此不顯示誰會看到此檢視', // objectstack#36409 — a shared view's name already taken, and a view that is gone. diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index 50718465788..4a968fab2d9 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -1862,7 +1862,7 @@ const STUDIO_EN: Record = { 'engine.form.allCapabilitiesAdded': 'All capabilities added', 'engine.form.audienceEveryone': 'No capability picked: everyone who can see the list sees it.', 'engine.form.audiencePositions': 'Positions that will see it: {positions}.', - 'engine.form.audienceNoPosition': 'No position holds every picked capability: only people granted them directly will see it.', + 'engine.form.audienceNoPosition': 'No single position holds every picked capability: only people who hold all of them, directly or through several positions, will see it.', 'engine.form.capabilityGrantedBy': 'Granted by {sets}', 'engine.form.capabilitiesUnread': 'The capability list is not available here, so none can be added.', 'engine.form.capabilitiesNone': 'No capability is defined yet. Capabilities are granted on permission sets, in Setup.', diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index e95d9c6cbcd..de7633a9df4 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -1649,7 +1649,7 @@ const STUDIO_ZH: Record = { 'engine.form.allCapabilitiesAdded': '已添加全部能力', 'engine.form.audienceEveryone': '未选能力:能看到该列表的人都能看到。', 'engine.form.audiencePositions': '会看到的岗位:{positions}。', - 'engine.form.audienceNoPosition': '没有岗位同时持有所选的全部能力:只有被直接授予这些能力的人能看到。', + 'engine.form.audienceNoPosition': '没有哪个岗位单独持有所选的全部能力:只有直接或通过多个岗位合计持有全部这些能力的人能看到。', 'engine.form.capabilityGrantedBy': '由 {sets} 授予', 'engine.form.capabilitiesUnread': '此处读取不到能力列表,无法添加。', 'engine.form.capabilitiesNone': '尚未定义任何能力。能力在设置中通过权限集授予。',