Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/components/map-projects/MapProjects.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ const MapProjects = ({ ownerType, owner, height }) => {
<TableRow>
<TableCell colSpan={COLUMN_COUNT} align='center' sx={{borderBottom: 'none', padding: '48px 16px'}}>
<Typography sx={{color: 'surface.dark'}}>
{t('map_project.could_not_load_projects')} <Link component='button' onClick={() => setAttempt(count => count + 1)} sx={{verticalAlign: 'baseline'}}>{t('map_project.try_again')}</Link>
{t('map_project.could_not_load_projects')} <Link component='button' onClick={() => setAttempt(count => count + 1)} sx={{verticalAlign: 'baseline'}}>{t('common.try_again')}</Link>
</Typography>
</TableCell>
</TableRow>
Expand Down
230 changes: 139 additions & 91 deletions src/components/search/TableResults.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,15 @@ import Switch from '@mui/material/Switch';
import Checkbox from '@mui/material/Checkbox';
import Skeleton from '@mui/material/Skeleton'
import IconButton from '@mui/material/IconButton';
import CircularProgress from '@mui/material/CircularProgress';
import Button from '@mui/material/Button';
import RightIcon from '@mui/icons-material/KeyboardArrowRight';
import DownIcon from '@mui/icons-material/KeyboardArrowDown';
import { visuallyHidden } from '@mui/utils';
import { get, map, times } from 'lodash'
import APIService from '../../services/APIService';
import { SECONDARY_COLORS } from '../../common/colors';
import { SECONDARY_COLORS, ERROR_COLORS } from '../../common/colors';
import { resolveColumns, isSameSortField } from './columns';
import { CHILDREN_PAGE_SIZE, initialChildrenState, childrenReducer, needsFetchOnExpand, nextChildrenPage } from './childrenPaging';

// What screen readers announce for the select-all checkbox, per result type
const SELECT_ALL_LABEL_KEYS = {
Expand Down Expand Up @@ -130,32 +131,46 @@ const getChildrenURL = (row, baseURL) => {
const conceptSuffix = row.url.replace(/^.*\/concepts\//, 'concepts/').replace(/\/$/, '')
return baseURL.replace(/concepts\/.*$/, '') + conceptSuffix + '/children/';
}
const ResultRow = ({row, index, columns, getValue, handleClick, handleRowClick, isSelected, isItemShown, size, hierarchical, level, baseURL, onRowsLoaded}) => {
const ResultRow = ({row, index, columns, getValue, handleClick, handleRowClick, isSelected, isItemShown, size, hierarchical, level, baseURL, onRowsLoaded, hidden}) => {
const { t } = useTranslation()
const [open, setOpen] = React.useState(false)
const [children, setChildren] = React.useState([])
const [fetched, setFetched] = React.useState(false)
const [loadingChildren, setLoadingChildren] = React.useState(false)
const [childrenState, dispatchChildren] = React.useReducer(childrenReducer, initialChildrenState)
const {children, total: childrenTotal, hasMore: moreChildren, fetched, loading: loadingChildren, failed: childrenFailed} = childrenState
const id = row.version_url || row.url || row.id
const isItemSelected = isSelected(id)
const isItemSelectedToShow = isItemShown(id)
const labelId = `enhanced-table-checkbox-${index}`
const color = row.retired ? SECONDARY_COLORS.main : 'none'
let bgColor = isItemSelectedToShow ? 'primary.90' : ''
const colSpan = columns.length + (handleClick ? 1 : 0) + 1
const fetchChildren = () => {
if(fetched)
// Children load a page at a time; a failed page can be retried without losing the pages already shown
const fetchChildrenPage = page => {
if(loadingChildren)
return
setLoadingChildren(true)
APIService.new().overrideURL(getChildrenURL(row, baseURL)).get().then(response => {
setLoadingChildren(false)
dispatchChildren({type: 'loading'})
APIService.new().overrideURL(getChildrenURL(row, baseURL)).get(null, null, {limit: CHILDREN_PAGE_SIZE, page: page}).then(response => {
if(Array.isArray(response?.data)) {
setChildren(response.data)
setFetched(true)
dispatchChildren({type: 'loaded', page: page, rows: response.data, total: parseInt(response?.headers?.num_found) || 0, hasMore: Boolean(response?.headers?.next)})
if(onRowsLoaded)
onRowsLoaded(response.data)
} else {
dispatchChildren({type: 'failed'})
}
})
}
const fetchChildren = () => {
if(needsFetchOnExpand(childrenState))
fetchChildrenPage(1)
}
// "Show more" and "Try again" both load the page after the last one shown
const onLoadNextChildren = event => {
event.preventDefault()
event.stopPropagation()
fetchChildrenPage(nextChildrenPage(childrenState))
}
const showChildren = hierarchical && open && !hidden
// up to 5 placeholder rows while a page loads, fewer when fewer children are left
const skeletonRows = Math.max(Math.min(5, fetched ? childrenTotal - children.length : 5), 1)
const onExpandClick = event => {
event.preventDefault()
event.stopPropagation()
Expand All @@ -166,88 +181,85 @@ const ResultRow = ({row, index, columns, getValue, handleClick, handleRowClick,
}
return (
<React.Fragment>
<TableRow
hover
role="checkbox"
aria-checked={isItemSelectedToShow}
tabIndex={-1}
onClick={event => handleRowClick(event, id)}
selected={isItemSelectedToShow}
className={isItemSelectedToShow ? 'show-item' : ''}
sx={[{
cursor: 'pointer',
backgroundColor: '#FFF',
'&.Mui-selected': {
backgroundColor: bgColor
}
}, isItemSelectedToShow ? {
'&.MuiTableRow-hover:hover': {
backgroundColor: bgColor
}
} : {
'&.MuiTableRow-hover:hover': {
backgroundColor: 'primary.95'
}
}]}
>
{
handleClick &&
<TableCell padding="checkbox" onClick={event => handleClick(event, id)} style={{color: color}}>
<Checkbox
size={size || 'medium'}
color="primary"
checked={isItemSelected}
slotProps={{
input: {
'aria-labelledby': labelId,
},
}}
/>
</TableCell>
}
{
hierarchical &&
<TableCell padding='none' sx={{width: '40px', paddingLeft: `${4 + (level * 24)}px`, whiteSpace: 'nowrap'}}>
{
row.has_children ?
<IconButton size='small' onClick={onExpandClick}>
{ open ? <DownIcon fontSize='inherit' /> : <RightIcon fontSize='inherit' /> }
</IconButton> :
null
}
</TableCell>
}
{
columns.map((column, idx) => {
const value = getValue(row, column)
return idx === 0 ?
<TableCell
key={idx}
component="th"
id={labelId}
scope="row"
padding="normal"
className={column.className}
sx={{color: color, ...column.sx}}
>
{value}
</TableCell>:
<TableCell key={idx} align={column.align || "left"} className={column.className} sx={{color: color, ...column.sx}}>
{value}
</TableCell>
})
}
</TableRow>
{
hierarchical && open && loadingChildren &&
<TableRow>
<TableCell colSpan={colSpan} sx={{paddingLeft: `${28 + (level * 24)}px`}}>
<CircularProgress size={16} />
</TableCell>
// a hidden row renders nothing of its own but stays mounted, keeping its children and expansion
!hidden &&
<TableRow
hover
role="checkbox"
aria-checked={isItemSelectedToShow}
tabIndex={-1}
onClick={event => handleRowClick(event, id)}
selected={isItemSelectedToShow}
className={isItemSelectedToShow ? 'show-item' : ''}
sx={[{
cursor: 'pointer',
backgroundColor: '#FFF',
'&.Mui-selected': {
backgroundColor: bgColor
}
}, isItemSelectedToShow ? {
'&.MuiTableRow-hover:hover': {
backgroundColor: bgColor
}
} : {
'&.MuiTableRow-hover:hover': {
backgroundColor: 'primary.95'
}
}]}
>
{
handleClick &&
<TableCell padding="checkbox" onClick={event => handleClick(event, id)} style={{color: color}}>
<Checkbox
size={size || 'medium'}
color="primary"
checked={isItemSelected}
slotProps={{
input: {
'aria-labelledby': labelId,
},
}}
/>
</TableCell>
}
{
hierarchical &&
<TableCell padding='none' sx={{width: '40px', paddingLeft: `${4 + (level * 24)}px`, whiteSpace: 'nowrap'}}>
{
row.has_children ?
<IconButton size='small' onClick={onExpandClick}>
{ open ? <DownIcon fontSize='inherit' /> : <RightIcon fontSize='inherit' /> }
</IconButton> :
null
}
</TableCell>
}
{
columns.map((column, idx) => {
const value = getValue(row, column)
return idx === 0 ?
<TableCell
key={idx}
component="th"
id={labelId}
scope="row"
padding="normal"
className={column.className}
sx={{color: color, ...column.sx}}
>
{value}
</TableCell>:
<TableCell key={idx} align={column.align || "left"} className={column.className} sx={{color: color, ...column.sx}}>
{value}
</TableCell>
})
}
</TableRow>
}
{
hierarchical && open && !loadingChildren &&
// fetched children stay mounted while collapsed, so they keep their own pages and expansions
hierarchical && fetched &&
children.map((child, i) => (
<ResultRow
key={child.version_url || child.url || child.uuid || i}
Expand All @@ -264,9 +276,45 @@ const ResultRow = ({row, index, columns, getValue, handleClick, handleRowClick,
level={level + 1}
baseURL={baseURL}
onRowsLoaded={onRowsLoaded}
hidden={!showChildren}
/>
))
}
{
showChildren && loadingChildren &&
times(skeletonRows, i => (
<TableRow key={`skeleton-${i}`}>
{handleClick && <TableCell padding="checkbox" />}
<TableCell padding='none' />
{
columns.map((column, idx) => (
<TableCell key={idx}>
<Skeleton variant='text' />
</TableCell>
))
}
</TableRow>
))
}
{
showChildren && !loadingChildren && (childrenFailed || moreChildren) &&
<TableRow>
<TableCell colSpan={colSpan} align='right' sx={{paddingTop: '2px', paddingBottom: '2px'}}>
{
childrenFailed ?
<span style={{color: ERROR_COLORS.main, marginRight: '8px'}}>{t('common.could_not_load')}</span> :
null
}
<Button size='small' onClick={onLoadNextChildren} sx={{textTransform: 'none'}}>
{
childrenFailed ?
t('common.try_again') :
t('common.show_more_of', {shown: children.length.toLocaleString(), total: childrenTotal.toLocaleString()})
}
</Button>
</TableCell>
</TableRow>
}
</React.Fragment>
);
}
Expand Down
66 changes: 66 additions & 0 deletions src/components/search/__tests__/childrenPaging.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import test from 'node:test'
import assert from 'node:assert/strict'

const {
CHILDREN_PAGE_SIZE, initialChildrenState, childrenReducer, mergeChildren, needsFetchOnExpand, nextChildrenPage
} = await import('../childrenPaging.js')

const rows = (from, count) => Array.from({length: count}, (_, i) => ({url: `/concepts/c${from + i}/`}))
const load = (state, page, pageRows, total, hasMore = false) =>
childrenReducer(childrenReducer(state, {type: 'loading'}), {type: 'loaded', page, rows: pageRows, total, hasMore})
const fail = state => childrenReducer(childrenReducer(state, {type: 'loading'}), {type: 'failed'})

test('page 2 is appended after page 1', () => {
const firstPage = load(initialChildrenState, 1, rows(0, CHILDREN_PAGE_SIZE), 30, true)
assert.equal(firstPage.children.length, CHILDREN_PAGE_SIZE)
assert.equal(firstPage.hasMore, true)
assert.equal(nextChildrenPage(firstPage), 2)

const secondPage = load(firstPage, 2, rows(CHILDREN_PAGE_SIZE, 5), 30)
assert.deepEqual(secondPage.children.map(child => child.url), rows(0, 30).map(child => child.url))
assert.equal(secondPage.hasMore, false)
})

test('a failed page keeps what is loaded and retrying asks for the same page once', () => {
const firstPage = load(initialChildrenState, 1, rows(0, CHILDREN_PAGE_SIZE), 30)
const failed = fail(firstPage)
assert.equal(failed.failed, true)
assert.equal(failed.children.length, CHILDREN_PAGE_SIZE)
assert.equal(nextChildrenPage(failed), 2)

const retried = load(failed, nextChildrenPage(failed), rows(CHILDREN_PAGE_SIZE, 5), 30)
assert.equal(retried.failed, false)
assert.equal(retried.children.length, 30)
assert.equal(new Set(retried.children.map(child => child.url)).size, 30)
})

test('collapsing and expanding again does not refetch loaded children', () => {
assert.equal(needsFetchOnExpand(initialChildrenState), true)
const loaded = load(initialChildrenState, 1, rows(0, 3), 3)
assert.equal(needsFetchOnExpand(loaded), false)
})

test('expanding again retries a first page that failed, but not one still loading', () => {
assert.equal(needsFetchOnExpand(fail(initialChildrenState)), true)
assert.equal(needsFetchOnExpand(childrenReducer(initialChildrenState, {type: 'loading'})), false)
})

test('a child returned on two pages is shown once and Show more still ends', () => {
const firstPage = load(initialChildrenState, 1, rows(0, CHILDREN_PAGE_SIZE), 30)
const secondPage = load(firstPage, 2, rows(CHILDREN_PAGE_SIZE - 1, 5), 30)
assert.equal(secondPage.children.length, 29)
assert.equal(new Set(secondPage.children.map(child => child.url)).size, 29)
assert.equal(secondPage.hasMore, false)
})

test('Show more follows the API even when it serves fewer rows than asked', () => {
const firstPage = load(initialChildrenState, 1, rows(0, 10), 40, true)
const secondPage = load(firstPage, 2, rows(10, 10), 40, true)
assert.equal(secondPage.hasMore, true)
assert.equal(nextChildrenPage(secondPage), 3)
})

test('mergeChildren keeps a versioned child apart from another version of it', () => {
const merged = mergeChildren([{version_url: '/concepts/a/1/', url: '/concepts/a/'}], [{version_url: '/concepts/a/2/', url: '/concepts/a/'}])
assert.equal(merged.length, 2)
})
Loading
Loading