generated from adamrybinski/haunted-snow
-
Notifications
You must be signed in to change notification settings - Fork 1
/
paginationMachine.js
84 lines (84 loc) · 2.24 KB
/
paginationMachine.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { assign, createMachine, actions } from './deps.js';
const paginationMachine = createMachine({
id: 'pagination',
initial: 'awaitingTotalPages',
context: {
currentPage: 1
},
on: {
UPDATE_TOTAL_PAGES: {
cond: 'newTotalPagesIsValidValue',
actions: actions.choose([{
cond: 'currentPageIsAboveNewTotalPages',
actions: ['assignTotalPagesToContext', 'goToFirstPage']
}, {
actions: ['assignTotalPagesToContext']
}]),
target: 'idle'
}
},
states: {
awaitingTotalPages: {},
idle: {
on: {
NEXT_PAGE: {
cond: 'canGoToNextPage',
actions: 'goToNextPage'
},
PREV_PAGE: {
cond: 'canGoToPrevPage',
actions: 'goToPrevPage'
},
GO_TO_TARGET_PAGE: {
actions: 'goToTargetPage',
cond: 'targetPageIsWithinBounds'
}
}
}
}
}, {
guards: {
newTotalPagesIsValidValue: (context, event) => {
if (event.type !== 'UPDATE_TOTAL_PAGES') return false;
return event.totalPages > 0;
},
currentPageIsAboveNewTotalPages: (context, event) => {
if (event.type !== 'UPDATE_TOTAL_PAGES') return false;
return context.currentPage > event.totalPages;
},
canGoToNextPage: context => {
return context.currentPage < context.totalPages;
},
canGoToPrevPage: context => {
return context.currentPage > 1;
},
targetPageIsWithinBounds: (context, event) => {
if (event.type !== 'GO_TO_TARGET_PAGE') return false;
return event.targetPage >= 1 && event.targetPage <= context.totalPages;
}
},
actions: {
goToFirstPage: assign({
currentPage: 1
}),
goToPrevPage: assign({
currentPage: context => context.currentPage - 1
}),
goToNextPage: assign({
currentPage: context => context.currentPage + 1
}),
goToTargetPage: assign((context, event) => {
if (event.type !== 'GO_TO_TARGET_PAGE') return {};
return {
currentPage: event.targetPage
};
}),
assignTotalPagesToContext: assign((context, event) => {
if (event.type !== 'UPDATE_TOTAL_PAGES') return {};
return {
totalPages: event.totalPages
};
})
}
});
export default paginationMachine;