@florasync/leaflet-geokit 0.8.3 → 0.9.1

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 (78) hide show
  1. package/ARCHITECTURE.md +195 -0
  2. package/CHANGELOG.md +8 -0
  3. package/README.md +146 -11
  4. package/custom-toolbar.html +165 -0
  5. package/dist/django/index.js +8993 -5090
  6. package/dist/django/index.js.map +1 -1
  7. package/dist/leaflet-geokit.es.js +21536 -5994
  8. package/dist/leaflet-geokit.es.js.map +1 -1
  9. package/dist/leaflet-geokit.external.es.js +18006 -2461
  10. package/dist/leaflet-geokit.external.es.js.map +1 -1
  11. package/dist/leaflet-geokit.umd.js +263 -60
  12. package/dist/leaflet-geokit.umd.js.map +1 -1
  13. package/dist/preact/index-DCKj0r6a.js +8545 -0
  14. package/dist/preact/index-DCKj0r6a.js.map +1 -0
  15. package/dist/preact/index.js +1 -1
  16. package/dist/preact-bundled/index.js +9002 -5089
  17. package/dist/preact-bundled/index.js.map +1 -1
  18. package/dist/react/index-DCKj0r6a.js +8545 -0
  19. package/dist/react/index-DCKj0r6a.js.map +1 -0
  20. package/dist/react/index.js +1 -1
  21. package/dist/react-bundled/index.js +9040 -5127
  22. package/dist/react-bundled/index.js.map +1 -1
  23. package/dist/types/components/LeafletDrawMapElement.d.ts +42 -3
  24. package/dist/types/django/index.d.ts +2 -2
  25. package/dist/types/external.d.ts +9 -3
  26. package/dist/types/index.d.ts +9 -3
  27. package/dist/types/lib/FeatureStore.d.ts +2 -2
  28. package/dist/types/lib/LayerRegistry.d.ts +19 -0
  29. package/dist/types/lib/MapController.d.ts +95 -5
  30. package/dist/types/lib/draw/L.Draw.Move.d.ts +1 -0
  31. package/dist/types/lib/draw/move-pointer.d.ts +12 -0
  32. package/dist/types/lib/layer-cake/LayerCakeManager.d.ts +10 -2
  33. package/dist/types/lib/layer-style-panel.d.ts +3 -0
  34. package/dist/types/lib/marker-icons.d.ts +1 -1
  35. package/dist/types/lib/providers.d.ts +64 -0
  36. package/dist/types/lib/snapping.d.ts +30 -0
  37. package/dist/types/lib/tool-buttons.d.ts +3 -1
  38. package/dist/types/lib/tool-capabilities.d.ts +27 -0
  39. package/dist/types/lib/toolbar-accessibility.d.ts +3 -0
  40. package/dist/types/lib/toolbar-layout.d.ts +14 -0
  41. package/dist/types/lib/toolbar-styles.d.ts +2 -0
  42. package/dist/types/preact/core.d.ts +2 -2
  43. package/dist/types/preact/index.d.ts +2 -2
  44. package/dist/types/preact-bundled/index.d.ts +3 -3
  45. package/dist/types/react/core.d.ts +2 -2
  46. package/dist/types/react/index.d.ts +2 -2
  47. package/dist/types/react-bundled/index.d.ts +3 -3
  48. package/dist/types/types/events.d.ts +15 -1
  49. package/dist/types/types/layers.d.ts +65 -0
  50. package/dist/types/types/public.d.ts +160 -5
  51. package/dist/types/utils/geojson-pipeline.d.ts +51 -0
  52. package/dist/types/utils/geojson.d.ts +15 -2
  53. package/dist/types/utils/grower-geometry.d.ts +107 -0
  54. package/docs/accessibility.md +142 -0
  55. package/docs/api-reference.md +249 -0
  56. package/docs/custom-toolbar.md +168 -0
  57. package/docs/diagnostics.md +216 -0
  58. package/docs/geojson-pipelines.md +145 -0
  59. package/docs/google-maps-adapter-spike.md +77 -0
  60. package/docs/grower-geometry.md +237 -0
  61. package/docs/grower-measurement.md +23 -0
  62. package/docs/integration-recipes.md +301 -0
  63. package/docs/layers.md +136 -0
  64. package/docs/providers.md +191 -0
  65. package/docs/release-verification.md +75 -0
  66. package/docs/shims/django.md +102 -0
  67. package/docs/shims/preact.md +98 -0
  68. package/docs/shims/react.md +98 -0
  69. package/docs/snapping-and-measurements.md +42 -0
  70. package/docs/tool-capabilities.md +131 -0
  71. package/docs/tool-lifecycle.md +124 -0
  72. package/docs/toolbar-layout.md +158 -0
  73. package/docs/toolbar-styling.md +118 -0
  74. package/package.json +35 -3
  75. package/dist/preact/index-BMfJn-mD.js +0 -4632
  76. package/dist/preact/index-BMfJn-mD.js.map +0 -1
  77. package/dist/react/index-BMfJn-mD.js +0 -4632
  78. package/dist/react/index-BMfJn-mD.js.map +0 -1
@@ -0,0 +1,237 @@
1
+ # Safe GeoJSON geometry and grower presets
2
+
3
+ `src/utils/grower-geometry.ts` is a framework-agnostic, map-free module. It
4
+ does not mutate GeoJSON, Leaflet layers, or caller-owned metadata. Every public
5
+ operation returns an explicit discriminated result instead of throwing geometry
6
+ errors into an application event handler.
7
+
8
+ The geometry helpers and grower presets are exported from both package
9
+ entry points (`src/index.ts` and `src/external.ts`). They remain framework-
10
+ agnostic and can be used independently of a map instance.
11
+
12
+ ## Result contract
13
+
14
+ ```ts
15
+ type GrowerGeometryResult<T> =
16
+ | { ok: true; value: T }
17
+ | {
18
+ ok: false;
19
+ error: {
20
+ code:
21
+ | "invalid-input"
22
+ | "invalid-options"
23
+ | "unsupported-geometry"
24
+ | "topology-error"
25
+ | "empty-result"
26
+ | "operation-failed";
27
+ message: string;
28
+ details?: readonly string[];
29
+ };
30
+ };
31
+ ```
32
+
33
+ Inputs first pass `validateGeoJSON` from `src/utils/geojson-pipeline.ts`, then
34
+ WGS84 range, degeneracy, OGC validity, and self-intersection checks. Generated
35
+ geometry goes through the same checks before success is returned. Inputs and
36
+ nested properties are JSON-cloned before maintained Turf algorithms receive
37
+ them.
38
+
39
+ ## Geometry operation signatures
40
+
41
+ ```ts
42
+ type SupportedGeoJSON =
43
+ | Geometry
44
+ | Feature<Geometry>
45
+ | FeatureCollection<Geometry>;
46
+
47
+ function bufferGeoJSON(
48
+ input: SupportedGeoJSON,
49
+ distanceMeters: number,
50
+ options?: { steps?: number },
51
+ ): GrowerGeometryResult<
52
+ Feature<Polygon | MultiPolygon> | FeatureCollection<Polygon | MultiPolygon>
53
+ >;
54
+
55
+ function splitGeoJSON(
56
+ line: Feature<LineString>,
57
+ splitter: Feature<
58
+ Point | MultiPoint | LineString | MultiLineString | Polygon | MultiPolygon
59
+ >,
60
+ ): GrowerGeometryResult<FeatureCollection<LineString>>;
61
+
62
+ function mergeGeoJSON(
63
+ polygons: FeatureCollection<Polygon | MultiPolygon>,
64
+ properties?: GeoJsonProperties,
65
+ ): GrowerGeometryResult<Feature<Polygon | MultiPolygon>>;
66
+
67
+ function simplifyGeoJSON<T extends SupportedGeoJSON>(
68
+ input: T,
69
+ options: {
70
+ toleranceDegrees: number;
71
+ highQuality?: boolean;
72
+ },
73
+ ): GrowerGeometryResult<T>;
74
+
75
+ function centroidGeoJSON(
76
+ input: SupportedGeoJSON,
77
+ properties?: GeoJsonProperties,
78
+ ): GrowerGeometryResult<Feature<Point>>;
79
+
80
+ function boundingBoxGeoJSON(
81
+ input: SupportedGeoJSON,
82
+ ): GrowerGeometryResult<
83
+ [west: number, south: number, east: number, north: number]
84
+ >;
85
+ ```
86
+
87
+ - Buffer distance is signed, finite, non-zero meters. Negative erosion that
88
+ removes any member fails with `empty-result`; a partial collection is never
89
+ silently returned. `steps` is 4–256.
90
+ - Split currently supports one `LineString`. A splitter that does not cut it is
91
+ `empty-result`. Nested properties are copied. Top-level and fallback
92
+ `properties.id` values become `<source>:split:<one-based-index>` so the output
93
+ does not contain duplicate IDs.
94
+ - Merge requires at least two polygon features and invokes polygon overlay
95
+ union. It never implements “merge” as coordinate concatenation. Disconnected
96
+ inputs correctly produce a `MultiPolygon`. Output properties are the supplied
97
+ properties, or a clone of the first feature's properties.
98
+ - Simplification supports line and polygon members only. The tolerance is
99
+ deliberately named `toleranceDegrees`: Turf's Ramer–Douglas–Peucker
100
+ implementation operates in coordinate units, not meters. An invalid or
101
+ degenerate simplified result is rejected.
102
+ - Centroid is the arithmetic mean of vertices, not an area-weighted center of
103
+ mass and not a guaranteed interior point.
104
+ - Bounding boxes always recompute coordinate extents and ignore a stale input
105
+ `bbox` field.
106
+
107
+ ## Measurement and formatting signatures
108
+
109
+ ```ts
110
+ interface GeoJSONMeasurements {
111
+ lengthMeters: number;
112
+ perimeterMeters: number;
113
+ areaSquareMeters: number;
114
+ }
115
+
116
+ function measureGeoJSON(
117
+ input: SupportedGeoJSON,
118
+ ): GrowerGeometryResult<GeoJSONMeasurements>;
119
+
120
+ function formatMeasurements(
121
+ measurements: GeoJSONMeasurements,
122
+ system: "metric" | "imperial",
123
+ options?: {
124
+ locale?: string;
125
+ maximumFractionDigits?: number;
126
+ autoScale?: boolean;
127
+ },
128
+ ): GrowerGeometryResult<{
129
+ length: { value: number; unit: "m" | "km" | "ft" | "mi"; text: string };
130
+ perimeter: { value: number; unit: "m" | "km" | "ft" | "mi"; text: string };
131
+ area: { value: number; unit: "m²" | "ha" | "ft²" | "ac"; text: string };
132
+ }>;
133
+ ```
134
+
135
+ `lengthMeters` sums open `LineString` and `MultiLineString` members.
136
+ `perimeterMeters` sums every polygon exterior and hole ring.
137
+ `areaSquareMeters` sums polygon and multipolygon geodesic area with holes
138
+ removed. Geometry collections and feature collections accumulate their members.
139
+ Points contribute zero.
140
+
141
+ Line and ring distance uses `computePreciseDistance`, including its Vincenty
142
+ path and existing fallback. Area uses Turf's geodesic-area implementation.
143
+ Formatting preserves the unrounded converted value and separately provides a
144
+ locale-rounded display string. With `autoScale: false` (the default), metric
145
+ uses meters and square meters while imperial uses feet and square feet. With
146
+ `autoScale: true`, large values switch to kilometers/miles and hectares/acres.
147
+ Conversions use 1 m = 3.280839895013123 ft and 1 m² =
148
+ 10.763910416709722 ft².
149
+
150
+ ## Grower presets and guide signatures
151
+
152
+ ```ts
153
+ const GROWER_PRESETS = {
154
+ bedWidthMeters: { compact: 0.75, standard: 1, wide: 1.2 },
155
+ rowSpacingMeters: { dense: 0.15, vegetables: 0.3, orchard: 3 },
156
+ irrigationRadiusMeters: {
157
+ dripEmitter: 0.3,
158
+ microSprinkler: 3,
159
+ sprinkler: 12,
160
+ },
161
+ } as const;
162
+
163
+ function createBedWidthGuides<T extends LineString | MultiLineString>(
164
+ centerLine: Feature<T>,
165
+ bedWidthMeters: number,
166
+ ): GrowerGeometryResult<FeatureCollection<T>>;
167
+
168
+ function createRowSpacingGuides<T extends LineString | MultiLineString>(
169
+ baseline: Feature<T>,
170
+ spacingMeters: number,
171
+ options?: {
172
+ rowsPerSide?: number; // default 2, range 1–100
173
+ includeBaseline?: boolean; // default true
174
+ },
175
+ ): GrowerGeometryResult<FeatureCollection<T>>;
176
+
177
+ function createIrrigationZones(
178
+ center: Position, // [longitude, latitude]
179
+ outerRadiusMeters: number,
180
+ options?: {
181
+ zoneCount?: number; // default 1, range 1–32
182
+ steps?: number; // default 64, range 8–256
183
+ },
184
+ ): GrowerGeometryResult<FeatureCollection<Polygon>>;
185
+ ```
186
+
187
+ Bed guides are offset by half the full width on opposite sides. Row guides are
188
+ symmetric offsets from the baseline. Each guide receives a `geokit:guide`
189
+ property with its type and signed meter offset; existing nested metadata is
190
+ cloned and IDs receive a guide suffix.
191
+
192
+ Turf line offsets use spherical calculations. Focused tests compare them with
193
+ the WGS84 ellipsoidal distance helper; at one-meter scale around the equator the
194
+ observed difference is about 0.1% (roughly 1 mm). These guide lines are planning
195
+ aids rather than survey or machine-control boundaries.
196
+
197
+ Irrigation zones reuse `bakeLayerCake` from
198
+ `src/lib/layer-cake/CakeBaker.ts`. `zoneCount` divides the outer radius into
199
+ equal-width concentric polygons: the first is a core and later zones are rings
200
+ with holes. CakeBaker assigns UUID feature IDs. The preset dimensions are
201
+ positive defaults, not agronomic recommendations; callers must select values
202
+ appropriate to crop, emitter, pressure, soil, and local practice.
203
+
204
+ ## Limits
205
+
206
+ - Coordinates must be finite WGS84 longitude/latitude and remain within
207
+ ±180/±90 degrees. No CRS reprojection is performed.
208
+ - Algorithms operate on ordinary RFC 7946 planar coordinate topology. Geometry
209
+ that crosses the antimeridian or encloses a pole should be normalized or
210
+ handled by a specialized geodesic engine first.
211
+ - Zero-area rings, zero-length lines, invalid hole relationships,
212
+ self-intersections, empty collections, and invalid generated outputs are
213
+ rejected.
214
+ - `GeometryCollection` is supported by validation, measurement, centroid,
215
+ bounds, and buffering. Simplification succeeds only when every leaf is a line
216
+ or polygon. Split and merge intentionally use the narrower signatures above.
217
+ - Input metadata must be finite, acyclic JSON, matching `validateGeoJSON`.
218
+ - These helpers produce GeoJSON only. They do not create, edit, or provision
219
+ Leaflet layers and do not call FloraSync APIs.
220
+
221
+ ## Maintained algorithm dependencies
222
+
223
+ The manifest includes only the Turf modules used by this file: area, bbox,
224
+ boolean-valid, buffer, centroid, kinks, line-offset, line-split, simplify, and
225
+ union. This keeps robust clipping/overlay behavior in maintained libraries
226
+ instead of an ad-hoc implementation while allowing bundlers to tree-shake each
227
+ operation.
228
+
229
+ ## Public grower presets
230
+
231
+ `GROWER_PRESETS` contains practical starting values for `bedWidthMeters`,
232
+ `rowSpacingMeters`, and `irrigationRadiusMeters`. Use `createBedWidthGuides`,
233
+ `createRowSpacingGuides`, or `createIrrigationZones` with a preset and add the
234
+ returned features through `importGeoJSON({ ... }, { behavior: "add", layer: { kind: "guide" } })`
235
+ when they should participate in guide-layer snapping. Every helper returns
236
+ `{ ok: false, error }` for invalid inputs; callers should surface the actionable
237
+ message and leave the existing FeatureCollection unchanged.
@@ -0,0 +1,23 @@
1
+ # Grower-scale measurement accuracy
2
+
3
+ The existing ruler uses `computePreciseDistance` in `src/utils/geodesic.ts`.
4
+ Its Vincenty iteration must execute at least once even when longitude difference
5
+ is zero. Otherwise a north/south bed or irrigation row is reported as zero length.
6
+ The initial previous-longitude sentinel now guarantees that first evaluation;
7
+ the public API and units remain unchanged.
8
+
9
+ Regression coverage in `tests/geodesic.spec.ts` checks a same-meridian row in both
10
+ directions (about 11.0574276 m for 0.0001 degrees latitude at the equator), a nearly
11
+ meridional grower-scale segment, identical points, and the existing long-distance
12
+ cases.
13
+
14
+ Verified commands for this prerequisite:
15
+
16
+ - `npm run test:unit:focused -- tests/geodesic.spec.ts` — 15 tests passed.
17
+ - `npm run typecheck` — passed.
18
+
19
+ This is a prerequisite repair for FLOA-510, not delivery of snapping, geometry
20
+ operations, grower presets, or area/perimeter overlays. Those features require
21
+ separate implementation and desktop/touch interaction verification. Existing
22
+ irrigation geometry in `src/lib/layer-cake/CakeBaker.ts` and the layer-cake session
23
+ APIs should be reused rather than replaced.
@@ -0,0 +1,301 @@
1
+ # Integration recipes
2
+
3
+ Use the public element API to keep your application independent of private
4
+ Leaflet handlers and Shadow DOM structure. These recipes compose existing
5
+ contracts; follow the linked guides for complete options and limitations.
6
+
7
+ ## Start with a ready browser map
8
+
9
+ This TypeScript module is for a browser bundle. The mount point is an app-owned
10
+ `<div id="map-root"></div>`. Register listeners and configure properties before
11
+ connecting a new element; `customElements.whenDefined` alone does not mean the
12
+ Leaflet map is ready.
13
+
14
+ ```ts
15
+ import { LeafletDrawMapElement } from "@florasync/leaflet-geokit";
16
+
17
+ const mount = document.getElementById("map-root");
18
+ if (!mount) throw new Error("Missing #map-root");
19
+ const map = new LeafletDrawMapElement();
20
+ map.style.cssText = "display:block;width:100%;height:420px";
21
+ map.setAttribute("draw-polygon", "");
22
+ map.setAttribute("draw-layer-cake", "");
23
+ map.setAttribute("edit-features", "");
24
+ map.setAttribute("tile-provider", "osm");
25
+ map.addEventListener("leaflet-geokit:diagnostic", (event) => {
26
+ console.error((event as CustomEvent).detail);
27
+ });
28
+ const ready = new Promise<void>((resolve) => {
29
+ const onStatus = () => {
30
+ if (!map.status.ready) return;
31
+ map.removeEventListener("leaflet-geokit:status", onStatus);
32
+ resolve();
33
+ };
34
+ map.addEventListener("leaflet-geokit:status", onStatus);
35
+ });
36
+ mount.append(map);
37
+ await ready;
38
+ ```
39
+
40
+ The following browser recipes assume this ready `map`. Production hosts should
41
+ surface initialization failure and provide cancellation/timeout rather than leave
42
+ a loading UI waiting forever. Remove the element on teardown (`map.remove()`),
43
+ and also remove listeners attached to host-owned buttons or sidebars.
44
+
45
+ ## Branded toolbar without Shadow DOM queries
46
+
47
+ For the complete worked example, use [branded toolbars and external buttons](custom-toolbar.md)
48
+ and its existing HTML harness. The small configuration below shows how that
49
+ contract composes with the ready map above: configure a managed group, then style
50
+ the public tokens/parts.
51
+
52
+ ```ts
53
+ map.toolbarGroups = [
54
+ {
55
+ id: "grower",
56
+ tools: ["polygon", "layerCake", "layerStyle"],
57
+ position: "topright",
58
+ orientation: "horizontal",
59
+ ariaLabel: "Growing area tools",
60
+ },
61
+ ];
62
+ map.toolButtonConfig = {
63
+ polygon: { title: "Draw a bed", ariaLabel: "Draw a growing bed" },
64
+ layerCake: { title: "Water zones", ariaLabel: "Draw concentric water zones" },
65
+ };
66
+ ```
67
+
68
+ ```css
69
+ leaflet-geokit {
70
+ --geokit-tool-background: #173d2b;
71
+ --geokit-tool-color: #fff;
72
+ --geokit-tool-hover-background: #275d43;
73
+ --geokit-tool-focus-ring: 3px solid #f3c969;
74
+ --geokit-tool-radius: 8px;
75
+ }
76
+ leaflet-geokit::part(toolbar-group) {
77
+ border: 2px solid #173d2b;
78
+ }
79
+ ```
80
+
81
+ The dedicated [toolbar styling contract](toolbar-styling.md) owns the full token,
82
+ part, slot, icon and state reference. For responsive zones use
83
+ [toolbar layout](toolbar-layout.md); keep the focus/disabled/active affordances in
84
+ [accessibility](accessibility.md). `themeCss`/`theme-url` support per-tool rules
85
+ inside the shadow root; a `::part` selector cannot filter by inner data attributes.
86
+ Only pass trusted/sanitized HTML to icon and popover renderers.
87
+
88
+ ## External layerCake button
89
+
90
+ An external button uses the same tool bus as the managed toolbar. Enable
91
+ `draw-layer-cake` before connection (as above); do not call private draw handlers.
92
+
93
+ ```ts
94
+ const cakeButton = document.createElement("button");
95
+ cakeButton.type = "button";
96
+ cakeButton.textContent = "Draw water zones";
97
+ mount.before(cakeButton);
98
+
99
+ const startCake = () => {
100
+ map.dispatchEvent(
101
+ new CustomEvent("leaflet-geokit:tool-command", {
102
+ detail: { tool: "layerCake", source: "host-sidebar" },
103
+ }),
104
+ );
105
+ };
106
+ cakeButton.addEventListener("click", startCake);
107
+
108
+ // On host teardown, also call:
109
+ // cakeButton.removeEventListener("click", startCake);
110
+ // cakeButton.remove();
111
+ ```
112
+
113
+ Alternatively, `await map.activateTool("layerCake", { source: "host-sidebar" })`
114
+ returns whether activation was handled; it does not mean the user saved a cake.
115
+ The user draws the first circle to start a draft. Only then may a sidebar call
116
+ `updateLayerCakeSession`, `saveLayerCakeSession`, or `cancelLayerCakeSession`.
117
+ Read [external cake controls](layers.md#external-cake-controls) for session events,
118
+ radii in meters, style presets and correlation fields. Use
119
+ [getToolCapabilities](tool-capabilities.md) to reflect availability in host UI and
120
+ [tool lifecycle](tool-lifecycle.md) to observe completion, cancellation or failure.
121
+
122
+ ## Validate an upload before importing
123
+
124
+ The app owns file selection, upload limits and error rendering. This function
125
+ accepts file text; it returns diagnostics when the structural validation fails
126
+ and rejects if the map import itself fails.
127
+
128
+ ```ts
129
+ import { importGeoJSONText } from "@florasync/leaflet-geokit";
130
+
131
+ async function importUpload(text: string) {
132
+ const parsed = importGeoJSONText(text);
133
+ if (!parsed.valid || !parsed.data) return parsed;
134
+
135
+ await map.importGeoJSON(parsed.data, {
136
+ behavior: "replace",
137
+ validate: true,
138
+ fitToData: true,
139
+ layer: { name: "Uploaded growing areas", kind: "imported" },
140
+ });
141
+ return parsed;
142
+ }
143
+ ```
144
+
145
+ For an already-parsed value use exported `validateGeoJSON(unknown)` to inspect
146
+ validity or `importGeoJSONData(unknown)` to validate and obtain a normalized
147
+ FeatureCollection. `validate: true` on the map also checks ingest-hook output
148
+ before replacement; add mode rejects existing IDs. This protects against data
149
+ validation failures, not arbitrary renderer failures. CRS warnings are nonfatal:
150
+ apply your own rejection policy if needed. No automatic reprojection occurs.
151
+
152
+ The [GeoJSON pipeline guide](geojson-pipelines.md) covers diagnostic shapes,
153
+ URL ingestion, Multi/GeometryCollection expansion, stable IDs, source export,
154
+ diff/patch and metadata conflicts. Use its diagnostic `exportGeoJSONData` recipe
155
+ when persisting source geometry; do not confuse it with legacy source export.
156
+
157
+ ## Host layer manager
158
+
159
+ Subscribe once, render a detached snapshot, and send changes through public
160
+ methods. Here the list is a minimal read-only summary; app-owned checkbox/style/
161
+ reorder controls can call the methods described below.
162
+
163
+ ```ts
164
+ const layerList = document.createElement("ul");
165
+ mount.after(layerList);
166
+ const renderLayers = () => {
167
+ layerList.replaceChildren(
168
+ ...map.getLayers().map((layer) => {
169
+ const item = document.createElement("li");
170
+ item.textContent = `${layer.name}: ${layer.visible ? "visible" : "hidden"}`;
171
+ return item;
172
+ }),
173
+ );
174
+ };
175
+ map.addEventListener("leaflet-geokit:layers-changed", renderLayers);
176
+ renderLayers();
177
+
178
+ // On host teardown, also call:
179
+ // map.removeEventListener("leaflet-geokit:layers-changed", renderLayers);
180
+ // layerList.remove();
181
+ ```
182
+
183
+ Use `setLayerVisibility`, `setLayerStyle`, `focusLayer`, `reorderLayers` and
184
+ `removeLayer` for interactions. Reordering requires every current ID exactly once;
185
+ the reserved basemap cannot be removed. Hidden features still export. For
186
+ persistence, use `exportGeoJSON({ preserveLayers: true })` and import with
187
+ `{ behavior: "replace", preserveLayers: true }` on restoration.
188
+
189
+ The [layer guide](layers.md) owns these invariants, draft editing and the
190
+ cancelable host-owned style-panel recipe. Run the existing
191
+ [layer-manager harness](../layer-manager.html) through `npm run dev` for the full
192
+ sidebar rather than introducing another controller implementation.
193
+
194
+ ## Raster providers and optional basemap adapters
195
+
196
+ The default is Leaflet with OSM. Choose `tile-provider="osm"` or `"here"` for
197
+ built-ins; a custom URL uses `tile-url`, not `tile-provider="custom"`.
198
+ After readiness, the equivalent property-based custom configuration is:
199
+
200
+ ```ts
201
+ map.tileProvider = undefined;
202
+ map.tileAttribution = "Your licensed dataset attribution";
203
+ map.tileUrl = "/tiles/{z}/{x}/{y}.png";
204
+ const diagnostics = map.getProviderDiagnostics();
205
+ console.log(diagnostics); // Configuration report, not tile-load health.
206
+ ```
207
+
208
+ The URL above is a **host-provided endpoint**, not a GeoKit tile service. Keep
209
+ attribution accurate. Root and `/external` export `createRasterProvider`,
210
+ `createCustomRasterProvider`, `createMapLibreBasemapAdapter`, and
211
+ `getProviderDiagnostics`. To mount an optional bridge, call
212
+ `map.setBasemapAdapter(adapter)` after readiness; `null` restores raster settings.
213
+
214
+ Follow [providers](providers.md) for the full injected MapLibre/PMTiles experiment,
215
+ shared Leaflet instance, worker/CSP setup, cleanup and production gates. It is a
216
+ basemap seam, not a packaged MapLibre renderer or alternate drawing engine.
217
+ Never put server secrets in browser properties, HTML or URLs; HERE/browser key
218
+ restrictions and vendor licensing remain host responsibilities. No automatic paid
219
+ fallback or offline cache is supplied.
220
+
221
+ ## React and Preact
222
+
223
+ Actual exported component names are `ReactLeafletGeoKit` and
224
+ `PreactLeafletGeoKit`, not `GeoKit` or `LeafletMap`.
225
+
226
+ | Host owns Leaflet/Draw assets | Package provisions assets (browser-only) |
227
+ | ---------------------------------------------------------- | ------------------------------------------------------------------ |
228
+ | `@florasync/leaflet-geokit/react` → `ReactLeafletGeoKit` | `@florasync/leaflet-geokit/react-bundled` → `ReactLeafletGeoKit` |
229
+ | `@florasync/leaflet-geokit/preact` → `PreactLeafletGeoKit` | `@florasync/leaflet-geokit/preact-bundled` → `PreactLeafletGeoKit` |
230
+
231
+ Use the existing [React](shims/react.md) and [Preact](shims/preact.md) quick starts.
232
+ Both wrappers accept `attributes`, `toolbarGroups`, `toolButtonConfig`,
233
+ `toolHooks`, `toolEventEmitter`, `initialGeoJSONText`, change/error callbacks and
234
+ `onReady(element)`. Use `onReady` to attach the public APIs above; keep callback
235
+ and configuration identities stable where possible. Supply a height.
236
+
237
+ Additive wrappers default to `use-external-leaflet` and `skip-leaflet-styles`;
238
+ supply compatible Leaflet/Draw assets and, when needed, `leafletInstance`. Global
239
+ page CSS does not penetrate Shadow DOM: use `themeCss`/`theme-url` for required
240
+ shadow styles or explicitly opt back into injected styles. Framework runtimes
241
+ are consumer peers, not bundled React/Preact copies.
242
+
243
+ ## Django form bridge
244
+
245
+ The exported initializer is `initDjangoGeokit`. The server renders a textarea
246
+ with class `geokit-editor-widget`; an app browser entry imports and initializes
247
+ the shim **after the textarea exists**:
248
+
249
+ ```ts
250
+ import { initDjangoGeokit } from "@florasync/leaflet-geokit/django";
251
+
252
+ const handles = initDjangoGeokit(".geokit-editor-widget", {
253
+ height: 420,
254
+ elementAttributes: { "draw-polygon": true, "edit-features": true },
255
+ onError: (error, context) => console.error(context.phase, error),
256
+ });
257
+ // Before app-controlled submission, await Promise.all(handles.map(h => h.sync())).
258
+ // When removing the widget, call handles.forEach(h => h.destroy()).
259
+ ```
260
+
261
+ See [Django shim](shims/django.md) for `data-geokit-*` configuration and form data
262
+ flow. The bridge hides the textarea, loads initial JSON on readiness, and writes
263
+ changes back to its value. For custom programmatic edits, explicitly await
264
+ `handle.sync()` before submission. Django still validates and authorizes posted
265
+ GeoJSON server-side. Load the built browser entry with a module script; a bare
266
+ npm specifier needs your bundler/import map, and a classic Django Media script
267
+ is not automatically an ESM loader. The optional browser global is
268
+ `window.GeoKitDjango.init`, installed by loading the shim, not by Python.
269
+
270
+ ## SSR-safe imports: separate wrapper modules from browser registration
271
+
272
+ Only the **additive** `/react` and `/preact` wrappers defer element registration to
273
+ client effects. They can be imported in SSR code with their respective framework
274
+ runtime installed. They do not render a working Leaflet map on the server.
275
+
276
+ The root, `/external`, `/django`, `/react-bundled` and `/preact-bundled` entries
277
+ are **not SSR-safe runtime imports**: they eagerly register custom elements or
278
+ import the root that does. A named utility import from the root is not an
279
+ exception. No `/ssr`, `/geojson`, `/utils` or `/providers` subpath is exported.
280
+
281
+ Type-only imports are erased and can be used in server-shared TypeScript. For
282
+ plain-element or bundled integrations, dynamically import in client-only code:
283
+
284
+ ```ts
285
+ import type { LeafletDrawMapElement } from "@florasync/leaflet-geokit";
286
+
287
+ async function createClientMap(): Promise<LeafletDrawMapElement | null> {
288
+ if (typeof window === "undefined" || typeof customElements === "undefined") {
289
+ return null;
290
+ }
291
+ const { LeafletDrawMapElement } = await import("@florasync/leaflet-geokit");
292
+ return new LeafletDrawMapElement(); // Configure/listen before appending.
293
+ }
294
+ ```
295
+
296
+ Call this from your framework's client lifecycle, not during server rendering.
297
+ Use its client-only/no-SSR component mechanism for bundled wrappers. Do not
298
+ statically import a browser-only entry elsewhere in that server module graph.
299
+ A successful server import of an additive wrapper proves only the import boundary,
300
+ not hydration, asset loading or browser editing: exercise those separately with
301
+ the existing framework harnesses.