qwc2-lts
Version:
QGIS Web Client
383 lines (377 loc) • 21 kB
JavaScript
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
/**
* Copyright 2016 GeoSolutions Sas
* Copyright 2016-2024 Sourcepole AG
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { Provider, connect } from 'react-redux';
import axios from 'axios';
import deepmerge from 'deepmerge';
import { register as olProj4Register } from 'ol/proj/proj4';
import Proj4js from 'proj4';
import PropTypes from 'prop-types';
import { addLayer } from '../actions/layers';
import { localConfigLoaded, setStartupParameters, setColorScheme } from '../actions/localConfig';
import { loadLocale } from '../actions/locale';
import { setBottombarHeight, setTopbarHeight } from '../actions/map';
import { setCurrentTask } from '../actions/task';
import { themesLoaded, setCurrentTheme } from '../actions/theme';
import { NotificationType, showNotification } from '../actions/windows';
import ReducerIndex from '../reducers/index';
import { createStore } from '../stores/StandardStore';
import ConfigUtils from '../utils/ConfigUtils';
import CoordinatesUtils from '../utils/CoordinatesUtils';
import LocaleUtils from '../utils/LocaleUtils';
import MapUtils from '../utils/MapUtils';
import MiscUtils from '../utils/MiscUtils';
import { UrlParams, resolvePermaLink } from '../utils/PermaLinkUtils';
import ThemeUtils from '../utils/ThemeUtils';
import PluginsContainer from './PluginsContainer';
import './style/App.css';
import './style/DefaultColorScheme.css';
var CSRF_TOKEN = MiscUtils.getCsrfToken();
if (CSRF_TOKEN) {
axios.interceptors.request.use(function (config) {
if (["POST", "PUT", "PATCH", "DELETE"].includes(config.method.toUpperCase())) {
config.headers["X-CSRF-TOKEN"] = CSRF_TOKEN;
}
return config;
}, function (error) {
return Promise.reject(error);
});
}
var AppInitComponent = /*#__PURE__*/function (_React$Component) {
function AppInitComponent(props) {
var _this;
_classCallCheck(this, AppInitComponent);
_this = _callSuper(this, AppInitComponent, [props]);
_defineProperty(_this, "init", function () {
_this.initialized = true;
// Set color scheme
var storedColorScheme = ConfigUtils.havePlugin("Settings") ? localStorage.getItem('qwc2-color-scheme') : null;
var colorScheme = _this.props.initialParams.style || storedColorScheme || ConfigUtils.getConfigProp("defaultColorScheme");
_this.props.setColorScheme(colorScheme);
// Load themes.json
axios.get("themes.json").then(function (response) {
var themes = response.data.themes || {};
if (_this.props.appConfig.themePreprocessor) {
_this.props.appConfig.themePreprocessor(themes);
}
_this.props.themesLoaded(themes);
// Resolve permalink and restore settings
resolvePermaLink(_this.props.initialParams, function (params, state, success) {
var _theme$config;
if (!success) {
_this.props.showNotification("missingtheme", LocaleUtils.tr("app.missingpermalink"), NotificationType.WARN, true);
}
var theme = ThemeUtils.getThemeById(themes, params.t);
if (!theme || theme.restricted) {
var _this$props$userInfos;
if (ConfigUtils.getConfigProp("dontLoadDefaultTheme")) {
return;
}
if (params.t) {
_this.props.showNotification("missingtheme", LocaleUtils.tr("app.missingtheme", params.t), NotificationType.WARN, true);
params.l = undefined;
}
var defaultTheme = Object.fromEntries((((_this$props$userInfos = _this.props.userInfos) === null || _this$props$userInfos === void 0 ? void 0 : _this$props$userInfos.default_url_params) || "").split("&").map(function (x) {
return x.split("=");
})).t || themes.defaultTheme;
theme = ThemeUtils.getThemeById(themes, defaultTheme);
params.t = defaultTheme;
}
_this.props.setStartupParameters(_objectSpread({}, params));
var layerParams = params.l !== undefined ? params.l.split(",").filter(function (entry) {
return entry;
}) : null;
if (layerParams && ConfigUtils.getConfigProp("urlReverseLayerOrder")) {
layerParams.reverse();
}
var visibleBgLayer = params.bl || params.bl === '' ? params.bl : null;
var initialView = null;
if (theme) {
if (params.c && params.s !== undefined) {
var coords = params.c.split(/[;,]/g).map(function (x) {
return parseFloat(x) || 0;
});
var scales = theme.scales || themes.defaultScales;
var zoom = MapUtils.computeZoom(scales, params.s);
if (coords.length === 2) {
var p = CoordinatesUtils.reproject(coords, params.crs || theme.mapCrs, theme.bbox.crs);
var bounds = theme.bbox.bounds;
// Only accept c if it is within the theme bounds
if (bounds[0] <= p[0] && p[0] <= bounds[2] && bounds[1] <= p[1] && p[1] <= bounds[3]) {
initialView = {
center: coords,
zoom: zoom,
crs: params.crs || theme.mapCrs
};
} else {
initialView = {
center: [0.5 * (bounds[0] + bounds[2]), 0.5 * (bounds[1] + bounds[3])],
zoom: zoom,
crs: theme.bbox.crs
};
}
}
} else if (params.e) {
var _bounds = params.e.split(/[;,]/g).map(function (x) {
return parseFloat(x) || 0;
});
if (CoordinatesUtils.isValidExtent(_bounds)) {
initialView = {
bounds: _bounds,
crs: params.crs || theme.mapCrs
};
}
}
}
// Clear all params
UrlParams.clear();
// Restore theme and layers
if (theme) {
try {
_this.props.setCurrentTheme(theme, themes, false, initialView, layerParams, visibleBgLayer, state.layers, _this.props.appConfig.themeLayerRestorer, _this.props.appConfig.externalLayerRestorer);
} catch (e) {
// eslint-disable-next-line
console.log(e.stack);
}
}
var task = ConfigUtils.getConfigProp("startupTask");
if (task && !((_theme$config = theme.config) !== null && _theme$config !== void 0 && _theme$config.startupTask)) {
var mapClickAction = ConfigUtils.getPluginConfig(task.key).mapClickAction;
_this.props.setCurrentTask(task.key, task.mode, mapClickAction);
}
});
});
});
_this.initialized = false;
// Set initial bottom/topbar height to zero, the components will set the proper height when initialized
props.setTopbarHeight(0);
props.setBottombarHeight(0);
return _this;
}
_inherits(AppInitComponent, _React$Component);
return _createClass(AppInitComponent, [{
key: "componentDidMount",
value: function componentDidMount() {
this.componentDidUpdate();
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
// The map component needs to have finished loading before theme initialization can proceed
if (this.props.mapSize && !this.initialized) {
this.init();
}
}
}, {
key: "render",
value: function render() {
return null;
}
}]);
}(React.Component);
_defineProperty(AppInitComponent, "propTypes", {
addLayer: PropTypes.func,
appConfig: PropTypes.object,
initialParams: PropTypes.object,
mapSize: PropTypes.object,
setBottombarHeight: PropTypes.func,
setColorScheme: PropTypes.func,
setCurrentTask: PropTypes.func,
setCurrentTheme: PropTypes.func,
setStartupParameters: PropTypes.func,
setTopbarHeight: PropTypes.func,
showNotification: PropTypes.func,
themesLoaded: PropTypes.func,
userInfos: PropTypes.object
});
var AppInit = connect(function (state) {
return {
mapSize: state.map.size,
layers: state.layers.flat,
userInfos: state.localConfig.user_infos,
currentTask: state.task.id
};
}, {
themesLoaded: themesLoaded,
setCurrentTask: setCurrentTask,
setColorScheme: setColorScheme,
setCurrentTheme: setCurrentTheme,
setStartupParameters: setStartupParameters,
addLayer: addLayer,
showNotification: showNotification,
setTopbarHeight: setTopbarHeight,
setBottombarHeight: setBottombarHeight
})(AppInitComponent);
var StandardApp = /*#__PURE__*/function (_React$Component2) {
function StandardApp(props) {
var _this2;
_classCallCheck(this, StandardApp);
_this2 = _callSuper(this, StandardApp, [props]);
_defineProperty(_this2, "computeVh", function () {
// https://css-tricks.com/the-trick-to-viewport-units-on-mobile/
document.documentElement.style.setProperty('--vh', window.innerHeight * 0.01 + 'px');
});
_defineProperty(_this2, "setupTouchEvents", function (el) {
el.addEventListener('touchstart', function (ev) {
_this2.touchY = ev.targetTouches[0].clientY;
}, {
passive: false
});
el.addEventListener('touchmove', _this2.preventOverscroll, {
passive: false
});
});
_defineProperty(_this2, "preventOverscroll", function (ev) {
if (ev.touches[0].touchType !== "direct") {
// Don't do anything for stylus inputs
return;
}
var scrollEvent = false;
var element = ev.target;
var direction = ev.targetTouches[0].clientY - _this2.touchY;
_this2.touchY = ev.targetTouches[0].clientY;
while (!scrollEvent && element) {
var scrollable = element.scrollHeight > element.clientHeight;
// Workaround for resizeable-window having scrollHeight > clientHeight even though it has no scrollbar
if (element.classList.contains('resizeable-window')) {
scrollable = false;
}
if (element.type === "range") {
// If it is a range element, treat it as a scroll event
scrollEvent = true;
} else if (scrollable && element.scrollTop + element.clientHeight < element.scrollHeight && direction < 0) {
// User scrolls down and element is not at end of scroll
scrollEvent = true;
} else if (scrollable && element.scrollTop > 0 && direction > 0) {
// User scrolls up and element is not at start of scroll
scrollEvent = true;
} else {
element = element.parentElement;
}
}
if (!scrollEvent) {
ev.preventDefault();
}
});
_defineProperty(_this2, "init", function () {
// Load config.json
var urlParams = UrlParams.getParams();
var configParams = Object.entries(urlParams).reduce(function (res, _ref) {
var _ref2 = _slicedToArray(_ref, 2),
key = _ref2[0],
value = _ref2[1];
if (key.startsWith("config:")) {
res[key.slice(7)] = value;
}
return res;
}, {});
ConfigUtils.loadConfiguration(configParams).then(function (config) {
// Merge common config into mobile/desktop config
var commonConfig = (config.plugins.common || []).reduce(function (res, entry) {
var key = entry.name + (entry.name === "TaskButton" ? "#" + (entry.cfg || {}).task : "");
return _objectSpread(_objectSpread({}, res), {}, _defineProperty({}, key, entry));
}, {});
config.plugins.desktop = Object.values(deepmerge(commonConfig, config.plugins.desktop.reduce(function (res, entry) {
var key = entry.name + (entry.name === "TaskButton" ? "#" + (entry.cfg || {}).task : "");
return _objectSpread(_objectSpread({}, res), {}, _defineProperty({}, key, entry));
}, {})));
config.plugins.mobile = Object.values(deepmerge(commonConfig, config.plugins.mobile.reduce(function (res, entry) {
var key = entry.name + (entry.name === "TaskButton" ? "#" + (entry.cfg || {}).task : "");
return _objectSpread(_objectSpread({}, res), {}, _defineProperty({}, key, entry));
}, {})));
delete config.plugins.common;
StandardApp.store.dispatch(localConfigLoaded(config));
var defaultLocale = _this2.props.appConfig.getDefaultLocale ? _this2.props.appConfig.getDefaultLocale() : "";
// Dispatch user locale
StandardApp.store.dispatch(loadLocale(_this2.props.appConfig.defaultLocaleData, defaultLocale));
// Add projections from config
var _iterator = _createForOfIteratorHelper(config.projections || []),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var proj = _step.value;
if (Proj4js.defs(proj.code) === undefined) {
Proj4js.defs(proj.code, proj.proj);
}
CoordinatesUtils.setCrsLabels(_defineProperty({}, proj.code, proj.label));
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
olProj4Register(Proj4js);
});
});
var initialState = _this2.props.appConfig.initialState || {};
StandardApp.store = createStore(ReducerIndex.reducers, initialState, _this2.props.appConfig.actionLogger);
_this2.init();
// Save initial params before they get overwritten
_this2.initialParams = UrlParams.getParams();
_this2.touchY = null;
return _this2;
}
_inherits(StandardApp, _React$Component2);
return _createClass(StandardApp, [{
key: "componentDidMount",
value: function componentDidMount() {
window.addEventListener('resize', this.computeVh);
this.computeVh();
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
window.removeEventListener('resize', this.computeVh);
}
}, {
key: "render",
value: function render() {
var plugins = this.props.appConfig.pluginsDef.plugins;
return /*#__PURE__*/React.createElement(Provider, {
store: StandardApp.store
}, /*#__PURE__*/React.createElement("div", {
ref: this.setupTouchEvents
}, /*#__PURE__*/React.createElement(AppInit, {
appConfig: this.props.appConfig,
initialParams: this.initialParams
}), /*#__PURE__*/React.createElement(PluginsContainer, {
plugins: plugins,
pluginsAppConfig: this.props.appConfig.pluginsDef.cfg || {}
})));
}
}]);
}(React.Component);
_defineProperty(StandardApp, "store", null);
_defineProperty(StandardApp, "propTypes", {
appConfig: PropTypes.object
});
export { StandardApp as default };