@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
390 lines (382 loc) • 21.9 kB
JavaScript
import { htmlFor as uHtmlFor } from 'uhtml/keyed';
import { html as uHtml } from 'uhtml';
import GirafeHTMLElement from '../../base/GirafeHTMLElement';
import UserDataManager from '../../tools/userdata/userdatamanager';
import { PreferenceGroups, UserPreference } from './userPreference';
import CustomThemesManager from '../../tools/themes/customthemesmanager';
import { getPropertyByPath, setPropertyByPath } from '../../tools/utils/pathUtils';
import GirafeColorPicker from '../../tools/utils/girafecolorpicker';
import { systemIsInDarkMode } from '../../tools/utils/utils';
/**
Lets the user override default configuration values and saves them as user data.
*/
export default class UserPreferencesComponent extends GirafeHTMLElement {
constructor() {
super('user-preferences');
Object.defineProperty(this, "template", {
enumerable: true,
configurable: true,
writable: true,
value: () => {
return uHtml `<style>
*{font-family:Arial,sans-serif}.hidden{display:none}.gg-rotate90{transform:rotate(90deg)}.gg-rotate180{transform:rotate(180deg)}.gg-rotate270{transform:rotate(270deg)}img{filter:var(--svg-filter)}img.legend-image{filter:var(--svg-map-filter);background:var(--svg-legend-bkg)}div{scrollbar-width:thin}a,a:visited{color:var(--link-color)}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}@keyframes spin-wait{0%{transform:rotate(0)}7%{transform:rotate(360deg)}to{transform:rotate(360deg)}}.gg-spin{animation-name:spin;animation-duration:2s;animation-timing-function:linear;animation-iteration-count:infinite}.gg-spin-wait{animation-name:spin-wait;animation-duration:10s;animation-timing-function:linear;animation-iteration-count:infinite}::-webkit-scrollbar{width:5px}::-webkit-scrollbar-thumb{background:#999}.gg-button,.gg-select,.gg-input,.gg-textarea{background-color:var(--bkg-color);color:var(--text-color);border:var(--app-standard-border);box-sizing:border-box;cursor:pointer;border-radius:3px;outline:0;margin:0;padding:0 0 0 .5rem;display:inline-block}.gg-label{background-color:var(--bkg-color);color:var(--text-color);border:none;align-items:center;margin:0;padding:0;display:flex}.gg-button,.gg-select,.gg-input,.gg-label{min-height:calc(var(--app-standard-height)/1.5)}.gg-textarea{max-height:initial;resize:vertical;height:6rem;padding:.5rem;line-height:1.3rem}.gg-input{cursor:text}.gg-checkbox{accent-color:var(--text-color);width:1.2rem}.gg-range{accent-color:var(--text-color)}.gg-button{padding:0 .5rem}.gg-button.active{border:solid 1px var(--text-color-grad2);background-color:var(--text-color-grad2);color:var(--bkg-color)}.gg-button:disabled{color:gray;cursor:not-allowed;background-color:#d3d3d3;border:none}.gg-input:disabled,.gg-select:disabled,.gg-textarea:disabled{color:gray;cursor:not-allowed;background-color:#d3d3d3}.gg-button>img{vertical-align:middle}.gg-icon-button{color:var(--text-color);cursor:pointer;background-color:#0000;border:none;flex-direction:column;justify-content:center;align-items:center;padding:0;display:flex}.gg-big,.gg-big-withtext{min-width:var(--app-standard-height);min-height:var(--app-standard-height);max-height:var(--app-standard-height)}.gg-big img,.gg-big-withtext img{width:calc(var(--app-standard-height) - 1.5rem);margin:0}.gg-big-withtext span{font-variant:small-caps;padding:0 1rem;font-size:.9rem}.gg-medium,.gg-medium-withtext{min-width:calc(var(--app-standard-height)/1.2);min-height:calc(var(--app-standard-height)/1.2);max-height:calc(var(--app-standard-height)/1.2);flex-direction:row}.gg-medium img{width:calc(var(--app-standard-height)/2.4);margin:0}.gg-medium-withtext img{width:calc(var(--app-standard-height)/2.4);margin-left:.5rem}.gg-medium-withtext span{padding:0 1rem 0 .5rem;font-size:.9rem}.gg-small,.gg-small-withtext{min-width:calc(var(--app-standard-height)/2);min-height:calc(var(--app-standard-height)/2);max-height:calc(var(--app-standard-height)/2);flex-direction:row}.gg-small img{width:calc(var(--app-standard-height)/3);margin:0}.gg-small-withtext img{width:calc(var(--app-standard-height)/3);margin-left:.5rem}.gg-small-withtext span{padding:0 .5rem 0 .3rem;font-size:.9rem}.gg-button:hover,.gg-select:hover,.gg-input:hover,.gg-textarea:hover,.gg-icon-button:hover{background-color:var(--bkg-color-grad1)}.gg-opacity{opacity:.5}.gg-opacity:hover{opacity:1;background-color:#0000}.gg-tabs{cursor:pointer;border-bottom:1px solid gray;justify-content:left;align-items:end;gap:1rem;height:2rem;margin:.5rem auto 1rem;display:flex}.gg-tab{cursor:pointer;color:var(--text-color);background:0 0;border:none;padding:.5rem}.gg-tab.active{border-bottom:solid 2px var(--text-color-grad2);font-weight:600}.girafe-button-big,.girafe-button-large,.girafe-button-small,.girafe-button-tiny{color:var(--text-color);background-color:#0000;border:none;flex-direction:column;display:flex}.girafe-button-big:hover,.girafe-button-large:hover,.girafe-button-small:hover,.girafe-button-tiny:hover{background-color:var(--bkg-color-grad1);cursor:pointer}.girafe-button-big.dark,.girafe-button-large.dark,.girafe-button-small.dark,.girafe-button-tiny.dark{background-color:var(--bkg-color);filter:invert()}.girafe-button-big{width:var(--app-standard-height);height:var(--app-standard-height);align-items:center;padding:1rem}.girafe-button-big img{overflow:hidden}.girafe-button-large{flex-direction:row}.girafe-button-large img{height:2rem;margin:.3rem}.girafe-button-large span{height:2rem;margin:.3rem;line-height:2rem}.girafe-button-small{min-width:calc(var(--app-standard-height)/2);height:calc(var(--app-standard-height)/2);align-items:center;padding:.5rem}.girafe-button-small img{overflow:hidden}.girafe-button-small span{text-align:left;text-overflow:ellipsis;width:100%;overflow:hidden}.girafe-button-tiny{align-items:center;width:1rem;height:1rem;padding:0}.girafe-button-tiny img{overflow:hidden}
</style><style>
#content{background:var(--bkg-color);color:var(--text-color);margin:0;padding:1rem}.preference-group{padding-bottom:1rem}.preference-group-title{padding-bottom:10px;font-weight:700}.preference-row{flex-direction:column;padding-bottom:8px;display:flex}.with-checkbox,.with-colorpicker{flex-direction:row;justify-content:space-between;align-items:center;height:2rem}.colorpicker{border:solid 1px var(--text-color);cursor:pointer;border-radius:3px;width:1.5rem;height:1.5rem}#reset-all{justify-self:end}#footer{margin-top:2rem}
</style>
<link rel="stylesheet" href="lib/vanilla-picker/vanilla-picker.csp.css" />
<link rel="stylesheet" href="styles/girafecolorpicker.css" />
<div id="panel">
<div id="content">
${this.preferenceGroups.map(group => uHtml `
<div class="preference-group">
<div class="preference-group-title" i18n="${group}">${group}</div>
${this.getPreferencesByGroup(group).map(([preference, key]) => uHtmlFor(preference, key) ` ${preference.uiElement
=== 'select' ? uHtml `
<div class="preference-row" hidden="${!preference.visible}">
<label for="${key}" class="gg-label" i18n="${key}">${key}</label>
<select
id="${key}"
class="gg-select"
onchange="${(evt) => this.onSelectOption(key, evt)}"
onmousedown="${() => this.onOpenSelectOption(key)}">
${preference.options.map(option => uHtml `
<option
i18n="${option.label}"
?selected="${preference.currentValue === option.value}"
value="${option.label}">
${option.label}
</option>
`)}
</select>
</div>
` : uHtml ``} ${preference.uiElement === 'checkbox' ? uHtml `
<div class="preference-row with-checkbox" hidden="${!preference.visible}">
<label for="${key}" i18n="${key}">${key}</label>
<input
id="${key}"
type="checkbox"
class="gg-checkbox"
?checked="${preference.currentValue}"
onchange="${() => this.changePreference(key, !preference.currentValue)}" />
</div>
` : uHtml ``} ${preference.uiElement === 'color' ? uHtml `
<div class="preference-row with-colorpicker" hidden="${!preference.visible}">
<label for="${key}" i18n="${key}">${key}</label>
<button class="colorpicker" id="${key}"></button>
</div>
` : uHtml ``} `)}
</div>
`)}
<div id="footer">
<button
id="reset-all"
class="gg-button"
tip="Reset all preferences back to the default value"
i18n="Reset All"
onclick="${() => this.onResetAll()}">
Reset All
</button>
</div>
</div>
</div>
`;
}
});
Object.defineProperty(this, "visible", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
Object.defineProperty(this, "ready", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
Object.defineProperty(this, "preferences", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "preferenceGroups", {
enumerable: true,
configurable: true,
writable: true,
value: PreferenceGroups
});
Object.defineProperty(this, "colorPickers", {
enumerable: true,
configurable: true,
writable: true,
value: {}
});
Object.defineProperty(this, "userDataManager", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "storagePath", {
enumerable: true,
configurable: true,
writable: true,
value: 'configOverrides'
});
this.userDataManager = UserDataManager.getInstance();
// Define all settings that the user can change
this.preferences = {
language: new UserPreference('languages.defaultLanguage', 'language', 'system', 'select'),
logLevel: new UserPreference('general.logLevel', null, 'system', 'select'),
theme: new UserPreference('themes.defaultTheme', 'theme', 'map', 'select', (themeName) => {
const themeId = Object.keys(this.state.themes._allThemes).find((themeKey) => this.state.themes._allThemes[Number(themeKey)].name === themeName);
return this.state.themes._allThemes[Number(themeId)];
}),
basemap: new UserPreference('basemaps.defaultBasemap', 'activeBasemap', 'map', 'select', (bsName) => {
const bsId = Object.keys(this.state.basemaps).find((bsKey) => this.state.basemaps[Number(bsKey)].name === bsName);
return this.state.basemaps[Number(bsId)];
}),
projection: new UserPreference('map.srid', 'projection', 'map', 'select'),
darkFrontendMode: new UserPreference('interface.darkFrontendMode', 'interface.darkFrontendMode', 'visual', 'select'),
darkMapMode: new UserPreference('interface.darkMapMode', 'interface.darkMapMode', 'visual', 'checkbox'),
selectionComponent: new UserPreference('interface.defaultSelectionComponent', 'interface.selectionComponent', 'visual', 'select'),
selectFillColor: new UserPreference('selection.defaultFillColor', null, 'visual', 'color'),
selectStrokeColor: new UserPreference('selection.defaultStrokeColor', null, 'visual', 'color'),
selectHighlightFillColor: new UserPreference('selection.highlightFillColor', null, 'visual', 'color'),
selectHighlightStrokeColor: new UserPreference('selection.highlightStrokeColor', null, 'visual', 'color'),
searchFillColor: new UserPreference('search.defaultFillColor', null, 'visual', 'color'),
searchStrokeColor: new UserPreference('search.defaultStrokeColor', null, 'visual', 'color'),
drawingFillColor: new UserPreference('drawing.defaultFillColor', null, 'visual', 'color'),
drawingStrokeColor: new UserPreference('drawing.defaultStrokeColor', null, 'visual', 'color')
};
this.subscribe('themes.isLoaded', (_, isLoaded) => {
if (isLoaded) {
this.initPreferenceOptions();
this.initCurrentPreferenceValues();
this.initDarkModeDefaults();
this.initColorPicker();
this.ready = true;
this.render();
}
});
}
connectedCallback() {
this.loadConfig().then(() => {
this.render();
this.subscribe('interface.userPreferencesPanelVisible', (_, newValue) => this.togglePanel(newValue));
this.subscribe('interface.darkFrontendMode', (_, newValue) => this.onChangeDarkFrontendMode(newValue));
this.subscribe('interface.darkMapMode', (_, newValue) => this.onChangeDarkMapMode(newValue));
});
}
render() {
if (this.visible) {
this.renderComponent();
}
else {
this.hide();
}
}
renderComponent() {
if (!this.ready) {
return;
}
super.render();
super.girafeTranslate();
}
togglePanel(visible) {
this.visible = visible;
this.render();
}
onChangeDarkMapMode(newValue) {
const currentTheme = newValue ? 'dark' : 'light';
this.activateTheme(currentTheme, 'map');
}
onChangeDarkFrontendMode(newValue) {
const themeIsDark = newValue ?? systemIsInDarkMode();
const currentTheme = themeIsDark ? 'dark' : 'light';
this.activateTheme(currentTheme, 'theme');
}
activateTheme(mode, className) {
const otherMode = mode === 'dark' ? 'light' : 'dark';
document.body.classList.remove(`${otherMode}-${className}`);
document.body.classList.add(`${mode}-${className}`);
}
/**
For preferences that have options to choose from, readout all possible select options to show in the dropdowns
*/
initPreferenceOptions() {
this.preferences.language.options = Object.keys(this.configManager.Config.languages.translations).map((key) => {
return { label: key, value: key };
});
this.preferences.logLevel.options = [
{ label: 'debug', value: 'debug' },
{ label: 'info', value: 'info' },
{ label: 'warn', value: 'warn' },
{ label: 'error', value: 'error' }
];
this.preferences.projection.options = Object.keys(this.configManager.Config.projections).map((key) => {
return { label: this.configManager.Config.projections[key], value: key };
});
this.refreshThemeOptions();
this.preferences.basemap.options = Object.keys(this.state.basemaps).map((key) => {
const baseMapName = this.state.basemaps[Number(key)].name;
return { label: baseMapName, value: baseMapName };
});
this.preferences.selectionComponent.options = [
{ label: 'window', value: 'window' },
{ label: 'grid', value: 'grid' }
];
this.preferences.darkFrontendMode.options = [
{ label: 'same as system', value: undefined },
{ label: 'dark', value: true },
{ label: 'light', value: false }
];
}
/**
* Collect all possible options for the default theme preference. This has to be repeatable, since the user
* can create new custom themes at any time.
*/
refreshThemeOptions() {
let defaultThemes = [{ label: '-', value: '' }];
Object.keys(this.state.themes._allThemes).forEach((key) => {
const themeName = this.state.themes._allThemes[Number(key)].name;
defaultThemes.push({ label: themeName, value: themeName });
});
defaultThemes = defaultThemes.sort((a, b) => a.label.toUpperCase().localeCompare(b.label.toUpperCase()));
const customThemes = CustomThemesManager.getInstance().customThemes.map((ct) => {
return { label: ct.name, value: ct.name };
});
this.preferences.theme.options = [...defaultThemes, ...customThemes];
}
/**
Readout the default value from the config to show in the component
*/
initCurrentPreferenceValues() {
for (const key in this.preferences) {
const { found, parentObject, lastKey } = getPropertyByPath(this.configManager.Config, this.preferences[key].configPath);
this.preferences[key].currentValue = found && parentObject && lastKey ? parentObject[lastKey] : undefined;
}
}
/**
* Initializes dark mode-related preferences with fallback logic
*/
initDarkModeDefaults() {
const config = this.configManager.Config.interface.darkFrontendMode;
this.state.interface.darkFrontendMode = config ?? systemIsInDarkMode();
this.state.interface.darkMapMode = this.configManager.Config.interface.darkMapMode;
}
/**
* Create color picker object and set the initial color value
*/
initColorPicker() {
super.render();
for (const preferenceKey in this.preferences) {
if (this.preferences[preferenceKey].uiElement === 'color') {
const parent = this.shadowRoot?.getElementById(preferenceKey);
if (parent) {
const colorPicker = new GirafeColorPicker({
parent: parent,
color: this.preferences[preferenceKey].currentValue,
popup: 'top'
}, true);
colorPicker.onChange = (color) => (parent.style.backgroundColor = color.hex);
colorPicker.onClose = (color) => this.changePreference(preferenceKey, color.hex);
colorPicker.setColor(this.preferences[preferenceKey].currentValue, false);
this.colorPickers[preferenceKey] = colorPicker;
}
}
}
}
/**
* If necessary, change/update options of select elements right before they're shown.
*/
onOpenSelectOption(preferenceKey) {
if (preferenceKey === 'theme') {
this.refreshThemeOptions();
this.refreshRender();
}
}
/**
Called when user changes a preference in the panel
*/
onSelectOption(preferenceKey, evt) {
const optionLabel = evt.target?.value;
const selectedOption = this.preferences[preferenceKey].options.find((o) => o.label === optionLabel);
if (selectedOption) {
this.changePreference(preferenceKey, selectedOption.value);
}
}
/**
Update state and local storage with new value
*/
changePreference(preferenceKey, newValue) {
if (this.preferences[preferenceKey]) {
this.preferences[preferenceKey].currentValue = newValue;
this.updatePreferenceInConfig(preferenceKey);
this.updatePreferenceInState(preferenceKey);
this.updatePreferenceInStorage(preferenceKey);
this.refreshRender();
}
}
/**
Update the config object with the new value
*/
updatePreferenceInConfig(preferenceKey) {
const preference = this.preferences[preferenceKey];
setPropertyByPath(this.configManager.Config, preference.configPath, preference.currentValue);
}
/**
Update the state with the new value
*/
updatePreferenceInState(preferenceKey) {
const preference = this.preferences[preferenceKey];
if (preference.statePath) {
setPropertyByPath(this.state, preference.statePath, preference.getCurrentValueForState());
}
}
/**
Save the user preference as a config override in user data storage
*/
updatePreferenceInStorage(preferenceKey) {
const preference = this.preferences[preferenceKey];
// Values are saved under 'configOverrides' in the same structure as in the config
this.userDataManager.saveUserData(`${this.storagePath}.${preference.configPath}`, preference.currentValue);
}
/**
Delete user preference in the local browser storage
*/
deletePreferenceInStorage(preferenceKey) {
this.userDataManager.deleteUserData(`${this.storagePath}.${this.preferences[preferenceKey].configPath}`);
}
/**
* Reset user preferences back to defaults. This will delete the configOverrides object in storage and set the
* current state back to the defaults from config.json
*/
async onResetAll() {
const confirm = await window.gConfirm('Reset user preferences back to default values?', 'Reset preferences');
if (confirm) {
this.resetAll();
}
}
resetAll() {
for (const preferenceKey in this.preferences) {
this.deletePreferenceInStorage(preferenceKey);
this.preferences[preferenceKey].currentValue = this.configManager.getDefaultConfigValue(this.preferences[preferenceKey].configPath);
this.updatePreferenceInState(preferenceKey);
this.updatePreferenceInConfig(preferenceKey);
this.colorPickers[preferenceKey]?.setColor(this.preferences[preferenceKey].currentValue, false);
}
this.render();
}
/**
* @returns all preferences of a group for easy usage in the template.
*/
getPreferencesByGroup(group) {
return Object.keys(this.preferences)
.map((key) => {
return [this.preferences[key], key];
})
.filter((p) => p[0].group === group);
}
}