-
-
Notifications
You must be signed in to change notification settings - Fork 301
Expand file tree
/
Copy pathpriorityAreasForm.js
More file actions
323 lines (290 loc) · 10.3 KB
/
priorityAreasForm.js
File metadata and controls
323 lines (290 loc) · 10.3 KB
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import { useState, useContext, useLayoutEffect, createRef } from 'react';
import maplibregl from 'maplibre-gl';
import 'maplibre-gl/dist/maplibre-gl.css';
import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css';
import MapboxDraw from '@mapbox/mapbox-gl-draw';
import DrawRectangle from 'mapbox-gl-draw-rectangle-mode';
import MapboxLanguage from '@mapbox/mapbox-gl-language';
import { featureCollection } from '@turf/helpers';
import { FormattedMessage } from 'react-intl';
import { useDropzone } from 'react-dropzone';
import messages from './messages';
import { StateContext, styleClasses } from '../../views/projectEdit';
import { CustomButton } from '../button';
import { MappedIcon, WasteIcon, MappedSquareIcon, FileImportIcon } from '../svgIcons';
import { MAPBOX_TOKEN, CHART_COLOURS, baseLayers, DEFAULT_MAP_STYLE } from '../../config';
import { BasemapMenu } from '../basemapMenu';
import {
verifyGeometry,
readGeoFile,
verifyFileFormat,
verifyFileSize,
} from '../../utils/geoFileFunctions';
import isWebglSupported from '../../utils/isWebglSupported';
import useSetRTLTextPlugin from '../../utils/useSetRTLTextPlugin';
import { getErrorMsg } from '../projectCreate/fileUploadErrors';
import { Alert } from '../alert';
import WebglUnsupported from '../webglUnsupported';
import useMapboxSupportedLanguage from '../../hooks/UseMapboxSupportedLanguage';
maplibregl.accessToken = MAPBOX_TOKEN;
export const PriorityAreasForm = () => {
const { projectInfo, setProjectInfo } = useContext(StateContext);
const mapboxSupportedLanguage = useMapboxSupportedLanguage();
const mapRef = createRef();
const [error, setError] = useState({ error: false, message: null });
useSetRTLTextPlugin();
const modes = MapboxDraw.modes;
modes.draw_rectangle = DrawRectangle;
const drawOptions = {
displayControlsDefault: false,
modes: modes,
styles: [
{
id: 'gl-draw-polygon-fill-inactive',
type: 'fill',
paint: {
'fill-color': '#d73f3f',
'fill-opacity': 0.3,
},
},
{
id: 'gl-draw-polygon-line-inactive',
type: 'line',
paint: {
'line-color': '#d73f3f',
'line-dasharray': [2, 2],
'line-width': 2,
'line-opacity': 0.7,
},
},
],
};
const [mapObj, setMapObj] = useState({
map: null,
draw: new MapboxDraw(drawOptions),
});
const [activeMode, setActiveMode] = useState(null);
let priorityAreas = projectInfo.priorityAreas ? projectInfo.priorityAreas : [];
// update priority areas as features
const drawPriorityAreas = priorityAreas.map((a) => ({
type: 'Feature',
properties: {},
geometry: a,
}));
const uploadFile = (files) => {
const file = files[0];
if (!file) return;
try {
setError({ error: false, message: null }); //reset error on new file upload
verifyFileSize(file);
verifyFileFormat(file);
readGeoFile(file)
.then((geometry) => {
verifyAndRenderPriorityArea(geometry);
})
.catch((e) => setError({ error: true, message: getErrorMsg(e.message) || e.message }));
} catch (err) {
setError({ error: true, message: getErrorMsg(err.message) || err.message });
}
};
const verifyAndRenderPriorityArea = (geom) => {
const supportedGeoms = ['Polygon'];
try {
let validGeometry = verifyGeometry(geom, supportedGeoms);
priorityAreas = validGeometry.features.map((g) => g.geometry);
setProjectInfo({ ...projectInfo, priorityAreas: priorityAreas });
mapObj.map.getSource('priority_areas').setData(validGeometry);
} catch (err) {
setError({ error: true, message: getErrorMsg(err.message) || err.message });
}
};
const { getRootProps, getInputProps, open } = useDropzone({
onDrop: uploadFile,
noClick: true,
noKeyboard: true,
});
useLayoutEffect(() => {
const map =
isWebglSupported() &&
new maplibregl.Map({
container: mapRef.current,
style: DEFAULT_MAP_STYLE,
center: [0, 0],
zoom: 1,
attributionControl: false,
})
.addControl(new maplibregl.AttributionControl({ compact: false }))
.addControl(new MapboxLanguage({ defaultLanguage: mapboxSupportedLanguage }))
.addControl(new maplibregl.NavigationControl());
setMapObj({ ...mapObj, map: map });
return () => map && map.remove();
// eslint-disable-next-line
}, []);
const addMapLayers = (map) => {
// load all base layer and toggle visibility
for (const [key, value] of Object.entries(baseLayers)) {
if (mapObj.map.getSource(`${key}-source`) === undefined) {
mapObj.map.addSource(`${key}-source`, value.source);
mapObj.map.addLayer(value.layer);
}
}
if (map.getSource('aoi') === undefined) {
map.addSource('aoi', {
type: 'geojson',
data: projectInfo.areaOfInterest,
});
map.addLayer({
id: 'aoi',
source: 'aoi',
type: 'fill',
paint: {
'fill-color': CHART_COLOURS.orange,
'fill-outline-color': '#929db3',
'fill-opacity': 0.4,
},
});
}
if (map.getSource('priority_areas') === undefined) {
// Render priority areas.
map.addSource('priority_areas', {
type: 'geojson',
data: { type: 'FeatureCollection', features: drawPriorityAreas },
});
map.addLayer({
id: 'priority_area_border',
type: 'line',
source: 'priority_areas',
paint: {
'line-color': '#d73f3f',
'line-dasharray': [2, 2],
'line-width': 2,
'line-opacity': 0.7,
},
layout: {
visibility: 'visible',
},
});
map.addLayer({
id: 'priority_areas',
type: 'fill',
source: 'priority_areas',
paint: {
'fill-color': '#d73f3f',
'fill-opacity': 0.3,
},
layout: {
visibility: 'visible',
},
});
}
};
const updatePriorityAreas = (event) => {
priorityAreas.push(event.features[0].geometry);
setProjectInfo({ ...projectInfo, priorityAreas: priorityAreas });
setActiveMode(null);
};
const drawPolygonHandler = () => {
if (activeMode === 'draw_polygon') {
setActiveMode(null);
mapObj.draw.changeMode('simple_select');
return;
}
setActiveMode('draw_polygon');
mapObj.map.on('draw.update', updatePriorityAreas);
mapObj.map.once('draw.create', updatePriorityAreas);
mapObj.draw.changeMode('draw_polygon');
};
const drawRectangleHandler = () => {
if (activeMode === 'draw_rectangle') {
setActiveMode(null);
mapObj.draw.changeMode('simple_select');
return;
}
setActiveMode('draw_rectangle');
mapObj.map.on('draw.update', updatePriorityAreas);
mapObj.map.once('draw.create', updatePriorityAreas);
mapObj.draw.changeMode('draw_rectangle');
};
useLayoutEffect(() => {
if (mapObj.map !== null && isWebglSupported()) {
mapObj.map.on('load', () => {
addMapLayers(mapObj.map);
mapObj.map.addControl(mapObj.draw);
mapObj.map.fitBounds(projectInfo.aoiBBOX, { duration: 0, padding: 100 });
});
mapObj.map.on('styledata', () => {
addMapLayers(mapObj.map);
if (mapObj.map.getSource('priority_areas') !== undefined) {
mapObj.map
.getSource('priority_areas')
.setData({ type: 'FeatureCollection', features: drawPriorityAreas });
}
});
}
// eslint-disable-next-line
}, [mapObj.map, mapObj.draw, projectInfo, setProjectInfo, drawPriorityAreas]);
const clearAll = () => {
const currentDrawMode = mapObj.draw.getMode();
mapObj.draw.deleteAll();
mapObj.draw.changeMode(currentDrawMode);
mapObj.map.getSource('priority_areas').setData(featureCollection([]));
setProjectInfo({ ...projectInfo, priorityAreas: [] });
};
if (!isWebglSupported()) {
return <WebglUnsupported className="vh-75 w-100 bg-white" />;
} else {
return (
<div className="w-100" {...getRootProps()}>
<div className="relative">
<div className="cf absolute bg-white o-90 top-1 left-1 pa3 mw6 z-4 br1">
<p className={styleClasses.pClass}>
<FormattedMessage {...messages.priorityAreasDescription} />
</p>
<div>
<CustomButton
className={`bg-white ph3 pv2 mr2 ba ${
activeMode === 'draw_polygon' ? 'red b--red' : 'blue-dark b--grey-light'
}`}
onClick={drawPolygonHandler}
>
<MappedIcon className="h1 w1 pb1 v-mid mr2" />
<FormattedMessage {...messages.drawPolygon} />
</CustomButton>
<CustomButton
className={`bg-white ph3 pv2 mr2 ba ${
activeMode === 'draw_rectangle' ? 'red b--red' : 'blue-dark b--grey-light'
}`}
onClick={drawRectangleHandler}
>
<MappedSquareIcon className="h1 w1 pb1 v-mid mr2" />
<FormattedMessage {...messages.drawRectangle} />
</CustomButton>
<CustomButton className="bg-white blue-dark ba b--grey-light ph3 pv2" onClick={open}>
<FileImportIcon className="h1 w1 v-mid mr2" />
<FormattedMessage {...messages.selectFile} />
</CustomButton>
<input {...getInputProps()} />
<p className="f6 blue-grey lh-title mt3">
<FormattedMessage {...messages.importDescription} />
</p>
<p className="f5 mb0">
<CustomButton
onClick={clearAll}
className="bg-white ph3 pv2 mr2 blue-dark ba b--grey-light"
>
<WasteIcon className="h1 w1 pb1 v-mid mr2" />
<FormattedMessage {...messages.clearAll} />
</CustomButton>
</p>
</div>
{error.error === true && <Alert type="error">{error.message}</Alert>}
</div>
<div className="absolute top-0 right-0 z-5 mr2">
<BasemapMenu map={mapObj.map} />
</div>
<div id="priority-area-map" ref={mapRef} className="vh-75 w-100 bg-white"></div>
</div>
</div>
);
}
};