-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
form.js
4838 lines (4239 loc) · 145 KB
/
form.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
'require ui';
'require uci';
'require rpc';
'require dom';
'require baseclass';
var scope = this;
var callSessionAccess = rpc.declare({
object: 'session',
method: 'access',
params: [ 'scope', 'object', 'function' ],
expect: { 'access': false }
});
var CBIJSONConfig = baseclass.extend({
__init__: function(data) {
data = Object.assign({}, data);
this.data = {};
var num_sections = 0,
section_ids = [];
for (var sectiontype in data) {
if (!data.hasOwnProperty(sectiontype))
continue;
if (Array.isArray(data[sectiontype])) {
for (var i = 0, index = 0; i < data[sectiontype].length; i++) {
var item = data[sectiontype][i],
anonymous, name;
if (!L.isObject(item))
continue;
if (typeof(item['.name']) == 'string') {
name = item['.name'];
anonymous = false;
}
else {
name = sectiontype + num_sections;
anonymous = true;
}
if (!this.data.hasOwnProperty(name))
section_ids.push(name);
this.data[name] = Object.assign(item, {
'.index': num_sections++,
'.anonymous': anonymous,
'.name': name,
'.type': sectiontype
});
}
}
else if (L.isObject(data[sectiontype])) {
this.data[sectiontype] = Object.assign(data[sectiontype], {
'.anonymous': false,
'.name': sectiontype,
'.type': sectiontype
});
section_ids.push(sectiontype);
num_sections++;
}
}
section_ids.sort(L.bind(function(a, b) {
var indexA = (this.data[a]['.index'] != null) ? +this.data[a]['.index'] : 9999,
indexB = (this.data[b]['.index'] != null) ? +this.data[b]['.index'] : 9999;
if (indexA != indexB)
return (indexA - indexB);
return L.naturalCompare(a, b);
}, this));
for (var i = 0; i < section_ids.length; i++)
this.data[section_ids[i]]['.index'] = i;
},
load: function() {
return Promise.resolve(this.data);
},
save: function() {
return Promise.resolve();
},
get: function(config, section, option) {
if (section == null)
return null;
if (option == null)
return this.data[section];
if (!this.data.hasOwnProperty(section))
return null;
var value = this.data[section][option];
if (Array.isArray(value))
return value;
if (value != null)
return String(value);
return null;
},
set: function(config, section, option, value) {
if (section == null || option == null || option.charAt(0) == '.')
return;
if (!this.data.hasOwnProperty(section))
return;
if (value == null)
delete this.data[section][option];
else if (Array.isArray(value))
this.data[section][option] = value;
else
this.data[section][option] = String(value);
},
unset: function(config, section, option) {
return this.set(config, section, option, null);
},
sections: function(config, sectiontype, callback) {
var rv = [];
for (var section_id in this.data)
if (sectiontype == null || this.data[section_id]['.type'] == sectiontype)
rv.push(this.data[section_id]);
rv.sort(function(a, b) { return a['.index'] - b['.index'] });
if (typeof(callback) == 'function')
for (var i = 0; i < rv.length; i++)
callback.call(this, rv[i], rv[i]['.name']);
return rv;
},
add: function(config, sectiontype, sectionname) {
var num_sections_type = 0, next_index = 0;
for (var name in this.data) {
num_sections_type += (this.data[name]['.type'] == sectiontype);
next_index = Math.max(next_index, this.data[name]['.index']);
}
var section_id = sectionname || sectiontype + num_sections_type;
if (!this.data.hasOwnProperty(section_id)) {
this.data[section_id] = {
'.name': section_id,
'.type': sectiontype,
'.anonymous': (sectionname == null),
'.index': next_index + 1
};
}
return section_id;
},
remove: function(config, section) {
if (this.data.hasOwnProperty(section))
delete this.data[section];
},
resolveSID: function(config, section_id) {
return section_id;
},
move: function(config, section_id1, section_id2, after) {
return uci.move.apply(this, [config, section_id1, section_id2, after]);
}
});
/**
* @class AbstractElement
* @memberof LuCI.form
* @hideconstructor
* @classdesc
*
* The `AbstractElement` class serves as abstract base for the different form
* elements implemented by `LuCI.form`. It provides the common logic for
* loading and rendering values, for nesting elements and for defining common
* properties.
*
* This class is private and not directly accessible by user code.
*/
var CBIAbstractElement = baseclass.extend(/** @lends LuCI.form.AbstractElement.prototype */ {
__init__: function(title, description) {
this.title = title || '';
this.description = description || '';
this.children = [];
},
/**
* Add another form element as children to this element.
*
* @param {AbstractElement} obj
* The form element to add.
*/
append: function(obj) {
this.children.push(obj);
},
/**
* Parse this elements form input.
*
* The `parse()` function recursively walks the form element tree and
* triggers input value reading and validation for each encountered element.
*
* Elements which are hidden due to unsatisfied dependencies are skipped.
*
* @returns {Promise<void>}
* Returns a promise resolving once this element's value and the values of
* all child elements have been parsed. The returned promise is rejected
* if any parsed values are not meeting the validation constraints of their
* respective elements.
*/
parse: function() {
var args = arguments;
this.children.forEach(function(child) {
child.parse.apply(child, args);
});
},
/**
* Render the form element.
*
* The `render()` function recursively walks the form element tree and
* renders the markup for each element, returning the assembled DOM tree.
*
* @abstract
* @returns {Node|Promise<Node>}
* May return a DOM Node or a promise resolving to a DOM node containing
* the form element's markup, including the markup of any child elements.
*/
render: function() {
L.error('InternalError', 'Not implemented');
},
/** @private */
loadChildren: function(/* ... */) {
var tasks = [];
if (Array.isArray(this.children))
for (var i = 0; i < this.children.length; i++)
if (!this.children[i].disable)
tasks.push(this.children[i].load.apply(this.children[i], arguments));
return Promise.all(tasks);
},
/** @private */
renderChildren: function(tab_name /*, ... */) {
var tasks = [],
index = 0;
if (Array.isArray(this.children))
for (var i = 0; i < this.children.length; i++)
if (tab_name === null || this.children[i].tab === tab_name)
if (!this.children[i].disable)
tasks.push(this.children[i].render.apply(
this.children[i], this.varargs(arguments, 1, index++)));
return Promise.all(tasks);
},
/**
* Strip any HTML tags from the given input string.
*
* @param {string} s
* The input string to clean.
*
* @returns {string}
* The cleaned input string with HTML tags removed.
*/
stripTags: function(s) {
if (typeof(s) == 'string' && !s.match(/[<>]/))
return s;
var x = dom.elem(s) ? s : dom.parse('<div>' + s + '</div>');
x.querySelectorAll('br').forEach(function(br) {
x.replaceChild(document.createTextNode('\n'), br);
});
return (x.textContent || x.innerText || '').replace(/([ \t]*\n)+/g, '\n');
},
/**
* Format the given named property as title string.
*
* This function looks up the given named property and formats its value
* suitable for use as element caption or description string. It also
* strips any HTML tags from the result.
*
* If the property value is a string, it is passed to `String.format()`
* along with any additional parameters passed to `titleFn()`.
*
* If the property value is a function, it is invoked with any additional
* `titleFn()` parameters as arguments and the obtained return value is
* converted to a string.
*
* In all other cases, `null` is returned.
*
* @param {string} property
* The name of the element property to use.
*
* @param {...*} fmt_args
* Extra values to format the title string with.
*
* @returns {string|null}
* The formatted title string or `null` if the property did not exist or
* was neither a string nor a function.
*/
titleFn: function(attr /*, ... */) {
var s = null;
if (typeof(this[attr]) == 'function')
s = this[attr].apply(this, this.varargs(arguments, 1));
else if (typeof(this[attr]) == 'string')
s = (arguments.length > 1) ? ''.format.apply(this[attr], this.varargs(arguments, 1)) : this[attr];
if (s != null)
s = this.stripTags(String(s)).trim();
if (s == null || s == '')
return null;
return s;
}
});
/**
* @constructor Map
* @memberof LuCI.form
* @augments LuCI.form.AbstractElement
*
* @classdesc
*
* The `Map` class represents one complete form. A form usually maps one UCI
* configuration file and is divided into multiple sections containing multiple
* fields each.
*
* It serves as main entry point into the `LuCI.form` for typical view code.
*
* @param {string} config
* The UCI configuration to map. It is automatically loaded along when the
* resulting map instance.
*
* @param {string} [title]
* The title caption of the form. A form title is usually rendered as separate
* headline element before the actual form contents. If omitted, the
* corresponding headline element will not be rendered.
*
* @param {string} [description]
* The description text of the form which is usually rendered as text
* paragraph below the form title and before the actual form contents.
* If omitted, the corresponding paragraph element will not be rendered.
*/
var CBIMap = CBIAbstractElement.extend(/** @lends LuCI.form.Map.prototype */ {
__init__: function(config /*, ... */) {
this.super('__init__', this.varargs(arguments, 1));
this.config = config;
this.parsechain = [ config ];
this.data = uci;
},
/**
* Toggle readonly state of the form.
*
* If set to `true`, the Map instance is marked readonly and any form
* option elements added to it will inherit the readonly state.
*
* If left unset, the Map will test the access permission of the primary
* uci configuration upon loading and mark the form readonly if no write
* permissions are granted.
*
* @name LuCI.form.Map.prototype#readonly
* @type boolean
*/
/**
* Find all DOM nodes within this Map which match the given search
* parameters. This function is essentially a convenience wrapper around
* `querySelectorAll()`.
*
* This function is sensitive to the amount of arguments passed to it;
* if only one argument is specified, it is used as selector-expression
* as-is. When two arguments are passed, the first argument is treated
* as attribute name, the second one as attribute value to match.
*
* As an example, `map.findElements('input')` would find all `<input>`
* nodes while `map.findElements('type', 'text')` would find any DOM node
* with a `type="text"` attribute.
*
* @param {string} selector_or_attrname
* If invoked with only one parameter, this argument is a
* `querySelectorAll()` compatible selector expression. If invoked with
* two parameters, this argument is the attribute name to filter for.
*
* @param {string} [attrvalue]
* In case the function is invoked with two parameters, this argument
* specifies the attribute value to match.
*
* @throws {InternalError}
* Throws an `InternalError` if more than two function parameters are
* passed.
*
* @returns {NodeList}
* Returns a (possibly empty) DOM `NodeList` containing the found DOM nodes.
*/
findElements: function(/* ... */) {
var q = null;
if (arguments.length == 1)
q = arguments[0];
else if (arguments.length == 2)
q = '[%s="%s"]'.format(arguments[0], arguments[1]);
else
L.error('InternalError', 'Expecting one or two arguments to findElements()');
return this.root.querySelectorAll(q);
},
/**
* Find the first DOM node within this Map which matches the given search
* parameters. This function is essentially a convenience wrapper around
* `findElements()` which only returns the first found node.
*
* This function is sensitive to the amount of arguments passed to it;
* if only one argument is specified, it is used as selector-expression
* as-is. When two arguments are passed, the first argument is treated
* as attribute name, the second one as attribute value to match.
*
* As an example, `map.findElement('input')` would find the first `<input>`
* node while `map.findElement('type', 'text')` would find the first DOM
* node with a `type="text"` attribute.
*
* @param {string} selector_or_attrname
* If invoked with only one parameter, this argument is a `querySelector()`
* compatible selector expression. If invoked with two parameters, this
* argument is the attribute name to filter for.
*
* @param {string} [attrvalue]
* In case the function is invoked with two parameters, this argument
* specifies the attribute value to match.
*
* @throws {InternalError}
* Throws an `InternalError` if more than two function parameters are
* passed.
*
* @returns {Node|null}
* Returns the first found DOM node or `null` if no element matched.
*/
findElement: function(/* ... */) {
var res = this.findElements.apply(this, arguments);
return res.length ? res[0] : null;
},
/**
* Tie another UCI configuration to the map.
*
* By default, a map instance will only load the UCI configuration file
* specified in the constructor but sometimes access to values from
* further configuration files is required. This function allows for such
* use cases by registering further UCI configuration files which are
* needed by the map.
*
* @param {string} config
* The additional UCI configuration file to tie to the map. If the given
* config already is in the list of required files, it will be ignored.
*/
chain: function(config) {
if (this.parsechain.indexOf(config) == -1)
this.parsechain.push(config);
},
/**
* Add a configuration section to the map.
*
* LuCI forms follow the structure of the underlying UCI configurations,
* means that a map, which represents a single UCI configuration, is
* divided into multiple sections which in turn contain an arbitrary
* number of options.
*
* While UCI itself only knows two kinds of sections - named and anonymous
* ones - the form class offers various flavors of form section elements
* to present configuration sections in different ways. Refer to the
* documentation of the different section classes for details.
*
* @param {LuCI.form.AbstractSection} sectionclass
* The section class to use for rendering the configuration section.
* Note that this value must be the class itself, not a class instance
* obtained from calling `new`. It must also be a class derived from
* `LuCI.form.AbstractSection`.
*
* @param {...string} classargs
* Additional arguments which are passed as-is to the constructor of the
* given section class. Refer to the class specific constructor
* documentation for details.
*
* @returns {LuCI.form.AbstractSection}
* Returns the instantiated section class instance.
*/
section: function(cbiClass /*, ... */) {
if (!CBIAbstractSection.isSubclass(cbiClass))
L.error('TypeError', 'Class must be a descendent of CBIAbstractSection');
var obj = cbiClass.instantiate(this.varargs(arguments, 1, this));
this.append(obj);
return obj;
},
/**
* Load the configuration covered by this map.
*
* The `load()` function first loads all referenced UCI configurations,
* then it recursively walks the form element tree and invokes the
* load function of each child element.
*
* @returns {Promise<void>}
* Returns a promise resolving once the entire form completed loading all
* data. The promise may reject with an error if any configuration failed
* to load or if any of the child elements load functions rejected with
* an error.
*/
load: function() {
var doCheckACL = (!(this instanceof CBIJSONMap) && this.readonly == null),
loadTasks = [ doCheckACL ? callSessionAccess('uci', this.config, 'write') : true ],
configs = this.parsechain || [ this.config ];
loadTasks.push.apply(loadTasks, configs.map(L.bind(function(config, i) {
return i ? L.resolveDefault(this.data.load(config)) : this.data.load(config);
}, this)));
return Promise.all(loadTasks).then(L.bind(function(res) {
if (res[0] === false)
this.readonly = true;
return this.loadChildren();
}, this));
},
/**
* Parse the form input values.
*
* The `parse()` function recursively walks the form element tree and
* triggers input value reading and validation for each child element.
*
* Elements which are hidden due to unsatisfied dependencies are skipped.
*
* @returns {Promise<void>}
* Returns a promise resolving once the entire form completed parsing all
* input values. The returned promise is rejected if any parsed values are
* not meeting the validation constraints of their respective elements.
*/
parse: function() {
var tasks = [];
if (Array.isArray(this.children))
for (var i = 0; i < this.children.length; i++)
tasks.push(this.children[i].parse());
return Promise.all(tasks);
},
/**
* Save the form input values.
*
* This function parses the current form, saves the resulting UCI changes,
* reloads the UCI configuration data and redraws the form elements.
*
* @param {function} [cb]
* An optional callback function that is invoked after the form is parsed
* but before the changed UCI data is saved. This is useful to perform
* additional data manipulation steps before saving the changes.
*
* @param {boolean} [silent=false]
* If set to `true`, trigger an alert message to the user in case saving
* the form data failures. Otherwise fail silently.
*
* @returns {Promise<void>}
* Returns a promise resolving once the entire save operation is complete.
* The returned promise is rejected if any step of the save operation
* failed.
*/
save: function(cb, silent) {
this.checkDepends();
return this.parse()
.then(cb)
.then(this.data.save.bind(this.data))
.then(this.load.bind(this))
.catch(function(e) {
if (!silent) {
ui.showModal(_('Save error'), [
E('p', {}, [ _('An error occurred while saving the form:') ]),
E('p', {}, [ E('em', { 'style': 'white-space:pre-wrap' }, [ e.message ]) ]),
E('div', { 'class': 'right' }, [
E('button', { 'class': 'cbi-button', 'click': ui.hideModal }, [ _('Dismiss') ])
])
]);
}
return Promise.reject(e);
}).then(this.renderContents.bind(this));
},
/**
* Reset the form by re-rendering its contents. This will revert all
* unsaved user inputs to their initial form state.
*
* @returns {Promise<Node>}
* Returns a promise resolving to the toplevel form DOM node once the
* re-rendering is complete.
*/
reset: function() {
return this.renderContents();
},
/**
* Render the form markup.
*
* @returns {Promise<Node>}
* Returns a promise resolving to the toplevel form DOM node once the
* rendering is complete.
*/
render: function() {
return this.load().then(this.renderContents.bind(this));
},
/** @private */
renderContents: function() {
var mapEl = this.root || (this.root = E('div', {
'id': 'cbi-%s'.format(this.config),
'class': 'cbi-map',
'cbi-dependency-check': L.bind(this.checkDepends, this)
}));
dom.bindClassInstance(mapEl, this);
return this.renderChildren(null).then(L.bind(function(nodes) {
var initialRender = !mapEl.firstChild;
dom.content(mapEl, null);
if (this.title != null && this.title != '')
mapEl.appendChild(E('h2', { 'name': 'content' }, this.title));
if (this.description != null && this.description != '')
mapEl.appendChild(E('div', { 'class': 'cbi-map-descr' }, this.description));
if (this.tabbed)
dom.append(mapEl, E('div', { 'class': 'cbi-map-tabbed' }, nodes));
else
dom.append(mapEl, nodes);
if (!initialRender) {
mapEl.classList.remove('flash');
window.setTimeout(function() {
mapEl.classList.add('flash');
}, 1);
}
this.checkDepends();
var tabGroups = mapEl.querySelectorAll('.cbi-map-tabbed, .cbi-section-node-tabbed');
for (var i = 0; i < tabGroups.length; i++)
ui.tabs.initTabGroup(tabGroups[i].childNodes);
return mapEl;
}, this));
},
/**
* Find a form option element instance.
*
* @param {string} name
* The name or the full ID of the option element to look up.
*
* @param {string} [section_id]
* The ID of the UCI section containing the option to look up. May be
* omitted if a full ID is passed as first argument.
*
* @param {string} [config_name]
* The name of the UCI configuration the option instance belongs to.
* Defaults to the main UCI configuration of the map if omitted.
*
* @returns {Array<LuCI.form.AbstractValue,string>|null}
* Returns a two-element array containing the form option instance as
* first item and the corresponding UCI section ID as second item.
* Returns `null` if the option could not be found.
*/
lookupOption: function(name, section_id, config_name) {
var id, elem, sid, inst;
if (name.indexOf('.') > -1)
id = 'cbid.%s'.format(name);
else
id = 'cbid.%s.%s.%s'.format(config_name || this.config, section_id, name);
elem = this.findElement('data-field', id);
sid = elem ? id.split(/\./)[2] : null;
inst = elem ? dom.findClassInstance(elem) : null;
return (inst instanceof CBIAbstractValue) ? [ inst, sid ] : null;
},
/** @private */
checkDepends: function(ev, n) {
var changed = false;
for (var i = 0, s = this.children[0]; (s = this.children[i]) != null; i++)
if (s.checkDepends(ev, n))
changed = true;
if (changed && (n || 0) < 10)
this.checkDepends(ev, (n || 10) + 1);
ui.tabs.updateTabs(ev, this.root);
},
/** @private */
isDependencySatisfied: function(depends, config_name, section_id) {
var def = false;
if (!Array.isArray(depends) || !depends.length)
return true;
for (var i = 0; i < depends.length; i++) {
var istat = true,
reverse = depends[i]['!reverse'],
contains = depends[i]['!contains'];
for (var dep in depends[i]) {
if (dep == '!reverse' || dep == '!contains') {
continue;
}
else if (dep == '!default') {
def = true;
istat = false;
}
else {
var res = this.lookupOption(dep, section_id, config_name),
val = (res && res[0].isActive(res[1])) ? res[0].formvalue(res[1]) : null;
var equal = contains
? isContained(val, depends[i][dep])
: isEqual(val, depends[i][dep]);
istat = (istat && equal);
}
}
if (istat ^ reverse)
return true;
}
return def;
}
});
/**
* @constructor JSONMap
* @memberof LuCI.form
* @augments LuCI.form.Map
*
* @classdesc
*
* A `JSONMap` class functions similar to [LuCI.form.Map]{@link LuCI.form.Map}
* but uses a multidimensional JavaScript object instead of UCI configuration
* as data source.
*
* @param {Object<string, Object<string, *>|Array<Object<string, *>>>} data
* The JavaScript object to use as data source. Internally, the object is
* converted into an UCI-like format. Its toplevel keys are treated like UCI
* section types while the object or array-of-object values are treated as
* section contents.
*
* @param {string} [title]
* The title caption of the form. A form title is usually rendered as separate
* headline element before the actual form contents. If omitted, the
* corresponding headline element will not be rendered.
*
* @param {string} [description]
* The description text of the form which is usually rendered as text
* paragraph below the form title and before the actual form contents.
* If omitted, the corresponding paragraph element will not be rendered.
*/
var CBIJSONMap = CBIMap.extend(/** @lends LuCI.form.JSONMap.prototype */ {
__init__: function(data /*, ... */) {
this.super('__init__', this.varargs(arguments, 1, 'json'));
this.config = 'json';
this.parsechain = [ 'json' ];
this.data = new CBIJSONConfig(data);
}
});
/**
* @class AbstractSection
* @memberof LuCI.form
* @augments LuCI.form.AbstractElement
* @hideconstructor
* @classdesc
*
* The `AbstractSection` class serves as abstract base for the different form
* section styles implemented by `LuCI.form`. It provides the common logic for
* enumerating underlying configuration section instances, for registering
* form options and for handling tabs to segment child options.
*
* This class is private and not directly accessible by user code.
*/
var CBIAbstractSection = CBIAbstractElement.extend(/** @lends LuCI.form.AbstractSection.prototype */ {
__init__: function(map, sectionType /*, ... */) {
this.super('__init__', this.varargs(arguments, 2));
this.sectiontype = sectionType;
this.map = map;
this.config = map.config;
this.optional = true;
this.addremove = false;
this.dynamic = false;
},
/**
* Access the parent option container instance.
*
* In case this section is nested within an option element container,
* this property will hold a reference to the parent option instance.
*
* If this section is not nested, the property is `null`.
*
* @name LuCI.form.AbstractSection.prototype#parentoption
* @type LuCI.form.AbstractValue
* @readonly
*/
/**
* Enumerate the UCI section IDs covered by this form section element.
*
* @abstract
* @throws {InternalError}
* Throws an `InternalError` exception if the function is not implemented.
*
* @returns {string[]}
* Returns an array of UCI section IDs covered by this form element.
* The sections will be rendered in the same order as the returned array.
*/
cfgsections: function() {
L.error('InternalError', 'Not implemented');
},
/**
* Filter UCI section IDs to render.
*
* The filter function is invoked for each UCI section ID of a given type
* and controls whether the given UCI section is rendered or ignored by
* the form section element.
*
* The default implementation always returns `true`. User code or
* classes extending `AbstractSection` may overwrite this function with
* custom implementations.
*
* @abstract
* @param {string} section_id
* The UCI section ID to test.
*
* @returns {boolean}
* Returns `true` when the given UCI section ID should be handled and
* `false` when it should be ignored.
*/
filter: function(section_id) {
return true;
},
/**
* Load the configuration covered by this section.
*
* The `load()` function recursively walks the section element tree and
* invokes the load function of each child option element.
*
* @returns {Promise<void>}
* Returns a promise resolving once the values of all child elements have
* been loaded. The promise may reject with an error if any of the child
* elements load functions rejected with an error.
*/
load: function() {
var section_ids = this.cfgsections(),
tasks = [];
if (Array.isArray(this.children))
for (var i = 0; i < section_ids.length; i++)
tasks.push(this.loadChildren(section_ids[i])
.then(Function.prototype.bind.call(function(section_id, set_values) {
for (var i = 0; i < set_values.length; i++)
this.children[i].cfgvalue(section_id, set_values[i]);
}, this, section_ids[i])));
return Promise.all(tasks);
},
/**
* Parse this sections form input.
*
* The `parse()` function recursively walks the section element tree and
* triggers input value reading and validation for each encountered child
* option element.
*
* Options which are hidden due to unsatisfied dependencies are skipped.
*
* @returns {Promise<void>}
* Returns a promise resolving once the values of all child elements have
* been parsed. The returned promise is rejected if any parsed values are
* not meeting the validation constraints of their respective elements.
*/
parse: function() {
var section_ids = this.cfgsections(),
tasks = [];
if (Array.isArray(this.children))
for (var i = 0; i < section_ids.length; i++)
for (var j = 0; j < this.children.length; j++)
tasks.push(this.children[j].parse(section_ids[i]));
return Promise.all(tasks);
},
/**
* Add an option tab to the section.
*
* The child option elements of a section may be divided into multiple
* tabs to provide a better overview to the user.
*
* Before options can be moved into a tab pane, the corresponding tab
* has to be defined first, which is done by calling this function.
*
* Note that once tabs are defined, user code must use the `taboption()`
* method to add options to specific tabs. Option elements added by
* `option()` will not be assigned to any tab and not be rendered in this
* case.
*
* @param {string} name
* The name of the tab to register. It may be freely chosen and just serves
* as an identifier to differentiate tabs.
*
* @param {string} title
* The human readable caption of the tab.
*
* @param {string} [description]
* An additional description text for the corresponding tab pane. It is
* displayed as text paragraph below the tab but before the tab pane
* contents. If omitted, no description will be rendered.
*
* @throws {Error}
* Throws an exception if a tab with the same `name` already exists.
*/
tab: function(name, title, description) {
if (this.tabs && this.tabs[name])
throw 'Tab already declared';
var entry = {
name: name,
title: title,
description: description,
children: []
};
this.tabs = this.tabs || [];
this.tabs.push(entry);
this.tabs[name] = entry;
this.tab_names = this.tab_names || [];
this.tab_names.push(name);
},
/**
* Add a configuration option widget to the section.
*
* Note that [taboption()]{@link LuCI.form.AbstractSection#taboption}
* should be used instead if this form section element uses tabs.
*
* @param {LuCI.form.AbstractValue} optionclass
* The option class to use for rendering the configuration option. Note
* that this value must be the class itself, not a class instance obtained
* from calling `new`. It must also be a class derived from