0){n.push("if (",r,"==null) {");if(y.length==1)n.push(r,"=",y[0],";");else{for(var h=0,p=y.length-1;h0&&n.push("} else "),n.push("if (",b,"!=null){",r,"=",b,";")}n.push("} else {",r,"=",y[y.length-1],";}")}}n.push("}")}}}});
-//*******************
-//LOGICAL-PATH:aria/utils/Path.js
-//*******************
-Aria.classDefinition({$classpath:"aria.utils.Path",$dependencies:["aria.utils.String","aria.utils.Type"],$singleton:!0,$statics:{WRONG_PATH_SYNTAX:"Syntax for path %1 is not valid. Note that variables cannot be used in paths.",RESOLVE_FAIL:"Resolve for path %1 failed, root element does not contain this path"},$prototype:{setValue:function(e,t,n){var r=aria.utils.Type;if(!e||!t||!r.isObject(e))return;r.isString(t)&&(t=this.parse(t));if(!r.isArray(t)||r.isNumber(t[0]))return;var i=e,s,o,u;for(var a=0,f=t.length
-;ai&&(i=s),this._logsPerClasspath
-[n.classpath]||(this._logsPerClasspath[n.classpath]={});var o=this._logsPerClasspath[n.classpath];o[n.msg]||(o[n.msg]=[0]),o[n.msg].push(n),o[n.msg][0]+=n.length}this._logsPerClasspath._max=i},showProfilingData:function(e){if(this._displayDiv!=null)return;this.process();var t=Aria.$window.document;this._displayDiv=t.createElement("div"),this._displayDiv.style.cssText="position:absolute;top:0px;left:0px;width:100%;height:100%; z-index:99999999;overflow:auto;background:white",t.body.appendChild(this._displayDiv
-),Aria.loadTemplate({classpath:"aria.utils.ProfilingDisplay",div:this._displayDiv,data:aria.utils.Json.copy(this._logsPerClasspath,!0)})},hideProfilingData:function(){this._displayDiv.innerHTML="",this._displayDiv!=null&&aria.utils.Dom.removeElement(this._displayDiv),this._displayDiv=null},logTimestamp:function(e,t){this._logs[this._nbLogs++]={classpath:e,msg:t,timestamp:(new Date).getTime()}},startMeasure:function(e,t){return this._logs[this._nbLogs++]={classpath:e,msg:t,id:this._ids,start:(new Date).getTime
-()},this._ids++},stopMeasure:function(e,t){this._logs[this._nbLogs++]={classpath:e,id:t,stop:(new Date).getTime()}},incrementCounter:function(e,t){this._counters.hasOwnProperty(e)?this._counters[e]+=t||1:this._counters[e]=t||1},resetCounter:function(e,t){if(!this._counters[e])return;this._counterSplits[e]||(this._counterSplits[e]=[]),this._counterSplits[e].push({value:this._counters[e],reason:t}),this._counters[e]=0},getCounterValue:function(e){return this._counters[e]||0},getAvgSplitCounterValue:function(e,
-t){if(!this._counterSplits[e])return 0;var n=0;for(var r=0,i=this._counterSplits[e].length;r=0;n--)e.releaseId(t[n]);this._dynamicIds=null}}}})})();
-//*******************
-//LOGICAL-PATH:aria/widgetLibs/BindableWidget.js
-//*******************
-Aria.classDefinition({$classpath:"aria.widgetLibs.BindableWidget",$extends:"aria.widgetLibs.BaseWidget",$statics:{INVALID_BEAN:"Invalid propety '%1' in widget's '%2' configuration."},$dependencies:["aria.utils.Json","aria.utils.Type"],$constructor:function(e,t,n){this.$BaseWidget.constructor.call(this,e,t,n),this._bindingListeners={}},$destructor:function(){var e=this._bindingListeners,t=aria.utils.Json;for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];t.removeListener(r.inside,r.to,r.cb)}this._bindingListeners=
-null,this.$BaseWidget.$destructor.call(this)},$prototype:{_registerBindings:function(){var e=this._cfg.bind,t=aria.utils.Json;if(e)for(var n in e){if(!e.hasOwnProperty(n))continue;var r=e[n];if(r){var i={fn:this._notifyDataChange,scope:this,args:n};try{t.addListener(r.inside,r.to,i,!0),this._bindingListeners[n]={inside:r.inside,to:r.to,transform:r.transform,cb:i};var s=this._transform(r.transform,r.inside[r.to],"toWidget");this.setWidgetProperty(n,s)}catch(o){this.$logError(this.INVALID_BEAN,[n,"bind"])}}}},
-_notifyDataChange:Aria.empty,setWidgetProperty:Aria.empty,_transform:function(e,t,n){var r=t;if(e){var i=!1,s=aria.utils.Type;s.isString(e)&&e.indexOf(".")!=-1&&(e=Aria.getClassInstance(e),i=!0),e[n]?r=this.evalCallback(e[n],r):s.isFunction(e)&&(r=this.evalCallback(e,r)),i&&e.$dispose()}return r},evalCallback:function(e,t){return this._context.evalCallback(e,t)}}});
-//*******************
-//LOGICAL-PATH:aria/widgetLibs/CommonBeans.js
-//*******************
-Aria.beanDefinitions({$package:"aria.widgetLibs.CommonBeans",$description:"",$namespaces:{json:"aria.core.JsonTypes"},$beans:{Callback:{$type:"json:MultiTypes",$description:"",$contentTypes:[{$type:"json:Object",$description:"",$properties:{fn:{$type:"FunctionName",$description:""},scope:{$type:"json:ObjectRef",$description:""},args:{$type:"json:MultiTypes",$description:""}}},{$type:"FunctionName",$description:""}]},FunctionName:{$type:"json:MultiTypes",$description:"",$contentTypes:[{$type:"json:String",$description
-:""},{$type:"json:FunctionRef",$description:""}]},BindingRef:{$type:"json:Object",$description:"",$properties:{to:{$type:"json:JsonProperty",$description:""},inside:{$type:"json:ObjectRef",$description:""},transform:{$type:"TransformRef",$description:""}}},TransformRef:{$type:"json:MultiTypes",$description:"",$contentTypes:[{$type:"json:Object",$description:"",$properties:{toWidget:{$type:"FunctionName",$description:""},fromWidget:{$type:"FunctionName",$description:""}}},{$type:"FunctionName",$description:""
-}]}}});
-//*******************
-//LOGICAL-PATH:aria/widgetLibs/WidgetLib.js
-//*******************
-Aria.classDefinition({$classpath:"aria.widgetLibs.WidgetLib",$statics:{UNKWOWN_WIDGET:"Unknown widget name in the library.",ERROR_WIDGET_INIT:"Template %1, line %2: an error occurred while initializing widget %3. Please check the name and classpath of the widget in the library, the constructor of the widget and its %4 method."},$prototype:{widgets:{},getWidgetDependencies:function(e,t){var n=this.widgets[e];return n==null?null:t||Aria.getClassRef(n)==null?[n]:[]},processWidgetMarkup:function(e,t,n,r){var i=this
-.widgets[e];try{if(!i)throw this.UNKWOWN_WIDGET;n||(n={});var s=Aria.getClassRef(i),o=new s(n,t.tplCtxt,r);t.registerBehavior(o),o.writeMarkup(t)}catch(u){t.write("#Error in widget:"+e+"#"),this.$logError(this.ERROR_WIDGET_INIT,[t.tplCtxt.tplClasspath,r,e,"writeMarkup"],u)}},processWidgetMarkupBegin:function(e,t,n,r){var i=this.widgets[e];try{if(i){n||(n={});var s=Aria.getClassRef(i),o=new s(n,t.tplCtxt,r);return t.registerBehavior(o),o.writeMarkupBegin(t),o}throw this.UNKWOWN_WIDGET}catch(u){t.write("#Error in widget:"+
-e+"#"),this.$logError(this.ERROR_WIDGET_INIT,[t.tplCtxt.tplClasspath,r,e,"writeMarkupBegin"],u)}}}});
-//*******************
-//LOGICAL-PATH:aria/widgets/environment/WidgetSettings.js
-//*******************
-Aria.classDefinition({$classpath:"aria.widgets.environment.WidgetSettings",$extends:"aria.core.environment.EnvironmentBase",$dependencies:["aria.widgets.environment.WidgetSettingsCfgBeans","aria.widgetLibs.environment.WidgetLibsSettings"],$singleton:!0,$prototype:{_cfgPackage:"aria.widgets.environment.WidgetSettingsCfgBeans.AppCfg",getWidgetLib:function(){return Aria.getClassRef(this.getWidgetLibClassName())},getWidgetLibClassName:function(){return this.$logWarn("The getWidgetLibClassName and getWidgetLib methods are deprecated. There is no longer a single default library. Instead of these methods, you can consider using the getWidgetLibs method in aria.widgetLibs.environment.WidgetLibsSettings."
-),aria.widgetLibs.environment.WidgetLibsSettings.getWidgetLibs().aria},getWidgetSettings:function(){return this.checkApplicationSettings("widgetSettings")}}});
-//*******************
-//LOGICAL-PATH:aria/widgets/environment/WidgetSettingsCfgBeans.js
-//*******************
-Aria.beanDefinitions({$package:"aria.widgets.environment.WidgetSettingsCfgBeans",$namespaces:{json:"aria.core.JsonTypes",dragDrop:"aria.utils.dragdrop.DragDropBean"},$description:"",$beans:{AppCfg:{$type:"json:Object",$description:"",$restricted:!1,$properties:{widgetSettings:{$type:"WidgetSettingsCfg",$description:"",$default:{}},defaultWidgetLib:{$type:"json:String",$description:""}}},WidgetSettingsCfg:{$type:"json:Object",$description:"",$properties:{directOnBlurValidation:{$type:"json:Boolean",$description
-:"",$default:!0},autoselect:{$type:"json:Boolean",$description:"",$default:!1},middleAlignment:{$type:"json:Boolean",$description:"",$default:!0},dialog:{$type:"json:Object",$description:"",$properties:{movable:{$type:"json:Boolean",$description:"",$default:!1},movableProxy:{$type:"dragDrop:ProxyCfg",$description:""}},$default:{}}}}}});
-//*******************
-//LOGICAL-PATH:aria/widgets/AriaLib.js
-//*******************
-Aria.classDefinition({$classpath:"aria.widgets.AriaLib",$singleton:!0,$prototype:{}});
-//*******************
-//LOGICAL-PATH:aria/widgets/AriaSkinBeans.js
-//*******************
-Aria.beanDefinitions({$package:"aria.widgets.AriaSkinBeans",$beans:{}});
-//*******************
-//LOGICAL-PATH:aria/widgets/AriaSkinInterface.js
-//*******************
-Aria.classDefinition({$classpath:"aria.widgets.AriaSkinInterface",$singleton:!0,$prototype:{}});
-//*******************
-//LOGICAL-PATH:aria/widgets/AriaSkinNormalization.js
-//*******************
-Aria.classDefinition({$classpath:"aria.widgets.AriaSkinNormalization",$singleton:!0,$prototype:{normalizeSkin:function(e){}}});
-//*******************
-//LOGICAL-PATH:aria/widgets/GlobalStyle.tpl.css
-//*******************
-{CSSTemplate {
- $classpath : "aria.widgets.GlobalStyle"
-}}
-
-{macro main()}
-{/macro}
-
-{/CSSTemplate}
-//*******************
-//LOGICAL-PATH:aria/widgets/WidgetStyle.tpl.css
-//*******************
-{CSSTemplate {
- $classpath : "aria.widgets.WidgetStyle"
-}}
- {macro main()}
- {/macro}
-{/CSSTemplate}
-//*******************
-//LOGICAL-PATH:aria/widgets/WidgetStyleScript.js
-//*******************
-Aria.tplScriptDefinition({$classpath:"aria.widgets.WidgetStyleScript",$prototype:{}});
\ No newline at end of file
diff --git a/examples/ariatemplates/js/view/Todo.tpl b/examples/ariatemplates/js/view/Todo.tpl
deleted file mode 100644
index 67844040ca..0000000000
--- a/examples/ariatemplates/js/view/Todo.tpl
+++ /dev/null
@@ -1,130 +0,0 @@
-{Template {
- $classpath: 'js.view.Todo',
- $hasScript: true,
- $wlibs: {
- html: 'aria.html.HtmlLibrary'
- }
-}}
- {macro main()}
-
- {section {
- macro: "mainDisplay",
- type: "div",
- bindRefreshTo: [{to: "emptylist", inside: data}]
- }/}
- {/macro}
-
- {macro mainDisplay()}
- {if !data.emptylist}
-
- {@html:CheckBox {
- attributes: {
- classList: ["toggle-all"]
- },
- bind: {
- checked: {
- to: "toggleall",
- inside: data,
- transform: {
- fromWidget: toggleAll
- }
- }
- }
- }/}
- Mark all as complete
- {repeater {
- id: "tasklist",
- content: data.todolist,
- type: "ul",
- attributes: {
- classList: (data.route.length > 0 ? ["todo-list", "filter-" + data.route] : ["todo-list"])
- },
- childSections: {
- id: "task",
- type: "li",
- macro: "taskDisplay",
- bindRefreshTo: function (e) { return [{to: "title", inside: e.item}] },
- attributes: function (e) {
- return { classList: e.item.completed ? ["completed"] : [] }
- }
- }
- }/}
-
-
- {/if}
- {/macro}
-
- {macro routing()}
-
- All
-
-
- Active
-
-
- Completed
-
- {/macro}
-
- {macro itemsleft()}
- ${data.itemsleft} ${data.itemsleft == 1 ? "item" : "items"} left
- {/macro}
-
- {macro itemsclear()}
- {if data.itemscompleted > 0}
- Clear completed
- {/if}
- {/macro}
-
- {macro taskDisplay(iter)}
- {if data.editedTask == iter.sectionId}
-
- {else/}
-
- {@html:CheckBox {
- attributes: {
- classList: ["toggle"]
- },
- bind: {
- checked: {
- to: "completed",
- inside: iter.item,
- transform: function (v) { return changeTaskStyle(v, iter.sectionId) }
- }
- }
- }/}
- ${iter.item.title|escapeForHTML}
-
-
- {/if}
- {/macro}
-
-{/Template}
diff --git a/examples/ariatemplates/js/view/TodoScript.js b/examples/ariatemplates/js/view/TodoScript.js
deleted file mode 100644
index ab86777db7..0000000000
--- a/examples/ariatemplates/js/view/TodoScript.js
+++ /dev/null
@@ -1,133 +0,0 @@
-/* global aria:true, Aria:true */
-'use strict';
-
-Aria.tplScriptDefinition({
- $classpath: 'js.view.TodoScript',
- $dependencies: ['aria.utils.HashManager'],
-
- $prototype: {
- $dataReady: function () {
- this.getRoute();
- this.data.editedTask = null;
- this.pauselistener = false;
- this.todolistUpdateHandler();
- this.$json.addListener(this.data, 'todolist', {fn: this.todolistUpdateHandler, scope: this}, false, true);
- aria.utils.HashManager.addCallback({fn: 'routeManager', scope: this});
- },
-
- $viewReady: function () {
- document.querySelector('.new-todo').focus();
- },
-
- getRoute: function () {
- var route = aria.utils.HashManager.getHashString();
- this.$json.setValue(this.data, 'route', route[0] === '/' ? route.substr(1) : route);
- },
-
- routeManager: function () {
- var el = this.$getElementById('tasklist');
- this.getRoute();
- el.classList.setClassName('todo-list' + (this.data.route.length > 0 ? ' filter-' + this.data.route : ''));
- },
-
- changeTaskStyle: function (val, where) {
- var el = this.$getElementById(where);
- if (el) { el.classList.setClassName(val ? 'completed' : ''); }
- return val;
- },
-
- newTaskOnEnter: function (evt) {
- var val;
- if (evt.keyCode === evt.KC_ENTER) {
- val = aria.utils.String.trim(evt.target.getValue());
- if (val.length > 0) {
- this.moduleCtrl.addTask(val);
- evt.target.setValue('');
- }
- }
- },
-
- deleteTask: function (evt, e) {
- this.moduleCtrl.deleteTask(e.index);
- },
-
- toggleAll: function (val) {
- var i;
- this.pauselistener = true;
- for (i = 0; i < this.data.todolist.length; i++) {
- this.$json.setValue(this.data.todolist[i], 'completed', val);
- }
- this.pauselistener = false;
- this.todolistUpdateHandler();
- return val;
- },
-
- clearCompleted: function () {
- var i;
- aria.templates.RefreshManager.stop();
- this.pauselistener = true;
- for (i = this.data.todolist.length - 1; i >= 0; i--) {
- if (this.data.todolist[i].completed) { this.deleteTask(null, {index: i}); }
- }
- this.pauselistener = false;
- this.todolistUpdateHandler();
- aria.templates.RefreshManager.resume();
- },
-
- editTask: function (evt, e) {
- var el = null;
- this.data.editedTask = e.sectionId;
- el = this.$getElementById(e.sectionId);
- if (el) { el.classList.add('editing'); }
- this.$refresh({outputSection: e.sectionId});
- this.$focus('editbox');
- },
-
- confirmOrRevertEdit: function (evt, e) {
- if (evt.keyCode === evt.KC_ENTER) { this.stopEdit(evt, e); }
- if (evt.keyCode === evt.KC_ESCAPE) { this.revertEdit(evt, e); }
- },
-
- stopEdit: function (evt, e) {
- var el, val;
- this.data.editedTask = null;
- el = this.$getElementById(e.sectionId);
- if (el) { el.classList.remove('editing'); }
- val = aria.utils.String.trim(evt.target.getValue());
- if (val.length > 0) {
- if (val === e.item.title) {
- this.$refresh({outputSection: e.sectionId});
- }
- else {
- this.$json.setValue(e.item, 'title', val);
- }
- }
- else {
- this.deleteTask(evt, e);
- }
- },
-
- revertEdit: function (evt, e) {
- var el;
- this.data.editedTask = null;
- el = this.$getElementById(e.sectionId);
- if (el) { el.classList.remove('editing'); }
- this.$refresh({outputSection: e.sectionId});
- this.$json.setValue(e.item, 'title', e.item.title);
- },
-
- todolistUpdateHandler: function () {
- var size;
- if (this.pauselistener) { return; }
- aria.templates.RefreshManager.stop();
- size = this.data.todolist.length;
- this.$json.setValue(this.data, 'emptylist', size === 0);
- this.$json.setValue(this.data, 'itemsleft', this.data.todolist.filter(function (e) { return !(e.completed); }).length);
- this.$json.setValue(this.data, 'itemscompleted', size - this.data.itemsleft);
- this.$json.setValue(this.data, 'toggleall', size === this.data.itemscompleted);
- aria.templates.RefreshManager.resume();
- this.moduleCtrl.saveTasks();
- }
-
- }
-});
diff --git a/examples/ariatemplates/js/view/TodoStyle.tpl.css b/examples/ariatemplates/js/view/TodoStyle.tpl.css
deleted file mode 100644
index 7ff2e4b8c1..0000000000
--- a/examples/ariatemplates/js/view/TodoStyle.tpl.css
+++ /dev/null
@@ -1,216 +0,0 @@
-{CSSTemplate {
- $classpath: 'js.view.TodoStyle',
- $dependencies: ['aria.core.Browser']
-}}
-
-{macro main ()}
-
-#label-toggle-all {
- display: none;
-}
-
-.toggle-all {
- position: absolute;
- top: -55px;
- left: -12px;
- width: 60px;
- height: 34px;
- text-align: center;
- border: none; /* Mobile Safari */
-}
-
-.toggle-all:before {
- content: '❯';
- font-size: 22px;
- color: #e6e6e6;
- padding: 10px 27px 10px 27px;
-}
-
-.toggle-all:checked:before {
- color: #737373;
-}
-
-.todo-list {
- margin: 0;
- padding: 0;
- list-style: none;
-}
-
-.todo-list li {
- position: relative;
- font-size: 24px;
- border-bottom: 1px solid #ededed;
-}
-
-.todo-list li:last-child {
- border-bottom: none;
-}
-
-.todo-list li.editing {
- border-bottom: none;
- padding: 0;
-}
-
-.todo-list li.editing .edit {
- display: block;
- width: 506px;
- padding: 13px 17px 12px 17px;
- margin: 0 0 0 43px;
-}
-
-.todo-list li.editing .view {
- display: none;
-}
-
-.todo-list li .toggle {
- text-align: center;
- width: 40px;
- /* auto, since non-WebKit browsers doesn't support input styling */
- height: auto;
- position: absolute;
- top: 0;
- bottom: 0;
- margin: auto 0;
- border: none; /* Mobile Safari */
- -webkit-appearance: none;
- -ms-appearance: none;
- appearance: none;
-}
-
-.todo-list li .toggle:after {
- content: url('data:image/svg+xml;utf8, ');
-}
-
-.todo-list li .toggle:checked:after {
- content: url('data:image/svg+xml;utf8, ');
-}
-
-.todo-list li label {
- white-space: pre;
- word-break: break-word;
- padding: 15px 60px 15px 15px;
- margin-left: 45px;
- display: block;
- line-height: 1.2;
- transition: color 0.4s;
-}
-
-.todo-list li.completed label {
- color: #d9d9d9;
- text-decoration: line-through;
-}
-
-.todo-list li .destroy {
- display: none;
- position: absolute;
- top: 0;
- right: 10px;
- bottom: 0;
- width: 40px;
- height: 40px;
- margin: auto 0;
- font-size: 30px;
- color: #cc9a9a;
- margin-bottom: 11px;
- transition: color 0.2s ease-out;
-}
-
-.todo-list li .destroy:hover {
- color: #af5b5e;
-}
-
-.todo-list li .destroy:after {
- content: '×';
-}
-
-.todo-list li:hover .destroy {
- display: block;
-}
-
-.todo-list li.editing:last-child {
- margin-bottom: -1px;
-}
-
-.todo-count {
- float: left;
- text-align: left;
-}
-
-.todo-count strong {
- font-weight: 300;
-}
-
-.filters {
- margin: 0;
- padding: 0;
- list-style: none;
- position: absolute;
- right: 0;
- left: 0;
-}
-
-.filters li {
- display: inline;
-}
-
-.filters li a {
- color: inherit;
- margin: 3px;
- padding: 3px 7px;
- text-decoration: none;
- border: 1px solid transparent;
- border-radius: 3px;
-}
-
-.filters li a.selected,
-.filters li a:hover {
- border-color: rgba(175, 47, 47, 0.1);
-}
-
-.filters li a.selected {
- border-color: rgba(175, 47, 47, 0.2);
-}
-
-.filter-active li.completed {
- display: none
-}
-
-.filter-completed li {
- display: none
-}
-.filter-completed li.completed {
- display: block
-}
-
-/*
- This replaces the original hack to remove background from Mobile Safari.
-*/
-{if aria.core.Browser.isWebkit}
-
-.toggle-all,
-.todo-list li .toggle {
- background: none;
-}
-
-.todo-list li .toggle {
- height: 40px;
-}
-
-.toggle-all {
- -webkit-transform: rotate(90deg);
- transform: rotate(90deg);
- -webkit-appearance: none;
- appearance: none;
-}
-
-{/if}
-
-@media (max-width: 430px) {
- .filters {
- bottom: 10px;
- }
-}
-
-{/macro}
-
-{/CSSTemplate}
\ No newline at end of file
diff --git a/examples/ariatemplates/node_modules/todomvc-app-css/index.css b/examples/ariatemplates/node_modules/todomvc-app-css/index.css
deleted file mode 100644
index d8be205ad4..0000000000
--- a/examples/ariatemplates/node_modules/todomvc-app-css/index.css
+++ /dev/null
@@ -1,376 +0,0 @@
-html,
-body {
- margin: 0;
- padding: 0;
-}
-
-button {
- margin: 0;
- padding: 0;
- border: 0;
- background: none;
- font-size: 100%;
- vertical-align: baseline;
- font-family: inherit;
- font-weight: inherit;
- color: inherit;
- -webkit-appearance: none;
- appearance: none;
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
-}
-
-body {
- font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
- line-height: 1.4em;
- background: #f5f5f5;
- color: #4d4d4d;
- min-width: 230px;
- max-width: 550px;
- margin: 0 auto;
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
- font-weight: 300;
-}
-
-:focus {
- outline: 0;
-}
-
-.hidden {
- display: none;
-}
-
-.todoapp {
- background: #fff;
- margin: 130px 0 40px 0;
- position: relative;
- box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2),
- 0 25px 50px 0 rgba(0, 0, 0, 0.1);
-}
-
-.todoapp input::-webkit-input-placeholder {
- font-style: italic;
- font-weight: 300;
- color: #e6e6e6;
-}
-
-.todoapp input::-moz-placeholder {
- font-style: italic;
- font-weight: 300;
- color: #e6e6e6;
-}
-
-.todoapp input::input-placeholder {
- font-style: italic;
- font-weight: 300;
- color: #e6e6e6;
-}
-
-.todoapp h1 {
- position: absolute;
- top: -155px;
- width: 100%;
- font-size: 100px;
- font-weight: 100;
- text-align: center;
- color: rgba(175, 47, 47, 0.15);
- -webkit-text-rendering: optimizeLegibility;
- -moz-text-rendering: optimizeLegibility;
- text-rendering: optimizeLegibility;
-}
-
-.new-todo,
-.edit {
- position: relative;
- margin: 0;
- width: 100%;
- font-size: 24px;
- font-family: inherit;
- font-weight: inherit;
- line-height: 1.4em;
- border: 0;
- color: inherit;
- padding: 6px;
- border: 1px solid #999;
- box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
- box-sizing: border-box;
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
-}
-
-.new-todo {
- padding: 16px 16px 16px 60px;
- border: none;
- background: rgba(0, 0, 0, 0.003);
- box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03);
-}
-
-.main {
- position: relative;
- z-index: 2;
- border-top: 1px solid #e6e6e6;
-}
-
-.toggle-all {
- text-align: center;
- border: none; /* Mobile Safari */
- opacity: 0;
- position: absolute;
-}
-
-.toggle-all + label {
- width: 60px;
- height: 34px;
- font-size: 0;
- position: absolute;
- top: -52px;
- left: -13px;
- -webkit-transform: rotate(90deg);
- transform: rotate(90deg);
-}
-
-.toggle-all + label:before {
- content: '❯';
- font-size: 22px;
- color: #e6e6e6;
- padding: 10px 27px 10px 27px;
-}
-
-.toggle-all:checked + label:before {
- color: #737373;
-}
-
-.todo-list {
- margin: 0;
- padding: 0;
- list-style: none;
-}
-
-.todo-list li {
- position: relative;
- font-size: 24px;
- border-bottom: 1px solid #ededed;
-}
-
-.todo-list li:last-child {
- border-bottom: none;
-}
-
-.todo-list li.editing {
- border-bottom: none;
- padding: 0;
-}
-
-.todo-list li.editing .edit {
- display: block;
- width: 506px;
- padding: 12px 16px;
- margin: 0 0 0 43px;
-}
-
-.todo-list li.editing .view {
- display: none;
-}
-
-.todo-list li .toggle {
- text-align: center;
- width: 40px;
- /* auto, since non-WebKit browsers doesn't support input styling */
- height: auto;
- position: absolute;
- top: 0;
- bottom: 0;
- margin: auto 0;
- border: none; /* Mobile Safari */
- -webkit-appearance: none;
- appearance: none;
-}
-
-.todo-list li .toggle {
- opacity: 0;
-}
-
-.todo-list li .toggle + label {
- /*
- Firefox requires `#` to be escaped - https://bugzilla.mozilla.org/show_bug.cgi?id=922433
- IE and Edge requires *everything* to be escaped to render, so we do that instead of just the `#` - https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7157459/
- */
- background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23ededed%22%20stroke-width%3D%223%22/%3E%3C/svg%3E');
- background-repeat: no-repeat;
- background-position: center left;
-}
-
-.todo-list li .toggle:checked + label {
- background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23bddad5%22%20stroke-width%3D%223%22/%3E%3Cpath%20fill%3D%22%235dc2af%22%20d%3D%22M72%2025L42%2071%2027%2056l-4%204%2020%2020%2034-52z%22/%3E%3C/svg%3E');
-}
-
-.todo-list li label {
- word-break: break-all;
- padding: 15px 15px 15px 60px;
- display: block;
- line-height: 1.2;
- transition: color 0.4s;
-}
-
-.todo-list li.completed label {
- color: #d9d9d9;
- text-decoration: line-through;
-}
-
-.todo-list li .destroy {
- display: none;
- position: absolute;
- top: 0;
- right: 10px;
- bottom: 0;
- width: 40px;
- height: 40px;
- margin: auto 0;
- font-size: 30px;
- color: #cc9a9a;
- margin-bottom: 11px;
- transition: color 0.2s ease-out;
-}
-
-.todo-list li .destroy:hover {
- color: #af5b5e;
-}
-
-.todo-list li .destroy:after {
- content: '×';
-}
-
-.todo-list li:hover .destroy {
- display: block;
-}
-
-.todo-list li .edit {
- display: none;
-}
-
-.todo-list li.editing:last-child {
- margin-bottom: -1px;
-}
-
-.footer {
- color: #777;
- padding: 10px 15px;
- height: 20px;
- text-align: center;
- border-top: 1px solid #e6e6e6;
-}
-
-.footer:before {
- content: '';
- position: absolute;
- right: 0;
- bottom: 0;
- left: 0;
- height: 50px;
- overflow: hidden;
- box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2),
- 0 8px 0 -3px #f6f6f6,
- 0 9px 1px -3px rgba(0, 0, 0, 0.2),
- 0 16px 0 -6px #f6f6f6,
- 0 17px 2px -6px rgba(0, 0, 0, 0.2);
-}
-
-.todo-count {
- float: left;
- text-align: left;
-}
-
-.todo-count strong {
- font-weight: 300;
-}
-
-.filters {
- margin: 0;
- padding: 0;
- list-style: none;
- position: absolute;
- right: 0;
- left: 0;
-}
-
-.filters li {
- display: inline;
-}
-
-.filters li a {
- color: inherit;
- margin: 3px;
- padding: 3px 7px;
- text-decoration: none;
- border: 1px solid transparent;
- border-radius: 3px;
-}
-
-.filters li a:hover {
- border-color: rgba(175, 47, 47, 0.1);
-}
-
-.filters li a.selected {
- border-color: rgba(175, 47, 47, 0.2);
-}
-
-.clear-completed,
-html .clear-completed:active {
- float: right;
- position: relative;
- line-height: 20px;
- text-decoration: none;
- cursor: pointer;
-}
-
-.clear-completed:hover {
- text-decoration: underline;
-}
-
-.info {
- margin: 65px auto 0;
- color: #bfbfbf;
- font-size: 10px;
- text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
- text-align: center;
-}
-
-.info p {
- line-height: 1;
-}
-
-.info a {
- color: inherit;
- text-decoration: none;
- font-weight: 400;
-}
-
-.info a:hover {
- text-decoration: underline;
-}
-
-/*
- Hack to remove background from Mobile Safari.
- Can't use it globally since it destroys checkboxes in Firefox
-*/
-@media screen and (-webkit-min-device-pixel-ratio:0) {
- .toggle-all,
- .todo-list li .toggle {
- background: none;
- }
-
- .todo-list li .toggle {
- height: 40px;
- }
-}
-
-@media (max-width: 430px) {
- .footer {
- height: 50px;
- }
-
- .filters {
- bottom: 10px;
- }
-}
diff --git a/examples/ariatemplates/node_modules/todomvc-common/base.css b/examples/ariatemplates/node_modules/todomvc-common/base.css
deleted file mode 100644
index da65968a73..0000000000
--- a/examples/ariatemplates/node_modules/todomvc-common/base.css
+++ /dev/null
@@ -1,141 +0,0 @@
-hr {
- margin: 20px 0;
- border: 0;
- border-top: 1px dashed #c5c5c5;
- border-bottom: 1px dashed #f7f7f7;
-}
-
-.learn a {
- font-weight: normal;
- text-decoration: none;
- color: #b83f45;
-}
-
-.learn a:hover {
- text-decoration: underline;
- color: #787e7e;
-}
-
-.learn h3,
-.learn h4,
-.learn h5 {
- margin: 10px 0;
- font-weight: 500;
- line-height: 1.2;
- color: #000;
-}
-
-.learn h3 {
- font-size: 24px;
-}
-
-.learn h4 {
- font-size: 18px;
-}
-
-.learn h5 {
- margin-bottom: 0;
- font-size: 14px;
-}
-
-.learn ul {
- padding: 0;
- margin: 0 0 30px 25px;
-}
-
-.learn li {
- line-height: 20px;
-}
-
-.learn p {
- font-size: 15px;
- font-weight: 300;
- line-height: 1.3;
- margin-top: 0;
- margin-bottom: 0;
-}
-
-#issue-count {
- display: none;
-}
-
-.quote {
- border: none;
- margin: 20px 0 60px 0;
-}
-
-.quote p {
- font-style: italic;
-}
-
-.quote p:before {
- content: '“';
- font-size: 50px;
- opacity: .15;
- position: absolute;
- top: -20px;
- left: 3px;
-}
-
-.quote p:after {
- content: '”';
- font-size: 50px;
- opacity: .15;
- position: absolute;
- bottom: -42px;
- right: 3px;
-}
-
-.quote footer {
- position: absolute;
- bottom: -40px;
- right: 0;
-}
-
-.quote footer img {
- border-radius: 3px;
-}
-
-.quote footer a {
- margin-left: 5px;
- vertical-align: middle;
-}
-
-.speech-bubble {
- position: relative;
- padding: 10px;
- background: rgba(0, 0, 0, .04);
- border-radius: 5px;
-}
-
-.speech-bubble:after {
- content: '';
- position: absolute;
- top: 100%;
- right: 30px;
- border: 13px solid transparent;
- border-top-color: rgba(0, 0, 0, .04);
-}
-
-.learn-bar > .learn {
- position: absolute;
- width: 272px;
- top: 8px;
- left: -300px;
- padding: 10px;
- border-radius: 5px;
- background-color: rgba(255, 255, 255, .6);
- transition-property: left;
- transition-duration: 500ms;
-}
-
-@media (min-width: 899px) {
- .learn-bar {
- width: auto;
- padding-left: 300px;
- }
-
- .learn-bar > .learn {
- left: 8px;
- }
-}
diff --git a/examples/ariatemplates/node_modules/todomvc-common/base.js b/examples/ariatemplates/node_modules/todomvc-common/base.js
deleted file mode 100644
index 44fb50c613..0000000000
--- a/examples/ariatemplates/node_modules/todomvc-common/base.js
+++ /dev/null
@@ -1,244 +0,0 @@
-/* global _ */
-(function () {
- 'use strict';
-
- /* jshint ignore:start */
- // Underscore's Template Module
- // Courtesy of underscorejs.org
- var _ = (function (_) {
- _.defaults = function (object) {
- if (!object) {
- return object;
- }
- for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {
- var iterable = arguments[argsIndex];
- if (iterable) {
- for (var key in iterable) {
- if (object[key] == null) {
- object[key] = iterable[key];
- }
- }
- }
- }
- return object;
- }
-
- // By default, Underscore uses ERB-style template delimiters, change the
- // following template settings to use alternative delimiters.
- _.templateSettings = {
- evaluate : /<%([\s\S]+?)%>/g,
- interpolate : /<%=([\s\S]+?)%>/g,
- escape : /<%-([\s\S]+?)%>/g
- };
-
- // When customizing `templateSettings`, if you don't want to define an
- // interpolation, evaluation or escaping regex, we need one that is
- // guaranteed not to match.
- var noMatch = /(.)^/;
-
- // Certain characters need to be escaped so that they can be put into a
- // string literal.
- var escapes = {
- "'": "'",
- '\\': '\\',
- '\r': 'r',
- '\n': 'n',
- '\t': 't',
- '\u2028': 'u2028',
- '\u2029': 'u2029'
- };
-
- var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
-
- // JavaScript micro-templating, similar to John Resig's implementation.
- // Underscore templating handles arbitrary delimiters, preserves whitespace,
- // and correctly escapes quotes within interpolated code.
- _.template = function(text, data, settings) {
- var render;
- settings = _.defaults({}, settings, _.templateSettings);
-
- // Combine delimiters into one regular expression via alternation.
- var matcher = new RegExp([
- (settings.escape || noMatch).source,
- (settings.interpolate || noMatch).source,
- (settings.evaluate || noMatch).source
- ].join('|') + '|$', 'g');
-
- // Compile the template source, escaping string literals appropriately.
- var index = 0;
- var source = "__p+='";
- text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
- source += text.slice(index, offset)
- .replace(escaper, function(match) { return '\\' + escapes[match]; });
-
- if (escape) {
- source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
- }
- if (interpolate) {
- source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
- }
- if (evaluate) {
- source += "';\n" + evaluate + "\n__p+='";
- }
- index = offset + match.length;
- return match;
- });
- source += "';\n";
-
- // If a variable is not specified, place data values in local scope.
- if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
-
- source = "var __t,__p='',__j=Array.prototype.join," +
- "print=function(){__p+=__j.call(arguments,'');};\n" +
- source + "return __p;\n";
-
- try {
- render = new Function(settings.variable || 'obj', '_', source);
- } catch (e) {
- e.source = source;
- throw e;
- }
-
- if (data) return render(data, _);
- var template = function(data) {
- return render.call(this, data, _);
- };
-
- // Provide the compiled function source as a convenience for precompilation.
- template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
-
- return template;
- };
-
- return _;
- })({});
-
- if (location.hostname === 'todomvc.com') {
- window._gaq = [['_setAccount','UA-31081062-1'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script'));
- }
- /* jshint ignore:end */
-
- function redirect() {
- if (location.hostname === 'tastejs.github.io') {
- location.href = location.href.replace('tastejs.github.io/todomvc', 'todomvc.com');
- }
- }
-
- function findRoot() {
- var base = location.href.indexOf('examples/');
- return location.href.substr(0, base);
- }
-
- function getFile(file, callback) {
- if (!location.host) {
- return console.info('Miss the info bar? Run TodoMVC from a server to avoid a cross-origin error.');
- }
-
- var xhr = new XMLHttpRequest();
-
- xhr.open('GET', findRoot() + file, true);
- xhr.send();
-
- xhr.onload = function () {
- if (xhr.status === 200 && callback) {
- callback(xhr.responseText);
- }
- };
- }
-
- function Learn(learnJSON, config) {
- if (!(this instanceof Learn)) {
- return new Learn(learnJSON, config);
- }
-
- var template, framework;
-
- if (typeof learnJSON !== 'object') {
- try {
- learnJSON = JSON.parse(learnJSON);
- } catch (e) {
- return;
- }
- }
-
- if (config) {
- template = config.template;
- framework = config.framework;
- }
-
- if (!template && learnJSON.templates) {
- template = learnJSON.templates.todomvc;
- }
-
- if (!framework && document.querySelector('[data-framework]')) {
- framework = document.querySelector('[data-framework]').dataset.framework;
- }
-
- this.template = template;
-
- if (learnJSON.backend) {
- this.frameworkJSON = learnJSON.backend;
- this.frameworkJSON.issueLabel = framework;
- this.append({
- backend: true
- });
- } else if (learnJSON[framework]) {
- this.frameworkJSON = learnJSON[framework];
- this.frameworkJSON.issueLabel = framework;
- this.append();
- }
-
- this.fetchIssueCount();
- }
-
- Learn.prototype.append = function (opts) {
- var aside = document.createElement('aside');
- aside.innerHTML = _.template(this.template, this.frameworkJSON);
- aside.className = 'learn';
-
- if (opts && opts.backend) {
- // Remove demo link
- var sourceLinks = aside.querySelector('.source-links');
- var heading = sourceLinks.firstElementChild;
- var sourceLink = sourceLinks.lastElementChild;
- // Correct link path
- var href = sourceLink.getAttribute('href');
- sourceLink.setAttribute('href', href.substr(href.lastIndexOf('http')));
- sourceLinks.innerHTML = heading.outerHTML + sourceLink.outerHTML;
- } else {
- // Localize demo links
- var demoLinks = aside.querySelectorAll('.demo-link');
- Array.prototype.forEach.call(demoLinks, function (demoLink) {
- if (demoLink.getAttribute('href').substr(0, 4) !== 'http') {
- demoLink.setAttribute('href', findRoot() + demoLink.getAttribute('href'));
- }
- });
- }
-
- document.body.className = (document.body.className + ' learn-bar').trim();
- document.body.insertAdjacentHTML('afterBegin', aside.outerHTML);
- };
-
- Learn.prototype.fetchIssueCount = function () {
- var issueLink = document.getElementById('issue-count-link');
- if (issueLink) {
- var url = issueLink.href.replace('https://github.com', 'https://api.github.com/repos');
- var xhr = new XMLHttpRequest();
- xhr.open('GET', url, true);
- xhr.onload = function (e) {
- var parsedResponse = JSON.parse(e.target.responseText);
- if (parsedResponse instanceof Array) {
- var count = parsedResponse.length
- if (count !== 0) {
- issueLink.innerHTML = 'This app has ' + count + ' open issues';
- document.getElementById('issue-count').style.display = 'inline';
- }
- }
- };
- xhr.send();
- }
- };
-
- redirect();
- getFile('learn.json', Learn);
-})();
diff --git a/examples/ariatemplates/package.json b/examples/ariatemplates/package.json
deleted file mode 100644
index 46dbefe6d2..0000000000
--- a/examples/ariatemplates/package.json
+++ /dev/null
@@ -1,7 +0,0 @@
-{
- "private": true,
- "dependencies": {
- "todomvc-common": "^1.0.1",
- "todomvc-app-css": "^2.1.0"
- }
-}
diff --git a/examples/ariatemplates/readme.md b/examples/ariatemplates/readme.md
deleted file mode 100644
index 77883a1e20..0000000000
--- a/examples/ariatemplates/readme.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# Aria Templates TodoMVC Example
-
-> Aria Templates (aka AT) is an application framework written in JavaScript for building rich and large-scaled enterprise web applications.
-
-> _[Aria Templates - ariatemplates.com](http://ariatemplates.com)_
-
-
-## Learning Aria Templates
-
-The [Aria Templates website](http://ariatemplates.com) is a great resource for getting started.
-
-Here are some links you may find helpful:
-
-* [Documentation](http://ariatemplates.com/usermanual)
-* [API Reference](http://ariatemplates.com/aria/guide/apps/apidocs)
-* [Guides](http://ariatemplates.com/guides)
-* [Blog](http://ariatemplates.com/blog)
-* [FAQ](http://ariatemplates.com/faq)
-* [Aria Templates on GitHub](https://github.com/ariatemplates)
-
-Get help from other Aria Templates users:
-
-* [Aria Templates on StackOverflow](http://stackoverflow.com/questions/tagged/ariatemplates)
-* [Forums](http://ariatemplates.com/forum)
-* [Aria Templates on Twitter](http://twitter.com/ariatemplates)
-
-_If you have other helpful links to share, or find any of the links above no longer work, please [let us know](https://github.com/tastejs/todomvc/issues)._
diff --git a/examples/atmajs/.gitignore b/examples/atmajs/.gitignore
deleted file mode 100644
index 10079b2979..0000000000
--- a/examples/atmajs/.gitignore
+++ /dev/null
@@ -1,18 +0,0 @@
-node_modules/atma-class/*
-!node_modules/atma-class/lib/class.js
-
-node_modules/includejs/*
-!node_modules/includejs/lib/include.js
-
-node_modules/maskjs/*
-!node_modules/maskjs/lib/mask.js
-
-node_modules/ruta/*
-!node_modules/ruta/lib/ruta.js
-
-node_modules/todomvc-app-css/*
-!node_modules/todomvc-app-css/index.css
-
-node_modules/todomvc-common/*
-!node_modules/todomvc-common/base.css
-!node_modules/todomvc-common/base.js
diff --git a/examples/atmajs/index.html b/examples/atmajs/index.html
deleted file mode 100644
index 82abe48597..0000000000
--- a/examples/atmajs/index.html
+++ /dev/null
@@ -1,23 +0,0 @@
-
-
-
-
- Atma.js • TodoMVC
-
-
-
-
-
-
-
-
-
-
-
diff --git a/examples/atmajs/js/Controls/Filter.mask b/examples/atmajs/js/Controls/Filter.mask
deleted file mode 100644
index cd48222f12..0000000000
--- a/examples/atmajs/js/Controls/Filter.mask
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * Filter Presentation:
- * - HASH-change listener
- * - navigation(filter) buttons
- */
-define Filter {
- var filters = {
- '' : 'All',
- active: 'Active',
- completed: 'Completed'
- };
-
- ul .filters {
- for ((key, val) in filters) {
- // compare with the scoped value `action`
- li >
- a .~[bind: action == key ? 'selected' ] href = '#~key' >
- '~val'
- }
- }
-}
diff --git a/examples/atmajs/js/Controls/TodoInput.mask b/examples/atmajs/js/Controls/TodoInput.mask
deleted file mode 100644
index 35e77a52eb..0000000000
--- a/examples/atmajs/js/Controls/TodoInput.mask
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * Extend INPUT tag to edit a todo's title
- * - format string
- * - complete edit on ENTER
- * - complete edit on BLUR
- *
- * Used as
- * - the main application's input
- * - single todo item editor
- *
- * Public Signals
- * - cancel: input interrupted
- * - submit: input formatted and completed
- */
-define TodoInput as (input type='text') {
-
- event blur (e) {
- this.submit();
- }
-
- event press:esc (e) {
- this.cancel();
- }
-
- event press:enter (e) {
- this.submit();
- // prevent IE from button click - `Clear Completed`
- e.preventDefault();
- }
-
- function submit () {
- var str = this.$.val().trim();
- this.emitOut('submit', str);
- this.afterEdit();
- }
-
- function cancel () {
- this.emitOut('cancel');
- this.afterEdit();
- }
-
- function afterEdit () {
- this.$.val(this.attr.preserve ? this.model.title : '');
- }
-}
diff --git a/examples/atmajs/js/Store/Todos.js b/examples/atmajs/js/Store/Todos.js
deleted file mode 100644
index 0455fd8563..0000000000
--- a/examples/atmajs/js/Store/Todos.js
+++ /dev/null
@@ -1,77 +0,0 @@
-/*jshint newcap:false */
-/*global Class, include */
-
-(function () {
- 'use strict';
-
- var Todo = Class({
- Base: Class.Serializable,
-
- // Properties with default values
- title: '',
- completed: false
- });
-
-
- include.exports = Class.Collection(Todo, {
- Store: Class.LocalStore('todos-atmajs'),
- create: function (title) {
- // `push` initilizes the `Task` instance. It does the same
- // as if we would do this via `new Task({title: title})`
- return this
- .push({
- title: title
- })
- .save();
- },
- toggleAll: function (completed) {
- this
- .forEach(function (task) {
- task.completed = completed;
- })
- .save();
- },
- removeCompleted: function () {
- this.del(function (x) {
- return x.completed === true;
- });
- },
- status: {
- count: 0,
- todoCount: 0,
- completedCount: 0
- },
- Override: {
- // Override mutators and recalculate status,
- // which will be used lately in M-V bindings
- save: function () {
- return this
- .super(arguments)
- .calcStatus();
- },
- del: function () {
- return this
- .super(arguments)
- .calcStatus();
- },
- fetch: function () {
- return this
- .super(arguments)
- .calcStatus();
- }
- },
- calcStatus: function () {
- var todos = 0;
- var completed = 0;
- this.forEach(function (todo) {
- todo.completed && ++completed || ++todos;
- });
-
- this.status.count = this.length;
- this.status.todoCount = todos;
- this.status.completedCount = completed;
- return this;
- }
- });
-
-}());
diff --git a/examples/atmajs/js/Todos/TodoList.mask b/examples/atmajs/js/Todos/TodoList.mask
deleted file mode 100644
index bf1168e7a2..0000000000
--- a/examples/atmajs/js/Todos/TodoList.mask
+++ /dev/null
@@ -1,30 +0,0 @@
-import TodoTask from 'TodoTask';
-
-define TodoList {
-
- slot toggleAll (event) {
- var completed = event.currentTarget.checked;
- this.model.toggleAll(completed);
- }
-
- slot taskChanged () {
- this.model.save();
- }
-
- slot taskRemoved (event, task) {
- this.model.del(task);
- }
-
- input .toggle-all
- type = checkbox
- checked = '~[bind: status.todoCount == 0 ? "checked" ]'
- x-tap = toggleAll
- ;
-
- label for='toggle-all' > 'Mark all as complete'
-
- ul .todo-list {
- // bind todos collection
- +each (.) > TodoTask;
- }
-}
diff --git a/examples/atmajs/js/Todos/TodoTask.js b/examples/atmajs/js/Todos/TodoTask.js
deleted file mode 100644
index 8dbd229553..0000000000
--- a/examples/atmajs/js/Todos/TodoTask.js
+++ /dev/null
@@ -1,75 +0,0 @@
-/*jshint newcap:false */
-/*global include, mask, Compo */
-
-/**
- * Single Todo Item Component
- * - View
- * - Edit
- *
- * Public signals -
- * taskChanged: Todo's state or title was changed
- * taskRemoved: Todo was removed
- * @arguments: Todo Model
- *
- */
-
-(function () {
- 'use strict';
-
- var STATE_VIEW = '';
- var STATE_EDIT = 'editing';
- include.exports = {
- scope: {
- state: STATE_VIEW
- },
-
- slots: {
- taskChanged: function () {
- if (!this.model.title) {
-
- // [emitIn/emitOut] signal propagation begins from a sender
- this.emitOut('taskRemoved');
-
- // stop propagation of the `taskChanged` signal
- return false;
- }
-
- this.scope.state = STATE_VIEW;
- },
- taskRemoved: function () {
- // remove component
- this.remove();
-
- // add arguments to the signal
- return [this.model];
- },
- cancel: function () {
- this.scope.state = STATE_VIEW;
- },
- submit: function () {
- // do not send the signal to the app
- return false;
- },
- edit: function () {
- this.scope.state = STATE_EDIT;
- this.compos.input.$.focus();
- }
- },
- compos: {
- input: 'compo: TaskEdit'
- },
-
- //= Private Methods
-
- _isVisible: function (completed, action) {
- if (action === 'completed' && !completed) {
- return false;
- }
- if (action === 'active' && completed) {
- return false;
- }
- return true;
- }
- };
-
-})();
diff --git a/examples/atmajs/js/Todos/TodoTask.mask b/examples/atmajs/js/Todos/TodoTask.mask
deleted file mode 100644
index 7bc8438d2b..0000000000
--- a/examples/atmajs/js/Todos/TodoTask.mask
+++ /dev/null
@@ -1,47 +0,0 @@
-import * as TodoTaskController from 'TodoTask.js';
-import TodoInput from '../Controls/TodoInput';
-
-define TodoTask extends TodoTaskController {
-
- let TaskView as (.view) {
-
- input.toggle type=checkbox {
- dualbind
- value = completed
- // emit signal when INPUTs state changes via user input
- x-signal = 'dom: taskChanged'
- ;
- }
- label > '~[bind:title]';
- button.destroy x-tap = 'taskRemoved';
- }
-
- let TaskEdit as (input.edit preserve) extends TodoInput {
-
- dualbind
- value = 'title'
- dom-slot = submit
-
- // emit `taskChange` signal each time model is changed
- // via user input
- x-signal = 'dom: taskChanged'
- ;
-
- }
-
- /* `+visible` is same as `+if` with one difference:
- * by falsy condition it still renders the nodes (with display:none)
- * and `+if` first renders only when the condition becomes true.
- */
- +visible ($._isVisible(completed, action)) {
- li
- .~[bind:completed ? 'completed']
- .~[bind:state]
- // emit `edit` on `dblclick` event
- x-signal = 'dblclick: edit'
- {
- TaskView;
- TaskEdit;
- }
- }
-}
diff --git a/examples/atmajs/js/app.js b/examples/atmajs/js/app.js
deleted file mode 100644
index aa8e6ae858..0000000000
--- a/examples/atmajs/js/app.js
+++ /dev/null
@@ -1,44 +0,0 @@
-/*jshint newcap:false */
-/*global include, mask, Compo, ruta */
-
-'use strict';
-
-/**
- * Controller for the App Component
- *
- * - load model dependecies
- */
-
-include
- .js('Store/Todos.js')
- .done(function (resp) {
-
- include.exports = {
- model: resp.Todos.fetch(),
- scope: {
- action: ''
- },
- slots: {
- submit: function (event, title) {
- if (title) {
- this.model.create(title);
- }
- },
- removeAllCompleted: function () {
- this.model.removeCompleted();
- }
- },
- onRenderStart: function () {
- // (RutaJS) Default router is the History API,
- // but for this app-spec we enable hashes
- ruta
- .setRouterType('hash')
- .add('/?:action', this.applyFilter.bind(this))
- .notifyCurrent()
- ;
- },
- applyFilter: function (route, params) {
- this.scope.action = params.action || '';
- }
- };
- });
diff --git a/examples/atmajs/js/app.mask b/examples/atmajs/js/app.mask
deleted file mode 100644
index a4d240c0b1..0000000000
--- a/examples/atmajs/js/app.mask
+++ /dev/null
@@ -1,42 +0,0 @@
-import * as AppController from 'app.js';
-import TodoInput from 'Controls/TodoInput';
-import TodoList from 'Todos/TodoList';
-import Filter from 'Controls/Filter';
-
-define App extends AppController {
- section .todoapp {
- header {
- h1 > 'todos'
-
- TodoInput .new-todo
- autofocus
- placeholder = 'What needs to be done?'
- ;
- }
-
- +if (status.count) {
- section .main >
- TodoList;
-
- footer .footer {
-
- span .todo-count {
- strong > '~[bind: status.todoCount]'
- span > ' item~[bind: status.todoCount != 1 ? "s"] left'
- }
-
- Filter;
-
- +if (status.completedCount > 0) {
- button .clear-completed x-tap = 'removeAllCompleted' >
- 'Clear completed'
- }
- }
- }
- }
- footer .info {
- p { 'Double-click to edit a todo' }
- p { 'Created by ' a href='http://github.com/tenbits' > 'Alex Kit' }
- p { 'Part of ' a href='http://todomvc.com' > 'TodoMVC' }
- }
-}
diff --git a/examples/atmajs/node_modules/atma-class/lib/class.js b/examples/atmajs/node_modules/atma-class/lib/class.js
deleted file mode 100644
index 9140390af6..0000000000
--- a/examples/atmajs/node_modules/atma-class/lib/class.js
+++ /dev/null
@@ -1,3550 +0,0 @@
-// source /src/license.txt
-/*!
- * ClassJS v1.0.68
- * Part of the Atma.js Project
- * http://atmajs.com/
- *
- * MIT license
- * http://opensource.org/licenses/MIT
- *
- * (c) 2012, 2015 Atma.js and other contributors
- */
-// end:source /src/license.txt
-// source /src/umd.js
-(function(root, factory){
- "use strict";
-
- var _global = typeof window === 'undefined' || window.navigator == null
- ? global
- : window
- ,
- _exports
- ;
-
- _exports = root || _global;
-
- function construct(){
- return factory(_global, _exports);
- }
-
-
- if (typeof define === 'function' && define.amd) {
- return define(construct);
- }
-
- // Browser OR Node
- construct();
-
- if (typeof module !== 'undefined')
- module.exports = _exports.Class;
-
-}(this, function(global, exports){
- "use strict";
-// end:source /src/umd.js
-
- // source /src/vars.js
- var _Array_slice = Array.prototype.slice,
- _Array_sort = Array.prototype.sort,
-
- _cfg = {
- ModelHost: null, // @default: Class.Model
- };
-
-
- var str_CLASS_IDENTITY = '__$class__';
- // end:source /src/vars.js
-
- // source /src/util/is.js
- var is_Function,
- is_Object,
- is_Array,
- is_ArrayLike,
- is_String,
- is_Date,
- is_notEmptyString,
- is_rawObject,
- is_NullOrGlobal;
- (function(){
-
- is_Function = function(x) {
- return typeof x === 'function';
- };
- is_Object = function(x) {
- return x != null
- && typeof x === 'object';
- };
- is_Date = function(x){
- return x != null
- && x.constructor.name === 'Date'
- && x instanceof Date;
- };
- is_Array = function(x) {
- return x != null
- && typeof x.length === 'number'
- && typeof x.slice === 'function';
- };
- is_ArrayLike = is_Array;
-
- is_String = function(x) {
- return typeof x === 'string';
- };
-
- is_notEmptyString = function(x) {
- return typeof x === 'string'
- && x !== '';
- };
-
- is_rawObject = function(obj) {
- if (obj == null)
- return false;
-
- if (typeof obj !== 'object')
- return false;
-
- return obj.constructor === Object;
- };
- is_NullOrGlobal = function(ctx){
- return ctx === void 0 || ctx === global;
- };
-
- }());
-
- // end:source /src/util/is.js
- // source /src/util/array.js
- var arr_each,
- arr_isArray,
- arr_remove
- ;
-
- (function(){
-
- arr_each = function(array, callback) {
-
- if (arr_isArray(array)) {
- for (var i = 0, imax = array.length; i < imax; i++){
- callback(array[i], i);
- }
- return;
- }
-
- callback(array);
- };
-
- arr_isArray = function(array) {
- return array != null
- && typeof array === 'object'
- && typeof array.length === 'number'
- && typeof array.splice === 'function';
- };
-
- arr_remove = function(array, fn){
- var imax = array.length,
- i = -1;
- while ( ++i < imax){
- if (fn(array[i]) === true) {
- array.splice(i, 1);
- i--;
- imax--;
- }
- }
- };
-
- /* polyfill */
- if (typeof Array.isArray !== 'function') {
- Array.isArray = function(array){
- if (array instanceof Array){
- return true;
- }
-
- if (array == null || typeof array !== 'object') {
- return false;
- }
-
-
- return array.length !== void 0 && typeof array.slice === 'function';
- };
- }
-
- }());
-
- // end:source /src/util/array.js
- // source /src/util/class.js
- var class_register,
- class_get,
-
- class_patch,
-
- class_stringify,
- class_parse,
- class_properties
-
- ;
-
- (function(){
-
- class_register = function(namespace, class_){
-
- obj_setProperty(
- _cfg.ModelHost || Class.Model,
- namespace,
- class_
- );
- };
-
- class_get = function(namespace){
-
- return obj_getProperty(
- _cfg.ModelHost || Class.Model,
- namespace
- );
- };
-
- class_patch = function(mix, Proto){
-
- var class_ = is_String(mix)
- ? class_get(mix)
- : mix
- ;
-
- // if DEBUG
- !is_Function(class_)
- && console.error(' Not a Function', mix);
- // endif
-
- Proto.Base = class_;
-
- class_ = Class(Proto);
-
- if (is_String(mix))
- class_register(mix, class_);
-
- return class_;
- };
-
- class_stringify = function(class_){
-
- return JSON.stringify(class_, stringify);
- };
-
- class_parse = function(str){
-
- return JSON.parse(str, parse);
- };
-
- class_properties = function(Ctor) {
- return getProperties(Ctor);
- };
-
- // private
-
- function stringify(key, val) {
-
- if (val == null || typeof val !== 'object')
- return val;
-
- var current = this,
- obj = current[key]
- ;
-
- if (obj[str_CLASS_IDENTITY] && obj.toJSON) {
-
- return stringifyMetaJSON(obj[str_CLASS_IDENTITY], val)
-
- ////val[str_CLASS_IDENTITY] = obj[str_CLASS_IDENTITY];
- ////return val;
- }
-
-
- return val;
- }
-
- function stringifyMetaJSON(className, json){
- var out = {};
- out['json'] = json;
- out[str_CLASS_IDENTITY] = className;
-
- return out;
- }
-
- function parse(key, val) {
-
- var Ctor;
-
- if (val != null && typeof val === 'object' && val[str_CLASS_IDENTITY]) {
- Ctor = Class(val[str_CLASS_IDENTITY]);
-
- if (typeof Ctor === 'function') {
-
- val = new Ctor(val.json);
- } else {
-
- console.error(' Class was not registered', val[str_CLASS_IDENTITY]);
- }
- }
-
- return val;
- }
-
- function getProperties(proto, out){
- if (typeof proto === 'function')
- proto = proto.prototype;
-
- if (out == null)
- out = {};
-
- var type,
- key,
- val;
- for(key in proto){
- val = proto[key];
- type = val == null
- ? null
- : typeof val
- ;
-
- if (type === 'function')
- continue;
-
- var c = key.charCodeAt(0);
- if (c === 95 && key !== '_id')
- // _
- continue;
-
- if (c >= 65 && c <= 90)
- // A-Z
- continue;
-
- if (type === 'object') {
- var ctor = val.constructor,
- ctor_name = ctor && ctor.name
- ;
-
- if (ctor_name !== 'Object' && ctor_name && global[ctor_name] === ctor) {
- // built-in objects
- out[key] = ctor_name;
- continue;
- }
-
- out[key] = getProperties(val);
- continue;
- }
-
- out[key] = type;
- }
-
- if (proto.__proto__)
- getProperties(proto.__proto__, out);
-
- return out;
- }
-
- }());
- // end:source /src/util/class.js
- // source /src/util/proto.js
- var class_inherit,
- class_inheritStatics,
- class_extendProtoObjects
- ;
-
- (function(){
-
- var PROTO = '__proto__';
-
- var _toString = Object.prototype.toString,
- _isArguments = function(args){
- return _toString.call(args) === '[object Arguments]';
- };
-
-
- class_inherit = PROTO in Object.prototype
- ? inherit
- : inherit_protoLess
- ;
-
- class_inheritStatics = function(_class, mix){
- if (mix == null)
- return;
-
- if (is_ArrayLike(mix)) {
- var i = mix.length;
- while ( --i > -1 ) {
- class_inheritStatics(_class, mix[i]);
- }
- return;
- }
-
- var Static;
- if (is_Function(mix))
- Static = mix;
- else if (is_Object(mix.Static))
- Static = mix.Static;
-
-
- if (Static == null)
- return;
-
- obj_extendDescriptorsDefaults(_class, Static);
- };
-
-
- class_extendProtoObjects = function(proto, _base, _extends){
- var key,
- protoValue;
-
- for (key in proto) {
- protoValue = proto[key];
-
- if (!is_rawObject(protoValue))
- continue;
-
- if (_base != null){
- if (is_rawObject(_base.prototype[key]))
- obj_defaults(protoValue, _base.prototype[key]);
- }
-
- if (_extends != null) {
- arr_each(
- _extends,
- proto_extendDefaultsDelegate(protoValue, key)
- );
- }
- }
- }
-
-
- // PRIVATE
-
- function proto_extendDefaultsDelegate(target, key) {
- return function(source){
- var proto = proto_getProto(source),
- val = proto[key];
- if (is_rawObject(val)) {
- obj_defaults(target, val);
- }
- }
- }
-
- function proto_extend(proto, source) {
- if (source == null)
- return;
-
- if (typeof proto === 'function')
- proto = proto.prototype;
-
- if (typeof source === 'function')
- source = source.prototype;
-
- var key, val;
- for (key in source) {
- if (key === 'constructor')
- continue;
-
- val = source[key];
- if (val != null)
- proto[key] = val;
- }
- }
-
- function proto_override(super_, fn) {
- var proxy;
-
- if (super_) {
- proxy = function(mix){
-
- var args = arguments.length === 1 && _isArguments(mix)
- ? mix
- : arguments
- ;
-
- return fn_apply(super_, this, args);
- }
- } else{
- proxy = fn_doNothing;
- }
-
-
- return function(){
- this['super'] = proxy;
-
- return fn_apply(fn, this, arguments);
- };
- }
-
- function inherit(_class, _base, _extends, original, _overrides, defaults) {
- var prototype = original,
- proto = original;
-
- prototype.constructor = _class.prototype.constructor;
-
- if (_extends != null) {
- proto[PROTO] = {};
-
- arr_each(_extends, function(x) {
- proto_extend(proto[PROTO], x);
- });
- proto = proto[PROTO];
- }
-
- if (_base != null)
- proto[PROTO] = _base.prototype;
-
- for (var key in defaults) {
- if (prototype[key] == null)
- prototype[key] = defaults[key];
- }
- for (var key in _overrides) {
- prototype[key] = proto_override(prototype[key], _overrides[key]);
- }
-
-
- _class.prototype = prototype;
- }
- function inherit_Object_create(_class, _base, _extends, original, _overrides, defaults) {
-
- if (_base != null) {
- _class.prototype = Object.create(_base.prototype);
- obj_extendDescriptors(_class.prototype, original);
- } else {
- _class.prototype = Object.create(original);
- }
-
- _class.prototype.constructor = _class;
-
- if (_extends != null) {
- arr_each(_extends, function(x) {
- obj_defaults(_class.prototype, x);
- });
- }
-
- var proto = _class.prototype;
- obj_defaults(proto, defaults);
- for (var key in _overrides) {
- proto[key] = proto_override(proto[key], _overrides[key]);
- }
- }
-
-
- // browser that doesnt support __proto__
- function inherit_protoLess(_class, _base, _extends, original, _overrides, defaults) {
-
- if (_base != null) {
- var tmp = function() {};
-
- tmp.prototype = _base.prototype;
-
- _class.prototype = new tmp();
- _class.prototype.constructor = _class;
- }
-
- if (_extends != null) {
- arr_each(_extends, function(x) {
-
- delete x.constructor;
- proto_extend(_class, x);
- });
- }
-
- var prototype = _class.prototype;
- obj_defaults(prototype, defaults);
-
- for (var key in _overrides) {
- prototype[key] = proto_override(prototype[key], _overrides[key]);
- }
- proto_extend(_class, original);
- }
-
-
- function proto_getProto(mix) {
-
- return is_Function(mix)
- ? mix.prototype
- : mix
- ;
- }
-
- }());
- // end:source /src/util/proto.js
- // source /src/util/json.js
- // Create from Complex Class Instance a lightweight json object
-
- var json_key_SER = '__$serialization',
- json_proto_toJSON,
- json_proto_arrayToJSON
- ;
-
- (function(){
-
- json_proto_toJSON = function(serialization){
-
- var object = this,
- json = {},
-
- key, val, s;
-
- if (serialization == null)
- serialization = object[json_key_SER];
-
-
- var asKey;
-
- for(key in object){
- asKey = key;
-
- if (serialization != null && serialization.hasOwnProperty(key)) {
- s = serialization[key];
- if (s != null && typeof s === 'object') {
-
- if (s.key)
- asKey = s.key;
-
- if (s.hasOwnProperty('serialize')) {
- if (s.serialize == null)
- continue;
-
- json[asKey] = s.serialize(object[key]);
- continue;
- }
-
- }
- }
-
- // _ (private)
- if (key.charCodeAt(0) === 95)
- continue;
-
- if ('Static' === key || 'Validate' === key)
- continue;
-
- val = object[key];
-
- if (val == null)
- continue;
-
- if ('_id' === key) {
- json[asKey] = val;
- continue;
- }
-
- switch (typeof val) {
- case 'function':
- continue;
- case 'object':
-
- if (is_Date(val))
- break;
-
- var toJSON = val.toJSON;
- if (toJSON == null)
- break;
-
- json[asKey] = val.toJSON();
- continue;
- }
-
- json[asKey] = val;
- }
-
- // make mongodb's _id property not private
- if (object._id != null)
- json._id = object._id;
-
- return json;
- };
-
- json_proto_arrayToJSON = function() {
- var array = this,
- imax = array.length,
- i = 0,
- output = new Array(imax),
-
- x;
-
- for (; i < imax; i++) {
-
- x = array[i];
-
- if (x != null && typeof x === 'object') {
-
- var toJSON = x.toJSON;
- if (toJSON === json_proto_toJSON || toJSON === json_proto_arrayToJSON) {
-
- output[i] = x.toJSON();
- continue;
- }
-
- if (toJSON == null) {
-
- output[i] = json_proto_toJSON.call(x);
- continue;
- }
- }
-
- output[i] = x;
- }
-
- return output;
- };
-
- }());
- // end:source /src/util/json.js
- // source /src/util/object.js
-
- var obj_inherit,
- obj_getProperty,
- obj_setProperty,
- obj_defaults,
- obj_extend,
- obj_extendDescriptors,
- obj_extendDescriptorsDefaults,
- obj_validate
- ;
-
- (function(){
-
- obj_inherit = function(target /* source, ..*/ ) {
- if (is_Function(target))
- target = target.prototype;
-
- var i = 1,
- imax = arguments.length,
- source, key;
- for (; i < imax; i++) {
-
- source = is_Function(arguments[i])
- ? arguments[i].prototype
- : arguments[i]
- ;
-
- for (key in source) {
-
- if ('Static' === key) {
- if (target.Static != null) {
-
- for (key in source.Static) {
- target.Static[key] = source.Static[key];
- }
-
- continue;
- }
- }
-
-
- target[key] = source[key];
-
- }
- }
- return target;
- };
-
- obj_getProperty = function(obj, property) {
- var chain = property.split('.'),
- imax = chain.length,
- i = -1;
- while ( ++i < imax ) {
- if (obj == null)
- return null;
-
- obj = obj[chain[i]];
- }
- return obj;
- };
-
- obj_setProperty = function(obj, property, value) {
- var chain = property.split('.'),
- imax = chain.length,
- i = -1,
- key;
-
- while ( ++i < imax - 1) {
- key = chain[i];
-
- if (obj[key] == null)
- obj[key] = {};
-
- obj = obj[key];
- }
-
- obj[chain[i]] = value;
- };
-
- obj_defaults = function(target, defaults) {
- for (var key in defaults) {
- if (target[key] == null)
- target[key] = defaults[key];
- }
- return target;
- };
-
- obj_extend = function(target, source) {
- if (target == null)
- target = {};
- if (source == null)
- return target;
-
- var val,
- key;
- for(key in source) {
- val = source[key];
- if (val != null)
- target[key] = val;
- }
- return target;
- };
-
- (function(){
- var getDescr = Object.getOwnPropertyDescriptor,
- define = Object.defineProperty;
-
- if (getDescr == null) {
- obj_extendDescriptors = obj_extend;
- obj_extendDescriptorsDefaults = obj_defaults;
- return;
- }
- obj_extendDescriptors = function(target, source){
- return _extendDescriptors(target, source, false);
- };
- obj_extendDescriptorsDefaults = function(target, source){
- return _extendDescriptors(target, source, true);
- };
- function _extendDescriptors (target, source, defaultsOnly) {
- if (target == null)
- return {};
- if (source == null)
- return source;
-
- var descr,
- key;
- for(key in source){
- if (defaultsOnly === true && target[key] != null)
- continue;
-
- descr = getDescr(source, key);
- if (descr == null) {
- obj_extendDescriptors(target, source['__proto__']);
- continue;
- }
- if (descr.value !== void 0) {
- target[key] = descr.value;
- continue;
- }
- define(target, key, descr);
- }
- return target;
- }
- }());
-
-
- (function(){
-
- obj_validate = function(a /*, b , ?isStrict, ?property, ... */) {
- if (a == null)
- return Err_Invalid('object');
-
- _props = null;
- _strict = false;
-
- var i = arguments.length,
- validator, x;
- while (--i > 0) {
- x = arguments[i];
- switch(typeof x){
- case 'string':
- if (_props == null)
- _props = {};
- _props[x] = 1;
- continue;
- case 'boolean':
- _strict = x;
- continue;
- case 'undefined':
- continue;
- default:
- if (i !== 1) {
- return Err_Invalid('validation argument at ' + i)
- }
- validator = x;
- continue;
- }
- }
- if (validator == null)
- validator = a.Validate;
- if (validator == null)
- // if no validation object - accept any.
- return null;
-
- return checkObject(a, validator, a);
- };
-
- // private
-
- // unexpect in `a` if not in `b`
- var _strict = false,
- // validate only specified properties
- _props = null;
-
- // a** - payload
- // b** - expect
- // strict -
- function checkObject(a, b, ctx) {
- var error,
- optional,
- key, aVal, aKey;
- for(key in b){
-
- if (_props != null && a === ctx && _props.hasOwnProperty(key) === false) {
- continue;
- }
-
- switch(key.charCodeAt(0)) {
- case 63:
- // ? (optional)
- aKey = key.substring(1);
- aVal = a[aKey];
- //! accept falsy value
- if (!aVal)
- continue;
-
- error = checkProperty(aVal, b[key], ctx);
- if (error != null) {
- error.setInvalidProperty(aKey);
- return error;
- }
-
- continue;
- case 45:
- // - (unexpect)
- aKey = key.substring(1);
- if (typeof a === 'object' && aKey in a)
- return Err_Unexpect(aKey);
-
- continue;
- }
-
- aVal = a[key];
- if (aVal == null)
- return Err_Expect(key);
-
-
- error = checkProperty(aVal, b[key], ctx);
- if (error != null) {
- error.setInvalidProperty(key);
- return error;
- }
- }
-
- if (_strict) {
- for(key in a){
- if (key in b || '?' + key in b)
- continue;
-
- return Err_Unexpect(key);
- }
- }
- }
-
- function checkProperty(aVal, bVal, ctx) {
- if (bVal == null)
- return null;
-
- if (typeof bVal === 'function') {
- var error = bVal.call(ctx, aVal);
- if (error == null || error === true)
- return null;
-
- if (error === false)
- return Err_Invalid();
-
- return Err_Custom(error);
- }
-
- if (aVal == null)
- return Err_Expect();
-
- if (typeof bVal === 'string') {
- var str = 'string',
- num = 'number',
- bool = 'boolean'
- ;
-
- switch(bVal) {
- case str:
- return typeof aVal !== str || aVal.length === 0
- ? Err_Type(str)
- : null;
- case num:
- return typeof aVal !== num
- ? Err_Type(num)
- : null;
- case bool:
- return typeof aVal !== bool
- ? Err_Type(bool)
- : null;
- }
- }
-
- if (bVal instanceof RegExp) {
- return bVal.test(aVal) === false
- ? Err_Invalid()
- : null;
- }
-
- if (Array.isArray(bVal)) {
- if (Array.isArray(aVal) === false)
- return Err_Type('array');
-
- var i = -1,
- imax = aVal.length,
- error;
- while ( ++i < imax ){
- error = checkObject(aVal[i], bVal[0])
-
- if (error) {
- error.setInvalidProperty(i);
- return error;
- }
- }
-
- return null;
- }
-
- if (typeof aVal !== typeof bVal)
- return Err_Type(typeof aVal);
-
-
- if (typeof aVal === 'object')
- return checkObject(aVal, bVal);
-
- return null;
- }
-
- var Err_Type,
- Err_Expect,
- Err_Unexpect,
- Err_Custom,
- Err_Invalid
- ;
- (function(){
-
- Err_Type = create('type',
- function TypeErr(expect) {
- this.expect = expect;
- },
- {
- toString: function(){
- return 'Invalid type.'
- + (this.expect
- ? ' Expect: ' + this.expect
- : '')
- + (this.property
- ? ' Property: ' + this.property
- : '')
- ;
- }
- }
- );
- Err_Expect = create('expect',
- function ExpectErr(property) {
- this.property = property;
- },
- {
- toString: function(){
- return 'Property expected.'
- + (this.property
- ? '`' + this.property + '`'
- : '')
- ;
- }
- }
- );
- Err_Unexpect = create('unexpect',
- function UnexpectErr(property) {
- this.property = property;
- },
- {
- toString: function(){
- return 'Unexpected property'
- + (this.property
- ? '`' + this.property + '`'
- : '')
- ;
- }
- }
- );
- Err_Custom = create('custom',
- function CustomErr(error) {
- this.error = error
- },
- {
- toString: function(){
- return 'Custom validation: '
- + this.error
- + (this.property
- ? ' Property: ' + this.property
- : '')
- ;
- }
- }
- );
- Err_Invalid = create('invalid',
- function InvalidErr(expect) {
- this.expect = expect
- }, {
- toString: function(){
- return 'Invalid.'
- + (this.expect
- ? ' Expect: ' + this.expect
- : '')
- + (this.property
- ? ' Property: ' + this.property
- : '')
- ;
- }
- }
- );
-
- function create(type, Ctor, proto) {
- proto.type = type;
- proto.property = null;
- proto.setInvalidProperty = setInvalidProperty;
-
- Ctor.prototype = proto;
- return function(mix){
- return new Ctor(mix);
- }
- }
- function setInvalidProperty(prop){
- if (this.property == null) {
- this.property = prop;
- return;
- }
- this.property = prop + '.' + this.property;
- }
- }()); /*< Errors */
-
- }());
- }());
- // end:source /src/util/object.js
- // source /src/util/patchObject.js
- var obj_patch,
- obj_patchValidate;
-
- (function(){
-
- obj_patch = function(obj, patch){
-
- for(var key in patch){
-
- var patcher = patches[key];
- if (patcher)
- patcher[fn_WALKER](obj, patch[key], patcher[fn_MODIFIER]);
- else
- console.error('Unknown or not implemented patcher', key);
- }
- return obj;
- };
-
- obj_patchValidate = function(patch){
- if (patch == null)
- return 'Undefined';
-
- var has = false;
- for(var key in patch){
- has = true;
-
- if (patches[key] == null)
- return 'Unsupported patcher: ' + key;
- }
- if (has === false)
- return 'No data';
-
- return null;
- };
-
- // === private
-
- function walk_mutator(obj, data, fn) {
- for (var key in data)
- fn(obj_getProperty(obj, key), data[key], key);
-
- }
-
- function walk_modifier(obj, data, fn){
- for(var key in data)
- obj_setProperty(
- obj,
- key,
- fn(obj_getProperty(obj, key), data[key], key)
- );
- }
-
- function fn_IoC(){
- var fns = arguments;
- return function(val, mix, prop){
- for (var i = 0, fn, imax = fns.length; i < imax; i++){
- fn = fns[i];
- if (fn(val, mix, prop) === false)
- return;
- }
- }
- }
-
- function arr_checkArray(val, mix, prop) {
- if (arr_isArray(val) === false) {
- // if DEBUG
- console.warn(' property is not an array', prop);
- // endif
- return false;
- }
- }
-
- function arr_push(val, mix, prop){
- if (mix.hasOwnProperty('$each')) {
- for (var i = 0, imax = mix.$each.length; i < imax; i++){
- val.push(mix.$each[i]);
- }
- return;
- }
- val.push(mix);
- }
-
- function arr_pop(val, mix, prop){
- val[mix > 0 ? 'pop' : 'shift']();
- }
- function arr_pull(val, mix, prop) {
- arr_remove(val, function(item){
- return query_match(item, mix);
- });
- }
-
- function val_inc(val, mix, key){
- return val + mix;
- }
- function val_set(val, mix, key){
- return mix;
- }
- function val_unset(){
- return void 0;
- }
-
- function val_bit(val, mix){
- if (mix.or)
- return val | mix.or;
-
- if (mix.and)
- return val & mix.and;
-
- return val;
- }
-
- var query_match;
- (function(){
- /** @TODO improve object matcher */
- query_match = function(obj, mix){
- for (var key in mix) {
- if (obj[key] !== mix[key])
- return false;
- }
- return true;
- };
- }());
-
-
- var fn_WALKER = 0,
- fn_MODIFIER = 1
- ;
-
- var patches = {
- '$push': [walk_mutator, fn_IoC(arr_checkArray, arr_push)],
- '$pop': [walk_mutator, fn_IoC(arr_checkArray, arr_pop)],
- '$pull': [walk_mutator, fn_IoC(arr_checkArray, arr_pull)],
-
- '$inc': [walk_modifier, val_inc],
- '$set': [walk_modifier, val_set],
- '$unset': [walk_modifier, val_unset],
- '$bit': [walk_modifier, val_unset],
- };
-
-
-
- }());
- // end:source /src/util/patchObject.js
- // source /src/util/function.js
- var fn_proxy,
- fn_apply,
- fn_createDelegate,
- fn_doNothing,
- fn_argsId
- ;
-
- (function(){
-
- fn_proxy = function(fn, ctx) {
- return function() {
- return fn_apply(fn, ctx, arguments);
- };
- };
-
- fn_apply = function(fn, ctx, _arguments){
- switch (_arguments.length) {
- case 0:
- return fn.call(ctx);
- case 1:
- return fn.call(ctx, _arguments[0]);
- case 2:
- return fn.call(ctx,
- _arguments[0],
- _arguments[1]);
- case 3:
- return fn.call(ctx,
- _arguments[0],
- _arguments[1],
- _arguments[2]);
- case 4:
- return fn.call(ctx,
- _arguments[0],
- _arguments[1],
- _arguments[2],
- _arguments[3]);
- case 5:
- return fn.call(ctx,
- _arguments[0],
- _arguments[1],
- _arguments[2],
- _arguments[3],
- _arguments[4]
- );
- }
- return fn.apply(ctx, _arguments);
- };
-
- fn_createDelegate = function(fn /* args */) {
- var args = _Array_slice.call(arguments, 1);
- return function(){
- if (arguments.length > 0)
- args = args.concat(_Array_slice.call(arguments));
-
- return fn_apply(fn, null, args);
- };
- };
-
- fn_doNothing = function(){};
-
- fn_argsId = function(args, cache){
- if (args.length === 0)
- return 0;
-
- var imax = cache.length,
- i = -1;
- while( ++i < imax ){
- if (args_match(cache[i], args))
- return i + 1;
- }
- cache.push(args);
- return cache.length;
- };
-
- // === private
-
- function args_match(a, b){
- if (a.length !== b.length)
- return false;
-
- var imax = a.length,
- i = 0;
- for (; i < imax; i++){
- if (a[i] !== b[i])
- return false;
- }
- return true;
- }
- }());
-
- // end:source /src/util/function.js
-
-
- // source /src/xhr/XHR.js
- var XHR = {};
-
- (function(){
-
- // source promise.js
- /*
- * Copyright 2012-2013 (c) Pierre Duquesne
- * Licensed under the New BSD License.
- * https://github.com/stackp/promisejs
- */
-
- (function(exports) {
-
- var ct_URL_ENCODED = 'application/x-www-form-urlencoded',
- ct_JSON = 'application/json';
-
- var e_NO_XHR = 1,
- e_TIMEOUT = 2,
- e_PRAPAIR_DATA = 3;
-
- function Promise() {
- this._callbacks = [];
- }
-
- Promise.prototype.then = function(func, context) {
- var p;
- if (this._isdone) {
- p = func.apply(context, this.result);
- } else {
- p = new Promise();
- this._callbacks.push(function () {
- var res = func.apply(context, arguments);
- if (res && typeof res.then === 'function')
- res.then(p.done, p);
- });
- }
- return p;
- };
-
- Promise.prototype.done = function() {
- this.result = arguments;
- this._isdone = true;
- for (var i = 0; i < this._callbacks.length; i++) {
- this._callbacks[i].apply(null, arguments);
- }
- this._callbacks = [];
- };
-
- function join(promises) {
- var p = new Promise();
- var results = [];
-
- if (!promises || !promises.length) {
- p.done(results);
- return p;
- }
-
- var numdone = 0;
- var total = promises.length;
-
- function notifier(i) {
- return function() {
- numdone += 1;
- results[i] = Array.prototype.slice.call(arguments);
- if (numdone === total) {
- p.done(results);
- }
- };
- }
-
- for (var i = 0; i < total; i++) {
- promises[i].then(notifier(i));
- }
-
- return p;
- }
-
- function chain(funcs, args) {
- var p = new Promise();
- if (funcs.length === 0) {
- p.done.apply(p, args);
- } else {
- funcs[0].apply(null, args).then(function() {
- funcs.splice(0, 1);
- chain(funcs, arguments).then(function() {
- p.done.apply(p, arguments);
- });
- });
- }
- return p;
- }
-
- /*
- * AJAX requests
- */
-
- function _encode(data) {
- var result = "";
- if (typeof data === "string") {
- result = data;
- } else {
- var e = encodeURIComponent;
- for (var k in data) {
- if (data.hasOwnProperty(k)) {
- result += '&' + e(k) + '=' + e(data[k]);
- }
- }
- }
- return result;
- }
-
- function new_xhr() {
- var xhr;
- if (window.XMLHttpRequest) {
- xhr = new XMLHttpRequest();
- } else if (window.ActiveXObject) {
- try {
- xhr = new ActiveXObject("Msxml2.XMLHTTP");
- } catch (e) {
- xhr = new ActiveXObject("Microsoft.XMLHTTP");
- }
- }
- return xhr;
- }
-
-
- function ajax(method, url, data, headers) {
- var p = new Promise(),
- contentType = headers && headers['Content-Type'] || promise.contentType;
-
- var xhr,
- payload;
-
-
- try {
- xhr = new_xhr();
- } catch (e) {
- p.done(e_NO_XHR, "");
- return p;
- }
- if (data) {
-
- if ('GET' === method) {
-
- url += '?' + _encode(data);
- data = null;
- } else {
-
-
- switch (contentType) {
- case ct_URL_ENCODED:
- data = _encode(data);
- break;
- case ct_JSON:
- try {
- data = JSON.stringify(data);
- } catch(error){
-
- p.done(e_PRAPAIR_DATA, '');
- return p;
- }
- break;
- default:
- // @TODO notify not supported content type
- // -> fallback to url encode
- data = _encode(data);
- break;
- }
- }
-
- }
-
- xhr.open(method, url);
-
- if (data)
- xhr.setRequestHeader('Content-Type', contentType);
-
- for (var h in headers) {
- if (headers.hasOwnProperty(h)) {
- xhr.setRequestHeader(h, headers[h]);
- }
- }
-
- function onTimeout() {
- xhr.abort();
- p.done(e_TIMEOUT, "", xhr);
- }
-
- var timeout = promise.ajaxTimeout;
- if (timeout) {
- var tid = setTimeout(onTimeout, timeout);
- }
-
- xhr.onreadystatechange = function() {
- if (timeout) {
- clearTimeout(tid);
- }
- if (xhr.readyState === 4) {
- var err = (!xhr.status ||
- (xhr.status < 200 || xhr.status >= 300) &&
- xhr.status !== 304);
- p.done(err, xhr.responseText, xhr);
- }
- };
-
- xhr.send(data);
- return p;
- }
-
- function _ajaxer(method) {
- return function(url, data, headers) {
- return ajax(method, url, data, headers);
- };
- }
-
- var promise = {
- Promise: Promise,
- join: join,
- chain: chain,
- ajax: ajax,
- get: _ajaxer('GET'),
- post: _ajaxer('POST'),
- put: _ajaxer('PUT'),
- del: _ajaxer('DELETE'),
- patch: _ajaxer('PATCH'),
-
- /* Error codes */
- ENOXHR: e_NO_XHR,
- ETIMEOUT: e_TIMEOUT,
- E_PREPAIR_DATA: e_PRAPAIR_DATA,
- /**
- * Configuration parameter: time in milliseconds after which a
- * pending AJAX request is considered unresponsive and is
- * aborted. Useful to deal with bad connectivity (e.g. on a
- * mobile network). A 0 value disables AJAX timeouts.
- *
- * Aborted requests resolve the promise with a ETIMEOUT error
- * code.
- */
- ajaxTimeout: 0,
-
-
- contentType: ct_JSON
- };
-
- if (typeof define === 'function' && define.amd) {
- /* AMD support */
- define(function() {
- return promise;
- });
- } else {
- exports.promise = promise;
- }
-
- })(this);
-
- // end:source promise.js
-
- }.call(XHR));
-
- arr_each(['get'], function(key){
- XHR[key] = function(path, sender){
-
- this
- .promise[key](path)
- .then(function(errored, response, xhr){
-
- if (errored) {
- sender.onError(errored, response, xhr);
- return;
- }
-
- sender.onSuccess(response);
- });
-
- };
- });
-
- arr_each(['del', 'post', 'put', 'patch'], function(key){
- XHR[key] = function(path, data, cb){
- this
- .promise[key](path, data)
- .then(function(error, response, xhr){
- cb(error, response, xhr);
- });
- };
- });
-
-
- // end:source /src/xhr/XHR.js
-
- // source /src/business/Serializable.js
- var Serializable;
-
- (function(){
-
- Serializable = function($serialization) {
-
- if (this === Class || this == null || this === global) {
-
- var Ctor = function(data){
- this[json_key_SER] = obj_extend(this[json_key_SER], $serialization);
-
- Serializable.call(this, data);
- };
-
- return Ctor;
- }
-
- if ($serialization != null) {
-
- if (this.deserialize)
- this.deserialize($serialization);
- else
- Serializable.deserialize(this, $serialization);
-
- }
-
- }
-
- Serializable.serialize = function(instance) {
-
- if (is_Function(instance.toJSON))
- return instance.toJSON();
-
-
- return json_proto_toJSON.call(instance, instance[json_key_SER]);
- };
-
- Serializable.deserialize = function(instance, json) {
-
- if (is_String(json)) {
- try {
- json = JSON.parse(json);
- }catch(error){
- console.error('', json);
- return instance;
- }
- }
-
- if (is_Array(json) && is_Function(instance.push)) {
- instance.length = 0;
- for (var i = 0, imax = json.length; i < imax; i++){
- instance.push(json[i]);
- }
- return instance;
- }
-
- var props = instance[json_key_SER],
- asKeys, asKey,
- key,
- val,
- Mix;
-
-
- if (props != null) {
- var pname = '__desAsKeys';
-
- asKeys = props[pname];
- if (asKeys == null) {
- asKeys = props[pname] = {};
- for (key in props) {
- if (key !== '__desAsKeys' && props[key].hasOwnProperty('key') === true)
- asKeys[props[key].key] = key;
- }
- }
- }
-
- for (key in json) {
-
- val = json[key];
- asKey = key;
-
- if (props != null) {
- Mix = props.hasOwnProperty(key)
- ? props[key]
- : null
- ;
- if (asKeys[key]) {
- asKey = asKeys[key];
- }
-
- if (Mix != null) {
- if (is_Object(Mix))
- Mix = Mix.deserialize;
-
- if (is_String(Mix))
- Mix = class_get(Mix);
-
- if (is_Function(Mix)) {
- instance[asKey] = val instanceof Mix
- ? val
- : new Mix(val)
- ;
- continue;
- }
- }
- }
-
- instance[asKey] = val;
- }
-
- return instance;
- }
-
- }());
-
- // end:source /src/business/Serializable.js
- // source /src/business/Route.js
- /**
- * var route = new Route('/user/:id');
- *
- * route.create({id:5}) // -> '/user/5'
- */
- var Route = (function(){
-
-
- function Route(route){
- this.route = route_parse(route);
- }
-
- Route.prototype = {
- constructor: Route,
- create: function(object){
- var path, query;
-
- path = route_interpolate(this.route.path, object, '/');
- if (path == null) {
- return null;
- }
-
- if (this.route.query) {
- query = route_interpolate(this.route.query, object, '&');
- if (query == null) {
- return null;
- }
- }
-
- return path + (query ? '?' + query : '');
- },
-
- hasAliases: function(object){
-
- var i = 0,
- imax = this.route.path.length,
- alias
- ;
- for (; i < imax; i++){
- alias = this.route.path[i].parts[1];
-
- if (alias && object[alias] == null) {
- return false;
- }
- }
-
- return true;
- }
- };
-
- var regexp_pathByColon = /^([^:\?]*)(\??):(\??)([\w]+)$/,
- regexp_pathByBraces = /^([^\{\?]*)(\{(\??)([\w]+)\})?([^\s]*)?$/;
-
- function parse_single(string) {
- var match = regexp_pathByColon.exec(string);
-
- if (match) {
- return {
- optional: (match[2] || match[3]) === '?',
- parts: [match[1], match[4]]
- };
- }
-
- match = regexp_pathByBraces.exec(string);
-
- if (match) {
- return {
- optional: match[3] === '?',
- parts: [match[1], match[4], match[5]]
- };
- }
-
- console.error('Paths breadcrumbs should be matched by regexps');
- return { parts: [string] };
- }
-
- function parse_path(path, delimiter) {
- var parts = path.split(delimiter);
-
- for (var i = 0, imax = parts.length; i < imax; i++){
- parts[i] = parse_single(parts[i]);
- }
-
- return parts;
- }
-
- function route_parse(route) {
- var question = /[^\:\{]\?[^:]/.exec(route),
- query = null;
-
- if (question){
- question = question.index + 1;
- query = route.substring(question + 1);
- route = route.substring(0, question);
- }
-
-
- return {
- path: parse_path(route, '/'),
- query: query == null ? null : parse_path(query, '&')
- };
- }
-
- /** - route - [] */
- function route_interpolate(breadcrumbs, object, delimiter) {
- var route = [],
- key,
- parts;
-
-
- for (var i = 0, x, imax = breadcrumbs.length; i < imax; i++){
- x = breadcrumbs[i];
- parts = x.parts.slice(0);
-
- if (parts[1] == null) {
- // is not an interpolated breadcrumb
- route.push(parts[0]);
- continue;
- }
-
- key = parts[1];
- parts[1] = object[key];
-
- if (parts[1] == null){
-
- if (!x.optional) {
- console.error('Object has no value, for not optional part - ', key);
- return null;
- }
-
- continue;
- }
-
- route.push(parts.join(''));
- }
-
- return route.join(delimiter);
- }
-
-
- return Route;
- }());
- // end:source /src/business/Route.js
- // source /src/business/Deferred.js
- var Deferred;
-
- (function(){
- Deferred = function(){};
- Deferred.prototype = {
- _isAsync: true,
-
- _done: null,
- _fail: null,
- _always: null,
- _resolved: null,
- _rejected: null,
-
- defer: function(){
- this._rejected = null;
- this._resolved = null;
- },
-
- isResolved: function(){
- return this._resolved != null;
- },
- isRejected: function(){
- return this._rejected != null;
- },
- isBusy: function(){
- return this._resolved == null && this._rejected == null;
- },
-
- resolve: function() {
- var done = this._done,
- always = this._always
- ;
-
- this._resolved = arguments;
-
- dfr_clearListeners(this);
- arr_callOnce(done, this, arguments);
- arr_callOnce(always, this, [ this ]);
-
- return this;
- },
-
- reject: function() {
- var fail = this._fail,
- always = this._always
- ;
-
- this._rejected = arguments;
-
- dfr_clearListeners(this);
- arr_callOnce(fail, this, arguments);
- arr_callOnce(always, this, [ this ]);
-
- return this;
- },
-
- resolveDelegate: function(){
- return fn_proxy(this.resolve, this);
- },
-
- rejectDelegate: function(){
- return fn_proxy(this.reject, this);
- },
-
- then: function(filterSuccess, filterError){
- return this.pipe(filterSuccess, filterError);
- },
-
- done: function(callback) {
- if (this._rejected != null)
- return this;
- return dfr_bind(
- this,
- this._resolved,
- this._done || (this._done = []),
- callback
- );
- },
-
- fail: function(callback) {
- if (this._resolved != null)
- return this;
- return dfr_bind(
- this,
- this._rejected,
- this._fail || (this._fail = []),
- callback
- );
- },
-
- always: function(callback) {
- return dfr_bind(
- this,
- this._rejected || this._resolved,
- this._always || (this._always = []),
- callback
- );
- },
-
- pipe: function(mix /* ..methods */){
- var dfr;
- if (typeof mix === 'function') {
- dfr = new Deferred;
- var done_ = mix,
- fail_ = arguments.length > 1
- ? arguments[1]
- : null;
-
- this
- .done(delegate(dfr, 'resolve', done_))
- .fail(delegate(dfr, 'reject', fail_))
- ;
- return dfr;
- }
-
- dfr = mix;
- var imax = arguments.length,
- done = imax === 1,
- fail = imax === 1,
- i = 0, x;
- while( ++i < imax ){
- x = arguments[i];
- switch(x){
- case 'done':
- done = true;
- break;
- case 'fail':
- fail = true;
- break;
- default:
- console.error('Unsupported pipe channel', arguments[i])
- break;
- }
- }
- done && this.done(dfr.resolveDelegate());
- fail && this.fail(dfr.rejectDelegate());
-
- function pipe(dfr, method) {
- return function(){
- dfr[method].apply(dfr, arguments);
- };
- }
- function delegate(dfr, name, fn) {
-
- return function(){
- if (fn != null) {
- var override = fn.apply(this, arguments);
- if (override != null) {
- if (isDeferred(override) === true) {
- override.pipe(dfr);
- return;
- }
-
- dfr[name](override)
- return;
- }
- }
- dfr[name].apply(dfr, arguments);
- };
- }
-
- return this;
- },
- pipeCallback: function(){
- var self = this;
- return function(error){
- if (error != null) {
- self.reject(error);
- return;
- }
- var args = _Array_slice.call(arguments, 1);
- fn_apply(self.resolve, self, args);
- };
- }
- };
-
- Deferred.run = function(fn, ctx){
- var dfr = new Deferred();
- if (ctx == null)
- ctx = dfr;
-
- fn.call(ctx, dfr.resolveDelegate(), dfr.rejectDelegate(), dfr);
- return dfr;
- };
- /**
- * Create function wich gets deferred object with first argument.
- * Created function returns always that deferred object
- */
- Deferred.create = function(fn){
- return function(){
- var args = _Array_slice.call(arguments),
- dfr = new Deferred;
- args.unshift(dfr);
-
- fn_apply(fn, this, args);
- return dfr;
- };
- };
- /**
- * Similar as `create` it will also cache the deferred object,
- * sothat the target function is called once pro specific arguments
- *
- * var fn = Deferred.memoize((dfr, name) => dfr.resolve(name));
- * fn('foo');
- * fn('baz');
- * fn('foo');
- * - is called only once for `foo`, and once for `baz`
- */
- Deferred.memoize = function(fn){
- var dfrs = {}, args_store = [];
- return function(){
- var args = _Array_slice.call(arguments),
- id = fn_argsId(args_store, args);
- if (dfrs[id] != null)
- return dfrs[id];
-
- var dfr = dfrs[id] = new Deferred;
- args.unshift(dfr);
-
- fn_apply(fn, this, args);
- return dfr;
- };
- };
-
- // PRIVATE
-
- function dfr_bind(dfr, arguments_, listeners, callback){
- if (callback == null)
- return dfr;
-
- if ( arguments_ != null)
- fn_apply(callback, dfr, arguments_);
- else
- listeners.push(callback);
-
- return dfr;
- }
-
- function dfr_clearListeners(dfr) {
- dfr._done = null;
- dfr._fail = null;
- dfr._always = null;
- }
-
- function arr_callOnce(arr, ctx, args) {
- if (arr == null)
- return;
-
- var imax = arr.length,
- i = -1,
- fn;
- while ( ++i < imax ) {
- fn = arr[i];
-
- if (fn)
- fn_apply(fn, ctx, args);
- }
- arr.length = 0;
- }
- function isDeferred(x){
- if (x == null || typeof x !== 'object')
- return false;
-
- if (x instanceof Deferred)
- return true;
-
- return typeof x.done === 'function'
- && typeof x.fail === 'function'
- ;
- }
-
- }());
- // end:source /src/business/Deferred.js
- // source /src/business/EventEmitter.js
- var EventEmitter;
- (function(){
-
- EventEmitter = function() {
- this._listeners = {};
- };
- EventEmitter.prototype = {
- constructor: EventEmitter,
- on: function(event, callback) {
- if (callback != null){
- (this._listeners[event] || (this._listeners[event] = [])).push(callback);
- }
-
- return this;
- },
- once: function(event, callback){
- if (callback != null) {
- callback._once = true;
- (this._listeners[event] || (this._listeners[event] = [])).push(callback);
- }
-
- return this;
- },
-
- pipe: function(event){
- var that = this,
- args;
- return function(){
- args = _Array_slice.call(arguments);
- args.unshift(event);
-
- fn_apply(that.trigger, that, args);
- };
- },
-
- emit: event_trigger,
- trigger: event_trigger,
-
- off: function(event, callback) {
- var listeners = this._listeners[event];
- if (listeners == null)
- return this;
-
- if (arguments.length === 1) {
- listeners.length = 0;
- return this;
- }
-
- var imax = listeners.length,
- i = -1;
- while (++i < imax) {
-
- if (listeners[i] === callback) {
- listeners.splice(i, 1);
- i--;
- imax--;
- }
-
- }
- return this;
- }
- };
-
- function event_trigger() {
- var args = _Array_slice.call(arguments),
- event = args.shift(),
- fns = this._listeners[event],
- fn, imax, i = 0;
-
- if (fns == null)
- return this;
-
- for (imax = fns.length; i < imax; i++) {
- fn = fns[i];
- fn_apply(fn, this, args);
-
- if (fn._once === true){
- fns.splice(i, 1);
- i--;
- imax--;
- }
- }
-
- return this;
- }
- }());
-
- // end:source /src/business/EventEmitter.js
-
-
-
-
- // source /src/Class.js
- var Class = function(mix) {
-
- var namespace,
- data;
-
- if (is_String(mix)) {
- namespace = mix;
-
- if (arguments.length === 1)
- return class_get(mix);
-
-
- data = arguments[1];
- data[str_CLASS_IDENTITY] = namespace;
- } else {
- data = mix;
- }
-
-
- var _base = data.Base,
- _extends = data.Extends,
- _static = data.Static,
- _construct = data.Construct,
- _class = null,
- _store = data.Store,
- _self = data.Self,
- _overrides = data.Override,
-
- key;
-
- if (_base != null)
- delete data.Base;
-
- if (_extends != null)
- delete data.Extends;
-
- if (_static != null)
- delete data.Static;
-
- if (_self != null)
- delete data.Self;
-
- if (_construct != null)
- delete data.Construct;
-
-
- if (_store != null) {
-
- if (_extends == null) {
- _extends = _store;
- } else if (is_Array(_extends)) {
- _extends.unshift(_store)
- } else {
- _extends = [_store, _extends];
- }
-
- delete data.Store;
- }
-
- if (_overrides != null)
- delete data.Override;
-
- if (_base == null && _extends == null && _self == null) {
-
- if (data.toJSON === void 0)
- data.toJSON = json_proto_toJSON;
-
- _class = _construct == null
- ? function() {}
- : _construct
- ;
-
- data.constructor = _class.prototype.constructor;
-
- if (_static != null) {
- obj_extendDescriptors(_class, _static);
- }
-
- _class.prototype = data;
-
- if (namespace != null)
- class_register(namespace, _class);
-
- return _class;
- }
-
- _class = function() {
-
- //// consider to remove
- ////if (this instanceof _class === false)
- //// return new (_class.bind.apply(_class, [null].concat(_Array_slice.call(arguments))));
-
-
- if (_extends != null) {
- var isarray = _extends instanceof Array,
-
- imax = isarray ? _extends.length : 1,
- i = 0,
- x = null;
- for (; i < imax; i++) {
- x = isarray
- ? _extends[i]
- : _extends
- ;
- if (typeof x === 'function') {
- fn_apply(x, this, arguments);
- }
- }
- }
-
- if (_base != null) {
- fn_apply(_base, this, arguments);
- }
-
- if (_self != null && is_NullOrGlobal(this) === false) {
-
- for (var key in _self) {
- this[key] = fn_proxy(_self[key], this);
- }
- }
-
- if (_construct != null) {
- var r = fn_apply(_construct, this, arguments);
- if (r != null) {
- return r;
- }
- }
-
- this['super'] = null;
-
- return this;
- };
-
- if (namespace != null)
- class_register(namespace, _class);
-
- if (_static != null) {
- obj_extendDescriptors(_class, _static);
- }
-
- if (_base != null)
- class_inheritStatics(_class, _base);
-
- if (_extends != null)
- class_inheritStatics(_class, _extends);
-
- class_extendProtoObjects(data, _base, _extends);
-
- class_inherit(_class, _base, _extends, data, _overrides, {
- toJSON: json_proto_toJSON
- });
-
- data = null;
- _static = null;
- return _class;
- };
- // end:source /src/Class.js
-
- // source /src/business/Await.js
- var Await;
-
- (function(){
-
- Await = Class({
- Extends: Deferred.prototype,
-
- _wait: 0,
- _timeout: null,
- _result: null,
- _resolved: [],
-
- Construct: function(/* promises */){
- var imax = arguments.length,
- i = -1,
- dfr
- ;
- while ( ++i < imax ){
- dfr = arguments[i];
- if (dfr != null && typeof dfr.done === 'function')
- await_deferredDelegate(this, null, dfr);
- }
- },
-
- delegate: function(name, errorable) {
- return await_createDelegate(this, name, errorable);
- },
-
- deferred: function(name) {
-
- return await_deferredDelegate(
- this,
- name,
- new Deferred);
- },
-
- Static: {
-
- TIMEOUT: 2000
- }
- });
-
- function await_deferredDelegate(await, name, dfr){
- var delegate = await_createDelegate(await, name, true),
- args
- ;
- return dfr
- .done(function(){
- args = _Array_slice.call(arguments);
- args.unshift(null);
-
- delegate.apply(null, args);
- })
- .fail(function(error){
-
- delegate(error);
- })
- ;
- }
-
- function await_createDelegate(await, name, errorable){
- if (errorable == null)
- errorable = true;
-
- if (await._timeout)
- clearTimeout(await._timeout);
-
- await.defer();
- await._wait++;
-
- if (name){
- if (!await._result)
- await._result = {};
-
- if (name in await._result)
- console.warn('', name, 'already awaiting');
-
- await._result[name] = null;
- }
-
- var delegate = fn_createDelegate(await_listener, await, name, errorable)
- ;
-
- await._timeout = setTimeout(delegate, Await.TIMEOUT);
-
- return delegate;
- }
-
- function await_listener(await, name, errorable /* .. args */ ) {
-
- if (arguments.length === 0) {
- // timeout
- await._wait = 0;
- await.reject('408: Timeout');
- return;
- }
-
- if (await._wait === 0)
- return;
-
- var result = await._result;
-
- if (name) {
- var args = _Array_slice.call(arguments, 3);
-
- result[name] = {
- error: errorable ? args.shift() : null,
- arguments: args
- };
- } else if (errorable && arguments[3] != null) {
-
- if (result == null)
- result = await._result = {};
-
- result.__error = arguments[3];
- }
-
- if (--await._wait === 0) {
- clearTimeout(await._timeout);
-
- var error = result && result.__error
- ;
- var val,
- key;
-
- if (error == null) {
- for(key in result){
-
- val = result[key];
- error = val && val.error;
-
- if (error)
- break;
- }
- }
-
- if (error) {
- await.reject(error, result);
- return;
- }
-
- await.resolve(result);
- }
- }
-
- }());
- // end:source /src/business/Await.js
-
- // source /src/store/Store.js
- var StoreProto = {
-
-
- // Abstract
-
- fetch: null,
- save: null,
- del: null,
- onSuccess: null,
- onError: null,
-
- Static: {
- fetch: function(data){
- return new this().fetch(data);
- }
- }
- };
- // end:source /src/store/Store.js
- // source /src/store/events.js
- var storageEvents_onBefore,
- storageEvents_onAfter,
- storageEvents_remove,
- storageEvents_overridenDefer
- ;
-
- (function(){
-
-
- var event_START = 'start',
- event_SUCCESS = 'fulfilled',
- event_FAIL = 'rejected';
-
- var events_ = new EventEmitter,
- hasBeforeListeners_,
- hasAfterListeners_
- ;
-
- storageEvents_onBefore = function(callback){
- events_.on(event_START, callback);
- hasBeforeListeners_ = true;
- };
-
- storageEvents_onAfter = function(onSuccess, onFailure){
- events_
- .on(event_SUCCESS, onSuccess)
- .on(event_FAIL, onFailure)
- ;
- hasAfterListeners_ = true;
- };
-
- storageEvents_remove = function(callback){
- events_
- .off(event_SUCCESS, callback)
- .off(event_FAIL, callback)
- .off(event_START, callback)
- ;
- };
-
- storageEvents_overridenDefer = function(type){
-
- Deferred.prototype.defer.call(this);
-
- if (hasBeforeListeners_)
- emit([event_START, this, type]);
-
- if (hasAfterListeners_)
- this.always(listenerDelegate(this, type));
-
- return this;
- };
-
- // PRIVATE
-
- function listenerDelegate(sender, type) {
- return function(){
- var isSuccess = sender._rejected == null,
- arguments_ = isSuccess
- ? sender._resolved
- : sender._rejected
- ,
- event = isSuccess
- ? event_SUCCESS
- : event_FAIL
- ;
- emit([event, sender, type].concat(arguments_));
- };
- }
-
-
- function emit(arguments_/* [ event, sender, .. ]*/){
- events_.trigger.apply(events_, arguments_);
- }
-
-
- }());
- // end:source /src/store/events.js
- // source /src/store/Remote.js
- Class.Remote = (function(){
-
- var str_CONTENT_TYPE = 'content-type',
- str_JSON = 'json'
- ;
-
- var XHRRemote = function(route){
- this._route = new Route(route);
- };
-
- obj_inherit(XHRRemote, StoreProto, Serializable, Deferred, {
-
- defer: storageEvents_overridenDefer,
-
- serialize: function(){
-
- return is_Array(this)
- ? json_proto_arrayToJSON.call(this)
- : json_proto_toJSON.call(this)
- ;
- },
-
- deserialize: function(json){
- return Serializable.deserialize(this, json);
- },
-
- fetch: function(data){
- this.defer('fetch');
-
- XHR.get(this._route.create(data || this), this);
- return this;
- },
-
- save: function(callback){
- this.defer('save');
-
- var json = this.serialize(),
- path = this._route.create(this),
- method = this._route.hasAliases(this)
- ? 'put'
- : 'post'
- ;
-
- XHR[method](path, json, resolveDelegate(this, callback, 'save'));
- return this;
- },
-
- patch: function(json){
- this.defer('patch');
-
- obj_patch(this, json);
-
- XHR.patch(
- this._route.create(this),
- json,
- resolveDelegate(this)
- );
- return this;
- },
-
- del: function(callback){
- this.defer('del');
-
- var json = this.serialize(),
- path = this._route.create(this)
- ;
-
- XHR.del(path, json, resolveDelegate(this, callback));
- return this;
- },
-
- onSuccess: function(response){
- parseFetched(this, response);
- },
- onError: function(errored, response, xhr){
- reject(this, response, xhr);
- }
-
-
- });
-
- function parseFetched(self, response){
- var json;
-
- try {
- json = JSON.parse(response);
- } catch(error) {
-
- reject(self, error);
- return;
- }
-
-
- self.deserialize(json);
- self.resolve(self);
- }
-
- function reject(self, response, xhr){
- var obj;
- if (typeof response === 'string' && is_JsonResponse(xhr)) {
- try {
- obj = JSON.parse(response);
- } catch (error) {
- obj = error;
- }
- }
-
- self.reject(obj || response);
- }
-
- function is_JsonResponse(xhr){
- var header = xhr.getResponseHeader(str_CONTENT_TYPE);
-
- return header != null
- && header.toLowerCase().indexOf(str_JSON) !== -1;
- }
-
- function resolveDelegate(self, callback, action){
-
- return function(error, response, xhr){
-
- if (is_JsonResponse(xhr)) {
- try {
- response = JSON.parse(response);
- } catch(error){
- console.error(' invalid json response', response);
-
- return reject(self, error, xhr);
- }
- }
-
- // @obsolete -> use deferred
- if (callback)
- callback(error, response);
-
- if (error)
- return reject(self, response, xhr);
-
- if ('save' === action && is_Object(response)) {
-
- if (is_Array(self)) {
-
- var imax = self.length,
- jmax = response.length,
- i = -1
- ;
-
- while ( ++i < imax && i < jmax){
-
- Serializable.deserialize(self[i], response[i]);
- }
-
- } else {
- self.deserialize(response);
- }
-
- return self.resolve(self);
- }
-
- self.resolve(response);
- };
- }
-
- function Remote(route){
- return new XHRRemote(route);
- }
-
- Remote.onBefore = storageEvents_onBefore;
- Remote.onAfter = storageEvents_onAfter;
-
- arr_each(['get', 'post', 'put', 'delete'], function(method){
-
- Remote[method] = function(url, obj){
-
- var json = obj;
- if (obj.serialize != null)
- json = obj.serialize();
-
- if (json == null && obj.toJSON)
- json = obj.toJSON();
-
- var dfr = new Deferred();
- XHR[method](url, json, resolveDelegate(dfr));
-
- return dfr;
- };
- });
-
- return Remote;
- }());
- // end:source /src/store/Remote.js
- // source /src/store/LocalStore.js
- Class.LocalStore = (function(){
-
- var LocalStore = function(route){
- this._route = new Route(route);
- };
-
- obj_inherit(LocalStore, StoreProto, Serializable, Deferred, {
-
- serialize: function(){
-
- var json = is_Array(this)
- ? json_proto_arrayToJSON.call(this)
- : json_proto_toJSON.call(this)
- ;
-
- return JSON.stringify(json);
- },
- deserialize: function(json){
- return Serializable.deserialize(this, json);
- },
- fetch: function(data){
-
- var path = this._route.create(data || this),
- object = localStorage.getItem(path);
-
- if (object == null) {
- return this.resolve(this);
- }
-
- if (is_String(object)){
- try {
- object = JSON.parse(object);
- } catch(e) {
- return this.reject(e);
- }
- }
-
- this.deserialize(object);
- return this.resolve(this);
- },
-
- save: function(callback){
- var path = this._route.create(this),
- store = this.serialize();
-
- localStorage.setItem(path, store);
- callback && callback();
- return this.resolve(this);
- },
-
- del: function(mix){
-
- if (mix == null && arguments.length !== 0) {
- return this.reject(' - selector is specified, but is undefined');
- }
-
- // Single
- if (arr_isArray(this) === false) {
- store_del(this._route, mix || this);
- return this.resolve();
- }
-
- // Collection
- if (mix == null) {
-
- for (var i = 0, imax = this.length; i < imax; i++){
- this[i] = null;
- }
- this.length = 0;
-
- store_del(this._route, this);
- return this.resolve();
- }
-
- var array = this.remove(mix);
- if (array.length === 0) {
- // was nothing removed
- return this.resolve();
- }
-
- return this.save();
- },
-
- onError: function(error){
- this.reject({
- error: error
- });
- }
-
-
- });
-
- function store_del(route, data){
- var path = route.create(data);
-
- localStorage.removeItem(path);
- }
-
- var Constructor = function(route){
-
- return new LocalStore(route);
- };
-
- Constructor.prototype = LocalStore.prototype;
-
-
- return Constructor;
-
- }());
- // end:source /src/store/LocalStore.js
-
-
- // source /src/Class.Static.js
- /**
- * Can be used in Constructor for binding class's functions to class's context
- * for using, for example, as callbacks
- *
- * @obsolete - use 'Self' property instead
- */
- Class.bind = function(cntx) {
- var arr = arguments,
- i = 1,
- length = arguments.length,
- key;
-
- for (; i < length; i++) {
- key = arr[i];
- cntx[key] = cntx[key].bind(cntx);
- }
- return cntx;
- };
-
- Class.cfg = function(mix, value){
-
- if (is_String(mix)) {
-
- if (arguments.length === 1)
- return _cfg[mix];
-
- _cfg[mix] = value;
- return;
- }
-
- if (is_Object(mix)) {
-
- for(var key in mix){
-
- Class.cfg(key, mix[key]);
- }
- }
- };
-
-
-
- Class.Model = {};
- Class.Serializable = Serializable;
- Class.Deferred = Deferred;
- Class.EventEmitter = EventEmitter;
- Class.Await = Await;
- Class.validate = obj_validate;
-
- Class.stringify = class_stringify;
- Class.parse = class_parse;
- Class.patch = class_patch;
- Class.properties = class_properties;
- // end:source /src/Class.Static.js
-
- // source /src/collection/Collection.js
- Class.Collection = (function(){
-
- // source ArrayProto.js
-
- var ArrayProto = (function(){
-
- function check(x, mix) {
- if (mix == null)
- return false;
-
- if (typeof mix === 'function')
- return mix(x);
-
- if (typeof mix === 'object'){
-
- if (x.constructor === mix.constructor && x.constructor !== Object) {
- return x === mix;
- }
-
- var value, matcher;
- for (var key in mix) {
-
- value = x[key];
- matcher = mix[key];
-
- if (typeof matcher === 'string') {
- var c = matcher[0],
- index = 1;
-
- if ('<' === c || '>' === c){
-
- if ('=' === matcher[1]){
- c +='=';
- index++;
- }
-
- matcher = matcher.substring(index);
-
- switch (c) {
- case '<':
- if (value >= matcher)
- return false;
- continue;
- case '<=':
- if (value > matcher)
- return false;
- continue;
- case '>':
- if (value <= matcher)
- return false;
- continue;
- case '>=':
- if (value < matcher)
- return false;
- continue;
- }
- }
- }
-
- /*jshint eqeqeq: false*/
- if (value != matcher) {
- return false;
- }
- /*jshint eqeqeq: true*/
-
- }
- return true;
- }
-
- console.warn('No valid matcher', mix);
- return false;
- }
-
- var ArrayProto = {
- length: 0,
- push: function(/*mix*/) {
- var imax = arguments.length,
- i = -1;
- while ( ++i < imax ) {
-
- this[this.length++] = create(this._ctor, arguments[i]);
- }
-
- return this;
- },
- pop: function() {
- var instance = this[--this.length];
-
- this[this.length] = null;
- return instance;
- },
- shift: function(){
- if (this.length === 0)
- return null;
-
-
- var first = this[0],
- imax = this.length - 1,
- i = 0;
-
- for (; i < imax; i++){
- this[i] = this[i + 1];
- }
-
- this[imax] = null;
- this.length--;
-
- return first;
- },
- unshift: function(mix){
- this.length++;
-
- var imax = this.length;
-
- while (--imax) {
- this[imax] = this[imax - 1];
- }
-
- this[0] = create(this._ctor, mix);
- return this;
- },
-
- splice: function(index, count /* args */){
-
- var length = this.length;
- var i, imax, y;
-
- // clear range after length until index
- if (index >= length) {
- count = 0;
- for (i = length, imax = index; i < imax; i++){
- this[i] = void 0;
- }
- }
-
- var rm_count = count,
- rm_start = index,
- rm_end = index + rm_count,
- add_count = arguments.length - 2,
-
- new_length = length + add_count - rm_count;
-
-
- // move block
-
- var block_start = rm_end,
- block_end = length,
- block_shift = new_length - length;
-
- if (0 < block_shift) {
- // move forward
-
- i = block_end;
- while (--i >= block_start) {
-
- this[i + block_shift] = this[i];
-
- }
-
- }
-
- if (0 > block_shift) {
- // move backwards
-
- i = block_start;
- while (i < block_end) {
- this[i + block_shift] = this[i];
- i++;
- }
- }
-
- // insert
-
- i = rm_start;
- y = 2;
- for (; y < arguments.length; y) {
- this[i++] = create(this._ctor, arguments[y++]);
- }
-
-
- this.length = new_length;
- return this;
- },
-
- slice: function(){
- return fn_apply(_Array_slice, this, arguments);
- },
-
- sort: function(fn){
- _Array_sort.call(this, fn);
- return this;
- },
-
- reverse: function(){
- var array = _Array_slice.call(this),
- imax = this.length,
- i = -1
- ;
- while( ++i < imax) {
- this[i] = array[imax - i - 1];
- }
- return this;
- },
-
- toString: function(){
- return _Array_slice.call(this, 0).toString()
- },
-
- each: forEach,
- forEach: forEach,
-
-
- where: function(mix){
-
- var collection = new this.constructor();
-
- for (var i = 0, x, imax = this.length; i < imax; i++){
- x = this[i];
-
- if (check(x, mix)) {
- collection[collection.length++] = x;
- }
- }
-
- return collection;
- },
- remove: function(mix){
- var index = -1,
- array = [];
- for (var i = 0, imax = this.length; i < imax; i++){
-
- if (check(this[i], mix)) {
- array.push(this[i]);
- continue;
- }
-
- this[++index] = this[i];
- }
- for (i = ++index; i < imax; i++) {
- this[i] = null;
- }
-
- this.length = index;
- return array;
- },
- first: function(mix){
- if (mix == null)
- return this[0];
-
- var i = this.indexOf(mix);
- return i !== -1
- ? this[i]
- : null;
-
- },
- last: function(mix){
- if (mix == null)
- return this[this.length - 1];
-
- var i = this.lastIndexOf(mix);
- return i !== -1
- ? this[i]
- : null;
- },
- indexOf: function(mix, index){
- if (mix == null)
- return -1;
-
- if (index != null) {
- if (index < 0)
- index = 0;
-
- if (index >= this.length)
- return -1;
-
- }
- else{
- index = 0;
- }
-
-
- var imax = this.length;
- for(; index < imax; index++) {
- if (check(this[index], mix))
- return index;
- }
- return -1;
- },
- lastIndexOf: function(mix, index){
- if (mix == null)
- return -1;
-
- if (index != null) {
- if (index >= this.length)
- index = this.length - 1;
-
- if (index < 0)
- return -1;
- }
- else {
- index = this.length - 1;
- }
-
-
- for (; index > -1; index--) {
- if (check(this[index], mix))
- return index;
- }
-
- return -1;
- },
-
- map: function(fn){
-
- var arr = [],
- imax = this.length,
- i = -1;
- while( ++i < imax ){
- arr[i] = fn(this[i]);
- }
- return arr;
- },
-
- filter: function(fn, ctx){
- var coll = new this.constructor(),
- imax = this.length,
- i = -1;
- while ( ++i < imax ){
- if (fn.call(ctx || this, this[i])) {
- coll.push(this[i]);
- }
- }
- return coll;
- }
- };
-
- // ES6 iterator
- if (typeof Symbol !== 'undefined' && Symbol.iterator) {
- ArrayProto[Symbol.iterator] = function(){
- var arr = this,
- i = -1;
- return {
- next: function(){
- return {
- value: arr[++i],
- done: i > arr.length - 1
- };
- },
- hasNext: function(){
- return i < arr.length;
- }
- }
- };
- }
-
- function forEach(fn, ctx){
- var imax = this.length,
- i = -1
- ;
- while( ++i < imax ) {
- fn.call(ctx || this, this[i], i);
- }
- return this;
- }
-
-
- return ArrayProto;
- }());
-
- // end:source ArrayProto.js
-
- function create(Constructor, mix) {
-
- if (mix instanceof Constructor)
- return mix;
-
- return new Constructor(mix);
- }
-
- var CollectionProto = {
- toArray: function(){
- var array = new Array(this.length);
- for (var i = 0, imax = this.length; i < imax; i++){
- array[i] = this[i];
- }
-
- return array;
- },
-
- toJSON: json_proto_arrayToJSON
- };
-
- function Collection(/* (ClassName, Child, Proto) (Child, Proto) */) {
- var length = arguments.length,
- Proto = arguments[length - 1],
- Child = arguments[length - 2],
-
- className
- ;
-
- if (length > 2)
- className = arguments[0];
-
-
- Proto._ctor = Child;
- obj_inherit(Proto, CollectionProto, ArrayProto);
-
- return className == null
- ? Class(Proto)
- : Class(className, Proto)
- ;
- }
-
-
- return Collection;
- }());
- // end:source /src/collection/Collection.js
-
- // source /src/fn/fn.js
- (function(){
-
- // source memoize.js
- var fn_memoize,
- fn_memoizeAsync;
-
- (function(){
- fn_memoize = function(fn) {
- var _cache = {},
- _args = [];
- return function() {
- var id = fn_argsId(arguments, _args);
-
- return _cache[id] == null
- ? (_cache[id] = fn_apply(fn, this, arguments))
- : _cache[id];
- };
- };
-
- fn_memoizeAsync = function(fn) {
- var _cache = {},
- _cacheCbs = {},
- _args = [];
-
- return function(){
-
- var args = _Array_slice.call(arguments),
- callback = args.pop();
-
- var id = fn_argsId(args, _args);
-
- if (_cache[id]){
- fn_apply(callback, this, _cache[id])
- return;
- }
-
- if (_cacheCbs[id]) {
- _cacheCbs[id].push(callback);
- return;
- }
-
- _cacheCbs[id] = [callback];
-
- args = _Array_slice.call(args);
- args.push(fn_resolveDelegate(_cache, _cacheCbs, id));
-
- fn_apply(fn, this, args);
- };
- };
-
- // === private
- function fn_resolveDelegate(cache, cbs, id) {
- return function(){
- cache[id] = arguments;
-
- for (var i = 0, x, imax = cbs[id].length; i < imax; i++){
- x = cbs[id][i];
- fn_apply(x, this, arguments);
- }
-
- cbs[i] = null;
- cache = null;
- cbs = null;
- };
- }
- }());
-
-
- // end:source memoize.js
-
- Class.Fn = {
- memoize: fn_memoize,
- memoizeAsync: fn_memoizeAsync
- };
-
- }());
- // end:source /src/fn/fn.js
-
- exports.Class = Class;
-
-}));
\ No newline at end of file
diff --git a/examples/atmajs/node_modules/includejs/lib/include.js b/examples/atmajs/node_modules/includejs/lib/include.js
deleted file mode 100644
index f704e74c14..0000000000
--- a/examples/atmajs/node_modules/includejs/lib/include.js
+++ /dev/null
@@ -1,2071 +0,0 @@
-
-// source ../src/head.js
-(function (root, factory) {
- 'use strict';
-
- var _global, _exports;
-
- if (typeof exports !== 'undefined' && (root === exports || root == null)){
- // raw nodejs module
- _global = _exports = global;
- }
-
- if (_global == null) {
- _global = typeof window === 'undefined' ? global : window;
- }
- if (_exports == null) {
- _exports = root || _global;
- }
-
- if (typeof include !== 'undefined' && typeof include.js === 'function') {
- // allow only one `include` per application
- _exports.include = include;
- _exports.includeLib = include.Lib || _global.includeLib;
- return;
- }
-
- factory(_global, _exports, _global.document);
-
-}(this, function (global, exports, document) {
- 'use strict';
-
-// end:source ../src/head.js
-
- // source ../src/1.scope-vars.js
-
- /**
- * .cfg
- * : path := root path. @default current working path, im browser window.location;
- * : eval := in node.js this conf. is forced
- * : lockedToFolder := makes current url as root path
- * Example "/script/main.js" within this window.location "{domain}/apps/1.html"
- * will become "{domain}/apps/script/main.js" instead of "{domain}/script/main.js"
- */
-
- var bin = {
- js: {},
- css: {},
- load: {}
- },
- isWeb = !! (global.location && global.location.protocol && /^https?:/.test(global.location.protocol)),
- reg_subFolder = /([^\/]+\/)?\.\.\//,
- reg_hasProtocol = /^(file|https?):/i,
- cfg = {
- path: null,
- loader: null,
- version: null,
- lockedToFolder: null,
- sync: null,
- eval: document == null
- },
- handler = {},
- hasOwnProp = {}.hasOwnProperty,
- emptyResponse = {
- load: {}
- },
- __array_slice = Array.prototype.slice,
-
- XMLHttpRequest = global.XMLHttpRequest;
-
-
- // end:source ../src/1.scope-vars.js
- // source ../src/2.Helper.js
- var Helper = { /** TODO: improve url handling*/
-
- reportError: function(e) {
- console.error('IncludeJS Error:', e, e.message, e.url);
- typeof handler.onerror === 'function' && handler.onerror(e);
- }
-
- },
-
- XHR = function(resource, callback) {
- var xhr = new XMLHttpRequest();
- xhr.onreadystatechange = function() {
- xhr.readyState === 4 && callback && callback(resource, xhr.responseText);
- };
-
- xhr.open('GET', typeof resource === 'object' ? resource.url : resource, true);
- xhr.send();
- };
-
- // end:source ../src/2.Helper.js
-
- // source ../src/utils/fn.js
- function fn_proxy(fn, ctx) {
-
- return function(){
- fn.apply(ctx, arguments);
- };
-
- }
-
- function fn_doNothing(fn) {
- typeof fn === 'function' && fn();
- }
- // end:source ../src/utils/fn.js
- // source ../src/utils/object.js
- var obj_inherit,
- obj_getProperty,
- obj_setProperty
- ;
-
- (function(){
-
- obj_inherit = function(target /* source, ..*/ ) {
- if (typeof target === 'function') {
- target = target.prototype;
- }
- var i = 1,
- imax = arguments.length,
- source, key;
- for (; i < imax; i++) {
-
- source = typeof arguments[i] === 'function'
- ? arguments[i].prototype
- : arguments[i];
-
- for (key in source) {
- target[key] = source[key];
- }
- }
- return target;
- };
-
- obj_getProperty = function(obj, property) {
- var chain = property.split('.'),
- length = chain.length,
- i = 0;
- for (; i < length; i++) {
- if (obj == null)
- return null;
-
- obj = obj[chain[i]];
- }
- return obj;
- };
-
- obj_setProperty = function(obj, property, value) {
- var chain = property.split('.'),
- imax = chain.length - 1,
- i = -1,
- key;
- while ( ++i < imax ) {
- key = chain[i];
- if (obj[key] == null)
- obj[key] = {};
-
- obj = obj[key];
- }
- obj[chain[i]] = value;
- };
-
- }());
-
- // end:source ../src/utils/object.js
- // source ../src/utils/array.js
- function arr_invoke(arr, args, ctx) {
-
- if (arr == null || arr instanceof Array === false) {
- return;
- }
-
- for (var i = 0, length = arr.length; i < length; i++) {
- if (typeof arr[i] !== 'function') {
- continue;
- }
- if (args == null) {
- arr[i].call(ctx);
- }else{
- arr[i].apply(ctx, args);
- }
- }
-
- }
-
- function arr_ensure(obj, xpath) {
- if (!xpath) {
- return obj;
- }
- var arr = xpath.split('.'),
- imax = arr.length - 1,
- i = 0,
- key;
-
- for (; i < imax; i++) {
- key = arr[i];
- obj = obj[key] || (obj[key] = {});
- }
-
- key = arr[imax];
- return obj[key] || (obj[key] = []);
- }
- // end:source ../src/utils/array.js
- // source ../src/utils/path.js
- var path_getDir,
- path_getFile,
- path_getExtension,
- path_resolveCurrent,
- path_normalize,
- path_win32Normalize,
- path_resolveUrl,
- path_combine,
- path_isRelative
- ;
-
- (function(){
-
-
- path_getDir = function(path) {
- return path.substring(0, path.lastIndexOf('/') + 1);
- };
-
- path_getFile = function(path) {
- path = path
- .replace('file://', '')
- .replace(/\\/g, '/')
- .replace(/\?[^\n]+$/, '');
-
- if (/^\/\w+:\/[^\/]/i.test(path)){
- // win32 drive
- return path.substring(1);
- }
- return path;
- };
-
- path_getExtension = function(path) {
- var query = path.indexOf('?');
- if (query === -1) {
- return path.substring(path.lastIndexOf('.') + 1);
- }
-
- return path.substring(path.lastIndexOf('.', query) + 1, query);
- };
-
- path_resolveCurrent = function() {
-
- if (document == null) {
- return typeof module === 'undefined'
- ? ''
- : path_win32Normalize(module.parent.filename);
- }
- var scripts = document.getElementsByTagName('script'),
- last = scripts[scripts.length - 1],
- url = last && last.getAttribute('src') || '';
-
- if (url[0] === '/') {
- return url;
- }
-
- var location = window
- .location
- .pathname
- .replace(/\/[^\/]+\.\w+$/, '');
-
- if (location[location.length - 1] !== '/') {
- location += '/';
- }
-
- return location + url;
- };
-
- path_normalize = function(path) {
- return path
- .replace(/\\/g, '/')
- // remove double slashes, but not near protocol
- .replace(/([^:\/])\/{2,}/g, '$1/')
- ;
- };
-
- path_win32Normalize = function(path){
- path = path_normalize(path);
- if (path.substring(0, 5) === 'file:')
- return path;
-
- return 'file:///' + path;
- };
-
- path_resolveUrl = function(url, parent) {
-
- if (reg_hasProtocol.test(url))
- return path_collapse(url);
-
- if (url.substring(0, 2) === './')
- url = url.substring(2);
-
- if (url[0] === '/' && parent != null && parent.base != null) {
- url = path_combine(parent.base, url);
- if (reg_hasProtocol.test(url))
- return path_collapse(url);
- }
- if (url[0] === '/' && cfg.path) {
- url = cfg.path + url.substring(1);
- if (reg_hasProtocol.test(url))
- return path_collapse(url);
- }
- if (url[0] === '/') {
- if (isWeb === false || cfg.lockedToFolder === true) {
- url = url.substring(1);
- }
- } else if (parent != null && parent.location != null) {
- url = parent.location + url;
- }
-
- return path_collapse(url);
- };
-
- path_isRelative = function(path) {
- var c = path.charCodeAt(0);
-
- switch (c) {
- case 47:
- // /
- return false;
- case 102:
- // f
- case 104:
- // h
- return reg_hasProtocol.test(path) === false;
- }
-
- return true;
- };
-
- path_combine = function() {
- var out = '',
- imax = arguments.length,
- i = -1,
- x
- ;
- while ( ++i < imax ){
- x = arguments[i];
- if (!x)
- continue;
-
- x = path_normalize(x);
-
- if (out === '') {
- out = x;
- continue;
- }
-
- if (out[out.length - 1] !== '/')
- out += '/'
-
- if (x[0] === '/')
- x = x.substring(1);
-
- out += x;
- }
-
- return out;
- };
-
- function path_collapse(url) {
- while (url.indexOf('../') !== -1) {
- url = url.replace(reg_subFolder, '');
- }
-
- return url.replace(/\/\.\//g, '/');
- }
-
- }());
-
-
- // end:source ../src/utils/path.js
- // source ../src/utils/tree.js
- var tree_resolveUsage;
-
-
- (function(){
-
- tree_resolveUsage = function(resource, usage, next){
- var use = [],
- imax = usage.length,
- i = -1,
-
- obj, path, name, index, parent
- ;
- while( ++i < imax ) {
-
- name = path = usage[i];
- index = path.indexOf('.');
- if ( index !== -1) {
- name = path.substring(0, index);
- path = path.substring(index + 1);
- }
-
- parent = use_resolveParent(name, resource.parent, resource);
- if (parent == null)
- return null;
-
- if (parent.state !== 4){
- resource.state = 3;
- parent.on(4, next, parent, 'push');
- return null;
- }
-
- obj = parent.exports;
-
- if (name !== path)
- obj = obj_getProperty(obj, path);
-
- // if DEBUG
- (typeof obj === 'object' && obj == null)
- && console.warn(' Used resource has no exports', name, resource.url);
- // endif
-
- use[i] = obj;
- }
- return use;
- };
-
-
- function use_resolveParent(name, resource, initiator){
-
- if (resource == null) {
- // if DEBUG
- console.warn(' Usage Not Found:', name);
- console.warn('- Ensure to have it included before with the correct alias')
- console.warn('- Initiator Stacktrace:');
-
- var arr = [], res = initiator;
- while(res != null){
- arr.push(res.url);
- res = res.parent;
- }
- console.warn(arr.join('\n'));
- // endif
-
- return null;
- }
-
-
- var includes = resource.includes,
- i = -1,
- imax = includes.length,
-
- include, exports, alias
- ;
-
- while( ++i < imax ) {
- include = includes[i];
- alias = include.route.alias || Routes.parseAlias(include.route);
- if (alias === name)
- return include.resource;
- }
-
- return use_resolveParent(name, resource.parent, initiator);
- }
-
-
- }());
- // end:source ../src/utils/tree.js
-
- // source ../src/2.Routing.js
- var RoutesLib = function() {
-
- var routes = {},
- regexpAlias = /([^\\\/]+)\.\w+$/;
-
-
-
- return {
- /**
- * @param route {String} = Example: '.reference/libjs/{0}/{1}.js'
- */
- register: function(namespace, route, currentInclude) {
-
- if (typeof route === 'string' && path_isRelative(route)) {
- var res = currentInclude || include,
- location = res.location || path_getDir(res.url || path_resolveCurrent());
-
- if (path_isRelative(location)) {
- location = '/' + location;
- }
-
- route = location + route;
- }
-
- routes[namespace] = route instanceof Array ? route : route.split(/[\{\}]/g);
-
- },
-
- /**
- * @param {String} template = Example: 'scroller/scroller.min?ui=black'
- */
- resolve: function(namespace, template) {
- var questionMark = template.indexOf('?'),
- aliasIndex = template.indexOf('::'),
- alias,
- path,
- params,
- route,
- i,
- x,
- length,
- arr;
-
-
- if (aliasIndex !== -1){
- alias = template.substring(aliasIndex + 2);
- template = template.substring(0, aliasIndex);
- }
-
- if (questionMark !== -1) {
- arr = template.substring(questionMark + 1).split('&');
- params = {};
-
- for (i = 0, length = arr.length; i < length; i++) {
- x = arr[i].split('=');
- params[x[0]] = x[1];
- }
-
- template = template.substring(0, questionMark);
- }
-
- template = template.split('/');
- route = routes[namespace];
-
- if (route == null){
- return {
- path: template.join('/'),
- params: params,
- alias: alias
- };
- }
-
- path = route[0];
-
- for (i = 1; i < route.length; i++) {
- if (i % 2 === 0) {
- path += route[i];
- } else {
- /** if template provides less "breadcrumbs" than needed -
- * take always the last one for failed peaces */
-
- var index = route[i] << 0;
- if (index > template.length - 1) {
- index = template.length - 1;
- }
-
-
-
- path += template[index];
-
- if (i === route.length - 2){
- for(index++; index < template.length; index++){
- path += '/' + template[index];
- }
- }
- }
- }
-
- return {
- path: path,
- params: params,
- alias: alias
- };
- },
-
- /**
- * @arg includeData :
- * 1. string - URL to resource
- * 2. array - URLs to resources
- * 3. object - {route: x} - route defines the route template to resource,
- * it must be set before in include.cfg.
- * example:
- * include.cfg('net','scripts/net/{name}.js')
- * include.js({net: 'downloader'}) // -> will load scipts/net/downloader.js
- * @arg namespace - route in case of resource url template, or namespace in case of LazyModule
- *
- * @arg fn - callback function, which receives namespace|route, url to resource and ?id in case of not relative url
- * @arg xpath - xpath string of a lazy object 'object.sub.and.othersub';
- */
- each: function(type, includeData, fn, namespace, xpath) {
- var key;
-
- if (includeData == null) {
- return;
- }
-
- if (type === 'lazy' && xpath == null) {
- for (key in includeData) {
- this.each(type, includeData[key], fn, null, key);
- }
- return;
- }
- if (includeData instanceof Array) {
- for (var i = 0; i < includeData.length; i++) {
- this.each(type, includeData[i], fn, namespace, xpath);
- }
- return;
- }
- if (typeof includeData === 'object') {
- for (key in includeData) {
- if (hasOwnProp.call(includeData, key)) {
- this.each(type, includeData[key], fn, key, xpath);
- }
- }
- return;
- }
-
- if (typeof includeData === 'string') {
- var x = this.resolve(namespace, includeData);
- if (namespace){
- namespace += '.' + includeData;
- }
-
- fn(namespace, x, xpath);
- return;
- }
-
- console.error('Include Package is invalid', arguments);
- },
-
- getRoutes: function(){
- return routes;
- },
-
- parseAlias: function(route){
- var path = route.path,
- result = regexpAlias.exec(path);
-
- return result && result[1];
- }
- };
-
- };
-
- var Routes = RoutesLib();
-
-
- /*{test}
-
- console.log(JSON.stringify(Routes.resolve(null,'scroller.js::Scroller')));
-
- Routes.register('lib', '.reference/libjs/{0}/lib/{1}.js');
- console.log(JSON.stringify(Routes.resolve('lib','scroller::Scroller')));
- console.log(JSON.stringify(Routes.resolve('lib','scroller/scroller.mobile?ui=black')));
-
- Routes.register('framework', '.reference/libjs/framework/{0}.js');
- console.log(JSON.stringify(Routes.resolve('framework','dom/jquery')));
-
-
- */
- // end:source ../src/2.Routing.js
- // source ../src/3.Events.js
- var Events = (function(document) {
- if (document == null) {
- return {
- ready: fn_doNothing,
- load: fn_doNothing
- };
- }
- var readycollection = [];
-
- function onReady() {
- Events.ready = fn_doNothing;
-
- if (readycollection == null) {
- return;
- }
-
- arr_invoke(readycollection);
- readycollection = null;
- }
-
- /** TODO: clean this */
-
- if ('onreadystatechange' in document) {
- document.onreadystatechange = function() {
- if (/complete|interactive/g.test(document.readyState) === false) {
- return;
- }
- onReady();
- };
- } else if (document.addEventListener) {
- document.addEventListener('DOMContentLoaded', onReady);
- }else {
- window.onload = onReady;
- }
-
-
- return {
- ready: function(callback) {
- readycollection.unshift(callback);
- }
- };
- })(document);
-
- // end:source ../src/3.Events.js
- // source ../src/6.ScriptStack.js
- /** @TODO Refactor loadBy* {combine logic} */
-
- var ScriptStack = (function() {
-
- var head,
- currentResource,
- stack = [],
-
- _cb_complete = [],
- _paused;
-
-
- function loadScript(url, callback) {
- //console.log('load script', url);
- var tag = document.createElement('script');
- tag.type = 'text/javascript';
- tag.src = url;
-
- if ('onreadystatechange' in tag) {
- tag.onreadystatechange = function() {
- (this.readyState === 'complete' || this.readyState === 'loaded') && callback();
- };
- } else {
- tag.onload = tag.onerror = callback;
- }
-
- ;(head || (head = document.getElementsByTagName('head')[0])).appendChild(tag);
- }
-
- function loadByEmbedding() {
- if (_paused) {
- return;
- }
-
- if (stack.length === 0){
- trigger_complete();
- return;
- }
-
- if (currentResource != null) {
- return;
- }
-
- var resource = (currentResource = stack[0]);
-
- if (resource.state === 1) {
- return;
- }
-
- resource.state = 1;
-
- global.include = resource;
- global.iparams = resource.route.params;
-
-
- function resourceLoaded(e) {
-
-
- if (e && e.type === 'error') {
- console.log('Script Loaded Error', resource.url);
- }
-
- var i = 0,
- length = stack.length;
-
- for (; i < length; i++) {
- if (stack[i] === resource) {
- stack.splice(i, 1);
- break;
- }
- }
-
- if (i === length) {
- console.error('Loaded Resource not found in stack', resource);
- return;
- }
-
- if (resource.state !== 2.5)
- resource.readystatechanged(3);
- currentResource = null;
- loadByEmbedding();
- }
-
- if (resource.source) {
- __eval(resource.source, resource);
-
- resourceLoaded();
- return;
- }
-
- loadScript(resource.url, resourceLoaded);
- }
-
- function processByEval() {
- if (_paused) {
- return;
- }
-
- if (stack.length === 0){
- trigger_complete();
- return;
- }
-
- if (currentResource != null) {
- return;
- }
-
- var resource = stack[0];
-
- if (resource.state < 2) {
- return;
- }
-
- currentResource = resource;
-
- resource.state = 1;
- global.include = resource;
-
- //console.log('evaling', resource.url, stack.length);
- __eval(resource.source, resource);
-
- for (var i = 0, x, length = stack.length; i < length; i++) {
- x = stack[i];
- if (x === resource) {
- stack.splice(i, 1);
- break;
- }
- }
-
- if (resource.state !== 2.5)
- resource.readystatechanged(3);
- currentResource = null;
- processByEval();
-
- }
-
-
- function trigger_complete() {
- var i = -1,
- imax = _cb_complete.length;
- while (++i < imax) {
- _cb_complete[i]();
- }
-
- _cb_complete.length = 0;
- }
-
-
-
- return {
- load: function(resource, parent, forceEmbed) {
-
- this.add(resource, parent);
-
- if (!cfg.eval || forceEmbed) {
- loadByEmbedding();
- return;
- }
-
- // was already loaded, with custom loader for example
- if (resource.source) {
- resource.state = 2;
- processByEval();
- return;
- }
-
- XHR(resource, function(resource, response) {
- if (!response) {
- console.error('Not Loaded:', resource.url);
- console.error('- Initiator:', resource.parent && resource.parent.url || '');
- }
-
- resource.source = response;
- resource.state = 2;
-
- processByEval();
- });
- },
-
- add: function(resource, parent){
-
- if (resource.priority === 1)
- return stack.unshift(resource);
-
-
- if (parent == null)
- return stack.push(resource);
-
-
- var imax = stack.length,
- i = -1
- ;
- // move close to parent
- while( ++i < imax){
- if (stack[i] === parent)
- return stack.splice(i, 0, resource);
- }
-
- // was still not added
- stack.push(resource);
- },
-
- /* Move resource in stack close to parent */
- moveToParent: function(resource, parent) {
- var length = stack.length,
- parentIndex = -1,
- resourceIndex = -1,
- i;
-
- for (i = 0; i < length; i++) {
- if (stack[i] === resource) {
- resourceIndex = i;
- break;
- }
- }
-
- if (resourceIndex === -1) {
- return;
- }
-
- for (i= 0; i < length; i++) {
- if (stack[i] === parent) {
- parentIndex = i;
- break;
- }
- }
-
- if (parentIndex === -1) {
- return;
- }
-
- if (resourceIndex < parentIndex) {
- return;
- }
-
- stack.splice(resourceIndex, 1);
- stack.splice(parentIndex, 0, resource);
-
-
- },
-
- pause: function(){
- _paused = true;
- },
-
- resume: function(){
- _paused = false;
-
- if (currentResource != null)
- return;
-
- this.touch();
- },
-
- touch: function(){
- var fn = cfg.eval
- ? processByEval
- : loadByEmbedding
- ;
- fn();
- },
-
- complete: function(callback){
- if (_paused !== true && stack.length === 0) {
- callback();
- return;
- }
-
- _cb_complete.push(callback);
- }
- };
- })();
-
- // end:source ../src/6.ScriptStack.js
-
- // source ../src/4.IncludeDeferred.js
-
- /**
- * STATES:
- * 0: Resource Created
- * 1: Loading
- * 2: Loaded - Evaluating
- * 2.5: Paused - Evaluating paused
- * 3: Evaluated - Childs Loading
- * 4: Childs Loaded - Completed
- */
-
- var IncludeDeferred = function() {
- this.callbacks = [];
- this.state = -1;
- };
-
- IncludeDeferred.prototype = { /** state observer */
-
- on: function(state, callback, sender, mutator) {
- if (this === sender && this.state === -1) {
- callback(this);
- return this;
- }
-
- // this === sender in case when script loads additional
- // resources and there are already parents listeners
-
- if (mutator == null) {
- mutator = (this.state < 3 || this === sender)
- ? 'unshift'
- : 'push'
- ;
- }
-
- state <= this.state ? callback(this) : this.callbacks[mutator]({
- state: state,
- callback: callback
- });
- return this;
- },
- readystatechanged: function(state) {
-
- var i, length, x, currentInclude;
-
- if (state > this.state) {
- this.state = state;
- }
-
- if (this.state === 3) {
- var includes = this.includes;
-
- if (includes != null && includes.length) {
- for (i = 0; i < includes.length; i++) {
- if (includes[i].resource.state !== 4) {
- return;
- }
- }
- }
-
- this.state = 4;
- }
-
- i = 0;
- length = this.callbacks.length;
-
- if (length === 0){
- return;
- }
-
- //do not set asset resource to global
- if (this.type === 'js' && this.state === 4) {
- currentInclude = global.include;
- global.include = this;
- }
-
- for (; i < length; i++) {
- x = this.callbacks[i];
- if (x == null || x.state > this.state) {
- continue;
- }
-
- this.callbacks.splice(i,1);
- length--;
- i--;
-
- /* if (!DEBUG)
- try {
- */
- x.callback(this);
- /* if (!DEBUG)
- } catch(error){
- console.error(error.toString(), 'file:', this.url);
- }
- */
-
- if (this.state < 4){
- break;
- }
- }
-
- if (currentInclude != null && currentInclude.type === 'js'){
- global.include = currentInclude;
- }
- },
-
- /** assets loaded and DomContentLoaded */
-
- ready: function(callback) {
- var that = this;
- return this.on(4, function() {
- Events.ready(function(){
- that.resolve(callback);
- });
- }, this);
- },
-
- /** assets loaded */
- done: function(callback) {
- var that = this;
- return this.on(4, function(){
- that.resolve(callback);
- }, this);
- },
- resolve: function(callback) {
- var includes = this.includes,
- length = includes == null
- ? 0
- : includes.length
- ;
-
- if (length > 0 && this.response == null){
- this.response = {};
-
- var resource,
- route;
-
- for(var i = 0, x; i < length; i++){
- x = includes[i];
- resource = x.resource;
- route = x.route;
-
- if (typeof resource.exports === 'undefined')
- continue;
-
- var type = resource.type;
- switch (type) {
- case 'js':
- case 'load':
- case 'ajax':
-
- var alias = route.alias || Routes.parseAlias(route),
- obj = type === 'js'
- ? (this.response)
- : (this.response[type] || (this.response[type] = {}))
- ;
-
- if (alias != null) {
- obj_setProperty(obj, alias, resource.exports);
- break;
- }
- console.warn(' Alias is undefined', resource);
- break;
- }
- }
- }
-
- var response = this.response || emptyResponse;
- var that = this;
- if (this._use == null && this._usage != null){
- this._use = tree_resolveUsage(this, this._usage, function(){
- that.state = 4;
- that.resolve(callback);
- that.readystatechanged(4);
- });
- if (this.state < 4)
- return;
- }
- if (this._use) {
- callback.apply(null, [response].concat(this._use));
- return;
- }
-
- callback(response);
- }
- };
-
- // end:source ../src/4.IncludeDeferred.js
- // source ../src/5.Include.js
- var Include,
- IncludeLib = {};
- (function(IncludeDeferred) {
-
- Include = function() {
- IncludeDeferred.call(this);
- };
-
- stub_release(Include.prototype);
-
- obj_inherit(Include, IncludeDeferred, {
- // Array: exports
- _use: null,
-
- // Array: names
- _usage: null,
-
- isBrowser: true,
- isNode: false,
-
- setCurrent: function(data) {
- var url = data.url,
- resource = this.getResourceById(url, 'js');
-
- if (resource == null) {
- if (url[0] === '/' && this.base)
- url = this.base + url.substring(1);
-
- var resource = new Resource(
- 'js'
- , { path: url }
- , data.namespace
- , null
- , null
- , url);
- }
- if (resource.state < 3) {
- console.error(" Resource should be loaded", data);
- }
-
- /**@TODO - probably state shoulb be changed to 2 at this place */
- resource.state = 3;
- global.include = resource;
- },
-
- cfg: function(arg) {
- switch (typeof arg) {
- case 'object':
- var key, value;
- for (key in arg) {
- value = arg[key];
-
- switch(key){
- case 'loader':
- for(var x in value){
- CustomLoader.register(x, value[x]);
- }
- break;
- case 'modules':
- if (value === true){
- enableModules();
- }
- break;
- default:
- cfg[key] = value;
- break;
- }
-
- }
- break;
- case 'string':
- if (arguments.length === 1) {
- return cfg[arg];
- }
- if (arguments.length === 2) {
- cfg[arg] = arguments[1];
- }
- break;
- case 'undefined':
- return cfg;
- }
- return this;
- },
- routes: function(mix) {
- if (mix == null) {
- return Routes.getRoutes();
- }
-
- if (arguments.length === 2) {
- Routes.register(mix, arguments[1], this);
- return this;
- }
-
- for (var key in mix) {
- Routes.register(key, mix[key], this);
- }
- return this;
- },
- promise: function(namespace) {
- var arr = namespace.split('.'),
- obj = global;
- while (arr.length) {
- var key = arr.shift();
- obj = obj[key] || (obj[key] = {});
- }
- return obj;
- },
- /** @TODO - `id` property seems to be unsed and always equal to `url` */
- register: function(_bin) {
-
- var base = this.base,
- key,
- info,
- infos,
- imax,
- i;
-
- function transform(info){
- if (base == null)
- return info;
- if (info.url[0] === '/')
- info.url = base + info.url.substring(1);
-
- if (info.parent[0] === '/')
- info.parent = base + info.parent.substring(1);
-
- info.id = info.url;
- return info;
- }
-
- for (key in _bin) {
- infos = _bin[key];
- imax = infos.length;
- i = -1;
-
- while ( ++i < imax ) {
-
- info = transform(infos[i]);
-
- var id = info.id,
- url = info.url,
- namespace = info.namespace,
- parent = info.parent && incl_getResource(info.parent, 'js'),
- resource = new Resource(),
- state = info.state
- ;
- if (! (id || url))
- continue;
-
- if (url) {
- if (url[0] === '/') {
- url = url.substring(1);
- }
- resource.location = path_getDir(url);
- }
-
-
- resource.state = state == null
- ? (key === 'js' ? 3 : 4)
- : state
- ;
- resource.namespace = namespace;
- resource.type = key;
- resource.url = url || id;
- resource.parent = parent;
- resource.base = parent && parent.base || base;
-
- switch (key) {
- case 'load':
- case 'lazy':
- var container = document.querySelector('#includejs-' + id.replace(/\W/g, ''));
- if (container == null) {
- console.error('"%s" Data was not embedded into html', id);
- break;
- }
- resource.exports = container.innerHTML;
- if (CustomLoader.exists(resource)){
-
- resource.state = 3;
- CustomLoader.load(resource, CustomLoader_onComplete);
- }
- break;
- }
-
- //
- (bin[key] || (bin[key] = {}))[id] = resource;
- }
- }
- function CustomLoader_onComplete(resource, response) {
- resource.exports = response;
- resource.readystatechanged(4);
- }
- },
- /**
- * Create new Resource Instance,
- * as sometimes it is necessary to call include. on new empty context
- */
- instance: function(url, parent) {
- var resource;
- if (url == null) {
- resource = new Include();
- resource.state = 4;
-
- return resource;
- }
-
- resource = new Resource('package');
- resource.state = 4;
- resource.location = path_getDir(path_normalize(url));
- resource.parent = parent;
- return resource;
- },
-
- getResource: function(url, type){
- if (this.base && url[0] === '/')
- url = this.base + url.substring(1);
-
- return incl_getResource(url, type)
- },
- getResourceById: function(url, type){
- var _bin = bin[type],
- _res = _bin[url];
- if (_res != null)
- return _res;
-
- if (this.base && url[0] === '/') {
- _res = _bin[path_combine(this.base, url)];
- if (_res != null)
- return _res;
- }
- if (this.base && this.location) {
- _res = _bin[path_combine(this.base, this.location, url)];
- if (_res != null)
- return _res;
- }
- if (this.location) {
- _res = _bin[path_combine(this.location, url)];
- if (_res != null)
- return _res;
- }
- return null;
- },
- getResources: function(){
- return bin;
- },
-
- plugin: function(pckg, callback) {
-
- var urls = [],
- length = 0,
- j = 0,
- i = 0,
- onload = function(url, response) {
- j++;
-
- embedPlugin(response);
-
- if (j === length - 1 && callback) {
- callback();
- callback = null;
- }
- };
- Routes.each('', pckg, function(namespace, route) {
- urls.push(route.path[0] === '/' ? route.path.substring(1) : route.path);
- });
-
- length = urls.length;
-
- for (; i < length; i++) {
- XHR(urls[i], onload);
- }
- return this;
- },
-
- client: function(){
- if (cfg.server === true)
- stub_freeze(this);
-
- return this;
- },
-
- server: function(){
- if (cfg.server !== true)
- stub_freeze(this);
-
- return this;
- },
-
- use: function(){
- if (this.parent == null) {
- console.error(' Parent resource is undefined');
- return this;
- }
-
- this._usage = arguments;
- return this;
- },
-
- pauseStack: fn_proxy(ScriptStack.pause, ScriptStack),
- resumeStack: fn_proxy(ScriptStack.resume, ScriptStack),
-
- allDone: function(callback){
- ScriptStack.complete(function(){
-
- var pending = include.getPending(),
- await = pending.length;
- if (await === 0) {
- callback();
- return;
- }
-
- var i = -1,
- imax = await;
- while( ++i < imax ){
- pending[i].on(4, check, null, 'push');
- }
-
- function check() {
- if (--await < 1)
- callback();
- }
- });
- },
-
- getPending: function(type){
- var resources = [],
- res, key, id;
-
- for(key in bin){
- if (type != null && type !== key)
- continue;
-
- for (id in bin[key]){
- res = bin[key][id];
- if (res.state < 4)
- resources.push(res);
- }
- }
-
- return resources;
- },
- Lib: IncludeLib
- });
-
-
- // >> FUNCTIONS
-
- function incl_getResource(url, type) {
- var id = url;
-
- if (path_isRelative(url) === true)
- id = '/' + id;
-
- if (type != null){
- return bin[type][id];
- }
-
- for (var key in bin) {
- if (bin[key].hasOwnProperty(id)) {
- return bin[key][id];
- }
- }
- return null;
- }
-
-
- function embedPlugin(source) {
- eval(source);
- }
-
- function enableModules() {
- if (typeof Object.defineProperty === 'undefined'){
- console.warn('Browser do not support Object.defineProperty');
- return;
- }
- Object.defineProperty(global, 'module', {
- get: function() {
- return global.include;
- }
- });
-
- Object.defineProperty(global, 'exports', {
- get: function() {
- var current = global.include;
- return (current.exports || (current.exports = {}));
- },
- set: function(exports) {
- global.include.exports = exports;
- }
- });
- }
-
- function includePackage(resource, type, mix){
- var pckg = mix.length === 1 ? mix[0] : __array_slice.call(mix);
-
- if (resource instanceof Resource) {
- return resource.include(type, pckg);
- }
- return new Resource('js').include(type, pckg);
- }
-
- function createIncluder(type) {
- return function(){
- return includePackage(this, type, arguments);
- };
- }
-
- function doNothing() {
- return this;
- }
-
- function stub_freeze(include) {
- include.js =
- include.css =
- include.load =
- include.ajax =
- include.embed =
- include.lazy =
- include.inject =
- doNothing;
- }
-
- function stub_release(proto) {
- var fns = ['js', 'css', 'load', 'ajax', 'embed', 'lazy'],
- i = fns.length;
- while (--i !== -1){
- proto[fns[i]] = createIncluder(fns[i]);
- }
-
- proto['inject'] = proto.js;
- }
-
- }(IncludeDeferred));
-
- // end:source ../src/5.Include.js
- // source ../src/7.CustomLoader.js
- var CustomLoader = (function() {
-
- // source loader/json.js
-
- var JSONParser = {
- process: function(source, res){
- try {
- return JSON.parse(source);
- } catch(error) {
- console.error(error, source);
- return null;
- }
- }
- };
-
-
- // end:source loader/json.js
-
- cfg.loader = {
- json : JSONParser
- };
-
- function loader_isInstance(x) {
- if (typeof x === 'string')
- return false;
-
- return typeof x.ready === 'function' || typeof x.process === 'function';
- }
-
- function createLoader(url) {
- var extension = path_getExtension(url),
- loader = cfg.loader[extension];
-
- if (loader_isInstance(loader)) {
- return loader;
- }
-
- var path = loader,
- namespace;
-
- if (typeof path === 'object') {
- // is route {namespace: path}
- for (var key in path) {
- namespace = key;
- path = path[key];
- break;
- }
- }
-
- return (cfg.loader[extension] = new Resource(
- 'js',
- Routes.resolve(namespace, path),
- namespace,
- null,
- null,
- null,
- 1
- ));
- }
-
- function loader_completeDelegate(callback, resource) {
- return function(response){
- callback(resource, response);
- };
- }
-
- function loader_process(source, resource, loader, callback) {
- if (loader.process == null) {
- callback(resource, source);
- return;
- }
-
- var delegate = loader_completeDelegate(callback, resource),
- syncResponse = loader.process(source, resource, delegate);
-
- // match also null
- if (typeof syncResponse !== 'undefined') {
- callback(resource, syncResponse);
- }
- }
-
- function tryLoad(resource, loader, callback) {
- if (typeof resource.exports === 'string') {
- loader_process(resource.exports, resource, loader, callback);
- return;
- }
-
- function onLoad(resource, response){
- loader_process(response, resource, loader, callback);
- }
-
- if (loader.load)
- return loader.load(resource, onLoad);
-
- XHR(resource, onLoad);
- }
-
- return {
- load: function(resource, callback) {
-
- var loader = createLoader(resource.url);
-
- if (loader.process) {
- tryLoad(resource, loader, callback);
- return;
- }
-
- loader.on(4, function() {
- tryLoad(resource, loader.exports, callback);
- }, null, 'push');
- },
- exists: function(resource) {
- if (!resource.url) {
- return false;
- }
-
- var ext = path_getExtension(resource.url);
-
- return cfg.loader.hasOwnProperty(ext);
- },
-
- /**
- * IHandler:
- * { process: function(content) { return _handler(content); }; }
- *
- * Url:
- * path to IHandler
- */
- register: function(extension, handler){
- if (typeof handler === 'string'){
- var resource = include;
- if (resource.location == null) {
- resource = {
- location: path_getDir(path_resolveCurrent())
- };
- }
-
- handler = path_resolveUrl(handler, resource);
- }
-
- cfg.loader[extension] = handler;
- }
- };
- }());
-
- // end:source ../src/7.CustomLoader.js
- // source ../src/8.LazyModule.js
- var LazyModule = {
- create: function(xpath, code) {
- var arr = xpath.split('.'),
- obj = global,
- module = arr[arr.length - 1];
- while (arr.length > 1) {
- var prop = arr.shift();
- obj = obj[prop] || (obj[prop] = {});
- }
- arr = null;
-
- Object.defineProperty(obj, module, {
- get: function() {
-
- delete obj[module];
- try {
- var r = __eval(code, global.include);
- if (!(r == null || r instanceof Resource)){
- obj[module] = r;
- }
- } catch (error) {
- error.xpath = xpath;
- Helper.reportError(error);
- } finally {
- code = null;
- xpath = null;
- return obj[module];
- }
- }
- });
- }
- };
- // end:source ../src/8.LazyModule.js
- // source ../src/9.Resource.js
- var Resource;
-
- (function(Include, Routes, ScriptStack, CustomLoader) {
-
- Resource = function(type, route, namespace, xpath, parent, id, priority) {
- Include.call(this);
-
- this.childLoaded = fn_proxy(this.childLoaded, this);
-
- var url = route && route.path;
- if (url != null)
- this.url = url = path_resolveUrl(url, parent);
-
- this.type = type;
- this.xpath = xpath;
- this.route = route;
- this.parent = parent;
- this.priority = priority;
- this.namespace = namespace;
- this.base = parent && parent.base;
-
- if (id == null && url)
- id = (path_isRelative(url) ? '/' : '') + url;
-
- var resource = bin[type] && bin[type][id];
- if (resource) {
-
- if (resource.state < 4 && type === 'js')
- ScriptStack.moveToParent(resource, parent);
-
- return resource;
- }
-
- if (url == null) {
- this.state = 3;
- this.location = path_getDir(path_resolveCurrent());
- return this;
- }
-
- this.state = 0;
- this.location = path_getDir(url);
-
- (bin[type] || (bin[type] = {}))[id] = this;
-
- if (cfg.version)
- this.url += (this.url.indexOf('?') === -1 ? '?' : '&') + 'v=' + cfg.version;
-
- return process(this);
-
- };
-
- Resource.prototype = obj_inherit(Resource, Include, {
-
- state: null,
- location: null,
- includes: null,
- response: null,
-
- url: null,
- base: null,
- type: null,
- xpath: null,
- route: null,
- parent: null,
- priority: null,
- namespace: null,
-
- setBase: function(baseUrl){
- this.base = baseUrl;
- return this;
- },
-
- childLoaded: function(child) {
- var resource = this,
- includes = resource.includes;
- if (includes && includes.length) {
- if (resource.state < 3) {
- // resource still loading/include is in process, but one of sub resources are already done
- return;
- }
- for (var i = 0; i < includes.length; i++) {
- if (includes[i].resource.state !== 4) {
- return;
- }
- }
- }
- resource.readystatechanged(4);
- },
- create: function(type, route, namespace, xpath, id) {
- var resource;
-
- this.state = this.state >= 3
- ? 3
- : 2;
- this.response = null;
-
- if (this.includes == null)
- this.includes = [];
-
-
- resource = new Resource(type, route, namespace, xpath, this, id);
-
- this.includes.push({
- resource: resource,
- route: route
- });
-
- return resource;
- },
- include: function(type, pckg) {
- var that = this,
- children = [],
- child;
- Routes.each(type, pckg, function(namespace, route, xpath) {
-
- if (that.route != null && that.route.path === route.path) {
- // loading itself
- return;
- }
- child = that.create(type, route, namespace, xpath);
- children.push(child);
- });
-
- var i = -1,
- imax = children.length;
- while ( ++i < imax ){
- children[i].on(4, this.childLoaded);
- }
-
- return this;
- },
-
- pause: function(){
- this.state = 2.5;
-
- var that = this;
- return function(exports){
-
- if (arguments.length === 1)
- that.exports = exports;
-
- that.readystatechanged(3);
- };
- },
-
- getNestedOfType: function(type){
- return resource_getChildren(this.includes, type);
- }
- });
-
- // private
-
- function process(resource) {
- var type = resource.type,
- parent = resource.parent,
- url = resource.url;
-
- if (document == null && type === 'css') {
- resource.state = 4;
- return resource;
- }
-
- if (CustomLoader.exists(resource) === false) {
- switch (type) {
- case 'js':
- case 'embed':
- ScriptStack.load(resource, parent, type === 'embed');
- break;
- case 'ajax':
- case 'load':
- case 'lazy':
- XHR(resource, onXHRCompleted);
- break;
- case 'css':
- resource.state = 4;
-
- var tag = document.createElement('link');
- tag.href = url;
- tag.rel = "stylesheet";
- tag.type = "text/css";
- document.getElementsByTagName('head')[0].appendChild(tag);
- break;
- }
- } else {
-
- if ('js' === type || 'embed' === type) {
- ScriptStack.add(resource, resource.parent);
- }
-
- CustomLoader.load(resource, onXHRCompleted);
- }
-
- return resource;
- }
-
- function onXHRCompleted(resource, response) {
- if (!response) {
- console.warn('Resource cannt be loaded', resource.url);
- //- resource.readystatechanged(4);
- //- return;
- }
-
- switch (resource.type) {
- case 'js':
- case 'embed':
- resource.source = response;
- resource.state = 2;
- ScriptStack.touch();
- return;
- case 'load':
- case 'ajax':
- resource.exports = response;
- break;
- case 'lazy':
- LazyModule.create(resource.xpath, response);
- break;
- case 'css':
- var tag = document.createElement('style');
- tag.type = "text/css";
- tag.innerHTML = response;
- document.getElementsByTagName('head')[0].appendChild(tag);
- break;
- }
-
- resource.readystatechanged(4);
- }
-
- function resource_getChildren(includes, type, out) {
- if (includes == null)
- return null;
-
- if (out == null)
- out = [];
-
- var imax = includes.length,
- i = -1,
- x;
- while ( ++i < imax ){
- x = includes[i].resource;
-
- if (type === x.type)
- out.push(x);
-
- if (x.includes != null)
- resource_getChildren(x.includes, type, out);
- }
- return out;
- }
-
- }(Include, Routes, ScriptStack, CustomLoader));
- // end:source ../src/9.Resource.js
-
- // source ../src/10.export.js
- IncludeLib.Routes = RoutesLib;
- IncludeLib.Resource = Resource;
- IncludeLib.ScriptStack = ScriptStack;
- IncludeLib.registerLoader = CustomLoader.register;
-
- exports.include = new Include();
- exports.includeLib = IncludeLib;
-
-
-
- // end:source ../src/10.export.js
-}));
-
-// source ../src/global-vars.js
-
-function __eval(source, include) {
- "use strict";
-
- var iparams = include && include.route.params;
-
- /* if !DEBUG
- try {
- */
- return eval.call(window, source);
-
- /* if !DEBUG
- } catch (error) {
- error.url = include && include.url;
- //Helper.reportError(error);
- console.error(error);
- }
- */
-
-}
-// end:source ../src/global-vars.js
\ No newline at end of file
diff --git a/examples/atmajs/node_modules/maskjs/lib/mask.js b/examples/atmajs/node_modules/maskjs/lib/mask.js
deleted file mode 100644
index 5ec2aa8e0f..0000000000
--- a/examples/atmajs/node_modules/maskjs/lib/mask.js
+++ /dev/null
@@ -1,19875 +0,0 @@
-
-
-
-// source umd-head
-/*!
- * MaskJS v0.51.37
- * Part of the Atma.js Project
- * http://atmajs.com/
- *
- * MIT license
- * http://opensource.org/licenses/MIT
- *
- * (c) 2012, 2015 Atma.js and other contributors
- */
-(function (root, factory) {
- 'use strict';
-
- var _env = (typeof window === 'undefined' || window.navigator == null)
- ? 'node'
- : 'dom';
- var _global = (_env === 'dom')
- ? window
- : global;
- var _isCommonJs = typeof exports !== 'undefined'
- && (root == null || root === exports || root === _global);
- if (_isCommonJs) {
- root = exports;
- }
- var _exports = root || _global;
- var _document = _global.document;
-
- function construct(){
- var mask = factory(_global, _exports, _document);
- if (_isCommonJs) {
- module.exports = mask;
- }
- return mask;
- }
-
- if (typeof define === 'function' && define.amd) {
- return define(construct);
- }
-
- // Browser OR Node
- return construct();
-
-}(this, function (global, exports, document) {
- 'use strict';
-
-// end:source umd-head
-
- // source /ref-utils/lib/utils.embed.js
- // source /src/refs.js
- var _Array_slice = Array.prototype.slice,
- _Array_splice = Array.prototype.splice,
- _Array_indexOf = Array.prototype.indexOf,
-
- _Object_create = null, // in obj.js
- _Object_hasOwnProp = Object.hasOwnProperty,
- _Object_getOwnProp = Object.getOwnPropertyDescriptor,
- _Object_defineProperty = Object.defineProperty;
-
- // end:source /src/refs.js
-
- // source /src/coll.js
- var coll_each,
- coll_remove,
- coll_map,
- coll_indexOf,
- coll_find;
- (function(){
- coll_each = function(coll, fn, ctx){
- if (ctx == null)
- ctx = coll;
- if (coll == null)
- return coll;
-
- var imax = coll.length,
- i = 0;
- for(; i< imax; i++){
- fn.call(ctx, coll[i], i);
- }
- return ctx;
- };
- coll_indexOf = function(coll, x){
- if (coll == null)
- return -1;
- var imax = coll.length,
- i = 0;
- for(; i < imax; i++){
- if (coll[i] === x)
- return i;
- }
- return -1;
- };
- coll_remove = function(coll, x){
- var i = coll_indexOf(coll, x);
- if (i === -1)
- return false;
- coll.splice(i, 1);
- return true;
- };
- coll_map = function(coll, fn, ctx){
- var arr = new Array(coll.length);
- coll_each(coll, function(x, i){
- arr[i] = fn.call(this, x, i);
- }, ctx);
- return arr;
- };
- coll_find = function(coll, fn, ctx){
- var imax = coll.length,
- i = 0;
- for(; i < imax; i++){
- if (fn.call(ctx || coll, coll[i], i))
- return true;
- }
- return false;
- };
- }());
-
- // end:source /src/coll.js
-
- // source /src/polyfill/arr.js
- if (Array.prototype.forEach === void 0) {
- Array.prototype.forEach = function(fn, ctx){
- coll_each(this, fn, ctx);
- };
- }
- if (Array.prototype.indexOf === void 0) {
- Array.prototype.indexOf = function(x){
- return coll_indexOf(this, x);
- };
- }
-
- // end:source /src/polyfill/arr.js
- // source /src/polyfill/str.js
- if (String.prototype.trim == null){
- String.prototype.trim = function(){
- var start = -1,
- end = this.length,
- code;
- if (end === 0)
- return this;
- while(++start < end){
- code = this.charCodeAt(start);
- if (code > 32)
- break;
- }
- while(--end !== 0){
- code = this.charCodeAt(end);
- if (code > 32)
- break;
- }
- return start !== 0 && end !== length - 1
- ? this.substring(start, end + 1)
- : this;
- };
- }
-
- // end:source /src/polyfill/str.js
- // source /src/polyfill/fn.js
-
- if (Function.prototype.bind == null) {
- var _Array_slice;
- Function.prototype.bind = function(){
- if (arguments.length < 2 && typeof arguments[0] === "undefined")
- return this;
- var fn = this,
- args = _Array_slice.call(arguments),
- ctx = args.shift();
- return function() {
- return fn.apply(ctx, args.concat(_Array_slice.call(arguments)));
- };
- };
- }
-
- // end:source /src/polyfill/fn.js
-
- // source /src/is.js
- var is_Function,
- is_Array,
- is_ArrayLike,
- is_String,
- is_Object,
- is_notEmptyString,
- is_rawObject,
- is_Date,
- is_NODE,
- is_DOM;
-
- (function() {
- is_Function = function(x) {
- return typeof x === 'function';
- };
- is_Object = function(x) {
- return x != null && typeof x === 'object';
- };
- is_Array = is_ArrayLike = function(arr) {
- return arr != null
- && typeof arr === 'object'
- && typeof arr.length === 'number'
- && typeof arr.slice === 'function'
- ;
- };
- is_String = function(x) {
- return typeof x === 'string';
- };
- is_notEmptyString = function(x) {
- return typeof x === 'string' && x !== '';
- };
- is_rawObject = function(obj) {
- if (obj == null || typeof obj !== 'object')
- return false;
-
- return obj.constructor === Object;
- };
- is_Date = function(x) {
- if (x == null || typeof x !== 'object') {
- return false;
- }
- if (x.getFullYear != null && isNaN(x) === false) {
- return true;
- }
- return false;
- };
- is_DOM = typeof window !== 'undefined' && window.navigator != null;
- is_NODE = !is_DOM;
-
- }());
-
- // end:source /src/is.js
- // source /src/obj.js
- var obj_getProperty,
- obj_setProperty,
- obj_hasProperty,
- obj_extend,
- obj_extendDefaults,
- obj_extendMany,
- obj_extendProperties,
- obj_extendPropertiesDefaults,
- obj_create,
- obj_toFastProps,
- obj_defineProperty;
- (function(){
- obj_getProperty = function(obj_, path){
- if ('.' === path) // obsolete
- return obj_;
-
- var obj = obj_,
- chain = path.split('.'),
- imax = chain.length,
- i = -1;
- while ( obj != null && ++i < imax ) {
- obj = obj[chain[i]];
- }
- return obj;
- };
- obj_setProperty = function(obj_, path, val) {
- var obj = obj_,
- chain = path.split('.'),
- imax = chain.length - 1,
- i = -1,
- key;
- while ( ++i < imax ) {
- key = chain[i];
- if (obj[key] == null)
- obj[key] = {};
-
- obj = obj[key];
- }
- obj[chain[i]] = val;
- };
- obj_hasProperty = function(obj, path) {
- var x = obj_getProperty(obj, path);
- return x !== void 0;
- };
- obj_defineProperty = function(obj, path, dscr) {
- var x = obj,
- chain = path.split('.'),
- imax = chain.length - 1,
- i = -1, key;
- while (++i < imax) {
- key = chain[i];
- if (x[key] == null)
- x[key] = {};
- x = x[key];
- }
- key = chain[imax];
- if (_Object_defineProperty) {
- if (dscr.writable === void 0) dscr.writable = true;
- if (dscr.configurable === void 0) dscr.configurable = true;
- if (dscr.enumerable === void 0) dscr.enumerable = true;
- _Object_defineProperty(x, key, dscr);
- return;
- }
- x[key] = dscr.value === void 0
- ? dscr.value
- : (dscr.get && dscr.get());
- };
- obj_extend = function(a, b){
- if (b == null)
- return a || {};
-
- if (a == null)
- return obj_create(b);
-
- for(var key in b){
- a[key] = b[key];
- }
- return a;
- };
- obj_extendDefaults = function(a, b){
- if (b == null)
- return a || {};
- if (a == null)
- return obj_create(b);
-
- for(var key in b) {
- if (a[key] == null)
- a[key] = b[key];
- }
- return a;
- }
- var extendPropertiesFactory = function(overwriteProps){
- if (_Object_getOwnProp == null)
- return overwriteProps ? obj_extend : obj_extendDefaults;
-
- return function(a, b){
- if (b == null)
- return a || {};
-
- if (a == null)
- return obj_create(b);
-
- var key, descr, ownDescr;
- for(key in b){
- descr = _Object_getOwnProp(b, key);
- if (descr == null)
- continue;
- if (overwriteProps !== true) {
- ownDescr = _Object_getOwnProp(a, key);
- if (ownDescr != null) {
- continue;
- }
- }
- if (descr.hasOwnProperty('value')) {
- a[key] = descr.value;
- continue;
- }
- _Object_defineProperty(a, key, descr);
- }
- return a;
- };
- };
-
- obj_extendProperties = extendPropertiesFactory(true);
- obj_extendPropertiesDefaults = extendPropertiesFactory(false );
-
- obj_extendMany = function(a){
- var imax = arguments.length,
- i = 1;
- for(; i -1 ) {
- x = args[i];
- if (typeof x === 'function') {
- BaseCtor = wrapFn(x, BaseCtor);
- x = x.prototype;
- }
- extendDefaultsFn(Proto, x);
- }
- return createClass(wrapFn(BaseCtor, Ctor), Proto);
- };
- }
-
- function createClass(Ctor, Proto) {
- Proto.constructor = Ctor;
- Ctor.prototype = Proto;
- return Ctor;
- }
- function wrapFn(fnA, fnB) {
- if (fnA == null) {
- return fnB;
- }
- if (fnB == null) {
- return fnA;
- }
- return function(){
- var args = _Array_slice.call(arguments);
- var x = fnA.apply(this, args);
- if (x !== void 0)
- return x;
-
- return fnB.apply(this, args);
- };
- }
- }());
-
- // end:source /src/class.js
- // source /src/error.js
- var error_createClass,
- error_formatSource,
- error_formatCursor,
- error_cursor;
-
- (function(){
- error_createClass = function(name, Proto, stackSliceFrom){
- var Ctor = _createCtor(Proto, stackSliceFrom);
- Ctor.prototype = new Error;
-
- Proto.constructor = Error;
- Proto.name = name;
- obj_extend(Ctor.prototype, Proto);
- return Ctor;
- };
-
- error_formatSource = function(source, index, filename) {
- var cursor = error_cursor(source, index),
- lines = cursor[0],
- lineNum = cursor[1],
- rowNum = cursor[2],
- str = '';
- if (filename != null) {
- str += str_format(' at {0}({1}:{2})\n', filename, lineNum, rowNum);
- }
- return str + error_formatCursor(lines, lineNum, rowNum);
- };
-
- /**
- * @returns [ lines, lineNum, rowNum ]
- */
- error_cursor = function(str, index){
- var lines = str.substring(0, index).split('\n'),
- line = lines.length,
- row = index + 1 - lines.slice(0, line - 1).join('\n').length;
- if (line > 1) {
- // remote trailing newline
- row -= 1;
- }
- return [str.split('\n'), line, row];
- };
-
- (function(){
- error_formatCursor = function(lines, lineNum, rowNum) {
-
- var BEFORE = 3,
- AFTER = 2,
- i = lineNum - BEFORE,
- imax = i + BEFORE + AFTER,
- str = '';
-
- if (i < 0) i = 0;
- if (imax > lines.length) imax = lines.length;
-
- var lineNumberLength = String(imax).length,
- lineNumber;
-
- for(; i < imax; i++) {
- if (str) str += '\n';
-
- lineNumber = ensureLength(i + 1, lineNumberLength);
- str += lineNumber + '|' + lines[i];
-
- if (i + 1 === lineNum) {
- str += '\n' + repeat(' ', lineNumberLength + 1);
- str += lines[i].substring(0, rowNum - 1).replace(/[^\s]/g, ' ');
- str += '^';
- }
- }
- return str;
- };
-
- function ensureLength(num, count) {
- var str = String(num);
- while(str.length < count) {
- str += ' ';
- }
- return str;
- }
- function repeat(char_, count) {
- var str = '';
- while(--count > -1) {
- str += char_;
- }
- return str;
- }
- }());
-
- function _createCtor(Proto, stackFrom){
- var Ctor = Proto.hasOwnProperty('constructor')
- ? Proto.constructor
- : null;
-
- return function(){
- obj_defineProperty(this, 'stack', {
- value: _prepairStack(stackFrom || 3)
- });
- obj_defineProperty(this, 'message', {
- value: str_format.apply(this, arguments)
- });
- if (Ctor != null) {
- Ctor.apply(this, arguments);
- }
- };
- }
-
- function _prepairStack(sliceFrom) {
- var stack = new Error().stack;
- return stack == null ? null : stack
- .split('\n')
- .slice(sliceFrom)
- .join('\n');
- }
-
- }());
-
- // end:source /src/error.js
-
- // source /src/class/Dfr.js
- var class_Dfr;
- (function(){
- class_Dfr = function(){};
- class_Dfr.prototype = {
- _isAsync: true,
- _done: null,
- _fail: null,
- _always: null,
- _resolved: null,
- _rejected: null,
-
- defer: function(){
- this._rejected = null;
- this._resolved = null;
- return this;
- },
- isResolved: function(){
- return this._resolved != null;
- },
- isRejected: function(){
- return this._rejected != null;
- },
- isBusy: function(){
- return this._resolved == null && this._rejected == null;
- },
- resolve: function() {
- var done = this._done,
- always = this._always
- ;
-
- this._resolved = arguments;
-
- dfr_clearListeners(this);
- arr_callOnce(done, this, arguments);
- arr_callOnce(always, this, [ this ]);
-
- return this;
- },
- reject: function() {
- var fail = this._fail,
- always = this._always
- ;
-
- this._rejected = arguments;
-
- dfr_clearListeners(this);
- arr_callOnce(fail, this, arguments);
- arr_callOnce(always, this, [ this ]);
- return this;
- },
- then: function(filterSuccess, filterError){
- return this.pipe(filterSuccess, filterError);
- },
- done: function(callback) {
- if (this._rejected != null)
- return this;
- return dfr_bind(
- this,
- this._resolved,
- this._done || (this._done = []),
- callback
- );
- },
- fail: function(callback) {
- if (this._resolved != null)
- return this;
- return dfr_bind(
- this,
- this._rejected,
- this._fail || (this._fail = []),
- callback
- );
- },
- always: function(callback) {
- return dfr_bind(
- this,
- this._rejected || this._resolved,
- this._always || (this._always = []),
- callback
- );
- },
- pipe: function(mix /* ..methods */){
- var dfr;
- if (typeof mix === 'function') {
- dfr = new class_Dfr;
- var done_ = mix,
- fail_ = arguments.length > 1
- ? arguments[1]
- : null;
-
- this
- .done(delegate(dfr, 'resolve', done_))
- .fail(delegate(dfr, 'reject', fail_))
- ;
- return dfr;
- }
-
- dfr = mix;
- var imax = arguments.length,
- done = imax === 1,
- fail = imax === 1,
- i = 0, x;
- while( ++i < imax ){
- x = arguments[i];
- switch(x){
- case 'done':
- done = true;
- break;
- case 'fail':
- fail = true;
- break;
- default:
- console.error('Unsupported pipe channel', arguments[i])
- break;
- }
- }
- done && this.done(delegate(dfr, 'resolve'));
- fail && this.fail(delegate(dfr, 'reject' ));
-
- function pipe(dfr, method) {
- return function(){
- dfr[method].apply(dfr, arguments);
- };
- }
- function delegate(dfr, name, fn) {
- return function(){
- if (fn != null) {
- var override = fn.apply(this, arguments);
- if (override != null) {
- if (isDeferred(override) === true) {
- override.pipe(dfr);
- return;
- }
-
- dfr[name](override)
- return;
- }
- }
- dfr[name].apply(dfr, arguments);
- };
- }
-
- return this;
- },
- pipeCallback: function(){
- var self = this;
- return function(error){
- if (error != null) {
- self.reject(error);
- return;
- }
- var args = _Array_slice.call(arguments, 1);
- fn_apply(self.resolve, self, args);
- };
- },
- resolveDelegate: function(){
- return fn_proxy(this.resolve, this);
- },
-
- rejectDelegate: function(){
- return fn_proxy(this.reject, this);
- },
-
- };
-
- class_Dfr.run = function(fn, ctx){
- var dfr = new class_Dfr();
- if (ctx == null)
- ctx = dfr;
-
- fn.call(
- ctx
- , fn_proxy(dfr.resolve, ctx)
- , fn_proxy(dfr.reject, dfr)
- , dfr
- );
- return dfr;
- };
-
- // PRIVATE
-
- function dfr_bind(dfr, arguments_, listeners, callback){
- if (callback == null)
- return dfr;
-
- if ( arguments_ != null)
- fn_apply(callback, dfr, arguments_);
- else
- listeners.push(callback);
-
- return dfr;
- }
-
- function dfr_clearListeners(dfr) {
- dfr._done = null;
- dfr._fail = null;
- dfr._always = null;
- }
-
- function arr_callOnce(arr, ctx, args) {
- if (arr == null)
- return;
-
- var imax = arr.length,
- i = -1,
- fn;
- while ( ++i < imax ) {
- fn = arr[i];
-
- if (fn)
- fn_apply(fn, ctx, args);
- }
- arr.length = 0;
- }
- function isDeferred(x){
- if (x == null || typeof x !== 'object')
- return false;
-
- if (x instanceof class_Dfr)
- return true;
-
- return typeof x.done === 'function'
- && typeof x.fail === 'function'
- ;
- }
- }());
-
- // end:source /src/class/Dfr.js
- // source /src/class/EventEmitter.js
- var class_EventEmitter;
- (function(){
-
- class_EventEmitter = function() {
- this._listeners = {};
- };
- class_EventEmitter.prototype = {
- on: function(event, fn) {
- if (fn != null){
- (this._listeners[event] || (this._listeners[event] = [])).push(fn);
- }
- return this;
- },
- once: function(event, fn){
- if (fn != null) {
- fn._once = true;
- (this._listeners[event] || (this._listeners[event] = [])).push(fn);
- }
- return this;
- },
-
- pipe: function(event){
- var that = this,
- args;
- return function(){
- args = _Array_slice.call(arguments);
- args.unshift(event);
- fn_apply(that.trigger, that, args);
- };
- },
-
- emit: event_trigger,
- trigger: event_trigger,
-
- off: function(event, fn) {
- var listeners = this._listeners[event];
- if (listeners == null)
- return this;
-
- if (arguments.length === 1) {
- listeners.length = 0;
- return this;
- }
-
- var imax = listeners.length,
- i = -1;
- while (++i < imax) {
-
- if (listeners[i] === fn) {
- listeners.splice(i, 1);
- i--;
- imax--;
- }
-
- }
- return this;
- }
- };
-
- function event_trigger() {
- var args = _Array_slice.call(arguments),
- event = args.shift(),
- fns = this._listeners[event],
- fn, imax, i = 0;
-
- if (fns == null)
- return this;
-
- for (imax = fns.length; i < imax; i++) {
- fn = fns[i];
- fn_apply(fn, this, args);
-
- if (fn._once === true){
- fns.splice(i, 1);
- i--;
- imax--;
- }
- }
- return this;
- }
- }());
-
- // end:source /src/class/EventEmitter.js
- // source /src/class/Uri.es6
- "use strict";
-
-var class_Uri;
-(function () {
-
- class_Uri = class_create({
- protocol: null,
- value: null,
- path: null,
- file: null,
- extension: null,
-
- constructor: function constructor(uri) {
- if (uri == null) {
- return this;
- }if (util_isUri(uri)) {
- return uri.combine("");
- }uri = normalize_uri(uri);
-
- this.value = uri;
-
- parse_protocol(this);
- parse_host(this);
-
- parse_search(this);
- parse_file(this);
-
- // normilize path - "/some/path"
- this.path = normalize_pathsSlashes(this.value);
-
- if (/^[\w]+:\//.test(this.path)) {
- this.path = "/" + this.path;
- }
- return this;
- },
- cdUp: function cdUp() {
- var path = this.path;
- if (path == null || path === "" || path === "/") {
- return this;
- }
-
- // win32 - is base drive
- if (/^\/?[a-zA-Z]+:\/?$/.test(path)) {
- return this;
- }
-
- this.path = path.replace(/\/?[^\/]+\/?$/i, "");
- return this;
- },
- /**
- * '/path' - relative to host
- * '../path', 'path','./path' - relative to current path
- */
- combine: function combine(path) {
-
- if (util_isUri(path)) {
- path = path.toString();
- }
-
- if (!path) {
- return util_clone(this);
- }
-
- if (rgx_win32Drive.test(path)) {
- return new class_Uri(path);
- }
-
- var uri = util_clone(this);
-
- uri.value = path;
-
- parse_search(uri);
- parse_file(uri);
-
- if (!uri.value) {
- return uri;
- }
-
- path = uri.value.replace(/^\.\//i, "");
-
- if (path[0] === "/") {
- uri.path = path;
- return uri;
- }
-
- while (/^(\.\.\/?)/ig.test(path)) {
- uri.cdUp();
- path = path.substring(3);
- }
-
- uri.path = normalize_pathsSlashes(util_combinePathes(uri.path, path));
-
- return uri;
- },
- toString: function toString() {
- var protocol = this.protocol ? this.protocol + "://" : "";
- var path = util_combinePathes(this.host, this.path, this.file) + (this.search || "");
- var str = protocol + path;
-
- if (!(this.file || this.search)) {
- str += "/";
- }
- return str;
- },
- toPathAndQuery: function toPathAndQuery() {
- return util_combinePathes(this.path, this.file) + (this.search || "");
- },
- /**
- * @return Current Uri Path{String} that is relative to @arg1 Uri
- */
- toRelativeString: function toRelativeString(uri) {
- if (typeof uri === "string") uri = new class_Uri(uri);
-
- if (this.path.indexOf(uri.path) === 0) {
- // host folder
- var p = this.path ? this.path.replace(uri.path, "") : "";
- if (p[0] === "/") p = p.substring(1);
-
- return util_combinePathes(p, this.file) + (this.search || "");
- }
-
- // sub folder
- var current = this.path.split("/"),
- relative = uri.path.split("/"),
- commonpath = "",
- i = 0,
- length = Math.min(current.length, relative.length);
-
- for (; i < length; i++) {
- if (current[i] === relative[i]) continue;
-
- break;
- }
-
- if (i > 0) commonpath = current.splice(0, i).join("/");
-
- if (commonpath) {
- var sub = "",
- path = uri.path,
- forward;
- while (path) {
- if (this.path.indexOf(path) === 0) {
- forward = this.path.replace(path, "");
- break;
- }
- path = path.replace(/\/?[^\/]+\/?$/i, "");
- sub += "../";
- }
- return util_combinePathes(sub, forward, this.file);
- }
-
- return this.toString();
- },
-
- toLocalFile: function toLocalFile() {
- var path = util_combinePathes(this.host, this.path, this.file);
-
- return util_win32Path(path);
- },
- toLocalDir: function toLocalDir() {
- var path = util_combinePathes(this.host, this.path, "/");
-
- return util_win32Path(path);
- },
- toDir: function toDir() {
- var str = this.protocol ? this.protocol + "://" : "";
-
- return str + util_combinePathes(this.host, this.path, "/");
- },
- isRelative: function isRelative() {
- return !(this.protocol || this.host);
- },
- getName: function getName() {
- return this.file.replace("." + this.extension, "");
- }
- });
-
- var rgx_protocol = /^([a-zA-Z]+):\/\//,
- rgx_extension = /\.([\w\d]+)$/i,
- rgx_win32Drive = /(^\/?\w{1}:)(\/|$)/,
- rgx_fileWithExt = /([^\/]+(\.[\w\d]+)?)$/i;
-
- function util_isUri(object) {
- return object && typeof object === "object" && typeof object.combine === "function";
- }
-
- function util_combinePathes() {
- var args = arguments,
- str = "";
- for (var i = 0, x, imax = arguments.length; i < imax; i++) {
- x = arguments[i];
- if (!x) continue;
-
- if (!str) {
- str = x;
- continue;
- }
-
- if (str[str.length - 1] !== "/") str += "/";
-
- str += x[0] === "/" ? x.substring(1) : x;
- }
- return str;
- }
-
- function normalize_pathsSlashes(str) {
-
- if (str[str.length - 1] === "/") {
- return str.substring(0, str.length - 1);
- }
- return str;
- }
-
- function util_clone(source) {
- var uri = new class_Uri(),
- key;
- for (key in source) {
- if (typeof source[key] === "string") {
- uri[key] = source[key];
- }
- }
- return uri;
- }
-
- function normalize_uri(str) {
- return str.replace(/\\/g, "/").replace(/^\.\//, "")
-
- // win32 drive path
- .replace(/^(\w+):\/([^\/])/, "/$1:/$2");
- }
-
- function util_win32Path(path) {
- if (rgx_win32Drive.test(path) && path[0] === "/") {
- return path.substring(1);
- }
- return path;
- }
-
- function parse_protocol(obj) {
- var match = rgx_protocol.exec(obj.value);
-
- if (match == null && obj.value[0] === "/") {
- obj.protocol = "file";
- }
-
- if (match == null) {
- return;
- }obj.protocol = match[1];
- obj.value = obj.value.substring(match[0].length);
- }
-
- function parse_host(obj) {
- if (obj.protocol == null) {
- return;
- }if (obj.protocol === "file") {
- var match = rgx_win32Drive.exec(obj.value);
- if (match) {
- obj.host = match[1];
- obj.value = obj.value.substring(obj.host.length);
- }
- return;
- }
-
- var pathStart = obj.value.indexOf("/", 2);
-
- obj.host = ~pathStart ? obj.value.substring(0, pathStart) : obj.value;
-
- obj.value = obj.value.replace(obj.host, "");
- }
-
- function parse_search(obj) {
- var question = obj.value.indexOf("?");
- if (question === -1) {
- return;
- }obj.search = obj.value.substring(question);
- obj.value = obj.value.substring(0, question);
- }
-
- function parse_file(obj) {
- var match = rgx_fileWithExt.exec(obj.value),
- file = match == null ? null : match[1];
-
- if (file == null) {
- return;
- }
- obj.file = file;
- obj.value = obj.value.substring(0, obj.value.length - file.length);
- obj.value = normalize_pathsSlashes(obj.value);
-
- match = rgx_extension.exec(file);
- obj.extension = match == null ? null : match[1];
- }
-
- class_Uri.combinePathes = util_combinePathes;
- class_Uri.combine = util_combinePathes;
-})();
-/*args*/
-//# sourceMappingURL=Uri.es6.map
- // end:source /src/class/Uri.es6
- // end:source /ref-utils/lib/utils.embed.js
-
- // source scope-vars
- var __rgxEscapedChar = {
- "'": /\\'/g,
- '"': /\\"/g,
- '{': /\\\{/g,
- '>': /\\>/g,
- ';': /\\>/g
- };
-
- /**
- * Configuration Options
- * @type {object}
- * @typedef Configuration
- */
- var __cfg = {
- /**
- * Relevant for NodeJS only. Disable/Enable compo caching.
- * @default true
- */
- allowCache: true,
- /**
- * Style and Script preprocessors
- * @type {object}
- * @memberOf Configuration
- */
- preprocessor: {
- /**
- * Transform style before using in `style` tag
- * @type {function}
- * @param {string} style
- * @returns {string}
- * @memberOf Configuration
- */
- style : null,
- /**
- * Transform script before using in `function,script,event,slot` tags
- * @type {function}
- * @param {string} source
- * @returns {string}
- * @memberOf Configuration
- */
- script: null
- },
- /**
- * Base path for modules
- * @default null
- * @memberOf Configuration
- */
- base: null,
- modules: 'default',
- /**
- * Define custom function for getting files content by path
- * @param {string} path
- * @returns {Promise}
- * @memberOf Configuration
- */
- getFile: null,
- /**
- * Define custom function for getting script
- * @param {string} path
- * @returns {Promise} Fulfill with exports
- * @memberOf Configuration
- */
- getScript: null,
- /**
- * Define custom function to build/combine styles
- * @param {string} path
- * @param {object} options
- * @returns {Promise} Fulfill with {string} content
- * @memberOf Configuration
- */
- buildStyle: null,
- /**
- * Define custom function to build/combine scripts
- * @param {string} path
- * @param {object} options
- * @returns {Promise} Fulfill with {string} content
- * @memberOf Configuration
- */
- buildScript: null,
- };
- // end:source scope-vars
-
- // source util/
- // source ./util.js
-
-
- // end:source ./util.js
- // source ./attr.js
- var attr_extend,
- attr_first;
-
- (function(){
- attr_extend = function (a, b) {
- if (a == null) {
- return b == null
- ? {}
- : obj_create(b);
- }
-
- if (b == null)
- return a;
-
- var key;
- for(key in b) {
- if ('class' === key && typeof a[key] === 'string') {
- a[key] += ' ' + b[key];
- continue;
- }
- a[key] = b[key];
- }
- return a;
- };
- attr_first = function(attr){
- for (var key in attr) return key;
- return null;
- };
- }());
-
- // end:source ./attr.js
- // source ./array.js
- var arr_pushMany;
-
- (function(){
- arr_pushMany = function(arr, arrSource){
- if (arrSource == null || arr == null)
- return;
-
- var il = arr.length,
- jl = arrSource.length,
- j = -1
- ;
- while( ++j < jl ){
- arr[il + j] = arrSource[j];
- }
- };
- }());
- // end:source ./array.js
- // source ./object.js
- var obj_getPropertyEx,
- obj_toDictionary;
- (function(){
- obj_getPropertyEx = function(path, model, ctx, ctr){
- if (path === '.')
- return model;
-
- var props = path.split('.'),
- imax = props.length,
- key = props[0]
- ;
-
- if ('$c' === key) {
- reporter_deprecated('accessor.compo', 'Use `$` instead of `$c`');
- key = '$';
- }
- if ('$u' === key) {
- reporter_deprecated('accessor.util', 'Use `_` instead of `$u`');
- key = '_';
- }
- if ('$' === key) {
- return getProperty_(ctr, props, 1, imax);
- }
- if ('$a' === key) {
- return getProperty_(ctr && ctr.attr, props, 1, imax);
- }
- if ('_' === key) {
- return getProperty_(customUtil_$utils, props, 1, imax);
- }
- if ('$ctx' === key) {
- return getProperty_(ctx, props, 1, imax);
- }
- if ('$scope' === key) {
- return getFromScope_(ctr, props, 1, imax);
- }
-
- var x = getProperty_(model, props, 0, imax);
- if (x != null) {
- return x;
- }
-
- return getFromScope_(ctr, props, 0, imax);
- };
-
- obj_toDictionary = function(obj){
- var array = [],
- i = 0,
- key
- ;
- for(key in obj){
- array[i++] = {
- key: key,
- value: obj[key]
- };
- }
- return array;
- };
-
- // = private
-
- function getProperty_(obj, props, startIndex, imax) {
- var i = startIndex,
- val = obj;
- while(i < imax && val != null){
- val = val[props[i]];
- i++;
- }
- return val;
- }
-
- function getFromScope_(ctr, props, startIndex, imax) {
- while (ctr != null){
- var scope = ctr.scope;
- if (scope != null) {
- var x = getProperty_(scope, props, startIndex, imax);
- if (x != null)
- return x;
- }
- ctr = ctr.parent;
- }
- return null;
- }
- }());
-
- // end:source ./object.js
- // source ./listeners.js
- var listeners_on,
- listeners_off,
- listeners_emit;
- (function(){
- /**
- * Bind listeners to some system events:
- * - `error` Any parser or render error
- * - `compoCreated` Each time new component is created
- * - `config` Each time configuration is changed via `config` fn
- * @param {string} eveny
- * @param {function} cb
- * @memberOf mask
- * @method on
- */
- listeners_on = function(event, fn) {
- (bin[event] || (bin[event] = [])).push(fn);
- };
- /**
- * Unbind listener
- * - `error` Any parser or render error
- * - `compoCreated` Each time new component is created
- * @param {string} eveny
- * @param {function} [cb]
- * @memberOf mask
- * @method on
- */
- listeners_off = function(event, fn){
- if (fn == null) {
- bin[event] = [];
- return;
- }
- arr_remove(bin[event], fn);
- };
- listeners_emit = function(event){
- var fns = bin[event];
- if (fns == null) {
- return false;
- }
- var imax = fns.length,
- i = -1,
- args = _Array_slice.call(arguments, 1)
- ;
- if (imax === 0) {
- return false;
- }
- while ( ++i < imax) {
- fns[i].apply(null, args);
- }
- return true;
- };
-
- // === private
-
- var bin = {
- compoCreated: null,
- error: null
- };
- }());
- // end:source ./listeners.js
- // source ./reporters.js
- var throw_,
- parser_error,
- parser_warn,
- error_,
- error_withSource,
- error_withNode,
- warn_,
- warn_withSource,
- warn_withNode,
-
- log,
- log_warn,
- log_error,
- reporter_createErrorNode,
- reporter_deprecated;
-
- (function(){
- (function () {
-
- if (typeof console === 'undefined') {
- log = log_warn = log_error = function(){};
- return;
- }
- var bind = Function.prototype.bind;
- log = bind.call(console.warn , console);
- log_warn = bind.call(console.warn , console, 'MaskJS [Warn] :');
- log_error = bind.call(console.error, console, 'MaskJS [Error] :');
- }());
-
- var STACK_SLICE = 4;
- var MaskError = error_createClass('MaskError', {}, STACK_SLICE);
- var MaskWarn = error_createClass('MaskWarn', {}, STACK_SLICE);
-
-
- throw_ = function(error){
- log_error(error);
- listeners_emit('error', error);
- };
-
- error_withSource = delegate_withSource(MaskError, 'error');
- error_withNode = delegate_withNode (MaskError, 'error');
-
- warn_withSource = delegate_withSource(MaskWarn, 'warn');
- warn_withNode = delegate_withNode (MaskWarn, 'warn');
-
- parser_error = delegate_parserReporter(MaskError, 'error');
- parser_warn = delegate_parserReporter(MaskWarn, 'warn');
-
- reporter_createErrorNode = function(message){
- return parser_parse(
- 'div style="background:red;color:white;">tt>"""' + message + '"""'
- );
- };
-
- (function(){
- reporter_deprecated = function(id, message){
- if (_notified[id] !== void 0) {
- return;
- }
- _notified[id] = 1;
- log_warn('[deprecated]', message);
- };
- var _notified = {};
- }());
-
- function delegate_parserReporter(Ctor, type) {
- return function(str, source, index, token, state, file) {
- var error = new Ctor(str);
- var tokenMsg = formatToken(token);
- if (tokenMsg) {
- error.message += tokenMsg;
- }
- var stateMsg = formatState(state);
- if (stateMsg) {
- error.message += stateMsg;
- }
- var cursorMsg = error_formatSource(source, index, file);
- if (cursorMsg) {
- error.message += '\n' + cursorMsg;
- }
- report(error, 'error');
- };
- }
- function delegate_withSource(Ctor, type){
- return function(str, source, index, file){
- var error = new Ctor(str);
- error.message = '\n' + error_formatSource(source, index, file);
- report(error, type);
- };
- }
- function delegate_withNode(Ctor, type){
- return function(str, node){
- var error = new Ctor(str);
- error.message = error.message
- + '\n'
- + _getNodeStack(node);
-
- report(error, type);
- };
- }
-
- function _getNodeStack(node){
- var stack = [ node ];
-
- var parent = node.parent;
- while (parent != null) {
- stack.unshift(parent);
- parent = parent.parent;
- }
- var str = '';
- var root = stack[0];
- if (root !== node && is_String(root.source) && node.sourceIndex > -1) {
- str += error_formatSource(root.source, node.sourceIndex, root.filename) + '\n';
- }
-
- str += ' at ' + stack
- .map(function(x){
- return x.tagName;
- })
- .join(' > ');
-
- return str;
- }
-
- function report(error, type) {
- if (listeners_emit(type, error)) {
- return;
- }
- var fn = type === 'error' ? log_error : log_warn;
- fn(error.message);
- fn('\n' + error.stack);
- }
-
- function formatToken(token){
- if (token == null)
- return '';
-
- if (typeof token === 'number')
- token = String.fromCharCode(token);
-
- return ' Invalid token: `'+ token + '`';
- }
-
- function formatState(state){
- var states = {
- '2': 'tag',
- '3': 'tag',
- '5': 'attribute key',
- '6': 'attribute value',
- '8': 'literal',
- 'var': 'VarStatement',
- 'expr': 'Expression'
- };
- if (state == null || states[state] == null)
- return '';
-
- return ' in `' + states[state] + '`';
- }
-
- }());
- // end:source ./reporters.js
- // source ./path.js
- var path_getDir,
- path_getFile,
- path_getExtension,
- path_resolveCurrent,
- path_normalize,
- path_resolveUrl,
- path_combine,
- path_isRelative,
- path_toRelative,
- path_appendQuery,
- path_toLocalFile
- ;
- (function(){
- var isWeb = true;
-
- path_getDir = function(path) {
- return path.substring(0, path.lastIndexOf('/') + 1);
- };
- path_getFile = function(path) {
- path = path
- .replace('file://', '')
- .replace(/\\/g, '/')
- .replace(/\?[^\n]+$/, '');
-
- if (/^\/\w+:\/[^\/]/i.test(path)){
- // win32 drive
- return path.substring(1);
- }
- return path;
- };
- path_getExtension = function(path) {
- var query = path.indexOf('?');
- if (query !== -1) {
- path = path.substring(0, query);
- }
- var match = rgx_EXT.exec(path);
- return match == null ? '' : match[1];
- };
-
- path_appendQuery = function(path, key, val){
- var conjunctor = path.indexOf('?') === -1 ? '?' : '&';
- return path + conjunctor + key + '=' + val;
- };
-
- (function(){
- var current_;
-
- // if (BROWSER)
- path_resolveCurrent = function(){
- if (current_ != null) return current_;
-
- var fn = 'baseURI' in global.document
- ? fromBase
- : fromLocation;
- return (current_ = path_sliceFilename(fn()));
- };
- function fromBase() {
- var base = global.document.baseURI;
- if (base.substring(0, 5) === 'file:') {
- return base;
- }
- return base.replace(global.location.origin, '');
- }
- function fromLocation() {
- return global.location.pathname;
- }
- // endif
-
-
- }());
-
-
- path_normalize = function(path) {
- var path_ = path
- .replace(/\\/g, '/')
- // remove double slashes, but not near protocol
- .replace(/([^:\/])\/{2,}/g, '$1/')
- // './xx' to relative string
- .replace(/^\.\//, '')
- // join 'xx/./xx'
- .replace(/\/\.\//g, '/')
- ;
- return path_collapse(path_);
- };
- path_resolveUrl = function(path, base) {
- var url = path_normalize(path);
- if (path_isRelative(url)) {
- return path_normalize(path_combine(base || path_resolveCurrent(), url));
- }
- if (rgx_PROTOCOL.test(url))
- return url;
-
- if (url.charCodeAt(0) === 47 /*/*/) {
- if (__cfg.base) {
- return path_combine(__cfg.base, url);
- }
- }
- return url;
- };
- path_isRelative = function(path) {
- var c = path.charCodeAt(0);
- switch (c) {
- case 47:
- // /
- return false;
- case 102:
- case 104:
- // f || h
- return rgx_PROTOCOL.test(path) === false;
- }
- return true;
- };
- path_toRelative = function(path, anchor, base){
- var path_ = path_resolveUrl(path_normalize(path), base),
- absolute_ = path_resolveUrl(path_normalize(anchor), base);
-
- if (path_getExtension(absolute_) !== '') {
- absolute_ = path_getDir(absolute_);
- }
- absolute_ = path_combine(absolute_, '/');
- if (path_.toUpperCase().indexOf(absolute_.toUpperCase()) === 0) {
- return path_.substring(absolute_.length);
- }
- return path;
- };
-
- path_combine = function() {
- var out = '',
- imax = arguments.length,
- i = -1, x;
- while ( ++i < imax ){
- x = arguments[i];
- if (!x) continue;
-
- x = path_normalize(x);
- if (out === '') {
- out = x;
- continue;
- }
- if (out[out.length - 1] !== '/') {
- out += '/'
- }
- if (x[0] === '/') {
- x = x.substring(1);
- }
- out += x;
- }
- return path_collapse(out);
- };
-
-
-
- var rgx_PROTOCOL = /^(file|https?):/i,
- rgx_SUB_DIR = /[^\/\.]+\/\.\.\//,
- rgx_FILENAME = /\/[^\/]+\.\w+(\?.*)?(#.*)?$/,
- rgx_EXT = /\.(\w+)$/,
- rgx_win32Drive = /(^\/?\w{1}:)(\/|$)/
- ;
-
- function path_win32Normalize (path){
- path = path_normalize(path);
- if (path.substring(0, 5) === 'file:')
- return path;
-
- return 'file:///' + path;
- }
-
- function path_collapse(url_) {
- var url = url_;
- while (rgx_SUB_DIR.test(url)) {
- url = url.replace(rgx_SUB_DIR, '');
- }
- return url;
- }
- function path_ensureTrailingSlash(path) {
- if (path.charCodeAt(path.length - 1) === 47 /* / */)
- return path;
-
- return path + '/';
- }
- function path_sliceFilename(path) {
- return path_ensureTrailingSlash(path.replace(rgx_FILENAME, ''));
- }
-
- }());
-
-
- // end:source ./path.js
- // source ./resource/file.js
- var file_get,
- file_getScript,
- file_getStyle,
- file_getJson;
-
- (function(){
- file_get = function(path, ctr){
- return get(xhr_get, path, ctr);
- };
- file_getScript = function(path, ctr){
- return get(script_get, path, ctr);
- };
- file_getStyle = function(path, ctr){
- return get(style_get, path, ctr);
- };
- file_getJson = function(path, ctr){
- return get(json_get, path, ctr);
- };
-
- function get(fn, path, ctr) {
- path = path_resolveUrl(path, ctr);
-
- var dfr = Cache[path];
- if (dfr !== void 0) {
- return dfr;
- }
- dfr = new class_Dfr;
- fn(path, dfr.pipeCallback());
- return dfr;
- }
-
- var Cache = {};
-
-
- // source transports/json
- var json_get;
- (function(){
- json_get = function(path, cb){
- xhr_get(path, function(error, str){
- if (error) {
- cb(error);
- return;
- }
- var json;
- try {
- json = JSON.parse(str);
- } catch (error) {
- cb('JSON error: ' + String(error));
- return;
- }
- cb(null, json);
- })
- };
- }());
- // end:source transports/json
-
- // if BROWSER
- // source transports/script
- var script_get;
- (function(){
- script_get = function(path, cb){
- var res = new Resource(path)
- .done(function(exports){
- cb(null, exports);
- })
- .fail(function(err){
- cb(err);
- });
-
- ScriptStack.load(res);
- };
-
- var Resource = class_create(class_Dfr, {
- exports: null,
- url: null,
- state: 0,
- constructor: function(url){
- this.url = url;
- },
- load: function(){
- if (this.state !== 0) {
- return this;
- }
- this.state = 1;
- global.module = {};
-
- var self = this;
- embedScript(this.url, function(event){
- self.state = 4;
- if (event && event.type === 'error') {
- self.reject(event);
- return;
- }
- self.resolve(self.exports = global.module.exports);
- });
- return this;
- }
- });
- var ScriptStack;
- (function() {
- ScriptStack = {
- load: function(resource) {
- _stack.push(resource);
- process();
- }
- };
-
- var _stack = [];
-
- function process() {
- if (_stack.length === 0)
- return;
-
- var res = _stack[0];
- if (res.state !== 0)
- return;
-
- res.load().always(function(){
- _stack.shift();
- process();
- });
- }
- })();
-
- var embedScript;
- (function(){
- embedScript = function (url, callback) {
- var tag = document.createElement('script');
- tag.type = 'text/javascript';
- tag.src = url;
- if ('onreadystatechange' in tag) {
- tag.onreadystatechange = function() {
- (this.readyState === 'complete' || this.readyState === 'loaded') && callback();
- };
- } else {
- tag.onload = tag.onerror = callback;
- }
- if (_head === void 0) {
- _head = document.getElementsByTagName('head')[0];
- }
- _head.appendChild(tag);
- };
- var _head;
- }());
-
-
- }());
- // end:source transports/script
- // source transports/style
- var style_get;
- (function(){
- style_get = function(path, cb){
- embedStyle(path);
- // do not wait for the load event
- cb();
- };
-
- var embedStyle;
- (function(){
- embedStyle = function (url, callback) {
- var tag = document.createElement('link');
- tag.rel = 'stylesheet';
- tag.href = url;
- if ('onreadystatechange' in tag) {
- tag.onreadystatechange = function() {
- (this.readyState === 'complete' || this.readyState === 'loaded') && callback();
- };
- } else {
- tag.onload = tag.onerror = callback;
- }
- if (_head === void 0) {
- _head = document.getElementsByTagName('head')[0];
- }
- _head.appendChild(tag);
- };
- var _head;
- }());
-
-
- }());
- // end:source transports/style
- // source transports/xhr
- var xhr_get;
- (function(){
- xhr_get = function(path, cb){
- var xhr = new XMLHttpRequest();
- xhr.onreadystatechange = function() {
- if (xhr.readyState !== 4)
- return;
-
- var res = xhr.responseText,
- status = xhr.status,
- err, errMsg;
- if (status !== 0 && status !== 200) {
- errMsg = res || xhr.statusText;
- }
- if (status === 0 && res === '') {
- errMsg = res || xhr.statusText || 'File is not accessable';
- }
- if (errMsg != null) {
- err = {
- status: status,
- content: errMsg
- };
- log_warn('File error', path, status);
- }
- cb(err, res);
- };
- xhr.open('GET', path, true);
- xhr.send();
- };
- }());
- // end:source transports/xhr
- // endif
-
-
-
- }());
- // end:source ./resource/file.js
-
- // end:source util/
- // source api/
- //source config
- /**
- * Get or Set configuration settings
- * - 1 `(name)`
- * - 2 `(name, value)`
- * - 3 `(object)`
- * @see @{link MaskOptions} for all options
- * @memberOf mask
- * @method config
- */
- function mask_config () {
- var args = arguments,
- length = args.length
- if (length === 0) {
- return __cfg;
- }
- if (length === 1) {
- var x = args[0]
- if (is_Object(x)) {
- obj_extend(__cfg, x);
- listeners_emit('config', x);
- return;
- }
- if (is_String(x)) {
- return obj_getProperty(__cfg, x);
- }
- }
- if (length === 2) {
- var prop = args[0];
- if (obj_hasProperty(__cfg, prop) === false) {
- log_warn('Unknown configuration property', prop);
- }
- var x = {};
- obj_setProperty(x , prop, args[1]);
- obj_setProperty(__cfg, prop, args[1]);
- listeners_emit('config', x);
- return;
- }
- }
- //end:source config
- // end:source api/
- // source custom/
- var custom_Utils,
- custom_Statements,
- custom_Attributes,
- custom_Tags,
- custom_Tags_global,
- custom_Tags_defs,
-
- custom_Parsers,
- custom_Parsers_Transform,
- custom_Optimizers,
-
- customUtil_get,
- customUtil_$utils,
- customUtil_register,
-
- customTag_get,
- customTag_getAll,
- customTag_register,
- customTag_registerScoped,
- customTag_registerFromTemplate,
- customTag_registerResolver,
- customTag_Resolver,
- customTag_Compo_getHandler,
- customTag_define,
- customTag_Base,
-
- custom_optimize,
-
- customStatement_register,
- customStatement_get,
-
- customAttr_register,
- customAttr_get
- ;
-
- (function(){
-
- // source ./repositories.js
- (function(){
- var _HtmlTags = {
- /*
- * Most common html tags
- * http://jsperf.com/not-in-vs-null/3
- */
- a: null,
- abbr: null,
- article: null,
- aside: null,
- audio: null,
- b: null,
- big: null,
- blockquote: null,
- br: null,
- button: null,
- canvas: null,
- datalist: null,
- details: null,
- div: null,
- em: null,
- fieldset: null,
- footer: null,
- form: null,
- h1: null,
- h2: null,
- h3: null,
- h4: null,
- h5: null,
- h6: null,
- header: null,
- i: null,
- img: null,
- input: null,
- label: null,
- legend: null,
- li: null,
- menu: null,
- nav: null,
- ol: null,
- option: null,
- p: null,
- pre: null,
- section: null,
- select: null,
- small: null,
- span: null,
- strong: null,
- svg: null,
- table: null,
- tbody: null,
- td: null,
- textarea: null,
- tfoot: null,
- th: null,
- thead: null,
- tr: null,
- tt: null,
- ul: null,
- video: null,
- };
- var _HtmlAttr = {
- 'class' : null,
- 'id' : null,
- 'style' : null,
- 'name' : null,
- 'type' : null,
- 'value' : null,
- 'required': null,
- 'disabled': null,
- };
-
- custom_Utils = {
- expression: function(value, model, ctx, element, ctr){
- return expression_eval(value, model, ctx, ctr);
- },
- };
- custom_Optimizers = {};
- custom_Statements = {};
- custom_Attributes = obj_extend({}, _HtmlAttr);
- custom_Tags = obj_extend({}, _HtmlTags);
- custom_Tags_global = obj_extend({}, _HtmlTags);
- custom_Parsers = obj_extend({}, _HtmlTags);
- custom_Parsers_Transform = obj_extend({}, _HtmlTags);
-
- // use on server to define reserved tags and its meta info
- custom_Tags_defs = {};
- }());
- // end:source ./repositories.js
- // source ./tag.js
- (function(){
- /**
- * Get Components constructor from the global repository or the scope
- * @param {string} name
- * @param {object} [component] - pass a component to look in its scope
- * @returns {IComponent}
- * @memberOf mask
- * @method getHandler
- */
- customTag_get = function(name, ctr) {
- if (arguments.length === 0) {
- reporter_deprecated('getHandler.all', 'Use `mask.getHandlers` to get all components (also scoped)');
- return customTag_getAll();
- }
- var Ctor = custom_Tags[name];
- if (Ctor == null) {
- return null;
- }
- if (Ctor !== Resolver) {
- return Ctor;
- }
-
- var ctr_ = is_Function(ctr) ? ctr.prototype : ctr;
- while(ctr_ != null) {
- if (is_Function(ctr_.getHandler)) {
- Ctor = ctr_.getHandler(name);
- if (Ctor != null) {
- return Ctor;
- }
- }
- ctr_ = ctr_.parent;
- }
- return custom_Tags_global[name];
- };
- /**
- * Get all components constructors from the global repository and/or the scope
- * @param {object} [component] - pass a component to look also in its scope
- * @returns {object} All components in an object `{name: Ctor}`
- * @memberOf mask
- * @method getHandlers
- */
- customTag_getAll = function(ctr) {
- if (ctr == null) {
- return custom_Tags;
- }
-
- var obj = {},
- ctr_ = ctr, x;
- while (ctr_ != null) {
- x = null;
- if (is_Function(ctr_.getHandlers)) {
- x = ctr_.getHandlers();
- } else {
- x = ctr_.__handlers__;
- }
- if (x != null) {
- obj = obj_extendDefaults(obj, x);
- }
- ctr_ = ctr_.parent;
- }
- for (var key in custom_Tags) {
- x = custom_Tags[key];
- if (x == null || x === Resolver) {
- continue;
- }
- if (obj[key] == null) {
- obj[key] = x;
- }
- }
- return obj;
- };
- /**
- * Register a component
- * @param {string} name
- * @param {object|IComponent} component
- * @param {object} component - Component static definition
- * @param {IComponent} component - Components constructor
- * @returns {void}
- * @memberOf mask
- * @method registerHandler
- */
- customTag_register = function(mix, Handler){
- if (typeof mix !== 'string' && arguments.length === 3) {
- customTag_registerScoped.apply(this, arguments);
- return;
- }
- var Current = custom_Tags[mix],
- Ctor = compo_ensureCtor(Handler),
- Repo = custom_Tags[mix] === Resolver
- ? custom_Tags_global
- : custom_Tags
- ;
- Repo[mix] = Ctor;
-
- //> make fast properties
- obj_toFastProps(custom_Tags);
- };
- /**
- * Register components from a template
- * @param {string} template - Mask template
- * @param {object|IComponent} [component] - Register in the components scope
- * @param {string} [path] - Optionally define the path for the template
- * @returns {Promise} - Fullfills when all submodules are resolved and components are registerd
- * @memberOf mask
- * @method registerFromTemplate
- */
- customTag_registerFromTemplate = function(mix, Ctr, path){
- var dfr = new class_Dfr;
- new Module
- .ModuleMask(path || '')
- .preprocess_(mix, function(error, exports){
- if (error) {
- return dfr.reject(error);
- }
- var store = exports.__handlers__;
- for (var key in store) {
- if (exports[key] != null) {
- // is global
- customTag_register(key, store[key]);
- continue;
- }
- customTag_registerScoped(Ctr, key, store[key]);
- }
- dfr.resolve(exports.__handlers__);
- });
-
- return dfr;
- };
- /**
- * Register a component
- * @param {object|IComponent} scopedComponent - Use components scope
- * @param {string} name - Name of the component
- * @param {object|IComponent} component - Components definition
- * @returns {void}
- * @memberOf mask
- * @method registerScoped
- */
- customTag_registerScoped = function(Ctx, name, Handler) {
- if (Ctx == null) {
- // Use global
- customTag_register(name, Handler);
- return;
- }
- customTag_registerResolver(name);
- var obj = is_Function(Ctx) ? Ctx.prototype : Ctx;
- var map = obj.__handlers__;
- if (map == null) {
- map = obj.__handlers__ = {};
- }
- map[name] = compo_ensureCtor(Handler);
-
- if (obj.getHandler == null) {
- obj.getHandler = customTag_Compo_getHandler;
- }
- };
-
- /** Variations:
- * - 1. (template)
- * - 2. (scopedCompoName, template)
- * - 3. (scopedCtr, template)
- * - 4. (name, Ctor)
- * - 5. (scopedCtr, name, Ctor)
- * - 6. (scopedCompoName, name, Ctor)
- */
-
- function is_Compo(val) {
- return is_Object(val) || is_Function(val);
- }
-
- /**
- * Universal component definition, which covers all the cases: simple, scoped, template
- * - 1. (template)
- * - 2. (scopedCompoName, template)
- * - 3. (scopedCtr, template)
- * - 4. (name, Ctor)
- * - 5. (scopedCtr, name, Ctor)
- * - 6. (scopedCompoName, name, Ctor)
- * @returns {void|Promise}
- * @memberOf mask
- * @method define
- */
- customTag_define = fn_createByPattern([{
- pattern: [is_String],
- handler: function(template) {
- return customTag_registerFromTemplate(template);
- }
- }, {
- pattern: [is_String, is_String],
- handler: function(name, template) {
- var Scope = customTag_get(name);
- return customTag_registerFromTemplate(template, Scope);
- }
- }, {
- pattern: [is_Compo, is_String],
- handler: function(Scope, template) {
- return customTag_registerFromTemplate(template, Scope);
- }
- }, {
- pattern: [is_String, is_Compo],
- handler: function(name, Ctor) {
- return customTag_register(name, Ctor);
- }
- }, {
- pattern: [is_Compo, is_String, is_Compo],
- handler: function(Scope, name, Ctor) {
- customTag_registerScoped(Scope, name, Ctor);
- }
- }, {
- pattern: [is_String, is_String, is_Compo],
- handler: function(scopeName, name, Ctor) {
- var Scope = customTag_get(scopeName);
- return customTag_registerScoped(Scope, name, Ctor);
- }
- }
- ]);
-
-
- customTag_registerResolver = function(name){
- var Ctor = custom_Tags[name];
- if (Ctor === Resolver)
- return;
-
- if (Ctor != null)
- custom_Tags_global[name] = Ctor;
-
- custom_Tags[name] = Resolver;
-
- //> make fast properties
- obj_toFastProps(custom_Tags);
- };
-
- customTag_Compo_getHandler = function (name) {
- var map = this.__handlers__;
- return map == null ? null : map[name];
- };
-
- customTag_Base = {
- async: false,
- attr: null,
- await: null,
- compoName: null,
- components: null,
- expression: null,
- ID: null,
- meta: null,
- model: null,
- nodes: null,
- parent: null,
- render: null,
- renderEnd: null,
- renderStart: null,
- tagName: null,
- type: null,
- };
-
- var Resolver;
- (function(){
- customTag_Resolver = Resolver = function (node, model, ctx, container, ctr) {
- var Mix = customTag_get(node.tagName, ctr);
- if (Mix != null) {
- if (is_Function(Mix) === false) {
- return obj_create(Mix);
- }
- return new Mix(node, model, ctx, container, ctr);
- }
- error_withNode('Component not found: ' + node.tagName, node);
- return null;
- };
- }());
-
- function wrapStatic(proto) {
- function Ctor(node, parent) {
- this.ID = null;
- this.tagName = node.tagName;
- this.attr = obj_create(node.attr);
- this.expression = node.expression;
- this.nodes = node.nodes;
- this.nextSibling = node.nextSibling;
- this.parent = parent;
- this.components = null;
- }
- Ctor.prototype = proto;
- return Ctor;
- }
-
-
-
- function compo_ensureCtor(Handler) {
- if (is_Object(Handler)) {
- //> static
- Handler.__Ctor = wrapStatic(Handler);
- }
- return Handler;
- }
-
- }());
- // end:source ./tag.js
- // source ./attribute.js
- /**
- * Register an attribute handler. Any changes can be made to:
- * - maskNode's template
- * - current element value
- * - controller
- * - model
- * Note: Attribute wont be set to an element.
- * @param {string} name - Attribute name to handle
- * @param {string} [mode] - Render mode `client|server|both`
- * @param {AttributeHandler} handler
- * @returns {void}
- * @memberOf mask
- * @method registerAttrHandler
- */
- customAttr_register = function(attrName, mix, Handler){
- if (is_Function(mix)) {
- Handler = mix;
- }
- custom_Attributes[attrName] = Handler;
- };
- /**
- * Get attribute handler
- * @param {string} name
- * @returns {AttributeHandler}
- * @memberOf mask
- * @method getAttrHandler
- */
- customAttr_get = function(attrName){
- return attrName != null
- ? custom_Attributes[attrName]
- : custom_Attributes;
- };
- /**
- * Is called when the builder matches the node by attribute name
- * @callback AttributeHandler
- * @param {MaskNode} node
- * @param {string} attrValue
- * @param {object} model
- * @param {object} ctx
- * @param {DomNode} element
- * @param {object} parentComponent
- */
- // end:source ./attribute.js
- // source ./util.js
- (function() {
- /**
- * Utils Repository
- * @param {string} name
- * @param {(IUtilHandler|UtilHandler)} handler
- * @memberOf mask
- * @name _
- * @category Mask Util
- */
- customUtil_$utils = {};
- /**
- * Register Util Handler. Template Example: `'~[myUtil: value]'`
- * @param {string} name
- * @param {(mask._.IUtilHandler|mask._.FUtilHandler)} handler
- * @memberOf mask
- * @method getUtil
- * @category Mask Util
- */
- customUtil_register = function(name, mix) {
- if (is_Function(mix)) {
- custom_Utils[name] = mix;
- return;
- }
- custom_Utils[name] = createUtil(mix);
- if (mix['arguments'] === 'parsed')
- customUtil_$utils[name] = mix.process;
- };
- /**
- * Get the Util Handler
- * @param {string} name
- * @memberOf mask
- * @method registerUtil
- * @category Mask Util
- */
- customUtil_get = function(name) {
- return name != null ? custom_Utils[name] : custom_Utils;
- };
-
- function createUtil(obj) {
- if (obj['arguments'] === 'parsed') {
- return processParsedDelegate(obj.process);
- }
- var fn = fn_proxy(obj.process || processRawFn, obj);
- // save reference to the initial util object.
- // Mask.Bootstrap needs the original util
- // @workaround
- fn.util = obj;
- return fn;
- }
- function processRawFn(expr, model, ctx, el, ctr, attrName, type) {
- if ('node' === type) {
- this.nodeRenderStart(expr, model, ctx, el, ctr);
- return this.node(expr, model, ctx, el, ctr);
- }
- // asume 'attr'
- this.attrRenderStart(expr, model, ctx, el, ctr, attrName);
- return this.attr(expr, model, ctx, el, ctr, attrName);
- }
- function processParsedDelegate(fn) {
- return function(expr, model, ctx, el, ctr) {
- var args = expression_evalStatements(
- expr, model, ctx, ctr
- );
- return fn.apply(null, args);
- };
- }
- /**
- * Is called when the builder matches the interpolation.
- * Define `process` function OR group of `node*`,`attr*` functions.
- * The seperation `*RenderStart/*` is needed for Nodejs rendering - the first part is called on nodejs side,
- * the other one is called on the client.
- * @typedef IUtilHandler
- * @type {object}
- * @property {bool} [arguments=false] - should parse interpolation string to arguments, otherwise raw string is passed
- * @property {UtilHandler} [process]
- * @property {function} [nodeRenderStart] - `expr, model, ctx, element, controller, attrName`
- * @property {function} [node] - `expr, model, ctx, element, controller`
- * @property {function} [attr] - `expr, model, ctx, element, controller, attrName`
- * @property {function} [attrRenderStart] - `expr, model, ctx, element, controller, attrName`
- * @abstract
- * @category Mask Util
- */
- var IUtilHandler = {
- 'arguments': null,
- 'process': null,
- 'nodeRenderStart': null,
- 'node': null,
- 'attrRenderStart': null,
- 'attr': null,
- };
- /**
- * Is called when the builder matches the interpolation
- * @param {string} value - string after the utility name
- * @param {object} model
- * @param {("attr"|"node")} type - Current location: text node or attribute
- * @param {HTMLNode} element
- * @param {string} name - If the interpolation is in attribute, then this will contain attributes name
- * @typedef UtilHandler
- * @type {function}
- * @abstract
- * @category Mask Util
- */
- function UtilHandler() {}
- }());
- // end:source ./util.js
- // source ./statement.js
- /**
- * Register a statement handler
- * @param {string} name - Tag name to handle
- * @param StatementHandler} handler
- * @memberOf mask
- * @method registerStatement
- */
- customStatement_register = function(name, handler){
- //@TODO should it be not allowed to override system statements, if, switch?
- custom_Statements[name] = is_Function(handler)
- ? { render: handler }
- : handler
- ;
- };
- /**
- * Get statement handler
- * @param {string} name
- * @returns {StatementHandler}
- * @memberOf mask
- * @method getStatement
- */
- customStatement_get = function(name){
- return name != null
- ? custom_Statements[name]
- : custom_Statements
- ;
- };
- /**
- * Is called when the builder matches the node by tagName
- * @callback StatementHandler
- * @param {MaskNode} node
- * @param {object} model
- * @param {object} ctx
- * @param {DomNode} container
- * @param {object} parentComponent
- * @param {Array} children - `out` Fill the array with rendered elements
- */
- // end:source ./statement.js
- // source ./optimize.js
- (function(){
- custom_optimize = function(){
- var i = _arr.length;
- while (--i > -1) {
- readProps(_arr[i]);
- }
- i = _arr.length;
- while(--i > -1) {
- defineProps(_arr[i]);
- obj_toFastProps(_arr[i]);
- }
- obj_toFastProps(custom_Attributes);
- };
- var _arr = [
- custom_Statements,
- custom_Tags,
- custom_Parsers,
- custom_Parsers_Transform
- ];
- var _props = {};
- function readProps(obj) {
- for (var key in obj) {
- _props[key] = null;
- }
- }
- function defineProps(obj) {
- for (var key in _props) {
- if (obj[key] === void 0) {
- obj[key] = null;
- }
- }
- }
- }());
- // end:source ./optimize.js
-
- }());
-
- // end:source custom/
- // source expression/
- /**
- * ExpressionUtil
- *
- * Helper to work with expressions
- **/
- var expression_eval,
- expression_evalStatements,
- ExpressionUtil;
-
- (function(){
-
- // source 1.scope-vars.js
-
- var index = 0,
- length = 0,
- cache = {},
- template, ast;
-
- var op_Minus = '-', //1,
- op_Plus = '+', //2,
- op_Divide = '/', //3,
- op_Multip = '*', //4,
- op_Modulo = '%', //5,
-
- op_LogicalOr = '||', //6,
- op_LogicalAnd = '&&', //7,
- op_LogicalNot = '!', //8,
- op_LogicalEqual = '==', //9,
- op_LogicalEqual_Strict = '===', // 111
- op_LogicalNotEqual = '!=', //11,
- op_LogicalNotEqual_Strict = '!==', // 112
- op_LogicalGreater = '>', //12,
- op_LogicalGreaterEqual = '>=', //13,
- op_LogicalLess = '<', //14,
- op_LogicalLessEqual = '<=', //15,
- op_Member = '.', // 16
-
- punc_ParantheseOpen = 20,
- punc_ParantheseClose = 21,
- punc_BracketOpen = 22,
- punc_BracketClose = 23,
- punc_BraceOpen = 24,
- punc_BraceClose = 25,
- punc_Comma = 26,
- punc_Dot = 27,
- punc_Question = 28,
- punc_Colon = 29,
- punc_Semicolon = 30,
-
- go_ref = 31,
- go_acs = 32,
- go_string = 33,
- go_number = 34,
- go_objectKey = 35;
-
- var type_Body = 1,
- type_Statement = 2,
- type_SymbolRef = 3,
- type_FunctionRef = 4,
- type_Accessor = 5,
- type_AccessorExpr = 6,
- type_Value = 7,
-
-
- type_Number = 8,
- type_String = 9,
- type_Object = 10,
- type_Array = 11,
- type_UnaryPrefix = 12,
- type_Ternary = 13;
-
- var state_body = 1,
- state_arguments = 2;
-
-
- var precedence = {};
-
- precedence[op_Member] = 1;
-
- precedence[op_Divide] = 2;
- precedence[op_Multip] = 2;
-
- precedence[op_Minus] = 3;
- precedence[op_Plus] = 3;
-
- precedence[op_LogicalGreater] = 4;
- precedence[op_LogicalGreaterEqual] = 4;
- precedence[op_LogicalLess] = 4;
- precedence[op_LogicalLessEqual] = 4;
-
- precedence[op_LogicalEqual] = 5;
- precedence[op_LogicalEqual_Strict] = 5;
- precedence[op_LogicalNotEqual] = 5;
- precedence[op_LogicalNotEqual_Strict] = 5;
-
-
- precedence[op_LogicalAnd] = 6;
- precedence[op_LogicalOr] = 6;
-
- // end:source 1.scope-vars.js
- // source 2.ast.js
- var Ast_Body,
- Ast_Statement,
- Ast_Value,
- Ast_Array,
- Ast_Object,
- Ast_FunctionRef,
- Ast_SymbolRef,
- Ast_Accessor,
- Ast_AccessorExpr,
- Ast_UnaryPrefix,
- Ast_TernaryStatement
- ;
-
-
- (function(){
-
- Ast_Body = function(parent) {
- this.parent = parent;
- this.type = type_Body;
- this.body = [];
- this.join = null;
- };
-
- Ast_Statement = function(parent) {
- this.parent = parent;
- };
-
- Ast_Statement.prototype = {
- constructor: Ast_Statement,
- type: type_Statement,
- join: null,
- body: null
- };
-
- Ast_Value = function(value) {
- this.type = type_Value;
- this.body = value;
- this.join = null;
- };
-
- Ast_Array = function(parent){
- this.type = type_Array;
- this.parent = parent;
- this.body = new Ast_Body(this);
- };
-
- Ast_Object = function(parent){
- this.type = type_Object;
- this.parent = parent;
- this.props = {};
- }
- Ast_Object.prototype = {
- nextProp: function(prop){
- var body = new Ast_Statement(this);
- this.props[prop] = body;
- return body;
- },
- };
-
- Ast_FunctionRef = function(parent, ref) {
- this.parent = parent;
- this.type = type_FunctionRef;
- this.body = ref;
- this.arguments = [];
- this.next = null;
- }
- Ast_FunctionRef.prototype = {
- constructor: Ast_FunctionRef,
- newArgument: function() {
- var body = new Ast_Body(this);
- this.arguments.push(body);
-
- return body;
- }
- };
-
- Ast_SymbolRef = function(parent, ref) {
- this.type = type_SymbolRef;
- this.parent = parent;
- this.body = ref;
- this.next = null;
- };
- Ast_Accessor = function(parent, ref) {
- this.type = type_Accessor;
- this.parent = parent;
- this.body = ref;
- this.next = null;
- };
- Ast_AccessorExpr = function(parent){
- this.parent = parent;
- this.body = new Ast_Statement(this);
- this.body.body = new Ast_Body(this.body);
- this.next = null;
- };
- Ast_AccessorExpr.prototype = {
- type: type_AccessorExpr,
- getBody: function(){
- return this.body.body;
- }
- };
-
-
- Ast_UnaryPrefix = function(parent, prefix) {
- this.parent = parent;
- this.prefix = prefix;
- };
- Ast_UnaryPrefix.prototype = {
- constructor: Ast_UnaryPrefix,
- type: type_UnaryPrefix,
- body: null
- };
-
-
- Ast_TernaryStatement = function(assertions){
- this.body = assertions;
- this.case1 = new Ast_Body(this);
- this.case2 = new Ast_Body(this);
- };
- Ast_TernaryStatement.prototype = {
- constructor: Ast_TernaryStatement,
- type: type_Ternary,
- case1: null,
- case2: null
- };
-
- }());
- // end:source 2.ast.js
- // source 2.ast.utils.js
- var ast_handlePrecedence,
- ast_append;
-
- (function(){
-
-
- ast_append = function(current, next) {
- switch(current.type) {
- case type_Body:
- current.body.push(next);
- return next;
-
- case type_Statement:
- if (next.type === type_Accessor || next.type === type_AccessorExpr) {
- return (current.next = next)
- }
- /* fall through */
- case type_UnaryPrefix:
- return (current.body = next);
-
- case type_SymbolRef:
- case type_FunctionRef:
- case type_Accessor:
- case type_AccessorExpr:
- return (current.next = next);
- }
-
- return util_throw('Invalid expression');
- };
-
-
- ast_handlePrecedence = function(ast) {
- if (ast.type !== type_Body){
-
- if (ast.body != null && typeof ast.body === 'object')
- ast_handlePrecedence(ast.body);
-
- return;
- }
-
- var body = ast.body,
- i = 0,
- length = body.length,
- x, prev, array;
-
- for(; i < length; i++){
- ast_handlePrecedence(body[i]);
- }
-
-
- for(i = 1; i < length; i++){
- x = body[i];
- prev = body[i-1];
-
- if (precedence[prev.join] > precedence[x.join])
- break;
-
- }
-
- if (i === length)
- return;
-
-
- array = [body[0]];
- for(i = 1; i < length; i++){
- x = body[i];
- prev = body[i-1];
-
- var prec_Prev = precedence[prev.join];
- if (prec_Prev > precedence[x.join] && i < length - 1){
-
- var start = i,
- nextJoin,
- arr;
-
- // collect all with join smaller or equal to previous
- // 5 == 3 * 2 + 1 -> 5 == (3 * 2 + 1);
- while (++i < length){
- nextJoin = body[i].join;
- if (nextJoin == null)
- break;
-
- if (prec_Prev <= precedence[nextJoin])
- break;
- }
-
- arr = body.slice(start, i + 1);
- x = ast_join(arr);
- ast_handlePrecedence(x);
- }
-
- array.push(x);
- }
-
- ast.body = array;
-
- };
-
- // = private
-
- function ast_join(bodyArr){
- if (bodyArr.length === 0)
- return null;
-
- var body = new Ast_Body(bodyArr[0].parent);
-
- body.join = bodyArr[bodyArr.length - 1].join;
- body.body = bodyArr;
-
- return body;
- }
-
-
- }());
- // end:source 2.ast.utils.js
- // source 3.util.js
- var util_resolveRef,
- util_throw;
-
- (function(){
-
- util_throw = function(msg, token){
- return parser_error(msg
- , template
- , index
- , token
- , 'expr'
- );
- };
-
- util_resolveRef = function(astRef, model, ctx, ctr) {
- var controller = ctr,
- current = astRef,
- key = astRef.body,
- object,
- value,
- args,
- i,
- imax
- ;
-
- if ('$c' === key) {
- reporter_deprecated(
- 'accessor.compo', "Use `$` instead of `$c`."
- );
- key = '$';
- }
- if ('$u' === key) {
- reporter_deprecated(
- 'accessor.util', "Use `_` instead of `$u`"
- );
- key = '_';
- }
- if ('$a' === key) {
- reporter_deprecated(
- 'accessor.attr', "Use `$.attr` instead of `$a`"
- );
- }
-
- if ('$' === key) {
- value = controller;
-
- var next = current.next,
- nextBody = next != null && next.body;
- if (nextBody != null && value[nextBody] == null){
-
- if (next.type === type_FunctionRef && is_Function(Compo.prototype[nextBody])) {
- // use fn from prototype if possible, like `closest`
- object = controller;
- value = Compo.prototype[nextBody];
- current = next;
- } else {
- // find the closest controller, which has the property
- while (true) {
- value = value.parent;
- if (value == null)
- break;
-
- if (value[nextBody] == null)
- continue;
-
- object = value;
- value = value[nextBody];
- current = next;
- break;
- }
- }
-
- if (value == null) {
- // prepair for warn message
- key = '$.' + nextBody;
- current = next;
- }
- }
-
- }
-
- else if ('$a' === key) {
- value = controller && controller.attr;
- }
-
- else if ('_' === key) {
- value = customUtil_$utils;
- }
-
-
- else if ('$ctx' === key) {
- value = ctx;
- }
-
- else if ('$scope' === key) {
- var next = current.next,
- nextBody = next != null && next.body;
-
- if (nextBody != null) {
- while (controller != null) {
- object = controller.scope;
- if (object != null) {
- value = object[nextBody];
- }
- if (value != null) {
- break;
- }
- controller = controller.parent;
- }
- current = next;
- }
- }
-
- else {
- // scope resolver
-
- if (model != null) {
- object = model;
- value = model[key];
- }
-
- if (value == null) {
-
- while (controller != null) {
- object = controller.scope;
-
- if (object != null)
- value = object[key];
-
- if (value != null)
- break;
-
- controller = controller.parent;
- }
- }
- }
-
- if (value == null) {
- if (current == null || current.next != null){
- // notify that value is not in model, ctx, controller;
- log_warn(' Accessor error:', key);
- }
- return null;
- }
-
- do {
- if (current.type === type_FunctionRef) {
-
- args = [];
- i = -1;
- imax = current.arguments.length;
-
- while( ++i < imax ) {
- args[i] = expression_evaluate(
- current.arguments[i]
- , model
- , ctx
- , controller
- );
- }
-
- value = value.apply(object, args);
- }
-
- if (value == null || current.next == null) {
- break;
- }
-
- current = current.next;
- key = current.type === type_AccessorExpr
- ? expression_evaluate(current.body, model, ctx, controller)
- : current.body
- ;
-
- object = value;
- value = value[key];
-
- if (value == null)
- break;
-
- } while (true);
-
- return value;
- };
-
-
- }());
-
-
- // end:source 3.util.js
- // source 4.parser.helper.js
- var parser_skipWhitespace,
- parser_getString,
- parser_getNumber,
- parser_getArray,
- parser_getObject,
- parser_getRef,
- parser_getDirective
- ;
-
- (function(){
- parser_skipWhitespace = function() {
- var c;
- while (index < length) {
- c = template.charCodeAt(index);
- if (c > 32)
- return c;
- index++;
- }
- return null;
- };
- parser_getString = function(c) {
- var isEscaped = false,
- _char = c === 39 ? "'" : '"',
- start = index,
- nindex, string;
-
- while ((nindex = template.indexOf(_char, index)) > -1) {
- index = nindex;
- if (template.charCodeAt(nindex - 1) !== 92 /*'\\'*/ ) {
- break;
- }
- isEscaped = true;
- index++;
- }
-
- string = template.substring(start, index);
- if (isEscaped === true) {
- string = string.replace(__rgxEscapedChar[_char], _char);
- }
- return string;
- };
-
- parser_getNumber = function() {
- var start = index,
- code, isDouble;
- while (true) {
-
- code = template.charCodeAt(index);
- if (code === 46) {
- // .
- if (isDouble === true) {
- util_throw('Invalid number', code);
- return null;
- }
- isDouble = true;
- }
- if ((code >= 48 && code <= 57 || code === 46) && index < length) {
- index++;
- continue;
- }
- break;
- }
- return +template.substring(start, index);
- };
-
-
- parser_getRef = function() {
- var start = index,
- c = template.charCodeAt(index),
- ref;
-
- if (c === 34 || c === 39) {
- // ' | "
- index++;
- ref = parser_getString(c);
- index++;
- return ref;
- }
-
- while (true) {
-
- if (index === length)
- break;
-
- c = template.charCodeAt(index);
-
- if (c === 36 || c === 95) {
- // $ _
- index++;
- continue;
- }
- if ((48 <= c && c <= 57) || // 0-9
- (65 <= c && c <= 90) || // A-Z
- (97 <= c && c <= 122)) { // a-z
- index++;
- continue;
- }
- // - [removed] (exit on not allowed chars) 5ba755ca
- break;
- }
- return template.substring(start, index);
- };
-
- parser_getDirective = function(code) {
- if (code == null && index === length)
- return null;
-
- switch (code) {
- case 40:
- // (
- return punc_ParantheseOpen;
- case 41:
- // )
- return punc_ParantheseClose;
- case 123:
- // {
- return punc_BraceOpen;
- case 125:
- // }
- return punc_BraceClose;
- case 91:
- // [
- return punc_BracketOpen;
- case 93:
- // ]
- return punc_BracketClose;
- case 44:
- // ,
- return punc_Comma;
- case 46:
- // .
- return punc_Dot;
- case 59:
- // ;
- return punc_Semicolon;
- case 43:
- // +
- return op_Plus;
- case 45:
- // -
- return op_Minus;
- case 42:
- // *
- return op_Multip;
- case 47:
- // /
- return op_Divide;
- case 37:
- // %
- return op_Modulo;
-
- case 61:
- // =
- if (template.charCodeAt(++index) !== code) {
- util_throw(
- 'Assignment violation: View can only access model/controllers', '='
- );
- return null;
- }
- if (template.charCodeAt(index + 1) === code) {
- index++;
- return op_LogicalEqual_Strict;
- }
- return op_LogicalEqual;
- case 33:
- // !
- if (template.charCodeAt(index + 1) === 61) {
- // =
- index++;
-
- if (template.charCodeAt(index + 1) === 61) {
- // =
- index++;
- return op_LogicalNotEqual_Strict;
- }
-
- return op_LogicalNotEqual;
- }
- return op_LogicalNot;
- case 62:
- // >
- if (template.charCodeAt(index + 1) === 61) {
- index++;
- return op_LogicalGreaterEqual;
- }
- return op_LogicalGreater;
- case 60:
- // <
- if (template.charCodeAt(index + 1) === 61) {
- index++;
- return op_LogicalLessEqual;
- }
- return op_LogicalLess;
- case 38:
- // &
- if (template.charCodeAt(++index) !== code) {
- util_throw(
- 'Not supported: Bitwise AND', code
- );
- return null;
- }
- return op_LogicalAnd;
- case 124:
- // |
- if (template.charCodeAt(++index) !== code) {
- util_throw(
- 'Not supported: Bitwise OR', code
- );
- return null;
- }
- return op_LogicalOr;
- case 63:
- // ?
- return punc_Question;
- case 58:
- // :
- return punc_Colon;
- }
-
- if ((code >= 65 && code <= 90) ||
- (code >= 97 && code <= 122) ||
- (code === 95) ||
- (code === 36)) {
- // A-Z a-z _ $
- return go_ref;
- }
-
- if (code >= 48 && code <= 57) {
- // 0-9 .
- return go_number;
- }
-
- if (code === 34 || code === 39) {
- // " '
- return go_string;
- }
-
- util_throw(
- 'Unexpected or unsupported directive', code
- );
- return null;
- };
- }());
- // end:source 4.parser.helper.js
- // source 5.parser.js
- /*
- * earlyExit - only first statement/expression is consumed
- */
- function expression_parse(expr, earlyExit) {
- if (earlyExit == null)
- earlyExit = false;
-
- template = expr;
- index = 0;
- length = expr.length;
-
- ast = new Ast_Body();
-
- var current = ast,
- state = state_body,
- c, next, directive;
-
- outer: while (true) {
-
- if (index < length && (c = template.charCodeAt(index)) < 33) {
- index++;
- continue;
- }
-
- if (index >= length)
- break;
-
- directive = parser_getDirective(c);
-
- if (directive == null && index < length) {
- break;
- }
- if (directive === punc_Semicolon) {
- if (earlyExit === true)
- return [ast, index];
-
- break;
- }
-
- if (earlyExit === true) {
- var p = current.parent;
- if (p != null && p.type === type_Body && p.parent == null) {
- // is in root body
- if (directive === go_ref)
- return [ast, index];
- }
- }
-
- if (directive === punc_Semicolon) {
- break;
- }
-
- switch (directive) {
- case punc_ParantheseOpen:
- current = ast_append(current, new Ast_Statement(current));
- current = ast_append(current, new Ast_Body(current));
-
- index++;
- continue;
- case punc_ParantheseClose:
- var closest = type_Body;
- if (state === state_arguments) {
- state = state_body;
- closest = type_FunctionRef;
- }
-
- do {
- current = current.parent;
- } while (current != null && current.type !== closest);
-
- if (closest === type_Body) {
- current = current.parent;
- }
-
- if (current == null) {
- util_throw('OutOfAst Exception', c);
- break outer;
- }
- index++;
- continue;
-
- case punc_BraceOpen:
- current = ast_append(current, new Ast_Object(current));
- directive = go_objectKey;
- index++;
- break;
- case punc_BraceClose:
- while (current != null && current.type !== type_Object){
- current = current.parent;
- }
- index++;
- continue;
- case punc_Comma:
- if (state !== state_arguments) {
-
- state = state_body;
- do {
- current = current.parent;
- } while (current != null &&
- current.type !== type_Body &&
- current.type !== type_Object
- );
- index++;
- if (current == null) {
- util_throw('Unexpected comma', c);
- break outer;
- }
-
- if (current.type === type_Object) {
- directive = go_objectKey;
- break;
- }
-
- continue;
- }
- do {
- current = current.parent;
- } while (current != null && current.type !== type_FunctionRef);
-
- if (current == null) {
- util_throw('OutOfAst Exception', c);
- break outer;
- }
-
- current = current.newArgument();
-
- index++;
- continue;
-
- case punc_Question:
- ast = new Ast_TernaryStatement(ast);
- current = ast.case1;
- index++;
- continue;
-
- case punc_Colon:
- current = ast.case2;
- index++;
- continue;
-
-
- case punc_Dot:
- c = template.charCodeAt(index + 1);
- if (c >= 48 && c <= 57) {
- directive = go_number;
- } else {
- directive = current.type === type_Body
- ? go_ref
- : go_acs
- ;
- index++;
- }
- break;
- case punc_BracketOpen:
- if (current.type === type_SymbolRef ||
- current.type === type_AccessorExpr ||
- current.type === type_Accessor
- ) {
- current = ast_append(current, new Ast_AccessorExpr(current))
- current = current.getBody();
- index++;
- continue;
- }
- current = ast_append(current, new Ast_Array(current));
- current = current.body;
- index++;
- continue;
- case punc_BracketClose:
- do {
- current = current.parent;
- } while (current != null &&
- current.type !== type_AccessorExpr &&
- current.type !== type_Array
- );
- index++;
- continue;
- }
-
-
- if (current.type === type_Body) {
- current = ast_append(current, new Ast_Statement(current));
- }
-
- if ((op_Minus === directive || op_LogicalNot === directive) && current.body == null) {
- current = ast_append(current, new Ast_UnaryPrefix(current, directive));
- index++;
- continue;
- }
-
- switch (directive) {
-
- case op_Minus:
- case op_Plus:
- case op_Multip:
- case op_Divide:
- case op_Modulo:
-
- case op_LogicalAnd:
- case op_LogicalOr:
- case op_LogicalEqual:
- case op_LogicalEqual_Strict:
- case op_LogicalNotEqual:
- case op_LogicalNotEqual_Strict:
-
- case op_LogicalGreater:
- case op_LogicalGreaterEqual:
- case op_LogicalLess:
- case op_LogicalLessEqual:
-
- while (current && current.type !== type_Statement) {
- current = current.parent;
- }
-
- if (current.body == null) {
- return util_throw(
- 'Unexpected operator', c
- );
- }
-
- current.join = directive;
-
- do {
- current = current.parent;
- } while (current != null && current.type !== type_Body);
-
- if (current == null) {
- return util_throw(
- 'Unexpected operator' , c
- );
- }
-
-
- index++;
- continue;
- case go_string:
- case go_number:
- if (current.body != null && current.join == null) {
- return util_throw(
- 'Directive expected', c
- );
- }
- if (go_string === directive) {
- index++;
- ast_append(current, new Ast_Value(parser_getString(c)));
- index++;
-
- }
-
- if (go_number === directive) {
- ast_append(current, new Ast_Value(parser_getNumber(c)));
- }
-
- continue;
-
- case go_ref:
- case go_acs:
- var ref = parser_getRef();
-
- if (directive === go_ref) {
-
- if (ref === 'null')
- ref = null;
-
- if (ref === 'false')
- ref = false;
-
- if (ref === 'true')
- ref = true;
-
- if (typeof ref !== 'string') {
- ast_append(current, new Ast_Value(ref));
- continue;
- }
- }
- while (index < length) {
- c = template.charCodeAt(index);
- if (c < 33) {
- index++;
- continue;
- }
- break;
- }
-
- if (c === 40) {
-
- // (
- // function ref
- state = state_arguments;
- index++;
-
- var fn = ast_append(current, new Ast_FunctionRef(current, ref));
-
- current = fn.newArgument();
- continue;
- }
-
- var Ctor = directive === go_ref
- ? Ast_SymbolRef
- : Ast_Accessor
- current = ast_append(current, new Ctor(current, ref));
- break;
- case go_objectKey:
- if (parser_skipWhitespace() === 125)
- continue;
-
-
- var key = parser_getRef();
-
- if (parser_skipWhitespace() !== 58) {
- //:
- return util_throw(
- 'Object parser. Semicolon expeted', c
- );
- }
- index++;
- current = current.nextProp(key);
- directive = go_ref;
- continue;
- }
- }
-
- if (current.body == null &&
- current.type === type_Statement) {
-
- return util_throw(
- 'Unexpected end of expression', c
- );
- }
-
- ast_handlePrecedence(ast);
-
- return ast;
- }
- // end:source 5.parser.js
- // source 6.eval.js
- function expression_evaluate(mix, model, ctx, controller) {
-
- var result, ast;
-
- if (null == mix)
- return null;
-
- if ('.' === mix)
- return model;
-
- if (typeof mix === 'string'){
- ast = cache.hasOwnProperty(mix) === true
- ? (cache[mix])
- : (cache[mix] = expression_parse(mix))
- ;
- }else{
- ast = mix;
- }
- if (ast == null)
- return null;
-
- var type = ast.type,
- i, x, length;
-
- if (type_Body === type) {
- var value, prev;
-
- outer: for (i = 0, length = ast.body.length; i < length; i++) {
- x = ast.body[i];
-
- value = expression_evaluate(x, model, ctx, controller);
-
- if (prev == null || prev.join == null) {
- prev = x;
- result = value;
- continue;
- }
-
- if (prev.join === op_LogicalAnd) {
- if (!result) {
- for (; i < length; i++) {
- if (ast.body[i].join === op_LogicalOr) {
- break;
- }
- }
- }else{
- result = value;
- }
- }
-
- if (prev.join === op_LogicalOr) {
- if (result){
- break outer;
- }
- if (value) {
- result = value;
- break outer;
- }
- }
-
- switch (prev.join) {
- case op_Minus:
- result -= value;
- break;
- case op_Plus:
- result += value;
- break;
- case op_Divide:
- result /= value;
- break;
- case op_Multip:
- result *= value;
- break;
- case op_Modulo:
- result %= value;
- break;
- case op_LogicalNotEqual:
- /* jshint eqeqeq: false */
- result = result != value;
- /* jshint eqeqeq: true */
- break;
- case op_LogicalNotEqual_Strict:
- result = result !== value;
- break;
- case op_LogicalEqual:
- /* jshint eqeqeq: false */
- result = result == value;
- /* jshint eqeqeq: true */
- break;
- case op_LogicalEqual_Strict:
- result = result === value;
- break;
- case op_LogicalGreater:
- result = result > value;
- break;
- case op_LogicalGreaterEqual:
- result = result >= value;
- break;
- case op_LogicalLess:
- result = result < value;
- break;
- case op_LogicalLessEqual:
- result = result <= value;
- break;
- }
-
- prev = x;
- }
- }
-
- if (type_Statement === type) {
- result = expression_evaluate(ast.body, model, ctx, controller);
- if (ast.next == null)
- return result;
-
- return util_resolveRef(ast.next, result);
- }
-
- if (type_Value === type) {
- return ast.body;
- }
- if (type_Array === type) {
- var body = ast.body.body,
- imax = body.length,
- i = -1;
-
- result = new Array(imax);
- while( ++i < imax ){
- result[i] = expression_evaluate(body[i], model, ctx, controller);
- }
- return result;
- }
- if (type_Object === type) {
- result = {};
- var props = ast.props;
- for(var key in props){
- result[key] = expression_evaluate(props[key], model, ctx, controller);
- }
- return result;
- }
-
- if (type_SymbolRef === type ||
- type_FunctionRef === type ||
- type_AccessorExpr === type ||
- type_Accessor === type) {
- return util_resolveRef(ast, model, ctx, controller);
- }
-
- if (type_UnaryPrefix === type) {
- result = expression_evaluate(ast.body, model, ctx, controller);
- switch (ast.prefix) {
- case op_Minus:
- result = -result;
- break;
- case op_LogicalNot:
- result = !result;
- break;
- }
- }
-
- if (type_Ternary === type){
- result = expression_evaluate(ast.body, model, ctx, controller);
- result = expression_evaluate(result ? ast.case1 : ast.case2, model, ctx, controller);
-
- }
-
- return result;
- }
-
- // end:source 6.eval.js
- // source 7.eval_statements.js
- function expression_evaluateStatements(expr, model, ctx, ctr){
-
- var body = expression_parse(expr).body,
- args = [],
- imax = body.length,
- i = -1
- ;
- var group = new Ast_Body;
- while( ++i < imax ){
- group.body.push(body[i]);
- if (body[i].join != null)
- continue;
-
- args.push(expression_evaluate(group, model, ctx, ctr));
- group.body.length = 0;
- }
- return args;
- }
- // end:source 7.eval_statements.js
- // source 8.vars.helper.js
- var refs_extractVars;
- (function() {
-
- /**
- * extract symbol references
- * ~[:user.name + 'px'] -> 'user.name'
- * ~[:someFn(varName) + user.name] -> ['varName', 'user.name']
- *
- * ~[:someFn().user.name] -> {accessor: (Accessor AST function call) , ref: 'user.name'}
- */
-
-
- refs_extractVars = function(expr, model, ctx, ctr){
- if (typeof expr === 'string')
- expr = expression_parse(expr);
-
- return _extractVars(expr, model, ctx, ctr);
- };
-
-
-
- function _extractVars(expr, model, ctx, ctr) {
-
- if (expr == null)
- return null;
-
- var exprType = expr.type,
- refs, x;
- if (type_Body === exprType) {
-
- var body = expr.body,
- imax = body.length,
- i = -1;
- while ( ++i < imax ){
- x = _extractVars(body[i], model, ctx, ctr);
- refs = _append(refs, x);
- }
- }
-
- if (type_SymbolRef === exprType ||
- type_Accessor === exprType ||
- type_AccessorExpr === exprType) {
-
- var path = expr.body,
- next = expr.next,
- nextType;
-
- while (next != null) {
- nextType = next.type;
- if (type_FunctionRef === nextType) {
- return _extractVars(next, model, ctx, ctr);
- }
- if ((type_SymbolRef !== nextType) &&
- (type_Accessor !== nextType) &&
- (type_AccessorExpr !== nextType)) {
-
- log_error('Ast Exception: next should be a symbol/function ref');
- return null;
- }
-
- var prop = nextType === type_AccessorExpr
- ? expression_evaluate(next.body, model, ctx, ctr)
- : next.body
- ;
- if (typeof prop !== 'string') {
- log_warn('Can`t extract accessor name', path);
- return null;
- }
- path += '.' + prop;
- next = next.next;
- }
-
- return path;
- }
-
-
- switch (exprType) {
- case type_Statement:
- case type_UnaryPrefix:
- case type_Ternary:
- x = _extractVars(expr.body, model, ctx, ctr);
- refs = _append(refs, x);
- break;
- }
-
- // get also from case1 and case2
- if (type_Ternary === exprType) {
- x = _extractVars(ast.case1, model, ctx, ctr);
- refs = _append(refs, x);
-
- x = _extractVars(ast.case2, model, ctx, ctr);
- refs = _append(refs, x);
- }
-
-
- if (type_FunctionRef === exprType) {
- var args = expr.arguments,
- imax = args.length,
- i = -1;
- while ( ++i < imax ){
- x = _extractVars(args[i], model, ctx, ctr);
- refs = _append(refs, x);
- }
-
- x = null;
- var parent = expr;
- outer: while ((parent = parent.parent)) {
- switch (parent.type) {
- case type_SymbolRef:
- case type_Accessor:
- case type_AccessorExpr:
- x = parent.body + (x == null ? '' : '.' + x);
- break;
- case type_Body:
- case type_Statement:
- break outer;
- default:
- x = null;
- break outer;
- }
- }
-
- if (x != null) {
- refs = _append(refs, x);
- }
-
- if (expr.next) {
- x = _extractVars(expr.next, model, ctx, ctr);
- refs = _append(refs, {accessor: _getAccessor(expr), ref: x});
- }
- }
-
- return refs;
- }
-
- function _append(current, x) {
- if (current == null) {
- return x;
- }
-
- if (x == null) {
- return current;
- }
-
- if (!(typeof current === 'object' && current.length != null)) {
- current = [current];
- }
-
- if (!(typeof x === 'object' && x.length != null)) {
-
- if (current.indexOf(x) === -1) {
- current.push(x);
- }
-
- return current;
- }
-
- for (var i = 0, imax = x.length; i < imax; i++) {
- if (current.indexOf(x[i]) === -1) {
- current.push(x[i]);
- }
- }
-
- return current;
-
- }
-
- function _getAccessor(current) {
-
- var parent = current;
-
- outer: while (parent.parent) {
- switch (parent.parent.type) {
- case type_Body:
- case type_Statement:
- break outer;
- }
- parent = parent.parent;
- }
-
- return _copy(parent, current.next);
- }
-
- function _copy(ast, stop) {
-
- if (ast === stop || ast == null) {
- return null;
- }
-
- if (typeof ast !== 'object') {
- return ast;
- }
-
- if (ast.length != null && typeof ast.splice === 'function') {
-
- var arr = [];
-
- for (var i = 0, imax = ast.length; i < imax; i++){
- arr[i] = _copy(ast[i], stop);
- }
-
- return arr;
- }
-
-
- var clone = {};
- for (var key in ast) {
- if (ast[key] == null || key === 'parent') {
- continue;
- }
- clone[key] = _copy(ast[key], stop);
- }
-
- return clone;
- }
-
- }());
-
- // end:source 8.vars.helper.js
-
- expression_eval = expression_evaluate;
- expression_evalStatements = expression_evaluateStatements;
- ExpressionUtil = {
- 'parse': expression_parse,
-
- /**
- * Expression.eval(expression [, model, cntx, controller]) -> result
- * - expression (String): Expression, only accessors are supoorted
- *
- * All symbol and function references will be looked for in
- *
- * 1. model, or via special accessors:
- * - `$c` controller
- * - `$ctx`
- * - `$a' controllers attributes
- * 2. scope:
- * controller.scope
- * controller.parent.scope
- * ...
- *
- * Sample:
- * '(user.age + 20) / 2'
- * 'fn(user.age + "!") + x'
- **/
- 'eval': expression_evaluate,
- 'varRefs': refs_extractVars,
-
- // Return all values of a comma delimiter expressions
- // like argumets: ' foo, bar, "4,50" ' => [ %fooValue, %barValue, "4,50" ]
- 'evalStatements': expression_evaluateStatements
- };
-
- }());
-
- // end:source expression/
- // source dom/
- var Dom;
-
- (function(){
-
- var dom_NODE = 1,
- dom_TEXTNODE = 2,
- dom_FRAGMENT = 3,
- dom_COMPONENT = 4,
- dom_CONTROLLER = 9,
- dom_SET = 10,
- dom_STATEMENT = 15
- ;
-
- // source 1.utils.js
- function _appendChild(el){
- var nodes = this.nodes;
- if (nodes == null) {
- this.nodes = [el];
- return;
- }
-
- var length = nodes.length;
- if (length !== 0) {
- var prev = nodes[length - 1];
- if (prev != null) {
- prev.nextSibling = el;
- }
- }
-
- nodes.push(el);
- }
- // end:source 1.utils.js
- // source 2.Node.js
- /**
- * @name MaskNode
- * @type {class}
- * @property {type} [type=1]
- * @property {object} attr
- * @property {string} tagName
- * @property {Array.} nodes
- * @property {IMaskNode} parent
- * @property {string} expression
- * @property {function} appendChild
- * @memberOf mask.Dom
- */
- var Node = class_create({
- constructor: function Node(tagName, parent) {
- this.type = Dom.NODE;
- this.tagName = tagName;
- this.parent = parent;
- this.attr = {};
- },
- __single: null,
- appendChild: _appendChild,
- attr: null,
- expression: null,
- nodes: null,
- parent: null,
- sourceIndex: -1,
- stringify: null,
- tagName: null,
- type: dom_NODE,
- });
-
- // end:source 2.Node.js
- // source 3.TextNode.js
- /**
- * @name TextNode
- * @type {class}
- * @property {type} [type=2]
- * @property {(string|function)} content
- * @property {IMaskNode} parent
- * @memberOf mask.Dom
- */
- var TextNode = class_create({
- constructor: function(text, parent) {
- this.content = text;
- this.parent = parent;
- },
- type: dom_TEXTNODE,
- content: null,
- parent: null
- });
-
- // end:source 3.TextNode.js
- // source 4.Component.js
- function Component(compoName, parent, controller){
- this.tagName = compoName;
- this.parent = parent;
- this.controller = controller;
- this.attr = {};
- }
- Component.prototype = {
- constructor: Component,
- type: dom_COMPONENT,
- parent: null,
- attr: null,
- controller: null,
- nodes: null,
- components: null,
- model: null,
- modelRef: null
- };
-
- // end:source 4.Component.js
- // source 5.Fragment.js
- var Fragment = class_create({
- type: dom_FRAGMENT,
- nodes: null,
- appendChild: _appendChild,
- source: ''
- });
- // end:source 5.Fragment.js
-
- /**
- * Dom
- * @type {object}
- * @memberOf mask
- */
- Dom = {
- NODE: dom_NODE,
- TEXTNODE: dom_TEXTNODE,
- FRAGMENT: dom_FRAGMENT,
- COMPONENT: dom_COMPONENT,
- CONTROLLER: dom_CONTROLLER,
- SET: dom_SET,
- STATEMENT: dom_STATEMENT,
-
- Node: Node,
- TextNode: TextNode,
- Fragment: Fragment,
- Component: Component
- };
- /**
- * @interface
- * @typedef IMaskNode
- * @type {class}
- * @property {number} type
- */
- }());
-
- // end:source dom/
- // source statements/
- // source ./01.if.js
- (function(){
-
- function getNodes(node, model, ctx, ctr){
- function evaluate(expr){
- return expression_eval(expr, model, ctx, ctr);
- }
-
- if (evaluate(node.expression))
- return node.nodes;
-
- while (true) {
- node = node.nextSibling;
-
- if (node == null || node.tagName !== 'else')
- break;
-
- var expr = node.expression;
- if (expr == null || expr === '' || evaluate(expr))
- return node.nodes;
- }
-
- return null;
- }
-
- custom_Statements['if'] = {
- getNodes: getNodes,
- render: function(node, model, ctx, container, ctr, childs){
-
- var nodes = getNodes(node, model, ctx, ctr);
- if (nodes == null)
- return;
-
- builder_build(nodes, model, ctx, container, ctr, childs);
- }
- };
-
- }());
-
- // end:source ./01.if.js
- // source ./02.for.js
-
- (function(){
- var FOR_OF_ITEM = 'for..of::item',
- FOR_IN_ITEM = 'for..in::item';
-
- custom_Statements['for'] = {
-
- render: function(node, model, ctx, container, ctr, children){
-
- parse_For(node.expression);
-
- var value = expression_eval(__ForDirective[3], model, ctx, ctr);
- if (value == null)
- return;
-
- build(
- value,
- __ForDirective,
- node.nodes,
- model,
- ctx,
- container,
- ctr,
- children
- );
- },
-
- build: build,
- parseFor: parse_For,
- createForNode: createForItemNode,
- getNodes: getNodes,
-
- getHandler: function(compoName, model){
- return createForItemHandler(compoName, model);
- }
- };
-
- (function(){
- custom_Tags[FOR_OF_ITEM] = createBootstrapCompo(FOR_OF_ITEM);
- custom_Tags[FOR_IN_ITEM] = createBootstrapCompo(FOR_IN_ITEM);
-
- function createBootstrapCompo(name) {
- function For_Item(){}
- For_Item.prototype = {
- meta: {
- serializeScope: true
- },
- serializeScope: for_proto_serializeScope,
- type: Dom.COMPONENT,
- compoName: name,
- renderEnd: handler_proto_renderEnd,
- dispose: handler_proto_dispose
- };
- return For_Item;
- }
- }());
-
-
- function build(value, For, nodes, model, ctx, container, ctr, childs) {
-
- builder_build(
- getNodes(nodes, value, For[0], For[1], For[2], For[3]),
- model,
- ctx,
- container,
- ctr,
- childs
- );
- }
-
- function getNodes(nodes, value, prop1, prop2, type, expr) {
-
- if ('of' === type) {
- if (is_Array(value) === false) {
- log_error(' Value is not enumerable', value);
- return null;
- }
- return loop_Array(nodes, value, prop1, prop2, expr);
- }
-
- if ('in' === type) {
- if (typeof value !== 'object') {
- log_warn(' Value is not an object', value);
- return null;
- }
- if (is_Array(value))
- log_warn(' Consider to use `for..of` for Arrays');
-
- return loop_Object(nodes, value, prop1, prop2, expr);
- }
- }
-
- function loop_Array(template, arr, prop1, prop2, expr){
-
- var i = -1,
- imax = arr.length,
- nodes = new Array(imax),
- scope;
-
- while ( ++i < imax ) {
- scope = {};
- scope[prop1] = arr[i];
-
- if (prop2)
- scope[prop2] = i;
-
- nodes[i] = createForItemNode(
- FOR_OF_ITEM
- , template
- , scope
- , i
- , prop1
- , expr
- );
- }
-
- return nodes;
- }
-
- function loop_Object(template, obj, prop1, prop2, expr){
- var nodes = [],
- i = 0,
- scope, key, value;
-
- for (key in obj) {
- value = obj[key];
- scope = {};
- scope[prop1] = key;
-
- if (prop2)
- scope[prop2] = value;
-
- nodes[i++] = createForItemNode(
- FOR_IN_ITEM
- , template
- , scope
- , key
- , prop2
- , expr
- );
- }
- return nodes;
- }
-
- function createForItemNode(name, nodes, scope, key, propVal, expr) {
- return {
- type: Dom.COMPONENT,
- tagName: name,
- nodes: nodes,
- controller: createForItemHandler(name, scope, key, propVal, expr)
- };
- }
- function createForItemHandler(name, scope, key, propVal, expr) {
- return {
- meta: {
- serializeScope: true,
- },
- compoName: name,
- scope: scope,
- elements: null,
-
- propVal: propVal,
- key: key,
- expression: expr,
-
- renderEnd: handler_proto_renderEnd,
- dispose: handler_proto_dispose,
- serializeScope: for_proto_serializeScope
- };
- }
-
- function handler_proto_renderEnd(elements) {
- this.elements = elements;
- }
- function handler_proto_dispose() {
- if (this.elements)
- this.elements.length = 0;
- }
- function for_proto_serializeScope(scope, model) {
- var ctr = this,
- expr = ctr.expression,
- key = ctr.key,
- propVal = ctr.propVal;
-
-
- var val = scope[propVal];
- if (val != null && typeof val === 'object')
- scope[propVal] = '$ref:(' + expr + ')."' + key + '"';
-
- return scope;
- }
-
-
- var __ForDirective = [ 'prop1', 'prop2', 'in|of', 'expression' ],
- i_PROP_1 = 0,
- i_PROP_2 = 1,
- i_TYPE = 2,
- i_EXPR = 3,
-
- state_prop = 1,
- state_multiprop = 2,
- state_loopType = 3
- ;
-
- var template,
- index,
- length
- ;
-
- function parse_For(expr) {
- // /([\w_$]+)((\s*,\s*([\w_$]+)\s*\))|(\s*\))|(\s+))(of|in)\s+([\w_$\.]+)/
-
- template = expr;
- length = expr.length;
- index = 0;
-
- var prop1,
- prop2,
- loopType,
- hasBrackets,
- c
- ;
-
- c = parser_skipWhitespace();
- if (c === 40) {
- // (
- hasBrackets = true;
- index++;
- parser_skipWhitespace();
- }
-
- prop1 = parser_getVarDeclaration();
-
- c = parser_skipWhitespace();
- if (c === 44) {
- //,
-
- if (hasBrackets !== true) {
- return throw_('Parenthese must be used in multiple var declarion');
- }
-
- index++;
- parser_skipWhitespace();
- prop2 = parser_getVarDeclaration();
- }
-
- if (hasBrackets) {
- c = parser_skipWhitespace();
-
- if (c !== 41)
- return throw_('Closing parenthese expected');
-
- index++;
- }
-
- c = parser_skipWhitespace();
-
- var loopType;
-
- if (c === 105 && template.charCodeAt(++index) === 110) {
- // i n
- loopType = 'in';
- }
-
- if (c === 111 && template.charCodeAt(++index) === 102) {
- // o f
- loopType = 'of';
- }
-
- if (loopType == null) {
- return throw_('Invalid FOR statement. (in|of) expected');
- }
-
- __ForDirective[0] = prop1;
- __ForDirective[1] = prop2;
- __ForDirective[2] = loopType;
- __ForDirective[3] = template.substring(++index);
-
-
- return __ForDirective;
- }
-
- function parser_skipWhitespace(){
- var c;
- for(; index < length; index++ ){
- c = template.charCodeAt(index);
- if (c < 33)
- continue;
-
- return c;
- }
-
- return -1;
- }
-
- function parser_getVarDeclaration(){
- var start = index,
- var_, c;
-
- for (; index < length; index++) {
-
- c = template.charCodeAt(index);
-
- if (c > 48 && c < 57) {
- // 0-9
- if (start === index)
- return throw_('Variable name begins with a digit');
-
- continue;
- }
-
- if (
- (c === 36) || // $
- (c === 95) || // _
- (c >= 97 && c <= 122) || // a-z
- (c >= 65 && c <= 90) // A-Z
- ) {
-
- continue;
- }
-
- break;
- }
-
- if (start === index)
- return throw_('Variable declaration expected');
-
- return template.substring(start, index);
- }
-
- function throw_(message) {
- throw new Error( ' '
- + message
- + ' `'
- + template.substring(index, 20)
- + '`'
- );
- }
-
- }());
-
-
- // end:source ./02.for.js
- // source ./03.each.js
- (function(){
-
- custom_Statements['each'] = {
- render: function(node, model, ctx, container, ctr, children){
-
- var array = expression_eval(node.expression, model, ctx, ctr);
- if (array == null)
- return;
-
- builder_build(
- getNodes(node, array)
- , array
- , ctx
- , container
- , ctr
- , children
- );
- }
- };
-
- function getNodes(node, array){
- var imax = array.length,
- nodes = new Array(imax),
- template = node.nodes,
- expression = node.expression,
- exprPrefix = expression === '.'
- ? '."'
- : '(' + node.expression + ')."',
- i = 0;
- for(; i < imax; i++){
- nodes[i] = createEachNode(template, array[i], exprPrefix, i);
- }
- return nodes;
- }
- function createEachNode(nodes, model, exprPrefix, i){
- return {
- type: Dom.COMPONENT,
- tagName: 'each::item',
- nodes: nodes,
- controller: createEachItemHandler(model, i, exprPrefix)
- };
- }
- function createEachItemHandler(model, i, exprPrefix) {
- return {
- compoName: 'each::item',
- model: model,
- scope: {
- index: i
- },
- modelRef: exprPrefix + i + '"',
- attr: null,
- meta: null
- };
- }
- }());
- // end:source ./03.each.js
- // source ./04.with.js
- custom_Statements['with'] = {
- render: function(node, model, ctx, el, ctr, elements){
- var obj = expression_eval(
- node.expression
- , model
- , ctx
- , ctr
- );
- builder_build(
- node.nodes
- , obj
- , ctx
- , el
- , ctr
- , elements
- );
- }
- };
- // end:source ./04.with.js
- // source ./05.switch.js
- (function(){
- custom_Statements['switch'] = {
- render: function(node, model, ctx, el, ctr, elements){
-
- var value = expression_eval(node.expression, model, ctx, ctr),
- nodes = getNodes(value, node.nodes, model, ctx, ctr);
- if (nodes == null)
- return;
-
- builder_build(nodes, model, ctx, el, ctr, elements);
- },
-
- getNodes: getNodes
- };
-
-
- function getNodes(value, nodes, model, ctx, ctr) {
- if (nodes == null)
- return null;
-
- var imax = nodes.length,
- i = -1,
-
- child, expr,
- case_, default_;
-
- while ( ++i < imax ){
- child = nodes[i];
-
- if (child.tagName === 'default') {
- default_ = child;
- continue;
- }
-
- if (child.tagName !== 'case') {
- log_warn(' Case expected', child.tagName);
- continue;
- }
- expr = child.expression;
- if (!expr) {
- log_warn(' Expression expected');
- continue;
- }
-
- /* jshint eqeqeq: false */
- if (expression_eval(expr, model, ctx, ctr) == value) {
- /* jshint eqeqeq: true */
- case_ = child;
- break;
- }
- }
-
- if (case_ == null)
- case_ = default_;
-
- return case_ != null
- ? case_.nodes
- : null
- ;
- }
-
- }());
-
-
- // end:source ./05.switch.js
- // source ./09.visible.js
- (function(){
- custom_Statements['visible'] = {
- toggle: toggle,
- render: function(node, model, ctx, container, ctr, children){
- var els = [];
- builder_build(node.nodes, model, ctx, container, ctr, els);
- arr_pushMany(children, els)
-
- var visible = expression_eval(node.expression, model, ctx, ctr);
- toggle(els, visible);
- }
- };
- function toggle(els, visible){
- for(var i = 0; i < els.length; i++){
- els[i].style.display = visible ? '' : 'none';
- }
- }
- }());
-
- // end:source ./09.visible.js
- // source ./10.repeat.js
- (function(){
- custom_Statements['repeat'] = {
- render: function(node, model, ctx, container, ctr, children){
- var run = expression_eval,
- str = node.expression,
- repeat = str.split('..'),
- index = + run(repeat[0] || '', model, ctx, ctr),
- length = + run(repeat[1] || '', model, ctx, ctr);
-
- if (index !== index || length !== length) {
- log_error('Repeat attribute(from..to) invalid', str);
- return;
- }
-
- var nodes = node.nodes;
- var arr = [];
- var i = -1;
- while (++i < length) {
- arr[i] = compo_init(
- 'repeat::item',
- nodes,
- model,
- i,
- container,
- ctr
- );
- }
-
- var els = [];
- builder_build(arr, model, ctx, container, ctr, els);
- arr_pushMany(children, els);
- }
- };
-
- function compo_init(name, nodes, model, index, container, parent) {
- return {
- type: Dom.COMPONENT,
- compoName: name,
- attr: {},
- nodes: nodes,
- model: model,
- container: container,
- parent: parent,
- index: index,
- scope: {
- index: index
- }
- };
- }
- }());
-
- // end:source ./10.repeat.js
- // end:source statements/
- // source formatter/stringify_stream
- var mask_stringify,
- mask_stringifyAttr;
- (function () {
-
- var defaultOptions = {
- minify: true,
- indent: 4,
- indentChar: ' '
- };
-
- /**
- * Serialize Mask AST to the Mask string (@analog to `JSON.stringify`)
- * @param {MaskNode} node - MaskNode
- * @param {(object|number)} [opts] - Indent count option or an object with options
- * @param {number} [opts.indent=0] - Indent count, `0` for minimization
- * @param {bool} [opts.minify=true]
- * @param {bool} [opts.minimizeAttributes=true] - Remove quotes when possible
- * @returns {string}
- * @memberOf mask
- * @method stringify
- */
- mask_stringify = function(input, opts) {
- if (input == null)
- return '';
-
- if (typeof input === 'string')
- input = parser_parse(input);
-
- if (opts == null) {
- opts = obj_create(defaultOptions);
- } else if (typeof opts === 'number'){
- var indent = opts;
- opts = obj_create(defaultOptions);
- opts.indent = indent;
- opts.minify = indent === 0;
- } else{
- opts = obj_extendDefaults(opts, defaultOptions);
- if (opts.indent > 0) {
- opts.minify = false;
- }
- if (opts.minify === true) {
- opts.indent = 0;
- }
- }
-
- return new Stream(input, opts).toString();
- };
-
- mask_stringifyAttr = function(attr){
- var str = '',
- key, x, part;
- for (key in attr) {
- x = getString(attr[key]);
-
- if (str.length !== 0) {
- str += ' ';
- }
- str += key;
-
- if (x !== key) {
- str += "=" + wrapString(x);
- }
- }
- return str;
- };
-
- var Stream = class_create({
- string: '',
- indent: 0,
- indentStr: '',
- minify: false,
- opts: null,
- ast : null,
- constructor: function(ast, opts) {
- this.opts = opts;
- this.ast = ast;
- this.minify = opts.minify;
- this.indentStr = doindent(opts.indent, opts.indentChar);
- },
- toString: function(){
- this.process(this.ast, this);
- return this.string;
- },
- process: function(mix){
- if (mix.type === Dom.FRAGMENT) {
- mix = mix.nodes;
- }
- if (is_ArrayLike(mix)) {
- var imax = mix.length,
- i = -1;
- while ( ++i < imax ){
- if (i !== 0) {
- this.newline();
- }
- this.processNode(mix[i]);
- }
- return;
- }
- this.processNode(mix);
- },
- processNode: function(node) {
- var stream = this;
- if (is_Function(node.stringify)) {
- var str = node.stringify(stream);
- if (str != null) {
- stream.write(str);
- }
- return;
- }
- if (is_String(node.content)) {
- stream.write(wrapString(node.content));
- return;
- }
- if (is_Function(node.content)){
- stream.write(wrapString(node.content()));
- return;
- }
-
- this.processHead(node);
-
- if (isEmpty(node)) {
- stream.print(';');
- return;
- }
- if (isSingle(node)) {
- stream.openBlock('>');
- stream.processNode(getSingle(node));
- stream.closeBlock(null);
- return;
- }
-
- stream.openBlock('{');
- stream.process(node.nodes);
- stream.closeBlock('}');
- },
- processHead: function(node) {
- var stream = this,
- str = '',
- id, cls, expr
- ;
-
- var attr = node.attr;
- if (attr != null) {
- id = attr.id;
- cls = attr['class'];
- if (typeof id === 'function') {
- id = id();
- }
- if (id != null && id.indexOf(' ') !== -1) {
- id = null;
- }
- if (id != null) {
- str += '#' + id;
- }
- if (typeof cls === 'function') {
- cls = cls();
- }
- if (cls != null) {
- str += '.' + cls.trim().replace(/\s+/g, '.');
- }
-
- for(var key in attr) {
- if (key === 'id' && id != null) {
- continue;
- }
- if (key === 'class' && cls != null) {
- continue;
- }
- var val = attr[key];
- if (val == null) {
- continue;
- }
-
- str += ' ' + key;
- if (val === key) {
- continue;
- }
-
- if (is_Function(val)) {
- val = val();
- }
- if (is_String(val)) {
- if (stream.minify === false || /[^\w_$\-\.]/.test(val)){
- val = wrapString(val);
- }
- }
-
- str += '=' + val;
- }
- }
-
- if (isTagNameOptional(node, id, cls) === false) {
- str = node.tagName + str;
- }
-
- var expr = node.expression;
- if (expr != null) {
- if (typeof expr === 'function') {
- expr = expr();
- }
- if (stream.minify === false) {
- str += ' ';
- }
- str += '(' + expr + ')';
- }
-
- if (this.minify === false) {
- str = doindent(this.indent, this.indentStr) + str;
- }
- stream.print(str);
- },
-
- newline: function(){
- if (this.minify === false) {
- this.string += '\n';
- }
- },
- openBlock: function(c){
- this.indent++;
- if (this.minify === false) {
- this.string += ' ' + c + '\n';
- return;
- }
- this.string += c;
- },
- closeBlock: function(c){
- this.indent--;
- if (c != null) {
- this.newline();
- this.write(c);
- }
- },
- write: function(str){
- if (this.minify === true) {
- this.string += str;
- return;
- }
- var prfx = doindent(this.indent, this.indentStr);
- this.string += str.replace(/^/gm, prfx);
- },
- print: function(str){
- this.string += str;
- }
- });
-
- function doindent(count, c) {
- var output = '';
- while (count--) {
- output += c;
- }
- return output;
- }
-
- function isEmpty(node) {
- return node.nodes == null || (is_ArrayLike(node.nodes) && node.nodes.length === 0);
- }
-
- function isSingle(node) {
- var arr = node.nodes;
- if (arr == null) {
- return true;
- }
- var isArray = typeof arr.length === 'number';
- if (isArray && arr.length > 1) {
- return false;
- }
- var x = isArray ? arr[0] : arr;
- return x.stringify == null;
- }
- function isTagNameOptional(node, id, cls) {
- if (id == null && cls == null) {
- return false;
- }
- var tagName = node.tagName;
- if (tagName === 'div') {
- return true;
- }
- return false;
- }
- function getSingle(node) {
- if (is_ArrayLike(node.nodes))
- return node.nodes[0];
-
- return node.nodes;
- }
-
- function wrapString(str) {
- if (str.indexOf("'") === -1)
- return "'" + str + "'";
-
- if (str.indexOf('"') === -1)
- return '"' + str + '"';
-
- return '"' + str.replace(/"/g, '\\"') + '"';
- }
-
- function getString(mix) {
- return is_Function(mix) ? mix() : mix;
- }
-
- }());
-
- // end:source formatter/stringify_stream
- // source feature/
- // source run
- var mask_run;
- (function(){
- /**
- * Find all `");
- }
-
- ready = true;
- if (await === 0) {
- flush();
- }
- function resumer(){
- if (--await === 0 && ready)
- flush();
- }
- function flush() {
- if (is_Function(ctr.renderEnd)) {
- ctr.renderEnd(container, model);
- }
- Compo.signal.emitIn(ctr, 'domInsert');
- }
-
- return ctr;
- }
-
- function _insertDelegate(fragment, script, done) {
- return function(){
- script.parentNode.insertBefore(fragment, script);
- done();
- };
- }
-
- if (document != null && document.addEventListener) {
- document.addEventListener("DOMContentLoaded", function(event) {
- if (_state !== 0) return;
- var _app;
- _state = _state_Auto;
- _app = mask_run();
- _state = _state_Manual;
-
- if (_app == null) return;
- if (global.app == null) {
- global.app = _app;
- return;
- }
- var source = _app.components
- if (source == null || source.length === 0) {
- return;
- }
- var target = global.app.components
- if (target == null || target.length === 0) {
- global.app.components = source;
- return;
- }
- target.push.apply(target, source);
- });
- }
-
- var _state_Auto = 2,
- _state_Manual = 4,
- _state_All = _state_Auto | _state_Manual,
- _state = 0;
-
- function isCurrent(state) {
- return (_state & state) === state;
- }
- }());
- // end:source run
- // source merge
- var mask_merge;
- (function(){
- /**
- * Join two Mask templates or DOM trees
- * @param {(string|MaskNode)} a - first template
- * @param {(string|MaskNode)} b - second template
- * @param {(MaskNode|Component)} [owner]
- * @param {object} [opts]
- * @param {bool} [opts.extending=false] - Clean the merged tree from all unused placeholders
- * @returns {MaskNode} New joined Mask DOM tree
- * @memberOf mask
- * @method merge
- */
- mask_merge = function(a, b, owner, opts){
- if (typeof a === 'string') {
- a = parser_parse(a);
- }
- if (typeof b === 'string') {
- b = parser_parse(b);
- }
- if (a == null || (is_ArrayLike(a) && a.length === 0)) {
- return b;
- }
-
- var placeholders = _resolvePlaceholders(b, b, new Placeholders(null, b, opts));
- var out = _merge(a, placeholders, owner);
- var extra = placeholders.$extra;
- if (extra != null && extra.length !== 0) {
- if (is_Array(out)) {
- return out.concat(extra);
- }
- return [ out ].concat(extra);
- }
- return out;
- };
-
- var tag_ELSE = '@else',
- tag_IF = '@if',
- tag_EACH = '@each',
- tag_PLACEHOLDER = '@placeholder',
-
- dom_NODE = Dom.NODE,
- dom_TEXTNODE = Dom.TEXTNODE,
- dom_FRAGMENT = Dom.FRAGMENT,
- dom_STATEMENT = Dom.STATEMENT,
- dom_COMPONENT = Dom.COMPONENT
- ;
-
- function _merge(node, placeholders, tmplNode, clonedParent){
- if (node == null)
- return null;
-
- var fn;
- if (is_Array(node)) {
- fn = _mergeArray;
- } else {
- switch(node.type){
- case dom_TEXTNODE:
- fn = _cloneTextNode;
- break;
- case dom_NODE:
- case dom_STATEMENT:
- fn = _mergeNode;
- break;
- case dom_FRAGMENT:
- fn = _mergeFragment;
- break;
- case dom_COMPONENT:
- fn = _mergeComponent;
- break;
- }
- }
- if (fn !== void 0) {
- return fn(node, placeholders, tmplNode, clonedParent);
- }
- log_warn('Uknown type', node.type);
- return null;
- }
- function _mergeArray(nodes, placeholders, tmplNode, clonedParent){
- if (nodes == null) {
- return null;
- }
- var fragment = [],
- imax = nodes.length,
- i = -1,
- x, node;
- while( ++i < imax ) {
- node = nodes[i];
-
- if (node.tagName === tag_ELSE) {
- // check previous
- if (x != null)
- continue;
-
- if (node.expression && !eval_(node.expression, placeholders, tmplNode))
- continue;
-
- x = _merge(nodes[i].nodes, placeholders, tmplNode, clonedParent)
- }
- else {
- x = _merge(node, placeholders, tmplNode, clonedParent);
- }
-
- appendAny(fragment, x);
- }
- return fragment;
- }
- function _mergeFragment(frag, placeholders, tmplNode, clonedParent) {
- var fragment = new Dom.Fragment;
- fragment.parent = clonedParent;
- fragment.nodes = _mergeArray(frag.nodes, placeholders, tmplNode, fragment);
- return fragment;
- }
- function _mergeComponent(node, placeholders, tmplNode, clonedParent) {
- if (node.nodes == null)
- return node;
-
- var cloned = new Dom.Component;
- obj_extend(cloned, node);
- cloned.nodes = _merge(cloned.nodes, placeholders, tmplNode, clonedParent);
- return cloned;
- }
- function _mergeNode(node, placeholders, tmplNode, clonedParent){
- var tagName = node.tagName;
- if (tagName.charCodeAt(0) !== 64) {
- // @
- return _cloneNode(node, placeholders, tmplNode, clonedParent);
- }
-
- var id = node.attr.id;
- if (tagName === tag_PLACEHOLDER && id == null) {
- if (tmplNode != null) {
- var tagName_ = tmplNode.tagName;
- if (tagName_ != null && tmplNode.tagName.charCodeAt(0) === 64 /*@*/) {
- return tmplNode.nodes
- }
- }
- id = '$root';
- placeholders.$extra = null;
- }
-
- if (tag_EACH === tagName) {
- var arr = placeholders.$getNode(node.expression),
- x;
- if (arr == null) {
- if (node.attr.optional == null) {
- error_withNode('No template node: @' + node.expression, node);
- }
- return null;
- }
- if (is_Array(arr) === false) {
- x = arr;
- return _merge(
- node.nodes
- , _resolvePlaceholders(x.nodes, x.nodes, new Placeholders(placeholders))
- , x
- , clonedParent
- );
- }
- var fragment = new Dom.Fragment,
- imax = arr.length,
- i = -1;
- while ( ++i < imax ){
- x = arr[i];
- appendAny(fragment, _merge(
- node.nodes
- , _resolvePlaceholders(x.nodes, x.nodes, new Placeholders(placeholders))
- , x
- , clonedParent
- ));
- }
- return fragment;
- }
- if (tag_IF === tagName) {
- var val = eval_(node.expression, placeholders, tmplNode);
- return val
- ? _merge(node.nodes, placeholders, tmplNode, clonedParent)
- : null
- ;
- }
-
- if (id == null)
- id = tagName.substring(1);
-
- var content = placeholders.$getNode(id, node.expression);
- if (content == null) {
- if (placeholders.opts.extending === true) {
- return node;
- }
- return null;
- }
-
- if (content.parent)
- _modifyParents(clonedParent, content.parent);
-
-
- var contentNodes = content.nodes,
- wrapperNode;
- if (node.attr.as !== void 0) {
- var tagName_ = node.attr.as;
- wrapperNode = {
- type: dom_NODE,
- tagName: tagName_,
- attr: _mergeAttr(node.attr, content.attr, placeholders, tmplNode),
- parent: clonedParent,
- nodes: contentNodes
- };
- wrapperNode.attr.as = null;
- }
-
- if (node.nodes == null) {
- return _merge((wrapperNode || contentNodes), placeholders, tmplNode, clonedParent);
- }
-
- var nodes = _merge(
- node.nodes
- , _resolvePlaceholders(contentNodes, contentNodes, new Placeholders(placeholders))
- , content
- , wrapperNode || clonedParent
- );
- if (wrapperNode != null) {
- wrapperNode.nodes = nodes;
- return wrapperNode;
- }
- return nodes;
- }
- function _mergeAttr(a, b, placeholders, tmplNode){
- if (a == null || b == null)
- return a || b;
-
- var out = interpolate_obj_(a, placeholders, tmplNode);
- for (var key in b){
- out[key] = interpolate_str_(b[key], placeholders, tmplNode);
- }
- return out;
- }
-
- function _cloneNode(node, placeholders, tmplNode, clonedParent){
- var tagName = node.tagName || node.compoName;
- switch (tagName) {
- case ':template':
- var id = interpolate_str_(node.attr.id, placeholders, tmplNode);
- Mask.templates.register(id, node.nodes);
- return null;
- case ':import':
- var id = interpolate_str_(node.attr.id, placeholders, tmplNode),
- nodes = Mask.templates.resolve(node, id);
- return _merge(nodes, placeholders, tmplNode, clonedParent);
- case 'define':
- case 'function':
- case 'var':
- case 'import':
- case 'script':
- case 'style':
- case 'slot':
- case 'event':
- return node;
- case 'include':
- var tagName = node.attr.id;
- if (tagName == null) {
- tagName = attr_first(node.attr);
- }
- tagName = interpolate_str_(tagName, placeholders, tmplNode);
-
- var handler = customTag_get(tagName, tmplNode);
- if (handler != null) {
- var proto = handler.prototype;
- var tmpl = proto.template || proto.nodes;
-
- placeholders = _resolvePlaceholders(
- node.nodes,
- node.nodes,
- new Placeholders(placeholders, node.nodes)
- );
- return _merge(tmpl, placeholders, tmplNode, clonedParent);
- }
- break;
- default:
- var handler = customTag_get(tagName, tmplNode);
- if (handler != null) {
- var proto = handler.prototype;
- if (proto && proto.meta != null && proto.meta.template === 'merge') {
- return node;
- }
- }
- break;
- }
-
- var outnode = {
- type: node.type,
- tagName: tagName,
- attr: interpolate_obj_(node.attr, placeholders, tmplNode),
- expression: interpolate_str_(node.expression, placeholders, tmplNode),
- controller: node.controller,
- parent: clonedParent,
- nodes: null
- };
- if (node.nodes)
- outnode.nodes = _merge(node.nodes, placeholders, tmplNode, outnode);
-
- return outnode;
- }
- function _cloneTextNode(node, placeholders, tmplNode, clonedParent){
- return {
- type: node.type,
- content: interpolate_str_(node.content, placeholders, tmplNode),
- parent: clonedParent
- };
- }
- function interpolate_obj_(obj, placeholders, node){
- var clone = _Object_create(obj),
- x;
- for(var key in clone){
- x = clone[key];
- if (x == null)
- continue;
-
- clone[key] = interpolate_str_(x, placeholders, node);
- }
- return clone;
- }
- function interpolate_str_(mix, placeholders, node){
- var index = -1,
- isFn = false,
- str = mix;
-
- if (typeof mix === 'function') {
- isFn = true;
- str = mix();
- }
- if (typeof str !== 'string' || (index = str.indexOf('@')) === -1)
- return mix;
-
- var result = str.substring(0, index),
- length = str.length,
- isBlockEntry = str.charCodeAt(index + 1) === 91, // [
- last = -1,
- c;
-
- while (index < length) {
- // interpolation
- last = index;
- if (isBlockEntry === true) {
- index = str.indexOf(']', last);
- if (index === -1)
- index = length;
- last += 2;
- }
- else {
- while (index < length) {
- c = str.charCodeAt(++index);
- if (c === 36 || c === 95 || c === 46) {
- // $ _ .
- continue;
- }
- if ((48 <= c && c <= 57) || // 0-9
- (65 <= c && c <= 90) || // A-Z
- (97 <= c && c <= 122)) { // a-z
- continue;
- }
- break;
- }
- }
-
- var expr = str.substring(last, index),
- fn = isBlockEntry ? eval_ : interpolate_,
- x = fn(expr, placeholders, node);
-
- if (x != null) {
- result += x;
- }
- else if (placeholders.opts.extending === true) {
- result += isBlockEntry ? ('@[' + expr + ']') : expr
- }
-
- // tail
- last = isBlockEntry ? (index + 1) : index;
- index = str.indexOf('@', index);
- if (index === -1)
- index = length;
-
- result += str.substring(last, index);
- }
-
- return isFn
- ? parser_ensureTemplateFunction(result)
- : result
- ;
- }
- function interpolate_(path, placeholders, node) {
- var index = path.indexOf('.');
- if (index === -1) {
- log_warn('Merge templates. Accessing node', path);
- return null;
- }
- var tagName = path.substring(0, index),
- id = tagName.substring(1),
- property = path.substring(index + 1),
- obj = null;
-
- if (node != null) {
- if (tagName === '@attr') {
- return interpolate_getAttr_(node, placeholders, property);
- }
- else if (tagName === '@counter') {
- return interpolate_getCounter_(property);
- }
- else if (tagName === node.tagName)
- obj = node;
- }
-
- if (obj == null)
- obj = placeholders.$getNode(id);
-
- if (obj == null) {
- //- log_error('Merge templates. Node not found', tagName);
- return null;
- }
- return obj_getProperty(obj, property);
- }
-
- function interpolate_getAttr_(node, placeholders, prop) {
- var x = node.attr && node.attr[prop];
- var el = placeholders;
- while (x == null && el != null) {
- x = el.attr && el.attr[prop];
- el = el.parent;
- }
- return x;
- }
-
- var interpolate_getCounter_;
- (function(){
- var _counters = {};
- interpolate_getCounter_ = function(prop) {
- var i = _counters[prop] || 0;
- return (_counters[prop] = ++i);
- };
- }());
-
- function appendAny(node, mix){
- if (mix == null)
- return;
- if (typeof mix.concat === 'function') {
- var imax = mix.length;
- for (var i = 0; i < imax; i++) {
- appendAny(node, mix[i]);
- }
- return;
- }
- if (mix.type === dom_FRAGMENT) {
- appendAny(node, mix.nodes);
- return;
- }
-
- if (typeof node.appendChild === 'function') {
- node.appendChild(mix);
- return;
- }
-
- var l = node.length;
- if (l > 0) {
- var prev = node[l - 1];
- prev.nextSibling = mix;
- }
- node.push(mix);
- }
-
- var RESERVED = ' else placeholder each attr if parent scope'
- function _resolvePlaceholders(root, node, placeholders) {
- if (node == null)
- return placeholders;
-
- if (is_Array(node)) {
- var imax = node.length,
- i = -1;
- while( ++i < imax ){
- _resolvePlaceholders(node === root ? node[i] : root, node[i], placeholders);
- }
- return placeholders;
- }
-
- var type = node.type;
- if (type === dom_TEXTNODE)
- return placeholders;
-
- if (type === dom_NODE) {
- var tagName = node.tagName;
- if (tagName != null && tagName.charCodeAt(0) === 64) {
- // @
- placeholders.$count++;
- var id = tagName.substring(1);
- // if DEBUG
- if (RESERVED.indexOf(' ' + id + ' ') !== -1)
- log_error('MaskMerge. Reserved Name', id);
- // endif
- var x = {
- tagName: node.tagName,
- parent: _getParentModifiers(root, node),
- nodes: node.nodes,
- attr: node.attr,
- expression: node.expression
- };
- if (placeholders[id] == null) {
- placeholders[id] = x;
- } else {
- var current = placeholders[id];
- if (is_Array(current)) {
- current.push(x);
- }
- else {
- placeholders[id] = [current, x];
- }
- }
- return placeholders;
- }
- }
-
- var count = placeholders.$count;
- var out = _resolvePlaceholders(root, node.nodes, placeholders);
- if (root === node && count === placeholders.$count) {
- placeholders.$extra.push(root);
- }
- return out;
- }
- function _getParentModifiers(root, node) {
- if (node === root)
- return null;
-
- var current, parents, parent = node.parent;
- while (true) {
- if (parent == null)
- break;
- if (parent === root && root.type !== dom_NODE)
- break;
-
- var p = {
- type: parent.type,
- tagName: parent.tagName,
- attr: parent.attr,
- controller: parent.controller,
- expression: parent.expression,
- nodes: null,
- parent: null
- };
-
- if (parents == null) {
- current = parents = p;
- } else {
- current.parent = p;
- current = p;
- }
- parent = parent.parent;
- }
- return parents;
- }
- function _modifyParents(clonedParent, parents){
- var nodeParent = clonedParent, modParent = parents;
- while(nodeParent != null && modParent != null){
-
- if (modParent.tagName)
- nodeParent.tagName = modParent.tagName;
-
- if (modParent.expression)
- nodeParent.expression = modParent.expression;
-
- for(var key in modParent.attr){
- nodeParent.attr[key] = modParent.attr[key];
- }
-
- nodeParent = nodeParent.parent;
- modParent = modParent.parent;
- }
- }
-
- function eval_(expr, placeholders, tmplNode) {
- if (tmplNode != null) {
- placeholders.attr = tmplNode.attr;
- }
- return expression_eval(expr, placeholders, null, placeholders);
- }
- function Placeholders(parent, nodes, opts){
- var $root = null;
- if (nodes != null) {
- $root = new Dom.Node(tag_PLACEHOLDER);
- $root.nodes = nodes;
- }
- this.scope = this;
- this.parent = parent;
- this.$root = $root || (parent && parent.$root);
- this.$extra = [];
-
- if (opts != null) {
- this.opts = opts;
- }
- else if (parent != null) {
- this.opts = parent.opts;
- }
- }
- Placeholders.prototype = {
- opts: {
- extending: false
- },
- parent: null,
- attr: null,
- scope: null,
- $root: null,
- $extra: null,
- $count: 0,
- $getNode: function(id, filter){
- var ctx = this, node;
- while(ctx != null){
- node = ctx[id];
- if (node != null)
- break;
- ctx = ctx.parent;
- }
- if (filter != null && node != null) {
- node = {
- nodes: jmask(node.nodes).filter(filter)
- };
- }
- return node;
- }
- };
-
- }());
- // end:source merge
- // source optimize
- var mask_optimize,
- mask_registerOptimizer;
- (function(){
- /**
- * Run all registerd optimizers recursively on the nodes
- * @param {MaskNode} node
- * @param {function} onComplete
- * @param {mask.optimize~onComplete} done
- */
- mask_optimize = function (dom, done) {
- mask_TreeWalker.walkAsync(
- dom
- , function (node, next) {
- var fn = getOptimizer(node);
- if (fn != null) {
- fn(node, next);
- return;
- }
- next();
- }
- , done
- );
- };
-
- /**
- * Register custom optimizer for a node name
- * @param {string} tagName - Node name
- * @param {function} visitor - Used for @see {@link mask.TreeWalker.walkSync}
- */
- mask_registerOptimizer = function(tagName, fn){
- custom_Optimizers[tagName] = fn;
- };
-
- function getOptimizer(node) {
- if (node.type !== Dom.NODE)
- return null;
-
- return custom_Optimizers[node.tagName];
- }
-
-
- /**
- * Returns optimized mask tree
- * @callback mask.optimize~onComplete
- * @param {MaskNode} node
- */
- }());
- // end:source optimize
- // source modules/
- var Module;
- (function(){
- Module = {};
- var _cache = {},
- _extensions_script = ' js es6 test coffee ',
- _extensions_style = ' css sass scss less ',
- _extensions_data = ' json ',
- _opts = {
- base: null,
- version: null
- };
-
- // source utils
- var u_resolveLocation,
- u_resolvePath,
- u_resolvePathFromImport,
- u_handler_getDelegate;
-
- (function(){
-
- u_resolveLocation = function(ctx, ctr, module) {
- if (module != null) {
- return module.location;
- }
- while(ctr != null) {
- if (ctr.location != null) {
- return ctr.location;
- }
- if (ctr.resource != null && ctr.resource.location) {
- return ctr.resource.location;
- }
- ctr = ctr.parent;
- }
- var path = null;
- if (ctx != null) {
- if (ctx.filename != null) {
- path = path_getDir(path_normalize(ctx.filename));
- }
- if (ctx.dirname != null) {
- path = path_normalize(ctx.dirname + '/');
- }
- }
-
- if (_opts.base == null) {
- _opts.base = path_resolveCurrent();
- }
-
- if (path != null) {
- if (path_isRelative(path) === false) {
- return path;
- }
- return path_combine(_opts.base, path);
- }
- return _opts.base;
- };
-
- u_resolvePath = function(path, ctx, ctr, module){
- if ('' === path_getExtension(path)) {
- path += '.mask';
- }
- if (path_isRelative(path) === false) {
- return path;
- }
- return path_normalize(path_combine(
- u_resolveLocation(ctx, ctr, module), path
- ));
- };
-
- u_resolvePathFromImport = function(node, ctx, ctr, module){
- var path = node.path;
- if ('' === path_getExtension(path)) {
- var type = node.contentType;
- if (type == null || type === 'mask' ) {
- path += '.mask';
- }
- }
- if (path_isRelative(path) === false) {
- return path;
- }
- return path_normalize(path_combine(
- u_resolveLocation(ctx, ctr, module), path
- ));
- };
-
-
- u_handler_getDelegate = function(compoName, compo, next) {
- return function(name) {
- if (name === compoName)
- return compo;
- if (next != null)
- return next(name);
-
- return null;
- };
- };
-
-
- }());
-
- // end:source utils
- // source loaders
- var _file_get,
- _file_getScript,
- _file_getStyle,
- _file_getJson;
-
- (function(){
-
- _file_get = createTransport(function(){
- return __cfg.getFile || file_get;
- });
- _file_getScript = createTransport(function(){
- return __cfg.getScript || file_getScript;
- });
- _file_getStyle = createTransport(function(){
- return __cfg.getStyle || file_getStyle;
- });
- _file_getJson = createTransport(function(){
- return __cfg.getData || file_getJson;
- });
-
-
- listeners_on('config', function (config) {
- var modules = config.modules;
- if (modules == null) {
- return;
- }
- var fn = Loaders[modules];
- if (is_Function(fn) === false) {
- log_warn('Module system is not supported: ' + modules);
- return;
- }
- fn();
- });
-
- function createTransport(loaderFactoryFn) {
- return function(path_){
- var fn = loaderFactoryFn(),
- path = path_,
- v = _opts.version;
- if (v != null) {
- path = path_appendQuery(path, 'v', v);
- }
- return fn(path);
- };
- }
-
- var Loaders = {
- 'default': function () {
- __cfg.getScript = __cfg.getFile = null;
- },
- 'include': function () {
- __cfg.getScript = getter('js');
- __cfg.getFile = getter('load');
-
- var lib = include;
- function getter(name) {
- return function(path){
- return class_Dfr.run(function(resolve, reject){
- lib.instance('/')[name](path + '::Module').done(function(resp){
- var exports = name === 'js'
- ? resp.Module
- : resp[name].Module;
-
- resolve(exports);
- });
- });
- }
- }
- }
- };
-
- if (typeof include !== 'undefined' && is_Function(include && include.js)) {
- mask_config('modules', 'include');
- }
- }());
- // end:source loaders
-
- // source class/Endpoint
- function Endpoint (path, contentType) {
- this.path = path;
- this.contentType = contentType;
- }
- // end:source class/Endpoint
- // source Import/Import
- var IImport = class_create({
- type: null,
- contentType: null,
- constructor: function(path, alias, exports, module){
- this.path = path;
- this.alias = alias;
- this.exports = exports;
-
- var endpoint = new Endpoint(path, this.contentType);
- this.module = Module.createModule(endpoint, module);
- this.parent = module;
- },
- eachExport: function(fn){
- var alias = this.alias;
- if (alias != null) {
- fn.call(this, alias, '*', alias);
- return;
- }
- var exports = this.exports
- if (exports != null) {
- var imax = exports.length,
- i = -1;
- while(++i < imax) {
- var x = exports[i];
- fn.call(
- this
- , x.alias == null ? x.name : x.alias
- , x.name
- , x.alias
- );
- }
- }
- },
-
- hasExport: function(name) {
- if (this.alias === name) {
- return true;
- }
- var exports = this.exports
- if (exports != null) {
- var imax = exports.length,
- i = -1;
- while(++i < imax) {
- var x = exports[i];
- var expName = x.alias == null ? x.name : x.alias;
- if (expName === name) {
- return true;
- }
- }
- }
- return false;
- },
-
- getOriginal: function(alias){
- if (this.alias === alias) {
- return '*';
- }
- var exports = this.exports;
- if (exports != null) {
- var imax = exports.length,
- i = -1, x;
- while(++i < imax) {
- x = exports[i];
- if ((x.alias || x.name) === alias) {
- return x.name;
- }
- }
- }
- return null;
- },
-
- loadImport: function(cb){
- var self = this;
- this
- .module
- .loadModule()
- .fail(cb)
- .done(function(module){
- cb(null, self);
- });
- },
-
- registerScope: null,
-
- logError_: function(msg){
- var str = '\n(Module) ' + (this.parent || {path: 'root'}).path
- str += '\n (Import) ' + this.path
- str += '\n ' + msg;
- log_error(str);
- }
- });
-
-
- (function(){
- IImport.create = function(endpoint, alias, exports, parent){
- return new (Factory(endpoint))(endpoint.path, alias, exports, parent);
- };
- function Factory(endpoint) {
- var type = endpoint.contentType;
- var ext = type || path_getExtension(endpoint.path);
- if (ext === 'mask') {
- return ImportMask;
- }
- if (ext === 'html') {
- return ImportHtml;
- }
- var search = ' ' + ext + ' ';
- if (_extensions_style.indexOf(search) !== -1) {
- return ImportStyle;
- }
- if (_extensions_data.indexOf(search) !== -1) {
- return ImportData;
- }
- // assume script, as anything else is not supported yet
- return ImportScript;
- }
- }());
- // end:source Import/Import
- // source Import/ImportMask
- var ImportMask = class_create(IImport, {
- type: 'mask',
- contentType: 'mask',
- constructor: function(){
- this.eachExport(function(compoName){
- if (compoName !== '*')
- customTag_registerResolver(compoName);
- });
- },
- getHandler: function(name){
- var module = this.module;
- if (module == null) {
- return;
- }
- if (module.error != null) {
- if (this.hasExport(name)) {
- this.logError_('Resource for the import `' + name + '` not loaded');
- return this.empty;
- }
- return null
- }
- var orig = this.getOriginal(name);
- if (orig == null) {
- return null;
- }
- return module.exports[orig] || module.queryHandler(orig);
- },
- empty: function EmptyCompo () {}
- });
- // end:source Import/ImportMask
- // source Import/ImportScript
- var ImportScript = class_create(IImport, {
- type: 'script',
- contentType: 'script',
- registerScope: function(owner){
- this.eachExport(function(exportName, name, alias){
- var obj = this.module.register(owner, name, alias);
- if (obj == null) {
- this.logError_('Exported property is undefined: ' + name);
- }
- });
- }
- });
- // end:source Import/ImportScript
- // source Import/ImportStyle
- var ImportStyle = class_create(IImport, {
- type: 'style',
- contentType: 'css'
- });
- // end:source Import/ImportStyle
- // source Import/ImportData
- var ImportData = class_create(ImportScript, {
- type: 'data',
- contentType: 'json'
- });
- // end:source Import/ImportData
- // source Import/ImportHtml
- var ImportHtml = class_create(ImportMask, {
- type: 'mask',
- contentType: 'html'
- });
- // end:source Import/ImportHtml
-
- // source Module/Module
- var IModule = class_create(class_Dfr, {
- type: null,
- path: null,
- location: null,
- exports: null,
- state: 0,
- constructor: function(path, parent) {
- this.path = path;
- this.parent = parent;
- this.exports = {};
- this.location = path_getDir(path);
- this.complete_ = this.complete_.bind(this);
- },
- loadModule: function(){
- if (this.state !== 0)
- return this;
-
- this.state = 1;
- var self = this;
- this
- .load_(this.path)
- .fail(function(err){
- self.onLoadError_(err);
- })
- .done(function(mix){
- self.onLoadSuccess_(mix);
- });
- return this;
- },
- complete_: function(error, exports){
- this.exports = exports;
- this.error = error;
- this.state = 4;
- if (error) {
- this.reject(error);
- return;
- }
- this.resolve(this);
- },
- onLoadSuccess_: function(mix){
- if (this.preprocess_ == null) {
- this.complete_(null, mix);
- return;
- }
- this.preprocess_(mix, this.complete_);
- },
- onLoadError_: function(error){
- if (this.preprocessError_ == null) {
- this.complete_(error);
- return;
- }
- this.preprocessError_(error, this.complete_);
- },
- load_: null,
- preprocess_: null,
- preprocessError_: null,
- register: fn_doNothing,
- });
-
- (function(){
- IModule.create = function(endpoint, parent, contentType){
- return new (Factory(endpoint))(endpoint.path, parent);
- };
- function Factory(endpoint) {
- var type = endpoint.contentType;
- var ext = type || path_getExtension(endpoint.path);
- if (ext === 'mask') {
- return ModuleMask;
- }
- var search = ' ' + ext + ' ';
- if (_extensions_style.indexOf(search) !== -1) {
- return ModuleStyle;
- }
- if (_extensions_data.indexOf(search) !== -1) {
- return ModuleData;
- }
- if (ext === 'html') {
- return ModuleHtml;
- }
- // assume script, as anything else is not supported yet
- return ModuleScript;
- }
- }());
-
- // end:source Module/Module
- // source Module/ModuleMask
- var ModuleMask;
- (function(){
- ModuleMask = class_create(IModule, {
- type: 'mask',
- scope: null,
- source: null,
- modules: null,
- exports: null,
- imports: null,
-
- load_: _file_get,
- preprocessError_: function(error, next) {
- var msg = 'Load error: ' + this.path;
- if (error && error.status) {
- msg += '; Status: ' + error.status;
- }
-
- this.source = reporter_createErrorNode(msg);
- next.call(this, error);
- },
- preprocess_: function(mix, next) {
- var ast = typeof mix === 'string'
- ? parser_parse(mix)
- : mix
- ;
-
- this.scope = {};
- this.source = ast;
- this.imports = [];
- this.exports = {
- '__nodes__': [],
- '__handlers__': {}
- };
-
- var arr = _nodesToArray(ast),
- imax = arr.length,
- i = -1,
- x;
- while( ++i < imax ){
- x = arr[i];
- switch (x.tagName) {
- case 'import':
- this.imports.push(Module.createImport(
- x, null, null, this
- ));
- break;
- case 'module':
- var path = u_resolvePath(x.attr.path, null, null, this),
- type = x.attr.contentType,
- endpoint = new Module.Endpoint(path, type)
- ;
- Module.registerModule(x.nodes, endpoint);
- break;
- case 'define':
- case 'let':
- continue;
- default:
- this.exports.__nodes__.push(x);
- break;
- }
- }
-
- _loadImports(this.imports, function(){
- next.call(this, null, _createExports(arr, null, this));
- }, this);
- },
-
- getHandler: function(name){
- return _module_getHandler.call(this, this, name);
- },
- queryHandler: function(selector) {
- if (this.error) {
- return _createHandlerForNodes(this.source, this);
- }
-
- var nodes = this.exports.__nodes__;
- if (selector !== '*') {
- nodes = _nodesFilter(nodes, selector);
- }
- return nodes != null && nodes.length !== 0
- ? _createHandlerForNodes(nodes, this)
- : null
- ;
- },
- });
-
- // Also flattern all `imports` tags
- function _nodesToArray (mix) {
- var type = mix.type;
- if (type === Dom.NODE && mix.tagName === 'imports') {
- return mix.nodes;
- }
- if (type !== Dom.FRAGMENT && type != null) {
- return [ mix ];
- }
- var arr = mix;
- if (type === Dom.FRAGMENT) {
- arr = mix.nodes;
- }
- var imax = arr.length,
- i = -1, x;
- while ( ++i < imax ){
- x = arr[i];
- if (x.tagName === 'imports') {
- arr.splice.apply(arr, [i, 1].concat(x.nodes));
- i--;
- }
- }
-
- return arr;
- }
- function _nodesFilter(nodes, tagName) {
- var arr = [],
- imax = nodes.length,
- i = -1, x;
- while ( ++i < imax ) {
- x = nodes[i];
- if (x.tagName === tagName) {
- arr.push(x);
- }
- }
- return arr;
- }
- function _createExports(nodes, model, module) {
- var exports = module.exports,
- imports = module.imports,
- scope = module.scope,
- getHandler = _module_getHandlerDelegate(module);
-
- var i = -1,
- imax = imports.length;
- while ( ++i < imax ) {
- var x = imports[i];
- if (x.registerScope) {
- x.registerScope(module);
- }
- }
-
- var i = -1,
- imax = nodes.length;
- while ( ++i < imax ) {
- var node = nodes[i];
- var name = node.tagName;
- if (name === 'define' || name === 'let') {
- var Base = {
- getHandler: _fn_wrap(customTag_Compo_getHandler, getHandler),
- location: module.location
- };
- var Ctor = Define.create(node, model, module, Base);
- var Proto = Ctor.prototype;
- Proto.scope = obj_extend(Proto.scope, scope);
-
-
- var compoName = node.name;
- if (name === 'define') {
- exports[compoName] = Ctor;
- customTag_register(compoName, Ctor);
- }
- if (name === 'let') {
- customTag_registerResolver(compoName)
- }
- exports.__handlers__[compoName] = Ctor;
- }
- }
- exports['*'] = class_create(customTag_Base, {
- getHandler: getHandler,
- location: module.location,
- nodes: exports.__nodes__,
- scope: scope
- });
-
- return exports;
- }
- function _createHandlerForNodes(nodes, module) {
- return class_create({
- scope: module.scope,
- location: module.location,
- nodes: nodes,
- getHandler: _module_getHandlerDelegate(module)
- });
- }
-
- function _loadImports(imports, done, module) {
- var count = imports.length;
- if (count === 0) {
- return done.call(module);
- }
- var imax = count,
- i = -1;
- while( ++i < imax ) {
- imports[i].loadImport(await);
- }
-
- function await(){
- if (--count > 0)
- return;
- done.call(module);
- }
- }
- function _module_getHandlerDelegate(module) {
- return function(name) {
- return _module_getHandler.call(this, module, name);
- };
- }
- function _module_getHandler(module, name) {
- var Ctor;
-
- // check public exports
- var exports = module.exports;
- if (exports != null && (Ctor = exports[name]) != null) {
- return Ctor;
- }
-
- // check private components store
- var handlers = exports.__handlers__;
- if (handlers != null && (Ctor = handlers[name]) != null) {
- return Ctor;
- }
-
- var arr = module.imports,
- i = arr.length,
- x, type;
- while( --i > -1) {
- x = arr[i];
- type = x.type;
- if (type === 'mask' && (Ctor = x.getHandler(name)) != null) {
- return Ctor;
- }
- }
- return null;
- }
-
- function _fn_wrap(baseFn, fn) {
- if (baseFn == null) {
- return fn;
- }
- return function(){
- var x = baseFn.apply(this, arguments);
- if (x != null) {
- return x;
- }
- return fn.apply(this, arguments);
- }
- }
- }());
-
- // end:source Module/ModuleMask
- // source Module/ModuleScript
- var ModuleScript = class_create(IModule, {
- type: 'script',
-
- load_: _file_getScript,
- getExport_: function(property) {
- var obj = this.exports;
- return property !== '*'
- ? obj_getProperty(obj, property)
- : obj
- ;
- },
-
- register: function(ctr, name, alias) {
- var prop = alias || name;
- var obj = this.getExport_(name);
- if (obj == null) {
- return null;
- }
- if (ctr.scope == null) {
- ctr.scope = {};
- }
- obj_setProperty(ctr.scope, prop, obj);
- return obj;
- },
- preprocessError_: function(error, next) {
- log_error('Resource ' + this.path + ' thrown an Exception: ' + error);
- next(error);
- }
- });
- // end:source Module/ModuleScript
- // source Module/ModuleStyle
- var ModuleStyle = class_create(IModule, {
- type: 'style',
-
- load_: _file_getStyle
- });
- // end:source Module/ModuleStyle
- // source Module/ModuleData
- var ModuleData = class_create(ModuleScript, {
- type: 'data',
-
- load_: _file_getJson
- });
- // end:source Module/ModuleData
- // source Module/ModuleHtml
- var ModuleHtml;
- (function(){
- ModuleHtml = class_create(ModuleMask, {
- type: 'mask',
- preprocess_: function(mix, next) {
- var ast = typeof mix === 'string'
- ? parser_parseHtml(mix)
- : mix
- ;
- return ModuleMask
- .prototype
- .preprocess_
- .call(this, ast, next);
- }
- });
- }());
- // end:source Module/ModuleHtml
-
- // source components
- (function() {
- var IMPORT = 'import',
- IMPORTS = 'imports';
-
- custom_Tags['module'] = class_create({
- constructor: function(node, model, ctx, container, ctr) {
- var path = path_resolveUrl(node.attr.path, u_resolveLocation(ctx, ctr)),
- type = node.attr.type,
- endpoint = new Module.Endpoint(path, type);
- Module.registerModule(node.nodes, endpoint, ctx, ctr);
- },
- render: fn_doNothing
- });
- custom_Tags['import:base'] = function(node, model, ctx, el, ctr){
- var base = path_normalize(expression_eval(node.expression, model, ctx, ctr));
- if (base != null && base[base.length - 1] !== '/') {
- base += '/';
- }
- Module.cfg('base', base);
- };
- custom_Tags[IMPORT] = class_create({
- meta: {
- serializeNodes: true
- },
- constructor: function(node, model, ctx, el, ctr) {
- if (node.alias == null && node.exports == null && Module.isMask(node)) {
- // embedding
- this.module = Module.createModule(node, ctx, ctr);
- }
- },
- renderStart: function(model, ctx){
- if (this.module == null) {
- return;
- }
- var resume = Compo.pause(this, ctx);
- var self = this;
- this
- .module
- .loadModule()
- .always(function(){
- self.scope = self.module.scope;
- self.nodes = self.module.source;
- self.getHandler = self.module.getHandler.bind(self.module);
- resume();
- });
- }
- });
-
- custom_Tags[IMPORTS] = class_create({
- imports_: null,
- load_: function(ctx, cb){
- var arr = this.imports_,
- self = this,
- imax = arr.length,
- await = imax,
- i = -1, x;
-
- function done(error, import_) {
- if (error == null) {
- if (import_.registerScope) {
- import_.registerScope(self);
- }
- if (ctx._modules != null) {
- ctx._modules.add(import_.module);
- }
- }
- if (--await === 0) {
- cb();
- }
- }
- while( ++i < imax ){
- x = arr[i];
- x.loadImport(done);
- }
- },
- start_: function(model, ctx){
- var resume = Compo.pause(this, ctx),
- nodes = this.nodes,
- imax = nodes.length,
- i = -1, x
- ;
- var arr = this.imports_ = [];
- while( ++i < imax ){
- x = nodes[i];
- if (x.tagName === IMPORT) {
- if (x.path.indexOf('~') !== -1) {
- var fn = parser_ensureTemplateFunction(x.path);
- if (is_Function(fn)) {
- x.path = fn('attr', model, ctx, null, this);
- }
- }
- arr.push(Module.createImport(x, ctx, this));
- }
- }
- this.load_(ctx, resume);
- },
- meta: {
- serializeNodes: true
- },
- renderStart: function(model, ctx){
- this.start_(model, ctx);
- },
- renderStartClient: function(model, ctx){
- this.start_(model, ctx);
- },
- serializeNodes: function(){
- // NodeJS
- var arr = [],
- i = this.nodes.length, x;
- while( --i > -1 ){
- x = this.nodes[i];
- if (x.tagName === IMPORT) {
- arr.push(x);
- }
- }
- return mask_stringify(arr);
- },
-
- getHandler: function(name){
- var arr = this.imports_,
- imax = arr.length,
- i = -1, import_, x;
- while ( ++i < imax ){
- import_ = arr[i];
- if (import_.type !== 'mask') {
- continue;
- }
- x = import_.getHandler(name);
- if (x != null) {
- return x;
- }
- }
- return null;
- },
- getHandlers: function(){
- var handlers = {};
- var arr = this.imports_,
- imax = arr.length,
- i = -1, import_, x;
- while ( ++i < imax ){
- import_ = arr[i];
- if (import_ !== 'mask') {
- continue;
- }
- x = import_.getHandlers();
- obj_extend(handlers, x);
- }
- return handlers;
- },
- });
-
-
- }());
-
- // end:source components
- // source tools/dependencies
- var tools_getDependencies;
- (function() {
-
- tools_getDependencies = function(template, path, opts_){
-
- var opts = obj_extendDefaults(opts_, defaultOptions);
- var dfr = new class_Dfr;
- var ast = typeof template === 'string'
- ? parser_parse(template)
- : template
- ;
-
- return get(ast, path, opts, dfr);
- };
-
-
- var defaultOptions = {
- deep: true,
- flattern: false
- };
-
- function get(ast, path, opts, dfr) {
- walk(ast, path, opts, function(error, dep){
- if (error) return dfr.reject(error);
- if (opts.flattern === true && opts.deep === true) {
- dep = flattern(dep);
- }
- dfr.resolve(dep);
- });
- return dfr;
- }
-
- function walk(ast, path, opts, done) {
- var location = path_getDir(path);
- var dependency = {
- mask: [],
- data: [],
- style: [],
- script: [],
- };
-
- mask_TreeWalker.walkAsync(ast, visit, complete);
-
- function visit (node, next){
- if (node.tagName !== 'import') {
- return next();
- }
- var path = resolvePath(node, location);
- var type = Module.getType(node);
- if (opts.deep === false) {
- dependency[type].push(path);
- return next();
- }
- if ('mask' === type) {
- getMask(path, opts, function(error, dep){
- if (error) {
- return done(error);
- }
- dependency.mask.push(dep);
- next();
- });
- return;
- }
-
- dependency[type].push(path);
- next();
- }
- function complete() {
- done(null, dependency);
- }
- }
-
- function getMask(path, opts, done){
- var dep = {
- path: path,
- dependencies: null
- };
-
- _file_get(path)
- .done(function(template){
- walk(parser_parse(template), path, opts, function(error, deps){
- if (error) {
- done(error);
- return;
- }
- dep.dependencies = deps;
- done(null, dep);
- });
- })
- .fail(done);
- }
- function resolvePath(node, location) {
- var path = node.path,
- type = node.contentType;
- if ((type == null || type === 'mask') && path_getExtension(path) === '') {
- path += '.mask';
- }
- if (path_isRelative(path)) {
- path = path_combine(location, path);
- }
- return path_normalize(path);
- }
-
- var flattern;
- (function () {
- flattern = function (deps) {
- return {
- mask: resolve(deps, 'mask'),
- data: resolve(deps, 'data'),
- style: resolve(deps, 'style'),
- script: resolve(deps, 'script'),
- };
- };
-
- function resolve(deps, type) {
- return distinct(get(deps, type, []));
- }
- function get (deps, type, stack) {
- if (deps == null) {
- return stack;
- }
- var arr = deps[type],
- imax = arr.length,
- i = -1, x;
- while ( ++i < imax ) {
- x = arr[i];
- if (typeof x === 'string') {
- stack.unshift(x);
- continue;
- }
- // assume is an object { path, dependencies[] }
- stack.unshift(x.path);
- get(x.dependencies, type, stack);
- }
- if ('mask' !== type) {
- deps.mask.forEach(function(x){
- get(x.dependencies, type, stack);
- });
- }
- return stack;
- }
- function distinct (stack) {
- for (var i = 0; i < stack.length; i++) {
- for (var j = i + 1; j < stack.length; j++) {
- if (stack[i] === stack[j]) {
- stack.splice(j, 1);
- j--;
- }
- }
- }
- return stack;
- }
- }());
-
- }());
- // end:source tools/dependencies
- // source tools/build
- var tools_build;
- (function(){
-
- tools_build = function(template, path, opts_){
- var opts = obj_extendDefaults(opts_, optionsDefault);
- return class_Dfr.run(function(resolve, reject){
- tools_getDependencies(template, path, { flattern: true })
- .fail(reject)
- .done(function(deps){
- build(deps, opts, complete, reject);
- });
- function complete (out) {
- out.mask += '\n' + template;
- resolve(out);
- }
- });
- };
-
- var optionsDefault = {
- minify: false
- };
-
- function build(deps, opts, resolve, reject) {
- var types = ['mask', 'script', 'style', 'data'];
- var out = {
- mask: '',
- data: '',
- style: '',
- script: '',
- };
- function next(){
- if (types.length === 0) {
- if (out.data) {
- out.script = out.data + '\n' + out.script;
- }
- return resolve(out);
- }
- var type = types.shift();
- build_type(deps, type, opts, function(error, str){
- if (error) return reject(error);
- out[type] = str;
- next();
- });
- }
- next();
- }
-
- function build_type (deps, type, opts, done) {
- var arr = deps[type],
- imax = arr.length,
- i = -1,
- stack = [];
-
- function next() {
- if (++i === imax) {
- done(null, stack.join('\n'));
- return;
- }
- Single[type](arr[i], opts)
- .fail(done)
- .done(function(str){
- stack.push('/* source ' + arr[i] + ' */');
- stack.push(str);
- next();
- });
- }
- next();
- }
-
- var Single = {
- mask: function(path, opts, done){
- return class_Dfr.run(function(resolve, reject) {
- _file_get(path)
- .fail(reject)
- .done(function(str) {
- // remove all remote styles
- var ast = mask_TreeWalker.walk(str, function(node){
- if (node.tagName === 'link' && node.attr.href) {
- return { remove: true };
- }
- });
- ast = jmask('module')
- .attr('path', path)
- .append(ast);
-
- var str = mask_stringify(ast[0], {
- indent: opts.minify ? 0 : 4
- });
- resolve(str);
- });
- });
- },
- script: function(path, opts){
- return (__cfg.buildScript || build_script)(path, opts);
- },
- style: function(path, opts) {
- return (__cfg.buildStyle || build_style)(path, opts);
- },
- data: function(path, opts) {
- return (__cfg.buildData || build_data)(path, opts);
- }
- }
-
- function build_script(path, opts, done) {
- return class_Dfr.run(function(resolve, reject){
- _file_get(path)
- .fail(reject)
- .done(function(str){
- var script = 'module = { exports: null }\n';
- script += str + ';\n';
- script += 'mask.Module.registerModule(module.exports, new mask.Module.Endpoint("' + path + '", "script"))';
- resolve(script);
- });
- });
- }
- function build_style(path, opts, done) {
- return _file_get(path, done);
- }
- function build_data(path, opts, done) {
- return class_Dfr.run(function(resolve, reject){
- _file_get(path)
- .fail(reject)
- .done(function(mix){
- var json;
- try {
- json = typeof mix === 'string'
- ? JSON.parse(mix)
- : mix;
- } catch (error) {
- reject(error);
- return;
- }
- var str = JSON.stringify(json, null, opts.minify ? 4 : void 0);
- var script = 'module = { exports: ' + str + ' }\n'
- + 'mask.Module.registerModule(module.exports, new mask.Module.Endpoint("' + path + '", "json"))';
-
- resolve(script);
- });
- });
- }
- }());
- // end:source tools/build
-
- obj_extend(Module, {
- ModuleMask: ModuleMask,
- Endpoint: Endpoint,
- createModule: function(node, ctx, ctr, parent) {
- var path = u_resolvePathFromImport(node, ctx, ctr, parent),
- module = _cache[path];
- if (module == null) {
- var endpoint = new Endpoint(path, node.contentType);
- module = _cache[path] = IModule.create(endpoint, parent);
- }
- return module;
- },
- registerModule: function(mix, endpoint, ctx, ctr, parent) {
- endpoint.path = u_resolvePath(endpoint.path, ctx, ctr, parent);
-
- var module = Module.createModule(endpoint, ctx, ctr, parent);
- module.state = 1;
- if (Module.isMask(endpoint)) {
- module.preprocess_(mix, function(){
- module.state = 4;
- module.resolve(module);
- });
- return module;
- }
- // assume others and is loaded
- module.state = 4;
- module.exports = mix;
- module.resolve(module);
- return module;
- },
-
- createImport: function(node, ctx, ctr, module){
- var path = u_resolvePathFromImport(node, ctx, ctr, module),
- alias = node.alias,
- exports = node.exports,
- endpoint = new Endpoint(path, node.contentType);
- return IImport.create(endpoint, alias, exports, module);
- },
- isMask: function(endpoint){
- var type = endpoint.contentType,
- ext = type || path_getExtension(endpoint.path);
- return ext === '' || ext === 'mask' || ext === 'html';
- },
- getType: function(endpoint) {
- var type = endpoint.contentType,
- path = endpoint.path;
- if (type != null) {
- return type;
- }
- var ext = path_getExtension(path);
- if (ext === '' || ext === 'mask'){
- return 'mask';
- }
- var search = ' ' + ext + ' ';
- if (_extensions_style.indexOf(search) !== -1){
- return 'style';
- }
- if (_extensions_data.indexOf(search) !== -1){
- return 'data';
- }
- // assume is javascript
- return 'script';
- },
- cfg: function(name, val){
- if (name in _opts === false) {
- log_error('Invalid module option: ', name);
- return;
- }
- _opts[name] = val;
- },
- resolveLocation: u_resolveLocation,
- getDependencies: tools_getDependencies,
- build: tools_build,
- });
- }());
- // end:source modules/
- // source Define
- var Define;
- (function(){
- Define = {
- create: function(node, model, ctr, Base){
- return compo_fromNode(node, model, ctr, Base);
- },
- registerGlobal: function(node, model, ctr, Base) {
- var Ctor = Define.create(node, model, ctr, Base);
- customTag_register(
- node.name, Ctor
- );
- },
- registerScoped: function(node, model, ctr, Base) {
- var Ctor = Define.create(node, model, ctr, Base);
- customTag_registerScoped(
- ctr, node.name, Ctor
- );
- }
- };
-
- function compo_prototype(compoName, tagName, attr, nodes, owner, model, Base) {
- var arr = [];
- var Proto = obj_extend({
- tagName: tagName,
- compoName: compoName,
- template: arr,
- attr: attr,
- location: trav_location(owner),
- meta: {
- template: 'merge'
- },
- renderStart: function(){
- Compo.prototype.renderStart.apply(this, arguments);
- if (this.nodes === this.template) {
- this.nodes = mask_merge(this.nodes, [], this);
- }
- },
- getHandler: null
- }, Base);
-
- var imax = nodes == null ? 0 : nodes.length,
- i = 0, x, name;
- for(; i < imax; i++) {
- x = nodes[i];
- if (x == null)
- continue;
- name = x.tagName;
- if ('function' === name) {
- Proto[x.name] = x.fn;
- continue;
- }
- if ('slot' === name || 'event' === name) {
- if ('event' === name && Proto.tagName != null) {
- // bind the event later via the component
- arr.push(x);
- continue;
- }
- var type = name + 's';
- var fns = Proto[type];
- if (fns == null) {
- fns = Proto[type] = {};
- }
- fns[x.name] = x.fn;
- continue;
- }
- if ('define' === name || 'let' === name) {
- var fn = name === 'define'
- ? Define.registerGlobal
- : Define.registerScoped;
- fn(x, model, Proto);
- continue;
- }
- if ('var' === name) {
- var obj = x.getObject(model, null, owner),
- key, val;
- for(key in obj) {
- val = obj[key];
- if (key === 'meta' || key === 'model' || key === 'attr') {
- Proto[key] = obj_extend(Proto[key], val);
- continue;
- }
- if (key === 'scope') {
- if (is_Object(val)) {
- Proto.scope = obj_extend(Proto.scope, val);
- continue;
- }
- }
- var scope = Proto.scope;
- if (scope == null) {
- Proto.scope = scope = {};
- }
- scope[key] = val;
- }
- continue;
- }
- arr.push(x);
- }
- return Proto;
- }
- function compo_extends(extends_, model, ctr) {
- var args = [];
- if (extends_ == null)
- return args;
-
- var imax = extends_.length,
- i = -1,
- await = 0, x;
- while( ++i < imax ){
- x = extends_[i];
- if (x.compo) {
- var compo = customTag_get(x.compo, ctr);
- if (compo != null) {
- args.unshift(compo);
- continue;
- }
-
- var obj = expression_eval(x.compo, model, null, ctr);
- if (obj != null) {
- args.unshift(obj);
- continue;
- }
- log_error('Nor component, nor scoped data is resolved:', x.compo);
- continue;
- }
- }
- return args;
- }
-
- function compo_fromNode(node, model, ctr, Base) {
- var extends_ = node['extends'],
- as_ = node['as'],
- tagName,
- attr;
- if (as_ != null) {
- var x = parser_parse(as_);
- tagName = x.tagName;
- attr = obj_extend(node.attr, x.attr);
- }
-
- var name = node.name,
- Proto = compo_prototype(name, tagName, attr, node.nodes, ctr, model, Base),
- args = compo_extends(extends_, model, ctr)
- ;
-
- args.push(Proto);
- return Compo.apply(null, args);
- }
-
- function trav_location(ctr) {
- while(ctr != null) {
- if (ctr.location) {
- return ctr.location;
- }
- if (ctr.resource && ctr.resource.location) {
- return ctr.resource.location;
- }
- ctr = ctr.parent;
- }
- return null;
- }
- }());
- // end:source Define
- // source TreeWalker
- var mask_TreeWalker;
- (function(){
- /**
- * TreeWalker
- * @memberOf mask
- * @name TreeWalker
- */
- mask_TreeWalker = {
- /**
- * Visit each mask node
- * @param {MaskNode} root
- * @param {TreeWalker~SyncVisitior} visitor
- * @memberOf mask.TreeWalker
- */
- walk: function(root, fn) {
- if (typeof root === 'object' && root.type === Dom.CONTROLLER) {
- new SyncWalkerCompos(root, fn);
- return root;
- }
- root = prepairRoot(root);
- new SyncWalker(root, fn);
- return root;
- },
- /**
- * Asynchronous visit each mask node
- * @param {MaskNode} root
- * @param {TreeWalker~AsyncVisitior} visitor
- * @param {function} done
- * @memberOf mask.TreeWalker
- */
- walkAsync: function(root, fn, done){
- root = prepairRoot(root);
- new AsyncWalker(root, fn, done);
- }
- };
-
- var SyncWalker,
- SyncWalkerCompos;
- (function(){
- SyncWalker = function(root, fn){
- walk(root, fn);
- };
- SyncWalkerCompos = function(root, fn){
- walkCompos(root, fn, root);
- };
- function walk(node, fn, parent, index) {
- if (node == null)
- return null;
-
- var deep = true, break_ = false, mod;
- if (isFragment(node) !== true) {
- mod = fn(node);
- }
- if (mod !== void 0) {
- mod = new Modifier(mod);
- mod.process(new Step(node, parent, index));
- deep = mod.deep;
- break_ = mod['break'];
- }
- var nodes = safe_getNodes(node);
- if (nodes == null || deep === false || break_ === true) {
- return mod;
- }
- var imax = nodes.length,
- i = 0, x;
- for(; i < imax; i++) {
- x = nodes[i];
- mod = walk(x, fn, node, i);
- if (mod != null && mod['break'] === true) {
- return mod;
- }
- }
- }
- function walkCompos(compo, fn, parent, index) {
- if (compo == null)
- return;
-
- var mod = fn(compo, index);
- if (mod !== void 0) {
- if (mod.deep === false || mod['break'] === true) {
- return mod;
- }
- }
- var compos = compo.components;
- if (compos == null) {
- return null;
- }
- var imax = compos.length,
- i = 0, x;
- for(; i < imax; i++) {
- x = compos[i];
- mod = walkCompos(x, fn, compo, i);
- if (mod != null && mod['break'] === true) {
- return mod;
- }
- }
- }
- }());
- var AsyncWalker;
- (function(){
- AsyncWalker = function(root, fn, done){
- this.stack = [];
- this.done = done;
- this.root = root;
- this.fn = fn;
-
- this.process = this.process.bind(this);
- this.visit(this.push(root));
- };
- AsyncWalker.prototype = {
- current: function(){
- return this.stack[this.stack.length - 1];
- },
- push: function(node, parent, index){
- var step = new Step(node, parent, index);
- this.stack.push(step);
- return step;
- },
- pop: function(){
- return this.stack.pop();
- },
- getNext: function(goDeep){
- var current = this.current(),
- node = current.node,
- nodes = safe_getNodes(node);
- if (node == null) {
- throw Error('Node is null');
- }
- if (nodes != null && goDeep !== false && nodes.length !== 0) {
- if (nodes[0] == null) {
- throw Error('Node is null');
- }
- return this.push(
- nodes[0],
- node,
- 0
- );
- }
- var parent, index;
- while (this.stack.length !== 0) {
- current = this.pop();
- parent = current.parent;
- index = current.index;
- if (parent == null) {
- this.pop();
- continue;
- }
- if (++index < parent.nodes.length) {
- return this.push(
- parent.nodes[index],
- parent,
- index
- );
- }
- }
- return null;
- },
- process: function(mod){
- var deep = true, break_ = false;
-
- if (mod !== void 0) {
- mod = new Modifier(mod);
- mod.process(this.current());
- deep = mod.deep;
- break_ = mod['break'];
- }
-
- var next = break_ === true ? null : this.getNext(deep);
- if (next == null) {
- this.done(this.root);
- return;
- }
- this.visit(next);
- },
-
- visit: function(step){
- var node = step.node;
- if (isFragment(node) === false) {
- this.fn(node, this.process);
- return;
- }
- this.process();
- },
-
- fn: null,
- done: null,
- stack: null
- };
- }());
-
- var Modifier;
- (function(){
- /**
- * @name IModifier
- * @memberOf TreeWalker
- */
- Modifier = function (mod, step) {
- for (var key in mod) {
- this[key] = mod[key];
- }
- };
- Modifier.prototype = {
- /**
- * On `true` stops the walker
- */
- 'break': false,
- /**
- * On `false` doesn't visit the subnodes
- */
- deep: true,
- /**
- * On `true` removes current node
- */
- remove: false,
- /**
- * On not `null`, replaces the current node with value
- */
- replace: null,
- process: function(step){
- if (this.replace != null) {
- this.deep = false;
- step.parent.nodes[step.index] = this.replace;
- return;
- }
- if (this.remove === true) {
- this.deep = false;
- var arr = step.parent.nodes,
- i = step.index;
- _Array_splice.call(arr, i, 1);
- return;
- }
- }
- };
- }());
-
- var Step = function (node, parent, index) {
- this.node = node;
- this.index = index;
- this.parent = parent;
- };
-
- /* UTILS */
-
- function isFragment(node) {
- return Dom.FRAGMENT === safe_getType(node);
- }
- function safe_getNodes(node) {
- var nodes = node.nodes;
- if (nodes == null)
- return null;
-
- return is_Array(nodes)
- ? (nodes)
- : (node.nodes = [ nodes ]);
- }
- function safe_getType(node) {
- var type = node.type;
- if (type != null)
- return type;
-
- if (is_Array(node)) return Dom.FRAGMENT;
- if (node.tagName != null) return Dom.NODE;
- if (node.content != null) return Dom.TEXTNODE;
-
- return Dom.NODE;
- }
- function prepairRoot(root){
- if (typeof root === 'string') {
- root = parser_parse(root);
- }
- if (isFragment(root) === false) {
- var fragment = new Dom.Fragment;
- fragment.appendChild(root);
-
- root = fragment;
- }
- return root;
- }
-
- /**
- * Is called on each node
- * @callback TreeWalker~SyncVisitor
- * @param {MaskNode} node
- * @returns {Modifier|void}
- */
- /**
- * Is called on each node
- * @callback TreeWalker~AsyncVisitor
- * @param {MaskNode} node
- * @param {function} done - Optional pass @see{@link TreeWalker.IModifier} to the callback
- * @returns {void}
- */
- }());
- // end:source TreeWalker
- // end:source feature/
- // source parser/
- var parser_parse,
- parser_parseHtml,
- parser_parseAttr,
- parser_parseAttrObject,
- parser_parseLiteral,
- parser_ensureTemplateFunction,
- parser_setInterpolationQuotes,
- parser_cleanObject,
- parser_ObjectLexer
- ;
-
- (function(Node, TextNode, Fragment, Component) {
-
- // source ./const
- var interp_START = '~',
- interp_OPEN = '[',
- interp_CLOSE = ']',
-
- // ~
- interp_code_START = 126,
- // [
- interp_code_OPEN = 91,
- // ]
- interp_code_CLOSE = 93,
-
-
- go_tag = 2,
- go_up = 9,
- go_attrVal = 6,
- go_attrHeadVal = 7,
-
- state_tag = 3,
- state_attr = 5,
- state_literal = 8
- ;
- // end:source ./const
- // source ./utils
- parser_cleanObject = function(mix) {
- if (is_Array(mix)) {
- for (var i = 0; i < mix.length; i++) {
- parser_cleanObject(mix[i]);
- }
- return mix;
- }
- delete mix.parent;
- delete mix.__single;
- if (mix.nodes != null) {
- parser_cleanObject(mix.nodes);
- }
- return mix;
- };
- // end:source ./utils
- // source ./cursor
- var cursor_groupEnd,
- cursor_quoteEnd,
- cursor_refEnd,
- cursor_tokenEnd,
- cursor_skipWhitespace,
- cursor_skipWhitespaceBack,
- cursor_goToWhitespace
- ;
- (function(){
-
- cursor_groupEnd = function(str, i, imax, startCode, endCode){
- var count = 0,
- start = i,
- c;
- for( ; i < imax; i++){
- c = str.charCodeAt(i);
- if (c === 34 || c === 39) {
- // "|'
- i = cursor_quoteEnd(
- str
- , i + 1
- , imax
- , c === 34 ? '"' : "'"
- );
- continue;
- }
- if (c === startCode) {
- count++;
- continue;
- }
- if (c === endCode) {
- if (--count === -1)
- return i;
- }
- }
- parser_warn('Group was not closed', str, start);
- return imax;
- };
-
- cursor_refEnd = function(str, i, imax){
- var c;
- while (i < imax){
- c = str.charCodeAt(i);
- if (c === 36 || c === 95) {
- // $ _
- i++;
- continue;
- }
- if ((48 <= c && c <= 57) || // 0-9
- (65 <= c && c <= 90) || // A-Z
- (97 <= c && c <= 122)) { // a-z
- i++;
- continue;
- }
- break;
- }
- return i;
- };
-
- cursor_tokenEnd = function(str, i, imax){
- var c;
- while (i < imax){
- c = str.charCodeAt(i);
- if (c === 36 || c === 95 || c === 58) {
- // $ _ :
- i++;
- continue;
- }
- if ((48 <= c && c <= 57) || // 0-9
- (65 <= c && c <= 90) || // A-Z
- (97 <= c && c <= 122)) { // a-z
- i++;
- continue;
- }
- break;
- }
- return i;
- };
-
- cursor_quoteEnd = function(str, i, imax, char_){
- var start = i;
- while ((i = str.indexOf(char_, i)) !== -1) {
- if (str.charCodeAt(i - 1) !== 92)
- // \
- return i;
- i++;
- }
- parser_warn('Quote was not closed', str, start - 1);
- return imax;
- };
-
- cursor_skipWhitespace = function(str, i, imax) {
- for(; i < imax; i++) {
- if (str.charCodeAt(i) > 32)
- return i;
- }
- return i;
- };
- cursor_skipWhitespaceBack = function(str, i) {
- for(; i > 0; i--) {
- if (str.charCodeAt(i) > 32)
- return i;
- }
- return i;
- };
-
- cursor_goToWhitespace = function(str, i, imax) {
- for(; i < imax; i++) {
- if (str.charCodeAt(i) < 33)
- return i;
- }
- return i;
- };
- }());
- // end:source ./cursor
- // source ./interpolation
- (function(){
-
- parser_ensureTemplateFunction = function (template) {
- var mix = _split(template);
- if (mix == null) {
- return template;
- }
- if (typeof mix === 'string') {
- return mix;
- }
- var array = mix;
- return function(type, model, ctx, element, ctr, name) {
- if (type === void 0) {
- return template;
- }
- return _interpolate(
- array
- , type
- , model
- , ctx
- , element
- , ctr
- , name
- );
- };
- };
-
-
- parser_setInterpolationQuotes = function(start, end) {
- if (!start || start.length !== 2) {
- log_error('Interpolation Start must contain 2 Characters');
- return;
- }
- if (!end || end.length !== 1) {
- log_error('Interpolation End must be of 1 Character');
- return;
- }
-
- interp_code_START = start.charCodeAt(0);
- interp_code_OPEN = start.charCodeAt(1);
- interp_code_CLOSE = end.charCodeAt(0);
-
- interp_START = start[0];
- interp_OPEN = start[1];
- interp_CLOSE = end;
- };
-
-
- function _split (template) {
- var index = -1,
- wasEscaped = false,
- nextC, nextI;
- /*
- * - single char indexOf is much faster then '~[' search
- * - function is divided in 2 parts: interpolation start lookup + interpolation parse
- * for better performance
- */
- while ((index = template.indexOf(interp_START, index)) !== -1) {
- nextC = template.charCodeAt(index + 1);
- var escaped = _char_isEscaped(template, index);
- if (escaped === true) {
- wasEscaped = true;
- }
- if (escaped === false) {
- if (nextC === interp_code_OPEN)
- break;
- if (_char_isSimpleInterp(nextC)) {
- break;
- }
- }
- index++;
- }
-
- if (index === -1) {
- if (wasEscaped === true) {
- return _escape(template);
- }
- return null;
- }
-
- var length = template.length,
- array = [],
- lastIndex = 0,
- i = 0,
- end;
-
- var propAccessor = false;
- while (true) {
-
- array[i++] = lastIndex === index
- ? ''
- : _slice(template, lastIndex, index);
-
-
- nextI = index + 1;
- nextC = template.charCodeAt(nextI);
- if (nextC === interp_code_OPEN) {
- propAccessor = false;
- end = cursor_groupEnd(
- template
- , nextI + 1
- , length
- , interp_code_OPEN
- , interp_code_CLOSE
- );
- var str = template.substring(index + 2, end);
- array[i++] = new InterpolationModel(null, str);
- lastIndex = index = end + 1;
- }
-
- else if (_char_isSimpleInterp(nextC)) {
- propAccessor = true;
- end = _cursor_propertyAccessorEnd(template, nextI, length);
-
- var str = template.substring(index + 1, end);
- array[i++] = new InterpolationModel(str, null);
- lastIndex = index = end;
- }
- else {
- array[i] += template[nextI];
- lastIndex = nextI;
- }
-
- while ((index = template.indexOf(interp_START, index)) !== -1) {
- nextC = template.charCodeAt(index + 1);
- var escaped = _char_isEscaped(template, index);
- if (escaped === true) {
- wasEscaped = true;
- }
- if (escaped === false) {
- if (nextC === interp_code_OPEN)
- break;
- if (_char_isSimpleInterp(nextC)) {
- break;
- }
- }
- index++;
- }
- if (index === -1) {
- break;
- }
- }
- if (lastIndex < length) {
- array[i] = wasEscaped === true
- ? _slice(template, lastIndex, length)
- : template.substring(lastIndex)
- ;
- }
- return array;
- }
-
- function _char_isSimpleInterp (c) {
- //A-z$_
- return (c >= 65 && c <= 122) || c === 36 || c === 95;
- }
- function _char_isEscaped (str, i) {
- if (i === 0) {
- return false;
- }
- var c = str.charCodeAt(--i);
- if (c === 92) {
- if (_char_isEscaped(str, c))
- return false;
- return true;
- }
- return false;
- }
-
- function _slice(string, start, end) {
- var str = string.substring(start, end);
- var i = str.indexOf(interp_START)
- if (i === -1) {
- return str;
- }
- return _escape(str);
- }
-
- function _escape(str) {
- return str.replace(/\\~/g, '~');
- }
-
- function InterpolationModel(prop, expr){
- this.prop = prop;
- this.expr = expr;
- }
- InterpolationModel.prototype.process = function(model, ctx, el, ctr, name, type){
- if (this.prop != null) {
- return obj_getPropertyEx(this.prop, model, ctx, ctr);
- }
- var expr = this.expr,
- index = expr.indexOf(':'),
- util;
- if (index !== -1) {
- if (index === 0) {
- expr = expr.substring(index + 1);
- }
- else {
- var match = rgx_UTIL.exec(expr);
- if (match != null) {
- util = match[1];
- expr = expr.substring(index + 1);
- }
- }
- }
- if (util == null || util === '') {
- util = 'expression';
- }
-
- var fn = custom_Utils[util];
- if (fn == null) {
- log_error('Undefined custom util:', util);
- return null;
- }
- return fn(expr, model, ctx, el, ctr, name, type);
- };
-
- /**
- * If we rendere interpolation in a TextNode, then custom util can return not only string values,
- * but also any HTMLElement, then TextNode will be splitted and HTMLElements will be inserted within.
- * So in that case we return array where we hold strings and that HTMLElements.
- *
- * If custom utils returns only strings, then String will be returned by this function
- * @returns {(array|string)}
- */
- function _interpolate(arr, type, model, ctx, el, ctr, name) {
- var imax = arr.length,
- i = -1,
- array = null,
- string = '',
- even = true;
- while ( ++i < imax ) {
- if (even === true) {
- if (array == null){
- string += arr[i];
- } else{
- array.push(arr[i]);
- }
- } else {
- var interp = arr[i],
- mix = interp.process(model, ctx, el, ctr, name, type);
- if (mix != null) {
- if (typeof mix === 'object' && array == null){
- array = [ string ];
- }
- if (array == null){
- string += mix;
- } else {
- array.push(mix);
- }
- }
- }
- even = !even;
- }
-
- return array == null
- ? string
- : array
- ;
- }
-
- function _cursor_propertyAccessorEnd(str, i, imax) {
- var c;
- while (i < imax){
- c = str.charCodeAt(i);
- if (c === 36 || c === 95 || c === 46) {
- // $ _ .
- i++;
- continue;
- }
- if ((48 <= c && c <= 57) || // 0-9
- (65 <= c && c <= 90) || // A-Z
- (97 <= c && c <= 122)) { // a-z
- i++;
- continue;
- }
- break;
- }
- return i;
- }
-
- var rgx_UTIL = /\s*(\w+):/;
- }());
-
- // end:source ./interpolation
- // source ./object/ObjectLexer
- var ObjectLexer;
- (function(){
-
- // source ./compile.js
- var _compile;
- (function(){
- _compile = function(str, i, imax){
- if (i === void 0) {
- i = 0;
- imax = str.length;
- }
-
- var tokens = [],
- c, optional, ref, start;
- outer: for(; i < imax; i++) {
- start = i;
- c = str.charCodeAt(i);
- optional = false;
- if (63 === c /* ? */) {
- optional = true;
- start = ++i;
- c = str.charCodeAt(i);
- }
- switch(c) {
- case 32 /* */:
- tokens.push(new token_Whitespace(optional, i));
- continue;
- case 34:
- case 39 /*'"*/:
- i = cursor_quoteEnd(str, i + 1, imax, c === 34 ? '"' : "'");
- tokens.push(
- new token_String(
- _compile(str, start + 1, i)
- )
- );
- continue;
- case 36 /*$*/:
- start = ++i;
- var isExtended = false;
- if (c === str.charCodeAt(i)) {
- isExtended = true;
- start = ++i;
- }
- i = cursor_tokenEnd(str, i, imax);
-
- var name = str.substring(start, i);
- if (optional === false && isExtended === false) {
- tokens.push(new token_Var(name));
- i--;
- continue;
- }
-
- c = str.charCodeAt(i);
- if (c === 91 /*[*/) {
- i = compileArray(name, tokens, str, i, imax, optional);
- continue;
- }
- if (c === 40 /*(*/) {
- i = compileExtendedVar(name, tokens, str, i, imax);
- continue;
- }
- if (c === 60 /*<*/ ) {
- i = compileCustomVar(name, tokens, str, i, imax);
- continue;
- }
- throw_('Unexpected extended type');
- continue;
-
- case 40 /*(*/:
- if (optional === true) {
- i = compileGroup(optional, tokens, str, i, imax);
- continue;
- }
- /* fall through */
- case 44 /*,*/:
- case 41 /*)*/:
- case 91 /*[*/:
- case 93 /*]*/:
- case 123 /*{*/:
- case 125 /*}*/:
- tokens.push(new token_Punctuation(String.fromCharCode(c)));
- continue;
- }
-
- while(i < imax) {
- c = str.charCodeAt(++i);
- if (c > 32 && c !== 34 && c !== 39 && c !== 36 && c !== 44) {
- continue;
- }
- tokens.push(new token_Const(str.substring(start, i)));
- --i;
- continue outer;
- }
- }
-
- var jmax = tokens.length,
- j = -1,
- orGroup = jmax > 1,
- x;
- while(orGroup === true && ++j < jmax) {
- x = tokens[j];
- if (x instanceof token_Group === false || x.optional !== true) {
- orGroup = false;
- }
- }
- if (0 && orGroup === true) {
- tokens = [ new token_OrGroup(tokens) ];
- }
-
- return tokens;
- };
-
- function compileArray(name, tokens, str, i, imax, optional){
- var start = ++i;
- i = cursor_groupEnd(str, i, imax, 91, 93);
- var innerTokens = _compile(str, start, i);
-
- i++;
- if (str.charCodeAt(i) !== 40 /*(*/)
- throw_('Punctuation group expected');
-
- start = ++i;
- i = cursor_groupEnd(str, i, imax, 40, 41)
- var delimiter = str.substring(start, i);
- tokens.push(
- new token_Array(
- name
- , innerTokens
- , new token_Punctuation(delimiter)
- , optional
- )
- );
- return i;
- }
- function compileExtendedVar(name, tokens, str, i, imax){
- var start = ++i;
- i = cursor_groupEnd(str, i, imax, 40, 41);
- tokens.push(
- new token_ExtendedVar(name, str.substring(start, i))
- );
- return i;
- }
- function compileCustomVar(name, tokens, str, i, imax) {
- var start = ++i;
- i = cursor_tokenEnd(str, i, imax);
- tokens.push(
- new token_CustomVar(name, str.substring(start, i))
- );
- return i;
- }
- function compileGroup(optional, tokens, str, i, imax) {
- var start = ++i;
- i = cursor_groupEnd(str, start, imax, 40, 41);
- tokens.push(
- new token_Group(_compile(str, start, i), optional)
- );
- return i;
- }
-
- function throw_(msg) {
- throw Error('Lexer pattern: ' + msg);
- }
- }());
- // end:source ./compile.js
- // source ./consume.js
- var _consume;
- (function() {
- _consume = function(tokens, str, index, length, out, isOptional){
- var index_ = index;
- var imax = tokens.length,
- i = 0, token, start;
- for(; i < imax; i++) {
- token = tokens[i];
- start = index;
- index = token.consume(str, index, length, out);
- if (index === start) {
- if (token.optional === true) {
- continue;
- }
- if (isOptional === true) {
- return index_;
- }
- // global require is also not optional: throw error
- var msg = 'Token of type `' + token.name + '`';
- if (token.token) {
- msg += ' Did you mean: `' + token.token + '`?';
- }
- parser_error(msg, str, index);
- return index_;
- }
- }
- return index;
- };
- }());
- // end:source ./consume.js
- // source ./tokens.js
- var token_Const,
- token_Var,
- token_String,
- token_Whitespace,
- token_Array,
- token_Punctuation,
- token_ExtendedVar,
- token_CustomVar,
- token_Group,
- token_OrGroup;
- (function(){
-
- token_Whitespace = create('Whitespace', {
- constructor: function(optional){
- this.optional = optional;
- },
- consume: cursor_skipWhitespace
- });
-
- // To match the string and continue, otherwise stops current consumer
- // foo
- token_Const = create('Const', {
- constructor: function(str) {
- this.token = str;
- },
- consume: function(str, i, imax){
- var end = i + this.token.length;
- str = str.substring(i, end);
- return str === this.token ? end : i;
- }
- });
- // consume string (JS syntax) to the variable
- // $foo
- token_Var = create('Var', {
- constructor: function(name){
- this.token = name;
- this.setter = generateSetter(name);
- },
- consume: function(str, i, imax, out) {
- var end = cursor_tokenEnd(str, i, imax);
- if (end === i)
- return i;
-
- this.setter(out, str.substring(i, end));
- return end;
- }
- });
- /* consume string to the variable
- * - by Regexp
- * $$foo(\w+)
- * - rest of the string
- * $$foo(*)
- * - inside a group of chars `()` `[]` `""` `''`, etc
- * $$foo(*())
- */
- token_ExtendedVar = create('ExtendedVar', {
- constructor: function(name, rgx){
- this.token = rgx;
- this.setter = generateSetter(name);
- if (rgx.charCodeAt(0) === 42) {
- // *
- if (rgx === '*') {
- this.consume = this.consumeAll;
- return;
- }
- if (rgx.length === 3) {
- this.consume = this.consumeGroup;
- return;
- }
- throw Error('`*` consumer expected group chars to parse');
- }
- this.rgx = new RegExp(rgx, 'g');
- },
- consumeAll: function(str, i, imax, out){
- this.setter(out, str.substring(i));
- return imax;
- },
- consumeGroup: function(str, i, imax, out){
- var start = this.token.charCodeAt(1),
- end = this.token.charCodeAt(2);
- if (str.charCodeAt(i) !== start) {
- return token_Var
- .prototype
- .consume
- .call(this, str, i, imax, out);
- }
-
- var end = cursor_groupEnd(str, ++i, imax, start, end);
- if (end === i)
- return i;
-
- this.setter(out, str.substring(i, end));
- return end + 1;
- },
- consume: function(str, i, imax, out) {
- this.rgx.lastIndex = i;
- var match = this.rgx.exec(str);
- if (match == null)
- return i;
-
- var x = match[0];
- this.setter(out, x);
- return i + x.length;
- }
- });
- (function(){
- // Consume string with custom Stop/Continue Function to the variable
- token_CustomVar = create('CustomVar', {
- constructor: function(name, consumer) {
- this.fn = Consumers[consumer];
- this.token = name;
- this.setter = generateSetter(name);
- },
- consume: function(str, i, imax, out) {
- var start = i;
-
- var c;
- for (; i < imax; i++){
- c = str.charCodeAt(i);
- if (c === 36 || c === 95 || c === 58) {
- // $ _ :
- continue;
- }
- if ((48 <= c && c <= 57) || // 0-9
- (65 <= c && c <= 90) || // A-Z
- (97 <= c && c <= 122)) { // a-z
- continue;
- }
- if (this.fn(c) === true) {
- continue;
- }
- break;
- }
- if (i === start)
- return i;
-
- this.setter(out, str.substring(start, i));
- return i;
- }
- });
-
- var Consumers = {
- accessor: function(c){
- if (c === 46 /*.*/) {
- return true;
- }
- return false;
- }
- };
- }());
-
- token_String = create('String', {
- constructor: function(tokens){
- this.tokens = tokens;
- },
- consume: function(str, i, imax, out) {
- var c = str.charCodeAt(i);
- if (c !== 34 && c !== 39)
- return i;
-
- var end = cursor_quoteEnd(str, i + 1, imax, c === 34 ? '"' : "'");
- if (this.tokens.length === 1) {
- var $var = this.tokens[0];
- out[$var.token] = str.substring(i + 1, end);
- } else {
- throw Error('Not implemented');
- }
- return ++end;
- }
- });
- token_Array = create('Array', {
- constructor: function(name, tokens, delim, optional) {
- this.token = name;
- this.delim = delim;
- this.tokens = tokens;
- this.optional = optional;
- },
- consume: function(str, i, imax, out){
- var obj, end, arr;
- while(true) {
- obj = {};
- end = _consume(this.tokens, str, i, imax, obj, this.optional);
-
- if (i === end) {
- if (arr == null)
- return i;
- throw Error('Next item expected');
- }
- if (arr == null)
- arr = [];
- arr.push(obj);
- i = end;
-
- end = this.delim.consume(str, i, imax);
- if (i === end)
- break;
- i = end;
- }
- out[this.token] = arr;
- return i;
- }
- });
- token_Punctuation = create('Punc', {
- constructor: function(str){
- this.before = new token_Whitespace(true);
- this.delim = new token_Const(str);
- this.after = new token_Whitespace(true);
- this.token = str;
- },
- consume: function(str, i, imax){
- var start = this.before.consume(str, i, imax);
- var end = this.delim.consume(str, start, imax);
- if (start === end) {
- return i;
- }
- return this.after.consume(str, end, imax);
- }
- });
- token_Group = create('Group', {
- constructor: function(tokens, optional) {
- this.optional = optional;
- this.tokens = tokens;
- },
- consume: function(str, i, imax, out){
- return _consume(this.tokens, str, i, imax, out, this.optional);
- }
- });
- token_OrGroup = create('OrGroup', {
- constructor: function(groups) {
- this.groups = groups,
- this.length = groups.length;
- },
- consume: function(str, i, imax, out) {
- var start = i,
- j = 0;
- for(; j < this.length; j++) {
- i = this.groups[j].consume(str, i, imax, out);
- if (i !== start)
- return i;
- }
- return i;
- }
- });
-
- function generateSetter(name) {
- return new Function('obj', 'val', 'obj.' + name + '= val;');
- }
- function create(name, Proto) {
- var Ctor = Proto.constructor;
- Proto.name = name;
- Proto.optional = false;
- Proto.token = null;
- Ctor.prototype = Proto;
- return Ctor;
- }
- }());
- // end:source ./tokens.js
-
- parser_ObjectLexer = ObjectLexer = function(pattern){
- if (arguments.length === 1 && typeof pattern === 'string') {
- return ObjectLexer_single(pattern);
- }
- return ObjectLexer_sequance(Array.prototype.slice.call(arguments));
- };
-
- function ObjectLexer_single (pattern){
- var tokens = _compile(pattern);
- return function(str, i, imax, out, optional){
- return _consume(tokens, str, i, imax, out, optional);
- };
- }
-
- var ObjectLexer_sequance;
- (function(){
- ObjectLexer_sequance = function(args) {
- var jmax = args.length,
- j = -1;
- while( ++j < jmax ) {
- args[j] = __createConsumer(args[j]);
- }
- return function(str, i, imax, out, optional){
- var start;
- j = -1;
- while( ++j < jmax ) {
- start = i;
- i = __consume(args[j], str, i, imax, out, optional);
- if (i === start)
- return start;
- }
- return i;
- }
- };
- function __consume(x, str, i, imax, out, optional) {
- if (typeof x === 'function') {
- return x(str, i, imax, out, optional);
- }
- return __consumeOptionals(x, str, i, imax, out, optional);
- }
- function __consumeOptionals(arr, str, i, imax, out, optional) {
- var start = i,
- jmax = arr.length,
- j = -1;
- while( ++j < jmax ){
- i = arr[j](str, i, imax, out, true);
- if (start !== i)
- return i;
- }
- if (optional !== true) {
- // notify
- arr[0](str, start, imax, out, optional);
- }
- return start;
- }
- function __createConsumer(mix) {
- if (typeof mix === 'string') {
- return ObjectLexer_single(mix);
- }
- // else Array
- var i = mix.length;
- while(--i > -1) mix[i] = ObjectLexer_single(mix[i]);
- return mix;
- }
- }());
-
- }());
- // end:source ./object/ObjectLexer
- // source ./parsers/var
- (function(){
- custom_Parsers['var'] = function(str, index, length, parent){
- var node = new VarNode('var', parent),
- start,
- c;
-
- var go_varName = 1,
- go_assign = 2,
- go_value = 3,
- go_next = 4,
- state = go_varName,
- token,
- key;
- while(true) {
- if (index < length && (c = str.charCodeAt(index)) < 33) {
- index++;
- continue;
- }
-
- if (state === go_varName) {
- start = index;
- index = cursor_refEnd(str, index, length);
- key = str.substring(start, index);
- state = go_assign;
- continue;
- }
-
- if (state === go_assign) {
- if (c !== 61 ) {
- // =
- parser_error(
- 'Assignment expected'
- , str
- , index
- , c
- , 'var'
- );
- return [node, index];
- }
- state = go_value;
- index++;
- continue;
- }
-
- if (state === go_value) {
- start = index;
- index++;
- switch(c){
- case 123:
- case 91:
- // { [
- index = cursor_groupEnd(str, index, length, c, c + 2);
- break;
- case 39:
- case 34:
- // ' "
- index = cursor_quoteEnd(str, index, length, c === 39 ? "'" : '"')
- break;
- default:
- while (index < length) {
- c = str.charCodeAt(index);
- if (c === 44 || c === 59) {
- //, ;
- break;
- }
- index++;
- }
- index--;
- break;
- }
- index++;
- node.attr[key] = str.substring(start, index);
- state = go_next;
- continue;
- }
- if (state === go_next) {
- if (c === 44) {
- // ,
- state = go_varName;
- index++;
- continue;
- }
- break;
- }
- }
- return [node, index, 0];
- };
-
- var VarNode = class_create(Dom.Node, {
- stringify: function() {
- var attr = this.attr;
- var str = 'var ';
- for(var key in attr){
- if (str !== 'var ')
- str += ',';
-
- str += key + '=' + attr[key];
- }
- return str + ';';
- },
- getObject: function(model, ctx, ctr){
- var obj = {},
- attr = this.attr,
- key;
- for(key in attr) {
- obj[key] = expression_eval(attr[key], model, ctx, ctr);
- }
- return obj;
- }
- });
- }());
- // end:source ./parsers/var
- // source ./parsers/content
- (function(){
-
- // source content/style
- var Style;
- (function () {
- Style = {
- transform: function(body, attr, parent) {
- if (attr.self != null) {
- var style = parent.attr.style;
- parent.attr.style = parser_ensureTemplateFunction((style || '') + body);
- return null;
- }
-
- var str = body;
- if (attr.scoped) {
- attr.scoped = null;
- str = style_scope(str, parent);
- }
-
- str = style_transformHost(str, parent);
- return str;
- }
- }
-
- var style_scope,
- style_transformHost;
- (function(){
- var counter = 0;
- var rgx_selector = /^([\s]*)([^\{\}]+)\{/gm;
- var rgx_host = /^([\s]*):host\s*(\(([^)]+)\))?\s*\{/gm;
-
- style_scope = function(css, parent){
- var id;
- return css.replace(rgx_selector, function(full, pref, selector){
- if (selector.indexOf(':host') !== -1)
- return full;
-
- if (id == null)
- id = getId(parent);
-
- var arr = selector.split(','),
- imax = arr.length,
- i = 0;
- for(; i < imax; i++) {
- arr[i] = id + ' ' + arr[i];
- }
- selector = arr.join(',');
- return pref + selector + '{';
- });
- };
-
- style_transformHost = function(css, parent) {
- var id;
- return css.replace(rgx_host, function(full, pref, ext, expr){
-
- return pref
- + (id || (id = getId(parent)))
- + (expr || '')
- + '{';
- });
- };
-
- function getId(parent) {
- if (parent == null) {
- log_warn('"style" should be inside elements node');
- return '';
- }
- var id = parent.attr.id;
- if (id == null) {
- id = parent.attr.id = 'scoped__css__' + (++counter);
- }
- return '#' + id;
- }
- }());
- }());
- // end:source content/style
-
- custom_Parsers['style' ] = createParser('style', Style.transform);
- custom_Parsers['script'] = createParser('script');
-
- custom_Tags['style' ] = createHandler('style');
- custom_Tags['script'] = createHandler('script');
-
- var ContentNode = class_create(Dom.Node, {
- content: null,
-
- stringify: function (stream) {
- stream.processHead(this);
-
- var body = this.content;
- if (body == null) {
- stream.print(';');
- return;
- }
- if (is_Function(body)) {
- body = body();
- }
-
- stream.openBlock('{');
- stream.print(body);
- stream.closeBlock('}');
- return;
- }
- });
-
- function createParser(name, transform) {
- return function (str, i, imax, parent) {
- var start = i,
- end,
- attr,
- hasBody,
- body,
- c;
-
- while(i < imax) {
- c = str.charCodeAt(i);
- if (c === 123 || c === 59 || c === 62) {
- //{;>
- break;
- }
- i++;
- }
-
- attr = parser_parseAttr(str, start, i);
- for (var key in attr) {
- attr[key] = parser_ensureTemplateFunction(attr[key]);
- }
-
- if (c === 62) {
- var nextI = cursor_skipWhitespace(str, i + 1, imax);
- var nextC = str.charCodeAt(nextI);
- if (nextC !== 34 && nextC !== 39){
- // "'
- var node = new Dom.Node(name, parent);
- node.attr = attr;
- // `>` handle single without literal as generic mask node
- return [ node, i, go_tag ];
- }
- }
-
- end = i;
- hasBody = c === 123 || c === 62;
-
- if (hasBody) {
- i++;
- if (c === 123) {
- end = cursor_groupEnd(str, i, imax, 123, 125); //{}
- body = str.substring(i, end);
- }
- if (c === 62) {
- var tuple = parser_parseLiteral(str, i, imax);
- if (tuple == null) {
- return null;
- }
- end = tuple[1];
- body = tuple[0];
- // move cursor one back to be consistance with the group
- end -= 1;
- }
-
- if (transform != null) {
- body = transform(body, attr, parent);
- if (body == null) {
- return [ null, end + 1 ];
- }
- }
-
- body = preprocess(name, body);
- if (name !== 'script') {
- body = parser_ensureTemplateFunction(body);
- }
- }
-
- var node = new ContentNode(name, parent);
- node.content = body;
- node.attr = attr;
- return [ node, end + 1, 0 ];
- };
- }
-
- function createHandler(name) {
- return class_create(customTag_Base, {
- meta: {
- mode: 'server'
- },
- body : null,
-
- constructor: function(node, model, ctx, el, ctr){
- var content = node.content;
- if (content == null && node.nodes) {
- var x = node.nodes[0];
- if (x.type === Dom.TEXTNODE) {
- content = x.content;
- } else {
- content = jmask(x.nodes).text(model, ctr);
- }
- }
-
- this.body = is_Function(content)
- ? content('node', model, ctx, el, ctr)
- : content
- ;
- },
- render: function(model, ctx, container) {
- var el = document.createElement(name),
- body = this.body,
- attr = this.attr;
- el.textContent = body;
- for(var key in attr) {
- var val = attr[key];
- if (val != null) {
- el.setAttribute(key, val);
- }
- }
- container.appendChild(el);
- }
- });
- }
-
- function preprocess(name, body) {
- var fn = __cfg.preprocessor[name];
- if (fn == null) {
- return body;
- }
- var result = fn(body);
- if (result == null) {
- log_error('Preprocessor must return a string');
- return body;
- }
- return result;
- }
- }());
- // end:source ./parsers/content
- // source ./parsers/import
- (function(){
- var IMPORT = 'import',
- IMPORTS = 'imports';
-
- custom_Parsers[IMPORT] = function(str, i, imax, parent){
- var obj = {
- exports: null,
- alias: null,
- path: null
- };
- var end = lex_(str, i, imax, obj);
- return [ new ImportNode(parent, obj), end, 0 ];
- };
- custom_Parsers_Transform[IMPORT] = function(current) {
- if (current.tagName === IMPORTS) {
- return null;
- }
- var imports = new ImportsNode('imports', current);
- current.appendChild(imports);
- return imports;
- };
-
- var lex_ = ObjectLexer(
- [ 'from "$path"?( is $contentType)'
- , '* as $alias from "$path"?( is $contentType)'
- , '$$exports[$name?( as $alias)](,) from "$path"?( is $contentType)'
- ]
- );
-
- var ImportsNode = class_create(Dom.Node, {
- stringify: function (stream) {
- stream.process(this.nodes);
- }
- });
-
- var ImportNode = class_create({
- type: Dom.COMPONENT,
- tagName: IMPORT,
-
- path: null,
- exports: null,
- alias: null,
-
- constructor: function(parent, data){
- this.path = data.path;
- this.alias = data.alias;
- this.exports = data.exports;
- this.contentType = data.contentType;
- this.parent = parent;
- },
- stringify: function(){
- var from = " from '" + this.path + "'";
-
- var type = this.contentType;
- if (type != null) {
- from += ' is ' + type;
- }
- from += ';';
-
- if (this.alias != null) {
- return IMPORT + " * as " + this.alias + from;
- }
- if (this.exports != null) {
- var arr = this.exports,
- str = '',
- imax = arr.length,
- i = -1, x;
- while( ++i < imax ){
- x = arr[i];
- str += x.name;
- if (x.alias) {
- str += ' as ' + x.alias;
- }
- if (i !== imax - 1) {
- str +=', ';
- }
- }
- return IMPORT + ' ' + str + from;
- }
- return IMPORT + from;
- }
- });
-
- }());
- // end:source ./parsers/import
- // source ./parsers/define
- (function(){
- createParser('define');
- createParser('let');
-
- function createParser (tagName) {
- custom_Parsers[tagName] = function(str, i, imax, parent){
- var node = new DefineNode(tagName, parent);
- var end = lex_(str, i, imax, node);
- return [ node, end, go_tag ];
- };
- }
- var lex_ = ObjectLexer(
- '$name'
- , '?( as $$as(*()))?( extends $$extends[$$compo](,))'
- , '{'
- );
- var DefineNode = class_create(Dom.Node, {
- 'name': null,
- 'extends': null,
- 'as': null,
-
- stringify: function(stream){
- var extends_ = this['extends'],
- as_ = this['as'],
- str = '';
- if (as_ != null && as_.length !== 0) {
- str += ' as (' + as_ + ')';
- }
- if (extends_ != null && extends_.length !== 0) {
- str += ' extends ';
- var imax = extends_.length,
- i = -1, x;
- while( ++i < imax ){
- str += extends_[i].compo;
- if (i < imax - 1)
- str += ', ';
- }
- }
-
- var head = this.tagName + ' ' + this.name + str;
- stream.write(head)
- stream.openBlock('{');
- stream.process(this.nodes);
- stream.closeBlock('}');
- },
- });
-
- }());
- // end:source ./parsers/define
- // source ./parsers/methods
- (function(){
- function create(tagName){
- return function(str, i, imax, parent) {
- var start = str.indexOf('{', i) + 1,
- head = parseHead(
- tagName, str.substring(i, start - 1)
- );
- if (head == null) {
- parser_error('Method head syntax error', str, i);
- }
- var end = cursor_groupEnd(str, start, imax, 123, 125),
- body = str.substring(start, end),
- node = head == null
- ? null
- : new MethodNode(tagName, head.name, head.args, body, parent)
- ;
- return [ node, end + 1, 0 ];
- };
- }
-
- function parseHead(name, str) {
- var parts = /([^\(\)\n]+)\s*(\(([^\)]*)\))?/.exec(str);
- if (parts == null) {
- return null;
- }
- var methodName = parts[1].trim();
- var str = parts[3],
- methodArgs = str == null ? [] : str.replace(/\s/g, '').split(',');
- return new MethodHead(methodName, methodArgs);
- }
- function MethodHead(name, args) {
- this.name = name;
- this.args = args;
- }
- function compileFn(args, body, sourceUrl) {
- var arr = _Array_slice.call(args);
- var compile = __cfg.preprocessor.script;
- if (compile != null) {
- body = compile(body);
- }
- if (sourceUrl != null) {
- body += '\n//# sourceURL=' + sourceUrl
- }
- arr.push(body);
- return new (Function.bind.apply(Function, [null].concat(arr)));
- }
-
- var MethodNode = class_create(Dom.Component.prototype, {
- 'name': null,
- 'body': null,
- 'args': null,
-
- 'fn': null,
-
- constructor: function(tagName, name, args, body, parent){
- this.tagName = tagName;
- this.name = name;
- this.args = args;
- this.body = body;
- this.parent = parent;
-
- var sourceUrl = null;
- //if DEBUG
- var ownerName = parent.tagName;
- if (ownerName === 'let' || ownerName === 'define') {
- ownerName += '_' + parent.name;
- }
- sourceUrl = constructSourceUrl(tagName, name, parent);
- //endif
- this.fn = compileFn(args, body, sourceUrl);
- },
- stringify: function(stream){
- var head = this.tagName
- + ' '
- + this.name
- + '('
- + this.args.join(',')
- + ')';
- stream.write(head);
- stream.openBlock('{');
- stream.print(this.body);
- stream.closeBlock('}');
- }
- });
-
- var constructSourceUrl;
- (function(){
- constructSourceUrl = function (methodType, methodName, owner) {
- var ownerName = owner.tagName,
- parent = owner,
- stack = '',
- tag;
- while(parent != null) {
- tag = parent.tagName;
- if ('let' === tag || 'define' === tag) {
- if (stack !== '') {
- stack = '.' + stack;
- }
- stack = parent.name + stack;
- }
- parent = parent.parent;
- }
- if ('let' !== ownerName && 'define' !== ownerName) {
- if (stack !== '') {
- stack += '_';
- }
- stack += ownerName
- }
- var url = stack + '_' + methodType + '_' + methodName;
- var index = null
- if (_sourceUrls[url] !== void 0) {
- index = ++_sourceUrls[url];
- }
- if (index != null) {
- url += '_' + index;
- }
- _sourceUrls[url] = 1;
- return 'dynamic://MaskJS/' + url;
- };
- var _sourceUrls = {};
- }());
-
- custom_Parsers['slot' ] = create('slot');
- custom_Parsers['event'] = create('event');
- custom_Parsers['function'] = create('function');
- }());
-
- // end:source ./parsers/methods
- // source ./html/parser
- (function () {
- var state_closeTag = 21;
-
- /**
- * Parse **Html** template to the AST tree
- * @param {string} template - Html Template
- * @returns {MaskNode}
- * @memberOf mask
- * @method parseHtml
- */
- parser_parseHtml = function(str) {
- var current = new Fragment(),
- fragment = current,
- state = go_tag,
- i = 0,
- imax = str.length,
- token,
- c, // charCode
- start;
-
- outer: while (i <= imax) {
- i = cursor_skipWhitespace(str, i, imax);
-
- if (state === state_attr) {
- i = parser_parseAttrObject(str, i, imax, current.attr);
- if (i === imax) {
- break;
- }
- handleNodeAttributes(current);
-
- switch (char_(str, i)) {
- case 47: // /
- current = current.parent;
- i = until_(str, i, imax, 62);
- i++;
- break;
- case 62: // >
- if (SINGLE_TAGS[current.tagName.toLowerCase()] === 1) {
- current = current.parent;
- }
- break;
- }
- i++;
- if (current.tagName === 'mask') {
- start = i;
- i = str.indexOf('', start);
- var mix = parser_parse(str.substring(start, i));
- var nodes = current.parent.nodes;
- nodes.splice(nodes.length - 1, 1);
- current = current.parent;
- if (mix.type === Dom.FRAGMENT) {
- _appendMany(current, mix.nodes);
- } else {
- current.appendChild(mix);
- }
- i += 7; // @TODO proper search
- }
-
- state = state_literal;
- continue outer;
- }
- c = char_(str, i);
- if (c === 60) {
- //<
- c = char_(str, ++i)
- if (c === 33 &&
- char_(str, i + 1) === 45 &&
- char_(str, i + 2) === 45) {
- //!--
- // COMMENT
- i = str.indexOf('-->', i + 3) + 3;
- if (i === 2) {
- // if DEBUG
- parser_warn('Comment has no ending', str, i);
- // endif
- i = imax;
- }
- continue;
- }
- if (c < 33) {
- i = cursor_skipWhitespace(str, i, imax);
- }
- c = char_(str, i, imax);
- if (c === 47 /*/*/) {
- state = state_closeTag;
- i++;
- i = cursor_skipWhitespace(str, i, imax);
- }
-
- start = i;
- i = cursor_tokenEnd(str, i + 1, imax);
- token = str.substring(start, i);
-
- if (state === state_closeTag) {
- current = tag_Close(current, token.toLowerCase());
- state = state_literal;
- i = until_(str, i, imax, 62 /*>*/);
- i ++;
- continue;
- }
- // open tag
- current = tag_Open(token, current);
- state = state_attr;
- continue;
- }
-
- // LITERAL
- start = i;
- token = '';
- while(i <= imax) {
- c = char_(str, ++i);
- if (c === 60 /*<*/) {
- // MAYBE NODE
- c = char_(str, i + 1);
- if (c === 36 || c === 95 || c === 58 || 43) {
- // $ _ : +
- break;
- }
- if ((65 <= c && c <= 90) || // A-Z
- (97 <= c && c <= 122)) { // a-z
- break;
- }
- }
- if (c === 38 /*&*/) {
- // ENTITY
- var Char = null;
- var ent = null;
- ent = unicode_(str, i + 1);
- if (ent != null) {
- Char = unicode_toChar(ent);
- } else {
- ent = entity_(str, i + 1);
- if (ent != null) {
- Char = entity_toChar(ent);
- }
- }
- if (Char != null) {
- token += str.substring(start, i) + Char;
- start = i + ent.length + 1 /*;*/;
- }
- }
- }
- token += str.substring(start, i);
- if (token !== '') {
- token = parser_ensureTemplateFunction(token);
- current.appendChild(new TextNode(token, current));
- }
- }
-
-
-
- var nodes = fragment.nodes;
- return nodes != null && nodes.length === 1
- ? nodes[0]
- : fragment
- ;
- };
-
-
- function char_(str, i) {
- return str.charCodeAt(i);
- }
- function until_(str, i, imax, c) {
- for(; i < imax; i++) {
- if (c === char_(str, i)) {
- return i;
- }
- }
- return i;
- }
- function unicode_(str, i, imax) {
- var lim = 7,
- c = char_(str, i);
- if (c !== 35 /*#*/) {
- return null;
- }
- var start = i + 1;
- while (++i < imax) {
- if (--lim === 0) {
- return null;
- }
- c = char_(str, i);
- if (48 <= c && c <= 57 /*0-9*/) {
- continue;
- }
- if (65 <= c && c <= 70 /*A-F*/) {
- continue;
- }
- if (c === 120 /*x*/) {
- continue;
- }
- if (c === 59 /*;*/) {
- return str.substring(start, i);
- }
- break;
- }
- return null;
- }
- function unicode_toChar(unicode) {
- var num = Number('0' + unicode);
- if (num !== num) {
- parser_warn('Invalid Unicode Char', unicode);
- return '';
- }
- return String.fromCharCode(num);
- }
- function entity_(str, i, imax) {
- var lim = 10,
- start = i;
- for(; i < imax; i++, lim--) {
- if (lim === 0) {
- return null;
- }
- var c = char_(str, i);
- if (c === 59 /*;*/) {
- break;
- }
- if ((48 <= c && c <= 57) || // 0-9
- (65 <= c && c <= 90) || // A-Z
- (97 <= c && c <= 122)) { // a-z
- i++;
- continue;
- }
- return null;
- }
- return str.substring(start, i);
- }
-
- var entity_toChar;
- (function (d) {
-
- //if BROWSER
- if (d == null) {
- return;
- }
- var i = d.createElement('i');
- entity_toChar = function(ent){
- i.innerHTML = '&' + ent + ';';
- return i.textContent;
- };
- //endif
-
-
- }(document));
-
- var SINGLE_TAGS = {
- area : 1,
- base : 1,
- br : 1,
- col : 1,
- embed : 1,
- hr : 1,
- img : 1,
- input : 1,
- keygen: 1,
- link : 1,
- menuitem: 1,
- meta : 1,
- param : 1,
- source: 1,
- track : 1,
- wbr : 1
- };
- var IMPLIES_CLOSE;
- (function(){
- var formTags = {
- input: 1,
- option: 1,
- optgroup: 1,
- select: 1,
- button: 1,
- datalist: 1,
- textarea: 1
- };
- IMPLIES_CLOSE = {
- tr : { tr:1, th:1, td:1 },
- th : { th:1 },
- td : { thead:1, td:1 },
- body : { head:1, link:1, script:1 },
- li : { li:1 },
- p : { p:1 },
- h1 : { p:1 },
- h2 : { p:1 },
- h3 : { p:1 },
- h4 : { p:1 },
- h5 : { p:1 },
- h6 : { p:1 },
- select : formTags,
- input : formTags,
- output : formTags,
- button : formTags,
- datalist: formTags,
- textarea: formTags,
- option : { option:1 },
- optgroup: { optgroup:1 }
- };
- }());
-
- function tag_Close(current, name) {
- if (SINGLE_TAGS[name] === 1) {
- // donothing
- return current;
- }
-
- var x = current;
- while(x != null) {
- if (x.tagName != null && x.tagName.toLowerCase() === name) {
- break;
- }
- x = x.parent;
- }
- if (x == null) {
- parser_warn('Unmatched closing tag', name);
- return current;
- }
- return x.parent || x;
- }
- function tag_Open(name, current) {
- var node = current;
- var TAGS = IMPLIES_CLOSE[name];
- if (TAGS != null) {
- while (node.parent != null && node.parent.tagName && TAGS[node.parent.tagName.toLowerCase()] === 1) {
- node = node.parent;
- }
- }
-
- var next = new Node(name, node);
- node.appendChild(next);
- return next;
- }
-
- function handleNodeAttributes(node) {
- var obj = node.attr,
- key, val;
- for(key in obj) {
- val = obj[key];
- if (val != null && val !== key) {
- obj[key] = parser_ensureTemplateFunction(val);
- }
- }
- if (obj.expression != null) {
- node.expression = obj.expression;
- node.type = Dom.STATEMENT;
- }
- }
-
- function _appendMany(node, nodes) {
- arr_each(nodes, function(x){
- node.appendChild(x)
- });
- }
- }());
- // end:source ./html/parser
- // source ./mask/parser
- (function(){
-
- /**
- * Parse **Mask** template to the AST tree
- * @param {string} template - Mask Template
- * @returns {MaskNode}
- * @memberOf mask
- * @method parse
- */
- parser_parse = function(template) {
- var current = new Fragment(),
- fragment = current,
- state = go_tag,
- last = state_tag,
- index = 0,
- length = template.length,
- classNames,
- token,
- tokenIndex,
- key,
- value,
- next,
- c, // charCode
- start,
- nextC;
-
- fragment.source = template;
- outer: while (true) {
-
- while (index < length && (c = template.charCodeAt(index)) < 33) {
- index++;
- }
-
- // COMMENTS
- if (c === 47) {
- // /
- nextC = template.charCodeAt(index + 1);
- if (nextC === 47){
- // inline (/)
- index++;
- while (c !== 10 && c !== 13 && index < length) {
- // goto newline
- c = template.charCodeAt(++index);
- }
- continue;
- }
- if (nextC === 42) {
- // block (*)
- index = template.indexOf('*/', index + 2) + 2;
- if (index === 1) {
- // if DEBUG
- parser_warn('Block comment has no ending', template, index);
- // endif
- index = length;
- }
- continue;
- }
- }
-
- if (last === state_attr) {
- if (classNames != null) {
- current.attr['class'] = parser_ensureTemplateFunction(classNames);
- classNames = null;
- }
- if (key != null) {
- current.attr[key] = key;
- key = null;
- token = null;
- }
- }
-
- if (token != null) {
-
- if (state === state_attr) {
-
- if (key == null) {
- key = token;
- } else {
- value = token;
- }
-
- if (key != null && value != null) {
- if (key !== 'class') {
- current.attr[key] = value;
- } else {
- classNames = classNames == null ? value : classNames + ' ' + value;
- }
-
- key = null;
- value = null;
- }
-
- } else if (last === state_tag) {
-
- //next = custom_Tags[token] != null
- // ? new Component(token, current, custom_Tags[token])
- // : new Node(token, current);
- var parser = custom_Parsers[token];
- if (parser != null) {
- // Parser should return: [ parsedNode, nextIndex, nextState ]
- var tuple = parser(
- template
- , index
- , length
- , current
- );
- var node = tuple[0],
- nextState = tuple[2];
-
- index = tuple[1];
- state = nextState === 0
- ? go_tag
- : nextState;
- if (node != null) {
- node.sourceIndex = tokenIndex;
-
- var transform = custom_Parsers_Transform[token];
- if (transform != null) {
- var x = transform(current, node);
- if (x != null) {
- // make the current node single, to exit this and the transformed node on close
- current.__single = true;
- current = x;
- }
- }
-
- current.appendChild(node);
- if (nextState !== 0) {
- current = node;
- } else {
- if (current.__single === true) {
- do {
- current = current.parent;
- } while (current != null && current.__single != null);
- }
- }
- }
- token = null;
- continue;
- }
-
-
- next = new Node(token, current);
- next.sourceIndex = tokenIndex;
-
- current.appendChild(next);
- current = next;
- state = state_attr;
-
- } else if (last === state_literal) {
-
- next = new TextNode(token, current);
- current.appendChild(next);
-
- if (current.__single === true) {
- do {
- current = current.parent;
- } while (current != null && current.__single != null);
- }
- state = go_tag;
-
- }
-
- token = null;
- }
-
- if (index >= length) {
- if (state === state_attr) {
- if (classNames != null) {
- current.attr['class'] = parser_ensureTemplateFunction(classNames);
- }
- if (key != null) {
- current.attr[key] = key;
- }
- }
- c = null;
- break;
- }
-
- if (state === go_up) {
- current = current.parent;
- while (current != null && current.__single != null) {
- current = current.parent;
- }
- if (current == null) {
- current = fragment;
- parser_warn(
- 'Unexpected tag closing'
- , template
- , cursor_skipWhitespaceBack(template, index - 1)
- );
- }
- state = go_tag;
- }
-
- switch (c) {
- case 123:
- // {
- last = state;
- state = go_tag;
- index++;
- continue;
- case 62:
- // >
- last = state;
- state = go_tag;
- index++;
- current.__single = true;
- continue;
- case 59:
- // ;
- if (current.nodes != null) {
- // skip ; , when node is not a single tag (else goto 125)
- index++;
- continue;
- }
- /* falls through */
- case 125:
- // ;}
- if (c === 125 && (state === state_tag || state === state_attr)) {
- // single tag was not closed with `;` but closing parent
- index--;
- }
- index++;
- last = state;
- state = go_up;
- continue;
- case 39:
- case 34:
- // '"
- // Literal - could be as textnode or attribute value
- if (state === go_attrVal) {
- state = state_attr;
- } else {
- last = state = state_literal;
- }
- index++;
-
- var isEscaped = false,
- isUnescapedBlock = false,
- _char = c === 39 ? "'" : '"';
-
- start = index;
-
- while ((index = template.indexOf(_char, index)) > -1) {
- if (template.charCodeAt(index - 1) !== 92 /*'\\'*/ ) {
- break;
- }
- isEscaped = true;
- index++;
- }
- if (index === -1) {
- parser_warn('Literal has no ending', template, start - 1);
- index = length;
- }
-
- if (index === start) {
- nextC = template.charCodeAt(index + 1);
- if (nextC === 124 || nextC === c) {
- // | (obsolete) or triple quote
- isUnescapedBlock = true;
- start = index + 2;
- index = template.indexOf((nextC === 124 ? '|' : _char) + _char + _char, start);
-
- if (index === -1)
- index = length;
- }
- }
-
- tokenIndex = start;
- token = template.substring(start, index);
-
- if (isEscaped === true) {
- token = token.replace(__rgxEscapedChar[_char], _char);
- }
-
- if (state !== state_attr || key !== 'class') {
- token = parser_ensureTemplateFunction(token);
- }
- index += isUnescapedBlock ? 3 : 1;
- continue;
- }
-
- if (state === go_tag) {
- last = state_tag;
- state = state_tag;
- //next_Type = Dom.NODE;
-
- if (c === 46 /* . */ || c === 35 /* # */ ) {
- tokenIndex = index;
- token = 'div';
- continue;
- }
-
- //-if (c === 58 || c === 36 || c === 64 || c === 37) {
- // // : /*$ @ %*/
- // next_Type = Dom.COMPONENT;
- //}
-
- }
-
- else if (state === state_attr) {
- if (c === 46) {
- // .
- index++;
- key = 'class';
- state = go_attrHeadVal;
- }
-
- else if (c === 35) {
- // #
- index++;
- key = 'id';
- state = go_attrHeadVal;
- }
-
- else if (c === 61) {
- // =;
- index++;
- state = go_attrVal;
-
- if (last === state_tag && key == null) {
- parser_warn('Unexpected tag assignment', template, index, c, state);
- }
- continue;
- }
-
- else if (c === 40) {
- // (
- start = 1 + index;
- index = 1 + cursor_groupEnd(template, start, length, c, 41 /* ) */);
- current.expression = template.substring(start, index - 1);
- current.type = Dom.STATEMENT;
- continue;
- }
-
- else {
-
- if (key != null) {
- tokenIndex = index;
- token = key;
- continue;
- }
- }
- }
-
- if (state === go_attrVal || state === go_attrHeadVal) {
- last = state;
- state = state_attr;
- }
-
-
-
- /* TOKEN */
-
- var isInterpolated = false;
-
- start = index;
- while (index < length) {
-
- c = template.charCodeAt(index);
-
- if (c === interp_code_START) {
- var nextC = template.charCodeAt(index + 1);
- if (nextC === interp_code_OPEN) {
- isInterpolated = true;
- index = 1 + cursor_groupEnd(
- template
- , index + 2
- , length
- , interp_code_START
- , interp_code_CLOSE
- );
- c = template.charCodeAt(index);
- }
- else if ((nextC >= 65 && nextC <= 122) || nextC === 36 || nextC === 95) {
- //A-z$_
- isInterpolated = true;
- }
- }
- if (c === 64 && template.charCodeAt(index + 1) === 91) {
- //@[
- index = cursor_groupEnd(template, index + 2, length, 91, 93) + 1;
- c = template.charCodeAt(index);
- }
-
- // if DEBUG
- if (c === 0x0027 || c === 0x0022 || c === 0x002F || c === 0x003C || c === 0x002C) {
- // '"/<,
- parser_error('Unexpected char', template, index, c, state);
- break outer;
- }
- // endif
-
-
- if (last !== go_attrVal && (c === 46 || c === 35)) {
- // .#
- // break on .# only if parsing attribute head values
- break;
- }
-
- if (c < 33 ||
- c === 61 ||
- c === 62 ||
- c === 59 ||
- c === 40 ||
- c === 123 ||
- c === 125) {
- // =>;({}
- break;
- }
- index++;
- }
-
- token = template.substring(start, index);
- tokenIndex = start;
- if (token === '') {
- parser_warn('String expected', template, index, c, state);
- break;
- }
-
- if (isInterpolated === true) {
- if (state === state_tag) {
- parser_warn('Invalid interpolation (in tag name)'
- , template
- , index
- , token
- , state);
- break;
- }
- if (state === state_attr) {
- if (key === 'id' || last === go_attrVal) {
- token = parser_ensureTemplateFunction(token);
- }
- else if (key !== 'class') {
- // interpolate class later
- parser_warn('Invalid interpolation (in attr name)'
- , template
- , index
- , token
- , state);
- break;
- }
- }
- }
- }
-
- if (c !== c) {
- parser_warn('IndexOverflow'
- , template
- , index
- , c
- , state
- );
- }
-
- // if DEBUG
- var parent = current.parent;
- if (parent != null &&
- parent !== fragment &&
- parent.__single !== true &&
- current.nodes != null &&
- parent.tagName !== 'imports') {
- parser_warn('Tag was not closed: ' + current.tagName, template)
- }
- // endif
-
-
- var nodes = fragment.nodes;
- return nodes != null && nodes.length === 1
- ? nodes[0]
- : fragment
- ;
- };
-
-
- }());
-
- // end:source ./mask/parser
- // source ./mask/partials/attributes
- (function(){
-
- parser_parseAttr = function(str, start, end){
- var attr = {},
- i = start,
- key, val, c;
- while(i < end) {
- i = cursor_skipWhitespace(str, i, end);
- if (i === end)
- break;
-
- start = i;
- for(; i < end; i++){
- c = str.charCodeAt(i);
- if (c === 61 || c < 33) break;
- }
-
- key = str.substring(start, i);
-
- i = cursor_skipWhitespace(str, i, end);
- if (i === end) {
- attr[key] = key;
- break;
- }
- if (str.charCodeAt(i) !== 61 /*=*/) {
- attr[key] = key;
- continue;
- }
-
- i = start = cursor_skipWhitespace(str, i + 1, end);
- c = str.charCodeAt(i);
- if (c === 34 || c === 39) {
- // "|'
- i = cursor_quoteEnd(str, i + 1, end, c === 39 ? "'" : '"');
-
- attr[key] = str.substring(start + 1, i);
- i++;
- continue;
- }
- i = cursor_goToWhitespace(str, i, end);
- attr[key] = str.substring(start, i);
- }
- return attr;
- };
-
- parser_parseAttrObject = function(str, i, imax, attr){
- var state_KEY = 1,
- state_VAL = 2,
- state_END = 3,
- state = state_KEY,
- token, index, key, c;
-
- outer: while(i < imax) {
- i = cursor_skipWhitespace(str, i, imax);
- if (i === imax)
- break;
-
- index = i;
- c = str.charCodeAt(i);
- switch (c) {
- case 61 /* = */:
- i++;
- state = state_VAL;
- continue outer;
- case 123:
- case 59:
- case 62:
- case 47:
- // {;>/
- state = state_END;
- break;
- case 40:
- //()
- i = cursor_groupEnd(str, ++index, imax, 40, 41);
- if (key != null) {
- attr[key] = key;
- }
- key = 'expression';
- token = str.substring(index, i);
- i++;
- state = state_VAL;
- break;
- case 39:
- case 34:
- //'"
- i = cursor_quoteEnd(str, ++index, imax, c === 39 ? "'" : '"');
- token = str.substring(index, i);
- i++;
- break;
- default:
- i++;
- for(; i < imax; i++){
- c = str.charCodeAt(i);
- if (c < 33 || c === 61 || c === 123 || c === 59 || c === 62 || c === 47) {
- // ={;>/
- break;
- }
- }
- token = str.substring(index, i);
- break;
- }
-
- if (token === '') {
- parser_warn('Token not readable', str, i);
- i++;
- continue;
- }
-
- if (state === state_VAL) {
- attr[key] = token;
- state = state_KEY;
- key = null;
- continue;
- }
- if (key != null) {
- attr[key] = key;
- key = null;
- }
- if (state === state_END) {
- break;
- }
- key = token;
- }
- return i;
- };
-
- }());
- // end:source ./mask/partials/attributes
- // source ./mask/partials/literal
- (function(){
- parser_parseLiteral = function(str, start, imax){
- var i = cursor_skipWhitespace(str, start, imax);
-
- var c = str.charCodeAt(i);
- if (c !== 34 && c !== 39) {
- // "'
- parser_error("A quote is expected", str, i);
- return null;
- }
-
- var isEscaped = false,
- isUnescapedBlock = false,
- _char = c === 39 ? "'" : '"';
-
- start = ++i;
-
- while ((i = str.indexOf(_char, i)) > -1) {
- if (str.charCodeAt(i - 1) !== 92 /*'\\'*/ ) {
- break;
- }
- isEscaped = true;
- i++;
- }
-
- if (i === -1) {
- parser_warn('Literal has no ending', str, start - 1);
- i = imax;
- }
-
- if (i === start) {
- var nextC = str.charCodeAt(i + 1);
- if (nextC === c) {
- isUnescapedBlock = true;
- start = i + 2;
- i = str.indexOf(_char + _char + _char, start);
- if (i === -1)
- i = imax;
- }
- }
-
- var token = str.substring(start, i);
- if (isEscaped === true) {
- token = token.replace(__rgxEscapedChar[_char], _char);
- }
- i += isUnescapedBlock ? 3 : 1;
- return [ token, i ];
- };
- }());
- // end:source ./mask/partials/literal
-
-
- }(Dom.Node, Dom.TextNode, Dom.Fragment, Dom.Component));
-
- // end:source parser/
-
- // source builder/
- var builder_componentID = 0,
- builder_build,
- builder_Ctx;
-
- (function(){
-
- // source ctx
- (function(){
-
- builder_Ctx = class_create(class_Dfr, {
- constructor: function(data){
- obj_extend(this, data);
- },
- // Is true, if some of the components in a ctx is async
- async: false,
- // List of busy components
- defers: null /*Array*/,
-
- // NodeJS
- // Track components ID
- _id: null,
- // ModelsBuilder for HTML serialization
- _models: null,
-
- // ModulesBuilder fot HTML serialization
- _modules: null,
-
- _redirect: null,
- _rewrite: null
- });
- }());
- // end:source ctx
- // source util
- var builder_resumeDelegate,
- builder_pushCompo;
-
- (function(){
-
- builder_resumeDelegate = function (ctr, model, ctx, container, children, finilizeFn){
- var anchor = document.createComment('');
- container.appendChild(anchor);
- return function(){
- return _resume(ctr, model, ctx, anchor, children, finilizeFn);
- };
- };
- builder_pushCompo = function (ctr, compo) {
- var compos = ctr.components;
- if (compos == null) {
- ctr.components = [ compo ];
- return;
- }
- compos.push(compo);
- };
-
- // == private
-
- function _resume(ctr, model, ctx, anchorEl, children, finilize) {
-
- if (ctr.tagName != null && ctr.tagName !== ctr.compoName) {
- ctr.nodes = {
- tagName: ctr.tagName,
- attr: ctr.attr,
- nodes: ctr.nodes,
- type: 1
- };
- }
- if (ctr.model != null) {
- model = ctr.model;
- }
-
- var nodes = ctr.nodes,
- elements = [];
- if (nodes != null) {
-
- var isarray = nodes instanceof Array,
- length = isarray === true ? nodes.length : 1,
- i = 0,
- childNode = null,
- fragment = document.createDocumentFragment();
-
- for (; i < length; i++) {
- childNode = isarray === true ? nodes[i] : nodes;
-
- builder_build(childNode, model, ctx, fragment, ctr, elements);
- }
-
- anchorEl.parentNode.insertBefore(fragment, anchorEl);
- }
-
-
- // use or override custom attr handlers
- // in Compo.handlers.attr object
- // but only on a component, not a tag ctr
- if (ctr.tagName == null) {
- var attrHandlers = ctr.handlers && ctr.handlers.attr,
- attrFn,
- key;
- for (key in ctr.attr) {
-
- attrFn = null;
-
- if (attrHandlers && is_Function(attrHandlers[key])) {
- attrFn = attrHandlers[key];
- }
-
- if (attrFn == null && is_Function(custom_Attributes[key])) {
- attrFn = custom_Attributes[key];
- }
-
- if (attrFn != null) {
- attrFn(anchorEl, ctr.attr[key], model, ctx, elements[0], ctr);
- }
- }
- }
-
- if (is_Function(finilize)) {
- finilize.call(
- ctr
- , elements
- , model
- , ctx
- , anchorEl.parentNode
- );
- }
-
-
- if (children != null && children !== elements){
- var il = children.length,
- jl = elements.length,
- j = -1;
-
- while(++j < jl){
- children[il + j] = elements[j];
- }
- }
- }
-
- }());
- // end:source util
- // source build_textNode
- var build_textNode;
- (function(){
- build_textNode = function build_textNode(node, model, ctx, el, ctr) {
-
- var content = node.content;
- if (is_Function(content)) {
- var result = content(
- 'node', model, ctx, el, ctr
- );
- if (typeof result === 'string') {
- append_textNode(el, result);
- return;
- }
- // result is array with some htmlelements
- var text = '',
- jmax = result.length,
- j = 0,
- x;
-
- for (; j < jmax; j++) {
- x = result[j];
-
- if (typeof x === 'object') {
- // In this casee result[j] should be any HTMLElement
- if (text !== '') {
- append_textNode(el, text);
- text = '';
- }
- if (x.nodeType == null) {
- text += x.toString();
- continue;
- }
- el.appendChild(x);
- continue;
- }
- text += x;
- }
- if (text !== '') {
- append_textNode(el, text);
- }
- return;
- }
- append_textNode(el, content);
- };
-
- var append_textNode;
- (function(doc){
- append_textNode = function(el, text){
- el.appendChild(doc.createTextNode(text));
- };
- }(document));
- }());
- // end:source build_textNode
- // source build_node
- var build_node;
- (function(){
- build_node = function build_node(node, model, ctx, container, ctr, children){
-
- var tagName = node.tagName,
- attr = node.attr;
-
- var el = el_create(tagName);
- if (el == null)
- return;
-
- if (children != null){
- children.push(el);
- attr['x-compo-id'] = ctr.ID;
- }
-
- // ++ insert el into container before setting attributes, so that in any
- // custom util parentNode is available. This is for mask.node important
- // http://jsperf.com/setattribute-before-after-dom-insertion/2
- if (container != null) {
- container.appendChild(el);
- }
-
- var key, mix, val, fn;
- for(key in attr) {
- mix = attr[key];
- if (is_Function(mix)) {
- var result = mix('attr', model, ctx, el, ctr, key);
- if (result == null) {
- continue;
- }
- if (typeof result === 'string') {
- val = result;
- } else if (is_ArrayLike(result)){
- if (result.length === 0) {
- continue;
- }
- val = result.join('');
- } else {
- val = result;
- }
- } else {
- val = mix;
- }
-
- if (val != null && val !== '') {
- fn = custom_Attributes[key];
- if (fn != null) {
- fn(node, val, model, ctx, el, ctr, container);
- } else {
- el.setAttribute(key, val);
- }
- }
- }
- return el;
- };
-
- var el_create;
- (function(doc){
- el_create = function(name){
- // if DEBUG
- try {
- // endif
- return doc.createElement(name);
- // if DEBUG
- } catch(error) {
- log_error(name, 'element cannot be created. If this should be a custom handler tag, then controller is not defined');
- return null;
- }
- // endif
- };
- }(document));
- }());
- // end:source build_node
- // source build_component
- var build_compo;
- (function(){
- build_compo = function(node, model, ctx, container, ctr, children){
-
- var compoName = node.tagName,
- Handler;
-
- if (node.controller != null)
- Handler = node.controller;
-
- if (Handler == null)
- Handler = custom_Tags[compoName];
-
- if (Handler == null)
- return build_NodeAsCompo(node, model, ctx, container, ctr, children);
-
- var isStatic = false,
- handler, attr, key;
-
- if (typeof Handler === 'function') {
- handler = new Handler(node, model, ctx, container, ctr);
- } else{
- handler = Handler;
- isStatic = true;
- }
- var fn = isStatic
- ? build_Static
- : build_Component
- ;
- return fn(handler, node, model, ctx, container, ctr, children);
- };
-
- // PRIVATE
-
- function build_Component(compo, node, model, ctx, container, ctr, children){
- var attr, key;
-
- compo.ID = ++builder_componentID;
- compo.attr = attr = attr_extend(compo.attr, node.attr);
- compo.parent = ctr;
- compo.expression = node.expression;
-
- if (compo.compoName == null)
- compo.compoName = node.tagName;
-
- if (compo.model == null)
- compo.model = model;
-
- if (compo.nodes == null)
- compo.nodes = node.nodes;
-
- for (key in attr) {
- if (typeof attr[key] === 'function')
- attr[key] = attr[key]('attr', model, ctx, container, ctr, key);
- }
-
-
- listeners_emit(
- 'compoCreated'
- , compo
- , model
- , ctx
- , container
- );
-
- if (is_Function(compo.renderStart))
- compo.renderStart(model, ctx, container);
-
-
- builder_pushCompo(ctr, compo);
-
- if (compo.async === true) {
- var resume = builder_resumeDelegate(
- compo
- , model
- , ctx
- , container
- , children
- , compo.renderEnd
- );
- compo.await(resume);
- return null;
- }
-
- if (compo.tagName != null) {
- compo.nodes = {
- tagName: compo.tagName,
- attr: compo.attr,
- nodes: compo.nodes,
- type: 1
- };
- }
-
-
- if (typeof compo.render === 'function') {
- compo.render(compo.model, ctx, container);
- // Overriden render behaviour - do not render subnodes
- return null;
- }
- return compo;
- }
-
-
- function build_Static(static_, node, model, ctx, container, ctr, children) {
- var Ctor = static_.__Ctor,
- wasRendered = false,
- elements,
- compo,
- clone;
-
- if (Ctor != null) {
- clone = new Ctor(node, ctr);
- }
- else {
- clone = static_;
-
- for (var key in node)
- clone[key] = node[key];
-
- clone.parent = ctr;
- }
-
- var attr = clone.attr;
- if (attr != null) {
- for (var key in attr) {
- if (typeof attr[key] === 'function')
- attr[key] = attr[key]('attr', model, ctx, container, ctr, key);
- }
- }
-
- if (is_Function(clone.renderStart)) {
- clone.renderStart(model, ctx, container, ctr, children);
- }
-
- clone.ID = ++builder_componentID;
- builder_pushCompo(ctr, clone);
-
- var i = ctr.components.length - 1;
- if (is_Function(clone.render)){
- wasRendered = true;
- elements = clone.render(model, ctx, container, ctr, children);
- arr_pushMany(children, elements);
-
- if (is_Function(clone.renderEnd)) {
- compo = clone.renderEnd(elements, model, ctx, container, ctr);
- if (compo != null) {
- // overriden
- ctr.components[i] = compo;
- compo.components = clone.components == null
- ? ctr.components.splice(i + 1)
- : clone.components
- ;
- }
- }
- }
-
- return wasRendered === true ? null : clone;
- }
-
- function build_NodeAsCompo(node, model, ctx, container, ctr, childs){
- node.ID = ++builder_componentID;
-
- builder_pushCompo(ctr, node);
-
- if (node.model == null)
- node.model = model;
-
- var els = node.elements = [];
- if (node.render) {
- node.render(node.model, ctx, container, ctr, els);
- } else {
- builder_build(node.nodes, node.model, ctx, container, node, els);
- }
-
- if (childs != null && els.length !== 0) {
- arr_pushMany(childs, els);
- }
- return null;
- }
-
- }());
-
- // end:source build_component
- // source build
- /**
- * @param {MaskNode} node
- * @param {*} model
- * @param {object} ctx
- * @param {IAppendChild} container
- * @param {object} controller
- * @param {Array} children - @out
- * @returns {IAppendChild} container
- * @memberOf mask
- * @method build
- */
- builder_build = function(node, model, ctx, container, ctr, children) {
-
- if (node == null)
- return container;
-
- var type = node.type,
- elements,
- key,
- value;
-
- if (ctr == null)
- ctr = new Dom.Component();
-
- if (type == null){
- // in case if node was added manually, but type was not set
- if (is_ArrayLike(node)) {
- // Dom.FRAGMENT
- type = 10;
- }
- else if (node.tagName != null){
- type = 1;
- }
- else if (node.content != null){
- type = 2;
- }
- }
-
-
- var tagName = node.tagName;
- if (tagName === 'else')
- return container;
-
- if (type === 1 && custom_Tags[tagName] != null) {
- // check if custom ctr exists
- type = 4;
- }
- if (type === 1 && custom_Statements[tagName] != null) {
- // check if custom statement exists
- type = 15;
- }
-
- if (container == null && type !== 1) {
- container = document.createDocumentFragment();
- }
-
- // Dom.TEXTNODE
- if (type === 2) {
- build_textNode(node, model, ctx, container, ctr);
- return container;
- }
-
- // Dom.SET
- if (type === 10) {
- var j = 0,
- jmax = node.length;
- for(; j < jmax; j++) {
- builder_build(node[j], model, ctx, container, ctr, children);
- }
- return container;
- }
-
- // Dom.STATEMENT
- if (type === 15) {
- var Handler = custom_Statements[tagName];
- if (Handler == null) {
- if (custom_Tags[tagName] != null) {
- // Dom.COMPONENT
- type = 4;
- } else {
- log_error('', tagName);
- return container;
- }
- }
- if (type === 15) {
- Handler.render(node, model, ctx, container, ctr, children);
- return container;
- }
- }
-
- // Dom.NODE
- if (type === 1) {
- container = build_node(node, model, ctx, container, ctr, children);
- children = null;
- }
-
- // Dom.COMPONENT
- if (type === 4) {
- ctr = build_compo(node, model, ctx, container, ctr, children);
- if (ctr == null) {
- return container;
- }
- elements = [];
- node = ctr;
-
- if (ctr.model !== model && ctr.model != null) {
- model = ctr.model;
- }
- }
-
- var nodes = node.nodes;
- if (nodes != null) {
- if (children != null && elements == null) {
- elements = children;
- }
- if (is_ArrayLike(nodes)) {
- var imax = nodes.length,
- i = 0;
- for(; i < imax; i++) {
- builder_build(nodes[i], model, ctx, container, ctr, elements);
- }
- } else {
-
- builder_build(nodes, model, ctx, container, ctr, elements);
- }
- }
-
- if (type === 4) {
-
- // use or override custom attr handlers
- // in Compo.handlers.attr object
- // but only on a component, not a tag ctr
- if (node.tagName == null) {
- var attrHandlers = node.handlers && node.handlers.attr,
- attrFn,
- val,
- key;
-
- for (key in node.attr) {
-
- val = node.attr[key];
-
- if (val == null)
- continue;
-
- attrFn = null;
-
- if (attrHandlers != null && is_Function(attrHandlers[key]))
- attrFn = attrHandlers[key];
-
- if (attrFn == null && custom_Attributes[key] != null)
- attrFn = custom_Attributes[key];
-
- if (attrFn != null)
- attrFn(node, val, model, ctx, elements[0], ctr);
- }
- }
-
- if (is_Function(node.renderEnd))
- node.renderEnd(elements, model, ctx, container);
- }
-
- if (children != null && elements != null && children !== elements)
- arr_pushMany(children, elements);
-
- return container;
- };
- // end:source build
-
- }());
- // end:source builder/
-
- // source mask
- /**
- * @namespace mask
- */
- var Mask;
- (function(){
- Mask = {
- /**
- * Render the mask template to document fragment or single html node
- * @param {(string|MaskDom)} template - Mask string template or Mask Ast to render from.
- * @param {*} [model] - Model Object.
- * @param {Object} [ctx] - Context can store any additional information, that custom handler may need
- * @param {IAppendChild} [container] - Container Html Node where template is rendered into
- * @param {Object} [controller] - Component that should own this template
- * @returns {(IAppendChild|Node|DocumentFragment)} container
- * @memberOf mask
- */
- render: function (mix, model, ctx, container, controller) {
-
- // if DEBUG
- if (container != null && typeof container.appendChild !== 'function'){
- log_error('.render(template[, model, ctx, container, controller]', 'Container should implement .appendChild method');
- }
- // endif
-
- var template = mix;
- if (typeof mix === 'string') {
- if (_Object_hasOwnProp.call(__templates, mix)){
- /* if Object doesnt contains property that check is faster
- then "!=null" http://jsperf.com/not-in-vs-null/2 */
- template = __templates[mix];
- }else{
- template = __templates[mix] = parser_parse(mix);
- }
- }
- if (ctx == null || ctx.constructor !== builder_Ctx)
- ctx = new builder_Ctx(ctx);
-
- return builder_build(template, model, ctx, container, controller);
- },
- /**
- * Same to `mask.render` but returns the promise, which is resolved when all async components
- * are resolved, or is in resolved state, when all components are synchronous.
- * For the parameters doc @see {@link mask.render}
- * @returns {Promise} Alwats fullfills with `IAppendChild|Node|DocumentFragment`
- * @memberOf mask
- */
- renderAsync: function(template, model, ctx, container, ctr) {
- if (ctx == null || ctx.constructor !== builder_Ctx)
- ctx = new builder_Ctx(ctx);
-
- var dom = this.render(template, model, ctx, container, ctr),
- dfr = new class_Dfr;
-
- if (ctx.async === true) {
- ctx.done(function(){
- dfr.resolve(dom);
- });
- } else {
- dfr.resolve(dom);
- }
- return dfr;
- },
- // parser/mask/parse.js
- parse: parser_parse,
- // parser/html/parse.js
- parseHtml: parser_parseHtml,
- // formatter/stringify.js
- stringify: mask_stringify,
- // builder/build.js
- build: builder_build,
- // feature/run.js
- run: mask_run,
- // feature/merge.js
- merge: mask_merge,
- // feature/optimize.js
- optimize: mask_optimize,
- registerOptimizer: mask_registerOptimizer,
- // feature/TreeWalker.js
- TreeWalker: mask_TreeWalker,
- // feature/Module.j
- Module: Module,
- // custom/tag.js
- registerHandler: customTag_register,
- registerFromTemplate: customTag_registerFromTemplate,
- define: customTag_define,
- getHandler: customTag_get,
- getHandlers: customTag_getAll,
- // custom/statement.js
- registerStatement: customStatement_register,
- getStatement: customStatement_get,
- // custom/attribute.js
- registerAttrHandler: customAttr_register,
- getAttrHandler: customAttr_get,
- // custom/util.js
- registerUtil: customUtil_register,
- getUtil: customUtil_get,
- $utils: customUtil_$utils,
- _ : customUtil_$utils,
- // dom/exports.js
- Dom: Dom,
- /**
- * Is present only in DEBUG (not minified) version
- * Evaluates script in masks library scope
- * @param {string} script
- */
- plugin: function(source){
- //if DEBUG
- eval(source);
- //endif
- },
- clearCache: function(key){
- if (arguments.length === 0) {
- __templates = {};
- return;
- }
- delete __templates[key];
- },
- Utils: {
- Expression: ExpressionUtil,
- ensureTmplFn: parser_ensureTemplateFunction
- },
- obj: {
- get: obj_getProperty,
- set: obj_setProperty,
- extend: obj_extend,
- },
- is: {
- Function: is_Function,
- String: is_String,
- ArrayLike: is_ArrayLike,
- Array: is_ArrayLike,
- Object: is_Object,
- NODE: is_NODE,
- DOM: is_DOM
- },
- 'class': {
- create: class_create,
- createError: error_createClass,
- Deferred: class_Dfr,
- EventEmitter: class_EventEmitter,
- },
- parser: {
- ObjectLexer: parser_ObjectLexer
- },
- // util/listeners.js
- on: listeners_on,
- off: listeners_off,
-
-
- // Stub for the reload.js, which will be used by includejs.autoreload
- delegateReload: function(){},
-
- /**
- * Define interpolation quotes for the parser
- * Starting from 0.6.9 mask uses ~[] for string interpolation.
- * Old '#{}' was changed to '~[]', while template is already overloaded with #, { and } usage.
- * @param {string} start - Must contain 2 Characters
- * @param {string} end - Must contain 1 Character
- **/
- setInterpolationQuotes: parser_setInterpolationQuotes,
-
- setCompoIndex: function(index){
- builder_componentID = index;
- },
-
- cfg: mask_config,
- config: mask_config,
-
- // For the consistence with the NodeJS
- toHtml: function(dom) {
- return $(dom).outerHtml();
- },
-
- factory: function(compoName){
- var params_ = _Array_slice.call(arguments, 1),
- factory = params_.pop(),
- mode = 'both';
- if (params_.length !== 0) {
- var x = params_[0];
- if (x === 'client' || x === 'server') {
- mode = x;
- }
- }
- if ((mode === 'client' && is_NODE) || (mode === 'server' && is_DOM) ) {
- customTag_register(compoName, {
- meta: { mode: mode }
- });
- return;
- }
- factory(global, Compo.config.getDOMLibrary(), function(compo){
- customTag_register(compoName, compo);
- });
- }
- };
-
-
- var __templates = {};
- }());
-
- // end:source mask
-
- /*** Libraries ***/
- // source /ref-mask-compo/lib/compo.embed.js
-
- var Compo = exports.Compo = Mask.Compo = (function(mask){
- // source /src/scope-vars.js
- var Dom = mask.Dom,
-
- _mask_ensureTmplFnOrig = mask.Utils.ensureTmplFn,
- _mask_ensureTmplFn,
- _resolve_External,
- domLib,
- Class
- ;
-
- (function(){
- _mask_ensureTmplFn = function(value) {
- return typeof value !== 'string'
- ? value
- : _mask_ensureTmplFnOrig(value)
- ;
- };
- _resolve_External = function(key){
- return _global[key] || _exports[key] || _atma[key]
- };
-
- var _global = global,
- _atma = global.atma || {},
- _exports = exports || {};
-
- function resolve() {
- var i = arguments.length, val;
- while( --i > -1 ) {
- val = _resolve_External(arguments[i]);
- if (val != null)
- return val;
- }
- return null;
- }
- domLib = resolve('jQuery', 'Zepto', '$');
- Class = resolve('Class');
- }());
-
-
- // if DEBUG
- if (global.document != null && domLib == null) {
-
- log_warn('DomLite is used. You can set jQuery-Zepto-Kimbo via `Compo.config.setDOMLibrary($)`');
- }
- // endif
- // end:source /src/scope-vars.js
-
- // source /src/util/exports.js
- // source ./selector.js
- var selector_parse,
- selector_match
- ;
-
- (function(){
-
- selector_parse = function(selector, type, direction) {
- if (selector == null)
- log_error('selector is undefined', type);
-
- if (typeof selector === 'object')
- return selector;
-
-
- var key, prop, nextKey;
-
- if (key == null) {
- switch (selector[0]) {
- case '#':
- key = 'id';
- selector = selector.substring(1);
- prop = 'attr';
- break;
- case '.':
- key = 'class';
- selector = sel_hasClassDelegate(selector.substring(1));
- prop = 'attr';
- break;
- default:
- key = type === Dom.SET ? 'tagName' : 'compoName';
- break;
- }
- }
-
- if (direction === 'up') {
- nextKey = 'parent';
- } else {
- nextKey = type === Dom.SET ? 'nodes' : 'components';
- }
-
- return {
- key: key,
- prop: prop,
- selector: selector,
- nextKey: nextKey
- };
- };
-
- selector_match = function(node, selector, type) {
- if (node == null)
- return false;
-
- if (is_String(selector)) {
- if (type == null)
- type = Dom[node.compoName ? 'CONTROLLER' : 'SET'];
-
- selector = selector_parse(selector, type);
- }
-
- var obj = selector.prop ? node[selector.prop] : node;
- if (obj == null)
- return false;
-
- if (is_Function(selector.selector))
- return selector.selector(obj[selector.key]);
-
- // regexp
- if (selector.selector.test != null)
- return selector.selector.test(obj[selector.key]);
-
- // string | int
- /* jshint eqeqeq: false */
- return obj[selector.key] == selector.selector;
- /* jshint eqeqeq: true */
- }
-
- // PRIVATE
-
- function sel_hasClassDelegate(matchClass) {
- return function(className){
- return sel_hasClass(className, matchClass);
- };
- }
-
- // [perf] http://jsperf.com/match-classname-indexof-vs-regexp/2
- function sel_hasClass(className, matchClass, index) {
- if (typeof className !== 'string')
- return false;
-
- if (index == null)
- index = 0;
-
- index = className.indexOf(matchClass, index);
-
- if (index === -1)
- return false;
-
- if (index > 0 && className.charCodeAt(index - 1) > 32)
- return sel_hasClass(className, matchClass, index + 1);
-
- var class_Length = className.length,
- match_Length = matchClass.length;
-
- if (index < class_Length - match_Length && className.charCodeAt(index + match_Length) > 32)
- return sel_hasClass(className, matchClass, index + 1);
-
- return true;
- }
-
- }());
-
- // end:source ./selector.js
- // source ./traverse.js
- var find_findSingle,
- find_findAll;
- (function(){
-
- find_findSingle = function(node, matcher) {
- if (node == null)
- return null;
-
- if (is_Array(node)) {
- var imax = node.length,
- i = 0, x;
-
- for(; i < imax; i++) {
- x = find_findSingle(node[i], matcher);
- if (x != null)
- return x;
- }
- return null;
- }
-
- if (selector_match(node, matcher))
- return node;
-
- node = node[matcher.nextKey];
- return node == null
- ? null
- : find_findSingle(node, matcher)
- ;
- };
-
- find_findAll = function(node, matcher, out) {
- if (out == null)
- out = [];
-
- if (is_Array(node)) {
- var imax = node.length,
- i = 0, x;
-
- for(; i < imax; i++) {
- find_findAll(node[i], matcher, out);
- }
- return out;
- }
-
- if (selector_match(node, matcher))
- out.push(node);
-
- node = node[matcher.nextKey];
- return node == null
- ? out
- : find_findAll(node, matcher, out)
- ;
- };
-
- }());
-
- // end:source ./traverse.js
- // source ./dom.js
- var dom_addEventListener,
-
- node_tryDispose,
- node_tryDisposeChildren
- ;
-
- (function(){
-
- dom_addEventListener = function(el, event, fn, param, ctr) {
-
- if (TouchHandler.supports(event)) {
- TouchHandler.on(el, event, fn);
- return;
- }
- if (KeyboardHandler.supports(event, param)) {
- KeyboardHandler.attach(el, event, param, fn, ctr);
- return;
- }
- // allows custom events - in x-signal, for example
- if (domLib != null)
- return domLib(el).on(event, fn);
-
- if (el.addEventListener != null)
- return el.addEventListener(event, fn, false);
-
- if (el.attachEvent)
- el.attachEvent('on' + event, fn);
- };
-
- node_tryDispose = function(node){
- if (node.hasAttribute('x-compo-id')) {
-
- var id = node.getAttribute('x-compo-id'),
- compo = Anchor.getByID(id)
- ;
-
- if (compo != null) {
- if (compo.$ == null || compo.$.length === 1) {
- compo_dispose(compo);
- compo_detachChild(compo);
- return;
- }
- var i = _Array_indexOf.call(compo.$, node);
- if (i !== -1)
- _Array_splice.call(compo.$, i, 1);
- }
- }
- node_tryDisposeChildren(node);
- };
-
- node_tryDisposeChildren = function(node){
-
- var child = node.firstChild;
- while(child != null) {
-
- if (child.nodeType === 1)
- node_tryDispose(child);
-
-
- child = child.nextSibling;
- }
- };
-
- }());
-
- // end:source ./dom.js
- // source ./domLib.js
- /**
- * Combine .filter + .find
- */
-
- var domLib_find,
- domLib_on
- ;
-
- (function(){
-
- domLib_find = function($set, selector) {
- return $set.filter(selector).add($set.find(selector));
- };
-
- domLib_on = function($set, type, selector, fn) {
-
- if (selector == null)
- return $set.on(type, fn);
-
- $set
- .on(type, selector, fn)
- .filter(selector)
- .on(type, fn);
-
- return $set;
- };
-
- }());
-
-
- // end:source ./domLib.js
- // source ./compo.js
- var compo_dispose,
- compo_detachChild,
- compo_ensureTemplate,
- compo_ensureAttributes,
- compo_attachDisposer,
- compo_removeElements,
- compo_prepairAsync,
- compo_errored,
-
- compo_meta_prepairAttributeHandler,
- compo_meta_executeAttributeHandler
- ;
-
- (function(){
-
- compo_dispose = function(compo) {
- if (compo.dispose != null)
- compo.dispose();
-
- Anchor.removeCompo(compo);
-
- var compos = compo.components;
- if (compos != null) {
- var i = compos.length;
- while ( --i > -1 ) {
- compo_dispose(compos[i]);
- }
- }
- };
-
- compo_detachChild = function(childCompo){
- var parent = childCompo.parent;
- if (parent == null)
- return;
-
- var arr = childCompo.$,
- elements = parent.$ || parent.elements,
- i;
-
- if (elements && arr) {
- var jmax = arr.length,
- el, j;
-
- i = elements.length;
- while( --i > -1){
- el = elements[i];
- j = jmax;
-
- while(--j > -1){
- if (el === arr[j]) {
- elements.splice(i, 1);
- break;
- }
- }
- }
- }
-
- var compos = parent.components;
- if (compos != null) {
-
- i = compos.length;
- while(--i > -1){
- if (compos[i] === childCompo) {
- compos.splice(i, 1);
- break;
- }
- }
-
- if (i === -1)
- log_warn(' - i`m not in parents collection', childCompo);
- }
- };
- compo_ensureTemplate = function(compo) {
- if (compo.nodes == null) {
- compo.nodes = getTemplateProp_(compo);
- return;
- }
- var behaviour = compo.meta.template;
- if (behaviour == null || behaviour === 'replace') {
- return;
- }
- var template = getTemplateProp_(compo);
- if (template == null) {
- return;
- }
- if (behaviour === 'merge') {
- compo.nodes = mask_merge(template, compo.nodes, compo);
- return;
- }
- if (behaviour === 'join') {
- compo.nodes = [template, compo.nodes];
- return;
- }
- log_error('Invalid meta.nodes behaviour', behaviour);
- };
- compo_attachDisposer = function(compo, disposer) {
-
- if (compo.dispose == null) {
- compo.dispose = disposer;
- return;
- }
-
- var prev = compo.dispose;
- compo.dispose = function(){
- disposer.call(this);
- prev.call(this);
- };
- };
-
- compo_removeElements = function(compo) {
- if (compo.$) {
- compo.$.remove();
- return;
- }
-
- var els = compo.elements;
- if (els) {
- var i = -1,
- imax = els.length;
- while ( ++i < imax ) {
- if (els[i].parentNode)
- els[i].parentNode.removeChild(els[i]);
- }
- return;
- }
-
- var compos = compo.components;
- if (compos) {
- var i = -1,
- imax = compos.length;
- while ( ++i < imax ){
- compo_removeElements(compos[i]);
- }
- }
- };
-
- compo_prepairAsync = function(dfr, compo, ctx){
- var resume = Compo.pause(compo, ctx)
- dfr.then(resume, function(error){
- compo_errored(compo, error);
- resume();
- });
- };
-
- compo_errored = function(compo, error){
- var msg = '[%] Failed.'.replace('%', compo.compoName || compo.tagName);
- if (error) {
- var desc = error.message || error.statusText || String(error);
- if (desc) {
- msg += ' ' + desc;
- }
- }
- compo.nodes = reporter_createErrorNode(msg);
- compo.renderEnd = fn_doNothing;
- };
-
- // == Meta Attribute Handler
- (function(){
-
- compo_meta_prepairAttributeHandler = function(Proto){
- if (Proto.meta == null) {
- Proto.meta = {
- attributes: null,
- cache: null,
- mode: null
- };
- }
-
- var attr = Proto.meta.attributes,
- fn = null;
- if (attr) {
- var hash = {};
- for(var key in attr) {
- _handleProperty_Delegate(Proto, key, attr[key], hash);
- }
- fn = _handleAll_Delegate(hash);
- }
- Proto.meta.handleAttributes = fn;
- };
- compo_meta_executeAttributeHandler = function(compo, model){
- var fn = compo.meta && compo.meta.handleAttributes;
- return fn == null ? true : fn(compo, model);
- };
-
- function _handleAll_Delegate(hash){
- return function(compo, model){
- var attr = compo.attr,
- key, fn, val, error;
- for(key in hash){
- fn = hash[key];
- val = attr[key];
- error = fn(compo, val, model);
-
- if (error == null)
- continue;
-
- _errored(compo, error, key, val)
- return false;
- }
- return true;
- };
- }
- function _handleProperty_Delegate(Proto, metaKey, metaVal, hash) {
- var optional = metaKey.charCodeAt(0) === 63, // ?
- default_ = null,
- attrName = optional
- ? metaKey.substring(1)
- : metaKey;
-
- var property = _getProperty(attrName),
- fn = null,
- type = typeof metaVal;
- if ('string' === type) {
- if (metaVal === 'string' || metaVal === 'number' || metaVal === 'boolean') {
- fn = _ensureFns[metaVal];
- } else {
- optional = true;
- default_ = metaVal;
- fn = _ensureFns_Delegate.any();
- }
- }
- else if ('boolean' === type || 'number' === type) {
- optional = true;
- fn = _ensureFns[type];
- default_ = metaVal;
- }
- else if ('function' === type) {
- fn = metaVal;
- }
- else if (metaVal == null) {
- fn = _ensureFns_Delegate.any();
- }
- else if (metaVal instanceof RegExp) {
- fn = _ensureFns_Delegate.regexp(metaVal);
- }
- else if (typeof metaVal === 'object') {
- fn = _ensureFns_Delegate.options(metaVal);
- default_ = metaVal['default'];
- if (default_ !== void 0) {
- optional = true;
- }
- }
-
- if (fn == null) {
- log_error('Function expected for the attr. handler', metaKey);
- return;
- }
-
- Proto[property] = null;
- Proto = null;
- hash [attrName] = function(compo, attrVal, model){
- if (attrVal == null) {
- if (optional === false) {
- return Error('Expected');
- }
- if (default_ != null) {
- compo[property] = default_;
- }
- return null;
- }
-
- var val = fn.call(compo, attrVal, compo, model, attrName);
- if (val instanceof Error)
- return val;
-
- compo[property] = val;
- return null;
- };
- }
-
- function _toCamelCase_Replacer(full, char_){
- return char_.toUpperCase();
- }
- function _getProperty(attrName) {
- var prop = attrName;
- if (prop.charCodeAt(0) !== 120) {
- // x
- prop = 'x-' + prop;
- }
- return prop.replace(/-(\w)/g, _toCamelCase_Replacer)
- }
- function _errored(compo, error, key, val) {
- error.message = compo.compoName + ' - attribute `' + key + '`: ' + error.message;
- compo_errored(compo, error);
- log_error(error.message, '. Current: ', val);
- }
- var _ensureFns = {
- 'string': function(x) {
- return typeof x === 'string' ? x : Error('String');
- },
- 'number': function(x){
- var num = Number(x);
- return num === num ? num : Error('Number');
- },
- 'boolean': function(x, compo, model, attrName){
- if (typeof x === 'boolean')
- return x;
- if (x === attrName) return true;
- if (x === 'true' || x === '1') return true;
- if (x === 'false' || x === '0') return false;
- return Error('Boolean');
- }
- };
- var _ensureFns_Delegate = {
- regexp: function(rgx){
- return function(x){
- return rgx.test(x) ? x : Error('RegExp');
- };
- },
- any: function(){
- return function(x){ return x; };
- },
- options: function(opts){
- var type = opts.type,
- def = opts.default || _defaults[type],
- validate = opts.validate,
- transform = opts.transform;
- return function(x){
- if (!x) return def;
-
- if (type != null) {
- var fn = _ensureFns[type];
- if (fn != null) {
- x = fn.apply(this, arguments);
- if (x instanceof Error) {
- return x;
- }
- }
- }
- if (validate) {
- var error = validate.call(this, x);
- if (error) {
- return Error(error);
- }
- }
- if (transform) {
- x = transform.call(this, x);
- }
- return x;
- };
- }
- };
- var _defaults = {
- string: '',
- boolean: false,
- number: 0
- };
- }());
- function getTemplateProp_(compo){
- var template = compo.template;
- if (template == null) {
- template = compo.attr.template;
- if (template == null)
- return null;
-
- delete compo.attr.template;
- }
- if (typeof template === 'object')
- return template;
-
- if (is_String(template)) {
- if (template.charCodeAt(0) === 35 && /^#[\w\d_-]+$/.test(template)) {
- // #
- var node = document.getElementById(template.substring(1));
- if (node == null) {
- log_warn('Template not found by id:', template);
- return null;
- }
- template = node.innerHTML;
- }
- return mask.parse(template);
- }
- log_warn('Invalid template', typeof template);
- return null;
- }
- }());
-
- // end:source ./compo.js
- // source ./compo_create.js
- var compo_create,
- compo_createConstructor;
- (function(){
- compo_create = function(arguments_){
-
- var argLength = arguments_.length,
- Proto = arguments_[argLength - 1],
- Ctor,
- key;
-
- if (argLength > 1)
- compo_inherit(Proto, _Array_slice.call(arguments_, 0, argLength - 1));
-
- if (Proto == null)
- Proto = {};
-
- var include = _resolve_External('include');
- if (include != null)
- Proto.__resource = include.url;
-
- var attr = Proto.attr;
- for (key in Proto.attr) {
- Proto.attr[key] = _mask_ensureTmplFn(Proto.attr[key]);
- }
-
- var slots = Proto.slots;
- for (key in slots) {
- if (typeof slots[key] === 'string'){
- //if DEBUG
- if (is_Function(Proto[slots[key]]) === false)
- log_error('Not a Function @Slot.',slots[key]);
- // endif
- slots[key] = Proto[slots[key]];
- }
- }
-
- compo_meta_prepairAttributeHandler(Proto);
-
- Ctor = Proto.hasOwnProperty('constructor')
- ? Proto.constructor
- : function CompoBase() {}
- ;
-
- Ctor = compo_createConstructor(Ctor, Proto);
-
- for(key in CompoProto){
- if (Proto[key] == null)
- Proto[key] = CompoProto[key];
- }
-
- Ctor.prototype = Proto;
- Proto = null;
- return Ctor;
- };
-
- compo_createConstructor = function(Ctor, proto) {
- var compos = proto.compos,
- pipes = proto.pipes,
- scope = proto.scope,
- attr = proto.attr;
-
- if (compos == null
- && pipes == null
- && attr == null
- && scope == null) {
- return Ctor;
- }
-
- /* extend compos / attr to keep
- * original prototyped values untouched
- */
- return function CompoBase(node, model, ctx, container, ctr){
-
- if (Ctor != null) {
- var overriden = Ctor.call(this, node, model, ctx, container, ctr);
- if (overriden != null)
- return overriden;
- }
-
- if (compos != null) {
- // use this.compos instead of compos from upper scope
- // : in case compos they were extended after
- this.compos = obj_create(this.compos);
- }
-
- if (pipes != null)
- Pipes.addController(this);
-
- if (attr != null)
- this.attr = obj_create(this.attr);
-
- if (scope != null)
- this.scope = obj_create(this.scope);
- };
- };
- }());
- // end:source ./compo_create.js
- // source ./compo_inherit.js
- var compo_inherit;
- (function(){
-
- compo_inherit = function(Proto, Extends){
- var imax = Extends.length,
- i = imax,
- ctors = [],
- x;
- while( --i > -1){
- x = Extends[i];
- if (typeof x === 'string') {
- x = mask.getHandler(x);
- if (x != null && x.name === 'Resolver') {
- log_error('Inheritance error: private component');
- x = null;
- }
- }
- if (x == null) {
- log_error('Base component not defined', Extends[i]);
- continue;
- }
- if (typeof x === 'function') {
- ctors.push(x);
- x = x.prototype;
- }
- inherit_(Proto, x, 'node');
- }
-
- i = -1;
- imax = ctors.length;
- if (imax > 0) {
- if (Proto.hasOwnProperty('constructor'))
- ctors.unshift(Proto.constructor);
-
- Proto.constructor = joinFns_(ctors);
- }
- var meta = Proto.meta;
- if (meta == null)
- meta = Proto.meta = {};
-
- if (meta.template == null)
- meta.template = 'merge';
- };
-
- function inherit_(target, source, name){
- if (target == null || source == null)
- return;
-
- if ('node' === name) {
- var targetNodes = target.template || target.nodes,
- sourceNodes = source.template || source.nodes;
- target.template = targetNodes == null || sourceNodes == null
- ? (targetNodes || sourceNodes)
- : (mask_merge(sourceNodes, targetNodes, target, {extending: true }));
-
- if (target.nodes != null) {
- target.nodes = target.template;
- }
- }
-
- var mix, type, fnAutoCall, hasFnOverrides = false;
- for(var key in source){
- mix = source[key];
- if (mix == null || key === 'constructor')
- continue;
-
- if ('node' === name && (key === 'template' || key === 'nodes'))
- continue;
-
- type = typeof mix;
-
- if (target[key] == null) {
- target[key] = mix;
- continue;
- }
- if ('node' === name) {
- // http://jsperf.com/indexof-vs-bunch-of-ifs
- var isSealed = key === 'renderStart'
- || key === 'renderEnd'
- || key === 'emitIn'
- || key === 'emitOut'
- || key === 'components'
- || key === 'nodes'
- || key === 'template'
- || key === 'find'
- || key === 'closest'
- || key === 'on'
- || key === 'remove'
- || key === 'slotState'
- || key === 'signalState'
- || key === 'append'
- || key === 'appendTo'
- ;
- if (isSealed === true)
- continue;
- }
- if ('pipes' === name) {
- inherit_(target[key], mix, 'pipe');
- continue;
- }
- if ('function' === type) {
- fnAutoCall = false;
- if ('slots' === name || 'events' === name || 'pipe' === name)
- fnAutoCall = true;
- else if ('node' === name && ('onRenderStart' === key || 'onRenderEnd' === key))
- fnAutoCall = true;
-
- target[key] = createWrapper_(target[key], mix, fnAutoCall);
- hasFnOverrides = true;
- continue;
- }
- if ('object' !== type) {
- continue;
- }
-
- switch(key){
- case 'slots':
- case 'pipes':
- case 'events':
- case 'attr':
- inherit_(target[key], mix, key);
- continue;
- }
- defaults_(target[key], mix);
- }
-
- if (hasFnOverrides === true) {
- if (target.super != null)
- log_error('`super` property is reserved. Dismissed. Current prototype', target);
- target.super = null;
- }
- }
-
- /*! Circular references are not handled */
- function clone_(a) {
- if (a == null)
- return null;
-
- if (typeof a !== 'object')
- return a;
-
- if (is_Array(a)) {
- var imax = a.length,
- i = -1,
- arr = new Array(imax)
- ;
- while( ++i < imax ){
- arr[i] = clone_(a[i]);
- }
- return arr;
- }
-
- var object = obj_create(a),
- key, val;
- for(key in object){
- val = object[key];
- if (val == null || typeof val !== 'object')
- continue;
- object[key] = clone_(val);
- }
- return object;
- }
- function defaults_(target, source){
- var targetV, sourceV, key;
- for(var key in source){
- targetV = target[key];
- sourceV = source[key];
- if (targetV == null) {
- target[key] = sourceV;
- continue;
- }
- if (is_rawObject(targetV) && is_rawObject(sourceV)){
- defaults_(targetV, sourceV);
- continue;
- }
- }
- }
- function createWrapper_(selfFn, baseFn, autoCallFunctions){
- if (selfFn.name === 'compoInheritanceWrapper') {
- selfFn._fn_chain.push(baseFn);
- return selfFn;
- }
-
- var compileFns = autoCallFunctions === true
- ? compileFns_autocall_
- : compileFns_
- ;
- function compoInheritanceWrapper(){
- var fn = x._fn || (x._fn = compileFns(x._fn_chain));
- return fn.apply(this, arguments);
- }
-
- var x = compoInheritanceWrapper;
- x._fn_chain = [ selfFn, baseFn ];
- x._fn = null;
-
- return x;
- }
- function compileFns_(fns){
- var i = fns.length,
- fn = fns[ --i ];
- while( --i > -1){
- fn = inheritFn_(fns[i], fn);
- }
- return fn;
- }
- function compileFns_autocall_(fns) {
- var imax = fns.length;
- return function(){
- var result, fn, x,
- i = imax;
- while( --i > -1 ){
- fn = fns[i];
- if (fn == null)
- continue;
-
- x = fn_apply(fn, this, arguments);
- if (x !== void 0) {
- result = x;
- }
- }
- return result;
- }
- }
- function inheritFn_(selfFn, baseFn){
- return function(){
- this.super = baseFn;
- var x = fn_apply(selfFn, this, arguments);
-
- this.super = null;
- return x;
- };
- }
- function joinFns_(fns) {
- var imax = fns.length;
- return function(){
- var i = imax, result;
- while( --i > -1 ){
- var x = fns[i].apply(this, arguments);
- if (x != null) {
- // use last return
- result = x;
- }
- }
- return result;
- };
- }
- }());
- // end:source ./compo_inherit.js
- // source ./dfr.js
- var dfr_isBusy;
- (function(){
- dfr_isBusy = function(dfr){
- if (dfr == null || typeof dfr.then !== 'function')
- return false;
-
- // Class.Deferred
- if (is_Function(dfr.isBusy))
- return dfr.isBusy();
-
- // jQuery Deferred
- if (is_Function(dfr.state))
- return dfr.state() === 'pending';
-
- log_warn('Class or jQuery deferred interface expected');
- return false;
- };
- }());
- // end:source ./dfr.js
-
- // end:source /src/util/exports.js
-
- // source /src/compo/children.js
- var Children_ = {
-
- /**
- * Component children. Example:
- *
- * Class({
- * Base: Compo,
- * Construct: function(){
- * this.compos = {
- * panel: '$: .container', // querying with DOMLib
- * timePicker: 'compo: timePicker', // querying with Compo selector
- * button: '#button' // querying with querySelector***
- * }
- * }
- * });
- *
- */
- select: function(component, compos) {
- for (var name in compos) {
- var data = compos[name],
- events = null,
- selector = null;
-
- if (data instanceof Array) {
- selector = data[0];
- events = data.splice(1);
- }
- if (typeof data === 'string') {
- selector = data;
- }
- if (data == null || selector == null) {
- log_error('Unknown component child', name, compos[name]);
- log_warn('Is this object shared within multiple compo classes? Define it in constructor!');
- return;
- }
-
- var index = selector.indexOf(':'),
- engine = selector.substring(0, index);
-
- engine = Compo.config.selectors[engine];
-
- if (engine == null) {
- component.compos[name] = component.$[0].querySelector(selector);
- } else {
- selector = selector.substring(++index).trim();
- component.compos[name] = engine(component, selector);
- }
-
- var element = component.compos[name];
-
- if (events != null) {
- if (element.$ != null) {
- element = element.$;
- }
-
- Events_.on(component, events, element);
- }
- }
- }
- };
-
- // end:source /src/compo/children.js
- // source /src/compo/events.js
- var Events_ = {
- on: function(component, events, $element) {
- if ($element == null) {
- $element = component.$;
- }
-
- var isarray = events instanceof Array,
- length = isarray ? events.length : 1;
-
- for (var i = 0, x; isarray ? i < length : i < 1; i++) {
- x = isarray ? events[i] : events;
-
- if (x instanceof Array) {
- // generic jQuery .on Arguments
-
- if (EventDecorator != null) {
- x[0] = EventDecorator(x[0]);
- }
-
- $element.on.apply($element, x);
- continue;
- }
-
-
- for (var key in x) {
- var fn = typeof x[key] === 'string' ? component[x[key]] : x[key],
- semicolon = key.indexOf(':'),
- type,
- selector;
-
- if (semicolon !== -1) {
- type = key.substring(0, semicolon);
- selector = key.substring(semicolon + 1).trim();
- } else {
- type = key;
- }
-
- if (EventDecorator != null) {
- type = EventDecorator(type);
- }
-
- domLib_on($element, type, selector, fn_proxy(fn, component));
- }
- }
- }
- },
- EventDecorator = null;
-
- // end:source /src/compo/events.js
- // source /src/compo/events.deco.js
- var EventDecos = (function() {
-
- var hasTouch = (function() {
- if (document == null) {
- return false;
- }
- if ('createTouch' in document) {
- return true;
- }
- try {
- return !!document.createEvent('TouchEvent').initTouchEvent;
- } catch (error) {
- return false;
- }
- }());
-
- return {
-
- 'touch': function(type) {
- if (hasTouch === false) {
- return type;
- }
-
- if ('click' === type) {
- return 'touchend';
- }
-
- if ('mousedown' === type) {
- return 'touchstart';
- }
-
- if ('mouseup' === type) {
- return 'touchend';
- }
-
- if ('mousemove' === type) {
- return 'touchmove';
- }
-
- return type;
- }
- };
-
- }());
-
- // end:source /src/compo/events.deco.js
- // source /src/compo/pipes.js
- var Pipes = (function() {
-
- var _collection = {};
-
- mask.registerAttrHandler('x-pipe-signal', 'client', function(node, attrValue, model, ctx, element, ctr) {
-
- var arr = attrValue.split(';'),
- imax = arr.length,
- i = -1,
- x;
- while ( ++i < imax ) {
- x = arr[i].trim();
- if (x === '')
- continue;
-
- var i_colon = x.indexOf(':'),
- event = x.substring(0, i_colon),
- handler = x.substring(i_colon + 1).trim(),
- dot = handler.indexOf('.'),
-
- pipe, signal;
-
- if (dot === -1) {
- log_error('Pipe-slot is invalid: {0} Usage e.g. "click: pipeName.pipeSignal"', x);
- return;
- }
-
- pipe = handler.substring(0, dot);
- signal = handler.substring(++dot);
-
- // if DEBUG
- !event && log_error('Pipe-slot is invalid. Event type is not set', attrValue);
- // endif
-
- dom_addEventListener(
- element
- , event
- , _createListener(pipe, signal)
- );
- }
- });
-
- function _createListener(pipe, signal) {
- return function(event){
- new Pipe(pipe).emit(signal, event);
- };
- }
-
-
- function pipe_attach(pipeName, ctr) {
- if (ctr.pipes[pipeName] == null) {
- log_error('Controller has no pipes to be added to collection', pipeName, ctr);
- return;
- }
-
- if (_collection[pipeName] == null) {
- _collection[pipeName] = [];
- }
- _collection[pipeName].push(ctr);
- }
-
- function pipe_detach(pipeName, ctr) {
- var pipe = _collection[pipeName],
- i = pipe.length;
-
- while (--i > -1) {
- if (pipe[i] === ctr)
- pipe.splice(i, 1);
- }
-
- }
-
- function _removeController(ctr) {
- var pipes = ctr.pipes;
- for (var key in pipes) {
- pipe_detach(key, ctr);
- }
- }
- function _removeControllerDelegate(ctr) {
- return function(){
- _removeController(ctr);
- ctr = null;
- };
- }
-
- function _addController(ctr) {
- var pipes = ctr.pipes;
-
- // if DEBUG
- if (pipes == null) {
- log_error('Controller has no pipes', ctr);
- return;
- }
- // endif
-
- for (var key in pipes) {
- pipe_attach(key, ctr);
- }
- Compo.attachDisposer(ctr, _removeControllerDelegate(ctr));
- }
-
- var Pipe = class_create({
- name: null,
- constructor: function Pipe (name) {
- if (this instanceof Pipe === false) {
- return new Pipe(name);
- }
- this.name = name;
- return this;
- },
- emit: function(signal){
- var controllers = _collection[this.name],
- name = this.name,
- args = _Array_slice.call(arguments, 1);
-
- if (controllers == null) {
- //if DEBUG
- log_warn('Pipe.emit: No signals were bound to:', name);
- //endif
- return;
- }
-
- var i = controllers.length,
- called = false;
-
- while (--i !== -1) {
- var ctr = controllers[i];
- var slots = ctr.pipes[name];
-
- if (slots == null)
- continue;
-
- var slot = slots[signal];
- if (slot != null) {
- slot.apply(ctr, args);
- called = true;
- }
- }
-
- // if DEBUG
- if (called === false)
- log_warn('Pipe `%s` has not slots for `%s`', name, signal);
- // endif
- }
- });
- Pipe.addController = _addController;
- Pipe.removeController = _removeController;
-
- return {
- addController: _addController,
- removeController: _removeController,
- pipe: Pipe
- };
-
- }());
-
- // end:source /src/compo/pipes.js
-
- // source /src/keyboard/Handler.js
- var KeyboardHandler;
- (function(){
-
- // source ./utils.js
- var event_bind,
- event_unbind,
- event_getCode;
- (function(){
-
- event_bind = function (el, type, mix){
- el.addEventListener(type, mix, false);
- };
- event_unbind = function (el, type, mix) {
- el.removeEventListener(type, mix, false);
- };
-
- event_getCode = function(event){
- var code = event.keyCode || event.which;
-
- if (code >= 96 && code <= 105) {
- // numpad digits
- return code - 48;
- }
-
- return code;
- };
-
- }());
-
- // end:source ./utils.js
- // source ./const.js
- var CODES, SHIFT_NUMS, MODS;
-
- CODES = {
- "backspace": 8,
- "tab": 9,
- "return": 13,
- "enter": 13,
- "shift": 16,
- "ctrl": 17,
- "control": 17,
- "alt": 18,
- "option": 18,
-
- "fn": 255,
-
- "pause": 19,
- "capslock": 20,
- "esc": 27,
- "escape": 27,
-
- "space": 32,
- "pageup": 33,
- "pagedown": 34,
- "end": 35,
- "home": 36,
- "start": 36,
-
- "left": 37,
- "up": 38,
- "right": 39,
- "down": 40,
-
- "insert": 45,
- "ins": 45,
- "del": 46,
- "numlock": 144,
- "scroll": 145,
-
- "f1": 112,
- "f2": 113,
- "f3": 114,
- "f4": 115,
- "f5": 116,
- "f6": 117,
- "f7": 118,
- "f8": 119,
- "f9": 120,
- "f10": 121,
- "f11": 122,
- "f12": 123,
-
- ";": 186,
- "=": 187,
- "*": 106,
- "+": 107,
- "-": 189,
- ".": 190,
- "/": 191,
-
- ",": 188,
- "`": 192,
- "[": 219,
- "\\": 220,
- "]": 221,
- "'": 222
- };
-
- SHIFT_NUMS = {
- "`": "~",
- "1": "!",
- "2": "@",
- "3": "#",
- "4": "$",
- "5": "%",
- "6": "^",
- "7": "&",
- "8": "*",
- "9": "(",
- "0": ")",
- "-": "_",
- "=": "+",
- ";": ": ",
- "'": "\"",
- ",": "<",
- ".": ">",
- "/": "?",
- "\\": "|"
- };
-
- MODS = {
- '16': 'shiftKey',
- '17': 'ctrlKey',
- '18': 'altKey',
- };
- // end:source ./const.js
- // source ./filters.js
- var filter_isKeyboardInput,
- filter_skippedInput,
- filter_skippedComponent,
- filter_skippedElement;
- (function(){
- filter_skippedInput = function(event, code){
- if (event.ctrlKey || event.altKey)
- return false;
- return filter_isKeyboardInput(event.target);
- };
-
- filter_skippedComponent = function(compo){
- if (compo.$ == null || compo.$.length === 0) {
- return false;
- }
- return filter_skippedElement(compo.$.get(0));
- };
- filter_skippedElement = function(el) {
- if (document.contains(el) === false)
- return false;
-
- if (el.style.display === 'none')
- return false;
-
- var disabled = el.disabled;
- if (disabled === true)
- return false;
-
- return true;
- };
- filter_isKeyboardInput = function (el) {
- var tag = el.tagName;
- if ('TEXTAREA' === tag) {
- return true;
- }
- if ('INPUT' !== tag) {
- return false;
- }
- return TYPELESS_INPUT.indexOf(' ' + el.type + ' ') === -1;
- };
-
- var TYPELESS_INPUT = ' button submit checkbox file hidden image radio range reset ';
- }());
- // end:source ./filters.js
- // source ./Hotkey.js
- var Hotkey;
- (function(){
- Hotkey = {
- on: function(combDef, fn, compo) {
- if (handler == null) init();
-
- var comb = IComb.create(
- combDef
- , 'keydown'
- , fn
- , compo
- );
- handler.attach(comb);
- },
- off: function(fn){
- handler.off(fn);
- },
- handleEvent: function(event){
- handler.handle(event.type, event_getCode(event), event);
- },
- reset: function(){
- handler.reset();
- }
- };
- var handler;
- function init() {
- handler = new CombHandler();
- event_bind(window, 'keydown', Hotkey);
- event_bind(window, 'keyup', Hotkey);
- event_bind(window, 'focus', Hotkey.reset);
- }
- }());
- // end:source ./Hotkey.js
- // source ./IComb.js
- var IComb;
- (function(){
- IComb = function(set){
- this.set = set;
- };
- IComb.parse = function (str) {
- var parts = str.split(','),
- combs = [],
- imax = parts.length,
- i = 0;
- for(; i < imax; i++){
- combs[i] = parseSingle(parts[i]);
- }
- return combs;
- };
- IComb.create = function (def, type, fn, ctx) {
- var codes = IComb.parse(def);
- var comb = Key.create(codes);
- if (comb == null) {
- comb = new KeySequance(codes)
- }
- comb.init(type, fn, ctx);
- return comb;
- };
- IComb.prototype = {
- type: null,
- ctx: null,
- set: null,
- fn: null,
- init: function(type, fn, ctx){
- this.type = type;
- this.ctx = ctx;
- this.fn = fn;
- },
- tryCall: null
- };
-
- function parseSingle(str) {
- var keys = str.split('+'),
- imax = keys.length,
- i = 0,
- out = [], x, code;
- for(; i < imax; i++){
- x = keys[i].trim();
- code = CODES[x];
- if (code === void 0) {
- if (x.length !== 1) {
- throw Error('Unexpected sequence. Neither a predefined key, nor a char: ' + x);
- }
- code = x.toUpperCase().charCodeAt(0);
- }
- out[i] = code;
- }
- return {
- last: out[imax - 1],
- keys: out.sort()
- };
- }
- }());
- // end:source ./IComb.js
- // source ./Key.js
- var Key;
- (function(){
- Key = class_create(IComb, {
- constructor: function(set, key, mods){
- this.key = key;
- this.mods = mods;
- },
- tryCall: function(event, codes, lastCode){
- if (event.type !== this.type || lastCode !== this.key) {
- return Key_MATCH_FAIL;
- }
-
- for (var key in this.mods){
- if (event[key] !== this.mods[key])
- return Key_MATCH_FAIL;
- }
-
- this.fn.call(this.ctx, event);
- return Key_MATCH_OK;
- }
- });
-
- Key.create = function(set){
- if (set.length !== 1)
- return null;
- var keys = set[0].keys,
- i = keys.length,
- mods = {
- shiftKey: false,
- ctrlKey: false,
- altKey: false
- };
-
- var key, mod, hasMod;
- while(--i > -1){
- if (MODS.hasOwnProperty(keys[i]) === false) {
- if (key != null)
- return null;
- key = keys[i];
- continue;
- }
- mods[MODS[keys[i]]] = true;
- hasMod = true;
- }
- return new Key(set, key, mods);
- };
-
- }());
- // end:source ./Key.js
- // source ./KeySequance.js
- var KeySequance,
- Key_MATCH_OK = 1,
- Key_MATCH_FAIL = 2,
- Key_MATCH_WAIT = 3,
- Key_MATCH_NEXT = 4;
-
- (function(){
- KeySequance = class_create(IComb, {
- index: 0,
- tryCall: function(event, codes, lastCode){
- var matched = this.check_(codes, lastCode);
- if (matched === Key_MATCH_OK) {
- this.index = 0;
- this.fn.call(this.ctx, event);
- }
- return matched;
- },
- fail_: function(){
- this.index = 0;
- return Key_MATCH_FAIL;
- },
- check_: function(codes, lastCode){
- var current = this.set[this.index],
- keys = current.keys,
- last = current.last;
-
- var l = codes.length;
- if (l < keys.length)
- return Key_MATCH_WAIT;
- if (l > keys.length)
- return this.fail_();
-
- if (last !== lastCode) {
- return this.fail_();
- }
- while (--l > -1) {
- if (keys[l] !== codes[l])
- return this.fail_();
- }
- if (this.index < this.set.length - 1) {
- this.index++;
- return Key_MATCH_NEXT;
- }
- this.index = 0;
- return Key_MATCH_OK;
- }
- });
-
- }());
-
-
- // end:source ./KeySequance.js
- // source ./CombHandler.js
- var CombHandler;
- (function(){
- CombHandler = function(){
- this.keys = [];
- this.combs = [];
- };
- CombHandler.prototype = {
- keys: null,
- combs: null,
- attach: function(comb) {
- this.combs.push(comb);
- },
- off: function(fn){
- var imax = this.combs.length,
- i = 0;
- for(; i < imax; i++){
- if (this.combs[i].fn === fn) {
- this.combs.splice(i, 1);
- return true;
- }
- }
- return false;
- },
- handle: function(type, code, event){
- if (this.combs.length === 0) {
- return;
- }
- if (this.filter_(event, code)) {
- return;
- }
- if (type === 'keydown') {
- if (this.add_(code)) {
- this.emit_(type, event, code);
- }
- return;
- }
- if (type === 'keyup') {
- this.emit_(type, event, code);
- this.remove_(code);
- }
- },
- handleEvent: function(event){
- var code = event_getCode(event),
- type = event.type;
- this.handle(type, code, event);
- },
- reset: function(){
- this.keys.length = 0;
- },
- add_: function(code){
- var imax = this.keys.length,
- i = 0, x;
- for(; i < imax; i++){
- x = this.keys[i];
- if (x === code)
- return false;
-
- if (x > code) {
- this.keys.splice(i, 0, code);
- return true;
- }
- }
- this.keys.push(code);
- return true;
- },
- remove_: function(code){
- var i = this.keys.length;
- while(--i > -1){
- if (this.keys[i] === code) {
- this.keys.splice(i, 1);
- return;
- }
- }
- },
- emit_: function(type, event, lastCode){
- var next = false,
- combs = this.combs,
- imax = combs.length,
- i = 0, x, stat;
- for(; i < imax; i++){
- x = combs[i];
- if (x.type !== type)
- continue;
-
- stat = x.tryCall(event, this.keys, lastCode);
- if (Key_MATCH_OK === stat || stat === Key_MATCH_NEXT) {
- event.preventDefault();
- }
- if (stat === Key_MATCH_WAIT || stat === Key_MATCH_NEXT) {
- next = true;
- }
- }
- },
- filter_: function(event, code){
- return filter_skippedInput(event, code);
- }
- };
- }());
- // end:source ./CombHandler.js
-
- KeyboardHandler = {
- supports: function(event, param){
- if (param == null)
- return false;
- switch(event){
- case 'press':
- case 'keypress':
- case 'keydown':
- case 'keyup':
- case 'hotkey':
- case 'shortcut':
- return true;
- }
- return false;
- },
- on: function(el, type, def, fn){
- if (type === 'keypress' || type === 'press') {
- type = 'keydown';
- }
- var comb = IComb.create(def, type, fn);
- if (comb instanceof Key) {
- event_bind(el, type, function (event) {
- var code = event_getCode(event);
- var r = comb.tryCall(event, null, code);
- if (r === Key_MATCH_OK) {
- event.preventDefault();
- }
- });
- return;
- }
-
- var handler = new CombHandler;
- event_bind(el, 'keydown', handler);
- event_bind(el, 'keyup', handler);
- handler.attach(comb);
- },
- hotkeys: function(compo, hotkeys){
- var fns = [], fn, comb;
- for(comb in hotkeys) {
- fn = hotkeys[comb];
- Hotkey.on(comb, fn, compo);
- }
- compo_attachDisposer(compo, function(){
- var comb, fn;
- for(comb in hotkeys) {
- Hotkey.off(hotkeys[comb]);
- }
- });
- },
- attach: function(el, type, comb, fn, ctr){
- if (filter_isKeyboardInput(el)) {
- this.on(el, type, comb, fn);
- return;
- }
- var x = ctr;
- while(x && x.slots == null) {
- x = x.parent;
- }
- if (x == null) {
- log_error('Slot-component not found:', comb);
- return;
- }
- var hotkeys = x.hotkeys;
- if (hotkeys == null) {
- hotkeys = x.hotkeys = {};
- }
- hotkeys[comb] = fn;
- }
- };
- }());
- // end:source /src/keyboard/Handler.js
- // source /src/touch/Handler.js
- var TouchHandler;
- (function(){
-
- // source ./utils.js
- var event_bind,
- event_unbind,
- event_trigger,
- isTouchable;
-
- (function(){
- isTouchable = 'ontouchstart' in global;
-
- event_bind = function(el, type, mix) {
- el.addEventListener(type, mix, false);
- };
- event_unbind = function (el, type, mix) {
- el.removeEventListener(type, mix, false);
- };
- event_trigger = function(el, type) {
- var event = new CustomEvent(type, {
- cancelable: true,
- bubbles: true
- });
- el.dispatchEvent(event);
- };
- }());
-
- // end:source ./utils.js
- // source ./Touch.js
- var Touch;
- (function(){
- Touch = function(el, type, fn) {
- this.el = el;
- this.fn = fn;
- this.dismiss = 0;
- event_bind(el, type, this);
- event_bind(el, MOUSE_MAP[type], this);
- };
-
- var MOUSE_MAP = {
- 'mousemove': 'touchmove',
- 'mousedown': 'touchstart',
- 'mouseup': 'touchend'
- };
- var TOUCH_MAP = {
- 'touchmove': 'mousemove',
- 'touchstart': 'mousedown',
- 'touchup': 'mouseup'
- };
-
- Touch.prototype = {
- handleEvent: function (event) {
- switch(event.type){
- case 'touchstart':
- case 'touchmove':
- case 'touchend':
- this.dismiss++;
- event = prepairTouchEvent(event);
- this.fn(event);
- break;
- case 'mousedown':
- case 'mousemove':
- case 'mouseup':
- if (--this.dismiss < 0) {
- this.dismiss = 0;
- this.fn(event);
- }
- break;
- }
- }
- };
- function prepairTouchEvent(event){
- var touch = null,
- touches = event.changedTouches;
- if (touches && touches.length) {
- touch = touches[0];
- }
- if (touch == null && event.touches) {
- touch = event.touches[0];
- }
- if (touch == null) {
- return event;
- }
- return createMouseEvent(event, touch);
- }
- function createMouseEvent (event, touch) {
- var obj = Object.create(MouseEvent.prototype);
- for (var key in event) {
- obj[key] = event[key];
- }
- for (var key in PROPS) {
- obj[key] = touch[key];
- }
- return new MouseEvent(TOUCH_MAP[event.type], obj);
- }
- var PROPS = {
- clientX: 1,
- clientY: 1,
- pageX: 1,
- pageY: 1,
- screenX: 1,
- screenY: 1
- };
- }());
- // end:source ./Touch.js
- // source ./FastClick.js
- var FastClick;
- (function(){
- FastClick = function (el, fn) {
- this.state = 0;
- this.el = el;
- this.fn = fn;
- this.startX = 0;
- this.startY = 0;
- this.tStart = 0;
- this.tEnd = 0;
- this.dismiss = 0;
-
- event_bind(el, 'touchstart', this);
- event_bind(el, 'touchend', this);
- event_bind(el, 'click', this);
- };
-
- var threshold_TIME = 300,
- threshold_DIST = 10,
- timestamp_LastTouch = null;
-
- FastClick.prototype = {
- handleEvent: function (event) {
- var type = event.type;
- switch (type) {
- case 'touchmove':
- case 'touchstart':
- case 'touchend':
- timestamp_LastTouch = event.timeStamp;
- this[type](event);
- break;
- case 'touchcancel':
- this.reset();
- break;
- case 'click':
- this.click(event);
- break;
- }
- },
-
- touchstart: function(event){
- event_bind(document.body, 'touchmove', this);
-
- var e = event.touches[0];
-
- this.state = 1;
- this.tStart = event.timeStamp;
- this.startX = e.clientX;
- this.startY = e.clientY;
- },
- touchend: function (event) {
- this.tEnd = event.timeStamp;
- if (this.state === 1) {
- this.dismiss++;
- if (this.tEnd - this.tStart <= threshold_TIME) {
- this.call(event);
- return;
- }
-
- event_trigger(this.el, 'taphold');
- return;
- }
- this.reset();
- },
- click: function(event){
- if (timestamp_LastTouch != null) {
- var dt = timestamp_LastTouch - event.timeStamp;
- if (dt < 500) {
- return;
- }
- }
- if (--this.dismiss > -1)
- return;
-
- var dt = event.timeStamp - this.tEnd;
- if (dt < 400)
- return;
-
- this.dismiss = 0;
- this.call(event);
- },
- touchmove: function(event) {
- var e = event.touches[0];
-
- var dx = e.clientX - this.startX;
- if (dx < 0) dx *= -1;
- if (dx > threshold_DIST) {
- this.reset();
- return;
- }
-
- var dy = e.clientY - this.startY;
- if (dy < 0) dy *= -1;
- if (dy > threshold_DIST) {
- this.reset();
- return;
- }
- },
-
- reset: function(){
- this.state = 0;
- event_unbind(document.body, 'touchmove', this);
- },
- call: function(event){
- this.reset();
- this.fn(event);
- }
- };
-
- }());
- // end:source ./FastClick.js
-
- TouchHandler = {
- supports: function (type) {
- if (isTouchable === false) {
- return false;
- }
- switch(type){
- case 'click':
- case 'mousedown':
- case 'mouseup':
- case 'mousemove':
- return true;
- }
- return false;
- },
- on: function(el, type, fn){
- if ('click' === type) {
- return new FastClick(el, fn);
- }
- return new Touch(el, type, fn);
- }
- };
- }());
- // end:source /src/touch/Handler.js
-
- // source /src/compo/anchor.js
- /**
- * Get component that owns an element
- **/
- var Anchor;
- (function(){
- Anchor = {
- create: function(compo){
- var id = compo.ID;
- if (id == null){
- log_warn('Component should have an ID');
- return;
- }
- _cache[id] = compo;
- },
- resolveCompo: function(el, silent){
- if (el == null)
- return null;
-
- var ownerId, id, compo;
- do {
- id = el.getAttribute('x-compo-id');
- if (id != null) {
- if (ownerId == null) {
- ownerId = id;
- }
- compo = _cache[id];
- if (compo != null) {
- compo = Compo.find(compo, {
- key: 'ID',
- selector: ownerId,
- nextKey: 'components'
- });
- if (compo != null)
- return compo;
- }
- }
- el = el.parentNode;
- }while(el != null && el.nodeType === 1);
-
- // if DEBUG
- ownerId && silent !== true && log_warn('No controller for ID', ownerId);
- // endif
- return null;
- },
- removeCompo: function(compo){
- var id = compo.ID;
- if (id != null)
- _cache[id] = void 0;
- },
- getByID: function(id){
- return _cache[id];
- }
- };
-
- var _cache = {};
- }());
-
- // end:source /src/compo/anchor.js
- // source /src/compo/Compo.js
- var Compo, CompoProto;
- (function() {
-
- Compo = function () {
- if (this instanceof Compo){
- // used in Class({Base: Compo})
- return void 0;
- }
-
- return compo_create(arguments);
- };
-
- // source ./Compo.static.js
- obj_extend(Compo, {
- create: function(){
- return compo_create(arguments);
- },
-
- createClass: function(){
-
- var Ctor = compo_create(arguments),
- classProto = Ctor.prototype;
- classProto.Construct = Ctor;
- return Class(classProto);
- },
-
- initialize: function(mix, model, ctx, container, parent) {
- if (mix == null)
- throw Error('Undefined is not a component');
-
- if (container == null){
- if (ctx && ctx.nodeType != null){
- container = ctx;
- ctx = null;
- }else if (model && model.nodeType != null){
- container = model;
- model = null;
- }
- }
- var node;
- function createNode(compo) {
- node = {
- controller: compo,
- type: Dom.COMPONENT
- };
- }
- if (typeof mix === 'string'){
- if (/^[^\s]+$/.test(mix)) {
- var compo = mask.getHandler(mix);
- if (compo == null)
- throw Error('Component not found: ' + mix);
-
- createNode(compo);
- } else {
- createNode(Compo({
- template: mix
- }));
- }
- }
- else if (typeof mix === 'function') {
- createNode(mix);
- }
-
- if (parent == null && container != null) {
- parent = Anchor.resolveCompo(container);
- }
- if (parent == null){
- parent = new Compo();
- }
-
- var dom = mask.render(node, model, ctx, null, parent),
- instance = parent.components[parent.components.length - 1];
-
- if (container != null){
- container.appendChild(dom);
- Compo.signal.emitIn(instance, 'domInsert');
- }
-
- return instance;
- },
-
-
- find: function(compo, selector){
- return find_findSingle(compo, selector_parse(selector, Dom.CONTROLLER, 'down'));
- },
- closest: function(compo, selector){
- return find_findSingle(compo, selector_parse(selector, Dom.CONTROLLER, 'up'));
- },
-
- dispose: compo_dispose,
-
- ensureTemplate: compo_ensureTemplate,
-
- attachDisposer: compo_attachDisposer,
-
- config: {
- selectors: {
- '$': function(compo, selector) {
- var r = domLib_find(compo.$, selector)
- // if DEBUG
- if (r.length === 0)
- log_warn(' - element not found -', selector, compo);
- // endif
- return r;
- },
- 'compo': function(compo, selector) {
- var r = Compo.find(compo, selector);
- // if DEBUG
- if (r == null)
- log_warn(' - component not found -', selector, compo);
- // endif
- return r;
- }
- },
- /**
- * @default, global $ is used
- * IDOMLibrary = {
- * {fn}(elements) - create dom-elements wrapper,
- * on(event, selector, fn) - @see jQuery 'on'
- * }
- */
- setDOMLibrary: function(lib) {
- if (domLib === lib)
- return;
-
- domLib = lib;
- domLib_initialize();
- },
-
- getDOMLibrary: function(){
- return domLib;
- },
-
- eventDecorator: function(mix){
- if (typeof mix === 'function') {
- EventDecorator = mix;
- return;
- }
- if (typeof mix === 'string') {
- console.error('EventDecorators are not used. Touch&Mouse support is already integrated');
- EventDecorator = EventDecos[mix];
- return;
- }
- if (typeof mix === 'boolean' && mix === false) {
- EventDecorator = null;
- return;
- }
- }
-
- },
-
- pipe: Pipes.pipe,
-
- resource: function(compo){
- var owner = compo;
-
- while (owner != null) {
-
- if (owner.resource)
- return owner.resource;
-
- owner = owner.parent;
- }
-
- return include.instance();
- },
-
- plugin: function(source){
- // if DEBUG
- eval(source);
- // endif
- },
-
- Dom: {
- addEventListener: dom_addEventListener
- }
- });
-
-
- // end:source ./Compo.static.js
- // source ./async.js
- (function(){
- Compo.pause = function(compo, ctx){
- if (ctx != null) {
- if (ctx.defers == null) {
- // async components
- ctx.defers = [];
- }
- if (ctx.resolve == null) {
- obj_extend(ctx, class_Dfr.prototype);
- }
- ctx.async = true;
- ctx.defers.push(compo);
- }
-
- obj_extend(compo, CompoProto);
- return function(){
- Compo.resume(compo, ctx);
- };
- };
- Compo.resume = function(compo, ctx){
- compo.async = false;
-
- // fn can be null when calling resume synced after pause
- if (compo.resume) {
- compo.resume();
- }
- if (ctx == null) {
- return;
- }
-
- var busy = false,
- dfrs = ctx.defers,
- imax = dfrs.length,
- i = -1,
- x;
- while ( ++i < imax ){
- x = dfrs[i];
-
- if (x === compo) {
- dfrs[i] = null;
- continue;
- }
- busy = busy || x != null;
- }
- if (busy === false)
- ctx.resolve();
- };
-
- var CompoProto = {
- async: true,
- await: function(resume){
- this.resume = resume;
- }
- };
- }());
- // end:source ./async.js
-
- CompoProto = {
- type: Dom.CONTROLLER,
- __resource: null,
-
- ID: null,
-
- tagName: null,
- compoName: null,
- nodes: null,
- components: null,
- expression: null,
- attr: null,
- model: null,
- scope: null,
-
- slots: null,
- pipes: null,
-
- compos: null,
- events: null,
- hotkeys: null,
- async: false,
- await: null,
-
- meta: {
- /* render modes, relevant for mask-node */
- mode: null,
- modelMode: null,
- attributes: null,
- serializeNodes: null,
- handleAttributes: null,
- },
-
- onRenderStart: null,
- onRenderEnd: null,
- render: null,
- renderStart: function(model, ctx, container){
-
- if (compo_meta_executeAttributeHandler(this, model) === false) {
- // errored
- return;
- }
- compo_ensureTemplate(this);
-
- if (is_Function(this.onRenderStart)){
- var x = this.onRenderStart(model, ctx, container);
- if (x !== void 0 && dfr_isBusy(x))
- compo_prepairAsync(x, this, ctx);
- }
- },
- renderEnd: function(elements, model, ctx, container){
-
- Anchor.create(this, elements);
-
- this.$ = domLib(elements);
-
- if (this.events != null) {
- Events_.on(this, this.events);
- }
- if (this.compos != null) {
- Children_.select(this, this.compos);
- }
- if (this.hotkeys != null) {
- KeyboardHandler.hotkeys(this, this.hotkeys);
- }
- if (is_Function(this.onRenderEnd)) {
- this.onRenderEnd(elements, model, ctx, container);
- }
- },
- appendTo: function(el) {
- this.$.appendTo(el);
- this.emitIn('domInsert');
- return this;
- },
- append: function(template, model, selector) {
- var parent;
-
- if (this.$ == null) {
- var ast = is_String(template) ? mask.parse(template) : template;
- var parent = this;
- if (selector) {
- parent = find_findSingle(this, selector_parse(selector, Dom.CONTROLLER, 'down'));
- if (parent == null) {
- log_error('Compo::append: Container not found');
- return this;
- }
- }
- parent.nodes = [parent.nodes, ast];
- return this;
- }
-
- var frag = mask.render(template, model, null, null, this);
- parent = selector
- ? this.$.find(selector)
- : this.$;
-
- parent.append(frag);
- // @todo do not emit to created compos before
- this.emitIn('domInsert');
- return this;
- },
- find: function(selector){
- return find_findSingle(
- this, selector_parse(selector, Dom.CONTROLLER, 'down')
- );
- },
- findAll: function(selector){
- return find_findAll(
- this, selector_parse(selector, Dom.CONTROLLER, 'down')
- );
- },
- closest: function(selector){
- return find_findSingle(
- this, selector_parse(selector, Dom.CONTROLLER, 'up')
- );
- },
- on: function() {
- var x = _Array_slice.call(arguments);
- if (arguments.length < 3) {
- log_error('Invalid Arguments Exception @use .on(type,selector,fn)');
- return this;
- }
-
- if (this.$ != null)
- Events_.on(this, [x]);
-
- if (this.events == null) {
- this.events = [x];
- } else if (is_Array(this.events)) {
- this.events.push(x);
- } else {
- this.events = [x, this.events];
- }
- return this;
- },
- remove: function() {
- compo_removeElements(this);
- compo_detachChild(this);
- compo_dispose(this);
-
- this.$ = null;
- return this;
- },
-
- slotState: function(slotName, isActive){
- Compo.slot.toggle(this, slotName, isActive);
- return this;
- },
-
- signalState: function(signalName, isActive){
- Compo.signal.toggle(this, signalName, isActive);
- return this;
- },
-
- emitOut: function(signalName /* args */){
- Compo.signal.emitOut(
- this,
- signalName,
- this,
- arguments.length > 1
- ? _Array_slice.call(arguments, 1)
- : null
- );
- return this;
- },
-
- emitIn: function(signalName /* args */){
- Compo.signal.emitIn(
- this,
- signalName,
- this,
- arguments.length > 1
- ? _Array_slice.call(arguments, 1)
- : null
- );
- return this;
- },
-
- $scope: function(path){
- var accessor = '$scope.' + path;
- return mask.Utils.Expression.eval(accessor, null, null, this);
- },
- $eval: function(expr, model_, ctx_){
- return mask.Utils.Expression.eval(expr, model_ || this.model, ctx_, this);
- },
- };
-
- Compo.prototype = CompoProto;
- }());
-
- // end:source /src/compo/Compo.js
-
- // source /src/signal/exports.js
- (function(){
-
- // source ./utils.js
- var _hasSlot,
- _fire;
-
- (function(){
- // @param sender - event if sent from DOM Event or CONTROLLER instance
- _fire = function (ctr, slot, sender, args_, direction) {
- if (ctr == null) {
- return false;
- }
- var found = false,
- args = args_,
- fn = ctr.slots != null && ctr.slots[slot];
-
- if (typeof fn === 'string') {
- fn = ctr[fn];
- }
- if (typeof fn === 'function') {
- found = true;
-
- var isDisabled = ctr.slots.__disabled != null && ctr.slots.__disabled[slot];
- if (isDisabled !== true) {
-
- var result = args == null
- ? fn.call(ctr, sender)
- : fn.apply(ctr, [ sender ].concat(args));
-
- if (result === false) {
- return true;
- }
- if (is_ArrayLike(result)) {
- args = result;
- }
- }
- }
-
- if (direction === -1 && ctr.parent != null) {
- return _fire(ctr.parent, slot, sender, args, direction) || found;
- }
-
- if (direction === 1 && ctr.components != null) {
- var compos = ctr.components,
- imax = compos.length,
- i = 0;
- for (; i < imax; i++) {
- found = _fire(compos[i], slot, sender, args, direction) || found;
- }
- }
-
- return found;
- } // _fire()
-
- _hasSlot = function (ctr, slot, direction, isActive) {
- if (ctr == null) {
- return false;
- }
- var slots = ctr.slots;
- if (slots != null && slots[slot] != null) {
- if (typeof slots[slot] === 'string') {
- slots[slot] = ctr[slots[slot]];
- }
- if (typeof slots[slot] === 'function') {
- if (isActive === true) {
- if (slots.__disabled == null || slots.__disabled[slot] !== true) {
- return true;
- }
- } else {
- return true;
- }
- }
- }
- if (direction === -1 && ctr.parent != null) {
- return _hasSlot(ctr.parent, slot, direction);
- }
- if (direction === 1 && ctr.components != null) {
- for (var i = 0, length = ctr.components.length; i < length; i++) {
- if (_hasSlot(ctr.components[i], slot, direction)) {
- return true;
- }
- }
- }
- return false;
- };
- }());
-
- // end:source ./utils.js
- // source ./toggle.js
- var _toggle_all,
- _toggle_single;
- (function(){
- _toggle_all = function (ctr, slot, isActive) {
-
- var parent = ctr,
- previous = ctr;
- while ((parent = parent.parent) != null) {
- __toggle_slotState(parent, slot, isActive);
-
- if (parent.$ == null || parent.$.length === 0) {
- // we track previous for changing elements :disable state
- continue;
- }
-
- previous = parent;
- }
-
- __toggle_slotStateWithChilds(ctr, slot, isActive);
- __toggle_elementsState(previous, slot, isActive);
- };
-
- _toggle_single = function(ctr, slot, isActive) {
- __toggle_slotState(ctr, slot, isActive);
-
- if (!isActive && (_hasSlot(ctr, slot, -1, true) || _hasSlot(ctr, slot, 1, true))) {
- // there are some active slots; do not disable elements;
- return;
- }
- __toggle_elementsState(ctr, slot, isActive);
- };
-
-
- function __toggle_slotState(ctr, slot, isActive) {
- var slots = ctr.slots;
- if (slots == null || slots.hasOwnProperty(slot) === false) {
- return;
- }
- var disabled = slots.__disabled;
- if (disabled == null) {
- disabled = slots.__disabled = {};
- }
- disabled[slot] = isActive === false;
- }
-
- function __toggle_slotStateWithChilds(ctr, slot, isActive) {
- __toggle_slotState(ctr, slot, isActive);
-
- var compos = ctr.components;
- if (compos != null) {
- var imax = compos.length,
- i = 0;
- for(; i < imax; i++) {
- __toggle_slotStateWithChilds(compos[i], slot, isActive);
- }
- }
- }
-
- function __toggle_elementsState(ctr, slot, isActive) {
- if (ctr.$ == null) {
- log_warn('Controller has no elements to toggle state');
- return;
- }
-
- domLib()
- .add(ctr.$.filter('[data-signals]'))
- .add(ctr.$.find('[data-signals]'))
- .each(function(index, node) {
- var signals = node.getAttribute('data-signals');
-
- if (signals != null && signals.indexOf(slot) !== -1) {
- node[isActive === true ? 'removeAttribute' : 'setAttribute']('disabled', 'disabled');
- }
- });
- }
-
-
-
- }());
- // end:source ./toggle.js
- // source ./attributes.js
- (function(){
-
- _create('signal');
-
- _createEvent('change');
- _createEvent('click');
- _createEvent('tap', 'click');
-
- _createEvent('keypress');
- _createEvent('keydown');
- _createEvent('keyup');
- _createEvent('mousedown');
- _createEvent('mouseup');
-
- _createEvent('press', 'keydown');
- _createEvent('shortcut', 'keydown');
-
- function _createEvent(name, type) {
- _create(name, type || name);
- }
- function _create(name, asEvent) {
- mask.registerAttrHandler('x-' + name, 'client', function(node, attrValue, model, ctx, el, ctr){
- _attachListener(el, ctr, attrValue, asEvent);
- });
- }
-
- function _attachListener(el, ctr, definition, asEvent) {
- var arr = definition.split(';'),
- signals = '',
- imax = arr.length,
- i = -1,
- x;
-
- var i_colon,
- i_param,
- event,
- mix,
- param,
- name,
- fn;
-
- while ( ++i < imax ) {
- x = arr[i].trim();
- if (x === '')
- continue;
-
- mix = param = name = null;
-
- i_colon = x.indexOf(':');
- if (i_colon !== -1) {
- mix = x.substring(0, i_colon);
- i_param = mix.indexOf('(');
- if (i_param !== -1) {
- param = mix.substring(i_param + 1, mix.lastIndexOf(')'));
- mix = mix.substring(0, i_param);
-
- // if DEBUG
- param === '' && log_error('Not valid signal parameter');
- // endif
- }
- x = x.substring(i_colon + 1).trim();
- }
-
- name = x;
- fn = _createListener(ctr, name);
-
- if (asEvent == null) {
- event = mix;
- } else {
- event = asEvent;
- param = mix;
- }
-
- if (!event) {
- log_error('Signal: Eventname is not set', arr[i]);
- }
- if (!fn) {
- log_warn('Slot not found:', name);
- continue;
- }
-
- signals += ',' + name + ',';
- dom_addEventListener(el, event, fn, param, ctr);
- }
-
- if (signals !== '') {
- var attr = el.getAttribute('data-signals');
- if (attr != null) {
- signals = attr + signals;
- }
- el.setAttribute('data-signals', signals);
- }
- }
-
- function _createListener (ctr, slot) {
- if (_hasSlot(ctr, slot, -1) === false) {
- return null;
- }
- return function(event) {
- var args = arguments.length > 1
- ? _Array_slice.call(arguments, 1)
- : null;
- _fire(ctr, slot, event, args, -1);
- };
- }
- }());
- // end:source ./attributes.js
-
- obj_extend(Compo, {
- signal: {
- toggle: _toggle_all,
-
- // to parent
- emitOut: function(controller, slot, sender, args) {
- var captured = _fire(controller, slot, sender, args, -1);
-
- // if DEBUG
- !captured && log_warn('Signal %c%s','font-weight:bold;', slot, 'was not captured');
- // endif
-
- },
- // to children
- emitIn: function(controller, slot, sender, args) {
- _fire(controller, slot, sender, args, 1);
- },
-
- enable: function(controller, slot) {
- _toggle_all(controller, slot, true);
- },
-
- disable: function(controller, slot) {
- _toggle_all(controller, slot, false);
- }
- },
- slot: {
- toggle: _toggle_single,
- enable: function(controller, slot) {
- _toggle_single(controller, slot, true);
- },
- disable: function(controller, slot) {
- _toggle_single(controller, slot, false);
- },
- invoke: function(controller, slot, event, args) {
- var slots = controller.slots;
- if (slots == null || typeof slots[slot] !== 'function') {
- log_error('Slot not found', slot, controller);
- return null;
- }
-
- if (args == null) {
- return slots[slot].call(controller, event);
- }
-
- return slots[slot].apply(controller, [event].concat(args));
- },
-
- }
-
- });
-
- }());
- // end:source /src/signal/exports.js
-
- // source /src/DomLite.js
- /*
- * Extrem simple Dom Library. If (jQuery | Kimbo | Zepto) is not used.
- * Only methods, required for the Compo library are implemented.
- */
- var DomLite;
- (function(document){
- if (document == null)
- return;
-
- Compo.DomLite = DomLite = function(els){
- if (this instanceof DomLite === false)
- return new DomLite(els);
-
- return this.add(els)
- };
-
- if (domLib == null)
- domLib = DomLite;
-
- var Proto = DomLite.fn = {
- constructor: DomLite,
- length: 0,
- add: function(mix){
- if (mix == null)
- return this;
- if (is_Array(mix) === true)
- return each(mix, this.add, this);
-
- var type = mix.nodeType;
- if (type === 11 /* Node.DOCUMENT_FRAGMENT_NODE */)
- return each(mix.childNodes, this.add, this);
-
- if (type == null) {
- if (typeof mix.length === 'number')
- return each(mix, this.add, this);
-
- log_warn('Uknown domlite object');
- return this;
- }
-
- this[this.length++] = mix;
- return this;
- },
- on: function(){
- return binder.call(this, on, delegate, arguments);
- },
- off: function(){
- return binder.call(this, off, undelegate, arguments);
- },
- find: function(sel){
- return each(this, function(node){
- this.add(_$$.call(node, sel));
- }, new DomLite);
- },
- filter: function(sel){
- return each(this, function(node, index){
- _is(node, sel) === true && this.add(node);
- }, new DomLite);
- },
- parent: function(){
- var x = this[0];
- return new DomLite(x && x.parentNode);
- },
- children: function(sel){
- var set = each(this, function(node){
- this.add(node.childNodes);
- }, new DomLite);
- return sel == null ? set : set.filter(sel);
- },
- closest: function(selector){
- var x = this[0],
- dom = new DomLite;
- while( x != null && x.parentNode != null){
- x = x.parentNode;
- if (_is(x, selector))
- return dom.add(x);
- }
- return dom;
- },
- next: function(selector){
- var x = this[0],
- dom = new DomLite;
- while (x != null && x.nextElementSibling != null) {
- x = x.nextElementSibling;
- if (selector == null) {
- return dom.add(x);
- }
- if (_is(x, selector)) {
- return dom.add(x);
- }
- }
- return dom;
- },
- remove: function(){
- return each(this, function(x){
- x.parentNode.removeChild(x);
- });
- },
- text: function(mix){
- if (arguments.length === 0) {
- return aggr('', this, function(txt, x){
- return txt + x.textContent;
- });
- }
- return each(this, function(x){
- x.textContent = mix;
- });
- },
- html: function(mix){
- if (arguments.length === 0) {
- return aggr('', this, function(txt, x){
- return txt + x.innerHTML;
- });
- }
- return each(this, function(x){
- x.innerHTML = mix;
- });
- },
- val: function(mix){
- if (arguments.length === 0) {
- return this.length === 0 ? null : this[0].value;
- }
- if (this.length !== 0) {
- this[0].value = mix;
- }
- return this;
- },
- focus: function(){
- return each(this, function(x){
- x.focus && x.focus();
- });
- }
- };
-
- (function(){
- each(['show', 'hide'], function(method) {
- Proto[method] = function(){
- return each(this, function(x){
- x.style.display = method === 'hide' ? 'none' : '';
- });
- };
- });
- }());
-
- (function(){
- var Manip = {
- append: function(node, el){
- after_(node, node.lastChild, el);
- },
- prepend: function(node, el){
- before_(node, node.firstChild, el);
- },
- after: function(node, el){
- after_(node.parentNode, node, el);
- },
- before: function(node, el){
- before_(node.parentNode, node, el);
- }
- };
- each(['append', 'prepend', 'before', 'after'], function(method){
- var fn = Manip[method];
- Proto[method] = function(mix){
- var isArray = is_Array(mix);
- return each(this, function(node){
- if (isArray) {
- each(mix, function(el){
- fn(node, el);
- });
- return;
- }
- fn(node, mix);
- });
- };
- });
- function before_(parent, anchor, el){
- if (parent == null || el == null)
- return;
- parent.insertBefore(el, anchor);
- }
- function after_(parent, anchor, el) {
- var next = anchor != null ? anchor.nextSibling : null;
- before_(parent, next, el);
- }
- }());
-
-
- function each(arr, fn, ctx){
- if (arr == null)
- return ctx || arr;
- var imax = arr.length,
- i = -1;
- while( ++i < imax ){
- fn.call(ctx || arr, arr[i], i);
- }
- return ctx || arr;
- }
- function aggr(seed, arr, fn, ctx) {
- each(arr, function(x, i){
- seed = fn.call(ctx || arr, seed, arr[i], i);
- });
- return seed;
- }
- function indexOf(arr, fn, ctx){
- if (arr == null)
- return -1;
- var imax = arr.length,
- i = -1;
- while( ++i < imax ){
- if (fn.call(ctx || arr, arr[i], i) === true)
- return i;
- }
- return -1;
- }
-
- var docEl = document.documentElement;
- var _$$ = docEl.querySelectorAll;
- var _is = (function(){
- var matchesSelector =
- docEl.webkitMatchesSelector ||
- docEl.mozMatchesSelector ||
- docEl.msMatchesSelector ||
- docEl.oMatchesSelector ||
- docEl.matchesSelector
- ;
- return function (el, selector) {
- return el == null || el.nodeType !== 1
- ? false
- : matchesSelector.call(el, selector);
- };
- }());
-
- /* Events */
- var binder, on, off, delegate, undelegate;
- (function(){
- binder = function(bind, bindSelector, args){
- var length = args.length,
- fn;
- if (2 === length)
- fn = bind
- if (3 === length)
- fn = bindSelector;
-
- if (fn != null) {
- return each(this, function(node){
- fn.apply(DomLite(node), args);
- });
- }
- log_error('`DomLite.on|off` - invalid arguments count');
- return this;
- };
- on = function(type, fn){
- return run(this, _addEvent, type, fn);
- };
- off = function(type, fn){
- return run(this, _remEvent, type, fn);
- };
- delegate = function(type, selector, fn){
- function guard(event){
- var el = event.target,
- current = event.currentTarget;
- if (current === el)
- return;
- while(el != null && el !== current){
- if (_is(el, selector)) {
- fn(event);
- return;
- }
- el = el.parentNode;
- }
- }
- (fn._guards || (fn._guards = [])).push(guard);
- return on.call(this, type, guard);
- };
- undelegate = function(type, selector, fn){
- return each(fn._quards, function(guard){
- off.call(this, type, guard);
- }, this);
- };
-
- function run(set, handler, type, fn){
- return each(set, function(node){
- handler.call(node, type, fn, false);
- });
- }
- var _addEvent = docEl.addEventListener,
- _remEvent = docEl.removeEventListener;
- }());
-
- /* class handler */
- (function(){
- var isClassListSupported = docEl.classList != null;
- var hasClass = isClassListSupported === true
- ? function (node, klass) {
- return node.classList.contains(klass);
- }
- : function(node, klass) {
- return -1 !== (' ' + node.className + ' ').indexOf(' ' + klass + ' ');
- };
- Proto.hasClass = function(klass){
- return -1 !== indexOf(this, function(node){
- return hasClass(node, klass)
- });
- };
- var Shim;
- (function(){
- Shim = {
- add: function(node, klass){
- if (hasClass(node, klass) === false)
- add(node, klass);
- },
- remove: function(node, klass){
- if (hasClass(node, klass) === true)
- remove(node, klass);
- },
- toggle: function(node, klass){
- var fn = hasClass(node, klass) === true
- ? remove
- : add;
- fn(node, klass);
- }
- };
- function add(node, klass){
- node.className += ' ' + klass;
- }
- function remove(node, klass){
- node.className = (' ' + node.className + ' ').replace(' ' + klass + ' ', ' ');
- }
- }());
-
- each(['add', 'remove', 'toggle'], function(method){
- var mutatorFn = isClassListSupported === false
- ? Shim[method]
- : function(node, klass){
- var classList = node.classList;
- classList[method].call(classList, klass);
- };
- Proto[method + 'Class'] = function(klass){
- return each(this, function(node){
- mutatorFn(node, klass);
- });
- };
- });
-
- }());
-
-
- // Events
- (function(){
- var createEvent = function(type){
- var event = document.createEvent('Event');
- event.initEvent(type, true, true);
- return event;
- };
- var create = function(type, data){
- if (data == null)
- return createEvent(type);
- var event = document.createEvent('CustomEvent');
- event.initCustomEvent(type, true, true, data);
- return event;
- };
- var dispatch = function(node, event){
- node.dispatchEvent(event);
- };
- Proto['trigger'] = function(type, data){
- var event = create(type, data);
- return each(this, function(node){
- dispatch(node, event);
- });
- };
- }());
-
- // Attributes
- (function(){
- Proto['attr'] = function(name, val){
- if (val === void 0)
- return this[0] && this[0].getAttribute(name);
- return each(this, function(node){
- node.setAttribute(name, val);
- });
- };
- Proto['removeAttr'] = function(name){
- return each(this, function(node){
- node.removeAttribute(name);
- });
- };
- }());
-
- if (Object.setPrototypeOf)
- Object.setPrototypeOf(Proto, Array.prototype);
- else if (Proto.__proto__)
- Proto.__proto__ = Array.prototype;
-
- DomLite.prototype = Proto;
- domLib_initialize();
-
- }(global.document));
- // end:source /src/DomLite.js
- // source /src/jcompo/jCompo.js
- // try to initialize the dom lib, or is then called from `setDOMLibrary`
- domLib_initialize();
-
- function domLib_initialize(){
- if (domLib == null || domLib.fn == null)
- return;
-
- domLib.fn.compo = function(selector){
- if (this.length === 0)
- return null;
-
- var compo = Anchor.resolveCompo(this[0], true);
-
- return selector == null
- ? compo
- : find_findSingle(compo, selector_parse(selector, Dom.CONTROLLER, 'up'));
- };
-
- domLib.fn.model = function(selector){
- var compo = this.compo(selector);
- if (compo == null)
- return null;
-
- var model = compo.model;
- while(model == null && compo.parent){
- compo = compo.parent;
- model = compo.model;
- }
- return model;
- };
-
- // insert
- (function(){
- var jQ_Methods = [
- 'append',
- 'prepend',
- 'before',
- 'after'
- ];
-
- [
- 'appendMask',
- 'prependMask',
- 'beforeMask',
- 'afterMask'
- ].forEach(function(method, index){
-
- domLib.fn[method] = function(template, model, ctr, ctx){
- if (this.length === 0) {
- // if DEBUG
- log_warn(' $.', method, '- no element was selected(found)');
- // endif
- return this;
- }
- if (this.length > 1) {
- // if DEBUG
- log_warn(' $.', method, ' can insert only to one element. Fix is comming ...');
- // endif
- }
- if (ctr == null) {
- ctr = index < 2
- ? this.compo()
- : this.parent().compo()
- ;
- }
-
- var isUnsafe = false;
- if (ctr == null) {
- ctr = {};
- isUnsafe = true;
- }
-
-
- if (ctr.components == null) {
- ctr.components = [];
- }
-
- var compos = ctr.components,
- i = compos.length,
- fragment = mask.render(template, model, ctx, null, ctr);
-
- var self = this[jQ_Methods[index]](fragment),
- imax = compos.length;
-
- for (; i < imax; i++) {
- Compo.signal.emitIn(compos[i], 'domInsert');
- }
-
- if (isUnsafe && imax !== 0) {
- // if DEBUG
- log_warn(
- '$.'
- , method
- , '- parent controller was not found in Elements DOM.'
- , 'This can lead to memory leaks.'
- );
- log_warn(
- 'Specify the controller directly, via $.'
- , method
- , '(template[, model, controller, ctx])'
- );
- // endif
- }
-
- return self;
- };
-
- });
- }());
-
-
- // remove
- (function(){
- var jq_remove = domLib.fn.remove,
- jq_empty = domLib.fn.empty
- ;
-
- domLib.fn.removeAndDispose = function(){
- this.each(each_tryDispose);
-
- return jq_remove.call(this);
- };
-
- domLib.fn.emptyAndDispose = function(){
- this.each(each_tryDisposeChildren);
-
- return jq_empty.call(this);
- }
-
-
- function each_tryDispose(index, node){
- node_tryDispose(node);
- }
-
- function each_tryDisposeChildren(index, node){
- node_tryDisposeChildren(node);
- }
-
- }());
- }
-
- // end:source /src/jcompo/jCompo.js
-
-
- // source /src/handler/slot.js
-
- function SlotHandler() {}
-
- mask.registerHandler(':slot', SlotHandler);
-
- SlotHandler.prototype = {
- constructor: SlotHandler,
- renderEnd: function(element, model, cntx, container){
- this.slots = {};
-
- this.expression = this.attr.on;
-
- this.slots[this.attr.signal] = this.handle;
- },
- handle: function(){
- var expr = this.expression;
-
- mask.Utils.Expression.eval(expr, this.model, global, this);
- }
- };
-
- // end:source /src/handler/slot.js
-
-
- return Compo;
-
- }(Mask));
-
- // end:source /ref-mask-compo/lib/compo.embed.js
- // source /ref-mask-j/lib/jmask.embed.js
-
- var jmask = exports.jmask = Mask.jmask = (function(mask){
-
- // source ../src/scope-vars.js
- var Dom = mask.Dom,
- _mask_render = mask.render,
- _mask_parse = mask.parse,
- _mask_ensureTmplFnOrig = mask.Utils.ensureTmplFn,
- _signal_emitIn = (mask.Compo || Compo).signal.emitIn;
-
-
- function _mask_ensureTmplFn(value) {
- if (typeof value !== 'string') {
- return value;
- }
- return _mask_ensureTmplFnOrig(value);
- }
-
-
- // end:source ../src/scope-vars.js
-
- // source ../src/util/array.js
- var arr_eachAny,
- arr_unique;
-
- (function(){
-
- arr_eachAny = function(mix, fn) {
- if (is_ArrayLike(mix) === false) {
- fn(mix);
- return;
- }
- var imax = mix.length,
- i = -1;
- while ( ++i < imax ){
- fn(mix[i], i);
- }
- };
-
- (function() {
- arr_unique = function(array) {
- hasDuplicate_ = false;
- array.sort(sort);
- if (hasDuplicate_ === false)
- return array;
-
- var duplicates = [],
- i = 0,
- j = 0,
- imax = array.length - 1;
-
- while (i < imax) {
- if (array[i++] === array[i]) {
- duplicates[j++] = i;
- }
- }
- while (j--) {
- array.splice(duplicates[j], 1);
- }
-
- return array;
- };
-
- var hasDuplicate_ = false;
- function sort(a, b) {
- if (a === b) {
- hasDuplicate_ = true;
- return 0;
- }
- return 1;
- }
- }());
-
- }());
-
- // end:source ../src/util/array.js
- // source ../src/util/selector.js
- var selector_parse,
- selector_match;
-
- (function(){
-
- selector_parse = function(selector, type, direction) {
- if (selector == null)
- log_error('selector is null for the type', type);
-
- if (typeof selector === 'object')
- return selector;
-
- var key,
- prop,
- nextKey,
- filters,
-
- _key,
- _prop,
- _selector;
-
- var index = 0,
- length = selector.length,
- c,
- end,
- matcher, root, current,
- eq,
- slicer;
-
- if (direction === 'up') {
- nextKey = sel_key_UP;
- } else {
- nextKey = type === Dom.SET
- ? sel_key_MASK
- : sel_key_COMPOS;
- }
-
- while (index < length) {
-
- c = selector.charCodeAt(index);
-
- if (c < 33) {
- index++;
- continue;
- }
- if (c === 62 /* > */) {
- if (matcher == null) {
- root = matcher = {
- selector: '__scope__',
- nextKey: nextKey,
- filters: null,
- next: {
- type: 'children',
- matcher: null
- }
- };
- } else {
- matcher.next = {
- type: 'children',
- matcher: null
- };
- }
- current = matcher;
- matcher = null;
- index++;
- continue;
- }
-
- end = selector_moveToBreak(selector, index + 1, length);
- if (c === 46 /*.*/ ) {
- _key = 'class';
- _prop = sel_key_ATTR;
- _selector = sel_hasClassDelegate(selector.substring(index + 1, end));
- }
-
- else if (c === 35 /*#*/ ) {
- _key = 'id';
- _prop = sel_key_ATTR;
- _selector = selector.substring(index + 1, end);
- }
-
- else if (c === 91 /*[*/ ) {
- eq = selector.indexOf('=', index);
- //if DEBUG
- eq === -1 && console.error('Attribute Selector: should contain "="');
- // endif
-
- _prop = sel_key_ATTR;
- _key = selector.substring(index + 1, eq);
-
- //slice out quotes if any
- c = selector.charCodeAt(eq + 1);
- slicer = c === 34 || c === 39 ? 2 : 1;
-
- _selector = selector.substring(eq + slicer, end - slicer + 1);
-
- // increment, as cursor is on closed ']'
- end++;
- }
- else if (c === 58 /*:*/ && selector.charCodeAt(index + 1) === 58) {
- index += 2;
- var start = index, name, expr;
- do {
- c = selector.charCodeAt(index);
- } while (c >= 97 /*a*/ && c <= 122 /*z*/ && ++index < length);
-
- name = selector.substring(start, index);
- if (c === 40 /*(*/) {
- start = ++index;
- do {
- c = selector.charCodeAt(index);
- } while (c !== 41/*)*/ && ++index < length);
- expr = selector.substring(start, index);
- index++;
- }
- var pseudo = PseudoSelectors(name, expr);
- if (matcher == null) {
- matcher = {
- selector: '*',
- nextKey: nextKey
- };
- }
- if (root == null) {
- root = matcher;
- }
- if (matcher.filters == null) {
- matcher.filters = [];
- }
- matcher.filters.push(pseudo);
- continue;
- }
- else {
-
- if (matcher != null) {
- matcher.next = {
- type: 'any',
- matcher: null
- };
- current = matcher;
- matcher = null;
- }
-
- _prop = null;
- _key = type === Dom.SET ? 'tagName' : 'compoName';
- _selector = selector.substring(index, end);
- }
-
- index = end;
-
- if (matcher == null) {
- matcher = {
- key: _key,
- prop: _prop,
- selector: _selector,
- nextKey: nextKey,
- filters: null
- };
- if (root == null)
- root = matcher;
-
- if (current != null) {
- current.next.matcher = matcher;
- }
-
- continue;
- }
- if (matcher.filters == null)
- matcher.filters = [];
-
- matcher.filters.push({
- key: _key,
- selector: _selector,
- prop: _prop
- });
- }
-
- if (current && current.next)
- current.next.matcher = matcher;
-
- return root;
- };
-
- selector_match = function(node, selector, type) {
- if (typeof selector === 'string') {
- if (type == null) {
- type = Dom[node.compoName ? 'CONTROLLER' : 'SET'];
- }
- selector = selector_parse(selector, type);
- }
-
- var obj = selector.prop ? node[selector.prop] : node,
- matched = false;
-
- if (obj == null)
- return false;
- if (selector.selector === '*') {
- matched = true
- }
- else if (typeof selector.selector === 'function') {
- matched = selector.selector(obj[selector.key]);
- }
- else if (selector.selector.test != null) {
- if (selector.selector.test(obj[selector.key])) {
- matched = true;
- }
- }
- else if (obj[selector.key] === selector.selector) {
- matched = true;
- }
-
- if (matched === true && selector.filters != null) {
- for(var i = 0, x, imax = selector.filters.length; i < imax; i++){
- x = selector.filters[i];
-
- if (typeof x === 'function') {
- matched = x(node, type);
- if (matched === false)
- return false;
- continue;
- }
- if (selector_match(node, x, type) === false) {
- return false;
- }
- }
- }
-
- return matched;
- };
-
- // ==== private
-
- var sel_key_UP = 'parent',
- sel_key_MASK = 'nodes',
- sel_key_COMPOS = 'components',
- sel_key_ATTR = 'attr';
-
-
- function sel_hasClassDelegate(matchClass) {
- return function(className){
- return sel_hasClass(className, matchClass);
- };
- }
-
- // [perf] http://jsperf.com/match-classname-indexof-vs-regexp/2
- function sel_hasClass(className, matchClass, index) {
- if (typeof className !== 'string')
- return false;
-
- if (index == null)
- index = 0;
-
- index = className.indexOf(matchClass, index);
-
- if (index === -1)
- return false;
-
- if (index > 0 && className.charCodeAt(index - 1) > 32)
- return sel_hasClass(className, matchClass, index + 1);
-
- var class_Length = className.length,
- match_Length = matchClass.length;
-
- if (index < class_Length - match_Length && className.charCodeAt(index + match_Length) > 32)
- return sel_hasClass(className, matchClass, index + 1);
-
- return true;
- }
-
-
- function selector_moveToBreak(selector, index, length) {
- var c,
- isInQuote = false,
- isEscaped = false;
-
- while (index < length) {
- c = selector.charCodeAt(index);
-
- if (c === 34 || c === 39) {
- // '"
- isInQuote = !isInQuote;
- }
-
- if (c === 92) {
- // [\]
- isEscaped = !isEscaped;
- }
-
- if (c === 46 || c === 35 || c === 91 || c === 93 || c === 62 || c < 33) {
- // .#[]>
- if (isInQuote !== true && isEscaped !== true) {
- break;
- }
- }
- index++;
- }
- return index;
- }
-
- var PseudoSelectors;
- (function() {
- PseudoSelectors = function(name, expr) {
- var fn = Fns[name];
- if (fn !== void 0)
- return fn;
-
- var worker = Workers[name];
- if (worker !== void 0)
- return worker(expr);
-
- throw new Error('Uknown pseudo selector:' + name);
- };
- var Fns = {
- text: function (node) {
- return node.type === Dom.TEXTNODE;
- },
- node: function(node) {
- return node.type === Dom.NODE;
- }
- };
- var Workers = {
- not: function(expr){
- return function(node, type){
- return !selector_match(node, expr, type);
- }
- }
- };
- }());
- }());
-
- // end:source ../src/util/selector.js
- // source ../src/util/utils.js
- var jmask_filter,
- jmask_find,
- jmask_clone,
- jmask_deepest,
- jmask_getText
- ;
-
- (function(){
-
- jmask_filter = function(mix, matcher) {
- if (matcher == null)
- return mix;
-
- var result = [];
- arr_eachAny(mix, function(node, i) {
- if (selector_match(node, matcher))
- result.push(node);
- });
- return result;
- };
-
- /**
- * - mix (Node | Array[Node])
- */
- jmask_find = function(mix, matcher, output, deep) {
- if (mix == null) {
- return output;
- }
- if (output == null) {
- output = [];
- }
- if (deep == null) {
- // is root and matchling like `> div` (childs only)
- if (matcher.selector === '__scope__') {
- deep = false;
- matcher = matcher.next.matcher;
- } else{
- deep = true;
- }
- }
-
- arr_eachAny(mix, function(node){
- if (selector_match(node, matcher) === false) {
-
- if (matcher.next == null && deep !== false)
- jmask_find(node[matcher.nextKey], matcher, output, deep);
-
- return;
- }
-
- if (matcher.next == null) {
- output.push(node);
- if (deep === true)
- jmask_find(node[matcher.nextKey], matcher, output, deep);
-
- return;
- }
-
- var next = matcher.next;
- deep = next.type !== 'children';
- jmask_find(node[matcher.nextKey], next.matcher, output, deep);
- });
- return output;
- };
-
- jmask_clone = function(node, parent){
- var clone = obj_create(node);
-
- var attr = node.attr;
- if (attr != null){
- clone.attr = obj_create(attr);
- }
-
- var nodes = node.nodes;
- if (nodes != null){
- if (is_ArrayLike(nodes) === false) {
- clone.nodes = [ jmask_clone(nodes, clone) ];
- }
- else {
- clone.nodes = [];
- var imax = nodes.length,
- i = 0;
- for(; i< imax; i++){
- clone.nodes[i] = jmask_clone(nodes[i], clone);
- }
- }
- }
- return clone;
- };
-
-
- jmask_deepest = function(node){
- var current = node,
- prev;
- while(current != null){
- prev = current;
- current = current.nodes && current.nodes[0];
- }
- return prev;
- };
-
-
- jmask_getText = function(node, model, ctx, controller) {
- if (Dom.TEXTNODE === node.type) {
- if (is_Function(node.content)) {
- return node.content('node', model, ctx, null, controller);
- }
- return node.content;
- }
-
- var output = '';
- if (node.nodes != null) {
- for(var i = 0, x, imax = node.nodes.length; i < imax; i++){
- x = node.nodes[i];
- output += jmask_getText(x, model, ctx, controller);
- }
- }
- return output;
- };
-
- }());
-
- // end:source ../src/util/utils.js
-
- // source ../src/jmask/jmask.js
- function jMask(mix) {
- if (this instanceof jMask === false)
- return new jMask(mix);
- if (mix == null)
- return this;
- if (mix.type === Dom.SET)
- return mix;
- return this.add(mix);
- }
-
- var Proto = jMask.prototype = {
- constructor: jMask,
- type: Dom.SET,
- length: 0,
- components: null,
- add: function(mix) {
- var i, length;
-
- if (typeof mix === 'string') {
- mix = _mask_parse(mix);
- }
-
- if (is_ArrayLike(mix)) {
- for (i = 0, length = mix.length; i < length; i++) {
- this.add(mix[i]);
- }
- return this;
- }
-
- if (typeof mix === 'function' && mix.prototype.type != null) {
- // assume this is a controller
- mix = {
- controller: mix,
- type: Dom.COMPONENT
- };
- }
-
-
- var type = mix.type;
-
- if (!type) {
- // @TODO extend to any type?
- console.error('Only Mask Node/Component/NodeText/Fragment can be added to jmask set', mix);
- return this;
- }
-
- if (type === Dom.FRAGMENT) {
- var nodes = mix.nodes;
-
- for(i = 0, length = nodes.length; i < length;) {
- this[this.length++] = nodes[i++];
- }
- return this;
- }
-
- if (type === Dom.CONTROLLER) {
-
- if (mix.nodes != null && mix.nodes.length) {
- for (i = mix.nodes.length; i !== 0;) {
- // set controller as parent, as parent is mask dom node
- mix.nodes[--i].parent = mix;
- }
- }
-
- if (mix.$ != null) {
- this.type = Dom.CONTROLLER;
- }
- }
-
-
-
- this[this.length++] = mix;
- return this;
- },
- toArray: function() {
- return _Array_slice.call(this);
- },
- /**
- * render([model, cntx, container]) -> HTMLNode
- * - model (Object)
- * - cntx (Object)
- * - container (Object)
- * - returns (HTMLNode)
- *
- **/
- render: function(model, ctx, el, ctr) {
- this.components = [];
-
- if (this.length === 1) {
- return _mask_render(this[0], model, ctx, el, ctr || this);
- }
-
- if (el == null) {
- el = document.createDocumentFragment();
- }
-
- for (var i = 0, length = this.length; i < length; i++) {
- _mask_render(this[i], model, ctx, el, ctr || this);
- }
- return el;
- },
- prevObject: null,
- end: function() {
- return this.prevObject || this;
- },
- pushStack: function(nodes) {
- var next;
- next = jMask(nodes);
- next.prevObject = this;
- return next;
- },
- controllers: function() {
- if (this.components == null) {
- console.warn('Set was not rendered');
- }
- return this.pushStack(this.components || []);
- },
- mask: function(template) {
- if (arguments.length !== 0) {
- return this.empty().append(template);
- }
- return mask.stringify(this);
- },
-
- text: function(mix, ctx, ctr){
- if (typeof mix === 'string' && arguments.length === 1) {
- var node = [ new Dom.TextNode(mix) ];
-
- for(var i = 0, imax = this.length; i < imax; i++){
- this[i].nodes = node;
- }
- return this;
- }
-
- var str = '';
- for(var i = 0, imax = this.length; i < imax; i++){
- str += jmask_getText(this[i], mix, ctx, ctr);
- }
- return str;
- }
- };
-
- arr_each(['append', 'prepend'], function(method) {
-
- Proto[method] = function(mix) {
- var $mix = jMask(mix),
- i = 0,
- length = this.length,
- arr, node;
-
- for (; i < length; i++) {
- node = this[i];
- // we create each iteration a new array to prevent collisions in future manipulations
- arr = $mix.toArray();
-
- for (var j = 0, jmax = arr.length; j < jmax; j++) {
- arr[j].parent = node;
- }
-
- if (node.nodes == null) {
- node.nodes = arr;
- continue;
- }
-
- node.nodes = method === 'append' ? node.nodes.concat(arr) : arr.concat(node.nodes);
- }
-
- return this;
- };
-
- });
-
- arr_each(['appendTo'], function(method) {
-
- Proto[method] = function(mix, model, cntx, controller) {
-
- if (controller == null) {
- controller = this;
- }
-
- if (mix.nodeType != null && typeof mix.appendChild === 'function') {
- mix.appendChild(this.render(model, cntx, null, controller));
-
- _signal_emitIn(controller, 'domInsert');
- return this;
- }
-
- jMask(mix).append(this);
- return this;
- };
-
- });
-
- // end:source ../src/jmask/jmask.js
- // source ../src/jmask/manip.attr.js
- (function() {
- Proto.removeAttr = Proto.removeProp = function(key){
- return coll_each(this, function(node){
- node.attr[key] = null;
- });
- };
- Proto.attr = Proto.prop = function(mix, val){
- if (arguments.length === 1 && is_String(mix)) {
- return this.length !== 0 ? this[0].attr[mix] : null;
- }
- function asString(node, key, val){
- node.attr[key] = _mask_ensureTmplFn(val);
- }
- function asObject(node, obj){
- for(var key in obj){
- asString(node, key, obj[key]);
- }
- }
- var fn = is_String(mix) ? asString : asObject;
- return coll_each(this, function(node){
- fn(node, mix, val);
- });
- };
- Proto.tag = function(name) {
- if (arguments.length === 0)
- return this[0] && this[0].tagName;
-
- return coll_each(this, function(node){
- node.tagName = name;
- });
- };
- Proto.css = function(mix, val) {
- if (arguments.length <= 1 && typeof mix === 'string') {
- if (this.length == null)
- return null;
-
- var style = this[0].attr.style;
- if (style == null)
- return null;
-
- var obj = css_parseStyle(style);
- return mix == null ? obj : obj[mix];
- }
-
- if (mix == null)
- return this;
-
- var stringify = typeof mix === 'object'
- ? css_stringify
- : css_stringifyKeyVal ;
- var extend = typeof mix === 'object'
- ? obj_extend
- : css_extendKeyVal ;
-
- return coll_each(this, function(node){
- var style = node.attr.style;
- if (style == null) {
- node.attr.style = stringify(mix, val);
- return;
- }
- var css = css_parseStyle(style);
- extend(css, mix, val);
- node.attr.style = css_stringify(css);
- });
- };
-
- function css_extendKeyVal(css, key, val){
- css[key] = val;
- }
- function css_parseStyle(style) {
- var obj = {};
- style.split(';').forEach(function(x){
- if (x === '')
- return;
- var i = x.indexOf(':'),
- key = x.substring(0, i).trim(),
- val = x.substring(i + 1).trim();
- obj[key] = val;
- });
- return obj;
- }
- function css_stringify(css) {
- var str = '', key;
- for(key in css) {
- str += key + ':' + css[key] + ';';
- }
- return str;
- }
- function css_stringifyKeyVal(key, val){
- return key + ':' + val + ';';
- }
-
- }());
-
- // end:source ../src/jmask/manip.attr.js
- // source ../src/jmask/manip.class.js
- (function() {
- Proto.hasClass = function(klass){
- return coll_find(this, function(node){
- return has(node, klass);
- });
- };
- var Mutator_ = {
- add: function(node, klass){
- if (has(node, klass) === false)
- add(node, klass);
- },
- remove: function(node, klass){
- if (has(node, klass) === true)
- remove(node, klass);
- },
- toggle: function(node, klass){
- var fn = has(node, klass) === true ? remove : add;
- fn(node, klass);
- }
- };
- arr_each(['add', 'remove', 'toggle'], function(method) {
- var fn = Mutator_[method];
- Proto[method + 'Class'] = function(klass) {
- return coll_each(this, function(node){
- fn(node, klass);
- });
- };
- });
- function current(node){
- var className = node.attr['class'];
- return typeof className === 'string' ? className : '';
- }
- function has(node, klass){
- return -1 !== (' ' + current(node) + ' ').indexOf(' ' + klass + ' ');
- }
- function add(node, klass){
- node.attr['class'] = (current(node) + ' ' + klass).trim();
- }
- function remove(node, klass) {
- node.attr['class'] = (' ' + current(node) + ' ').replace(' ' + klass + ' ', '').trim();
- }
- }());
-
- // end:source ../src/jmask/manip.class.js
- // source ../src/jmask/manip.dom.js
- obj_extend(Proto, {
- clone: function(){
- return jMask(coll_map(this, jmask_clone));
- },
- wrap: function(wrapper){
- var $wrap = jMask(wrapper);
- if ($wrap.length === 0){
- log_warn('Not valid wrapper', wrapper);
- return this;
- }
- var result = coll_map(this, function(x){
- var node = $wrap.clone()[0];
- jmask_deepest(node).nodes = [ x ];
-
- if (x.parent != null) {
- var i = coll_indexOf(x.parent.nodes, x);
- if (i !== -1)
- x.parent.nodes.splice(i, 1, node);
- }
- return node
- });
- return jMask(result);
- },
- wrapAll: function(wrapper){
- var $wrap = jMask(wrapper);
- if ($wrap.length === 0){
- log_error('Not valid wrapper', wrapper);
- return this;
- }
- this.parent().mask($wrap);
- jmask_deepest($wrap[0]).nodes = this.toArray();
- return this.pushStack($wrap);
- }
- });
-
- arr_each(['empty', 'remove'], function(method) {
- Proto[method] = function(){
- return coll_each(this, Methods_[method]);
- };
- var Methods_ = {
- remove: function(node){
- if (node.parent != null)
- coll_remove(node.parent.nodes, node);
- },
- empty: function(node){
- node.nodes = null;
- }
- };
- });
-
- // end:source ../src/jmask/manip.dom.js
- // source ../src/jmask/traverse.js
- obj_extend(Proto, {
- each: function(fn, ctx) {
- for (var i = 0; i < this.length; i++) {
- fn.call(ctx || this, this[i], i)
- }
- return this;
- },
- eq: function(i) {
- return i === -1 ? this.slice(i) : this.slice(i, i + 1);
- },
- get: function(i) {
- return i < 0 ? this[this.length - i] : this[i];
- },
- slice: function() {
- return this.pushStack(Array.prototype.slice.apply(this, arguments));
- }
- });
-
-
- arr_each([
- 'filter',
- 'children',
- 'closest',
- 'parent',
- 'find',
- 'first',
- 'last'
- ], function(method) {
-
- Proto[method] = function(selector) {
- var result = [],
- matcher = selector == null
- ? null
- : selector_parse(selector, this.type, method === 'closest' ? 'up' : 'down'),
- i, x;
-
- switch (method) {
- case 'filter':
- return jMask(jmask_filter(this, matcher));
- case 'children':
- for (i = 0; i < this.length; i++) {
- x = this[i];
- if (x.nodes == null) {
- continue;
- }
- result = result.concat(matcher == null ? x.nodes : jmask_filter(x.nodes, matcher));
- }
- break;
- case 'parent':
- for (i = 0; i < this.length; i++) {
- x = this[i].parent;
- if (!x || x.type === Dom.FRAGMENT || (matcher && selector_match(x, matcher))) {
- continue;
- }
- result.push(x);
- }
- arr_unique(result);
- break;
- case 'closest':
- case 'find':
- if (matcher == null) {
- break;
- }
- for (i = 0; i < this.length; i++) {
- jmask_find(this[i][matcher.nextKey], matcher, result);
- }
- break;
- case 'first':
- case 'last':
- var index;
- for (i = 0; i < this.length; i++) {
-
- index = method === 'first' ? i : this.length - i - 1;
- x = this[index];
- if (matcher == null || selector_match(x, matcher)) {
- result[0] = x;
- break;
- }
- }
- break;
- }
-
- return this.pushStack(result);
- };
-
- });
-
- // end:source ../src/jmask/traverse.js
-
-
- jMask.prototype.fn = jMask.prototype;
- return jMask;
-
- }(Mask));
-
- // end:source /ref-mask-j/lib/jmask.embed.js
- // source /ref-mask-binding/lib/binding_embed
-
-
-
- (function(mask, Compo){
-
- // source vars
- var __Compo = typeof Compo !== 'undefined' ? Compo : (mask.Compo || global.Compo),
- __dom_addEventListener = __Compo.Dom.addEventListener,
- __registerHandler = mask.registerHandler,
- __registerAttr = mask.registerAttrHandler,
- __registerUtil = mask.registerUtil,
-
- domLib = __Compo.config.getDOMLibrary();
-
-
- // end:source vars
- // source utils/
- // source object
-
- // end:source object
- // source object_observe
- var obj_addObserver,
- obj_hasObserver,
- obj_removeObserver,
- obj_lockObservers,
- obj_unlockObservers,
- obj_ensureObserversProperty,
- obj_addMutatorObserver,
- obj_removeMutatorObserver
- ;
-
- (function(){
- obj_addObserver = function(obj, property, cb) {
- // closest observer
- var parts = property.split('.'),
- imax = parts.length,
- i = -1,
- x = obj;
- while ( ++i < imax ) {
- x = x[parts[i]];
-
- if (x == null)
- break;
-
- if (x[prop_OBS] != null) {
-
- var prop = parts.slice(i + 1).join('.');
- if (x[prop_OBS][prop] != null) {
-
- pushListener_(x, prop, cb);
-
- var cbs = pushListener_(obj, property, cb);
- if (cbs.length === 1) {
- var arr = parts.splice(0, i);
- if (arr.length !== 0)
- attachProxy_(obj, property, cbs, arr, true);
- }
- return;
- }
- }
- }
-
- var cbs = pushListener_(obj, property, cb);
- if (cbs.length === 1)
- attachProxy_(obj, property, cbs, parts, true);
-
- var val = obj_getProperty(obj, property),
- mutators = getSelfMutators(val);
- if (mutators != null) {
- objMutator_addObserver(
- val, mutators, cb
- );
- }
- };
-
- obj_hasObserver = function(obj, property, callback){
- // nested observer
- var parts = property.split('.'),
- imax = parts.length,
- i = -1,
- x = obj;
- while ( ++i < imax ) {
- x = x[parts[i]];
- if (x == null)
- break;
-
- if (x[prop_OBS] != null) {
- if (obj_hasObserver(x, parts.slice(i).join('.'), callback))
- return true;
-
- break;
- }
- }
-
- var obs = obj[prop_OBS];
- if (obs == null || obs[property] == null)
- return false;
-
- return arr_contains(obs[property], callback);
- };
-
- obj_removeObserver = function(obj, property, callback) {
- // nested observer
- var parts = property.split('.'),
- imax = parts.length,
- i = -1,
- x = obj;
- while ( ++i < imax ) {
- x = x[parts[i]];
- if (x == null)
- break;
-
- if (x[prop_OBS] != null) {
- obj_removeObserver(x, parts.slice(i).join('.'), callback);
- break;
- }
- }
-
-
- var obs = obj_ensureObserversProperty(obj, property),
- val = obj_getProperty(obj, property);
- if (callback === void 0) {
- // callback not provided -> remove all observers
- obs.length = 0;
- } else {
- arr_remove(obs, callback);
- }
-
- var mutators = getSelfMutators(val);
- if (mutators != null)
- objMutator_removeObserver(val, mutators, callback)
-
- };
- obj_lockObservers = function(obj) {
- var obs = obj[prop_OBS];
- if (obs != null)
- obs[prop_DIRTY] = {};
- };
- obj_unlockObservers = function(obj) {
- var obs = obj[prop_OBS],
- dirties = obs == null ? null : obs[prop_DIRTY];
- if (dirties == null)
- return;
-
- obs[prop_DIRTY] = null;
-
- var prop, cbs, val, imax, i;
- for(prop in dirties) {
- cbs = obj[prop_OBS][prop];
- imax = cbs == null ? 0 : cbs.length;
- if (imax === 0)
- continue;
-
- i = -1;
- val = prop === prop_MUTATORS
- ? obj
- : obj_getProperty(obj, prop)
- ;
- while ( ++i < imax ) {
- cbs[i](val);
- }
- }
- };
-
- obj_ensureObserversProperty = function(obj, type){
- var obs = obj[prop_OBS];
- if (obs == null) {
- obs = {
- __dirty: null,
- __dfrTimeout: null,
- __mutators: null
- };
- defineProp_(obj, '__observers', {
- value: obs,
- enumerable: false
- });
- }
- if (type == null)
- return obs;
-
- var arr = obs[type];
- return arr == null
- ? (obs[type] = [])
- : arr
- ;
- };
-
- obj_addMutatorObserver = function(obj, cb){
- var mutators = getSelfMutators(obj);
- if (mutators != null)
- objMutator_addObserver(obj, mutators, cb);
- };
- obj_removeMutatorObserver = function(obj, cb){
- objMutator_removeObserver(obj, null, cb);
- };
-
- // PRIVATE
- var prop_OBS = '__observers',
- prop_MUTATORS = '__mutators',
- prop_TIMEOUT = '__dfrTimeout',
- prop_DIRTY = '__dirty';
-
- var defineProp_ = Object.defineProperty;
-
-
- //Resolve object, or if property do not exists - create
- function ensureProperty_(obj, chain) {
- var i = -1,
- imax = chain.length - 1,
- key
- ;
- while ( ++i < imax ) {
- key = chain[i];
-
- if (obj[key] == null)
- obj[key] = {};
-
- obj = obj[key];
- }
- return obj;
- }
- function getSelfMutators(obj) {
- if (obj == null || typeof obj !== 'object')
- return null;
-
- if (typeof obj.length === 'number' && typeof obj.slice === 'function')
- return MUTATORS_.Array;
- if (typeof obj.toUTCString === 'function')
- return MUTATORS_.Date;
-
- return null;
- }
- var MUTATORS_ = {
- Array: {
- throttle: false,
- methods: [
- // native mutators
- 'push',
- 'unshift',
- 'splice',
- 'pop',
- 'shift',
- 'reverse',
- 'sort',
- // collection mutators
- 'remove'
- ]
- },
- Date: {
- throttle: true,
- methods: [
- 'setDate',
- 'setFullYear',
- 'setHours',
- 'setMilliseconds',
- 'setMinutes',
- 'setMonth',
- 'setSeconds',
- 'setTime',
- 'setUTCDate',
- 'setUTCFullYear',
- 'setUTCHours',
- 'setUTCMilliseconds',
- 'setUTCMinutes',
- 'setUTCMonth',
- 'setUTCSeconds',
- ]
- }
- };
- function attachProxy_(obj, property, cbs, chain) {
- var length = chain.length,
- parent = length > 1
- ? ensureProperty_(obj, chain)
- : obj,
- key = chain[length - 1],
- currentVal = parent[key];
-
- if (length > 1) {
- obj_defineCrumbs(obj, chain);
- }
-
-
- if ('length' === key) {
- var mutators = getSelfMutators(parent);
- if (mutators != null) {
- objMutator_addObserver(
- parent, mutators, function(){
- var imax = cbs.length,
- i = -1
- ;
- while ( ++i < imax ) {
- cbs[i].apply(null, arguments);
- }
- });
- return currentVal;
- }
-
- }
-
- defineProp_(parent, key, {
- get: function() {
- return currentVal;
- },
- set: function(x) {
- if (x === currentVal)
- return;
- var oldVal = currentVal;
-
- currentVal = x;
- var i = 0,
- imax = cbs.length,
- mutators = getSelfMutators(x);
-
-
- if (mutators != null) {
- for(; i < imax; i++) {
- objMutator_addObserver(
- x, mutators, cbs[i]
- );
- }
- }
-
- if (obj[prop_OBS][prop_DIRTY] != null) {
- obj[prop_OBS][prop_DIRTY][property] = 1;
- return;
- }
-
- for (i = 0; i < imax; i++) {
- cbs[i](x);
- }
-
- obj_sub_notifyListeners(obj, property, oldVal)
- },
- configurable: true,
- enumerable : true
- });
-
- return currentVal;
- }
-
- function obj_defineCrumbs(obj, chain) {
- var rebinder = obj_crumbRebindDelegate(obj),
- path = '',
- key;
-
- var imax = chain.length - 1,
- i = 0;
- for(; i < imax; i++) {
- key = chain[i];
- path += key + '.';
-
- obj_defineCrumb(path, obj, key, rebinder);
- obj = obj[key];
- }
- }
-
- function obj_defineCrumb(path, obj, key, rebinder) {
-
- var value = obj[key],
- old;
-
- defineProp_(obj, key, {
- get: function() {
- return value;
- },
- set: function(x) {
- if (x === value)
- return;
-
- old = value;
- value = x;
- rebinder(path, old);
- },
- configurable: true,
- enumerable : true
- });
- }
- function obj_sub_notifyListeners(obj, path, oldVal) {
- var obs = obj[prop_OBS];
- if (obs == null)
- return;
- for(var prop in obs) {
- if (prop.indexOf(path + '.') !== 0)
- continue;
-
- var cbs = obs[prop].slice(0),
- imax = cbs.length,
- i = 0, oldProp, cb;
- if (imax === 0)
- continue;
-
- var val = obj_getProperty(obj, prop);
- for (i = 0; i < imax; i++) {
- cb = cbs[i];
- obj_removeObserver(obj, prop, cb);
-
- if (oldVal != null && typeof oldVal === 'object') {
- oldProp = prop.substring(path.length + 1);
- obj_removeObserver(oldVal, oldProp, cb);
- }
- }
- for (i = 0; i < imax; i++){
- cbs[i](val);
- }
- for (i = 0; i < imax; i++){
- obj_addObserver(obj, prop, cbs[i]);
- }
- }
- }
-
- function obj_crumbRebindDelegate(obj) {
- return function(path, oldValue){
- obj_crumbRebind(obj, path, oldValue);
- };
- }
- function obj_crumbRebind(obj, path, oldValue) {
- var obs = obj[prop_OBS];
- if (obs == null)
- return;
-
- for (var prop in obs) {
- if (prop.indexOf(path) !== 0)
- continue;
-
- var cbs = obs[prop].slice(0),
- imax = cbs.length,
- i = 0;
-
- if (imax === 0)
- continue;
-
- var val = obj_getProperty(obj, prop),
- cb, oldProp;
-
- for (i = 0; i < imax; i++) {
- cb = cbs[i];
- obj_removeObserver(obj, prop, cb);
-
- if (oldValue != null && typeof oldValue === 'object') {
- oldProp = prop.substring(path.length);
- obj_removeObserver(oldValue, oldProp, cb);
- }
- }
- for (i = 0; i < imax; i++){
- cbs[i](val);
- }
-
- for (i = 0; i < imax; i++){
- obj_addObserver(obj, prop, cbs[i]);
- }
- }
- }
-
- // Create Collection - Check If Exists - Add Listener
- function pushListener_(obj, property, cb) {
- var obs = obj_ensureObserversProperty(obj, property);
- if (arr_contains(obs, cb) === false)
- obs.push(cb);
- return obs;
- }
-
- var objMutator_addObserver,
- objMutator_removeObserver;
- (function(){
- objMutator_addObserver = function(obj, mutators, cb){
- var methods = mutators.methods,
- throttle = mutators.throttle,
- obs = obj_ensureObserversProperty(obj, prop_MUTATORS);
- if (obs.length === 0) {
- var imax = methods.length,
- i = -1,
- method, fn;
- while( ++i < imax ){
- method = methods[i];
- fn = obj[method];
- if (fn == null)
- continue;
-
- obj[method] = objMutator_createWrapper_(
- obj
- , fn
- , method
- , throttle
- );
- }
- }
- obs[obs.length++] = cb;
- };
- objMutator_removeObserver = function(obj, mutators, cb){
- var obs = obj_ensureObserversProperty(obj, prop_MUTATORS);
- if (cb === void 0) {
- obs.length = 0;
- return;
- }
- arr_remove(obs, cb);
- };
-
- function objMutator_createWrapper_(obj, originalFn, method, throttle) {
- var fn = throttle === true ? callDelayed : call;
- return function() {
- return fn(
- obj,
- originalFn,
- method,
- _Array_slice.call(arguments)
- );
- };
- }
- function call(obj, original, method, args) {
- var cbs = obj_ensureObserversProperty(obj, prop_MUTATORS),
- result = original.apply(obj, args);
-
- tryNotify(obj, cbs, method, args, result);
- return result;
- }
- function callDelayed(obj, original, method, args) {
- var cbs = obj_ensureObserversProperty(obj, prop_MUTATORS),
- result = original.apply(obj, args);
-
- var obs = obj[prop_OBS];
- if (obs[prop_TIMEOUT] != null)
- return result;
-
- obs[prop_TIMEOUT] = setTimeout(function(){
- obs[prop_TIMEOUT] = null;
- tryNotify(obj, cbs, method, args, result);
- });
- return result;
- }
-
- function tryNotify(obj, cbs, method, args, result){
- if (cbs.length === 0)
- return;
-
- var obs = obj[prop_OBS];
- if (obs[prop_DIRTY] != null) {
- obs[prop_DIRTY][prop_MUTATORS] = 1;
- return;
- }
- var imax = cbs.length,
- i = -1,
- x;
- while ( ++i < imax ){
- x = cbs[i];
- if (typeof x === 'function') {
- x(obj, method, args, result);
- }
- }
- }
- }());
-
- }());
- // end:source object_observe
- // source date
- var date_ensure;
- (function(){
- date_ensure = function(val){
- if (val == null || val === '')
- return null;
-
- var date = val;
- var type = typeof val;
- if (type === 'string') {
- date = new Date(val);
-
- if (rgx_es5Date.test(date) && val.indexOf('Z') === -1) {
- // adjust to local time (http://es5.github.io/x15.9.html#x15.9.1.15)
- val.setMinutes(val.getTimezoneOffset());
- }
- }
- if (type === 'number') {
- date = new Date(val);
- }
-
- return isNaN(date) === false && typeof date.getFullYear === 'function'
- ? date
- : null
- ;
- };
-
- var rgx_es5Date = /^\d{4}\-\d{2}/;
- }());
- // end:source date
- // source dom
-
- function dom_removeElement(node) {
- return node.parentNode.removeChild(node);
- }
-
- function dom_removeAll(array) {
- if (array == null)
- return;
-
- var imax = array.length,
- i = -1;
- while ( ++i < imax ) {
- dom_removeElement(array[i]);
- }
- }
-
- function dom_insertAfter(element, anchor) {
- return anchor.parentNode.insertBefore(element, anchor.nextSibling);
- }
-
- function dom_insertBefore(element, anchor) {
- return anchor.parentNode.insertBefore(element, anchor);
- }
-
-
-
-
- // end:source dom
- // source compo
- var compo_fragmentInsert,
- compo_render,
- compo_dispose,
- compo_inserted,
- compo_attachDisposer,
- compo_trav_children,
- compo_getScopeFor
- ;
- (function(){
-
- compo_fragmentInsert = function(compo, index, fragment, placeholder) {
- if (compo.components == null)
- return dom_insertAfter(fragment, placeholder || compo.placeholder);
-
- var compos = compo.components,
- anchor = null,
- insertBefore = true,
- imax = compos.length,
- i = index - 1,
- elements;
-
- if (anchor == null) {
- while (++i < imax) {
- elements = compos[i].elements;
-
- if (elements && elements.length) {
- anchor = elements[0];
- break;
- }
- }
- }
- if (anchor == null) {
- insertBefore = false;
- i = index < imax
- ? index
- : imax
- ;
- while (--i > -1) {
- elements = compos[i].elements;
- if (elements && elements.length) {
- anchor = elements[elements.length - 1];
- break;
- }
- }
- }
- if (anchor == null)
- anchor = placeholder || compo.placeholder;
-
- if (insertBefore)
- return dom_insertBefore(fragment, anchor);
-
- return dom_insertAfter(fragment, anchor);
- };
-
- compo_render = function(parentCtr, template, model, ctx, container) {
- return mask.render(template, model, ctx, container, parentCtr);
- };
-
- compo_dispose = function(compo, parent) {
- if (compo == null)
- return false;
-
- if (compo.elements != null) {
- dom_removeAll(compo.elements);
- compo.elements = null;
- }
- __Compo.dispose(compo);
-
- var compos = (parent && parent.components) || (compo.parent && compo.parent.components);
- if (compos == null) {
- log_error('Parent Components Collection is undefined');
- return false;
- }
- return arr_remove(compos, compo);
- };
-
- compo_inserted = function(compo) {
- __Compo.signal.emitIn(compo, 'domInsert');
- };
-
- compo_attachDisposer = function(ctr, disposer) {
- if (typeof ctr.dispose === 'function') {
- var previous = ctr.dispose;
- ctr.dispose = function(){
- disposer.call(this);
- previous.call(this);
- };
-
- return;
- }
- ctr.dispose = disposer;
- };
-
- compo_trav_children = function(compo, compoName){
- var out = [],
- arr = compo.components || [],
- imax = arr.length,
- i = -1;
-
- while ( ++i < imax ){
- if (arr[i].compoName === compoName) {
- out.push(arr[i]);
- }
- }
- return out;
- };
-
- compo_getScopeFor = function(ctr, path){
- var key = path;
- var i = path.indexOf('.');
- if (i !== -1) {
- key = path.substring(0, i);
- }
- while (ctr != null) {
- if (ctr.scope != null && ctr.scope.hasOwnProperty(key)) {
- return ctr.scope;
- }
- ctr = ctr.parent;
- }
- return null;
- };
- }());
- // end:source compo
- // source expression
- var expression_eval,
- expression_eval_strict,
- expression_bind,
- expression_unbind,
- expression_createBinder,
- expression_createListener,
-
- expression_parse,
- expression_varRefs
- ;
-
- (function(){
- var Expression = mask.Utils.Expression;
-
- expression_eval_strict = Expression.eval;
- expression_parse = Expression.parse;
- expression_varRefs = Expression.varRefs;
-
- expression_eval = function(expr, model, ctx, ctr){
- if (expr === '.')
- return model;
-
- var x = expression_eval_strict(expr, model, ctx, ctr);
- return x == null ? '' : x;
- };
-
- expression_bind = function(expr, model, ctx, ctr, callback) {
- if (expr === '.') {
- if (model != null) {
- obj_addMutatorObserver(model, callback);
- }
- return;
- }
-
- var ast = expression_parse(expr),
- vars = expression_varRefs(ast, model, ctx, ctr),
- obj, ref;
-
- if (vars == null)
- return;
-
- if (typeof vars === 'string') {
- _toggleObserver(obj_addObserver, model, ctr, vars, callback);
- return;
- }
-
- var isArray = vars.length != null && typeof vars.splice === 'function',
- imax = isArray === true ? vars.length : 1,
- i = 0,
- x, prop;
-
- for (; i < imax; i++) {
- x = isArray === true ? vars[i] : vars;
- _toggleObserver(obj_addObserver, model, ctr, x, callback);
- }
- };
-
- expression_unbind = function(expr, model, ctr, callback) {
-
- if (typeof ctr === 'function')
- log_warn('[mask.binding] - expression unbind(expr, model, controller, callback)');
-
- if (expr === '.') {
- if (model != null) {
- obj_removeMutatorObserver(model, callback);
- }
- return;
- }
-
- var vars = expression_varRefs(expr, model, null, ctr),
- x, ref;
-
- if (vars == null)
- return;
-
- if (typeof vars === 'string') {
- _toggleObserver(obj_removeObserver, model, ctr, vars, callback);
- return;
- }
-
- var isArray = vars.length != null && typeof vars.splice === 'function',
- imax = isArray === true ? vars.length : 1,
- i = 0,
- x;
-
- for (; i < imax; i++) {
- x = isArray === true ? vars[i] : vars;
- _toggleObserver(obj_removeObserver, model, ctr, x, callback);
- }
-
- }
-
- /**
- * expression_bind only fires callback, if some of refs were changed,
- * but doesnt supply new expression value
- **/
- expression_createBinder = function(expr, model, cntx, controller, callback) {
- var locks = 0;
- return function binder() {
- if (++locks > 1) {
- locks = 0;
- log_warn(' Concurent binder detected', expr);
- return;
- }
-
- var value = expression_eval(expr, model, cntx, controller);
- if (arguments.length > 1) {
- var args = _Array_slice.call(arguments);
-
- args[0] = value;
- callback.apply(this, args);
-
- } else {
-
- callback(value);
- }
-
- locks--;
- };
- };
-
- expression_createListener = function(callback){
- var locks = 0;
- return function(){
- if (++locks > 1) {
- locks = 0;
- log_warn(' concurent binder');
- return;
- }
-
- callback();
- locks--;
- }
- };
-
- function _toggleObserver(mutatorFn, model, ctr, accessor, callback) {
- if (accessor == null)
- return;
-
- if (typeof accessor === 'object') {
- var obj = expression_eval_strict(accessor.accessor, model, null, ctr);
- if (obj == null || typeof obj !== 'object') {
- console.error('Binding failed to an object over accessor', accessor.ref);
- return;
- }
- mutatorFn(obj, accessor.ref, callback);
- return;
- }
-
- // string;
- var property = accessor,
- parts = property.split('.'),
- imax = parts.length;
-
- if (imax > 1) {
- var first = parts[0];
- if (first === '$c' || first === '$') {
- if (parts[1] === 'attr') {
- return;
- }
- // Controller Observer
- var owner = _getObservable_Controller(ctr, parts.slice(1), imax - 1);
- var cutIdx = first.length + 1;
- mutatorFn(owner, property.substring(cutIdx), callback);
- return;
- }
- if (first === '$scope') {
- // Controller Observer
- var scope = _getObservable_Scope(ctr, parts[1]);
- var cutIdx = 6 + 1;
- mutatorFn(scope, property.substring(cutIdx), callback);
- return;
- }
- if ('$a' === first || '$ctx' === first || '_' === first || '$u' === first)
- return;
- }
-
- var obj = null;
- if (_isDefined(model, parts, imax)) {
- obj = model;
- }
- if (obj == null) {
- obj = _getObservable_Scope(ctr, parts[0], imax);
- }
- if (obj == null) {
- obj = model;
- }
-
- mutatorFn(obj, property, callback);
- }
-
- function _getObservable_Scope_(ctr, parts, imax){
- var scope;
- while(ctr != null){
- scope = ctr.scope;
- if (scope != null && _isDefined(scope, parts, imax))
- return scope;
-
- ctr = ctr.parent;
- }
- return null;
- }
- function _getObservable_Controller(ctr_, parts, imax) {
- var ctr = ctr_;
- while(ctr != null){
- if (_isDefined(ctr, parts, imax))
- return ctr;
- ctr = ctr.parent;
- }
- return ctr;
- }
- function _getObservable_Scope(ctr_, property, imax) {
- var ctr = ctr_, scope;
- while(ctr != null){
- scope = ctr.scope;
- if (scope != null && scope[property] != null) {
- return scope;
- }
- ctr = ctr.parent;
- }
- return null;
- }
- function _isDefined(obj, parts, imax){
- if (obj == null)
- return false;
-
- var i = 0, val;
- for(; i < imax; i++) {
- obj = obj[parts[i]];
- if (obj == null)
- return false;
- }
- return true;
- }
-
-
- }());
-
-
-
- // end:source expression
- // source signal
- var signal_parse,
- signal_create
- ;
-
- (function(){
-
-
- signal_parse = function(str, isPiped, defaultType) {
- var signals = str.split(';'),
- set = [],
- i = 0,
- imax = signals.length,
- x,
- signalName, type,
- signal;
-
-
- for (; i < imax; i++) {
- x = signals[i].split(':');
-
- if (x.length !== 1 && x.length !== 2) {
- log_error('Too much ":" in a signal def.', signals[i]);
- continue;
- }
-
-
- type = x.length === 2 ? x[0] : defaultType;
- signalName = x[x.length === 2 ? 1 : 0];
-
- signal = signal_create(signalName.trim(), type, isPiped);
-
- if (signal != null) {
- set.push(signal);
- }
- }
-
- return set;
- };
-
-
- signal_create = function(signal, type, isPiped) {
- if (isPiped !== true) {
- return {
- signal: signal,
- type: type
- };
- }
-
- var index = signal.indexOf('.');
- if (index === -1) {
- log_error('No pipe name in a signal', signal);
- return null;
- }
-
- return {
- signal: signal.substring(index + 1),
- pipe: signal.substring(0, index),
- type: type
- };
- };
- }());
-
- // end:source signal
- // end:source utils/
-
- // source DomObjectTransport
- var DomObjectTransport;
- (function(){
-
- var objectWay = {
- get: function(provider, expression) {
- var getter = provider.objGetter;
- if (getter == null) {
- return expression_eval(
- expression
- , provider.model
- , provider.ctx
- , provider.ctr
- );
- }
-
- var obj = getAccessorObject_(provider, getter);
- if (obj == null)
- return null;
-
- return obj[getter](expression, provider.model, provider.ctr.parent);
- },
- set: function(obj, property, value, provider) {
- var setter = provider.objSetter;
- if (setter == null) {
- obj_setProperty(obj, property, value);
- return;
- }
- var ctx = getAccessorObject_(provider, setter);
- if (ctx == null)
- return;
-
- ctx[setter](
- property
- , value
- , provider.model
- , provider.ctr.parent
- );
- }
- };
- var domWay = {
- get: function(provider) {
- var getter = provider.domGetter;
- if (getter == null) {
- return obj_getProperty(provider, provider.property);
- }
- var ctr = provider.ctr.parent;
- if (isValidFn_(ctr, getter, 'Getter') === false) {
- return null;
- }
- return ctr[getter](provider.element);
- },
- set: function(provider, value) {
- var setter = provider.domSetter;
- if (setter == null) {
- obj_setProperty(provider, provider.property, value);
- return;
- }
- var ctr = provider.ctr.parent;
- if (isValidFn_(ctr, setter, 'Setter') === false) {
- return;
- }
- ctr[setter](value, provider.element);
- }
- };
- var DateTimeDelegate = {
- domSet: function(format){
- return function(prov, val){
- var date = date_ensure(val);
- prov.element.value = date == null ? '' : format(date);
- }
- },
- objSet: function(extend){
- return function(obj, prop, val){
-
- var date = date_ensure(val);
- if (date == null)
- return;
-
- var target = obj_getProperty(obj, prop);
- if (target == null) {
- obj_setProperty(obj, prop, date);
- return;
- }
- if (target.getFullYear == null || isNaN(target)) {
- target = date_ensure(target) || date;
- extend(target, date);
- obj_setProperty(obj, prop, target);
- return;
- }
- extend(target, date);
- }
- }
- };
-
- DomObjectTransport = {
- // generic
- objectWay: objectWay,
- domWay: domWay,
-
- SELECT: {
- get: function(provider) {
- var el = provider.element,
- i = el.selectedIndex;
- if (i === -1)
- return '';
-
- var opt = el.options[i],
- val = opt.getAttribute('value');
- return val == null
- ? opt.getAttribute('name') /* obsolete */
- : val
- ;
- },
- set: function(provider, val) {
- var el = provider.element,
- options = el.options,
- imax = options.length,
- opt, x, i;
- for(i = 0; i < imax; i++){
- opt = options[i];
- x = opt.getAttribute('value');
- if (x == null)
- x = opt.getAttribute('name');
-
- /* jshint eqeqeq: false */
- if (x == val) {
- /* jshint eqeqeq: true */
- el.selectedIndex = i;
- return;
- }
- }
- log_warn('Value is not an option', val);
- }
- },
- SELECT_MULT: {
- get: function(provider) {
- return coll_map(provider.element.selectedOptions, function(x){
- return x.value;
- });
- },
- set: function(provider, mix) {
- coll_each(provider.element.options, function(el){
- el.selected = false;
- });
- if (mix == null) {
- return;
- }
- var arr = is_ArrayLike(mix) ? mix : [ mix ];
- coll_each(arr, function(val){
- var els = provider.element.options,
- imax = els.length,
- i = -1;
- while (++i < imax) {
- /* jshint eqeqeq: false */
- if (els[i].value == val) {
- els[i].selected = true;
- }
- }
- log_warn('Value is not an option', val);
- });
- }
- },
- DATE: {
- domWay: {
- get: domWay.get,
- set: function(prov, val){
- var date = date_ensure(val);
- prov.element.value = date == null ? '' : formatDate(date);
- }
- },
- objectWay: {
- get: objectWay.get,
- set: DateTimeDelegate.objSet(function(a, b){
- a.setFullYear(b.getFullYear());
- a.setMonth(b.getMonth());
- a.setDate(b.getDate());
- })
- }
- },
- TIME: {
- domWay: {
- get: domWay.get,
- set: DateTimeDelegate.domSet(formatTime)
- },
- objectWay: {
- get: objectWay.get,
- set: DateTimeDelegate.objSet(function(a, b){
- a.setHours(b.getHours())
- a.setMinutes(b.getMinutes());
- a.setSeconds(b.getSeconds());
- })
- }
- },
- RADIO: {
- domWay: {
- get: function(provider){
- var el = provider.element;
- return el.checked ? el.value : null;
- },
- set: function(provider, value){
- var el = provider.element;
- el.checked = el.value === value;
- }
- },
- }
-
- };
-
- function isValidFn_(obj, prop, name) {
- if (obj== null || typeof obj[prop] !== 'function') {
- log_error('BindingProvider. Controllers accessor.', name, 'should be a function. Property:', prop);
- return false;
- }
- return true;
- }
- function getAccessorObject_(provider, accessor) {
- var ctr = provider.ctr.parent;
- if (ctr[accessor] != null)
- return ctr;
- var model = provider.model;
- if (model[accessor] != null)
- return model;
-
- log_error('BindingProvider. Accessor `', accessor, '`should be a function');
- return null;
- }
- function formatDate(date) {
- var YYYY = date.getFullYear(),
- MM = date.getMonth() + 1,
- DD = date.getDate();
- return YYYY
- + '-'
- + (MM < 10 ? '0' : '')
- + (MM)
- + '-'
- + (DD < 10 ? '0' : '')
- + (DD)
- ;
- }
- function formatTime(date) {
- var H = date.getHours(),
- M = date.getMinutes();
- return H
- + ':'
- + (M < 10 ? '0' : '')
- + (M)
- ;
- }
- }());
-
- // end:source DomObjectTransport
- // source ValidatorProvider
- var ValidatorProvider,
- Validators;
- (function() {
- var class_INVALID = '-validate__invalid';
-
- ValidatorProvider = {
- getFnFromModel: fn_fromModelWrapp,
- getFnByName: fn_byName,
- validate: validate,
- validateUi: function(fns, val, ctr, el, oncancel) {
- var error = validate(fns, val, ctr);
- if (error != null) {
- ui_notifyInvalid(el, error, oncancel);
- return error;
- }
- ui_clearInvalid(el);
- return null;
- }
- };
-
- function validate(fns, val, ctr) {
- if (fns == null) {
- return null;
- }
- var imax = fns.length,
- i = -1,
- error, fn;
- while ( ++i < imax ){
- fn = fns[i];
- if (fn == null) {
- continue;
- }
- error = fn(val, ctr);
- if (error != null) {
- if (is_String(error)) {
- return {
- message: error,
- actual: val
- };
- }
- if (error.actual == null) {
- error.actual = val;
- }
- return error;
- }
- }
- }
-
- function fn_fromModel(model, prop) {
- if (is_Object(model) === false) {
- return null;
- }
- var Validate = model.Validate;
- if (Validate != null) {
- var fn = null;
- if (is_Function(fn = Validate)) {
- return fn;
- }
- if (is_Function(fn = Validate[prop])) {
- return fn;
- }
- }
-
- var i = prop.indexOf('.');
- if (i !== -1) {
- return fn_fromModel(
- model[prop.substring(0, i)], prop.substring(i+1)
- );
- }
- return null;
- }
- function fn_fromModelWrapp(model, prop) {
- var fn = fn_fromModel(model, prop);
- if (fn == null) {
- return null;
- }
- return function(){
- var mix = fn.apply(model, arguments),
- message, error;
- if (mix == null) {
- return null;
- }
- if (is_String(mix)) {
- return {
- message: mix,
- property: prop,
- ctx: model
- };
- }
- mix.property = prop;
- mix.ctx = model;
- return mix;
- };
- }
-
- function fn_byName(name, param, message) {
- var Delegate = Validators[name];
- if (Delegate == null) {
- log_error('Invalid validator', name, 'Supports:', Object.keys(Validators));
- return null;
- }
- var fn = Delegate(param);
- return function(val, ctr){
- var mix = fn(val, ctr);
- if (mix == null || mix === true) {
- return null;
- }
- if (mix === false) {
- return message || ('Check failed: `' + name + '`');
- }
- if (is_String(mix) && mix.length !== 0) {
- return mix;
- }
- return null;
- };
- }
-
- function ui_notifyInvalid(el, error, oncancel) {
-
- var message = error.message || error;
- var next = domLib(el).next('.' + class_INVALID);
- if (next.length === 0) {
- next = domLib('')
- .addClass(class_INVALID)
- .html('
⊗ ')
- .insertAfter(el);
- }
-
- return next
- .children('button')
- .off()
- .on('click', function() {
- next.hide();
- oncancel && oncancel();
-
- })
- .end()
- .children('span').text(message)
- .end()
- .show();
- }
-
- function ui_clearInvalid(el) {
- return domLib(el).next('.' + class_INVALID).hide();
- }
-
- Validators = {
- match: function (match) {
- return function (str){
- return new RegExp(match).test(str);
- };
- },
- unmatch: function (unmatch) {
- return function (str){
- return !(new RegExp(unmatch).test(str));
- };
- },
- minLength: function (min) {
- return function (str){
- return str.length >= parseInt(min, 10);
- };
- },
- maxLength: function (max) {
- return function (str){
- return str.length <= parseInt(max, 10);
- };
- },
- check: function (condition, node){
- return function (str){
- return expression_eval('x' + condition, node.model, {x: str}, node);
- };
- }
- };
- }());
- // end:source ValidatorProvider
- // source BindingProvider
- var CustomProviders,
- BindingProvider;
- (function() {
- CustomProviders = {};
-
- BindingProvider = class_create({
- validations: null,
- constructor: function BindingProvider(model, element, ctr, bindingType) {
- if (bindingType == null) {
- bindingType = 'dual';
-
- var name = ctr.compoName;
- if (name === ':bind' || name === 'bind') {
- bindingType = 'single';
- }
- }
-
- var attr = ctr.attr,
- type;
-
- this.node = ctr; // backwards compat.
- this.ctr = ctr;
- this.ctx = null;
-
- this.model = model;
- this.element = element;
- this.value = attr.value;
- this.property = attr.property;
- this.domSetter = attr.setter || attr['dom-setter'];
- this.domGetter = attr.getter || attr['dom-getter'];
- this.objSetter = attr['obj-setter'];
- this.objGetter = attr['obj-getter'];
-
- /* Convert to an instance, e.g. Number, on domchange event */
- this['typeof'] = attr['typeof'] || null;
-
- this.dismiss = 0;
- this.bindingType = bindingType;
- this.log = false;
- this.signal_domChanged = null;
- this.signal_objectChanged = null;
- this.locked = false;
-
-
- if (this.property == null && this.domGetter == null) {
-
- switch (element.tagName) {
- case 'INPUT':
- type = element.getAttribute('type');
- if ('checkbox' === type) {
- this.property = 'element.checked';
- break;
- }
- else if ('date' === type) {
- var x = DomObjectTransport.DATE;
- this.domWay = x.domWay;
- this.objectWay = x.objectWay;
- }
- else if ('number' === type) {
- this['typeof'] = 'Number';
- }
- else if ('radio' === type) {
- var x = DomObjectTransport.RADIO;
- this.domWay = x.domWay;
- break;
- }
-
- this.property = 'element.value';
- break;
- case 'TEXTAREA':
- this.property = 'element.value';
- break;
- case 'SELECT':
- this.domWay = element.multiple
- ? DomObjectTransport.SELECT_MULT
- : DomObjectTransport.SELECT;
- break;
- default:
- this.property = 'element.innerHTML';
- break;
- }
- }
-
- if (attr['log']) {
- this.log = true;
- if (attr.log !== 'log') {
- this.logExpression = attr.log;
- }
- }
-
- // Send signal on OBJECT or DOM change
- if (attr['x-signal']) {
- var signal = signal_parse(attr['x-signal'], null, 'dom')[0],
- signalType = signal && signal.type;
-
- switch(signalType){
- case 'dom':
- case 'object':
- this['signal_' + signalType + 'Changed'] = signal.signal;
- break;
- default:
- log_error('Signal typs is not supported', signal);
- break;
- }
- }
-
- // Send PIPED signal on OBJECT or DOM change
- if (attr['x-pipe-signal']) {
- var signal = signal_parse(attr['x-pipe-signal'], true, 'dom')[0],
- signalType = signal && signal.type;
-
- switch(signalType){
- case 'dom':
- case 'object':
- this['pipe_' + signalType + 'Changed'] = signal;
- break;
- default:
- log_error('Pipe type is not supported');
- break;
- }
- }
-
- var domSlot = attr['dom-slot'];
- if (domSlot != null) {
- this.slots = {};
- // @hack - place dualb. provider on the way of a signal
- //
- var parent = ctr.parent,
- newparent = parent.parent;
-
- parent.parent = this;
- this.parent = newparent;
- this.slots[domSlot] = function(sender, value){
- this.domChanged(sender, value);
- };
- }
-
- /*
- * @obsolete: attr name : 'x-pipe-slot'
- */
- var pipeSlot = attr['object-pipe-slot'] || attr['x-pipe-slot'];
- if (pipeSlot) {
- var str = pipeSlot,
- index = str.indexOf('.'),
- pipeName = str.substring(0, index),
- signal = str.substring(index + 1);
-
- this.pipes = {};
- this.pipes[pipeName] = {};
- this.pipes[pipeName][signal] = function(){
- this.objectChanged();
- };
-
- __Compo.pipe.addController(this);
- }
-
-
- if (attr.expression) {
- this.expression = attr.expression;
- if (this.value == null && bindingType !== 'single') {
- var refs = expression_varRefs(this.expression);
- if (typeof refs === 'string') {
- this.value = refs;
- } else {
- log_warn('Please set value attribute in DualBind Control.');
- }
- }
- return;
- }
-
- this.expression = this.value;
- },
- dispose: function() {
- expression_unbind(this.expression, this.model, this.ctr, this.binder);
- },
- objectChanged: function(x) {
- if (this.dismiss-- > 0) {
- return;
- }
- if (this.locked === true) {
- log_warn('Concurance change detected', this);
- return;
- }
- this.locked = true;
-
- if (x == null) {
- x = this.objectWay.get(this, this.expression);
- }
-
- this.domWay.set(this, x);
-
- if (this.log) {
- console.log('[BindingProvider] objectChanged -', x);
- }
- if (this.signal_objectChanged) {
- signal_emitOut(this.ctr, this.signal_objectChanged, [x]);
- }
- if (this.pipe_objectChanged) {
- var pipe = this.pipe_objectChanged;
- __Compo.pipe(pipe.pipe).emit(pipe.signal);
- }
-
- this.locked = false;
- },
- domChanged: function(event, value) {
- if (this.locked === true) {
- log_warn('Concurance change detected', this);
- return;
- }
- this.locked = true;
-
- if (value == null)
- value = this.domWay.get(this);
-
- var typeof_ = this['typeof'];
- if (typeof_ != null) {
- var Converter = window[typeof_];
- value = Converter(value);
- }
-
- var error = this.validate(value);
- if (error == null) {
- this.dismiss = 1;
- var obj = this.model;
- var prop = this.value;
- if (prop.charCodeAt(0) === 36 /*$*/) {
- var i = prop.indexOf('.');
- if (i !== -1) {
- var key = prop.substring(0, i);
- if (key === '$scope') {
- prop = prop.substring(i + 1);
- obj = compo_getScopeFor(this.ctr.parent, prop);
- }
- }
- }
-
- this.objectWay.set(obj, prop, value, this);
- this.dismiss = 0;
-
- if (this.log) {
- console.log('[BindingProvider] domChanged -', value);
- }
- if (this.signal_domChanged != null) {
- signal_emitOut(this.ctr, this.signal_domChanged, [value]);
- }
- if (this.pipe_domChanged != null) {
- var pipe = this.pipe_domChanged;
- __Compo.pipe(pipe.pipe).emit(pipe.signal);
- }
- }
- this.locked = false;
- },
- addValidation: function(mix){
- if (this.validations == null) {
- this.validations = [];
- }
- if (is_Array(mix)) {
- this.validations = this.validations.concat(mix);
- return;
- }
- this.validations.push(mix);
- },
- validate: function (val) {
- var fns = this.validations,
- ctr = this.ctr,
- el = this.element
- ;
- if (fns == null || fns.length === 0) {
- return null;
- }
- var val_ = arguments.length !== 0
- ? val
- : this.domWay.get(this);
-
- return ValidatorProvider.validateUi(
- fns, val_, ctr, el, this.objectChanged.bind(this)
- );
- },
- objectWay: DomObjectTransport.objectWay,
- domWay: DomObjectTransport.domWay,
- });
-
-
- obj_extend(BindingProvider, {
- create: function (model, el, ctr, bindingType) {
-
- /* Initialize custom provider */
- var type = ctr.attr.bindingProvider,
- CustomProvider = type == null ? null : CustomProviders[type],
- provider;
-
- if (typeof CustomProvider === 'function') {
- return new CustomProvider(model, el, ctr, bindingType);
- }
-
- provider = new BindingProvider(model, el, ctr, bindingType);
-
- if (CustomProvider != null) {
- obj_extend(provider, CustomProvider);
- }
- return provider;
- },
-
- bind: function (provider){
- return apply_bind(provider);
- }
- });
-
- function apply_bind(provider) {
-
- var expr = provider.expression,
- model = provider.model,
- onObjChanged = provider.objectChanged = provider.objectChanged.bind(provider);
-
- provider.binder = expression_createBinder(expr, model, provider.ctx, provider.ctr, onObjChanged);
-
- expression_bind(expr, model, provider.ctx, provider.ctr, provider.binder);
-
- if (provider.bindingType === 'dual') {
- var attr = provider.ctr.attr;
-
- if (!attr['change-slot'] && !attr['change-pipe-event']) {
- var element = provider.element,
- /*
- * @obsolete: attr name : 'changeEvent'
- */
- eventType = attr['change-event'] || attr.changeEvent || 'change',
- onDomChange = provider.domChanged.bind(provider);
-
- __dom_addEventListener(element, eventType, onDomChange);
- }
-
-
- if (!provider.objectWay.get(provider, provider.expression)) {
- // object has no value, so check the dom
- setTimeout(function(){
- if (provider.domWay.get(provider))
- // and apply when exists
- provider.domChanged();
- });
- return provider;
- }
- }
-
- // trigger update
- provider.objectChanged();
- return provider;
- }
-
- function signal_emitOut(ctr, signal, args) {
- if (ctr == null)
- return;
-
- var slots = ctr.slots;
- if (slots != null && typeof slots[signal] === 'function') {
- if (slots[signal].apply(ctr, args) === false)
- return;
- }
-
- signal_emitOut(ctr.parent, signal, args);
- }
-
-
- obj_extend(BindingProvider, {
- addObserver: obj_addObserver,
- removeObserver: obj_removeObserver
- });
- }());
-
- // end:source BindingProvider
-
- // source handlers/
- // source visible
- /**
- * visible handler. Used to bind directly to display:X/none
- *
- * attr =
- * check - expression to evaluate
- * bind - listen for a property change
- */
-
- function VisibleHandler() {}
-
- __registerHandler(':visible', VisibleHandler);
-
-
- VisibleHandler.prototype = {
- constructor: VisibleHandler,
-
- refresh: function(model, container) {
- container.style.display = expression_eval(this.attr.check, model) ? '' : 'none';
- },
- renderStart: function(model, cntx, container) {
- this.refresh(model, container);
-
- if (this.attr.bind) {
- obj_addObserver(model, this.attr.bind, this.refresh.bind(this, model, container));
- }
- }
- };
-
- // end:source visible
- // source validate
- var ValidationCompo;
- (function() {
- var class_INVALID = '-validate-invalid';
-
- ValidationCompo = class_create({
- attr: null,
- element: null,
- validators: null,
-
- constructor: function(){
- this.validators = [];
- },
- renderStart: function(model, ctx, container) {
- this.element = container;
-
- var prop = this.attr.value;
- if (prop) {
- var fn = ValidatorProvider.getFnFromModel(model, prop);
- if (fn != null) {
- this.validators.push(fn);
- }
- }
- },
- /**
- * @param input - {control specific} - value to validate
- * @param element - {HTMLElement} - (optional, @default this.element) -
- * Invalid message is schown(inserted into DOM) after this element
- * @param oncancel - {Function} - Callback function for canceling
- * invalid notification
- */
- validate: function(val, el, oncancel) {
- var element = el == null ? this.element : el,
- value = val;
- if (arguments.length === 0) {
- value = obj_getProperty(this.model, this.attr.value);
- }
- if (this.validators.length === 0) {
- this.initValidators();
- }
- var fns = this.validators,
- type = this.attr.silent ? 'validate' : 'validateUi'
- ;
-
- return ValidatorProvider[type](
- fns, value, this, element, oncancel
- );
- },
- initValidators: function() {
- var attr = this.attr,
- message = this.attr.message,
- isDefault = message == null
-
- if (isDefault) {
- message = 'Invalid value of `' + this.attr.value + '`';
- }
- for (var key in attr) {
- switch (key) {
- case 'message':
- case 'value':
- case 'getter':
- case 'silent':
- continue;
- }
- if (key in Validators === false) {
- log_error('Unknown Validator:', key, this);
- continue;
- }
- var str = isDefault ? (message + ' Validation: `' + key + '`') : message
- var fn = ValidatorProvider.getFnByName(key, attr[key], str);
- if (fn != null) {
- this.validators.push(fn);
- }
- }
- }
- });
-
- __registerHandler(':validate', ValidationCompo);
-
- __registerHandler(':validate:message', Compo({
- template: 'div.' + class_INVALID + ' { span > "~[bind:message]" button > "~[cancel]" }',
-
- onRenderStart: function(model){
- if (typeof model === 'string') {
- model = {
- message: model
- };
- }
-
- if (!model.cancel) {
- model.cancel = 'cancel';
- }
-
- this.model = model;
- },
- compos: {
- button: '$: button',
- },
- show: function(message, oncancel){
- var that = this;
-
- this.model.message = message;
- this.compos.button.off().on(function(){
- that.hide();
- oncancel && oncancel();
-
- });
-
- this.$.show();
- },
- hide: function(){
- this.$.hide();
- }
- }));
-
- }());
-
- // end:source validate
- // source validate_group
- function ValidateGroup() {}
-
- __registerHandler(':validate:group', ValidateGroup);
-
-
- ValidateGroup.prototype = {
- constructor: ValidateGroup,
- validate: function() {
- var validations = getValidations(this);
-
-
- for (var i = 0, x, length = validations.length; i < length; i++) {
- x = validations[i];
- if (!x.validate()) {
- return false;
- }
- }
- return true;
- }
- };
-
- function getValidations(component, out){
- if (out == null){
- out = [];
- }
-
- if (component.components == null){
- return out;
- }
- var compos = component.components;
- for(var i = 0, x, length = compos.length; i < length; i++){
- x = compos[i];
-
- if (x.compoName === 'validate'){
- out.push(x);
- continue;
- }
-
- getValidations(x);
- }
- return out;
- }
-
- // end:source validate_group
-
-
-
- // if BROWSER
- // source bind
- /**
- * Mask Custom Tag Handler
- * attr =
- * attr: {String} - attribute name to bind
- * prop: {Stirng} - property name to bind
- * - : {default} - innerHTML
- */
-
-
-
- (function() {
-
- function Bind() {}
-
- __registerHandler(':bind', Bind);
- __registerHandler( 'bind', Bind);
-
- Bind.prototype = {
- constructor: Bind,
- renderEnd: function(els, model, cntx, container){
-
- this.provider = BindingProvider.create(model, container, this, 'single');
-
- BindingProvider.bind(this.provider);
- },
- dispose: function(){
- if (this.provider && typeof this.provider.dispose === 'function') {
- this.provider.dispose();
- }
- }
- };
-
-
- }());
-
- // end:source bind
- // source dualbind
- /**
- * Mask Custom Handler
- *
- * 2 Way Data Model binding
- *
- *
- * attr =
- * value: {string} - property path in object
- * ?property : {default} 'element.value' - value to get/set from/to HTMLElement
- * ?changeEvent: {default} 'change' - listen to this event for HTMLELement changes
- *
- * ?setter: {string} - setter function of a parent controller
- * ?getter: {string} - getter function of a parent controller
- *
- *
- */
-
- var DualbindCompo = class_create({
-
- renderEnd: function(elements, model, ctx, container) {
- this.provider = BindingProvider.create(model, container, this);
-
- var compos = this.components;
- if (compos != null) {
- var imax = compos.length,
- i = -1, x;
- while ( ++i < imax ){
- x = compos[i];
- if (x.compoName === ':validate') {
- this.provider.addValidation(x.validations);
- }
- }
- }
-
-
- if (this.attr['no-validation'] == null) {
- var fn = ValidatorProvider.getFnFromModel(model, this.provider.value);
- if (fn != null) {
- this.provider.addValidation(fn);
- }
- }
- BindingProvider.bind(this.provider);
- },
- dispose: function() {
- var dispose = this.provider && this.provider.dispose;
- if (dispose != null) {
- dispose.call(this.provider);
- }
- },
-
- validate: function(){
- return this.provider && this.provider.validate();
- },
-
- handlers: {
- attr: {
- 'x-signal': function() {}
- }
- }
- });
-
- __registerHandler(':dualbind', DualbindCompo);
- __registerHandler( 'dualbind', DualbindCompo);
- // end:source dualbind
- // endif
- // end:source handlers/
- // source utilities/
- // source bind
- /**
- * Mask Custom Utility - for use in textContent and attribute values
- */
- (function(){
-
- function attr_strReplace(attrValue, currentValue, newValue) {
- if (!attrValue)
- return newValue;
-
- if (currentValue == null || currentValue === '')
- return attrValue + ' ' + newValue;
-
- return attrValue.replace(currentValue, newValue);
- }
-
- function refresherDelegate_NODE(element){
- return function(value) {
- element.textContent = value;
- };
- }
- function refresherDelegate_ATTR(element, attrName, currentValue) {
- return function(value){
- var currentAttr = element.getAttribute(attrName),
- attr = attr_strReplace(currentAttr, currentValue, value);
-
- element.setAttribute(attrName, attr);
- currentValue = value;
- };
- }
- function refresherDelegate_PROP(element, attrName, currentValue) {
- return function(value){
- switch(typeof element[attrName]) {
- case 'boolean':
- currentValue = element[attrName] = !!value;
- return;
- case 'number':
- currentValue = element[attrName] = Number(value);
- return;
- case 'string':
- currentValue = element[attrName] = attr_strReplace(element[attrName], currentValue, value);
- return;
- default:
- log_warn('Unsupported elements property type', attrName);
- return;
- }
- };
- }
-
- function create_refresher(type, expr, element, currentValue, attrName) {
- if ('node' === type) {
- return refresherDelegate_NODE(element);
- }
- if ('attr' === type) {
- switch(attrName) {
- case 'value':
- case 'disabled':
- case 'checked':
- case 'selected':
- case 'selectedIndex':
- return refresherDelegate_PROP(element, attrName, currentValue);
- }
- return refresherDelegate_ATTR(element, attrName, currentValue);
- }
- throw Error('Unexpected binder type: ' + type);
- }
-
-
- function bind (current, expr, model, ctx, element, controller, attrName, type){
- var refresher = create_refresher(type, expr, element, current, attrName),
- binder = expression_createBinder(expr, model, ctx, controller, refresher);
-
- expression_bind(expr, model, ctx, controller, binder);
-
-
- compo_attachDisposer(controller, function(){
- expression_unbind(expr, model, controller, binder);
- });
- }
-
- __registerUtil('bind', {
- mode: 'partial',
- current: null,
- element: null,
- nodeRenderStart: function(expr, model, ctx, element, controller){
-
- var current = expression_eval(expr, model, ctx, controller);
-
- // though we apply value's to `this` context, but it is only for immediat use
- // in .node() function, as `this` context is a static object that share all bind
- // utils
- this.element = document.createTextNode(current);
-
- return (this.current = current);
- },
- node: function(expr, model, ctx, container, ctr){
- var el = this.element,
- val = this.current;
- bind(
- val
- , expr
- , model
- , ctx
- , el
- , ctr
- , null
- , 'node'
- );
- this.element = null;
- this.current = null;
- return el;
- },
-
- attrRenderStart: function(expr, model, ctx, element, controller){
- return (this.current = expression_eval(expr, model, ctx, controller));
- },
- attr: function(expr, model, ctx, element, controller, attrName){
- bind(
- this.current,
- expr,
- model,
- ctx,
- element,
- controller,
- attrName,
- 'attr');
-
- return this.current;
- }
- });
-
- }());
-
- // end:source bind
- // end:source utilities/
- // source attributes/
- // source xxVisible
-
-
- __registerAttr('xx-visible', function(node, attrValue, model, cntx, element, controller) {
-
- var binder = expression_createBinder(attrValue, model, cntx, controller, function(value){
- element.style.display = value ? '' : 'none';
- });
-
- expression_bind(attrValue, model, cntx, controller, binder);
-
- compo_attachDisposer(controller, function(){
- expression_unbind(attrValue, model, controller, binder);
- });
-
-
-
- if (!expression_eval(attrValue, model, cntx, controller)) {
-
- element.style.display = 'none';
- }
- });
- // end:source xxVisible
- // source xToggle
- /**
- * Toggle value with ternary operator on an event.
- *
- * button x-toggle='click: foo === "bar" ? "zet" : "bar" > 'Toggle'
- */
-
- __registerAttr('x-toggle', 'client', function(node, attrValue, model, ctx, element, controller){
-
-
- var event = attrValue.substring(0, attrValue.indexOf(':')),
- expression = attrValue.substring(event.length + 1),
- ref = expression_varRefs(expression);
-
- if (typeof ref !== 'string') {
- // assume is an array
- ref = ref[0];
- }
-
- __dom_addEventListener(element, event, function(){
- var value = expression_eval(expression, model, ctx, controller);
-
- obj_setProperty(model, ref, value);
- });
- });
-
- // end:source xToggle
- // source xClassToggle
- /**
- * Toggle Class Name
- *
- * button x-toggle='click: selected'
- */
-
- __registerAttr('x-class-toggle', 'client', function(node, attrVal, model, ctx, element){
-
- var event = attrVal.substring(0, attrVal.indexOf(':')),
- klass = attrVal.substring(event.length + 1).trim();
-
-
- __dom_addEventListener(element, event, function(){
- domLib(element).toggleClass(klass);
- });
- });
-
- // end:source xClassToggle
- // end:source attributes/
- // source statements/
- (function(){
- var custom_Statements = mask.getStatement();
-
- // source 1.utils.js
- var _getNodes,
- _renderElements,
- _renderPlaceholder,
- _compo_initAndBind,
-
- els_toggle
-
- ;
-
- (function(){
-
- _getNodes = function(name, node, model, ctx, controller){
- return custom_Statements[name].getNodes(node, model, ctx, controller);
- };
-
- _renderElements = function(nodes, model, ctx, container, ctr){
- if (nodes == null)
- return null;
-
- var elements = [];
- builder_build(nodes, model, ctx, container, ctr, elements);
- return elements;
- };
-
- _renderPlaceholder = function(staticCompo, compo, container){
- var placeholder = staticCompo.placeholder;
- if (placeholder == null) {
- placeholder = document.createComment('');
- container.appendChild(placeholder);
- }
- compo.placeholder = placeholder;
- };
-
- _compo_initAndBind = function(compo, node, model, ctx, container, controller) {
-
- compo.parent = controller;
- compo.model = model;
-
- compo.refresh = fn_proxy(compo.refresh, compo);
- compo.binder = expression_createBinder(
- compo.expr || compo.expression,
- model,
- ctx,
- controller,
- compo.refresh
- );
-
-
- expression_bind(compo.expr || compo.expression, model, ctx, controller, compo.binder);
- };
-
-
- els_toggle = function(els, state){
- if (els == null)
- return;
-
- var isArray = typeof els.splice === 'function',
- imax = isArray ? els.length : 1,
- i = -1,
- x;
- while ( ++i < imax ){
- x = isArray ? els[i] : els;
- x.style.display = state ? '' : 'none';
- }
- }
-
- }());
- // end:source 1.utils.js
- // source 2.if.js
- (function(){
-
- __registerHandler('+if', {
- placeholder: null,
- meta: {
- serializeNodes: true
- },
- render: function(model, ctx, container, ctr, children){
-
- var node = this,
- nodes = _getNodes('if', node, model, ctx, ctr),
- index = 0;
-
- var next = node;
- while(true){
-
- if (next.nodes === nodes)
- break;
-
- index++;
- next = node.nextSibling;
-
- if (next == null || next.tagName !== 'else') {
- index = null;
- break;
- }
- }
-
- this.attr['switch-index'] = index;
-
- return _renderElements(nodes, model, ctx, container, ctr, children);
- },
-
- renderEnd: function(els, model, ctx, container, ctr){
-
- var compo = new IFStatement(),
- index = this.attr['switch-index'];
-
- _renderPlaceholder(this, compo, container);
-
- return initialize(
- compo
- , this
- , index
- , els
- , model
- , ctx
- , container
- , ctr
- );
- },
-
- serializeNodes: function(current){
-
- var nodes = [ current ];
- while (true) {
- current = current.nextSibling;
- if (current == null || current.tagName !== 'else')
- break;
-
- nodes.push(current);
- }
-
- return mask.stringify(nodes);
- }
-
- });
-
-
- function IFStatement() {}
-
- IFStatement.prototype = {
- compoName: '+if',
- ctx : null,
- model : null,
- controller : null,
-
- index : null,
- Switch : null,
- binder : null,
-
- refresh: function() {
- var compo = this,
- switch_ = compo.Switch,
-
- imax = switch_.length,
- i = -1,
- expr,
- item, index = 0;
-
- var currentIndex = compo.index,
- model = compo.model,
- ctx = compo.ctx,
- ctr = compo.controller
- ;
-
- while ( ++i < imax ){
- expr = switch_[i].node.expression;
- if (expr == null)
- break;
-
- if (expression_eval(expr, model, ctx, ctr))
- break;
- }
-
- if (currentIndex === i)
- return;
-
- if (currentIndex != null)
- els_toggle(switch_[currentIndex].elements, false);
-
- if (i === imax) {
- compo.index = null;
- return;
- }
-
- this.index = i;
-
- var current = switch_[i];
- if (current.elements != null) {
- els_toggle(current.elements, true);
- return;
- }
-
- var frag = mask.render(current.node.nodes, model, ctx, null, ctr);
- var els = frag.nodeType === Node.DOCUMENT_FRAGMENT_NODE
- ? _Array_slice.call(frag.childNodes)
- : frag
- ;
-
-
- dom_insertBefore(frag, compo.placeholder);
-
- current.elements = els;
-
- },
- dispose: function(){
- var switch_ = this.Switch,
- imax = switch_.length,
- i = -1,
-
- x, expr;
-
- while( ++i < imax ){
- x = switch_[i];
- expr = x.node.expression;
-
- if (expr) {
- expression_unbind(
- expr,
- this.model,
- this.controller,
- this.binder
- );
- }
-
- x.node = null;
- x.elements = null;
- }
-
- this.controller = null;
- this.model = null;
- this.ctx = null;
- }
- };
-
- function initialize(compo, node, index, elements, model, ctx, container, ctr) {
-
- compo.model = model;
- compo.ctx = ctx;
- compo.controller = ctr;
- compo.refresh = fn_proxy(compo.refresh, compo);
- compo.binder = expression_createListener(compo.refresh);
- compo.index = index;
- compo.Switch = [{
- node: node,
- elements: null
- }];
-
- expression_bind(node.expression, model, ctx, ctr, compo.binder);
-
- while (true) {
- node = node.nextSibling;
- if (node == null || node.tagName !== 'else')
- break;
-
- compo.Switch.push({
- node: node,
- elements: null
- });
-
- if (node.expression)
- expression_bind(node.expression, model, ctx, ctr, compo.binder);
- }
- if (index != null) {
- compo.Switch[index].elements = elements;
- }
- return compo;
- }
-
-
- }());
- // end:source 2.if.js
- // source 3.switch.js
- (function(){
-
- var $Switch = custom_Statements['switch'],
- attr_SWITCH = 'switch-index'
- ;
-
- var _nodes,
- _index;
-
- __registerHandler('+switch', {
- meta: {
- serializeNodes: true
- },
- serializeNodes: function(current){
- return mask.stringify(current);
- },
- render: function(model, ctx, container, ctr, children){
-
- var value = expression_eval(this.expression, model, ctx, ctr);
-
-
- resolveNodes(value, this.nodes, model, ctx, ctr);
-
- if (_nodes == null)
- return null;
-
- this.attr[attr_SWITCH] = _index;
-
- return _renderElements(_nodes, model, ctx, container, ctr, children);
- },
-
- renderEnd: function(els, model, ctx, container, ctr){
-
- var compo = new SwitchStatement(),
- index = this.attr[attr_SWITCH];
-
- _renderPlaceholder(this, compo, container);
-
- return initialize(
- compo
- , this
- , index
- , els
- , model
- , ctx
- , container
- , ctr
- );
- }
- });
-
-
- function SwitchStatement() {}
-
- SwitchStatement.prototype = {
- compoName: '+switch',
- ctx: null,
- model: null,
- controller: null,
-
- index: null,
- nodes: null,
- Switch: null,
- binder: null,
-
-
- refresh: function(value) {
-
- var compo = this,
- switch_ = compo.Switch,
-
- imax = switch_.length,
- i = -1,
- expr,
- item, index = 0;
-
- var currentIndex = compo.index,
- model = compo.model,
- ctx = compo.ctx,
- ctr = compo.controller
- ;
-
- resolveNodes(value, compo.nodes, model, ctx, ctr);
-
- if (_index === currentIndex)
- return;
-
- if (currentIndex != null)
- els_toggle(switch_[currentIndex], false);
-
- if (_index == null) {
- compo.index = null;
- return;
- }
-
- this.index = _index;
-
- var elements = switch_[_index];
- if (elements != null) {
- els_toggle(elements, true);
- return;
- }
-
- var frag = mask.render(_nodes, model, ctx, null, ctr);
- var els = frag.nodeType === Node.DOCUMENT_FRAGMENT_NODE
- ? _Array_slice.call(frag.childNodes)
- : frag
- ;
-
-
- dom_insertBefore(frag, compo.placeholder);
-
- switch_[_index] = els;
-
- },
- dispose: function(){
- expression_unbind(
- this.expr,
- this.model,
- this.controller,
- this.binder
- );
-
- this.controller = null;
- this.model = null;
- this.ctx = null;
-
- var switch_ = this.Switch,
- key,
- els, i, imax
- ;
-
- for(key in switch_) {
- els = switch_[key];
-
- if (els == null)
- continue;
-
- imax = els.length;
- i = -1;
- while ( ++i < imax ){
- if (els[i].parentNode != null)
- els[i].parentNode.removeChild(els[i]);
- }
- }
- }
- };
-
- function resolveNodes(val, nodes, model, ctx, ctr) {
-
- _nodes = $Switch.getNodes(val, nodes, model, ctx, ctr);
- _index = null;
-
- if (_nodes == null)
- return;
-
- var imax = nodes.length,
- i = -1;
- while( ++i < imax ){
- if (nodes[i].nodes === _nodes)
- break;
- }
-
- _index = i === imax ? null : i;
- }
-
- function initialize(compo, node, index, elements, model, ctx, container, ctr) {
-
- compo.ctx = ctx;
- compo.expr = node.expression;
- compo.model = model;
- compo.controller = ctr;
- compo.index = index;
- compo.nodes = node.nodes;
-
- compo.refresh = fn_proxy(compo.refresh, compo);
- compo.binder = expression_createBinder(
- compo.expr,
- model,
- ctx,
- ctr,
- compo.refresh
- );
-
-
- compo.Switch = new Array(node.nodes.length);
-
- if (index != null) {
- compo.Switch[index] = elements;
- }
- expression_bind(node.expression, model, ctx, ctr, compo.binder);
-
- return compo;
- }
-
-
- }());
- // end:source 3.switch.js
- // source 4.with.js
- (function(){
-
- var $With = custom_Statements['with'];
-
- __registerHandler('+with', {
- meta: {
- serializeNodes: true
- },
- rootModel: null,
- render: function(model, ctx, container, ctr){
- var expr = this.expression,
- nodes = this.nodes,
- val = expression_eval_strict(
- expr, model, ctx, ctr
- )
- ;
- this.rootModel = model;
- return build(nodes, val, ctx, container, ctr);
- },
-
- onRenderStartClient: function(model, ctx){
- this.rootModel = model;
- this.model = expression_eval_strict(
- this.expression, model, ctx, this
- );
- },
-
- renderEnd: function(els, model, ctx, container, ctr){
- model = this.rootModel || model;
-
- var compo = new WithStatement(this);
-
- compo.elements = els;
- compo.model = model;
- compo.parent = ctr;
- compo.refresh = fn_proxy(compo.refresh, compo);
- compo.binder = expression_createBinder(
- compo.expr,
- model,
- ctx,
- ctr,
- compo.refresh
- );
-
- expression_bind(compo.expr, model, ctx, ctr, compo.binder);
-
- _renderPlaceholder(this, compo, container);
- return compo;
- }
- });
-
-
- function WithStatement(node){
- this.expr = node.expression;
- this.nodes = node.nodes;
- }
-
- WithStatement.prototype = {
- compoName: '+with',
- elements: null,
- binder: null,
- model: null,
- parent: null,
- refresh: function(val){
- dom_removeAll(this.elements);
-
- if (this.components) {
- var imax = this.components.length,
- i = -1;
- while ( ++i < imax ){
- Compo.dispose(this.components[i]);
- }
- this.components.length = 0;
- }
-
-
- var fragment = document.createDocumentFragment();
- this.elements = build(this.nodes, val, null, fragment, this);
-
- dom_insertBefore(fragment, this.placeholder);
- compo_inserted(this);
- },
-
-
- dispose: function(){
- expression_unbind(
- this.expr,
- this.model,
- this.parent,
- this.binder
- );
-
- this.parent = null;
- this.model = null;
- this.ctx = null;
- }
-
- };
-
- function build(nodes, model, ctx, container, controller){
- var els = [];
- builder_build(nodes, model, ctx, container, controller, els);
- return els;
- }
- }());
- // end:source 4.with.js
- // source 5.visible.js
- (function(){
- var $Visible = custom_Statements['visible'];
-
- __registerHandler('+visible', {
- meta: {
- serializeNodes: true
- },
- render: function(model, ctx, container, ctr, childs){
- return build(this.nodes, model, ctx, container, ctr);
- },
- renderEnd: function(els, model, ctx, container, ctr){
-
- var compo = new VisibleStatement(this);
- compo.elements = els;
- compo.model = model;
- compo.parent = ctr;
- compo.refresh = fn_proxy(compo.refresh, compo);
- compo.binder = expression_createBinder(
- compo.expr,
- model,
- ctx,
- ctr,
- compo.refresh
- );
-
- expression_bind(compo.expr, model, ctx, ctr, compo.binder);
- compo.refresh();
- return compo;
- }
- });
-
-
- function VisibleStatement(node){
- this.expr = node.expression;
- this.nodes = node.nodes;
- }
-
- VisibleStatement.prototype = {
- compoName: '+visible',
- elements: null,
- binder: null,
- model: null,
- parent: null,
- refresh: function(){
- var isVisible = expression_eval(
- this.expr, this.model, this.ctx, this
- );
- $Visible.toggle(this.elements, isVisible);
- },
- dispose: function(){
- expression_unbind(
- this.expr,
- this.model,
- this.parent,
- this.binder
- );
-
- this.parent = null;
- this.model = null;
- this.ctx = null;
- }
-
- };
-
- function build(nodes, model, ctx, container, ctr){
- var els = [];
- builder_build(nodes, model, ctx, container, ctr, els);
- return els;
- }
- }());
- // end:source 5.visible.js
- // source loop/exports.js
- (function(){
-
- // source utils.js
-
-
- function arr_createRefs(array){
- var imax = array.length,
- i = -1,
- x;
- while ( ++i < imax ){
- //create references from values to distinguish the models
- x = array[i];
- switch (typeof x) {
- case 'string':
- case 'number':
- case 'boolean':
- array[i] = Object(x);
- break;
- }
- }
- }
-
-
- function list_sort(self, array) {
-
- var compos = self.node.components,
- i = 0,
- imax = compos.length,
- j = 0,
- jmax = null,
- element = null,
- compo = null,
- fragment = document.createDocumentFragment(),
- sorted = [];
-
- for (; i < imax; i++) {
- compo = compos[i];
- if (compo.elements == null || compo.elements.length === 0)
- continue;
-
- for (j = 0, jmax = compo.elements.length; j < jmax; j++) {
- element = compo.elements[j];
- element.parentNode.removeChild(element);
- }
- }
-
-
- outer: for (j = 0, jmax = array.length; j < jmax; j++) {
-
- for (i = 0; i < imax; i++) {
- if (array[j] === self._getModel(compos[i])) {
- sorted[j] = compos[i];
- continue outer;
- }
- }
-
- console.warn('No Model Found for', array[j]);
- }
-
-
-
- for (i = 0, imax = sorted.length; i < imax; i++) {
- compo = sorted[i];
-
- if (compo.elements == null || compo.elements.length === 0) {
- continue;
- }
-
-
- for (j = 0, jmax = compo.elements.length; j < jmax; j++) {
- element = compo.elements[j];
-
- fragment.appendChild(element);
- }
- }
-
- self.components = self.node.components = sorted;
-
- dom_insertBefore(fragment, self.placeholder);
-
- }
-
- function list_update(self, deleteIndex, deleteCount, insertIndex, rangeModel) {
-
- var node = self.node,
- compos = node.components
- ;
- if (compos == null)
- compos = node.components = []
-
- var prop1 = self.prop1,
- prop2 = self.prop2,
- type = self.type,
-
- ctx = self.ctx,
- ctr = self.node
- ;
-
- if (deleteIndex != null && deleteCount != null) {
- var i = deleteIndex,
- length = deleteIndex + deleteCount;
-
- if (length > compos.length)
- length = compos.length;
-
- for (; i < length; i++) {
- if (compo_dispose(compos[i], node)){
- i--;
- length--;
- }
- }
- }
-
- if (insertIndex != null && rangeModel && rangeModel.length) {
-
- var i = compos.length,
- imax,
- fragment = self._build(node, rangeModel, ctx, ctr),
- new_ = compos.splice(i)
- ;
- compo_fragmentInsert(node, insertIndex, fragment, self.placeholder);
-
- compos.splice.apply(compos, [insertIndex, 0].concat(new_));
- i = 0;
- imax = new_.length;
- for(; i < imax; i++){
- __Compo.signal.emitIn(new_[i], 'domInsert');
- }
- }
- }
-
- function list_remove(self, removed){
- var compos = self.components,
- i = compos.length,
- x;
- while(--i > -1){
- x = compos[i];
-
- if (removed.indexOf(x.model) === -1)
- continue;
-
- compo_dispose(x, self.node);
- }
- }
-
-
- // end:source utils.js
- // source proto.js
- var LoopStatementProto = {
- model: null,
- parent: null,
- refresh: function(value, method, args, result){
- var i = 0,
- x, imax;
-
- var node = this.node,
-
- model = this.model,
- ctx = this.ctx,
- ctr = this.node
- ;
-
- if (method == null) {
- // this was new array/object setter and not an immutable function call
-
- var compos = node.components;
- if (compos != null) {
- var imax = compos.length,
- i = -1;
- while ( ++i < imax ){
- if (compo_dispose(compos[i], node)){
- i--;
- imax--;
- }
- }
- compos.length = 0;
- }
-
- var frag = this._build(node, value, ctx, ctr);
-
- dom_insertBefore(frag, this.placeholder);
- arr_each(node.components, compo_inserted);
- return;
- }
-
- var array = value;
- arr_createRefs(value);
-
-
- switch (method) {
- case 'push':
- list_update(this, null, null, array.length - 1, array.slice(array.length - 1));
- break;
- case 'pop':
- list_update(this, array.length, 1);
- break;
- case 'unshift':
- list_update(this, null, null, 0, array.slice(0, 1));
- break;
- case 'shift':
- list_update(this, 0, 1);
- break;
- case 'splice':
- var sliceStart = args[0],
- sliceRemove = args.length === 1 ? this.components.length : args[1],
- sliceAdded = args.length > 2 ? array.slice(args[0], args.length - 2 + args[0]) : null;
-
- list_update(this, sliceStart, sliceRemove, sliceStart, sliceAdded);
- break;
- case 'sort':
- case 'reverse':
- list_sort(this, array);
- break;
- case 'remove':
- if (result != null && result.length)
- list_remove(this, result);
- break;
- }
- },
-
- dispose: function(){
-
- expression_unbind(
- this.expr || this.expression, this.model, this.parent, this.binder
- );
- }
- };
-
- // end:source proto.js
- // source for.js
- (function(){
-
- var For = custom_Statements['for'],
-
- attr_PROP_1 = 'for-prop-1',
- attr_PROP_2 = 'for-prop-2',
- attr_TYPE = 'for-type',
- attr_EXPR = 'for-expr'
- ;
-
-
- __registerHandler('+for', {
- meta: {
- serializeNodes: true
- },
- serializeNodes: function(node){
- return mask.stringify(node);
- },
- render: function(model, ctx, container, ctr, children){
- var directive = For.parseFor(this.expression),
- attr = this.attr;
-
- attr[attr_PROP_1] = directive[0];
- attr[attr_PROP_2] = directive[1];
- attr[attr_TYPE] = directive[2];
- attr[attr_EXPR] = directive[3];
-
- var value = expression_eval_strict(directive[3], model, ctx, ctr);
- if (value == null)
- return;
-
- if (is_Array(value))
- arr_createRefs(value);
-
- For.build(
- value,
- directive,
- this.nodes,
- model,
- ctx,
- container,
- this,
- children
- );
- },
-
- renderEnd: function(els, model, ctx, container, ctr){
-
- var compo = new ForStatement(this, this.attr);
- _renderPlaceholder(this, compo, container);
- _compo_initAndBind(compo, this, model, ctx, container, ctr);
- return compo;
- },
-
- getHandler: function(name, model){
-
- return For.getHandler(name, model);
- }
-
- });
-
- function initialize(compo, node, els, model, ctx, container, ctr) {
-
- compo.parent = ctr;
- compo.model = model;
-
- compo.refresh = fn_proxy(compo.refresh, compo);
- compo.binder = expression_createBinder(
- compo.expr,
- model,
- ctx,
- ctr,
- compo.refresh
- );
-
-
- expression_bind(compo.expr, model, ctx, ctr, compo.binder);
-
- }
-
- function ForStatement(node, attr) {
- this.prop1 = attr[attr_PROP_1];
- this.prop2 = attr[attr_PROP_2];
- this.type = attr[attr_TYPE];
- this.expr = attr[attr_EXPR];
-
- if (node.components == null)
- node.components = [];
-
- this.node = node;
- this.components = node.components;
- }
-
- ForStatement.prototype = {
- compoName: '+for',
- model: null,
- parent: null,
-
- refresh: LoopStatementProto.refresh,
- dispose: LoopStatementProto.dispose,
-
- _getModel: function(compo) {
- return compo.scope[this.prop1];
- },
-
- _build: function(node, model, ctx, component) {
- var nodes = For.getNodes(node.nodes, model, this.prop1, this.prop2, this.type);
-
- return builder_build(nodes, this.model, ctx, null, component);
- }
- };
-
- }());
- // end:source for.js
- // source each.js
- (function(){
-
- var Each = custom_Statements['each'];
- var EachBinded = {
- meta: {
- serializeNodes: true
- },
- serializeNodes: function(node){
- return mask.stringify(node);
- },
- //modelRef: null,
- render: function(model, ctx, container, ctr, children){
- //this.modelRef = this.expression;
- var array = expression_eval(this.expression, model, ctx, ctr);
- if (array == null)
- return;
-
- arr_createRefs(array);
-
- build(
- this.nodes,
- array,
- ctx,
- container,
- this,
- children
- );
- },
-
- renderEnd: function(els, model, ctx, container, ctr){
- var compo = new EachStatement(this, this.attr);
-
- _renderPlaceholder(this, compo, container);
- _compo_initAndBind(compo, this, model, ctx, container, ctr);
- return compo;
- }
-
- };
-
- var EachItem = class_create({
- compoName: 'each::item',
- scope: null,
- model: null,
- modelRef: null,
- parent: null,
-
- // if BROWSER
- renderStart: null,
- // endif
- renderEnd: function(els) {
- this.elements = els;
- },
- dispose: function(){
- if (this.elements != null) {
- this.elements.length = 0;
- this.elements = null;
- }
- }
- });
-
- var EachStatement = class_create({
- constructor: function EachStatement(node, attr) {
- this.expression = node.expression;
- this.nodes = node.nodes;
-
- if (node.components == null)
- node.components = [];
-
- this.node = node;
- this.components = node.components;
- },
- compoName: '+each',
- refresh: LoopStatementProto.refresh,
- dispose: LoopStatementProto.dispose,
-
- _getModel: function(compo) {
- return compo.model;
- },
-
- _build: function(node, model, ctx, component) {
- var fragment = document.createDocumentFragment();
-
- build(node.nodes, model, ctx, fragment, component);
-
- return fragment;
- }
- });
-
- // METHODS
-
- function build(nodes, array, ctx, container, ctr, elements) {
- var imax = array.length,
- nodes_ = new Array(imax),
- i = 0, node;
-
- for(; i < imax; i++) {
- node = createEachNode(nodes, i);
- builder_build(node, array[i], ctx, container, ctr, elements);
- }
- }
-
- function createEachNode(nodes, index){
- var item = new EachItem;
- item.scope = { index: index };
-
- return {
- type: Dom.COMPONENT,
- tagName: 'each::item',
- nodes: nodes,
- controller: function() {
- return item;
- }
- };
- }
-
- // EXPORTS
-
- __registerHandler('each::item', EachItem);
- __registerHandler('+each', EachBinded);
- }());
- // end:source each.js
-
- }());
-
- // end:source loop/exports.js
-
- }());
- // end:source statements/
-
- // source exports
- obj_extend(mask, {
- Validators: Validators,
- registerValidator: function(type, fn) {
- Validators[type] = fn;
- },
- BindingProviders: CustomProviders,
- registerBinding: function(name, Prov) {
- CustomProviders[name] = Prov;
- }
- });
-
- // end:source exports
-
- // source api/utils
- obj_extend(mask.obj, {
- addObserver : obj_addObserver,
- removeObserver: obj_removeObserver,
- });
- // end:source api/utils
-
- }(Mask, Compo));
-
- // end:source /ref-mask-binding/lib/binding_embed
-
- // source handlers/
- // source debug
- (function(){
- custom_Statements['log'] = {
- render: function(node, model, ctx, container, controller){
- var arr = expression_evalStatements(node.expression, model, ctx, controller);
- arr.unshift('Mask::Log');
- console.log.apply(console, arr);
- }
- };
- customTag_register('debugger', {
- render: function(model, ctx, container, compo){
- debugger;
- }
- });
- customTag_register(':utest', Compo({
- render: function (model, ctx, container) {
- if (container.nodeType === Node.DOCUMENT_FRAGMENT_NODE)
- container = container.childNodes;
- this.$ = $(container);
- }
- }));
- }());
- // end:source debug
- // source define
- custom_Tags['define'] = class_create({
- meta: {
- serializeNodes: true
- },
- constructor: function(node, model, ctx, el, ctr) {
- Define.registerGlobal(node, model, ctr);
- },
- render: fn_doNothing
- });
-
- custom_Tags['let'] = class_create({
- meta: {
- serializeNodes: true
- },
- constructor: function(node, model, ctx, el, ctr) {
- Define.registerScoped(node, model, ctr);
- },
- render: fn_doNothing
- });
- // end:source define
- // source html
- (function() {
- var Compo = {
- meta: {
- mode: 'server:all'
- },
- render: function(model, ctx, container) {
- this.html = jmask(this.nodes).text(model, ctx, this);
-
- if (container.insertAdjacentHTML) {
- container.insertAdjacentHTML('beforeend', this.html);
- return;
- }
- if (container.ownerDocument) {
- var div = document.createElement('div'),
- child;
- div.innerHTML = this.html;
- child = div.firstChild;
- while (child != null) {
- container.appendChild(child);
- child = child.nextSibling;
- }
- }
- },
- toHtml: function(){
- return this.html || '';
- },
- html: null
- };
- customTag_register(':html', Compo);
- }());
-
- // end:source html
- // source methods
- (function() {
- var Method = class_create({
- meta: {
- serializeNodes: true
- },
- constructor: function(node) {
- this.fn = node.fn; // || compileFn(node.args, node.body);
- this.name = node.name;
- }
- });
-
- custom_Tags['slot'] = class_create(Method, {
- renderEnd: function(){
- var ctr = this.parent;
- var slots = ctr.slots;
- if (slots == null) {
- slots = ctr.slots = {};
- }
- slots[this.name] = this.fn;
- }
- });
- custom_Tags['event'] = class_create(Method, {
- renderEnd: function(els, model, ctx, el){
- this.fn = this.fn.bind(this.parent);
- var name = this.name,
- params = null,
- i = name.indexOf(':');
- if (i !== -1) {
- params = name.substring(i + 1).trim();
- name = name.substring(0, i).trim();
- }
- Compo.Dom.addEventListener(el, name, this.fn, params);
- }
- });
- custom_Tags['function'] = class_create(Method, {
- renderEnd: function(){
- this.parent[this.name] = this.fn;
- }
- });
- }());
- // end:source methods
- // source template
- (function(){
- var templates_ = {},
- helper_ = {
- get: function(id){
- return templates_[id]
- },
- resolve: function(node, id){
- var nodes = templates_[id];
- if (nodes != null)
- return nodes;
-
- var selector = ':template[id=' + id +']',
- parent = node.parent,
- tmpl = null
- ;
- while (parent != null) {
- tmpl = jmask(parent.nodes)
- .filter(selector)
- .get(0);
-
- if (tmpl != null)
- return tmpl.nodes;
-
- parent = parent.parent;
- }
- log_warn('Template was not found', id);
- return null;
- },
- register: function(id, nodes){
- if (id == null) {
- log_warn('`:template` must define the `id` attr');
- return;
- }
- templates_[id] = nodes;
- }
- };
-
- Mask.templates = helper_;
- customTag_register(':template', {
- render: function() {
- helper_.register(this.attr.id, this.nodes);
- }
- });
-
- customTag_register(':import', {
- renderStart: function() {
- var id = this.attr.id;
- if (id == null) {
- log_error('`:import` shoud reference the template via id attr')
- return;
- }
- this.nodes = helper_.resolve(this, id);
- }
- });
-
- custom_Statements['include'] = {
- render: function (node, model, ctx, container, ctr, els) {
- var name = attr_first(node.attr);
- var Compo = customTag_get(name, ctr);
- var template;
-
- if (Compo != null) {
- template = Compo.prototype.template || Compo.prototype.nodes;
- if (template != null) {
- template = mask_merge(template, node.nodes);
- }
- }
- else {
- template = helper_.get(name);
- }
- if (template != null) {
- builder_build(template, model, ctx, container, ctr, els);
- }
- }
- };
-
- customTag_register('layout:master', {
- render: function () {
- var name = this.attr.id || attr_first(this.attr);
- helper_.register(name, this.nodes);
- }
- });
-
- customTag_register('layout:view', {
- render: function (model, ctx, container, ctr, els) {
- var nodes = helper_.get(this.attr.master);
- var template = mask_merge(nodes, this.nodes, null, { extending: true });
- builder_build(template, model, ctx, container, ctr, els);
- }
- });
-
- }());
- // end:source template
- // source var
- (function(){
- // TODO: refactor methods, use MaskNode Serialization instead Model Serialization
- custom_Tags['var'] = class_create(customTag_Base, {
- renderStart: function(model, ctx){
- set(this, this.attr, true, model, ctx);
- },
- onRenderStartClient: function(){
- set(this, this.model, false)
- }
- });
-
- function set(self, source, doEval, attr, model, ctx) {
- // set data also to model, so that it will be serialized in NodeJS
- self.model = {};
-
- var parent = self.parent;
- var scope = parent.scope;
- if (scope == null) {
- scope = parent.scope = {};
- }
- for(var key in source){
- self.model[key] = scope[key] = doEval === false
- ? source[key]
- : expression_eval(source[key], model, ctx, parent);
- }
- }
- }());
- // end:source var
- // end:source handlers/
-
-// source umd-footer
- Mask.Compo = Compo;
- Mask.jmask = jmask;
-
- Mask.version = '0.51.37';
-
- //> make fast properties
- custom_optimize();
-
- return (exports.mask = Mask);
-}));
-// end:source umd-footer
diff --git a/examples/atmajs/node_modules/ruta/lib/ruta.js b/examples/atmajs/node_modules/ruta/lib/ruta.js
deleted file mode 100644
index d91ced4d92..0000000000
--- a/examples/atmajs/node_modules/ruta/lib/ruta.js
+++ /dev/null
@@ -1,1144 +0,0 @@
-(function(root, factory){
- "use strict";
-
- if (root == null) {
- root = typeof window !== 'undefined' && typeof document !== 'undefined'
- ? window
- : global;
- }
-
-
- root.ruta = factory(root);
-
-}(this, function(global){
- "use strict";
-
- // source ../src/vars.js
-
- var mask = global.mask || (typeof Mask !== 'undefined' ? Mask : null);
-
- // settings
-
- /** define if routes like '/path' are strict by default,
- * or set explicit '!/path' - strict, '^/path' - not strict
- *
- * Strict means - like in regex start-end /^$/
- * */
- var _cfg_isStrict = true,
- _Array_slice = Array.prototype.slice;
- // end:source ../src/vars.js
-
- // source ../src/utils/obj.js
- var obj_extend,
- obj_create;
- (function(){
-
- obj_extend = function(a, b){
- if (b == null)
- return a || {};
-
- if (a == null)
- return obj_create(b);
-
- for(var key in b){
- a[key] = b[key];
- }
- return a;
- };
-
- obj_create = Object.create || function(x) {
- var Ctor = function(){};
- Ctor.prototype = x;
- return new Ctor;
- };
-
- }());
- // end:source ../src/utils/obj.js
- // source ../src/utils/log.js
- var log_error;
- (function(){
-
- log_error = function(){
- var args = _Array_slice.call(arguments);
-
- console.error.apply(console, ['Ruta'].concat(args));
- };
-
- }());
- // end:source ../src/utils/log.js
- // source ../src/utils/path.js
- var path_normalize,
- path_split,
- path_join,
- path_fromCLI,
- path_getQuery,
- path_setQuery
- ;
-
- (function(){
-
-
- path_normalize = function(str) {
-
- var length = str.length,
- i = 0,
- j = length - 1;
-
- for(; i < length; i++) {
- if (str[i] === '/')
- continue;
-
- break;
- }
- for (; j > i; j--) {
- if (str[j] === '/')
- continue;
-
- break;
- }
-
- return str.substring(i, j + 1);
- };
-
- path_split = function(path) {
- path = path_normalize(path);
-
- return path === ''
- ? []
- : path.split('/');
- };
-
- path_join = function(pathParts) {
- return '/' + pathParts.join('/');
- };
-
- path_fromCLI = function(commands){
-
- if (typeof commands === 'string')
- commands = cli_split(commands);
-
- var parts = cli_parseArguments(commands);
-
- return parts_serialize(parts);
- };
-
- path_getQuery = function(path){
- var i = path.indexOf('?');
- if (i === -1)
- return null;
-
- var query = path.substring(i + 1);
- return query_deserialize(query, '&');
- };
-
- path_setQuery = function(path, mix){
- var query = typeof mix !== 'string'
- ? query_serialize(mix, '&')
- : mix;
-
- var i = path.indexOf('?');
- if (i !== -1) {
- path = path.substring(0, i);
- }
- return path + '?' + query;
- };
-
- // == private
-
- function cli_split(string){
- var args = string.trim().split(/\s+/);
-
- var imax = args.length,
- i = -1,
- c, arg;
-
- while ( ++i < imax ){
-
- arg = args[i];
- if (arg.length === 0)
- continue;
-
- c = arg[0];
-
- if (c !== '"' && c !== "'")
- continue;
-
-
- var start = i;
- for( ; i < imax; i++ ){
-
- arg = args[i];
- if (arg[arg.length - 1] === c) {
-
- var str = args
- .splice(start, i - start + 1)
- .join(' ')
- .slice(1, -1)
- ;
-
- args.splice(start, 0, str);
- imax = args.length;
- break;
- }
- }
- }
-
- return args;
- }
-
- function cli_parseArguments(argv){
- var imax = argv.length,
- i = 0,
- params = {},
- args = [],
- key, val, x;
-
- for (; i < imax; i++){
- x = argv[i];
-
- if (x[0] === '-') {
-
- key = x.replace(/^[\-]+/, '');
-
- if (i < imax - 1 && argv[i + 1][0] !== '-') {
- val = argv[i + 1];
- i++;
- } else {
- val = true;
- }
-
- params[key] = val;
- continue;
- }
-
- args.push(x);
- }
-
- return {
- path: args,
- query: params
- };
- }
-
- }());
-
- // end:source ../src/utils/path.js
- // source ../src/utils/query.js
- var query_deserialize,
- query_serialize
- ;
-
- (function(){
-
- query_deserialize = function(query, delimiter) {
- if (delimiter == null)
- delimiter = '&';
-
- var obj = {},
- parts = query.split(delimiter),
- i = 0,
- imax = parts.length,
- x, val;
-
- for (; i < imax; i++) {
- x = parts[i].split('=');
- val = x[1] == null
- ? ''
- : decode(x[1])
- ;
- obj_setProperty(obj, x[0], val);
- }
- return obj;
- };
- query_serialize = function(params, delimiter) {
- if (delimiter == null)
- delimiter = '&';
-
- var query = '',
- key, val;
- for(key in params) {
- val = params[key];
- if (val == null)
- continue;
-
- // serialize as flag
- if (typeof val === 'boolean')
- val = null;
-
- query = query + (query ? delimiter : '') + key;
- if (val != null)
- query += '=' + encode(val);
- }
-
- return query;
- };
-
- // = private
-
- function obj_setProperty(obj, property, value) {
- var chain = property.split('.'),
- imax = chain.length,
- i = -1,
- key;
-
- while ( ++i < imax - 1) {
- key = chain[i];
-
- if (obj[key] == null)
- obj[key] = {};
-
- obj = obj[key];
- }
-
- obj[chain[i]] = value;
- }
- function decode(str) {
- try {
- return decodeURIComponent(str);
- } catch(error) {
- log_error('decode:URI malformed');
- return '';
- }
- }
- function encode(str) {
- try {
- return encodeURIComponent(str);
- } catch(error) {
- log_error('encode:URI malformed');
- return '';
- }
- }
- }());
-
-
- // end:source ../src/utils/query.js
- // source ../src/utils/rgx.js
- var rgx_fromString,
-
- // Url part should be completely matched, so add ^...$ and create RegExp
- rgx_aliasMatcher,
-
- // :debugger(d|debug) => { alias: 'debugger', matcher: RegExp }
- rgx_parsePartWithRegExpAlias
- ;
-
- (function(){
-
-
- rgx_fromString = function(str, flags) {
- return new RegExp(str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), flags);
- };
-
- rgx_aliasMatcher = function(str){
-
- if (str[0] === '^')
- return new RegExp(str);
-
- var groups = str.split('|');
- for (var i = 0, imax = groups.length; i < imax; i++){
- groups[i] = '^' + groups[i] + '$';
- }
-
- return new RegExp(groups.join('|'));
- };
-
- rgx_parsePartWithRegExpAlias = function(str){
- var pStart = str.indexOf('('),
- pEnd = str.lastIndexOf(')')
- ;
-
- if (pStart === -1 || pEnd === -1) {
- log_error('Expected alias part with regexp', str);
- return null;
- }
-
- var rgx = str.substring(pStart + 1, pEnd);
- return {
- alias: str.substring(1, pStart),
- matcher: rgx_aliasMatcher(rgx)
- };
- };
-
- }());
-
- // end:source ../src/utils/rgx.js
- // source ../src/utils/parts.js
-
- /**
- * '/foo/bar?a=b' =>
- * { path: ['foo', 'bar'], query: { a: 'b' } }
- */
-
- var parts_serialize,
- parts_deserialize
- ;
-
- (function(){
-
-
- parts_serialize = function(parts){
- var path = path_join(parts.path);
-
- if (parts.query == null)
- return path;
-
- return path
- + '?'
- + query_serialize(parts.query, '&')
- ;
- };
-
- parts_deserialize = function(url){
- var query = url.indexOf('?'),
- path = query === -1
- ? url
- : url.substring(0, query);
-
-
- return {
- path: path_split(path),
- query: query === -1
- ? null
- : query_deserialize(url.substring(query + 1), '&')
- };
- };
-
-
- }());
-
- // end:source ../src/utils/parts.js
-
- // source ../src/route/Collection.js
- var Routes = (function(){
-
- // source Route.js
-
- // source parse.js
- var route_parseDefinition, // out route, definition
-
- // path should be already matched by the route
- route_parsePath // route, path
- ;
-
- (function(){
-
-
- route_parseDefinition = function(route, definition) {
-
- var c = definition.charCodeAt(0);
- switch(c){
- case 33:
- // !
- route.strict = true;
- definition = definition.substring(1);
- break;
- case 94:
- // ^
- route.strict = false;
- definition = definition.substring(1);
- break;
- case 40:
- // (
- var start = 1,
- end = definition.length - 1
- ;
- if (definition.charCodeAt(definition.length - 1) !== 41) {
- // )
- log_error('parser - expect group closing');
- end ++;
- }
-
- route.match = new RegExp(definition.substring(start, end));
- return;
- }
-
-
-
- var parts = definition.split('/'),
- search,
- searchIndex,
- i = 0,
- imax = parts.length,
- x,
- c0,
- index,
- c1;
-
-
- var last = parts[imax - 1];
- searchIndex = last.indexOf('?');
- if (searchIndex > (imax === 1 ? -1 : 0)) {
- // `?` cannt be at `0` position, when has url definition contains `path`
- search = last.substring(searchIndex + 1);
- parts[imax - 1] = last.substring(0, searchIndex);
- }
-
- var matcher = '',
- alias = null,
- strictCount = 0;
-
- var gettingMatcher = true,
- isOptional,
- isAlias,
- rgx;
-
- var array = route.path = [];
-
- for (; i < imax; i++) {
- x = parts[i];
-
- if (x === '')
- continue;
-
-
- c0 = x.charCodeAt(0);
- c1 = x.charCodeAt(1);
-
- isOptional = c0 === 63; /* ? */
- isAlias = (isOptional ? c1 : c0) === 58; /* : */
- index = 0;
-
- if (isOptional)
- index++;
-
- if (isAlias)
- index++;
-
-
- if (index !== 0)
- x = x.substring(index);
-
-
- // if DEBUG
- if (!isOptional && !gettingMatcher)
- log_error('Strict part found after optional', definition);
- // endif
-
-
- if (isOptional)
- gettingMatcher = false;
-
- var bracketIndex = x.indexOf('(');
- if (isAlias && bracketIndex !== -1) {
- var end = x.length - 1;
- if (x[end] !== ')')
- end+= 1;
-
- rgx = new RegExp(rgx_aliasMatcher(x.substring(bracketIndex + 1, end)));
- x = x.substring(0, bracketIndex);
- }
-
- if (!isOptional && !isAlias) {
- array.push(x);
- continue;
- }
-
- if (isAlias) {
- array.push({
- alias: x,
- matcher: rgx,
- optional: isOptional
- });
- }
-
- }
-
- if (search) {
- var query = route.query = {};
-
- parts = search.split('&');
-
- i = -1;
- imax = parts.length;
-
- var key, value, str, eqIndex;
- while(++i < imax){
- str = parts[i];
-
- eqIndex = str.indexOf('=');
- if (eqIndex === -1) {
- query[str] = ''; //
- continue;
- }
-
- key = str.substring(0, eqIndex);
- value = str.substring(eqIndex + 1);
-
- if (value.charCodeAt(0) === 40) {
- // (
- value = new RegExp(rgx_aliasMatcher(value));
- }
-
- query[key] = value;
- }
-
- if (route.path.length === 0) {
- route.strict = false;
- }
- }
- };
-
-
- route_parsePath = function(route, path) {
-
- var queryIndex = path.indexOf('?'),
-
- query = queryIndex === -1
- ? null
- : path.substring(queryIndex + 1),
-
- current = {
- path: path,
- params: query == null
- ? {}
- : query_deserialize(query, '&')
- };
-
- if (route.query) {
- // ensura aliased queries, like ?:debugger(d|debug)
- for (var key in route.query){
-
- if (key[0] === '?')
- key = key.substring(1);
-
- if (key[0] === ':') {
- var alias = rgx_parsePartWithRegExpAlias(key),
- name = alias.alias;
-
- current.params[name] = getAliasedValue(current.params, alias.matcher);
- }
- }
- }
-
- if (queryIndex !== -1) {
- path = path.substring(0, queryIndex);
- }
-
- if (route.path != null) {
-
- var pathArr = path_split(path),
- routePath = route.path,
- routeLength = routePath.length,
-
- imax = pathArr.length,
- i = 0,
- part,
- x;
-
- for (; i < imax; i++) {
- part = pathArr[i];
- x = i < routeLength ? routePath[i] : null;
-
- if (x) {
-
- if (typeof x === 'string')
- continue;
-
- if (x.alias) {
- current.params[x.alias] = part;
- continue;
- }
- }
- }
- }
-
- return current;
- };
-
-
- // = private
-
- function getAliasedValue(obj, matcher) {
- for (var key in obj){
- if (matcher.test(key))
- return obj[key];
- }
- }
- }());
- // end:source parse.js
- // source match.js
- var route_match,
- route_isMatch
- ;
-
- (function(){
-
- route_match = function(url, routes, currentMethod){
-
- var parts = parts_deserialize(url);
-
-
- for (var i = 0, route, imax = routes.length; i < imax; i++){
- route = routes[i];
-
- if (route_isMatch(parts, route, currentMethod)) {
-
- route.current = route_parsePath(route, url);
- return route;
- }
- }
-
- return null;
- };
-
- route_isMatch = function(parts, route, currentMethod) {
-
- if (currentMethod != null &&
- route.method != null &&
- route.method !== currentMethod) {
- return false;
- }
-
- if (route.match) {
-
- return route.match.test(
- typeof parts === 'string'
- ? parts
- : parts_serialize(parts)
- );
- }
-
-
- if (typeof parts === 'string')
- parts = parts_deserialize(parts);
-
- // route defines some query, match these with the current path{parts}
- if (route.query) {
- var query = parts.query,
- key, value;
- if (query == null)
- return false;
-
- for(key in route.query){
- value = route.query[key];
-
-
- var c = key[0];
- if (c === ':') {
- // '?:isGlob(g|glob) will match if any is present
- var alias = rgx_parsePartWithRegExpAlias(key);
- if (alias == null || hasKey(query, alias.matcher) === false)
- return false;
-
- continue;
- }
-
- if (c === '?')
- continue;
-
-
- if (typeof value === 'string') {
-
- if (query[key] == null)
- return false;
-
- if (value && query[key] !== value)
- return false;
-
- continue;
- }
-
- if (value.test && !value.test(query[key]))
- return false;
- }
- }
-
-
- var routePath = route.path,
- routeLength = routePath.length;
-
-
- if (routeLength === 0) {
- if (route.strict)
- return parts.path.length === 0;
-
- return true;
- }
-
-
-
- for (var i = 0, x, imax = parts.path.length; i < imax; i++){
-
- x = routePath[i];
-
- if (i >= routeLength)
- return route.strict !== true;
-
- if (typeof x === 'string') {
- if (parts.path[i] === x)
- continue;
-
- return false;
- }
-
- if (x.matcher && x.matcher.test(parts.path[i]) === false) {
- return false;
- }
-
- if (x.optional)
- return true;
-
- if (x.alias)
- continue;
-
- return false;
- }
-
- if (i < routeLength)
- return routePath[i].optional === true;
-
-
- return true;
- };
-
-
- function hasKey(obj, rgx){
-
- for(var key in obj){
- if (rgx.test(key))
- return true;
- }
- return false;
- }
-
- }());
-
- // end:source match.js
-
- var regexp_var = '([^\\\\]+)';
-
- function Route(definition, value) {
-
- this.method = definition.charCodeAt(0) === 36
- ? definition.substring(1, definition.indexOf(' ')).toUpperCase()
- : null
- ;
-
- if (this.method != null) {
- definition = definition.substring( this.method.length + 2 );
- }
-
- this.strict = _cfg_isStrict;
- this.value = value;
- this.definition = definition;
-
- route_parseDefinition(this, definition);
- }
-
- Route.prototype = {
- path: null,
- query: null,
- value: null,
- current: null
- };
-
- // end:source Route.js
-
-
- function RouteCollection() {
- this.routes = [];
- }
-
- RouteCollection.prototype = {
- add: function(regpath, value){
- this.routes.push(new Route(regpath, value));
- return this;
- },
-
- get: function(path, currentMethod){
-
- return route_match(path, this.routes, currentMethod);
- },
-
- clear: function(){
- this.routes.length = 0;
- return this;
- }
- };
-
- RouteCollection.parse = function(definition, path){
- var route = {};
-
- route_parseDefinition(route, definition);
- return route_parsePath(route, path);
- };
-
- return RouteCollection;
- }());
- // end:source ../src/route/Collection.js
-
- // source ../src/emit/Location.js
-
- var Location = (function(){
-
- if (typeof window === 'undefined') {
- return function(){};
- }
-
- // source Hash.js
- function HashEmitter(listener) {
- if (typeof window === 'undefined' || 'onhashchange' in window === false)
- return null;
-
- this.listener = listener;
-
- var that = this;
- window.onhashchange = function() {
- that.changed(location.hash);
- };
- return this;
- }
-
- (function() {
-
- function hash_normalize(hash) {
- return hash.replace(/^[!#/]+/, '/');
- }
-
- HashEmitter.prototype = {
- navigate: function(hash) {
- if (hash == null) {
- this.changed(location.hash);
- return;
- }
-
- location.hash = hash;
- },
- changed: function(hash) {
- this
- .listener
- .changed(hash_normalize(hash));
-
- },
- current: function() {
- return hash_normalize(location.hash);
- }
- };
-
- }());
- // end:source Hash.js
- // source History.js
- function HistoryEmitter(listener){
- if (typeof window === 'undefined')
- return null;
-
- if (!(window.history && window.history.pushState))
- return null;
-
- var that = this;
- that.listener = listener;
- that.initial = location.pathname;
-
- window.onpopstate = function(){
- if (that.initial === location.pathname) {
- that.initial = null;
- return;
- }
- that.changed();
- };
-
- return that;
- }
-
- HistoryEmitter.prototype = {
- navigate: function(url, opts){
- if (url == null) {
- this.changed();
- return;
- }
-
- if (opts != null && opts.extend === true) {
- var query = path_getQuery(url),
- current = path_getQuery(location.search);
-
- if (current != null && query != null) {
- for (var key in current) {
- // strict compare
- if (query[key] !== void 0 && query[key] === null) {
- delete current[key];
- }
- }
- query = obj_extend(current, query);
- url = path_setQuery(url, query);
- }
- }
-
-
- history.pushState({}, null, url);
- this.initial = null;
- this.changed();
- },
- changed: function(){
- this.listener.changed(location.pathname + location.search);
- },
- current: function(){
- return location.pathname + location.search;
- }
- };
-
- // end:source History.js
-
- function Location(collection, type) {
-
- this.collection = collection || new Routes();
-
- if (type) {
- var Constructor = type === 'hash'
- ? HashEmitter
- : HistoryEmitter
- ;
- this.emitter = new Constructor(this);
- }
-
- if (this.emitter == null)
- this.emitter = new HistoryEmitter(this);
-
- if (this.emitter == null)
- this.emitter = new HashEmitter(this);
-
- if (this.emitter == null)
- log_error('Router can not be initialized - (nor HistoryAPI / nor hashchange');
- }
-
- Location.prototype = {
-
- changed: function(path){
- var item = this.collection.get(path);
-
- if (item)
- this.action(item);
-
- },
- action: function(route){
- if (typeof route.value === 'function') {
- var current = route.current;
- route.value(route, current && current.params);
- }
- },
- navigate: function(url, opts){
- this.emitter.navigate(url, opts);
- },
- current: function(){
- return this.collection.get(
- this.currentPath()
- );
- },
- currentPath: function(){
- return this.emitter.current();
- }
- };
-
- return Location;
- }());
- // end:source ../src/emit/Location.js
-
- // source ../src/api/utils.js
- var ApiUtils = {
- /*
- * Format URI path from CLI command:
- * some action -foo bar === /some/action?foo=bar
- */
- pathFromCLI: path_fromCLI,
-
- query: {
- serialize: query_serialize,
- deserialize: query_deserialize,
- get: function(path_){
- var path = path_ == null
- ? location.search
- : path_;
- return path_getQuery(path);
- }
- }
- };
- // end:source ../src/api/utils.js
- // source ../src/ruta.js
- var routes = new Routes(),
- router;
-
- function router_ensure() {
- if (router == null)
- router = new Location(routes);
-
- return router;
- }
-
- var Ruta = {
-
- Collection: Routes,
-
- setRouterType: function(type){
- if (router == null)
- router = new Location(routes, type);
- return this;
- },
-
- setStrictBehaviour: function(isStrict){
- _cfg_isStrict = isStrict;
- return this;
- },
-
- add: function(regpath, mix){
- router_ensure();
- routes.add(regpath, mix);
- return this;
- },
-
- get: function(path){
- return routes.get(path);
- },
- navigate: function(mix, opts){
- var path = mix;
- if (mix != null && typeof mix === 'object') {
- path = '?' + query_serialize(mix, '&');
- }
- router_ensure().navigate(path, opts);
- return this;
- },
- current: function(){
- return router_ensure().current();
- },
- currentPath: function(){
- return router_ensure().currentPath();
- },
-
- notifyCurrent: function(){
- router_ensure().navigate();
- return this;
- },
-
- parse: Routes.parse,
-
- /*
- * @deprecated - use `_` instead
- */
- $utils: ApiUtils,
- _ : ApiUtils,
- };
-
-
-
- // end:source ../src/ruta.js
-
- // source ../src/mask/attr/anchor-dynamic.js
- (function() {
- if (mask == null) {
- return;
- }
-
- mask.registerAttrHandler('x-dynamic', function(node, value, model, ctx, tag){
- tag.onclick = navigate;
- }, 'client');
-
- function navigate(event) {
- event.preventDefault();
- event.stopPropagation();
-
- Ruta.navigate(this.href);
- }
- }());
-
- // end:source ../src/mask/attr/anchor-dynamic.js
-
- return Ruta;
-}));
\ No newline at end of file
diff --git a/examples/atmajs/node_modules/todomvc-app-css/index.css b/examples/atmajs/node_modules/todomvc-app-css/index.css
deleted file mode 100644
index d8be205ad4..0000000000
--- a/examples/atmajs/node_modules/todomvc-app-css/index.css
+++ /dev/null
@@ -1,376 +0,0 @@
-html,
-body {
- margin: 0;
- padding: 0;
-}
-
-button {
- margin: 0;
- padding: 0;
- border: 0;
- background: none;
- font-size: 100%;
- vertical-align: baseline;
- font-family: inherit;
- font-weight: inherit;
- color: inherit;
- -webkit-appearance: none;
- appearance: none;
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
-}
-
-body {
- font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
- line-height: 1.4em;
- background: #f5f5f5;
- color: #4d4d4d;
- min-width: 230px;
- max-width: 550px;
- margin: 0 auto;
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
- font-weight: 300;
-}
-
-:focus {
- outline: 0;
-}
-
-.hidden {
- display: none;
-}
-
-.todoapp {
- background: #fff;
- margin: 130px 0 40px 0;
- position: relative;
- box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2),
- 0 25px 50px 0 rgba(0, 0, 0, 0.1);
-}
-
-.todoapp input::-webkit-input-placeholder {
- font-style: italic;
- font-weight: 300;
- color: #e6e6e6;
-}
-
-.todoapp input::-moz-placeholder {
- font-style: italic;
- font-weight: 300;
- color: #e6e6e6;
-}
-
-.todoapp input::input-placeholder {
- font-style: italic;
- font-weight: 300;
- color: #e6e6e6;
-}
-
-.todoapp h1 {
- position: absolute;
- top: -155px;
- width: 100%;
- font-size: 100px;
- font-weight: 100;
- text-align: center;
- color: rgba(175, 47, 47, 0.15);
- -webkit-text-rendering: optimizeLegibility;
- -moz-text-rendering: optimizeLegibility;
- text-rendering: optimizeLegibility;
-}
-
-.new-todo,
-.edit {
- position: relative;
- margin: 0;
- width: 100%;
- font-size: 24px;
- font-family: inherit;
- font-weight: inherit;
- line-height: 1.4em;
- border: 0;
- color: inherit;
- padding: 6px;
- border: 1px solid #999;
- box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
- box-sizing: border-box;
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
-}
-
-.new-todo {
- padding: 16px 16px 16px 60px;
- border: none;
- background: rgba(0, 0, 0, 0.003);
- box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03);
-}
-
-.main {
- position: relative;
- z-index: 2;
- border-top: 1px solid #e6e6e6;
-}
-
-.toggle-all {
- text-align: center;
- border: none; /* Mobile Safari */
- opacity: 0;
- position: absolute;
-}
-
-.toggle-all + label {
- width: 60px;
- height: 34px;
- font-size: 0;
- position: absolute;
- top: -52px;
- left: -13px;
- -webkit-transform: rotate(90deg);
- transform: rotate(90deg);
-}
-
-.toggle-all + label:before {
- content: '❯';
- font-size: 22px;
- color: #e6e6e6;
- padding: 10px 27px 10px 27px;
-}
-
-.toggle-all:checked + label:before {
- color: #737373;
-}
-
-.todo-list {
- margin: 0;
- padding: 0;
- list-style: none;
-}
-
-.todo-list li {
- position: relative;
- font-size: 24px;
- border-bottom: 1px solid #ededed;
-}
-
-.todo-list li:last-child {
- border-bottom: none;
-}
-
-.todo-list li.editing {
- border-bottom: none;
- padding: 0;
-}
-
-.todo-list li.editing .edit {
- display: block;
- width: 506px;
- padding: 12px 16px;
- margin: 0 0 0 43px;
-}
-
-.todo-list li.editing .view {
- display: none;
-}
-
-.todo-list li .toggle {
- text-align: center;
- width: 40px;
- /* auto, since non-WebKit browsers doesn't support input styling */
- height: auto;
- position: absolute;
- top: 0;
- bottom: 0;
- margin: auto 0;
- border: none; /* Mobile Safari */
- -webkit-appearance: none;
- appearance: none;
-}
-
-.todo-list li .toggle {
- opacity: 0;
-}
-
-.todo-list li .toggle + label {
- /*
- Firefox requires `#` to be escaped - https://bugzilla.mozilla.org/show_bug.cgi?id=922433
- IE and Edge requires *everything* to be escaped to render, so we do that instead of just the `#` - https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7157459/
- */
- background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23ededed%22%20stroke-width%3D%223%22/%3E%3C/svg%3E');
- background-repeat: no-repeat;
- background-position: center left;
-}
-
-.todo-list li .toggle:checked + label {
- background-image: url('data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%2240%22%20height%3D%2240%22%20viewBox%3D%22-10%20-18%20100%20135%22%3E%3Ccircle%20cx%3D%2250%22%20cy%3D%2250%22%20r%3D%2250%22%20fill%3D%22none%22%20stroke%3D%22%23bddad5%22%20stroke-width%3D%223%22/%3E%3Cpath%20fill%3D%22%235dc2af%22%20d%3D%22M72%2025L42%2071%2027%2056l-4%204%2020%2020%2034-52z%22/%3E%3C/svg%3E');
-}
-
-.todo-list li label {
- word-break: break-all;
- padding: 15px 15px 15px 60px;
- display: block;
- line-height: 1.2;
- transition: color 0.4s;
-}
-
-.todo-list li.completed label {
- color: #d9d9d9;
- text-decoration: line-through;
-}
-
-.todo-list li .destroy {
- display: none;
- position: absolute;
- top: 0;
- right: 10px;
- bottom: 0;
- width: 40px;
- height: 40px;
- margin: auto 0;
- font-size: 30px;
- color: #cc9a9a;
- margin-bottom: 11px;
- transition: color 0.2s ease-out;
-}
-
-.todo-list li .destroy:hover {
- color: #af5b5e;
-}
-
-.todo-list li .destroy:after {
- content: '×';
-}
-
-.todo-list li:hover .destroy {
- display: block;
-}
-
-.todo-list li .edit {
- display: none;
-}
-
-.todo-list li.editing:last-child {
- margin-bottom: -1px;
-}
-
-.footer {
- color: #777;
- padding: 10px 15px;
- height: 20px;
- text-align: center;
- border-top: 1px solid #e6e6e6;
-}
-
-.footer:before {
- content: '';
- position: absolute;
- right: 0;
- bottom: 0;
- left: 0;
- height: 50px;
- overflow: hidden;
- box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2),
- 0 8px 0 -3px #f6f6f6,
- 0 9px 1px -3px rgba(0, 0, 0, 0.2),
- 0 16px 0 -6px #f6f6f6,
- 0 17px 2px -6px rgba(0, 0, 0, 0.2);
-}
-
-.todo-count {
- float: left;
- text-align: left;
-}
-
-.todo-count strong {
- font-weight: 300;
-}
-
-.filters {
- margin: 0;
- padding: 0;
- list-style: none;
- position: absolute;
- right: 0;
- left: 0;
-}
-
-.filters li {
- display: inline;
-}
-
-.filters li a {
- color: inherit;
- margin: 3px;
- padding: 3px 7px;
- text-decoration: none;
- border: 1px solid transparent;
- border-radius: 3px;
-}
-
-.filters li a:hover {
- border-color: rgba(175, 47, 47, 0.1);
-}
-
-.filters li a.selected {
- border-color: rgba(175, 47, 47, 0.2);
-}
-
-.clear-completed,
-html .clear-completed:active {
- float: right;
- position: relative;
- line-height: 20px;
- text-decoration: none;
- cursor: pointer;
-}
-
-.clear-completed:hover {
- text-decoration: underline;
-}
-
-.info {
- margin: 65px auto 0;
- color: #bfbfbf;
- font-size: 10px;
- text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
- text-align: center;
-}
-
-.info p {
- line-height: 1;
-}
-
-.info a {
- color: inherit;
- text-decoration: none;
- font-weight: 400;
-}
-
-.info a:hover {
- text-decoration: underline;
-}
-
-/*
- Hack to remove background from Mobile Safari.
- Can't use it globally since it destroys checkboxes in Firefox
-*/
-@media screen and (-webkit-min-device-pixel-ratio:0) {
- .toggle-all,
- .todo-list li .toggle {
- background: none;
- }
-
- .todo-list li .toggle {
- height: 40px;
- }
-}
-
-@media (max-width: 430px) {
- .footer {
- height: 50px;
- }
-
- .filters {
- bottom: 10px;
- }
-}
diff --git a/examples/atmajs/node_modules/todomvc-app-css/package.json b/examples/atmajs/node_modules/todomvc-app-css/package.json
deleted file mode 100644
index 203457cfec..0000000000
--- a/examples/atmajs/node_modules/todomvc-app-css/package.json
+++ /dev/null
@@ -1,59 +0,0 @@
-{
- "_from": "todomvc-app-css@^2.0.0",
- "_id": "todomvc-app-css@2.1.0",
- "_inBundle": false,
- "_integrity": "sha1-tvJxbTOa+i5feZNH0qSLBTliQqU=",
- "_location": "/todomvc-app-css",
- "_phantomChildren": {},
- "_requested": {
- "type": "range",
- "registry": true,
- "raw": "todomvc-app-css@^2.0.0",
- "name": "todomvc-app-css",
- "escapedName": "todomvc-app-css",
- "rawSpec": "^2.0.0",
- "saveSpec": null,
- "fetchSpec": "^2.0.0"
- },
- "_requiredBy": [
- "#USER",
- "/"
- ],
- "_resolved": "https://registry.npmjs.org/todomvc-app-css/-/todomvc-app-css-2.1.0.tgz",
- "_shasum": "b6f2716d339afa2e5f799347d2a48b05396242a5",
- "_spec": "todomvc-app-css@^2.0.0",
- "_where": "/private/tmp/todomvc/examples/atmajs",
- "author": {
- "name": "Sindre Sorhus",
- "email": "sindresorhus@gmail.com",
- "url": "sindresorhus.com"
- },
- "bugs": {
- "url": "https://github.com/tastejs/todomvc-app-css/issues"
- },
- "bundleDependencies": false,
- "deprecated": false,
- "description": "CSS for TodoMVC apps",
- "files": [
- "index.css"
- ],
- "homepage": "https://github.com/tastejs/todomvc-app-css#readme",
- "keywords": [
- "todomvc",
- "tastejs",
- "app",
- "todo",
- "template",
- "css",
- "style",
- "stylesheet"
- ],
- "license": "CC-BY-4.0",
- "name": "todomvc-app-css",
- "repository": {
- "type": "git",
- "url": "git+https://github.com/tastejs/todomvc-app-css.git"
- },
- "style": "index.css",
- "version": "2.1.0"
-}
diff --git a/examples/atmajs/node_modules/todomvc-app-css/readme.md b/examples/atmajs/node_modules/todomvc-app-css/readme.md
deleted file mode 100644
index 6ddbebf024..0000000000
--- a/examples/atmajs/node_modules/todomvc-app-css/readme.md
+++ /dev/null
@@ -1,28 +0,0 @@
-# todomvc-app-css
-
-> CSS for TodoMVC apps
-
-
-
-
-## Install
-
-
-```
-$ npm install --save todomvc-app-css
-```
-
-
-## Getting started
-
-```html
-
-```
-
-See the [TodoMVC app template](https://github.com/tastejs/todomvc-app-template).
-
-
-
-## License
-
- This work by Sindre Sorhus is licensed under a Creative Commons Attribution 4.0 International License .
diff --git a/examples/atmajs/node_modules/todomvc-common/base.css b/examples/atmajs/node_modules/todomvc-common/base.css
deleted file mode 100644
index da65968a73..0000000000
--- a/examples/atmajs/node_modules/todomvc-common/base.css
+++ /dev/null
@@ -1,141 +0,0 @@
-hr {
- margin: 20px 0;
- border: 0;
- border-top: 1px dashed #c5c5c5;
- border-bottom: 1px dashed #f7f7f7;
-}
-
-.learn a {
- font-weight: normal;
- text-decoration: none;
- color: #b83f45;
-}
-
-.learn a:hover {
- text-decoration: underline;
- color: #787e7e;
-}
-
-.learn h3,
-.learn h4,
-.learn h5 {
- margin: 10px 0;
- font-weight: 500;
- line-height: 1.2;
- color: #000;
-}
-
-.learn h3 {
- font-size: 24px;
-}
-
-.learn h4 {
- font-size: 18px;
-}
-
-.learn h5 {
- margin-bottom: 0;
- font-size: 14px;
-}
-
-.learn ul {
- padding: 0;
- margin: 0 0 30px 25px;
-}
-
-.learn li {
- line-height: 20px;
-}
-
-.learn p {
- font-size: 15px;
- font-weight: 300;
- line-height: 1.3;
- margin-top: 0;
- margin-bottom: 0;
-}
-
-#issue-count {
- display: none;
-}
-
-.quote {
- border: none;
- margin: 20px 0 60px 0;
-}
-
-.quote p {
- font-style: italic;
-}
-
-.quote p:before {
- content: '“';
- font-size: 50px;
- opacity: .15;
- position: absolute;
- top: -20px;
- left: 3px;
-}
-
-.quote p:after {
- content: '”';
- font-size: 50px;
- opacity: .15;
- position: absolute;
- bottom: -42px;
- right: 3px;
-}
-
-.quote footer {
- position: absolute;
- bottom: -40px;
- right: 0;
-}
-
-.quote footer img {
- border-radius: 3px;
-}
-
-.quote footer a {
- margin-left: 5px;
- vertical-align: middle;
-}
-
-.speech-bubble {
- position: relative;
- padding: 10px;
- background: rgba(0, 0, 0, .04);
- border-radius: 5px;
-}
-
-.speech-bubble:after {
- content: '';
- position: absolute;
- top: 100%;
- right: 30px;
- border: 13px solid transparent;
- border-top-color: rgba(0, 0, 0, .04);
-}
-
-.learn-bar > .learn {
- position: absolute;
- width: 272px;
- top: 8px;
- left: -300px;
- padding: 10px;
- border-radius: 5px;
- background-color: rgba(255, 255, 255, .6);
- transition-property: left;
- transition-duration: 500ms;
-}
-
-@media (min-width: 899px) {
- .learn-bar {
- width: auto;
- padding-left: 300px;
- }
-
- .learn-bar > .learn {
- left: 8px;
- }
-}
diff --git a/examples/atmajs/node_modules/todomvc-common/base.js b/examples/atmajs/node_modules/todomvc-common/base.js
deleted file mode 100644
index 3c6723f390..0000000000
--- a/examples/atmajs/node_modules/todomvc-common/base.js
+++ /dev/null
@@ -1,249 +0,0 @@
-/* global _ */
-(function () {
- 'use strict';
-
- /* jshint ignore:start */
- // Underscore's Template Module
- // Courtesy of underscorejs.org
- var _ = (function (_) {
- _.defaults = function (object) {
- if (!object) {
- return object;
- }
- for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {
- var iterable = arguments[argsIndex];
- if (iterable) {
- for (var key in iterable) {
- if (object[key] == null) {
- object[key] = iterable[key];
- }
- }
- }
- }
- return object;
- }
-
- // By default, Underscore uses ERB-style template delimiters, change the
- // following template settings to use alternative delimiters.
- _.templateSettings = {
- evaluate : /<%([\s\S]+?)%>/g,
- interpolate : /<%=([\s\S]+?)%>/g,
- escape : /<%-([\s\S]+?)%>/g
- };
-
- // When customizing `templateSettings`, if you don't want to define an
- // interpolation, evaluation or escaping regex, we need one that is
- // guaranteed not to match.
- var noMatch = /(.)^/;
-
- // Certain characters need to be escaped so that they can be put into a
- // string literal.
- var escapes = {
- "'": "'",
- '\\': '\\',
- '\r': 'r',
- '\n': 'n',
- '\t': 't',
- '\u2028': 'u2028',
- '\u2029': 'u2029'
- };
-
- var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
-
- // JavaScript micro-templating, similar to John Resig's implementation.
- // Underscore templating handles arbitrary delimiters, preserves whitespace,
- // and correctly escapes quotes within interpolated code.
- _.template = function(text, data, settings) {
- var render;
- settings = _.defaults({}, settings, _.templateSettings);
-
- // Combine delimiters into one regular expression via alternation.
- var matcher = new RegExp([
- (settings.escape || noMatch).source,
- (settings.interpolate || noMatch).source,
- (settings.evaluate || noMatch).source
- ].join('|') + '|$', 'g');
-
- // Compile the template source, escaping string literals appropriately.
- var index = 0;
- var source = "__p+='";
- text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
- source += text.slice(index, offset)
- .replace(escaper, function(match) { return '\\' + escapes[match]; });
-
- if (escape) {
- source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
- }
- if (interpolate) {
- source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
- }
- if (evaluate) {
- source += "';\n" + evaluate + "\n__p+='";
- }
- index = offset + match.length;
- return match;
- });
- source += "';\n";
-
- // If a variable is not specified, place data values in local scope.
- if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
-
- source = "var __t,__p='',__j=Array.prototype.join," +
- "print=function(){__p+=__j.call(arguments,'');};\n" +
- source + "return __p;\n";
-
- try {
- render = new Function(settings.variable || 'obj', '_', source);
- } catch (e) {
- e.source = source;
- throw e;
- }
-
- if (data) return render(data, _);
- var template = function(data) {
- return render.call(this, data, _);
- };
-
- // Provide the compiled function source as a convenience for precompilation.
- template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
-
- return template;
- };
-
- return _;
- })({});
-
- if (location.hostname === 'todomvc.com') {
- (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
- (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
- m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
- })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
- ga('create', 'UA-31081062-1', 'auto');
- ga('send', 'pageview');
- }
- /* jshint ignore:end */
-
- function redirect() {
- if (location.hostname === 'tastejs.github.io') {
- location.href = location.href.replace('tastejs.github.io/todomvc', 'todomvc.com');
- }
- }
-
- function findRoot() {
- var base = location.href.indexOf('examples/');
- return location.href.substr(0, base);
- }
-
- function getFile(file, callback) {
- if (!location.host) {
- return console.info('Miss the info bar? Run TodoMVC from a server to avoid a cross-origin error.');
- }
-
- var xhr = new XMLHttpRequest();
-
- xhr.open('GET', findRoot() + file, true);
- xhr.send();
-
- xhr.onload = function () {
- if (xhr.status === 200 && callback) {
- callback(xhr.responseText);
- }
- };
- }
-
- function Learn(learnJSON, config) {
- if (!(this instanceof Learn)) {
- return new Learn(learnJSON, config);
- }
-
- var template, framework;
-
- if (typeof learnJSON !== 'object') {
- try {
- learnJSON = JSON.parse(learnJSON);
- } catch (e) {
- return;
- }
- }
-
- if (config) {
- template = config.template;
- framework = config.framework;
- }
-
- if (!template && learnJSON.templates) {
- template = learnJSON.templates.todomvc;
- }
-
- if (!framework && document.querySelector('[data-framework]')) {
- framework = document.querySelector('[data-framework]').dataset.framework;
- }
-
- this.template = template;
-
- if (learnJSON.backend) {
- this.frameworkJSON = learnJSON.backend;
- this.frameworkJSON.issueLabel = framework;
- this.append({
- backend: true
- });
- } else if (learnJSON[framework]) {
- this.frameworkJSON = learnJSON[framework];
- this.frameworkJSON.issueLabel = framework;
- this.append();
- }
-
- this.fetchIssueCount();
- }
-
- Learn.prototype.append = function (opts) {
- var aside = document.createElement('aside');
- aside.innerHTML = _.template(this.template, this.frameworkJSON);
- aside.className = 'learn';
-
- if (opts && opts.backend) {
- // Remove demo link
- var sourceLinks = aside.querySelector('.source-links');
- var heading = sourceLinks.firstElementChild;
- var sourceLink = sourceLinks.lastElementChild;
- // Correct link path
- var href = sourceLink.getAttribute('href');
- sourceLink.setAttribute('href', href.substr(href.lastIndexOf('http')));
- sourceLinks.innerHTML = heading.outerHTML + sourceLink.outerHTML;
- } else {
- // Localize demo links
- var demoLinks = aside.querySelectorAll('.demo-link');
- Array.prototype.forEach.call(demoLinks, function (demoLink) {
- if (demoLink.getAttribute('href').substr(0, 4) !== 'http') {
- demoLink.setAttribute('href', findRoot() + demoLink.getAttribute('href'));
- }
- });
- }
-
- document.body.className = (document.body.className + ' learn-bar').trim();
- document.body.insertAdjacentHTML('afterBegin', aside.outerHTML);
- };
-
- Learn.prototype.fetchIssueCount = function () {
- var issueLink = document.getElementById('issue-count-link');
- if (issueLink) {
- var url = issueLink.href.replace('https://github.com', 'https://api.github.com/repos');
- var xhr = new XMLHttpRequest();
- xhr.open('GET', url, true);
- xhr.onload = function (e) {
- var parsedResponse = JSON.parse(e.target.responseText);
- if (parsedResponse instanceof Array) {
- var count = parsedResponse.length;
- if (count !== 0) {
- issueLink.innerHTML = 'This app has ' + count + ' open issues';
- document.getElementById('issue-count').style.display = 'inline';
- }
- }
- };
- xhr.send();
- }
- };
-
- redirect();
- getFile('learn.json', Learn);
-})();
diff --git a/examples/atmajs/package.json b/examples/atmajs/package.json
deleted file mode 100644
index e5239447ec..0000000000
--- a/examples/atmajs/package.json
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "private": true,
- "dependencies": {
- "atma-class": "^1.1.69",
- "includejs": "^0.9.14",
- "maskjs": "^0.52.0",
- "ruta": "^0.1.16",
- "todomvc-app-css": "^2.0.1",
- "todomvc-common": "^1.0.2"
- }
-}
diff --git a/examples/atmajs/readme.md b/examples/atmajs/readme.md
deleted file mode 100644
index bb15864399..0000000000
--- a/examples/atmajs/readme.md
+++ /dev/null
@@ -1,124 +0,0 @@
-# Atma.js TodoMVC Example
-
-> Fast, elegant and component oriented framework for desktops, mobiles or servers _(Node.js)_
-> _[Atma - atmajs.com](http://atmajs.com)_
-
-The framework consists of several stand-alone libraries. This approach not only reduces barriers to entry, but also
-allows developers to exclude or replace any library with other third party one.
-
-The goal of the framework is to deliver the component-based development and to provide libraries for making their composition easily and with blazing fast performance _(even on mobile CPUs)_.
-
-## Learning Atma.js
-
-#### ClassJS
-[web-page](http://atmajs.com/class) [GitHub](http://github.com/atmajs/ClassJS)
-
-— is a class-model implementation. A business logic layer for applications. It accumulates best practices of the OOP and supports model de-/serialization with the persistence to localStorage, RESTful service or MongoDB. Any additional adapter can be created by the developer.
-
-
-#### MaskJS
-[web-page](http://atmajs.com/mask) [GitHub](https://github.com/atmajs/MaskJS)
-
-— is the core library of the Atma.js framework. It brings HMVC engine into play and everything starts with the markup. Along HTML, more compact and component-oriented syntax can be used, which is similar to LESS and Zen Coding. But not the syntax is the advantage of the mask markup, but the DOM creation approach. Mask or HTML templates are prarsed to the tiny MaskDOM AST. And while traversing the MaskDOM, the builder creates DOM Elements and initializes components. As the MaskDom structure is extremely lightweight, each component can easily manipulate the MaskDOM. So the all dynamic behavior, like interpolation, 1-/2way-binding, component's nesting and many other things, are almost for free in sens of the performance. Beyond fast DOM creation there are other distinguishing features:
-
-- model agnostic
-- components hierarchy
- - better referencing via `find/closest` search _in a jQuery way)_
- - better communication via signals and slots. _Piped-signals are used to bind components, that are not in ascendant-descendant relation, but anywhere in an app_
-- one-/two-way bindings with complex object observers, so even if deep, nested path to the property is used, any manipulations with the model preserve observers in place
-- modules. Can load: Mask, Html, Javascript, Css, Json
-- custom attribute handlers
-- designed to be used with other libraries. For example, with small wrappers we can encapsulate twitter bootstrap markups and widgets initializations
-- high code reuse
-
-To mention is, that the templates and the components can be rendered on the server side.
-
-
-#### IncludeJS
-[web-page](http://atmajs.com/include) [GitHub](https://github.com/atmajs/IncludeJS)
-
-— is created to load component's resources and to work in browsers and Node.js the same way.
-
-Some key points of the library are:
-
-- no requirements for the module definition, but supports several: CommonJS and `include.exports`
-- in-place dependency declaration with nice namespaced routing
-- custom loaders. _Already implemented `coffee, less, yml, json`_
-- lazy modules
-- better debugging: loads javascript in browsers via `script src='x'`
-- for production builder can combine and optimize all resources into single `*.js` and single `*.css`. All the templates are embedded into main `*.html`. _Developing a web page using Atma Node.js application module, builder also creates additionally single js/css/html files per page from the components that are specific to a page_
-
-
-##### µTest
-[GitHub](https://github.com/atmajs/utest)
-
-— Simplifies unit-test creation and runs them in Node.js or in browser-slave(s) environments. All the Atma.js libraries are tested using the µTest.
-
-##### DomTest
-[GitHub](https://github.com/atmajs/domtest)
-
-The module is embedded into the µTest library and allows the developer to easily write test suites for the UI using MaskJS syntax.
-
-##### Ruta
-[GitHub](https://github.com/atmajs/Ruta)
-
-— is not only an url routing via History API or `hashchange`, but it implements a Route-Value Collection for adding/retrieving any object by the route.
-
-#### Atma.Toolkit
-[GitHub](https://github.com/atmajs/Atma.Toolkit)
-
-— command-line tool, which runs unit tests, builds applications, runs Node.js `bash` scripts, creates static file server with live reload feature, etc.
-
-### Mask.Animation
-[GitHub](https://github.com/atmajs/mask-animation)
-
-— CSS3 and sprite animations for MaskJS.
-
-
-### Atma.js Server Application
-[web-page](http://atmajs.com/atma-server) [GitHub](https://github.com/atmajs/atma-server)
-
-— a connect middle-ware. All the routes are declared in configuration files, and there are 3 types of endpoints:
-
-- Handlers
-- RESTful services
-- Pages
-
-Pages benefits from component based approach. Each component's controller can define caching settings, so that the component renders only once. Developer can restrict any component for the server side rendering only, so that the controller itself and any sensitive data is not sent to the client. When a component is rendered, then only HTML is sent to the client, _where all bindings and event listeners are attached_. So it is extremely SEO friendly.
-
-Here are some links you may find helpful:
-
-- [Get Started](http://atmajs.com/get/github)
-- [Mask Markup Live Test](http://atmajs.com/mask-try)
-- Mask Syntax Plugins
- - [Sublime](https://github.com/tenbits/sublime-mask)
- - [Atom](https://github.com/tenbits/package-atom)
-
-- [Atma.js on GitHub](https://github.com/atmajs)
-
-_If you have other helpful links to share, or find any of the links above no longer work, please [let us know](https://github.com/tastejs/todomvc/issues)._
-
-### Implementation
-
-The Application is split into components hierarchy, and so the application structure consists of a component and a business logic Layer. Components have the resources (_that are component specific, like styles / templates and other nested components_) in the same or a sub-folder. These makes it easer to _reuse_ them in other applications and makes it easer to develop and test them. Atma.js is not a opinionated, but extremely flexible framework, so that the developer can choose the way he wants to structure the applications architecture. This demo application just demonstrates one possible way.
-
-### Run
-
-Open `index.html` as a file in browser or run a static server:
-
-```bash
-# install atma.toolkit
-$ npm install atma --global
-$ atma server
-```
-
-navigate to `http://localhost:5777/`
-
-### Build
-
-To build the application for release, run `$ atma build --file index.html --output release/`.
-
-
-## Contact
-- [team@atmajs.com](mailto:team@atmajs.com)
-- [Google Group QA](https://groups.google.com/forum/#!forum/atmajs)
diff --git a/examples/chaplin-brunch/.editorconfig b/examples/chaplin-brunch/.editorconfig
deleted file mode 100644
index f4eb7985f7..0000000000
--- a/examples/chaplin-brunch/.editorconfig
+++ /dev/null
@@ -1,6 +0,0 @@
-# editorconfig.org
-root = true
-
-[*.coffee]
-indent_style = space
-indent_size = 2
diff --git a/examples/chaplin-brunch/.gitignore b/examples/chaplin-brunch/.gitignore
deleted file mode 100644
index c56daf338c..0000000000
--- a/examples/chaplin-brunch/.gitignore
+++ /dev/null
@@ -1,25 +0,0 @@
-node_modules/chaplin/*
-!node_modules/chaplin/chaplin.js
-
-node_modules/exoskeleton/*
-!node_modules/exoskeleton/exoskeleton.js
-
-node_modules/backbone.localstorage/*
-!node_modules/backbone.localstorage/backbone.localStorage.js
-
-node_modules/backbone.nativeview/*
-!node_modules/backbone.nativeview/backbone.nativeview.js
-
-node_modules/todomvc-app-css/*
-!node_modules/todomvc-app-css/index.css
-
-node_modules/todomvc-common/*
-!node_modules/todomvc-common/base.css
-!node_modules/todomvc-common/base.js
-
-node_modules/coffee-script-brunch/*
-node_modules/javascript-brunch/*
-node_modules/handlebars-brunch/*
-node_modules/uglify-js-brunch/*
-
-tmp/*
diff --git a/examples/chaplin-brunch/app/application.coffee b/examples/chaplin-brunch/app/application.coffee
deleted file mode 100644
index 70c016009a..0000000000
--- a/examples/chaplin-brunch/app/application.coffee
+++ /dev/null
@@ -1,21 +0,0 @@
-mediator = require 'mediator'
-Todos = require 'models/todos'
-
-# The application object
-module.exports = class Application extends Chaplin.Application
- # Set your application name here so the document title is set to
- # “Controller title – Site title” (see Layout#adjustTitle)
- title: 'Chaplin • TodoMVC'
-
- # Create additional mediator properties
- # -------------------------------------
- initMediator: ->
- # Add additional application-specific properties and methods
- mediator.todos = new Todos()
- # Seal the mediator
- super
-
- start: ->
- # If todos are fetched from server, we will need to wait for them.
- mediator.todos.fetch()
- super
diff --git a/examples/chaplin-brunch/app/assets/index.html b/examples/chaplin-brunch/app/assets/index.html
deleted file mode 100644
index d5609b7dd7..0000000000
--- a/examples/chaplin-brunch/app/assets/index.html
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
-
- Chaplin & Brunch • TodoMVC
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/examples/chaplin-brunch/app/controllers/index-controller.coffee b/examples/chaplin-brunch/app/controllers/index-controller.coffee
deleted file mode 100644
index 0bf4ffcb18..0000000000
--- a/examples/chaplin-brunch/app/controllers/index-controller.coffee
+++ /dev/null
@@ -1,25 +0,0 @@
-HeaderView = require '../views/header-view'
-FooterView = require '../views/footer-view'
-TodosView = require '../views/todos-view'
-mediator = require 'mediator'
-
-module.exports = class IndexController extends Chaplin.Controller
- # The method is executed before any controller actions.
- # We compose structure in order for it to be rendered only once.
- beforeAction: ->
- @reuse 'structure', ->
- params = collection: mediator.todos
- @header = new HeaderView params
- @footer = new FooterView params
-
- # On each new load, old @view will be disposed and
- # new @view will be created. This is idiomatic Chaplin memory management:
- # one controller per screen.
- list: (params) ->
- filterer = params.filterer?.trim() ? 'all'
- @publishEvent 'todos:filter', filterer
- @view = new TodosView collection: mediator.todos, filterer: (model) ->
- switch filterer
- when 'completed' then model.get('completed')
- when 'active' then not model.get('completed')
- else true
diff --git a/examples/chaplin-brunch/app/initialize.coffee b/examples/chaplin-brunch/app/initialize.coffee
deleted file mode 100644
index f08a80c37f..0000000000
--- a/examples/chaplin-brunch/app/initialize.coffee
+++ /dev/null
@@ -1,8 +0,0 @@
-Application = require 'application'
-routes = require 'routes'
-
-# Initialize the application on DOM ready event.
-document.addEventListener 'DOMContentLoaded', ->
- new Application
- controllerSuffix: '-controller', pushState: false, routes: routes
-, false
diff --git a/examples/chaplin-brunch/app/lib/utils.coffee b/examples/chaplin-brunch/app/lib/utils.coffee
deleted file mode 100644
index a58de10ae6..0000000000
--- a/examples/chaplin-brunch/app/lib/utils.coffee
+++ /dev/null
@@ -1,14 +0,0 @@
-# Application-specific utilities
-# ------------------------------
-
-# Delegate to Chaplin’s utils module.
-utils = Chaplin.utils.beget Chaplin.utils
-
-Backbone.utils.extend utils,
- toggle: (elem, visible) ->
- elem.style.display = (if visible then '' else 'none')
-
-# Prevent creating new properties and stuff.
-Object.seal? utils
-
-module.exports = utils
diff --git a/examples/chaplin-brunch/app/mediator.coffee b/examples/chaplin-brunch/app/mediator.coffee
deleted file mode 100644
index e86d741e3d..0000000000
--- a/examples/chaplin-brunch/app/mediator.coffee
+++ /dev/null
@@ -1 +0,0 @@
-module.exports = Chaplin.mediator
diff --git a/examples/chaplin-brunch/app/models/todo.coffee b/examples/chaplin-brunch/app/models/todo.coffee
deleted file mode 100644
index 40fa0d38ed..0000000000
--- a/examples/chaplin-brunch/app/models/todo.coffee
+++ /dev/null
@@ -1,18 +0,0 @@
-# It is a very good idea to have base Model / Collection
-# e.g. Model = require 'models/base/model'
-# But in this particular app since we only have one
-# model type, we will inherit directly from Chaplin Model.
-module.exports = class Todo extends Chaplin.Model
- defaults:
- title: ''
- completed: no
-
- initialize: ->
- super
- @set 'created', Date.now() if @isNew()
-
- toggle: ->
- @set completed: not @get('completed')
-
- isVisible: ->
- isCompleted = @get('completed')
diff --git a/examples/chaplin-brunch/app/models/todos.coffee b/examples/chaplin-brunch/app/models/todos.coffee
deleted file mode 100644
index a59f2e6c07..0000000000
--- a/examples/chaplin-brunch/app/models/todos.coffee
+++ /dev/null
@@ -1,17 +0,0 @@
-Todo = require 'models/todo'
-
-module.exports = class Todos extends Chaplin.Collection
- model: Todo
- localStorage: new Store 'todos-chaplin'
-
- allAreCompleted: ->
- @getCompleted().length is @length
-
- getCompleted: ->
- @where completed: yes
-
- getActive: ->
- @where completed: no
-
- comparator: (todo) ->
- todo.get('created')
diff --git a/examples/chaplin-brunch/app/routes.coffee b/examples/chaplin-brunch/app/routes.coffee
deleted file mode 100644
index 34fbc6b64c..0000000000
--- a/examples/chaplin-brunch/app/routes.coffee
+++ /dev/null
@@ -1,3 +0,0 @@
-module.exports = (match) ->
- match ':filterer', 'index#list'
- match '', 'index#list'
diff --git a/examples/chaplin-brunch/app/views/base/collection-view.coffee b/examples/chaplin-brunch/app/views/base/collection-view.coffee
deleted file mode 100644
index ecd5faf0ef..0000000000
--- a/examples/chaplin-brunch/app/views/base/collection-view.coffee
+++ /dev/null
@@ -1,7 +0,0 @@
-View = require 'views/base/view'
-
-module.exports = class CollectionView extends Chaplin.CollectionView
- # This class doesn’t inherit from the application-specific View class,
- # so we need to borrow the method from the View prototype:
- getTemplateFunction: View::getTemplateFunction
- useCssAnimation: true
diff --git a/examples/chaplin-brunch/app/views/base/view.coffee b/examples/chaplin-brunch/app/views/base/view.coffee
deleted file mode 100644
index b38d99e3ab..0000000000
--- a/examples/chaplin-brunch/app/views/base/view.coffee
+++ /dev/null
@@ -1,4 +0,0 @@
-module.exports = class View extends Chaplin.View
- # Precompiled templates function initializer.
- getTemplateFunction: ->
- @template
diff --git a/examples/chaplin-brunch/app/views/footer-view.coffee b/examples/chaplin-brunch/app/views/footer-view.coffee
deleted file mode 100644
index 5c0e9d1bdf..0000000000
--- a/examples/chaplin-brunch/app/views/footer-view.coffee
+++ /dev/null
@@ -1,39 +0,0 @@
-View = require './base/view'
-utils = require 'lib/utils'
-
-module.exports = class FooterView extends View
- autoRender: true
- el: '#footer'
- events:
- 'click #clear-completed': 'clearCompleted'
- listen:
- 'todos:filter mediator': 'updateFilterer'
- 'all collection': 'renderCounter'
- template: require './templates/footer'
-
- render: ->
- super
- @renderCounter()
-
- updateFilterer: (filterer) ->
- filterer = '' if filterer is 'all'
- selector = "[href='#/#{filterer}']"
- cls = 'selected'
- @findAll('#filters a').forEach (link) =>
- link.classList.remove cls
- link.classList.add cls if Backbone.utils.matchesSelector link, selector
-
- renderCounter: ->
- total = @collection.length
- active = @collection.getActive().length
- completed = @collection.getCompleted().length
-
- @find('#todo-count > strong').textContent = active
- countDescription = (if active is 1 then 'item' else 'items')
- @find('.todo-count-title').textContent = countDescription
-
- utils.toggle @find('#clear-completed'), completed > 0
- utils.toggle @el, total > 0
-
- clearCompleted: ->
- @publishEvent 'todos:clear'
diff --git a/examples/chaplin-brunch/app/views/header-view.coffee b/examples/chaplin-brunch/app/views/header-view.coffee
deleted file mode 100644
index 73cbdc4915..0000000000
--- a/examples/chaplin-brunch/app/views/header-view.coffee
+++ /dev/null
@@ -1,15 +0,0 @@
-View = require './base/view'
-
-module.exports = class HeaderView extends View
- autoRender: true
- el: '#header'
- events:
- 'keypress #new-todo': 'createOnEnter'
- template: require './templates/header'
-
- createOnEnter: (event) ->
- ENTER_KEY = 13
- title = event.delegateTarget.value.trim()
- return if event.keyCode isnt ENTER_KEY or not title
- @collection.create {title}
- @find('#new-todo').value = ''
diff --git a/examples/chaplin-brunch/app/views/templates/footer.hbs b/examples/chaplin-brunch/app/views/templates/footer.hbs
deleted file mode 100644
index 2869ed1cde..0000000000
--- a/examples/chaplin-brunch/app/views/templates/footer.hbs
+++ /dev/null
@@ -1,17 +0,0 @@
-
-
- items
- left
-
-
-Clear completed
diff --git a/examples/chaplin-brunch/app/views/templates/header.hbs b/examples/chaplin-brunch/app/views/templates/header.hbs
deleted file mode 100644
index 8b235ae18d..0000000000
--- a/examples/chaplin-brunch/app/views/templates/header.hbs
+++ /dev/null
@@ -1,2 +0,0 @@
-todos
-
diff --git a/examples/chaplin-brunch/app/views/templates/todo.hbs b/examples/chaplin-brunch/app/views/templates/todo.hbs
deleted file mode 100644
index ffe17da100..0000000000
--- a/examples/chaplin-brunch/app/views/templates/todo.hbs
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
- {{title}}
-
-
-
diff --git a/examples/chaplin-brunch/app/views/templates/todos.hbs b/examples/chaplin-brunch/app/views/templates/todos.hbs
deleted file mode 100644
index 51920bdf69..0000000000
--- a/examples/chaplin-brunch/app/views/templates/todos.hbs
+++ /dev/null
@@ -1,3 +0,0 @@
-
-Mark all as complete
-
diff --git a/examples/chaplin-brunch/app/views/todo-view.coffee b/examples/chaplin-brunch/app/views/todo-view.coffee
deleted file mode 100644
index ccd29710f5..0000000000
--- a/examples/chaplin-brunch/app/views/todo-view.coffee
+++ /dev/null
@@ -1,43 +0,0 @@
-View = require './base/view'
-
-module.exports = class TodoView extends View
- events:
- 'click .toggle': 'toggle'
- 'dblclick label': 'edit'
- 'keyup .edit': 'save'
- 'focusout .edit': 'save'
- 'click .destroy': 'clear'
-
- listen:
- 'change model': 'render'
-
- template: require './templates/todo'
- tagName: 'li'
-
- render: ->
- super
- @toggleClass()
-
- toggleClass: ->
- isCompleted = @model.get('completed')
- @el.classList.toggle 'completed', isCompleted
-
- clear: ->
- @model.destroy()
-
- toggle: ->
- @model.toggle().save()
-
- edit: ->
- @el.classList.add 'editing'
- input = @find('.edit')
- input.focus()
- input.value = input.value;
-
- save: (event) ->
- ENTER_KEY = 13
- title = event.delegateTarget.value.trim()
- return @model.destroy() unless title
- return if event.type is 'keyup' and event.keyCode isnt ENTER_KEY
- @model.save {title}
- @el.classList.remove 'editing'
diff --git a/examples/chaplin-brunch/app/views/todos-view.coffee b/examples/chaplin-brunch/app/views/todos-view.coffee
deleted file mode 100644
index 7d9290cdbf..0000000000
--- a/examples/chaplin-brunch/app/views/todos-view.coffee
+++ /dev/null
@@ -1,30 +0,0 @@
-CollectionView = require './base/collection-view'
-TodoView = require './todo-view'
-utils = require 'lib/utils'
-
-module.exports = class TodosView extends CollectionView
- container: '#main'
- events:
- 'click #toggle-all': 'toggleCompleted'
- itemView: TodoView
- listSelector: '#todo-list'
- listen:
- 'all collection': 'renderCheckbox'
- 'todos:clear mediator': 'clear'
- template: require './templates/todos'
-
- render: ->
- super
- @renderCheckbox()
-
- renderCheckbox: ->
- @find('#toggle-all').checked = @collection.allAreCompleted()
- utils.toggle @el, @collection.length isnt 0
-
- toggleCompleted: (event) ->
- isChecked = event.delegateTarget.checked
- @collection.forEach (todo) -> todo.save completed: isChecked
-
- clear: ->
- @collection.getCompleted().forEach (model) ->
- model.destroy()
diff --git a/examples/chaplin-brunch/config.coffee b/examples/chaplin-brunch/config.coffee
deleted file mode 100644
index ca8abe40c4..0000000000
--- a/examples/chaplin-brunch/config.coffee
+++ /dev/null
@@ -1,13 +0,0 @@
-exports.config =
- # See http://brunch.readthedocs.org/en/latest/config.html for documentation.
- files:
- javascripts:
- joinTo:
- 'app.js': /^app/
- 'vendor.js': /^vendor/
-
- stylesheets:
- joinTo: 'app.css'
-
- templates:
- joinTo: 'app.js'
diff --git a/examples/chaplin-brunch/node_modules/backbone.localstorage/backbone.localStorage.js b/examples/chaplin-brunch/node_modules/backbone.localstorage/backbone.localStorage.js
deleted file mode 100644
index 6365ecefa5..0000000000
--- a/examples/chaplin-brunch/node_modules/backbone.localstorage/backbone.localStorage.js
+++ /dev/null
@@ -1,258 +0,0 @@
-/**
- * Backbone localStorage Adapter
- * Version 1.1.16
- *
- * https://github.com/jeromegn/Backbone.localStorage
- */
-(function (root, factory) {
- if (typeof exports === 'object' && typeof require === 'function') {
- module.exports = factory(require("backbone"));
- } else if (typeof define === "function" && define.amd) {
- // AMD. Register as an anonymous module.
- define(["backbone"], function(Backbone) {
- // Use global variables if the locals are undefined.
- return factory(Backbone || root.Backbone);
- });
- } else {
- factory(Backbone);
- }
-}(this, function(Backbone) {
-// A simple module to replace `Backbone.sync` with *localStorage*-based
-// persistence. Models are given GUIDS, and saved into a JSON object. Simple
-// as that.
-
-// Generate four random hex digits.
-function S4() {
- return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
-};
-
-// Generate a pseudo-GUID by concatenating random hexadecimal.
-function guid() {
- return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
-};
-
-function isObject(item) {
- return item === Object(item);
-}
-
-function contains(array, item) {
- var i = array.length;
- while (i--) if (array[i] === item) return true;
- return false;
-}
-
-function extend(obj, props) {
- for (var key in props) obj[key] = props[key]
- return obj;
-}
-
-function result(object, property) {
- if (object == null) return void 0;
- var value = object[property];
- return (typeof value === 'function') ? object[property]() : value;
-}
-
-// Our Store is represented by a single JS object in *localStorage*. Create it
-// with a meaningful name, like the name you'd give a table.
-// window.Store is deprectated, use Backbone.LocalStorage instead
-Backbone.LocalStorage = window.Store = function(name, serializer) {
- if( !this.localStorage ) {
- throw "Backbone.localStorage: Environment does not support localStorage."
- }
- this.name = name;
- this.serializer = serializer || {
- serialize: function(item) {
- return isObject(item) ? JSON.stringify(item) : item;
- },
- // fix for "illegal access" error on Android when JSON.parse is passed null
- deserialize: function (data) {
- return data && JSON.parse(data);
- }
- };
- var store = this.localStorage().getItem(this.name);
- this.records = (store && store.split(",")) || [];
-};
-
-extend(Backbone.LocalStorage.prototype, {
-
- // Save the current state of the **Store** to *localStorage*.
- save: function() {
- this.localStorage().setItem(this.name, this.records.join(","));
- },
-
- // Add a model, giving it a (hopefully)-unique GUID, if it doesn't already
- // have an id of it's own.
- create: function(model) {
- if (!model.id && model.id !== 0) {
- model.id = guid();
- model.set(model.idAttribute, model.id);
- }
- this.localStorage().setItem(this._itemName(model.id), this.serializer.serialize(model));
- this.records.push(model.id.toString());
- this.save();
- return this.find(model);
- },
-
- // Update a model by replacing its copy in `this.data`.
- update: function(model) {
- this.localStorage().setItem(this._itemName(model.id), this.serializer.serialize(model));
- var modelId = model.id.toString();
- if (!contains(this.records, modelId)) {
- this.records.push(modelId);
- this.save();
- }
- return this.find(model);
- },
-
- // Retrieve a model from `this.data` by id.
- find: function(model) {
- return this.serializer.deserialize(this.localStorage().getItem(this._itemName(model.id)));
- },
-
- // Return the array of all models currently in storage.
- findAll: function() {
- var result = [];
- for (var i = 0, id, data; i < this.records.length; i++) {
- id = this.records[i];
- data = this.serializer.deserialize(this.localStorage().getItem(this._itemName(id)));
- if (data != null) result.push(data);
- }
- return result;
- },
-
- // Delete a model from `this.data`, returning it.
- destroy: function(model) {
- this.localStorage().removeItem(this._itemName(model.id));
- var modelId = model.id.toString();
- for (var i = 0, id; i < this.records.length; i++) {
- if (this.records[i] === modelId) {
- this.records.splice(i, 1);
- }
- }
- this.save();
- return model;
- },
-
- localStorage: function() {
- return localStorage;
- },
-
- // Clear localStorage for specific collection.
- _clear: function() {
- var local = this.localStorage(),
- itemRe = new RegExp("^" + this.name + "-");
-
- // Remove id-tracking item (e.g., "foo").
- local.removeItem(this.name);
-
- // Match all data items (e.g., "foo-ID") and remove.
- for (var k in local) {
- if (itemRe.test(k)) {
- local.removeItem(k);
- }
- }
-
- this.records.length = 0;
- },
-
- // Size of localStorage.
- _storageSize: function() {
- return this.localStorage().length;
- },
-
- _itemName: function(id) {
- return this.name+"-"+id;
- }
-
-});
-
-// localSync delegate to the model or collection's
-// *localStorage* property, which should be an instance of `Store`.
-// window.Store.sync and Backbone.localSync is deprecated, use Backbone.LocalStorage.sync instead
-Backbone.LocalStorage.sync = window.Store.sync = Backbone.localSync = function(method, model, options) {
- var store = result(model, 'localStorage') || result(model.collection, 'localStorage');
-
- var resp, errorMessage;
- //If $ is having Deferred - use it.
- var syncDfd = Backbone.$ ?
- (Backbone.$.Deferred && Backbone.$.Deferred()) :
- (Backbone.Deferred && Backbone.Deferred());
-
- try {
-
- switch (method) {
- case "read":
- resp = model.id != undefined ? store.find(model) : store.findAll();
- break;
- case "create":
- resp = store.create(model);
- break;
- case "update":
- resp = store.update(model);
- break;
- case "delete":
- resp = store.destroy(model);
- break;
- }
-
- } catch(error) {
- if (error.code === 22 && store._storageSize() === 0)
- errorMessage = "Private browsing is unsupported";
- else
- errorMessage = error.message;
- }
-
- if (resp) {
- if (options && options.success) {
- if (Backbone.VERSION === "0.9.10") {
- options.success(model, resp, options);
- } else {
- options.success(resp);
- }
- }
- if (syncDfd) {
- syncDfd.resolve(resp);
- }
-
- } else {
- errorMessage = errorMessage ? errorMessage
- : "Record Not Found";
-
- if (options && options.error)
- if (Backbone.VERSION === "0.9.10") {
- options.error(model, errorMessage, options);
- } else {
- options.error(errorMessage);
- }
-
- if (syncDfd)
- syncDfd.reject(errorMessage);
- }
-
- // add compatibility with $.ajax
- // always execute callback for success and error
- if (options && options.complete) options.complete(resp);
-
- return syncDfd && syncDfd.promise();
-};
-
-Backbone.ajaxSync = Backbone.sync;
-
-Backbone.getSyncMethod = function(model, options) {
- var forceAjaxSync = options && options.ajaxSync;
-
- if(!forceAjaxSync && (result(model, 'localStorage') || result(model.collection, 'localStorage'))) {
- return Backbone.localSync;
- }
-
- return Backbone.ajaxSync;
-};
-
-// Override 'Backbone.sync' to default to localSync,
-// the original 'Backbone.sync' is still available in 'Backbone.ajaxSync'
-Backbone.sync = function(method, model, options) {
- return Backbone.getSyncMethod(model, options).apply(this, [method, model, options]);
-};
-
-return Backbone.LocalStorage;
-}));
diff --git a/examples/chaplin-brunch/node_modules/backbone.nativeview/backbone.nativeview.js b/examples/chaplin-brunch/node_modules/backbone.nativeview/backbone.nativeview.js
deleted file mode 100644
index 476c438b1c..0000000000
--- a/examples/chaplin-brunch/node_modules/backbone.nativeview/backbone.nativeview.js
+++ /dev/null
@@ -1,169 +0,0 @@
-// Backbone.NativeView.js 0.3.2
-// ---------------
-
-// (c) 2014 Adam Krebs, Jimmy Yuen Ho Wong
-// Backbone.NativeView may be freely distributed under the MIT license.
-// For all details and documentation:
-// https://github.com/akre54/Backbone.NativeView
-
-(function (factory) {
- if (typeof define === 'function' && define.amd) { define(['backbone'], factory);
- } else if (typeof exports === 'object') { factory(require('backbone'));
- } else { factory(Backbone); }
-}(function (Backbone) {
- // Cached regex to match an opening '<' of an HTML tag, possibly left-padded
- // with whitespace.
- var paddedLt = /^\s*;
-
- // Caches a local reference to `Element.prototype` for faster access.
- var ElementProto = (typeof Element !== 'undefined' && Element.prototype) || {};
-
- // Cross-browser event listener shims
- var elementAddEventListener = ElementProto.addEventListener || function(eventName, listener) {
- return this.attachEvent('on' + eventName, listener);
- }
- var elementRemoveEventListener = ElementProto.removeEventListener || function(eventName, listener) {
- return this.detachEvent('on' + eventName, listener);
- }
-
- var indexOf = function(array, item) {
- for (var i = 0, len = array.length; i < len; i++) if (array[i] === item) return i;
- return -1;
- }
-
- // Find the right `Element#matches` for IE>=9 and modern browsers.
- var matchesSelector = ElementProto.matches ||
- ElementProto.webkitMatchesSelector ||
- ElementProto.mozMatchesSelector ||
- ElementProto.msMatchesSelector ||
- ElementProto.oMatchesSelector ||
- // Make our own `Element#matches` for IE8
- function(selector) {
- // Use querySelectorAll to find all elements matching the selector,
- // then check if the given element is included in that list.
- // Executing the query on the parentNode reduces the resulting nodeList,
- // (document doesn't have a parentNode).
- var nodeList = (this.parentNode || document).querySelectorAll(selector) || [];
- return !!~indexOf(nodeList, this);
- };
-
- // Cache Backbone.View for later access in constructor
- var BBView = Backbone.View;
-
- // To extend an existing view to use native methods, extend the View prototype
- // with the mixin: _.extend(MyView.prototype, Backbone.NativeViewMixin);
- Backbone.NativeViewMixin = {
-
- _domEvents: null,
-
- constructor: function() {
- this._domEvents = [];
- return BBView.apply(this, arguments);
- },
-
- $: function(selector) {
- return this.el.querySelectorAll(selector);
- },
-
- _removeElement: function() {
- this.undelegateEvents();
- if (this.el.parentNode) this.el.parentNode.removeChild(this.el);
- },
-
- // Apply the `element` to the view. `element` can be a CSS selector,
- // a string of HTML, or an Element node.
- _setElement: function(element) {
- if (typeof element == 'string') {
- if (paddedLt.test(element)) {
- var el = document.createElement('div');
- el.innerHTML = element;
- this.el = el.firstChild;
- } else {
- this.el = document.querySelector(element);
- }
- } else {
- this.el = element;
- }
- },
-
- // Set a hash of attributes to the view's `el`. We use the "prop" version
- // if available, falling back to `setAttribute` for the catch-all.
- _setAttributes: function(attrs) {
- for (var attr in attrs) {
- attr in this.el ? this.el[attr] = attrs[attr] : this.el.setAttribute(attr, attrs[attr]);
- }
- },
-
- // Make a event delegation handler for the given `eventName` and `selector`
- // and attach it to `this.el`.
- // If selector is empty, the listener will be bound to `this.el`. If not, a
- // new handler that will recursively traverse up the event target's DOM
- // hierarchy looking for a node that matches the selector. If one is found,
- // the event's `delegateTarget` property is set to it and the return the
- // result of calling bound `listener` with the parameters given to the
- // handler.
- delegate: function(eventName, selector, listener) {
- if (typeof selector === 'function') {
- listener = selector;
- selector = null;
- }
-
- var root = this.el;
- var handler = selector ? function (e) {
- var node = e.target || e.srcElement;
- for (; node && node != root; node = node.parentNode) {
- if (matchesSelector.call(node, selector)) {
- e.delegateTarget = node;
- listener(e);
- }
- }
- } : listener;
-
- elementAddEventListener.call(this.el, eventName, handler, false);
- this._domEvents.push({eventName: eventName, handler: handler, listener: listener, selector: selector});
- return handler;
- },
-
- // Remove a single delegated event. Either `eventName` or `selector` must
- // be included, `selector` and `listener` are optional.
- undelegate: function(eventName, selector, listener) {
- if (typeof selector === 'function') {
- listener = selector;
- selector = null;
- }
-
- if (this.el) {
- var handlers = this._domEvents.slice();
- for (var i = 0, len = handlers.length; i < len; i++) {
- var item = handlers[i];
-
- var match = item.eventName === eventName &&
- (listener ? item.listener === listener : true) &&
- (selector ? item.selector === selector : true);
-
- if (!match) continue;
-
- elementRemoveEventListener.call(this.el, item.eventName, item.handler, false);
- this._domEvents.splice(indexOf(handlers, item), 1);
- }
- }
- return this;
- },
-
- // Remove all events created with `delegate` from `el`
- undelegateEvents: function() {
- if (this.el) {
- for (var i = 0, len = this._domEvents.length; i < len; i++) {
- var item = this._domEvents[i];
- elementRemoveEventListener.call(this.el, item.eventName, item.handler, false);
- };
- this._domEvents.length = 0;
- }
- return this;
- }
- };
-
- Backbone.NativeView = Backbone.View.extend(Backbone.NativeViewMixin);
-
- return Backbone.NativeView;
-}));
diff --git a/examples/chaplin-brunch/node_modules/chaplin/chaplin.js b/examples/chaplin-brunch/node_modules/chaplin/chaplin.js
deleted file mode 100644
index efd2e473e6..0000000000
--- a/examples/chaplin-brunch/node_modules/chaplin/chaplin.js
+++ /dev/null
@@ -1,3110 +0,0 @@
-/*!
- * Chaplin 1.0.1
- *
- * Chaplin may be freely distributed under the MIT license.
- * For all details and documentation:
- * http://chaplinjs.org
- */
-
-(function(){
-
-var loader = (function() {
- var modules = {};
- var cache = {};
-
- var dummy = function() {return function() {};};
- var initModule = function(name, definition) {
- var module = {id: name, exports: {}};
- definition(module.exports, dummy(), module);
- var exports = cache[name] = module.exports;
- return exports;
- };
-
- var loader = function(path) {
- if (cache.hasOwnProperty(path)) return cache[path];
- if (modules.hasOwnProperty(path)) return initModule(path, modules[path]);
- throw new Error('Cannot find module "' + path + '"');
- };
-
- loader.register = function(bundle, fn) {
- modules[bundle] = fn;
- };
- return loader;
-})();
-
-loader.register('chaplin/application', function(e, r, module) {
-'use strict';
-
-var Application, Backbone, Composer, Dispatcher, EventBroker, Layout, Router, mediator, _;
-
-_ = loader('underscore');
-
-Backbone = loader('backbone');
-
-Dispatcher = loader('chaplin/dispatcher');
-
-Layout = loader('chaplin/views/layout');
-
-Composer = loader('chaplin/composer');
-
-Router = loader('chaplin/lib/router');
-
-EventBroker = loader('chaplin/lib/event_broker');
-
-mediator = loader('chaplin/mediator');
-
-module.exports = Application = (function() {
-
- Application.extend = Backbone.Model.extend;
-
- _.extend(Application.prototype, EventBroker);
-
- Application.prototype.title = '';
-
- Application.prototype.dispatcher = null;
-
- Application.prototype.layout = null;
-
- Application.prototype.router = null;
-
- Application.prototype.composer = null;
-
- Application.prototype.started = false;
-
- function Application(options) {
- if (options == null) {
- options = {};
- }
- this.initialize(options);
- }
-
- Application.prototype.initialize = function(options) {
- if (options == null) {
- options = {};
- }
- if (this.started) {
- throw new Error('Application#initialize: App was already started');
- }
- this.initRouter(options.routes, options);
- this.initDispatcher(options);
- this.initLayout(options);
- this.initComposer(options);
- this.initMediator();
- return this.start();
- };
-
- Application.prototype.initDispatcher = function(options) {
- return this.dispatcher = new Dispatcher(options);
- };
-
- Application.prototype.initLayout = function(options) {
- var _ref;
- if (options == null) {
- options = {};
- }
- if ((_ref = options.title) == null) {
- options.title = this.title;
- }
- return this.layout = new Layout(options);
- };
-
- Application.prototype.initComposer = function(options) {
- if (options == null) {
- options = {};
- }
- return this.composer = new Composer(options);
- };
-
- Application.prototype.initMediator = function() {
- return mediator.seal();
- };
-
- Application.prototype.initRouter = function(routes, options) {
- this.router = new Router(options);
- return typeof routes === "function" ? routes(this.router.match) : void 0;
- };
-
- Application.prototype.start = function() {
- this.router.startHistory();
- this.started = true;
- return typeof Object.freeze === "function" ? Object.freeze(this) : void 0;
- };
-
- Application.prototype.disposed = false;
-
- Application.prototype.dispose = function() {
- var prop, properties, _i, _len;
- if (this.disposed) {
- return;
- }
- properties = ['dispatcher', 'layout', 'router', 'composer'];
- for (_i = 0, _len = properties.length; _i < _len; _i++) {
- prop = properties[_i];
- if (this[prop] != null) {
- this[prop].dispose();
- }
- }
- this.disposed = true;
- return typeof Object.freeze === "function" ? Object.freeze(this) : void 0;
- };
-
- return Application;
-
-})();
-
-});;loader.register('chaplin/mediator', function(e, r, module) {
-'use strict';
-
-var Backbone, handlers, mediator, support, utils, _,
- __slice = [].slice;
-
-Backbone = loader('backbone');
-
-_ = loader('underscore');
-
-support = loader('chaplin/lib/support');
-
-utils = loader('chaplin/lib/utils');
-
-mediator = {};
-
-mediator.subscribe = mediator.on = Backbone.Events.on;
-
-mediator.subscribeOnce = mediator.once = Backbone.Events.once;
-
-mediator.unsubscribe = mediator.off = Backbone.Events.off;
-
-mediator.publish = mediator.trigger = Backbone.Events.trigger;
-
-mediator._callbacks = null;
-
-handlers = mediator._handlers = {};
-
-mediator.setHandler = function(name, method, instance) {
- return handlers[name] = {
- instance: instance,
- method: method
- };
-};
-
-mediator.execute = function() {
- var args, handler, name, nameOrObj, silent;
- nameOrObj = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
- silent = false;
- if (typeof nameOrObj === 'object') {
- silent = nameOrObj.silent;
- name = nameOrObj.name;
- } else {
- name = nameOrObj;
- }
- handler = handlers[name];
- if (handler) {
- return handler.method.apply(handler.instance, args);
- } else if (!silent) {
- throw new Error("mediator.execute: " + name + " handler is not defined");
- }
-};
-
-mediator.removeHandlers = function(instanceOrNames) {
- var handler, name, _i, _len;
- if (!instanceOrNames) {
- mediator._handlers = {};
- }
- if (utils.isArray(instanceOrNames)) {
- for (_i = 0, _len = instanceOrNames.length; _i < _len; _i++) {
- name = instanceOrNames[_i];
- delete handlers[name];
- }
- } else {
- for (name in handlers) {
- handler = handlers[name];
- if (handler.instance === instanceOrNames) {
- delete handlers[name];
- }
- }
- }
-};
-
-utils.readonly(mediator, 'subscribe', 'subscribeOnce', 'unsubscribe', 'publish', 'setHandler', 'execute', 'removeHandlers');
-
-mediator.seal = function() {
- if (support.propertyDescriptors && Object.seal) {
- return Object.seal(mediator);
- }
-};
-
-utils.readonly(mediator, 'seal');
-
-module.exports = mediator;
-
-});;loader.register('chaplin/dispatcher', function(e, r, module) {
-'use strict';
-
-var Backbone, Dispatcher, EventBroker, mediator, utils, _;
-
-_ = loader('underscore');
-
-Backbone = loader('backbone');
-
-mediator = loader('chaplin/mediator');
-
-utils = loader('chaplin/lib/utils');
-
-EventBroker = loader('chaplin/lib/event_broker');
-
-module.exports = Dispatcher = (function() {
-
- Dispatcher.extend = Backbone.Model.extend;
-
- _.extend(Dispatcher.prototype, EventBroker);
-
- Dispatcher.prototype.previousRoute = null;
-
- Dispatcher.prototype.currentController = null;
-
- Dispatcher.prototype.currentRoute = null;
-
- Dispatcher.prototype.currentParams = null;
-
- Dispatcher.prototype.currentQuery = null;
-
- function Dispatcher() {
- this.initialize.apply(this, arguments);
- }
-
- Dispatcher.prototype.initialize = function(options) {
- if (options == null) {
- options = {};
- }
- this.settings = _.defaults(options, {
- controllerPath: 'controllers/',
- controllerSuffix: '_controller'
- });
- return this.subscribeEvent('router:match', this.dispatch);
- };
-
- Dispatcher.prototype.dispatch = function(route, params, options) {
- var _ref, _ref1,
- _this = this;
- params = params ? _.extend({}, params) : {};
- options = options ? _.extend({}, options) : {};
- if (!(options.query != null)) {
- options.query = {};
- }
- if (options.forceStartup !== true) {
- options.forceStartup = false;
- }
- if (!options.forceStartup && ((_ref = this.currentRoute) != null ? _ref.controller : void 0) === route.controller && ((_ref1 = this.currentRoute) != null ? _ref1.action : void 0) === route.action && _.isEqual(this.currentParams, params) && _.isEqual(this.currentQuery, options.query)) {
- return;
- }
- return this.loadController(route.controller, function(Controller) {
- return _this.controllerLoaded(route, params, options, Controller);
- });
- };
-
- Dispatcher.prototype.loadController = function(name, handler) {
- var fileName, moduleName,
- _this = this;
- fileName = name + this.settings.controllerSuffix;
- moduleName = this.settings.controllerPath + fileName;
- if (typeof define !== "undefined" && define !== null ? define.amd : void 0) {
- return require([moduleName], handler);
- } else {
- return setTimeout(function() {
- return handler(require(moduleName));
- }, 0);
- }
- };
-
- Dispatcher.prototype.controllerLoaded = function(route, params, options, Controller) {
- var controller, prev, previous;
- if (this.nextPreviousRoute = this.currentRoute) {
- previous = _.extend({}, this.nextPreviousRoute);
- if (this.currentParams != null) {
- previous.params = this.currentParams;
- }
- if (previous.previous) {
- delete previous.previous;
- }
- prev = {
- previous: previous
- };
- }
- this.nextCurrentRoute = _.extend({}, route, prev);
- controller = new Controller(params, this.nextCurrentRoute, options);
- return this.executeBeforeAction(controller, this.nextCurrentRoute, params, options);
- };
-
- Dispatcher.prototype.executeAction = function(controller, route, params, options) {
- if (this.currentController) {
- this.publishEvent('beforeControllerDispose', this.currentController);
- this.currentController.dispose(params, route, options);
- }
- this.currentController = controller;
- this.currentParams = params;
- this.currentQuery = options.query;
- controller[route.action](params, route, options);
- if (controller.redirected) {
- return;
- }
- return this.publishEvent('dispatcher:dispatch', this.currentController, params, route, options);
- };
-
- Dispatcher.prototype.executeBeforeAction = function(controller, route, params, options) {
- var before, executeAction, promise,
- _this = this;
- before = controller.beforeAction;
- executeAction = function() {
- if (controller.redirected || _this.currentRoute && route === _this.currentRoute) {
- _this.nextPreviousRoute = _this.nextCurrentRoute = null;
- controller.dispose();
- return;
- }
- _this.previousRoute = _this.nextPreviousRoute;
- _this.currentRoute = _this.nextCurrentRoute;
- _this.nextPreviousRoute = _this.nextCurrentRoute = null;
- return _this.executeAction(controller, route, params, options);
- };
- if (!before) {
- executeAction();
- return;
- }
- if (typeof before !== 'function') {
- throw new TypeError('Controller#beforeAction: function expected. ' + 'Old object-like form is not supported.');
- }
- promise = controller.beforeAction(params, route, options);
- if (promise && promise.then) {
- return promise.then(executeAction);
- } else {
- return executeAction();
- }
- };
-
- Dispatcher.prototype.disposed = false;
-
- Dispatcher.prototype.dispose = function() {
- if (this.disposed) {
- return;
- }
- this.unsubscribeAllEvents();
- this.disposed = true;
- return typeof Object.freeze === "function" ? Object.freeze(this) : void 0;
- };
-
- return Dispatcher;
-
-})();
-
-});;loader.register('chaplin/composer', function(e, r, module) {
-'use strict';
-
-var Backbone, Composer, Composition, EventBroker, mediator, utils, _;
-
-_ = loader('underscore');
-
-Backbone = loader('backbone');
-
-mediator = loader('chaplin/mediator');
-
-utils = loader('chaplin/lib/utils');
-
-Composition = loader('chaplin/lib/composition');
-
-EventBroker = loader('chaplin/lib/event_broker');
-
-module.exports = Composer = (function() {
-
- Composer.extend = Backbone.Model.extend;
-
- _.extend(Composer.prototype, EventBroker);
-
- Composer.prototype.compositions = null;
-
- function Composer() {
- this.initialize.apply(this, arguments);
- }
-
- Composer.prototype.initialize = function(options) {
- if (options == null) {
- options = {};
- }
- this.compositions = {};
- mediator.setHandler('composer:compose', this.compose, this);
- mediator.setHandler('composer:retrieve', this.retrieve, this);
- return this.subscribeEvent('dispatcher:dispatch', this.cleanup);
- };
-
- Composer.prototype.compose = function(name, second, third) {
- if (typeof second === 'function') {
- if (third || second.prototype.dispose) {
- if (second.prototype instanceof Composition) {
- return this._compose(name, {
- composition: second,
- options: third
- });
- } else {
- return this._compose(name, {
- options: third,
- compose: function() {
- var autoRender, disabledAutoRender;
- if (second.prototype instanceof Backbone.Model || second.prototype instanceof Backbone.Collection) {
- this.item = new second(null, this.options);
- } else {
- this.item = new second(this.options);
- }
- autoRender = this.item.autoRender;
- disabledAutoRender = autoRender === void 0 || !autoRender;
- if (disabledAutoRender && typeof this.item.render === 'function') {
- return this.item.render();
- }
- }
- });
- }
- }
- return this._compose(name, {
- compose: second
- });
- }
- if (typeof third === 'function') {
- return this._compose(name, {
- compose: third,
- options: second
- });
- }
- return this._compose(name, second);
- };
-
- Composer.prototype._compose = function(name, options) {
- var composition, current, isPromise, returned;
- if (typeof options.compose !== 'function' && !(options.composition != null)) {
- throw new Error('Composer#compose was used incorrectly');
- }
- if (options.composition != null) {
- composition = new options.composition(options.options);
- } else {
- composition = new Composition(options.options);
- composition.compose = options.compose;
- if (options.check) {
- composition.check = options.check;
- }
- }
- current = this.compositions[name];
- isPromise = false;
- if (current && current.check(composition.options)) {
- current.stale(false);
- } else {
- if (current) {
- current.dispose();
- }
- returned = composition.compose(composition.options);
- isPromise = typeof (returned != null ? returned.then : void 0) === 'function';
- composition.stale(false);
- this.compositions[name] = composition;
- }
- if (isPromise) {
- return returned;
- } else {
- return this.compositions[name].item;
- }
- };
-
- Composer.prototype.retrieve = function(name) {
- var active;
- active = this.compositions[name];
- if (active && !active.stale()) {
- return active.item;
- } else {
- return void 0;
- }
- };
-
- Composer.prototype.cleanup = function() {
- var composition, name, _ref;
- _ref = this.compositions;
- for (name in _ref) {
- composition = _ref[name];
- if (composition.stale()) {
- composition.dispose();
- delete this.compositions[name];
- } else {
- composition.stale(true);
- }
- }
- };
-
- Composer.prototype.dispose = function() {
- var composition, name, _ref;
- if (this.disposed) {
- return;
- }
- this.unsubscribeAllEvents();
- mediator.removeHandlers(this);
- _ref = this.compositions;
- for (name in _ref) {
- composition = _ref[name];
- composition.dispose();
- }
- delete this.compositions;
- this.disposed = true;
- return typeof Object.freeze === "function" ? Object.freeze(this) : void 0;
- };
-
- return Composer;
-
-})();
-
-});;loader.register('chaplin/controllers/controller', function(e, r, module) {
-'use strict';
-
-var Backbone, Controller, EventBroker, mediator, utils, _,
- __slice = [].slice,
- __hasProp = {}.hasOwnProperty;
-
-_ = loader('underscore');
-
-Backbone = loader('backbone');
-
-EventBroker = loader('chaplin/lib/event_broker');
-
-utils = loader('chaplin/lib/utils');
-
-mediator = loader('chaplin/mediator');
-
-module.exports = Controller = (function() {
-
- Controller.extend = Backbone.Model.extend;
-
- _.extend(Controller.prototype, Backbone.Events);
-
- _.extend(Controller.prototype, EventBroker);
-
- Controller.prototype.view = null;
-
- Controller.prototype.redirected = false;
-
- function Controller() {
- this.initialize.apply(this, arguments);
- }
-
- Controller.prototype.initialize = function() {};
-
- Controller.prototype.beforeAction = function() {};
-
- Controller.prototype.adjustTitle = function(subtitle) {
- return mediator.execute('adjustTitle', subtitle);
- };
-
- Controller.prototype.reuse = function(name) {
- var method;
- method = arguments.length === 1 ? 'retrieve' : 'compose';
- return mediator.execute.apply(mediator, ["composer:" + method].concat(__slice.call(arguments)));
- };
-
- Controller.prototype.compose = function() {
- throw new Error('Controller#compose was moved to Controller#reuse');
- };
-
- Controller.prototype.redirectTo = function(pathDesc, params, options) {
- this.redirected = true;
- return utils.redirectTo(pathDesc, params, options);
- };
-
- Controller.prototype.disposed = false;
-
- Controller.prototype.dispose = function() {
- var obj, prop;
- if (this.disposed) {
- return;
- }
- for (prop in this) {
- if (!__hasProp.call(this, prop)) continue;
- obj = this[prop];
- if (!(obj && typeof obj.dispose === 'function')) {
- continue;
- }
- obj.dispose();
- delete this[prop];
- }
- this.unsubscribeAllEvents();
- this.stopListening();
- this.disposed = true;
- return typeof Object.freeze === "function" ? Object.freeze(this) : void 0;
- };
-
- return Controller;
-
-})();
-
-});;loader.register('chaplin/models/collection', function(e, r, module) {
-'use strict';
-
-var Backbone, Collection, EventBroker, Model, utils, _,
- __hasProp = {}.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
-
-_ = loader('underscore');
-
-Backbone = loader('backbone');
-
-EventBroker = loader('chaplin/lib/event_broker');
-
-Model = loader('chaplin/models/model');
-
-utils = loader('chaplin/lib/utils');
-
-module.exports = Collection = (function(_super) {
-
- __extends(Collection, _super);
-
- function Collection() {
- return Collection.__super__.constructor.apply(this, arguments);
- }
-
- _.extend(Collection.prototype, EventBroker);
-
- Collection.prototype.model = Model;
-
- Collection.prototype.serialize = function() {
- return this.map(utils.serialize);
- };
-
- Collection.prototype.disposed = false;
-
- Collection.prototype.dispose = function() {
- var prop, properties, _i, _len;
- if (this.disposed) {
- return;
- }
- this.trigger('dispose', this);
- this.reset([], {
- silent: true
- });
- this.unsubscribeAllEvents();
- this.stopListening();
- this.off();
- properties = ['model', 'models', '_byId', '_byCid', '_callbacks'];
- for (_i = 0, _len = properties.length; _i < _len; _i++) {
- prop = properties[_i];
- delete this[prop];
- }
- this.disposed = true;
- return typeof Object.freeze === "function" ? Object.freeze(this) : void 0;
- };
-
- return Collection;
-
-})(Backbone.Collection);
-
-});;loader.register('chaplin/models/model', function(e, r, module) {
-'use strict';
-
-var Backbone, EventBroker, Model, serializeAttributes, serializeModelAttributes, utils, _,
- __hasProp = {}.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
-
-_ = loader('underscore');
-
-Backbone = loader('backbone');
-
-utils = loader('chaplin/lib/utils');
-
-EventBroker = loader('chaplin/lib/event_broker');
-
-serializeAttributes = function(model, attributes, modelStack) {
- var delegator, key, otherModel, serializedModels, value, _i, _len, _ref;
- delegator = utils.beget(attributes);
- if (modelStack == null) {
- modelStack = {};
- }
- modelStack[model.cid] = true;
- for (key in attributes) {
- value = attributes[key];
- if (value instanceof Backbone.Model) {
- delegator[key] = serializeModelAttributes(value, model, modelStack);
- } else if (value instanceof Backbone.Collection) {
- serializedModels = [];
- _ref = value.models;
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- otherModel = _ref[_i];
- serializedModels.push(serializeModelAttributes(otherModel, model, modelStack));
- }
- delegator[key] = serializedModels;
- }
- }
- delete modelStack[model.cid];
- return delegator;
-};
-
-serializeModelAttributes = function(model, currentModel, modelStack) {
- var attributes;
- if (model === currentModel || model.cid in modelStack) {
- return null;
- }
- attributes = typeof model.getAttributes === 'function' ? model.getAttributes() : model.attributes;
- return serializeAttributes(model, attributes, modelStack);
-};
-
-module.exports = Model = (function(_super) {
-
- __extends(Model, _super);
-
- function Model() {
- return Model.__super__.constructor.apply(this, arguments);
- }
-
- _.extend(Model.prototype, EventBroker);
-
- Model.prototype.getAttributes = function() {
- return this.attributes;
- };
-
- Model.prototype.serialize = function() {
- return serializeAttributes(this, this.getAttributes());
- };
-
- Model.prototype.disposed = false;
-
- Model.prototype.dispose = function() {
- var prop, properties, _i, _len;
- if (this.disposed) {
- return;
- }
- this.trigger('dispose', this);
- this.unsubscribeAllEvents();
- this.stopListening();
- this.off();
- properties = ['collection', 'attributes', 'changed', 'defaults', '_escapedAttributes', '_previousAttributes', '_silent', '_pending', '_callbacks'];
- for (_i = 0, _len = properties.length; _i < _len; _i++) {
- prop = properties[_i];
- delete this[prop];
- }
- this.disposed = true;
- return typeof Object.freeze === "function" ? Object.freeze(this) : void 0;
- };
-
- return Model;
-
-})(Backbone.Model);
-
-});;loader.register('chaplin/views/layout', function(e, r, module) {
-'use strict';
-
-var $, Backbone, EventBroker, Layout, View, mediator, utils, _,
- __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
- __hasProp = {}.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
-
-_ = loader('underscore');
-
-Backbone = loader('backbone');
-
-mediator = loader('chaplin/mediator');
-
-utils = loader('chaplin/lib/utils');
-
-EventBroker = loader('chaplin/lib/event_broker');
-
-View = loader('chaplin/views/view');
-
-$ = Backbone.$;
-
-module.exports = Layout = (function(_super) {
-
- __extends(Layout, _super);
-
- Layout.prototype.el = 'body';
-
- Layout.prototype.keepElement = true;
-
- Layout.prototype.title = '';
-
- Layout.prototype.globalRegions = null;
-
- Layout.prototype.listen = {
- 'beforeControllerDispose mediator': 'scroll'
- };
-
- function Layout(options) {
- if (options == null) {
- options = {};
- }
- this.openLink = __bind(this.openLink, this);
-
- this.globalRegions = [];
- this.title = options.title;
- if (options.regions) {
- this.regions = options.regions;
- }
- this.settings = _.defaults(options, {
- titleTemplate: function(data) {
- var st;
- st = data.subtitle ? "" + data.subtitle + " \u2013 " : '';
- return st + data.title;
- },
- openExternalToBlank: false,
- routeLinks: 'a, .go-to',
- skipRouting: '.noscript',
- scrollTo: [0, 0]
- });
- mediator.setHandler('region:show', this.showRegion, this);
- mediator.setHandler('region:register', this.registerRegionHandler, this);
- mediator.setHandler('region:unregister', this.unregisterRegionHandler, this);
- mediator.setHandler('region:find', this.regionByName, this);
- mediator.setHandler('adjustTitle', this.adjustTitle, this);
- Layout.__super__.constructor.apply(this, arguments);
- if (this.settings.routeLinks) {
- this.startLinkRouting();
- }
- }
-
- Layout.prototype.scroll = function() {
- var position;
- position = this.settings.scrollTo;
- if (position) {
- return window.scrollTo(position[0], position[1]);
- }
- };
-
- Layout.prototype.adjustTitle = function(subtitle) {
- var title,
- _this = this;
- if (subtitle == null) {
- subtitle = '';
- }
- title = this.settings.titleTemplate({
- title: this.title,
- subtitle: subtitle
- });
- setTimeout(function() {
- document.title = title;
- return _this.publishEvent('adjustTitle', subtitle, title);
- }, 50);
- return title;
- };
-
- Layout.prototype.startLinkRouting = function() {
- var route;
- route = this.settings.routeLinks;
- if (!route) {
- return;
- }
- if ($) {
- return this.$el.on('click', route, this.openLink);
- } else {
- return this.delegate('click', route, this.openLink);
- }
- };
-
- Layout.prototype.stopLinkRouting = function() {
- var route;
- route = this.settings.routeLinks;
- if ($) {
- if (route) {
- return this.$el.off('click', route);
- }
- } else {
- return this.undelegate('click', route, this.openLink);
- }
- };
-
- Layout.prototype.isExternalLink = function(link) {
- var _ref, _ref1;
- return link.target === '_blank' || link.rel === 'external' || ((_ref = link.protocol) !== 'http:' && _ref !== 'https:' && _ref !== 'file:') || ((_ref1 = link.hostname) !== location.hostname && _ref1 !== '');
- };
-
- Layout.prototype.openLink = function(event) {
- var el, external, href, isAnchor, skipRouting, type;
- if (utils.modifierKeyPressed(event)) {
- return;
- }
- el = $ ? event.currentTarget : event.delegateTarget;
- isAnchor = el.nodeName === 'A';
- href = el.getAttribute('href') || el.getAttribute('data-href') || null;
- if (!(href != null) || href === '' || href.charAt(0) === '#') {
- return;
- }
- skipRouting = this.settings.skipRouting;
- type = typeof skipRouting;
- if (type === 'function' && !skipRouting(href, el) || type === 'string' && ($ ? $(el).is(skipRouting) : Backbone.utils.matchesSelector(el, skipRouting))) {
- return;
- }
- external = isAnchor && this.isExternalLink(el);
- if (external) {
- if (this.settings.openExternalToBlank) {
- event.preventDefault();
- window.open(href);
- }
- return;
- }
- utils.redirectTo({
- url: href
- });
- event.preventDefault();
- };
-
- Layout.prototype.registerRegionHandler = function(instance, name, selector) {
- if (name != null) {
- return this.registerGlobalRegion(instance, name, selector);
- } else {
- return this.registerGlobalRegions(instance);
- }
- };
-
- Layout.prototype.registerGlobalRegion = function(instance, name, selector) {
- this.unregisterGlobalRegion(instance, name);
- return this.globalRegions.unshift({
- instance: instance,
- name: name,
- selector: selector
- });
- };
-
- Layout.prototype.registerGlobalRegions = function(instance) {
- var name, selector, version, _i, _len, _ref;
- _ref = utils.getAllPropertyVersions(instance, 'regions');
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- version = _ref[_i];
- for (name in version) {
- selector = version[name];
- this.registerGlobalRegion(instance, name, selector);
- }
- }
- };
-
- Layout.prototype.unregisterRegionHandler = function(instance, name) {
- if (name != null) {
- return this.unregisterGlobalRegion(instance, name);
- } else {
- return this.unregisterGlobalRegions(instance);
- }
- };
-
- Layout.prototype.unregisterGlobalRegion = function(instance, name) {
- var cid, region;
- cid = instance.cid;
- return this.globalRegions = (function() {
- var _i, _len, _ref, _results;
- _ref = this.globalRegions;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- region = _ref[_i];
- if (region.instance.cid !== cid || region.name !== name) {
- _results.push(region);
- }
- }
- return _results;
- }).call(this);
- };
-
- Layout.prototype.unregisterGlobalRegions = function(instance) {
- var region;
- return this.globalRegions = (function() {
- var _i, _len, _ref, _results;
- _ref = this.globalRegions;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- region = _ref[_i];
- if (region.instance.cid !== instance.cid) {
- _results.push(region);
- }
- }
- return _results;
- }).call(this);
- };
-
- Layout.prototype.regionByName = function(name) {
- var reg, _i, _len, _ref;
- _ref = this.globalRegions;
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- reg = _ref[_i];
- if (reg.name === name && !reg.instance.stale) {
- return reg;
- }
- }
- };
-
- Layout.prototype.showRegion = function(name, instance) {
- var region;
- region = this.regionByName(name);
- if (!region) {
- throw new Error("No region registered under " + name);
- }
- return instance.container = region.selector === '' ? $ ? region.instance.$el : region.instance.el : region.instance.noWrap ? $ ? $(region.instance.container).find(region.selector) : region.instance.container.querySelector(region.selector) : region.instance[$ ? '$' : 'find'](region.selector);
- };
-
- Layout.prototype.dispose = function() {
- var prop, _i, _len, _ref;
- if (this.disposed) {
- return;
- }
- this.stopLinkRouting();
- _ref = ['globalRegions', 'title', 'route'];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- prop = _ref[_i];
- delete this[prop];
- }
- mediator.removeHandlers(this);
- return Layout.__super__.dispose.apply(this, arguments);
- };
-
- return Layout;
-
-})(View);
-
-});;loader.register('chaplin/views/view', function(e, r, module) {
-'use strict';
-
-var $, Backbone, EventBroker, View, attach, bind, mediator, setHTML, utils, _,
- __hasProp = {}.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
- __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
-
-_ = loader('underscore');
-
-Backbone = loader('backbone');
-
-mediator = loader('chaplin/mediator');
-
-EventBroker = loader('chaplin/lib/event_broker');
-
-utils = loader('chaplin/lib/utils');
-
-$ = Backbone.$;
-
-bind = (function() {
- if (Function.prototype.bind) {
- return function(item, ctx) {
- return item.bind(ctx);
- };
- } else if (_.bind) {
- return _.bind;
- }
-})();
-
-setHTML = (function() {
- if ($) {
- return function(elem, html) {
- return elem.html(html);
- };
- } else {
- return function(elem, html) {
- return elem.innerHTML = html;
- };
- }
-})();
-
-attach = (function() {
- if ($) {
- return function(view) {
- var actual;
- actual = $(view.container);
- if (typeof view.containerMethod === 'function') {
- return view.containerMethod(actual, view.el);
- } else {
- return actual[view.containerMethod](view.el);
- }
- };
- } else {
- return function(view) {
- var actual;
- actual = typeof view.container === 'string' ? document.querySelector(view.container) : view.container;
- if (typeof view.containerMethod === 'function') {
- return view.containerMethod(actual, view.el);
- } else {
- return actual[view.containerMethod](view.el);
- }
- };
- }
-})();
-
-module.exports = View = (function(_super) {
-
- __extends(View, _super);
-
- _.extend(View.prototype, EventBroker);
-
- View.prototype.autoRender = false;
-
- View.prototype.autoAttach = true;
-
- View.prototype.container = null;
-
- View.prototype.containerMethod = $ ? 'append' : 'appendChild';
-
- View.prototype.regions = null;
-
- View.prototype.region = null;
-
- View.prototype.stale = false;
-
- View.prototype.noWrap = false;
-
- View.prototype.keepElement = false;
-
- View.prototype.subviews = null;
-
- View.prototype.subviewsByName = null;
-
- View.prototype.optionNames = ['autoAttach', 'autoRender', 'container', 'containerMethod', 'region', 'regions', 'noWrap'];
-
- function View(options) {
- var optName, optValue, region, render,
- _this = this;
- if (options) {
- for (optName in options) {
- optValue = options[optName];
- if (__indexOf.call(this.optionNames, optName) >= 0) {
- this[optName] = optValue;
- }
- }
- }
- render = this.render;
- this.render = function() {
- if (_this.disposed) {
- return false;
- }
- render.apply(_this, arguments);
- if (_this.autoAttach) {
- _this.attach.apply(_this, arguments);
- }
- return _this;
- };
- this.subviews = [];
- this.subviewsByName = {};
- if (this.noWrap) {
- if (this.region) {
- region = mediator.execute('region:find', this.region);
- if (region != null) {
- this.el = region.instance.container != null ? region.instance.region != null ? $(region.instance.container).find(region.selector) : region.instance.container : region.instance.$(region.selector);
- }
- }
- if (this.container) {
- this.el = this.container;
- }
- }
- View.__super__.constructor.apply(this, arguments);
- this.delegateListeners();
- if (this.model) {
- this.listenTo(this.model, 'dispose', this.dispose);
- }
- if (this.collection) {
- this.listenTo(this.collection, 'dispose', function(subject) {
- if (!subject || subject === _this.collection) {
- return _this.dispose();
- }
- });
- }
- if (this.regions != null) {
- mediator.execute('region:register', this);
- }
- if (this.autoRender) {
- this.render();
- }
- }
-
- View.prototype.delegate = function(eventName, second, third) {
- var bound, event, events, handler, list, selector;
- if (Backbone.utils) {
- return Backbone.utils.delegate(this, eventName, second, third);
- }
- if (typeof eventName !== 'string') {
- throw new TypeError('View#delegate: first argument must be a string');
- }
- if (arguments.length === 2) {
- handler = second;
- } else if (arguments.length === 3) {
- selector = second;
- if (typeof selector !== 'string') {
- throw new TypeError('View#delegate: ' + 'second argument must be a string');
- }
- handler = third;
- } else {
- throw new TypeError('View#delegate: ' + 'only two or three arguments are allowed');
- }
- if (typeof handler !== 'function') {
- throw new TypeError('View#delegate: ' + 'handler argument must be function');
- }
- list = (function() {
- var _i, _len, _ref, _results;
- _ref = eventName.split(' ');
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- event = _ref[_i];
- _results.push("" + event + ".delegate" + this.cid);
- }
- return _results;
- }).call(this);
- events = list.join(' ');
- bound = bind(handler, this);
- this.$el.on(events, selector || null, bound);
- return bound;
- };
-
- View.prototype._delegateEvents = function(events) {
- var bound, eventName, handler, key, match, selector, value;
- if (Backbone.View.prototype.delegateEvents.length === 2) {
- return Backbone.View.prototype.delegateEvents.call(this, events, true);
- }
- for (key in events) {
- value = events[key];
- handler = typeof value === 'function' ? value : this[value];
- if (!handler) {
- throw new Error("Method '" + value + "' does not exist");
- }
- match = key.match(/^(\S+)\s*(.*)$/);
- eventName = "" + match[1] + ".delegateEvents" + this.cid;
- selector = match[2];
- bound = bind(handler, this);
- this.$el.on(eventName, selector || null, bound);
- }
- };
-
- View.prototype.delegateEvents = function(events, keepOld) {
- var classEvents, _i, _len, _ref;
- if (!keepOld) {
- this.undelegateEvents();
- }
- if (events) {
- return this._delegateEvents(events);
- }
- _ref = utils.getAllPropertyVersions(this, 'events');
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- classEvents = _ref[_i];
- if (typeof classEvents === 'function') {
- classEvents = classEvents.call(this);
- }
- this._delegateEvents(classEvents);
- }
- };
-
- View.prototype.undelegate = function(eventName, second, third) {
- var event, events, handler, list, selector;
- if (Backbone.utils) {
- return Backbone.utils.undelegate(this, eventName, second, third);
- }
- if (eventName) {
- if (typeof eventName !== 'string') {
- throw new TypeError('View#undelegate: first argument must be a string');
- }
- if (arguments.length === 2) {
- if (typeof second === 'string') {
- selector = second;
- } else {
- handler = second;
- }
- } else if (arguments.length === 3) {
- selector = second;
- if (typeof selector !== 'string') {
- throw new TypeError('View#undelegate: ' + 'second argument must be a string');
- }
- handler = third;
- }
- list = (function() {
- var _i, _len, _ref, _results;
- _ref = eventName.split(' ');
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- event = _ref[_i];
- _results.push("" + event + ".delegate" + this.cid);
- }
- return _results;
- }).call(this);
- events = list.join(' ');
- return this.$el.off(events, selector || null);
- } else {
- return this.$el.off(".delegate" + this.cid);
- }
- };
-
- View.prototype.delegateListeners = function() {
- var eventName, key, method, target, version, _i, _len, _ref, _ref1;
- if (!this.listen) {
- return;
- }
- _ref = utils.getAllPropertyVersions(this, 'listen');
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- version = _ref[_i];
- if (typeof version === 'function') {
- version = version.call(this);
- }
- for (key in version) {
- method = version[key];
- if (typeof method !== 'function') {
- method = this[method];
- }
- if (typeof method !== 'function') {
- throw new Error('View#delegateListeners: ' + ("listener for \"" + key + "\" must be function"));
- }
- _ref1 = key.split(' '), eventName = _ref1[0], target = _ref1[1];
- this.delegateListener(eventName, target, method);
- }
- }
- };
-
- View.prototype.delegateListener = function(eventName, target, callback) {
- var prop;
- if (target === 'model' || target === 'collection') {
- prop = this[target];
- if (prop) {
- this.listenTo(prop, eventName, callback);
- }
- } else if (target === 'mediator') {
- this.subscribeEvent(eventName, callback);
- } else if (!target) {
- this.on(eventName, callback, this);
- }
- };
-
- View.prototype.registerRegion = function(name, selector) {
- return mediator.execute('region:register', this, name, selector);
- };
-
- View.prototype.unregisterRegion = function(name) {
- return mediator.execute('region:unregister', this, name);
- };
-
- View.prototype.unregisterAllRegions = function() {
- return mediator.execute({
- name: 'region:unregister',
- silent: true
- }, this);
- };
-
- View.prototype.subview = function(name, view) {
- var byName, subviews;
- subviews = this.subviews;
- byName = this.subviewsByName;
- if (name && view) {
- this.removeSubview(name);
- subviews.push(view);
- byName[name] = view;
- return view;
- } else if (name) {
- return byName[name];
- }
- };
-
- View.prototype.removeSubview = function(nameOrView) {
- var byName, index, name, otherName, otherView, subviews, view;
- if (!nameOrView) {
- return;
- }
- subviews = this.subviews;
- byName = this.subviewsByName;
- if (typeof nameOrView === 'string') {
- name = nameOrView;
- view = byName[name];
- } else {
- view = nameOrView;
- for (otherName in byName) {
- otherView = byName[otherName];
- if (!(otherView === view)) {
- continue;
- }
- name = otherName;
- break;
- }
- }
- if (!(name && view && view.dispose)) {
- return;
- }
- view.dispose();
- index = utils.indexOf(subviews, view);
- if (index !== -1) {
- subviews.splice(index, 1);
- }
- return delete byName[name];
- };
-
- View.prototype.getTemplateData = function() {
- var data, source;
- data = this.model ? utils.serialize(this.model) : this.collection ? {
- items: utils.serialize(this.collection),
- length: this.collection.length
- } : {};
- source = this.model || this.collection;
- if (source) {
- if (typeof source.isSynced === 'function' && !('synced' in data)) {
- data.synced = source.isSynced();
- }
- }
- return data;
- };
-
- View.prototype.getTemplateFunction = function() {
- throw new Error('View#getTemplateFunction must be overridden');
- };
-
- View.prototype.render = function() {
- var el, html, templateFunc;
- if (this.disposed) {
- return false;
- }
- templateFunc = this.getTemplateFunction();
- if (typeof templateFunc === 'function') {
- html = templateFunc(this.getTemplateData());
- if (this.noWrap) {
- el = document.createElement('div');
- el.innerHTML = html;
- if (el.children.length > 1) {
- throw new Error('There must be a single top-level element when ' + 'using `noWrap`.');
- }
- this.undelegateEvents();
- this.setElement(el.firstChild, true);
- } else {
- setHTML(($ ? this.$el : this.el), html);
- }
- }
- return this;
- };
-
- View.prototype.attach = function() {
- if (this.region != null) {
- mediator.execute('region:show', this.region, this);
- }
- if (this.container && !document.body.contains(this.el)) {
- attach(this);
- return this.trigger('addedToDOM');
- }
- };
-
- View.prototype.disposed = false;
-
- View.prototype.dispose = function() {
- var prop, properties, subview, _i, _j, _len, _len1, _ref;
- if (this.disposed) {
- return;
- }
- this.unregisterAllRegions();
- _ref = this.subviews;
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- subview = _ref[_i];
- subview.dispose();
- }
- this.unsubscribeAllEvents();
- this.off();
- if (this.keepElement) {
- this.undelegateEvents();
- this.undelegate();
- this.stopListening();
- } else {
- this.remove();
- }
- properties = ['el', '$el', 'options', 'model', 'collection', 'subviews', 'subviewsByName', '_callbacks'];
- for (_j = 0, _len1 = properties.length; _j < _len1; _j++) {
- prop = properties[_j];
- delete this[prop];
- }
- this.disposed = true;
- return typeof Object.freeze === "function" ? Object.freeze(this) : void 0;
- };
-
- return View;
-
-})(Backbone.View);
-
-});;loader.register('chaplin/views/collection_view', function(e, r, module) {
-'use strict';
-
-var $, Backbone, CollectionView, View, addClass, endAnimation, filterChildren, insertView, startAnimation, toggleElement, utils, _,
- __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
- __hasProp = {}.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
-
-_ = loader('underscore');
-
-Backbone = loader('backbone');
-
-View = loader('chaplin/views/view');
-
-utils = loader('chaplin/lib/utils');
-
-$ = Backbone.$;
-
-filterChildren = function(nodeList, selector) {
- var node, _i, _len, _results;
- if (!selector) {
- return nodeList;
- }
- _results = [];
- for (_i = 0, _len = nodeList.length; _i < _len; _i++) {
- node = nodeList[_i];
- if (Backbone.utils.matchesSelector(node, selector)) {
- _results.push(node);
- }
- }
- return _results;
-};
-
-toggleElement = (function() {
- if ($) {
- return function(elem, visible) {
- return elem.toggle(visible);
- };
- } else {
- return function(elem, visible) {
- return elem.style.display = (visible ? '' : 'none');
- };
- }
-})();
-
-addClass = (function() {
- if ($) {
- return function(elem, cls) {
- return elem.addClass(cls);
- };
- } else {
- return function(elem, cls) {
- return elem.classList.add(cls);
- };
- }
-})();
-
-startAnimation = (function() {
- if ($) {
- return function(elem, useCssAnimation, cls) {
- if (useCssAnimation) {
- return addClass(elem, cls);
- } else {
- return elem.css('opacity', 0);
- }
- };
- } else {
- return function(elem, useCssAnimation, cls) {
- if (useCssAnimation) {
- return addClass(elem, cls);
- } else {
- return elem.style.opacity = 0;
- }
- };
- }
-})();
-
-endAnimation = (function() {
- if ($) {
- return function(elem, duration) {
- return elem.animate({
- opacity: 1
- }, duration);
- };
- } else {
- return function(elem, duration) {
- elem.style.transition = "opacity " + (duration / 1000) + "s";
- return elem.opacity = 1;
- };
- }
-})();
-
-insertView = (function() {
- if ($) {
- return function(list, viewEl, position, length, itemSelector) {
- var children, childrenLength, insertInMiddle, isEnd, method;
- insertInMiddle = (0 < position && position < length);
- isEnd = function(length) {
- return length === 0 || position === length;
- };
- if (insertInMiddle || itemSelector) {
- children = list.children(itemSelector);
- childrenLength = children.length;
- if (children[position] !== viewEl) {
- if (isEnd(childrenLength)) {
- return list.append(viewEl);
- } else {
- if (position === 0) {
- return children.eq(position).before(viewEl);
- } else {
- return children.eq(position - 1).after(viewEl);
- }
- }
- }
- } else {
- method = isEnd(length) ? 'append' : 'prepend';
- return list[method](viewEl);
- }
- };
- } else {
- return function(list, viewEl, position, length, itemSelector) {
- var children, childrenLength, insertInMiddle, isEnd, last;
- insertInMiddle = (0 < position && position < length);
- isEnd = function(length) {
- return length === 0 || position === length;
- };
- if (insertInMiddle || itemSelector) {
- children = filterChildren(list.children, itemSelector);
- childrenLength = children.length;
- if (children[position] !== viewEl) {
- if (isEnd(childrenLength)) {
- return list.appendChild(viewEl);
- } else if (position === 0) {
- return list.insertBefore(viewEl, children[position]);
- } else {
- last = children[position - 1];
- if (list.lastChild === last) {
- return list.appendChild(viewEl);
- } else {
- return list.insertBefore(viewEl, last.nextElementSibling);
- }
- }
- }
- } else if (isEnd(length)) {
- return list.appendChild(viewEl);
- } else {
- return list.insertBefore(viewEl, list.firstChild);
- }
- };
- }
-})();
-
-module.exports = CollectionView = (function(_super) {
-
- __extends(CollectionView, _super);
-
- CollectionView.prototype.itemView = null;
-
- CollectionView.prototype.autoRender = true;
-
- CollectionView.prototype.renderItems = true;
-
- CollectionView.prototype.animationDuration = 500;
-
- CollectionView.prototype.useCssAnimation = false;
-
- CollectionView.prototype.animationStartClass = 'animated-item-view';
-
- CollectionView.prototype.animationEndClass = 'animated-item-view-end';
-
- CollectionView.prototype.listSelector = null;
-
- CollectionView.prototype.$list = null;
-
- CollectionView.prototype.fallbackSelector = null;
-
- CollectionView.prototype.$fallback = null;
-
- CollectionView.prototype.loadingSelector = null;
-
- CollectionView.prototype.$loading = null;
-
- CollectionView.prototype.itemSelector = null;
-
- CollectionView.prototype.filterer = null;
-
- CollectionView.prototype.filterCallback = function(view, included) {
- if ($) {
- view.$el.stop(true, true);
- }
- return toggleElement(($ ? view.$el : view.el), included);
- };
-
- CollectionView.prototype.visibleItems = null;
-
- CollectionView.prototype.optionNames = View.prototype.optionNames.concat(['renderItems', 'itemView']);
-
- function CollectionView(options) {
- this.renderAllItems = __bind(this.renderAllItems, this);
-
- this.toggleFallback = __bind(this.toggleFallback, this);
-
- this.itemsReset = __bind(this.itemsReset, this);
-
- this.itemRemoved = __bind(this.itemRemoved, this);
-
- this.itemAdded = __bind(this.itemAdded, this);
- this.visibleItems = [];
- CollectionView.__super__.constructor.apply(this, arguments);
- }
-
- CollectionView.prototype.initialize = function(options) {
- if (options == null) {
- options = {};
- }
- this.addCollectionListeners();
- if (options.filterer != null) {
- return this.filter(options.filterer);
- }
- };
-
- CollectionView.prototype.addCollectionListeners = function() {
- this.listenTo(this.collection, 'add', this.itemAdded);
- this.listenTo(this.collection, 'remove', this.itemRemoved);
- return this.listenTo(this.collection, 'reset sort', this.itemsReset);
- };
-
- CollectionView.prototype.getTemplateData = function() {
- var templateData;
- templateData = {
- length: this.collection.length
- };
- if (typeof this.collection.isSynced === 'function') {
- templateData.synced = this.collection.isSynced();
- }
- return templateData;
- };
-
- CollectionView.prototype.getTemplateFunction = function() {};
-
- CollectionView.prototype.render = function() {
- var listSelector;
- CollectionView.__super__.render.apply(this, arguments);
- listSelector = _.result(this, 'listSelector');
- if ($) {
- this.$list = listSelector ? this.$(listSelector) : this.$el;
- } else {
- this.list = listSelector ? this.find(this.listSelector) : this.el;
- }
- this.initFallback();
- this.initLoadingIndicator();
- if (this.renderItems) {
- return this.renderAllItems();
- }
- };
-
- CollectionView.prototype.itemAdded = function(item, collection, options) {
- return this.insertView(item, this.renderItem(item), options.at);
- };
-
- CollectionView.prototype.itemRemoved = function(item) {
- return this.removeViewForItem(item);
- };
-
- CollectionView.prototype.itemsReset = function() {
- return this.renderAllItems();
- };
-
- CollectionView.prototype.initFallback = function() {
- if (!this.fallbackSelector) {
- return;
- }
- if ($) {
- this.$fallback = this.$(this.fallbackSelector);
- } else {
- this.fallback = this.find(this.fallbackSelector);
- }
- this.on('visibilityChange', this.toggleFallback);
- this.listenTo(this.collection, 'syncStateChange', this.toggleFallback);
- return this.toggleFallback();
- };
-
- CollectionView.prototype.toggleFallback = function() {
- var visible;
- visible = this.visibleItems.length === 0 && (typeof this.collection.isSynced === 'function' ? this.collection.isSynced() : true);
- return toggleElement(($ ? this.$fallback : this.fallback), visible);
- };
-
- CollectionView.prototype.initLoadingIndicator = function() {
- if (!(this.loadingSelector && typeof this.collection.isSyncing === 'function')) {
- return;
- }
- if ($) {
- this.$loading = this.$(this.loadingSelector);
- } else {
- this.loading = this.find(this.loadingSelector);
- }
- this.listenTo(this.collection, 'syncStateChange', this.toggleLoadingIndicator);
- return this.toggleLoadingIndicator();
- };
-
- CollectionView.prototype.toggleLoadingIndicator = function() {
- var visible;
- visible = this.collection.length === 0 && this.collection.isSyncing();
- return toggleElement(($ ? this.$loading : this.loading), visible);
- };
-
- CollectionView.prototype.getItemViews = function() {
- var itemViews, name, view, _ref;
- itemViews = {};
- if (this.subviews.length > 0) {
- _ref = this.subviewsByName;
- for (name in _ref) {
- view = _ref[name];
- if (name.slice(0, 9) === 'itemView:') {
- itemViews[name.slice(9)] = view;
- }
- }
- }
- return itemViews;
- };
-
- CollectionView.prototype.filter = function(filterer, filterCallback) {
- var hasItemViews, included, index, item, view, _i, _len, _ref,
- _this = this;
- if (typeof filterer === 'function' || filterer === null) {
- this.filterer = filterer;
- }
- if (typeof filterCallback === 'function' || filterCallback === null) {
- this.filterCallback = filterCallback;
- }
- hasItemViews = (function() {
- var name;
- if (_this.subviews.length > 0) {
- for (name in _this.subviewsByName) {
- if (name.slice(0, 9) === 'itemView:') {
- return true;
- }
- }
- }
- return false;
- })();
- if (hasItemViews) {
- _ref = this.collection.models;
- for (index = _i = 0, _len = _ref.length; _i < _len; index = ++_i) {
- item = _ref[index];
- included = typeof this.filterer === 'function' ? this.filterer(item, index) : true;
- view = this.subview("itemView:" + item.cid);
- if (!view) {
- throw new Error('CollectionView#filter: ' + ("no view found for " + item.cid));
- }
- this.filterCallback(view, included);
- this.updateVisibleItems(view.model, included, false);
- }
- }
- return this.trigger('visibilityChange', this.visibleItems);
- };
-
- CollectionView.prototype.renderAllItems = function() {
- var cid, index, item, items, remainingViewsByCid, view, _i, _j, _len, _len1, _ref;
- items = this.collection.models;
- this.visibleItems = [];
- remainingViewsByCid = {};
- for (_i = 0, _len = items.length; _i < _len; _i++) {
- item = items[_i];
- view = this.subview("itemView:" + item.cid);
- if (view) {
- remainingViewsByCid[item.cid] = view;
- }
- }
- _ref = this.getItemViews();
- for (cid in _ref) {
- if (!__hasProp.call(_ref, cid)) continue;
- view = _ref[cid];
- if (!(cid in remainingViewsByCid)) {
- this.removeSubview("itemView:" + cid);
- }
- }
- for (index = _j = 0, _len1 = items.length; _j < _len1; index = ++_j) {
- item = items[index];
- view = this.subview("itemView:" + item.cid);
- if (view) {
- this.insertView(item, view, index, false);
- } else {
- this.insertView(item, this.renderItem(item), index);
- }
- }
- if (items.length === 0) {
- return this.trigger('visibilityChange', this.visibleItems);
- }
- };
-
- CollectionView.prototype.renderItem = function(item) {
- var view;
- view = this.subview("itemView:" + item.cid);
- if (!view) {
- view = this.initItemView(item);
- this.subview("itemView:" + item.cid, view);
- }
- view.render();
- return view;
- };
-
- CollectionView.prototype.initItemView = function(model) {
- if (this.itemView) {
- return new this.itemView({
- autoRender: false,
- model: model
- });
- } else {
- throw new Error('The CollectionView#itemView property ' + 'must be defined or the initItemView() must be overridden.');
- }
- };
-
- CollectionView.prototype.insertView = function(item, view, position, enableAnimation) {
- var elem, included, length, list,
- _this = this;
- if (enableAnimation == null) {
- enableAnimation = true;
- }
- if (this.animationDuration === 0) {
- enableAnimation = false;
- }
- if (typeof position !== 'number') {
- position = this.collection.indexOf(item);
- }
- included = typeof this.filterer === 'function' ? this.filterer(item, position) : true;
- elem = $ ? view.$el : view.el;
- if (included && enableAnimation) {
- startAnimation(elem, this.useCssAnimation, this.animationStartClass);
- }
- if (this.filterer) {
- this.filterCallback(view, included);
- }
- length = this.collection.length;
- list = $ ? this.$list : this.list;
- insertView(list, elem, position, length, this.itemSelector);
- view.trigger('addedToParent');
- this.updateVisibleItems(item, included);
- if (included && enableAnimation) {
- if (this.useCssAnimation) {
- setTimeout((function() {
- return addClass(elem, _this.animationEndClass);
- }), 0);
- } else {
- endAnimation(elem, this.animationDuration);
- }
- }
- return view;
- };
-
- CollectionView.prototype.removeViewForItem = function(item) {
- this.updateVisibleItems(item, false);
- return this.removeSubview("itemView:" + item.cid);
- };
-
- CollectionView.prototype.updateVisibleItems = function(item, includedInFilter, triggerEvent) {
- var includedInVisibleItems, visibilityChanged, visibleItemsIndex;
- if (triggerEvent == null) {
- triggerEvent = true;
- }
- visibilityChanged = false;
- visibleItemsIndex = utils.indexOf(this.visibleItems, item);
- includedInVisibleItems = visibleItemsIndex !== -1;
- if (includedInFilter && !includedInVisibleItems) {
- this.visibleItems.push(item);
- visibilityChanged = true;
- } else if (!includedInFilter && includedInVisibleItems) {
- this.visibleItems.splice(visibleItemsIndex, 1);
- visibilityChanged = true;
- }
- if (visibilityChanged && triggerEvent) {
- this.trigger('visibilityChange', this.visibleItems);
- }
- return visibilityChanged;
- };
-
- CollectionView.prototype.dispose = function() {
- var prop, properties, _i, _len;
- if (this.disposed) {
- return;
- }
- properties = ['$list', '$fallback', '$loading', 'visibleItems'];
- for (_i = 0, _len = properties.length; _i < _len; _i++) {
- prop = properties[_i];
- delete this[prop];
- }
- return CollectionView.__super__.dispose.apply(this, arguments);
- };
-
- return CollectionView;
-
-})(View);
-
-});;loader.register('chaplin/lib/route', function(e, r, module) {
-'use strict';
-
-var Backbone, Controller, EventBroker, Route, utils, _,
- __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
- __hasProp = {}.hasOwnProperty;
-
-_ = loader('underscore');
-
-Backbone = loader('backbone');
-
-EventBroker = loader('chaplin/lib/event_broker');
-
-Controller = loader('chaplin/controllers/controller');
-
-utils = loader('chaplin/lib/utils');
-
-module.exports = Route = (function() {
- var escapeRegExp, optionalRegExp, paramRegExp, processTrailingSlash;
-
- Route.extend = Backbone.Model.extend;
-
- _.extend(Route.prototype, EventBroker);
-
- escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
-
- optionalRegExp = /\((.*?)\)/g;
-
- paramRegExp = /(?::|\*)(\w+)/g;
-
- processTrailingSlash = function(path, trailing) {
- switch (trailing) {
- case true:
- if (path.slice(-1) !== '/') {
- path += '/';
- }
- break;
- case false:
- if (path.slice(-1) === '/') {
- path = path.slice(0, -1);
- }
- }
- return path;
- };
-
- function Route(pattern, controller, action, options) {
- var _ref;
- this.pattern = pattern;
- this.controller = controller;
- this.action = action;
- this.handler = __bind(this.handler, this);
-
- this.replaceParams = __bind(this.replaceParams, this);
-
- this.parseOptionalPortion = __bind(this.parseOptionalPortion, this);
-
- if (typeof this.pattern !== 'string') {
- throw new Error('Route: RegExps are not supported.\
- Use strings with :names and `constraints` option of route');
- }
- this.options = options ? _.extend({}, options) : {};
- if (this.options.paramsInQS !== false) {
- this.options.paramsInQS = true;
- }
- if (this.options.name != null) {
- this.name = this.options.name;
- }
- if (this.name && this.name.indexOf('#') !== -1) {
- throw new Error('Route: "#" cannot be used in name');
- }
- if ((_ref = this.name) == null) {
- this.name = this.controller + '#' + this.action;
- }
- this.allParams = [];
- this.requiredParams = [];
- this.optionalParams = [];
- if (this.action in Controller.prototype) {
- throw new Error('Route: You should not use existing controller ' + 'properties as action names');
- }
- this.createRegExp();
- if (typeof Object.freeze === "function") {
- Object.freeze(this);
- }
- }
-
- Route.prototype.matches = function(criteria) {
- var invalidParamsCount, name, propertiesCount, property, _i, _len, _ref;
- if (typeof criteria === 'string') {
- return criteria === this.name;
- } else {
- propertiesCount = 0;
- _ref = ['name', 'action', 'controller'];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- name = _ref[_i];
- propertiesCount++;
- property = criteria[name];
- if (property && property !== this[name]) {
- return false;
- }
- }
- invalidParamsCount = propertiesCount === 1 && (name === 'action' || name === 'controller');
- return !invalidParamsCount;
- }
- };
-
- Route.prototype.reverse = function(params, query) {
- var name, raw, remainingParams, url, value, _i, _j, _len, _len1, _ref, _ref1;
- params = this.normalizeParams(params);
- remainingParams = _.extend({}, params);
- if (params === false) {
- return false;
- }
- url = this.pattern;
- _ref = this.requiredParams;
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- name = _ref[_i];
- value = params[name];
- url = url.replace(RegExp("[:*]" + name, "g"), value);
- delete remainingParams[name];
- }
- _ref1 = this.optionalParams;
- for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
- name = _ref1[_j];
- if (value = params[name]) {
- url = url.replace(RegExp("[:*]" + name, "g"), value);
- delete remainingParams[name];
- }
- }
- raw = url.replace(optionalRegExp, function(match, portion) {
- if (portion.match(/[:*]/g)) {
- return "";
- } else {
- return portion;
- }
- });
- url = processTrailingSlash(raw, this.options.trailing);
- if (typeof query !== 'object') {
- query = utils.queryParams.parse(query);
- }
- if (this.options.paramsInQS !== false) {
- _.extend(query, remainingParams);
- }
- if (!_.isEmpty(query)) {
- url += '?' + utils.queryParams.stringify(query);
- }
- return url;
- };
-
- Route.prototype.normalizeParams = function(params) {
- var paramIndex, paramName, paramsHash, _i, _len, _ref;
- if (utils.isArray(params)) {
- if (params.length < this.requiredParams.length) {
- return false;
- }
- paramsHash = {};
- _ref = this.requiredParams;
- for (paramIndex = _i = 0, _len = _ref.length; _i < _len; paramIndex = ++_i) {
- paramName = _ref[paramIndex];
- paramsHash[paramName] = params[paramIndex];
- }
- if (!this.testConstraints(paramsHash)) {
- return false;
- }
- params = paramsHash;
- } else {
- if (params == null) {
- params = {};
- }
- if (!this.testParams(params)) {
- return false;
- }
- }
- return params;
- };
-
- Route.prototype.testConstraints = function(params) {
- var constraint, constraints, name;
- constraints = this.options.constraints;
- if (constraints) {
- for (name in constraints) {
- if (!__hasProp.call(constraints, name)) continue;
- constraint = constraints[name];
- if (!constraint.test(params[name])) {
- return false;
- }
- }
- }
- return true;
- };
-
- Route.prototype.testParams = function(params) {
- var paramName, _i, _len, _ref;
- _ref = this.requiredParams;
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- paramName = _ref[_i];
- if (params[paramName] === void 0) {
- return false;
- }
- }
- return this.testConstraints(params);
- };
-
- Route.prototype.createRegExp = function() {
- var pattern,
- _this = this;
- pattern = this.pattern;
- pattern = pattern.replace(escapeRegExp, '\\$&');
- this.replaceParams(pattern, function(match, param) {
- return _this.allParams.push(param);
- });
- pattern = pattern.replace(optionalRegExp, this.parseOptionalPortion);
- pattern = this.replaceParams(pattern, function(match, param) {
- _this.requiredParams.push(param);
- return _this.paramCapturePattern(match);
- });
- return this.regExp = RegExp("^" + pattern + "(?=\\/*(?=\\?|$))");
- };
-
- Route.prototype.parseOptionalPortion = function(match, optionalPortion) {
- var portion,
- _this = this;
- portion = this.replaceParams(optionalPortion, function(match, param) {
- _this.optionalParams.push(param);
- return _this.paramCapturePattern(match);
- });
- return "(?:" + portion + ")?";
- };
-
- Route.prototype.replaceParams = function(s, callback) {
- return s.replace(paramRegExp, callback);
- };
-
- Route.prototype.paramCapturePattern = function(param) {
- if (param.charAt(0) === ':') {
- return '([^\/\?]+)';
- } else {
- return '(.*?)';
- }
- };
-
- Route.prototype.test = function(path) {
- var constraints, matched;
- matched = this.regExp.test(path);
- if (!matched) {
- return false;
- }
- constraints = this.options.constraints;
- if (constraints) {
- return this.testConstraints(this.extractParams(path));
- }
- return true;
- };
-
- Route.prototype.handler = function(pathParams, options) {
- var actionParams, params, path, query, route, _ref;
- options = options ? _.extend({}, options) : {};
- if (typeof pathParams === 'object') {
- query = utils.queryParams.stringify(options.query);
- params = pathParams;
- path = this.reverse(params);
- } else {
- _ref = pathParams.split('?'), path = _ref[0], query = _ref[1];
- if (!(query != null)) {
- query = '';
- } else {
- options.query = utils.queryParams.parse(query);
- }
- params = this.extractParams(path);
- path = processTrailingSlash(path, this.options.trailing);
- }
- actionParams = _.extend({}, params, this.options.params);
- route = {
- path: path,
- action: this.action,
- controller: this.controller,
- name: this.name,
- query: query
- };
- return this.publishEvent('router:match', route, actionParams, options);
- };
-
- Route.prototype.extractParams = function(path) {
- var index, match, matches, paramName, params, _i, _len, _ref;
- params = {};
- matches = this.regExp.exec(path);
- _ref = matches.slice(1);
- for (index = _i = 0, _len = _ref.length; _i < _len; index = ++_i) {
- match = _ref[index];
- paramName = this.allParams.length ? this.allParams[index] : index;
- params[paramName] = match;
- }
- return params;
- };
-
- return Route;
-
-})();
-
-});;loader.register('chaplin/lib/router', function(e, r, module) {
-'use strict';
-
-var Backbone, EventBroker, History, Route, Router, mediator, utils, _,
- __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
-
-_ = loader('underscore');
-
-Backbone = loader('backbone');
-
-mediator = loader('chaplin/mediator');
-
-EventBroker = loader('chaplin/lib/event_broker');
-
-History = loader('chaplin/lib/history');
-
-Route = loader('chaplin/lib/route');
-
-utils = loader('chaplin/lib/utils');
-
-module.exports = Router = (function() {
-
- Router.extend = Backbone.Model.extend;
-
- _.extend(Router.prototype, EventBroker);
-
- function Router(options) {
- var isWebFile;
- this.options = options != null ? options : {};
- this.match = __bind(this.match, this);
-
- isWebFile = window.location.protocol !== 'file:';
- _.defaults(this.options, {
- pushState: isWebFile,
- root: '/',
- trailing: false
- });
- this.removeRoot = new RegExp('^' + utils.escapeRegExp(this.options.root) + '(#)?');
- this.subscribeEvent('!router:route', this.oldEventError);
- this.subscribeEvent('!router:routeByName', this.oldEventError);
- this.subscribeEvent('!router:changeURL', this.oldURLEventError);
- this.subscribeEvent('dispatcher:dispatch', this.changeURL);
- mediator.setHandler('router:route', this.route, this);
- mediator.setHandler('router:reverse', this.reverse, this);
- this.createHistory();
- }
-
- Router.prototype.oldEventError = function() {
- throw new Error('!router:route and !router:routeByName events were removed.\
- Use `Chaplin.utils.redirectTo`');
- };
-
- Router.prototype.oldURLEventError = function() {
- throw new Error('!router:changeURL event was removed.');
- };
-
- Router.prototype.createHistory = function() {
- return Backbone.history = new History();
- };
-
- Router.prototype.startHistory = function() {
- return Backbone.history.start(this.options);
- };
-
- Router.prototype.stopHistory = function() {
- if (Backbone.History.started) {
- return Backbone.history.stop();
- }
- };
-
- Router.prototype.findHandler = function(predicate) {
- var handler, _i, _len, _ref;
- _ref = Backbone.history.handlers;
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- handler = _ref[_i];
- if (predicate(handler)) {
- return handler;
- }
- }
- };
-
- Router.prototype.match = function(pattern, target, options) {
- var action, controller, route, _ref;
- if (options == null) {
- options = {};
- }
- if (arguments.length === 2 && typeof target === 'object') {
- options = target;
- controller = options.controller, action = options.action;
- if (!(controller && action)) {
- throw new Error('Router#match must receive either target or ' + 'options.controller & options.action');
- }
- } else {
- controller = options.controller, action = options.action;
- if (controller || action) {
- throw new Error('Router#match cannot use both target and ' + 'options.controller / options.action');
- }
- _ref = target.split('#'), controller = _ref[0], action = _ref[1];
- }
- _.defaults(options, {
- trailing: this.options.trailing
- });
- route = new Route(pattern, controller, action, options);
- Backbone.history.handlers.push({
- route: route,
- callback: route.handler
- });
- return route;
- };
-
- Router.prototype.route = function(pathDesc, params, options) {
- var handler, path, pathParams;
- if (typeof pathDesc === 'object') {
- path = pathDesc.url;
- if (!params && pathDesc.params) {
- params = pathDesc.params;
- }
- }
- params = params ? utils.isArray(params) ? params.slice() : _.extend({}, params) : {};
- if (path != null) {
- path = path.replace(this.removeRoot, '');
- handler = this.findHandler(function(handler) {
- return handler.route.test(path);
- });
- options = params;
- params = null;
- } else {
- options = options ? _.extend({}, options) : {};
- handler = this.findHandler(function(handler) {
- if (handler.route.matches(pathDesc)) {
- params = handler.route.normalizeParams(params);
- if (params) {
- return true;
- }
- }
- return false;
- });
- }
- if (handler) {
- _.defaults(options, {
- changeURL: true
- });
- pathParams = path != null ? path : params;
- handler.callback(pathParams, options);
- return true;
- } else {
- throw new Error('Router#route: request was not routed');
- }
- };
-
- Router.prototype.reverse = function(criteria, params, query) {
- var handler, handlers, reversed, root, url, _i, _len;
- root = this.options.root;
- if ((params != null) && typeof params !== 'object') {
- throw new TypeError('Router#reverse: params must be an array or an ' + 'object');
- }
- handlers = Backbone.history.handlers;
- for (_i = 0, _len = handlers.length; _i < _len; _i++) {
- handler = handlers[_i];
- if (!(handler.route.matches(criteria))) {
- continue;
- }
- reversed = handler.route.reverse(params, query);
- if (reversed !== false) {
- url = root ? root + reversed : reversed;
- return url;
- }
- }
- throw new Error("Router#reverse: invalid route criteria specified: " + (JSON.stringify(criteria)));
- };
-
- Router.prototype.changeURL = function(controller, params, route, options) {
- var navigateOptions, url;
- if (!((route.path != null) && options.changeURL)) {
- return;
- }
- url = route.path + (route.query ? "?" + route.query : "");
- navigateOptions = {
- trigger: options.trigger === true,
- replace: options.replace === true
- };
- return Backbone.history.navigate(url, navigateOptions);
- };
-
- Router.prototype.disposed = false;
-
- Router.prototype.dispose = function() {
- if (this.disposed) {
- return;
- }
- this.stopHistory();
- delete Backbone.history;
- this.unsubscribeAllEvents();
- mediator.removeHandlers(this);
- this.disposed = true;
- return typeof Object.freeze === "function" ? Object.freeze(this) : void 0;
- };
-
- return Router;
-
-})();
-
-});;loader.register('chaplin/lib/history', function(e, r, module) {
-'use strict';
-
-var Backbone, History, isExplorer, rootStripper, routeStripper, trailingSlash, _,
- __hasProp = {}.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
-
-_ = loader('underscore');
-
-Backbone = loader('backbone');
-
-routeStripper = /^[#\/]|\s+$/g;
-
-rootStripper = /^\/+|\/+$/g;
-
-isExplorer = /msie [\w.]+/;
-
-trailingSlash = /\/$/;
-
-History = (function(_super) {
-
- __extends(History, _super);
-
- function History() {
- return History.__super__.constructor.apply(this, arguments);
- }
-
- History.prototype.getFragment = function(fragment, forcePushState) {
- var root;
- if (!(fragment != null)) {
- if (this._hasPushState || !this._wantsHashChange || forcePushState) {
- fragment = this.location.pathname + this.location.search;
- root = this.root.replace(trailingSlash, '');
- if (!fragment.indexOf(root)) {
- fragment = fragment.substr(root.length);
- }
- } else {
- fragment = this.getHash();
- }
- }
- return fragment.replace(routeStripper, '');
- };
-
- History.prototype.start = function(options) {
- var atRoot, fragment, loc, _ref, _ref1;
- if (Backbone.History.started) {
- throw new Error('Backbone.history has already been started');
- }
- Backbone.History.started = true;
- this.options = _.extend({}, {
- root: '/'
- }, this.options, options);
- this.root = this.options.root;
- this._wantsHashChange = this.options.hashChange !== false;
- this._wantsPushState = Boolean(this.options.pushState);
- this._hasPushState = Boolean(this.options.pushState && this.history && this.history.pushState);
- fragment = this.getFragment();
- routeStripper = (_ref = this.options.routeStripper) != null ? _ref : routeStripper;
- rootStripper = (_ref1 = this.options.rootStripper) != null ? _ref1 : rootStripper;
- this.root = ('/' + this.root + '/').replace(rootStripper, '/');
- if (this._hasPushState) {
- Backbone.$(window).on('popstate', this.checkUrl);
- } else if (this._wantsHashChange && 'onhashchange' in window) {
- Backbone.$(window).on('hashchange', this.checkUrl);
- } else if (this._wantsHashChange) {
- this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
- }
- this.fragment = fragment;
- loc = this.location;
- atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
- if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
- this.fragment = this.getFragment(null, true);
- this.location.replace(this.root + '#' + this.fragment);
- return true;
- } else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
- this.fragment = this.getHash().replace(routeStripper, '');
- this.history.replaceState({}, document.title, this.root + this.fragment);
- }
- if (!this.options.silent) {
- return this.loadUrl();
- }
- };
-
- History.prototype.navigate = function(fragment, options) {
- var historyMethod, isSameFragment, url;
- if (fragment == null) {
- fragment = '';
- }
- if (!Backbone.History.started) {
- return false;
- }
- if (!options || options === true) {
- options = {
- trigger: options
- };
- }
- fragment = this.getFragment(fragment);
- url = this.root + fragment;
- if (this.fragment === fragment) {
- return false;
- }
- this.fragment = fragment;
- if (fragment.length === 0 && url !== '/' && (url !== this.root || this.options.trailing !== true)) {
- url = url.slice(0, -1);
- }
- if (this._hasPushState) {
- historyMethod = options.replace ? 'replaceState' : 'pushState';
- this.history[historyMethod]({}, document.title, url);
- } else if (this._wantsHashChange) {
- this._updateHash(this.location, fragment, options.replace);
- isSameFragment = fragment !== this.getFragment(this.getHash(this.iframe));
- if ((this.iframe != null) && isSameFragment) {
- if (!options.replace) {
- this.iframe.document.open().close();
- }
- this._updateHash(this.iframe.location, fragment, options.replace);
- }
- } else {
- return this.location.assign(url);
- }
- if (options.trigger) {
- return this.loadUrl(fragment);
- }
- };
-
- return History;
-
-})(Backbone.History);
-
-module.exports = Backbone.$ ? History : Backbone.History;
-
-});;loader.register('chaplin/lib/event_broker', function(e, r, module) {
-'use strict';
-
-var EventBroker, mediator,
- __slice = [].slice;
-
-mediator = loader('chaplin/mediator');
-
-EventBroker = {
- subscribeEvent: function(type, handler) {
- if (typeof type !== 'string') {
- throw new TypeError('EventBroker#subscribeEvent: ' + 'type argument must be a string');
- }
- if (typeof handler !== 'function') {
- throw new TypeError('EventBroker#subscribeEvent: ' + 'handler argument must be a function');
- }
- mediator.unsubscribe(type, handler, this);
- return mediator.subscribe(type, handler, this);
- },
- subscribeEventOnce: function(type, handler) {
- if (typeof type !== 'string') {
- throw new TypeError('EventBroker#subscribeEventOnce: ' + 'type argument must be a string');
- }
- if (typeof handler !== 'function') {
- throw new TypeError('EventBroker#subscribeEventOnce: ' + 'handler argument must be a function');
- }
- mediator.unsubscribe(type, handler, this);
- return mediator.subscribeOnce(type, handler, this);
- },
- unsubscribeEvent: function(type, handler) {
- if (typeof type !== 'string') {
- throw new TypeError('EventBroker#unsubscribeEvent: ' + 'type argument must be a string');
- }
- if (typeof handler !== 'function') {
- throw new TypeError('EventBroker#unsubscribeEvent: ' + 'handler argument must be a function');
- }
- return mediator.unsubscribe(type, handler);
- },
- unsubscribeAllEvents: function() {
- return mediator.unsubscribe(null, null, this);
- },
- publishEvent: function() {
- var args, type;
- type = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
- if (typeof type !== 'string') {
- throw new TypeError('EventBroker#publishEvent: ' + 'type argument must be a string');
- }
- return mediator.publish.apply(mediator, [type].concat(__slice.call(args)));
- }
-};
-
-if (typeof Object.freeze === "function") {
- Object.freeze(EventBroker);
-}
-
-module.exports = EventBroker;
-
-});;loader.register('chaplin/lib/support', function(e, r, module) {
-'use strict';
-
-var support;
-
-support = {
- propertyDescriptors: (function() {
- var o;
- if (!(typeof Object.defineProperty === 'function' && typeof Object.defineProperties === 'function')) {
- return false;
- }
- try {
- o = {};
- Object.defineProperty(o, 'foo', {
- value: 'bar'
- });
- return o.foo === 'bar';
- } catch (error) {
- return false;
- }
- })()
-};
-
-module.exports = support;
-
-});;loader.register('chaplin/lib/composition', function(e, r, module) {
-'use strict';
-
-var Backbone, Composition, EventBroker, has, _,
- __hasProp = {}.hasOwnProperty;
-
-_ = loader('underscore');
-
-Backbone = loader('backbone');
-
-EventBroker = loader('chaplin/lib/event_broker');
-
-has = Object.prototype.hasOwnProperty;
-
-module.exports = Composition = (function() {
-
- Composition.extend = Backbone.Model.extend;
-
- _.extend(Composition.prototype, Backbone.Events);
-
- _.extend(Composition.prototype, EventBroker);
-
- Composition.prototype.item = null;
-
- Composition.prototype.options = null;
-
- Composition.prototype._stale = false;
-
- function Composition(options) {
- if (options != null) {
- this.options = _.extend({}, options);
- }
- this.item = this;
- this.initialize(this.options);
- }
-
- Composition.prototype.initialize = function() {};
-
- Composition.prototype.compose = function() {};
-
- Composition.prototype.check = function(options) {
- return _.isEqual(this.options, options);
- };
-
- Composition.prototype.stale = function(value) {
- var item, name;
- if (value == null) {
- return this._stale;
- }
- this._stale = value;
- for (name in this) {
- item = this[name];
- if (item && item !== this && typeof item === 'object' && has.call(item, 'stale')) {
- item.stale = value;
- }
- }
- };
-
- Composition.prototype.disposed = false;
-
- Composition.prototype.dispose = function() {
- var obj, prop, properties, _i, _len;
- if (this.disposed) {
- return;
- }
- for (prop in this) {
- if (!__hasProp.call(this, prop)) continue;
- obj = this[prop];
- if (obj && typeof obj.dispose === 'function') {
- if (obj !== this) {
- obj.dispose();
- delete this[prop];
- }
- }
- }
- this.unsubscribeAllEvents();
- this.stopListening();
- properties = ['redirected'];
- for (_i = 0, _len = properties.length; _i < _len; _i++) {
- prop = properties[_i];
- delete this[prop];
- }
- this.disposed = true;
- return typeof Object.freeze === "function" ? Object.freeze(this) : void 0;
- };
-
- return Composition;
-
-})();
-
-});;loader.register('chaplin/lib/sync_machine', function(e, r, module) {
-'use strict';
-
-var STATE_CHANGE, SYNCED, SYNCING, SyncMachine, UNSYNCED, event, _fn, _i, _len, _ref;
-
-UNSYNCED = 'unsynced';
-
-SYNCING = 'syncing';
-
-SYNCED = 'synced';
-
-STATE_CHANGE = 'syncStateChange';
-
-SyncMachine = {
- _syncState: UNSYNCED,
- _previousSyncState: null,
- syncState: function() {
- return this._syncState;
- },
- isUnsynced: function() {
- return this._syncState === UNSYNCED;
- },
- isSynced: function() {
- return this._syncState === SYNCED;
- },
- isSyncing: function() {
- return this._syncState === SYNCING;
- },
- unsync: function() {
- var _ref;
- if ((_ref = this._syncState) === SYNCING || _ref === SYNCED) {
- this._previousSync = this._syncState;
- this._syncState = UNSYNCED;
- this.trigger(this._syncState, this, this._syncState);
- this.trigger(STATE_CHANGE, this, this._syncState);
- }
- },
- beginSync: function() {
- var _ref;
- if ((_ref = this._syncState) === UNSYNCED || _ref === SYNCED) {
- this._previousSync = this._syncState;
- this._syncState = SYNCING;
- this.trigger(this._syncState, this, this._syncState);
- this.trigger(STATE_CHANGE, this, this._syncState);
- }
- },
- finishSync: function() {
- if (this._syncState === SYNCING) {
- this._previousSync = this._syncState;
- this._syncState = SYNCED;
- this.trigger(this._syncState, this, this._syncState);
- this.trigger(STATE_CHANGE, this, this._syncState);
- }
- },
- abortSync: function() {
- if (this._syncState === SYNCING) {
- this._syncState = this._previousSync;
- this._previousSync = this._syncState;
- this.trigger(this._syncState, this, this._syncState);
- this.trigger(STATE_CHANGE, this, this._syncState);
- }
- }
-};
-
-_ref = [UNSYNCED, SYNCING, SYNCED, STATE_CHANGE];
-_fn = function(event) {
- return SyncMachine[event] = function(callback, context) {
- if (context == null) {
- context = this;
- }
- this.on(event, callback, context);
- if (this._syncState === event) {
- return callback.call(context);
- }
- };
-};
-for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- event = _ref[_i];
- _fn(event);
-}
-
-if (typeof Object.freeze === "function") {
- Object.freeze(SyncMachine);
-}
-
-module.exports = SyncMachine;
-
-});;loader.register('chaplin/lib/utils', function(e, r, module) {
-'use strict';
-
-var support, utils, _,
- __slice = [].slice,
- __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
- __hasProp = {}.hasOwnProperty;
-
-_ = loader('underscore');
-
-support = loader('chaplin/lib/support');
-
-utils = {
- beget: (function() {
- var ctor;
- if (typeof Object.create === 'function') {
- return Object.create;
- } else {
- ctor = function() {};
- return function(obj) {
- ctor.prototype = obj;
- return new ctor;
- };
- }
- })(),
- indexOf: (function() {
- if (Array.prototype.indexOf) {
- return function(list, index) {
- return list.indexOf(index);
- };
- } else if (_.indexOf) {
- return _.indexOf;
- }
- })(),
- isArray: Array.isArray || _.isArray,
- serialize: function(data) {
- if (typeof data.serialize === 'function') {
- return data.serialize();
- } else if (typeof data.toJSON === 'function') {
- return data.toJSON();
- } else {
- throw new TypeError('utils.serialize: Unknown data was passed');
- }
- },
- readonly: (function() {
- var readonlyDescriptor;
- if (support.propertyDescriptors) {
- readonlyDescriptor = {
- writable: false,
- enumerable: true,
- configurable: false
- };
- return function() {
- var obj, prop, properties, _i, _len;
- obj = arguments[0], properties = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
- for (_i = 0, _len = properties.length; _i < _len; _i++) {
- prop = properties[_i];
- readonlyDescriptor.value = obj[prop];
- Object.defineProperty(obj, prop, readonlyDescriptor);
- }
- return true;
- };
- } else {
- return function() {
- return false;
- };
- }
- })(),
- getPrototypeChain: function(object) {
- var chain, _ref, _ref1, _ref2, _ref3;
- chain = [object.constructor.prototype];
- while (object = (_ref = (_ref1 = object.constructor) != null ? (_ref2 = _ref1.superclass) != null ? _ref2.prototype : void 0 : void 0) != null ? _ref : (_ref3 = object.constructor) != null ? _ref3.__super__ : void 0) {
- chain.push(object);
- }
- return chain.reverse();
- },
- getAllPropertyVersions: function(object, property) {
- var proto, result, value, _i, _len, _ref;
- result = [];
- _ref = utils.getPrototypeChain(object);
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- proto = _ref[_i];
- value = proto[property];
- if (value && __indexOf.call(result, value) < 0) {
- result.push(value);
- }
- }
- return result;
- },
- upcase: function(str) {
- return str.charAt(0).toUpperCase() + str.substring(1);
- },
- escapeRegExp: function(str) {
- return String(str || '').replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
- },
- modifierKeyPressed: function(event) {
- return event.shiftKey || event.altKey || event.ctrlKey || event.metaKey;
- },
- reverse: function(criteria, params, query) {
- return loader('chaplin/mediator').execute('router:reverse', criteria, params, query);
- },
- redirectTo: function(pathDesc, params, options) {
- return loader('chaplin/mediator').execute('router:route', pathDesc, params, options);
- },
- querystring: {
- stringify: function(queryParams) {
- var arrParam, encodedKey, key, query, stringifyKeyValuePair, value, _i, _len;
- query = '';
- stringifyKeyValuePair = function(encodedKey, value) {
- if (value != null) {
- return '&' + encodedKey + '=' + encodeURIComponent(value);
- } else {
- return '';
- }
- };
- for (key in queryParams) {
- if (!__hasProp.call(queryParams, key)) continue;
- value = queryParams[key];
- encodedKey = encodeURIComponent(key);
- if (utils.isArray(value)) {
- for (_i = 0, _len = value.length; _i < _len; _i++) {
- arrParam = value[_i];
- query += stringifyKeyValuePair(encodedKey, arrParam);
- }
- } else {
- query += stringifyKeyValuePair(encodedKey, value);
- }
- }
- return query && query.substring(1);
- },
- parse: function(queryString) {
- var current, field, pair, pairs, params, value, _i, _len, _ref;
- params = {};
- if (!queryString) {
- return params;
- }
- queryString = queryString.slice(queryString.indexOf('?') + 1);
- pairs = queryString.split('&');
- for (_i = 0, _len = pairs.length; _i < _len; _i++) {
- pair = pairs[_i];
- if (!pair.length) {
- continue;
- }
- _ref = pair.split('='), field = _ref[0], value = _ref[1];
- if (!field.length) {
- continue;
- }
- field = decodeURIComponent(field);
- value = decodeURIComponent(value);
- current = params[field];
- if (current) {
- if (current.push) {
- current.push(value);
- } else {
- params[field] = [current, value];
- }
- } else {
- params[field] = value;
- }
- }
- return params;
- }
- }
-};
-
-utils.queryParams = utils.querystring;
-
-if (typeof Object.seal === "function") {
- Object.seal(utils);
-}
-
-module.exports = utils;
-
-});;loader.register('chaplin', function(e, r, module) {
-
-module.exports = {
- Application: loader('chaplin/application'),
- mediator: loader('chaplin/mediator'),
- Dispatcher: loader('chaplin/dispatcher'),
- Controller: loader('chaplin/controllers/controller'),
- Composer: loader('chaplin/composer'),
- Composition: loader('chaplin/lib/composition'),
- Collection: loader('chaplin/models/collection'),
- Model: loader('chaplin/models/model'),
- Layout: loader('chaplin/views/layout'),
- View: loader('chaplin/views/view'),
- CollectionView: loader('chaplin/views/collection_view'),
- Route: loader('chaplin/lib/route'),
- Router: loader('chaplin/lib/router'),
- EventBroker: loader('chaplin/lib/event_broker'),
- support: loader('chaplin/lib/support'),
- SyncMachine: loader('chaplin/lib/sync_machine'),
- utils: loader('chaplin/lib/utils')
-};
-
-});
-var regDeps = function(Backbone, _) {
- loader.register('backbone', function(exports, require, module) {
- module.exports = Backbone;
- });
- loader.register('underscore', function(exports, require, module) {
- module.exports = _;
- });
-};
-
-if (typeof define === 'function' && define.amd) {
- define(['backbone', 'underscore'], function(Backbone, _) {
- regDeps(Backbone, _);
- return loader('chaplin');
- });
-} else if (typeof module === 'object' && module && module.exports) {
- regDeps(require('backbone'), require('underscore'));
- module.exports = loader('chaplin');
-} else if (typeof require === 'function') {
- regDeps(window.Backbone, window._ || window.Backbone.utils);
- window.Chaplin = loader('chaplin');
-} else {
- throw new Error('Chaplin requires Common.js or AMD modules');
-}
-
-})();
\ No newline at end of file
diff --git a/examples/chaplin-brunch/node_modules/exoskeleton/exoskeleton.js b/examples/chaplin-brunch/node_modules/exoskeleton/exoskeleton.js
deleted file mode 100644
index 8bf783a937..0000000000
--- a/examples/chaplin-brunch/node_modules/exoskeleton/exoskeleton.js
+++ /dev/null
@@ -1,1960 +0,0 @@
-/*!
- * Exoskeleton.js 0.6.3
- * (c) 2013 Paul Miller
- * Based on Backbone.js
- * (c) 2010-2013 Jeremy Ashkenas, DocumentCloud
- * Exoskeleton may be freely distributed under the MIT license.
- * For all details and documentation:
- */
-
-(function(root, factory) {
- // Set up Backbone appropriately for the environment.
- if (typeof define === 'function' && define.amd) {
- define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
- root.Backbone = root.Exoskeleton = factory(root, exports, _, $);
- });
- } else if (typeof exports !== 'undefined') {
- var _, $;
- try { _ = require('underscore'); } catch(e) { }
- try { $ = require('jquery'); } catch(e) { }
- factory(root, exports, _, $);
- } else {
- root.Backbone = root.Exoskeleton = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
- }
-
-})(this, function(root, Backbone, _, $) {
- 'use strict';
-
- // Initial Setup
- // -------------
-
- // Save the previous value of the `Backbone` variable, so that it can be
- // restored later on, if `noConflict` is used.
- var previousBackbone = root.Backbone;
- var previousExoskeleton = root.Exoskeleton;
-
- // Underscore replacement.
- var utils = Backbone.utils = _ = (_ || {});
-
- // Hold onto a local reference to `$`. Can be changed at any point.
- Backbone.$ = $;
-
- // Create local references to array methods we'll want to use later.
- var array = [];
- var push = array.push;
- var slice = array.slice;
- var toString = ({}).toString;
-
- // Current version of the library. Keep in sync with `package.json`.
- // Backbone.VERSION = '1.0.0';
-
- // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
- // to its previous owner. Returns a reference to this Backbone object.
- Backbone.noConflict = function() {
- root.Backbone = previousBackbone;
- root.Exoskeleton = previousExoskeleton;
- return this;
- };
-
- // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option
- // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and
- // set a `X-Http-Method-Override` header.
- Backbone.emulateHTTP = false;
-
- // Turn on `emulateJSON` to support legacy servers that can't deal with direct
- // `application/json` requests ... will encode the body as
- // `application/x-www-form-urlencoded` instead and will send the model in a
- // form param named `model`.
- Backbone.emulateJSON = false;
-
- // Helpers
- // -------
-
- // Helper function to correctly set up the prototype chain, for subclasses.
- // Similar to `goog.inherits`, but uses a hash of prototype properties and
- // class properties to be extended.
- Backbone.extend = function(protoProps, staticProps) {
- var parent = this;
- var child;
-
- // The constructor function for the new subclass is either defined by you
- // (the "constructor" property in your `extend` definition), or defaulted
- // by us to simply call the parent's constructor.
- if (protoProps && hasOwnProperty.call(protoProps, 'constructor')) {
- child = protoProps.constructor;
- } else {
- child = function(){ return parent.apply(this, arguments); };
- }
-
- // Add static properties to the constructor function, if supplied.
- _.extend(child, parent, staticProps);
-
- // Set the prototype chain to inherit from `parent`, without calling
- // `parent`'s constructor function.
- var Surrogate = function(){ this.constructor = child; };
- Surrogate.prototype = parent.prototype;
- child.prototype = new Surrogate;
-
- // Add prototype properties (instance properties) to the subclass,
- // if supplied.
- if (protoProps) _.extend(child.prototype, protoProps);
-
- // Set a convenience property in case the parent's prototype is needed
- // later.
- child.__super__ = parent.prototype;
-
- return child;
- };
-
- // Throw an error when a URL is needed, and none is supplied.
- var urlError = function() {
- throw new Error('A "url" property or function must be specified');
- };
-
- // Wrap an optional error callback with a fallback error event.
- var wrapError = function(model, options) {
- var error = options.error;
- options.error = function(resp) {
- if (error) error(model, resp, options);
- model.trigger('error', model, resp, options);
- };
- };
-
- // Checker for utility methods. Useful for custom builds.
- var utilExists = function(method) {
- return typeof _[method] === 'function';
- };
-utils.result = function result(object, property) {
- var value = object ? object[property] : undefined;
- return typeof value === 'function' ? object[property]() : value;
-};
-
-utils.defaults = function defaults(obj) {
- slice.call(arguments, 1).forEach(function(item) {
- for (var key in item) if (obj[key] === undefined)
- obj[key] = item[key];
- });
- return obj;
-};
-
-utils.extend = function extend(obj) {
- slice.call(arguments, 1).forEach(function(item) {
- for (var key in item) obj[key] = item[key];
- });
- return obj;
-};
-
-var htmlEscapes = {
- '&': '&',
- '<': '<',
- '>': '>',
- '"': '"',
- "'": '''
-};
-
-utils.escape = function escape(string) {
- return string == null ? '' : String(string).replace(/[&<>"']/g, function(match) {
- return htmlEscapes[match];
- });
-};
-
-utils.sortBy = function(obj, value, context) {
- var iterator = typeof value === 'function' ? value : function(obj){ return obj[value]; };
- return obj
- .map(function(value, index, list) {
- return {
- value: value,
- index: index,
- criteria: iterator.call(context, value, index, list)
- };
- })
- .sort(function(left, right) {
- var a = left.criteria;
- var b = right.criteria;
- if (a !== b) {
- if (a > b || a === void 0) return 1;
- if (a < b || b === void 0) return -1;
- }
- return left.index - right.index;
- })
- .map(function(item) {
- return item.value;
- });
-};
-
-/** Used to generate unique IDs */
-var idCounter = 0;
-
-utils.uniqueId = function uniqueId(prefix) {
- var id = ++idCounter + '';
- return prefix ? prefix + id : id;
-};
-
-var eq = function(a, b, aStack, bStack) {
- // Identical objects are equal. `0 === -0`, but they aren't identical.
- // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
- if (a === b) return a !== 0 || 1 / a == 1 / b;
- // A strict comparison is necessary because `null == undefined`.
- if (a == null || b == null) return a === b;
- // Unwrap any wrapped objects.
- //if (a instanceof _) a = a._wrapped;
- //if (b instanceof _) b = b._wrapped;
- // Compare `[[Class]]` names.
- var className = toString.call(a);
- if (className != toString.call(b)) return false;
- switch (className) {
- // Strings, numbers, dates, and booleans are compared by value.
- case '[object String]':
- // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
- // equivalent to `new String("5")`.
- return a == String(b);
- case '[object Number]':
- // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
- // other numeric values.
- return a !== +a ? b !== +b : (a === 0 ? 1 / a === 1 / b : a === +b);
- case '[object Date]':
- case '[object Boolean]':
- // Coerce dates and booleans to numeric primitive values. Dates are compared by their
- // millisecond representations. Note that invalid dates with millisecond representations
- // of `NaN` are not equivalent.
- return +a == +b;
- // RegExps are compared by their source patterns and flags.
- case '[object RegExp]':
- return a.source == b.source &&
- a.global == b.global &&
- a.multiline == b.multiline &&
- a.ignoreCase == b.ignoreCase;
- }
- if (typeof a != 'object' || typeof b != 'object') return false;
- // Assume equality for cyclic structures. The algorithm for detecting cyclic
- // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
- var length = aStack.length;
- while (length--) {
- // Linear search. Performance is inversely proportional to the number of
- // unique nested structures.
- if (aStack[length] == a) return bStack[length] == b;
- }
- // Objects with different constructors are not equivalent, but `Object`s
- // from different frames are.
- var aCtor = a.constructor, bCtor = b.constructor;
- if (aCtor !== bCtor && !(typeof aCtor === 'function' && (aCtor instanceof aCtor) &&
- typeof bCtor === 'function' && (bCtor instanceof bCtor))) {
- return false;
- }
- // Add the first object to the stack of traversed objects.
- aStack.push(a);
- bStack.push(b);
- var size = 0, result = true;
- // Recursively compare objects and arrays.
- if (className === '[object Array]') {
- // Compare array lengths to determine if a deep comparison is necessary.
- size = a.length;
- result = size === b.length;
- if (result) {
- // Deep compare the contents, ignoring non-numeric properties.
- while (size--) {
- if (!(result = eq(a[size], b[size], aStack, bStack))) break;
- }
- }
- } else {
- // Deep compare objects.
- for (var key in a) {
- if (hasOwnProperty.call(a, key)) {
- // Count the expected number of properties.
- size++;
- // Deep compare each member.
- if (!(result = hasOwnProperty.call(b, key) && eq(a[key], b[key], aStack, bStack))) break;
- }
- }
- // Ensure that both objects contain the same number of properties.
- if (result) {
- for (key in b) {
- if (hasOwnProperty.call(b, key) && !(size--)) break;
- }
- result = !size;
- }
- }
- // Remove the first object from the stack of traversed objects.
- aStack.pop();
- bStack.pop();
- return result;
-};
-
-// Perform a deep comparison to check if two objects are equal.
-utils.isEqual = function(a, b) {
- return eq(a, b, [], []);
-};
-// Usage:
-// utils.matchesSelector(div, '.something');
-utils.matchesSelector = (function() {
- if (typeof document === 'undefined') return;
- // Suffix.
- var sfx = 'MatchesSelector';
- var tag = document.createElement('div');
- var name;
- // Detect the right suffix.
- ['matches', 'webkit' + sfx, 'moz' + sfx, 'ms' + sfx].some(function(item) {
- var valid = (item in tag);
- name = item;
- return valid;
- });
- if (!name) throw new Error('Element#matches is not supported');
- return function(element, selector) {
- return element[name](selector);
- };
-})();
-
-utils.delegate = function(view, eventName, selector, callback) {
- if (typeof selector === 'function') {
- callback = selector;
- selector = null;
- }
-
- if (typeof callback !== 'function') {
- throw new TypeError('View#delegate expects callback function');
- }
-
- var root = view.el;
- var bound = callback.bind(view);
- var handler = selector ? function(event) {
- for (var el = event.target; el && el !== root; el = el.parentNode) {
- if (utils.matchesSelector(el, selector)) {
- // event.currentTarget or event.target are read-only.
- event.delegateTarget = el;
- return bound(event);
- }
- }
- } : bound;
-
- root.addEventListener(eventName, handler, false);
- view._handlers.push({
- eventName: eventName, selector: selector,
- callback: callback, handler: handler
- });
- return handler;
-};
-
-utils.undelegate = function(view, eventName, selector, callback) {
- if (typeof selector === 'function') {
- callback = selector;
- selector = null;
- }
-
- var handlers = view._handlers;
- var removeListener = function(item) {
- view.el.removeEventListener(item.eventName, item.handler, false);
- };
-
- // Remove all handlers.
- if (!eventName && !selector && !callback) {
- handlers.forEach(removeListener);
- view._handlers = [];
- } else {
- // Remove some handlers.
- handlers
- .filter(function(item) {
- return item.eventName === eventName &&
- (callback ? item.callback === callback : true) &&
- (selector ? item.selector === selector : true);
- })
- .forEach(function(item) {
- removeListener(item);
- handlers.splice(handlers.indexOf(item), 1);
- });
- }
-};
-
-// Make AJAX request to the server.
-// Usage:
-// var callback = function(error, data) {console.log('Done.', error, data);};
-// ajax({url: 'url', type: 'PATCH', data: 'data'}, callback);
-utils.ajax = (function() {
- var xmlRe = /^(?:application|text)\/xml/;
- var jsonRe = /^application\/json/;
-
- var getData = function(accepts, xhr) {
- if (accepts == null) accepts = xhr.getResponseHeader('content-type');
- if (xmlRe.test(accepts)) {
- return xhr.responseXML;
- } else if (jsonRe.test(accepts)) {
- return JSON.parse(xhr.responseText);
- } else {
- return xhr.responseText;
- }
- };
-
- var isValid = function(xhr) {
- return (xhr.status >= 200 && xhr.status < 300) ||
- (xhr.status === 304) ||
- (xhr.status === 0 && window.location.protocol === 'file:')
- };
-
- var end = function(xhr, options, deferred) {
- return function() {
- if (xhr.readyState !== 4) return;
-
- var status = xhr.status;
- var data = getData(options.headers && options.headers.Accept, xhr);
-
- // Check for validity.
- if (isValid(xhr)) {
- if (options.success) options.success(data);
- if (deferred) deferred.resolve(data);
- } else {
- var error = new Error('Server responded with a status of ' + status);
- if (options.error) options.error(xhr, status, error);
- if (deferred) deferred.reject(xhr);
- }
- }
- };
-
- return function(options) {
- if (options == null) throw new Error('You must provide options');
- if (options.type == null) options.type = 'GET';
-
- var xhr = new XMLHttpRequest();
- var deferred = Backbone.Deferred && Backbone.Deferred();
-
- if (options.contentType) {
- if (options.headers == null) options.headers = {};
- options.headers['Content-Type'] = options.contentType;
- }
-
- // Stringify GET query params.
- if (options.type === 'GET' && typeof options.data === 'object') {
- var query = '';
- var stringifyKeyValuePair = function(key, value) {
- return value == null ? '' :
- '&' + encodeURIComponent(key) +
- '=' + encodeURIComponent(value);
- };
- for (var key in options.data) {
- query += stringifyKeyValuePair(key, options.data[key]);
- }
-
- if (query) {
- var sep = (options.url.indexOf('?') === -1) ? '?' : '&';
- options.url += sep + query.substring(1);
- }
- }
-
- if (options.credentials) options.withCredentials = true;
- xhr.addEventListener('readystatechange', end(xhr, options, deferred));
- xhr.open(options.type, options.url, true);
- if (options.headers) for (var key in options.headers) {
- xhr.setRequestHeader(key, options.headers[key]);
- }
- if (options.beforeSend) options.beforeSend(xhr);
- xhr.send(options.data);
-
- return deferred ? deferred.promise : undefined;
- };
-})();
-// Backbone.Events
-// ---------------
-
-// A module that can be mixed in to *any object* in order to provide it with
-// custom events. You may bind with `on` or remove with `off` callback
-// functions to an event; `trigger`-ing an event fires all callbacks in
-// succession.
-//
-// var object = {};
-// _.extend(object, Backbone.Events);
-// object.on('expand', function(){ alert('expanded'); });
-// object.trigger('expand');
-//
-var Events = Backbone.Events = {
-
- // Bind an event to a `callback` function. Passing `"all"` will bind
- // the callback to all events fired.
- on: function(name, callback, context) {
- if (!eventsApi(this, 'on', name, [callback, context]) || !callback)
- return this;
- this._events || (this._events = {});
- var events = this._events[name] || (this._events[name] = []);
- events.push({callback: callback, context: context, ctx: context || this});
- return this;
- },
-
- // Bind an event to only be triggered a single time. After the first time
- // the callback is invoked, it will be removed.
- once: function(name, callback, context) {
- if (!eventsApi(this, 'once', name, [callback, context]) || !callback)
- return this;
- var self = this;
- var ran;
-
- var once = function() {
- if (ran) return;
- ran = true;
- self.off(name, once);
- callback.apply(this, arguments);
- };
- once._callback = callback;
- return this.on(name, once, context);
- },
-
- // Remove one or many callbacks. If `context` is null, removes all
- // callbacks with that function. If `callback` is null, removes all
- // callbacks for the event. If `name` is null, removes all bound
- // callbacks for all events.
- off: function(name, callback, context) {
- var retain, ev, events, names, i, l, j, k;
- if (!this._events || !eventsApi(this, 'off', name, [callback, context]))
- return this;
- if (!name && !callback && !context) {
- this._events = undefined;
- return this;
- }
-
- names = name ? [name] : Object.keys(this._events);
- for (i = 0, l = names.length; i < l; i++) {
- name = names[i];
- if (events = this._events[name]) {
- this._events[name] = retain = [];
- if (callback || context) {
- for (j = 0, k = events.length; j < k; j++) {
- ev = events[j];
- if ((callback && callback !== ev.callback &&
- callback !== ev.callback._callback) ||
- (context && context !== ev.context)) {
- retain.push(ev);
- }
- }
- }
- if (!retain.length) delete this._events[name];
- }
- }
-
- return this;
- },
-
- // Trigger one or many events, firing all bound callbacks. Callbacks are
- // passed the same arguments as `trigger` is, apart from the event name
- // (unless you're listening on `"all"`, which will cause your callback to
- // receive the true name of the event as the first argument).
- trigger: function(name) {
- if (!this._events) return this;
- var args = slice.call(arguments, 1);
- if (!eventsApi(this, 'trigger', name, args)) return this;
- var events = this._events[name];
- var allEvents = this._events.all;
- if (events) triggerEvents(events, args);
- if (allEvents) triggerEvents(allEvents, arguments);
- return this;
- },
-
- // Tell this object to stop listening to either specific events ... or
- // to every object it's currently listening to.
- stopListening: function(obj, name, callback) {
- var listeningTo = this._listeningTo;
- if (!listeningTo) return this;
- var remove = !name && !callback;
- if (!callback && typeof name === 'object') callback = this;
- if (obj) (listeningTo = {})[obj._listenId] = obj;
- for (var id in listeningTo) {
- obj = listeningTo[id];
- obj.off(name, callback, this);
- if (remove || !Object.keys(obj._events).length) {
- delete this._listeningTo[id];
- }
- }
- return this;
- }
-
-};
-
-// Regular expression used to split event strings.
-var eventSplitter = /\s+/;
-
-// Implement fancy features of the Events API such as multiple event
-// names `"change blur"` and jQuery-style event maps `{change: action}`
-// in terms of the existing API.
-var eventsApi = function(obj, action, name, rest) {
- if (!name) return true;
- var arr;
-
- // Handle event maps.
- if (typeof name === 'object') {
- for (var key in name) {
- arr = [key, name[key]];
- push.apply(arr, rest);
- obj[action].apply(obj, arr);
- }
- return false;
- }
-
- // Handle space separated event names.
- if (eventSplitter.test(name)) {
- var names = name.split(eventSplitter);
- for (var i = 0, l = names.length; i < l; i++) {
- arr = [names[i]];
- push.apply(arr, rest);
- obj[action].apply(obj, arr);
- }
- return false;
- }
-
- return true;
-};
-
-// A difficult-to-believe, but optimized internal dispatch function for
-// triggering events. Tries to keep the usual cases speedy (most internal
-// Backbone events have 3 arguments).
-var triggerEvents = function(events, args) {
- var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
- switch (args.length) {
- case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
- case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
- case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
- case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
- default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
- }
-};
-
-var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
-
-// Inversion-of-control versions of `on` and `once`. Tell *this* object to
-// listen to an event in another object ... keeping track of what it's
-// listening to.
-Object.keys(listenMethods).forEach(function(method) {
- var implementation = listenMethods[method];
- Events[method] = function(obj, name, callback) {
- var listeningTo = this._listeningTo || (this._listeningTo = {});
- var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
- listeningTo[id] = obj;
- if (!callback && typeof name === 'object') callback = this;
- obj[implementation](name, callback, this);
- return this;
- };
-});
-
-// Aliases for backwards compatibility.
-Events.bind = Events.on;
-Events.unbind = Events.off;
-// Backbone.Model
-// --------------
-
-// Backbone **Models** are the basic data object in the framework --
-// frequently representing a row in a table in a database on your server.
-// A discrete chunk of data and a bunch of useful, related methods for
-// performing computations and transformations on that data.
-
-// Create a new model with the specified attributes. A client id (`cid`)
-// is automatically generated and assigned for you.
-var Model = Backbone.Model = function(attributes, options) {
- var attrs = attributes || {};
- options || (options = {});
- this.cid = _.uniqueId('c');
- this.attributes = Object.create(null);
- if (options.collection) this.collection = options.collection;
- if (options.parse) attrs = this.parse(attrs, options) || {};
- attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
- this.set(attrs, options);
- this.changed = Object.create(null);
- this.initialize.apply(this, arguments);
-};
-
-// Attach all inheritable methods to the Model prototype.
-_.extend(Model.prototype, Events, {
-
- // A hash of attributes whose current and previous value differ.
- changed: null,
-
- // The value returned during the last failed validation.
- validationError: null,
-
- // The default name for the JSON `id` attribute is `"id"`. MongoDB and
- // CouchDB users may want to set this to `"_id"`.
- idAttribute: 'id',
-
- // Initialize is an empty function by default. Override it with your own
- // initialization logic.
- initialize: function(){},
-
- // Return a copy of the model's `attributes` object.
- toJSON: function(options) {
- return _.extend(Object.create(null), this.attributes);
- },
-
- // Proxy `Backbone.sync` by default -- but override this if you need
- // custom syncing semantics for *this* particular model.
- sync: function() {
- return Backbone.sync.apply(this, arguments);
- },
-
- // Get the value of an attribute.
- get: function(attr) {
- return this.attributes[attr];
- },
-
- // Get the HTML-escaped value of an attribute.
- escape: function(attr) {
- return _.escape(this.get(attr));
- },
-
- // Returns `true` if the attribute contains a value that is not null
- // or undefined.
- has: function(attr) {
- return this.get(attr) != null;
- },
-
- // Set a hash of model attributes on the object, firing `"change"`. This is
- // the core primitive operation of a model, updating the data and notifying
- // anyone who needs to know about the change in state. The heart of the beast.
- set: function(key, val, options) {
- var attr, attrs, unset, changes, silent, changing, prev, current;
- if (key == null) return this;
-
- // Handle both `"key", value` and `{key: value}` -style arguments.
- if (typeof key === 'object') {
- attrs = key;
- options = val;
- } else {
- (attrs = {})[key] = val;
- }
-
- options || (options = {});
-
- // Run validation.
- if (!this._validate(attrs, options)) return false;
-
- // Extract attributes and options.
- unset = options.unset;
- silent = options.silent;
- changes = [];
- changing = this._changing;
- this._changing = true;
-
- if (!changing) {
- this._previousAttributes = _.extend(Object.create(null), this.attributes);
- this.changed = {};
- }
- current = this.attributes, prev = this._previousAttributes;
-
- // Check for changes of `id`.
- if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
-
- // For each `set` attribute, update or delete the current value.
- for (attr in attrs) {
- val = attrs[attr];
- if (!_.isEqual(current[attr], val)) changes.push(attr);
- if (!_.isEqual(prev[attr], val)) {
- this.changed[attr] = val;
- } else {
- delete this.changed[attr];
- }
- unset ? delete current[attr] : current[attr] = val;
- }
-
- // Trigger all relevant attribute changes.
- if (!silent) {
- if (changes.length) this._pending = true;
- for (var i = 0, l = changes.length; i < l; i++) {
- this.trigger('change:' + changes[i], this, current[changes[i]], options);
- }
- }
-
- // You might be wondering why there's a `while` loop here. Changes can
- // be recursively nested within `"change"` events.
- if (changing) return this;
- if (!silent) {
- while (this._pending) {
- this._pending = false;
- this.trigger('change', this, options);
- }
- }
- this._pending = false;
- this._changing = false;
- return this;
- },
-
- // Remove an attribute from the model, firing `"change"`. `unset` is a noop
- // if the attribute doesn't exist.
- unset: function(attr, options) {
- return this.set(attr, void 0, _.extend({}, options, {unset: true}));
- },
-
- // Clear all attributes on the model, firing `"change"`.
- clear: function(options) {
- var attrs = {};
- for (var key in this.attributes) attrs[key] = void 0;
- return this.set(attrs, _.extend({}, options, {unset: true}));
- },
-
- // Determine if the model has changed since the last `"change"` event.
- // If you specify an attribute name, determine if that attribute has changed.
- hasChanged: function(attr) {
- if (attr == null) return !!Object.keys(this.changed).length;
- return hasOwnProperty.call(this.changed, attr);
- },
-
- // Return an object containing all the attributes that have changed, or
- // false if there are no changed attributes. Useful for determining what
- // parts of a view need to be updated and/or what attributes need to be
- // persisted to the server. Unset attributes will be set to undefined.
- // You can also pass an attributes object to diff against the model,
- // determining if there *would be* a change.
- changedAttributes: function(diff) {
- if (!diff) return this.hasChanged() ? _.extend(Object.create(null), this.changed) : false;
- var val, changed = false;
- var old = this._changing ? this._previousAttributes : this.attributes;
- for (var attr in diff) {
- if (_.isEqual(old[attr], (val = diff[attr]))) continue;
- (changed || (changed = {}))[attr] = val;
- }
- return changed;
- },
-
- // Get the previous value of an attribute, recorded at the time the last
- // `"change"` event was fired.
- previous: function(attr) {
- if (attr == null || !this._previousAttributes) return null;
- return this._previousAttributes[attr];
- },
-
- // Get all of the attributes of the model at the time of the previous
- // `"change"` event.
- previousAttributes: function() {
- return _.extend(Object.create(null), this._previousAttributes);
- },
-
- // Fetch the model from the server. If the server's representation of the
- // model differs from its current attributes, they will be overridden,
- // triggering a `"change"` event.
- fetch: function(options) {
- options = options ? _.extend({}, options) : {};
- if (options.parse === void 0) options.parse = true;
- var model = this;
- var success = options.success;
- options.success = function(resp) {
- if (!model.set(model.parse(resp, options), options)) return false;
- if (success) success(model, resp, options);
- model.trigger('sync', model, resp, options);
- };
- wrapError(this, options);
- return this.sync('read', this, options);
- },
-
- // Set a hash of model attributes, and sync the model to the server.
- // If the server returns an attributes hash that differs, the model's
- // state will be `set` again.
- save: function(key, val, options) {
- var attrs, method, xhr, attributes = this.attributes;
-
- // Handle both `"key", value` and `{key: value}` -style arguments.
- if (key == null || typeof key === 'object') {
- attrs = key;
- options = val;
- } else {
- (attrs = {})[key] = val;
- }
-
- options = _.extend({validate: true}, options);
-
- // If we're not waiting and attributes exist, save acts as
- // `set(attr).save(null, opts)` with validation. Otherwise, check if
- // the model will be valid when the attributes, if any, are set.
- if (attrs && !options.wait) {
- if (!this.set(attrs, options)) return false;
- } else {
- if (!this._validate(attrs, options)) return false;
- }
-
- // Set temporary attributes if `{wait: true}`.
- if (attrs && options.wait) {
- this.attributes = _.extend(Object.create(null), attributes, attrs);
- }
-
- // After a successful server-side save, the client is (optionally)
- // updated with the server-side state.
- if (options.parse === void 0) options.parse = true;
- var model = this;
- var success = options.success;
- options.success = function(resp) {
- // Ensure attributes are restored during synchronous saves.
- model.attributes = attributes;
- var serverAttrs = model.parse(resp, options);
- if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
- if (serverAttrs && typeof serverAttrs === 'object' && !model.set(serverAttrs, options)) {
- return false;
- }
- if (success) success(model, resp, options);
- model.trigger('sync', model, resp, options);
- };
- wrapError(this, options);
-
- method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
- if (method === 'patch') options.attrs = attrs;
- xhr = this.sync(method, this, options);
-
- // Restore attributes.
- if (attrs && options.wait) this.attributes = attributes;
-
- return xhr;
- },
-
- // Destroy this model on the server if it was already persisted.
- // Optimistically removes the model from its collection, if it has one.
- // If `wait: true` is passed, waits for the server to respond before removal.
- destroy: function(options) {
- options = options ? _.extend({}, options) : {};
- var model = this;
- var success = options.success;
-
- var destroy = function() {
- model.trigger('destroy', model, model.collection, options);
- };
-
- options.success = function(resp) {
- if (options.wait || model.isNew()) destroy();
- if (success) success(model, resp, options);
- if (!model.isNew()) model.trigger('sync', model, resp, options);
- };
-
- if (this.isNew()) {
- options.success();
- return false;
- }
- wrapError(this, options);
-
- var xhr = this.sync('delete', this, options);
- if (!options.wait) destroy();
- return xhr;
- },
-
- // Default URL for the model's representation on the server -- if you're
- // using Backbone's restful methods, override this to change the endpoint
- // that will be called.
- url: function() {
- var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError();
- if (this.isNew()) return base;
- return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id);
- },
-
- // **parse** converts a response into the hash of attributes to be `set` on
- // the model. The default implementation is just to pass the response along.
- parse: function(resp, options) {
- return resp;
- },
-
- // Create a new model with identical attributes to this one.
- clone: function() {
- return new this.constructor(this.attributes);
- },
-
- // A model is new if it has never been saved to the server, and lacks an id.
- isNew: function() {
- return this.id == null;
- },
-
- // Check if the model is currently in a valid state.
- isValid: function(options) {
- return this._validate({}, _.extend(options || {}, { validate: true }));
- },
-
- // Run validation against the next complete set of model attributes,
- // returning `true` if all is well. Otherwise, fire an `"invalid"` event.
- _validate: function(attrs, options) {
- if (!options.validate || !this.validate) return true;
- attrs = _.extend(Object.create(null), this.attributes, attrs);
- var error = this.validationError = this.validate(attrs, options) || null;
- if (!error) return true;
- this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
- return false;
- }
-
-});
-
-if (_.keys) {
- // Underscore methods that we want to implement on the Model.
- var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
-
- // Mix in each Underscore method as a proxy to `Model#attributes`.
- modelMethods.filter(utilExists).forEach(function(method) {
- Model.prototype[method] = function() {
- var args = slice.call(arguments);
- args.unshift(this.attributes);
- return _[method].apply(_, args);
- };
- });
-}
-// Backbone.Collection
-// -------------------
-
-// If models tend to represent a single row of data, a Backbone Collection is
-// more analagous to a table full of data ... or a small slice or page of that
-// table, or a collection of rows that belong together for a particular reason
-// -- all of the messages in this particular folder, all of the documents
-// belonging to this particular author, and so on. Collections maintain
-// indexes of their models, both in order, and for lookup by `id`.
-
-// Create a new **Collection**, perhaps to contain a specific type of `model`.
-// If a `comparator` is specified, the Collection will maintain
-// its models in sort order, as they're added and removed.
-var Collection = Backbone.Collection = function(models, options) {
- options || (options = {});
- if (options.model) this.model = options.model;
- if (options.comparator !== void 0) this.comparator = options.comparator;
- this._reset();
- this.initialize.apply(this, arguments);
- if (models) this.reset(models, _.extend({silent: true}, options));
-};
-
-// Default options for `Collection#set`.
-var setOptions = {add: true, remove: true, merge: true};
-var addOptions = {add: true, remove: false};
-
-// Define the Collection's inheritable methods.
-_.extend(Collection.prototype, Events, {
-
- // The default model for a collection is just a **Backbone.Model**.
- // This should be overridden in most cases.
- model: typeof Model === 'undefined' ? null : Model,
-
- // Initialize is an empty function by default. Override it with your own
- // initialization logic.
- initialize: function(){},
-
- // The JSON representation of a Collection is an array of the
- // models' attributes.
- toJSON: function(options) {
- return this.map(function(model){ return model.toJSON(options); });
- },
-
- // Proxy `Backbone.sync` by default.
- sync: function() {
- return Backbone.sync.apply(this, arguments);
- },
-
- // Add a model, or list of models to the set.
- add: function(models, options) {
- return this.set(models, _.extend({merge: false}, options, addOptions));
- },
-
- // Remove a model, or a list of models from the set.
- remove: function(models, options) {
- var singular = !Array.isArray(models);
- models = singular ? [models] : models.slice();
- options || (options = {});
- var i, l, index, model;
- for (i = 0, l = models.length; i < l; i++) {
- model = models[i] = this.get(models[i]);
- if (!model) continue;
- delete this._byId[model.id];
- delete this._byId[model.cid];
- index = this.indexOf(model);
- this.models.splice(index, 1);
- this.length--;
- if (!options.silent) {
- options.index = index;
- model.trigger('remove', model, this, options);
- }
- this._removeReference(model);
- }
- return singular ? models[0] : models;
- },
-
- // Update a collection by `set`-ing a new list of models, adding new ones,
- // removing models that are no longer present, and merging models that
- // already exist in the collection, as necessary. Similar to **Model#set**,
- // the core operation for updating the data contained by the collection.
- set: function(models, options) {
- options = _.defaults({}, options, setOptions);
- if (options.parse) models = this.parse(models, options);
- var singular = !Array.isArray(models);
- models = singular ? (models ? [models] : []) : models.slice();
- var i, l, id, model, attrs, existing, sort;
- var at = options.at;
- var targetModel = this.model;
- var sortable = this.comparator && (at == null) && options.sort !== false;
- var sortAttr = typeof this.comparator === 'string' ? this.comparator : null;
- var toAdd = [], toRemove = [], modelMap = {};
- var add = options.add, merge = options.merge, remove = options.remove;
- var order = !sortable && add && remove ? [] : false;
-
- // Turn bare objects into model references, and prevent invalid models
- // from being added.
- for (i = 0, l = models.length; i < l; i++) {
- attrs = models[i];
- if (attrs instanceof Model) {
- id = model = attrs;
- } else {
- id = attrs[targetModel.prototype.idAttribute];
- }
-
- // If a duplicate is found, prevent it from being added and
- // optionally merge it into the existing model.
- if (existing = this.get(id)) {
- if (remove) modelMap[existing.cid] = true;
- if (merge) {
- attrs = attrs === model ? model.attributes : attrs;
- if (options.parse) attrs = existing.parse(attrs, options);
- existing.set(attrs, options);
- if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
- }
- models[i] = existing;
-
- // If this is a new, valid model, push it to the `toAdd` list.
- } else if (add) {
- model = models[i] = this._prepareModel(attrs, options);
- if (!model) continue;
- toAdd.push(model);
-
- // Listen to added models' events, and index models for lookup by
- // `id` and by `cid`.
- model.on('all', this._onModelEvent, this);
- this._byId[model.cid] = model;
- if (model.id != null) this._byId[model.id] = model;
- }
- if (order) order.push(existing || model);
- }
-
- // Remove nonexistent models if appropriate.
- if (remove) {
- for (i = 0, l = this.length; i < l; ++i) {
- if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
- }
- if (toRemove.length) this.remove(toRemove, options);
- }
-
- // See if sorting is needed, update `length` and splice in new models.
- if (toAdd.length || (order && order.length)) {
- if (sortable) sort = true;
- this.length += toAdd.length;
- if (at != null) {
- for (i = 0, l = toAdd.length; i < l; i++) {
- this.models.splice(at + i, 0, toAdd[i]);
- }
- } else {
- if (order) this.models.length = 0;
- var orderedModels = order || toAdd;
- for (i = 0, l = orderedModels.length; i < l; i++) {
- this.models.push(orderedModels[i]);
- }
- }
- }
-
- // Silently sort the collection if appropriate.
- if (sort) this.sort({silent: true});
-
- // Unless silenced, it's time to fire all appropriate add/sort events.
- if (!options.silent) {
- for (i = 0, l = toAdd.length; i < l; i++) {
- (model = toAdd[i]).trigger('add', model, this, options);
- }
- if (sort || (order && order.length)) this.trigger('sort', this, options);
- }
-
- // Return the added (or merged) model (or models).
- return singular ? models[0] : models;
- },
-
- // When you have more items than you want to add or remove individually,
- // you can reset the entire set with a new list of models, without firing
- // any granular `add` or `remove` events. Fires `reset` when finished.
- // Useful for bulk operations and optimizations.
- reset: function(models, options) {
- options || (options = {});
- for (var i = 0, l = this.models.length; i < l; i++) {
- this._removeReference(this.models[i]);
- }
- options.previousModels = this.models;
- this._reset();
- models = this.add(models, _.extend({silent: true}, options));
- if (!options.silent) this.trigger('reset', this, options);
- return models;
- },
-
- // Add a model to the end of the collection.
- push: function(model, options) {
- return this.add(model, _.extend({at: this.length}, options));
- },
-
- // Remove a model from the end of the collection.
- pop: function(options) {
- var model = this.at(this.length - 1);
- this.remove(model, options);
- return model;
- },
-
- // Add a model to the beginning of the collection.
- unshift: function(model, options) {
- return this.add(model, _.extend({at: 0}, options));
- },
-
- // Remove a model from the beginning of the collection.
- shift: function(options) {
- var model = this.at(0);
- this.remove(model, options);
- return model;
- },
-
- // Slice out a sub-array of models from the collection.
- slice: function() {
- return slice.apply(this.models, arguments);
- },
-
- // Get a model from the set by id.
- get: function(obj) {
- if (obj == null) return void 0;
- return this._byId[obj.id] || this._byId[obj.cid] || this._byId[obj];
- },
-
- // Get the model at the given index.
- at: function(index) {
- return this.models[index];
- },
-
- // Return models with matching attributes. Useful for simple cases of
- // `filter`.
- where: function(attrs, first) {
- if (!attrs || !Object.keys(attrs).length) return first ? void 0 : [];
- return this[first ? 'find' : 'filter'](function(model) {
- for (var key in attrs) {
- if (attrs[key] !== model.get(key)) return false;
- }
- return true;
- });
- },
-
- // Return the first model with matching attributes. Useful for simple cases
- // of `find`.
- findWhere: function(attrs) {
- return this.where(attrs, true);
- },
-
- // Force the collection to re-sort itself. You don't need to call this under
- // normal circumstances, as the set will maintain sort order as each item
- // is added.
- sort: function(options) {
- if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
- options || (options = {});
-
- // Run sort based on type of `comparator`.
- if (typeof this.comparator === 'string' || this.comparator.length === 1) {
- this.models = this.sortBy(this.comparator, this);
- } else {
- this.models.sort(this.comparator.bind(this));
- }
-
- if (!options.silent) this.trigger('sort', this, options);
- return this;
- },
-
- // Pluck an attribute from each model in the collection.
- pluck: function(attr) {
- return this.models.map(function(model) {
- return model.get(attr);
- });
- },
-
- // Fetch the default set of models for this collection, resetting the
- // collection when they arrive. If `reset: true` is passed, the response
- // data will be passed through the `reset` method instead of `set`.
- fetch: function(options) {
- options = options ? _.extend({}, options) : {};
- if (options.parse === void 0) options.parse = true;
- var success = options.success;
- var collection = this;
- options.success = function(resp) {
- var method = options.reset ? 'reset' : 'set';
- collection[method](resp, options);
- if (success) success(collection, resp, options);
- collection.trigger('sync', collection, resp, options);
- };
- wrapError(this, options);
- return this.sync('read', this, options);
- },
-
- // Create a new instance of a model in this collection. Add the model to the
- // collection immediately, unless `wait: true` is passed, in which case we
- // wait for the server to agree.
- create: function(model, options) {
- options = options ? _.extend({}, options) : {};
- if (!(model = this._prepareModel(model, options))) return false;
- if (!options.wait) this.add(model, options);
- var collection = this;
- var success = options.success;
- options.success = function(model, resp, options) {
- if (options.wait) collection.add(model, options);
- if (success) success(model, resp, options);
- };
- model.save(null, options);
- return model;
- },
-
- // **parse** converts a response into a list of models to be added to the
- // collection. The default implementation is just to pass it through.
- parse: function(resp, options) {
- return resp;
- },
-
- // Create a new collection with an identical list of models as this one.
- clone: function() {
- return new this.constructor(this.models);
- },
-
- // Private method to reset all internal state. Called when the collection
- // is first initialized or reset.
- _reset: function() {
- this.length = 0;
- this.models = [];
- this._byId = Object.create(null);
- },
-
- // Prepare a hash of attributes (or other model) to be added to this
- // collection.
- _prepareModel: function(attrs, options) {
- if (attrs instanceof Collection.prototype.model) {
- if (!attrs.collection) attrs.collection = this;
- return attrs;
- }
- options = options ? _.extend({}, options) : {};
- options.collection = this;
- var model = new this.model(attrs, options);
- if (!model.validationError) return model;
- this.trigger('invalid', this, model.validationError, options);
- return false;
- },
-
- // Internal method to sever a model's ties to a collection.
- _removeReference: function(model) {
- if (this === model.collection) delete model.collection;
- model.off('all', this._onModelEvent, this);
- },
-
- // Internal method called every time a model in the set fires an event.
- // Sets need to update their indexes when models change ids. All other
- // events simply proxy through. "add" and "remove" events that originate
- // in other collections are ignored.
- _onModelEvent: function(event, model, collection, options) {
- if ((event === 'add' || event === 'remove') && collection !== this) return;
- if (event === 'destroy') this.remove(model, options);
- if (model && event === 'change:' + model.idAttribute) {
- delete this._byId[model.previous(model.idAttribute)];
- if (model.id != null) this._byId[model.id] = model;
- }
- this.trigger.apply(this, arguments);
- }
-
-});
-
-if (utilExists('each')) {
- // Underscore methods that we want to implement on the Collection.
- // 90% of the core usefulness of Backbone Collections is actually implemented
- // right here:
- var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
- 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
- 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
- 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
- 'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle',
- 'lastIndexOf', 'isEmpty', 'chain'];
-
- // Mix in each Underscore method as a proxy to `Collection#models`.
- methods.filter(utilExists).forEach(function(method) {
- Collection.prototype[method] = function() {
- var args = slice.call(arguments);
- args.unshift(this.models);
- return _[method].apply(_, args);
- };
- });
-
- // Underscore methods that take a property name as an argument.
- var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
-
- // Use attributes instead of properties.
- attributeMethods.filter(utilExists).forEach(function(method) {
- Collection.prototype[method] = function(value, context) {
- var iterator = typeof value === 'function' ? value : function(model) {
- return model.get(value);
- };
- return _[method](this.models, iterator, context);
- };
- });
-} else {
- ['forEach', 'map', 'filter', 'some', 'every', 'reduce', 'reduceRight',
- 'indexOf', 'lastIndexOf'].forEach(function(method) {
- Collection.prototype[method] = function(arg, context) {
- return this.models[method](arg, context);
- };
- });
-
- // Exoskeleton-specific:
- Collection.prototype.find = function(iterator, context) {
- var result;
- this.some(function(value, index, list) {
- if (iterator.call(context, value, index, list)) {
- result = value;
- return true;
- }
- });
- return result;
- };
-
- // Underscore methods that take a property name as an argument.
- ['sortBy'].forEach(function(method) {
- Collection.prototype[method] = function(value, context) {
- var iterator = typeof value === 'function' ? value : function(model) {
- return model.get(value);
- };
- return _[method](this.models, iterator, context);
- };
- });
-}
-// Backbone.View
-// -------------
-
-// Backbone Views are almost more convention than they are actual code. A View
-// is simply a JavaScript object that represents a logical chunk of UI in the
-// DOM. This might be a single item, an entire list, a sidebar or panel, or
-// even the surrounding frame which wraps your whole app. Defining a chunk of
-// UI as a **View** allows you to define your DOM events declaratively, without
-// having to worry about render order ... and makes it easy for the view to
-// react to specific changes in the state of your models.
-
-// Options with special meaning *(e.g. model, collection, id, className)* are
-// attached directly to the view. See `viewOptions` for an exhaustive
-// list.
-
-// Cached regex to split keys for `delegate`.
-var delegateEventSplitter = /^(\S+)\s*(.*)$/;
-
-// List of view options to be merged as properties.
-var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
-
-// Creating a Backbone.View creates its initial element outside of the DOM,
-// if an existing element is not provided...
-var View = Backbone.View = function(options) {
- this.cid = _.uniqueId('view');
- if (options) Object.keys(options).forEach(function(key) {
- if (viewOptions.indexOf(key) !== -1) this[key] = options[key];
- }, this);
- this._handlers = [];
- this._ensureElement();
- this.initialize.apply(this, arguments);
- this.delegateEvents();
-};
-
-// Set up all inheritable **Backbone.View** properties and methods.
-_.extend(View.prototype, Events, {
- // In case you want to include jQuery with your app
- // for *some* views and use native methods for other views.
- useNative: false,
-
- // The default `tagName` of a View's element is `"div"`.
- tagName: 'div',
-
- // jQuery delegate for element lookup, scoped to DOM elements within the
- // current view. This should be preferred to global lookups where possible.
- $: function(selector) {
- return Backbone.$ && !this.useNative ? this.$el.find(selector) : this.findAll(selector);
- },
-
- // Exoskeleton-related DOM methods.
- find: function(selector) {
- return this.el.querySelector(selector);
- },
-
- findAll: function(selector) {
- return slice.call(this.el.querySelectorAll(selector));
- },
-
- // Initialize is an empty function by default. Override it with your own
- // initialization logic.
- initialize: function(){},
-
- // **render** is the core function that your view should override, in order
- // to populate its element (`this.el`), with the appropriate HTML. The
- // convention is for **render** to always return `this`.
- render: function() {
- return this;
- },
-
- // Remove this view by taking the element out of the DOM, and removing any
- // applicable Backbone.Events listeners.
- remove: function() {
- var parent;
- if (Backbone.$ && !this.useNative) {
- this.$el.remove();
- } else if (parent = this.el.parentNode) {
- parent.removeChild(this.el);
- }
- this.stopListening();
- return this;
- },
-
- // Change the view's element (`this.el` property), including event
- // re-delegation.
- setElement: function(element, delegate) {
- if (Backbone.$ && !this.useNative) {
- if (this.$el) this.undelegateEvents();
- this.$el = element instanceof Backbone.$ ? element : Backbone.$(element);
- this.el = this.$el[0];
- } else {
- if (this.el) this.undelegateEvents();
- this.el = (typeof element === 'string') ?
- document.querySelector(element) : element;
- }
- if (delegate !== false) this.delegateEvents();
- return this;
- },
-
- // Set callbacks, where `this.events` is a hash of
- //
- // *{"event selector": "callback"}*
- //
- // {
- // 'mousedown .title': 'edit',
- // 'click .button': 'save',
- // 'click .open': function(e) { ... }
- // }
- //
- // pairs. Callbacks will be bound to the view, with `this` set properly.
- // Uses event delegation for efficiency.
- // Omitting the selector binds the event to `this.el`.
- // This only works for delegate-able events: not `focus`, `blur`, and
- // not `change`, `submit`, and `reset` in Internet Explorer.
- delegateEvents: function(events, keepOld) {
- if (!(events || (events = _.result(this, 'events')))) return this;
- if (!keepOld) this.undelegateEvents();
- for (var key in events) {
- var method = events[key];
- if (typeof method !== 'function') method = this[events[key]];
- // if (!method) continue;
-
- var match = key.match(delegateEventSplitter);
- var eventName = match[1], selector = match[2];
-
- if (Backbone.$ && !this.useNative) {
- eventName += '.delegateEvents' + this.cid;
- method = method.bind(this);
- this.$el.on(eventName, (selector ? selector : null), method);
- } else {
- utils.delegate(this, eventName, selector, method);
- }
- }
- return this;
- },
-
- // Clears all callbacks previously bound to the view with `delegateEvents`.
- // You usually don't need to use this, but may wish to if you have multiple
- // Backbone views attached to the same DOM element.
- undelegateEvents: function() {
- if (Backbone.$ && !this.useNative) {
- this.$el.off('.delegateEvents' + this.cid);
- } else {
- utils.undelegate(this);
- }
- return this;
- },
-
- // Ensure that the View has a DOM element to render into.
- // If `this.el` is a string, pass it through `$()`, take the first
- // matching element, and re-assign it to `el`. Otherwise, create
- // an element from the `id`, `className` and `tagName` properties.
- _ensureElement: function() {
- if (!this.el) {
- var attrs = _.extend({}, _.result(this, 'attributes'));
- if (this.id) attrs.id = _.result(this, 'id');
- if (this.className) attrs.className = _.result(this, 'className');
- if (attrs['class']) attrs.className = attrs['class'];
- var el = _.extend(document.createElement(_.result(this, 'tagName')), attrs);
- this.setElement(el, false);
- } else {
- this.setElement(_.result(this, 'el'), false);
- }
- }
-
-});
-// Backbone.sync
-// -------------
-
-// Override this function to change the manner in which Backbone persists
-// models to the server. You will be passed the type of request, and the
-// model in question. By default, makes a RESTful Ajax request
-// to the model's `url()`. Some possible customizations could be:
-//
-// * Use `setTimeout` to batch rapid-fire updates into a single request.
-// * Send up the models as XML instead of JSON.
-// * Persist models via WebSockets instead of Ajax.
-//
-// Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests
-// as `POST`, with a `_method` parameter containing the true HTTP method,
-// as well as all requests with the body as `application/x-www-form-urlencoded`
-// instead of `application/json` with the model in a param named `model`.
-// Useful when interfacing with server-side languages like **PHP** that make
-// it difficult to read the body of `PUT` requests.
-Backbone.sync = function(method, model, options) {
- var type = methodMap[method];
-
- // Default options, unless specified.
- _.defaults(options || (options = {}), {
- emulateHTTP: Backbone.emulateHTTP,
- emulateJSON: Backbone.emulateJSON
- });
-
- // Default JSON-request options.
- var params = {type: type, dataType: 'json'};
-
- // Ensure that we have a URL.
- if (!options.url) {
- params.url = _.result(model, 'url') || urlError();
- }
-
- // Ensure that we have the appropriate request data.
- if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
- params.contentType = 'application/json';
- params.data = JSON.stringify(options.attrs || model.toJSON(options));
- }
-
- // For older servers, emulate JSON by encoding the request into an HTML-form.
- if (options.emulateJSON) {
- params.contentType = 'application/x-www-form-urlencoded';
- params.data = params.data ? {model: params.data} : {};
- }
-
- // For older servers, emulate HTTP by mimicking the HTTP method with `_method`
- // And an `X-HTTP-Method-Override` header.
- if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) {
- params.type = 'POST';
- if (options.emulateJSON) params.data._method = type;
- var beforeSend = options.beforeSend;
- options.beforeSend = function(xhr) {
- xhr.setRequestHeader('X-HTTP-Method-Override', type);
- if (beforeSend) return beforeSend.apply(this, arguments);
- };
- }
-
- // Don't process data on a non-GET request.
- if (params.type !== 'GET' && !options.emulateJSON) {
- params.processData = false;
- }
-
- // Make the request, allowing the user to override any Ajax options.
- var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
- model.trigger('request', model, xhr, options);
- return xhr;
-};
-
-// Map from CRUD to HTTP for our default `Backbone.sync` implementation.
-var methodMap = {
- 'create': 'POST',
- 'update': 'PUT',
- 'patch': 'PATCH',
- 'delete': 'DELETE',
- 'read': 'GET'
-};
-
-// Set the default implementation of `Backbone.ajax` to proxy through to `$`.
-// Override this if you'd like to use a different library.
-Backbone.ajax = Backbone.$ ? function() {
- return Backbone.$.ajax.apply(Backbone.$, arguments);
-} : utils.ajax;
-
-if (Backbone.$) Backbone.Deferred = function() {
- return new Backbone.$.Deferred();
-};
-// Backbone.Router
-// ---------------
-
-// Routers map faux-URLs to actions, and fire events when routes are
-// matched. Creating a new one sets its `routes` hash, if not set statically.
-var Router = Backbone.Router = function(options) {
- options || (options = {});
- if (options.routes) this.routes = options.routes;
- this._bindRoutes();
- this.initialize.apply(this, arguments);
-};
-
-// Cached regular expressions for matching named param parts and splatted
-// parts of route strings.
-var optionalParam = /\((.*?)\)/g;
-var namedParam = /(\(\?)?:\w+/g;
-var splatParam = /\*\w+/g;
-var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
-
-var isRegExp = function(value) {
- return value ? (typeof value === 'object' && toString.call(value) === '[object RegExp]') : false;
-};
-
-// Set up all inheritable **Backbone.Router** properties and methods.
-_.extend(Router.prototype, Events, {
-
- // Initialize is an empty function by default. Override it with your own
- // initialization logic.
- initialize: function(){},
-
- // Manually bind a single named route to a callback. For example:
- //
- // this.route('search/:query/p:num', 'search', function(query, num) {
- // ...
- // });
- //
- route: function(route, name, callback) {
- if (!isRegExp(route)) route = this._routeToRegExp(route);
- if (typeof name === 'function') {
- callback = name;
- name = '';
- }
- if (!callback) callback = this[name];
- var router = this;
- Backbone.history.route(route, function(fragment) {
- var args = router._extractParameters(route, fragment);
- callback && callback.apply(router, args);
- router.trigger.apply(router, ['route:' + name].concat(args));
- router.trigger('route', name, args);
- Backbone.history.trigger('route', router, name, args);
- });
- return this;
- },
-
- // Simple proxy to `Backbone.history` to save a fragment into the history.
- navigate: function(fragment, options) {
- Backbone.history.navigate(fragment, options);
- return this;
- },
-
- // Bind all defined routes to `Backbone.history`. We have to reverse the
- // order of the routes here to support behavior where the most general
- // routes can be defined at the bottom of the route map.
- _bindRoutes: function() {
- if (!this.routes) return;
- this.routes = _.result(this, 'routes');
- var route, routes = Object.keys(this.routes);
- while ((route = routes.pop()) != null) {
- this.route(route, this.routes[route]);
- }
- },
-
- // Convert a route string into a regular expression, suitable for matching
- // against the current location hash.
- _routeToRegExp: function(route) {
- route = route.replace(escapeRegExp, '\\$&')
- .replace(optionalParam, '(?:$1)?')
- .replace(namedParam, function(match, optional) {
- return optional ? match : '([^\/]+)';
- })
- .replace(splatParam, '(.*?)');
- return new RegExp('^' + route + '$');
- },
-
- // Given a route, and a URL fragment that it matches, return the array of
- // extracted decoded parameters. Empty or unmatched parameters will be
- // treated as `null` to normalize cross-browser behavior.
- _extractParameters: function(route, fragment) {
- var params = route.exec(fragment).slice(1);
- return params.map(function(param) {
- return param ? decodeURIComponent(param) : null;
- });
- }
-
-});
-// Backbone.History
-// ----------------
-
-// Handles cross-browser history management, based on either
-// [pushState](http://diveintohtml5.info/history.html) and real URLs, or
-// [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
-// and URL fragments.
-var History = Backbone.History = function() {
- this.handlers = [];
- this.checkUrl = this.checkUrl.bind(this);
-
- // Ensure that `History` can be used outside of the browser.
- if (typeof window !== 'undefined') {
- this.location = window.location;
- this.history = window.history;
- }
-};
-
-// Cached regex for stripping a leading hash/slash and trailing space.
-var routeStripper = /^[#\/]|\s+$/g;
-
-// Cached regex for stripping leading and trailing slashes.
-var rootStripper = /^\/+|\/+$/g;
-
-// Cached regex for removing a trailing slash.
-var trailingSlash = /\/$/;
-
-// Cached regex for stripping urls of hash and query.
-var pathStripper = /[#].*$/;
-
-// Has the history handling already been started?
-History.started = false;
-
-// Set up all inheritable **Backbone.History** properties and methods.
-_.extend(History.prototype, Events, {
-
- // Gets the true hash value. Cannot use location.hash directly due to bug
- // in Firefox where location.hash will always be decoded.
- getHash: function(window) {
- var match = (window || this).location.href.match(/#(.*)$/);
- return match ? match[1] : '';
- },
-
- // Get the cross-browser normalized URL fragment, either from the URL,
- // the hash, or the override.
- getFragment: function(fragment) {
- if (fragment == null) {
- if (this._wantsPushState || !this._wantsHashChange) {
- // CHANGED: Make fragment include query string.
- fragment = this.location.pathname + this.location.search;
- var root = this.root.replace(trailingSlash, '');
- if (!fragment.indexOf(root)) fragment = fragment.slice(root.length);
- } else {
- fragment = this.getHash();
- }
- }
- return fragment.replace(routeStripper, '');
- },
-
- // Start the hash change handling, returning `true` if the current URL matches
- // an existing route, and `false` otherwise.
- start: function(options) {
- if (History.started) throw new Error("Backbone.history has already been started");
- History.started = true;
-
- // Figure out the initial configuration.
- // Is pushState desired or should we use hashchange only?
- this.options = _.extend({root: '/'}, this.options, options);
- this.root = this.options.root;
- this._wantsHashChange = this.options.hashChange !== false;
- this._wantsPushState = !!this.options.pushState;
- var fragment = this.getFragment();
-
- // Normalize root to always include a leading and trailing slash.
- this.root = ('/' + this.root + '/').replace(rootStripper, '/');
-
- // Depending on whether we're using pushState or hashes, determine how we
- // check the URL state.
- if (this._wantsPushState) {
- window.addEventListener('popstate', this.checkUrl, false);
- } else if (this._wantsHashChange) {
- window.addEventListener('hashchange', this.checkUrl, false);
- }
-
- // Determine if we need to change the base url, for a pushState link
- // opened by a non-pushState browser.
- this.fragment = fragment;
- var loc = this.location;
- var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
-
- // Transition from hashChange to pushState or vice versa if both are
- // requested.
- if (this._wantsHashChange && this._wantsPushState) {
- // If we've started out with a hash-based route, but we're currently
- // in a browser where it could be `pushState`-based instead...
- if (atRoot && loc.hash) {
- this.fragment = this.getHash().replace(routeStripper, '');
- // CHANGED: It's no longer needed to add loc.search at the end,
- // as query params have been already included into @fragment
- this.history.replaceState({}, document.title, this.root + this.fragment);
- }
-
- }
-
- if (!this.options.silent) return this.loadUrl();
- },
-
- // Disable Backbone.history, perhaps temporarily. Not useful in a real app,
- // but possibly useful for unit testing Routers.
- stop: function() {
- window.removeEventListener('popstate', this.checkUrl);
- window.removeEventListener('hashchange', this.checkUrl);
- History.started = false;
- },
-
- // Add a route to be tested when the fragment changes. Routes added later
- // may override previous routes.
- route: function(route, callback) {
- this.handlers.unshift({route: route, callback: callback});
- },
-
- // Checks the current URL to see if it has changed, and if it has,
- // calls `loadUrl`.
- checkUrl: function() {
- var current = this.getFragment();
- if (current === this.fragment) return false;
- this.loadUrl();
- },
-
- // Attempt to load the current URL fragment. If a route succeeds with a
- // match, returns `true`. If no defined routes matches the fragment,
- // returns `false`.
- loadUrl: function(fragment) {
- fragment = this.fragment = this.getFragment(fragment);
- return this.handlers.some(function(handler) {
- if (handler.route.test(fragment)) {
- handler.callback(fragment);
- return true;
- }
- });
- },
-
- // Save a fragment into the hash history, or replace the URL state if the
- // 'replace' option is passed. You are responsible for properly URL-encoding
- // the fragment in advance.
- //
- // The options object can contain `trigger: true` if you wish to have the
- // route callback be fired (not usually desirable), or `replace: true`, if
- // you wish to modify the current URL without adding an entry to the history.
- navigate: function(fragment, options) {
- if (!History.started) return false;
- if (!options || options === true) options = {trigger: !!options};
-
- var url = this.root + (fragment = this.getFragment(fragment || ''));
-
- // Strip the fragment of the query and hash for matching.
- fragment = fragment.replace(pathStripper, '');
-
- if (this.fragment === fragment) return;
- this.fragment = fragment;
-
- // Don't include a trailing slash on the root.
- if (fragment === '' && url !== '/') url = url.slice(0, -1);
-
- // If we're using pushState we use it to set the fragment as a real URL.
- if (this._wantsPushState) {
- this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
-
- // If hash changes haven't been explicitly disabled, update the hash
- // fragment to store history.
- } else if (this._wantsHashChange) {
- this._updateHash(this.location, fragment, options.replace);
- // If you've told us that you explicitly don't want fallback hashchange-
- // based history, then `navigate` becomes a page refresh.
- } else {
- return this.location.assign(url);
- }
- if (options.trigger) return this.loadUrl(fragment);
- },
-
- // Update the hash location, either replacing the current entry, or adding
- // a new one to the browser history.
- _updateHash: function(location, fragment, replace) {
- if (replace) {
- var href = location.href.replace(/(javascript:|#).*$/, '');
- location.replace(href + '#' + fragment);
- } else {
- // Some browsers require that `hash` contains a leading #.
- location.hash = '#' + fragment;
- }
- }
-
-});
- // !!!
- // Init.
- ['Model', 'Collection', 'Router', 'View', 'History'].forEach(function(name) {
- var item = Backbone[name];
- if (item) item.extend = Backbone.extend;
- });
-
- // Allow the `Backbone` object to serve as a global event bus, for folks who
- // want global "pubsub" in a convenient place.
- _.extend(Backbone, Events);
-
- // Create the default Backbone.history.
- Backbone.history = new History();
- return Backbone;
-});
diff --git a/examples/chaplin-brunch/node_modules/todomvc-app-css/index.css b/examples/chaplin-brunch/node_modules/todomvc-app-css/index.css
deleted file mode 100644
index 54d89abda7..0000000000
--- a/examples/chaplin-brunch/node_modules/todomvc-app-css/index.css
+++ /dev/null
@@ -1,378 +0,0 @@
-html,
-body {
- margin: 0;
- padding: 0;
-}
-
-button {
- margin: 0;
- padding: 0;
- border: 0;
- background: none;
- font-size: 100%;
- vertical-align: baseline;
- font-family: inherit;
- font-weight: inherit;
- color: inherit;
- -webkit-appearance: none;
- appearance: none;
- -webkit-font-smoothing: antialiased;
- -moz-font-smoothing: antialiased;
- font-smoothing: antialiased;
-}
-
-body {
- font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
- line-height: 1.4em;
- background: #f5f5f5;
- color: #4d4d4d;
- min-width: 230px;
- max-width: 550px;
- margin: 0 auto;
- -webkit-font-smoothing: antialiased;
- -moz-font-smoothing: antialiased;
- font-smoothing: antialiased;
- font-weight: 300;
-}
-
-button,
-input[type="checkbox"] {
- outline: none;
-}
-
-.hidden {
- display: none;
-}
-
-#todoapp {
- background: #fff;
- margin: 130px 0 40px 0;
- position: relative;
- box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2),
- 0 25px 50px 0 rgba(0, 0, 0, 0.1);
-}
-
-#todoapp input::-webkit-input-placeholder {
- font-style: italic;
- font-weight: 300;
- color: #e6e6e6;
-}
-
-#todoapp input::-moz-placeholder {
- font-style: italic;
- font-weight: 300;
- color: #e6e6e6;
-}
-
-#todoapp input::input-placeholder {
- font-style: italic;
- font-weight: 300;
- color: #e6e6e6;
-}
-
-#todoapp h1 {
- position: absolute;
- top: -155px;
- width: 100%;
- font-size: 100px;
- font-weight: 100;
- text-align: center;
- color: rgba(175, 47, 47, 0.15);
- -webkit-text-rendering: optimizeLegibility;
- -moz-text-rendering: optimizeLegibility;
- text-rendering: optimizeLegibility;
-}
-
-#new-todo,
-.edit {
- position: relative;
- margin: 0;
- width: 100%;
- font-size: 24px;
- font-family: inherit;
- font-weight: inherit;
- line-height: 1.4em;
- border: 0;
- outline: none;
- color: inherit;
- padding: 6px;
- border: 1px solid #999;
- box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
- box-sizing: border-box;
- -webkit-font-smoothing: antialiased;
- -moz-font-smoothing: antialiased;
- font-smoothing: antialiased;
-}
-
-#new-todo {
- padding: 16px 16px 16px 60px;
- border: none;
- background: rgba(0, 0, 0, 0.003);
- box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03);
-}
-
-#main {
- position: relative;
- z-index: 2;
- border-top: 1px solid #e6e6e6;
-}
-
-label[for='toggle-all'] {
- display: none;
-}
-
-#toggle-all {
- position: absolute;
- top: -55px;
- left: -12px;
- width: 60px;
- height: 34px;
- text-align: center;
- border: none; /* Mobile Safari */
-}
-
-#toggle-all:before {
- content: '❯';
- font-size: 22px;
- color: #e6e6e6;
- padding: 10px 27px 10px 27px;
-}
-
-#toggle-all:checked:before {
- color: #737373;
-}
-
-#todo-list {
- margin: 0;
- padding: 0;
- list-style: none;
-}
-
-#todo-list li {
- position: relative;
- font-size: 24px;
- border-bottom: 1px solid #ededed;
-}
-
-#todo-list li:last-child {
- border-bottom: none;
-}
-
-#todo-list li.editing {
- border-bottom: none;
- padding: 0;
-}
-
-#todo-list li.editing .edit {
- display: block;
- width: 506px;
- padding: 13px 17px 12px 17px;
- margin: 0 0 0 43px;
-}
-
-#todo-list li.editing .view {
- display: none;
-}
-
-#todo-list li .toggle {
- text-align: center;
- width: 40px;
- /* auto, since non-WebKit browsers doesn't support input styling */
- height: auto;
- position: absolute;
- top: 0;
- bottom: 0;
- margin: auto 0;
- border: none; /* Mobile Safari */
- -webkit-appearance: none;
- appearance: none;
-}
-
-#todo-list li .toggle:after {
- content: url('data:image/svg+xml;utf8, ');
-}
-
-#todo-list li .toggle:checked:after {
- content: url('data:image/svg+xml;utf8, ');
-}
-
-#todo-list li label {
- white-space: pre;
- word-break: break-word;
- padding: 15px 60px 15px 15px;
- margin-left: 45px;
- display: block;
- line-height: 1.2;
- transition: color 0.4s;
-}
-
-#todo-list li.completed label {
- color: #d9d9d9;
- text-decoration: line-through;
-}
-
-#todo-list li .destroy {
- display: none;
- position: absolute;
- top: 0;
- right: 10px;
- bottom: 0;
- width: 40px;
- height: 40px;
- margin: auto 0;
- font-size: 30px;
- color: #cc9a9a;
- margin-bottom: 11px;
- transition: color 0.2s ease-out;
-}
-
-#todo-list li .destroy:hover {
- color: #af5b5e;
-}
-
-#todo-list li .destroy:after {
- content: '×';
-}
-
-#todo-list li:hover .destroy {
- display: block;
-}
-
-#todo-list li .edit {
- display: none;
-}
-
-#todo-list li.editing:last-child {
- margin-bottom: -1px;
-}
-
-#footer {
- color: #777;
- padding: 10px 15px;
- height: 20px;
- text-align: center;
- border-top: 1px solid #e6e6e6;
-}
-
-#footer:before {
- content: '';
- position: absolute;
- right: 0;
- bottom: 0;
- left: 0;
- height: 50px;
- overflow: hidden;
- box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2),
- 0 8px 0 -3px #f6f6f6,
- 0 9px 1px -3px rgba(0, 0, 0, 0.2),
- 0 16px 0 -6px #f6f6f6,
- 0 17px 2px -6px rgba(0, 0, 0, 0.2);
-}
-
-#todo-count {
- float: left;
- text-align: left;
-}
-
-#todo-count strong {
- font-weight: 300;
-}
-
-#filters {
- margin: 0;
- padding: 0;
- list-style: none;
- position: absolute;
- right: 0;
- left: 0;
-}
-
-#filters li {
- display: inline;
-}
-
-#filters li a {
- color: inherit;
- margin: 3px;
- padding: 3px 7px;
- text-decoration: none;
- border: 1px solid transparent;
- border-radius: 3px;
-}
-
-#filters li a.selected,
-#filters li a:hover {
- border-color: rgba(175, 47, 47, 0.1);
-}
-
-#filters li a.selected {
- border-color: rgba(175, 47, 47, 0.2);
-}
-
-#clear-completed,
-html #clear-completed:active {
- float: right;
- position: relative;
- line-height: 20px;
- text-decoration: none;
- cursor: pointer;
- position: relative;
-}
-
-#clear-completed:hover {
- text-decoration: underline;
-}
-
-#info {
- margin: 65px auto 0;
- color: #bfbfbf;
- font-size: 10px;
- text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
- text-align: center;
-}
-
-#info p {
- line-height: 1;
-}
-
-#info a {
- color: inherit;
- text-decoration: none;
- font-weight: 400;
-}
-
-#info a:hover {
- text-decoration: underline;
-}
-
-/*
- Hack to remove background from Mobile Safari.
- Can't use it globally since it destroys checkboxes in Firefox
-*/
-@media screen and (-webkit-min-device-pixel-ratio:0) {
- #toggle-all,
- #todo-list li .toggle {
- background: none;
- }
-
- #todo-list li .toggle {
- height: 40px;
- }
-
- #toggle-all {
- -webkit-transform: rotate(90deg);
- transform: rotate(90deg);
- -webkit-appearance: none;
- appearance: none;
- }
-}
-
-@media (max-width: 430px) {
- #footer {
- height: 50px;
- }
-
- #filters {
- bottom: 10px;
- }
-}
diff --git a/examples/chaplin-brunch/node_modules/todomvc-common/base.css b/examples/chaplin-brunch/node_modules/todomvc-common/base.css
deleted file mode 100644
index da65968a73..0000000000
--- a/examples/chaplin-brunch/node_modules/todomvc-common/base.css
+++ /dev/null
@@ -1,141 +0,0 @@
-hr {
- margin: 20px 0;
- border: 0;
- border-top: 1px dashed #c5c5c5;
- border-bottom: 1px dashed #f7f7f7;
-}
-
-.learn a {
- font-weight: normal;
- text-decoration: none;
- color: #b83f45;
-}
-
-.learn a:hover {
- text-decoration: underline;
- color: #787e7e;
-}
-
-.learn h3,
-.learn h4,
-.learn h5 {
- margin: 10px 0;
- font-weight: 500;
- line-height: 1.2;
- color: #000;
-}
-
-.learn h3 {
- font-size: 24px;
-}
-
-.learn h4 {
- font-size: 18px;
-}
-
-.learn h5 {
- margin-bottom: 0;
- font-size: 14px;
-}
-
-.learn ul {
- padding: 0;
- margin: 0 0 30px 25px;
-}
-
-.learn li {
- line-height: 20px;
-}
-
-.learn p {
- font-size: 15px;
- font-weight: 300;
- line-height: 1.3;
- margin-top: 0;
- margin-bottom: 0;
-}
-
-#issue-count {
- display: none;
-}
-
-.quote {
- border: none;
- margin: 20px 0 60px 0;
-}
-
-.quote p {
- font-style: italic;
-}
-
-.quote p:before {
- content: '“';
- font-size: 50px;
- opacity: .15;
- position: absolute;
- top: -20px;
- left: 3px;
-}
-
-.quote p:after {
- content: '”';
- font-size: 50px;
- opacity: .15;
- position: absolute;
- bottom: -42px;
- right: 3px;
-}
-
-.quote footer {
- position: absolute;
- bottom: -40px;
- right: 0;
-}
-
-.quote footer img {
- border-radius: 3px;
-}
-
-.quote footer a {
- margin-left: 5px;
- vertical-align: middle;
-}
-
-.speech-bubble {
- position: relative;
- padding: 10px;
- background: rgba(0, 0, 0, .04);
- border-radius: 5px;
-}
-
-.speech-bubble:after {
- content: '';
- position: absolute;
- top: 100%;
- right: 30px;
- border: 13px solid transparent;
- border-top-color: rgba(0, 0, 0, .04);
-}
-
-.learn-bar > .learn {
- position: absolute;
- width: 272px;
- top: 8px;
- left: -300px;
- padding: 10px;
- border-radius: 5px;
- background-color: rgba(255, 255, 255, .6);
- transition-property: left;
- transition-duration: 500ms;
-}
-
-@media (min-width: 899px) {
- .learn-bar {
- width: auto;
- padding-left: 300px;
- }
-
- .learn-bar > .learn {
- left: 8px;
- }
-}
diff --git a/examples/chaplin-brunch/node_modules/todomvc-common/base.js b/examples/chaplin-brunch/node_modules/todomvc-common/base.js
deleted file mode 100644
index 61cf1dc931..0000000000
--- a/examples/chaplin-brunch/node_modules/todomvc-common/base.js
+++ /dev/null
@@ -1,279 +0,0 @@
-/* global _ */
-;(function () {
- 'use strict'
- /* jshint ignore:start */
- // Underscore's Template Module
- // Courtesy of underscorejs.org
- var _ = (function (_) {
- _.defaults = function (object) {
- if (!object) {
- return object
- }
- for (
- var argsIndex = 1, argsLength = arguments.length;
- argsIndex < argsLength;
- argsIndex++
- ) {
- var iterable = arguments[argsIndex]
- if (iterable) {
- for (var key in iterable) {
- if (object[key] == null) {
- object[key] = iterable[key]
- }
- }
- }
- }
- return object
- }
-
- // By default, Underscore uses ERB-style template delimiters, change the
- // following template settings to use alternative delimiters.
- _.templateSettings = {
- evaluate: /<%([\s\S]+?)%>/g,
- interpolate: /<%=([\s\S]+?)%>/g,
- escape: /<%-([\s\S]+?)%>/g
- }
-
- // When customizing `templateSettings`, if you don't want to define an
- // interpolation, evaluation or escaping regex, we need one that is
- // guaranteed not to match.
- var noMatch = /(.)^/
-
- // Certain characters need to be escaped so that they can be put into a
- // string literal.
- var escapes = {
- "'": "'",
- '\\': '\\',
- '\r': 'r',
- '\n': 'n',
- '\t': 't',
- '\u2028': 'u2028',
- '\u2029': 'u2029'
- }
-
- var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g
-
- // JavaScript micro-templating, similar to John Resig's implementation.
- // Underscore templating handles arbitrary delimiters, preserves whitespace,
- // and correctly escapes quotes within interpolated code.
- _.template = function (text, data, settings) {
- var render
- settings = _.defaults({}, settings, _.templateSettings)
-
- // Combine delimiters into one regular expression via alternation.
- var matcher = new RegExp(
- [
- (settings.escape || noMatch).source,
- (settings.interpolate || noMatch).source,
- (settings.evaluate || noMatch).source
- ].join('|') + '|$',
- 'g'
- )
-
- // Compile the template source, escaping string literals appropriately.
- var index = 0
- var source = "__p+='"
- text.replace(matcher, function (
- match,
- escape,
- interpolate,
- evaluate,
- offset
- ) {
- source += text.slice(index, offset).replace(escaper, function (match) {
- return '\\' + escapes[match]
- })
-
- if (escape) {
- source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"
- }
- if (interpolate) {
- source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"
- }
- if (evaluate) {
- source += "';\n" + evaluate + "\n__p+='"
- }
- index = offset + match.length
- return match
- })
- source += "';\n"
-
- // If a variable is not specified, place data values in local scope.
- if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'
-
- source =
- "var __t,__p='',__j=Array.prototype.join," +
- "print=function(){__p+=__j.call(arguments,'');};\n" +
- source +
- 'return __p;\n'
-
- try {
- render = new Function(settings.variable || 'obj', '_', source)
- } catch (e) {
- e.source = source
- throw e
- }
-
- if (data) return render(data, _)
- var template = function (data) {
- return render.call(this, data, _)
- }
-
- // Provide the compiled function source as a convenience for precompilation.
- template.source =
- 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'
-
- return template
- }
-
- return _
- })({})
-
- if (location.hostname === 'todomvc.com') {
- window._gaq = [['_setAccount', 'UA-31081062-1'], ['_trackPageview']]
- ;(function (d, t) {
- var g = d.createElement(t), s = d.getElementsByTagName(t)[0]
- g.src = '//www.google-analytics.com/ga.js'
- s.parentNode.insertBefore(g, s)
- })(document, 'script')
- }
- /* jshint ignore:end */
-
- function redirect () {
- if (location.hostname === 'tastejs.github.io') {
- location.href = location.href.replace(
- 'tastejs.github.io/todomvc',
- 'todomvc.com'
- )
- }
- }
-
- function findRoot () {
- var base = location.href.indexOf('examples/')
- return location.href.substr(0, base)
- }
-
- function getFile (file, callback) {
- if (!location.host) {
- return console.info(
- 'Miss the info bar? Run TodoMVC from a server to avoid a cross-origin error.'
- )
- }
-
- var xhr = new XMLHttpRequest()
-
- xhr.open('GET', findRoot() + file, true)
- xhr.send()
-
- xhr.onload = function () {
- if (xhr.status === 200 && callback) {
- callback(xhr.responseText)
- }
- }
- }
-
- function Learn (learnJSON, config) {
- if (!(this instanceof Learn)) {
- return new Learn(learnJSON, config)
- }
-
- var template, framework
-
- if (typeof learnJSON !== 'object') {
- try {
- learnJSON = JSON.parse(learnJSON)
- } catch (e) {
- return
- }
- }
-
- if (config) {
- template = config.template
- framework = config.framework
- }
-
- if (!template && learnJSON.templates) {
- template = learnJSON.templates.todomvc
- }
-
- if (!framework && document.querySelector('[data-framework]')) {
- framework = document.querySelector('[data-framework]').dataset.framework
- }
-
- this.template = template
-
- if (learnJSON.backend) {
- this.frameworkJSON = learnJSON.backend
- this.frameworkJSON.issueLabel = framework
- this.append({
- backend: true
- })
- } else if (learnJSON[framework]) {
- this.frameworkJSON = learnJSON[framework]
- this.frameworkJSON.issueLabel = framework
- this.append()
- }
-
- this.fetchIssueCount()
- }
-
- Learn.prototype.append = function (opts) {
- var aside = document.createElement('aside')
- aside.innerHTML = _.template(this.template, this.frameworkJSON)
- aside.className = 'learn'
-
- if (opts && opts.backend) {
- // Remove demo link
- var sourceLinks = aside.querySelector('.source-links')
- var heading = sourceLinks.firstElementChild
- var sourceLink = sourceLinks.lastElementChild
- // Correct link path
- var href = sourceLink.getAttribute('href')
- sourceLink.setAttribute('href', href.substr(href.lastIndexOf('http')))
- sourceLinks.innerHTML = heading.outerHTML + sourceLink.outerHTML
- } else {
- // Localize demo links
- var demoLinks = aside.querySelectorAll('.demo-link')
- Array.prototype.forEach.call(demoLinks, function (demoLink) {
- if (demoLink.getAttribute('href').substr(0, 4) !== 'http') {
- demoLink.setAttribute(
- 'href',
- findRoot() + demoLink.getAttribute('href')
- )
- }
- })
- }
-
- // not sure why document.body is undefined sometimes
- if (document && document.body) {
- document.body.className = (document.body.className + ' learn-bar').trim()
- document.body.insertAdjacentHTML('afterBegin', aside.outerHTML)
- }
- }
-
- Learn.prototype.fetchIssueCount = function () {
- var issueLink = document.getElementById('issue-count-link')
- if (issueLink) {
- var url = issueLink.href.replace(
- 'https://github.com',
- 'https://api.github.com/repos'
- )
- var xhr = new XMLHttpRequest()
- xhr.open('GET', url, true)
- xhr.onload = function (e) {
- var parsedResponse = JSON.parse(e.target.responseText)
- if (parsedResponse instanceof Array) {
- var count = parsedResponse.length
- if (count !== 0) {
- issueLink.innerHTML = 'This app has ' + count + ' open issues'
- document.getElementById('issue-count').style.display = 'inline'
- }
- }
- }
- xhr.send()
- }
- }
-
- redirect()
- getFile('learn.json', Learn)
-})()
diff --git a/examples/chaplin-brunch/package.json b/examples/chaplin-brunch/package.json
deleted file mode 100644
index a8020d3c16..0000000000
--- a/examples/chaplin-brunch/package.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "private": true,
- "dependencies": {
- "chaplin": "^1.0.0",
- "exoskeleton": "^0.6.3",
- "backbone.localstorage": "^1.1.16",
- "backbone.nativeview": "^0.3.2",
-
- "todomvc-app-css": "^1.0.0",
- "todomvc-common": "^1.0.1",
-
- "javascript-brunch": ">= 1.0 < 1.8",
- "coffee-script-brunch": ">= 1.0 < 1.8",
- "handlebars-brunch": ">= 1.0 < 1.8",
- "uglify-js-brunch": ">= 1.0 < 1.8"
- }
-}
diff --git a/examples/chaplin-brunch/public/app.js b/examples/chaplin-brunch/public/app.js
deleted file mode 100644
index d9e56237cd..0000000000
--- a/examples/chaplin-brunch/public/app.js
+++ /dev/null
@@ -1,720 +0,0 @@
-(function(/*! Brunch !*/) {
- 'use strict';
-
- var globals = typeof window !== 'undefined' ? window : global;
- if (typeof globals.require === 'function') return;
-
- var modules = {};
- var cache = {};
-
- var has = function(object, name) {
- return ({}).hasOwnProperty.call(object, name);
- };
-
- var expand = function(root, name) {
- var results = [], parts, part;
- if (/^\.\.?(\/|$)/.test(name)) {
- parts = [root, name].join('/').split('/');
- } else {
- parts = name.split('/');
- }
- for (var i = 0, length = parts.length; i < length; i++) {
- part = parts[i];
- if (part === '..') {
- results.pop();
- } else if (part !== '.' && part !== '') {
- results.push(part);
- }
- }
- return results.join('/');
- };
-
- var dirname = function(path) {
- return path.split('/').slice(0, -1).join('/');
- };
-
- var localRequire = function(path) {
- return function(name) {
- var dir = dirname(path);
- var absolute = expand(dir, name);
- return globals.require(absolute, path);
- };
- };
-
- var initModule = function(name, definition) {
- var module = {id: name, exports: {}};
- cache[name] = module;
- definition(module.exports, localRequire(name), module);
- return module.exports;
- };
-
- var require = function(name, loaderPath) {
- var path = expand(name, '.');
- if (loaderPath == null) loaderPath = '/';
-
- if (has(cache, path)) return cache[path].exports;
- if (has(modules, path)) return initModule(path, modules[path]);
-
- var dirIndex = expand(path, './index');
- if (has(cache, dirIndex)) return cache[dirIndex].exports;
- if (has(modules, dirIndex)) return initModule(dirIndex, modules[dirIndex]);
-
- throw new Error('Cannot find module "' + name + '" from '+ '"' + loaderPath + '"');
- };
-
- var define = function(bundle, fn) {
- if (typeof bundle === 'object') {
- for (var key in bundle) {
- if (has(bundle, key)) {
- modules[key] = bundle[key];
- }
- }
- } else {
- modules[bundle] = fn;
- }
- };
-
- var list = function() {
- var result = [];
- for (var item in modules) {
- if (has(modules, item)) {
- result.push(item);
- }
- }
- return result;
- };
-
- globals.require = require;
- globals.require.define = define;
- globals.require.register = define;
- globals.require.list = list;
- globals.require.brunch = true;
-})();
-require.register("application", function(exports, require, module) {
-var Application, Todos, mediator, _ref,
- __hasProp = {}.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
-
-mediator = require('mediator');
-
-Todos = require('models/todos');
-
-module.exports = Application = (function(_super) {
- __extends(Application, _super);
-
- function Application() {
- _ref = Application.__super__.constructor.apply(this, arguments);
- return _ref;
- }
-
- Application.prototype.title = 'Chaplin • TodoMVC';
-
- Application.prototype.initMediator = function() {
- mediator.todos = new Todos();
- return Application.__super__.initMediator.apply(this, arguments);
- };
-
- Application.prototype.start = function() {
- mediator.todos.fetch();
- return Application.__super__.start.apply(this, arguments);
- };
-
- return Application;
-
-})(Chaplin.Application);
-});
-
-;require.register("controllers/index-controller", function(exports, require, module) {
-var FooterView, HeaderView, IndexController, TodosView, mediator, _ref,
- __hasProp = {}.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
-
-HeaderView = require('../views/header-view');
-
-FooterView = require('../views/footer-view');
-
-TodosView = require('../views/todos-view');
-
-mediator = require('mediator');
-
-module.exports = IndexController = (function(_super) {
- __extends(IndexController, _super);
-
- function IndexController() {
- _ref = IndexController.__super__.constructor.apply(this, arguments);
- return _ref;
- }
-
- IndexController.prototype.beforeAction = function() {
- return this.reuse('structure', function() {
- var params;
- params = {
- collection: mediator.todos
- };
- this.header = new HeaderView(params);
- return this.footer = new FooterView(params);
- });
- };
-
- IndexController.prototype.list = function(params) {
- var filterer, _ref1, _ref2;
- filterer = (_ref1 = (_ref2 = params.filterer) != null ? _ref2.trim() : void 0) != null ? _ref1 : 'all';
- this.publishEvent('todos:filter', filterer);
- return this.view = new TodosView({
- collection: mediator.todos,
- filterer: function(model) {
- switch (filterer) {
- case 'completed':
- return model.get('completed');
- case 'active':
- return !model.get('completed');
- default:
- return true;
- }
- }
- });
- };
-
- return IndexController;
-
-})(Chaplin.Controller);
-});
-
-;require.register("initialize", function(exports, require, module) {
-var Application, routes;
-
-Application = require('application');
-
-routes = require('routes');
-
-document.addEventListener('DOMContentLoaded', function() {
- return new Application({
- controllerSuffix: '-controller',
- pushState: false,
- routes: routes
- });
-}, false);
-});
-
-;require.register("lib/utils", function(exports, require, module) {
-var utils;
-
-utils = Chaplin.utils.beget(Chaplin.utils);
-
-Backbone.utils.extend(utils, {
- toggle: function(elem, visible) {
- return elem.style.display = (visible ? '' : 'none');
- }
-});
-
-if (typeof Object.seal === "function") {
- Object.seal(utils);
-}
-
-module.exports = utils;
-});
-
-;require.register("mediator", function(exports, require, module) {
-module.exports = Chaplin.mediator;
-});
-
-;require.register("models/todo", function(exports, require, module) {
-var Todo, _ref,
- __hasProp = {}.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
-
-module.exports = Todo = (function(_super) {
- __extends(Todo, _super);
-
- function Todo() {
- _ref = Todo.__super__.constructor.apply(this, arguments);
- return _ref;
- }
-
- Todo.prototype.defaults = {
- title: '',
- completed: false
- };
-
- Todo.prototype.initialize = function() {
- Todo.__super__.initialize.apply(this, arguments);
- if (this.isNew()) {
- return this.set('created', Date.now());
- }
- };
-
- Todo.prototype.toggle = function() {
- return this.set({
- completed: !this.get('completed')
- });
- };
-
- Todo.prototype.isVisible = function() {
- var isCompleted;
- return isCompleted = this.get('completed');
- };
-
- return Todo;
-
-})(Chaplin.Model);
-});
-
-;require.register("models/todos", function(exports, require, module) {
-var Todo, Todos, _ref,
- __hasProp = {}.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
-
-Todo = require('models/todo');
-
-module.exports = Todos = (function(_super) {
- __extends(Todos, _super);
-
- function Todos() {
- _ref = Todos.__super__.constructor.apply(this, arguments);
- return _ref;
- }
-
- Todos.prototype.model = Todo;
-
- Todos.prototype.localStorage = new Store('todos-chaplin');
-
- Todos.prototype.allAreCompleted = function() {
- return this.getCompleted().length === this.length;
- };
-
- Todos.prototype.getCompleted = function() {
- return this.where({
- completed: true
- });
- };
-
- Todos.prototype.getActive = function() {
- return this.where({
- completed: false
- });
- };
-
- Todos.prototype.comparator = function(todo) {
- return todo.get('created');
- };
-
- return Todos;
-
-})(Chaplin.Collection);
-});
-
-;require.register("routes", function(exports, require, module) {
-module.exports = function(match) {
- match(':filterer', 'index#list');
- return match('', 'index#list');
-};
-});
-
-;require.register("views/base/collection-view", function(exports, require, module) {
-var CollectionView, View, _ref,
- __hasProp = {}.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
-
-View = require('views/base/view');
-
-module.exports = CollectionView = (function(_super) {
- __extends(CollectionView, _super);
-
- function CollectionView() {
- _ref = CollectionView.__super__.constructor.apply(this, arguments);
- return _ref;
- }
-
- CollectionView.prototype.getTemplateFunction = View.prototype.getTemplateFunction;
-
- CollectionView.prototype.useCssAnimation = true;
-
- return CollectionView;
-
-})(Chaplin.CollectionView);
-});
-
-;require.register("views/base/view", function(exports, require, module) {
-var View, _ref,
- __hasProp = {}.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
-
-module.exports = View = (function(_super) {
- __extends(View, _super);
-
- function View() {
- _ref = View.__super__.constructor.apply(this, arguments);
- return _ref;
- }
-
- View.prototype.getTemplateFunction = function() {
- return this.template;
- };
-
- return View;
-
-})(Chaplin.View);
-});
-
-;require.register("views/footer-view", function(exports, require, module) {
-var FooterView, View, utils, _ref,
- __hasProp = {}.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
-
-View = require('./base/view');
-
-utils = require('lib/utils');
-
-module.exports = FooterView = (function(_super) {
- __extends(FooterView, _super);
-
- function FooterView() {
- _ref = FooterView.__super__.constructor.apply(this, arguments);
- return _ref;
- }
-
- FooterView.prototype.autoRender = true;
-
- FooterView.prototype.el = '#footer';
-
- FooterView.prototype.events = {
- 'click #clear-completed': 'clearCompleted'
- };
-
- FooterView.prototype.listen = {
- 'todos:filter mediator': 'updateFilterer',
- 'all collection': 'renderCounter'
- };
-
- FooterView.prototype.template = require('./templates/footer');
-
- FooterView.prototype.render = function() {
- FooterView.__super__.render.apply(this, arguments);
- return this.renderCounter();
- };
-
- FooterView.prototype.updateFilterer = function(filterer) {
- var cls, selector,
- _this = this;
- if (filterer === 'all') {
- filterer = '';
- }
- selector = "[href='#/" + filterer + "']";
- cls = 'selected';
- return this.findAll('#filters a').forEach(function(link) {
- link.classList.remove(cls);
- if (Backbone.utils.matchesSelector(link, selector)) {
- return link.classList.add(cls);
- }
- });
- };
-
- FooterView.prototype.renderCounter = function() {
- var active, completed, countDescription, total;
- total = this.collection.length;
- active = this.collection.getActive().length;
- completed = this.collection.getCompleted().length;
- this.find('#todo-count > strong').textContent = active;
- countDescription = (active === 1 ? 'item' : 'items');
- this.find('.todo-count-title').textContent = countDescription;
- utils.toggle(this.find('#clear-completed'), completed > 0);
- return utils.toggle(this.el, total > 0);
- };
-
- FooterView.prototype.clearCompleted = function() {
- return this.publishEvent('todos:clear');
- };
-
- return FooterView;
-
-})(View);
-});
-
-;require.register("views/header-view", function(exports, require, module) {
-var HeaderView, View, _ref,
- __hasProp = {}.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
-
-View = require('./base/view');
-
-module.exports = HeaderView = (function(_super) {
- __extends(HeaderView, _super);
-
- function HeaderView() {
- _ref = HeaderView.__super__.constructor.apply(this, arguments);
- return _ref;
- }
-
- HeaderView.prototype.autoRender = true;
-
- HeaderView.prototype.el = '#header';
-
- HeaderView.prototype.events = {
- 'keypress #new-todo': 'createOnEnter'
- };
-
- HeaderView.prototype.template = require('./templates/header');
-
- HeaderView.prototype.createOnEnter = function(event) {
- var ENTER_KEY, title;
- ENTER_KEY = 13;
- title = event.delegateTarget.value.trim();
- if (event.keyCode !== ENTER_KEY || !title) {
- return;
- }
- this.collection.create({
- title: title
- });
- return this.find('#new-todo').value = '';
- };
-
- return HeaderView;
-
-})(View);
-});
-
-;require.register("views/templates/footer", function(exports, require, module) {
-var __templateData = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
- this.compilerInfo = [4,'>= 1.0.0'];
-helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
-
-
-
- return "\n \n items \n left\n \n\nClear completed \n";
- });
-if (typeof define === 'function' && define.amd) {
- define([], function() {
- return __templateData;
- });
-} else if (typeof module === 'object' && module && module.exports) {
- module.exports = __templateData;
-} else {
- __templateData;
-}
-});
-
-;require.register("views/templates/header", function(exports, require, module) {
-var __templateData = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
- this.compilerInfo = [4,'>= 1.0.0'];
-helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
-
-
-
- return "todos \n \n";
- });
-if (typeof define === 'function' && define.amd) {
- define([], function() {
- return __templateData;
- });
-} else if (typeof module === 'object' && module && module.exports) {
- module.exports = __templateData;
-} else {
- __templateData;
-}
-});
-
-;require.register("views/templates/todo", function(exports, require, module) {
-var __templateData = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
- this.compilerInfo = [4,'>= 1.0.0'];
-helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
- var buffer = "", stack1, helper, self=this, functionType="function", escapeExpression=this.escapeExpression;
-
-function program1(depth0,data) {
-
-
- return " checked";
- }
-
- buffer += "\n \n ";
- if (helper = helpers.title) { stack1 = helper.call(depth0, {hash:{},data:data}); }
- else { helper = (depth0 && depth0.title); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; }
- buffer += escapeExpression(stack1)
- + " \n \n
\n \n";
- return buffer;
- });
-if (typeof define === 'function' && define.amd) {
- define([], function() {
- return __templateData;
- });
-} else if (typeof module === 'object' && module && module.exports) {
- module.exports = __templateData;
-} else {
- __templateData;
-}
-});
-
-;require.register("views/templates/todos", function(exports, require, module) {
-var __templateData = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
- this.compilerInfo = [4,'>= 1.0.0'];
-helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
-
-
-
- return " \nMark all as complete \n\n";
- });
-if (typeof define === 'function' && define.amd) {
- define([], function() {
- return __templateData;
- });
-} else if (typeof module === 'object' && module && module.exports) {
- module.exports = __templateData;
-} else {
- __templateData;
-}
-});
-
-;require.register("views/todo-view", function(exports, require, module) {
-var TodoView, View, _ref,
- __hasProp = {}.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
-
-View = require('./base/view');
-
-module.exports = TodoView = (function(_super) {
- __extends(TodoView, _super);
-
- function TodoView() {
- _ref = TodoView.__super__.constructor.apply(this, arguments);
- return _ref;
- }
-
- TodoView.prototype.events = {
- 'click .toggle': 'toggle',
- 'dblclick label': 'edit',
- 'keyup .edit': 'save',
- 'focusout .edit': 'save',
- 'click .destroy': 'clear'
- };
-
- TodoView.prototype.listen = {
- 'change model': 'render'
- };
-
- TodoView.prototype.template = require('./templates/todo');
-
- TodoView.prototype.tagName = 'li';
-
- TodoView.prototype.render = function() {
- TodoView.__super__.render.apply(this, arguments);
- return this.toggleClass();
- };
-
- TodoView.prototype.toggleClass = function() {
- var isCompleted;
- isCompleted = this.model.get('completed');
- return this.el.classList.toggle('completed', isCompleted);
- };
-
- TodoView.prototype.clear = function() {
- return this.model.destroy();
- };
-
- TodoView.prototype.toggle = function() {
- return this.model.toggle().save();
- };
-
- TodoView.prototype.edit = function() {
- var input;
- this.el.classList.add('editing');
- input = this.find('.edit');
- input.focus();
- return input.value = input.value;
- };
-
- TodoView.prototype.save = function(event) {
- var ENTER_KEY, title;
- ENTER_KEY = 13;
- title = event.delegateTarget.value.trim();
- if (!title) {
- return this.model.destroy();
- }
- if (event.type === 'keyup' && event.keyCode !== ENTER_KEY) {
- return;
- }
- this.model.save({
- title: title
- });
- return this.el.classList.remove('editing');
- };
-
- return TodoView;
-
-})(View);
-});
-
-;require.register("views/todos-view", function(exports, require, module) {
-var CollectionView, TodoView, TodosView, utils, _ref,
- __hasProp = {}.hasOwnProperty,
- __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
-
-CollectionView = require('./base/collection-view');
-
-TodoView = require('./todo-view');
-
-utils = require('lib/utils');
-
-module.exports = TodosView = (function(_super) {
- __extends(TodosView, _super);
-
- function TodosView() {
- _ref = TodosView.__super__.constructor.apply(this, arguments);
- return _ref;
- }
-
- TodosView.prototype.container = '#main';
-
- TodosView.prototype.events = {
- 'click #toggle-all': 'toggleCompleted'
- };
-
- TodosView.prototype.itemView = TodoView;
-
- TodosView.prototype.listSelector = '#todo-list';
-
- TodosView.prototype.listen = {
- 'all collection': 'renderCheckbox',
- 'todos:clear mediator': 'clear'
- };
-
- TodosView.prototype.template = require('./templates/todos');
-
- TodosView.prototype.render = function() {
- TodosView.__super__.render.apply(this, arguments);
- return this.renderCheckbox();
- };
-
- TodosView.prototype.renderCheckbox = function() {
- this.find('#toggle-all').checked = this.collection.allAreCompleted();
- return utils.toggle(this.el, this.collection.length !== 0);
- };
-
- TodosView.prototype.toggleCompleted = function(event) {
- var isChecked;
- isChecked = event.delegateTarget.checked;
- return this.collection.forEach(function(todo) {
- return todo.save({
- completed: isChecked
- });
- });
- };
-
- TodosView.prototype.clear = function() {
- return this.collection.getCompleted().forEach(function(model) {
- return model.destroy();
- });
- };
-
- return TodosView;
-
-})(CollectionView);
-});
-
-;
-//# sourceMappingURL=app.js.map
\ No newline at end of file
diff --git a/examples/chaplin-brunch/public/app.js.map b/examples/chaplin-brunch/public/app.js.map
deleted file mode 100644
index 4b0dfa22da..0000000000
--- a/examples/chaplin-brunch/public/app.js.map
+++ /dev/null
@@ -1 +0,0 @@
-{"version":3,"sources":["app/application.coffee","app/controllers/index-controller.coffee","app/initialize.coffee","app/lib/utils.coffee","app/mediator.coffee","app/models/todo.coffee","app/models/todos.coffee","app/routes.coffee","app/views/base/collection-view.coffee","app/views/base/view.coffee","app/views/footer-view.coffee","app/views/header-view.coffee","app/views/templates/footer.hbs","app/views/templates/header.hbs","app/views/templates/todo.hbs","app/views/templates/todos.hbs","app/views/todo-view.coffee","app/views/todos-view.coffee"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;GAAA;kSAAA;;AAAA,GAAW,KAAX,EAAW;;AACX,CADA,EACQ,EAAR,EAAQ;;AAGR,CAJA,EAIuB,GAAjB,CAAN;CAGE;;;;;CAAA;;CAAA,EAAO,EAAP;;CAAA,EAIc,SAAd;CAEE,EAAqB,CAArB,IAAQ;CAFI,QAIZ;CARF,EAIc;;CAJd,EAUO,EAAP,IAAO;CAEL,IAAc,GAAN;CAFH,QAGL;CAbF,EAUO;;CAVP;;CAHyC,MAAO;;;;ACJlD;GAAA;kSAAA;;AAAA,GAAa,OAAb,YAAa;;AACb,CADA,EACa,OAAb,YAAa;;AACb,CAFA,EAEY,MAAZ,YAAY;;AACZ,CAHA,EAGW,KAAX,EAAW;;AAEX,CALA,EAKuB,GAAjB,CAAN;CAGE;;;;;CAAA;;CAAA,EAAc,SAAd;CACG,CAAmB,EAAnB,CAAD,IAAoB,EAApB;CACE;CAAA,EAAS,GAAT;CAAS,CAAY,GAAZ;CAAT;CAAA,EACc,CAAb,EAAD,IAAc;CACb,EAAa,CAAb,EAAD,IAAc,GAAd;CAHF,IAAoB;CADtB,EAAc;;CAAd,EASM,CAAN,EAAM,GAAC;CACL;CAAA,EAAqC,CAArC;CAAA,CAC8B,EAA9B;CACC,EAAW,CAAX,KAAW,EAAZ;CAAsB,CAAY,GAAZ,GAAoB,EAApB;CAAA,CAAsC,IAAV,GAAW;CAC3D,eAAO;CAAP,cACO;CAAuB,EAAN,EAAK,MAAL;CADxB,cAEO;AAAkB,CAAJ,EAAI,EAAK,MAAL,QAAJ;CAFrB;CAAA,kBAGO;CAHP,QAD0D;CAAtC,MAAsC;CAHxD,KAGQ;CAZd,EASM;;CATN;;CAH6C,MAAO;;;;ACLtD;;AAAA,GAAc,QAAd,EAAc;;AACd,CADA,EACS,GAAT,CAAS;;AAGT,CAJA,CAI8C,MAAtC,CAAsC,OAA9C;CAEI,GADE;CACF,CAAkB,EAAlB;CAAA,CAA4C,EAAX,CAAjC,IAAiC;CAAjC,CAA2D,EAAR;CAFT,GACxC;CADwC,CAG5C,GAHF;;;;ACAA;;AAAA,GAAQ,EAAR,EAAe;;AAEf,CAFA,CAGE,GADY,CAAd,EAAQ;CACN,EAAQ,GAAR,CAAQ,EAAC;CACF,CAAiB,CAAD,CAAjB,CAAM,CAAW,CAArB;CADF,EAAQ;CAHV,CAEA;;;CAKO,CAAP,IAAM;CAPN;;AASA,CATA,EASiB,EATjB,CASM,CAAN;;;;ACbA,CAAO,EAAU,GAAX,CAAN;;;;ACIA;GAAA;kSAAA;;AAAA,GAAuB,GAAjB,CAAN;CACE;;;;;CAAA;;CAAA,EACE,KADF;CACE,CAAO,EAAP;CAAA,CACW,EAAX,CADA,IACA;CAFF;;CAAA,EAIY,OAAZ;CACE;CACA,IAA8B;CAA7B,CAAe,CAAhB,CAAC,KAAD;KAFU;CAJZ,EAIY;;CAJZ,EAQQ,GAAR,GAAQ;CACL,EAAD,CAAC,OAAD;AAAoB,CAAf,CAAW,CAAI,CAAC,EAAhB,KAAe;CADd,KACN;CATF,EAQQ;;CARR,EAWW,MAAX;CACE;CAAe,EAAD,CAAC,OAAf;CAZF,EAWW;;CAXX;;CADkC,MAAO;;;;ACJ3C;GAAA;kSAAA;;AAAA,GAAO,CAAP,GAAO;;AAEP,CAFA,EAEuB,GAAjB,CAAN;CACE;;;;;CAAA;;CAAA,EAAO,CAAP;;CAAA,EACkB,SAAlB,GAAkB;;CADlB,EAGiB,YAAjB;CACG,IAAyB,CAA1B;CAJF,EAGiB;;CAHjB,EAMc,SAAd;CACG,IAAD;CAAO,CAAW,EAAX;CADK,KACZ;CAPF,EAMc;;CANd,EASW,MAAX;CACG,IAAD;CAAO,CAAW,GAAX;CADE,KACT;CAVF,EASW;;CATX,EAYY,MAAC,CAAb;CACO,EAAL,CAAI,KAAJ;CAbF,EAYY;;CAZZ;;CADmC,MAAO;;;;ACF5C,CAAO,EAAU,GAAX,CAAN,EAAkB;CAChB;CACM,CAAN;CAFe;;;;ACAjB;GAAA;kSAAA;;AAAA,GAAO,CAAP,GAAO;;AAEP,CAFA,EAEuB,GAAjB,CAAN;CAGE;;;;;CAAA;;CAAA,EAAqB,CAAI,KAAE,UAA3B;;CAAA,EACiB,CADjB,WACA;;CADA;;CAH4C,MAAO;;;;ACFrD;GAAA;kSAAA;;AAAA,GAAuB,GAAjB,CAAN;CAEE;;;;;CAAA;;CAAA,EAAqB,gBAArB;CACG,UAAD;CADF,EAAqB;;CAArB;;CAFkC,MAAO;;;;ACA3C;GAAA;kSAAA;;AAAA,GAAO,CAAP,GAAO;;AACP,CADA,EACQ,EAAR,EAAQ;;AAER,CAHA,EAGuB,GAAjB,CAAN;CACE;;;;;CAAA;;CAAA,EAAY,CAAZ;;CAAA,CACA,CAAI,MADJ;;CAAA,EAGE,GADF;CACE,CAA0B,EAA1B;CAHF;;CAAA,EAKE,GADF;CACE,CAAyB,EAAzB;CAAA,CACkB,EAAlB,WADA,CACA;CANF;;CAAA,EAOU,KAAV,YAAU;;CAPV,EASQ,GAAR,GAAQ;CACN;CACC,UAAD;CAXF,EASQ;;CATR,EAagB,MAAC,KAAjB;CACE;OAAA;CAAA,IAA6B,GAAZ;CAAjB,EAAW,GAAX;KAAA;CAAA,EACY,CAAZ,OAAY;CADZ,EAEA,OAFA;CAGC,EAA8B,CAA9B,GAAD,EAAgC,EAAhC;CACE,GAAI,EAAJ,GAAc;CACd,CAA+D,EAArC,CAAc,CAAxC,EAAkC,OAAR;CAArB,EAAL,CAAI,KAAU,MAAd;OAF6B;CAA/B,IAA+B;CAjBjC,EAagB;;CAbhB,EAqBe,UAAf;CACE;CAAA,EAAQ,CAAR,MAAmB;CAAnB,EACS,CAAT,KAAS,CAAW;CADpB,EAEY,CAAZ,EAFA,GAEA,CAAuB,EAAX;CAFZ,EAI4C,CAA5C,EAJA,KAIA;CAJA,EAKmB,CAAnB,CAAiC,CAAV,CAAJ,SAAnB;CALA,EAMyC,CAAzC,YANA,GAMA;CANA,CAQwC,CAAY,CAApD,CAAK,CAAL,GAAwC,SAA3B;CACP,CAAN,CAA0B,CAAZ,CAAT,CAAL;CA/BF,EAqBe;;CArBf,EAiCgB,WAAhB;CACG,UAAD;CAlCF,EAiCgB;;CAjChB;;CADwC;;;;ACH1C;GAAA;kSAAA;;AAAA,GAAO,CAAP,GAAO;;AAEP,CAFA,EAEuB,GAAjB,CAAN;CACE;;;;;CAAA;;CAAA,EAAY,CAAZ;;CAAA,CACA,CAAI,MADJ;;CAAA,EAGE,GADF;CACE,CAAsB,EAAtB;CAHF;;CAAA,EAIU,KAAV,YAAU;;CAJV,EAMe,MAAC,IAAhB;CACE;CAAA,EAAY,CAAZ;CAAA,EACQ,CAAR,UAA4B;AACkB,CAA9C,IAAe,EAAL;CAAV;KAFA;CAAA,GAGA,MAAW;CAAQ,CAAC,GAAD,CAAC;CAHpB,KAGA;CACC,EAA0B,CAA1B,CAAD;CAXF,EAMe;;CANf;;CADwC;;;CCF1C;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAhBA;AAAA;CCAA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAhBA;AAAA;CCAA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAjCA;AAAA;CCAA;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAhBA;AAAA;;ACAA;GAAA;kSAAA;;AAAA,GAAO,CAAP,GAAO;;AAEP,CAFA,EAEuB,GAAjB,CAAN;CACE;;;;;CAAA;;CAAA,EACE,GADF;CACE,CAAiB,EAAjB;CAAA,CACkB,EAAlB,EADA,UACA;CADA,CAEe,EAAf,EAFA,OAEA;CAFA,CAGkB,EAAlB,EAHA,UAGA;CAHA,CAIkB,EAAlB,GAJA,SAIA;CALF;;CAAA,EAQE,GADF;CACE,CAAgB,EAAhB;CARF;;CAAA,EAUU,KAAV,UAAU;;CAVV,EAWS,CAXT,GAWA;;CAXA,EAaQ,GAAR,GAAQ;CACN;CACC,UAAD;CAfF,EAaQ;;CAbR,EAiBa,QAAb;CACE;CAAA,EAAc,CAAd,CAAoB,MAApB;CACC,CAAE,EAAF,EAAD,GAAa,EAAb;CAnBF,EAiBa;;CAjBb,EAqBO,EAAP,IAAO;CACJ,IAAK,EAAN;CAtBF,EAqBO;;CArBP,EAwBQ,GAAR,GAAQ;CACL,IAAK,CAAN;CAzBF,EAwBQ;;CAxBR,EA2BM,CAAN,KAAM;CACJ;CAAA,CAAG,CAAH,MAAa;CAAb,EACQ,CAAR,GAAQ;CADR,GAEA,CAAK;CACC,EAAQ,EAAT,MAAL;CA/BF,EA2BM;;CA3BN,EAiCM,CAAN,CAAM,IAAC;CACL;CAAA,EAAY,CAAZ;CAAA,EACQ,CAAR,UAA4B;AACG,CAA/B;CAAA,GAAQ,CAAK,EAAN;KAFP;CAGA,IAAe,EAAL,EAAV;CAAA;KAHA;CAAA,GAIA,CAAM;CAAM,CAAC,GAAD,CAAC;CAJb,KAIA;CACC,CAAE,EAAF,EAAD,GAAa,EAAb;CAvCF,EAiCM;;CAjCN;;CADsC;;;;ACFxC;GAAA;kSAAA;;AAAA,GAAiB,WAAjB,UAAiB;;AACjB,CADA,EACW,KAAX,KAAW;;AACX,CAFA,EAEQ,EAAR,EAAQ;;AAER,CAJA,EAIuB,GAAjB,CAAN;CACE;;;;;CAAA;;CAAA,EAAW,IAAX;;CAAA,EAEE,GADF;CACE,CAAqB,EAArB;CAFF;;CAAA,EAGU,KAAV;;CAHA,EAIc,SAAd;;CAJA,EAME,GADF;CACE,CAAkB,EAAlB;CAAA,CACwB,EAAxB,GADA,eACA;CAPF;;CAAA,EAQU,KAAV,WAAU;;CARV,EAUQ,GAAR,GAAQ;CACN;CACC,UAAD;CAZF,EAUQ;;CAVR,EAcgB,WAAhB;CACE,EAA+B,CAA/B,MAA0C,GAA1C,EAA+B;CACzB,CAAN,EAAc,CAAT,CAAL,IAA6B,CAA7B;CAhBF,EAcgB;;CAdhB,EAkBiB,MAAC,MAAlB;CACE;CAAA,EAAY,CAAZ,CAAiB,EAAjB,OAAgC;CAC/B,EAAmB,CAAnB,GAAD,EAAqB,CAAV,CAAX;CAAmC,GAAD,SAAJ;CAAU,CAAW,MAAX;CAApB,OAAU;CAA9B,IAAoB;CApBtB,EAkBiB;;CAlBjB,EAsBO,EAAP,IAAO;CACJ,EAAkC,CAAlC,CAAkC,EAAnC,EAAoC,CAAzB,CAAX;CACQ,IAAD,EAAL;CADF,IAAmC;CAvBrC,EAsBO;;CAtBP;;CADuC","file":"public/app.js","sourcesContent":["mediator = require 'mediator'\nTodos = require 'models/todos'\n\n# The application object\nmodule.exports = class Application extends Chaplin.Application\n # Set your application name here so the document title is set to\n # “Controller title – Site title” (see Layout#adjustTitle)\n title: 'Chaplin • TodoMVC'\n\n # Create additional mediator properties\n # -------------------------------------\n initMediator: ->\n # Add additional application-specific properties and methods\n mediator.todos = new Todos()\n # Seal the mediator\n super\n\n start: ->\n # If todos are fetched from server, we will need to wait for them.\n mediator.todos.fetch()\n super\n","HeaderView = require '../views/header-view'\nFooterView = require '../views/footer-view'\nTodosView = require '../views/todos-view'\nmediator = require 'mediator'\n\nmodule.exports = class IndexController extends Chaplin.Controller\n # The method is executed before any controller actions.\n # We compose structure in order for it to be rendered only once.\n beforeAction: ->\n @reuse 'structure', ->\n params = collection: mediator.todos\n @header = new HeaderView params\n @footer = new FooterView params\n\n # On each new load, old @view will be disposed and\n # new @view will be created. This is idiomatic Chaplin memory management:\n # one controller per screen.\n list: (params) ->\n filterer = params.filterer?.trim() ? 'all'\n @publishEvent 'todos:filter', filterer\n @view = new TodosView collection: mediator.todos, filterer: (model) ->\n switch filterer\n when 'completed' then model.get('completed')\n when 'active' then not model.get('completed')\n else true\n","Application = require 'application'\nroutes = require 'routes'\n\n# Initialize the application on DOM ready event.\ndocument.addEventListener 'DOMContentLoaded', ->\n new Application\n controllerSuffix: '-controller', pushState: false, routes: routes\n, false\n","# Application-specific utilities\n# ------------------------------\n\n# Delegate to Chaplin’s utils module.\nutils = Chaplin.utils.beget Chaplin.utils\n\nBackbone.utils.extend utils,\n toggle: (elem, visible) ->\n elem.style.display = (if visible then '' else 'none')\n\n# Prevent creating new properties and stuff.\nObject.seal? utils\n\nmodule.exports = utils\n","module.exports = Chaplin.mediator\n","# It is a very good idea to have base Model / Collection\n# e.g. Model = require 'models/base/model'\n# But in this particular app since we only have one\n# model type, we will inherit directly from Chaplin Model.\nmodule.exports = class Todo extends Chaplin.Model\n defaults:\n title: ''\n completed: no\n\n initialize: ->\n super\n @set 'created', Date.now() if @isNew()\n\n toggle: ->\n @set completed: not @get('completed')\n\n isVisible: ->\n isCompleted = @get('completed')\n","Todo = require 'models/todo'\n\nmodule.exports = class Todos extends Chaplin.Collection\n model: Todo\n localStorage: new Store 'todos-chaplin'\n\n allAreCompleted: ->\n @getCompleted().length is @length\n\n getCompleted: ->\n @where completed: yes\n\n getActive: ->\n @where completed: no\n\n comparator: (todo) ->\n todo.get('created')\n","module.exports = (match) ->\n match ':filterer', 'index#list'\n match '', 'index#list'\n","View = require 'views/base/view'\n\nmodule.exports = class CollectionView extends Chaplin.CollectionView\n # This class doesn’t inherit from the application-specific View class,\n # so we need to borrow the method from the View prototype:\n getTemplateFunction: View::getTemplateFunction\n useCssAnimation: true\n","module.exports = class View extends Chaplin.View\n # Precompiled templates function initializer.\n getTemplateFunction: ->\n @template\n","View = require './base/view'\nutils = require 'lib/utils'\n\nmodule.exports = class FooterView extends View\n autoRender: true\n el: '#footer'\n events:\n 'click #clear-completed': 'clearCompleted'\n listen:\n 'todos:filter mediator': 'updateFilterer'\n 'all collection': 'renderCounter'\n template: require './templates/footer'\n\n render: ->\n super\n @renderCounter()\n\n updateFilterer: (filterer) ->\n filterer = '' if filterer is 'all'\n selector = \"[href='#/#{filterer}']\"\n cls = 'selected'\n @findAll('#filters a').forEach (link) =>\n link.classList.remove cls\n link.classList.add cls if Backbone.utils.matchesSelector link, selector\n\n renderCounter: ->\n total = @collection.length\n active = @collection.getActive().length\n completed = @collection.getCompleted().length\n\n @find('#todo-count > strong').textContent = active\n countDescription = (if active is 1 then 'item' else 'items')\n @find('.todo-count-title').textContent = countDescription\n\n utils.toggle @find('#clear-completed'), completed > 0\n utils.toggle @el, total > 0\n\n clearCompleted: ->\n @publishEvent 'todos:clear'\n","View = require './base/view'\n\nmodule.exports = class HeaderView extends View\n autoRender: true\n el: '#header'\n events:\n 'keypress #new-todo': 'createOnEnter'\n template: require './templates/header'\n\n createOnEnter: (event) ->\n ENTER_KEY = 13\n title = event.delegateTarget.value.trim()\n return if event.keyCode isnt ENTER_KEY or not title\n @collection.create {title}\n @find('#new-todo').value = ''\n","var __templateData = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {\n this.compilerInfo = [4,'>= 1.0.0'];\nhelpers = this.merge(helpers, Handlebars.helpers); data = data || {};\n \n\n\n return \"\\n \\n items \\n left\\n \\n\\nClear completed \\n\";\n });\nif (typeof define === 'function' && define.amd) {\n define([], function() {\n return __templateData;\n });\n} else if (typeof module === 'object' && module && module.exports) {\n module.exports = __templateData;\n} else {\n __templateData;\n}","var __templateData = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {\n this.compilerInfo = [4,'>= 1.0.0'];\nhelpers = this.merge(helpers, Handlebars.helpers); data = data || {};\n \n\n\n return \"todos \\n \\n\";\n });\nif (typeof define === 'function' && define.amd) {\n define([], function() {\n return __templateData;\n });\n} else if (typeof module === 'object' && module && module.exports) {\n module.exports = __templateData;\n} else {\n __templateData;\n}","var __templateData = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {\n this.compilerInfo = [4,'>= 1.0.0'];\nhelpers = this.merge(helpers, Handlebars.helpers); data = data || {};\n var buffer = \"\", stack1, helper, self=this, functionType=\"function\", escapeExpression=this.escapeExpression;\n\nfunction program1(depth0,data) {\n \n \n return \" checked\";\n }\n\n buffer += \"\\n \\n \";\n if (helper = helpers.title) { stack1 = helper.call(depth0, {hash:{},data:data}); }\n else { helper = (depth0 && depth0.title); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; }\n buffer += escapeExpression(stack1)\n + \" \\n \\n
\\n \\n\";\n return buffer;\n });\nif (typeof define === 'function' && define.amd) {\n define([], function() {\n return __templateData;\n });\n} else if (typeof module === 'object' && module && module.exports) {\n module.exports = __templateData;\n} else {\n __templateData;\n}","var __templateData = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {\n this.compilerInfo = [4,'>= 1.0.0'];\nhelpers = this.merge(helpers, Handlebars.helpers); data = data || {};\n \n\n\n return \" \\nMark all as complete \\n\\n\";\n });\nif (typeof define === 'function' && define.amd) {\n define([], function() {\n return __templateData;\n });\n} else if (typeof module === 'object' && module && module.exports) {\n module.exports = __templateData;\n} else {\n __templateData;\n}","View = require './base/view'\n\nmodule.exports = class TodoView extends View\n events:\n 'click .toggle': 'toggle'\n 'dblclick label': 'edit'\n 'keyup .edit': 'save'\n 'focusout .edit': 'save'\n 'click .destroy': 'clear'\n\n listen:\n 'change model': 'render'\n\n template: require './templates/todo'\n tagName: 'li'\n\n render: ->\n super\n @toggleClass()\n\n toggleClass: ->\n isCompleted = @model.get('completed')\n @el.classList.toggle 'completed', isCompleted\n\n clear: ->\n @model.destroy()\n\n toggle: ->\n @model.toggle().save()\n\n edit: ->\n @el.classList.add 'editing'\n input = @find('.edit')\n input.focus()\n input.value = input.value;\n\n save: (event) ->\n ENTER_KEY = 13\n title = event.delegateTarget.value.trim()\n return @model.destroy() unless title\n return if event.type is 'keyup' and event.keyCode isnt ENTER_KEY\n @model.save {title}\n @el.classList.remove 'editing'\n","CollectionView = require './base/collection-view'\nTodoView = require './todo-view'\nutils = require 'lib/utils'\n\nmodule.exports = class TodosView extends CollectionView\n container: '#main'\n events:\n 'click #toggle-all': 'toggleCompleted'\n itemView: TodoView\n listSelector: '#todo-list'\n listen:\n 'all collection': 'renderCheckbox'\n 'todos:clear mediator': 'clear'\n template: require './templates/todos'\n\n render: ->\n super\n @renderCheckbox()\n\n renderCheckbox: ->\n @find('#toggle-all').checked = @collection.allAreCompleted()\n utils.toggle @el, @collection.length isnt 0\n\n toggleCompleted: (event) ->\n isChecked = event.delegateTarget.checked\n @collection.forEach (todo) -> todo.save completed: isChecked\n\n clear: ->\n @collection.getCompleted().forEach (model) ->\n model.destroy()\n"]}
\ No newline at end of file
diff --git a/examples/chaplin-brunch/public/index.html b/examples/chaplin-brunch/public/index.html
deleted file mode 100644
index d5609b7dd7..0000000000
--- a/examples/chaplin-brunch/public/index.html
+++ /dev/null
@@ -1,29 +0,0 @@
-
-
-
-
- Chaplin & Brunch • TodoMVC
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/examples/chaplin-brunch/public/vendor.js b/examples/chaplin-brunch/public/vendor.js
deleted file mode 100644
index a2e8754086..0000000000
--- a/examples/chaplin-brunch/public/vendor.js
+++ /dev/null
@@ -1,627 +0,0 @@
-(function(/*! Brunch !*/) {
- 'use strict';
-
- var globals = typeof window !== 'undefined' ? window : global;
- if (typeof globals.require === 'function') return;
-
- var modules = {};
- var cache = {};
-
- var has = function(object, name) {
- return ({}).hasOwnProperty.call(object, name);
- };
-
- var expand = function(root, name) {
- var results = [], parts, part;
- if (/^\.\.?(\/|$)/.test(name)) {
- parts = [root, name].join('/').split('/');
- } else {
- parts = name.split('/');
- }
- for (var i = 0, length = parts.length; i < length; i++) {
- part = parts[i];
- if (part === '..') {
- results.pop();
- } else if (part !== '.' && part !== '') {
- results.push(part);
- }
- }
- return results.join('/');
- };
-
- var dirname = function(path) {
- return path.split('/').slice(0, -1).join('/');
- };
-
- var localRequire = function(path) {
- return function(name) {
- var dir = dirname(path);
- var absolute = expand(dir, name);
- return globals.require(absolute, path);
- };
- };
-
- var initModule = function(name, definition) {
- var module = {id: name, exports: {}};
- cache[name] = module;
- definition(module.exports, localRequire(name), module);
- return module.exports;
- };
-
- var require = function(name, loaderPath) {
- var path = expand(name, '.');
- if (loaderPath == null) loaderPath = '/';
-
- if (has(cache, path)) return cache[path].exports;
- if (has(modules, path)) return initModule(path, modules[path]);
-
- var dirIndex = expand(path, './index');
- if (has(cache, dirIndex)) return cache[dirIndex].exports;
- if (has(modules, dirIndex)) return initModule(dirIndex, modules[dirIndex]);
-
- throw new Error('Cannot find module "' + name + '" from '+ '"' + loaderPath + '"');
- };
-
- var define = function(bundle, fn) {
- if (typeof bundle === 'object') {
- for (var key in bundle) {
- if (has(bundle, key)) {
- modules[key] = bundle[key];
- }
- }
- } else {
- modules[bundle] = fn;
- }
- };
-
- var list = function() {
- var result = [];
- for (var item in modules) {
- if (has(modules, item)) {
- result.push(item);
- }
- }
- return result;
- };
-
- globals.require = require;
- globals.require.define = define;
- globals.require.register = define;
- globals.require.list = list;
- globals.require.brunch = true;
-})();
-Backbone.View = Backbone.NativeView;
-
-/*!
-
- handlebars v1.3.0
-
-Copyright (C) 2011 by Yehuda Katz
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
-
-@license
-*/
-/* exported Handlebars */
-var Handlebars = (function() {
-// handlebars/safe-string.js
-var __module3__ = (function() {
- "use strict";
- var __exports__;
- // Build out our basic SafeString type
- function SafeString(string) {
- this.string = string;
- }
-
- SafeString.prototype.toString = function() {
- return "" + this.string;
- };
-
- __exports__ = SafeString;
- return __exports__;
-})();
-
-// handlebars/utils.js
-var __module2__ = (function(__dependency1__) {
- "use strict";
- var __exports__ = {};
- /*jshint -W004 */
- var SafeString = __dependency1__;
-
- var escape = {
- "&": "&",
- "<": "<",
- ">": ">",
- '"': """,
- "'": "'",
- "`": "`"
- };
-
- var badChars = /[&<>"'`]/g;
- var possible = /[&<>"'`]/;
-
- function escapeChar(chr) {
- return escape[chr] || "&";
- }
-
- function extend(obj, value) {
- for(var key in value) {
- if(Object.prototype.hasOwnProperty.call(value, key)) {
- obj[key] = value[key];
- }
- }
- }
-
- __exports__.extend = extend;var toString = Object.prototype.toString;
- __exports__.toString = toString;
- // Sourced from lodash
- // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt
- var isFunction = function(value) {
- return typeof value === 'function';
- };
- // fallback for older versions of Chrome and Safari
- if (isFunction(/x/)) {
- isFunction = function(value) {
- return typeof value === 'function' && toString.call(value) === '[object Function]';
- };
- }
- var isFunction;
- __exports__.isFunction = isFunction;
- var isArray = Array.isArray || function(value) {
- return (value && typeof value === 'object') ? toString.call(value) === '[object Array]' : false;
- };
- __exports__.isArray = isArray;
-
- function escapeExpression(string) {
- // don't escape SafeStrings, since they're already safe
- if (string instanceof SafeString) {
- return string.toString();
- } else if (!string && string !== 0) {
- return "";
- }
-
- // Force a string conversion as this will be done by the append regardless and
- // the regex test will do this transparently behind the scenes, causing issues if
- // an object's to string has escaped characters in it.
- string = "" + string;
-
- if(!possible.test(string)) { return string; }
- return string.replace(badChars, escapeChar);
- }
-
- __exports__.escapeExpression = escapeExpression;function isEmpty(value) {
- if (!value && value !== 0) {
- return true;
- } else if (isArray(value) && value.length === 0) {
- return true;
- } else {
- return false;
- }
- }
-
- __exports__.isEmpty = isEmpty;
- return __exports__;
-})(__module3__);
-
-// handlebars/exception.js
-var __module4__ = (function() {
- "use strict";
- var __exports__;
-
- var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
-
- function Exception(message, node) {
- var line;
- if (node && node.firstLine) {
- line = node.firstLine;
-
- message += ' - ' + line + ':' + node.firstColumn;
- }
-
- var tmp = Error.prototype.constructor.call(this, message);
-
- // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
- for (var idx = 0; idx < errorProps.length; idx++) {
- this[errorProps[idx]] = tmp[errorProps[idx]];
- }
-
- if (line) {
- this.lineNumber = line;
- this.column = node.firstColumn;
- }
- }
-
- Exception.prototype = new Error();
-
- __exports__ = Exception;
- return __exports__;
-})();
-
-// handlebars/base.js
-var __module1__ = (function(__dependency1__, __dependency2__) {
- "use strict";
- var __exports__ = {};
- var Utils = __dependency1__;
- var Exception = __dependency2__;
-
- var VERSION = "1.3.0";
- __exports__.VERSION = VERSION;var COMPILER_REVISION = 4;
- __exports__.COMPILER_REVISION = COMPILER_REVISION;
- var REVISION_CHANGES = {
- 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
- 2: '== 1.0.0-rc.3',
- 3: '== 1.0.0-rc.4',
- 4: '>= 1.0.0'
- };
- __exports__.REVISION_CHANGES = REVISION_CHANGES;
- var isArray = Utils.isArray,
- isFunction = Utils.isFunction,
- toString = Utils.toString,
- objectType = '[object Object]';
-
- function HandlebarsEnvironment(helpers, partials) {
- this.helpers = helpers || {};
- this.partials = partials || {};
-
- registerDefaultHelpers(this);
- }
-
- __exports__.HandlebarsEnvironment = HandlebarsEnvironment;HandlebarsEnvironment.prototype = {
- constructor: HandlebarsEnvironment,
-
- logger: logger,
- log: log,
-
- registerHelper: function(name, fn, inverse) {
- if (toString.call(name) === objectType) {
- if (inverse || fn) { throw new Exception('Arg not supported with multiple helpers'); }
- Utils.extend(this.helpers, name);
- } else {
- if (inverse) { fn.not = inverse; }
- this.helpers[name] = fn;
- }
- },
-
- registerPartial: function(name, str) {
- if (toString.call(name) === objectType) {
- Utils.extend(this.partials, name);
- } else {
- this.partials[name] = str;
- }
- }
- };
-
- function registerDefaultHelpers(instance) {
- instance.registerHelper('helperMissing', function(arg) {
- if(arguments.length === 2) {
- return undefined;
- } else {
- throw new Exception("Missing helper: '" + arg + "'");
- }
- });
-
- instance.registerHelper('blockHelperMissing', function(context, options) {
- var inverse = options.inverse || function() {}, fn = options.fn;
-
- if (isFunction(context)) { context = context.call(this); }
-
- if(context === true) {
- return fn(this);
- } else if(context === false || context == null) {
- return inverse(this);
- } else if (isArray(context)) {
- if(context.length > 0) {
- return instance.helpers.each(context, options);
- } else {
- return inverse(this);
- }
- } else {
- return fn(context);
- }
- });
-
- instance.registerHelper('each', function(context, options) {
- var fn = options.fn, inverse = options.inverse;
- var i = 0, ret = "", data;
-
- if (isFunction(context)) { context = context.call(this); }
-
- if (options.data) {
- data = createFrame(options.data);
- }
-
- if(context && typeof context === 'object') {
- if (isArray(context)) {
- for(var j = context.length; i\": \">\",\n '\"': \""\",\n \"'\": \"'\",\n \"`\": \"`\"\n };\n\n var badChars = /[&<>\"'`]/g;\n var possible = /[&<>\"'`]/;\n\n function escapeChar(chr) {\n return escape[chr] || \"&\";\n }\n\n function extend(obj, value) {\n for(var key in value) {\n if(Object.prototype.hasOwnProperty.call(value, key)) {\n obj[key] = value[key];\n }\n }\n }\n\n __exports__.extend = extend;var toString = Object.prototype.toString;\n __exports__.toString = toString;\n // Sourced from lodash\n // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt\n var isFunction = function(value) {\n return typeof value === 'function';\n };\n // fallback for older versions of Chrome and Safari\n if (isFunction(/x/)) {\n isFunction = function(value) {\n return typeof value === 'function' && toString.call(value) === '[object Function]';\n };\n }\n var isFunction;\n __exports__.isFunction = isFunction;\n var isArray = Array.isArray || function(value) {\n return (value && typeof value === 'object') ? toString.call(value) === '[object Array]' : false;\n };\n __exports__.isArray = isArray;\n\n function escapeExpression(string) {\n // don't escape SafeStrings, since they're already safe\n if (string instanceof SafeString) {\n return string.toString();\n } else if (!string && string !== 0) {\n return \"\";\n }\n\n // Force a string conversion as this will be done by the append regardless and\n // the regex test will do this transparently behind the scenes, causing issues if\n // an object's to string has escaped characters in it.\n string = \"\" + string;\n\n if(!possible.test(string)) { return string; }\n return string.replace(badChars, escapeChar);\n }\n\n __exports__.escapeExpression = escapeExpression;function isEmpty(value) {\n if (!value && value !== 0) {\n return true;\n } else if (isArray(value) && value.length === 0) {\n return true;\n } else {\n return false;\n }\n }\n\n __exports__.isEmpty = isEmpty;\n return __exports__;\n})(__module3__);\n\n// handlebars/exception.js\nvar __module4__ = (function() {\n \"use strict\";\n var __exports__;\n\n var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];\n\n function Exception(message, node) {\n var line;\n if (node && node.firstLine) {\n line = node.firstLine;\n\n message += ' - ' + line + ':' + node.firstColumn;\n }\n\n var tmp = Error.prototype.constructor.call(this, message);\n\n // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.\n for (var idx = 0; idx < errorProps.length; idx++) {\n this[errorProps[idx]] = tmp[errorProps[idx]];\n }\n\n if (line) {\n this.lineNumber = line;\n this.column = node.firstColumn;\n }\n }\n\n Exception.prototype = new Error();\n\n __exports__ = Exception;\n return __exports__;\n})();\n\n// handlebars/base.js\nvar __module1__ = (function(__dependency1__, __dependency2__) {\n \"use strict\";\n var __exports__ = {};\n var Utils = __dependency1__;\n var Exception = __dependency2__;\n\n var VERSION = \"1.3.0\";\n __exports__.VERSION = VERSION;var COMPILER_REVISION = 4;\n __exports__.COMPILER_REVISION = COMPILER_REVISION;\n var REVISION_CHANGES = {\n 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it\n 2: '== 1.0.0-rc.3',\n 3: '== 1.0.0-rc.4',\n 4: '>= 1.0.0'\n };\n __exports__.REVISION_CHANGES = REVISION_CHANGES;\n var isArray = Utils.isArray,\n isFunction = Utils.isFunction,\n toString = Utils.toString,\n objectType = '[object Object]';\n\n function HandlebarsEnvironment(helpers, partials) {\n this.helpers = helpers || {};\n this.partials = partials || {};\n\n registerDefaultHelpers(this);\n }\n\n __exports__.HandlebarsEnvironment = HandlebarsEnvironment;HandlebarsEnvironment.prototype = {\n constructor: HandlebarsEnvironment,\n\n logger: logger,\n log: log,\n\n registerHelper: function(name, fn, inverse) {\n if (toString.call(name) === objectType) {\n if (inverse || fn) { throw new Exception('Arg not supported with multiple helpers'); }\n Utils.extend(this.helpers, name);\n } else {\n if (inverse) { fn.not = inverse; }\n this.helpers[name] = fn;\n }\n },\n\n registerPartial: function(name, str) {\n if (toString.call(name) === objectType) {\n Utils.extend(this.partials, name);\n } else {\n this.partials[name] = str;\n }\n }\n };\n\n function registerDefaultHelpers(instance) {\n instance.registerHelper('helperMissing', function(arg) {\n if(arguments.length === 2) {\n return undefined;\n } else {\n throw new Exception(\"Missing helper: '\" + arg + \"'\");\n }\n });\n\n instance.registerHelper('blockHelperMissing', function(context, options) {\n var inverse = options.inverse || function() {}, fn = options.fn;\n\n if (isFunction(context)) { context = context.call(this); }\n\n if(context === true) {\n return fn(this);\n } else if(context === false || context == null) {\n return inverse(this);\n } else if (isArray(context)) {\n if(context.length > 0) {\n return instance.helpers.each(context, options);\n } else {\n return inverse(this);\n }\n } else {\n return fn(context);\n }\n });\n\n instance.registerHelper('each', function(context, options) {\n var fn = options.fn, inverse = options.inverse;\n var i = 0, ret = \"\", data;\n\n if (isFunction(context)) { context = context.call(this); }\n\n if (options.data) {\n data = createFrame(options.data);\n }\n\n if(context && typeof context === 'object') {\n if (isArray(context)) {\n for(var j = context.length; i Chaplin is an architecture for JavaScript applications using the Backbone.js library. Chaplin addresses Backbone’s limitations by providing a lightweight and flexible structure that features well-proven design patterns and best practices.
-
-In this case, Backbone is replaced with [Exoskeleton](http://exosjs.com),
-faster and leaner Backbone without dependencies on jQuery and underscore.
-
-> _[Chaplin - chaplinjs.org](http://chaplinjs.org)_
-
-
-## Learning Chaplin
-
-The [Chaplin website](http://chaplinjs.org) is a great resource for getting started.
-
-Here are some links you may find helpful:
-
-* [Getting Started](https://github.com/chaplinjs/chaplin/blob/master/docs/getting_started.md)
-* [Documentation](https://github.com/chaplinjs/chaplin/tree/master/docs)
-* [API Reference](https://github.com/chaplinjs/chaplin/tree/master/docs#api-docs)
-* [Annotated Source Code](http://chaplinjs.org/annotated/chaplin.html)
-* [Applications built with Chaplin](https://github.com/chaplinjs/chaplin/wiki/Projects-and-companies-using-Chaplin)
-* [Cookbook](https://github.com/chaplinjs/chaplin/wiki/Cookbook)
-* [Chaplin on GitHub](https://github.com/chaplinjs)
-
-Articles and guides from the community:
-
-* [JavaScript MVC frameworks: A Comparison of Marionette and Chaplin](http://9elements.com/io/index.php/comparison-of-marionette-and-chaplin/)
-
-Get help from other Chaplin users:
-
-* [Chaplin on StackOverflow](http://stackoverflow.com/questions/tagged/chaplinjs)
-* [Chaplin on Twitter](http://twitter.com/chaplinjs)
-
-_If you have other helpful links to share, or find any of the links above no longer work, please [let us know](https://github.com/tastejs/todomvc/issues)._
-
-
-## Running
-
-If you haven't already installed [Brunch](http://brunch.io), run:
-
- npm install -g brunch
-
-Once you have Brunch, install this application's dependencies:
-
- # from examples/chaplin-brunch
- npm install & bower install
-
-To build the app, run:
-
- # from examples/chaplin-brunch
- brunch build
-
-To watch for changes and re-compile:
-
- # from examples/chaplin-brunch
- brunch watch
-
-Open `public/index.html` in your browser to see it in action!
-
-
-## Credit
-
-This TodoMVC application was created by [@paulmillr](http://paulmillr.com).
diff --git a/examples/chaplin-brunch/vendor/vendor.js b/examples/chaplin-brunch/vendor/vendor.js
deleted file mode 100644
index 04728944b5..0000000000
--- a/examples/chaplin-brunch/vendor/vendor.js
+++ /dev/null
@@ -1 +0,0 @@
-Backbone.View = Backbone.NativeView;
diff --git a/examples/flight/.gitignore b/examples/flight/.gitignore
deleted file mode 100644
index 21d0fdfe11..0000000000
--- a/examples/flight/.gitignore
+++ /dev/null
@@ -1,41 +0,0 @@
-node_modules/.bin/
-
-node_modules/depot/
-!node_modules/depot/depot.js
-
-node_modules/es5-shim/
-!node_modules/es5-shim/es5-shim.js
-!node_modules/es5-shim/es5-sham.js
-
-node_modules/jquery/
-!node_modules/jquery/dist
-node_modules/jquery/dist/
-!node_modules/jquery/dist/jquery.js
-
-node_modules/flight/
-!node_modules/flight/lib
-
-node_modules/requirejs/
-!node_modules/requirejs/require.js
-
-node_modules/requirejs-text/
-!node_modules/requirejs-text/text.js
-
-node_modules/todomvc-app-css/
-!node_modules/todomvc-app-css/index.css
-
-node_modules/todomvc-common/
-!node_modules/todomvc-common/base.css
-!node_modules/todomvc-common/base.js
-
-
-node_modules/karma/
-node_modules/karma-chrome-launcher/
-node_modules/karma-firefox-launcher/
-node_modules/karma-ie-launcher/
-node_modules/karma-jasmine/
-node_modules/karma-phantomjs-launcher/
-node_modules/jasmine-jquery/
-node_modules/jasmine-flight/
-node_modules/karma-safari-launcher/
-node_modules/karma-requirejs/
diff --git a/examples/flight/.jshintrc b/examples/flight/.jshintrc
deleted file mode 100644
index db0b04df48..0000000000
--- a/examples/flight/.jshintrc
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "node": true,
- "browser": true,
- "esnext": true,
- "bitwise": true,
- "camelcase": true,
- "curly": true,
- "eqeqeq": true,
- "immed": true,
- "indent": 4,
- "latedef": true,
- "newcap": true,
- "noarg": true,
- "quotmark": "single",
- "regexp": true,
- "undef": true,
- "unused": true,
- "strict": true,
- "trailing": true,
- "smarttabs": true,
- "white": true,
- "validthis": true
-}
diff --git a/examples/flight/app/js/data/stats.js b/examples/flight/app/js/data/stats.js
deleted file mode 100644
index 1a8a0437a5..0000000000
--- a/examples/flight/app/js/data/stats.js
+++ /dev/null
@@ -1,39 +0,0 @@
-/*global define */
-'use strict';
-
-define([
- 'flight/lib/component',
- 'app/store'
-], function (defineComponent, dataStore) {
- function stats() {
- this.attributes({
- dataStore: dataStore
- });
-
- this.recount = function () {
- var todos = this.attr.dataStore.all();
- var all = todos.length;
- var remaining = todos.reduce(function (memo, each) {
- return memo += each.completed ? 0 : 1;
- }, 0);
-
- this.trigger('dataStatsCounted', {
- all: all,
- remaining: remaining,
- completed: all - remaining,
- filter: localStorage.getItem('filter') || ''
- });
- };
-
- this.after('initialize', function () {
- this.on(document, 'dataTodosLoaded', this.recount);
- this.on(document, 'dataTodoAdded', this.recount);
- this.on(document, 'dataTodoRemoved', this.recount);
- this.on(document, 'dataTodoToggled', this.recount);
- this.on(document, 'dataClearedCompleted', this.recount);
- this.on(document, 'dataTodoToggledAll', this.recount);
- });
- }
-
- return defineComponent(stats);
-});
diff --git a/examples/flight/app/js/data/todos.js b/examples/flight/app/js/data/todos.js
deleted file mode 100644
index 973a3d1942..0000000000
--- a/examples/flight/app/js/data/todos.js
+++ /dev/null
@@ -1,102 +0,0 @@
-/*global define */
-'use strict';
-
-define([
- 'flight/lib/component',
- 'app/store'
-], function (defineComponent, dataStore) {
- function todos() {
- var filter;
- this.attributes({
- dataStore: dataStore
- });
-
- this.add = function (e, data) {
- var todo = this.attr.dataStore.save({
- title: data.title,
- completed: false
- });
-
- this.trigger('dataTodoAdded', { todo: todo, filter: filter });
- };
-
- this.remove = function (e, data) {
- var todo = this.attr.dataStore.destroy(data.id);
-
- this.trigger('dataTodoRemoved', todo);
- };
-
- this.load = function () {
- var todos;
-
- filter = localStorage.getItem('filter');
- todos = this.find();
- this.trigger('dataTodosLoaded', { todos: todos });
- };
-
- this.update = function (e, data) {
- this.attr.dataStore.save(data);
- };
-
- this.toggleCompleted = function (e, data) {
- var eventType;
- var todo = this.attr.dataStore.get(data.id);
-
- todo.completed = !todo.completed;
- this.attr.dataStore.save(todo);
-
- eventType = filter ? 'dataTodoRemoved' : 'dataTodoToggled';
-
- this.trigger(eventType, todo);
- };
-
- this.toggleAllCompleted = function (e, data) {
- this.attr.dataStore.updateAll({ completed: data.completed });
- this.trigger('dataTodoToggledAll', { todos: this.find(filter) });
- };
-
- this.filter = function (e, data) {
- var todos;
-
- localStorage.setItem('filter', data.filter);
- filter = data.filter;
- todos = this.find();
-
- this.trigger('dataTodosFiltered', { todos: todos });
- };
-
- this.find = function () {
- var todos;
-
- if (filter) {
- todos = this.attr.dataStore.find(function (each) {
- return (typeof each[filter] !== 'undefined') ? each.completed : !each.completed;
- });
- } else {
- todos = this.attr.dataStore.all();
- }
-
- return todos;
- };
-
- this.clearCompleted = function () {
- this.attr.dataStore.destroyAll({ completed: true });
-
- this.trigger('uiFilterRequested', { filter: filter });
- this.trigger('dataClearedCompleted');
- };
-
- this.after('initialize', function () {
- this.on(document, 'uiAddRequested', this.add);
- this.on(document, 'uiUpdateRequested', this.update);
- this.on(document, 'uiRemoveRequested', this.remove);
- this.on(document, 'uiLoadRequested', this.load);
- this.on(document, 'uiToggleRequested', this.toggleCompleted);
- this.on(document, 'uiToggleAllRequested', this.toggleAllCompleted);
- this.on(document, 'uiClearRequested', this.clearCompleted);
- this.on(document, 'uiFilterRequested', this.filter);
- });
- }
-
- return defineComponent(todos);
-});
diff --git a/examples/flight/app/js/main.js b/examples/flight/app/js/main.js
deleted file mode 100644
index 49f8fe6d19..0000000000
--- a/examples/flight/app/js/main.js
+++ /dev/null
@@ -1,31 +0,0 @@
-/*global DEBUG */
-'use strict';
-
-require.config({
- baseUrl: './',
- paths: {
- jquery: 'node_modules/jquery/dist/jquery',
- es5shim: 'node_modules/es5-shim/es5-shim',
- es5sham: 'node_modules/es5-shim/es5-sham',
- text: 'node_modules/requirejs-text/text',
- flight: 'node_modules/flight',
- depot: 'node_modules/depot/depot',
- app: 'app/js',
- templates: 'app/templates',
- ui: 'app/js/ui',
- data: 'app/js/data',
- },
- shim: {
- 'app/page/app': {
- deps: ['jquery', 'es5shim', 'es5sham']
- }
- }
-});
-
-require(['flight/lib/debug'], function (debug) {
- debug.enable(true);
- DEBUG.events.logAll();
- require(['app/page/app'],function(App){
- App.initialize();
- });
-});
diff --git a/examples/flight/app/js/page/app.js b/examples/flight/app/js/page/app.js
deleted file mode 100644
index 47e43d8583..0000000000
--- a/examples/flight/app/js/page/app.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/*global define */
-'use strict';
-
-define([
- 'data/todos',
- 'data/stats',
- 'ui/new_item',
- 'ui/todo_list',
- 'ui/stats',
- 'ui/main_selector',
- 'ui/toggle_all'
-], function (TodosData, StatsData, NewItemUI, TodoListUI, StatsUI, MainSelectorUI, ToggleAllUI) {
- var initialize = function () {
- StatsData.attachTo(document);
- TodosData.attachTo(document);
- NewItemUI.attachTo('.new-todo');
- MainSelectorUI.attachTo('.main');
- StatsUI.attachTo('.footer');
- ToggleAllUI.attachTo('.toggle-all');
- TodoListUI.attachTo('.todo-list');
- };
-
- return {
- initialize: initialize
- };
-});
diff --git a/examples/flight/app/js/store.js b/examples/flight/app/js/store.js
deleted file mode 100644
index e9ab55ddae..0000000000
--- a/examples/flight/app/js/store.js
+++ /dev/null
@@ -1,9 +0,0 @@
-/*global define */
-
-'use strict';
-
-define([
- 'depot'
-], function (depot) {
- return depot('todos', { idAttribute: 'id' });
-});
diff --git a/examples/flight/app/js/ui/main_selector.js b/examples/flight/app/js/ui/main_selector.js
deleted file mode 100644
index 12f7e2ae08..0000000000
--- a/examples/flight/app/js/ui/main_selector.js
+++ /dev/null
@@ -1,20 +0,0 @@
-/*global define */
-'use strict';
-
-define([
- 'flight/lib/component'
-], function (defineComponent) {
- function mainSelector() {
- this.toggle = function (e, data) {
- var toggle = data.all > 0;
- this.$node.toggle(toggle);
- };
-
- this.after('initialize', function () {
- this.$node.hide();
- this.on(document, 'dataStatsCounted', this.toggle);
- });
- }
-
- return defineComponent(mainSelector);
-});
diff --git a/examples/flight/app/js/ui/new_item.js b/examples/flight/app/js/ui/new_item.js
deleted file mode 100644
index 0a9554c880..0000000000
--- a/examples/flight/app/js/ui/new_item.js
+++ /dev/null
@@ -1,29 +0,0 @@
-/*global define */
-'use strict';
-
-define([
- 'flight/lib/component'
-], function (defineComponent) {
- function newItem() {
- var ENTER_KEY = 13;
-
- this.createOnEnter = function (e) {
- if (e.which !== ENTER_KEY ||
- !this.$node.val().trim()) {
- return;
- }
-
- this.trigger('uiAddRequested', {
- title: this.$node.val().trim()
- });
-
- this.$node.val('');
- };
-
- this.after('initialize', function () {
- this.on('keydown', this.createOnEnter);
- });
- }
-
- return defineComponent(newItem);
-});
diff --git a/examples/flight/app/js/ui/stats.js b/examples/flight/app/js/ui/stats.js
deleted file mode 100644
index 90ee824690..0000000000
--- a/examples/flight/app/js/ui/stats.js
+++ /dev/null
@@ -1,37 +0,0 @@
-/*global define */
-'use strict';
-
-define([
- 'flight/lib/component',
- './with_filters',
- 'text!templates/stats.html',
- 'app/utils'
-], function (defineComponent, withFilters, statsTmpl, utils) {
- function stats() {
- var template = utils.tmpl(statsTmpl);
-
- this.attributes({
- clearCompletedSelector: '.clear-completed'
- });
-
- this.render = function (e, data) {
- var toggle = data.all > 0;
-
- this.$node.html(template(data));
- this.$node.toggle(toggle);
- this.markSelected(data.filter);
- };
-
- this.clearCompleted = function () {
- this.trigger('uiClearRequested');
- };
-
- this.after('initialize', function () {
- this.$node.hide();
- this.on(document, 'dataStatsCounted', this.render);
- this.on('click', { 'clearCompletedSelector': this.clearCompleted });
- });
- }
-
- return defineComponent(stats, withFilters);
-});
diff --git a/examples/flight/app/js/ui/todo_list.js b/examples/flight/app/js/ui/todo_list.js
deleted file mode 100644
index 897b141c6c..0000000000
--- a/examples/flight/app/js/ui/todo_list.js
+++ /dev/null
@@ -1,124 +0,0 @@
-/*global define, $ */
-'use strict';
-
-define([
- 'flight/lib/component',
- 'text!templates/todo.html',
- 'app/utils'
-], function (defineComponent, todoTmpl, utils) {
- function todoList() {
- var ENTER_KEY = 'Enter';
- var ESCAPE_KEY = 'Escape';
- var template = utils.tmpl(todoTmpl);
-
- this.attributes({
- destroySelector: 'button.destroy',
- toggleSelector: 'input.toggle',
- labelSelector: 'label',
- editSelector: '.edit'
- });
-
- this.renderAll = function (e, data) {
- this.$node.html('');
- data.todos.forEach(function (each) {
- this.render(e, { todo: each });
- }, this);
- };
-
- this.render = function (e, data) {
- if (e.type === 'dataTodoAdded' && data.filter === 'completed') {
- return;
- }
-
- this.$node.append(template(data.todo));
- };
-
- this.edit = function (e, data) {
- var $todoEl = $(data.el).parents('li');
- var $inputEl = $todoEl.find('input');
- var value = $todoEl.find('label').text();
-
- $todoEl.addClass('editing');
- $inputEl.val(value);
- this.select('editSelector').focus();
- };
-
- this.requestUpdate = function (e) {
- var $inputEl = $(e.currentTarget);
- var $todoEl = $inputEl.parents('li');
- var value = $inputEl.val().trim();
- var id = $todoEl.attr('id');
-
- if (!$todoEl.hasClass('editing')) {
- return;
- }
-
- $todoEl.removeClass('editing');
-
- if (value) {
- $todoEl.find('label').html(value);
- this.trigger('uiUpdateRequested', { id: id, title: value });
- } else {
- this.trigger('uiRemoveRequested', { id: id });
- }
- };
-
- this.requestCancel = function (e) {
- var $inputEl = $(e.currentTarget);
- var $todoEl = $inputEl.parents('li');
-
- $todoEl.removeClass('editing');
- $inputEl.val('');
-
- this.trigger('uiUpdateRequested');
- };
-
- this.requestUpdateOrCancelEvent = function (e, data) {
- if (e.key === ENTER_KEY) {
- this.requestUpdate(e, data);
- } else if (e.key === ESCAPE_KEY) {
- this.requestCancel(e, data);
- }
- };
-
- this.requestRemove = function (e, data) {
- var id = $(data.el).attr('id').split('_')[1];
- this.trigger('uiRemoveRequested', { id: id });
- };
-
- this.remove = function (e, data) {
- var $todoEl = this.$node.find('#' + data.id);
- $todoEl.remove();
- };
-
- this.toggle = function (e, data) {
- var $todoEl = $(data.el).parents('li');
-
- $todoEl.toggleClass('completed');
- this.trigger('uiToggleRequested', { id: $todoEl.attr('id') });
- };
-
- this.after('initialize', function () {
- this.on(document, 'dataTodoAdded', this.render);
- this.on(document, 'dataTodosLoaded', this.renderAll);
- this.on(document, 'dataTodosFiltered', this.renderAll);
- this.on(document, 'dataTodoToggledAll', this.renderAll);
- this.on(document, 'dataTodoRemoved', this.remove);
-
- this.on('click', { 'destroySelector': this.requestRemove });
- this.on('click', { 'toggleSelector': this.toggle });
- this.on('dblclick', { 'labelSelector': this.edit });
-
- this.$node.on('blur', '.edit', this.requestUpdate.bind(this));
- this.$node.on('keydown', '.edit', this.requestUpdateOrCancelEvent.bind(this));
-
- // these don't work
- // this.on(this.attr.editSelector, 'blur', this.requestUpdate);
- // this.on('blur', { 'editSelector': this.requestUpdate });
-
- this.trigger('uiLoadRequested');
- });
- }
-
- return defineComponent(todoList);
-});
diff --git a/examples/flight/app/js/ui/toggle_all.js b/examples/flight/app/js/ui/toggle_all.js
deleted file mode 100644
index d415b1114b..0000000000
--- a/examples/flight/app/js/ui/toggle_all.js
+++ /dev/null
@@ -1,25 +0,0 @@
-/*global define */
-'use strict';
-
-define([
- 'flight/lib/component'
-], function (defineComponent) {
- function toggleAll() {
- this.toggleAllComplete = function () {
- this.trigger('uiToggleAllRequested', {
- completed: this.$node.is(':checked')
- });
- };
-
- this.toggleCheckbox = function (e, data) {
- this.node.checked = !data.remaining;
- };
-
- this.after('initialize', function () {
- this.on('click', this.toggleAllComplete);
- this.on(document, 'dataStatsCounted', this.toggleCheckbox);
- });
- }
-
- return defineComponent(toggleAll);
-});
diff --git a/examples/flight/app/js/ui/with_filters.js b/examples/flight/app/js/ui/with_filters.js
deleted file mode 100644
index a8823422c0..0000000000
--- a/examples/flight/app/js/ui/with_filters.js
+++ /dev/null
@@ -1,26 +0,0 @@
-/*global define, $ */
-'use strict';
-
-define(function () {
- return function withFilters() {
- this.attributes({
- filterSelector: '.filters a'
- });
-
- this.chooseFilter = function (e, data) {
- var filter = data.el.hash.slice(2);
-
- this.select('filterSelector').removeClass('selected');
- $(data.el).addClass('selected');
- this.trigger('uiFilterRequested', { filter: filter });
- };
-
- this.markSelected = function (filter) {
- this.$node.find('[href="#/' + filter + '"]').addClass('selected');
- };
-
- this.after('initialize', function () {
- this.on('click', { filterSelector: this.chooseFilter });
- });
- };
-});
diff --git a/examples/flight/app/js/utils.js b/examples/flight/app/js/utils.js
deleted file mode 100644
index fc1101bce0..0000000000
--- a/examples/flight/app/js/utils.js
+++ /dev/null
@@ -1,134 +0,0 @@
-/*global define */
-'use strict';
-
-// tmpl function scooped from underscore.
-// http://documentcloud.github.com/underscore/#template
-define(function () {
- var _ = {};
-
- // List of HTML entities for escaping.
- var entityMap = {
- escape: {
- '&': '&',
- '<': '<',
- '>': '>',
- '"': '"',
- /*jshint quotmark:false */
- "'": ''',
- '/': '/'
- }
- };
-
- var escapeKeys = '&<>"\'/';
- var unescapeKeys = '&|<|>|"|'|/';
-
- // Regexes containing the keys and values listed immediately above.
- var entityRegexes = {
- escape: new RegExp('[' + escapeKeys + ']', 'g'),
- unescape: new RegExp('(' + unescapeKeys + ')', 'g')
- };
-
- // Functions for escaping and unescaping strings to/from HTML interpolation.
- ['escape', 'unescape'].forEach(function (method) {
- _[method] = function (string) {
- if (string === null || string === undefined) {
- return '';
- }
-
- return ('' + string).replace(entityRegexes[method], function (match) {
- return entityMap[method][match];
- });
- };
- });
-
- var settings = {
- evaluate: /<%([\s\S]+?)%>/g,
- interpolate: /<%=([\s\S]+?)%>/g,
- escape: /<%-([\s\S]+?)%>/g
- };
-
- var noMatch = /(.)^/;
- var escapes = {
- /*jshint quotmark:false */
- "'": "'",
- '\\': '\\',
- '\r': 'r',
- '\n': 'n',
- '\t': 't',
- '\u2028': 'u2028',
- '\u2029': 'u2029'
- };
-
- var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
-
- // JavaScript micro-templating, similar to John Resig's implementation.
- // Underscore templating handles arbitrary delimiters, preserves whitespace,
- // and correctly escapes quotes within interpolated code.
- var template = function (text, data) {
- var render;
-
- // Combine delimiters into one regular expression via alternation.
- var matcher = new RegExp([
- (settings.escape || noMatch).source,
- (settings.interpolate || noMatch).source,
- (settings.evaluate || noMatch).source
- ].join('|') + '|$', 'g');
-
- // Compile the template source, escaping string literals appropriately.
- var index = 0;
- var source = "__p+='";
- text.replace(matcher, function (match, escape, interpolate, evaluate, offset) {
- source += text.slice(index, offset)
- .replace(escaper, function (match) {
- return '\\' + escapes[match];
- });
-
- if (escape) {
- source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
- }
- if (interpolate) {
- source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
- }
- if (evaluate) {
- source += "';\n" + evaluate + "\n__p+='";
- }
- index = offset + match.length;
- return match;
- });
- source += "';\n";
-
- // If a variable is not specified, place data values in local scope.
- if (!settings.variable) {
- source = 'with(obj||{}){\n' + source + '}\n';
- }
-
- source = "var __t,__p='',__j=Array.prototype.join," +
- "print=function(){__p+=__j.call(arguments,'');};\n" +
- source + "return __p;\n";
-
- try {
- /*jshint evil:true */
- render = new Function(settings.variable || 'obj', '_', source);
- } catch (err) {
- err.source = source;
- throw err;
- }
-
- if (data) {
- return render(data, _);
- }
-
- var template = function (data) {
- return render.call(this, data, _);
- };
-
- // Provide the compiled function source as a convenience for precompilation.
- template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
-
- return template;
- };
-
- return {
- tmpl: template
- };
-});
diff --git a/examples/flight/app/templates/stats.html b/examples/flight/app/templates/stats.html
deleted file mode 100644
index 57689f4622..0000000000
--- a/examples/flight/app/templates/stats.html
+++ /dev/null
@@ -1,17 +0,0 @@
-
- <%= remaining %> <%= remaining == 1 ? 'item' : 'items' %> left
-
-
-<% if (completed) { %>
-Clear completed
-<% } %>
diff --git a/examples/flight/app/templates/todo.html b/examples/flight/app/templates/todo.html
deleted file mode 100644
index 66d0b03ec3..0000000000
--- a/examples/flight/app/templates/todo.html
+++ /dev/null
@@ -1,8 +0,0 @@
-
-
- >
- <%- title %>
-
-
-
-
diff --git a/examples/flight/index.html b/examples/flight/index.html
deleted file mode 100644
index 2e151c12bd..0000000000
--- a/examples/flight/index.html
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
-
-
- Flight • Todo
-
-
-
-
-
-
-
-
-
-
diff --git a/examples/flight/karma.conf.js b/examples/flight/karma.conf.js
deleted file mode 100644
index 11ba3f040c..0000000000
--- a/examples/flight/karma.conf.js
+++ /dev/null
@@ -1,86 +0,0 @@
-// Karma configuration file
-//
-// For all available config options and default values, see:
-// https://github.com/karma-runner/karma/blob/stable/lib/config.js#L54
-
-module.exports = function (config) {
- 'use strict';
-
- config.set({
- // base path, that will be used to resolve files and exclude
- basePath: '',
-
- frameworks: ['jasmine'],
-
- // list of files / patterns to load in the browser
- files: [
- // loaded without require
- 'node_modules/es5-shim/es5-shim.js',
- 'node_modules/es5-shim/es5-sham.js',
-
- 'node_modules/jquery/dist/jquery.js',
- 'node_modules/jasmine-jquery/lib/jasmine-jquery.js',
- 'node_modules/jasmine-flight/lib/jasmine-flight.js',
-
- // hack to load RequireJS after the shim libs
- 'node_modules/requirejs/require.js',
- 'node_modules/karma-requirejs/lib/adapter.js',
-
- // loaded with require
- { pattern: 'node_modules/flight/lib/*.js', included: false },
- { pattern: 'node_modules/flight/index.js', included: false },
- { pattern: 'node_modules/depot/depot.js', included: false },
- { pattern: 'node_modules/requirejs-text/text.js', included: false },
- { pattern: 'app/**/*.js', included: false },
- { pattern: 'app/**/*.html', included: false },
- { pattern: 'test/spec/**/*_spec.js', included: false },
- { pattern: 'test/fixture/*.html', included: false },
-
- // Entry point for karma.
- 'test/test-main.js',
-
- { pattern: 'test/mock/*.js', included: true }
- ],
-
- // list of files to exclude
- exclude: [],
-
- // use dots reporter, as travis terminal does not support escaping sequences
- // possible values: 'dots', 'progress'
- // CLI --reporters progress
- reporters: ['dots'],
-
- // enable / disable watching file and executing tests whenever any file changes
- // CLI --auto-watch --no-auto-watch
- autoWatch: true,
-
- // Start these browsers, currently available:
- // - Chrome
- // - ChromeCanary
- // - Firefox
- // - Opera
- // - Safari (only Mac)
- // - PhantomJS
- // - IE (only Windows)
- // CLI --browsers Chrome, Firefox, Safari
- browsers: ['Chrome', 'Firefox'],
-
- // If browser does not capture in given timeout [ms], kill it
- // CLI --capture-timeout 5000
- captureTimeout: 20000,
-
- // Auto run tests on start (when browsers are captured) and exit
- // CLI --single-run --no-single-run
- singleRun: false,
-
- plugins: [
- 'karma-jasmine',
- 'karma-requirejs',
- 'karma-chrome-launcher',
- 'karma-firefox-launcher',
- 'karma-ie-launcher',
- 'karma-phantomjs-launcher',
- 'karma-safari-launcher'
- ]
- });
-};
diff --git a/examples/flight/node_modules/depot/depot.js b/examples/flight/node_modules/depot/depot.js
deleted file mode 100644
index 5f8382bb0f..0000000000
--- a/examples/flight/node_modules/depot/depot.js
+++ /dev/null
@@ -1,249 +0,0 @@
-// depot.js v0.1.6
-
-// (c) 2013 Michal Kuklis
-// Licensed under The MIT License
-// http://opensource.org/licenses/MIT
-
-(function (name, root, factory) {
- if (typeof exports == 'object') {
- module.exports = factory();
- } else if (typeof define == 'function' && define.amd) {
- define(factory);
- } else {
- root[name] = factory();
- }
-}("depot", this, function () {
-
- "use strict";
-
- // depot api
-
- var api = {
-
- save: function (record) {
- var id, ids;
-
- this.refresh();
-
- if (!record[this.idAttribute]) {
- record[this.idAttribute] = guid();
- }
-
- id = record[this.idAttribute] + '';
-
- if (this.ids.indexOf(id) < 0) {
- this.ids.push(id);
- ids = this.ids.join(",");
- this.storageAdaptor.setItem(this.name, ids);
- this.store = ids;
- }
-
- this.storageAdaptor.setItem(getKey(this.name, id), JSON.stringify(record));
-
- return record;
- },
-
- update: function (id, data) {
- if (typeof data == 'undefined') {
- data = id;
- id = data[this.idAttribute];
- }
-
- var record = this.get(id);
-
- if (record) {
- record = extend(record, data);
- this.save(record);
- }
-
- return record;
- },
-
- updateAll: function (data) {
- var records = this.all();
-
- records.forEach(function (record) {
- record = extend(record, data);
- this.save(record);
- }, this);
-
- return records;
- },
-
- find: function (criteria) {
- var key, match, record;
- var name = this.name;
- var self = this;
-
- if (!criteria) return this.all();
-
- this.refresh();
-
- return this.ids.reduce(function (memo, id) {
- record = jsonData(self.storageAdaptor.getItem(getKey(name, id)));
- match = findMatch(criteria, record);
-
- if (match) {
- memo.push(record);
- }
-
- return memo;
- }, []);
- },
-
- get: function (id) {
- return jsonData(this.storageAdaptor.getItem(getKey(this.name, id)));
- },
-
- all: function () {
- var record, self = this, name = this.name;
-
- this.refresh();
-
- return this.ids.reduce(function (memo, id) {
- record = self.storageAdaptor.getItem(getKey(name, id));
-
- if (record) {
- memo.push(jsonData(record));
- }
-
- return memo;
- }, []);
- },
-
- destroy: function (record) {
- var index;
- var id = (record[this.idAttribute]) ? record[this.idAttribute] : record;
- var key = getKey(this.name, id);
-
- record = jsonData(this.storageAdaptor.getItem(key));
- this.storageAdaptor.removeItem(key);
-
- index = this.ids.indexOf(id);
- if (index != -1) this.ids.splice(index, 1);
- this.storageAdaptor.setItem(this.name, this.ids.join(","));
-
- return record;
- },
-
- destroyAll: function (criteria) {
- var attr, id, match, record, key;
-
- this.refresh();
-
- for (var i = this.ids.length - 1; i >= 0; i--) {
- id = this.ids[i];
- key = getKey(this.name, id);
-
- if (criteria) {
-
- record = jsonData(this.storageAdaptor.getItem(key));
- match = findMatch(criteria, record);
-
- if (match) {
- this.storageAdaptor.removeItem(key);
- this.ids.splice(i, 1);
- }
-
- }
- else {
- this.storageAdaptor.removeItem(key);
- }
- }
-
- if (criteria) {
- this.storageAdaptor.setItem(this.name, this.ids.join(","));
- }
- else {
- this.storageAdaptor.removeItem(this.name);
- this.ids = [];
- }
- },
-
- size: function () {
- this.refresh();
-
- return this.ids.length;
- },
-
- refresh: function () {
- var store = this.storageAdaptor.getItem(this.name);
-
- if (this.store && this.store === store) {
- return;
- }
-
- this.ids = (store && store.split(",")) || [];
- this.store = store;
- }
- };
-
- // helpers
-
- function jsonData(data) {
- return data && JSON.parse(data);
- }
-
- function getKey(name, id) {
- return name + "-" + id;
- }
-
- function findMatch(criteria, record) {
- var match, attr;
-
- if (typeof criteria == 'function') {
- match = criteria(record);
- }
- else {
- match = true;
- for (attr in criteria) {
- match &= (criteria[attr] === record[attr]);
- }
- }
-
- return match;
- }
-
- function s4() {
- return Math.floor((1 + Math.random()) * 0x10000)
- .toString(16).substring(1);
- }
-
- function guid() {
- return s4() + s4() + '-' + s4() + '-' + s4() +
- '-' +s4() + '-' + s4() + s4() + s4();
- }
-
- function extend(dest, source) {
- for (var key in source) {
- if (source.hasOwnProperty(key)) {
- dest[key] = source[key];
- }
- }
-
- return dest;
- }
-
- function depot(name, options) {
- var instance;
-
- options = extend({
- idAttribute: '_id',
- storageAdaptor: localStorage
- }, options);
-
- if (!options.storageAdaptor) throw new Error("No storage adaptor was found");
-
- instance = Object.create(api, {
- name: { value: name },
- idAttribute: { value: options.idAttribute },
- storageAdaptor: { value: options.storageAdaptor }
- });
-
- instance.refresh();
-
- return instance;
- }
-
- return depot;
-}));
diff --git a/examples/flight/node_modules/es5-shim/es5-sham.js b/examples/flight/node_modules/es5-shim/es5-sham.js
deleted file mode 100644
index 20c9845975..0000000000
--- a/examples/flight/node_modules/es5-shim/es5-sham.js
+++ /dev/null
@@ -1,446 +0,0 @@
-// Copyright 2009-2012 by contributors, MIT License
-// vim: ts=4 sts=4 sw=4 expandtab
-
-//Add semicolon to prevent IIFE from being passed as argument to concated code.
-;
-// Module systems magic dance
-(function (definition) {
- // RequireJS
- if (typeof define == "function") {
- define(definition);
- // YUI3
- } else if (typeof YUI == "function") {
- YUI.add("es5-sham", definition);
- // CommonJS and
-
-
-
-
-
-