var pw={version:"0.1.1"};!function(){pw.util={guid:function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var n=16*Math.random()|0,e="x"==t?n:3&n|8;return e.toString(16)})},dup:function(t){return JSON.parse(JSON.stringify(t))}};var t=[];pw.init={register:function(n){t.push(n)}},document.addEventListener("DOMContentLoaded",function(){t.forEach(function(t){t()})});var e=["data-scope","data-prop"],i=["SELECT"],o=["AREA","BASE","BASEFONT","BR","HR","INPUT","IMG","LINK","META"];pw.node={value:function(t){return"INPUT"===t.tagName?"checkbox"===t.type?t.checked?t.value?t.value:!0:!1:t.value:"TEXTAREA"===t.tagName?t.value:"SELECT"===t.tagName?t.value:t.textContent.trim()},significant:function(t,n){t===document&&(t=document.getElementsByTagName("body")[0]),void 0===n&&(n=[]);var e,i;return(e=pw.node.isSignificant(t))?(i=[],n.push([{node:e[0],type:e[1]},i])):i=n,pw.node.toA(t.children).forEach(function(t){pw.node.significant(t,i)}),n},isSignificant:function(t){var n=e.find(function(n){return t.hasAttribute(n)});return n?[t,n.split("-")[1]]:!1},mutable:function(t){pw.node.significant(t).flatten().filter(function(t){return pw.node.isMutable(t.node)}).map(function(t){return t.node})},isMutable:function(t){var n=t.tagName;return"FORM"===n||"INPUT"===n&&!t.disabled},trigger:function(t,n,e){var i=document.createEvent("Event");i.initEvent(t,!0,!0),n._evtData=e,n.dispatchEvent(i)},replaceEventListener:function(t,n,e){n.removeEventListener(t),n.addEventListener(t,e)},inForm:function(t){if("FORM"===t.tagName)return!0;var n=t.parentNode;return n!==document?pw.node.inForm(n):void 0},component:function(t){if(t.getAttribute("data-ui"))return t;var n=t.parentNode;return n!==document?pw.node.component(n):void 0},scope:function(t){if(t.getAttribute("data-scope"))return t;var n=t.parentNode;return n!==document?pw.node.scope(n):void 0},scopeName:function(t){if(t.getAttribute("data-scope"))return t.getAttribute("data-scope");var n=t.parentNode;return n!==document?pw.node.scopeName(n):void 0},prop:function(t){if(t.getAttribute("data-prop"))return t;var n=t.parentNode;return n!==document?pw.node.prop(n):void 0},propName:function(t){if(t.getAttribute("data-prop"))return t.getAttribute("data-prop");var n=t.parentNode;return n!==document?pw.node.propName(n):void 0},versionName:function(t){return t.hasAttribute("data-version")?t.getAttribute("data-version"):void 0},"with":function(t,n){n.call(t)},"for":function(t,n,e){pw.node.isNodeList(t)&&(t=pw.node.toA(t)),t=Array.ensure(t),n=Array.ensure(n),t.forEach(function(t,i){e.call(t,n[i])})},match:function(t,e){pw.node.isNodeList(t)&&(t=pw.node.toA(t)),t=Array.ensure(t),e=Array.ensure(e);var i=e.reduce(function(t,e,i){var o=n[i]||n[n.length-1],r=o.cloneNode(!0);return o.parentNode.insertBefore(r),t.concat([r])},[]);return t.forEach(function(t){t.parentNode.removeChild(t)}),i},repeat:function(t,n,e){pw.node["for"](pw.node.match(t,n),n,e)},bind:function(t,n,e){var i=pw.node.findBindings(n)[0];pw.node["for"](n,t,function(t){t&&(t.id&&this.setAttribute("data-id",t.id),pw.node.bindDataToScope(t,i,n),"undefined"!=typeof e&&e.call(this,t))})},apply:function(t,n,e){var i=pw.node.match(n,t);return pw.node.bind(t,i,e),i},findBindings:function(t){var n=[];return pw.node.breadthFirst(t,function(){var t=this,e=t.getAttribute("data-scope");if(e){var i=[];pw.node.breadthFirst(t,function(){var n=this;if(t==n||!n.getAttribute("data-scope")){var e=n.getAttribute("data-prop");e&&i.push({prop:e,doc:n})}}),n.push({scope:e,props:i,doc:t})}}),n},bindDataToScope:function(t,n,e){t&&n&&n.props.forEach(function(n){k=n.prop,v=t[k],v||(v=""),"object"==typeof v?(pw.node.bindValueToNode(v.__content,n.doc),pw.node.bindAttributesToNode(v.__attrs,n.doc)):pw.node.bindValueToNode(v,n.doc)})},bindAttributesToNode:function(t,n){var e=pw.attrs.init(pw.view.init(n));for(var i in t){var o=t[i];"function"==typeof o&&(o=o.call(n.getAttribute(i))),o?o instanceof Array?o.forEach(function(t){e[t[0]](i,t[1])}):e.set(i,o):e.remove(i)}},bindValueToNode:function(t,n){pw.node.isTagWithoutValue(n)||("INPUT"===n.tagName&&"checkbox"===n.type?t===!0||n.value&&t===n.value?n.checked=!0:n.checked=!1:"TEXTAREA"===n.tagName||pw.node.isSelfClosingTag(n)?n.value=t:n.innerHTML=t)},isTagWithoutValue:function(t){return-1!=i.indexOf(t.tagName)?!0:!1},isSelfClosingTag:function(t){return-1!=o.indexOf(t.tagName)?!0:!1},breadthFirst:function(t,n){for(var e=[t];e.length>0;){var i=e.shift();if(i){"object"==typeof i&&"nodeType"in i&&1===i.nodeType&&i.cloneNode&&n.call(i);var o=i.childNodes;if(o)for(var r=0;r-1?"hash":r.bool.indexOf(t)>-1?"bool":r.mult.indexOf(t)>-1?"mult":"text"},findValue:function(t,n){switch(n){case"class":return t.node.classList;case"style":return t.node.style}return"bool"===this.findType(n)?t.node.hasAttribute(n):t.node.getAttribute(n)},set:function(t,n){this.views.forEach(function(e){pw.node.setAttr(e.node,t,n)})},remove:function(t){this.views.forEach(function(n){n.node.removeAttribute(t)})},ensure:function(t,n){this.views.forEach(function(e){var i=this.findValue(e,t);if("class"===t)i.contains(n)||i.add(n);else if("style"===t)n.pairs().forEach(function(t){e.node.style[t[0]]=t[1]});else if("bool"===this.findType(t))e.node.hasAttribute(t)||pw.node.setAttr(e.node,t,t);else{var i=e.node.getAttribute(t)||"";i.match(n)||pw.node.setAttr(e.node,t,i+n)}},this)},deny:function(t,n){this.views.forEach(function(e){var i=this.findValue(e,t);"class"===t?i.contains(n)&&i.remove(n):"style"===t?n.pairs().forEach(function(t){e.node.style[t[0]]=e.node.style[t[0]].replace(t[1],"")}):"bool"===this.findType(t)?e.node.hasAttribute(t)&&e.node.removeAttribute(t):pw.node.setAttr(e.node,t,e.node.getAttribute(t).replace(n,""))},this)},insert:function(t,n){this.views.forEach(function(e){var i=this.findValue(e,t);switch(t){case"class":i.add(n);break;default:pw.node.setAttr(e.node,t,i+n)}},this)}},pw.state={build:function(t,n){var e;return t.reduce(function(t,i){return(e=pw.state.buildForNode(i,n))&&t.push(e),t},[])},buildForNode:function(t,n){var e=t[0],i={};if("scope"===e.type)i.id=e.node.getAttribute("data-id"),i.scope=e.node.getAttribute("data-scope");else if("prop"===e.type&&n)return void(n[e.node.getAttribute("data-prop")]=pw.node.value(e.node));return i.__nested=pw.state.build(t[1],i),i},init:function(t,n){return new c(t,n)}};var c=function(t){this.node=t,this.snapshots=[],this.update()};c.prototype={update:function(){this.snapshots.push(pw.state.build(pw.node.significant(this.node)))},diffNode:function(t){return pw.state.build(pw.node.significant(pw.node.scope(t)))[0]},revert:function(){var t=pw.util.dup(this.snapshots[0]);return this.snapshots=[t],t},rollback:function(){return this.snapshots.pop(),this.current()},node:function(t){return this.current.flatten().find(function(n){return n.scope===t.scope&&n.id===t.id})},append:function(t){var n=this.copy();n.push(t),this.snapshots.push(n)},prepend:function(t){var n=this.copy();n.unshift(t),this.snapshots.push(n)},"delete":function(t){var n=this.copy(),e=n.find(function(n){return n.id===t.id});e&&(n.splice(n.indexOf(e),1),this.snapshots.push(n))},copy:function(){return pw.util.dup(this.current())},current:function(){return this.snapshots[this.snapshots.length-1]},initial:function(){return this.snapshots[0]}},pw.view={init:function(t){return new s(t)},fromStr:function(t){var n=document.createElement("div");return n.innerHTML=t,pw.view.init(n.childNodes[0])}};var s=function(t){this.node=t};s.prototype={clone:function(){return pw.view.init(this.node.cloneNode(!0))},title:function(t){pw.node.title(this.node,t)},text:function(t){this.node.innerText=t},html:function(t){this.node.innerHTML=t},component:function(t){return pw.collection.init(pw.node.byAttr(this.node,"data-ui",t).reduce(function(t,n){return t.concat(pw.view.init(n))},[]),this)},attrs:function(){return pw.attrs.init(this)},"with":function(t){pw.node["with"](this.node,t)},match:function(t){pw.node.match(this.node,t)},"for":function(t,n){pw.node["for"](this.node,t,n)},repeat:function(t,n){pw.node.repeat(this.node,t,n)},bind:function(t,n){pw.node.bind(t,this.node,n)},apply:function(t,n){pw.node.apply(t,this.node,n)}},["scope","prop"].forEach(function(t){s.prototype[t]=function(n){return pw.collection.init(pw.node.byAttr(this.node,"data-"+t,n).reduce(function(t,n){return t.concat(pw.view.init(n))},[]),this,n)}}),["remove","clear","versionNode"].forEach(function(t){s.prototype[t]=function(){return pw.node[t](this.node)}}),["after","before","replace","append","prepend","insert"].forEach(function(t){s.prototype[t]=function(n){return pw.node[t](this.node,n.node)}}),pw.collection={init:function(t,n,e){return t instanceof u?t:(t.constructor!==Array&&(t=[t]),new u(t,n,e))},fromNodes:function(t,n,e){return pw.collection.init(t.map(function(t){return pw.view.init(t)}),n,e)}};var u=function(t,n,e){this.views=t,this.parent=n,this.scope=e};u.prototype={clone:function(){return pw.collection.init(this.views.map(function(t){return t.clone()}))},last:function(){return this.views[this.length()-1]},first:function(){return this.views[0]},removeView:function(t){var n=this.views.indexOf(t);n>-1&&this.views.splice(n,1)[0].remove()},addView:function(t){var n=[];t instanceof u?n=t.views:n.push(t),this.length()>0?n.forEach(function(t){pw.node.after(this.last().node,t.node)},this):this.parent&&n.forEach(function(t){this.parent.append(t)},this),this.views=this.views.concat(n)},order:function(t){t.forEach(function(t){if(t){var n=this.views.find(function(n){return n.node.getAttribute("data-id")==t.toString()});if(n){n.node.parentNode.appendChild(n.node);var e=this.views.indexOf(n);this.views.splice(e,1),this.views.push(n)}}},this)},length:function(){return this.views.length},attrs:function(){return pw.attrs.init(this.views)},append:function(t){t=Array.ensure(t);var n=this.last();return this.views.push(n.append(t)),n},prepend:function(t){t=Array.ensure(t);var n=t.map(function(t){var n=this.first().prepend(t);return this.views.push(n),n},this);return pw.collection.init(n)},"with":function(t){pw.node["with"](this.views,t)},"for":function(t,n){t=Array.ensure(t),this.views.forEach(function(e,i){n.call(e,t[i])})},match:function(t,n){if(t=Array.ensure(t),0===t.length)return this.remove(),n.call(this);var e,i;if(this.views[0]&&(e=this.views[0].clone(),i=this.views[0].node.parentNode),this.views.slice(0).forEach(function(n){var e=n.node.getAttribute("data-id");e&&(t.find(function(t){return t.id.toString()===e})||this.removeView(n))},this),!(t.length>this.length()))return n.call(this);var o=this;return this.endpoint.template(this,function(r){return r||(r=e.clone(),o.parent=pw.view.init(i)),t.forEach(function(t){if(!o.views.find(function(n){return n.node.getAttribute("data-id")===(t.id||"").toString()})){var n=r.clone();n instanceof u&&(n=n.views[0]),n.node.setAttribute("data-id",t.id),o.addView(n),pw.component.findAndInit(n.node)}},o),n.call(o)}),this},repeat:function(t,n){this.match(t,function(){this["for"](t,n)})},bind:function(t,n){return this["for"](t,function(t){this.bind(t),"undefined"!=typeof n&&n.call(this,t)}),this},apply:function(t,n){this.match(t,function(){var e;this.order(t.map(function(t){return(e=t.id)?e.toString():void 0})),this.bind(t,n)})},endpoint:function(t){return this.endpoint=t,this}},["scope","prop","component"].forEach(function(t){u.prototype[t]=function(n){return pw.collection.init(this.views.reduce(function(e,i){return e.concat(i[t](n).views)},[]))}}),["remove","clear","text","html"].forEach(function(t){u.prototype[t]=function(n){this.views.forEach(function(e){e[t](n)})}}),pw.init.register(function(){pw.component.findAndInit(document.querySelectorAll("body")[0])});var d={},p={},f={},h={};pw.component={init:function(t,n){return new l(t,n)},resetChannels:function(){p={}},findAndInit:function(t){pw.node.byAttr(t,"data-ui").forEach(function(t){if(!t._ui){var n=t.getAttribute("data-ui"),e=d[n]||pw.component.init;h[n]||(h[n]=[]);var i=t.getAttribute("data-channel"),o=t.getAttribute("data-config"),r=pw.view.init(t),a=h[n].length,c=new e(r,pw.component.buildConfigObject(o),n,a);c.init(r,o,n),pw.component.registerForChannel(c,i),h[n].push(c),t._ui=!0}})},push:function(t){var n=t.channel,e=t.payload,i=e.instruct;(p[n]||[]).forEach(function(t){i?t.instruct(n,i):t.message(n,e)})},register:function(t,n){var e=l.prototype;Object.getOwnPropertyNames(e).forEach(function(t){n.prototype[t]=e[t]}),d[t]=n},buildConfigObject:function(t){return t?t.split(";").reduce(function(t,n){var e=n.trim().split(":");return t[e[0].trim()]=e[1].trim(),t},{}):{}},registerForChannel:function(t,n){p[n]||(p[n]=[]),p[n].push(t)},registerForBroadcast:function(t,n,e){f[t]||(f[t]=[]),f[t].push([n,e])},deregisterForBroadcast:function(t,n){var e=f[t],i=e.find(function(t){return t[1]==n}),o=e.indexOf(i);e.splice(o,1)},broadcast:function(t,n){(f[t]||[]).forEach(function(t){t[0].call(t[1],n)})}};var l=function(t,n,e){};l.prototype={init:function(t,n,e){var i=t.node;this.view=t,this.node=i,this.config=n,this.name=e,this.templates={};var o=this;if(pw.node.toA(i.querySelectorAll(":scope > *[data-template]")).forEach(function(t){var n=t.cloneNode(!0);pw.node.remove(t);var e=n.getAttribute("data-scope");this.templates[e]?this.templates[e].views.push(pw.view.init(n)):this.templates[e]=pw.collection.init(pw.view.init(n)),n.removeAttribute("data-template")},this),this.state=pw.state.init(this.node),this.dCb){var r=pw.node.component(this.node.parentNode);r&&(r.addEventListener("mutated",function(t){o.transform(o.dCb(t.target._evtData))}),o.transform(o.dCb(pw.state.init(r).current())))}var a=function(t){t.preventDefault();var n=pw.node.scope(t.target);n&&o.mutated(n)};i.addEventListener("submit",a),i.addEventListener("change",function(t){pw.node.inForm(t.target)||a(t)}),this.inited&&this.inited()},listen:function(t,n){pw.component.registerForBroadcast(t,n,this)},ignore:function(t){pw.component.deregisterForBroadcast(t,this)},instruct:function(t,n){this.endpoint=pw.instruct;var e=this.state.current();if(1===e.length){var i=this.view.scope(e[0].scope),o=i.views[0].node;if("empty"===o.getAttribute("data-version")){var r=this;return void pw.instruct.template(i,function(t){var e=o.parentNode;e.replaceChild(t.node,o),n.forEach(function(t){r[t[0]](t[1])})})}}n.forEach(function(t){this[t[0]](t[1])},this)},message:function(t,n){},mutated:function(t){this.mutation(this.state.diffNode(t)),this.state.update(),pw.node.trigger("mutated",this.node,this.state.current())},mutation:function(t){},transform:function(t){this._transform(t)},_transform:function(t){t&&(t.length>0?this.view.scope(t[0].scope).endpoint(this.endpoint||this).apply(t):pw.node.breadthFirst(this.view.node,function(){this.hasAttribute("data-scope")&&pw.node.remove(this)}),pw.node.trigger("mutated",this.node,this.state.current()))},revert:function(){this.transform(this.state.revert())},rollback:function(){this.transform(this.state.rollback())},template:function(t,n){var e;(e=this.templates[t.scope])&&n(e)},"delete":function(t){this.state["delete"](t),this.transform(this.state.current())},append:function(t){this.state.append(t),this.transform(this.state.current())},prepend:function(t){this.state.prepend(t),this.transform(this.state.current())},parent:function(){var t=pw.node.scope(this.node);return t?pw.state.init(t).current()[0]:void 0},dependent:function(t){this.dCb=t}},pw.init.register(function(){pw.socket.init({cb:function(t){window.socket=t}})}),pw.socket={init:function(t){return pw.socket.connect(t.host,t.port,t.protocol,t.connId,t.cb)},connect:function(t,n,e,i,o){if("undefined"==typeof t&&(t=window.location.hostname),"undefined"==typeof n&&(n=window.location.port),"undefined"==typeof e&&(e=window.location.protocol),"undefined"==typeof i&&(i=document.getElementsByTagName("body")[0].getAttribute("data-socket-connection-id")),i){var r="";return"http:"===e?r+="ws://":"https:"===e&&(r+="wss://"),r+=t,n&&(r+=":"+n),r+="/?socket_connection_id="+i,new w(r,o)}}};var w=function(t,n){var e=this;this.callbacks={},this.url=t,this.initCb=n,this.ws=new WebSocket(t),this.id=t.split("socket_connection_id=")[1];var i;this.ws.onmessage=function(t){pw.component.broadcast("socket:loaded");var n=JSON.parse(t.data);if(n.id){var i=e.callbacks[n.id];if(i)return void i.call(this,n)}e.message(n)},this.ws.onclose=function(t){console.log("socket closed"),clearInterval(i),e.reconnect()},this.ws.onopen=function(t){console.log("socket open"),e.initCb&&e.initCb(e),i=setInterval(function(){e.send({action:"ping"})},3e4)}};w.prototype={send:function(t,n){pw.component.broadcast("socket:loading"),t.id=pw.util.guid(),t.input||(t.input={}),t.input.socket_connection_id=this.id,this.callbacks[t.id]=n,this.ws.send(JSON.stringify(t))},message:function(t){console.log("received message"),console.log(t);var n='*[data-channel="'+t.channel+'"]';if(t.channel&&"component"===t.channel.split(":")[0])return void pw.component.push(t);var e=pw.node.toA(document.querySelectorAll(n));0!==e.length&&pw.instruct.process(pw.collection.fromNodes(e,n),t,this)},reconnect:function(){var t=this;t.wait?t.wait*=1.25:t.wait=100,console.log("reconnecting socket in "+t.wait+"ms"),setTimeout(function(){pw.socket.init({cb:t.initCb})},t.wait)},fetchView:function(t,n){var e;if(window.location.hash){var i=window.location.hash.split("#:")[1].split("/");i.shift(),e=i.join("/")}else e=window.location.pathname+window.location.search;this.send({action:"fetch-view",lookup:t,uri:e},function(t){var e=pw.view.fromStr(t.body);e.node?(e.node.removeAttribute("data-id"),n(e)):n()})}},pw.instruct={process:function(t,n,e){1===t.length()&&"empty"===t.views[0].node.getAttribute("data-version")?pw.instruct.fetchView(n,e,t.views[0].node):pw.instruct.perform(t,n.payload)},fetchView:function(t,n,e){n.fetchView({channel:t.channel},function(n){if(n){var i=e.parentNode;i.replaceChild(n.node,e);var o='*[data-channel="'+t.channel+'"]',r=pw.node.toA(i.querySelectorAll(o));pw.instruct.perform(pw.collection.fromNodes(r,o),t.payload)}else console.log("trouble fetching view :(")})},template:function(t,n){var e={};if(!t||!t.first())return n();var i=t.first().node;if(i.hasAttribute("data-channel"))e.channel=t.first().node.getAttribute("data-channel");else{if(!i.hasAttribute("data-ui")||!i.hasAttribute("data-scope"))return void n();e.component=pw.node.component(i).getAttribute("data-ui"),e.scope=i.getAttribute("data-scope")}window.socket.fetchView(e,function(t){n(t)})},perform:function(t,n){var e=this;(n||[]).forEach(function(n,i){var o=n[0],r=n[1],a=n[2];if(!t[o])return void console.log("could not find method named: "+o);if("with"==o||"for"==o||"bind"==o||"repeat"==o||"apply"==o)return void t.endpoint(e)[o].call(t,r,function(t){pw.instruct.perform(this,a[r.indexOf(t)])});if("attrs"==o)return void e.performAttr(t.attrs(),a);var c=t[o].call(t,r);a instanceof Array?pw.instruct.perform(c,a):c&&(t=c)}),pw.component.findAndInit(t.node)},performAttr:function(t,n){n.forEach(function(n){var e=n[0],i=n[1],o=n[2];i?t.set(e,i):t[o[0][0]](e,o[0][1])})}},Array.prototype.flatten||(Array.prototype.flatten=function(){return this.reduce(function(t,n){return t.concat(Array.isArray(n)?n.flatten():n)},[])}),Array.prototype.find||(Array.prototype.find=function(t){if(null==this)throw new TypeError("Array.prototype.find called on null or undefined");if("function"!=typeof t)throw new TypeError("predicate must be a function");for(var n,e=Object(this),i=e.length>>>0,o=arguments[1],r=0;i>r;r++)if(n=e[r],t.call(o,n,r,e))return n;return void 0}),Array.ensure=function(t){return t instanceof Array?t:[t]},NodeList.prototype.forEach=Array.prototype.forEach,Object.prototype.pairs||Object.defineProperty(Object.prototype,"pairs",{value:function(){return Object.keys(this).map(function(t){return[t,this[t]]},this)},enumerable:!1}),"function"==typeof define&&define.amd?define(pw):"object"==typeof module&&module.exports?module.exports=pw:this.pw=pw}();