-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathEditorForm.tsx
136 lines (124 loc) · 4.08 KB
/
EditorForm.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
import React, { useState, useEffect, useMemo, PropsWithChildren } from 'react';
import Form, { Field, UiSchema } from '@rjsf/core';
import { useSelector } from 'react-redux';
import { GeoJsonProperties } from 'geojson';
import { JSONSchema7 } from 'json-schema';
import { isNil, omitBy } from 'lodash';
import './EditorForm.scss';
import { useTranslation } from 'react-i18next';
import i18n from 'i18n';
import { EditorEntity } from 'types';
import { translateSchema } from 'applications/editor/tools/translationTools';
import {
getLayerForObjectType,
getJsonSchemaForLayer,
NEW_ENTITY_ID,
} from 'applications/editor/data/utils';
import { EditorState } from 'applications/editor/tools/types';
import { FormComponent, FormLineStringLength } from './LinearMetadata';
const fields = {
ArrayField: FormComponent,
};
interface EditorFormProps<T> {
data: T;
onSubmit: (data: T) => Promise<void>;
onChange?: (data: T) => void;
// Overrides:
overrideSchema?: JSONSchema7;
overrideUiSchema?: UiSchema;
overrideFields?: Record<string, Field>;
}
/**
* Display a form to create/update a new entity.
*/
function EditorForm<T extends Omit<EditorEntity, 'objType'> & { objType: string }>({
data,
onSubmit,
onChange,
overrideSchema,
overrideUiSchema,
overrideFields,
children,
}: PropsWithChildren<EditorFormProps<T>>) {
const [error, setError] = useState<string | null>(null);
const [formData, setFormData] = useState<GeoJsonProperties>(data.properties);
const [submited, setSubmited] = useState<boolean>(false);
const { t } = useTranslation('infraEditor');
const editorState = useSelector((state: { editor: EditorState }) => state.editor);
const layer = useMemo(
() => getLayerForObjectType(editorState.editorSchema, data.objType),
[data.objType, editorState.editorSchema]
);
const schema = useMemo(
() => overrideSchema || getJsonSchemaForLayer(editorState.editorSchema, layer || ''),
[editorState.editorSchema, layer, overrideSchema]
);
if (!schema) throw new Error(`Missing data type for ${layer}`);
const isFrench = i18n.language === 'fr';
const isI18nLoaded = i18n.hasLoadedNamespace('infraEditor');
const translatedSchema = useMemo(() => translateSchema(schema, t), [schema, isI18nLoaded]);
/**
* When data or schema change
* => recompute formData by fixing LM
*/
useEffect(() => {
setFormData(omitBy(data.properties, isNil));
}, [data, schema]);
/**
* When errors are displayed, we scroll to them.
*/
useEffect(() => {
const container = document.getElementsByClassName('panel-box')[0];
if (error && container) {
container.scrollTo({ top: 0, left: 0, behavior: 'smooth' });
}
}, [error]);
return (
<div>
{submited && error !== null && (
<div className="form-error mt-3 mb-3">
<p>{error}</p>
</div>
)}
<Form
fields={{ ...fields, ...(overrideFields || {}) }}
liveValidate={submited}
action={undefined}
noHtml5Validate
method={undefined}
schema={isFrench ? translatedSchema : schema}
uiSchema={{
length: {
'ui:widget': FormLineStringLength,
},
...(overrideUiSchema || {}),
}}
formData={formData}
formContext={{
geometry: data.geometry,
length: data.properties?.length,
isCreation: isNil(formData?.id) || formData?.id === NEW_ENTITY_ID,
}}
onError={() => setSubmited(true)}
onSubmit={async () => {
try {
setError(null);
await onSubmit({ ...data, properties: { ...data.properties, ...formData } });
} catch (e) {
if (e instanceof Error) setError(e.message);
else setError(JSON.stringify(e));
} finally {
setSubmited(true);
}
}}
onChange={(event) => {
setFormData({ ...data.properties, ...event.formData });
onChange?.({ ...data, properties: { ...data.properties, ...event.formData } });
}}
>
{children}
</Form>
</div>
);
}
export default EditorForm;