iobroker.smartcontrol 2.0.1 → 2.2.0

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