forked from jaandrle/dollar_dom_component
-
Notifications
You must be signed in to change notification settings - Fork 0
/
$dom_component.js
520 lines (473 loc) · 19.2 KB
/
$dom_component.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
/* jshint esversion: 6,-W097, -W040, browser: true, expr: true, undef: true, maxcomplexity: 19, maxparams: 5, maxdepth: 3 */
init(window);
function init(global){
"use strict";
const $dom= {
empty: function(container){
let len= container.childNodes.length;
while(len--){ container.removeChild(container.lastChild); }
},
mount(element_target, type= "childLast"){
return function mount_inner(element){
if(!(element instanceof Element)){
if(typeof element.mount !== "function") throw new TypeError("`element` must be `Element` or `share` of `$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":
$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;
};
}
};
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;
};
global.$dom= $dom;
}