@iobroker/adapter-react-v5 3.1.4 → 3.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/GenericApp.js ADDED
@@ -0,0 +1,1025 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ var _typeof3 = require("@babel/runtime/helpers/typeof");
6
+
7
+ Object.defineProperty(exports, "__esModule", {
8
+ value: true
9
+ });
10
+ exports["default"] = void 0;
11
+
12
+ var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
13
+
14
+ var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
15
+
16
+ var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
17
+
18
+ var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));
19
+
20
+ var _get2 = _interopRequireDefault(require("@babel/runtime/helpers/get"));
21
+
22
+ var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
23
+
24
+ var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
25
+
26
+ var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
27
+
28
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
29
+
30
+ var _react = _interopRequireDefault(require("react"));
31
+
32
+ var _Connection = _interopRequireWildcard(require("./Connection"));
33
+
34
+ var _propTypes = _interopRequireDefault(require("prop-types"));
35
+
36
+ var Sentry = _interopRequireWildcard(require("@sentry/browser"));
37
+
38
+ var SentryIntegrations = _interopRequireWildcard(require("@sentry/integrations"));
39
+
40
+ var _Error = _interopRequireDefault(require("./Dialogs/Error"));
41
+
42
+ var _Snackbar = _interopRequireDefault(require("@mui/material/Snackbar"));
43
+
44
+ var _IconButton = _interopRequireDefault(require("@mui/material/IconButton"));
45
+
46
+ var _Close = _interopRequireDefault(require("@mui/icons-material/Close"));
47
+
48
+ var _Prompt = _interopRequireDefault(require("./Prompt"));
49
+
50
+ var _Theme = _interopRequireDefault(require("./Theme"));
51
+
52
+ var _Loader = _interopRequireDefault(require("./Components/Loader"));
53
+
54
+ var _Router2 = _interopRequireDefault(require("./Components/Router"));
55
+
56
+ var _Utils = _interopRequireDefault(require("./Components/Utils"));
57
+
58
+ var _SaveCloseButtons = _interopRequireDefault(require("./Components/SaveCloseButtons"));
59
+
60
+ var _i18n = _interopRequireDefault(require("./i18n"));
61
+
62
+ function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
63
+
64
+ function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof3(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
65
+
66
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
67
+
68
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
69
+
70
+ function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; }
71
+
72
+ function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
73
+
74
+ // import './index.css';
75
+ var cssStyle = "\nhtml {\n height: 100%;\n}\n\nbody {\n margin: 0;\n padding: 0;\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", \"Roboto\", \"Oxygen\", \"Ubuntu\", \"Cantarell\", \"Fira Sans\", \"Droid Sans\", \"Helvetica Neue\", sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n width: 100%;\n height: 100%;\n overflow: hidden;\n}\n\n/* scrollbar */\n::-webkit-scrollbar-track {\n background-color: #ccc;\n border-radius: 5px;\n}\n\n::-webkit-scrollbar {\n width: 5px;\n height: 5px;\n background-color: #ccc;\n}\n\n::-webkit-scrollbar-thumb {\n background-color: #575757;\n border-radius: 5px;\n}\n\n#root {\n height: 100%;\n}\n\n.App {\n height: 100%;\n}\n\n@keyframes glow {\n from {\n background-color: initial;\n }\n to {\n background-color: #58c458;\n }\n}\n";
76
+
77
+ if (!window.localStorage) {
78
+ window.localStorage = {
79
+ getItem: function getItem() {
80
+ return null;
81
+ },
82
+ setItem: function setItem() {
83
+ return null;
84
+ }
85
+ };
86
+ }
87
+ /**
88
+ * @extends {Router<import('./types').GenericAppProps, import('./types').GenericAppState>}
89
+ */
90
+
91
+
92
+ var GenericApp = /*#__PURE__*/function (_Router) {
93
+ (0, _inherits2["default"])(GenericApp, _Router);
94
+
95
+ var _super = _createSuper(GenericApp);
96
+
97
+ /**
98
+ * @param {import('./types').GenericAppProps} props
99
+ * @param {import('./types').GenericAppSettings | undefined} settings
100
+ */
101
+ function GenericApp(props, settings) {
102
+ var _this;
103
+
104
+ (0, _classCallCheck2["default"])(this, GenericApp);
105
+ var ConnectionClass = props.Connection || settings.Connection || _Connection["default"];
106
+
107
+ if (!window.document.getElementById('generic-app-iobroker-component')) {
108
+ var style = window.document.createElement('style');
109
+ style.setAttribute('id', 'generic-app-iobroker-component');
110
+ style.innerHTML = cssStyle;
111
+ window.document.head.appendChild(style);
112
+ } // Remove `!Connection.isWeb() && window.adapterName !== 'material'` when iobroker.socket will support native ws
113
+
114
+
115
+ if (!ConnectionClass.isWeb() && window.io && window.location.port === '3000') {
116
+ try {
117
+ var io = new window.SocketClient();
118
+ delete window.io;
119
+ window.io = io;
120
+ } catch (e) {// ignore
121
+ }
122
+ }
123
+
124
+ _this = _super.call(this, props);
125
+ (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onSystemConfigChanged", function (id, obj) {
126
+ if (obj && id === 'system.config') {
127
+ var _obj$common;
128
+
129
+ if (_this.socket.systemLang !== (obj === null || obj === void 0 ? void 0 : obj.common.language)) {
130
+ _this.socket.systemLang = (obj === null || obj === void 0 ? void 0 : obj.common.language) || 'en';
131
+
132
+ _i18n["default"].setLanguage(_this.socket.systemLang);
133
+ }
134
+
135
+ if (_this._systemConfig.expertMode !== !!(obj !== null && obj !== void 0 && (_obj$common = obj.common) !== null && _obj$common !== void 0 && _obj$common.expertMode)) {
136
+ _this._systemConfig = (obj === null || obj === void 0 ? void 0 : obj.common) || {};
137
+
138
+ _this.setState({
139
+ expertMode: _this.getExpertMode()
140
+ });
141
+ } else {
142
+ _this._systemConfig = (obj === null || obj === void 0 ? void 0 : obj.common) || {};
143
+ }
144
+ }
145
+ });
146
+ (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onReceiveMessage", function (message) {
147
+ if (message !== null && message !== void 0 && message.data) {
148
+ if (message.data === 'updateTheme') {
149
+ var newThemeName = _Utils["default"].getThemeName();
150
+
151
+ _Utils["default"].setThemeName(_Utils["default"].getThemeName());
152
+
153
+ var _theme = _this.createTheme(newThemeName);
154
+
155
+ _this.setState({
156
+ theme: _theme,
157
+ themeName: _this.getThemeName(_theme),
158
+ themeType: _this.getThemeType(_theme)
159
+ }, function () {
160
+ _this.props.onThemeChange && _this.props.onThemeChange(newThemeName);
161
+ _this.onThemeChanged && _this.onThemeChanged(newThemeName);
162
+ });
163
+ } else if (message.data === 'updateExpertMode') {
164
+ _this.onToggleExpertMode && _this.onToggleExpertMode(_this.getExpertMode());
165
+ } else {
166
+ console.warn('Received unknown message: ' + JSON.stringify(message.data));
167
+ }
168
+ }
169
+ });
170
+ (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onResize", function () {
171
+ _this.resizeTimer && clearTimeout(_this.resizeTimer);
172
+ _this.resizeTimer = setTimeout(function () {
173
+ _this.resizeTimer = null;
174
+
175
+ _this.setState({
176
+ width: GenericApp.getWidth()
177
+ });
178
+ }, 200);
179
+ });
180
+ (0, _Prompt["default"])();
181
+ var query = (window.location.search || '').replace(/^\?/, '').replace(/#.*$/, '');
182
+ var args = {};
183
+ query.trim().split('&').filter(function (t) {
184
+ return t.trim();
185
+ }).forEach(function (b) {
186
+ var parts = b.split('=');
187
+ args[parts[0]] = parts.length === 2 ? parts[1] : true;
188
+
189
+ if (args[parts[0]] === 'true') {
190
+ args[parts[0]] = true;
191
+ } else if (args[parts[0]] === 'false') {
192
+ args[parts[0]] = false;
193
+ }
194
+ }); // extract instance from URL
195
+
196
+ _this.instance = args.instance !== undefined ? parseInt(args.instance, 10) || 0 : parseInt(window.location.search.slice(1), 10) || 0; // extract adapter name from URL
197
+
198
+ var tmp = window.location.pathname.split('/');
199
+ _this.adapterName = (settings === null || settings === void 0 ? void 0 : settings.adapterName) || props.adapterName || window.adapterName || tmp[tmp.length - 2] || 'iot';
200
+ _this.instanceId = "system.adapter.".concat(_this.adapterName, ".").concat(_this.instance);
201
+ _this.newReact = args.newReact === true; // it is admin5
202
+
203
+ var location = _Router2["default"].getLocation();
204
+
205
+ location.tab = location.tab || (window._localStorage || window.localStorage).getItem(_this.adapterName + '-adapter') || '';
206
+
207
+ var themeInstance = _this.createTheme();
208
+
209
+ _this.state = {
210
+ selectedTab: (window._localStorage || window.localStorage).getItem(_this.adapterName + '-adapter') || '',
211
+ selectedTabNum: -1,
212
+ "native": {},
213
+ errorText: '',
214
+ changed: false,
215
+ connected: false,
216
+ loaded: false,
217
+ isConfigurationError: '',
218
+ expertMode: false,
219
+ toast: '',
220
+ theme: themeInstance,
221
+ themeName: _this.getThemeName(themeInstance),
222
+ themeType: _this.getThemeType(themeInstance),
223
+ bottomButtons: (settings && settings.bottomButtons) === false ? false : (props && props.bottomButtons) === false ? false : true,
224
+ width: GenericApp.getWidth()
225
+ }; // init translations
226
+
227
+ var translations = {
228
+ 'en': require('./i18n/en.json'),
229
+ 'de': require('./i18n/de.json'),
230
+ 'ru': require('./i18n/ru.json'),
231
+ 'pt': require('./i18n/pt.json'),
232
+ 'nl': require('./i18n/nl.json'),
233
+ 'fr': require('./i18n/fr.json'),
234
+ 'it': require('./i18n/it.json'),
235
+ 'es': require('./i18n/es.json'),
236
+ 'pl': require('./i18n/pl.json'),
237
+ 'zh-cn': require('./i18n/zh-cn.json')
238
+ }; // merge together
239
+
240
+ if (settings && settings.translations) {
241
+ Object.keys(settings.translations).forEach(function (lang) {
242
+ return translations[lang] = Object.assign(translations[lang], settings.translations[lang]);
243
+ });
244
+ } else if (props.translations) {
245
+ Object.keys(props.translations).forEach(function (lang) {
246
+ return translations[lang] = Object.assign(translations[lang], props.translations[lang]);
247
+ });
248
+ }
249
+
250
+ _i18n["default"].setTranslations(translations);
251
+
252
+ _this.savedNative = {}; // to detect if the config changed
253
+
254
+ _this.encryptedFields = props.encryptedFields || (settings === null || settings === void 0 ? void 0 : settings.encryptedFields) || [];
255
+ _this.sentryDSN = settings && settings.sentryDSN || props.sentryDSN;
256
+ _this.socket = new ConnectionClass(_objectSpread(_objectSpread({}, (props === null || props === void 0 ? void 0 : props.socket) || (settings === null || settings === void 0 ? void 0 : settings.socket)), {}, {
257
+ name: _this.adapterName,
258
+ doNotLoadAllObjects: settings === null || settings === void 0 ? void 0 : settings.doNotLoadAllObjects,
259
+ onProgress: function onProgress(progress) {
260
+ if (progress === _Connection.PROGRESS.CONNECTING) {
261
+ _this.setState({
262
+ connected: false
263
+ });
264
+ } else if (progress === _Connection.PROGRESS.READY) {
265
+ _this.setState({
266
+ connected: true
267
+ });
268
+ } else {
269
+ _this.setState({
270
+ connected: true
271
+ });
272
+ }
273
+ },
274
+ onReady: function onReady(objects, scripts) {
275
+ _i18n["default"].setLanguage(_this.socket.systemLang); // subscribe because of language and expert mode
276
+
277
+
278
+ _this.socket.subscribeObject('system.config', _this.onSystemConfigChanged).then(function () {
279
+ return _this.getSystemConfig();
280
+ }).then(function (obj) {
281
+ _this._secret = typeof obj !== 'undefined' && obj["native"] && obj["native"].secret || 'Zgfr56gFe87jJOM';
282
+ _this._systemConfig = (obj === null || obj === void 0 ? void 0 : obj.common) || {};
283
+ return _this.socket.getObject(_this.instanceId);
284
+ }).then(function (instanceObj) {
285
+ var waitPromise;
286
+ var sentryEnabled = _this._systemConfig.diag !== 'none' && instanceObj && instanceObj.common && instanceObj.common.name && instanceObj.common.version && !instanceObj.common.disableDataReporting && window.location.host !== 'localhost:3000'; // activate sentry plugin
287
+
288
+ if (!_this.sentryStarted && _this.sentryDSN && sentryEnabled) {
289
+ _this.sentryStarted = true;
290
+ Sentry.init({
291
+ dsn: _this.sentryDSN,
292
+ release: "iobroker.".concat(instanceObj.common.name, "@").concat(instanceObj.common.version),
293
+ integrations: [new SentryIntegrations.Dedupe()]
294
+ });
295
+ } // read UUID and init sentry with it.
296
+ // for backward compatibility it will be processed separately from above logic: some adapters could still have this.sentryDSN as undefined
297
+
298
+
299
+ if (!_this.sentryInited && sentryEnabled) {
300
+ _this.sentryInited = true;
301
+ waitPromise = _this.socket.getObject('system.meta.uuid').then(function (uuidObj) {
302
+ if (uuidObj && uuidObj["native"] && uuidObj["native"].uuid) {
303
+ Sentry.configureScope(function (scope) {
304
+ return scope.setUser({
305
+ id: uuidObj["native"].uuid
306
+ });
307
+ });
308
+ }
309
+ });
310
+ }
311
+
312
+ waitPromise = waitPromise || Promise.resolve();
313
+ waitPromise.then(function () {
314
+ if (instanceObj) {
315
+ _this.common = instanceObj === null || instanceObj === void 0 ? void 0 : instanceObj.common;
316
+
317
+ _this.onPrepareLoad(instanceObj["native"], instanceObj.encryptedNative); // decode all secrets
318
+
319
+
320
+ _this.savedNative = JSON.parse(JSON.stringify(instanceObj["native"]));
321
+
322
+ _this.setState({
323
+ "native": instanceObj["native"],
324
+ loaded: true,
325
+ expertMode: _this.getExpertMode()
326
+ }, function () {
327
+ return _this.onConnectionReady && _this.onConnectionReady();
328
+ });
329
+ } else {
330
+ console.warn('Cannot load instance settings');
331
+
332
+ _this.setState({
333
+ "native": {},
334
+ loaded: true,
335
+ expertMode: _this.getExpertMode()
336
+ }, function () {
337
+ return _this.onConnectionReady && _this.onConnectionReady();
338
+ });
339
+ }
340
+ });
341
+ });
342
+ },
343
+ onError: function onError(err) {
344
+ console.error(err);
345
+
346
+ _this.showError(err);
347
+ }
348
+ }));
349
+ return _this;
350
+ }
351
+
352
+ (0, _createClass2["default"])(GenericApp, [{
353
+ key: "componentDidMount",
354
+ value:
355
+ /**
356
+ * Called immediately after a component is mounted. Setting state here will trigger re-rendering.
357
+ */
358
+ function componentDidMount() {
359
+ window.addEventListener('resize', this.onResize, true);
360
+ window.addEventListener('message', this.onReceiveMessage, false);
361
+ (0, _get2["default"])((0, _getPrototypeOf2["default"])(GenericApp.prototype), "componentDidMount", this).call(this);
362
+ }
363
+ /**
364
+ * Called immediately before a component is destroyed.
365
+ */
366
+
367
+ }, {
368
+ key: "componentWillUnmount",
369
+ value: function componentWillUnmount() {
370
+ window.removeEventListener('resize', this.onResize, true);
371
+ window.removeEventListener('message', this.onReceiveMessage, false);
372
+ (0, _get2["default"])((0, _getPrototypeOf2["default"])(GenericApp.prototype), "componentWillUnmount", this).call(this);
373
+ }
374
+ }, {
375
+ key: "createTheme",
376
+ value:
377
+ /**
378
+ * Get a theme
379
+ * @param {string} name Theme name
380
+ * @returns {import('./types').Theme}
381
+ */
382
+ function createTheme() {
383
+ var name = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
384
+ return (0, _Theme["default"])(_Utils["default"].getThemeName(name));
385
+ }
386
+ /**
387
+ * Get the theme name
388
+ * @param {import('./types').Theme} theme Theme
389
+ * @returns {string} Theme name
390
+ */
391
+
392
+ }, {
393
+ key: "getThemeName",
394
+ value: function getThemeName(theme) {
395
+ return theme.name;
396
+ }
397
+ /**
398
+ * Get the theme type
399
+ * @param {import('./types').Theme} theme Theme
400
+ * @returns {string} Theme type
401
+ */
402
+
403
+ }, {
404
+ key: "getThemeType",
405
+ value: function getThemeType(theme) {
406
+ return theme.palette.mode;
407
+ }
408
+ /**
409
+ * Changes the current theme
410
+ */
411
+
412
+ }, {
413
+ key: "toggleTheme",
414
+ value: function toggleTheme() {
415
+ var _this2 = this;
416
+
417
+ var themeName = this.state.themeName; // dark => blue => colored => light => dark
418
+
419
+ var newThemeName = themeName === 'dark' ? 'blue' : themeName === 'blue' ? 'colored' : themeName === 'colored' ? 'light' : 'dark';
420
+
421
+ _Utils["default"].setThemeName(newThemeName);
422
+
423
+ var theme = this.createTheme(newThemeName);
424
+ this.setState({
425
+ theme: theme,
426
+ themeName: this.getThemeName(theme),
427
+ themeType: this.getThemeType(theme)
428
+ }, function () {
429
+ _this2.props.onThemeChange && _this2.props.onThemeChange(newThemeName);
430
+ _this2.onThemeChanged && _this2.onThemeChanged(newThemeName);
431
+ });
432
+ }
433
+ /**
434
+ * Gets the system configuration.
435
+ * @returns {Promise<ioBroker.OtherObject>}
436
+ */
437
+
438
+ }, {
439
+ key: "getSystemConfig",
440
+ value: function getSystemConfig() {
441
+ return this.socket.getSystemConfig();
442
+ }
443
+ /**
444
+ * Get current expert mode
445
+ * @returns {boolean}
446
+ */
447
+
448
+ }, {
449
+ key: "getExpertMode",
450
+ value: function getExpertMode() {
451
+ return window.sessionStorage.getItem('App.expertMode') === 'true' || !!this._systemConfig.expertMode;
452
+ }
453
+ /**
454
+ * Gets called when the socket.io connection is ready.
455
+ * You can overload this function to execute own commands.
456
+ */
457
+
458
+ }, {
459
+ key: "onConnectionReady",
460
+ value: function onConnectionReady() {}
461
+ /**
462
+ * Encrypts a string.
463
+ * @param {string} value
464
+ * @returns {string}
465
+ */
466
+
467
+ }, {
468
+ key: "encrypt",
469
+ value: function encrypt(value) {
470
+ var result = '';
471
+
472
+ for (var i = 0; i < value.length; i++) {
473
+ result += String.fromCharCode(this._secret[i % this._secret.length].charCodeAt(0) ^ value.charCodeAt(i));
474
+ }
475
+
476
+ return result;
477
+ }
478
+ /**
479
+ * Decrypts a string.
480
+ * @param {string} value
481
+ * @returns {string}
482
+ */
483
+
484
+ }, {
485
+ key: "decrypt",
486
+ value: function decrypt(value) {
487
+ var result = '';
488
+
489
+ for (var i = 0; i < value.length; i++) {
490
+ result += String.fromCharCode(this._secret[i % this._secret.length].charCodeAt(0) ^ value.charCodeAt(i));
491
+ }
492
+
493
+ return result;
494
+ }
495
+ /**
496
+ * Gets called when the navigation hash changes.
497
+ * You may override this if needed.
498
+ */
499
+
500
+ }, {
501
+ key: "onHashChanged",
502
+ value: function onHashChanged() {
503
+ var location = _Router2["default"].getLocation();
504
+
505
+ if (location.tab !== this.state.selectedTab) {
506
+ this.selectTab(location.tab);
507
+ }
508
+ }
509
+ /**
510
+ * Selects the given tab.
511
+ * @param {string} tab
512
+ * @param {number} [index]
513
+ */
514
+
515
+ }, {
516
+ key: "selectTab",
517
+ value: function selectTab(tab, index) {
518
+ (window._localStorage || window.localStorage)[this.adapterName + '-adapter'] = tab;
519
+ this.setState({
520
+ selectedTab: tab,
521
+ selectedTabNum: index
522
+ });
523
+ }
524
+ /**
525
+ * Gets called before the settings are saved.
526
+ * You may override this if needed.
527
+ * @param {Record<string, any>} settings
528
+ */
529
+
530
+ }, {
531
+ key: "onPrepareSave",
532
+ value: function onPrepareSave(settings) {
533
+ var _this3 = this;
534
+
535
+ // here you can encode values
536
+ this.encryptedFields && this.encryptedFields.forEach(function (attr) {
537
+ if (settings[attr]) {
538
+ settings[attr] = _this3.encrypt(settings[attr]);
539
+ }
540
+ });
541
+ return true;
542
+ }
543
+ /**
544
+ * Gets called after the settings are loaded.
545
+ * You may override this if needed.
546
+ * @param {Record<string, any>} settings
547
+ * @param {string[]} encryptedNative optional list of fields to be decrypted
548
+ */
549
+
550
+ }, {
551
+ key: "onPrepareLoad",
552
+ value: function onPrepareLoad(settings, encryptedNative) {
553
+ var _this4 = this;
554
+
555
+ // here you can encode values
556
+ this.encryptedFields && this.encryptedFields.forEach(function (attr) {
557
+ if (settings[attr]) {
558
+ settings[attr] = _this4.decrypt(settings[attr]);
559
+ }
560
+ });
561
+ encryptedNative && encryptedNative.forEach(function (attr) {
562
+ _this4.encryptedFields = _this4.encryptedFields || [];
563
+ !_this4.encryptedFields.includes(attr) && _this4.encryptedFields.push(attr);
564
+
565
+ if (settings[attr]) {
566
+ settings[attr] = _this4.decrypt(settings[attr]);
567
+ }
568
+ });
569
+ }
570
+ /**
571
+ * Gets the extendable instances.
572
+ * @returns {Promise<any[]>}
573
+ */
574
+
575
+ }, {
576
+ key: "getExtendableInstances",
577
+ value: function getExtendableInstances() {
578
+ var _this5 = this;
579
+
580
+ return new Promise(function (resolve) {
581
+ _this5.socket._socket.emit('getObjectView', 'system', 'instance', null, function (err, doc) {
582
+ if (err) {
583
+ resolve([]);
584
+ } else {
585
+ resolve(doc.rows.filter(function (item) {
586
+ return item.value.common.webExtendable;
587
+ }).map(function (item) {
588
+ return item.value;
589
+ }));
590
+ }
591
+ });
592
+ });
593
+ }
594
+ /**
595
+ * Gets the IP addresses of the given host.
596
+ * @param {string} host
597
+ */
598
+
599
+ }, {
600
+ key: "getIpAddresses",
601
+ value: function getIpAddresses(host) {
602
+ var _this6 = this;
603
+
604
+ return new Promise(function (resolve, reject) {
605
+ _this6.socket._socket.emit('getHostByIp', host || _this6.common.host, function (ip, _host) {
606
+ var IPs4 = [{
607
+ name: '[IPv4] 0.0.0.0 - ' + _i18n["default"].t('ra_Listen on all IPs'),
608
+ address: '0.0.0.0',
609
+ family: 'ipv4'
610
+ }];
611
+ var IPs6 = [{
612
+ name: '[IPv6] ::',
613
+ address: '::',
614
+ family: 'ipv6'
615
+ }];
616
+
617
+ if (_host) {
618
+ host = _host;
619
+
620
+ if (host["native"].hardware && host["native"].hardware.networkInterfaces) {
621
+ Object.keys(host["native"].hardware.networkInterfaces).forEach(function (eth) {
622
+ return host["native"].hardware.networkInterfaces[eth].forEach(function (inter) {
623
+ if (inter.family !== 'IPv6') {
624
+ IPs4.push({
625
+ name: '[' + inter.family + '] ' + inter.address + ' - ' + eth,
626
+ address: inter.address,
627
+ family: 'ipv4'
628
+ });
629
+ } else {
630
+ IPs6.push({
631
+ name: '[' + inter.family + '] ' + inter.address + ' - ' + eth,
632
+ address: inter.address,
633
+ family: 'ipv6'
634
+ });
635
+ }
636
+ });
637
+ });
638
+ }
639
+
640
+ IPs6.forEach(function (ip) {
641
+ return IPs4.push(ip);
642
+ });
643
+ }
644
+
645
+ resolve(IPs4);
646
+ });
647
+ });
648
+ }
649
+ /**
650
+ * Saves the settings to the server.
651
+ * @param {boolean} isClose True if the user is closing the dialog.
652
+ */
653
+
654
+ }, {
655
+ key: "onSave",
656
+ value: function onSave(isClose) {
657
+ var _this7 = this;
658
+
659
+ var oldObj;
660
+
661
+ if (this.state.isConfigurationError) {
662
+ this.setState({
663
+ errorText: this.state.isConfigurationError
664
+ });
665
+ return;
666
+ }
667
+
668
+ this.socket.getObject(this.instanceId).then(function (_oldObj) {
669
+ oldObj = _oldObj || {};
670
+
671
+ for (var a in _this7.state["native"]) {
672
+ if (_this7.state["native"].hasOwnProperty(a)) {
673
+ if (_this7.state["native"][a] === null) {
674
+ oldObj["native"][a] = null;
675
+ } else if (_this7.state["native"][a] !== undefined) {
676
+ oldObj["native"][a] = JSON.parse(JSON.stringify(_this7.state["native"][a]));
677
+ } else {
678
+ delete oldObj["native"][a];
679
+ }
680
+ }
681
+ }
682
+
683
+ if (_this7.state.common) {
684
+ for (var b in _this7.state.common) {
685
+ if (_this7.state.common[b] === null) {
686
+ oldObj.common[b] = null;
687
+ } else if (_this7.state.common[b] !== undefined) {
688
+ oldObj.common[b] = JSON.parse(JSON.stringify(_this7.state.common[b]));
689
+ } else {
690
+ delete oldObj.common[b];
691
+ }
692
+ }
693
+ }
694
+
695
+ if (_this7.onPrepareSave(oldObj["native"]) !== false) {
696
+ return _this7.socket.setObject(_this7.instanceId, oldObj);
697
+ } else {
698
+ return Promise.reject('Invalid configuration');
699
+ }
700
+ }).then(function () {
701
+ _this7.savedNative = oldObj["native"];
702
+ globalThis.changed = false;
703
+
704
+ _this7.setState({
705
+ changed: false
706
+ });
707
+
708
+ isClose && GenericApp.onClose();
709
+ })["catch"](function (e) {
710
+ console.error("Cannot save configuration: ".concat(e));
711
+ });
712
+ }
713
+ /**
714
+ * Renders the toast.
715
+ * @returns {JSX.Element | null} The JSX element.
716
+ */
717
+
718
+ }, {
719
+ key: "renderToast",
720
+ value: function renderToast() {
721
+ var _this8 = this;
722
+
723
+ if (!this.state.toast) {
724
+ return null;
725
+ }
726
+
727
+ return /*#__PURE__*/_react["default"].createElement(_Snackbar["default"], {
728
+ anchorOrigin: {
729
+ vertical: 'bottom',
730
+ horizontal: 'left'
731
+ },
732
+ open: true,
733
+ autoHideDuration: 6000,
734
+ onClose: function onClose() {
735
+ return _this8.setState({
736
+ toast: ''
737
+ });
738
+ },
739
+ ContentProps: {
740
+ 'aria-describedby': 'message-id'
741
+ },
742
+ message: /*#__PURE__*/_react["default"].createElement("span", {
743
+ id: "message-id"
744
+ }, this.state.toast),
745
+ action: [/*#__PURE__*/_react["default"].createElement(_IconButton["default"], {
746
+ key: "close",
747
+ "aria-label": "Close",
748
+ color: "inherit",
749
+ className: this.props.classes.close,
750
+ onClick: function onClick() {
751
+ return _this8.setState({
752
+ toast: ''
753
+ });
754
+ },
755
+ size: "large"
756
+ }, /*#__PURE__*/_react["default"].createElement(_Close["default"], null))]
757
+ });
758
+ }
759
+ /**
760
+ * Closes the dialog.
761
+ * @private
762
+ */
763
+
764
+ }, {
765
+ key: "renderError",
766
+ value:
767
+ /**
768
+ * Renders the error dialog.
769
+ * @returns {JSX.Element | null} The JSX element.
770
+ */
771
+ function renderError() {
772
+ var _this9 = this;
773
+
774
+ if (!this.state.errorText) {
775
+ return null;
776
+ } else {
777
+ return /*#__PURE__*/_react["default"].createElement(_Error["default"], {
778
+ text: this.state.errorText,
779
+ onClose: function onClose() {
780
+ return _this9.setState({
781
+ errorText: ''
782
+ });
783
+ }
784
+ });
785
+ }
786
+ }
787
+ /**
788
+ * Checks if the configuration has changed.
789
+ * @param {Record<string, any>} [native] the new state
790
+ */
791
+
792
+ }, {
793
+ key: "getIsChanged",
794
+ value: function getIsChanged(_native) {
795
+ _native = _native || this.state["native"];
796
+ var isChanged = JSON.stringify(_native) !== JSON.stringify(this.savedNative);
797
+
798
+ if (isChanged) {
799
+ globalThis.changed = true;
800
+ } else {
801
+ globalThis.changed = false;
802
+ }
803
+
804
+ return isChanged;
805
+ }
806
+ /**
807
+ * Gets called when loading the configuration.
808
+ * @param {Record<string, any>} newNative The new configuration object.
809
+ */
810
+
811
+ }, {
812
+ key: "onLoadConfig",
813
+ value: function onLoadConfig(newNative) {
814
+ if (JSON.stringify(newNative) !== JSON.stringify(this.state["native"])) {
815
+ this.setState({
816
+ "native": newNative,
817
+ changed: this.getIsChanged(newNative)
818
+ });
819
+ }
820
+ }
821
+ /**
822
+ * Sets the configuration error.
823
+ * @param {string} errorText
824
+ */
825
+
826
+ }, {
827
+ key: "setConfigurationError",
828
+ value: function setConfigurationError(errorText) {
829
+ if (this.state.isConfigurationError !== errorText) {
830
+ this.setState({
831
+ isConfigurationError: errorText
832
+ });
833
+ }
834
+ }
835
+ /**
836
+ * Renders the save and close buttons.
837
+ * @returns {JSX.Element | undefined} The JSX element.
838
+ */
839
+
840
+ }, {
841
+ key: "renderSaveCloseButtons",
842
+ value: function renderSaveCloseButtons() {
843
+ var _this10 = this;
844
+
845
+ if (this.state.bottomButtons) {
846
+ return /*#__PURE__*/_react["default"].createElement(_SaveCloseButtons["default"], {
847
+ theme: this.state.theme,
848
+ newReact: this.newReact,
849
+ noTextOnButtons: this.state.width === 'xs' || this.state.width === 'sm' || this.state.width === 'md',
850
+ changed: this.state.changed,
851
+ onSave: function onSave(isClose) {
852
+ return _this10.onSave(isClose);
853
+ },
854
+ onClose: function onClose() {
855
+ return GenericApp.onClose();
856
+ }
857
+ });
858
+ } else {
859
+ return null;
860
+ }
861
+ }
862
+ /**
863
+ * @private
864
+ * @param {Record<string, any>} obj
865
+ * @param {any} attrs
866
+ * @param {any} value
867
+ * @returns {boolean | undefined}
868
+ */
869
+
870
+ }, {
871
+ key: "_updateNativeValue",
872
+ value: function _updateNativeValue(obj, attrs, value) {
873
+ if ((0, _typeof2["default"])(attrs) !== 'object') {
874
+ attrs = attrs.split('.');
875
+ }
876
+
877
+ var attr = attrs.shift();
878
+
879
+ if (!attrs.length) {
880
+ if (value && (0, _typeof2["default"])(value) === 'object') {
881
+ if (JSON.stringify(obj[attr]) !== JSON.stringify(value)) {
882
+ obj[attr] = value;
883
+ return true;
884
+ }
885
+ } else if (obj[attr] !== value) {
886
+ obj[attr] = value;
887
+ return true;
888
+ } else {
889
+ return false;
890
+ }
891
+ } else {
892
+ obj[attr] = obj[attr] || {};
893
+
894
+ if ((0, _typeof2["default"])(obj[attr]) !== 'object') {
895
+ throw new Error('attribute ' + attr + ' is no object, but ' + (0, _typeof2["default"])(obj[attr]));
896
+ }
897
+
898
+ return this._updateNativeValue(obj[attr], attrs, value);
899
+ }
900
+ }
901
+ /**
902
+ * Update the native value
903
+ * @param {string} attr The attribute name with dots as delimiter.
904
+ * @param {any} value The new value.
905
+ * @param {(() => void)} [cb] Callback which will be called upon completion.
906
+ */
907
+
908
+ }, {
909
+ key: "updateNativeValue",
910
+ value: function updateNativeValue(attr, value, cb) {
911
+ var _native2 = JSON.parse(JSON.stringify(this.state["native"]));
912
+
913
+ if (this._updateNativeValue(_native2, attr, value)) {
914
+ var changed = this.getIsChanged(_native2);
915
+ this.setState({
916
+ "native": _native2,
917
+ changed: changed
918
+ }, cb);
919
+ }
920
+ }
921
+ /**
922
+ * Set the error text to be shown.
923
+ * @param {string | JSX.Element} text
924
+ */
925
+
926
+ }, {
927
+ key: "showError",
928
+ value: function showError(text) {
929
+ this.setState({
930
+ errorText: text
931
+ });
932
+ }
933
+ /**
934
+ * Sets the toast to be shown.
935
+ * @param {string} toast
936
+ */
937
+
938
+ }, {
939
+ key: "showToast",
940
+ value: function showToast(toast) {
941
+ this.setState({
942
+ toast: toast
943
+ });
944
+ }
945
+ /**
946
+ * Renders this component.
947
+ * @returns {JSX.Element} The JSX element.
948
+ */
949
+
950
+ }, {
951
+ key: "render",
952
+ value: function render() {
953
+ if (!this.state.loaded) {
954
+ return /*#__PURE__*/_react["default"].createElement(_Loader["default"], {
955
+ theme: this.state.themeType
956
+ });
957
+ }
958
+
959
+ return /*#__PURE__*/_react["default"].createElement("div", {
960
+ className: "App"
961
+ }, this.renderError(), this.renderToast(), this.renderSaveCloseButtons());
962
+ }
963
+ }], [{
964
+ key: "getWidth",
965
+ value:
966
+ /**
967
+ * Gets the width depending on the window inner width.
968
+ * @returns {import('./types').Width}
969
+ */
970
+ function getWidth() {
971
+ /**
972
+ * innerWidth |xs sm md lg xl
973
+ * |-------|-------|-------|-------|------>
974
+ * width | xs | sm | md | lg | xl
975
+ */
976
+ var SIZES = {
977
+ xs: 0,
978
+ sm: 600,
979
+ md: 960,
980
+ lg: 1280,
981
+ xl: 1920
982
+ };
983
+ var width = window.innerWidth;
984
+ var keys = Object.keys(SIZES).reverse();
985
+ var widthComputed = keys.find(function (key) {
986
+ return width >= SIZES[key];
987
+ });
988
+ return widthComputed || 'xs';
989
+ }
990
+ }, {
991
+ key: "onClose",
992
+ value: function onClose() {
993
+ if (typeof window.parent !== 'undefined' && window.parent) {
994
+ try {
995
+ if (window.parent.$iframeDialog && typeof window.parent.$iframeDialog.close === 'function') {
996
+ window.parent.$iframeDialog.close();
997
+ } else {
998
+ window.parent.postMessage('close', '*');
999
+ }
1000
+ } catch (e) {
1001
+ window.parent.postMessage('close', '*');
1002
+ }
1003
+ }
1004
+ }
1005
+ }]);
1006
+ return GenericApp;
1007
+ }(_Router2["default"]);
1008
+
1009
+ GenericApp.propTypes = {
1010
+ adapterName: _propTypes["default"].string,
1011
+ // (optional) name of adapter
1012
+ onThemeChange: _propTypes["default"].func,
1013
+ // (optional) called by theme change
1014
+ socket: _propTypes["default"].object,
1015
+ // (optional) socket information (host, port)
1016
+ encryptedFields: _propTypes["default"].array,
1017
+ // (optional) list of native attributes, that must be encrypted
1018
+ bottomButtons: _propTypes["default"].bool,
1019
+ // If the bottom buttons (Save/Close) must be shown
1020
+ Connection: _propTypes["default"].object // If the bottom buttons (Save/Close) must be shown
1021
+
1022
+ };
1023
+ var _default = GenericApp;
1024
+ exports["default"] = _default;
1025
+ //# sourceMappingURL=GenericApp.js.map