-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathFormLineStringLength.tsx
77 lines (72 loc) · 2.59 KB
/
FormLineStringLength.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
import React, { useEffect, useState } from 'react';
import { WidgetProps } from '@rjsf/core';
import { useTranslation } from 'react-i18next';
import { isNil, toNumber, isEmpty } from 'lodash';
import { getLineStringDistance, DISTANCE_ERROR_RANGE } from 'common/IntervalsDataViz/data';
export const FormLineStringLength: React.FC<WidgetProps> = (props) => {
const { t } = useTranslation();
const { id, value, required, readonly, onChange, formContext } = props;
const [length, setLength] = useState<number>(value);
const [min, setMin] = useState<number>(-Infinity);
const [max, setMax] = useState<number>(Infinity);
const [geoLength, setGeoLength] = useState<number>(0);
useEffect(() => {
setLength(value);
}, [value]);
/**
* When the geometry changes
* => recompute min & max plus its length
*/
useEffect(() => {
const distance = getLineStringDistance(formContext.geometry);
setMin(Math.round(distance - distance * DISTANCE_ERROR_RANGE));
setMax(Math.round(distance + distance * DISTANCE_ERROR_RANGE));
setGeoLength(distance);
}, [formContext.geometry, formContext.isCreation]);
return (
<div>
{readonly ? (
<span className="form-control readonly bg-light">{value}</span>
) : (
<input
className="form-control"
id={id}
required={required}
type="number"
value={!isNil(length) ? length : ''}
onChange={(e) => {
setLength(e.target.valueAsNumber);
onChange(!isEmpty(e.target.value) ? toNumber(e.target.value) : null);
}}
/>
)}
{geoLength > 0 && (length < min || length > max) && (
<p className="text-warning">
{t('Editor.errors.length-out-of-sync-with-geometry', { min, max })}.{' '}
<button
type="button"
className="btn btn-link btn-secondary"
title={t('Editor.linear-metadata.sync-length-with-geometry')}
onClick={() => onChange(geoLength)}
>
{t('Editor.linear-metadata.sync-length-with-geometry')}
</button>
</p>
)}
{isNil(length) && (
<p className="text-danger">
{t('Editor.errors.length-number-and-required')}
<button
type="button"
className="btn btn-link btn-secondary"
title={t('Editor.linear-metadata.sync-length-with-geometry')}
onClick={() => onChange(geoLength)}
>
{t('Editor.linear-metadata.sync-length-with-geometry')}
</button>
</p>
)}
</div>
);
};
export default FormLineStringLength;