import { DOMEditor as HTMLEditor } from "../dom/DOMEditor"; export type SpecialTemplateSourceElementCallback = (special:string,selector:string,attribute:string) => Node[]; export class SpecialTemplateSourceElement { _specialCallback:SpecialTemplateSourceElementCallback; static assignSpecialTemplateSource( element:Element, callback:SpecialTemplateSourceElementCallback ) { let sp = element as any as SpecialTemplateSourceElement; sp._specialCallback = callback; // console.log( "Adding speical cb to:", element.nodeName ); } static getNodes( element:Element, templateSource:TemplateSource):Node[] { let sp = element as any as SpecialTemplateSourceElement; if ( ! sp._specialCallback ) { console.log( "NOT ASSIGNED SPECIAL:", element.nodeName, templateSource.special, templateSource.selector, templateSource.attribute ); return []; } let special = templateSource.special; let selector = templateSource.selector; let attribute = templateSource.attribute; let result = sp._specialCallback( special, selector, attribute ); //console.log( "LOADED SPECIAL:", templateSource.special, templateSource.selector, templateSource.attribute, "\n>>", result ); return result; } } export class TemplateSource { special:string; selector:string; attribute:string; innerHTML:boolean; defaultValue:string; copyParent:boolean; getInnerHTML( target:Element ) { if ( this.innerHTML ) { return target.innerHTML; } let nodes = this.getNodes( target ); let container = target.ownerDocument.createElement( "div" ) as HTMLElement; nodes.forEach( n => container.appendChild( n ) ); return container.innerHTML; } get emptyNodes():Node[] { if ( this.defaultValue ) { return [ document.createTextNode( this.defaultValue ) ]; } return []; } getNodes( target:Element ):Node[] { if ( this.innerHTML ) { return HTMLEditor.cloneChildren( target ); } else if ( this.special ) { return SpecialTemplateSourceElement.getNodes( target, this ); } else if ( this.attribute ) { let attributTarget = this.selector ? target.querySelector( this.selector ) : target; if ( ! attributTarget ) { return this.emptyNodes; } if ( ! attributTarget.hasAttribute( this.attribute ) ) { return this.emptyNodes; } let attributeValue = attributTarget.getAttribute( this.attribute ); let textNode = target.ownerDocument.createTextNode( attributeValue ); return [ textNode ]; } else { let node = target.querySelector( this.selector ); if ( ! node ) { return this.emptyNodes; } if ( this.copyParent ) { return [ target.ownerDocument.importNode( node, true ) ]; } let nodes = []; for ( let i = 0; i < node.childNodes.length; i++ ) { let clone = target.ownerDocument.importNode( node.childNodes[ i ], true ); nodes.push( clone ); } return nodes; } } }