This repository has been archived by the owner on Aug 12, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPages.tsx
194 lines (181 loc) · 5.18 KB
/
Pages.tsx
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
import {
FC,
useState,
useRef,
useCallback,
ComponentType,
createContext,
useEffect,
useContext,
createElement,
Fragment,
useMemo,
} from 'react';
import {
SFActions,
actions,
StatefulFormProps,
StatefulForm,
useSFValue,
SFContext,
NO_DEFAULT,
ASYNC_VALIDATION,
} from 'react-stateful-form';
import { ObjectSchema, ValidationError } from 'yup';
interface StatefulFormPagesProps {
onSubmit: StatefulFormProps['onSubmit'];
pages: ComponentType<any>[];
}
export const Pages: FC<StatefulFormPagesProps> = props => {
return (
<StatefulForm
preserveData={true}
onSubmit={values => {
const { '@@pages': pages, ...rest } = values;
if (props.onSubmit) {
return props.onSubmit(rest);
}
}}
render={() => {
const valueState = useSFValue<number[]>(
'@@pages',
[0],
NO_DEFAULT, // Don't get reset
value => (props.pages.length !== value.length ? 'more pages exist' : null)
);
const valueStateRef = useRef(valueState);
valueStateRef.current = valueState;
const pageState = useState(0);
const pageStateRef = useRef(pageState);
pageStateRef.current = pageState;
const setPageIndex = useCallback((index: number) => {
if (index < 0 || index >= props.pages.length) {
return;
}
pageStateRef.current[1](index);
const value = valueStateRef.current[0];
if (value.indexOf(index) !== -1) {
return;
}
valueStateRef.current[1](value.concat(index));
}, []);
const navigate = useCallback((decrement: boolean = false) => {
const newState = decrement ? pageStateRef.current[0] - 1 : pageStateRef.current[0] + 1;
setPageIndex(newState);
}, []);
const pageIndex = pageStateRef.current[0];
const pageProviderValue = useMemo(
() => ({
navigation: {
forward: pageIndex !== props.pages.length - 1,
backward: pageIndex !== 0,
current: pageIndex,
max: props.pages.length - 1,
},
navigate: navigate,
setPageIndex: setPageIndex,
}),
[pageIndex]
);
const Page = props.pages[pageState[0]];
return (
<PagesContext.Provider value={pageProviderValue}>
<Page />
</PagesContext.Provider>
);
}}
/>
);
};
interface PageProps {
validationSchema?: ObjectSchema<{}>;
}
function flushErrorState(
dispatch: (action: SFActions) => void,
keys: string[],
errors?: { path: string; message: string }[]
) {
const errorActions: ReturnType<typeof actions.error>[] = [];
const keysMap: { [key: string]: boolean } = {};
if (errors) {
for (const error of errors) {
keysMap[error.path] = true;
errorActions.push(
actions.error(error.path, {
hasError: true,
errorMessage: error.message,
})
);
}
}
for (const key of keys) {
if (keysMap[key]) {
continue;
}
errorActions.push(
actions.error(key, {
hasError: false,
})
);
}
dispatch(actions.batchErrors(errorActions));
}
export const Page: FC<PageProps> = props => {
const sfCtx = useContext(SFContext);
if (!sfCtx) {
throw new Error('SFContext not found. Use Page inside Pages Component');
}
const validationRequested = useRef(false);
useEffect(() => {
const validationScheme = props.validationSchema;
if (!validationScheme) {
return;
}
const validations: { [key: string]: () => ASYNC_VALIDATION } = {};
const validatefn = () => {
if (!validationRequested.current) {
validationRequested.current = true;
requestAnimationFrame(() => {
validationRequested.current = false;
validationScheme
.validate(sfCtx.stateRef.current.values, { abortEarly: false })
.then(() => {
flushErrorState(
sfCtx.dispatch,
// ObjectSchema has untyped fields
Object.keys((props.validationSchema as any).fields)
);
})
.catch(e => {
if (e instanceof ValidationError) {
flushErrorState(
sfCtx.dispatch,
// ObjectSchema has untyped fields
Object.keys((props.validationSchema as any).fields),
(e as ValidationError).inner
);
}
});
});
}
return ASYNC_VALIDATION;
};
// ObjectSchema has untyped fields
for (const key of Object.keys((props.validationSchema as any).fields)) {
validations[key] = validatefn;
}
sfCtx.dispatch(actions.updateValidations(validations));
}, []);
return <Fragment>{props.children}</Fragment>;
};
interface PagesContext {
readonly navigation: Readonly<{
forward: boolean;
backward: boolean;
current: number;
max: number;
}>;
readonly navigate: (decrement?: boolean) => void;
readonly setPageIndex: (index: number) => void;
}
export const PagesContext = createContext<PagesContext | null>(null);