@defra/interactive-map 0.0.56-alpha → 0.0.57-alpha
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.
- package/dist/esm/im-core.js +1 -1
- package/dist/umd/im-core.js +1 -1
- package/dist/umd/index.js +1 -1
- package/docs/api/button-definition.md +11 -0
- package/docs/api/context.md +2 -0
- package/docs/api.md +3 -1
- package/docs/plugins/draw.md +189 -33
- package/package.json +1 -1
- package/plugins/datasets/dist/esm/im-datasets-plugin.js +1 -1
- package/plugins/datasets/dist/umd/im-datasets-plugin.js +1 -1
- package/plugins/datasets/dist/umd/index.js +1 -1
- package/plugins/datasets/src/initialise/DatasetsInit.jsx +6 -17
- package/plugins/datasets/src/initialise/DatasetsInit.test.jsx +3 -43
- package/plugins/draw/dist/esm/im-draw-ml-adapter.js +1 -1
- package/plugins/draw/dist/esm/im-draw-ol-adapter.js +1 -1
- package/plugins/draw/dist/esm/im-draw-plugin.js +1 -1
- package/plugins/draw/dist/esm/index.js +1 -1
- package/plugins/draw/dist/esm/liveDrawChecks.js +1 -1
- package/plugins/draw/dist/umd/im-draw-ml-adapter.js +1 -1
- package/plugins/draw/dist/umd/im-draw-ol-adapter.js +1 -1
- package/plugins/draw/dist/umd/im-draw-plugin.js +1 -1
- package/plugins/draw/dist/umd/index.js +1 -1
- package/plugins/draw/src/DrawInit.jsx +9 -6
- package/plugins/draw/src/DrawInit.test.jsx +15 -0
- package/plugins/draw/src/adapterEvents.js +78 -44
- package/plugins/draw/src/adapters/adapterContract.test.js +3 -3
- package/plugins/draw/src/adapters/maplibre/MaplibreDrawAdapter.js +18 -10
- package/plugins/draw/src/adapters/maplibre/MaplibreDrawAdapter.test.js +31 -22
- package/plugins/draw/src/adapters/maplibre/drawEvents.js +2 -1
- package/plugins/draw/src/adapters/maplibre/modes/drawMode/clickHandlers.js +13 -12
- package/plugins/draw/src/adapters/maplibre/modes/drawMode/clickHandlers.test.js +5 -5
- package/plugins/draw/src/adapters/maplibre/modes/drawMode/undoHandlers.js +1 -1
- package/plugins/draw/src/adapters/maplibre/modes/drawMode/undoHandlers.test.js +2 -2
- package/plugins/draw/src/adapters/maplibre/modes/drawPointMode.js +6 -9
- package/plugins/draw/src/adapters/maplibre/modes/drawPointMode.test.js +4 -4
- package/plugins/draw/src/adapters/maplibre/modes/editPointMode/pointerHandlers.js +6 -9
- package/plugins/draw/src/adapters/maplibre/modes/editPointMode/pointerHandlers.test.js +1 -1
- package/plugins/draw/src/adapters/maplibre/modes/editPointMode/undoHandlers.js +8 -14
- package/plugins/draw/src/adapters/maplibre/modes/editPointMode/undoHandlers.test.js +37 -8
- package/plugins/draw/src/adapters/maplibre/modes/editPointMode.js +11 -1
- package/plugins/draw/src/adapters/maplibre/modes/editVertexMode/undoHandlers.js +14 -19
- package/plugins/draw/src/adapters/maplibre/modes/editVertexMode/undoHandlers.test.js +41 -4
- package/plugins/draw/src/adapters/maplibre/modes/editVertexMode.js +12 -1
- package/plugins/draw/src/adapters/maplibre/utils/editModeEvents.js +3 -1
- package/plugins/draw/src/adapters/maplibre/utils/geometryValidation.js +9 -10
- package/plugins/draw/src/adapters/maplibre/utils/geometryValidation.test.js +5 -24
- package/plugins/draw/src/adapters/openlayers/OLDrawAdapter.js +10 -7
- package/plugins/draw/src/adapters/openlayers/OLDrawAdapter.test.js +12 -7
- package/plugins/draw/src/adapters/openlayers/core/OLDrawManager.js +5 -0
- package/plugins/draw/src/adapters/openlayers/core/OLDrawManager.test.js +7 -3
- package/plugins/draw/src/adapters/openlayers/draw/DrawMode.js +11 -11
- package/plugins/draw/src/adapters/openlayers/draw/DrawMode.test.js +15 -15
- package/plugins/draw/src/adapters/openlayers/edit/EditMode.js +21 -28
- package/plugins/draw/src/adapters/openlayers/edit/EditMode.test.js +26 -5
- package/plugins/draw/src/adapters/openlayers/edit/selectionState.js +5 -6
- package/plugins/draw/src/adapters/openlayers/edit/selectionState.test.js +2 -12
- package/plugins/draw/src/adapters/openlayers/edit/undoOps.js +9 -0
- package/plugins/draw/src/adapters/openlayers/edit/undoOps.test.js +7 -0
- package/plugins/draw/src/adapters/openlayers/point/drawPointMode.js +6 -9
- package/plugins/draw/src/adapters/openlayers/point/drawPointMode.test.js +3 -3
- package/plugins/draw/src/adapters/openlayers/point/editPointMode.js +18 -9
- package/plugins/draw/src/adapters/openlayers/point/editPointMode.test.js +29 -4
- package/plugins/draw/src/adapters/openlayers/point/pointOps.js +3 -2
- package/plugins/draw/src/adapters/openlayers/point/pointOps.test.js +6 -0
- package/plugins/draw/src/adapters/openlayers/point/pointSelectionState.js +3 -4
- package/plugins/draw/src/adapters/openlayers/point/pointSelectionState.test.js +2 -12
- package/plugins/draw/src/api/createNewShape.js +4 -4
- package/plugins/draw/src/api/createNewShape.test.js +1 -1
- package/plugins/draw/src/api/editFeature.js +8 -11
- package/plugins/draw/src/api/editFeature.test.js +33 -22
- package/plugins/draw/src/api/newLine.test.js +3 -3
- package/plugins/draw/src/api/newPoint.js +4 -5
- package/plugins/draw/src/api/newPoint.test.js +3 -3
- package/plugins/draw/src/api/newPolygon.test.js +3 -3
- package/plugins/draw/src/api/recheckGeometry.js +32 -0
- package/plugins/draw/src/api/recheckGeometry.test.js +55 -0
- package/plugins/draw/src/api/setGeometry.js +33 -0
- package/plugins/draw/src/api/setGeometry.test.js +48 -0
- package/plugins/draw/src/api/split.js +23 -22
- package/plugins/draw/src/api/split.test.js +33 -18
- package/plugins/draw/src/events.js +265 -77
- package/plugins/draw/src/events.test.js +708 -34
- package/plugins/draw/src/hooks/useSpatialList.js +10 -11
- package/plugins/draw/src/hooks/useSpatialList.test.js +3 -3
- package/plugins/draw/src/manifest.js +30 -15
- package/plugins/draw/src/manifest.test.js +91 -9
- package/plugins/draw/src/reducer.js +31 -9
- package/plugins/draw/src/reducer.test.js +35 -3
- package/plugins/draw/src/utils/drawModes.js +27 -0
- package/plugins/draw/src/utils/drawModes.test.js +27 -0
- package/plugins/draw/src/utils/needsDrawTarget.js +1 -5
- package/plugins/draw/src/utils/needsDrawTarget.test.js +1 -11
- package/plugins/draw/src/utils/touchTarget.js +34 -26
- package/plugins/draw/src/utils/touchTarget.test.js +32 -20
- package/plugins/draw/src/validation/commitChecks.js +185 -0
- package/plugins/draw/src/validation/commitChecks.test.js +205 -0
- package/plugins/draw/src/validation/liveDrawChecks.js +11 -11
- package/plugins/draw/src/validation/liveDrawChecks.test.js +37 -37
- package/plugins/draw/src/validation/liveStroke.js +6 -6
- package/plugins/draw/src/validation/liveStroke.test.js +27 -27
- package/plugins/draw/src/validation/rules.js +16 -14
- package/plugins/draw/src/validation/rules.test.js +5 -5
- package/plugins/draw/src/validation/validateGeometry.js +58 -31
- package/plugins/draw/src/validation/validateGeometry.test.js +68 -44
- package/plugins/interact/dist/esm/im-interact-plugin.js +1 -1
- package/plugins/interact/dist/umd/im-interact-plugin.js +1 -1
- package/plugins/interact/dist/umd/index.js +1 -1
- package/plugins/interact/src/hooks/useInteractionHandlers.js +3 -5
- package/plugins/interact/src/hooks/useInteractionHandlers.test.js +4 -3
- package/plugins/interact/src/hooks/useSpatialList.js +16 -17
- package/plugins/interact/src/hooks/useSpatialList.test.js +9 -9
- package/plugins/map-styles/dist/esm/im-map-styles-plugin.js +1 -1
- package/plugins/map-styles/dist/umd/im-map-styles-plugin.js +1 -1
- package/plugins/map-styles/src/MapStyles.jsx +2 -2
- package/providers/maplibre/dist/esm/index.js +1 -1
- package/providers/maplibre/dist/umd/index.js +1 -1
- package/providers/maplibre/src/index.js +11 -2
- package/providers/maplibre/src/index.test.js +23 -1
- package/providers/maplibre/src/utils/detectModuleWorker.js +8 -19
- package/providers/maplibre/src/utils/detectModuleWorker.test.js +19 -23
- package/providers/maplibre/src/utils/workerUrl.js +12 -0
- package/providers/maplibre/src/utils/workerUrl.test.js +14 -1
- package/src/App/components/MapButton/MapButton.jsx +6 -0
- package/src/App/components/MapButton/MapButton.test.jsx +10 -0
- package/src/App/components/Markers/Markers.jsx +3 -5
- package/src/App/components/Markers/Markers.test.jsx +9 -11
- package/src/App/components/Panel/Panel.jsx +2 -9
- package/src/App/hooks/useInterfaceAPI.js +16 -4
- package/src/App/hooks/useInterfaceAPI.test.js +66 -1
- package/src/App/renderer/mapButtons.js +2 -1
- package/src/App/renderer/mapButtons.test.js +9 -0
- package/src/App/store/MapProvider.jsx +3 -0
- package/src/App/store/MapProvider.test.jsx +24 -0
- package/src/config/mapSizeScales.js +3 -0
- package/src/types.js +4 -0
- package/src/utils/focusAfterPanelClose.js +9 -0
- package/src/utils/focusAfterPanelClose.test.js +40 -0
package/docs/plugins/draw.md
CHANGED
|
@@ -71,11 +71,19 @@ createDrawPlugin({
|
|
|
71
71
|
|
|
72
72
|
---
|
|
73
73
|
|
|
74
|
+
### `onGeometryPreview`
|
|
75
|
+
|
|
76
|
+
**Type:** `Function`
|
|
77
|
+
|
|
78
|
+
Plugin-level synchronous check, called while a shape is drawn or dragged and when a vertex is about to be placed. Can be overridden per call. See [`onGeometryPreview`](#ongeometrypreviewevent).
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
74
82
|
### `onGeometryChange`
|
|
75
83
|
|
|
76
84
|
**Type:** `Function`
|
|
77
85
|
|
|
78
|
-
Plugin-level
|
|
86
|
+
Plugin-level check, called after each committed change to a shape. Can return a Promise, so the shape can be checked against a service. Can be overridden per call. See [`onGeometryChange`](#ongeometrychangeevent-context).
|
|
79
87
|
|
|
80
88
|
---
|
|
81
89
|
|
|
@@ -113,7 +121,10 @@ createDrawPlugin({
|
|
|
113
121
|
|
|
114
122
|
## Validation
|
|
115
123
|
|
|
116
|
-
Every geometry change
|
|
124
|
+
Every geometry change is checked against a set of built-in rules, plus your own callbacks if you provide them:
|
|
125
|
+
|
|
126
|
+
- [`onGeometryPreview`](#ongeometrypreviewevent) — synchronous. Gives live feedback while a shape is drawn or dragged, and can reject a vertex before it's placed.
|
|
127
|
+
- [`onGeometryChange`](#ongeometrychangeevent-context) — called after each committed change. Can be asynchronous. Its result for the latest change gates the Done button.
|
|
117
128
|
|
|
118
129
|
### Built-in rules
|
|
119
130
|
|
|
@@ -126,53 +137,138 @@ Every geometry change — placing a vertex, dragging one, finishing a shape —
|
|
|
126
137
|
|
|
127
138
|
Rule failures gate the Done button (the shape can pass through interim invalid states while being built or reshaped, shown with a dashed outline) except the placement-time self-intersection check, which is a hard veto — that specific vertex is rejected and never placed.
|
|
128
139
|
|
|
129
|
-
###
|
|
140
|
+
### Setting the callbacks
|
|
141
|
+
|
|
142
|
+
Both callbacks are set at the plugin level (`createDrawPlugin({ onGeometryPreview, onGeometryChange })`) or per call, in the options of `newPolygon`, `newLine`, `newPoint` and `editFeature`. A per-call callback replaces the plugin-level one for that session. To run both, call the plugin-level callback from the per-call one.
|
|
143
|
+
|
|
144
|
+
Each session has one of each callback. When more than one part of your app needs `onGeometryChange`, such as a measurements panel and a rules service, pass a single callback that calls each of them and returns the result that should gate Done:
|
|
145
|
+
|
|
146
|
+
```js
|
|
147
|
+
createDrawPlugin({
|
|
148
|
+
onGeometryChange: (event, context) => {
|
|
149
|
+
measurements.update(event.feature)
|
|
150
|
+
return rules.check(event, context)
|
|
151
|
+
}
|
|
152
|
+
})
|
|
153
|
+
```
|
|
130
154
|
|
|
131
|
-
|
|
155
|
+
Neither is used by `split` (which checks that the line divides the shape in two) or by `merge`, `addFeature` and `setStyle`.
|
|
132
156
|
|
|
133
|
-
|
|
157
|
+
Both return the same result:
|
|
134
158
|
|
|
135
159
|
| Return value | Meaning |
|
|
136
160
|
|---|---|
|
|
137
161
|
| `true` / `undefined` | Valid |
|
|
138
162
|
| `false` | Invalid, no reason shown |
|
|
139
|
-
| `{ valid, reason }` | Valid or invalid, with
|
|
163
|
+
| `{ valid, reason, announcement, recheckOnFinish }` | Valid or invalid, with these optional fields |
|
|
140
164
|
|
|
141
|
-
|
|
165
|
+
| Result field | Type | Description |
|
|
166
|
+
|---|---|---|
|
|
167
|
+
| `reason` | `string` | Why the shape is invalid. Shown as a hint toast and sent with [`draw:geometryinvalid`](#drawgeometryinvalid) |
|
|
168
|
+
| `announcement` | `string` | Announced to screen readers instead of draw's own message, whether the result is valid or not. When set, `reason` isn't shown as a hint toast, so you can present the issue yourself. From `onGeometryPreview`, only a rejected placement is announced |
|
|
169
|
+
| `recheckOnFinish` | `boolean` | `onGeometryChange` only. When the shape is finished, check it again with phase `'create'` or `'edit-finish'` rather than reusing this result. See [Checking once a shape is finished](#checking-once-a-shape-is-finished) |
|
|
170
|
+
|
|
171
|
+
Both receive the same event:
|
|
142
172
|
|
|
143
173
|
| Property | Type | Description |
|
|
144
174
|
|----------|------|-------------|
|
|
145
|
-
| `feature` | `GeoJSON.Feature` | The shape
|
|
146
|
-
| `phase` | `string` |
|
|
175
|
+
| `feature` | `GeoJSON.Feature` | The shape being checked — the in-progress feature during `'preview'`, the committed or candidate feature in every other phase |
|
|
176
|
+
| `phase` | `string` | Why the callback was called — see each callback's phases below |
|
|
147
177
|
| `mode` | `'draw_polygon' \| 'draw_line' \| 'draw_point' \| 'edit_vertex' \| 'edit_point'` | The active draw mode |
|
|
148
|
-
| `vertexIndex` | `number` | Index of the vertex being placed
|
|
178
|
+
| `vertexIndex` | `number` | Index of the vertex being placed, added, moved, inserted or deleted. Present on `'place'`, and on a `'change'` to a single vertex |
|
|
149
179
|
| `numVertices` | `number` | Count of already-committed vertices, excluding any in-progress cursor point. Present on every `'preview'` call |
|
|
150
180
|
|
|
151
|
-
|
|
181
|
+
### `onGeometryPreview(event)`
|
|
182
|
+
|
|
183
|
+
**Signature:** `onGeometryPreview(event) => boolean | { valid: boolean, reason?: string, announcement?: string } | undefined`
|
|
184
|
+
|
|
185
|
+
Must return synchronously. A returned Promise is treated as valid.
|
|
186
|
+
|
|
187
|
+
| Phase | When | Effect |
|
|
188
|
+
|-------|------|--------|
|
|
189
|
+
| `'preview'` | Every rubber-band move or drag, throttled to once per frame | Drives the dashed outline and the Add point button. While editing, also gates the Done button |
|
|
190
|
+
| `'place'` | A click, tap, <kbd>Enter</kbd> or Add point press, before the vertex is placed | Invalid rejects the vertex — it never appears |
|
|
191
|
+
|
|
192
|
+
It runs on every frame of a drag, so keep it quick, using only the shape and data already in the page. Rules about a single vertex, such as where the first point may go, belong here: `onGeometryChange` isn't called until the shape has its minimum number of vertices.
|
|
193
|
+
|
|
194
|
+
### `onGeometryChange(event, context)`
|
|
195
|
+
|
|
196
|
+
**Signature:** `onGeometryChange(event, { signal, revision }) => boolean | { valid: boolean, reason?: string, announcement?: string, recheckOnFinish?: boolean } | undefined | Promise<…>`
|
|
197
|
+
|
|
198
|
+
Called after each change to a shape. It can return a Promise, so you can check the shape with a service.
|
|
199
|
+
|
|
200
|
+
| Phase | When |
|
|
201
|
+
|-------|------|
|
|
202
|
+
| `'change'` | The shape changed, including with [`setGeometry`](#setgeometrygeometry) or undo |
|
|
203
|
+
| `'create'` | A new shape was finished without a passing result, such as a new point, or with [`recheckOnFinish`](#checking-once-a-shape-is-finished) |
|
|
204
|
+
| `'edit-start'` | `editFeature` opened the shape |
|
|
205
|
+
| `'edit-finish'` | Done was pressed on an edit, with [`recheckOnFinish`](#checking-once-a-shape-is-finished) |
|
|
206
|
+
| `'recheck'` | [`recheckGeometry`](#recheckgeometrydetail) was called. Its `detail` is on `event.detail` |
|
|
207
|
+
|
|
208
|
+
| Context property | Type | Description |
|
|
209
|
+
|----------|------|-------------|
|
|
210
|
+
| `signal` | `AbortSignal` | Aborted when the shape changes again or the session ends. Pass it to `fetch` to cancel the request |
|
|
211
|
+
| `revision` | `number` | Increases with every check |
|
|
212
|
+
|
|
213
|
+
- It's only called once the built-in rules pass.
|
|
214
|
+
- Only the result for the latest change counts.
|
|
215
|
+
- A shape that fails, or whose check throws or rejects, can't be finished. Call `recheckGeometry()` to retry.
|
|
216
|
+
- If the user finishes while a check is running, draw waits for it. A new shape that then fails is reopened in edit mode ([`draw:reopened`](#drawreopened)). An edit that fails stays open.
|
|
217
|
+
|
|
218
|
+
### Checking once a shape is finished
|
|
219
|
+
|
|
220
|
+
When a shape is finished, the result for its last change is used. To check the whole shape once at the end instead, such as with a single service call, return `recheckOnFinish: true` for each change. `onGeometryChange` is then called again when the shape is finished, with phase `'create'` for a new shape or `'edit-finish'` when Done is pressed on an edit.
|
|
221
|
+
|
|
222
|
+
This updates a panel on every change, and calls a validation service once, when the shape is finished:
|
|
223
|
+
|
|
224
|
+
```js
|
|
225
|
+
createDrawPlugin({
|
|
226
|
+
onGeometryChange: ({ feature, phase }, { signal }) => {
|
|
227
|
+
// Update the panel without waiting for it, so finishing never waits on it.
|
|
228
|
+
// The signal cancels the request if the shape changes again.
|
|
229
|
+
contextPanel.update(feature, { signal })
|
|
230
|
+
|
|
231
|
+
// Let each change through, and check once the shape is finished
|
|
232
|
+
if (phase === 'change' || phase === 'edit-start') {
|
|
233
|
+
return { valid: true, recheckOnFinish: true }
|
|
234
|
+
}
|
|
235
|
+
// 'create', 'edit-finish' and 'recheck' are checked by the service
|
|
236
|
+
return validateWithService(feature, { signal })
|
|
237
|
+
}
|
|
238
|
+
})
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
This works with an `async` function too, as long as the panel update isn't awaited. Otherwise draw treats the check as pending until the panel replies.
|
|
242
|
+
|
|
243
|
+
In a reopened shape, Undo starts empty, and Cancel discards the shape, as it does while the shape is waiting on its check.
|
|
244
|
+
|
|
245
|
+
### Debouncing
|
|
152
246
|
|
|
153
|
-
|
|
154
|
-
|-------|------|-----------|
|
|
155
|
-
| `'preview'` | Live feedback on every rubber-band move while drawing/dragging, throttled to once per frame. Drives both the dashed-outline check and the Add-point button | No — display only |
|
|
156
|
-
| `'place'` | A real click/tap/Add-point press, evaluated once, synchronously | Yes — a hard rule or your callback returning invalid rejects the vertex outright; it never appears |
|
|
157
|
-
| `'create'` | A whole new feature just finished being drawn | Gates whether it's accepted as-is or reopened in edit mode |
|
|
158
|
-
| `'edit-start'` | An existing feature was just loaded into an edit session — the baseline check before anything has changed | Gates the initial Done state |
|
|
159
|
-
| `'commit-add'` | A vertex was added while drawing | Gates Done |
|
|
160
|
-
| `'commit-move'` | A vertex was dragged/nudged while editing | Gates Done |
|
|
161
|
-
| `'commit-insert'` | A vertex was inserted at a midpoint while editing | Gates Done |
|
|
162
|
-
| `'commit-delete'` | A vertex was removed while editing | Gates Done |
|
|
247
|
+
Debouncing and timeouts are up to you. Waiting on `signal` gives a debounce that cancels itself when the shape changes again:
|
|
163
248
|
|
|
164
249
|
```js
|
|
250
|
+
const wait = (ms, signal) => new Promise((resolve, reject) => {
|
|
251
|
+
const timer = setTimeout(resolve, ms)
|
|
252
|
+
signal.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason) }, { once: true })
|
|
253
|
+
})
|
|
254
|
+
|
|
165
255
|
createDrawPlugin({
|
|
166
|
-
|
|
256
|
+
onGeometryPreview: (event) => ({
|
|
167
257
|
valid: isEastOfWalesBorder(event.feature.geometry),
|
|
168
258
|
reason: 'Points must be placed east of the England/Wales border'
|
|
169
|
-
})
|
|
259
|
+
}),
|
|
260
|
+
onGeometryChange: async ({ feature }, { signal }) => {
|
|
261
|
+
infoPanel.update(measureArea(feature))
|
|
262
|
+
await wait(300, signal)
|
|
263
|
+
const response = await fetch('/api/boundary-checks', { method: 'POST', body: JSON.stringify(feature), signal })
|
|
264
|
+
return response.json() // { valid, reason }
|
|
265
|
+
}
|
|
170
266
|
})
|
|
171
267
|
```
|
|
172
268
|
|
|
173
269
|
## Methods
|
|
174
270
|
|
|
175
|
-
Methods are called on the plugin instance. `newPolygon`, `newLine`, `newPoint`, `editFeature`, `addFeature`, `setStyle`, `deleteFeature`, `split`, and `
|
|
271
|
+
Methods are called on the plugin instance. `newPolygon`, `newLine`, `newPoint`, `editFeature`, `addFeature`, `setStyle`, `deleteFeature`, `split`, `merge`, `setGeometry` and `recheckGeometry` all need `mapProvider.draw` to be ready — call them after [`draw:ready`](#drawready).
|
|
176
272
|
|
|
177
273
|
---
|
|
178
274
|
|
|
@@ -184,7 +280,8 @@ Start drawing a new polygon.
|
|
|
184
280
|
|----------|------|-------------|
|
|
185
281
|
| `featureId` | `string` | **Required.** ID to assign the finished feature |
|
|
186
282
|
| `options.snapLayers` | `string[]` | Overrides the plugin-level `snapLayers` for this session |
|
|
187
|
-
| `options.
|
|
283
|
+
| `options.onGeometryPreview` | `Function` | Replaces the plugin-level `onGeometryPreview` for this session — see [Validation](#validation) |
|
|
284
|
+
| `options.onGeometryChange` | `Function` | Replaces the plugin-level `onGeometryChange` for this session — see [Validation](#validation) |
|
|
188
285
|
| `options.stroke` | `string \| Record<string, string>` | Stroke colour for this shape |
|
|
189
286
|
| `options.fill` | `string \| Record<string, string>` | Fill colour for this shape |
|
|
190
287
|
| `options.strokeWidth` | `number` | Stroke width in pixels for this shape |
|
|
@@ -220,7 +317,8 @@ Start drawing a new point. Unlike `newPolygon`/`newLine`, it commits as soon as
|
|
|
220
317
|
|----------|------|-------------|
|
|
221
318
|
| `featureId` | `string` | **Required.** ID to assign the finished feature |
|
|
222
319
|
| `options.snapLayers` | `string[]` | Overrides the plugin-level `snapLayers` for this session |
|
|
223
|
-
| `options.
|
|
320
|
+
| `options.onGeometryPreview` | `Function` | Replaces the plugin-level `onGeometryPreview` for this session — see [Validation](#validation) |
|
|
321
|
+
| `options.onGeometryChange` | `Function` | Replaces the plugin-level `onGeometryChange` for this session — see [Validation](#validation) |
|
|
224
322
|
| `options.properties` | `Object` | Custom GeoJSON properties to set on the finished feature |
|
|
225
323
|
| `options.symbol` | `string` | Built-in symbol id — `'pin'`, `'circle'`, `'square'`, `'hexagon'`, `'triangle'`, or `'diamond'` |
|
|
226
324
|
| `options.symbolSvgContent` | `string` | Custom SVG markup, used instead of `symbol` |
|
|
@@ -251,7 +349,8 @@ Open an existing feature in edit mode — vertex-edit for a `Polygon`/`LineStrin
|
|
|
251
349
|
|----------|------|-------------|
|
|
252
350
|
| `featureId` | `string` | **Required.** ID of the feature to edit |
|
|
253
351
|
| `options.snapLayers` | `string[]` | Overrides the plugin-level `snapLayers` for this session |
|
|
254
|
-
| `options.
|
|
352
|
+
| `options.onGeometryPreview` | `Function` | Replaces the plugin-level `onGeometryPreview` for this session — see [Validation](#validation) |
|
|
353
|
+
| `options.onGeometryChange` | `Function` | Replaces the plugin-level `onGeometryChange` for this session — see [Validation](#validation) |
|
|
255
354
|
|
|
256
355
|
```js
|
|
257
356
|
const editSuccess = drawPlugin.editFeature(selectedFeatureId)
|
|
@@ -382,6 +481,55 @@ interactiveMap.on('draw:merge', (event) => {
|
|
|
382
481
|
})
|
|
383
482
|
```
|
|
384
483
|
|
|
484
|
+
---
|
|
485
|
+
|
|
486
|
+
### `setGeometry(geometry)`
|
|
487
|
+
|
|
488
|
+
Replace the shape in the current edit session, for example with a corrected boundary from a service. The change can be undone, and is checked like any other change, with phase `'change'`. Returns `false` (without doing anything) outside an edit session, or when the geometry type differs from the shape being edited.
|
|
489
|
+
|
|
490
|
+
| Argument | Type | Description |
|
|
491
|
+
|----------|------|-------------|
|
|
492
|
+
| `geometry` | `GeoJSON.Geometry` | **Required.** The new geometry, of the same type as the shape being edited |
|
|
493
|
+
|
|
494
|
+
```js
|
|
495
|
+
drawPlugin.setGeometry(correctedBoundary)
|
|
496
|
+
```
|
|
497
|
+
|
|
498
|
+
---
|
|
499
|
+
|
|
500
|
+
### `recheckGeometry(detail?)`
|
|
501
|
+
|
|
502
|
+
Call `onGeometryChange` again for the current shape, unchanged, with phase `'recheck'`. Use it when your answer may have changed without the shape changing — for example after the user chooses to ignore a warning — or to retry a check that failed. Returns `false` (without doing anything) outside a draw or edit session, or before the shape has been checked.
|
|
503
|
+
|
|
504
|
+
| Argument | Type | Description |
|
|
505
|
+
|----------|------|-------------|
|
|
506
|
+
| `detail` | `any` | Passed to `onGeometryChange` as `event.detail`, for example to tell an ignored warning from a retry |
|
|
507
|
+
|
|
508
|
+
```js
|
|
509
|
+
const ignoredWarnings = new Set()
|
|
510
|
+
|
|
511
|
+
let warnings = []
|
|
512
|
+
|
|
513
|
+
createDrawPlugin({
|
|
514
|
+
onGeometryChange: async ({ feature, detail }, { signal }) => {
|
|
515
|
+
// Ignoring a warning reuses the last answer; anything else, including a retry, asks again
|
|
516
|
+
if (detail?.reason !== 'ignore') {
|
|
517
|
+
warnings = await checkBoundary(feature, { signal })
|
|
518
|
+
}
|
|
519
|
+
return { valid: warnings.every((warning) => ignoredWarnings.has(warning.id)) }
|
|
520
|
+
}
|
|
521
|
+
})
|
|
522
|
+
|
|
523
|
+
const onIgnoreWarning = (warning) => {
|
|
524
|
+
ignoredWarnings.add(warning.id)
|
|
525
|
+
drawPlugin.recheckGeometry({ reason: 'ignore' })
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
const onRetry = () => drawPlugin.recheckGeometry({ reason: 'retry' })
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
---
|
|
532
|
+
|
|
385
533
|
## Application mode
|
|
386
534
|
|
|
387
535
|
While drawing or editing, the plugin sets the `'draw'` [application mode](../api.md#setapplicationmodeid-options), which gives the interface over to drawing: every button, panel and control, in every slot, is hidden except draw's own and these defaults:
|
|
@@ -447,7 +595,7 @@ Emitted once the draw plugin has initialised. Safe to call API methods from here
|
|
|
447
595
|
|
|
448
596
|
Emitted when `newPolygon`, `newLine`, or `newPoint` starts a new draw session.
|
|
449
597
|
|
|
450
|
-
**Payload:** `{ mode: 'draw_polygon' | 'draw_line' | 'draw_point' }`
|
|
598
|
+
**Payload:** `{ mode: 'draw_polygon' | 'draw_line' | 'draw_point', featureId: string }`
|
|
451
599
|
|
|
452
600
|
---
|
|
453
601
|
|
|
@@ -455,13 +603,13 @@ Emitted when `newPolygon`, `newLine`, or `newPoint` starts a new draw session.
|
|
|
455
603
|
|
|
456
604
|
Emitted when `editFeature` opens an existing feature for editing.
|
|
457
605
|
|
|
458
|
-
**Payload:** `{ mode: 'edit_polygon' | 'edit_line' | 'edit_point' }`
|
|
606
|
+
**Payload:** `{ mode: 'edit_polygon' | 'edit_line' | 'edit_point', featureId: string }`
|
|
459
607
|
|
|
460
608
|
---
|
|
461
609
|
|
|
462
610
|
### `draw:created`
|
|
463
611
|
|
|
464
|
-
Emitted when a new shape finishes drawing and passes
|
|
612
|
+
Emitted when a new shape finishes drawing and passes its checks. Also fires for a shape that finished invalid, was automatically reopened in edit mode, and was then fixed and finished — from the caller's perspective it's still a creation, not an edit.
|
|
465
613
|
|
|
466
614
|
**Payload:** the finished `GeoJSON.Feature`
|
|
467
615
|
|
|
@@ -475,9 +623,17 @@ Emitted when an existing feature finishes an edit session (via `editFeature`).
|
|
|
475
623
|
|
|
476
624
|
---
|
|
477
625
|
|
|
626
|
+
### `draw:reopened`
|
|
627
|
+
|
|
628
|
+
Emitted when a new shape is finished, its `onGeometryChange` check fails, and it reopens in edit mode. See [Validation](#validation).
|
|
629
|
+
|
|
630
|
+
**Payload:** `{ feature, status: 'invalid' | 'error', reason }` — `reason` is `null` unless an invalid result gave one
|
|
631
|
+
|
|
632
|
+
---
|
|
633
|
+
|
|
478
634
|
### `draw:cancelled`
|
|
479
635
|
|
|
480
|
-
Emitted when the Cancel button is pressed during a draw or edit session.
|
|
636
|
+
Emitted when the Cancel button is pressed during a draw or edit session. Cancelling a new shape that's waiting on its check, or has reopened in edit mode, removes it from the map. Also emitted when a new session starts while a finished shape is still waiting on its check, which discards it.
|
|
481
637
|
|
|
482
638
|
**Payload:** the feature being drawn/edited at the time of cancellation
|
|
483
639
|
|
|
@@ -509,9 +665,9 @@ Emitted when the input device changes mid-session (e.g. switching from mouse to
|
|
|
509
665
|
|
|
510
666
|
### `draw:geometryinvalid`
|
|
511
667
|
|
|
512
|
-
Emitted whenever a
|
|
668
|
+
Emitted whenever a check — a built-in rule, a placement rejected by `onGeometryPreview`, or an invalid result from `onGeometryChange` for the latest change — fails. Not emitted for the `'edit-start'` check of a feature that was already invalid. The `reason` is also shown as a hint toast, unless the result has its own `announcement`, or the shape simply hasn't reached its minimum vertex count yet. See [Validation](#validation).
|
|
513
669
|
|
|
514
|
-
**Payload:** `{ feature, reason, phase, mode, vertexIndex? }`
|
|
670
|
+
**Payload:** `{ feature, reason, source, phase, mode, vertexIndex? }` — `source` is `'rules'` for a built-in rule and `'callback'` for `onGeometryPreview` or `onGeometryChange`
|
|
515
671
|
|
|
516
672
|
---
|
|
517
673
|
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{useRef as t,useEffect as e}from"preact/compat";import{jsx as a,jsxs as s,Fragment as i}from"preact/jsx-runtime";const r=t=>{const{datasets:e=[]}=t,a=[],s=e.filter(t=>t.showInMenu||t.sublayers?.some(t=>t.showInMenu)),i=new Map;return s.forEach(t=>{if(t.sublayers?.length){const e=t.sublayers.filter(e=>t.showInMenu?!1!==e.showInMenu:e.showInMenu);if(!1===t.showInMenu&&!e.length)return;const s={id:t.id,groupLabel:t.label,visibleWhen:!0,type:"checkbox",items:e.map(e=>({id:`${t.id}-${e.id}`,label:e.label}))};0===s.items.length&&(delete s.groupLabel,s.items.push({id:t.id,label:t.label})),a.push(s)}else if(t.groupLabel){const e=i.has(t.groupLabel)?i.get(t.groupLabel):{id:t.groupLabel,groupLabel:t.groupLabel,visibleWhen:!0,type:"checkbox",items:[]};i.has(t.groupLabel)||(i.set(t.groupLabel,e),a.push(e)),e.items.push({id:t.id,label:t.label})}else a.push({visibleWhen:!0,type:"checkbox",id:t.id,items:[{id:t.id,label:t.label}]})}),a},n=(t,e)=>t.reduce((t,a)=>{const s=a.items.filter(t=>!e.includes(t.id));return s.length&&t.push({...a,items:s}),t},[]),o={minZoom:6,maxZoom:24,showInKey:!1,showInMenu:!1,visible:!0,style:{stroke:"#d4351c",strokeWidth:2,symbolDescription:"red outline"}},l=["stroke","strokeWidth","strokeDashArray","fill","fillPattern","fillPatternSvgContent","fillPatternForegroundColor","fillPatternBackgroundColor","opacity","symbolDescription","symbol","symbolSvgContent","symbolViewBox","symbolAnchor","symbolSize","symbolBackgroundColor","symbolForegroundColor","symbolHaloWidth","symbolGraphic"],d=["stroke","fill","fillPattern","fillPatternSvgContent","symbol","symbolSvgContent"],u=t=>d.some(e=>e in t),p=(t={})=>u(t)?{strokeWidth:o.style.strokeWidth,...t}:{...o.style,...t},h=(t,e)=>{const{id:a}=e,s=(t=>{!0!==t.visible&&!1!==t.visible&&(t.visible="hidden"!==t.visibility);const e={...o,...t,style:{...t.style}};return l.forEach(t=>delete e[t]),e})(e);e.parentId&&("showInKey"in e||delete s.showInKey,"showInMenu"in e||delete s.showInMenu),t[a]=s;const{orderedDatasets:i}=t;i.push(a);const r=e.sublayers?.map(t=>((t,e)=>{const a=`${t}-${e.id}`,s=e.id;return"hidden"!==e.visibility&&(e.visibility="visible"),{...e,id:a,parentId:t,sublayerId:s}})(a,t));if(r?.length){const e=r?.map(t=>t.id),s=r?.reduce(h,{orderedDatasets:i});return t[a].sublayerIds=e,delete t[a].sublayers,{...t,...s,orderedDatasets:i}}return{...t,orderedDatasets:i}},c=t=>{const e=(t.datasets||[]).reduce(h,{orderedDatasets:[]}),{orderedDatasets:a}=e;return delete e.orderedDatasets,{...t,mappedDatasets:e,orderedDatasets:a}},y="[interactive-map]",m={warn:(...t)=>console.warn(y,...t),error:(...t)=>console.error(y,...t)},g={globals:{visible:!0,opacity:1,opacityMode:"dataset"},key:{items:[],hasGroups:!1},mappedDatasets:{},orderedDatasets:[],actionsArray:[],menu:[],menuInitialised:!1},b=(t,e,a,s="not found")=>!!t.mappedDatasets[e]||(m.error(`${a}: Dataset with id '${e}' ${s}`),!1),f=(t,e,a)=>({...a,actionsArray:[...a.actionsArray,{method:t,parameters:e}]}),D={SET_DATASETS:(t,e)=>{const{mappedDatasets:a,orderedDatasets:s}=e;return{...t,mappedDatasets:a,orderedDatasets:s}},ADD_DATASET:(t,e)=>{const{dataset:a,mapStyle:s}=e;if(t.mappedDatasets[a.id])return m.error(`addDataset: Dataset with id '${a.id}' already exists`),t;const{mappedDatasets:i,orderedDatasets:n}=c({datasets:[a]}),o=((t,e)=>{const a=[...t.menu],s=r({datasets:[e]}),i=a.find(t=>t.groupLabel===s[0].groupLabel);return i?i.items.push(...s[0].items):a.push(...s),a})(t,a);return f("addDataset",[a.id,s],{...t,mappedDatasets:{...t.mappedDatasets,...i},orderedDatasets:[...t.orderedDatasets,...n],menu:o})},REMOVE_DATASET:(t,e)=>{const{id:a}=e;if(!b(t,a,"removeDataset"))return t;const s={...t.mappedDatasets},i=[a,...s[a]?.sublayerIds||[]];i.forEach(t=>delete s[t]);const r=t.orderedDatasets.filter(t=>!i.includes(t));return{...t,mappedDatasets:s,orderedDatasets:r,menu:n(t.menu,i)}},SET_DATASET_VISIBILITY:(t,e)=>{const{datasetId:a,visible:s}=e;return b(t,a,"setDatasetVisibility")?t.mappedDatasets[a].visible===s?t:f("applyDatasetVisibility",[a,s],{...t,mappedDatasets:{...t.mappedDatasets,[a]:{...t.mappedDatasets[a],visible:s}}}):t},SET_GLOBAL_VISIBILITY:(t,e)=>{const{visible:a}=e;return f("applyGlobalVisibility",[a],{...t,globals:{...t.globals,visible:a}})},SET_DATASET_STYLE:(t,e)=>{const{datasetId:a,styleChanges:s,mapStyle:i}=e;if(!b(t,a,"setDatasetStyle"))return t;const r={...t.mappedDatasets[a].style,...s},n={...t.mappedDatasets[a],...s,style:r};return f("applyStyle",[a,i],{...t,mappedDatasets:{...t.mappedDatasets,[a]:n}})},SET_OPACITY:(t,e)=>{const{datasetId:a,opacity:s}=e;if(!b(t,a,"setOpacity"))return t;const i={...t.mappedDatasets[a].style,opacity:s},r={...t.mappedDatasets[a],style:i};return f("applyDatasetOpacity",[a],{...t,mappedDatasets:{...t.mappedDatasets,[a]:r}})},SET_GLOBAL_OPACITY:(t,e)=>{const{opacity:a}=e;return f("applyGlobalOpacity",[],{...t,globals:{...t.globals,opacity:a}})},HIDE_FEATURES:(t,e)=>{const{datasetId:a,featureIds:s}=e;if(!b(t,a,"setFeatureVisibility - hideFeatures"))return t;const i={...t.mappedDatasets[a]},r=i.hiddenFeatures||[],n=Array.from(new Set([...r,...s]));return i.hiddenFeatures=n,f("applyFeatureFilter",[a],{...t,mappedDatasets:{...t.mappedDatasets,[a]:i}})},SHOW_FEATURES:(t,e)=>{const{datasetId:a,featureIds:s}=e;if(!b(t,a,"setFeatureVisibility - showFeatures"))return t;const i={...t.mappedDatasets[a]},r=(i.hiddenFeatures||[]).filter(t=>!s.includes(t));return i.hiddenFeatures=r.length?r:[-1],f("applyFeatureFilter",[a],{...t,mappedDatasets:{...t.mappedDatasets,[a]:i}})},REMOVE_ADAPTER_ACTIONS:(t,e)=>e?.length?{...t,actionsArray:t.actionsArray.filter(t=>!e.includes(t))}:t,SET_GLOBAL_STATE:(t,e)=>f("applyGlobalOpacity",[],{...t,globals:{...t.globals,...e}}),SET_MENU:(t,e)=>{const{menu:a}=e;return{...t,menu:a,menuInitialised:!0}}},S={APP_HIDE_PANEL:"app:hidepanel",MAP_SIZE_CHANGE:"map:sizechange",MAP_DATA_CHANGE:"map:datachange"},_=(t,e)=>!(!t||!e)&&!(t[2]<e[0]||t[0]>e[2]||t[3]<e[1]||t[1]>e[3]),I=t=>{let e=1/0,a=1/0,s=-1/0,i=-1/0;const r=(t,n)=>{var o;0===n?(o=t,e=Math.min(e,o[0]),a=Math.min(a,o[1]),s=Math.max(s,o[0]),i=Math.max(i,o[1])):t.forEach(t=>r(t,n-1))};switch(t.type){case"Point":r(t.coordinates,0);break;case"LineString":case"MultiPoint":r(t.coordinates,1);break;case"Polygon":case"MultiLineString":r(t.coordinates,2);break;case"MultiPolygon":r(t.coordinates,3);break;case"GeometryCollection":t.geometries.forEach(t=>{const r=I(t);e=Math.min(e,r[0]),a=Math.min(a,r[1]),s=Math.max(s,r[2]),i=Math.max(i,r[3])});break;default:throw new Error(`Unsupported geometry type: ${t.type}`)}return[e,a,s,i]},v=t=>({type:"FeatureCollection",features:Array.from(t.values()).map(t=>t.feature)}),A=async(t,{mapProvider:e,dynamicGeoJSON:a,onUpdate:s})=>{const{url:i,idProperty:r,transformRequest:n,maxFeatures:o,minZoom:l=0}=a,d=e.getZoom();if(d<l)return;const u=(t=>t.getBounds())(e);if(!(t.fetchedBbox&&(p=t.fetchedBbox,h=u,p&&h&&h[0]>=p[0]&&h[1]>=p[1]&&h[2]<=p[2]&&h[3]<=p[3]))){var p,h,c,y;t.currentController&&t.currentController.abort(),t.currentController=new AbortController;try{const e={bbox:u,zoom:d},l=await(async(t,e,a,s)=>{const i=a(t,e),r="string"==typeof i?{url:i}:i,{url:n,headers:o={}}=r,l=await fetch(n,{headers:o,signal:s});if(!l.ok)throw new Error(`Failed to fetch GeoJSON: ${l.status} ${l.statusText}`);const d=await l.json();if("FeatureCollection"===d.type)return d;if("Feature"===d.type)return{type:"FeatureCollection",features:[d]};if(Array.isArray(d))return{type:"FeatureCollection",features:d};throw new Error("Invalid GeoJSON response")})(i,e,n,t.currentController.signal);((t,e,a)=>{const s=Date.now();e.features.forEach(e=>{const i=((t,e)=>e?t.properties?.[e]??t.id:t.id)(e,a);null!=i?t.set(i,{feature:e,bbox:I(e.geometry),lastSeenAt:s}):console.warn("Feature missing ID, skipping:",e)})})(t.features,l,r),t.fetchedBbox=(c=t.fetchedBbox,y=u,c?[Math.min(c[0],y[0]),Math.min(c[1],y[1]),Math.max(c[2],y[2]),Math.max(c[3],y[3])]:[...y]);const p=t.features.size;((t,e,a)=>{if(!a||t.size<=1.2*a)return;const s=a,i=[],r=[];for(const[a,s]of t)_(s.bbox,e)?i.push(a):r.push({id:a,lastSeenAt:s.lastSeenAt});r.sort((t,e)=>t.lastSeenAt-e.lastSeenAt);const n=t.size-s;for(let e=0;e<n&&e<r.length;e++)t.delete(r[e].id);if(t.size>s){const e=t.size-s,a=i.map(e=>({id:e,lastSeenAt:t.get(e).lastSeenAt})).sort((t,e)=>t.lastSeenAt-e.lastSeenAt);for(let s=0;s<e&&s<a.length;s++)t.delete(a[s].id)}})(t.features,u,o),t.features.size<p&&(t.fetchedBbox=u),s(a.id,v(t.features))}catch(t){if("AbortError"===t.name)return;console.error(`Failed to fetch dynamic GeoJSON for ${a.id}:`,t)}}},C=({dynamicGeoJSON:t,mapProvider:e,onUpdate:a})=>{const s={features:new Map,fetchedBbox:null,currentController:null},i=()=>A(s,{mapProvider:e,dynamicGeoJSON:t,onUpdate:a}),r=((t,e)=>{let a;const s=(...s)=>{clearTimeout(a),a=setTimeout(()=>t(...s),e)};return s.cancel=()=>{clearTimeout(a),a=null},s})(i,200),n=()=>{r()};return e.map.on("moveend",n),i(),{destroy(){var t,a;t=e.map,a=n,(t.off||t.un).call(t,"moveend",a),r.cancel(),s.currentController&&s.currentController.abort()},clear(){s.features.clear(),s.fetchedBbox=null,a(t.id,{type:"FeatureCollection",features:[]})},refresh(){s.features.clear(),s.fetchedBbox=null,i()},getFeatureCount:()=>s.features.size,reapply(){s.features.size>0&&a(t.id,v(s.features))}}},E=async(t,e,a,s)=>{const i=await(async t=>{switch(t.name){case"MapLibreProvider":{const{default:t}=await import(/* webpackChunkName: "im-datasets-ml-adapter" */ "./im-datasets-ml-adapter.js");return t}case"EsriProvider":{const{default:t}=await import(/* webpackChunkName: "im-datasets-esri-adapter" */ "./im-datasets-esri-adapter.js");return t}case"OpenLayersProvider":{const{default:t}=await import(/* webpackChunkName: "im-datasets-ol-adapter" */ "./im-datasets-ol-adapter.js");return t}default:throw new Error(`No layer adapter available for map provider ${t.name}. Please provide a compatible layer adapter.`)}})(t);return new i(t,e,a,s)},M=({pluginConfig:t,pluginState:e})=>!1!==t.hasMenu&&(e.menuInitialised?e.menu.length>0:(t.datasets||[]).some(t=>t.showInMenu||t.sublayers?.some(t=>t.showInMenu)));const T="datasetsLayers";function w({appConfig:a,appState:s,pluginConfig:i,pluginState:n,mapState:o,mapProvider:l,services:d}){const{dispatch:u,datasetRegistry:p}=n,{eventBus:h,symbolRegistry:y,patternRegistry:m}=d,g=Boolean(l?.isBaseMapReady());!function({appConfig:a,appState:s,pluginConfig:i,pluginState:r,services:n}){const{eventBus:o,focusMap:l}=n,d=M({pluginConfig:i,pluginState:r}),u=Boolean(s.openPanels[T]),p=t(null);e(()=>{if(d||!u)return;const t=document.getElementById(`${a.id}-panel-${e=T,e?.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`);var e;const s=Boolean(t?.contains(document.activeElement));o.emit(S.APP_HIDE_PANEL,T),s&&(p.current=requestAnimationFrame(()=>l()))},[d,u]),e(()=>()=>cancelAnimationFrame(p.current),[])}({appConfig:a,appState:s,pluginConfig:i,pluginState:n,services:d});const b=t(n);b.current=n;const f=t(null),D=t=>{const e=l?.datasets;t.length&&e&&(t.forEach(({method:t,parameters:a})=>e[t](...a)),u({type:"REMOVE_ADAPTER_ACTIONS",payload:t}))};return e(()=>{if(!g)return;if(f.current)return;(async()=>{const t=await E(l,y,m,p);f.current=(({adapter:t,datasetRegistry:e,pluginConfig:a,mapStyle:s,mapProvider:i,events:n,dispatch:o,eventBus:l})=>{const{datasets:d}=a,u=new Map;a.globals&&o({type:"SET_GLOBAL_STATE",payload:a.globals});const{mappedDatasets:p,orderedDatasets:h}=c({datasets:d});t.createDataset&&e.attachCreateDataset(t.createDataset),e.attach(p,h,s);const y=r({datasets:d});l.requestOnce("menu:state",t=>e.attachMenuStateRef(t)),o({type:"SET_MENU",payload:{menu:y}}),o({type:"SET_DATASETS",payload:{mappedDatasets:p,orderedDatasets:h}}),t.init().then(()=>{e.forEachDataset(e=>{if(!e.hasDynamicGeoJSON)return;const{dynamicGeoJSON:a}=e,s=C({dynamicGeoJSON:a,mapProvider:i,onUpdate:(e,a)=>t.setData(e,a)});u.set(e.id,s)}),t.attachDynamicSources(u),l.emit("datasets:ready")});const m=()=>{t.onMapSizeChange()};l.on(n.MAP_SIZE_CHANGE,m);const g=l.emitWhenRequested("datasets:registry",e);return l.on("menu:changed",a=>{e.invalidateKeyItemsOnMenuStateChange(a),t.applyGlobalVisibility()}),{remove(){l.off(n.MAP_SIZE_CHANGE,m),g(),u.forEach(t=>t.destroy()),u.clear(),t.destroy()},refreshDataset(t){u.get(t)?.refresh()},clearDatasetCache(t){u.get(t)?.clear()},getFeatureCount:t=>u.get(t)?.getFeatureCount()??null}})({adapter:t,datasetRegistry:p,pluginConfig:i,mapStyle:o.mapStyle,mapProvider:l,events:S,dispatch:u,eventBus:h}),l.datasets=t,D(b.current.actionsArray)})()},[g]),e(()=>{p.attach(n.mappedDatasets,n.orderedDatasets),h.emit("datasets:changed")},[n.mappedDatasets,n.orderedDatasets]),e(()=>{p.attachMapStyle(o.mapStyle);const t=l?.datasets;t?.onMapStyleChange&&Promise.resolve(t.onMapStyleChange()).then(()=>{h.emit(S.MAP_DATA_CHANGE)})},[o.mapStyle]),e(()=>p.attachGlobals(n.globals),[n.globals]),e(()=>D(n.actionsArray),[n.actionsArray]),e(()=>()=>{f.current&&(f.current.remove(),f.current=null,l.datasets=null)},[]),null}const L=({pluginState:{dispatch:t}},e,a={})=>{const{datasetId:s,sublayerId:i}=a,r=i?`${s}-${i}`:s;t(r?{type:"SET_DATASET_VISIBILITY",payload:{datasetId:r,visible:e}}:{type:"SET_GLOBAL_VISIBILITY",payload:{visible:e}})},P=({menuGroupItem:t,datasetRegistry:e,onChange:i})=>{const r=e.getDataset(t.id);if(!r)return null;const n=r.isSublayer?r.parentId:r.id,o=r.isSublayer?r.id:void 0,l="im-c-datasets-layers__item govuk-checkboxes govuk-checkboxes--small"+(r.visible?"":" im-c-datasets-layers__item--checked");return a("div",{className:l,"data-module":"govuk-checkboxes",children:s("div",{className:"govuk-checkboxes__item",children:[a("input",{className:"govuk-checkboxes__input",id:r.id,"data-dataset-id":n,"data-sublayer-id":o,name:"layers",type:"checkbox",value:r.id,checked:r.isLocallyVisible,onChange:i}),a("label",{className:"im-c-datasets-layers__item-label govuk-label govuk-checkboxes__label",htmlFor:r.id,children:r.label})]})},r.id)},k=({menuGroup:t,children:e})=>{if(!t.groupLabel)return a(i,{children:e});return a("div",{className:"govuk-form-group im-c-datasets-layers-group",children:s("fieldset",{className:"im-c-datasets-layers-group__fieldset",children:[a("legend",{className:"im-c-datasets-layers-group__legend",children:a("h3",{children:t.groupLabel})}),e]})},t.id)},O=({pluginState:{dispatch:t},mapState:e},a)=>{t({type:"ADD_DATASET",payload:{dataset:a,mapStyle:e.mapStyle}})},F=({pluginState:{dispatch:t},mapProvider:e},a)=>{e.datasets?.removeDataset(a),t({type:"REMOVE_DATASET",payload:{id:a}})},x=({pluginState:{dispatch:t,datasetRegistry:e}},a,s,{datasetId:i=null}={})=>{if(i){const t=e.getDataset(i);!t||t.idProperty||t.generateIds||m.warn(`setFeatureVisibility: Dataset "${i}" has no idProperty or generateIds configured. Features may not be matched correctly. Add idProperty to match by a feature property, or add generateIds: true to use auto-generated IDs.`)}t({type:a?"SHOW_FEATURES":"HIDE_FEATURES",payload:{datasetId:i,featureIds:s}})},G=({pluginState:{dispatch:t},mapState:e},a,{datasetId:s,sublayerId:i}={})=>{t({type:"SET_DATASET_STYLE",payload:{datasetId:s=i?`${s}-${i}`:s,styleChanges:a,mapStyle:e.mapStyle}})},B=({pluginState:{datasetRegistry:t}},{datasetId:e,sublayerId:a}={})=>{e=a?`${e}-${a}`:e;const s=t.getDataset(e);return s?s.style:(m.warn(`getStyle: Dataset with id ${e} not found`),null)},R=({pluginState:{dispatch:t}},e,a={})=>{const{datasetId:s,sublayerId:i}=a,r=i?`${s}-${i}`:s;t(r?{type:"SET_OPACITY",payload:{datasetId:r,opacity:e}}:{type:"SET_GLOBAL_OPACITY",payload:{opacity:e}})},N=({pluginState:{globals:t,datasetRegistry:e}},a={})=>{const{datasetId:s,sublayerId:i}=a,r=i?`${s}-${i}`:s;if(r){const t=e.getDataset(r);return t?t.opacity??null:(m.warn(`getOpacity: Dataset with id ${r} not found`),null)}return t.opacity??null},$=({pluginState:{datasetRegistry:t},mapProvider:e},a,{datasetId:s})=>{const i=t.getDataset(s);i?i?.tiles?m.warn(`setData called on vector tile dataset "${s}" — has no effect`):e.datasets?.setData(s,a):m.warn(`setData: Dataset with id ${s} not found`)},V=({pluginState:{dispatch:t}},e)=>{const{opacityMode:a}=e,s={};let i=!1;a&&(["dataset","global","multiply"].includes(a)?(i=!0,s.opacityMode=a):m.warn(`Ignoring invalid opacityMode: ${a}. Must be one of 'dataset', 'global' or 'multiply'.`)),i?t({type:"SET_GLOBAL_STATE",payload:s}):m.warn("setGlobals: requires a valid value for opacityMode to be set")};class W{constructor(t){this.id=t.id,this.url=t.url,this.transformRequest=t.transformRequest,this.maxFeatures=t.maxFeatures,this.minZoom=t.minZoom,this.idProperty=t.idProperty,this.hiddenFeaturesIdExpression=["to-string",["get",this.idProperty]],this.sourceId=`geojson-dynamic-${this.id}`,this.source={type:"geojson",data:{type:"FeatureCollection",features:[]},...this.idProperty?{promoteId:this.idProperty}:{generateId:!0}}}}const j=(t,e,a)=>{switch(t.opacityMode){case"global":return t.opacity;case"multiply":return((t,e=1,a=1)=>Math.round(100*(e*a*t.opacity+Number.EPSILON))/100)(t,e,a);default:return((t,e,a)=>void 0===e?void 0===a?t.opacity:a:e)(t,e,a)}};class Z{constructor(t,e){this._datasetDefinition=t,this._datasetRegistry=e}get id(){return this._datasetDefinition.id}get label(){return this._datasetDefinition.label}get hasSymbol(){return!(this.hasSublayers||(t=this.style,!t?.symbol&&!t?.symbolSvgContent));var t}get hasPattern(){return!(this.hasSublayers||this.hasSymbol||(t=this.style,!t.fillPattern&&!t.fillPatternSvgContent));var t}get hasFill(){return!this.hasSublayers&&!this.hasSymbol&&(this.hasPattern||this.style?.fill&&"transparent"!==this.style?.fill)}get hasStroke(){return!this.hasSublayers&&!this.hasSymbol&&Boolean(this.style?.stroke)}get tiles(){return this._datasetDefinition.tiles}get geojson(){return this._datasetDefinition.geojson}get idProperty(){return this._datasetDefinition.idProperty}get generateIds(){return this._datasetDefinition.generateIds}get parentId(){return this._datasetDefinition.parentId}get minZoom(){return this._datasetDefinition.minZoom||this.parent?.minZoom}get maxZoom(){return this._datasetDefinition.maxZoom||this.parent?.maxZoom}get type(){return this._datasetDefinition.type||this.parent?.type}get showInKey(){const t=this._datasetDefinition.showInKey;return void 0!==t?t:this.parent?.showInKey??!1}get visibleWhen(){return void 0===this._datasetDefinition.visibleWhen?this.parent?.visibleWhen:this._datasetDefinition.visibleWhen}get groupLabel(){return this._datasetDefinition.groupLabel||this.parent?.groupLabel||this.parent?.label}get groupId(){const t=this._datasetDefinition.groupId||this.parent?.groupId;return t||(this.groupLabel?this.groupLabel.toLowerCase().replace(/\s+/g,"-"):null)}get opacity(){const t=this.style?.opacity,e=this.parent?.style?.opacity;return j(this._datasetRegistry.globals,t,e)}get hasDynamicGeoJSON(){return Boolean(this._datasetDefinition.dynamicGeoJSON)}get dynamicGeoJSON(){return new W({...this._datasetDefinition.dynamicGeoJSON,id:this.id,minZoom:this.minZoom})}get hiddenFeatures(){return this._datasetDefinition.hiddenFeatures}get hasHiddenFeatures(){return Boolean(this.hiddenFeatures?.length>0||this.parent?.hasHiddenFeatures)}get filter(){return null}get isHiddenByInheritance(){return this.isSublayer?!this.parent?.visible:!this._datasetRegistry.globals.visible}get isLocallyVisible(){return!!this.isVisible||this._datasetDefinition.visible}get visible(){return this.isSublayer?this._datasetDefinition.visible&&this.parent?.visible:this._datasetDefinition.visible&&this._datasetRegistry.globals.visible}get esriStyleLayerId(){return this._datasetDefinition.esriStyleLayerId}get visibility(){const{visible:t,visibleWhen:e}=this;return t&&e?this._datasetRegistry.isVisibleWhen(e)?"visible":"none":t?"visible":"none"}get keyVisibility(){return this.showInKey&&"visible"===this.visibility}get symbolAnchor(){return this.style?.symbolAnchor?this.style.symbolAnchor:this.parent?.symbolAnchor}get sourceLayer(){return this.isSublayer?this.parent.sourceLayer:this.tiles?this._datasetDefinition.sourceLayer:void 0}get isSublayer(){return Boolean(this._datasetDefinition.parentId)}get hasSublayers(){return this._datasetDefinition.sublayerIds?.length>0}get sublayerIds(){return this._datasetDefinition.sublayerIds}get sublayers(){const{sublayerIds:t}=this;return t?t.map(t=>this._datasetRegistry.getDataset(t)):[]}get parent(){if(this._datasetDefinition.parentId)return this._datasetRegistry.getDataset(this._datasetDefinition.parentId)}get inheritedStyle(){const t=this._datasetDefinition.style||{},e=this.parent;return e?{...e.inheritedStyle,opacity:void 0,...t}:t}get style(){return{...p(this.inheritedStyle),symbolDescription:this.symbolDescription}}get hasCustomVisualStyle(){return u(this._datasetDefinition.style||{})}get symbolDescription(){return this._datasetDefinition.style?.symbolDescription?this._datasetDefinition.style.symbolDescription:this.hasCustomVisualStyle?void 0:this.parent?this.parent.symbolDescription:o.style.symbolDescription}get patternConfigs(){const t=this.hasPattern?[this.style]:[];return this.hasSublayers?[...t,...this.sublayers.flatMap(t=>t.patternConfigs)]:t}get symbolConfigs(){const t=this.hasSymbol?[this.style]:[];return this.hasSublayers?[...t,...this.sublayers.flatMap(t=>t.symbolConfigs)]:t}get keyDefinition(){return{id:this.id,type:"dataset",label:this.label,hasSymbol:this.hasSymbol,hasPattern:this.hasPattern,style:this.style,symbolDescription:this.symbolDescription}}}class K{constructor(){this.idToDefinitionMap=new Map,this.definitionToInstanceMap=new Map}add(t){this.idToDefinitionMap.set(t.id,t._datasetDefinition),this.definitionToInstanceMap.set(t._datasetDefinition,t)}invalidateDataset(t){const e=this.idToDefinitionMap.get(t.id);[e.id,...e?.sublayerIds||[]].forEach(t=>{const e=this.idToDefinitionMap.get(t);this.definitionToInstanceMap.delete(e),this.idToDefinitionMap.delete(t)})}invalidateChangedDatasets(t){t.forEach(t=>{const e=this.idToDefinitionMap.get(t.id);if(e&&e!==t){const t=this.definitionToInstanceMap.get(e);this.invalidateDataset(t.isSublayer&&t.parent?t.parent:t)}})}getByDefinition(t){return this.definitionToInstanceMap.get(t)}}const z=(t,e={})=>{for(const[a,s]of Object.entries(t)){const t=e[a];if(!s.includes(t))return!1}return!0},H=(t,e)=>(Array.isArray(t)?t:[t]).includes(e),J={attach(t,e,a){this._datasets=t,this._orderedDatasets=e,this.attachMapStyle(a),this._invalidateChangedDatasets()},_invalidateCache(){this._definitionCache=new K},_invalidateChangedDatasets(){this._datasets?this._definitionCache.invalidateChangedDatasets(Object.values(this._datasets)):this._invalidateCache()},attachCreateDataset(t){this._createDataset=t},_createDataset:(t,e)=>((t,e)=>new Z(t,e))(t,e),attachMapStyle(t){t&&(this._mapStyle=t)},get mapStyle(){return this._mapStyle},attachGlobals(t){t&&(this._globals=t)},get globals(){return this._globals},attachMenuStateRef(t){this._menuStateRef=t},isVisibleWhen(t){return((t,{mapStyleId:e,menuState:a}={})=>{if(null==t)return!0;if("boolean"==typeof t)return t;if("object"==typeof t){for(const[s,i]of Object.entries(t)){if("mapStyleId"===s&&!H(i,e))return!1;if("menu"===s&&!z(i,a))return!1}return!0}return!0})(t,{mapStyleId:this._mapStyle?.id,menuState:this._menuStateRef?.current?.menuState})},get datasets(){return this._datasets},getDataset(t){const e=this.datasets[t];if(!e)return;const a=this._definitionCache.getByDefinition(e);if(a)return a;const s=this._createDataset(e,this);return this._definitionCache.add(s),s.isSublayer&&this.getDataset(s.parentId),s},forEach(t){this._orderedDatasets.forEach(e=>t(this.getDataset(e)))},forEachDataset(t){Object.values(this.datasets).filter(t=>!t.parentId).forEach(e=>t(this.getDataset(e.id)))},topLevelDatasets(){return Object.values(this.datasets).filter(t=>!t.parentId).map(t=>this.getDataset(t.id))},getPatternAndSymbolConfigs(){return this.topLevelDatasets().reduce((t,e)=>({...t,patternConfigs:[...t.patternConfigs,...e.patternConfigs],symbolConfigs:[...t.symbolConfigs,...e.symbolConfigs]}),{patternConfigs:[],symbolConfigs:[]})},invalidateKeyItemsOnMenuStateChange(t){t!==this._lastMenuState&&(this._lastMenuState=t,this._lastKeyItemsDatasets=null)},keyItems(){if(this.datasets===this._lastKeyItemsDatasets)return this._lastKeyItems;this._lastKeyItemsDatasets=this.datasets;const t=[],e=new Map;this.forEach(a=>{if(!a.keyVisibility)return;if(!(a.hasSublayers||a.groupId||a.groupLabel))return void t.push({type:"flat",id:a.id,keyDefinition:a.keyDefinition});const s=a.groupId,i=((a,s)=>{if(e.has(s))return e.get(s);const i={type:"group",id:s,groupLabel:a,keyDefinitions:[]};return e.set(s,i),t.push(i),i})(a.groupLabel||s||a.label,s);a.hasSublayers||i.keyDefinitions.push(a.keyDefinition)});const a=t.filter(t=>"flat"===t.type||Boolean(t.keyDefinitions?.length)),s=a.some(t=>"group"===t.type);return this._lastKeyItems={items:a,hasGroups:s},this._lastKeyItems}},U={id:"datasetsLayers",label:"Layers",mobile:{slot:"drawer",modal:!0,dismissible:!0},tablet:{slot:"left-top",dismissible:!0,exclusive:!0,width:"260px"},desktop:{slot:"left-top",modal:!1,dismissible:!0,exclusive:!0,width:"280px"},render:({pluginState:t})=>{const{menu:e=[]}=t,i=e=>{const{value:a,checked:s}=e.target;L({pluginState:t},s,{datasetId:a})},r=e.some(t=>t.groupLabel);return a("div",{className:"im-c-datasets-layers"+(r?" im-c-datasets-layers--has-groups":""),children:e.map(e=>s(k,{menuGroup:e,children:[" ",e.items.map(e=>a(P,{menuGroupItem:e,datasetRegistry:t.datasetRegistry,onChange:i},e.id))]},e.id))})}},Y={id:"datasetsLayers",label:"Layers",panelId:"datasetsLayers",excludeWhen:t=>!M(t),iconId:"layers",mobile:{slot:"top-left",showLabel:!0},tablet:{slot:"top-left",showLabel:!0},desktop:{slot:"top-left",showLabel:!0}};var q=Object.freeze({__proto__:null,createManifest:({hasMenu:t}={})=>({InitComponent:w,reducer:{initialState:{...g,datasetRegistry:Object.assign(Object.create(J),{_definitionCache:new K,_globals:{},_menuStateRef:{},_lastMenuState:{},_lastKeyItems:{}})},actions:D},panels:!1===t?[]:[U],buttons:!1===t?[]:[Y],icons:[{id:"layers",svgContent:'<path d="M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z"></path><path d="M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12"></path><path d="M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17"></path>'},{id:"key",svgContent:'<path d="M3 5h.01"/><path d="M3 12h.01"/><path d="M3 19h.01"/><path d="M8 5h13"/><path d="M8 12h13"/><path d="M8 19h13"/>'}],api:{addDataset:O,removeDataset:F,setDatasetVisibility:L,setFeatureVisibility:x,setStyle:G,getStyle:B,setOpacity:R,getOpacity:N,setData:$,setGlobals:V}})});export{Z as D,m as l,q as m};
|
|
1
|
+
import{useRef as t,useEffect as e}from"preact/compat";import{jsx as a,jsxs as s,Fragment as i}from"preact/jsx-runtime";const r=t=>{const{datasets:e=[]}=t,a=[],s=e.filter(t=>t.showInMenu||t.sublayers?.some(t=>t.showInMenu)),i=new Map;return s.forEach(t=>{if(t.sublayers?.length){const e=t.sublayers.filter(e=>t.showInMenu?!1!==e.showInMenu:e.showInMenu);if(!1===t.showInMenu&&!e.length)return;const s={id:t.id,groupLabel:t.label,visibleWhen:!0,type:"checkbox",items:e.map(e=>({id:`${t.id}-${e.id}`,label:e.label}))};0===s.items.length&&(delete s.groupLabel,s.items.push({id:t.id,label:t.label})),a.push(s)}else if(t.groupLabel){const e=i.has(t.groupLabel)?i.get(t.groupLabel):{id:t.groupLabel,groupLabel:t.groupLabel,visibleWhen:!0,type:"checkbox",items:[]};i.has(t.groupLabel)||(i.set(t.groupLabel,e),a.push(e)),e.items.push({id:t.id,label:t.label})}else a.push({visibleWhen:!0,type:"checkbox",id:t.id,items:[{id:t.id,label:t.label}]})}),a},n=(t,e)=>t.reduce((t,a)=>{const s=a.items.filter(t=>!e.includes(t.id));return s.length&&t.push({...a,items:s}),t},[]),o={minZoom:6,maxZoom:24,showInKey:!1,showInMenu:!1,visible:!0,style:{stroke:"#d4351c",strokeWidth:2,symbolDescription:"red outline"}},l=["stroke","strokeWidth","strokeDashArray","fill","fillPattern","fillPatternSvgContent","fillPatternForegroundColor","fillPatternBackgroundColor","opacity","symbolDescription","symbol","symbolSvgContent","symbolViewBox","symbolAnchor","symbolSize","symbolBackgroundColor","symbolForegroundColor","symbolHaloWidth","symbolGraphic"],d=["stroke","fill","fillPattern","fillPatternSvgContent","symbol","symbolSvgContent"],u=t=>d.some(e=>e in t),p=(t={})=>u(t)?{strokeWidth:o.style.strokeWidth,...t}:{...o.style,...t},h=(t,e)=>{const{id:a}=e,s=(t=>{!0!==t.visible&&!1!==t.visible&&(t.visible="hidden"!==t.visibility);const e={...o,...t,style:{...t.style}};return l.forEach(t=>delete e[t]),e})(e);e.parentId&&("showInKey"in e||delete s.showInKey,"showInMenu"in e||delete s.showInMenu),t[a]=s;const{orderedDatasets:i}=t;i.push(a);const r=e.sublayers?.map(t=>((t,e)=>{const a=`${t}-${e.id}`,s=e.id;return"hidden"!==e.visibility&&(e.visibility="visible"),{...e,id:a,parentId:t,sublayerId:s}})(a,t));if(r?.length){const e=r?.map(t=>t.id),s=r?.reduce(h,{orderedDatasets:i});return t[a].sublayerIds=e,delete t[a].sublayers,{...t,...s,orderedDatasets:i}}return{...t,orderedDatasets:i}},c=t=>{const e=(t.datasets||[]).reduce(h,{orderedDatasets:[]}),{orderedDatasets:a}=e;return delete e.orderedDatasets,{...t,mappedDatasets:e,orderedDatasets:a}},y="[interactive-map]",m={warn:(...t)=>console.warn(y,...t),error:(...t)=>console.error(y,...t)},g={globals:{visible:!0,opacity:1,opacityMode:"dataset"},key:{items:[],hasGroups:!1},mappedDatasets:{},orderedDatasets:[],actionsArray:[],menu:[],menuInitialised:!1},b=(t,e,a,s="not found")=>!!t.mappedDatasets[e]||(m.error(`${a}: Dataset with id '${e}' ${s}`),!1),f=(t,e,a)=>({...a,actionsArray:[...a.actionsArray,{method:t,parameters:e}]}),D={SET_DATASETS:(t,e)=>{const{mappedDatasets:a,orderedDatasets:s}=e;return{...t,mappedDatasets:a,orderedDatasets:s}},ADD_DATASET:(t,e)=>{const{dataset:a,mapStyle:s}=e;if(t.mappedDatasets[a.id])return m.error(`addDataset: Dataset with id '${a.id}' already exists`),t;const{mappedDatasets:i,orderedDatasets:n}=c({datasets:[a]}),o=((t,e)=>{const a=[...t.menu],s=r({datasets:[e]}),i=a.find(t=>t.groupLabel===s[0].groupLabel);return i?i.items.push(...s[0].items):a.push(...s),a})(t,a);return f("addDataset",[a.id,s],{...t,mappedDatasets:{...t.mappedDatasets,...i},orderedDatasets:[...t.orderedDatasets,...n],menu:o})},REMOVE_DATASET:(t,e)=>{const{id:a}=e;if(!b(t,a,"removeDataset"))return t;const s={...t.mappedDatasets},i=[a,...s[a]?.sublayerIds||[]];i.forEach(t=>delete s[t]);const r=t.orderedDatasets.filter(t=>!i.includes(t));return{...t,mappedDatasets:s,orderedDatasets:r,menu:n(t.menu,i)}},SET_DATASET_VISIBILITY:(t,e)=>{const{datasetId:a,visible:s}=e;return b(t,a,"setDatasetVisibility")?t.mappedDatasets[a].visible===s?t:f("applyDatasetVisibility",[a,s],{...t,mappedDatasets:{...t.mappedDatasets,[a]:{...t.mappedDatasets[a],visible:s}}}):t},SET_GLOBAL_VISIBILITY:(t,e)=>{const{visible:a}=e;return f("applyGlobalVisibility",[a],{...t,globals:{...t.globals,visible:a}})},SET_DATASET_STYLE:(t,e)=>{const{datasetId:a,styleChanges:s,mapStyle:i}=e;if(!b(t,a,"setDatasetStyle"))return t;const r={...t.mappedDatasets[a].style,...s},n={...t.mappedDatasets[a],...s,style:r};return f("applyStyle",[a,i],{...t,mappedDatasets:{...t.mappedDatasets,[a]:n}})},SET_OPACITY:(t,e)=>{const{datasetId:a,opacity:s}=e;if(!b(t,a,"setOpacity"))return t;const i={...t.mappedDatasets[a].style,opacity:s},r={...t.mappedDatasets[a],style:i};return f("applyDatasetOpacity",[a],{...t,mappedDatasets:{...t.mappedDatasets,[a]:r}})},SET_GLOBAL_OPACITY:(t,e)=>{const{opacity:a}=e;return f("applyGlobalOpacity",[],{...t,globals:{...t.globals,opacity:a}})},HIDE_FEATURES:(t,e)=>{const{datasetId:a,featureIds:s}=e;if(!b(t,a,"setFeatureVisibility - hideFeatures"))return t;const i={...t.mappedDatasets[a]},r=i.hiddenFeatures||[],n=Array.from(new Set([...r,...s]));return i.hiddenFeatures=n,f("applyFeatureFilter",[a],{...t,mappedDatasets:{...t.mappedDatasets,[a]:i}})},SHOW_FEATURES:(t,e)=>{const{datasetId:a,featureIds:s}=e;if(!b(t,a,"setFeatureVisibility - showFeatures"))return t;const i={...t.mappedDatasets[a]},r=(i.hiddenFeatures||[]).filter(t=>!s.includes(t));return i.hiddenFeatures=r.length?r:[-1],f("applyFeatureFilter",[a],{...t,mappedDatasets:{...t.mappedDatasets,[a]:i}})},REMOVE_ADAPTER_ACTIONS:(t,e)=>e?.length?{...t,actionsArray:t.actionsArray.filter(t=>!e.includes(t))}:t,SET_GLOBAL_STATE:(t,e)=>f("applyGlobalOpacity",[],{...t,globals:{...t.globals,...e}}),SET_MENU:(t,e)=>{const{menu:a}=e;return{...t,menu:a,menuInitialised:!0}}},S={APP_HIDE_PANEL:"app:hidepanel",MAP_SIZE_CHANGE:"map:sizechange",MAP_DATA_CHANGE:"map:datachange"},_=(t,e)=>!(!t||!e)&&!(t[2]<e[0]||t[0]>e[2]||t[3]<e[1]||t[1]>e[3]),I=t=>{let e=1/0,a=1/0,s=-1/0,i=-1/0;const r=(t,n)=>{var o;0===n?(o=t,e=Math.min(e,o[0]),a=Math.min(a,o[1]),s=Math.max(s,o[0]),i=Math.max(i,o[1])):t.forEach(t=>r(t,n-1))};switch(t.type){case"Point":r(t.coordinates,0);break;case"LineString":case"MultiPoint":r(t.coordinates,1);break;case"Polygon":case"MultiLineString":r(t.coordinates,2);break;case"MultiPolygon":r(t.coordinates,3);break;case"GeometryCollection":t.geometries.forEach(t=>{const r=I(t);e=Math.min(e,r[0]),a=Math.min(a,r[1]),s=Math.max(s,r[2]),i=Math.max(i,r[3])});break;default:throw new Error(`Unsupported geometry type: ${t.type}`)}return[e,a,s,i]},v=t=>({type:"FeatureCollection",features:Array.from(t.values()).map(t=>t.feature)}),A=async(t,{mapProvider:e,dynamicGeoJSON:a,onUpdate:s})=>{const{url:i,idProperty:r,transformRequest:n,maxFeatures:o,minZoom:l=0}=a,d=e.getZoom();if(d<l)return;const u=(t=>t.getBounds())(e);if(!(t.fetchedBbox&&(p=t.fetchedBbox,h=u,p&&h&&h[0]>=p[0]&&h[1]>=p[1]&&h[2]<=p[2]&&h[3]<=p[3]))){var p,h,c,y;t.currentController&&t.currentController.abort(),t.currentController=new AbortController;try{const e={bbox:u,zoom:d},l=await(async(t,e,a,s)=>{const i=a(t,e),r="string"==typeof i?{url:i}:i,{url:n,headers:o={}}=r,l=await fetch(n,{headers:o,signal:s});if(!l.ok)throw new Error(`Failed to fetch GeoJSON: ${l.status} ${l.statusText}`);const d=await l.json();if("FeatureCollection"===d.type)return d;if("Feature"===d.type)return{type:"FeatureCollection",features:[d]};if(Array.isArray(d))return{type:"FeatureCollection",features:d};throw new Error("Invalid GeoJSON response")})(i,e,n,t.currentController.signal);((t,e,a)=>{const s=Date.now();e.features.forEach(e=>{const i=((t,e)=>e?t.properties?.[e]??t.id:t.id)(e,a);null!=i?t.set(i,{feature:e,bbox:I(e.geometry),lastSeenAt:s}):console.warn("Feature missing ID, skipping:",e)})})(t.features,l,r),t.fetchedBbox=(c=t.fetchedBbox,y=u,c?[Math.min(c[0],y[0]),Math.min(c[1],y[1]),Math.max(c[2],y[2]),Math.max(c[3],y[3])]:[...y]);const p=t.features.size;((t,e,a)=>{if(!a||t.size<=1.2*a)return;const s=a,i=[],r=[];for(const[a,s]of t)_(s.bbox,e)?i.push(a):r.push({id:a,lastSeenAt:s.lastSeenAt});r.sort((t,e)=>t.lastSeenAt-e.lastSeenAt);const n=t.size-s;for(let e=0;e<n&&e<r.length;e++)t.delete(r[e].id);if(t.size>s){const e=t.size-s,a=i.map(e=>({id:e,lastSeenAt:t.get(e).lastSeenAt})).sort((t,e)=>t.lastSeenAt-e.lastSeenAt);for(let s=0;s<e&&s<a.length;s++)t.delete(a[s].id)}})(t.features,u,o),t.features.size<p&&(t.fetchedBbox=u),s(a.id,v(t.features))}catch(t){if("AbortError"===t.name)return;console.error(`Failed to fetch dynamic GeoJSON for ${a.id}:`,t)}}},M=({dynamicGeoJSON:t,mapProvider:e,onUpdate:a})=>{const s={features:new Map,fetchedBbox:null,currentController:null},i=()=>A(s,{mapProvider:e,dynamicGeoJSON:t,onUpdate:a}),r=((t,e)=>{let a;const s=(...s)=>{clearTimeout(a),a=setTimeout(()=>t(...s),e)};return s.cancel=()=>{clearTimeout(a),a=null},s})(i,200),n=()=>{r()};return e.map.on("moveend",n),i(),{destroy(){var t,a;t=e.map,a=n,(t.off||t.un).call(t,"moveend",a),r.cancel(),s.currentController&&s.currentController.abort()},clear(){s.features.clear(),s.fetchedBbox=null,a(t.id,{type:"FeatureCollection",features:[]})},refresh(){s.features.clear(),s.fetchedBbox=null,i()},getFeatureCount:()=>s.features.size,reapply(){s.features.size>0&&a(t.id,v(s.features))}}},E=async(t,e,a,s)=>{const i=await(async t=>{switch(t.name){case"MapLibreProvider":{const{default:t}=await import(/* webpackChunkName: "im-datasets-ml-adapter" */ "./im-datasets-ml-adapter.js");return t}case"EsriProvider":{const{default:t}=await import(/* webpackChunkName: "im-datasets-esri-adapter" */ "./im-datasets-esri-adapter.js");return t}case"OpenLayersProvider":{const{default:t}=await import(/* webpackChunkName: "im-datasets-ol-adapter" */ "./im-datasets-ol-adapter.js");return t}default:throw new Error(`No layer adapter available for map provider ${t.name}. Please provide a compatible layer adapter.`)}})(t);return new i(t,e,a,s)},C=({pluginConfig:t,pluginState:e})=>!1!==t.hasMenu&&(e.menuInitialised?e.menu.length>0:(t.datasets||[]).some(t=>t.showInMenu||t.sublayers?.some(t=>t.showInMenu))),T="datasetsLayers";function w({appState:a,pluginConfig:s,pluginState:i,mapState:n,mapProvider:o,services:l}){const{dispatch:d,datasetRegistry:u}=i,{eventBus:p,symbolRegistry:h,patternRegistry:y}=l,m=Boolean(o?.isBaseMapReady());!function({appState:t,pluginConfig:a,pluginState:s,services:i}){const{eventBus:r}=i,n=C({pluginConfig:a,pluginState:s}),o=Boolean(t.openPanels[T]);e(()=>{!n&&o&&r.emit(S.APP_HIDE_PANEL,T)},[n,o])}({appState:a,pluginConfig:s,pluginState:i,services:l});const g=t(i);g.current=i;const b=t(null),f=t=>{const e=o?.datasets;t.length&&e&&(t.forEach(({method:t,parameters:a})=>e[t](...a)),d({type:"REMOVE_ADAPTER_ACTIONS",payload:t}))};return e(()=>{if(!m)return;if(b.current)return;(async()=>{const t=await E(o,h,y,u);b.current=(({adapter:t,datasetRegistry:e,pluginConfig:a,mapStyle:s,mapProvider:i,events:n,dispatch:o,eventBus:l})=>{const{datasets:d}=a,u=new Map;a.globals&&o({type:"SET_GLOBAL_STATE",payload:a.globals});const{mappedDatasets:p,orderedDatasets:h}=c({datasets:d});t.createDataset&&e.attachCreateDataset(t.createDataset),e.attach(p,h,s);const y=r({datasets:d});l.requestOnce("menu:state",t=>e.attachMenuStateRef(t)),o({type:"SET_MENU",payload:{menu:y}}),o({type:"SET_DATASETS",payload:{mappedDatasets:p,orderedDatasets:h}}),t.init().then(()=>{e.forEachDataset(e=>{if(!e.hasDynamicGeoJSON)return;const{dynamicGeoJSON:a}=e,s=M({dynamicGeoJSON:a,mapProvider:i,onUpdate:(e,a)=>t.setData(e,a)});u.set(e.id,s)}),t.attachDynamicSources(u),l.emit("datasets:ready")});const m=()=>{t.onMapSizeChange()};l.on(n.MAP_SIZE_CHANGE,m);const g=l.emitWhenRequested("datasets:registry",e);return l.on("menu:changed",a=>{e.invalidateKeyItemsOnMenuStateChange(a),t.applyGlobalVisibility()}),{remove(){l.off(n.MAP_SIZE_CHANGE,m),g(),u.forEach(t=>t.destroy()),u.clear(),t.destroy()},refreshDataset(t){u.get(t)?.refresh()},clearDatasetCache(t){u.get(t)?.clear()},getFeatureCount:t=>u.get(t)?.getFeatureCount()??null}})({adapter:t,datasetRegistry:u,pluginConfig:s,mapStyle:n.mapStyle,mapProvider:o,events:S,dispatch:d,eventBus:p}),o.datasets=t,f(g.current.actionsArray)})()},[m]),e(()=>{u.attach(i.mappedDatasets,i.orderedDatasets),p.emit("datasets:changed")},[i.mappedDatasets,i.orderedDatasets]),e(()=>{u.attachMapStyle(n.mapStyle);const t=o?.datasets;t?.onMapStyleChange&&Promise.resolve(t.onMapStyleChange()).then(()=>{p.emit(S.MAP_DATA_CHANGE)})},[n.mapStyle]),e(()=>u.attachGlobals(i.globals),[i.globals]),e(()=>f(i.actionsArray),[i.actionsArray]),e(()=>()=>{b.current&&(b.current.remove(),b.current=null,o.datasets=null)},[]),null}const L=({pluginState:{dispatch:t}},e,a={})=>{const{datasetId:s,sublayerId:i}=a,r=i?`${s}-${i}`:s;t(r?{type:"SET_DATASET_VISIBILITY",payload:{datasetId:r,visible:e}}:{type:"SET_GLOBAL_VISIBILITY",payload:{visible:e}})},P=({menuGroupItem:t,datasetRegistry:e,onChange:i})=>{const r=e.getDataset(t.id);if(!r)return null;const n=r.isSublayer?r.parentId:r.id,o=r.isSublayer?r.id:void 0,l="im-c-datasets-layers__item govuk-checkboxes govuk-checkboxes--small"+(r.visible?"":" im-c-datasets-layers__item--checked");return a("div",{className:l,"data-module":"govuk-checkboxes",children:s("div",{className:"govuk-checkboxes__item",children:[a("input",{className:"govuk-checkboxes__input",id:r.id,"data-dataset-id":n,"data-sublayer-id":o,name:"layers",type:"checkbox",value:r.id,checked:r.isLocallyVisible,onChange:i}),a("label",{className:"im-c-datasets-layers__item-label govuk-label govuk-checkboxes__label",htmlFor:r.id,children:r.label})]})},r.id)},k=({menuGroup:t,children:e})=>{if(!t.groupLabel)return a(i,{children:e});return a("div",{className:"govuk-form-group im-c-datasets-layers-group",children:s("fieldset",{className:"im-c-datasets-layers-group__fieldset",children:[a("legend",{className:"im-c-datasets-layers-group__legend",children:a("h3",{children:t.groupLabel})}),e]})},t.id)},O=({pluginState:{dispatch:t},mapState:e},a)=>{t({type:"ADD_DATASET",payload:{dataset:a,mapStyle:e.mapStyle}})},x=({pluginState:{dispatch:t},mapProvider:e},a)=>{e.datasets?.removeDataset(a),t({type:"REMOVE_DATASET",payload:{id:a}})},F=({pluginState:{dispatch:t,datasetRegistry:e}},a,s,{datasetId:i=null}={})=>{if(i){const t=e.getDataset(i);!t||t.idProperty||t.generateIds||m.warn(`setFeatureVisibility: Dataset "${i}" has no idProperty or generateIds configured. Features may not be matched correctly. Add idProperty to match by a feature property, or add generateIds: true to use auto-generated IDs.`)}t({type:a?"SHOW_FEATURES":"HIDE_FEATURES",payload:{datasetId:i,featureIds:s}})},G=({pluginState:{dispatch:t},mapState:e},a,{datasetId:s,sublayerId:i}={})=>{t({type:"SET_DATASET_STYLE",payload:{datasetId:s=i?`${s}-${i}`:s,styleChanges:a,mapStyle:e.mapStyle}})},R=({pluginState:{datasetRegistry:t}},{datasetId:e,sublayerId:a}={})=>{e=a?`${e}-${a}`:e;const s=t.getDataset(e);return s?s.style:(m.warn(`getStyle: Dataset with id ${e} not found`),null)},B=({pluginState:{dispatch:t}},e,a={})=>{const{datasetId:s,sublayerId:i}=a,r=i?`${s}-${i}`:s;t(r?{type:"SET_OPACITY",payload:{datasetId:r,opacity:e}}:{type:"SET_GLOBAL_OPACITY",payload:{opacity:e}})},N=({pluginState:{globals:t,datasetRegistry:e}},a={})=>{const{datasetId:s,sublayerId:i}=a,r=i?`${s}-${i}`:s;if(r){const t=e.getDataset(r);return t?t.opacity??null:(m.warn(`getOpacity: Dataset with id ${r} not found`),null)}return t.opacity??null},$=({pluginState:{datasetRegistry:t},mapProvider:e},a,{datasetId:s})=>{const i=t.getDataset(s);i?i?.tiles?m.warn(`setData called on vector tile dataset "${s}" — has no effect`):e.datasets?.setData(s,a):m.warn(`setData: Dataset with id ${s} not found`)},V=({pluginState:{dispatch:t}},e)=>{const{opacityMode:a}=e,s={};let i=!1;a&&(["dataset","global","multiply"].includes(a)?(i=!0,s.opacityMode=a):m.warn(`Ignoring invalid opacityMode: ${a}. Must be one of 'dataset', 'global' or 'multiply'.`)),i?t({type:"SET_GLOBAL_STATE",payload:s}):m.warn("setGlobals: requires a valid value for opacityMode to be set")};class W{constructor(t){this.id=t.id,this.url=t.url,this.transformRequest=t.transformRequest,this.maxFeatures=t.maxFeatures,this.minZoom=t.minZoom,this.idProperty=t.idProperty,this.hiddenFeaturesIdExpression=["to-string",["get",this.idProperty]],this.sourceId=`geojson-dynamic-${this.id}`,this.source={type:"geojson",data:{type:"FeatureCollection",features:[]},...this.idProperty?{promoteId:this.idProperty}:{generateId:!0}}}}const j=(t,e,a)=>{switch(t.opacityMode){case"global":return t.opacity;case"multiply":return((t,e=1,a=1)=>Math.round(100*(e*a*t.opacity+Number.EPSILON))/100)(t,e,a);default:return((t,e,a)=>void 0===e?void 0===a?t.opacity:a:e)(t,e,a)}};class Z{constructor(t,e){this._datasetDefinition=t,this._datasetRegistry=e}get id(){return this._datasetDefinition.id}get label(){return this._datasetDefinition.label}get hasSymbol(){return!(this.hasSublayers||(t=this.style,!t?.symbol&&!t?.symbolSvgContent));var t}get hasPattern(){return!(this.hasSublayers||this.hasSymbol||(t=this.style,!t.fillPattern&&!t.fillPatternSvgContent));var t}get hasFill(){return!this.hasSublayers&&!this.hasSymbol&&(this.hasPattern||this.style?.fill&&"transparent"!==this.style?.fill)}get hasStroke(){return!this.hasSublayers&&!this.hasSymbol&&Boolean(this.style?.stroke)}get tiles(){return this._datasetDefinition.tiles}get geojson(){return this._datasetDefinition.geojson}get idProperty(){return this._datasetDefinition.idProperty}get generateIds(){return this._datasetDefinition.generateIds}get parentId(){return this._datasetDefinition.parentId}get minZoom(){return this._datasetDefinition.minZoom||this.parent?.minZoom}get maxZoom(){return this._datasetDefinition.maxZoom||this.parent?.maxZoom}get type(){return this._datasetDefinition.type||this.parent?.type}get showInKey(){const t=this._datasetDefinition.showInKey;return void 0!==t?t:this.parent?.showInKey??!1}get visibleWhen(){return void 0===this._datasetDefinition.visibleWhen?this.parent?.visibleWhen:this._datasetDefinition.visibleWhen}get groupLabel(){return this._datasetDefinition.groupLabel||this.parent?.groupLabel||this.parent?.label}get groupId(){const t=this._datasetDefinition.groupId||this.parent?.groupId;return t||(this.groupLabel?this.groupLabel.toLowerCase().replace(/\s+/g,"-"):null)}get opacity(){const t=this.style?.opacity,e=this.parent?.style?.opacity;return j(this._datasetRegistry.globals,t,e)}get hasDynamicGeoJSON(){return Boolean(this._datasetDefinition.dynamicGeoJSON)}get dynamicGeoJSON(){return new W({...this._datasetDefinition.dynamicGeoJSON,id:this.id,minZoom:this.minZoom})}get hiddenFeatures(){return this._datasetDefinition.hiddenFeatures}get hasHiddenFeatures(){return Boolean(this.hiddenFeatures?.length>0||this.parent?.hasHiddenFeatures)}get filter(){return null}get isHiddenByInheritance(){return this.isSublayer?!this.parent?.visible:!this._datasetRegistry.globals.visible}get isLocallyVisible(){return!!this.isVisible||this._datasetDefinition.visible}get visible(){return this.isSublayer?this._datasetDefinition.visible&&this.parent?.visible:this._datasetDefinition.visible&&this._datasetRegistry.globals.visible}get esriStyleLayerId(){return this._datasetDefinition.esriStyleLayerId}get visibility(){const{visible:t,visibleWhen:e}=this;return t&&e?this._datasetRegistry.isVisibleWhen(e)?"visible":"none":t?"visible":"none"}get keyVisibility(){return this.showInKey&&"visible"===this.visibility}get symbolAnchor(){return this.style?.symbolAnchor?this.style.symbolAnchor:this.parent?.symbolAnchor}get sourceLayer(){return this.isSublayer?this.parent.sourceLayer:this.tiles?this._datasetDefinition.sourceLayer:void 0}get isSublayer(){return Boolean(this._datasetDefinition.parentId)}get hasSublayers(){return this._datasetDefinition.sublayerIds?.length>0}get sublayerIds(){return this._datasetDefinition.sublayerIds}get sublayers(){const{sublayerIds:t}=this;return t?t.map(t=>this._datasetRegistry.getDataset(t)):[]}get parent(){if(this._datasetDefinition.parentId)return this._datasetRegistry.getDataset(this._datasetDefinition.parentId)}get inheritedStyle(){const t=this._datasetDefinition.style||{},e=this.parent;return e?{...e.inheritedStyle,opacity:void 0,...t}:t}get style(){return{...p(this.inheritedStyle),symbolDescription:this.symbolDescription}}get hasCustomVisualStyle(){return u(this._datasetDefinition.style||{})}get symbolDescription(){return this._datasetDefinition.style?.symbolDescription?this._datasetDefinition.style.symbolDescription:this.hasCustomVisualStyle?void 0:this.parent?this.parent.symbolDescription:o.style.symbolDescription}get patternConfigs(){const t=this.hasPattern?[this.style]:[];return this.hasSublayers?[...t,...this.sublayers.flatMap(t=>t.patternConfigs)]:t}get symbolConfigs(){const t=this.hasSymbol?[this.style]:[];return this.hasSublayers?[...t,...this.sublayers.flatMap(t=>t.symbolConfigs)]:t}get keyDefinition(){return{id:this.id,type:"dataset",label:this.label,hasSymbol:this.hasSymbol,hasPattern:this.hasPattern,style:this.style,symbolDescription:this.symbolDescription}}}class K{constructor(){this.idToDefinitionMap=new Map,this.definitionToInstanceMap=new Map}add(t){this.idToDefinitionMap.set(t.id,t._datasetDefinition),this.definitionToInstanceMap.set(t._datasetDefinition,t)}invalidateDataset(t){const e=this.idToDefinitionMap.get(t.id);[e.id,...e?.sublayerIds||[]].forEach(t=>{const e=this.idToDefinitionMap.get(t);this.definitionToInstanceMap.delete(e),this.idToDefinitionMap.delete(t)})}invalidateChangedDatasets(t){t.forEach(t=>{const e=this.idToDefinitionMap.get(t.id);if(e&&e!==t){const t=this.definitionToInstanceMap.get(e);this.invalidateDataset(t.isSublayer&&t.parent?t.parent:t)}})}getByDefinition(t){return this.definitionToInstanceMap.get(t)}}const H=(t,e={})=>{for(const[a,s]of Object.entries(t)){const t=e[a];if(!s.includes(t))return!1}return!0},z=(t,e)=>(Array.isArray(t)?t:[t]).includes(e),J={attach(t,e,a){this._datasets=t,this._orderedDatasets=e,this.attachMapStyle(a),this._invalidateChangedDatasets()},_invalidateCache(){this._definitionCache=new K},_invalidateChangedDatasets(){this._datasets?this._definitionCache.invalidateChangedDatasets(Object.values(this._datasets)):this._invalidateCache()},attachCreateDataset(t){this._createDataset=t},_createDataset:(t,e)=>((t,e)=>new Z(t,e))(t,e),attachMapStyle(t){t&&(this._mapStyle=t)},get mapStyle(){return this._mapStyle},attachGlobals(t){t&&(this._globals=t)},get globals(){return this._globals},attachMenuStateRef(t){this._menuStateRef=t},isVisibleWhen(t){return((t,{mapStyleId:e,menuState:a}={})=>{if(null==t)return!0;if("boolean"==typeof t)return t;if("object"==typeof t){for(const[s,i]of Object.entries(t)){if("mapStyleId"===s&&!z(i,e))return!1;if("menu"===s&&!H(i,a))return!1}return!0}return!0})(t,{mapStyleId:this._mapStyle?.id,menuState:this._menuStateRef?.current?.menuState})},get datasets(){return this._datasets},getDataset(t){const e=this.datasets[t];if(!e)return;const a=this._definitionCache.getByDefinition(e);if(a)return a;const s=this._createDataset(e,this);return this._definitionCache.add(s),s.isSublayer&&this.getDataset(s.parentId),s},forEach(t){this._orderedDatasets.forEach(e=>t(this.getDataset(e)))},forEachDataset(t){Object.values(this.datasets).filter(t=>!t.parentId).forEach(e=>t(this.getDataset(e.id)))},topLevelDatasets(){return Object.values(this.datasets).filter(t=>!t.parentId).map(t=>this.getDataset(t.id))},getPatternAndSymbolConfigs(){return this.topLevelDatasets().reduce((t,e)=>({...t,patternConfigs:[...t.patternConfigs,...e.patternConfigs],symbolConfigs:[...t.symbolConfigs,...e.symbolConfigs]}),{patternConfigs:[],symbolConfigs:[]})},invalidateKeyItemsOnMenuStateChange(t){t!==this._lastMenuState&&(this._lastMenuState=t,this._lastKeyItemsDatasets=null)},keyItems(){if(this.datasets===this._lastKeyItemsDatasets)return this._lastKeyItems;this._lastKeyItemsDatasets=this.datasets;const t=[],e=new Map;this.forEach(a=>{if(!a.keyVisibility)return;if(!(a.hasSublayers||a.groupId||a.groupLabel))return void t.push({type:"flat",id:a.id,keyDefinition:a.keyDefinition});const s=a.groupId,i=((a,s)=>{if(e.has(s))return e.get(s);const i={type:"group",id:s,groupLabel:a,keyDefinitions:[]};return e.set(s,i),t.push(i),i})(a.groupLabel||s||a.label,s);a.hasSublayers||i.keyDefinitions.push(a.keyDefinition)});const a=t.filter(t=>"flat"===t.type||Boolean(t.keyDefinitions?.length)),s=a.some(t=>"group"===t.type);return this._lastKeyItems={items:a,hasGroups:s},this._lastKeyItems}},U={id:"datasetsLayers",label:"Layers",mobile:{slot:"drawer",modal:!0,dismissible:!0},tablet:{slot:"left-top",dismissible:!0,exclusive:!0,width:"260px"},desktop:{slot:"left-top",modal:!1,dismissible:!0,exclusive:!0,width:"280px"},render:({pluginState:t})=>{const{menu:e=[]}=t,i=e=>{const{value:a,checked:s}=e.target;L({pluginState:t},s,{datasetId:a})},r=e.some(t=>t.groupLabel);return a("div",{className:"im-c-datasets-layers"+(r?" im-c-datasets-layers--has-groups":""),children:e.map(e=>s(k,{menuGroup:e,children:[" ",e.items.map(e=>a(P,{menuGroupItem:e,datasetRegistry:t.datasetRegistry,onChange:i},e.id))]},e.id))})}},Y={id:"datasetsLayers",label:"Layers",panelId:"datasetsLayers",excludeWhen:t=>!C(t),iconId:"layers",mobile:{slot:"top-left",showLabel:!0},tablet:{slot:"top-left",showLabel:!0},desktop:{slot:"top-left",showLabel:!0}};var q=Object.freeze({__proto__:null,createManifest:({hasMenu:t}={})=>({InitComponent:w,reducer:{initialState:{...g,datasetRegistry:Object.assign(Object.create(J),{_definitionCache:new K,_globals:{},_menuStateRef:{},_lastMenuState:{},_lastKeyItems:{}})},actions:D},panels:!1===t?[]:[U],buttons:!1===t?[]:[Y],icons:[{id:"layers",svgContent:'<path d="M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z"></path><path d="M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12"></path><path d="M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17"></path>'},{id:"key",svgContent:'<path d="M3 5h.01"/><path d="M3 12h.01"/><path d="M3 19h.01"/><path d="M8 5h13"/><path d="M8 12h13"/><path d="M8 19h13"/>'}],api:{addDataset:O,removeDataset:x,setDatasetVisibility:L,setFeatureVisibility:F,setStyle:G,getStyle:R,setOpacity:B,getOpacity:N,setData:$,setGlobals:V}})});export{Z as D,m as l,q as m};
|