@gugell/nitro-ui-maps-maplibre 0.2.1 → 0.3.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#7](https://github.com/gugell/nitro-ui-maps/pull/7) [`70d2a07`](https://github.com/gugell/nitro-ui-maps/commit/70d2a0750e457622e330f49523bcbd120a533058) Thanks [@gugell](https://github.com/gugell)! - Engines are objects you create and pass to a view, the way a camera library passes a device.
8
+
9
+ - `createMapLibreEngine(options)` replaces `maplibre(options)`; `createMapEngine(definition)` replaces `defineMapEngine`.
10
+ - `<MapView engine={engine} />` draws with that engine and types its own props (MapLibre's `mapStyle`, `layers`, …). `<MapProvider engine>` and `createMapView(engine)` still work.
11
+ - `getMapEngine(engines, { needs, glyphs })` and `useMapEngine(engines, filter)` pick the engine that best fits what a screen needs. They rank the engines and never drop one, so a list always yields an engine.
12
+ - `MapMarker.selectedIcon`: the icon a selected marker draws. Markers no longer have to change when the selection does, so a pick redraws only the selected marker.
13
+ - No casts between engine types: an engine with its own props fits wherever a `MapEngine` goes.
14
+
15
+ ### Patch Changes
16
+
17
+ - [#5](https://github.com/gugell/nitro-ui-maps/pull/5) [`c54a0c4`](https://github.com/gugell/nitro-ui-maps/commit/c54a0c4d91581371ac2f9bb1d012ccd55649e96b) Thanks [@gugell](https://github.com/gugell)! - Published on npm (with provenance) instead of GitHub Packages: install with no registry setup or token.
18
+ - Updated dependencies [[`70d2a07`](https://github.com/gugell/nitro-ui-maps/commit/70d2a0750e457622e330f49523bcbd120a533058), [`c54a0c4`](https://github.com/gugell/nitro-ui-maps/commit/c54a0c4d91581371ac2f9bb1d012ccd55649e96b)]:
19
+ - @gugell/nitro-ui-maps@0.3.0
20
+
3
21
  ## 0.2.1
4
22
 
5
23
  ### Patch Changes
package/README.md CHANGED
@@ -6,12 +6,12 @@ zoom, rotate, pitch). Markers are GeoJSON points drawn by style layers, so thous
6
6
  one source update, not thousands of views. No API key needed: by default it shows OpenStreetMap's
7
7
  raster tiles.
8
8
 
9
- | | |
10
- | --- | --- |
11
- | iOS | MapLibre Native 6.26.0 (Swift Package `maplibre-gl-native-distribution`) |
12
- | Android | `org.maplibre.gl:android-sdk-opengl:13.2.0` (Maven Central) |
13
- | NitroUI | `nitro-ui-renderer` 0.3 or 0.4, `nitro-core` (the version your app pins) |
14
- | Native module | `NitroMapLibre`, host view `NitroMapLibreView` |
9
+ | | |
10
+ | ------------- | ------------------------------------------------------------------------ |
11
+ | iOS | MapLibre Native 6.26.0 (Swift Package `maplibre-gl-native-distribution`) |
12
+ | Android | `org.maplibre.gl:android-sdk-opengl:13.2.0` (Maven Central) |
13
+ | NitroUI | `nitro-ui-renderer` 0.3 or 0.4, `nitro-core` (the version your app pins) |
14
+ | Native module | `NitroMapLibre`, host view `NitroMapLibreView` |
15
15
 
16
16
  ## Install
17
17
 
@@ -35,19 +35,21 @@ The map never asks for the location by itself; `locateUser()` asks the first tim
35
35
 
36
36
  ## Use
37
37
 
38
+ Documentation: [MapLibre Native](https://gugell.github.io/nitro-ui-maps/engines/maplibre)
39
+
38
40
  ```tsx
39
- import { createMapView } from '@gugell/nitro-ui-maps'
40
- import { OSM_RASTER_STYLE, maplibre } from '@gugell/nitro-ui-maps-maplibre'
41
-
42
- const CityMap = createMapView(
43
- maplibre({
44
- fallbackStyle: OSM_RASTER_STYLE,
45
- onStyleError: (error) => console.warn(error.message),
46
- layers: { clusterCount: { paint: { 'text-halo-color': 'rgba(0,0,0,0.15)', 'text-halo-width': 1 } } },
47
- }),
48
- )
49
-
50
- <CityMap
41
+ import { MapView } from '@gugell/nitro-ui-maps'
42
+ import { OSM_RASTER_STYLE, createMapLibreEngine } from '@gugell/nitro-ui-maps-maplibre'
43
+
44
+ // Module scope: each call makes a new view component.
45
+ const engine = createMapLibreEngine({
46
+ fallbackStyle: OSM_RASTER_STYLE,
47
+ onStyleError: (error) => console.warn(error.message),
48
+ layers: { clusterCount: { paint: { 'text-halo-color': 'rgba(0,0,0,0.15)', 'text-halo-width': 1 } } },
49
+ })
50
+
51
+ <MapView
52
+ engine={engine}
51
53
  layout={{ flex: 1 }}
52
54
  mapStyle={styleUrl}
53
55
  camera={camera}
@@ -59,22 +61,20 @@ const CityMap = createMapView(
59
61
  />
60
62
  ```
61
63
 
62
- ### Engine options (`maplibre(options)`)
63
-
64
- | Option | What it does |
65
- | --- | --- |
66
- | `defaultStyle` | The style a view draws without `mapStyle`. Default `OSM_RASTER_STYLE`. |
67
- | `fallbackStyle` | Drawn when a style URL can't be read. Default `OSM_RASTER_STYLE`. |
68
- | `fetchStyle`, `onStyleError` | How style URLs are read (default `fetch`), and the failure report. |
69
- | `textFont` | The font stack of cluster counts; the style must serve it. Default `['Noto Sans Regular']`. |
70
- | `layers` | MapLibre `paint` / `layout` merged over the built `point`, `cluster` and `clusterCount` layers: data-driven colours (`['get', 'category']` from marker `properties`), halos, anything the shared options don't say. |
64
+ ### Engine options (`createMapLibreEngine(options)`)
71
65
 
72
- Call `maplibre()` once at module scope: each call makes a new view component.
66
+ | Option | What it does |
67
+ | ---------------------------- | ----------------------------------------------------------------------------------------------- |
68
+ | `defaultStyle` | The style a view draws without `mapStyle`. Default `OSM_RASTER_STYLE`. |
69
+ | `fallbackStyle` | Drawn when a style URL can't be read. Default `OSM_RASTER_STYLE`. |
70
+ | `fetchStyle`, `onStyleError` | How style URLs are read (default `fetch`), and the failure report. |
71
+ | `textFont` | The font stack of cluster counts; the style must serve it. Default `['Noto Sans Regular']`. |
72
+ | `layers` | MapLibre `paint` / `layout` merged over the built `point`, `cluster` and `clusterCount` layers. |
73
73
 
74
- ### View props (`createMapView(engine)`)
74
+ ### View props
75
75
 
76
- | Prop | What it does |
77
- | --- | --- |
76
+ | Prop | What it does |
77
+ | ---------- | ------------------------------------------------------------------------------------------- |
78
78
  | `mapStyle` | A MapLibre style object, or a style URL (read in JS so the marker layers can be merged in). |
79
79
 
80
80
  Plus every shared option of the core's `MapView`.
@@ -89,7 +89,7 @@ secret key there.
89
89
 
90
90
  ### Lower-level helpers
91
91
 
92
- `markerSources`, `markerLayers`, `withMarkerLayers`, `markerLayerPaints`, `clusterLayerPaints`,
92
+ `markersGeoJSON`, `markerLayers`, `withMarkerLayers`, `markerLayerPaints`, `clusterLayerPaints`,
93
93
  `pointLayerPaint`, `cssColor`, `loadStyle` and `useMapStyle`: what the view builds, for tests or a
94
94
  custom view.
95
95
 
package/package.json CHANGED
@@ -1,44 +1,54 @@
1
1
  {
2
2
  "name": "@gugell/nitro-ui-maps-maplibre",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "The MapLibre Native engine for @gugell/nitro-ui-maps: native pan, pinch, rotate and double-tap, GeoJSON markers with clustering, any MapLibre style, the user's location.",
5
5
  "keywords": [
6
- "nitro-ui",
7
- "nitroui",
8
- "nitro",
9
- "nitro-modules",
10
- "maplibre",
6
+ "android",
7
+ "ios",
11
8
  "map",
9
+ "maplibre",
12
10
  "maps",
13
- "ios",
14
- "android"
11
+ "nitro",
12
+ "nitro-modules",
13
+ "nitro-ui",
14
+ "nitroui"
15
15
  ],
16
- "license": "MIT",
17
16
  "homepage": "https://github.com/gugell/nitro-ui-maps#readme",
18
17
  "bugs": {
19
18
  "url": "https://github.com/gugell/nitro-ui-maps/issues"
20
19
  },
20
+ "license": "MIT",
21
21
  "repository": {
22
22
  "type": "git",
23
23
  "url": "git+https://github.com/gugell/nitro-ui-maps.git",
24
24
  "directory": "packages/maplibre"
25
25
  },
26
+ "files": [
27
+ "src",
28
+ "!src/**/*.test.ts",
29
+ "Package.swift",
30
+ "ios",
31
+ "android/build.gradle",
32
+ "android/src",
33
+ "nitrogen/generated",
34
+ "nitro.json",
35
+ "README.md",
36
+ "CHANGELOG.md",
37
+ "LICENSE"
38
+ ],
26
39
  "type": "module",
40
+ "imports": {
41
+ "#nitro/*": "./nitrogen/generated/shared/javascript/*.cjs"
42
+ },
27
43
  "exports": {
28
44
  ".": "./src/index.ts",
29
45
  "./package.json": "./package.json"
30
46
  },
31
- "imports": {
32
- "#nitro/*": "./nitrogen/generated/shared/javascript/*.cjs"
33
- },
34
- "peerDependencies": {
35
- "@gugell/nitro-ui-maps": "^0.2.1",
36
- "nitro-core": "1.0.0-alpha.nightly.137.gd4793c40b8b8",
37
- "nitro-ui-renderer": ">=0.3.0 <0.5.0",
38
- "react": ">=19.3.0"
47
+ "publishConfig": {
48
+ "access": "public"
39
49
  },
40
50
  "devDependencies": {
41
- "@gugell/nitro-ui-maps": "0.2.1",
51
+ "@gugell/nitro-ui-maps": "0.3.0",
42
52
  "@types/react": "19.3.0",
43
53
  "nitro-core": "1.0.0-alpha.nightly.137.gd4793c40b8b8",
44
54
  "nitro-ui-renderer": "0.3.0",
@@ -47,22 +57,12 @@
47
57
  "typescript": "7.0.2",
48
58
  "vitest": "4.1.12"
49
59
  },
50
- "publishConfig": {
51
- "access": "public"
60
+ "peerDependencies": {
61
+ "@gugell/nitro-ui-maps": "^0.3.0",
62
+ "nitro-core": "1.0.0-alpha.nightly.137.gd4793c40b8b8",
63
+ "nitro-ui-renderer": ">=0.3.0 <0.5.0",
64
+ "react": ">=19.3.0"
52
65
  },
53
- "files": [
54
- "src",
55
- "!src/**/*.test.ts",
56
- "Package.swift",
57
- "ios",
58
- "android/build.gradle",
59
- "android/src",
60
- "nitrogen/generated",
61
- "nitro.json",
62
- "README.md",
63
- "CHANGELOG.md",
64
- "LICENSE"
65
- ],
66
66
  "scripts": {
67
67
  "test": "vitest run",
68
68
  "typecheck": "tsc --noEmit -p tsconfig.json",
@@ -2,7 +2,14 @@ import { useImperativeHandle, useMemo, useRef } from 'react'
2
2
  import { processColor } from 'nitro-ui-renderer'
3
3
  import type { MapEngineViewProps } from '@gugell/nitro-ui-maps'
4
4
  import { MapLibreHost } from './host'
5
- import { markerLayerFilters, markersGeoJSON, MARKERS_SOURCE, PRESSABLE_LAYERS, SELECTED_SOURCE, withMarkerLayers } from './layers'
5
+ import {
6
+ markerLayerFilters,
7
+ markersGeoJSON,
8
+ MARKERS_SOURCE,
9
+ PRESSABLE_LAYERS,
10
+ SELECTED_SOURCE,
11
+ withMarkerLayers,
12
+ } from './layers'
6
13
  import { nativeImageOf } from './nativeImage'
7
14
  import { cssColor } from './cssColor'
8
15
  import { markerLayerPaints } from './paint'
@@ -20,27 +27,54 @@ export function createMapLibreView(options: MapLibreEngineOptions) {
20
27
  const fallbackStyle = options.fallbackStyle ?? OSM_RASTER_STYLE
21
28
 
22
29
  function MapLibreView(props: MapEngineViewProps<MapLibreViewProps>) {
23
- const { mapStyle, camera, markers, selectedMarkerId, markerIcons, pointStyle, clustering, gestures, userLocation, insets, attribution, ref, ...rest } = props
30
+ const {
31
+ mapStyle,
32
+ camera,
33
+ markers,
34
+ selectedMarkerId,
35
+ markerIcons,
36
+ pointStyle,
37
+ clustering,
38
+ gestures,
39
+ userLocation,
40
+ insets,
41
+ attribution,
42
+ ref,
43
+ ...rest
44
+ } = props
24
45
  const host = useRef<NativeMapView>(null)
25
- useImperativeHandle(ref, () => ({
26
- locateUser: (zoom) => {
27
- const view = host.current
28
- return view ? view.locateUser(zoom) : Promise.resolve('unavailable')
29
- },
30
- }), [])
46
+ useImperativeHandle(
47
+ ref,
48
+ () => ({
49
+ locateUser: (zoom) => {
50
+ const view = host.current
51
+ return view ? view.locateUser(zoom) : Promise.resolve('unavailable')
52
+ },
53
+ }),
54
+ [],
55
+ )
31
56
  const base = useMapStyle(mapStyle ?? defaultStyle, fallbackStyle, options.fetchStyle, options.onStyleError)
32
- const paints = useMemo(() => markerLayerPaints({ pointStyle, clustering }, options, cssColor), [pointStyle, clustering])
57
+ const paints = useMemo(
58
+ () => markerLayerPaints({ pointStyle, clustering }, options, cssColor),
59
+ [pointStyle, clustering],
60
+ )
33
61
  const styleJSON = useMemo(() => (base ? JSON.stringify(withMarkerLayers(base, paints)) : ''), [base, paints])
34
62
  // Picking a marker changes a filter and the one-marker source; the source of every marker is
35
63
  // rebuilt only when the markers change, from features cached per marker object.
36
64
  const markersJSON = useMemo(() => markersGeoJSON(markers, false), [markers])
37
- const selected = useMemo(() => markers.find((marker) => marker.id === selectedMarkerId), [markers, selectedMarkerId])
65
+ const selected = useMemo(
66
+ () => markers.find((marker) => marker.id === selectedMarkerId),
67
+ [markers, selectedMarkerId],
68
+ )
38
69
  const selectedJSON = useMemo(() => markersGeoJSON(selected ? [selected] : [], true), [selected])
39
70
  const sources = useSourceUpdates([
40
71
  { sourceId: MARKERS_SOURCE, geoJSON: markersJSON },
41
72
  { sourceId: SELECTED_SOURCE, geoJSON: selectedJSON },
42
73
  ])
43
- const layerFilters = useMemo(() => markerLayerFilters(clustering !== null, selected?.id ?? null), [clustering, selected])
74
+ const layerFilters = useMemo(
75
+ () => markerLayerFilters(clustering !== null, selected?.id ?? null),
76
+ [clustering, selected],
77
+ )
44
78
  const images = useMemo(() => markerIcons.map(nativeImageOf), [markerIcons])
45
79
  return (
46
80
  <MapLibreHost
package/src/host.ts CHANGED
@@ -43,21 +43,55 @@ declare module 'nitro-ui-renderer' {
43
43
 
44
44
  export const MapLibreHost = registerView('NitroMapLibreView', () => new NativeMapView(), {
45
45
  ...viewPropsSetters,
46
- styleJSON: (view, json) => { view.styleJSON = json },
47
- sources: (view, sources) => { view.sources = sources },
48
- images: (view, images) => { view.images = images },
49
- layerFilters: (view, filters) => { view.layerFilters = filters },
50
- pressableLayerIds: (view, ids) => { view.pressableLayerIds = ids },
51
- camera: (view, camera) => { view.camera = camera },
52
- insets: (view, insets) => { view.insets = insets },
53
- scrollEnabled: (view, on) => { view.scrollEnabled = on },
54
- zoomEnabled: (view, on) => { view.zoomEnabled = on },
55
- rotateEnabled: (view, on) => { view.rotateEnabled = on },
56
- pitchEnabled: (view, on) => { view.pitchEnabled = on },
57
- showsUserLocation: (view, on) => { view.showsUserLocation = on },
58
- userLocationColor: (view, color) => { view.userLocationColor = color },
59
- attributionVisible: (view, on) => { view.attributionVisible = on },
60
- onCameraChange: (view, callback) => { view.onCameraChange = callback },
61
- onMarkerPress: (view, callback) => { view.onMarkerPress = callback },
62
- onMapPress: (view, callback) => { view.onMapPress = callback },
46
+ styleJSON: (view, json) => {
47
+ view.styleJSON = json
48
+ },
49
+ sources: (view, sources) => {
50
+ view.sources = sources
51
+ },
52
+ images: (view, images) => {
53
+ view.images = images
54
+ },
55
+ layerFilters: (view, filters) => {
56
+ view.layerFilters = filters
57
+ },
58
+ pressableLayerIds: (view, ids) => {
59
+ view.pressableLayerIds = ids
60
+ },
61
+ camera: (view, camera) => {
62
+ view.camera = camera
63
+ },
64
+ insets: (view, insets) => {
65
+ view.insets = insets
66
+ },
67
+ scrollEnabled: (view, on) => {
68
+ view.scrollEnabled = on
69
+ },
70
+ zoomEnabled: (view, on) => {
71
+ view.zoomEnabled = on
72
+ },
73
+ rotateEnabled: (view, on) => {
74
+ view.rotateEnabled = on
75
+ },
76
+ pitchEnabled: (view, on) => {
77
+ view.pitchEnabled = on
78
+ },
79
+ showsUserLocation: (view, on) => {
80
+ view.showsUserLocation = on
81
+ },
82
+ userLocationColor: (view, color) => {
83
+ view.userLocationColor = color
84
+ },
85
+ attributionVisible: (view, on) => {
86
+ view.attributionVisible = on
87
+ },
88
+ onCameraChange: (view, callback) => {
89
+ view.onCameraChange = callback
90
+ },
91
+ onMarkerPress: (view, callback) => {
92
+ view.onMarkerPress = callback
93
+ },
94
+ onMapPress: (view, callback) => {
95
+ view.onMapPress = callback
96
+ },
63
97
  })
package/src/index.ts CHANGED
@@ -1,9 +1,19 @@
1
1
  // @gugell/nitro-ui-maps-maplibre: the MapLibre Native engine for @gugell/nitro-ui-maps.
2
- export { maplibre, MAPLIBRE_CAPABILITIES } from './maplibre'
2
+ export { createMapLibreEngine, MAPLIBRE_CAPABILITIES, type MapLibreEngine } from './maplibre'
3
3
  export { OSM_RASTER_STYLE, loadStyle } from './style'
4
4
  export { useMapStyle } from './useMapStyle'
5
5
  export { DEFAULT_TEXT_FONT, clusterLayerPaints, markerLayerPaints, pointLayerPaint } from './paint'
6
6
  export { cssColor } from './cssColor'
7
- export { MARKER_LAYERS, MARKERS_SOURCE, PRESSABLE_LAYERS, SELECTED_SOURCE, markerFilters, markerLayerFilters, markerLayers, markersGeoJSON, withMarkerLayers } from './layers'
7
+ export {
8
+ MARKER_LAYERS,
9
+ MARKERS_SOURCE,
10
+ PRESSABLE_LAYERS,
11
+ SELECTED_SOURCE,
12
+ markerFilters,
13
+ markerLayerFilters,
14
+ markerLayers,
15
+ markersGeoJSON,
16
+ withMarkerLayers,
17
+ } from './layers'
8
18
  export type * from './types'
9
19
  export { changedSources, useSourceUpdates } from './useSourceUpdates'
package/src/layers.ts CHANGED
@@ -4,7 +4,15 @@
4
4
  // and hidden from the lower layers by their filter, so picking a marker changes a filter and that
5
5
  // small source, never the source of every marker. Pure: the view sends what these build to native.
6
6
  import type { MapMarker } from '@gugell/nitro-ui-maps'
7
- import type { MapFeatureProperties, MapLayer, MapLayerFilterData, MapStyle, MarkerFeature, MarkerFeatureCollection, MarkerLayerPaints } from './types'
7
+ import type {
8
+ MapFeatureProperties,
9
+ MapLayer,
10
+ MapLayerFilterData,
11
+ MapStyle,
12
+ MarkerFeature,
13
+ MarkerFeatureCollection,
14
+ MarkerLayerPaints,
15
+ } from './types'
8
16
 
9
17
  /** The (clustered) source of every marker. */
10
18
  export const MARKERS_SOURCE = 'nitro-maps-markers'
@@ -68,8 +76,14 @@ const featureJSON = (marker: MapMarker, selected: boolean): string => {
68
76
  const cached = cache.get(marker)
69
77
  if (cached !== undefined) return cached
70
78
  const properties: MapFeatureProperties = { ...marker.properties, markerId: marker.id, selected }
71
- if (marker.icon) properties.icon = marker.icon
72
- const feature: MarkerFeature = { type: 'Feature', id: marker.id, geometry: { type: 'Point', coordinates: [marker.coordinate.longitude, marker.coordinate.latitude] }, properties }
79
+ const icon = selected ? (marker.selectedIcon ?? marker.icon) : marker.icon
80
+ if (icon) properties.icon = icon
81
+ const feature: MarkerFeature = {
82
+ type: 'Feature',
83
+ id: marker.id,
84
+ geometry: { type: 'Point', coordinates: [marker.coordinate.longitude, marker.coordinate.latitude] },
85
+ properties,
86
+ }
73
87
  const json = JSON.stringify(feature)
74
88
  cache.set(marker, json)
75
89
  return json
@@ -89,16 +103,44 @@ export function markerLayers(paints: MarkerLayerPaints): MapLayer[] {
89
103
  const layers: MapLayer[] = []
90
104
  if (cluster) {
91
105
  layers.push(
92
- { id: MARKER_LAYERS.clusters, type: 'circle', source: MARKERS_SOURCE, filter: CLUSTERED, paint: cluster.circle.paint ?? {}, layout: cluster.circle.layout ?? {} },
93
- { id: MARKER_LAYERS.clusterCount, type: 'symbol', source: MARKERS_SOURCE, filter: CLUSTERED, paint: cluster.count.paint ?? {}, layout: cluster.count.layout ?? {} },
106
+ {
107
+ id: MARKER_LAYERS.clusters,
108
+ type: 'circle',
109
+ source: MARKERS_SOURCE,
110
+ filter: CLUSTERED,
111
+ paint: cluster.circle.paint ?? {},
112
+ layout: cluster.circle.layout ?? {},
113
+ },
114
+ {
115
+ id: MARKER_LAYERS.clusterCount,
116
+ type: 'symbol',
117
+ source: MARKERS_SOURCE,
118
+ filter: CLUSTERED,
119
+ paint: cluster.count.paint ?? {},
120
+ layout: cluster.count.layout ?? {},
121
+ },
94
122
  )
95
123
  }
96
124
  const pointPaint = point.paint ?? {}
97
125
  const pointLayout = point.layout ?? {}
98
126
  layers.push(
99
- { id: MARKER_LAYERS.points, type: 'circle', source: MARKERS_SOURCE, filter: filters.points, paint: pointPaint, layout: pointLayout },
127
+ {
128
+ id: MARKER_LAYERS.points,
129
+ type: 'circle',
130
+ source: MARKERS_SOURCE,
131
+ filter: filters.points,
132
+ paint: pointPaint,
133
+ layout: pointLayout,
134
+ },
100
135
  { id: MARKER_LAYERS.icons, type: 'symbol', source: MARKERS_SOURCE, filter: filters.icons, layout: ICON_LAYOUT },
101
- { id: MARKER_LAYERS.selectedPoint, type: 'circle', source: SELECTED_SOURCE, filter: NO_ICON, paint: pointPaint, layout: pointLayout },
136
+ {
137
+ id: MARKER_LAYERS.selectedPoint,
138
+ type: 'circle',
139
+ source: SELECTED_SOURCE,
140
+ filter: NO_ICON,
141
+ paint: pointPaint,
142
+ layout: pointLayout,
143
+ },
102
144
  { id: MARKER_LAYERS.selectedIcon, type: 'symbol', source: SELECTED_SOURCE, filter: HAS_ICON, layout: ICON_LAYOUT },
103
145
  )
104
146
  return layers
@@ -109,7 +151,9 @@ const EMPTY: MarkerFeatureCollection = { type: 'FeatureCollection', features: []
109
151
  /** The style with the marker sources (empty: the native map fills them) and layers on top of its own. */
110
152
  export function withMarkerLayers(style: MapStyle, paints: MarkerLayerPaints): MapStyle {
111
153
  const cluster = paints.cluster
112
- const markers = cluster ? { type: 'geojson', data: EMPTY, cluster: true, clusterRadius: cluster.radius, clusterMaxZoom: cluster.maxZoom } : { type: 'geojson', data: EMPTY }
154
+ const markers = cluster
155
+ ? { type: 'geojson', data: EMPTY, cluster: true, clusterRadius: cluster.radius, clusterMaxZoom: cluster.maxZoom }
156
+ : { type: 'geojson', data: EMPTY }
113
157
  return {
114
158
  ...style,
115
159
  sources: { ...style.sources, [MARKERS_SOURCE]: markers, [SELECTED_SOURCE]: { type: 'geojson', data: EMPTY } },
package/src/maplibre.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { defineMapEngine } from '@gugell/nitro-ui-maps'
1
+ import { createMapEngine } from '@gugell/nitro-ui-maps'
2
2
  import type { MapEngine, MapEngineCapabilities } from '@gugell/nitro-ui-maps'
3
3
  import { createMapLibreView } from './MapLibreView'
4
4
  import type { MapLibreEngineOptions, MapLibreViewProps } from './types'
@@ -12,14 +12,21 @@ export const MAPLIBRE_CAPABILITIES: MapEngineCapabilities = {
12
12
  glyphs: ['sfSymbol', 'androidDrawable'],
13
13
  }
14
14
 
15
+ /** The MapLibre Native engine: its views take `mapStyle` next to the shared props. */
16
+ export type MapLibreEngine = MapEngine<MapLibreViewProps>
17
+
15
18
  /**
16
- * The MapLibre Native engine, configured. Call once at module scope and keep the engine: each call
17
- * makes a new view component, so a new engine in a render remounts the native map.
19
+ * Creates the MapLibre Native engine with this configuration. Create it once at module scope and
20
+ * keep it: each call makes a new view component, so an engine created in a render remounts the map.
18
21
  *
19
- * const engine = maplibre({ fallbackStyle, layers: { clusterCount: { paint: { 'text-halo-width': 1 } } } })
20
- * <MapProvider engine={engine}>…</MapProvider> // screens use MapView
21
- * const CityMap = createMapView(engine) // or a view that takes mapStyle, typed
22
+ * export const mapEngine = createMapLibreEngine({ fallbackStyle })
23
+ * <MapView engine={mapEngine} mapStyle={styleUrl} markers={markers} clustering />
22
24
  */
23
- export function maplibre(options: MapLibreEngineOptions = {}): MapEngine<MapLibreViewProps> {
24
- return defineMapEngine<MapLibreViewProps>({ id: 'maplibre', capabilities: MAPLIBRE_CAPABILITIES, View: createMapLibreView(options) })
25
+ export function createMapLibreEngine(options: MapLibreEngineOptions = {}): MapLibreEngine {
26
+ return createMapEngine<MapLibreViewProps>({
27
+ id: 'maplibre',
28
+ name: 'MapLibre Native',
29
+ capabilities: MAPLIBRE_CAPABILITIES,
30
+ View: createMapLibreView(options),
31
+ })
25
32
  }
package/src/paint.ts CHANGED
@@ -2,7 +2,13 @@
2
2
  // symbol layer paint. The engine's layer overrides are merged last, for what the options can't say.
3
3
  // Pure; colours go through `color` (cssColor in the app) so this runs without the renderer.
4
4
  import type { MapClusterStyle, MapPointStyle, ResolvedMapViewOptions } from '@gugell/nitro-ui-maps'
5
- import type { ClusterLayerPaints, MapLibreEngineOptions, MapLibreLayerOverride, MarkerLayerPaints, StyleColor } from './types'
5
+ import type {
6
+ ClusterLayerPaints,
7
+ MapLibreEngineOptions,
8
+ MapLibreLayerOverride,
9
+ MarkerLayerPaints,
10
+ StyleColor,
11
+ } from './types'
6
12
 
7
13
  /** The font stack cluster counts use unless the engine names another (the default OSM style serves it). */
8
14
  export const DEFAULT_TEXT_FONT: readonly string[] = ['Noto Sans Regular']
@@ -20,16 +26,25 @@ export function pointLayerPaint(style: MapPointStyle, color: StyleColor): MapLib
20
26
  }
21
27
 
22
28
  /** A `step` expression over the cluster's point count: the first step's value, then each later step from its minCount. */
23
- const byCount = (cluster: MapClusterStyle, value: (step: MapClusterStyle['steps'][number]) => string | number): unknown[] => {
29
+ const byCount = (
30
+ cluster: MapClusterStyle,
31
+ value: (step: MapClusterStyle['steps'][number]) => string | number,
32
+ ): unknown[] => {
24
33
  const [first, ...rest] = cluster.steps
25
34
  if (!first) throw new Error('A cluster style needs at least one step')
26
- return rest.length === 0 ? [value(first)] : ['step', ['get', 'point_count'], value(first), ...rest.flatMap((step) => [step.minCount, value(step)])]
35
+ return rest.length === 0
36
+ ? [value(first)]
37
+ : ['step', ['get', 'point_count'], value(first), ...rest.flatMap((step) => [step.minCount, value(step)])]
27
38
  }
28
39
 
29
40
  const unwrap = (expression: unknown[]): unknown => (expression.length === 1 ? expression[0] : expression)
30
41
 
31
42
  /** The cluster source's settings and the paint of its bubbles and counts. */
32
- export function clusterLayerPaints(cluster: MapClusterStyle, color: StyleColor, textFont: readonly string[]): ClusterLayerPaints {
43
+ export function clusterLayerPaints(
44
+ cluster: MapClusterStyle,
45
+ color: StyleColor,
46
+ textFont: readonly string[],
47
+ ): ClusterLayerPaints {
33
48
  return {
34
49
  radius: cluster.radius,
35
50
  maxZoom: cluster.maxZoom,
@@ -66,5 +81,12 @@ export function markerLayerPaints(
66
81
  const point = merged(pointLayerPaint(options.pointStyle, color), overrides?.point)
67
82
  if (!options.clustering) return { point, cluster: null }
68
83
  const cluster = clusterLayerPaints(options.clustering, color, engine.textFont ?? DEFAULT_TEXT_FONT)
69
- return { point, cluster: { ...cluster, circle: merged(cluster.circle, overrides?.cluster), count: merged(cluster.count, overrides?.clusterCount) } }
84
+ return {
85
+ point,
86
+ cluster: {
87
+ ...cluster,
88
+ circle: merged(cluster.circle, overrides?.cluster),
89
+ count: merged(cluster.count, overrides?.clusterCount),
90
+ },
91
+ }
70
92
  }
package/src/style.ts CHANGED
@@ -7,7 +7,12 @@ export const OSM_RASTER_STYLE: MapStyle = {
7
7
  version: 8,
8
8
  glyphs: 'https://demotiles.maplibre.org/font/{fontstack}/{range}.pbf',
9
9
  sources: {
10
- osm: { type: 'raster', tiles: ['https://tile.openstreetmap.org/{z}/{x}/{y}.png'], tileSize: 256, attribution: '© OpenStreetMap contributors' },
10
+ osm: {
11
+ type: 'raster',
12
+ tiles: ['https://tile.openstreetmap.org/{z}/{x}/{y}.png'],
13
+ tileSize: 256,
14
+ attribution: '© OpenStreetMap contributors',
15
+ },
11
16
  },
12
17
  layers: [{ id: 'osm-tiles', type: 'raster', source: 'osm' }],
13
18
  }
@@ -15,7 +20,9 @@ export const OSM_RASTER_STYLE: MapStyle = {
15
20
  const isStyle = (value: unknown): value is MapStyle => {
16
21
  if (typeof value !== 'object' || value === null) return false
17
22
  const style = value as Partial<MapStyle>
18
- return style.version === 8 && typeof style.sources === 'object' && style.sources !== null && Array.isArray(style.layers)
23
+ return (
24
+ style.version === 8 && typeof style.sources === 'object' && style.sources !== null && Array.isArray(style.layers)
25
+ )
19
26
  }
20
27
 
21
28
  /** A style URL's document; rejects when it can't be read or isn't a version 8 style. */
package/src/types.ts CHANGED
@@ -22,7 +22,7 @@ export interface MapLibreLayerOverrides {
22
22
  readonly clusterCount?: MapLibreLayerOverride
23
23
  }
24
24
 
25
- /** How the maplibre engine is configured: once per `maplibre(options)`, for every view it draws. */
25
+ /** How the MapLibre engine is configured: once per `createMapLibreEngine(options)`, for every view it draws. */
26
26
  export interface MapLibreEngineOptions {
27
27
  /** The style a view draws when it passes no `mapStyle`. Defaults to OSM_RASTER_STYLE. */
28
28
  readonly defaultStyle?: MapStyleInput
@@ -1,33 +1,54 @@
1
- import { useEffect, useRef, useState } from 'react'
1
+ import { useEffect, useLayoutEffect, useRef, useState } from 'react'
2
2
  import { loadStyle } from './style'
3
3
  import type { MapStyle, MapStyleFetch, MapStyleInput } from './style.types'
4
4
 
5
+ /** The style read for a URL: a stale one never draws for the next URL. */
6
+ interface LoadedStyle {
7
+ readonly url: string
8
+ readonly style: MapStyle
9
+ }
10
+
11
+ /** What the loader calls back into, kept current without restarting a load. */
12
+ interface StyleCallbacks {
13
+ readonly fetchStyle: MapStyleFetch | undefined
14
+ readonly onError: ((error: Error) => void) | undefined
15
+ }
16
+
5
17
  const globalFetch: MapStyleFetch = (url) => fetch(url)
6
18
 
7
19
  /**
8
20
  * The style document to draw: the object as given, or the URL's once read (null until then).
9
21
  * A URL that can't be read draws `fallback` and is reported through `onError`.
10
22
  */
11
- export function useMapStyle(input: MapStyleInput, fallback: MapStyle, fetchStyle: MapStyleFetch | undefined, onError: ((error: Error) => void) | undefined): MapStyle | null {
12
- const [loaded, setLoaded] = useState<MapStyle | null>(null)
13
- const report = useRef(onError)
14
- report.current = onError
15
- const reader = useRef(fetchStyle)
16
- reader.current = fetchStyle
23
+ export function useMapStyle(
24
+ input: MapStyleInput,
25
+ fallback: MapStyle,
26
+ fetchStyle: MapStyleFetch | undefined,
27
+ onError: ((error: Error) => void) | undefined,
28
+ ): MapStyle | null {
29
+ const [loaded, setLoaded] = useState<LoadedStyle | null>(null)
30
+ const latest = useRef<StyleCallbacks>({ fetchStyle, onError })
31
+ useLayoutEffect(() => {
32
+ latest.current = { fetchStyle, onError }
33
+ })
17
34
  const url = typeof input === 'string' ? input : null
18
35
  useEffect(() => {
19
36
  if (url === null) return
20
37
  let current = true
21
- setLoaded(null)
22
- loadStyle(url, reader.current ?? globalFetch).then(
23
- (style) => { if (current) setLoaded(style) },
38
+ loadStyle(url, latest.current.fetchStyle ?? globalFetch).then(
39
+ (style) => {
40
+ if (current) setLoaded({ url, style })
41
+ },
24
42
  (error: unknown) => {
25
43
  if (!current) return
26
- setLoaded(fallback)
27
- report.current?.(error instanceof Error ? error : new Error(String(error)))
44
+ setLoaded({ url, style: fallback })
45
+ latest.current.onError?.(error instanceof Error ? error : new Error(String(error)))
28
46
  },
29
47
  )
30
- return () => { current = false }
48
+ return () => {
49
+ current = false
50
+ }
31
51
  }, [url, fallback])
32
- return typeof input === 'string' ? loaded : input
52
+ if (typeof input !== 'string') return input
53
+ return loaded?.url === input ? loaded.style : null
33
54
  }
@@ -1,24 +1,41 @@
1
- import { useLayoutEffect, useRef } from 'react'
1
+ import { useState } from 'react'
2
2
  import type { MapSourceUpdate } from './types'
3
3
 
4
4
  /** The sources whose data differs from what was last sent (string identity first, so unchanged memoized JSON costs nothing). */
5
- export function changedSources(sources: readonly MapSourceUpdate[], sent: ReadonlyMap<string, string>): MapSourceUpdate[] {
5
+ export function changedSources(
6
+ sources: readonly MapSourceUpdate[],
7
+ sent: ReadonlyMap<string, string>,
8
+ ): MapSourceUpdate[] {
6
9
  return sources.filter((source) => sent.get(source.sourceId) !== source.geoJSON)
7
10
  }
8
11
 
12
+ /** What the native view was last given, by source, and that batch. */
13
+ interface SourceUpdates {
14
+ readonly updates: MapSourceUpdate[]
15
+ readonly sent: ReadonlyMap<string, string>
16
+ }
17
+
18
+ const NOTHING_SENT: SourceUpdates = { updates: [], sent: new Map() }
19
+
20
+ const withSent = (
21
+ sent: ReadonlyMap<string, string>,
22
+ updates: readonly MapSourceUpdate[],
23
+ ): ReadonlyMap<string, string> => {
24
+ const next = new Map(sent)
25
+ for (const source of updates) next.set(source.sourceId, source.geoJSON)
26
+ return next
27
+ }
28
+
9
29
  /**
10
30
  * Only the sources whose data changed since the last commit, for the native view (which keeps
11
31
  * each source's newest data across style reloads): a pin pick sends the one-marker source, not
12
32
  * every marker again. The same array while nothing changes, so the host's setter runs only then.
13
33
  */
14
34
  export function useSourceUpdates(sources: readonly MapSourceUpdate[]): MapSourceUpdate[] {
15
- const sent = useRef(new Map<string, string>())
16
- const last = useRef<MapSourceUpdate[]>([])
17
- const changed = changedSources(sources, sent.current)
18
- const updates = changed.length === 0 ? last.current : changed
19
- useLayoutEffect(() => {
20
- last.current = updates
21
- for (const source of updates) sent.current.set(source.sourceId, source.geoJSON)
22
- }, [updates])
23
- return updates
35
+ const [state, setState] = useState<SourceUpdates>(NOTHING_SENT)
36
+ const changed = changedSources(sources, state.sent)
37
+ if (changed.length === 0) return state.updates
38
+ // Recorded during render: React re-renders at once with it, and drops it with a discarded render.
39
+ setState({ updates: changed, sent: withSent(state.sent, changed) })
40
+ return changed
24
41
  }