From 5109d0e7d42cff47db7ec480dbdfc7d9eb1162d6 Mon Sep 17 00:00:00 2001 From: eavichay Date: Wed, 17 May 2017 22:34:51 +0300 Subject: [PATCH] injections --- Slim.js | 48 ++++++++++++++++++++++++---------- Slim.min.js | 2 +- example/tests/test-inject.html | 6 ++--- src/Slim.js | 48 ++++++++++++++++++++++++---------- 4 files changed, 72 insertions(+), 32 deletions(-) diff --git a/Slim.js b/Slim.js index 8a3df3f..acd40db 100644 --- a/Slim.js +++ b/Slim.js @@ -58,8 +58,12 @@ var Slim = function (_CustomElement2) { Slim.__templateDict[_tag] = clazzOrTemplate; } Slim.__prototypeDict[_tag] = clazz; - // window.customElements.define(tag, clazz); - document.registerElement(_tag, clazz); + if (Slim.__prototypeDict['slim-repeat'] === undefined) { + Slim.__initRepeater(); + } + setTimeout(function () { + document.registerElement(_tag, clazz); + }, 0); } //noinspection JSUnusedGlobalSymbols @@ -144,15 +148,18 @@ var Slim = function (_CustomElement2) { if (target.remove) { target.remove(); } - if (!target.remove && target.parentNode) { + if (target.parentNode) { target.parentNode.removeChild(target); - if (target._boundChildren) { - target._boundChildren.forEach(function (child) { - if (child.__ieClone) { - Slim.removeChild(child.__ieClone); - } - }); - } + } + if (target.__ieClone) { + Slim.removeChild(target.__ieClone); + } + if (target._boundChildren) { + target._boundChildren.forEach(function (child) { + if (child.__ieClone) { + Slim.removeChild(child.__ieClone); + } + }); } } @@ -260,6 +267,22 @@ var Slim = function (_CustomElement2) { } return { source: desc, prop: prop, obj: obj }; } + }, { + key: '__inject', + value: function __inject(descriptor) { + try { + descriptor.target[Slim.__dashToCamel(descriptor.attribute)] = Slim.__injections[descriptor.factory](descriptor.target); + } catch (err) { + console.error('Could not inject ' + descriptor.attribute + ' into ' + descriptor.target); + console.info('Descriptor ', descriptor); + throw err; + } + } + }, { + key: 'inject', + value: function inject(name, injector) { + Slim.__injections[name] = injector; + } /** * @@ -270,9 +293,6 @@ var Slim = function (_CustomElement2) { }, { key: '__createRepeater', value: function __createRepeater(descriptor) { - if (Slim.__prototypeDict['slim-repeat'] === undefined) { - Slim.__initRepeater(); - } var repeater = void 0; repeater = document.createElement('slim-repeat'); repeater.sourceNode = descriptor.target; @@ -1130,7 +1150,6 @@ var Slim = function (_CustomElement2) { }, { key: 'extract', value: function extract(target, expression) { - var rxInject = Slim.rxInject.exec(expression); var rxProp = Slim.rxProp.exec(expression); var rxMethod = Slim.rxMethod.exec(expression); @@ -1217,6 +1236,7 @@ Slim.__customAttributeProcessors = {}; Slim.__prototypeDict = {}; Slim.__uqIndex = 0; Slim.__templateDict = {}; +Slim.__injections = {}; Slim.__plugins = { 'create': [], 'beforeRender': [], diff --git a/Slim.min.js b/Slim.min.js index 7da3863..231cfa8 100644 --- a/Slim.min.js +++ b/Slim.min.js @@ -1 +1 @@ -"use strict";var _createClass=function(){function defineProperties(target,props){for(var i=0;i')}},{key:"tag",value:function tag(_tag,clazzOrTemplate,clazz){if(clazz===undefined){clazz=clazzOrTemplate}else{Slim.__templateDict[_tag]=clazzOrTemplate}Slim.__prototypeDict[_tag]=clazz;document.registerElement(_tag,clazz)}},{key:"getTag",value:function getTag(clazz){for(var tag in Slim.__prototypeDict){if(Slim.__prototypeDict[tag]===clazz)return tag}}},{key:"__createUqIndex",value:function __createUqIndex(){Slim.__uqIndex++;return Slim.__uqIndex.toString(16)}},{key:"plugin",value:function plugin(phase,_plugin){if(["create","beforeRender","beforeRemove","afterRender"].indexOf(phase)===-1){throw"Supported phase can be create, beforeRemove, beforeRender or afterRender only"}Slim.__plugins[phase].push(_plugin)}},{key:"registerCustomAttribute",value:function registerCustomAttribute(attr,fn){Slim.__customAttributeProcessors[attr]=Slim.__customAttributeProcessors[attr]||[];Slim.__customAttributeProcessors[attr].push(fn)}},{key:"__runPlugins",value:function __runPlugins(phase,element){Slim.__plugins[phase].forEach(function(fn){fn(element)})}},{key:"removeChild",value:function removeChild(target){if(target.remove){target.remove()}if(!target.remove&&target.parentNode){target.parentNode.removeChild(target);if(target._boundChildren){target._boundChildren.forEach(function(child){if(child.__ieClone){Slim.removeChild(child.__ieClone)}})}}}},{key:"__moveChildrenBefore",value:function __moveChildrenBefore(source,target,activate){while(source.firstChild){target.parentNode.insertBefore(source.firstChild,target)}var children=Slim.selectorToArr(target,"*");var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=children[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var child=_step.value;if(activate&&child.isSlim){child.createdCallback()}}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}}},{key:"__moveChildren",value:function __moveChildren(source,target,activate){while(source.firstChild){target.appendChild(source.firstChild)}var children=Slim.selectorToArr(target,"*");var _iteratorNormalCompletion2=true;var _didIteratorError2=false;var _iteratorError2=undefined;try{for(var _iterator2=children[Symbol.iterator](),_step2;!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=true){var child=_step2.value;if(activate&&child.isSlim){child.createdCallback()}}}catch(err){_didIteratorError2=true;_iteratorError2=err}finally{try{if(!_iteratorNormalCompletion2&&_iterator2.return){_iterator2.return()}}finally{if(_didIteratorError2){throw _iteratorError2}}}}},{key:"__lookup",value:function __lookup(obj,desc){var arr=desc.split(".");var prop=arr[0];while(arr.length&&obj){obj=obj[prop=arr.shift()]}return{source:desc,prop:prop,obj:obj}}},{key:"__createRepeater",value:function __createRepeater(descriptor){if(Slim.__prototypeDict["slim-repeat"]===undefined){Slim.__initRepeater()}var repeater=void 0;repeater=document.createElement("slim-repeat");repeater.sourceNode=descriptor.target;descriptor.target.repeater=repeater;descriptor.target.parentNode.insertBefore(repeater,descriptor.target);descriptor.repeater=repeater;repeater._boundParent=descriptor.source;descriptor.target.parentNode.removeChild(descriptor.target);repeater._isAdjacentRepeater=descriptor.repeatAdjacent;repeater.setAttribute("source",descriptor.properties[0]);repeater.setAttribute("target-attr",descriptor.targetAttribute);descriptor.repeater=repeater}},{key:"__dashToCamel",value:function __dashToCamel(dash){return dash.indexOf("-")<0?dash:dash.replace(/-[a-z]/g,function(m){return m[1].toUpperCase()})}},{key:"__camelToDash",value:function __camelToDash(camel){return camel.replace(/([A-Z])/g,"-$1").toLowerCase()}},{key:"interactionEventNames",get:function get(){return["click","mouseover","mouseout","mousemove","mouseenter","mousedown","mouseup","dblclick","contextmenu","wheel","mouseleave","select","pointerlockchange","pointerlockerror","focus","blur","input","error","invalid","animationstart","animationend","animationiteration","reset","submit","resize","scroll","keydown","keypress","keyup","change"]}}]);function Slim(){_classCallCheck(this,Slim);var _this=_possibleConstructorReturn(this,(Slim.__proto__||Object.getPrototypeOf(Slim)).call(this));_this.createdCallback();return _this}_createClass(Slim,[{key:"find",value:function find(selector){return this.rootElement.querySelector(selector)}},{key:"findAll",value:function findAll(selector){return Slim.selectorToArr(this.rootElemnt,selector)}},{key:"watch",value:function watch(prop,executor){var descriptor={type:"W",properties:[prop],executor:executor,target:this,source:this};this._bindings=this._bindings||{};this._boundParent=this._boundParent||this;this.__bind(descriptor)}},{key:"callAttribute",value:function callAttribute(attributeName,value){if(!this._boundParent){throw"Unable to call attribute-bound method when no bound parent available"}var fnName=this.getAttribute(attributeName);if(fnName===null){console.warn&&console.warn("Unable to call null attribute-bound method on bound parent "+this._boundParent.outerHTML);return}if(typeof this._boundParent[fnName]==="function"){this._boundParent[fnName](value)}else if(this._boundParent&&this._boundParent._boundParent&&typeof this._boundParent._boundParent[fnName]==="function"){this._boundParent._boundParent[fnName](value)}else if(this._boundRepeaterParent&&typeof this._boundRepeaterParent[fnName]==="function"){this._boundRepeaterParent[fnName](value)}else{throw"Unable to call attribute-bound method: "+fnName+" on bound parent "+this._boundParent.outerHTML+" with value "+value}if(typeof this.update==="function"&&(this.isInteractive||Slim.autoAttachInteractionEvents||this.getAttribute("interactive"))){this.update()}}},{key:"__propertyChanged",value:function __propertyChanged(property,value){if(typeof this[property+"Changed"]==="function"){this[property+"Changed"](value)}}},{key:"__bind",value:function __bind(descriptor){descriptor.properties.forEach(function(prop){var rootProp=void 0;if(prop.indexOf(".")>0){rootProp=prop.split(".")[0]}else{rootProp=prop}var source=descriptor.source||descriptor.target._boundParent||descriptor.parentNode;source._bindings=source._bindings||{};source._bindings[rootProp]=source._bindings[rootProp]||{value:source[rootProp],executors:[]};if(!source.__lookupGetter__(rootProp))source.__defineGetter__(rootProp,function(){return this._bindings[rootProp].value});if(!source.__lookupSetter__(rootProp))source.__defineSetter__(rootProp,function(x){this._bindings[rootProp].value=x;if(descriptor.sourceText){descriptor.target.innerText=descriptor.sourceText}this._executeBindings(rootProp);this.__propertyChanged(rootProp,x)});var executor=void 0;if(descriptor.type==="C"){executor=function executor(){descriptor.executor()}}else if(descriptor.type==="P"){executor=function executor(){var targets=void 0;if(!descriptor.target.hasAttribute("slim-repeat")){targets=[descriptor.target]}else{targets=descriptor.target.repeater.clones}if(targets){var sourceRef=descriptor.target._boundRepeaterParent;var value=Slim.__lookup(sourceRef||source,prop).obj||Slim.__lookup(descriptor.target,prop).obj;var attrName=Slim.__dashToCamel(descriptor.attribute);targets.forEach(function(target){target[attrName]=value;target.setAttribute(descriptor.attribute,value)})}}}else if(descriptor.type==="M"){executor=function executor(){var targets=[descriptor.target];if(descriptor.target.hasAttribute("slim-repeat")){targets=descriptor.target.repeater.clones}var sourceRef=descriptor.target._boundRepeaterParent||source;var value=sourceRef[descriptor.method].apply(sourceRef,descriptor.properties.map(function(prop){return descriptor.target[prop]||sourceRef[prop]}));var attrName=Slim.__dashToCamel(descriptor.attribute);targets.forEach(function(target){target[attrName]=value;target.setAttribute(descriptor.attribute,value)})}}else if(descriptor.type==="T"){executor=function executor(){var source=descriptor.target._boundParent;descriptor.target._innerText=descriptor.target._innerText.replace("[["+prop+"]]",Slim.__lookup(source,prop).obj)}}else if(descriptor.type==="TM"){executor=function executor(){var values=descriptor.properties.map(function(compoundProp){return Slim.__lookup(source,compoundProp).obj});try{var value=source[descriptor.methodName].apply(source,values);descriptor.target._innerText=descriptor.target._innerText.replace(descriptor.expression,value)}catch(exc){console.error("Could not execute function "+descriptor.methodName+" in element "+descriptor.source.localName);console.info(exc)}}}else if(descriptor.type==="R"){executor=function executor(){descriptor.repeater.unregister();descriptor.repeater.renderList()}}else if(descriptor.type==="W"){executor=function executor(){descriptor.executor(Slim.__lookup(source,prop).obj)}}else if(descriptor.type==="F"){executor=function executor(){var value=!!Slim.__lookup(descriptor.source,prop).obj;if(descriptor.reversed){value=!value}if(!value){if(descriptor.target.parentNode){descriptor.target.insertAdjacentElement("beforeBegin",descriptor.helper);Slim.removeChild(descriptor.target)}}else{if(!descriptor.target.parentNode){descriptor.helper.insertAdjacentElement("beforeBegin",descriptor.target);if(descriptor.target.isSlim){descriptor.target.createdCallback()}Slim.removeChild(descriptor.helper)}}}}executor.descriptor=descriptor;source._bindings[rootProp].executors.push(executor)})}},{key:"createdCallback",value:function createdCallback(){if(this.isVirtual)return;if(this.__createdCallbackRunOnce)return;this.__createdCallbackRunOnce=true;this.initialize();this.onBeforeCreated();this._captureBindings();Slim.__runPlugins("create",this);this.onCreated();this.__onCreatedComplete=true;this.onBeforeRender();Slim.__runPlugins("beforeRender",this);Slim.__moveChildren(this._virtualDOM,this.rootElement,true);this.onAfterRender();Slim.__runPlugins("afterRender",this);this.update()}},{key:"detachedCallback",value:function detachedCallback(){Slim.__runPlugins("beforeRemove",this);this.onRemoved()}},{key:"_initInteractiveEvents",value:function _initInteractiveEvents(){var _this2=this;if(!this.__eventsInitialized&&(Slim.autoAttachInteractionEvents||this.isInteractive||this.hasAttribute("interactive")))Slim.interactionEventNames.forEach(function(eventType){_this2.addEventListener(eventType,function(e){_this2.handleEvent(e)})})}},{key:"initialize",value:function initialize(){this.uq_index=Slim.__createUqIndex();this.setAttribute("slim-uq",this.uq_index);this._bindings=this._bindings||{};this._boundChildren=this._boundChildren||[];this._initInteractiveEvents();this.__eventsInitialized=true;this.alternateTemplate=this.alternateTemplate||null;this._virtualDOM=this._virtualDOM||document.createDocumentFragment()}},{key:"handleEvent",value:function handleEvent(e){if(this.hasAttribute("on"+e.type)){this.callAttribute("on"+e.type,e)}else if(this.hasAttribute(e.type)){this.callAttribute(e.type,e)}}},{key:"connectedCallback",value:function connectedCallback(){this.attachedCallback()}},{key:"disconnectedCallback",value:function disconnectedCallback(){this.detachedCallback()}},{key:"attachedCallback",value:function attachedCallback(){this.onAdded()}},{key:"attributeChangedCallback",value:function attributeChangedCallback(attr,oldValue,newValue){if(oldValue===newValue)return;if(!this._bindings)return;if(this._bindings[attr]){this[Slim.__dashToCamel(attr)]=newValue}}},{key:"onAdded",value:function onAdded(){}},{key:"onRemoved",value:function onRemoved(){}},{key:"onBeforeCreated",value:function onBeforeCreated(){}},{key:"onCreated",value:function onCreated(){}},{key:"onBeforeRender",value:function onBeforeRender(){}},{key:"onAfterRender",value:function onAfterRender(){}},{key:"onBeforeUpdate",value:function onBeforeUpdate(){}},{key:"onAfterUpdate",value:function onAfterUpdate(){}},{key:"update",value:function update(){this.onBeforeUpdate();this._executeBindings();this.onAfterUpdate()}},{key:"render",value:function render(template){Slim.__runPlugins("beforeRender",this);this.onBeforeRender();this.alternateTemplate=template;this.initialize();this.rootElement.innerHTML="";this._captureBindings();this._executeBindings();Slim.__moveChildren(this._virtualDOM,this.rootElement,true);this.onAfterRender();Slim.__runPlugins("afterRender",this)}},{key:"_executeBindings",value:function _executeBindings(prop){var _this3=this;if(!this._bindings)return;this._boundChildren.forEach(function(child){if(child.hasAttribute("bind")&&child.sourceText!==undefined){child._innerText=child.sourceText}});var properties=prop?[prop]:Object.keys(this._bindings);properties.forEach(function(property){_this3._bindings[property].executors.forEach(function(fn){if(fn.descriptor.type!=="T"&&fn.descriptor.type!=="TM")fn()})});Object.keys(this._bindings).forEach(function(property){_this3._bindings[property].executors.forEach(function(fn){if(fn.descriptor.type==="T"||fn.descriptor.type==="TM"){fn()}});_this3._bindings[property].executors.forEach(function(fn){if(fn.descriptor.type==="T"||fn.descriptor.type==="TM"){fn.descriptor.target.innerText=fn.descriptor.target._innerText;if(fn.descriptor.target.__ieClone){fn.descriptor.target.__ieClone.innerText=fn.descriptor.target.innerText}}})})}},{key:"_captureBindings",value:function _captureBindings(){var _this4=this;var self=this;var $tpl=this.alternateTemplate||this.template;if(!$tpl){while(this.firstChild){self._virtualDOM=this._virtualDOM||document.createDocumentFragment();self._virtualDOM.appendChild(this.firstChild)}}else if(typeof $tpl==="string"){var frag=document.createRange().createContextualFragment($tpl);while(frag.firstChild){this._virtualDOM.appendChild(frag.firstChild)}var virtualContent=this._virtualDOM.querySelector("slim-content");if(virtualContent){while(self.firstChild){self.firstChild._boundParent=this.firstChild._boundParent||this;virtualContent.appendChild(this.firstChild)}}}var allChildren=Slim.selectorToArr(this._virtualDOM,"*");var _iteratorNormalCompletion3=true;var _didIteratorError3=false;var _iteratorError3=undefined;try{for(var _iterator3=allChildren[Symbol.iterator](),_step3;!(_iteratorNormalCompletion3=(_step3=_iterator3.next()).done);_iteratorNormalCompletion3=true){var child=_step3.value;if(child._boundP)continue;child._boundP=true;child._sourceOuterHTML=child.outerHTML;child._boundParent=child._boundParent||this;self._boundChildren=this._boundChildren||[];self._boundChildren.push(child);self._boundChildren.push(child);if(child.localName==="style"&&this.useShadow){Slim.__processStyleNode(child,this.localName,this.uq_index)}if(child.getAttribute("slim-id")){child._boundParent[Slim.__dashToCamel(child.getAttribute("slim-id"))]=child}var slimID=child.getAttribute("slim-id");if(slimID)this[slimID]=child;var descriptors=[];if(child.attributes)for(var i=0;i=0){child.isInteractive=true;child.handleEvent=self.handleEvent.bind(child);child.callAttribute=self.callAttribute.bind(child);child.addEventListener(child.attributes[i].nodeName,child.handleEvent);child.__eventsInitialized=true}var desc=Slim.__processAttribute(child.attributes[i],child);if(desc)descriptors.push(desc);child[Slim.__dashToCamel(child.attributes[i].nodeName)]=child.attributes[i].nodeValue;if(child.attributes[i].nodeName.indexOf("#")=="0"){var refName=child.attributes[i].nodeName.slice(1);this[refName]=child}}descriptors=descriptors.sort(function(a){if(a.type==="I"){return-1}else if(a.type==="R")return 1;else if(a.type==="C")return 2;return 0});descriptors.forEach(function(descriptor){if(descriptor.type==="P"||descriptor.type==="M"||descriptor.type==="C"){_this4.__bind(descriptor)}else if(descriptor.type==="I"){Slim.__inject(descriptor)}else if(descriptor.type==="R"){Slim.__createRepeater(descriptor);_this4.__bind(descriptor)}else if(descriptor.type==="F"){_this4.__bind(descriptor)}})}}catch(err){_didIteratorError3=true;_iteratorError3=err}finally{try{if(!_iteratorNormalCompletion3&&_iterator3.return){_iterator3.return()}}finally{if(_didIteratorError3){throw _iteratorError3}}}allChildren=Slim.selectorToArr(this._virtualDOM,"*[bind]");var _loop=function _loop(_child){if(_child._boundTM)return"continue";_child._boundTM=true;var match=_child.innerText.match(/\[\[(\w+)\((.+)\)]\]/g);if(match){match.forEach(function(expression){var matches=expression.match(Slim.rxMethod);var methodName=matches[1];var props=matches[3].split(" ").join("").split(",");var descriptor={type:"TM",properties:props,target:_child,expression:expression,source:_child._boundParent,sourceText:_child.innerText,methodName:methodName};_child.sourceText=_child.innerText;_this4.__bind(descriptor)})}};var _iteratorNormalCompletion4=true;var _didIteratorError4=false;var _iteratorError4=undefined;try{for(var _iterator4=allChildren[Symbol.iterator](),_step4;!(_iteratorNormalCompletion4=(_step4=_iterator4.next()).done);_iteratorNormalCompletion4=true){var _child=_step4.value;var _ret=_loop(_child);if(_ret==="continue")continue}}catch(err){_didIteratorError4=true;_iteratorError4=err}finally{try{if(!_iteratorNormalCompletion4&&_iterator4.return){_iterator4.return()}}finally{if(_didIteratorError4){throw _iteratorError4}}}var _iteratorNormalCompletion5=true;var _didIteratorError5=false;var _iteratorError5=undefined;try{for(var _iterator5=allChildren[Symbol.iterator](),_step5;!(_iteratorNormalCompletion5=(_step5=_iterator5.next()).done);_iteratorNormalCompletion5=true){var _child2=_step5.value;if(_child2._boundT)continue;_child2._boundT=true;var _match=_child2.innerText.match(/\[\[([\w|.]+)\]\]/g);if(_match&&_child2.children.firstChild){throw"Bind Error: Illegal bind attribute use on element type "+_child2.localName+" with nested children.\n"+_child2.outerHTML}if(_match){var properties=[];for(var _i=0;_i<_match.length;_i++){var lookup=_match[_i].match(/([^\[].+[^\]])/)[0];properties.push(lookup)}var descriptor={type:"T",properties:properties,target:_child2,sourceText:_child2.innerText};_child2.sourceText=_child2.innerText;this.__bind(descriptor)}}}catch(err){_didIteratorError5=true;_iteratorError5=err}finally{try{if(!_iteratorNormalCompletion5&&_iterator5.return){_iterator5.return()}}finally{if(_didIteratorError5){throw _iteratorError5}}}}},{key:"isVirtual",get:function get(){var node=this;while(node){node=node.parentNode;if(!node){return true}if(node.nodeName==="BODY"||node.host){return false}}return true}},{key:"useShadow",get:function get(){return false}},{key:"rootElement",get:function get(){if(this.useShadow&&this.createShadowRoot){this.__shadowRoot=this.__shadowRoot||this.createShadowRoot();return this.__shadowRoot}return this}},{key:"isSlim",get:function get(){return true}},{key:"template",get:function get(){return Slim.__templateDict[this.nodeName.toLowerCase()]||null}},{key:"isInteractive",get:function get(){return false}}],[{key:"__processStyleNode",value:function __processStyleNode(node,tag,uqIndex){if(Slim.__isWCSupported)return;var rxRules=/([^\r\n,{}]+)(,(?=[^}]*{)|\s*{)/g;var unique_index=node._boundParent.uq_index;var match=node.innerText.match(rxRules);if(match){match.forEach(function(selector){if(selector.indexOf(":host")<0){node.innerText=node.innerText.replace(selector,":host "+selector)}})}var customTagName=tag+'[slim-uq="'+uqIndex+'"]';node.innerText=node.innerText.replace(/\:host/g,customTagName);if(Slim.__isIE11){var ieClone=document.createElement("style");ieClone.type="text/css";node.__ieClone=ieClone;ieClone.innerText=node.innerText;while(ieClone.innerText.indexOf(" ")>=0){ieClone.innerText=ieClone.innerText.replace(" "," ")}document.head.appendChild(ieClone)}}},{key:"__processRepeater",value:function __processRepeater(attribute,child){return{type:"R",target:child,targetAttribute:child.getAttribute("slim-repeat-as")?child.getAttribute("slim-repeat-as"):"data",repeatAdjacent:child.hasAttribute("slim-repeat-adjacent")||child.localName==="option"||child.localName==="tr"||child.localName==="td",attribute:attribute.nodeName,properties:[attribute.nodeValue],source:child._boundParent}}},{key:"__processCustomAttribute",value:function __processCustomAttribute(attribute,child){return{type:"C",target:child,properties:[attribute.nodeValue],executor:function executor(){Slim.__customAttributeProcessors[attribute.nodeName].forEach(function(customAttrProcessor){customAttrProcessor(child,attribute.nodeValue)})}}}},{key:"extract",value:function extract(target,expression){var rxInject=Slim.rxInject.exec(expression);var rxProp=Slim.rxProp.exec(expression);var rxMethod=Slim.rxMethod.exec(expression);if(rxProp){return target[rxProp[1]]}else if(rxMethod){return target[rxMethod[1]].apply(target,rxMethod[3].replace(" ","").split(","))}}},{key:"__processAttribute",value:function __processAttribute(attribute,child){if(attribute.nodeName==="slim-repeat"){return Slim.__processRepeater(attribute,child)}if(attribute.nodeName==="slim-if"){var propertyName=attribute.nodeValue;var reverse=false;if(attribute.nodeValue.charAt(0)==="!"){propertyName=propertyName.slice(1);reverse=true}return{type:"F",target:child,source:child._boundParent,helper:document.createElement("slim-if-helper"),reversed:reverse,properties:[propertyName]}}if(Slim.__customAttributeProcessors[attribute.nodeName]){return Slim.__processCustomAttribute(attribute,child)}var rxInject=Slim.rxInject.exec(attribute.nodeValue);var rxProp=Slim.rxProp.exec(attribute.nodeValue);var rxMethod=Slim.rxMethod.exec(attribute.nodeValue);if(rxMethod){return{type:"M",target:child,attribute:attribute.nodeName,method:rxMethod[1],properties:rxMethod[3].replace(" ","").split(",")}}else if(rxProp){return{type:"P",target:child,attribute:attribute.nodeName,properties:[rxProp[1]]}}else if(rxInject){return{type:"I",target:child,attribute:attribute.nodeName,factory:rxInject[1]}}}}]);return Slim}(_CustomElement);Slim.rxInject=/\{(.+[^(\((.+)\))])\}/;Slim.rxProp=/\[\[(.+[^(\((.+)\))])\]\]/;Slim.rxMethod=/\[\[(.+)(\((.+)\)){1}\]\]/;Slim.__customAttributeProcessors={};Slim.__prototypeDict={};Slim.__uqIndex=0;Slim.__templateDict={};Slim.__plugins={create:[],beforeRender:[],afterRender:[],beforeRemove:[]};try{Slim.__isWCSupported=function(){return"registerElement"in document&&"import"in document.createElement("link")&&"content"in document.createElement("template")}()}catch(err){Slim.__isWCSupported=false}try{Slim.__isIE11=function(){return!!window["MSInputMethodContext"]&&!!document["documentMode"]}()}catch(err){Slim.__isIE11=false}if(Slim.__isWCSupported){Slim.selectorToArr=function(target,selector){return target.querySelectorAll(selector)}}else{Slim.selectorToArr=function(target,selector){return Array.prototype.slice.call(target.querySelectorAll(selector))}}Slim.__initRepeater=function(){var SlimRepeater=function(_Slim){_inherits(SlimRepeater,_Slim);function SlimRepeater(){_classCallCheck(this,SlimRepeater);return _possibleConstructorReturn(this,(SlimRepeater.__proto__||Object.getPrototypeOf(SlimRepeater)).apply(this,arguments))}_createClass(SlimRepeater,[{key:"onBeforeCreated",value:function onBeforeCreated(){this.clones=[]}},{key:"onAdded",value:function onAdded(){if(!this.uq_index){this.createdCallback()}this.renderList()}},{key:"onRemoved",value:function onRemoved(){this.sourceData.unregisterSlimRepeater(this)}},{key:"registerForRender",value:function registerForRender(){var _this6=this;if(this.pendingRender)return;this.pendingRender=true;setTimeout(function(){_this6.checkoutRender()},0)}},{key:"checkoutRender",value:function checkoutRender(){this.pendingRender=false;this.renderList()}},{key:"unregister",value:function unregister(){this.sourceData.unregisterSlimRepeater(this)}},{key:"clearList",value:function clearList(){this.clones&&this.clones.forEach(function(clone){Slim.removeChild(clone)});this.clones=[];this._boundChildren=[]}},{key:"removeClone",value:function removeClone(clone){var _this7=this;Slim.removeChild(clone);Slim.selectorToArr(clone,"*").forEach(function(child){_this7._boundChildren.splice(_this7._boundChildren.indexOf(child),1)});this._boundChildren.splice(this._boundChildren.indexOf(clone),1)}},{key:"updateList",value:function updateList(){var _this8=this;var targetPropName=this.getAttribute("target-attr");this.clones.forEach(function(clone,idx){var data=_this8.sourceData[idx];if(clone[targetPropName]===data)return;clone[targetPropName]=data;Slim.selectorToArr(clone,"*").forEach(function(child){child[targetPropName]=data})})}},{key:"renderList",value:function renderList(){var _this9=this;this.sourceData.registerSlimRepeater(this);if(!this.sourceNode)return;if(this.sourceData.length===0){this.clearList();return}else if(this.clones&&this.clones.length===this.sourceData.length){this.updateList();this._executeBindings();return}else if(this.clones&&this.clones.length>this.sourceData.length){this.updateList();var leftovers=this.clones.splice(this.sourceData.length);leftovers.forEach(function(leftover){_this9.removeClone(leftover)});this._executeBindings();return}else if(this.clones&&this.clones.length=0){this.registeredSlimRepeaters.splice(this.registeredSlimRepeaters.indexOf(repeater),1)}}})();if(typeof module!=="undefined"&&module.exports){module.exports.Slim=Slim} \ No newline at end of file +"use strict";var _createClass=function(){function defineProperties(target,props){for(var i=0;i')}},{key:"tag",value:function tag(_tag,clazzOrTemplate,clazz){if(clazz===undefined){clazz=clazzOrTemplate}else{Slim.__templateDict[_tag]=clazzOrTemplate}Slim.__prototypeDict[_tag]=clazz;if(Slim.__prototypeDict["slim-repeat"]===undefined){Slim.__initRepeater()}setTimeout(function(){document.registerElement(_tag,clazz)},0)}},{key:"getTag",value:function getTag(clazz){for(var tag in Slim.__prototypeDict){if(Slim.__prototypeDict[tag]===clazz)return tag}}},{key:"__createUqIndex",value:function __createUqIndex(){Slim.__uqIndex++;return Slim.__uqIndex.toString(16)}},{key:"plugin",value:function plugin(phase,_plugin){if(["create","beforeRender","beforeRemove","afterRender"].indexOf(phase)===-1){throw"Supported phase can be create, beforeRemove, beforeRender or afterRender only"}Slim.__plugins[phase].push(_plugin)}},{key:"registerCustomAttribute",value:function registerCustomAttribute(attr,fn){Slim.__customAttributeProcessors[attr]=Slim.__customAttributeProcessors[attr]||[];Slim.__customAttributeProcessors[attr].push(fn)}},{key:"__runPlugins",value:function __runPlugins(phase,element){Slim.__plugins[phase].forEach(function(fn){fn(element)})}},{key:"removeChild",value:function removeChild(target){if(target.remove){target.remove()}if(target.parentNode){target.parentNode.removeChild(target)}if(target.__ieClone){Slim.removeChild(target.__ieClone)}if(target._boundChildren){target._boundChildren.forEach(function(child){if(child.__ieClone){Slim.removeChild(child.__ieClone)}})}}},{key:"__moveChildrenBefore",value:function __moveChildrenBefore(source,target,activate){while(source.firstChild){target.parentNode.insertBefore(source.firstChild,target)}var children=Slim.selectorToArr(target,"*");var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=children[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var child=_step.value;if(activate&&child.isSlim){child.createdCallback()}}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}}},{key:"__moveChildren",value:function __moveChildren(source,target,activate){while(source.firstChild){target.appendChild(source.firstChild)}var children=Slim.selectorToArr(target,"*");var _iteratorNormalCompletion2=true;var _didIteratorError2=false;var _iteratorError2=undefined;try{for(var _iterator2=children[Symbol.iterator](),_step2;!(_iteratorNormalCompletion2=(_step2=_iterator2.next()).done);_iteratorNormalCompletion2=true){var child=_step2.value;if(activate&&child.isSlim){child.createdCallback()}}}catch(err){_didIteratorError2=true;_iteratorError2=err}finally{try{if(!_iteratorNormalCompletion2&&_iterator2.return){_iterator2.return()}}finally{if(_didIteratorError2){throw _iteratorError2}}}}},{key:"__lookup",value:function __lookup(obj,desc){var arr=desc.split(".");var prop=arr[0];while(arr.length&&obj){obj=obj[prop=arr.shift()]}return{source:desc,prop:prop,obj:obj}}},{key:"__inject",value:function __inject(descriptor){try{descriptor.target[Slim.__dashToCamel(descriptor.attribute)]=Slim.__injections[descriptor.factory](descriptor.target)}catch(err){console.error("Could not inject "+descriptor.attribute+" into "+descriptor.target);console.info("Descriptor ",descriptor);throw err}}},{key:"inject",value:function inject(name,injector){Slim.__injections[name]=injector}},{key:"__createRepeater",value:function __createRepeater(descriptor){var repeater=void 0;repeater=document.createElement("slim-repeat");repeater.sourceNode=descriptor.target;descriptor.target.repeater=repeater;descriptor.target.parentNode.insertBefore(repeater,descriptor.target);descriptor.repeater=repeater;repeater._boundParent=descriptor.source;descriptor.target.parentNode.removeChild(descriptor.target);repeater._isAdjacentRepeater=descriptor.repeatAdjacent;repeater.setAttribute("source",descriptor.properties[0]);repeater.setAttribute("target-attr",descriptor.targetAttribute);descriptor.repeater=repeater}},{key:"__dashToCamel",value:function __dashToCamel(dash){return dash.indexOf("-")<0?dash:dash.replace(/-[a-z]/g,function(m){return m[1].toUpperCase()})}},{key:"__camelToDash",value:function __camelToDash(camel){return camel.replace(/([A-Z])/g,"-$1").toLowerCase()}},{key:"interactionEventNames",get:function get(){return["click","mouseover","mouseout","mousemove","mouseenter","mousedown","mouseup","dblclick","contextmenu","wheel","mouseleave","select","pointerlockchange","pointerlockerror","focus","blur","input","error","invalid","animationstart","animationend","animationiteration","reset","submit","resize","scroll","keydown","keypress","keyup","change"]}}]);function Slim(){_classCallCheck(this,Slim);var _this=_possibleConstructorReturn(this,(Slim.__proto__||Object.getPrototypeOf(Slim)).call(this));_this.createdCallback();return _this}_createClass(Slim,[{key:"find",value:function find(selector){return this.rootElement.querySelector(selector)}},{key:"findAll",value:function findAll(selector){return Slim.selectorToArr(this.rootElemnt,selector)}},{key:"watch",value:function watch(prop,executor){var descriptor={type:"W",properties:[prop],executor:executor,target:this,source:this};this._bindings=this._bindings||{};this._boundParent=this._boundParent||this;this.__bind(descriptor)}},{key:"callAttribute",value:function callAttribute(attributeName,value){if(!this._boundParent){throw"Unable to call attribute-bound method when no bound parent available"}var fnName=this.getAttribute(attributeName);if(fnName===null){console.warn&&console.warn("Unable to call null attribute-bound method on bound parent "+this._boundParent.outerHTML);return}if(typeof this._boundParent[fnName]==="function"){this._boundParent[fnName](value)}else if(this._boundParent&&this._boundParent._boundParent&&typeof this._boundParent._boundParent[fnName]==="function"){this._boundParent._boundParent[fnName](value)}else if(this._boundRepeaterParent&&typeof this._boundRepeaterParent[fnName]==="function"){this._boundRepeaterParent[fnName](value)}else{throw"Unable to call attribute-bound method: "+fnName+" on bound parent "+this._boundParent.outerHTML+" with value "+value}if(typeof this.update==="function"&&(this.isInteractive||Slim.autoAttachInteractionEvents||this.getAttribute("interactive"))){this.update()}}},{key:"__propertyChanged",value:function __propertyChanged(property,value){if(typeof this[property+"Changed"]==="function"){this[property+"Changed"](value)}}},{key:"__bind",value:function __bind(descriptor){descriptor.properties.forEach(function(prop){var rootProp=void 0;if(prop.indexOf(".")>0){rootProp=prop.split(".")[0]}else{rootProp=prop}var source=descriptor.source||descriptor.target._boundParent||descriptor.parentNode;source._bindings=source._bindings||{};source._bindings[rootProp]=source._bindings[rootProp]||{value:source[rootProp],executors:[]};if(!source.__lookupGetter__(rootProp))source.__defineGetter__(rootProp,function(){return this._bindings[rootProp].value});if(!source.__lookupSetter__(rootProp))source.__defineSetter__(rootProp,function(x){this._bindings[rootProp].value=x;if(descriptor.sourceText){descriptor.target.innerText=descriptor.sourceText}this._executeBindings(rootProp);this.__propertyChanged(rootProp,x)});var executor=void 0;if(descriptor.type==="C"){executor=function executor(){descriptor.executor()}}else if(descriptor.type==="P"){executor=function executor(){var targets=void 0;if(!descriptor.target.hasAttribute("slim-repeat")){targets=[descriptor.target]}else{targets=descriptor.target.repeater.clones}if(targets){var sourceRef=descriptor.target._boundRepeaterParent;var value=Slim.__lookup(sourceRef||source,prop).obj||Slim.__lookup(descriptor.target,prop).obj;var attrName=Slim.__dashToCamel(descriptor.attribute);targets.forEach(function(target){target[attrName]=value;target.setAttribute(descriptor.attribute,value)})}}}else if(descriptor.type==="M"){executor=function executor(){var targets=[descriptor.target];if(descriptor.target.hasAttribute("slim-repeat")){targets=descriptor.target.repeater.clones}var sourceRef=descriptor.target._boundRepeaterParent||source;var value=sourceRef[descriptor.method].apply(sourceRef,descriptor.properties.map(function(prop){return descriptor.target[prop]||sourceRef[prop]}));var attrName=Slim.__dashToCamel(descriptor.attribute);targets.forEach(function(target){target[attrName]=value;target.setAttribute(descriptor.attribute,value)})}}else if(descriptor.type==="T"){executor=function executor(){var source=descriptor.target._boundParent;descriptor.target._innerText=descriptor.target._innerText.replace("[["+prop+"]]",Slim.__lookup(source,prop).obj)}}else if(descriptor.type==="TM"){executor=function executor(){var values=descriptor.properties.map(function(compoundProp){return Slim.__lookup(source,compoundProp).obj});try{var value=source[descriptor.methodName].apply(source,values);descriptor.target._innerText=descriptor.target._innerText.replace(descriptor.expression,value)}catch(exc){console.error("Could not execute function "+descriptor.methodName+" in element "+descriptor.source.localName);console.info(exc)}}}else if(descriptor.type==="R"){executor=function executor(){descriptor.repeater.unregister();descriptor.repeater.renderList()}}else if(descriptor.type==="W"){executor=function executor(){descriptor.executor(Slim.__lookup(source,prop).obj)}}else if(descriptor.type==="F"){executor=function executor(){var value=!!Slim.__lookup(descriptor.source,prop).obj;if(descriptor.reversed){value=!value}if(!value){if(descriptor.target.parentNode){descriptor.target.insertAdjacentElement("beforeBegin",descriptor.helper);Slim.removeChild(descriptor.target)}}else{if(!descriptor.target.parentNode){descriptor.helper.insertAdjacentElement("beforeBegin",descriptor.target);if(descriptor.target.isSlim){descriptor.target.createdCallback()}Slim.removeChild(descriptor.helper)}}}}executor.descriptor=descriptor;source._bindings[rootProp].executors.push(executor)})}},{key:"createdCallback",value:function createdCallback(){if(this.isVirtual)return;if(this.__createdCallbackRunOnce)return;this.__createdCallbackRunOnce=true;this.initialize();this.onBeforeCreated();this._captureBindings();Slim.__runPlugins("create",this);this.onCreated();this.__onCreatedComplete=true;this.onBeforeRender();Slim.__runPlugins("beforeRender",this);Slim.__moveChildren(this._virtualDOM,this.rootElement,true);this.onAfterRender();Slim.__runPlugins("afterRender",this);this.update()}},{key:"detachedCallback",value:function detachedCallback(){Slim.__runPlugins("beforeRemove",this);this.onRemoved()}},{key:"_initInteractiveEvents",value:function _initInteractiveEvents(){var _this2=this;if(!this.__eventsInitialized&&(Slim.autoAttachInteractionEvents||this.isInteractive||this.hasAttribute("interactive")))Slim.interactionEventNames.forEach(function(eventType){_this2.addEventListener(eventType,function(e){_this2.handleEvent(e)})})}},{key:"initialize",value:function initialize(){this.uq_index=Slim.__createUqIndex();this.setAttribute("slim-uq",this.uq_index);this._bindings=this._bindings||{};this._boundChildren=this._boundChildren||[];this._initInteractiveEvents();this.__eventsInitialized=true;this.alternateTemplate=this.alternateTemplate||null;this._virtualDOM=this._virtualDOM||document.createDocumentFragment()}},{key:"handleEvent",value:function handleEvent(e){if(this.hasAttribute("on"+e.type)){this.callAttribute("on"+e.type,e)}else if(this.hasAttribute(e.type)){this.callAttribute(e.type,e)}}},{key:"connectedCallback",value:function connectedCallback(){this.attachedCallback()}},{key:"disconnectedCallback",value:function disconnectedCallback(){this.detachedCallback()}},{key:"attachedCallback",value:function attachedCallback(){this.onAdded()}},{key:"attributeChangedCallback",value:function attributeChangedCallback(attr,oldValue,newValue){if(oldValue===newValue)return;if(!this._bindings)return;if(this._bindings[attr]){this[Slim.__dashToCamel(attr)]=newValue}}},{key:"onAdded",value:function onAdded(){}},{key:"onRemoved",value:function onRemoved(){}},{key:"onBeforeCreated",value:function onBeforeCreated(){}},{key:"onCreated",value:function onCreated(){}},{key:"onBeforeRender",value:function onBeforeRender(){}},{key:"onAfterRender",value:function onAfterRender(){}},{key:"onBeforeUpdate",value:function onBeforeUpdate(){}},{key:"onAfterUpdate",value:function onAfterUpdate(){}},{key:"update",value:function update(){this.onBeforeUpdate();this._executeBindings();this.onAfterUpdate()}},{key:"render",value:function render(template){Slim.__runPlugins("beforeRender",this);this.onBeforeRender();this.alternateTemplate=template;this.initialize();this.rootElement.innerHTML="";this._captureBindings();this._executeBindings();Slim.__moveChildren(this._virtualDOM,this.rootElement,true);this.onAfterRender();Slim.__runPlugins("afterRender",this)}},{key:"_executeBindings",value:function _executeBindings(prop){var _this3=this;if(!this._bindings)return;this._boundChildren.forEach(function(child){if(child.hasAttribute("bind")&&child.sourceText!==undefined){child._innerText=child.sourceText}});var properties=prop?[prop]:Object.keys(this._bindings);properties.forEach(function(property){_this3._bindings[property].executors.forEach(function(fn){if(fn.descriptor.type!=="T"&&fn.descriptor.type!=="TM")fn()})});Object.keys(this._bindings).forEach(function(property){_this3._bindings[property].executors.forEach(function(fn){if(fn.descriptor.type==="T"||fn.descriptor.type==="TM"){fn()}});_this3._bindings[property].executors.forEach(function(fn){if(fn.descriptor.type==="T"||fn.descriptor.type==="TM"){fn.descriptor.target.innerText=fn.descriptor.target._innerText;if(fn.descriptor.target.__ieClone){fn.descriptor.target.__ieClone.innerText=fn.descriptor.target.innerText}}})})}},{key:"_captureBindings",value:function _captureBindings(){var _this4=this;var self=this;var $tpl=this.alternateTemplate||this.template;if(!$tpl){while(this.firstChild){self._virtualDOM=this._virtualDOM||document.createDocumentFragment();self._virtualDOM.appendChild(this.firstChild)}}else if(typeof $tpl==="string"){var frag=document.createRange().createContextualFragment($tpl);while(frag.firstChild){this._virtualDOM.appendChild(frag.firstChild)}var virtualContent=this._virtualDOM.querySelector("slim-content");if(virtualContent){while(self.firstChild){self.firstChild._boundParent=this.firstChild._boundParent||this;virtualContent.appendChild(this.firstChild)}}}var allChildren=Slim.selectorToArr(this._virtualDOM,"*");var _iteratorNormalCompletion3=true;var _didIteratorError3=false;var _iteratorError3=undefined;try{for(var _iterator3=allChildren[Symbol.iterator](),_step3;!(_iteratorNormalCompletion3=(_step3=_iterator3.next()).done);_iteratorNormalCompletion3=true){var child=_step3.value;if(child._boundP)continue;child._boundP=true;child._sourceOuterHTML=child.outerHTML;child._boundParent=child._boundParent||this;self._boundChildren=this._boundChildren||[];self._boundChildren.push(child);self._boundChildren.push(child);if(child.localName==="style"&&this.useShadow){Slim.__processStyleNode(child,this.localName,this.uq_index)}if(child.getAttribute("slim-id")){child._boundParent[Slim.__dashToCamel(child.getAttribute("slim-id"))]=child}var slimID=child.getAttribute("slim-id");if(slimID)this[slimID]=child;var descriptors=[];if(child.attributes)for(var i=0;i=0){child.isInteractive=true;child.handleEvent=self.handleEvent.bind(child);child.callAttribute=self.callAttribute.bind(child);child.addEventListener(child.attributes[i].nodeName,child.handleEvent);child.__eventsInitialized=true}var desc=Slim.__processAttribute(child.attributes[i],child);if(desc)descriptors.push(desc);child[Slim.__dashToCamel(child.attributes[i].nodeName)]=child.attributes[i].nodeValue;if(child.attributes[i].nodeName.indexOf("#")=="0"){var refName=child.attributes[i].nodeName.slice(1);this[refName]=child}}descriptors=descriptors.sort(function(a){if(a.type==="I"){return-1}else if(a.type==="R")return 1;else if(a.type==="C")return 2;return 0});descriptors.forEach(function(descriptor){if(descriptor.type==="P"||descriptor.type==="M"||descriptor.type==="C"){_this4.__bind(descriptor)}else if(descriptor.type==="I"){Slim.__inject(descriptor)}else if(descriptor.type==="R"){Slim.__createRepeater(descriptor);_this4.__bind(descriptor)}else if(descriptor.type==="F"){_this4.__bind(descriptor)}})}}catch(err){_didIteratorError3=true;_iteratorError3=err}finally{try{if(!_iteratorNormalCompletion3&&_iterator3.return){_iterator3.return()}}finally{if(_didIteratorError3){throw _iteratorError3}}}allChildren=Slim.selectorToArr(this._virtualDOM,"*[bind]");var _loop=function _loop(_child){if(_child._boundTM)return"continue";_child._boundTM=true;var match=_child.innerText.match(/\[\[(\w+)\((.+)\)]\]/g);if(match){match.forEach(function(expression){var matches=expression.match(Slim.rxMethod);var methodName=matches[1];var props=matches[3].split(" ").join("").split(",");var descriptor={type:"TM",properties:props,target:_child,expression:expression,source:_child._boundParent,sourceText:_child.innerText,methodName:methodName};_child.sourceText=_child.innerText;_this4.__bind(descriptor)})}};var _iteratorNormalCompletion4=true;var _didIteratorError4=false;var _iteratorError4=undefined;try{for(var _iterator4=allChildren[Symbol.iterator](),_step4;!(_iteratorNormalCompletion4=(_step4=_iterator4.next()).done);_iteratorNormalCompletion4=true){var _child=_step4.value;var _ret=_loop(_child);if(_ret==="continue")continue}}catch(err){_didIteratorError4=true;_iteratorError4=err}finally{try{if(!_iteratorNormalCompletion4&&_iterator4.return){_iterator4.return()}}finally{if(_didIteratorError4){throw _iteratorError4}}}var _iteratorNormalCompletion5=true;var _didIteratorError5=false;var _iteratorError5=undefined;try{for(var _iterator5=allChildren[Symbol.iterator](),_step5;!(_iteratorNormalCompletion5=(_step5=_iterator5.next()).done);_iteratorNormalCompletion5=true){var _child2=_step5.value;if(_child2._boundT)continue;_child2._boundT=true;var _match=_child2.innerText.match(/\[\[([\w|.]+)\]\]/g);if(_match&&_child2.children.firstChild){throw"Bind Error: Illegal bind attribute use on element type "+_child2.localName+" with nested children.\n"+_child2.outerHTML}if(_match){var properties=[];for(var _i=0;_i<_match.length;_i++){var lookup=_match[_i].match(/([^\[].+[^\]])/)[0];properties.push(lookup)}var descriptor={type:"T",properties:properties,target:_child2,sourceText:_child2.innerText};_child2.sourceText=_child2.innerText;this.__bind(descriptor)}}}catch(err){_didIteratorError5=true;_iteratorError5=err}finally{try{if(!_iteratorNormalCompletion5&&_iterator5.return){_iterator5.return()}}finally{if(_didIteratorError5){throw _iteratorError5}}}}},{key:"isVirtual",get:function get(){var node=this;while(node){node=node.parentNode;if(!node){return true}if(node.nodeName==="BODY"||node.host){return false}}return true}},{key:"useShadow",get:function get(){return false}},{key:"rootElement",get:function get(){if(this.useShadow&&this.createShadowRoot){this.__shadowRoot=this.__shadowRoot||this.createShadowRoot();return this.__shadowRoot}return this}},{key:"isSlim",get:function get(){return true}},{key:"template",get:function get(){return Slim.__templateDict[this.nodeName.toLowerCase()]||null}},{key:"isInteractive",get:function get(){return false}}],[{key:"__processStyleNode",value:function __processStyleNode(node,tag,uqIndex){if(Slim.__isWCSupported)return;var rxRules=/([^\r\n,{}]+)(,(?=[^}]*{)|\s*{)/g;var unique_index=node._boundParent.uq_index;var match=node.innerText.match(rxRules);if(match){match.forEach(function(selector){if(selector.indexOf(":host")<0){node.innerText=node.innerText.replace(selector,":host "+selector)}})}var customTagName=tag+'[slim-uq="'+uqIndex+'"]';node.innerText=node.innerText.replace(/\:host/g,customTagName);if(Slim.__isIE11){var ieClone=document.createElement("style");ieClone.type="text/css";node.__ieClone=ieClone;ieClone.innerText=node.innerText;while(ieClone.innerText.indexOf(" ")>=0){ieClone.innerText=ieClone.innerText.replace(" "," ")}document.head.appendChild(ieClone)}}},{key:"__processRepeater",value:function __processRepeater(attribute,child){return{type:"R",target:child,targetAttribute:child.getAttribute("slim-repeat-as")?child.getAttribute("slim-repeat-as"):"data",repeatAdjacent:child.hasAttribute("slim-repeat-adjacent")||child.localName==="option"||child.localName==="tr"||child.localName==="td",attribute:attribute.nodeName,properties:[attribute.nodeValue],source:child._boundParent}}},{key:"__processCustomAttribute",value:function __processCustomAttribute(attribute,child){return{type:"C",target:child,properties:[attribute.nodeValue],executor:function executor(){Slim.__customAttributeProcessors[attribute.nodeName].forEach(function(customAttrProcessor){customAttrProcessor(child,attribute.nodeValue)})}}}},{key:"extract",value:function extract(target,expression){var rxProp=Slim.rxProp.exec(expression);var rxMethod=Slim.rxMethod.exec(expression);if(rxProp){return target[rxProp[1]]}else if(rxMethod){return target[rxMethod[1]].apply(target,rxMethod[3].replace(" ","").split(","))}}},{key:"__processAttribute",value:function __processAttribute(attribute,child){if(attribute.nodeName==="slim-repeat"){return Slim.__processRepeater(attribute,child)}if(attribute.nodeName==="slim-if"){var propertyName=attribute.nodeValue;var reverse=false;if(attribute.nodeValue.charAt(0)==="!"){propertyName=propertyName.slice(1);reverse=true}return{type:"F",target:child,source:child._boundParent,helper:document.createElement("slim-if-helper"),reversed:reverse,properties:[propertyName]}}if(Slim.__customAttributeProcessors[attribute.nodeName]){return Slim.__processCustomAttribute(attribute,child)}var rxInject=Slim.rxInject.exec(attribute.nodeValue);var rxProp=Slim.rxProp.exec(attribute.nodeValue);var rxMethod=Slim.rxMethod.exec(attribute.nodeValue);if(rxMethod){return{type:"M",target:child,attribute:attribute.nodeName,method:rxMethod[1],properties:rxMethod[3].replace(" ","").split(",")}}else if(rxProp){return{type:"P",target:child,attribute:attribute.nodeName,properties:[rxProp[1]]}}else if(rxInject){return{type:"I",target:child,attribute:attribute.nodeName,factory:rxInject[1]}}}}]);return Slim}(_CustomElement);Slim.rxInject=/\{(.+[^(\((.+)\))])\}/;Slim.rxProp=/\[\[(.+[^(\((.+)\))])\]\]/;Slim.rxMethod=/\[\[(.+)(\((.+)\)){1}\]\]/;Slim.__customAttributeProcessors={};Slim.__prototypeDict={};Slim.__uqIndex=0;Slim.__templateDict={};Slim.__injections={};Slim.__plugins={create:[],beforeRender:[],afterRender:[],beforeRemove:[]};try{Slim.__isWCSupported=function(){return"registerElement"in document&&"import"in document.createElement("link")&&"content"in document.createElement("template")}()}catch(err){Slim.__isWCSupported=false}try{Slim.__isIE11=function(){return!!window["MSInputMethodContext"]&&!!document["documentMode"]}()}catch(err){Slim.__isIE11=false}if(Slim.__isWCSupported){Slim.selectorToArr=function(target,selector){return target.querySelectorAll(selector)}}else{Slim.selectorToArr=function(target,selector){return Array.prototype.slice.call(target.querySelectorAll(selector))}}Slim.__initRepeater=function(){var SlimRepeater=function(_Slim){_inherits(SlimRepeater,_Slim);function SlimRepeater(){_classCallCheck(this,SlimRepeater);return _possibleConstructorReturn(this,(SlimRepeater.__proto__||Object.getPrototypeOf(SlimRepeater)).apply(this,arguments))}_createClass(SlimRepeater,[{key:"onBeforeCreated",value:function onBeforeCreated(){this.clones=[]}},{key:"onAdded",value:function onAdded(){if(!this.uq_index){this.createdCallback()}this.renderList()}},{key:"onRemoved",value:function onRemoved(){this.sourceData.unregisterSlimRepeater(this)}},{key:"registerForRender",value:function registerForRender(){var _this6=this;if(this.pendingRender)return;this.pendingRender=true;setTimeout(function(){_this6.checkoutRender()},0)}},{key:"checkoutRender",value:function checkoutRender(){this.pendingRender=false;this.renderList()}},{key:"unregister",value:function unregister(){this.sourceData.unregisterSlimRepeater(this)}},{key:"clearList",value:function clearList(){this.clones&&this.clones.forEach(function(clone){Slim.removeChild(clone)});this.clones=[];this._boundChildren=[]}},{key:"removeClone",value:function removeClone(clone){var _this7=this;Slim.removeChild(clone);Slim.selectorToArr(clone,"*").forEach(function(child){_this7._boundChildren.splice(_this7._boundChildren.indexOf(child),1)});this._boundChildren.splice(this._boundChildren.indexOf(clone),1)}},{key:"updateList",value:function updateList(){var _this8=this;var targetPropName=this.getAttribute("target-attr");this.clones.forEach(function(clone,idx){var data=_this8.sourceData[idx];if(clone[targetPropName]===data)return;clone[targetPropName]=data;Slim.selectorToArr(clone,"*").forEach(function(child){child[targetPropName]=data})})}},{key:"renderList",value:function renderList(){var _this9=this;this.sourceData.registerSlimRepeater(this);if(!this.sourceNode)return;if(this.sourceData.length===0){this.clearList();return}else if(this.clones&&this.clones.length===this.sourceData.length){this.updateList();this._executeBindings();return}else if(this.clones&&this.clones.length>this.sourceData.length){this.updateList();var leftovers=this.clones.splice(this.sourceData.length);leftovers.forEach(function(leftover){_this9.removeClone(leftover)});this._executeBindings();return}else if(this.clones&&this.clones.length=0){this.registeredSlimRepeaters.splice(this.registeredSlimRepeaters.indexOf(repeater),1)}}})();if(typeof module!=="undefined"&&module.exports){module.exports.Slim=Slim} \ No newline at end of file diff --git a/example/tests/test-inject.html b/example/tests/test-inject.html index c896af7..364f462 100644 --- a/example/tests/test-inject.html +++ b/example/tests/test-inject.html @@ -14,15 +14,15 @@ Slim.tag('inject-demo', '

Hello [[modelName.e]]

', class extends Slim { onBeforeCreated() { - console.log('onBeforeCreated', this.model); + console.log('onBeforeCreated', this.modelName); } onCreated() { - console.log('onCreated', this.model); + console.log('onCreated', this.modelName); } onBeforeRender() { - console.log('onBeforeRender', this.model); + console.log('onBeforeRender', this.modelName); } }); diff --git a/src/Slim.js b/src/Slim.js index 7014eb7..939a71b 100644 --- a/src/Slim.js +++ b/src/Slim.js @@ -32,8 +32,12 @@ class Slim extends HTMLElement { Slim.__templateDict[tag] = clazzOrTemplate; } Slim.__prototypeDict[tag] = clazz; - // window.customElements.define(tag, clazz); - document.registerElement(tag, clazz); + if (Slim.__prototypeDict['slim-repeat'] === undefined) { + Slim.__initRepeater(); + } + setTimeout( () => { + document.registerElement(tag, clazz); + }, 0); } //noinspection JSUnusedGlobalSymbols @@ -109,15 +113,18 @@ class Slim extends HTMLElement { if (target.remove) { target.remove(); } - if (!target.remove && target.parentNode) { + if (target.parentNode) { target.parentNode.removeChild(target); - if (target._boundChildren) { - target._boundChildren.forEach( child => { - if (child.__ieClone) { - Slim.removeChild(child.__ieClone); - } - }); - } + } + if (target.__ieClone) { + Slim.removeChild(target.__ieClone); + } + if (target._boundChildren) { + target._boundChildren.forEach( child => { + if (child.__ieClone) { + Slim.removeChild(child.__ieClone); + } + }); } } @@ -175,15 +182,28 @@ class Slim extends HTMLElement { return {source: desc, prop:prop, obj:obj}; } + static __inject(descriptor) { + try { + descriptor.target[ Slim.__dashToCamel(descriptor.attribute) ] = Slim.__injections[ descriptor.factory ](descriptor.target); + } + catch (err) { + console.error('Could not inject ' + descriptor.attribute + ' into ' + descriptor.target); + console.info('Descriptor ', descriptor); + throw err; + } + + } + + static inject(name, injector) { + Slim.__injections[name] = injector; + } + /** * * @param descriptor * @private */ static __createRepeater(descriptor) { - if (Slim.__prototypeDict['slim-repeat'] === undefined) { - Slim.__initRepeater(); - } let repeater; repeater = document.createElement('slim-repeat'); repeater.sourceNode = descriptor.target; @@ -482,7 +502,6 @@ class Slim extends HTMLElement { * @returns {*} */ static extract(target, expression) { - const rxInject = Slim.rxInject.exec(expression); const rxProp = Slim.rxProp.exec(expression); const rxMethod = Slim.rxMethod.exec(expression); @@ -933,6 +952,7 @@ Slim.__customAttributeProcessors = {}; Slim.__prototypeDict = {}; Slim.__uqIndex = 0; Slim.__templateDict = {}; +Slim.__injections = {}; Slim.__plugins = { 'create': [], 'beforeRender': [],