-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgeospatial-map.js
More file actions
1066 lines (929 loc) · 29.1 KB
/
geospatial-map.js
File metadata and controls
1066 lines (929 loc) · 29.1 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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { bbox } from '@turf/bbox'
import {
EVENTS,
createMap,
defaultConfig,
getCentroidGridRef,
getCoordinateGridRef
} from '~/src/client/javascripts/map.js'
const helpPanelConfig = {
showLabel: true,
label: 'How to use this map',
mobile: {
slot: 'drawer',
open: true,
dismissible: true,
modal: false
},
tablet: {
slot: 'drawer',
open: true,
dismissible: true,
modal: false
},
desktop: {
slot: 'drawer',
open: true,
dismissible: true,
modal: false
},
html: '<p class="govuk-body-s govuk-!-margin-bottom-2">You can add points, shapes or lines to the map.</p><ul class="govuk-list govuk-list--number govuk-body-s"><li>Search for a county, place or postcode</li><li>Use the + and - icons to zoom in and out</li><li>Double‑click, or select \'Done\', when you have finished drawing a line or shape</li><li>Give the location a name</li></ul>'
}
const lineFeatureProperties = {
stroke: 'rgba(0, 11, 112, 1)',
fill: 'rgba(0, 11, 112, 0.2)',
strokeWidth: 2
}
const polygonFeatureProperties = {
stroke: 'rgba(0,112,60,1)',
fill: 'rgba(0,112,60,0.2)',
strokeWidth: 2
}
/**
* @type {Record<'Point' | 'LineString' | 'Polygon', string>}
*/
const typeDescriptions = {
Point: 'Point',
LineString: 'Line',
Polygon: 'Shape'
}
const POINT_SVG =
'<path d="M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0" /><circle cx="12" cy="10" r="3" />'
const POLYGON_SVG =
'<path d="M19.5 7v10M4.5 7v10M7 19.5h10M7 4.5h10"/><path d="M22 18v3a1 1 0 0 1-1 1h-3a1 1 0 0 1-1-1v-3a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1zm0-15v3a1 1 0 0 1-1 1h-3a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1zM7 18v3a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-3a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1zM7 3v3a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1z"/>'
const LINE_SVG =
'<path d="M5.706 16.294L16.294 5.706"/><path d="M21 2v3c0 .549-.451 1-1 1h-3c-.549 0-1-.451-1-1V2c0-.549.451-1 1-1h3c.549 0 1 .451 1 1zM6 17v3c0 .549-.451 1-1 1H2c-.549 0-1-.451-1-1v-3c0-.549.451-1 1-1h3c.549 0 1 .451 1 1z"/>'
/**
* Extract and parses the GeoJSON from the textarea
* @param {HTMLTextAreaElement} geospatialInput - the textarea containing the geojson
*/
export function getGeoJSON(geospatialInput) {
const value = geospatialInput.value.trim()
const hasValue = !!value
/** @type {FeatureCollection} */
const features = hasValue ? JSON.parse(value) : []
/** @type {GeoJSON} */
const geojson = {
type: 'FeatureCollection',
features
}
return geojson
}
/**
* Gets the bounding box covering a feature collection
* @param {GeoJSON} geojson - the geojson
*/
export function getBoundingBox(geojson) {
return bbox(geojson)
}
/**
* Processes a geospatial field to add map capability
* @param {MapsEnvironmentConfig} config - the geospatial field element
* @param {Element} geospatial - the geospatial field element
* @param {number} index - the 0-based index
*/
export function processGeospatial(config, geospatial, index) {
// @ts-expect-error - Defra namespace currently comes from UMD support files
const defra = window.defra
if (!(geospatial instanceof HTMLDivElement)) {
return
}
const geospatialInput = geospatial.querySelector('.govuk-textarea')
if (!(geospatialInput instanceof HTMLTextAreaElement)) {
return
}
const { listEl, mapId } = createContainers(geospatialInput, index)
const geojson = getGeoJSON(geospatialInput)
const bounds = geojson.features.length ? getBoundingBox(geojson) : undefined
const drawPlugin = defra.drawMLPlugin()
const initConfig = {
...defaultConfig,
bounds,
plugins: [drawPlugin]
}
const { map, interactPlugin } = createMap(mapId, initConfig, config)
const featuresManager = getFeaturesManager(geojson)
const activeFeatureManager = getActiveFeatureManager()
const uiManager = getUIManager(geojson, map, mapId, listEl, geospatialInput)
/**
* @type {Context}
*/
const context = {
map,
featuresManager,
activeFeatureManager,
uiManager,
interactPlugin,
drawPlugin
}
addEventListeners(context)
}
/**
* Adds a feature to the map
* @param {Feature} feature - the geojson feature
* @param {any} drawPlugin - the map draw plugin
* @param {InteractiveMap} map - the interactive map
*/
export function addFeatureToMap(feature, drawPlugin, map) {
switch (feature.geometry.type) {
case 'Polygon':
drawPlugin.addFeature({ ...feature, ...polygonFeatureProperties })
break
case 'LineString':
drawPlugin.addFeature({ ...feature, ...lineFeatureProperties })
break
case 'Point':
map.addMarker(feature.id, feature.geometry.coordinates)
break
default:
break
}
}
/**
* Returns HTML summary list for the features
* @param {FeatureCollection} features - the features
* @param {string} mapId - the ID of the map
* @param {boolean} [disabled] - render the list with disabled links
* @param {boolean} [readonly] - render the list in readonly mode
*/
export function createFeaturesHTML(
features,
mapId,
disabled = false,
readonly = false
) {
return `<dl class="govuk-summary-list">
${features.map((feature, index) => createFeatureHTML(feature, index, mapId, disabled, readonly)).join('\n')}
</dl>`
}
/**
* Focus feature
* @param {Feature} feature - the feature
* @param {MapLibreMap} mapProvider - the feature id
*/
export function focusFeature(feature, mapProvider) {
mapProvider.fitBounds(bbox(feature))
}
/**
* Returns HTML summary row for an single feature
* @param {Feature} feature - the geo feature
* @param {number} index - the feature index
* @param {string} mapId - the ID of the map
* @param {boolean} [disabled] - render the list with disabled links
* @param {boolean} [readonly] - render the list item in readonly mode
*/
export function createFeatureHTML(
feature,
index,
mapId,
disabled = false,
readonly = false
) {
const flattened = feature.geometry.coordinates.flat(2)
const points = []
for (let i = 0; i < flattened.length; i += 2) {
points.push(flattened.slice(i, i + 2).join(', '))
}
const coordinates = points.map((p) => `<li>${p}</li>`).join('')
const description = readonly
? `<p class="govuk-body govuk-!-margin-bottom-0">${feature.properties.description}</p>`
: `<input class="govuk-input govuk-!-width-two-thirds" type="text" id="description_${index}" value="${feature.properties.description}" data-id="${feature.id}">`
// Change action link
const changeAction = () => `<li class="govuk-summary-list__actions-list-item">
<a class="govuk-link govuk-link--no-visited-state ${disabled ? 'govuk-link--disabled' : ''}" href="#${mapId}" data-action="edit" data-id="${feature.id}"
data-type="${feature.geometry.type}">Update<span class="govuk-visually-hidden"> location</span></a>
</li>`
// Delete action link
const deleteAction = () => `<li class="govuk-summary-list__actions-list-item">
<a class="govuk-link govuk-link--no-visited-state ${disabled ? 'govuk-link--disabled' : ''}" href="#" data-action="delete" data-id="${feature.id}"
data-type="${feature.geometry.type}">Delete<span class="govuk-visually-hidden"> location</span></a>
</li>`
// Focus action link
const focusAction = () => `<li class="govuk-summary-list__actions-list-item">
<a class="govuk-link govuk-link--no-visited-state" href="#${mapId}" data-action="focus" data-id="${feature.id}">Show<span class="govuk-visually-hidden"> location</span></a>
</li>`
const links = readonly ? focusAction() : `${changeAction()}${deleteAction()}`
const actions = `<ul class="govuk-summary-list__actions-list">${links}</ul>`
return `<div class="govuk-summary-list__row govuk-summary-list__row--no-border">
<dt class="govuk-summary-list__key">
<div class="govuk-form-group">
<label class="govuk-label govuk-label--s" ${readonly ? '' : `for="description_${index}"`}>Location ${index + 1} description</label>
${description}
</div>
</dt>
<dd class="govuk-summary-list__actions">
${actions}
</dd>
</div>
<div class="govuk-summary-list__row">
<details class="govuk-details govuk-!-margin-bottom-2">
<summary class="govuk-details__summary">
<span class="govuk-details__summary-text">Coordinates</span>
</summary>
<div class="govuk-details__text">
<dl class="govuk-summary-list">
<div class="govuk-summary-list__row">
<dt class="govuk-summary-list__key">Type</dt>
<dd class="govuk-summary-list__value">${typeDescriptions[feature.geometry.type]}</dd>
</div>
<div class="govuk-summary-list__row">
<dt class="govuk-summary-list__key">Centre grid reference</dt>
<dd class="govuk-summary-list__value">${feature.properties.centroidGridReference}</dd>
</div>
<div class="govuk-summary-list__row">
<dt class="govuk-summary-list__key">First point grid reference</dt>
<dd class="govuk-summary-list__value">${feature.properties.coordinateGridReference}</dd>
</div>
<div class="govuk-summary-list__row">
<dt class="govuk-summary-list__key">Detailed coordinates</dt>
<dd class="govuk-summary-list__value">
<ol class="govuk-list govuk-list--number">${coordinates}</ol>
</dd>
</div>
</dl>
</div>
</details>
</div>`
}
/**
* Generate a random id
*/
function generateID() {
return window.crypto.randomUUID()
}
/**
* Factory closure to track the active feature id
* @returns {ActiveFeatureManager}
*/
function getActiveFeatureManager() {
/** @type {string | undefined} */
let activeFeature
/**
* Returns the active feature id
* @type {GetActiveFeature}
*/
function getActiveFeature() {
return activeFeature
}
/**
* Sets the active feature id
* @type {SetActiveFeature}
*/
function setActiveFeature(id) {
activeFeature = id
}
/**
* Resets the active feature id
* @type {ResetActiveFeature}
*/
function resetActiveFeature() {
activeFeature = undefined
}
return {
getActiveFeature,
setActiveFeature,
resetActiveFeature
}
}
/**
* Reduce coordinate precision to 7 dps
* @param {Feature} feature
*/
function prepareGeometry(feature) {
const { geometry } = feature
const maxPrecision = 7
/**
* @param {Coordinates} coordinates
*/
function formatPrecision(coordinates) {
coordinates[0] = +coordinates[0].toFixed(maxPrecision)
coordinates[1] = +coordinates[1].toFixed(maxPrecision)
}
if (geometry.type === 'Point') {
formatPrecision(geometry.coordinates)
} else if (geometry.type === 'LineString') {
geometry.coordinates.forEach(formatPrecision)
} else {
geometry.coordinates.flat().forEach(formatPrecision)
}
}
/**
* Factory closure to return a features manager
* @param {GeoJSON} geojson
* @returns {FeaturesManager}
*/
function getFeaturesManager(geojson) {
/**
* Get a feature from the geojson by id
* @type {GetFeatures}
*/
function getFeatures() {
return geojson.features
}
/**
* Get a feature from the geojson by id
* @type {GetFeature}
*/
function getFeature(id) {
return geojson.features.find((f) => f.id === id)
}
/**
* Add a feature to the geojson
* @type {AddFeature}
*/
function addFeature(feature) {
feature.properties.coordinateGridReference = getCoordinateGridRef(feature)
feature.properties.centroidGridReference = getCentroidGridRef(feature)
prepareGeometry(feature)
geojson.features.push(feature)
}
/**
* Updates a feature in the geojson
* @type {UpdateFeature}
*/
function updateFeature(id, geometry) {
const feature = getFeature(id)
// Ensure the feature exists in the geojson
if (feature) {
feature.properties.coordinateGridReference = getCoordinateGridRef(feature)
feature.properties.centroidGridReference = getCentroidGridRef(feature)
feature.geometry = geometry
prepareGeometry(feature)
}
return feature
}
/**
* Removes a feature from the geojson
* @type {RemoveFeature}
*/
function removeFeature(id) {
const idx = geojson.features.findIndex((f) => f.id === id)
return idx > -1 ? geojson.features.splice(idx, 1) : undefined
}
return {
getFeatures,
getFeature,
addFeature,
updateFeature,
removeFeature
}
}
/**
* Factory to render features into the list and hidden textarea
* @param {GeoJSON} geojson - the geojson of features
* @param {string} mapId - the ID of the map
* @param {HTMLDivElement} listEl - where to render the feature list
* @param {Function} renderValue - function that renders the features JSON into the hidden textarea
* @returns {RenderList}
*/
function getListRenderer(geojson, mapId, listEl, renderValue) {
return function renderList(disabled = false) {
const html = createFeaturesHTML(geojson.features, mapId, disabled)
listEl.innerHTML = html
renderValue()
}
}
/**
* Factory to render features JSON into the hidden textarea
* @param {GeoJSON} geojson - the features
* @param {HTMLTextAreaElement} geospatialInput - the geospatial textarea
* @returns {RenderValue}
*/
function getValueRenderer(geojson, geospatialInput) {
return function renderValue() {
geospatialInput.value = JSON.stringify(geojson.features, null, 2)
}
}
/**
* Factory closure to manage the UI
* @param {GeoJSON} geojson - the features
* @param {InteractiveMap} map - the map
* @param {string} mapId - the ID of the map
* @param {HTMLDivElement} listEl - where to render the feature list
* @param {HTMLTextAreaElement} geospatialInput - the geospatial textarea
*/
function getUIManager(geojson, map, mapId, listEl, geospatialInput) {
/**
* Toggle the hidden state of the action buttons
* @type {ToggleActionButtons}
*/
function toggleActionButtons(hidden) {
map.toggleButtonState('btnAddPoint', 'hidden', hidden)
map.toggleButtonState('btnAddPolygon', 'hidden', hidden)
map.toggleButtonState('btnAddLine', 'hidden', hidden)
}
/**
* Set focus to the last description input
* @type {FocusDescriptionInput}
*/
function focusDescriptionInput() {
const inputs = listEl.querySelectorAll('input')
if (inputs.length) {
const lastInput = /** @type {HTMLInputElement} */ inputs.item(
inputs.length - 1
)
lastInput.focus()
lastInput.select()
}
}
const renderValue = getValueRenderer(geojson, geospatialInput)
const renderList = getListRenderer(geojson, mapId, listEl, renderValue)
/** @type {UIManager} */
return {
renderList,
renderValue,
listEl,
toggleActionButtons,
focusDescriptionInput
}
}
/**
* Setup the UI event listeners
* @param {Context} context - the context
*/
function addEventListeners(context) {
const { map } = context
map.on(EVENTS.mapReady, onMapReadyFactory(context))
}
/**
* Create the map and list containers and adds them to the DOM
* @param {HTMLTextAreaElement} geospatialInput - the textarea containing the geojson
* @param {number} index - the 0 based index
*/
function createContainers(geospatialInput, index) {
const mapEl = document.createElement('div')
const mapId = `geospatialmap_${index}`
mapEl.setAttribute('id', mapId)
mapEl.setAttribute('class', 'map-container')
const listEl = document.createElement('div')
const listId = `${mapId}_list`
listEl.setAttribute('id', listId)
geospatialInput.after(mapEl)
mapEl.after(listEl)
geospatialInput.classList.add('js-hidden')
return { mapEl, listEl, mapId }
}
/**
* Callback factory function which fires when the map is ready
* @param {Context} context - the UI context
*/
function onMapReadyFactory(context) {
const { map, activeFeatureManager, uiManager, interactPlugin, drawPlugin } =
context
const { toggleActionButtons, renderList } = uiManager
const { resetActiveFeature } = activeFeatureManager
/**
* Callback function which fires when the map is ready
* @param {object} e - the event
* @param {MapLibreMap} e.map - the map provider instance
*/
return function onMapReady(e) {
// Add info panel
map.addPanel('info', helpPanelConfig)
map.addButton('btnAddPoint', {
variant: 'tertiary',
label: 'Add point',
iconSvgContent: POINT_SVG,
onClick: () => {
resetActiveFeature()
toggleActionButtons(true)
renderList(true)
interactPlugin.enable()
},
mobile: { slot: 'actions' },
tablet: { slot: 'actions' },
desktop: { slot: 'actions' }
})
map.addButton('btnAddPolygon', {
variant: 'tertiary',
label: 'Add shape',
iconSvgContent: POLYGON_SVG,
onClick: () => {
resetActiveFeature()
toggleActionButtons(true)
renderList(true)
drawPlugin.newPolygon(generateID(), polygonFeatureProperties)
},
mobile: { slot: 'actions' },
tablet: { slot: 'actions' },
desktop: { slot: 'actions' }
})
map.addButton('btnAddLine', {
variant: 'tertiary',
label: 'Add line',
iconSvgContent: LINE_SVG,
onClick: () => {
resetActiveFeature()
toggleActionButtons(true)
renderList(true)
drawPlugin.newLine(generateID(), lineFeatureProperties)
},
mobile: { slot: 'actions' },
tablet: { slot: 'actions' },
desktop: { slot: 'actions' }
})
// Set the map provider on the context
context.mapProvider = e.map
map.on(EVENTS.drawReady, onDrawReadyFactory(context))
map.on(EVENTS.drawCreated, onDrawCreatedFactory(context))
map.on(EVENTS.drawEdited, onDrawEditedFactory(context))
map.on(EVENTS.drawCancelled, onDrawCancelledFactory(context))
map.on(EVENTS.interactMarkerChange, onInteractMarkerChangedFactory(context))
const { listEl } = uiManager
listEl.addEventListener('click', onListElClickFactory(context), false)
listEl.addEventListener('change', onListElChangeFactory(context), false)
listEl.addEventListener('keydown', onListElKeydownFactory(), false)
}
}
/**
* Callback factory function which fires when the map draw plugin is ready
* @param {Context} context - the UI context
*/
function onDrawReadyFactory(context) {
const { featuresManager, uiManager, drawPlugin, map } = context
const { renderList } = uiManager
const { getFeatures } = featuresManager
/**
* Callback when the draw plugin is ready
*/
return function onDrawReady() {
getFeatures().forEach((feature) =>
addFeatureToMap(feature, drawPlugin, map)
)
// Update the features
renderList()
}
}
/**
* Callback factory function which fires when the map draw plugin creates a new feature
* @param {Context} context - the UI context
*/
function onDrawCreatedFactory(context) {
const { featuresManager, uiManager } = context
const { addFeature } = featuresManager
const { renderList, toggleActionButtons, focusDescriptionInput } = uiManager
/**
* Callback when a draw feature has been created
* @param {Feature} e
*/
return function onDrawCreated(e) {
// New feature
addFeature({
...e,
properties: {
description: ''
}
})
// Update the features
renderList()
toggleActionButtons(false)
focusDescriptionInput()
}
}
/**
* Callback factory function which fires when the map draw plugin edits a feature
* @param {Context} context - the UI context
*/
function onDrawEditedFactory(context) {
const { featuresManager, activeFeatureManager, uiManager } = context
const { updateFeature } = featuresManager
const { getActiveFeature, resetActiveFeature } = activeFeatureManager
const { renderList, toggleActionButtons } = uiManager
/**
* Callback when a draw feature has been edited
* @param {{ id: string, geometry: Geometry }} e
*/
return function onDrawEdited(e) {
const changedFeature = e
const featureId = changedFeature.id
if (getActiveFeature() === featureId) {
updateFeature(featureId, changedFeature.geometry)
// Update the features
renderList()
}
resetActiveFeature()
toggleActionButtons(false)
}
}
/**
* Callback factory function which fires when the map draw plugin cancels the editing of a feature
* @param {Context} context - the UI context
*/
function onDrawCancelledFactory(context) {
const { uiManager, activeFeatureManager } = context
const { toggleActionButtons, renderList } = uiManager
const { resetActiveFeature } = activeFeatureManager
/**
* Callback when a draw feature has been cancelled
*/
return function onDrawCancelled() {
toggleActionButtons(false)
resetActiveFeature()
renderList()
}
}
/**
* Callback factory function that fires when an interact marker has been changed
* @param {Context} context - the UI context
*/
function onInteractMarkerChangedFactory(context) {
const {
featuresManager,
activeFeatureManager,
map,
interactPlugin,
uiManager
} = context
const { addFeature, updateFeature } = featuresManager
const { getActiveFeature, resetActiveFeature } = activeFeatureManager
const { renderList, focusDescriptionInput, toggleActionButtons } = uiManager
/**
* Callback when an interact marker has been changed
* @param {{ coords: Coordinates }} e
*/
return function onInteractMarkerChange(e) {
const activeFeatureId = getActiveFeature()
if (activeFeatureId) {
// Editing an existing point
const feature = updateFeature(activeFeatureId, {
type: 'Point',
coordinates: e.coords
})
map.addMarker(activeFeatureId, e.coords)
if (feature) {
// Update the features
renderList()
}
resetActiveFeature()
} else {
// Adding a new point
const id = generateID()
addFeature({
type: 'Feature',
properties: {
description: ''
},
geometry: {
type: 'Point',
coordinates: e.coords
},
id
})
map.addMarker(id, e.coords)
// Update the features
renderList()
focusDescriptionInput()
}
map.removeMarker('location')
interactPlugin.disable()
toggleActionButtons(false)
}
}
/**
* Callback factory function that fires a 'click' event is fired on the list container
* @param {Context} context - the UI context
*/
function onListElClickFactory(context) {
const {
map,
mapProvider,
featuresManager,
activeFeatureManager,
interactPlugin,
uiManager,
drawPlugin
} = context
const { getFeature, removeFeature } = featuresManager
const { getActiveFeature, setActiveFeature } = activeFeatureManager
const { renderList, toggleActionButtons } = uiManager
/**
* Delete a feature
* @param {string} id - the feature id
* @param {string} type - the feature type
*/
function deleteFeature(id, type) {
if (type === 'Point') {
map.removeMarker(id)
removeFeature(id)
} else {
drawPlugin.deleteFeature(id)
removeFeature(id)
}
renderList()
}
/**
* Start editing feature
* @param {string} id - the feature id
* @param {string} type - the feature type
*/
function editFeature(id, type) {
setActiveFeature(id)
// "Change" feature link was clicked
if (type === 'Point') {
interactPlugin.selectFeature({ featureId: id })
interactPlugin.enable()
} else {
drawPlugin.editFeature(id)
}
const feature = getFeature(id)
if (feature && mapProvider) {
focusFeature(feature, mapProvider)
}
toggleActionButtons(true)
renderList(true)
}
/**
* List container delegated 'click' events handler
* @param {MouseEvent} e
*/
return function (e) {
const target = e.target
if (!(target instanceof HTMLElement)) {
return
}
if (getActiveFeature()) {
e.preventDefault()
e.stopPropagation()
return
}
if (
target.tagName === 'A' &&
target.dataset.action &&
target.dataset.id &&
target.dataset.type
) {
const { action, id, type } = target.dataset
if (action === 'edit') {
// "Update" feature link was clicked
editFeature(id, type)
} else {
e.preventDefault()
e.stopPropagation()
if (action === 'delete') {
// "Remove" feature link was clicked
deleteFeature(id, type)
}
}
}
}
}
/**
* Callback factory function that fires when a 'change' event is fired on the list container
* @param {Context} context - the UI context
*/
function onListElChangeFactory(context) {
const { featuresManager, uiManager } = context
const { getFeature } = featuresManager
const { renderValue } = uiManager
/**
* List container delegated 'change' events handler
* Used to update the description of features
* @param {Event} e
*/
return function (e) {
e.preventDefault()
e.stopPropagation()
const target = e.target
if (!(target instanceof HTMLInputElement) || !target.dataset.id) {
return
}
const { id } = target.dataset
const feature = getFeature(id)
if (feature) {
feature.properties.description = target.value.trim()
renderValue()
}
}
}
/**
* Callback factory function that fires when a 'keydown' event is fired on the list container
*/
function onListElKeydownFactory() {
/**
* List container delegated 'keydown' events handler
* Fixes the issue of pressing "Enter" key in the description input triggering the map search
* @param {KeyboardEvent} e
*/
return function (e) {
const target = e.target
if (!(target instanceof HTMLInputElement)) {
return
}
if (e.code === 'Enter' || e.code === 'NumpadEnter') {
e.preventDefault()
e.stopPropagation()
}
}
}
/**
* @import { MapsEnvironmentConfig, InteractiveMap } from '~/src/client/javascripts/map.js'
*/
/**
* @import { Geometry, FeatureCollection, Feature, Coordinates } from '~/src/server/plugins/engine/types.js'
*/
/**
* @typedef {object} GeoJSON
* @property {'FeatureCollection'} type - the GeoJSON type string
* @property {FeatureCollection} features - the features
*/
/**
* Gets all the features
* @callback GetFeatures
* @returns {FeatureCollection}
*/
/**
* Gets a feature from the geojson by id
* @callback GetFeature
* @param {string} id - the feature id
* @returns {Feature | undefined}
*/
/**
* Add a feature to the geojson
* @callback AddFeature
* @param {Feature} feature - the feature to add
*/
/**
* Update a feature in the geojson
* @callback UpdateFeature
* @param {string} id - the feature id
* @param {Geometry} geometry - the feature geometry
* @returns {Feature | undefined}
*/
/**
* Removes a feature from the geojson
* @callback RemoveFeature
* @param {string} id - the feature id
*/
/**
* Gets the active feature id
* @callback GetActiveFeature
* @returns {string | undefined}
*/
/**
* Set the active feature id
* @callback SetActiveFeature
* @param {string} id - the feature id
* @returns {void}
*/
/**
* Resets the active feature id
* @callback ResetActiveFeature
* @returns {void}
*/