-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelement.js
More file actions
1844 lines (1602 loc) · 46.9 KB
/
delement.js
File metadata and controls
1844 lines (1602 loc) · 46.9 KB
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
/*!
delement.js ö
K345 2006-2022
dElement() http://js.knrs.de
No recent or fancy programming styles or es6+ versions will be used for now.
*/
/* %% devel on %% */
/* eslint-disable */
/*global K345, document*/
/** @namespace */
var K345 = K345 || {};
/* eslint-enable */
/* eslint new-cap: ["error", { "newIsCapExceptions": ["dError"] }] */
/* %% devel off %% */
/* @@CODESTART DATTR "Javascript" */
/** conversion table for HTML-attribute names
@type {object} */
K345.attrNames = K345.attrNames || {
acceptcharset: 'acceptCharset', accesskey: 'accessKey', alink: 'aLink',
bgcolor: 'bgColor', cellindex: 'cellIndex', cellpadding: 'cellPadding',
cellspacing: 'cellSpacing', charoff: 'chOff', 'class': 'className',
codebase: 'codeBase', codetype: 'codeType', colspan: 'colSpan',
datetime: 'dateTime', 'for': 'htmlFor', frameborder: 'frameBorder',
framespacing: 'frameSpacing', ismap: 'isMap', longdesc: 'longDesc',
marginheight: 'marginHeight', marginwidth: 'marginWidth', maxlength: 'maxLength',
nohref: 'noHref', noresize: 'noResize', nowrap: 'noWrap',
readonly: 'readOnly', rowindex: 'rowIndex', rowspan: 'rowSpan',
tabindex: 'tabIndex', usemap: 'useMap', valign: 'vAlign', vlink: 'vLink'};
/* @@CODEEND DATTR */
/** names of HTML elements with content type "void"
@type {Array} */
K345.voidElements = K345.voidElements || ['area', 'base', 'basefont', 'br', 'col',
'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'keygen', 'link', 'meta',
'param', 'source', 'track', 'wbr'];
/* @@CODESTART DELEM "Javascript" */
/**
dElement / dAppend
requires Array.isArray()
requires Array.prototype.filter()
requires Array.prototype.forEach()
requires Array.prototype.indexOf()
requires Array.prototype.some()
requires Function.prototype.bind()
requires K345.attrNames
requires K345.voidElements
*/
(function (attrNames, voidElems) {
''; 'use strict';
/* internal vars */
var _slice = Array.prototype.slice,
dAppend_regex = (/[#\.=\[\]:\s]+/),
eventStack, initStack, refs, loopdepth,
/* predefined data */
skipProps, saveProps, formProps, boolProps, multiProps,
/* functions */
hasOwn, dError, isNode, isEl, isAppendable, isTextNode, parseElemStr, strToNodes;
/* ============== COMMON FUNCTIONS ================= */
/** test if object 'obj' has own property 'prop'
@param {object} obj
Object to test
@param {string} prop
Property which must be in 'obj'
@returns {boolean}
true, if 'prop' is a native property of 'obj'
@function
*/
hasOwn = (function () {
return (isMeth(Object, 'hasOwn'))
/* browsers supporting Object.hasOwn() */
? function (obj, prop) {
return Object.hasOwn(obj, prop);
}
/* fallback for browsers without Object.hasOwn support */
: function (obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
};
})();
/** test if el is a nodeElement and has a specific nodeType
@param {HTMLElement} el
Element to test
@returns {boolean}
true, if nodetype matches item in array '@this'.
@this {Array} allowed nodeTypes to test against
*/
function nodeTest (el) {
/* "nodeType" in el must NOT be replaced by call to hasOwnProperty! */
return isObj(el) && 'nodeType' in el && this.indexOf(el.nodeType) > -1;
}
/** test: is 'el' a DOM element?
@function
@name isEl
@param {HTMLElement} el
Element to test
@returns {boolean}
true if 'el' is a nodeElement(1)
*/
isEl = nodeTest.bind([
Node.ELEMENT_NODE
]);
/** test: is 'el' a DOM element or a documentFragment?
@function
@name isNode
@param {HTMLElement} el
Element to test
@returns {boolean}
true if 'el' is a nodeElement(1) or a documentFragment(11)
*/
isNode = nodeTest.bind([
Node.ELEMENT_NODE,
Node.DOCUMENT_FRAGMENT_NODE
]);
/** test: can 'el' be appended to nodeElements?
@function
@name isAppendable
@param {HTMLElement} el
Element to test
@returns {boolean}
true if 'el' is a nodeElement(1), a documentFragment(11),
a comment(8) or a textNode(3)
*/
isAppendable = nodeTest.bind([
Node.ELEMENT_NODE,
Node.TEXT_NODE,
Node.COMMENT_NODE,
Node.DOCUMENT_FRAGMENT_NODE
]);
/** test: is 'el' a text node?
@function
@name isTextNode
@param {HTMLElement} el
Element to test
@returns {boolean}
true if 'el' is a textNode(3)
*/
isTextNode = nodeTest.bind([
Node.TEXT_NODE
]);
/**
remove dash(es) (-) from a string and convert the following char to uppercase
( no-text => noText it-is-fine => itIsFine)
@param {string} str
original string
@returns {string}
modified string
*/
function camelCase (str) {
return str.replace(/\-./g, function (s) {
return s.substr(1).toUpperCase();
});
}
/**
test: is item a string?
@param {*} item
given item to test against
@returns {boolean}
true, if type of given item is 'string'
*/
function isStr (item) {
return typeof item === 'string';
}
/**
test: is o an object but not null or Array object? (simple test)
@param {*} item
given item to test against
@returns {boolean}
true, if type of given item is 'object'
*/
function isObj (item) {
return item !== null && typeof item === 'object' && !Array.isArray(item);
}
/**
test: is "m" a method of "o"?
@param {object} o
the given object
@param {string} m
method name which should be found in object "o"
@returns {boolean}
true, if object "o" contains a method "m"
*/
function isMeth (o, m) {
var t = typeof o[m];
return ('function|unknown'.indexOf(t) > -1) || (t === 'object' && Boolean(o[m]));
}
/**
create deep copy of an object.
IMPORTANT: Simplified, because it will only be used for dElement
declaration objects
@param {object} o
object to be cloned
@returns {object}
the copy of o
*/
function oCpy (o) {
var no = {},
p, op;
for (p in o) {
if (hasOwn(o, p)) {
op = o[p];
if (Array.isArray(op)) {
no[p] = _slice.call(op, 0);
}
else if (isObj(op)) {
no[p] = oCpy(op);
}
else {
no[p] = op;
}
}
}
return no;
}
/* throw error */
dError = (function () {
var F;
/** throw error
@param {string} message error message
@class
@name dError */
function dErr (message) {
var err;
if (!this || !(this instanceof Error)) {
throw new dError(message);
}
this.message = 'dElement Error:\n' + message + '\n';
this.name = 'dError';
err = new Error(this.message);
err.name = this.name;
this.stack = err.stack;
console.error(this.message);
if (isMeth(console, 'trace')) {
console.trace(arguments);
}
}
if (isMeth(Object, 'create')) {
dErr.prototype = Object.create(Error.prototype);
}
else {
F = function () {};
F.prototype = Error.prototype;
dErr.prototype = new F();
}
return dErr;
})();
/** map property names of an object.
@param {object} o
object to be changed
@param {object} nmap
description object of property names to change in 'o'
"oldname": "newname"
@returns {object}
changed object
@example
var o = {a: 1, b: 42, c: 'hey'}; // before
o = mapNames(o, {a: 'one', c: 'greet'});
// o is now {one: 1, b: 42, greet: 'hey'}
*/
function mapNames (o, nmap) {
var pr;
for (pr in nmap) {
if (hasOwn(o, pr)) {
o[nmap[pr]] = o[pr];
delete o[pr];
}
}
return o;
}
/* ================ VARIABLES AND DATA ================= */
/** these properties are processed ahead of any remaining properties to avoid
browser bugs (mainly IE of course). Retain order!
@type {Array} */
formProps = ['type', 'name', 'value', 'checked', 'selected'];
/** skip the following internal properties in createTree() property loop
@type {Array} */
skipProps = ['element', 'elrefs', 'clone', 'clonetop'];
/** multi-properties. These properties may appear multiple times inside a object
declaration, postfixed by an underscore and an unique identifier
@type {Array} */
multiProps = ['text', 'event', 'attribute', 'setif', 'html', 'child',
'comment', 'collect'];
/** save element reference if one of these props appears
@type {Array} */
saveProps = ['id', 'name'];
/** recursion counter for variable replacement depth in loop
@type {number} */
loopdepth = 0;
/** attributes of 'boolean' type. value may be either empty or the attribute name
@type {Array} */
boolProps = [
'checked', 'compact', 'declare', 'defer', 'disabled', 'ismap', 'multiple',
'nohref', 'noresize', 'noshade', 'nowrap', 'readonly', 'selected'
];
/* ============== EVENTS ================= */
/**
attach event handler(s) to an element
@param {object} evtDcl
An object with event data
@param {HTMLElement} evtDcl.el
target element to attach element to
@param {object} evtDcl.val
object with function/function name and arguments
@param {string|Function} evtDcl.val.func
function reference or function name of the event handler
@param {Array} evtDcl.val.args
arguments to pass to event handler function
*/
function setEvent (evtDcl) {
var ix, fn,
o = evtDcl.val,
el = evtDcl.el;
o = mapNames(o, {
'function': 'func',
'arguments': 'args'
});
if (!isObj(o) || !hasOwn(o, 'args')) {
throw new dError('Not a valid event declaration', o);
}
if (!Array.isArray(o.args)) {
throw new dError('Expected o.args to be array', o.args);
}
/* call external, e.g. cross browser event handling
o.func is a function reference */
/* o.func is not defined or a string */
if (typeof o.func !== 'function') {
/* call method "o.func" of el (defaults to "addEventListener") */
o.func = o.func || 'addEventListener';
fn = el[String(o.func)];
if (typeof fn !== 'function') {
throw new dError('eventhandler is not a function/method of element', o);
}
fn.apply(el, o.args);
return;
}
ix = o.args.indexOf('#el#');
/* placeholder #el# not found, try to find #elp# */
if (ix < 0) {
ix = o.args.indexOf('#elp#');
/* placeholder #elp# found */
if (ix >= 0) {
if (!el.parentNode) {
throw new dError('placeholder #elp# found, but element ' +
'has no parent node', evtDcl);
}
el = el.parentNode;
}
else {
ix = o.args.indexOf('#elpp#');
/* placeholder #elpp# found */
if (ix >= 0) {
if (!el.parentNode || !el.parentNode.parentNode) {
throw new dError('placeholder #elpp# found, but element ' +
'has no grandparent node', evtDcl);
}
el = el.parentNode.parentNode;
}
}
}
/* none of the placeholders was found */
if (ix < 0) {
/* insert element reference as first argument */
o.args.unshift(el);
}
/* a placeholder was found */
else {
/* insert element reference at defined position */
o.args.splice(ix, 1, el);
}
/* call event set function */
o.func.apply(el, o.args);
}
/**
add event(s) to event stack
@param {HTMLElement} el
@param {Array} eo
*/
function pushEvt (el, eo) {
if (!Array.isArray(eo)) {
eo = [eo];
}
eo.forEach(function (item) {
eventStack.push({
el: el,
val: item
});
});
}
/* ============== PROPERTIES ================= */
/**
Set a property "prop" of el to "val".
Falls back to setAttribute if prop set fails
*/
function setProp (el, prop, val) {
var lcProp = prop.toLowerCase(),
rProp;
if (lcProp.indexOf('data-') === 0) {
/* throw error if data attribute starts with 'data-xml' or contains
uppercase letters or semicolon */
if (
lcProp !== prop || /* has uppercase */
lcProp.indexOf('data-xml') > -1 || /* starts with xml */
lcProp.indexOf(';') > -1
) {
throw new dError('data-* property/attribute name may not start with "xml" or' +
' contain any semicolon or uppercase chars');
}
/* dataset stores values as string, so it's best to do the same for all
data attributes even if dataset API is n/a */
val = String(val);
/* set value in dataset API if available.
ALWAYS use "in" operator, "hasOwnProperty" returns false on elements */
if ('dataset' in el && isObj(el.dataset)) {
el.dataset[camelCase(lcProp.substring(5))] = val;
return el;
}
rProp = lcProp;
}
else if (boolProps.indexOf(lcProp) > -1) {
/* handle attributes which work as a switch (either have no value in HTML or
self reference their name as value (e.g. checked="checked")) */
if (val === true || (isStr(val) && val.toLowerCase() === lcProp)) {
val = true;
}
else if (val === false || val === '') {
return el;
}
else { /* not a valid value for boolProps */
throw new dError(
'switch attribute "' + prop + '" has an invalid value of "' + val +
'".\nValue may be the attribute\'s name or boolean true only.'
);
}
rProp = lcProp;
}
else {
/* some attribute names must be replaced, eg. for => htmlFor */
rProp = replaceAttrName(prop);
if (
(rProp === 'className' && val === '') || /* prevent empty "className" */
(typeof val === 'boolean' && !val)
) {
return el;
}
}
/*
set a property, fallback to setAttribute if assignment fails.
some old browsers misbehave on "data-" attributes, even in bracket
notation
*/
try {
el[rProp] = val;
if (el[rProp] !== val && lcProp !== 'href') {
/* throw error to apply 'catch' branch */
throw new Error('value type mismatch in property ' + prop);
}
}
catch (ex) {
setAttribs(el, {name: rProp, value: val});
}
return el;
}
/**
set a property if condition in declaration object is truthy
*/
function setPropIf (el, pobj) {
if (isObj(pobj) && hasOwn(pobj, 'name') && hasOwn(pobj, 'value')) {
if (hasOwn(pobj, 'condition') && Boolean(pobj.condition)) {
if (pobj.name !== 'child') {
setProp(el, pobj.name, pobj.value);
}
else if (isObj(pobj.value)) {
appendTree.call(el, pobj.value);
}
}
}
}
/**
map property names. returns base name of 'multi' properties
*/
function mapMultiProps (p) {
var uscoPos = p.indexOf('_'),
base;
if (uscoPos > 0) { /* underscore found */
base = p.substring(0, uscoPos);
if (multiProps.indexOf(base) > -1) {
p = base;
}
}
return p;
}
/* ============== MISC ================= */
/**
set element styles
*/
function setStyles (el, sty) {
if (Array.isArray(sty)) {
sty = sty.join(';');
}
/* Prefer element.style.cssText if available. */
if (el.style.cssText !== undefined) {
el.style.cssText = sty;
}
else {
el.setAttribute('style', sty);
}
return el;
}
/**
create HTML comment node
If document.createComment() is not available, this function adds comment nodes
to node elements only
*/
function addComment (el, comm) {
if (Array.isArray(comm)) {
comm.forEach(addComment.bind(null, el));
}
else {
if (isMeth(document, 'createComment')) { /* node element and fragment */
el.appendChild(document.createComment(comm));
}
else if (isMeth(el, 'insertAdjacentHTML')) { /* node element only, no fragment */
el.insertAdjacentHTML('beforeEnd', '<!--' + comm + '-->');
}
}
}
/**
push function reference from init property and element reference to init stack
*/
function pushInit (el, val) {
if (typeof val === 'function') {
initStack.push({
el: el,
func: val
});
}
}
/**
call functions from init stack
'this' is a reference to the created element tree
*/
function callInit (fobj) {
fobj.func.call(fobj.el, this);
}
/* ============== LOOPS ================= */
/**
loop element creation and replace placeholders
*/
function loopDecl (s) {
var step = 1,
start = 0,
cnt = 1,
parr = ['chk', 'sel'],
isdeep = hasOwn(s, 'loopdeep'),
frg, i, o, lprop, lobj, lcnt;
if (hasOwn(s, 'loop') && isdeep) {
throw new dError('You may use only one of "loop" OR "loopdeep", not both.');
}
lprop = (isdeep) ? 'loopdeep' : 'loop';
lobj = s[lprop];
delete s[lprop];
/* check if lobj is either a valid object or a numeric value */
if (isObj(lobj) && hasOwn(lobj, 'count') && !isNaN(lobj.count)) {
/* validate loop values count, step and start */
cnt = Number(lobj.count);
if (hasOwn(lobj, 'step') && !isNaN(lobj.step)) {
step = Number(lobj.step);
if (step === 0) {
step = 1;
}
}
if (hasOwn(lobj, 'start') && !isNaN(lobj.start)) {
start = Number(lobj.start);
}
/* validate 'values' array (for "v" placeholder) */
if (hasOwn(lobj, 'values')) {
if (!Array.isArray(lobj.values)) {
throw new dError('loop property "values" has to be an array');
}
if (!hasOwn(lobj, 'valuesrepeat') && lobj.values.length < lobj.count) {
throw new dError(
'"values" array has less elements (' + lobj.values.length +
') than loop count (' + lobj.count + ').\nAdd more items to' +
' the array or set "valuesrepeat" mode.'
);
}
}
/* validate chk/sel properties (checked or selected elements) */
parr.forEach(function (item) {
if (hasOwn(lobj, item)) {
if (!Array.isArray(lobj[item]) && isNaN(lobj[item])) {
throw new dError(
'type of loop property "' + item + '" must be array or number'
);
}
}
});
}
else if (!isNaN(lobj)) {
cnt = Number(lobj);
}
cnt = Math.abs(Math.round(cnt)); /* make count a positive integer */
frg = document.createDocumentFragment();
/* element loop */
lcnt = 0;
for (i = start; i < (start + (step * cnt)); i += step) {
if (Math.floor(i) !== i) { /* float check */
i = parseFloat(i.toFixed(8), 10); /* avoid rounding errors */
}
/* replace placeholders with current values */
o = replaceCounter({
declaration: s,
value: i,
counter: lcnt,
recursive: isdeep,
config: lobj
});
/* set checked/selected if one of the properties from "parr" exists */
if (parr.some(hasOwn.bind(null, lobj))) {
o = setCSFlags({
declaration: o,
config: lobj,
loopcount: lcnt,
properties: parr
});
}
/* create element tree and append to fragment */
appendTree.call(frg, o);
lcnt++;
}
// write it back to s
s[lprop] = lobj;
return frg;
}
/**
find placeholders and replace them with committed values
@param {object} argObj
object with required values
@param {object} argObj.declaration
dElement declaration object
@param {number} argObj.value
calculated value
@param {number} argObj.counter
loop counter
@param {boolean} argObj.recursive
recursive replace in subdeclarations
@param {object} argObj.config
loop configuration object
@returns {object}
declaration with replaced values
*/
function replaceCounter (argObj) {
var i = argObj.value,
c = argObj.counter,
isdeep = argObj.recursive,
lobj = argObj.config,
o = oCpy(argObj.declaration), /* create copy of declaration */
phreg, p, cc, v;
/* RegExp to match all parts of "n" and "c" placeholders */
phreg = /\!\!(?:([+-]?\d+(?:\.\d+)?)[•\*]?)?(n|c)([+-]\d+(?:\.\d+)?)?\!\!/gi;
/* !! | mul number |mul sign| nc | add/sub number | !! */
/* | [1] | | [2]| [3] | */
/* handle array index if "values" propery is an array */
if (hasOwn(lobj, 'values')) {
v = lobj.values;
cc = (hasOwn(lobj, 'valuesrepeat'))
? c % v.length
: c;
}
for (p in o) {
/* replace all placeholders in string */
if (isStr(o[p])) {
/* replace each "v" placeholder with array value */
if (Array.isArray(v) && o[p].indexOf('!!v!!') > -1) {
o[p] = o[p].replace(
/\!\!v\!\!/gi,
v[cc]
);
}
/* replace each "n" or "c" placeholder with its calculated value */
o[p] = o[p].replace(
phreg,
loopReplace.bind(null, c, i)
);
}
else if (
/* scan for placeholders in subdeclarations until a loop, loopstop or
loopdeep property is found or loop depth exceeds 1 on loop property
(but always replace placeholders in first child declaration
[loopdepth = 0])
*/
p === 'child' &&
isObj(o.child) &&
!hasOwn(o.child, 'loop') &&
!hasOwn(o.child, 'loopdeep') &&
!hasOwn(o.child, 'loopstop') &&
(isdeep || loopdepth < 1)
) {
loopdepth++; /* increase depth counter */
o.child = replaceCounter({
declaration: o.child,
value: i,
counter: c,
recursive: isdeep,
config: lobj
});
loopdepth--;
}
}
return o;
}
/**
callback for op.replace in function replaceCounter:
calculate value of placeholder and replace it.
@param {number} cnt
loop counter
@param {number} val
loop value
@param {string} matched
matched string (not used)
@param {string} mul
multiplier (can include leading "+" or "-")
@param {string} ptype
placeholder type (n or c for loop value or counter)
@param {string} add
sum to add (can include leading "+" or "-")
@return {number}
final calculated value for placeholder replacement
*/ /* eslint-disable-next-line max-params */
function loopReplace (cnt, val, matched, mul, ptype, add) {
/* determine type of value */
var cv = (ptype.toLowerCase() === 'c')
? cnt /* loop counter */
: val; /* calculated value */
mul = Number(mul);
if (!isNaN(mul)) {
cv *= mul;
}
add = Number(add);
if (!isNaN(add)) {
cv += add;
}
return cv;
}
/**
set checked or selected property in declaration
@param {object} argObj.declaration
original dElement declaration object
@param {object} argObj.config
loop configuration object
@param {number} argObj.loopcount
loop counter
@param {array} argObj.properties
array of property names to process
@returns {object}
declaration object with replaced values
*/
function setCSFlags (argObj) {
var o = argObj.declaration,
lobj = argObj.config,
lc = argObj.loopcount,
arr = argObj.properties,
i = arr.length,
c = lc + 1,
item, prp;
while (i--) {
item = arr[i];
if (hasOwn(lobj, item) && (
c === lobj[item] ||
(Array.isArray(lobj[item]) && lobj[item].indexOf(c) > -1)
)) {
prp = (item === 'sel') ? 'selected' : 'checked';
o[prp] = true;
}
}
return o;
}
/* ============== ELEMENT REFERENCES ================= */
/**
add current element reference to collection
*/
function collectElRef (sc, el) {
if (Array.isArray(sc)) {
sc.push(el);
}
else if (isObj(sc) && hasOwn(sc, 'obj') && hasOwn(sc, 'name') && isObj(sc.obj)) {
if (sc.obj[sc.name] === undefined) {
sc.obj[sc.name] = el;
}
else {
throw new dError(
'duplicate declaration of ' + sc.name + ' in property "collect"'
);
}
}
else {
throw new dError('Value of property "collect" must be an array or an object' +
' containing the properties "obj" and "name".');
}
}
/**
save references of elements with name or id property
*/
function saveRefs (rObj, sdata) {
var pr = sdata.s[sdata.p];
if (sdata.lp === 'id') {
rObj.i[pr] = sdata.el;
}
else if (sdata.lp === 'name') {
if (Array.isArray(rObj.n[pr])) {
rObj.n[pr].push(sdata.el);
}
else {
rObj.n[pr] = [sdata.el];
}
}
return rObj;
}
/* ============== ATTRIBUTES ================= */
/**
replace special property names
*/
function replaceAttrName (atn) {
var lcAtt = atn.toLowerCase();
return (lcAtt in attrNames)
? attrNames[lcAtt]
: camelCase(atn);
}
/**
set attributes with setAttribute(). will be used only when enforced by property
attr|attrib|attribute or with certain problematic properties
value has to be either
- an object containing properties value and name
e.g. attribute: {name: 'foo', value: 'bar'}
- an array with objects as described above
*/
function setAttribs (el, att) {
if (Array.isArray(att)) {
att.forEach(setAttribs.bind(null, el));
}
else if (
isNode(el) && isObj(att) && hasOwn(att, 'name') &&
hasOwn(att, 'value') && isStr(att.name)
) {
if (att.name.toLowerCase() === 'style') {
/* setAttribute with "style" fails in some browsers, handle it */
setStyles(el, att.value);
}
else {
el.setAttribute(att.name, att.value);
}
}
return el;
}
/* ============== PARSE EXTENDED SYNTAX ================= */
/* parseElemStr() */
parseElemStr = (function () {
var ETX = '\x03', /* 0x03 (ETX, end of text) */
US = '\x1F', /* 0x1F (US, unit separator) */
WSP = ' \t\r\n\f\x0B\xA0', /* some whitespace */
MODE_END = ETX,
MODE_TAGNAME = '$',
MODE_ID = '#',
MODE_CLASS = '.',
MODE_NAME = '~',
MODE_TYPE = '@',
MODE_VALUE = '=',
modeChars = {},
moc = '',
stopChars, pr;
/* data for parse modes
defaults are unique:true and stop:true
*/
modeChars[MODE_TAGNAME] = {};
modeChars[MODE_END] = {};
modeChars[MODE_CLASS] = {attrName: 'class', unique: false};
modeChars[MODE_ID] = {attrName: 'id'};
modeChars[MODE_NAME] = {attrName: 'name'};
modeChars[MODE_TYPE] = {attrName: 'type'};
modeChars[MODE_VALUE] = {attrName: 'value', stop: false};
/* eslint-enable no-multi-spaces */
for (pr in modeChars) {
if (hasOwn(modeChars, pr)) {
moc += pr;