All files / app/util geo.ts

92.85% Statements 195/210
85.85% Branches 176/205
93.18% Functions 41/44
96.17% Lines 151/157

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329  25x     71x             40x                   5x 5x 5x 12x 6x 6x 6x 6x 4x     5x 6x 5x   5x 3x               3x 3x   3x 3x 3x 3x 2x 2x 2x     3x 3x                 8x 5x 5x 5x 6x 6x 2x 2x     5x 5x 5x               3x 3x 3x 15x 5x 5x 5x 10x 6x     3x 3x 2x 2x               29x 17x 17x 34x                 14x 2x   13x 13x 20x 19x 5x 14x 14x     13x 14x       13x 13x 13x 13x   4x       4x             4x   2x 2x                       8x       7x 6x 6x 3x   4x   3x     25x                                     20x 20x 4x 4x 2x   4x     16x 15x 20x   20x 15x 15x   2x 2x   15x 15x   1x 1x   15x 4x 4x   15x 7x 1x 1x   6x 6x   15x 15x 15x 15x       8x       5x                     3x 3x     3x 3x 3x 3x 1x 1x         1x   2x 3x 2x   2x 3x 3x 3x 2x                       1x 3x 1x             9x 7x 17x 5x 5x 4x 1x             9x 9x 14x 6x 6x 5x 3x    
import type { Feature, Geometry, Position } from 'geojson';
import { cloneDeep } from 'lodash-es';
 
export function isPosition(p: any): p is Position {
  return Array.isArray(p) && p.length >= 2 && typeof p[0] === 'number' && typeof p[1] === 'number' && isFinite(p[0]) && isFinite(p[1]);
}
 
/**
 * A position other than the unset [0, 0] default.
 */
export function hasLocation(v: any): v is [number, number] {
  return isPosition(v)
    && v[0] >= -180 && v[0] <= 180
    && v[1] >= -90 && v[1] <= 90
    && (v[0] !== 0 || v[1] !== 0);
}
 
/**
 * Centre of the bounds of every location in the Ref's geo plugins.
 */
export function geoCenter(plugins?: Record<string, any>): [number, number] | undefined {
  const lons: number[] = [];
  let s = Infinity, n = -Infinity;
  const visit = (c: any) => {
    if (hasLocation(c)) {
      lons.push(c[0]);
      s = Math.min(s, c[1]);
      n = Math.max(n, c[1]);
    } else if (Array.isArray(c)) {
      c.forEach(visit);
    }
  };
  for (const [key, value] of Object.entries(plugins || {})) {
    if (!key.startsWith('plugin/geo/')) continue;
    for (const f of geoFeatures(value, value?.geometry?.type === 'Point' ? hasLocation : isPosition)) visit((f.geometry as any).coordinates);
  }
  if (!lons.length) return undefined;
  return [lonCenter(lons), (s + n) / 2];
}
 
/**
 * Centre of the smallest longitude interval containing every longitude,
 * allowing the interval to wrap across the antimeridian.
 */
function lonCenter(lons: number[]): number {
  const sorted = [...lons].sort((a, b) => a - b);
  const last = sorted.length - 1;
  // The interval is the complement of the largest gap between neighbours
  let gap = sorted[0] + 360 - sorted[last];
  let west = sorted[0], east = sorted[last];
  for (let i = 0; i < last; i++) {
    if (sorted[i + 1] - sorted[i] > gap) {
      gap = sorted[i + 1] - sorted[i];
      west = sorted[i + 1];
      east = sorted[i] + 360;
    }
  }
  const c = (west + east) / 2;
  return c > 180 ? c - 360 : c;
}
 
/**
 * Smallest longitude interval containing all normalized longitudes, possibly
 * crossing the antimeridian. Returns [west, east] with east >= west, where east
 * may exceed 180 when the interval crosses the antimeridian.
 */
export function minimalLngInterval(lngs: number[]): [number, number] {
  const sorted = [...lngs].sort((a, b) => a - b);
  let gap = sorted[0] + 360 - sorted[sorted.length - 1];
  let start = 0;
  for (let i = 1; i < sorted.length; i++) {
    const g = sorted[i] - sorted[i - 1];
    if (g > gap) {
      gap = g;
      start = i;
    }
  }
  const west = sorted[start];
  const east = sorted[(start + sorted.length - 1) % sorted.length];
  return [west, east < west ? east + 360 : east];
}
 
/**
 * Bounds [west, south, east, north] of every location, possibly crossing
 * the antimeridian, in which case east exceeds 180.
 */
export function locationBounds(coordinates: any): [number, number, number, number] | undefined {
  const lngs: number[] = [];
  let south = Infinity, north = -Infinity;
  const visit = (c: any) => {
    if (hasLocation(c)) {
      lngs.push(c[0]);
      south = Math.min(south, c[1]);
      north = Math.max(north, c[1]);
    } else if (Array.isArray(c)) {
      c.forEach(visit);
    }
  };
  visit(coordinates);
  if (!lngs.length) return undefined;
  const [west, east] = minimalLngInterval(lngs);
  return [west, south, east, north];
}
 
/**
 * A linear ring is closed with four or more positions, the first and last
 * being identical (RFC 7946 3.1.6).
 */
export function isLinearRing(ring: Position[]): boolean {
  if (ring.length < 4) return false;
  const first = ring[0];
  const last = ring[ring.length - 1];
  return first.length === last.length && first.every((n, i) => n === last[i]);
}
 
/**
 * Convert a feature or feature collection into renderable features. Rings are never closed
 * automatically: invalid polygons are drawn as open lines and points so the
 * map always shows exactly what is stored.
 */
export function geoFeatures(feature: any, valid: (p: any) => p is Position = isPosition): Feature[] {
  if (feature?.type === 'FeatureCollection') {
    return (Array.isArray(feature.features) ? feature.features : []).flatMap((f: any) => geoFeatures(f, valid));
  }
  const result: Feature[] = [];
  const add = (geometry?: Geometry) => {
    if (!geometry) return;
    if (geometry.type === 'GeometryCollection') {
      geometry.geometries.forEach(add);
    E} else if (!Array.isArray(geometry.coordinates) || geometry.coordinates.length) {
      result.push({ type: 'Feature', properties: feature?.properties || {}, geometry });
    }
  };
  add(sanitize(feature?.geometry, valid));
  return result;
}
 
function sanitize(geometry: any, valid: (p: any) => p is Position): Geometry | undefined {
  const c = geometry?.coordinates;
  const positions = (ps: any): Position[] => Array.isArray(ps) ? ps.filter(valid) : [];
  const polygon = (rings: any[]) => toPolygon(rings.map(positions));
  switch (geometry?.type) {
    case 'Point':
      return valid(c) ? { type: 'Point', coordinates: c } : undefined;
    case 'MultiPoint':
      return { type: 'MultiPoint', coordinates: positions(c) };
    case 'LineString':
      return line(positions(c));
    case 'MultiLineString':
      return {
        type: 'GeometryCollection',
        geometries: (Array.isArray(c) ? c : []).map(positions).filter(l => l.length).map(line),
      };
    case 'Polygon':
      return polygon(Array.isArray(c) ? c : []);
    case 'MultiPolygon': {
      const polys = (Array.isArray(c) ? c : []).map(p => polygon(Array.isArray(p) ? p : []));
      return { type: 'GeometryCollection', geometries: polys.filter(p => !!p) as Geometry[] };
    }
    case 'GeometryCollection':
      return {
        type: 'GeometryCollection',
        geometries: (Array.isArray(geometry.geometries) ? geometry.geometries : []).map((g: any) => sanitize(g, valid)).filter((g: any) => !!g),
      };
  }
  return undefined;
}
 
function line(ps: Position[]): Geometry {
  return ps.length > 1 ? { type: 'LineString', coordinates: ps } : { type: 'MultiPoint', coordinates: ps };
}
 
function toPolygon(rings: Position[][]): Geometry | undefined {
  const rs = rings.filter(r => r.length);
  Iif (!rs.length) return undefined;
  if (!isLinearRing(rings[0])) return { type: 'GeometryCollection', geometries: rs.map(line) };
  const geometries: Geometry[] = [
    { type: 'Polygon', coordinates: rs.filter(isLinearRing) },
    ...rs.filter(r => !isLinearRing(r)).map(line),
  ];
  return geometries.length === 1 ? geometries[0] : { type: 'GeometryCollection', geometries };
}
 
const DEPTH: Record<string, number> = {
  Point: 0,
  MultiPoint: 1,
  LineString: 1,
  MultiLineString: 2,
  Polygon: 2,
  MultiPolygon: 3,
};
 
/**
 * Convert geometry to another GeoJSON geometry type, keeping as much as
 * possible. Single geometries are wrapped when converting to a multi type,
 * and the first is kept when converting back, except a multi point keeps
 * every position. Polygon rings are lines that
 * are closed when converting to a polygon, and opened when converting back.
 * A geometry collection keeps every geometry when converting to a multi type,
 * otherwise only the first.
 */
export function convertGeometry(geometry: any, type: string): Geometry {
  Iif (!(type in DEPTH)) throw new Error('Unknown geometry type: ' + type);
  if (geometry?.type === 'GeometryCollection') {
    const geometries: any[] = Array.isArray(geometry.geometries) ? geometry.geometries : [];
    if (!type.startsWith('Multi')) return convertGeometry(geometries[0], type);
    return {
      type,
      coordinates: geometries.flatMap(g => (convertGeometry(g, type) as any).coordinates),
    } as Geometry;
  }
  if (geometry?.type === type) return cloneDeep(geometry);
  let depth = DEPTH[geometry?.type] ?? -1;
  let c: any = cloneDeep(geometry?.coordinates);
  // Open polygon rings into lines
  if (depth === 2 && geometry.type === 'Polygon') c = openRings(c);
  if (depth === 3) c = (Array.isArray(c) ? c : []).map(openRings);
  if (depth === 0 && !hasLocation(c) || depth < 0 || depth > 0 && !Array.isArray(c)) {
    // Nothing to keep
    depth = 1;
    c = [];
  }
  const target = DEPTH[type];
  if (type === 'MultiPoint' && depth > 1) {
    // Keep every position
    c = c.flat(depth - 1);
    depth = 1;
  }
  while (depth > target) {
    c = depth === 1 ? c[0] : c[0] || [];
    depth--;
  }
  while (depth < target) {
    if (Array.isArray(c) && !c.length) {
      depth = target;
      break;
    }
    c = [c];
    depth++;
  }
  if (target === 0 && !isPosition(c)) c = [0, 0];
  if (type === 'Polygon') c = closeRings(c);
  if (type === 'MultiPolygon') c = c.map(closeRings);
  return { type, coordinates: c } as Geometry;
}
 
function openRings(rings: any): Position[][] {
  return (Array.isArray(rings) ? rings : []).map((r: any) => Array.isArray(r) && isLinearRing(r) ? r.slice(0, -1) : r);
}
 
function closeRings(rings: Position[][]): Position[][] {
  return rings.map(r => r.length >= 3 && !isLinearRing(r) ? [...r, [...r[0]]] : r);
}
 
/**
 * Convert GeoJSON plugin data (a Feature or FeatureCollection) to the type of
 * the plugin defaults, keeping as much as possible. A FeatureCollection keeps
 * the properties of each feature, otherwise the first feature's properties
 * are kept.
 * Properties are dropped if not allowed.
 */
export function convertFeature(value: any, defaults: any, properties = true): any {
  Iif (!defaults?.type) return undefined;
  const sourceFeatures: any[] = value?.type === 'FeatureCollection'
    ? (Array.isArray(value.features) ? value.features : [])
    : value?.geometry ? [value] : [];
  Iif (!sourceFeatures.length) return undefined;
  const result: any = cloneDeep(defaults);
  Iif (value.bbox) result.bbox = cloneDeep(value.bbox);
  if (defaults.type === 'FeatureCollection') {
    const template = defaults.features?.[0];
    result.features = sourceFeatures.map(f => ({
      type: 'Feature',
      ...f.properties ? { properties: cloneDeep(f.properties) } : {},
      geometry: template?.geometry?.type ? convertGeometry(f.geometry, template.geometry.type) : cloneDeep(f.geometry),
    }));
    return result;
  }
  const type = defaults.geometry?.type;
  Iif (!type) return undefined;
  const geometry = sourceFeatures.length === 1
    ? sourceFeatures[0].geometry
    : { type: 'GeometryCollection', geometries: sourceFeatures.map(f => f.geometry).filter(g => !!g) };
  result.geometry = convertGeometry(geometry, type);
  const props = sourceFeatures.find(f => f.properties)?.properties;
  if (properties && props) result.properties = cloneDeep(props);
  return result;
}
 
export interface MapView {
  center: [number, number];
  zoom: number;
}
 
/**
 * Format a map view for the URL as lng,lat,zoom.
 */
export function formatMapView(view?: MapView) {
  Iif (!view) return '';
  const fixed = (n: number, digits: number) => '' + (Math.round(n * 10 ** digits) / 10 ** digits);
  return [fixed(view.center[0], 5), fixed(view.center[1], 5), fixed(view.zoom, 2)].join(',');
}
 
/**
 * Parse a map view from the URL formatted as lng,lat,zoom.
 */
export function parseMapView(value?: string | null): MapView | undefined {
  if (!value || typeof value !== 'string') return undefined;
  const parts = value.split(',');
  if (parts.length !== 3 || parts.some(p => !p.trim())) return undefined;
  const [lng, lat, zoom] = parts.map(Number);
  if (![lng, lat, zoom].every(isFinite)) return undefined;
  if (Math.abs(lng) > 180 || Math.abs(lat) > 90 || zoom < 0 || zoom > 24) return undefined;
  return { center: [lng, lat], zoom };
}
 
/**
 * Parse a "lng, lat" location, optionally wrapped in brackets like a GeoJSON position.
 */
export function parseLocation(value?: string | null): [number, number] | undefined {
  Iif (!value || typeof value !== 'string') return undefined;
  const parts = value.trim().replace(/^\[(.*)]$/s, '$1').split(',');
  if (parts.length !== 2 || parts.some(p => !p.trim())) return undefined;
  const [lng, lat] = parts.map(Number);
  if (!isFinite(lng) || !isFinite(lat)) return undefined;
  if (Math.abs(lng) > 180 || Math.abs(lat) > 90) return undefined;
  return [lng, lat];
}