mapframe 0.3.0__py3-none-any.whl
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.
- mapframe/__init__.py +45 -0
- mapframe/_callbacks.py +186 -0
- mapframe/_camera.py +69 -0
- mapframe/_draw.py +378 -0
- mapframe/_events.py +47 -0
- mapframe/state.py +552 -0
- mapframe/static/widget.css +1 -0
- mapframe/static/widget.js +858 -0
- mapframe/widget.py +1483 -0
- mapframe-0.3.0.dist-info/METADATA +236 -0
- mapframe-0.3.0.dist-info/RECORD +14 -0
- mapframe-0.3.0.dist-info/WHEEL +4 -0
- mapframe-0.3.0.dist-info/licenses/LICENSE +17 -0
- mapframe-0.3.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +1453 -0
mapframe/_events.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""The events a map sends to Python."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class FeatureHit:
|
|
12
|
+
"""A rendered feature under a click.
|
|
13
|
+
|
|
14
|
+
``instance`` is the widget instance of the layer the hit was on, so a
|
|
15
|
+
reader can tell it from a replacement of the same layer id.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
layer_id: str
|
|
19
|
+
instance: int
|
|
20
|
+
properties: Mapping[str, Any]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class ClickEvent:
|
|
25
|
+
"""A click on one view.
|
|
26
|
+
|
|
27
|
+
``zoom`` is that view's zoom. ``settled`` says the view had reconciled its
|
|
28
|
+
latest state, every GeoJSON payload loaded. ``features`` are the hits on
|
|
29
|
+
current layer instances, top first, on the map shown at the click. In
|
|
30
|
+
compare, ``hidden_features`` holds the hits of the other map, the one the
|
|
31
|
+
shown half covers there, in the same form; it is empty outside compare.
|
|
32
|
+
``stale`` holds the ids of layers whose hits, in either, were dropped
|
|
33
|
+
because they were on a retired instance.
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
lng: float
|
|
37
|
+
lat: float
|
|
38
|
+
zoom: float
|
|
39
|
+
settled: bool
|
|
40
|
+
features: tuple[FeatureHit, ...]
|
|
41
|
+
stale: frozenset[str]
|
|
42
|
+
view_id: str
|
|
43
|
+
hidden_features: tuple[FeatureHit, ...] = ()
|
|
44
|
+
|
|
45
|
+
def hits(self, layer_id: str) -> tuple[Mapping[str, Any], ...]:
|
|
46
|
+
"""The properties of the features hit on ``layer_id``, top first."""
|
|
47
|
+
return tuple(f.properties for f in self.features if f.layer_id == layer_id)
|
mapframe/state.py
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
"""Frozen declarations of everything a map persistently shows."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import numbers
|
|
7
|
+
import re
|
|
8
|
+
from collections.abc import Mapping, Sequence
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from typing import Any, Literal, Protocol
|
|
11
|
+
|
|
12
|
+
THEMES = ("light", "dark")
|
|
13
|
+
ZONES = ("data", "overlay")
|
|
14
|
+
SIDES = ("left", "right", "both")
|
|
15
|
+
#: Which half of a compare map draws a layer.
|
|
16
|
+
Side = Literal["left", "right", "both"]
|
|
17
|
+
_PLACEHOLDER = re.compile(r"\{[^}]*\}")
|
|
18
|
+
_DRAWABLE = frozenset({"{z}", "{x}", "{y}", "{s}", "{r}"})
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class _TileProvider(Protocol):
|
|
22
|
+
"""The part of an xyzservices ``TileProvider`` that ``Basemap.from_xyz`` reads."""
|
|
23
|
+
|
|
24
|
+
def get(self, key: str, default: Any = ..., /) -> Any: ...
|
|
25
|
+
|
|
26
|
+
def build_url(self, *, fill_subdomain: bool = ...) -> str: ...
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _finite(name: str, value: float) -> float:
|
|
30
|
+
"""``value`` as a plain float; any finite real number but a bool."""
|
|
31
|
+
if isinstance(value, bool) or not isinstance(value, numbers.Real):
|
|
32
|
+
raise ValueError(f"{name} must be a number, got {value!r}")
|
|
33
|
+
if not math.isfinite(value):
|
|
34
|
+
raise ValueError(f"{name} must be finite, got {value!r}")
|
|
35
|
+
return float(value)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _int(name: str, value: int) -> int:
|
|
39
|
+
"""``value`` as a plain int; any integer but a bool."""
|
|
40
|
+
if isinstance(value, bool) or not isinstance(value, numbers.Integral):
|
|
41
|
+
raise ValueError(f"{name} must be an int, got {value!r}")
|
|
42
|
+
return int(value)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _zoom_level(name: str, value: int) -> int:
|
|
46
|
+
level = _int(name, value)
|
|
47
|
+
if not 0 <= level <= 24:
|
|
48
|
+
raise ValueError(f"{name} must be an int in [0, 24], got {value!r}")
|
|
49
|
+
return level
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _unit(name: str, value: float) -> float:
|
|
53
|
+
number = _finite(name, value)
|
|
54
|
+
if not 0 <= number <= 1:
|
|
55
|
+
raise ValueError(f"{name} must be in [0, 1], got {value!r}")
|
|
56
|
+
return number
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def tile_urls(template: str, subdomains: str | Sequence[str] = "abc") -> tuple[str, ...]:
|
|
60
|
+
"""Expand a Leaflet-style tile URL template into one URL per subdomain.
|
|
61
|
+
|
|
62
|
+
``{s}`` takes each of ``subdomains`` in turn, one character each when a
|
|
63
|
+
string, and ``{r}`` (Leaflet's retina suffix) is dropped. A template
|
|
64
|
+
without ``{s}`` comes back alone.
|
|
65
|
+
"""
|
|
66
|
+
template = template.replace("{r}", "")
|
|
67
|
+
if "{s}" not in template:
|
|
68
|
+
return (template,)
|
|
69
|
+
if not subdomains:
|
|
70
|
+
raise ValueError(f"{template!r} has {{s}} but no subdomain is given")
|
|
71
|
+
return tuple(template.replace("{s}", sub) for sub in subdomains)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _tiles(name: str, tiles: tuple[str, ...]) -> tuple[str, ...]:
|
|
75
|
+
"""The tile URLs, each Leaflet template expanded by ``tile_urls``."""
|
|
76
|
+
if isinstance(tiles, str) or not tiles:
|
|
77
|
+
raise ValueError(f"{name} needs a non-empty tuple of tile URLs")
|
|
78
|
+
for tile in tiles:
|
|
79
|
+
if not isinstance(tile, str) or not tile:
|
|
80
|
+
raise ValueError(f"{name} entries must be non-empty strings, got {tile!r}")
|
|
81
|
+
# MapLibre requests {s} literally, so it never reaches the front end.
|
|
82
|
+
return tuple(url for tile in tiles for url in tile_urls(tile))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _bounds(name: str, bounds) -> tuple[float, float, float, float]:
|
|
86
|
+
"""``(west, south, east, north)`` as floats; west may exceed east."""
|
|
87
|
+
try:
|
|
88
|
+
values = tuple(bounds)
|
|
89
|
+
except TypeError:
|
|
90
|
+
values = ()
|
|
91
|
+
if isinstance(bounds, str) or len(values) != 4:
|
|
92
|
+
raise ValueError(f"{name} must be (west, south, east, north), got {bounds!r}")
|
|
93
|
+
corners = ("west", "south", "east", "north")
|
|
94
|
+
west, south, east, north = (_finite(f"{name} {c}", v) for c, v in zip(corners, values))
|
|
95
|
+
if not -90 <= south <= north <= 90:
|
|
96
|
+
raise ValueError(f"{name} needs -90 <= south <= north <= 90, got {bounds!r}")
|
|
97
|
+
return west, south, east, north
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@dataclass(frozen=True)
|
|
101
|
+
class RasterSource:
|
|
102
|
+
tiles: tuple[str, ...]
|
|
103
|
+
tile_size: int = 256
|
|
104
|
+
bounds: tuple[float, float, float, float] | None = None
|
|
105
|
+
max_native_zoom: int | None = None
|
|
106
|
+
|
|
107
|
+
def __post_init__(self) -> None:
|
|
108
|
+
"""Reject bad tiles, tile size, bounds or native zoom; store plain numbers."""
|
|
109
|
+
object.__setattr__(self, "tiles", _tiles("RasterSource.tiles", self.tiles))
|
|
110
|
+
tile_size = _int("RasterSource.tile_size", self.tile_size)
|
|
111
|
+
if tile_size < 1:
|
|
112
|
+
raise ValueError(f"RasterSource.tile_size must be positive, got {self.tile_size!r}")
|
|
113
|
+
object.__setattr__(self, "tile_size", tile_size)
|
|
114
|
+
if self.bounds is not None:
|
|
115
|
+
object.__setattr__(self, "bounds", _bounds("RasterSource.bounds", self.bounds))
|
|
116
|
+
if self.max_native_zoom is not None:
|
|
117
|
+
zoom = _zoom_level("RasterSource.max_native_zoom", self.max_native_zoom)
|
|
118
|
+
object.__setattr__(self, "max_native_zoom", zoom)
|
|
119
|
+
|
|
120
|
+
def to_json(self) -> dict:
|
|
121
|
+
"""The source as the JSON the front end reads, with bounds as a plain list."""
|
|
122
|
+
return {
|
|
123
|
+
"tiles": list(self.tiles),
|
|
124
|
+
"tile_size": self.tile_size,
|
|
125
|
+
"max_native_zoom": self.max_native_zoom,
|
|
126
|
+
"bounds": None if self.bounds is None else list(self.bounds),
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
@dataclass(frozen=True)
|
|
131
|
+
class Cluster:
|
|
132
|
+
"""Group the points of a GeoJSON source into count bubbles below ``max_zoom``.
|
|
133
|
+
|
|
134
|
+
``radius`` is the grouping distance in pixels. MapLibre reads a max zoom of 0
|
|
135
|
+
as its default and wants it below the source's own max zoom (18).
|
|
136
|
+
"""
|
|
137
|
+
|
|
138
|
+
radius: int = 50
|
|
139
|
+
max_zoom: int = 14
|
|
140
|
+
|
|
141
|
+
def __post_init__(self) -> None:
|
|
142
|
+
"""Reject a radius below 1 or a max zoom outside [1, 17]; store plain ints."""
|
|
143
|
+
radius = _int("Cluster.radius", self.radius)
|
|
144
|
+
if radius < 1:
|
|
145
|
+
raise ValueError(f"Cluster.radius must be at least 1, got {self.radius!r}")
|
|
146
|
+
max_zoom = _int("Cluster.max_zoom", self.max_zoom)
|
|
147
|
+
if not 1 <= max_zoom <= 17:
|
|
148
|
+
raise ValueError(f"Cluster.max_zoom must be an int in [1, 17], got {self.max_zoom!r}")
|
|
149
|
+
object.__setattr__(self, "radius", radius)
|
|
150
|
+
object.__setattr__(self, "max_zoom", max_zoom)
|
|
151
|
+
|
|
152
|
+
def to_json(self) -> dict:
|
|
153
|
+
"""The cluster options as JSON."""
|
|
154
|
+
return {"radius": self.radius, "max_zoom": self.max_zoom}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@dataclass(frozen=True)
|
|
158
|
+
class GeoJSONSource:
|
|
159
|
+
digest: str
|
|
160
|
+
cluster: Cluster | None = None
|
|
161
|
+
|
|
162
|
+
def to_json(self) -> dict:
|
|
163
|
+
"""The source as JSON: the digest, since the data travels apart, and the cluster."""
|
|
164
|
+
return {
|
|
165
|
+
"digest": self.digest,
|
|
166
|
+
"cluster": None if self.cluster is None else self.cluster.to_json(),
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def check_clusterable(geojson: Mapping[str, Any] | None) -> None:
|
|
171
|
+
"""Raise ``ValueError`` unless ``geojson`` suits a clustered ``GeoJSONSource``.
|
|
172
|
+
|
|
173
|
+
MapLibre's cluster index drops lines and polygons and marks its bubbles
|
|
174
|
+
with ``cluster: true``, so every feature must be a point without that
|
|
175
|
+
property. ``geojson`` is a parsed FeatureCollection, Feature or geometry;
|
|
176
|
+
None passes. ``publish`` runs it on every clustered payload.
|
|
177
|
+
"""
|
|
178
|
+
if not geojson:
|
|
179
|
+
return
|
|
180
|
+
if "features" in geojson or geojson.get("type") == "FeatureCollection":
|
|
181
|
+
features = geojson.get("features") or ()
|
|
182
|
+
elif geojson.get("type") == "Feature":
|
|
183
|
+
features = (geojson,)
|
|
184
|
+
else:
|
|
185
|
+
features = ({"geometry": geojson},)
|
|
186
|
+
for feature in features:
|
|
187
|
+
geometry = feature.get("geometry")
|
|
188
|
+
if geometry is None or geometry.get("type") != "Point":
|
|
189
|
+
raise ValueError("clustering needs point features only")
|
|
190
|
+
if (feature.get("properties") or {}).get("cluster") is True:
|
|
191
|
+
raise ValueError("property cluster=true is reserved for clusters")
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
@dataclass(frozen=True)
|
|
195
|
+
class PMTilesSource:
|
|
196
|
+
url: str
|
|
197
|
+
source_layer: str
|
|
198
|
+
|
|
199
|
+
def to_json(self) -> dict:
|
|
200
|
+
"""The source as JSON: the archive URL and the vector layer to draw."""
|
|
201
|
+
return {"url": self.url, "source_layer": self.source_layer}
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
#: The upper bound of JavaScript's safe integer range.
|
|
205
|
+
_MAX_SAFE_INTEGER = 2**53 - 1
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _safe_int(name: str, value: int) -> int:
|
|
209
|
+
number = _int(name, value)
|
|
210
|
+
if abs(number) > _MAX_SAFE_INTEGER:
|
|
211
|
+
raise ValueError(f"{name} must be a JavaScript safe integer, got {value!r}")
|
|
212
|
+
return number
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _class_value(value) -> str | int:
|
|
216
|
+
"""A class value: a str, or an int MapLibre can compare exactly; never a bool."""
|
|
217
|
+
if isinstance(value, str):
|
|
218
|
+
return value
|
|
219
|
+
return _safe_int("class value", value)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _class_colors(value) -> tuple[tuple[str | int, str], ...]:
|
|
223
|
+
"""``(value, color)`` pairs from a mapping or a sequence of pairs, values all of one type."""
|
|
224
|
+
bad = f"class_colors must be a mapping or (value, color) pairs, got {value!r}"
|
|
225
|
+
if isinstance(value, Mapping):
|
|
226
|
+
entries = list(value.items())
|
|
227
|
+
elif isinstance(value, Sequence) and not isinstance(value, str):
|
|
228
|
+
entries = list(value)
|
|
229
|
+
else:
|
|
230
|
+
raise ValueError(bad)
|
|
231
|
+
pairs = []
|
|
232
|
+
for entry in entries:
|
|
233
|
+
if isinstance(entry, str) or not isinstance(entry, Sequence) or len(entry) != 2:
|
|
234
|
+
raise ValueError(bad)
|
|
235
|
+
label, color = entry
|
|
236
|
+
if not isinstance(color, str) or not color:
|
|
237
|
+
raise ValueError(f"class colours must be non-empty strings, got {color!r}")
|
|
238
|
+
pairs.append((_class_value(label), color))
|
|
239
|
+
labels = [label for label, _ in pairs]
|
|
240
|
+
if len({type(label) for label in labels}) > 1:
|
|
241
|
+
raise ValueError("class values must be all str or all int")
|
|
242
|
+
if len(set(labels)) != len(labels):
|
|
243
|
+
raise ValueError(f"class values must be unique, got {labels!r}")
|
|
244
|
+
return tuple(pairs)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
@dataclass(frozen=True)
|
|
248
|
+
class VectorPaint:
|
|
249
|
+
"""How a vector layer is drawn.
|
|
250
|
+
|
|
251
|
+
``color_by`` names a feature property and ``class_colors``, a mapping or a
|
|
252
|
+
sequence of ``(value, color)`` pairs, gives its values their colours; the two
|
|
253
|
+
go together. Fill, line, circle and pin then take the colour of the
|
|
254
|
+
feature's class, and a feature of no class keeps the colour it would have
|
|
255
|
+
without them. Values are unique and all str or all int, and are compared as
|
|
256
|
+
they are, so ``"1"`` is not ``1``.
|
|
257
|
+
"""
|
|
258
|
+
|
|
259
|
+
stroke: str = "#3388ff"
|
|
260
|
+
fill: str | None = None
|
|
261
|
+
fill_opacity: float = 0.0
|
|
262
|
+
width: float = 2.0
|
|
263
|
+
point_radius: float = 5.0
|
|
264
|
+
marker: Literal["circle", "pin"] = "circle"
|
|
265
|
+
color_by: str | None = None
|
|
266
|
+
class_colors: tuple[tuple[str | int, str], ...] = ()
|
|
267
|
+
|
|
268
|
+
def __post_init__(self) -> None:
|
|
269
|
+
"""Reject a bad opacity, size, marker or class; store the classes as pairs."""
|
|
270
|
+
if self.marker not in ("circle", "pin"):
|
|
271
|
+
raise ValueError(f"marker must be 'circle' or 'pin', got {self.marker!r}")
|
|
272
|
+
object.__setattr__(self, "fill_opacity", _unit("fill_opacity", self.fill_opacity))
|
|
273
|
+
for name in ("width", "point_radius"):
|
|
274
|
+
value = _finite(name, getattr(self, name))
|
|
275
|
+
if value < 0:
|
|
276
|
+
raise ValueError(f"{name} must not be negative")
|
|
277
|
+
object.__setattr__(self, name, value)
|
|
278
|
+
if self.color_by is not None and (not isinstance(self.color_by, str) or not self.color_by):
|
|
279
|
+
raise ValueError(f"color_by must be a non-empty string, got {self.color_by!r}")
|
|
280
|
+
object.__setattr__(self, "class_colors", _class_colors(self.class_colors))
|
|
281
|
+
if (self.color_by is None) != (not self.class_colors):
|
|
282
|
+
raise ValueError("color_by and class_colors must be given together")
|
|
283
|
+
|
|
284
|
+
def to_json(self) -> dict:
|
|
285
|
+
"""The paint as the JSON the front end reads."""
|
|
286
|
+
return {
|
|
287
|
+
"stroke": self.stroke,
|
|
288
|
+
"fill": self.fill,
|
|
289
|
+
"fill_opacity": self.fill_opacity,
|
|
290
|
+
"width": self.width,
|
|
291
|
+
"point_radius": self.point_radius,
|
|
292
|
+
"marker": self.marker,
|
|
293
|
+
"color_by": self.color_by,
|
|
294
|
+
"class_colors": [[label, color] for label, color in self.class_colors],
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
_FieldPairs = tuple[tuple[str, str], ...]
|
|
299
|
+
_FieldSelection = Mapping[str, str] | Sequence[str] | _FieldPairs | None
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _fields(name: str, value) -> _FieldPairs | None:
|
|
303
|
+
"""``value`` as ``(name, label)`` pairs, or None.
|
|
304
|
+
|
|
305
|
+
A mapping gives name -> label; a sequence of names labels each with itself.
|
|
306
|
+
Stored pairs also go through here when dataclasses.replace copies a field.
|
|
307
|
+
"""
|
|
308
|
+
if value is None:
|
|
309
|
+
return None
|
|
310
|
+
if isinstance(value, str):
|
|
311
|
+
raise ValueError(f"{name} must be a tuple of property names, got {value!r}")
|
|
312
|
+
if isinstance(value, Mapping):
|
|
313
|
+
pairs = tuple(value.items())
|
|
314
|
+
else:
|
|
315
|
+
try:
|
|
316
|
+
pairs = tuple(
|
|
317
|
+
item if isinstance(item, tuple) and len(item) == 2 else (item, item)
|
|
318
|
+
for item in value
|
|
319
|
+
)
|
|
320
|
+
except TypeError:
|
|
321
|
+
raise ValueError(
|
|
322
|
+
f"{name} must be a tuple of property names or a mapping to labels, got {value!r}"
|
|
323
|
+
) from None
|
|
324
|
+
for field_name, label in pairs:
|
|
325
|
+
if not isinstance(field_name, str) or not field_name:
|
|
326
|
+
raise ValueError(f"{name} entries must be non-empty strings, got {field_name!r}")
|
|
327
|
+
if not isinstance(label, str) or not label:
|
|
328
|
+
raise ValueError(f"{name} labels must be non-empty strings, got {label!r}")
|
|
329
|
+
return pairs
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
@dataclass(frozen=True)
|
|
333
|
+
class Interaction:
|
|
334
|
+
"""What a click or the pointer shows of a feature's properties.
|
|
335
|
+
|
|
336
|
+
``()`` shows every property, a tuple names the ones to show in that order, a mapping
|
|
337
|
+
names them with the label to show for each, ``None`` turns the popup or tooltip off.
|
|
338
|
+
"""
|
|
339
|
+
|
|
340
|
+
popup: _FieldPairs | None = None
|
|
341
|
+
tooltip: _FieldPairs | None = None
|
|
342
|
+
|
|
343
|
+
def __init__(self, popup: _FieldSelection = None, tooltip: _FieldSelection = None) -> None:
|
|
344
|
+
"""Store each field as checked ``(name, label)`` pairs."""
|
|
345
|
+
object.__setattr__(self, "popup", _fields("Interaction.popup", popup))
|
|
346
|
+
object.__setattr__(self, "tooltip", _fields("Interaction.tooltip", tooltip))
|
|
347
|
+
|
|
348
|
+
def to_json(self) -> dict:
|
|
349
|
+
"""The interaction as JSON, with each field a list of ``[name, label]`` or null."""
|
|
350
|
+
return {
|
|
351
|
+
"popup": None if self.popup is None else [list(pair) for pair in self.popup],
|
|
352
|
+
"tooltip": None if self.tooltip is None else [list(pair) for pair in self.tooltip],
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
@dataclass(frozen=True)
|
|
357
|
+
class Layer:
|
|
358
|
+
id: str
|
|
359
|
+
source: RasterSource | GeoJSONSource | PMTilesSource
|
|
360
|
+
token: int = 0
|
|
361
|
+
zone: Literal["data", "overlay"] = "data"
|
|
362
|
+
visible: bool = True
|
|
363
|
+
opacity: float = 1.0
|
|
364
|
+
min_zoom: float = 0
|
|
365
|
+
max_zoom: float | None = None
|
|
366
|
+
paint: VectorPaint | None = None
|
|
367
|
+
attribution: str = ""
|
|
368
|
+
interaction: Interaction | None = None
|
|
369
|
+
side: Side = "both"
|
|
370
|
+
|
|
371
|
+
def __post_init__(self) -> None:
|
|
372
|
+
"""Reject an unknown source, zone or side, a non-int token, out-of-range opacity or zooms, and a paint or interaction on a raster layer; give vector layers the default paint."""
|
|
373
|
+
if not isinstance(self.source, (RasterSource, GeoJSONSource, PMTilesSource)):
|
|
374
|
+
raise ValueError(f"unsupported source {self.source!r}")
|
|
375
|
+
object.__setattr__(self, "token", _safe_int("token", self.token))
|
|
376
|
+
if self.zone not in ZONES:
|
|
377
|
+
raise ValueError(f"zone must be one of {ZONES}, got {self.zone!r}")
|
|
378
|
+
if self.side not in SIDES:
|
|
379
|
+
raise ValueError(f"side must be one of {SIDES}, got {self.side!r}")
|
|
380
|
+
object.__setattr__(self, "opacity", _unit("opacity", self.opacity))
|
|
381
|
+
for name in ("min_zoom", "max_zoom"):
|
|
382
|
+
value = getattr(self, name)
|
|
383
|
+
if value is None and name == "max_zoom":
|
|
384
|
+
continue
|
|
385
|
+
zoom = _finite(name, value)
|
|
386
|
+
if not 0 <= zoom <= 24:
|
|
387
|
+
raise ValueError(f"{name} must be in [0, 24], got {value!r}")
|
|
388
|
+
object.__setattr__(self, name, zoom)
|
|
389
|
+
if self.max_zoom is not None and self.min_zoom >= self.max_zoom:
|
|
390
|
+
raise ValueError("min_zoom must be below max_zoom")
|
|
391
|
+
if self.kind == "raster":
|
|
392
|
+
if self.paint is not None:
|
|
393
|
+
raise ValueError("a raster layer takes no paint")
|
|
394
|
+
if self.interaction is not None:
|
|
395
|
+
raise ValueError("a raster layer takes no interaction")
|
|
396
|
+
elif self.paint is None:
|
|
397
|
+
object.__setattr__(self, "paint", VectorPaint())
|
|
398
|
+
|
|
399
|
+
@property
|
|
400
|
+
def kind(self) -> Literal["raster", "geojson", "pmtiles"]:
|
|
401
|
+
"""Which kind of layer the source makes: "raster", "geojson" or "pmtiles"."""
|
|
402
|
+
if isinstance(self.source, RasterSource):
|
|
403
|
+
return "raster"
|
|
404
|
+
if isinstance(self.source, GeoJSONSource):
|
|
405
|
+
return "geojson"
|
|
406
|
+
return "pmtiles"
|
|
407
|
+
|
|
408
|
+
def to_json(self) -> dict:
|
|
409
|
+
"""The layer as JSON, with its source and paint nested."""
|
|
410
|
+
return {
|
|
411
|
+
"id": self.id,
|
|
412
|
+
"kind": self.kind,
|
|
413
|
+
"token": self.token,
|
|
414
|
+
"zone": self.zone,
|
|
415
|
+
"visible": self.visible,
|
|
416
|
+
"opacity": self.opacity,
|
|
417
|
+
"min_zoom": self.min_zoom,
|
|
418
|
+
"max_zoom": self.max_zoom,
|
|
419
|
+
"attribution": self.attribution,
|
|
420
|
+
"source": self.source.to_json(),
|
|
421
|
+
"paint": None if self.paint is None else self.paint.to_json(),
|
|
422
|
+
"interaction": None if self.interaction is None else self.interaction.to_json(),
|
|
423
|
+
"side": self.side,
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
@dataclass(frozen=True)
|
|
428
|
+
class Basemap:
|
|
429
|
+
tiles: tuple[str, ...]
|
|
430
|
+
attribution: str = ""
|
|
431
|
+
max_zoom: int = 19
|
|
432
|
+
|
|
433
|
+
def __post_init__(self) -> None:
|
|
434
|
+
"""Reject bad tiles or a max zoom outside [0, 24]."""
|
|
435
|
+
object.__setattr__(self, "tiles", _tiles("Basemap.tiles", self.tiles))
|
|
436
|
+
object.__setattr__(self, "max_zoom", _zoom_level("Basemap.max_zoom", self.max_zoom))
|
|
437
|
+
|
|
438
|
+
@classmethod
|
|
439
|
+
def from_xyz(cls, provider: _TileProvider) -> Basemap:
|
|
440
|
+
"""The basemap of an xyzservices ``TileProvider``.
|
|
441
|
+
|
|
442
|
+
It takes every subdomain of the provider (``"abc"`` by default), its
|
|
443
|
+
attribution and its max zoom (22 by default, at most 24). Raises
|
|
444
|
+
``ValueError`` when MapLibre cannot draw the provider: a TMS one, or
|
|
445
|
+
one whose URL keeps a placeholder other than z, x, y, s and r, such as
|
|
446
|
+
an ``{ext}`` it lacks or a missing API key.
|
|
447
|
+
"""
|
|
448
|
+
name = provider.get("name", "the provider")
|
|
449
|
+
if provider.get("tms"):
|
|
450
|
+
raise ValueError(f"MapLibre cannot draw {name}: it is a TMS provider")
|
|
451
|
+
try:
|
|
452
|
+
template = provider.build_url(fill_subdomain=False)
|
|
453
|
+
except KeyError as error:
|
|
454
|
+
raise ValueError(
|
|
455
|
+
f"MapLibre cannot draw {name}: unfilled placeholder {{{error.args[0]}}}"
|
|
456
|
+
) from None
|
|
457
|
+
except (ValueError, IndexError) as error:
|
|
458
|
+
raise ValueError(f"MapLibre cannot draw {name}: {error}") from None
|
|
459
|
+
unfilled = set(_PLACEHOLDER.findall(template)) - _DRAWABLE
|
|
460
|
+
if unfilled:
|
|
461
|
+
raise ValueError(
|
|
462
|
+
f"MapLibre cannot draw {name}: unfilled placeholder {', '.join(sorted(unfilled))}"
|
|
463
|
+
)
|
|
464
|
+
return cls(
|
|
465
|
+
tiles=tile_urls(template, provider.get("subdomains", "abc")),
|
|
466
|
+
attribution=provider.get("attribution", ""),
|
|
467
|
+
max_zoom=min(int(provider.get("max_zoom", 22)), 24),
|
|
468
|
+
)
|
|
469
|
+
|
|
470
|
+
def to_json(self) -> dict:
|
|
471
|
+
"""The basemap as the JSON the front end reads."""
|
|
472
|
+
return {
|
|
473
|
+
"tiles": list(self.tiles),
|
|
474
|
+
"attribution": self.attribution,
|
|
475
|
+
"max_zoom": self.max_zoom,
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
@dataclass(frozen=True)
|
|
480
|
+
class Controls:
|
|
481
|
+
"""The map controls to show.
|
|
482
|
+
|
|
483
|
+
``scale`` is a metric scale bar; ``coordinates`` a readout of the pointer's
|
|
484
|
+
position at the bottom left; ``globe`` a button that turns the view's map
|
|
485
|
+
into a globe and back. The projection is the view's, like its camera:
|
|
486
|
+
hiding the button takes the view back to the flat map.
|
|
487
|
+
"""
|
|
488
|
+
|
|
489
|
+
zoom: bool = True
|
|
490
|
+
fullscreen: bool = True
|
|
491
|
+
scale: bool = True
|
|
492
|
+
coordinates: bool = False
|
|
493
|
+
globe: bool = False
|
|
494
|
+
|
|
495
|
+
def to_json(self) -> dict:
|
|
496
|
+
"""The control switches as JSON."""
|
|
497
|
+
return {
|
|
498
|
+
"zoom": self.zoom,
|
|
499
|
+
"fullscreen": self.fullscreen,
|
|
500
|
+
"scale": self.scale,
|
|
501
|
+
"coordinates": self.coordinates,
|
|
502
|
+
"globe": self.globe,
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
@dataclass(frozen=True)
|
|
507
|
+
class LayerStatus:
|
|
508
|
+
"""What the mounted views report for the current instance of a layer.
|
|
509
|
+
|
|
510
|
+
``error`` holds a message only when ``status`` is ``"error"``.
|
|
511
|
+
"""
|
|
512
|
+
|
|
513
|
+
status: Literal["loading", "ready", "error"]
|
|
514
|
+
error: str | None
|
|
515
|
+
token: int
|
|
516
|
+
instance: int
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
@dataclass(frozen=True)
|
|
520
|
+
class MapState:
|
|
521
|
+
"""Layers are top-first: index 0 draws on top."""
|
|
522
|
+
|
|
523
|
+
layers: tuple[Layer, ...] = ()
|
|
524
|
+
basemap: Basemap | None = None
|
|
525
|
+
theme: Literal["light", "dark"] = "light"
|
|
526
|
+
controls: Controls = field(default_factory=Controls)
|
|
527
|
+
compare: bool = False
|
|
528
|
+
|
|
529
|
+
def __post_init__(self) -> None:
|
|
530
|
+
"""Reject an unknown theme, a non-bool compare, and missing or duplicate layer ids."""
|
|
531
|
+
if not isinstance(self.compare, bool):
|
|
532
|
+
raise TypeError(f"compare must be a bool, got {self.compare!r}")
|
|
533
|
+
if self.theme not in THEMES:
|
|
534
|
+
raise ValueError(f"theme must be one of {THEMES}, got {self.theme!r}")
|
|
535
|
+
object.__setattr__(self, "layers", tuple(self.layers))
|
|
536
|
+
seen: set[str] = set()
|
|
537
|
+
for layer in self.layers:
|
|
538
|
+
if not isinstance(layer.id, str) or not layer.id:
|
|
539
|
+
raise ValueError("layer ids must be non-empty strings")
|
|
540
|
+
if layer.id in seen:
|
|
541
|
+
raise ValueError(f"duplicate layer id {layer.id!r}")
|
|
542
|
+
seen.add(layer.id)
|
|
543
|
+
|
|
544
|
+
def to_json(self) -> dict:
|
|
545
|
+
"""The whole desired state as the JSON published to the views."""
|
|
546
|
+
return {
|
|
547
|
+
"theme": self.theme,
|
|
548
|
+
"compare": self.compare,
|
|
549
|
+
"controls": self.controls.to_json(),
|
|
550
|
+
"basemap": None if self.basemap is None else self.basemap.to_json(),
|
|
551
|
+
"layers": [layer.to_json() for layer in self.layers],
|
|
552
|
+
}
|