This repository was archived by the owner on Feb 22, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjaaJSU.js
2074 lines (1922 loc) · 79.9 KB
/
jaaJSU.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
/* jshint esversion: 6,-W097, -W040, browser: true, expr: true, undef: true, maxcomplexity: 21, maxparams: 8, maxdepth: 4, latedef: false */
/* gulp *//* global gulp_place, define, module *///gulp.keep.line
/**
* @module jaaJSU
* @version 2.0.0
*/
(function(module_name, factory) {
'use strict';
let window_export;
if (typeof define === 'function' && define.amd) {
define([], function(){
return factory(window, document);
});
} else if (typeof exports !== 'undefined') {
module.exports = factory(window, document);
} else {
window_export= factory(window, document);
Object.keys(window_export).forEach(key=> window[key]= window_export[key]);
window[module_name+"_version"]= "2.0.0";
}
})("jaaJSU", function(window, document){
'use strict';
const _public= {};
_public.$array= {};
function __eachInArrayLike(iterable, i_function, scope, share){
const key_length= iterable.length;
for(let key=0, j=key_length-1; key<key_length; key++, j--){
share= i_function.call(scope, { item: iterable[key], last: !j, key, share });
}
return share;
}
function __eachInArrayLikeDynamic(iterable, i_function, scope, share){
for(let key=0; key<iterable.length; key++){
share= i_function.call(scope, { item: iterable[key], key, share });
}
return share;
}
_public.$array.each= __eachInArrayLike;
_public.$array.eachDynamic= __eachInArrayLikeDynamic;
_public.$array.partition= function(arr){
if(!Array.isArray(arr))
arr= Array.from(arr);
return {
head: function(){ const [x, ...xs]= arr; return [x, xs]; },
tail: function(){ let local_arr= [...arr]; const last= local_arr.pop(); return [local_arr, last]; },
onIndex: function(index){ return [arr.slice(0,index), arr.slice(index)]; },
byCondition: function(fn){ return arr.reduce((out, item, key)=> ( out[+!Boolean(fn(item, key))].push(item), out ), [ [], [] ]); }
};
};
_public.$array.arrayIndex= function(i,s,l){ return (l+i+(s%l))%l; };
_public.$array.getLast= function(arr){ return arr[arr.length-1]; };
_public.$array.removeItem= function(arr, item){
let p_arr= [...arr];
var i = 0;
while (i < p_arr.length) {
if (p_arr[i] === item) p_arr.splice(i, 1);
else i++;
}
return p_arr;
};
_public.$array.sortRandom= function(){ return Math.random() - 0.5; };
/*
join concurrent/serial [fork-join.mjs](https://gist.github.com/rauschma/bdc56a046b18528959ad1db3eed05386)
[debug-promise.js](https://gist.github.com/jaandrle/9714466561b86412a30dd7b0b73fea8c)
*/
_public.$async= {};
_public.$async.each_= function(...functions){return function(...input){
return Promise.all(functions.map(f=>f(...input)));
};};
_public.$async.CANCEL= Symbol("$async.CANCEL");
_public.$async.iterateMixed_= function(...tasks){
return new Promise(function(resolve, reject){
return (function run(result){
if(!tasks.length) return resolve(result);
const task= tasks.shift();
const value= typeof task==='function' ? task(result):task;
// check against nil values
if(value!==null){
if(value===_public.$async.CANCEL) return;
if(value.then) return value.then(run);
}
return Promise.resolve(run(value));
})();
});
};
_public.$async.iterate_= function(iterablePromises){
let p= Promise.resolve();
for(let i= 0, { length }= iterablePromises; i < length; i++)
p= p.then(iterablePromises[i]);
return p;
};
_public.$async.sequention= function(...functions){
return function(input){
let p= Promise.resolve(input);
for(let i= 0, { length }= functions; i < length; i++)
p= p.then(functions[i]);
return p;
};
};
_public.$async.serialize= (function(){
const concat = list => Array.prototype.concat.bind(list);
const promiseConcat = f => x => f().then(concat(x));
const promiseReduce = (acc, f) => acc.then(promiseConcat(f));
return funcs => funcs.reduce(promiseReduce, Promise.resolve([]));
})();
_public.$async.serialize_= _public.$async.serialize;
_public.$dom= {};
_public.$dom.each= __eachInArrayLike;
_public.$dom.eachDynamic= __eachInArrayLikeDynamic;
_public.$dom.toggleAttribute= function(element, attribute_name, attribute_a, attribute_b){
const attribute_new= element.getAttribute(attribute_name) === attribute_a ? attribute_b : attribute_a;
element.setAttribute(attribute_name, attribute_new);
return attribute_new;
};
_public.$dom.empty= function(container){
let len = container.childNodes.length;
while(len--){ container.removeChild(container.lastChild); }
};
_public.$dom.mount= function(element_target, type= "childLast"){
return function mount_inner(element){
if(!(element instanceof Element)){
if(typeof element.mount !== "function") throw new TypeError("`element` must be instance of `Element` or `$dom.component`.");
return element.mount(element_target, type);
}
switch ( type ){
case "after":
const { parentNode, nextSibling }= element_target;
if(nextSibling) parentNode.insertBefore(element, nextSibling);
else parentNode.appendChild(element);
break;
case "before":
element_target.parentNode.insertBefore(element, element_target);
break;
case "replace":
element_target.parentNode.insertBefore(element, element_target);
element_target.remove();
break;
case "replaceContent":
_public.$dom.empty(element_target);
element_target.appendChild(element);
break;
default:
if(type==="childFirst" && element_target.childNodes.length) element_target.insertBefore(element, element_target.childNodes[0]);
else element_target.appendChild(element);
break;
}
return element;
};
};
(function(){
const $dom= _public.$dom;
const component_utils= Object.freeze({
registerToMap: function(store, current, indexGenerator){
let current_index= -1;
for(const [i, v] of store){
if(v===current) current_index= i;
if(current_index!==-1) break;
}
if(current_index!==-1) return current_index;
current_index= indexGenerator();
store.set(current_index, current);
return current_index;
},
indexGenerator: (index= 0)=> ()=> index++
});
const $dom_emptyPseudoComponent= (function(){
const share= { mount, update, destroy, ondestroy, isStatic };
let component_out= { add, component, mount, update, ondestroy, share };
return component_out;
function mount(element, type= "childLast"){
// let temp_el;
switch ( type ) {
case "replace":
element.remove();
break;
case "replaceContent":
$dom.empty(element);
break;
// case "before":
// temp_el= element.previousElementSibling;
// if(temp_el) temp_el.remove();
// break;
// case "after":
// temp_el= element.nextElementSibling;
// if(temp_el) temp_el.remove();
// break;
// default:
// if(element.childNodes.length) element.childNodes[type==="childFirst" ? 0 : element.childNodes.length-1].remove();
// break;
}
return null;
}
function add(){ return component_out; }
function component(){ return component_out; }
function update(){ return true; }
function isStatic(){ return true; }
function ondestroy(){ return true; }
function destroy(){ component_out= null; return null; }
})();
const special_components_names= { empty: [ "", "empty" ], fragment: [ "<>", "fragment" ] };
function isInternalElement( target, candidate, safe_only ){
const [ short, long ]= special_components_names[target];
if(safe_only) return short===candidate;
return short===candidate||long===candidate.toLowerCase();
}
$dom.component= function(el_name, attrs, { mapUpdate, namespace_group, safe_el_name_only }={}){
if(!el_name||isInternalElement("empty", el_name, safe_el_name_only)) return $dom_emptyPseudoComponent;
if(el_name==="svg") namespace_group= "SVG";
let assign, createElement;
if(namespace_group==="SVG"){
assign= $dom.assignNS.bind(null, "SVG");
createElement= document.createElementNS.bind(document, "http://www.w3.org/2000/svg");
} else {
assign= $dom.assign;
createElement= document.createElement.bind(document);
}
let /* holds `initStorage()` if `onupdate` was registered and other component related listeners */
internal_storage= null,
on_destroy_funs= null,
/* on first mount */
on_mount_funs= null,
observer= null;
let /* main parent (wrapper), container for children elements */
container,
/* store for all registered elements */
els= [], all_els_counter= 0,
/* current elements deep which holds indicies of elements:
- add(...);add(...); = final deep=[0,1];
- add(...);add(...,-1);add(...) = final deep=[1,2]; (by steps: [0], [0,1], [1,2])
- see `shift` in `add`
*/
deep= [];
const share= { mount, update, destroy, ondestroy, isStatic };
let component_out= { add, addText, component, dynamicComponent, setShift, mount, update, ondestroy, share };
let add_out_methods= {
getReference: function(add_out, el){ return el; },
on: function(add_out, el, ...listeners){
listeners.forEach(([ event_name, args ]= [])=> event_name && add_out[event_name].apply(this, args));
return add_out;
},
oninit: function(add_out, el, fn){ fn.call(add_out, el); return add_out; },
onmount: function(add_out, el, onMountFunction){
if(!on_mount_funs) on_mount_funs= new Map();
on_mount_funs.set(el, onMountFunction);
return add_out;
},
onupdate: function(add_out, el, data, onUpdateFunction){
if(!data) return add_out;
if(!internal_storage) internal_storage= initStorage();
assign(el, internal_storage.register(el, data, onUpdateFunction));
return add_out;
}
};
/**
* Its purpose is to make easy transfering methods somewhere else (like for using in another component, see {@link module:jaaJSU~$dom~instance_component.component} method).
* @typedef share
* @memberof module:jaaJSU~$dom~instance_component
* @borrows module:jaaJSU~$dom~instance_component.mount as mount
* @borrows module:jaaJSU~$dom~instance_component.update as update
* @type {Object}
*/
/**
* This is minimal export of "functional class" {@link module:jaaJSU~$dom.component} and its methods (if they are chainable).
* @typedef instance_component
* @memberof module:jaaJSU~$dom
* @category types descriptions
* @inner
* @type {Object}
*/
if(!isInternalElement("fragment", el_name, safe_el_name_only)) return add(el_name, attrs);
return _addElement(document.createDocumentFragment(), attrs, 0);
function add(el_name, attrs, shift= 0){ return _addElement(createElement(el_name), attrs, shift); }
function _addElement(el, attrs, shift){
recalculateDeep(shift);
attrs= attrs || {};
if(!all_els_counter) container= els[0]= el;
else els[all_els_counter]= getParentElement().appendChild(el);
el= els[all_els_counter];
all_els_counter+= 1;
assign(el, attrs);
const add_out= Object.create(component_out);
add_out.getReference= add_out_methods.getReference.bind(null, add_out, el);
add_out.on= add_out_methods.on.bind(null, add_out, el);
add_out.oninit= add_out_methods.oninit.bind(null, add_out, el);
add_out.onmount= add_out_methods.onmount.bind(null, add_out, el);
add_out.onupdate= add_out_methods.onupdate.bind(null, add_out, el);
return add_out;
}
function addText(text= "", shift= 0){
recalculateDeep(shift);
const text_node= document.createTextNode(text);
let el= els[all_els_counter]= getParentElement().appendChild(text_node);
all_els_counter+= 1;
const add_out= Object.create(component_out);
add_out.getReference= add_out_methods.getReference.bind(null, add_out, el);
add_out.on= add_out_methods.on.bind(null, add_out, el);
add_out.oninit= add_out_methods.oninit.bind(null, add_out, el);
add_out.onmount= add_out_methods.onmount.bind(null, add_out, el);
add_out.onupdate= add_out_methods.onupdate.bind(null, add_out, el);
return add_out;
}
function component({ mount, update, isStatic: isStaticCandidate, destroy: destroyCandidate }, shift= 0){
recalculateDeep(shift);
const el_parent= getParentElement();
els[all_els_counter]= mount(el_parent);
if(el_parent instanceof DocumentFragment) ondestroy(destroyCandidate);
if(!isStaticCandidate()){
if(isStatic()) internal_storage= initStorage();
internal_storage.registerComponent(update);
}
all_els_counter+= 1;
return component_out;
}
function dynamicComponent(data, generator, shift= 0){
recalculateDeep(shift);
const parent= getParentElement();
let current_value= null, current_component= null, current_element= null;
return add_out_methods.onupdate(component_out, parent, data, function(data){
current_value= generator.call(parent, mount, current_component, data, current_value);
});
function mount(component_share){
current_component= component_share;
if(current_element){
current_element= current_component.mount(current_element, "replace");
} else {
current_element= current_component.mount(parent);
}
}
}
function mount(element, type= "childLast"){
if(observer) observer.disconnect();
$dom.mount(element, type)(container);
const parent_node= type==="after"||type==="before" ? element.parentNode : element;
if(!(element instanceof DocumentFragment)){//TODO/WIP
const [ el_c, el_p ]= __observedEls(container, parent_node);
observer= new MutationObserver(mutations=> mutations.forEach(function(record){
if(!record.removedNodes||Array.prototype.indexOf.call(record.removedNodes, el_c)===-1) return false;
destroy();
}));
observer.observe(el_p, { childList: true, subtree: true, attributes: false, characterData: false });
}
if(on_mount_funs){
on_mount_funs.forEach(onMountFunctionCall);
on_mount_funs= undefined;
}
function __observedEls(container, parent_node){
if(!(container instanceof DocumentFragment)) return [ container, parent_node ];
return [ parent_node, parent_node.parentNode ];
}
return container;
function onMountFunctionCall(onMountFunction, el){ return assign(el, onMountFunction.call(el, element, type)); }
}
function destroy(){
if(on_destroy_funs) on_destroy_funs.forEach(onDestroyFunction=> onDestroyFunction.call(container));
if(container) {
if(!(container instanceof DocumentFragment)) container.remove();
els= [];
}
if(observer) observer.disconnect();
observer= undefined;
on_destroy_funs= undefined;
assign= undefined;
createElement= undefined;
container= undefined;
if(internal_storage&&internal_storage.clear){
internal_storage.clear();
internal_storage= undefined;
}
component_out= undefined;
add_out_methods= undefined;
return null;
}
function ondestroy(onDestroyFunction){
if(!on_destroy_funs) on_destroy_funs= new Set();
on_destroy_funs.add(onDestroyFunction);
return component_out;
}
function recalculateDeep(shift){
if(!shift) deep.push(all_els_counter);
else { deep.splice(deep.length+1+shift); deep[deep.length-1]= all_els_counter; }
}
function getParentElement(){
return els[deep[deep.length-2]] || container;
}
function setShift(shift= 0){
let last;
if(!shift){ last= deep.pop(); deep.push(last, last); }
else deep.splice(deep.length+1+shift);
return component_out;
}
function initStorage(){
const
{ registerToMap, indexGenerator }= component_utils;
let /* storage for component, functions for updates and mapping data keys and corresponding elements */
data, components, els, functions, listeners, getIndex;
internalVars(indexGenerator(0));
return {
register: function(el, init_data, fun){
Object.assign(data, init_data);
const ids= registerToMap(els, el, getIndex)+"_"+registerToMap(functions, fun, getIndex);
const init_data_keys= Object.keys(init_data);
for(let i=0, i_key, i_length= init_data_keys.length; i<i_length; i++){
i_key= init_data_keys[i];
if(!listeners.has(i_key)) listeners.set(i_key, [ ids ]);
else listeners.get(i_key).push(ids);
}
return fun.call(el, init_data) || {};
},
registerComponent: function(update){
if(components.indexOf(update)===-1) components.push(update);
},
update: function(new_data_input){
const new_data= typeof mapUpdate==="function" ? mapUpdate(new_data_input) : new_data_input;
let out= false;
for(let i=0, i_length= components.length; i<i_length; i++){ if(components[i](new_data)&&!out){out=true;} }
if(!listeners.size) return out;
const /* keys to update (subscribers exits and was changed) */
new_data_keys= Object.keys(new_data)
.filter(key=>listeners.has(key)&&data[key]!==new_data[key]),
new_data_keys_length= new_data_keys.length;
if(!new_data_keys_length) return out;
Object.assign(data, new_data);
const els_for_redraw= [];
for(let i=0, i_listeners; i<new_data_keys_length; i++){
i_listeners= listeners.get(new_data_keys[i]);
for(let j=0, ji_listener, j_length= i_listeners.length; j<j_length; j++){
ji_listener= i_listeners[j];
if(els_for_redraw.indexOf(ji_listener)===-1) els_for_redraw.push(ji_listener);
}
}
for(let i=0, i_length= els_for_redraw.length; i<i_length; i++){ processChanges(els_for_redraw[i]); }
return true;
function processChanges(ids){
const [ el_id, fun_id ]= ids.split("_").map(Number);
const el= els.get(el_id);
const new_data= functions.get(fun_id).call(el, data) || {};
if(el.parentNode===null) return unregister(el_id, fun_id, new_data_keys);
assign(el, new_data);
}
},
clear: function(){
internalVars();
},
getData: function(){
return data;
},
unregister
};
function internalVars(initIndex){
data= {};
components= [];
els= new Map();
functions= new Map();
listeners= new Map();
getIndex= initIndex;
}
function unregister(el_id, fun_id, data_keys){
let funcs_counter= 0;
els.delete(el_id);
listeners.forEach(function(listeners_arr, i_key){
if(data_keys.indexOf(i_key)===-1) return listeners_arr.forEach(function(ids){ if(Number(ids.split("_")[1])===fun_id){ funcs_counter+= 1; } });
if(listeners_arr.length===1) listeners.delete(i_key);
else listeners.set(i_key, listeners_arr.filter(el_idFilter));
});
if(!funcs_counter) functions.delete(fun_id);
function el_idFilter(ids){ return Number(ids.split("_")[0])!==el_id; }
}
}
function update(new_data){
if(!internal_storage) return false;
return internal_storage.update(typeof new_data==="function" ? new_data(internal_storage.getData()) : new_data);
}
function isStatic(){
return !internal_storage;
}
};
$dom.componentListener= (function(){
const internal_component_events= [ "oninit", "onmount", "onupdate" ];
const EventListener_interface= {
/*
api: {},
event_function: listener function,
*/
registerListener: function(target_element, api, event_name, event_function, event_options= { passive: true }){
this.api= { getReference: api.getReference, update: api.update, removeEventListener: this.removeEventListener.bind(this) };
this.event_name= event_name;
this.event_function= event_function;
target_element.addEventListener(event_name, this, event_options);
},
removeEventListener: function(){ this.api.getReference().removeEventListener(this.event_name, this); },
handleEvent: function(event){ this.event_function.call(this.api, event); }
};
return function(event_name, ...args){
const event_name_id= internal_component_events.indexOf((/^on/g.test(event_name) ? "" : "on")+event_name);
if(event_name_id===-1) return Object.freeze([ "oninit", [ function(el){ Object.create(EventListener_interface).registerListener(el, this, event_name, ...args); } ] ]);
return Object.freeze([ internal_component_events[event_name_id], args ]);
};
})();
$dom.assign= function(element, ...objects_attributes){
const object_attributes= Object.assign({}, ...objects_attributes);
const object_attributes_keys= Object.keys(object_attributes);
for(let i=0, key, attr, i_length= object_attributes_keys.length; i<i_length; i++){
key= object_attributes_keys[i];
attr= object_attributes[key];
const key_aria_data= /(aria|data)([A-Z])/.test(key) ? key.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase() : false;
if(typeof attr==="undefined"){
if(key_aria_data) element.removeAttribute(key_aria_data);
if(Reflect.has(element, key)) Reflect.deleteProperty(element, key);
continue;
}
switch(key){
case "style":
if(typeof attr==="string") element.setAttribute("style", attr);
else for(let k=0, k_key, k_keys= Object.keys(attr), k_length= k_keys.length; k<k_length; k++){ k_key= k_keys[k]; element.style.setProperty(k_key, attr[k_key]); }
break;
case "style_vars":
for(let k=0, k_key, k_keys= Object.keys(attr), k_length= k_keys.length; k<k_length; k++){ k_key= k_keys[k]; element.style.setProperty(k_key, attr[k_key]); }
break;
case "classList":
if(!element[key].toggle) break;
for(let k=0, k_key, k_attr, k_keys= Object.keys(attr), k_length= k_keys.length; k<k_length; k++){
k_key= k_keys[k]; k_attr= attr[k_key];
if(k_attr===-1) element.classList.toggle(k_key);
else element.classList.toggle(k_key, Boolean(k_attr));
}
break;
case "dataset":
for(let k=0, k_key, k_keys= Object.keys(attr), k_length= k_keys.length; k<k_length; k++){ k_key= k_keys[k]; element.dataset[k_key]= attr[k_key]; }
break;
case "href" || "src" || "class":
element.setAttribute(key, attr);
break;
default:
if(key_aria_data) element.setAttribute(key_aria_data, attr);
else element[key]= attr;
break;
}
}
return element;
};
$dom.assignNS= function(namespace, element, ...objects_attributes){
const on_keys_regexp= /^on[a-z]+/;
const object_attributes= Object.assign({}, ...objects_attributes);
const object_attributes_keys= Object.keys(object_attributes);
for(let i=0, key, attr, i_length= object_attributes_keys.length; i<i_length; i++){
key= object_attributes_keys[i];
attr= object_attributes[key];
if(typeof attr==="undefined"){ if(element.hasAttributeNS(null, key)){ element.removeAttributeNS(null, key); } continue; }
switch(key){
case "textContent" || "innerText":
element.appendChild(document.createTextNode(attr));
break;
case "style":
if(typeof attr==="string") element.setAttributeNS(null, "style", attr);
else for(let k=0, k_key, k_keys= Object.keys(attr), k_length= k_keys.length; k<k_length; k++){ k_key= k_keys[k]; element.style.setProperty(k_key, attr[k_key]); }
break;
case "style_vars":
for(let k=0, k_key, k_keys= Object.keys(attr), k_length= k_keys.length; k<k_length; k++){ k_key= k_keys[k]; element.style.setProperty(k_key, attr[k_key]); }
break;
case "className":
element.setAttributeNS(null, "class", attr);
break;
case "classList":
if(!element[key].toggle) break;
for(let k=0, k_key, k_attr, k_keys= Object.keys(attr), k_length= k_keys.length; k<k_length; k++){
k_key= k_keys[k]; k_attr= attr[k_key];
if(k_attr===-1) element.classList.toggle(k_key);
else element.classList.toggle(k_key, Boolean(k_attr));
}
break;
case "xlink:href":
element.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", attr);
break;
default:
if(on_keys_regexp.test(key)) element[key]= attr;
else element.setAttributeNS(null, key, attr);
break;
}
}
return element;
};
})();
_public.$dom.elementReady_= function(el_selector, parent= document){
const sel_key= Object.keys(el_selector)[0];
const sel_val= el_selector[sel_key];
return new Promise(function(resolve){
function check(){
const el= parent[sel_key](sel_val);
if(el) resolve(el);
else requestAnimationFrame(check); //...zajistuje cyklus
}
requestAnimationFrame(check);
});
};
_public.$dom.forceRedraw= function(element= document.body){
let d= element.style.display;
element.style.display= 'none';
let trick= element.offsetHeight;
element.style.display= d;
//v2
//document.documentElement.style.paddingRight = '1px';
//setTimeout(()=>{document.documentElement.style.paddingRight = '';}, 0);
};
_public.$dom.ready_= function(...args){ return new Promise(function(resolve){
if(document.readyState!=='loading')
return resolve(...args);
document.addEventListener('readystatechange', checkState);
function checkState() {
if(document.readyState==='loading') return;
document.removeEventListener('readystatechange', checkState);
resolve(...args);
}
}); };
_public.$dom.removeElements= function(els_to_delete,from_index,to_index){
from_index= from_index || 0;
to_index= to_index || els_to_delete.length;
let els_array= [];
let j= 0;
for(let i= from_index; i < to_index; i++){els_array[j++]= els_to_delete[i];}
for(let i= 0, i_length= els_array.length; i < i_length; i++){els_array[i].remove();}
};
_public.$function= {};
_public.$function.arguments= function(fun, ...indicies){
if(!indicies.length) return function(...args){ return fun.apply(this, args); };
return function(...args){ return fun.apply(this, indicies.map(v=> args[v])); };
};
_public.$function.bindRight= function(fun, context, ...currentArgs){
return function partiallyApplied(...laterArgs){ return fun.call(context, ...laterArgs, ...currentArgs); };
};
_public.$function.branches= function(reduceFun= (acc, res)=> (acc.push(res), acc), reduceInitValueCreator= ()=> []){
return function mapFunctions(...functions){
return function inputProccess(...inputs){
const finalReduceFun= (acc, fun)=> reduceFun(acc, fun(...inputs));
return functions.reduce(finalReduceFun, typeof reduceInitValueCreator==="function" ? reduceInitValueCreator() : reduceInitValueCreator);
};
};
};
_public.$function.call= function(...args){ return function(fun){ return fun.call(this, ...args); }; };
_public.$function.conditionalCall= function(mixed,fun){
if(!mixed) return false;
if(typeof fun === "function") return fun(mixed);
return mixed;
};
_public.$function.constant= constantArg=> ()=> constantArg;
_public.$function.each= function(...functions){ return function(input){ for(let i=0, i_length= functions.length; i<i_length; i++){ functions[i](input); } }; };
_public.$function.exception= function(_throw){ throw _throw; };
_public.$function.exceptionError= function(message){ throw new Error(message); };
_public.$function.gather= function(fun, ...spliced){
if(!spliced.length) return function(...args){ return fun.call(this, args); };
return function(...args){ args.splice(...spliced); return fun.call(this, args); };
};
_public.$function.identity= id=> id;
_public.$function.ifElse= function(onTrue, onFalse= v=> v, onTest= Boolean){
return function(...val){
if(onTest(...val)) return onTrue(...val);
if(typeof onFalse==="function") return onFalse(...val);
};
};
_public.$function.partial= function(fn, ...currentArgs){
return function partiallyApplied(...laterArgs){ return fn.call(this, ...currentArgs, ...laterArgs); };
};
_public.$function.partialRight= function(fn, ...currentArgs){
return function partiallyApplied(...laterArgs){ return fn.call(this, ...laterArgs, ...currentArgs); };
};
_public.$optimizier= {};
_public.$optimizier.timeoutAnimationFrame= function(f, delay= 150){setTimeout(requestAnimationFrame.bind(null, f),delay);};
_public.$function.schedule= function(functions, {context= window, delay= 150}= {}){
_public.$optimizier.timeoutAnimationFrame(function loop(){
let process= functions.shift();
process.call(context);
if(functions.length > 0) _public.$optimizier.timeoutAnimationFrame(loop, delay);
}, delay);
};
_public.$function.self= function(){ return this; };
_public.$function.sequention= function(...functions){return function(input){
let current= input;
for(let i=0, i_length= functions.length; i<i_length; i++)
current= functions[i].call(this, current);
return current;
}; };
class __sequentionCatch__{
constructor(callback){ this.callback= callback; }
call(context, input){ return this.callback.call(context, input); }
}
_public.$function.sequentionCatch= function(fun= _public.$function.identity){ return new __sequentionCatch__(fun); };
_public.$function.sequentionTry= function(...functions){
const i_length= functions.length;
return function(input){
let current= input, err= false;
for(let i= 0, is_catch; i<i_length; i++){
is_catch= functions[i] instanceof __sequentionCatch__;
if(err&&is_catch){
try{ current= functions[i].call(this, current); err= false; }
catch(e){ current= e; }
} else if(!err&&!is_catch) {
try{ current= functions[i].call(this, current); }
catch(e){ current= e; err= true; }
}
}
if(err) throw current;
return current;
};
};
_public.$function.sideEffect= function(callback){ return function(input){ callback.call(this, input); return input; }; };
_public.$function.spread= function(fun, ...spliced){
if(!spliced.length) return function(args= []){ return fun.apply(this, args); };
return function(args= []){ args.splice(...spliced); return fun.apply(this, args); };
};
_public.$object= {};
_public.$object.each= __objectEach;
_public.$object.eachDynamic= __objectEachDynamic;
function __objectEach(iterable, i_function, scope, share){
const iterable_keys= Object.keys(iterable);
for(let index=0, index_length= iterable_keys.length, key; index<index_length; index++){ key= iterable_keys[index];
share= i_function.call(scope, { item: iterable[key], key, index, share });
}
return share;
}
function __objectEachDynamic(iterable, i_function, scope){
let share;
for(let key in iterable){
if (iterable.hasOwnProperty(key)){
share= i_function.call(scope, { item: iterable[key], key, target: iterable, share });
}
}
return share;
}
_public.$object.assignDescriptor= function(obj, property, descriptor){
if(typeof descriptor==="function") descriptor= descriptor(property);
return Object.defineProperty(obj, property,
Object.assign(Object.getOwnPropertyDescriptor(obj, property), descriptor));
};
_public.$object.fromArray= function(arr, fun= (acc, curr, i)=> acc[""+i]= curr, default_value= {}){
return arr.reduce((acc, curr, i)=>{ fun(acc, curr, i); return acc; }, default_value);
};
_public.$object.hasProp= function(obj, prop){ return Object.prototype.hasOwnProperty.call(obj, prop); };
_public.$object.immutable_keys= function(obj_input={}){
return new Proxy(Object.keys(obj_input).reduce(function(obj,key){obj[key]= obj_input[key]; return obj;},{}),{
get(target, command){
if(Object.keys(target).indexOf(command)!==-1){
return target[command];
} else {
switch(command){
case "set":
return setItemFCE(target);
case "keys":
return function(){return Object.keys(target);};
default:
return;
}
}
},
set(){return false;}
});
function setItemFCE(target){
return function(key, value){
if(Object.keys(target).indexOf(key)!==-1) return false;
target[key]= value;
return true;
};
}
};
_public.$object.method= (methodName, ...args)=> object=> object[methodName](...args);
_public.$object.methodFrom= object=> methodName=> (...args)=> object[methodName](...args);
_public.$object.pluck= key=> object=> object[key];
_public.$object.pluckFrom= object=> key=> object[key];
_public.$object.setter= (setterName, arg)=> object=> (object[setterName]= arg, object);
_public.$object.setterFrom= object=> setter_name=> arg=> (object[setter_name]= arg, object);
_public.$optimizier.debounce= function(func, wait, immediate) {
if(!wait) wait= 150;
var timeout, args, context, timestamp;
return function() {
context= this; args = [].slice.call(arguments, 0);
timestamp= new Date();
let later= function() {
let time_diff= (new Date()) - timestamp;
if (time_diff < wait) {
timeout= setTimeout(later, wait-time_diff);
} else {
timeout= null;
if(!immediate) func.apply(context, args);
}
};
if(immediate&&!timeout) func.apply(context, args);
if(!timeout) timeout= setTimeout(later, wait);
};
};
/* global requestIdleCallback, cancelIdleCallback *///gulp.keep.line
/* see https://github.com/GoogleChromeLabs/idlize/ */
const [ rIC, cIC ]= (supports=> {
if(supports) return [ requestIdleCallback, cancelIdleCallback ];
/* minimal shim */
class IdleDeadline {
constructor(init_time){ this._init_time= init_time; }
get didTimeout(){ return false; }
timeRemaining(){ return Math.max(0, 50 - (now() - this._init_time)); }
}
return [
function requestIdleCallback(callback){
const deadline= new IdleDeadline(now());
return setTimeout(()=> callback(deadline), 0);
},
function cancelIdleCallback(handle){
clearTimeout(handle);
}
];
function now(){ return +(new Date());}
})(typeof requestIdleCallback === 'function');
class IdleValue {
constructor(init, msg= "IdleValue: `init` argument for class constructor must be a function!"){
if(typeof init!=="function") throw new TypeError(msg);
this._init= init;
this._value= undefined;
this._idleHandle= rIC(this.initValue.bind(this));
}
initValue(){
if(!this._init) return this._value;
this._value= this._init();
this._init= undefined;
return this._value;
}
value(){
if(this._value!==undefined) return this._value;
this.cancel();
return this.initValue();
}
cancel(){
if(this._idleHandle){
cIC(this._idleHandle);
this._idleHandle= undefined;
}
return this._value;
}
}
IdleValue.throwErrorIfNotIdleValue= function(candidat, msg){
if(candidat instanceof IdleValue) return true;
throw new Error(msg);
};
_public.$optimizier.setIdleValue= function(initFunction){ return new IdleValue(initFunction, "`setIdleValue`: `initFunction` argument must be a function!"); };
_public.$optimizier.getIdleValue= function(idle_value){ if(IdleValue.throwErrorIfNotIdleValue(idle_value, "`getIdleValue`: Argument `idle_value` is not `IdleValue`!")) return idle_value.value(); };
_public.$optimizier.clearIdleValue= function(idle_value){ if(IdleValue.throwErrorIfNotIdleValue(idle_value, "`clearIdleValue`: Argument `idle_value` is not `IdleValue`!")) idle_value.cancel(); };
_public.$optimizier.once= function(fn, context){
var result;
return function(){
if(fn){
result= fn.apply(context || this, arguments);
fn= null;
}
return result;
};
};
_public.$optimizier.poll_= function(fn, timeout, interval) {
var endTime= Number(new Date()) + (timeout || 2000);
interval= interval || 100;
var checkCondition= function(resolve, reject) {
var result = fn();
if(result) {
resolve(result);
}
else if (Number(new Date()) < endTime) {
setTimeout(checkCondition, interval, resolve, reject);
}
else {
reject(new Error('timed out for ' + fn + ': ' + arguments));
}
};
return new Promise(checkCondition);
};
_public.$optimizier.requestAnimationFrame_= function(input){ return new Promise(function(resolve){ requestAnimationFrame(resolve.bind(this, input)); }); };
_public.$optimizier.setTimeout_= function(timeout= 0){ return (...params)=> new Promise(function(resolve){ setTimeout(resolve, timeout, ...params); }); };
_public.$optimizier.trottle= function(func, cycles_leap){
if(!cycles_leap) cycles_leap= 1;
var args, context, cycle, counter= 0;
function check(){
if(counter===cycles_leap){
counter= 0;
cancelAnimationFrame(cycle);
} else {
cycle= requestAnimationFrame(check);
}