-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathForm.tsx
303 lines (267 loc) · 10.7 KB
/
Form.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
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import React, { useEffect, useMemo } from 'react';
import { Helmet } from 'react-helmet-async';
import { Flex } from 'src/app-components/Flex/Flex';
import classes from 'src/components/form/Form.module.css';
import { MessageBanner } from 'src/components/form/MessageBanner';
import { ErrorReport, ErrorReportList } from 'src/components/message/ErrorReport';
import { ReadyForPrint } from 'src/components/ReadyForPrint';
import { Loader } from 'src/core/loading/Loader';
import { useAppName, useAppOwner } from 'src/core/texts/appTexts';
import { useApplicationMetadata } from 'src/features/applicationMetadata/ApplicationMetadataProvider';
import { useExpandedWidthLayouts, useLayoutLookups } from 'src/features/form/layout/LayoutsContext';
import { useNavigateToNode, useRegisterNodeNavigationHandler } from 'src/features/form/layout/NavigateToNode';
import { useUiConfigContext } from 'src/features/form/layout/UiConfigContext';
import { usePageSettings } from 'src/features/form/layoutSettings/LayoutSettingsContext';
import { useLanguage } from 'src/features/language/useLanguage';
import {
SearchParams,
useNavigate,
useNavigationParam,
useNavigationPath,
useQueryKey,
useQueryKeysAsString,
useQueryKeysAsStringAsRef,
} from 'src/features/routing/AppRoutingContext';
import { useOnFormSubmitValidation } from 'src/features/validation/callbacks/onFormSubmitValidation';
import { useTaskErrors } from 'src/features/validation/selectors/taskErrors';
import { useCurrentView, useNavigatePage, useStartUrl } from 'src/hooks/useNavigatePage';
import { getComponentCapabilities } from 'src/layout';
import { GenericComponentById } from 'src/layout/GenericComponent';
import { getPageTitle } from 'src/utils/getPageTitle';
import { NodesInternal, useNode } from 'src/utils/layout/NodesContext';
import type { NavigateToNodeOptions } from 'src/features/form/layout/NavigateToNode';
import type { AnyValidation, BaseValidation, NodeRefValidation } from 'src/features/validation';
import type { NodeData } from 'src/utils/layout/types';
interface FormState {
hasRequired: boolean;
mainIds: string[];
errorReportIds: string[];
formErrors: NodeRefValidation<AnyValidation<'error'>>[];
taskErrors: BaseValidation<'error'>[];
}
export function Form() {
const currentPageId = useCurrentView();
return <FormPage currentPageId={currentPageId} />;
}
export function FormPage({ currentPageId }: { currentPageId: string | undefined }) {
const { isValidPageId, navigateToPage } = useNavigatePage();
const appName = useAppName();
const appOwner = useAppOwner();
const { langAsString } = useLanguage();
const { hasRequired, mainIds, errorReportIds, formErrors, taskErrors } = useFormState(currentPageId);
const requiredFieldsMissing = NodesInternal.usePageHasVisibleRequiredValidations(currentPageId);
useRedirectToStoredPage();
useSetExpandedWidth();
useRegisterNodeNavigationHandler(async (targetNode, options) => {
const targetView = targetNode?.pageKey;
if (targetView && targetView !== currentPageId) {
await navigateToPage(targetView, {
...options?.pageNavOptions,
shouldFocusComponent: options?.shouldFocus ?? options?.pageNavOptions?.shouldFocusComponent ?? true,
replace:
window.location.href.includes(SearchParams.FocusComponentId) ||
window.location.href.includes(SearchParams.ExitSubform),
});
return true;
}
return false;
});
if (!currentPageId || !isValidPageId(currentPageId)) {
return <FormFirstPage />;
}
const hasSetCurrentPageId = langAsString(currentPageId) !== currentPageId;
if (!hasSetCurrentPageId) {
window.logWarnOnce(
`You have not set a page title for this page. This is highly recommended for user experience and WCAG compliance and will be required in the future.
To add a title to this page, add this to your language resource file (for example language.nb.json):
{
"id": "${currentPageId}",
"value": "Your custom title goes here"
}`,
);
}
return (
<>
<Helmet>
<title>{`${getPageTitle(appName, hasSetCurrentPageId ? langAsString(currentPageId) : undefined, appOwner)}`}</title>
</Helmet>
{hasRequired && (
<MessageBanner
error={requiredFieldsMissing}
messageKey='form_filler.required_description'
/>
)}
<Flex
container
spacing={6}
alignItems='flex-start'
>
{mainIds.map((id) => (
<GenericComponentById
key={id}
id={id}
/>
))}
{formErrors.length > 0 || taskErrors.length > 0 ? (
<Flex
item={true}
size={{ xs: 12 }}
aria-live='polite'
className={classes.errorReport}
>
<ErrorReport
errors={
<ErrorReportList
formErrors={formErrors}
taskErrors={taskErrors}
/>
}
>
{errorReportIds.map((id) => (
<GenericComponentById
key={id}
id={id}
/>
))}
</ErrorReport>
</Flex>
) : null}
</Flex>
<ReadyForPrint type='load' />
<HandleNavigationFocusComponent />
</>
);
}
export function FormFirstPage() {
const navigate = useNavigate();
const startUrl = useStartUrl();
const currentLocation = `${useNavigationPath()}${useQueryKeysAsString()}`;
useEffect(() => {
if (currentLocation !== startUrl) {
navigate(startUrl, { replace: true });
}
}, [currentLocation, navigate, startUrl]);
return <Loader reason='navigate-to-start' />;
}
/**
* Redirects users that had a stored page in their local storage to the correct
* page, and later removes this currentViewCacheKey from localstorage, as
* it is no longer needed.
*/
function useRedirectToStoredPage() {
const pageKey = useCurrentView();
const instanceOwnerPartyId = useNavigationParam('instanceOwnerPartyId');
const instanceGuid = useNavigationParam('instanceGuid');
const { isValidPageId, navigateToPage } = useNavigatePage();
const applicationMetadataId = useApplicationMetadata()?.id;
const instanceId = `${instanceOwnerPartyId}/${instanceGuid}`;
const currentViewCacheKey = instanceId || applicationMetadataId;
useEffect(() => {
if (!pageKey && !!currentViewCacheKey) {
const lastVisitedPage = localStorage.getItem(currentViewCacheKey);
if (lastVisitedPage !== null && isValidPageId(lastVisitedPage)) {
localStorage.removeItem(currentViewCacheKey);
navigateToPage(lastVisitedPage, { replace: true });
}
}
}, [pageKey, currentViewCacheKey, isValidPageId, navigateToPage]);
}
/**
* Sets the expanded width for the current page if it is defined in the currently viewed layout-page
*/
function useSetExpandedWidth() {
const currentPageId = useCurrentView();
const expandedPagesFromLayout = useExpandedWidthLayouts();
const expandedWidthFromSettings = usePageSettings().expandedWidth;
const { setExpandedWidth } = useUiConfigContext();
useEffect(() => {
let defaultExpandedWidth = false;
if (currentPageId && expandedPagesFromLayout[currentPageId] !== undefined) {
defaultExpandedWidth = !!expandedPagesFromLayout[currentPageId];
} else if (expandedWidthFromSettings !== undefined) {
defaultExpandedWidth = expandedWidthFromSettings;
}
setExpandedWidth(defaultExpandedWidth);
}, [currentPageId, expandedPagesFromLayout, expandedWidthFromSettings, setExpandedWidth]);
}
const emptyArray = [];
function nodeDataIsRequired(n: NodeData) {
const item = n.item;
return !!(item && 'required' in item && item.required === true);
}
function useFormState(currentPageId: string | undefined): FormState {
const lookups = useLayoutLookups();
const topLevelIds = currentPageId ? (lookups.topLevelComponents[currentPageId] ?? emptyArray) : emptyArray;
const { formErrors, taskErrors } = useTaskErrors();
const hasErrors = Boolean(formErrors.length) || Boolean(taskErrors.length);
const [mainIds, errorReportIds] = useMemo(() => {
if (!hasErrors) {
return [topLevelIds, emptyArray];
}
const toMainLayout: string[] = [];
const toErrorReport: string[] = [];
for (const id of [...topLevelIds].reverse()) {
const type = lookups.allComponents[id]?.type;
if (!type) {
continue;
}
const capabilities = getComponentCapabilities(type);
const isButtonLike = type === 'ButtonGroup' || (capabilities.renderInButtonGroup && type !== 'Custom');
if (isButtonLike && toMainLayout.length === 0) {
toErrorReport.push(id);
} else {
toMainLayout.push(id);
}
}
return [toMainLayout.reverse(), toErrorReport.reverse()];
}, [hasErrors, lookups.allComponents, topLevelIds]);
const hasRequired = NodesInternal.useSelector((state) =>
Object.values(state.nodeData).some((node) => node.pageKey === currentPageId && nodeDataIsRequired(node)),
);
return {
hasRequired,
mainIds,
errorReportIds,
formErrors,
taskErrors,
};
}
function HandleNavigationFocusComponent() {
const onFormSubmitValidation = useOnFormSubmitValidation();
const searchStringRef = useQueryKeysAsStringAsRef();
const componentId = useQueryKey(SearchParams.FocusComponentId);
const exitSubform = useQueryKey(SearchParams.ExitSubform)?.toLocaleLowerCase() === 'true';
const validate = useQueryKey(SearchParams.Validate)?.toLocaleLowerCase() === 'true';
const focusNode = useNode(componentId ?? undefined);
const navigateTo = useNavigateToNode();
const navigate = useNavigate();
React.useEffect(() => {
(async () => {
// Replace URL if we have query params
if (focusNode || exitSubform || validate) {
const location = new URLSearchParams(searchStringRef.current);
location.delete(SearchParams.FocusComponentId);
location.delete(SearchParams.ExitSubform);
location.delete(SearchParams.Validate);
const baseHash = window.location.hash.slice(1).split('?')[0];
const nextLocation = location.size > 0 ? `${baseHash}?${location.toString()}` : baseHash;
navigate(nextLocation, { replace: true });
}
// Set validation visibility to the equivalent of trying to submit
if (validate) {
onFormSubmitValidation();
}
// Focus on node?
if (focusNode) {
const nodeNavOptions: NavigateToNodeOptions = {
shouldFocus: true,
pageNavOptions: {
resetReturnToView: !exitSubform,
},
};
await navigateTo(focusNode, nodeNavOptions);
}
})();
}, [navigateTo, focusNode, navigate, searchStringRef, exitSubform, validate, onFormSubmitValidation]);
return null;
}