Coverage for app / documents / visuals / maps / features.py: 94%

138 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1"""A ```map fence read as fe-core reads it (``RichMarkdown.tsx``). 

2 

3``_parseMapCode``: the fence is GeoJSON itself, or an object whose 

4``geojson`` key holds it, with ``title``, ``center`` (``[lat, lng]``) and 

5``zoom``. ``_mapStyle``: a shape's line is ``stroke`` (else ``color``) at 

6``stroke-width`` (else ``weight``) pixels, its fill ``fill`` (else 

7``color``), fill opacity 0.25 and line opacity 0.85 unless set; a point is a 

8circle of 5, 8 or 11 pixels by ``marker-size``, ``marker-color`` (else 

9``color``), at 0.9 with a white rim. A name is ``name``, ``title``, 

10``label`` or ``Name``. 

11""" 

12 

13from __future__ import annotations 

14 

15import math 

16from collections.abc import Iterator 

17from dataclasses import dataclass, field 

18from typing import Any 

19 

20from reportlab.lib.colors import Color, HexColor 

21 

22from ..colors import parse_color 

23from ..fence import VisualError, number, read_object, text 

24from ..theme import PX 

25 

26#: The GeoJSON types a map fence may be (registry ``render_map``'s 

27#: ``valid_types`` and fe-core's ``_GEO_TYPES``, pinned by the tests). 

28GEO_TYPES: tuple[str, ...] = ( 

29 "FeatureCollection", 

30 "Feature", 

31 "Point", 

32 "MultiPoint", 

33 "LineString", 

34 "MultiLineString", 

35 "Polygon", 

36 "MultiPolygon", 

37 "GeometryCollection", 

38) 

39DEFAULT_COLOR = HexColor("#6366f1") 

40MAX_FEATURES = 2_000 

41MAX_VERTICES = 50_000 

42#: How deep a GeometryCollection may nest. 

43_MAX_DEPTH = 8 

44_RADIUS = {"small": 5, "large": 11} 

45 

46LngLat = tuple[float, float] 

47 

48 

49@dataclass(frozen=True) 

50class Style: 

51 stroke: Color 

52 #: Points. 

53 weight: float 

54 fill: Color 

55 fill_opacity: float 

56 opacity: float 

57 

58 

59@dataclass(frozen=True) 

60class MapPoint: 

61 at: LngLat 

62 radius: float 

63 fill: Color 

64 name: str 

65 

66 

67@dataclass(frozen=True) 

68class MapLine: 

69 points: list[LngLat] 

70 style: Style 

71 name: str 

72 

73 

74@dataclass(frozen=True) 

75class MapPolygon: 

76 rings: list[list[LngLat]] 

77 style: Style 

78 name: str 

79 

80 

81@dataclass 

82class MapSpec: 

83 title: str | None 

84 #: ``(lat, lng)``, as fe-core's ``center``. 

85 center: tuple[float, float] | None 

86 zoom: float | None 

87 points: list[MapPoint] = field(default_factory=list) 

88 lines: list[MapLine] = field(default_factory=list) 

89 polygons: list[MapPolygon] = field(default_factory=list) 

90 

91 def positions(self) -> list[LngLat]: 

92 out = [p.at for p in self.points] 

93 out += [q for line in self.lines for q in line.points] 

94 out += [q for poly in self.polygons for ring in poly.rings for q in ring] 

95 return out 

96 

97 

98def _first_set(*values: Any) -> Any: 

99 return next((v for v in values if v is not None), None) 

100 

101 

102def _opacity(value: Any, default: float) -> float: 

103 found = number(value) 

104 return default if found is None else max(0.0, min(1.0, found)) 

105 

106 

107def _style(props: dict[str, Any]) -> Style: 

108 weight = number(_first_set(props.get("stroke-width"), props.get("weight"))) 

109 return Style( 

110 stroke=parse_color( 

111 _first_set(props.get("stroke"), props.get("color")), DEFAULT_COLOR 

112 ), 

113 weight=(2.0 if weight is None else max(0.0, min(20.0, weight))) * PX, 

114 fill=parse_color( 

115 _first_set(props.get("fill"), props.get("color")), DEFAULT_COLOR 

116 ), 

117 fill_opacity=_opacity(props.get("fill-opacity"), 0.25), 

118 opacity=_opacity(props.get("stroke-opacity"), 0.85), 

119 ) 

120 

121 

122def _name(props: dict[str, Any]) -> str: 

123 return text( 

124 _first_set( 

125 props.get("name"), props.get("title"), props.get("label"), props.get("Name") 

126 ) 

127 ) 

128 

129 

130def _position(value: Any) -> LngLat | None: 

131 """A GeoJSON position, ``[lng, lat]``; anything else is skipped, where 

132 Leaflet would throw.""" 

133 if not isinstance(value, (list, tuple)) or len(value) < 2: 

134 return None 

135 lng, lat = value[0], value[1] 

136 if not all( 

137 isinstance(v, (int, float)) and not isinstance(v, bool) for v in (lng, lat) 

138 ): 

139 return None 

140 if not (math.isfinite(lng) and math.isfinite(lat)): 

141 return None 

142 return float(lng), float(lat) 

143 

144 

145def _line(value: Any) -> list[LngLat]: 

146 return ( 

147 [p for p in (_position(v) for v in value or []) if p] 

148 if isinstance(value, list) 

149 else [] 

150 ) 

151 

152 

153def _geometries( 

154 geometry: Any, props: dict[str, Any], depth: int = 0 

155) -> Iterator[tuple[str, Any, dict[str, Any]]]: 

156 if not isinstance(geometry, dict): 

157 return 

158 kind = geometry.get("type") 

159 if kind == "GeometryCollection": 

160 if depth < _MAX_DEPTH: 

161 for inner in geometry.get("geometries") or []: 

162 yield from _geometries(inner, props, depth + 1) 

163 return 

164 yield str(kind), geometry.get("coordinates"), props 

165 

166 

167def _features(value: Any) -> Iterator[tuple[str, Any, dict[str, Any]]]: 

168 if not isinstance(value, dict): 

169 return 

170 kind = value.get("type") 

171 if kind == "FeatureCollection": 

172 for feature in value.get("features") or []: 

173 if isinstance(feature, dict) and feature.get("type") == "Feature": 

174 yield from _features(feature) 

175 elif kind == "Feature": 

176 props = value.get("properties") 

177 yield from _geometries( 

178 value.get("geometry"), props if isinstance(props, dict) else {} 

179 ) 

180 else: 

181 yield from _geometries(value, {}) 

182 

183 

184def read(source: str) -> MapSpec: 

185 obj = read_object(source) 

186 if obj.get("type") in GEO_TYPES: 

187 geojson, cfg = obj, {} 

188 elif isinstance(obj.get("geojson"), dict): 

189 geojson, cfg = obj["geojson"], obj 

190 else: 

191 raise VisualError("it holds no GeoJSON") 

192 center = cfg.get("center") 

193 lat_lng = ( 

194 (number(center[0]), number(center[1])) 

195 if isinstance(center, list) and len(center) >= 2 

196 else (None, None) 

197 ) 

198 title = cfg.get("title") 

199 spec = MapSpec( 

200 text(title) or None if isinstance(title, str) else None, 

201 lat_lng if None not in lat_lng else None, # type: ignore[arg-type] 

202 number(cfg.get("zoom")), 

203 ) 

204 count = 0 

205 vertices = 0 

206 for kind, coordinates, props in _features(geojson): 

207 count += 1 

208 if count > MAX_FEATURES: 

209 raise VisualError(f"it has more than {MAX_FEATURES:,} features") 

210 if kind in ("Point", "MultiPoint"): 

211 positions = ( 

212 [_position(coordinates)] 

213 if kind == "Point" 

214 else [ 

215 _position(c) 

216 for c in (coordinates or []) 

217 if isinstance(coordinates, list) 

218 ] 

219 ) 

220 size = _RADIUS.get(props.get("marker-size"), 8) # type: ignore[arg-type] 

221 fill = parse_color( 

222 _first_set(props.get("marker-color"), props.get("color")), DEFAULT_COLOR 

223 ) 

224 for at in positions: 

225 if at: 

226 spec.points.append(MapPoint(at, size * PX, fill, _name(props))) 

227 vertices += 1 

228 elif kind in ("LineString", "MultiLineString"): 

229 lines = ( 

230 [_line(coordinates)] 

231 if kind == "LineString" 

232 else [ 

233 _line(c) 

234 for c in (coordinates if isinstance(coordinates, list) else []) 

235 ] 

236 ) 

237 for points in lines: 

238 if len(points) > 1: 

239 spec.lines.append(MapLine(points, _style(props), _name(props))) 

240 vertices += len(points) 

241 elif kind in ("Polygon", "MultiPolygon"): 

242 polygons = ( 

243 [coordinates] 

244 if kind == "Polygon" 

245 else (coordinates if isinstance(coordinates, list) else []) 

246 ) 

247 for rings in polygons: 

248 kept = [r for r in (_line(ring) for ring in rings or []) if len(r) > 2] 

249 if kept: 

250 spec.polygons.append(MapPolygon(kept, _style(props), _name(props))) 

251 vertices += sum(len(r) for r in kept) 

252 if vertices > MAX_VERTICES: 

253 raise VisualError(f"it has more than {MAX_VERTICES:,} points") 

254 if not spec.positions(): 

255 raise VisualError("it has no features") 

256 return spec