function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _templateObject7() {
  var data = _taggedTemplateLiteral(["\n  bottom: 0;\n  right: 0;\n"]);

  _templateObject7 = function _templateObject7() {
    return data;
  };

  return data;
}

function _templateObject6() {
  var data = _taggedTemplateLiteral(["\n  bottom: 0;\n  left: 0;\n"]);

  _templateObject6 = function _templateObject6() {
    return data;
  };

  return data;
}

function _templateObject5() {
  var data = _taggedTemplateLiteral(["\n  top: 0;\n  left: 0;\n"]);

  _templateObject5 = function _templateObject5() {
    return data;
  };

  return data;
}

function _templateObject4() {
  var data = _taggedTemplateLiteral(["\n  top: 0;\n  right: 0;\n"]);

  _templateObject4 = function _templateObject4() {
    return data;
  };

  return data;
}

function _templateObject3() {
  var data = _taggedTemplateLiteral(["\n  position: absolute;\n  margin: 5px 25px 35px 45px;\n"]);

  _templateObject3 = function _templateObject3() {
    return data;
  };

  return data;
}

function _templateObject2() {
  var data = _taggedTemplateLiteral(["\n  position: absolute;\n  left: 0;\n  z-index: 1;\n"]);

  _templateObject2 = function _templateObject2() {
    return data;
  };

  return data;
}

function _templateObject() {
  var data = _taggedTemplateLiteral(["\n  position: relative;\n  margin: 0 auto;\n  padding: 0;\n  width: 100%;\n  height: 100%;\n"]);

  _templateObject = function _templateObject() {
    return data;
  };

  return data;
}

function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); }

import { Component, Children, cloneElement } from "react";
import MapGL, { NavigationControl, Marker, FlyToInterpolator } from "react-map-gl";
import Dimensions from "react-dimensions";
import { jsx, css } from "@emotion/core";
import PropTypes from "prop-types";
import createRef from "create-react-ref/lib/createRef";
import Geocoder from "react-map-gl-geocoder";
import { isEqual } from "lodash";
import bbox from "@turf/bbox";
import WebMercatorViewport from "viewport-mercator-project";
import mapboxgl from "./mapboxgl";
import "mapbox-gl/dist/mapbox-gl.css";
var MapGLResources = {
  MAPBOX_TOKEN: "pk.eyJ1IjoiaGFja29yZWdvbiIsImEiOiJjamk0MGZhc2cwNDl4M3FsdHAwaG54a3BnIn0.Fq1KA0IUwpeKQlFIoaEn_Q",
  CIVIC_LIGHT: "mapbox://styles/hackoregon/cjiazbo185eib2srytwzleplg",
  CIVIC_PENCIL: "mapbox://styles/hackoregon/ck0blt1d63wrm1cqhcnccrf9s",
  CIVIC_DARK: "mapbox://styles/mapbox/dark-v9",
  SANDBOX_DARK: "mapbox://styles/hackoregon/cjyluzgci27k41crxywr2gqnr",
  DISASTER_GAME: "mapbox://styles/hackoregon/cjzki4sok5wgd1cmxadz9xdxi"
};
var MAPBOX_TOKEN = MapGLResources.MAPBOX_TOKEN,
    CIVIC_LIGHT = MapGLResources.CIVIC_LIGHT,
    CIVIC_DARK = MapGLResources.CIVIC_DARK,
    CIVIC_PENCIL = MapGLResources.CIVIC_PENCIL,
    DISASTER_GAME = MapGLResources.DISASTER_GAME,
    SANDBOX_DARK = MapGLResources.SANDBOX_DARK;
var mapWrapper = css(_templateObject());
var navControl = css(_templateObject2());
var geoCoderWrapper = css(_templateObject3());
var topRight = css(_templateObject4());
var topLeft = css(_templateObject5());
var bottomLeft = css(_templateObject6());
var bottomRight = css(_templateObject7());

var BaseMap = function (_Component) {
  _inherits(BaseMap, _Component);

  function BaseMap(props) {
    var _this;

    _classCallCheck(this, BaseMap);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(BaseMap).call(this, props));

    _defineProperty(_assertThisInitialized(_this), "onHover", function (_ref) {
      var object = _ref.object,
          x = _ref.x,
          y = _ref.y;

      _this.setState({
        tooltipInfo: object,
        x: x,
        y: y
      });
    });

    _defineProperty(_assertThisInitialized(_this), "onViewportChange", function (viewport) {
      var _this$props = _this.props,
          minZoom = _this$props.minZoom,
          maxZoom = _this$props.maxZoom;
      var zoom = viewport.zoom;

      if (zoom >= minZoom && zoom <= maxZoom) {
        _this.setState(function (prevState) {
          return {
            viewport: _objectSpread({}, prevState.viewport, viewport)
          };
        });
      } else if (zoom < minZoom) {
        _this.setState(function (prevState) {
          return {
            viewport: _objectSpread({}, prevState.viewport, {
              zoom: minZoom
            })
          };
        });
      } else if (zoom > maxZoom) {
        _this.setState(function (prevState) {
          return {
            viewport: _objectSpread({}, prevState.viewport, {
              zoom: maxZoom
            })
          };
        });
      }
    });

    _this.state = {
      viewport: {
        longitude: props.initialLongitude,
        latitude: props.initialLatitude,
        zoom: props.initialZoom,
        minZoom: props.minZoom,
        maxZoom: props.maxZoom,
        pitch: props.initialPitch,
        bearing: 0
      },
      tooltipInfo: null,
      x: null,
      y: null,
      mounted: false
    };
    _this.mapRef = createRef();
    _this.geocoderContainerRef = createRef();
    return _this;
  }

  _createClass(BaseMap, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.setState({
        mounted: true
      });
      var _this$props2 = this.props,
          bboxData = _this$props2.bboxData,
          bboxPadding = _this$props2.bboxPadding,
          boundBox = _this$props2.boundBox;
      var viewport = this.state.viewport;

      if (bboxData.length > 0) {
        var toGeoJSON = {
          type: "FeatureCollection",
          features: _toConsumableArray(bboxData)
        };
        var boundingBox = bbox(toGeoJSON);
        var bboxViewport = new WebMercatorViewport({
          width: viewport.width,
          height: viewport.height
        }).fitBounds([[boundingBox[0], boundingBox[1]], [boundingBox[2], boundingBox[3]]], {
          padding: bboxPadding
        });
        this.onViewportChange(bboxViewport);
      }

      if (boundBox.length === 4) {
        var _bboxViewport = new WebMercatorViewport({
          width: viewport.width,
          height: viewport.height
        }).fitBounds([[boundBox[0], boundBox[1]], [boundBox[2], boundBox[3]]], {
          padding: bboxPadding
        });

        this.onViewportChange(_bboxViewport);
      }
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(props) {
      var updateViewport = props.updateViewport;

      if (updateViewport) {
        var updatedViewportProps = {
          zoom: props.initialZoom,
          pitch: props.initialPitch,
          longitude: props.initialLongitude,
          latitude: props.initialLatitude
        };
        Object.keys(updatedViewportProps).forEach(function (key) {
          if (updatedViewportProps[key] == null) {
            delete updatedViewportProps[key];
          }
        });
        this.setState(function (prevState) {
          return {
            viewport: _objectSpread({}, prevState.viewport, updatedViewportProps)
          };
        });
      }
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var prevMapboxData = prevProps.mapboxData,
          prevMapboxLayerOptions = prevProps.mapboxLayerOptions,
          prevBoundBox = prevProps.boundBox;
      var _this$props3 = this.props,
          mapboxData = _this$props3.mapboxData,
          mapboxDataId = _this$props3.mapboxDataId,
          mapboxLayerOptions = _this$props3.mapboxLayerOptions,
          mapboxLayerId = _this$props3.mapboxLayerId,
          bboxData = _this$props3.bboxData,
          bboxPadding = _this$props3.bboxPadding,
          boundBox = _this$props3.boundBox;
      var viewport = this.state.viewport;

      if (!isEqual(prevMapboxData, mapboxData)) {
        var map = this.mapRef.current.getMap();
        map.getSource(mapboxDataId).setData(mapboxData);
      }

      if (!isEqual(prevMapboxLayerOptions, mapboxLayerOptions)) {
        var _map = this.mapRef.current.getMap();

        var updatedProperties = Object.keys(mapboxLayerOptions).filter(function (m) {
          return !isEqual(prevMapboxLayerOptions[m], mapboxLayerOptions[m]);
        });
        updatedProperties.forEach(function (p) {
          return _map.setPaintProperty(mapboxLayerId, p, mapboxLayerOptions[p]);
        });
      }

      if (bboxData.length > 0 && !isEqual(prevProps.bboxData, bboxData)) {
        var toGeoJSON = {
          type: "FeatureCollection",
          features: _toConsumableArray(bboxData)
        };
        var boundingbox = bbox(toGeoJSON);
        var bboxViewport = new WebMercatorViewport({
          width: viewport.width,
          height: viewport.height
        }).fitBounds([[boundingbox[0], boundingbox[1]], [boundingbox[2], boundingbox[3]]], {
          padding: bboxPadding
        });
        this.onViewportChange(bboxViewport);
      }

      if (boundBox.length === 4 && !isEqual(prevBoundBox, boundBox)) {
        var _bboxViewport2 = new WebMercatorViewport({
          width: viewport.width,
          height: viewport.height
        }).fitBounds([[boundBox[0], boundBox[1]], [boundBox[2], boundBox[3]]], {
          padding: bboxPadding
        });

        this.onViewportChange(_bboxViewport2);
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$state = this.state,
          viewport = _this$state.viewport,
          tooltipInfo = _this$state.tooltipInfo,
          x = _this$state.x,
          y = _this$state.y,
          mounted = _this$state.mounted;
      var _this$props4 = this.props,
          height = _this$props4.height,
          containerHeight = _this$props4.containerHeight,
          containerWidth = _this$props4.containerWidth,
          civicMapStyle = _this$props4.civicMapStyle,
          mapboxToken = _this$props4.mapboxToken,
          navigation = _this$props4.navigation,
          geocoder = _this$props4.geocoder,
          locationMarker = _this$props4.locationMarker,
          geocoderOptions = _this$props4.geocoderOptions,
          geocoderOnChange = _this$props4.geocoderOnChange,
          geocoderPosition = _this$props4.geocoderPosition,
          mapGLOptions = _this$props4.mapGLOptions,
          children = _this$props4.children,
          useContainerHeight = _this$props4.useContainerHeight,
          onBaseMapClick = _this$props4.onBaseMapClick,
          onBaseMapHover = _this$props4.onBaseMapHover,
          onBaseMapMouseOut = _this$props4.onBaseMapMouseOut,
          mapboxData = _this$props4.mapboxData,
          mapboxDataId = _this$props4.mapboxDataId,
          mapboxLayerType = _this$props4.mapboxLayerType,
          mapboxLayerOptions = _this$props4.mapboxLayerOptions,
          mapboxLayerId = _this$props4.mapboxLayerId,
          locationMarkerCoord = _this$props4.locationMarkerCoord,
          animate = _this$props4.animate,
          animationDuration = _this$props4.animationDuration,
          scaleBar = _this$props4.scaleBar,
          scaleBarOptions = _this$props4.scaleBarOptions,
          sharedViewport = _this$props4.sharedViewport,
          onSharedViewportChange = _this$props4.onSharedViewportChange,
          useScrollZoom = _this$props4.useScrollZoom,
          useFitBounds = _this$props4.useFitBounds,
          bboxData = _this$props4.bboxData;
      viewport.width = containerWidth || 500;
      viewport.height = useContainerHeight ? containerHeight : height;
      var childrenLayers = Children.map(children, function (child) {
        var layerViewport = sharedViewport ? _objectSpread({}, viewport, sharedViewport) : viewport;
        return cloneElement(child, {
          viewport: layerViewport,
          tooltipInfo: tooltipInfo,
          x: x,
          y: y,
          onHover: function onHover(info) {
            return _this2.onHover(info);
          }
        });
      });

      var onMapLoad = function onMapLoad() {
        var map = _this2.mapRef.current.getMap();

        if (scaleBar) {
          map.addControl(new mapboxgl.ScaleControl({
            maxWidth: scaleBarOptions.maxWidth,
            unit: scaleBarOptions.units
          }));
        }

        if (!mapboxData || !mapboxLayerType || !mapboxLayerOptions) return;
        map.addSource(mapboxDataId, {
          type: "geojson",
          data: mapboxData
        });
        map.addLayer({
          id: mapboxLayerId,
          type: mapboxLayerType,
          source: mapboxDataId,
          paint: mapboxLayerOptions
        }, "waterway-label");
      };

      var baseMapboxStyleURL = CIVIC_LIGHT;

      if (civicMapStyle === "dark") {
        baseMapboxStyleURL = CIVIC_DARK;
      } else if (civicMapStyle === "pencil") {
        baseMapboxStyleURL = CIVIC_PENCIL;
      } else if (civicMapStyle === "disaster-game") {
        baseMapboxStyleURL = DISASTER_GAME;
      } else if (civicMapStyle === "sandbox-dark") {
        baseMapboxStyleURL = SANDBOX_DARK;
      }

      var animationProps = !animate ? {} : {
        transitionDuration: animationDuration,
        transitionInterpolator: new FlyToInterpolator()
      };
      var boundingbox;

      if (useFitBounds && bboxData.length > 0) {
        var toGeoJSON = {
          type: "FeatureCollection",
          features: _toConsumableArray(bboxData)
        };
        boundingbox = bbox(toGeoJSON);
      }

      var finalViewport = sharedViewport ? _objectSpread({}, viewport, sharedViewport, {
        height: height,
        width: containerWidth
      }) : viewport;
      var geocoderPositions = {
        "top-left": topLeft,
        "top-right": topRight,
        "bottom-left": bottomLeft,
        "bottom-right": bottomRight
      };
      return jsx("div", {
        css: mapWrapper
      }, jsx("div", {
        ref: this.geocoderContainerRef,
        css: [geoCoderWrapper, geocoderPositions[geocoderPosition]]
      }), jsx(MapGL, _extends({
        className: "MapGL"
      }, finalViewport, animationProps, {
        mapStyle: baseMapboxStyleURL,
        mapboxApiAccessToken: mapboxToken,
        onViewportChange: function onViewportChange(newViewport) {
          if (onSharedViewportChange) {
            onSharedViewportChange(newViewport);
          } else {
            _this2.onViewportChange(newViewport);
          }
        },
        ref: this.mapRef
      }, mapGLOptions, {
        onClick: onBaseMapClick,
        onHover: function onHover(baseInfo) {
          var baseMapboxRef = _this2.mapRef.current.getMap();

          if (onBaseMapHover) {
            onBaseMapHover(baseInfo, baseMapboxRef);
          }
        },
        onMouseOut: function onMouseOut() {
          var baseMapboxRef = _this2.mapRef.current.getMap();

          if (onBaseMapMouseOut) {
            onBaseMapMouseOut(baseMapboxRef);
          }
        },
        onBlur: function onBlur() {
          var baseMapboxRef = _this2.mapRef.current.getMap();

          if (onBaseMapMouseOut) {
            onBaseMapMouseOut(baseMapboxRef);
          }
        },
        onLoad: onMapLoad,
        scrollZoom: useScrollZoom
      }), jsx("div", {
        css: navControl
      }, navigation && jsx(NavigationControl, null)), locationMarker && jsx(Marker, {
        latitude: locationMarkerCoord.latitude,
        longitude: locationMarkerCoord.longitude,
        offsetLeft: -20,
        offsetTop: -10
      }, jsx("span", {
        role: "img",
        "aria-label": "star"
      }, "\u274C")), geocoder && mounted && jsx(Geocoder, {
        mapRef: {
          current: this.mapRef.current
        },
        containerRef: this.geocoderContainerRef,
        mapboxApiAccessToken: mapboxToken,
        onViewportChange: function onViewportChange(newViewport) {
          _this2.onViewportChange(newViewport);

          !!geocoderOnChange && geocoderOnChange(newViewport);
        },
        bbox: boundingbox,
        position: geocoderPosition,
        options: _objectSpread({}, geocoderOptions)
      }), childrenLayers));
    }
  }]);

  return BaseMap;
}(Component);

BaseMap.propTypes = {
  initialLongitude: PropTypes.number,
  initialLatitude: PropTypes.number,
  initialZoom: PropTypes.number,
  minZoom: PropTypes.number,
  maxZoom: PropTypes.number,
  initialPitch: PropTypes.number,
  height: PropTypes.number,
  containerHeight: PropTypes.number,
  containerWidth: PropTypes.number,
  mapboxToken: PropTypes.string,
  civicMapStyle: PropTypes.oneOf(["light", "dark", "pencil", "disaster-game", "sandbox-dark"]),
  navigation: PropTypes.bool,
  locationMarker: PropTypes.bool,
  locationMarkerCoord: PropTypes.shape({
    latitude: PropTypes.number,
    longitude: PropTypes.number
  }),
  geocoder: PropTypes.bool,
  geocoderOptions: PropTypes.shape({}),
  geocoderOnChange: PropTypes.func,
  geocoderPosition: PropTypes.oneOf(["top-left", "top-right", "bottom-left", "bottom-right"]),
  mapGLOptions: PropTypes.shape({}),
  children: PropTypes.node,
  useContainerHeight: PropTypes.bool,
  updateViewport: PropTypes.bool,
  animate: PropTypes.bool,
  animationDuration: PropTypes.number,
  onBaseMapClick: PropTypes.func,
  onBaseMapHover: PropTypes.func,
  onBaseMapMouseOut: PropTypes.func,
  mapboxDataId: PropTypes.string,
  mapboxData: PropTypes.shape({
    type: PropTypes.string,
    features: PropTypes.arrayOf(PropTypes.shape({}))
  }),
  mapboxLayerType: PropTypes.string,
  mapboxLayerId: PropTypes.string,
  mapboxLayerOptions: PropTypes.shape({}),
  scaleBar: PropTypes.bool,
  scaleBarOptions: PropTypes.shape({
    maxWidth: PropTypes.number,
    units: PropTypes.string
  }),
  sharedViewport: PropTypes.shape({}),
  onSharedViewportChange: PropTypes.func,
  bboxData: PropTypes.arrayOf(PropTypes.shape({})),
  bboxPadding: PropTypes.number,
  boundBox: PropTypes.arrayOf(PropTypes.number),
  useScrollZoom: PropTypes.bool,
  useFitBounds: PropTypes.bool
};
BaseMap.defaultProps = {
  mapboxToken: MAPBOX_TOKEN,
  navigation: true,
  geocoder: false,
  geocoderPosition: "top-right",
  useContainerHeight: false,
  updateViewport: true,
  animate: false,
  initialLongitude: -122.6765,
  initialLatitude: 45.5231,
  initialZoom: 9.5,
  minZoom: 6,
  maxZoom: 20,
  initialPitch: 0,
  height: 500,
  locationMarkerCoord: {
    latitude: 0,
    longitude: 0
  },
  animationDuration: 1000,
  scaleBar: false,
  bboxData: [],
  bboxPadding: 10,
  boundBox: [],
  useScrollZoom: false
};
export default Dimensions()(BaseMap);