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
85
86
87
88
89
90
91
92
93
94
|
import { fromJS, List, Map } from 'immutable';
import notif from 'ba-api/notifMessage';
import {
FETCH_DATA,
ADD_EMPTY_ROW,
UPDATE_ROW,
REMOVE_ROW,
EDIT_ROW,
SAVE_ROW,
CLOSE_NOTIF
} from 'ba-actions/actionTypes';
const initialState = {
dataTable: List([]),
notifMsg: '',
};
const initialItem = (keyTemplate, anchor) => {
const [...rawKey] = keyTemplate.keys();
const staticKey = {
id: (+new Date() + Math.floor(Math.random() * 999999)).toString(36),
};
for (let i = 0; i < rawKey.length; i += 1) {
if (rawKey[i] !== 'id' && rawKey[i] !== 'edited') {
staticKey[rawKey[i]] = anchor[i].initialValue;
}
}
// Push another static key
staticKey.edited = true;
return Map(staticKey);
};
const initialImmutableState = fromJS(initialState);
export default function reducer(state = initialImmutableState, action = {}) {
const { branch } = action;
switch (action.type) {
case `${branch}/${FETCH_DATA}`:
return state.withMutations((mutableState) => {
const items = fromJS(action.items);
mutableState.set('dataTable', items);
});
case `${branch}/${ADD_EMPTY_ROW}`:
return state.withMutations((mutableState) => {
const raw = state.get('dataTable').last();
const initial = initialItem(raw, action.anchor);
mutableState.update('dataTable', dataTable => dataTable.unshift(initial));
});
case `${branch}/${REMOVE_ROW}`:
return state.withMutations((mutableState) => {
const index = state.get('dataTable').indexOf(action.item);
mutableState
.update('dataTable', dataTable => dataTable.splice(index, 1))
.set('notifMsg', notif.removed);
});
case `${branch}/${UPDATE_ROW}`:
return state.withMutations((mutableState) => {
const index = state.get('dataTable').indexOf(action.item);
const cellTarget = action.event.target.name;
const newVal = type => {
if (type === 'checkbox') {
return action.event.target.checked;
}
return action.event.target.value;
};
mutableState.update('dataTable', dataTable => dataTable
.setIn([index, cellTarget], newVal(action.event.target.type))
);
});
case `${branch}/${EDIT_ROW}`:
return state.withMutations((mutableState) => {
const index = state.get('dataTable').indexOf(action.item);
mutableState.update('dataTable', dataTable => dataTable
.setIn([index, 'edited'], true)
);
});
case `${branch}/${SAVE_ROW}`:
return state.withMutations((mutableState) => {
const index = state.get('dataTable').indexOf(action.item);
mutableState
.update('dataTable', dataTable => dataTable
.setIn([index, 'edited'], false)
)
.set('notifMsg', notif.saved);
});
case `${branch}/${CLOSE_NOTIF}`:
return state.withMutations((mutableState) => {
mutableState.set('notifMsg', '');
});
default:
return state;
}
}
|