-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathDrawModeRenderer.ts
More file actions
344 lines (312 loc) · 12.3 KB
/
DrawModeRenderer.ts
File metadata and controls
344 lines (312 loc) · 12.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
import { MapboxLayer } from '@deck.gl/mapbox';
import gpsi from 'geojson-polygon-self-intersections';
import { setMapInteractivity } from '~utils/map/setMapInteractivity';
import { registerMapListener } from '~core/shared_state/mapListeners';
import { i18n } from '~core/localization';
import { LogicalLayerDefaultRenderer } from '~core/logical_layers/renderers/DefaultRenderer';
import { createDrawingLayers, drawModes } from '../constants';
import { layersConfigs } from '../configs';
import type { ApplicationMap } from '~components/ConnectedMap/ConnectedMap';
import type { DrawModeType } from '../constants';
import type { FeatureCollection, Feature } from 'geojson';
import type { NotNullableMap, CommonHookArgs } from '~core/logical_layers/types/renderer';
import type { CombinedAtom } from '../atoms/combinedAtom';
import type { NotificationType } from '~core/shared_state/currentNotifications';
import type { NotificationMessage } from '~core/types/notification';
type mountedDeckLayersType = {
[key in DrawModeType]?: MapboxLayer<unknown>;
};
const completedTypes = [
'selectFeature',
'addPosition',
'removePosition',
'finishMovePosition',
'rotated',
'translated',
'scaled',
];
export class DrawModeRenderer extends LogicalLayerDefaultRenderer<CombinedAtom> {
public readonly id: string;
public readonly name?: string;
public mode?: DrawModeType;
public mountedDeckLayers: mountedDeckLayersType;
public drawnData: FeatureCollection;
public selectedIndexes: number[] = [];
private _map!: ApplicationMap;
private _createDrawingLayer: DrawModeType | null;
private _editDrawingLayer: DrawModeType | null;
private _removeClickListener: null | (() => void) = null;
private _removeMousemoveListener: null | (() => void) = null;
private _previousValidGeometry: FeatureCollection = {
type: 'FeatureCollection',
features: [],
};
// actions
private _setFeaturesAction: (features: Feature[]) => void = () =>
console.error('setFeatures action isn`t available yet');
private _addFeatureAction: (feature: Feature) => void = () =>
console.error('addFeature action isn`t available yet');
private _updateTempFeaturesAction: (
features: Feature[],
updateIndexes: number[],
) => void = () => console.error('updateTempFeatures action isn`t available yet');
private _showNotificationAction: (
type: NotificationType,
message: NotificationMessage,
lifetimeSec: number,
) => void = () => console.error('showNotification action isn`t available yet');
private _setSelectedIndexes: (indexes: number[]) => void = () =>
console.error('setIndexes action isn`t available yet');
private _setDrawingStarted: (isStarted: boolean) => void = () =>
console.error('setDrawingStarting action isn`t available yet');
// hooks
public constructor(id: string, name?: string) {
super();
this.id = id;
this.mountedDeckLayers = {};
this.drawnData = {
features: [],
type: 'FeatureCollection',
};
if (name) {
this.name = name;
}
this._createDrawingLayer = null;
this._editDrawingLayer = null;
}
willMount(args: NotNullableMap & CommonHookArgs): void {
this._map = args.map;
}
willUnMount(args: NotNullableMap & CommonHookArgs): void {
this._setDrawingStarted(false);
this._removeAllDeckLayers(args.map);
this._detachEventBlockers();
}
willHide(args: NotNullableMap & CommonHookArgs): void {
this._removeAllDeckLayers(args.map);
this._detachEventBlockers();
}
willUnhide(args: NotNullableMap & CommonHookArgs): void {
this.addClickListener();
}
setupExtension(extentionAtom: CombinedAtom): void {
this._setFeaturesAction = (features) => extentionAtom.setFeatures.dispatch(features);
this._addFeatureAction = (feature) => {
this._map.doubleClickZoom.disable();
extentionAtom.addFeature.dispatch(feature);
};
extentionAtom.hookWithAtom.dispatch([
'drawnGeometryAtom',
(featureCollection) => {
this._previousValidGeometry = featureCollection;
this._updateData(featureCollection);
},
]);
this._updateTempFeaturesAction = (features, indexes) =>
extentionAtom.updateTempFeatures.dispatch({ features, indexes });
extentionAtom.hookWithAtom.dispatch([
'temporaryGeometryAtom',
(featureCollection) => {
// temporary geometry clears out after every deletion of any amount of features
// if we cleared temporaryGeometry, there's no need to clear all displayed geometry (geometry from drawnGeometryAtom)
if (featureCollection.features.length) this._updateData(featureCollection);
},
]);
this._setSelectedIndexes = (indexes) => extentionAtom.setIndexes.dispatch(indexes);
extentionAtom.hookWithAtom.dispatch([
'selectedIndexesAtom',
(indexes) => {
this.selectedIndexes = [...indexes];
if (this.mode) {
const layer = this.mountedDeckLayers[this.mode];
layer?.setProps({
selectedFeatureIndexes: this.selectedIndexes,
});
}
},
]);
this._setDrawingStarted = (isStarted) =>
extentionAtom.setDrawingIsStarted.dispatch(isStarted);
this._showNotificationAction = (type, message, lifetimeSec) =>
extentionAtom.showNotification.dispatch({ type, message, lifetimeSec });
}
// Public methods
public setMode(mode: DrawModeType) {
this.mode = mode;
// Case setting mode to create drawings
if (createDrawingLayers.includes(mode)) {
// if we had other drawing mode - remove it
if (this._createDrawingLayer && this._createDrawingLayer !== mode)
this._removeDeckLayer(this._createDrawingLayer);
this._addDeckLayer(drawModes[mode]);
this._createDrawingLayer = mode;
}
// Case editing - remove create-drawing modes, add modify and icon showing modes
else {
// Case switched from create drawig mode - remove create-drawing modes
if (this._createDrawingLayer) {
this._removeDeckLayer(this._createDrawingLayer);
this._createDrawingLayer = null;
}
if (this._editDrawingLayer === mode) return;
this._addDeckLayer(drawModes[mode]);
this._editDrawingLayer = mode;
}
}
public addClickListener() {
if (this._removeClickListener !== null) return;
function preventClicking(e) {
e.preventDefault();
return false;
}
function preventMousemove(e) {
return false;
}
this._removeClickListener = registerMapListener('click', preventClicking, 10);
this._removeMousemoveListener = registerMapListener(
'mousemove',
preventMousemove,
10,
);
}
// Private methods
private _detachEventBlockers(): void {
this._removeClickListener?.();
this._removeClickListener = null;
this._removeMousemoveListener?.();
this._removeMousemoveListener = null;
}
_addDeckLayer(mode: DrawModeType): void {
if (this.mountedDeckLayers[mode])
return console.error(`cannot add ${mode} as it's already mounted`);
const config = layersConfigs[mode];
// Types for data are wrong. See https://deck.gl/docs/api-reference/layers/geojson-layer#data
if (mode === drawModes.ModifyMode) {
config.data = this.drawnData;
config.selectedFeatureIndexes = this.selectedIndexes;
config.onEdit = this._onModifyEdit;
config.getEditHandleIcon = (d) => {
if (
d.properties.editHandleType === 'scale' ||
d.properties.editHandleType === 'rotate'
)
return 'pointIcon';
if (!('featureIndex' in d.properties)) return null;
const featureToHandle = this.drawnData.features[d.properties.featureIndex];
if (featureToHandle.geometry.type !== 'Point') return 'pointIcon';
return 'selectedIcon';
};
config.getEditHandleIconSize = (d) => {
if (!('featureIndex' in d.properties)) return 1.8;
const featureToHandle = this.drawnData.features[d.properties.featureIndex];
if (featureToHandle.geometry.type !== 'Point') return 1.8;
return 6;
};
config.geojsonIcons.getIcon = (d) => {
if (!d.properties || d.properties.isHidden) return null;
if (d.properties.isSelected) return 'selectedIcon';
return 'defaultIcon';
};
} else if (createDrawingLayers.includes(mode)) {
config.onEdit = this._onDrawEdit;
}
config._subLayerProps.guides.pointRadiusMinPixels = 4;
config._subLayerProps.guides.pointRadiusMaxPixels = 4;
const deckLayer = new MapboxLayer({ ...config });
if (!this._map.getLayer(deckLayer.id)) {
this._map.addLayer(deckLayer);
}
this.mountedDeckLayers[mode] = deckLayer;
}
_removeDeckLayer(mode: DrawModeType): void {
const deckLayer = this.mountedDeckLayers[mode];
if (!deckLayer) return console.error(`cannot remove ${mode} as it wasn't mounted`);
this._map.removeLayer(deckLayer.id);
delete this.mountedDeckLayers[mode];
}
private _removeAllDeckLayers(map: ApplicationMap) {
map.doubleClickZoom.enable();
this._setSelectedIndexes([]);
const keys = Object.keys(this.mountedDeckLayers) as DrawModeType[];
keys.forEach((deckLayer) => this._removeDeckLayer(deckLayer));
this._createDrawingLayer = null;
this._editDrawingLayer = null;
}
_updateData(data: FeatureCollection) {
if (!this._map) return;
this.drawnData = data;
this._refreshMode(drawModes.ModifyMode);
}
_refreshMode(mode: DrawModeType): void {
const layer = this.mountedDeckLayers[mode];
layer?.setProps({
data: this.drawnData,
selectedFeatureIndexes: this.selectedIndexes,
});
}
_onModifyEdit = ({ editContext, updatedData, editType }) => {
const changedIndexes: number[] = editContext?.featureIndexes || [];
if (this.mode !== 'ModifyMode') return;
this._setSelectedIndexes(changedIndexes);
// edit types list available here in the description of onEdit method https://nebula.gl/docs/api-reference/layers/editable-geojson-layer
if (editType === 'selectFeature' && this._createDrawingLayer) {
this._setSelectedIndexes([]);
} else if (editType === 'removeFeature') {
this._setFeaturesAction(updatedData.features);
} else if (updatedData.features?.[0] && completedTypes.includes(editType)) {
// make map interactive if we finished drawing
setMapInteractivity(this._map, true);
for (let i = 0; i < updatedData.features.length; i++) {
const feature = updatedData.features[i];
if (changedIndexes.includes(i)) {
feature.properties.isSelected = true;
// check each edited feature for intersections
if (hasIntersections(feature)) {
this._showNotificationAction(
'error',
{ title: i18n.t('draw_tools.overlap_error') },
5,
);
return this._updateData(this._previousValidGeometry);
}
} else {
// remove edit coloring for all of them
delete feature.properties.temporary;
delete feature.properties.isSelected;
}
}
this._setFeaturesAction(updatedData.features);
// temporaryGeometryAtom.resetToDefault.dispatch()
} else if (updatedData.features?.[0]) {
// Case we're in process of modifying features that could be not validated yet
setMapInteractivity(this._map, false);
this._updateTempFeaturesAction(updatedData.features, changedIndexes);
} else {
this._setFeaturesAction(updatedData.features);
}
};
_onDrawEdit = ({ editContext, updatedData, editType }) => {
if (editType === 'addTentativePosition' || editType === 'addFeature')
this._setDrawingStarted(true);
if (editType === 'addFeature' && updatedData.features[0])
this._addFeatureAction(updatedData.features[0]);
};
}
function hasIntersections(feature: Feature) {
if (feature.geometry.type === 'MultiPolygon') {
for (let i = 0; i < feature.geometry.coordinates.length; i++) {
const polygonFeature: Feature = {
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: feature.geometry.coordinates[i],
},
properties: {},
};
if (hasIntersections(polygonFeature)) return true;
}
}
if (feature.geometry.type !== 'Polygon') return false;
const intersectionFeature = gpsi(feature);
if (intersectionFeature.geometry.coordinates.length) return true;
}