@florasync/leaflet-geokit 0.8.3 → 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 +8 -0
  2. package/README.md +140 -11
  3. package/dist/django/index.js +8993 -5090
  4. package/dist/django/index.js.map +1 -1
  5. package/dist/leaflet-geokit.es.js +21536 -5994
  6. package/dist/leaflet-geokit.es.js.map +1 -1
  7. package/dist/leaflet-geokit.external.es.js +18006 -2461
  8. package/dist/leaflet-geokit.external.es.js.map +1 -1
  9. package/dist/leaflet-geokit.umd.js +263 -60
  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 +9002 -5089
  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 +9040 -5127
  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 +23 -2
  54. package/dist/preact/index-BMfJn-mD.js +0 -4632
  55. package/dist/preact/index-BMfJn-mD.js.map +0 -1
  56. package/dist/react/index-BMfJn-mD.js +0 -4632
  57. package/dist/react/index-BMfJn-mD.js.map +0 -1
@@ -0,0 +1,145 @@
1
+ # GeoJSON pipelines
2
+
3
+ GeoKit exports `validateGeoJSON`, `normalizeGeoJSON`, `diffGeoJSON`,
4
+ `applyGeoJSONPatch`, `importGeoJSONData`, `importGeoJSONText`,
5
+ `importGeoJSONURL`, and `exportGeoJSONData` from the main and external entrypoints.
6
+ The helpers are framework-agnostic TypeScript and do not mutate a map or their
7
+ inputs. Package entrypoints register the web component and therefore require a
8
+ browser; these are not advertised as SSR entrypoints.
9
+
10
+ ## Reject uploads before changing the map
11
+
12
+ ```ts
13
+ import {
14
+ importGeoJSONText,
15
+ exportGeoJSONData,
16
+ diffGeoJSON,
17
+ applyGeoJSONPatch,
18
+ } from "@florasync/leaflet-geokit";
19
+
20
+ const upload = importGeoJSONText(fileText);
21
+ if (!upload.valid || !upload.data) {
22
+ showUploadErrors(upload.diagnostics);
23
+ return;
24
+ }
25
+ // CRS warnings are non-fatal. Your host may reject them too.
26
+ if (upload.diagnostics.some((d) => d.code === "crs-mismatch")) return;
27
+ await map.importGeoJSON(upload.data, { validate: true, fitToData: true });
28
+ const saved = structuredClone(await map.getGeoJSON());
29
+ // Later, after drawing/editing:
30
+ const current = await map.getGeoJSON();
31
+ const diff = diffGeoJSON(saved, current);
32
+ showSavePrompt(diff.createdIds, diff.updatedIds, diff.deletedIds);
33
+ const nextSaved = applyGeoJSONPatch(saved, diff);
34
+ const source = exportGeoJSONData(nextSaved, { adapter: "source" });
35
+ if (source.valid) persist(source.data);
36
+ else showUploadErrors(source.diagnostics);
37
+ ```
38
+
39
+ The illustrative host functions above are app-owned, not GeoKit APIs.
40
+
41
+ - `validateGeoJSON(unknown)` returns `{ valid, featureCount, diagnostics }`.
42
+ Each diagnostic has `severity`, `code`, `path`, and `message`.
43
+ - `importGeoJSONData(unknown)` accepts a Feature, FeatureCollection, or bare
44
+ geometry and returns the summary plus `data: FeatureCollection | null`.
45
+ - `importGeoJSONText(text)` parses JSON and returns `invalid-json` on parse errors.
46
+ - `importGeoJSONURL(url, { signal, fetcher })` fetches explicitly. Abort/network
47
+ failures and non-2xx HTTP responses reject; invalid JSON/data returns the
48
+ validation summary. The host owns URL trust, CORS, request timeouts and upload
49
+ size limits. Strings are never implicitly fetched.
50
+ - `normalizeGeoJSON(input, { expandMulti: false })` wraps the common shapes,
51
+ deep-clones JSON properties/coordinates, preserves supplied root IDs, and
52
+ assigns UUIDs to missing IDs (falling back to `properties.id`). Normalize once
53
+ and retain that snapshot: re-normalizing ID-less data generates new IDs.
54
+ Invalid input throws `GeoJSONValidationError` with a `.summary`.
55
+ - `{ expandMulti: true }` additionally creates single-geometry editing features,
56
+ including recursively nested GeometryCollections. Expansion collisions are
57
+ rejected. Each expanded child gets an isolated copy of app metadata.
58
+ - `map.importGeoJSON(fc, { validate: true })` validates and expands before any
59
+ replace/clear operation. Add mode also rejects IDs already present in the map.
60
+ The preflight runs after the ingest hook, so hook-modified data is checked.
61
+ This is opt-in for backwards compatibility; old import calls retain their
62
+ permissive behavior. These guarantees cover data-validation failures, not
63
+ arbitrary Leaflet/rendering failures.
64
+
65
+ ## Diagnostics and limits
66
+
67
+ Ingest and export summaries report invalid rings (minimum four positions and
68
+ exact closure), invalid positions/lines, unsupported geometry, empty/null
69
+ geometry, malformed JSON/properties/IDs, duplicate IDs, and malformed reserved
70
+ provenance. Multi geometries and GeometryCollections emit `multi-expansion`
71
+ information. Legacy `crs` declarations and out-of-range WGS84 coordinates emit
72
+ `crs-mismatch` warnings: GeoKit does not reproject or guess coordinate order.
73
+ An empty FeatureCollection is valid; an empty geometry is not editable and is
74
+ rejected. Cycles, non-finite values, sparse arrays, non-JSON metadata and excessive
75
+ nesting are rejected.
76
+
77
+ Validation is structural, not a GIS topology engine: it does not detect every
78
+ self-intersection, validate hole containment, repair rings, change winding,
79
+ reproject, or simplify geometry. Hosts needing those policies must apply a
80
+ separate topology validator. Normalization never silently repairs invalid data.
81
+
82
+ ## Metadata and source round trips
83
+
84
+ App-owned JSON belongs in `properties`; nested records and arrays are preserved.
85
+ All `geokit:*` property names are reserved for library use. Currently
86
+ `properties["geokit:source"]` is an internal provenance stack created by validated
87
+ Multi/collection expansion. Preserve it while editing; do not author or modify
88
+ it. It records source IDs, source geometry types, and the original `properties.id`
89
+ state. It contains no cached coordinates: source export reconstructs from the
90
+ current visible editing geometry, preserving singleton Multi types and nested
91
+ collection structure. Removed children stay removed; removing every child
92
+ removes the source feature.
93
+
94
+ Editing IDs are `sourceId::childIndex` (nested paths append another `::index`).
95
+ The existing map store uses string IDs, including for numeric root IDs.
96
+ Provenance-backed source export restores the original numeric Multi source ID
97
+ and original app-owned `properties.id`. For simple non-expanded features the
98
+ store's established string-ID behavior is unchanged. Diff ID lists are always
99
+ strings; `1` and `"1"` identify the same feature and cannot coexist.
100
+
101
+ `exportGeoJSONData(fc, { adapter: "source" })` returns the same summary/data shape
102
+ as the import helpers. It collapses only explicit provenance, not arbitrary app
103
+ IDs ending in `::0`. If sibling properties have diverged, it returns
104
+ `metadata-conflict` rather than silently discarding one child's edits. Reconcile
105
+ those properties or export the editing collection (the default adapter). It also
106
+ validates the reconstructed output. Legacy `map.exportGeoJSON({adapter:"source"})`
107
+ retains historical suffix inference and first-child metadata behavior; use the
108
+ new diagnostic helper for safe persistence. GeoJSON foreign members and cached
109
+ `bbox` values are not promised across Multi expansion; keep application data
110
+ under `properties` rather than foreign top-level fields.
111
+
112
+ Existing irrigation drawing, tool events, and layer-cake generation remain in
113
+ place; this pipeline wraps the existing expansion/export implementation rather
114
+ than introducing another map or drawing engine.
115
+
116
+ ## Diff and patch contract
117
+
118
+ `diffGeoJSON(before, after)` requires valid FeatureCollections with stable unique
119
+ IDs. It returns `created`, `updated` (complete feature payloads), and `deleted`
120
+ (string IDs), plus `createdIds`, `updatedIds`, and `deletedIds` for save prompts.
121
+ Geometry and metadata changes count; object-key and feature-array order do not.
122
+ Feature reordering and collection-level foreign-member changes are not tracked.
123
+
124
+ `applyGeoJSONPatch(base, patch)` is pure and atomic: it returns a deep-cloned
125
+ collection and never mutates `base`. Creates must be absent, updates/deletes must
126
+ exist, and operations may not overlap. It validates all feature payloads and
127
+ rejects conflicts. Existing feature order is retained; new features are appended.
128
+ This is an ID-based local patch format, not RFC 6902, a server transaction, or an
129
+ optimistic concurrency protocol. The host owns revision checks when saving.
130
+
131
+ ## Verification
132
+
133
+ ```sh
134
+ npm run test:unit:focused -- tests/geojson-pipeline.spec.ts tests/geojson.spec.ts tests/geojson-more.spec.ts tests/geojson-merge.spec.ts tests/map-controller.spec.ts
135
+ npm run typecheck
136
+ npm run test:e2e -- e2e/geojson-pipeline.spec.ts --workers=1
137
+ ```
138
+
139
+ The Playwright test uses the existing irrigation harness with real Leaflet
140
+ markers. It proves invalid replacement and duplicate-ID add rejection, edits a
141
+ visible marker through Leaflet's draw-edited event, compares visible coordinates
142
+ with export, checks nested app metadata/numeric source ID restoration, and
143
+ applies the save-prompt diff back to the baseline. In shared workspaces, pass
144
+ `--output="$PAPERCLIP_RUN_SCRATCH_DIR/geojson-playwright"` to avoid another run's
145
+ Playwright output directory.
@@ -0,0 +1,77 @@
1
+ # Google Maps optional adapter spike
2
+
3
+ Status: design spike only. No Google SDK, browser key, billing account, paid tile
4
+ endpoint or runtime network request has been added to GeoKit. Core stays Leaflet
5
+
6
+ - OSM. See [provider boundary and security guidance](providers.md).
7
+
8
+ ## Package boundary
9
+
10
+ A future, separately installed package (proposed name, **not published**:
11
+ `@florasync/geokit-google-adapter`) owns SDK loading, credentials policy, vendor
12
+ terms, attribution, quota/billing controls and Google-specific cleanup. It must
13
+ not be imported by core or automatically selected as fallback. Review vendor
14
+ terms for the chosen product and map-compositing approach before implementation.
15
+ Do not fabricate a Google raster URL or treat Google imagery as a generic XYZ
16
+ endpoint.
17
+
18
+ Two possible strategies, deliberately not conflated:
19
+
20
+ 1. A vendor-permitted Leaflet-compatible basemap bridge returns a fresh Leaflet
21
+ layer through `VectorBasemapProvider.createLayer` (or raster resolution only
22
+ when the licensed product genuinely supplies that contract). It uses existing
23
+ `setBasemapAdapter` and Leaflet.draw/irrigation features without touching the
24
+ public component API. The bridge must prove visual synchronization, attribution,
25
+ map-pane ordering, pointer routing and cleanup. Google SDK capability alone is
26
+ not evidence that such a bridge is permitted or drawing-compatible.
27
+ 2. A native Google map needs an implementation of the separate
28
+ `DrawEngineAdapter<Context, Document, Command>` design port plus translation to
29
+ GeoKit GeoJSON, stable IDs, public lifecycle events, edit/delete/move and
30
+ irrigation semantics. That is a larger optional package, not part of this
31
+ basemap shim. Do not advertise native Google drawing until parity is proven.
32
+
33
+ ## Authentication and spend decision
34
+
35
+ Browser Maps SDK credentials are observable. Moving them from an HTML attribute
36
+ into a JavaScript property, an environment variable bundled at build time, or a
37
+ proxy-delivered bootstrap response does not make them secret.
38
+
39
+ - Prefer approved server-side APIs behind a narrow authenticated gateway where
40
+ supported. Keep private credentials server-side, constrain requests, enforce
41
+ quotas and redact logs. A gateway cannot hide a browser SDK key while that SDK
42
+ still requires it in the browser, nor can it bypass usage/display terms.
43
+ - A browser SDK deployment is an explicitly approved exception: separate
44
+ application/environment keys, website-origin and API restrictions, usage
45
+ monitoring, quota controls, billing alerts, documented ownership and revocation.
46
+ Budget alerts alone are not a hard spending cap. Never use server/signing keys
47
+ in the client and never provision a paid account as part of a default install.
48
+ - State key requirements as `required`, offline support conservatively as
49
+ `unsupported` unless the exact licensed product allows and implements it.
50
+ Attribution cannot be hidden by GeoKit theme configuration.
51
+ - Keep user geometry independent of vendor objects and IDs. Round-trip fixtures
52
+ through the existing GeoJSON import/export pipeline. Switching back to OSM or
53
+ custom tiles must not lose user features or depend on a paid account.
54
+
55
+ ## Executable promotion checklist
56
+
57
+ The implementation owner can start in the optional package without changing the
58
+ new core basemap method:
59
+
60
+ 1. Select exact Google product and supported SDK/version; review licensing,
61
+ attribution/display and storage restrictions. Decide bridge versus native
62
+ renderer; record why existing drawing is supported or not.
63
+ 2. Obtain explicit provisioning and billing approval before live calls. Until then,
64
+ use contract fixtures with no credentials and no vendor requests.
65
+ 3. Implement fresh layer creation and cleanup for the bridge path. Mark native
66
+ rendering/drawing unavailable unless the separate draw port passes parity.
67
+ 4. Run GeoKit's provider unit/Chromium tests plus adapter-owned browser tests for
68
+ repeated mount/remove, auth denial, quota exhaustion, network loss, restoration
69
+ to OSM, attribution, resize/pan/zoom and read-only operation.
70
+ 5. Verify exports preserve user GeoJSON/IDs; exported files and diagnostics contain
71
+ no keys, session tokens, SDK objects or paid-vendor-only identifiers.
72
+ 6. Approve cost and security controls independently of technical feasibility. Ship
73
+ optional documentation and separate dependency entrypoint; no core dependency,
74
+ default switch or auto paid fallback.
75
+
76
+ Source: [Google Maps Platform security guidance](https://developers.google.com/maps/api-security-best-practices).
77
+ This spike is not a vendor-term approval or a claim of live Google validation.
@@ -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.
package/docs/layers.md ADDED
@@ -0,0 +1,136 @@
1
+ # Named layers and layer-cake sessions
2
+
3
+ GeoKit's framework-agnostic element API exposes a detached layer registry. Existing feature CRUD, tool commands and GeoJSON defaults remain available. This is client-side map state; there is no FloraSync API integration or vendor provisioning.
4
+
5
+ ## Registry and rendering
6
+
7
+ `getLayers(): MapLayer[]` returns back-to-front records with `id`, `name`, `kind`, `visible`, `order`, `featureIds` and portable `style`. Kinds are `base`, `drawn`, `imported`, `guide` (including references), and `measurement` (persisted measurement GeoJSON overlays). The live basemap has the reserved id `base`. Temporary ruler plugin graphics are not persisted measurement features.
8
+
9
+ Each ordinary drawing becomes a drawn layer. Each import becomes a named group; a saved cake becomes one drawn group containing its editable core/ring polygon features. Group membership is independent of feature properties. A hidden group is removed from the edit/draw feature group but its features remain in the store/export.
10
+
11
+ ```ts
12
+ await map.importGeoJSON(fenceGeoJSON, {
13
+ behavior: "add",
14
+ layer: {
15
+ id: "fences",
16
+ name: "Fence reference",
17
+ kind: "guide",
18
+ style: { color: "#735aa6", dashArray: "6 4" },
19
+ },
20
+ });
21
+ await map.importGeoJSON(measurementGeoJSON, {
22
+ behavior: "add",
23
+ layer: { name: "Measured bed lengths", kind: "measurement" },
24
+ });
25
+ const layers = map.getLayers();
26
+ await map.setLayerVisibility("fences", false);
27
+ await map.setLayerStyle("fences", {
28
+ color: "#176da5",
29
+ weight: 3,
30
+ opacity: 0.8,
31
+ });
32
+ await map.reorderLayers(layers.map((layer) => layer.id).reverse());
33
+ await map.focusLayer("fences");
34
+ await map.removeLayer("fences");
35
+ ```
36
+
37
+ - `reorderLayers` requires every current id exactly once; invalid orders do not mutate state. Order applies within Leaflet's vector/marker panes; a basemap cannot cover vector overlays simply by reordering. Marker offsets also retain Leaflet's latitude-based stacking behavior.
38
+ - `focusLayer` fits its features without changing visibility. A basemap or empty group has no feature bounds, so focus is a no-op.
39
+ - `setLayerStyle` merges a portable subset: `color`, `fillColor`, `weight` (0–100), `opacity`/`fillOpacity` (0–1), `dashArray`. Invalid numeric values fail before mutation. Paths support path styling; standard image markers support opacity, not vector fill/stroke. Tile basemaps support opacity; an optional non-tile adapter may not implement opacity.
40
+ - `removeLayer` removes all member features, including hidden features. It rejects read-only mode and the basemap. Hide the basemap instead. Visibility/style/order are presentation changes and remain available in read-only mode. Guide/measurement are semantic kinds, not separate permissions; visible features still use the existing editor.
41
+ - Individual feature updates/removals and draw deletion keep membership synchronized. An empty data group disappears. An add-import with an existing feature id retains legacy upsert semantics, moving that feature into the new import group rather than drawing a duplicate.
42
+ - Subscribe to `leaflet-geokit:layers-changed` (`detail.layers`) for a sidebar. Snapshots are detached; mutate state only through the API.
43
+
44
+ ## External cake controls
45
+
46
+ The existing public tool bus activates the same circle-drawing tool used by the toolbar:
47
+
48
+ ```ts
49
+ secondaryButton.onclick = () =>
50
+ map.dispatchEvent(
51
+ new CustomEvent("leaflet-geokit:tool-command", {
52
+ detail: {
53
+ tool: "layerCake",
54
+ source: "secondary-button",
55
+ commandId: "orchard-1",
56
+ },
57
+ }),
58
+ );
59
+ map.addEventListener("tool:layer-cake:session-started", (event) => {
60
+ renderSidebar(event.detail.session);
61
+ });
62
+ ```
63
+
64
+ The map must enable `draw-layer-cake`. Draw the first circle to begin a session. `getLayerCakeSession()` returns null before/after the session, otherwise `{ id, name, center, rings: [{ radius }], style }`. Distances are meters regardless of the ruler's display units.
65
+
66
+ ```ts
67
+ await map.updateLayerCakeSession({
68
+ name: "Orchard water zones",
69
+ radii: [100, 150, 225],
70
+ preset: "water",
71
+ });
72
+ await map.saveLayerCakeSession(); // Same save operation as the map's Save button.
73
+ // Or: await map.cancelLayerCakeSession();
74
+ ```
75
+
76
+ `radii` must have one to ten strictly increasing positive finite values. Updating replaces the session's editable circle handles; dragging those handles also updates the session. The circles keep a shared center. `name`, `radii`, `preset`, and `style` can be updated independently. Built-in presets are `crop`, `water`, and `reference`, also exported as `LAYER_STYLE_PRESETS`. Explicit style fields override the chosen preset.
77
+
78
+ Session events are DOM events on the element (bubbling/composed), and also remain available through `toolHooks`/`toolEventEmitter`:
79
+
80
+ - `tool:layer-cake:session-started`
81
+ - `tool:layer-cake:session-changed` (ring controls/dragging/sidebar edits)
82
+ - `tool:layer-cake:saved` (adds `layerId`, `featureCollection`)
83
+ - `tool:layer-cake:cancelled` (draft discarded)
84
+
85
+ Their `LayerCakeEventDetail` contains `session` and the initiating command's `source`, `commandId`, `groupId` when available. The original started event's `center`/`radius` fields and saved event's `featureCollection` remain compatible. These events supplement, not replace, the correlated `leaflet-geokit:tool-*` lifecycle. Save produces named core/ring polygons using the existing cake baker; standard polygon edit/move works afterward. Session radii are draft controls, not a reconstruction API for an already-saved cake. Cancellation, Escape, a superseding tool, clearing data, and destruction dispose draft handles/listeners. Updating/saving a missing session rejects; cancellation without a session is harmless.
86
+
87
+ ## Style panel: built in or host-owned
88
+
89
+ ```ts
90
+ map.dispatchEvent(
91
+ new CustomEvent("leaflet-geokit:tool-command", {
92
+ detail: { tool: "layerStyle", source: "sidebar" },
93
+ }),
94
+ );
95
+ ```
96
+
97
+ Without a host override this opens a compact layer selector and preset panel. It uses `part="layer-style-panel"`, `--geokit-panel-background`, and `--geokit-panel-color`. Escape/Close dismiss it and restore focus. `layerStyle`'s tool-completed event still means the panel request was handled, not that a style has been saved.
98
+
99
+ To render the editor anywhere outside the component:
100
+
101
+ ```ts
102
+ map.addEventListener("leaflet-geokit:layer-style-request", (event) => {
103
+ event.preventDefault(); // Synchronous cancellation suppresses the built-in panel.
104
+ renderHostPanel(event.detail.layers, async (id, style) => {
105
+ await map.setLayerStyle(id, style);
106
+ });
107
+ });
108
+ ```
109
+
110
+ `LayerStyleRequestDetail` is a detached snapshot; subscribe to layers-changed if a host panel needs live updates. Closing a host-owned panel is the host's responsibility. No framework or DOM node is required in the public data model.
111
+
112
+ ## Optional export/import persistence
113
+
114
+ ```ts
115
+ const snapshot = await map.exportGeoJSON({ preserveLayers: true });
116
+ await map.importGeoJSON(JSON.parse(JSON.stringify(snapshot)), {
117
+ behavior: "replace",
118
+ preserveLayers: true,
119
+ });
120
+ ```
121
+
122
+ The versioned FeatureCollection foreign member `geokit:layers` stores the registry, including order, visibility, style, names and membership. It contains no URLs, provider keys or Leaflet objects. Basemap presentation is restored, not provider configuration. Default export remains ordinary GeoJSON. Default import ignores registry metadata and groups the imported features normally. Use `preserveLayers` on **both** ends. `getGeoJSON()` remains a feature-only store snapshot.
123
+
124
+ Restoration requires replace mode, unique known feature membership, complete feature coverage and the reserved base record. Missing/invalid metadata fails before clearing current data. `preserveLayers` with add mode is deliberately rejected: silently merging conflicting layer ids/order would be ambiguous. It also works with the source export adapter when expanded feature ids remain reconstructible by the existing GeoJSON pipeline. External tools that strip foreign members lose layer presentation metadata; geometry/properties remain standard GeoJSON. Do not rely on JSON object property key order when comparing snapshots.
125
+
126
+ ## Exercised harness and checks
127
+
128
+ `npm run dev`, then open `/layer-manager.html`. The host sidebar uses only public APIs and events: secondary cake button, ring edits, save/cancel, built-in and host-owned style panels, visibility and export/restore.
129
+
130
+ ```sh
131
+ npm run typecheck
132
+ npm run test:unit:focused -- tests/layer-registry.spec.ts tests/layer-cake-manager.spec.ts tests/map-controller.spec.ts tests/tool-lifecycle.spec.ts
133
+ npx playwright test -c playwright.layers.config.ts
134
+ ```
135
+
136
+ The isolated Playwright server uses port 5191, no HMR, Chromium and deterministic tile responses for the new harness. It proves actual circle drawing/handles, sidebar session edits/save/cancel, SVG styles, hidden physical layers, exact structural registry restoration, and legacy irrigation tool-bus interaction. Public tile network availability is not part of that assertion.