diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md index 76c6b0513..971ca2a7e 100644 --- a/apps/web/AGENTS.md +++ b/apps/web/AGENTS.md @@ -184,7 +184,10 @@ add UI that an e2e test will drive. ## Tables -A table listing records is the libui `DataTable`. libui's plain `Table` is for a small table the +A table listing records is `@/components/DataTable`: libui's `DataTable` plus a required `tableName`, +under which it remembers the page and sort a user leaves it on (eslint rejects importing libui's +own). A test rendering the same table twice clears `savedTableViews` from `@/services/table-views` +between renders. libui's plain `Table` is for a small table the component lays out itself, such as the rows of inputs in `UserPermissionsEditor` and `PermissionSetRulesEditor`. Two of `DataTable`'s behaviours are load-bearing and neither is visible from the call site. diff --git a/apps/web/src/components/BulkRemoteAssignmentWizard/SourceStep.tsx b/apps/web/src/components/BulkRemoteAssignmentWizard/SourceStep.tsx index a1962c154..9a7df8e6f 100644 --- a/apps/web/src/components/BulkRemoteAssignmentWizard/SourceStep.tsx +++ b/apps/web/src/components/BulkRemoteAssignmentWizard/SourceStep.tsx @@ -1,12 +1,13 @@ import React, { useState } from 'react'; import { toBasicISOString } from '@douglasneuroinformatics/libjs'; -import { Button, Checkbox, DataTable, FileDropzone, Input, TextArea } from '@douglasneuroinformatics/libui/components'; +import { Button, Checkbox, FileDropzone, Input, TextArea } from '@douglasneuroinformatics/libui/components'; import { useTranslation } from '@douglasneuroinformatics/libui/hooks'; import { BULK_ASSIGNMENT_MAX_SUBJECTS } from '@opendatacapture/schemas/assignment'; import type { Subject } from '@opendatacapture/schemas/subject'; import { removeSubjectIdScope } from '@opendatacapture/subject-utils'; +import { DataTable } from '@/components/DataTable'; import { SectionTabs } from '@/components/SectionTabs'; import { SortableHeader } from '@/components/SortableHeader'; import { @@ -340,6 +341,7 @@ export const SourceStep = ({ : []) ]} data={rows} + tableName={`bulk-assignment-subjects-${groupName}`} onRowClick={(row) => toggle(row.id)} /> diff --git a/apps/web/src/components/DataTable/DataTable.tsx b/apps/web/src/components/DataTable/DataTable.tsx new file mode 100644 index 000000000..be58e2677 --- /dev/null +++ b/apps/web/src/components/DataTable/DataTable.tsx @@ -0,0 +1,154 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import type { RefObject } from 'react'; + +import { DataTable as LibuiDataTable } from '@douglasneuroinformatics/libui/components'; +import type { DataTableProps as LibuiDataTableProps, TanstackTable } from '@douglasneuroinformatics/libui/components'; + +import { savedTableViews } from '@/services/table-views'; + +/** + * libui hands the Tanstack table to no prop that every table renders: the toggles and the search + * callback are skipped under `disableSearch`. Every visible column renders its header, so each + * header captures it. + */ +function withTableCapture( + columns: TanstackTable.ColumnDef[], + tableRef: RefObject> +): TanstackTable.ColumnDef[] { + if (!columns.some((column) => column.header !== undefined)) { + throw new Error('Expected at least one DataTable column to define a header'); + } + return columns.map((column) => { + const { header: Header } = column; + if (Header === undefined) { + return column; + } + // Tanstack names a column without an id or accessorKey after its string header, so replacing + // that header with a function would rename the column unless the id is kept. + const id = column.id ?? ('accessorKey' in column || typeof Header !== 'string' ? undefined : Header); + return { + ...column, + header: (context: TanstackTable.HeaderContext) => { + tableRef.current = context.table; + return typeof Header === 'function' ?
: Header; + }, + id + } as TanstackTable.ColumnDef; + }); +} + +/** + * Tanstack sends a table back to page one whenever its rows recompute, so a refetch of the same + * list would undo the page restored on return. The table returns to page one only when what + * selects or orders its rows changes, which is when the page the user was on stops meaning anything. + */ +function keepPageAcrossRefetches(table: TanstackTable.Table) { + const returnToFirstPageOnChange = ( + key: TKey, + onChange: TanstackTable.OnChangeFn | undefined + ): TanstackTable.OnChangeFn => { + return (updater) => { + const previous = JSON.stringify(table.getState()[key]); + + onChange!(updater); + if (JSON.stringify(table.getState()[key]) !== previous) { + table.setPageIndex(0); + } + }; + }; + // libui's store rebuilds the options from the previous ones on every update, so these survive it. + table.setOptions((options) => ({ + ...options, + autoResetPageIndex: false, + onColumnFiltersChange: returnToFirstPageOnChange('columnFilters', options.onColumnFiltersChange), + onGlobalFilterChange: returnToFirstPageOnChange('globalFilter', options.onGlobalFilterChange), + onSortingChange: returnToFirstPageOnChange('sorting', options.onSortingChange) + })); +} + +const ClientDataTable = ({ + pageResetKey, + tableName, + ...props +}: Extract, { mode?: 'client' }>) => { + const tableRef = useRef>(null); + const [savedView] = useState(() => savedTableViews.get(tableName)); + const columns = useMemo(() => withTableCapture(props.columns, tableRef), [props.columns]); + const serializedPageResetKey = JSON.stringify(pageResetKey); + const pageResetKeyRef = useRef(serializedPageResetKey); + + useEffect(() => { + const table = tableRef.current!; + keepPageAcrossRefetches(table); + if (savedView) { + table.setPageIndex(savedView.pageIndex); + } + const columnFiltersOnOpen = JSON.stringify(table.getState().columnFilters); + const pageResetKeyOnOpen = serializedPageResetKey; + return () => { + const { columnFilters, globalFilter, pagination, sorting } = table.getState(); + const isFiltered = + Boolean(globalFilter) || + JSON.stringify(columnFilters) !== columnFiltersOnOpen || + pageResetKeyRef.current !== pageResetKeyOnOpen; + savedTableViews.set(tableName, { pageIndex: isFiltered ? 0 : pagination.pageIndex, sorting }); + }; + }, []); + + useEffect(() => { + if (pageResetKeyRef.current !== serializedPageResetKey) { + pageResetKeyRef.current = serializedPageResetKey; + tableRef.current!.setPageIndex(0); + } + }, [serializedPageResetKey]); + + useEffect(() => { + const table = tableRef.current!; + // Rows still loading would clamp a restored page to the first before they arrive. + if (props.data.length === 0) { + return; + } + const lastPageIndex = Math.max(table.getPageCount() - 1, 0); + if (table.getState().pagination.pageIndex > lastPageIndex) { + table.setPageIndex(lastPageIndex); + } + }, [props.data]); + + return ( + + ); +}; + +/** + * The libui `DataTable`, returning to the page and sort the user left it on. libui keeps both in + * state that unmounts with the table, so without this a list opened again from a row's page always + * starts on page one. + * + * A view left while searching or filtering keeps its sort but not its page: the search box always + * opens empty, so the saved page would index rows the user never saw. A server-mode table is passed + * through untouched, since its caller already holds the page and sort it requests. + */ +export const DataTable = (props: DataTableProps) => { + if (props.mode === 'server') { + const { pageResetKey: _, ...serverProps } = props; + return ; + } + // Keyed by name, so a table renamed in place (a group switch, say) restores and saves its own view. + return ; +}; + +export type DataTableProps = LibuiDataTableProps & { + /** + * The filters a caller applies to `data` itself, outside the table's search and column filters. + * The table returns to page one when it changes; any other change of `data` is taken for a + * refetch of the same rows, which keeps the page. + */ + pageResetKey?: unknown; + /** Keys the page and sort this table returns to after the user leaves it, so it must be unique */ + tableName: string; +}; diff --git a/apps/web/src/components/DataTable/__tests__/DataTable.test.tsx b/apps/web/src/components/DataTable/__tests__/DataTable.test.tsx new file mode 100644 index 000000000..eb764efcf --- /dev/null +++ b/apps/web/src/components/DataTable/__tests__/DataTable.test.tsx @@ -0,0 +1,241 @@ +import type { TanstackTable } from '@douglasneuroinformatics/libui/components'; +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { DataTable } from '@/components/DataTable/DataTable'; +import type { DataTableProps } from '@/components/DataTable/DataTable'; +import { savedTableViews } from '@/services/table-views'; + +import '@/services/i18n'; + +type Row = { name: string }; + +const NAME_LABEL = 'Name'; +const FILTER_LABEL = 'Filter'; +const REFILTER_LABEL = 'Refilter'; + +const makeRows = (count: number): Row[] => { + return Array.from({ length: count }, (_, index) => ({ name: `row ${String(index + 1).padStart(2, '0')}` })); +}; + +const columns: TanstackTable.ColumnDef[] = [ + { + accessorKey: 'name', + header: ({ column }) => ( + + ) + } +]; + +type ClientProps = Partial, { mode?: 'client' }>>; + +const renderTable = (props: ClientProps = {}) => { + return render(); +}; + +const firstRowText = () => screen.getAllByTestId('data-table-row')[0]!.textContent; + +/** Tanstack queues its automatic page reset as a microtask, so a test must let it run. */ +const flushQueuedReset = () => act(() => Promise.resolve()); + +const goToPage = (page: number) => fireEvent.click(screen.getByRole('button', { name: String(page) })); + +const remount = async (props: ClientProps = {}) => { + cleanup(); + renderTable(props); + await flushQueuedReset(); +}; + +describe('DataTable', () => { + beforeEach(() => { + savedTableViews.clear(); + }); + + afterEach(cleanup); + + it('should open on the page it was left on, so returning from a row does not restart the list', async () => { + renderTable(); + goToPage(2); + await remount(); + expect(firstRowText()).toBe('row 11'); + }); + + it('should keep the sort it was left with', async () => { + renderTable(); + fireEvent.click(screen.getByText('Name')); + fireEvent.click(screen.getByText('Name')); + await remount(); + expect(firstRowText()).toBe('row 25'); + }); + + it('should open on the first page when left mid-search, since the search box opens empty', async () => { + renderTable(); + fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'row' } }); + goToPage(2); + await remount(); + expect(firstRowText()).toBe('row 01'); + }); + + it('should open on the first page when left with a column filter changed', async () => { + renderTable({ + togglesComponent: ({ table }) => ( + + ) + }); + fireEvent.click(screen.getByRole('button', { name: 'Filter' })); + goToPage(2); + await remount(); + expect(firstRowText()).toBe('row 01'); + }); + + it('should open on the last page when the rows it was left on no longer exist', async () => { + renderTable(); + goToPage(3); + await remount({ data: makeRows(12) }); + expect(firstRowText()).toBe('row 11'); + }); + + it('should stay on its page when the rows are refetched, as after returning from editing one', async () => { + const { rerender } = renderTable(); + await flushQueuedReset(); + goToPage(2); + rerender(); + await flushQueuedReset(); + expect(firstRowText()).toBe('row 11'); + }); + + it('should move to the last page when a refetch leaves fewer pages than the one shown', () => { + const { rerender } = renderTable(); + goToPage(3); + rerender(); + expect(firstRowText()).toBe('row 11'); + }); + + it('should return to the first page when the search changes, since the page no longer applies', () => { + renderTable(); + goToPage(2); + fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'row' } }); + expect(firstRowText()).toBe('row 01'); + }); + + it('should stay on its page when a filter is set to the value it already has', () => { + renderTable({ + togglesComponent: ({ table }) => ( + + ) + }); + goToPage(2); + fireEvent.click(screen.getByRole('button', { name: 'Refilter' })); + expect(firstRowText()).toBe('row 11'); + }); + + it('should return to the first page when the sort changes', () => { + renderTable(); + goToPage(2); + fireEvent.click(screen.getByText('Name')); + expect(firstRowText()).toBe('row 01'); + }); + + it('should return to the first page when the caller filters its rows differently', () => { + const { rerender } = renderTable({ pageResetKey: 0 }); + goToPage(2); + rerender(); + expect(firstRowText()).toBe('row 01'); + }); + + it('should stay on its page when the caller re-renders with the same filters', () => { + const { rerender } = renderTable({ pageResetKey: [0, 'all'] }); + goToPage(2); + rerender(); + expect(firstRowText()).toBe('row 11'); + }); + + it('should open on the first page when left with the caller filtering differently from when it opened', async () => { + const { rerender } = renderTable({ pageResetKey: 0 }); + rerender(); + goToPage(2); + await remount(); + expect(firstRowText()).toBe('row 01'); + }); + + it('should keep the page it reopens on while its rows are still loading', async () => { + renderTable(); + goToPage(2); + cleanup(); + const { rerender } = renderTable({ data: [] }); + await flushQueuedReset(); + rerender(); + await flushQueuedReset(); + expect(firstRowText()).toBe('row 11'); + }); + + it('should save and restore under its new name when renamed in place, as on a group switch', async () => { + savedTableViews.set('group b', { pageIndex: 2, sorting: [] }); + const { rerender } = renderTable({ tableName: 'group a' }); + goToPage(2); + rerender(); + await flushQueuedReset(); + expect(firstRowText()).toBe('row 21'); + expect(savedTableViews.get('group a')?.pageIndex).toBe(1); + }); + + it('should keep each table on its own page, keyed by table name', async () => { + renderTable(); + goToPage(2); + await remount({ tableName: 'other rows' }); + expect(firstRowText()).toBe('row 01'); + }); + + it('should keep the id Tanstack derives from a string header, so the column can still be found', () => { + const getColumn = vi.fn(); + renderTable({ + columns: [{ accessorFn: (row) => row.name, header: 'Name' }], + togglesComponent: ({ table }) => { + getColumn(table.getColumn('Name')?.id); + return null; + } + }); + expect(getColumn).toHaveBeenLastCalledWith('Name'); + }); + + it('should render a header that is plain text', () => { + renderTable({ columns: [{ accessorKey: 'name', header: 'Plain Name' }] }); + expect(screen.getByText('Plain Name')).toBeTruthy(); + }); + + it('should leave a column without a header as it is', () => { + renderTable({ columns: [...columns, { accessorKey: 'name', id: 'unlabelled' }] }); + expect(screen.getAllByTestId('data-table-row')).toHaveLength(10); + }); + + it('should refuse columns without any header, since a header is how it reaches the table', () => { + vi.spyOn(console, 'error').mockImplementation(() => undefined); + expect(() => renderTable({ columns: [{ accessorKey: 'name' }] })).toThrow( + 'Expected at least one DataTable column to define a header' + ); + }); + + it('should leave a server-mode table to its caller, which holds the page it requests', () => { + const onPaginationChange = vi.fn(); + savedTableViews.set('rows', { pageIndex: 1, sorting: [] }); + render( + + ); + expect(firstRowText()).toBe('row 01'); + expect(onPaginationChange).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/components/DataTable/index.ts b/apps/web/src/components/DataTable/index.ts new file mode 100644 index 000000000..89841a480 --- /dev/null +++ b/apps/web/src/components/DataTable/index.ts @@ -0,0 +1 @@ +export * from './DataTable'; diff --git a/apps/web/src/components/DeleteRemoteAssignments/DeleteRemoteAssignments.tsx b/apps/web/src/components/DeleteRemoteAssignments/DeleteRemoteAssignments.tsx index 01c6dc6c9..9c1ec25e9 100644 --- a/apps/web/src/components/DeleteRemoteAssignments/DeleteRemoteAssignments.tsx +++ b/apps/web/src/components/DeleteRemoteAssignments/DeleteRemoteAssignments.tsx @@ -1,13 +1,14 @@ import React, { useState } from 'react'; import { toBasicISOString } from '@douglasneuroinformatics/libjs'; -import { Button, Card, Checkbox, DataTable, Dialog } from '@douglasneuroinformatics/libui/components'; +import { Button, Card, Checkbox, Dialog } from '@douglasneuroinformatics/libui/components'; import { useTheme, useTranslation } from '@douglasneuroinformatics/libui/hooks'; import type { Assignment } from '@opendatacapture/schemas/assignment'; import type { UnilingualInstrumentInfo } from '@opendatacapture/schemas/instrument'; import { removeSubjectIdScope } from '@opendatacapture/subject-utils'; import { ColorTagCell } from '@/components/ColorTagCell'; +import { DataTable } from '@/components/DataTable'; import { SortableHeader } from '@/components/SortableHeader'; import { useAssignmentsQuery } from '@/hooks/useAssignmentsQuery'; import { useDeleteBulkAssignmentsMutation } from '@/hooks/useDeleteBulkAssignmentsMutation'; @@ -221,6 +222,7 @@ export const DeleteRemoteAssignments = ({ groupId, onBack, subjectIdDisplayLengt } ]} data={rows} + tableName={`delete-remote-assignments-${groupId}`} onRowClick={(row) => toggle(row.id)} /> )} diff --git a/apps/web/src/components/InstrumentRepoSyncLogTable/InstrumentRepoSyncLogTable.tsx b/apps/web/src/components/InstrumentRepoSyncLogTable/InstrumentRepoSyncLogTable.tsx index dc4e49356..8b7ce30e9 100644 --- a/apps/web/src/components/InstrumentRepoSyncLogTable/InstrumentRepoSyncLogTable.tsx +++ b/apps/web/src/components/InstrumentRepoSyncLogTable/InstrumentRepoSyncLogTable.tsx @@ -1,6 +1,6 @@ import { Fragment, useState } from 'react'; -import { Badge, Button, DataTable, Dialog } from '@douglasneuroinformatics/libui/components'; +import { Badge, Button, Dialog } from '@douglasneuroinformatics/libui/components'; import { useTheme, useTranslation } from '@douglasneuroinformatics/libui/hooks'; import { $InstrumentRepoSyncLogsSortBy } from '@opendatacapture/schemas/instrument-repo'; import type { @@ -10,6 +10,7 @@ import type { } from '@opendatacapture/schemas/instrument-repo'; import { ColorTagCell } from '@/components/ColorTagCell'; +import { DataTable } from '@/components/DataTable'; import { SortableHeader } from '@/components/SortableHeader'; import { TruncatedCell } from '@/components/TruncatedCell'; import { MIN_TABLE_BODY_HEIGHT, readServerSort } from '@/utils/data-table'; @@ -260,6 +261,7 @@ const InstrumentRepoSyncLogTable = ({ }} mode="server" pageCount={pageCount} + tableName="instrument-repo-sync-log" onPaginationChange={({ pageIndex }) => onPageChange(pageIndex + 1)} onSortingChange={(state) => onSortChange(readServerSort(state, $InstrumentRepoSyncLogsSortBy.options))} /> diff --git a/apps/web/src/components/InstrumentTable/InstrumentTable.tsx b/apps/web/src/components/InstrumentTable/InstrumentTable.tsx index c1f62f150..15f237a93 100644 --- a/apps/web/src/components/InstrumentTable/InstrumentTable.tsx +++ b/apps/web/src/components/InstrumentTable/InstrumentTable.tsx @@ -1,7 +1,7 @@ import React, { useMemo, useState } from 'react'; import { toBasicISOString } from '@douglasneuroinformatics/libjs'; -import { Button, DataTable, DropdownMenu } from '@douglasneuroinformatics/libui/components'; +import { Button, DropdownMenu } from '@douglasneuroinformatics/libui/components'; import type { TanstackTable } from '@douglasneuroinformatics/libui/components'; import { useDownload, useNotificationsStore, useTranslation } from '@douglasneuroinformatics/libui/hooks'; import type { InstrumentKind } from '@opendatacapture/runtime-core'; @@ -9,6 +9,7 @@ import { ChevronDownIcon } from 'lucide-react'; import { unparse } from 'papaparse'; import { CollectedFilterMenu } from '@/components/CollectedFilterMenu'; +import { DataTable } from '@/components/DataTable'; import { InstrumentKindCell } from '@/components/InstrumentKindCell'; import { InstrumentPreviewDialog } from '@/components/InstrumentPreviewDialog'; import type { InstrumentPreviewItem } from '@/components/InstrumentPreviewDialog'; @@ -260,6 +261,7 @@ type InstrumentTableProps = { */ recordExport?: (option: RecordExportOption) => void; rows: InstrumentRow[]; + tableName: string; }; /** @@ -272,7 +274,8 @@ export const InstrumentTable = ({ onMinRecordsChange, onOpen, recordExport, - rows + rows, + tableName }: InstrumentTableProps) => { const { t } = useTranslation(); const [highlightedRowId, setHighlightedRowId] = useState(null); @@ -324,8 +327,7 @@ export const InstrumentTable = ({ return (
- setPreview(toPreviewItem(row)) } ]} + tableName={tableName} togglesComponent={ToolbarWithRows} onRowClick={(row) => setHighlightedRowId(row.id)} onRowDoubleClick={onOpen} diff --git a/apps/web/src/components/InstrumentTable/__tests__/InstrumentTable.test.tsx b/apps/web/src/components/InstrumentTable/__tests__/InstrumentTable.test.tsx index 51ee0aabc..fcf665c92 100644 --- a/apps/web/src/components/InstrumentTable/__tests__/InstrumentTable.test.tsx +++ b/apps/web/src/components/InstrumentTable/__tests__/InstrumentTable.test.tsx @@ -58,13 +58,13 @@ const row = (overrides: Partial = {}): InstrumentRow => ({ }); const renderTable = (rows: InstrumentRow[], onOpen = vi.fn()) => { - render(); + render(); return onOpen; }; const renderTableWithRecordExport = (rows: InstrumentRow[]) => { const recordExport = vi.fn(); - render(); + render(); return recordExport; }; @@ -135,6 +135,7 @@ describe('InstrumentTable', () => { ); diff --git a/apps/web/src/components/SearchSubmitGuard/__tests__/SearchSubmitGuard.test.tsx b/apps/web/src/components/SearchSubmitGuard/__tests__/SearchSubmitGuard.test.tsx index 685abbea5..1cbf08776 100644 --- a/apps/web/src/components/SearchSubmitGuard/__tests__/SearchSubmitGuard.test.tsx +++ b/apps/web/src/components/SearchSubmitGuard/__tests__/SearchSubmitGuard.test.tsx @@ -1,7 +1,7 @@ -import { DataTable } from '@douglasneuroinformatics/libui/components'; import { cleanup, fireEvent, render, screen } from '@testing-library/react'; import { beforeAll, beforeEach, describe, expect, it } from 'vitest'; +import { DataTable } from '@/components/DataTable'; import { SearchSubmitGuard } from '@/components/SearchSubmitGuard/SearchSubmitGuard'; // Initialises the shared libui translator, which the table's controls read on render. @@ -10,7 +10,9 @@ import '@/services/i18n'; const noop = () => undefined; const renderTable = (guarded: boolean) => { - const table = ; + const table = ( + + ); render(guarded ? {table} : table); return screen.getByTestId('data-table-search-bar'); }; diff --git a/apps/web/src/routes/_app/__tests__/dashboard.test.tsx b/apps/web/src/routes/_app/__tests__/dashboard.test.tsx index eda5c3a5c..21e61e7db 100644 --- a/apps/web/src/routes/_app/__tests__/dashboard.test.tsx +++ b/apps/web/src/routes/_app/__tests__/dashboard.test.tsx @@ -8,6 +8,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type { Mock } from 'vitest'; import { Route } from '@/routes/_app/dashboard'; +import { savedTableViews } from '@/services/table-views'; import '@/services/i18n'; @@ -213,6 +214,7 @@ describe('Route', () => { describe('dashboard page', () => { beforeEach(() => { vi.clearAllMocks(); + savedTableViews.clear(); i18n.changeLanguage('en'); mocks.store.currentGroup = null; mocks.summary = { data: SUMMARY }; diff --git a/apps/web/src/routes/_app/admin/audit/logs.tsx b/apps/web/src/routes/_app/admin/audit/logs.tsx index 4c0243ab7..bfef51873 100644 --- a/apps/web/src/routes/_app/admin/audit/logs.tsx +++ b/apps/web/src/routes/_app/admin/audit/logs.tsx @@ -1,7 +1,7 @@ import React, { Fragment, useCallback, useMemo, useState } from 'react'; import { snakeToCamelCase, toLowerCase } from '@douglasneuroinformatics/libjs'; -import { Button, DataTable, DropdownMenu, Heading } from '@douglasneuroinformatics/libui/components'; +import { Button, DropdownMenu, Heading } from '@douglasneuroinformatics/libui/components'; import { useDownload, useTheme, useTranslation } from '@douglasneuroinformatics/libui/hooks'; import { $AuditLogsQuerySearchParams, $AuditLogsSortBy } from '@opendatacapture/schemas/audit'; import type { @@ -13,6 +13,7 @@ import { createFileRoute } from '@tanstack/react-router'; import { CalendarIcon, DownloadIcon, XIcon } from 'lucide-react'; import { ColorTagCell } from '@/components/ColorTagCell'; +import { DataTable } from '@/components/DataTable'; import { FilterMenu } from '@/components/FilterMenu'; import { PageHeader } from '@/components/PageHeader'; import { SortableHeader } from '@/components/SortableHeader'; @@ -269,6 +270,7 @@ const AuditLogsTable: React.FC<{ search: AuditLogsSearchParams }> = ({ search }) data={auditLogsQuery.data?.data ?? []} mode="server" pageCount={auditLogsQuery.data?.pageCount ?? 0} + tableName="admin-audit-logs" onPaginationChange={({ pageIndex }) => setPage(pageIndex + 1)} onSortingChange={(state) => { setSort(readServerSort(state, $AuditLogsSortBy.options)); diff --git a/apps/web/src/routes/_app/admin/groups/index.tsx b/apps/web/src/routes/_app/admin/groups/index.tsx index 220002f8c..476625281 100644 --- a/apps/web/src/routes/_app/admin/groups/index.tsx +++ b/apps/web/src/routes/_app/admin/groups/index.tsx @@ -1,7 +1,7 @@ import { useEffect, useState } from 'react'; import { toBasicISOString } from '@douglasneuroinformatics/libjs'; -import { Button, Checkbox, DataTable, Dialog, Heading, Sheet } from '@douglasneuroinformatics/libui/components'; +import { Button, Checkbox, Dialog, Heading, Sheet } from '@douglasneuroinformatics/libui/components'; import { useNotificationsStore, useTheme, useTranslation } from '@douglasneuroinformatics/libui/hooks'; import { $Group } from '@opendatacapture/schemas/group'; import type { Group } from '@opendatacapture/schemas/group'; @@ -10,6 +10,7 @@ import { createFileRoute, Link } from '@tanstack/react-router'; import axios from 'axios'; import { ColorTagCell } from '@/components/ColorTagCell'; +import { DataTable } from '@/components/DataTable'; import { PageHeader } from '@/components/PageHeader'; import { SortableHeader } from '@/components/SortableHeader'; import { useArchiveGroupMutation } from '@/hooks/useArchiveGroupMutation'; @@ -197,6 +198,7 @@ const RouteComponent = () => { onSelect: setSelectedGroup } ]} + tableName="admin-groups" togglesComponent={() => (
)} @@ -346,6 +348,7 @@ const RouteComponent = () => { ]} data={instrumentInfo} initialState={{ columnPinning: { right: ['kind'] } }} + tableName="dashboard-instruments" /> ) : ( @@ -413,6 +416,7 @@ const RouteComponent = () => { ]} data={recordCounter} initialState={{ columnPinning: { right: ['count'] }, sorting: [{ desc: true, id: 'count' }] }} + tableName="dashboard-record-counts" /> ) : ( diff --git a/apps/web/src/routes/_app/datahub/instruments/$instrumentId/table.tsx b/apps/web/src/routes/_app/datahub/instruments/$instrumentId/table.tsx index 6184b806f..a3d6fabc6 100644 --- a/apps/web/src/routes/_app/datahub/instruments/$instrumentId/table.tsx +++ b/apps/web/src/routes/_app/datahub/instruments/$instrumentId/table.tsx @@ -1,13 +1,7 @@ import { useMemo, useState } from 'react'; import { camelToSnakeCase, toBasicISOString } from '@douglasneuroinformatics/libjs'; -import { - ActionDropdown, - Button, - DataTable, - DropdownMenu, - TanstackTable -} from '@douglasneuroinformatics/libui/components'; +import { ActionDropdown, Button, DropdownMenu, TanstackTable } from '@douglasneuroinformatics/libui/components'; import { useTranslation } from '@douglasneuroinformatics/libui/hooks'; import type { InstrumentKind } from '@opendatacapture/runtime-core'; import { $SessionType } from '@opendatacapture/schemas/session'; @@ -16,6 +10,7 @@ import { removeSubjectIdScope } from '@opendatacapture/subject-utils'; import { createFileRoute } from '@tanstack/react-router'; import { ChevronDownIcon } from 'lucide-react'; +import { DataTable } from '@/components/DataTable'; import { InstrumentTable } from '@/components/InstrumentTable'; import type { InstrumentRow } from '@/components/InstrumentTable'; import { SelectEdition } from '@/components/SelectEdition'; @@ -195,6 +190,7 @@ const RouteComponent = () => { minRecords={search.minRecords} recordExport={dl} rows={seriesMembers} + tableName={`series-members-${seriesInstrumentId}`} onMinRecordsChange={(value) => { void navigate({ search: (prev) => ({ ...prev, minRecords: value }) }); }} @@ -276,6 +272,7 @@ const RouteComponent = () => { ...measureColumns ]} data={records} + pageResetKey={[search.methods, search.series, search.minDateKey]} rowActions={[ { label: t({ en: 'View Record', es: 'Ver registro', fr: "Voir l'enregistrement" }), @@ -292,6 +289,7 @@ const RouteComponent = () => { } } ]} + tableName={`instrument-records-${seriesInstrumentId}`} onRowClick={(row) => setHighlightedRowId(row.__id__)} onRowDoubleClick={handleViewRecord} /> diff --git a/apps/web/src/routes/_app/datahub/instruments/index.tsx b/apps/web/src/routes/_app/datahub/instruments/index.tsx index fc4eb90a8..246c6d331 100644 --- a/apps/web/src/routes/_app/datahub/instruments/index.tsx +++ b/apps/web/src/routes/_app/datahub/instruments/index.tsx @@ -63,7 +63,12 @@ const RouteComponent = () => { })} - + ); }; diff --git a/apps/web/src/routes/_app/datahub/subjects/$subjectId/assignments.tsx b/apps/web/src/routes/_app/datahub/subjects/$subjectId/assignments.tsx index de848f798..b333bf3d7 100644 --- a/apps/web/src/routes/_app/datahub/subjects/$subjectId/assignments.tsx +++ b/apps/web/src/routes/_app/datahub/subjects/$subjectId/assignments.tsx @@ -4,13 +4,14 @@ import React, { useState } from 'react'; import { toBasicISOString } from '@douglasneuroinformatics/libjs'; -import { Button, DataTable, Heading, Input, Label, Sheet } from '@douglasneuroinformatics/libui/components'; +import { Button, Heading, Input, Label, Sheet } from '@douglasneuroinformatics/libui/components'; import { useTranslation } from '@douglasneuroinformatics/libui/hooks'; import { CopyButton } from '@opendatacapture/react-core'; import type { Assignment, AssignmentStatus } from '@opendatacapture/schemas/assignment'; import { createFileRoute, redirect } from '@tanstack/react-router'; import { AssignmentEmailForm } from '@/components/AssignmentEmailForm'; +import { DataTable } from '@/components/DataTable'; import { QRCode } from '@/components/QRCode'; import { SortableHeader } from '@/components/SortableHeader'; import { config } from '@/config'; @@ -88,6 +89,7 @@ const AssignmentsTable: React.FC<{ onSelection: (assignment: Assignment) => void; selectedId: null | string; }> = ({ assignments, onSelection, selectedId }) => { + const { subjectId } = Route.useParams(); const { t } = useTranslation('datahub'); const instrumentInfoQuery = useInstrumentInfoQuery(); const instruments = new Map((instrumentInfoQuery.data ?? []).map((instrument) => [instrument.id, instrument])); @@ -147,6 +149,7 @@ const AssignmentsTable: React.FC<{ } ]} data={rows} + tableName={`subject-assignments-${subjectId}`} onRowClick={onSelection} /> ); diff --git a/apps/web/src/routes/_app/datahub/subjects/$subjectId/table/index.tsx b/apps/web/src/routes/_app/datahub/subjects/$subjectId/table/index.tsx index 559129a52..37fa41531 100644 --- a/apps/web/src/routes/_app/datahub/subjects/$subjectId/table/index.tsx +++ b/apps/web/src/routes/_app/datahub/subjects/$subjectId/table/index.tsx @@ -1,10 +1,11 @@ import { useMemo } from 'react'; import { camelToSnakeCase, toBasicISOString } from '@douglasneuroinformatics/libjs'; -import { ActionDropdown, DataTable, TanstackTable } from '@douglasneuroinformatics/libui/components'; +import { ActionDropdown, TanstackTable } from '@douglasneuroinformatics/libui/components'; import { useTranslation } from '@douglasneuroinformatics/libui/hooks'; import { createFileRoute } from '@tanstack/react-router'; +import { DataTable } from '@/components/DataTable'; import { SelectEdition } from '@/components/SelectEdition'; import { SelectInstrument } from '@/components/SelectInstrument'; import { SortableHeader } from '@/components/SortableHeader'; @@ -19,7 +20,7 @@ import { timeframeMinDate } from '@/utils/timeframe'; const RouteComponent = () => { const navigate = Route.useNavigate(); const params = Route.useParams(); - const { dl, editionOptions, instrumentId, instrumentOptions, records, setInstrumentId, setMinDate } = + const { dl, editionOptions, instrumentId, instrumentOptions, minDate, records, setInstrumentId, setMinDate } = useInstrumentVisualization({ params: { subjectId: params.subjectId } }); @@ -88,6 +89,7 @@ const RouteComponent = () => { ...columns ]} data={records} + pageResetKey={[instrumentId, minDate]} rowActions={[ { label: t('common.view'), @@ -96,6 +98,7 @@ const RouteComponent = () => { } } ]} + tableName={`subject-records-${params.subjectId}`} onRowDoubleClick={(row) => { void navigate({ params: { recordId: row.__id__ }, to: './$recordId' }); }} diff --git a/apps/web/src/routes/_app/datahub/subjects/index.tsx b/apps/web/src/routes/_app/datahub/subjects/index.tsx index 62cf69b63..cf8d8b8ac 100644 --- a/apps/web/src/routes/_app/datahub/subjects/index.tsx +++ b/apps/web/src/routes/_app/datahub/subjects/index.tsx @@ -1,14 +1,7 @@ import React, { useMemo, useRef, useState } from 'react'; import { toBasicISOString } from '@douglasneuroinformatics/libjs'; -import { - ActionDropdown, - Button, - DataTable, - Dialog, - DropdownMenu, - Heading -} from '@douglasneuroinformatics/libui/components'; +import { ActionDropdown, Button, Dialog, DropdownMenu, Heading } from '@douglasneuroinformatics/libui/components'; import type { TanstackTable } from '@douglasneuroinformatics/libui/components'; import { useDownload, useNotificationsStore, useTheme, useTranslation } from '@douglasneuroinformatics/libui/hooks'; import type { InstrumentRecordsExport } from '@opendatacapture/schemas/instrument-records'; @@ -22,6 +15,7 @@ import { unparse } from 'papaparse'; import { CollectedFilterMenu } from '@/components/CollectedFilterMenu'; import { ColorTagCell } from '@/components/ColorTagCell'; +import { DataTable } from '@/components/DataTable'; import { IdentificationForm } from '@/components/IdentificationForm'; import { PageHeader } from '@/components/PageHeader'; import { SearchSubmitGuard } from '@/components/SearchSubmitGuard'; @@ -533,12 +527,14 @@ const MasterDataTable: React.FC<{ ], columnPinning: { left: ['subjectId'] } }} + pageResetKey={minRecordCount} rowActions={[ { label: t({ en: 'View', es: 'Ver', fr: 'Voir' }), onSelect } ]} + tableName={`datahub-subjects-${currentGroup?.id ?? 'all'}`} togglesComponent={TogglesWithFilter} onRowClick={(subject) => setHighlightedRowId(subject.id)} onRowDoubleClick={onRowDoubleClick} diff --git a/apps/web/src/services/table-views.ts b/apps/web/src/services/table-views.ts new file mode 100644 index 000000000..bcccafc03 --- /dev/null +++ b/apps/web/src/services/table-views.ts @@ -0,0 +1,13 @@ +import type { TanstackTable } from '@douglasneuroinformatics/libui/components'; + +export type TableView = { + pageIndex: number; + sorting: TanstackTable.SortingState; +}; + +/** + * Where each client-mode `DataTable` was left, by table name. In memory only: signing out reloads + * the app, which clears it, so one user's place in a list never carries over to the next user of + * the browser. A test rendering the same table twice clears it between renders. + */ +export const savedTableViews = new Map(); diff --git a/apps/web/src/utils/__tests__/table.test.tsx b/apps/web/src/utils/__tests__/table.test.tsx index ccfee4b71..f889596ee 100644 --- a/apps/web/src/utils/__tests__/table.test.tsx +++ b/apps/web/src/utils/__tests__/table.test.tsx @@ -1,11 +1,11 @@ import React from 'react'; -import { DataTable } from '@douglasneuroinformatics/libui/components'; import type { TanstackTable } from '@douglasneuroinformatics/libui/components'; import type { Subject } from '@opendatacapture/schemas/subject'; import { render } from '@testing-library/react'; import { describe, expect, it } from 'vitest'; +import { DataTable } from '@/components/DataTable'; import { getListedSubjectIds } from '@/utils/table'; // Initialises the shared libui translator, which the table's controls read on render. @@ -46,6 +46,7 @@ const renderMasterTableLike = (ids: string[]) => { ]} data={ids.map(subject)} rowActions={[{ label: 'View', onSelect: noop }]} + tableName="test" togglesComponent={Capture} /> ); diff --git a/eslint.config.js b/eslint.config.js index 23ee8878b..bd4157b40 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -35,6 +35,13 @@ const NO_TAILWIND_MERGE = { name: 'tailwind-merge' }; +const NO_LIBUI_DATA_TABLE = { + importNames: ['DataTable'], + message: + "Import DataTable from '@/components/DataTable'. libui's own forgets its page and sort when it unmounts, so a list reopened from a row's page starts over on page one.", + name: '@douglasneuroinformatics/libui/components' +}; + const NO_AXIOS_INSTANCE = { message: 'apps/web uses the default axios instance; the retry, offline and error-notification interceptors in src/services/axios.ts are installed on it. A separate instance silently bypasses all of them.', @@ -200,6 +207,13 @@ export default config( 'no-restricted-syntax': ['error', NO_AXIOS_INSTANCE] } }, + { + files: ['apps/web/src/**/*'], + ignores: ['apps/web/src/components/DataTable/DataTable.tsx'], + rules: { + 'no-restricted-imports': ['error', { paths: [NO_BARE_ZOD, NO_CLSX, NO_TAILWIND_MERGE, NO_LIBUI_DATA_TABLE] }] + } + }, { plugins: { odc: { diff --git a/testing/src/pages/_app/admin/permission-sets/index.page.ts b/testing/src/pages/_app/admin/permission-sets/index.page.ts index 94a442dff..80c805f50 100644 --- a/testing/src/pages/_app/admin/permission-sets/index.page.ts +++ b/testing/src/pages/_app/admin/permission-sets/index.page.ts @@ -17,6 +17,7 @@ export class PermissionSetsPage extends AppPage { /** Opens a row's actions menu and picks one; the menu renders in a portal outside the table. */ async chooseRowAction(name: string, action: 'Delete' | 'Manage') { + await this.search(name); await this.row(name).getByTestId('row-actions-trigger').click(); await this.$ref.getByTestId('row-actions-dropdown').getByRole('menuitem', { name: action }).click(); } @@ -28,4 +29,9 @@ export class PermissionSetsPage extends AppPage { row(name: string): Locator { return this.table.getByTestId('data-table-row').filter({ hasText: name }); } + + /** Other specs share the list and can push a set past the first page, so find it by name. */ + async search(name: string) { + await this.table.getByTestId('data-table-search-bar').getByRole('searchbox').fill(name); + } } diff --git a/testing/src/specs/list-return.spec.ts b/testing/src/specs/list-return.spec.ts new file mode 100644 index 000000000..b72abc22e --- /dev/null +++ b/testing/src/specs/list-return.spec.ts @@ -0,0 +1,75 @@ +import type { Page } from '@playwright/test'; + +import { expect, test } from '../support/fixtures'; + +/** + * Opens the first row on the list's second page, runs `whileAway` on the row's page and follows its + * Return link. Resolves to the list's first row and the text it had on the second page. + */ +async function returnFromSecondPage( + page: Page, + { returnTestId, whileAway }: { returnTestId: string; whileAway?: () => Promise } +) { + const firstRow = page.getByTestId('data-table-row').first(); + const secondPageButton = page.getByTestId('data-table').getByRole('button', { exact: true, name: '2' }); + // The button exists only once more than one page of rows has loaded. + await expect(secondPageButton).toBeVisible(); + const firstRowOnFirstPage = await firstRow.textContent(); + await secondPageButton.click(); + await expect(firstRow).not.toHaveText(firstRowOnFirstPage!); + const firstRowOnSecondPage = (await firstRow.textContent())!; + + await firstRow.dblclick(); + await expect(page.getByTestId(returnTestId)).toBeVisible(); + await whileAway?.(); + await page.getByTestId(returnTestId).click(); + return { firstRow, firstRowOnSecondPage }; +} + +test.describe('returning to a list', () => { + test('should come back to the page of users it left, even after the list changed meanwhile', async ({ + api, + authenticateAs, + page + }) => { + await Promise.all(Array.from({ length: 11 }, () => api.createUser())); + await authenticateAs('ADMIN'); + await page.goto('/admin/users'); + const { firstRow, firstRowOnSecondPage } = await returnFromSecondPage(page, { + returnTestId: 'admin-user-back', + whileAway: async () => { + await api.createUser(); + } + }); + await expect(firstRow).toHaveText(firstRowOnSecondPage); + }); + + test('should come back to the page of permission sets it left', async ({ api, authenticateAs, page, uniqueId }) => { + // The list is ordered by name, so a leading '!' keeps these eleven ahead of the sets other specs + // create meanwhile, and the second page starts on the eleventh of them whatever else is added. + await Promise.all( + Array.from({ length: 11 }, (_, index) => { + const name = `!List Return ${uniqueId} ${String(index).padStart(2, '0')}`; + return api.createPermissionSet([{ action: 'read', scope: 'HOLDER_GROUPS', subject: 'User' }], { name }); + }) + ); + await authenticateAs('ADMIN'); + await page.goto('/admin/permission-sets'); + const { firstRow, firstRowOnSecondPage } = await returnFromSecondPage(page, { + returnTestId: 'admin-permission-set-back' + }); + await expect(firstRow).toHaveText(firstRowOnSecondPage); + }); + + test('should come back to the page of subjects it left', async ({ api, isolatedGroupManager, page, uniqueId }) => { + const group = await isolatedGroupManager(); + // The list shows only the first nine characters of an id, so these differ within them; ids from + // createSubject all start `subject_`, and two pages of them can read alike. + for (let index = 0; index < 12; index++) { + await api.createSession(group.id, { id: `${String(index).padStart(2, '0')}-${uniqueId}` }); + } + await page.goto('/datahub/subjects'); + const { firstRow, firstRowOnSecondPage } = await returnFromSecondPage(page, { returnTestId: 'subject-hub-back' }); + await expect(firstRow).toHaveText(firstRowOnSecondPage); + }); +}); diff --git a/testing/src/specs/permission-sets.spec.ts b/testing/src/specs/permission-sets.spec.ts index d1586a81a..2232c9219 100644 --- a/testing/src/specs/permission-sets.spec.ts +++ b/testing/src/specs/permission-sets.spec.ts @@ -189,6 +189,7 @@ test.describe('permission sets', () => { await api.createPermissionSet(RULES, { name }); const listPage = await getPageModel('/admin/permission-sets'); + await listPage.search(name); const cell = listPage.nameCell(name); await expect(cell).toHaveAttribute('title', name);