All files / app/components EditLocationMap.tsx

57.63% Statements 83/144
36.92% Branches 24/65
38.7% Functions 12/31
61.94% Lines 83/134

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 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 4662x 2x 2x 2x 2x 2x           2x 2x 2x                     2x   2x                                                                       2x                 34x 34x 34x   34x     34x             34x     34x 34x       34x                                         34x                       34x       1x 1x 1x 1x   1x 1x       1x 1x   1x     34x 1x 1x 1x                   34x       2x 2x 1x 1x   2x     2x           2x 1x       1x       1x           1x 1x 1x         34x 4x 4x                                                                                                             4x       4x   4x               4x 4x   4x 4x 4x 4x 4x     34x 1x 1x 1x 1x         1x                   34x                                                 1x 1x 1x 1x   1x                                                                             30x 30x                                                           35x                                                 1x                   60x                                           62x   62x         62x    
import { BoxProps, Slider, Typography, useTheme } from "@material-ui/core";
import { userLocationMaxRadius, userLocationMinRadius } from "appConstants";
import classNames from "classnames";
import Map from "components/Map";
import MapSearch from "components/MapSearch";
import TextField from "components/TextField";
import maplibregl, {
  GeoJSONSource,
  LngLat,
  MapMouseEvent,
  MapTouchEvent,
} from "maplibre-gl";
import React, { useRef, useState } from "react";
import makeStyles from "utils/makeStyles";
 
import {
  DISPLAY_LOCATION,
  DISPLAY_LOCATION_NOT_EMPTY,
  getRadiusText,
  INVALID_COORDINATE,
  LOCATION_ACCURACY,
  LOCATION_PUBLICLY_VISIBLE,
  LOCATION_WARN,
  MAP_IS_BLANK,
} from "./constants";
 
const useStyles = makeStyles({
  root: {
    margin: "auto",
    maxWidth: 700,
  },
  map: {
    height: 400,
    position: "relative",
  },
  grow: {
    height: "100%",
    width: "100%",
  },
  displayLocation: {
    width: "100%",
  },
});
 
export interface ApproximateLocation {
  address: string;
  lat: number;
  lng: number;
  radius: number;
}
 
export interface EditLocationMapProps extends BoxProps {
  initialLocation?: ApproximateLocation;
  // this function is called on mouse release
  updateLocation: (value: ApproximateLocation | null) => void;
  grow?: boolean;
  // whether to hide the radius slider
  showRadiusSlider?: boolean;
  // whether we are selecting an exact point (for pages, etc) or approx circle, doesn't maeks ense with radius slider
  exact?: boolean;
}
 
export default function EditLocationMap({
  initialLocation,
  updateLocation,
  className,
  grow,
  showRadiusSlider,
  exact,
  ...otherProps
}: EditLocationMapProps) {
  const classes = useStyles();
  const theme = useTheme();
  const [error, setError] = useState("");
 
  const map = useRef<maplibregl.Map | null>(null);
 
  // map is imperative so these don't need to cause re-render
  const location = useRef<ApproximateLocation>({
    address: initialLocation?.address ?? "",
    radius: initialLocation?.radius ?? (exact ? 0 : 250),
    lat: initialLocation?.lat ?? 0,
    lng: initialLocation?.lng ?? 0,
  });
  // have not selected a location in any way yet
  const isBlank = useRef<boolean>(
    !(initialLocation?.lng || initialLocation?.lat)
  );
  const locationDisplayRef = useRef<HTMLInputElement>(null);
  const [shrinkLabel, setShrinkLabel] = useState(
    location.current.address !== ""
  );
 
  const onCircleMouseDown = (e: MapMouseEvent | MapTouchEvent) => {
    Iif (!map.current) return;
    // Prevent the default map drag behavior.
    e.preventDefault();
 
    map.current.getCanvas().style.cursor = "grab";
 
    if (e.type === "touchstart") {
      const handleTouchMove = (e: MapMouseEvent | MapTouchEvent) =>
        onCircleMove(e);
      map.current.on("touchmove", handleTouchMove);
      map.current.once("touchend", (e) =>
        handleCoordinateMoved(e, handleTouchMove)
      );
    } else {
      const handleMove = (e: MapMouseEvent | MapTouchEvent) => onCircleMove(e);
      map.current.on("mousemove", handleMove);
      map.current.once("mouseup", (e) => handleCoordinateMoved(e, handleMove));
    }
  };
 
  const onCircleMove = (e: MapMouseEvent | MapTouchEvent) => {
    const wrapped = e.lngLat.wrap();
    commit(
      {
        lat: wrapped.lat,
        lng: wrapped.lng,
      },
      false
    );
    redrawMap();
  };
 
  const handleCoordinateMoved = (
    e: MapMouseEvent | MapTouchEvent,
    moveHandler: (x: MapMouseEvent | MapTouchEvent) => void = () => null
  ) => {
    Iif (!map.current) return;
    map.current.off("mousemove", moveHandler);
    map.current.off("touchmove", moveHandler);
    map.current.getCanvas().style.cursor = "move";
 
    const wrapped = e.lngLat.wrap();
    commit({
      lat: wrapped.lat,
      lng: wrapped.lng,
    });
    if (!isBlank.current) {
      map.current.setLayoutProperty("circle", "visibility", "visible");
    }
    redrawMap();
  };
 
  const redrawMap = () => {
    Iif (!map.current) return;
    if (!exact) {
      (map.current.getSource("circle") as GeoJSONSource).setData(
        circleGeoJson(extractLngLat(location.current), location.current.radius)
      );
    } else E{
      (map.current.getSource("circle") as GeoJSONSource).setData(
        pointGeoJson(extractLngLat(location.current))
      );
    }
  };
 
  const commit = (
    updates: Partial<ApproximateLocation>,
    shouldUpdate = true
  ) => {
    const addressNotEmpty = !!updates.address;
    if (updates.address !== undefined) {
      setShrinkLabel(addressNotEmpty);
      location.current.address = updates.address;
    }
    Iif (updates.radius !== undefined && !exact) {
      location.current.radius = updates.radius;
    }
    Iif (updates.lat !== undefined && updates.lng !== undefined) {
      location.current.lat = updates.lat;
      location.current.lng = updates.lng;
      isBlank.current = false;
    }
 
    if (shouldUpdate) {
      Iif (isBlank.current) {
        // haven't selected a location yet
        setError(addressNotEmpty ? MAP_IS_BLANK : "");
        updateLocation(null);
      } else Iif (location.current.lat === 0 && location.current.lng === 0) {
        // somehow have lat/lng == 0
        setError(INVALID_COORDINATE);
        updateLocation(null);
      } else Iif (location.current.address === "") {
        // missing display address
        setError(DISPLAY_LOCATION_NOT_EMPTY);
        setShrinkLabel(false);
        updateLocation(null);
      } else {
        setError("");
        setShrinkLabel(true);
        updateLocation({ ...location.current });
      }
    }
  };
 
  const initializeMap = (mapRef: maplibregl.Map) => {
    map.current = mapRef;
    map.current.once("load", () => {
      Iif (!map.current) return;
      if (!exact) {
        map.current.addSource("circle", {
          data: circleGeoJson(
            extractLngLat(location.current),
            location.current.radius
          ),
          type: "geojson",
        });
 
        map.current.addLayer({
          id: "circle",
          layout: {
            visibility: isBlank.current ? "none" : "visible",
          },
          paint: {
            "fill-color": theme.palette.primary.main,
            "fill-opacity": 0.5,
          },
          source: "circle",
          type: "fill",
        });
      } else {
        map.current.addSource("circle", {
          data: pointGeoJson(extractLngLat(location.current)),
          type: "geojson",
        });
 
        map.current.addLayer({
          id: "circle",
          layout: {
            visibility: isBlank.current ? "none" : "visible",
          },
          paint: {
            "circle-color": theme.palette.primary.main,
            "circle-radius": 8,
            "circle-stroke-color": "#fff",
            "circle-stroke-width": 1,
          },
          source: "circle",
          type: "circle",
        });
      }
 
      // if no user is specified, ask to get the location from browser
      Iif (!initialLocation && navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
          flyToSearch(
            new LngLat(position.coords.longitude, position.coords.latitude)
          );
        });
      }
    });
 
    const onDblClick = (e: MapMouseEvent & maplibregl.EventData) => {
      e.preventDefault();
      handleCoordinateMoved(e);
    };
    map.current.on("dblclick", onDblClick);
 
    const onCircleTouch = (
      e: MapTouchEvent & {
        features?: maplibregl.MapboxGeoJSONFeature[] | undefined;
      } & maplibregl.EventData
    ) => {
      Iif (e.points.length !== 1) return;
      onCircleMouseDown(e);
    };
    map.current.on("mousedown", "circle", onCircleMouseDown);
    map.current.on("touchstart", "circle", onCircleTouch);
 
    const canvas = map.current.getCanvas();
    const setCursorMove = () => (canvas.style.cursor = "move");
    const unsetCursor = () => (canvas.style.cursor = "");
    map.current.on("mouseenter", "circle", setCursorMove);
    map.current.on("mouseleave", "circle", unsetCursor);
  };
 
  const flyToSearch = (coords: LngLat) => {
    Iif (!map.current) return;
    map.current.flyTo({ center: coords, zoom: 12.5 });
    if (!exact) {
      const randomizedLocation = displaceLngLat(
        coords,
        Math.random() * location.current.radius,
        Math.random() * 2 * Math.PI
      );
      handleCoordinateMoved({
        lngLat: randomizedLocation,
      } as MapMouseEvent);
    } else E{
      handleCoordinateMoved({
        lngLat: coords,
      } as MapMouseEvent);
    }
  };
 
  return (
    <>
      <div
        className={classNames(
          classes.root,
          { [classes.grow]: grow },
          className
        )}
      >
        <div className={classNames(classes.map)}>
          <Map
            // (10, 35, 0.5) is just a pretty view
            initialZoom={isBlank.current ? 0.5 : 12.5}
            initialCenter={
              isBlank.current
                ? new LngLat(10, 35)
                : extractLngLat(location.current)
            }
            postMapInitialize={initializeMap}
            grow
            {...otherProps}
          />
          <MapSearch
            setError={setError}
            setResult={(coordinate, _, simplified) => {
              commit({ address: simplified }, false);
              if (locationDisplayRef.current) {
                locationDisplayRef.current.value = simplified;
                setShrinkLabel(true);
              }
              flyToSearch(coordinate);
            }}
          />
        </div>
        {showRadiusSlider && (
          <RadiusSlider
            commit={commit}
            initialRadius={location.current.radius}
            redrawMap={redrawMap}
          />
        )}
        <TextField
          defaultValue={location.current.address}
          onChange={(e) => {
            commit({ address: e.target.value });
          }}
          error={error !== ""}
          id="display-address"
          inputRef={locationDisplayRef}
          InputLabelProps={{ shrink: shrinkLabel }}
          fullWidth
          variant="standard"
          label={DISPLAY_LOCATION}
          helperText={error !== "" ? error : LOCATION_PUBLICLY_VISIBLE}
          onFocus={() => setShrinkLabel(true)}
          onBlur={() => !location.current.address && setShrinkLabel(false)}
        />
      </div>
    </>
  );
}
 
interface RadiusSliderProps {
  commit(updates: Partial<ApproximateLocation>, shouldUpdate?: boolean): void;
  initialRadius: number;
  redrawMap(): void;
}
 
function RadiusSlider({ commit, initialRadius, redrawMap }: RadiusSliderProps) {
  const [radius, setRadius] = useState(initialRadius);
  return (
    <>
      <Typography variant="body2" gutterBottom>
        {LOCATION_WARN}
      </Typography>
      <Typography id="location-radius" gutterBottom>
        {LOCATION_ACCURACY}
      </Typography>
      <Slider
        aria-labelledby="location-radius"
        aria-valuetext={getRadiusText(radius)}
        value={radius}
        step={5}
        min={userLocationMinRadius}
        max={userLocationMaxRadius}
        onChange={(_, value) => {
          setRadius(value as number);
          commit({ radius: value as number }, false);
          redrawMap();
        }}
        onChangeCommitted={(_, value) => {
          commit({ radius: value as number });
          redrawMap();
        }}
      />
    </>
  );
}
 
function extractLngLat(loc: ApproximateLocation): LngLat {
  return new LngLat(loc.lng, loc.lat);
}
 
function pointGeoJson(
  coords: LngLat
): GeoJSON.FeatureCollection<GeoJSON.Geometry> {
  return {
    features: [
      {
        geometry: {
          coordinates: coords.toArray(),
          type: "Point",
        },
        properties: {},
        type: "Feature",
      },
    ],
    type: "FeatureCollection",
  };
}
 
function circleGeoJson(
  coords: LngLat,
  radius: number
): GeoJSON.FeatureCollection<GeoJSON.Geometry> {
  return {
    features: [
      {
        geometry: {
          //create a circle of 60 points
          coordinates: [
            [
              ...Array(60)
                .fill(0)
                .map((_, index) => {
                  return displaceLngLat(
                    coords,
                    radius,
                    (index * 2 * Math.PI) / 60
                  ).toArray();
                }),
              displaceLngLat(coords, radius, 0).toArray(),
            ],
          ],
          type: "Polygon",
        },
        properties: {},
        type: "Feature",
      },
    ],
    type: "FeatureCollection",
  };
}
 
function displaceLngLat(coords: LngLat, distance: number, angle: number) {
  // see https://gis.stackexchange.com/a/2964
  // 111111 m ~ 1 degree
  const lat = coords.lat + (1 / 111111) * distance * Math.cos(angle);
  const lng =
    coords.lng +
    (1 / (111111 * Math.cos((coords.lat / 360) * 2 * Math.PI))) *
      distance *
      Math.sin(angle);
 
  return new LngLat(lng, lat);
}