-
Notifications
You must be signed in to change notification settings - Fork 22
/
use-lunatic.ts
221 lines (204 loc) · 5.45 KB
/
use-lunatic.ts
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import { useCallback, useMemo, useReducer } from 'react';
import {
goToPageAction,
goNextPageAction,
goPreviousPageAction,
handleChangesAction,
} from './actions';
import { getPageTag, isFirstLastPage } from './commons';
import type {
LunaticChangesHandler,
LunaticData,
LunaticOptions,
LunaticState,
PageTag,
} from './type';
import D from '../i18n';
import { COLLECTED } from '../utils/constants';
import { createLunaticProvider } from './lunatic-context';
import type { LunaticSource } from './type';
import { compileControls as compileControlsLib } from './commons/compile-controls';
import { useLoopVariables } from './hooks/use-loop-variables';
import { getQuestionnaireData } from './commons/variables/get-questionnaire-data';
import { useTrackChanges } from '../hooks/use-track-changes';
import { usePageHasResponse } from './hooks/use-page-has-response';
import { useOverview } from './hooks/useOverview';
import { reducerInitializer } from './reducer/reducerInitializer';
import { getComponentsFromState } from './commons/get-components-from-state';
import { fillComponents } from './commons/fill-components/fill-components';
import { reducer } from './reducer/reducer';
import { mergeDefault } from '../utils/object';
import { useRefSync } from '../hooks/useRefSync';
import { ConsoleLogger } from './logger/ConsoleLogger';
import { useWarnDepChange } from './hooks/useWarnDepChange';
const empty = {}; // Keep the same empty object (to avoid problem with useEffect dependencies)
const DEFAULT_DATA = empty as LunaticData;
const DEFAULT_FEATURES = ['VTL', 'MD'] as ['VTL', 'MD'];
const DEFAULT_PREFERENCES = [COLLECTED] as ['COLLECTED'];
const DEFAULT_SHORTCUT = { dontKnow: '', refused: '' };
const DEFAULT_DONT_KNOW = D.DK;
const DEFAULT_REFUSED = D.RF;
const defaultOptions = {
features: DEFAULT_FEATURES,
preferences: DEFAULT_PREFERENCES,
savingType: COLLECTED,
onChange: () => {},
onVariableChange: () => {},
management: false,
shortcut: false,
initialPage: '1' as PageTag,
lastReachedPage: undefined,
autoSuggesterLoading: false,
activeControls: false,
// Calculate an overview of every sequence (will be exposed as "overview")
withOverview: false,
missing: false,
missingStrategy: () => {},
missingShortcut: DEFAULT_SHORTCUT,
dontKnowButton: DEFAULT_DONT_KNOW,
refusedButton: DEFAULT_REFUSED,
trackChanges: false,
logger: ConsoleLogger,
} satisfies LunaticOptions;
export function useLunatic(
source: LunaticSource,
data: LunaticData = DEFAULT_DATA,
argOptions: LunaticOptions = empty
) {
const options = mergeDefault(argOptions, defaultOptions);
const {
management,
missing,
missingStrategy,
shortcut,
missingShortcut,
dontKnowButton,
refusedButton,
onChange,
trackChanges,
preferences,
logger,
} = options;
// Help debug with warnings for options expected to be memoized
useWarnDepChange(
logger,
"'logger' option should not change between render",
logger
);
const [state, dispatch] = useReducer(
reducer,
{
...options,
source,
data,
onVariableChange: useRefSync(options.onVariableChange),
},
reducerInitializer
);
// Required context provider: cleaner than prop drilling through every component
const Provider = useMemo(
() =>
createLunaticProvider({
management,
missing,
missingStrategy,
shortcut,
missingShortcut,
dontKnowButton,
refusedButton,
}),
[
management,
missing,
missingStrategy,
shortcut,
missingShortcut,
dontKnowButton,
refusedButton,
]
);
const compileControls: LunaticState['compileControls'] = () => {
return compileControlsLib(state);
};
const goPreviousPage: LunaticState['goPreviousPage'] = useCallback(
function () {
dispatch(goPreviousPageAction());
},
[dispatch]
);
const goNextPage: LunaticState['goNextPage'] = useCallback(
function (payload = {}) {
dispatch(goNextPageAction(payload));
},
[dispatch]
);
const goToPage: LunaticState['goToPage'] = useCallback(
function (payload) {
dispatch(goToPageAction(payload));
},
[dispatch]
);
const handleChanges = useCallback<LunaticChangesHandler>(
(responses) => {
dispatch(handleChangesAction(responses));
onChange(responses);
},
[dispatch, onChange]
);
const getData: LunaticState['getData'] = (
withRefreshedCalculated,
variableNames
) => {
return getQuestionnaireData(
state.variables,
source.variables,
withRefreshedCalculated,
variableNames
);
};
const { resetChangedData, getChangedData } = useTrackChanges(
trackChanges,
state.variables,
(variableNames?: string[]) => getData(false, variableNames)
);
const pageTag = getPageTag(state.pager);
const { isFirstPage, isLastPage } = isFirstLastPage(state.pager);
const components = fillComponents(getComponentsFromState(state), {
handleChanges,
preferences,
goToPage,
shortcut,
goNextPage,
goPreviousPage,
management,
...state,
});
const getComponents: LunaticState['getComponents'] = () => {
return components;
};
return {
pageTag,
isFirstPage,
isLastPage,
updatedAt: state.updatedAt,
pager: state.pager,
isInLoop: state.isInLoop,
overview: useOverview(state, [pageTag]),
loopVariables: useLoopVariables(state.pager, state.pages),
// Methods
getComponents,
goPreviousPage,
goNextPage,
goToPage,
compileControls,
getData,
getChangedData,
resetChangedData,
hasPageResponse: usePageHasResponse(components, state.executeExpression),
// Components
Provider,
testing: {
handleChanges,
},
} satisfies LunaticState;
}