diff --git a/.changeset/35892-related-tab-full-list.md b/.changeset/35892-related-tab-full-list.md new file mode 100644 index 00000000000..bcfa1ae29f8 --- /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 export `ListConditionsBlock` (`@object-ui/plugin-list`, the condition row as a host element, not a registered node type) and its `ListConditionsHostProps`; a new slot `RelatedListConditionsSlotContext` and its `RelatedListConditionsProps` (`@object-ui/plugin-detail`), which the record page fills (`@object-ui/app-shell`); new exports `ConditionDiscardButton` and its type `ConditionDiscardButtonProps` (`@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`, and the count family `detail.deleteRowsConfirmation` with its plural slots `_zero`, `_one`, `_two`, `_few`, `_many`, `_other` as each pack needs them); 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, deletes the selection in one batch call where the data source has one, and says how many rows went and how many did not), 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, for that reader only, 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/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/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 0fbd83c6947..79270eb45f5 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -83,7 +83,8 @@ import type { ConsoleActionDispatch } from '../consoleActionDispatch.js'; import { useRecordApprovals, openApprovalOf, isSubmitterOf } from '../hooks/useRecordApprovals.js'; import { RecordAttachmentsPanel } from './RecordAttachmentsPanel.js'; import { RecordApprovalsPanel } from './RecordApprovalsPanel.js'; -import { ApprovalBandOnceScope, RecordStageMenu } from '@object-ui/plugin-detail'; +import { ApprovalBandOnceScope, RecordStageMenu, RelatedListConditionsSlotContext } from '@object-ui/plugin-detail'; +import { renderRelatedListConditions } from './relatedListConditions.js'; import { DeclaredActionsBar } from './DeclaredActionsBar.js'; import { SYS_APPROVAL_REQUEST_OBJECT, @@ -5603,6 +5604,8 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri attachments: !!(filesEnabled && !hasAttachments && pureRecordId), }); const pageTree = ( + // objectstack#35892 — a related tab draws the list page's condition row. + @@ -6103,6 +6106,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri + ); // A drawer draws this view embedded and is its own host. A page is the host // of the drawer its related rows and lookups open over it diff --git a/ui/packages/app-shell/src/views/relatedListConditions.tsx b/ui/packages/app-shell/src/views/relatedListConditions.tsx new file mode 100644 index 00000000000..6b979ab1ab8 --- /dev/null +++ b/ui/packages/app-shell/src/views/relatedListConditions.tsx @@ -0,0 +1,32 @@ +/** + * 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. + */ + +/** + * The condition row a record page's related tab draws (objectstack#35892): + * the list page's own Sort and Filter, `@object-ui/plugin-list`'s + * `ListConditionsBlock`. `@object-ui/plugin-detail` draws the tab but cannot + * import `plugin-list` (which depends on it), so the record page hands the + * block in through `RelatedListConditionsSlotContext`. It loads with the first + * tab that draws it, as `plugin-list` loads for the list page. + */ + +import { lazy, Suspense } from 'react'; +import type { RelatedListConditionsProps } from '@object-ui/plugin-detail'; + +const ListConditionsBlock = lazy(() => + import('@object-ui/plugin-list').then((m) => ({ default: m.ListConditionsBlock })), +); + +/** The record page's `RelatedListConditionsSlotContext` value. */ +export function renderRelatedListConditions(props: RelatedListConditionsProps) { + return ( + + + + ); +} 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 4c2baf5e26c..d4bb7b921b4 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1814,6 +1814,16 @@ const ar = { deleteRow: "حذف", deleteRowConfirmation: "حذف “{{name}}”؟", deleteRowTitle: "حذف السجل", + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: "لا توجد سجلات تطابق عامل التصفية", + deleteRowsTitle: "حذف السجلات المحددة", + deleteRowsConfirmation: "سيتم حذف {{count}} سجل. لا يمكن التراجع عن ذلك.", + deleteRowsConfirmation_zero: "سيتم حذف {{count}} سجل. لا يمكن التراجع عن ذلك.", + deleteRowsConfirmation_one: "سيتم حذف {{count}} سجل. لا يمكن التراجع عن ذلك.", + deleteRowsConfirmation_two: "سيتم حذف سجلين ({{count}}). لا يمكن التراجع عن ذلك.", + deleteRowsConfirmation_few: "سيتم حذف {{count}} سجلات. لا يمكن التراجع عن ذلك.", + deleteRowsConfirmation_many: "سيتم حذف {{count}} سجلًا. لا يمكن التراجع عن ذلك.", + deleteRowsConfirmation_other: "سيتم حذف {{count}} سجل. لا يمكن التراجع عن ذلك.", actions: "الإجراءات", previousPage: "السابق", nextPage: "التالي", @@ -5698,6 +5708,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 9bc2c0d3e4c..4cd2e8c99df 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1607,6 +1607,12 @@ 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: "{{count}} Datensätze werden gelöscht. Dies kann nicht rückgängig gemacht werden.", + deleteRowsConfirmation_one: "{{count}} Datensatz wird gelöscht. Dies kann nicht rückgängig gemacht werden.", + deleteRowsConfirmation_other: "{{count}} Datensätze werden gelöscht. Dies kann nicht rückgängig gemacht werden.", actions: "Aktionen", previousPage: "Zurück", nextPage: "Weiter", @@ -5092,6 +5098,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 a3b02b94376..0c2ae96d915 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1828,6 +1828,12 @@ 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: '{{count}} records will be deleted. This cannot be undone.', + deleteRowsConfirmation_one: '{{count}} record will be deleted. This cannot be undone.', + deleteRowsConfirmation_other: '{{count}} records will be deleted. This cannot be undone.', actions: 'Actions', previousPage: 'Previous', nextPage: 'Next', @@ -5852,6 +5858,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 676aa8d2452..f443d8ca588 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1660,6 +1660,13 @@ 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: "Se eliminarán {{count}} registros. Esto no se puede deshacer.", + deleteRowsConfirmation_one: "Se eliminará {{count}} registro. Esto no se puede deshacer.", + deleteRowsConfirmation_many: "Se eliminarán {{count}} de registros. Esto no se puede deshacer.", + deleteRowsConfirmation_other: "Se eliminarán {{count}} registros. Esto no se puede deshacer.", actions: "Acciones", previousPage: "Anterior", nextPage: "Siguiente", @@ -5244,6 +5251,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 c51bb5b5ef3..1980b816713 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1657,6 +1657,13 @@ 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: "{{count}} enregistrements seront supprimés. Cette action est irréversible.", + deleteRowsConfirmation_one: "{{count}} enregistrement sera supprimé. Cette action est irréversible.", + deleteRowsConfirmation_many: "{{count}} d'enregistrements seront supprimés. Cette action est irréversible.", + deleteRowsConfirmation_other: "{{count}} enregistrements seront supprimés. Cette action est irréversible.", actions: "Actions", previousPage: "Précédent", nextPage: "Suivant", @@ -5240,6 +5247,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 cc871a6d741..09a69fae360 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1615,6 +1615,12 @@ const ja = { history: "履歴", historyEmpty: "履歴はまだありません", deleteRowTitle: "レコードを削除", + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: "フィルターに一致するレコードはありません", + deleteRowsTitle: "選択したレコードを削除", + deleteRowsConfirmation: "{{count}} 件のレコードを削除します。この操作は元に戻せません。", + deleteRowsConfirmation_one: "{{count}} 件のレコードを削除します。この操作は元に戻せません。", + deleteRowsConfirmation_other: "{{count}} 件のレコードを削除します。この操作は元に戻せません。", createdBy: "作成者", updatedBy: "更新者", created: "作成", @@ -5094,6 +5100,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 b135096e4d4..bab68eebc15 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1607,6 +1607,12 @@ const ko = { deleteRow: "삭제", deleteRowConfirmation: "“{{name}}”을(를) 삭제하시겠습니까?", deleteRowTitle: "레코드 삭제", + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: "필터와 일치하는 레코드가 없습니다", + deleteRowsTitle: "선택한 레코드 삭제", + deleteRowsConfirmation: "레코드 {{count}}개가 삭제됩니다. 이 작업은 되돌릴 수 없습니다.", + deleteRowsConfirmation_one: "레코드 {{count}}개가 삭제됩니다. 이 작업은 되돌릴 수 없습니다.", + deleteRowsConfirmation_other: "레코드 {{count}}개가 삭제됩니다. 이 작업은 되돌릴 수 없습니다.", actions: "작업", previousPage: "이전", nextPage: "다음", @@ -5091,6 +5097,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 6db720fc3fd..6b26fc4784d 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1657,6 +1657,13 @@ 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: "{{count}} registros serão excluídos. Esta ação não pode ser desfeita.", + deleteRowsConfirmation_one: "{{count}} registro será excluído. Esta ação não pode ser desfeita.", + deleteRowsConfirmation_many: "{{count}} de registros serão excluídos. Esta ação não pode ser desfeita.", + deleteRowsConfirmation_other: "{{count}} registros serão excluídos. Esta ação não pode ser desfeita.", actions: "Ações", previousPage: "Anterior", nextPage: "Próximo", @@ -5239,6 +5246,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 1d1a15796a9..af90b6f0c1c 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1722,6 +1722,14 @@ const ru = { history: "История", historyEmpty: "Истории пока нет", deleteRowTitle: "Удалить запись", + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: "Нет записей, соответствующих фильтру", + deleteRowsTitle: "Удалить выбранные записи", + deleteRowsConfirmation: "{{count}} записи будут удалены. Это действие нельзя отменить.", + deleteRowsConfirmation_one: "{{count}} запись будет удалена. Это действие нельзя отменить.", + deleteRowsConfirmation_few: "{{count}} записи будут удалены. Это действие нельзя отменить.", + deleteRowsConfirmation_many: "{{count}} записей будут удалены. Это действие нельзя отменить.", + deleteRowsConfirmation_other: "{{count}} записи будут удалены. Это действие нельзя отменить.", createdBy: "Создано", updatedBy: "Обновлено", // objectui#3863 — base key, answering only a call made without a count: since @@ -5405,6 +5413,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 32a00d683b4..4ff3c34527b 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1528,6 +1528,12 @@ const zh = { deleteRow: '删除', deleteRowConfirmation: '确定要删除“{{name}}”吗?', deleteRowTitle: '删除记录', + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: '没有符合筛选条件的记录', + deleteRowsTitle: '删除选中的记录', + deleteRowsConfirmation: '将删除 {{count}} 条记录,删除后无法恢复。', + deleteRowsConfirmation_one: '将删除 {{count}} 条记录,删除后无法恢复。', + deleteRowsConfirmation_other: '将删除 {{count}} 条记录,删除后无法恢复。', actions: '操作', previousPage: '上一页', nextPage: '下一页', @@ -5151,6 +5157,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 d8d3da10050..da940f50db3 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1528,6 +1528,12 @@ const zhHant = { deleteRow: '刪除', deleteRowConfirmation: '確定要刪除“{{name}}”嗎?', deleteRowTitle: '刪除記錄', + // objectstack#35892 — the related tab: a filter that matches nothing, and its bulk delete. + relatedNoMatches: '沒有符合篩選條件的記錄', + deleteRowsTitle: '刪除選中的記錄', + deleteRowsConfirmation: '將刪除 {{count}} 條記錄,刪除後無法恢復。', + deleteRowsConfirmation_one: '將刪除 {{count}} 條記錄,刪除後無法恢復。', + deleteRowsConfirmation_other: '將刪除 {{count}} 條記錄,刪除後無法恢復。', actions: '操作', previousPage: '上一頁', nextPage: '下一頁', @@ -5151,6 +5157,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 92e56c10dc7..a1279838c36 100644 --- a/ui/packages/plugin-detail/README.md +++ b/ui/packages/plugin-detail/README.md @@ -720,6 +720,26 @@ 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`'s `ListConditionsBlock`, which the record page +hands in through `RelatedListConditionsSlotContext`, since that package depends +on this one; a host that supplies none gets no condition row): **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..ad2b9c0e63a 100644 --- a/ui/packages/plugin-detail/src/RelatedList.tsx +++ b/ui/packages/plugin-detail/src/RelatedList.tsx @@ -85,10 +85,11 @@ import { type ActionDef, type ActionResult, type FilterNode, + withHeaderSortPick, } from '@object-ui/core'; import { useSafeFieldLabel, useRecordContext, useRecordPagePreferences, type RelatedListPreference } from '@object-ui/react'; import { usePermissions } from '@object-ui/permissions'; -import { useDisplayLocale, useLocalization, resolveFieldCurrency, recordCurrencyField, recordCurrencyPath, withFollowedParent } from '@object-ui/i18n'; +import { useObjectLabel, useDisplayLocale, useLocalization, resolveFieldCurrency, recordCurrencyField, recordCurrencyPath, withFollowedParent } from '@object-ui/i18n'; import { useDetailTranslation } from './useDetailTranslation'; import { isMaskedDetailFieldType } from './fieldEnrichment'; import { @@ -99,11 +100,13 @@ import { RelatedCardCountContext, RelatedEnlargeContext, RelatedListCompactContext, + RelatedListConditionsSlotContext, RelatedListEnlargedContext, RelatedListTotalReportContext, 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,67 @@ 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; + +/** 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 +1374,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 +1539,53 @@ 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 reader, the parent record and this list's relationship, as the list + // page's draft is keyed by its reader: another account signed in on the + // same tab starts from the default. + const readerScope = useFilterScope(); + const tabRecord = enlargedFace && !schema && (type === 'grid' || type === 'table') + && ownRelationshipId && parentId !== undefined && parentId !== null && parentId !== '' + ? `${readerScope.currentUserId ?? ''}|${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); + // Supplied by the host (`plugin-list`'s row, which this package cannot + // import: it depends on this one): without it the tab draws no condition row. + const renderListConditions = React.useContext(RelatedListConditionsSlotContext); + // 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 +1597,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 +1623,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 +2151,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 +2220,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 +2238,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 +2257,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 +2268,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 +2286,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 +2391,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 +2561,38 @@ export const RelatedList: React.FC = ({ } setDeleteTarget(null); }, [deleteTarget, onRowDelete]); + // objectstack#35892 — the related tab's floating bar deletes the selected + // rows (up to every matching row, with "select all"): one confirm that + // counts them, then the data source's batch delete in one call where it + // has one, else every row through the row delete this list was handed, + // settled together as the list page settles them. One re-read, and the + // outcome stays on screen: how many went, and how many did not. + const [bulkDeleteTargets, setBulkDeleteTargets] = React.useState(null); + const [bulkDeleteOutcome, setBulkDeleteOutcome] = React.useState<{ succeeded: number; failed: number } | null>(null); + const { objectLabel } = useObjectLabel(); + const handleBulkDeleteRows = React.useCallback((rows: any[]) => { + if (rows.length > 0) setBulkDeleteTargets(rows); + }, []); + const handleConfirmBulkDelete = React.useCallback(async () => { + const rows = (bulkDeleteTargets ?? []).filter((row) => row?.id != null || row?._id != null); + setBulkDeleteTargets(null); + if (rows.length === 0) return; + const ids = rows.map((row) => String(row.id ?? row._id)); + let succeeded = 0; + 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); + } catch (err) { + console.error('[RelatedList] bulk delete failed', err); + } + } else if (onRowDelete) { + const settled = await Promise.allSettled(rows.map((row) => Promise.resolve(onRowDelete(row)))); + succeeded = settled.filter((result) => result.status === 'fulfilled').length; + } + setBulkDeleteOutcome({ succeeded, failed: ids.length - succeeded }); + setRefreshNonce((n) => n + 1); + }, [bulkDeleteTargets, onRowDelete, dataSource, api]); /** * May the caller Add existing here? The write's row of the affordance-to-grant @@ -3212,20 +3389,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 +3443,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 +3471,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 +3493,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 +3594,16 @@ 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; + // 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; @@ -3420,12 +3628,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 +3739,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 +3764,57 @@ 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 } : {}), + ...(tabBulkDelete ? { onBulkDelete: handleBulkDeleteRows } : {}), + ...(writeTabColumnState ? { onColumnStateChange: writeTabColumnState } : {}), + }; + } return { manualPagination: true, rowCount, @@ -3565,9 +3826,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, tabBulkDelete]); // objectstack#35601 — a stateful child (tasks) is grouped by its status on // the related tab: open groups first, completed last (`statusGroupsOf`). @@ -3644,7 +3905,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 +4055,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 (the host's `RelatedListConditionsSlotContext`): + // 「排序」 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 && renderListConditions ? renderListConditions({ + objectName: api, + objectDef: objectSchema, + shownFields: tabShownFields, + sort: tabConditions.sort, + onSortChange: (sort) => patchTabConditions({ sort }), + filters: tabConditions.filters, + onFiltersChange: (filters, filterNode) => patchTabConditions({ filters, filterNode }), + 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}
} + {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 ? (
{t('detail.loading')}
) : isEmpty ? (
- {t('detail.noRelatedRecords')} + {tabFilterNode !== undefined ? t('detail.relatedNoMatches') : t('detail.noRelatedRecords')}
) : ( <> @@ -4088,18 +4401,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 +4427,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..fea150bf90d --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.tab-35892.test.tsx @@ -0,0 +1,294 @@ +/** + * 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 (the host's, through + * `RelatedListConditionsSlotContext`), 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 { FilterScopeProvider } from '@object-ui/react'; +import { RelatedList } from '../RelatedList'; +import { + RelatedListConditionsSlotContext, + RelatedListEnlargedContext, + RelatedListTotalReportContext, + type RelatedListConditionsProps, +} from '../relatedListCompact'; +import { resetRelatedTabConditionsForTests } from '../relatedTabConditions'; + +/** What `RelatedList` hands each `SchemaRenderer` by node type, and the host's condition row its props. */ +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 }; + return null; + } + return { ...actual, SchemaRenderer: CapturingRenderer }; +}); + +/** The host's condition row (the record page passes `plugin-list`'s block). */ +function CapturingConditions(props: RelatedListConditionsProps) { + h.byType.conditions = { schema: undefined, props }; + return props.onDiscard + ? + : null; +} + +beforeAll(() => { + Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1440 }); +}); + +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 })), + }; +} + +const renderCapturing = (props: RelatedListConditionsProps) => ; + +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 ( + + + + + + + + + + ); +} + +const lastFind = (find: ReturnType) => find.mock.calls[find.mock.calls.length - 1][1]; +const conditions = () => h.byType.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'); + expect(h.byType['list-conditions'], 'a host element, never a node').toBeUndefined(); + }); + + it('a host that supplies no condition row gets the table without one', async () => { + render(); + await waitFor(() => expect(grid()?.schema.data.items).toHaveLength(12)); + expect(conditions()).toBeUndefined(); + expect(document.querySelector('[data-related-enlarged-conditions]')).toBeNull(); + }); + + 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; without a batch delete it deletes each row, then 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('3 records will be deleted. 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)); + 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/__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/index.tsx b/ui/packages/plugin-detail/src/index.tsx index 2f39740cf2b..4048fd20f2f 100644 --- a/ui/packages/plugin-detail/src/index.tsx +++ b/ui/packages/plugin-detail/src/index.tsx @@ -239,6 +239,10 @@ export { RecordBodyTablesContext } from './relatedListCompact'; // the host's editor through this slot. export { RecordBodyTableEditorSlotContext } from './relatedListCompact'; export type { RecordBodyTableEditorSlot } from './relatedListCompact'; +// objectstack#35892 — the related tab's condition row, supplied by the host +// (`plugin-list`'s `ListConditionsBlock`) through this slot. +export { RelatedListConditionsSlotContext } from './relatedListCompact'; +export type { RelatedListConditionsProps } from './relatedListCompact'; // objectstack#27056 — for the app-shell record drawer's prefetch: it warms // the next record's related counts before the reader steps to it. export { prefetchRelatedCounts, relatedCountTargetsIn } from './useRelatedCounts'; diff --git a/ui/packages/plugin-detail/src/relatedListCompact.ts b/ui/packages/plugin-detail/src/relatedListCompact.ts index 2982f15d773..a7a875fba15 100644 --- a/ui/packages/plugin-detail/src/relatedListCompact.ts +++ b/ui/packages/plugin-detail/src/relatedListCompact.ts @@ -7,6 +7,8 @@ */ import * as React from 'react'; +import type { FilterBuilderRowGroup, SortItem } from '@object-ui/components'; +import type { DataSource } from '@object-ui/types'; /** * `true` inside the record page's related column (objectstack#26678): a @@ -98,6 +100,33 @@ export interface RecordBodyTableEditorSlot { /** The open edit state's body-table editor slot, or `null` (see {@link RecordBodyTableEditorSlot}). */ export const RecordBodyTableEditorSlotContext = React.createContext(null); +/** + * What a related list opened as the record page's tab draws as its condition + * row (objectstack#35892): the list page's own Sort and Filter, supplied by the + * host because the row lives in `@object-ui/plugin-list`, which depends on + * this package. The host draws `plugin-list`'s `ListConditionsBlock`; while + * the value is `null` (a host that supplies none) the tab draws no condition + * row. A host element, never a node type a page could carry. + */ +export interface RelatedListConditionsProps { + objectName?: string; + objectDef?: { fields?: Record } | null; + /** The fields the tab's table shows, in column order. */ + shownFields?: ReadonlyArray; + sort: ReadonlyArray; + onSortChange: (next: SortItem[]) => void; + filters: FilterBuilderRowGroup; + /** The next filter group, with the query node it applies (`undefined` = no filter). */ + onFiltersChange: (next: FilterBuilderRowGroup, filter: unknown[] | undefined) => void; + /** 「Discard」 at the row's end, passed only while the reader changed anything. */ + onDiscard?: () => void; + /** Where the names of the records a lookup condition points at are read. */ + dataSource?: Pick | null; +} + +/** The host's condition row for a related tab, or `null` (see {@link RelatedListConditionsProps}). */ +export const RelatedListConditionsSlotContext = React.createContext<((props: RelatedListConditionsProps) => React.ReactNode) | null>(null); + /** Enlarge a related list in place — the host's `?related=` — for a body table. */ export const RelatedEnlargeContext = React.createContext<((id: string) => void) | null>(null); 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..20815248982 100644 --- a/ui/packages/plugin-detail/src/useDetailTranslation.ts +++ b/ui/packages/plugin-detail/src/useDetailTranslation.ts @@ -121,6 +121,17 @@ 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': '{{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', 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", diff --git a/ui/packages/plugin-list/README.md b/ui/packages/plugin-list/README.md index b5db5ce0c19..c873de5d07e 100644 --- a/ui/packages/plugin-list/README.md +++ b/ui/packages/plugin-list/README.md @@ -344,6 +344,50 @@ function TaskList() { } ``` +### The condition row for another host: `ListConditionsBlock` + +A host that draws a child object's rows itself gets the list page's condition +row as `ListConditionsBlock` (objectstack#35892). The record page's related tab +is one: `@object-ui/plugin-detail` sits below this package, so it cannot import +the block, and the record page hands it in through `plugin-detail`'s +`RelatedListConditionsSlotContext`. It is the same `ConditionChipRow`, +`SortPanel` and `FilterPanel` with the same field lists, and no view switch, +view settings or search. It is a host element, not a registered node type: it is +controlled, and every input is a React prop. + +```tsx +import { useState } from 'react'; +import type { FilterBuilderRowGroup, SortItem } from '@object-ui/components'; +import { ListConditionsBlock } from '@object-ui/plugin-list'; + +const NO_FILTER: FilterBuilderRowGroup = { id: 'root', logic: 'and', conditions: [] }; + +export function QuoteConditions({ quoteDefinition }: { quoteDefinition: { fields?: Record } }) { + const [sort, setSort] = useState([]); + const [filterGroup, setFilterGroup] = useState(NO_FILTER); + const [, setFilter] = useState(undefined); + const changed = sort.length > 0 || filterGroup.conditions.length > 0; + const discard = () => { setSort([]); setFilterGroup(NO_FILTER); setFilter(undefined); }; + return ( + { 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 9be9a4f61d3..a07e4ce4420 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -61,7 +61,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, isObjectExportOffered, 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, isObjectExportOffered, 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 @@ -1249,7 +1249,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 })); @@ -1921,7 +1921,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) @@ -2002,7 +2002,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, @@ -2019,13 +2019,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'; @@ -5783,18 +5955,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; }; @@ -5819,48 +5981,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; @@ -5912,33 +6036,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). @@ -6022,42 +6127,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]); @@ -6140,9 +6218,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 0a1c6764f0b..6bbcb86a84e 100644 --- a/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx +++ b/ui/packages/plugin-list/src/conditions/ListConditionControls.tsx @@ -509,6 +509,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; } @@ -543,6 +550,7 @@ export function ConditionChipRow({ renderSortPanel, end, filterOffered = true, + collapsibleLabels = false, className, }: ConditionChipRowProps) { const { t } = useListConditionTranslation(); @@ -567,6 +575,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)}> @@ -593,7 +607,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: @@ -609,12 +627,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 } : {})} >