@florasync/leaflet-geokit 0.8.2 → 0.9.0

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.
Files changed (57) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +140 -11
  3. package/dist/django/index.js +8999 -5044
  4. package/dist/django/index.js.map +1 -1
  5. package/dist/leaflet-geokit.es.js +21508 -5914
  6. package/dist/leaflet-geokit.es.js.map +1 -1
  7. package/dist/leaflet-geokit.external.es.js +18022 -2425
  8. package/dist/leaflet-geokit.external.es.js.map +1 -1
  9. package/dist/leaflet-geokit.umd.js +270 -19
  10. package/dist/leaflet-geokit.umd.js.map +1 -1
  11. package/dist/preact/index-DCKj0r6a.js +8545 -0
  12. package/dist/preact/index-DCKj0r6a.js.map +1 -0
  13. package/dist/preact/index.js +1 -1
  14. package/dist/preact-bundled/index.js +9001 -5036
  15. package/dist/preact-bundled/index.js.map +1 -1
  16. package/dist/react/index-DCKj0r6a.js +8545 -0
  17. package/dist/react/index-DCKj0r6a.js.map +1 -0
  18. package/dist/react/index.js +1 -1
  19. package/dist/react-bundled/index.js +9043 -5078
  20. package/dist/react-bundled/index.js.map +1 -1
  21. package/dist/types/components/LeafletDrawMapElement.d.ts +40 -1
  22. package/dist/types/external.d.ts +6 -0
  23. package/dist/types/index.d.ts +6 -0
  24. package/dist/types/lib/LayerRegistry.d.ts +19 -0
  25. package/dist/types/lib/MapController.d.ts +91 -1
  26. package/dist/types/lib/draw/L.Draw.Move.d.ts +1 -0
  27. package/dist/types/lib/draw/move-pointer.d.ts +12 -0
  28. package/dist/types/lib/layer-cake/LayerCakeManager.d.ts +9 -1
  29. package/dist/types/lib/layer-style-panel.d.ts +3 -0
  30. package/dist/types/lib/providers.d.ts +64 -0
  31. package/dist/types/lib/snapping.d.ts +30 -0
  32. package/dist/types/lib/tool-buttons.d.ts +2 -0
  33. package/dist/types/lib/tool-capabilities.d.ts +27 -0
  34. package/dist/types/lib/toolbar-accessibility.d.ts +3 -0
  35. package/dist/types/lib/toolbar-layout.d.ts +14 -0
  36. package/dist/types/lib/toolbar-styles.d.ts +2 -0
  37. package/dist/types/types/events.d.ts +14 -0
  38. package/dist/types/types/layers.d.ts +65 -0
  39. package/dist/types/types/public.d.ts +157 -2
  40. package/dist/types/utils/geojson-pipeline.d.ts +51 -0
  41. package/dist/types/utils/geojson.d.ts +15 -2
  42. package/dist/types/utils/grower-geometry.d.ts +107 -0
  43. package/docs/accessibility.md +142 -0
  44. package/docs/geojson-pipelines.md +145 -0
  45. package/docs/google-maps-adapter-spike.md +77 -0
  46. package/docs/grower-geometry.md +237 -0
  47. package/docs/layers.md +136 -0
  48. package/docs/providers.md +191 -0
  49. package/docs/snapping-and-measurements.md +42 -0
  50. package/docs/tool-capabilities.md +131 -0
  51. package/docs/tool-lifecycle.md +124 -0
  52. package/docs/toolbar-styling.md +118 -0
  53. package/package.json +24 -3
  54. package/dist/preact/index-DCGBWrrm.js +0 -4580
  55. package/dist/preact/index-DCGBWrrm.js.map +0 -1
  56. package/dist/react/index-DCGBWrrm.js +0 -4580
  57. package/dist/react/index-DCGBWrrm.js.map +0 -1
@@ -0,0 +1,191 @@
1
+ # Provider abstraction v2
2
+
3
+ ## Contents
4
+
5
+ - [Compatibility and boundary](#compatibility-and-boundary)
6
+ - [Public API](#public-api)
7
+ - [MapLibre and PMTiles execution path](#maplibre-and-pmtiles-execution-path)
8
+ - [Capability diagnostics](#capability-diagnostics)
9
+ - [Security and vendor independence](#security-and-vendor-independence)
10
+ - [Verification and limitations](#verification-and-limitations)
11
+
12
+ ## Compatibility and boundary
13
+
14
+ Implemented against package version 0.8.3. Leaflet + OSM remains the default;
15
+ no vendor SDK, paid account, or new runtime dependency is added.
16
+
17
+ The existing `tile-provider="osm"`, `tile-provider="here"`, `tile-style`,
18
+ `api-key` / `here-api-key`, and custom `tile-url` / `tile-attribution` paths
19
+ remain intact. Custom URLs use `tile-url`, not a new `tile-provider="custom"`
20
+ identifier. Clear `tileProvider` to use a custom URL.
21
+
22
+ Three separate ports are declared in `src/lib/providers.ts`:
23
+
24
+ 1. `RasterTileProvider`: resolves a URL template and tile options. The legacy
25
+ OSM/HERE factory remains the source of truth; custom URLs have their own factory.
26
+ 2. `VectorBasemapProvider`: creates a fresh, unmounted Leaflet layer through an
27
+ injected renderer bridge. GeoKit retains map ownership and existing draw tools.
28
+ 3. `DrawEngineAdapter<Context, Document, Command>`: attach/read/write/execute/dispose
29
+ contract for a future draw-engine replacement. This is a **design port**, not
30
+ a claim that Leaflet.draw has been refactored or native MapLibre/Google drawing
31
+ is implemented. Current drawing and completed irrigation work are reused as-is.
32
+
33
+ Renderer-specific dependencies belong outside core. A native map renderer swap
34
+ would need a draw adapter implementing GeoJSON and public tool lifecycle parity.
35
+ Do not mistake the basemap seam for that much larger project.
36
+
37
+ ## Public API
38
+
39
+ Both root and `/external` entrypoints export the provider contracts and factories:
40
+
41
+ - `createRasterProvider({ provider: "osm" | "here", ... })`
42
+ - `createCustomRasterProvider({ urlTemplate, attribution, ... })`
43
+ - `createMapLibreBasemapAdapter({ createLayer, attribution, offline?, apiKey? })`
44
+ - `getProviderDiagnostics(provider, attribution)` (pure configuration report)
45
+
46
+ The existing element gains:
47
+
48
+ - `setBasemapAdapter(adapter)` after `ready`: replace only the basemap.
49
+ - `setBasemapAdapter(null)`: restore the current raster attributes/properties.
50
+ - `getProviderDiagnostics()`: detached configuration snapshot, or null before
51
+ initialization / after disconnect.
52
+
53
+ The adapter's layer must clean up renderer workers, event handlers and resources
54
+ in Leaflet `onRemove`. GeoKit removes it on swap and map destruction. Return a
55
+ fresh layer each time; mounted/reused layers are rejected. A synchronous vector
56
+ mount failure leaves the previous basemap active. Missing required attribution
57
+ is rejected before mounting. Async renderer load errors are the optional bridge's
58
+ responsibility; restore `null` explicitly if the host wants raster fallback.
59
+
60
+ Existing provider attributes override an active adapter when changed. Reconnect
61
+ restores raster configuration; reapply the adapter after readiness. Geometry,
62
+ feature IDs, existing draw controls, read-only state and public tool events remain
63
+ owned by GeoKit. `tile-provider-changed` reports `provider: "adapter"`; tool
64
+ capabilities report `requested/active: "adapter"` without vendor configuration.
65
+
66
+ ## MapLibre and PMTiles execution path
67
+
68
+ This release ships a **dependency-injected feasibility shim**, not a production
69
+ WebGL renderer. The next optional adapter package can use the existing public
70
+ `setBasemapAdapter` method without changing web component consumers.
71
+
72
+ Host-side experiment (not installed by this slice):
73
+
74
+ 1. Create a separate adapter/example package. Select and pin mutually compatible
75
+ `leaflet`, `maplibre-gl`, `@maplibre/maplibre-gl-leaflet`, and `pmtiles` versions.
76
+ The current upstream bridge documentation uses a named `maplibreGL` export;
77
+ older bridge versions use different registration patterns. Recheck the selected
78
+ release, rather than copying a historical global `L.maplibreGL` call.
79
+ 2. Use GeoKit's external entrypoint and one shared Leaflet instance. Load Leaflet,
80
+ draw and MapLibre styles, configure MapLibre's worker/CSP requirements, and
81
+ supply `leafletInstance` before connecting the element.
82
+ 3. Register PMTiles once per host application. Feed the bridge a style whose source
83
+ is `type: "vector", url: "pmtiles://https://your-host/region.pmtiles"`.
84
+ PMTiles is a tile archive transport, not a renderer; it also supports raster
85
+ archives. This vector bridge contract describes the rendering path, not every
86
+ source inside a MapLibre style.
87
+ 4. Wrap the bridge factory in the shipped shim:
88
+
89
+ ```ts
90
+ import { maplibreGL } from "@maplibre/maplibre-gl-leaflet";
91
+ import maplibregl from "maplibre-gl";
92
+ import { Protocol } from "pmtiles";
93
+ import { createMapLibreBasemapAdapter } from "@florasync/leaflet-geokit/external";
94
+
95
+ // Host initialization: once, using the SAME MapLibre module as the bridge.
96
+ const protocol = new Protocol();
97
+ maplibregl.addProtocol("pmtiles", protocol.tile);
98
+
99
+ // After GeoKit ready; /maps/style.json contains the PMTiles source.
100
+ mapElement.setBasemapAdapter(
101
+ createMapLibreBasemapAdapter({
102
+ createLayer: () => maplibreGL({ style: "/maps/style.json" }),
103
+ attribution: "Your licensed dataset attribution",
104
+ offline: "host-managed",
105
+ apiKey: "none",
106
+ }),
107
+ );
108
+
109
+ // Remove all maps/bridges BEFORE host-global protocol teardown.
110
+ mapElement.setBasemapAdapter(null);
111
+ maplibregl.removeProtocol("pmtiles");
112
+ ```
113
+
114
+ This recipe is sourced from upstream APIs, but the optional packages and actual
115
+ archive rendering are **not exercised by this slice**. Before production promotion:
116
+
117
+ - Verify HTTP range requests, CORS, archive content type, source-layer names,
118
+ fonts, sprites and licensing with an owned fixture archive.
119
+ - Verify offline mode with network disabled and all required assets provisioned.
120
+ `host-managed` declares potential, not a cache implementation or permission.
121
+ - Exercise pan/zoom, high-DPI, touch, resize, WebGL loss, worker/CSP failures,
122
+ renderer error fallback, repeated swaps and multiple simultaneous maps.
123
+ - Keep drawing above the basemap and pointer events with Leaflet. The upstream
124
+ bridge has no pitch/rotation support and recommends minZoom 1 plus bounds
125
+ restrictions to avoid renderer synchronization issues. Test those explicitly.
126
+ - Confirm no duplicate Leaflet/MapLibre module instances and no worker/listener
127
+ leaks on removal. Do not remove a global PMTiles protocol still used by another map.
128
+
129
+ Sources:
130
+ [MapLibre Leaflet bridge](https://github.com/maplibre/maplibre-gl-leaflet),
131
+ [PMTiles protocol integration](https://docs.protomaps.com/pmtiles/maplibre).
132
+
133
+ ## Capability diagnostics
134
+
135
+ Reports contain only: `kind`, `attribution`, `attributionRequired`, `offline`,
136
+ `apiKey`, `drawing`, `scope`. No URLs, keys, style JSON, attribution HTML, arbitrary
137
+ error payloads or vendor metadata are returned. `scope: "configuration"` explicitly
138
+ means this is not a tile-load health, key-validity or renderer-readiness probe.
139
+ Use existing provider/status events for runtime failures.
140
+
141
+ | Path | Kind | API key | Offline | Drawing |
142
+ | ---------------- | ------ | ----------------------- | ------------------ | ------------ |
143
+ | OSM public tiles | raster | none | unsupported | leaflet-draw |
144
+ | HERE built-in | raster | required | unsupported | leaflet-draw |
145
+ | Custom tile URL | raster | host-defined | unknown | leaflet-draw |
146
+ | MapLibre shim | vector | host-defined by default | unknown by default | leaflet-draw |
147
+
148
+ Attribution is `present` or `missing`, not a legal-compliance validation. Hosts
149
+ must provide the required data/vendor notices even for offline maps. Missing
150
+ attribution on a legacy custom URL is reported, not a breaking rejection.
151
+ Capability declarations are trusted host configuration, not telemetry evidence.
152
+
153
+ ## Security and vendor independence
154
+
155
+ - Never put server credentials, signing secrets, service-account material or
156
+ unrestricted paid-vendor keys into HTML, attributes, browser bundles, URLs,
157
+ diagnostics, screenshots, logs or exported GeoJSON. A key passed through a JS
158
+ property instead of an attribute is **still visible to the browser**.
159
+ - Existing HERE browser key support is compatibility, not the blessed production
160
+ path. Use a vendor-approved server-side gateway with application authentication,
161
+ rate limits and quotas when that product permits it. A proxy must not become an
162
+ open paid API relay, and cannot bypass vendor licensing or conceal keys required
163
+ by a browser SDK. See [Google adapter spike](google-maps-adapter-spike.md).
164
+ - Some SDKs necessarily use public browser identifiers. Such an optional deployment
165
+ requires an explicit security/billing decision, origin + API restrictions,
166
+ separate environments, usage monitoring, quotas and a revocation plan. These
167
+ controls reduce abuse; they do not turn browser identifiers into secrets.
168
+ - Attribution is trusted HTML passed to Leaflet. Sanitize remote/untrusted inputs.
169
+ Bridge code, style sources, worker URLs and tile URLs are trusted host input;
170
+ apply CSP/allowlists and avoid sending private grower data to an unapproved vendor.
171
+ - No automatic paid fallback, provisioning, billing integration or FloraSync API
172
+ wiring. Keep user data in GeoJSON with stable IDs and retain a tested OSM/custom
173
+ path. A commercial style or archive license must not trap user-authored geometry.
174
+ - Public OSM tiles are not an offline/bulk-download service. Self-host appropriately
175
+ licensed data for offline deployments; offline capability is not vendor permission.
176
+
177
+ ## Verification and limitations
178
+
179
+ ```sh
180
+ npm run test:unit:focused -- tests/providers.spec.ts tests/tile-provider-factory.spec.ts tests/component-tile-provider.spec.ts tests/map-controller.spec.ts
181
+ npx playwright test -c playwright.providers.config.ts
182
+ npm run typecheck
183
+ npm run build
184
+ ```
185
+
186
+ The Chromium test uses the existing irrigation harness and real Leaflet/Draw.
187
+ External raster requests are intercepted with deterministic image fixtures; HERE
188
+ credentials and service access are not tested. The vector fixture is deliberately
189
+ an injected Leaflet layer, not an imitation MapLibre renderer. It proves the shim
190
+ boundary, attribution, diagnostics, public switching and real pointer drawing with
191
+ feature preservation. Actual WebGL/PMTiles is the optional follow-on gate above.
@@ -0,0 +1,42 @@
1
+ # Snapping and live measurements
2
+
3
+ Snapping is opt-in and does not change existing maps. Set the web component
4
+ property before or after connection:
5
+
6
+ ```ts
7
+ map.snapping = {
8
+ enabled: true,
9
+ modes: ["vertex", "edge", "grid", "guide"],
10
+ tolerancePx: 12,
11
+ gridSizeMeters: 1,
12
+ gridOrigin: [0, 0], // [longitude, latitude]
13
+ };
14
+ map.measurementOverlay = { enabled: true, autoScale: true };
15
+ ```
16
+
17
+ Candidates are compared in rendered screen pixels, which keeps the tolerance
18
+ consistent across zoom levels and desktop/touch input. `gridSizeMeters` is a
19
+ physical WGS84 spacing. Grid nodes are stable relative to the fixed
20
+ `gridOrigin` (`[longitude, latitude]`, default `[0, 0]`): latitude is
21
+ quantized by ellipsoidal meridian distance, while longitude uses the WGS84
22
+ parallel scale at the snapped latitude. This keeps adjacent nodes one meter
23
+ apart at realistic latitudes, including 45°, rather than treating longitude
24
+ degrees as latitude degrees.
25
+
26
+ Grid coordinates must remain in WGS84 longitude/latitude ranges, and grid
27
+ snapping is available inside ±89.9° latitude. The default origin is not moved
28
+ to the pointer, so repeated calls produce the same node. Antimeridian wrapping,
29
+ polar coordinates, CRS reprojection, and survey/machine-control accuracy are
30
+ outside this contract; use a local origin and a suitable cell size for
31
+ ordinary editing and planning.
32
+
33
+ Visible registered layers are the only guide sources. Hidden, measurement, and
34
+ currently edited features are excluded. A small marker and status label
35
+ identify the active snap. All listeners and feedback layers are removed on
36
+ cancellation, reconfiguration, and destroy.
37
+
38
+ The measurement overlay uses the same `measurementSystem` state as the ruler.
39
+ `setMeasurementUnits("metric" | "imperial")` refreshes an active overlay while
40
+ retaining the existing ruler behavior. Length, perimeter, and area are derived
41
+ with the exported grower measurement helpers and update while a shape is drawn
42
+ or a vertex is dragged.
@@ -0,0 +1,131 @@
1
+ # Tool capabilities and external controls
2
+
3
+ `map.getToolCapabilities()` synchronously returns a detached `ToolCapabilities`
4
+ snapshot. It is safe before connection (tools report `unavailable/not_ready`).
5
+ Subscribe on the element or a composed ancestor to
6
+ `leaflet-geokit:tool-capabilities-changed`; its `detail` has exactly the same
7
+ shape. Notifications are change-deduplicated; controller changes within one
8
+ microtask are coalesced. Always read an initial snapshot after subscribing.
9
+
10
+ ## Snapshot contract
11
+
12
+ `tools` is keyed by every existing `ToolButtonName`: polygon, polyline, rectangle,
13
+ circle, marker, layerCake, move, select, edit, delete, ruler,
14
+ measurementSettings, layerStyle, and save. Each entry contains:
15
+
16
+ - `state`: `enabled`, `disabled` (a prerequisite or host UI restriction), or
17
+ `unavailable` (runtime not ready, missing handler/plugin, or failed runtime).
18
+ - `reason`: null when enabled, otherwise `{ code, message, requirement? }`.
19
+ Codes are stable; messages are explanatory, not identifiers.
20
+ - `active`: whether this tool is the controller's persistent active mode.
21
+ - `groupIds`: deduplicated configured toolbar groups containing this tool.
22
+ Caller-provided command `groupId` values do not create toolbar groups.
23
+ - `hotkey`: actual built-in activation shortcut, currently null for all tools.
24
+ GeoKit does not register letter shortcuts. Leaflet's contextual Escape cancel
25
+ behavior is not a global select shortcut.
26
+ - `commands`: support for `activate` and `deactivate` commands. The existing
27
+ bus accepts both for every tool; `deactivate` always returns to select mode.
28
+ - `commandEnabled`: whether activation may run. The longstanding
29
+ `toolButtonConfig.disabled` option disables buttons, not the imperative API.
30
+ Runtime failures disable buttons but permit an explicit imperative retry.
31
+ - `behavior`: `draw`, `mode`, `action`, or `deactivate`. LayerCake is multi-stage
32
+ drawing; consult [the lifecycle contract](tool-lifecycle.md) for completion.
33
+
34
+ `provider` separately reports `requested`, `active`, `state`, and `reason`.
35
+ Missing HERE credentials, unknown providers, and tile runtime errors are visible
36
+ here even when fallback OSM tiles work. No key, tile URL, or raw provider error
37
+ payload is included. Local geometry tools do **not** require a paid tile
38
+ provider and remain enabled during fallback.
39
+
40
+ `selectedFeatureIds` contains the currently valid host-supplied selection.
41
+ Snapshots and events never expose mutable internal arrays or registry objects.
42
+
43
+ ## Requirements and recovery
44
+
45
+ The registry reflects:
46
+
47
+ | Reason code | Meaning / recovery |
48
+ | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
49
+ | `not_ready` | Wait for initialization or reconnect the element. |
50
+ | `read_only` | Drawing, move, edit and delete need read-only removed. Save/select/ruler remain usable. |
51
+ | `missing_attribute` | Enable the named draw/edit/delete/ruler attribute. Delete also needs `edit-features` because Leaflet.draw owns remove under its edit toolbar. |
52
+ | `unavailable_plugin` | The configured tool's actual handler/plugin is absent. Supply the runtime/plugin and rebuild. |
53
+ | `no_editable_layers` | Move/edit/delete need at least one actual editable layer, not merely a GeoJSON feature count. |
54
+ | `empty_selection` | An opt-in selection prerequisite has no valid selected feature ids. |
55
+ | `missing_provider` | Requested tile provider is not supported. |
56
+ | `missing_api_key` | Requested provider needs credentials; use a supported free provider or configure credentials privately. |
57
+ | `runtime_error` | A tool threw/failed or the requested provider failed. Tool activation may be retried explicitly; successful retry/rebuild clears its failure. Provider change/reconfiguration clears provider failure. |
58
+ | `configured_disabled` | Host disabled the managed button; imperative compatibility API remains available. |
59
+
60
+ Reasons have deterministic precedence: readiness, read-only, attributes, plugin,
61
+ editable layers, selection, provider, runtime error, host-disabled flag. Changes
62
+ after load/add/clear/update/remove, Leaflet create/delete, tool activation,
63
+ configuration, read-only rebuild, and provider reconfiguration are reflected.
64
+ Rapid structural attribute changes are serialized, retaining stored geometry.
65
+
66
+ GeoKit has no global feature-selection UI. Existing layerStyle remains a
67
+ host-owned action/popover, and save still exports an empty collection. To opt
68
+ host actions into stronger prerequisites without breaking those defaults:
69
+
70
+ ```ts
71
+ map.toolButtonConfig = {
72
+ layerStyle: { requirements: { selection: true } },
73
+ // Only opt in when YOUR action truly needs the requested provider.
74
+ save: { requirements: { provider: true } },
75
+ };
76
+ map.setToolSelection(["bed-17"]); // Supply ids from your host selection model.
77
+ ```
78
+
79
+ Unknown/deleted ids are excluded. Clear/load-replace resets selection. These
80
+ opt-in prerequisites also apply to imperative/event activation. No implicit
81
+ selection engine, provider provisioning, or host API wiring is introduced.
82
+
83
+ ## Declarative external buttons
84
+
85
+ ```html
86
+ <leaflet-geokit id="map" draw-polygon edit-features></leaflet-geokit>
87
+ <button data-tool="polygon" disabled>Draw boundary</button>
88
+ <button data-tool="edit" disabled>Edit boundaries</button>
89
+ <script type="module">
90
+ import "@florasync/leaflet-geokit";
91
+ const map = document.querySelector("#map");
92
+ const buttons = document.querySelectorAll("button[data-tool]");
93
+ const render = () => {
94
+ const { tools } = map.getToolCapabilities();
95
+ for (const button of buttons) {
96
+ const capability = tools[button.dataset.tool];
97
+ button.disabled = capability.state !== "enabled";
98
+ button.title = capability.reason?.message ?? "";
99
+ button.setAttribute("aria-pressed", String(capability.active));
100
+ }
101
+ };
102
+ map.addEventListener("leaflet-geokit:tool-capabilities-changed", render);
103
+ render();
104
+ for (const button of buttons) {
105
+ button.addEventListener("click", () =>
106
+ map.activateTool(button.dataset.tool),
107
+ );
108
+ }
109
+ </script>
110
+ ```
111
+
112
+ The existing `irrigation-draw-mode.html` harness contains working external
113
+ buttons, an empty-layer edit state, and a read-only toggle. Managed toolbar
114
+ buttons consume the same snapshot, including duplicate placements. The
115
+ intentionally unguarded “Try unavailable polyline” button remains a failure-bus
116
+ example, not the recommended capability binding.
117
+
118
+ ## Focused verification
119
+
120
+ ```sh
121
+ npm run typecheck
122
+ npm run test:unit:focused -- tests/tool-capabilities.spec.ts tests/tool-lifecycle.spec.ts tests/map-controller.spec.ts tests/element.spec.ts
123
+ npx playwright test --config playwright.capabilities.config.ts --output "$PAPERCLIP_RUN_SCRATCH_DIR/browser-results"
124
+ npm run build
125
+ ```
126
+
127
+ Outside a Paperclip run, supply a writable output directory yourself. The
128
+ capability Playwright config starts an isolated Vite harness on port 5186 with
129
+ HMR off and shuts it down after the tests. Capability tests use fixture tile
130
+ responses while exercising real Leaflet pointer drawing and public APIs; they
131
+ do not contact paid providers or prove vendor availability.
@@ -0,0 +1,124 @@
1
+ # Public tool command and lifecycle bus
2
+
3
+ GeoKit exposes one framework-agnostic command surface for host controls, managed
4
+ toolbars, and the native Leaflet toolbar. Consumers can use the imperative
5
+ methods or dispatch a typed command event; lifecycle results always leave the
6
+ actual `<leaflet-geokit>` element as bubbling, composed `CustomEvent`s.
7
+
8
+ ## Command entry points
9
+
10
+ - `activateTool(tool, options)` starts a tool. `triggerTool` is its
11
+ compatibility alias.
12
+ - `deactivateTool(options)` stops the current persistent tool and returns to
13
+ select mode.
14
+ - Dispatch `leaflet-geokit:tool-command` with `ToolCommandEventDetail` to
15
+ use the event-only API. Its `action` defaults to `activate`; use
16
+ `{ tool: "select", action: "deactivate" }` to stop.
17
+ - `leaflet-geokit:activate-tool`, `leaflet-geokit:trigger-tool`, and
18
+ `leaflet-geokit:deactivate-tool` remain compatibility aliases.
19
+ - Managed toolbar buttons and observed native Leaflet toolbar buttons enter the
20
+ same controller bus. They do not synthesize a second activation.
21
+
22
+ `ToolTriggerOptions` accepts `source`, `groupId`, and an optional
23
+ `commandId`. GeoKit generates a command id when callers omit one. Reuse that
24
+ id only when the calls are intentionally the same logical command; repeated
25
+ commands normally need distinct ids.
26
+
27
+ ```ts
28
+ import type {
29
+ LeafletDrawMapElementAPI,
30
+ ToolEventDetail,
31
+ } from "@florasync/leaflet-geokit";
32
+
33
+ const map = document.querySelector("leaflet-geokit") as HTMLElement &
34
+ LeafletDrawMapElementAPI;
35
+
36
+ map.addEventListener("leaflet-geokit:tool-failed", (event) => {
37
+ const detail = (event as CustomEvent<ToolEventDetail>).detail;
38
+ console.error(detail.commandId, detail.reason);
39
+ });
40
+
41
+ await map.activateTool("polygon", {
42
+ source: "field-panel",
43
+ groupId: "outside-controls",
44
+ });
45
+
46
+ map.dispatchEvent(
47
+ new CustomEvent("leaflet-geokit:tool-command", {
48
+ bubbles: true,
49
+ composed: true,
50
+ detail: {
51
+ tool: "layerCake",
52
+ source: "field-panel",
53
+ groupId: "outside-controls",
54
+ },
55
+ }),
56
+ );
57
+ ```
58
+
59
+ ## Lifecycle and ordering
60
+
61
+ Every lifecycle event uses exported `ToolEventDetail`:
62
+
63
+ - `tool`, `action`, `source`, `groupId`, and `commandId` identify the
64
+ command.
65
+ - `previousTool` and `activeTool` are null when there is no persistent mode.
66
+ - `featureIds` is always present. It is empty when no features apply.
67
+ - `geometry` is a GeoJSON `Feature` or `FeatureCollection` snapshot when a
68
+ committed operation has geometry.
69
+ - `reason` explains cancellations and failures.
70
+ - `timestamp` is milliseconds since the Unix epoch.
71
+
72
+ The canonical order is:
73
+
74
+ 1. `leaflet-geokit:tool-command` — a normalized request entered the public bus.
75
+ For an event command, the caller's event is this phase; GeoKit enriches its
76
+ mutable detail rather than emitting a duplicate.
77
+ 2. `leaflet-geokit:tool-commanded` — the controller accepted the request and
78
+ is attempting it.
79
+ 3. Persistent tools emit `tool-started`, then `tool-state-changed` if the
80
+ active tool changed. Action tools emit `tool-completed` immediately.
81
+ 4. Interactive commits emit `tool-completed` with ids/geometry. A one-shot
82
+ tool then emits `tool-state-changed` when Leaflet stops it.
83
+ 5. Escape, select, and switches emit `tool-cancelled` for the command that was
84
+ active. A real active-state transition emits `tool-state-changed` once.
85
+ 6. Unavailable handlers, thrown activation errors, and missing controllers emit
86
+ `tool-failed` with `reason`; they never leave the failed tool active.
87
+
88
+ On a switch, the new command/commanded phases occur first, the previous command
89
+ is cancelled using its original correlation id, and the new command starts.
90
+ Repeating the same persistent tool cancels the old command and starts the new
91
+ one without a false state-change event (the active tool name did not change).
92
+
93
+ The older `tool-trigger-requested`, `tool-triggered`, and
94
+ `tool-trigger-failed` events are still emitted for compatibility and include
95
+ `commandId`. Their presence does not change the canonical ordering above.
96
+
97
+ ## Complete tool inventory
98
+
99
+ | Tool | Kind | Activation and terminal behavior |
100
+ | --------------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
101
+ | `polygon` | Persistent, one-shot draw | Starts on Leaflet `drawstart`; created feature completes with one id/Feature; `drawstop` clears active state. Escape cancels. |
102
+ | `polyline` | Persistent, one-shot draw | Same contract as polygon. |
103
+ | `rectangle` | Persistent, one-shot draw | Same contract as polygon. |
104
+ | `circle` | Persistent, one-shot draw | Same contract as polygon. |
105
+ | `marker` | Persistent, one-shot draw | Same contract as polygon. |
106
+ | `layerCake` | Persistent, multi-stage draw | Starts with the base-circle command. Base-circle creation opens `LayerCakeManager` and is not completion. Manager Save completes with all ids and the FeatureCollection. Select/switch destroys the session and cancels the original command. Source/group/id are retained through save. |
107
+ | `move` | Persistent operation mode | Starts once. Each confirmed move completes with the moved id and new Feature. The mode remains active until select/switch/Escape; the existing `tool:move:*` events remain available for pending/confirmed/per-move-cancel observations. |
108
+ | `select` | Deactivation action | Cancels the current persistent command, clears state, then completes the select command. With nothing active it simply completes. |
109
+ | `edit` | Persistent batch mode | Leaflet edit save completes with edited ids and the current FeatureCollection; edit stop clears state. Closing without save cancels. |
110
+ | `delete` | Persistent batch mode | Leaflet delete save completes with deleted ids and the remaining FeatureCollection; delete stop clears state. Closing without save cancels. |
111
+ | `ruler` | Persistent plugin mode | Starts when the ruler toggle becomes active. Select/switch/Escape or the native toggle cancels and clears it. The third-party plugin does not expose a committed measurement geometry event, so GeoKit does not invent one. |
112
+ | `measurementSettings` | Action | Completes when the settings dialog opens. Choosing units continues to emit `tool:ruler:units-changed`; closing the dialog is not a new command. |
113
+ | `layerStyle` | Action | Completes when GeoKit delivers the style action/popover request. Host-owned styling after that point is outside this lifecycle. |
114
+ | `save` | Action | Completes with all current feature ids and a FeatureCollection snapshot, while also preserving `leaflet-draw:export` and `tool:save`. It does not stop the active persistent tool. |
115
+
116
+ ## Integration rules
117
+
118
+ Listen on the element or any composed ancestor. Do not read `_controller`,
119
+ Leaflet handler internals, or Shadow DOM-private callbacks. Outside controls can
120
+ start/stop/save and observe failure using only the methods/events above.
121
+
122
+ A `tool-completed` event means an actual action or interactive commit. It is
123
+ never emitted merely because a draw handler was enabled. In particular,
124
+ LayerCake activation and base-circle creation are not reported as completion.
@@ -0,0 +1,118 @@
1
+ # Toolbar styling contract v2
2
+
3
+ Managed `toolbarGroups` support host-native styling without shadowRoot access or
4
+ positional Leaflet selectors. See README for pure CSS, JS-only and mixed examples,
5
+ and `irrigation-draw-mode.html` for live examples. Existing APIs remain supported.
6
+
7
+ ## Parts and states
8
+
9
+ | Part | Surface |
10
+ | ------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
11
+ | `host`, `map` | Both name the internal map-sized surface. Style the actual custom-element box with `leaflet-geokit` itself. |
12
+ | `toolbar-group` | Each configured toolbar container. |
13
+ | `toolbar-button` | Tool buttons (also exposed on discovered native Leaflet controls). Full visual replacement applies to managed group buttons. |
14
+ | `icon` | Custom/fallback icon wrapper; inherits color for currentColor SVGs. |
15
+ | `popover` | Open guidance dialog; position follows the trigger. |
16
+ | `active` | Additional part on managed draw/edit mode buttons while active, reset on completion/cancel/deactivation. |
17
+ | `disabled` | Additional part on managed buttons configured with disabled: true. |
18
+ | `badge`, `tooltip` | Decorative badge and visible hover/focus tooltip wrappers. |
19
+
20
+ Native Leaflet sprite/visibility compatibility rules are retained. Disabled config
21
+ applies only to managed buttons, not the imperative `activateTool` API. Actions
22
+ such as Save are not persistent selected modes. Active represents draw/edit modes;
23
+ ruler and host-owned panels retain their own existing state/behavior.
24
+
25
+ Defaults include 44px buttons, hover background, a focus outline, inset active ring,
26
+ and dashed disabled border plus opacity. Keep these affordances visible when
27
+ replacing styles. Disabled native buttons skip Tab and cannot trigger actions.
28
+ Tooltips and badges are decorative (`aria-hidden`): include essential information
29
+ in `ariaLabel` or accessible popover content. This slice does not introduce modal
30
+ focus trapping or responsive zones/overflow.
31
+
32
+ ## CSS custom properties
33
+
34
+ Tokens inherit from the custom element. Lengths accept CSS units. Internal
35
+ `--_geokit-*` config fallbacks are private, not theme APIs. Public tokens override
36
+ JS visual defaults; `::part` rules can replace properties outright. `themeCss`
37
+ and `theme-url` can scope tokens via stable data attributes. No managed button,
38
+ group or popover visual declaration uses `!important`.
39
+
40
+ | Public token(s) | Default |
41
+ | ---------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
42
+ | `--geokit-tool-size`, `--geokit-tool-radius` | `44px`, `12px` |
43
+ | `--geokit-tool-background`, `--geokit-tool-color` | `#fff`, `#1f5134` |
44
+ | `--geokit-tool-border`, `--geokit-tool-shadow` | `1px solid rgba(15,23,18,.18)`, `0 2px 6px rgba(15,23,18,.16)` |
45
+ | `--geokit-tool-hover-background` | `#f0f8ed` |
46
+ | `--geokit-tool-active-background`, `--geokit-tool-active-color` | `#dceddf`, `#16452b` |
47
+ | `--geokit-tool-disabled-opacity`, `--geokit-tool-focus-ring` | `.5`, `2px solid #2f8f5f` |
48
+ | `--geokit-toolbar-gap`, `--geokit-toolbar-direction` | group gap or `6px`; group orientation mapped to `row`/`column` |
49
+ | `--geokit-toolbar-offset-x`, `--geokit-toolbar-offset-y` | group offset or `10px` each |
50
+ | `--geokit-toolbar-padding`, `--geokit-toolbar-radius` | `6px`, `16px` |
51
+ | `--geokit-toolbar-background`, `--geokit-toolbar-border` | `rgba(255,255,255,.94)`, `1px solid rgba(15,23,18,.16)` |
52
+ | `--geokit-toolbar-shadow`, `--geokit-toolbar-z-index` | `0 1px 5px rgba(0,0,0,.35)`, `1000` |
53
+ | `--geokit-icon-size` | configured iconSize (width/height), otherwise `20px` managed / `18px` custom native icons |
54
+ | `--geokit-popover-background`, `--geokit-popover-color` | `#fff`, `#163323` |
55
+ | `--geokit-popover-border`, `--geokit-popover-radius` | `1px solid rgba(0,0,0,.22)`, `8px` |
56
+ | `--geokit-popover-shadow`, `--geokit-popover-z-index` | `0 8px 24px rgba(0,0,0,.24)`, `10001` |
57
+ | `--geokit-popover-padding`, `--geokit-popover-max-width`, `--geokit-popover-font` | `10px 12px`, `260px`, `13px system-ui, sans-serif` |
58
+ | `--geokit-badge-background`, `--geokit-badge-color`, `--geokit-badge-radius` | `#1f5134`, `#fff`, `8px` |
59
+ | `--geokit-tooltip-background`, `--geokit-tooltip-color`, `--geokit-tooltip-radius` | `#163323`, `#fff`, `4px` |
60
+
61
+ ## Placement and data attributes
62
+
63
+ `position` supports `topleft`, `topright`, `bottomleft`, `bottomright`.
64
+ `orientation` is `vertical` (default) or `horizontal`; `gap` is a finite,
65
+ nonnegative pixel value. Offsets are `[x,y]` nonnegative pixels. Each group has
66
+ independent settings. CSS direction overrides visual flow only; use config for
67
+ semantic orientation too.
68
+
69
+ Native draw/ruler controls hide if **any** group leaves `hideDefaultToolbar`
70
+ true/default; set it false on **all** groups to retain native controls. Removing
71
+ groups restores their previous display styles.
72
+
73
+ Stable data hooks:
74
+
75
+ - Groups: `data-geokit-managed-toolbar`, `data-geokit-toolbar-group`,
76
+ `data-geokit-toolbar-position`, `data-geokit-toolbar-orientation`.
77
+ - Managed buttons: `data-geokit-tool`, `data-geokit-toolbar-group`,
78
+ `data-geokit-toolbar-position`, `data-geokit-tool-instance`,
79
+ `data-geokit-active`, `data-geokit-disabled`.
80
+ - Popovers: `data-geokit-tool-popover`, `data-geokit-tool`,
81
+ `data-geokit-toolbar-group`, `data-geokit-tool-instance`.
82
+
83
+ Tool data names keep the existing kebab-case mapping (`layer-cake`, `layer-style`,
84
+ `measurement-settings`). `::part` cannot select descendants or filter by these
85
+ attributes: use a host selector for whole instances, and `themeCss`/`theme-url`
86
+ for per-group/per-tool rules. Config setters rerender managed groups; public parts
87
+ and tokens remain effective after rerender.
88
+
89
+ ## Named slots
90
+
91
+ Managed buttons provide `{groupId}-{toolKey}-{zeroBasedIndex}-icon`, `-badge`,
92
+ and `-tooltip`. Tool keys use config spelling (`layerStyle`, not `layer-style`).
93
+ For `{ id: "care", tools: ["polygon", "save"] }`:
94
+
95
+ ```html
96
+ <leaflet-geokit>
97
+ <span slot="care-save-1-icon" aria-hidden="true">S</span>
98
+ <span slot="care-save-1-badge">2</span>
99
+ <span slot="care-save-1-tooltip">Save growing spaces</span>
100
+ </leaflet-geokit>
101
+ ```
102
+
103
+ Slots replace configured/default content, not the button or its accessible label.
104
+ Use noninteractive decorative content only. Keep group IDs unique; indices allow
105
+ duplicate tools to have independent content. Reordering tools changes slot names.
106
+ Framework hosts may still use `renderIcon` and popover renderers instead.
107
+
108
+ ## Verification
109
+
110
+ ```sh
111
+ npm run test:unit:focused -- tests/toolbar-contract.spec.ts tests/element.spec.ts tests/component-events.spec.ts tests/map-controller.spec.ts
112
+ npm run test:e2e -- --project=chromium e2e/toolbar-contract.spec.ts e2e/irrigation-draw-mode.spec.ts
113
+ ```
114
+
115
+ The current project is `chromium`, not the historical `leaflet` name. Use a
116
+ user-writable `--output` directory if existing Playwright artifacts belong to
117
+ another user. The focused unit command disables repo-wide coverage thresholds;
118
+ it does not replace the full coverage gate for a release.