iobroker.smartcontrol 2.1.0 → 2.2.1

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.
Files changed (115) hide show
  1. package/README.md +21 -10
  2. package/admin/custom/assets/Components-CevOCMYi.js +77 -0
  3. package/admin/custom/assets/Components-DIpDvtxi.js +1 -0
  4. package/admin/custom/assets/_virtual_mf-localSharedImportMap___mfe_internal__SmartcontrolSet__mf_owner__1-C9SdP7_s.js +1 -0
  5. package/admin/custom/assets/_virtual_mf___mfe_internal__SmartcontrolSet__mf_owner__108197177487852__loadShare___mf_0_iobroker_mf_1_gui_mf_2_components__loadShare__.js-Ca-6Y14s.js +1525 -0
  6. package/admin/custom/assets/_virtual_mf___mfe_internal__SmartcontrolSet__mf_owner__108197177487852__loadShare__shared-4MdeZwge.js +2 -0
  7. package/admin/custom/assets/_virtual_mf___mfe_internal__SmartcontrolSet__mf_owner__108197177487852__prebuild___mf_0_iobroker_mf_1_json_mf_2_config__prebuild__-QT6he7QZ.js +122 -0
  8. package/admin/custom/assets/_virtual_mf___mfe_internal__SmartcontrolSet__mf_owner__108197177487852__prebuild__react_mf_1_jsx_mf_2_runtime__prebuild__-BWTOCVCn.js +1 -0
  9. package/admin/custom/assets/dist-Cnxr-ruU.js +1 -0
  10. package/admin/custom/assets/helpers-CNHzo155.js +1 -0
  11. package/admin/custom/assets/hostInit-BVoHSU7s.js +1 -0
  12. package/admin/custom/assets/iconLibraryData-B5fiyl1C.js +1 -0
  13. package/admin/custom/assets/index-DKuAVH1b.js +1 -0
  14. package/admin/custom/assets/lib-CgOpGT17.js +3 -0
  15. package/admin/custom/assets/mf-entry-bootstrap-0-c2b3685a.js +54 -0
  16. package/admin/custom/assets/pendingShares-CEz9fejL.js +2 -0
  17. package/admin/custom/assets/prod-XWAlCKxB.js +492 -0
  18. package/admin/custom/assets/rolldown-runtime-9C0vUP4u.js +1 -0
  19. package/admin/custom/assets/utils-DmVoYT7i.js +4 -0
  20. package/admin/custom/assets/vite-preload-helper-nldAWQd6.js +1 -0
  21. package/admin/custom/customComponents.js +12 -0
  22. package/admin/custom/i18n/de.json +59 -0
  23. package/admin/custom/i18n/en.json +59 -0
  24. package/admin/custom/i18n/es.json +59 -0
  25. package/admin/custom/i18n/fr.json +59 -0
  26. package/admin/custom/i18n/it.json +59 -0
  27. package/admin/custom/i18n/nl.json +59 -0
  28. package/admin/custom/i18n/pl.json +59 -0
  29. package/admin/custom/i18n/pt.json +59 -0
  30. package/admin/custom/i18n/ru.json +59 -0
  31. package/admin/custom/i18n/uk.json +59 -0
  32. package/admin/custom/i18n/zh-cn.json +59 -0
  33. package/admin/custom/mf-manifest.json +1 -0
  34. package/admin/doc-md/readme.txt +2 -6
  35. package/admin/doc-md/start_de.md +34 -89
  36. package/admin/doc-md/start_en.md +33 -90
  37. package/admin/doc-md/table-conditions_de.md +7 -9
  38. package/admin/doc-md/table-conditions_en.md +7 -9
  39. package/admin/doc-md/table-execution_de.md +11 -10
  40. package/admin/doc-md/table-execution_en.md +12 -11
  41. package/admin/doc-md/table-options_de.md +58 -0
  42. package/admin/doc-md/table-options_en.md +58 -0
  43. package/admin/doc-md/table-target-devices_de.md +20 -16
  44. package/admin/doc-md/table-target-devices_en.md +18 -16
  45. package/admin/doc-md/table-target-enums_de.md +13 -13
  46. package/admin/doc-md/table-target-enums_en.md +12 -14
  47. package/admin/doc-md/table-target-url_de.md +14 -25
  48. package/admin/doc-md/table-target-url_en.md +14 -23
  49. package/admin/doc-md/table-trigger-devices_de.md +10 -11
  50. package/admin/doc-md/table-trigger-devices_en.md +10 -10
  51. package/admin/doc-md/table-trigger-motion_de.md +41 -24
  52. package/admin/doc-md/table-trigger-motion_en.md +35 -19
  53. package/admin/doc-md/table-trigger-times_de.md +11 -12
  54. package/admin/doc-md/table-trigger-times_en.md +11 -11
  55. package/admin/doc-md/table-zones_de.md +19 -14
  56. package/admin/doc-md/table-zones_en.md +19 -14
  57. package/admin/doc-md/table-zones_select-targets_de.md +7 -15
  58. package/admin/doc-md/table-zones_select-targets_en.md +7 -15
  59. package/admin/i18n/{de/translations.json → de.json} +2 -1
  60. package/admin/i18n/{en/translations.json → en.json} +2 -1
  61. package/admin/i18n/{es/translations.json → es.json} +2 -1
  62. package/admin/i18n/{fr/translations.json → fr.json} +2 -1
  63. package/admin/i18n/{it/translations.json → it.json} +2 -1
  64. package/admin/i18n/{nl/translations.json → nl.json} +2 -1
  65. package/admin/i18n/{pl/translations.json → pl.json} +2 -1
  66. package/admin/i18n/{pt/translations.json → pt.json} +2 -1
  67. package/admin/i18n/{ru/translations.json → ru.json} +2 -1
  68. package/admin/i18n/uk.json +110 -0
  69. package/admin/i18n/{zh-cn/translations.json → zh-cn.json} +2 -1
  70. package/admin/img/option-screenshots/tab-conditions.png +0 -0
  71. package/admin/img/option-screenshots/tab-further-options.png +0 -0
  72. package/admin/img/option-screenshots/tab-start.png +0 -0
  73. package/admin/img/option-screenshots/tab-target-devices.png +0 -0
  74. package/admin/img/option-screenshots/tab-triggers-motion.png +0 -0
  75. package/admin/img/option-screenshots/tab-triggers-other.png +0 -0
  76. package/admin/img/option-screenshots/tab-triggers-time.png +0 -0
  77. package/admin/img/option-screenshots/tab-zones-execution.png +0 -0
  78. package/admin/img/option-screenshots/tab-zones.png +0 -0
  79. package/admin/jsonConfig.json5 +569 -0
  80. package/io-package.json +30 -27
  81. package/lib/helper.js +40 -6
  82. package/lib/trigger-class.js +185 -80
  83. package/lib/trigger-match.js +76 -0
  84. package/main.js +132 -62
  85. package/package.json +11 -21
  86. package/admin/admin.d.ts +0 -4
  87. package/admin/css/LICENSE-github-markdown-css.txt +0 -24
  88. package/admin/css/github-markdown-dark.min.css +0 -8
  89. package/admin/css/github-markdown.min.css +0 -8
  90. package/admin/doc-md/img/start_dropdown-ani.gif +0 -0
  91. package/admin/doc-md/img/start_open-dialog.png +0 -0
  92. package/admin/doc-md/img/start_show-explanation.gif +0 -0
  93. package/admin/doc-md/img/table-zones_select-target-devices-overwrite.gif +0 -0
  94. package/admin/fancytree/skin-lion/icons-rtl.gif +0 -0
  95. package/admin/fancytree/skin-lion/icons.gif +0 -0
  96. package/admin/fancytree/skin-lion/loading.gif +0 -0
  97. package/admin/fancytree/skin-lion/ui.fancytree.min.css +0 -6
  98. package/admin/fancytree/skin-lion/vline-rtl.gif +0 -0
  99. package/admin/fancytree/skin-lion/vline.gif +0 -0
  100. package/admin/img/info-big.png +0 -0
  101. package/admin/img/info-big.png_README.txt +0 -6
  102. package/admin/img/sc_always.png +0 -0
  103. package/admin/img/select-target-devices-overwrite.gif +0 -0
  104. package/admin/img/smartControl_options1.gif +0 -0
  105. package/admin/img/smartControl_options_dropdown.gif +0 -0
  106. package/admin/img/smartControl_options_dropdown_2.gif +0 -0
  107. package/admin/index_m.html +0 -812
  108. package/admin/index_m.js +0 -1659
  109. package/admin/style.css +0 -255
  110. package/admin/tsconfig.json +0 -45
  111. package/admin/words.js +0 -113
  112. package/admin/zero-md/readme.txt +0 -1
  113. package/admin/zero-md/webcomponents-loader.min.js +0 -9
  114. package/admin/zero-md/zero-md.min.js.js +0 -9
  115. package/lib/tools.js +0 -99
package/admin/index_m.js DELETED
@@ -1,1659 +0,0 @@
1
- /* eslint-disable no-irregular-whitespace */
2
- /* eslint-disable-next-line no-undef */
3
- /* eslint-env jquery, browser */ // https://eslint.org/docs/user-guide/configuring#specifying-environments
4
- /* global sendTo, getEnums, common, systemLang, socket, values2table, table2values, M, _, instance */ // for eslint
5
- /**
6
- * List of some global constants
7
- *
8
- * systemLang - 'en', 'de', 'ru', ect. // iobroker.admin/www/js/adapter-settings.js
9
- */
10
-
11
-
12
- /**
13
- * ioBroker function explanation
14
- * onChange(boolean) - if set true, grayed out save button turns to blue and being activated, and vice versa if false
15
- * _(string) - the provided translation key will be translated into ioBroker's admin language (words.js)
16
- *
17
- */
18
-
19
- const adapterNamespace = `smartcontrol.${instance}`;
20
-
21
- /**
22
- * Basic Constants
23
- */
24
-
25
- // ++++++ Define option tables ++++++
26
- const tableIds = [
27
- 'tableTargetDevices',
28
- 'tableTargetEnums',
29
- 'tableTargetURLs',
30
- 'tableConditions',
31
- 'tableTriggerMotion',
32
- 'tableTriggerDevices',
33
- 'tableTriggerTimes',
34
- 'tableZones',
35
- ];
36
-
37
- const optionTablesSettings = {}; // Table variable holding the table settings array
38
- for (const lpTableId of tableIds) {
39
- optionTablesSettings[lpTableId] = [];
40
- }
41
-
42
- /**
43
- * Enums
44
- */
45
- const enums = {};
46
-
47
-
48
- /** More Globals, being set once load() is called */
49
- let g_settings; // To have globally the settings available.
50
- const g_zonesTargetsOverwrite = {}; // { 'Hallway': {'Hallway.Light':'new val' 'Hallway.Radio':'Radio XYZ'} }, {'Bath Light': '33%'} }
51
-
52
-
53
- /************************************************************************
54
- *** This is called by the admin adapter once the settings page loads ***
55
- ************************************************************************/
56
- function load (settings, onChange) { /*eslint-disable-line no-unused-vars*/
57
-
58
- /**
59
- * 06-October-2020
60
- * Once load() is called, we need to get the enums, before we continue.
61
- * Quickly implemented with callbacks and call load2() once completed.
62
- * TODO: Do this more beautiful and with better performance, like with Promise.all() if supported by current browsers
63
- */
64
- getTargetEnums('rooms', (res)=> {
65
- if(res) {
66
- enums.rooms = res;
67
- } else {
68
- console.warn(`No room enumerations found, so you cannot select rooms in Targets > Enums`);
69
- }
70
- getTargetEnums('functions', (res)=>{
71
- if(res) {
72
- enums.functions = res;
73
- } else {
74
- console.warn(`No function enumerations found, so you cannot use Targets > Table 'Target Devices: Enums'.`);
75
- }
76
- load2(settings, onChange);
77
- });
78
- });
79
-
80
-
81
- }
82
-
83
-
84
- /**
85
- * Helligkeit einer CSS-Hintergrundfarbe (nur opak, kein transparent).
86
- */
87
- function luminanceFromCssColor(bg) {
88
- const m = bg && bg.match(
89
- /rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:\s*,\s*([\d.]+))?\s*\)/,
90
- );
91
- if (!m) {
92
- return null;
93
- }
94
- const alpha = m[4] !== undefined ? parseFloat(m[4]) : 1;
95
- if (alpha < 0.05) {
96
- return null;
97
- }
98
- return 0.299 * +m[1] + 0.587 * +m[2] + 0.114 * +m[3];
99
- }
100
-
101
- /** Hellster sichtbarer Tab-Hintergrund (versteckte Tabs ignorieren). */
102
- function pageBackgroundLuminance() {
103
- let brightest = null;
104
- const pages = document.querySelectorAll('.adapter-container .page, .page');
105
- pages.forEach((page) => {
106
- const style = getComputedStyle(page);
107
- if (style.display === 'none' || style.visibility === 'hidden') {
108
- return;
109
- }
110
- const lum = luminanceFromCssColor(style.backgroundColor);
111
- if (lum !== null && (brightest === null || lum > brightest)) {
112
- brightest = lum;
113
- }
114
- });
115
- if (brightest !== null) {
116
- return brightest;
117
- }
118
- return luminanceFromCssColor(getComputedStyle(document.body).backgroundColor);
119
- }
120
-
121
- /**
122
- * Markdown hell/dunkel: heller sichtbarer Hintergrund schlägt hängende react-dark-Klasse.
123
- */
124
- function isAdminDarkTheme() {
125
- const root = document.querySelector('.adapter-container');
126
- if (
127
- root &&
128
- (root.classList.contains('react-light') || root.classList.contains('react-colored'))
129
- ) {
130
- return false;
131
- }
132
-
133
- const lum = pageBackgroundLuminance();
134
- if (lum !== null && lum >= 140) {
135
- return false;
136
- }
137
- if (lum !== null && lum < 90) {
138
- return true;
139
- }
140
-
141
- return !!(
142
- root &&
143
- (root.classList.contains('react-dark') || root.classList.contains('react-blue'))
144
- );
145
- }
146
-
147
- /** Steuert style.css für Klapp-Hilfen (react-dark-Klasse kann nach Theme-Wechsel hängen bleiben). */
148
- function syncMarkdownThemeMarker(adminIsDark) {
149
- const root = document.querySelector('.adapter-container');
150
- if (root) {
151
- root.setAttribute('data-smartcontrol-md-theme', adminIsDark ? 'dark' : 'light');
152
- }
153
- }
154
-
155
- function clearZeroMdStylesheetCache() {
156
- if (!window.ZeroMd || !window.ZeroMd.cache) {
157
- return;
158
- }
159
- Object.keys(window.ZeroMd.cache).forEach((key) => {
160
- if (key.includes('github-markdown')) {
161
- delete window.ZeroMd.cache[key];
162
- }
163
- });
164
- }
165
-
166
- /**
167
- * zero-md lädt css-urls nur, wenn KEIN <template><style> gesetzt ist (siehe zero-md render).
168
- */
169
- function applyZeroMdTheme(mdEl, adminIsDark) {
170
- if (!mdEl) {
171
- return;
172
- }
173
- const tpl = mdEl.querySelector('template');
174
- if (tpl) {
175
- const st = tpl.content.querySelector('style');
176
- if (st) {
177
- st.remove();
178
- }
179
- }
180
- clearZeroMdStylesheetCache();
181
- const themeTag = adminIsDark ? 'dark' : 'light';
182
- // Lokal im Adapter (kein CDN): Installationen ohne Internet behalten die Hilfe-Styles.
183
- const cssFile = adminIsDark ? 'css/github-markdown-dark.min.css' : 'css/github-markdown.min.css';
184
- const cssUrls = [`${cssFile}?sc=${themeTag}`];
185
- mdEl.setAttribute('css-urls', JSON.stringify(cssUrls));
186
-
187
- const onRendered = () => {
188
- mdEl.removeEventListener('zero-md-rendered', onRendered);
189
- if (!mdEl.shadowRoot) {
190
- return;
191
- }
192
- mdEl.shadowRoot.querySelectorAll('style.smartcontrol-md-extra').forEach((el) => el.remove());
193
- const extra = document.createElement('style');
194
- extra.className = 'smartcontrol-md-extra';
195
- extra.textContent = adminIsDark ? ZERO_MD_DARK_SHADOW_STYLE : ZERO_MD_LIGHT_SHADOW_STYLE;
196
- mdEl.shadowRoot.appendChild(extra);
197
- };
198
- mdEl.addEventListener('zero-md-rendered', onRendered);
199
- }
200
-
201
- /** Zusatz-CSS im zero-md Shadow DOM, falls das GitHub-Dark-Sheet nicht alles trifft */
202
- const ZERO_MD_DARK_SHADOW_STYLE = `
203
- .markdown-body {
204
- color-scheme: dark;
205
- background-color: transparent !important;
206
- color: #e6edf3 !important;
207
- }
208
- .markdown-body p,
209
- .markdown-body li,
210
- .markdown-body td,
211
- .markdown-body th {
212
- color: #e6edf3 !important;
213
- }
214
- .markdown-body table tr {
215
- background-color: transparent !important;
216
- }
217
- .markdown-body th {
218
- background-color: #21262d !important;
219
- }
220
- .markdown-body a {
221
- color: #58a6ff !important;
222
- }
223
- .markdown-body code {
224
- background-color: rgba(110, 118, 129, 0.35) !important;
225
- color: #e6edf3 !important;
226
- }
227
- `;
228
-
229
- /** Hellmodus: überschreibt auch Reste von github-markdown-dark (dunkle Tabellenzeilen) */
230
- const ZERO_MD_LIGHT_SHADOW_STYLE = `
231
- .markdown-body {
232
- color-scheme: light;
233
- background-color: #ffffff !important;
234
- color: #1f2328 !important;
235
- }
236
- .markdown-body p,
237
- .markdown-body li,
238
- .markdown-body td,
239
- .markdown-body th,
240
- .markdown-body strong {
241
- color: #1f2328 !important;
242
- }
243
- .markdown-body table,
244
- .markdown-body table tr,
245
- .markdown-body table td,
246
- .markdown-body table th {
247
- background-color: #ffffff !important;
248
- border-color: #d0d7de !important;
249
- }
250
- .markdown-body table tr:nth-child(2n) td {
251
- background-color: #f6f8fa !important;
252
- }
253
- .markdown-body th {
254
- background-color: #f6f8fa !important;
255
- }
256
- .markdown-body a {
257
- color: #0969da !important;
258
- }
259
- .markdown-body code {
260
- background-color: rgba(175, 184, 193, 0.2) !important;
261
- color: #1f2328 !important;
262
- }
263
- `;
264
-
265
- function load2(settings, onChange) {
266
- // Adapter Settings
267
- if (!settings) return;
268
- g_settings = settings;
269
-
270
- const adapterVersion = common.version;
271
- $('#tabMain span#adapter-version').html(adapterVersion);
272
-
273
- /**
274
- * Apply markdown for documentation through https://github.com/zerodevx/zero-md
275
- */
276
-
277
- // index_m.html: All ids defined in <zero-md> tags, like ['md-start', 'md-targetDevices', ...]
278
- const mdIds = $('zero-md[manual-render]').map((i, el) => el.getAttribute('id')).get(); // https://stackoverflow.com/a/54392415
279
-
280
- const adminIsDark = isAdminDarkTheme();
281
- syncMarkdownThemeMarker(adminIsDark);
282
-
283
- for (const mdId of mdIds) {
284
- const mdEl = document.querySelector('zero-md#' + mdId);
285
- applyZeroMdTheme(mdEl, adminIsDark);
286
-
287
- const mdFilePath = $('zero-md#' + mdId).attr('src'); // like 'doc-md/start_en.md'
288
- if (mdFilePath) {
289
-
290
- if (systemLang !== 'en') { // English is always required
291
- const newFilePath = mdFilePath.slice(0, -5) + `${systemLang}.md`; // remove last 5 chars 'en.js' and add <lang>.js
292
- if (fileExists(newFilePath)) {
293
- $('zero-md#' + mdId).attr('src', newFilePath); // set new file path src of <zero-md>
294
- } else {
295
- // Fallback is English. We add a note to the HTML
296
- $(`
297
- <p class='translation-required'>
298
- Your current ioBroker language is <strong>${systemLang.toUpperCase()}</strong>, however, the following instructions have not yet been translated into your language, so English is used as fallback.
299
- If you are fluently speaking ${systemLang.toUpperCase()}, please help and translate into your language.
300
- The English file is <a target="_blank" href="https://github.com/iobroker-community-adapters/ioBroker.smartcontrol/blob/master/admin/${mdFilePath}">located on Github</a>: <code>https://github.com/iobroker-community-adapters/ioBroker.smartcontrol/blob/master/admin/${mdFilePath}</code>.
301
- Please translate and provide a Github pull request for adding a new file '${newFilePath}' with your ${systemLang.toUpperCase()} translation. Thank you!
302
- </p>
303
- `).insertBefore('zero-md#' + mdId);
304
- }
305
- }
306
- } else {
307
- console.warn(`load(): mdFilePath for '${mdId}' is undefined, so we use English.`);
308
- }
309
-
310
- // Finally, render zero-md - https://github.com/zerodevx/zero-md#public-methods
311
- setTimeout(() => {
312
- const el = document.querySelector('zero-md#' + mdId);
313
- if (el) {
314
- applyZeroMdTheme(el, adminIsDark);
315
- el.render();
316
- }
317
- }, 100);
318
- }
319
-
320
- // Hilfe neu rendern, wenn Klappbereich aufgeht (Materialize-Collapsible)
321
- $('.collapsible').off('click.smartcontrolMd', '.collapsible-header').on(
322
- 'click.smartcontrolMd',
323
- '.collapsible-header',
324
- function () {
325
- setTimeout(() => {
326
- const dark = isAdminDarkTheme();
327
- syncMarkdownThemeMarker(dark);
328
- $(this).siblings('.collapsible-body').find('zero-md[manual-render]').each(function () {
329
- applyZeroMdTheme(this, dark);
330
- this.render();
331
- });
332
- }, 350);
333
- },
334
- );
335
-
336
- /**
337
- * tableTargetEnums: set enum room and function names to drop down (multiple select) fields
338
- */
339
- if(enums.rooms) $('#tableTargetEnums *[data-name="enumRooms"]').data('options', enums.rooms.join(';'));
340
- if(enums.functions) $('#tableTargetEnums *[data-name="enumId"]').data('options', enums.functions.join(';'));
341
-
342
- /**
343
- * Set tableZones>targetsOverwrite to global variable
344
- */
345
- for (const lpZonesRow of settings['tableZones']) {
346
- const lpZoneName = lpZonesRow.name;
347
- if(!isLikeEmpty(lpZonesRow['targetsOverwrite'])) {
348
- g_zonesTargetsOverwrite[lpZoneName] = lpZonesRow['targetsOverwrite'];
349
- }
350
- }
351
-
352
- // This handles if the save button is clickable or not.
353
- // From Adapter Creator.
354
- $('.value').each(function() {
355
- const $key = $(this);
356
- const id = $key.attr('id');
357
- if (!id) {
358
- console.warn(`Attribute 'id' not found for $('.value')`);
359
- } else {
360
- if ($key.attr('type') === 'checkbox') {
361
- // do not call onChange direct, because onChange could expect some arguments
362
- $key.prop('checked', settings[id])
363
- .on('change', () => onChange());
364
- } else {
365
- // do not call onChange direct, because onChange could expect some arguments
366
- $key.val(settings[id])
367
- .on('change', () => onChange())
368
- .on('keyup', () => onChange());
369
- }
370
- }
371
- });
372
-
373
- // load fancytree for target device selection modal dialog
374
- fancytreeLoad('fancytree-select-settings');
375
-
376
- // ++++++ For option tables ++++++
377
- for (const lpTableId of tableIds) {
378
- optionTablesSettings[lpTableId] = settings[lpTableId] || [];
379
- }
380
-
381
- onChange(false);
382
-
383
- // ++++++ For option tables ++++++
384
- // values2table() - see iobroker/node_modules/iobroker.admin/www/js/adapter-settings.js
385
- const tTableIds = tableIds;
386
- tTableIds.push('tableZoneExecution'); // special dialog table
387
- for (const lpTableId of tableIds) {
388
- // x@ts-ignore - Ignore "An argument for 'maxRaw' was not provided."
389
- values2table(lpTableId, optionTablesSettings[lpTableId], onChange, function(){val2tableOnReady(lpTableId);});
390
- }
391
-
392
- /**
393
- * We call with values2table onReady parameter
394
- * @param {string} tableId - Table Id, like 'tableTriggerMotion', or blank string '' if nothing shall be executed
395
- */
396
- function val2tableOnReady(tableId) {
397
-
398
- switch (tableId) {
399
- case 'tableTargetDevices':
400
- statePathPopupSelection(tableId,'stateSelectPopupOnState', 'onState');
401
- statePathPopupSelection(tableId,'stateSelectPopupOffState', 'offState');
402
- updateTableButtonIcons(tableId, [{dataButton:'stateSelectPopupOnState', icon:'search'},{dataButton:'stateSelectPopupOffState', icon:'search'}]);
403
- addCopyTableRowSmarter(tableId);
404
- break;
405
- case 'tableTargetEnums':
406
- addCopyTableRowSmarter(tableId);
407
- break;
408
- case 'tableTargetURLs':
409
- addCopyTableRowSmarter(tableId);
410
- break;
411
- case 'tableConditions':
412
- statePathPopupSelection(tableId,'stateSelectPopupConditionState', 'conditionState');
413
- updateTableButtonIcons(tableId, [{dataButton:'stateSelectPopupConditionState', icon:'search'}]);
414
- addCopyTableRowSmarter(tableId);
415
- break;
416
-
417
- case 'tableTriggerMotion':
418
- statePathPopupSelection(tableId,'stateSelectPopupMotionState', 'stateId');
419
- statePathPopupSelection(tableId,'stateSelectPopupBriState', 'briStateId');
420
- dialogSelectSettings({tableId:'tableTriggerMotion', triggerDataCmd:'motionSelectLinkedTrigger', targetField:'motionLinkedTrigger', dialogTitle:_('Select linked triggers') });
421
- updateTableButtonIcons(tableId, [{dataButton:'stateSelectPopupMotionState', icon:'search'},{dataButton:'stateSelectPopupBriState', icon:'search'}, {dataButton:'motionSelectLinkedTrigger', icon:'pageview'}]);
422
- addCopyTableRowSmarter(tableId);
423
- break;
424
-
425
- case 'tableTriggerDevices':
426
- statePathPopupSelection(tableId,'stateSelectPopupStateId', 'stateId');
427
- updateTableButtonIcons(tableId, [{dataButton:'stateSelectPopupStateId', icon:'search'}]);
428
- addCopyTableRowSmarter(tableId);
429
- otherTriggersShowHideUserStates();
430
- break;
431
- case 'tableTriggerTimes':
432
- dialogSelectSettings({tableId:'tableTriggerTimes', triggerDataCmd:'selectAdditionalConditions', targetField:'additionalConditions', dialogTitle:_('Select additional conditions') });
433
- dialogSelectSettings({tableId:'tableTriggerTimes', triggerDataCmd:'selectNever', targetField:'never', dialogTitle:_(`Select 'never if...'`) });
434
- updateTableButtonIcons(tableId, [{dataButton:'selectAdditionalConditions', icon:'pageview'},{dataButton:'selectNever', icon:'pageview'}]);
435
- addCopyTableRowSmarter(tableId);
436
- break;
437
- case 'tableZones':
438
- dialogSelectSettings({tableId:'tableZones', triggerDataCmd:'selectTriggers', targetField:'triggers', dialogTitle:_('Select triggers') });
439
- dialogSelectSettings({tableId:'tableZones', triggerDataCmd:'selectTargetsMenu', targetField:'targets', dialogTitle:_('Select target devices') });
440
- dialogSelectSettings({tableId:'tableZones', triggerDataCmd:'selectNeverOff', targetField:'neverOff', dialogTitle:_(`Select 'never switch off if...'`) });
441
- dialogConfigureZoneExecution();
442
- updateTableButtonIcons(tableId, [{dataButton:'selectTriggers', icon:'pageview'},{dataButton:'selectTargetsMenu', icon:'pageview'},{dataButton:'selectNeverOff', icon:'pageview'},{dataButton:'configureExecution', icon:'schedule', regularSize:true}]);
443
- addCopyTableRowSmarter(tableId);
444
- addInfo(tableId);
445
- break;
446
- case 'tableZoneExecution':
447
- dialogSelectSettings({tableId:tableId, triggerDataCmd:'selectAdditionalConditions', targetField:'additionalConditions', dialogTitle:_('Select additional conditions') });
448
- dialogSelectSettings({tableId:tableId, triggerDataCmd:'selectNever', targetField:'never', dialogTitle:_(`Select 'never switch on if...'`) });
449
- updateTableButtonIcons(tableId, [{dataButton:'selectAdditionalConditions', icon:'pageview'},{dataButton:'selectNever', icon:'pageview'}]);
450
- break;
451
- default:
452
- break;
453
- }
454
-
455
-
456
- }
457
-
458
- // Enhance Tabs with onTabShow-Function. Source: iQontrol Adapter.
459
- // This allows using JavaScript to perform certain actions as defined in function onTabShow(), since we have
460
- // several tabs in this adapter configuration.
461
- onTabShow('#tabMain');
462
- onTabShow('#tabDevices');
463
- onTabShow('#tabConditions');
464
- onTabShow('#tabTriggers');
465
- onTabShow('#tabZones');
466
- onTabShow('#tabSchedules');
467
- // --
468
-
469
- $('ul.tabs li a').on('click', function() {
470
- onTabShow($(this).attr('href'));
471
- });
472
- function onTabShow(tabId){
473
- switch(tabId){
474
-
475
- case '#tabMain':
476
- $('.collapsible').collapsible(); // https://materializecss.com/collapsible.html
477
- break;
478
-
479
- case '#tabDevices':
480
- $('.collapsible').collapsible(); // https://materializecss.com/collapsible.html
481
- if(enums.rooms) $('#tableTargetEnums *[data-name="enumRooms"]').data('options', enums.rooms.join(';'));
482
- if(enums.functions) $('#tableTargetEnums *[data-name="enumId"]').data('options', enums.functions.join(';'));
483
- values2table('tableTargetEnums', optionTablesSettings['tableTargetEnums'], onChange, function(){val2tableOnReady('tableTargetEnums');});
484
- break;
485
-
486
- case '#tabConditions':
487
- $('.collapsible').collapsible(); // https://materializecss.com/collapsible.html
488
- break;
489
-
490
- case '#tabTriggers':
491
- $('.collapsible').collapsible(); // https://materializecss.com/collapsible.html
492
- populateTable('tableConditions', 'name', 'tableTriggerTimes', 'additionalConditions');
493
- populateTable('tableConditions', 'name', 'tableTriggerTimes', 'never');
494
- populateTable(['tableTriggerDevices'], ['name'], 'tableTriggerMotion', 'motionLinkedTrigger');
495
- break;
496
-
497
- case '#tabZones':
498
- $('.collapsible').collapsible(); // https://materializecss.com/collapsible.html
499
- populateTable(['tableTriggerMotion', 'tableTriggerDevices', 'tableTriggerTimes'], ['name', 'name', 'name'], 'tableZones', 'triggers');
500
- populateTable(['tableTargetDevices', 'tableTargetEnums', 'tableTargetURLs'], ['name', 'name', 'name'], 'tableZones', 'targets');
501
- populateTable('tableConditions', 'name', 'tableZones', 'neverOff');
502
- break;
503
-
504
- }
505
- }
506
-
507
- function otherTriggersShowHideUserStates() {
508
-
509
- const jQueryStrCheckbox = `#tableTriggerDevices input[type="checkbox"][data-name="userState"]`;
510
- $(jQueryStrCheckbox).each(function() {
511
- doOrNot($(this));
512
- });
513
-
514
- $(jQueryStrCheckbox).on('change', function() {
515
- doOrNot($(this));
516
- });
517
-
518
- function doOrNot($checkbox) {
519
-
520
- const index = $checkbox.data('index'); // table row number which was clicked, starting at zero.
521
- const $stateField = $(`#tableTriggerDevices tr[data-index="${index}"] input[data-name="stateId"]`);
522
-
523
- if($checkbox.prop('checked') == true) {
524
- //checked
525
- $stateField.prev('div.userstates').remove(); // just in case
526
- $stateField.addClass('input-userstates');
527
- $stateField.before(`<div class="translate userstates">${_('State under')} ${adapterNamespace}.userstates. (${_('will be generated automatically')})</div>`);
528
- } else {
529
- //unchecked
530
- $stateField.removeClass('input-userstates');
531
- $stateField.prev('div.userstates').remove();
532
- }
533
-
534
- }
535
-
536
-
537
- }
538
-
539
-
540
- /**
541
- * Populate select field
542
- * @param {*} sourceTableIds Id of input table, like "tableTriggerMotion". String or array of strings for multiple tables
543
- * @param {*} sourceFieldIds Id of table line field, from which to get content, like "name". . String or array of strings for multiple fields
544
- * @param {string} targetTableId Target table id, like "tableZones"
545
- * @param {string} targetFieldId Target table line field, like 'Test'
546
- * @param {boolean} [sort] Optional: if true, values will be sorted
547
- * @param {boolean} [fill] Optional: if true, table will be filled. Set to false for tableExecution
548
- */
549
- function populateTable(sourceTableIds, sourceFieldIds, targetTableId, targetFieldId, sort=false, fill=true) {
550
-
551
- // jQuery
552
- const jQ = `#${targetTableId} *[data-name="${targetFieldId}"]`;
553
-
554
- if(!Array.isArray(sourceTableIds)) sourceTableIds = [sourceTableIds]; // wrap into array
555
- if(!Array.isArray(sourceFieldIds)) sourceFieldIds = [sourceFieldIds]; // wrap into array
556
- const result = [];
557
-
558
- for (let i = 0; i < sourceTableIds.length; i++) {
559
- const configTbl = settings[sourceTableIds[i]] || [];
560
- for (const lpElement of configTbl) {
561
- //if (lpElement['active'] == true) { // check for checkbox "active"
562
- result.push(lpElement[sourceFieldIds[i]]);
563
- //}
564
- }
565
- }
566
- // Create dropdown menu
567
- if(sort) result.sort();
568
- $(jQ).data('options', result.join(';'));
569
-
570
- // Fill table
571
- if(fill) values2table(targetTableId, optionTablesSettings[targetTableId], onChange, function(){val2tableOnReady(targetTableId);});
572
-
573
- }
574
-
575
-
576
- const fieldChangeConfig = [
577
- {changedTableId:'tableTargetDevices', targetTableId:'tableZones', targetId:'targets'},
578
- {changedTableId:'tableTargetEnums', targetTableId:'tableZones', targetId:'targets'},
579
- {changedTableId:'tableTargetURLs', targetTableId:'tableZones', targetId:'targets'},
580
- {changedTableId:'tableConditions', targetTableId:'tableTriggerTimes', targetId:'additionalConditions'},
581
- {changedTableId:'tableConditions', targetTableId:'tableTriggerTimes', targetId:'never'},
582
- {changedTableId:'tableConditions', targetTableId:'tableZones', targetId:'neverOff'},
583
- {changedTableId:'tableTriggerMotion', targetTableId:'tableZones', targetId:'triggers'},
584
- {changedTableId:'tableTriggerDevices', targetTableId:'tableZones', targetId:'triggers'},
585
- {changedTableId:'tableTriggerDevices', targetTableId:'tableTriggerMotion', targetId:'motionLinkedTrigger'},
586
- {changedTableId:'tableTriggerTimes', targetTableId:'tableZones', targetId:'triggers'},
587
- {changedTableId:'tableTriggerTimes', targetTableId:'tableTriggerMotion', targetId:'motionLinkedTrigger'},
588
- ];
589
- onTableRowNameChanges(fieldChangeConfig);
590
- /**
591
- * Handle all Table field changes of column "name":
592
- * Apply any name change (rename) to according tables using the name
593
- * For getting old field value, see https://stackoverflow.com/a/29118530
594
- * @param {array} fieldChangeConfig - Config array
595
- */
596
- function onTableRowNameChanges(fieldChangeConfig) {
597
-
598
-
599
- for (const lpConfig of fieldChangeConfig) {
600
- const jQueryName = `#${lpConfig.changedTableId} input.values-input[data-name="name"]`;
601
- // * Important - we cannot use //$(jQueryName).on('xxx') here. See https://stackoverflow.com/a/41457428
602
- // * It is not recognized if populateTable() is executed for that specific table.
603
- // * So we use $(document).on(), which works well.
604
- $(document).on('focusin', jQueryName, function(){ $(this).data('old-val', $(this).val()); });
605
- //$(jQueryName).on('change', function(){
606
- $(document).on('change',jQueryName, function() {
607
- const previousValue = $(this).data('old-val').trim();
608
- const newValue = $(this).val().trim();
609
- if (previousValue != newValue && newValue.length > 0) {
610
- // We have a field change.
611
- // Now let's change all values in according table and target field
612
- for (let i = 0; i < g_settings[lpConfig.targetTableId].length; i++) {
613
- const lpTargets = g_settings[lpConfig.targetTableId][i][lpConfig.targetId];
614
- if (typeof lpTargets == 'string') {
615
- // Handle string
616
- if (lpTargets.trim() == previousValue.trim()) {
617
- g_settings[lpConfig.targetTableId][i][lpConfig.targetId] = newValue;
618
- }
619
- } else {
620
- // We have an array. Process targets accordingly.
621
- for (let k = 0; k < lpTargets.length; k++) {
622
- if (lpTargets[k].trim() == previousValue.trim()) {
623
- g_settings[lpConfig.targetTableId][i][lpConfig.targetId][k] = newValue;
624
- }
625
- }
626
- }
627
-
628
- }
629
- }
630
- });
631
- }
632
- }
633
-
634
-
635
-
636
- /**
637
- * For Table Filter
638
- */
639
- for (const lpId of tableIds) {
640
-
641
- // Initially hide 'clear filter button' since no filter is set at this time
642
- $(`div#${lpId} .table-filter button`).hide();
643
-
644
- // Apply the filter
645
- applyTableFilter(lpId);
646
-
647
- // Clear filters on "Clear Filters" button click
648
- $(`div#${lpId} .table-filter button`).click(function() {
649
- $(`div#${lpId} .table-filter input`).val(''); // empty field
650
- $(`div#${lpId} table`).find('tr:gt(0)').show(); // show all rows
651
- $(`div#${lpId} .table-filter button`).hide(); // hide button
652
- });
653
-
654
- }
655
-
656
- /**
657
- * Dialog: Configure Execution of Zone
658
- */
659
- function dialogConfigureZoneExecution() {
660
-
661
- const queryResult = $(`#tableZones a.values-buttons[data-command="configureExecution"]`);
662
- queryResult.on('click', function() {
663
-
664
- // Fill drop down (select) fields with additional conditions
665
- populateTable('tableConditions', 'name', 'tableZoneExecution', 'additionalConditions', false, false);
666
- populateTable('tableConditions', 'name', 'tableZoneExecution', 'never', false, false);
667
-
668
- // a few variables
669
- const tableZonesObj = table2values('tableZones');
670
- const rowNum = $(this).data('index'); // table row number which was clicked, starting at zero.
671
- //const zoneName = optionTablesSettings['tableZones'][rowNum]['name'];
672
- const zoneName = tableZonesObj[rowNum].name;
673
-
674
- const always = (tableZonesObj[rowNum].executeAlways) ? true : false;
675
- const tableSett = (tableZonesObj[rowNum].executionJson) ? JSON.parse(tableZonesObj[rowNum].executionJson) : [];
676
-
677
- // Prepare table and checkbox
678
- values2table('tableZoneExecution', tableSett, onChange, function(){val2tableOnReady('tableZoneExecution');});
679
- $('#dialog-configure-zone-execution #executeZoneAlways').prop('checked', always);
680
-
681
- // Initialize dialog (modal)
682
- initDialog('dialog-configure-zone-execution', dialogOkClose);
683
-
684
- // Hide detailed config if "Execute always" checkbox is checked
685
- const $jQueryRes = $('#dialog-configure-zone-execution #executeZoneAlways');
686
-
687
- if (always) {
688
- $('#dialog-configure-zone-execution .show-if-always').show();
689
- $('#dialog-configure-zone-execution .hide-if-always').hide();
690
- } else {
691
- $('#dialog-configure-zone-execution .show-if-always').hide();
692
- $('#dialog-configure-zone-execution .hide-if-always').show();
693
- }
694
- $jQueryRes.change(function(){
695
- if(this.checked) {
696
- $('#dialog-configure-zone-execution .hide-if-always').fadeOut('slow');
697
- setTimeout(()=> { $('#dialog-configure-zone-execution .show-if-always').fadeIn('slow'); }, 500);
698
- } else {
699
- $('#dialog-configure-zone-execution .hide-if-always').fadeIn('slow');
700
- $('#dialog-configure-zone-execution .show-if-always').hide();
701
- }
702
- });
703
-
704
- // Add Zone Name to title
705
- $('#dialog-configure-zone-execution span.zone-name').text(zoneName);
706
-
707
- // Open dialog
708
- $('#dialog-configure-zone-execution').modal('open');
709
-
710
- // Called once user clicked "Ok" in the dialog
711
- function dialogOkClose() {
712
-
713
- const tableResult = table2values('tableZoneExecution');
714
-
715
- tableZonesObj[rowNum].executeAlways = $('#dialog-configure-zone-execution #executeZoneAlways').prop('checked');
716
- tableZonesObj[rowNum].executionJson = JSON.stringify(tableResult);
717
- values2table('tableZones', tableZonesObj, onChange, function(){val2tableOnReady('tableZones');});
718
-
719
- }
720
-
721
- });
722
- }
723
-
724
- /**
725
- * info button for textual explanation of the object
726
- */
727
- function addInfo(tableId) {
728
- // set the icon
729
- updateTableButtonIcons(tableId, [{dataButton:'info', icon:'live_help'}]);
730
- // Apply info editor
731
- $(`#${tableId} table tbody td a.values-buttons[data-command="info"]`).on('click', function() {
732
- const rowNum = $(this).data('index'); // table row number which was clicked, starting at zero.
733
- const tableArr = table2values(tableId);
734
- const actInfoText = tableArr[rowNum].infoText;
735
-
736
- $('#dialog-edit-info #infoText').prop('value', actInfoText);
737
-
738
- // Initialize dialog (modal)
739
- initDialog('dialog-edit-info', dialogOkClose);
740
- // Add Name to title
741
- $('#dialog-edit-info span.info-name').text(tableArr[rowNum].name);
742
- // Open dialog
743
- $('#dialog-edit-info').modal('open');
744
-
745
- // Called once user clicked "Ok" in the dialog
746
- function dialogOkClose() {
747
- onChange && onChange();
748
- tableArr[rowNum].infoText = $('#dialog-edit-info #infoText').prop('value');
749
- values2table(tableId, tableArr, onChange, function(){val2tableOnReady(tableId);});
750
- }
751
- });
752
- }
753
- /**
754
- * We replace "copy table row" command from node_modules/iobroker.admin/www/js/adapter-settings.js
755
- * Reason: rename name functionality does not work any longer if name keeps the same, therefore
756
- * we add '_Copy' to name field of copied row.
757
- * @param {string} tableId - Table ID, like "tableTargetDevices"
758
- */
759
- function addCopyTableRowSmarter(tableId) {
760
-
761
- // Replace icon, reason: If 'data-buttons' in table th is not set to a known keyword (like 'edit'), it uses 'add' as materialize icon.
762
- updateTableButtonIcons(tableId, [{dataButton:'copy_smart', icon:'content_copy'}]);
763
-
764
- // Apply copy
765
- $(`#${tableId} table tbody td a.values-buttons[data-command="copy_smart"]`).on('click', function() {
766
-
767
- const rowNum = $(this).data('index'); // table row number which was clicked, starting at zero.
768
- const tableArr = table2values(tableId);
769
- const elem = {... tableArr[rowNum] }; // Copy, so not referencing
770
- if (elem.name) elem.name = elem.name + '_Copy';
771
-
772
- // Add copied row below current row, of which the copy button was clicked
773
- //tableArr.splice(rowNum+1, 0, elem);
774
- tableArr.push(elem); // push would add it at the end
775
- onChange && onChange();
776
-
777
- g_settings[tableId] = tableArr; // ? Seems to be important: without this, onTableRowNameChanges() will not work
778
- setTimeout(()=> {
779
- // Timeout is set in adapter-settings.js for copy - most likely for very good reasons, so we do as well.
780
- values2table(tableId, tableArr, onChange, function(){val2tableOnReady(tableId);});
781
- }, 100);
782
-
783
-
784
- // Activate save button
785
- //onChange(true);
786
-
787
- });
788
- }
789
-
790
-
791
- /**
792
- * Dialog: Select Settings (like Triggers or Target Devices)
793
- * @param {object} given - like: {tableId:'tableZones', triggerDataCmd:'selectTargetsMenu', targetField:'targets', dialogTitle:'some title' }
794
- */
795
- function dialogSelectSettings(given) {
796
-
797
- const tableId = given.tableId;
798
- const triggerDataCmd = given.triggerDataCmd;
799
- const targetField = given.targetField;
800
- const dialogTitle = given.dialogTitle;
801
-
802
- const queryResult = $(`#${tableId} a.values-buttons[data-command="${triggerDataCmd}"]`);
803
- queryResult.on('click', function() {
804
-
805
- // A few variables
806
- let anyChange = false; // true if anything changed, i.e. either checkbox (de-)selected, or overwrite option val changed
807
- const rowNum = $(this).data('index'); // table row number which was clicked, starting at zero. data-index is also the row number starting at zero
808
- const dropDownAllOptions = getSelectOptions(`#${tableId} .values-input[data-name="${targetField}"][data-index="${rowNum}"]`, true);
809
- const dropDownSelectionArray = getSelectOptions(`#${tableId} .values-input[data-name="${targetField}"][data-index="${rowNum}"]`, false);
810
- const editTargetVals = (triggerDataCmd == 'selectTargetsMenu') ? true : false;
811
-
812
- // Set modal title
813
- $('#dialog-select-settings>.modal-content>.row>.col>h6.title').text(dialogTitle);
814
-
815
- // Initialize dialog (modal)
816
- initDialog('dialog-select-settings', dialogOkClose);
817
-
818
- // Hide explanation in dialog if editTargetVals is false
819
- if (!editTargetVals) $('#dialog-select-settings #fancy-explanation').hide();
820
-
821
- // Set current settings as source into FancyTree
822
- // If Target Device Selection, we set according zoneName
823
- const zoneName = (editTargetVals) ? (g_settings.tableZones[rowNum].name) : undefined; // like "Relax Area"
824
- $('#fancytree-select-settings').fancytree('option', 'source', convertToFancySource(dropDownAllOptions, dropDownSelectionArray, zoneName));
825
-
826
- /**
827
- * Sort nodes
828
- */
829
- // Folders first. To deactivate folders first: set variable "cmp" to null to deactivate. // https://stackoverflow.com/a/22638802
830
- const cmp=function(a, b) {
831
- const x = (a.isFolder() ? '0' : '1') + a.title.toLowerCase();
832
- const y = (b.isFolder() ? '0' : '1') + b.title.toLowerCase();
833
- return x === y ? 0 : x > y ? 1 : -1;
834
- };
835
- const node = $.ui.fancytree.getTree('#fancytree-select-settings').getRootNode();
836
- node.sortChildren(cmp, true);
837
-
838
- // Open dialog
839
- $('#dialog-select-settings').modal('open');
840
-
841
- // Called once user clicked "Ok" in the dialog
842
- function dialogOkClose() {
843
-
844
- const tree = $.ui.fancytree.getTree('#fancytree-select-settings');
845
- const allFancyNodes = tree.getRootNode().findAll('');
846
- const selectedFancyNodes = tree.getSelectedNodes();
847
- const zoneName = g_settings['tableZones'][rowNum]['name']; // Current Zone Name
848
-
849
- for (const lpNode of allFancyNodes) {
850
- if(!lpNode.children) { // We just need end nodes
851
- // If title has {xxx} at the end, we retrieve xxx
852
- const matches = lpNode.title.match(/{(.+)}$/);
853
- if (matches && matches[1] && matches[1].length > 0) {
854
- if (isLikeEmpty(g_zonesTargetsOverwrite) || isLikeEmpty(g_zonesTargetsOverwrite[zoneName])) {
855
- g_zonesTargetsOverwrite[zoneName] = {}; // Add key with empty object
856
- }
857
- // Add to global variable, e.g. '{'Bath.Mirror.Light':'20%'}'
858
- if ( isLikeEmpty(g_zonesTargetsOverwrite[zoneName][lpNode.key])
859
- || ( !isLikeEmpty(g_zonesTargetsOverwrite[zoneName][lpNode.key])
860
- && g_zonesTargetsOverwrite[zoneName][lpNode.key] != matches[1] ) )
861
- {
862
- g_zonesTargetsOverwrite[zoneName][lpNode.key] = matches[1];
863
- anyChange = true;
864
- }
865
-
866
- } else {
867
- // Remove from global variable
868
- if (!isLikeEmpty(g_zonesTargetsOverwrite)
869
- && !isLikeEmpty(g_zonesTargetsOverwrite[zoneName])
870
- && !isLikeEmpty(g_zonesTargetsOverwrite[zoneName][lpNode.key]))
871
- {
872
- delete g_zonesTargetsOverwrite[zoneName][lpNode.key];
873
- anyChange = true;
874
- }
875
- }
876
- }
877
- }
878
-
879
-
880
- const selectedKeys = [];
881
- for (const selectedNode of selectedFancyNodes) {
882
- selectedKeys.push(selectedNode.key);
883
-
884
- }
885
-
886
- // check if selected nodes actually changed
887
- if (!arraysEqual(dropDownSelectionArray, selectedKeys)) anyChange = true;
888
-
889
- /**
890
- * Finally: Set to option tables, also to ensure materialize select field is being updated, save button is available, etc.
891
- */
892
- if (anyChange) {
893
-
894
- // Option tables
895
- if (tableId == 'tableZoneExecution') {
896
- const tableExecObj = table2values(tableId);
897
- tableExecObj[rowNum][targetField] = selectedKeys;
898
- values2table(tableId, tableExecObj, onChange, function(){val2tableOnReady(tableId);});
899
- } else {
900
- optionTablesSettings[tableId][rowNum][targetField] = selectedKeys;
901
- values2table(tableId, optionTablesSettings[tableId], onChange, function(){val2tableOnReady(tableId);});
902
- }
903
-
904
- // Activate save button
905
- onChange(true);
906
-
907
- }
908
-
909
- }
910
-
911
- });
912
- }
913
-
914
- // From ioBroker Adapter Creator:
915
- // Re-initialize all the Materialize labels on the page if you are dynamically adding inputs.
916
- // @ts-ignore - Property 'updateTextFields' does not exist on type 'typeof M'.ts(2339)
917
- if (M) M.updateTextFields();
918
-
919
-
920
- } // load
921
-
922
-
923
- /**
924
- * Save Options - Called by the admin adapter when the user clicks save
925
- * @param {function} callback(settingsObject) - callback function containing the settings object to be saved.
926
- */
927
- async function save(callback) { /*eslint-disable-line no-unused-vars*/
928
-
929
- try {
930
-
931
- /**
932
- * Select elements with class=value and build settings object
933
- * (from Adapter Creator)
934
- */
935
- let obj = {};
936
- $('.value').each(function() {
937
- const $this = $(this);
938
- if ($this.attr('type') === 'checkbox') {
939
- obj[$this.attr('id')] = $this.prop('checked');
940
- } else {
941
- obj[$this.attr('id')] = $this.val();
942
- }
943
- });
944
-
945
- // Set Option Table values
946
- for (const tableId of tableIds) {
947
- obj[tableId] = table2values(tableId);
948
- }
949
-
950
- // Set g_zonesTargetsOverwrite
951
- // ! Must be after setting the Option Table Values
952
- for (let i = 0; i < obj['tableZones'].length; i++) {
953
-
954
- // get g_zonesTargetsOverwrite value for zone row
955
- const overwriteObject = g_zonesTargetsOverwrite[obj['tableZones'][i]['name']]; // Like {'Hallway.Light':'new val' 'Hallway.Radio':'Radio XYZ'}
956
- if (overwriteObject && !isLikeEmpty(overwriteObject)) {
957
- obj['tableZones'][i]['targetsOverwrite'] = overwriteObject;
958
- } else {
959
- delete obj['tableZones'][i]['targetsOverwrite'];
960
- }
961
-
962
- }
963
-
964
- /*****************************
965
- * Input Validation
966
- * We use sendTo() to use adapter's node.js code for validation.
967
- *****************************/
968
-
969
- let verifyConfigResultObj = undefined;
970
- let errors = [];
971
-
972
- // Adapter must be alive
973
- const aliveStateObj = await getStateAsync(`system.adapter.${adapterNamespace}.alive`);
974
- if (aliveStateObj == null) throw(`'getStateAsync(${adapterNamespace}.alive)' returned error.`);
975
- if (aliveStateObj && aliveStateObj.val) {
976
- // Adapter is alive, so verify the config.
977
- verifyConfigResultObj = await sendToAsync('verifyConfig', obj);
978
- if (verifyConfigResultObj == null) throw(`'sendToAsync('verifyConfig', obj)' returned null`);
979
- if (verifyConfigResultObj.passed) {
980
- console.debug(`Verifying Config: successfully passed.`);
981
- // Low priority (nice to have) enhancement idea: we may want to also update configuration by refreshing all tabs / tables.
982
- // set the altered object
983
- // obj = objResult.obj;
984
- } else {
985
- errors = verifyConfigResultObj.issues;
986
- console.warn(`Verifying Config: failed!`);
987
- }
988
-
989
- } else {
990
- // Adapter is NOT alive
991
- errors = [`Adapter instance ${adapterNamespace} is not running, so we cannot verify the configuration and cannot save your changes. Please turn the adapter instance on. Hint: To not lose your changes, keep this browser window/tab open, open ioBroker in a new browser window/tab, turn the adapter instance on, and try again to save the changes.`];
992
- }
993
-
994
- if(errors.length === 0) {
995
- // Finally, save settings by calling callback function and provide the settings object
996
- callback(obj);
997
- } else {
998
- // Errors occurred, so do not save settings but provide dialog with the errors
999
- let errorHtml = '<ol>\n';
1000
- for (const errorEntry of errors) {
1001
- errorHtml += `<li>${errorEntry}</li>`;
1002
- }
1003
- errorHtml += '\n</ol>';
1004
- // open error dialog
1005
- $('#dialog-save-verification #save-errors').html(errorHtml);
1006
- $('#dialog-save-verification').modal();
1007
- $('#dialog-save-verification').modal('open');
1008
- }
1009
-
1010
- } catch (error) {
1011
- console.error(`[save()] - ${error}`);
1012
- return;
1013
- }
1014
-
1015
-
1016
- }
1017
-
1018
-
1019
- /**
1020
- * Promise Wrapping:
1021
- * async sendTo
1022
- * Mic - 25-Nov-2020
1023
- * @param {string} cmd - Command
1024
- * @param {object} obj - Object
1025
- * @return {Promise<object|null>}
1026
- */
1027
- function sendToAsync(cmd, obj) {
1028
- return new Promise((resolve, reject) => {
1029
- sendTo(adapterNamespace, cmd, obj, (result) => {
1030
- if (result.error) {
1031
- console.error('sendToAsync(): ' + result.error);
1032
- reject(null);
1033
- } else {
1034
- resolve(result);
1035
- }
1036
- });
1037
- });
1038
- }
1039
-
1040
- /**
1041
- * Promise Wrapping:
1042
- * async getState
1043
- * Mic - 01-Dec-2020
1044
- * @param {string} id - state id
1045
- * @return {Promise<object|null>} state object, or null if error
1046
- */
1047
- function getStateAsync(id) {
1048
- return new Promise((resolve, reject) => {
1049
- socket.emit('getState', id, (err, stateObj) => {
1050
- if (err) {
1051
- console.error('getStateAsync(): ' + err);
1052
- reject(null);
1053
- } else {
1054
- resolve(stateObj);
1055
- }
1056
- });
1057
- });
1058
- }
1059
-
1060
-
1061
- /**
1062
- * Update Table Button Icons
1063
- * If 'data-buttons' in table th is not set to a known keyword (like 'edit'), it uses 'add' as materialize icon.
1064
- * We modify this icon by replacing 'add' with an icon of our choice: https://materializecss.com/icons.html
1065
- *
1066
- * @param {string} tableId - Table ID, like "tableTargetDevices"
1067
- * @param {array} iconsConfArr - [{dataButton:'xyz', icon:'search'}, {data-button:'abc', icon:'add', regularSize:true}];
1068
- */
1069
- function updateTableButtonIcons(tableId, iconsConfArr) {
1070
-
1071
- for (const lpIconObj of iconsConfArr) {
1072
- $(`#${tableId} table tbody td a.values-buttons[data-command="${lpIconObj.dataButton}"] i.material-icons:contains('add')`).each(function() {
1073
- const text = $(this).text().replace('add', lpIconObj.icon);
1074
- $(this).text(text);
1075
- });
1076
- if (lpIconObj.regularSize) {
1077
- // replace .btn-small with .btn to change icon to regular size
1078
- const $query = $(`#${tableId} table tbody td a.values-buttons[data-command="${lpIconObj.dataButton}"].btn-small`);
1079
- $query.addClass('btn').removeClass('btn-small');
1080
- }
1081
- }
1082
-
1083
- }
1084
-
1085
-
1086
-
1087
-
1088
- /*************************************************************
1089
- * Table Filter
1090
- * Inspired by: https://github.com/mjansma/LiveSearch/livesearch.js
1091
- * @param {string} id - like 'tableTargetDevices'
1092
- *************************************************************/
1093
- function applyTableFilter(id) {
1094
- $(`div#${id} .table-filter input`).keyup(function() {
1095
- //$(this).keyup(function() {
1096
- const table = $('div#' + id + ' table');
1097
- //Get all table columns
1098
- const children = table.find('td');
1099
- const searchString = $(this).val().toLowerCase();
1100
-
1101
- if (searchString.length < 1) {
1102
-
1103
- $(`div#${id} .table-filter button`).hide(); // hide filter button
1104
- table.find('tr:gt(0)').show(); // show all if search string is too short
1105
- return;
1106
-
1107
- } else {
1108
-
1109
- $(`div#${id} .table-filter button`).show(); // show filter button since we have 2+ chars in filter
1110
-
1111
- //Hide all rows except the table header
1112
- table.find('tr:gt(0)').hide();
1113
-
1114
- //Loop through all table columns
1115
- children.each(function(index, child){
1116
- //If search string matches table column
1117
- let checkFor;
1118
- if (child.firstChild && child.firstChild.firstChild && child.firstChild.firstChild.value) {
1119
- checkFor = child.firstChild.firstChild.value; // we have a drop down
1120
- } else if (!checkFor && child.firstChild && child.firstChild.value && child.firstChild.value != '' && child.firstChild.value != 'on') {
1121
- checkFor = child.firstChild.value;
1122
- }
1123
- if (checkFor && checkFor.toLowerCase().indexOf(searchString) != -1) {
1124
- $(child).closest('tr').show(); //Show table row
1125
- }
1126
- });
1127
- }
1128
-
1129
- });
1130
- }
1131
-
1132
- /**
1133
- * From: selectID.js (node_modules/iobroker.admin/www/lib/js/)
1134
- * Name "dialog-select-member" is important, because for that exist the CSS classes
1135
- * Important to have "admin/img/big-info.png", because this icon will be loaded if no icon found, otherwise we have endless loop
1136
- */
1137
- let selectId;
1138
- function initSelectId (cb) {
1139
- if (selectId) return cb ? cb(selectId) : selectId;
1140
- socket.emit('getObjects', function (err, res) {
1141
- if (!err && res) {
1142
- selectId = $('#dialog-select-member').selectId('init', {
1143
- noMultiselect: true,
1144
- objects: res,
1145
- imgPath: '../../lib/css/fancytree/',
1146
- filter: {type: 'state'},
1147
- name: 'adapter-select-state',
1148
- texts: {
1149
- select: _('Select'),
1150
- cancel: _('Cancel'),
1151
- all: _('All'),
1152
- id: _('ID'),
1153
- name: _('Name'),
1154
- role: _('Role'),
1155
- room: _('Room'),
1156
- value: _('Value'),
1157
- selectid: _('Select state'),
1158
- from: _('From'),
1159
- lc: _('Last changed'),
1160
- ts: _('Time stamp'),
1161
- wait: _('Processing...'),
1162
- ack: _('Acknowledged'),
1163
- selectAll: _('Select all'),
1164
- unselectAll: _('Deselect all'),
1165
- invertSelection: _('Invert selection')
1166
- },
1167
- columns: ['image', 'name', 'role', 'room']
1168
- });
1169
- cb && cb(selectId);
1170
- }
1171
- });
1172
- }
1173
-
1174
- /**
1175
- * Opens the dialog for state selection.
1176
- * Using selectID.js (node_modules/iobroker.admin/www/lib/js/)
1177
- * It monitors a button for a click, and writes the selected state into a field.
1178
- *
1179
- * @param {string} tableId - The id of the table, like 'tableTargetDevices'
1180
- * @param {string} dataCommand - Name of [data-buttons="edit1"] of the <th>. so like 'edit1'.
1181
- * If you use multiple buttons per table row, use like 'edit1', 'edit2' for 'data-buttons=' in <th>
1182
- * @param {string} targetField - The target field, like 'onState' (of data-name="onState")
1183
- */
1184
- function statePathPopupSelection(tableId, dataCommand, targetField) {
1185
-
1186
- const queryResult = $(`#${tableId} a.values-buttons[data-command="${dataCommand}"]`);
1187
- queryResult.on('click', function() {
1188
- const id = $(this).data('index');
1189
- initSelectId(function (sid) {
1190
- sid.selectId('show', $(`#${tableId} .values-input[data-name="${targetField}"][data-index="${id}"]`).val(), function (statePath) {
1191
- if (statePath) {
1192
- // We have a selected state, so let's fill the target field
1193
- $(`#${tableId} .values-input[data-name="${targetField}"][data-index="${id}"]`).val(statePath).trigger('change');
1194
- }
1195
- });
1196
- });
1197
- });
1198
-
1199
- }
1200
-
1201
-
1202
-
1203
- /**
1204
- * Initializes a dialog (materialize Modal)
1205
- *
1206
- * @source iQontrol adapter
1207
- *
1208
- * @param {string} id - id of Modal, like 'dialog-select-settings'
1209
- * @param {*} callback - callback function.
1210
- */
1211
- function initDialog(id, callback) {
1212
- const $dialog = $('#' + id);
1213
- if (!$dialog.data('isInitialized')) {
1214
- $dialog.data('isInitialized', true);
1215
- $dialog.modal({
1216
- dismissible: false
1217
- });
1218
-
1219
- $dialog.find('.btn-set').on('click', function () {
1220
- const $dialog = $('#' + $(this).data('dialogId'));
1221
- const callback = $dialog.data('callback');
1222
- if (typeof callback === 'function') callback();
1223
- $dialog.data('callback', null);
1224
- });
1225
- }
1226
- $dialog.find('.btn-set').data('dialogId', id);
1227
- $dialog.data('callback', callback);
1228
- }
1229
-
1230
-
1231
- /**
1232
- * To be called in load() function of index_m.html / index_m.js
1233
- * @param {string} fancytreeId - like 'fancytree-select-settings' for #fancytree-select-settings
1234
- */
1235
- function fancytreeLoad(fancytreeId) {
1236
-
1237
- $(`#${fancytreeId}`).fancytree({
1238
- checkbox: true,
1239
- checkboxAutoHide: undefined, // Display check boxes on hover only
1240
- extensions: ['filter', 'edit'],
1241
- quicksearch: true,
1242
- filter: {
1243
- autoApply: true, // Re-apply last filter if lazy data is loaded
1244
- autoExpand: true, // Expand all branches that contain matches while filtered
1245
- counter: true, // Show a badge with number of matching child nodes near parent icons
1246
- fuzzy: false, // Match single characters in order, e.g. 'fb' will match 'FooBar'
1247
- hideExpandedCounter: true, // Hide counter badge if parent is expanded
1248
- hideExpanders: false, // Hide expanders if all child nodes are hidden by filter
1249
- highlight: true, // Highlight matches by wrapping inside <mark> tags
1250
- leavesOnly: false, // Match end nodes only
1251
- nodata: false, // Display a 'no data' status node if result is empty
1252
- mode: 'hide' // 'dimm' to gray out unmatched nodes, 'hide' to remove unmatched node instead)
1253
- },
1254
-
1255
- edit: {
1256
- // Available options with their default:
1257
- adjustWidthOfs: 4, // null: don't adjust input size to content
1258
- inputCss: { minWidth: '3em' },
1259
- triggerStart: ['f2', 'dblclick', 'shift+click', 'mac+enter'],
1260
- beforeEdit: function(event, data){
1261
- if (data.node.children) return false; // Return false to prevent edit mode for folders (i.e. if nodes having children)
1262
- if (!data.node.data.overwriteTargets) return false; // Go out if we do not want to overwrite / set new target values
1263
- },
1264
- edit: function(event, data){ // Editor opened (available as data.input)
1265
-
1266
- // Some additional HTML/CSS
1267
- $('input.fancytree-edit-input').addClass('browser-default');
1268
- $('input.fancytree-edit-input').before(`<span>${data.node.key.split('.').pop()} - ${_('overwrite options')}: {</span>`);
1269
- $('input.fancytree-edit-input').after(`<span>}</span>`);
1270
-
1271
- const newVal = data.input.val();
1272
- const matches = newVal.match(/{(.+)}$/);
1273
- if (matches && matches[1] && matches[1].length > 0) {
1274
- $('input.fancytree-edit-input').val(matches[1]);
1275
- } else {
1276
- $('input.fancytree-edit-input').val('');
1277
- }
1278
- },
1279
-
1280
- save: $.noop,
1281
- beforeClose: $.noop,
1282
-
1283
- // We handle all in close.
1284
- close: function(event, data) {
1285
- const key = data.node.key; // key, like "Bath.Lights.Mirror Light"
1286
- const nodeTitle = key.split('.').pop(); // like 'Mirror Light'
1287
- const newVal = data.node.title; // the new value which the user entered
1288
- if (!newVal || newVal.length < 1) {
1289
- data.node.setTitle(nodeTitle);
1290
- } else if (newVal.startsWith(nodeTitle)) {
1291
- // to avoid result like Mirror Light {Mirror Light}
1292
- data.node.setTitle(nodeTitle);
1293
- } else {
1294
- // Set node title like 'Mirror Light {20%}'
1295
- data.node.setTitle(`${nodeTitle} {${newVal}}`);
1296
- }
1297
- },
1298
-
1299
- },
1300
-
1301
-
1302
- selectMode: 2, // 1:single, 2:multi(limited to actual selected items), 3:multi-hierarchy (will also select parent items)
1303
- source: [], // We set this later
1304
-
1305
- activate: function(event, data) {
1306
- $('#statusLine').text(event.type + ': ' + data.node);
1307
- },
1308
-
1309
- strings: {
1310
- //loading: 'Loading&#8230;',
1311
- //loadError: 'Load error!',
1312
- //moreData: 'More&#8230;',
1313
- noData: 'No hits',
1314
- }
1315
-
1316
- });
1317
-
1318
-
1319
-
1320
- /**********************
1321
- * Event handlers
1322
- **********************/
1323
- const tree = $.ui.fancytree.getTree(`#${fancytreeId}`);
1324
-
1325
- //https://wwwendt.de/tech/fancytree/doc/jsdoc/jquery.fancytree.edit.js.html
1326
-
1327
- /**
1328
- * Collapse/Expand All - Event Handler
1329
- */
1330
- $('a#fancy-expand-all').click(function() {
1331
- tree.visit(function(node){ node.setExpanded(); });
1332
- });
1333
- $('a#fancy-collapse-all').click(function() {
1334
- tree.visit(function(node){ node.setExpanded(false); });
1335
- });
1336
-
1337
- /**
1338
- * Search - Event Handler
1339
- */
1340
- $('input[name=search]').on('keyup', function(e){
1341
-
1342
- const tree = $.ui.fancytree.getTree();
1343
- const match = $(this).val();
1344
-
1345
- if(e && e.which === $.ui.keyCode.ESCAPE || $.trim(match) === ''){
1346
- $('button#btnResetSearch').click();
1347
- return;
1348
- }
1349
-
1350
- // Get matches
1351
- const filterFunc = tree.filterBranches; // filterBranches = match whole branches, filterNodes = nodes only
1352
- const n = filterFunc.call(tree, match);
1353
- $(`label[for='fancy-filter-input']`).text(`(${n} Treffer)`);
1354
-
1355
- // Enable "reset search" button
1356
- $('button#btnResetSearch').attr('disabled', false);
1357
-
1358
-
1359
- }).focus();
1360
-
1361
- $('button#btnResetSearch').click(function(){
1362
- $('input[name=search]').val('');
1363
- $(`label[for='fancy-filter-input']`).text('');
1364
- tree.clearFilter();
1365
- $('button#btnResetSearch').attr('disabled', true);
1366
- });
1367
-
1368
- $('fieldset input:checkbox').change(function() {
1369
- const id = $(this).attr('id');
1370
- const flag = $(this).is(':checked');
1371
-
1372
- // Some options can only be set with general filter options (not method args):
1373
- switch( id ){
1374
- case 'counter':
1375
- case 'hideExpandedCounter':
1376
- tree.options.filter[id] = flag;
1377
- break;
1378
- }
1379
- tree.clearFilter();
1380
- $('input[name=search]').keyup();
1381
- });
1382
- }
1383
-
1384
- /**
1385
- * tableTargetEnums: Get lists of enum room and function names to set to drop down (multiple select) fields for selection
1386
- * @param {string} enumType - 'rooms' for rooms, and 'functions' for functions
1387
- * @param {function} callback - callback function
1388
- * @return {object} callback with array of enum room names or enum function names, or null if nothing found
1389
- */
1390
- function getTargetEnums(enumType, callback) {
1391
-
1392
- getEnums(enumType, (error, enumObj)=> {
1393
- if (!error && enumObj) {
1394
- const enumIds = [];
1395
- for (const id in enumObj) {
1396
- const nameObj = enumObj[id].common.name; // either string like 'Living room' or {en:'Living room', de:'Wohnzimmer', ...}
1397
- if (typeof nameObj === 'string') {
1398
- enumIds.push(nameObj);
1399
- } else if (typeof nameObj === 'object') {
1400
- enumIds.push(nameObj[systemLang]);
1401
- } else {
1402
- console.warn(`Getting enum ${(enumType=='rooms'?'room':'function')} name for '${id}': type for name must be string or object, but is '${typeof nameObj}'.`);
1403
- }
1404
- }
1405
- if (!isLikeEmpty(enumIds)) {
1406
- return callback(enumIds.sort());
1407
- } else {
1408
- console.warn(`No enum ${enumType} found.`);
1409
- return callback(null);
1410
- }
1411
- } else {
1412
- if (error) {
1413
- console.error(`getTargetEnums(${enumType}) - error: ${error}`);
1414
- return callback(null);
1415
- } else {
1416
- console.error(`getTargetEnums(${enumType}) - blank object was returned, so could not get ${enumType}.`);
1417
- return callback(null);
1418
- }
1419
- }
1420
- });
1421
-
1422
- }
1423
-
1424
-
1425
- /**
1426
- * Converts array of dotted strings to FancyTree source format.
1427
- *
1428
- * @param {array} allDottedStrings - array of ALL dotted strings, like: ['Bath.Radio.on', 'Bath.Light', 'Hallway']
1429
- * @param {array} selectedDottedStrings - array of SELECTED dotted strings, like: ['Hallway']
1430
- * @param {string} [zoneName=undefined] - set Zone Name if you want to add target values.
1431
- * @return {array|null} Array for FancyTree source - https://github.com/mar10/fancytree/wiki/TutorialLoadData
1432
- */
1433
- function convertToFancySource(allDottedStrings, selectedDottedStrings, zoneName=undefined) {
1434
-
1435
- try {
1436
-
1437
- /**
1438
- * First: Prepare array of objects, example:
1439
- * [
1440
- * {"key":"Bath.Radio.on","title":"on", , parent:"Bath.Radio", selected:false},
1441
- * {"key":"Bath.Radio","title":"Radio", parent:"Bath"},
1442
- * {"key":"Bath","title":"Bath"},
1443
- * {"key":"Bath.Light","title":"Light", parent:"Bath", selected:false},
1444
- * {"key":"Hallway","title":"Hallway", selected:false}
1445
- * ]
1446
- */
1447
- const objectArray = [];
1448
-
1449
- for (const lpDottedStr of allDottedStrings) {
1450
-
1451
- // Like {'Hallway.Light':'new val' 'Hallway.Radio':'Radio XYZ'}
1452
- const targetsToOverwrite = (zoneName) ? g_zonesTargetsOverwrite[zoneName] : undefined;
1453
-
1454
- const dottedArr = lpDottedStr.split('.');
1455
- for (let i = dottedArr.length-1; i > -1; i--) {
1456
- const resObj = {};
1457
-
1458
- // get id of looped value, like "Bath.Radio", if i==1, or "Bath.Radio.on" of i==2
1459
- let resId = '';
1460
- for (let k = 0; k <= i; k++) {
1461
- if (k > 0) resId = resId + '.';
1462
- resId = resId + dottedArr[k];
1463
- }
1464
- resObj.key = resId;
1465
-
1466
- // Skip if key value is already in any array object
1467
- if (objectArray.some( (elem)=> elem.key === resId)) continue;
1468
-
1469
- // Title - 'Bath.Radio.on' -> 'on' if i=2
1470
- resObj.title = dottedArr[i];
1471
-
1472
-
1473
- // If overwrite targets: add flag to easily identify
1474
- if (zoneName) {
1475
- resObj.overwriteTargets = true; // to easily identify.
1476
- }
1477
-
1478
- // If overwrite targets: Change the node title of each end node accordingly
1479
- if (zoneName && (i == dottedArr.length -1)) {
1480
- if (targetsToOverwrite && !isLikeEmpty(targetsToOverwrite[lpDottedStr])) {
1481
- resObj.title = `${resObj.title} {${targetsToOverwrite[lpDottedStr]}}`;
1482
- }
1483
- }
1484
-
1485
- // Always expand all nodes if selected by adding "expanded:true" to selected ones.
1486
- if (selectedDottedStrings.indexOf(lpDottedStr) != -1) {
1487
- resObj.expanded = true;
1488
- }
1489
-
1490
- // Check box for selected ones, but only to end nodes (last level)
1491
- if (i == dottedArr.length -1) {
1492
- resObj.selected = (selectedDottedStrings.indexOf(lpDottedStr) != -1) ? true : false;
1493
- } else {
1494
- resObj.checkbox = false; // https://wwwendt.de/tech/fancytree/demo/sample-select.html
1495
- }
1496
-
1497
- // Add parent id
1498
- if (i > 0) {
1499
- resObj.parent = resObj.key.substr(0, resObj.key.lastIndexOf('.')); // 'Bath.Radio' for 'Bath.Radio.on'
1500
- }
1501
-
1502
- objectArray.push(resObj);
1503
-
1504
- }
1505
- }
1506
-
1507
- /**
1508
- * Next, convert to final FancyTree source.
1509
- * @source (modified accordingly) - https://github.com/mar10/fancytree/wiki/TutorialLoadData#howto-load-data-from-a-flat-parent-referencing-list
1510
- */
1511
-
1512
- const nodeMap = {};
1513
-
1514
-
1515
- // Pass 1: store all tasks in reference map
1516
- for(const lpVal of objectArray) {
1517
- nodeMap[lpVal.key] = lpVal;
1518
- }
1519
-
1520
-
1521
- // Pass 2: adjust fields and fix child structure
1522
- let parent;
1523
- let mappedArray = objectArray.map( function (value) {
1524
-
1525
- // Check if value is a child node
1526
- if( value.parent ) {
1527
- // add value to `children` array of parent node
1528
- parent = nodeMap[value.parent];
1529
- if (!parent) throw('Unexpected error: No parent found.');
1530
- parent.folder = true;
1531
- if(parent.children ) {
1532
- parent.children.push(value);
1533
- } else {
1534
- parent.children = [value];
1535
- }
1536
- return null; // Remove value from childList
1537
- }
1538
- return value; // Keep top-level nodes
1539
- });
1540
- mappedArray = mappedArray.filter(val => val != null);
1541
-
1542
- // Pass 3: sort children by 'title'
1543
- for(const lpVal of mappedArray) {
1544
- if( lpVal && lpVal.children && lpVal.children.length > 1 ) {
1545
- lpVal.children.sort(function(a, b){
1546
- return ((a.title < b.title) ? -1 : ((a.title > b.title) ? 1 : 0));
1547
- });
1548
- }
1549
- }
1550
- return mappedArray;
1551
-
1552
-
1553
- } catch (error) {
1554
- console.error(`[convertToFancySource] - ${error}`);
1555
- return null;
1556
- }
1557
-
1558
- }
1559
-
1560
-
1561
-
1562
- /*
1563
- ██████  ███████ ███  ██ ███████ ██████  ██  ██████  ██ ███████ 
1564
- ██       ██      ████  ██ ██      ██   ██ ██ ██       ██ ██      
1565
- ██  ███ █████  ██ ██  ██ █████  ██████  ██ ██  ██ ███████ 
1566
- ██  ██ ██     ██  ██ ██ ██     ██   ██ ██ ██  ██ ██      ██ 
1567
-  ██████  ███████ ██   ████ ███████ ██  ██ ██  ██████   █████  ███████ 
1568
- Generic JS Functions
1569
- */
1570
-
1571
-
1572
- /**
1573
- * Checks if 2 arrays have the same values
1574
- * [2, 4] and [4, 2] is considered equal
1575
- *
1576
- * @param {array} arr1 - first array
1577
- * @param {array} arr2 - second array
1578
- * @return {boolean} - true or false
1579
- */
1580
- function arraysEqual(arr1, arr2) {
1581
-
1582
- if (!Array.isArray(arr1) || ! Array.isArray(arr2) || arr1.length !== arr2.length) {
1583
- return false;
1584
- }
1585
-
1586
- const fArr1 = arr1.concat().sort();
1587
- const fArr2 = arr2.concat().sort();
1588
-
1589
- for (let i = 0; i < fArr1.length; i++) {
1590
- if (fArr1[i] !== fArr2[i]) {
1591
- return false;
1592
- }
1593
- }
1594
-
1595
- return true;
1596
-
1597
- }
1598
-
1599
- /**
1600
- * Get (all) options of a Select dropdown
1601
- * https://stackoverflow.com/a/7760197
1602
- * @param {string} jQuery - the jQuery string, like '#selectBox'
1603
- * @param {boolean} [all=false] - true: get all option items, false: just get selected option items
1604
- *
1605
- */
1606
- function getSelectOptions(jQuery, all=false) {
1607
- if (!all) {
1608
- return $(jQuery).val();
1609
- } else {
1610
- const options = $(`${jQuery} option`);
1611
- const values = $.map(options, function(option) {
1612
- return option.value;
1613
- });
1614
- return values;
1615
- }
1616
- }
1617
-
1618
-
1619
- /**
1620
- * Checks if Array or String is not undefined, null or empty.
1621
- * Array, object, or string containing just white spaces or >'< or >"< or >[< or >]< is considered empty
1622
- * 18-Jun-2020: added check for { and } to also catch empty objects.
1623
- * 08-Sep-2019: added check for [ and ] to also catch arrays with empty strings.
1624
- * @param {any} inputVar Input Array or String, Number, etc.
1625
- * @return {boolean} True if it is undefined/null/empty, false if it contains value(s)
1626
- */
1627
- function isLikeEmpty(inputVar) {
1628
- if (typeof inputVar !== 'undefined' && inputVar !== null) {
1629
- let strTemp = JSON.stringify(inputVar);
1630
- strTemp = strTemp.replace(/\s+/g, ''); // remove all white spaces
1631
- strTemp = strTemp.replace(/"+/g, ''); // remove all >"<
1632
- strTemp = strTemp.replace(/'+/g, ''); // remove all >'<
1633
- strTemp = strTemp.replace(/\[+/g, ''); // remove all >[<
1634
- strTemp = strTemp.replace(/\]+/g, ''); // remove all >]<
1635
- strTemp = strTemp.replace(/\{+/g, ''); // remove all >{<
1636
- strTemp = strTemp.replace(/\}+/g, ''); // remove all >}<
1637
- if (strTemp !== '') {
1638
- return false;
1639
- } else {
1640
- return true;
1641
- }
1642
- } else {
1643
- return true;
1644
- }
1645
- }
1646
-
1647
- /**
1648
- * Checks if a file exists
1649
- * Source: https://stackoverflow.com/a/58344215
1650
- * @param url {string} path to file
1651
- * @return {boolean} true if file exists, false if not
1652
- */
1653
- function fileExists(url) {
1654
- const http = new XMLHttpRequest();
1655
- http.open('HEAD', url, false);
1656
- http.send();
1657
- return http.status!=404;
1658
- }
1659
-