Skip to content

Commit

Permalink
[Maps] lazy load maps_legacy, tile_map, and region_map bundle (elasti…
Browse files Browse the repository at this point in the history
…c#78027)

* [Maps] lazy load maps_legacy bundle

* tslint

* lazy load leaflet

* try to get lodash out of maps_legacy bundle and work on tile_map bundle

* lazy load service settings

* lazy load region_map and fix vega unit tests

* tslint fixes

* remove lodash from region_map bundle

* review feedback

* remove unused file

Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com>
  • Loading branch information
nreese and elasticmachine committed Sep 24, 2020
1 parent c912b55 commit 8a88cbc
Show file tree
Hide file tree
Showing 33 changed files with 338 additions and 193 deletions.
39 changes: 39 additions & 0 deletions src/plugins/maps_legacy/public/get_service_settings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { lazyLoadMapsLegacyModules } from './lazy_load_bundle';
// @ts-expect-error
import { getMapsLegacyConfig } from './kibana_services';
import { IServiceSettings } from './map/service_settings_types';

let loadPromise: Promise<IServiceSettings>;

export async function getServiceSettings(): Promise<IServiceSettings> {
if (typeof loadPromise !== 'undefined') {
return loadPromise;
}

loadPromise = new Promise(async (resolve) => {
const modules = await lazyLoadMapsLegacyModules();
const config = getMapsLegacyConfig();
// @ts-expect-error
resolve(new modules.ServiceSettings(config, config.tilemap));
});
return loadPromise;
}
10 changes: 4 additions & 6 deletions src/plugins/maps_legacy/public/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@

// @ts-ignore
import { PluginInitializerContext } from 'kibana/public';
// @ts-ignore
import { L } from './leaflet';
import { MapsLegacyPlugin } from './plugin';
// @ts-ignore
import * as colorUtil from './map/color_util';
Expand All @@ -29,14 +27,14 @@ import { KibanaMapLayer } from './map/kibana_map_layer';
// @ts-ignore
import { convertToGeoJson } from './map/convert_to_geojson';
// @ts-ignore
import { scaleBounds, getPrecision, geoContains } from './map/decode_geo_hash';
import { getPrecision, geoContains } from './map/decode_geo_hash';
import {
VectorLayer,
FileLayerField,
FileLayer,
TmsLayer,
IServiceSettings,
} from './map/service_settings';
} from './map/service_settings_types';
// @ts-ignore
import { mapTooltipProvider } from './tooltip_provider';

Expand All @@ -48,7 +46,6 @@ export function plugin(initializerContext: PluginInitializerContext) {

/** @public */
export {
scaleBounds,
getPrecision,
geoContains,
colorUtil,
Expand All @@ -60,13 +57,14 @@ export {
FileLayer,
TmsLayer,
mapTooltipProvider,
L,
};

export * from './common/types';
export { ORIGIN } from './common/constants/origin';

export { WmsOptions } from './components/wms_options';

export { lazyLoadMapsLegacyModules } from './lazy_load_bundle';

export type MapsLegacyPluginSetup = ReturnType<MapsLegacyPlugin['setup']>;
export type MapsLegacyPluginStart = ReturnType<MapsLegacyPlugin['start']>;
43 changes: 43 additions & 0 deletions src/plugins/maps_legacy/public/lazy_load_bundle/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

let loadModulesPromise: Promise<LazyLoadedMapsLegacyModules>;

interface LazyLoadedMapsLegacyModules {
KibanaMap: unknown;
L: unknown;
ServiceSettings: unknown;
}

export async function lazyLoadMapsLegacyModules(): Promise<LazyLoadedMapsLegacyModules> {
if (typeof loadModulesPromise !== 'undefined') {
return loadModulesPromise;
}

loadModulesPromise = new Promise(async (resolve) => {
const { KibanaMap, L, ServiceSettings } = await import('./lazy');

resolve({
KibanaMap,
L,
ServiceSettings,
});
});
return loadModulesPromise;
}
25 changes: 25 additions & 0 deletions src/plugins/maps_legacy/public/lazy_load_bundle/lazy/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

// @ts-expect-error
export { KibanaMap } from '../../map/kibana_map';
// @ts-expect-error
export { ServiceSettings } from '../../map/service_settings';
// @ts-expect-error
export { L } from '../../leaflet';
32 changes: 15 additions & 17 deletions src/plugins/maps_legacy/public/map/base_maps_visualization.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,22 @@
* under the License.
*/

import _ from 'lodash';
import { i18n } from '@kbn/i18n';
import * as Rx from 'rxjs';
import { filter, first } from 'rxjs/operators';
import { getEmsTileLayerId, getUiSettings, getToasts } from '../kibana_services';
import { lazyLoadMapsLegacyModules } from '../lazy_load_bundle';
import { getServiceSettings } from '../get_service_settings';

const WMS_MINZOOM = 0;
const WMS_MAXZOOM = 22; //increase this to 22. Better for WMS

export function BaseMapsVisualizationProvider(getKibanaMap, mapServiceSettings) {
export function BaseMapsVisualizationProvider() {
/**
* Abstract base class for a visualization consisting of a map with a single baselayer.
* @class BaseMapsVisualization
* @constructor
*/

const serviceSettings = mapServiceSettings;
const toastService = getToasts();

return class BaseMapsVisualization {
constructor(element, vis) {
this.vis = vis;
Expand Down Expand Up @@ -95,9 +92,9 @@ export function BaseMapsVisualizationProvider(getKibanaMap, mapServiceSettings)
const centerFromUIState = uiState.get('mapCenter');
options.zoom = !isNaN(zoomFromUiState) ? zoomFromUiState : this.vis.params.mapZoom;
options.center = centerFromUIState ? centerFromUIState : this.vis.params.mapCenter;
const services = { toastService };

this._kibanaMap = getKibanaMap(this._container, options, services);
const modules = await lazyLoadMapsLegacyModules();
this._kibanaMap = new modules.KibanaMap(this._container, options);
this._kibanaMap.setMinZoom(WMS_MINZOOM); //use a default
this._kibanaMap.setMaxZoom(WMS_MAXZOOM); //use a default

Expand Down Expand Up @@ -138,6 +135,7 @@ export function BaseMapsVisualizationProvider(getKibanaMap, mapServiceSettings)
const mapParams = this._getMapsParams();
if (!this._tmsConfigured()) {
try {
const serviceSettings = await getServiceSettings();
const tmsServices = await serviceSettings.getTMSServices();
const userConfiguredTmsLayer = tmsServices[0];
const initBasemapLayer = userConfiguredTmsLayer
Expand All @@ -147,7 +145,7 @@ export function BaseMapsVisualizationProvider(getKibanaMap, mapServiceSettings)
this._setTmsLayer(initBasemapLayer);
}
} catch (e) {
toastService.addWarning(e.message);
getToasts().addWarning(e.message);
return;
}
return;
Expand All @@ -174,7 +172,7 @@ export function BaseMapsVisualizationProvider(getKibanaMap, mapServiceSettings)
this._setTmsLayer(selectedTmsLayer);
}
} catch (tmsLoadingError) {
toastService.addWarning(tmsLoadingError.message);
getToasts().addWarning(tmsLoadingError.message);
}
}

Expand All @@ -189,13 +187,14 @@ export function BaseMapsVisualizationProvider(getKibanaMap, mapServiceSettings)
isDesaturated = true;
}
const isDarkMode = getUiSettings().get('theme:darkMode');
const serviceSettings = await getServiceSettings();
const meta = await serviceSettings.getAttributesForTMSLayer(
tmsLayer,
isDesaturated,
isDarkMode
);
const showZoomMessage = serviceSettings.shouldShowZoomMessage(tmsLayer);
const options = _.cloneDeep(tmsLayer);
const options = { ...tmsLayer };
delete options.id;
delete options.subdomains;
this._kibanaMap.setBaseLayer({
Expand Down Expand Up @@ -228,12 +227,11 @@ export function BaseMapsVisualizationProvider(getKibanaMap, mapServiceSettings)
}

_getMapsParams() {
return _.assign(
{},
this.vis.type.visConfig.defaults,
{ type: this.vis.type.name },
this._params
);
return {
...this.vis.type.visConfig.defaults,
type: this.vis.type.name,
...this._params,
};
}

_whenBaseLayerIsLoaded() {
Expand Down
29 changes: 0 additions & 29 deletions src/plugins/maps_legacy/public/map/decode_geo_hash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
* under the License.
*/

import _ from 'lodash';

interface DecodedGeoHash {
latitude: number[];
longitude: number[];
Expand Down Expand Up @@ -101,33 +99,6 @@ interface GeoBoundingBox {
bottom_right: GeoBoundingBoxCoordinate;
}

export function scaleBounds(bounds: GeoBoundingBox): GeoBoundingBox {
const scale = 0.5; // scale bounds by 50%

const topLeft = bounds.top_left;
const bottomRight = bounds.bottom_right;
let latDiff = _.round(Math.abs(topLeft.lat - bottomRight.lat), 5);
const lonDiff = _.round(Math.abs(bottomRight.lon - topLeft.lon), 5);
// map height can be zero when vis is first created
if (latDiff === 0) latDiff = lonDiff;

const latDelta = latDiff * scale;
let topLeftLat = _.round(topLeft.lat, 5) + latDelta;
if (topLeftLat > 90) topLeftLat = 90;
let bottomRightLat = _.round(bottomRight.lat, 5) - latDelta;
if (bottomRightLat < -90) bottomRightLat = -90;
const lonDelta = lonDiff * scale;
let topLeftLon = _.round(topLeft.lon, 5) - lonDelta;
if (topLeftLon < -180) topLeftLon = -180;
let bottomRightLon = _.round(bottomRight.lon, 5) + lonDelta;
if (bottomRightLon > 180) bottomRightLon = 180;

return {
top_left: { lat: topLeftLat, lon: topLeftLon },
bottom_right: { lat: bottomRightLat, lon: bottomRightLon },
};
}

export function geoContains(collar?: GeoBoundingBox, bounds?: GeoBoundingBox) {
if (!bounds || !collar) return false;
// test if bounds top_left is outside collar
Expand Down
4 changes: 1 addition & 3 deletions src/plugins/maps_legacy/public/map/grid_dimensions.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
* under the License.
*/

import _ from 'lodash';

// geohash precision mapping of geohash grid cell dimensions (width x height, in meters) at equator.
// https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-geohashgrid-aggregation.html#_cell_dimensions_at_the_equator
const gridAtEquator = {
Expand All @@ -37,5 +35,5 @@ const gridAtEquator = {
};

export function gridDimensions(precision) {
return _.get(gridAtEquator, precision);
return gridAtEquator[precision];
}
10 changes: 5 additions & 5 deletions src/plugins/maps_legacy/public/map/kibana_map.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import { EventEmitter } from 'events';
import { createZoomWarningMsg } from './map_messages';
import $ from 'jquery';
import _ from 'lodash';
import { get, isEqual, escape } from 'lodash';
import { zoomToPrecision } from './zoom_to_precision';
import { i18n } from '@kbn/i18n';
import { ORIGIN } from '../common/constants/origin';
Expand Down Expand Up @@ -380,7 +380,7 @@ export class KibanaMap extends EventEmitter {

const distanceX = latLngC.distanceTo(latLngX); // calculate distance between c and x (latitude)
const distanceY = latLngC.distanceTo(latLngY); // calculate distance between c and y (longitude)
return _.min([distanceX, distanceY]);
return Math.min(distanceX, distanceY);
}

_getLeafletBounds(resizeOnFail) {
Expand Down Expand Up @@ -544,7 +544,7 @@ export class KibanaMap extends EventEmitter {
}

setBaseLayer(settings) {
if (_.isEqual(settings, this._baseLayerSettings)) {
if (isEqual(settings, this._baseLayerSettings)) {
return;
}

Expand All @@ -567,7 +567,7 @@ export class KibanaMap extends EventEmitter {
let baseLayer;
if (settings.baseLayerType === 'wms') {
//This is user-input that is rendered with the Leaflet attribution control. Needs to be sanitized.
this._baseLayerSettings.options.attribution = _.escape(settings.options.attribution);
this._baseLayerSettings.options.attribution = escape(settings.options.attribution);
baseLayer = this._getWMSBaseLayer(settings.options);
} else if (settings.baseLayerType === 'tms') {
baseLayer = this._getTMSBaseLayer(settings.options);
Expand Down Expand Up @@ -661,7 +661,7 @@ export class KibanaMap extends EventEmitter {
_updateDesaturation() {
const tiles = $('img.leaflet-tile-loaded');
// Don't apply client-side styling to EMS basemaps
if (_.get(this._baseLayerSettings, 'options.origin') === ORIGIN.EMS) {
if (get(this._baseLayerSettings, 'options.origin') === ORIGIN.EMS) {
tiles.addClass('filters-off');
} else {
if (this._baseLayerIsDesaturated) {
Expand Down
Loading

0 comments on commit 8a88cbc

Please sign in to comment.