UNPKG

@geogirafe/lib-geoportal

Version:

GeoGirafe is a flexible application to build online geoportals.

73 lines (72 loc) 3.16 kB
// SPDX-License-Identifier: Apache-2.0 import GirafeSingleton from '../../base/GirafeSingleton.js'; import GroupLayer from '../../models/layers/grouplayer.js'; import Layer from '../../models/layers/layer.js'; import ThemeLayer from '../../models/layers/themelayer.js'; import CustomTheme from '../../models/customtheme.js'; import CustomLayersSerializer from '../share/serializers/customlayersserializer.js'; class CustomThemesManager extends GirafeSingleton { customThemes = []; storagePath = 'customThemes'; serializer = new CustomLayersSerializer(this.context); addTheme(themeName, layersList) { const theme = new CustomTheme(themeName); for (const layerBase of layersList) { const layer = layerBase.clone(); this.manageActiveStateForClonedObject(layer); theme.layers.push(layer); } this.customThemes.push(theme); this.saveCustomThemes(); } manageActiveStateForClonedObject(layer) { /** Manage the current active state and default active state * 1. We set isDefaultChecked to the active state (because when the layer will be loaded, we want to activate it automatically) * 2. We deactivate the layer, because it was just cloned and is not active yet. * We only do this on layers, not on groups **/ if (layer instanceof Layer) { layer.isDefaultChecked = layer.active; layer.activeState = 'off'; } else if (layer instanceof GroupLayer || layer instanceof ThemeLayer) { for (const child of layer.children) { this.manageActiveStateForClonedObject(child); } } } deleteTheme(theme) { const index = this.customThemes.findIndex((item) => item === theme); if (index >= 0) { this.customThemes.splice(index, 1); this.saveCustomThemes(); } else { throw new Error('The custom theme to be removed cannot be found in the list of custom themes'); } } saveCustomThemes() { const serializedObject = {}; for (const customTheme of this.customThemes) { serializedObject[customTheme.name] = this.serializer.customThemeSerialize(customTheme); } this.context.userDataManager.saveUserData(this.storagePath, serializedObject); } loadCustomThemes() { const customThemes = this.context.userDataManager.getUserData(this.storagePath); if (customThemes) { for (const customThemeName of Object.keys(customThemes)) { try { const customTheme = this.serializer.customThemeDeserialize(customThemeName, customThemes[customThemeName]); this.customThemes.push(customTheme); } catch (error) { console.warn('Cannot deserialize custom themes from local storage'); console.warn(error); // Do not throw the error, the themes selector can still be used } } } } } export default CustomThemesManager;