From 049c12602fe41c0caf144af06a254b94110c6d4f Mon Sep 17 00:00:00 2001 From: dntzhang Date: Tue, 18 Apr 2017 12:02:29 +0800 Subject: [PATCH] omi v.1.4.0 - add omi soda version --- dist/omi.js | 2 +- dist/omi.lite.js | 2 +- dist/omi.lite.min.js | 2 +- dist/omi.min.js | 2 +- dist/omi.soda.js | 2977 ++++++++++++++++++++++++++++++++++++++ dist/omi.soda.min.js | 7 + example/es5/soda.html | 29 + example/soda/bundler.js | 3004 +++++++++++++++++++++++++++++++++++++++ example/soda/index.html | 14 + example/soda/main.js | 25 + package.json | 3 +- src/index.soda.js | 15 + src/soda.js | 623 ++++++++ webpack.config.js | 6 +- 14 files changed, 6704 insertions(+), 7 deletions(-) create mode 100644 dist/omi.soda.js create mode 100644 dist/omi.soda.min.js create mode 100644 example/es5/soda.html create mode 100644 example/soda/bundler.js create mode 100644 example/soda/index.html create mode 100644 example/soda/main.js create mode 100644 src/index.soda.js create mode 100644 src/soda.js diff --git a/dist/omi.js b/dist/omi.js index 99e209fb4..f34713b76 100644 --- a/dist/omi.js +++ b/dist/omi.js @@ -1,5 +1,5 @@ /*! - * Omi v1.3.2 By dntzhang + * Omi v1.4.0 By dntzhang * Github: https://github.com/AlloyTeam/omi * MIT Licensed. */ diff --git a/dist/omi.lite.js b/dist/omi.lite.js index 3624c5abe..dbb3f68de 100644 --- a/dist/omi.lite.js +++ b/dist/omi.lite.js @@ -1,5 +1,5 @@ /*! - * Omi v1.3.2 By dntzhang + * Omi v1.4.0 By dntzhang * Github: https://github.com/AlloyTeam/omi * MIT Licensed. */ diff --git a/dist/omi.lite.min.js b/dist/omi.lite.min.js index 95a93c966..5af843f51 100644 --- a/dist/omi.lite.min.js +++ b/dist/omi.lite.min.js @@ -1,5 +1,5 @@ /*! - * Omi v1.3.2 By dntzhang + * Omi v1.4.0 By dntzhang * Github: https://github.com/AlloyTeam/omi * MIT Licensed. */ diff --git a/dist/omi.min.js b/dist/omi.min.js index 796767de8..2ee16365b 100644 --- a/dist/omi.min.js +++ b/dist/omi.min.js @@ -1,5 +1,5 @@ /*! - * Omi v1.3.2 By dntzhang + * Omi v1.4.0 By dntzhang * Github: https://github.com/AlloyTeam/omi * MIT Licensed. */ diff --git a/dist/omi.soda.js b/dist/omi.soda.js new file mode 100644 index 000000000..eea982702 --- /dev/null +++ b/dist/omi.soda.js @@ -0,0 +1,2977 @@ +/*! + * Omi v1.4.0 By dntzhang + * Github: https://github.com/AlloyTeam/omi + * MIT Licensed. + */ +(function webpackUniversalModuleDefinition(root, factory) { + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define([], factory); + else if(typeof exports === 'object') + exports["Omi"] = factory(); + else + root["Omi"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _omi = __webpack_require__(1); + + var _omi2 = _interopRequireDefault(_omi); + + var _soda = __webpack_require__(9); + + var _soda2 = _interopRequireDefault(_soda); + + var _component = __webpack_require__(3); + + var _component2 = _interopRequireDefault(_component); + + var _store = __webpack_require__(8); + + var _store2 = _interopRequireDefault(_store); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + _omi2['default'].template = _soda2['default']; + + _omi2['default'].Store = _store2['default']; + _omi2['default'].Component = _component2['default']; + if (window.Omi) { + module.exports = window.Omi; + } else { + window.Omi = _omi2['default']; + module.exports = _omi2['default']; + } + +/***/ }, +/* 1 */ +/***/ function(module, exports) { + + "use strict"; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + var Omi = {}; + Omi.instances = {}; + Omi._instanceId = 0; + Omi.getInstanceId = function () { + return Omi._instanceId++; + }; + Omi.customTags = []; + Omi.mapping = {}; + + Omi.STYLEPREFIX = "omi_style_"; + Omi.STYLESCOPEDPREFIX = "omi_scoped_"; + + Omi.style = {}; + + Omi.componentConstructor = {}; + + //fix ie bug + if (typeof Object.assign != 'function') { + Object.assign = function (target) { + 'use strict'; + + if (target == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + + target = Object(target); + for (var index = 1; index < arguments.length; index++) { + var source = arguments[index]; + if (source != null) { + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + } + return target; + }; + } + + /** + * Shim for "fixing" IE's lack of support (IE < 9) for applying slice + * on host objects like NamedNodeMap, NodeList, and HTMLCollection + * (technically, since host objects have been implementation-dependent, + * at least before ES6, IE hasn't needed to work this way). + * Also works on strings, fixes IE < 9 to allow an explicit undefined + * for the 2nd argument (as in Firefox), and prevents errors when + * called on other DOM objects. + */ + (function () { + 'use strict'; + + var _slice = Array.prototype.slice; + + try { + // Can't be used with DOM elements in IE < 9 + _slice.call(document.documentElement); + } catch (e) { + // Fails in IE < 9 + // This will work for genuine arrays, array-like objects, + // NamedNodeMap (attributes, entities, notations), + // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes), + // and will not fail on other DOM objects (as do DOM elements in IE < 9) + Array.prototype.slice = function (begin, end) { + // IE < 9 gets unhappy with an undefined end argument + end = typeof end !== 'undefined' ? end : this.length; + + // For native Array objects, we use the native slice function + if (Object.prototype.toString.call(this) === '[object Array]') { + return _slice.call(this, begin, end); + } + + // For array like object we handle it ourselves. + var i, + cloned = [], + size, + len = this.length; + + // Handle negative value for "begin" + var start = begin || 0; + start = start >= 0 ? start : len + start; + + // Handle negative value for "end" + var upTo = end ? end : len; + if (end < 0) { + upTo = len + end; + } + + // Actual expected size of the slice + size = upTo - start; + + if (size > 0) { + cloned = new Array(size); + if (this.charAt) { + for (i = 0; i < size; i++) { + cloned[i] = this.charAt(start + i); + } + } else { + for (i = 0; i < size; i++) { + cloned[i] = this[start + i]; + } + } + } + + return cloned; + }; + } + })(); + + var _createClass = function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor); + } + }return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor; + }; + }(); + + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + }return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass))); + }subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + function toArr(obj) { + var arr = []; + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + arr.push({ key: key, value: obj[key] }); + } + } + return arr; + } + + Omi.create = function (tagName, parent, setting) { + var u_setting = parent, + u_parent = Omi.Component; + if (arguments.length > 2) { + u_setting = setting; + u_parent = parent; + } + Omi.componentConstructor[tagName] = function (parent) { + _inherits(Obj, parent); + + function Obj(data, server) { + _classCallCheck(this, Obj); + this.___omi_constructor_name = tagName; + return _possibleConstructorReturn(this, (Obj.__proto__ || Object.getPrototypeOf(Obj)).call(this, data, server)); + } + + _createClass(Obj, toArr(u_setting)); + + return Obj; + }(u_parent); + + Omi.customTags.push(tagName); + + return Omi.componentConstructor[tagName]; + }; + + Omi.createStore = function (option) { + + var Store = function (parent) { + _inherits(Obj, parent); + + function Obj(data, isReady) { + _classCallCheck(this, Obj); + this.data = data; + option.methods.install && option.methods.install.call(this); + return _possibleConstructorReturn(this, (Obj.__proto__ || Object.getPrototypeOf(Obj)).call(this, data, isReady)); + } + + _createClass(Obj, toArr(option.methods)); + + return Obj; + }(Omi.Store); + + return new Store(option.data, true); + }; + + Omi.mixIndex = function (array, key) { + var len = array.length, + indexName = key || "index"; + for (var i = 0; i < len; i++) { + var item = array[i]; + if ((typeof item === "undefined" ? "undefined" : _typeof(item)) === "object") { + item[indexName] = i; + } else { + array[i] = { value: item }; + array[i][indexName] = i; + } + } + return array; + }; + + Omi.$ = function (selector, context) { + if (context) { + return context.querySelector(selector); + } else { + return document.querySelector(selector); + } + }; + + Omi.$$ = function (selector, context) { + if (context) { + return Array.prototype.slice.call(context.querySelectorAll(selector)); + } else { + return Array.prototype.slice.call(document.querySelectorAll(selector)); + } + }; + + Omi.getClassFromString = function (str) { + if (str.indexOf('.') !== -1) { + //root is window + var arr = str.split('.'); + var len = arr.length; + var current = window[arr[0]]; + for (var i = 1; i < len; i++) { + current = current[arr[i]]; + } + return current; + } else { + return Omi.componentConstructor[str]; + } + }; + + //以前是Component的静态方法,移到omi下来,不然makehtml 在ie下child访问不到父亲的静态方法 + Omi.makeHTML = function (name, ctor) { + Omi.componentConstructor[name] = ctor; + Omi.componentConstructor[name.toLowerCase()] = ctor; + Omi.customTags.push(name, name.toLowerCase()); + }; + + Omi.tag = Omi.makeHTML; + + Omi.render = function (component, renderTo, incrementOrOption) { + component.renderTo = typeof renderTo === "string" ? document.querySelector(renderTo) : renderTo; + if (typeof incrementOrOption === 'boolean') { + component._omi_increment = incrementOrOption; + } else if (incrementOrOption) { + component._omi_increment = incrementOrOption.increment; + if (incrementOrOption.store) { + if (incrementOrOption.store instanceof Omi.Store) { + component.$store = incrementOrOption.store; + } else { + component.$store = Omi.createStore(incrementOrOption.store); + } + } + component._omi_autoStoreToData = incrementOrOption.autoStoreToData; + } + component.install(); + component._render(true); + component._childrenInstalled(component); + component.installed(); + component._execInstalledHandlers(); + return component; + }; + + Omi.get = function (name) { + return Omi.mapping[name]; + }; + + Omi.plugins = {}; + + Omi.extendPlugin = function (name, handler) { + Omi.plugins[name] = handler; + }; + + Omi.getParameters = function (dom, instance, types) { + var data = {}; + var noop = function noop() {}; + var methodMapping = { + stringType: function stringType(value) { + return value; + }, + numberType: function numberType(value) { + return Number(value); + }, + booleanType: function booleanType(value) { + if (value === 'true') { + return true; + } else if (value === 'false') { + return false; + } else { + return Boolean(value); + } + }, + functionType: function functionType(value) { + if (value) { + var handler = instance[value.replace(/Omi.instances\[\d\]./, '')]; + if (handler) { + return handler.bind(instance); + } else { + console.warn('You do not define [ ' + value + ' ] method in following component'); + console.warn(instance); + } + } else { + return noop; + } + } + }; + Object.keys(types).forEach(function (type) { + types[type].forEach(function (name) { + var attr = dom.getAttribute(name); + if (attr !== null) { + data[name] = methodMapping[type](attr); + } + }); + }); + + return data; + }; + + Omi.mixIndexToArray = function (arr, indexName) { + arr.forEach(function (item, index) { + item[indexName || 'index'] = index; + }); + }; + + Omi.deletePlugin = function (name) { + delete Omi.plugins[name]; + }; + + module.exports = Omi; + +/***/ }, +/* 2 */, +/* 3 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _omi = __webpack_require__(1); + + var _omi2 = _interopRequireDefault(_omi); + + var _style = __webpack_require__(4); + + var _style2 = _interopRequireDefault(_style); + + var _event = __webpack_require__(5); + + var _event2 = _interopRequireDefault(_event); + + var _morphdom = __webpack_require__(6); + + var _morphdom2 = _interopRequireDefault(_morphdom); + + var _html2json = __webpack_require__(7); + + var _html2json2 = _interopRequireDefault(_html2json); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var Component = function () { + function Component(data, option) { + _classCallCheck(this, Component); + + var componentOption = Object.assign({ + server: false, + ignoreStoreData: false, + preventSelfUpdate: false, + selfDataFirst: false, + domDiffDisabled: false, + scopedSelfCSS: false + }, option); + this._omi_scopedSelfCSS = componentOption.scopedSelfCSS; + this._omi_preventSelfUpdate = componentOption.preventSelfUpdate; + this._omi_domDiffDisabled = componentOption.domDiffDisabled; + this._omi_ignoreStoreData = componentOption.ignoreStoreData; + //re render the server-side rendering html on the client-side + var type = Object.prototype.toString.call(data); + var isReRendering = type !== '[object Object]' && type !== '[object Undefined]'; + if (isReRendering) { + this.renderTo = typeof data === "string" ? document.querySelector(data) : data; + this._hidden = this.renderTo.querySelector('.omi_scoped__hidden_data'); + this.id = this._hidden.dataset.omiId; + this.data = JSON.parse(this._hidden.value); + } else { + this.data = data || {}; + this._omi_server_rendering = componentOption.server; + this.id = this._omi_server_rendering ? 1000000 + _omi2['default'].getInstanceId() : _omi2['default'].getInstanceId(); + } + this.refs = {}; + this.children = []; + this.childrenData = []; + this.HTML = null; + + _omi2['default'].instances[this.id] = this; + this.selfDataFirst = componentOption.selfDataFirst; + + this._omi_scoped_attr = _omi2['default'].STYLESCOPEDPREFIX + this.id; + //this.BODY_ELEMENT = document.createElement('body') + this._preCSS = null; + this._omiGroupDataCounter = {}; + this._omi_installedHandlers = null; + if (this._omi_server_rendering || isReRendering) { + this.install(); + this._render(true); + this._childrenInstalled(this); + this.installed(); + this._execInstalledHandlers(); + } + } + + _createClass(Component, [{ + key: 'install', + value: function install() {} + }, { + key: 'installed', + value: function installed() {} + }, { + key: 'onInstalled', + value: function onInstalled(handler) { + if (!this._omi_installedHandlers) { + this._omi_installedHandlers = []; + } + this._omi_installedHandlers.push(handler); + } + }, { + key: '_execInstalledHandlers', + value: function _execInstalledHandlers() { + this._omi_installedHandlers && this._omi_installedHandlers.forEach(function (handler) { + handler(); + }); + } + }, { + key: 'uninstall', + value: function uninstall() {} + }, { + key: 'afterUpdate', + value: function afterUpdate() {} + }, { + key: 'beforeUpdate', + value: function beforeUpdate() {} + }, { + key: 'render', + value: function render() {} + }, { + key: 'style', + value: function style() {} + }, { + key: 'beforeRender', + value: function beforeRender() {} + }, { + key: 'useStore', + value: function useStore(store) { + var _this = this; + + this.$$store = store; + var isInclude = false; + store.instances.forEach(function (instance) { + if (instance.id === _this.id) { + isInclude = true; + } + }); + if (!isInclude) { + store.instances.push(this); + } + } + }, { + key: 'updateSelf', + value: function updateSelf() { + this.beforeUpdate(); + if (this.renderTo) { + this._render(false, true); + } else { + if (this._omi_preventSelfUpdate) return; + // update child node + if (this._omi_removed) { + var hdNode = this._createHiddenNode(); + this.node.parentNode.replaceChild(hdNode, this.node); + this.node = hdNode; + } else { + (0, _morphdom2['default'])(this.node, (0, _event2['default'])(this._childRender(this._omiChildStr, true), this.id), { + ignoreAttr: this._getIgnoreAttr() + }); + + this.node = document.querySelector("[" + this._omi_scoped_attr + "]"); + this._queryElements(this); + this._fixForm(); + } + } + this.afterUpdate(); + } + }, { + key: 'update', + value: function update() { + this.beforeUpdate(); + this._childrenBeforeUpdate(this); + if (this.renderTo) { + this._render(); + } else { + if (this._omi_preventSelfUpdate) return; + // update child node + if (this._omi_removed) { + var hdNode = this._createHiddenNode(); + this.node.parentNode.replaceChild(hdNode, this.node); + this.node = hdNode; + } else { + if (this._omi_domDiffDisabled) { + this.node.parentNode.replaceChild(_morphdom2['default'].toElement((0, _event2['default'])(this._childRender(this._omiChildStr), this.id)), this.node); + } else { + (0, _morphdom2['default'])(this.node, (0, _event2['default'])(this._childRender(this._omiChildStr), this.id)); + } + this.node = document.querySelector("[" + this._omi_scoped_attr + "]"); + this._queryElements(this); + this._fixForm(); + } + } + + this._childrenAfterUpdate(this); + this.afterUpdate(); + } + }, { + key: '_childrenBeforeUpdate', + value: function _childrenBeforeUpdate(root) { + var _this2 = this; + + root.children.forEach(function (child) { + child.beforeUpdate(); + _this2._childrenBeforeUpdate(child); + }); + } + }, { + key: '_childrenAfterUpdate', + value: function _childrenAfterUpdate(root) { + var _this3 = this; + + root.children.forEach(function (child) { + _this3._childrenAfterUpdate(child); + child.afterUpdate(); + }); + } + }, { + key: 'setData', + value: function setData(data, update) { + this.data = data; + if (update) { + this.update(); + } + } + }, { + key: 'removeChild', + value: function removeChild(indexOrChild) { + var child = indexOrChild; + if (typeof indexOrChild === 'number') { + child = this.children[indexOrChild]; + } + + child.remove(); + } + }, { + key: 'restoreChild', + value: function restoreChild(indexOrChild) { + var child = indexOrChild; + if (typeof indexOrChild === 'number') { + child = this.children[indexOrChild]; + } + + child.restore(); + } + }, { + key: 'remove', + value: function remove() { + this._omi_removed = true; + this.update(); + this.uninstall(); + } + }, { + key: 'restore', + value: function restore() { + this._omi_removed = false; + this.update(); + this.installed(); + this._execInstalledHandlers(); + } + }, { + key: '_render', + value: function _render(isFirst, isSelf) { + var _this4 = this; + + if (this._omi_removed) { + var node = this._createHiddenNode(); + if (!isFirst) { + this.node.parentNode.replaceChild(node, this.node); + this.node = node; + } else if (this.renderTo) { + this.renderTo.appendChild(node); + } + return; + } + if (this._omi_autoStoreToData) { + if (!this._omi_ignoreStoreData) { + this.data = this.$store.data; + } + } + this.beforeRender(); + this._generateHTMLCSS(); + if (!isSelf) { + this._extractChildren(this); + } else { + this._extractChildrenString(this); + } + + this.children.forEach(function (item) { + _this4.HTML = _this4.HTML.replace(item._omiChildStr, isSelf ? item.node.outerHTML : item.HTML); + }); + + this.HTML = (0, _event2['default'])(this.HTML, this.id); + if (isFirst) { + if (this.renderTo) { + if (this._omi_increment) { + this.renderTo.insertAdjacentHTML('beforeend', this.HTML); + } else { + this.renderTo.innerHTML = this.HTML; + } + } + } else { + if (this.HTML !== "") { + if (this._omi_domDiffDisabled) { + this.renderTo.innerHTML = this.HTML; + } else { + (0, _morphdom2['default'])(this.node, this.HTML, isSelf ? { + ignoreAttr: this._getIgnoreAttr() + } : null); + } + } else { + (0, _morphdom2['default'])(this.node, this._createHiddenNode()); + } + } + //get node prop from parent node + if (this.renderTo) { + this.node = document.querySelector("[" + this._omi_scoped_attr + "]"); + this._queryElements(this); + this._fixForm(); + } + } + }, { + key: '_getIgnoreAttr', + value: function _getIgnoreAttr() { + var arr = []; + this.children.forEach(function (child) { + arr.push(child._omi_scoped_attr); + }); + return arr; + } + }, { + key: '_childRender', + value: function _childRender(childStr, isSelf) { + var _this5 = this; + + if (this._omi_removed) { + this.HTML = ''; + return this.HTML; + } + //childStr = childStr.replace("", ">") + this._mergeData(childStr); + if (this.parent._omi_autoStoreToData) { + this._omi_autoStoreToData = true; + if (!this._omi_ignoreStoreData) { + this.data = this.$store.data; + } + } + this.beforeRender(); + this._fixSlot(this._generateHTMLCSS()); + if (!isSelf) { + this._extractChildren(this); + } else { + this._extractChildrenString(this); + } + + this.children.forEach(function (item) { + _this5.HTML = _this5.HTML.replace(item._omiChildStr, isSelf ? item.node.outerHTML : item.HTML); + }); + this.HTML = (0, _event2['default'])(this.HTML, this.id); + return this.HTML; + } + }, { + key: '_fixSlot', + value: function _fixSlot(shareAttr) { + var _this6 = this; + + if (!this._omi_slotContent) return; + this._omi_slotContent = this._scopedAttr(this._omi_slotContent, this._omi_scoped_attr, shareAttr); + var nodes = _morphdom2['default'].toElements(this._omi_slotContent); + var slotMatch = this.HTML.match(//g); + if (nodes.length === 1 && slotMatch && slotMatch.length === 1) { + this.HTML = this.HTML.replace(//, this._omi_slotContent); + } else { + nodes.sort(function (a, b) { + return parseInt(a.getAttribute('slot-index')) - parseInt(b.getAttribute('slot-index')); + }); + nodes.forEach(function (node) { + _this6.HTML = _this6.HTML.replace(//, node.outerHTML); + }); + } + } + }, { + key: '_queryElements', + value: function _queryElements(current) { + current._mixRefs(); + current._execPlugins(); + current.children.forEach(function (item) { + item.node = current.node.querySelector("[" + _omi2['default'].STYLESCOPEDPREFIX + item.id + "]"); + //recursion get node prop from parent node + item.node && current._queryElements(item); + }); + } + }, { + key: '_mixRefs', + value: function _mixRefs() { + var _this7 = this; + + var nodes = _omi2['default'].$$('*[ref]', this.node); + nodes.forEach(function (node) { + if (node.hasAttribute(_this7._omi_scoped_attr)) { + _this7.refs[node.getAttribute('ref')] = node; + } + }); + var attr = this.node.getAttribute('ref'); + if (attr) { + this.refs[attr] = this.node; + } + } + }, { + key: '_execPlugins', + value: function _execPlugins() { + var _this8 = this; + + Object.keys(_omi2['default'].plugins).forEach(function (item) { + var nodes = _omi2['default'].$$('*[' + item + ']', _this8.node); + nodes.forEach(function (node) { + if (node.hasAttribute(_this8._omi_scoped_attr)) { + _omi2['default'].plugins[item](node, _this8); + } + }); + if (_this8.node.hasAttribute(item)) { + _omi2['default'].plugins[item](_this8.node, _this8); + } + }); + } + }, { + key: '_childrenInstalled', + value: function _childrenInstalled(root) { + var _this9 = this; + + root.children.forEach(function (child) { + _this9._childrenInstalled(child); + child.installed(); + child._execInstalledHandlers(); + }); + } + }, { + key: '_fixForm', + value: function _fixForm() { + + _omi2['default'].$$('input', this.node).forEach(function (element) { + var type = element.type.toLowerCase(); + if (element.getAttribute('value') === '') { + element.value = ''; + } + if (type === 'checked' || type === 'radio') { + if (element.hasAttribute('checked')) { + element.checked = 'checked'; + } else { + element.checked = false; + } + } + }); + + _omi2['default'].$$('textarea', this.node).forEach(function (textarea) { + textarea.value = textarea.getAttribute('value'); + }); + + _omi2['default'].$$('select', this.node).forEach(function (select) { + var value = select.getAttribute('value'); + if (value) { + _omi2['default'].$$('option', select).forEach(function (option) { + if (value === option.getAttribute('value')) { + option.setAttribute('selected', 'selected'); + } + }); + } else { + var firstOption = _omi2['default'].$$('option', select)[0]; + firstOption && firstOption.setAttribute('selected', 'selected'); + } + }); + } + }, { + key: '_replaceTags', + value: function _replaceTags(array, html, updateSelf) { + var _this10 = this; + + if (_omi2['default'].customTags.length === 0) return; + var str = array.join("|"); + var reg = new RegExp('<(' + str + '+)((?:\\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\\s*=\\s*(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>\\s]+))?)*)\\s*((\\/>)|>(([\\s\\S]*?)<\\/\\1>))', 'g'); + var index = 0; + return html.replace(reg, function (m, a, b, c, d, e, f) { + if (updateSelf) { + var cmi = _this10.children[index]; + if (cmi && cmi.___omi_constructor_name === a) { + cmi._omiChildStr = m; + } + } else { + _this10._initComponentByString(a, m, f, index++, _this10); + } + }); + } + }, { + key: '_createHiddenNode', + value: function _createHiddenNode() { + var hdNode = document.createElement("input"); + hdNode.setAttribute("type", "hidden"); + hdNode.setAttribute(this._omi_scoped_attr, ''); + return hdNode; + } + }, { + key: '_mergeData', + value: function _mergeData(childStr) { + if (this.selfDataFirst) { + this.data = Object.assign({}, this._getDataset(childStr), this.data); + } else { + this.data = Object.assign({}, this.data, this._getDataset(childStr)); + } + } + }, { + key: '_generateHTMLCSS', + value: function _generateHTMLCSS() { + this.CSS = (this.style() || '').replace(/<\/?style>/g, ''); + var shareAttr = this.___omi_constructor_name ? _omi2['default'].STYLESCOPEDPREFIX + this.___omi_constructor_name.toLowerCase() : this._omi_scoped_attr; + if (this.CSS) { + if (this._omi_scopedSelfCSS || !_omi2['default'].style[shareAttr]) { + this.CSS = _style2['default'].scoper(this.CSS, this._omi_scopedSelfCSS ? "[" + this._omi_scoped_attr + "]" : "[" + shareAttr + "]"); + _omi2['default'].style[shareAttr] = this.CSS; + if (this.CSS !== this._preCSS && !this._omi_server_rendering) { + _style2['default'].addStyle(this.CSS, this.id); + this._preCSS = this.CSS; + } + } + } + var tpl = this.render(); + this.HTML = this._scopedAttr(_omi2['default'].template(tpl ? tpl : "", this.data), this._omi_scoped_attr, shareAttr).trim(); + if (this._omi_server_rendering) { + this.HTML = '\r\n\r\n' + this.HTML; + this.HTML += '\r\n\r\n'; + } + + return shareAttr; + } + }, { + key: '_scopedAttr', + value: function _scopedAttr(html, id, shareAtrr) { + var _this11 = this; + + return html.replace(/<[^/]([A-Za-z]*)[^>]*>/g, function (m) { + var str = m.split(" ")[0].replace(">", ""); + if (_this11._omi_scopedSelfCSS || !_this11.___omi_constructor_name) { + return m.replace(str, str + " " + id); + } else { + return m.replace(str, str + " " + id + " " + shareAtrr); + } + }); + } + }, { + key: '_getDataset', + value: function _getDataset(childStr) { + var _this12 = this; + + var json = (0, _html2json2['default'])(childStr); + var attr = json.child[0].attr; + var baseData = {}; + Object.keys(attr).forEach(function (key) { + var value = attr[key]; + if (key.indexOf('on') === 0) { + var handler = _this12.parent[value]; + if (handler) { + baseData[key] = handler.bind(_this12.parent); + } + } else if (key.indexOf('data-') === 0) { + _this12._dataset[_this12._capitalize(key.replace('data-', ''))] = value; + } else if (key.indexOf(':data-') === 0) { + _this12._dataset[_this12._capitalize(key.replace(':data-', ''))] = eval('(' + value + ')'); + } else if (key === ':data') { + _this12._dataset = eval('(' + value + ')'); + } else if (key === 'data') { + _this12._dataset = _this12._extractPropertyFromString(value, _this12.parent); + } else if (key === 'group-data') { + _this12._dataset = _this12._extractPropertyFromString(value, _this12.parent)[_this12._omi_groupDataIndex]; + } + }); + + return Object.assign(baseData, this._dataset); + } + }, { + key: '_capitalize', + value: function _capitalize(str) { + str = str.toLowerCase(); + str = str.replace(/\b\w+\b/g, function (word) { + return word.substring(0, 1).toUpperCase() + word.substring(1); + }).replace(/-/g, ''); + return str.substring(0, 1).toLowerCase() + str.substring(1); + } + }, { + key: '_extractPropertyFromString', + value: function _extractPropertyFromString(str, instance) { + var arr = str.replace(/['|"|\]]/g, '').replace(/\[/g, '.').split('.'); + var current = instance; + arr.forEach(function (prop) { + current = current[prop]; + }); + arr = null; + return current; + } + }, { + key: '_extractChildrenString', + value: function _extractChildrenString(child) { + this._replaceTags(_omi2['default'].customTags, child.HTML, true); + } + }, { + key: '_extractChildren', + value: function _extractChildren(child) { + this._replaceTags(_omi2['default'].customTags, child.HTML); + } + }, { + key: '_initComponentByString', + value: function _initComponentByString(name, childStr, slotContent, i, child) { + var _this13 = this; + + var json = (0, _html2json2['default'])(childStr); + var attr = json.child[0].attr; + var cmi = this.children[i]; + //if not first time to invoke _extractChildren method + if (cmi && cmi.___omi_constructor_name === name) { + cmi._omiChildStr = childStr; + cmi._omi_slotContent = slotContent; + Object.keys(attr).forEach(function (key) { + var value = attr[key]; + if (key === 'group-data') { + if (child._omiGroupDataCounter.hasOwnProperty(value)) { + child._omiGroupDataCounter[value]++; + } else { + child._omiGroupDataCounter[value] = 0; + } + cmi._omi_groupDataIndex = child._omiGroupDataCounter[value]; + } + }); + + cmi._childRender(childStr); + } else { + (function () { + var baseData = {}; + var dataset = {}; + + var groupDataIndex = null; + var omiID = null; + var instanceName = null; + var _omi_option = {}; + + Object.keys(attr).forEach(function (key) { + var value = attr[key]; + if (key.indexOf('on') === 0) { + var handler = child[value]; + if (handler) { + baseData[key] = handler.bind(child); + } + } else if (key === 'omi-id') { + omiID = value; + } else if (key === 'name') { + instanceName = value; + } else if (key === 'group-data') { + if (child._omiGroupDataCounter.hasOwnProperty(value)) { + child._omiGroupDataCounter[value]++; + } else { + child._omiGroupDataCounter[value] = 0; + } + groupDataIndex = child._omiGroupDataCounter[value]; + dataset = _this13._extractPropertyFromString(value, child)[groupDataIndex]; + } else if (key.indexOf('data-') === 0) { + dataset[_this13._capitalize(key.replace('data-', ''))] = value; + } else if (key.indexOf(':data-') === 0) { + dataset[_this13._capitalize(key.replace(':data-', ''))] = eval('(' + value + ')'); + } else if (key === ':data') { + dataset = eval('(' + value + ')'); + } else if (key === 'data') { + dataset = _this13._extractPropertyFromString(value, child); + } else if (key === 'preventSelfUpdate' || key === 'psu') { + _omi_option.preventSelfUpdate = true; + } else if (key === 'selfDataFirst' || key === 'sdf') { + _omi_option.selfDataFirst = true; + } else if (key === 'domDiffDisabled' || key === 'ddd') { + _omi_option.domDiffDisabled = true; + } else if (key === 'ignoreStoreData' || key === 'isd') { + _omi_option.ignoreStoreData = true; + } else if (key === 'scopedSelfCSS' || key === 'ssc') { + _omi_option.scopedSelfCSS = true; + } + }); + + var ChildClass = _omi2['default'].getClassFromString(name); + if (!ChildClass) throw "Can't find Class called [" + name + "]"; + var sub_child = new ChildClass(Object.assign(baseData, child.childrenData[i], dataset), _omi_option); + sub_child._omi_groupDataIndex = groupDataIndex; + sub_child._omiChildStr = childStr; + sub_child._omi_slotContent = slotContent; + sub_child.parent = child; + sub_child.$store = child.$store; + sub_child.___omi_constructor_name = name; + sub_child._dataset = {}; + sub_child.install(); + + omiID && (_omi2['default'].mapping[omiID] = sub_child); + instanceName && (child[instanceName] = sub_child); + + if (!cmi) { + child.children.push(sub_child); + } else { + child.children[i] = sub_child; + } + + sub_child._childRender(childStr); + })(); + } + } + }]); + + return Component; + }(); + + exports['default'] = Component; + +/***/ }, +/* 4 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _omi = __webpack_require__(1); + + var _omi2 = _interopRequireDefault(_omi); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + //many thanks to https://github.com/thomaspark/scoper/ + function scoper(css, prefix) { + //https://www.w3.org/TR/css-syntax-3/#lexical + css = css.replace(/\/\*[^*]*\*+([^/][^*]*\*+)*\//g, ''); + + var re = new RegExp("([^\r\n,{}:]+)(:[^\r\n,{}]+)?(,(?=[^{}]*{)|\s*{)", "g"); + /** + * Example: + * + * .classname::pesudo { color:red } + * + * g1 is normal selector `.classname` + * g2 is pesudo class or pesudo element + * g3 is the suffix + */ + css = css.replace(re, function (g0, g1, g2, g3) { + if (typeof g2 === "undefined") { + g2 = ""; + } + + if (g1.match(/^\s*(@media|@keyframes|to|from|@font-face)/)) { + return g1 + g2 + g3; + } + + var appendClass = g1.replace(/(\s*)$/, "") + prefix + g2; + var prependClass = prefix + " " + g1.trim() + g2; + return appendClass + "," + prependClass + g3; + }); + + return css; + } + + function addStyle(cssText, id) { + var ele = document.getElementById(_omi2['default'].STYLEPREFIX + id), + head = document.getElementsByTagName('head')[0]; + if (ele && ele.parentNode === head) { + head.removeChild(ele); + } + + var someThingStyles = document.createElement('style'); + head.appendChild(someThingStyles); + someThingStyles.setAttribute('type', 'text/css'); + someThingStyles.setAttribute('id', _omi2['default'].STYLEPREFIX + id); + if (!!window.ActiveXObject) { + someThingStyles.styleSheet.cssText = cssText; + } else { + someThingStyles.textContent = cssText; + } + } + + exports['default'] = { + scoper: scoper, + addStyle: addStyle + }; + +/***/ }, +/* 5 */ +/***/ function(module, exports) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + function scopedEvent(tpl, id) { + return tpl.replace(/<[\s\S]*?>/g, function (item) { + return item.replace(/on(abort|blur|cancel|canplay|canplaythrough|change|click|close|contextmenu|cuechange|dblclick|drag|dragend|dragenter|dragleave|dragover|dragstart|drop|durationchange|emptied|ended|error|focus|input|invalid|keydown|keypress|keyup|load|loadeddata|loadedmetadata|loadstart|mousedown|mouseenter|mouseleave|mousemove|mouseout|mouseover|mouseup|mousewheel|pause|play|playing|progress|ratechange|reset|resize|scroll|seeked|seeking|select|show|stalled|submit|suspend|timeupdate|toggle|volumechange|waiting|autocomplete|autocompleteerror|beforecopy|beforecut|beforepaste|copy|cut|paste|search|selectstart|wheel|webkitfullscreenchange|webkitfullscreenerror|touchstart|touchmove|touchend|touchcancel|pointerdown|pointerup|pointercancel|pointermove|pointerover|pointerout|pointerenter|pointerleave|Abort|Blur|Cancel|CanPlay|CanPlayThrough|Change|Click|Close|ContextMenu|CueChange|DblClick|Drag|DragEnd|DragEnter|DragLeave|DragOver|DragStart|Drop|DurationChange|Emptied|Ended|Error|Focus|Input|Invalid|KeyDown|KeyPress|KeyUp|Load|LoadedData|LoadedMetadata|LoadStart|MouseDown|MouseEnter|MouseLeave|MouseMove|MouseOut|MouseOver|MouseUp|MouseWheel|Pause|Play|Playing|Progress|RateChange|Reset|Resize|Scroll|Seeked|Seeking|Select|Show|Stalled|Submit|Suspend|TimeUpdate|Toggle|VolumeChange|Waiting|AutoComplete|AutoCompleteError|BeforeCopy|BeforeCut|BeforePaste|Copy|Cut|Paste|Search|SelectStart|Wheel|WebkitFullScreenChange|WebkitFullScreenError|TouchStart|TouchMove|TouchEnd|TouchCancel|PointerDown|PointerUp|PointerCancel|PointerMove|PointerOver|PointerOut|PointerEnter|PointerLeave)=(('([\s\S]*?)')|("([\s\S]*?)"))/g, function (eventStr, b, c) { + if (c.indexOf('Omi.instances[') === 1) { + return eventStr; + } else if (c.lastIndexOf(')') === c.length - 2) { + return eventStr.replace(/=(['|"])/, '=$1Omi.instances[' + id + '].'); + } else { + var str = eventStr.replace(/=(['|"])/, '=$1Omi.instances[' + id + '].'); + return str.substr(0, str.length - 1) + "(event)" + str.substr(str.length - 1, 1); + } + }); + }); + } + + exports['default'] = scopedEvent; + +/***/ }, +/* 6 */ +/***/ function(module, exports, __webpack_require__) { + + var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + (function (global, factory) { + ( false ? 'undefined' : _typeof(exports)) === 'object' && typeof module !== 'undefined' ? module.exports = factory() : true ? !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : global.morphdom = factory(); + })(undefined, function () { + 'use strict'; + + var range; // Create a range object for efficently rendering strings to elements. + var NS_XHTML = 'http://www.w3.org/1999/xhtml'; + + var doc = typeof document === 'undefined' ? undefined : document; + + var testEl = doc ? doc.body || doc.createElement('div') : {}; + + // Fixes + // (IE7+ support) <=IE7 does not support el.hasAttribute(name) + var actualHasAttributeNS; + + if (testEl.hasAttributeNS) { + actualHasAttributeNS = function actualHasAttributeNS(el, namespaceURI, name) { + return el.hasAttributeNS(namespaceURI, name); + }; + } else if (testEl.hasAttribute) { + actualHasAttributeNS = function actualHasAttributeNS(el, namespaceURI, name) { + return el.hasAttribute(name); + }; + } else { + actualHasAttributeNS = function actualHasAttributeNS(el, namespaceURI, name) { + return el.getAttributeNode(namespaceURI, name) != null; + }; + } + + var hasAttributeNS = actualHasAttributeNS; + + function toElement(str) { + if (!range && doc.createRange) { + range = doc.createRange(); + range.selectNode(doc.body); + } + + var fragment; + if (range && range.createContextualFragment) { + fragment = range.createContextualFragment(str); + } else { + fragment = doc.createElement('body'); + fragment.innerHTML = str; + } + return fragment.childNodes[0]; + } + + function toElements(str) { + if (!range && doc.createRange) { + range = doc.createRange(); + range.selectNode(doc.body); + } + + var fragment; + if (range && range.createContextualFragment) { + fragment = range.createContextualFragment(str); + } else { + fragment = doc.createElement('body'); + fragment.innerHTML = str; + } + + var arr = [], + i = 0, + len = fragment.childNodes.length; + for (; i < len; i++) { + var item = fragment.childNodes[i]; + if (item.nodeType === 1) { + arr.push(item); + } + } + return arr; + } + + /** + * Returns true if two node's names are the same. + * + * NOTE: We don't bother checking `namespaceURI` because you will never find two HTML elements with the same + * nodeName and different namespace URIs. + * + * @param {Element} a + * @param {Element} b The target element + * @return {boolean} + */ + function compareNodeNames(fromEl, toEl) { + var fromNodeName = fromEl.nodeName; + var toNodeName = toEl.nodeName; + + if (fromNodeName === toNodeName) { + return true; + } + + if (toEl.actualize && fromNodeName.charCodeAt(0) < 91 && /* from tag name is upper case */ + toNodeName.charCodeAt(0) > 90 /* target tag name is lower case */) { + // If the target element is a virtual DOM node then we may need to normalize the tag name + // before comparing. Normal HTML elements that are in the "http://www.w3.org/1999/xhtml" + // are converted to upper case + return fromNodeName === toNodeName.toUpperCase(); + } else { + return false; + } + } + + /** + * Create an element, optionally with a known namespace URI. + * + * @param {string} name the element name, e.g. 'div' or 'svg' + * @param {string} [namespaceURI] the element's namespace URI, i.e. the value of + * its `xmlns` attribute or its inferred namespace. + * + * @return {Element} + */ + function createElementNS(name, namespaceURI) { + return !namespaceURI || namespaceURI === NS_XHTML ? doc.createElement(name) : doc.createElementNS(namespaceURI, name); + } + + /** + * Copies the children of one DOM element to another DOM element + */ + function moveChildren(fromEl, toEl) { + var curChild = fromEl.firstChild; + while (curChild) { + var nextChild = curChild.nextSibling; + toEl.appendChild(curChild); + curChild = nextChild; + } + return toEl; + } + + function morphAttrs(fromNode, toNode) { + var attrs = toNode.attributes; + var i; + var attr; + var attrName; + var attrNamespaceURI; + var attrValue; + var fromValue; + + for (i = attrs.length - 1; i >= 0; --i) { + attr = attrs[i]; + attrName = attr.name; + attrNamespaceURI = attr.namespaceURI; + attrValue = attr.value; + + if (attrNamespaceURI) { + attrName = attr.localName || attrName; + fromValue = fromNode.getAttributeNS(attrNamespaceURI, attrName); + + if (fromValue !== attrValue) { + fromNode.setAttributeNS(attrNamespaceURI, attrName, attrValue); + } + } else { + fromValue = fromNode.getAttribute(attrName); + + if (fromValue !== attrValue) { + fromNode.setAttribute(attrName, attrValue); + } + } + } + + // Remove any extra attributes found on the original DOM element that + // weren't found on the target element. + attrs = fromNode.attributes; + + for (i = attrs.length - 1; i >= 0; --i) { + attr = attrs[i]; + if (attr.specified !== false) { + attrName = attr.name; + attrNamespaceURI = attr.namespaceURI; + + if (attrNamespaceURI) { + attrName = attr.localName || attrName; + + if (!hasAttributeNS(toNode, attrNamespaceURI, attrName)) { + fromNode.removeAttributeNS(attrNamespaceURI, attrName); + } + } else { + if (!hasAttributeNS(toNode, null, attrName)) { + fromNode.removeAttribute(attrName); + } + } + } + } + } + + function syncBooleanAttrProp(fromEl, toEl, name) { + if (fromEl[name] !== toEl[name]) { + fromEl[name] = toEl[name]; + if (fromEl[name]) { + fromEl.setAttribute(name, ''); + } else { + fromEl.removeAttribute(name, ''); + } + } + } + + var specialElHandlers = { + /** + * Needed for IE. Apparently IE doesn't think that "selected" is an + * attribute when reading over the attributes using selectEl.attributes + */ + OPTION: function OPTION(fromEl, toEl) { + syncBooleanAttrProp(fromEl, toEl, 'selected'); + }, + /** + * The "value" attribute is special for the element since it sets + * the initial value. Changing the "value" attribute without changing the + * "value" property will have no effect since it is only used to the set the + * initial value. Similar for the "checked" attribute, and "disabled". + */ + INPUT: function INPUT(fromEl, toEl) { + syncBooleanAttrProp(fromEl, toEl, 'checked'); + syncBooleanAttrProp(fromEl, toEl, 'disabled'); + + if (fromEl.value !== toEl.value) { + fromEl.value = toEl.value; + } + + if (!hasAttributeNS(toEl, null, 'value')) { + fromEl.removeAttribute('value'); + } + }, + + TEXTAREA: function TEXTAREA(fromEl, toEl) { + var newValue = toEl.value; + if (fromEl.value !== newValue) { + fromEl.value = newValue; + } + + if (fromEl.firstChild) { + // Needed for IE. Apparently IE sets the placeholder as the + // node value and vise versa. This ignores an empty update. + if (newValue === '' && fromEl.firstChild.nodeValue === fromEl.placeholder) { + return; + } + + fromEl.firstChild.nodeValue = newValue; + } + }, + SELECT: function SELECT(fromEl, toEl) { + if (!hasAttributeNS(toEl, null, 'multiple')) { + var selectedIndex = -1; + var i = 0; + var curChild = toEl.firstChild; + while (curChild) { + var nodeName = curChild.nodeName; + if (nodeName && nodeName.toUpperCase() === 'OPTION') { + if (hasAttributeNS(curChild, null, 'selected')) { + selectedIndex = i; + break; + } + i++; + } + curChild = curChild.nextSibling; + } + + fromEl.selectedIndex = i; + } + } + }; + + var ELEMENT_NODE = 1; + var TEXT_NODE = 3; + var COMMENT_NODE = 8; + + function noop() {} + + function defaultGetNodeKey(node) { + return node.id; + } + + function morphdomFactory(morphAttrs) { + + return function morphdom(fromNode, toNode, options) { + if (!options) { + options = {}; + } + + if (typeof toNode === 'string') { + if (fromNode.nodeName === '#document' || fromNode.nodeName === 'HTML') { + var toNodeHtml = toNode; + toNode = doc.createElement('html'); + toNode.innerHTML = toNodeHtml; + } else { + toNode = toElement(toNode); + } + } + + var getNodeKey = options.getNodeKey || defaultGetNodeKey; + var onBeforeNodeAdded = options.onBeforeNodeAdded || noop; + var onNodeAdded = options.onNodeAdded || noop; + var onBeforeElUpdated = options.onBeforeElUpdated || noop; + var onElUpdated = options.onElUpdated || noop; + var onBeforeNodeDiscarded = options.onBeforeNodeDiscarded || noop; + var onNodeDiscarded = options.onNodeDiscarded || noop; + var onBeforeElChildrenUpdated = options.onBeforeElChildrenUpdated || noop; + var childrenOnly = options.childrenOnly === true; + var ignoreAttr = options.ignoreAttr; + // This object is used as a lookup to quickly find all keyed elements in the original DOM tree. + var fromNodesLookup = {}; + var keyedRemovalList; + + function addKeyedRemoval(key) { + if (keyedRemovalList) { + keyedRemovalList.push(key); + } else { + keyedRemovalList = [key]; + } + } + + function walkDiscardedChildNodes(node, skipKeyedNodes) { + if (node.nodeType === ELEMENT_NODE) { + var curChild = node.firstChild; + while (curChild) { + + var key = undefined; + + if (skipKeyedNodes && (key = getNodeKey(curChild))) { + // If we are skipping keyed nodes then we add the key + // to a list so that it can be handled at the very end. + addKeyedRemoval(key); + } else { + // Only report the node as discarded if it is not keyed. We do this because + // at the end we loop through all keyed elements that were unmatched + // and then discard them in one final pass. + onNodeDiscarded(curChild); + if (curChild.firstChild) { + walkDiscardedChildNodes(curChild, skipKeyedNodes); + } + } + + curChild = curChild.nextSibling; + } + } + } + + /** + * Removes a DOM node out of the original DOM + * + * @param {Node} node The node to remove + * @param {Node} parentNode The nodes parent + * @param {Boolean} skipKeyedNodes If true then elements with keys will be skipped and not discarded. + * @return {undefined} + */ + function removeNode(node, parentNode, skipKeyedNodes) { + if (onBeforeNodeDiscarded(node) === false) { + return; + } + + if (parentNode) { + parentNode.removeChild(node); + } + + onNodeDiscarded(node); + walkDiscardedChildNodes(node, skipKeyedNodes); + } + + // // TreeWalker implementation is no faster, but keeping this around in case this changes in the future + // function indexTree(root) { + // var treeWalker = document.createTreeWalker( + // root, + // NodeFilter.SHOW_ELEMENT); + // + // var el; + // while((el = treeWalker.nextNode())) { + // var key = getNodeKey(el); + // if (key) { + // fromNodesLookup[key] = el; + // } + // } + // } + + // // NodeIterator implementation is no faster, but keeping this around in case this changes in the future + // + // function indexTree(node) { + // var nodeIterator = document.createNodeIterator(node, NodeFilter.SHOW_ELEMENT); + // var el; + // while((el = nodeIterator.nextNode())) { + // var key = getNodeKey(el); + // if (key) { + // fromNodesLookup[key] = el; + // } + // } + // } + + function indexTree(node) { + if (node.nodeType === ELEMENT_NODE) { + var curChild = node.firstChild; + while (curChild) { + var key = getNodeKey(curChild); + if (key) { + fromNodesLookup[key] = curChild; + } + + // Walk recursively + indexTree(curChild); + + curChild = curChild.nextSibling; + } + } + } + + indexTree(fromNode); + + function handleNodeAdded(el) { + onNodeAdded(el); + + var curChild = el.firstChild; + while (curChild) { + var nextSibling = curChild.nextSibling; + + var key = getNodeKey(curChild); + if (key) { + var unmatchedFromEl = fromNodesLookup[key]; + if (unmatchedFromEl && compareNodeNames(curChild, unmatchedFromEl)) { + curChild.parentNode.replaceChild(unmatchedFromEl, curChild); + morphEl(unmatchedFromEl, curChild); + } + } + + handleNodeAdded(curChild); + curChild = nextSibling; + } + } + + function morphEl(fromEl, toEl, childrenOnly) { + if (ignoreAttr) { + var ignoreF = false, + ignoreT = false, + attrF = null, + attrT = null; + for (var _i = 0, _len = ignoreAttr.length; _i < _len; _i++) { + var selector = ignoreAttr[_i]; + if (!ignoreF && fromEl.getAttribute(selector) !== null) { + ignoreF = true; + attrF = selector; + } + if (!ignoreT && toEl.getAttribute(selector) !== null) { + ignoreT = true; + attrT = selector; + } + if (ignoreF && ignoreT) break; + } + if (ignoreF && ignoreT && attrF === attrT) { + return; + } + } + var toElKey = getNodeKey(toEl); + var curFromNodeKey; + + if (toElKey) { + // If an element with an ID is being morphed then it is will be in the final + // DOM so clear it out of the saved elements collection + delete fromNodesLookup[toElKey]; + } + + if (toNode.isSameNode && toNode.isSameNode(fromNode)) { + return; + } + + if (!childrenOnly) { + if (onBeforeElUpdated(fromEl, toEl) === false) { + return; + } + + morphAttrs(fromEl, toEl); + onElUpdated(fromEl); + + if (onBeforeElChildrenUpdated(fromEl, toEl) === false) { + return; + } + } + + if (fromEl.nodeName !== 'TEXTAREA') { + var curToNodeChild = toEl.firstChild; + var curFromNodeChild = fromEl.firstChild; + var curToNodeKey; + + var fromNextSibling; + var toNextSibling; + var matchingFromEl; + + outer: while (curToNodeChild) { + toNextSibling = curToNodeChild.nextSibling; + curToNodeKey = getNodeKey(curToNodeChild); + + while (curFromNodeChild) { + fromNextSibling = curFromNodeChild.nextSibling; + + if (curToNodeChild.isSameNode && curToNodeChild.isSameNode(curFromNodeChild)) { + curToNodeChild = toNextSibling; + curFromNodeChild = fromNextSibling; + continue outer; + } + + curFromNodeKey = getNodeKey(curFromNodeChild); + + var curFromNodeType = curFromNodeChild.nodeType; + + var isCompatible = undefined; + + if (curFromNodeType === curToNodeChild.nodeType) { + if (curFromNodeType === ELEMENT_NODE) { + // Both nodes being compared are Element nodes + + if (curToNodeKey) { + // The target node has a key so we want to match it up with the correct element + // in the original DOM tree + if (curToNodeKey !== curFromNodeKey) { + // The current element in the original DOM tree does not have a matching key so + // let's check our lookup to see if there is a matching element in the original + // DOM tree + if (matchingFromEl = fromNodesLookup[curToNodeKey]) { + if (curFromNodeChild.nextSibling === matchingFromEl) { + // Special case for single element removals. To avoid removing the original + // DOM node out of the tree (since that can break CSS transitions, etc.), + // we will instead discard the current node and wait until the next + // iteration to properly match up the keyed target element with its matching + // element in the original tree + isCompatible = false; + } else { + // We found a matching keyed element somewhere in the original DOM tree. + // Let's moving the original DOM node into the current position and morph + // it. + + // NOTE: We use insertBefore instead of replaceChild because we want to go through + // the `removeNode()` function for the node that is being discarded so that + // all lifecycle hooks are correctly invoked + fromEl.insertBefore(matchingFromEl, curFromNodeChild); + + fromNextSibling = curFromNodeChild.nextSibling; + + if (curFromNodeKey) { + // Since the node is keyed it might be matched up later so we defer + // the actual removal to later + addKeyedRemoval(curFromNodeKey); + } else { + // NOTE: we skip nested keyed nodes from being removed since there is + // still a chance they will be matched up later + removeNode(curFromNodeChild, fromEl, true /* skip keyed nodes */); + } + + curFromNodeChild = matchingFromEl; + } + } else { + // The nodes are not compatible since the "to" node has a key and there + // is no matching keyed node in the source tree + isCompatible = false; + } + } + } else if (curFromNodeKey) { + // The original has a key + isCompatible = false; + } + + isCompatible = isCompatible !== false && compareNodeNames(curFromNodeChild, curToNodeChild); + if (isCompatible) { + // We found compatible DOM elements so transform + // the current "from" node to match the current + // target DOM node. + morphEl(curFromNodeChild, curToNodeChild); + } + } else if (curFromNodeType === TEXT_NODE || curFromNodeType == COMMENT_NODE) { + // Both nodes being compared are Text or Comment nodes + isCompatible = true; + // Simply update nodeValue on the original node to + // change the text value + curFromNodeChild.nodeValue = curToNodeChild.nodeValue; + } + } + + if (isCompatible) { + // Advance both the "to" child and the "from" child since we found a match + curToNodeChild = toNextSibling; + curFromNodeChild = fromNextSibling; + continue outer; + } + + // No compatible match so remove the old node from the DOM and continue trying to find a + // match in the original DOM. However, we only do this if the from node is not keyed + // since it is possible that a keyed node might match up with a node somewhere else in the + // target tree and we don't want to discard it just yet since it still might find a + // home in the final DOM tree. After everything is done we will remove any keyed nodes + // that didn't find a home + if (curFromNodeKey) { + // Since the node is keyed it might be matched up later so we defer + // the actual removal to later + addKeyedRemoval(curFromNodeKey); + } else { + // NOTE: we skip nested keyed nodes from being removed since there is + // still a chance they will be matched up later + removeNode(curFromNodeChild, fromEl, true /* skip keyed nodes */); + } + + curFromNodeChild = fromNextSibling; + } + + // If we got this far then we did not find a candidate match for + // our "to node" and we exhausted all of the children "from" + // nodes. Therefore, we will just append the current "to" node + // to the end + if (curToNodeKey && (matchingFromEl = fromNodesLookup[curToNodeKey]) && compareNodeNames(matchingFromEl, curToNodeChild)) { + fromEl.appendChild(matchingFromEl); + morphEl(matchingFromEl, curToNodeChild); + } else { + var onBeforeNodeAddedResult = onBeforeNodeAdded(curToNodeChild); + if (onBeforeNodeAddedResult !== false) { + if (onBeforeNodeAddedResult) { + curToNodeChild = onBeforeNodeAddedResult; + } + + if (curToNodeChild.actualize) { + curToNodeChild = curToNodeChild.actualize(fromEl.ownerDocument || doc); + } + fromEl.appendChild(curToNodeChild); + handleNodeAdded(curToNodeChild); + } + } + + curToNodeChild = toNextSibling; + curFromNodeChild = fromNextSibling; + } + + // We have processed all of the "to nodes". If curFromNodeChild is + // non-null then we still have some from nodes left over that need + // to be removed + while (curFromNodeChild) { + fromNextSibling = curFromNodeChild.nextSibling; + if (curFromNodeKey = getNodeKey(curFromNodeChild)) { + // Since the node is keyed it might be matched up later so we defer + // the actual removal to later + addKeyedRemoval(curFromNodeKey); + } else { + // NOTE: we skip nested keyed nodes from being removed since there is + // still a chance they will be matched up later + removeNode(curFromNodeChild, fromEl, true /* skip keyed nodes */); + } + curFromNodeChild = fromNextSibling; + } + } + + var specialElHandler = specialElHandlers[fromEl.nodeName]; + if (specialElHandler) { + specialElHandler(fromEl, toEl); + } + } // END: morphEl(...) + + var morphedNode = fromNode; + var morphedNodeType = morphedNode.nodeType; + var toNodeType = toNode.nodeType; + + if (!childrenOnly) { + // Handle the case where we are given two DOM nodes that are not + // compatible (e.g.
--> or
--> TEXT) + if (morphedNodeType === ELEMENT_NODE) { + if (toNodeType === ELEMENT_NODE) { + if (!compareNodeNames(fromNode, toNode)) { + onNodeDiscarded(fromNode); + morphedNode = moveChildren(fromNode, createElementNS(toNode.nodeName, toNode.namespaceURI)); + } + } else { + // Going from an element node to a text node + morphedNode = toNode; + } + } else if (morphedNodeType === TEXT_NODE || morphedNodeType === COMMENT_NODE) { + // Text or comment node + if (toNodeType === morphedNodeType) { + morphedNode.nodeValue = toNode.nodeValue; + return morphedNode; + } else { + // Text node to something else + morphedNode = toNode; + } + } + } + + if (morphedNode === toNode) { + // The "to node" was not compatible with the "from node" so we had to + // toss out the "from node" and use the "to node" + onNodeDiscarded(fromNode); + } else { + morphEl(morphedNode, toNode, childrenOnly); + + // We now need to loop over any keyed nodes that might need to be + // removed. We only do the removal if we know that the keyed node + // never found a match. When a keyed node is matched up we remove + // it out of fromNodesLookup and we use fromNodesLookup to determine + // if a keyed node has been matched up or not + if (keyedRemovalList) { + for (var i = 0, len = keyedRemovalList.length; i < len; i++) { + var elToRemove = fromNodesLookup[keyedRemovalList[i]]; + if (elToRemove) { + removeNode(elToRemove, elToRemove.parentNode, false); + } + } + } + } + + if (!childrenOnly && morphedNode !== fromNode && fromNode.parentNode) { + if (morphedNode.actualize) { + morphedNode = morphedNode.actualize(fromNode.ownerDocument || doc); + } + // If we had to swap out the from node with a new node because the old + // node was not compatible with the target node then we need to + // replace the old DOM node in the original DOM tree. This is only + // possible if the original DOM node was part of a DOM tree which + // we know is the case if it has a parent node. + fromNode.parentNode.replaceChild(morphedNode, fromNode); + } + + return morphedNode; + }; + } + + var morphdom = morphdomFactory(morphAttrs); + morphdom.toElement = toElement; + morphdom.toElements = toElements; + return morphdom; + }); + +/***/ }, +/* 7 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + /* + * html2json for omi + * https://github.com/AlloyTeam/omi + * + * Original code by John Resig (ejohn.org) + * http://ejohn.org/blog/pure-javascript-html-parser/ + * Original code by Erik Arvidsson, Mozilla Public License + * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js + * Original code by Jxck + * https://github.com/Jxck/html2json + */ + + // Regular Expressions for parsing tags and attributes + var startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/, + endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/, + attr = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g; + + var HTMLParser = function HTMLParser(html, handler) { + var index, + chars, + match, + stack = [], + last = html; + stack.last = function () { + return this[this.length - 1]; + }; + + while (html) { + chars = true; + + // Make sure we're not in a script or style element + if (!stack.last()) { + + if (html.indexOf("]*>"), function (all, text) { + + if (handler.chars) handler.chars(text); + + return ""; + }); + + parseEndTag("", stack.last()); + } + + if (html == last) throw "Parse Error: " + html; + last = html; + } + + // Clean up any remaining tags + parseEndTag(); + + function parseStartTag(tag, tagName, rest, unary) { + //tagName = tagName.toLowerCase(); + + unary = !!unary; + + if (!unary) stack.push(tagName); + + if (handler.start) { + var attrs = []; + + rest.replace(attr, function (match, name) { + var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : ""; + + attrs.push({ + name: name, + value: value, + escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') //" + }); + }); + + if (handler.start) handler.start(tagName, attrs, unary); + } + } + + function parseEndTag(tag, tagName) { + // If no tag name is provided, clean shop + if (!tagName) var pos = 0; + + // Find the closest opened tag of the same type + else for (var pos = stack.length - 1; pos >= 0; pos--) { + if (stack[pos] == tagName) break; + }if (pos >= 0) { + // Close all the open elements, up the stack + for (var i = stack.length - 1; i >= pos; i--) { + if (handler.end) handler.end(stack[i]); + } // Remove the open elements from the stack + stack.length = pos; + } + } + }; + + var DEBUG = false; + var debug = DEBUG ? console.log.bind(console) : function () {}; + + // Production steps of ECMA-262, Edition 5, 15.4.4.21 + // Reference: http://es5.github.io/#x15.4.4.21 + if (!Array.prototype.reduce) { + Array.prototype.reduce = function (callback /*, initialValue*/) { + 'use strict'; + + if (this == null) { + throw new TypeError('Array.prototype.reduce called on null or undefined'); + } + if (typeof callback !== 'function') { + throw new TypeError(callback + ' is not a function'); + } + var t = Object(this), + len = t.length >>> 0, + k = 0, + value; + if (arguments.length == 2) { + value = arguments[1]; + } else { + while (k < len && !(k in t)) { + k++; + } + if (k >= len) { + throw new TypeError('Reduce of empty array with no initial value'); + } + value = t[k++]; + } + for (; k < len; k++) { + if (k in t) { + value = callback(value, t[k], k, t); + } + } + return value; + }; + } + + var html2json = function html2json(html) { + + var bufArray = []; + var results = { + node: 'root', + child: [] + }; + HTMLParser(html, { + start: function start(tag, attrs, unary) { + debug(tag, attrs, unary); + // node for this element + var node = { + node: 'element', + tag: tag + }; + if (attrs.length !== 0) { + node.attr = attrs.reduce(function (pre, attr) { + var name = attr.name; + var value = attr.value; + + pre[name] = value; + return pre; + }, {}); + } + if (unary) { + // if this tag dosen't have end tag + // like + // add to parents + var parent = bufArray[0] || results; + if (parent.child === undefined) { + parent.child = []; + } + parent.child.push(node); + } else { + bufArray.unshift(node); + } + }, + end: function end(tag) { + debug(tag); + // merge into parent tag + var node = bufArray.shift(); + if (node.tag !== tag) console.error('invalid state: mismatch end tag'); + + if (bufArray.length === 0) { + results.child.push(node); + } else { + var parent = bufArray[0]; + if (parent.child === undefined) { + parent.child = []; + } + parent.child.push(node); + } + }, + chars: function chars(text) { + debug(text); + var node = { + node: 'text', + text: text + }; + if (bufArray.length === 0) { + results.child.push(node); + } else { + var parent = bufArray[0]; + if (parent.child === undefined) { + parent.child = []; + } + parent.child.push(node); + } + } + }); + return results; + }; + + exports["default"] = html2json; + +/***/ }, +/* 8 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var Store = function () { + function Store(isReady) { + _classCallCheck(this, Store); + + this.readyHandlers = []; + this.isReady = isReady; + this.instances = []; + this.updateSelfInstances = []; + } + + _createClass(Store, [{ + key: "ready", + value: function ready(readyHandler) { + if (this.isReady) { + readyHandler(); + return; + } + this.readyHandlers.push(readyHandler); + } + }, { + key: "addSelfView", + value: function addSelfView(view) { + var added = false; + + for (var i = 0, len = this.updateSelfInstances.length; i < len; i++) { + if (this.updateSelfInstances[i].id === view.id) { + added = true; + break; + } + } + if (!added) { + this.updateSelfInstances.push(view); + } + } + }, { + key: "addView", + value: function addView(view) { + var added = false; + + for (var i = 0, len = this.instances.length; i < len; i++) { + if (this.instances[i].id === view.id) { + added = true; + break; + } + } + if (!added) { + this.instances.push(view); + } + } + }, { + key: "beReady", + value: function beReady() { + this.isReady = true; + this.readyHandlers.forEach(function (handler) { + return handler(); + }); + } + }, { + key: "update", + value: function update() { + this._mergeInstances(); + this._mergeSelfInstances(); + this.instances.forEach(function (instance) { + return instance.update(); + }); + this.updateSelfInstances.forEach(function (instance) { + return instance.updateSelf(); + }); + } + }, { + key: "_mergeSelfInstances", + value: function _mergeSelfInstances() { + var _this = this; + + var arr = []; + this.updateSelfInstances.forEach(function (instance) { + if (!_this._checkSelfUpdateInstance(instance)) { + arr.push(instance); + } + }); + this.updateSelfInstances = arr; + } + }, { + key: "_mergeInstances", + value: function _mergeInstances() { + var _this2 = this; + + var arr = []; + this.idArr = []; + this.instances.forEach(function (instance) { + _this2.idArr.push(instance.id); + }); + + this.instances.forEach(function (instance) { + if (!instance.parent) { + arr.push(instance); + } else { + if (!_this2._isSubInstance(instance)) { + arr.push(instance); + } + } + }); + + this.instances = arr; + } + }, { + key: "_checkSelfUpdateInstance", + value: function _checkSelfUpdateInstance(instance) { + if (this.idArr.indexOf(instance.id) !== -1) { + return true; + } else if (instance.parent) { + return this._checkSelfUpdateInstance(instance.parent); + } + } + }, { + key: "_isSubInstance", + value: function _isSubInstance(instance) { + if (this.idArr.indexOf(instance.parent.id) !== -1) { + return true; + } else if (instance.parent.parent) { + return this._isSubInstance(instance.parent); + } + } + }]); + + return Store; + }(); + + exports["default"] = Store; + +/***/ }, +/* 9 */ +/***/ function(module, exports, __webpack_require__) { + + var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module) {'use strict'; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + /** + * sodajs v0.3.0 by dorsywang + * Light weight but powerful template engine for JavaScript + * Github: https://github.com/AlloyTeam/sodajs + * MIT License + */ + + ;(function () { + var valueoutReg = /\{\{([^\}]*)\}\}/g; + + var classNameRegExp = function classNameRegExp(className) { + return new RegExp('(^|\\s+)' + className + '(\\s+|$)', 'g'); + }; + + var addClass = function addClass(el, className) { + if (!el.className) { + el.className = className; + + return; + } + + if (el.className.match(classNameRegExp(className))) {} else { + el.className += " " + className; + } + }; + + var removeClass = function removeClass(el, className) { + el.className = el.className.replace(classNameRegExp(className), ""); + }; + + var getValue = function getValue(_data, _attrStr) { + CONST_REGG.lastIndex = 0; + var realAttrStr = _attrStr.replace(CONST_REGG, function (r) { + if (typeof _data[r] === "undefined") { + return r; + } else { + return _data[r]; + } + }); + + if (_attrStr === 'true') { + return true; + } + + if (_attrStr === 'false') { + return false; + } + + var _getValue = function _getValue(data, attrStr) { + var dotIndex = attrStr.indexOf("."); + + if (dotIndex > -1) { + var attr = attrStr.substr(0, dotIndex); + attrStr = attrStr.substr(dotIndex + 1); + + // ��?查attrStr是否属�?�变量并转换 + if (typeof _data[attr] !== "undefined" && CONST_REG.test(attr)) { + attr = _data[attr]; + } + + if (typeof data[attr] !== "undefined") { + return _getValue(data[attr], attrStr); + } else { + var eventData = { + name: realAttrStr, + data: _data + }; + + triggerEvent("nullvalue", { + type: "nullattr", + data: eventData + }, eventData); + + // 如果还有 + return ""; + } + } else { + + // ��?查attrStr是否属�?�变量并转换 + if (typeof _data[attrStr] !== "undefined" && CONST_REG.test(attrStr)) { + attrStr = _data[attrStr]; + } + + var rValue; + if (typeof data[attrStr] !== "undefined") { + rValue = data[attrStr]; + } else { + var eventData = { + name: realAttrStr, + data: _data + }; + + triggerEvent("nullvalue", { + type: "nullvalue", + data: eventData + }, eventData); + + rValue = ''; + } + + return rValue; + } + }; + + return _getValue(_data, _attrStr); + }; + + // 注释node + var commentNode = function commentNode(node) {}; + + // 标识��? + var IDENTOR_REG = /[a-zA-Z_\$]+[\w\$]*/g; + var STRING_REG = /"([^"]*)"|'([^']*)'/g; + var NUMBER_REG = /\d+|\d*\.\d+/g; + + var OBJECT_REG = /[a-zA-Z_\$]+[\w\$]*(?:\s*\.\s*(?:[a-zA-Z_\$]+[\w\$]*|\d+))*/g; + var ATTR_REG = /\[([^\[\]]*)\]/g; + var ATTR_REG_DOT = /\.([a-zA-Z_\$]+[\w\$]*)/g; + + var NOT_ATTR_REG = /[^\.|]([a-zA-Z_\$]+[\w\$]*)/g; + + var OR_REG = /\|\|/g; + + var OR_REPLACE = "OR_OPERATOR\x1E"; + + var getRandom = function getRandom() { + return "$$" + ~~(Math.random() * 1E6); + }; + + var CONST_PRIFIX = "_$C$_"; + var CONST_REG = /^_\$C\$_/; + var CONST_REGG = /_\$C\$_[^\.]+/g; + + var getAttrVarKey = function getAttrVarKey() { + return CONST_PRIFIX + ~~(Math.random() * 1E6); + }; + + var parseSodaExpression = function parseSodaExpression(str, scope) { + // 对filter进行处理 + str = str.replace(OR_REG, OR_REPLACE).split("|"); + + for (var i = 0; i < str.length; i++) { + str[i] = (str[i].replace(new RegExp(OR_REPLACE, 'g'), "||") || '').trim(); + } + + var expr = str[0] || ""; + var filters = str.slice(1); + + // 将字符常量保存下��? + expr = expr.replace(STRING_REG, function (r, $1, $2) { + var key = getRandom(); + scope[key] = $1 || $2; + return key; + }); + + while (ATTR_REG.test(expr)) { + ATTR_REG.lastIndex = 0; + + //对expr预处��? + expr = expr.replace(ATTR_REG, function (r, $1) { + var key = getAttrVarKey(); + // 属�?�名��? 为字符常��? + var attrName = parseSodaExpression($1, scope); + + // 给一个特殊的前缀 表示是属性变��? + + scope[key] = attrName; + + return "." + key; + }); + } + + expr = expr.replace(OBJECT_REG, function (value) { + return "getValue(scope,'" + value.trim() + "')"; + }); + + var parseFilter = function parseFilter() { + var filterExpr = filters.shift(); + + if (!filterExpr) { + return; + } + + var filterExpr = filterExpr.split(":"); + var args = filterExpr.slice(1) || []; + var name = filterExpr[0] || ""; + + var stringReg = /^'.*'$|^".*"$/; + for (var i = 0; i < args.length; i++) { + //这里根据类型进行判断 + if (OBJECT_REG.test(args[i])) { + args[i] = "getValue(scope,'" + args[i] + "')"; + } else {} + } + + if (sodaFilterMap[name]) { + args.unshift(expr); + + args = args.join(","); + + expr = "sodaFilterMap['" + name + "'](" + args + ")"; + } + + parseFilter(); + }; + + parseFilter(); + + var evalFunc = new Function("getValue", "sodaFilterMap", "return function sodaExp(scope){ return " + expr + "}")(getValue, sodaFilterMap); + + return evalFunc(scope); + }; + + var hashTable = { + id2Expression: {}, + + expression2id: {}, + + getRandId: function getRandId() { + return 'soda' + ~~(Math.random() * 1E5); + } + }; + + // 解析指令 + // 解析attr + var compileNode = function compileNode(node, scope) { + // 如果只是文本 + if (node.nodeType === 3) { + node.nodeValue = node.nodeValue.replace(valueoutReg, function (item, $1) { + /* + var id = hashTable.getRandId(); + hashTable.id2Expression[id] = { + expression: $1, + el: child + }; + hashTable.expression2id[$1] = { + id: id, + el: child + }; + */ + + return parseSodaExpression($1, scope); + }); + } + + if (node.attributes) { + // 指令处理 + sodaDirectiveArr.map(function (item) { + var name = item.name; + + var opt = item.opt; + + if (node.getAttribute(name) && node.parentNode) { + opt.link(scope, node, node.attributes); + } + }); + + // 处理输出 包含 soda-* + [].map.call(node.attributes, function (attr) { + // 如果dirctiveMap有的就跳过不再处��? + if (!sodaDirectiveMap[attr.name]) { + if (/^soda-/.test(attr.name)) { + var attrName = attr.name.replace(/^soda-/, ''); + + if (attrName) { + var attrValue = attr.value.replace(valueoutReg, function (item, $1) { + return parseSodaExpression($1, scope); + }); + + node.setAttribute(attrName, attrValue); + } + + // 对其他属性里含expr 处理 + } else { + attr.value = attr.value.replace(valueoutReg, function (item, $1) { + return parseSodaExpression($1, scope); + }); + } + } + }); + } + + [].map.call([].slice.call(node.childNodes, []), function (child) { + compileNode(child, scope); + }); + }; + + var sodaDirectiveMap = {}; + + var sodaFilterMap = {}; + + var sodaDirectiveArr = []; + + var sodaDirective = function sodaDirective(name, func) { + var name = 'soda-' + name; + sodaDirectiveMap[name] = func(); + + sodaDirectiveArr.push({ + name: name, + opt: sodaDirectiveMap[name] + }); + }; + + var sodaFilter = function sodaFilter(name, func) { + sodaFilterMap[name] = func; + }; + + sodaFilter.get = function (name) { + return sodaFilterMap[name]; + }; + + sodaFilter("date", function (input, lenth) { + return lenth; + }); + + sodaDirective('repeat', function () { + return { + priority: 10, + compile: function compile(scope, el, attrs) {}, + link: function link(scope, el, attrs) { + var opt = el.getAttribute('soda-repeat'); + var itemName; + var valueName; + + var trackReg = /\s+by\s+([^\s]+)$/; + + var trackName; + opt = opt.replace(trackReg, function (item, $1) { + if ($1) { + trackName = ($1 || '').trim(); + } + + return ''; + }); + + var inReg = /([^\s]+)\s+in\s+([^\s]+)|\(([^,]+)\s*,\s*([^)]+)\)\s+in\s+([^\s]+)/; + + var r = inReg.exec(opt); + if (r) { + if (r[1] && r[2]) { + itemName = (r[1] || '').trim(); + valueName = (r[2] || '').trim(); + + if (!(itemName && valueName)) { + return; + } + } else if (r[3] && r[4] && r[5]) { + trackName = (r[3] || '').trim(); + itemName = (r[4] || '').trim(); + valueName = (r[5] || '').trim(); + } + } else { + return; + } + + trackName = trackName || '$index'; + + // 这里要处理一��? + var repeatObj = getValue(scope, valueName) || []; + + var repeatFunc = function repeatFunc(i) { + var itemNode = el.cloneNode(true); + + // 这里创建��?个新的scope + var itemScope = {}; + itemScope[trackName] = i; + + itemScope[itemName] = repeatObj[i]; + + itemScope.__proto__ = scope; + + itemNode.removeAttribute('soda-repeat'); + + el.parentNode.insertBefore(itemNode, el); + + // 这里是新加的dom, 要单独编��? + compileNode(itemNode, itemScope); + }; + + if ('length' in repeatObj) { + for (var i = 0; i < repeatObj.length; i++) { + repeatFunc(i); + } + } else { + for (var i in repeatObj) { + if (repeatObj.hasOwnProperty(i)) { + repeatFunc(i); + } + } + } + + el.parentNode.removeChild(el); + } + }; + }); + + sodaDirective('if', function () { + return { + priority: 9, + link: function link(scope, el, attrs) { + var opt = el.getAttribute('soda-if'); + + var expressFunc = parseSodaExpression(opt, scope); + + if (expressFunc) {} else { + // el.setAttribute("removed", "removed"); + el.parentNode && el.parentNode.removeChild(el); + } + } + }; + }); + + sodaDirective('class', function () { + return { + link: function link(scope, el, attrs) { + var opt = el.getAttribute("soda-class"); + + var expressFunc = parseSodaExpression(opt, scope); + + if (expressFunc) { + addClass(el, expressFunc); + } else {} + } + }; + }); + + sodaDirective('src', function () { + return { + link: function link(scope, el, attrs) { + var opt = el.getAttribute("soda-src"); + + var expressFunc = opt.replace(valueoutReg, function (item, $1) { + return parseSodaExpression($1, scope); + }); + + if (expressFunc) { + el.setAttribute("src", expressFunc); + } else {} + } + }; + }); + + sodaDirective('bind-html', function () { + return { + link: function link(scope, el, attrs) { + var opt = el.getAttribute("soda-bind-html"); + var expressFunc = parseSodaExpression(opt, scope); + + if (expressFunc) { + el.innerHTML = expressFunc; + + return { + command: "childDone" + }; + } + } + }; + }); + + sodaDirective("style", function () { + return { + link: function link(scope, el, attrs) { + var opt = el.getAttribute("soda-style"); + var expressFunc = parseSodaExpression(opt, scope); + + var getCssValue = function getCssValue(name, value) { + var numberWithoutpx = /opacity|z-index/; + if (numberWithoutpx.test(name)) { + return parseFloat(value); + } + + if (isNaN(value)) { + return value; + } else { + return value + "px"; + } + }; + + if (expressFunc) { + var stylelist = []; + + for (var i in expressFunc) { + if (expressFunc.hasOwnProperty(i)) { + var provalue = getCssValue(i, expressFunc[i]); + + stylelist.push([i, provalue].join(":")); + } + } + + var style = el.style; + for (var i = 0; i < style.length; i++) { + var name = style[i]; + if (expressFunc[name]) {} else { + stylelist.push([name, style[name]].join(":")); + } + } + + var styleStr = stylelist.join(";"); + + el.setAttribute("style", styleStr); + } + } + }; + }); + + var sodaRender = function sodaRender(str, data) { + // 对directive进行排序 + sodaDirectiveArr.sort(function (b, a) { + return Number(a.opt.priority || 0) - Number(b.opt.priority || 0); + }); + + console.log(sodaDirectiveArr); + + // 解析模板DOM + var div = document.createElement("div"); + + div.innerHTML = str; + + [].map.call([].slice.call(div.childNodes, []), function (child) { + compileNode(child, data); + }); + + return div.innerHTML; + + // var frament = document.createDocumentFragment(); + // frament.innerHTML = div.innerHTML; + + /* + frament.update = function(newData){ + //checkingDirtyData(data, d); + var diff = DeepDiff.noConflict(); + var diffResult = diff(data, newData); + console.log(diffResult); + var dirtyData = ['a']; + for(var i = 0; i < dirtyData.length; i ++){ + var item = dirtyData[i]; + var id = hashTable.expression2id[item]; + var nowValue = parseSodaExpression(item, newData); + //console.log(nowValue); + if(id.el){ + id.el.nodeValue = nowValue; + } + } + console.log(hashTable); + }; + */ + + var child; + while (child = div.childNodes[0]) { + frament.appendChild(child); + } + + return frament; + }; + + var eventPool = {}; + sodaRender.addEventListener = function (type, func) { + if (eventPool[type]) {} else { + eventPool[type] = []; + } + + eventPool[type].push(func); + }; + + sodaRender.author = "dorsy"; + + var triggerEvent = function triggerEvent(type, e, data) { + var events = eventPool[type] || []; + + for (var i = 0; i < events.length; i++) { + var eventFunc = events[i]; + eventFunc && eventFunc(e, data); + } + }; + + sodaRender.filter = sodaFilter; + + if (( false ? 'undefined' : _typeof(exports)) === 'object' && ( false ? 'undefined' : _typeof(module)) === 'object') module.exports = sodaRender;else if (true) !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { + return sodaRender; + }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));else if ((typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object') exports["soda"] = sodaRender;else window.soda = sodaRender; + + // 监听数据异常情况 + })(); + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10)(module))) + +/***/ }, +/* 10 */ +/***/ function(module, exports) { + + module.exports = function(module) { + if(!module.webpackPolyfill) { + module.deprecate = function() {}; + module.paths = []; + // module.parent = undefined by default + module.children = []; + module.webpackPolyfill = 1; + } + return module; + } + + +/***/ } +/******/ ]) +}); +; \ No newline at end of file diff --git a/dist/omi.soda.min.js b/dist/omi.soda.min.js new file mode 100644 index 000000000..5c9f312a1 --- /dev/null +++ b/dist/omi.soda.min.js @@ -0,0 +1,7 @@ +/*! + * Omi v1.4.0 By dntzhang + * Github: https://github.com/AlloyTeam/omi + * MIT Licensed. + */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Omi=t():e.Omi=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var i=n[r]={exports:{},id:r,loaded:!1};return e[r].call(i.exports,i,i.exports,t),i.loaded=!0,i.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}var i=n(1),o=r(i),a=n(9),s=r(a),l=n(2),u=r(l),c=n(7),d=r(c);o.default.template=s.default,o.default.Store=d.default,o.default.Component=u.default,window.Omi?e.exports=window.Omi:(window.Omi=o.default,e.exports=o.default)},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!==("undefined"==typeof t?"undefined":a(t))&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+("undefined"==typeof t?"undefined":a(t)));e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function o(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push({key:n,value:e[n]});return t}var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s={};s.instances={},s._instanceId=0,s.getInstanceId=function(){return s._instanceId++},s.customTags=[],s.mapping={},s.STYLEPREFIX="omi_style_",s.STYLESCOPEDPREFIX="omi_scoped_",s.style={},s.componentConstructor={},"function"!=typeof Object.assign&&(Object.assign=function(e){if(null==e)throw new TypeError("Cannot convert undefined or null to object");e=Object(e);for(var t=1;t=0?s:a+s;var l=n?n:a;if(n<0&&(l=a+n),i=l-s,i>0)if(o=new Array(i),this.charAt)for(r=0;r2&&(u=a,c=t),s.componentConstructor[e]=function(t){function a(t,i){return n(this,a),this.___omi_constructor_name=e,r(this,(a.__proto__||Object.getPrototypeOf(a)).call(this,t,i))}return i(a,t),l(a,o(u)),a}(c),s.customTags.push(e),s.componentConstructor[e]},s.createStore=function(e){var t=function(t){function a(t,i){return n(this,a),this.data=t,e.methods.install&&e.methods.install.call(this),r(this,(a.__proto__||Object.getPrototypeOf(a)).call(this,t,i))}return i(a,t),l(a,o(e.methods)),a}(s.Store);return new t(e.data,!0)},s.mixIndex=function(e,t){for(var n=e.length,r=t||"index",i=0;i",this.HTML):(this._mergeData(e),this.parent._omi_autoStoreToData&&(this._omi_autoStoreToData=!0,this._omi_ignoreStoreData||(this.data=this.$store.data)),this.beforeRender(),this._fixSlot(this._generateHTMLCSS()),t?this._extractChildrenString(this):this._extractChildren(this),this.children.forEach(function(e){n.HTML=n.HTML.replace(e._omiChildStr,t?e.node.outerHTML:e.HTML)}),this.HTML=(0,_event2.default)(this.HTML,this.id),this.HTML)}},{key:"_fixSlot",value:function(e){var t=this;if(this._omi_slotContent){this._omi_slotContent=this._scopedAttr(this._omi_slotContent,this._omi_scoped_attr,e);var n=_morphdom2.default.toElements(this._omi_slotContent),r=this.HTML.match(//g);1===n.length&&r&&1===r.length?this.HTML=this.HTML.replace(//,this._omi_slotContent):(n.sort(function(e,t){return parseInt(e.getAttribute("slot-index"))-parseInt(t.getAttribute("slot-index"))}),n.forEach(function(e){t.HTML=t.HTML.replace(//,e.outerHTML)}))}}},{key:"_queryElements",value:function(e){e._mixRefs(),e._execPlugins(),e.children.forEach(function(t){t.node=e.node.querySelector("["+_omi2.default.STYLESCOPEDPREFIX+t.id+"]"),t.node&&e._queryElements(t)})}},{key:"_mixRefs",value:function(){var e=this,t=_omi2.default.$$("*[ref]",this.node);t.forEach(function(t){t.hasAttribute(e._omi_scoped_attr)&&(e.refs[t.getAttribute("ref")]=t)});var n=this.node.getAttribute("ref");n&&(this.refs[n]=this.node)}},{key:"_execPlugins",value:function(){var e=this;Object.keys(_omi2.default.plugins).forEach(function(t){var n=_omi2.default.$$("*["+t+"]",e.node);n.forEach(function(n){n.hasAttribute(e._omi_scoped_attr)&&_omi2.default.plugins[t](n,e)}),e.node.hasAttribute(t)&&_omi2.default.plugins[t](e.node,e)})}},{key:"_childrenInstalled",value:function(e){var t=this;e.children.forEach(function(e){t._childrenInstalled(e),e.installed(),e._execInstalledHandlers()})}},{key:"_fixForm",value:function(){_omi2.default.$$("input",this.node).forEach(function(e){var t=e.type.toLowerCase();""===e.getAttribute("value")&&(e.value=""),"checked"!==t&&"radio"!==t||(e.hasAttribute("checked")?e.checked="checked":e.checked=!1)}),_omi2.default.$$("textarea",this.node).forEach(function(e){e.value=e.getAttribute("value")}),_omi2.default.$$("select",this.node).forEach(function(e){var t=e.getAttribute("value");if(t)_omi2.default.$$("option",e).forEach(function(e){t===e.getAttribute("value")&&e.setAttribute("selected","selected")});else{var n=_omi2.default.$$("option",e)[0];n&&n.setAttribute("selected","selected")}})}},{key:"_replaceTags",value:function(e,t,n){var r=this;if(0!==_omi2.default.customTags.length){var i=e.join("|"),o=new RegExp("<("+i+"+)((?:\\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\\s*=\\s*(?:(?:\"[^\"]*\")|(?:'[^']*')|[^>\\s]+))?)*)\\s*((\\/>)|>(([\\s\\S]*?)<\\/\\1>))","g"),a=0;return t.replace(o,function(e,t,i,o,s,l,u){if(n){var c=r.children[a];c&&c.___omi_constructor_name===t&&(c._omiChildStr=e)}else r._initComponentByString(t,e,u,a++,r)})}}},{key:"_createHiddenNode",value:function(){var e=document.createElement("input");return e.setAttribute("type","hidden"),e.setAttribute(this._omi_scoped_attr,""),e}},{key:"_mergeData",value:function(e){this.selfDataFirst?this.data=Object.assign({},this._getDataset(e),this.data):this.data=Object.assign({},this.data,this._getDataset(e))}},{key:"_generateHTMLCSS",value:function(){this.CSS=(this.style()||"").replace(/<\/?style>/g,"");var e=this.___omi_constructor_name?_omi2.default.STYLESCOPEDPREFIX+this.___omi_constructor_name.toLowerCase():this._omi_scoped_attr;this.CSS&&(!this._omi_scopedSelfCSS&&_omi2.default.style[e]||(this.CSS=_style2.default.scoper(this.CSS,this._omi_scopedSelfCSS?"["+this._omi_scoped_attr+"]":"["+e+"]"),_omi2.default.style[e]=this.CSS,this.CSS===this._preCSS||this._omi_server_rendering||(_style2.default.addStyle(this.CSS,this.id),this._preCSS=this.CSS)));var t=this.render();return this.HTML=this._scopedAttr(_omi2.default.template(t?t:"",this.data),this._omi_scoped_attr,e).trim(),this._omi_server_rendering&&(this.HTML='\r\n\r\n"+this.HTML,this.HTML+='\r\n\r\n"),e}},{key:"_scopedAttr",value:function(e,t,n){var r=this;return e.replace(/<[^\/]([A-Za-z]*)[^>]*>/g,function(e){var i=e.split(" ")[0].replace(">","");return r._omi_scopedSelfCSS||!r.___omi_constructor_name?e.replace(i,i+" "+t):e.replace(i,i+" "+t+" "+n)})}},{key:"_getDataset",value:function _getDataset(childStr){var _this12=this,json=(0,_html2json2.default)(childStr),attr=json.child[0].attr,baseData={};return Object.keys(attr).forEach(function(key){var value=attr[key];if(0===key.indexOf("on")){var handler=_this12.parent[value];handler&&(baseData[key]=handler.bind(_this12.parent))}else 0===key.indexOf("data-")?_this12._dataset[_this12._capitalize(key.replace("data-",""))]=value:0===key.indexOf(":data-")?_this12._dataset[_this12._capitalize(key.replace(":data-",""))]=eval("("+value+")"):":data"===key?_this12._dataset=eval("("+value+")"):"data"===key?_this12._dataset=_this12._extractPropertyFromString(value,_this12.parent):"group-data"===key&&(_this12._dataset=_this12._extractPropertyFromString(value,_this12.parent)[_this12._omi_groupDataIndex])}),Object.assign(baseData,this._dataset)}},{key:"_capitalize",value:function(e){return e=e.toLowerCase(),e=e.replace(/\b\w+\b/g,function(e){return e.substring(0,1).toUpperCase()+e.substring(1)}).replace(/-/g,""),e.substring(0,1).toLowerCase()+e.substring(1)}},{key:"_extractPropertyFromString",value:function(e,t){var n=e.replace(/['|"|\]]/g,"").replace(/\[/g,".").split("."),r=t;return n.forEach(function(e){r=r[e]}),n=null,r}},{key:"_extractChildrenString",value:function(e){this._replaceTags(_omi2.default.customTags,e.HTML,!0)}},{key:"_extractChildren",value:function(e){this._replaceTags(_omi2.default.customTags,e.HTML)}},{key:"_initComponentByString",value:function _initComponentByString(name,childStr,slotContent,i,child){var _this13=this,json=(0,_html2json2.default)(childStr),attr=json.child[0].attr,cmi=this.children[i];cmi&&cmi.___omi_constructor_name===name?(cmi._omiChildStr=childStr,cmi._omi_slotContent=slotContent,Object.keys(attr).forEach(function(e){var t=attr[e];"group-data"===e&&(child._omiGroupDataCounter.hasOwnProperty(t)?child._omiGroupDataCounter[t]++:child._omiGroupDataCounter[t]=0,cmi._omi_groupDataIndex=child._omiGroupDataCounter[t])}),cmi._childRender(childStr)):!function(){var baseData={},dataset={},groupDataIndex=null,omiID=null,instanceName=null,_omi_option={};Object.keys(attr).forEach(function(key){var value=attr[key];if(0===key.indexOf("on")){var handler=child[value];handler&&(baseData[key]=handler.bind(child))}else"omi-id"===key?omiID=value:"name"===key?instanceName=value:"group-data"===key?(child._omiGroupDataCounter.hasOwnProperty(value)?child._omiGroupDataCounter[value]++:child._omiGroupDataCounter[value]=0,groupDataIndex=child._omiGroupDataCounter[value],dataset=_this13._extractPropertyFromString(value,child)[groupDataIndex]):0===key.indexOf("data-")?dataset[_this13._capitalize(key.replace("data-",""))]=value:0===key.indexOf(":data-")?dataset[_this13._capitalize(key.replace(":data-",""))]=eval("("+value+")"):":data"===key?dataset=eval("("+value+")"):"data"===key?dataset=_this13._extractPropertyFromString(value,child):"preventSelfUpdate"===key||"psu"===key?_omi_option.preventSelfUpdate=!0:"selfDataFirst"===key||"sdf"===key?_omi_option.selfDataFirst=!0:"domDiffDisabled"===key||"ddd"===key?_omi_option.domDiffDisabled=!0:"ignoreStoreData"===key||"isd"===key?_omi_option.ignoreStoreData=!0:"scopedSelfCSS"!==key&&"ssc"!==key||(_omi_option.scopedSelfCSS=!0)});var ChildClass=_omi2.default.getClassFromString(name);if(!ChildClass)throw"Can't find Class called ["+name+"]";var sub_child=new ChildClass(Object.assign(baseData,child.childrenData[i],dataset),_omi_option);sub_child._omi_groupDataIndex=groupDataIndex,sub_child._omiChildStr=childStr,sub_child._omi_slotContent=slotContent,sub_child.parent=child,sub_child.$store=child.$store,sub_child.___omi_constructor_name=name,sub_child._dataset={},sub_child.install(),omiID&&(_omi2.default.mapping[omiID]=sub_child),instanceName&&(child[instanceName]=sub_child),cmi?child.children[i]=sub_child:child.children.push(sub_child),sub_child._childRender(childStr)}()}}]),Component}();exports.default=Component},function(e,t,n){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function i(e,t){e=e.replace(/\/\*[^*]*\*+([^\/][^*]*\*+)*\//g,"");var n=new RegExp("([^\r\n,{}:]+)(:[^\r\n,{}]+)?(,(?=[^{}]*{)|s*{)","g");return e=e.replace(n,function(e,n,r,i){if("undefined"==typeof r&&(r=""),n.match(/^\s*(@media|@keyframes|to|from|@font-face)/))return n+r+i;var o=n.replace(/(\s*)$/,"")+t+r,a=t+" "+n.trim()+r;return o+","+a+i})}function o(e,t){var n=document.getElementById(s.default.STYLEPREFIX+t),r=document.getElementsByTagName("head")[0];n&&n.parentNode===r&&r.removeChild(n);var i=document.createElement("style");r.appendChild(i),i.setAttribute("type","text/css"),i.setAttribute("id",s.default.STYLEPREFIX+t),window.ActiveXObject?i.styleSheet.cssText=e:i.textContent=e}Object.defineProperty(t,"__esModule",{value:!0});var a=n(1),s=r(a);t.default={scoper:i,addStyle:o}},function(e,t){"use strict";function n(e,t){return e.replace(/<[\s\S]*?>/g,function(e){return e.replace(/on(abort|blur|cancel|canplay|canplaythrough|change|click|close|contextmenu|cuechange|dblclick|drag|dragend|dragenter|dragleave|dragover|dragstart|drop|durationchange|emptied|ended|error|focus|input|invalid|keydown|keypress|keyup|load|loadeddata|loadedmetadata|loadstart|mousedown|mouseenter|mouseleave|mousemove|mouseout|mouseover|mouseup|mousewheel|pause|play|playing|progress|ratechange|reset|resize|scroll|seeked|seeking|select|show|stalled|submit|suspend|timeupdate|toggle|volumechange|waiting|autocomplete|autocompleteerror|beforecopy|beforecut|beforepaste|copy|cut|paste|search|selectstart|wheel|webkitfullscreenchange|webkitfullscreenerror|touchstart|touchmove|touchend|touchcancel|pointerdown|pointerup|pointercancel|pointermove|pointerover|pointerout|pointerenter|pointerleave|Abort|Blur|Cancel|CanPlay|CanPlayThrough|Change|Click|Close|ContextMenu|CueChange|DblClick|Drag|DragEnd|DragEnter|DragLeave|DragOver|DragStart|Drop|DurationChange|Emptied|Ended|Error|Focus|Input|Invalid|KeyDown|KeyPress|KeyUp|Load|LoadedData|LoadedMetadata|LoadStart|MouseDown|MouseEnter|MouseLeave|MouseMove|MouseOut|MouseOver|MouseUp|MouseWheel|Pause|Play|Playing|Progress|RateChange|Reset|Resize|Scroll|Seeked|Seeking|Select|Show|Stalled|Submit|Suspend|TimeUpdate|Toggle|VolumeChange|Waiting|AutoComplete|AutoCompleteError|BeforeCopy|BeforeCut|BeforePaste|Copy|Cut|Paste|Search|SelectStart|Wheel|WebkitFullScreenChange|WebkitFullScreenError|TouchStart|TouchMove|TouchEnd|TouchCancel|PointerDown|PointerUp|PointerCancel|PointerMove|PointerOver|PointerOut|PointerEnter|PointerLeave)=(('([\s\S]*?)')|("([\s\S]*?)"))/g,function(e,n,r){if(1===r.indexOf("Omi.instances["))return e;if(r.lastIndexOf(")")===r.length-2)return e.replace(/=(['|"])/,"=$1Omi.instances["+t+"].");var i=e.replace(/=(['|"])/,"=$1Omi.instances["+t+"].");return i.substr(0,i.length-1)+"(event)"+i.substr(i.length-1,1)})})}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n},function(e,t,n){var r,i,o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};!function(a,s){"object"===o(t)&&"undefined"!=typeof e?e.exports=s():(r=s,i="function"==typeof r?r.call(t,n,t,e):r,!(void 0!==i&&(e.exports=i)))}(void 0,function(){"use strict";function e(e){!c&&h.createRange&&(c=h.createRange(),c.selectNode(h.body));var t;return c&&c.createContextualFragment?t=c.createContextualFragment(e):(t=h.createElement("body"),t.innerHTML=e),t.childNodes[0]}function t(e){!c&&h.createRange&&(c=h.createRange(),c.selectNode(h.body));var t;c&&c.createContextualFragment?t=c.createContextualFragment(e):(t=h.createElement("body"),t.innerHTML=e);for(var n=[],r=0,i=t.childNodes.length;r90)&&n===r.toUpperCase()}function r(e,t){return t&&t!==f?h.createElementNS(t,e):h.createElement(e)}function i(e,t){for(var n=e.firstChild;n;){var r=n.nextSibling;t.appendChild(n),n=r}return t}function o(e,t){var n,r,i,o,a,s,l=t.attributes;for(n=l.length-1;n>=0;--n)r=l[n],i=r.name,o=r.namespaceURI,a=r.value,o?(i=r.localName||i,s=e.getAttributeNS(o,i),s!==a&&e.setAttributeNS(o,i,a)):(s=e.getAttribute(i),s!==a&&e.setAttribute(i,a));for(l=e.attributes,n=l.length-1;n>=0;--n)r=l[n],r.specified!==!1&&(i=r.name,o=r.namespaceURI,o?(i=r.localName||i,_(t,o,i)||e.removeAttributeNS(o,i)):_(t,null,i)||e.removeAttribute(i))}function a(e,t,n){e[n]!==t[n]&&(e[n]=t[n],e[n]?e.setAttribute(n,""):e.removeAttribute(n,""))}function s(){}function l(e){return e.id}function u(t){return function(o,a,u){function c(e){C?C.push(e):C=[e]}function d(e,t){if(e.nodeType===v)for(var n=e.firstChild;n;){var r=void 0;t&&(r=k(n))?c(r):(w(n),n.firstChild&&d(n,t)),n=n.nextSibling}}function f(e,t,n){D(e)!==!1&&(t&&t.removeChild(e),w(e),d(e,n))}function p(e){if(e.nodeType===v)for(var t=e.firstChild;t;){var n=k(t);n&&(L[n]=t),p(t),t=t.nextSibling}}function _(e){x(e);for(var t=e.firstChild;t;){var r=t.nextSibling,i=k(t);if(i){var o=L[i];o&&n(t,o)&&(t.parentNode.replaceChild(o,t),b(o,t))}_(t),t=r}}function b(e,r,i){if(M){for(var s=!1,l=!1,u=null,d=null,p=0,S=M.length;p\s]+))?)*)\s*(\/?)>/,r=/^<\/([-A-Za-z0-9_]+)[^>]*>/,i=/([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g,o=function(e,t){function o(e,n,r,o){if(o=!!o,o||c.push(n),t.start){var a=[];r.replace(i,function(e,t){var n=arguments[2]?arguments[2]:arguments[3]?arguments[3]:arguments[4]?arguments[4]:"";a.push({name:t,value:n,escaped:n.replace(/(^|[^\\])"/g,'$1\\"')})}),t.start&&t.start(n,a,o)}}function a(e,n){if(n)for(var r=c.length-1;r>=0&&c[r]!=n;r--);else var r=0;if(r>=0){for(var i=c.length-1;i>=r;i--)t.end&&t.end(c[i]);c.length=r}}var s,l,u,c=[],d=e;for(c.last=function(){return this[this.length-1]};e;){if(l=!0,c.last())e=e.replace(new RegExp("([\\s\\S]*?)]*>"),function(e,n){return t.chars&&t.chars(n),""}),a("",c.last());else if(0==e.indexOf(">>0,i=0;if(2==arguments.length)t=arguments[1];else{for(;i=r)throw new TypeError("Reduce of empty array with no initial value");t=n[i++]}for(;i-1){var a=i.substr(0,o);if(i=i.substr(o+1),"undefined"!=typeof e[a]&&m.test(a)&&(a=e[a]),"undefined"!=typeof r[a])return t(r[a],i);var s={name:n,data:e};return D("nullvalue",{type:"nullattr",data:s},s),""}"undefined"!=typeof e[i]&&m.test(i)&&(i=e[i]);var l;if("undefined"!=typeof r[i])l=r[i];else{var s={name:n,data:e};D("nullvalue",{type:"nullvalue",data:s},s),l=""}return l};return r(e,t)},u=/"([^"]*)"|'([^']*)'/g,c=/[a-zA-Z_\$]+[\w\$]*(?:\s*\.\s*(?:[a-zA-Z_\$]+[\w\$]*|\d+))*/g,d=/\[([^\[\]]*)\]/g,f=/\|\|/g,h="OR_OPERATOR",p=function(){return"$$"+~~(1e6*Math.random())},_="_$C$_",m=/^_\$C\$_/,v=/_\$C\$_[^\.]+/g,y=function(){return _+~~(1e6*Math.random())},g=function e(t,n){t=t.replace(f,h).split("|");for(var r=0;r + + + + + + + + + + \ No newline at end of file diff --git a/example/soda/bundler.js b/example/soda/bundler.js new file mode 100644 index 000000000..318952aa8 --- /dev/null +++ b/example/soda/bundler.js @@ -0,0 +1,3004 @@ +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) +/******/ return installedModules[moduleId].exports; + +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ exports: {}, +/******/ id: moduleId, +/******/ loaded: false +/******/ }; + +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); + +/******/ // Flag the module as loaded +/******/ module.loaded = true; + +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } + + +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; + +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; + +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; + +/******/ // Load entry module and return exports +/******/ return __webpack_require__(0); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _indexSoda = __webpack_require__(1); + + var _indexSoda2 = _interopRequireDefault(_indexSoda); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } + + function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } + + var List = function (_Omi$Component) { + _inherits(List, _Omi$Component); + + function List(data) { + _classCallCheck(this, List); + + return _possibleConstructorReturn(this, (List.__proto__ || Object.getPrototypeOf(List)).call(this, data)); + } + + _createClass(List, [{ + key: 'render', + value: function render() { + + return '
    \n
  • \n {{$index}}- {{item.text}}\n
  • \n
'; + } + }]); + + return List; + }(_indexSoda2['default'].Component); + + _indexSoda2['default'].render(new List({ + items: [{ text: 'Omi', show: true }, { text: 'dntzhang', show: true }, { text: 'AlloyTeam' }] + }), "body", true); + +/***/ }, +/* 1 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + var _omi = __webpack_require__(2); + + var _omi2 = _interopRequireDefault(_omi); + + var _soda = __webpack_require__(3); + + var _soda2 = _interopRequireDefault(_soda); + + var _component = __webpack_require__(5); + + var _component2 = _interopRequireDefault(_component); + + var _store = __webpack_require__(10); + + var _store2 = _interopRequireDefault(_store); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + _omi2['default'].template = _soda2['default']; + + _omi2['default'].Store = _store2['default']; + _omi2['default'].Component = _component2['default']; + if (window.Omi) { + module.exports = window.Omi; + } else { + window.Omi = _omi2['default']; + module.exports = _omi2['default']; + } + +/***/ }, +/* 2 */ +/***/ function(module, exports) { + + "use strict"; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + var Omi = {}; + Omi.instances = {}; + Omi._instanceId = 0; + Omi.getInstanceId = function () { + return Omi._instanceId++; + }; + Omi.customTags = []; + Omi.mapping = {}; + + Omi.STYLEPREFIX = "omi_style_"; + Omi.STYLESCOPEDPREFIX = "omi_scoped_"; + + Omi.style = {}; + + Omi.componentConstructor = {}; + + //fix ie bug + if (typeof Object.assign != 'function') { + Object.assign = function (target) { + 'use strict'; + + if (target == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + + target = Object(target); + for (var index = 1; index < arguments.length; index++) { + var source = arguments[index]; + if (source != null) { + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + } + return target; + }; + } + + /** + * Shim for "fixing" IE's lack of support (IE < 9) for applying slice + * on host objects like NamedNodeMap, NodeList, and HTMLCollection + * (technically, since host objects have been implementation-dependent, + * at least before ES6, IE hasn't needed to work this way). + * Also works on strings, fixes IE < 9 to allow an explicit undefined + * for the 2nd argument (as in Firefox), and prevents errors when + * called on other DOM objects. + */ + (function () { + 'use strict'; + + var _slice = Array.prototype.slice; + + try { + // Can't be used with DOM elements in IE < 9 + _slice.call(document.documentElement); + } catch (e) { + // Fails in IE < 9 + // This will work for genuine arrays, array-like objects, + // NamedNodeMap (attributes, entities, notations), + // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes), + // and will not fail on other DOM objects (as do DOM elements in IE < 9) + Array.prototype.slice = function (begin, end) { + // IE < 9 gets unhappy with an undefined end argument + end = typeof end !== 'undefined' ? end : this.length; + + // For native Array objects, we use the native slice function + if (Object.prototype.toString.call(this) === '[object Array]') { + return _slice.call(this, begin, end); + } + + // For array like object we handle it ourselves. + var i, + cloned = [], + size, + len = this.length; + + // Handle negative value for "begin" + var start = begin || 0; + start = start >= 0 ? start : len + start; + + // Handle negative value for "end" + var upTo = end ? end : len; + if (end < 0) { + upTo = len + end; + } + + // Actual expected size of the slice + size = upTo - start; + + if (size > 0) { + cloned = new Array(size); + if (this.charAt) { + for (i = 0; i < size; i++) { + cloned[i] = this.charAt(start + i); + } + } else { + for (i = 0; i < size; i++) { + cloned[i] = this[start + i]; + } + } + } + + return cloned; + }; + } + })(); + + var _createClass = function () { + function defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor); + } + }return function (Constructor, protoProps, staticProps) { + if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor; + }; + }(); + + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + + function _possibleConstructorReturn(self, call) { + if (!self) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + }return call && ((typeof call === "undefined" ? "undefined" : _typeof(call)) === "object" || typeof call === "function") ? call : self; + } + + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : _typeof(superClass))); + }subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; + } + + function toArr(obj) { + var arr = []; + for (var key in obj) { + if (obj.hasOwnProperty(key)) { + arr.push({ key: key, value: obj[key] }); + } + } + return arr; + } + + Omi.create = function (tagName, parent, setting) { + var u_setting = parent, + u_parent = Omi.Component; + if (arguments.length > 2) { + u_setting = setting; + u_parent = parent; + } + Omi.componentConstructor[tagName] = function (parent) { + _inherits(Obj, parent); + + function Obj(data, server) { + _classCallCheck(this, Obj); + this.___omi_constructor_name = tagName; + return _possibleConstructorReturn(this, (Obj.__proto__ || Object.getPrototypeOf(Obj)).call(this, data, server)); + } + + _createClass(Obj, toArr(u_setting)); + + return Obj; + }(u_parent); + + Omi.customTags.push(tagName); + + return Omi.componentConstructor[tagName]; + }; + + Omi.createStore = function (option) { + + var Store = function (parent) { + _inherits(Obj, parent); + + function Obj(data, isReady) { + _classCallCheck(this, Obj); + this.data = data; + option.methods.install && option.methods.install.call(this); + return _possibleConstructorReturn(this, (Obj.__proto__ || Object.getPrototypeOf(Obj)).call(this, data, isReady)); + } + + _createClass(Obj, toArr(option.methods)); + + return Obj; + }(Omi.Store); + + return new Store(option.data, true); + }; + + Omi.mixIndex = function (array, key) { + var len = array.length, + indexName = key || "index"; + for (var i = 0; i < len; i++) { + var item = array[i]; + if ((typeof item === "undefined" ? "undefined" : _typeof(item)) === "object") { + item[indexName] = i; + } else { + array[i] = { value: item }; + array[i][indexName] = i; + } + } + return array; + }; + + Omi.$ = function (selector, context) { + if (context) { + return context.querySelector(selector); + } else { + return document.querySelector(selector); + } + }; + + Omi.$$ = function (selector, context) { + if (context) { + return Array.prototype.slice.call(context.querySelectorAll(selector)); + } else { + return Array.prototype.slice.call(document.querySelectorAll(selector)); + } + }; + + Omi.getClassFromString = function (str) { + if (str.indexOf('.') !== -1) { + //root is window + var arr = str.split('.'); + var len = arr.length; + var current = window[arr[0]]; + for (var i = 1; i < len; i++) { + current = current[arr[i]]; + } + return current; + } else { + return Omi.componentConstructor[str]; + } + }; + + //以前是Component的静态方法,移到omi下来,不然makehtml 在ie下child访问不到父亲的静态方法 + Omi.makeHTML = function (name, ctor) { + Omi.componentConstructor[name] = ctor; + Omi.componentConstructor[name.toLowerCase()] = ctor; + Omi.customTags.push(name, name.toLowerCase()); + }; + + Omi.tag = Omi.makeHTML; + + Omi.render = function (component, renderTo, incrementOrOption) { + component.renderTo = typeof renderTo === "string" ? document.querySelector(renderTo) : renderTo; + if (typeof incrementOrOption === 'boolean') { + component._omi_increment = incrementOrOption; + } else if (incrementOrOption) { + component._omi_increment = incrementOrOption.increment; + if (incrementOrOption.store) { + if (incrementOrOption.store instanceof Omi.Store) { + component.$store = incrementOrOption.store; + } else { + component.$store = Omi.createStore(incrementOrOption.store); + } + } + component._omi_autoStoreToData = incrementOrOption.autoStoreToData; + } + component.install(); + component._render(true); + component._childrenInstalled(component); + component.installed(); + component._execInstalledHandlers(); + return component; + }; + + Omi.get = function (name) { + return Omi.mapping[name]; + }; + + Omi.plugins = {}; + + Omi.extendPlugin = function (name, handler) { + Omi.plugins[name] = handler; + }; + + Omi.getParameters = function (dom, instance, types) { + var data = {}; + var noop = function noop() {}; + var methodMapping = { + stringType: function stringType(value) { + return value; + }, + numberType: function numberType(value) { + return Number(value); + }, + booleanType: function booleanType(value) { + if (value === 'true') { + return true; + } else if (value === 'false') { + return false; + } else { + return Boolean(value); + } + }, + functionType: function functionType(value) { + if (value) { + var handler = instance[value.replace(/Omi.instances\[\d\]./, '')]; + if (handler) { + return handler.bind(instance); + } else { + console.warn('You do not define [ ' + value + ' ] method in following component'); + console.warn(instance); + } + } else { + return noop; + } + } + }; + Object.keys(types).forEach(function (type) { + types[type].forEach(function (name) { + var attr = dom.getAttribute(name); + if (attr !== null) { + data[name] = methodMapping[type](attr); + } + }); + }); + + return data; + }; + + Omi.mixIndexToArray = function (arr, indexName) { + arr.forEach(function (item, index) { + item[indexName || 'index'] = index; + }); + }; + + Omi.deletePlugin = function (name) { + delete Omi.plugins[name]; + }; + + module.exports = Omi; + +/***/ }, +/* 3 */ +/***/ function(module, exports, __webpack_require__) { + + var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(module) {'use strict'; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + /** + * sodajs v0.3.0 by dorsywang + * Light weight but powerful template engine for JavaScript + * Github: https://github.com/AlloyTeam/sodajs + * MIT License + */ + + ;(function () { + var valueoutReg = /\{\{([^\}]*)\}\}/g; + + var classNameRegExp = function classNameRegExp(className) { + return new RegExp('(^|\\s+)' + className + '(\\s+|$)', 'g'); + }; + + var addClass = function addClass(el, className) { + if (!el.className) { + el.className = className; + + return; + } + + if (el.className.match(classNameRegExp(className))) {} else { + el.className += " " + className; + } + }; + + var removeClass = function removeClass(el, className) { + el.className = el.className.replace(classNameRegExp(className), ""); + }; + + var getValue = function getValue(_data, _attrStr) { + CONST_REGG.lastIndex = 0; + var realAttrStr = _attrStr.replace(CONST_REGG, function (r) { + if (typeof _data[r] === "undefined") { + return r; + } else { + return _data[r]; + } + }); + + if (_attrStr === 'true') { + return true; + } + + if (_attrStr === 'false') { + return false; + } + + var _getValue = function _getValue(data, attrStr) { + var dotIndex = attrStr.indexOf("."); + + if (dotIndex > -1) { + var attr = attrStr.substr(0, dotIndex); + attrStr = attrStr.substr(dotIndex + 1); + + // ��?查attrStr是否属�?�变量并转换 + if (typeof _data[attr] !== "undefined" && CONST_REG.test(attr)) { + attr = _data[attr]; + } + + if (typeof data[attr] !== "undefined") { + return _getValue(data[attr], attrStr); + } else { + var eventData = { + name: realAttrStr, + data: _data + }; + + triggerEvent("nullvalue", { + type: "nullattr", + data: eventData + }, eventData); + + // 如果还有 + return ""; + } + } else { + + // ��?查attrStr是否属�?�变量并转换 + if (typeof _data[attrStr] !== "undefined" && CONST_REG.test(attrStr)) { + attrStr = _data[attrStr]; + } + + var rValue; + if (typeof data[attrStr] !== "undefined") { + rValue = data[attrStr]; + } else { + var eventData = { + name: realAttrStr, + data: _data + }; + + triggerEvent("nullvalue", { + type: "nullvalue", + data: eventData + }, eventData); + + rValue = ''; + } + + return rValue; + } + }; + + return _getValue(_data, _attrStr); + }; + + // 注释node + var commentNode = function commentNode(node) {}; + + // 标识��? + var IDENTOR_REG = /[a-zA-Z_\$]+[\w\$]*/g; + var STRING_REG = /"([^"]*)"|'([^']*)'/g; + var NUMBER_REG = /\d+|\d*\.\d+/g; + + var OBJECT_REG = /[a-zA-Z_\$]+[\w\$]*(?:\s*\.\s*(?:[a-zA-Z_\$]+[\w\$]*|\d+))*/g; + var ATTR_REG = /\[([^\[\]]*)\]/g; + var ATTR_REG_DOT = /\.([a-zA-Z_\$]+[\w\$]*)/g; + + var NOT_ATTR_REG = /[^\.|]([a-zA-Z_\$]+[\w\$]*)/g; + + var OR_REG = /\|\|/g; + + var OR_REPLACE = "OR_OPERATOR\x1E"; + + var getRandom = function getRandom() { + return "$$" + ~~(Math.random() * 1E6); + }; + + var CONST_PRIFIX = "_$C$_"; + var CONST_REG = /^_\$C\$_/; + var CONST_REGG = /_\$C\$_[^\.]+/g; + + var getAttrVarKey = function getAttrVarKey() { + return CONST_PRIFIX + ~~(Math.random() * 1E6); + }; + + var parseSodaExpression = function parseSodaExpression(str, scope) { + // 对filter进行处理 + str = str.replace(OR_REG, OR_REPLACE).split("|"); + + for (var i = 0; i < str.length; i++) { + str[i] = (str[i].replace(new RegExp(OR_REPLACE, 'g'), "||") || '').trim(); + } + + var expr = str[0] || ""; + var filters = str.slice(1); + + // 将字符常量保存下��? + expr = expr.replace(STRING_REG, function (r, $1, $2) { + var key = getRandom(); + scope[key] = $1 || $2; + return key; + }); + + while (ATTR_REG.test(expr)) { + ATTR_REG.lastIndex = 0; + + //对expr预处��? + expr = expr.replace(ATTR_REG, function (r, $1) { + var key = getAttrVarKey(); + // 属�?�名��? 为字符常��? + var attrName = parseSodaExpression($1, scope); + + // 给一个特殊的前缀 表示是属性变��? + + scope[key] = attrName; + + return "." + key; + }); + } + + expr = expr.replace(OBJECT_REG, function (value) { + return "getValue(scope,'" + value.trim() + "')"; + }); + + var parseFilter = function parseFilter() { + var filterExpr = filters.shift(); + + if (!filterExpr) { + return; + } + + var filterExpr = filterExpr.split(":"); + var args = filterExpr.slice(1) || []; + var name = filterExpr[0] || ""; + + var stringReg = /^'.*'$|^".*"$/; + for (var i = 0; i < args.length; i++) { + //这里根据类型进行判断 + if (OBJECT_REG.test(args[i])) { + args[i] = "getValue(scope,'" + args[i] + "')"; + } else {} + } + + if (sodaFilterMap[name]) { + args.unshift(expr); + + args = args.join(","); + + expr = "sodaFilterMap['" + name + "'](" + args + ")"; + } + + parseFilter(); + }; + + parseFilter(); + + var evalFunc = new Function("getValue", "sodaFilterMap", "return function sodaExp(scope){ return " + expr + "}")(getValue, sodaFilterMap); + + return evalFunc(scope); + }; + + var hashTable = { + id2Expression: {}, + + expression2id: {}, + + getRandId: function getRandId() { + return 'soda' + ~~(Math.random() * 1E5); + } + }; + + // 解析指令 + // 解析attr + var compileNode = function compileNode(node, scope) { + // 如果只是文本 + if (node.nodeType === 3) { + node.nodeValue = node.nodeValue.replace(valueoutReg, function (item, $1) { + /* + var id = hashTable.getRandId(); + hashTable.id2Expression[id] = { + expression: $1, + el: child + }; + hashTable.expression2id[$1] = { + id: id, + el: child + }; + */ + + return parseSodaExpression($1, scope); + }); + } + + if (node.attributes) { + // 指令处理 + sodaDirectiveArr.map(function (item) { + var name = item.name; + + var opt = item.opt; + + if (node.getAttribute(name) && node.parentNode) { + opt.link(scope, node, node.attributes); + } + }); + + // 处理输出 包含 soda-* + [].map.call(node.attributes, function (attr) { + // 如果dirctiveMap有的就跳过不再处��? + if (!sodaDirectiveMap[attr.name]) { + if (/^soda-/.test(attr.name)) { + var attrName = attr.name.replace(/^soda-/, ''); + + if (attrName) { + var attrValue = attr.value.replace(valueoutReg, function (item, $1) { + return parseSodaExpression($1, scope); + }); + + node.setAttribute(attrName, attrValue); + } + + // 对其他属性里含expr 处理 + } else { + attr.value = attr.value.replace(valueoutReg, function (item, $1) { + return parseSodaExpression($1, scope); + }); + } + } + }); + } + + [].map.call([].slice.call(node.childNodes, []), function (child) { + compileNode(child, scope); + }); + }; + + var sodaDirectiveMap = {}; + + var sodaFilterMap = {}; + + var sodaDirectiveArr = []; + + var sodaDirective = function sodaDirective(name, func) { + var name = 'soda-' + name; + sodaDirectiveMap[name] = func(); + + sodaDirectiveArr.push({ + name: name, + opt: sodaDirectiveMap[name] + }); + }; + + var sodaFilter = function sodaFilter(name, func) { + sodaFilterMap[name] = func; + }; + + sodaFilter.get = function (name) { + return sodaFilterMap[name]; + }; + + sodaFilter("date", function (input, lenth) { + return lenth; + }); + + sodaDirective('repeat', function () { + return { + priority: 10, + compile: function compile(scope, el, attrs) {}, + link: function link(scope, el, attrs) { + var opt = el.getAttribute('soda-repeat'); + var itemName; + var valueName; + + var trackReg = /\s+by\s+([^\s]+)$/; + + var trackName; + opt = opt.replace(trackReg, function (item, $1) { + if ($1) { + trackName = ($1 || '').trim(); + } + + return ''; + }); + + var inReg = /([^\s]+)\s+in\s+([^\s]+)|\(([^,]+)\s*,\s*([^)]+)\)\s+in\s+([^\s]+)/; + + var r = inReg.exec(opt); + if (r) { + if (r[1] && r[2]) { + itemName = (r[1] || '').trim(); + valueName = (r[2] || '').trim(); + + if (!(itemName && valueName)) { + return; + } + } else if (r[3] && r[4] && r[5]) { + trackName = (r[3] || '').trim(); + itemName = (r[4] || '').trim(); + valueName = (r[5] || '').trim(); + } + } else { + return; + } + + trackName = trackName || '$index'; + + // 这里要处理一��? + var repeatObj = getValue(scope, valueName) || []; + + var repeatFunc = function repeatFunc(i) { + var itemNode = el.cloneNode(true); + + // 这里创建��?个新的scope + var itemScope = {}; + itemScope[trackName] = i; + + itemScope[itemName] = repeatObj[i]; + + itemScope.__proto__ = scope; + + itemNode.removeAttribute('soda-repeat'); + + el.parentNode.insertBefore(itemNode, el); + + // 这里是新加的dom, 要单独编��? + compileNode(itemNode, itemScope); + }; + + if ('length' in repeatObj) { + for (var i = 0; i < repeatObj.length; i++) { + repeatFunc(i); + } + } else { + for (var i in repeatObj) { + if (repeatObj.hasOwnProperty(i)) { + repeatFunc(i); + } + } + } + + el.parentNode.removeChild(el); + } + }; + }); + + sodaDirective('if', function () { + return { + priority: 9, + link: function link(scope, el, attrs) { + var opt = el.getAttribute('soda-if'); + + var expressFunc = parseSodaExpression(opt, scope); + + if (expressFunc) {} else { + // el.setAttribute("removed", "removed"); + el.parentNode && el.parentNode.removeChild(el); + } + } + }; + }); + + sodaDirective('class', function () { + return { + link: function link(scope, el, attrs) { + var opt = el.getAttribute("soda-class"); + + var expressFunc = parseSodaExpression(opt, scope); + + if (expressFunc) { + addClass(el, expressFunc); + } else {} + } + }; + }); + + sodaDirective('src', function () { + return { + link: function link(scope, el, attrs) { + var opt = el.getAttribute("soda-src"); + + var expressFunc = opt.replace(valueoutReg, function (item, $1) { + return parseSodaExpression($1, scope); + }); + + if (expressFunc) { + el.setAttribute("src", expressFunc); + } else {} + } + }; + }); + + sodaDirective('bind-html', function () { + return { + link: function link(scope, el, attrs) { + var opt = el.getAttribute("soda-bind-html"); + var expressFunc = parseSodaExpression(opt, scope); + + if (expressFunc) { + el.innerHTML = expressFunc; + + return { + command: "childDone" + }; + } + } + }; + }); + + sodaDirective("style", function () { + return { + link: function link(scope, el, attrs) { + var opt = el.getAttribute("soda-style"); + var expressFunc = parseSodaExpression(opt, scope); + + var getCssValue = function getCssValue(name, value) { + var numberWithoutpx = /opacity|z-index/; + if (numberWithoutpx.test(name)) { + return parseFloat(value); + } + + if (isNaN(value)) { + return value; + } else { + return value + "px"; + } + }; + + if (expressFunc) { + var stylelist = []; + + for (var i in expressFunc) { + if (expressFunc.hasOwnProperty(i)) { + var provalue = getCssValue(i, expressFunc[i]); + + stylelist.push([i, provalue].join(":")); + } + } + + var style = el.style; + for (var i = 0; i < style.length; i++) { + var name = style[i]; + if (expressFunc[name]) {} else { + stylelist.push([name, style[name]].join(":")); + } + } + + var styleStr = stylelist.join(";"); + + el.setAttribute("style", styleStr); + } + } + }; + }); + + var sodaRender = function sodaRender(str, data) { + // 对directive进行排序 + sodaDirectiveArr.sort(function (b, a) { + return Number(a.opt.priority || 0) - Number(b.opt.priority || 0); + }); + + console.log(sodaDirectiveArr); + + // 解析模板DOM + var div = document.createElement("div"); + + div.innerHTML = str; + + [].map.call([].slice.call(div.childNodes, []), function (child) { + compileNode(child, data); + }); + + return div.innerHTML; + + // var frament = document.createDocumentFragment(); + // frament.innerHTML = div.innerHTML; + + /* + frament.update = function(newData){ + //checkingDirtyData(data, d); + var diff = DeepDiff.noConflict(); + var diffResult = diff(data, newData); + console.log(diffResult); + var dirtyData = ['a']; + for(var i = 0; i < dirtyData.length; i ++){ + var item = dirtyData[i]; + var id = hashTable.expression2id[item]; + var nowValue = parseSodaExpression(item, newData); + //console.log(nowValue); + if(id.el){ + id.el.nodeValue = nowValue; + } + } + console.log(hashTable); + }; + */ + + var child; + while (child = div.childNodes[0]) { + frament.appendChild(child); + } + + return frament; + }; + + var eventPool = {}; + sodaRender.addEventListener = function (type, func) { + if (eventPool[type]) {} else { + eventPool[type] = []; + } + + eventPool[type].push(func); + }; + + sodaRender.author = "dorsy"; + + var triggerEvent = function triggerEvent(type, e, data) { + var events = eventPool[type] || []; + + for (var i = 0; i < events.length; i++) { + var eventFunc = events[i]; + eventFunc && eventFunc(e, data); + } + }; + + sodaRender.filter = sodaFilter; + + if (( false ? 'undefined' : _typeof(exports)) === 'object' && ( false ? 'undefined' : _typeof(module)) === 'object') module.exports = sodaRender;else if (true) !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { + return sodaRender; + }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));else if ((typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object') exports["soda"] = sodaRender;else window.soda = sodaRender; + + // 监听数据异常情况 + })(); + /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)(module))) + +/***/ }, +/* 4 */ +/***/ function(module, exports) { + + "use strict"; + + module.exports = function (module) { + if (!module.webpackPolyfill) { + module.deprecate = function () {}; + module.paths = []; + // module.parent = undefined by default + module.children = []; + module.webpackPolyfill = 1; + } + return module; + }; + +/***/ }, +/* 5 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + var _omi = __webpack_require__(2); + + var _omi2 = _interopRequireDefault(_omi); + + var _style = __webpack_require__(6); + + var _style2 = _interopRequireDefault(_style); + + var _event = __webpack_require__(7); + + var _event2 = _interopRequireDefault(_event); + + var _morphdom = __webpack_require__(8); + + var _morphdom2 = _interopRequireDefault(_morphdom); + + var _html2json = __webpack_require__(9); + + var _html2json2 = _interopRequireDefault(_html2json); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var Component = function () { + function Component(data, option) { + _classCallCheck(this, Component); + + var componentOption = Object.assign({ + server: false, + ignoreStoreData: false, + preventSelfUpdate: false, + selfDataFirst: false, + domDiffDisabled: false, + scopedSelfCSS: false + }, option); + this._omi_scopedSelfCSS = componentOption.scopedSelfCSS; + this._omi_preventSelfUpdate = componentOption.preventSelfUpdate; + this._omi_domDiffDisabled = componentOption.domDiffDisabled; + this._omi_ignoreStoreData = componentOption.ignoreStoreData; + //re render the server-side rendering html on the client-side + var type = Object.prototype.toString.call(data); + var isReRendering = type !== '[object Object]' && type !== '[object Undefined]'; + if (isReRendering) { + this.renderTo = typeof data === "string" ? document.querySelector(data) : data; + this._hidden = this.renderTo.querySelector('.omi_scoped__hidden_data'); + this.id = this._hidden.dataset.omiId; + this.data = JSON.parse(this._hidden.value); + } else { + this.data = data || {}; + this._omi_server_rendering = componentOption.server; + this.id = this._omi_server_rendering ? 1000000 + _omi2['default'].getInstanceId() : _omi2['default'].getInstanceId(); + } + this.refs = {}; + this.children = []; + this.childrenData = []; + this.HTML = null; + + _omi2['default'].instances[this.id] = this; + this.selfDataFirst = componentOption.selfDataFirst; + + this._omi_scoped_attr = _omi2['default'].STYLESCOPEDPREFIX + this.id; + //this.BODY_ELEMENT = document.createElement('body') + this._preCSS = null; + this._omiGroupDataCounter = {}; + this._omi_installedHandlers = null; + if (this._omi_server_rendering || isReRendering) { + this.install(); + this._render(true); + this._childrenInstalled(this); + this.installed(); + this._execInstalledHandlers(); + } + } + + _createClass(Component, [{ + key: 'install', + value: function install() {} + }, { + key: 'installed', + value: function installed() {} + }, { + key: 'onInstalled', + value: function onInstalled(handler) { + if (!this._omi_installedHandlers) { + this._omi_installedHandlers = []; + } + this._omi_installedHandlers.push(handler); + } + }, { + key: '_execInstalledHandlers', + value: function _execInstalledHandlers() { + this._omi_installedHandlers && this._omi_installedHandlers.forEach(function (handler) { + handler(); + }); + } + }, { + key: 'uninstall', + value: function uninstall() {} + }, { + key: 'afterUpdate', + value: function afterUpdate() {} + }, { + key: 'beforeUpdate', + value: function beforeUpdate() {} + }, { + key: 'render', + value: function render() {} + }, { + key: 'style', + value: function style() {} + }, { + key: 'beforeRender', + value: function beforeRender() {} + }, { + key: 'useStore', + value: function useStore(store) { + var _this = this; + + this.$$store = store; + var isInclude = false; + store.instances.forEach(function (instance) { + if (instance.id === _this.id) { + isInclude = true; + } + }); + if (!isInclude) { + store.instances.push(this); + } + } + }, { + key: 'updateSelf', + value: function updateSelf() { + this.beforeUpdate(); + if (this.renderTo) { + this._render(false, true); + } else { + if (this._omi_preventSelfUpdate) return; + // update child node + if (this._omi_removed) { + var hdNode = this._createHiddenNode(); + this.node.parentNode.replaceChild(hdNode, this.node); + this.node = hdNode; + } else { + (0, _morphdom2['default'])(this.node, (0, _event2['default'])(this._childRender(this._omiChildStr, true), this.id), { + ignoreAttr: this._getIgnoreAttr() + }); + + this.node = document.querySelector("[" + this._omi_scoped_attr + "]"); + this._queryElements(this); + this._fixForm(); + } + } + this.afterUpdate(); + } + }, { + key: 'update', + value: function update() { + this.beforeUpdate(); + this._childrenBeforeUpdate(this); + if (this.renderTo) { + this._render(); + } else { + if (this._omi_preventSelfUpdate) return; + // update child node + if (this._omi_removed) { + var hdNode = this._createHiddenNode(); + this.node.parentNode.replaceChild(hdNode, this.node); + this.node = hdNode; + } else { + if (this._omi_domDiffDisabled) { + this.node.parentNode.replaceChild(_morphdom2['default'].toElement((0, _event2['default'])(this._childRender(this._omiChildStr), this.id)), this.node); + } else { + (0, _morphdom2['default'])(this.node, (0, _event2['default'])(this._childRender(this._omiChildStr), this.id)); + } + this.node = document.querySelector("[" + this._omi_scoped_attr + "]"); + this._queryElements(this); + this._fixForm(); + } + } + + this._childrenAfterUpdate(this); + this.afterUpdate(); + } + }, { + key: '_childrenBeforeUpdate', + value: function _childrenBeforeUpdate(root) { + var _this2 = this; + + root.children.forEach(function (child) { + child.beforeUpdate(); + _this2._childrenBeforeUpdate(child); + }); + } + }, { + key: '_childrenAfterUpdate', + value: function _childrenAfterUpdate(root) { + var _this3 = this; + + root.children.forEach(function (child) { + _this3._childrenAfterUpdate(child); + child.afterUpdate(); + }); + } + }, { + key: 'setData', + value: function setData(data, update) { + this.data = data; + if (update) { + this.update(); + } + } + }, { + key: 'removeChild', + value: function removeChild(indexOrChild) { + var child = indexOrChild; + if (typeof indexOrChild === 'number') { + child = this.children[indexOrChild]; + } + + child.remove(); + } + }, { + key: 'restoreChild', + value: function restoreChild(indexOrChild) { + var child = indexOrChild; + if (typeof indexOrChild === 'number') { + child = this.children[indexOrChild]; + } + + child.restore(); + } + }, { + key: 'remove', + value: function remove() { + this._omi_removed = true; + this.update(); + this.uninstall(); + } + }, { + key: 'restore', + value: function restore() { + this._omi_removed = false; + this.update(); + this.installed(); + this._execInstalledHandlers(); + } + }, { + key: '_render', + value: function _render(isFirst, isSelf) { + var _this4 = this; + + if (this._omi_removed) { + var node = this._createHiddenNode(); + if (!isFirst) { + this.node.parentNode.replaceChild(node, this.node); + this.node = node; + } else if (this.renderTo) { + this.renderTo.appendChild(node); + } + return; + } + if (this._omi_autoStoreToData) { + if (!this._omi_ignoreStoreData) { + this.data = this.$store.data; + } + } + this.beforeRender(); + this._generateHTMLCSS(); + if (!isSelf) { + this._extractChildren(this); + } else { + this._extractChildrenString(this); + } + + this.children.forEach(function (item) { + _this4.HTML = _this4.HTML.replace(item._omiChildStr, isSelf ? item.node.outerHTML : item.HTML); + }); + + this.HTML = (0, _event2['default'])(this.HTML, this.id); + if (isFirst) { + if (this.renderTo) { + if (this._omi_increment) { + this.renderTo.insertAdjacentHTML('beforeend', this.HTML); + } else { + this.renderTo.innerHTML = this.HTML; + } + } + } else { + if (this.HTML !== "") { + if (this._omi_domDiffDisabled) { + this.renderTo.innerHTML = this.HTML; + } else { + (0, _morphdom2['default'])(this.node, this.HTML, isSelf ? { + ignoreAttr: this._getIgnoreAttr() + } : null); + } + } else { + (0, _morphdom2['default'])(this.node, this._createHiddenNode()); + } + } + //get node prop from parent node + if (this.renderTo) { + this.node = document.querySelector("[" + this._omi_scoped_attr + "]"); + this._queryElements(this); + this._fixForm(); + } + } + }, { + key: '_getIgnoreAttr', + value: function _getIgnoreAttr() { + var arr = []; + this.children.forEach(function (child) { + arr.push(child._omi_scoped_attr); + }); + return arr; + } + }, { + key: '_childRender', + value: function _childRender(childStr, isSelf) { + var _this5 = this; + + if (this._omi_removed) { + this.HTML = ''; + return this.HTML; + } + //childStr = childStr.replace("", ">
") + this._mergeData(childStr); + if (this.parent._omi_autoStoreToData) { + this._omi_autoStoreToData = true; + if (!this._omi_ignoreStoreData) { + this.data = this.$store.data; + } + } + this.beforeRender(); + this._fixSlot(this._generateHTMLCSS()); + if (!isSelf) { + this._extractChildren(this); + } else { + this._extractChildrenString(this); + } + + this.children.forEach(function (item) { + _this5.HTML = _this5.HTML.replace(item._omiChildStr, isSelf ? item.node.outerHTML : item.HTML); + }); + this.HTML = (0, _event2['default'])(this.HTML, this.id); + return this.HTML; + } + }, { + key: '_fixSlot', + value: function _fixSlot(shareAttr) { + var _this6 = this; + + if (!this._omi_slotContent) return; + this._omi_slotContent = this._scopedAttr(this._omi_slotContent, this._omi_scoped_attr, shareAttr); + var nodes = _morphdom2['default'].toElements(this._omi_slotContent); + var slotMatch = this.HTML.match(//g); + if (nodes.length === 1 && slotMatch && slotMatch.length === 1) { + this.HTML = this.HTML.replace(//, this._omi_slotContent); + } else { + nodes.sort(function (a, b) { + return parseInt(a.getAttribute('slot-index')) - parseInt(b.getAttribute('slot-index')); + }); + nodes.forEach(function (node) { + _this6.HTML = _this6.HTML.replace(//, node.outerHTML); + }); + } + } + }, { + key: '_queryElements', + value: function _queryElements(current) { + current._mixRefs(); + current._execPlugins(); + current.children.forEach(function (item) { + item.node = current.node.querySelector("[" + _omi2['default'].STYLESCOPEDPREFIX + item.id + "]"); + //recursion get node prop from parent node + item.node && current._queryElements(item); + }); + } + }, { + key: '_mixRefs', + value: function _mixRefs() { + var _this7 = this; + + var nodes = _omi2['default'].$$('*[ref]', this.node); + nodes.forEach(function (node) { + if (node.hasAttribute(_this7._omi_scoped_attr)) { + _this7.refs[node.getAttribute('ref')] = node; + } + }); + var attr = this.node.getAttribute('ref'); + if (attr) { + this.refs[attr] = this.node; + } + } + }, { + key: '_execPlugins', + value: function _execPlugins() { + var _this8 = this; + + Object.keys(_omi2['default'].plugins).forEach(function (item) { + var nodes = _omi2['default'].$$('*[' + item + ']', _this8.node); + nodes.forEach(function (node) { + if (node.hasAttribute(_this8._omi_scoped_attr)) { + _omi2['default'].plugins[item](node, _this8); + } + }); + if (_this8.node.hasAttribute(item)) { + _omi2['default'].plugins[item](_this8.node, _this8); + } + }); + } + }, { + key: '_childrenInstalled', + value: function _childrenInstalled(root) { + var _this9 = this; + + root.children.forEach(function (child) { + _this9._childrenInstalled(child); + child.installed(); + child._execInstalledHandlers(); + }); + } + }, { + key: '_fixForm', + value: function _fixForm() { + + _omi2['default'].$$('input', this.node).forEach(function (element) { + var type = element.type.toLowerCase(); + if (element.getAttribute('value') === '') { + element.value = ''; + } + if (type === 'checked' || type === 'radio') { + if (element.hasAttribute('checked')) { + element.checked = 'checked'; + } else { + element.checked = false; + } + } + }); + + _omi2['default'].$$('textarea', this.node).forEach(function (textarea) { + textarea.value = textarea.getAttribute('value'); + }); + + _omi2['default'].$$('select', this.node).forEach(function (select) { + var value = select.getAttribute('value'); + if (value) { + _omi2['default'].$$('option', select).forEach(function (option) { + if (value === option.getAttribute('value')) { + option.setAttribute('selected', 'selected'); + } + }); + } else { + var firstOption = _omi2['default'].$$('option', select)[0]; + firstOption && firstOption.setAttribute('selected', 'selected'); + } + }); + } + }, { + key: '_replaceTags', + value: function _replaceTags(array, html, updateSelf) { + var _this10 = this; + + if (_omi2['default'].customTags.length === 0) return; + var str = array.join("|"); + var reg = new RegExp('<(' + str + '+)((?:\\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\\s*=\\s*(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>\\s]+))?)*)\\s*((\\/>)|>(([\\s\\S]*?)<\\/\\1>))', 'g'); + var index = 0; + return html.replace(reg, function (m, a, b, c, d, e, f) { + if (updateSelf) { + var cmi = _this10.children[index]; + if (cmi && cmi.___omi_constructor_name === a) { + cmi._omiChildStr = m; + } + } else { + _this10._initComponentByString(a, m, f, index++, _this10); + } + }); + } + }, { + key: '_createHiddenNode', + value: function _createHiddenNode() { + var hdNode = document.createElement("input"); + hdNode.setAttribute("type", "hidden"); + hdNode.setAttribute(this._omi_scoped_attr, ''); + return hdNode; + } + }, { + key: '_mergeData', + value: function _mergeData(childStr) { + if (this.selfDataFirst) { + this.data = Object.assign({}, this._getDataset(childStr), this.data); + } else { + this.data = Object.assign({}, this.data, this._getDataset(childStr)); + } + } + }, { + key: '_generateHTMLCSS', + value: function _generateHTMLCSS() { + this.CSS = (this.style() || '').replace(/<\/?style>/g, ''); + var shareAttr = this.___omi_constructor_name ? _omi2['default'].STYLESCOPEDPREFIX + this.___omi_constructor_name.toLowerCase() : this._omi_scoped_attr; + if (this.CSS) { + if (this._omi_scopedSelfCSS || !_omi2['default'].style[shareAttr]) { + this.CSS = _style2['default'].scoper(this.CSS, this._omi_scopedSelfCSS ? "[" + this._omi_scoped_attr + "]" : "[" + shareAttr + "]"); + _omi2['default'].style[shareAttr] = this.CSS; + if (this.CSS !== this._preCSS && !this._omi_server_rendering) { + _style2['default'].addStyle(this.CSS, this.id); + this._preCSS = this.CSS; + } + } + } + var tpl = this.render(); + this.HTML = this._scopedAttr(_omi2['default'].template(tpl ? tpl : "", this.data), this._omi_scoped_attr, shareAttr).trim(); + if (this._omi_server_rendering) { + this.HTML = '\r\n\r\n' + this.HTML; + this.HTML += '\r\n\r\n'; + } + + return shareAttr; + } + }, { + key: '_scopedAttr', + value: function _scopedAttr(html, id, shareAtrr) { + var _this11 = this; + + return html.replace(/<[^/]([A-Za-z]*)[^>]*>/g, function (m) { + var str = m.split(" ")[0].replace(">", ""); + if (_this11._omi_scopedSelfCSS || !_this11.___omi_constructor_name) { + return m.replace(str, str + " " + id); + } else { + return m.replace(str, str + " " + id + " " + shareAtrr); + } + }); + } + }, { + key: '_getDataset', + value: function _getDataset(childStr) { + var _this12 = this; + + var json = (0, _html2json2['default'])(childStr); + var attr = json.child[0].attr; + var baseData = {}; + Object.keys(attr).forEach(function (key) { + var value = attr[key]; + if (key.indexOf('on') === 0) { + var handler = _this12.parent[value]; + if (handler) { + baseData[key] = handler.bind(_this12.parent); + } + } else if (key.indexOf('data-') === 0) { + _this12._dataset[_this12._capitalize(key.replace('data-', ''))] = value; + } else if (key.indexOf(':data-') === 0) { + _this12._dataset[_this12._capitalize(key.replace(':data-', ''))] = eval('(' + value + ')'); + } else if (key === ':data') { + _this12._dataset = eval('(' + value + ')'); + } else if (key === 'data') { + _this12._dataset = _this12._extractPropertyFromString(value, _this12.parent); + } else if (key === 'group-data') { + _this12._dataset = _this12._extractPropertyFromString(value, _this12.parent)[_this12._omi_groupDataIndex]; + } + }); + + return Object.assign(baseData, this._dataset); + } + }, { + key: '_capitalize', + value: function _capitalize(str) { + str = str.toLowerCase(); + str = str.replace(/\b\w+\b/g, function (word) { + return word.substring(0, 1).toUpperCase() + word.substring(1); + }).replace(/-/g, ''); + return str.substring(0, 1).toLowerCase() + str.substring(1); + } + }, { + key: '_extractPropertyFromString', + value: function _extractPropertyFromString(str, instance) { + var arr = str.replace(/['|"|\]]/g, '').replace(/\[/g, '.').split('.'); + var current = instance; + arr.forEach(function (prop) { + current = current[prop]; + }); + arr = null; + return current; + } + }, { + key: '_extractChildrenString', + value: function _extractChildrenString(child) { + this._replaceTags(_omi2['default'].customTags, child.HTML, true); + } + }, { + key: '_extractChildren', + value: function _extractChildren(child) { + this._replaceTags(_omi2['default'].customTags, child.HTML); + } + }, { + key: '_initComponentByString', + value: function _initComponentByString(name, childStr, slotContent, i, child) { + var _this13 = this; + + var json = (0, _html2json2['default'])(childStr); + var attr = json.child[0].attr; + var cmi = this.children[i]; + //if not first time to invoke _extractChildren method + if (cmi && cmi.___omi_constructor_name === name) { + cmi._omiChildStr = childStr; + cmi._omi_slotContent = slotContent; + Object.keys(attr).forEach(function (key) { + var value = attr[key]; + if (key === 'group-data') { + if (child._omiGroupDataCounter.hasOwnProperty(value)) { + child._omiGroupDataCounter[value]++; + } else { + child._omiGroupDataCounter[value] = 0; + } + cmi._omi_groupDataIndex = child._omiGroupDataCounter[value]; + } + }); + + cmi._childRender(childStr); + } else { + (function () { + var baseData = {}; + var dataset = {}; + + var groupDataIndex = null; + var omiID = null; + var instanceName = null; + var _omi_option = {}; + + Object.keys(attr).forEach(function (key) { + var value = attr[key]; + if (key.indexOf('on') === 0) { + var handler = child[value]; + if (handler) { + baseData[key] = handler.bind(child); + } + } else if (key === 'omi-id') { + omiID = value; + } else if (key === 'name') { + instanceName = value; + } else if (key === 'group-data') { + if (child._omiGroupDataCounter.hasOwnProperty(value)) { + child._omiGroupDataCounter[value]++; + } else { + child._omiGroupDataCounter[value] = 0; + } + groupDataIndex = child._omiGroupDataCounter[value]; + dataset = _this13._extractPropertyFromString(value, child)[groupDataIndex]; + } else if (key.indexOf('data-') === 0) { + dataset[_this13._capitalize(key.replace('data-', ''))] = value; + } else if (key.indexOf(':data-') === 0) { + dataset[_this13._capitalize(key.replace(':data-', ''))] = eval('(' + value + ')'); + } else if (key === ':data') { + dataset = eval('(' + value + ')'); + } else if (key === 'data') { + dataset = _this13._extractPropertyFromString(value, child); + } else if (key === 'preventSelfUpdate' || key === 'psu') { + _omi_option.preventSelfUpdate = true; + } else if (key === 'selfDataFirst' || key === 'sdf') { + _omi_option.selfDataFirst = true; + } else if (key === 'domDiffDisabled' || key === 'ddd') { + _omi_option.domDiffDisabled = true; + } else if (key === 'ignoreStoreData' || key === 'isd') { + _omi_option.ignoreStoreData = true; + } else if (key === 'scopedSelfCSS' || key === 'ssc') { + _omi_option.scopedSelfCSS = true; + } + }); + + var ChildClass = _omi2['default'].getClassFromString(name); + if (!ChildClass) throw "Can't find Class called [" + name + "]"; + var sub_child = new ChildClass(Object.assign(baseData, child.childrenData[i], dataset), _omi_option); + sub_child._omi_groupDataIndex = groupDataIndex; + sub_child._omiChildStr = childStr; + sub_child._omi_slotContent = slotContent; + sub_child.parent = child; + sub_child.$store = child.$store; + sub_child.___omi_constructor_name = name; + sub_child._dataset = {}; + sub_child.install(); + + omiID && (_omi2['default'].mapping[omiID] = sub_child); + instanceName && (child[instanceName] = sub_child); + + if (!cmi) { + child.children.push(sub_child); + } else { + child.children[i] = sub_child; + } + + sub_child._childRender(childStr); + })(); + } + } + }]); + + return Component; + }(); + + exports['default'] = Component; + +/***/ }, +/* 6 */ +/***/ function(module, exports, __webpack_require__) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _omi = __webpack_require__(2); + + var _omi2 = _interopRequireDefault(_omi); + + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } + + //many thanks to https://github.com/thomaspark/scoper/ + function scoper(css, prefix) { + //https://www.w3.org/TR/css-syntax-3/#lexical + css = css.replace(/\/\*[^*]*\*+([^/][^*]*\*+)*\//g, ''); + + var re = new RegExp("([^\r\n,{}:]+)(:[^\r\n,{}]+)?(,(?=[^{}]*{)|\s*{)", "g"); + /** + * Example: + * + * .classname::pesudo { color:red } + * + * g1 is normal selector `.classname` + * g2 is pesudo class or pesudo element + * g3 is the suffix + */ + css = css.replace(re, function (g0, g1, g2, g3) { + if (typeof g2 === "undefined") { + g2 = ""; + } + + if (g1.match(/^\s*(@media|@keyframes|to|from|@font-face)/)) { + return g1 + g2 + g3; + } + + var appendClass = g1.replace(/(\s*)$/, "") + prefix + g2; + var prependClass = prefix + " " + g1.trim() + g2; + return appendClass + "," + prependClass + g3; + }); + + return css; + } + + function addStyle(cssText, id) { + var ele = document.getElementById(_omi2['default'].STYLEPREFIX + id), + head = document.getElementsByTagName('head')[0]; + if (ele && ele.parentNode === head) { + head.removeChild(ele); + } + + var someThingStyles = document.createElement('style'); + head.appendChild(someThingStyles); + someThingStyles.setAttribute('type', 'text/css'); + someThingStyles.setAttribute('id', _omi2['default'].STYLEPREFIX + id); + if (!!window.ActiveXObject) { + someThingStyles.styleSheet.cssText = cssText; + } else { + someThingStyles.textContent = cssText; + } + } + + exports['default'] = { + scoper: scoper, + addStyle: addStyle + }; + +/***/ }, +/* 7 */ +/***/ function(module, exports) { + + 'use strict'; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + function scopedEvent(tpl, id) { + return tpl.replace(/<[\s\S]*?>/g, function (item) { + return item.replace(/on(abort|blur|cancel|canplay|canplaythrough|change|click|close|contextmenu|cuechange|dblclick|drag|dragend|dragenter|dragleave|dragover|dragstart|drop|durationchange|emptied|ended|error|focus|input|invalid|keydown|keypress|keyup|load|loadeddata|loadedmetadata|loadstart|mousedown|mouseenter|mouseleave|mousemove|mouseout|mouseover|mouseup|mousewheel|pause|play|playing|progress|ratechange|reset|resize|scroll|seeked|seeking|select|show|stalled|submit|suspend|timeupdate|toggle|volumechange|waiting|autocomplete|autocompleteerror|beforecopy|beforecut|beforepaste|copy|cut|paste|search|selectstart|wheel|webkitfullscreenchange|webkitfullscreenerror|touchstart|touchmove|touchend|touchcancel|pointerdown|pointerup|pointercancel|pointermove|pointerover|pointerout|pointerenter|pointerleave|Abort|Blur|Cancel|CanPlay|CanPlayThrough|Change|Click|Close|ContextMenu|CueChange|DblClick|Drag|DragEnd|DragEnter|DragLeave|DragOver|DragStart|Drop|DurationChange|Emptied|Ended|Error|Focus|Input|Invalid|KeyDown|KeyPress|KeyUp|Load|LoadedData|LoadedMetadata|LoadStart|MouseDown|MouseEnter|MouseLeave|MouseMove|MouseOut|MouseOver|MouseUp|MouseWheel|Pause|Play|Playing|Progress|RateChange|Reset|Resize|Scroll|Seeked|Seeking|Select|Show|Stalled|Submit|Suspend|TimeUpdate|Toggle|VolumeChange|Waiting|AutoComplete|AutoCompleteError|BeforeCopy|BeforeCut|BeforePaste|Copy|Cut|Paste|Search|SelectStart|Wheel|WebkitFullScreenChange|WebkitFullScreenError|TouchStart|TouchMove|TouchEnd|TouchCancel|PointerDown|PointerUp|PointerCancel|PointerMove|PointerOver|PointerOut|PointerEnter|PointerLeave)=(('([\s\S]*?)')|("([\s\S]*?)"))/g, function (eventStr, b, c) { + if (c.indexOf('Omi.instances[') === 1) { + return eventStr; + } else if (c.lastIndexOf(')') === c.length - 2) { + return eventStr.replace(/=(['|"])/, '=$1Omi.instances[' + id + '].'); + } else { + var str = eventStr.replace(/=(['|"])/, '=$1Omi.instances[' + id + '].'); + return str.substr(0, str.length - 1) + "(event)" + str.substr(str.length - 1, 1); + } + }); + }); + } + + exports['default'] = scopedEvent; + +/***/ }, +/* 8 */ +/***/ function(module, exports, __webpack_require__) { + + var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; + + var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; + + (function (global, factory) { + ( false ? 'undefined' : _typeof(exports)) === 'object' && typeof module !== 'undefined' ? module.exports = factory() : true ? !(__WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)) : global.morphdom = factory(); + })(undefined, function () { + 'use strict'; + + var range; // Create a range object for efficently rendering strings to elements. + var NS_XHTML = 'http://www.w3.org/1999/xhtml'; + + var doc = typeof document === 'undefined' ? undefined : document; + + var testEl = doc ? doc.body || doc.createElement('div') : {}; + + // Fixes + // (IE7+ support) <=IE7 does not support el.hasAttribute(name) + var actualHasAttributeNS; + + if (testEl.hasAttributeNS) { + actualHasAttributeNS = function actualHasAttributeNS(el, namespaceURI, name) { + return el.hasAttributeNS(namespaceURI, name); + }; + } else if (testEl.hasAttribute) { + actualHasAttributeNS = function actualHasAttributeNS(el, namespaceURI, name) { + return el.hasAttribute(name); + }; + } else { + actualHasAttributeNS = function actualHasAttributeNS(el, namespaceURI, name) { + return el.getAttributeNode(namespaceURI, name) != null; + }; + } + + var hasAttributeNS = actualHasAttributeNS; + + function toElement(str) { + if (!range && doc.createRange) { + range = doc.createRange(); + range.selectNode(doc.body); + } + + var fragment; + if (range && range.createContextualFragment) { + fragment = range.createContextualFragment(str); + } else { + fragment = doc.createElement('body'); + fragment.innerHTML = str; + } + return fragment.childNodes[0]; + } + + function toElements(str) { + if (!range && doc.createRange) { + range = doc.createRange(); + range.selectNode(doc.body); + } + + var fragment; + if (range && range.createContextualFragment) { + fragment = range.createContextualFragment(str); + } else { + fragment = doc.createElement('body'); + fragment.innerHTML = str; + } + + var arr = [], + i = 0, + len = fragment.childNodes.length; + for (; i < len; i++) { + var item = fragment.childNodes[i]; + if (item.nodeType === 1) { + arr.push(item); + } + } + return arr; + } + + /** + * Returns true if two node's names are the same. + * + * NOTE: We don't bother checking `namespaceURI` because you will never find two HTML elements with the same + * nodeName and different namespace URIs. + * + * @param {Element} a + * @param {Element} b The target element + * @return {boolean} + */ + function compareNodeNames(fromEl, toEl) { + var fromNodeName = fromEl.nodeName; + var toNodeName = toEl.nodeName; + + if (fromNodeName === toNodeName) { + return true; + } + + if (toEl.actualize && fromNodeName.charCodeAt(0) < 91 && /* from tag name is upper case */ + toNodeName.charCodeAt(0) > 90 /* target tag name is lower case */) { + // If the target element is a virtual DOM node then we may need to normalize the tag name + // before comparing. Normal HTML elements that are in the "http://www.w3.org/1999/xhtml" + // are converted to upper case + return fromNodeName === toNodeName.toUpperCase(); + } else { + return false; + } + } + + /** + * Create an element, optionally with a known namespace URI. + * + * @param {string} name the element name, e.g. 'div' or 'svg' + * @param {string} [namespaceURI] the element's namespace URI, i.e. the value of + * its `xmlns` attribute or its inferred namespace. + * + * @return {Element} + */ + function createElementNS(name, namespaceURI) { + return !namespaceURI || namespaceURI === NS_XHTML ? doc.createElement(name) : doc.createElementNS(namespaceURI, name); + } + + /** + * Copies the children of one DOM element to another DOM element + */ + function moveChildren(fromEl, toEl) { + var curChild = fromEl.firstChild; + while (curChild) { + var nextChild = curChild.nextSibling; + toEl.appendChild(curChild); + curChild = nextChild; + } + return toEl; + } + + function morphAttrs(fromNode, toNode) { + var attrs = toNode.attributes; + var i; + var attr; + var attrName; + var attrNamespaceURI; + var attrValue; + var fromValue; + + for (i = attrs.length - 1; i >= 0; --i) { + attr = attrs[i]; + attrName = attr.name; + attrNamespaceURI = attr.namespaceURI; + attrValue = attr.value; + + if (attrNamespaceURI) { + attrName = attr.localName || attrName; + fromValue = fromNode.getAttributeNS(attrNamespaceURI, attrName); + + if (fromValue !== attrValue) { + fromNode.setAttributeNS(attrNamespaceURI, attrName, attrValue); + } + } else { + fromValue = fromNode.getAttribute(attrName); + + if (fromValue !== attrValue) { + fromNode.setAttribute(attrName, attrValue); + } + } + } + + // Remove any extra attributes found on the original DOM element that + // weren't found on the target element. + attrs = fromNode.attributes; + + for (i = attrs.length - 1; i >= 0; --i) { + attr = attrs[i]; + if (attr.specified !== false) { + attrName = attr.name; + attrNamespaceURI = attr.namespaceURI; + + if (attrNamespaceURI) { + attrName = attr.localName || attrName; + + if (!hasAttributeNS(toNode, attrNamespaceURI, attrName)) { + fromNode.removeAttributeNS(attrNamespaceURI, attrName); + } + } else { + if (!hasAttributeNS(toNode, null, attrName)) { + fromNode.removeAttribute(attrName); + } + } + } + } + } + + function syncBooleanAttrProp(fromEl, toEl, name) { + if (fromEl[name] !== toEl[name]) { + fromEl[name] = toEl[name]; + if (fromEl[name]) { + fromEl.setAttribute(name, ''); + } else { + fromEl.removeAttribute(name, ''); + } + } + } + + var specialElHandlers = { + /** + * Needed for IE. Apparently IE doesn't think that "selected" is an + * attribute when reading over the attributes using selectEl.attributes + */ + OPTION: function OPTION(fromEl, toEl) { + syncBooleanAttrProp(fromEl, toEl, 'selected'); + }, + /** + * The "value" attribute is special for the element since it sets + * the initial value. Changing the "value" attribute without changing the + * "value" property will have no effect since it is only used to the set the + * initial value. Similar for the "checked" attribute, and "disabled". + */ + INPUT: function INPUT(fromEl, toEl) { + syncBooleanAttrProp(fromEl, toEl, 'checked'); + syncBooleanAttrProp(fromEl, toEl, 'disabled'); + + if (fromEl.value !== toEl.value) { + fromEl.value = toEl.value; + } + + if (!hasAttributeNS(toEl, null, 'value')) { + fromEl.removeAttribute('value'); + } + }, + + TEXTAREA: function TEXTAREA(fromEl, toEl) { + var newValue = toEl.value; + if (fromEl.value !== newValue) { + fromEl.value = newValue; + } + + if (fromEl.firstChild) { + // Needed for IE. Apparently IE sets the placeholder as the + // node value and vise versa. This ignores an empty update. + if (newValue === '' && fromEl.firstChild.nodeValue === fromEl.placeholder) { + return; + } + + fromEl.firstChild.nodeValue = newValue; + } + }, + SELECT: function SELECT(fromEl, toEl) { + if (!hasAttributeNS(toEl, null, 'multiple')) { + var selectedIndex = -1; + var i = 0; + var curChild = toEl.firstChild; + while (curChild) { + var nodeName = curChild.nodeName; + if (nodeName && nodeName.toUpperCase() === 'OPTION') { + if (hasAttributeNS(curChild, null, 'selected')) { + selectedIndex = i; + break; + } + i++; + } + curChild = curChild.nextSibling; + } + + fromEl.selectedIndex = i; + } + } + }; + + var ELEMENT_NODE = 1; + var TEXT_NODE = 3; + var COMMENT_NODE = 8; + + function noop() {} + + function defaultGetNodeKey(node) { + return node.id; + } + + function morphdomFactory(morphAttrs) { + + return function morphdom(fromNode, toNode, options) { + if (!options) { + options = {}; + } + + if (typeof toNode === 'string') { + if (fromNode.nodeName === '#document' || fromNode.nodeName === 'HTML') { + var toNodeHtml = toNode; + toNode = doc.createElement('html'); + toNode.innerHTML = toNodeHtml; + } else { + toNode = toElement(toNode); + } + } + + var getNodeKey = options.getNodeKey || defaultGetNodeKey; + var onBeforeNodeAdded = options.onBeforeNodeAdded || noop; + var onNodeAdded = options.onNodeAdded || noop; + var onBeforeElUpdated = options.onBeforeElUpdated || noop; + var onElUpdated = options.onElUpdated || noop; + var onBeforeNodeDiscarded = options.onBeforeNodeDiscarded || noop; + var onNodeDiscarded = options.onNodeDiscarded || noop; + var onBeforeElChildrenUpdated = options.onBeforeElChildrenUpdated || noop; + var childrenOnly = options.childrenOnly === true; + var ignoreAttr = options.ignoreAttr; + // This object is used as a lookup to quickly find all keyed elements in the original DOM tree. + var fromNodesLookup = {}; + var keyedRemovalList; + + function addKeyedRemoval(key) { + if (keyedRemovalList) { + keyedRemovalList.push(key); + } else { + keyedRemovalList = [key]; + } + } + + function walkDiscardedChildNodes(node, skipKeyedNodes) { + if (node.nodeType === ELEMENT_NODE) { + var curChild = node.firstChild; + while (curChild) { + + var key = undefined; + + if (skipKeyedNodes && (key = getNodeKey(curChild))) { + // If we are skipping keyed nodes then we add the key + // to a list so that it can be handled at the very end. + addKeyedRemoval(key); + } else { + // Only report the node as discarded if it is not keyed. We do this because + // at the end we loop through all keyed elements that were unmatched + // and then discard them in one final pass. + onNodeDiscarded(curChild); + if (curChild.firstChild) { + walkDiscardedChildNodes(curChild, skipKeyedNodes); + } + } + + curChild = curChild.nextSibling; + } + } + } + + /** + * Removes a DOM node out of the original DOM + * + * @param {Node} node The node to remove + * @param {Node} parentNode The nodes parent + * @param {Boolean} skipKeyedNodes If true then elements with keys will be skipped and not discarded. + * @return {undefined} + */ + function removeNode(node, parentNode, skipKeyedNodes) { + if (onBeforeNodeDiscarded(node) === false) { + return; + } + + if (parentNode) { + parentNode.removeChild(node); + } + + onNodeDiscarded(node); + walkDiscardedChildNodes(node, skipKeyedNodes); + } + + // // TreeWalker implementation is no faster, but keeping this around in case this changes in the future + // function indexTree(root) { + // var treeWalker = document.createTreeWalker( + // root, + // NodeFilter.SHOW_ELEMENT); + // + // var el; + // while((el = treeWalker.nextNode())) { + // var key = getNodeKey(el); + // if (key) { + // fromNodesLookup[key] = el; + // } + // } + // } + + // // NodeIterator implementation is no faster, but keeping this around in case this changes in the future + // + // function indexTree(node) { + // var nodeIterator = document.createNodeIterator(node, NodeFilter.SHOW_ELEMENT); + // var el; + // while((el = nodeIterator.nextNode())) { + // var key = getNodeKey(el); + // if (key) { + // fromNodesLookup[key] = el; + // } + // } + // } + + function indexTree(node) { + if (node.nodeType === ELEMENT_NODE) { + var curChild = node.firstChild; + while (curChild) { + var key = getNodeKey(curChild); + if (key) { + fromNodesLookup[key] = curChild; + } + + // Walk recursively + indexTree(curChild); + + curChild = curChild.nextSibling; + } + } + } + + indexTree(fromNode); + + function handleNodeAdded(el) { + onNodeAdded(el); + + var curChild = el.firstChild; + while (curChild) { + var nextSibling = curChild.nextSibling; + + var key = getNodeKey(curChild); + if (key) { + var unmatchedFromEl = fromNodesLookup[key]; + if (unmatchedFromEl && compareNodeNames(curChild, unmatchedFromEl)) { + curChild.parentNode.replaceChild(unmatchedFromEl, curChild); + morphEl(unmatchedFromEl, curChild); + } + } + + handleNodeAdded(curChild); + curChild = nextSibling; + } + } + + function morphEl(fromEl, toEl, childrenOnly) { + if (ignoreAttr) { + var ignoreF = false, + ignoreT = false, + attrF = null, + attrT = null; + for (var _i = 0, _len = ignoreAttr.length; _i < _len; _i++) { + var selector = ignoreAttr[_i]; + if (!ignoreF && fromEl.getAttribute(selector) !== null) { + ignoreF = true; + attrF = selector; + } + if (!ignoreT && toEl.getAttribute(selector) !== null) { + ignoreT = true; + attrT = selector; + } + if (ignoreF && ignoreT) break; + } + if (ignoreF && ignoreT && attrF === attrT) { + return; + } + } + var toElKey = getNodeKey(toEl); + var curFromNodeKey; + + if (toElKey) { + // If an element with an ID is being morphed then it is will be in the final + // DOM so clear it out of the saved elements collection + delete fromNodesLookup[toElKey]; + } + + if (toNode.isSameNode && toNode.isSameNode(fromNode)) { + return; + } + + if (!childrenOnly) { + if (onBeforeElUpdated(fromEl, toEl) === false) { + return; + } + + morphAttrs(fromEl, toEl); + onElUpdated(fromEl); + + if (onBeforeElChildrenUpdated(fromEl, toEl) === false) { + return; + } + } + + if (fromEl.nodeName !== 'TEXTAREA') { + var curToNodeChild = toEl.firstChild; + var curFromNodeChild = fromEl.firstChild; + var curToNodeKey; + + var fromNextSibling; + var toNextSibling; + var matchingFromEl; + + outer: while (curToNodeChild) { + toNextSibling = curToNodeChild.nextSibling; + curToNodeKey = getNodeKey(curToNodeChild); + + while (curFromNodeChild) { + fromNextSibling = curFromNodeChild.nextSibling; + + if (curToNodeChild.isSameNode && curToNodeChild.isSameNode(curFromNodeChild)) { + curToNodeChild = toNextSibling; + curFromNodeChild = fromNextSibling; + continue outer; + } + + curFromNodeKey = getNodeKey(curFromNodeChild); + + var curFromNodeType = curFromNodeChild.nodeType; + + var isCompatible = undefined; + + if (curFromNodeType === curToNodeChild.nodeType) { + if (curFromNodeType === ELEMENT_NODE) { + // Both nodes being compared are Element nodes + + if (curToNodeKey) { + // The target node has a key so we want to match it up with the correct element + // in the original DOM tree + if (curToNodeKey !== curFromNodeKey) { + // The current element in the original DOM tree does not have a matching key so + // let's check our lookup to see if there is a matching element in the original + // DOM tree + if (matchingFromEl = fromNodesLookup[curToNodeKey]) { + if (curFromNodeChild.nextSibling === matchingFromEl) { + // Special case for single element removals. To avoid removing the original + // DOM node out of the tree (since that can break CSS transitions, etc.), + // we will instead discard the current node and wait until the next + // iteration to properly match up the keyed target element with its matching + // element in the original tree + isCompatible = false; + } else { + // We found a matching keyed element somewhere in the original DOM tree. + // Let's moving the original DOM node into the current position and morph + // it. + + // NOTE: We use insertBefore instead of replaceChild because we want to go through + // the `removeNode()` function for the node that is being discarded so that + // all lifecycle hooks are correctly invoked + fromEl.insertBefore(matchingFromEl, curFromNodeChild); + + fromNextSibling = curFromNodeChild.nextSibling; + + if (curFromNodeKey) { + // Since the node is keyed it might be matched up later so we defer + // the actual removal to later + addKeyedRemoval(curFromNodeKey); + } else { + // NOTE: we skip nested keyed nodes from being removed since there is + // still a chance they will be matched up later + removeNode(curFromNodeChild, fromEl, true /* skip keyed nodes */); + } + + curFromNodeChild = matchingFromEl; + } + } else { + // The nodes are not compatible since the "to" node has a key and there + // is no matching keyed node in the source tree + isCompatible = false; + } + } + } else if (curFromNodeKey) { + // The original has a key + isCompatible = false; + } + + isCompatible = isCompatible !== false && compareNodeNames(curFromNodeChild, curToNodeChild); + if (isCompatible) { + // We found compatible DOM elements so transform + // the current "from" node to match the current + // target DOM node. + morphEl(curFromNodeChild, curToNodeChild); + } + } else if (curFromNodeType === TEXT_NODE || curFromNodeType == COMMENT_NODE) { + // Both nodes being compared are Text or Comment nodes + isCompatible = true; + // Simply update nodeValue on the original node to + // change the text value + curFromNodeChild.nodeValue = curToNodeChild.nodeValue; + } + } + + if (isCompatible) { + // Advance both the "to" child and the "from" child since we found a match + curToNodeChild = toNextSibling; + curFromNodeChild = fromNextSibling; + continue outer; + } + + // No compatible match so remove the old node from the DOM and continue trying to find a + // match in the original DOM. However, we only do this if the from node is not keyed + // since it is possible that a keyed node might match up with a node somewhere else in the + // target tree and we don't want to discard it just yet since it still might find a + // home in the final DOM tree. After everything is done we will remove any keyed nodes + // that didn't find a home + if (curFromNodeKey) { + // Since the node is keyed it might be matched up later so we defer + // the actual removal to later + addKeyedRemoval(curFromNodeKey); + } else { + // NOTE: we skip nested keyed nodes from being removed since there is + // still a chance they will be matched up later + removeNode(curFromNodeChild, fromEl, true /* skip keyed nodes */); + } + + curFromNodeChild = fromNextSibling; + } + + // If we got this far then we did not find a candidate match for + // our "to node" and we exhausted all of the children "from" + // nodes. Therefore, we will just append the current "to" node + // to the end + if (curToNodeKey && (matchingFromEl = fromNodesLookup[curToNodeKey]) && compareNodeNames(matchingFromEl, curToNodeChild)) { + fromEl.appendChild(matchingFromEl); + morphEl(matchingFromEl, curToNodeChild); + } else { + var onBeforeNodeAddedResult = onBeforeNodeAdded(curToNodeChild); + if (onBeforeNodeAddedResult !== false) { + if (onBeforeNodeAddedResult) { + curToNodeChild = onBeforeNodeAddedResult; + } + + if (curToNodeChild.actualize) { + curToNodeChild = curToNodeChild.actualize(fromEl.ownerDocument || doc); + } + fromEl.appendChild(curToNodeChild); + handleNodeAdded(curToNodeChild); + } + } + + curToNodeChild = toNextSibling; + curFromNodeChild = fromNextSibling; + } + + // We have processed all of the "to nodes". If curFromNodeChild is + // non-null then we still have some from nodes left over that need + // to be removed + while (curFromNodeChild) { + fromNextSibling = curFromNodeChild.nextSibling; + if (curFromNodeKey = getNodeKey(curFromNodeChild)) { + // Since the node is keyed it might be matched up later so we defer + // the actual removal to later + addKeyedRemoval(curFromNodeKey); + } else { + // NOTE: we skip nested keyed nodes from being removed since there is + // still a chance they will be matched up later + removeNode(curFromNodeChild, fromEl, true /* skip keyed nodes */); + } + curFromNodeChild = fromNextSibling; + } + } + + var specialElHandler = specialElHandlers[fromEl.nodeName]; + if (specialElHandler) { + specialElHandler(fromEl, toEl); + } + } // END: morphEl(...) + + var morphedNode = fromNode; + var morphedNodeType = morphedNode.nodeType; + var toNodeType = toNode.nodeType; + + if (!childrenOnly) { + // Handle the case where we are given two DOM nodes that are not + // compatible (e.g.
--> or
--> TEXT) + if (morphedNodeType === ELEMENT_NODE) { + if (toNodeType === ELEMENT_NODE) { + if (!compareNodeNames(fromNode, toNode)) { + onNodeDiscarded(fromNode); + morphedNode = moveChildren(fromNode, createElementNS(toNode.nodeName, toNode.namespaceURI)); + } + } else { + // Going from an element node to a text node + morphedNode = toNode; + } + } else if (morphedNodeType === TEXT_NODE || morphedNodeType === COMMENT_NODE) { + // Text or comment node + if (toNodeType === morphedNodeType) { + morphedNode.nodeValue = toNode.nodeValue; + return morphedNode; + } else { + // Text node to something else + morphedNode = toNode; + } + } + } + + if (morphedNode === toNode) { + // The "to node" was not compatible with the "from node" so we had to + // toss out the "from node" and use the "to node" + onNodeDiscarded(fromNode); + } else { + morphEl(morphedNode, toNode, childrenOnly); + + // We now need to loop over any keyed nodes that might need to be + // removed. We only do the removal if we know that the keyed node + // never found a match. When a keyed node is matched up we remove + // it out of fromNodesLookup and we use fromNodesLookup to determine + // if a keyed node has been matched up or not + if (keyedRemovalList) { + for (var i = 0, len = keyedRemovalList.length; i < len; i++) { + var elToRemove = fromNodesLookup[keyedRemovalList[i]]; + if (elToRemove) { + removeNode(elToRemove, elToRemove.parentNode, false); + } + } + } + } + + if (!childrenOnly && morphedNode !== fromNode && fromNode.parentNode) { + if (morphedNode.actualize) { + morphedNode = morphedNode.actualize(fromNode.ownerDocument || doc); + } + // If we had to swap out the from node with a new node because the old + // node was not compatible with the target node then we need to + // replace the old DOM node in the original DOM tree. This is only + // possible if the original DOM node was part of a DOM tree which + // we know is the case if it has a parent node. + fromNode.parentNode.replaceChild(morphedNode, fromNode); + } + + return morphedNode; + }; + } + + var morphdom = morphdomFactory(morphAttrs); + morphdom.toElement = toElement; + morphdom.toElements = toElements; + return morphdom; + }); + +/***/ }, +/* 9 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + /* + * html2json for omi + * https://github.com/AlloyTeam/omi + * + * Original code by John Resig (ejohn.org) + * http://ejohn.org/blog/pure-javascript-html-parser/ + * Original code by Erik Arvidsson, Mozilla Public License + * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js + * Original code by Jxck + * https://github.com/Jxck/html2json + */ + + // Regular Expressions for parsing tags and attributes + var startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/, + endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/, + attr = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g; + + var HTMLParser = function HTMLParser(html, handler) { + var index, + chars, + match, + stack = [], + last = html; + stack.last = function () { + return this[this.length - 1]; + }; + + while (html) { + chars = true; + + // Make sure we're not in a script or style element + if (!stack.last()) { + + if (html.indexOf("]*>"), function (all, text) { + + if (handler.chars) handler.chars(text); + + return ""; + }); + + parseEndTag("", stack.last()); + } + + if (html == last) throw "Parse Error: " + html; + last = html; + } + + // Clean up any remaining tags + parseEndTag(); + + function parseStartTag(tag, tagName, rest, unary) { + //tagName = tagName.toLowerCase(); + + unary = !!unary; + + if (!unary) stack.push(tagName); + + if (handler.start) { + var attrs = []; + + rest.replace(attr, function (match, name) { + var value = arguments[2] ? arguments[2] : arguments[3] ? arguments[3] : arguments[4] ? arguments[4] : ""; + + attrs.push({ + name: name, + value: value, + escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') //" + }); + }); + + if (handler.start) handler.start(tagName, attrs, unary); + } + } + + function parseEndTag(tag, tagName) { + // If no tag name is provided, clean shop + if (!tagName) var pos = 0; + + // Find the closest opened tag of the same type + else for (var pos = stack.length - 1; pos >= 0; pos--) { + if (stack[pos] == tagName) break; + }if (pos >= 0) { + // Close all the open elements, up the stack + for (var i = stack.length - 1; i >= pos; i--) { + if (handler.end) handler.end(stack[i]); + } // Remove the open elements from the stack + stack.length = pos; + } + } + }; + + var DEBUG = false; + var debug = DEBUG ? console.log.bind(console) : function () {}; + + // Production steps of ECMA-262, Edition 5, 15.4.4.21 + // Reference: http://es5.github.io/#x15.4.4.21 + if (!Array.prototype.reduce) { + Array.prototype.reduce = function (callback /*, initialValue*/) { + 'use strict'; + + if (this == null) { + throw new TypeError('Array.prototype.reduce called on null or undefined'); + } + if (typeof callback !== 'function') { + throw new TypeError(callback + ' is not a function'); + } + var t = Object(this), + len = t.length >>> 0, + k = 0, + value; + if (arguments.length == 2) { + value = arguments[1]; + } else { + while (k < len && !(k in t)) { + k++; + } + if (k >= len) { + throw new TypeError('Reduce of empty array with no initial value'); + } + value = t[k++]; + } + for (; k < len; k++) { + if (k in t) { + value = callback(value, t[k], k, t); + } + } + return value; + }; + } + + var html2json = function html2json(html) { + + var bufArray = []; + var results = { + node: 'root', + child: [] + }; + HTMLParser(html, { + start: function start(tag, attrs, unary) { + debug(tag, attrs, unary); + // node for this element + var node = { + node: 'element', + tag: tag + }; + if (attrs.length !== 0) { + node.attr = attrs.reduce(function (pre, attr) { + var name = attr.name; + var value = attr.value; + + pre[name] = value; + return pre; + }, {}); + } + if (unary) { + // if this tag dosen't have end tag + // like + // add to parents + var parent = bufArray[0] || results; + if (parent.child === undefined) { + parent.child = []; + } + parent.child.push(node); + } else { + bufArray.unshift(node); + } + }, + end: function end(tag) { + debug(tag); + // merge into parent tag + var node = bufArray.shift(); + if (node.tag !== tag) console.error('invalid state: mismatch end tag'); + + if (bufArray.length === 0) { + results.child.push(node); + } else { + var parent = bufArray[0]; + if (parent.child === undefined) { + parent.child = []; + } + parent.child.push(node); + } + }, + chars: function chars(text) { + debug(text); + var node = { + node: 'text', + text: text + }; + if (bufArray.length === 0) { + results.child.push(node); + } else { + var parent = bufArray[0]; + if (parent.child === undefined) { + parent.child = []; + } + parent.child.push(node); + } + } + }); + return results; + }; + + exports["default"] = html2json; + +/***/ }, +/* 10 */ +/***/ function(module, exports) { + + "use strict"; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); + + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + + var Store = function () { + function Store(isReady) { + _classCallCheck(this, Store); + + this.readyHandlers = []; + this.isReady = isReady; + this.instances = []; + this.updateSelfInstances = []; + } + + _createClass(Store, [{ + key: "ready", + value: function ready(readyHandler) { + if (this.isReady) { + readyHandler(); + return; + } + this.readyHandlers.push(readyHandler); + } + }, { + key: "addSelfView", + value: function addSelfView(view) { + var added = false; + + for (var i = 0, len = this.updateSelfInstances.length; i < len; i++) { + if (this.updateSelfInstances[i].id === view.id) { + added = true; + break; + } + } + if (!added) { + this.updateSelfInstances.push(view); + } + } + }, { + key: "addView", + value: function addView(view) { + var added = false; + + for (var i = 0, len = this.instances.length; i < len; i++) { + if (this.instances[i].id === view.id) { + added = true; + break; + } + } + if (!added) { + this.instances.push(view); + } + } + }, { + key: "beReady", + value: function beReady() { + this.isReady = true; + this.readyHandlers.forEach(function (handler) { + return handler(); + }); + } + }, { + key: "update", + value: function update() { + this._mergeInstances(); + this._mergeSelfInstances(); + this.instances.forEach(function (instance) { + return instance.update(); + }); + this.updateSelfInstances.forEach(function (instance) { + return instance.updateSelf(); + }); + } + }, { + key: "_mergeSelfInstances", + value: function _mergeSelfInstances() { + var _this = this; + + var arr = []; + this.updateSelfInstances.forEach(function (instance) { + if (!_this._checkSelfUpdateInstance(instance)) { + arr.push(instance); + } + }); + this.updateSelfInstances = arr; + } + }, { + key: "_mergeInstances", + value: function _mergeInstances() { + var _this2 = this; + + var arr = []; + this.idArr = []; + this.instances.forEach(function (instance) { + _this2.idArr.push(instance.id); + }); + + this.instances.forEach(function (instance) { + if (!instance.parent) { + arr.push(instance); + } else { + if (!_this2._isSubInstance(instance)) { + arr.push(instance); + } + } + }); + + this.instances = arr; + } + }, { + key: "_checkSelfUpdateInstance", + value: function _checkSelfUpdateInstance(instance) { + if (this.idArr.indexOf(instance.id) !== -1) { + return true; + } else if (instance.parent) { + return this._checkSelfUpdateInstance(instance.parent); + } + } + }, { + key: "_isSubInstance", + value: function _isSubInstance(instance) { + if (this.idArr.indexOf(instance.parent.id) !== -1) { + return true; + } else if (instance.parent.parent) { + return this._isSubInstance(instance.parent); + } + } + }]); + + return Store; + }(); + + exports["default"] = Store; + +/***/ } +/******/ ]); \ No newline at end of file diff --git a/example/soda/index.html b/example/soda/index.html new file mode 100644 index 000000000..842a71b5c --- /dev/null +++ b/example/soda/index.html @@ -0,0 +1,14 @@ + + + + + + + +
+ + + + + + \ No newline at end of file diff --git a/example/soda/main.js b/example/soda/main.js new file mode 100644 index 000000000..44ceb4a8e --- /dev/null +++ b/example/soda/main.js @@ -0,0 +1,25 @@ +import Omi from '../../src/index.soda.js'; + +class List extends Omi.Component { + constructor(data) { + super(data); + } + + render(){ + + return `
    +
  • + {{$index}}- {{item.text}} +
  • +
` + } + +} + +Omi.render(new List({ + items: [ + { text: 'Omi', show: true}, + { text: 'dntzhang', show: true}, + { text: 'AlloyTeam'} + ] +}),"body",true); \ No newline at end of file diff --git a/package.json b/package.json index 942e0f46c..86ee5f9ed 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "omi", - "version": "1.3.2", + "version": "1.4.0", "description": "Open and modern framework for building user interfaces.", "main": "dist/omi.js", "types": "index.d.ts", @@ -15,6 +15,7 @@ "textarea": "webpack -w", "svg": "webpack -w", "simple": "webpack -w", + "soda": "webpack -w", "group-data": "webpack -w", "jsx-like-event":"webpack -w", "loop": "webpack -w", diff --git a/src/index.soda.js b/src/index.soda.js new file mode 100644 index 000000000..0f27bc635 --- /dev/null +++ b/src/index.soda.js @@ -0,0 +1,15 @@ +import Omi from './omi.js' +import soda from './soda.js' +import Component from './component.js' +import Store from './store.js' + +Omi.template = soda + +Omi.Store = Store +Omi.Component = Component +if(window.Omi){ + module.exports = window.Omi +}else { + window.Omi = Omi + module.exports = Omi +} \ No newline at end of file diff --git a/src/soda.js b/src/soda.js new file mode 100644 index 000000000..d94e42bd2 --- /dev/null +++ b/src/soda.js @@ -0,0 +1,623 @@ +/** + * sodajs v0.4.0 by dorsywang + * Light weight but powerful template engine for JavaScript + * Github: https://github.com/AlloyTeam/sodajs + * MIT License + */ + +;(function(){ + var valueoutReg = /\{\{([^\}]*)\}\}/g; + + var classNameRegExp = function(className) { + return new RegExp('(^|\\s+)' + className + '(\\s+|$)', 'g'); + }; + + var addClass = function(el, className){ + if(! el.className){ + el.className = className; + + return; + } + + if(el.className.match(classNameRegExp(className))){ + }else{ + el.className += " " + className; + } + }; + + var removeClass = function(el, className){ + el.className = el.className.replace(classNameRegExp(className), ""); + }; + + var getValue = function(_data, _attrStr){ + CONST_REGG.lastIndex = 0; + var realAttrStr = _attrStr.replace(CONST_REGG, function(r){ + if(typeof _data[r] === "undefined"){ + return r; + }else{ + return _data[r]; + } + }); + + if(_attrStr === 'true'){ + return true; + } + + if(_attrStr === 'false'){ + return false; + } + + var _getValue = function(data, attrStr){ + var dotIndex = attrStr.indexOf("."); + + if(dotIndex > -1){ + var attr = attrStr.substr(0, dotIndex); + attrStr = attrStr.substr(dotIndex + 1); + + // ?查attrStr是否属?变量并转换 + if(typeof _data[attr] !== "undefined" && CONST_REG.test(attr)){ + attr = _data[attr]; + } + + if(typeof data[attr] !== "undefined"){ + return _getValue(data[attr], attrStr); + }else{ + var eventData = { + name: realAttrStr, + data: _data + }; + + triggerEvent("nullvalue", { + type: "nullattr", + data: eventData + }, eventData); + + // 如果还有 + return ""; + } + }else{ + + // ?查attrStr是否属?变量并转换 + if(typeof _data[attrStr] !== "undefined" && CONST_REG.test(attrStr)){ + attrStr = _data[attrStr]; + } + + var rValue; + if(typeof data[attrStr] !== "undefined"){ + rValue = data[attrStr]; + }else{ + var eventData = { + name: realAttrStr, + data: _data + }; + + triggerEvent("nullvalue", { + type: "nullvalue", + data: eventData + }, eventData); + + rValue = ''; + } + + return rValue; + } + }; + + return _getValue(_data, _attrStr); + }; + + // 注释node + var commentNode = function(node){ + }; + + // 标识? + var IDENTOR_REG = /[a-zA-Z_\$]+[\w\$]*/g; + var STRING_REG = /"([^"]*)"|'([^']*)'/g + var NUMBER_REG = /\d+|\d*\.\d+/g; + + var OBJECT_REG = /[a-zA-Z_\$]+[\w\$]*(?:\s*\.\s*(?:[a-zA-Z_\$]+[\w\$]*|\d+))*/g; + var ATTR_REG = /\[([^\[\]]*)\]/g; + var ATTR_REG_DOT = /\.([a-zA-Z_\$]+[\w\$]*)/g; + + var NOT_ATTR_REG = /[^\.|]([a-zA-Z_\$]+[\w\$]*)/g; + + var OR_REG = /\|\|/g; + + var OR_REPLACE = "OR_OPERATOR\x1E"; + + var getRandom = function(){ + return "$$" + ~~ (Math.random() * 1E6); + }; + + var CONST_PRIFIX = "_$C$_"; + var CONST_REG = /^_\$C\$_/; + var CONST_REGG = /_\$C\$_[^\.]+/g; + + var getAttrVarKey = function(){ + return CONST_PRIFIX + ~~ (Math.random() * 1E6); + }; + + var parseSodaExpression = function(str, scope){ + // 对filter进行处理 + str = str.replace(OR_REG, OR_REPLACE).split("|"); + + for(var i = 0; i < str.length; i ++){ + str[i] = (str[i].replace(new RegExp(OR_REPLACE, 'g'), "||") || '').trim(); + } + + var expr = str[0] || ""; + var filters = str.slice(1); + + // 将字符常量保存下? + expr = expr.replace(STRING_REG, function(r, $1, $2){ + var key = getRandom(); + scope[key] = $1 || $2; + return key; + }); + + while(ATTR_REG.test(expr)){ + ATTR_REG.lastIndex = 0; + + //对expr预处? + expr = expr.replace(ATTR_REG, function(r, $1){ + var key = getAttrVarKey(); + // 属?名? 为字符常? + var attrName = parseSodaExpression($1, scope); + + // 给一个特殊的前缀 表示是属性变? + + scope[key] = attrName; + + return "." + key; + }); + } + + expr = expr.replace(OBJECT_REG, function(value){ + return "getValue(scope,'" + value.trim() + "')"; + }); + + + var parseFilter = function(){ + var filterExpr = filters.shift(); + + if(! filterExpr){ + return; + } + + var filterExpr = filterExpr.split(":"); + var args = filterExpr.slice(1) || []; + var name = filterExpr[0] || ""; + + var stringReg = /^'.*'$|^".*"$/; + for(var i = 0; i < args.length; i ++){ + //这里根据类型进行判断 + if(OBJECT_REG.test(args[i])){ + args[i] = "getValue(scope,'" + args[i] + "')"; + }else{ + } + } + + if(sodaFilterMap[name]){ + args.unshift(expr); + + args = args.join(","); + + expr = "sodaFilterMap['" + name + "'](" + args + ")"; + } + + parseFilter(); + }; + + parseFilter(); + + var evalFunc = new Function("getValue", "sodaFilterMap", "return function sodaExp(scope){ return " + expr + "}")(getValue, sodaFilterMap); + + return evalFunc(scope); + }; + + var hashTable = { + id2Expression: { + }, + + expression2id: { + }, + + getRandId: function(){ + return 'soda' + ~~ (Math.random() * 1E5); + } + }; + + // 解析指令 + // 解析attr + var compileNode = function(node, scope){ + // 如果只是文本 + if(node.nodeType === 3){ + node.nodeValue = node.nodeValue.replace(valueoutReg, function(item, $1){ + /* + var id = hashTable.getRandId(); + + hashTable.id2Expression[id] = { + expression: $1, + el: child + }; + + hashTable.expression2id[$1] = { + id: id, + el: child + }; + */ + + + return parseSodaExpression($1, scope); + }); + } + + if(node.attributes){ + // 指令处理 + sodaDirectiveArr.map(function(item){ + var name = item.name; + + var opt = item.opt; + + if(node.getAttribute(name) && node.parentNode){ + opt.link(scope, node, node.attributes); + } + }); + + // 处理输出 包含 soda-* + [].map.call(node.attributes, function(attr){ + // 如果dirctiveMap有的就跳过不再处? + if(! sodaDirectiveMap[attr.name]){ + if(/^soda-/.test(attr.name)){ + var attrName = attr.name.replace(/^soda-/, ''); + + if(attrName){ + var attrValue = attr.value.replace(valueoutReg, function(item, $1){ + return parseSodaExpression($1, scope); + }); + + node.setAttribute(attrName, attrValue); + } + + // 对其他属性里含expr 处理 + }else{ + attr.value = attr.value.replace(valueoutReg, function(item, $1){ + return parseSodaExpression($1, scope); + }); + } + } + }); + + } + + [].map.call([].slice.call(node.childNodes, []), function(child){ + compileNode(child, scope); + }); + }; + + var sodaDirectiveMap = { + }; + + var sodaFilterMap = { + }; + + var sodaDirectiveArr = []; + + var sodaDirective = function(name, func){ + var name = 'soda-' + name; + sodaDirectiveMap[name] = func(); + + sodaDirectiveArr.push({ + name: name, + opt: sodaDirectiveMap[name] + }); + }; + + var sodaFilter = function(name, func){ + sodaFilterMap[name] = func; + }; + + sodaFilter.get = function(name){ + return sodaFilterMap[name]; + }; + + sodaFilter("date", function(input, lenth){ + return lenth; + }); + + sodaDirective('repeat', function(){ + return { + priority: 10, + compile: function(scope, el, attrs){ + + }, + link: function(scope, el, attrs){ + var opt = el.getAttribute('soda-repeat'); + var itemName; + var valueName; + + var trackReg = /\s+by\s+([^\s]+)$/; + + var trackName; + opt = opt.replace(trackReg, function(item, $1){ + if($1){ + trackName = ($1 || '').trim(); + } + + return ''; + }); + + + var inReg = /([^\s]+)\s+in\s+([^\s]+)|\(([^,]+)\s*,\s*([^)]+)\)\s+in\s+([^\s]+)/; + + var r = inReg.exec(opt); + if(r){ + if(r[1] && r[2]){ + itemName = (r[1] || '').trim(); + valueName = (r[2] || '').trim(); + + if(! (itemName && valueName)){ + return; + } + }else if(r[3] && r[4] && r[5]){ + trackName = (r[3] || '').trim(); + itemName = (r[4] || '').trim(); + valueName = (r[5] || '').trim(); + } + }else{ + return; + } + + trackName = trackName || '$index'; + + // 这里要处理一? + var repeatObj = getValue(scope, valueName) || []; + + var repeatFunc = function(i){ + var itemNode = el.cloneNode(true); + + // 这里创建?个新的scope + var itemScope = {}; + itemScope[trackName] = i; + + itemScope[itemName] = repeatObj[i]; + + itemScope.__proto__ = scope; + + itemNode.removeAttribute('soda-repeat'); + + el.parentNode.insertBefore(itemNode, el); + + // 这里是新加的dom, 要单独编? + compileNode(itemNode, itemScope); + + }; + + if('length' in repeatObj){ + for(var i = 0; i < repeatObj.length; i ++){ + repeatFunc(i); + } + }else{ + for(var i in repeatObj){ + if(repeatObj.hasOwnProperty(i)){ + repeatFunc(i); + } + } + } + + el.parentNode.removeChild(el); + + } + }; + }); + + sodaDirective('if', function(){ + return { + priority: 9, + link: function(scope, el, attrs){ + var opt = el.getAttribute('soda-if'); + + var expressFunc = parseSodaExpression(opt, scope); + + if(expressFunc){ + }else{ + // el.setAttribute("removed", "removed"); + el.parentNode && el.parentNode.removeChild(el); + } + } + }; + }); + + sodaDirective('class', function(){ + return { + link: function(scope, el, attrs){ + var opt = el.getAttribute("soda-class"); + + var expressFunc = parseSodaExpression(opt, scope); + + if(expressFunc){ + addClass(el, expressFunc); + }else{ + } + } + }; + }); + + sodaDirective('src', function(){ + return { + link: function(scope, el, attrs){ + var opt = el.getAttribute("soda-src"); + + var expressFunc = opt.replace(valueoutReg, function(item, $1){ + return parseSodaExpression($1, scope); + }); + + if(expressFunc){ + el.setAttribute("src", expressFunc); + }else{ + } + } + }; + }); + + sodaDirective('bind-html', function(){ + return { + link: function(scope, el, attrs){ + var opt = el.getAttribute("soda-bind-html"); + var expressFunc = parseSodaExpression(opt, scope); + + if(expressFunc){ + el.innerHTML = expressFunc; + + return { + command: "childDone" + }; + } + } + }; + }); + + sodaDirective("style", function(){ + return { + link: function(scope, el, attrs){ + var opt = el.getAttribute("soda-style"); + var expressFunc = parseSodaExpression(opt, scope); + + var getCssValue = function(name, value){ + var numberWithoutpx = /opacity|z-index/; + if(numberWithoutpx.test(name)){ + return parseFloat(value); + } + + if(isNaN(value)){ + return value; + }else{ + return value + "px"; + } + }; + + if(expressFunc){ + var stylelist = []; + + for(var i in expressFunc){ + if(expressFunc.hasOwnProperty(i)){ + var provalue = getCssValue(i, expressFunc[i]); + + stylelist.push([i, provalue].join(":")); + } + } + + var style = el.style; + for(var i = 0; i < style.length; i ++){ + var name = style[i]; + if(expressFunc[name]){ + }else{ + stylelist.push([name, style[name]].join(":")); + } + } + + var styleStr = stylelist.join(";"); + + el.setAttribute("style", styleStr); + } + } + }; + }); + + var sodaRender = function(str, data){ + // 对directive进行排序 + sodaDirectiveArr.sort(function(b, a){ + return (Number(a.opt.priority || 0) - Number(b.opt.priority || 0)); + }); + + //console.log(sodaDirectiveArr); + + // 解析模板DOM + var div = document.createElement("div"); + + div.innerHTML = str; + + [].map.call([].slice.call(div.childNodes, []), function(child){ + compileNode(child, data); + }); + + return div.innerHTML; + + // var frament = document.createDocumentFragment(); + // frament.innerHTML = div.innerHTML; + + /* + frament.update = function(newData){ + //checkingDirtyData(data, d); + var diff = DeepDiff.noConflict(); + + var diffResult = diff(data, newData); + + console.log(diffResult); + + var dirtyData = ['a']; + + for(var i = 0; i < dirtyData.length; i ++){ + var item = dirtyData[i]; + + var id = hashTable.expression2id[item]; + + var nowValue = parseSodaExpression(item, newData); + //console.log(nowValue); + + if(id.el){ + id.el.nodeValue = nowValue; + } + } + + console.log(hashTable); + + + }; + */ + + var child; + while(child = div.childNodes[0]){ + frament.appendChild(child); + } + + + return frament; + }; + + var eventPool = {}; + sodaRender.addEventListener = function(type, func){ + if(eventPool[type]){ + }else{ + eventPool[type] = []; + } + + eventPool[type].push(func); + }; + + sodaRender.author = "dorsy"; + + var triggerEvent = function(type, e, data){ + var events = eventPool[type] || []; + + for(var i = 0; i < events.length; i ++){ + var eventFunc = events[i]; + eventFunc && eventFunc(e, data); + } + }; + + sodaRender.filter = sodaFilter; + + if(typeof exports === 'object' && typeof module === 'object') + module.exports = sodaRender; + else if(typeof define === 'function' && define.amd) + define([], function(){ + return sodaRender; + }); + else if(typeof exports === 'object') + exports["soda"] = sodaRender; + else + window.soda = sodaRender; + + // 监听数据异常情况 +})(); diff --git a/webpack.config.js b/webpack.config.js index 051c80123..485ab8927 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -45,7 +45,8 @@ if(ENV === 'build'||ENV === 'build-min'){ config = { entry: { omi: './src/index.js', - 'omi.lite': './src/index.lite.js' + 'omi.lite': './src/index.lite.js', + 'omi.soda': './src/index.soda.js' }, output: { // path: __dirname, @@ -87,7 +88,8 @@ if(ENV === 'build'||ENV === 'build-min'){ config.plugins.push(new webpack.optimize.UglifyJsPlugin()); config.entry = { 'omi.min': './src/index.js', - 'omi.lite.min': './src/index.lite.js' + 'omi.lite.min': './src/index.lite.js', + 'omi.soda.min': './src/index.soda.js' }; } }else if(ENV==='todomvc'){