Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Maps] lazy load maps_legacy, tile_map, and region_map bundle #78027

Merged
merged 11 commits into from
Sep 24, 2020
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';
40 changes: 19 additions & 21 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,11 @@ 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._leaflet = modules.L;
this._kibanaMap = new modules.KibanaMap(this._container, options);
this._serviceSettings = await getServiceSettings();
this._kibanaMap.setMinZoom(WMS_MINZOOM); //use a default
this._kibanaMap.setMaxZoom(WMS_MAXZOOM); //use a default

Expand Down Expand Up @@ -131,14 +130,14 @@ export function BaseMapsVisualizationProvider(getKibanaMap, mapServiceSettings)
async _updateBaseLayer() {
const emsTileLayerId = getEmsTileLayerId();

if (!this._kibanaMap) {
if (!this._kibanaMap || !this._serviceSettings) {
return;
}

const mapParams = this._getMapsParams();
if (!this._tmsConfigured()) {
try {
const tmsServices = await serviceSettings.getTMSServices();
const tmsServices = await this._serviceSettings.getTMSServices();
const userConfiguredTmsLayer = tmsServices[0];
const initBasemapLayer = userConfiguredTmsLayer
? userConfiguredTmsLayer
Expand All @@ -147,7 +146,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 +173,7 @@ export function BaseMapsVisualizationProvider(getKibanaMap, mapServiceSettings)
this._setTmsLayer(selectedTmsLayer);
}
} catch (tmsLoadingError) {
toastService.addWarning(tmsLoadingError.message);
getToasts().addWarning(tmsLoadingError.message);
}
}

Expand All @@ -189,13 +188,13 @@ export function BaseMapsVisualizationProvider(getKibanaMap, mapServiceSettings)
isDesaturated = true;
}
const isDarkMode = getUiSettings().get('theme:darkMode');
const meta = await serviceSettings.getAttributesForTMSLayer(
const meta = await this._serviceSettings.getAttributesForTMSLayer(
tmsLayer,
isDesaturated,
isDarkMode
);
const showZoomMessage = serviceSettings.shouldShowZoomMessage(tmsLayer);
const options = _.cloneDeep(tmsLayer);
const showZoomMessage = this._serviceSettings.shouldShowZoomMessage(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