From 2e9a26395b6bac4d0ee46225611febc920bb0d43 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 15:30:22 +0000 Subject: [PATCH 1/8] feat(ui): a record page's related tab is the child object's full list The related tab draws the list page's condition row (Sort, Filter) through the new list-conditions block, the list page's grid with the column menu, cell editing, selection with the bulk bar and the whole-set footer row, and loads rows as the page scrolls. What the reader changes lasts while they stay on the record; Discard puts the tab back and is the list page's button. The tab no longer remembers its header sort or stores column widths in the reader's record-page preference; widths live in the browser as on the list. The list page's condition-field rules are shared with the new block. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgTKEPqtmiK9SGpHsmW --- .changeset/35892-related-tab-full-list.md | 25 + ui/apps/console/src/register-plugins.ts | 6 + .../app-shell/src/views/ListDraftActions.tsx | 32 +- ui/packages/core/src/index.ts | 1 + .../core/src/utils/column-sortability.ts | 16 + ui/packages/i18n/src/locales/ar.ts | 6 + ui/packages/i18n/src/locales/de.ts | 6 + ui/packages/i18n/src/locales/en.ts | 6 + ui/packages/i18n/src/locales/es.ts | 6 + ui/packages/i18n/src/locales/fr.ts | 6 + ui/packages/i18n/src/locales/ja.ts | 6 + ui/packages/i18n/src/locales/ko.ts | 6 + ui/packages/i18n/src/locales/pt-BR.ts | 6 + ui/packages/i18n/src/locales/ru.ts | 6 + ui/packages/i18n/src/locales/zh-Hans.ts | 6 + ui/packages/i18n/src/locales/zh-Hant.ts | 6 + ui/packages/plugin-detail/README.md | 19 + ui/packages/plugin-detail/src/RelatedList.tsx | 467 +++++++++++++++--- ...elatedList.enlargedListGrid-28865.test.tsx | 66 ++- ...RelatedList.enlargedToolbar-27524.test.tsx | 54 +- .../__tests__/RelatedList.tab-35892.test.tsx | 224 +++++++++ .../relatedTabConditions-35892.test.ts | 63 +++ .../plugin-detail/src/relatedTabConditions.ts | 140 ++++++ .../plugin-detail/src/useDetailTranslation.ts | 4 + ui/packages/plugin-list/README.md | 29 ++ ui/packages/plugin-list/src/ListView.tsx | 326 +++++++----- .../src/conditions/ListConditionControls.tsx | 92 +++- .../src/conditions/ListConditionsBlock.tsx | 202 ++++++++ .../ListConditionsBlock-35892.test.tsx | 109 ++++ .../src/conditions/conditionTranslations.ts | 2 + ui/packages/plugin-list/src/index.tsx | 16 + 31 files changed, 1672 insertions(+), 287 deletions(-) create mode 100644 .changeset/35892-related-tab-full-list.md create mode 100644 ui/packages/plugin-detail/src/__tests__/RelatedList.tab-35892.test.tsx create mode 100644 ui/packages/plugin-detail/src/__tests__/relatedTabConditions-35892.test.ts create mode 100644 ui/packages/plugin-detail/src/relatedTabConditions.ts create mode 100644 ui/packages/plugin-list/src/conditions/ListConditionsBlock.tsx create mode 100644 ui/packages/plugin-list/src/conditions/__tests__/ListConditionsBlock-35892.test.tsx diff --git a/.changeset/35892-related-tab-full-list.md b/.changeset/35892-related-tab-full-list.md new file mode 100644 index 00000000000..60b45083dee --- /dev/null +++ b/.changeset/35892-related-tab-full-list.md @@ -0,0 +1,25 @@ +--- +'@object-ui/core': patch +'@object-ui/i18n': patch +'@object-ui/plugin-list': patch +'@object-ui/plugin-detail': patch +'@object-ui/app-shell': patch +--- + +feat(ui): a record page's related tab is the child object's full list + +Clause-②: yes (widening) — a new registry component `list-conditions` (`@object-ui/plugin-list`, host props only, no node keys) and its exported `ListConditionsHostProps`; new exports `ConditionDiscardButton` (`@object-ui/plugin-list`) and `withHeaderSortPick` (`@object-ui/core`); new i18n keys in every `@object-ui/i18n` locale pack (`listConditions.chips.discard`, `listConditions.chips.discardHint`, `detail.relatedNoMatches`, `detail.deleteRowsTitle`, `detail.deleteRowsConfirmation`); nothing removed or renamed +Metadata-protocol: none + +On a record page, a related list opened as its own tab now works like the object's list page: + +- The first row names the child list (its tile and title) on the left and keeps **+ Add** on the right. The **Open in list** button is gone. +- The second row is the list page's own condition row: **Sort** (several levels) and **Filter**, with no view switch, view settings or search. On a narrow tab or in the drawer their labels fold to icons. +- The table is the list page's grid: the column menu, cell editing as on the list page wherever the reader may edit the child object, row selection with the floating bulk bar (bulk delete asks once), and the footer row, whose calculations cover every matching row, not just the loaded ones. A tab grouped by status draws no footer row. +- Rows load as the page scrolls instead of in pages. +- The tab title still counts every child; the footer counts the rows the filter keeps. +- What the reader changes (sort, filter, footer calculations) lasts while they stay on the record, across its tabs and between its page and its drawer, and is gone after a reload or on another record. **Discard** appears once something changed and puts the tab back; there is no Save. The list page's Discard and this one are one button. + +Upgrade note: the header sort and the column widths and order that an earlier version remembered for a related tab in a reader's record-page preference (`sys_user_preference`) no longer apply: the tab opens in its declared order, and its column widths and order are now kept in the reader's browser, as the list page's are, so they start from the default once. Nothing stored is deleted. The default sort and columns of every related list are unchanged. + +`@object-ui/core` adds `withHeaderSortPick`, the list page's rule for how a header sort joins an existing multi-level sort, now shared with the related tab. `@object-ui/app-shell`'s list Discard is drawn by `ConditionDiscardButton`; it looks and behaves as before. diff --git a/ui/apps/console/src/register-plugins.ts b/ui/apps/console/src/register-plugins.ts index 8d40edc09f7..bc0a46c056e 100644 --- a/ui/apps/console/src/register-plugins.ts +++ b/ui/apps/console/src/register-plugins.ts @@ -56,6 +56,12 @@ ComponentRegistry.registerLazy('object-gallery', () => import('@object-ui/plugin namespace: 'plugin-list', category: 'view', }); +// objectstack#35892 — the list page's condition row, for the record page's +// related tab (`plugin-detail`, which cannot import this package). +ComponentRegistry.registerLazy('list-conditions', () => import('@object-ui/plugin-list'), { + namespace: 'plugin-list', + category: 'Views', +}); // The form and the object view: the shell takes their pure helpers from the // side-effect-free `/core` subpaths and draws their components behind diff --git a/ui/packages/app-shell/src/views/ListDraftActions.tsx b/ui/packages/app-shell/src/views/ListDraftActions.tsx index 19ed7239239..256d299cdfd 100644 --- a/ui/packages/app-shell/src/views/ListDraftActions.tsx +++ b/ui/packages/app-shell/src/views/ListDraftActions.tsx @@ -31,7 +31,7 @@ import { cn, } from '@object-ui/components'; import { useObjectTranslation } from '@object-ui/i18n'; -import type { ListViewProps } from '@object-ui/plugin-list'; +import { ConditionDiscardButton, type ListViewProps } from '@object-ui/plugin-list'; import { ChevronDown, CopyPlus, RotateCcw, Save } from 'lucide-react'; /** One part of a list that can differ from its view (`ListView`'s vocabulary). */ @@ -112,18 +112,13 @@ export function ListDraftActions({ return ( {/* The wide face: Discard beside Save ▾. */} - + className="hidden @[40rem]/list:inline-flex" + onDiscard={onDiscard} + /> {offersSave ? ( @@ -169,18 +164,13 @@ export function ListDraftActions({ ) : ( - + className="inline-flex @[40rem]/list:hidden" + onDiscard={onDiscard} + /> )} ); diff --git a/ui/packages/core/src/index.ts b/ui/packages/core/src/index.ts index 867ff827211..6cb712eaa9f 100644 --- a/ui/packages/core/src/index.ts +++ b/ui/packages/core/src/index.ts @@ -98,6 +98,7 @@ export { readObjectSortability, isPlatformSortableField, filterPlatformSortableSort, + withHeaderSortPick, } from './utils/column-sortability.js'; // [objectstack#27504] The served packaged-action activation: which declared // actions the installation switched off, stamped by the data layer and asked diff --git a/ui/packages/core/src/utils/column-sortability.ts b/ui/packages/core/src/utils/column-sortability.ts index f414501d9bd..1805cb6606d 100644 --- a/ui/packages/core/src/utils/column-sortability.ts +++ b/ui/packages/core/src/utils/column-sortability.ts @@ -225,3 +225,19 @@ export function filterPlatformSortableSort( if (!Array.isArray(sort)) return []; return sort.filter((item) => isPlatformSortableField(sortability, item?.field)); } + +/** + * A column-header sort pick laid over the sort in force (objectstack#35876): + * the header menu hands back the ONE column the reader picked. With no sort + * or a single level, that column replaces the sort. With two levels or more it + * becomes the first level and every other level keeps its place after it; a + * column already in the sort moves up and takes the picked direction. No level + * is dropped. Shared by every host that draws the header menu over its own + * sort (the list page, a record page's related tab), so one click means one + * thing on both. + */ +export function withHeaderSortPick(current: readonly T[], picked: readonly T[]): T[] { + return picked.length === 1 && current.length >= 2 + ? [picked[0], ...current.filter((s) => s.field !== picked[0].field)] + : [...picked]; +} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 56b6567f5cb..1c12fa8a438 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1813,6 +1813,10 @@ const ar = { deleteRow: "حذف", deleteRowConfirmation: "حذف “{{name}}”؟", deleteRowTitle: "حذف السجل", + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: "لا توجد سجلات تطابق عامل التصفية", + deleteRowsTitle: "حذف السجلات المحددة", + deleteRowsConfirmation: "المحدد: {{count}}. لا يمكن التراجع عن ذلك.", actions: "الإجراءات", previousPage: "السابق", nextPage: "التالي", @@ -5670,6 +5674,8 @@ const ar = { sortedBy: "مرتب حسب {{field}}", reset: 'إعادة تعيين', resetHint: 'العودة إلى طريقة العرض المحفوظة', + discard: 'تجاهل', + discardHint: 'العودة إلى الفرز والتصفية الافتراضيين', remove: 'إزالة {{label}}', toggleSort: 'عكس {{label}}', dragSort: 'اسحب لتغيير أولوية الفرز', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index c347cc22840..5d4c13930f4 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1606,6 +1606,10 @@ const de = { deleteRow: "Löschen", deleteRowConfirmation: "Möchten Sie „{{name}}“ wirklich löschen?", deleteRowTitle: "Datensatz löschen", + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: "Keine Datensätze entsprechen dem Filter", + deleteRowsTitle: "Ausgewählte Datensätze löschen", + deleteRowsConfirmation: "Ausgewählt: {{count}}. Dies kann nicht rückgängig gemacht werden.", actions: "Aktionen", previousPage: "Zurück", nextPage: "Weiter", @@ -5072,6 +5076,8 @@ const de = { sortedBy: "Sortiert nach {{field}}", reset: 'Zurücksetzen', resetHint: 'Zurück zur gespeicherten Ansicht', + discard: 'Verwerfen', + discardHint: 'Zurück zur Standardsortierung und zum Standardfilter', remove: '{{label}} entfernen', toggleSort: '{{label}} umkehren', dragSort: 'Ziehen, um die Sortierpriorität zu ändern', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 20e3f55ac33..4048a99273a 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1827,6 +1827,10 @@ const en = { deleteRow: 'Delete', deleteRowConfirmation: 'Are you sure you want to delete "{{name}}"?', deleteRowTitle: 'Delete record', + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: 'No records match the filter', + deleteRowsTitle: 'Delete selected records', + deleteRowsConfirmation: 'Selected: {{count}}. This cannot be undone.', actions: 'Actions', previousPage: 'Previous', nextPage: 'Next', @@ -5832,6 +5836,8 @@ const en = { sortedBy: 'Sorted by {{field}}', reset: 'Reset', resetHint: 'Back to the view as saved', + discard: 'Discard', + discardHint: 'Back to the default sort and filter', remove: 'Remove {{label}}', toggleSort: 'Reverse {{label}}', dragSort: 'Drag to change the sort priority', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 5a9c2d0003c..225c5741da5 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1659,6 +1659,10 @@ const es = { deleteRow: "Eliminar", deleteRowConfirmation: "¿Eliminar “{{name}}”?", deleteRowTitle: "Eliminar registro", + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: "Ningún registro coincide con el filtro", + deleteRowsTitle: "Eliminar los registros seleccionados", + deleteRowsConfirmation: "Seleccionados: {{count}}. Esto no se puede deshacer.", actions: "Acciones", previousPage: "Anterior", nextPage: "Siguiente", @@ -5222,6 +5226,8 @@ const es = { sortedBy: "Ordenado por {{field}}", reset: 'Restablecer', resetHint: 'Volver a la vista guardada', + discard: 'Descartar', + discardHint: 'Volver al orden y filtro predeterminados', remove: 'Quitar {{label}}', toggleSort: 'Invertir {{label}}', dragSort: 'Arrastra para cambiar la prioridad del orden', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index efaebb7ac85..bf370959525 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1656,6 +1656,10 @@ const fr = { deleteRow: "Supprimer", deleteRowConfirmation: "Supprimer « {{name}} » ?", deleteRowTitle: "Supprimer l'enregistrement", + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: "Aucun enregistrement ne correspond au filtre", + deleteRowsTitle: "Supprimer les enregistrements sélectionnés", + deleteRowsConfirmation: "Sélectionnés : {{count}}. Cette action est irréversible.", actions: "Actions", previousPage: "Précédent", nextPage: "Suivant", @@ -5218,6 +5222,8 @@ const fr = { sortedBy: "Trié par {{field}}", reset: 'Réinitialiser', resetHint: 'Revenir à la vue enregistrée', + discard: 'Abandonner', + discardHint: 'Revenir au tri et au filtre par défaut', remove: 'Retirer {{label}}', toggleSort: 'Inverser {{label}}', dragSort: 'Faire glisser pour changer la priorité du tri', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 38dcdc76b67..079bf7447c7 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1614,6 +1614,10 @@ const ja = { history: "履歴", historyEmpty: "履歴はまだありません", deleteRowTitle: "レコードを削除", + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: "フィルターに一致するレコードはありません", + deleteRowsTitle: "選択したレコードを削除", + deleteRowsConfirmation: "選択中: {{count}} 件。この操作は元に戻せません。", createdBy: "作成者", updatedBy: "更新者", created: "作成", @@ -5074,6 +5078,8 @@ const ja = { sortedBy: "{{field}} で並べ替え", reset: 'リセット', resetHint: '保存されたビューに戻す', + discard: '破棄', + discardHint: '既定の並べ替えと絞り込みに戻す', remove: '{{label}}を削除', toggleSort: '{{label}}を反転', dragSort: 'ドラッグして並べ替えの優先順位を変更', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index b0102e0d9fd..79c4199edea 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1606,6 +1606,10 @@ const ko = { deleteRow: "삭제", deleteRowConfirmation: "“{{name}}”을(를) 삭제하시겠습니까?", deleteRowTitle: "레코드 삭제", + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: "필터와 일치하는 레코드가 없습니다", + deleteRowsTitle: "선택한 레코드 삭제", + deleteRowsConfirmation: "선택됨: {{count}}개. 이 작업은 되돌릴 수 없습니다.", actions: "작업", previousPage: "이전", nextPage: "다음", @@ -5071,6 +5075,8 @@ const ko = { sortedBy: "{{field}} 기준 정렬", reset: '초기화', resetHint: '저장된 보기로 돌아가기', + discard: '변경 취소', + discardHint: '기본 정렬과 필터로 돌아가기', remove: '{{label}} 제거', toggleSort: '{{label}} 방향 바꾸기', dragSort: '드래그하여 정렬 우선순위 변경', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 652138d24cf..c2fbaf057c3 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1656,6 +1656,10 @@ const pt = { deleteRow: "Excluir", deleteRowConfirmation: "Excluir “{{name}}”?", deleteRowTitle: "Excluir registro", + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: "Nenhum registro corresponde ao filtro", + deleteRowsTitle: "Excluir registros selecionados", + deleteRowsConfirmation: "Selecionados: {{count}}. Esta ação não pode ser desfeita.", actions: "Ações", previousPage: "Anterior", nextPage: "Próximo", @@ -5217,6 +5221,8 @@ const pt = { sortedBy: "Ordenado por {{field}}", reset: 'Redefinir', resetHint: 'Voltar à visualização salva', + discard: 'Descartar', + discardHint: 'Voltar à ordenação e ao filtro padrão', remove: 'Remover {{label}}', toggleSort: 'Inverter {{label}}', dragSort: 'Arraste para mudar a prioridade da ordenação', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 39a945a76a0..0253845dee6 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1721,6 +1721,10 @@ const ru = { history: "История", historyEmpty: "Истории пока нет", deleteRowTitle: "Удалить запись", + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: "Нет записей, соответствующих фильтру", + deleteRowsTitle: "Удалить выбранные записи", + deleteRowsConfirmation: "Выбрано: {{count}}. Это действие нельзя отменить.", createdBy: "Создано", updatedBy: "Обновлено", // objectui#3863 — base key, answering only a call made without a count: since @@ -5381,6 +5385,8 @@ const ru = { sortedBy: "Сортировка: {{field}}", reset: 'Сбросить', resetHint: 'Вернуться к сохранённому представлению', + discard: 'Отменить', + discardHint: 'Вернуться к сортировке и фильтру по умолчанию', remove: 'Удалить {{label}}', toggleSort: 'Обратить {{label}}', dragSort: 'Перетащите, чтобы изменить приоритет сортировки', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index a35f4da21ce..8606d331936 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1527,6 +1527,10 @@ const zh = { deleteRow: '删除', deleteRowConfirmation: '确定要删除“{{name}}”吗?', deleteRowTitle: '删除记录', + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: '没有符合筛选条件的记录', + deleteRowsTitle: '删除选中的记录', + deleteRowsConfirmation: '已选 {{count}} 条,删除后无法恢复。', actions: '操作', previousPage: '上一页', nextPage: '下一页', @@ -5131,6 +5135,8 @@ const zh = { sortedBy: '按 {{field}} 排序', reset: '重置', resetHint: '回到视图保存的状态', + discard: '放弃', + discardHint: '回到默认的排序和筛选', remove: '删除{{label}}', toggleSort: '切换{{label}}', dragSort: '拖动以调整排序优先级', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index b2cb363edd2..1d8dd02f16e 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1527,6 +1527,10 @@ const zhHant = { deleteRow: '刪除', deleteRowConfirmation: '確定要刪除“{{name}}”嗎?', deleteRowTitle: '刪除記錄', + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: '沒有符合篩選條件的記錄', + deleteRowsTitle: '刪除選中的記錄', + deleteRowsConfirmation: '已選 {{count}} 條,刪除後無法恢復。', actions: '操作', previousPage: '上一頁', nextPage: '下一頁', @@ -5131,6 +5135,8 @@ const zhHant = { sortedBy: '按 {{field}} 排序', reset: '重置', resetHint: '回到檢視儲存的狀態', + discard: '放棄', + discardHint: '回到預設的排序和篩選', remove: '刪除{{label}}', toggleSort: '切換{{label}}', dragSort: '拖動以調整排序優先順序', diff --git a/ui/packages/plugin-detail/README.md b/ui/packages/plugin-detail/README.md index 2ab07af1183..d175fc2b9e3 100644 --- a/ui/packages/plugin-detail/README.md +++ b/ui/packages/plugin-detail/README.md @@ -720,6 +720,25 @@ declared filter is refused with a console explanation rather than dropped — answering with more rows than the metadata asked for is the failure this key's wiring exists to remove. +On the record page, a related list opened as its own **tab** is the child +object's full list (objectstack#35892). Its first row is the list's tile and +name on the left and **+ Add** on the right; its second row is the list page's +own condition row (`plugin-list` registers it as `list-conditions`, since that +package depends on this one): **Sort** and **Filter**, with no view switch, no +view settings and no search. The table is the list page's grid: the column +menu, cell editing where the reader may edit the child object, row selection +with the floating bulk bar, and the footer row, whose calculations cover every +matching row. Rows load as the page scrolls; there is no pager and no "Open in +list". The tab title counts every child; the footer counts the rows the filter +keeps. Whatever the reader changes there (sort, filter, footer calculations) +lasts while they stay on the record, across its tabs and its drawer, and is +gone after a reload or on another record. **Discard** appears once something +changed and puts the tab back; nothing is saved. Column widths and order are +kept by the grid in the reader's browser, as on the list page. A header sort, +column widths or order that an earlier version remembered in the reader's +record-page preference no longer apply. A tab whose child object is grouped +by status draws no footer row. + The **Add** affordance renders only where every link in its chain is available: a spec-valid `add.picker.object` *and* a `dataSource`. The picker dialog and the add callback both required the adapter already, so without it the button used to diff --git a/ui/packages/plugin-detail/src/RelatedList.tsx b/ui/packages/plugin-detail/src/RelatedList.tsx index bb02e17d125..8f31b2c2f87 100644 --- a/ui/packages/plugin-detail/src/RelatedList.tsx +++ b/ui/packages/plugin-detail/src/RelatedList.tsx @@ -48,7 +48,7 @@ import { Maximize2, } from 'lucide-react'; import type { LucideIcon } from 'lucide-react'; -import type { DataSource, FieldMetadata } from '@object-ui/types'; +import type { DataSource, DeclaredNode, FieldMetadata } from '@object-ui/types'; import type { ViewFilterElement } from '@objectstack/spec/ui'; import { getCellRenderer, resolveCellRendererType, RecordPickerDialog, deriveLookupColumns, MaskedCellRenderer, RecordHoverCard, formatCurrency } from '@object-ui/fields'; import { @@ -85,6 +85,8 @@ import { type ActionDef, type ActionResult, type FilterNode, + withHeaderSortPick, + ComponentRegistry, } from '@object-ui/core'; import { useSafeFieldLabel, useRecordContext, useRecordPagePreferences, type RelatedListPreference } from '@object-ui/react'; import { usePermissions } from '@object-ui/permissions'; @@ -104,6 +106,7 @@ import { useSeenOnce, } from './relatedListCompact'; import { relatedCardId } from './synth/relatedArrangement'; +import { relatedTabConditionsChanged, useRelatedTabConditions } from './relatedTabConditions'; import { RelatedCardMenu, RelatedPanelHandle } from './RelatedCardMenu'; import { detectStatusField } from '@object-ui/types'; @@ -1201,6 +1204,22 @@ export function statusGroupsOf( ].filter((g) => g.rows.length > 0); } +/** + * objectstack#35892 — the related tab's columns, with the footer calculations + * the reader picked: as field names while there is none (the node it always + * sent), as `{ field, summary }` once there is (`null` = None, no summary). + */ +export function tabSummaryColumns( + fields: readonly string[], + summaries: Readonly> | undefined, +): string[] | Array<{ field: string; summary?: unknown }> { + if (!summaries || Object.keys(summaries).length === 0) return [...fields]; + return fields.map((field) => { + const pick = summaries[field]; + return pick ? { field, summary: pick } : { field }; + }); +} + /** The groups of `statusGroupsOf`, each collapsible under its header. */ const RelatedStatusGroups: React.FC<{ groups: readonly RelatedStatusGroup[]; @@ -1241,6 +1260,75 @@ const RelatedStatusGroups: React.FC<{ ); }; +/** + * objectstack#35892 F1 — whether the related tab reads and writes the header + * sort the reader's record-page preferences remember (objectstack#35601). + * `false`: the card's rule, a sort holds for this visit to the record only, + * as the tab's filter and footer calculations do (`./relatedTabConditions`). + * The one place that decides it: `true` makes the remembered sort the tab's + * starting order again and writes a header sort back to it. + */ +const RELATED_TAB_REMEMBERS_SORT = false; + +/** + * objectstack#35892 — whether the related tab's column widths and order go to + * the reader's record-page preferences (objectstack#35601, on the server). + * `false`: the grid keeps them in this browser, as the list page does + * (objectstack#35955). The one place that decides it. + */ +const RELATED_TAB_COLUMNS_IN_PREFERENCES = false; + +/** + * objectstack#35892 — the rows the related tab reads per step as the reader + * scrolls: the first window, and each one after it. At least the list's own + * page size. + */ +export const RELATED_TAB_WINDOW = 50; + +/** + * The condition row `plugin-list` registers (objectstack#35892); one node, so + * its identity never changes. Not an authored type (no page declares it, it + * reads only host props), so no `DeclaredNode` arm names it: the cast says + * this node is the host's, never a page's. + */ +const LIST_CONDITIONS_NODE = { type: 'list-conditions' } as unknown as DeclaredNode; + +/** How far below the view the next window is asked for, as the list page asks (`LOAD_MORE_THRESHOLD_PX`). */ +const RELATED_TAB_LOAD_AHEAD = '320px'; + +/** + * objectstack#35892 — the end of the related tab's rows: in view (or within + * {@link RELATED_TAB_LOAD_AHEAD} of it), it asks for the next window. The + * record page scrolls as a whole, so the tab loads as the page does, with no + * scroll box of its own. Says 「加载中…」 while a window is on its way. + */ +const RelatedTabLoadMore: React.FC<{ loading: boolean; onLoadMore: () => void; label: string }> = ({ + loading, + onLoadMore, + label, +}) => { + const [end, setEnd] = React.useState(null); + const latest = React.useRef({ loading, onLoadMore }); + latest.current = { loading, onLoadMore }; + React.useEffect(() => { + if (!end || typeof IntersectionObserver === 'undefined') return undefined; + const observer = new IntersectionObserver( + (entries) => { + if (entries.some((entry) => entry.isIntersecting) && !latest.current.loading) latest.current.onLoadMore(); + }, + { rootMargin: `0px 0px ${RELATED_TAB_LOAD_AHEAD} 0px` }, + ); + observer.observe(end); + return () => observer.disconnect(); + // Re-observed after each window lands, so an end still in view asks again. + }, [end, loading]); + return ( +
+ {loading ? label : null} +
+ ); +}; + export const RelatedList: React.FC = ({ title, type, @@ -1294,6 +1382,8 @@ export const RelatedList: React.FC = ({ // `hasMore` keeps "Next" usable when a non-conforming backend omits `total`. const [total, setTotal] = React.useState(null); const [hasMore, setHasMore] = React.useState(false); + // objectstack#35892 — the query behind the related tab's rows (set by the read). + const [tabFindParams, setTabFindParams] = React.useState | undefined>(undefined); /** * The child object's definition, and whether the read for THIS `api` has * SETTLED: one piece of state, through the shared hook (objectui#10690). @@ -1457,14 +1547,50 @@ export const RelatedList: React.FC = ({ ); // The remembered sort applies once, when it is first read; a header click // after that is the reader's and is written back. + // The tab's column widths and order, read and written here alone. Kept by + // the grid itself in this browser, under the node's `id` + // (`related-`), as the list page keeps its own + // (objectstack#35892, objectstack#35955); no longer in the record-page + // preference (`RELATED_TAB_COLUMNS_IN_PREFERENCES`). + const tabColumnState = RELATED_TAB_COLUMNS_IN_PREFERENCES ? storedListPreference?.columnState : undefined; + const writeTabColumnState = React.useMemo( + () => (RELATED_TAB_COLUMNS_IN_PREFERENCES && preferenceKey + ? (columnState: RelatedListPreference['columnState']) => writeListPreference({ columnState }) + : undefined), + [preferenceKey, writeListPreference], + ); const storedSortApplied = React.useRef(false); - const storedSort = storedListPreference?.sort; + const storedSort = RELATED_TAB_REMEMBERS_SORT ? storedListPreference?.sort : undefined; React.useEffect(() => { if (storedSortApplied.current || !storedSort) return; storedSortApplied.current = true; setSortField(storedSort.field); setSortDirection(storedSort.order); }, [storedSort]); + // objectstack#35892 — the related tab is the child object's full list: the + // list page's condition row (sort and filter), its column menu, cell + // editing, selection and footer calculations, over the rows this list + // reads. What the reader changes there holds while they stay on this record + // (another tab, or the record's drawer, keeps it) and is gone on a reload or + // another record; 「Discard」 clears it (`./relatedTabConditions`). Keyed by + // the parent record and this list's relationship. + const tabRecord = enlargedFace && !schema && (type === 'grid' || type === 'table') + && ownRelationshipId && parentId !== undefined && parentId !== null && parentId !== '' + ? `${preferenceObject ?? ''}:${String(parentId)}` + : null; + const tabList = tabRecord !== null; + const { + conditions: tabConditions, + patch: patchTabConditions, + discard: discardTabConditions, + } = useRelatedTabConditions(tabRecord, tabList ? ownRelationshipId : null); + const tabChanged = tabList && relatedTabConditionsChanged(tabConditions); + // Registered by `plugin-list`, which this package cannot import (it depends + // on this one): without it the tab draws no condition row. + const listConditionsRegistered = ComponentRegistry.has('list-conditions') || ComponentRegistry.hasLazy('list-conditions'); + // The filter the reader set on the tab, ANDed with the list's own scope. + const tabFilterNode = tabList ? tabConditions.filterNode : undefined; + const tabFilterKey = tabFilterNode === undefined ? null : JSON.stringify(tabFilterNode); // objectstack#35597 — a body table shows its first `pageSize` rows (ten by // default, the page may say otherwise) and 「显示全部 N 条」 expands it in // place: every row, one read, no pages. N is the server's count when the @@ -1476,7 +1602,10 @@ export const RelatedList: React.FC = ({ ? COMPACT_RELATED_ROWS : bodyTable && bodyTableShowAll && pagedSize > 0 ? (total != null ? Math.max(pagedSize, total) : 0) - : pagedSize; + // objectstack#35892 — the tab reads window by window as it scrolls. + : tabList && pagedSize > 0 + ? Math.max(pagedSize, RELATED_TAB_WINDOW) + : pagedSize; // The built-in contains-filter is a CLIENT-side sweep over the list's // unmasked columns (objectui#10728, `unmaskedColumnKeysKey`) — inexpressible // as a generic server filter. While the user is typing in it @@ -1499,8 +1628,25 @@ export const RelatedList: React.FC = ({ // doesn't re-run (and re-download the full collection) on page clicks or // column sorts that the client pipeline already handles in memory. const fetchPage = windowed ? currentPage : 0; - const fetchSortField = windowed ? sortField : null; - const fetchSortDirection = windowed ? sortDirection : 'asc'; + // The reader's sort: the related tab's levels (objectstack#35892), else the + // header's one field; `null` = the list's declared order. + const tabSort = tabList && tabConditions.sort.length > 0 ? tabConditions.sort : null; + const sortSpec = React.useMemo( + (): Array<{ field: string; order: 'asc' | 'desc' }> | null => + tabSort + ? tabSort.map((item) => ({ field: item.field, order: item.order === 'desc' ? 'desc' : 'asc' })) + : sortField + ? [{ field: sortField, order: sortDirection }] + : null, + [tabSort, sortField, sortDirection], + ); + const sortKey = sortSpec ? JSON.stringify(sortSpec) : null; + const fetchSortSpec = windowed ? sortSpec : null; + const fetchSortKey = windowed ? sortKey : null; + // objectstack#35892 — the tab grows ONE window from the first row as it + // scrolls (`$top` = every row loaded, `$skip` 0), so a re-read after an + // edit, a delete or an add answers every row on screen, in order. + const tabGrows = tabList && windowed; // Key the memo on content, not identity — inline `sort` arrays from schema // nodes would otherwise re-trigger the fetch effect every render. const defaultSortKey = JSON.stringify(defaultSort ?? null); @@ -2010,7 +2156,7 @@ export const RelatedList: React.FC = ({ compact && windowed && fetchPage === 0 - && !fetchSortField + && !fetchSortSpec && refreshNonce === 0 ) { const seedKey = JSON.stringify([api, referenceField, String(parentId), filter ?? null]); @@ -2079,10 +2225,12 @@ export const RelatedList: React.FC = ({ // the untouched MongoDB-style object it has always been, rather than a // freshly lowered AST that means the same thing (the difference is // invisible on screen and visible to every caller pinning the wire). + // objectstack#35892 — and the filter the reader set on the related tab, + // which narrows further still. const queryFilter = - listFilterNode === undefined + listFilterNode === undefined && tabFilterNode === undefined ? parentScope - : mergeFilterNodes(parentScope, listFilterNode); + : mergeFilterNodes(parentScope, listFilterNode, tabFilterNode); if (dataSource && typeof dataSource.find === 'function') { const params: Record = { $filter: queryFilter }; // Resolve reference columns server-side, the way every other list in @@ -2095,15 +2243,16 @@ export const RelatedList: React.FC = ({ // list — see `selectFields` for why that path sends no projection. if (wireSelect) params.$select = wireSelect; if (windowed) { - params.$top = effectivePageSize; - params.$skip = fetchPage * effectivePageSize; + params.$top = tabGrows ? (fetchPage + 1) * effectivePageSize : effectivePageSize; + params.$skip = tabGrows ? 0 : fetchPage * effectivePageSize; // A user column sort becomes a server $orderby so ordering stays // global across pages; otherwise the schema's declared `sort` wins. - const orderby = fetchSortField - ? [{ field: fetchSortField, order: fetchSortDirection }] - : defaultSortSpec; + const orderby = fetchSortSpec ?? defaultSortSpec; if (orderby.length > 0) params.$orderby = orderby; } + // The query behind the tab's rows, for the grid's whole-set footer + // and its 「select all N matching」 (objectstack#35892). + const asked = { $filter: queryFilter, ...(params.$orderby ? { $orderby: params.$orderby } : {}) }; dataSource.find(api, params).then((result) => { if (cancelled) return; const isArrayResult = Array.isArray(result); @@ -2113,6 +2262,7 @@ export const RelatedList: React.FC = ({ ? (result as any).data : []; setRelatedData(items); + if (tabList) setTabFindParams(asked); if (windowed) { const reportedTotal = !isArrayResult && typeof (result as any)?.total === 'number' ? (result as any).total as number @@ -2123,7 +2273,7 @@ export const RelatedList: React.FC = ({ setHasMore( !isArrayResult && typeof (result as any)?.hasMore === 'boolean' ? (result as any).hasMore as boolean - : items.length === effectivePageSize, + : items.length === params.$top, ); } else { setTotal(null); @@ -2141,7 +2291,7 @@ export const RelatedList: React.FC = ({ setLoadFailure({ error: err }); setLoading(false); }); - } else if (listFilterNode !== undefined) { + } else if (listFilterNode !== undefined || tabFilterNode !== undefined) { // No adapter — the legacy raw-URL path, whose query language is // `filter[]=` and cannot carry an operator, let alone a // rule array. Dropping the authored filter here would answer with MORE @@ -2246,7 +2396,7 @@ export const RelatedList: React.FC = ({ // card's in-view / non-zero gate, a boolean. `compact` decides whether the // record page's payload may serve the read (objectstack#27627), a boolean. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [api, dataProvided, dataSource, referenceField, referenceFieldIsMultiValue, parentId, refreshNonce, windowed, effectivePageSize, fetchPage, fetchSortField, fetchSortDirection, defaultSortKey, filterKey, expandKey, selectKey, wireExpandKey, wireSelectKey, rowsWanted, objectSchemaReady, compact]); + }, [api, dataProvided, dataSource, referenceField, referenceFieldIsMultiValue, parentId, refreshNonce, windowed, effectivePageSize, fetchPage, fetchSortKey, tabGrows, tabFilterKey, defaultSortKey, filterKey, expandKey, selectKey, wireExpandKey, wireSelectKey, rowsWanted, objectSchemaReady, compact]); // Windowed mode: a page beyond the (shrunken) collection — e.g. the last // row of the last page was just deleted — comes back empty. Step back one @@ -2416,6 +2566,24 @@ export const RelatedList: React.FC = ({ } setDeleteTarget(null); }, [deleteTarget, onRowDelete]); + // objectstack#35892 — the related tab's floating bar deletes the selected + // rows: one confirm that counts them, then the row delete this list was + // handed, row by row, and one re-read. A row that fails stops the rest and + // the re-read shows what was removed. + const [bulkDeleteTargets, setBulkDeleteTargets] = React.useState(null); + const handleBulkDeleteRows = React.useCallback((rows: any[]) => { + if (rows.length > 0) setBulkDeleteTargets(rows); + }, []); + const handleConfirmBulkDelete = React.useCallback(async () => { + const rows = bulkDeleteTargets ?? []; + setBulkDeleteTargets(null); + try { + for (const row of rows) await onRowDelete?.(row); + } catch (err) { + console.error('[RelatedList] remove failed', err); + } + setRefreshNonce((n) => n + 1); + }, [bulkDeleteTargets, onRowDelete]); /** * May the caller Add existing here? The write's row of the affordance-to-grant @@ -3212,20 +3380,31 @@ export const RelatedList: React.FC = ({ // opaque id and reduced the second to "[object Object]", i.e. every row equal. // Feeding the resolved label map to `getSortValue` sorts by the string the // cell actually renders (objectui#3096). + // + // Level by level (the related tab sorts on several, objectstack#35892). const sortedData = React.useMemo(() => { - if (windowed || !sortField) return filteredData; + if (windowed || !sortSpec) return filteredData; // A masked column orders nothing (objectui#10728), including a sort set // before its column was stamped: rows ordered by a credential tell the // reader how it compares with every other row's. - if (!readColumnKeys(unmaskedColumnKeysKey).includes(sortField)) return filteredData; - const labels = lookupLabels[sortField]; - const keyed = filteredData.map((row) => ({ row, key: getSortValue(row[sortField], { labels }) })); + const unmasked = readColumnKeys(unmaskedColumnKeysKey); + const levels = sortSpec.filter((level) => unmasked.includes(level.field)); + if (levels.length === 0) return filteredData; + const keyed = filteredData.map((row) => ({ + row, + keys: levels.map((level) => getSortValue(row[level.field], { labels: lookupLabels[level.field] })), + })); keyed.sort((a, b) => { - const cmp = compareSortValues(a.key, b.key); - return sortDirection === 'asc' ? cmp : -cmp; + for (let i = 0; i < levels.length; i += 1) { + const cmp = compareSortValues(a.keys[i], b.keys[i]); + if (cmp !== 0) return levels[i].order === 'asc' ? cmp : -cmp; + } + return 0; }); return keyed.map((entry) => entry.row); - }, [filteredData, sortField, sortDirection, windowed, lookupLabels, unmaskedColumnKeysKey]); + // `sortKey` is the content of `sortSpec`. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [filteredData, sortKey, windowed, lookupLabels, unmaskedColumnKeysKey]); // Paginate data. Windowed mode already holds exactly one page; client mode // slices the in-memory collection as before. @@ -3255,7 +3434,7 @@ export const RelatedList: React.FC = ({ // Reset to first page when filter/sort changes React.useEffect(() => { setCurrentPage(0); - }, [filterText, sortField, sortDirection]); + }, [filterText, sortKey, tabFilterKey]); const handleSort = React.useCallback((field: string) => { // A masked column is never sorted by (objectui#10728). The button row @@ -3283,8 +3462,10 @@ export const RelatedList: React.FC = ({ * request `asc` on a list that is already `desc`. */ const activeSort = React.useMemo( - () => (sortField ? [{ field: sortField, order: sortDirection }] : defaultSortSpec), - [sortField, sortDirection, defaultSortSpec], + () => sortSpec ?? defaultSortSpec, + // `sortKey` is the content of `sortSpec`. + // eslint-disable-next-line react-hooks/exhaustive-deps + [sortKey, defaultSortSpec], ); /** @@ -3303,12 +3484,20 @@ export const RelatedList: React.FC = ({ if (!first) return; if (!readColumnKeys(unmaskedColumnKeysKey).includes(first.field)) return; setCurrentPage(0); + storedSortApplied.current = true; + if (RELATED_TAB_REMEMBERS_SORT) writeListPreference({ sort: { field: first.field, order: first.order } }); + if (tabList) { + // objectstack#35892 — the tab's sort is the condition row's: a + // header pick leads the reader's levels, as on the list page + // (`withHeaderSortPick`). + const picked = withHeaderSortPick(tabConditions.sort, next.map((item) => ({ id: `sort-${item.field}`, ...item }))); + patchTabConditions({ sort: picked }); + return; + } setSortField(first.field); setSortDirection(first.order); - storedSortApplied.current = true; - writeListPreference({ sort: { field: first.field, order: first.order } }); }, - [unmaskedColumnKeysKey, writeListPreference], + [unmaskedColumnKeysKey, writeListPreference, tabList, tabConditions.sort, patchTabConditions], ); // A `grid`/`table` list renders a real table, whose column headers carry the @@ -3396,6 +3585,11 @@ export const RelatedList: React.FC = ({ [bodyTable, tableColumns], ); + // objectstack#35892 — the related tab edits cells where the list page + // would: the `listInlineEdit` row of the affordance-to-grant map, asked of + // the child object. + const tabInlineEdit = tabList + && resolveAffordance('listInlineEdit', { objectSchema, objectName: api, perms }).allowed; const viewSchema = React.useMemo(() => { if (schema) return schema; @@ -3420,12 +3614,19 @@ export const RelatedList: React.FC = ({ ...(ownRelationshipId ? { id: `related-${ownRelationshipId}` } : {}), objectName: api, data: { provider: 'value', items: paginatedData }, - ...(storedListPreference?.columnState ? { columnState: storedListPreference.columnState } : {}), - columns: effectiveColumns - .map((c: any) => c.accessorKey || columnIdentity(c)) - .filter(Boolean), + ...(tabColumnState ? { columnState: tabColumnState } : {}), + // objectstack#35892 — a footer calculation the reader picked on the + // tab rides back on its column, so it survives the grid remounting + // (another tab and back) until 「Discard」. + columns: tabSummaryColumns( + effectiveColumns.map((c: any) => c.accessorKey || columnIdentity(c)).filter(Boolean), + tabList ? tabConditions.summaries : undefined, + ), showSearch: false, showPagination: false, + // objectstack#35892 — cell editing as on the list page + // (objectstack#35683): where the reader may edit the child object. + ...(tabList ? { editable: tabInlineEdit } : {}), // The host's row actions (`list_item`, and `record_related` inside a // parent record), already localized — the non-author host key the // console's object page hands the same grid. A dispatch from them is @@ -3524,10 +3725,11 @@ export const RelatedList: React.FC = ({ default: return { type: 'div', children: 'No view configured' }; } - }, [type, paginatedData, tableColumns, effectiveColumns, schema, effectivePageSize, hasRowActions, hasCustomRowActions, rowActions, onRowAction, onRowEdit, onRowDelete, handleDeleteRow, handleRowClick, isMobile, compact, enlargedFace, api, objectSchema, activeSort, handleTableSort, bodyTable, bodyTableOverflows, bodyTableColumnsOmitted, bodyTableColumnCap, bodySummaryRow, ownRelationshipId, storedListPreference?.columnState]); + }, [type, paginatedData, tableColumns, effectiveColumns, schema, effectivePageSize, hasRowActions, hasCustomRowActions, rowActions, onRowAction, onRowEdit, onRowDelete, handleDeleteRow, handleRowClick, isMobile, compact, enlargedFace, api, objectSchema, activeSort, handleTableSort, bodyTable, bodyTableOverflows, bodyTableColumnsOmitted, bodyTableColumnCap, bodySummaryRow, ownRelationshipId, tabColumnState, tabList, tabConditions.summaries, tabInlineEdit]); const enlargedGrid = enlargedFace && !schema && (type === 'grid' || type === 'table'); + /** * objectstack#28865 — the enlarged face's grid, driven by this list on the * grid's host channel: the React props `ObjectGrid` reads when a host owns @@ -3548,12 +3750,56 @@ export const RelatedList: React.FC = ({ * paints withheld while the grid reads its own (objectui#10657). * - `onEdit` / `onDelete`: this list's row Edit and its confirm-then-delete. */ + const tabShownFields = React.useMemo( + () => (tabList ? effectiveColumns.map((c: any) => c.accessorKey || columnIdentity(c)).filter(Boolean) as string[] : []), + [tabList, effectiveColumns], + ); + const tabRecordCountLead = React.useCallback( + (count: number) => (count === 1 ? t('detail.relatedRecordOne', { count }) : t('detail.relatedRecords', { count })), + [t], + ); + const tabSummaries = tabConditions.summaries; + const pickTabSummary = React.useCallback( + (field: string, summary: unknown) => { + const { [field]: _previous, ...rest } = tabSummaries; + // None on a column that declares nothing is the default, not a change. + patchTabConditions({ summaries: summary ? { ...rest, [field]: summary as never } : rest }); + }, + [tabSummaries, patchTabConditions], + ); const enlargedGridHost = React.useMemo(() => { if (!enlargedGrid) return undefined; const heldBefore = currentPage * (effectivePageSize || 0); const rowCount = windowed ? total ?? heldBefore + relatedData.length + (hasMore ? 1 : 0) : sortedData.length; + // objectstack#35892 — the related tab is the list page's grid: its + // column menu, select-first cells, the resident footer row with the + // reader's calculations over every matching row (`findParams`, the + // tab's own query), and selection with the floating bar (bulk delete). + // One growing window, no pager: `data` is every row loaded so far and + // `rowCount` the match total, which the footer leads with. + if (tabList) { + return { + manualPagination: true, + rowCount: total ?? sortedData.length, + page: 1, + pageSize: Math.max(1, paginatedData.length), + onPageChange: () => {}, + sort: activeSort, + onSortChange: handleTableSort, + headerMenu: true, + cellSelection: true, + residentSummaryRow: true, + summaryRowLead: tabRecordCountLead, + onColumnSummaryPick: pickTabSummary, + ...(tabFindParams ? { findParams: tabFindParams } : {}), + ...(objectSchema?.fields ? { objectFields: objectSchema.fields } : {}), + ...(onRowEdit ? { onEdit: onRowEdit } : {}), + ...(onRowDelete ? { onDelete: handleDeleteRow, onBulkDelete: handleBulkDeleteRows } : {}), + ...(writeTabColumnState ? { onColumnStateChange: writeTabColumnState } : {}), + }; + } return { manualPagination: true, rowCount, @@ -3565,9 +3811,9 @@ export const RelatedList: React.FC = ({ ...(objectSchema?.fields ? { objectFields: objectSchema.fields } : {}), ...(onRowEdit ? { onEdit: onRowEdit } : {}), ...(onRowDelete ? { onDelete: handleDeleteRow } : {}), - ...(preferenceKey ? { onColumnStateChange: (columnState: RelatedListPreference['columnState']) => writeListPreference({ columnState }) } : {}), + ...(writeTabColumnState ? { onColumnStateChange: writeTabColumnState } : {}), }; - }, [preferenceKey, writeListPreference, enlargedGrid, windowed, total, currentPage, effectivePageSize, relatedData.length, hasMore, sortedData.length, paginatedData.length, activeSort, handleTableSort, objectSchema, onRowEdit, onRowDelete, handleDeleteRow]); + }, [writeTabColumnState, enlargedGrid, windowed, total, currentPage, effectivePageSize, relatedData.length, hasMore, sortedData.length, paginatedData.length, activeSort, handleTableSort, objectSchema, onRowEdit, onRowDelete, handleDeleteRow, tabList, tabRecordCountLead, pickTabSummary, tabFindParams, handleBulkDeleteRows]); // objectstack#35601 — a stateful child (tasks) is grouped by its status on // the related tab: open groups first, completed last (`statusGroupsOf`). @@ -3644,7 +3890,9 @@ export const RelatedList: React.FC = ({ // reading, whose read failed, or whose filter was refused holds no number // yet, and says none. const reportTotal = React.useContext(RelatedListTotalReportContext); - const settledTotal = loading || loadFailure || filterRefusal ? null : recordCount; + // The related tab's own filter narrows its rows, never the number its tab + // title shows (objectstack#35892): every child, so a filtered read says none. + const settledTotal = loading || loadFailure || filterRefusal || tabFilterNode !== undefined ? null : recordCount; React.useEffect(() => { if (settledTotal !== null) reportTotal?.(settledTotal); }, [reportTotal, settledTotal]); @@ -3792,6 +4040,34 @@ export const RelatedList: React.FC = ({ + {/* objectstack#35892 — the related tab's bulk delete, confirmed once. */} + { if (!open) setBulkDeleteTargets(null); }} + > + + + + {t('detail.deleteRowsTitle', { count: bulkDeleteTargets?.length ?? 0 })} + + + {t('detail.deleteRowsConfirmation', { count: bulkDeleteTargets?.length ?? 0 })} + + + + + {t('detail.cancel', { defaultValue: 'Cancel' })} + + + {t('detail.delete', { defaultValue: 'Delete' })} + + + + {addError && (
= ({ ); } - // objectstack#35601 — the record page's related tab: no filter, sort, - // options or condition row (sorting is the table header's, filtering is the - // list page's), and the count only in the tab title. Its right end carries - // two entries: 「↗」, the child object's list under this record's condition, - // drawn on an empty list too, and 「+ 添加」, the one add entry - // (`addEntry`). The child object's own toolbar actions stay beside them. + // objectstack#35892 — the record page's related tab is the child object's + // full list (it was objectstack#35601's bare table). Row one: the child + // list's tile and name on the left; the child object's toolbar actions and + // 「+ 添加」, the one add entry (`addEntry`), on the right. Row two: the list + // page's own condition row (`list-conditions`, registered by `plugin-list`): + // 「排序」 and 「筛选」, no view switch, view settings or search, and 「放弃」 + // at its end while the reader changed anything. The tab title keeps the + // count of every child; the table's footer counts the matching ones. No + // 「在列表中打开」. The rows load as the page scrolls. if (enlargedFace) { + const conditionRow = tabList && listConditionsRegistered ? ( + patchTabConditions({ sort })} + filters={tabConditions.filters} + onFiltersChange={(filters: typeof tabConditions.filters, filterNode: unknown[] | undefined) => + patchTabConditions({ filters, filterNode })} + dataSource={dataSource} + {...(tabChanged ? { onDiscard: discardTabConditions } : {})} + /> + ) : null; + // A re-read after a new sort or filter dims the rows it replaces; the + // next window as the page scrolls does not. + const rereading = loading && !(tabGrows && currentPage > 0); return ( -
-
- {onToolbarAction && permittedToolbarActions.map((a) => ( - - ))} - {onViewAll && ( - - )} - {addEntry && ( - - )} +
+
+ +

+ {title} +

+
+ {onToolbarAction && permittedToolbarActions.map((a) => ( + + ))} + {addEntry && ( + + )} +
+ {conditionRow &&
{conditionRow}
} {loadFailure ? ( ) : loading && relatedData.length === 0 ? (
{t('detail.loading')}
) : isEmpty ? (
- {t('detail.noRelatedRecords')} + {tabFilterNode !== undefined ? t('detail.relatedNoMatches') : t('detail.noRelatedRecords')}
) : ( <> @@ -4088,18 +4379,23 @@ export const RelatedList: React.FC = ({ ( + // A grouped tab draws no footer row (objectstack#35892 F5): + // its groups already count their rows. )} actions={enlargedGridActions} /> ) : ( -
+
{enlargedGridActions ? ( @@ -4109,7 +4405,14 @@ export const RelatedList: React.FC = ({ )}
)} - {showPagination && ( + {tabGrows && canGoNext && ( + setCurrentPage((p) => p + 1)} + label={t('detail.loading')} + /> + )} + {showPagination && !tabGrows && (
{t('detail.pageOf', { current: currentPage + 1, total: totalPages })} diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedListGrid-28865.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedListGrid-28865.test.tsx index 9a9d98bc195..98848f5bf0b 100644 --- a/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedListGrid-28865.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedListGrid-28865.test.tsx @@ -25,6 +25,10 @@ import '@testing-library/jest-dom'; import * as React from 'react'; import { FilterScopeProvider, RecordContextProvider, RecordPagePreferencesProvider } from '@object-ui/react'; import { RelatedList } from '../RelatedList'; +import { resetRelatedTabConditionsForTests } from '../relatedTabConditions'; + +// The related tab's conditions live in module memory for the visit (objectstack#35892). +afterEach(() => resetRelatedTabConditionsForTests()); import { RelatedListEnlargedContext } from '../relatedListCompact'; /** @@ -65,7 +69,8 @@ const FIELDS = { account: { type: 'lookup', reference: 'account', label: 'Account' }, owner_id: { type: 'lookup', reference: 'sys_user', label: 'Owner' }, }; -const TOTAL = 30; +// More than one window of the related tab (`RELATED_TAB_WINDOW`, 50). +const TOTAL = 80; const ALL_ROWS = Array.from({ length: TOTAL }, (_, i) => ({ id: `o${i + 1}`, name: `Deal ${i + 1}`, @@ -130,7 +135,7 @@ const lastFind = (find: ReturnType) => find.mock.calls[find.mock.c describe('the enlarged related tab on a desktop is the child object list face (objectstack#28865)', () => { it('hands object-grid the page it read, with its columns, and turns off the grid’s own pager and search', async () => { renderList(); - await waitFor(() => expect(h.schema?.data?.items).toHaveLength(25)); + await waitFor(() => expect(h.schema?.data?.items).toHaveLength(50)); expect(h.schema.type).toBe('object-grid'); expect(h.schema.objectName).toBe('opportunity'); expect(h.schema.data.provider).toBe('value'); @@ -143,7 +148,9 @@ describe('the enlarged related tab on a desktop is the child object list face (o it('drives the grid on its host channel: this list’s window, page and sort, never node keys', async () => { renderList(); await waitFor(() => expect(h.props?.rowCount).toBe(TOTAL)); - expect(h.props).toMatchObject({ manualPagination: true, page: 1, pageSize: 25, sort: [] }); + // objectstack#35892 — one growing window: every row loaded so far is + // page 1, and `rowCount` is the match total the footer leads with. + expect(h.props).toMatchObject({ manualPagination: true, page: 1, pageSize: 50, sort: [] }); expect(h.props.objectFields).toEqual(FIELDS); for (const key of ['manualPagination', 'rowCount', 'page', 'onPageChange', 'onSortChange', 'objectFields']) { expect(h.schema, `${key} rides the host channel, not the node`).not.toHaveProperty(key); @@ -159,29 +166,44 @@ describe('the enlarged related tab on a desktop is the child object list face (o await waitFor(() => expect(h.props.sort).toEqual([{ field: 'amount', order: 'desc' }])); }); - it('a page from the grid is this list’s page: the next window is read from the server', async () => { - const { dataSource } = renderList(); - await waitFor(() => expect(h.props?.rowCount).toBe(TOTAL)); - act(() => h.props.onPageChange(2)); - await waitFor(() => expect(lastFind(dataSource.find).$skip).toBe(25)); - await waitFor(() => expect(h.schema.data.items.map((row: any) => row.id)).toEqual(['o26', 'o27', 'o28', 'o29', 'o30'])); - expect(h.props.page).toBe(2); - // This list's own pager is the one pager. - expect(screen.getByText('Previous')).toBeInTheDocument(); + it('rows load as the page scrolls: the end of the rows in view reads one longer window from the first row (objectstack#35892)', async () => { + const observers: Array<(entries: Array<{ isIntersecting: boolean }>) => void> = []; + const original = (globalThis as any).IntersectionObserver; + (globalThis as any).IntersectionObserver = class { + constructor(callback: (entries: Array<{ isIntersecting: boolean }>) => void) { observers.push(callback); } + observe() {} + disconnect() {} + }; + try { + const { dataSource } = renderList(); + await waitFor(() => expect(h.props?.rowCount).toBe(TOTAL)); + expect(document.querySelector('[data-related-load-more]')).not.toBeNull(); + act(() => observers[observers.length - 1]([{ isIntersecting: true }])); + await waitFor(() => expect(lastFind(dataSource.find)).toMatchObject({ $top: 100, $skip: 0 })); + await waitFor(() => expect(h.schema.data.items).toHaveLength(TOTAL)); + expect(h.props.page).toBe(1); + // Every row is loaded: nothing more to ask for, and no pager at all. + expect(document.querySelector('[data-related-load-more]')).toBeNull(); + expect(screen.queryByText('Previous')).toBeNull(); + } finally { + (globalThis as any).IntersectionObserver = original; + } }); // objectstack#35601 retired the tab's filter box and chips, and with them // the in-memory sort state the DEVIATION pin above them described: every // sort is now the server's. - it('the count is not repeated under the grid: the line keeps only the page (the count lives in the tab title)', async () => { + it('no pager line under the grid: the footer row counts the matching rows, the tab title every child', async () => { renderList(); await waitFor(() => expect(h.props?.rowCount).toBe(TOTAL)); - expect(document.querySelector('[data-related-enlarged-status]')?.textContent).toBe('Page 1 of 2'); + expect(document.querySelector('[data-related-enlarged-status]')).toBeNull(); + expect(h.props.residentSummaryRow).toBe(true); + expect(String(h.props.summaryRowLead(TOTAL))).toContain(String(TOTAL)); expect(document.querySelector('[data-related-chip]')).toBeNull(); expect(screen.queryByRole('searchbox')).toBeNull(); }); - it('column widths and order are the reader\'s: read from and written to the record-page preference (objectstack#35601)', async () => { + it('column widths and order stay in this browser, kept by the grid under the node id; the record-page preference is neither read nor written (objectstack#35892)', async () => { const stored = { order: ['amount', 'name', 'owner_id'], widths: { name: 260 } }; const store = { get: vi.fn(() => ({ relatedLists: { 'opportunity.account': { columnState: stored } } })), @@ -209,12 +231,10 @@ describe('the enlarged related tab on a desktop is the child object list face (o , ); await waitFor(() => expect(h.props?.rowCount).toBe(TOTAL)); - expect(h.schema.columnState).toEqual(stored); expect(h.schema.id).toBe('related-opportunity.account'); - act(() => h.props.onColumnStateChange({ widths: { name: 300 } })); - expect(store.update).toHaveBeenCalledWith('account', { - relatedLists: { 'opportunity.account': { columnState: { widths: { name: 300 } } } }, - }); + expect(h.schema).not.toHaveProperty('columnState'); + expect(h.props).not.toHaveProperty('onColumnStateChange'); + expect(store.update).not.toHaveBeenCalled(); }); it('CONTROL: with no preference store the grid gets no column state and no writer', async () => { @@ -227,7 +247,7 @@ describe('the enlarged related tab on a desktop is the child object list face (o it('row actions: the host’s defs ride to the grid, and a dispatch from the grid reaches onRowAction with the row', async () => { const onRowAction = vi.fn(async () => undefined); renderList({ onRowAction }); - await waitFor(() => expect(h.schema?.data?.items).toHaveLength(25)); + await waitFor(() => expect(h.schema?.data?.items).toHaveLength(50)); expect(h.schema.rowActionDefs).toEqual(ROW_ACTIONS); const row = h.schema.data.items[2]; // The grid's own dispatch shape (`objectGridActionsColumn` `onActionDef`). @@ -240,7 +260,7 @@ describe('the enlarged related tab on a desktop is the child object list face (o it('CONTROL: a dispatch that is not one of this list’s row actions reaches the surrounding runner', async () => { const onRowAction = vi.fn(async () => undefined); renderList({ onRowAction }); - await waitFor(() => expect(h.schema?.data?.items).toHaveLength(25)); + await waitFor(() => expect(h.schema?.data?.items).toHaveLength(50)); await h.execute!({ type: 'some_bulk_action', params: { records: [] } }).catch(() => undefined); await h.execute!({ name: 'not_ours', params: { _rowRecord: h.schema.data.items[0] } }).catch(() => undefined); expect(onRowAction).not.toHaveBeenCalled(); @@ -250,7 +270,7 @@ describe('the enlarged related tab on a desktop is the child object list face (o const onRowEdit = vi.fn(); const onRowDelete = vi.fn(); renderList({ onRowEdit, onRowDelete }); - await waitFor(() => expect(h.schema?.data?.items).toHaveLength(25)); + await waitFor(() => expect(h.schema?.data?.items).toHaveLength(50)); expect(h.props.onEdit).toBe(onRowEdit); act(() => h.props.onDelete(h.schema.data.items[0])); expect(await screen.findByRole('alertdialog')).toBeInTheDocument(); diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedToolbar-27524.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedToolbar-27524.test.tsx index 8086b5eebc7..31999a54bfd 100644 --- a/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedToolbar-27524.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.enlargedToolbar-27524.test.tsx @@ -10,24 +10,29 @@ * The record page's related tab (the enlarged related list, * `RelatedListEnlargedContext`). * - * objectstack#35601 — no filter, sort, options or condition row, and the count - * only in the tab title. The right end carries two entries: 「↗」 (the child's - * list under this record's condition, on an empty list too) and 「+ 添加」, - * the one add entry, decided by the relationship when the page authored no + * objectstack#35601 — the count only in the tab title, and 「+ 添加」, the one + * add entry, at the right end. objectstack#35892 took 「↗」 (open in list) + * away, put the list's name at the left and the list page's condition row + * under it (`RelatedList.tab-35892.test.tsx`). The add entry is decided by the relationship when the page authored no * `add`: a `lookup` child opens a picker of the child object whose first row is * 「新建」; a `master_detail` child with a catalog opens a picker of the * catalog; one with none creates a row directly. A pick of several is ONE * transactional batch: all rows or none. A stateful child is grouped by its - * status, completed last. The reader's header sort is remembered. + * status, completed last. The reader's header sort holds for this visit only + * (objectstack#35892, ruling 7064083597): it is no longer remembered. */ -import { describe, it, expect, vi, beforeAll } from 'vitest'; +import { describe, it, expect, vi, beforeAll, afterEach } from 'vitest'; import { render, screen, waitFor, fireEvent, within } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; import { FilterScopeProvider, RecordContextProvider, RecordPagePreferencesProvider, type RecordPagePreference } from '@object-ui/react'; import { ComponentRegistry } from '@object-ui/core'; import { RelatedList } from '../RelatedList'; +import { resetRelatedTabConditionsForTests } from '../relatedTabConditions'; + +// The related tab's conditions live in module memory for the visit (objectstack#35892). +afterEach(() => resetRelatedTabConditionsForTests()); import { RelatedListEnlargedContext } from '../relatedListCompact'; /** @@ -156,28 +161,28 @@ async function pickThree() { fireEvent.click(within(dialog).getByTestId('record-picker-confirm')); } -describe('the related tab carries 「↗」 and 「+ 添加」 alone (objectstack#35601)', () => { - it('no filter, chips, export or New; the count is not repeated; ↗ opens the list', async () => { +describe('the related tab names its list and carries 「+ 添加」, with no 「↗」 (objectstack#35601, objectstack#35892)', () => { + it('no filter box, chips, export, New or 「↗」; the count is not repeated; the name leads the row', async () => { const onViewAll = vi.fn(); renderList({ onViewAll }); await waitFor(() => expect(screen.getByText('Send quote')).toBeInTheDocument()); const bar = toolbar(); expect(bar.getAttribute('role')).toBe('toolbar'); const controls = Array.from(bar.querySelectorAll('button')).map((b) => b.getAttribute('aria-label') || b.textContent); - expect(controls).toEqual(['View All', 'Add']); + expect(controls).toEqual(['Add']); + expect(document.querySelector('[data-related-enlarged-title]')?.textContent).toBe('Tasks'); expect(within(bar).queryByRole('searchbox')).toBeNull(); expect(bar.querySelector('[data-related-chip], [data-related-enlarged-export]')).toBeNull(); expect(screen.queryByTestId('related-list-new')).toBeNull(); expect(document.querySelector('[data-related-enlarged-status]')).toBeNull(); expect(screen.queryByLabelText('2 records')).toBeNull(); - fireEvent.click(bar.querySelector('[data-related-open-list]')!); - expect(onViewAll).toHaveBeenCalledTimes(1); + expect(document.querySelector('[data-related-open-list]')).toBeNull(); }); - it('an empty list keeps both entries', async () => { + it('an empty list keeps its add entry', async () => { renderList({ rows: [] }); await waitFor(() => expect(document.querySelector('[data-related-enlarged-empty]')).not.toBeNull()); - expect(toolbar().querySelector('[data-related-open-list]')).not.toBeNull(); + expect(document.querySelector('[data-related-open-list]')).toBeNull(); expect(addButton()).not.toBeNull(); }); @@ -376,7 +381,7 @@ describe('a stateful child is grouped by its status on the related tab (objectst }); }); -describe('the related tab remembers the reader\'s header sort (objectstack#35601)', () => { +describe('the related tab no longer remembers the reader\'s header sort (objectstack#35601 → objectstack#35892)', () => { function store(initial: RecordPagePreference = {}) { const states: Record = { lead: initial }; return { @@ -385,7 +390,7 @@ describe('the related tab remembers the reader\'s header sort (objectstack#35601 }; } - it('a header click is written to the record-page preference of the parent object', async () => { + it('a header click is not written to the record-page preference: it holds for this visit (objectstack#35892)', async () => { const preferences = store(); render( @@ -408,14 +413,11 @@ describe('the related tab remembers the reader\'s header sort (objectstack#35601 ); await waitFor(() => expect(screen.getByText('Send quote')).toBeInTheDocument()); fireEvent.click(document.querySelector('[data-sort-header="subject"]')!); - await waitFor(() => expect(preferences.update).toHaveBeenCalled()); - expect(preferences.update.mock.calls.at(-1)).toEqual([ - 'lead', - { relatedLists: { 'task.lead': { sort: { field: 'subject', order: 'desc' } } } }, - ]); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(preferences.update).not.toHaveBeenCalled(); }); - it('a remembered sort is the one the list reads by', async () => { + it('a sort an earlier version remembered is no longer read: the list reads in its declared order (objectstack#35892)', async () => { const preferences = store({ relatedLists: { 'task.lead': { sort: { field: 'subject', order: 'desc' } } } }); const ds = dataSourceFor(); render( @@ -437,12 +439,10 @@ describe('the related tab remembers the reader\'s header sort (objectstack#35601 , ); - await waitFor(() => { - const last = ds.find.mock.calls.filter(([r]: [string]) => r === 'task').at(-1); - expect(JSON.stringify(last?.[1]?.$orderby)).toContain('subject'); - }); - const last = ds.find.mock.calls.filter(([r]: [string]) => r === 'task').at(-1); - expect(JSON.stringify(last?.[1]?.$orderby)).toContain('desc'); + await waitFor(() => expect(screen.getByText('Send quote')).toBeInTheDocument()); + for (const [resource, params] of ds.find.mock.calls as Array<[string, any]>) { + if (resource === 'task') expect(params?.$orderby).toBeUndefined(); + } }); }); diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.tab-35892.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.tab-35892.test.tsx new file mode 100644 index 00000000000..48a81d5fa80 --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.tab-35892.test.tsx @@ -0,0 +1,224 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35892 — the record page's related tab is the child object's + * full list: the list page's condition row (`list-conditions`, through the + * registry), its grid with the column menu, cell editing, selection and the + * footer row, rows that load as the page scrolls, and 「Discard」 while the + * reader changed anything. What they change holds for this visit to the + * record: across a remount (another tab and back), not on another record. + * The tab title's count is every child; a filter never changes it. + */ + +import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest'; +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import * as React from 'react'; +import { ComponentRegistry } from '@object-ui/core'; +import { RelatedList } from '../RelatedList'; +import { RelatedListEnlargedContext, RelatedListTotalReportContext } from '../relatedListCompact'; +import { resetRelatedTabConditionsForTests } from '../relatedTabConditions'; + +/** What `RelatedList` hands each `SchemaRenderer`, by node type. */ +const h = vi.hoisted(() => ({ byType: {} as Record })); +vi.mock('@object-ui/react', async (importOriginal) => { + const actual = await importOriginal>(); + function CapturingRenderer({ schema, ...props }: any) { + h.byType[schema?.type] = { schema, props }; + if (schema?.type === 'list-conditions' && props.onDiscard) { + return ; + } + return null; + } + return { ...actual, SchemaRenderer: CapturingRenderer }; +}); + +beforeAll(() => { + Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1440 }); + // `plugin-list` registers it in the app; this package cannot import that one. + if (!ComponentRegistry.has('list-conditions')) ComponentRegistry.register('list-conditions', () => null); +}); + +afterEach(() => { + cleanup(); + h.byType = {}; + resetRelatedTabConditionsForTests(); +}); + +const FIELDS = { + name: { type: 'text', label: 'Name' }, + amount: { type: 'currency', label: 'Amount' }, + opportunity: { type: 'lookup', reference: 'opportunity', label: 'Opportunity' }, +}; +const ROWS = Array.from({ length: 12 }, (_, i) => ({ id: `q${i + 1}`, name: `Quote ${i + 1}`, amount: (i + 1) * 100, opportunity: 'O-1' })); + +function dataSourceFor() { + return { + find: vi.fn(async (_object: string, params: any) => { + const narrowed = JSON.stringify(params?.$filter ?? null).includes('amount'); + const rows = narrowed ? ROWS.filter((row) => row.amount > 600) : ROWS; + return { data: rows.slice(params?.$skip ?? 0, (params?.$skip ?? 0) + (params?.$top ?? rows.length)), total: rows.length }; + }), + getObjectSchema: vi.fn(async () => ({ name: 'quote', fields: FIELDS })), + }; +} + +function Tab({ parentId = 'O-1', dataSource, onTotal, onRowDelete }: { + parentId?: string; + dataSource: ReturnType; + onTotal?: (n: number) => void; + onRowDelete?: (row: any) => Promise | void; +}) { + return ( + + + + + + ); +} + +const lastFind = (find: ReturnType) => find.mock.calls[find.mock.calls.length - 1][1]; +const conditions = () => h.byType['list-conditions']; +const grid = () => h.byType['object-grid']; +const AMOUNT_OVER_600 = ['amount', '>', 600]; +const AMOUNT_GROUP = { id: 'root', logic: 'and' as const, conditions: [{ id: 'r1', field: 'amount', operator: '>', value: 600 }] }; + +describe('the related tab is the child object\'s full list (objectstack#35892)', () => { + it('draws the list page\'s condition row with the child object and the table\'s columns, and no Discard yet', async () => { + render(); + await waitFor(() => expect(grid()?.schema.data.items).toHaveLength(12)); + expect(conditions().props).toMatchObject({ objectName: 'quote', shownFields: ['name', 'amount'], sort: [] }); + expect(conditions().props.objectDef?.fields).toEqual(FIELDS); + expect(conditions().props).not.toHaveProperty('onDiscard'); + for (const key of ['sort', 'filters', 'onSortChange', 'onFiltersChange']) { + expect(conditions().schema, `${key} is a host prop, never a node key`).not.toHaveProperty(key); + } + }); + + it('hands the grid the list page\'s host keys: column menu, select-first cells, footer row, its query, selection', async () => { + const onRowDelete = vi.fn(); + render(); + await waitFor(() => expect(grid()?.props.findParams).toBeDefined()); + expect(grid().props).toMatchObject({ headerMenu: true, cellSelection: true, residentSummaryRow: true, rowCount: 12 }); + expect(grid().props.findParams.$filter).toBeDefined(); + expect(typeof grid().props.onBulkDelete).toBe('function'); + expect(typeof grid().props.onColumnSummaryPick).toBe('function'); + expect(grid().schema).toHaveProperty('editable'); + }); + + it('a filter reaches the query beside the parent scope; the tab title keeps every child, the footer the matches', async () => { + const ds = dataSourceFor(); + const onTotal = vi.fn(); + render(); + await waitFor(() => expect(onTotal).toHaveBeenLastCalledWith(12)); + act(() => conditions().props.onFiltersChange(AMOUNT_GROUP, AMOUNT_OVER_600)); + await waitFor(() => expect(grid().schema.data.items).toHaveLength(6)); + const sent = JSON.stringify(lastFind(ds.find).$filter); + expect(sent).toContain('opportunity'); + expect(sent).toContain('amount'); + expect(grid().props.rowCount).toBe(6); + expect(onTotal).not.toHaveBeenCalledWith(6); + expect(onTotal).toHaveBeenLastCalledWith(12); + }); + + it('a sort of several levels is one $orderby from the first row; a header pick leads it', async () => { + const ds = dataSourceFor(); + render(); + await waitFor(() => expect(grid()?.schema.data.items).toHaveLength(12)); + act(() => conditions().props.onSortChange([ + { id: 'a', field: 'amount', order: 'desc' }, + { id: 'b', field: 'name', order: 'asc' }, + ])); + await waitFor(() => expect(lastFind(ds.find).$orderby).toEqual([ + { field: 'amount', order: 'desc' }, + { field: 'name', order: 'asc' }, + ])); + expect(lastFind(ds.find).$skip).toBe(0); + act(() => grid().props.onSortChange([{ field: 'name', order: 'desc' }])); + await waitFor(() => expect(lastFind(ds.find).$orderby).toEqual([ + { field: 'name', order: 'desc' }, + { field: 'amount', order: 'desc' }, + ])); + }); + + it('「Discard」 appears once something changed and puts the tab back', async () => { + const ds = dataSourceFor(); + render(); + await waitFor(() => expect(grid()?.schema.data.items).toHaveLength(12)); + act(() => conditions().props.onFiltersChange(AMOUNT_GROUP, AMOUNT_OVER_600)); + fireEvent.click(await screen.findByTestId('condition-discard')); + await waitFor(() => expect(grid().schema.data.items).toHaveLength(12)); + expect(screen.queryByTestId('condition-discard')).toBeNull(); + expect(JSON.stringify(lastFind(ds.find).$filter)).not.toContain('amount'); + }); + + it('a footer calculation the reader picks rides back on its column, and counts as a change', async () => { + render(); + await waitFor(() => expect(grid()?.schema.data.items).toHaveLength(12)); + act(() => grid().props.onColumnSummaryPick('amount', 'sum')); + await waitFor(() => expect(grid().schema.columns).toEqual([{ field: 'name' }, { field: 'amount', summary: 'sum' }])); + expect(conditions().props.onDiscard).toBeDefined(); + }); + + it('holds across a remount on the same record (another tab and back), and is gone on another record', async () => { + const ds = dataSourceFor(); + const first = render(); + await waitFor(() => expect(grid()?.schema.data.items).toHaveLength(12)); + act(() => conditions().props.onFiltersChange(AMOUNT_GROUP, AMOUNT_OVER_600)); + await waitFor(() => expect(grid().schema.data.items).toHaveLength(6)); + first.unmount(); + h.byType = {}; + const again = render(); + await waitFor(() => expect(grid()?.schema.data.items).toHaveLength(6)); + expect(conditions().props.filters).toEqual(AMOUNT_GROUP); + again.unmount(); + h.byType = {}; + render(); + await waitFor(() => expect(grid()?.schema.data.items).toHaveLength(12)); + expect(conditions().props.filters.conditions).toEqual([]); + }); + + it('a filter that matches nothing says so, and the condition row stays to change it', async () => { + const ds = dataSourceFor(); + ds.find.mockImplementation(async (_o: string, params: any) => ( + JSON.stringify(params?.$filter ?? null).includes('amount') ? { data: [], total: 0 } : { data: ROWS, total: ROWS.length } + )); + render(); + await waitFor(() => expect(grid()?.schema.data.items).toHaveLength(12)); + act(() => conditions().props.onFiltersChange(AMOUNT_GROUP, AMOUNT_OVER_600)); + await waitFor(() => expect(document.querySelector('[data-related-enlarged-empty]')?.textContent).toBe('No records match the filter')); + expect(document.querySelector('[data-related-enlarged-conditions]')).not.toBeNull(); + }); + + it('the bulk bar\'s delete asks once, counting the rows, then deletes each and reads again', async () => { + const ds = dataSourceFor(); + const onRowDelete = vi.fn(async () => undefined); + render(); + await waitFor(() => expect(grid()?.schema.data.items).toHaveLength(12)); + const reads = ds.find.mock.calls.length; + act(() => grid().props.onBulkDelete(ROWS.slice(0, 3))); + expect(await screen.findByText('Selected: 3. This cannot be undone.')).toBeInTheDocument(); + expect(onRowDelete).not.toHaveBeenCalled(); + fireEvent.click(document.querySelector('[data-related-bulk-delete-confirm]')!); + await waitFor(() => expect(onRowDelete).toHaveBeenCalledTimes(3)); + await waitFor(() => expect(ds.find.mock.calls.length).toBeGreaterThan(reads)); + }); +}); diff --git a/ui/packages/plugin-detail/src/__tests__/relatedTabConditions-35892.test.ts b/ui/packages/plugin-detail/src/__tests__/relatedTabConditions-35892.test.ts new file mode 100644 index 00000000000..ab0e13e6ab2 --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/relatedTabConditions-35892.test.ts @@ -0,0 +1,63 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35892 — what a reader changes on a record page's related tab + * holds while they stay on the record, across its tabs, and is gone on + * another record; 「Discard」 clears one tab. + */ + +import { afterEach, describe, expect, it } from 'vitest'; +import { + EMPTY_RELATED_TAB_CONDITIONS, + discardRelatedTabConditions, + patchRelatedTabConditions, + readRelatedTabConditions, + relatedTabConditionsChanged, + resetRelatedTabConditionsForTests, +} from '../relatedTabConditions'; + +const SORT = [{ id: 'sort-amount', field: 'amount', order: 'desc' as const }]; + +afterEach(() => resetRelatedTabConditionsForTests()); + +describe('related tab conditions (objectstack#35892)', () => { + it('starts at the default and counts nothing as a change', () => { + expect(readRelatedTabConditions('opportunity:1', 'quote.opportunity')).toBe(EMPTY_RELATED_TAB_CONDITIONS); + expect(relatedTabConditionsChanged(EMPTY_RELATED_TAB_CONDITIONS)).toBe(false); + }); + + it('holds each tab of the record apart', () => { + patchRelatedTabConditions('opportunity:1', 'quote.opportunity', { sort: SORT }); + patchRelatedTabConditions('opportunity:1', 'task.what', { summaries: { amount: 'sum' } }); + expect(readRelatedTabConditions('opportunity:1', 'quote.opportunity').sort).toEqual(SORT); + expect(readRelatedTabConditions('opportunity:1', 'quote.opportunity').summaries).toEqual({}); + expect(readRelatedTabConditions('opportunity:1', 'task.what').summaries).toEqual({ amount: 'sum' }); + }); + + it('drops the last record\'s tabs once another record is written', () => { + patchRelatedTabConditions('opportunity:1', 'quote.opportunity', { sort: SORT }); + patchRelatedTabConditions('opportunity:2', 'quote.opportunity', { filterNode: ['amount', '>', 10] }); + expect(readRelatedTabConditions('opportunity:1', 'quote.opportunity')).toBe(EMPTY_RELATED_TAB_CONDITIONS); + expect(readRelatedTabConditions('opportunity:2', 'quote.opportunity').filterNode).toEqual(['amount', '>', 10]); + }); + + it('Discard puts one tab back and leaves the others', () => { + patchRelatedTabConditions('opportunity:1', 'quote.opportunity', { sort: SORT }); + patchRelatedTabConditions('opportunity:1', 'task.what', { sort: SORT }); + discardRelatedTabConditions('opportunity:1', 'quote.opportunity'); + expect(readRelatedTabConditions('opportunity:1', 'quote.opportunity')).toBe(EMPTY_RELATED_TAB_CONDITIONS); + expect(readRelatedTabConditions('opportunity:1', 'task.what').sort).toEqual(SORT); + }); + + it('a change undone by hand is no change', () => { + patchRelatedTabConditions('opportunity:1', 'quote.opportunity', { sort: SORT }); + patchRelatedTabConditions('opportunity:1', 'quote.opportunity', { sort: [] }); + expect(readRelatedTabConditions('opportunity:1', 'quote.opportunity')).toBe(EMPTY_RELATED_TAB_CONDITIONS); + }); +}); diff --git a/ui/packages/plugin-detail/src/relatedTabConditions.ts b/ui/packages/plugin-detail/src/relatedTabConditions.ts new file mode 100644 index 00000000000..d211047fb45 --- /dev/null +++ b/ui/packages/plugin-detail/src/relatedTabConditions.ts @@ -0,0 +1,140 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * What a reader changed on a record page's related tab (objectstack#35892): + * its sort, its filter and the footer's calculations. Temporary by the card's + * rule: it holds while the reader stays on the record (switching tabs, or + * between the record's page and its drawer, keeps it), and it is gone after a + * reload or on another record. 「Discard」 clears it. Nothing is written + * anywhere: the tab has no Save. + * + * Held in module memory rather than in the tab's React state because the + * record page unmounts a tab's face when another tab opens. One record's tabs + * at a time: claiming the tabs of another record drops the last record's. + */ + +import * as React from 'react'; +import type { FilterBuilderRowGroup, SortItem } from '@object-ui/components'; +import type { ColumnSummary } from '@objectstack/spec/ui'; + +export interface RelatedTabConditions { + /** The reader's sort levels; empty = the list's default order. */ + sort: SortItem[]; + /** The filter group the condition row edits. */ + filters: FilterBuilderRowGroup; + /** The filter it applies, as the query node (`undefined` = none). */ + filterNode: unknown[] | undefined; + /** Footer calculations the reader picked, by field (`null` = None). */ + summaries: Readonly>; +} + +export const EMPTY_RELATED_TAB_CONDITIONS: RelatedTabConditions = Object.freeze({ + sort: [], + filters: { id: 'root', logic: 'and', conditions: [] }, + filterNode: undefined, + summaries: Object.freeze({}), +}) as RelatedTabConditions; + +/** Whether the reader changed anything on the tab: what lights 「Discard」. */ +export function relatedTabConditionsChanged(conditions: RelatedTabConditions): boolean { + return conditions.sort.length > 0 + || conditions.filterNode !== undefined + || Object.keys(conditions.summaries).length > 0; +} + +let heldRecord: string | null = null; +const held = new Map(); +const listeners = new Set<() => void>(); + +function notify(): void { + for (const listener of listeners) listener(); +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener); + return () => listeners.delete(listener); +} + +/** The key of one record's tab: the record (`object:id`) and the relationship the list hangs on. */ +export function relatedTabKey(record: string, relationship: string): string { + return `${record}\u0000${relationship}`; +} + +/** Start holding `record`'s tabs; another record's are dropped. */ +function claimRecord(record: string): void { + if (heldRecord === record) return; + heldRecord = record; + if (held.size > 0) held.clear(); +} + +/** The tab's conditions, held for this record; the empty set before any change. */ +export function readRelatedTabConditions(record: string, relationship: string): RelatedTabConditions { + if (heldRecord !== record) return EMPTY_RELATED_TAB_CONDITIONS; + return held.get(relatedTabKey(record, relationship)) ?? EMPTY_RELATED_TAB_CONDITIONS; +} + +/** Lay `patch` over the tab's conditions. */ +export function patchRelatedTabConditions( + record: string, + relationship: string, + patch: Partial, +): void { + claimRecord(record); + const key = relatedTabKey(record, relationship); + const next = { ...(held.get(key) ?? EMPTY_RELATED_TAB_CONDITIONS), ...patch }; + if (relatedTabConditionsChanged(next)) held.set(key, next); + else held.delete(key); + notify(); +} + +/** 「Discard」: the tab back to its default. */ +export function discardRelatedTabConditions(record: string, relationship: string): void { + if (heldRecord !== record || !held.delete(relatedTabKey(record, relationship))) return; + notify(); +} + +/** For tests: forget every record's tabs. */ +export function resetRelatedTabConditionsForTests(): void { + heldRecord = null; + held.clear(); + notify(); +} + +/** + * The tab's conditions and their writers. `record` / `relationship` null ⇒ + * not a tab (the empty set, writers that do nothing). Opening a tab of + * another record drops the last record's tabs. + */ +export function useRelatedTabConditions(record: string | null, relationship: string | null): { + conditions: RelatedTabConditions; + patch: (patch: Partial) => void; + discard: () => void; +} { + React.useEffect(() => { + if (record && relationship && heldRecord !== record) { + claimRecord(record); + notify(); + } + }, [record, relationship]); + const conditions = React.useSyncExternalStore( + subscribe, + () => (record && relationship ? readRelatedTabConditions(record, relationship) : EMPTY_RELATED_TAB_CONDITIONS), + () => EMPTY_RELATED_TAB_CONDITIONS, + ); + const patch = React.useCallback( + (next: Partial) => { + if (record && relationship) patchRelatedTabConditions(record, relationship, next); + }, + [record, relationship], + ); + const discard = React.useCallback(() => { + if (record && relationship) discardRelatedTabConditions(record, relationship); + }, [record, relationship]); + return { conditions, patch, discard }; +} diff --git a/ui/packages/plugin-detail/src/useDetailTranslation.ts b/ui/packages/plugin-detail/src/useDetailTranslation.ts index 47211097553..0cda75c6b46 100644 --- a/ui/packages/plugin-detail/src/useDetailTranslation.ts +++ b/ui/packages/plugin-detail/src/useDetailTranslation.ts @@ -121,6 +121,10 @@ export const DETAIL_DEFAULT_TRANSLATIONS: Record = { 'detail.deleteRow': 'Delete', // objectui#13333 — the related list's row delete names the row by its title. 'detail.deleteRowConfirmation': 'Are you sure you want to delete "{{name}}"?', + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + 'detail.relatedNoMatches': 'No records match the filter', + 'detail.deleteRowsTitle': 'Delete selected records', + 'detail.deleteRowsConfirmation': 'Selected: {{count}}. This cannot be undone.', 'detail.actions': 'Actions', 'detail.previousPage': 'Previous', 'detail.nextPage': 'Next', diff --git a/ui/packages/plugin-list/README.md b/ui/packages/plugin-list/README.md index 2a07217973d..d4421eab61c 100644 --- a/ui/packages/plugin-list/README.md +++ b/ui/packages/plugin-list/README.md @@ -344,6 +344,35 @@ function TaskList() { } ``` +### The condition row for another host: `list-conditions` + +A host that draws a child object's rows itself, and sits below this package so +it cannot import it (the record page's related tab, `@object-ui/plugin-detail`), +reaches the list page's condition row through the registry as +`list-conditions` (objectstack#35892), the way it reaches `object-grid`. It is +the same `ConditionChipRow`, `SortPanel` and `FilterPanel` with the same field +lists, and no view switch, view settings or search. It is controlled and every +input is a React prop, never a node key: + +```tsx + { setFilterGroup(group); setFilter(filterNode); }} + onDiscard={changed ? discard : undefined} +/> +``` + +`onFiltersChange` hands back the group the panels edit and the query node the +list page would send for it (`undefined` = no filter). **Discard** +(`ConditionDiscardButton`, the list page's own) is drawn at the row's end while +`onDiscard` is passed. Labels fold to icons when the row is narrow. + ## Schema The ListView component accepts a `ListViewSchema`, exported from diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 7ecfd1938a6..5c453f095c1 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -49,7 +49,7 @@ import { useDensityMode, resolveInlineAriaProps } from '@object-ui/react'; import type { DataTableSchema, DependsOnInput, ListViewSchema, ObjectMapConfig } from '@object-ui/types'; import { detectStatusField, isSystemManagedField } from '@object-ui/types'; import { usePullToRefresh } from '@object-ui/mobile'; -import { type ListViewVisualization, resolveConditionalFormatting, buildExpandFields, buildExportFileName, resolveAffordance, type SchemaLike, partitionRowsByPredicate, normalizeListViewSchema, isListViewVisualization, rowHeightToDensityMode, mergeFilterNodes, toFilterNodeSafely, FilterOperatorError, columnIdentity, collectPredicateFieldRefs, collectGroupingFieldRefs, listViewPredicates, PLATFORM_RECORD_COLUMNS, EXPANDABLE_FIELD_TYPES, UNMATERIALIZED_FIELD_TYPES, readObjectSortability, isPlatformSortableField, leadWithNameField, filterPlatformSortableSort, applyNonGridRowCeiling, type NonGridCeilingResult, resolveNameField, declaredNameField, resolveDependsOnFields, GANTT_CONFIG_SPELLING, kanbanDeclaredLanes, csvBlob, readWithheldFieldNames, refersToWithheldField } from '@object-ui/core'; +import { type ListViewVisualization, resolveConditionalFormatting, buildExpandFields, buildExportFileName, resolveAffordance, type SchemaLike, partitionRowsByPredicate, normalizeListViewSchema, isListViewVisualization, rowHeightToDensityMode, mergeFilterNodes, toFilterNodeSafely, FilterOperatorError, columnIdentity, collectPredicateFieldRefs, collectGroupingFieldRefs, listViewPredicates, PLATFORM_RECORD_COLUMNS, EXPANDABLE_FIELD_TYPES, UNMATERIALIZED_FIELD_TYPES, readObjectSortability, isPlatformSortableField, leadWithNameField, filterPlatformSortableSort, applyNonGridRowCeiling, type NonGridCeilingResult, resolveNameField, declaredNameField, resolveDependsOnFields, GANTT_CONFIG_SPELLING, kanbanDeclaredLanes, csvBlob, readWithheldFieldNames, refersToWithheldField, withHeaderSortPick } from '@object-ui/core'; import { useObjectLabel, useSafeFieldLabel, createSafeTranslation, useDisplayLocale, pickLocalized, recordCurrencyField, recordCurrencyReadField } from '@object-ui/i18n'; // Two resolvers, two vocabularies — the repo spells the distinction into the // NAMES (objectui#4167). `resolveInlineI18nLabel` is the spec's own @@ -1237,7 +1237,7 @@ function filterRowsKey(group: FilterBuilderRowGroup): string { return JSON.stringify([rows.length > 1 ? group.logic ?? 'and' : 'and', rows]); } -function appliedFilterGroup(group: FilterBuilderRowGroup): FilterBuilderRowGroup { +export function appliedFilterGroup(group: FilterBuilderRowGroup): FilterBuilderRowGroup { const rows = group.conditions ?? []; const finished = rows.filter(isAppliedFilterRow); const kept = finished.filter((c) => !isCurrencyCompanion(c, group) || isCurrencyCompanion(c, { ...group, conditions: finished })); @@ -1909,7 +1909,7 @@ const NO_DRAFT_ONLY_FIELDS: ReadonlySet = new Set(); const NO_DRAFT_ONLY_QUERY_DROPS: readonly string[] = []; /** The names `objectDef` marks {@link DRAFT_ONLY_FIELD_KEY}, in either field-map shape. */ -function readDraftOnlyFieldNames(objectDef: unknown): ReadonlySet { +export function readDraftOnlyFieldNames(objectDef: unknown): ReadonlySet { const raw = (objectDef as { fields?: unknown } | null | undefined)?.fields; if (!raw || typeof raw !== 'object') return NO_DRAFT_ONLY_FIELDS; const entries: Array<[unknown, unknown]> = Array.isArray(raw) @@ -1990,7 +1990,7 @@ function omitDraftOnlyFilterFields(node: unknown, draftOnly: ReadonlySet * hook. Every memo that calls it already depends on those two, so none depends * on a function's identity (AGENTS.md #10). */ -function canReadField( +export function canReadField( perms: ReturnType, objectName: string | undefined, field: string, @@ -2007,13 +2007,185 @@ function canReadField( * is not blank and can be removed; the hide-fields lists never offer one to * add. A plain function of the definition's field map, like `canReadField`. */ -function isDeclaredHidden( +export function isDeclaredHidden( defs: Record | undefined, field: string, ): boolean { return defs?.[field]?.hidden === true; } +/** + * A field's declared `options` (an array of `{ value, label }` or a keyed + * object) as the array the pickers' value lists read, before the host + * translates the labels. `undefined` when none are declared. + */ +export function conditionOptionsOf(raw: unknown): Array<{ value: any; label: string; [k: string]: any }> | undefined { + if (!raw) return undefined; + return Array.isArray(raw) + ? raw.map((o: any) => ({ + value: o?.value ?? o, + label: o?.label ?? String(o?.value ?? o), + ...(o && typeof o === 'object' ? o : {}), + })) + : Object.entries(raw as Record).map(([value, meta]) => ({ + value, + label: (meta as any)?.label || value, + ...(meta as any), + })); +} + +/** One field the Filter and Sort pickers may name, as the object definition declares it. */ +export interface ConditionCandidateField { + value: string; + label: string; + type: string; + multiple?: boolean; + options?: any; + referenceTo?: string; + displayField?: string; + currencyField?: string; +} + +/** + * The fields an object definition offers the condition controls, in the + * definition's own order: the base set both pickers narrow (see + * `candidateFields` in `ListView` for every rule this reads). Shared with any + * host of the same controls over the same object (the related tab's condition + * row, objectstack#35892), so the two lists never drift. + */ +export function conditionCandidatesOf( + defs: Record, + label: (field: string, fallback: string) => string, + options: (field: string, raw: unknown) => any[] | undefined, +): ConditionCandidateField[] { + return Object.entries(defs).map(([key, field]: [string, any]) => ({ + value: key, + label: label(key, field.label || key), + type: field.type || 'text', + // With the type, whether the field's value is a list: the filter + // offers a multi-value field only the operators the server takes. + multiple: field.multiple === true, + options: options(key, field.options), + // ⚠️ objectui#6837 half 2: the READ narrows to `reference` (the only + // spelling the protocol declares — `FieldSchema` refuses `reference_to` + // by name). The EMITTED key is unchanged: it is what this emit's TARGET + // contract declares, and renaming it would be a separate change. + // Target contract here: this file's own local filter-field descriptor, + // which spells it camelCase `referenceTo`. + referenceTo: field.reference, + // objectui#10545 — the display field is read in the DECLARED spelling + // and only in it. `FieldSchema` declares `displayField`; it refuses + // `display_field` and `reference_field` with `unrecognized_keys`. This is + // the single spelling `plugin-grid`'s copy set reads + // (`RELATIONAL_META_READ_SET`, objectui#7155). A stored pre-strict + // `display_field` is folded onto `displayField` once, at ingestion + // (`normalizeSchemaReferenceKeys`, objectui#7650), never here. + // + // No id column is read: `FieldSchema` declares none for a lookup (it + // refuses `idField` and `id_field` alike), so the filter's value + // picker keys the lookup by its own `id` default. + displayField: field.displayField, + // ADR-0144 D6: a `record`-mode amount's row pairs with its code + // field, so the filter compares within one currency. + ...(recordCurrencyField(field) ? { currencyField: recordCurrencyField(field) } : {}), + })); +} + +/** + * The FILTER picker's fields, in the order its list draws them (see + * `filterFields` in `ListView` for why each rule is there): readable, not + * declared hidden and not draft-only unless a held condition names it; this + * list's columns first in column order, then the other business fields, then + * the system fields, then a hidden field kept by a held condition. + */ +export function filterConditionFieldsOf( + candidates: ReadonlyArray, + opts: { + defs: Record | undefined; + perms: ReturnType; + objectName: string | undefined; + /** The fields the held filter rows name. */ + held: ReadonlySet; + /** The list's columns, in the order it shows them. */ + columnOrder: ReadonlyArray; + draftOnly: ReadonlySet; + }, +): T[] { + const { defs, perms, objectName, held, columnOrder, draftOnly } = opts; + const isHidden = (name: string) => isDeclaredHidden(defs, name); + const columnRank = new Map(); + for (const name of columnOrder) { + if (name && !columnRank.has(name)) columnRank.set(name, columnRank.size); + } + // 0: a column of this view · 1: another business field · 2: a system + // field · 3: a hidden field kept only because a held condition names it. + const tierOf = (name: string) => + isHidden(name) ? 3 : columnRank.has(name) ? 0 : isSystemManagedField(name, defs?.[name]) ? 2 : 1; + return candidates + .filter((f) => canReadField(perms, objectName, f.value)) + .filter((f) => !isHidden(f.value) || held.has(f.value)) + // objectstack#34807 — a draft-only field cannot filter the list (the + // data door refuses it), so it is not offered; a held condition naming + // one keeps its row, so it can be removed. + .filter((f) => !draftOnly.has(f.value) || held.has(f.value)) + .map((field, index) => ({ field, index, tier: tierOf(field.value) })) + .sort((a, b) => + a.tier - b.tier || + (a.tier === 0 ? columnRank.get(a.field.value)! - columnRank.get(b.field.value)! : a.index - b.index), + ) + .map(({ field }) => field); +} + +/** + * The SORT picker's fields (see `sortFields` in `ListView` for why each rule + * is there): readable, not declared hidden, not relational and one the + * platform orders by; a field the current sort already names stays listed, + * removable only. Also says whether a relational field was left out + * (`excluded`) and whether the current sort names one (`picked`). + */ +export function sortConditionFieldsOf( + candidates: ReadonlyArray<{ value: string; label: string; type: string }>, + opts: { + defs: Record | undefined; + perms: ReturnType; + objectName: string | undefined; + /** The fields the current sort names. */ + inUse: ReadonlySet; + platformSortability: ReturnType; + draftOnly: ReadonlySet; + /** Appended to a relational field's label when the sort keeps it (it orders by the stored id). */ + byIdSuffix: string; + }, +): { fields: Array<{ value: string; label: string; disabled?: boolean; type?: string }>; excluded: boolean; picked: boolean } { + const { defs, perms, objectName, inUse, platformSortability, draftOnly, byIdSuffix } = opts; + let excluded = false; + let picked = false; + const fields: Array<{ value: string; label: string; disabled?: boolean; type?: string }> = []; + for (const field of candidates) { + const offered = canReadField(perms, objectName, field.value) && !isDeclaredHidden(defs, field.value); + if (!offered && !inUse.has(field.value)) continue; + const relational = EXPANDABLE_FIELD_TYPES.has(field.type); + const platformSortable = !draftOnly.has(field.value) && (platformSortability + ? isPlatformSortableField(platformSortability, field.value) + : !UNMATERIALIZED_FIELD_TYPES.has(field.type)); + if (offered && !relational && platformSortable) { + fields.push({ value: field.value, label: field.label, type: field.type }); + continue; + } + if (inUse.has(field.value)) { + if (relational) picked = true; + fields.push({ + value: field.value, + label: relational ? `${field.label} ${byIdSuffix}` : field.label, + disabled: true, + }); + continue; + } + if (relational) excluded = true; + } + return { fields, excluded, picked }; +} + /** The item a value none of a picker's options carries is shown by. */ const OUTSIDE_OPTIONS = 'outside'; @@ -5759,18 +5931,8 @@ export const ListView = React.forwardRef(({ // we normalize to array form so FilterBuilder's value-pickers show // localized option labels (e.g. 网站 instead of "Web"). const buildOptions = (key: string, raw: any): any[] | undefined => { - if (!raw) return undefined; - const arr: Array<{ value: any; label: string; [k: string]: any }> = Array.isArray(raw) - ? raw.map((o: any) => ({ - value: o?.value ?? o, - label: o?.label ?? String(o?.value ?? o), - ...(o && typeof o === 'object' ? o : {}), - })) - : Object.entries(raw as Record).map(([value, meta]) => ({ - value, - label: (meta as any)?.label || value, - ...(meta as any), - })); + const arr = conditionOptionsOf(raw); + if (!arr) return undefined; return schema.objectName ? translateOptions(schema.objectName, key, arr) : arr; }; @@ -5795,48 +5957,10 @@ export const ListView = React.forwardRef(({ }]; }); } else { - fields = Object.entries(objectDef.fields).map(([key, field]: [string, any]) => ({ - value: key, - label: tFieldLabel(key, field.label || key), - type: field.type || 'text', - // With the type, whether the field's value is a list: the filter - // offers a multi-value field only the operators the server takes. - multiple: field.multiple === true, - options: buildOptions(key, field.options), - // ⚠️ objectui#6837 half 2: the READ narrows to `reference` (the only - // spelling the protocol declares — `FieldSchema` refuses `reference_to` - // by name). The EMITTED key is unchanged: it is what this emit's TARGET - // contract declares, and renaming it would be a separate change. - // Target contract here: this file's own local filter-field descriptor, - // which spells it camelCase `referenceTo`. - // ⚠️ The SIBLING branch above (the `schema.columns` fallback) is NOT - // narrowed: it reads a list-view COLUMN, and the spec's `ListColumnSchema` - // declares neither `reference` nor `reference_to` — measured, both refused - // with no rename hint. That is a different question and is filed, not - // answered here. - referenceTo: field.reference, - // objectui#10545 — the display field is read in the DECLARED spelling - // and only in it. `objectDef` is - // `dataSource.getObjectSchema(schema.objectName)`, the object-schema - // def, and `FieldSchema` declares `displayField`; it refuses - // `display_field` (renaming it to `displayField`) and - // `reference_field` (pointing at `referenceVia`, a different key) - // with `unrecognized_keys`. This is the single spelling `plugin-grid`'s - // copy set reads (`RELATIONAL_META_READ_SET`, objectui#7155), and it - // supersedes the objectui#7642 census KEEP, which held only while - // this chain had no `displayField` leg. A stored pre-strict - // `display_field` is folded onto `displayField` once, at ingestion - // (`normalizeSchemaReferenceKeys`, objectui#7650), never here. - // - // No id column is read: `FieldSchema` declares none for a lookup (it - // refuses `idField` and `id_field` alike), so the filter's value - // picker keys the lookup by its own `id` default, and `plugin-grid`'s - // copy set copies no id column either. - displayField: field.displayField, - // ADR-0144 D6: a `record`-mode amount's row pairs with its code - // field, so the filter compares within one currency. - ...(recordCurrencyField(field) ? { currencyField: recordCurrencyField(field) } : {}), - })); + // The definition's fields, read by the one shared mapping + // (`conditionCandidatesOf`, above), so every host of these controls + // offers the same list. + fields = conditionCandidatesOf(objectDef.fields, tFieldLabel, buildOptions); } return fields; @@ -5888,33 +6012,14 @@ export const ListView = React.forwardRef(({ * The predicate is `canReadField`, which the Sort picker shares * (objectui#11943). */ - const filterFields = React.useMemo(() => { - const defs: Record | undefined = objectDef?.fields; - const isHidden = (name: string) => isDeclaredHidden(defs, name); - const held = new Set((currentFilters.conditions ?? []).map((c) => c.field)); - const columnRank = new Map(); - for (const column of effectiveFields) { - const name = columnIdentity(column); - if (name && !columnRank.has(name)) columnRank.set(name, columnRank.size); - } - // 0: a column of this view · 1: another business field · 2: a system - // field · 3: a hidden field kept only because a held condition names it. - const tierOf = (name: string) => - isHidden(name) ? 3 : columnRank.has(name) ? 0 : isSystemManagedField(name, defs?.[name]) ? 2 : 1; - return candidateFields - .filter((f) => canReadField(perms, schema.objectName, f.value)) - .filter((f) => !isHidden(f.value) || held.has(f.value)) - // objectstack#34807 — a draft-only field cannot filter the list (the - // data door refuses it), so it is not offered; a held condition naming - // one keeps its row, so it can be removed. - .filter((f) => !draftOnlyFields.has(f.value) || held.has(f.value)) - .map((field, index) => ({ field, index, tier: tierOf(field.value) })) - .sort((a, b) => - a.tier - b.tier || - (a.tier === 0 ? columnRank.get(a.field.value)! - columnRank.get(b.field.value)! : a.index - b.index), - ) - .map(({ field }) => field); - }, [candidateFields, currentFilters.conditions, effectiveFields, objectDef, schema.objectName, perms, draftOnlyFields]); + const filterFields = React.useMemo(() => filterConditionFieldsOf(candidateFields, { + defs: objectDef?.fields, + perms, + objectName: schema.objectName, + held: new Set((currentFilters.conditions ?? []).map((c) => c.field)), + columnOrder: effectiveFields.map((column) => columnIdentity(column)).filter((name): name is string => !!name), + draftOnly: draftOnlyFields, + }), [candidateFields, currentFilters.conditions, effectiveFields, objectDef, schema.objectName, perms, draftOnlyFields]); // Sort candidates: ALL fields the view can name, minus the ones the sort // cannot honestly reach (objectui#4243 — previously ⊂ filter candidates). @@ -5998,42 +6103,15 @@ export const ListView = React.forwardRef(({ // the request by). const { sortFields, sortHasRelationalField, sortPicksRelationalField } = React.useMemo(() => { - const inUse = new Set(currentSort.map((item) => item.field).filter(Boolean)); - let excluded = false; - // objectui#12528 — the current sort names a relational field (a stored or - // URL sort; the picker never offers one), so the list IS sorted by the - // stored ID: said in one line under the rows, only while it is true. - let picked = false; - const fields: Array<{ value: string; label: string; disabled?: boolean; type?: string }> = []; - const defs: Record | undefined = objectDef?.fields; - for (const field of candidateFields) { - const offered = canReadField(perms, schema.objectName, field.value) && !isDeclaredHidden(defs, field.value); - if (!offered && !inUse.has(field.value)) continue; - const relational = EXPANDABLE_FIELD_TYPES.has(field.type); - // A draft-only field (objectstack#34807) is never sortable: the data - // door refuses it, whatever the projection says. - const platformSortable = !draftOnlyFields.has(field.value) && (platformSortability - ? isPlatformSortableField(platformSortability, field.value) - : !UNMATERIALIZED_FIELD_TYPES.has(field.type)); - // `type` lets the picker name a date's direction as time - // (objectstack#27520): "Oldest → Newest", not "A → Z". - if (offered && !relational && platformSortable) { - fields.push({ value: field.value, label: field.label, type: field.type }); - continue; - } - if (inUse.has(field.value)) { - if (relational) picked = true; - // Listed only because the current sort names it: `disabled`, so its - // own row shows it and can drop it, and nothing can choose it anew. - fields.push({ - value: field.value, - label: relational ? `${field.label} ${t('list.sortByIdSuffix')}` : field.label, - disabled: true, - }); - continue; - } - if (relational) excluded = true; - } + const { fields, excluded, picked } = sortConditionFieldsOf(candidateFields, { + defs: objectDef?.fields, + perms, + objectName: schema.objectName, + inUse: new Set(currentSort.map((item) => item.field).filter(Boolean)), + platformSortability, + draftOnly: draftOnlyFields, + byIdSuffix: t('list.sortByIdSuffix'), + }); return { sortFields: fields, sortHasRelationalField: excluded, sortPicksRelationalField: picked }; }, [candidateFields, currentSort, t, platformSortability, perms, schema.objectName, objectDef, draftOnlyFields]); @@ -6116,9 +6194,7 @@ export const ListView = React.forwardRef(({ field: s.field, order: s.order, })); - const items: SortItem[] = picked.length === 1 && currentSort.length >= 2 - ? [picked[0], ...currentSort.filter((s) => s.field !== picked[0].field)] - : picked; + const items: SortItem[] = withHeaderSortPick(currentSort, picked); setCurrentSort(items); setServerPage(1); emitSortChange(items); diff --git a/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx b/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx index 8671c58b118..b95c531cb6f 100644 --- a/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx +++ b/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx @@ -502,6 +502,13 @@ export interface ConditionChipRowProps { end?: React.ReactNode; /** The reader may add a filter (`userActions.filter`); `false` ⇒ no 「Filter」 and no 「+」. */ filterOffered?: boolean; + /** + * objectstack#35892 — where the row may be narrow (a record page's related + * tab, in a drawer too): below 28rem of the row's own width the 「Sort」 and + * 「Filter」 buttons and the sort chip keep their icon alone, named by their + * `aria-label` and `title`. + */ + collapsibleLabels?: boolean; className?: string; } @@ -536,6 +543,7 @@ export function ConditionChipRow({ renderSortPanel, end, filterOffered = true, + collapsibleLabels = false, className, }: ConditionChipRowProps) { const { t } = useListConditionTranslation(); @@ -560,6 +568,12 @@ export function ConditionChipRow({ } const fieldOf = (list: ReadonlyArray, name: string) => list.find((f) => f.value === name); + // objectstack#35892 — under `collapsibleLabels`, a button's words go below + // 28rem of the row's width (the row is its own container, `@container/conditions`). + const collapsingLabel = collapsibleLabels ? 'hidden @[28rem]/conditions:inline' : undefined; + const sortChipName = sort.length > 0 + ? t('listConditions.chips.sortedBy', { field: fieldOf(sortFields, sort[0].field)?.label ?? sort[0].field }) + : t('listConditions.chips.sort'); const filterPopover = (key: string, trigger: React.ReactNode, conditionId?: string) => ( setOpenChip(open ? key : null)}> @@ -586,7 +600,11 @@ export function ConditionChipRow({ aria-label={t('listConditions.chips.region')} // One line at every width: what does not fit scrolls sideways // (objectstack#35878). - className={cn('flex min-w-0 flex-1 flex-nowrap items-center gap-1.5 overflow-x-auto', className)} + className={cn( + 'flex min-w-0 flex-1 flex-nowrap items-center gap-1.5 overflow-x-auto', + collapsibleLabels && '@container/conditions', + className, + )} data-testid="condition-chips" > {/* objectstack#35878 — the sort, at any number of levels, is ONE chip: @@ -602,12 +620,11 @@ export function ConditionChipRow({ className={cn(CHIP_CLASS, ROW_TOUCH_TARGET, 'border-primary/30 bg-primary/5 text-foreground hover:bg-primary/10')} data-testid="condition-sort" data-levels={sort.length} + {...(collapsibleLabels ? { 'aria-label': sortChipName, title: sortChipName } : {})} >
{conditionRow &&
{conditionRow}
} + {bulkDeleteOutcome && ( +

0 ? 'text-destructive' : 'text-muted-foreground')} + > + {bulkDeleteOutcome.failed > 0 + ? t('objectActions.bulkDeletePartial', { succeeded: bulkDeleteOutcome.succeeded, failed: bulkDeleteOutcome.failed }) + : t('objectActions.bulkDeleteSuccess', { count: bulkDeleteOutcome.succeeded, label: objectLabel({ name: api, label: objectSchema?.label ?? api }) })} +

+ )} {loadFailure ? ( ) : loading && relatedData.length === 0 ? ( diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.tab-35892.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.tab-35892.test.tsx index 06f4631034f..fea150bf90d 100644 --- a/ui/packages/plugin-detail/src/__tests__/RelatedList.tab-35892.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.tab-35892.test.tsx @@ -20,6 +20,7 @@ import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest'; import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom'; import * as React from 'react'; +import { FilterScopeProvider } from '@object-ui/react'; import { RelatedList } from '../RelatedList'; import { RelatedListConditionsSlotContext, @@ -78,14 +79,16 @@ function dataSourceFor() { const renderCapturing = (props: RelatedListConditionsProps) => ; -function Tab({ parentId = 'O-1', dataSource, onTotal, onRowDelete, slot = renderCapturing }: { +function Tab({ parentId = 'O-1', dataSource, onTotal, onRowDelete, slot = renderCapturing, reader = 'u-1' }: { parentId?: string; + reader?: string; dataSource: ReturnType; onTotal?: (n: number) => void; onRowDelete?: (row: any) => Promise | void; slot?: ((props: RelatedListConditionsProps) => React.ReactNode) | null; }) { return ( + @@ -104,6 +107,7 @@ function Tab({ parentId = 'O-1', dataSource, onTotal, onRowDelete, slot = render + ); } @@ -225,7 +229,7 @@ describe('the related tab is the child object\'s full list (objectstack#35892)', expect(document.querySelector('[data-related-enlarged-conditions]')).not.toBeNull(); }); - it('the bulk bar\'s delete asks once, counting the rows, then deletes each and reads again', async () => { + it('the bulk bar\'s delete asks once, counting the rows; without a batch delete it deletes each row, then reads again', async () => { const ds = dataSourceFor(); const onRowDelete = vi.fn(async () => undefined); render(); @@ -237,5 +241,54 @@ describe('the related tab is the child object\'s full list (objectstack#35892)', fireEvent.click(document.querySelector('[data-related-bulk-delete-confirm]')!); await waitFor(() => expect(onRowDelete).toHaveBeenCalledTimes(3)); await waitFor(() => expect(ds.find.mock.calls.length).toBeGreaterThan(reads)); + expect((await screen.findByRole('status')).textContent).toBe('Deleted 3 quote records'); + }); + + it('with the data source\'s batch delete, the selection goes in ONE call, not row by row', async () => { + const ds = Object.assign(dataSourceFor(), { bulkDelete: vi.fn(async () => 3) }); + const onRowDelete = vi.fn(async () => undefined); + render(); + await waitFor(() => expect(grid()?.schema.data.items).toHaveLength(12)); + act(() => grid().props.onBulkDelete(ROWS.slice(0, 3))); + fireEvent.click(await screen.findByText('Delete', { selector: '[data-related-bulk-delete-confirm]' })); + await waitFor(() => expect(ds.bulkDelete).toHaveBeenCalledTimes(1)); + expect(ds.bulkDelete).toHaveBeenCalledWith('quote', ['q1', 'q2', 'q3']); + expect(onRowDelete).not.toHaveBeenCalled(); + expect((await screen.findByRole('status')).textContent).toBe('Deleted 3 quote records'); + }); + + it('a partial failure says how many went and how many did not, on the batch path and row by row', async () => { + const batch = Object.assign(dataSourceFor(), { + bulkDelete: vi.fn(async () => ({ succeeded: 2, errors: [{ id: 'q3', error: 'refused' }] })), + }); + const first = render(); + await waitFor(() => expect(grid()?.schema.data.items).toHaveLength(12)); + act(() => grid().props.onBulkDelete(ROWS.slice(0, 3))); + fireEvent.click(await screen.findByText('Delete', { selector: '[data-related-bulk-delete-confirm]' })); + expect((await screen.findByRole('status')).textContent).toBe('2 deleted, 1 failed'); + first.unmount(); + h.byType = {}; + + const rowByRow = dataSourceFor(); + const onRowDelete = vi.fn(async (row: any) => { if (row.id === 'q2') throw new Error('refused'); }); + render(); + await waitFor(() => expect(grid()?.schema.data.items).toHaveLength(12)); + act(() => grid().props.onBulkDelete(ROWS.slice(0, 3))); + fireEvent.click(await screen.findByText('Delete', { selector: '[data-related-bulk-delete-confirm]' })); + await waitFor(() => expect(onRowDelete).toHaveBeenCalledTimes(3)); + expect((await screen.findByRole('status')).textContent).toBe('2 deleted, 1 failed'); + }); + + it('is held per reader: another account signed in on the same record starts from the default', async () => { + const ds = dataSourceFor(); + const first = render(); + await waitFor(() => expect(grid()?.schema.data.items).toHaveLength(12)); + act(() => conditions().props.onFiltersChange(AMOUNT_GROUP, AMOUNT_OVER_600)); + await waitFor(() => expect(grid().schema.data.items).toHaveLength(6)); + first.unmount(); + h.byType = {}; + render(); + await waitFor(() => expect(grid()?.schema.data.items).toHaveLength(12)); + expect(conditions().props.filters.conditions).toEqual([]); }); }); diff --git a/ui/packages/plugin-detail/src/useDetailTranslation.ts b/ui/packages/plugin-detail/src/useDetailTranslation.ts index c0539006611..20815248982 100644 --- a/ui/packages/plugin-detail/src/useDetailTranslation.ts +++ b/ui/packages/plugin-detail/src/useDetailTranslation.ts @@ -127,6 +127,11 @@ export const DETAIL_DEFAULT_TRANSLATIONS: Record = { 'detail.deleteRowsConfirmation': '{{count}} records will be deleted. This cannot be undone.', 'detail.deleteRowsConfirmation_one': '{{count}} record will be deleted. This cannot be undone.', 'detail.deleteRowsConfirmation_other': '{{count}} records will be deleted. This cannot be undone.', + // The bulk delete's outcome, in the list page's own words (`objectActions`). + 'objectActions.bulkDeleteSuccess': 'Deleted {{count}} {{label}} records', + 'objectActions.bulkDeleteSuccess_one': 'Deleted {{count}} {{label}} record', + 'objectActions.bulkDeleteSuccess_other': 'Deleted {{count}} {{label}} records', + 'objectActions.bulkDeletePartial': '{{succeeded}} deleted, {{failed}} failed', 'detail.actions': 'Actions', 'detail.previousPage': 'Previous', 'detail.nextPage': 'Next', From 4e82b601e568cf07a2e5254c1996d261de933194 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 17:26:42 +0000 Subject: [PATCH 7/8] fix(ui): the related tab's batch delete needs an object name to send Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgTKEPqtmiK9SGpHsmW --- ui/packages/plugin-detail/src/RelatedList.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ui/packages/plugin-detail/src/RelatedList.tsx b/ui/packages/plugin-detail/src/RelatedList.tsx index b8eedbc7de0..389078cab32 100644 --- a/ui/packages/plugin-detail/src/RelatedList.tsx +++ b/ui/packages/plugin-detail/src/RelatedList.tsx @@ -2579,7 +2579,7 @@ export const RelatedList: React.FC = ({ if (rows.length === 0) return; const ids = rows.map((row) => String(row.id ?? row._id)); let succeeded = 0; - if (typeof dataSource?.bulkDelete === 'function') { + if (api && typeof dataSource?.bulkDelete === 'function') { try { const answer = await dataSource.bulkDelete(api, ids); succeeded = Math.min(ids.length, typeof answer === 'number' ? answer : answer.succeeded); @@ -4378,7 +4378,7 @@ export const RelatedList: React.FC = ({ > {bulkDeleteOutcome.failed > 0 ? t('objectActions.bulkDeletePartial', { succeeded: bulkDeleteOutcome.succeeded, failed: bulkDeleteOutcome.failed }) - : t('objectActions.bulkDeleteSuccess', { count: bulkDeleteOutcome.succeeded, label: objectLabel({ name: api, label: objectSchema?.label ?? api }) })} + : t('objectActions.bulkDeleteSuccess', { count: bulkDeleteOutcome.succeeded, label: objectLabel({ name: api ?? '', label: objectSchema?.label ?? api ?? '' }) })}

)} {loadFailure ? ( From 5b76d7a5ed9310789ae70b291362bd111e0c73ce Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 17:48:53 +0000 Subject: [PATCH 8/8] fix(ui): the related tab's bulk delete reads the child object's row delete grant The batch call is a write site of its own, so the tab offers it only where the relatedRowDelete row of the affordance map allows it, beside the row delete the host hands in, and the write census names it. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgTKEPqtmiK9SGpHsmW --- ui/packages/plugin-detail/src/RelatedList.tsx | 10 ++++++++-- .../plugin-form/src/affordanceGrantMap-12082.test.tsx | 4 ++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/ui/packages/plugin-detail/src/RelatedList.tsx b/ui/packages/plugin-detail/src/RelatedList.tsx index 389078cab32..ad2b9c0e63a 100644 --- a/ui/packages/plugin-detail/src/RelatedList.tsx +++ b/ui/packages/plugin-detail/src/RelatedList.tsx @@ -3599,6 +3599,11 @@ export const RelatedList: React.FC = ({ // the child object. const tabInlineEdit = tabList && resolveAffordance('listInlineEdit', { objectSchema, objectName: api, perms }).allowed; + // The bulk bar's delete is one batch call to the data source, so it reads + // the child object's `relatedRowDelete` row itself, beside the row delete + // the host hands in (objectstack#35892). + const tabBulkDelete = !!onRowDelete + && resolveAffordance('relatedRowDelete', { objectSchema, objectName: api, perms }).allowed; const viewSchema = React.useMemo(() => { if (schema) return schema; @@ -3805,7 +3810,8 @@ export const RelatedList: React.FC = ({ ...(tabFindParams ? { findParams: tabFindParams } : {}), ...(objectSchema?.fields ? { objectFields: objectSchema.fields } : {}), ...(onRowEdit ? { onEdit: onRowEdit } : {}), - ...(onRowDelete ? { onDelete: handleDeleteRow, onBulkDelete: handleBulkDeleteRows } : {}), + ...(onRowDelete ? { onDelete: handleDeleteRow } : {}), + ...(tabBulkDelete ? { onBulkDelete: handleBulkDeleteRows } : {}), ...(writeTabColumnState ? { onColumnStateChange: writeTabColumnState } : {}), }; } @@ -3822,7 +3828,7 @@ export const RelatedList: React.FC = ({ ...(onRowDelete ? { onDelete: handleDeleteRow } : {}), ...(writeTabColumnState ? { onColumnStateChange: writeTabColumnState } : {}), }; - }, [writeTabColumnState, enlargedGrid, windowed, total, currentPage, effectivePageSize, relatedData.length, hasMore, sortedData.length, paginatedData.length, activeSort, handleTableSort, objectSchema, onRowEdit, onRowDelete, handleDeleteRow, tabList, tabRecordCountLead, pickTabSummary, tabFindParams, handleBulkDeleteRows]); + }, [writeTabColumnState, enlargedGrid, windowed, total, currentPage, effectivePageSize, relatedData.length, hasMore, sortedData.length, paginatedData.length, activeSort, handleTableSort, objectSchema, onRowEdit, onRowDelete, handleDeleteRow, tabList, tabRecordCountLead, pickTabSummary, tabFindParams, handleBulkDeleteRows, tabBulkDelete]); // objectstack#35601 — a stateful child (tasks) is grouped by its status on // the related tab: open groups first, completed last (`statusGroupsOf`). diff --git a/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx b/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx index 500efd81612..f619add6bca 100644 --- a/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx +++ b/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx @@ -853,6 +853,10 @@ const WRITE_SITES: Record = { // the picked rows (relatedRowEdit). 'packages/plugin-detail/src/RelatedList.tsx :: RelatedList > handleAddRecords :: batch': mapped(['relatedNew', 'relatedRowEdit'], RELATED_LIST), + // The related tab's bulk delete (objectstack#35892): one batch call to the + // data source, offered beside the host's row delete and read here. + 'packages/plugin-detail/src/RelatedList.tsx :: RelatedList > handleConfirmBulkDelete :: delete': + mapped(['relatedRowDelete'], RELATED_LIST), 'packages/plugin-detail/src/renderers/record-related-list.tsx :: RecordRelatedListBody :: delete': { ...mapped(['relatedRowDelete'], RELATED_LIST_BLOCK), note: "the FALLBACK remove (an `add` config, no host delete) reads the same row the host's delete reads, so it never puts back a delete the host withheld",