-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
index.ts
57 lines (44 loc) · 1.88 KB
/
index.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
import {useCallback, useRef, useState} from 'react';
import type {SubStepProps, UseSubStep} from './types';
/**
* This hook ensures uniform handling of components across different screens, enabling seamless integration and navigation through sub steps of the VBBA flow.
* @param bodyContent - array of components to display in particular step
* @param onFinished - callback triggered after finish last step
* @param startFrom - initial index for bodyContent array
*/
export default function useSubStep<TProps extends SubStepProps>({bodyContent, onFinished, startFrom = 0}: UseSubStep<TProps>) {
const [screenIndex, setScreenIndex] = useState(startFrom);
const isEditing = useRef(false);
const prevScreen = useCallback(() => {
const prevScreenIndex = screenIndex - 1;
if (prevScreenIndex < 0) {
return;
}
setScreenIndex(prevScreenIndex);
}, [screenIndex]);
const nextScreen = useCallback(() => {
if (isEditing.current) {
isEditing.current = false;
setScreenIndex(bodyContent.length - 1);
return;
}
const nextScreenIndex = screenIndex + 1;
if (nextScreenIndex === bodyContent.length) {
onFinished();
} else {
setScreenIndex(nextScreenIndex);
}
}, [screenIndex, bodyContent.length, onFinished]);
const moveTo = useCallback((step: number) => {
isEditing.current = true;
setScreenIndex(step);
}, []);
const resetScreenIndex = useCallback(() => {
setScreenIndex(0);
}, []);
const goToTheLastStep = useCallback(() => {
isEditing.current = false;
setScreenIndex(bodyContent.length - 1);
}, [bodyContent]);
return {componentToRender: bodyContent[screenIndex], isEditing: isEditing.current, screenIndex, prevScreen, nextScreen, moveTo, resetScreenIndex, goToTheLastStep};
}