Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pagination Front End - Part 1 #9937

Merged
merged 15 commits into from
Apr 5, 2022
25 changes: 25 additions & 0 deletions src/app/lib/utilities/findNClosestIndicies/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Given an array, radiate out bidirectionally from a starting index
// Find the indices of the n closest elements that fulfill a predicate
export default ({ array, startingIndex, n, predicate }) => {
const results = [];
if (predicate(array[startingIndex])) results.push(startingIndex);
let leftPointer = startingIndex - 1;
let rightPointer = startingIndex + 1;

while (leftPointer >= 0 || rightPointer < array.length) {
const searchLeft = leftPointer >= 0;
if (searchLeft && predicate(array[leftPointer])) {
results.push(leftPointer);
}

const searchRight = rightPointer < array.length;
if (searchRight && predicate(array[rightPointer])) {
results.push(rightPointer);
}

if (results.length >= n) break;
leftPointer -= 1;
rightPointer += 1;
}
return results.slice(0, n).sort((a, b) => a - b);
};
92 changes: 92 additions & 0 deletions src/app/lib/utilities/findNClosestIndicies/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import findNClosestIndices from '.';

const tests = [
{
name: 'n = 0',
array: [true],
predicate: Boolean,
startingIndex: 0,
n: 0,
expectedResult: [],
},
{
name: 'no matching element',
array: [false],
predicate: Boolean,
startingIndex: 0,
n: 1,
expectedResult: [],
},
{
name: 'one matching element in position 0',
array: [true],
predicate: Boolean,
startingIndex: 0,
n: 1,
expectedResult: [0],
},
{
name: 'n > matching elements',
array: [true],
predicate: Boolean,
startingIndex: 0,
n: 2,
expectedResult: [0],
},
{
name: 'matching elements > n',
array: [true, true],
predicate: Boolean,
startingIndex: 0,
n: 1,
expectedResult: [0],
},
{
name: 'returns multiple indices - case A',
array: [true, true],
predicate: Boolean,
startingIndex: 0,
n: 2,
expectedResult: [0, 1],
},
{
name: 'returns multiple indices - case B',
array: [false, true, true],
predicate: Boolean,
startingIndex: 0,
n: 2,
expectedResult: [1, 2],
},
{
name: 'returns multiple indices - case C',
array: [false, true, true],
predicate: Boolean,
startingIndex: 2,
n: 2,
expectedResult: [1, 2],
},
{
name: 'searches bidirectionally',
array: [true, false, true],
predicate: Boolean,
startingIndex: 1,
n: 2,
expectedResult: [0, 2],
},
{
name: 'prefers left elements when number of found elements > n',
array: [true, false, true],
predicate: Boolean,
startingIndex: 1,
n: 1,
expectedResult: [0],
},
];

describe('findNClosestIndicies', () => {
it('returns correct results', () => {
tests.forEach(({ expectedResult, name, ...args }) => {
expect(findNClosestIndices(args)).toEqual(expectedResult);
});
});
});
194 changes: 194 additions & 0 deletions src/app/pages/TopicPage/Pagination/buildBlocks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
/* eslint-disable no-param-reassign */
import pipe from 'ramda/src/pipe';
import findNClosestIndices from '#lib/utilities/findNClosestIndicies';

export const AVAILABILITY = {
AVAILABLE: 'AVAILABLE',
UNAVAILABLE: 'UNAVAILABLE',
ACTIVE: 'ACTIVE',
};

export const TYPE = {
ELLIPSIS: 'ELLIPSIS',
LEFT_ARROW: 'LEFT_ARROW',
RIGHT_ARROW: 'RIGHT_ARROW',
NUMBER: 'NUMBER',
};

export const VISIBILITY = {
ALL: 'ALL',
MOBILE_ONLY: 'MOBILE_ONLY',
TABLET_DOWN: 'TABLET_DOWN',
TABLET_UP: 'TABLET_UP',
DESKTOP_ONLY: 'DESKTOP_ONLY',
};

// we're returning an array of page elements to be consumed by the renderer
const createPage = (index, state) => {
const isActivePage = index + 1 === state.activePage;
if (isActivePage) {
state.activePageIndex = index;
}
return {
type: TYPE.NUMBER,
pageNumber: index + 1,
availability: isActivePage ? AVAILABILITY.ACTIVE : AVAILABILITY.AVAILABLE,
};
};

// The first page, last page, and active page should always be visible
const setRequiredVisibility = state => {
state.result[0].visibility = VISIBILITY.ALL;
state.result[state.activePageIndex].visibility = VISIBILITY.ALL;
state.result[state.activePageIndex].availability = AVAILABILITY.ACTIVE;
state.result[state.result.length - 1].visibility = VISIBILITY.ALL;

return state;
};

// Iteratively radiate out from the active page, setting the visibility of pages
// Pages closer to the active page are visible on more devices
const setDynamicVisibility = state => {
const iterations = [
[VISIBILITY.ALL, state.activePageOnEdge ? 1 : 0],
[VISIBILITY.TABLET_UP, state.activePageOnEdge ? 1 : 2],
[VISIBILITY.DESKTOP_ONLY, 4],
];

iterations.forEach(([deviceSize, additionalPagesToShow]) =>
findNClosestIndices({
n: additionalPagesToShow,
startingIndex: state.activePageIndex,
predicate: e => !e.visibility,
array: state.result,
}).forEach(index => {
// keeping track of the visibility level we are setting
// this will help us determine on which devices we need to display an ellipsis
if (index < state.activePageIndex) {
state.highestVisibilityOnLeft = deviceSize;
} else {
state.highestVisibilityOnRight = deviceSize;
}
state.result[index].visibility = deviceSize;
}),
);

return state;

// TODO - if there is just a single number missing at a boundary, fill it in?
// eg if we have 1, 2, 3, 5 - should we just add the 4?
// Otherwise, we'll have an ellipsis being used to fill in a gap of only one number
};

// After setting the visibility of all the pages we want to show, we can remove the others
const pruneInvisible = state => {
state.result = state.result.filter((page, index) => {
if (!page.visibility) {
// if an element is being filtered out, we need to remember we did this
// this is so we can display an ellipsis in this position
if (index < state.activePageIndex) {
state.pagesTruncatedOnLeft = true;
} else {
state.pagesTruncatedOnRight = true;
}
return false;
}
return true;
});

return state;
};

// Determine the devices that an ellipsis is displayed on
const getEllipsisVisibility = (side, state) => {
// If we pruned some pages on this side, we display an ellipsis on all devices
const wasTruncated =
side === 'left' ? state.pagesTruncatedOnLeft : state.pagesTruncatedOnRight;
if (wasTruncated) return VISIBILITY.ALL;

// Otherwise, the ellipsis visibility is based on the visibility of the page on that edge
// eg, if page 2 is visible on all devices, there will never be an ellipsis on the left
// if it is only visible on tablets and up, there will be an ellipsis on mobile
const highestVisibility =
side === 'left'
? state.highestVisibilityOnLeft
: state.highestVisibilityOnRight;

if (!highestVisibility || highestVisibility === VISIBILITY.ALL) return null;
if (highestVisibility === VISIBILITY.TABLET_UP) return VISIBILITY.MOBILE_ONLY;
if (highestVisibility === VISIBILITY.DESKTOP_ONLY)
return VISIBILITY.TABLET_DOWN;
return null;
};

// Conditionally adding the ellipsis blocks to our return value
const insertEllipsis = state => {
const leftEllipsisVisibility = getEllipsisVisibility('left', state);
const rightEllipsisVisibility = getEllipsisVisibility('right', state);
if (leftEllipsisVisibility) {
state.result.splice(1, 0, {
type: TYPE.ELLIPSIS,
visibility: leftEllipsisVisibility,
});
}

if (rightEllipsisVisibility) {
state.result.splice(state.result.length - 1, 0, {
type: TYPE.ELLIPSIS,
visibility: rightEllipsisVisibility,
});
}

return state;
};

// We display left and right arrows on all devices
const insertArrows = state => {
state.result.unshift({
type: TYPE.LEFT_ARROW,
visibility: VISIBILITY.ALL,
// The left arrow is disabled if the user is already on the first page
availability:
state.activePage === 1
? AVAILABILITY.UNAVAILABLE
: AVAILABILITY.AVAILABLE,
});
state.result.push({
type: TYPE.RIGHT_ARROW,
visibility: VISIBILITY.ALL,
// The right arrow is disabled if the user is already on the last page
availability:
state.activePage === state.pageCount
? AVAILABILITY.UNAVAILABLE
: AVAILABILITY.AVAILABLE,
});

return state;
};

const addKeys = state => ({
...state,
result: state.result.map((page, i) => ({ ...page, key: i })),
});

export default (activePage, pageCount) => {
if (pageCount <= 1) return null;
const initialState = {
activePage,
pageCount,
activePageOnEdge: activePage === 1 || activePage === pageCount,
};
Copy link
Contributor

@andrewscfc andrewscfc Mar 25, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When I first looked at this file I was pretty unclear where state is initialised (here I eventually found). I'm unsure of the need for a global state variable in this case 🤔 Can we chain the functions so state is not mutated globally?

On this line for example we could reduce rather than map arrive at the final state value, see below for a sketch of what I might suggest

I feel it reads better and elimates the risk of errors being introduced later when working with global state.


initialState.result = Array(pageCount)
.fill()
.map((_, i) => createPage(i, initialState));

return pipe(
setRequiredVisibility,
setDynamicVisibility,
pruneInvisible,
insertEllipsis,
insertArrows,
addKeys,
)(initialState).result;
};
Loading