@twobirds/microcomponents
Version:
Micro Components Organization Class
97 lines (78 loc) • 2.12 kB
text/typescript
;
var isBrowser=new Function("try {return this===window;}catch(e){ return false;}");
let nativeEventNames: Set<string> = new Set();
// HTMLElement native event names
if ( isBrowser() ){
Object.keys( HTMLElement.prototype ).filter( key => /^on/.test(key) ).forEach( eventName => nativeEventNames.add( eventName ) );
}
function isDOM(element: { [key:string]: any } ) {
return element && element instanceof HTMLElement;
}
interface McEvent {
data: any;
bubble: string;
}
class McEvent{
#type: string;
#stopped: boolean = false;
#immediateStopped: boolean = false;
constructor( type: string, data: any = {}, bubble: string = 'l' ){
// bubble standard = local only, options = any combination of'uld' characters: up to root, local, down
this.#type = type;
this.data = data;
this.bubble = bubble;
}
get type(): string {
return this.#type;
}
get stopped(): boolean {
return this.#stopped;
}
get immediateStopped(): boolean {
return this.#immediateStopped;
}
stopPropagation(){
this.#stopped = true;
}
stopImmediatePropagation(){
this.stopPropagation();
this.#immediateStopped = true;
}
}
// get all microcomponents from a list of HTMLElements
function getMicroComponents( elements: any[], search: string): any[] {
let mcValues: any[] = [];
elements.forEach( e => {
if (e) {
if (e instanceof HTMLElement) {
const _mc = ( e as any )?._mc;
if ( !search && _mc ) {
mcValues = mcValues.concat(Object.values(( e as any )._mc));
}
else if ( search && _mc && _mc[search] ) {
mcValues.push( _mc[search] );
}
}
}
});
return mcValues;
}
// get all ancestor DOM nodes up to the document root
function traverseNodes(node: { [key:string]: any }, search: string, firstonly = true): any[] {
let mcValues: any[] = [];
while (node) {
if (node._mc) {
if (!search) {
mcValues = mcValues.concat(Object.values(node._mc));
}
else if (search && node._mc[search]) {
mcValues.push(node._mc[search]);
}
if (firstonly)
return mcValues;
}
node = node.parentNode;
}
return mcValues;
}
export { McEvent };