@trackunit/react-map-draw 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,277 @@
1
+ 'use strict';
2
+
3
+ var reactMapAdapterShared = require('@trackunit/react-map-adapter-shared');
4
+ var terraDraw = require('terra-draw');
5
+ var index = require('./index.cjs.js');
6
+ require('@trackunit/geo-json-utils');
7
+ require('es-toolkit');
8
+
9
+ /** Terra Draw mode names. `static` is Terra Draw's built-in no-interaction mode. */
10
+ const STATIC_MODE = "static";
11
+ const POLYGON_MODE = "polygon";
12
+ const SELECT_MODE = "select";
13
+ const toTerraDrawMode = (mode) => {
14
+ switch (mode) {
15
+ case "idle":
16
+ return STATIC_MODE;
17
+ case "polygon":
18
+ return POLYGON_MODE;
19
+ case "select":
20
+ return SELECT_MODE;
21
+ default:
22
+ throw new Error(`${mode} is not a draw mode`);
23
+ }
24
+ };
25
+ const roundCoordinate = (value) => {
26
+ const factor = 10 ** index.DRAW_COORDINATE_PRECISION;
27
+ return Math.round(value * factor) / factor;
28
+ };
29
+ /**
30
+ * Converts committed polygons into Terra Draw store features. Ids are dropped so the
31
+ * store assigns its own (Terra Draw validates ids against its id strategy), and
32
+ * coordinates are rounded to the store precision so validation does not reject
33
+ * high-precision input.
34
+ */
35
+ const toStoreFeatures = (value) => value.features.flatMap((feature) => {
36
+ const geometry = feature.geometry;
37
+ if (geometry === null || geometry.type !== "Polygon")
38
+ return [];
39
+ return [
40
+ {
41
+ type: "Feature",
42
+ geometry: {
43
+ type: "Polygon",
44
+ coordinates: geometry.coordinates.map(ring => ring.map(([lng, lat]) => [roundCoordinate(lng), roundCoordinate(lat)])),
45
+ },
46
+ properties: { mode: POLYGON_MODE },
47
+ },
48
+ ];
49
+ });
50
+ /** The desired value as the store will hold it: same rounding as `toStoreFeatures`, ids and properties untouched. */
51
+ const roundDrawValue = (value) => ({
52
+ type: "FeatureCollection",
53
+ features: value.features.map(feature => {
54
+ const geometry = feature.geometry;
55
+ if (geometry === null || geometry.type !== "Polygon")
56
+ return feature;
57
+ return {
58
+ ...feature,
59
+ geometry: {
60
+ type: "Polygon",
61
+ coordinates: geometry.coordinates.map(ring => ring.map(([lng, lat]) => [roundCoordinate(lng), roundCoordinate(lat)])),
62
+ },
63
+ };
64
+ }),
65
+ });
66
+ const toPosition = (position) => {
67
+ const lng = position[0];
68
+ const lat = position[1];
69
+ if (lng === undefined || lat === undefined)
70
+ return null;
71
+ return [lng, lat];
72
+ };
73
+ /**
74
+ * Reads the committed drawing out of a Terra Draw snapshot: polygons owned by the
75
+ * polygon mode that are not currently being drawn. Guidance features (closing
76
+ * points, coordinate points, selection handles) are points and never pass.
77
+ */
78
+ const toDrawValue = (snapshot) => {
79
+ const features = [];
80
+ for (const feature of snapshot) {
81
+ if (feature.geometry.type !== "Polygon")
82
+ continue;
83
+ if (feature.properties.mode !== POLYGON_MODE)
84
+ continue;
85
+ if (feature.properties.currentlyDrawing === true)
86
+ continue;
87
+ const rings = [];
88
+ for (const ring of feature.geometry.coordinates) {
89
+ const positions = [];
90
+ for (const raw of ring) {
91
+ const position = toPosition(raw);
92
+ if (position !== null)
93
+ positions.push(position);
94
+ }
95
+ rings.push(positions);
96
+ }
97
+ features.push({
98
+ type: "Feature",
99
+ id: feature.id,
100
+ geometry: { type: "Polygon", coordinates: rings },
101
+ properties: {},
102
+ });
103
+ }
104
+ return features.length === 0 ? reactMapAdapterShared.EMPTY_DRAW_VALUE : { type: "FeatureCollection", features };
105
+ };
106
+ /**
107
+ * Creates the Terra Draw backed `DrawEngine`. One instance per native map: the
108
+ * `DrawController` destroys it and creates a new one on every reconnect.
109
+ *
110
+ * Mode and value may be applied before the provider adapter reports `ready`
111
+ * (Google Maps reports it asynchronously, once its overlay is attached); they are
112
+ * queued and applied in order when it fires.
113
+ */
114
+ const createTerraDrawEngine = ({ adapter, style }) => {
115
+ const resolvedStyle = { ...index.DEFAULT_DRAW_STYLE, ...style };
116
+ const polygonMode = new terraDraw.TerraDrawPolygonMode({
117
+ showCoordinatePoints: true,
118
+ // A site boundary must be a simple ring; this rejects bow-ties while drawing,
119
+ // editing and loading alike.
120
+ validation: terraDraw.ValidateNotSelfIntersecting,
121
+ styles: {
122
+ fillColor: resolvedStyle.fillColor,
123
+ fillOpacity: resolvedStyle.fillOpacity,
124
+ outlineColor: resolvedStyle.outlineColor,
125
+ outlineWidth: resolvedStyle.outlineWidth,
126
+ closingPointColor: resolvedStyle.vertexColor,
127
+ closingPointOutlineColor: resolvedStyle.vertexOutlineColor,
128
+ closingPointWidth: resolvedStyle.vertexWidth,
129
+ closingPointOutlineWidth: 2,
130
+ coordinatePointColor: resolvedStyle.vertexColor,
131
+ coordinatePointOutlineColor: resolvedStyle.vertexOutlineColor,
132
+ coordinatePointWidth: resolvedStyle.vertexWidth,
133
+ coordinatePointOutlineWidth: 2,
134
+ },
135
+ });
136
+ const selectMode = new terraDraw.TerraDrawSelectMode({
137
+ // A site has one polygon, so the Delete key must not wipe it; removing the whole
138
+ // drawing is the explicit Clear action. Escape still deselects. Rotate and scale
139
+ // keyboard shortcuts stay off.
140
+ keyEvents: { deselect: "Escape", delete: null, rotate: null, scale: null },
141
+ flags: {
142
+ [POLYGON_MODE]: {
143
+ feature: {
144
+ draggable: false,
145
+ coordinates: { midpoints: true, draggable: true, deletable: true },
146
+ },
147
+ },
148
+ },
149
+ styles: {
150
+ selectedPolygonColor: resolvedStyle.fillColor,
151
+ selectedPolygonFillOpacity: resolvedStyle.fillOpacity,
152
+ selectedPolygonOutlineColor: resolvedStyle.outlineColor,
153
+ selectedPolygonOutlineWidth: resolvedStyle.outlineWidth,
154
+ selectionPointColor: resolvedStyle.vertexColor,
155
+ selectionPointOutlineColor: resolvedStyle.vertexOutlineColor,
156
+ selectionPointWidth: resolvedStyle.vertexWidth,
157
+ selectionPointOutlineWidth: 2,
158
+ midPointColor: resolvedStyle.vertexOutlineColor,
159
+ midPointOutlineColor: resolvedStyle.vertexColor,
160
+ midPointWidth: 3,
161
+ midPointOutlineWidth: 1,
162
+ },
163
+ });
164
+ const draw = new terraDraw.TerraDraw({ adapter, modes: [polygonMode, selectMode] });
165
+ let ready = false;
166
+ let destroyed = false;
167
+ let applying = false;
168
+ let desiredMode = "idle";
169
+ let desiredValue = reactMapAdapterShared.EMPTY_DRAW_VALUE;
170
+ let lastEmitted = reactMapAdapterShared.EMPTY_DRAW_VALUE;
171
+ const listeners = new Set();
172
+ /**
173
+ * Replaces the store with the desired value. Terra Draw validates every feature
174
+ * on its own terms (after rounding, a degenerate ring may collapse); whatever it
175
+ * rejected is not on the map, so the rendered value is reported back through
176
+ * `onChange` to keep the controller and the map in agreement.
177
+ */
178
+ const applyValue = () => {
179
+ applying = true;
180
+ try {
181
+ draw.clear();
182
+ draw.addFeatures(toStoreFeatures(desiredValue));
183
+ }
184
+ finally {
185
+ applying = false;
186
+ }
187
+ const rendered = toDrawValue(draw.getSnapshot());
188
+ lastEmitted = rendered;
189
+ // Compare against the rounded input: rounding alone is not a rejection, and a
190
+ // stored polygon with 14 decimals must not come back as a "user edit".
191
+ if (!index.drawValuesEqual(rendered, roundDrawValue(desiredValue))) {
192
+ listeners.forEach(listener => listener(rendered));
193
+ }
194
+ };
195
+ const applyMode = () => {
196
+ const target = toTerraDrawMode(desiredMode);
197
+ if (draw.getMode() !== target) {
198
+ draw.setMode(target);
199
+ }
200
+ };
201
+ const emitIfChanged = () => {
202
+ const next = toDrawValue(draw.getSnapshot());
203
+ if (index.drawValuesEqual(lastEmitted, next))
204
+ return;
205
+ lastEmitted = next;
206
+ listeners.forEach(listener => listener(next));
207
+ };
208
+ /**
209
+ * Every user edit ends in a `finish`: closing a polygon, dragging a vertex,
210
+ * inserting a midpoint, deleting a vertex. Reporting from here (and not from the
211
+ * per-frame `change` stream) is what keeps in-progress geometry out of the value.
212
+ */
213
+ const handleFinish = () => {
214
+ if (!ready || applying || destroyed)
215
+ return;
216
+ emitIfChanged();
217
+ };
218
+ /**
219
+ * `change` fires per pointer move while drawing and per frame while dragging, so
220
+ * only feature deletions are taken from it; those have no `finish` of their own.
221
+ */
222
+ const handleChange = (_ids, type) => {
223
+ if (!ready || applying || destroyed)
224
+ return;
225
+ if (type !== "delete")
226
+ return;
227
+ emitIfChanged();
228
+ };
229
+ const handleReady = () => {
230
+ if (ready || destroyed)
231
+ return;
232
+ ready = true;
233
+ applyValue();
234
+ applyMode();
235
+ };
236
+ draw.on("change", handleChange);
237
+ draw.on("finish", handleFinish);
238
+ draw.on("ready", handleReady);
239
+ draw.start();
240
+ return {
241
+ setMode: mode => {
242
+ desiredMode = mode;
243
+ if (ready && !destroyed)
244
+ applyMode();
245
+ },
246
+ setValue: value => {
247
+ desiredValue = value;
248
+ if (ready && !destroyed)
249
+ applyValue();
250
+ },
251
+ onChange: listener => {
252
+ listeners.add(listener);
253
+ return () => {
254
+ listeners.delete(listener);
255
+ };
256
+ },
257
+ destroy: () => {
258
+ if (destroyed)
259
+ return;
260
+ destroyed = true;
261
+ listeners.clear();
262
+ draw.off("change", handleChange);
263
+ draw.off("finish", handleFinish);
264
+ draw.off("ready", handleReady);
265
+ try {
266
+ if (draw.enabled)
267
+ draw.stop();
268
+ }
269
+ catch {
270
+ // The native map or style may already be gone (Mapbox setStyle, Google map
271
+ // recreation); there is nothing left to release in that case.
272
+ }
273
+ },
274
+ };
275
+ };
276
+
277
+ exports.createTerraDrawEngine = createTerraDrawEngine;
@@ -0,0 +1,275 @@
1
+ import { EMPTY_DRAW_VALUE } from '@trackunit/react-map-adapter-shared';
2
+ import { TerraDrawPolygonMode, ValidateNotSelfIntersecting, TerraDrawSelectMode, TerraDraw } from 'terra-draw';
3
+ import { DEFAULT_DRAW_STYLE, drawValuesEqual, DRAW_COORDINATE_PRECISION } from './index.esm.js';
4
+ import '@trackunit/geo-json-utils';
5
+ import 'es-toolkit';
6
+
7
+ /** Terra Draw mode names. `static` is Terra Draw's built-in no-interaction mode. */
8
+ const STATIC_MODE = "static";
9
+ const POLYGON_MODE = "polygon";
10
+ const SELECT_MODE = "select";
11
+ const toTerraDrawMode = (mode) => {
12
+ switch (mode) {
13
+ case "idle":
14
+ return STATIC_MODE;
15
+ case "polygon":
16
+ return POLYGON_MODE;
17
+ case "select":
18
+ return SELECT_MODE;
19
+ default:
20
+ throw new Error(`${mode} is not a draw mode`);
21
+ }
22
+ };
23
+ const roundCoordinate = (value) => {
24
+ const factor = 10 ** DRAW_COORDINATE_PRECISION;
25
+ return Math.round(value * factor) / factor;
26
+ };
27
+ /**
28
+ * Converts committed polygons into Terra Draw store features. Ids are dropped so the
29
+ * store assigns its own (Terra Draw validates ids against its id strategy), and
30
+ * coordinates are rounded to the store precision so validation does not reject
31
+ * high-precision input.
32
+ */
33
+ const toStoreFeatures = (value) => value.features.flatMap((feature) => {
34
+ const geometry = feature.geometry;
35
+ if (geometry === null || geometry.type !== "Polygon")
36
+ return [];
37
+ return [
38
+ {
39
+ type: "Feature",
40
+ geometry: {
41
+ type: "Polygon",
42
+ coordinates: geometry.coordinates.map(ring => ring.map(([lng, lat]) => [roundCoordinate(lng), roundCoordinate(lat)])),
43
+ },
44
+ properties: { mode: POLYGON_MODE },
45
+ },
46
+ ];
47
+ });
48
+ /** The desired value as the store will hold it: same rounding as `toStoreFeatures`, ids and properties untouched. */
49
+ const roundDrawValue = (value) => ({
50
+ type: "FeatureCollection",
51
+ features: value.features.map(feature => {
52
+ const geometry = feature.geometry;
53
+ if (geometry === null || geometry.type !== "Polygon")
54
+ return feature;
55
+ return {
56
+ ...feature,
57
+ geometry: {
58
+ type: "Polygon",
59
+ coordinates: geometry.coordinates.map(ring => ring.map(([lng, lat]) => [roundCoordinate(lng), roundCoordinate(lat)])),
60
+ },
61
+ };
62
+ }),
63
+ });
64
+ const toPosition = (position) => {
65
+ const lng = position[0];
66
+ const lat = position[1];
67
+ if (lng === undefined || lat === undefined)
68
+ return null;
69
+ return [lng, lat];
70
+ };
71
+ /**
72
+ * Reads the committed drawing out of a Terra Draw snapshot: polygons owned by the
73
+ * polygon mode that are not currently being drawn. Guidance features (closing
74
+ * points, coordinate points, selection handles) are points and never pass.
75
+ */
76
+ const toDrawValue = (snapshot) => {
77
+ const features = [];
78
+ for (const feature of snapshot) {
79
+ if (feature.geometry.type !== "Polygon")
80
+ continue;
81
+ if (feature.properties.mode !== POLYGON_MODE)
82
+ continue;
83
+ if (feature.properties.currentlyDrawing === true)
84
+ continue;
85
+ const rings = [];
86
+ for (const ring of feature.geometry.coordinates) {
87
+ const positions = [];
88
+ for (const raw of ring) {
89
+ const position = toPosition(raw);
90
+ if (position !== null)
91
+ positions.push(position);
92
+ }
93
+ rings.push(positions);
94
+ }
95
+ features.push({
96
+ type: "Feature",
97
+ id: feature.id,
98
+ geometry: { type: "Polygon", coordinates: rings },
99
+ properties: {},
100
+ });
101
+ }
102
+ return features.length === 0 ? EMPTY_DRAW_VALUE : { type: "FeatureCollection", features };
103
+ };
104
+ /**
105
+ * Creates the Terra Draw backed `DrawEngine`. One instance per native map: the
106
+ * `DrawController` destroys it and creates a new one on every reconnect.
107
+ *
108
+ * Mode and value may be applied before the provider adapter reports `ready`
109
+ * (Google Maps reports it asynchronously, once its overlay is attached); they are
110
+ * queued and applied in order when it fires.
111
+ */
112
+ const createTerraDrawEngine = ({ adapter, style }) => {
113
+ const resolvedStyle = { ...DEFAULT_DRAW_STYLE, ...style };
114
+ const polygonMode = new TerraDrawPolygonMode({
115
+ showCoordinatePoints: true,
116
+ // A site boundary must be a simple ring; this rejects bow-ties while drawing,
117
+ // editing and loading alike.
118
+ validation: ValidateNotSelfIntersecting,
119
+ styles: {
120
+ fillColor: resolvedStyle.fillColor,
121
+ fillOpacity: resolvedStyle.fillOpacity,
122
+ outlineColor: resolvedStyle.outlineColor,
123
+ outlineWidth: resolvedStyle.outlineWidth,
124
+ closingPointColor: resolvedStyle.vertexColor,
125
+ closingPointOutlineColor: resolvedStyle.vertexOutlineColor,
126
+ closingPointWidth: resolvedStyle.vertexWidth,
127
+ closingPointOutlineWidth: 2,
128
+ coordinatePointColor: resolvedStyle.vertexColor,
129
+ coordinatePointOutlineColor: resolvedStyle.vertexOutlineColor,
130
+ coordinatePointWidth: resolvedStyle.vertexWidth,
131
+ coordinatePointOutlineWidth: 2,
132
+ },
133
+ });
134
+ const selectMode = new TerraDrawSelectMode({
135
+ // A site has one polygon, so the Delete key must not wipe it; removing the whole
136
+ // drawing is the explicit Clear action. Escape still deselects. Rotate and scale
137
+ // keyboard shortcuts stay off.
138
+ keyEvents: { deselect: "Escape", delete: null, rotate: null, scale: null },
139
+ flags: {
140
+ [POLYGON_MODE]: {
141
+ feature: {
142
+ draggable: false,
143
+ coordinates: { midpoints: true, draggable: true, deletable: true },
144
+ },
145
+ },
146
+ },
147
+ styles: {
148
+ selectedPolygonColor: resolvedStyle.fillColor,
149
+ selectedPolygonFillOpacity: resolvedStyle.fillOpacity,
150
+ selectedPolygonOutlineColor: resolvedStyle.outlineColor,
151
+ selectedPolygonOutlineWidth: resolvedStyle.outlineWidth,
152
+ selectionPointColor: resolvedStyle.vertexColor,
153
+ selectionPointOutlineColor: resolvedStyle.vertexOutlineColor,
154
+ selectionPointWidth: resolvedStyle.vertexWidth,
155
+ selectionPointOutlineWidth: 2,
156
+ midPointColor: resolvedStyle.vertexOutlineColor,
157
+ midPointOutlineColor: resolvedStyle.vertexColor,
158
+ midPointWidth: 3,
159
+ midPointOutlineWidth: 1,
160
+ },
161
+ });
162
+ const draw = new TerraDraw({ adapter, modes: [polygonMode, selectMode] });
163
+ let ready = false;
164
+ let destroyed = false;
165
+ let applying = false;
166
+ let desiredMode = "idle";
167
+ let desiredValue = EMPTY_DRAW_VALUE;
168
+ let lastEmitted = EMPTY_DRAW_VALUE;
169
+ const listeners = new Set();
170
+ /**
171
+ * Replaces the store with the desired value. Terra Draw validates every feature
172
+ * on its own terms (after rounding, a degenerate ring may collapse); whatever it
173
+ * rejected is not on the map, so the rendered value is reported back through
174
+ * `onChange` to keep the controller and the map in agreement.
175
+ */
176
+ const applyValue = () => {
177
+ applying = true;
178
+ try {
179
+ draw.clear();
180
+ draw.addFeatures(toStoreFeatures(desiredValue));
181
+ }
182
+ finally {
183
+ applying = false;
184
+ }
185
+ const rendered = toDrawValue(draw.getSnapshot());
186
+ lastEmitted = rendered;
187
+ // Compare against the rounded input: rounding alone is not a rejection, and a
188
+ // stored polygon with 14 decimals must not come back as a "user edit".
189
+ if (!drawValuesEqual(rendered, roundDrawValue(desiredValue))) {
190
+ listeners.forEach(listener => listener(rendered));
191
+ }
192
+ };
193
+ const applyMode = () => {
194
+ const target = toTerraDrawMode(desiredMode);
195
+ if (draw.getMode() !== target) {
196
+ draw.setMode(target);
197
+ }
198
+ };
199
+ const emitIfChanged = () => {
200
+ const next = toDrawValue(draw.getSnapshot());
201
+ if (drawValuesEqual(lastEmitted, next))
202
+ return;
203
+ lastEmitted = next;
204
+ listeners.forEach(listener => listener(next));
205
+ };
206
+ /**
207
+ * Every user edit ends in a `finish`: closing a polygon, dragging a vertex,
208
+ * inserting a midpoint, deleting a vertex. Reporting from here (and not from the
209
+ * per-frame `change` stream) is what keeps in-progress geometry out of the value.
210
+ */
211
+ const handleFinish = () => {
212
+ if (!ready || applying || destroyed)
213
+ return;
214
+ emitIfChanged();
215
+ };
216
+ /**
217
+ * `change` fires per pointer move while drawing and per frame while dragging, so
218
+ * only feature deletions are taken from it; those have no `finish` of their own.
219
+ */
220
+ const handleChange = (_ids, type) => {
221
+ if (!ready || applying || destroyed)
222
+ return;
223
+ if (type !== "delete")
224
+ return;
225
+ emitIfChanged();
226
+ };
227
+ const handleReady = () => {
228
+ if (ready || destroyed)
229
+ return;
230
+ ready = true;
231
+ applyValue();
232
+ applyMode();
233
+ };
234
+ draw.on("change", handleChange);
235
+ draw.on("finish", handleFinish);
236
+ draw.on("ready", handleReady);
237
+ draw.start();
238
+ return {
239
+ setMode: mode => {
240
+ desiredMode = mode;
241
+ if (ready && !destroyed)
242
+ applyMode();
243
+ },
244
+ setValue: value => {
245
+ desiredValue = value;
246
+ if (ready && !destroyed)
247
+ applyValue();
248
+ },
249
+ onChange: listener => {
250
+ listeners.add(listener);
251
+ return () => {
252
+ listeners.delete(listener);
253
+ };
254
+ },
255
+ destroy: () => {
256
+ if (destroyed)
257
+ return;
258
+ destroyed = true;
259
+ listeners.clear();
260
+ draw.off("change", handleChange);
261
+ draw.off("finish", handleFinish);
262
+ draw.off("ready", handleReady);
263
+ try {
264
+ if (draw.enabled)
265
+ draw.stop();
266
+ }
267
+ catch {
268
+ // The native map or style may already be gone (Mapbox setStyle, Google map
269
+ // recreation); there is nothing left to release in that case.
270
+ }
271
+ },
272
+ };
273
+ };
274
+
275
+ export { createTerraDrawEngine };